photostructure 2026.10.3 → 2026.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -2
- package/VERSION.json +5 -5
- package/bin/auth.js +855 -0
- package/bin/bootstrap.js +3 -3
- package/bin/docker-env.js +3 -3
- package/bin/doctor.js +243 -250
- package/bin/fix.js +245 -249
- package/bin/info.js +233 -238
- package/bin/list.js +234 -242
- package/bin/logcat.js +74 -142
- package/bin/logtail.js +73 -141
- package/bin/main.js +119 -110
- package/bin/photostructure.js +5 -5
- package/bin/sync.js +290 -290
- package/bin/web.js +547 -332
- package/bin/worker.js +59 -64
- package/data/auth-schema.json +263 -0
- package/data/auth-schema.sql +75 -0
- package/data/migrations/auth/20261126_sign_in.sql +133 -0
- package/data/migrations/models/20261126_drop_pre_sign_in_session.sql +15 -0
- package/data/models-schema.json +0 -23
- package/data/models-schema.sql +0 -6
- package/defaults.env +393 -119
- package/package.json +15 -12
- package/public/3rd-party-licenses.html.gz +0 -0
- package/public/3rd-party-licenses.txt.gz +0 -0
- package/public/app/AccountMenu.js +8 -0
- package/public/app/AccountMenu.js.gz +0 -0
- package/public/app/AnimatedNumber.js +1 -1
- package/public/app/AnimatedNumber.js.gz +0 -0
- package/public/app/Array.js.gz +0 -0
- package/public/app/AssetGallery.js +1 -1
- package/public/app/AssetGallery.js.gz +0 -0
- package/public/app/DropDown.js +1 -9
- package/public/app/DropDown.js.gz +0 -0
- package/public/app/HealthChecks.js.gz +0 -0
- package/public/app/Lazy.js +1 -1
- package/public/app/Lazy.js.gz +0 -0
- package/public/app/Modal.js +1 -1
- package/public/app/Modal.js.gz +0 -0
- package/public/app/NavMenuButton.js +3 -3
- package/public/app/NavMenuButton.js.gz +0 -0
- package/public/app/PageActionsMenu.js +1 -1
- package/public/app/PageActionsMenu.js.gz +0 -0
- package/public/app/PlusTrialOffer.js +1 -1
- package/public/app/ProgressState.js +1 -1
- package/public/app/ProgressState.js.gz +0 -0
- package/public/app/SSEChannels.js +1 -1
- package/public/app/SSEChannels.js.gz +0 -0
- package/public/app/SSEClient.js +16 -0
- package/public/app/SSEClient.js.gz +0 -0
- package/public/app/Search.js +1 -1
- package/public/app/Search.js.gz +0 -0
- package/public/app/Spinner.js +4 -5
- package/public/app/Spinner.js.gz +0 -0
- package/public/app/StickyHeader.js +1 -1
- package/public/app/StickyHeader.js.gz +0 -0
- package/public/app/SvgIcon.js +9 -0
- package/public/app/SvgIcon.js.gz +0 -0
- package/public/app/SyncApi.js +8 -0
- package/public/app/SyncApi.js.gz +0 -0
- package/public/app/Tag.js +1 -1
- package/public/app/Tag.js.gz +0 -0
- package/public/app/_plugin-vue_export-helper.js +1 -1
- package/public/app/_plugin-vue_export-helper.js.gz +0 -0
- package/public/app/about.css +1 -1
- package/public/app/about.css.gz +0 -0
- package/public/app/about.js +1 -1
- package/public/app/about.js.gz +0 -0
- package/public/app/account-menu.css +8 -0
- package/public/app/account-menu.css.gz +0 -0
- package/public/app/account-menu.js +8 -0
- package/public/app/app.css +1 -1
- package/public/app/app.css.gz +0 -0
- package/public/app/app.js +5 -5
- package/public/app/app.js.gz +0 -0
- package/public/app/assets/sse-worker-DM-4CYA4.js.gz +0 -0
- package/public/app/health.css +1 -1
- package/public/app/health.css.gz +0 -0
- package/public/app/health.js +2 -2
- package/public/app/health.js.gz +0 -0
- package/public/app/logs.css +1 -1
- package/public/app/logs.css.gz +0 -0
- package/public/app/logs.js +1 -1
- package/public/app/logs.js.gz +0 -0
- package/public/app/platform.js +1 -1
- package/public/app/platform.js.gz +0 -0
- package/public/app/roboto-mono-v22-latin-700.woff2.gz +0 -0
- package/public/app/roboto-mono-v22-latin-regular.woff2.gz +0 -0
- package/public/app/roboto-v51-latin-wght.woff2.gz +0 -0
- package/public/app/settings.css +1 -1
- package/public/app/settings.css.gz +0 -0
- package/public/app/settings.js +1 -1
- package/public/app/settings.js.gz +0 -0
- package/public/app/splash.css +1 -1
- package/public/app/splash.css.gz +0 -0
- package/public/app/splash.js.gz +0 -0
- package/public/app/sync.css +1 -1
- package/public/app/sync.css.gz +0 -0
- package/public/app/sync.js +5 -5
- package/public/app/sync.js.gz +0 -0
- package/public/app/useAnchorHighlight.js +1 -1
- package/public/images/framed-picture.svg.gz +0 -0
- package/public/images/key.svg.gz +0 -0
- package/public/images/label.svg.gz +0 -0
- package/public/images/mailbox-with-raised-flag.svg.gz +0 -0
- package/public/images/unlocked.svg.gz +0 -0
- package/views/_account-menu.ejs +23 -0
- package/views/_library-dir-choice.ejs +150 -0
- package/views/_library-name-field.ejs +17 -0
- package/views/_setting-override-source.ejs +6 -0
- package/views/_setting-override.ejs +13 -7
- package/views/docker-setup.ejs +17 -20
- package/views/error.ejs +3 -0
- package/views/license-activation.ejs +40 -12
- package/views/login.ejs +169 -0
- package/views/settings.ejs +139 -195
- package/views/spa.ejs +4 -0
- package/views/users.ejs +215 -0
- package/views/welcome-tools.ejs +21 -11
- package/views/welcome.ejs +71 -40
- package/public/images/photostructure-black.svg.gz +0 -0
- package/public/images/starry-night.svg.gz +0 -0
- package/public/images/tools.svg.gz +0 -0
package/bin/auth.js
ADDED
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Copyright © 2026, PhotoStructure Inc. All rights reserved.
|
|
3
|
+
// BY USING THIS SOFTWARE, YOU ACCEPT ALL OF THE TERMS IN
|
|
4
|
+
// https://photostructure.com/eula
|
|
5
|
+
// IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE
|
|
6
|
+
"use strict";
|
|
7
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="87b33af5-bf87-595b-9a2a-589b2b45fd73")}catch(e){}}();
|
|
8
|
+
var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__knownSymbol=(e,n)=>(n=Symbol[e])?n:Symbol.for(`Symbol.`+e),__typeError=e=>{throw TypeError(e)},__commonJS=(e,n)=>function(){try{return n||(0,e[__getOwnPropNames(e)[0]])((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}},__copyProps=(e,n,r,a)=>{if(n&&typeof n==`object`||typeof n==`function`)for(let o of __getOwnPropNames(n))!__hasOwnProp.call(e,o)&&o!==r&&__defProp(e,o,{get:()=>n[o],enumerable:!(a=__getOwnPropDesc(n,o))||a.enumerable});return e},__toESM=(e,n,r)=>(r=e==null?{}:__create(__getProtoOf(e)),__copyProps(n||!e||!e.__esModule?__defProp(r,`default`,{value:e,enumerable:!0}):r,e)),__using=(e,n,r)=>{if(n!=null){typeof n!=`object`&&typeof n!=`function`&&__typeError(`Object expected`);var a,o;r&&(a=n[__knownSymbol(`asyncDispose`)]),a===void 0&&(a=n[__knownSymbol(`dispose`)],r&&(o=a)),typeof a!=`function`&&__typeError(`Object not disposable`),o&&(a=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.push([r,a,n])}else r&&e.push([r]);return n},__callDispose=(e,n,r)=>{var a=typeof SuppressedError==`function`?SuppressedError:function(e,n,r,a){return a=Error(r),a.name=`SuppressedError`,a.error=e,a.suppressed=n,a},o=e=>n=r?new a(e,n,`An error was suppressed during disposal`):(r=!0,e),s=a=>{for(;a=e.pop();)try{var c=a[1]&&a[1].call(a[2]);if(a[0])return Promise.resolve(c).then(s,e=>(o(e),s()))}catch(e){o(e)}if(r)throw n};return s()},require_parser=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js"(e,n){var r=1114112,a=class e extends Error{constructor(n,r,a){super(`[ParserError] `+n,r,a),this.name=`ParserError`,this.code=`ParserError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},o=class{constructor(e){this.parser=e,this.buf=``,this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}},s=class{constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf=``,this.char=null,this.ii=0,this.state=new o(this.parseStart)}parse(e){if(e.length===0||e.length==null)return;this._buf=String(e),this.ii=-1,this.char=-1;let n;for(;n===!1||this.nextChar();)n=this.runOne();this._buf=null}nextChar(){return this.char===10&&(++this.line,this.col=-1),++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){this.char=r;let e;do e=this.state.parser,this.runOne();while(this.state.parser!==e);return this.ctx=null,this.state=null,this._buf=null,this.obj}next(e){if(typeof e!=`function`)throw new a(`Tried to set state to non-existent state: `+JSON.stringify(e));this.state.parser=e}goto(e){return this.next(e),this.runOne()}call(e,n){n&&this.next(n),this.stack.push(this.state),this.state=new o(e)}callNow(e,n){return this.call(e,n),this.runOne()}return(e){if(this.stack.length===0)throw this.error(new a(`Stack underflow`));e===void 0&&(e=this.state.buf),this.state=this.stack.pop(),this.state.returned=e}returnNow(e){return this.return(e),this.runOne()}consume(){if(this.char===r)throw this.error(new a(`Unexpected end-of-buffer`));this.state.buf+=this._buf[this.ii]}error(e){return e.line=this.line,e.col=this.col,e.pos=this.pos,e}parseStart(){throw new a(`Must declare a parseStart method`)}};s.END=r,s.Error=a,n.exports=s}}),require_create_datetime=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js"(e,n){n.exports=e=>{let n=new Date(e);if(isNaN(n))throw TypeError(`Invalid Datetime`);return n}}}),require_format_num=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js"(e,n){n.exports=(e,n)=>{for(n=String(n);n.length<e;)n=`0`+n;return n}}}),require_create_datetime_float=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js"(e,n){var r=require_format_num(),a=class extends Date{constructor(e){super(e+`Z`),this.isFloating=!0}toISOString(){return`${`${this.getUTCFullYear()}-${r(2,this.getUTCMonth()+1)}-${r(2,this.getUTCDate())}`}T${`${r(2,this.getUTCHours())}:${r(2,this.getUTCMinutes())}:${r(2,this.getUTCSeconds())}.${r(3,this.getUTCMilliseconds())}`}`}};n.exports=e=>{let n=new a(e);if(isNaN(n))throw TypeError(`Invalid Datetime`);return n}}}),require_create_date=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js"(e,n){var r=require_format_num(),a=global.Date,o=class extends a{constructor(e){super(e),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${r(2,this.getUTCMonth()+1)}-${r(2,this.getUTCDate())}`}};n.exports=e=>{let n=new o(e);if(isNaN(n))throw TypeError(`Invalid Datetime`);return n}}}),require_create_time=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js"(e,n){var r=require_format_num(),a=class extends Date{constructor(e){super(`0000-01-01T${e}Z`),this.isTime=!0}toISOString(){return`${r(2,this.getUTCHours())}:${r(2,this.getUTCMinutes())}:${r(2,this.getUTCSeconds())}.${r(3,this.getUTCMilliseconds())}`}};n.exports=e=>{let n=new a(e);if(isNaN(n))throw TypeError(`Invalid Datetime`);return n}}}),require_toml_parser=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js"(exports,module){module.exports=makeParserClass(require_parser()),module.exports.makeParserClass=makeParserClass;var TomlError=class e extends Error{constructor(n){super(n),this.name=`TomlError`,Error.captureStackTrace&&Error.captureStackTrace(this,e),this.fromTOML=!0,this.wrapped=null}};TomlError.wrap=e=>{let n=new TomlError(e.message);return n.code=e.code,n.wrapped=e,n},module.exports.TomlError=TomlError;var createDateTime=require_create_datetime(),createDateTimeFloat=require_create_datetime_float(),createDate=require_create_date(),createTime=require_create_time(),CTRL_I=9,CTRL_J=10,CTRL_M=13,CTRL_CHAR_BOUNDARY=31,CHAR_SP=32,CHAR_QUOT=34,CHAR_NUM=35,CHAR_APOS=39,CHAR_PLUS=43,CHAR_COMMA=44,CHAR_HYPHEN=45,CHAR_PERIOD=46,CHAR_0=48,CHAR_1=49,CHAR_7=55,CHAR_9=57,CHAR_COLON=58,CHAR_EQUALS=61,CHAR_A=65,CHAR_E=69,CHAR_F=70,CHAR_T=84,CHAR_U=85,CHAR_Z=90,CHAR_LOWBAR=95,CHAR_a=97,CHAR_b=98,CHAR_e=101,CHAR_f=102,CHAR_i=105,CHAR_l=108,CHAR_n=110,CHAR_o=111,CHAR_r=114,CHAR_s=115,CHAR_t=116,CHAR_u=117,CHAR_x=120,CHAR_z=122,CHAR_LCUB=123,CHAR_RCUB=125,CHAR_LSQB=91,CHAR_BSOL=92,CHAR_RSQB=93,CHAR_DEL=127,SURROGATE_FIRST=55296,SURROGATE_LAST=57343,escapes={[CHAR_b]:`\b`,[CHAR_t]:` `,[CHAR_n]:`
|
|
9
|
+
`,[CHAR_f]:`\f`,[CHAR_r]:`\r`,[CHAR_QUOT]:`"`,[CHAR_BSOL]:`\\`};function isDigit(e){return e>=CHAR_0&&e<=CHAR_9}function isHexit(e){return e>=CHAR_A&&e<=CHAR_F||e>=CHAR_a&&e<=CHAR_f||e>=CHAR_0&&e<=CHAR_9}function isBit(e){return e===CHAR_1||e===CHAR_0}function isOctit(e){return e>=CHAR_0&&e<=CHAR_7}function isAlphaNumQuoteHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_APOS||e===CHAR_QUOT||e===CHAR_LOWBAR||e===CHAR_HYPHEN}function isAlphaNumHyphen(e){return e>=CHAR_A&&e<=CHAR_Z||e>=CHAR_a&&e<=CHAR_z||e>=CHAR_0&&e<=CHAR_9||e===CHAR_LOWBAR||e===CHAR_HYPHEN}var _type=Symbol(`type`),_declared=Symbol(`declared`),hasOwnProperty=Object.prototype.hasOwnProperty,defineProperty=Object.defineProperty,descriptor={configurable:!0,enumerable:!0,writable:!0,value:void 0};function hasKey(e,n){return hasOwnProperty.call(e,n)?!0:(n===`__proto__`&&defineProperty(e,`__proto__`,descriptor),!1)}var INLINE_TABLE=Symbol(`inline-table`);function InlineTable(){return Object.defineProperties({},{[_type]:{value:INLINE_TABLE}})}function isInlineTable(e){return typeof e!=`object`||!e?!1:e[_type]===INLINE_TABLE}var TABLE=Symbol(`table`);function Table(){return Object.defineProperties({},{[_type]:{value:TABLE},[_declared]:{value:!1,writable:!0}})}function isTable(e){return typeof e!=`object`||!e?!1:e[_type]===TABLE}var _contentType=Symbol(`content-type`),INLINE_LIST=Symbol(`inline-list`);function InlineList(e){return Object.defineProperties([],{[_type]:{value:INLINE_LIST},[_contentType]:{value:e}})}function isInlineList(e){return typeof e!=`object`||!e?!1:e[_type]===INLINE_LIST}var LIST=Symbol(`list`);function List(){return Object.defineProperties([],{[_type]:{value:LIST}})}function isList(e){return typeof e!=`object`||!e?!1:e[_type]===LIST}var _custom;try{const utilInspect=eval(`require('util').inspect`);_custom=utilInspect.custom}catch{}var _inspect=_custom||`inspect`,BoxedBigInt=class{constructor(e){try{this.value=global.BigInt.asIntN(64,e)}catch{this.value=null}Object.defineProperty(this,_type,{value:INTEGER})}isNaN(){return this.value===null}toString(){return String(this.value)}[_inspect](){return`[BigInt: ${this.toString()}]}`}valueOf(){return this.value}},INTEGER=Symbol(`integer`);function Integer(e){let n=Number(e);return Object.is(n,-0)&&(n=0),global.BigInt&&!Number.isSafeInteger(n)?new BoxedBigInt(e):Object.defineProperties(new Number(n),{isNaN:{value:function(){return isNaN(this)}},[_type]:{value:INTEGER},[_inspect]:{value:()=>`[Integer: ${e}]`}})}function isInteger(e){return typeof e!=`object`||!e?!1:e[_type]===INTEGER}var FLOAT=Symbol(`float`);function Float(e){return Object.defineProperties(new Number(e),{[_type]:{value:FLOAT},[_inspect]:{value:()=>`[Float: ${e}]`}})}function isFloat(e){return typeof e!=`object`||!e?!1:e[_type]===FLOAT}function tomlType(e){let n=typeof e;if(n===`object`){if(e===null)return`null`;if(e instanceof Date)return`datetime`;if(_type in e)switch(e[_type]){case INLINE_TABLE:return`inline-table`;case INLINE_LIST:return`inline-list`;case TABLE:return`table`;case LIST:return`list`;case FLOAT:return`float`;case INTEGER:return`integer`}}return n}function makeParserClass(e){class n extends e{constructor(){super(),this.ctx=this.obj=Table()}atEndOfWord(){return this.char===CHAR_NUM||this.char===CTRL_I||this.char===CHAR_SP||this.atEndOfLine()}atEndOfLine(){return this.char===e.END||this.char===CTRL_J||this.char===CTRL_M}parseStart(){if(this.char===e.END)return null;if(this.char===CHAR_LSQB)return this.call(this.parseTableOrList);if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(isAlphaNumQuoteHyphen(this.char))return this.callNow(this.parseAssignStatement);throw this.error(new TomlError(`Unknown character "${this.char}"`))}parseWhitespaceToEOL(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M)return null;if(this.char===CHAR_NUM)return this.goto(this.parseComment);if(this.char===e.END||this.char===CTRL_J)return this.return();throw this.error(new TomlError(`Unexpected character, expected only whitespace or comments till end of line`))}parseAssignStatement(){return this.callNow(this.parseAssign,this.recordAssignStatement)}recordAssignStatement(e){let n=this.ctx,r=e.key.pop();for(let r of e.key){if(hasKey(n,r)&&(!isTable(n[r])||n[r][_declared]))throw this.error(new TomlError(`Can't redefine existing key`));n=n[r]=n[r]||Table()}if(hasKey(n,r))throw this.error(new TomlError(`Can't redefine existing key`));return isInteger(e.value)||isFloat(e.value)?n[r]=e.value.valueOf():n[r]=e.value,this.goto(this.parseWhitespaceToEOL)}parseAssign(){return this.callNow(this.parseKeyword,this.recordAssignKeyword)}recordAssignKeyword(e){return this.state.resultTable?this.state.resultTable.push(e):this.state.resultTable=[e],this.goto(this.parseAssignKeywordPreDot)}parseAssignKeywordPreDot(){if(this.char===CHAR_PERIOD)return this.next(this.parseAssignKeywordPostDot);if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.goto(this.parseAssignEqual)}parseAssignKeywordPostDot(){if(this.char!==CHAR_SP&&this.char!==CTRL_I)return this.callNow(this.parseKeyword,this.recordAssignKeyword)}parseAssignEqual(){if(this.char===CHAR_EQUALS)return this.next(this.parseAssignPreValue);throw this.error(new TomlError(`Invalid character, expected "="`))}parseAssignPreValue(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseValue,this.recordAssignValue)}recordAssignValue(e){return this.returnNow({key:this.state.resultTable,value:e})}parseComment(){do if(this.char===e.END||this.char===CTRL_J)return this.return();while(this.nextChar())}parseTableOrList(){if(this.char===CHAR_LSQB)this.next(this.parseList);else return this.goto(this.parseTable)}parseTable(){return this.ctx=this.obj,this.goto(this.parseTableNext)}parseTableNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseTableMore)}parseTableMore(e){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,e)&&(!isTable(this.ctx[e])||this.ctx[e][_declared]))throw this.error(new TomlError(`Can't redefine existing key`));return this.ctx=this.ctx[e]=this.ctx[e]||Table(),this.ctx[_declared]=!0,this.next(this.parseWhitespaceToEOL)}if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,e))this.ctx=this.ctx[e]=Table();else if(isTable(this.ctx[e]))this.ctx=this.ctx[e];else if(isList(this.ctx[e]))this.ctx=this.ctx[e][this.ctx[e].length-1];else throw this.error(new TomlError(`Can't redefine existing key`));return this.next(this.parseTableNext)}throw this.error(new TomlError(`Unexpected character, expected whitespace, . or ]`))}parseList(){return this.ctx=this.obj,this.goto(this.parseListNext)}parseListNext(){return this.char===CHAR_SP||this.char===CTRL_I?null:this.callNow(this.parseKeyword,this.parseListMore)}parseListMore(e){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CHAR_RSQB){if(hasKey(this.ctx,e)||(this.ctx[e]=List()),isInlineList(this.ctx[e]))throw this.error(new TomlError(`Can't extend an inline array`));if(isList(this.ctx[e])){let n=Table();this.ctx[e].push(n),this.ctx=n}else throw this.error(new TomlError(`Can't redefine an existing key`));return this.next(this.parseListEnd)}if(this.char===CHAR_PERIOD){if(!hasKey(this.ctx,e))this.ctx=this.ctx[e]=Table();else if(isInlineList(this.ctx[e]))throw this.error(new TomlError(`Can't extend an inline array`));else if(isInlineTable(this.ctx[e]))throw this.error(new TomlError(`Can't extend an inline table`));else if(isList(this.ctx[e]))this.ctx=this.ctx[e][this.ctx[e].length-1];else if(isTable(this.ctx[e]))this.ctx=this.ctx[e];else throw this.error(new TomlError(`Can't redefine an existing key`));return this.next(this.parseListNext)}throw this.error(new TomlError(`Unexpected character, expected whitespace, . or ]`))}parseListEnd(e){if(this.char===CHAR_RSQB)return this.next(this.parseWhitespaceToEOL);throw this.error(new TomlError(`Unexpected character, expected whitespace, . or ]`))}parseValue(){if(this.char===e.END)throw this.error(new TomlError(`Key without value`));if(this.char===CHAR_QUOT)return this.next(this.parseDoubleString);if(this.char===CHAR_APOS)return this.next(this.parseSingleString);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)return this.goto(this.parseNumberSign);if(this.char===CHAR_i)return this.next(this.parseInf);if(this.char===CHAR_n)return this.next(this.parseNan);if(isDigit(this.char))return this.goto(this.parseNumberOrDateTime);if(this.char===CHAR_t||this.char===CHAR_f)return this.goto(this.parseBoolean);if(this.char===CHAR_LSQB)return this.call(this.parseInlineList,this.recordValue);if(this.char===CHAR_LCUB)return this.call(this.parseInlineTable,this.recordValue);throw this.error(new TomlError(`Unexpected character, expecting string, number, datetime, boolean, inline array or inline table`))}recordValue(e){return this.returnNow(e)}parseInf(){if(this.char===CHAR_n)return this.next(this.parseInf2);throw this.error(new TomlError(`Unexpected character, expected "inf", "+inf" or "-inf"`))}parseInf2(){if(this.char===CHAR_f)return this.state.buf===`-`?this.return(-1/0):this.return(1/0);throw this.error(new TomlError(`Unexpected character, expected "inf", "+inf" or "-inf"`))}parseNan(){if(this.char===CHAR_a)return this.next(this.parseNan2);throw this.error(new TomlError(`Unexpected character, expected "nan"`))}parseNan2(){if(this.char===CHAR_n)return this.return(NaN);throw this.error(new TomlError(`Unexpected character, expected "nan"`))}parseKeyword(){return this.char===CHAR_QUOT?this.next(this.parseBasicString):this.char===CHAR_APOS?this.next(this.parseLiteralString):this.goto(this.parseBareKey)}parseBareKey(){do{if(this.char===e.END)throw this.error(new TomlError(`Key ended without value`));if(isAlphaNumHyphen(this.char))this.consume();else if(this.state.buf.length===0)throw this.error(new TomlError(`Empty bare keys are not allowed`));else return this.returnNow()}while(this.nextChar())}parseSingleString(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiStringMaybe):this.goto(this.parseLiteralString)}parseLiteralString(){do{if(this.char===CHAR_APOS)return this.return();if(this.atEndOfLine())throw this.error(new TomlError(`Unterminated string`));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}parseLiteralMultiStringMaybe(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiString):this.returnNow()}parseLiteralMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseLiteralMultiStringContent):this.goto(this.parseLiteralMultiStringContent)}parseLiteralMultiStringContent(){do{if(this.char===CHAR_APOS)return this.next(this.parseLiteralMultiEnd);if(this.char===e.END)throw this.error(new TomlError(`Unterminated multi-line string`));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}parseLiteralMultiEnd(){return this.char===CHAR_APOS?this.next(this.parseLiteralMultiEnd2):(this.state.buf+=`'`,this.goto(this.parseLiteralMultiStringContent))}parseLiteralMultiEnd2(){return this.char===CHAR_APOS?this.return():(this.state.buf+=`''`,this.goto(this.parseLiteralMultiStringContent))}parseDoubleString(){return this.char===CHAR_QUOT?this.next(this.parseMultiStringMaybe):this.goto(this.parseBasicString)}parseBasicString(){do{if(this.char===CHAR_BSOL)return this.call(this.parseEscape,this.recordEscapeReplacement);if(this.char===CHAR_QUOT)return this.return();if(this.atEndOfLine())throw this.error(new TomlError(`Unterminated string`));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}recordEscapeReplacement(e){return this.state.buf+=e,this.goto(this.parseBasicString)}parseMultiStringMaybe(){return this.char===CHAR_QUOT?this.next(this.parseMultiString):this.returnNow()}parseMultiString(){return this.char===CTRL_M?null:this.char===CTRL_J?this.next(this.parseMultiStringContent):this.goto(this.parseMultiStringContent)}parseMultiStringContent(){do{if(this.char===CHAR_BSOL)return this.call(this.parseMultiEscape,this.recordMultiEscapeReplacement);if(this.char===CHAR_QUOT)return this.next(this.parseMultiEnd);if(this.char===e.END)throw this.error(new TomlError(`Unterminated multi-line string`));if(this.char===CHAR_DEL||this.char<=CTRL_CHAR_BOUNDARY&&this.char!==CTRL_I&&this.char!==CTRL_J&&this.char!==CTRL_M)throw this.errorControlCharInString();this.consume()}while(this.nextChar())}errorControlCharInString(){let e=`\\u00`;return this.char<16&&(e+=`0`),e+=this.char.toString(16),this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${e} instead`))}recordMultiEscapeReplacement(e){return this.state.buf+=e,this.goto(this.parseMultiStringContent)}parseMultiEnd(){return this.char===CHAR_QUOT?this.next(this.parseMultiEnd2):(this.state.buf+=`"`,this.goto(this.parseMultiStringContent))}parseMultiEnd2(){return this.char===CHAR_QUOT?this.return():(this.state.buf+=`""`,this.goto(this.parseMultiStringContent))}parseMultiEscape(){return this.char===CTRL_M||this.char===CTRL_J?this.next(this.parseMultiTrim):this.char===CHAR_SP||this.char===CTRL_I?this.next(this.parsePreMultiTrim):this.goto(this.parseEscape)}parsePreMultiTrim(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===CTRL_M||this.char===CTRL_J)return this.next(this.parseMultiTrim);throw this.error(new TomlError(`Can't escape whitespace`))}parseMultiTrim(){return this.char===CTRL_J||this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M?null:this.returnNow()}parseEscape(){if(this.char in escapes)return this.return(escapes[this.char]);if(this.char===CHAR_u)return this.call(this.parseSmallUnicode,this.parseUnicodeReturn);if(this.char===CHAR_U)return this.call(this.parseLargeUnicode,this.parseUnicodeReturn);throw this.error(new TomlError(`Unknown escape character: `+this.char))}parseUnicodeReturn(e){try{let n=parseInt(e,16);if(n>=SURROGATE_FIRST&&n<=SURROGATE_LAST)throw this.error(new TomlError(`Invalid unicode, character in range 0xD800 - 0xDFFF is reserved`));return this.returnNow(String.fromCodePoint(n))}catch(e){throw this.error(TomlError.wrap(e))}}parseSmallUnicode(){if(!isHexit(this.char))throw this.error(new TomlError(`Invalid character in unicode sequence, expected hex`));if(this.consume(),this.state.buf.length>=4)return this.return()}parseLargeUnicode(){if(!isHexit(this.char))throw this.error(new TomlError(`Invalid character in unicode sequence, expected hex`));if(this.consume(),this.state.buf.length>=8)return this.return()}parseNumberSign(){return this.consume(),this.next(this.parseMaybeSignedInfOrNan)}parseMaybeSignedInfOrNan(){return this.char===CHAR_i?this.next(this.parseInf):this.char===CHAR_n?this.next(this.parseNan):this.callNow(this.parseNoUnder,this.parseNumberIntegerStart)}parseNumberIntegerStart(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberIntegerExponentOrDecimal)):this.goto(this.parseNumberInteger)}parseNumberIntegerExponentOrDecimal(){return this.char===CHAR_PERIOD?(this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat)):this.char===CHAR_E||this.char===CHAR_e?(this.consume(),this.next(this.parseNumberExponentSign)):this.returnNow(Integer(this.state.buf))}parseNumberInteger(){if(isDigit(this.char))this.consume();else if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder);else if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===CHAR_PERIOD)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else{let e=Integer(this.state.buf);if(e.isNaN())throw this.error(new TomlError(`Invalid number`));return this.returnNow(e)}}parseNoUnder(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD||this.char===CHAR_E||this.char===CHAR_e)throw this.error(new TomlError(`Unexpected character, expected digit`));if(this.atEndOfWord())throw this.error(new TomlError(`Incomplete number`));return this.returnNow()}parseNoUnderHexOctBinLiteral(){if(this.char===CHAR_LOWBAR||this.char===CHAR_PERIOD)throw this.error(new TomlError(`Unexpected character, expected digit`));if(this.atEndOfWord())throw this.error(new TomlError(`Incomplete number`));return this.returnNow()}parseNumberFloat(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberFloat);if(isDigit(this.char))this.consume();else if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);else return this.returnNow(Float(this.state.buf))}parseNumberExponentSign(){if(isDigit(this.char))return this.goto(this.parseNumberExponent);if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.call(this.parseNoUnder,this.parseNumberExponent);else throw this.error(new TomlError(`Unexpected character, expected -, + or digit`))}parseNumberExponent(){if(isDigit(this.char))this.consume();else if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder);else return this.returnNow(Float(this.state.buf))}parseNumberOrDateTime(){return this.char===CHAR_0?(this.consume(),this.next(this.parseNumberBaseOrDateTime)):this.goto(this.parseNumberOrDateTimeOnly)}parseNumberOrDateTimeOnly(){if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnder,this.parseNumberInteger);if(isDigit(this.char))this.consume(),this.state.buf.length>4&&this.next(this.parseNumberInteger);else if(this.char===CHAR_E||this.char===CHAR_e)return this.consume(),this.next(this.parseNumberExponentSign);else if(this.char===CHAR_PERIOD)return this.consume(),this.call(this.parseNoUnder,this.parseNumberFloat);else if(this.char===CHAR_HYPHEN)return this.goto(this.parseDateTime);else if(this.char===CHAR_COLON)return this.goto(this.parseOnlyTimeHour);else return this.returnNow(Integer(this.state.buf))}parseDateTimeOnly(){if(this.state.buf.length<4){if(isDigit(this.char))return this.consume();if(this.char===CHAR_COLON)return this.goto(this.parseOnlyTimeHour);throw this.error(new TomlError(`Expected digit while parsing year part of a date`))}if(this.char===CHAR_HYPHEN)return this.goto(this.parseDateTime);throw this.error(new TomlError(`Expected hyphen (-) while parsing year part of date`))}parseNumberBaseOrDateTime(){return this.char===CHAR_b?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerBin)):this.char===CHAR_o?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerOct)):this.char===CHAR_x?(this.consume(),this.call(this.parseNoUnderHexOctBinLiteral,this.parseIntegerHex)):this.char===CHAR_PERIOD?this.goto(this.parseNumberInteger):isDigit(this.char)?this.goto(this.parseDateTimeOnly):this.returnNow(Integer(this.state.buf))}parseIntegerHex(){if(isHexit(this.char))this.consume();else if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);else{let e=Integer(this.state.buf);if(e.isNaN())throw this.error(new TomlError(`Invalid number`));return this.returnNow(e)}}parseIntegerOct(){if(isOctit(this.char))this.consume();else if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);else{let e=Integer(this.state.buf);if(e.isNaN())throw this.error(new TomlError(`Invalid number`));return this.returnNow(e)}}parseIntegerBin(){if(isBit(this.char))this.consume();else if(this.char===CHAR_LOWBAR)return this.call(this.parseNoUnderHexOctBinLiteral);else{let e=Integer(this.state.buf);if(e.isNaN())throw this.error(new TomlError(`Invalid number`));return this.returnNow(e)}}parseDateTime(){if(this.state.buf.length<4)throw this.error(new TomlError(`Years less than 1000 must be zero padded to four characters`));return this.state.result=this.state.buf,this.state.buf=``,this.next(this.parseDateMonth)}parseDateMonth(){if(this.char===CHAR_HYPHEN){if(this.state.buf.length<2)throw this.error(new TomlError(`Months less than 10 must be zero padded to two characters`));return this.state.result+=`-`+this.state.buf,this.state.buf=``,this.next(this.parseDateDay)}if(isDigit(this.char))this.consume();else throw this.error(new TomlError(`Incomplete datetime`))}parseDateDay(){if(this.char===CHAR_T||this.char===CHAR_SP){if(this.state.buf.length<2)throw this.error(new TomlError(`Days less than 10 must be zero padded to two characters`));return this.state.result+=`-`+this.state.buf,this.state.buf=``,this.next(this.parseStartTimeHour)}if(this.atEndOfWord())return this.returnNow(createDate(this.state.result+`-`+this.state.buf));if(isDigit(this.char))this.consume();else throw this.error(new TomlError(`Incomplete datetime`))}parseStartTimeHour(){return this.atEndOfWord()?this.returnNow(createDate(this.state.result)):this.goto(this.parseTimeHour)}parseTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError(`Hours less than 10 must be zero padded to two characters`));return this.state.result+=`T`+this.state.buf,this.state.buf=``,this.next(this.parseTimeMin)}if(isDigit(this.char))this.consume();else throw this.error(new TomlError(`Incomplete datetime`))}parseTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else if(this.state.buf.length===2&&this.char===CHAR_COLON)return this.state.result+=`:`+this.state.buf,this.state.buf=``,this.next(this.parseTimeSec);else throw this.error(new TomlError(`Incomplete datetime`))}parseTimeSec(){if(isDigit(this.char)){if(this.consume(),this.state.buf.length===2)return this.state.result+=`:`+this.state.buf,this.state.buf=``,this.next(this.parseTimeZoneOrFraction)}else throw this.error(new TomlError(`Incomplete datetime`))}parseOnlyTimeHour(){if(this.char===CHAR_COLON){if(this.state.buf.length<2)throw this.error(new TomlError(`Hours less than 10 must be zero padded to two characters`));return this.state.result=this.state.buf,this.state.buf=``,this.next(this.parseOnlyTimeMin)}throw this.error(new TomlError(`Incomplete time`))}parseOnlyTimeMin(){if(this.state.buf.length<2&&isDigit(this.char))this.consume();else if(this.state.buf.length===2&&this.char===CHAR_COLON)return this.state.result+=`:`+this.state.buf,this.state.buf=``,this.next(this.parseOnlyTimeSec);else throw this.error(new TomlError(`Incomplete time`))}parseOnlyTimeSec(){if(isDigit(this.char)){if(this.consume(),this.state.buf.length===2)return this.next(this.parseOnlyTimeFractionMaybe)}else throw this.error(new TomlError(`Incomplete time`))}parseOnlyTimeFractionMaybe(){if(this.state.result+=`:`+this.state.buf,this.char===CHAR_PERIOD)this.state.buf=``,this.next(this.parseOnlyTimeFraction);else return this.return(createTime(this.state.result))}parseOnlyTimeFraction(){if(isDigit(this.char))this.consume();else if(this.atEndOfWord()){if(this.state.buf.length===0)throw this.error(new TomlError(`Expected digit in milliseconds`));return this.returnNow(createTime(this.state.result+`.`+this.state.buf))}else throw this.error(new TomlError(`Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z`))}parseTimeZoneOrFraction(){if(this.char===CHAR_PERIOD)this.consume(),this.next(this.parseDateTimeFraction);else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));else throw this.error(new TomlError(`Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z`))}parseDateTimeFraction(){if(isDigit(this.char))this.consume();else if(this.state.buf.length===1)throw this.error(new TomlError(`Expected digit in milliseconds`));else if(this.char===CHAR_HYPHEN||this.char===CHAR_PLUS)this.consume(),this.next(this.parseTimeZoneHour);else if(this.char===CHAR_Z)return this.consume(),this.return(createDateTime(this.state.result+this.state.buf));else if(this.atEndOfWord())return this.returnNow(createDateTimeFloat(this.state.result+this.state.buf));else throw this.error(new TomlError(`Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z`))}parseTimeZoneHour(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.next(this.parseTimeZoneSep)}else throw this.error(new TomlError(`Unexpected character in datetime, expected digit`))}parseTimeZoneSep(){if(this.char===CHAR_COLON)this.consume(),this.next(this.parseTimeZoneMin);else throw this.error(new TomlError(`Unexpected character in datetime, expected colon`))}parseTimeZoneMin(){if(isDigit(this.char)){if(this.consume(),/\d\d$/.test(this.state.buf))return this.return(createDateTime(this.state.result+this.state.buf))}else throw this.error(new TomlError(`Unexpected character in datetime, expected digit`))}parseBoolean(){if(this.char===CHAR_t)return this.consume(),this.next(this.parseTrue_r);if(this.char===CHAR_f)return this.consume(),this.next(this.parseFalse_a)}parseTrue_r(){if(this.char===CHAR_r)return this.consume(),this.next(this.parseTrue_u);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseTrue_u(){if(this.char===CHAR_u)return this.consume(),this.next(this.parseTrue_e);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseTrue_e(){if(this.char===CHAR_e)return this.return(!0);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseFalse_a(){if(this.char===CHAR_a)return this.consume(),this.next(this.parseFalse_l);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseFalse_l(){if(this.char===CHAR_l)return this.consume(),this.next(this.parseFalse_s);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseFalse_s(){if(this.char===CHAR_s)return this.consume(),this.next(this.parseFalse_e);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseFalse_e(){if(this.char===CHAR_e)return this.return(!1);throw this.error(new TomlError(`Invalid boolean, expected true or false`))}parseInlineList(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===e.END)throw this.error(new TomlError(`Unterminated inline array`));return this.char===CHAR_NUM?this.call(this.parseComment):this.char===CHAR_RSQB?this.return(this.state.resultArr||InlineList()):this.callNow(this.parseValue,this.recordInlineListValue)}recordInlineListValue(e){if(this.state.resultArr){let n=this.state.resultArr[_contentType],r=tomlType(e);if(n!==r)throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${n} and ${r}`))}else this.state.resultArr=InlineList(tomlType(e));return isFloat(e)||isInteger(e)?this.state.resultArr.push(e.valueOf()):this.state.resultArr.push(e),this.goto(this.parseInlineListNext)}parseInlineListNext(){if(this.char===CHAR_SP||this.char===CTRL_I||this.char===CTRL_M||this.char===CTRL_J)return null;if(this.char===CHAR_NUM)return this.call(this.parseComment);if(this.char===CHAR_COMMA)return this.next(this.parseInlineList);if(this.char===CHAR_RSQB)return this.goto(this.parseInlineList);throw this.error(new TomlError(`Invalid character, expected whitespace, comma (,) or close bracket (])`))}parseInlineTable(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError(`Unterminated inline array`));return this.char===CHAR_RCUB?this.return(this.state.resultTable||InlineTable()):(this.state.resultTable||(this.state.resultTable=InlineTable()),this.callNow(this.parseAssign,this.recordInlineTableValue))}recordInlineTableValue(e){let n=this.state.resultTable,r=e.key.pop();for(let r of e.key){if(hasKey(n,r)&&(!isTable(n[r])||n[r][_declared]))throw this.error(new TomlError(`Can't redefine existing key`));n=n[r]=n[r]||Table()}if(hasKey(n,r))throw this.error(new TomlError(`Can't redefine existing key`));return isInteger(e.value)||isFloat(e.value)?n[r]=e.value.valueOf():n[r]=e.value,this.goto(this.parseInlineTableNext)}parseInlineTableNext(){if(this.char===CHAR_SP||this.char===CTRL_I)return null;if(this.char===e.END||this.char===CHAR_NUM||this.char===CTRL_J||this.char===CTRL_M)throw this.error(new TomlError(`Unterminated inline array`));if(this.char===CHAR_COMMA)return this.next(this.parseInlineTable);if(this.char===CHAR_RCUB)return this.goto(this.parseInlineTable);throw this.error(new TomlError(`Invalid character, expected whitespace, comma (,) or close bracket (])`))}}return n}}}),require_parse_pretty_error=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js"(e,n){n.exports=r;function r(e,n){if(e.pos==null||e.line==null)return e;let r=e.message;if(r+=` at row ${e.line+1}, col ${e.col+1}, pos ${e.pos}:
|
|
10
|
+
`,n&&n.split){let a=n.split(/\n/),o=String(Math.min(a.length,e.line+3)).length,s=` `;for(;s.length<o;)s+=` `;for(let n=Math.max(0,e.line-1);n<Math.min(a.length,e.line+2);++n){let c=String(n+1);if(c.length<o&&(c=` `+c),e.line===n){r+=c+`> `+a[n]+`
|
|
11
|
+
`,r+=s+` `;for(let n=0;n<e.col;++n)r+=` `;r+=`^
|
|
12
|
+
`}else r+=c+`: `+a[n]+`
|
|
13
|
+
`}}return e.message=r+`
|
|
14
|
+
`,e}}}),require_parse_string=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js"(e,n){n.exports=o;var r=require_toml_parser(),a=require_parse_pretty_error();function o(e){global.Buffer&&global.Buffer.isBuffer(e)&&(e=e.toString(`utf8`));let n=new r;try{return n.parse(e),n.finish()}catch(n){throw a(n,e)}}}}),require_parse_async=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js"(e,n){n.exports=o;var r=require_toml_parser(),a=require_parse_pretty_error();function o(e,n){n||={};let o=0,s=n.blocksize||40960,c=new r;return new Promise((e,n)=>{setImmediate(l,0,s,e,n)});function l(n,r,o,s){if(n>=e.length)try{return o(c.finish())}catch(n){return s(a(n,e))}try{c.parse(e.slice(n,n+r)),setImmediate(l,n+r,r,o,s)}catch(n){s(a(n,e))}}}}}),require_parse_stream=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js"(e,n){n.exports=o;var r=require("stream"),a=require_toml_parser();function o(e){return e?s(e):c(e)}function s(e){let n=new a;return e.setEncoding(`utf8`),new Promise((r,a)=>{let o,s=!1,c=!1;function l(){if(s=!0,!o)try{r(n.finish())}catch(e){a(e)}}function u(e){c=!0,a(e)}e.once(`end`,l),e.once(`error`,u),d();function d(){o=!0;let r;for(;(r=e.read())!==null;)try{n.parse(r)}catch(e){return u(e)}if(o=!1,s)return l();c||e.once(`readable`,d)}})}function c(){let e=new a;return new r.Transform({objectMode:!0,transform(n,r,a){try{e.parse(n.toString(r))}catch(e){this.emit(`error`,e)}a()},flush(n){try{this.push(e.finish())}catch(e){this.emit(`error`,e)}n()}})}}}),require_parse=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js"(e,n){n.exports=require_parse_string(),n.exports.async=require_parse_async(),n.exports.stream=require_parse_stream(),n.exports.prettyError=require_parse_pretty_error()}}),require_stringify=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js"(e,n){n.exports=r,n.exports.value=E;function r(e){if(e===null)throw a(`null`);if(e===void 0)throw a(`undefined`);if(typeof e!=`object`)throw a(typeof e);if(typeof e.toJSON==`function`&&(e=e.toJSON()),e==null)return null;let n=f(e);if(n!==`table`)throw a(n);return u(``,``,e)}function a(e){return Error(`Can only stringify objects, not `+e)}function o(){return Error(`Array values can't have mixed types`)}function s(e){return Object.keys(e).filter(n=>d(e[n]))}function c(e){return Object.keys(e).filter(n=>!d(e[n]))}function l(e){let n=Array.isArray(e)?[]:Object.prototype.hasOwnProperty.call(e,`__proto__`)?{["__proto__"]:void 0}:{};for(let r of Object.keys(e))n[r]=e[r]&&typeof e[r].toJSON==`function`&&!(`toISOString`in e[r])?e[r].toJSON():e[r];return n}function u(e,n,r){r=l(r);var a=s(r),o=c(r),u=[],d=n||``;a.forEach(e=>{var n=f(r[e]);n!==`undefined`&&n!==`null`&&u.push(d+h(e)+` = `+T(r[e],!0))}),u.length>0&&u.push(``);var _=e&&a.length>0?n+` `:``;return o.forEach(n=>{u.push(I(e,_,n,r[n]))}),u.join(`
|
|
15
|
+
`)}function d(e){switch(f(e)){case`undefined`:case`null`:case`integer`:case`nan`:case`float`:case`boolean`:case`string`:case`datetime`:return!0;case`array`:return e.length===0||f(e[0])!==`table`;case`table`:return Object.keys(e).length===0;default:return!1}}function f(e){return e===void 0?`undefined`:e===null?`null`:typeof e==`bigint`||Number.isInteger(e)&&!Object.is(e,-0)?`integer`:typeof e==`number`?`float`:typeof e==`boolean`?`boolean`:typeof e==`string`?`string`:`toISOString`in e?isNaN(e)?`undefined`:`datetime`:Array.isArray(e)?`array`:`table`}function h(e){var n=String(e);return/^[-A-Za-z0-9_]+$/.test(n)?n:_(n)}function _(e){return`"`+C(e).replace(/"/g,`\\"`)+`"`}function y(e){return`'`+e+`'`}function x(e,n){for(;n.length<e;)n=`0`+n;return n}function C(e){return e.replace(/\\/g,`\\\\`).replace(/[\b]/g,`\\b`).replace(/\t/g,`\\t`).replace(/\n/g,`\\n`).replace(/\f/g,`\\f`).replace(/\r/g,`\\r`).replace(/([\u0000-\u001f\u007f])/,e=>`\\u`+x(4,e.codePointAt(0).toString(16)))}function w(e){let n=e.split(/\n/).map(e=>C(e).replace(/"(?="")/g,`\\"`)).join(`
|
|
16
|
+
`);return n.slice(-1)===`"`&&(n+=`\\
|
|
17
|
+
`),`"""
|
|
18
|
+
`+n+`"""`}function T(e,n){let r=f(e);return r===`string`&&(n&&/\n/.test(e)?r=`string-multiline`:!/[\b\t\n\f\r']/.test(e)&&/"/.test(e)&&(r=`string-literal`)),E(e,r)}function E(e,n){switch(n||=f(e),n){case`string-multiline`:return w(e);case`string`:return _(e);case`string-literal`:return y(e);case`integer`:return D(e);case`float`:return O(e);case`boolean`:return k(e);case`datetime`:return A(e);case`array`:return P(e.filter(e=>f(e)!==`null`&&f(e)!==`undefined`&&f(e)!==`nan`));case`table`:return F(e);default:throw a(n)}}function D(e){return String(e).replace(/\B(?=(\d{3})+(?!\d))/g,`_`)}function O(e){if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Object.is(e,NaN))return`nan`;if(Object.is(e,-0))return`-0.0`;var n=String(e).split(`.`),r=n[0],a=n[1]||0;return D(r)+`.`+a}function k(e){return String(e)}function A(e){return e.toISOString()}function j(e){return e===`float`||e===`integer`}function M(e){var n=f(e[0]);return e.every(e=>f(e)===n)?n:e.every(e=>j(f(e)))?`float`:`mixed`}function N(e){let n=M(e);if(n===`mixed`)throw o();return n}function P(e){e=l(e);let n=N(e);var r=`[`,a=e.map(e=>E(e,n));return a.join(`, `).length>60||/\n/.test(a)?r+=`
|
|
19
|
+
`+a.join(`,
|
|
20
|
+
`)+`
|
|
21
|
+
`:r+=` `+a.join(`, `)+(a.length>0?` `:``),r+`]`}function F(e){e=l(e);var n=[];return Object.keys(e).forEach(r=>{n.push(h(r)+` = `+T(e[r],!1))}),`{ `+n.join(`, `)+(n.length>0?` `:``)+`}`}function I(e,n,r,o){var s=f(o);if(s===`array`)return R(e,n,r,o);if(s===`table`)return z(e,n,r,o);throw a(s)}function R(e,n,r,o){o=l(o),N(o);var s=f(o[0]);if(s!==`table`)throw a(s);var c=e+h(r),d=``;return o.forEach(e=>{d.length>0&&(d+=`
|
|
22
|
+
`),d+=n+`[[`+c+`]]
|
|
23
|
+
`,d+=u(c+`.`,n,e)}),d}function z(e,n,r,a){var o=e+h(r),c=``;return s(a).length>0&&(c+=n+`[`+o+`]
|
|
24
|
+
`),c+u(o+`.`,n,a)}}}),require_toml=__commonJS({"../core/node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js"(e){e.parse=require_parse(),e.stringify=require_stringify()}}),require_errors=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/errors.js"(e,n){var r={PasetoNotSupported:`ERR_PASETO_NOT_SUPPORTED`,PasetoDecryptionFailed:`ERR_PASETO_DECRYPTION_FAILED`,PasetoInvalid:`ERR_PASETO_INVALID`,PasetoVerificationFailed:`ERR_PASETO_VERIFICATION_FAILED`,PasetoClaimInvalid:`ERR_PASETO_CLAIM_INVALID`},a=class extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=r[this.constructor.name],Error.captureStackTrace(this,this.constructor)}};n.exports.PasetoError=a,n.exports.PasetoNotSupported=class extends a{},n.exports.PasetoDecryptionFailed=class extends a{},n.exports.PasetoInvalid=class extends a{},n.exports.PasetoVerificationFailed=class extends a{},n.exports.PasetoClaimInvalid=class extends a{}}}),require_is_object=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/is_object.js"(e,n){n.exports=e=>!!e&&e.constructor===Object}}),require_check_footer=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/check_footer.js"(e,n){var r=require_is_object();n.exports=function(e){if(e===void 0)return Buffer.from(``);if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),`utf8`);if(typeof e!=`string`)throw TypeError(`options.footer must be a string, Buffer, or a plain object`);return Buffer.from(e,`utf8`)}}}),require_ms=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/ms.js"(e,n){var r=1e3,a=r*60,o=a*60,s=o*24,c=s*7,l=s*365.25,u=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;n.exports=e=>{let n=u.exec(e);if(!n)throw TypeError(`invalid time period format ("${e}")`);let d=parseFloat(n[1]);switch(n[2].toLowerCase()){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:return Math.round(d*r);case`minute`:case`minutes`:case`min`:case`mins`:case`m`:return Math.round(d*a);case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:return Math.round(d*o);case`day`:case`days`:case`d`:return Math.round(d*s);case`week`:case`weeks`:case`w`:return Math.round(d*c);case`year`:case`years`:case`yr`:case`yrs`:case`y`:return Math.round(d*l)}}}}),require_apply_options=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/apply_options.js"(e,n){var r=require_ms();n.exports=({audience:e,expiresIn:n,iat:a=!0,issuer:o,jti:s,kid:c,notBefore:l,now:u=new Date,subject:d},f)=>{if(!(u instanceof Date)||!u.getTime())throw TypeError(`options.now must be a valid Date object`);let h=u.getTime();if(a!==void 0){if(typeof a!=`boolean`)throw TypeError(`options.iat must be a boolean`);a&&(f.iat=new Date(h))}if(n!==void 0){if(typeof n!=`string`)throw TypeError(`options.expiresIn must be a string`);f.exp=new Date(h+r(n))}if(l!==void 0){if(typeof l!=`string`)throw TypeError(`options.notBefore must be a string`);f.nbf=new Date(h+r(l))}if(e!==void 0){if(typeof e!=`string`)throw TypeError(`options.audience must be a string`);f.aud=e}if(o!==void 0){if(typeof o!=`string`)throw TypeError(`options.issuer must be a string`);f.iss=o}if(d!==void 0){if(typeof d!=`string`)throw TypeError(`options.subject must be a string`);f.sub=d}if(c!==void 0){if(typeof c!=`string`)throw TypeError(`options.kid must be a string`);f.kid=c}if(s!==void 0){if(typeof s!=`string`)throw TypeError(`options.jti must be a string`);f.jti=s}return f}}}),require_check_payload=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/check_payload.js"(e,n){var r=require_apply_options(),a=require_is_object(),o=e=>JSON.parse(JSON.stringify(e));n.exports=(e,n)=>{if(Buffer.isBuffer(e)){if(Object.keys(n).length!==0)throw TypeError(`options cannot contain claims when payload is a Buffer`);return e}if(!a(e))throw TypeError(`payload must be a Buffer or a plain object`);return e=o(e),e=r(n,e),Buffer.from(JSON.stringify(e),`utf-8`)}}}),require_le64=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/le64.js"(e,n){var{PasetoNotSupported:r}=require_errors();n.exports=e=>{if(!Number.isSafeInteger(e))throw new r(`message is too long for Node.js to safely process`);let n=~~(e/4294967295),a=e%4294967295-n,o=Buffer.allocUnsafe(8);return o.writeUInt32LE(n,4),o.writeUInt32LE(a,0),o}}}),require_pae=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/pae.js"(e,n){var r=require_le64();n.exports=(...e)=>{e=e.filter(Boolean);let n=r(e.length);for(let a of e){a=Buffer.from(a,`utf8`);let e=r(Buffer.byteLength(a));n=Buffer.concat([n,e,a])}return n}}}),require_base64url=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/base64url.js"(e,n){n.exports.encode=e=>e.toString(`base64url`),n.exports.decode=e=>Buffer.from(e,`base64`)}}),require_pack=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/pack.js"(e,n){var{encode:r}=require_base64url();n.exports=function(e,n,...a){let o=`${e}${r(Buffer.concat(a))}`;return n.byteLength&&(o+=`.${r(n)}`),o}}}),require_timing_safe_equal=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/timing_safe_equal.js"(e,n){var{timingSafeEqual:r}=require("crypto"),a=(e,n)=>{if(e.length===n)return e;let r=Buffer.alloc(n);return e.copy(r),r};n.exports=(e,n)=>{let o=Math.max(e.length,n.length);return r(a(e,o),a(n,o))}}}),require_crypto_worker=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/crypto_worker.js"(e,n){var r=require("crypto"),a=require("util"),o=require_pae(),s=require_pack(),{PasetoDecryptionFailed:c}=require_errors(),l=require_timing_safe_equal(),{webcrypto:{subtle:u}}=r,d=a.promisify(r.hkdf),f=Buffer.from(`paseto-encryption-key`),h=Buffer.from(`paseto-auth-key-for-aead`),_=Buffer.alloc(0);async function y(e,n,a){let c=`v1.local.`,l=T(e,r.randomBytes(32)).subarray(0,32),u=l.subarray(0,16),[_,y]=await Promise.all([d(`sha384`,a,u,f,32).then(Buffer.from),d(`sha384`,a,u,h,32).then(Buffer.from)]),x=await D(e,_,l.subarray(16));return s(c,n,l,x,T(o(c,l,x,n),y))}async function x(e,n,r){let a=`v1.local.`,s=e.subarray(0,32),u=e.subarray(-48),_=e.subarray(32,-48),y=s.subarray(0,16),[x,C]=await Promise.all([d(`sha384`,r,y,f,32).then(Buffer.from),d(`sha384`,r,y,h,32).then(Buffer.from)]);if(!l(u,T(o(`v1.local.`,s,_,n),C)))throw new c(`decryption failed`);let w=await O(_,x,s.subarray(16));if(!w)throw new c(`decryption failed`);return w}async function C(e,n,a,c){let l=`v3.local.`,u=r.randomBytes(32),[y,x]=await Promise.all([d(`sha384`,a,_,Buffer.concat([f,u]),48).then(Buffer.from),d(`sha384`,a,_,Buffer.concat([h,u]),48).then(Buffer.from)]),C=await D(e,y.subarray(0,32),y.subarray(32));return s(l,n,u,C,T(o(l,u,C,n,c),x))}async function w(e,n,r,a){let s=`v3.local.`,u=e.subarray(0,32),y=e.subarray(-48),x=e.subarray(32,-48),[C,w]=await Promise.all([d(`sha384`,r,_,Buffer.concat([f,u]),48).then(Buffer.from),d(`sha384`,r,_,Buffer.concat([h,u]),48).then(Buffer.from)]),E=C.subarray(0,32),D=C.subarray(32);if(!l(y,T(o(`v3.local.`,u,x,n,a),w)))throw new c(`decryption failed`);let k=await O(x,E,D);if(!k)throw new c(`decryption failed`);return k}var T=(e,n)=>r.createHmac(`sha384`,n).update(e).digest(),E=async(e,n,r,a)=>u[e]({name:`AES-CTR`,counter:a,length:16},await u.importKey(`raw`,r,`AES-CTR`,!1,[e]),n).then(Buffer.from),D=E.bind(void 0,`encrypt`),O=E.bind(void 0,`decrypt`);n.exports={sign:a.promisify(r.sign),verify:a.promisify(r.verify),"v1.local-encrypt":y,"v1.local-decrypt":x,"v3.local-encrypt":C,"v3.local-decrypt":w}}}),require_sign=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/sign.js"(e,n){var{sign:r}=require_crypto_worker(),a=require_pae(),o=require_pack();n.exports=async function(e,n,s,c,l,u,d){return o(e,s,n,await r(c,a(d,e,n,s,u),l))}}}),require_is_key_object=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/is_key_object.js"(e,n){var{KeyObject:r}=require("crypto"),{isKeyObject:a}=require("util/types");a||=e=>e!=null&&e instanceof r,n.exports=a}}),require_sign2=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v1/sign.js"(e,n){var{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:a},createPrivateKey:o}=require("crypto"),s=require_check_footer(),c=require_check_payload(),l=require_sign(),u=require_is_key_object();function d(e){if(typeof e==`string`&&e.startsWith(`k1.secret.`))try{e={key:Buffer.from(e.slice(10),`base64url`),format:`der`,type:`pkcs1`}}catch{}if(!u(e))try{e=o(e)}catch{}if(!u(e))throw TypeError(`invalid key provided`);if(e.type!==`private`||e.asymmetricKeyType!==`rsa`||e.asymmetricKeyDetails.modulusLength!==2048)throw TypeError(`v1.public signing key must be a private RSA key with 2048 bit modulus length`);return e}n.exports=async function(e,n,{footer:o,...u}={}){let f=c(e,u),h=s(o);return n=d(n),l(`v1.public.`,f,h,`sha384`,{key:n,padding:r,saltLength:a})}}}),require_assert_payload=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/assert_payload.js"(e,n){var{PasetoClaimInvalid:r}=require_errors(),a=require_ms();n.exports=({ignoreExp:e,ignoreNbf:n,ignoreIat:o,maxTokenAge:s,subject:c,issuer:l,clockTolerance:u,audience:d,now:f=new Date},h)=>{if(!(f instanceof Date)||!f.getTime())throw TypeError(`options.now must be a valid Date object`);let _=f.getTime();if(`iss`in h&&typeof h.iss!=`string`)throw new r(`payload.iss must be a string`);if(l!==void 0){if(typeof l!=`string`)throw TypeError(`options.issuer must be a string`);if(h.iss!==l)throw new r(`issuer mismatch`)}if(`sub`in h&&typeof h.sub!=`string`)throw new r(`payload.sub must be a string`);if(c!==void 0){if(typeof c!=`string`)throw TypeError(`options.subject must be a string`);if(h.sub!==c)throw new r(`subject mismatch`)}if(`aud`in h&&typeof h.aud!=`string`)throw new r(`payload.aud must be a string`);if(d!==void 0){if(typeof d!=`string`)throw TypeError(`options.audience must be a string`);if(h.aud!==d)throw new r(`audience mismatch`)}if(u!==void 0&&typeof u!=`string`)throw TypeError(`options.clockTolerance must be a string`);let y=u?a(u):0,x;if(`iat`in h){if(typeof h.iat!=`string`)throw new r(`payload.iat must be a string`);if(x=new Date(h.iat).getTime(),!x)throw new r(`payload.iat must be a valid ISO8601 string`);if(!o&&x>_+y)throw new r(`token issued in the future`)}if(`nbf`in h){if(typeof h.nbf!=`string`)throw new r(`payload.nbf must be a string`);let e=new Date(h.nbf).getTime();if(!e)throw new r(`payload.nbf must be a valid ISO8601 string`);if(!n&&e>_+y)throw new r(`token is not active yet`)}if(`exp`in h){if(typeof h.exp!=`string`)throw new r(`payload.exp must be a string`);let n=new Date(h.exp).getTime();if(!n)throw new r(`payload.exp must be a valid ISO8601 string`);if(!e&&n<=_-y)throw new r(`token is expired`)}if(s!==void 0){if(typeof s!=`string`)throw TypeError(`options.maxTokenAge must be a string`);if(!(`iat`in h))throw new r(`missing iat claim`);if(x+a(s)<_+y)throw new r(`maxTokenAge exceeded`)}}}}),require_parse_paseto_payload=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/parse_paseto_payload.js"(e,n){var{PasetoInvalid:r}=require_errors(),{strict:a}=require("assert"),o=require_is_object();n.exports=e=>{try{let n=JSON.parse(e);return a(o(n)),n}catch{throw new r(`All PASETO payloads MUST be a JSON object`)}}}}),require_consume=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/consume.js"(e,n){var r=require("assert"),{PasetoInvalid:a}=require_errors(),o=require_assert_payload(),{decode:s}=require_base64url(),c=require_parse_paseto_payload();function l(e,n){if(typeof n!=`string`)throw TypeError(`token must be a string, got: ${typeof n}`);if(n.slice(0,e.length)!==e)throw new a(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:o,1:c=``,length:l}=n.slice(e.length).split(`.`);try{r(l<=2),o=s(o),c=s(c)}catch{throw new a(`token is not a PASETO formatted value`)}return{raw:o,f:c}}function u(e,n,r,a,s,l,u){if(n){if(Object.keys(r).length!==0)throw TypeError(`options cannot contain claims when options.buffer is true`);return a?{payload:s,footer:l?.length?l:void 0,version:e,purpose:u}:s}let d=c(s);return o(r,d),a?{payload:d,footer:l?.length?l:void 0,version:e,purpose:u}:d}n.exports={post:u,pre:l}}}),require_verify=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/verify.js"(e,n){var{PasetoVerificationFailed:r}=require_errors(),{verify:a}=require_crypto_worker(),o=require_pae(),{pre:s}=require_consume();n.exports=async function(e,n,c,l,u,d,f){let{raw:h,f:_}=s(e,n),y=h.subarray(0,-l),x=h.subarray(-l);if(!await a(c,o(f,e,y,_,d),u,x))throw new r(`invalid signature`);return{m:y,footer:_.length?_:void 0}}}}),require_verify2=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v1/verify.js"(e,n){var{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:a},createPublicKey:o}=require("crypto"),s=require_verify(),c=require_is_key_object(),{post:l}=require_consume();function u(e){if(typeof e==`string`&&e.startsWith(`k1.public.`))try{e={key:Buffer.from(e.slice(10),`base64url`),format:`der`,type:`pkcs1`}}catch{}if(!c(e)||e.type===`private`)try{e=o(e)}catch{}if(!c(e))throw TypeError(`invalid key provided`);if(e.type!==`public`||e.asymmetricKeyType!==`rsa`||e.asymmetricKeyDetails.modulusLength!==2048)throw TypeError(`v1.public verify key must be a public RSA key with 2048 bit modulus length`);return e}n.exports=async function(e,n,{complete:o=!1,buffer:c=!1,...d}={}){n=u(n);let{m:f,footer:h}=await s(`v1.public.`,e,`sha384`,256,{key:n,padding:r,saltLength:a});return l(`v1`,c,d,o,f,h,`public`)}}}),require_symmetric_key_check=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/symmetric_key_check.js"(e,n){var{createSecretKey:r}=require("crypto"),a=require_is_key_object();n.exports=function(e,n){if(typeof n==`string`&&n.startsWith(`k${e.slice(1)}`)&&(n=Buffer.from(n.slice(e.length),`base64url`)),!a(n))try{n=r(n)}catch{}if(!a(n))throw TypeError(`invalid key provided`);if(n.type!==`secret`||n.symmetricKeySize!==32)throw TypeError(`${e} secret key must be 32 bytes long symmetric key`);return n}}}),require_encrypt=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v1/encrypt.js"(e,n){var r=require_check_footer(),a=require_symmetric_key_check().bind(void 0,`v1.local`),o=require_check_payload(),{"v1.local-encrypt":s}=require_crypto_worker();n.exports=async function(e,n,{footer:c,...l}={}){let u=o(e,l);return n=a(n),s(u,r(c),n.export())}}}),require_decrypt=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v1/decrypt.js"(e,n){var{"v1.local-decrypt":r}=require_crypto_worker(),a=require_symmetric_key_check().bind(void 0,`v1.local`),{pre:o,post:s}=require_consume(),c=`v1.local.`;n.exports=async function(e,n,{complete:l=!1,buffer:u=!1,...d}={}){let{raw:f,f:h}=o(c,e);return n=a(n),s(`v1`,u,d,l,await r(f,h,n.export()),h,`local`)}}}),require_key=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v1/key.js"(e,n){var r=require("crypto"),{promisify:a}=require("util"),{PasetoNotSupported:o}=require_errors(),s=a(r.generateKeyPair),c=a(r.generateKey);async function l(e,{format:n=`keyobject`}={}){if(n!==`keyobject`&&n!==`paserk`)throw TypeError(`invalid format`);switch(e){case`local`:{let e=await c(`aes`,{length:256});return n===`paserk`?`k1.local.${e.export().toString(`base64url`)}`:e}case`public`:{let{privateKey:e,publicKey:r}=await s(`rsa`,{modulusLength:2048});return n===`paserk`?{secretKey:`k1.secret.${e.export({format:`der`,type:`pkcs1`}).toString(`base64url`)}`,publicKey:`k1.public.${r.export({format:`der`,type:`pkcs1`}).toString(`base64url`)}`}:e}default:throw new o(`unsupported v1 purpose`)}}n.exports=l}}),require_v1=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v1/index.js"(e,n){n.exports={sign:require_sign2(),verify:require_verify2(),encrypt:require_encrypt(),decrypt:require_decrypt(),generateKey:require_key()}}}),require_key2=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v2/key.js"(e,n){var r=require("assert"),a=require("crypto"),{promisify:o}=require("util"),{PasetoNotSupported:s}=require_errors(),c=require_is_key_object(),l=o(a.generateKeyPair);function u(e,n){if(typeof n==`string`&&n.startsWith(`k${e.slice(1)}.secret.`))try{n=Buffer.from(n.slice(10),`base64url`),r.strictEqual(n.byteLength,64)}catch{}if(Buffer.isBuffer(n))try{n=h(n)}catch{}if(!c(n))try{n=a.createPrivateKey(n)}catch{}if(!c(n))throw TypeError(`invalid key provided`);if(n.type!==`private`||n.asymmetricKeyType!==`ed25519`)throw TypeError(`${e}.public signing key must be a private ed25519 key`);return n}function d(e,n){if(typeof n==`string`&&n.startsWith(`k${e.slice(1)}.public.`))try{n=Buffer.from(n.slice(10),`base64url`),r.strictEqual(n.byteLength,32)}catch{}if(Buffer.isBuffer(n))try{n=h(n)}catch{}if(!c(n)||n.type===`private`)try{n=a.createPublicKey(n)}catch{}if(!c(n))throw TypeError(`invalid key provided`);if(n.type!==`public`||n.asymmetricKeyType!==`ed25519`)throw TypeError(`${e}.public verify key must be a public ed25519 key`);return n}async function f(e,n,{format:r=`keyobject`}={}){if(r!==`keyobject`&&r!==`paserk`)throw TypeError(`invalid format`);switch(n){case`public`:{let{privateKey:n,publicKey:a}=await l(`ed25519`);return r===`paserk`?{secretKey:`k${e.slice(1)}.secret.${x(n).toString(`base64url`)}`,publicKey:`k${e.slice(1)}.public.${x(a).toString(`base64url`)}`}:n}default:throw new s(`unsupported ${e} purpose`)}}function h(e){if(!Buffer.isBuffer(e))throw TypeError(`bytes must be a Buffer`);switch(e.byteLength){case 64:{let n=a.createPrivateKey({key:Buffer.concat([Buffer.from(`302e020100300506032b657004220420`,`hex`),e.subarray(0,32)]),format:`der`,type:`pkcs8`});if(!e.subarray(32).equals(Buffer.from(n.export({format:`jwk`}).x,`base64`)))throw TypeError(`invalid byte sequence`);return n}case 32:return a.createPublicKey({key:Buffer.concat([Buffer.from(`302a300506032b6570032100`,`hex`),e]),format:`der`,type:`spki`});default:throw TypeError(`bytes must be 64 bytes (private key), or 32 bytes (public key)`)}}function _(e,n){if(!c(n))throw TypeError(`keyObject must be a KeyObject instance`);if(n.type===`secret`||n.asymmetricKeyType!==`ed25519`)throw TypeError(`${e}.public key must be an Ed25519 key`);switch(n.type){case`public`:return Buffer.from(n.export({format:`jwk`}).x,`base64`);case`private`:{let{d:e,x:r}=n.export({format:`jwk`});return Buffer.concat([Buffer.from(e,`base64`),Buffer.from(r,`base64`)])}}}async function y(...e){return f(`v2`,...e)}function x(...e){return _(`v2`,...e)}n.exports={_checkPrivateKey:u,_checkPublicKey:d,_generateKey:f,_keyObjectToBytes:_,bytesToKeyObject:h,generateKey:y,keyObjectToBytes:x}}}),require_sign3=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v2/sign.js"(e,n){var r=require_check_footer(),a=require_check_payload(),o=require_sign(),{_checkPrivateKey:s}=require_key2(),c=s.bind(void 0,`v2`);n.exports=async function(e,n,{footer:s,...l}={}){let u=a(e,l);return n=c(n),o(`v2.public.`,u,r(s),void 0,n)}}}),require_verify3=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v2/verify.js"(e,n){var r=require_verify(),{_checkPublicKey:a}=require_key2(),{post:o}=require_consume(),s=a.bind(void 0,`v2`);n.exports=async function(e,n,{complete:a=!1,buffer:c=!1,...l}={}){n=s(n);let{m:u,footer:d}=await r(`v2.public.`,e,void 0,64,n);return o(`v2`,c,l,a,u,d,`public`)}}}),require_v2=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v2/index.js"(e,n){var r=require_sign3(),a=require_verify3(),{generateKey:o,bytesToKeyObject:s,keyObjectToBytes:c}=require_key2();n.exports={sign:r,verify:a,generateKey:o,bytesToKeyObject:s,keyObjectToBytes:c}}}),require_check_assertion=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/check_assertion.js"(e,n){n.exports=function(e){if(e===void 0)return Buffer.from(``);if(Buffer.isBuffer(e))return e;if(typeof e!=`string`)throw TypeError(`options.assertion must be a string, or a Buffer`);return Buffer.from(e,`utf8`)}}}),require_compress_pk=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/help/compress_pk.js"(e,n){n.exports=e=>{let{x:n,y:r}=e.export({format:`jwk`}),a=Buffer.from(r,`base64`),o=2+(a[a.length-1]&1);return Buffer.concat([Buffer.alloc(1,o),Buffer.from(n,`base64`)])}}}),require_key3=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v3/key.js"(e,n){var r=require("crypto"),{promisify:a}=require("util"),{PasetoNotSupported:o}=require_errors(),s=require_is_key_object(),c=require_compress_pk(),l=a(r.generateKeyPair),u=a(r.generateKey);async function d(e,{format:n=`keyobject`}={}){if(n!==`keyobject`&&n!==`paserk`)throw TypeError(`invalid format`);switch(e){case`local`:{let e=await u(`aes`,{length:256});return n===`paserk`?`k3.local.${e.export().toString(`base64url`)}`:e}case`public`:{let{privateKey:e,publicKey:r}=await l(`ec`,{namedCurve:`P-384`});return n===`paserk`?{secretKey:`k3.secret.${h(e).toString(`base64url`)}`,publicKey:`k3.public.${h(r).toString(`base64url`)}`}:e}default:throw new o(`unsupported v3 purpose`)}}function f(e){if(!Buffer.isBuffer(e))throw 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(e[0]!==2&&e[0]!==3)throw TypeError(`invalid compressed public key`);return r.createPublicKey({key:Buffer.concat([Buffer.from(`3046301006072a8648ce3d020106052b81040022033200`,`hex`),e]),format:`der`,type:`spki`});case 97:if(e[0]!==4)throw TypeError(`invalid uncompressed public key`);return r.createPublicKey({key:Buffer.concat([Buffer.from(`3076301006072a8648ce3d020106052b81040022036200`,`hex`),e]),format:`der`,type:`spki`});default:throw TypeError(`bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)`)}}function h(e){if(!s(e))throw TypeError(`keyObject must be a KeyObject instance`);if(e.type===`secret`||e.asymmetricKeyType!==`ec`||e.asymmetricKeyDetails.namedCurve!==`secp384r1`)throw TypeError(`v3.public key must be an EC P-384 key`);switch(e.type){case`public`:return c(e);case`private`:return Buffer.from(e.export({format:`jwk`}).d,`base64`)}}n.exports={generateKey:d,bytesToKeyObject:f,keyObjectToBytes:h}}}),require_sign4=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v3/sign.js"(e,n){var{createPrivateKey:r}=require("crypto"),a=require_check_footer(),o=require_check_payload(),s=require_check_assertion(),c=require_sign(),l=require_is_key_object(),{bytesToKeyObject:u}=require_key3(),d=require_compress_pk();function f(e){if(typeof e==`string`&&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 TypeError(`invalid key provided`);if(e.type!==`private`||e.asymmetricKeyType!==`ec`||e.asymmetricKeyDetails.namedCurve!==`secp384r1`)throw TypeError(`v3.public signing key must be a private EC P-384 key`);return e}n.exports=async function(e,n,{footer:r,assertion:l,...u}={}){let h=o(e,u),_=a(r),y=s(l);return n=f(n),c(`v3.public.`,h,_,`sha384`,{key:n,dsaEncoding:`ieee-p1363`},y,d(n))}}}),require_verify4=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v3/verify.js"(e,n){var{createPublicKey:r}=require("crypto"),a=require_check_assertion(),o=require_verify(),s=require_is_key_object(),{bytesToKeyObject:c}=require_key3(),l=require_compress_pk(),{post:u}=require_consume();function d(e){if(typeof e==`string`&&e.startsWith(`k3.public.`))try{e=Buffer.from(e.slice(10),`base64url`),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=c(e)}catch{}if(!s(e)||e.type===`private`)try{e=r(e)}catch{}if(!s(e))throw TypeError(`invalid key provided`);if(e.type!==`public`||e.asymmetricKeyType!==`ec`||e.asymmetricKeyDetails.namedCurve!==`secp384r1`)throw TypeError(`v3.public verify key must be a public EC P-384 key`);return e}n.exports=async function(e,n,{complete:r=!1,buffer:s=!1,assertion:c,...f}={}){n=d(n);let h=a(c),{m:_,footer:y}=await o(`v3.public.`,e,`sha384`,96,{key:n,dsaEncoding:`ieee-p1363`},h,l(n));return u(`v3`,s,f,r,_,y,`public`)}}}),require_encrypt2=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v3/encrypt.js"(e,n){var r=require_check_footer(),a=require_symmetric_key_check().bind(void 0,`v3.local`),o=require_check_payload(),s=require_check_assertion(),{"v3.local-encrypt":c}=require_crypto_worker();n.exports=async function(e,n,{footer:l,assertion:u,...d}={}){let f=o(e,d);n=a(n);let h=r(l),_=s(u);return c(f,h,n.export(),_)}}}),require_decrypt2=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v3/decrypt.js"(e,n){var{"v3.local-decrypt":r}=require_crypto_worker(),a=require_symmetric_key_check().bind(void 0,`v3.local`),o=require_check_assertion(),{pre:s,post:c}=require_consume(),l=`v3.local.`;n.exports=async function(e,n,{complete:u=!1,buffer:d=!1,assertion:f,...h}={}){let{raw:_,f:y}=s(l,e);n=a(n);let x=o(f);return c(`v3`,d,h,u,await r(_,y,n.export(),x),y,`local`)}}}),require_v3=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v3/index.js"(e,n){var r=require_sign4(),a=require_verify4(),o=require_encrypt2(),s=require_decrypt2(),{generateKey:c,bytesToKeyObject:l,keyObjectToBytes:u}=require_key3();n.exports={sign:r,verify:a,encrypt:o,decrypt:s,generateKey:c,bytesToKeyObject:l,keyObjectToBytes:u}}}),require_key4=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v4/key.js"(e,n){var{_checkPrivateKey:r,_checkPublicKey:a,_generateKey:o,_keyObjectToBytes:s,bytesToKeyObject:c}=require_key2();async function l(...e){return o(`v4`,...e)}function u(...e){return s(`v4`,...e)}n.exports={_checkPrivateKey:r,_checkPublicKey:a,bytesToKeyObject:c,generateKey:l,keyObjectToBytes:u}}}),require_sign5=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v4/sign.js"(e,n){var r=require_check_footer(),a=require_check_payload(),o=require_check_assertion(),s=require_sign(),{_checkPrivateKey:c}=require_key4(),l=c.bind(void 0,`v4`);n.exports=async function(e,n,{footer:c,assertion:u,...d}={}){let f=a(e,d),h=o(u);return n=l(n),s(`v4.public.`,f,r(c),void 0,n,h)}}}),require_verify5=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v4/verify.js"(e,n){var r=require_check_assertion(),a=require_verify(),{_checkPublicKey:o}=require_key4(),{post:s}=require_consume(),c=o.bind(void 0,`v4`);n.exports=async function(e,n,{complete:o=!1,buffer:l=!1,assertion:u,...d}={}){n=c(n);let f=r(u),{m:h,footer:_}=await a(`v4.public.`,e,void 0,64,n,f);return s(`v4`,l,d,o,h,_,`public`)}}}),require_v4=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/v4/index.js"(e,n){var r=require_sign5(),a=require_verify5(),{generateKey:o,bytesToKeyObject:s,keyObjectToBytes:c}=require_key4();n.exports={sign:r,verify:a,generateKey:o,bytesToKeyObject:s,keyObjectToBytes:c}}}),require_decode=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/general/decode.js"(e,n){var{PasetoInvalid:r,PasetoNotSupported:a}=require_errors(),{decode:o}=require_base64url(),s=require_parse_paseto_payload();n.exports=(e,{parse:n=!0}={})=>{if(typeof e!=`string`)throw TypeError(`token must be a string`);let{0:c,1:l,2:u,3:d,length:f}=e.split(`.`);if(f!==3&&f!==4)throw new r(`token is not a PASETO formatted value`);if(c!==`v1`&&c!==`v2`&&c!==`v3`&&c!==`v4`)throw new a(`unsupported PASETO version`);if(l!==`local`&&l!==`public`)throw new a(`unsupported PASETO purpose`);let h={footer:d?o(d):void 0,payload:void 0,version:c,purpose:l};if(l===`local`)return h;let _=c===`v1`?256:c===`v3`?96:64,y;try{y=o(u).subarray(0,-_)}catch{throw new r(`token is not a PASETO formatted value`)}return h.payload=n?s(y):y,h}}}),require_general=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/general/index.js"(e,n){n.exports={decode:require_decode()}}}),require_lib=__commonJS({"../core/node_modules/.pnpm/paseto@3.1.4/node_modules/paseto/lib/index.js"(e,n){var r=require_errors(),a=require_v1(),o=require_v2(),s=require_v3(),c=require_v4(),{decode:l}=require_general();n.exports={decode:l,V1:a,V2:o,V3:s,V4:c,errors:r}}}),import_node_process13=__toESM(require("node:process"));function isFunction(e){return typeof e==`function`}function tot(e){return isFunction(e)?e():e}async function tol(e){return isFunction(e)?e():e}function firstDefinedThunk(e){for(let n of e){let e=n();if(e!=null)return e}}var NoOp=()=>void 0;function copyArrayTo(e,n){for(let r=0;r<e.length;r++)n[r]=e[r];return n.length=e.length,n}function at(e,n){if(e!=null&&(n=Math.trunc(n)||0,n<0&&(n+=e.length),!(n<0||n>=e.length)))return e[n]}function toA(e){return optToA(e)??[]}function optToA(e){return Array.isArray(e)?e:e==null?void 0:isString(e)?[e]:isIterable(e)?Array.from(e):[e]}function flatten(e,n=[]){for(let r of toA(e))if(r!=null)for(let e of toA(r))e!=null&&n.push(e);return n}function isString(e){return typeof e==`string`}function isBuffer(e){return e?.constructor?.name===`Buffer`}function isBMP(e){for(let n=e.length-1;n>=0;n--)if(e.charCodeAt(n)!==e.codePointAt(n))return!1;return!0}var _graphemeSegmenter;function graphemeSegmenter(){if(_graphemeSegmenter===void 0)try{_graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:`grapheme`})}catch{_graphemeSegmenter=null}return _graphemeSegmenter??null}function strslice(e,n,r){if(isBMP(e))return n<0&&(n+=e.length),e.slice(n,r);{let a=graphemeSegmenter();return a==null?[...toS(e)].slice(n,r).join(``):sliceIterable(a.segment(e),n,r).map(e=>e.segment).join(``)}}function charArr(e){let n=graphemeSegmenter();return n==null?[...toS(e)]:[...n.segment(e)].map(e=>e.segment)}function trimRight(e){return toS(e).replace(/\s+$/,``)}function stripPrefix(e,n){let r=toS(e),a=toS(n);return a.length>0&&r.startsWith(a)?r.slice(a.length):r}function stripSuffix(e,n){if(n==null)return e;let r=toS(e),a=toS(n);return a.length>0&&r.endsWith(a)?r.slice(0,-a.length):r}function stripPrefixSuffix(e,{prefix:n,suffix:r}){return stripSuffix(stripPrefix(e,n),r)}function ensurePrefix(e,n){return n==null||n===``?e:(e=toS(e),n=toS(n),e.startsWith(n)?e:n+e)}function ensureSuffix(e,n){return n==null||n===``?e:(e=toS(e),n=toS(n),e.endsWith(n)?e:e+n)}function ellipsize(e,n=80,r=0){if(e==null)return``;n=Math.max(1,round(n)),r=clamp(0,n-1,round(r));let a=charArr(e);return a.length<=n?a.join(``):a.slice(0,n-1-r).join(``)+`…`+(r>0?a.slice(-r).join(``):``)}function newlineRe(){return/\r?\n/g}function trimLastNewline(e){return toS(e).replace(/\r?\n$/,``)}function leftIndexOf(e,n,r){r??=e.length;for(let a=r;a>=0;a--)if(strslice(e,a).startsWith(n))return a;return-1}function wrap(e,n){let r=n?.maxLineLen??80,a=n?.prefix??``;if(Array.isArray(e)||e.includes(`
|
|
25
|
+
`))return flatten(flatten(toA(e).map(e=>toS(e).split(newlineRe()))).map(e=>wrap(e,n)));if(e=ensurePrefix(toS(e),a).trim(),e.length<=r)return[e];let o=leftIndexOf(e,` `,r);if(o>a.length)return[strslice(e,0,o),...wrap(strslice(e,o+1),n)];{let r=e.indexOf(` `,a.length+1);return r>0&&r<e.length-1?[strslice(e,0,r),...wrap(strslice(e,r+1),n)]:[e]}}function replaceAll(e,n,r){return n===``?e:e.split(n).join(r)}function compressWhitespace(...e){return e.join(` `).replace(/\s+/g,` `).trim()}function splitLast(e,n){e=toS(e);let r=e.lastIndexOf(n);return r===-1?e:e.slice(r+n.length)}var baseCollator=new Intl.Collator(void 0,{sensitivity:`base`}),accentCollator=new Intl.Collator(void 0,{sensitivity:`accent`});function equalsIgnoreCase(e,n,{normalize:r=!0}={}){if(e==null||n==null)return!1;let a=toS(e),o=toS(n);return a.length===o.length?a===o||a.toLowerCase()===o.toLowerCase()||(r?baseCollator:accentCollator).compare(r?a.normalize():a,r?o.normalize():o)===0:!1}function firstIgnoreCase(e,n){return isEmpty(e)||blank(n)?void 0:e.find(e=>equalsIgnoreCase(n,e))}function includesIgnoreCase(e,n){return firstIgnoreCase(e,n)!=null}function isNumber(e){return typeof e==`number`&&isFinite(e)}function isInvalidNumber(e){return typeof e==`number`&&(isNaN(e)||!isFinite(e))}var NumeralRE=/^\d+$/;function isDigits(e){return NumeralRE.test(toS(e))}var FloatRegex=/^[+-]?[\d.]+$/;function isNumeric(e){if(isNumber(e)||isBigInt(e))return!0;try{if(isString(e)&&(e=e.trim(),FloatRegex.test(e)))return isFinite(parseFloat(e))}catch{}return!1}function isBigInt(e){return typeof e==`bigint`}function mapFinite(e,n){return isNumber(e)?n(e):void 0}function lt(e,n){return isNumber(e)&&isNumber(n)&&e<n}function lte(e,n){return isNumber(e)&&isNumber(n)&&e<=n}function gt(e,n){return isNumber(e)&&isNumber(n)&&e>n}function gte(e,n){return isNumber(e)&&isNumber(n)&&e>=n}function toFinite(e){return isNumber(e)?e:void 0}function absdiff(e,n){return isNumber(e)&&isNumber(n)?Math.abs(e-n):void 0}function approximates(e,n,r=.95){if(!isNumber(e)||!isNumber(n))return;if(e===n)return!0;if(r>=1)return!1;let a=Math.max(e,n)*(1-r);return within(n-a,n+a,e)}function within(e,n,r){return r==null||!isNumber(r)?!1:([e,n]=sort([e,n]),gte(r,e)&<e(r,n))}function max_(...e){let n;for(let r of e)isNumber(r)&&(n==null||n<r)&&(n=r);if(n==null)throw Error(`no numbers given to max()`);return n}function closeTo(e,n,r){return isNumber(e)&&isNumber(n)?Math.abs(e-n)<=r:!1}function isEquivalentNumber(e,n,r){return r<0||isNumber(e)&&isNumber(n)&&Math.abs(e-n)<=r}function trunc(e){if(!isNumber(e))return;let n=Math.trunc(e);return n===0?Math.abs(n):n}function isToNumber(e){return typeof e?.toNumber==`function`}function toNumber(e,n){if(blank(e)||isInvalidNumber(e)||!0===n.strict&&!isNumeric(e))return n.defaultValue;if(isNumber(e))return n.nton(e);if(isBigInt(e)){if(e>BigInt(2**53-1)||e<BigInt(-(2**53-1)))throw Error(`precision loss for `+e);return n.nton(Number(e))}if(isToNumber(e))return n.nton(e.toNumber());try{let r=n.ston(toS(e).trim());return isNumber(r)?n.nton(r):n.defaultValue}catch{return n.defaultValue}}function toInt(e,n){return toNumber(e,{defaultValue:void 0,nton:trunc,ston:parseInt,...n})}function unchangedNumber(e){return e}function toFloat(e,n){return toNumber(e,{defaultValue:void 0,nton:unchangedNumber,ston:parseFloat,...n})}function toIntWithin(e,n,r){if(!Number.isSafeInteger(e))return;let a=toInt(e);return a!=null&&a>=n&&a<=r?a:void 0}function toGt0(e){return toGt(e,0)}function toGt(e,n){let r=toInt(e);return r!=null&&r>n?r:void 0}function toGt0f(e){return toGtf(e,0)}function toGtf(e,n){let r=toFloat(e);return r!=null&&r>n?r:void 0}function lt0(e){return isNumber(e)&&e<0}function gt0(e){return isNumber(e)&&e>0}function gte0(e){return isNumber(e)&&e>=0}function toGte0(e){return gte0(e)?e:void 0}function mapInt(e,n){let r=toInt(e);return r==null?void 0:n(r)}function mapFloat(e,n){let r=toFloat(e);return r==null?void 0:n(r)}function mapNumeric(e,n){return isNumber(e)?n(e):void 0}function map2Numeric(e,n,r){return mapNumeric(e,e=>mapNumeric(n,n=>r(e,n)))}function mapNumericOr(e,n,r){return isNumber(e)?n(e):r}function round(e){return isNumber(e)?e<0?-Math.round(-e):Math.round(e):0}function roundToDecimalPlaces(e,n){if(e==null)return 0;let r=10**n;return round(e*r)/r}function sigFigs(e,n){if(!isNumber(e)||e===0||n===0)return 0;let r=n-round(Math.ceil(Math.log10(Math.abs(e)))),a=10**Math.abs(r);return r<0?round(e/a)*a:round(e*a)/a}function clamp(e,n,r){if(e>n||!isNumber(e)||!isNumber(n))throw Error(`invalid clamp(${e}, ${n}, ${r})`);return isNumber(r)?r<e?e:r>n?n:r:(e+n)/2}function times(e,n){if(!gt0(e))return[];let r=Math.round(e);return r<=0?[]:[...Array(r)].map((e,r)=>n(r))}function pct(e,n){return clamp(0,100,gt0(n)?round(100*(toGt0(e)??0)/n):0)}function fmtPct(e,n){if(e==null)return;let r=Math.round(e);return n==null||within(0,n,r)?r+`%`:void 0}function roundEven(e){return Math.sign(e)*Math.round(Math.abs(e)/2)*2}function isIterable(e){return e!=null&&typeof e!=`string`&&typeof e[Symbol.iterator]==`function`}function sliceIterable(e,n,r){if(lt0(n))return[...e].slice(n,r);let a=e[Symbol.iterator]();if(gt0(n))for(let e=0;e<n;e++)a.next();let o=[];for(let e=n;!gte0(r)||e<r;e++){let e=a.next();if((e.value!=null||e.done!==!0)&&o.push(e.value),e.done===!0)break}return lt0(r)?o.slice(0,r):o}async function*asyncUniqBy(e,n){let r=new Set;for await(let a of e){let e=n(a);r.has(e)||(r.add(e),yield a)}}function max(e,n){let r,a;for(let o of e){let e=n(o);(a==null||a<e)&&(a=e,r=o)}return r}async function*iterate(e){if(e==null||(e=await e,e==null))return;let n=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():Symbol.iterator in e?e[Symbol.iterator]():e,r;do{r=await n.next();let e=await r.value;e!=null&&r.done!==!0&&(yield e)}while(r?.done!==!0)}async function*chainAsyncIterators(...e){for(let n of e){if(n==null)continue;let e=await n;e!=null&&(yield*iterate(await(isFunction(e)?e():e)))}}async function iterToA(...e){let n=[];for await(let r of chainAsyncIterators(...e))r!=null&&n.push(r);return n}function getOrSet(e,n,r){if(n==null)throw Error(`null key`);if(e.has(n))return e.get(n);{let a=r();return a!=null&&e.set(n,a),a}}function isPrimitive(e){switch(typeof e){case`number`:return isFinite(e);case`string`:case`boolean`:return!0;default:return!1}}function isPrimitiveArray(e){return Array.isArray(e)&&e.every(isPrimitive)}function isComparable(e){return isPrimitive(e)||e instanceof Date||Array.isArray(e)&&e.every(isComparable)}var TypeLevel=[`boolean`,`number`,`bigint`,`symbol`,`string`,`object`,`function`],CmpReverseFlag=`⤹`;function cmp(e,n){if(e===n)return 0;if(e==null)return-1;if(n==null)return 1;let r=typeof e,a=typeof n;if((r===`string`||r===`symbol`)&&(a===`string`||a===`symbol`)){let r=toS(e),a=toS(n),o=r.localeCompare(a);return r[0]===CmpReverseFlag&&a[0]===CmpReverseFlag?-o:o}return Array.isArray(e)&&Array.isArray(n)?cmpArr(e,n):r===a?e>n?1:e<n?-1:0:TypeLevel.indexOf(r)-TypeLevel.indexOf(a)}function lt2(e,n){return cmp(e,n)<0}function gte2(e,n){return cmp(e,n)>=0}function gt2(e,n){return cmp(e,n)>0}function cmpArr(e,n,r=!0){if(isEmpty(e)&&isEmpty(n))return 0;let a=Math.min(e.length,n.length);for(let r=0;r<a;r++){let a=cmp(e[r],n[r]);if(a!==0)return a}return cmp(e.length,n.length)*(r?1:-1)}function sort(e){return sortByInPlace(compact(e),toPrimitive)}function sortByInPlace(e,n){return isSorted(e,n)?e:copyArrayTo(sortBy(e,n),e)}function isSorted(e,n=e=>e){if(e.length<=1)return!0;let r=n(e[0],0);for(let a=0;a<e.length;a++){let o=n(e[a],a);if(o==null||gt2(r,o))return!1;r=o}return!0}function sortBy(e,n){return toA(e).filter(e=>e!=null).map((e,r)=>({item:e,cmp:map(n(e,r),e=>[e,r])})).filter(e=>e.cmp!=null).sort((e,n)=>cmp(e.cmp,n.cmp)).map(e=>e.item)}function leastBy(e,n){let r,a;for(let[o,s]of toA(e).entries()){if(s==null)continue;let e=n(s,o);e!=null&&(a===void 0||cmp(e,a)<0)&&(r=s,a=e)}return r}function least(e){return leastBy(e,e=>e)}function toBoolean(e){if(typeof e==`boolean`)return e;if(e==null)return;if(e===1)return!0;if(e===0)return!1;if(typeof e!=`string`)return;let n=e.toLowerCase().trim();if([`true`,`1`].includes(n))return!0;if([`false`,`0`].includes(n))return!1}function isTrue(e){return toBoolean(e)===!0}function isFalse(e){return toBoolean(e)===!1}function isBoolean(e){return typeof e==`boolean`}function toNotBoolean(e){let n=toBoolean(e);return n==null?void 0:!n}var DISABLED=`disabled`,DisabledSynonyms=[`disable`,DISABLED,`never`,`no`,`none`,`off`];function isDisabled(e){return isFalse(e)||DisabledSynonyms.includes(toS(e).toLowerCase())}function maybeOr(e){let n;for(let r of e){if(r===!0)return!0;r===!1&&(n??=!1)}return n}function maybeAnd(e){let n;for(let r of e){if(r===!1)return!1;r===!0&&(n??=!0)}return n}var promiseExists=typeof Promise==`function`,symbolExists=typeof Symbol<`u`,mapExists=typeof Map<`u`,setExists=typeof Set<`u`,weakMapExists=typeof WeakMap<`u`,weakSetExists=typeof WeakSet<`u`,dataViewExists=typeof DataView<`u`,symbolIteratorExists=symbolExists&&Symbol.iterator!==void 0,symbolToStringTagExists=symbolExists&&Symbol.toStringTag!==void 0,setEntriesExists=setExists&&typeof Set.prototype.entries==`function`,mapEntriesExists=mapExists&&typeof Map.prototype.entries==`function`,setIteratorPrototype=setEntriesExists&&Object.getPrototypeOf(new Set().entries()),mapIteratorPrototype=mapEntriesExists&&Object.getPrototypeOf(new Map().entries()),arrayIteratorExists=symbolIteratorExists&&typeof Array.prototype[Symbol.iterator]==`function`,arrayIteratorPrototype=arrayIteratorExists&&Object.getPrototypeOf([][Symbol.iterator]()),stringIteratorExists=symbolIteratorExists&&typeof String.prototype[Symbol.iterator]==`function`,stringIteratorPrototype=stringIteratorExists&&Object.getPrototypeOf(``[Symbol.iterator]()),toStringLeftSliceLength=8,toStringRightSliceLength=-1;function typeDetect(e){let n=typeof e;if(n!==`object`)return n;if(e===null)return`null`;if(e===globalThis)return`global`;if(Array.isArray(e)&&(symbolToStringTagExists===!1||!(Symbol.toStringTag in e)))return`Array`;if(typeof window==`object`&&window!==null){if(typeof window.location==`object`&&e===window.location)return`Location`;if(typeof window.document==`object`&&e===window.document)return`Document`;if(typeof window.navigator==`object`){if(typeof window.navigator.mimeTypes==`object`&&e===window.navigator.mimeTypes)return`MimeTypeArray`;if(typeof window.navigator.plugins==`object`&&e===window.navigator.plugins)return`PluginArray`}if((typeof window.HTMLElement==`function`||typeof window.HTMLElement==`object`)&&e instanceof window.HTMLElement){if(e.tagName===`BLOCKQUOTE`)return`HTMLQuoteElement`;if(e.tagName===`TD`)return`HTMLTableDataCellElement`;if(e.tagName===`TH`)return`HTMLTableHeaderCellElement`}}let r=symbolToStringTagExists&&e[Symbol.toStringTag];if(typeof r==`string`)return r;let a=Object.getPrototypeOf(e);return a===RegExp.prototype?`RegExp`:a===Date.prototype?`Date`:promiseExists&&a===Promise.prototype?`Promise`:setExists&&a===Set.prototype?`Set`:mapExists&&a===Map.prototype?`Map`:weakSetExists&&a===WeakSet.prototype?`WeakSet`:weakMapExists&&a===WeakMap.prototype?`WeakMap`:dataViewExists&&a===DataView.prototype?`DataView`:mapExists&&a===mapIteratorPrototype?`Map Iterator`:setExists&&a===setIteratorPrototype?`Set Iterator`:arrayIteratorExists&&a===arrayIteratorPrototype?`Array Iterator`:stringIteratorExists&&a===stringIteratorPrototype?`String Iterator`:a===null?`Object`:Object.prototype.toString.call(e).slice(toStringLeftSliceLength,toStringRightSliceLength)}function memoizeCompare(e,n,r){if(r==null||isPrimitive2(e)||isPrimitive2(n))return null;let a=r.get(e)?.get(n);return typeof a==`boolean`?a:null}function memoizeSet(e,n,r,a){if(r==null||isPrimitive2(e)||isPrimitive2(n))return;let o=r.get(e);o==null?(o=new WeakMap,o.set(n,a),r.set(e,o)):o.set(n,a)}function deepEql(e,n,r){return r??={},!1!==r.memoize&&(r.memoize??=new WeakMap),_deepEqual(e,n,r)}function _deepEqual(e,n,r,a){if(r?.comparator!=null)return extensiveDeepEqual(e,n,r,a);let o=simpleEqual(e,n);return o===null?extensiveDeepEqual(e,n,r):o}function simpleEqual(e,n){return e===n?e!==0||1/e==1/n:e!==e&&n!==n?!0:isPrimitive2(e)||isPrimitive2(n)?!1:null}function extensiveDeepEqual(e,n,r,a){r??={};let o=r.memoize===!1?void 0:r.memoize??=new WeakMap,s=r?.comparator,c=memoizeCompare(e,n,o);if(c!==null)return c;let l=memoizeCompare(n,e,o);if(l!==null)return l;if(s){let r=s(e,n,a);if(r===!1||r===!0)return memoizeSet(e,n,o,r),r;let c=simpleEqual(e,n);if(c!==null)return c}let u=typeDetect(e);if(u!==typeDetect(n))return memoizeSet(e,n,o,!1),!1;memoizeSet(e,n,o,!0);let d=extensiveDeepEqualByType(e,n,u,r);return memoizeSet(e,n,o,d),d}function extensiveDeepEqualByType(e,n,r,a){switch(r){case`String`:case`Number`:case`Boolean`:case`Date`:return _deepEqual(e.valueOf(),n.valueOf());case`Promise`:case`Symbol`:case`function`:case`WeakMap`:case`WeakSet`:return e===n;case`Error`:return keysEqual(e,n,[`name`,`message`,`code`],a);case`Arguments`:case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:case`Int16Array`:case`Uint16Array`:case`Int32Array`:case`Uint32Array`:case`Float32Array`:case`Float64Array`:case`Array`:return iterableEqual(e,n,a);case`RegExp`:return regexpEqual(e,n);case`Generator`:return generatorEqual(e,n,a);case`DataView`:return iterableEqual(new Uint8Array(e.buffer),new Uint8Array(n.buffer),a);case`ArrayBuffer`:return iterableEqual(new Uint8Array(e),new Uint8Array(n),a);case`Set`:return entriesEqual(e,n,a);case`Map`:return entriesEqual(e,n,a);case`Temporal.PlainDate`:case`Temporal.PlainTime`:case`Temporal.PlainDateTime`:case`Temporal.Instant`:case`Temporal.ZonedDateTime`:case`Temporal.PlainYearMonth`:case`Temporal.PlainMonthDay`:return e.equals(n);case`Temporal.Duration`:return e.total(`nanoseconds`)===n.total(`nanoseconds`);case`Temporal.TimeZone`:case`Temporal.Calendar`:return e.toString()===n.toString();default:return objectEqual(e,n,a)}}function regexpEqual(e,n){return e.toString()===n.toString()}function entriesEqual(e,n,r){if(e.size!==n.size)return!1;if(e.size===0)return!0;let a=[],o=[];return e.forEach(function(e,n){a.push([e,n])}),n.forEach(function(e,n){o.push([e,n])}),iterableEqual(a.sort(),o.sort(),r)}function iterableEqual(e,n,r){let a=e.length;if(a!==n.length)return!1;if(a===0)return!0;let o=-1;for(;++o<a;)if(_deepEqual(e[o],n[o],r)===!1)return!1;return!0}function generatorEqual(e,n,r){return iterableEqual(getGeneratorEntries(e),getGeneratorEntries(n),r)}function hasIteratorFunction(e){return typeof Symbol<`u`&&typeof e==`object`&&Symbol.iterator!==void 0&&typeof e[Symbol.iterator]==`function`}function getIteratorEntries(e){if(hasIteratorFunction(e))try{return getGeneratorEntries(e[Symbol.iterator]())}catch{return[]}return[]}function getGeneratorEntries(e){let n=e.next(),r=[n.value];for(;n.done===!1;)n=e.next(),r.push(n.value);return r}function getEnumerableKeys(e){let n=[];for(let r in e)e[r]!==void 0&&n.push(r);return n}function getEnumerableSymbols(e){let n=[],r=Object.getOwnPropertySymbols(e);for(let a=0;a<r.length;a+=1){let o=r[a];Object.getOwnPropertyDescriptor(e,o)?.enumerable===!0&&n.push(o)}return n}function keysEqual(e,n,r,a){let o=r.length;if(o===0)return!0;for(let s=0;s<o;s+=1){let o=r[s],c=e[o],l=n[o];if(typeof c==`function`&&typeof l==`function`){if(c.toString()!==l.toString())return!1}else if(_deepEqual(c,l,a,o)===!1)return!1}return!0}function objectEqual(e,n,r){if(typeof e.eql==`function`){let r=e.eql(n);if(isBoolean(r))return r}if(typeof n.eql==`function`){let r=n.eql(e);if(isBoolean(r))return r}if(typeof e.toJSON==`function`)return objectEqual(e.toJSON(),n,r);if(typeof n.toJSON==`function`)return objectEqual(e,n.toJSON(),r);if(typeof e==`object`&&typeof n==`object`&&typeof e.constructor==`function`&&typeof n.constructor==`function`&&!1===objectEqual(e.constructor,n.constructor,r))return!1;let a=[...getEnumerableKeys(e),...getEnumerableSymbols(e)],o=[...getEnumerableKeys(n),...getEnumerableSymbols(n)];if(a.length&&a.length===o.length)return iterableEqual(mapSymbols(a).sort(),mapSymbols(o).sort())!==!1&&keysEqual(e,n,a,r);let s=getIteratorEntries(e),c=getIteratorEntries(n);return s.length&&s.length===c.length?(s.sort(),c.sort(),iterableEqual(s,c,r)):a.length===0&&s.length===0&&o.length===0&&c.length===0}function isPrimitive2(e){return typeof e!=`object`||!e}function mapSymbols(e){return e.map(function(e){return typeof e==`symbol`?e.toString():e})}function splitFirst(e,n){let r=e.indexOf(n);return r===-1?[e]:[e.slice(0,r),e.slice(r+n.length)]}function isObject(e){return typeof e==`object`&&!!e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tap(e,n){return n==null?typeof e==`string`?console.log(e):console.dir(e,{depth:null}):n(e),e}function keys(e){return isObject(e)?Object.keys(e).filter(n=>typeof n==`string`&&[void 0,!0].includes(e.propertyIsEnumerable?.(n))):[]}function keysWithDefinedOrNullValues(e){return e==null?[]:keys(e).filter(n=>e[n]!==void 0)}function*propertyNames(e){if(e!=null)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(yield n)}function isEmptyObj(e){if(typeof e!=`object`||!e)return!0;for(let n in e)if(e[n]!==void 0)return!1;return!0}function notEmptyObj(e){return!isEmptyObj(e)}function toCompactObj(e){let n=compactValues(e);return isEmptyObj(n)?void 0:n}function mapCompactObj(e,n){let r=compactValues(e);return notEmptyObj(r)?n(r):void 0}function values(e){return keys(e).map(n=>e[n])}function entries(e){return e==null?[]:Object.entries?.(e)??keys(e??{}).map(n=>[n,e[n]])}function fromEntries(e,n){if(e==null)return n;for(let r of e)if(r!=null&&Array.isArray(r)){let[e,a]=r;e!=null&&a!==void 0&&(typeof n!=`object`&&(n={}),n[e]=a)}return n}function assignFields(e,n,r){let a=r?.assignNullish??!1;if(!isObject(n))return e;if(!0===r?.deleteExtraFields&&isRecord(e))for(let r of Object.keys(e))(!(r in n)||!a&&n[r]==null)&&delete e[r];for(let[o,s]of entries(n))r?.omitKeys?.includes(o)!==!0&&(s!=null||a)&&(e[o]=s);return e}function assignUndefinedFields(e,n,...r){if(n==null)return e;for(let a of r){let r=n[a];r!==void 0&&e[a]===void 0&&(e[a]=r)}return e}function compactValues(e){if(e==null)return;let n=entries(e);if(n.every(([,e])=>e!=null))return e;let r=n.filter(([,e])=>e!=null);return isEmpty(r)?void 0:fromEntries(r)}function compactBlankValues(e){if(e==null)return;let n=entries(e).filter(([e,n])=>e!=null&¬Blank(n));return isEmpty(n)?void 0:fromEntries(n)}function mergeObjectsDeep(...e){let n=compact(e);if(n.length===0)return;if(n.length===1)return n[0];let r=n.filter(isObject);if(n.length!==r.length)return n;let a={};for(let e of uniq(flatMap(r,keys)))a[e]=mergeObjectsDeep(...r.map(n=>n[e]));return a}function pick(e,...n){if(!isObject(e))return e;let r={};for(let a of n)e[a]!==void 0&&(r[a]=e[a]);return r}function pickRequired(e,...n){if(!isObject(e))return;let r={};for(let a of n){if(e[a]==null)return;r[a]=e[a]}return r}function pickDeep(e,...n){if(!isObject(e))return e;if(Array.isArray(e))return e.map(e=>pickDeep(e,...n));let r={};function a(e,n){if(n==null)return;let a=r[e];r[e]=a==null?n:mergeObjectsDeep(a,n)}for(let r of n){let[n,o]=splitFirst(r,`.`);if(n.includes(`*`)){let r=n.replace(/[.+?^${}()|[\]\\]/g,`\\$&`),s=RegExp(`^`+r.replace(/\*/g,`.*`)+`$`,`i`);for(let n of keys(e))if(s.test(n)){let r=e[n];r!=null&&a(n,blank(o)?r:pickDeep(r,o))}}else{let r=pluck(e,n);r?.value!=null&&a(r.key,blank(o)?r.value:pickDeep(r.value,o))}}for(let r of keys(e))(toInt(r)??-1)>=0&&a(r,pickDeep(e[r],...n));return r}function pluck(e,n){if(!isObject(e)||blank(n))return;if(n in e)return{key:n,value:e[n]};let r=RegExp(`^`+n.replace(/\*/g,`.*`)+`$`,`i`);for(let n of keys(e))if(r.test(n))return{key:n,value:e[n]}}function pluckDeep(e,n){if(e==null||blank(n))return;if(Array.isArray(e)){let r=compact(e.map(e=>pluckDeep(e,n)));return isEmpty(r)?void 0:{key:r[0].key,value:flatMap(r,e=>e.value)}}let[r,a]=splitFirst(n,`.`),o=pluck(e,r);if(o==null)return;if(blank(a))return o;let s=pluckDeep(o.value,a);return s==null?void 0:{key:o.key+`.`+s.key,value:s.value}}function omit(e,...n){return e==null?e:fromEntries(entries(e).filter(([e])=>!n.includes(e)))}function isReqValued(e){return values(e).every(e=>e!=null)}function toReqValued(e){return isReqValued(e)?e:void 0}function reqValuedOrElse(e){return isReqValued(e)?e:void 0}function filter(e,n){return e==null?e:fromEntries(entries(e).filter(([e,r])=>n(e,r)))}function maybeCall(e,n,...r){let a=e?.[n];return isFunction(a)?a.bind(e)(...r):void 0}function eql(e,n){return deepEql(e,n,{comparator})}function findEql(e,n){for(let r of e)if(eql(n,r))return r}function eqlSubset(e,n){if(e==null||n==null||isPrimitive(e)||isPrimitive(n))return e===n;if(!isObject(e)||!isObject(n))return!1;for(let r of keys(e))if(!eql(e[r],n[r]))return!1;return!0}function dateComparator(e,n){if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime()}function objComparator(e,n){if(isObject(e)&&isFunction(e.$eql)){let r=e.$eql(n);if(isBoolean(r))return r}if(isObject(n)&&isFunction(n.$eql)){let r=n.$eql(e);if(isBoolean(r))return r}}function functionComparator(e,n){return isFunction(e)&&isFunction(n)?e.toString()===n.toString():void 0}function weakRefComparator(e,n){return isObject(e)&&isObject(n)&&e.constructor?.name===`WeakRef`&&n.constructor?.name===`WeakRef`?e.deref()===n.deref():void 0}var objComparators=[objComparator,dateComparator,functionComparator,weakRefComparator],fieldComparators=new Map;function comparator(e,n,r){if(e==null||n==null)return e===n;if(r!=null){let a=fieldComparators.get(r)?.(e,n);if(a!=null)return a}for(let r of objComparators){let a=r(e,n);if(a!=null)return a}return null}function rndInt(e,n){return Math.floor(Math.random()*(n-e))+e}function randomInt(e,n,r){return r==null||r.length===0?rndInt(e,n):randomInts(e,n,1,r)[0]}function randomInts(e,n,r,a){if(e=Math.ceil(e),n=Math.floor(n),n<e)throw Error(`randomInts(): invalid range: ${e} > ${n}`);let o=n-e,s=new Set(a??[]);if(n===e&&o===0&&s.size===0&&r===1)return[e];let c=o-s.size;if(r>c)throw Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:n,min:e,range:o,size:r,slotsRemaining:c})}`);let l=new Set;for(;l.size<r;){let r=rndInt(e,n);s.has(r)||l.add(r)}return[...l]}function randomFloat(e,n){return Math.random()*(n-e)+e}var NumericChars=`0123456789`,LowercaseChars=`abcdefghijkmnopqrstuvwxyz`,RandomChars=NumericChars+LowercaseChars;function randomChars(e,n=RandomChars){let r=[];for(let a=0;a<e;a++)r.push(n[rndInt(0,n.length)]);return r.join(``)}function isNotEmpty(e){return e!=null&&toA(e).length>0}function toNotEmpty(e){return isNotEmpty(e)?e:void 0}function isEmpty(e){return e==null||toA(e).length===0}function mapNotEmpty(e,n){return isNotEmpty(e)?n(e):void 0}function toPrimitive(e){return isPrimitive(e)||isPrimitiveArray(e)?e:e.valueOf()}function eqlPrimitiveArray(e,n){return e!=null&&n!=null&&e.length===n.length&&e.every((e,r)=>e===n[r])}function startsWith(e,n){return eqlPrimitiveArray(e.slice(0,n.length),n)}function filterInPlace(e,n,r=!1){for(let a=0;a<e.length;)if(n(e[a],a,e))a++;else if(e.splice(a,1),r)break;return e}async function filterInPlaceAsync(e,n){for(let r=0;r<e.length;)!0===await n(e[r],r,e)?r++:e.splice(r,1);return e}function flatMap(e,n){let r=[];for(let a of e)r.push(...compact(n(a)));return r}function includes(e,n){if(e==null)return!1;for(let r of e)if(n.valueOf()===r.valueOf())return!0;return!1}function includesAny(e,n){return isNotEmpty(e)&&isNotEmpty(n)&&e.some(e=>n.includes(e))}function pushNotSame(e,...n){for(let r of n)r!=null&&!e.includes(r)&&e.push(r);return e}function pushUniq(e,...n){for(let r of n)r!=null&&findEql(e,r)==null&&e.push(r);return e}function remove(e,...n){let r=e.length;return filterInPlace(e,e=>n.every(n=>!eql(e,n))),r!==e.length}function removeSame(e,...n){let r=e.length;return filterInPlace(e,e=>n.every(n=>e!==n)),r!==e.length}function compact(e){return e==null?[]:filterInPlace(toA(e),e=>e!=null)}function compactBlanks(e){return e==null?[]:toA(e).map(e=>toS(e).trim()).filter(e=>e.length>0)}function compactBlankish(e){return e==null?[]:[...e].filter(notBlankish)}function uniq(...e){if(e==null)return[];let n=[];for(let r of e)if(r!=null)for(let e of r)e!=null&&n.push(e);return uniqBy(n,e=>isPrimitive(e)?e:stringify(e))}function uniqSubstrings(e){if(e==null)return[];let n=compact(e);if(e.length===0)return[];let r=[];for(let e of sortBy(n,e=>[-e.length,e.toLowerCase()]))r.some(n=>n.includes(e))||r.push(e);return sortBy(r,e=>n.indexOf(e))}function uniqBy(e,n=e=>stringify(e)){let r=new Map;for(let a of e)if(a!=null){let e=n(a);e!=null&&getOrSet(r,e,()=>a)}return[...r.values()]}function uniqBy2(e,n){let r=[];for(let a of e)a!=null&&r.every(e=>!n(a,e))&&r.push(a);return r}function count(e,n){let r=0;for(let a of e)n(a)&&r++;return r}function sum(e,n){let r=0;for(let a=0;a<e.length;a++)r+=n(e[a],a);return r}function range(e,n,r=e=>e){return stepRange(e,n,1,r)}function stepRange(e,n,r=1,a=e=>e){let o=[];if(e<n)for(let s=e;s<n;s+=r)o.push(a(s));else for(let s=e;s>n;s-=r)o.push(a(s));return o}var primitiveValueOfOrElse=e=>{if(isPrimitive(e))return e;if(Array.isArray(e))return stringify(e);if(isFunction(e.valueOf))return e.valueOf();throw Error(`Cannot get primitive value for `+JSON.stringify(e))};function diff(e,n,r=primitiveValueOfOrElse){let a=new Set(n.map(r));return e.filter(e=>!a.has(r(e)))}function last(e){return e?.[e.length-1]}function arrayEndsWith(e,n){if(e.length<n.length)return!1;for(let r=0;r<n.length;r++)if(e[e.length-n.length+r]!==n[r])return!1;return!0}function findIndexes(e,n){let r=[];for(let a=0;a<e.length;a++)n(e[a],a)&&r.push(a);return r}var MultiMap=class e{store;static fromJSON(n){let r=new e;for(let[e,a]of Object.entries(n))r.add(e,...a);return r}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,n){return this.store.get(e)?.includes(n)===!0}keyCount(){return this.store.size}isEmpty(){for(let e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return sum([...this.store.values()].map(e=>e.length),e=>e)}add(e,...n){let r=getOrSet(this.store,e,()=>[]);return r.push(...n),r}addUniq(e,...n){return pushUniq(getOrSet(this.store,e,()=>[]),...n)}set(e,n){this.store.set(e,n)}delete(e,n){if(n==null)return this.store.delete(e);{let r=this.store.get(e);if(r==null)return!1;{let a=r.filter(e=>!eql(e,n));return a.length===0?this.store.delete(e):this.store.set(e,a),r.length!==a.length}}}clear(){return this.store.clear(),this}*keys(){for(let[e,n]of this.store.entries())n.length>0&&(yield e)}*values(){for(let e of this.store.values())e.length>0&&(yield e)}vacuum(e=(e,n)=>uniq(n)){for(let n of this.keys()){let r=this.store.get(n),a=r==null?[]:e(n,r);isEmpty(a)?this.store.delete(n):this.store.set(n,a)}}*valuesFlat(){for(let e of this.store.values())for(let n of e)yield n}entriesArray(){return[...this.store.entries()].filter(([,e])=>isNotEmpty(e))}*entries(){for(let[e,n]of this.store.entries())n.length>0&&(yield[e,n])}*tuples(){for(let[e,n]of this.store.entries())for(let r of toA(n))r!=null&&(yield[e,r])}filterInPlace(e){let n=!1;for(let[r,a]of this.store.entries()){let o=findIndexes(a,n=>!e(r,n,a));if(o.length>0){n=!0;for(let e of o.reverse())a.splice(e,1)}a.length===0&&this.store.delete(r)}return n}filterKeysInPlace(e){let n=!1;for(let[r,a]of this.store.entries())e(r,a)||(n=!0,this.store.delete(r));return n}inverse(){let n=new e;for(let[e,r]of this.store.entries())for(let a of r)n.add(a,e);return n}findKeyByTuple(e){for(let[n,r]of this.tuples())if(e(n,r))return n}filterKeysByTuple(e){let n=[];for(let[r,a]of this.entries())a.some(n=>e(r,n))&&n.push(r);return n}toJSON(){let e={};for(let[n,r]of this.entries())e[isString(n)?n:stringify(n)]=r;return e}};function groupBy(e,n){let r=new MultiMap;return e.forEach(e=>map(n(e),n=>r.add(n,e))),r}function toJsonObject(e){return new Decycler().apply(e)}function stringify(e,n){return JSON.stringify(toJsonObject(e),void 0,n)}function stringifyPretty(e,n=2){return stringify(e,n)}function fromJsonObject(e){return e==null?e:new Reviver().apply(e)}function parseJSON_(e){return fromJsonObject(JSON.parse(e.toString().trim()))}function parseJSON(e){try{return e==null||blank(e)?void 0:parseJSON_(e)}catch{return}}var JsonRevivableClasses=class{static#e=new Map;static#t=new WeakMap;static add(e,n,r=n){this.#e.set(e,r),this.#t.set(n,e)}static getClass(e){return blank(e)?void 0:this.#e.get(e)}static getId(e){return this.#t.get(e?.constructor)}static isRevivable(e){return Array.isArray(e)||e instanceof Map||e instanceof Set||this.getId(e)!=null}static addDefaults(){this.add(`Date`,Date,{toJSON(e){return{ts:e.getTime()}},fromJSON(e){return mapInt(e?.ts,e=>new Date(e))}}),this.add(`RegExp`,RegExp,{toJSON(e){return{source:e.source,flags:e.flags}},fromJSON(e){return new RegExp(e.source,e.flags)}}),this.add(`Error`,Error,{toJSON(e){return pick(e,`message`,`stack`,`code`,`errno`)},fromJSON(e){let n=Error(e.message);return n.stack=e.stack,n.code=e.code,n.errno=e.errno,n}}),this.add(`BigInt`,BigInt,{toJSON(e){return{n:e.toString()}},fromJSON(e){return BigInt(e.n)}})}};JsonRevivableClasses.addDefaults();var OBJECT_ID=`_id`,REFERENCE_ID=`_ref`,CTOR=`_ctor`,ARRAY_ID=`_id[]`,DecycleTypes=[`object`,`bigint`];function canDecycle(e){return e!=null&&DecycleTypes.includes(typeof e)}var Decycler=class{idCount=0;maxIdObjs=new Set;objects=new Map;idAdders=new MultiMap;usedRefIds=new Set;apply(e){this.findMaxId(e),this.maxIdObjs.clear();let n=this._decycle(e);return this.finalize(),this.objects.clear(),this.idAdders.clear(),this.usedRefIds.clear(),n}maybeIncrIdCount(e){gt(e,this.idCount)&&(this.idCount=e+1)}findMaxId(e){if(canDecycle(e)&&!this.maxIdObjs.has(e)){if(this.maxIdObjs.add(e),Array.isArray(e)){let n=0;for(e.length>0&&isObject(e[n])&&(ARRAY_ID in e[n])&&(this.maybeIncrIdCount(e[n]?.[ARRAY_ID]),n++);n<e.length;n++)this.findMaxId(e[n])}else if(isObject(e)){this.maybeIncrIdCount(e[OBJECT_ID]);for(let n of propertyNames(e))this.findMaxId(e[n])}}}getId(e){if(Array.isArray(e))return toGt0(e[0]?.[ARRAY_ID]);if(isObject(e))return toGt0(e[OBJECT_ID])}_decycle(e){if(!canDecycle(e))return e;let n=this.objects.get(e);if(n!=null)return this.usedRefIds.add(n),fromEntries([[REFERENCE_ID,n]]);let r=this.getId(e),a=r??++this.idCount;if(this.objects.set(e,a),Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n[r]=this._decycle(e[r]);return r??this.idAdders.add(a,()=>n.unshift(fromEntries([[ARRAY_ID,a]]))),n}let o={};this.objects.set(o,a);let s=JsonRevivableClasses.getId(e)??e.constructor?.name;if(e.constructor!==Object&&(o[CTOR]=s),r??this.idAdders.add(a,()=>o[OBJECT_ID]=a),e instanceof Map)o._=[...e.entries()].map(([e,n])=>[this._decycle(e),this._decycle(n)]);else if(e instanceof Set)o._=[...e.values()].map(e=>this._decycle(e));else{let n=JsonRevivableClasses.getClass(s)?.toJSON?.(e)??e.toJSON?.()??e;for(let e of propertyNames(n))o[e]=this._decycle(n[e])}return o}finalize(){for(let e of this.usedRefIds)for(let n of this.idAdders.get(e)??[])n()}},Reviver=class{objectsById=new Map;later=new MultiMap;apply(e){let n=this.vivify(e);return this.resolveDeferredReferences(),n}getRefId(e){return isObject(e)?toGt0(e[REFERENCE_ID]):void 0}ifRefIdResolved(e,n){let r=this.getRefId(e);return r!=null&&(this.objectsById.has(r)?n(this.objectsById.get(r)):this.later.add(r,()=>n(this.objectsById.get(r))),!0)}vivify(e){if(!canDecycle(e))return e;if(this.getRefId(e)!=null)throw Error(`Reference ID found in root object`);if(Array.isArray(e)){let n=[],r;e.length>0&&isObject(e[0])&&ARRAY_ID in e[0]&&(r=e.shift()[ARRAY_ID],this.objectsById.set(r,n));for(let r=0;r<e.length;r++)this.ifRefIdResolved(e[r],e=>n[r]=e)||(n[r]=this.vivify(e[r]));return n}let n=e[OBJECT_ID],r=e[CTOR],a=JsonRevivableClasses.getClass(r),o=typeof a?.fromJSON==`function`,s;if(s=r===`Map`?new Map:r===`Set`?new Set:{},gt0(n)&&!o&&this.objectsById.set(n,s),s instanceof Map)for(let[n,r]of e._){let e=this.vivify(n);this.ifRefIdResolved(r,n=>s.set(e,n))||s.set(e,this.vivify(r))}else if(s instanceof Set)for(let n of e._)this.ifRefIdResolved(n,e=>s.add(e))||s.add(this.vivify(n));else if(!(s instanceof Date)&&!(s instanceof RegExp))for(let n of Object.keys(e))n!==OBJECT_ID&&n!==CTOR&&(this.ifRefIdResolved(e[n],e=>s[n]=e)||(s[n]=this.vivify(e[n])));return o&&(s=a.fromJSON(s),gt0(n)&&this.objectsById.set(n,s)),s}resolveDeferredReferences(){let e=this.later.keyCount();for(let n=0;n<e;n++)for(let e of this.later.keys())if(this.objectsById.has(e)){let n=this.later.get(e);if(n!=null){this.later.delete(e);for(let e of n)e()}}}};function toS(e){return toStr(e,`,`)}var DefaultToString={}.toString;function toStr(e,n=`,`){if(e==null)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=>toStr(e,n)).join(n):e.toString===DefaultToString?stringify(e):e.toString()}}function map(e,n){return e==null?void 0:n(e)}function map2(e,n,r){return e==null||n==null?void 0:r(e,n)}function orElse(e,n){return e??tot(n)}function mapOr(e,n,r){return e==null?tot(r):n(e)}function map2Or(e,n,r,a){return orElse(map2(e,n,r),a)}function denull(e){return e==null||toS(e)===`null`?void 0:e}function blank(e){return e==null||typeof e==`string`&&e.trim().length===0}function notBlank(e){return!blank(e)}function notBlankToS(e){return notBlank(e)&&e!==`undefined`?toS(e).trim():void 0}function toNotBlank(e){if(e==null)return;let n=toS(e);return n.length===0||n.trim().length===0?void 0:n}function notBlankOr(e,n){if(e==null)return tot(n);let r=toS(e).trim();return r.length>0?r:tot(n)}function mapNotBlank(e,n){if(e===!1||e==null||e===``)return;let r=toS(e);return notBlank(r)?n(r):void 0}function mapNotBlankOr(e,n,r){return orElse(mapNotBlank(e,n),r)}function firstNotBlank(...e){for(let n of e)if(typeof n==`string`&&n.trim().length>0)return n}var BlankishRE=/^\s*(?:(?:null|undefined)\s*)?$/i;function blankish(e){return e==null||BlankishRE.test(toS(e))}function notBlankish(e){return!blankish(e)}function isError(e){return e!=null&&e instanceof Error}function toError(e){return e==null?void 0:isError(e)?e:Error(String(e))}var deferredComputations=new WeakSet;function defer(e){let n,r,a=!1,o=function(){if(a){if(r!=null)throw r;return n}try{return a=!0,n=e()}catch(e){throw r=toError(e),r}};return o.prior=()=>n,o.hasPrior=()=>a,o.applied=()=>a,o.reset=()=>{let e=n;return n=void 0,r=void 0,a=!1,e},deferredComputations.add(o),o}var import_node_process=require("node:process");function noColor(){return toNotBoolean(import_node_process.env.PS_LOG_COLOR)??(!blank(import_node_process.env.NO_COLOR)||[`dumb`,`unknown`].includes(import_node_process.env.TERM))}var colorEnabled=!noColor();function setColorEnabled(e){colorEnabled=e??!noColor()}function isColorEnabled(){return colorEnabled}function withAsciiEscape(e,n){return function(r){return isColorEnabled()?`\x1B[${e}m${r}\x1B[${n}m`:r}}var reset=withAsciiEscape(0,0),bold=withAsciiEscape(1,22),dim=withAsciiEscape(2,22),italic=withAsciiEscape(3,23),underline=withAsciiEscape(4,24),overline=withAsciiEscape(53,55),inverse=withAsciiEscape(7,27),hidden=withAsciiEscape(8,28),strikethrough=withAsciiEscape(9,29),black=withAsciiEscape(30,39),red=withAsciiEscape(31,39),green=withAsciiEscape(32,39),yellow=withAsciiEscape(33,39),blue=withAsciiEscape(34,39),magenta=withAsciiEscape(35,39),cyan=withAsciiEscape(36,39),orange=withAsciiEscape(`38;5;208`,39),lightGrey=withAsciiEscape(37,39),darkGrey=withAsciiEscape(90,39),redBright=withAsciiEscape(91,39),greenBright=withAsciiEscape(92,39),yellowBright=withAsciiEscape(93,39),blueBright=withAsciiEscape(94,39),magentaBright=withAsciiEscape(95,39),cyanBright=withAsciiEscape(96,39),white=withAsciiEscape(97,39),bgBlack=withAsciiEscape(40,49),bgRed=withAsciiEscape(41,49),bgGreen=withAsciiEscape(42,49),bgYellow=withAsciiEscape(43,49),bgBlue=withAsciiEscape(44,49),bgMagenta=withAsciiEscape(45,49),bgCyan=withAsciiEscape(46,49),bgLightGrey=withAsciiEscape(47,49),bgDarkGrey=withAsciiEscape(100,49),bgRedBright=withAsciiEscape(101,49),bgGreenBright=withAsciiEscape(102,49),bgYellowBright=withAsciiEscape(103,49),bgBlueBright=withAsciiEscape(104,49),bgMagentaBright=withAsciiEscape(105,49),bgCyanBright=withAsciiEscape(106,49),bgWhite=withAsciiEscape(107,49),import_node_util3=require("node:util"),import_node_path=require("node:path"),import_node_process4=__toESM(require("node:process")),import_node_util=require("node:util"),import_node_timers=require("node:timers"),MaxSetTimeoutMs=2**31-1;function setUnrefTimeout(e,n,...r){return(0,import_node_timers.setTimeout)(e,Math.round(n),...r).unref()}function setUnrefInterval(e,n,...r){return(0,import_node_timers.setInterval)(e,Math.round(n),...r).unref()}var MaxChunkMs=36e5;function setLongTimeout(e,n,r=Date.now){let a=r()+n,o,s=()=>{let n=a-r();o=setUnrefTimeout(()=>{o=void 0,r()>=a?e():s()},Math.max(0,Math.min(n,MaxChunkMs)))};return s(),{clear:()=>{o!=null&&(0,import_node_timers.clearTimeout)(o),o=void 0}}}var ExtensibleFunction=class extends Function{_self;constructor(){super(`...args`,`return this._self._call(...args)`);let e=this.bind(this);return this._self=e,e}},pads={};function padding(e,n){if(n<1)return``;if(!gte(pads[e]?.length,n)){let r=pads[e]??e;for(;r.length<n;)r+=e;pads[e]=r}return pads[e].substring(0,n)}function leftPad(e,n,r){if(r.length===0)throw Error(`leftPad() given empty pad`);if(lt(e,0))return`-`+leftPad(String(Math.abs(e)),n-1,r);let a=toS(e);return padding(r,n-a.length)+a}function padNumeric(e,n){return leftPad(isNumber(e)?round(e):`0`,n,`0`)}function pad2(e){return padNumeric(e,2)}function pad3(e){return padNumeric(e,3)}var irregular=new Map([[`child`,`children`],[`photo`,`photos`],[`video`,`videos`]]),es=/([sxz]|ss|sh|ch)$/,consonant_y=/[^aeiou]y$/,vowel_y=/[aeiou]y$/,is=/is$/;function pluralize(e){return blank(e)?e:irregular.get(e)??(e.match(es)==null?e.match(consonant_y)==null?e.match(vowel_y)==null?e.endsWith(`o`)?e+`es`:e.match(is)==null?e+`s`:e.replace(is,`es`):e+`s`:e.replace(/y$/i,`ies`):e+`es`)}function strEnum(...e){let n=Object.freeze([...new Set(e)]),r=new Map(n.map(e=>[e.toLowerCase(),e])),a=new Map(n.map((e,n)=>[e,n])),o={};for(let e of n)o[e]=e;let s=e=>typeof e==`string`?r.get(e.toLowerCase()):void 0,c=e=>e==null?void 0:a.get(e),l=e=>c(e)!=null,u=e=>e==null?void 0:l(e)?e:s(e);return{...o,values:n,length:n.length,has:l,includes:l,getCI:s,pick:(...e)=>n.filter(n=>e.includes(n)),omit:(...e)=>n.filter(n=>!e.includes(n)),indexOf:c,ordinal:e=>c(e)??n.length,toValid:u,firstValid:(...e)=>{for(let n of e){let e=u(n);if(e!=null)return e}},mapValid:(e,n)=>l(e)?n(e):void 0,cmp:(e,n)=>{let r=c(e),a=c(n);return r==null||a==null?void 0:r>a?1:r<a?-1:0},lt:(e,n)=>{let r=c(e),a=c(n);return r!=null&&a!=null&&r<a},next:e=>{let r=c(e);return r==null?void 0:n[r]},toReversed:()=>strEnum(...[...n].reverse()),[Symbol.iterator]:()=>n[Symbol.iterator]()}}var numberFormat=defer(()=>new Intl.NumberFormat),decimalSep=defer(()=>replaceAll(numberFormat().format(1.1),`1`,``).charAt(0));function fmt(e){return numberFormat().format(e)}var KB=1e3,MB=KB*1e3,GB=MB*1e3,TB=GB*1e3,KiB=1024,MiB=KiB*1024,GiB=MiB*1024,TiB=GiB*1024,MP=1e6;function megapixels(e){return sigFigs(e/MP,2)}var SizeDescriptions=strEnum(`tiny`,`small`,`medium`,`large`,`original`);function pixels2size(e){return e<76800?`tiny`:e<345600?`small`:e<2073600?`medium`:`large`}function plur(e,n,r){return e==null?``:blank(n)?fmt(e):(e===0?`no`:fmt(e))+` `+(e===1?n:(r??pluralize(n)).trim())}var secondMs=1e3,minuteMs=60*secondMs,hourMs=60*minuteMs,dayMs=24*hourMs,weekMs=7*dayMs,monthMs=32*dayMs,yearMs=365.25*dayMs,hourCycle;function withHourCycle(e){return hourCycle==null?e:{...e,hourCycle}}var clockFormats=[];function registerClockFormat(e){return clockFormats.push(e),e}var shortDateTimeFormat=registerClockFormat(defer(()=>new Intl.DateTimeFormat(void 0,withHourCycle({year:`numeric`,month:`short`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`})))),shortDateFormat=defer(()=>new Intl.DateTimeFormat(void 0,{day:`numeric`,year:`numeric`,month:`short`})),compactDateFormat=defer(()=>new Intl.DateTimeFormat(void 0,{day:`numeric`,month:`short`})),compactTimeFormat=registerClockFormat(defer(()=>new Intl.DateTimeFormat(void 0,withHourCycle({hour:`numeric`,minute:`2-digit`}))));function toDate(e){return e instanceof Date?e:new Date(e)}function fmtDateShort(e){if(e!=null)return e instanceof Date&&e.getHours()===0&&e.getMinutes()===0&&e.getSeconds()===0?shortDateFormat().format(e):shortDateTimeFormat().format(e)}function isDate(e){return e instanceof Date&&!isNaN(e.getTime())}function ago(e,n){return new Date((n?.getTime()??Date.now())-e)}function fmtYMDHMS(e){return toYMDHMS(e).join(``)}function toYMDHMS(e){let n=toDate(e);return[String(n.getFullYear()),pad2(n.getMonth()+1),pad2(n.getDate()),pad2(n.getHours()),pad2(n.getMinutes()),pad2(n.getSeconds())]}function fmtIsoDateTime(e){let[n,r,a,o,s,c]=toYMDHMS(e);return`${n}-${r}-${a}T${o}:${s}:${c}`}function fmtIsoDateTimeSpace(e){let[n,r,a,o,s,c]=toYMDHMS(e);return`${n}-${r}-${a} ${o}:${s}:${c}`}function fmtHMS(e,n={includeMs:!0}){let r=Math.floor(e/hourMs);e-=r*hourMs;let a=Math.floor(e/minuteMs);e-=a*minuteMs;let o=Math.floor(e/secondMs),s=Math.floor(e-o*secondMs);return pad2(r)+`:`+pad2(a)+`:`+pad2(o)+(n.includeMs?`.`+pad3(s):``)}function fmtIsoDate(e){let n=isDate(e)?e:new Date(e);return n.getFullYear()+`-`+pad2(n.getMonth()+1)+`-`+pad2(n.getDate())}function localToDate(e){if(e==null||e<0)return;let n=e,r=()=>{let e=n%100;return n=Math.floor(n/100),e},a=10*r(),o=r(),s=r(),c=r(),l=r(),u=r();return new Date(n,u-1,l,c,s,o,a)}function fmtLocalToShort(e){return map(localToDate(e),fmtDateShort)}function nextMidnightTs(){return new Date().setHours(24,0,0,0)}function fmtElapsedMs(e,n=`ago`){let{compact:r=!1,justNowMs:a=1e3,suffix:o=`ago`}=typeof n==`string`?{suffix:n}:n,s=blank(o)?``:ensurePrefix(o,` `);return e<a&&s===` ago`?`just now`:r?e>=yearMs?Math.floor(e/yearMs)+`y`+s:e>=weekMs?Math.floor(e/weekMs)+`w`+s:e>=dayMs?Math.floor(e/dayMs)+`d`+s:e>=hourMs?Math.floor(e/hourMs)+`h`+s:e>=minuteMs?Math.floor(e/minuteMs)+`m`+s:Math.floor(e/secondMs)+`s`+s:e<secondMs?`less than a second`+s:e<minuteMs?plur(Math.floor(e/secondMs),`second`)+s:e<hourMs?plur(Math.floor(e/minuteMs),`minute`)+s:e<dayMs?plur(Math.floor(e/hourMs),`hour`)+s:e<weekMs?plur(Math.floor(e/dayMs),`day`)+s:e<yearMs?plur(Math.floor(e/weekMs),`week`)+s:plur(Math.floor(e/yearMs),`year`)+s}var g=globalThis,isBrowser=typeof g?.window==`object`&&typeof g?.document==`object`,isNode=typeof g?.process?.versions?.node==`string`;function delay(e,n=!0){return new Promise(r=>{if(e<=0)r();else{let a=setTimeout(()=>r(),Math.ceil(e+.5));e>secondMs&&n&&isNode&&a.unref?.()}})}function later(e,n=1){let r=Math.max(1,Math.ceil(n)),a=isNode&&r<=1?setImmediate(e):setTimeout(e,r);return isBrowser||n<=secondMs?a:maybeCall(a,`unref`)??a}function setUnrefTimeout2(e,n){let r=setTimeout(e,n);return maybeCall(r,`unref`)??r}function lazy(e,n){let r,a,o=null,s=[];function c(){return c.isStale()&&c.setResult(e()),a}async function l(e,r){if(r!==a)return;let l=await e,u=await r;if(o=u,s.length>0&&!eql(l,u))for(let e of s)e(u);n!=null&&n>0&&u!==void 0&&setUnrefTimeout2(()=>c.vacuum(),n)}return c.vacuum=function(){c.isStale()&&c.unset()},c.setResult=function(e){let n=a;return r=Date.now(),a=e,o=null,l(n,e),e},c.isStale=function(){return r==null||gt0(n)&&r+n<=Date.now()},c.set=function(e){c.setResult(e)},c.unset=function(){c.setResult(void 0),r=void 0,o=null},c.clear=function(){let e=a;return c.unset(),e},c.prior=function(){return c.vacuum(),a},c.priorSync=function(){return c.vacuum(),o},c.refresh=function(){return c.setResult(e())},c.ttl=function(){return n},c.setTTL=function(e){n=gt0(e)?e:void 0},c.watch=function(e){e(c()),delay(1).then(()=>s.push(e))},c.watchLater=function(e){s.push(e)},c.toString=function(){return`[Lazy]`},c.toJSON=function(){},c.lastSetAgoMs=function(){return r==null?void 0:Date.now()-r},c.hasPrior=function(){return r!=null},c.setFn=function(n){let r=e;return e=n,c.unset(),r},c}function lazy2(e,n){return new LazyClass(e,n)}var LazyClass=class extends ExtensibleFunction{constructor(e,n){super(),this.fn=e,this.ttlMs=n}fn;ttlMs;#e;#t;#n=null;#r;#i;watchers=[];_call(){return this.isStale()&&this.#c(this.fn()),this.#t}async#a(e){let n;try{n=await e}catch{e===this.#t&&(this.#r=void 0);return}if(e!==this.#t)return;this.#n=n,this.ttlMs!=null&&this.ttlMs>0&&n!==void 0&&this.#o();let r=this.#r;if(this.#r=n,!eql(r,n))for(let e of this.watchers)e(n)}#o(){this.#s();let e=this.#e;e!=null&>0(this.ttlMs)&&(this.#i=setLongTimeout(()=>{this.#i=void 0,this.unset()},e+this.ttlMs-performance.now(),()=>performance.now()))}#s(){this.#i?.clear(),this.#i=void 0}setFn(e){let n=this.fn;return this.fn=e,this.unset(),n}vacuum(){this.isStale()&&this.unset()}#c(e){return this.#s(),this.#n=null,this.#e=performance.now(),this.#a(e),this.#t=e}isStale(){return this.#e==null||gt0(this.ttlMs)&&this.#e+this.ttlMs<=performance.now()}set(e){this.#c(e)}unset(){this.#c(void 0),this.#e=void 0}clear(){let e=this.#t;return this.unset(),e}prior(){return this.vacuum(),this.#t}priorSync(){return this.vacuum(),this.#n}refresh(){return this.#c(this.fn())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=gt0(e)?e:void 0,this.#o()}watchLater(e){this.watchers.push(e)}watch(e){this.watchers.push(e)}toString(){return`[Lazy]`}[import_node_util.inspect.custom](){return`[Lazy]`}lastSetAgoMs(){return this.#e==null?void 0:performance.now()-this.#e}hasPrior(){return this.#e!=null}},ROLazy=class extends LazyClass{set(e){}};function rolazy(e,n){return new ROLazy(e,n)}var ErrorDelimiter=`: `,IgnoredErrorNames=[`Error`,`String`,`Object`,`WrappedError`];function errorName(e){let n=e?.name;return n==null||IgnoredErrorNames.includes(n)?void 0:n.toString()}function errorCode(e){return e==null?void 0:toNotBlank(e?.code)}function errorErrno(e){return e==null?void 0:toInt(e?.errno)}var FramesToIgnoreRE=/shortStack|errorToVerbose|LogWriter|ContextualLogger/;function shortStack(e,n=9){try{if(blank(e)){let n=Error();Error.captureStackTrace?.(n),e=n.stack}let r=toS(e).split(`
|
|
26
|
+
`).filter(e=>!blank(e)&&e.trim().startsWith(`at `)&&!FramesToIgnoreRE.test(e)).slice(0,n).map(e=>e.replace(/^\s*at /i,``));return isEmpty(r)?[`(missing stack)`]:r}catch(e){return[`Failed to captured stacktrace: `+e]}}function asError(e){if(blank(e))throw Error(`undefined error`);if(e instanceof Error)return e;if(Array.isArray(e)){let n=e[0];return n instanceof Error?(e.length>1&&(n.errors=e.slice(1)),n):Error(e.map(e=>toS(e)).filter(notBlank).join(`, `))}{let n=errorToS(e).replace(/^Error: /i,``);return Error(n)}}function errorToJson(e){return compactValues({message:e.message??String(e),stack:e.stack,name:errorName(e),code:errorCode(e),errno:errorErrno(e),...omit(e,`name`,`message`,`code`,`errno`)})}function errorFromJson(e){return assignFields(Error(),omit(e,`_ctor`))}function errorToArr(...e){let n=[];for(let r of e)r!=null&&(r instanceof Error?n.push(errorName(r),errorCode(r),r?.message):n.push(toS(r)));return uniq(compactBlankish(flatten(compact(n).map(e=>e.split(ErrorDelimiter)))))}function errorToS(...e){return errorToArr(...e).join(ErrorDelimiter)}function throwNewError(e){throw Error(e)}var ServiceNames=strEnum(`main`,`desktop`,`web`,`sync`,`fix`,`info`,`doctor`,`auth`,`test`,`logcat`,`logtail`,`list`,`billing`,`worker`,`test-worker`,`tool`),import_node_assert=__toESM(require("node:assert")),import_node_process2=__toESM(require("node:process"));function isPacked(){return!0}var MaybeTestArgRe=/mocha(?:\.js)?$|\.spec(\.js)?$/;function _nodeEnv(){if(isPacked())return`production`;switch(toS(import_node_process2.default.env.NODE_ENV).toLowerCase()){case`test`:return`test`;case`dev`:case`development`:return`development`;case`prod`:case`production`:return`production`;default:return import_node_process2.default.argv.some(e=>MaybeTestArgRe.exec(e)!=null)?`test`:`development`}}var nodeEnv=lazy2(()=>import_node_process2.default.env.NODE_ENV=_nodeEnv());function isTest(){return nodeEnv()===`test`}function assertIsTest(){(0,import_node_assert.default)(isTest(),`test-only function called in ${nodeEnv()}`)}function isProd(){return nodeEnv()===`production`}function isSingleSpecTests(){return isTest()&&isTrue(import_node_process2.default.env.SINGLE_SPEC_TESTS)}var import_node_os=__toESM(require("node:os")),import_node_process3=__toESM(require("node:process")),PS_IS_CHILD_PROCESS=`PS_IS_CHILD_PROCESS`,PS_IS_DOCKER=`PS_IS_DOCKER`,PS_IS_ELECTRON=`PS_IS_ELECTRON`,PS_IS_UTILITY_PROCESS=`PS_IS_UTILITY_PROCESS`,PS_RESET_LIBRARY_DIR=`PS_RESET_LIBRARY_DIR`,PS_ELECTRON_AUTH_SECRET=`PS_ELECTRON_AUTH_SECRET`,PS_ACCEPT_PHOTOSTRUCTURE_END_USER_LICENSE_AGREEMENT=`PS_ACCEPT_PHOTOSTRUCTURE_END_USER_LICENSE_AGREEMENT`,PS_INSTALL_TOOLS_AND_ACCEPT_PATENT_LICENSE_RESPONSIBILITY=`PS_INSTALL_TOOLS_AND_ACCEPT_PATENT_LICENSE_RESPONSIBILITY`,PS_UPDATE_FEED_BASE_URL=`PS_UPDATE_FEED_BASE_URL`,PS_ENV_FILE=`PS_ENV_FILE`,PS_ENV=`PS_ENV`,ELECTRON_RUN_AS_NODE=`ELECTRON_RUN_AS_NODE`,UV_THREADPOOL_SIZE=`UV_THREADPOOL_SIZE`,PS_TEST_JSON_MODE=`PS_TEST_JSON_MODE`,PS_SYNC_REPORT_STDOUT=`PS_SYNC_REPORT_STDOUT`,PS_EXPECT_TEST_ERRORS=`PS_EXPECT_TEST_ERRORS`,PS_TEST_PRODUCTION_RUNTIME=`PS_TEST_PRODUCTION_RUNTIME`,PS_BAIL_AFTER_TASK_COUNT=`PS_BAIL_AFTER_TASK_COUNT`,DevEnvFlags=strEnum(`PS_BAIL_ON_ERROR`,PS_EXPECT_TEST_ERRORS,`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_LOG_SQL`,`PS_NO_RANDOM_IMAGE_CACHE`,`PS_PRIVATE_KEYS`,`PS_QUICK`,`PS_SINGLE_SPEC_TESTS`,`PS_SKIP_ALL_TESTS`,`PS_SKIP_CLEANUP`,`PS_SKIP_RUN`,`PS_SLOMO`,`PS_TEST_HEALTH_CHECK_LEVEL`,`PS_TEST_NO_LIBRARY_MOUNT`,PS_SYNC_REPORT_STDOUT,PS_BAIL_AFTER_TASK_COUNT,`PS_SETTINGS_IO_TEST`),DevEnvKeys=[`PS_NO_PUID_CHOWN`,`PS_TMPDIR_PREFIX`,`PS_TEST_VOLUME_UUIDS`,`PS_TEST_FAT_DIR`,`PS_TEST_NOEXEC_DIR`,`PS_SKIP_DOCKER_TESTS`,PS_TEST_JSON_MODE,PS_TEST_PRODUCTION_RUNTIME],IgnorableEnvKeys=[PS_ELECTRON_AUTH_SECRET,`PS_CONFIG_DIR`,`PS_IS_PACKED`,PS_IS_DOCKER,PS_IS_ELECTRON,PS_IS_CHILD_PROCESS,PS_IS_UTILITY_PROCESS,PS_RESET_LIBRARY_DIR,PS_ACCEPT_PHOTOSTRUCTURE_END_USER_LICENSE_AGREEMENT,PS_INSTALL_TOOLS_AND_ACCEPT_PATENT_LICENSE_RESPONSIBILITY,PS_UPDATE_FEED_BASE_URL,PS_ENV_FILE,PS_ENV,...DevEnvKeys,...DevEnvFlags.values],_platform=import_node_os.default.platform(),inspectFlag=import_node_process3.default.argv.includes(`--inspect`)||isTrue(import_node_process3.default.env.NODE_INSPECT),isCI=isTrue(import_node_process3.default.env.CI),isWin=_platform===`win32`||_platform===`cygwin`,isWinPortable=isWin&¬Blank(import_node_process3.default.env.PORTABLE_EXECUTABLE_DIR),isMac=_platform===`darwin`,isLinux=_platform===`linux`,isLinux_x64=isLinux&&import_node_os.default.arch()===`x64`,isArm32=import_node_os.default.arch()===`arm`,isLinux_arm32=isLinux&&isArm32,isPosix=isMac||isLinux,isCaseSensitiveFs=isLinux,isMainElectron=import_node_process3.default.versions.electron!=null&&!isTrue(import_node_process3.default.env[ELECTRON_RUN_AS_NODE])&&import_node_process3.default.env[PS_IS_UTILITY_PROCESS]!==`1`,isElectron=lazy(()=>isTrue(import_node_process3.default.env[PS_IS_ELECTRON])||import_node_process3.default.versions.electron!=null||isTrue(import_node_process3.default.env[ELECTRON_RUN_AS_NODE])),hasGlibc=lazy(()=>reportIndicatesGlibc(import_node_process3.default.report?.getReport()));function reportIndicatesGlibc(e){let n=e?.header;return notBlank(n?.glibcVersionRuntime)}var platformName=isWin?`win`:isMac?`mac`:isLinux?`linux`:_platform,platformArch=platformName+`-`+import_node_os.default.arch(),serviceName=lazy2(()=>{if(isMainElectron)return ServiceNames.main;let e=import_node_process4.default.argv[1];if(blank(e))return`test`;let n=stripSuffix((0,import_node_path.basename)(e),`.js`);return ServiceNames.toValid(n)??(isTest()?ServiceNames.test:n.endsWith(`Mk`)?ServiceNames.tool:(console.error(`Unknown service name`,{result:n,caller:shortStack()}),`unknown`))}),processName=lazy2(()=>compactBlanks([serviceName.prior(),toS(import_node_process4.default.pid)]).join(`-`));serviceName.watchLater(()=>{processName.unset()});var MainServices=[ServiceNames.main,ServiceNames.desktop],DbServices=[ServiceNames.auth,ServiceNames.doctor,ServiceNames.fix,ServiceNames.info,ServiceNames.list,ServiceNames.sync,ServiceNames.test,ServiceNames.web];function isDbService(){return DbServices.includes(serviceName())}function isMainService(e){return MainServices.includes(e??serviceName())}function isWebService(e){return(e??serviceName())===ServiceNames.web}function isWorkerService(e){return(e??serviceName())===ServiceNames.worker}function isSyncService(e){return(e??serviceName())===ServiceNames.sync}function isInfoService(e){return(e??serviceName())===ServiceNames.info}function isTestService(e){return(e??serviceName())===ServiceNames.test}function isLogtailService(e){return(e??serviceName())===ServiceNames.logtail}var isDbJanitorService=lazy2(()=>isSyncService()||isTestService());function janitorPriority(){return isSyncService()||isTestService()?0:9}function canTailLogs(e){return isMainService(e)||isSyncService(e)||isWebService(e)||isTestService(e)||isLogtailService(e)}var import_node_process5=require("node:process"),Newline=isWin?`\r
|
|
27
|
+
`:`
|
|
28
|
+
`;function crlf(...e){let n=e.map(toS).join(`
|
|
29
|
+
`);return isWin?n.replace(newlineRe(),`\r
|
|
30
|
+
`):n}function splitLines(...e){return flatten(e.map(e=>Array.isArray(e)?splitLines(...e):toS(e).split(newlineRe())))}function joinLines(...e){return splitLines(...e).join(Newline)}function splitCompactLines(...e){return compactBlanks(splitLines(...e))}function streamEnded(e){return e==null||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}function writeStdout(e,...n){streamEnded(import_node_process5.stdout)||console.log(crlf(e),...n)}function writeStderr(e){streamEnded(import_node_process5.stderr)||import_node_process5.stderr.write(e)}var import_node_util2=require("node:util"),import_he=require("he");function firstThunk(...e){for(let n of e){let e=n();if(e!=null)return e}}function Try(e,n){try{return e()}catch(e){return n?.(toError(e))}}function identity(e){return e}function assignNullishFields(e,n){if(n==null)return e;for(let[r,a]of entries(n))(e[r]==null||blank(e[r]))&&(e[r]=a);return e}function mapEntries(e,n){let r={};for(let[a,o]of entries(e)){let e=n(a,o);e!=null&&(r[a]=e)}return r}function mapNullEntries(e,n,r){let a={},o=0;for(let s of keys(e))if(a[s]=n(s,e[s]),o++,gt(o,r))break;return a}function sortedKeys(e){if(e==null||isPrimitive(e))return e;if(Array.isArray(e))return e.map(e=>sortedKeys(e));if(typeof e==`object`){let n={};for(let r of sortIgnoreCase(keys(e)))n[r]=sortedKeys(e[r]);return n}return e}function pluckCaseInsensitive(e,n){if(typeof e==`object`){if(e[n]!==void 0)return e[n];for(let r of keys(e).filter(e=>equalsIgnoreCase(e,n)))if(e[r]!==void 0)return e[r]}}function pairToObject(e,n){let r={};return r[e]=n,r}function downcaseObjectKeys(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>downcaseObjectKeys(e));let n={};for(let[r,a]of entries(e))n[r.toLowerCase()]=downcaseObjectKeys(a);return n}function stringifySorted(e){return stringify(sortedKeys(e))}async function findAsync(e,n){for(let r of toA(e))if(r!=null&&!0===await n(r))return r}function first(e,n){if(e!=null){for(let r of toA(e))if(r!=null){let e=n(r);if(e!=null)return e}}}function intersection(e,n,r=primitiveValueOfOrElse){let a=new Set(n.map(r));return e.filter(e=>a.has(r(e)))}function diceCoeff(e,n,r=primitiveValueOfOrElse){return isEmpty(e)&&isEmpty(n)?1:intersection(e,n,r).length*2/(e.length+n.length)}function eqlUnordered(e,n){return e==null||n==null?!1:zip(sortBy(e,stringifySorted),sortBy(n,stringifySorted)).every(([e,n])=>eql(e,n))}function partition(e,n){let r=[],a=[],o=0;for(let s of e)(n(s,o++)?r:a).push(s);return[r,a]}function uniqCount(e){return _uniqCount(e.sort())}function _uniqCount(e){if(e==null||e.length===0)return[];let n=e[0],r=e.lastIndexOf(n);return[{t:n,count:r+1},..._uniqCount(e.slice(r+1))]}function retainLastN(e,n){return e.length>n&&e.splice(0,e.length-n),e}function retainFirstN(e,n){return e.length=Math.min(e.length,n),e}function zip(...e){let n=[],r=Math.max(...e.map(e=>e?.length??0));for(let a=0;a<r;a++)n.push(e.map(e=>e?.[a]));return n}function flatZip(...e){let n=Math.max(...e.map(e=>e?.length??0)),r=[];return times(n,n=>e.map(e=>r.push(e?.[n]))),r}function leastIndex(e){return leastIndexBy(e,e=>e.valueOf())}function max2(e){return e[greatestIndex(e)]}function greatestIndex(e){return greatestIndexBy(e,e=>e.valueOf())}function leastIndexBy(e,n){return estIndex(e,n,(e,n)=>lt2(e,n))}function greatestIndexBy(e,n){return estIndex(e,n,(e,n)=>gt2(e,n))}function greatestBy(e,n){return isEmpty(e)?void 0:e[greatestIndexBy(e,n)]}function estIndex(e,n,r){return estIndexCtx(e,n,r).index}function leastByCtx(e,n){let r=estIndexCtx(e??[],n,lt2);return e==null||r==null||r.index<0||r.value==null?void 0:{result:e[r.index],index:r.index,value:r.value}}function estIndexCtx(e,n,r){if(isEmpty(e))return{index:-1,value:void 0};let a=-1,o;for(let s=0;s<e.length;s++){let c=e[s];if(c!=null){let e=n(c);e!=null&&(o==null||r(e,o)===!0)&&(a=s,o=e)}}return{index:a,value:o}}function batches(e,n){return n<1&&(n=1),stepRange(0,e.length,Math.round(n),r=>e.slice(r,r+n))}function rightPadArray(e,n,r){if(e.length<n){let a=Array(n-e.length).fill(r);e.push(...a)}return e}var SmartSingleQuotes=`‘’`,SmartDoubleQuotes=`“”„«»〃`,SmartQuotes=RegExp(`[${SmartSingleQuotes}${SmartDoubleQuotes}]`,`g`),Smart2Dumb=[[RegExp(`[${SmartSingleQuotes}]`,`g`),`'`],[RegExp(`[${SmartDoubleQuotes}]`,`g`),`"`]];function dumbquote(e){return Smart2Dumb.reduce((e,[n,r])=>e.replace(n,r),e).normalize()}var NothingRegExp=/$^/,MagicRegExpChars=/[-.,\\^$*+?()|[\]{}]/g;function escapeRegExp(e){return e instanceof RegExpEscaped?e.source:toS(e).replace(MagicRegExpChars,`\\$&`)}function matchQuotes(e){return e.replace(/[‘’']/g,`[‘’']`).replace(/[“”„«»〃"]/g,`[“”„”«»〃"]`)}function orRegExpPatterns(e,n){let r=[];for(let n of e)try{r.push(n instanceof RegExp?n.source:new RegExp(n).source)}catch{r.push(escapeRegExp(n))}let a=r.length===0?NothingRegExp:r.map(e=>`(?:`+e+`)`).join(`|`);return new RegExp(a,n)}var RegExpEscaped=class{constructor(e,n){this.source=e,this.flags=n}source;flags;get global(){return this.flags?.includes(`g`)??!1}get ignoreCase(){return this.flags?.includes(`m`)??!1}get multiline(){return this.flags?.includes(`i`)??!1}},RegExpOptional=class e extends RegExpEscaped{static from(...n){let r=concatRegexp(n);return new e(`(?:`+r.source+`)?`,r.flags)}};function concatRegexp(e,n){let r=``,a=n?.includes(`g`)??!1,o=n?.includes(`i`)??!1,s=n?.includes(`m`)??!1;for(let n of e)n instanceof RegExpEscaped||n instanceof RegExp?(r+=n.source,a||=n.global,o||=n.ignoreCase,s||=n.multiline):r+=escapeRegExp(toS(n));return new RegExp(r,n??(a?`g`:``)+(o?`i`:``)+(s?`m`:``))}var ErrorFlags=strEnum(`¹`,`²`,`³`,`⁴`,`⁵`,`⁶`,`⁷`,`⁸`,`⁹`,`₀`,`₁`,`₂`,`₄`);function sortErrorFlags(e){return sortBy(uniq(e),e=>ErrorFlags.indexOf(e))}var FatalErrorFlag=ErrorFlags[`¹`],NonFatalErrorFlag=ErrorFlags[`₂`],IgnorableErrorFlag=ErrorFlags[`³`],NonIgnorableErrorFlag=ErrorFlags[`₄`],RetriableErrorFlag=ErrorFlags[`⁷`],NonRetriableErrorFlag=ErrorFlags[`²`],DoNotSendErrorFlag=ErrorFlags[`⁶`],PleaseSendErrorFlag=ErrorFlags[`⁴`],InternalErrorFlag=ErrorFlags[`⁹`],HealthCheckErrorFlag=ErrorFlags[`⁵`],HealthCheckWarningFlag=ErrorFlags[`⁸`],NoLibraryErrorFlag=ErrorFlags[`₀`],DbSetupErrorFlag=ErrorFlags[`₁`],ErrorFlagDescriptions={[FatalErrorFlag]:`FatalErrorFlag`,[NonFatalErrorFlag]:`NonFatalErrorFlag`,[IgnorableErrorFlag]:`IgnorableErrorFlag`,[NonIgnorableErrorFlag]:`NonIgnorableErrorFlag`,[RetriableErrorFlag]:`RetriableErrorFlag`,[NonRetriableErrorFlag]:`NonRetriableErrorFlag`,[DoNotSendErrorFlag]:`DoNotSendErrorFlag`,[PleaseSendErrorFlag]:`PleaseSendErrorFlag`,[InternalErrorFlag]:`InternalErrorFlag`,[HealthCheckErrorFlag]:`HealthCheckErrorFlag`,[HealthCheckWarningFlag]:`HealthCheckWarningFlag`,[NoLibraryErrorFlag]:`NoLibraryErrorFlag`,[DbSetupErrorFlag]:`DbSetupErrorFlag`},ErrorFlagsRE=RegExp(`(`+ErrorFlags.values.join(`|`)+`)`,`g`),FailStr=JSON.stringify({fatal:!0}),FatalErrorPatterns=[`EADDRINUSE`,`Error: Cannot find module`,FatalErrorFlag,FailStr],FatalErrorRe=new RegExp(FatalErrorPatterns.map(escapeRegExp).join(`|`),`i`),InternalErrorRe=/⁹|internal ?error/i;function rightPad(e,n,r){if(!r||r.length===0)throw Error(`rightPad() requires a non-empty pad character`);let a=String(e);if(a.length>=n)return a;let o=n-a.length;if(r.length>1){let e=``;for(let n=0;n<o;n++)e+=r[n%r.length];return a+e}return a+r.repeat(o)}function countChars(e,n,r=0){if(n==null||n.length===0)return 0;let a=e.indexOf(n,r);return a===-1?0:1+countChars(e,n,a+n.length)}function splitEvery(e,n,r){let a=Math.min(Math.ceil(e.length/n),r??e.length)-1;return a<=0?[e]:[...times(a,r=>e.slice(r*n,(r+1)*n)),e.slice(a*n)]}function spliceCapture(e,n){let r=n.exec(e);if(r==null||r[1]==null)return;let a=r[0].indexOf(r[1])+r.index;return{captured:r[1],uncaptured:e.substring(0,a)+e.substring(a+r[1].length),unmatched:e.substring(0,r.index)+e.substring(r.index+r[0].length),matchedIndex:a}}var CapRE=/^[A-Z]/;function isFirstCharAZ(e){return CapRE.test(toS(e))}function capitalize(e){return e=toS(e),blank(e)?e:strslice(e,0,1).toLocaleUpperCase()+strslice(e,1)}function compareIgnoreCase(e,n){return e.localeCompare(n,void 0,{sensitivity:`base`})}function uniqIgnoreCase(e){return uniqBy2(e,equalsIgnoreCase)}function sortIgnoreCase(e){return sortBy(e,e=>e==null?void 0:[e.toLocaleLowerCase(),e])}function sortByCaseInsensitive(e,n){return toA(e).filter(e=>e!=null).map((e,r)=>({item:e,idx:r,f:n(e,r)})).filter(e=>e.f!=null).sort((e,n)=>{let r=compareIgnoreCase(e.f,n.f);return r===0?cmp(e.idx,n.idx):r}).map(e=>e.item)}function startsWithIgnoreCase(e,n){return e==null||n==null||n.length===0||e.length===0?!1:equalsIgnoreCase(e.substring(0,n.length),n)}function firstSubstringIgnoreCase(e,n){if(isEmpty(e)||blank(n))return;for(let r of e)if(equalsIgnoreCase(r,n))return{index:0,match:r};for(let r of e){let e=n.indexOf(r);if(e>=0)return{index:e,match:r}}let r=n.normalize();for(let n of e){{let e=r.indexOf(n);if(e>=0)return{index:e,match:n}}let e=n.normalize();{let n=r.indexOf(e);if(n>=0)return{index:n,match:e}}{let n=r.toLowerCase(),a=e.toLowerCase(),o=n.indexOf(a);if(o>=0)return{index:o,match:a}}}}function stripAnsiEsc(e){return toS(e).replace(/\u001B\[[\d;]+[a-z]/gi,``)}var quoted=/^(['"]).+\1$/;function stripQuotes(e){return blank(e)||(e=toS(e).trim(),quoted.exec(dumbquote(e))!=null&&(e=e.slice(1,-1).trim())),e}var SingleQuoteWrappedRE=/^['‘’].*['‘’]$/,DoubleQuoteWrappedRE=/^["“”„«»〃].*["“”„«»〃]$/;function trimQuotes(e){return e=toS(e).trim(),SingleQuoteWrappedRE.test(e)||DoubleQuoteWrappedRE.test(e)?e.slice(1,-1).trim():e}function*yieldSplit(e,n){if(!e)return;if(!n.global)throw Error(`yieldSplit requires a global regex (with g flag)`+NonRetriableErrorFlag);let r=0,a;for(n.lastIndex=0;(a=n.exec(e))!==null;)a.index===n.lastIndex?n.lastIndex++:(yield e.substring(r,n.lastIndex),r=n.lastIndex);r<e.length&&(yield e.substring(r))}function splitKeep(e,n){let r=splitUp(e,n);return flatZip(r.nonSeparators,r.separators).filter(e=>e!=null&&e.length>0)}function splitUp(e,n){if(!n.global)throw Error(`bad regex (missing global flag)`+NonRetriableErrorFlag);let r=[],a=[],o=0,s;for(;(s=n.exec(e))!=null;)s.index===n.lastIndex?n.lastIndex++:(n.lastIndex=s[0].length+s.index,r.push(e.substring(o,s.index)),a.push(e.substring(s.index,n.lastIndex)),o=n.lastIndex);return o<e.length&&r.push(e.substring(o)),{nonSeparators:r,separators:a}}var ControlCharRE=/[\x00-\x08\v\f\x0e-\x1f\x7f-\x9f]/,UnicodeAlphaNumRE=/[\p{L}\p{N}]/gu,ExtendedPictographicRE=RegExp(`\\p{Extended_Pictographic}`,`u`),PlaceholderOnlyRE=/^0*[?:][?:0]*$/;function hasCorruptionMarkers(e){return hasEncodingCorruption(e)||isPlaceholderOnly(e)||lacksContentBearingChars(e)}function hasEncodingCorruption(e){let n=toS(e).trim();return n.length===0?!1:ControlCharRE.test(n)?!0:n.includes(`�`)}function isPlaceholderOnly(e){let n=toS(e).trim().replace(/\s/g,``);return n.length>0&&PlaceholderOnlyRE.test(n)}function lacksContentBearingChars(e){let n=toS(e).trim();return n.length===0||(n.match(UnicodeAlphaNumRE)??[]).length>0?!1:!ExtendedPictographicRE.test(n)}function commonPrefixIgnoreCase(e,n,r={}){if(blank(e)||blank(n))return``;let a=Math.min(e.length,n.length);for(let o=0;o<a;o++)if(!equalsIgnoreCase(e[o],n[o],r))return e.slice(0,o);return e.slice(0,a)}function indexOfNonSpace(e){return e.match(/\S/)?.index}function lastIndexOfNonSpace(e){return e.match(/\S\s*$/)?.index}function trimLeftPadding(e){return e.replace(/^[-0_\s]+/,``)}var CommentRE=/#.*$/gm;function stripComments(e){return e.replace(CommentRE,``)}function dedupeNeedle(e,n,r){if(blank(n))return e;let a=RegExp(`(['"]?)`+escapeRegExp(n)+`\\1`,`gm`),o=e.findIndex(e=>a.test(e)),s=RegExp(`(`+escapeRegExp(r)+`[,:\\s]*){2,}`,`gim`);if(o<0)return e;for(let n=o+1;n<e.length;n++)e[n]=e[n].replace(a,r).replace(/\s{2,}/g,` `).replace(s,r).trim();return e}function splitUniq(e,n){return uniq(compactBlanks(e.join(n).split(n).map(e=>e.trim())))}var LogLevels=strEnum(`fatal`,`error`,`warn`,`info`,`debug`,`trace`),TraceLevelIndex=LogLevels.indexOf(`trace`);function levelIndex(e){return LogLevels.indexOf(e)??LogLevels.indexOf(e.trim().split(/[^a-z]/i)[0]?.toLowerCase())??TraceLevelIndex}function maxSevereLevel(e,...n){let r=e;for(let e of n)e!=null&&LogLevels.lt(e,r)&&(r=e);return r}var LogLevel2SyslogLevel=new Map([[LogLevels.fatal,1],[LogLevels.error,3],[LogLevels.warn,4],[LogLevels.info,6],[LogLevels.debug,7]]);function level2syslog(e){return LogLevel2SyslogLevel.get(e)}var defaultErrorMs=minuteMs;function setDefaultElapsedErrorLogMs(e){defaultErrorMs=toGt0(e)??defaultErrorMs}function msToLevel(e,n){let r=toGt0(n)??defaultErrorMs;return e>=r?`error`:e>=r*.5?`warn`:e>=r*.25?`info`:`debug`}var PlaintextLogFormatter=class{constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e}inspectOptions;paddedLogLevels=fromEntries(LogLevels.values.map(e=>[e,rightPad(e,5,` `)]));formatLogEntry(e){return compactBlanks([new Date(e.ts).toISOString(),e.from??processName(),this.paddedLogLevels[e.l],stripAnsiEsc(e.ctx),stripAnsiEsc(e.msg),map(e.meta,e=>(0,import_node_util2.inspect)(e,this.inspectOptions))]).map(e=>toS(e)).join(` `)}format(e,n,r,a){return this.formatLogEntry({ts:Date.now(),l:e,from:processName(),ctx:n,msg:r,meta:a})}},DefaultLogFormatter=lazy2(()=>new PlaintextLogFormatter);function DefaultLogEntryWriter(e){writeStdout(DefaultLogFormatter().formatLogEntry(e))}function logLevelDefaultValue(){return isTest()?`error`:`warn`}var SimpleLogFilter=class{constructor(e){this.minLogLevel=e,this.defaultLevelIndex=levelIndex(e)}minLogLevel;defaultLevelIndex;highlight(){return!1}enabled(e){return!this.silent&&levelIndex(e)<=this.defaultLevelIndex}silent=!1},logFilter=lazy2(()=>new SimpleLogFilter(logLevelDefaultValue())),defaultLogLevel=lazy2(()=>LogLevels.values[logFilter().defaultLevelIndex]);function isDefaultLogLevelAtLeast(e){return logFilter().defaultLevelIndex>=levelIndex(e)}function isLogged(e,n){return logFilter().enabled(e,n)}var ConsoleLogger=class e{static instance=defer(()=>new e);log(e,n,r,a){this.isEnabled(e,n)&&this._logEntry({ts:Date.now(),l:e,from:processName(),ctx:n,msg:r,meta:a})}_logEntry(e){DefaultLogEntryWriter(e)}isEnabled(e,n){return logFilter().enabled(e,n)}async maybeFlush(){}toLogJSON(){return`ConsoleLogger()`}[import_node_util3.inspect.custom](){return this.toLogJSON()}},import_node_util5=require("node:util"),Timeout=Symbol(`timeout`),TimeoutError=class extends Error{name=`TimeoutError`};function isTimeoutError(e){return e instanceof TimeoutError||Object.prototype.toString.call(e)===`[object Error]`&&e.name===`TimeoutError`}async function thenOrTimeout(e,n,r=!1){return n==null||n<=0?e:(n=Math.round(n),n<=1?Timeout:_thenOrTimeout(e,n,r))}async function _thenOrTimeout(e,n,r){return new Promise((a,o)=>{let s=!0,c=setTimeout(()=>{s&&(s=!1,a(Timeout))},n);r&&c.unref?.(),(async()=>{try{let n=await e;s&&(s=!1,a(n))}catch(e){s&&(s=!1,o(e))}finally{clearTimeout(c)}})()})}async function thenOrTimeoutError(e,n,r=!1){let a=await thenOrTimeout(e,n,r);if(a===Timeout)throw new TimeoutError(`timeout (`+fmtHMS(n)+`)`);return a}function roundMs(e){return Math.round(e*10)/10}var ShortCommandTimeoutMs=7*secondMs,AbortError=class extends Error{name=`AbortError`};function isAbortError(e){return e instanceof AbortError||String(e).includes(`AbortError`)}var BasePromise=class{promise;_resolve;_reject;constructor(){this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}_state=`pending`;isPending(){return this._state===`pending`}isSettled(){return!this.isPending()}isResolved(){return this._state===`resolved`}isRejected(){return this._state===`rejected`}state(){return this._state}toLogJSON(){return{_ctor:this[Symbol.toStringTag],state:this.state()}}then(e,n){return this.promise.then(e,n)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}},_id=0,Latch=class extends BasePromise{constructor(e=_id++){super(),this.id=e}id;startedAt=Date.now();settledAt=void 0;[Symbol.toStringTag]=`Latch`;error;get elapsedMs(){return(this.settledAt??Date.now())-this.startedAt}resolve(){return this.isPending()&&(this.settledAt=Date.now(),this._resolve(),this._state=`resolved`),this}reject(e){return this.isPending()&&(this.settledAt=Date.now(),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}},Abortable=class{_aborted=!1;_abortReason;#e=new AbortController;#t;#n=defer(()=>new Latch);#r=new Set;abort(e){if(this._aborted)return;this._aborted=!0,this._abortReason=e;let n=new AbortError(e);for(let e of this.#r)e(n);this.#r.clear(),this.#n().reject(n).catch(()=>{}),this.#e.abort(n)}throwIfAborted_(e){if(!0===e?.aborted||this.aborted)throw new AbortError(e?.reason??this._abortReason??`(no reason given)`)}get aborted(){return this._aborted}get reason(){return this._abortReason}get signal(){return this.#e.signal}abortPromise_(){return this.#n().promise}awaitOrAbort(e){this.throwIfAborted_();let n,r=new Promise((e,r)=>n=r);this.#r.add(n);let a=Promise.race([e,r]),o=()=>this.#r.delete(n);return a.then(o,o),a}setAbortTimeout(e,n){this.clearAbortTimeout(),this.#t=setTimeout(()=>this.abort(n),e).unref()}clearAbortTimeout(){this.#t!=null&&clearTimeout(this.#t),this.#t=void 0}observeRejections(e){e.catch(e=>this.abort(e.message))}observeResolutions(e,n){e.then(()=>this.abort(n))}},_ending=!1;function ending(){return _ending}function setEnding(e){_ending=isTest()?e:e||_ending}var SubstringMatcher=class{#e;constructor(e){e.length>0&&(this.#e=new RegExp(e.map(e=>escapeRegExp(e)).join(`|`),`i`))}test(e){return this.#e!=null&&this.#e.test(e)}},BoundedList=class{constructor(e){if(this.maxLength=e,e>1e4)throw Error(`BoundedList.maxLength of `+e);this.#e=new Array(...times(e,()=>null))}maxLength;#e;#t=0;#n=0;#r(e,n){return e=Math.trunc(e)??0,e<0&&(e+=this.#t),e<0||e>=this.#t?void 0:n((e+this.#n+this.maxLength)%this.maxLength)}at(e){return this.#r(e,e=>this.#e[e])}get last(){return this.at(-1)}set(e,n){return this.#r(e,e=>this.#e[e]=n)}get length(){return this.#t}set length(e){this.#t=clamp(0,this.#t,e)}clear(){this.length=0}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.#r(e,e=>this.#e[e])}push(...e){for(let n of e.slice(-this.maxLength))this.#t<this.maxLength?this.#t++:(this.#n++,this.#n%=this.maxLength),this.#r(this.#t-1,e=>{this.#e[e]=n});return this.#t}pop(){return this.#r(this.#t-1,e=>(this.#t--,this.#e[e]))}unshift(...e){for(let n of e.reverse())this.#t<this.maxLength&&this.#t++,this.#n--,this.#r(0,e=>{this.#e[e]=n,this.#n=e});return this.#t}shift(){return this.#r(0,e=>(this.#n++,this.#t--,this.#e[e]))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let n=0;n<this.#t;n++)if(!e(this.at(n),n))return!1;return!0}some(e){for(let n=0;n<this.#t;n++)if(e(this.at(n),n))return!0;return!1}forEach(e){for(let n=0;n<this.#t;n++)e(this.at(n),n)}map(e){let n=[];for(let r=0;r<this.#t;r++)n.push(e(this.at(r),r));return n}reduce(e,n){let r=n;for(let n=0;n<this.#t;n++)r=e(r,this.at(n),n);return r}reverse(){for(let e=0;e<Math.floor(this.#t/2);e++)this.#r(e,n=>{this.#r(this.#t-1-e,e=>{let r=this.#e[e];this.#e[e]=this.#e[n],this.#e[n]=r})});return this}toJSON(){return this.toA()}toA(){return[...this]}slice(e,n){return[...this].slice(e,n)}},Rate=class{constructor(e=minuteMs,n=secondMs){this.periodMs=e,this.warmupMs=n,this.#s()}periodMs;warmupMs;#e=performance.now();#t=performance.now();#n=0;#r=0;#i=0;#a=null;#o=null;#s(){this.#c(),this.#o=setInterval(()=>this.#l(),this.periodMs),this.#o.unref()}#c(){this.#o!=null&&(clearInterval(this.#o),this.#o=null)}#l(){this.#r=this.#n,this.#n=0,this.#t=performance.now()}onEvent(){this.#i++,this.#n++,this.#a=performance.now()}get eventCount(){return this.#i}get msSinceLastEvent(){return this.#a==null?null:performance.now()-this.#a}#u(){return this.#a!=null&&performance.now()-this.#e>=this.warmupMs}#d(){return Math.min(this.periodMs,performance.now()-this.#e)}#f(){let e=performance.now()-this.#t,n=Math.max(0,this.periodMs-e)/this.periodMs;return this.#r*n+this.#n}get eventsPerMs(){if(!this.#u())return 0;let e=this.#f();return e===0?0:e/this.#d()}get eventsPerSecond(){return this.eventsPerMs*secondMs}get eventsPerMinute(){return this.eventsPerMs*minuteMs}clear(){return this.#e=performance.now(),this.#t=performance.now(),this.#n=0,this.#r=0,this.#a=null,this.#i=0,this.#s(),this}stats(){return{eventCount:this.eventCount,eventsPerSecond:sigFigs(this.eventsPerSecond,2),msSinceLastEvent:this.msSinceLastEvent}}[Symbol.dispose](){this.#c()}},import_node_os2=require("node:os");function isSQLiteError(e){return typeof e?.sqliteExtendedCode==`number`&&typeof e?.sqliteCodeName==`string`}function sqliteErrorDescriptions(e){return isSQLiteError(e)?compact([sqliteResultCodeName(e),e.systemErrno==null?void 0:`OS error `+e.systemErrno]):[]}function sqliteResultCodeName(e){let n=e.sqliteExtendedCode;return ExtendedResultCodeNames[n]??(n>255?`${e.sqliteCodeName} (${n})`:e.sqliteCodeName)}var PosixErrorKinds=new Map([[import_node_os2.constants.errno.ENXIO,`disconnected`],[import_node_os2.constants.errno.ENODEV,`disconnected`],[import_node_os2.constants.errno.ESTALE,`disconnected`],[import_node_os2.constants.errno.EIO,`failing`]]),ExtendedResultCodeNames={256:`SQLITE_OK_LOAD_PERMANENTLY`,257:`SQLITE_ERROR_MISSING_COLLSEQ`,261:`SQLITE_BUSY_RECOVERY`,262:`SQLITE_LOCKED_SHAREDCACHE`,264:`SQLITE_READONLY_RECOVERY`,266:`SQLITE_IOERR_READ`,267:`SQLITE_CORRUPT_VTAB`,270:`SQLITE_CANTOPEN_NOTEMPDIR`,275:`SQLITE_CONSTRAINT_CHECK`,279:`SQLITE_AUTH_USER`,283:`SQLITE_NOTICE_RECOVER_WAL`,284:`SQLITE_WARNING_AUTOINDEX`,512:`SQLITE_OK_SYMLINK`,513:`SQLITE_ERROR_RETRY`,516:`SQLITE_ABORT_ROLLBACK`,517:`SQLITE_BUSY_SNAPSHOT`,518:`SQLITE_LOCKED_VTAB`,520:`SQLITE_READONLY_CANTLOCK`,522:`SQLITE_IOERR_SHORT_READ`,523:`SQLITE_CORRUPT_SEQUENCE`,526:`SQLITE_CANTOPEN_ISDIR`,531:`SQLITE_CONSTRAINT_COMMITHOOK`,539:`SQLITE_NOTICE_RECOVER_ROLLBACK`,769:`SQLITE_ERROR_SNAPSHOT`,773:`SQLITE_BUSY_TIMEOUT`,776:`SQLITE_READONLY_ROLLBACK`,778:`SQLITE_IOERR_WRITE`,779:`SQLITE_CORRUPT_INDEX`,782:`SQLITE_CANTOPEN_FULLPATH`,787:`SQLITE_CONSTRAINT_FOREIGNKEY`,795:`SQLITE_NOTICE_RBU`,1025:`SQLITE_ERROR_RESERVESIZE`,1032:`SQLITE_READONLY_DBMOVED`,1034:`SQLITE_IOERR_FSYNC`,1038:`SQLITE_CANTOPEN_CONVPATH`,1043:`SQLITE_CONSTRAINT_FUNCTION`,1281:`SQLITE_ERROR_KEY`,1288:`SQLITE_READONLY_CANTINIT`,1290:`SQLITE_IOERR_DIR_FSYNC`,1294:`SQLITE_CANTOPEN_DIRTYWAL`,1299:`SQLITE_CONSTRAINT_NOTNULL`,1537:`SQLITE_ERROR_UNABLE`,1544:`SQLITE_READONLY_DIRECTORY`,1546:`SQLITE_IOERR_TRUNCATE`,1550:`SQLITE_CANTOPEN_SYMLINK`,1555:`SQLITE_CONSTRAINT_PRIMARYKEY`,1802:`SQLITE_IOERR_FSTAT`,1811:`SQLITE_CONSTRAINT_TRIGGER`,2058:`SQLITE_IOERR_UNLOCK`,2067:`SQLITE_CONSTRAINT_UNIQUE`,2314:`SQLITE_IOERR_RDLOCK`,2323:`SQLITE_CONSTRAINT_VTAB`,2570:`SQLITE_IOERR_DELETE`,2579:`SQLITE_CONSTRAINT_ROWID`,2826:`SQLITE_IOERR_BLOCKED`,2835:`SQLITE_CONSTRAINT_PINNED`,3082:`SQLITE_IOERR_NOMEM`,3091:`SQLITE_CONSTRAINT_DATATYPE`,3338:`SQLITE_IOERR_ACCESS`,3594:`SQLITE_IOERR_CHECKRESERVEDLOCK`,3850:`SQLITE_IOERR_LOCK`,4106:`SQLITE_IOERR_CLOSE`,4362:`SQLITE_IOERR_DIR_CLOSE`,4618:`SQLITE_IOERR_SHMOPEN`,4874:`SQLITE_IOERR_SHMSIZE`,5130:`SQLITE_IOERR_SHMLOCK`,5386:`SQLITE_IOERR_SHMMAP`,5642:`SQLITE_IOERR_SEEK`,5898:`SQLITE_IOERR_DELETE_NOENT`,6154:`SQLITE_IOERR_MMAP`,6410:`SQLITE_IOERR_GETTEMPPATH`,6666:`SQLITE_IOERR_CONVPATH`,6922:`SQLITE_IOERR_VNODE`,7178:`SQLITE_IOERR_AUTH`,7434:`SQLITE_IOERR_BEGIN_ATOMIC`,7690:`SQLITE_IOERR_COMMIT_ATOMIC`,7946:`SQLITE_IOERR_ROLLBACK_ATOMIC`,8202:`SQLITE_IOERR_DATA`,8458:`SQLITE_IOERR_CORRUPTFS`,8714:`SQLITE_IOERR_IN_PAGE`,8970:`SQLITE_IOERR_BADKEY`,9226:`SQLITE_IOERR_CODEC`};function describeError(e){return ErrorCodes[stripSuffix(toS(e).trim().toUpperCase(),`:`)]?.description??e}function getErrorDescriptions(...e){let n=[];for(let r of e)map(errorErrno(r),e=>n.push(err2desc.get(e))),map(errorCode(r),e=>n.push(ErrorCodes[e]?.description)),mapNotBlank(r?.message,e=>{n.push(e),n.push(describeError(e))}),n.push(...sqliteErrorDescriptions(r));return uniq(n)}var ErrorCodes={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`}},err2desc=new Map(Object.values(ErrorCodes).map(e=>[e.errno,e.description])),import_node_util4=require("node:util");function NoBlanksStringNormalizer(e){return e==null||blank(e)?void 0:StringNormalizer(e)}function StringNormalizer(e){return toS(e).toLowerCase().normalize()}var CaseInsensitiveSet=class{constructor(e=[],n=NoBlanksStringNormalizer){this.normalizer=n;for(let n of e)this.add(n)}normalizer;#e=new Map;add(e){let n=this.normalizer(e);return n!=null&&e!=null&&this.#e.set(n,e),this}clear(){this.#e.clear()}delete(e){let n=this.normalizer(e);return n!=null&&this.#e.delete(n)}forEach(e){this.#e.forEach((n,r)=>e(n,n,this))}has(e){if(e==null)return!1;let n=this.normalizer(e);return n!=null&&this.#e.has(n)}hasAny(e){for(let n of e)if(this.has(n))return!0;return!1}lookup(e){if(e==null)return;let n=this.normalizer(e);return n==null?void 0:this.#e.get(n)}get size(){return this.#e.size}entries(){return new Set(this.#e.values()).entries()}keys(){return this.#e.values()}values(){return this.#e.values()}[Symbol.iterator](){return this.#e.values()[Symbol.iterator]()}get[Symbol.toStringTag](){return`CaseInsensitiveSet`}};function toWrappedError(e,n){let r=n==null?{}:n instanceof Error?{cause:n}:{cause:n?.error,...n};if(e instanceof WrappedError){if(n==null||blank(r.message)&&r.cause==null&&(r.meta==null||isEmptyObj(r.meta)))return e;let a=e.causes??[],o=r.causes??[],s=[...a,...o,e.cause].filter(e=>e!=null),c=[e,...s,n];return new WrappedError(firstNotBlank(r.message,e.message)??`(missing error message)`,{...r,causes:s,code:r.code??e.code,path:r.path??e.path,syscall:r.syscall??e.syscall,errno:r.errno??e.errno,meta:mergeObjectsDeep({},e.meta,r.meta),retriable:maybeAnd([r.retriable,...c.map(isRetriableError)]),ignorable:maybeAnd([r.ignorable,...c.map(isIgnorableError)]),fatal:maybeOr([r.fatal,...c.map(isFatalError)]),doNotSend:maybeAnd([r.doNotSend,...c.map(isDoNotSendError)]),internal:maybeOr([r.internal,...c.map(isInternalError)])})}let a=firstNotBlank(isString(e)?e:void 0,e?.message,r?.message),o=isError(e)?{...r,cause:e,causes:compact([r.cause,...toA(r.causes)])}:r;return new WrappedError(a??`(missing error message)`,o)}function mkMessage(e,n){let r=splitErrorMessage(e,n?.message,n?.cause,...n?.causes??[]),a=new CaseInsensitiveSet(IgnoredErrorNames);blank(n?.name)||a.add(n.name),filterInPlace(r,e=>!a.has(e));let o=n?.path;blank(o)||(r=dedupeNeedle(r,o,`file`)),notEmptyObj(n?.meta)&&r.push(stringify(n.meta));for(let e of uniq(compact([n?.syscall,n?.code,...toA(n?.codes)])))r.join(`
|
|
31
|
+
`).includes(e)||r.unshift(e);return joinErrorMessages(r)}var WrappedError=class e extends Error{code;codes;errno;syscall;path;cause;causes;meta;constructor(e,n={}){super(e);let r=uniqBy(toErrors(n.cause,n.meta?.error,...toA(n.causes)),e=>e.message);this.cause=r[0],this.causes=toNotEmpty(r.slice(1)),this.name=errorName(n)??first(r,errorName)??`Error`,this.codes=splitUniq([n.code,...r.map(errorCode)],ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=n.errno??first(r,e=>errorErrno(e)),this.syscall=n.syscall??first(r,e=>toNotBlank(e.syscall)),this.path=n.path??first(r,e=>toNotBlank(e.path));let a=n?.flags??[],o=[e,n,a.join(``),...r],s=n.fatal??o.some(isFatalError),c=n.internal??maybeOr(o.map(isInternalError)),l=n.retriable??maybeAnd(o.map(isRetriableError)),u=n.ignorable??maybeAnd(o.map(isIgnorableError)),d=n.doNotSend??maybeAnd(o.map(isDoNotSendError));a=sortErrorFlags([...a,s===!0?FatalErrorFlag:void 0,c===!0?InternalErrorFlag:void 0,l===!0?RetriableErrorFlag:void 0,l===!1?NonRetriableErrorFlag:void 0,u===!0?IgnorableErrorFlag:void 0,u===!1?NonIgnorableErrorFlag:void 0,d===!1?PleaseSendErrorFlag:void 0,d===!0?DoNotSendErrorFlag:void 0]),this.meta=omit(mergeObjectsDeep(...(n.causes??[]).map(e=>e.meta),n.cause?.meta,n.meta,n),`_ctor`,`name`,`message`,`stack`,`code`,`codes`,`errno`,`syscall`,`path`,`cause`,`causes`,`retriable`,`ignorable`,`internal`,`fatal`,`doNotSend`,`flags`,`meta`),this.message=stripErrorFlags(mkMessage(e,this))+a.join(``);let f=n.stack??this.stack;if(f==null){let e=Error();Error.captureStackTrace(e),f=e.stack}let h=f?.split(`
|
|
32
|
+
`)??[];for(let e of r)`stack`in e&&h.push(...toS(e.stack).split(`
|
|
33
|
+
`));filterInPlace(h,e=>!blank(e)&&!e.trim().startsWith(`at new WrappedError`)&&!e.trim().startsWith(`at toWrappedError`));let _=new Set,y=[];for(let e=h.length-1;e>=1;e--)_.has(h[e])||(_.add(h[e]),y.unshift(h[e]));this.stack=h[0]+`
|
|
34
|
+
`+y.join(`
|
|
35
|
+
`)}get fatal(){return this.message.includes(FatalErrorFlag)&&!this.message.includes(NonFatalErrorFlag)}get internal(){return this.message.includes(InternalErrorFlag)?!0:void 0}get retriable(){return this.message.includes(RetriableErrorFlag)?!0:!this.message.includes(NonRetriableErrorFlag)&&void 0}get ignorable(){return this.message.includes(NonIgnorableErrorFlag)?!1:this.message.includes(IgnorableErrorFlag)?!0:void 0}get doNotSend(){return this.message.includes(DoNotSendErrorFlag)?!0:!this.message.includes(PleaseSendErrorFlag)&&void 0}get flags(){return extractErrorFlags(this.message)}[import_node_util4.inspect.custom](){return this.stack}toString(){return(IgnoredErrorNames.includes(this.name)?``:this.name+ErrorDelimiter)+this.message}toJSON(){return pick(this,`name`,`message`,`stack`,`ignorable`,`retriable`,`fatal`,`doNotSend`,`code`,`codes`,`errno`,`syscall`,`path`,`flags`)}static fromJSON(n){return new e(n.message,omit(n,`message`))}},errorRate=new Rate,internalErrorRate=new Rate,lastInternalErrors=new BoundedList(10);function toErrors(...e){return compact(toA(e).map(toError))}function splitErrorMessage(...e){if(isEmpty(e))return[];let n=compact(e).flatMap(e=>isError(e)?getErrorDescriptions(e):isString(e)?e:isBuffer(e)?e.toString():isObject(e)?splitErrorMessage(...Object.values(e)):toS(e));return uniqSubstrings(normalizeErrorMessages(flatten([...e.filter(isError).map(errorName),...e.map(errorCode),...compactBlanks(n).map(stripAnsiEsc).flatMap(e=>splitCompactLines(e)).flatMap(e=>e.split(ErrorDelimiter))])))}function normalizeErrorMessages(e){return compact(e).filter(e=>!IgnoredErrorNames.includes(e)).map(e=>e.replace(/\s+/g,` `).trim().replace(/^code ([A-Z]+)$/i,`$1`).trim()).filter(notBlank)}function joinErrorMessages(e,n){let r=uniq(normalizeErrorMessages(e)),a=n?.maxLen??400,o=n?.trailingChars??64,s=sortErrorFlags([...n?.flags??[],...extractErrorFlags(e.join(``))]);return ellipsize(stripErrorFlags(r.join(ErrorDelimiter)),a-s.length,o)+s.join(``)}function errorToS2(e,n){return blank(e)?``:e instanceof WrappedError?e.toString():joinErrorMessages(splitErrorMessage(e),n)}var MissingError=`(missing error)`;function errorToVerbose(e,n=256,r=7){return blank(e)&&(e=MissingError),errorToS2(e,{maxLen:n})+` at `+shortStack(e?.stack,r).join(`; `)}function stripErrorFlags(e){return toS(e).replace(ErrorFlagsRE,``).trim()}function extractErrorFlags(e){return ErrorFlags.values.filter(n=>e.includes(n))}function isHealthCheckError(e){return errorToS2(e).includes(HealthCheckErrorFlag)}function isPleaseSendError(e){return errorToS2(e).includes(PleaseSendErrorFlag)}var notIgnorablePatternRE=orRegExpPatterns([NonIgnorableErrorFlag,/Can't write [a-z\d]+ files/i]),ignorablePatternsRE=orRegExpPatterns(compact([IgnorableErrorFlag,`AbortError`,`debugger attached`,`debugger listening on`,`diskutil: interrupted`,`ECONNABORTED`,`ECONNRESET`,`ECONNREFUSED`,`EAI_AGAIN`,`ENOTFOUND`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`EPIPE`,`ERR_STREAM_DESTROYED`,`for help`,`Format error in file`,`https://nodejs.org/en/docs/inspector`,`Missing expected status message`,`net::ERR_`,`System.Net.WebException`,`The network connection was lost`,`The remote name could not be resolved`,`Unable to connect to the remote server`,`This socket has been ended by the other party`,`Unexpected error while trimming`,`Unsupported file format or not RAW file`,isTest()?/PS_FAIL_VOLUMES|throwIfInvalidFile_/:void 0,/\bwarning\b/i]),`i`);function isIgnorableError(e){if(e==null)return!0;let n=e?.ignorable;if(typeof n==`boolean`)return n;let r=errorToS2(e);return notIgnorablePatternRE.test(r)?!1:r.includes(`BatchCluster has ended`)?!!ending():ignorablePatternsRE.test(r)?!0:void 0}var BusyErrorRe=/SQLITE_BUSY|database is locked|busy executing a query/i;function isSqliteBusyError(e){return e!=null&&(toS(e?.code).startsWith(`SQLITE_BUSY`)||BusyErrorRe.test(errorToS2(e)))}function isSqliteDisconnectedError(e){return/database .+ not open/i.test(errorToS2(e))}var SqliteConstraintRe=/SQLITE_CONSTRAINT|constraint failed/i;function isSqliteConstraintError(e){return toS(e?.code).startsWith(`SQLITE_CONSTRAINT`)||SqliteConstraintRe.test(errorToS2(e))}var TimeoutRE=/time[d -]?out/i;function isTimeoutError2(e){return e instanceof TimeoutError||TimeoutRE.test(errorToS2(e))}function isRetriableError(e){if(e==null)return;if(isNonRetriableError(e)===!0)return!1;let n=e?.retriable;if(typeof n==`boolean`)return n;if(errorCode(e)===`EBUSY`||isSqliteBusyError(e)||isSqliteDisconnectedError(e))return!0;let r=errorToS2(e);return r.includes(`EBUSY`)||r.includes(RetriableErrorFlag)?!0:void 0}function isNonRetriableError(e){return isFalse(e?.retriable)||isAbortError(e)||errorToS2(e).includes(NonRetriableErrorFlag)||isSqliteConstraintError(e)?!0:void 0}var PermissionErrorRegex=/\bEPERM\b|\bEACCES\b|operation not permitted|preserving permissions|permission denied/i;function isPermissionError(e){if(e==null)return!1;let n=errorCode(e);return n===`EPERM`||n===`EACCES`||PermissionErrorRegex.test(errorToS2(e))}function isVolumeGoneError(e){if(e==null)return!1;let n=errorCode(e);return n===`ENOENT`||n===`ENOTDIR`||n===`ENXIO`||n===`ENODEV`||n===`EIO`||n===`ESTALE`}var corruptMediaPatterns=[`Corrupt JPEG data`,`Premature end of JPEG file`,`VipsJpeg`,`VipsPng`,`VipsHeif`,`VipsTiff`,`VipsWebp`,`Invalid data found when processing input`,`error while decoding`,`moov atom not found`,`Corrupted data or unexpected EOF`,`File format error`],corruptMediaRegExps=[/Cannot unpack\b.*?: *(?:Input\/output error|Corrupted data or unexpected EOF)/i],corruptMediaMatcher=new SubstringMatcher(corruptMediaPatterns),outputWriteFailureMatcher=new SubstringMatcher([`unable to write to target`]);function isCorruptMediaError(e){let n=errorToS2(e);return!outputWriteFailureMatcher.test(n)&&(corruptMediaMatcher.test(n)||corruptMediaRegExps.some(e=>e.test(n)))}var doNotSendMatcher=new SubstringMatcher([DoNotSendErrorFlag,`ENOSPC`,...corruptMediaPatterns]);function isDoNotSendError(e){let n=e?.doNotSend;if(typeof n==`boolean`)return n;if(isPleaseSendError(e))return!1;if(doNotSendMatcher.test(errorToS2(e))||isCorruptMediaError(e))return!0}function isFatalError(e){if(e==null)return!1;if(isTrue(e.fatal))return!0;let n=errorToS2(e);return n.includes(FatalErrorFlag)?!0:!n.includes(NonFatalErrorFlag)&&FatalErrorRe.test(n)}function isInternalError(e){return e==null?!1:isTrue(e.internal)||isTrue(e.internalError)||InternalErrorRe.test(errorToS2(e))}var IgnorableFrameRE=/logger|lazy|defer/i,ContextualLogger=class e{constructor(e,n=rootLoggers,r=new Abortable,a){this.loggers=n,this.abortable=r,this.defaultMeta=a,this.context=toNotBlank(e)??shortStack().find(e=>!IgnorableFrameRE.test(e))??``}loggers;abortable;defaultMeta;context;get aborted(){return this.abortable.aborted}abort(e){this.abortable.abort(e)}toLogJSON(){return`CtxLogger(`+this.context+`)`}[import_node_util5.inspect.custom](){return this.toLogJSON()}child(n){return new e(this.context+n,this.loggers,this.abortable,this.defaultMeta)}throwIfAborted_(e){ending()&&this.throw(new AbortError(`throwIfAborted_(): ending`),{logLevel:`warn`});try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log(isIgnorableError(e)===!0?`debug`:`warn`,`throwIfAborted_()`,{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log(isIgnorableError(e)===!0?`debug`:`warn`,`awaitOrAbort()`,{error:e}),e}}resetAbortable(){this.abortable.aborted&&(this.abortable=new Abortable)}throw(e,n){let r=e instanceof Error&&isEmptyObj(omit(n??{},`logLevel`))?e:toWrappedError(e,{...this.defaultMeta,...n,message:this.context}),a=isIgnorableError(r),o=isDoNotSendError(r);throw blank(r.stack)&&Error.captureStackTrace?.(r),this.log(n?.logLevel??(a===!0||o===!0?`warn`:`error`),`.throw() `+r.message,{stack:r.stack,...omit(n??{},`name`)}),r}tap(e){let n=e.level??maxSevereLevel(LogLevels.debug,e.meta?.error==null?void 0:`warn`,gt0(e.meta?.elapsedMs)?msToLevel(e.meta.elapsedMs):void 0);return this.log(n,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){let n=performance.now(),r;try{r=setTimeout(()=>this.log(`warn`,`slow: `+e.msg),ShortCommandTimeoutMs);let a=e.result(),o=roundMs(performance.now()-n);return this.tap({level:o>500?`info`:e.level,msg:e.msg,result:a,meta:{...e.meta,elapsedMs:o}})}catch(n){throw this.log(`error`,`error: `+e.msg,{error:n,...e.meta}),n}finally{map(r,clearTimeout)}}async tapAsync_(e){try{let n=performance.now(),r=await thenOrTimeoutError(e.result,e.timeoutMs),a=roundMs(performance.now()-n);return this.tap({...e,result:r,meta:gt0(a)?{...e.meta,elapsedMs:a}:e.meta})}catch(n){throw n instanceof WrappedError||this.log(e.errorLevel??(isIgnorableError(n)||isDoNotSendError(n)?`warn`:`error`),`error: `+(e.errorMsg??e.msg),{error:n,...e.meta}),n}}isEnabled(e,n){for(let r of this.loggers())if(r.isEnabled(e,n??this.context))return!0;return!1}isDebugEnabled(e){return this.isEnabled(LogLevels.debug,e??this.context)}log(e,n,r){this.defaultMeta!=null&&(r==null?r={...this.defaultMeta}:typeof r==`object`&&!Array.isArray(r)&&(r={...this.defaultMeta,...r}));for(let a of this.loggers())a.log(e,this.context,n,r)}_logEntry(e){for(let n of this.loggers())n._logEntry(e)}elapsed(e,n){this.log(maxSevereLevel(msToLevel(n.elapsedMs),n.level),e,n)}async maybeFlush(){for(let e of this.loggers())await e.maybeFlush()}fatal(e,n){this.log(`fatal`,e,n)}error(e,n){this.log(`error`,e,n)}warn(e,n){this.log(`warn`,e,n)}info(e,n){this.log(`info`,e,n)}debug(e,n){this.log(`debug`,e,n)}trace(e,n){this.log(`trace`,e,n)}deprecate(e,n){this.warn(`${e} is deprecated, use ${n} instead`)}},rootLoggers=defer(()=>[ConsoleLogger.instance()]);function mkLogger(e,n){return new ContextualLogger(e,rootLoggers,void 0,n)}var consoleLogger=defer(()=>[ConsoleLogger.instance()]);function mkConsoleLogger(e){return new ContextualLogger(e,consoleLogger)}var import_node_process6=__toESM(require("node:process")),PromiseStates=strEnum(`pending`,`resolved`,`rejected`);function isDeferred(e){return typeof e==`object`&&!!e&&e instanceof Deferred}var Deferred=class e{constructor(e){this.id=e,this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}id;static observe(n){return new e().observe(n)}[Symbol.toStringTag]=`Deferred`;promise;startedAt=Date.now();settledAt=void 0;_resolve;_reject;_state=PromiseStates.pending;get state(){return this._state}get elapsedMs(){return(this.settledAt??Date.now())-this.startedAt}isPending(){return this._state===PromiseStates.pending}isResolved(){return this._state===PromiseStates.resolved}isRejected(){return this._state===PromiseStates.rejected}isSettled(){return!this.isPending()}then(e,n){return this.promise.then(e,n)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}resolve(e){return!this.isSettled()&&(this._state=PromiseStates.resolved,this.settledAt??=Date.now(),this._resolve(e),!0)}reject(e){return!this.isSettled()&&(this._state=PromiseStates.rejected,this.settledAt??=Date.now(),this._reject(e),!0)}async observeFn(e){try{let n=await e();return this.resolve(n),n}catch(e){throw this.reject(toError(e)),e}}observe(e){return e.then(e=>this.resolve(e),e=>this.reject(e)),this}observeQuietly(e){return e==null?this.resolve(void 0):e.then(e=>this.resolve(e),()=>this.resolve(void 0)),this}toJSON(){return{$ctor:`fe.Deferred`,...this.id==null?{}:{id:this.id},state:this._state,elapsedMs:this.elapsedMs}}},import_node_timers2=__toESM(require("node:timers"));function serialized(e){return new Serialized(e)}var Serialized=class extends ExtensibleFunction{constructor(e){super(),this.fn=e}fn;#e;#t;#n;_call(...e){return this.#t==null?this.#e==null?this.#i(e):(this.#n=e,this.#t=this.#r(),this.#t):(this.#n=e,this.#t)}async#r(){try{await this.#e}catch{}let e=this.#n;return this.#t=void 0,this.#n=void 0,this.#i(e)}#i(e){return this.#e=(async()=>{try{return await this.fn(...e)}finally{this.#e=void 0}})(),this.#e}ifIdle(...e){return this.isIdle()?this(...e):void 0}isIdle(){return this.#e==null&&this.#t==null}};function trailingThrottle(e){return new TrailingThrottle(e.fn,e.minDelayMs)}var TrailingThrottle=class extends ExtensibleFunction{#e;#t;#n=0;#r;#i=void 0;constructor(e,n){super(),this.#t=n,this.#e=serialized(async(...n)=>(this.#n=performance.now(),e(...n)))}get applying(){return!this.#e.isIdle()}#a=async()=>{let e=this.#t-(performance.now()-this.#n);if(e>0&&e<=this.#t){this.#r=import_node_timers2.default.setTimeout(this.#a,Math.ceil(e)+1);return}let n=this.#i;if(this.#i=void 0,this.#r=void 0,n!=null)try{await this.#e(...n)}catch{}};_call(...e){if(!gt0(this.#t))return this.#e(...e);let n=performance.now()-this.#n;if(n>this.#t&&!this.applying&&this.#r==null)return this.#e(...e);this.#i=e,this.#r??=import_node_timers2.default.setTimeout(this.#a,Math.max(1,1+this.#t-n))}reset(){this.#r!=null&&import_node_timers2.default.clearTimeout(this.#r),this.#r=void 0}minDelayMs(){return this.#t}},TTLSet=class{constructor(e,n=!1){this.ttlMs=e,this.scheduleExpirationTimers=n}ttlMs;scheduleExpirationTimers;[Symbol.toStringTag]=`TTLSet`;expireListeners=[];delegate=new Map;get size(){return this.#t(),this.delegate.size}add(e){return this.delegate.set(e,performance.now()),this.scheduleExpirationTimers&&setUnrefTimeout(()=>this.#t(),this.ttlMs+1),this}addAll(e){for(let n of e)this.add(n)}addIfMissing(e,n){let r=this.delegate.get(e);if(r==null||this.#e(e,r))return this.add(e),n()}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(let[n,r]of this.delegate)this.#e(n,r)||e(n,n,this)}has(e){return e!=null&&!this.#e(e)}*values(){for(let[e,n]of this.delegate)this.#e(e,n)||(yield e)}keys=this.values.bind(this);*entries(){for(let[e,n]of this.delegate)this.#e(e,n)||(yield[e,e])}toA(){return this.#t(),[...this.delegate.keys()]}[Symbol.iterator](){return this.values()}on(e,n){this.expireListeners.push(n)}#e(e,n){if(n??=this.delegate.get(e),n==null||!this.delegate.has(e))return!0;let r=n<=performance.now()-this.ttlMs;if(r){this.delegate.delete(e);for(let n of this.expireListeners)n(e)}return r}#t(){for(let[e,n]of this.delegate)this.#e(e,n)}},logger=defer(()=>mkLogger(`event.TypedEventEmitter`)),FunctionWrapper=class{constructor(e,n){this.fn=e,this.once=n}fn;once},EventThrottleMs=50;function throttleFor(e,n,r,a){return getOrSet(getOrSet(e,n,()=>new Map),JSON.stringify(r),()=>trailingThrottle({fn:a,minDelayMs:EventThrottleMs}))}function resetThrottles(e){for(let n of e.values())for(let e of n.values())e.reset();e.clear()}var TypedEventEmitterImpl=class{listeners=new MultiMap;#e=new TTLSet(EventThrottleMs);once(e,n){return this.listeners.add(e,new FunctionWrapper(n,!0)),this}waitOnce(e){let n=new Deferred;return this.once(e,(...e)=>n.resolve(e)),n}on(e,n){return this.listeners.add(e,new FunctionWrapper(n,!1)),this}off(e,n){let r=this.listeners.get(e)??[];for(let e of r)e.fn===n&&removeSame(r,e);return this}async emit(e,...n){if(ending())return!1;this.#e.add(e);let r=!1,a=this.listeners.get(e)??[];for(let o of a){o.once&&removeSame(a,o);try{await o.fn(...n)}catch(n){logger().warn(`TypedEventEmitterImpl listener failed`,{eventName:e,error:n})}r=!0}return r}emitSync(e,...n){if(ending())return!1;this.#e.add(e);let r=!1,a=this.listeners.get(e)??[];for(let o of a){o.once&&removeSame(a,o);try{o.fn(...n)}catch(n){logger().warn(`TypedEventEmitterImpl listener failed`,{eventName:e,error:n})}r=!0}return r}emitRateLimited(e,...n){return this.#e.has(e)?void 0:this.emit(e,...n)}emitSyncRateLimited(e,...n){return this.#e.has(e)?void 0:this.emitSync(e,...n)}#t=new Map;emitThrottled(e,...n){throttleFor(this.#t,e,n,(...n)=>this.emit(e,...n))(...n)}clear(){this.removeAllListeners(),this.#e.clear(),resetThrottles(this.#t)}removeAllListeners(e){return e==null?this.listeners.clear():this.listeners.delete(e),this}listenerCount(e){return this.listeners.get(e)?.length??0}},CapturingEventEmitter=class extends TypedEventEmitterImpl{constructor(e=isTest()?10:0){super(),this.eventsToRetain=e,this.priorEvents=e>0?new BoundedList(e):void 0}eventsToRetain;priorEvents;#e(e,...n){this.eventsToRetain>0&&this.priorEvents?.push({event:e,args:n})}emit(e,...n){return this.#e(e,...n),super.emit(e,...n)}emitSync(e,...n){return this.#e(e,...n),super.emitSync(e,...n)}},ee=defer(()=>new CapturingEventEmitter);ee.reset=()=>{throw Error(`ee.reset() is not allowed`)};var ReadyStr=JSON.stringify({ready:!0});function stdoutWrite(e,n){return writeTTY({obj:e,ready:n,stream:import_node_process6.default.stdout})}function stderrWrite(e){return writeTTY({obj:e,stream:import_node_process6.default.stderr})}function writeTTY({obj:e,ready:n,stream:r}){if(r==null||streamEnded(r))return;let a=stringify(e,isInfoService()||isMainService()?2:void 0);r.write(a+`
|
|
36
|
+
`),isWorkerService()&&n!=null&&(a.includes(FailStr)||isFatalError(a)||isHealthCheckError(a)?r.write(FailStr+`
|
|
37
|
+
`):r.write(ReadyStr+`
|
|
38
|
+
`))}var import_node_child_process=require("node:child_process"),import_node_process7=__toESM(require("node:process"));function sdNotifyAvailable(){return isLinux&&import_node_process7.default.env.NOTIFY_SOCKET!=null}function sdNotifyStopping(){sdNotifySync(`STOPPING=1`)}var sdNotifyVersion=lazy2(()=>{if(isLinux)try{return(0,import_node_child_process.execFileSync)(`systemd-notify`,[`--version`],{timeout:2e3}).toString().split(`
|
|
39
|
+
`)[0]?.trim()}catch{return}});function sdNotifySync(...e){if(sdNotifyAvailable())try{(0,import_node_child_process.execFileSync)(`systemd-notify`,e,{timeout:1e3})}catch{}}var CaseInsensitiveMap=class{constructor(e=[],n=NoBlanksStringNormalizer){this.normalizer=n;for(let[n,r]of e)this.set(n,r)}normalizer;store=new Map;get(e){let n=this.normalizer(e);return n==null?void 0:this.store.get(n)?.[1]}lookup(e){let n=this.normalizer(e);return n==null?void 0:this.store.get(n)}has(e){let n=this.normalizer(e);return n!=null&&this.store.has(n)}set(e,n){let r=this.normalizer(e);return e!=null&&r!=null&&this.store.set(r,[e,n]),this}clear(){this.store.clear()}delete(e){let n=this.normalizer(e);return n!=null&&this.store.delete(n)}forEach(e){this.store.forEach(n=>e(n[1],n[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){let n={};for(let r of e){let e=this.lookup(r);e!=null&&(n[e[0]]=e[1])}return n}},import_node_crypto=require("node:crypto"),zero=BigInt(0);function encodeDigits(e,n,r=0){if(!isFinite(n)||e<=1)return[];let a=[];if(n===0)a.unshift(0);else for(;n>0;)a.unshift(n%e),n=Math.floor(n/e);for(;a.length<r;)a.unshift(0);return a}var Radix=class{constructor(e,n,r=identity){this.name=e,this.numerals=n,this.decodePreparser=r,this.base=n.length}name;numerals;decodePreparser;base;digitsToNumerals(e){return e.map(e=>this.numerals[e]).join(``)}encode(e,n=0){if(!isFinite(e))return``;let r=e<0;return r&&(e=Math.abs(e),n--),(r?`-`:``)+this.digitsToNumerals(encodeDigits(this.base,e,n))}encodeBigInt(e){if(typeof e!=`bigint`)throw Error(`bad input`);if(e===zero)return this.numerals[0];let n=[],r=BigInt(this.base),a=e;for(;a>zero;)n.push(Number(a%r)),a/=r;return this.digitsToNumerals(n.reverse())}encodeBuffer(e){if(e==null||e.length===0)return``;let n=[0];for(let r of e)for(n.forEach((e,a)=>{r+=e<<8,n[a]=r%this.base,r=Math.floor(r/this.base)});r>0;)n.push(r%this.base),r=Math.floor(r/this.base);return this.digitsToNumerals(n.reverse())}decode(e){return map(this.decodeBigInt(e),n=>{if(n>BigInt(2**53-1))throw Error(`decode(`+e+`) is > 2^53`);return Number(n)})}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(e==null||blank(e))return;e=isFunction(this.decodePreparser)?this.decodePreparser(e):e;let n=e[0]===`-`;n&&(e=e.slice(1));let r=BigInt(this.base),a=BigInt(0);for(let n of e){let e=this.numerals.indexOf(n);if(e<0)return;a=a*r+BigInt(e)}return n?BigInt(-1)*a:a}randomChars(e){let n=``;for(let r=0;r<e;r++)n+=this.numerals[(0,import_node_crypto.randomInt)(this.base)];return n}randomUid(e=20,n=5,r=`-`){return splitEvery(this.randomChars(e),n).join(r)}tokenEql(e,n,r){let a=this.normalizeToken(e),o=this.normalizeToken(n);return a.length>=r&&a===o}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter(e=>this.numerals.includes(e)).join(``)}},Hex=new Radix(`hex`,`0123456789abcdef`,e=>e.toLowerCase()),Radix58=new Radix(`Radix58`,`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`),Base64=new Radix(`Radix64`,`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`),Radix36=new Radix(`Radix36`,`0123456789abcdefghijklmnopqrstuvwxyz`,e=>e.toLowerCase()),GeoRadix=new Radix(`GeoRadix`,`0123456789bcdefghjkmnpqrstuvwxyz`,e=>e.toLowerCase()),TokenRadix=new Radix(`TokenRadix`,`0123456789abcdefghjkmnpqrtuvwxyz`,e=>e.toLowerCase().replace(/o/g,`0`).replace(/[il]/g,`1`).replace(/s/g,`5`)),AlphaRadix=new Radix(`AlphaRadix`,`abcdefghjkmnopqrtuvwxyz`,e=>e.toLowerCase().replace(/0/g,`o`).replace(/2/g,`z`).replace(/5/g,`s`).replace(/9/g,`g`)),NumericRadix=new Radix(`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`));function firstGt0(...e){return e.find(gt0)}function firstNonZero(...e){for(let n of flatten(e)){let e=toFloat(n);if(e!=null&&e!==0)return e}}function mapGte0(e,n){return mapInt(e,e=>e>=0?n(e):void 0)}function mapGt0f(e,n){let r=toFloat(e);return r!=null&&r>0?n(r):void 0}function mapGt0(e,n){let r=toInt(e);return r!=null&&r>0?n(r):void 0}function map2Gt0(e,n,r){let a=toInt(e),o=toInt(n);return a!=null&&a>0&&o!=null&&o>0?r(a,o):void 0}var numstartRe=/[+-]?[\d,.]+/;function extractFloat(e){if(isNumber(e))return e;if(blank(e))return;let n=String(e);return map(numstartRe.exec(n),e=>toFloat(n.substr(e.index)))}function extractInt(e){return toInt(extractFloat(e))}var fracSepRE=/[:/]/;function extractFraction(e){if(isNumber(e)||e==null)return e;if(fracSepRE.test(e)){let n=toS(e).split(fracSepRE,2);return map2Numeric(extractFloat(n[0]),extractFloat(n[1]),(e,n)=>e/n)}return extractFloat(e)}function asSet(e){return e instanceof Set?e:new Set(toA(e))}function intersection2(e,n){let r=asSet(n);return new Set([...e].filter(e=>r.has(e)))}function diff2(e,n){let r=asSet(n);return new Set([...e].filter(e=>!r.has(e)))}function hamming(e,n){if(e==null||n==null)return;if(e===n)return 0;let r=_hamming(e,n);if(r!=null)return r;let a=e.normalize(),o=n.normalize();return e!==a||n!==o?_hamming(a,o):void 0}function _hamming(e,n){return e.length===n.length?[...e].reduce((e,r,a)=>r===n.charAt(a)?e:e+1,0):void 0}function diceCoeff2(e,n){let r=e.toUpperCase().normalize(),a=n.toUpperCase().normalize();return firstThunk(()=>r===a?1:void 0,()=>blank(e)===blank(n)?void 0:0,()=>e.length===1&&n.length===1?0:void 0,()=>{let e=bigrams(r),n=bigrams(a);return 2*nonUniqIntersection(e,n).length/(e.length+n.length)})}function bigrams(e){if(e==null||e.length===0)return[];let n=[...e];return n.slice(0,-1).map((e,r)=>e+n[r+1])}function nonUniqIntersection(e,n){let r=intersection2(e,n),a=[];return r.forEach(r=>{times(Math.min(count(e,e=>e===r),count(n,e=>e===r)),()=>a.push(r))}),a}function lcdiff(e){return count([...e.normalize()],e=>e.toLowerCase().localeCompare(e)!==0)}var CaseInsensitiveValued=class{constructor(e,n=()=>void 0){this.obj=e,this.synonyms=n,this.m=new MultiMap,this.rebuild()}obj;synonyms;m;rebuild(){this.m.clear();for(let[e,n]of entries(this.obj))for(let r of uniq([e,...toA(this.synonyms(e,n))].map(e=>e.toLowerCase())))this.m.add(r,e);this.m.vacuum()}lookup(e){if(e!=null){{let n=this.obj[e];if(n!=null)return{key:e,value:n}}for(let n of this.m.get(e.toLowerCase())??[]){let e=this.obj[n];if(e!=null)return{key:n,value:e}}}}findKeys(e){return this.m.get(e.toLowerCase())??[]}lookupNearest(e,n=.4){let r=this.lookup(e);if(r!=null)return r;let a=-1,o;for(let[r,s]of this.m.entries()){let c=diceCoeff2(r,e);if(c>n&&c>a){let e=this.getFirst(s);e!=null&&(o=e,a=c)}}return o}get(e){return this.lookup(e)?.value}set(e,n){this.obj[e]=n,this.rebuild()}getFirst(e){if(e!=null)for(let n of e){let e=this.lookup(n);if(e!=null)return e}}delete(e){let n=toS(e).toLowerCase(),r=this.m.get(n)??[];for(let e of r)delete this.obj[e];return this.m.delete(n),r}pick(...e){let n={};for(let r of e){let e=this.lookup(r);e?.key!=null&&(n[e.key]=e.value)}return n}},AggregationModes=strEnum(`default`,`strict`,`lenient`,`manual`),AssetFileSortCriteria=strEnum(`resolution`,`isBrowserSupported`,`mimetype`,`schemeIdx`,`metadataDate`,`capturedAtPrecisionMs`,`isEditOrUpdate`,`isCover`,`fileSize`,`sha`,`uri`,`count`,`mtime`,`basename`,`parentBasename`),import_node_fs=require("node:fs"),import_node_util6=require("node:util");function shallowClone(e){return e==null?e:Array.isArray(e)?[...e]:typeof e==`object`?{...e}:e}function fmtList(e,n){return e=uniq(compactBlanks(e)),e==null||e.length===0?``:e.length===1?e.join(``):e.slice(0,-1).join(`, `)+` `+n.trim()+` `+e[e.length-1]}function orList(e){return fmtList(e,`or`)}function andList(e){return fmtList(e,`and`)}var ByteOrderMarks=[{bom:[239,187,191],encoding:`utf8`},{bom:[255,254],encoding:`utf16le`}];function debom(e){for(let{bom:n,encoding:r}of ByteOrderMarks)if(n.every((n,r)=>e[r]===n))return e.subarray(n.length).toString(r);return e.toString()}var ciEnv=lazy2(()=>new CaseInsensitiveValued(process.env));function handleDeprecatedEnv(){process.env.PS_LICENSE===`lite`&&(process.env.PS_FORCE_LITE=`true`,delete process.env.PS_LICENSE)}function camel2snake(e){return toS(e).replace(/([A-Z])([a-z])/g,(e,n,r)=>`_`+n.toLowerCase()+r).replace(/[A-Z]+|\d+/g,e=>`_`+e).replace(/^_/,``).replace(/_+/g,`_`)}function camel2words(e){return toS(e).replace(/([A-Z])([a-z])/g,(e,n,r)=>` `+n.toLowerCase()+r).replace(/[A-Z]+|\d+/g,e=>` `+e).trim()}function envFromName(e){return ensurePrefix(camel2snake(e).toUpperCase(),`PS_`)}var SettingCategories=strEnum(`Paths`,`Desktops`,`Filesystem`,`Cache`,`Logging`,`Networking`,`Processes`,`Security`,`Tools`,`Update`,`Hardware`,`Performance`,`Aggregation`,`Auth`,`Color`,`Db`,`Email`,`Filters`,`Health`,`OIDC`,`Organization`,`Parsing`,`Previews`,`Privacy`,`Reporting`,`Sidecars`,`Subscription`,`Sync`,`Tagging`,`Video`,`Volumes`,`Web`),LibraryCategories=Object.freeze([SettingCategories.Aggregation,SettingCategories.Auth,SettingCategories.Color,SettingCategories.Db,SettingCategories.Email,SettingCategories.Filters,SettingCategories.Health,SettingCategories.OIDC,SettingCategories.Organization,SettingCategories.Parsing,SettingCategories.Previews,SettingCategories.Privacy,SettingCategories.Reporting,SettingCategories.Sidecars,SettingCategories.Subscription,SettingCategories.Sync,SettingCategories.Tagging,SettingCategories.Video,SettingCategories.Volumes,SettingCategories.Web].sort()),SystemCategories=Object.freeze(SettingCategories.values.filter(e=>!LibraryCategories.includes(e)).sort()),SettingCategoryDescriptions=Object.freeze({Paths:`Specifies file system paths for library, previews, originals, cache, and scan locations.`,Desktops:`Controls behavior specific to PhotoStructure for Desktops (Electron), ignored by Server editions.`,Email:`Configures the outgoing mail server that sends email sign-in codes.`,OIDC:`Configures the OpenID Connect provider that signs library users in.`,Filesystem:`Controls file system interaction including change detection, timeouts, and mount point validation.`,Cache:`Controls caching behavior for computationally expensive operations and file conversions.`,Logging:`Controls diagnostic log output including levels, destinations, formatting, and filtering.`,Networking:`Controls network connectivity including ports, hostnames, and network modes.`,Processes:`Controls process spawning, concurrency, resource limits, and subprocess management.`,Security:`Manages web service access controls, HTTPS enforcement, and security headers.`,Tools:`Configures external tools and utilities for file operations and image processing.`,Hardware:`Monitors hardware temperature and sensor health to pause operations if overheating.`,Performance:`Controls performance diagnostics and function timing for analysis and debugging.`,Aggregation:`Controls how files are grouped into assets using image hashing, metadata comparison, and temporal matching, and how the best asset variation is selected from grouped files.`,Auth:`Controls library access and user authorization.`,Color:`Configures color detection, dominant color extraction, and monochrome classification.`,Db:`Configures SQLite database performance, reliability, backup retention, and recovery.`,Filters:`Specifies criteria for which files and formats to include or exclude during import.`,Health:`Configures which automated health checks to skip when validating library integrity.`,Organization:`Determines how and where PhotoStructure organizes imported photos and videos.`,Parsing:`Controls metadata extraction from media files including dates, titles, and descriptions.`,Previews:`Configures preview image and thumbnail generation, resolution, and compression.`,Privacy:`Controls external network requests for version checks, error reporting, and telemetry.`,Reporting:`Configures crash reporting, error tracking, and contact information for support.`,Sidecars:`Configures detection, reading, and writing of metadata sidecar files.`,Subscription:`Manages license validation, plan selection, and automatic license renewal.`,Sync:`Controls file import and synchronization scheduling, behavior, and performance.`,Tagging:`Controls automatic tag assignment from metadata, filenames, geolocation, and face regions.`,Update:`Controls automatic update checking and settings file migration.`,Video:`Configures video transcoding behavior, codec support, and FFmpeg options.`,Volumes:`Manages volume identification and metadata caching for cross-host library portability.`,Web:`Configures web UI behavior, rendering performance, and OpenGraph metadata.`});function escapeSmartQuotes(e){return e.replace(SmartQuotes,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function stringifyToml(e){return flatten(entries(e).map(([e,n])=>kvToToml(e,n)))}function kvToToml(e,n,r){if(blank(e))throw Error(`kvToToml(): Blank key`);let a=e+` = `+escapeSmartQuotes(stringifyPretty(n));return blank(r?.prefix)?[a]:wrap(a.split(`
|
|
40
|
+
`),r)}function wrapTomlToLines(e){return blank(e.key)||e.value==null||(e.prepend!=null&&e.lines.push(...wrap([``,...e.prepend],e.wrap)),e.lines.push(...kvToToml(e.key,e.value,e.wrap))),e.lines}var WrapComments={maxLineLen:78,prefix:`# `},DefaultEnvKeySuffix=`_DEFAULT`,FileEnvKeySuffix=`_FILE`,DeprecatedNote=`NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.`,BlankIsValueNote=`NOTE: unlike most settings, a blank value is honored here rather than ignored, and turns this setting off. (Every other setting treats a blank as unset, so another configured value or the built-in default remains in effect.)`;function settingsToLogObj(e){let n={};for(let r of e)r.hasValue()&&(n[r.name]=r.isSensitive()?`(hidden)`:r.value);return n}var Setting=class{constructor(e){this.opts=e,isTest()&¬Blank(e.name)&&this._setName(e.name),e.onChange!=null&&this.watch(e.onChange)}opts;_name;_names;_key;_keys;_testValue;_cliValue;_envValue=lazy2(()=>this.readFromEnv());#e=lazy2(()=>this.readDefaultFromEnv());_userValue;_fileValue;_invalidFileInputPresent=!1;watchers=[];optsOverrides={};isSensitive(){return this.opts.sensitive===!0}shouldRedactInvalidValue(){return this.isSensitive()||this.opts.redactInvalidValue===!0}getState(){return{user:this._userValue,cli:this._cliValue,env:this.envValue,file:this._fileValue,test:this._testValue}}[import_node_util6.inspect.custom](){return this.dump()}dump(){return{name:this.name,key:this.key,value:this.value,...this.getState(),hasValue:this.hasValue(),isUnset:this.isUnset(),defaultValue:this.defaultValue}}toEnv(e){return this.opts.whyInvalid?.(e)==null?this.opts.toEnv(e):void 0}fromEnv(e){if(e==null)return;let n=this.opts.fromEnv(e);return n==null||this.opts.whyInvalid?.(n)!=null?void 0:n}normalizeValue(e){return blank(e)&&this.opts.blankIsValue!==!0?void 0:this.fromEnv(this.toEnv(e))}#t(e){let n=`Invalid value for setting "${this.key}"`;return this.shouldRedactInvalidValue()?n:`${n}: ${stringify(e)}`}whyInvalidValue(e){let n=this.opts.whyInvalid?.(e);return n==null?this.whyInvalidEnvValue(this.toEnv(e),e):this.#t(e)+`: `+n}whyInvalidEnvValue(e,n){let r=e==null?void 0:this.opts.fromEnv(e),a=this.opts.whyInvalid?.(r??e);return a==null?this.fromEnv(e)==null?this.#t(e??n):void 0:this.#t(e??n)+`: `+a}get testValue(){return this._testValue}set testValue(e){if(!isTest())throw Error(`${this.name}.testValue can only be set in tests (NODE_ENV=test)`);this.onChange(e,e=>this._testValue=e)}get cliValue(){return this._cliValue}set cliValue(e){this.onChange(e,e=>this._cliValue=e)}setCliValueIfUnset(e){this._cliValue??(this.cliValue=e)}isFileValueOverridden(){return this.cliValue!=null||this.envValue!=null}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.#n(e,!1)}noteInvalidFileInput(){this.#n(void 0,!0)}#n(e,n,r=!1){let a=shallowClone(this.valueOrDefault),o=this._invalidFileInputPresent;this.onChange(e,e=>{r&&(this._userValue=void 0),this._fileValue=e,this._invalidFileInputPresent=n}),o!==this._invalidFileInputPresent&&eql(this.valueOrDefault,a)&&this.broadcastChange()}hasInvalidFileInput(){return this._invalidFileInputPresent}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,e=>{e==null?this.deleteFromEnv():this.addToEnv(void 0,e),this._envValue.unset()})}refreshEnvValue(e={}){let n=shallowClone(this.valueOrDefault);this.unsetCachedEnvValue(),!0===e?.broadcastChange&&this.maybeBroadcastChange(n)}get value(){return this._testValue??this._cliValue??this._envValue()??this._userValue??this._fileValue}async withValue(e,n){let r=this._testValue,a=this._cliValue;this._testValue=void 0,this._cliValue=e;try{return await n()}finally{this._testValue=r,this._cliValue=a}}set value(e){this.userValue=e??void 0}get humanValue(){return this.value}get userValue(){return this._userValue}set userValue(e){this.onChange(e,e=>this._userValue=e)}get valueOrThrow(){let e=this.value;if(e==null)throw Error(`Missing value for setting `+this.name);return e}hasValue(){return this.value!=null}isUnset(){return this.value==null}includesEnvKey(e){return includesIgnoreCase(this.envKeys(),e)}envKeys(){return uniq([...this.keys??[],...this.opts.prefixedEnvKeysOnly===!0?[]:this.names??[]])}defaultEnvKeys(){return this.opts.envDefault===!0?(this.keys??[]).map(e=>e+DefaultEnvKeySuffix):[]}fileEnvKeys(){return this.isSensitive()?(this.keys??[]).map(e=>e+FileEnvKeySuffix):[]}includesFileEnvKey(e){return includesIgnoreCase(this.fileEnvKeys(),e)}#r(e,n=this.envKeys()){return(e==null?ciEnv():new CaseInsensitiveValued(e)).getFirst(n)}#i(e){let n=this.#r(e,this.fileEnvKeys());return n==null||blank(n.value)?void 0:n}#a(e){let n=this.#i(e);if(n==null)return;let r=n.value,a=this.#r(e);if(a!=null&&(notBlank(a.value)||this.opts.blankIsValue===!0))return{path:r,problem:`${a.key} is also set, so both are ignored. Unset one of them.`};try{return{path:r,value:debom((0,import_node_fs.readFileSync)(r)).replace(/(?:\r?\n)+$/,``)}}catch(e){return{path:r,problem:`PhotoStructure can't read "${r}" (${errorCode(e)??asError(e).message}), so it ignores this variable.`}}}whyEnvFileIgnored(e){let n=this.#a(e);if(n!=null)return n.problem==null?blank(n.value)&&this.opts.blankIsValue!==!0?`The file "${n.path}" is blank, so PhotoStructure ignores this variable.`:this.whyInvalidEnvValue(n.value):n.problem}envKeyWithValue(e){return this.#i(e)?.key??this.#r(e)?.key}rawEnvValue(e){let n=this.#a(e),r=n==null?this.#r(e)?.value:n.value;return blank(r)&&this.opts.blankIsValue!==!0?void 0:r}readFromEnv(e){return map(this.rawEnvValue(e),e=>this.fromEnv(e))}readDefaultFromEnv(e){let n=this.#r(e,this.defaultEnvKeys())?.value;return blank(n)&&this.opts.blankIsValue!==!0?void 0:map(n,e=>this.fromEnv(e))}hasEnvValue(){return this.readFromEnv()!=null}setFromEnv(e){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){e!=null&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate(()=>this.broadcastChange())}unWatch(e){filterInPlace(this.watchers,n=>n!==e)}broadcastChange(){let e=this.valueOrDefault;for(let n of this.watchers)n(e);return ee().emitThrottled(`settingsChanged`)}onChange(e,n){if(!(blank(e)&&this.opts.blankIsValue!==!0)&&e!=null){let n=this.whyInvalidValue(e);if(n!=null){console.warn(`Settings.`+this.name+` rejected value:`+n,{value:this.shouldRedactInvalidValue()?`(hidden)`:e});return}}let r=shallowClone(this.valueOrDefault);n(this.normalizeValue(e)),this.maybeBroadcastChange(r)}maybeBroadcastChange(e){return eql(this.valueOrDefault,e)?void 0:this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(this._name!=null&&e!==this._name)throw Error(`Setting name already set to `+this._name+`, cannot change to `+e);this._name=e,this._names=uniq([e,...toA(this.opts.aliases)]),this._key=envFromName(e),this._keys=uniq([this._key,...toA(this.opts.envAliases),...this._names.map(envFromName)])}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 LibraryCategories.includes(this.category)?`library`:`system`}get transient(){return this.opts.transient===!0}get propagateToChildren(){return this.opts.propagateToChildren!==!1}get advanced(){return mapOr(this.opts.advanced,e=>e(),()=>!0)}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set testValueIfUnset(e){this.isUnset()&&(this.testValue=e)}addToChildProcessEnv(e,n){let r=this._testValue??this._cliValue;if(r!=null)return this.addToEnv(e,r),e;if(this.#i()!=null)return e;let a=n?this.value:this._envValue();return a!=null&&!eql(a,this.defaultValue)&&this.addToEnv(e,a),e}get defaultValue(){return tot(this.optsOverrides.defaultValue)??this.#e()??tot(this.opts.defaultValue)}set defaultValue(e){let n=shallowClone(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(n)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return tot(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,n){let r=e??process.env,a=n??this.value;return a!=null&&(r[this.key]=this.toEnv(a)),r}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,n){let r=e??process.env,a=this.toEnvValue(n);return a!=null&&(r[this.key]=a),r}deleteFromEnv(e){let n=e??process.env;for(let e of[...this.names,...this.keys])delete n[e];return n}unsetCliValue(){this._cliValue=void 0}unsetTestValue(){this._testValue=void 0}unsetCachedEnvValue(){this._envValue.unset(),this.#e.unset()}unsetFileValue(){this.#n(void 0,!1,!0)}unset(e){return e?.preserveTestValue!==!0&&(this._testValue=void 0),this._cliValue=void 0,this.unsetCachedEnvValue(),e?.preserveEnv!==!0&&this.deleteFromEnv(),this._userValue=void 0,this._fileValue=void 0,this._invalidFileInputPresent=!1,this.broadcastChange(),this}factoryReset(){return this.unset(),this.resetDefaultValue(),this}addToJsonDocs(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}descriptionLines(){let e=this.defaultEnvKeys(),n=this.fileEnvKeys();return[...this.opts.deprecated===!0?[DeprecatedNote,``]:[],...this.opts.blankIsValue===!0?[BlankIsValueNote,``]:[],this.opts.description.replace(/\n+/g,`
|
|
41
|
+
|
|
42
|
+
`),...isEmpty(e)?[]:[``,`Set ${orList(e)} to change this setting's default. Unlike ${this.key}, it doesn't override a value saved in the app or lock this setting on the settings page.`],...isEmpty(n)?[]:[``,`To read this setting from a file, such as a Docker secret, set ${orList(n)} to the file's path. PhotoStructure removes every trailing line ending from the file's contents and keeps all spaces, including those at the start and end. If ${orList(this.keys)} also has a nonblank value, PhotoStructure ignores both.`]]}toCommentedLines(){let e=this.name+` or `+this.key,n=wrap([padding(`-`,e.length),e,padding(`-`,e.length),``,...this.descriptionLines()],WrapComments);function r(e,r){isEmpty(r)||n.push(...wrap([``,(r.length===1?e:pluralize(e))+`: `+orList(r.map(e=>stringify(e)))],WrapComments))}r(`alias`,this.opts.aliases),r(`environment alias`,this.altKeys);for(let[e,r]of entries(this.addToJsonDocs())){let a=Array.isArray(r)?orList(r.map(e=>stringify(e))):stringify(r);n.push(...wrap([``,e+`: `+a],WrapComments))}return n}toEnvLine(e){return this.key+`=`+(map(e,e=>this.toEnv(e))??this.envValueOrDefault)}toTomlLine({lines:e,value:n}={}){return wrapTomlToLines({lines:e??[],key:this.name,value:tot(n??this.fileValue)})}toTomlLines({includeValue:e=!0}={}){let n=this.toCommentedLines();return wrapTomlToLines({lines:n,wrap:WrapComments,prepend:[`Example value:`],key:this.name,value:tot(this.exampleValue)}),wrapTomlToLines({lines:n,wrap:WrapComments,prepend:[`Default value:`],key:this.name,value:tot(this.defaultValue)}),e&&this.toTomlLine({lines:n,value:this.fileValue}),n}},BooleanSetting=class extends Setting{constructor(e){super({...e,toEnv:notBlankToS,fromEnv:toBoolean})}},NoneImpl;(e=>{e.isDefined=!1,e.isEmpty=!0,e.get=()=>void 0,e.exists=()=>!1;let n=()=>e;e.map=n,e.flatMap=n,e.filter=n,e.forEach=n,e.getOrElse=e=>e(),e.orElse=e=>opt(e()),e.zip1=n,e.zip2=n,e.zip3=n})(NoneImpl||={});var None=NoneImpl,Some=class e{constructor(e){this.a=e}a;isDefined=!0;isEmpty=!1;get(){return this.a}exists(e){return e(this.a)}map(n){return new e(n(this.a))}flatMap(e){let n=e(this.a);return isOpt(n)?n:opt(n)}filter(e){return opt(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,n){return opt(e).flatMap(e=>n(this.a,e))}zip2(e,n,r){return opt(e).flatMap(e=>opt(n).flatMap(n=>r(this.a,e,n)))}zip3(e,n,r,a){return opt(e).flatMap(e=>opt(n).flatMap(n=>opt(r).flatMap(r=>a(this.a,e,n,r))))}};function isOpt(e){return e instanceof Some||e===None}function opt(e){return isOpt(e)?e:e==null?None:new Some(e)}var BoundedFloatSetting=class extends Setting{constructor(e){if(e.min!=null&&!isNumber(e.min))throw Error(`BoundedFloatSetting min must be finite`);if(e.max!=null&&!isNumber(e.max))throw Error(`BoundedFloatSetting max must be finite`);if(e.min!=null&&e.max!=null&&e.min>e.max)throw Error(`BoundedFloatSetting min must not exceed max`);super({...e,toEnv:notBlankToS,fromEnv:n=>opt(n).flatMap(toFloat).map(n=>e.min!=null&&n<e.min?e.min:e.max!=null&&n>e.max?e.max:n).get()}),this.options=e}options;addToJsonDocs(){return{...this.options.min==null?{}:{"minimum value":this.options.min},...this.options.max==null?{}:{"maximum value":this.options.max}}}},DefaultMimetypeSortOrder=[`image/jpeg`,`image/heic`,`image/x-*`,`image/*`,`video/*`],FloatSetting=class extends Setting{constructor(e){super({...e,toEnv:notBlankToS,fromEnv:toFloat})}},IntegerSetting=class extends Setting{constructor(e){super({...e,toEnv:notBlankToS,fromEnv:toInt})}},import_node_path2=require("node:path");function _join(e){return e==null?void 0:stringify(e)}var StringArrayDelimiter=`¦`;function _split(e,n){let r=notBlankToS(e);if(r!=null){if(r.startsWith(`[`)&&r.endsWith(`]`))try{return compact(toA(JSON.parse(r)).map(notBlankToS))}catch{}for(let e of n)if(r.includes(e))return compactBlankish(r.split(e));return[r]}}function splitStringArray(e){return map(_split(e,[StringArrayDelimiter,import_node_path2.delimiter]),compactBlankish)}function colonSafeDelimiters(e){return e===`:`?[StringArrayDelimiter]:[StringArrayDelimiter,e]}function splitStringArrayKeepingColons(e){return map(_split(e,colonSafeDelimiters(import_node_path2.delimiter)),compactBlankish)}var StringArraySetting=class extends Setting{constructor(e){super({defaultValue:[],fromEnv:splitStringArray,toEnv:_join,...e}),this.watchLater(()=>{this.synonymMap.clear()})}toValidValue(e){return notBlankToS(e)}toValidValues(e){return e==null?void 0:uniq(e.map(e=>this.toValidValue(e)))}push(...e){isEmpty(e)||(this.value=this.toValidValues(uniq([...toA(this.value),...toA(e)])))}has(e){return toA(this.values).includes(e)}get values(){return optToA(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}set testValues(e){this.testValue=e??void 0}isEmpty(){return isEmpty(this.values)}isNotEmpty(){return isNotEmpty(this.values)}toNotEmpty(){return toNotEmpty(compactBlanks(this.values))}synonymMap=lazy2(()=>{let e=new Map;for(let n of this.values){let r=n.split(`|`);for(let n of r)e.set(n,r)}return e})};function resolveWithAliases(e,n,r){if(e!=null)return n.getCI(e)??r?.get(e.toLowerCase())}function fromEnvWithAliases(e,n,r){let a=n.values.find(isDisabled);return a!=null&&isDisabled(e)?a:resolveWithAliases(e,n,r)}var StringEnumSetting=class extends Setting{strEnum;_valueAliases;constructor(e){let n=e.valueAliases==null?void 0:new Map(Object.entries(e.valueAliases).map(([e,n])=>[e.toLowerCase(),n]));super({...e,toEnv:r=>resolveWithAliases(r,e.strEnum,n),fromEnv:r=>fromEnvWithAliases(r,e.strEnum,n)}),this.strEnum=e.strEnum,this._valueAliases=e.valueAliases;let r=this.defaultValue;if(!this.strEnum.has(r))throw Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}isDisabled(){return isDisabled(this.valueOrDefault)}isEnabled(){return!this.isDisabled()}addToJsonDocs(){return{"valid values":this.strEnum.values}}toCommentedLines(){let e=super.toCommentedLines();if(this._valueAliases!=null){e.push(`#`,`# deprecated aliases:`);for(let[n,r]of Object.entries(this._valueAliases))e.push(`# - "${n}" -> "${r}"`)}return e}},StringEnumsSetting=class extends StringArraySetting{strEnum;constructor(e){super({toEnv:e=>map(e,e=>stringify(uniq(e))),fromEnv:e=>this.#e(e),defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}#e(e){let n=splitStringArray(e);if(n==null)return;let r=compact(n.map(e=>this.strEnum.getCI(e)));return isEmpty(r)&&isNotEmpty(n)?void 0:r}get values(){return super.values}set values(e){super.values=e}toValidValue(e){return this.strEnum.getCI(e)}addToJsonDocs(){return{"valid values":this.strEnum.values}}},StringSetting=class extends Setting{constructor(e){super({toEnv:trim,fromEnv:trim,...e})}hasValue(){return notBlank(this.value)}};function trim(e){return e==null?void 0:trimQuotes(e)}var AggregationSettings={strictDeduping:new BooleanSetting({category:SettingCategories.Aggregation,deprecated:!0,description:`Use aggregationMode=strict instead of setting this to true.`,defaultValue:!1}),aggregationMode:new StringEnumSetting({category:SettingCategories.Aggregation,aliases:[`deduplicationMode`,`dedupingMode`],description:`Use "default" to control individual aggregation settings directly. Use "strict" to change the default values for aggregation settings to require exact-match deduplication (almost identical image hashes and very high similarity thresholds). Use "lenient" to change the default values for aggregation settings to favor more matches (lower similarity thresholds and loose metadata-based grouping). "manual" is a synonym for "default".`,defaultValue:AggregationModes.default,strEnum:AggregationModes}),assetVariationSortCriteria:new StringEnumsSetting({category:SettingCategories.Aggregation,aliases:[`assetFileSortCriteria`,`variantSortCriteria`],description:`How should PhotoStructure pick the "best" asset file variation for a given asset?
|
|
43
|
+
Details about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria`,strEnum:AssetFileSortCriteria}),assetVariationResolutionTolerance:new BoundedFloatSetting({category:SettingCategories.Aggregation,description:`Maximum pixel-count ratio for two resolutions to be considered equivalent when ranking asset file variants. The default of 1.5 means files must differ by more than 50% in total pixels to get different resolution scores. Larger values are more lenient; smaller values are stricter.`,defaultValue:()=>1.5,min:1.1,max:4}),assetVariationMimetypeSortOrder:new StringArraySetting({category:SettingCategories.Aggregation,aliases:[`mimetypeSortOrder`],description:`When PhotoStructure is trying to determine which asset file variation to use for a given asset, it will use this list of mimetypes to determine the order in which to check for variants, if "assetVariationSortCriteria" contains "mimetype". Globs are supported. The default value prefers JPEG, then HEIC, then RAW and other "image/x-*" types, then other images, then videos.`,defaultValue:DefaultMimetypeSortOrder}),checkBasenameMatches:new BooleanSetting({category:SettingCategories.Aggregation,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?
|
|
44
|
+
Note that image hash and other asset file comparisons will still be performed before determining a given asset is a match.`,defaultValue:!0}),allowFuzzyDateImageHashMatches:new BooleanSetting({category:SettingCategories.Aggregation,description:`For images that don't have a reliable precise captured-at time (say, from "stat" or a datestamp from the pathname), can we aggregate variations by perceptual image hashes even when their dates differ? The imageHashFuzzyDateThresholdPct setting controls the required similarity. Enabled by aggregationMode=lenient.
|
|
45
|
+
See https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.`,defaultValue:!1}),requireSameColorSpace:new BooleanSetting({category:SettingCategories.Aggregation,description:`Require matching color spaces when grouping photos. When enabled (default), a color photo and its greyscale/B&W conversion are kept as separate assets. Disable this to group them together using luminance-based similarity. Note that grouping is best-effort and depends on matching metadata and hash thresholds.`,defaultValue:!0}),maxContemporaryAdoptionAssets:new IntegerSetting({category:SettingCategories.Aggregation,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?
|
|
46
|
+
Monitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.
|
|
47
|
+
Higher values will slow down imports, but may result in more accurate de-duplication results.`,defaultValue:512}),imageHashMatchK:new IntegerSetting({category:SettingCategories.Aggregation,description:`The number of nearest neighbors to request from the AssetFileHash index when searching for similar images by perceptual hash. The MATCH query uses sqlite-vec's optimized SIMD implementation and scales well on large libraries (scalar vec_distance_hamming queries took ~10 seconds on large libraries). Since the candidate search uses a stricter threshold than final validation (to reduce candidates), k=500 provides a good buffer to ensure true matches aren't missed. Results are ordered by distance, and we validate candidates with full similarity checks.`,defaultValue:500}),datesBeforeAreEstimated:new StringSetting({category:SettingCategories.Aggregation,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."
|
|
48
|
+
When assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.
|
|
49
|
+
The 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`}),imageHashThresholdPct:new BoundedFloatSetting({category:SettingCategories.Aggregation,aliases:[`minImageCoeffPct`,`imageHashConfidenceThresholdPct`],description:`How similar must two images of the same file format be to group them as variants? This controls duplicate detection when comparing images with matching file types (e.g., JPEG to JPEG, PNG to PNG, RAW to RAW). Higher values (90-100%) only match nearly identical images. Lower values (60-80%) will group images with more differences like crops, filters, or compression artifacts.`,defaultValue:()=>70,min:0,max:100}),imageHashRelaxedThresholdPct:new BoundedFloatSetting({category:SettingCategories.Aggregation,description:`Base threshold for relaxed image hash comparisons. This value serves as the default for the more specific relaxed thresholds imageHashCrossFormatThresholdPct and imageHashRotationThresholdPct. Changing this value adjusts those two unless they have been individually overridden.`,defaultValue:()=>45,min:0,max:100}),imageHashFuzzyDateThresholdPct:new BoundedFloatSetting({category:SettingCategories.Aggregation,description:`How similar must two images be to group them when their captured-at times are imprecise? When a photo's date comes from filename patterns or file modification times rather than reliable EXIF tags, PhotoStructure can match duplicates using image hashes alone (requires allowFuzzyDateImageHashMatches to be enabled). Lower values allow more variation. Higher values reduce false positives. This defaults to being strict to avoid scanned images being aggressively aggregated.`,defaultValue:()=>80,min:0,max:100}),imageHashCrossFormatThresholdPct:new BoundedFloatSetting({category:SettingCategories.Aggregation,description:`How similar must images of different file formats be to group them as the same photo? This applies when comparing across formats (e.g., JPEG vs RAW, PNG vs TIFF, HEIC vs JPEG). Format conversions often introduce visual differences due to processing, compression, or color space changes. Higher values require very similar appearance despite format differences. Lower values accommodate more variation. Defaults to imageHashRelaxedThresholdPct.`,defaultValue:()=>45,min:0,max:100}),imageHashRotationThresholdPct:new BoundedFloatSetting({category:SettingCategories.Aggregation,description:`How similar must two images be when one appears to be a rotated version of the other? PhotoStructure compares both original and 90°-rotated perceptual hashes to detect duplicates with different orientations. Rotation changes the hash significantly, so this threshold is typically lower than same-orientation comparisons. Defaults to imageHashRelaxedThresholdPct.`,defaultValue:()=>45,min:0,max:100}),gpsErrorMeters:new IntegerSetting({category:SettingCategories.Aggregation,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.
|
|
50
|
+
GPS position error is ~10-100m. Cellular position error is ~500-750m.`,defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new IntegerSetting({category:SettingCategories.Aggregation,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}),fuzzyDatePrecisionFactor:new FloatSetting({category:SettingCategories.Aggregation,aliases:[`fuzzyDatePrecisionCoeff`],description:`When comparing "captured-at" dates that aren't from reliable metadata tags, what multiplier 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})};for(let[e,n]of entries(AggregationSettings))n._setName(e);var ReservedDomainSuffixes=[`example.com`,`example.net`,`example.org`,`example.edu`,`.example`].map(e=>stripPrefix(e,`.`).split(`.`));function isExampleDomain(e){let n=e.toLowerCase().split(`.`);return ReservedDomainSuffixes.some(e=>arrayEndsWith(n,e))}var MinimalEmailRE=/^(?<local>.+)@(?<domain>.[^@\n\r.\u2028\u2029]*\..+)$/,MaxMailboxLength=254,PlainMailboxRE=/^[^\s\p{Cc}@,;:<>()[\]"\\]+@[^\s\p{Cc}@,;:<>()[\]"\\.]+(?:\.[^\s\p{Cc}@,;:<>()[\]"\\.]+)+$/u;function isPlainMailbox(e){let n=toS(e).trim();return hasPlainMailboxForm(n)&&parseEmail(n)!=null}function isExampleDomainMailbox(e){let n=toS(e).trim();return hasPlainMailboxForm(n)&&isExampleDomain(n.slice(n.indexOf(`@`)+1))}function hasPlainMailboxForm(e){return e.length<=MaxMailboxLength&&PlainMailboxRE.test(e)}function parseEmail(e){let n=MinimalEmailRE.exec(toS(e).trim());if(n?.groups==null)return;let{local:r,domain:a}=n.groups;return blank(r)||blank(a)||isExampleDomain(a)?void 0:{local:r,domain:a}}var AuthModes=strEnum(`none`,`email`,`oidc`),AuthStates=strEnum(`initialSetup`,`configurationFailure`,...AuthModes.values),AuthExternalOriginStates=strEnum(`notRequired`,`valid`,`missing`,`invalid`),AuthEmailDeliveryStates=strEnum(`usable`,`unusable`),AuthOidcClientStates=strEnum(`usable`,`unusable`),AuthUserStates=strEnum(`present`,`absent`),AuthListenerProfiles=strEnum(`loopback`,`network`),Units=[{ms:yearMs,s:`y`},{ms:weekMs,s:`w`},{ms:dayMs,s:`d`},{ms:hourMs,s:`h`},{ms:minuteMs,s:`m`},{ms:secondMs,s:`s`},{ms:1,s:`ms`}];function fmtDuration(e,n={}){if(!isNumber(e))return``;if(e===0)return`0`;if(!gte0(e))return`-`+fmtDuration(Math.abs(e),n);let{units:r,sep:a=``,suffix:o}=n,s=[],c=Units.findIndex(n=>n.ms<=e);if(c===-1)return``;let l=r==null?Units.length:c+r;for(let n of Units.slice(c,l)){let r=Math.floor(e/n.ms);e-=r*n.ms,r>0&&s.push({n:r,s:n.s})}if(s.length===0)return``;let u=s.map(e=>e.n+e.s).join(a);if(o==null)return u;let d=s[s.length-1].n;return u+` `+(d===1?o.singular:o.plural)}var durationRegExp=/[\s,]*(?<value>-?\d*\.?\d+)\s*(?<type>MILLISECONDS?|MSECS?|MILLIS|MS|SECONDS?|SECS?|S|MINUTES?|MINS?|M|HOURS?|HRS?|H|DAYS?|D|WEEKS?|W|YEARS?|YRS?|Y)?[\s,]*/gi;function parseDuration(e){if(e==null||!isString(e)&&!isNumber(e))return;if(isNumber(e))return e;if(isDigits(e))return toInt(e);if(e=e.trim().toUpperCase(),e.length===0)return;let n=[...e.matchAll(durationRegExp)];if(n.length===0)return;let r=[];for(let e of n){let n=parseUnit(e.groups?.value,e.groups?.type);n!=null&&r.push(n)}if(r.length===0)return;let a=r[0];return lt0(a)?a-r.slice(1).reduce((e,n)=>e+n,0):r.reduce((e,n)=>e+n,0)}function parseUnit(e,n){let r=toFloat(e);if(r!=null){if(blank(n))return r;switch(n.toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return r*yearMs;case`weeks`:case`week`:case`w`:return r*weekMs;case`days`:case`day`:case`d`:return r*dayMs;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return r*hourMs;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return r*minuteMs;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return r*secondMs;case`milliseconds`:case`millisecond`:case`millis`:case`msecs`:case`msec`:case`ms`:return r;default:throw Error(`parseDuration(): unit ${n} was matched, but no matching case exists.`)}}}function decodeDuration(e){return isNumber(e)?e:blank(e)?void 0:parseDuration(e)}function encodeDuration(e){return toNotBlank(e)==null?void 0:fmtDuration(isNumber(e)?e:decodeDuration(e))||void 0}function declaredDurationBounds(e,n=isTest()){function r(r){let a=`DurationSetting `+r;if(n)throw Error(a);console.warn(a+`; the bound is ignored`,{options:e})}let a=decodeDuration(e.min),o=decodeDuration(e.max);e.min!=null&&a==null&&r(`min must be a valid duration`),e.max!=null&&o==null&&r(`max must be a valid duration`),a!=null&&o!=null&&a>o&&(r(`min must not exceed max`),a=void 0,o=void 0);let s=typeof e.defaultValue==`function`?void 0:decodeDuration(e.defaultValue);return s!=null&&(a!=null&&s<a&&(r(`defaultValue must be at least min`),a=void 0),o!=null&&s>o&&(r(`defaultValue must not exceed max`),o=void 0)),{min:a,max:o}}var DurationSetting=class extends Setting{constructor(e){let{min:n,max:r}=declaredDurationBounds(e),a=e.whyInvalid;super({toEnv:encodeDuration,...e,whyInvalid:e=>{let o=a?.(e);if(o!=null)return o;let s=decodeDuration(e);if(s!=null){if(n!=null&&s<n)return`must be at least ${encodeDuration(n)}`;if(r!=null&&s>r)return`must be at most ${encodeDuration(r)}`}},fromEnv:decodeDuration}),this.options=e}options;get valueOrDefault(){return decodeDuration(super.valueOrDefault)}get value(){return decodeDuration(super.value)}set value(e){super.userValue=decodeDuration(e)}get humanValue(){return fmtDuration(this.value)}get fileValue(){return encodeDuration(super.fileValue)}set fileValue(e){super.fileValue=decodeDuration(e)}addToJsonDocs(){return compactValues({"minimum value":encodeDuration(this.options.min),"maximum value":encodeDuration(this.options.max)})??{}}},OptionalStringEnumSetting=class extends Setting{strEnum;constructor(e){super({...e,defaultValue:void 0,toEnv:n=>e.strEnum.getCI(n),fromEnv:n=>e.strEnum.getCI(n)}),this.strEnum=e.strEnum}get value(){return this._testValue==null?this._cliValue==null?this.rawEnvValue()==null?this._userValue??this._fileValue:this.envValue:this._cliValue:this._testValue}set value(e){super.value=e}addToJsonDocs(){return{"valid values":this.strEnum.values}}},OptionalStringSetting=class extends Setting{constructor(e){super({toEnv:e=>typeof e==`string`?e.trim():void 0,fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return this.value!=null}},import_proxy_addr=__toESM(require("proxy-addr")),import_node_fs2=require("node:fs");function resolveIsDocker({envValue:e,hasMarker:n}){return toBoolean(e)===!0||n}var isDocker=lazy2(()=>isLinux&&resolveIsDocker({envValue:process.env[PS_IS_DOCKER],hasMarker:(0,import_node_fs2.existsSync)(`/.running-in-container`)})),HelmetPlugins=strEnum(`all`,`contentSecurityPolicy`,`crossOriginEmbedderPolicy`,`crossOriginOpenerPolicy`,`crossOriginResourcePolicy`,`dnsPrefetchControl`,`expectCt`,`frameguard`,`hidePoweredBy`,`hsts`,`ieNoOpen`,`noSniff`,`originAgentCluster`,`permittedCrossDomainPolicies`,`referrerPolicy`,`xssFilter`);function externalOriginDetails(e){if(typeof e!=`string`)return{valid:!1};let n=e.trim();if(n.length===0)return{valid:!1};try{let e=new URL(n),r=(e.protocol===`http:`||e.protocol===`https:`)&&e.pathname===`/`&&e.username.length===0&&e.password.length===0&&e.search.length===0&&e.hash.length===0;return r?{canonicalOrigin:e.origin,valid:r}:{valid:!1}}catch{return{valid:!1}}}function trustProxyExpressValue(e){let n=e.trim().toLowerCase();return n===`true`||n!==`false`&&toNotBlank(n)}function whyExpressRejectsTrustProxy(e){let n=trustProxyExpressValue(e);if(typeof n==`string`)try{import_proxy_addr.default.compile(n.split(`,`).map(e=>e.trim()));return}catch(e){if(!(e instanceof TypeError))throw e;return`Express can't parse it: ${e.message}`}}var SecuritySettings={externalOrigin:new OptionalStringSetting({category:SettingCategories.Security,description:`The one exact public browser origin used to access PhotoStructure, including scheme and any non-default port. A reverse proxy must preserve this Host and Origin. For an HTTPS origin, it must also send X-Forwarded-Proto: https. Configure trustProxy separately for the immediate proxy address or subnet.`,redactInvalidValue:!0,whyInvalid:e=>e==null||externalOriginDetails(e).valid?void 0:`Expected one exact HTTP or HTTPS origin`}),requireSetupLink:new BooleanSetting({category:SettingCategories.Security,description:`While a library has no sign-in mode and no users, the first visitor on your network may set up sign-in in the 10 minutes after PhotoStructure starts. Set this to true to require the one-time setup link PhotoStructure prints at each start instead.`,defaultValue:!1}),exposeNetworkWithoutAuth:new BooleanSetting({category:SettingCategories.Security,description:`Normally the web service listens only on the computer running PhotoStructure. Setting this to true makes it reachable from the network; despite this legacy setting name, it does not disable the selected auth mode. With email or OIDC sign-in (see authMode), network access also requires an exact externalOrigin. In none mode, every visitor who can connect acts as the library owner.
|
|
51
|
+
**Don't enable this unless you understand and trust your network exposure**.`,defaultValue:()=>isDocker()}),previewApiToken:new OptionalStringSetting({category:SettingCategories.Security,sensitive:!0,description:`A secret that a file browser's server, such as HexOS's, sends to fetch file previews. When this is set, a GET or HEAD request for /api/preview needs the header "Authorization: Bearer <this value>", and gets 401 without it. With email or OIDC sign-in on, /api/preview takes only this token, and refuses every request while it is unset. The token opens no other page or API. A file browser's installer sets this; leave it unset otherwise.`}),trustProxy:new StringSetting({category:SettingCategories.Security,description:`What reverse proxies should PhotoStructure "trust"? See <http://expressjs.com/en/guide/behind-proxies.html>.
|
|
52
|
+
This 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.
|
|
53
|
+
With email or OIDC sign-in, "true" (trust every proxy) and "1" pause access.`,defaultValue:`loopback`,whyInvalid:e=>e==null?void 0:whyExpressRejectsTrustProxy(toS(e))}),cspReportOnly:new BooleanSetting({category:SettingCategories.Security,description:`DANGEROUS: do not enforce, and only report CSP violations. This should only be set to true temporarily to assist in debugging. For more details see https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP`,defaultValue:()=>!1}),upgradeInsecureRequests:new BooleanSetting({category:SettingCategories.Security,description:`Should PhotoStructure add the "upgrade-insecure-requests" directive to its Content-Security-Policy? Browsers then load every page resource over https.
|
|
54
|
+
Only set this to true if you always reach PhotoStructure through https URLs: a page served over plain http with this directive cannot load its scripts or stylesheets.`,defaultValue:()=>!1}),cspDirective:new OptionalStringSetting({category: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. For more details see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src`,exampleValue:()=>`https://myphotos.example.com`}),disabledHelmetMiddleware:new StringEnumsSetting({category:SettingCategories.Security,description:`What Helmet middleware should PhotoStructure disable?
|
|
55
|
+
By default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet's functionality.
|
|
56
|
+
Disable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.
|
|
57
|
+
For more details see https://github.com/helmetjs/helmet#reference`,defaultValue:[],strEnum:HelmetPlugins})};for(let[e,n]of entries(SecuritySettings))n._setName(e);var AuthSettings={authAdminEmail:new OptionalStringSetting({category:SettingCategories.Auth,description:`The first Admin's email address for email or OIDC sign-in. When authMode is "email" or "oidc" and the library has no users yet, PhotoStructure adds this address as an Admin when it starts. Once the library has users, this setting never adds or changes users.`,redactInvalidValue:!0,whyInvalid:e=>e==null||isPlainMailbox(String(e))?void 0:`Expected an email address`}),authMode:new OptionalStringEnumSetting({category:SettingCategories.Auth,description:`Who can use this library. "none" serves it without sign-in, giving every visitor full library-owner access, as releases before sign-in did. "email" signs users in with a one-time code sent to their email address; with no Email settings, photostructure.com's relay sends the codes. "oidc" signs users in with an OpenID Connect identity provider, and needs the OIDC settings.
|
|
58
|
+
With no mode set, PhotoStructure pauses access until one is chosen: photostructure auth set-email, set-oidc or set-none, or PhotoStructure for Desktop's setup window, save a mode in the library's settings.`,redactInvalidValue:!0,strEnum:AuthModes}),enableArchive:new BooleanSetting({category:SettingCategories.Auth,description:`If false, PhotoStructure refuses every request to archive an asset, including an Admin's. Archived assets can still be unarchived.`,defaultValue:()=>!0}),enableDelete:new BooleanSetting({category:SettingCategories.Auth,description:`If false, PhotoStructure refuses every request to move an asset to the trash, including an Admin's. Assets in the trash can still be restored.`,defaultValue:()=>!0}),enableEmptyTrash:new BooleanSetting({category:SettingCategories.Auth,description:`If false, PhotoStructure refuses every request to empty the trash, including an Admin's. When true, only Admins can empty the trash.
|
|
59
|
+
This setting is disabled by default if exposeNetworkWithoutAuth is true.`,defaultValue:()=>!SecuritySettings.exposeNetworkWithoutAuth.valueOrDefault}),enableRemove:new BooleanSetting({category:SettingCategories.Auth,description:`If false, PhotoStructure refuses every request to mark an asset for removal from the library, including an Admin's. Assets already marked can still be unmarked.`,defaultValue:()=>!0}),enableRemoveAssets:new BooleanSetting({category:SettingCategories.Auth,description:`If false, PhotoStructure refuses every request to remove the assets marked for removal from the library, including an Admin's. When true, only Admins can remove them.
|
|
60
|
+
This setting is disabled by default if exposeNetworkWithoutAuth is true.`,defaultValue:()=>!SecuritySettings.exposeNetworkWithoutAuth.valueOrDefault}),sessionAbsoluteTimeout:new DurationSetting({category:SettingCategories.Auth,description:`How long a user stays signed in after signing in, however active they are. A session ends at this time or after sessionTimeout without a request, whichever comes first.`,defaultValue:`30d`}),sessionTimeout:new DurationSetting({category:SettingCategories.Auth,description:`How long a user stays signed in without making a request. After this period, they must sign in again. Every session also ends sessionAbsoluteTimeout after sign-in, however active it is.`,defaultValue:`14d`})};for(let[e,n]of entries(AuthSettings))n._setName(e);var isProd2=lazy2(isProd),isNotProd=()=>!isProd2(),CacheSettings={fsCacheSlowMs:new DurationSetting({category:SettingCategories.Cache,description:`If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.
|
|
61
|
+
The default is very short, under the assumption that cache filesystem read/writes are <10ms.
|
|
62
|
+
Set this to 0 to never cache to the filesystem.`,defaultValue:()=>isNotProd()?`1`:`25`}),imageCacheMs:new DurationSetting({category: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`}),metadataCacheMs:new DurationSetting({category:SettingCategories.Cache,description:`How long can file metadata be safely cached?
|
|
63
|
+
Set to 0 to disable metadata caching.`,defaultValue:`10m`})};for(let[e,n]of entries(CacheSettings))n._setName(e);var ColorEncodings=strEnum(`labhash`,`rgboctal`),BoundedIntegerSetting=class extends Setting{constructor(e){super({...e,toEnv:notBlankToS,fromEnv:n=>opt(n).filter(notBlank).flatMap(toInt).map(n=>clamp(e.min,e.max,n)).get()}),this.options=e}options;get min(){return this.options.min}get max(){return this.options.max}clamp(e){return clamp(this.min,this.max,e??this.min)}addToJsonDocs(){return{"minimum value":this.options.min,"maximum value":this.options.max}}},ColorDistanceFunctions=strEnum(`cie76`,`cie94`,`ciede2000`),DominantColorKmeansRunsDefault=7,ColorSettings={colorVarianceThreshold:new BoundedIntegerSetting({aliases:[`colourVarianceThreshold`],category:SettingCategories.Color,description:`Controls how PhotoStructure detects monochrome images. An image is classified as monochrome (grayscale) if the total color variance - measured as the sum of standard deviations of a* and b* values in CIELAB color space - is less than this value. Higher values are more lenient and will classify more images as monochrome, including those with slight coloration from aging or scanning artifacts. If an image fails this grayscale test, it may still be classified as monochrome if it has a consistent tint (like sepia photos), which is determined by analyzing hue and chroma consistency. Lower values are stricter and will classify fewer images as monochrome.`,defaultValue:10,max:128,min:0}),chromaVariationThreshold:new BoundedFloatSetting({category:SettingCategories.Color,description:`Controls the detection of tinted monochrome images (like sepia photos). This setting defines how consistent the color intensity (chroma) must be across the image to be considered a tinted monochrome image. Specifically, it's the maximum allowed coefficient of variation (standard deviation / mean) of chroma values. Lower values are stricter and require more consistent tinting, while higher values are more lenient and will classify more varied tinting as monochrome.`,defaultValue:.36,max:.5,min:.05}),dominantColorDeltaE:new StringEnumSetting({aliases:[`delta_e`,`dominantColourDeltaE`],category: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:ColorDistanceFunctions.ciede2000,strEnum:ColorDistanceFunctions}),dominantColorKmeansRuns:new BoundedIntegerSetting({category:SettingCategories.Color,aliases:[`modeRuns`,`dominantColourKmeansRuns`],description:`PhotoStructure uses k-means clustering to extract dominant colors from your images.
|
|
64
|
+
Larger 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.
|
|
65
|
+
Using 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.
|
|
66
|
+
Changing this value will subtly change many image's dominant color lists.
|
|
67
|
+
This defaults to 0 run when "quickSyncMode" is enabled.`,defaultValue:DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new BoundedIntegerSetting({aliases:[`dominantColourMergeThreshold`],category: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}),dominantColorGrayThreshold:new BoundedIntegerSetting({category:SettingCategories.Color,aliases:[`modeGray`,`modeGrey`,`dominantColourGreyThreshold`],description:`May PhotoStructure ignore pixels that are grayscale, 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.
|
|
68
|
+
Set this to 0 to include grays in dominant colors, but note that this tends to reduce image deduplication effectiveness, as most natural-tone images contain a good deal of grayscales, which results in false matches.`,defaultValue:11,max:80,min:0}),colorEncoding:new StringEnumSetting({aliases:[`colourEncoding`],category:SettingCategories.Color,strEnum:ColorEncodings,description:`How should PhotoStructure encode colors? The "labhash" mode is an LSH in CIE L*a*b* space, which is efficient in encoding but difficult for humans to read. The "rgboctal" mode reduces each RGB channel to a single octal value between 0 and 7, which has poor LSH behavior, but is easier for humans to parse: for example, white is 777, black is 000.`,defaultValue:`labhash`})};for(let[e,n]of entries(ColorSettings))n._setName(e);var SynchronousModes=strEnum(`OFF`,`NORMAL`,`FULL`,`EXTRA`),DbSettings={forceLocalDbReplica:new BooleanSetting({category: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 SQLite can't write to the library's database where it is (for example, on a network share without file locking), 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.\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 IntegerSetting({category:SettingCategories.Db,description:`If SQLITE_BUSY is encountered, how many times should an operation be retried before giving up?`,advanced:()=>!0,defaultValue:7}),dbBackupRetentionCount:new BoundedIntegerSetting({aliases:[`dbBackupsCount`],category:SettingCategories.Db,description:`How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.
|
|
69
|
+
We 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}),dbInvalidFKThreshold:new IntegerSetting({category: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.
|
|
70
|
+
Set this to 0 to disable this recovery step, which will make any foreign key violation fatal.`,defaultValue:64}),dbSynchronousMode:new StringEnumSetting({category:SettingCategories.Db,description:`Change SQLite's synchronous mode.
|
|
71
|
+
"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you're seeing dataloss.
|
|
72
|
+
For more details, see https://sqlite.org/pragma.html#pragma_synchronous`,strEnum:SynchronousModes,defaultValue:SynchronousModes.NORMAL}),dbWalAutoCheckpointPages:new BoundedIntegerSetting({category:SettingCategories.Db,aliases:[`dbWalAutoCheckpoint`],description:`Applies to PhotoStructure's quarantine database (problem files and deferred tasks) and to the web service's database connections, including the sign-in database, where web writes sign-in sessions even when sync isn't running. The sync service checkpoints the library database itself, every few seconds on a background thread, and empties its WAL during periodic database maintenance. SQLite's WAL (Write-Ahead Logging) mode appends changes to a separate file. When the quarantine database's WAL reaches this many pages, SQLite automatically checkpoints (copies changes back to the main database). With 8KB pages, the default of 5000 pages triggers checkpointing at ~40MB WAL size. Larger values improve write throughput but increase WAL size and reader scan time. Smaller values keep the WAL compact but add checkpoint overhead.
|
|
73
|
+
For more details, see https://sqlite.org/pragma.html#pragma_wal_autocheckpoint`,advanced:()=>!0,min:100,max:1e5,defaultValue:()=>5e3}),maxBusyDbMs:new DurationSetting({category: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 DurationSetting({category: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. PhotoStructure uses SQLite's default of 5 seconds. Note that setting this value to be lower than disk I/O latency (~1ms-100ms) will cause all database queries to fail.\nFor more details, see https://sqlite.org/pragma.html#pragma_busy_timeout",advanced:()=>!0,defaultValue:()=>`5s`}),dbMaintenanceTimeoutMs:new DurationSetting({category:SettingCategories.Db,description:`How long is a reasonable time to wait for the library database to apply a migration, vacuum, quick check, validate foreign keys, or validate the schema?
|
|
74
|
+
Note that the default of 2 minutes should be very generous--these operations should only take a second or two unless your library is very large and/or your disk is very slow.`,advanced:()=>!0,defaultValue:()=>`2m`}),dbBackupIntervalMs:new DurationSetting({category:SettingCategories.Db,description:`How often sync backs up the library database while it runs. Sync checks this in its hourly maintenance pauses, so a value under an hour backs up hourly. Sync also backs up at the end of each sync. Each backup runs inside a brief pause for the same database maintenance that dbMaintenanceEveryTasks triggers. PhotoStructure never restores these backups itself. A library whose database runs from a local replica uses dbReplicaBackupIntervalMs instead.`,advanced:()=>!0,defaultValue:()=>`1d`}),dbReplicaBackupIntervalMs:new DurationSetting({category:SettingCategories.Db,description:`How often sync backs up the library database while it runs, for a library whose database runs from a local replica, as it does for a library on a network share. Each of these backups also copies the replica back to the library folder, so this bounds how far the library folder's copy lags behind. Sync checks this in its hourly maintenance pauses, so a value under an hour backs up hourly. Sync also backs up at the end of each sync. Other libraries use dbBackupIntervalMs.`,advanced:()=>!0,defaultValue:()=>`1h`}),dbMaintenanceEveryTasks:new BoundedIntegerSetting({category:SettingCategories.Db,description:`After sync finishes this many tasks (importing a file, refreshing or repairing an asset, and the like), it pauses briefly for library database maintenance: it waits for running tasks to finish, updates the query planner's statistics, copies the write-ahead log back into the database and empties it unless another process is reading it, and compacts the database when more than a quarter of it is free space. Sync also runs this maintenance every hour, and backs up every dbBackupIntervalMs (dbReplicaBackupIntervalMs for a library whose database runs from a local replica).`,advanced:()=>!0,min:1,max:1e6,defaultValue:()=>isNotProd()?50:2500}),dbBackupIntervalMinutes:new BoundedFloatSetting({category:SettingCategories.Db,deprecated:!0,description:`This setting was replaced by "dbBackupIntervalMs".`,min:1,max:1440,advanced:()=>!0,defaultValue:()=>30}),dbPageSizeBytes:new IntegerSetting({category: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.
|
|
75
|
+
For more details, see https://sqlite.org/pragma.html#pragma_page_size`,advanced:()=>!0,defaultValue:8192}),dbCacheSizeMb:new IntegerSetting({category: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.
|
|
76
|
+
For more details, see https://sqlite.org/pragma.html#pragma_cache_size`,advanced:()=>!0,defaultValue:256}),dbMaxCacheRamPercent:new BoundedIntegerSetting({category:SettingCategories.Db,description:`Upper bound on SQLite cache_size as a percentage of total system RAM, per process. PhotoStructure runs two processes (sync + web), each with their own SQLite page cache. This cap prevents unbounded cache growth on memory-constrained systems (e.g., NAS devices, small Docker containers). Set to 0 to disable the cap and let cache_size grow to match the database file size.
|
|
77
|
+
For more details, see https://sqlite.org/pragma.html#pragma_cache_size`,advanced:()=>!0,defaultValue:25,min:0,max:100}),dbMMapSizeMb:new IntegerSetting({category:SettingCategories.Db,description:`This value will be used for SQLite's mmap_size PRAGMA. Confusingly, this PRAGMA is in bytes, and does not accept negative numbers. 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.
|
|
78
|
+
For more details, see https://sqlite.org/pragma.html#pragma_mmap_size`,advanced:()=>!0,defaultValue:256}),dbBatchSelectSize:new BoundedIntegerSetting({category:SettingCategories.Db,description:`How many objects can be selected at at time? The default should be fine. (Exposed for performance tests).`,advanced:()=>!0,defaultValue:128,min:1,max:1024}),dbBatchUpsertSize:new BoundedIntegerSetting({category:SettingCategories.Db,description:`How many objects can be upserted at at time? The default should be fine. (Exposed for performance tests).`,advanced:()=>!0,defaultValue:128,min:1,max:128}),dbForceRepair:new BooleanSetting({category:SettingCategories.Db,aliases:[`dbForceRecover`,`dbForceRebuild`],transient:!0,propagateToChildren:!1,description:`SQLite databases can sometimes be repaired with SQLite's .recover tooling. Set this to true to have PhotoStructure attempt a .recover on startup.
|
|
79
|
+
This can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.
|
|
80
|
+
For more details, see https://sqlite.org/recovery.html`,defaultValue:()=>!1}),enableSimilaritySearch:new BooleanSetting({category:SettingCategories.Db,description:`Enable or disable similarity searches via the sqlite-vec extension. This must be enabled for allowFuzzyDateImageHashMatches to work.
|
|
81
|
+
Disabling this setting stops the AssetFileHash index from being updated or queried. Any existing index is left in place (and ignored) so the database stays valid.`,defaultValue:()=>!0})};for(let[e,n]of entries(DbSettings))n._setName(e);var DesktopsSettings={autoHideMenuBar:new BooleanSetting({category: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 BooleanSetting({category:SettingCategories.Desktops,description:`If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.
|
|
82
|
+
This setting is ignored by PhotoStructure for Server editions.`,defaultValue:!1}),pauseSyncOnBattery:new BooleanSetting({category:SettingCategories.Desktops,description:`If true, PhotoStructure for Desktops will pause sync when the system is on battery power.
|
|
83
|
+
This setting is ignored by PhotoStructure for Server editions.`,defaultValue:!1}),closeToTray:new BooleanSetting({category:SettingCategories.Desktops,description:`If true (the default), closing the main window hides it to the system tray and sync continues running in the background. Set to false to fully exit PhotoStructure when the window is closed.
|
|
84
|
+
This setting is ignored by PhotoStructure for Server editions.`,defaultValue:!0})};for(let[e,n]of entries(DesktopsSettings))n._setName(e);var EmailSmtpSecurities=strEnum(`starttls`,`tls`,`none`),EmailSettings={emailFromAddress:new OptionalStringSetting({category:SettingCategories.Email,description:`The email address that sends sign-in codes. Your mail server must accept it as a sender. Required once any email setting is set; with none set, photostructure.com sends sign-in codes.`,whyInvalid:e=>e==null||isPlainMailbox(e)?void 0:`Expected only an email address, with no name around it (any sender name goes in emailFromName); addresses at example domains such as example.com can't send mail`}),emailFromName:new OptionalStringSetting({category:SettingCategories.Email,description:`The sender name users see beside emailFromAddress, like "Smith Family Photos". Leave unset to send from the address alone.`}),emailSmtpHost:new OptionalStringSetting({category:SettingCategories.Email,description:`The hostname of the SMTP server that sends email sign-in codes. Amazon SES works through its SMTP interface. Required once any email setting is set; with none set, photostructure.com sends sign-in codes.`}),emailSmtpPassword:new OptionalStringSetting({category:SettingCategories.Email,sensitive:!0,description:`The password for emailSmtpUser. Leading and trailing spaces are removed.`}),emailSmtpPort:new IntegerSetting({category:SettingCategories.Email,description:`The SMTP server port. 587 is usual for "starttls" and 465 for "tls".`,defaultValue:587,whyInvalid:e=>{let n=Number(e);return Number.isInteger(n)&&n>=1&&n<=65535?void 0:`Expected a TCP port from 1 to 65535`}}),emailSmtpSecurity:new StringEnumSetting({category:SettingCategories.Email,description:`How PhotoStructure protects its connection to the SMTP server. "starttls" upgrades the connection with STARTTLS and refuses to send if the server does not offer it. "tls" connects with TLS from the start. "none" sends without encryption: use it only for a mail relay on the same host or a trusted network.`,strEnum:EmailSmtpSecurities,defaultValue:EmailSmtpSecurities.starttls}),emailSmtpUser:new OptionalStringSetting({category:SettingCategories.Email,description:`The username PhotoStructure signs in to the SMTP server with. Leave unset if the server does not require authentication.`})};for(let[e,n]of entries(EmailSettings))n._setName(e);function emailSenderFromSettings(){return Object.values(EmailSettings).some(e=>e.value!=null||hasInvalidInput(e))?`mailServer`:`relay`}function hasInvalidInput(e){return e.rawEnvValue()==null?e.hasInvalidFileInput():e.envValue==null}function emailDeliveryConfigFromSettings(){let e=EmailSettings;if(Object.values(e).some(hasInvalidInput))return;let n=e.emailSmtpHost.valueOrDefault,r=e.emailFromAddress.valueOrDefault,a=e.emailSmtpUser.valueOrDefault,o=e.emailSmtpPassword.valueOrDefault;if(n!=null&&r!=null&&(o==null||a!=null))return{host:n,port:e.emailSmtpPort.valueOrDefault,security:e.emailSmtpSecurity.valueOrDefault,user:a,password:o,from:{name:e.emailFromName.valueOrDefault,address:r}}}var import_node_path3=require("node:path"),CopiesRe=[/\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}$/],Copies2Re=[...CopiesRe,/\s*-?edit(?:ed)?$/i],ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/;function stripCopySuffixFromName(e,n={aggressive:!0}){return _stripCopySuffixFromName(toNotBlank(e.name)??toS(e),n).normalize()}function _stripCopySuffixFromName(e,n){if(ymdIsoRE.test(e))return e;let r=e;for(let e of n.aggressive?Copies2Re:CopiesRe){let n=r.match(e);if(gt0(n?.index)){let e=r.slice(0,n.index).trim();e.length>0&&(r=e)}}return e===r?e:_stripCopySuffixFromName(r,n)}function copySuffixCountFromName(e){let n=(isString(e)?e:e.name).toLowerCase().normalize(),r=stripCopySuffixFromName(n);return map(extractInt(stripPrefix(n.toLowerCase().normalize(),r)),Math.abs)}var burstRe=/burst\s*([\w-]{8,})\s*$/i,coverRe=/(?<=.{6})_cover$/i,dscPrefixRe=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i;function stripDSC(e){let n=(isString(e)?e:e.name).trim().replace(coverRe,``).trim();return map(burstRe.exec(n),e=>n=e[1].trim()),map(dscPrefixRe.exec(n),e=>n=e[1].trim()),n}var import_semver=require("semver"),UpdateChannels=strEnum(`beta`,`stable`);function _compact(e){return toA(e).map(e=>toGte0(e)??toS(e).trim()).filter(e=>!blank(e))}var DebianVersionRE=/^(?<epoch>\d+:)?[vn]?(?<major>\d+)(?:\.(?<minor>\d+))?(?:\.(?<patch>\d+))?(?:-(?<prerelease>[^+\s]+))?(?:\+(?<build>\S+))?/;function splitMeta(e){return _compact(toS(e).split(/\s*\.\s*/)).map(e=>toInt(e,{strict:!0})??e)}function isSemVer(e){return e!=null&&typeof e.major==`number`}function toSemVer(e,n=!1){return isSemVer(e)?e:parseLooseSemVer(toS(e),n)}function parseLooseSemVer(e,n=!1){if(blank(e))return;let r=DebianVersionRE.exec(e)?.groups;if(!r)return;let a={epoch:r.epoch?toInt(r.epoch.replace(`:`,``)):void 0,major:toInt(r.major)??0,minor:toInt(r.minor),patch:toInt(r.patch)};return n||(r.prerelease&&(a.prerelease=splitMeta(r.prerelease)),r.build&&(a.build=splitMeta(r.build))),a}function semVerToString(e,n=!1){let r=`${toGte0(e.major)??0}.${toGte0(e.minor)??0}.${toGte0(e.patch)??0}`;if(!n){let n=_compact(e.prerelease);n.length>0&&(r+=`-${n.join(`.`)}`);let a=_compact(e.build);a.length>0&&(r+=`+${a.join(`.`)}`)}return r}function semVerSatisfies(e,n){let r=toSemVer(e);if(r==null)return!1;let a=semVerToString(r,!0);return(0,import_semver.satisfies)(a,n,{loose:!0,includePrerelease:!0})}function getUpdateChannelIndex(e){return isString(e)?UpdateChannels.indexOf(e):void 0}function toSortable(e){return toInt(e,{strict:!0})??e}function prereleaseSortBy(e){let n=compactBlanks(e);return[first(n,getUpdateChannelIndex)??UpdateChannels.length+1,...rightPadArray(n.map(e=>getUpdateChannelIndex(e)??toSortable(e)),2,-1)]}function buildSortBy(e){return rightPadArray(toA(e).map(e=>toInt(e,{strict:!0})??-1),2,1/0)}function semverSortBy(e){let n=toSemVer(e);return n==null?void 0:[toGte0(n.major)??-1,toGte0(n.minor)??-1,toGte0(n.patch)??-1,...prereleaseSortBy(n.prerelease),...buildSortBy(n.build)]}function semVerCompare(e,n){return cmp(semverSortBy(e),semverSortBy(n))}function semverLt(e,n){return semVerCompare(e,n)<0}function sortNatural(e){return sortBy(e,sortNaturalBy)}var NaturalSplitRE=/[-._/\\]|(?<=\d)(?=\D)|(?<=\D)(?=\d)/;function sortNaturalByRegExp(e,n){return toS(e).split(n).map(e=>toInt(e)??e)}var HasFileExtRE=/\.[^.]{1,5}$/;function filenameSortBy(e){if(e.includes(import_node_path3.sep)||e.includes(`/`)){let n=HasFileExtRE.exec(e);if(n==null)return;let r=stripCopySuffixFromName(e,{aggressive:!1}).replace(HasFileExtRE,``);if(blank(r))return;let a=copySuffixCountFromName(e);return[...sortNaturalByRegExp(r,NaturalSplitRE),a??-1,n[0],e]}}function sortNaturalWithSpaces(e){return/\s/.test(e)?sortNaturalByRegExp(e,/[-\s_./\\]/):void 0}function sortNaturalBy(e){return[...semverSortBy(e)??filenameSortBy(e)??sortNaturalWithSpaces(e)??sortNaturalByRegExp(e,NaturalSplitRE),e.length]}var _SystemPathPatternsDefault=`/boot,/boot/efi,/dev,/dev/**,/proc/**,/run,/run/credentials/**,/run/flatpak/**,/run/lock,/run/snapd/**,/run/user/*/doc,/run/user/*/gvfs,/snap/**,/var/lib/snapd/snap/**,/sys/**,/tmp,/var/tmp,**/#snapshot,/run/docker/**,/var/lib/docker/**,/run/containerd/**,/var/lib/containerd/**,/run/containers/**,/var/lib/containers/**,/var/lib/kubelet/**,/var/lib/lxc/**,/var/lib/lxd/**,/mnt/wslg/distro,/mnt/wslg/doc,/mnt/wslg/versions.txt,/usr/lib/wsl/drivers,/private/var/vm`.split(`,`),ExcludedMountpointPathsBase=sortNatural([..._SystemPathPatternsDefault,`/var/lib/libvirt/**`,`/ps/no-import/**`]),ExcludedMountpointPathsDocker=sortNatural([...ExcludedMountpointPathsBase,`/`,`/etc/hostname`,`/etc/hosts`,`/etc/resolv.conf`]),FileCopyStrategies=strEnum(`auto`,`builtin-reflink`,`builtin`,`builtin-no-wip`,`native-preserve`,`native`),_SystemFsTypesDefault=`autofs,binfmt_misc,bpf,cgroup,cgroup2,configfs,debugfs,devpts,devtmpfs,efivarfs,fusectl,fuse.gvfsd-fuse,fuse.lxcfs,fuse.portal,fuse.snapfuse,fuse.squashfuse,hugetlbfs,mqueue,none,nsfs,proc,pstore,ramfs,rootfs,rpc_pipefs,securityfs,squashfs,sysfs,tmpfs,tracefs`.split(`,`),FilesystemSettings={useFsWatch:new BooleanSetting({category: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.
|
|
85
|
+
For more details see https://nodejs.org/api/fs.html#availability`,defaultValue:()=>!0}),statTimeoutMs:new DurationSetting({aliases:[`commandTimeoutMs`,`fsTimeoutMs`],category: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.
|
|
86
|
+
Set to 0 to disable.`,defaultValue:()=>`30s`}),statRetries:new IntegerSetting({category:SettingCategories.Filesystem,description:`If a stat or readdir times out, how many times can PhotoStructure retry before giving up?.
|
|
87
|
+
Set to 0 to disable retries.`,defaultValue:()=>3}),watchDebounceMs:new DurationSetting({category: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.
|
|
88
|
+
The default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.
|
|
89
|
+
Set to 0 to disable.`,defaultValue:()=>`500ms`}),excludedFilesystemTypes:new StringArraySetting({aliases:[`ignoredFilesystemTypes`],category:SettingCategories.Filesystem,description:`Volumes with these filesystem types will never be scanned or imported.
|
|
90
|
+
These are only relevant to Linux and macOS systems.
|
|
91
|
+
Defaults to @photostructure/fs-metadata's \`SystemFsTypesDefault\`: see https://photostructure.github.io/fs-metadata/variables/index.SystemFsTypesDefault.html`,defaultValue:()=>[..._SystemFsTypesDefault]}),excludedMountpointPaths:new StringArraySetting({aliases:[`ignoredMountpoints`],category:SettingCategories.Filesystem,description:"PhotoStructure library imports skip mountpoints that match these paths, unless the mountpoint is inside a folder PhotoStructure already scans, such as the originals folder or a scan path.\nDefaults to @photostructure/fs-metadata's `SystemPathPatternsDefault` (https://photostructure.github.io/fs-metadata/variables/index.SystemPathPatternsDefault.html), libvirt storage pools, and mountpoints below /ps/no-import, plus Docker bind-mount paths when running in a container.",defaultValue:()=>isDocker()?ExcludedMountpointPathsDocker:ExcludedMountpointPathsBase}),excludedMountpointPathsAdd:new StringArraySetting({category:SettingCategories.Filesystem,description:"Mountpoint paths to add to the default exclusion list.\nThese patterns will be added to the default list which includes @photostructure/fs-metadata's `SystemPathPatternsDefault` plus Docker's /etc/* bind-mount paths.",defaultValue:()=>[]}),excludedMountpointPathsOmit:new StringArraySetting({category:SettingCategories.Filesystem,description:`Mountpoint paths to remove from the default exclusion list.
|
|
92
|
+
If you want to scan a path that's excluded by default, add it here.`}),validateMountpoints:new BooleanSetting({category: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}),mountpointRefreshMinIntervalMs:new DurationSetting({aliases:[`mountpointsTtlMs`],category:SettingCategories.Filesystem,description:`Minimum time between mountpoint refreshes after a path or volume lookup fails. Every sync invalidates cached mount information before resolving its scan paths. A value of 0 disables recovery scans between syncs.`,defaultValue:()=>`15m`}),missingFileVolumeProofTtlMs:new DurationSetting({category:SettingCategories.Filesystem,description:`How long a volume's cached identity may be reused when proving a file was deleted. Raise it if volume metadata reads are slow.`,defaultValue:`7s`,min:`2s`}),fileCopyStrategy:new StringEnumSetting({category:SettingCategories.Filesystem,strEnum:FileCopyStrategies,description:`File copy strategy. See https://photostructure.com/faq/file-copy-strategies/ for details on each strategy.`,defaultValue:FileCopyStrategies.auto}),fileCopyOnlyNative:new BooleanSetting({aliases:[`onlyNativeFileCopy`],category:SettingCategories.Filesystem,description:`DEPRECATED: Use "fileCopyStrategy" instead. This setting will be auto-migrated.
|
|
93
|
+
Should PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?
|
|
94
|
+
PhotoStructure is typically faster than native file copies by 2x or more.
|
|
95
|
+
If true, PhotoStructure will use "ditto" on macOS, "cp" on Linux, and "Copy-Item" via PowerShell on Windows.`,defaultValue:!1}),fileCopyVerify:new BooleanSetting({aliases:[`verifyFileCopy`,`verifyFileCopies`],category:SettingCategories.Filesystem,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}),fileCopyWithReflink:new BooleanSetting({envAliases:[`PS_COPYFILE_FICLONE`],category:SettingCategories.Filesystem,description:`DEPRECATED: Use "fileCopyStrategy" instead. This setting will be auto-migrated.
|
|
96
|
+
Should PhotoStructure use Node.js's COPYFILE_FICLONE flag? If true, file copy operations will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used. Note that this defaulted to true in previous versions of PhotoStructure, but benchmarks show it to be (much) slower on Windows and it may be problematic over NFS, so the default is now false.`,defaultValue:!1}),trySoftDeletes:new BooleanSetting({category:SettingCategories.Filesystem,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").
|
|
97
|
+
This setting defaults to false on docker. For more details, see https://photostructure.com/go/docker-soft-delete`,defaultValue:()=>isNotProd()?!0:!isDocker()}),directorySortThreshold:new IntegerSetting({category:SettingCategories.Filesystem,description:`Maximum directory entries to buffer for sorted (deterministic) iteration. When a directory has more entries than this threshold, or it takes longer than directorySortThresholdMs to get to that threshold, entries are yielded in filesystem order instead of sorted order. Sorted order places files before directories, then uses a case-insensitive natural sort. Set to 0 to disable sorting entirely.`,defaultValue:1024}),directorySortThresholdMs:new DurationSetting({category:SettingCategories.Filesystem,description:`Maximum time to spend buffering directory entries for sorted iteration. If reading a directory takes longer than this (e.g., slow network filesystems), entries are yielded in filesystem order. This prevents slow directories from blocking iteration while waiting to sort. Set to 0 to disable sorting based on time (sorting will still respect directorySortThreshold).`,defaultValue:`7s`}),includeZfsGuids:new BooleanSetting({category:SettingCategories.Filesystem,description:"If true, PhotoStructure will run the `zfs` and `zpool` CLIs to read pool and dataset GUIDs from ZFS volumes on Linux. These compose the strongest, copy-specific volume identity, and are recommended. If false, volume identity falls back to a persisted `.uuid` file, then the filesystem UUID, then the lightweight but re-mappable `f_fsid` stat record. PLEASE NOTE: if you change this setting, rebuild your library afterwards — volumes whose identity changed may otherwise catalog duplicate asset file rows.",defaultValue:!0,advanced:()=>!0})};for(let[e,n]of entries(FilesystemSettings))n._setName(e);var SharpFailOns=strEnum(`none`,`truncated`,`error`,`warning`),RangeRegex=/^(?<lhs>[-+]?\d+(?:\.\d+)?)?\s*-\s*(?<rhs>[-+]?\d+(?:\.\d+)?)?$/;function parseNumeric(e){if(blank(e))return;let n=Number(e);if(isNaN(n))throw Error(`Invalid number: `+JSON.stringify(e));return n}var NumericRanges=class e{constructor(n){this.encodedString=n;let r=toS(n).trim();this.encodedString=blank(r)||e.UnsetValue===r.toLowerCase()?e.UnsetValue:r;let a=this.encodedString===e.UnsetValue?[]:this.encodedString.split(`,`);for(let e of a){let n=Number(e);if(!isNaN(n))this.#e.add(n);else{let n=RangeRegex.exec(e.trim())?.groups;if(n==null)throw Error(`Invalid part: ${JSON.stringify(e)}`);let r=parseNumeric(n.lhs),a=parseNumeric(n.rhs);if(r==null&&a==null)throw Error(`Invalid range format (missing both lhs and rhs of a range): ${JSON.stringify(e)}`);r===a?this.#e.add(r):(r!=null&&this.#e.add(r),a!=null&&this.#e.add(a),this.#t.push([r,a]))}}}encodedString;static UnsetValue=`empty`;#e=new Set;#t=[];test(e){if(!this.encodedString)return!1;if(this.#e.has(e))return!0;for(let[n,r]of this.#t)if((n==null||e>=n)&&(r==null||e<=r))return!0;return!1}toString(){return this.encodedString}},NumericRangesSetting=class extends StringSetting{constructor(e){super({...e,whyInvalid:e=>{try{new NumericRanges(e);return}catch(e){return toError(e)?.message??`Invalid format: `+String(e)}}}),this.watchLater(()=>this.#e.reset())}hasValue(){return this.value!=null}#e=defer(()=>{try{let e=this.value;if(e!=null)return new NumericRanges(e)}catch{}try{return new NumericRanges(this.defaultValue)}catch{}return new NumericRanges(``)});test(e){return this.#e().test(e)}},OptionalFloatSetting=class extends Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:notBlankToS,fromEnv:toFloat})}},OptionalIntegerSetting=class extends Setting{constructor(e){super({...e,toEnv:notBlankToS,fromEnv:toInt,defaultValue:void 0})}},FiltersSettings={disableAllFilters:new BooleanSetting({category: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.
|
|
98
|
+
If 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 StringArraySetting({aliases:[`excludedGlobsAdd`],category:SettingCategories.Filters,description:`This setting adds glob patterns for files and directories that should be excluded from your library.
|
|
99
|
+
These patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.
|
|
100
|
+
See https://forum.photostructure.com/t/1458 for details.`,exampleValue:()=>[`**/tmp/`],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new BooleanSetting({aliases:[`omitDefaultExcludeGlobs`,`disableIgnorableFilters`],category: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 StringArraySetting({aliases:[`excludedGlobsOmit`],category:SettingCategories.Filters,description:`PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.
|
|
101
|
+
If you don't like one or two of them, add them here, and they will be removed from the excluded globs list.
|
|
102
|
+
If you don't want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".
|
|
103
|
+
See https://forum.photostructure.com/t/1458 for details.`}),globsCaseInsensitive:new BooleanSetting({category:SettingCategories.Filters,description:`Should "globs" match case-insensitively?`,defaultValue:!0}),excludeHidden:new BooleanSetting({category:SettingCategories.Filters,description:`PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.
|
|
104
|
+
As of v2023, this defaults to "false", as most people don't use this filesystem feature, and it's expensive for PhotoStructure to check for this flag on every file it imports.
|
|
105
|
+
This setting is ignored on Linux systems.`,defaultValue:!1}),respectFileExtensions:new BooleanSetting({category: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 BooleanSetting({category: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 IntegerSetting({category:SettingCategories.Filters,deprecated:!0,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.
|
|
106
|
+
Note: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.
|
|
107
|
+
This setting is deprecated: use "rejectRating" instead.
|
|
108
|
+
`,defaultValue:0}),rejectRating:new NumericRangesSetting({category:SettingCategories.Filters,blankIsValue:!0,description:`What rating values should force PhotoStructure to omit a photo or video from your library? Ratings are stored in the "rating" XMP tag, and are typically between 0 and 5. 0 typically represents "unrated," 1 is "poor," 2 is "fair", 3 "good," 4 "very good," and 5 "excellent."
|
|
109
|
+
This is a numeric ranges setting. Separate values with a comma. Values can either be a single numeric value or a range. If you want to exclude unrated and poor photos, set this to "0,1". If this is blank, no ratings will be excluded from your library.`,defaultValue:``}),keywordBlocklist:new StringArraySetting({category: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 IntegerSetting({category: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 IntegerSetting({category: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 OptionalFloatSetting({category: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.
|
|
110
|
+
Browsers may have issues playing videos shorter than 2 seconds, and live photos from iOS are typically shorter than 3.5 seconds.`,defaultValue:3.5}),maxVideoDurationSec:new OptionalIntegerSetting({category: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 IntegerSetting({aliases:[`minAssetSizeBytes`,`minAssetSize`,`minFileSizeBytes`],category:SettingCategories.Filters,description:`What's the minimum photo or video size you want imported into your library?
|
|
111
|
+
This setting can prevent small GIFs and screenshots from being imported.
|
|
112
|
+
Values less than 1000 will be ignored.
|
|
113
|
+
A 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.`,defaultValue:50*KB}),maxAssetFileSizeBytes:new IntegerSetting({aliases:[`maxAssetSizeBytes`,`maxAssetSize`,`maxFileSizeBytes`],category: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*GB}),validateJpegImages:new BooleanSetting({category: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 StringEnumSetting({category:SettingCategories.Filters,description:`How sensitive should PhotoStructure be with warnings or errors when loading images?
|
|
114
|
+
Use "none" to try loading images with best efforts, even if the file may be corrupt.
|
|
115
|
+
Use "warning" to be conservative--any defects in the image will prevent it from being imported.
|
|
116
|
+
The default, "truncated," will allow images with minor encoding defects to be imported.`,defaultValue:SharpFailOns.truncated,strEnum:SharpFailOns}),validateRawImages:new BooleanSetting({category: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.
|
|
117
|
+
If a camera produces raw files that LibRaw cannot decode yet, add its mimetype to "validateMimetypeSkiplist" rather than disabling this setting.`,defaultValue:!0}),validateMimetypeSkiplist:new StringArraySetting({category: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 BooleanSetting({category: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 StringArraySetting({category: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.
|
|
118
|
+
Note 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".
|
|
119
|
+
Also see "validationErrorAllowlist".`,defaultValue:()=>[`cannot decode`,`cannot determine format of input`,`corrupt`,`error while decoding`,`failed`,`inconsistent progression sequence`,`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 StringArraySetting({category: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.
|
|
120
|
+
Note the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.
|
|
121
|
+
Also see "validationErrorBlocklist".`,defaultValue:()=>[`warning: ignored non-standard exif`,`invalid SOS parameters for sequential jpeg`,`referenced qt chapter track not found`,`non monotonically increasing dts`]}),rejectedFileCacheThresholdMs:new DurationSetting({category:SettingCategories.Filters,description:`Files rejected by expensive filters (like MIME type detection or file validation) will be cached if the filter or validation step that rejected the file took longer than this threshold (in milliseconds). This speeds up subsequent syncs by skipping re-evaluation of unchanged rejected files for up to a week. Unreadable files are never cached. Set to 0 to disable caching.`,defaultValue:500})};for(let[e,n]of entries(FiltersSettings))n._setName(e);var HardwareSettings={maxCpuTempCelsius:new IntegerSetting({category:SettingCategories.Hardware,description:`CPU temperature limit for pausing sync. Defaults to 96°C because some AMD Ryzen processors intentionally target 95°C under sustained load; the extra degree keeps normal 95°C operation below our configured pause threshold. Intel's maximum junction temperature is commonly 100–110°C, but varies by model. This is a background-work pause threshold, not a universal hardware rating.
|
|
122
|
+
Set a positive Celsius value to enable CPU pauses at that temperature, or at a lower hardware critical limit. This is your chosen limit, not a fallback: a CPU driver's reported max does not override it. Sync resumes after cooling 7°C below the configured limit; when only a lower hardware critical limit applies, its hysteresis is used instead.
|
|
123
|
+
Set to 0 to disable CPU pauses, even at hardware critical; readings remain visible and may warn.
|
|
124
|
+
This setting applies to recognized CPU temperature sensors on Linux. Sensors outside CPU and drive categories are diagnostic only.`,defaultValue:96}),maxHddTempCelsius:new IntegerSetting({category:SettingCategories.Hardware,description:`Stop-work temperature for spinning drives. This is a ceiling: a drive stops at this temperature or its own declared max, whichever is lower. Drive firmware states when the drive itself gives up, which is well past where a library sync should keep it pinned. Sync resumes at the drive's declared max_hyst when its max is the limit and max_hyst is available; otherwise it resumes after cooling 7°C below the limit.
|
|
125
|
+
Published limits for spinning drives vary by class: commonly 55°C for enterprise, 60°C for client, and 65°C for some NAS models, stated as either ambient or case temperature. 52°C leaves 4°C above the 48°C observed under sustained sync while staying below the lowest common published limit; a drive declaring a stricter max keeps it. Solid-state drives use maxSsdTempCelsius. PhotoStructure tells them apart with the drive's own rotational flag; a drive it cannot classify is treated as spinning.
|
|
126
|
+
Set to 0 to disable all temperature pauses for this drive category, including hardware max and critical limits. Readings remain visible and may warn.`,defaultValue:52}),maxSsdTempCelsius:new IntegerSetting({category:SettingCategories.Hardware,description:`Stop-work temperature for solid-state drives, both NVMe and SATA. This is a ceiling: a drive stops at this temperature or its own declared max, whichever is lower. Sync resumes at the drive's declared max_hyst when its max is the limit and max_hyst is available; otherwise it resumes after cooling 7°C below the limit.
|
|
127
|
+
70°C is a common upper operating limit for client SSDs, and some controllers begin thermal management there; Samsung documents the 950 PRO entering its throttling ladder at 75°C. Pausing background sync at 70°C therefore respects the common rated boundary instead of waiting for every drive's firmware to reduce performance. A drive publishing a lower max keeps it.
|
|
128
|
+
A SATA SSD is governed here rather than by maxHddTempCelsius, even though it shares the drivetemp driver with spinning drives: PhotoStructure separates them by the drive's own rotational flag.
|
|
129
|
+
Set to 0 to disable all temperature pauses for this drive category, including hardware max and critical limits. Readings remain visible and may warn.`,defaultValue:70}),warningCelsiusDelta:new IntegerSetting({category:SettingCategories.Hardware,description:`Early-warning headroom below each sensor's effective max temperature. Linux hwmon does not define a separate warning threshold, so PhotoStructure warns this many °C before each sensor's effective max, whether that came from hardware or from a configured limit. The fixed °C gap is intentional: a percentage of Celsius is not a meaningful physical margin. The 5°C default keeps warning close to the stop boundary, while the separate 7°C stop hysteresis makes a tripped sensor cool below the warning boundary before sync resumes. This changes only the warning band; it does not change when sync pauses.
|
|
130
|
+
Set to 0 to disable the separate early-warning band.`,defaultValue:5}),excludedSensorNames:new StringArraySetting({category:SettingCategories.Hardware,description:`Any sensor name that matches any pattern in this list will be ignored. This is a list of simple globs that are applied without case sensitivity. Only '*' and '?' are considered magic characters: '*' matches 0 or more characters, and '?' matches exactly one character.
|
|
131
|
+
Patterns must match the whole sensor name, so wrap a partial name in '*': 'AUXTIN0' matches nothing, but '*AUXTIN0*' matches. A sensor name is its chip, its channel label, and its channel — for example 'nct6798-isa-0290/AUXTIN0/temp3_input'. Sensors read directly from /sys/class/hwmon/ also match their label-less form, so a pattern written before channel labels were reported ('nct6798/temp3_input') still works.
|
|
132
|
+
If you see a sensor that is always reporting a temperature that is incorrect, add its name to this list.`,defaultValue:[]}),minDiskFreeGb:new IntegerSetting({category:SettingCategories.Hardware,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).
|
|
133
|
+
Set this value to 0 to disable free disk space health checks.`,defaultValue:16})};for(let[e,n]of entries(HardwareSettings))n._setName(e);var HealthCheckIds=strEnum(`library-db`,`library-directories`,`library-file-copy`,`library-free-space`,`library-tag-fts`,`library-tag-hierarchy`,`library-asset-file-hash-index`,`ps-version`,`release-branch`,`media-directories`,`nodejs-version`,`problematic-files`,`proc-memory-use`,`proc-security`,`progress-watchdog`,`service-errors`,`settings-env`,`settings-library`,`settings-system`,`auth-admin-email`,`supported-filesystem`,`cache-service`,`sync-rpc`,`systemd`,`system-file-watchers`,`desktop-thermal`,`docker-library-mount`,`system-load`,`system-temp`,`system-version`,`system-volumes`,`system-workers`,`tools-changes`,`tools-exiftool`,`tools-heif`,`tools-jpegtran`,`tools-powershell`,`tools-sharp`,`tools-sqlite-version`,`tools-ripgrep`,`tools-video`,`volume-uuids`),HealthSettings={skipHealthCheckIds:new StringEnumsSetting({category:SettingCategories.Health,description:`List of health check IDs to skip.`,defaultValue:[],strEnum:HealthCheckIds})};for(let[e,n]of entries(HealthSettings))n._setName(e);var DEFAULT_FLIGHT_RECORDER_CAPACITY=64,LoggingSettings={quiet:new BooleanSetting({category: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 StringSetting({envAliases:[`PS_LOG`,`LOG`,`LOG_LEVEL`],category: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:logLevelDefaultValue}),logDir:new StringSetting({category:SettingCategories.Logging,description:`Determines the directory that log files will be written to.`,defaultValue:()=>``}),logRetention:new DurationSetting({category:SettingCategories.Logging,description:`How long should we retain old log files? If set to 0, logs are never deleted.`,defaultValue:`10d`}),logCompression:new BooleanSetting({category:SettingCategories.Logging,description:"Should inactive log files be compressed? Active (currently-written) files are always plain .jsonl so `tail -f` works. Disabling skips the background compressor.",defaultValue:!0}),logWebRequests:new BooleanSetting({category:SettingCategories.Logging,description:`Write an access log for all web requests?`,defaultValue:!1}),logWebDir:new OptionalStringSetting({category:SettingCategories.Logging,description:`Determines the directory that log files will be written to. If unset, will use logDir.`}),logStdout:new BooleanSetting({envAliases:[`LOG_STDOUT`,`PS_STDOUT`],category:SettingCategories.Logging,description:`Log to stdout? This should be false unless you're running a service by hand.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),logFlushMs:new DurationSetting({category:SettingCategories.Logging,description:`How frequently should PhotoStructure flush log entries to disk? Lower values will result in more frequent writes to disk, but will also reduce the amount of data lost in the event of a crash. Higher values will result in less frequent writes to disk at the expense of memory consumption (which shouldn't be an issue unless you're doing debug or trace logging).`,defaultValue:`1s`}),logMaxLinesPerFile:new IntegerSetting({category:SettingCategories.Logging,description:`Maximum number of log entries (one JSONL line per entry) written to a single file before rotating to a new file. Lower values produce more, smaller files; higher values produce fewer, larger files. The default strikes a balance between max file size (which causes performance issues with the log viewer) and number of files (which is unwieldy).)`,defaultValue:()=>1e5}),tailLogs:new BooleanSetting({category: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,propagateToChildren:!1}),logColor:new BooleanSetting({aliases:[`logColour`],category: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.`,defaultValue:()=>!noColor()}),logContextLimit:new IntegerSetting({category:SettingCategories.Logging,description:`PhotoStructure will only log, at most, this number of elements or key/value pairs.`,defaultValue:()=>32}),logSql:new BooleanSetting({category:SettingCategories.Logging,description:`Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.
|
|
134
|
+
This defaults to false.`,defaultValue:()=>!1}),logServer:new OptionalStringSetting({category:SettingCategories.Logging,description:`Format as hostname:port or ip_address:port.
|
|
135
|
+
If set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.
|
|
136
|
+
For more details see https://docs.graylog.org/docs/gelf`,exampleValue:()=>`localhost:12201`}),logServerLevel:new StringSetting({category:SettingCategories.Logging,description:`This is the log level used to filter logs before sending them to "PS_LOG_SERVER".
|
|
137
|
+
If unset, we'll use the value of "PS_LOG_LEVEL".`,defaultValue:logLevelDefaultValue}),logFlightRecorderCapacity:new IntegerSetting({category:SettingCategories.Logging,description:`Maximum number of log entries held by the flight recorder.
|
|
138
|
+
The flight recorder buffers every entry "logLevel" filtered out, down to "logFlightRecorderMinLevel". They are written to the log when a trigger-level event fires, so a warning or error arrives with the context that led up to it, and whatever is still buffered is written when the process exits. Setting "logLevel" to "error" therefore still keeps warnings as context, rather than discarding them.
|
|
139
|
+
The default of 64 holds a little more than three times the log reader's usual 20-line before-context, leaving room for a multi-step shutdown without making every clean exit dump hundreds of routine entries.
|
|
140
|
+
When more entries arrive than this, the oldest are dropped, and a marker in the log records how many were lost and the time span they covered.
|
|
141
|
+
Set to 0 to disable.`,defaultValue:DEFAULT_FLIGHT_RECORDER_CAPACITY}),logFlightRecorderTriggerLevel:new StringEnumSetting({category:SettingCategories.Logging,description:`Log level that triggers a flight recorder flush. Events at this level or more severe cause the buffered entries to be written to the log immediately ahead of them.
|
|
142
|
+
The default, "warn", means warnings arrive with the context that led up to them, which is what makes stalls diagnosable. Set this to "error" to spend that context only on errors.
|
|
143
|
+
Must be more severe than "logFlightRecorderMinLevel".`,strEnum:LogLevels,defaultValue:`warn`}),logFlightRecorderMinLevel:new StringEnumSetting({category:SettingCategories.Logging,description:`Least severe level the flight recorder captures. Default "debug" excludes trace entries. Must be less severe than logFlightRecorderTriggerLevel.`,strEnum:LogLevels,defaultValue:`debug`})};for(let[e,n]of entries(LoggingSettings))n._setName(e);var import_node_os3=require("node:os"),DefaultHttpPort=1787,NetworkingSettings={hostname:new StringSetting({prefixedEnvKeysOnly:!0,category:SettingCategories.Networking,description:`If set, this overrides the local hostname. Useful under docker and when OSes change hostnames due to networking bugs (see macOS).`,defaultValue:()=>(0,import_node_os3.hostname)()}),localhost:new StringSetting({category: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"). For more details see https://letsencrypt.org/docs/certificates-for-localhost/ https://tools.ietf.org/html/draft-ietf-dnsop-let-localhost-be-localhost-02 and https://photostructure.com/faq/troubleshooting/#windows-firewall-issues`,defaultValue:()=>`127.0.0.1`}),httpPort:new IntegerSetting({category:SettingCategories.Networking,description:`Network port for HTTP access to your PhotoStructure library.`,defaultValue:DefaultHttpPort}),noNetwork:new BooleanSetting({category:SettingCategories.Networking,description:`If set to true, PhotoStructure treats the network as unavailable and makes no outbound requests. It does not attempt error reports, update checks, automatic license renewal, photo and video tool installs, or other downloads. That includes the mail server and OIDC provider that email and OIDC sign-in need, so while sign-in is on, either mode pauses library access until noNetwork is off. The "optOut" setting controls telemetry; it does not disable update checks, licensing, or billing.
|
|
144
|
+
While noNetwork is set, PhotoStructure can't renew its license on its own. A browser with network access can still pick a plan, activate, or renew a license without PhotoStructure itself making a request. For renewal, click "Renew in your browser" on the About or Settings page, in a browser that can reach both this library and https://account.photostructure.com/. Your browser fetches the renewed license from your account and hands it to this library.`,defaultValue:!1})};for(let[e,n]of entries(NetworkingSettings))n._setName(e);var OidcSettings={oidcClientId:new OptionalStringSetting({category:SettingCategories.OIDC,description:`The client ID your OIDC provider assigned to PhotoStructure. Required when authMode is "oidc".`}),oidcClientSecret:new OptionalStringSetting({category:SettingCategories.OIDC,sensitive:!0,description:`The client secret your OIDC provider assigned to PhotoStructure. Leading and trailing spaces are removed. Required when authMode is "oidc".`}),oidcIssuer:new OptionalStringSetting({category:SettingCategories.OIDC,description:`The issuer URL of your OIDC provider, like "https://accounts.example.com". PhotoStructure reads the provider's configuration from the issuer's /.well-known/openid-configuration. Register PhotoStructure with the provider using the redirect URI "<externalOrigin>/auth/oidc/callback". Use an "http:" issuer only for a provider on your own trusted network. Required when authMode is "oidc".`,whyInvalid:e=>e==null?void 0:whyInvalidIssuer(e)})};for(let[e,n]of entries(OidcSettings))n._setName(e);function whyInvalidIssuer(e){let n;try{n=new URL(String(e))}catch{return`Expected an http: or https: URL`}if(n.protocol!==`https:`&&n.protocol!==`http:`)return`Expected an http: or https: URL`;if(n.username!==``||n.password!==``)return`An issuer URL cannot hold a username or password`;if(/[?#]/.test(n.href))return`An issuer URL cannot have a query or fragment`}function oidcClientConfigFromSettings(){let e=OidcSettings;if(Object.values(e).some(hasInvalidInput))return;let n=e.oidcIssuer.valueOrDefault,r=e.oidcClientId.valueOrDefault,a=e.oidcClientSecret.valueOrDefault;if(n!=null&&r!=null&&a!=null)return{issuer:n,clientId:r,clientSecret:a}}var OrganizationSettings={copyAssetsToLibrary:new BooleanSetting({aliases:[`copyToLibrary`],category:SettingCategories.Organization,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.
|
|
145
|
+
Read more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .`,defaultValue:!0,envDefault:!0,advanced:()=>!1}),copyToLibraryMimeTypes:new StringArraySetting({category:SettingCategories.Organization,description:`When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.
|
|
146
|
+
Note that MIME types can include an asterisk to do glob-matching.
|
|
147
|
+
See the related system setting "copyAssetsToLibrary".
|
|
148
|
+
A list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .`,defaultValue:()=>[`image/*`,`video/*`]}),assetPathnameFormat:new StringSetting({category:SettingCategories.Organization,description:`If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into <originals directory>/<result of assetPathnameFormat>.
|
|
149
|
+
- See the originalsDir system setting for what your <originals directory> is (it defaults to your library root directory).
|
|
150
|
+
- Please encode this path with forward-slashes, even if you're on Windows.
|
|
151
|
+
- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.
|
|
152
|
+
- If you want to add a static path, escape the pathname with single quotes (like "'photos'/y/MM/dd").
|
|
153
|
+
- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.
|
|
154
|
+
- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").
|
|
155
|
+
- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").
|
|
156
|
+
- Use token "PARENT" as a shorthand for the original file's parent directory name ("to" for "/path/to/photo.jpg").
|
|
157
|
+
- Use token "GRANDPARENT" as a shorthand for the original file's grandparent directory name ("path" for "/path/to/photo.jpg").
|
|
158
|
+
- Use token "EXT" for the filename's extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").
|
|
159
|
+
- Use token "ISO" as a shorthand for "yyyy-MM-dd'T'HH-mm-ss.SSSZZZ" when the capture timezone is known, or "yyyy-MM-dd'T'HH-mm-ss.SSS" otherwise (dashes keep the time separators valid in filenames).
|
|
160
|
+
- Use token "DECADE" for the capture date's decade. For example, "DECADE/y/y-MM-dd/BASE" produces "2020-2029/2026/2026-09-13/image.jpeg" for an image captured on September 13, 2026.
|
|
161
|
+
- Use token "SHORTSHA" for the first 8 characters of the file's content hash, encoded with filesystem-safe characters. Useful for deterministic naming when multiple files share the same basename and date--this is used internally for tests.
|
|
162
|
+
- You can escape other static text by wrapping with single quotes.
|
|
163
|
+
- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .
|
|
164
|
+
- For more details, see https://photostructure.com/getting-started/automatic-library-organization/#asset-pathname-format`,defaultValue:`y/y-MM-dd/BASE`}),assetSubdirectoryDatestampFormat:new StringSetting({category:SettingCategories.Organization,envAliases:[`PS_ASSET_SUBDIR_FORMAT`],description:`This setting has been replaced by "assetPathnameFormat".
|
|
165
|
+
If this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".`,defaultValue:``,deprecated:!0}),writeSourceTagToLibraryCopies:new BooleanSetting({category:SettingCategories.Organization,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}),writeInferredTagsToLibraryCopies:new BooleanSetting({category:SettingCategories.Organization,description:`When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.`,defaultValue:!0}),overwriteOriginal:new BooleanSetting({category:SettingCategories.Organization,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:!0})};for(let[e,n]of entries(OrganizationSettings))n._setName(e);var etv=__toESM(require("exiftool-vendored")),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`,`y-MM-dd'T'HH-mm-ss`,`F`,`FF`],DefaultTimezoneSuffixes=[`ZZ`,`z`],OverrideUTCZoneTags=[`DateTimeUTC`,`GPSDateTime`],CapturedAtTagsPrimary=sortIgnoreCase([`CreationDate`,`DateTimeOriginal`,`SubSecDateTimeOriginal`,`OriginalCreateDateTime`]),CapturedAtTagsSecondary=sortIgnoreCase([`applePhotosDateCreated`,`SubSecCreateDate`,`SubSecModifyDate`,`ModifyDate`,`DateTime`,`DateTimeCreated`,`CreateDate`,`MediaCreateDate`,`CreationTime`]),CapturedAtTagsTertiary=sortIgnoreCase([`DigitalCreationDateTime`,`DateTimeDigitized`,`TrackCreateDate`]),CapturedAtTagsFallback=sortIgnoreCase([`photoTakenTime`,...OverrideUTCZoneTags]),DefaultExcludedExifTags=[`MWG:Description`,`MakerNotes:City`,`MakerNotes:State`,`MakerNotes:Country`,`MakerNotes:Location`,`MakerNotes:Title`],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`.split(`.`);function newlineCharsetHint(e){let n=!1;for(let r=0;r<e.length;r++)if(e[r]===13){if(e[r+1]===10)return`windows-1252`;n=!0}return n?`macintosh`:void 0}function candidateCharsets(e,n){return uniq([newlineCharsetHint(e),n.cameraCharset].filter(e=>e!=null))}function isValidCharset(e){try{return new TextDecoder(e),!0}catch{return!1}}function decode(e,n){try{return new TextDecoder(n,{fatal:!1}).decode(e)}catch{return}}function needsUtf8Recovery(e){return typeof e==`string`&&e.includes(`�`)}function recoverBytes(e,n){for(let r of candidateCharsets(e,n)){let n=decode(e,r);if(n!=null&&!blank(n)&&!hasEncodingCorruption(n))return{text:n,charset:r}}}function recoverInvalidUtf8Tags(e,n){let r=e.invalidUtf8Bytes,a={};if(r==null)return{tags:e,charsetByPath:a};let o={...e},s={};for(let e of Object.keys(r)){let c=r[e];if(c instanceof Uint8Array){if(!needsUtf8Recovery(o[e]))continue;let r=recoverBytes(c,n);r==null?s[e]=c:(o[e]=r.text,a[e]=r.charset);continue}let l={},u=Array.isArray(o[e])?[...o[e]]:void 0;if(u==null)s[e]=c;else{for(let r of Object.keys(c)){let o=c[r];if(!(o instanceof Uint8Array)){l[r]=o;continue}let s=Number(r);if(!needsUtf8Recovery(u[s]))continue;let d=recoverBytes(o,n);d==null?l[r]=o:(u[s]=d.text,a[`${e}.${r}`]=d.charset)}o[e]=u,Object.keys(l).length>0&&(s[e]=l)}}return o.invalidUtf8Bytes=Object.keys(s).length>0?s:void 0,{tags:o,charsetByPath:a}}function validateStringMap(e){if(e!=null&&isObject(e)&&!Array.isArray(e)){for(let[n,r]of entries(e))if(typeof n!=`string`||typeof r!=`string`)return;return e}}function parseStringMap(e){if(notBlank(e))try{return validateStringMap(JSON.parse(e))}catch{return}}function stringifyMap(e){if(e!=null)return stringify(e)}function toTomlInlineTable(e){let n=entries(e).map(([e,n])=>`${JSON.stringify(e)} = ${JSON.stringify(n)}`);return n.length===0?`{}`:`{ ${n.join(`, `)} }`}var StringMapSetting=class extends Setting{constructor(e){super({defaultValue:{},fromEnv:parseStringMap,toEnv:stringifyMap,...e})}toTomlLine({lines:e=[],value:n}={}){let r=n??this.fileValue;return r==null||e.push(`${this.name} = ${toTomlInlineTable(r)}`),e}toTomlLines({includeValue:e=!0}={}){let n=this.toCommentedLines();return wrapTomlToLines({lines:n,wrap:WrapComments,prepend:[`Example value:`],key:this.name,value:void 0}),this.exampleValue!=null&&n.push(`# ${this.name} = ${toTomlInlineTable(this.exampleValue)}`),wrapTomlToLines({lines:n,wrap:WrapComments,prepend:[`Default value:`],key:this.name,value:void 0}),n.push(`# ${this.name} = ${toTomlInlineTable(this.defaultValue)}`),e&&this.toTomlLine({lines:n,value:this.fileValue}),n}isEmpty(){let e=this.valueOrDefault;return e==null||Object.keys(e).length===0}isNotEmpty(){return!this.isEmpty()}get(e){return this.valueOrDefault[e]}has(e){return e in this.valueOrDefault}mapKeys(){return Object.keys(this.valueOrDefault)}entries(){return entries(this.valueOrDefault)}},TagInferenceSettingValues=strEnum(`never`,`always`,`auto`),ExifToolTagNameRE=/^[\w:*?+#^][\w:\-*?+#^]*$/;function whyInvalidExcludedExifTags(e){let n=Array.isArray(e)?e:typeof e==`string`?splitStringArrayKeepingColons(e):void 0;if(n==null)return`must be an array of group-qualified tag names`;for(let e of n){if(typeof e!=`string`)return`every entry must be a group-qualified tag name`;let n=e.split(`:`);if(n.length!==2||n.some(e=>e.length===0)||!ExifToolTagNameRE.test(e))return`every entry must use Group:TagName; invalid entry: ${e}`}}function whyInvalidCharsetByCamera(e){if(e==null)return;let n=e;if(typeof e==`string`)try{n=JSON.parse(e)}catch{return`must be a JSON map of camera name to charset`}if(typeof n!=`object`||!n||Array.isArray(n))return`must be a map of camera name to charset`;for(let e of Object.values(n))if(typeof e!=`string`||!isValidCharset(e))return`unknown charset: ${String(e)} (try "macintosh" or "windows-1252")`}var ParsingSettings={capturedAtTagsPrimary:new StringArraySetting({category:SettingCategories.Parsing,aliases:[`capturedAtTags`],description:`The following tags are examined to determine when a file was captured at.
|
|
166
|
+
The tag with the oldest valid value is returned: order here doesn't matter.
|
|
167
|
+
If none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsSecondary" tags.
|
|
168
|
+
See https://photostructure.com/faq/captured-at/ for details.`,defaultValue:CapturedAtTagsPrimary}),capturedAtTagsSecondary:new StringArraySetting({category:SettingCategories.Parsing,description:`If no capturedAtTagsPrimary are defined, the following tags are examined to determine when a file was captured at.
|
|
169
|
+
The tag with the oldest valid value is returned: order here doesn't matter.
|
|
170
|
+
If none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsTertiary" tags.
|
|
171
|
+
See https://photostructure.com/faq/captured-at/ for details.`,defaultValue:CapturedAtTagsSecondary}),capturedAtTagsTertiary:new StringArraySetting({category:SettingCategories.Parsing,description:`If no capturedAtTagsPrimary or capturedAtTagsSecondary are defined, the following tags are examined to determine when a file was captured at.
|
|
172
|
+
The tag with the oldest valid value is returned: order here doesn't matter.
|
|
173
|
+
If none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.
|
|
174
|
+
See https://photostructure.com/faq/captured-at/ for details.`,defaultValue:CapturedAtTagsTertiary}),capturedAtTagsFallback:new StringArraySetting({category: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.
|
|
175
|
+
See https://photostructure.com/faq/captured-at/ for details.`,defaultValue:CapturedAtTagsFallback}),applePhotosMetadata:new BooleanSetting({category:SettingCategories.Parsing,description:`Read metadata from Apple Photos libraries.
|
|
176
|
+
When PhotoStructure finds a file inside a macOS "*.photoslibrary" bundle, or inside an iPhone/iPad backup's "PhotoData" directory, it reads that library's "Photos.sqlite" (or legacy "photos.db") for metadata that Photos keeps only in its own database: album membership, keywords, named people, titles and descriptions, and locations or capture times that were corrected within Photos.
|
|
177
|
+
The database is only ever read, never written. Values found in the file itself always win; this only fills in what the file doesn't carry.
|
|
178
|
+
On macOS this requires Full Disk Access, as the Photos library is protected by the system.`,defaultValue:!0}),useMWG:new BooleanSetting({category:SettingCategories.Parsing,description:`Enable Metadata Working Group composite tag reading and writing. See https://exiftool.org/TagNames/MWG.html for details.`,defaultValue:!0}),badDates:new StringArraySetting({category: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 BooleanSetting({category: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 OptionalStringSetting({category: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.
|
|
179
|
+
This has no default.`}),likeRating:new IntegerSetting({category:SettingCategories.Parsing,description:`What's the minimum "rating" for an asset to be considered "liked"?
|
|
180
|
+
Know 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").
|
|
181
|
+
PhotoStructure will prefer the XMP Rating tag.
|
|
182
|
+
If the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.
|
|
183
|
+
If you want only ratings of 5 to be considered a "liked" asset, set this to 5.
|
|
184
|
+
This value will be used when assets are liked via the PhotoStructure UI.
|
|
185
|
+
Note that PhotoStructure doesn't import assets with a negative Rating (to respect the "rejected" rating).`,defaultValue:()=>3}),lensMakes:new StringArraySetting({category:SettingCategories.Parsing,description:`Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).`,defaultValue:()=>DefaultLensMakes}),numericTags:new StringArraySetting({category:SettingCategories.Parsing,description:`These tags are expected to contain numeric values (integers or floats). If the tag value is a string, we'll try to parse it as a number.
|
|
186
|
+
Caution: ExifTool is inconsistent about units for some tags, and PhotoStructure **needs** the string value to disambiguate the units. For example, AvgBitrate is (probably) in bits per second (bit/s), while MaxDataRate is (probably) in bytes per second (B/s), so don't add those tags here!`,defaultValue:()=>etv.DefaultExifToolOptions.numericTags}),extraDateTimeFormats:new StringArraySetting({category: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. Each of those is then tried in this machine's locale and in en-US, so the localized tokens (like "F" and "FF") match screenshots named by this desktop, while English month names from files written elsewhere still parse. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.`,defaultValue:()=>DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new StringArraySetting({category: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:()=>DefaultTimezoneSuffixes}),preferTimezoneInferenceFromGps:new BooleanSetting({category:SettingCategories.Parsing,description:`If GPS metadata is present, should we prefer the timezone indicated by GPS metadata over the timezone inferred from any other metadata?
|
|
187
|
+
Note that there are regions that have had their IANA timezone change over time. If you have photos or videos from these regions, you may want to set this to false.`,defaultValue:!0}),allowArchaicTimezoneOffsets:new BooleanSetting({category:SettingCategories.Parsing,description:`Allow parsing of archaic timezone offsets that are no longer in use.
|
|
188
|
+
|
|
189
|
+
These include historical offsets like:
|
|
190
|
+
- "-10:30" (Hawaii 1896-1947)
|
|
191
|
+
- "-04:30" (Venezuela 1912-1965, 2007-2016)
|
|
192
|
+
- "+04:51" (Bombay until 1955)
|
|
193
|
+
- and others from
|
|
194
|
+
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
|
|
195
|
+
|
|
196
|
+
**Warning**: Enabling this may lead to incorrect timezone parsing for modern files, as these offsets are not currently used anywhere. Only enable this if you are specifically working with historical photographs or scanned archival material.`,defaultValue:()=>etv.Settings.allowArchaicTimezoneOffsets.defaultValue,onChange:e=>etv.Settings.allowArchaicTimezoneOffsets.value=e}),allowBakerIslandTime:new BooleanSetting({category:SettingCategories.Parsing,description:`Allow parsing of the UTC-12:00 timezone offset ("Baker Island Time") as a valid timezone. This timezone is not used for any populated land, and is disabled by default to prevent incorrect timezone parsing from files with mangled metadata.`,defaultValue:()=>etv.Settings.allowBakerIslandTime.defaultValue,onChange:e=>etv.Settings.allowBakerIslandTime.value=e}),fuzzyDateParsing:new BooleanSetting({category:SettingCategories.Parsing,description:`When enabled, PhotoStructure also reads dates that aren't strictly formatted, including metadata dates stored as free-form text (like "6/17/2021, 6:35:15 PM UTC") and year-and-month names in filenames and folder names (like "August 1983" or "1983-08"). When disabled, those are ignored, but full dates in filenames and folder names, like "1983-08-01" or "1 August 1983", are still used.`,defaultValue:!0}),fuzzyYearParsing:new BooleanSetting({category:SettingCategories.Parsing,description:`When enabled, PhotoStructure also reads a four-digit year (1800-2099) anywhere in a filename or folder name, like the "1983" in "Hawaii 1983" or "Scans_1983", as a captured-at year. Numbers that aren't years, like the "2000" in "Olympus C2000Z", match too. Folder names are checked for a year only after full dates and year-and-month names. This setting works independently of "fuzzyDateParsing".`,defaultValue:!1}),twoDigitCutoffYear:new IntegerSetting({category: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?
|
|
197
|
+
As an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.
|
|
198
|
+
See https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.
|
|
199
|
+
This defaults to 3 years in the future (modulus 100) and is updated automatically.`,defaultValue:()=>(new Date().getFullYear()+3)%100}),minValidYear:new IntegerSetting({category:SettingCategories.Parsing,description:`If PhotoStructure encounters a date that is in 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.
|
|
200
|
+
For what it's worth, 1826 is the first year a photograph was captured (see https://en.wikipedia.org/wiki/History_of_photography ). KODAK Brownies were available in 1900 (see https://en.wikipedia.org/wiki/Kodak_Brownie ).
|
|
201
|
+
You should set this to the earliest year you expect to find in your library.`,defaultValue:()=>1880}),maxValidFutureMs:new DurationSetting({category:SettingCategories.Parsing,description:`If PhotoStructure encounters a date that is more than this value in the future, it will consider that source to be invalid and look elsewhere for the captured-at date for that given file.
|
|
202
|
+
Set to 0 to disable future date filtering.`,defaultValue:()=>`2d`}),omittedDescriptions:new StringArraySetting({category:SettingCategories.Parsing,description:`Reserved for the planned Title and Caption/Description features; PhotoStructure does not currently use this setting. Its future behavior and migration are not yet settled.`,defaultValue:()=>[`OLYMPUS DIGITAL CAMERA`]}),descriptionTags:new StringArraySetting({category:SettingCategories.Parsing,description:`Reserved for the planned Caption/Description feature; PhotoStructure does not currently use this setting. Its future behavior and migration are not yet settled.`,defaultValue:()=>[`XPSubject`,`Description`,`ImageDescription`,`Caption-Abstract`]}),titleTags:new StringArraySetting({category:SettingCategories.Parsing,description:`Reserved for the planned Title feature; PhotoStructure does not currently use this setting. Its future behavior and migration are not yet settled.`,defaultValue:()=>[`XPTitle`,`Title`,`ObjectName`]}),excludedExifTags:new StringArraySetting({category:SettingCategories.Parsing,description:`Metadata fields that PhotoStructure asks ExifTool to skip. Every entry must be group-qualified, as "Group:TagName"--an unqualified name would suppress that field in every group, including the IPTC and XMP fields we want to keep.
|
|
203
|
+
The MWG Description composite is excluded because ExifTool computes it independently for the main file and each sidecar before PhotoStructure merges them. Keeping the composite can let an older main-file ImageDescription outrank a newer sidecar value under the synthesized Description name. The underlying XMP Description, EXIF ImageDescription, and IPTC Caption-Abstract fields remain available.
|
|
204
|
+
Several camera makers store free-form text in maker-note fields whose names collide with the standard IPTC/XMP fields PhotoStructure reads (Panasonic defines City, State, Country, Location, and Title; Nikon defines Location). When a file has no IPTC or XMP location of its own, that maker-note field becomes the only source for the name, and cameras with damaged maker notes store raw binary there--which then shows up as unreadable "Where" tags or titles.
|
|
205
|
+
These fields carry no metadata that PhotoStructure cannot read from a standard field, so they are excluded by default. If you use Panasonic's on-camera travel mode (which writes real city and country names), remove the matching entries to import them.
|
|
206
|
+
To set this from the environment, use a JSON array or separate entries with "¦": PS_EXCLUDED_EXIF_TAGS='["MakerNotes:City","MakerNotes:Title"]'`,defaultValue:()=>[...DefaultExcludedExifTags],fromEnv:splitStringArrayKeepingColons,whyInvalid:whyInvalidExcludedExifTags}),exifCharsetByCamera:new StringMapSetting({category:SettingCategories.Parsing,description:`Map of camera name to the character set PhotoStructure should use to recover EXIF text that was not valid UTF-8 (for example, older cameras that wrote MacRoman or Windows-1252 titles and descriptions).
|
|
207
|
+
Keys are matched case-insensitively against the camera "Make", or "Make/Model" for a more specific rule; values are character-set names such as "macintosh" or "windows-1252".
|
|
208
|
+
You rarely need this: PhotoStructure already infers the character set from the line-ending style embedded in the text (classic-Mac cameras use a bare carriage return and MacRoman; Windows uses CRLF and Windows-1252). Add an entry only when a file has no such clue and the recovered text looks wrong.`,defaultValue:{},exampleValue:()=>({"KODAK/DCS Pro 14nx":`macintosh`}),whyInvalid:whyInvalidCharsetByCamera}),useStatToInferDates:new BooleanSetting({category:SettingCategories.Parsing,description:`When enabled, and no other source supplies the "captured-at" time, PhotoStructure uses the earlier of the file's creation time ("birthtime") and modification time ("mtime"). On filesystems that don't record a creation time, it uses the modification time. Note that these values are not very reliable, as file transfers and backups frequently don't retain these values correctly.`,defaultValue:!0}),usePathsToInferDates:new BooleanSetting({category: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 BooleanSetting({category: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 directory names of files that are in your PhotoStructure library, and in their filenames when "assetPathnameFormat" puts a date in them. This defaults to false, as PhotoStructure names those from the captured-at it already chose, and prior versions of PhotoStructure may have placed files into incorrect datestamped directories. When the filename part of "assetPathnameFormat" has no date fields, like the default "BASE", dates in library filenames are used even when this setting is off.`,defaultValue:!1}),backfillTimezones:new BooleanSetting({category: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.
|
|
209
|
+
Setting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.
|
|
210
|
+
Prior versions of exiftool-vendored would use the file's ".zone" as a backstop even if this was set to false.
|
|
211
|
+
As of version 2023.10, this now defaults to true, as it's more likely to be what people expect.`,defaultValue:!0}),inferTimezoneFromDatestamps:new BooleanSetting({category:SettingCategories.Parsing,description:`We always look at {@link Tags.TimeZone}, {@link Tags.TimeZoneOffset}, {@link Tags.OffsetTimeOriginal}, {@link Tags.OffsetTimeDigitized}, and GPS metadata to infer the timezone.
|
|
212
|
+
If 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.
|
|
213
|
+
This defaults to true as of version 2023.10.`,defaultValue:!0}),enableSiblingInference:new BooleanSetting({category:SettingCategories.Parsing,deprecated:!0,description:`This setting has been replaced by "inferenceSiblingRadius". Set inferenceSiblingRadius to 0 to disable sibling inference.`,defaultValue:!0}),siblingInference:new StringEnumSetting({category:SettingCategories.Parsing,deprecated:!0,description:`This setting has been replaced by "inferenceSiblingRadius". Set inferenceSiblingRadius to 0 to disable sibling inference.`,strEnum:TagInferenceSettingValues,defaultValue:TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new FloatSetting({category:SettingCategories.Parsing,deprecated:!0,description:`This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.`,defaultValue:.6}),siblingInferenceBasenameCoeffPct:new BoundedIntegerSetting({category:SettingCategories.Parsing,description:`What's the minimum case-insensitive Sørensen–Dice similarity index between file basenames, without the extension, to be used for sibling inference?
|
|
214
|
+
0 will accept all siblings, 100 will only accept exact matches.`,defaultValue:60,max:100,min:0}),inferenceSiblingRadius:new BoundedIntegerSetting({category:SettingCategories.Parsing,description:`The maximum number of nearby sibling files "before" and "after" (as per "natural" sort) to examine when inferring timezone, captured-at, or make/model from neighboring files. Higher values increase accuracy but slow down tag inference for each file. Setting this to 0 will disable sibling inference.`,defaultValue:7,min:0,max:100})};for(let[e,n]of entries(ParsingSettings))n._setName(e);function isSiblingInferenceEnabled(){return gt0(ParsingSettings.inferenceSiblingRadius.valueOrDefault)}var import_node_path4=__toESM(require("node:path")),DefaultDockerLibraryDir=`/ps/library`,LibraryDirSettingNames=[`libraryDir`,`libraryPath`,`library`],DockerLibraryDirEnvKeys=[`PS_LIBRARY_DIR`,`PS_LIBRARY_PATH`,`PS_LIBRARY`],LibraryDirSettingEnvKeys=[...DockerLibraryDirEnvKeys,...LibraryDirSettingNames];function whyInvalidPathMap(e,n,r){return a=>{if(a==null)return;let o=a;if(typeof a==`string`)try{o=JSON.parse(a)}catch{return`must be a JSON map of ${e} to ${n}`}if(typeof o!=`object`||!o||Array.isArray(o))return`must be a map of ${e} to ${n}`;for(let[n,a]of entries(o)){if(!import_node_path4.default.isAbsolute(n))return`${e}s must be absolute: ${n}`;let o=r(a);if(o!=null)return o}}}var PathSettings={libraryDir:new OptionalStringSetting({aliases:[...LibraryDirSettingNames.slice(1)],category:SettingCategories.Paths,description:`This is the absolute path to your PhotoStructure library. If missing, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes). To forget a previously-chosen library, set PS_RESET_LIBRARY_DIR=true for one launch.`,defaultValue:()=>``,advanced:()=>!1}),hostPaths:new StringMapSetting({category:SettingCategories.Paths,description:`Lists the directories bind-mounted into PhotoStructure's container, host path first, the way Docker's -v option writes them. /open and /api/preview take a file's host path, and only under one of these (/api/preview follows symbolic links in them): a requested path has the longest matching host path replaced by its container path, and any other path gets 404. On an install without a container, map each folder to itself. Only this setting and the keys of "fileBrowserUrls" name host paths: every other path setting takes container paths. Keys and values are absolute paths. Set PS_HOST_PATHS to a JSON object, like PS_HOST_PATHS='{"/mnt/HDDs/Photos":"/ps/originals"}'. JSON is required because "=", ":" and ";" are valid in path names.`,defaultValue:{},whyInvalid:whyInvalidPathMap(`host path`,`container path`,e=>typeof e==`string`&&import_node_path4.default.isAbsolute(e)?void 0:`container paths must be absolute: ${String(e)}`)}),fileBrowserUrls:new StringMapSetting({category:SettingCategories.Paths,description:`Maps each host folder to the web address of that folder in a file browser, such as a NAS's web interface. When a file lives under one of these folders, the asset info panel links to its folder there. Keys are absolute host paths, mapped to PhotoStructure's container paths through "hostPaths": a folder links only when a "hostPaths" entry covers it, so on an install without a container, map the folder to itself there. Values are http or https URLs. Set PS_FILE_BROWSER_URLS to a JSON object, like PS_FILE_BROWSER_URLS='{"/mnt/HDDs/Photos":"https://deck.hexos.com/folders/Photos/files"}'. JSON is required because "=", ":" and ";" are valid in path names.`,defaultValue:{},whyInvalid:whyInvalidPathMap(`host path`,`file browser URL`,e=>typeof e==`string`&&/^https?:\/\//i.test(e)?void 0:`file browser URLs must be http or https: ${String(e)}`)}),previewsDir:new StringSetting({category: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.
|
|
215
|
+
NOTE: "originalsDir" 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.
|
|
216
|
+
For more details see https://forum.photostructure.com/t/hybrid-photostructure-libraries/775`,defaultValue:()=>`.photostructure/previews`}),originalsDir:new StringSetting({aliases:[`originalDir`],category: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.
|
|
217
|
+
If 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.
|
|
218
|
+
This system setting needs to be set appropriately on different computers (it won't be set automatically!)
|
|
219
|
+
If 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.
|
|
220
|
+
For more details see 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`,defaultValue:``}),projectDir:new OptionalStringSetting({category:SettingCategories.Paths,transient:!0,description:`This directory contains the public/, data/, views/, and tools/ directories that PhotoStructure relies on to run. This is determined by PhotoStructure automatically.`}),scanAllDrives:new BooleanSetting({category:SettingCategories.Paths,description:`Should PhotoStructure scan all folders on all drives available to this computer for photos and videos? On macOS, this scans all external volumes plus /Users. To scan other boot-volume directories, add them to "scanPaths".`,defaultValue:!0,advanced:()=>!1}),scanMyPictures:new BooleanSetting({category: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 StringArraySetting({aliases:[`scanPath`],category: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 StringArraySetting({category:SettingCategories.Paths,description:`For internal use only: this is an array of absolute paths provided on the command line to import. This overrides "scanPaths", and should always be scanned for changes. For more details see https://forum.photostructure.com/t/1597/4`,transient:!0,advanced:()=>!0}),pidFile:new OptionalStringSetting({category:SettingCategories.Paths,envAliases:[`PIDFILE`],description:`This is the absolute path to the PID file for the main process. PhotoStructure for Node defaults to main.pid in the system config directory. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.`,exampleValue:()=>`/var/run/photostructure.pid`}),cacheDir:new StringSetting({category:SettingCategories.Paths,envAliases:[`PS_TMP_DIR`,`PS_TEMP_DIR`],description:`Where would you like PhotoStructure's scratch file directory? This must be a fast, local disk with several gigabytes free.
|
|
221
|
+
Note 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!
|
|
222
|
+
If this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.`,defaultValue:()=>``})};for(let[e,n]of entries(PathSettings))n._setName(e);var PerformanceSettings={emitTimingsOnExit:new BooleanSetting({category:SettingCategories.Performance,transient:!0,propagateToChildren:!1,description:`If true, PhotoStructure will emit a JSON payload containing function performance information including timings to stdout on exit.`,defaultValue:!1}),enableSIMD:new BooleanSetting({category:SettingCategories.Performance,description:`Should PhotoStructure enable SIMD extensions when running image operations? This defaults to true, but automatically downgrades to false.`,defaultValue:()=>!0}),enableVipsCache:new BooleanSetting({category:SettingCategories.Performance,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})};for(let[e,n]of entries(PerformanceSettings))n._setName(e);var PixiSettings={pixiVersion:new OptionalStringSetting({category:SettingCategories.Tools,description:`Advanced: install this version of the Pixi package manager instead of the version PhotoStructure pinned and tested. Give the release version without a leading "v", like "0.76.2".
|
|
223
|
+
This must be set together with pixiSha256, or PhotoStructure will refuse to install: a version without its checksum could only be verified against the same server that served the download, which is exactly what the pin protects against.
|
|
224
|
+
Find the checksum on the release page at https://github.com/prefix-dev/pixi/releases — it is per operating system and per CPU architecture, so a settings file copied between machines of different architectures will need a different value.`,exampleValue:()=>`0.76.2`,whyInvalid:e=>{if(e!=null&&(typeof e!=`string`||!/^\d+\.\d+\.\d+$/.test(e.trim())))return`must be a version like "0.76.2" (no leading "v")`}}),pixiSha256:new OptionalStringSetting({category:SettingCategories.Tools,description:`Advanced: the expected SHA-256 checksum, in lowercase hexadecimal, of the Pixi download named by pixiVersion. Must be set together with pixiVersion.
|
|
225
|
+
The checksum covers the archive for this machine's operating system and CPU architecture. If it does not match what was downloaded, the install stops and nothing is run.`,exampleValue:()=>`255f8930c1d68d7d7914253fa56ed6911229980610cac4b5f55334844f6568f7`,whyInvalid:e=>{if(e!=null&&(typeof e!=`string`||!/^[0-9a-f]{64}$/.test(e.trim().toLowerCase())))return`must be 64 hexadecimal characters`}})};for(let[e,n]of entries(PixiSettings))n._setName(e);function normalizeRotation(e,n=!1){if(!isNumber(e))return;n&&(e=-e);let r=Math.round((e%360+360)%360/90)*90;return r===360?0:r}function swappableRotation(e){if(e==null)return!1;let n=normalizeRotation(e);return n===90||n===270}var DimensionsRE=/^\s*(?<width>\d+)\s*[x×]\s*(?<height>\d+)\s*$/i;function isDimensions(e){return e!=null&>0(e.width)&>0(e.height)}function parseDimensions(e){if(e==null)return;let n=DimensionsRE.exec(e);if(n==null)return;let r={width:Number(n.groups.width),height:Number(n.groups.height)};return isDimensions(r)?r:void 0}function parseDimensionsList(e){if(e==null)return;let n=[];for(let r of e.split(`,`)){let e=parseDimensions(r);if(e==null)return;n.push(e)}return n.length===0?void 0:n}function dimensionsToString(e){return`${e.width}x${e.height}`}function dimensionsListToString(e){return e.map(dimensionsToString).join(`,`)}function normalizeDimensionsList(e){let n=parseDimensionsList(e);return n==null?void 0:dimensionsListToString(n)}function pickDims(e){return pick(e,`width`,`height`)}function dimEql(e,n){return e.width===n.width&&e.height===n.height}function fmtDim(e,n=` `){return`${e.width}${n}\xD7${n}${e.height}`}function dimToSize(e){return pixels2size(e.width*e.height)}function dimSwap(e){return{width:e.height,height:e.width}}function maybeDimSwap(e,n){return swappableRotation(n)?dimSwap(e):e}function dmegapixels(e){return megapixels(pixels(e))}function pixels(e){return(toGt0(e?.width)??0)*(toGt0(e?.height)??0)}function previewResolutionOption(e,n,r){let a=normalizeDimensionsList(n);return{label:e,...r==null?{}:{alias:r},fitInside:n,normalizedFitInside:a}}var PreviewResolutionOptions=Object.freeze([previewResolutionOption(`480p`,`854×480,480×854`,`SD`),previewResolutionOption(`720p`,`1280×720,720×1280`,`HD`),previewResolutionOption(`1080p`,`1920×1080,1080×1920`,`FHD`),previewResolutionOption(`1440p`,`2560×1440,1440×2560`,`QHD`),previewResolutionOption(`4K`,`4096×2160`,`UHD`),previewResolutionOption(`5K`,`5120×2880`),previewResolutionOption(`6K`,`6144×3456`),previewResolutionOption(`8K`,`7680×4320`)]),PreviewCacheProfiles=strEnum(`xs`,`s`,`m`,`l`,`xl`),PreviewCacheProfileOptions=Object.freeze([{value:PreviewCacheProfiles.xs,label:`Minimum`,title:`Keep the smallest preview cache`,description:`May download larger files while browsing`,maxThumbnailLongEdge:480,previewPixelWastePct:0},{value:PreviewCacheProfiles.s,label:`Small`,title:`Use a smaller preview cache`,description:`Smaller thumbnails and fewer cached preview sizes`,maxThumbnailLongEdge:600,previewPixelWastePct:90},{value:PreviewCacheProfiles.m,label:`Balanced`,title:`Recommended for most libraries`,description:`Balances preview disk space and browsing quality`,maxThumbnailLongEdge:720,previewPixelWastePct:80},{value:PreviewCacheProfiles.l,label:`Large`,title:`Keep sharper browsing previews`,description:`Sharper thumbnails and less network data`,maxThumbnailLongEdge:840,previewPixelWastePct:70},{value:PreviewCacheProfiles.xl,label:`Maximum`,title:`Keep the sharpest browsing previews`,description:`Sharpest thumbnails and least network data`,maxThumbnailLongEdge:960,previewPixelWastePct:60}]),DefaultPreviewCacheProfile=PreviewCacheProfiles.m;function previewCacheProfileOption(e){return PreviewCacheProfileOptions.find(n=>n.value===e)}var MinThumbnailLongEdge=60,MinMaxThumbnailLongEdge=480,MaxMaxThumbnailLongEdge=960,DefaultMaxThumbnailLongEdge=720,DefaultPreviewPixelWastePct=80,PreviewPixelWastePct=lazy(()=>DefaultPreviewPixelWastePct),MaxThumbnailLongEdge=lazy(()=>DefaultMaxThumbnailLongEdge);function maxPixelRatio(e){return 1/(1-e/100)}function thumbnailWidthsForPixelWaste(e,{maxThumbnailLongEdge:n=DefaultMaxThumbnailLongEdge,maxOutputLongEdge:r=n}={}){let a=Math.max(1,Math.min(Math.floor(n),Math.floor(r))),o=Math.min(MinThumbnailLongEdge,a);if(a<=o||e===0)return[a];let s=Math.max(1,Math.ceil(Math.log(a*a/(o*o))/Math.log(maxPixelRatio(e)))),c=[a];for(let e=1;e<s;e++){let n=Math.max(1,Math.round(a*(o/a)**(e/s)));n<c[c.length-1]&&n>o&&c.push(n)}return c[c.length-1]!==o&&c.push(o),c}var CropStrategies=strEnum(`center`,`entropy`,`attention`),DefaultIncludedPreviewTags=[`AttributionName`,`AttributionURL`,`capturedAt`,`Copyright`,`exposureSettings`,`GPSLatitude`,`GPSLongitude`,`License`,`Make`,`Model`,`Permits`,`Prohibits`,`Rating`,`Requires`,`Source`],import_node_os4=__toESM(require("node:os")),logger2=lazy2(()=>mkLogger(`work.CpuInfo`)),cpuInfo=lazy2(()=>import_node_os4.default.cpus(),5*minuteMs),cpuCount=lazy2(()=>{try{let e=import_node_os4.default.availableParallelism?.(),n=cpuInfo().length;return logger2().tap({msg:`cpuCount()`,result:clamp(1,128,Math.ceil(e??n)),meta:{availableParallelism:e,cpuInfoLength:n}})}catch(e){return logger2().warn(`availableParallelism()/cpuCount() failed`,{error:e}),1}});function validDimensions(e){return!Array.isArray(e)||e.length<1||e.length>2||!e.every(isDimensions)?!1:new Set(e.map(e=>`${e.width}x${e.height}`)).size===e.length}function square(e){let n=typeof e==`number`?e:Number(e);return Number.isSafeInteger(n)&&n>0?[{width:n,height:n}]:void 0}function parseSettingDimensions(e,n){if(validDimensions(e))return e.map(({width:e,height:n})=>({width:e,height:n}));if(typeof e==`number`)return n?square(e):void 0;if(typeof e!=`string`)return;let r=e.trim();if(n&&/^\d+$/.test(r))return square(r);let a=parseDimensionsList(r);return validDimensions(a)?a:void 0}function formatDimensions(e,n){let r=parseSettingDimensions(e,n);return r==null?void 0:dimensionsListToString(r)}var DimensionsSetting=class extends Setting{constructor(e){if(!validDimensions(e.defaultValue))throw Error(`DimensionsSetting defaultValue must contain one or two unique positive integer dimensions`);let n=e.legacySquareNumbers===!0;super({...e,toEnv:e=>formatDimensions(e,n),fromEnv:e=>parseSettingDimensions(e,n)}),this.options=e}options;addToJsonDocs(){return{"valid format":`WIDTHxHEIGHT[,WIDTHxHEIGHT] (x, X, or × accepted)`}}toTomlLine({lines:e=[],value:n}={}){let r=this.toEnv(n??this.fileValue);return r!=null&&e.push(`${this.name} = ${JSON.stringify(r)}`),e}toTomlLines({includeValue:e=!0}={}){let n=this.toCommentedLines();return wrapTomlToLines({lines:n,wrap:WrapComments,prepend:[`Example value:`],key:this.name,value:this.toEnv(this.exampleValue)}),wrapTomlToLines({lines:n,wrap:WrapComments,prepend:[`Default value:`],key:this.name,value:this.toEnv(this.defaultValue)}),e&&this.toTomlLine({lines:n,value:this.fileValue}),n}},DisableablePercentageSetting=class extends Setting{constructor(e){if(!isNumber(e.minEnabled)||e.minEnabled<=0)throw Error(`DisableablePercentageSetting minEnabled must be greater than 0`);if(!isNumber(e.maxEnabled)||e.maxEnabled>100)throw Error(`DisableablePercentageSetting maxEnabled must not exceed 100`);if(e.minEnabled>e.maxEnabled)throw Error(`DisableablePercentageSetting minEnabled must not exceed maxEnabled`);super({...e,toEnv:notBlankToS,fromEnv:n=>opt(n).flatMap(toFloat).map(n=>n===0?0:n<e.minEnabled?e.minEnabled:n>e.maxEnabled?e.maxEnabled:n).get()}),this.options=e}options;addToJsonDocs(){return{"disabled value":0,"minimum enabled value":this.options.minEnabled,"maximum enabled value":this.options.maxEnabled}}},OptionalBooleanSetting=class extends Setting{constructor(e){super({toEnv:notBlankToS,fromEnv:toBoolean,defaultValue:void 0,...e})}},MinFitPreviewLongEdge=160,MinPreviewPixelWastePct=40,MaxPreviewPixelWastePct=95;function whyInvalidPreviewFitInside(e){if(Array.isArray(e))return e.every(e=>Math.max(e.width,e.height)>=MinFitPreviewLongEdge)?void 0:`long edge must be at least ${MinFitPreviewLongEdge}`}var PreviewsSettings={previewQuality:new BoundedIntegerSetting({aliases:[`jpegQuality`],category: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 and display, values less than 60 can produce noticeable artifacts, and values greater than 95 can substantially increase preview file sizes with little quality gain.`,defaultValue:()=>80,max:100,min:10}),previewProgressive:new BooleanSetting({category: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 BooleanSetting({aliases:[`jpegMinimized`,`previewMinimised`,`jpegMinimised`],category: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.
|
|
226
|
+
This setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.
|
|
227
|
+
This automatically defaults to true if at least 4 CPU cores are present.`,defaultValue:()=>isNotProd()?!0:cpuCount()>=4}),dcrawEmuArgs:new StringArraySetting({category: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.
|
|
228
|
+
Run "dcraw_emu" with no arguments to get usage help.
|
|
229
|
+
"-q 1" sets interpolation quality to "0".
|
|
230
|
+
"-H 2" turns on highlight blending.
|
|
231
|
+
"-w" uses the camera-set white balance.
|
|
232
|
+
Note: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.`,defaultValue:[`-q`,`0`,`-w`]}),iccProfileMappings:new StringArraySetting({category: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 StringEnumSetting({category: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:CropStrategies.attention,strEnum:CropStrategies}),previewSharpen:new BooleanSetting({aliases:[`sharpen`],category: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}),photoPreviewFitInside:new DimensionsSetting({aliases:[`photoPreviewMaxDim`],category:SettingCategories.Previews,description:`One or two maximum fit boxes for generated photo previews, written as "WIDTHxHEIGHT[,WIDTHxHEIGHT]". PhotoStructure fits each original inside every box without enlarging it and uses the highest-resolution result. The default 4096x2160 fits a landscape 4K display. Smaller boxes save disk space; larger boxes preserve more detail. This does not modify originals or prevent browser-compatible originals from being streamed directly.`,defaultValue:[{width:4096,height:2160}],legacySquareNumbers:!0,whyInvalid:whyInvalidPreviewFitInside}),previewCacheProfile:new StringEnumSetting({category:SettingCategories.Previews,description:`Chooses how much preview disk space PhotoStructure uses to keep gallery thumbnails sharp and browsing responsive. Larger profiles create larger thumbnails and more intermediate preview sizes. The Settings page labels these xs through xl as "Minimum", "Small", "Balanced", "Large", and "Maximum". The default, m, is recommended for most libraries.
|
|
233
|
+
Changing this rebuilds your preview cache in the background: current previews keep working until their replacements are ready, but large libraries may take several days.
|
|
234
|
+
This setting changes the defaults of maxThumbnailLongEdge and previewPixelWastePct; explicit values for either advanced setting take precedence.`,defaultValue:DefaultPreviewCacheProfile,strEnum:PreviewCacheProfiles}),maxThumbnailLongEdge:new BoundedIntegerSetting({advanced:()=>!0,category:SettingCategories.Previews,description:`Maximum long edge, in pixels, of generated gallery thumbnails. Larger values keep thumbnails sharper on high-density displays but use more preview disk space. The previewCacheProfile setting chooses this setting's default; an explicit value overrides that part of the profile.`,defaultValue:DefaultMaxThumbnailLongEdge,min:MinMaxThumbnailLongEdge,max:MaxMaxThumbnailLongEdge}),previewPixelWastePct:new DisableablePercentageSetting({advanced:()=>!0,category:SettingCategories.Previews,description:`Limits the percentage of a selected preview that may be beyond what the browser requested. Set this to 0 to disable intermediate sizes. Enabled values are 40 through 95; lower values prepare more sizes, using more preview disk space but speeding browsing on slow networks. The previewCacheProfile setting chooses this setting's default; an explicit value overrides that part of the profile.`,defaultValue:DefaultPreviewPixelWastePct,minEnabled:MinPreviewPixelWastePct,maxEnabled:MaxPreviewPixelWastePct}),previewOriginalDirectly:new OptionalBooleanSetting({category:SettingCategories.Previews,description:`Can PhotoStructure skip generating a preview size for assets that are in a natively-supported browser format (like JPEG)?
|
|
235
|
+
If you know you'll never eject any synced directories and you aren't using copyAssetsToLibrary, set this to true.
|
|
236
|
+
If this is unset, PhotoStructure defaults this to true for assets in your originals and library directory hierarchies, and false otherwise (so ejected external directories don't cause 404s).`}),skipEmbeddedImageMimeTypes:new StringArraySetting({category:SettingCategories.Previews,description:`PhotoStructure's image library, "sharp," can be quite efficient at loading very large images that it supports natively. When we encounter an image with the following mimetypes, we will skip using embedded thumbnail and preview images, even if they are present.`,defaultValue:[`image/tiff`,`image/jpeg`,`image/png`,`image/webp`]}),embeddedPreviews:new StringArraySetting({category: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.
|
|
237
|
+
Note that this does not include ThumbnailImage or ThumbnailTIFF, as those can be letterboxed.
|
|
238
|
+
Set this to an empty array to disable using embedded previews.`,defaultValue:[`PreviewImage`,`PreviewTIFF`,`JpgFromRaw`,`JpgFromRaw2`]}),embeddedThumbnails:new StringArraySetting({category: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.
|
|
239
|
+
Set this to an empty array to disable using embedded previews.`,defaultValue:[`ThumbnailImage`,`ThumbnailTIFF`]}),maxThumbTrimPct:new BoundedFloatSetting({category:SettingCategories.Previews,description:`When PhotoStructure uses embedded image thumbnails, some cameras will add black "letterboxing" to the top and bottom of the image. This setting controls how much of the top and bottom of the image should be trimmed to remove this letterboxing. A value of 0 means no trimming. Typical letterboxing is only about 12%, so 16% is a safe default. If the letterboxing is found to be more than this amount, the thumb will be ignored by the image processing pipelines.`,defaultValue:()=>16,min:0,max:50}),thumbTrimAliasPixels:new BoundedIntegerSetting({category:SettingCategories.Previews,description:`When PhotoStructure uses embedded image thumbnails, some cameras will add black "letterboxing" to the top and bottom of the image. This letterboxing may be "aliased" with image content, which causes image hash content to be incorrect.`,defaultValue:()=>2,min:0,max:8}),skipPreviews:new BooleanSetting({category:SettingCategories.Previews,description:`Only used for tests.`,advanced:()=>!0,defaultValue:!1,transient:!0,propagateToChildren:!1}),includePreviewTags:new BooleanSetting({category: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 StringArraySetting({category: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.
|
|
240
|
+
- "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.
|
|
241
|
+
- "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).
|
|
242
|
+
- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.`,defaultValue:()=>DefaultIncludedPreviewTags})};for(let[e,n]of entries(PreviewsSettings))n._setName(e);var DO_NOT_TRACK_ENV_KEYS=[`DO_NOT_TRACK`,`DNT`,`GPC`];function doNotTrack(){for(let e of DO_NOT_TRACK_ENV_KEYS)if(isTrue(process.env[e]))return!0;return!1}var PrivacySettings={allowUserAgent:new BooleanSetting({category: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?
|
|
243
|
+
See https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.`,defaultValue:!1}),optOut:new BooleanSetting({aliases:[`doNotTrack`],envAliases:DO_NOT_TRACK_ENV_KEYS,category:SettingCategories.Privacy,description:`If set to true, PhotoStructure does not send telemetry about your library, browser, or operating system. It disables error reports (including Sentry) and installation details in outgoing User-Agent headers by setting "reportErrors=false" and "allowUserAgent=false".
|
|
244
|
+
Opting out does not prevent update checks, choosing a PLUS plan, activation, billing, or license renewal; set "autoUpdateCheck=false" to stop update checks. It also allows software downloads, such as the photo and video tools that Pixi installs. To treat the network as unavailable and prevent PhotoStructure from making outbound requests, set "noNetwork=true".
|
|
245
|
+
PhotoStructure also respects "DO_NOT_TRACK", "DNT", and "GPC" as aliases for this setting. PhotoStructure, Inc. never shares or sells user telemetry or data.
|
|
246
|
+
See https://photostructure.com/legal/privacy/ for more details about PhotoStructure's privacy policies.`,defaultValue:()=>doNotTrack()})};for(let[e,n]of entries(PrivacySettings))n._setName(e);var import_node_os5=__toESM(require("node:os")),PriorityClasses=strEnum(`Normal`,`BelowNormal`,`Idle`,`Low`),PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),PriorityClassToNode=Object.freeze({AboveNormal:import_node_os5.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:import_node_os5.default.constants.priority.PRIORITY_NORMAL,BelowNormal:import_node_os5.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:import_node_os5.default.constants.priority.PRIORITY_LOW,Low:import_node_os5.default.constants.priority.PRIORITY_LOW});function priorityPosixToClass(e){if(e!=null&&isFinite(e))return e<PriorityClassToPosix.BelowNormal?PriorityClasses.Normal:e<PriorityClassToPosix.Idle?PriorityClasses.BelowNormal:PriorityClasses.Idle}var ProcessesSettings={shortProcessNames:new BooleanSetting({category: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:()=>!isElectron()}),minDelayBetweenSpawnMs:new DurationSetting({category: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. For more details see https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#minDelayBetweenSpawnMillis`,defaultValue:()=>encodeDuration(1500)}),minDelayBetweenRetriesMs:new DurationSetting({category: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 IntegerSetting({category:SettingCategories.Processes,description:`If a task has an error, how many times should we retry before giving up?
|
|
247
|
+
If you have a flaky network, this can help ensure imports are comprehensive.
|
|
248
|
+
Set this to 0 to disable retries.`,defaultValue:()=>2}),problematicCooldownMs:new DurationSetting({category:SettingCategories.Processes,description:`Base cooldown period for files that timeout during sync. When a file fails, it enters cooldown for this duration multiplied by its strike count. For example, with a 1-day base: first strike = 1 day cooldown, second strike = 2 days, etc. After the cooldown period, the file is eligible for retry.`,defaultValue:()=>`1d`}),problematicMaxStrikes:new IntegerSetting({category:SettingCategories.Processes,description:`Maximum number of strikes before a file is permanently blocked. Files that fail this many times (within the decay window) will not be retried until manually cleared via the System Activity page. Set to 0 to disable permanent blocking (files always get another chance after cooldown).`,defaultValue:()=>3}),problematicDecayMs:new DurationSetting({category:SettingCategories.Processes,description:`How long until old strikes "decay" and no longer count toward the maximum. This allows files to recover if the underlying issue was fixed (e.g., PS update, file repaired). Only strikes within this window count toward cooldown and permanent blocking. Set to 0 to never decay strikes (all historical strikes count forever).`,defaultValue:()=>`8w`}),progressWatchdogTimeoutMs:new DurationSetting({category:SettingCategories.Processes,description:`If no task progress occurs within this duration while work is pending, sync is considered "wedged" and the health check will report an error. This detects situations where sync has completely stalled (not just individual slow tasks). Set to 0 to disable the progress watchdog.`,defaultValue:()=>isNotProd()?`30s`:`5m`}),streamFlushMs:new DurationSetting({category:SettingCategories.Processes,aliases:[`streamFlushMillis`],description:`See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis`,defaultValue:()=>`10ms`}),healthCheckIntervalMs:new DurationSetting({category:SettingCategories.Processes,description:`How often should the main process check on the health of the web and sync subprocesses?`,defaultValue:()=>`2m`}),exiftoolProcsPerChild:new OptionalIntegerSetting({category: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.
|
|
249
|
+
If this is unset, "sync" will default to the number of supported concurrent imports.`}),sensitiveWordsAdd:new StringArraySetting({category:SettingCategories.Processes,description:`PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg". Environment keys that look like they hold a credential (like API access tokens or passwords) are removed from those child processes, and their values are hidden from logs, the health page, and error reports.
|
|
250
|
+
If your environment uses a word PhotoStructure doesn't recognize, add it here. These words are added to PhotoStructure's built-in list rather than replacing it.
|
|
251
|
+
Use one word per entry. Matching is case-insensitive and by whole word, so "mycorp" hides "MYCORP_BLOB" and "mycorpBlob" but not "mycorporation".`,exampleValue:()=>[`mycorp`],defaultValue:()=>[]}),syncExitTimeoutMs:new DurationSetting({category: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 DurationSetting({category:SettingCategories.Processes,description:`Minimum spacing between service (like web or sync) restart attempts. Automatic restarts after a crash are delayed until this much time has passed since the prior attempt, which lets services ride out transient failures instead of exhausting maxRestartsPerMinute immediately. This helps prevent system load due to service flapping.`,defaultValue:`7s`}),maxRestartsPerMinute:new IntegerSetting({category:SettingCategories.Processes,aliases:[`fatalErrorRatePerMinute`],description:`Maximum number of service restarts allowed within a 1-minute sliding window before PhotoStructure gives up and treats the failure as fatal. The default of 10 allows transient failures (network blips, USB hiccups) while catching persistent crashes that indicate a broken configuration or environment. If minTimeBetweenServiceRestartsMs spacing allows fewer restarts than this within a minute, the effective limit is the number of attempts that fit in the window.`,defaultValue:10}),cpuBusyPercent:new BoundedIntegerSetting({category:SettingCategories.Processes,aliases:[`cpuLoadPercent`,`cpuPct`],description:`This setting is a rough goal for total-system CPU utilization during library synchronization. PhotoStructure adjusts import concurrency downward when utilization exceeds this value and recovers it gradually after utilization falls. A higher value allows more parallel work, but may impact system responsiveness. Excessive CPU utilization also pauses new work as a safety backstop.
|
|
252
|
+
Setting this value to 0 disables CPU-based concurrency adjustment and throttling, allowing the sync process to run up to maxConcurrentImports concurrent imports.`,defaultValue:75,min:0,max:100}),timeoutThrottleCoeff:new FloatSetting({category: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.
|
|
253
|
+
Specifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.
|
|
254
|
+
Throttling 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.
|
|
255
|
+
Disable throttling by setting to 0.`,defaultValue:1}),maxConcurrentImports:new OptionalIntegerSetting({category:SettingCategories.Processes,aliases:[`maxSyncFileJobs`],advanced:()=>!0,description:`What ceiling should PhotoStructure request for concurrent imports?
|
|
256
|
+
If not set, a sensible value is computed from "cpuBusyPercent" and available memory. The effective TaskList ceiling is the lesser of this setting and the current CPU/memory limit, and CPU-based adaptive concurrency may run fewer imports than that.`}),maxConcurrentImportsWhenRemote:new IntegerSetting({category: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 * cpuBusyPercent) or max child processes given available memory, this value will be ignored.`,defaultValue:2}),sharpThreadsPerProcess:new BoundedIntegerSetting({category:SettingCategories.Processes,aliases:[`sharpThreadsPerJob`],advanced:()=>!0,description:`How many image processing threads can be spun per process?
|
|
257
|
+
If 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 StringEnumSetting({category: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.
|
|
258
|
+
For Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .
|
|
259
|
+
For Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .`,defaultValue:()=>PriorityClasses.BelowNormal,strEnum:PriorityClasses}),maxMemoryMb:new IntegerSetting({category:SettingCategories.Processes,description:`PhotoStructure will restart services if their resident memory (RSS) exceeds this value (measured in megabytes, or 1,000,000 bytes).
|
|
260
|
+
PhotoStructure automatically raises positive values when required by the library database size. Set to 0 to deactivate this check. Workers use maxWorkerMemoryMb instead.`,defaultValue:()=>2048}),maxWorkerMemoryMb:new IntegerSetting({category:SettingCategories.Processes,advanced:()=>!0,description:`Workers retire after finishing a request if their resident memory (RSS) exceeds this value, in megabytes (1,000,000 bytes). The current request completes before the worker exits, and queued requests use a replacement. This is not a hard memory limit during a request. Set to 0 to disable memory retirement.
|
|
261
|
+
This threshold is independent of maxMemoryMb, the service restart threshold, and workerMemoryMb, the import concurrency estimate. It is not raised when the library database grows.`,defaultValue:()=>1e3}),workerMemoryMb:new IntegerSetting({category:SettingCategories.Processes,advanced:()=>!0,description:`Estimated memory needed per worker, in megabytes (1,000,000 bytes). Available memory divided by this estimate limits import concurrency. Must be at least 1. Lower values allow more workers but increase memory pressure. This estimate is independent of maxMemoryMb, the service restart threshold, and is not raised when the library database grows.`,whyInvalid:e=>toGt0(e)==null?`must be at least 1`:void 0,defaultValue:1e3}),memoryWatchdogStartupGraceMs:new DurationSetting({category:SettingCategories.Processes,description:`How long after a service (web or sync, not worker) starts should PhotoStructure report excessive memory use as a warning before allowing the memory watchdog to restart it?
|
|
262
|
+
This only suppresses restarts during startup; memory limits crossed after the grace period are acted on normally. Set to 0 to disable the startup grace period.`,defaultValue:()=>`15m`}),maxMemoryErrorMultiplier:new FloatSetting({category:SettingCategories.Processes,description:`How much larger than expected memory usage before reporting an error in health checks?
|
|
263
|
+
|
|
264
|
+
Expected memory scales with database size: ~160 MB baseline + 1.0x DB file size.
|
|
265
|
+
This multiplier provides headroom for platform differences and legitimate memory usage patterns.
|
|
266
|
+
|
|
267
|
+
Validated values (from MemoryScaling.stress.spec.ts benchmarks):
|
|
268
|
+
- Linux: 5.0x (benchmark shows 1.0x scaling, 5x provides safety margin)
|
|
269
|
+
- macOS: TODO - needs benchmark (expected 10-25x due to 2-5x higher memory usage)
|
|
270
|
+
- Windows: TODO - needs benchmark
|
|
271
|
+
|
|
272
|
+
To determine the correct value for your platform, see instructions in:
|
|
273
|
+
src/library/health/MemoryScaling.stress.spec.ts`,defaultValue:()=>process.platform===`linux`?5:10}),maxTasksPerProcess:new IntegerSetting({category:SettingCategories.Processes,description:`PhotoStructure will recycle threads and worker processes after they handle this number of requests. Must be at least 1. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.`,whyInvalid:e=>toGt0(e)==null?`must be at least 1`:void 0,defaultValue:()=>isNotProd()?50:1024})};for(let[e,n]of entries(ProcessesSettings))n._setName(e);var ReportingSettings={email:new OptionalStringSetting({category: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 BooleanSetting({aliases:[`enableSentry`],category: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. The "optOut" and "noNetwork" settings prevent error reports even when this setting is enabled.`,defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new BoundedIntegerSetting({category:SettingCategories.Reporting,description:`Maximum number of distinct error reports sent per installation each day. Errors explicitly flagged for reporting may use an additional allowance.`,defaultValue:()=>16,min:0,max:32})};for(let[e,n]of entries(ReportingSettings))n._setName(e);var SidecarExts=strEnum(`xmp`,`mie`,`exv`),SidecarsSettings={matchSidecarsCaseInsensitively:new BooleanSetting({category: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").
|
|
274
|
+
If set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").`,defaultValue:!0}),matchSidecarsFuzzily:new BooleanSetting({category: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").
|
|
275
|
+
This setting only impacts .XMP, .MIE, and .EXIF sidecars.
|
|
276
|
+
Note that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.`,defaultValue:!1}),defaultSidecarType:new StringEnumSetting({category:SettingCategories.Sidecars,description:`What type of sidecar file do you want to generate for non-destructive edits?
|
|
277
|
+
- "XMP" is a popular and well-adopted format.
|
|
278
|
+
-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .
|
|
279
|
+
- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.
|
|
280
|
+
Case is preserved.`,strEnum:SidecarExts,defaultValue:SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new BooleanSetting({category: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 StringArraySetting({category: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`]}),directorySidecars:new StringArraySetting({category:SettingCategories.Sidecars,description:`When gathering sidecars for a given photo or video, PhotoStructure will also look for files with the following names, and use those as "low priority" sidecars. The metadata in these files will be used as a "default value," and will be overridden by metadata in the file itself, or file-specific sidecar(s).
|
|
281
|
+
Note that these are case-sensitive.`,defaultValue:()=>[`album.xmp`,`metadata.xmp`]}),writeMetadataToSidecarsIfVideo:new BooleanSetting({category: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 BooleanSetting({category: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})};for(let[e,n]of entries(SidecarsSettings))n._setName(e);var SignInSettings={signInIpv4Prefix:new BoundedIntegerSetting({envAliases:[`PS_SIGN_IN_IPV4_PREFIX`],advanced:()=>!0,category:SettingCategories.Security,description:`How many leading bits of an IPv4 address name the network that email sign-in counts its requests and code entries against, and that OIDC sign-in counts its starts against. 32 counts each address on its own; 24 counts each /24 (256 addresses) as one network.`,defaultValue:32,min:16,max:32}),signInIpv6Prefix:new BoundedIntegerSetting({envAliases:[`PS_SIGN_IN_IPV6_PREFIX`],advanced:()=>!0,category:SettingCategories.Security,description:`How many leading bits of an IPv6 address name the network that email sign-in counts its requests and code entries against, and that OIDC sign-in counts its starts against. 64 counts each /64, which providers usually assign to one home or phone, as one network; 56 counts each /56 as one.`,defaultValue:64,min:32,max:64})};for(let[e,n]of entries(SignInSettings))n._setName(e);var SubscriptionSettings={subscriptionTimeoutMs:new DurationSetting({category:SettingCategories.Subscription,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 BooleanSetting({category:SettingCategories.Subscription,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 OptionalStringSetting({category:SettingCategories.Subscription,description:`Coupon to automatically apply during subscription setup. This value will be ignored if you've already gone through the subscription setup flow.
|
|
282
|
+
The example value is a valid coupon code: thanks for reading!)
|
|
283
|
+
Note that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .`,exampleValue:()=>`RTFM15`}),autoRefreshLicense:new BooleanSetting({category:SettingCategories.Subscription,description:`Automatically keep this installation's cryptographically signed subscription license current. After browser activation stores an opaque renewal credential, PhotoStructure contacts https://account.photostructure.com/ at the signed renewal time. The signed license is then used offline until another renewal is due. Legacy licenses retain their released reactive refresh behavior during migration.
|
|
284
|
+
Set this to false to disable automatic renewal. Browser activation still brings back the first license. The optOut setting controls telemetry; it does not disable update checks, activation, billing, or license renewal. The noNetwork setting prevents PhotoStructure from attempting automatic renewal; see its description for browser renewal.`,defaultValue:!0}),license:new OptionalStringSetting({category:SettingCategories.Subscription,aliases:[`licence`],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(let[e,n]of entries(SubscriptionSettings))n._setName(e);var import_luxon=require("luxon"),DisabledCronValue=`disabled`,JsonlFlavors=strEnum(`logs`,`sync-reports`),SyncReportFileFilters=[{key:`all`,label:`All`,description:`Show and download every row`},{key:`imported`,label:`Imported files`,description:`Files successfully imported — states: imported, updated, unchanged, copied`,states:[`imported`,`updated`,`unchanged`,`copied`]},{key:`notImported`,label:`Not imported files`,description:`Files not imported — states: excluded (by settings), unavailable (inaccessible), blocklisted (safety), deleted (rejected by filters)`,states:[`excluded`,`unavailable`,`blocklisted`,`deleted`]},{key:`errors`,label:`Errored files`,description:`Files with problems — states: failed, timeout, stalled, canceled, unknown`,states:[`failed`,`timeout`,`stalled`,`canceled`,`unknown`]}],SyncReportFilterOptions=[...SyncReportFileFilters,{key:`scannedDirs`,label:`Scanned folders`,description:`Directories that were scanned during this sync`,states:[`scanned`,`completed`],type:`dir`,adHocDownload:!0},{key:`excludedDirs`,label:`Excluded folders`,description:`Directories excluded by settings (hidden, .nomedia, glob pattern)`,states:[`excluded`],type:`dir`,adHocDownload:!0}],import_node_fs3=__toESM(require("node:fs"));function containsRpiModel(e=`/proc/cpuinfo`){if(isWin||isMac)return!1;try{return import_node_fs3.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)!=null}catch{return!1}}var isRaspberryPi=lazy2(()=>isLinux_arm32&&containsRpiModel()),procDeviceModel=lazy2(()=>{try{return isLinux?import_node_fs3.default.readFileSync(`/proc/device-tree/model`).toString():void 0}catch{return}}),import_croner=require("croner"),import_node_process8=__toESM(require("node:process")),isChildProcess=lazy2(()=>isTrue(process.env[PS_IS_CHILD_PROCESS])),RunStates=strEnum(`loading`,`welcome`,`ready`,`failed`),HealthCheckSections=strEnum(`Summary`,`Library`,`System`,`Tools`),HealthCheckLevels=strEnum(`error`,`no-library`,`pending`,`stop-sync`,`warn`,`ok`,`disabled`,`user-disabled`,`installing`),SyncBlockingLevels=[HealthCheckLevels.error,HealthCheckLevels[`no-library`],HealthCheckLevels[`stop-sync`]],OkLevels=[HealthCheckLevels.ok,HealthCheckLevels.disabled,HealthCheckLevels[`user-disabled`],HealthCheckLevels.pending,HealthCheckLevels.installing,HealthCheckLevels[`no-library`]];function levelIsNotOK(e){return!OkLevels.includes(e)}function isHealthCheckResult(e){return isObject(e)&&!blank(e.id)&&!blank(e.section)&&HealthCheckLevels.has(e.level)&&!blank(e.msg)}function isHealthCheckSummary(e){return isObject(e)&&RunStates.has(e.state)&&isBoolean(e.settled)&&isHealthCheckResult(e)}var BaseHealthCheckSummary={id:`summary`,section:HealthCheckSections.Summary},SyncStorageTooSlowCode=`SYNC_STORAGE_TOO_SLOW`,SlowStorageRestartLimit=3,SlowStorageWindowMs=2*hourMs,SyncStorageTooSlowMessage=`Your library's storage is too slow for sync: sync's health checks timed out ${SlowStorageRestartLimit} times in ${SlowStorageWindowMs/hourMs} hours, so PhotoStructure stopped restarting sync. Move your library to faster storage, or check that drive's health.`,errorLookup=lazy2(()=>[{match:{service:`web`,errno:`EADDRINUSE`},userMessage:`Web server port is already in use. Is another PhotoStructure instance running?`,href:`https://photostructure.com/faq/port-in-use/`,linkText:`Troubleshoot port conflicts`,remediation:[`Stop any other PhotoStructure instance`,`Stop any other process using this port`,`Use a different port by setting PS_HTTP_PORT`],category:`config`},{match:{service:`sync`,errno:`EADDRINUSE`},userMessage:`Sync service IPC socket is already in use. Is another PhotoStructure instance running?`,href:`https://photostructure.com/faq/port-in-use/`,linkText:`Troubleshoot address conflicts`,remediation:[`Stop any other PhotoStructure instance`,`Restart PhotoStructure (a stale socket from a prior crash is cleaned up on startup)`],category:`config`},{match:{service:`sync`,errno:`EACCES`},userMessage:`Permission denied during sync startup.`,href:`https://photostructure.com/faq/file-permissions/`,linkText:`Fix file permissions`,remediation:[`Use a port above 1024`,`Check file and directory permissions`,`Run with elevated privileges if necessary`],category:`config`},{match:{service:`sync`,errno:`MODULE_NOT_FOUND`},userMessage:`Required module not found. The installation may be corrupt.`,href:`https://photostructure.com/faq/installation-corrupt/`,linkText:`Reinstall PhotoStructure`,remediation:[`Reinstall PhotoStructure`,`Verify the installation completed successfully`],category:`dependency`},{match:{service:`sync`,errno:SyncStorageTooSlowCode},userMessage:SyncStorageTooSlowMessage,href:`https://photostructure.com/faq/slow-library-storage/`,linkText:`Fix slow library storage`,remediation:[`Move your library to faster storage, such as a local SSD rather than a network share or a busy spinning disk`,`Check the drive's health and free space: a failing or nearly full drive can be very slow`,`Pause other heavy work on that drive, such as backups or RAID scrubs, while PhotoStructure syncs`,`Then click "Acknowledge & restart sync" on the health page`],category:`storage`},{match:{errno:`EADDRINUSE`},userMessage:`Port is already in use. Is another PhotoStructure instance running?`,href:`https://photostructure.com/faq/port-in-use/`,linkText:`Troubleshoot port conflicts`,remediation:[`Stop any other PhotoStructure instance`,`Stop any other process using this port`,`Use a different port by setting PS_HTTP_PORT`],category:`config`},{match:{errno:`EACCES`},userMessage:`Permission denied.`,href:`https://photostructure.com/faq/file-permissions/`,linkText:`Fix file permissions`,remediation:[`Use a port above 1024`,`Check file and directory permissions`,`Run with elevated privileges if necessary`],category:`config`},{match:{errno:`ENOENT`},userMessage:`File or directory not found.`,remediation:[`Verify the path exists`,`Check for typos in the path`,`Ensure the volume is mounted`],category:`config`},{match:{errno:`EPERM`},userMessage:`Operation not permitted.`,href:`https://photostructure.com/faq/file-permissions/`,linkText:`Fix file permissions`,remediation:[`Check file and directory permissions`,`Verify the filesystem is not read-only`],category:`config`},{match:{errno:`ENOSPC`},userMessage:`No space left on device.`,remediation:[`Free up disk space`,`Move the library to a larger volume`,`Delete old previews or logs`],category:`resource`},{match:{errno:`EMFILE`},userMessage:`Too many open files.`,href:`https://photostructure.com/faq/too-many-open-files/`,linkText:`Fix open file limits`,remediation:[`Increase the file descriptor limit (ulimit -n)`,`Reduce parallelism with ${ProcessesSettings.cpuBusyPercent.key} or ${ProcessesSettings.exiftoolProcsPerChild.key}`],category:`resource`},{match:{errno:`MODULE_NOT_FOUND`},userMessage:`Required module not found. The installation may be corrupt.`,remediation:[`Reinstall PhotoStructure`,`Check that all dependencies are installed`],category:`dependency`},{match:{errno:`REPO_ROOT_NOT_FOUND`},userMessage:`Failed to locate PhotoStructure source directory. The installation may be corrupt.`,href:`https://photostructure.com/faq/installation-corrupt/`,remediation:[`Reinstall PhotoStructure`,`Verify installation directory structure`],category:`dependency`},{match:{signal:`SIGSEGV`},userMessage:`Process crashed with segmentation fault.`,href:`https://photostructure.com/faq/crashes/`,linkText:`Troubleshoot crashes`,remediation:[`This is usually a bug - please report it`,`Try updating to the latest version`,`Check if a specific file causes the crash`],category:`crash`},{match:{signal:`SIGABRT`},userMessage:`Process aborted.`,href:`https://photostructure.com/faq/crashes/`,linkText:`Troubleshoot crashes`,remediation:[`This is usually a bug - please report it`,`Check system logs for more details`],category:`crash`},{match:{signal:`SIGBUS`},userMessage:`Process crashed with bus error.`,href:`https://photostructure.com/faq/crashes/`,linkText:`Troubleshoot crashes`,remediation:[`This may indicate memory or hardware issues`,`Check if the filesystem is healthy`],category:`crash`},{match:{signal:`SIGKILL`},userMessage:`Process was killed (likely out of memory).`,href:`https://photostructure.com/faq/out-of-memory/`,linkText:`Fix memory issues`,remediation:[`Increase available memory`,`Reduce parallelism with ${ProcessesSettings.cpuBusyPercent.key} or ${ProcessesSettings.exiftoolProcsPerChild.key}`,`Check system logs for OOM killer activity`],category:`resource`},{match:{signal:`SIGILL`},userMessage:`Process crashed with illegal instruction.`,href:`https://photostructure.com/faq/crashes/`,linkText:`Troubleshoot crashes`,remediation:[`This may indicate CPU compatibility issues`,`Ensure you're using the correct build for your architecture`],category:`crash`},{match:{signal:`SIGFPE`},userMessage:`Process crashed with floating point exception.`,href:`https://photostructure.com/faq/crashes/`,linkText:`Troubleshoot crashes`,remediation:[`This is usually a bug - please report it`],category:`crash`},{match:{exitCode:137},userMessage:`Process was killed (exit code 137, likely OOM).`,href:`https://photostructure.com/faq/out-of-memory/`,linkText:`Fix memory issues`,remediation:[`Increase available memory`,`Reduce parallelism with ${ProcessesSettings.cpuBusyPercent.key} or ${ProcessesSettings.exiftoolProcsPerChild.key}`,`Check system logs for OOM killer activity`],category:`resource`}]);function matchesEntry(e,n){return n.service!=null&&e.service!==n.service||n.errno!=null&&(e.errno??e.code)!==n.errno||n.signal!=null&&e.signal!==n.signal||n.exitCode!=null&&e.exitCode!==n.exitCode?!1:n.service!=null||n.errno!=null||n.signal!=null||n.exitCode!=null}function enrichError(e,n=errorLookup()){for(let r of n)if(matchesEntry(e,r.match))return{userMessage:r.userMessage,href:r.href,linkText:r.linkText,remediation:r.remediation,category:r.category};return{category:`unknown`}}function formatEnrichedError(e,n,r,a=`FATAL ERROR`){let o=[],s=r.service==null?``:` (${r.service})`;if(o.push(``),o.push(`=`.repeat(70)),o.push(`${a}${s}`),o.push(`=`.repeat(70)),o.push(``),n.userMessage!=null&&(o.push(n.userMessage),o.push(``)),o.push(`Technical details:`),o.push(` Message: ${e}`),(r.errno!=null||r.code!=null)&&o.push(` Code: ${r.errno??r.code}`),r.signal!=null&&o.push(` Signal: ${r.signal}`),r.exitCode!=null&&o.push(` Exit code: ${r.exitCode}`),o.push(``),n.remediation!=null&&n.remediation.length>0){o.push(`To resolve this issue:`);for(let e of n.remediation)o.push(` - ${e}`);o.push(``)}if(n.href!=null){let e=n.linkText??`More information`;o.push(`${e}: ${n.href}`),o.push(``)}return o.push(`=`.repeat(70)),o.push(``),o.join(`
|
|
285
|
+
`)}function stack(){let e={};return Error.captureStackTrace?.(e,stack),e.stack==null?Error().stack?.split(/\n(?:\s*at\s+)?/).slice(1)??[]:e.stack.split(/\n(?:\s*at\s+)?/).slice(1)}var logger3=defer(()=>mkLogger(`error.OnError`)),errorHistory=defer(()=>isTest()?new BoundedList(10):null);function isOnErrorMeta(e){if(typeof e!=`object`||!e||e instanceof Error)return!1;let n=e;return typeof n.userMessage==`string`||typeof n.code==`string`||typeof n.signal==`string`||typeof n.exitCode==`number`||typeof n.service==`string`||typeof n.href==`string`||typeof n.fatal==`boolean`||typeof n.doNotSend==`boolean`}function onError(e,n){try{if(typeof e==`function`){let n=e.name||`anonymous`;e=Error(`onError: received function instead of error: ${n}`)}if(typeof n==`function`){let e=n.name||`anonymous`;n=Error(`onError: received function instead of meta: ${e}`)}if(blank(e)&&isEmptyObj(n))return logger3().warn(`onError() with no args`,stack()),!1;let r=toWrappedError(e,n);isInternalError(r)&&(internalErrorRate.onEvent(),lastInternalErrors.push(r));let a=r.fatal===!0,o=r.ignorable===!0;if(!a&&o)return logger3().info(`onError(): (ignorable)`,{error:e}),!1;errorRate.onEvent(),ee().emit(a?`fatal`:`nonFatal`,r),logger3().log(a?`error`:`warn`,`onError()`,{error:r});let{userMessage:s,code:c,signal:l,exitCode:u,href:d,service:f}=isOnErrorMeta(n)?n:{},h=f??serviceName(),_=stripErrorFlags(s??r.message);if(errorHistory()?.push({service:h,message:_,code:c,ts:Date.now(),fatal:a}),a){if(isChildProcess())stderrWrite({serviceError:{service:h,message:_,code:c,ts:Date.now(),fatal:!0}});else{let e={errno:c,signal:l,exitCode:u,service:h};writeStderr(formatEnrichedError(_,enrichError(e),e))}mkLogger(`ServiceError`).fatal(_,{service:h,code:c,signal:l,exitCode:u,href:d,pid:import_node_process8.default.pid})}return a}catch{return console.error(`onError() threw an error!`,{error:e,meta:n}),!1}}function whyInvalid(e){try{let n=trimQuotes(e);if(n===DisabledCronValue)return;blank(n)||new import_croner.Cron(n);return}catch(e){return e?.message??errorToS2(e)}}var CronSetting=class extends StringSetting{constructor(e){super({whyInvalid,...e})}cron_(e){let n=this.valueOrDefault;if(n!==DisabledCronValue)return new import_croner.Cron(n,{name:this.name,unref:!0,protect:!0,catch:e=>onError(e,{name:this.name,crontab:n}),...e})}},SyncSettings={expedite:new BooleanSetting({category:SettingCategories.Sync,description:`If true, PhotoStructure will defer some maintenance tasks (like database vacuuming and full tag recounts). Also used internally to expedite shutdowns.`,defaultValue:()=>!1}),syncUvThreads:new BoundedIntegerSetting({category:SettingCategories.Sync,description:`How many libuv threads should the primary sync process be given? Higher values may allow for slightly higher concurrency, but may also consume more memory and CPU and result in iowait from non-SSD storage.
|
|
286
|
+
The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.`,advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),syncReportsDir:new StringSetting({category: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`}),syncReportRetention:new DurationSetting({category:SettingCategories.Sync,description:`How long should we retain old sync reports? If set to 0 (and syncReportRetentionCount is 0), sync reports are never deleted.`,defaultValue:`15d`}),syncReportRetentionCount:new IntegerSetting({category:SettingCategories.Sync,description:`How many historical sync reports should be retained? If set to 0 (and syncReportRetention is 0), sync reports are never deleted.`,defaultValue:()=>0}),syncReportMaxLinesPerFile:new IntegerSetting({category:SettingCategories.Sync,description:`Maximum number of rows (one JSONL line per row) written to a single sync report before rolling to a new file. Sync reports are otherwise only rolled when a scan path finishes, so a single large folder can produce one enormous file — which is slow to open in the report viewer, and can exceed the maximum file size on FAT and other older filesystems. Lower values produce more, smaller files. Set to 0 to disable the row cap entirely; sync reports are still started fresh when a scan path finishes.`,defaultValue:()=>1e5}),quickSyncMode:new BooleanSetting({category:SettingCategories.Sync,description:`Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, metadata inference, and more efficient preview encoding. It is true by default on 32-bit Raspberry Pi OS and false everywhere else, including 64-bit Raspberry Pi OS.`,defaultValue:()=>isRaspberryPi()}),taskTimeoutMs:new DurationSetting({category:SettingCategories.Sync,aliases:[`taskTimeoutMillis`],description:`What's the longest time it can validly take to compute an image hash, extract tags for a file, or generate one preview size for an asset?
|
|
287
|
+
A file SHA may take longer: it only times out after this long without reading any more of the file. An asset's full set of previews may also take longer, as long as each preview size finishes within this time.
|
|
288
|
+
Note that this does not impact video transcoding timeouts.
|
|
289
|
+
On a reasonable server and disk, these tasks should take at most a handful of seconds, but the default should be sufficiently long for a RPi4 on a slow, remote disk.
|
|
290
|
+
Set this to 0 to disable task timeouts.`,defaultValue:()=>`2m`}),taskMaxDurationMs:new DurationSetting({category:SettingCategories.Sync,aliases:[`taskMaxDurationMillis`],description:`Maximum wall-clock time for any single task (syncFile, finalizeAsset, etc.). This is a safety net to prevent hung tasks from permanently occupying queue slots. Must be significantly longer than taskTimeoutMs since a single task may involve multiple sub-operations.
|
|
291
|
+
Set to 0 to disable.`,defaultValue:()=>`10m`}),stallWarningFloorMs:new DurationSetting({category:SettingCategories.Sync,description:`The minimum duration before a stall warning is emitted for a task. This helps to avoid false positives for tasks that complete quickly.`,defaultValue:()=>`30s`}),syncMaxUptime:new DurationSetting({category:SettingCategories.Sync,aliases:[`syncMaxUptimeMs`],description:'Maximum uptime for the sync process before a graceful restart, regardless of what the sync is doing. Disabled by default: a wall-clock restart cannot tell the difference between a healthy long-running scan and a leak, and the symmetric tradeoff (kill a slow but healthy initial sync before it finishes) is worse than the leak it might prevent. `syncMaxTimeoutsBeforeRestart` already restarts on real failure signals.\nSet to a positive duration (e.g. `"1d"`) if you want a periodic restart anyway.\nThe sync process will finish in-flight tasks before restarting.',defaultValue:()=>`0`}),syncMaxTimeoutsBeforeRestart:new IntegerSetting({category:SettingCategories.Sync,description:`Maximum number of task timeouts before the sync process performs a graceful restart. Each timeout may leave behind zombie child processes or leaked resources. A restart cleans them up.
|
|
292
|
+
The sync process will finish in-flight tasks before restarting.
|
|
293
|
+
Set to 0 to disable timeout-count-based restart.`,defaultValue:1}),scanLibraryFirst:new BooleanSetting({aliases:[`syncLibraryFirst`],category:SettingCategories.Sync,description:`Should PhotoStructure scan your library before all other paths are synchronized?
|
|
294
|
+
This 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 BooleanSetting({aliases:[`syncLibraryLast`],category:SettingCategories.Sync,description:`Should PhotoStructure scan your library after all other paths are synchronized?`,defaultValue:!1}),progressRetentionDays:new IntegerSetting({category:SettingCategories.Sync,description:`How many days of sync progress should we keep around in the database before it's removed?`,defaultValue:180}),progressStaleDays:new IntegerSetting({category: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}),startPaused:new BooleanSetting({category:SettingCategories.Sync,description:`Should sync be paused every time PhotoStructure starts? To resume, click "Resume sync" on the System activity page.`,defaultValue:!1}),syncCron:new CronSetting({category:SettingCategories.Sync,description:`This is a crontab entry that defines when sync will start work. Set this to "${DisabledCronValue}" to disable regularly scheduled syncs. Initial, unfinished, and manually requested syncs still run.
|
|
295
|
+
If the value you provide is not a valid crontab entry or "${DisabledCronValue}", the default value will be used instead (which is to run at 2AM, nightly).
|
|
296
|
+
See https://github.com/Hexagon/croner?tab=readme-ov-file#pattern for details on what patterns are accepted (or ask for help on the forum or discord).`,defaultValue:`0 2 * * *`}),syncCronTZ:new OptionalStringSetting({category:SettingCategories.Sync,whyInvalid(e){if(blank(e))return`(blank)`;if(!import_luxon.Info.isValidIANAZone(e))return`not a valid IANA time zone`},description:`The system timezone will be used to interpret "syncCron", unless this setting is specified. If this is not specified, the zone environment variable will be used, and if zone is blank, we'll default to UTC. This must be an IANA time zone, like "America/Los_Angeles" or "Europe/Stockholm". See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a complete list.`}),forceRebuildLibrary:new BooleanSetting({category:SettingCategories.Sync,aliases:[`rebuild`],description:`When set, marks all assets and files for re-validation. Reprocessing happens incrementally during sync, not in a single monolithic operation.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),forceSync:new BooleanSetting({category:SettingCategories.Sync,description:`When set, all files will be visited, even if the asset seems in sync with the filesystem.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),forceFilters:new BooleanSetting({category:SettingCategories.Sync,description:`When set, all files filters will be applied to visited files. If this is false, files already in the library database will be assumed to be validly passing all import filters. This is set to true by default when rebuilding libraries.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),forceCheckLibraryCopy:new BooleanSetting({category:SettingCategories.Sync,description:`When set, all files outside your Originals directory will be verified to have a valid copy in your library. This is set to true by default when import settings change.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),forceRebuildPreviews:new BooleanSetting({category:SettingCategories.Sync,description:`When set, previews and transcoded videos will always be rebuilt.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),skipAssetRepair:new BooleanSetting({category:SettingCategories.Sync,description:`When set, deleted asset files will not schedule asset repairs. This is only useful during library rebuilds.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),skipAssetTagging:new BooleanSetting({category:SettingCategories.Sync,description:`When set, asset tagging (face detection, scene detection, etc.) will be skipped during sync.`,defaultValue:!1,transient:!0,propagateToChildren:!1}),skipLibraryRebuild:new BooleanSetting({aliases:[`noModelUpdates`],category:SettingCategories.Sync,description:`When set, skip any pending library database updates (only used for tests).`,defaultValue:!1,transient:!0,propagateToChildren:!1}),exitWhenDone:new BooleanSetting({category:SettingCategories.Sync,description:`When set, the sync process will exit after jobs are completed (used internally and for tests).`,defaultValue:!1,transient:!0,propagateToChildren:!1}),maxDuplicatePathElements:new IntegerSetting({category: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}),excludeNoMediaAssetsOnRebuild:new BooleanSetting({category:SettingCategories.Sync,description:`Should previously-imported assets that are found to have *any* files in NoMedia directories be excluded from your library?`,defaultValue:()=>!0}),taskListCap:new BoundedIntegerSetting({category:SettingCategories.Sync,aliases:[`workQueueHighWater`],description:`PhotoStructure sync involves two tasks: searching for files to import, and _actually importing_ those files. This value is a "high water" level to pause searching for files to import.
|
|
297
|
+
Much larger values will incur cache misses and increase sync RAM consumption. Much smaller values may cause backpressure that slows sync throughput.
|
|
298
|
+
Note that until the last batch of work is scheduled, sync ETAs will be inaccurate.
|
|
299
|
+
This defaults to the bigger value of 8 and 3 x maxConcurrentImports. Values at or below 2 x maxConcurrentImports will starve workers: the queue only refills once it drains to half this value.`,defaultValue:1,min:1,max:32768}),fileSizeEpsilon:new IntegerSetting({category:SettingCategories.Sync,description:`How many bytes can a file's size be different from prior synchronization runs and still be considered "untouched"?
|
|
300
|
+
Set this to 0 to require exactly the same filesize.
|
|
301
|
+
Set this to a negative value to disable filesize checking: only differences in mtimeMs or additions of sidecars will cause a file to be re-sync'ed.`,defaultValue:0}),mtimeMsEpsilon:new IntegerSetting({category:SettingCategories.Sync,description:`How many milliseconds can a file's "mtimeMs" be different from prior synchronization runs and still be considered "untouched"?
|
|
302
|
+
A value of 0 will require exactly the same mtimeMs (which may be fractional milliseconds on some unix filesystems!), and may result in unnecessary re-syncs.
|
|
303
|
+
Set this to a negative value to disable mtime checking: only differences in filesizes or additions of sidecars will cause a file to be re-sync'ed.`,defaultValue:secondMs}),findUriEquivalents:new BooleanSetting({category:SettingCategories.Sync,description:`Enable this if you share your PhotoStructure library between macOS and other operating systems (Windows/Linux) AND have files with non-ASCII characters (accents, Chinese, Cyrillic, Arabic, etc.) in their names.
|
|
304
|
+
|
|
305
|
+
macOS uses NFD Unicode normalization (decomposed characters) while Windows and Linux use NFC (composed characters). This setting ensures these different representations are recognized as the same file.
|
|
306
|
+
|
|
307
|
+
Warning: Enabling this slows down sync because PhotoStructure must check multiple equivalent paths for every file.
|
|
308
|
+
|
|
309
|
+
Leave this disabled if you only use one operating system or only have ASCII filenames.`,defaultValue:()=>!1})};for(let[e,n]of entries(SyncSettings))n._setName(e);var DateTagFormats=strEnum(`y`,`ym`,`ymd`,DISABLED),KeywordReparentingStrategies=strEnum(`move`,`copy`,`retain`),NameTagFormats=strEnum(`as-is`,`family/given`,`family/fullname`),NameTagOrders=strEnum(`givenFirst`,`surnameFirst`),KeywordVariationScopes=strEnum(`all`,`primary`),TaggingSettings={recountAllTags:new BooleanSetting({category: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,propagateToChildren:!1}),tagCamera:new BooleanSetting({category:SettingCategories.Tagging,description:`Should assets be tagged with cameras' make and model?`,defaultValue:!0}),tagLens:new BooleanSetting({category:SettingCategories.Tagging,description:`Should assets be tagged with lens' make and model?`,defaultValue:!0}),tagFullLensModel:new BooleanSetting({category: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 StringEnumSetting({category: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)?
|
|
310
|
+
Setting this to "disabled" will disable date tagging.`,defaultValue:DateTagFormats.ym,strEnum:DateTagFormats}),tagDateFromStat:new BooleanSetting({category: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:()=>!isNotProd()}),tagKeywordsFromPath:new BooleanSetting({category:SettingCategories.Tagging,description:`Should assets be tagged with keywords extracted from file pathnames?`,defaultValue:!0}),tagKeywordsFromMetadata:new BooleanSetting({category:SettingCategories.Tagging,description:`Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?`,defaultValue:!0}),tagKeywordsFromVariations:new StringEnumSetting({category:SettingCategories.Tagging,description:`Should keywords be combined from "all" variations of an asset, or extracted only from the "primary" variation? The default, "all", preserves keywords found only in a RAW, JPEG, edited copy, or sidecar. Use "primary" when variations may contain conflicting or stale keywords.`,defaultValue:KeywordVariationScopes.all,strEnum:KeywordVariationScopes}),keywordTags:new StringArraySetting({category: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 StringEnumSetting({category:SettingCategories.Tagging,description:`How should PhotoStructure handle hierarchical keywords?
|
|
311
|
+
If this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."
|
|
312
|
+
If this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.
|
|
313
|
+
If 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".
|
|
314
|
+
See https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.`,defaultValue:KeywordReparentingStrategies.move,strEnum:KeywordReparentingStrategies}),rootTagAlbumsAliases:new StringArraySetting({category:SettingCategories.Tagging,description:`Other names that PhotoStructure treats as "Albums". For example, "Collection/Summer 2024" becomes "Albums/Summer 2024". This applies to both newly imported photos and existing tags in your library (which are renamed automatically). Case-insensitive.`,defaultValue:()=>[`Album`,`Albums`,`Collection`,`Collections`]}),rootTagKeywordsAliases:new StringArraySetting({category:SettingCategories.Tagging,description:`Other names that PhotoStructure treats as "Keywords". For example, "Tag/sunset" becomes "Keywords/sunset". This applies to both newly imported photos and existing tags in your library (which are renamed automatically). Case-insensitive.`,defaultValue:()=>[`Keyword`,`Keywords`,`Tag`,`Tags`]}),rootTagWhatAliases:new StringArraySetting({category:SettingCategories.Tagging,description:`Other names that PhotoStructure treats as "What". For example, "Subject/Nature" becomes "What/Nature". This applies to both newly imported photos and existing tags in your library (which are renamed automatically). Case-insensitive.`,defaultValue:()=>uniq([`Article`,`Articles`,`Item`,`Items`,`Object`,`Objects`,`Subject`,`Subjects`,`What`,`le sujet`,`matière`,`objet`,`objets`,`sujet`,`Gegenstand`,`Objekt`,`Subjekt`,`Oggetto`,`Soggetto`,`Assunto`,`Objeto`,`sujeta`,`sujeto`])}),rootTagWhereAliases:new StringArraySetting({category:SettingCategories.Tagging,description:`Other names that PhotoStructure treats as "Where". For example, "Location/Beach" becomes "Where/Beach". This applies to both newly imported photos and existing tags in your library (which are renamed automatically). Case-insensitive.`,defaultValue:()=>uniq(`Country.Geo.GPS.Location.Locations.Place.Places.Region.Site.Locatie.Plaats.emplacement.endroit.les pays.pays.région.Lage.ort.platz.Standort.stätte.Luogo.Posizione.Local.Localização.el país.posición.sitio.ubicación`.split(`.`))}),rootTagWhoAliases:new StringArraySetting({category:SettingCategories.Tagging,aliases:[`tagWhoSynonyms`],description:`Other names that PhotoStructure treats as "Who". For example, "People/Jane Doe" becomes "Who/Jane Doe" (or "Who/Doe/Jane" if tagNamesFormatter="family/given"). This applies to both newly imported photos and existing tags in your library (which are renamed automatically). Digikam uses "People". Case-insensitive.`,defaultValue:()=>uniq(`Face.Faces.Family.People.Person.Famille.Personne.Personnes.Visage.Visages.Familie.Gesicht.Gesichter.Personen.Famiglia.Persona.Persone.Viso.Volto.Família.Pessoa.Pessoas.Rosto.Rostos.Familia.Personas.Rostro.Rostros`.split(`.`))}),rootTagEventAliases:new StringArraySetting({category:SettingCategories.Tagging,description:`Other names that PhotoStructure treats as "Event". For example, "Occasion/Birthday" becomes "Event/Birthday". This applies to both newly imported photos and existing tags in your library (which are renamed automatically). Case-insensitive.`,defaultValue:()=>uniq(`Activity.Activities.Events.Occasion.Occasions.Activité.Activités.Événement.Événements.Occasion.Occasions.Aktivität.Aktivitäten.Ereignis.Ereignisse.Attività.Evento.Eventi.Atividade.Atividades.Evento.Eventos.Actividad.Actividades.Evento.Eventos`.split(`.`))}),keywordDelimiters:new OptionalStringSetting({category:SettingCategories.Tagging,blankIsValue:!0,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".
|
|
315
|
+
Note 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.
|
|
316
|
+
See https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.
|
|
317
|
+
After changing this value, you must force-resync your library for the changes to take affect.`,defaultValue:`,;`}),keywordDashDashDelimiters:new StringSetting({category:SettingCategories.Tagging,blankIsValue:!0,description:`PhotoStructure extracts keywords from pathnames if any parent folder includes a "--" in the name. Keywords are separated by these characters. Note that by default, space will separate keywords (because " " is an included character), as will sub-directories (because "/" is an included character).
|
|
318
|
+
Windows pathnames are converted to forward-slash for this use, so you don't need to include backward-slash.
|
|
319
|
+
After changing this value, you must force-resync your entire library for the changes to take affect.`,defaultValue:`,; /`}),keywordPathSeparators:new StringSetting({category:SettingCategories.Tagging,blankIsValue:!0,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 BooleanSetting({category:SettingCategories.Tagging,aliases:[`tagType`],description:`Should assets be tagged with their file type (like "Type/Image/JPEG")?`,defaultValue:!0}),tagGeo:new BooleanSetting({category:SettingCategories.Tagging,description:`Should we add geolocation tags to assets that have latitude/longitude?`,defaultValue:!0}),tagGeoCountryFlags:new BooleanSetting({category:SettingCategories.Tagging,description:`Should country tags include a flag emoji in their display name (e.g. "🇫🇷 France")? Requires "tagGeo" to be enabled.`,defaultValue:!0}),tagGeoMaxDistanceKm:new FloatSetting({category:SettingCategories.Tagging,description:`If "tagGeo" is enabled, and "GeolocationDistance" is greater than "tagGeoMaxDistanceKm", geolocation for that asset will be ignored. Set to 0 to disable.`,defaultValue:25}),tagGeoSynonyms:new StringArraySetting({category:SettingCategories.Tagging,description:`Due to EXIF and XMP specification drift, there are several ways for geolocation information to be encoded in files. When PhotoStructure applies the "tagGeoTemplate", we'll use these "synonyms" to build the geo tag (first synonym with a value wins). See https://exiftool.org/forum/index.php?topic=13811.msg74413#msg74413 for details.
|
|
320
|
+
Fields a file asserts outrank ExifTool's "Geolocation*" tags, which name the nearest city in a bundled database and report how far away it was; a Country or City written into a file is an assertion about that photo.
|
|
321
|
+
The "applePhotos*" fields come first: they are an Apple Photos library's own reverse geocoding, read from its database, and only assets inside such a library have them.
|
|
322
|
+
The state is the one level where "Geolocation*" leads, because Apple stores the postal abbreviation ("CA") and ExifTool the full name ("California"), which makes the better navigation label.
|
|
323
|
+
This ordering is also what lets an organized copy keep the place names of the original: a library copy sits outside the Photos library, so its metadata arrives through an XMP sidecar under these standard names rather than the "applePhotos*" ones.`,defaultValue:()=>[`applePhotosCountry|Country|LocationShown.CountryName|LocationCreated.CountryName|GeolocationCountry`,`GeolocationRegion|applePhotosState|State|LocationShown.ProvinceState|LocationCreated.ProvinceState`,`applePhotosCounty|County|GeolocationSubregion`,`applePhotosCity|City|LocationShown.City|LocationCreated.City|GeolocationCity`,`applePhotosSubLocality|Location|LocationShown.SubLocation|LocationCreated.SubLocation`,`applePhotosPOI|POI`]}),tagGeoTemplate:new StringArraySetting({category:SettingCategories.Tagging,description:`How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.
|
|
324
|
+
The "POI" level names a specific point of interest -- a park, a business, a harbor -- and is currently only populated for assets read from an Apple Photos library. Levels with no value are skipped, so it costs nothing for every other file.`,defaultValue:[`Country`,`State`,`County`,`City`,`Location`,`POI`]}),tagGeoCollapseRepeatedLevels:new BooleanSetting({category:SettingCategories.Tagging,description:`Should a place name that merely repeats the level directly above it be dropped from the "Where" hierarchy?
|
|
325
|
+
Some places carry one name at several levels: San Francisco is a city and its own county, which renders as "Where / US / CA / San Francisco / San Francisco". So do roughly a tenth of the places in ExifTool's geolocation database, like Hobart in Tasmania. Turning this on collapses each of those to a single segment.
|
|
326
|
+
It is off by default because a repeated name is sometimes a real distinction rather than a restatement. New York is a state, a county, and a city; collapsing them removes New York County from the county level, so a New York library could no longer list its counties.
|
|
327
|
+
Only a level that repeats the one directly above it is dropped. The country is compared as its ISO code, so a city named after its own country -- Luxembourg -- keeps its segment, as does any name that recurs at levels further apart.
|
|
328
|
+
Note that if you edit this setting, you need to rebuild your library to see the changes take effect.`,defaultValue:!1}),tagJsonFaces:new BooleanSetting({category: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 BooleanSetting({category: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 StringArraySetting({category: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 StringEnumSetting({category:SettingCategories.Tagging,description:`How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?
|
|
329
|
+
- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".
|
|
330
|
+
- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).
|
|
331
|
+
- "family/fullname" will tag "Who/Einstein/Albert Einstein".
|
|
332
|
+
The default is "as-is," because discerning given and family names aren't reliably inferable.
|
|
333
|
+
See https://en.wikipedia.org/wiki/Personal_name#Name_order .`,defaultValue:NameTagFormats[`as-is`],strEnum:NameTagFormats}),tagNamesDefaultFamily:new StringSetting({category:SettingCategories.Tagging,blankIsValue:!0,description:`If a name has no family name, this value is used in place of one, so every "Who" tag keeps the same shape: "Madonna" is tagged "Who/-/Madonna", and the second level stays a family name throughout.
|
|
334
|
+
If this value is blank, the family level is omitted instead, and the name is tagged "Who/Madonna".
|
|
335
|
+
Only used when "tagNamesFormatter" is set to "family/given" or "family/fullname".`,defaultValue:`-`}),tagNamesCapitalizedAsFamily:new BooleanSetting({category:SettingCategories.Tagging,description:`Assume uppercased names are family names (this is common practice in geneology).`,defaultValue:!0}),tagNamesOrder:new StringEnumSetting({category:SettingCategories.Tagging,description:`Controls how PhotoStructure interprets ambiguous name ordering when parsing people's names. "givenFirst" assumes "Given Surname" order (e.g., "John Smith"). "surnameFirst" assumes "Surname Given" order (e.g., "Miyazaki Hayao"). This affects both parsing (which part is the family name) and rendering (display order in "family/fullname" mode). Only used when "tagNamesFormatter" is set to "family/given" or "family/fullname". See https://en.wikipedia.org/wiki/Personal_name#Name_order . Terminology follows Unicode CLDR: https://www.unicode.org/reports/tr35/tr35-personNames.html . Previous versions of PhotoStructure used "western" and "eastern" as the values for this setting, but these were confusing and not particularly accurate, so they are now deprecated aliases for "givenFirst" and "surnameFirst", respectively.`,defaultValue:`givenFirst`,strEnum:NameTagOrders,valueAliases:{western:`givenFirst`,eastern:`surnameFirst`}}),tagNamesSurnamePrefixes:new StringArraySetting({category: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,St.,ten,ter,Van 't,van de,van der,van,von der,von,z,zu`.split(`,`)}),tagNamesSurnames:new StringArraySetting({category: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 StringArraySetting({category: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 StringArraySetting({category: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 StringArraySetting({category: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 BooleanSetting({category: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 givenFirst 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 StringArraySetting({category: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 StringSetting({category: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:`Filesystem`}),tagDisplayNameFSRoot:new StringSetting({category: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 BooleanSetting({category:SettingCategories.Tagging,description:`On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?`,defaultValue:()=>isNotProd()?!0:!isDocker()}),tagDisplayNameFSLabels:new BooleanSetting({category: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 StringArraySetting({aliases:[`tagAlbumJsonFilenames`],category: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.
|
|
336
|
+
Set this to an empty array ("[]") to disable this feature.`,defaultValue:[`metadata.json`]}),tagAlbumTitle:new StringArraySetting({category:SettingCategories.Tagging,description:`What's the name of the field encoding the album file?
|
|
337
|
+
The first defined field will win.
|
|
338
|
+
Object hierarchies are separated with a ".".
|
|
339
|
+
Google Takeout uses "albumData.title" for album titles.
|
|
340
|
+
"Album" will pull in the XMP "Album" tag.
|
|
341
|
+
The MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.
|
|
342
|
+
Note that if you edit this setting, you need to rebuild your library to see the changes take effect.`,defaultValue:[`Album`,`albumData.title`,`Collections.CollectionName`,`applePhotosAlbums`]}),tagAlbumTitleHierarchies:new BooleanSetting({category: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 StringArraySetting({category: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 StringArraySetting({category: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 StringArraySetting({category: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`]}),tagPathRenames:new StringMapSetting({category:SettingCategories.Tagging,description:`Map of tag paths to rename. Keys are patterns to match, values are replacements. This allows you to fix misspellings, consolidate duplicate tags, and reorganize your tag hierarchy.
|
|
343
|
+
|
|
344
|
+
Pattern matching:
|
|
345
|
+
- Patterns starting with "/" are anchored to the beginning of the path
|
|
346
|
+
- Patterns without "/" match anywhere in the path (first match wins)
|
|
347
|
+
- All matching is case-insensitive
|
|
348
|
+
- Matched prefix/segment is replaced; remaining path segments are preserved
|
|
349
|
+
|
|
350
|
+
Examples:
|
|
351
|
+
- "/Album/Wrong": "Album/Correct" - renames Album/Wrong/* to Album/Correct/*
|
|
352
|
+
- "/Who/John Doe": "Who/Doe/John" - reorganizes a person's tag hierarchy
|
|
353
|
+
- "USA": "United States" - renames any "USA" segment anywhere in the path
|
|
354
|
+
- "Australia/Victoria/Saint Albans": "Australia/Victoria/St Albans" - fixes a misspelling
|
|
355
|
+
|
|
356
|
+
Changes require a library rebuild to take effect.`,defaultValue:{},exampleValue:()=>({"Australia/Victoria/Saint Albans":`Australia/Victoria/St Albans`})}),vacuumOrphanTags:new BooleanSetting({category:SettingCategories.Tagging,description:"Should empty tags (with zero assets and no children) be removed at the end of each sync? Tags under roots listed in `keepEmptyTags` are preserved. Disable this to keep all tags indefinitely.",defaultValue:!0}),keepEmptyTags:new StringArraySetting({category:SettingCategories.Tagging,description:`Root tag names whose self and descendants are preserved during orphan tag cleanup, even when they have zero assets. This is useful for tags like "Albums" where users may create empty tags intentionally.`,defaultValue:[`Albums`]}),omitAncestorTags:new BooleanSetting({category:SettingCategories.Tagging,description:`PhotoStructure's hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.
|
|
357
|
+
If 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})};for(let[e,n]of entries(TaggingSettings))n._setName(e);var RootTagAliasConfigs=[{root:`Albums`,setting:TaggingSettings.rootTagAlbumsAliases},{root:`Keywords`,setting:TaggingSettings.rootTagKeywordsAliases},{root:`What`,setting:TaggingSettings.rootTagWhatAliases},{root:`Where`,setting:TaggingSettings.rootTagWhereAliases},{root:`Who`,setting:TaggingSettings.rootTagWhoAliases},{root:`Event`,setting:TaggingSettings.rootTagEventAliases}],import_node_fs8=require("node:fs"),import_promises=require("node:fs/promises"),import_node_os8=require("node:os"),import_node_path11=__toESM(require("node:path")),import_win32=__toESM(require("node:path/win32")),import_node_process12=require("node:process"),import_node_os7=require("node:os"),import_node_path10=require("node:path"),import_node_path5=require("node:path");function dockerConfigDirs(e){return[{dir:`/ps/config`,preexistingDir:`/ps/config`},{dir:e+`/.photostructure/docker-config`,preexistingDir:e}]}function nativeConfigDirs(e){let{appName:n,home:r}=e;return(e.os===`win`?[e.appData,(0,import_node_path5.join)(r,`AppData`,`Roaming`),e.localAppData]:e.os===`mac`?[(0,import_node_path5.join)(r,`Library`,`Application Support`)]:[notBlank2(e.xdgConfigHome)??(0,import_node_path5.join)(r,`.config`)]).map(e=>notBlank2(e)).filter(e=>e!=null).map(e=>({dir:(0,import_node_path5.join)(e,n),preexistingDir:e}))}function notBlank2(e){return e!=null&&e.trim().length>0?e:void 0}function dockerLibraryDir(){for(let e of DockerLibraryDirEnvKeys){let n=process.env[e];if(!blank(n))return n}return DefaultDockerLibraryDir}var DockerInternalDirs=[`/ps/cache`,`/ps/config`,`/ps/log`,`/ps/logs`,`/ps/temp`,`/ps/tmp`],import_node_process11=require("node:process"),version=`2026.12.3`,versionMajor=2026,versionMinor=12,versionPatch=3,gitDate=new Date(1796391838e3),SimpleAppName=`PhotoStructure`,SimpleAppNameLC=SimpleAppName.toLowerCase(),AppName=lazy2(()=>SimpleAppName+(isProd()?``:`-${nodeEnv()}`)),AppNameVersion=lazy2(()=>AppName()+` `+version);function envToKeys(e){return[e,ensurePrefix(camel2snake(e).toUpperCase(),`PS_`)]}function getEnv(e){for(let n of envToKeys(e)){let e=process.env[n];if(e!=null)return e}}function getEnvs(e){let n=[];for(let r of envToKeys(e)){let e=process.env[r];e!=null&&n.push(e)}return n}function isEnvTrue(e){return isTrue(getEnv(e))}var import_node_fs6=require("node:fs"),import_luxon2=require("luxon"),logger4=lazy2(()=>mkLogger(`date.Date`));function isDateObject(e){return isObject(e)&&typeof e.year==`number`}function neg(e,n){return(e<0?`-`:``)+n}function fmtMs(e){return neg(e,import_luxon2.Duration.fromMillis(Math.abs(e)).toFormat(`m:ss.SSS`))}function durationHMS(e){let n=Math.abs(e);return neg(e,import_luxon2.Duration.fromMillis(round(n/secondMs)*secondMs).toFormat(n<hourMs?`m:ss`:`h:mm:ss`))}function utcIsoToTs(e){if(blank(e))return;let n=import_luxon2.DateTime.fromISO(e,{zone:`utc`});return n.isValid?n.toMillis():void 0}function dateObjectToDateTime(e,n=!1){if(e!=null)try{if(e instanceof import_luxon2.DateTime)return e.isValid===!0?e:void 0;if(e.month!=null&&e.day!=null){let r={year:e.year,month:e.month,day:e.day};e.hour!=null&&(r.hour=e.hour),e.minute!=null&&(r.minute=e.minute),e.second!=null&&(r.second=e.second),e.millisecond!=null&&(r.millisecond=e.millisecond);let a=import_luxon2.DateTime.fromObject(r,{zone:e.zone});return a!=null&&!a.isValid&&logger4().debug(`dateObjectToDateTime() invalid`,{obj:e,why:a.invalidExplanation}),n||a?.isValid?a:void 0}return}catch(n){logger4().debug(`dateObjectToDateTime() failed`,{obj:e,error:n});return}}var import_node_fs4=__toESM(require("node:fs")),import_node_path6=require("node:path"),import_node_process9=__toESM(require("node:process")),getUid=lazy2(()=>import_node_process9.default.geteuid?.());function writeProbeBasename(){return`.ps-write-test-`+import_node_process9.default.pid}var RetriableProbeCodes=[`EPERM`,`EACCES`,`EBUSY`],WriteProbeAttempts=3;function probeWrite(e){try{import_node_fs4.default.appendFileSync(e,``)}catch(e){return e}try{import_node_fs4.default.unlinkSync(e)}catch{}}function dirWriteError(e){if(blank(e))return Error(`directory pathname is blank`);let n=(0,import_node_path6.join)(e,writeProbeBasename()),r;for(let e=0;e<WriteProbeAttempts;e++){if(r=probeWrite(n),r==null)return;if(!RetriableProbeCodes.includes(r.code??``))return r}return r}function errnoError(e,n){let r=Error(n);return r.code=e,r}function statRWXError(e,n){if(isWin)return blank(n)?Error(`pathname is blank`):e==null?errnoError(`ENOENT`,`does not exist`):e.isDirectory()?dirWriteError(n):void 0;if(e==null)return errnoError(`ENOENT`,`does not exist`);if(blank(n))return Error(`pathname is blank`);try{if(import_node_fs4.default.accessSync(n,import_node_fs4.default.constants.R_OK|import_node_fs4.default.constants.W_OK|import_node_fs4.default.constants.X_OK),e.isDirectory()){let e=dirWriteError(n);if(e!=null)throw e}return}catch(n){return withStatContext(n,e)}}function withStatContext(e,n){return e.message=`${stripSuffix(stripPrefix(e.message,`${e.code}: `),e.path==null?``:` '${e.path}'`)}; mode 0o${(n.mode&511).toString(8)}, owned by uid ${n.uid} gid ${n.gid}, process uid ${getUid()}`,e}function isStatRWX(e,n){return statRWXError(e,n)==null}function isStatRX(e,n){return e!=null&&canAccessSync(n,{r:!0,x:!0})}async function canAccess(e,n){if(blank(e))return!1;try{return await import_node_fs4.default.promises.access(e,accessMode(n)),!0}catch{return!1}}function canAccessSync(e,n){return accessError(e,n)==null}function accessError(e,n){if(blank(e))return Error(`pathname is blank`);try{import_node_fs4.default.accessSync(e,accessMode(n));return}catch(e){return e}}function accessMode({r:e=!1,w:n=!1,x:r=!1}){return(e?import_node_fs4.default.constants.R_OK:0)|(n?import_node_fs4.default.constants.W_OK:0)|(r?import_node_fs4.default.constants.X_OK:0)}var import_node_path7=__toESM(require("node:path"));function posix2native(e,n){if(blank(e)||import_node_path7.default.sep===import_node_path7.default.posix.sep)return e;let r=notBlank(n)?import_node_path7.default.sep+import_node_path7.default.sep+n+import_node_path7.default.sep:``,a=e.split(import_node_path7.default.posix.sep);return equalsIgnoreCase(a[0],n)&&a.unshift(),r+a.join(import_node_path7.default.sep)}function native2posix(e){return blank(e)||import_node_path7.default.sep===import_node_path7.default.posix.sep||import_node_path7.default.posix.sep===import_node_path7.default.sep?e:e.split(import_node_path7.default.sep).join(import_node_path7.default.posix.sep)}var import_node_fs5=__toESM(require("node:fs"));function statSync(e){try{return blank(e)?void 0:import_node_fs5.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function isEmptyStats(e){return e==null||e.isFile()&&e.size===0}function isFileSync(e,n=0){let r=statSync(e);return r!=null&&r.isFile()&&r.size>=n}function isEmptyFileSync(e,n={emptyIsNew:!0}){let r=statSync(e);return n.emptyIsNew?r==null:isEmptyStats(r)}function isNonEmptyFileSync(e,n=0){let r=statSync(e);return r!=null&&r.isFile()&&r.size>=n}function isDirectorySync(e){return statSync(e)?.isDirectory()===!0}function nativePathSizeSync(e){return statSync(e)?.size}function isReadableDirectorySync(e){let n=statSync(e);return n!=null&&n.isDirectory()&&canAccessSync(e,{r:!0,x:!0})}function isReadWriteableDirectorySync(e){if(blank(e))return!1;let n=statSync(e);return n!=null&&n.isDirectory()&&canAccessSync(e,{r:!0,w:!0,x:!0})}function firstDir({dirs:e,desc:n}){for(let{dir:r,preexistingDir:a}of compact(e))if(!blank(r)){if(isReadWriteableDirectorySync(r))return r;if(blank(a)||isReadWriteableDirectorySync(a))try{return(0,import_node_fs6.mkdirSync)(r,{recursive:!0}),r}catch(e){console.error(`Failed to mkdir for `+n,e)}}}var import_node_os6=require("node:os"),import_node_path8=require("node:path"),import_node_process10=require("node:process"),homeDir=defer(()=>{let e=[];isWin?e.push(import_node_process10.env.USERPROFILE):e.push(import_node_process10.env.HOME);for(let n of compactBlanks(e)){let e=(0,import_node_path8.resolve)(n);if(isDirectorySync(e))return e}return(0,import_node_os6.homedir)()});function desktopConfigDir(){return firstDir({dirs:desktopConfigDirs(),desc:`config`})}function desktopConfigDirs(){return nativeConfigDirs({appName:AppName(),home:homeDir(),os:isWin?`win`:isMac?`mac`:`linux`,appData:getEnv(`APPDATA`),localAppData:getEnv(`LOCALAPPDATA`),xdgConfigHome:import_node_process11.env.XDG_CONFIG_HOME})}var import_node_fs7=require("node:fs"),import_node_path9=require("node:path");function envConfigDir(){let e=getEnv(`PS_CONFIG_DIR`);if(!blank(e)){if(e===(0,import_node_path9.dirname)(e))return e;try{return(0,import_node_fs7.mkdirSync)(e,{recursive:!0}),e}catch(n){if(isReadWriteableDirectorySync(e))return e;console.error(`The environment variable PS_CONFIG_DIR is set to `+e+`, but mkdir failed.`,n)}}}var resolvedConfigDir=lazy2(()=>envConfigDir()??(isDocker()?dockerConfigDir():desktopConfigDir()));function configDir_(){let e=resolvedConfigDir();if(e!=null)return e;throw Error(`No writable, persistent config directory is available. Set PS_CONFIG_DIR to one, or make one of these directories available: `+osConfigDirs().map(e=>JSON.stringify(e)).join(`, `))}var safeConfigDir=lazy2(()=>{try{return configDir_()}catch(e){console.error(`configDir_() failed`,e);return}});function configDir(){return safeConfigDir()}ee().on(`resetDirectories`,resetConfigDir);function dockerConfigDirs2(e=dockerLibraryDir()){return dockerConfigDirs(e)}function dockerConfigDir(){return firstDir({dirs:dockerConfigDirs2(),desc:`config`})}function resetConfigDir(){resolvedConfigDir.unset(),safeConfigDir.unset()}function osConfigDirs(){return(isDocker()?dockerConfigDirs2():desktopConfigDirs()).map(e=>e.dir)}function dockerPixiHome(){let e=usableDirOverride(process.env.PIXI_HOME);if(e!=null)return e;let n=configDir();if(n==null)throw Error(`Cannot resolve the Pixi prefix: no config directory is readable or creatable. Bind-mount /ps/config, or set PIXI_HOME.`);return(0,import_node_path10.join)(n,`pixi`,platformArch)}function dockerPixiBinDir(){return(0,import_node_path10.join)(dockerPixiHome(),`bin`)}function usableDirOverride(e){let n=toNotBlank(e);return n!=null&&(0,import_node_path10.isAbsolute)(n)?n:void 0}function userPixiBinDir(){return(0,import_node_path10.join)((0,import_node_os7.homedir)(),`.pixi`,`bin`)}var logger5=lazy2(()=>mkLogger(`fs.DefaultPaths`));function removeBlanksAndDuplicates(e){return compactBlanks(uniq(e))}var HomebrewBinDirs=[`/opt/homebrew/bin`,`/usr/local/bin`];function managedMacToolPaths(e=import_node_fs8.existsSync,n=userPixiBinDir()){return removeBlanksAndDuplicates([HomebrewBinDirs.find(n=>e(import_node_path11.default.join(n,`brew`))),n])}function managedWinToolPaths(e=userPixiBinDir(),n=windowsSystemDrive()){return removeBlanksAndDuplicates([e,import_win32.default.join(n,`msys64`,`mingw64`,`bin`)])}function defaultMacOSPaths(){return removeBlanksAndDuplicates([`/opt/homebrew/bin`,`/opt/homebrew/sbin`,...defaultPosixPaths()])}function defaultPosixPaths(){return removeBlanksAndDuplicates([`/usr/local/bin`,`/usr/local/sbin`,`/opt/local/bin`,`/opt/local/sbin`,`/usr/lib/libraw`,`/usr/sbin`,`/usr/bin`,`/sbin`,`/bin`])}function defaultLinuxPaths(){return removeBlanksAndDuplicates([isLinux?userPixiBinDir():void 0,...defaultPosixPaths()])}function pathsForDocs(e){let n=(0,import_node_os8.homedir)();return blank(n)?[...e]:e.map(e=>e===n||e.startsWith(n+import_node_path11.default.sep)?`~`+e.slice(n.length):e)}function managedToolPaths(){if(isDocker())try{return[dockerPixiBinDir()]}catch(e){return logger5().warn(`managedToolPaths(): cannot resolve the Pixi prefix`,{error:e}),[]}return isMac?managedMacToolPaths():isLinux?[userPixiBinDir()]:isWin?managedWinToolPaths():[]}function defaultDockerPaths(){return removeBlanksAndDuplicates([`/opt/photostructure/tools`,...defaultPosixPaths()])}function windowsSystemDrive(){return isWin?toNotBlank(import_node_process12.env.SystemDrive)??`C:`:`C:`}var wingetFfmpegBinDirs=lazy2(()=>[]);async function readdirIfExists(e){try{return await(0,import_promises.readdir)(e)}catch(e){let n=e.code;if(n===`ENOENT`||n===`ENOTDIR`)return[];throw e}}async function isDirectoryIfExists(e){try{return(await(0,import_promises.stat)(e)).isDirectory()}catch(e){let n=e.code;if(n===`ENOENT`||n===`ENOTDIR`)return!1;throw e}}async function refreshWingetFfmpegBinDirs(){let e=compactBlanks([mapNotBlank(import_node_process12.env.LOCALAPPDATA,e=>import_win32.default.join(e,`Microsoft`,`WinGet`,`Packages`)),mapNotBlank(import_node_process12.env.ProgramFiles,e=>import_win32.default.join(e,`WinGet`,`Packages`))]),n=[];for(let r of e)for(let e of await readdirIfExists(r)){if(!e.startsWith(`Gyan.FFmpeg_`))continue;let a=import_win32.default.join(r,e);for(let e of await readdirIfExists(a)){if(!e.startsWith(`ffmpeg-`))continue;let r=import_win32.default.join(a,e,`bin`);await isDirectoryIfExists(r)&&n.push(r)}}wingetFfmpegBinDirs.set(n)}later(()=>{refreshWingetFfmpegBinDirs(),ee().on(`clearToolCache`,()=>void refreshWingetFfmpegBinDirs())});function defaultWinPaths(){let e=windowsSystemDrive(),n=toNotBlank(import_node_process12.env.SystemRoot)??`C:\\WINDOWS`,r=toNotBlank(import_node_process12.env.ProgramData)??`C:\\ProgramData`;return removeBlanksAndDuplicates([n,import_win32.default.join(n,`System32`),import_win32.default.join(e,`msys64`,`mingw64`,`bin`),...wingetFfmpegBinDirs(),mapNotBlank(import_node_process12.env.ChocolateyInstall,e=>import_win32.default.join(e,`bin`)),import_win32.default.join(r,`chocolatey`,`bin`)])}function defaultPaths(){let e=isDocker()?defaultDockerPaths():isWin?defaultWinPaths():isMac?defaultMacOSPaths():isLinux?defaultLinuxPaths():defaultPosixPaths();if(isElectron()){let n=process.resourcesPath;blank(n)||e.push(import_node_path11.default.join(n,`tools`))}return removeBlanksAndDuplicates(e)}var ToolsSettings={showFileInFolderUsesThunar:new BooleanSetting({category:SettingCategories.Tools,description:`If we're on Linux, should we use Thunar (via dbus) to "show file in folder"?`,defaultValue:!1}),showFileInFolderUsesFileUri:new BooleanSetting({category: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:()=>isLinux}),showFileInFolderCommand:new StringArraySetting({category: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.
|
|
358
|
+
This is provided to support Linux desktops that don't use Gnome.`,defaultValue:[]}),powerShellArgs:new StringArraySetting({category:SettingCategories.Tools,description:`The following are the default arguments added to spin up PowerShell on Windows devices.
|
|
359
|
+
See 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.
|
|
360
|
+
See https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.
|
|
361
|
+
See https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.
|
|
362
|
+
(Versions prior to v1.0.0 only specified "-NoLogo").`,defaultValue:[`-NoLogo`,`-NoProfile`,`-ExecutionPolicy`,`Bypass`]}),powerShellCulture:new StringSetting({category:SettingCategories.Tools,blankIsValue:!0,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 IntegerSetting({category:SettingCategories.Tools,description:`How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).`,defaultValue:()=>2}),toolPaths:new StringArraySetting({category:SettingCategories.Tools,description:`These paths are prepended to the PATH environment variable to ensure PhotoStructure can find and run external tools like ffmpeg.
|
|
363
|
+
You can encode this as a JSON array, or use your operating system's separator to separate paths (":" for mac and linux, ";" for windows).
|
|
364
|
+
On Windows, this defaults to ${pathsForDocs(defaultWinPaths()).join(`;`)}
|
|
365
|
+
On macOS, this defaults to ${pathsForDocs(defaultMacOSPaths()).join(`:`)}
|
|
366
|
+
On bare-metal Linux, the standard-directory backstop defaults to ${pathsForDocs(defaultPosixPaths()).join(`:`)}
|
|
367
|
+
Docker additionally checks /opt/photostructure/tools; its managed Pixi prefix is derived from the system settings directory and searched separately.
|
|
368
|
+
Tools are searched for in this order: these paths first, then any tools PhotoStructure installed for you, then the PATH environment variable, and finally a series of standard directories specific to your operating system as a backstop.
|
|
369
|
+
On Windows, PhotoStructure installs tools into a per-user Pixi prefix (%USERPROFILE%\\.pixi\\bin), and %SystemDrive%\\msys64\\mingw64\\bin is searched next, for machines where an earlier release installed MSYS2. Both take precedence over same-named tools on PATH; set toolPaths to override them.`})};for(let[e,n]of entries(ToolsSettings))n._setName(e);var UpdateSettings={autoUpgradeSettings:new BooleanSetting({category:SettingCategories.Update,description:`Should PhotoStructure automatically re-write system and library settings.toml if it's determined that they are from a prior version of PhotoStructure?`,defaultValue:!0,advanced:()=>!0}),autoUpdateCheck:new BooleanSetting({category:SettingCategories.Update,description:`While running, PhotoStructure will check periodically for updates.
|
|
370
|
+
See https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.
|
|
371
|
+
Set this to "false" to disable automatic update checking.
|
|
372
|
+
Git-based Node installations also upgrade at startup unless autoUpdateCheck (or PS_AUTO_UPDATE_CHECK) is explicitly false in system settings.toml or the environment. Environment values override the file; PS_AUTO_UPDATE_CHECK takes priority when both names are set. An absent setting does not disable startup upgrades. The optOut setting does not affect update checks; noNetwork disables them.
|
|
373
|
+
The macOS and Windows desktop apps support automatic upgrades.
|
|
374
|
+
Node startup upgrades can also be disabled with NOGIT=1, PS_NO_GIT=1, or PS_CHECK_UPDATES=none.`,defaultValue:!1}),updateCheckTtlMs:new DurationSetting({category:SettingCategories.Update,description:`How frequently should PhotoStructure check for updates when running?`,defaultValue:()=>`6h`})};for(let[e,n]of entries(UpdateSettings))n._setName(e);var FFmpegPresets=strEnum(`ultrafast`,`superfast`,`veryfast`,`faster`,`fast`,`medium`,`slow`,`slower`,`veryslow`),FFmpegVideoCodecs=strEnum(`libx264`,`libx265`),VideoSettings={transcodeVideos:new BooleanSetting({aliases:[`transcodeVideo`],category:SettingCategories.Video,description:`Whether to transcode videos during import so every browser can play them. Requires ffmpeg.
|
|
375
|
+
|
|
376
|
+
**true (default, recommended):** Videos that aren't already a streamable mp4 are processed into one. When the source codecs are already browser-compatible this is a fast *remux* (new container, same bytes — no quality loss, low CPU). Only videos that actually need re-encoding pay the full transcode cost.
|
|
377
|
+
|
|
378
|
+
**false:** Original files are served to the browser as-is. Only set this if you're certain your library will play directly; otherwise you'll see black/"stalled" videos with no hint why. Common ways originals fail to play even when the codec looks fine:
|
|
379
|
+
- **Non-mp4 containers** (video/quicktime/MOV, MKV, AVI, etc.) — only video/mp4 and video/webm stream universally.
|
|
380
|
+
- **\`moov\` atom at the end of the file** — typical for iPhone/DSLR MOVs straight off the camera. Firefox refuses to stream these; Chromium handles them. Transcoding remuxes with \`+faststart\` to fix this.
|
|
381
|
+
- **Non-H.264 video codecs** (HEVC/h265, VP9, AV1, ProRes, etc.) — depends on the specific browser + OS + hardware.
|
|
382
|
+
- **Non-AAC audio codecs** (AC-3, DTS, etc.) — require transcoding for browser playback.
|
|
383
|
+
|
|
384
|
+
Use \`false\` only if you've already standardized your library on faststart'd mp4s, or you're fine using Chrome/Edge exclusively for playback.`,defaultValue:!0}),ffmpegHwaccel:new StringSetting({category:SettingCategories.Video,description:`FFmpeg supports both software and hardware encoders. Valid values include "auto" (which should "just work" for everyone, but verify this yourself!), "h264_nvenc" for GPUs, "cuda" for NVIDIA GPUs, "dxva2" or "d3d11va" for Windows, or use "disabled" to omit this argument.
|
|
385
|
+
Run "ffmpeg -hwaccels" to see supported acceleration methods.
|
|
386
|
+
Note that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.
|
|
387
|
+
Note that PhotoStructure will automatically retry without hwaccel if there are hwaccel errors.
|
|
388
|
+
For more details, see https://forum.photostructure.com/t/hardware-accelerated-encoding-transcoding/166 https://trac.ffmpeg.org/wiki/HWAccelIntro https://github.com/NVIDIA/nvidia-docker`,defaultValue:`disabled`}),ffmpegThreads:new BoundedIntegerSetting({category:SettingCategories.Video,description:`How many threads should ffmpeg use per transcode? Values are clamped to 0–6.
|
|
389
|
+
|
|
390
|
+
Set to 1–6 to explicitly cap threads per transcode. Multiple transcodes will run concurrently up to "maxConcurrentImports" / PS_MAX_CONCURRENT_IMPORTS, so the effective ffmpeg load is roughly ffmpegThreads × concurrent imports.
|
|
391
|
+
|
|
392
|
+
Set to 0 to let ffmpeg pick its own thread count — ffmpeg's \`-threads 0\` heuristic chooses a value based on the codec and your CPU (usually ≈ physical core count). In this mode, PhotoStructure automatically serializes video transcodes (only one runs at a time) so you won't oversubscribe the CPU; image imports and other tasks still run concurrently up to "maxConcurrentImports".`,defaultValue:()=>1,min:0,max:6}),ffmpegStallTimeoutMs:new IntegerSetting({category:SettingCategories.Video,description:"Per-ffmpeg stall timeout, in milliseconds. If an ffmpeg transcode emits no live progress tick (via `-progress pipe:1` with `speed` above 0.01) for this long, PhotoStructure aborts that transcode via its halt signal. This catches hangs where ffmpeg is alive but making zero forward progress (e.g., spinning on a malformed frame, or waiting indefinitely on a hwaccel device) without relying on the much larger total-duration cap.\nSet to 0 to disable stall detection. Default is 5 minutes, which is generous enough to tolerate a slow-seeking NAS but tight enough to surface real stalls.",defaultValue:()=>3e5}),ffmpegPreset:new StringEnumSetting({category:SettingCategories.Video,strEnum:FFmpegPresets,description:`Encoding preset for x264/x265. Faster presets encode more quickly but produce larger files.
|
|
393
|
+
Options: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow.
|
|
394
|
+
"veryfast" offers an excellent speed/quality tradeoff (3-5x faster than "medium" with minimal quality difference).
|
|
395
|
+
Note: These presets work for both libx264 and libx265 encoders.
|
|
396
|
+
See https://trac.ffmpeg.org/wiki/Encode/H.264#Preset for more details.`,defaultValue:`veryfast`}),transcodeVideoCodec:new StringEnumSetting({category:SettingCategories.Video,strEnum:FFmpegVideoCodecs,description:`Video codec for transcoding. Choose based on your browser/device mix:
|
|
397
|
+
|
|
398
|
+
**libx264 (H.264)** - Default, recommended for most users
|
|
399
|
+
- Universal support: Works in ALL browsers on ALL platforms
|
|
400
|
+
- Fast encoding speed
|
|
401
|
+
- Larger files than HEVC
|
|
402
|
+
|
|
403
|
+
**libx265 (HEVC/H.265)** - For Apple-only or storage-constrained setups
|
|
404
|
+
- 25-40% smaller files than H.264
|
|
405
|
+
- 2-5x slower encoding
|
|
406
|
+
|
|
407
|
+
HEVC browser support:
|
|
408
|
+
- Safari (macOS/iOS): Full support since Safari 11
|
|
409
|
+
- Chrome (macOS/Windows only): Supported since v107 (NO Linux support)
|
|
410
|
+
- Edge (Windows): Supported with hardware decode
|
|
411
|
+
- Firefox: NO native support (requires OS-level codecs)
|
|
412
|
+
- macOS: Works if system HEVC codec available
|
|
413
|
+
- Windows: Firefox 134+ with HEVC Video Extensions from Microsoft Store
|
|
414
|
+
- Linux: Firefox 137+ with VA-API hardware decode
|
|
415
|
+
|
|
416
|
+
**Choose HEVC if:** You only use Safari/Chrome, or Apple devices, and want smaller files.
|
|
417
|
+
**Stick with H.264 if:** You use Firefox on Linux/Windows, or need universal compatibility.
|
|
418
|
+
|
|
419
|
+
If switching to libx265, also set transcodeCrf to 28 for equivalent quality.
|
|
420
|
+
See https://photostructure.com/getting-started/video-support/ for details.`,defaultValue:`libx264`}),transcodeCrf:new BoundedIntegerSetting({category:SettingCategories.Video,description:`Constant Rate Factor (CRF) for quality-based video encoding. Lower values = higher quality and larger files.
|
|
421
|
+
|
|
422
|
+
**For libx264 (H.264, default):** 0 = lossless, 18 = visually transparent, 23 = good quality (default), 28 = acceptable for web.
|
|
423
|
+
**For libx265 (HEVC):** 0 = lossless, 22 = visually transparent, 28 = good quality, 32 = acceptable for web.
|
|
424
|
+
|
|
425
|
+
Note: HEVC CRF values are ~5 higher than H.264 for equivalent quality (HEVC 28 ≈ H.264 23).
|
|
426
|
+
CRF automatically adjusts bitrate based on content complexity, producing smaller files for simple scenes and larger files for complex action.`,defaultValue:()=>23,min:0,max:51}),ffmpegAvcTranscodeArgs:new StringArraySetting({category:SettingCategories.Video,aliases:[`ffmpegTranscodeArgs`],description:`Base arguments for ffmpeg video transcoding. These follow "ffmpeg -loglevel error -i INPUT".
|
|
427
|
+
|
|
428
|
+
**Note**: Colorspace handling is now automatic based on source video metadata:
|
|
429
|
+
- HDR (BT.2020/PQ/HLG): Preserved without conversion
|
|
430
|
+
- BT.709 (most HD): Tagged correctly, no conversion
|
|
431
|
+
- BT.601 (SD): Converted to BT.709 for browser compatibility
|
|
432
|
+
- Unknown: Height-based heuristic (HD=BT.709, SD=BT.601)
|
|
433
|
+
|
|
434
|
+
See https://forum.photostructure.com/t/poor-transcoding-of-videos-in-wider-color-spaces-rec-2020/646
|
|
435
|
+
CAUTION: Invalid values may cause transcoded videos to not play in browsers.`,defaultValue:[`-c:a`,`aac`,`-c:v`,`libx264`,`-pix_fmt`,`yuv420p`,`-movflags`,`+faststart`]}),ffmpegErrDetect:new StringSetting({category:SettingCategories.Video,description:`PhotoStructure applies the given option to FFmpeg's "-err_detect" option. Available levels:
|
|
436
|
+
- "crccheck" - Verify embedded CRCs
|
|
437
|
+
- "bitstream" - Detect bitstream specification deviations
|
|
438
|
+
- "buffer" - Detect improper bitstream length
|
|
439
|
+
- "explode" - Abort decoding on minor error detection
|
|
440
|
+
- "ignore_err" - Ignore decoding errors and continue (useful for analysis, but may produce unwatchable videos)
|
|
441
|
+
- "careful" - Consider things that violate the spec but haven't been seen in the wild as errors
|
|
442
|
+
- "compliant" - Consider all spec non-compliances as errors (strictest)
|
|
443
|
+
- "aggressive" - Consider things a sane encoder shouldn't do as errors
|
|
444
|
+
|
|
445
|
+
You can combine multiple options with "+" (e.g., "crccheck+bitstream+buffer").
|
|
446
|
+
The default "crccheck+bitstream+buffer" provides strict but reasonable error detection.`,defaultValue:`crccheck+bitstream+buffer`}),videoPreviewFitInside:new DimensionsSetting({aliases:[`videoPreviewMaxDim`,`transcodeMaxDim`],category:SettingCategories.Video,description:`One or two maximum fit boxes for generated video previews: both poster images and browser-compatible transcoded MP4 files. Write them as "WIDTHxHEIGHT[,WIDTHxHEIGHT]". PhotoStructure fits each video inside every box without enlarging it and uses the highest-resolution result. The default covers FHD displays in either orientation. Downsampling may require lossy video re-encoding instead of a lossless remux. Originals are never modified, and browser-compatible originals may still be streamed directly at native resolution.`,defaultValue:[{width:1920,height:1080},{width:1080,height:1920}],legacySquareNumbers:!0,whyInvalid:whyInvalidPreviewFitInside}),transcodeFrameRate:new OptionalIntegerSetting({category: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.
|
|
447
|
+
Note 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.
|
|
448
|
+
Unset this or set to 0 to disable bounded frame rates.`,exampleValue:()=>30}),doNotTranscodeMimeTypes:new StringArraySetting({category:SettingCategories.Video,description:`Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.
|
|
449
|
+
See https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.
|
|
450
|
+
If 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 StringArraySetting({category:SettingCategories.Video,description:`Video codecs that don't need transcoding (already browser-compatible). The video codec may be stored in the "VideoCodec", "CompressorID", or "CompressorName" tags.
|
|
451
|
+
|
|
452
|
+
**Browser Compatibility:**
|
|
453
|
+
- "avc1" (H.264): Universal support - all browsers, all platforms
|
|
454
|
+
- "hvc1" (HEVC/H.265): Safari 11+, Chrome 107+ (macOS/Windows only, NO Linux support), Edge (hardware). Firefox requires OS-level codecs (macOS: system codec, Windows: HEVC Video Extensions, Linux: VA-API hardware decode)
|
|
455
|
+
- "vp09" (VP9): Chrome/Firefox/Edge (full), Safari 14+ (hardware only on newer Apple chips)
|
|
456
|
+
|
|
457
|
+
**Default excludes hvc1** because Chrome on Linux has no HEVC support, and PhotoStructure commonly runs on Linux (Docker/NAS). If you only use Safari or Chrome on macOS/Windows, add "hvc1" to skip HEVC transcoding (saves CPU and ~25-40% storage vs H.264).
|
|
458
|
+
|
|
459
|
+
VP9 is NOT included by default because older iOS devices lack hardware VP9 decode.
|
|
460
|
+
See https://photostructure.com/getting-started/video-support/ for details.`,defaultValue:()=>[`avc1`]}),doNotTranscodeAudioCodecs:new StringArraySetting({category: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 "AudioFormat" tag.
|
|
461
|
+
|
|
462
|
+
**Browser Compatibility (2025):**
|
|
463
|
+
- "mp4a" (AAC): Universal support across all browsers and devices
|
|
464
|
+
- "sowt" (PCM/Linear): Universal support (uncompressed audio)
|
|
465
|
+
- Opus: Supported by Chrome, Firefox, Edge, Safari 15.4+
|
|
466
|
+
|
|
467
|
+
Note: AC-3, DTS, and other surround codecs require transcoding to AAC for browser playback.`,defaultValue:()=>[`mp4a`,`sowt`]}),browserCompatibleContainers:new StringArraySetting({category:SettingCategories.Video,description:`MIME types of video containers that browsers can play directly without transcoding.
|
|
468
|
+
This is used to determine if a video only needs remuxing (container change) vs full transcoding.
|
|
469
|
+
Remuxing is lossless and very fast compared to transcoding.
|
|
470
|
+
|
|
471
|
+
**Browser Compatibility (2025):**
|
|
472
|
+
- "video/mp4": Universal support across all browsers and devices
|
|
473
|
+
- "video/webm": Chrome, Firefox, Edge (full), Safari 14.1+ (partial - VP8/VP9 only, no AV1 on older devices)
|
|
474
|
+
|
|
475
|
+
Note: This is different from doNotTranscodeMimeTypes - that setting controls whether to transcode at all,
|
|
476
|
+
while this setting helps optimize HOW to transcode (remux vs full re-encode).`,defaultValue:()=>[`video/mp4`,`video/webm`]})};for(let[e,n]of entries(VideoSettings))n._setName(e);var PS_LIBRARY_SCHEME=`pslib`,PS_LIBRARY_PROTOCOL=PS_LIBRARY_SCHEME+`:`,PS_LOCAL_FILE_SCHEME=`psfile`,PS_LOCAL_FILE_PROTOCOL=PS_LOCAL_FILE_SCHEME+`:`,PS_NETWORK_FILESYSTEM_SCHEME=`psnet`,PS_NETWORK_FILESYSTEM_PROTOCOL=PS_NETWORK_FILESYSTEM_SCHEME+`:`,PS_EXAMPLES_SCHEME=`examples`,PLAIN_FILE_SCHEME=`file`,AssetFileUriSchemes=strEnum(PS_LIBRARY_SCHEME,PS_LOCAL_FILE_SCHEME,PS_NETWORK_FILESYSTEM_SCHEME,PLAIN_FILE_SCHEME),URI_SCHEME_ORDER_BY=[PS_LIBRARY_SCHEME,PS_LOCAL_FILE_SCHEME,PS_NETWORK_FILESYSTEM_SCHEME,PS_EXAMPLES_SCHEME,`file`];function sortURIs(e){return sortBy(e,e=>{let n=e.split(`:`)[0],r=URI_SCHEME_ORDER_BY.indexOf(n);return[r===-1?URI_SCHEME_ORDER_BY.length:r,e]})}var DefaultWriteVolumeUuidFilesystemBlocklist=[`sshfs`,`s3fs`],LegacyWriteVolumeUuidFilesystemBlocklist=new CaseInsensitiveSet(DefaultWriteVolumeUuidFilesystemBlocklist.flatMap(e=>[e,`fuse.${e}`,`${e}.fuse`]));function isLegacyWriteVolumeUuidFilesystemBlocklistEntry(e){return LegacyWriteVolumeUuidFilesystemBlocklist.has(e)}function matchesWriteVolumeUuidFilesystemBlocklistEntry(e,n){let r=e?.toLowerCase(),a=n.toLowerCase();return r===a||r?.startsWith(a+`.`)===!0||r?.endsWith(`.`+a)===!0}var VolumesSettings={assetFileUriSchemes:new StringEnumsSetting({category:SettingCategories.Volumes,strEnum:AssetFileUriSchemes,description:`Which URI schemes may PhotoStructure use to record where each of your files lives? These are tried in order and the first that applies wins, so removing one makes those files fall back to the next -- and removing "file" means any file no remaining scheme can identify is skipped and reported instead of imported.
|
|
477
|
+
CAUTION: a "file" URI records no volume, so an unplugged drive becomes indistinguishable from deleted files, and a volume that moves re-imports as duplicates. Read https://photostructure.com/guide/file-uris/ before changing this, and rebuild your library afterwards.`,advanced:()=>!0}),volumeUuidFilePaths:new StringArraySetting({category: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).
|
|
478
|
+
Prior versions included "System Volume Information/IndexerVolumeGuid" but read permissions for that directory under Windows requires admin privileges, which we don't want.
|
|
479
|
+
Windows users should use a forward slash as a path separator.`,defaultValue:()=>[`.uuid`]}),readVolumeUuidFiles:new BooleanSetting({category: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.
|
|
480
|
+
Note that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."
|
|
481
|
+
For more details see https://photostructure.com/faq/what-is-a-volume`,defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new BooleanSetting({category:SettingCategories.Volumes,description:`When true, PhotoStructure will NOT write files with universally unique identifiers into the root directory of volumes that have been marked with a NoMedia file or folder. If writeVolumeUuidFiles is false this setting is ignored.`,defaultValue:!0}),writeVolumeUuidFiles:new BooleanSetting({category: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. For more details see https://photostructure.com/faq/what-is-a-volume`,defaultValue:!0}),writeVolumeUuidFilesystemBlocklist:new StringArraySetting({category:SettingCategories.Volumes,description:`Never write a volume UUID file to volumes with these filesystem types. Matching is case-insensitive, and an unqualified entry like "sshfs" also matches dot-qualified variants like "fuse.sshfs" and "sshfs.fuse". Writing to network and object-storage filesystems is slow, and for object storage may be billed per request. Default entries are bypassed when writing a ".uuid" is the only way to establish a durable volume identity; explicitly configured entries are always honored.`,defaultValue:()=>[...DefaultWriteVolumeUuidFilesystemBlocklist]}),writeVolumeUuidPathBlocklist:new StringArraySetting({category:SettingCategories.Volumes,description:`Never write a volume UUID file to mount points whose path contains one of these entries. Matching is case-insensitive and accepts either slash style. If no readable ".uuid" already exists, a blocked volume without an intrinsic filesystem UUID will not gain a portable volume identity.`,defaultValue:()=>[]}),writeVolumeUuidMountpointBlocklist:new StringArraySetting({category:SettingCategories.Volumes,deprecated:!0,description:`DEPRECATED: replaced by "writeVolumeUuidFilesystemBlocklist" (filesystem types) and "writeVolumeUuidPathBlocklist" (mount point paths). Any value here is split across those two settings on startup and then removed from this file.`,defaultValue:()=>[]}),volumeMetadataTtlMs:new DurationSetting({category:SettingCategories.Volumes,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. PhotoStructure may extend this budget up to 24 hours when monitored library and image-cache volumes have ample free space. Mounted-volume metadata is also refreshed when PhotoStructure rescans mount points, so this is an upper budget rather than a guaranteed lifetime. A value of 0 disables only the fixed lower bound.`,defaultValue:`15m`})};for(let[e,n]of entries(VolumesSettings))n._setName(e);var LibraryNameMaxLength=64;function normalizeLibraryName(e){return e.normalize(`NFC`).replace(/\s+/g,` `).trim()}function whyInvalidLibraryName(e){return normalizeLibraryName(e).length>LibraryNameMaxLength?`A library name can have at most ${LibraryNameMaxLength} characters`:void 0}var WebSettings={webUvThreads:new BoundedIntegerSetting({category:SettingCategories.Web,description:`How many libuv threads should the web process be given? If unset, UV_THREADPOOL_SIZE will be used. Higher values may allow for more concurrent requests, but may also consume more memory and CPU and overwhelm non-SSD storage. The default is 4, which should be fine for most installations. Read more about UV_THREADPOOL_SIZE: https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size.`,advanced:()=>!0,defaultValue:()=>4,max:32,min:1}),minStreamCorrPct:new BoundedFloatSetting({category: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 IntegerSetting({category: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.
|
|
482
|
+
The default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.
|
|
483
|
+
If you have fast hardware and fast network, you could try bumping this up to 200.
|
|
484
|
+
If you have very slow network, you might want to set this to 0.`,defaultValue:50}),hiddenRootTags:new StringArraySetting({category:SettingCategories.Web,aliases:[`hiddenHomeTags`],description:`The given root tags will be omitted from the home page. (Valid values include "When", "Camera", "Lens", "Type", "Fs", and "Keyword").`,defaultValue:()=>[],exampleValue:()=>[`Type`]}),openGraphTargetWidth:new IntegerSetting({category:SettingCategories.Web,description:`When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.
|
|
485
|
+
See https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.`,defaultValue:800}),fastForwardEmptyTags:new BooleanSetting({category: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 StringEnumSetting({category:SettingCategories.Web,description:`Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?
|
|
486
|
+
(IMHO /splash is more fun, but it slows down getting to the home page).`,strEnum:strEnum(`/tag`,`/splash`),defaultValue:()=>`/tag`}),libraryName:new OptionalStringSetting({category:SettingCategories.Web,description:`This library's name, like "Alex's Photos" or "Alex and Sam's Photos". The library's sign-in page shows it as its title. At most ${LibraryNameMaxLength} characters.`,fromEnv:e=>e==null?void 0:normalizeLibraryName(e),whyInvalid:e=>typeof e==`string`?whyInvalidLibraryName(e):void 0}),webAppName:new StringSetting({category:SettingCategories.Web,description:`The name shown when a visitor installs PhotoStructure as a PWA (via Chrome's "Install app" option). Defaults to "PhotoStructure", but you can customize it to something like "Family Photos" or whatever suits.`,defaultValue:`PhotoStructure`}),webAppShortName:new StringSetting({category:SettingCategories.Web,description:`The short_name shown when a visitor installs PhotoStructure as a PWA (via Chrome's "Install app" option). Defaults to "PhotoStructure".`,defaultValue:`PhotoStructure`})};for(let[e,n]of entries(WebSettings))n._setName(e);var Settings2={...PathSettings,...DesktopsSettings,...EmailSettings,...OidcSettings,...FilesystemSettings,...CacheSettings,...LoggingSettings,...NetworkingSettings,...ProcessesSettings,...SecuritySettings,...SignInSettings,...ToolsSettings,...PixiSettings,...UpdateSettings,...HardwareSettings,...PerformanceSettings,...AuthSettings,...ColorSettings,...DbSettings,...AggregationSettings,...FiltersSettings,...HealthSettings,...OrganizationSettings,...ParsingSettings,...PreviewsSettings,...PrivacySettings,...ReportingSettings,...SidecarsSettings,...SubscriptionSettings,...SyncSettings,...TaggingSettings,...VideoSettings,...VolumesSettings,...WebSettings};for(let[e,n]of entries(Settings2))if(n.name!==e)throw Error(`Setting "${e}" was not named by its group module (name: ${n.name}). Add \`for (const [k, v] of entries(XSettings)) v._setName(k)\` to it.`);var allSettings=lazy2(()=>sortBy(values(Settings2),settingsSorter)),persistedSettings=lazy2(()=>allSettings().filter(e=>!e.transient)),persistedSystemSettings=lazy2(()=>persistedSettings().filter(e=>SystemCategories.includes(e.category))),persistedLibrarySettings=lazy2(()=>persistedSettings().filter(e=>LibraryCategories.includes(e.category)));function settingsSorter(e){return[e.categoryType===`system`?0:1,SettingCategories.indexOf(e.category)??SettingCategories.length+1,e.advanced,e.name]}var SettingsByNameOrKey=lazy2(()=>{let e=new CaseInsensitiveMap;for(let n of persistedSettings()){for(let r of n.names)e.set(r,n);for(let r of n.keys)e.set(r,n)}return e});function getSettingByNameOrKey(e){return SettingsByNameOrKey().get(toS(e).toLowerCase())}var ciSettings=lazy2(()=>new CaseInsensitiveValued(Settings2,(e,n)=>[...n.names,...n.keys]));function getDevEnvFlag(e){return isProd()||isPacked()?!1:toBoolean(process.env[e])??!1}var EndableRanks=strEnum(`first`,`stats`,`service`,`predb`,`db`,`postdb`,`logger`,`logtail`,`last`),logger6=defer(()=>mkLogger(`async.Endable`)),endablesByRank=new MultiMap;setUnrefInterval(()=>vacuumEndables(),10*minuteMs);var DefaultEndTimeoutMs=5*secondMs;function addEndable(e,n){if(!EndableRanks.includes(e))throw Error(`internal error: invalid rank `+e);return endablesByRank.add(e,n),n}async function end(e,n){let r=await e;if(r==null||!0===r?.ended)return;let a=isTest()&&getDevEnvFlag(`PS_SINGLE_SPEC_TESTS`)?500:firstGt0(n,r.endTimeoutMs,DefaultEndTimeoutMs);logger6().trace(r.name+` ending...`,{timeoutMs:a});try{await thenOrTimeoutError(r.end(),a,isTest())}catch(e){try{logger6().warn(r.name+`.end() failed`,e)}catch{}}}function vacuumEndables(){endablesByRank.filterInPlace((e,n)=>n.ended!==!0),logger6().debug(`vacuumEndables()`,endablesByRank.entriesArray().map(([e,n])=>[e,n.map(e=>e.name)]))}var endEndables=lazy2(async()=>{let e=isSingleSpecTests()?500:void 0;logger6().debug(`endEndables()`,{isTest:isTest(),isSingleSpecTests:isSingleSpecTests()}),isTest()||setEnding(!0),vacuumEndables();for(let n of EndableRanks.values){let r=endablesByRank.get(n)??[];isNotEmpty(r)&&(logger6().debug(`endEndables(): ending `+n),await Promise.allSettled(r.map(n=>end(n,e))))}}),import_node_async_hooks=require("node:async_hooks"),import_types=require("node:util/types"),import_node_util7=require("node:util");function min(e){let n;for(let r of e)isComparable(r)&&(n==null||r<n)&&(n=r);return n}function max3(e){let n;for(let r of toA(e))isComparable(r)&&(n==null||r>n)&&(n=r);return n}function sum2(e){let n=0;for(let r of e??[])isNumber(r)&&(n+=r);return n}function sumf(e,n){let r=0,a=0;for(let o of e){if(o!=null){let e=n(o,r);isNumber(e)&&(a+=e)}r++}return a}var Mean=class{#e=0;#t;push(e){isNumber(e)&&(this.#t=this.#t==null?e:this.#t*this.#e/(this.#e+1)+e/(this.#e+1),this.#e++)}get mean(){return this.#t}};function avg(e){if(e!=null){if(Array.isArray(e)){let n=e.length;if(n===0)return;let r=0,a=0;for(let o=0;o<n;++o){let n=e[o];isNumber(n)&&(a++,r+=(n-r)/a)}return a>0?r:void 0}{let n=new Mean;for(let r of e)n.push(r);return n.mean}}}function slope(e){let n=toA(e).filter(isNumber),r=avg(n);if(r!=null){let e=(n.length-1)/2,a=sumf(n,(n,a)=>(n-r)*(a-e)),o=sumf(n,e=>(e-r)**2);return o===0?0:a/o}}function variance(e){if(e==null)return;let n=avg(e);if(n==null)return;let r=0,a=0;for(let o of e)isNumber(o)&&(a++,r+=(o-n)*(o-n));return r/a}function stdDev(e){return map(variance(e),Math.sqrt)}function ema(e,n=.5){if(e.length===0)throw Error(`values must contain at least one number`);if(!(n>0&&n<=1))throw Error(`carryForward must be in the range (0, 1]`);let r=1-n,a=e[0];for(let o=1;o<e.length;o++)a=n*a+r*e[o];return a}function weightedMean(e){if(e.length===0)throw Error(`samples must contain at least one element`);let n=0,r=0;for(let{value:a,weight:o}of e){if(o<0)throw Error(`weights must be non‑negative`);if(!isFinite(o)||!isFinite(a))throw Error(`values and weights must be finite numbers`);o!==0&&(r+=o,n+=o*(a-n)/r)}if(r===0)throw Error(`total weight must be greater than zero`);return n}var Average=class e{constructor(e=20){this.maxSamples=e,this._n=0,this._samples=new BoundedList(e)}maxSamples;static#e(n,r){let a=Math.max(n.maxSamples,r.maxSamples),o=new e(a);o._n=n._n+r._n,o._min=min([n._min,r._min]),o._max=max3([n._max,r._max]),n._m!=null&&r._m!=null?o._m=(n._m*n._n+r._m*r._n)/o._n:n._m==null?r._m!=null&&(o._m=r._m):o._m=n._m,n._s!=null&&r._s!=null?o._s=(n._s*n._n+r._s*r._n)/o._n:n._s==null?r._s!=null&&(o._s=r._s):o._s=n._s,o._ema=avg([n._ema,r._ema]);let s=n.samples,c=r.samples;if(s.length+c.length<=a)o._samples.push(...s,...c);else{let e=Math.floor(a/2),n=a-e;o._samples.push(...s.slice(-e),...c.slice(-n))}return o}static merge(n,r){return n===r?n:n==null?r?.clone()??new e:r==null?n?.clone()??new e:n.n===0&&r.n===0?new e(Math.max(n.maxSamples,r.maxSamples)):n.n===0?r.clone():r.n===0?n.clone():e.#e(n,r)}_n;_min;_max;_m;_s;_ema;_samples;[import_node_util7.inspect.custom](){return this.stats()}toJSON(){return{n:this._n,m:this._m,s:this._s,min:this._min,max:this._max,ema:this._ema,samples:this._samples.toA(),maxSamples:this.maxSamples}}static fromJSON(n){return isObject(n)?new e(toGte0(n.maxSamples)).with(n):void 0}with(e){return this._n=toInt(e?.n)??0,this._m=toFloat(e?.m),this._s=toFloat(e?.s),this._min=toFloat(e?.min),this._max=toFloat(e?.max),this._ema=toFloat(e?.ema),this._samples.push(...compact(toA(e?.samples).map(e=>toFloat(e)))),this}merge(n){if(n==null||n.n===0)return this;if(this.n===0)return this.with(n.toJSON());let r=e.#e(this,n);return this._n=r._n,this._m=r._m,this._s=r._s,this._min=r._min,this._max=r._max,this._ema=r._ema,this._samples.clear(),this._samples.push(...r._samples),this}push(e){if(!isFinite(e))throw Error(`Average.push(`+e+`): not a number`);if(this._n++,this._samples.push(e),this._min=this._min==null?e:Math.min(e,this._min),this._max=this._max==null?e:Math.max(e,this._max),this._n===1||this._m==null||this._s==null||this._ema==null)this._m=e,this._s=0,this._ema=e;else{let n=this._m;this._m+=(e-n)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._ema=(this._ema+e)/2}return e}clone(){return tap(new e(this.maxSamples),e=>{e._n=this._n,e._m=this._m,e._s=this._s,e._min=this._min,e._max=this._max,e._ema=this._ema,e._samples.push(...this._samples)})}pushAll(e){if(e!=null)for(let n of e)isNumber(n)&&this.push(n);return this}stats(e=2){let n=n=>map(n,n=>n>100?Math.round(n):sigFigs(n,e)),r={};return r.n=n(this.n),this.empty||(r.mean=n(this.avg),r.sum=n(this.sum),r.sd=n(this.stdDev),r.max=n(this.max),r.min=n(this.min),r.p84=n(this.p84)),r}get empty(){return this._n===0}get n(){return this._n}get count(){return this._n}get avg(){return this.empty?void 0: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}#t(e){return this._m==null||this._s==null?void 0:sigFigs(this._m+Math.sqrt(this._s)*e,4)}get p16(){return this.#t(-1)}get p29(){return this.#t(-.5)}get p38(){return this.#t(-.25)}get p50(){return this.avg}get p69(){return this.#t(.5)}get p84(){return this.#t(1)}get p98(){return this.#t(2)}get p99(){return this.#t(3)}p(e){switch(e){case`p16`:return this.#t(-1);case`p50`:return this.#t(0);case`p69`:return this.#t(.5);case`p84`:return this.#t(1);case`p98`:return this.#t(2);case`p99`:return this.#t(3)}}get stdDevOverMean(){return this._m==null||this._s==null?void 0:sigFigs(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){let e=this.variance;return e==null?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;let n=new CountingSet;return this._samples.forEach(e=>n.incr(e)),n.topKeys(e)}get sampleVariance(){return mapNotEmpty(this._samples,variance)}get sampleStdDev(){return mapNotEmpty(this._samples,stdDev)}get sampleAvg(){return mapNotEmpty(this._samples,avg)}get sampleSlope(){return slope(this._samples)??0}get samples(){return[...this._samples]}get sampleEma(){let e=this._samples.toA();if(e.length!==0)return sigFigs(ema(e),4)}get ema(){return this._ema}clear(){this._n=0,this._m=void 0,this._s=void 0,this._ema=0,this._samples.length=0}},CountingSet=class e{#e=new Map;static fromJSON(n){if(!(0,import_types.isMap)(n?.m))return;let r=new e;for(let[e,a]of n.m)gt0(a)&&r.incr(e,a);return r}merge(e){for(let[n,r]of e.entries())this.incr(n,r);return this}incr(e,n=1){let r=this.get(e)+n;return r===0?this.#e.delete(e):this.#e.set(e,r),r}get(e){return this.#e.get(e)??0}max(...e){return Math.max(...e.length===0?this.#e.values():e.map(e=>this.get(e)))}has(e){return this.#e.has(e)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}get countSum(){return sum2(this.#e.values())}keys(){return this.#e.keys()}keyAvg(){let e=new Average(0);for(let n of this.keys())if(isNumber(n))e.push(n);else return;return e.avg}entries(){return this.#e.entries()}toJSON(){return{m:this.#e}}toRecord(){let e={};for(let[n,r]of this.#e.entries())e[toS(n)]=r;return e}entriesByCountDesc(){let e=this.keyAvg();return sortBy([...this.entries()],([n,r])=>[-r,mapNumericOr(e,e=>Math.abs(n-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 tap(new Average(this.size),e=>[...this.#e.values()].forEach(n=>e.push(n)))}forEach(e){this.#e.forEach(e)}clear(){this.#e.clear()}sortedByKey(){let n=new e;for(let[e,r]of sortBy(this.#e.entries(),e=>e[0]))n.incr(e,r);return n}addAll(e){for(let[n,r]of e.entries())this.incr(n,r);return this}get toS(){return sort([...this.keys()]).map(e=>e+` `+this.get(e)).join(`
|
|
487
|
+
`)}valuesToA(e){let n=[];n.length=sum2(this.#e.values());let r=0;for(let[a,o]of this.#e.entries()){let s=e(a);n.fill(s,r,r+o),r+=o}return n}},Elapsed=class{constructor(e,n){this.l=e,this.listener=n}l;listener;ts=performance.now();elapsed(e){let n=performance.now(),r=roundMs(n-this.ts);this.ts=n,map(this.listener,n=>n(e,r)),r>2&&this.l.log(r>500?`warn`:r>100?`info`:`debug`,e,{elapsedMs:r})}};async function elapsedAsync(e){let n=performance.now(),r=await e;return{elapsedMs:roundMs(performance.now()-n),result:r}}var import_node_util8=require("node:util");function isLandmarkJSON(e){return isObject(e)&&isNumber(e.x)&&isNumber(e.y)&&isNumber(e.s)&&isNumber(e.n)}var DurationEstimator=class e{#e=[];#t;#n;constructor(e=15,n=.2){this.#t=e,this.#n=n}estimate(e,n){return this.#i(e,n)}push(e,n){gt0(e)&>0(n)&&this.#r(e,n)}#r(e,n){let r=this.#c(e),a=e*this.#n;if(r!=null&&Math.abs(r.x-e)<a){let a=r.n,o=a+1,s=r.y;r.x=(r.x*a+e)/o,r.y=s+(n-s)/o,r.s+=((n-r.y)*(n-s)-r.s)/o,r.n=o}else for(this.#e.push({x:e,y:n,s:0,n:1}),this.#e.sort((e,n)=>e.x-n.x);this.#e.length>this.#t;)this.#l()}#i(e,n){let r=this.#e;if(r.length===0)return;if(r.length===1)return this.#a(r[0],n);let a=r.findIndex(n=>n.x>=e);if(a===0)return this.#s(r[0],r[1],e,n);if(a===-1){let a=r.length,o=r[a-2],s=r[a-1],c=s.x-o.x,l=c>0?Math.max(0,(s.y-o.y)/c):0;return roundMs(this.#a(s,n)+l*(e-s.x))}return this.#s(r[a-1],r[a],e,n)}#a(e,n){let r=Math.sqrt(Math.max(0,e.s));switch(n){case`p16`:return Math.max(0,e.y-r);case`p50`:return e.y;case`p69`:return e.y+.5*r;case`p84`:return e.y+r;case`p98`:return e.y+2*r;case`p99`:return e.y+3*r}}get landmarkCount(){return this.#e.length}get sampleCount(){return this.#e.reduce((e,n)=>e+n.n,0)}get n(){return this.sampleCount}get sum(){return this.#e.reduce((e,n)=>e+n.y*n.n,0)}get mean(){let e=this.sampleCount;if(e!==0)return this.sum/e}get variance(){let e=this.#e;if(e.length===0)return;if(e.length===1)return e[0].s;let n=e[0].y,r=e[0].s,a=e[0].n;for(let o=1;o<e.length;o++){let s=e[o],c=a+s.n,l=s.y-n,u=r*a+s.s*s.n+l*l*(a*s.n/c);n+=l*(s.n/c),r=u/c,a=c}return r}get stdDev(){let e=this.variance;return e==null?void 0:Math.sqrt(e)}get min(){if(this.#e.length!==0)return Math.min(...this.#e.map(e=>e.y))}get max(){if(this.#e.length!==0)return Math.max(...this.#e.map(e=>e.y))}get p84(){let e=this.mean,n=this.stdDev;if(e!=null&&n!=null)return e+n}get p16(){let e=this.mean,n=this.stdDev;if(e!=null&&n!=null)return Math.max(0,e-n)}get p50(){return this.mean}stats(){let e={n:this.sampleCount};return this.#e.length>0&&(e.mean=this.mean,e.sd=this.stdDev,e.min=this.min,e.max=this.max,e.sum=this.sum,e.p16=this.p16,e.p50=this.p50,e.p84=this.p84),e}clear(){this.#e=[]}toJSON(){return{maxLandmarks:this.#t,mergeRadiusPct:this.#n,landmarks:this.#e.map(e=>({x:e.x,y:e.y,s:e.s,n:e.n}))}}static fromJSON(n){if(!isObject(n))return;let r=new e(toGt0(n?.maxLandmarks),toGt0f(n?.mergeRadiusPct));if(isObject(n)&&Array.isArray(n.landmarks)){for(let e of n.landmarks){if(!isLandmarkJSON(e))continue;let n=toFloat(e?.x),a=toFloat(e?.y),o=toFloat(e?.s)??0,s=toInt(e?.n)??1;n!=null&&a!=null&&n>0&&a>0&&s>0&&r.#e.push({x:n,y:a,s:Math.max(0,o),n:s})}r.#e.sort((e,n)=>e.x-n.x)}return r}merge(e){if(e==null)return this;for(let n of e.#e){let e=this.#c(n.x),r=n.x*this.#n;e!=null&&Math.abs(e.x-n.x)<r?this.#o(e,n):(this.#e.push({...n}),this.#e.sort((e,n)=>e.x-n.x))}for(;this.#e.length>this.#t;)this.#l();return this}#o(e,n){let r=e.n+n.n,a=n.y-e.y,o=e.s*e.n+n.s*n.n+a*a*(e.n*n.n/r);e.x=(e.x*e.n+n.x*n.n)/r,e.y+=a*(n.n/r),e.s=o/r,e.n=r}[import_node_util8.inspect.custom](){return{landmarkCount:this.landmarkCount,sampleCount:this.sampleCount,stats:this.stats(),landmarks:this.#e.map(e=>({x:e.x,y:e.y,s:e.s,p50:this.#a(e,`p50`),p84:this.#a(e,`p84`),n:e.n}))}}#s(e,n,r,a){let o=this.#a(e,a),s=this.#a(n,a);return e.x===n.x?roundMs((o*e.n+s*n.n)/(e.n+n.n)):roundMs(o+clamp(0,1,(r-e.x)/(n.x-e.x))*(s-o))}#c(e){if(this.#e.length===0)return;let n,r=1/0;for(let a of this.#e){let o=Math.abs(a.x-e);o<r&&(r=o,n=a)}return n}#l(){if(this.#e.length<2)return;let e=0,n=1/0;for(let r=0;r<this.#e.length-1;r++){let a=this.#e[r+1].x-this.#e[r].x;a<n&&(n=a,e=r)}let r=this.#e[e],a=this.#e[e+1],o=r.n+a.n,s=a.y-r.y,c=r.s*r.n+a.s*a.n+s*s*(r.n*a.n/o),l={x:(r.x*r.n+a.x*a.n)/o,y:r.y+s*(a.n/o),s:c/o,n:o};this.#e.splice(e,2,l)}},EndableWrapper=class{constructor(e,n,r=EndableRanks.first,a){this.endTimeoutMs=a,this.setName(e),n!=null&&this.onEnds.push(n),addEndable(r,this)}endTimeoutMs;#e;logger;#t=new TypedEventEmitterImpl;onEnds=[];#n=defer(()=>new Latch);#r=!1;#i=!1;setName(e){this.#e=e,this.logger=mkLogger(e)}get name(){return this.#e}get endStarted(){return this.#r}get endEnded(){return this.#i}get ended(){return this.endStarted}on=this.#t.on.bind(this.#t);off=this.#t.off.bind(this.#t);listenerCount=this.#t.listenerCount.bind(this.#t);end=defer(async()=>{this.#r=!0,await this.#t.emit(`end`),this.logger.abortable.abort(ending()?`service ending`:`onEnd()`);for(let e of this.onEnds)try{await thenOrTimeoutError(e(),this.endTimeoutMs??DefaultEndTimeoutMs)}catch(e){this.logger.warn(`onEnd() error`,e)}this.#n.prior()?.resolve(),this.#t.clear(),this.#i=!0});awaitEnd(){return this.#n()}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}},MinMs=15,PromiseTimer=class e{static fromJSON(n){let r=new e(n?.errors,n?.times);return n?.durationEstimators!=null&&r.loadDurationEstimators(n.durationEstimators),r}static instance=lazy2(()=>{let n=new e;return new EndableWrapper(`PromiseTimer`,()=>{let e=mkLogger(`async.PromiseTimer`);mapCompactObj(n.report(),n=>e.info(`timings:`,n)),n.hasErrors()&&e.info(`error counts:`,n.errorCounts())},EndableRanks.stats),isTest()&&ee().on(`clearCache`,()=>n.clear()),n});#e;#t;#n;#r=new import_node_async_hooks.AsyncLocalStorage;#i=new import_node_async_hooks.AsyncLocalStorage;constructor(e,n){this.#e=e??new CountingSet,this.#t=n??new Map,this.#n=new Map}clear(){this.#e.clear(),this.#t.clear(),this.#n.clear()}collectTimings(e,n){return this.#i.run(e,n)}time(e){return this.#a(e,!1)}async#a(e,n){let{name:r,p:a,post:o,timeoutMs:s,meta:c}=e,l={ms:0},u=this.#r.getStore(),d=!1,f=performance.now(),h=clamp(10*secondMs,minuteMs,Math.round(this.#t.get(r)?.p98??(s??minuteMs)/4)),_=setUnrefTimeout(()=>{mkLogger(`time(`+r+`)`).info(`unsettled`,{...c,elapsedMs:roundMs(performance.now()-f),timeoutMs:s,expectedMs:h})},h);try{let e=await this.#r.run(l,async()=>{let e=await a;return thenOrTimeoutError(isFunction(e)?e():e,s)}),c=roundMs(performance.now()-f-(n?l.ms:0));return o?.(e,c),this.push(r,c),d=!0,e}catch(e){throw this.pushError(r),o?.(toError(e),roundMs(performance.now()-f)),e}finally{clearTimeout(_),u!=null&&(n||!d)&&(u.ms+=l.ms)}}timeExcludingNested({name:e,thunk:n,meta:r}){return this.#a({name:e,p:n,meta:r},!0)}async excludeWaitFromEnclosingTimer(e){let n=this.#r.getStore();if(n==null)return e();let r=performance.now();try{return await this.#r.run({ms:0},e)}finally{n.ms+=performance.now()-r}}get entriesBySumDesc(){return sortBy([...this.#t.entries()],([,e])=>-e.sum)}statsWithName(e){return this.#t.get(e)?.stats()}statsWithPrefix(e){let n=this.entriesBySumDesc.filter(([n])=>n.startsWith(e)),r=n.reduce((e,n)=>Average.merge(n[1],e),new Average),a=n.map(([e,n])=>[e,n.stats()]);return fromEntries([[`merged`,r.stats()],...a])}mkElapsed(e){return new Elapsed(e,(e,n)=>this.push(e,n))}push(e,n,r){if(n<MinMs)return;n=roundMs(n),this.#i.getStore()?.samples.push({name:e,elapsedMs:n,sizeBytes:r});let a=this.#r.getStore();a!=null&&(a.ms+=n),r!=null&&r>0?getOrSet(this.#n,e,()=>new DurationEstimator).push(r,n):getOrSet(this.#t,e,()=>new Average).push(n)}estimate(e,n,r=`p50`){if(n!=null&&n>0){let a=this.#n.get(e);if(a!=null)return a.estimate(n,r)}return this.#t.get(e)?.p(r)}getDurationEstimator(e){return this.#n.get(e)}get totalDurationEstimatorSampleCount(){let e=0;for(let n of this.#n.values())e+=n.sampleCount;return e}getDurationEstimators(){return this.#n}loadDurationEstimators(e){let n=e instanceof Map?e.entries():Object.entries(e??{});for(let[e,r]of n){let n=r instanceof DurationEstimator?r:DurationEstimator.fromJSON(r);if(n==null)continue;let a=this.#n.get(e);a==null?this.#n.set(e,n):a.merge(n)}}pushError(e){this.#e.incr(e);let n=this.#i.getStore();n!=null&&(n.errors[e]=(n.errors[e]??0)+1)}weightedAvg(e){return this.#t.get(e)?.sampleEma}hasErrors(){return this.#e.size>0}errorCounts(){return fromEntries(this.#e.top(10))}callCounts(){return[...this.#t.entries()].reduce((e,[n,r])=>({...e,[n]:r.n}),{})}weightedAvgs(){return compactValues([...this.#t.entries()].reduce((e,[n,r])=>({...e,[n]:mapFinite(r.sampleEma,round)}),{}))}toJSON(){let e={};for(let[n,r]of this.#n)e[n]=r.toJSON();return{errors:this.#e,times:this.#t,durationEstimators:e}}report(){return this.entriesBySumDesc.reduce((e,[n,r])=>({...e,[n]:{...omit(r.stats(),`sum`),sumSec:sigFigs(r.sum/secondMs,3)}}),{})}merge(e,n){this.#e.merge(e.#e);let r=n??``;for(let[n,a]of e.#t.entries())getOrSet(this.#t,r+n,()=>new Average).merge(a);for(let[n,a]of e.#n.entries()){let e=r+n,o=this.#n.get(e);if(o!=null)o.merge(a);else{let n=DurationEstimator.fromJSON(a.toJSON());n!=null&&this.#n.set(e,n)}}}};function time(e){return PromiseTimer.instance().time(e)}function timeExcludingNested(e){return PromiseTimer.instance().timeExcludingNested(e)}function excludeWaitFromEnclosingTimer(e){return PromiseTimer.instance().excludeWaitFromEnclosingTimer(e)}function timeSync({name:e,t:n}){let r=performance.now(),a=n();return pushTime({name:e,elapsedMs:roundMs(performance.now()-r)}),a}function pushTime({name:e,elapsedMs:n}){PromiseTimer.instance().push(e,n)}function timedLazy({name:e,thunk:n,ttlMs:r,meta:a}){return lazy2(async()=>timeExcludingNested({name:tot(e),thunk:n,meta:a}),r)}var logger7=defer(()=>mkLogger(magenta(`Exit`))),exitStatus,onFatalHandlers=[],emitTimingsOnExit=defer(()=>{Settings2.emitTimingsOnExit.valueOrDefault&&(isInfoService()?console.dir(PromiseTimer.instance().report()):stdoutWrite(stringify(PromiseTimer.instance())))});async function exit(e){exitStatus??=e.status,isMainService()&&sdNotifyStopping(),logger7().log(e.status===0?LogLevels.debug:LogLevels.warn,`exit()`,{...e,ending:ending()});let n=ending();setEnding(!0),emitTimingsOnExit();let r=toWrappedError(e.error,{message:e.reason,errno:e.status});if(r.errno!==0||r.fatal===!0||e.status!==0){let n=toNotBlank(e?.reason)??r.toString();for(let e of onFatalHandlers)await e(n)}n||(await endEndables(),import_node_process13.default.exit(e.status))}var exitOnStdStream=defer(()=>{for(let e of[`stdin`,`stdout`,`stderr`])for(let n of[`close`,`error`,`disconnect`,`end`])import_node_process13.default[e].on(n,r=>{exit({reason:`${e}:${n}`,status:0,error:r})})}),import_commander2=require("commander"),import_promises38=require("node:fs/promises"),import_node_path74=require("node:path"),import_consumers=require("node:stream/consumers"),import_commander=require("commander");function setServiceName(e){isMainService(e)&&(e=ServiceNames.main);let n=serviceName.prior();n!==e&&(!isTest()&&n!=null&&n!==e&&console.error(`Don't set service name twice`,{prior:n,new:e}),serviceName.set(e))}var import_node_os13=require("node:os"),import_node_path44=require("node:path"),import_node_path17=require("node:path"),import_node_fs10=require("node:fs"),import_promises4=require("node:fs/promises"),import_node_path15=__toESM(require("node:path"));async function retryOnReject_(e,n){let r=gt0(n.timeoutMs)?()=>thenOrTimeoutError(e(),n.timeoutMs):e,a=n.maxRetries??0;if(a<=0)return r();let o=n.onRetryWaitUntil??(e=>delay(Math.max(250,(n.retryDelay??250)*(e??1)),!1)),s=0,c=async()=>{try{return await r()}catch(e){let r=toError(e);if(!1===n.errorIsRetriable?.(r)||s>=a)throw r;return s++,await o(s),c()}};return c()}function isUNC(e){return e==null||typeof e!=`string`||!isWin?!1:/^\\\\[^\\]+\\[^\\]+/.test(e)}var import_node_path14=__toESM(require("node:path")),import_node_fs9=__toESM(require("node:fs")),import_node_path13=__toESM(require("node:path")),import_promises2=require("node:fs/promises"),import_node_path12=__toESM(require("node:path")),import_node_process14=require("node:process"),MingwPathRE=/^(?:\/cygdrive)?\/(?<drive>[a-z])\/(?<path>.*)$/i;function resolve2(...e){let n=compact(e);if(isEmpty(n))return(0,import_node_process14.cwd)();if(!isWin||isUNC(n.join(`\\`)))return import_node_path12.default.resolve(...n);let r=MingwPathRE.exec(n.join(`/`))?.groups;return r==null?import_node_path12.default.resolve(...n.map(upcaseDriveLetters)):import_node_path12.default.resolve(upcaseDriveLetters(r.drive+`:\\`+r.path))}async function resolvePathSymlinks(e){try{return await(0,import_promises2.realpath)(e)}catch{let n=import_node_path12.default.dirname(e);if(n===e)return e;let r=await resolvePathSymlinks(n);return import_node_path12.default.join(r,import_node_path12.default.basename(e))}}function macSymlinkAltPath(e){if(!isMac)return;let n=`/private`;for(let r of[`/var`,`/tmp`,`/etc`]){let a=n+r;if(e.startsWith(a+`/`)||e===a)return e.slice(8);if(e.startsWith(r+`/`)||e===r)return n+e}}var execDir=defer(()=>import_node_path12.default.dirname(process.execPath)),DriveRE=/^(?<drive>[A-Z]:)(?<path>.*)$/i;function upcaseDriveLetters(e){if(!isWin)return e;let n=DriveRE.exec(e)?.groups;return n==null?e:n.drive.toUpperCase()+ensurePrefix((n.path??``).replace(/\//g,import_node_path12.default.sep),import_node_path12.default.sep)}function isSimpleDirent(e){return e!=null&¬Blank(e.basename)&&isBoolean(e.isFile)&&isBoolean(e.isDirectory)}function isSimpleFile(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.nativePath==`string`&&typeof e.base==`string`&&typeof e.ext==`string`&&typeof e.base==`string`&&typeof e.dir==`string`&&typeof e.isFile==`function`}function toNativePath(e){try{return e==null?void 0:toNativePath_(e)}catch{return}}function toNativePath_(e){if(e==null)throw TypeError(`toNativePath(null)`);if(blank(e))throw TypeError(`toNativePath(blank)`);if(isString(e))return resolve2(e);if(e instanceof import_node_fs9.Dirent){let n=e.parentPath;return(0,import_node_path13.join)(n,e.name)}if(blank(e.nativePath))throw TypeError(`toNativePath(): blank nativePath: ${stringify(e)}`);return e.nativePath}function basename2(e){return e instanceof import_node_fs9.default.Dirent?e.name:isSimpleFile(e)?e.base:import_node_path13.default.basename(String(e))}function nameWithoutExt(e){return parseNativePath(basename2(e)).name}function dirname2(e){return isSimpleFile(e)?e.dir:import_node_path13.default.dirname(toNativePath_(e))}function toPathnames(e){if(!blank(e)){if(!isString(e)&&`pathnames`in e){let n=e.pathnames;if(Array.isArray(n))return n}return toNativePath(e)?.split(import_node_path14.default.sep).filter(e=>e!=null&&e!==``)}}function pathDepth(e){let n=toPathnames(e);return n==null?void 0:n.length-+!!isWin}var import_promises3=__toESM(require("node:fs/promises")),logger8=lazy2(()=>mkLogger(`fs.Stat`)),RetriableFsCodes=new Set([`EAGAIN`,`EALREADY`,`EBUSY`,`ECONNABORTED`,`ECONNRESET`,`ECONNREFUSED`,`EHOSTDOWN`,`EHOSTUNREACH`,`EINPROGRESS`,`EINTR`,`EMFILE`,`ENETDOWN`,`ENETRESET`,`ENETUNREACH`,`ESTALE`,`ETIMEDOUT`,`EWOULDBLOCK`]);function fsOperation_(e,n){return retryOnReject_(e,{timeoutMs:FilesystemSettings.statTimeoutMs.valueOrDefault,maxRetries:FilesystemSettings.statRetries.valueOrDefault,retryDelay:secondMs,errorIsRetriable:e=>RetriableFsCodes.has(errorCode(e)??``),...n})}function stat_(e){return blank(e)?logger8().throw(`stat_() for blank path`,{nativePath:e,retriable:!1,fatal:!1}):fsOperation_(()=>import_promises3.default.stat(e))}function statMaybe(e,n=LogLevels.debug){return blank(e)?void 0:stat_(e).catch(r=>{logger8().log(n,`stat() failed`,{nativePath:e,error:r})})}async function exists(e,n=LogLevels.info){return await statMaybe(e,n)!=null}async function isEmptyFile(e,n){let r=await statMaybe(e,n?.logLevel??LogLevels.trace);return r==null||(n?.emptyIsNew??!0)?isEmptyStats(r):!1}async function isNonEmptyFile(e,n=0){let r=await statMaybe(e);return r!=null&&r.isFile()&&r.size>=n}async function isDirectory(e){return!0===(await statMaybe(e))?.isDirectory()}async function isReadableDirectory(e,n=LogLevels.trace){let r=await statMaybe(e,n);return r!=null&&r.isDirectory()&&await canAccess(e,{r:!0,x:!0})}async function readWriteableDirectoryError(e,n=LogLevels.trace){if(blank(e))return errnoError(`ENOENT`,`pathname is blank`);let r;try{r=await stat_(e)}catch(r){return logger8().log(n,`stat() failed`,{nativePath:e,error:r}),r}return r.isDirectory()?statRWXError(r,e):errnoError(`ENOTDIR`,`is not a directory`)}async function isReadWriteableDirectory(e,n=LogLevels.trace){return await readWriteableDirectoryError(e,n)==null}async function mtimeMs(e){return(await statMaybe(e))?.mtimeMs}var MtimeGranularityMs=2*secondMs;function isRacyMtime(e,n){return Math.abs(n-e)<MtimeGranularityMs}function statTimes(e){return uniq([e.birthtimeMs,e.mtimeMs].filter(e=>e!=null&&e!==0))}function isNativePath(e){return e.includes(import_node_path15.default.sep)}function isHiddenBasename(e){return(isSimpleFile(e)?e.base:import_node_path15.default.basename(resolve2(e))).startsWith(`.`)}function resolveMaybe(...e){return e.some(blank)?void 0:resolve2(...e)}function parsePosixPath(e){return parseNativePath(posix2native(e))}function extname(e){return parseNativePath(e).ext}function dirname_(e){return import_node_path15.default.dirname(toNativePath_(e))}function pathIsRoot(e){let n=toNativePath(e);return!blank(n)&&n===import_node_path15.default.dirname(n)}var CompressedExtRE=/^(?<path>.*?)(?<ext2>\.(?:gz|z|7z|xz|bz2|br))?$/i;function parseNativePath(e){let n=CompressedExtRE.exec(e)?.groups,r=n?.ext2??``,a=import_node_path15.default.parse(n?.path??e);return{...a,ext:(a.ext??``)+r,base:(a.base??``)+r}}function parentBasename(e){let n=import_node_path15.default.parse(toNativePath_(e));return(n.root===n.dir?n.root:splitLast(n.dir,import_node_path15.default.sep)).normalize()}function grandParentBasename(e){return parentBasename(import_node_path15.default.parse(toNativePath_(e)).dir)}function _eqlPath(e,n,r){if(n==null||r==null)return!1;let a=e(n),o=e(r);return a==null||o==null?!1:equalsIgnoreCase(a,o)}function eqlNameWithoutExt(e,n){return _eqlPath(nameWithoutExt,e,n)}function eqlPath(e,n){return _eqlPath(toNativePath_,e,n)}function posixPathFrom(e,n){let r=toNativePath_(e),a=toNativePath_(n);if(blank(r)||blank(a))throw Error(`posixPathFrom empty args `+stringify({parent:e,child:n}));return r===a?``:stripPrefix(native2posix(a).normalize(),ensureSuffix(native2posix(r),`/`).normalize()).normalize()}function ellipsizePath({p:e,maxLength:n}){let r=toNativePath_(e);if(r.length<=n)return r;let a=toPathnames(e)??[],o=a.pop(),s=[],c=[o];for(;a.length>0;)if(s.length<c.length){if(s.push(a.shift()),joinNativePath([...s,...c]).length>=n){a.unshift(s.pop());break}}else if(c.unshift(a.pop()),joinNativePath([...s,...c]).length>=n){a.push(c.shift());break}return a.length>0&&s.push(`…`),joinNativePath([...s,...c])}function posixPathFromGrandparent(e){return toPathnames(e)?.slice(-3).join(`/`)??``}var DriveRE2=/^[A-Z]:[\\/]/i;function isAbsolute2(e){return isPosix&&e.startsWith(`/`)||isWin&&(isUNC(e)||DriveRE2.test(e))}async function mkdirp_(e){try{if(pathIsRoot(e)||await isReadableDirectory(e))return;await(0,import_promises4.mkdir)(e,{recursive:!0})}catch(n){if(await isReadableDirectory(e))return;throw n}}function mkdirpSync_(e,n){try{if(pathIsRoot(e)||isReadWriteableDirectorySync(e))return;(0,import_node_fs10.mkdirSync)(e,{recursive:!0,...n})}catch(n){if(isReadWriteableDirectorySync(e))return;throw n}}async function moveWithOverwrite_(e,n){try{await(0,import_promises4.rename)(e,n)}catch(r){if(r?.code===`EXDEV`){let r=await(0,import_promises4.stat)(e);await(0,import_promises4.copyFile)(e,n),await(0,import_promises4.chmod)(n,r.mode),await(0,import_promises4.unlink)(e)}else throw r}}async function move_(e,n){return retryOnReject_(()=>moveWithOverwrite_(e,n),{errorIsRetriable:isRetriableError,maxRetries:5,retryDelay:250})}function splitNativePath(e){return toNativePath_(e).split(import_node_path15.default.sep).filter(e=>e!=null&&e!==``)}function joinNativePath(e){return ensurePrefix(compactBlanks(e).join(import_node_path15.default.sep),isWin?``:import_node_path15.default.sep)}async function ensureFile_(e){await mkdirp_(dirname_(e)),await(0,import_promises4.appendFile)(e,``)}function ensureFileSync_(e){mkdirpSync_(dirname_(e)),(0,import_node_fs10.appendFileSync)(e,``)}var import_promises5=require("node:fs/promises");async function readFilePart_({nativePath:e,position:n=0,length:r}){let a;try{let o=r??(await(0,import_promises5.stat)(e)).size-n,s=Buffer.alloc(o);return a=await(0,import_promises5.open)(e,`r`),await a.read(s,0,o,n)}finally{await a?.close()}}var import_node_fs11=require("node:fs"),import_promises6=require("node:fs/promises"),import_node_path16=__toESM(require("node:path"));async function writeFile_(e,n){let r=import_node_path16.default.dirname(e);await mkdirp_(r),await(0,import_promises6.writeFile)(e,n,{flush:!0}),ee().emit(`fileChanged`,r)}async function writeText_(e,...n){return writeFile_(e,crlf(ensureSuffix(n.map(toS).join(`
|
|
488
|
+
`),`
|
|
489
|
+
`)))}async function writeTextfile_(e,...n){await writeFile_(e,crlf(...wrap(n)))}function writeFileSync_(e,n){let r=import_node_path16.default.dirname(e);mkdirpSync_(r);let a=(0,import_node_fs11.openSync)(e,`w`);try{typeof n==`string`?(0,import_node_fs11.writeSync)(a,n):(0,import_node_fs11.writeSync)(a,n,0,n.length),(0,import_node_fs11.fsyncSync)(a)}finally{(0,import_node_fs11.closeSync)(a)}ee().emitSync(`fileChanged`,r)}function writeTextSync_(e,...n){return writeFileSync_(e,crlf(ensureSuffix(n.map(toS).join(`
|
|
490
|
+
`),`
|
|
491
|
+
`)))}var CACHEDIR_TAG=`CACHEDIR.TAG`,CACHEDIR_TAG_CONTENT=`Signature: 8a477f597d28d172789f06886806bc55`,logger9=lazy2(()=>mkLogger(`fs.CachedirTag`));async function isCachedirTagDirectory(e){return isCachedirTagFile((0,import_node_path17.join)(toNativePath_(e),CACHEDIR_TAG))}async function isCachedirTagFile(e){if(basename2(e)!==CACHEDIR_TAG)return!1;try{return(await readFilePart_({nativePath:toNativePath_(e),position:0,length:CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString()===CACHEDIR_TAG_CONTENT}catch(n){return logger9().trace(`isCachedirTagFile(): failed to read `+e,n),!1}}async function writeCachedirTag_(e){let n=toNativePath_(e);await isCachedirTagDirectory(n)||(await mkdirp_(n),await writeTextfile_(joinNativePath([n,CACHEDIR_TAG]),CACHEDIR_TAG_CONTENT,`# This file marks this directory hierarchy as cached content.`,`# It can be safely deleted if PhotoStructure is not currently running.`,`#`,`# Created by https://photostructure.com `+version,`#`,`# See https://bford.info/cachedir/ for details about this file`))}var import_node_path18=__toESM(require("node:path"));async function mkNoMedia_(e){let n=import_node_path18.default.join(toNativePath_(e),`.NoMedia`);if(!await exists(n,LogLevels.trace))return writeTextfile_(n,`This directory's contents are excluded from PhotoStructure libraries.`,``,`See https://photostructure.com/nomedia/ for details.`)}var import_node_fs23=require("node:fs"),import_node_os12=require("node:os"),import_node_path40=require("node:path"),import_node_fs12=require("node:fs"),import_node_path19=require("node:path");function ancestors(e){return[...ancestorG(e)]}function*ancestorG(e){if(!blank(e))for(;e!==(0,import_node_path19.dirname)(e);)e=(0,import_node_path19.dirname)(e),yield e}function childrenSync(e){try{return(0,import_node_fs12.readdirSync)(e)}catch{return[]}}function hasChildrenSync(e,n){if(blank(e))return!1;let r=childrenSync(e);return n.every(e=>r.includes(e))}function ancestorWithChildren(e,n){return ancestors(e).find(e=>hasChildrenSync(e,n))}var RepoRootMarker=`.__phstr_repo_root__`,repoRoot=defer(()=>{let e=ancestorWithChildren(__dirname,[RepoRootMarker]);if(e==null)throw Error(`Couldn't find the PhotoStructure project root directory`);return e}),rmTestTmpfiles=lazy2(()=>!getDevEnvFlag(`PS_SKIP_CLEANUP`)),import_node_fs22=__toESM(require("node:fs")),import_promises19=__toESM(require("node:fs/promises")),import_node_path39=__toESM(require("node:path")),import_promises20=require("node:stream/promises"),import_node_os9=__toESM(require("node:os"));function isMissingPasswdEntry(e){if(errorCode(e)!==`ERR_SYSTEM_ERROR`)return!1;let n=e.info;return n?.code===`ENOENT`&&n.syscall===`uv_os_get_passwd`}function passwdEntry(){try{return import_node_os9.default.userInfo()}catch(e){if(isMissingPasswdEntry(e))return;throw e}}var import_node_process15=__toESM(require("node:process")),userids=lazy2(()=>uniq([import_node_process15.default.geteuid?.(),import_node_process15.default.getuid?.(),passwdEntry()?.uid]).filter(gte0)),userid=lazy2(()=>userids()[0]),import_node_child_process4=__toESM(require("node:child_process")),import_node_process23=__toESM(require("node:process")),import_node_os11=__toESM(require("node:os")),import_node_path30=__toESM(require("node:path")),import_batch_cluster3=require("batch-cluster"),import_exiftool_vendored=require("exiftool-vendored"),import_node_process19=__toESM(require("node:process")),timeoutHandler=e=>null;function onTimeout({soft:e}={}){timeoutHandler(e)}var import_batch_cluster2=require("batch-cluster"),import_node_child_process3=__toESM(require("node:child_process")),import_node_process18=__toESM(require("node:process")),import_node_timers3=__toESM(require("node:timers")),import_node_util9=__toESM(require("node:util"));async function thenCollect(e,n){let r=[];for(let a of toA(await e))if(a!=null){let e=await a;if(e!=null){let a=await n(e);a!=null&&r.push(a)}}return r}function isPromiseLike(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}function isPromise(e){return isPromiseLike(e)&&typeof e.catch==`function`&&typeof e.finally==`function`}var InvalidStateError=class extends Error{name=`InvalidStateError`},TimeoutName=`TIMEOUT`,logger10=defer(()=>mkLogger(`async.Deferred`)),Deferred2=class e{constructor(n,r){this.name=n,this.id=e.#e++,this.promise=new Promise((e,n)=>{this.#i=e,this.#a=n}),this.payload=r?.payload,this.serialIds=r?.serialIds??[],this.#l=r?.timer,this.#u=r?.timerName,this.#d=r?.fileSize}name;static observe(n){return new e(`.observe()`).observe(n)}static async*toAsyncIterable(n,r){let a=compact([...n]).reverse(),o=gt0(r)?new e(TimeoutName).setTimeout(r):void 0;for(o!=null&&a.push(o);;){for(let e=a.length-1;e>=0;e--){let n=a[e];if(n.isSettled){if(n.name===TimeoutName){logger10().warn(`toAsyncIterable(): timeout`,{timeoutMs:r,pending:a.map(e=>e.name)});return}a.splice(e,1),yield n.value}}if(a.every(e=>e.name===TimeoutName))break;try{await Promise.race(a)}catch{}}o?.clearTimeout()}static#e=0;static resolve(n,r){return new e(`.resolved()`,r).resolve(n)}id;payload;serialIds;startedAt=Date.now();observeStartedAt;#t;#n=PromiseStates.pending;#r;promise;#i;#a;#o;#s;#c;#l;#u;#d;get logger(){return this.#c??mkLogger(`async.Deferred(`+this.name+`)`)}eql(n){return n instanceof e&&n.id===this.id}toLogJSON(){return{name:this.name,state:this.#n,value:this.value,serialIds:toNotBlank(this.serialIds),payload:this.payload,elapsedMs:this.elapsedMs,settledMs:this.settledMs}}[import_node_util9.default.inspect.custom](){return this.toLogJSON()}get settledAt(){return this.#t}get elapsedMs(){return(this.#t??Date.now())-this.startedAt}get timerName(){return this.#u??this.name}get[Symbol.toStringTag](){return`async.Deferred(`+this.name+`)`}#f(e,n){if(this.observeStartedAt!=null)throw new InvalidStateError(`observe() called multiple times`);this.observeStartedAt=this.startedAt=Date.now();try{let r=isFunction(e)?e():e;isPromise(r)?r.then(e=>this.maybeResolve(e)).catch(e=>{n?(this.logger.warn(`observeQuietly.reject()`,e),this.maybeResolve(void 0)):this.maybeReject(e)}):this.maybeResolve(r)}catch(e){n?(this.logger.warn(`observeQuietly.reject()`,e),this.maybeResolve(void 0)):this.maybeReject(e)}return this}observeQuietly(e){return this.#f(e,!0)}observe(e){return this.#f(e,!1)}clearTimeout(){return this.#s!=null&&(import_node_timers3.default.clearTimeout(this.#s),this.#s=void 0,!0)}setTimeout(e){this.clearTimeout();let n=new TimeoutError(`Timeout `+this.name);return gt0(e)&&(this.#s=import_node_timers3.default.setTimeout(()=>{this.isPending&&(this.reject(n),onTimeout())},Math.ceil(e)),this.#s.unref()),this}get state(){return this.#n}get isPending(){return this.#n===PromiseStates.pending}get isObserved(){return this.observeStartedAt!=null}get value(){return this.isResolved?this.#r:void 0}get error(){return this.#o}get isSettled(){return this.#n!==PromiseStates.pending}get isResolved(){return this.#n===PromiseStates.resolved}get isRejected(){return this.#n===PromiseStates.rejected}get settledMs(){return this.#t==null?void 0:this.#t-this.startedAt}resolve(e){return this.#p(()=>{this.#n=PromiseStates.resolved,this.#r=e,this.#i(e)})}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){let n=isIgnorableError(e)===!0||isDoNotSendError(e)===!0;this.logger.log(n?`info`:`warn`,`.reject()`,e);let r=asError(e);return this.#p(()=>{this.#o=r,this.#n=PromiseStates.rejected,this.#a(r)})}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch(()=>void 0),this}then(e,n){return this.promise.then(e,n)}catch(e){return this.promise.catch(n=>e(n))}#p(e){if(this.#n===PromiseStates.pending){map(this.#s,import_node_timers3.default.clearTimeout),this.#t=Date.now();let n=this.#t-this.startedAt;this.#l?.push(this.timerName,n,this.#d),e(),this.isResolved&&n>5e3&&this.logger.info(`Completed in `+n+`ms`)}else this.logger.warn(`settled multiple times (already `+this.state+`)`,{value:this.#r});return this}};function rateLimited({f:e,minCallDelayMs:n,timeoutMs:r=void 0,nullOnBusy:a,name:o}){let s=!1,c=0,l,u,d=[];function f(){return s||c>performance.now()}function h(){if(u!=null){let e=u;u=void 0,y(...e)}}async function _(...a){s=!0,c=performance.now()+max_(tot(n),r);let u=l=new Deferred2(o);gt0(r)&&u.setTimeout(r);try{u.resolve(await e(...a))}catch(e){u.reject(new WrappedError(`RateLimited(`+o+`) failed`,{cause:e}))}finally{s=!1,c=performance.now()+tot(n),setUnrefTimeout(h,tot(n)+1),d.forEach(e=>e.resolve()),d.length=0}return u.promise}let y=(...e)=>{if(f()){if(a===!0)return null;let n=l?.promise;return u=e,delay(1).then(()=>n)}return _(...e)};return y.clear=()=>{u=void 0},y.donePromise=()=>{if(!s)return Promise.resolve();let e=new Latch;return d.push(e),e},y.force=async(...e)=>(u=void 0,s&&await y.donePromise(),_(...e)),y.isRateLimited=()=>f(),y.status=()=>({running:s,needToDelay:c>performance.now(),minNextDelayMs:Math.max(0,performance.now()-c)}),y.minCallDelayMs=()=>tot(n),y.setMinCallDelayMs=e=>{n=e},y}var import_node_timers4=require("node:timers"),EndableInterval=class extends EndableWrapper{constructor(e){super(e.name,()=>this.#r(),e.rank??EndableRanks.first,e.endTimeoutMs),this.opts=e,e.onEnd!=null&&this.onEnds.push(e.onEnd),this._setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}opts;#e;#t;#n=!1;#r(){map(this.#e,import_node_timers4.clearInterval),this.#e=void 0,map(this.#t,import_node_timers4.clearTimeout),this.#t=void 0}hasTimer(){return this.#e!=null}hasTimeout(){return this.#t!=null}get timingOpts(){return pick(this.opts,`intervalMs`,`initialDelayMs`)}#i=()=>{!ending()&&!this.ended&&this.opts.callback()};get#a(){return!ending()&&!this.ended}pauseInterval(){this.#n||(this.#n=!0,this.#r())}resumeInterval(){this.#n&&(this.#n=!1,this.#o())}setIntervalMs=e=>this._setIntervalMs(e);_setIntervalMs(e,n,r=!1){return ending()||this.ended||(e=toInt(e)??0,n=toInt(n)??0,gt0(e)||(n=0),!r&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===n)?!1:(this.opts.intervalMs=e,this.opts.initialDelayMs=n,this.#r(),this.#n||(gt0(this.opts.initialDelayMs)?(this.#t=(0,import_node_timers4.setTimeout)(()=>{this.#a&&(this.#i(),this.#o())},this.opts.initialDelayMs),this.opts.unref===!0&&this.#t.unref()):this.#o()),!0)}#o(){this.#a&>0(this.opts.intervalMs)&&(this.#e=(0,import_node_timers4.setInterval)(this.#i,this.opts.intervalMs),this.opts.unref===!0&&this.#e.unref())}},SequentialTaskQueue=class{#e=new Set;#t;async enqueue(e){let n=this.#t,r=new Latch;this.#e.add(r),this.#t=r,await n;try{return await e()}finally{r.resolve(),this.#e.delete(r),this.#t===r&&(this.#t=void 0)}}enqueueIfIdle(e){return this.#e.size===0?this.enqueue(e):void 0}get pendingSize(){return this.#e.size}awaitSettled(){return Promise.all(this.#e)}};function sequential(e){let n=new SequentialTaskQueue;return Object.assign((...r)=>n.enqueue(()=>e(...r)),{isIdle:()=>n.pendingSize===0})}var import_node_crypto4=require("node:crypto"),import_node_fs18=require("node:fs"),import_promises13=require("node:fs/promises"),import_node_path27=__toESM(require("node:path")),import_promises14=require("node:stream/promises"),import_node_util11=__toESM(require("node:util")),import_node_zlib2=__toESM(require("node:zlib")),estimatedFreeMem=lazy2(()=>process.availableMemory(),10*secondMs),import_node_timers5=require("node:timers"),logger11=lazy2(()=>mkLogger(`work.WorkTimeout`)),timeoutRate=lazy2(()=>new Rate(5*minuteMs,isTest()?100:ShortCommandTimeoutMs)),refreshEveryMinute=lazy2(()=>(0,import_node_timers5.setInterval)(refresh,minuteMs).unref());function refresh(){maxCpus.refresh(),maxConcurrentImports.refresh(),refreshEveryMinute()}later(()=>{ee().on(`clearCache`,()=>{maxCpus.unset(),maxConcurrentImports.unset(),timeoutRate.unset()})});var logger12=lazy2(()=>mkLogger(`work.MaxCpus`));later(()=>{isTest()&&ee().on(`clearCache`,()=>clearMaxWorkCaches()),ee().on(`settingsChanged`,clearMaxWorkCaches),ProcessesSettings.cpuBusyPercent.watchLater(clearMaxWorkCaches),ProcessesSettings.maxConcurrentImports.watchLater(clearMaxWorkCaches)});function clearMaxWorkCaches(){estimatedFreeMem.unset(),maxProcsForMem.unset(),maxCpus.unset(),maxConcurrentImports.unset(),timeoutRate.prior()?.clear(),cpuCount.unset()}var maxProcsForMem=lazy2(()=>{let e=ProcessesSettings.workerMemoryMb.valueOrDefault;return logger12().tap({msg:`maxProcsForMem`,result:Math.max(1,Math.floor(estimatedFreeMem()/(e*MB))),meta:{estFreeMemMb:Math.floor(estimatedFreeMem()/MB),workerMemoryMb:e}})},minuteMs);function timeoutPenalization(){let e=Math.round(timeoutRate.prior()?.eventsPerMinute??0),n=ProcessesSettings.timeoutThrottleCoeff.valueOrDefault,r=e===0||n===0?1:sigFigs(n/e,2);return logger12().tap({msg:`timeoutPenalization()`,level:r>1?LogLevels.warn:LogLevels.debug,result:r,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:n}})}function targetCpuLoadPct(){return(toGt0(ProcessesSettings.cpuBusyPercent.valueOrDefault)??1)/100}var maxCpus=lazy2(_maxWorkers,minuteMs),maxCpusBound=`cpu`;function _maxWorkers(){let e=ProcessesSettings.cpuBusyPercent.valueOrDefault===0?cpuCount():Math.max(1,Math.floor(targetCpuLoadPct()*cpuCount())),n=e,r=timeoutRate.prior()?.eventsPerMinute??0,a=timeoutPenalization();if(a!==1){let e=n;n*=a,logger12().warn(`Recent timeouts! Throttling down.`,{penalization:a,resultBeforePenalization:e,resultAfterPenalization:n})}let o=Math.min(e,maxProcsForMem());return n=clamp(1,o,Math.floor(n)),maxCpusBound=n<o?`timeouts`:maxProcsForMem()<e?`memory`:`cpu`,maxConcurrentImports.unset(),logger12().tap({msg:`maxCpus()`,level:LogLevels.info,result:n,meta:{cpuLoadPct:targetCpuLoadPct(),cpuCount:cpuCount(),cpuPortion:e,penalization:a,timeoutsPerSecond:r,maxProcsForMem:maxProcsForMem()}})}var maxConcurrentImports=lazy2(_maxConcurrentImports,minuteMs);function effectiveMaxConcurrentImports(){return Math.min(maxCpus(),maxConcurrentImports())}function importCeilingBound(){let e=maxCpus();return maxConcurrentImports()<e?`setting`:maxCpusBound}function _maxConcurrentImports(){return toGt0(ProcessesSettings.maxConcurrentImports.valueOrDefault)??maxCpus()}function sharpThreadsPerProcess(){return toGt0(ProcessesSettings.sharpThreadsPerProcess.valueOrDefault)??(maxCpus()<=6?2:1)}async function someOrTimeout(e,n){return Promise.all(e.map(e=>thenOrTimeoutError(tol(e),n.timeoutMs).catch(e=>e)))}async function timeOrTimeout(e,n){return Promise.all(Object.entries(e).map(([e,r])=>time({name:e,p:r,post:void 0,timeoutMs:n?.timeoutMs}).catch(e=>e)))}async function thenCollectSerial({name:e,arr:n,f:r,timeoutMs:a}){let o=[];for(let s of compact(await n))try{let e=await(gt0(a)?thenOrTimeoutError(r(s),a):r(s));e!=null&&o.push([e,s])}catch(n){mkLogger(e).warn(`failed to apply`,{ea:s,error:n})}return o}async function mapAsyncSerial(e){return(await thenCollectSerial(e)).map(e=>e[0])}async function thenCollectParallel({iter:e,f:n,maxConcurrent:r=maxCpus(),timeoutMs:a}){if(!gt0(r))throw Error(`maxConcurrency must be a positive integer, got: ${r}`);if(typeof n!=`function`)throw TypeError(`fn must be a function, got: ${typeof n}`);let o=[],s=new Set,c=-1;for await(let l of iterate(e)){for(c++;s.size>=r;)await Promise.race(s);let e=o[c]=thenOrTimeoutError(n(l),a).catch(e=>e).then(e=>[e,l]);s.add(e),e.finally(()=>s.delete(e))}return Promise.all(o)}async function mapAsync({iter:e,f:n,maxConcurrent:r,timeoutMs:a}){return(await thenCollectParallel({iter:e,f:n,maxConcurrent:r,timeoutMs:a})).filter(e=>e[0]!=null&&!(e[0]instanceof Error)).map(e=>e[0])}async function filterAsync({arr:e,f:n,maxConcurrent:r,timeoutMs:a}){return(await thenCollectParallel({iter:e,f:n,maxConcurrent:r,timeoutMs:a})).filter(([e])=>isTrue(e)).map(([,e])=>e)}async function tryAsync(e){try{return await e()}catch{return}}var DefaultTryAllTimeoutMs=30*secondMs;async function thenNot(e,n=!0){if(e==null)return n;let r=await e;return r==null?n:!isTrue(r)}async function sortByAsync({iter:e,f:n}){return sortBy((await thenCollectParallel({iter:e,f:n})).filter(e=>e[0]!=null&&!(e[0]instanceof Error)),e=>e[0]).map(e=>e[1])}var FirstIntervalMs=10,MaxIntervalMs=secondMs;function derivedIntervalMs(e,n){return Math.min(MaxIntervalMs,(e??minuteMs)/10,FirstIntervalMs*2**(n-1))}async function until(e,{timeoutMs:n,intervalMs:r,acceptable:a,timeoutResult:o,unref:s}={}){let c=!1,l=n==null?void 0:n+performance.now(),u=1;for(;l==null||performance.now()<l;){let o=performance.now(),l=await e();if(l!=null&&(isFunction(a)?a(l):l!==!1))return l;{let e=performance.now()-o;n!=null&&e>n/2&&!c&&(c=!0,onTimeout({soft:!0})),await delay(r??derivedIntervalMs(n,u),s),u++}}return c||onTimeout({soft:!1}),o}async function untilTrue(e,n={}){return until(e,{...n,acceptable:isTrue,timeoutResult:!1})}function bufferToString(e){return Buffer.isBuffer(e)?debom(e):toS(e)}var import_node_path20=require("node:path"),import_node_fs13=require("node:fs"),WipTimeoutMs=ShortCommandTimeoutMs,WipPrefix=`.WIP-`;function addWipPrefix(e){return WipPrefix+randomChars(5).toUpperCase()+`-`+e}var WipPrefixRE=/^.WIP-[\da-z]{5}-/i;function rmWipPrefix(e){return e.replace(WipPrefixRE,``)}function isWip(e){return WipPrefixRE.test(basename2(e)??``)}var logger13=defer(()=>mkLogger(`stream.Gzip`)),JpegExts=[`jpg`,`jpeg`,`jpe`],Ext2Aliases=[JpegExts,[`tif`,`tiff`],[`heic`,`heif`],[`html`,`htm`],[`jp2`,`jp2k`]],extAlias2normalized=defer(()=>{let e={};for(let[n,...r]of Ext2Aliases)for(let a of r)e[a]=n;return e}),ShortExtRe=/(?:^\.?|.\.)(?<ext>[a-z\d]{2,4})(?:_original)?$/i;function normalizeExt(e){let n=isSimpleFile(e)?e.ext:e instanceof import_node_fs13.Dirent||typeof e==`object`&&e&&`name`in e?toS(e.name):toS(e),r=ShortExtRe.exec(n)?.groups?.ext?.toLowerCase();return blank(r)?void 0:extAlias2normalized()[r]??r}function isJsonExt(e){return normalizeExt(e)===`json`}var 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`]},SidecarExts2=flatten(values(SidecarFiletypes));function isExt(e,...n){e=normalizeExt(e);for(let r of n)if(r===e)return!0;return!1}function isSidecarExt(e){return isExt(e,...SidecarExts2)}var ExtTypes=strEnum(`Sharp`,`HEIF`,`RawImage`,`Video`,`Sidecar`,`Media`,`Exif`,`SupportedByCurrentBrowser`,`SupportedByOldBrowser`),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`]},SharpImageFiletypes={"image/jpeg":JpegExts,"image/gif":[`gif`],"image/png":[`png`],"image/svg+xml":[`svg`],"image/tiff":[`tif`,`tiff`],"image/webp":[`webp`]},HeifFiletypes={"image/avif":[`avif`],"image/heic":[`heic`],"image/heif":[`heif`]},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`],"image/x-raw":[`raw`],"image/x-samsung-srw":[`srw`],"image/x-sigma-x3f":[`x3f`],"image/x-sony-arw":[`arw`],"image/x-sony-sr2":[`sr2`],"image/x-sony-srf":[`srf`]},ImageFiletypes={...SharpImageFiletypes,...HeifFiletypes,...RawImageFiletypes},VideoFiletypes={"video/3gpp":[`3gp`,`3gpp`],"video/3gpp2":[`3g2`],"video/hevc":[`hevc`,`265`,`h265`],"video/mp2t":[`mts`,`ts`],"video/mp4":[`mp4`,`insv`],"video/mpeg":[`m2v`,`mpeg`,`mpg`],"video/quicktime":[`mov`,`qt`],"video/mkv":[`mkv`],"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`]},AllFiletypes={...BrowserFiletypes,...SidecarFiletypes,...SharpImageFiletypes,...HeifFiletypes,...RawImageFiletypes,...VideoFiletypes},MediaFiletypes={...SharpImageFiletypes,...HeifFiletypes,...RawImageFiletypes,...VideoFiletypes},ExifFiletypes={...MediaFiletypes,...SidecarFiletypes},Ext2mime=defer(()=>{let e={};for(let[n,r]of entries(AllFiletypes))for(let a of r)e[a]=n;return e}),ExtAliases=defer(()=>{let e={};for(let n of values(AllFiletypes))for(let r of n)e[r]=n;return e}),AllFileExts=defer(()=>{let e=new CaseInsensitiveSet;for(let n of values(AllFiletypes))for(let r of n)e.add(r);return e}),MediaFileExts=defer(()=>{let e=new CaseInsensitiveSet;for(let n of values(MediaFiletypes))for(let r of n)e.add(r);return e}),AssetFileExts=defer(()=>uniq(flatten(values(MediaFiletypes)))),VideoFileExts=defer(()=>uniq(values(VideoFiletypes).flat())),HeifFileExts=defer(()=>uniq(values(HeifFiletypes).flat()));function extMimetype(e){let n=normalizeExt(e);return n==null?void 0:Ext2mime()[n]}function mimetypeExt(e){return AllFiletypes[toS(e).trim().toLowerCase()]?.[0]}var OldBrowserMimetypes=[`image/gif`,`image/jpeg`,`image/png`],CurrentBrowserMimetypes=[...OldBrowserMimetypes,`image/avif`,`image/svg+xml`,`image/webp`,`video/mp4`,`video/webm`],ext2types=defer(()=>{let e=new MultiMap;for(let{exts:n,type:r}of[{exts:SharpImageFiletypes,type:ExtTypes.Sharp},{exts:HeifFiletypes,type:ExtTypes.HEIF},{exts:RawImageFiletypes,type:ExtTypes.RawImage},{exts:VideoFiletypes,type:ExtTypes.Video},{exts:SidecarFiletypes,type:ExtTypes.Sidecar},{exts:MediaFiletypes,type:ExtTypes.Media},{exts:ExifFiletypes,type:ExtTypes.Exif}])for(let a of flatten(values(n)))e.add(a,r);for(let n of OldBrowserMimetypes)for(let r of AllFiletypes[n]??[])e.add(r,ExtTypes.SupportedByOldBrowser);for(let n of CurrentBrowserMimetypes)for(let r of AllFiletypes[n]??[])e.add(r,ExtTypes.SupportedByCurrentBrowser);return e});function extTypes(e){let n=normalizeExt(e);return n==null?void 0:ext2types().get(n)}function isExtType(e,n){return extTypes(e)?.includes(n)??!1}function isHeifExt(e){return isExtType(e,ExtTypes.HEIF)}function isRawImageExt(e){return isExtType(e,ExtTypes.RawImage)}function isSharpExt(e){return isExtType(e,ExtTypes.Sharp)}function isVideoExt(e){return isExtType(e,ExtTypes.Video)}function isMediaExt(e){return isExtType(e,ExtTypes.Media)}function isSupportedByCurrentBrowserExt(e){return isExtType(e,ExtTypes.SupportedByCurrentBrowser)}function stripExt(e,n){let r=splitLast(e,`.`);return n==null?MediaFileExts().has(r)?stripSuffix(e,`.${r}`):e:isExtType(r,n)?e.slice(0,-(r.length+1)):e}function getMediaCategory(e){if(isHeifExt(e))return`heic`;if(isVideoExt(e))return`video`;if(isRawImageExt(e))return`raw`;if(isSharpExt(e))return`image`}function bname(e){if(e==null||blank(e))return[];let n=isString(e)?stripExt((0,import_node_path20.basename)(e)):toS(e?.name);if(blank(n))return[];let r=n.toLowerCase().normalize(),a=new Set([r]);for(let e of[stripCopySuffixFromName,stripDSC,trimLeftPadding,e=>stripDSC(stripCopySuffixFromName(e)),e=>trimLeftPadding(stripCopySuffixFromName(e)),e=>trimLeftPadding(stripDSC(e)),e=>trimLeftPadding(stripDSC(stripCopySuffixFromName(e)))]){let n=e(r);blank(n)||a.add(n)}return[...a].sort()}function shortestBname(e){return leastBy(bname(e),(e,n)=>[e.length,n])??``}var import_node_fs14=__toESM(require("node:fs")),import_promises8=__toESM(require("node:fs/promises")),import_node_path22=require("node:path"),import_node_util10=require("node:util");function definedAndNotEql(e,n){return e!=null&&n!=null&&!eql(e,n)}var import_promises7=require("node:fs/promises"),import_node_path21=require("node:path"),import_node_process16=require("node:process"),lastTime=0,UidRadix=TokenRadix,uidSuffix=lazy2(()=>`-`+UidRadix.randomChars(7));function uid(){return lastTime=Math.max(Date.now(),lastTime+1),uidForTs(lastTime)}function uidForTs(e){return UidRadix.encode(e)+uidSuffix()}function addInstanceIds(e){let n=e;return isObject(n)&&(n.__pid__=import_node_process16.pid,n.__uid__=uid()),n}var WeakCache=class{[Symbol.toStringTag]=`WeakCache`;#e=new Map;clear(){return this.#e.clear(),this}delete(e){return this.#e.delete(e)}deleteAll(e){for(let n of e)this.delete(n)}forEach(e){for(let[n,r]of this.entries())e(r,n,this)}findEntry(e){for(let[n,r]of this.entries())if(e(r,n,this))return r}deleteValueIf(e){let n=!1;for(let[r,a]of this.entries())e(a,r,this)&&(n||=this.#e.delete(r));return n}get(e){let n=this.#e.get(e),r=n?.deref();return r==null&&n!=null&&this.#e.delete(e),r}getOrMaybeSet(e,n){let r=this.#e.get(e)?.deref();if(r!=null)return r;let a=n();return a!=null&&this.set(e,a),a}set(e,n){return this.#e.set(e,new WeakRef(n)),this}has(e){return this.#e.get(e)?.deref()!=null}get size(){return this.#t(),this.#e.size}*keys(){for(let[e,n]of this.#e.entries())n.deref()==null?this.#e.delete(e):yield e}*values(){for(let[e,n]of this.#e.entries()){let r=n.deref();r==null?this.#e.delete(e):yield r}}*entries(){for(let[e,n]of this.#e.entries()){let r=n.deref();r==null?this.#e.delete(e):yield[e,r]}}#t(){for(let[e,n]of this.#e.entries())n.deref()??this.#e.delete(e)}[Symbol.iterator](){return this.entries()}},ZeroStats={hits:0,misses:0,sets:0,errors:0,timeouts:0},activeCaches=new WeakCache,registerClearCache=defer(()=>{isTest()&&ee().on(`clearCache`,()=>{for(let e of activeCaches.values())e.reset()})}),Cache=class{[Symbol.toStringTag]=`Cache`;#e=[];#t;#n;#r;#i;#a;#o;#s=new Map;#c={...ZeroStats};#l=0;constructor(e){this.#t={maxSize:256,...e},this.setOptions({}),isTest()&&(activeCaches.set(uid(),this),registerClearCache())}[Symbol.iterator](){return this.entries()}get opts(){return{...this.#t}}setTTL(e){this.setOptions({ttlMs:e})}setOptions(e){let n={...this.#t};Object.assign(this.#t,e);function r(e,n,r){return e!=null&&clearInterval(e),gt0(n)?setInterval(()=>r(),n).unref():void 0}let{clearEveryMs:a,ttlMs:o,maxSize:s}=this.#t;a!==this.#a&&(this.#n=r(this.#n,a,()=>this.clear()),this.#a=a),o!==this.#o&&(this.#r=r(this.#r,gt0(o)?Math.max(1,Math.round(o/4)):void 0,()=>this.vacuum()),this.#o=o),(s!==n.maxSize||o!==n.ttlMs)&&this.vacuum()}lastSetTs(e){return this.vacuum(),e==null?this.#i:this.#s.get(e)?.ts}#u(e,n,r){if(n==null)return!1;if(r??=this.#t.ttlMs,!gt0(r)||this.#d(n))return!0;if(n.ts+r<Date.now()){let r=n.v;return isPromiseLike(r)||this.#e.forEach(n=>n(e,r)),this.delete(e),!1}return!0}#d(e){return(this.#t.keepPending===!0||this.#t.noop===!0)&&isPromiseLike(e.v)}destroy(){this.#n!=null&&(clearInterval(this.#n),this.#n=void 0),this.#r!=null&&(clearInterval(this.#r),this.#r=void 0),this.#a=void 0,this.#o=void 0,this.clear()}clear(){return this.#s.clear(),this.#l++,this}reset(){return Object.assign(this.#c,ZeroStats),this.clear()}delete(e){return this.#s.delete(e)}deleteArgs(...e){return this.delete(memoizedArgsKey(e))}deleteAll(e){for(let n of e)this.delete(n)}deleteByPrefix(e){let n=0;for(let r of this.#s.keys())r.startsWith(e)&&(this.#s.delete(r),n++);return n}async deleteIf(e){for(let[n,r]of this.#s.entries())await e(n,r.v)&&this.#s.delete(n)}deleteValueIfSync(e){let n=!1;for(let[r,a]of this.#s.entries())!isPromiseLike(a.v)&&e(a.v)&&(n||=this.#s.delete(r));return n}deleteResolved(){for(let[e,n]of this.#s.entries())this.#u(e,n)&&isDeferred(n.v)||this.#s.delete(e)}forEach(e){for(let[n,r]of this.#s.entries())this.#u(n,r)&&!isPromiseLike(r.v)&&e(r.v,n,this)}find(e){for(let[n,r]of this.#s.entries())if(this.#u(n,r)&&!isPromiseLike(r.v)&&e(r.v,n))return r.v}get(e){let n=this.#s.get(e);if(this.#u(e,n)&&!isPromiseLike(n.v))return this.#c.hits++,n.v;this.#c.misses++}getAsync(e,n){let r=this.#s.get(e);if(this.#u(e,r)&&(n===void 0||r.stamp===n))return this.#c.hits++,r.v;this.#c.misses++}peek(e,n){let r=this.#s.get(e);if(this.#u(e,r)&&(n===void 0||r.stamp===n)){let e=r.v;if(!isPromiseLike(e))return e??null}}peekAsync(e){let n=this.#s.get(e);if(this.#u(e,n))return n.v}getOrMaybeSet(e,n){let r=this.#s.get(e);if(this.#u(e,r)&&!isPromiseLike(r.v))return this.#c.hits++,r.v;this.#c.misses++;let a=n();return a!=null&&this.set(e,a),a}getOrSet(e,n,r){let a=this.#s.get(e);return this.#u(e,a)&&(r===void 0||a.stamp===r)?(this.#c.hits++,a.v):(this.#c.misses++,this.setAndGet(e,n(),r))}has(e){let n=this.#s.get(e);return this.#u(e,n)}hasSync(e){let n=this.#s.get(e);return n!=null&&!isPromiseLike(n.v)}set(e,n){return this.setAndGet(e,n),this}setAndGet(e,n,r){let a=Date.now(),o=this.#l;if(this.#i=a,this.#c.sets++,n==null)return this.#s.delete(e),n;if(!isPromiseLike(n))return this.#t.noop===!0?(this.#s.delete(e),n):(this.#s.set(e,{ts:a,stamp:r,v:n}),this.#f(),n);let s=isDeferred(n)?n:new Deferred().observe(thenOrTimeoutError(n,this.#t.timeoutMs));return s.then(n=>{if(this.#l===o){let o=this.#s.get(e);if(o?.v===s&&o.ts===a&&o.stamp===r){if(this.#t.noop===!0){this.#s.delete(e);return}this.#s.set(e,{ts:this.#t.keepPending===!0?Date.now():a,stamp:r,v:n})}}}).catch(n=>{if(this.#c.errors++,isTimeoutError(n)&&this.#c.timeouts++,this.#l===o){let n=this.#s.get(e);n?.v===s&&n.ts===a&&n.stamp===r&&this.#s.delete(e)}}),this.#s.set(e,{ts:a,stamp:r,v:s}),this.#f(),s}#f(){let e=this.#t.maxSize;if(!gt0(e)||this.#s.size<=e)return;let n=this.#s.keys();for(;this.#s.size>e;){let e=n.next().value;if(e==null)break;this.#s.delete(e)}}get size(){return this.vacuum(),this.#s.size}stats(){return{size:this.size,...this.#c}}mergeStats(e){for(let[n,r]of Object.entries(e))n in this.#c&&(this.#c[n]+=r)}*keys(){for(let[e]of this.#s.entries())this.#u(e,this.#s.get(e))&&(yield e)}*values(){for(let[e,n]of this.#s.entries())this.#u(e,n)&&!isPromiseLike(n.v)&&(yield n.v)}*valuesAsync(){for(let[e,n]of this.#s.entries())this.#u(e,n)&&(yield n.v)}valuesByRecency(){return this.vacuum(),sortBy(Array.from(this.values()),(e,n)=>-n)}*entries(){for(let[e,n]of this.#s.entries())this.#u(e,n)&&!isPromiseLike(n.v)&&(yield[e,n.v])}*entriesAsync(){for(let[e,n]of this.#s.entries())this.#u(e,n)&&(yield[e,n.v])}on(e,n){e===`expire`&&this.#e.push(n)}vacuum(){if(gt0(this.#t.ttlMs)){let e=Date.now()-this.#t.ttlMs;for(let[n,r]of this.#s.entries())if(r.ts<=e&&!this.#d(r)){let e=r.v;isPromiseLike(e)||this.#e.forEach(r=>r(n,e)),this.#s.delete(n)}}this.#f()}memoize(e){let n=((...n)=>{let r=memoizedArgsKey(n);return this.getOrMaybeSet(r,()=>e(...n))});return n.cache=this,n.set=(e,n)=>Promise.resolve(this.setAndGet(memoizedArgsKey(e),n)),n.refreshIfOlderThan=async(e,...r)=>{let a=memoizedArgsKey(r),o=this.#s.get(a),s=o?.v;if(isPromiseLike(s))return this.#c.hits++,await s;if(!gt0(e))this.delete(a);else if(this.#u(a,o,e))return this.#c.hits++,await o.v;return await n(...r)},n}};function memoizedArgsKey(e){return JSON.stringify(e)}function memoize(e,n){return new Cache(n).memoize(e)}var InstanceCacheMaxSize=256;function isClearable(e){return typeof e==`object`&&typeof e?.clear==`function`}var ZeroCanonicalScanStats={scans:0,activeScans:0,maxActiveScans:0,keysVisited:0,keysVisitedBeyondStart:0,scansCoalesced:0,maxQueuedPaths:0},FileCache=class e extends Cache{static#e=new Set;static#t=new Map;static#n=!1;static#r={...ZeroCanonicalScanStats};static canonicalScanStats(){return{...e.#r}}static resetCanonicalScanStats(){let{activeScans:n}=e.#r;Object.assign(e.#r,ZeroCanonicalScanStats,{activeScans:n,maxActiveScans:n})}static#i=new Map;static#a;static#o(n){let r=e.#i.get(n);if(r!=null)return e.#r.scansCoalesced++,r.promise;let a=new Deferred(`FileCache canonical scan`);return e.#i.set(n,a),e.#r.maxQueuedPaths=Math.max(e.#r.maxQueuedPaths,e.#i.size),e.#a??=e.#s(),a.promise}static async whenCanonicalScansIdle(){for(;e.#a!=null;)await e.#a}static async#s(){try{for(;;){let n=e.#i.entries().next();if(n.done===!0)return;let[r,a]=n.value;e.#i.delete(r);try{await e.#c(r)}catch(e){mkLogger(`FileCache`).warn(`canonical invalidation failed`,{fromPath:r,error:e})}finally{a.resolve()}}}finally{e.#a=void 0}}static async#c(n){let r=await e.#l(n);await e.#d([...e.#e],`fileChanged`,n,async e=>await e.#_(r,n,macSymlinkAltPath(n)))}static async#l(n){let r=e.#t.get(n);if(r!=null)return await r;let a=resolvePathSymlinks(n);e.#t.set(n,a);try{return await a}finally{e.#t.get(n)===a&&e.#t.delete(n)}}static#u(n,r,a,o){for(let s of n)if(e.#e.has(s))try{o(s)}catch(e){mkLogger(`FileCache`).warn(`cache event listener failed`,{cacheName:s.opts.name,eventName:r,fromPath:a,error:e})}}static async#d(n,r,a,o){for(let s of n)if(e.#e.has(s))try{await o(s)}catch(e){mkLogger(`FileCache`).warn(`cache event listener failed`,{cacheName:s.opts.name,eventName:r,fromPath:a,error:e})}}static async#f(n){let r=[...e.#e];if(r.length===0)return;if(blank(n)){e.#u(r,`fileChanged`,n,e=>e.#h());return}e.#u(r,`fileChanged`,n,e=>e.#g(n));let a=macSymlinkAltPath(n);a!=null&&e.#u(r,`fileChanged`,n,e=>e.#g(a)),await e.#o(n)}static#p(){e.#u([...e.#e],`clearCache`,void 0,e=>e.clear())}clearOnFileChange;#m=new Map;constructor(n){super({timeoutMs:SyncSettings.taskTimeoutMs.valueOrDefault,ttlMs:CacheSettings.metadataCacheMs.valueOrDefault,maxSize:InstanceCacheMaxSize,...n}),this.clearOnFileChange=n.clearOnFileChange??!1,e.#e.add(this),e.#n||=(ee().on(`fileChanged`,e.#f),ee().on(`clearCache`,e.#p),!0),PerformanceSettings.emitTimingsOnExit.valueOrDefault&&new EndableWrapper(n.name+` stats`,async()=>{let e=mapEntries(this.stats(),(e,n)=>n>0?n:void 0);isNotEmpty(keys(e))&&mkLogger(n.name).info(`stats`,e)},EndableRanks.stats)}destroy(){e.#e.delete(this)&&super.destroy()}clear(){return this.#m.clear(),super.clear()}delete(e){return this.#m.delete(e),super.delete(e)}setAndGet(e,n,r){return this.#m.delete(e),super.setAndGet(e,n,r)}#h(){if(this.clearOnFileChange)for(let[e,n]of this.entriesAsync())isClearable(n)?n.clear({emit:!1}):this.delete(e);else this.clear()}#g(e){for(let[n,r]of this.entriesAsync())n.startsWith(e)&&this.#v(n,r)}async#_(n,r,a){let o=e.#r,s=this.size,c=0;o.scans++,o.activeScans++,o.maxActiveScans=Math.max(o.maxActiveScans,o.activeScans);try{let o=new Set;for(let[e]of this.entriesAsync())o.add(e);for(let s of o){if(c++,s.startsWith(r)||a!=null&&s.startsWith(a))continue;let o=this.#m.get(s);if(typeof o!=`string`){let n=o??e.#l(s);if(this.#m.set(s,n),o=await n,!e.#e.has(this))return;if(this.#m.get(s)!==n)continue;this.#m.set(s,o)}if(!o.startsWith(n))continue;let l=this.peekAsync(s);l!==void 0&&this.#v(s,l)}for(let e of this.#m.keys())o.has(e)||this.#m.delete(e)}finally{o.activeScans--,o.keysVisited+=c,o.keysVisitedBeyondStart+=Math.max(0,c-s)}}#v(e,n){this.clearOnFileChange&&isClearable(n)?n.clear({emit:!1}):this.delete(e)}};function metadataCacheOptions(){let e=CacheSettings.metadataCacheMs.valueOrDefault;return{ttlMs:e,noop:e===0}}var logger14=defer(()=>mkLogger(`fs.Readdir`));async function readdir2(e,n){try{return await readdir_(e,n)}catch(n){logger14().warn(`readdir() failed`,{file:e,error:n});return}}async function readdir_(e,n){let r=[];for await(let a of iterateDir_(e,{...n,sortThreshold:0}))r.push({basename:a.name,isFile:a.isFile(),isDirectory:a.isDirectory()});let a=sortBy(r,e=>[e.isDirectory,...sortNaturalBy(e.basename)]);return n?.reverse===!0&&a.reverse(),a}async function*iterateDir_(e,n){let r=n?.sortThreshold??FilesystemSettings.directorySortThreshold.valueOrDefault,a=n?.directorySortThresholdMs??FilesystemSettings.directorySortThresholdMs.valueOrDefault,o=performance.now(),s,c=n?.retries??FilesystemSettings.statRetries.valueOrDefault,l=n?.timeoutMs??FilesystemSettings.statTimeoutMs.valueOrDefault,u=defer(async()=>{try{await s?.close()}catch(n){logger14().warn(`Failed to close directory handle`,{file:e,error:n})}}),d=async()=>{for(;;)try{return await thenOrTimeoutError(s.read(),l)}catch(n){if(logger14().warn(`dir.read() failed for a child entry`,{error:n,file:e}),--c<=0)throw n}};try{if(s=await fsOperation_(()=>(0,import_promises7.opendir)(e,n)),r<=0){let e;for(;(e=await d())!=null;)yield e;return}let c=[],l;for(;(l=await d())!=null;)if(c.push(l),c.length>r||performance.now()-o>a){if(!0===n?.onlyYieldIfSorted)return;for(yield*c;(l=await d())!=null;)yield l;return}let u=sortBy(c,e=>[e.isDirectory(),...sortNaturalBy(e.name)]);n?.reverse===!0&&u.reverse(),yield*u}finally{await u()}}var readdirSortedCache=defer(()=>new FileCache({name:`readdirSorted`}));function eqlDirentBasename(e,n){return e.toLowerCase()===n.toLowerCase()}async function readdirSortedMaybe_(e,n){let r=n?.expectBasename,a=r?.toLowerCase(),o=await readdirSortedCache().peekAsync(e),s;if(o!=null){let n=await staleness(e,o,r);n!==`fresh`&&(n===`entry-missing`&&a!=null&&(s=new Map(o.confirmedAbsent),s.delete(a)),readdirSortedCache().delete(e))}let c=await readdirSortedCache().getOrSet(e,async()=>{let n=await mtimeMs(e),r=Date.now(),a=[];for await(let n of iterateDir_(e,{onlyYieldIfSorted:!0}))a.push({basename:n.name,isFile:n.isFile(),isDirectory:n.isDirectory()});return a.length===0?void 0:{mtimeMs:n,readAtMs:r,dirents:a,confirmedAbsent:s}});if(r!=null&&a!=null&&c!=null&&!includesBasename(c.dirents,r)){let n=c.confirmedAbsent??=new Map;n.has(a)||n.set(a,await mtimeMs((0,import_node_path21.join)(e,r)))}return c?.dirents}function includesBasename(e,n){return e.some(e=>eqlDirentBasename(e.basename,n))}async function staleness(e,n,r){let a=await mtimeMs(e);if(a!==n.mtimeMs)return logger14().debug(`readdirSortedMaybe_(): directory changed since it was read`,{file:e,priorMtimeMs:n.mtimeMs,currentMtimeMs:a}),`dir-changed`;if(typeof n.mtimeMs==`number`&&isRacyMtime(n.mtimeMs,n.readAtMs))return logger14().debug(`readdirSortedMaybe_(): prior listing was racy`,{file:e,mtimeMs:n.mtimeMs,readAtMs:n.readAtMs}),`dir-racy`;if(r==null||includesBasename(n.dirents,r))return`fresh`;let o=r.toLowerCase();if(n.confirmedAbsent?.has(o)===!0){let a=n.confirmedAbsent.get(o),s=await mtimeMs((0,import_node_path21.join)(e,r));if(s===a)return`fresh`;logger14().debug(`readdirSortedMaybe_(): `+r+` changed since it went missing`,{file:e,confirmedAbsentMtimeMs:a,currentEntryMtimeMs:s})}else logger14().debug(`readdirSortedMaybe_(): cached listing predates `+r,{file:e,mtimeMs:a});return`entry-missing`}var StatDirent=class{constructor(e,n){this.base=e,isSimpleDirent(n)?(this.isFile=n.isFile,this.isDirectory=n.isDirectory):(this.isFile=n.isFile(),this.isDirectory=n.isDirectory()),n instanceof import_node_fs14.default.Stats&&(this.size=n.size,this.mtimeMs=n.mtimeMs)}base;isFile;isDirectory;size;mtimeMs};function toFileMeta(e){return e instanceof DirectoryEntry?{size:e.size(),mtimeMs:e.mtimeMs(),isFile:e.isFile(),isDirectory:e.isDirectory()}:{size:e.size,mtimeMs:e.mtimeMs,isFile:e instanceof import_node_fs14.default.Stats?e.isFile():e.isFile,isDirectory:e instanceof import_node_fs14.default.Stats?e.isDirectory():e.isDirectory}}function eqlFileMeta(e,n){return e!=null&&n!=null&&eql(toFileMeta(e),toFileMeta(n))}var logger15=lazy2(()=>mkLogger(`fs.DirectoryEntry`)),DirectoryEntry=class e{constructor(e,n){this.dir=e,this.dirent=n,this.nativePath=(0,import_node_path22.join)(this.dir,n.base),this.ext=parseNativePath(n.base).ext}dir;dirent;nativePath;ext;static fromSimpleDirent(n,r){return new e(n,new StatDirent(r.basename,r))}static fromDirent(n,r){return new e(n,new StatDirent(r.name,r))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(n){let{nativePath:r,dir:a,base:o}=isSimpleFile(n)?n:{nativePath:n,...parseNativePath(n)},s=await import_promises8.default.stat(r);return new e(a,new StatDirent(o,s))}clear(){return ee().emitSync(`fileChanged`,this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...n){return e.for((0,import_node_path22.join)(this.nativePath,...n))}get base(){return this.dirent.base}get name(){return stripSuffix(this.base,this.ext)}get pathnames(){return this.nativePath.split(import_node_path22.sep)}get parentAndBase(){return this.pathnames.slice(-2).join(`/`)}get parentBasename(){return parentBasename(this.nativePath)}toJSON(){return{dir:this.dir,base:this.base}}toLogJSON(){return this.nativePath}[import_node_util10.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,import_node_path22.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(`.`)}parent(){let n=parseNativePath(this.dir);return n.dir===this.dir?this:new e(n.dir,{base:n.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await readdir2(this.nativePath))?.map(e=>e.basename):void 0}catch(e){logger15().warn(`childNames() failed to readdir(`+this.nativePath+`)`,e);return}}async children(){try{return this.isDirectory()?(await readdir2(this.nativePath))?.map(n=>e.fromSimpleDirent(this.nativePath,n)):void 0}catch(e){logger15().warn(`children() failed to readdir(`+this.nativePath+`)`,e);return}}childFromDirent(n){return new e(this.nativePath,new StatDirent(n.name,n))}childrenSync(){try{return this.isDirectory()?sortByCaseInsensitive(import_node_fs14.default.readdirSync(this.nativePath,{withFileTypes:!0}),e=>e.name).map(n=>new e(this.nativePath,new StatDirent(n.name,n))):void 0}catch(e){logger15().warn(`children() failed to readdir(`+this.nativePath+`)`,e);return}}async childDirectories(){return toA(await this.children()).filter(e=>e.isDirectory())}async childFiles(){return toA(await this.children()).filter(e=>e.isFile())}visitDescendantsSync(e){let n=this.childrenSync();if(n!=null){for(let r of n)r.isFile()&&e(r);for(let r of n)r.isDirectory()&&(r.visitDescendantsSync(e),e(r))}}async*descendantsIterable_(){let e;try{e=sortByCaseInsensitive(await import_promises8.default.readdir(this.nativePath,{withFileTypes:!0}),e=>e.name)}catch(e){if(errorCode(e)!==`ENOENT`)throw e;logger15().trace(`descendantsIterable_(): directory disappeared`,{directory:this.nativePath,error:e});return}for(let n of e)n.isDirectory()&&(yield*this.childFromDirent(n).descendantsIterable_());for(let n of e)yield this.childFromDirent(n)}async*descendantsIterable(){let e=await this.children();for(let n of e??[])n.isDirectory()&&(yield*n.descendantsIterable());for(let n of e??[])yield n}statDirent(){let e=statSync(this.nativePath);return e==null?void 0:this.dirent=new StatDirent(this.base,e)}async stat(){try{let e=await stat_(this.nativePath);return this.dirent=new StatDirent(this.base,e),e}catch{return}}hasStats(){return this.dirent.size!=null&&this.dirent.mtimeMs!=null}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){try{await import_promises8.default.unlink(this.nativePath)}catch(e){if(e.code!==`ENOENT`)throw e}await ee().emit(`fileChanged`,this.nativePath)}async rmdir_(){await import_promises8.default.rmdir(this.nativePath),await ee().emit(`fileChanged`,this.nativePath)}},import_node_path23=__toESM(require("node:path"));function lastIndex(e){return e.startIndex+e.maxVersions-1}function tooManyVersions(e,n){return Error(`There are already more than `+n+` of `+e)}var DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1});async function ensureNewNativePath_(e){let n={...DefaultEnsureNewOptions,...e},r=parseNativePath(n.nativePath);if(await mkdirp_(r.dir),!n.requireNumber&&await isEmptyFile(n.nativePath,n))return n.nativePath;let a=lastIndex(n);for(let e=n.startIndex;e<=a;e++){let a=import_node_path23.default.join(r.dir,`${r.name}-${leftPad(e,n.leftPad,`0`)}${r.ext}`);if(await isEmptyFile(a,n))return a}throw tooManyVersions(n.nativePath,n.maxVersions)}function ensureNewNativePathSync_(e){let n={...DefaultEnsureNewOptions,...e},r=parseNativePath(n.nativePath);if(mkdirpSync_(r.dir),!n.requireNumber&&isEmptyFileSync(n.nativePath,n))return n.nativePath;let a=lastIndex(n);for(let e=n.startIndex;e<=a;e++){let a=import_node_path23.default.join(r.dir,`${r.name}-${leftPad(e,n.leftPad,`0`)}${r.ext}`);if(isEmptyFileSync(a,n))return a}throw tooManyVersions(n.nativePath,n.maxVersions)}var import_node_crypto3=__toESM(require("node:crypto")),import_node_fs15=__toESM(require("node:fs")),import_node_stream=require("node:stream"),import_promises9=require("node:stream/promises"),HashBits=192,import_node_async_hooks2=require("node:async_hooks"),owners=new import_node_async_hooks2.AsyncLocalStorage;function runWithOperationOwner(e,n){return owners.run(e,n)}function operationOwner(){return owners.getStore()}async function awaitOutsideDeadline(e){let n=operationOwner();return n?.awaitOutsideDeadline==null?await e:await n.awaitOutsideDeadline(e)}function shim(e){return new ShimImpl(e.name,e.impl,e.cache,e.toKey,e.stamp)}var ShimImpl=class extends ExtensibleFunction{constructor(e,n,r,a,o){super(),this.impl=n,this.cache=r,this.toKey=a,this.stamp=o,this.#e=e}impl;cache;toKey;stamp;#e;#t;#n(...e){return this.toKey?.(...e)??(isPrimitive(e)?toS(e):stringify(e))}#r(...e){return this.#t==null?this.#e==null?this.impl(...e):timeExcludingNested({name:this.#e,thunk:()=>this.impl(...e)}):this.#t(...e)}async _call(...e){let n=this.#n(...e);return excludeWaitFromEnclosingTimer(async()=>{if(this.cache==null)return this.#r(...e);let r=this.stamp==null?void 0:await this.stamp(...e);return this.cache().getOrSet(n,()=>this.#r(...e),r)})}setShim(e){this.#t=e}hasShim(){return this.#t!=null}clearShim(){this.#t=void 0}cacheDelete(...e){this.cache?.().delete(this.#n(...e))}},import_node_crypto2=__toESM(require("node:crypto"));function stringShaToBuffer(e,n=HashBits){return import_node_crypto2.default.createHash(`sha512`).update(e).digest().subarray(0,n/8)}function shortStringSha(e,n=9,r=Radix58,a=224){return r.encodeBuffer(stringShaToBuffer(e,a)).substring(0,n)}function shortFsStringSha(e,n=24,r=GeoRadix,a=224){return shortStringSha(e,n,r,a)}function toFileStats(e){return e==null?void 0:pick(e,`size`,`mtimeMs`,`ino`,`birthtimeMs`)}async function fileStats_(e){return toFileStats(await stat_(toNativePath_(e)))}async function fileStats(e){try{return await fileStats_(e)}catch{return}}async function fileStamp(e){let n=await fileStats(e);return n==null?MissingFileStamp:JSON.stringify(n)}var MissingFileStamp=`missing`,cache=lazy2(()=>new Cache({name:`fs.Hash`,maxSize:1024,timeoutMs:0,keepPending:!0,clearEveryMs:0,ttlMs:10*minuteMs})),shimmedFileSha_=shim({name:`fs.Hash`,cache,toKey:fileShaCacheKey_,stamp:(...[e])=>fileStamp(toNativePath_(e)),impl:uncachedFileSha_});function fileShaCacheKey_(e,n,r){let a=toNativePath_(e);return n===void 0&&r===void 0?a:stringify([a,n,r])}async function fileShaMeta_(e,{autoInvalidate:n=!0}={}){if(!n){let n=await excludeWaitFromEnclosingTimer(async()=>cache().getAsync(toNativePath_(e)));if(n!=null)return n}return shimmedFileSha_(e)}async function fileSha_(e){return(await fileShaMeta_(e)).sha}var MaxShaReads=3,SettlePollMs=secondMs,MaxSettleMs=30*secondMs;async function uncachedFileSha_(e,n,r){let a=performance.now(),o=toNativePath_(e),s=operationOwner(),c=0,l=0,u=s?.onProgress==null?void 0:e=>{l=c+(e.step??0),s.onProgress?.({...e,step:l})};for(let e=1;;e++){c=l;let s=await stat_(o),d=await readSha(o,n,r,u),f=toFileStats(s);if(!s.isFile()||sameFileStats(f,toFileStats(await stat_(o))))return{sha:d,stats:f,elapsedMs:roundMs(performance.now()-a)};if(e>=MaxShaReads)throw Error(`${o} changed while it was read, ${MaxShaReads} times`+NonRetriableErrorFlag);await untilFileStopsChanging(o)}}function readSha(e,n,r,a){return streamSha_({source:import_node_fs15.default.createReadStream(e),transforms:a==null?[]:[byteProgress({path:e,op:`Hashing`,intervalMs:hashProgressIntervalMs(),onProgress:a})],hashAlgorithm:r,bits:n})}function sameFileStats(e,n){return e.size===n.size&&e.mtimeMs===n.mtimeMs&&e.birthtimeMs===n.birthtimeMs&&e.ino===n.ino}async function untilFileStopsChanging(e){let n=performance.now()+MaxSettleMs,r=toFileStats(await stat_(e));for(;performance.now()<n;){await delay(SettlePollMs);let n=toFileStats(await stat_(e));if(sameFileStats(r,n))return;r=n}}function hashProgressIntervalMs(){let e=SyncSettings.taskTimeoutMs.valueOrDefault;return gt0(e)?Math.min(secondMs,e/4):secondMs}function byteProgress({path:e,op:n,intervalMs:r,onProgress:a}){let o=0,s=0,c=Date.now(),l=()=>{s=o,c=Date.now(),a(e==null?{op:n,step:o}:{path:e,op:n,step:o})};return new import_node_stream.Transform({transform(e,n,a){try{o+=e.length,Date.now()-c>=r&&l(),a(null,e)}catch(e){a(e)}},flush(e){try{o>s&&l(),e()}catch(n){e(n)}}})}async function streamSha_({source:e,transforms:n=[],hashAlgorithm:r=`sha512`,bits:a=HashBits}){let o=import_node_crypto3.default.createHash(r);await(0,import_promises9.pipeline)([e,...n,o]);let s=o.digest();return a!=null&&a>0&&(s=s.subarray(0,a/8)),s.toString(`base64`)}var import_node_path25=__toESM(require("node:path")),import_fs_metadata=require("@photostructure/fs-metadata"),import_promises10=require("node:fs/promises"),import_node_path24=require("node:path"),logger16=defer(()=>mkLogger(`async.LazyAsync`));function lazyAsync({later:e,desc:n,ttlMs:r,timeoutMs:a}){return new LazyAsyncClass(e,n,r,a)}var LazyAsyncClass=class extends ExtensibleFunction{constructor(e,n,r,a){super(),this.later=e,this.desc=n,this.ttlMs=r,this.timeoutMs=a}later;desc;ttlMs;timeoutMs;#e;#t=0;#n=0;#r=0;#i;#a;#o=[];_call(){return this.isStale()?this.#c(this.later()):this.#i}async#s(e){try{let n=await e,r=this.#a;if(this.#i!==e)return;if(this.#a=n,this.#t++,!eql(r,n))for(let e of this.#o)await e.onChange?.(n)}catch(n){if(this.#i===e){this.#n++;let e=toError(n);if(logger16().warn(this.desc+`: onSetResult failed`,{error:e}),e!=null)for(let n of this.#o)n.onError?.(e)}}finally{this.#i===e&&this.#r++}}#c(e){this.#e=performance.now();let n=this.#i=e instanceof Deferred2?e:new Deferred2(this.toString()).observe(e);return gt0(this.timeoutMs)&&n.setTimeout(this.timeoutMs),this.#s(n),n}clear(){this.#r=0,this.#t=0,this.#n=0,this.#a=void 0,this.#e=void 0,this.#i=void 0}set(e,n){let r=this.#c(Deferred2.resolve(e));return n!=null&&(this.#e=performance.now()+(n-(this.ttlMs??0))),r}refresh(){return this.#c(this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=gt0(e)?e:void 0}watchLater(e){this.#o.push(e)}prior(){return this.isStale()?void 0:this.#i}lastValue(){return this.#a}syncValue(){let e=this.lastValue();return this._call(),e}settledCount(){return this.#r}resolvedCount(){return this.#t}rejectedCount(){return this.#n}isStale(){return this.#e==null||gt0(this.ttlMs)&&performance.now()-this.#e>this.ttlMs}lastSetAgoMs(){return this.#e==null?void 0:performance.now()-this.#e}elapsedMs(){return this.#i?.settledMs??this.#i?.elapsedMs}toString(){return this.desc??`[LazyAsync]`}toJSON(){return this.toString()}},logger17=defer(()=>mkLogger(`fs.MacFirmlinks`));async function*parseTsvPairs(e){let n=(await(0,import_promises10.readFile)(e,`utf-8`)).split(`
|
|
492
|
+
`);for(let e of n){if(e.length===0||e.startsWith(`#`))continue;let[n,r]=e.split(` `,2);notBlank(n)&¬Blank(r)&&(yield{visiblePath:stripSuffix(n,import_node_path24.sep),targetPath:stripSuffix(r,import_node_path24.sep)})}}var getFirmlinks=lazyAsync({desc:`getFirmlinks`,later:async()=>{if(!isMac)return;let e=[];for await(let n of parseTsvPairs(`/usr/share/firmlinks`))e.push(n);let n;for(let e of[`/Users`,`/Library`,`/opt`])try{n??=await(0,import_fs_metadata.getMountPointForPath)(e);break}catch(n){logger17().warn(`getFirmlinks: error getting mount point for path`,{path:e,error:n})}return n??=(logger17().warn(`getFirmlinks: could not determine mount point for firmlinked paths, defaulting to /System/Volumes/Data`),`/System/Volumes/Data`),{links:e,mountPoint:n}}});function matchVisible(e,n){if(e===n.visiblePath)return``;if(e.startsWith(n.visiblePath+`/`))return e.slice(n.visiblePath.length)}function matchTarget(e,n){let r=`/`+n.targetPath;if(e===r)return``;if(e.startsWith(r+`/`))return e.slice(r.length)}function canonicalizeMacPathSync(e){if(!isMac)return e;let n=getFirmlinks.lastValue();if(n===void 0)return;if(!e.startsWith(n.mountPoint))return e;let r=e.slice(n.mountPoint.length);for(let e of n.links){let n=matchTarget(r,e);if(n!=null)return e.visiblePath+n}return e}async function canonicalizeMacPath(e){if(!isMac)return e;let n=await getFirmlinks();if(n==null||!e.startsWith(n.mountPoint))return e;let r=e.slice(n.mountPoint.length);for(let e of n.links){let n=matchTarget(r,e);if(n!=null)return e.visiblePath+n}return e}async function dataVolumePath(e){let n=await getFirmlinks();if(n!=null)for(let r of n.links){let a=matchVisible(e,r);if(a!=null)return n.mountPoint+`/`+r.targetPath+a}}var logger18=lazy2(()=>mkLogger(`fs.PathContains`));function sameNativePath(e,n){let r=canonicalizeMacPathSync(e)??e,a=canonicalizeMacPathSync(n)??n;return isCaseSensitiveFs?r===a:r.toLowerCase()===a.toLowerCase()}function containedByNativePath(e){try{if(e.descendant==null||e.ancestor==null)return!1;let n=toNativePath_(e.ancestor),r=toNativePath_(e.descendant);if(blank(n)||blank(r))return!1;let a=e.acceptSelf??!1;return n===r?a:r.startsWith(ensureSuffix(n,import_node_path25.default.sep))}catch(n){return logger18().warn(`containedByNativePath() failed (returning false)`,{args:e,error:n}),!1}}var import_promises11=require("node:fs/promises");function statTimeoutMs(){return FilesystemSettings.statTimeoutMs.valueOrDefault}var import_node_path26=__toESM(require("node:path")),InvalidFilesystemCharacters=[`<`,`>`,`:`,`"`,`/`,`\\`,`|`,`?`,`*`],InvalidBasenameCharacters=InvalidFilesystemCharacters.filter(e=>e!==import_node_path26.default.posix.sep&&e!==import_node_path26.default.win32.sep),InvalidRE=RegExp(`[\\x00-\\x1f${escapeRegExp(InvalidFilesystemCharacters.join(``))}]+`,`g`),InvalidWinName=/^(?:CON|PRN|AUX|NUL|COM\d|LPT\d)(?:$|\.)/i;function isValidFilename(e){return mkValidFilename(e)===e}function mkValidFilename(e,n=`_`){let r=stripAnsiEsc(e).replace(InvalidRE,n);return isWin&&r.endsWith(`.`)&&(r=r.replace(/\.$/,n)),r===`.`||r===`..`||InvalidWinName.test(r)?n+r:r}function toMs(e){let n=e==null?void 0:isDate(e)?e.getTime():isNumber(e)?e:void 0;return isTest()&&n!=null?Math.round(n):n}async function touch_(e){let n=e.ensureFile??!0;if(e.file==null||blank(e.file))throw Error(`can't touch blank path`);let r=basename2(e.file);if(!isValidFilename(r))throw Error(`Invalid filename: ${JSON.stringify(r)}`);let a=toNativePath_(e.file);n&&await mkdirp_(dirname2(e.file));let o=defer(()=>statMaybe(e.reference?.nativePath)),s=e.mtimeMs!=null||e.atimeMs!=null||e.btimeMs!=null||e.reference!=null,c=defer(()=>s?statMaybe(a,LogLevels.trace):void 0),l=async e=>mapNumeric((await c())?.[e],Math.round),u=Math.round(toMs(e.mtimeMs)??(await o())?.mtimeMs??await l(`mtimeMs`)??Date.now()),d=Math.round(toMs(e.atimeMs)??(await o())?.atimeMs??await l(`atimeMs`)??u),f=toMs(e.btimeMs);try{if(isMac&&f!=null){let e=(await statMaybe(a))?.birthtimeMs;e!=null&&e>f&&await thenOrTimeoutError((0,import_promises11.utimes)(a,new Date(f),new Date(f)),statTimeoutMs())}await thenOrTimeoutError((0,import_promises11.utimes)(a,new Date(d),new Date(u)),statTimeoutMs())}catch(r){if(n&&r.code===`ENOENT`)await thenOrTimeoutError((0,import_promises11.appendFile)(a,``),statTimeoutMs()),s&&await touch_({...e,ensureFile:!1});else throw r}}var import_node_events=require("node:events"),import_node_fs16=require("node:fs"),PathRoles={"BaseFile.watchUntil":`watched-path`,"FsLock.acquire_":`lock-directory`,FileWatcher:`watched-path`,checkFileWatcherStatus:`temporary-directory`,LogFileMonitor:`log-file`},diagnosticsByError=new WeakMap;function watchWithDiagnostics(e,n,r,a){let o=performance.now(),s=Error(`Filesystem watcher created`);Error.captureStackTrace(s,watchWithDiagnostics);let c={owner:a,pathRole:PathRoles[a],storageKind:/^\/\/(?:\?\/UNC\/|[^?./])/i.test(e.replace(/\\/g,`/`))?`unc`:`non-unc`,backend:`node:fs.watch`,recursive:n.recursive??!1,persistent:n.persistent??!0,creationStack:s.stack?.split(`
|
|
493
|
+
`).slice(0,13).join(`
|
|
494
|
+
`).slice(0,8192)},l=(e,n)=>{e instanceof Error&&!diagnosticsByError.has(e)&&diagnosticsByError.set(e,{...c,phase:n,ageMs:Math.floor(performance.now()-o)})};try{n.recursive===!0&&(0,import_node_fs16.statSync)(e);let a=(0,import_node_fs16.watch)(e,n,r);return a.on(import_node_events.errorMonitor,e=>l(e,`async`)),a}catch(e){throw l(e,`setup`),e}}var import_node_fs17=__toESM(require("node:fs")),import_promises12=require("node:stream/promises"),import_node_zlib=require("node:zlib"),import_node_stream2=require("node:stream"),import_node_string_decoder=require("node:string_decoder"),DefaultLineReaderOptions={trimStart:!1,trimEnd:!1,onlyStreamFullLines:!1},LineReader=class extends import_node_stream2.Transform{#e=``;#t;#n;constructor(e={}){super({objectMode:!0}),this.#n={...DefaultLineReaderOptions,...e}}#r(e,n){let r=Buffer.isEncoding(n)?n:`utf8`;return this.#t??=new import_node_string_decoder.StringDecoder(r),this.#t.write(e)}#i(e){let n=String(e);return n===``?``:this.#a()+n}#a(){let e=this.#t?.end()??``;return this.#t=void 0,e}#o(e){if(e==null)return;let n=this.#n.trimStart?e.trimStart():e;return n=this.#n.trimEnd?n.trimEnd():n,n===``?void 0:n}_transform(e,n,r){try{let a=Buffer.isBuffer(e)?this.#r(e,n):this.#i(e);this.#e&&=(a=this.#e+a,``);for(let e of yieldSplit(a,/\n/g)){if(!e.endsWith(`
|
|
495
|
+
`)){this.#e=e;break}let n=this.#o(e);n!==void 0&&this.push(n)}r()}catch(e){r(e)}}_flush(e){if(this.#e+=this.#a(),!this.#n.onlyStreamFullLines){let e=this.#o(this.#e);e!=null&&(this.push(e),this.#e=``)}e()}},import_node_stream3=require("node:stream"),ReadableBuffer=class extends import_node_stream3.Readable{constructor(e){super(),this.push(e),this.push(null)}},import_node_stream4=require("node:stream"),WritableToBuffer=class extends import_node_stream4.Writable{deferred=new Deferred2(`WritableToBuffer`);_buf=[];constructor(e){super(e),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,n,r){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,n)),r()}},logger19=lazy2(()=>mkLogger(`fs.zcat`));async function zpipe_(e,n,r){let a=await zCopyToBuffer_(e);if(r?.start!==void 0||r?.end!==void 0){let e=r?.start??0,o=r?.end??a.length,s=a.subarray(e,o+1);return(0,import_promises12.pipeline)(new ReadableBuffer(s),n)}let o=[],s=import_node_fs17.default.createReadStream(e,{autoClose:!0}).on(`error`,e=>o.push(e)),c=e.toLowerCase(),l=c.endsWith(`.gz`)?(0,import_node_zlib.createGunzip)().on(`error`,e=>o.push(e)):c.endsWith(`.br`)?(0,import_node_zlib.createBrotliDecompress)().on(`error`,e=>o.push(e)):null;return(l?(0,import_promises12.pipeline)(s,l,n):(0,import_promises12.pipeline)(s,n)).finally(()=>{if(isNotEmpty(o))throw new WrappedError(`zPipe(`+e+`) failed`,{causes:o,path:e})})}async function zCopyToBuffer_(e,n){let r=new WritableToBuffer;if(n?.start!==void 0||n?.end!==void 0)return await zpipe_(e,r,n),await r.buffer;let a=import_node_fs17.default.createReadStream(e,{autoClose:!0}),o=e.toLowerCase(),s=o.endsWith(`.gz`)?(0,import_node_zlib.createGunzip)():o.endsWith(`.br`)?(0,import_node_zlib.createBrotliDecompress)():null;return s?await(0,import_promises12.pipeline)(a,s,r):await(0,import_promises12.pipeline)(a,r),await r.buffer}function isBaseFile(e){return isSimpleFile(e)&&e instanceof BaseFile}var cache2=lazy2(()=>new FileCache({name:`fs.BaseFile`,clearOnFileChange:!0})),instanceCount=0,BaseFile=class e{constructor(e,n){if(this.dirent=n,n!=null)this.nativePath=n.nativePath,this.dir=n.dir,this.base=n.base,this.name=n.name,this.ext=n.ext;else{this.nativePath=e;let n=parseNativePath(this.nativePath);this.dir=n.dir,this.base=n.base,this.name=n.name,this.ext=n.ext}this.posixPath=native2posix(this.nativePath)}dirent;$id=instanceCount++;bflog=lazy2(()=>mkLogger(`fs.BaseFile`,{file:this.nativePath}));static attrTTL=3*minuteMs;posixPath;nativePath;dir;base;name;ext;toJSON(){return{nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[import_node_util11.default.inspect.custom](){return this.toLogJSON()}static async withFastestAccess(e){let n=compact(e);return n[leastIndex(await excludeWaitFromEnclosingTimer(()=>Promise.all(n.map(e=>e.shaMs()))))]}static forPosix(n){return n instanceof e?n:this.for(n.split(`/`).join(import_node_path27.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(n,r){if(n instanceof e)return n;let a=isSimpleFile(n)?n.nativePath:toS(n);if(blank(a))throw Error(`BaseFile.for(): empty nativePathOrFile`);let o=cache2().get(a);if(o!=null)return o;let s=resolve2(a),c=new e(s,r);return cache2().set(a,c),cache2().set(s,c),c}static forMaybe(n){return notBlank(n)?e.for(n):void 0}static clear(e){return ee().emit(`fileChanged`,e)}for(n,r){return e.for(n,r)}forDirectoryEntry(n){return e.for(n.nativePath,n)}forChildDirent(e){return this.forDirectoryEntry(DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingSimpleDirent(e){return this.forDirectoryEntry(DirectoryEntry.fromSimpleDirent(this.dir,e))}forSiblingDirent(e){return this.forDirectoryEntry(DirectoryEntry.fromDirent(this.dir,e))}clearIfChanged(){if(!this.clearable())return this;let e=statSync(this.nativePath);return this.#r!=null&&!eqlFileMeta(this.#r,e)||this.dirent!=null&&!eqlFileMeta(this.dirent,e)?this.clear({emit:!0}):(e!=null&&this.#e!=null&&isRacyMtime(e.mtimeMs,this.#e)&&(this.#t.unset(),this.#e=void 0),this)}clearable(){return this.#r!=null||this.dirent!=null}clear({emit:e}={}){return e===!0&&ee().emitSync(`fileChanged`,this.nativePath),this.dirent=void 0,this.#t.unset(),this.#e=void 0,this.#r=void 0,this}clearThisAndParent(){return ee().emitSync(`fileChanged`,this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){let e=resolve2(this.nativePath);return e===this.nativePath?this:this.for(e)}$eql(e){return e!=null&&eqlPath(this,e)}get isUNC(){return isUNC(this.nativePath)}get baseWithParent(){return(this.isRoot?`/`:this.parent().isRoot?`/`+this.base:(this.parent().parent().isRoot?`/`:``)+this.parent().base+`/`+this.base).normalize()}get baseWithGrandparent(){return(this.isRoot?`/`:this.parent().isRoot?this.baseWithParent:this.parent().baseWithParent+`/`+this.base).normalize()}posixPathFrom(e){return posixPathFrom(e,this)}async directoryEntry(){let e=await this.stat();return this.dirent??=e==null?void 0:new DirectoryEntry(this.dir,new StatDirent(this.base,e))}directoryEntrySync(){return this.dirent??=map(this.statSync(),e=>new DirectoryEntry(this.dir,new StatDirent(this.base,e)))}#e;#t=lazy2(async()=>{let e=await this.directoryEntry();return this.#e=Date.now(),e?.children()});async childDirectoryEntries(e){let n=await this.#t();if(n==null||e==null||isEmpty(n))return n;let r=[];for(let a of n)!0===await e(a)&&r.push(a);return r}_directoryEntryChild(e){return this.for(import_node_path27.default.join(this.nativePath,e.base),e)}async childNames(){return(await this.childDirectoryEntries())?.map(e=>e.base)}async resolve_(){return await this.#n()??(this.clearThisAndParent(),this.#n())}async#n(){let e=(await readdir_(this.dir)).filter(e=>equalsIgnoreCase(e.basename,this.base)),n=leastBy(e,e=>hamming(e.basename,this.base));return this.bflog().tap({msg:`resolve()`,result:n?.basename===this.base?this:map(n,e=>this.forSiblingSimpleDirent(e)),meta:{sibs:e}})}async*iterateDir_(){for await(let e of iterateDir_(this.nativePath))yield this.forSiblingDirent(e)}async children_(e){let n=await readdir_(this.nativePath);return e!=null&&await filterInPlaceAsync(n,e),n.map(e=>this.forChildDirent(e))}async children(e){return await this.isDirectory()?(await this.childDirectoryEntries(e))?.map(e=>this._directoryEntryChild(e)):void 0}async childFiles(e){return(await this.childDirectoryEntries(async n=>n.isFile()&&(e==null||!0===await e(n))))?.map(e=>this._directoryEntryChild(e))}async childDirectories(e){return(await this.childDirectoryEntries(async n=>n.isDirectory()&&(e==null||!0===await e(n))))?.map(e=>this._directoryEntryChild(e))}childrenSync(){return this.descendantsSync(void 0,()=>!1)}childFilesSync(){return this.descendantsSync(e=>e.isFileSync(),()=>!1)}descendantsSync(e,n){let r=[];return this.trapSync(`childrenSync`,()=>{for(let a of(0,import_node_fs18.readdirSync)(this.nativePath,{withFileTypes:!0})){let o=DirectoryEntry.fromDirent(this.nativePath,a);a.isDirectory()&&!1!==n?.(o)&&r.push(...this.join(a.name).descendantsSync(e,n)),!1!==e?.(o)&&r.push(this.join(a.name))}}),r}async hasChildren(e){if(isEmpty(e))try{if(await this.isDirectory())for await(let e of iterateDir_(this.nativePath))return!0;return!1}catch(e){return this.bflog().warn(`hasChildren()`,e),!1}for(let n of e)if(!await exists((0,import_node_path27.join)(this.nativePath,n)))return!1;return!0}async*descendantsIterable(e,n){for await(let r of iterateDir_(this.nativePath)){let a=DirectoryEntry.fromDirent(this.nativePath,r),o=this._directoryEntryChild(a);r.isDirectory()&&!1!==await n?.(a)&&(yield*o.descendantsIterable(e,n)),!1!==await e?.(a)&&(yield o)}}async*descendantFilesIterable(e,n){for await(let r of this.descendantsIterable(e,n))await r.isFile()&&(yield r)}async descendants(e,n){return iterToA(this.descendantsIterable(e,n))}async siblings(e){let n=this.parent();return(await this.siblingDirectoryEntries(e))?.map(e=>n._directoryEntryChild(e))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries(async n=>n.base!==this.base&&(e==null||!0===await e(n)))}get pathnames(){return splitNativePath(this.nativePath)}pathsForDateParsing(){return compactBlanks([...this.isRoot?[]:this.parent().pathnamesWithoutDrive,leastBy(bname(this.name),e=>e.length)])}get pathnamesWithoutDrive(){return isWin?this.pathnames.slice(1):this.pathnames}get depth(){return pathDepth(this)}get isRoot(){return 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,n){return containedByNativePath({ancestor:this,descendant:e,...n})}isDescendantOf(e){return containedByNativePath({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return e!=null&&(this.nativePath===toNativePath_(e)||this.isDescendantOf(e))}selfAndParents(e){return[this,...this.isRoot||e<=0?[]:this.parent().selfAndParents(e-1)]}ancestor(e=1){return this.isRoot&&e>0?void 0:e===0?this:this.parent().ancestor(e-1)}findSelfOrAncestor(e){return e(this)?this:this.isRoot?void 0:this.parent().findSelfOrAncestor(e)}parents(){let e=this.parent();return this.isRoot?[]:[...e.parents(),e]}sibling(e){return this.parent().join(e)}withNameSuffix(e){return this.sibling(this.name+e+this.ext)}withSuffix(e){return this.sibling(this.base+e)}withExt(e){let n=normalizeExt(e);return n==null?this.sibling(this.name):this.sibling(this.name+`.`+n)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return isEmpty(e)||eql([`.`],e)||e.every(blank)?this:isAbsolute2(e[0])?this.for(import_node_path27.default.join(...e)):this.for(import_node_path27.default.join(this.nativePath,...e))}child(...e){if(isEmpty(e))return this;let n=flatten(e.map(e=>e.split(import_node_path27.default.sep))).filter(e=>e!==`..`);return this.join(...n)}async trap(e,n,r=`warn`){try{return await timeExcludingNested({name:`fs.`+e,thunk:n,meta:{path:this.nativePath}})}catch(n){this.bflog().log(r,`trap: ${e}() failed`,{error:n});return}}trapSync(e,n,r){try{return timeSync({name:`fs.`+e,t:n})}catch(n){this.bflog().log(r??`warn`,`${e}() failed`,{error:n});return}}stat_(){return stat_(this.nativePath)}#r=void 0;async stat(e){return(e?.refresh??!1)&&(this.#r=void 0),this.#r??=await statMaybe(this.nativePath,e?.logLevel??`trace`)}statSync(e){return(e?.refresh??!1)&&(this.#r=void 0),this.#r??=statSync(this.nativePath)}async exists(e){return(e?.refresh??!1)&&(this.dirent=void 0),this.dirent!=null||await this.stat(e)!=null}existsSync(e){return(e?.refresh??!0)&&(this.dirent=void 0),this.dirent!=null||this.statSync(e)!=null}async notExists(e){return await this.stat({refresh:!0,...e})==null}async mtime(){return(await this.stat())?.mtime}async mtimeMs(e){let n=await this.stat(e);return n==null?void 0:Math.floor(n.mtimeMs)}mtimeMsSync(e){return mapNumeric(this.statSync(e)?.mtimeMs,Math.floor)}async statTimes(){let e=await this.stat();return e==null?void 0:statTimes(e)}async maxStatMs(){let e=await this.statTimes();return e==null?void 0:max2(e)}async minStatMs(){let e=await this.statTimes();return e==null?void 0:min(e)}async minStatDate(){let e=await this.minStatMs();return e==null?void 0:new Date(e)}async size(e){return(await this.stat(e))?.size}async size_(){return(await this.stat_()).size}async isReadable(){return await canAccess(this.nativePath,{r:!0})}async isReadWriteExecutable(){return isStatRWX(await this.stat(),this.nativePath)}async readWriteExecutableError(){return statRWXError(await this.stat(),this.nativePath)}async readWriteExecutableError_(){return statRWXError(await this.stat_(),this.nativePath)}isReadWriteExecutableSync(){return isStatRWX(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return isStatRWX(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){let e=await this.stat();return e?.isDirectory()===!0&&isStatRWX(e,this.nativePath)}async maybeReadWriteDirectory(){return await this.isFile()===!0?!1:await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory()}isHiddenBasename(){return isHiddenBasename(this.base)}async isEmptyOrMissing(e=0){if(await this.isDirectory())return!isNotEmpty(await this.childNames());{let n=await this.size();return n==null||n<=e}}isNonEmpty(e=1){return thenNot(this.isEmptyOrMissing(e-1))}async isEmptyFile(e=1){let n=await this.stat({logLevel:`trace`});return n==null||n.isFile()&&n.size<e}async isNonEmptyFile(e=1){let n=await this.stat({logLevel:`trace`});return n!=null&&n.isFile()&&n.size>=e}async isDirectory_(){return this.dirent==null?(await this.stat_()).isDirectory():this.dirent.isDirectory()}async isDirectory(e){return!0===e?.refresh&&(this.dirent=void 0),this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return thenNot(this.isDirectory())}isDirectorySync(e){return!0===e?.refresh&&(this.dirent=void 0),this.dirent?.isDirectory()??this.statSync(e)?.isDirectory()??!1}async nearestDir(){return await this.isDirectory()?this:this.parent()}async isFile_(){if(this.dirent!=null)return this.dirent.isFile();let e=await this.stat_();return e!=null&&e.isFile()}async isFile(){return!0===await this.trap(`isFile()`,()=>this.isFile_())}isFileSync(){return this.dirent==null?opt(this.statSync()).filter(e=>e.isFile()).isDefined:this.dirent.isFile()}async rmdir(e=`warn`){return this.clear(),await this.trap(`rmdir`,async()=>(await retryOnReject_(()=>(0,import_promises13.rmdir)(this.nativePath),{maxRetries:8,retryDelay:500,errorIsRetriable:isRetriableError}),!0),e)??!1}rmdirSync(e=`warn`){return this.clear(),this.trapSync(`rmdirSync`,()=>{let e=8;for(let e=0;e<=8;e++)try{return(0,import_node_fs18.rmdirSync)(this.nativePath),!0}catch(n){if(e<8&&isRetriableError(n)===!0)continue;throw n}return!0},e)??!1}async mkdirp_(){if(this.isRoot||await this.isDirectory({refresh:!0}))return this;if(await mkdirp_(this.nativePath),!1===await untilTrue(()=>this.isDirectory({refresh:!0}),{timeoutMs:2*secondMs,intervalMs:200}))throw Error(`Failed to mkdirp `+this);return this.clearThisAndParent()}async mkdirp(){return this.isRoot||await this.isDirectory({refresh:!0})?this:this.trap(`mkdirp`,async()=>this.mkdirp_())}mkdirpSync_(){return mkdirpSync_(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync(`mkdirpSync`,()=>this.mkdirpSync_())}sha_(){return fileSha_(this.nativePath)}async sha(){return this.trap(`sha`,()=>this.sha_())}async shaMs(){return this.trap(`shaMs`,async()=>(await fileShaMeta_(this,{autoInvalidate:!1})).elapsedMs)}async sha256_(){let e=(0,import_node_crypto4.createHash)(`sha256`);return await(0,import_promises14.pipeline)([(0,import_node_fs18.createReadStream)(this.nativePath),e]),e.digest(`hex`)}async readJson_(){return parseJSON((await(0,import_promises13.readFile)(this.nativePath)).toString())}async readJson(e=`warn`){return await this.isNonEmptyFile()?this.trap(`readJson`,()=>this.readJson_(),e):void 0}readJsonSync(e){return this.trapSync(`readJsonSync`,()=>parseJSON((0,import_node_fs18.readFileSync)(this.nativePath).toString()),e)??void 0}readFileSync_(){return(0,import_node_fs18.readFileSync)(this.nativePath)}readFile_(){return(0,import_promises13.readFile)(this.nativePath)}readFile(e=`warn`){return this.trap(`readFile`,()=>this.readFile_(),e)}async readText_(){return bufferToString(await this.readFile_())}readText(e=`warn`){return this.trap(`readTextFile`,()=>this.readText_(),e)}async zReadFile_(e){return zCopyToBuffer_(this.nativePath,e)}async zcat(e){return this.trap(`zcat`,async()=>{let n=await this.zReadFile_(e);return n==null?void 0:toS(n)})}async readLines(e=`warn`){let n=await this.readText(e);return n==null?void 0:splitLines(n)}readFileSync(e=`warn`){try{return(0,import_node_fs18.readFileSync)(this.nativePath).toString()}catch(n){this.bflog().log(e,`readFileSync() failed`,{error:n});return}}async writeText_(...e){return await writeText_(this.nativePath,...e),this}writeTextSync_(...e){return writeTextSync_(this.nativePath,...e),this}async writeFile_(e){return await writeFile_(this.nativePath,e),this}writeJsonSync(e,n){return this.trapSync(`writeJsonSync`,()=>this.writeJsonSync_(e,n))}writeJsonSync_(e,n){let r=n?.sortKeys===!0?sortedKeys(e):e;writeFileSync_(this.nativePath,stringify(r,n?.spaces)+`
|
|
496
|
+
`)}async writeJson(e,n){return this.trap(`writeJson`,()=>this.writeJson_(e,n))}async writeJson_(e,n){await mkdirp_(this.dir);let r=n?.sortKeys===!0?sortedKeys(e):e;return await(0,import_promises13.writeFile)(this.nativePath,stringify(r,n?.spaces)+`
|
|
497
|
+
`,{...omit(n??{},`spaces`,`sortKeys`),flush:!0}),this.clearThisAndParent(),this}async matchesContent(e){let n=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);if(n[0]==null||n[1]==null||n[0].size!==n[1].size)return!1;let r=await excludeWaitFromEnclosingTimer(()=>Promise.all([this.sha(),e.sha()]));return r[0]===r[1]}async touch(e={}){return this.trap(`touch`,()=>this.touch_(e))}async touch_(e={}){return await touch_({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap(`utimes`,async()=>(await touch_({...e,file:this,ensureFile:!1}),this.clearThisAndParent(),this))}async rm(e=`warn`){return this.unlink(e)}async unlink(e=`warn`){return this.bflog().debug(`unlink()`),this.trap(`unlink`,()=>this.unlink_(),e)}unlinkSync_(){try{(0,import_node_fs18.unlinkSync)(this.nativePath)}catch(e){if(e.code!==`ENOENT`)throw e}finally{this.clearThisAndParent()}}unlinkSync(e=`info`){return this.trapSync(`unlinkSync`,()=>this.unlinkSync_(),e)}async unlink_(){try{await(0,import_promises13.unlink)(this.nativePath)}catch(e){if(e.code!==`ENOENT`)throw e}return this.clearThisAndParent()}async rmrf(e=`info`){return this.trap(`rmrf`,()=>this.rmrf_(),e)}async rmrf_(){let e=await this.isDirectory({refresh:!0});return await retryOnReject_(()=>(0,import_promises13.rm)(this.nativePath,{recursive:e,force:!0}),{maxRetries:ending()?1:3,timeoutMs:0,retryDelay:secondMs,errorIsRetriable:isRetriableError}),this.clearThisAndParent()}async#i(e,n){return this.trap(`pipeTo(`+e+`)`,async()=>{let r=await this.sibling(e).ensureNew_();return await(0,import_promises14.pipeline)([(0,import_node_fs18.createReadStream)(this.nativePath,{autoClose:!0}),n,(0,import_node_fs18.createWriteStream)(r.nativePath,{autoClose:!0})]),await this.unlink(),r})}async gzip(){return this.#i(this.base+`.gz`,import_node_zlib2.default.createGzip())}async compressBrotli(){return this.#i(this.base+`.br`,import_node_zlib2.default.createBrotliCompress())}async ensureFile_(){return await ensureFile_(this.nativePath),this.clearThisAndParent()}ensureFile(){return this.trap(`ensureFile`,()=>this.ensureFile_())}ensureFileSync_(){return ensureFileSync_(this.nativePath),this.clearThisAndParent()}ensureNewNativePath_(e){return ensureNewNativePath_({nativePath:this.nativePath,...e})}async ensureNew_(e={}){return this.for(await this.ensureNewNativePath_(e)).clearThisAndParent()}ensureNewSync_(e={}){return this.for(ensureNewNativePathSync_({nativePath:this.nativePath,...e}))}async chmod_(e){return await(0,import_promises13.chmod)(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(n){this.bflog().warn(`failed to chmod to `+e.toString(8),n);return}}chmodSync(e){try{return(0,import_node_fs18.chmodSync)(this.nativePath,e),this.clear()}catch(n){this.bflog().warn(`failed to chmod to `+e.toString(8),n);return}}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return timeExcludingNested({name:`fs.childWithSameContents`,thunk:async()=>{if(!await this.isDirectory())return;let n=await e.size();if(n==null)return;if(!this.$eql(e.parent())){let n=this.join(e.base);if(await e.matchesContent(n))return n}let r=await this.children(async r=>!r.isNameHidden()&&n===r.size()&&r.nativePath!==e.nativePath);if(isEmpty(r))return;let a=await e.sha();if(a!=null){for(let e of r.sort((e,n)=>-diceCoeff2(e.base,n.base)).slice(0,64))if(await e.sha()===a)return e}}})}watchUntil(e){let n=new Deferred2(`watchUntil(`+this.nativePath+`)`);e.timeoutMs>0&&n.setTimeout(e.timeoutMs);let r=Math.ceil(toGt0(e.intervalMs)??500),a=trailingThrottle({minDelayMs:clamp(25,secondMs,Math.ceil(r/5)),fn:async(r,a)=>{try{if(n.isSettled)return;let o=await e.f(r,denull(a));this.bflog().debug(`watchUntil().debouncedApply`,{result:o,event:r,filename:a}),o!=null&&o!==!1&&(e.accept?.(o)??!0)&&n.resolve(o)}catch(e){n.reject(e)}}}),o=setInterval(()=>a(),r);e.persistent||o.unref();let s=r=>{n.isSettled||(e.recursive?n.reject(r):this.bflog().warn(`fs.watch failed; continuing with polling only`,{error:r,opts:e}))};if(n.finally(()=>{a.reset(),clearInterval(o)}),e.recursive&&!_useFsWatch)return n.reject(Error(`Recursive watching requires useFsWatch`));if(a(),_useFsWatch)try{let r=watchWithDiagnostics(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:`utf8`},a,e.watcherOwner??`BaseFile.watchUntil`);return r.on(`error`,e=>{r.close(),s(e)}),n.finally(()=>{r.close()}),n}catch(e){s(e)}return n}},_useFsWatch=!0;function useFsWatch(e){_useFsWatch=e}var import_node_child_process2=require("node:child_process"),import_node_fs19=require("node:fs"),import_node_os10=require("node:os"),import_node_process17=__toESM(require("node:process")),IndexedHeader=class{text;greedyLeft;indexOf;leftIdx;rightIdx;constructor(e){this.text=isString(e)?e:e.text,this.greedyLeft=isString(e)?!1:e.greedyLeft??!1}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}},logger20=lazy2(()=>mkLogger(`Fixed`));function parseFixed(e,n,r=!0){return new Fixed(e,n,r).entries}var Fixed=class{constructor(e,n,r=!0){this.warnIfMissingHeaders=r,this.rows=splitLines(n),this.headerRow=this.rows.shift();let a=max_(...this.rows.map(e=>e.length));this.blankColumns=new Set(range(0,a).filter(e=>this.rows.every(n=>blank(n[e])))),this.headers=this.extractHeaders(e.map(e=>new IndexedHeader(e))),this.entries=this.rows.map(e=>this.headers.map(n=>n.toEntry(e))).map(e=>fromEntries(e)).filter(e=>values(e).some(notBlank))}warnIfMissingHeaders;headers;headerRow;skippedHeaders=[];rows;entries;blankColumns;firstBlankColumn(e,n){for(let r=e;r!==n;n>e?r++:r--)if(this.blankColumns.has(r))return r;if(this.blankColumns.has(n))return n;if(e===0||n===0)return 0}extractHeaders(e){let n=new RegExp(e.map(e=>(e.greedyLeft?`\\s+`:`\\b`)+escapeRegExp(e.text)+`\\b`).join(`|`),`gi`),r=[],a,o=0;for(;(a=n.exec(this.headerRow))!=null;){let s=this.headerRow.substring(o,a.index);blank(s)||(logger20().debug(`extractHeaders: skipping over unknown header`,{skippedOver:s,m_index:a.index}),this.skippedHeaders.push(s.trim()));let c=this.headerRow.substring(a.index,n.lastIndex),l=a.index+(indexOfNonSpace(c)??0),u=a.index+(lastIndexOfNonSpace(c)??c.length),d=c.trim(),f=e.find(e=>e.text===d);if(f==null||l==null||u==null)this.skippedHeaders.push(d),logger20().debug(`extractHeaders: internal error`,{matched:c,match:a,left:l,right:u});else{let e=last(r);if(r.push(f),e!=null){let n=e.rightIdx+(indexOfNonSpace(s)??s.length)+1;e.rightIdx=f.greedyLeft?this.firstBlankColumn(e.rightIdx,n):this.firstBlankColumn(n,e.rightIdx)}let n=max_(e?.rightIdx,a.index-(lastIndexOfNonSpace(s)??s.length));f.leftIdx=f.greedyLeft?this.firstBlankColumn(n,l):this.firstBlankColumn(l,n),f.rightIdx=u}o=n.lastIndex}let s=last(r);return s!=null&&(s.rightIdx=blank(this.headerRow.slice(o))?max_(...this.rows.map(e=>e.length)):o),r}},WinDateRe=/Date\((\d+)\)/;function pwshJsonDate(e){return opt(e).flatMap(e=>WinDateRe.exec(e)).flatMap(e=>e[1]).flatMap(toInt).filter(e=>within(0,Date.now()+dayMs,e)).map(e=>new Date(e)).get()}var import_promises15=require("node:fs/promises"),logger21=lazy2(()=>mkLogger(`fs.ReadFile`));async function readFileMaybe(e,n=LogLevels.debug){try{return await(0,import_promises15.readFile)(e)}catch(r){logger21().log(n,`.readFileMaybe(`+e+`)`,r);return}}var import_batch_cluster=require("batch-cluster");function existingPids(e){return toA(e).filter(e=>(0,import_batch_cluster.pidExists)(e))}function waitForPidExit(e,n){return untilTrue(()=>!(0,import_batch_cluster.pidExists)(e),{timeoutMs:n,intervalMs:250})}var logger22=lazy2(()=>mkLogger(`proc.ps`));function isProcEntry(e){return e!=null&>0(e.pid)&&e.start!=null&¬Blank(e.cmd)}async function pidInfos(e){if(isLinux)return pidInfoProc(e);let n=existingPids(e),r=[];for(let e of batches(n,20)){let n=await(isWin?pidInfoWin:pidInfoPosix)(e);if(n==null)return;r.push(...n)}let a=r.filter(e=>isProcEntry(e)&&n.includes(e.pid));return logger22().tap({msg:`pidInfos()`,result:a,meta:{pids:e}})}function win2pe(e){return e.map(e=>({pid:e.Id,start:pwshJsonDate(e.StartTime),cmd:e.ProcessName}))}var PsWinCmd=`Get-Process`,PsWinSelectObj=`| Select-Object -Property Id,ProcessName,StartTime`;function pidToS(e){return uniq([...e.filter(gt0),import_node_process17.default.pid]).join(`,`)}async function pidInfoWin(e){if(PowerShell.instance().ended)return;let n=[PsWinCmd,`-Id`,pidToS(e),`-ErrorAction SilentlyContinue`,PsWinSelectObj].join(` `),r=await PowerShell.instance().executeJsonToA(n);return r==null?void 0:win2pe(r)}var stdoutOpts={maxBuffer:1048576,timeoutMs:15*secondMs,ignoreExitCode:!0,ignoreStderr:!0};function psStdout2ProcEntry(e){return blank(e)?[]:parseFixed([`PID`,{text:`STARTED`,greedyLeft:!0},`COMMAND`],e).map(e=>({pid:toInt(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:toS(e.COMMAND)}))}async function pidInfoPosix(e){return psStdout2ProcEntry((await stdoutResult_(`ps`,[`-p`,pidToS(e),`-wwwo`,`pid,lstart,command`],{...stdoutOpts,timerName:`proc.ps`,ignoreExitCode:!0})).result)}async function pidInfoProc(e){let n=[];for(let r of e)n.push(parseProcStat(await readFileMaybe(`/proc/`+r+`/stat`)));return logger22().tap({msg:`pidInfoProc`,result:compact(n)})}var clk_tck=lazy2(()=>{try{if(isLinux)return toGt0((0,import_node_child_process2.spawnSync)(`getconf`,[`CLK_TCK`],{shell:!1}).stdout?.toString())??100}catch(e){logger22().warn(`clk_tck failed`,{error:e})}return 100}),BtimeRE=/^btime (?<btime>\d+)$/m,btimeTs=lazy2(()=>{if(isLinux)try{let e=(0,import_node_fs19.readFileSync)(`/proc/stat`,`utf8`),n=toGt0(BtimeRE.exec(e)?.groups?.btime);if(n!=null)return n*secondMs}catch{}return Date.now()-(0,import_node_os10.uptime)()*secondMs}),ProcStatRE=/(?<pid>\d+) \((?<comm>.+)\) (?<state>[A-Z]) (?:-?\d+ ){18}(?<starttime>\d+)/i;function parseProcStat(e){let n=ProcStatRE.exec(toS(e))?.groups,r=toInt(n?.pid),a=n?.comm,o=toInt(n?.starttime);return gt0(r)&&!blank(a)&>0(o)?{pid:r,cmd:a,start:new Date(btimeTs()+o/clk_tck()*secondMs),state:n?.state}:void 0}var logger23=lazy2(()=>mkLogger(`proc.Pids`)),AllowableStartSlopMs=10*secondMs;function matchesPidfileInfo(e,n){if(e==null||n==null||e.pid!==n.pid)return!1;let r=map(n.start,e=>e.getTime()),a=e.startTime;return gt0(r)&>0(a)&&Math.abs(r-a)<AllowableStartSlopMs}function killPidWinTaskkill(e,n=!1){let r=[`/PID`,toS(toInt(e)),`/T`];n&&r.push(`/F`),import_node_child_process3.default.execFile(`taskkill`,r)}async function killPidWin(e,n=!1){if(ending()||PowerShell.instance().ended)killPidWinTaskkill(e,n);else try{let r=compact([`Stop-Process`,`-Id`,toInt(e),n?`-Force`:void 0]).join(` `);await PowerShell.instance().execute(r,identity)}catch(r){logger23().warn(`killWin(): pwsh error, using TASKKILL`,{error:r}),killPidWinTaskkill(e,n)}}async function killPidWithNode(e,n=!1){try{import_node_process18.default.kill(e,n?`SIGKILL`:`SIGTERM`)}catch(e){if(!String(e).includes(`ESRCH`))throw e}}async function killPid(e,n=!1,r=!0){return gt0(e)?e===1?logger23().warn(`killPid(): refusing to kill init`,{pid:e}):e===import_node_process18.default.pid||e===import_node_process18.default.ppid?logger23().warn(`killPid(): cannot self-terminate`,{pid:e}):(logger23().log(n?`warn`:`debug`,`killPid`,{pid:e,force:n}),n&&r&&await Pids.instance()?.onKill(e),isWin?killPidWin(e,n):killPidWithNode(e,n)):logger23().warn(`killPid(): invalid pid`,{pid:e})}var Pids=class e extends EndableInterval{constructor(e,n=new SequentialTaskQueue){super({name:`proc.Pids`,intervalMs:isSyncService()?5*minuteMs:0,initialDelayMs:minuteMs,callback:()=>this.killOldProcs(),rank:EndableRanks.postdb}),this.pidsDir=e,this.pidsDir.mkdirpSync()??logger23().warn(`Failed to create PID directory`,{pidsDir:this.pidsDir.nativePath}),this.#e=n}pidsDir;static instance=lazy2(()=>map(configDir(),n=>new e(BaseFile.for(n).join(`pids`))));#e;async addPid_(e,n,r=!1){return this.#e.enqueue(()=>this.#t(e,n,r))}async#t(e,n,r=!1){if(e==null)throw Error(`undefined info`);let a=e.pid;if(!gt0(a))throw Error(`undefined pid`);if(!(0,import_batch_cluster2.pidExists)(a)){logger23().debug(`addPid(): no-op, pid already gone during write`,{info:e,start:n});return}let o=this.#n(e.pid),s=opt(Try(()=>parseNativePath(e.cmd).base)).filter(notBlank).getOrElse(()=>e.cmd),c=n.getTime(),l=await o.readJson();if(!r&&l!=null&&l.startTime>=c)return logger23().debug(`addPid(): keeping same or newer pid lifetime`,{info:e,start:n,priorInfo:l}),o;let u={...e,cmd:s,startTime:c};try{return await o.writeJson_(u),logger23().debug(`addPid() wrote `+o,u),o}catch(e){throw logger23().warn(`addPid(): failed to write pidfile`,{error:e,pid:a,file:o.nativePath}),e}}#n(e){return this.pidsDir.join(e+`.json`)}pidfiles(){return this.pidsDir.clear().children(e=>{let n=toInt(e.name);return e.ext===`.json`&&n!=null&&n!==import_node_process18.default.pid})}async pids(e=this.pidfiles()){return compact(toA(await e).map(e=>toInt(e.name)))}async onKill(e,n){return this.#e.enqueue(async()=>{let r=await this.#n(e).readJson();if(r!=null){if(n!=null&&r.startTime!==n.getTime())logger23().debug(`onKill(): pid now belongs to another lifetime`,{pid:e,expectedStart:n,priorInfo:r});else try{return await this.#t({...r,timeoutMs:1},ago(minuteMs),!0)}catch(n){logger23().info(`onKill(): failed to rewrite pidfile`,{pid:e,error:n});return}}})}vacuumOldWip=rateLimited({name:`Pids.vacuumOldWip()`,minCallDelayMs:minuteMs,f:async()=>{let e=Date.now()-2*minuteMs,n=await this.pidsDir.childFiles(async n=>isJsonExt(n)&&isHiddenBasename(n.base)&<(n.mtimeMs(),e));for(let e of toA(n))logger23().warn(`killOldProcs(): deleting old pid WIP, `+e.base),await e.unlink(`debug`)}});killOldProcs=rateLimited({name:`Pids.killOldProcs()`,minCallDelayMs:minuteMs,f:async(e={})=>this.#e.enqueue(async()=>{logger23().info(`killOldProcs()`,e),await this.vacuumOldWip();let n=e.everything??!1,r=e.force??isWin,a=await this.pidfiles(),o=await this.pids(a??[]);if(isEmpty(o))return logger23().info(`killOldProcs(): no pidfiles`),[];let s=[],c=[],l=await pidInfos(o);if(l==null)onError(`Pids.killOldProcs(): failed to get process information`);else{for(let o of a){let a=await o.readJson();if(a==null){logger23().warn(`killOldProcs(): failed to read pidfile `+o.base),await o.unlink(`debug`);continue}let u=a.pid;if(!gt0(u)){logger23().warn(`killOldProcs(): invalid json.pid: unlinking pidfile `+o.base,{json:a,pid:u}),await o.unlink(`debug`);continue}let d=l.find(e=>e.pid===u);if(d==null||!matchesPidfileInfo(a,d)){logger23().debug(`killOldProcs(): pid no longer present: unlinking `+o.base,{json:a,pidEntry:d}),await o.unlink(`debug`),s.push(a);continue}let f=gt0(a.timeoutMs)?a.startTime+a.timeoutMs:void 0,h=!(0,import_batch_cluster2.pidExists)(a.ppid),_=n?`all pids are being shut down`:h?`parent pid ${a.ppid} is gone`:gt(Date.now(),f)?`timed out ${Date.now()-f} ms ago`:lt(a.startTime,e.everythingBefore)?`cleanup everything before `+new Date(e.everythingBefore).toISOString():void 0;_!=null&&(logger23().info(`killOldProcs(): killing`,{reason:_,json:a}),c.push(killPid(u,r||h,!1)),s.push({...a,...d}))}return c.length>0&&await Promise.allSettled(c),s}})})};function addPid(e,n){return Pids.instance()?.addPid_(e,n)}function volumeMetadataTtlMs(){return VolumesSettings.volumeMetadataTtlMs.valueOrDefault}function commandTimeoutMs(){return FilesystemSettings.statTimeoutMs.valueOrDefault}var MinIoRate=MiB/secondMs,BatchClusterObserver=class extends EndableWrapper{constructor(e,n,r=EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,()=>this.#t(),r,e===`worker`?commandTimeoutMs():ShortCommandTimeoutMs),this.t=n;let a=n;a.on(`childStart`,async n=>{if(n.pid==null){this.onError(`No PID returned for `+e,new TimeoutError);return}this.logger.info(`Started child process`,{pid:n.pid}),renice(n.pid).catch(e=>this.onError(`renice failed`,e));let r=new Date;this.#e.set(n,r),addPid({pid:n.pid,ppid:import_node_process19.default.pid,cmd:e,timeoutMs:0},r)?.catch(n=>this.onError(`addPid failed for `+e,n))}),a.on(`startError`,e=>{this.lastStartError=e,this.onError(`failed to start`,e)}),a.on(`taskError`,(e,n)=>{errorToS2(e).match(/\btimeout\b/)!=null&&onTimeout(),this.lastTaskError=e,this.onError(`failed to run `+map(n,e=>e.command),e)}),a.on(`internalError`,e=>{this.lastInternalError=e,this.onError(`internal error`,e)}),a.on(`noTaskData`,(e,r,a)=>{let o=n.options.streamFlushMillis;o<secondMs&&(n.options.streamFlushMillis+=100,this.logger.warn(`on(noTaskData): bumping up streamFlushMillis.`,{prior:o,new:n.options.streamFlushMillis,stout:toS(e),stderr:toS(r),child_pid:a?.pid}))}),a.on(`endError`,e=>{this.logger.error(`observeBatchCluster.endError()`,e)}),a.on(`childEnd`,(n,r)=>{let{exitCode:a,exitSignal:o}=n;this.logger.info(`on(childEnd)`,{pid:n?.pid,name:n?.name,reason:r,exitCode:a,exitSignal:o}),gt0(n?.pid)&&Pids.instance()?.onKill(n.pid,this.#e.get(n)),this.#e.delete(n),!ending()&&!this.t.ended&&n.unexpectedExit&&r.startsWith(`proc.`)&&(o!=null||a!=null&&a!==0)&&onError((o==null?`${e} exited with code ${a}`:`${e} terminated by ${o}`)+FatalErrorFlag,{signal:o??void 0,exitCode:a??void 0,service:e,fatal:!0})})}t;lastStartError;lastInternalError;lastTaskError;#e=new WeakMap;childEndCounts(){return this.t instanceof import_exiftool_vendored.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}#t(){this.logger.info(`onEnd()`,{childEndCounts:this.childEndCounts()});let e=!0;return this.t.end(!0)}onError(e,n){this.t.ended||ending()||isIgnorableError(n)===!0?this.logger.warn(`onError() (ending or ignorable)`,{reason:e,error:n}):onError(this.name+`: `+e,n)}};function spawnTimeoutOptions(){return{spawnTimeoutMillis:commandTimeoutMs(),maxProcAgeMillis:max_(5*minuteMs,commandTimeoutMs())}}function batchClusterOptions(e,n){return{maxProcs:e,maxIdleMsPerProcess:minuteMs,maxTasksPerProcess:Settings2.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:Settings2.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:Settings2.streamFlushMs.valueOrDefault,logger:lazy2(()=>mkLogger(n)),...spawnTimeoutOptions(),taskTimeoutMillis:Settings2.taskTimeoutMs.valueOrDefault}}var import_node_path29=__toESM(require("node:path")),import_node_process21=require("node:process"),import_node_path28=__toESM(require("node:path")),import_node_process20=__toESM(require("node:process")),ProjectDirs=[`data`,`public`,`views`,`tools`],CwdRoot=lazy2(()=>firstDirWithChildDirs([execDir(),import_node_process20.default.cwd(),__dirname]));function firstDirWithChildDirs(e,n=ProjectDirs){let r=uniq(compactBlanks(e));for(let e of r)if(hasChildrenSync(e,n))return e;for(let e of r)for(let r of ancestors(e).slice(0,isPacked()?2:6))if(hasChildrenSync(r,n))return r}var Root=lazy2(()=>{let e=compactBlanks([import_node_process20.default.env.PS_PROJECT_DIR]);return isDocker()?e.push(`/opt/photostructure`):isElectron()&&(isMac?e.push(import_node_path28.default.join(execDir(),`..`,`Resources`)):e.push(import_node_path28.default.join(execDir(),`resources`))),firstDirWithChildDirs(e)??(isMainElectron&&isPacked()?void 0:CwdRoot())??mkLogger(`fs.ProjectDir`).throw(`Failed to find project root.`+FatalErrorFlag,{dirs:e})});function pathTo(...e){return lazy2(()=>{let n=import_node_path28.default.join(Root(),...compact(e));return!n.includes(`.asar`)&&!isReadableDirectorySync(n)&&mkLogger(`fs.ProjectDir`).throw(`Not a readable directory:`+n,{fatal:!0}),n})}var ProjectDir={Root,CwdRoot,Bin:isElectron()?pathTo(`app.asar`,`.webpack`,`main`):pathTo(`bin`),Data:pathTo(`data`),ICC:pathTo(`data`,`icc`),Migrations:pathTo(`data`,`migrations`),Public:pathTo(`public`),Tools:isDocker()||isElectron()&&isPacked()?pathTo(`tools`):pathTo(`tools`,platformArch),Views:pathTo(`views`)},logger24=lazy2(()=>mkLogger(`fs.PathTo`)),MinBinarySize=KiB;async function isRXFile(e,n=MinBinarySize){let r=await statMaybe(e,`trace`);return r!=null&&r.isFile()&>e(r.size,n)&&isStatRX(r,e)}function projectToolsPath(){try{return ProjectDir.Tools()}catch{return}}function pathDirectories(){return uniq(compactBlanks(flatten(compactBlanks([...Settings2.toolPaths.values,projectToolsPath(),...managedToolPaths(),import_node_process21.env.PATH,...defaultPaths()]).map(e=>e.split(import_node_path29.default.delimiter)))))}async function pathTo2({tool:e}){let n=isWin&&blank((0,import_node_path29.extname)(e))?ensureSuffix(e,`.exe`):e,r=pathDirectories();for(let e of r){let r=import_node_path29.default.join(e,n);if(await isRXFile(r))return r}logger24().info(`Failed to find tool`,{tool:e,base:n,dirs:r})}var pingWin=()=>`ping`,Done=`{ready}`,ConvertToEncodedJson=` | ConvertTo-Json -Compress | ForEach-Object { [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($_)) }`;function pwshQuote(e){return`([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(e,`utf8`).toString(`base64`)}')))`}function versionCommand(){return[`function prompt {"${Done}"}`,...mapNotBlankOr(Settings2.powerShellCulture.valueOrDefault,e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`],[])].join(`;`)}var PowerShell=class e extends EndableWrapper{static ensureInstance(){return!0===this._instance?.ended&&(this._instance=void 0),this.instance()}static _instance;static instance(){if(!isWin)throw Error(`PowerShell isn't available on this platform`);return isTest()&&!0===this._instance?.ended&&(this._instance=void 0),this._instance??=new e}static async endInstance(){await this._instance?.end(),this._instance=void 0}bco;pwsh;constructor(){super(`PowerShell`,()=>this.bco.end(),EndableRanks.postdb),this.bco=new BatchClusterObserver(`PowerShell`,new import_batch_cluster3.BatchCluster({processFactory:async()=>execFile2(await this.pwshPath(),Settings2.powerShellArgs.values),logger:()=>mkLogger(`PowerShell`),versionCommand:versionCommand(),pass:RegExp(`^`+escapeRegExp(Done)+`$`,`m`),fail:/$./,exitCommand:`exit`,maxProcs:Settings2.powerShellProcs.valueOrDefault,...spawnTimeoutOptions(),taskTimeoutMillis:commandTimeoutMs(),maxIdleMsPerProcess:minuteMs,cleanupChildProcs:!1}),EndableRanks.postdb),Settings2.powerShellProcs.watch(()=>this.bco.t.setMaxProcs(Settings2.powerShellProcs.valueOrDefault)),this.pwsh=this.bco.t}pwshPath=lazy2(async()=>await pathTo2({tool:`powershell`})??`powershell`);get lastStartError(){return this.bco.lastStartError}get lastTaskError(){return this.bco.lastTaskError}get ended(){return this.pwsh.ended}versionPojo(){return this.executeJson(`$PSVersionTable.PSVersion`)}async version(){let e=await this.executeJson(`$PSVersionTable.PSVersion`);return e==null?void 0:`${e.Major}.${e.Minor}.${e.Build}`}get spawnedProcCount(){return this.pwsh.spawnedProcCount}async execute(e,n){if(this.pwsh.ended||ending())this.logger.warn(`execute() failed (ended)`,{cmd:e});else try{let r=await elapsedAsync(this.pwsh.enqueueTask(new import_batch_cluster3.Task(e,(r,a,o)=>n(map(r,n=>stripPrefix(n,e)),a,o&&blank(a)))));return this.logger.tap({msg:`execute()`,result:r.result,meta:{elapsedMs:r.elapsedMs,cmd:e}})}catch(n){this.logger.warn(`execute() failed`,{cmd:e,error:n});return}}async executeJson(e){let n=await this.execute(ensureSuffix(e,ConvertToEncodedJson),(e,n,r)=>({stdout:e,stderr:n,passed:r}));if(n==null){this.logger.warn(`executeJson(): null result`,{cmd:e});return}if(blank(n.stdout)||notBlank(n.stderr)||!n.passed){this.logger.warn(`executeJson(): failed result`,{cmd:e,...n});return}let r=Buffer.from(n.stdout.trim(),`base64`).toString(`utf8`);try{return JSON.parse(r)}catch{let e=r.replace(/\\/g,`\\\\`);this.logger.info(`executeJson(): parsing failed, trying dub-whack fix...`,{raw:ellipsize(n.stdout),before:ellipsize(r),after:ellipsize(e)});try{return JSON.parse(e)}catch(e){let a=e instanceof Error?e.message:String(e);throw SyntaxError(`${a}; decoded: ${ellipsize(r)}; raw: ${ellipsize(n.stdout)}`,{cause:e})}}}async executeJsonToA(e){let n=await this.executeJson(e);return n==null?void 0:Array.isArray(n)?n:[n]}async getWindowsPath(e){try{let n=`[Environment]::GetFolderPath('${e.replace(/[^a-z]/gi,``)}', 'DoNotVerify')`,r=await this.executeJson(n);return blank(r)?void 0:r}catch(n){this.logger.warn(`Failed to get Windows path`,{folderId:e,error:n});return}}async which(e){let n=await this.executeJson(`Get-Command -ErrorAction SilentlyContinue `+pwshQuote(e)+` | Select-Object -Property Source`);return Array.isArray(n)?n[0]?.Source:n?.Source}},logger25=lazy2(()=>mkLogger(`Renice`));later(()=>ee().on(`clearCache`,()=>reniced.prior()?.clear()));var niceableCmds=lazy2(()=>[`sync.js`,`worker.js`,...flatten([`dcraw_emu`,`ffmpeg`].map(e=>isWin?[e,ensureSuffix(e,`.exe`)]:e))]);function niceable(e,n){return compactBlanks([import_node_path30.default.basename(e),...n.map(e=>import_node_path30.default.basename(e))]).some(e=>niceableCmds().includes(e.toLowerCase()))}var nodeReniceWorks=!0,reniced=lazy2(()=>new TTLSet(minuteMs));async function renice(e,n){if(!gt0(e)||reniced().has(e))return;let r=priorityPosixToClass(n)??Settings2.processPriority.valueOrDefault;if(n??=PriorityClassToNode[r],n===import_node_os11.default.constants.priority.PRIORITY_NORMAL)logger25().debug(`renice(): no-op as priority === normal`,{priority:n,priorityClass:r});else{if(reniced().add(e),nodeReniceWorks)try{return import_node_os11.default.setPriority(e,n),n}catch(r){let a=r?.errno===-13||r?.info?.code===`EACCES`;if(logger25().warn(`Failed to renice using node:os`,{pid:e,priority:n,permissionDenied:a,error:r}),a)return;nodeReniceWorks=!1}try{return await(isWin?reniceWin(e,r):renicePosix(e,PriorityClassToPosix[r]??PriorityClassToPosix.BelowNormal)),logger25().info(`Renice pid `+e+` to `+r),n}catch(n){logger25().info(`Failed to renice pid `+e,{error:n});return}}}async function reniceWin(e,n){gt0(e)&&PriorityClasses.includes(n)&&await PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${n}"`,e=>e).catch(e=>logger25().info(`reniceWin() failed`,e))}async function renicePosix(e,n=19){await stdoutResult_(`renice`,[n,`-p`,e].map(toS),{timerName:`proc.renice`,timeoutMs:10*secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch(e=>logger25().info(`renicePosix() failed`,e))}async function asPromise(e){let n=await e;return isFunction(n)?n():n}async function thenOrTimeoutError2({p:e,timeoutMs:n,halt:r}){let a=!0,o=Promise.race(compact([asPromise(e).finally(()=>a=!1),gt0(n)?delay(n).then(()=>{if(a)throw new TimeoutError(`timeout (`+fmtHMS(n)+`)`)}):void 0]));return r==null?o:r.awaitOrAbort(o)}async function writeAsync(e,n){return e==null||!0!==e.writable||!0===e.destroyed?Promise.reject(Error(`target is not writable`)):new Promise((r,a)=>{e.write(n,e=>{e==null?r():a(e)})})}async function disposeStream(e,n={}){if(e==null)return;let{delayMs:r=50,force:a=ending()}=n;try{`allowHalfOpen`in e&&(e.allowHalfOpen=!1)}catch{}try{e.unref?.()}catch{}if(`end`in e&&typeof e.end==`function`&&(e.readable===!0||e.writable===!0)&&e.destroyed!==!0&&(a?e.end():await new Promise(n=>e.end(n)),a||await delay(r)),`close`in e&&typeof e.close==`function`&&e.closed!==!0){if(a)try{e.close(NoOp)}catch{}else await new Promise(n=>e.close(n));a||await delay(r)}try{e.closeAllConnections?.()}catch{}try{`destroy`in e&&typeof e.destroy==`function`&&e.destroyed!==!0&&e.destroy()}catch{}}function closeStreams(e){for(let n of[e?.stdin,e?.stdout,e?.stderr])try{!1===n?.destroyed&&n?.destroy()}catch{}}var import_node_path31=require("node:path"),import_node_process22=__toESM(require("node:process"));function parseEnvTokenPairs(e){let n={},r=e.replace(/\r\n?/g,`
|
|
498
|
+
`),a=/\s*#.*$|(?:export[\t ]*)?(?<key>[\w.-]+)[\t ]*[:=](?:(?<quote>["'`])(?<qval>(?:\\.|(?!\2)[\s\S])*)\2|(?<val>[^\s#]*))(?:[\t ]*#.*$)?(?:$|\s)/gim,o;for(;(o=a.exec(r))!=null;){let e=o.groups?.key;if(e==null)continue;let r=(o.groups?.qval??o.groups?.val??``).trim();o.groups?.quote===`"`&&(r=r.replace(/\\n/g,`
|
|
499
|
+
`).replace(/\\r/g,`\r`).replace(/\\"/g,`"`)),n[e]=r}return n}function parseEnvTokens({input:e,lowerCaseKeys:n}){let r={};if(blank(e))return r;let a=parseEnvTokenPairs(e);return n?downcaseObjectKeys(a):a}var DefaultLocale=`en`,logger26=lazy2(()=>mkLogger(`Locale`));function localeSync(){return locale.lastValue()??envLocale()??DefaultLocale}var locale=lazyAsync({desc:`locale`,later:async()=>lc2locale(extractLocale()??await(isWin?localeWin():isMac?localeMac():localePosix()).catch(e=>(logger26().warn(`Failed to get locale`,{error:e}),DefaultLocale))),timeoutMs:commandTimeoutMs()}),envLocale=lazy2(extractLocale);function extractLocale(e=process.env){for(let n of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){let e=toLocale(n);if(e!=null)return e}}var regex=/^(?<lang>[a-z]{2,3})(?:[_-](?<country>[a-z]{2,3}))?\b/i;function toLocale(e){if(blank(e))return;if(e===DefaultLocale||equalsIgnoreCase(`c`,e)||equalsIgnoreCase(`posix`,e))return DefaultLocale;let n=regex.exec(e.trim())?.groups;return n==null?void 0:compact([n.lang,n.country]).join(`-`)}function lc2locale(e){return toLocale(e)??DefaultLocale}async function localeWin(){return(await PowerShell.instance().executeJson(`Get-WinSystemLocale | Select-Object -Property Name`))?.Name}var opts={timeoutMs:10*secondMs};async function localeMac(){return toLocale(await stdout_(`defaults`,[`read`,`-globalDomain`,`AppleLocale`],opts))}async function localePosix(){return lc2locale(extractLocale(parseEnvTokens({lowerCaseKeys:!1,input:await stdout_(`locale`,[],opts)})))}function childProcLocale(){return{LANG:`C`,LC_ALL:`C`}}function keyWords(e){return e.split(/[^a-zA-Z0-9]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/).filter(e=>e.length>0).map(e=>e.toLowerCase())}var EnvSensitiveWordPatterns=[`credentials?`,`dsn`,`keys?`,`aws`,`npm`,`pass`,`passwd`,`password`,`private`,`secret`,`token`],EnvSensitiveWords=EnvSensitiveWordPatterns.flatMap(e=>e.endsWith(`s?`)?[e.slice(0,-2),e.slice(0,-1)]:[e]),DefaultSensitiveEnvRegexPattern=`(?:^|[^a-z])(?:`+EnvSensitiveWordPatterns.join(`|`)+`)(?:$|[^a-z])`,SensitiveWords=new Set(`auth.authorization.aws.bearer.cookie.cookies.credential.credentials.crypt.csrf.dsn.jwt.key.keys.npm.otp.passphrase.passwd.password.passwords.private.pswd.pw.salt.secret.secrets.session.sid.signature.token.tokens.xsrf.accesskey.accesstoken.apikey.apikeys.authtoken.clientsecret.csrftoken.idtoken.privatekey.refreshtoken.secretkey.sessionid.xsrftoken`.split(`.`)),logger27=lazy2(()=>mkLogger(`SensitiveEnvKey`)),sensitiveEnvRE=new RegExp(DefaultSensitiveEnvRegexPattern,`i`);later(()=>Settings2.sensitiveWordsAdd.watchLater(()=>addedWords.unset()));var addedWords=lazy2(()=>new Set(Settings2.sensitiveWordsAdd.valueOrDefault.map(e=>keyWords(e).join(``)).filter(e=>e.length>0)));function isSensitiveEnvKey(e){return!blank(e)&&(SensitiveEnvSettings().has(e)||sensitiveEnvRE.test(e)||keyWords(e).some(e=>addedWords().has(e)))}var SensitiveEnvSettings=lazy2(()=>new Set(allSettings().filter(e=>e.isSensitive()).flatMap(e=>e.envKeys())));function addSensitiveSettings(){for(let e of allSettings())!e.isSensitive()&&e.envKeys().some(isSensitiveEnvKey)&&(logger27().warn(`Forcing `+e.name+` to be sensitive.`),e.opts.sensitive=!0)}function isPsEnvKey(e){return nodeOrPsKeys().has(e)||e.startsWith(`LC_`)||e.startsWith(`PS_`)}var nodeOrPsKeys=defer(()=>{let e=new CaseInsensitiveSet;for(let n of values(Settings2)){for(let r of n.names)e.add(r);for(let r of n.keys)e.add(r);for(let r of n.fileEnvKeys())e.add(r)}return e.add(`NODE_ENV`),e.add(UV_THREADPOOL_SIZE),e.add(`TZ`),e.add(ELECTRON_RUN_AS_NODE),e});function psenv(){return sortedKeys(filter(import_node_process22.default.env,e=>isPsEnvKey(e)))}later(()=>{function e(){sanitizedEnv.unset()}ee().on(`clearCache`,e),ee().on(`settingsChanged`,e);for(let n of allSettings())n.watchLater(e)});var RequiredPosixEnv=[`HOME`,`LANG`,`USER`],RequiredWindowsEnv=[`APPDATA`,`HOME`,`HOMEDRIVE`,`LOCALAPPDATA`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`];function envKeysRemovedByWord(e){return Object.keys(import_node_process22.default.env).filter(n=>!isPsEnvKey(n)&&!(n in requiredEnv())&&keyWords(n).includes(e))}var requiredEnv=lazy2(()=>{let e=pick(import_node_process22.default.env,...isPosix?RequiredPosixEnv:RequiredWindowsEnv,...DO_NOT_TRACK_ENV_KEYS);return e.PATH=pathDirectories().join(import_node_path31.delimiter),e}),sanitizedEnv=lazy2(()=>filter(import_node_process22.default.env,e=>isPsEnvKey(e)||!isSensitiveEnvKey(e)));function deleteWebServiceSecrets(e){let n=[Settings2.emailSmtpPassword,Settings2.oidcClientSecret,Settings2.previewApiToken];for(let r of Object.keys(e))(n.some(e=>e.includesEnvKey(r)||e.includesFileEnvKey(r))||r.toUpperCase()===PS_ELECTRON_AUTH_SECRET)&&delete e[r];return e}function childProcEnvSettings(e){let n={NODE_ENV:nodeEnv(),NO_COLOR:`1`,PS_LOG_STDOUT:`0`};if(n[PS_IS_CHILD_PROCESS]=`1`,n[PS_IS_DOCKER]=isDocker()?`1`:`0`,isElectron()){n[ELECTRON_RUN_AS_NODE]=`1`;let e=Settings2.projectDir.value;notBlank(e)&&Settings2.projectDir.addToEnv(n,e)}for(let r of persistedSettings())r.addToChildProcessEnv(n,e);return n}function spawnOptions(e){let n=e??{};return{...omit(n,`forceCLocale`,`forWorker`,`keepWebServiceSecrets`),env:childEnv({overrides:n.env,forceCLocale:n.forceCLocale,forWorker:n.forWorker,keepWebServiceSecrets:n.keepWebServiceSecrets}),detached:!1,shell:!1,windowsHide:n.windowsHide??!0}}var childEnvLogged=!1;function childEnv({overrides:e,forceCLocale:n=!0,forWorker:r=!1,keepWebServiceSecrets:a=!1}={}){let o=compactValues({...sanitizedEnv(),...requiredEnv(),...n?childProcLocale():{},...childProcEnvSettings(r),...e??{}});if(isTest()){let n=e??{};blank(n.PS_CONFIG_DIR)&&mapNotBlank(import_node_process22.default.env.PS_CONFIG_DIR,e=>o.PS_CONFIG_DIR=e),Settings2.libraryDir.addToEnv(o,Settings2.libraryDir.rawEnvValue(n));let r=Settings2.httpPort.rawEnvValue(n);r==null?Settings2.httpPort.rawEnvValue(o)??Settings2.httpPort.addToEnv(o):o[Settings2.httpPort.key]=r}for(let e of allSettings())e.propagateToChildren||e.deleteFromEnv(o);for(let e of Object.keys(o))e.toUpperCase()===`NODE_OPTIONS`&&delete o[e];if(a||deleteWebServiceSecrets(o),isLogged(`debug`)&&!childEnvLogged){childEnvLogged=!0;let e=mkLogger(`child.ChildEnv`),[n,r]=partition(entries(o).map(([e,n])=>[e,isSensitiveEnvKey(e)?`(hidden)`:n]),([e])=>isPsEnvKey(e));e.debug(`PS env:`,fromEntries(n)),e.debug(`non PS env:`,fromEntries(r))}return o}var logger28=lazy2(()=>mkLogger(`child.ChildProcess`));function cp2log(e){return pick(e,`pid`,`killed`,`connected`,`exitCode`,`signalCode`,`spawnfile`,`spawnargs`)}var KillReapTimeoutMs=5*secondMs;async function endProcess(e,n=30*secondMs){if(e==null)return!1;logger28().debug(`endProcess()`,cp2log(e));let r=e.pid;if(r==null||r<=0)return logger28().warn(`endProcess(): asked to end invalid pid`,cp2log(e)),!1;if(r===import_node_process23.default.pid)return logger28().warn(`endProcess(): asked to end MY pid`,cp2log(e)),!1;if(r===import_node_process23.default.ppid)return logger28().warn(`endProcess(): asked to end my parent pid`,cp2log(e)),!1;closeStreams(e);{let n=e.kill();logger28().debug(`endProcess(`+r+`)`,{killResult:n,childGotSigterm:e.killed}),!n&&(0,import_batch_cluster.pidExists)(r)&&await killPid(r).catch(e=>{logger28().warn(`endProcess(): kill(`+r+`,false) failed: `+e)})}if(Try(()=>e.unref()),await waitForPidExit(r,isSingleSpecTests()?500:n))return logger28().debug(`endProcess(): exitted`,cp2log(e)),!0;{Pids.instance()?.onKill(r);let n=e.kill(`SIGKILL`);logger28().warn(`endProcess(`+r+`) had to resort to SIGKILL`,{killResult:n}),!n&&(0,import_batch_cluster.pidExists)(r)&&await killPid(r,!0).catch(e=>{logger28().warn(`endProcess(): kill(`+r+`,true) failed: `+e)})}return waitForPidExit(r,KillReapTimeoutMs)}var ReniceAfterMs=lazy2(()=>15*secondMs),AddPidAfterMs=lazy2(()=>30*secondMs);function newProc(e,n,r,a=0,o){let s=new Date,c=[];return niceable(n,r)&&c.push(setUnrefTimeout(()=>{gt0(e.pid)&&renice(e.pid)},ReniceAfterMs())),gt(a,secondMs)&&c.push(setUnrefTimeout(()=>{gt0(e.pid)&&endProcess(e)},a-250)),c.push(setUnrefTimeout(()=>{if(gt0(e.pid))return addPid({pid:e.pid,cmd:n,timeoutMs:o??a,ppid:import_node_process23.default.pid},s)},AddPidAfterMs())),e.on(`exit`,()=>c.forEach(clearTimeout)),e}function spawn(e,n,r,a,o){let s=spawnOptions(a);return logger28().debug(`spawn()`,{command:e,args:n,maxAgeMs:r}),newProc(import_node_child_process4.default.spawn(e,n,s),e,n,r,o)}function execFile2(e,n,r,a){let o=spawnOptions(a);return isLogged(`trace`,logger28().context)?logger28().debug(`execFile()`,{command:e,args:n,timeoutMs:r,opts:o}):logger28().debug(`execFile()`,{command:e,args:n,timeoutMs:r}),newProc(import_node_child_process4.default.execFile(e,n,o),e,n,r)}async function stdoutResult_(e,n,r){let a=performance.now(),o=r.quiet??!1,s=r.ignoreStderr??!1,c=r.ignoreExitCode??!1,l=omit(r,`timeout`,`quiet`,`ignoreStderr`,`ignoreExitCode`,`timerName`,`onStdoutChunk`,`stdinFileDescriptor`,`stdoutFileDescriptor`),u=r.stdinFileDescriptor==null&&r.stdoutFileDescriptor==null?execFile2(e,n,r.timeoutMs,l):spawn(e,n,r.timeoutMs,{...l,stdio:[r.stdinFileDescriptor??`pipe`,r.stdoutFileDescriptor??`pipe`,`pipe`]});if(r.stdinFileDescriptor!=null||r.stdoutFileDescriptor!=null){let e=typeof r.encoding==`string`&&Buffer.isEncoding(r.encoding)?r.encoding:`utf8`;u.stdout?.setEncoding(e),u.stderr?.setEncoding(e)}let d=r.isIgnorableError??isIgnorableError,f=r.isExpectedError??d,h=u.pid;h!=null&&addPid({pid:h,ppid:import_node_process23.default.pid,cmd:e,timeoutMs:r.timeoutMs},new Date)?.catch(()=>{});try{if(r.disconnect===!0){try{u.disconnect?.()}catch{}return{result:``,pid:u.pid}}let l=stringify({pid:h,cmd:e,args:n}),_=0,y=[],x=[],C=[],w=new Deferred2(l),T=null;u.on(`error`,e=>C.push(e)),u.on(`exit`,(e,n)=>{w.isPending&&!u.killed&&(T=n,w.resolve(e))}),u.on(`close`,(e,n)=>{w.isPending&&!u.killed&&(T=n,w.resolve(e))});let E=new Latch;u.stdout==null?E.resolve():(u.stdout.on(`error`,e=>C.push(e)),u.stdout.on(`data`,a=>{if(y.push(a),_+=a.length,r.onStdoutChunk!=null){let e=typeof a==`string`?a:a.toString(`utf8`);try{r.onStdoutChunk(e)}catch(e){logger28().warn(`stdoutResult_() onStdoutChunk threw`,{error:e})}}gt0(r.maxBytes)&>(_,r.maxBytes)&&(logger28().warn(`stdoutResult_() maxBytes exceeded`,{bytesRead:_,maxBytes:r.maxBytes,cmd:e,args:n}),u.kill(`SIGINT`),r.halt?.abort(`maxBytes exceeded`),w.resolve(1))}),u.stdout.on(`end`,()=>E.resolve()));let D=new Latch;u.stderr==null?D.resolve():s?(u.stderr.resume(),D.resolve()):(u.stderr?.on(`error`,e=>C.push(e)),u.stderr?.on(`data`,e=>x.push(e)),u.stderr?.on(`end`,()=>D.resolve())),logger28().debug(`stdoutResult_() invoked and waiting for completion...`,{name:l}),await disposeStream(u.stdin),await thenOrTimeoutError2({p:w.promise,timeoutMs:r.timeoutMs,halt:r.halt}),logger28().debug(`stdoutResult_() exitCode settled...`,{name:l,exitCode:w.value,stdout:E.state(),stderr:D.state()}),await thenOrTimeoutError2({p:E.promise,timeoutMs:ShortCommandTimeoutMs,halt:r.halt}),await thenOrTimeoutError2({p:D.promise,timeoutMs:ShortCommandTimeoutMs,halt:r.halt});let O=x.join(``);notBlank(O)&&C.push(Error(O));let k=r.cleanError==null?C:C.map(e=>Error(r.cleanError(e.message)));if(!o&&isNotEmpty(k)){let n=k.every(e=>f(e)===!0||isCorruptMediaError(e));logger28().log(n?`info`:`warn`,e+` resulted in errors:`,k)}let A=k.filter(e=>d(e)!==!0);if(T!=null)throw new WrappedError(e+`: terminated by `+T,{causes:A});if(A.length>0)throw A.length===1?A[0]:new WrappedError(`Failed to run `+e+` `+n.join(` `),{causes:A});if(!c&&w.value!==0&&!k.some(e=>f(e)===!0))throw Error(e+`: exit code `+w.value);let j=y.join(``);return r.timerName!=null&&pushTime({name:r.timerName,elapsedMs:roundMs(performance.now()-a)}),{result:j,pid:h,code:w.value??void 0,stderr:O}}catch(e){throw r.timerName!=null&&pushTime({name:r.timerName,elapsedMs:roundMs(performance.now()-a)}),logger28().warn(`stdoutResult_() failed`,e),await endProcess(u),e}}async function stdout_(e,n,r){let a=await thenOrTimeoutError2({p:stdoutResult_(e,n,r),timeoutMs:r.timeoutMs});return logger28().tap({level:`trace`,msg:`stdout_()`,result:trimLastNewline(a.result),meta:{cmd:e,args:n,opts:r,result:a}})}var logger29=lazy2(()=>mkLogger(`UserInfo`));async function userDesc(){let e=await username(),n=mapGte0(userid(),e=>`userid `+e);return e==null?n??`unknown user`:`user `+e+(n==null?``:` (${n})`)}var usernameFromEnv=lazy2(()=>{for(let e of[`SUDO_USER`,`C9_USER`,`LOGNAME`,`USER`,`LNAME`,`USERNAME`]){let n=getEnv(e);if(!blank(n))return n}}),usernameFromUserInfo=lazy2(()=>toNotBlank(passwdEntry()?.username)),userNameFromWhoami=lazy2(async()=>{try{let e=toNotBlank(await stdout_(`whoami`,[],{ignoreExitCode:!0,timeoutMs:ShortCommandTimeoutMs,isIgnorableError:()=>!0}));return isWin?last(e?.split(`\\`)):e}catch(e){logger29().warn(`$(whoami) failed`,{error:e});return}}),userNameFromWindowsAccessToken=lazy2(async()=>isWin?last((await PowerShell.instance().execute(`[System.Security.Principal.WindowsIdentity]::GetCurrent().Name`,toNotBlank))?.trim().split(`\\`)):void 0),username=lazy2(async()=>toNotBlank(usernameFromEnv())??toNotBlank(usernameFromUserInfo())??toNotBlank(await userNameFromWhoami())??toNotBlank(await userNameFromWindowsAccessToken()));async function pwshIsAdmin(){return isWin?await PowerShell.instance().execute(`(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)`,toBoolean)??!1:void 0}var isRootUser=lazy2(async()=>isWin?pwshIsAdmin():userid()===0);function libraryDir(e){return toNotBlank(toS(e))??Settings2.libraryDir.valueOrDefault}function originalsDir(e){let n=libraryDir(e);if(n==null)return;let r=Settings2.originalsDir.valueOrDefault;return blank(r)?n:isAbsolute2(r)?r:resolve2(n,r)}function originalsDirIsOutsideLibrary(e){let n=originalsDir(e);return n!=null&&!containedByNativePath({ancestor:libraryDir(e),descendant:n,acceptSelf:!0})}function libraryDataDir(e){return resolveMaybe(libraryDir(e),`.photostructure`)}function libraryPreviewsDir(e){return resolveMaybe(libraryDir(e),Settings2.previewsDir.valueOrDefault)}var import_node_util12=require("node:util"),BoundedMap=class{constructor(e){if(this.capacity=e,e<1)throw Error(`BoundedMap.capacity must be >= 1: `+e);this.#e=new Map}capacity;#e;#t;get size(){return this.#e.size}get lastKey(){return this.#t}get lastValue(){return this.#t==null?void 0:this.#e.get(this.#t)}has(e){return this.#e.has(e)}get(e){return this.#e.get(e)}set(e,n){if(this.#e.has(e))this.#e.delete(e);else if(this.#e.size>=this.capacity){let e=this.#e.keys().next();e.done!==!0&&this.#e.delete(e.value)}return this.#e.set(e,n),this.#t=e,this}delete(e){return this.#e.delete(e)}clear(){this.#e.clear(),this.#t=void 0}keys(){return this.#e.keys()}values(){return this.#e.values()}entries(){return this.#e.entries()}forEach(e){this.#e.forEach((n,r)=>e(n,r,this))}[Symbol.iterator](){return this.#e[Symbol.iterator]()}get[Symbol.toStringTag](){return`BoundedMap`}[import_node_util12.inspect.custom](){return Object.fromEntries(this.#e)}},StartTs=Date.now(),PauseReasons=strEnum(`user`,`battery`,`suspend`,`maintenance`),DefaultPauseReason=`user`,reasons=new Set,onResumeLatch,onPauseChangeLatch,lastResumeTimestamp=StartTs;function isPaused(){return reasons.size>0}function isPausedFor(e){return reasons.has(e)}function pauseReasons(){return[...reasons]}function pauseReasonsExcept(e=[]){return[...reasons].filter(n=>!e.includes(n))}function pause(e=!0,n=DefaultPauseReason){let r=isPaused(),a=e?!reasons.has(n):reasons.has(n);e?reasons.add(n):reasons.delete(n);let o=isPaused();r&&!o&&(lastResumeTimestamp=Date.now(),onResumeLatch?.resolve(),onResumeLatch=void 0),a&&(onPauseChangeLatch?.resolve(),onPauseChangeLatch=void 0,ee().emitSync(`syncStateChanged`))}function lastResumeTs(){return lastResumeTimestamp}function resolveOnPauseChange(){return isPaused()?onPauseChangeLatch??=new Latch:Promise.resolve()}function progressEvtToS(e){return compactBlanks([blank(e.path)?null:ellipsizePath({p:e.path,maxLength:80}),e.op,e.done===!0?`done`:e.pct==null?fmt(e.step):fmtPct(e.pct)]).join(`: `)}var logger30=defer(()=>mkLogger(`progress.ProgressWatchdog`)),ProgressWatchdog=class e{#e;#t=new Set;#n;#r;#i;static instance=new e;constructor(){this.#e=new BoundedMap(10),this.#n=()=>!1,this.#r=()=>0,logger30().debug(`ProgressWatchdog initialized`)}setIsWorkPending(e){this.#n=e}setPendingCount(e){this.#r=e}setOnWedged(e){this.#i=defer(()=>{logger30().warn(`triggerOnWedged: invoking callback to mark tasks as problematic`);try{e()}catch(e){logger30().error(`triggerOnWedged: callback failed`,{error:e})}})}triggerOnWedged(){this.#i==null?logger30().warn(`triggerOnWedged: no callback set`):this.#i.applied()?logger30().debug(`triggerOnWedged: already triggered, skipping`):this.#i()}ping(e){this.#e.set(e,Date.now()),this.#i?.reset()}progressEvent(e){this.ping(progressEvtToS(e))}get lastPing(){let e=this.#e.lastValue,n=this.#e.lastKey;return e==null||n==null?void 0:{ts:e,desc:n}}get recentPings(){return[...this.#e.entries()].map(([e,n])=>({desc:e,ts:n}))}enterOperation(e){this.#t.add(e),this.ping(`enter: ${e}`),logger30().debug(`enterOperation`,{name:e,active:[...this.#t]})}exitOperation(e){this.#t.delete(e),logger30().debug(`exitOperation`,{name:e,active:[...this.#t]})}get isInWorkingMode(){return this.#t.size>0}get activeOperations(){return[...this.#t]}isWedged(){if(!this.isInWorkingMode)return!1;let e=Settings2.progressWatchdogTimeoutMs.valueOrDefault;if(e<=0||!this.#n()||isPaused())return!1;let n=this.#e.lastValue??StartTs-minuteMs,r=Math.max(n,lastResumeTs());return Date.now()-r>e}get pendingCount(){return this.#r()}},DefaultThrottleMs=5e3,PullProgressObserver=class extends EndableInterval{constructor(e,n,r,a=DefaultThrottleMs){super({name:`PullProgressObserver(`+stringify(e)+`)`,callback:()=>this.#e(),intervalMs:a,rank:EndableRanks.first}),this.ctx=e,this.total=n,this.progress=r,this.throttleMs=a}ctx;total;progress;throttleMs;done;toJSON(){}observe(e){return e.then(()=>this.completed(),e=>{this.logger.warn(`failed`,{error:e}),this.ctx.op+=` (failed: `+errorToS2(e)+`)`,this.end()}),e}async#e(){if(ending()){this.end();return}let e=await this.progress();this.ended||this.onResult(e)}onResult(e){ProgressWatchdog.instance.progressEvent({...this.ctx,pct:pct(e,this.total),done:this.done})}completed(){let e=this.done;this.done=!0,!this.ended&&(e!==!0&&this.onResult(this.total),this.end())}},import_node_path32=require("node:path");function strEql(e,n,{ignoreCase:r}){return r?equalsIgnoreCase(e,n,{normalize:!0}):e===n}function sidecarNames(e){if(!isSidecarExt(e.ext)||e.base.startsWith(`.`))return;let n=isJsonExt(e.ext);return{base:e.base,name:e.name,isJson:n,ignoreCase:n||Settings2.matchSidecarsCaseInsensitively.valueOrDefault,fuzzy:n||Settings2.matchSidecarsFuzzily.valueOrDefault,ext:normalizeExt(e.name),subname:(0,import_node_path32.parse)(e.name).name,variants:uniq([e.base,e.name,stripExt(e.name)]).map(e=>stripCopySuffixFromName(e))}}function sourceNames(e){return{base:e.base,name:e.name,ext:normalizeExt(e),variants:uniq([e.base,e.name,stripExt(e.base)]).map(e=>stripCopySuffixFromName(e))}}function matchesSidecar(e,n){if(n==null)return!1;let{isJson:r,ignoreCase:a,fuzzy:o}=n;if(strEql(e.base,n.name,{ignoreCase:a})||strEql(e.name,n.name,{ignoreCase:a})||e.ext===n.ext&&strEql(e.name,n.subname,{ignoreCase:a}))return!0;if(o){for(let r of e.variants)for(let e of n.variants)if(strEql(r,e,{ignoreCase:o}))return!0}return r&&isJsonFuzzyMatch(e.name,n.name)}function isSidecarOf(e,n){let r=sidecarNames(n);return r!=null&&matchesSidecar(sourceNames(e),r)}var AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i;function isJsonFuzzyMatch(e,n){let r=commonPrefixIgnoreCase(e,n);if(r.length<8)return!1;function a(e){return blank(e)||e.match(AllowedUncommonSuffixRe)!=null}let o=a(e.slice(r.length)),s=a(n.slice(r.length));return o&&s}function cannotHaveSidecars(e){return isSidecarExt(e.ext)||isInInternalDir(e)}async function existingSidecars(e){return cannotHaveSidecars(e)?[]:sortByAsync({iter:e.siblings(n=>isSidecarOf(e,n)),f:e=>e.mtimeMs()})}function mayBeSidecar(e){return isSidecarExt(e.ext)||compactBlanks(Settings2.directorySidecars.valueOrDefault).includes(e.base)}function listedSidecarsOf(e,n){let{own:r,shared:a}=n.candidatesOf(e);return uniq([...r,...a.filter(e=>(e.size()??0)>=1)])}var ListedSidecars=class{#e;#t;constructor(e){this.#e=e.map(e=>({file:e,names:sidecarNames(e)}));let n=compactBlanks(Settings2.directorySidecars.valueOrDefault);this.#t=e.filter(e=>n.includes(e.base))}candidatesOf(e){let n=[];if(!cannotHaveSidecars(e)){let r=sourceNames(e);for(let a of this.#e)a.file.base!==e.base&&matchesSidecar(r,a.names)&&n.push(a.file)}return{own:n,shared:[...this.#t]}}};function defaultSidecarExt(){return ensurePrefix(Settings2.defaultSidecarType.valueOrDefault,`.`)}var SidecarFileFieldsToIgnore=`Error.ExifToolVersion.SourceFile.Warning.BMPVersion.BitsPerSample.ColorComponents.CurrentIPTCDigest.Directory.EncodingProcess.ExifByteOrder.FileAccessDate.FileCreateDate.FileInodeChangeDate.FileModifyDate.FileName.FilePermissions.FileSize.FileType.FileTypeExtension.ImageDataMD5.ImageDataHash.ImageHeight.ImageWidth.MIMEType.ExifImageWidth.ExifImageHeight.Orientation.Rotation.Duration.MediaDuration.TrackDuration.Planes.YCbCrSubSampling`.split(`.`),IgnoredSidecarFields=[...SidecarFileFieldsToIgnore,`errors`,`FileIndex2`,`FileInfoVersion`,`FileFormat`,`FileIndex`,`FileNumber`,`FileNumberMemory`,`FileNumberSequence`],import_node_path38=require("node:path"),fsm=__toESM(require("@photostructure/fs-metadata")),import_promises16=require("node:fs/promises"),import_node_path37=require("node:path"),SqliteExt=`.sqlite3`,SqliteBase=`db`+SqliteExt,Schemas=strEnum(`models`,`auth`),SchemaTraits={models:{verifiedWhenWebOpens:!1,holdsSignInState:!1},auth:{verifiedWhenWebOpens:!0,holdsSignInState:!0}};function pathToDbDir(e,n){return e.join(n)}function pathToDb(e,n){return pathToDbDir(e,n).join(SqliteBase)}function dbBackupDir(e){return e.sibling(`backups`)}function mapSchemas(e){return Object.fromEntries(Schemas.values.map(n=>[n,e(n)]))}var path_posix=__toESM(require("node:path/posix")),examplesNativePath_=defer(()=>joinNativePath([repoRoot(),`examples`])),examples=lazy2(()=>PosixFile.for(examplesNativePath_())),TestLibraryDirPrefix=`test-ps-lib-`,import_node_path33=require("node:path"),import_posix=require("node:path/posix"),import_node_util13=require("node:util"),import_punycode=require("punycode.js");function isURLSearchParams(e){return e?.constructor?.name===`URLSearchParams`}function toURLSearchParams(e){return e==null?void 0:isURLSearchParams(e)?e:new URLSearchParams(e)}function mergeURLSearchParams(...e){let n=compact(e.map(toURLSearchParams)),r=n.shift();if(r!=null){for(let e of n)for(let[n,a]of e.entries())r.set(n,a);return r}}function assembleFullPath(e,...n){let r=toS(mergeURLSearchParams(...n));return e+(blank(r)?``:`?`+r)}var _schemePattern=/^\w[\w+.-]*$/,_singleSlashStart=/^\//,_doubleSlashStart=/^\/\//;function _validateUri(e,n){if(!e.scheme&&n===!0)throw Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!_schemePattern.test(e.scheme))throw Error(`[UriError]: Scheme contains illegal characters.`);if(e.path){if(e.authority){if(!_singleSlashStart.test(e.path))throw 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(_doubleSlashStart.test(e.path))throw Error(`[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")`)}}function _schemeFix(e,n){return!e&&!n?`file`:e}function _referenceResolution(e,n){switch(e){case`https`:case`http`:case`file`:n?n[0]!==_slash&&(n=_slash+n):n=_slash}return n}var _empty=``,_slash=`/`,_regexp=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,URI=class e{static isUri(n){return n instanceof e||n!=null&&typeof n.authority==`string`&&typeof n.fragment==`string`&&typeof n.path==`string`&&typeof n.query==`string`&&typeof n.scheme==`string`&&typeof n.fsPath==`function`&&typeof n.with==`function`&&typeof n.toString==`function`}scheme;authority;path;query;fragment;constructor(e,n,r,a,o,s=!1){typeof e==`object`?(this.scheme=e.scheme||_empty,this.authority=e.authority||_empty,this.path=e.path||_empty,this.query=toURLSearchParams(e.query??``),this.fragment=e.fragment||_empty):(this.scheme=_schemeFix(e,s),this.authority=n??_empty,this.path=_referenceResolution(this.scheme,r??_empty),this.query=toURLSearchParams(a??``),this.fragment=o??_empty,_validateUri(this,s))}get fsPath(){return uriToFsPath(this)}get relativeFsPath(){let e=this.fsPath;return isWin?e:stripPrefix(e,`/`)}with(e){if(e==null)return this;let{scheme:n,authority:r,path:a,query:o,fragment:s}=e;return n===void 0?n=this.scheme:n===null&&(n=_empty),r===void 0?r=this.authority:r===null&&(r=_empty),a===void 0?a=this.path:a===null&&(a=_empty),o===void 0?o=this.query:o===null&&(o=_empty),s===void 0?s=this.fragment:s===null&&(s=_empty),n===this.scheme&&r===this.authority&&a===this.path&&o===this.query&&s===this.fragment?this:new Uri(n,r,a,o,s)}static parse(e,n=!1){let r=_regexp.exec(e);if(!r)return new Uri(_empty,_empty,_empty,_empty,_empty);let a=r[2]||_empty,o=percentDecode(r[4]||_empty),s=(r[5]||_empty).split(`/`).map(percentDecode).join(`/`);return new Uri(a,o,a===`psfile`&&s.startsWith(`//`)?s.slice(1):s,toURLSearchParams(r[7]),percentDecode(r[9]||_empty),n)}static file(e){let n=_empty;if(isWin&&(e=e.replace(/\\/g,_slash)),e[0]===_slash&&e[1]===_slash){let r=e.indexOf(_slash,2);r===-1?(n=e.substring(2),e=_slash):(n=e.substring(2,r),e=e.substring(r)||_slash)}return new Uri(`file`,n,e,_empty,_empty)}static from(e){return new Uri(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(n,...r){if(!n.path)throw Error(`[UriError]: cannot call joinPaths on URI without path`);let a;return a=isWin&&n.scheme===`file`?e.file(import_node_path33.win32.join(uriToFsPath(n),...r)).path:import_node_path33.posix.join(n.path,...r),n.with({path:a})}isRootPath(){return this.path==null||this.path===_slash}get pathBase(){return blank(this.path)||this.isRootPath()?``:(0,import_posix.basename)(this.path)}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(_slash))})}join(...e){return this.with({path:ensureSuffix(this.path,_slash)+e.join(_slash)})}toString(e=!1){return _asFormatted(this,e)}toJSON(){return this}[import_node_util13.inspect.custom](){return this.toString()}},_pathSepMarker=isWinPortable?1:void 0,Uri=class extends URI{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath??=uriToFsPath(this),this._fsPath}toString(e=!1){return e?_asFormatted(this,!0):(this._formatted??=_asFormatted(this,!1),this._formatted)}toJSON(){let e={};return this._fsPath!=null&&(e.fsPath=this._fsPath,e._sep=_pathSepMarker),this._formatted!=null&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),mapNotBlank(this.query,n=>e.query=n),this.fragment&&(e.fragment=this.fragment),e}},encodeTable={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 encodeURIComponentFast(e,n){let r,a=-1;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);if(s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||s===45||s===46||s===95||s===126||n&&s===47)a!==-1&&(r+=encodeURIComponent(e.substring(a,o)),a=-1),r!==void 0&&(r+=e.charAt(o));else{r===void 0&&(r=e.slice(0,o));let n=encodeTable[s];n===void 0?a===-1&&(a=o):(a!==-1&&(r+=encodeURIComponent(e.substring(a,o)),a=-1),r+=n)}}return a!==-1&&(r+=encodeURIComponent(e.substring(a))),r===void 0?e:r}function encodeURIComponentMinimal(e){let n;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);a===35||a===63?(n===void 0&&(n=e.slice(0,r)),n+=encodeTable[a]):n!==void 0&&(n+=e[r])}return n===void 0?e:n}function uriToFsPath(e){let n;return n=e.authority&&e.path.length>1&&e.scheme===`file`?`//${e.authority}${e.path}`:e.path.charCodeAt(0)===47&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&e.path.charCodeAt(2)===58?isWin?e.path[1].toUpperCase()+e.path.slice(2):e.path.slice(1):e.path,isWin&&(n=n.replace(/\//g,`\\`)),n}function _asFormatted(e,n){let r=n?encodeURIComponentMinimal:encodeURIComponentFast,a=``,{scheme:o,query:s,fragment:c}=e,{authority:l,path:u}=e;if(o&&(a+=o,a+=`:`),(l||o===`file`)&&(a+=_slash,a+=_slash),l){let e=l.indexOf(`@`);if(e!==-1){let n=l.slice(0,e);l=l.slice(e+1),e=n.indexOf(`:`),e===-1?a+=r(n,!1):(a+=r(n.slice(0,e),!1),a+=`:`,a+=r(n.slice(e+1),!1)),a+=`@`}e=l.indexOf(`:`),e===-1?a+=r(l,!1):(a+=r(l.slice(0,e),!1),a+=l.slice(e))}if(u){let e=/^\/?[a-z]:/i.exec(u);e!=null&&(a+=e[0].toUpperCase(),u=u.slice(e[0].length)),a+=r(u,!0)}return mapNotBlank(s,e=>a+=`?`+e),c&&(a+=`#`,a+=n?c:encodeURIComponentFast(c,!1)),a}function decodeURIComponentGraceful(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.slice(0,3)+decodeURIComponentGraceful(e.slice(3)):e}}var _rEncodedAsHex=/(?:%[\dA-Z][\dA-Z])+/gi;function percentDecode(e){return e.startsWith(`xn--`)?(0,import_punycode.toUnicode)(e):e.match(_rEncodedAsHex)?e.replace(_rEncodedAsHex,e=>decodeURIComponentGraceful(e)):e}function toURI(e){return URI.isUri(e)?e:URI.parse(e)}var RepoRootToken=`$repoRoot`,RepoRootRe=RegExp(`^`+escapeRegExp(RepoRootToken)+`\\b`);function stableBasename(e){return stripCopySuffixFromName(e,{aggressive:!1})+e.ext}function ciSafePath(e,n){if(!isTest())return toNativePath_(e);let r=PosixFile.for(e),a=blank(r.ext),o=n?.stableBasename??!a?stableBasename(r):r.base.normalize(),s=r.sibling(o),c=r.existsSync(),l=s.isDirectorySync()||!c&&a?`/`:``,u=PosixFile.for(repoRoot()).join(`src`);if(s.isSelfOrDescendantOf(u)){let e=s.posixPathFrom(u);return e=e.replace(/^(\w+)\/dist\/\1\//,`$1/`),e=e.replace(/\.js$/,`.ts`),`$src/`+e+l}for(let{desc:e,dir:n}of[{desc:`$examples`,dir:examples()},{desc:`$library`,dir:PosixFile.forMaybe(Settings2.libraryDir.valueOrDefault)},{desc:`$library`,dir:PosixFile.forMaybe(originalsDir())},{desc:`$cache`,dir:PosixFile.for(cacheDir_())},{desc:`$library`,dir:r.findSelfOrAncestor(e=>e.base.startsWith(TestLibraryDirPrefix))},...toA(Settings2.scanPaths.valueOrDefault).map(e=>({desc:`SCAN_PATH`,dir:PosixFile.forMaybe(e)})),{desc:`SCAN_PATH`,dir:r.findSelfOrAncestor(e=>/^sync-(?:tiny|small|full)-/.test(e.base))}])if(n!=null&&s.isSelfOrDescendantOf(n)){let r=s.posixPathFrom(n);return path_posix.join(e,r)+l}let d=PosixFile.for(repoRoot());return s.isSelfOrDescendantOf(d)?path_posix.join(RepoRootToken,s.posixPathFrom(d))+l:r.baseWithGrandparent+l}var logger31=lazy2(()=>mkLogger(`img.ImgCache`)),ImageCacheName=`image-cache`,ReadableToFileTimeoutMs=2*minuteMs,imageCacheDirSync_=lazy2(()=>(watchCacheDir(),PosixFile.for(cacheDir_()).join(ImageCacheName)));ee().on(`resetDirectories`,()=>imageCacheDirSync_.unset());var imageCacheDir_=lazy2(()=>imageCacheDirSync_().mkdirp_());ee().on(`resetDirectories`,()=>imageCacheDir_.unset());var watchCacheDir=lazy2(()=>{cacheDir_.watchLater(()=>{imageCacheDirSync_.unset(),imageCacheDir_.unset()})});function imgCacheSubdir(e){return imgCacheSubdirFor(e.nativePath,e.statSync({refresh:!0}))}function imgCacheSubdirFor(e,n){return splitEvery(shortFsStringSha(JSON.stringify({np:isTest()?ciSafePath(e):e,size:n?.size,mtime:isTest()?0:n?.mtime}),24).slice(0,24),2,3)}async function tmpImageFile_(e){let n=await imageCacheDir_(),r=getDevEnvFlag(`PS_NO_RANDOM_IMAGE_CACHE`)?n.join(`tmp`,shortStringSha(ciSafePath(e.src),10,Radix36)+`-`+e.tag+e.ext):n.join(`tmp-`+Radix36.randomChars(2),Radix36.randomChars(16)+toS(e.ext));return await r.parent().mkdirp_(),r}async function cachedImageFile_(e,n,r){let a=await imageCacheDir_();n??=e.name,r=ensurePrefix(r??e.ext,`.`);let o=a.join(...imgCacheSubdir(e));await o.mkdirp_(),await o.utimes();let s=o.join(n+r);return logger31().debug(`cachedImgFile(`+e.baseWithGrandparent+`)`,{desc:n,ext:r,result:s}),s}async function readableToFile_({src:e,desc:n,suffix:r,f:a,minSizeBytes:o=256}){return(await cachedImageFile_(e,n,r)).applyIfEmpty_({fn_:a,timeoutMs:ReadableToFileTimeoutMs,minSizeBytes:o})}async function withImageCache_(e,n,r,a){try{let o=await cachedImageFile_(e,n,r);return await o.applyIfEmpty_({fn_:a,skipFsLock:!1,skipWip:!1,timeoutMs:Settings2.taskTimeoutMs.valueOrDefault,minSizeBytes:256,dirty:!0}),o}catch(a){return logger31().throw(`withImgCache_() failed`,{error:a,src:e.nativePath,desc:n,ext:r})}}var logger32=defer(()=>mkLogger(`dir.LibraryDirs`)),README=`
|
|
500
|
+
Hello, and thank you for using PhotoStructure!
|
|
501
|
+
|
|
502
|
+
The files in this folder support your PhotoStructure Library, including
|
|
503
|
+
|
|
504
|
+
* a database with the filepaths to your photos and movies
|
|
505
|
+
* previews and thumbnails of your photos and movies
|
|
506
|
+
* content metadata about these assets, like ratings and sharing information
|
|
507
|
+
* albums that both you and PhotoStructure Curators have assembled
|
|
508
|
+
* synchronization reports describing what directories and files were synced (and why)
|
|
509
|
+
|
|
510
|
+
Moving or deleting any files here will cause problems using your library.
|
|
511
|
+
|
|
512
|
+
See https://photostructure.com for more information.
|
|
513
|
+
|
|
514
|
+
Sincerely,
|
|
515
|
+
|
|
516
|
+
Your Friendly Neighborhood PhotoStructure, v${version}
|
|
517
|
+
`;function libraryDirPosixFile(e){return PosixFile.forMaybe(libraryDir(e))}function libraryDataDirPosixFile(e){return PosixFile.forMaybe(libraryDataDir(e))}function libraryDirs_(e){return uniqBy(libraryDirsWithRoles_(e).map(e=>e.dir),e=>e?.nativePath)}function libraryDirsWithRoles_(e){return[...uniqBy([libraryDirPosixFile(e),libraryDataDirPosixFile(e),libraryOriginalsDirPosixFile(e),libraryPreviewsDirPosixFile(e),librarySyncReportsDir(e),...Schemas.values.map(n=>map(libraryDataDirPosixFile(e),e=>pathToDbDir(e,n)))],e=>e?.nativePath).map(e=>({dir:e,role:`durable`})),{dir:imageCacheDirSync_(),role:`image-cache`}]}async function setupLibraryDirs_(e){return uniqBy(await setupLibraryDirectoryRoles_(e),e=>e.dir.nativePath).map(e=>e.dir)}async function setupLibraryDirectoryRoles_(e){let n=libraryDirPosixFile(e);await mkdirRW_(n,!1);let r=[n,await setupLibraryDataDir_(n),await setupLibraryOriginalsDir_(n),await setupLibraryPreviewsDir_(n),await setupLibrarySyncReportsDir_(n)];for(let e of Schemas.values)r.push(await setupLibraryDbDir_(n,e));return[...uniq(r).map(e=>({dir:e,role:`durable`})),{dir:await imageCacheDir_(),role:`image-cache`}]}async function mkdirRW_(e,n=!0){if(e!=null)return await e?.mkdirp_(),await e?.assertReadWriteExecutable(),n&&await e?.join(`.metadata_never_index`).touch(),e}async function setupLibraryDataDir_(e){let n=libraryDataDirPosixFile(e);if(n==null)throw Error(`empty libraryDataDir`+NoLibraryErrorFlag);await mkdirRW_(n),await mkNoMedia_(n),await writeCachedirTag_(n);let r=n.join(`README.txt`).nativePath;return await exists(r,LogLevels.trace)||await writeTextfile_(r,README),n}function libraryOriginalsDirPosixFile(e){return PosixFile.forMaybe(originalsDir(e))}async function setupLibraryOriginalsDir_(e){let n=libraryOriginalsDirPosixFile(e);if(n!=null&&!n.$eql(libraryDirPosixFile(e))&&await isReadableDirectory(n.nativePath))return n;let r=!1;return mkdirRW_(n,!1)}function libraryAssetDirPosixFiles(e){let n=[],r=libraryDirPosixFile(e);r!=null&&n.push(r);let a=libraryOriginalsDirPosixFile(e);return a!=null&&r?.$eql(a)!==!0&&n.push(a),uniqBy(n,e=>e.nativePath)}function libraryPreviewsDirPosixFile(e){return PosixFile.forMaybe(libraryPreviewsDir(e))}async function setupLibraryPreviewsDir_(e){return mkdirRW_(libraryPreviewsDirPosixFile(e))}function librarySyncReportsDir(e){return libraryDirPosixFile(e)?.join(Settings2.syncReportsDir.valueOrDefault)}async function setupLibrarySyncReportsDir_(e){return mkdirRW_(librarySyncReportsDir(e))}async function setupLibraryDbDir_(e,n){return mkdirRW_(map(libraryDataDirPosixFile(e),e=>pathToDbDir(e,n)))}async function*libraryVolumes(e){let n=new Set;for(let r of libraryDirs_(e))try{let e=toNativePath_(r),a=await bestMountPointForPath(e);if(a==null)logger32().warn(`libraryVolshas_(): no mount point`,{file:e});else if(n.has(a.mountPoint))logger32().debug(`libraryVolshas_(): skipping already-yielded mount point`,{file:e,mountPoint:a.mountPoint});else{n.add(a.mountPoint);let r=await getVolumeMetadata(a.mountPoint);r==null?logger32().warn(`libraryVolshas_(): no volume metadata`,{file:e,mountPoint:a.mountPoint}):yield r}}catch(e){logger32().warn(`libraryVolshas_(): error from directory`,{dir:r,error:e})}}async function*libraryVolumeUUIDs(e){let n=new Set;for await(let r of libraryVolumes(e))blank(r.uuid)?r.isReadOnly===!0?logger32().info(`libraryVolshas_(): no volsha for volume (readonly)`,{volume:r}):logger32().warn(`libraryVolshas_(): no volsha for volume`,{volume:r}):n.has(r.uuid)?logger32().info(`libraryVolshas_(): skipping already-yielded volsha`,{volume:r}):(n.add(r.uuid),logger32().info(`libraryVolshas_(): yielding volume`,{volume:r}),yield r.uuid)}function shimSync(e){return new ShimSyncImpl(e.name,e.impl,e.cache,e.toKey)}var ShimSyncImpl=class extends ExtensibleFunction{constructor(e,n,r,a){super(),this.impl=n,this.cache=r,this.toKey=a,this.#e=e}impl;cache;toKey;#e;#t;#n(...e){return this.toKey?.(...e)??(isPrimitive(e)?toS(e):stringify(e))}#r(...e){return timeSync({name:this.#e,t:()=>this.#t==null?this.impl(...e):this.#t(...e)})}_call(...e){return this.cache==null?this.#r(...e):this.cache().getOrSet(this.#n(...e),()=>this.#r(...e))}setShim(e){this.#t=e}hasShim(){return this.#t!=null}clearShim(){this.#t=void 0}cacheDelete(e){this.cache?.().delete(this.#n(...e))}},volsha=memoize(e=>mapNotBlank(e,shortStringSha),{name:`uri.volsha`,ttlMs:5*minuteMs}),import_node_crypto5=require("node:crypto"),import_node_path36=require("node:path"),import_node_path34=__toESM(require("node:path"));function isExplicitScanPath(e){return!!(Settings2.argvScanPaths.values.some(n=>eqlPath(n,e))||Settings2.scanPaths.values.some(n=>eqlPath(n,e))||(Settings2.scanLibraryFirst.valueOrDefault||Settings2.scanLibraryLast.valueOrDefault)&&[libraryDir(),originalsDir()].some(n=>n!=null&&eqlPath(n,e)))}var logger33=lazy2(()=>mkLogger(`fs.hasNoMedia()`)),NoMedia=`NoMedia`,nomediaRe=RegExp(`(?:^|[`+uniq([escapeRegExp(import_node_path34.default.sep),`/`]).join(``)+`])\\.?`+NoMedia+`$`,`im`);function variants(e){return[e,e.toLowerCase(),e.toUpperCase()]}var NoMediaNames=Object.freeze([`.`+NoMedia,NoMedia].flatMap(variants));function honorsNoMediaMarkersIn(e){return isWin||e!==`/`}function isNoMediaName(e){return nomediaRe.exec(e)!=null}var noMediaDirsCache=lazy2(()=>new FileCache({name:`fs.noMediaDirsCache`}));async function whyNoMedia(e,n){if(e==null)return null;let r=BaseFile.for(e),a=await r.stat();if(a==null||!a.isFile()&&!a.isDirectory())return null;if(a.isFile())return isNoMediaName(r.base)&&honorsNoMediaMarkersIn(r.parent().nativePath)||await isCachedirTagFile(r)?noMediaDirsCache().setAndGet(r.parent().nativePath,ciSafePath(r.nativePath)):whyNoMedia(r.parent());{let e=await noMediaDirsCache().getOrSet(r.nativePath,()=>whyNoMediaDir(r));return e!=null||!1===n?.recurse||r.isRoot||isExplicitScanPath(r.nativePath)||await isMountPoint(r.nativePath)?e:whyNoMedia(r.parent())}}async function whyNoMediaDir(e){if(isNoMediaName(e.base)&&honorsNoMediaMarkersIn(e.dir))return noMediaDirsCache().set(e.dir,e.nativePath),logger33().tap({msg:`whyNoMedia()`,result:ciSafePath(e.nativePath)});let n=await _dirHasNoMediaChild(e.nativePath);return n==null?await isCachedirTagDirectory(e)?logger33().tap({msg:`whyNoMedia()`,result:ciSafePath((0,import_node_path34.join)(e.nativePath,CACHEDIR_TAG))}):null:(noMediaDirsCache().set(e.nativePath,n),n)}async function _dirHasNoMediaChild(e){if(!honorsNoMediaMarkersIn(e))return null;for(let n of NoMediaNames){let r=import_node_path34.default.join(e,n);if(await exists(r,LogLevels.trace))return logger33().tap({msg:`_dirHasNoMediaChild`,result:ciSafePath(r)})}return null}var import_node_path35=require("node:path"),InvalidURIError=class extends Error{name=`InvalidURIError`;retriable=!1;doNotSend=!0};function isInvalidURIError(e){return e instanceof InvalidURIError||e instanceof Error&&e.name===`InvalidURIError`}function comparePsfileMountPoints(e,n){return e.length-n.length||(e<n?-1:+(e>n))}function selectPsfileMountPoint(e,n){let r=e.filter(e=>e.exists);if(r.length===0){if(n.missingFallback===`first`)return e[0];let r;for(let n of e)(r==null||comparePsfileMountPoints(n.mountPoint,r.mountPoint)<0)&&(r=n);return r}let a=n.preferredNativePath;if(a!=null){let e=r.find(e=>sameNativePath(e.nativePath,a));if(e!=null)return e}let o;for(let e of r)(o==null||comparePsfileMountPoints(e.mountPoint,o.mountPoint)<0)&&(o=e);return o}var logger34=defer(()=>mkLogger(`uri.psfile`)),warnedNoVolshaMounts=new Set;function psfileUri(e){let n=toNotBlank(e.path)??`/`,r=toNotBlank(e.volsha)??volsha(e.volumeUUID);return(r==null?URI.file(n):URI.from({scheme:PS_LOCAL_FILE_SCHEME,authority:r,path:n})).toString()}async function nativePathToPsfile(e,n){if(blank(e))return;let r=n??await bestVolumeForPath(e);if(r==null){logger34().warn(`nativePathToPsfile(): no volume UUID found`,{file:e,volumeMetadata:r});return}if(blank(r.volsha)){let n={file:e,volume:r};r.isReadOnly===!0?logger34().info(`nativePathToPsfile(): no volsha for volume (readonly)`,n):warnedNoVolshaMounts.has(r.mountPoint)||(warnedNoVolshaMounts.add(r.mountPoint),logger34().warn(`nativePathToPsfile(): no volsha for volume`,n));return}let a=native2posix(e),o=native2posix(r.mountPoint),s=a;if(!s.normalize().startsWith(o.normalize())){let n=await dataVolumePath(e);n!=null&&(s=native2posix(n))}if(!s.normalize().startsWith(o.normalize())){let n=await resolvePathSymlinks(e);if(n!==e&&(s=native2posix(n),!s.normalize().startsWith(o.normalize()))){let e=await dataVolumePath(n);e!=null&&(s=native2posix(e))}}if(!s.normalize().startsWith(o.normalize()))return;let c=ensurePrefix(s.slice(o.length),`/`);return{nativePath:e,uri:URI.from({scheme:PS_LOCAL_FILE_SCHEME,authority:r.volsha,path:c})}}function joinMountpoint(e,n){return(0,import_node_path35.join)(e,...stripPrefix(n,`/`).split(`/`))}async function psfileToNativePath_(e){if(e.scheme!==PS_LOCAL_FILE_SCHEME)return logger34().throw(new InvalidURIError(`Invalid scheme: `+e));if(blank(e.authority))return logger34().throw(new InvalidURIError(`Missing authority: `+e));let n=await volshaToMountPoints(e.authority),r=selectPsfileMountPoint(await Promise.all(n.map(async n=>{let r=joinMountpoint(n,e.path);return{mountPoint:n,nativePath:r,exists:await exists(r)}})),{missingFallback:`shortest`});return r==null?logger34().tap({msg:`psfileToNativePath_(): no mount point found for volsha`,level:`debug`,result:void 0,meta:{uri:e.toString()}}):{mountPoint:r.mountPoint,nativePath:await canonicalizeMacPath(r.nativePath)}}var logger35=lazy2(()=>mkLogger(`volumes.VolumeUUID`)),warnedPaths=new Cache({name:`VolumeUUID.warnedPaths`,maxSize:256,ttlMs:36e5}),writeErrors=new Cache({name:`VolumeUUID.writeErrors`,maxSize:256,ttlMs:36e5});function volumeUuidNotExpected(e){return isPosix&&!0===e.isSystemVolume||isDocker()&&e.mountPoint===`/`||isTest()&&(0,import_node_path36.basename)(e.mountPoint)===`node_modules`}async function addVolumeUUID(e){if(volumeUuidNotExpected(e))return fallbackVolumeUuid(e);let n=await readVolumeUUID(e);return n!=null&&(e.uuid=n),n}function toVolumeUUID(e){if(blank(e))return;let n=stripComments(e).replace(/[^\da-z-]+/gi,``).trim().replace(/^-|-$/g,``);return n.length<8||/^[0-]*$/.test(n)||/^[F-]*$/i.test(n)?void 0:n}var MaxUint64=(1n<<64n)-1n;function toZfsGuid(e){if(e==null||!/^[1-9]\d{0,19}$/.test(e))return;let n=BigInt(e);return n<=MaxUint64?n.toString(10):void 0}function zfsVolumeUuid(e){let n=toZfsGuid(e.zfsPoolGuid),r=toZfsGuid(e.zfsDatasetGuid);return n==null||r==null?void 0:`zfs-${n}-${r}`}function parseZfsVolumeUuid(e){let n=/^zfs-(\d+)-(\d+)$/i.exec(e);if(n==null)return;let r=toZfsGuid(n[1]),a=toZfsGuid(n[2]);return r==null||a==null?void 0:{poolGuid:r,datasetGuid:a}}function isZfsVolumeUuid(e){return parseZfsVolumeUuid(e)!=null}function fallbackVolumeUuid(e){return toVolumeUUID(e.subvolumeUuid)??zfsVolumeUuid(e)??toVolumeUUID(e.uuid)??toVolumeUUID(e.fsid)}function isMissingUuidFileError(e){let n=errorCode(e);return n===`ENOENT`||n===`ENOTDIR`}async function readUuidFileIds_(e){let n=await thenOrTimeoutError(e.readText_(),commandTimeoutMs()),r=[];for(let e of splitLines(n)){let n=toVolumeUUID(e);n!=null&&!r.includes(n)&&r.push(n)}return r}async function mayHoldIdentity(e){try{return await stat_(e.nativePath),!0}catch(e){return!isMissingUuidFileError(e)}}async function readExistingVolumeUuidFile(e){let n=PosixFile.for(e.mountPoint).join(volumeUuidSubpath()),r=n.nativePath,a=Settings2.readVolumeUuidFiles.valueOrDefault?Settings2.volumeUuidFilePaths.values:[],o=!1,s=!1;for(let n of a){let a=PosixFile.for(e.mountPoint).join(n),c=a.nativePath===r;c&&(s=!0);try{let e=await readUuidFileIds_(a);if(e.length>0)return{ids:e,unsafeToOverwrite:o}}catch(e){c&&!isMissingUuidFileError(e)&&(o=!0),warnedPaths.getOrSet(`read:`+a.nativePath,()=>(logger35().info(`Failed to read `+a,{error:e}),!0))}}return s||(o=await mayHoldIdentity(n)),{ids:[],unsafeToOverwrite:o}}async function skipWriteAsNoMedia(e){return Settings2.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault?await whyNoMediaDir(BaseFile.for(e.mountPoint))!=null:!1}async function whyCannotWriteVolumeUuidFile(e,n){if(n.unsafeToOverwrite)return`a ${volumeUuidSubpath()} is already here, but could not be read`;if(e.mountPoint===`/`)return`the mount point is the root directory`;if(!Settings2.writeVolumeUuidFiles.valueOrDefault)return`${Settings2.writeVolumeUuidFiles.key} is false`;if(await skipWriteAsNoMedia(e))return`the mount point is marked as containing no media`}async function canWriteVolumeUuidFile(e,n){return await whyCannotWriteVolumeUuidFile(e,n)==null}async function readVolumeUUID(e){let n=zfsVolumeUuid(e),r=toVolumeUUID(e.subvolumeUuid)??n,a=await readExistingVolumeUuidFile(e),o=a.ids,s=toZfsGuid(e.zfsPoolGuid),c=toZfsGuid(e.zfsDatasetGuid),l=o.some(e=>{let n=parseZfsVolumeUuid(e);return n!=null&&(s!=null&&n.poolGuid!==s||c!=null&&n.datasetGuid!==c)}),u=l&&n==null,d=l?[]:o,f=d[0];f!=null&&(e.uuidFileContent=f),d.length>0&&(e.uuidFileContents=d);let h=r??f??fallbackVolumeUuid(e),_=(0,import_node_path36.join)(e.mountPoint,volumeUuidSubpath());if(n!=null&&o.length>0&&(o[0]!==n||l)&&await canWriteVolumeUuidFile(e,a)){let r=toVolumeUUID(e.fsid),a=l?[]:[...new Set([...o.filter(e=>e!==n&&!isZfsVolumeUuid(e)),...r==null?[]:[r]])],s=await writeVolumeUuid({mountPoint:e.mountPoint,fstype:e.fstype,uuid:n,aliases:a});if(!blank(s))return e.uuidFileContent=n,e.uuidFileContents=[n,...a],logger35().tap({msg:`readVolumeUUID(): persisted authoritative ZFS identity at `+_,result:s,meta:{volume:e,priorFileUuids:o}})}if(r!=null&&f!=null&&f!==r&&f===toVolumeUUID(e.uuid)&&await canWriteVolumeUuidFile(e,a)){let n=d.filter(e=>e!==r),a=await writeVolumeUuid({mountPoint:e.mountPoint,fstype:e.fstype,uuid:r,aliases:n});if(!blank(a))return e.uuidFileContent=a,e.uuidFileContents=[a,...n],logger35().tap({msg:`readVolumeUUID(): rewrote stale filesystem-uuid .uuid to the strong intrinsic id at `+_,result:a,meta:{volume:e,priorFileUuid:f}})}if(f==null&&!u&&await canWriteVolumeUuidFile(e,a)){let r=n!=null&&o.length===0?toVolumeUUID(e.fsid):void 0,a=r==null?[]:[r],s=await writeVolumeUuid({mountPoint:e.mountPoint,fstype:e.fstype,uuid:h,aliases:a,allowDefaultFilesystemBlocklistBypass:h==null});if(!blank(s))return e.uuidFileContent=s,e.uuidFileContents=[s,...a],logger35().tap({msg:`readVolumeUUID(): created `+_+(h==null?`, minting a random id: this volume exposes no identity of its own`:`, holding the volume's own id`),result:s,meta:{volume:e}})}return logger35().tap({msg:`readVolumeUUID(): serving `+(r==null?f==null?`volume metadata`:`.uuid file`:`strong intrinsic`)+` UUID`,result:h,meta:{mountpoint:e.mountPoint}})}function volumeUuidSubpath(){return toNotBlank(Settings2.volumeUuidFilePaths.values[0])??`.uuid`}function whyNotWriteVolumeUuid(e,{allowDefaultFilesystemBlocklistBypass:n=!1}={}){let r=Settings2.writeVolumeUuidFilesystemBlocklist,a=n&&r.isUnset()?[]:r.values;for(let n of a){let r=toNotBlank(n);if(r!=null&&matchesWriteVolumeUuidFilesystemBlocklistEntry(e.fstype,r))return`filesystem type "${e.fstype}" is in writeVolumeUuidFilesystemBlocklist`}let o=normalizeMountpointBlocklistPath(e.mountPoint);for(let e of Settings2.writeVolumeUuidPathBlocklist.values){let n=toNotBlank(e),r=n==null?void 0:normalizeMountpointBlocklistPath(n);if(r!=null&&o.includes(r))return`mount point matches "${e}" in writeVolumeUuidPathBlocklist`}}function normalizeMountpointBlocklistPath(e){return e.replace(/\\/g,`/`).toLowerCase()}async function writeVolumeUuid({mountPoint:e,fstype:n,uuid:r,aliases:a=[],allowDefaultFilesystemBlocklistBypass:o=!1}){let s=whyNotWriteVolumeUuid({mountPoint:e,fstype:n},{allowDefaultFilesystemBlocklistBypass:o});if(s!=null){warnedPaths.getOrSet(`blocklist:`+e,()=>(logger35().info(`writeVolumeUuid(): skipping ${e}: ${s}`),!0));return}let c=(0,import_node_path36.join)(e,volumeUuidSubpath());r=toVolumeUUID(r)??(0,import_node_crypto5.randomUUID)();let l=await readWriteableDirectoryError((0,import_node_path36.dirname)(c));if(l==null)try{return await writeText_(c,...volumeUuidText(r,a)),logger35().info(`writeVolumeUuid(): wrote `+c,{uuid:r,aliases:a}),writeErrors.delete(c),r}catch(n){writeErrors.set(c,`${c} could not be written: ${errorToS(n)}`),warnedPaths.getOrSet(`saveFail:`+c,()=>(logger35().warn(`writeVolumeUuid(): Failed to save new UUID for `+e,{error:n}),!0))}else writeErrors.set(c,`${c} cannot be written: ${l.code}: ${l.message}`),warnedPaths.getOrSet(`write:`+c,()=>(logger35().warn(`writeVolumeUuid(): cannot write to ${c}: ${l.code}: ${l.message}`),!0))}function volumeUuidText(e,n=[]){let r=[...new Set(n.map(toVolumeUUID).filter(n=>n!=null&&n!==e))];return[e,``,...r.length===0?[]:[`# Alternate identities retained for URI compatibility:`,...r,``],`# This volume UUID was written by PhotoStructure v`+version,`# See https://photostructure.com/faq/what-is-a-volume/ for details.`,`# Files found on this volume will have a URI that starts with`,`# `+psfileUri({volumeUUID:e,path:`/`})]}var import_picomatch=__toESM(require("picomatch")),import_types2=require("node:util/types"),FifoCache=class{#e;#t;#n;#r;#i;#a=new Map;#o={hits:0,misses:0,errors:0,timeouts:0};constructor(e){this.#e=e,this.setOptions({})}get opts(){return{...this.#e}}setOptions(e){let n={...this.#e};Object.assign(this.#e,e);let r=(e,n,r)=>(e!=null&&clearInterval(e),gt0(n)?setInterval(()=>r(),n).unref():void 0),{clearEveryMs:a,ttlMs:o,maxSize:s}=this.#e;a!==this.#r&&(this.#t=r(this.#t,a,()=>this.clear()),this.#r=a),o!==this.#i&&(this.#n=r(this.#n,gt0(o)?Math.round(o/3):void 0,()=>this.vacuum()),this.#i=o),(s!==n.maxSize||o!==n.ttlMs)&&this.vacuum()}has(e){return this.#a.has(e)}hasSync(e){return this.#a.has(e)&&!(0,import_types2.isPromise)(this.#a.get(e)?.v)}getSync(e){let n=this.#a.get(e)?.v;if(n==null||isPromiseLike(n))this.#o.misses++;else return this.#o.hits++,n??null}_get(e){return this.#a.get(e)?.v}get(e){let n=this.#a.get(e)?.v;if(n!=null)return this.#o.hits++,n;this.#o.misses++}clear(){this.#a.clear()}delete(e){return this.#a.delete(e)}async deleteIf(e){for(let[n,r]of this.#a.entries())await e(n,r.v)&&this.delete(n)}entries(){return this.#a.entries()}values(){return this.#a.values()}get size(){return this.#a.size}stats(){return{size:this.size,...this.#o}}vacuum(){if(gt0(this.#e.ttlMs)){let e=performance.now()-this.#e.ttlMs;for(let[n,r]of this.#a.entries())r.ts<=e&&this.#a.delete(n)}if(gt0(this.#e.maxSize)){let e=this.#a.keys();for(;this.size>this.#e.maxSize;){let n=e.next().value;if(n==null)break;this.#a.delete(n)}}}set(e,n){if(this.vacuum(),n==null)return this.#a.delete(e),n;if((0,import_types2.isPromise)(n)){let r=thenOrTimeoutError(n,this.#e.timeoutMs);return r.then(n=>{this.#a.get(e)?.v===r&&this.#a.set(e,{ts:performance.now(),v:n})}).catch(e=>{this.#o.errors++,isTimeoutError(e)&&this.#o.timeouts++}),this.#a.set(e,{ts:performance.now(),v:r}),r}return this.#a.set(e,{ts:performance.now(),v:n}),n}getOrSet(e,n){if(this.#e.noop===!0)return this.#o.misses++,n();let r=this.#a.get(e)?.v;return r==null?(this.#o.misses++,this.set(e,n())):(this.#o.hits++,r)}mergeStats(e){for(let[n,r]of Object.entries(e))n in this.#o&&(this.#o[n]+=r)}};function negateFilterName(e){if(blank(e))return;let n=/\s/.test(e)?e:camel2words(e).replace(/\bphoto structure\b/gi,`PhotoStructure`);return n.match(/^not\b/)?n.replace(/^not\b/,``).trim():`not `+stripPrefix(n,`is `)}var _logger=lazy2(()=>mkLogger(`predicates.Predicates`)),Predicates=class e{static async accepted(e,...n){for(let r of n)for(let n of values(r)){let r=await n(e);if(r===!1||isString(r))return!1}return!0}static async rejected(n,...r){return!await e.accepted(n,...r)}static async explain(e,...n){let r=[],a=[],o=[];for(let s of n)for(let[n,c]of entries(s)){let s=await c(e);s===!0?r.push(n):s===!1||isString(s)?a.push(n):o.push(n)}return{accepted:r,rejected:a,notApplicable:o}}static async whyRejected(e,...n){for(let r of n)for(let[n,a]of entries(r))try{let r=await a(e);if(r==null||r===!0)continue;return isString(r)?r:negateFilterName(n)}catch(e){if(isTimeoutError(e))throw e;_logger().warn(`whyRejected() caught from `+n,{error:e})}}static async logged({a:n,logger:r,msg:a,predicates:o}){let{accepted:s,rejected:c}=await e.explain(n,...o);return r.tap({msg:a,result:isEmpty(c),meta:{a:n,accepted:s,rejected:c}})}},import_fs_metadata2=require("@photostructure/fs-metadata");async function hide_(e){if(!isWin&&!isMac)return;let n=toNativePath_(e),r=await(0,import_fs_metadata2.setHidden)(n,!0);return await ee().emit(`fileChanged`,r.pathname),r.pathname}async function isHidden_(e){let n=toNativePath_(e);return!pathIsRoot(n)&&await(0,import_fs_metadata2.isHidden)(n)}function seemsLikeSymlinkLoop(e){let n=new CountingSet;for(let r of toPathnames(e)??[])n.incr(r.toLowerCase().normalize());return n.max()>Settings2.maxDuplicatePathElements.valueOrDefault}var logger36=lazy2(()=>mkLogger(`fs.ExcludeGlobs`)),path2formattedPathForGlobCache=new FifoCache({maxSize:256}),EndWithSepRe=/[\\/]$/;function formatPathForGlob(e){let n=toS(e),r=path2formattedPathForGlobCache.getSync(n);if(r!=null)return r;let a=isSimpleFile(e)?e:BaseFile.for(e),o=EndWithSepRe.test(n)||a.isDirectorySync(),s=native2posix(a.nativePath),c=o?ensureSuffix(s,`/`):s;return path2formattedPathForGlobCache.set(n,c),path2formattedPathForGlobCache.set(c,c),path2formattedPathForGlobCache.set(a.nativePath,c),c}var Glob=class{constructor(e,n,r=!0){if(this.pattern=e,this.desc=n,this.exclude=r,e.includes(`\\`)){let n=e;e=native2posix(n),logger36().warn(`globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?`,{given:n,input:e})}this.reason=compactBlanks([this.exclude?`not`:``,n,`(`+ellipsize(e,48,12)+`)`]).join(` `);let a=FiltersSettings.globsCaseInsensitive.valueOrDefault;try{this.re=import_picomatch.default.makeRe(this.pattern,{nocase:a,dot:!0}),this.valid=!0}catch(e){this.valid=!1,logger36().warn(`Cannot parse pattern`,{glob:this.pattern,error:e})}this.bundle=this.valid&&this.re!=null?pairToObject(this.reason,this.#e.bind(this)):{}}pattern;desc;exclude;reason;re;bundle;valid;#e(e){let n=formatPathForGlob(e),r=this.re?.test(n)??this.exclude,a=r?!this.exclude:this.exclude;return logger36().tap({msg:`apply()`,level:LogLevels.trace,result:a,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:n,matched:r}})}},GlobSet=class{#e=[];push(...e){for(let n of e){if(!n.valid){logger36().warn(`Ignoring invalid glob`,{glob:n});continue}let e=this.#e.find(e=>e.pattern===n.pattern);e==null?this.#e.push(n):logger36().debug(`Ignoring duplicate glob`,{glob:n,prior:e})}}pushNativePath(e,n){this.push(new Glob(native2posix(e),n))}toA(){return this.#e}},defaultExcludeGlobs=lazy2(()=>{let e=new GlobSet;e.push(new Glob(`**/.*/`,`hidden directory`),new Glob(`**/.*`,`hidden file`));for(let n of[{s:`boot`,desc:`boot drive`},{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 Glob((isWin?`*`:``)+`/`+n.s+`/`,n.desc));if(isWin)for(let n of[`ProgramFiles`,`ProgramFiles(x86)`,`ProgramW6432`,`SystemRoot`,`windir`]){let r=process.env[n];blank(r)||e.pushNativePath(r,`%${n}%`)}isLinux&&(e.push(new Glob(`${homeDir()}/snap/`,`Snap software`)),e.push(new Glob(`/run/!(media|user)/`,`Linux runtime data`)),e.push(new Glob(`/run/user/*/!(gvfs|kio-fuse-*)/`,`Linux runtime data`)));for(let n 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:`$SysReset`,desc:`Windows`},{s:`3rdParty`,desc:`code`},{s:`Application Data`,desc:`Windows apps`},{s:`Application Support`,desc:`macOS apps`},{s:`Applications`,desc:`macOS apps`},{s:`arangodb`,desc:`3rd party`},{s:`cache`,desc:`Cache directory`},{s:`CacheClip`,desc:`Movie cache directory`},{s:`caches`,desc:`Cache directory`},{s:`Chipset_Software`,desc:`Windows apps`},{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 apps`},{s:`Program Files`,desc:`Windows apps`},{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:`SystemTemp`,desc:`Windows temporary`},{s:`temp`,desc:`temporary`},{s:`Temporary Items`,desc:`temporary`},{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`},{s:`Trash`,desc:`trash directory`},{s:`Windows`,desc:`Windows`},{s:`Windows.old`,desc:`Windows`},{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 Glob(`**/`+n.s+`/`,n.desc));map(configDir(),n=>e.pushNativePath(n,`PhotoStructure configuration`));function n(n,r,a){if(!blank(n)){let o=sort(uniq(compactBlanks(r).map(e=>e.toLowerCase())));o.length===1&&e.push(new Glob(`**/${n}/${o[0]}/`,a)),o.length>1&&e.push(new Glob(`**/${n}/(${o.join(`|`)})/`,a))}}n(`nix`,[`store`],`NixOS package`),e.push(new Glob(`**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/`,`Apple Photos/Aperture library`)),n(`PhotoData`,[`Metadata`],`iOS Photos metadata`),e.push(new Glob(`**/facetile*`,`face thumbnail`));let r=[`bin`,`cygdrive`,`dev`,`etc`,`games`,`include`,`lib?(32|64|x64)`,`libexec`,`local`,`locale`,`man`,`proc`,`sbin`,`share`,`src`,`tmp`,`usr`,`var`];n(`usr`,r,`FHS system`),n(`cygwin?(64)`,r,`Cygwin`),n(`local`,r,`FHS system`),n(`Windows`,[`assembly`,`Boot`,`Containers`,`Cursors`,`Fonts`,`Help`,`Installer`,`Logs`,`Microsoft.NET`,`Servicing`,`SoftwareDistribution`,`System32`,`SystemApps`,`SysWOW64`,`Temp`,`WinSxS`],`Windows`),n(`Recovery`,[`Customizations`,`OEM`],`Windows`),n(`lib`,[`firmware`,`modules`,`systemd`,`udev`,`x86_64-linux-gnu`],`Linux system package`),n(`opt`,[`google`,`x11`,...r],`FHS package`),n(`lfs`,[`incomplete`,`objects`],`Git LFS object`);let a=[`cache`,`crash`,`games`,`lib`,`local`,`lock`,`log`,`logs`,`mail`,`run`,`snap`,`spool`,`tmp`];n(`var`,a,`Linux /var`),n(`mnt`,a,`Linux /mnt`),n(`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`),n(`proc`,[`acpi`,`asound`,`bus`,`driver`,`fs`,`ipmi`,`irq`,`net`,`scsi`,`self`,`sys`,`sysvipc`,`thread-self`,`tty`],`Linux /proc backup`),n(`library`,`Apple,Assistant,Bluetooth,com.apple.iTunesCloud,Containers,CoreAnalytics,Developer,Desktop Pictures,Documentation,Extensions,Finance,Fonts,Frameworks,FrontBoard,Group Containers,HTTPStorages,iTunes,KeyboardServices,Keychains,Logs,Messages,News,Passes,Photos,Preferences,Ruby,Saved Application State,Scripts,User Pictures,Updates,User Template,WebKit,WebServer`.split(`,`),`macOS Library`),n(`packages`,[`*.pkg`,`*.mpkg`],`macOS package`),n(`src/**`,[`bin`,`ci`,`dist`,`doc?(s)`,`etc`,`lib?(s)`,`main`,`spec?(s)`,`src`,`test?(s)`,`tools`,`util`],`code`),n(`docs`,[`admin`,`content`,`general`,`generated`,`sql`],`code`),n(`pkg`,[`acceptance`,`ccl`,`cli`,`cmd`,`server`,`sql`,`storage`,`ui`,`util`,`workload`],`code`),n(`osv`,[`apps`,`arch`,`compiler`,`external`,`include`,`java`,`modules`,`musl`,`tests`],`code`),n(`go`,[`bin`,`blog`,`cmd`,`doc`,`lib`,`misc`,`pkg`,`src`,`test`,`vt`],`code`),n(`Perl?(64)`,[`bin`,`eg`,`etc`,`html`,`lib`,`site`],`code`),n(`Python*`,[`dlls`,`doc?(s)`,`include`,`lib?(s)`,`scripts`,`tools`,`tcl`],`code`),n(`Ruby*`,[`bin`,`include`,`lib`,`msys*`,`packages`,`share`,`ssl`],`code`),n(`msys*`,[`clang*`,`dev`,`etc`,`mingw*`,`tmp`,`ucrt*`,`var`],`code`),n(`sdk`,[`build-tools`,`emulator`,`extras`,`patcher`,`platforms`,`platform-tools`,`sources`,`tools`],`code`),n(`test`,[`fixtures`],`code`),n(`data`,[`$of`],`windows backup`),n(`System`,[`Applications`,`Developer`,`DriverKit`,`Library`,`iOSSupport`,`Update`,`Preboot`],`macOS System`),n(`Volumes/Data`,[`Applications`,`etc`,`mnt`,`private`,`sw`,`System`,`tftpboot`,`tmp`,`usr`,`var`],`macOS System`),n(`contents`,[`frameworks`,`plugins`,`resources`,`sharedsupport`],`macOS application`),n(`pg`,[`pgsql`],`code`);for(let e of[`local`,`locallow`,`roaming`])n(`appdata`,[e],`Windows default AppData`);return e.toA()}),clearCaches=()=>{excludeGlobs.unset(),excludeBundles.unset()},clearNotExcludedDirs=()=>{notExcludedDirs.unset()},watchSettings=lazy2(()=>{FiltersSettings.excludeGlobsOmitDefaults.watchLater(clearCaches),FiltersSettings.excludeGlobsAdd.watchLater(clearCaches),FiltersSettings.excludeGlobsOmit.watchLater(clearCaches),FiltersSettings.globsCaseInsensitive.watchLater(clearCaches),PathSettings.libraryDir.watchLater(clearNotExcludedDirs),PathSettings.originalsDir.watchLater(clearNotExcludedDirs),PathSettings.scanPaths.watchLater(clearNotExcludedDirs),PathSettings.argvScanPaths.watchLater(clearNotExcludedDirs)}),defaultDirPredicates=lazy2(()=>[{notSymlinkLoop,notInInternalPhotoStructureDir,whyNoMedia,notHidden}]),defaultFilePredicates=lazy2(()=>[{notInInternalPhotoStructureDir}]),excludeGlobs=lazy2(()=>{watchSettings();let e=new CaseInsensitiveMap;function n(n){if(n!=null&&n.valid){let r=n.pattern.trim();e.has(r)&&logger36().warn(`Duplicate glob:`,{glob:n}),e.set(r,n)}}function r(n){let r=n.trim();e.has(r)?e.delete(r):logger36().warn(`Failed to find and remove glob specified in ${FiltersSettings.excludeGlobsOmit.key}`,{glob:n})}if(!FiltersSettings.excludeGlobsOmitDefaults.valueOrDefault)for(let e of defaultExcludeGlobs())n(e);for(let e of FiltersSettings.excludeGlobsOmit.values)r(e);for(let e of FiltersSettings.excludeGlobsAdd.values)n(new Glob(e,`(from ${FiltersSettings.excludeGlobsAdd.key})`));let[a,o]=partition(sortBy(e.values(),e=>compactBlanks(e.pattern.toLowerCase().split(`/`))),e=>e.pattern.endsWith(`/`));return{dir:a,file:o}}),excludeBundles=lazy2(()=>{let e=excludeGlobs();return{dir:[...e.dir.map(e=>e.bundle),...defaultDirPredicates()],file:[...defaultFilePredicates(),...e.file.map(e=>e.bundle)]}}),ifDisabled=[{notInInternalPhotoStructureDir}],ifBlank=[{notBlank:()=>!1}];function excludedFilePredicates(e){return FiltersSettings.disableAllFilters.valueOrDefault?ifDisabled:blank(e)?ifBlank:excludeBundles().file}function excludedDirPredicates(e){return FiltersSettings.disableAllFilters.valueOrDefault?ifDisabled:blank(e)?ifBlank:excludeBundles().dir}async function whyExcludedDirectory(e){return Predicates.whyRejected(e,...excludedDirPredicates(e))}function testRepoRoot(){return isTest()?repoRoot():void 0}var notExcludedDirs=lazy2(()=>logger36().tap({msg:`notExcludedDirs() (these directories will never be excluded)`,level:`info`,result:uniq(compactBlanks([libraryDirPosixFile(),libraryOriginalsDirPosixFile(),testRepoRoot(),...PathSettings.argvScanPaths.values,...PathSettings.scanPaths.values]))}));async function whyExcludedDirectoryRecursive(e){let n=notExcludedDirs();for(let r=e;r!=null&&!r.isRoot;r=await r?.parent()){if(n.includes(r?.nativePath))return;let e=await whyExcludedDirectory(r);if(e!=null)return e}}function notSymlinkLoop(e){return!seemsLikeSymlinkLoop(e)}function notHidden(e){return isLinux||!FiltersSettings.excludeHidden.valueOrDefault||thenNot(isHidden_(e))}function notInInternalPhotoStructureDir(e){return!isInInternalDir(e)}var logger37=defer(()=>mkLogger(`fs.FsMetadata`)),getMountPoints=lazyAsync({desc:`getVolumeMountPoints`,later:()=>_getMountPoints()}),allMountPoints=lazyAsync({desc:`allVolumeMountPoints`,later:()=>_getMountPoints(!0)});async function _getMountPoints(e){let n=e===!0;if(getDevEnvFlag(`PS_FAIL_VOLUMES`))throw Error(`PS_FAIL_VOLUMES`);let r=fsmOptions(),a=await time({name:n?`fs.allVolumeMountPoints`:`fs.volumeMountPoints`,p:mapAsync({iter:await fsm.getVolumeMountPoints(n?{...r,includeSystemVolumes:e}:r),f:async e=>compactValues({...e,ok:isOK(e)})})});invalidateObservedMountPointMetadata(a);let o=libraryDirs_(),s=PathSettings.scanPaths.valueOrDefault.map(e=>BaseFile.for(e));return sortBy(a,e=>[!o.some(n=>n.isSelfOrDescendantOf(e.mountPoint)),!s.some(n=>n.isSelfOrDescendantOf(e.mountPoint)),e.mountPoint])}var _volshaToMountPoint=new MultiMap,_mountPointToVolsha=new Map,lastMountPointListInvalidationAt;function invalidateMountPointLists({force:e=!1}={}){let n=performance.now(),r=FilesystemSettings.mountpointRefreshMinIntervalMs.valueOrDefault;return!e&&(r<=0||lastMountPointListInvalidationAt!=null&&n-lastMountPointListInvalidationAt<r)?!1:(lastMountPointListInvalidationAt=n,getMountPoints.clear(),allMountPoints.clear(),!0)}function addMountPointVolsha(e){e.fromCache!==!0&&_volshaToMountPoint.filterInPlace((n,r)=>r!==e.mountPoint||n===e.volsha),_volshaToMountPoint.addUniq(e.volsha,e.mountPoint),e.fromCache===!0&&_mountPointToVolsha.has(e.mountPoint)||_mountPointToVolsha.set(e.mountPoint,e.volsha)}var onHealthyVolumeDiscovered=shimSync({name:`FsMetadata.onHealthyVolumeDiscovered`,impl:e=>{}}),freshVolumeMetadataObservers=new Set;function notifyFreshVolumeMetadata(e,n){for(let r of freshVolumeMetadataObservers)try{r(e,n)}catch(n){logger37().warn(`Fresh volume metadata observer failed`,{mountPoint:e.mountPoint,error:n})}}var volshaToMountPointFallback=shimSync({name:`volshaToMountPointFallback`,impl:e=>[]});async function volshaToMountPoints(e){return volshaToMountPoints_(e,!0)}async function volshaToMountPoints_(e,n){let r=getMountPoints.lastValue()!=null,a=[],o=new Map;for await(let n of volumesWithUUIDs()){let r=n.volshas??(n.volsha==null?[]:[n.volsha]);o.set(n.mountPoint,n),r.includes(e)&&a.push(n.mountPoint)}let s=n=>{let r=o.get(n);return r==null||(r.volshas??(r.volsha==null?[]:[r.volsha])).includes(e)},c=(_volshaToMountPoint.get(e)??[]).filter(s);if(n&&r&&a.length===0&&invalidateMountPointLists())return volshaToMountPoints_(e,!1);let l=uniq([...a,...c]);return l.length>0?l:volshaToMountPointFallback(e).filter(s)}function volumeClaimsAuthority(e,n){return(e.volshas??(e.volsha==null?[]:[e.volsha])).includes(n)}async function isVolumeAuthorityMountedAt({mountPoint:e,volumeSha:n}){if(await mountPointIdForPath(e)!==e)return!1;let r=await refreshVolumeMetadata(e,FilesystemSettings.missingFileVolumeProofTtlMs.valueOrDefault);return r?.ok===!0&&volumeClaimsAuthority(r,n)}function isOK(e){return blank(e?.error)&&(e?.status??`healthy`)===`healthy`}var getVolumeMetadataCache=new Cache({name:`fs.FsMetadata.getVolumeMetadata`,ttlMs:0,maxSize:256});function invalidateObservedMountPointMetadata(e){invalidateMountPointMetadata(e.map(e=>e.mountPoint))}function invalidateMountPointMetadata(e){let n=new Set(e);_volshaToMountPoint.filterInPlace((e,r)=>!n.has(r));for(let e of n)_mountPointToVolsha.delete(e),getVolumeMetadataCache.deleteArgs(e)}async function getVolumeMetadata(e){try{return await getVolumeMetadata_(e)}catch(n){logger37().warn(`getVolumeMetadata() failed`,{mountPoint:e,error:n});return}}async function loadVolumeMetadata_(e){return time({name:`fs.volumeMetadata`,meta:{volume:e},p:async()=>{let n=Date.now(),r=await fsm.getVolumeMetadata(e,fsmOptions());if(!gte0(r.available))return logger37().throw(`getVolumeMetadata(): invalid available`,{vol:r});let a=toVolumeUUID(r.uuid),o=toVolumeUUID(r.subvolumeUuid),s=zfsVolumeUuid(r),c=toVolumeUUID(r.fsid),l=await addVolumeUUID(r),u=[URI.file(r.mountPoint).toString()];r.volshas=uniq([volsha(l),volsha(o),volsha(s),volsha(a),volsha(c),volsha(toVolumeUUID(r.uuidFileContent)),...(r.uuidFileContents??[]).map(e=>volsha(toVolumeUUID(e)))]);let d=r.volshas[0];return d!=null&&(r.volsha=d,u.push(URI.from({scheme:PS_LOCAL_FILE_SCHEME,authority:d,path:`/`}).toString()),addMountPointVolsha({mountPoint:r.mountPoint,volsha:d,fromCache:!1})),r.uris=sortURIs(uniq(u,r.uris)),r.ok=isOK(r),r.ok&&(onHealthyVolumeDiscovered(r),notifyFreshVolumeMetadata(r,n)),r}})}var getVolumeMetadata_=getVolumeMetadataCache.memoize(loadVolumeMetadata_);async function refreshVolumeMetadata(e,n){try{return await getVolumeMetadata_.refreshIfOlderThan(n,e)}catch(n){logger37().warn(`refreshVolumeMetadata() failed`,{mountPoint:e,error:n});return}}function setVolumeMetadataTTL(e){getVolumeMetadataCache.setTTL(e)}later(()=>{VolumesSettings.volumeMetadataTtlMs.watch(setVolumeMetadataTTL)});function getExcludedMountpointPaths(){let e=new Set(FilesystemSettings.excludedMountpointPaths.valueOrDefault);for(let n of FilesystemSettings.excludedMountpointPathsOmit.values)e.delete(n);for(let n of FilesystemSettings.excludedMountpointPathsAdd.values)e.add(n);return[...e]}function fsmOptions(){return fsm.optionsWithDefaults({systemFsTypes:FilesystemSettings.excludedFilesystemTypes.valueOrDefault,systemPathPatterns:getExcludedMountpointPaths(),timeoutMs:FilesystemSettings.statTimeoutMs.valueOrDefault,includeZfsGuids:FilesystemSettings.includeZfsGuids.valueOrDefault})}async function isMountPoint(e){let n=await getMountPoints(),r=await canonicalizeMacPath(e);return n.some(n=>n.mountPoint===e||n.mountPoint===r)}async function bestMountPointForPath(e,n){if(blank(e))return;let r=toNotEmpty(n),a=allMountPoints.lastValue()!=null,o=r??await allMountPoints(),s=await bestMountPointForPath_(e,o);return s!=null||r!=null||!a||!invalidateMountPointLists()?s:(o=await allMountPoints(),bestMountPointForPath_(e,o))}async function mountPointIdForPath(e){if(blank(e))return;let n=fsmOptions(),r=e;for(;;){try{let e=await fsm.getMountPointForPath(r,n);if(notBlank(e))return e}catch(n){if(n?.code!==`ENOENT`){logger37().warn(`mountPointIdForPath(): cannot resolve mount point`,{nativePath:e,path:r,error:n});return}}let a=(0,import_node_path37.dirname)(r);if(a===r)return;r=a}}async function bestMountPointForPath_(e,n){let r={mountPoints:n,...fsmOptions()},a=e;for(;;){try{let e=await fsm.getMountPointForPath(a,r);if(e!=null)return n.find(n=>n.mountPoint===e)??{mountPoint:e,ok:!0}}catch(n){if(n?.code!==`ENOENT`){logger37().warn(`bestMountPointForPath(): error checking mount point`,{nativePath:e,pathToResolve:a,error:n});return}logger37().info(`bestMountPointForPath(): path does not exist, trying parent`,{nativePath:e,pathToResolve:a})}let o=(0,import_node_path37.dirname)(a);if(o===a)break;a=o}}async function bestVolumeForPath(e,n){let r=await bestMountPointForPath(e,n);if(r==null)return;let a=await getVolumeMetadata(r.mountPoint);return a??logger37().warn(`bestVolumeForPath(): no volume metadata found`,{nativePath:e}),a}async function*volumes(e=()=>!0){for(let n of await getMountPoints())try{n.ok&&await e(n)&&(yield await getVolumeMetadata_(n.mountPoint))}catch(e){logger37().warn(`volumes(): skipping volume`,{mp:n,error:e})}}async function*remoteVolumes(){for await(let e of volumes(e=>e.isSystemVolume!==!0))e.remote===!0&&(yield e)}async function*volumesWithUUIDs(){for await(let e of volumes())notBlank(e.volsha)&&(yield e)}async function whyNotScanMountPoint(e){if(!e.ok)return e.status??e.error??`unknown`;if(await fsm.isHidden(e.mountPoint))return`hidden directory`;let n=await whyExcludedDirectory(e.mountPoint);if(!blank(n))return n}async function*scannableMountPoints(e){for(let n of e??await getMountPoints()){let e=await whyNotScanMountPoint(n);e==null?yield n:logger37().info(`scannableMountPoints(): skipping mount point`,{mountPoint:n.mountPoint,why:e})}}async function*scannedVolumes(){for await(let e of mountPointsToScan()){if(!e.ok)continue;let n=await getVolumeMetadata(e.mountPoint);n!=null&&(yield n)}}async function*mountPointsToScan(){yield*asyncUniqBy(_mountPointsToScan(),e=>e.mountPoint)}async function*_mountPointsToScan(){let e=await allMountPoints();if(PathSettings.argvScanPaths.isNotEmpty())yield*pathsToMountPoints(compactBlanks(PathSettings.argvScanPaths.values),e);else if(yield*pathsToMountPoints(libraryDirs_().map(e=>e.nativePath),e),yield*pathsToMountPoints(compactBlanks(PathSettings.scanPaths.values),e),PathSettings.scanAllDrives.valueOrDefault){let n=fsmOptions().includeSystemVolumes?e:e.filter(e=>e.isSystemVolume!==!0);yield*n.filter(e=>!e.ok),yield*scannableMountPoints(n)}}async function*pathsToMountPoints(e,n){for(let r of e){let e=await mountPointOfPath(r,n);e==null?logger37().warn(`mountPointsToScan(): no mount point found`,{file:r}):yield e}}var MaxSymlinks=40;async function mountPointOfPath(e,n,r=0){let a=BaseFile.for(e),o=max(n.filter(e=>a.isSelfOrDescendantOf(e.mountPoint)),e=>e.mountPoint.length);if(o?.ok===!1)return o;for(let a=e;;a=(0,import_node_path37.dirname)(a)){let o=await bestMountPointForPath(a,n);if(o!=null)return o;let s=r<MaxSymlinks?await symlinkTarget(a):void 0;if(s!=null)return mountPointOfPath((0,import_node_path37.join)(s,(0,import_node_path37.relative)(a,e)),n,r+1);if((0,import_node_path37.dirname)(a)===a)return}}async function symlinkTarget(e){try{let n=await(0,import_promises16.readlink)(e);return(0,import_node_path37.resolve)(await(0,import_promises16.realpath)((0,import_node_path37.dirname)(e)),n)}catch{return}}var import_promises17=require("node:fs/promises"),uriPrefixes=[`http:`,`https:`,`file:`,PS_LOCAL_FILE_SCHEME,PS_NETWORK_FILESYSTEM_SCHEME].map(e=>e+`//`),logger38=lazy2(()=>mkLogger(`uri.UriNormalization`));function normalizeURI(e){try{return URI.parse(e).toString()}catch(n){return logger38().warn(`Failed to normalize invalid URI`,{uri:e,error:n}),e}}function strEql2(e,n){return e==null||n==null?!1:e===n||e.normalize()===n.normalize()}function uriEqlSync(e,n,r={}){try{if(e==null||n==null)return!1;let a=toURI(e),o=toURI(n);return a.scheme===o.scheme&&a.authority===o.authority&&strEql2(a.path,o.path)&&(!isTrue(r.compareQuery)||eql(a.query,o.query))&&(!isTrue(r.compareFragment)||strEql2(a.fragment,o.fragment))}catch{return!1}}async function uriIsEquivalent(e,n){try{if(e==null||n==null)return!1;if(eql(e,n)||uriEqlSync(e,n))return!0;let r=await uriToNativePath(e),a=await uriToNativePath(n);if(strEql2(r,a))return!0;if(r!=null&&a!=null)try{let[e,n]=await Promise.all([(0,import_promises17.realpath)(r),(0,import_promises17.realpath)(a)]);return strEql2(e,n)}catch{return!1}return!1}catch{return!1}}function uriEncodingVariantURIs(e){let n=toURI(e);return uniqBy([n,n.with({path:n.path.normalize(`NFC`)}),n.with({path:n.path.normalize(`NFD`)})],e=>e.toString())}function uriEncodingVariants(e){return uriEncodingVariantURIs(e).map(toS)}var logger39=lazy2(()=>mkLogger(`uri.pslib`)),PSLIB_ROOT_URI=URI.from({scheme:PS_LIBRARY_SCHEME,path:`/`});function nativePathToPslib(e){if(blank(e))return;let n=libraryDir();if(n==null||!containedByNativePath({ancestor:n,descendant:e,acceptSelf:!0}))return;let r=ensurePrefix(posixPathFrom(n,e),`/`);return{nativePath:e,uri:URI.from({scheme:PS_LIBRARY_SCHEME,path:r})}}function nativePathToLegacyPslib(e){let n=originalsDir();if(!(blank(e)||n==null||sameNativePath(n,libraryDir()??``)||!containedByNativePath({ancestor:n,descendant:e,acceptSelf:!0})))return URI.from({scheme:PS_LIBRARY_SCHEME,path:ensurePrefix(posixPathFrom(n,e),`/`)})}function pslibToNativePath_({uri:e}){if(e.scheme!==PS_LIBRARY_SCHEME)return logger39().throw(new InvalidURIError(`Invalid scheme: `+e));let n=stripPrefix(e.path,`/`),r=libraryAssetDirPosixFiles().map(e=>{let r=e.join(n);return{nativePath:r.nativePath,mountPoint:e.nativePath,isFileSync:r.isFileSync()}});return r.find(e=>e.isFileSync)??r[0]??logger39().throw(new InvalidURIError(`No library dirs configured`))}var _path15=__toESM(require("node:path")),import_node_dns=require("node:dns"),ping=memoize(async e=>stdout_(isWin?pingWin():`ping`,[isWin?`-n`:`-c`,`1`,e],{timeoutMs:5*secondMs}),{name:`net.ping`,maxSize:255,timeoutMs:ShortCommandTimeoutMs,clearEveryMs:10*minuteMs}),ipv4Re=RegExp(`\\b`+times(4,()=>`[0-9]{1,3}`).join(`\\.`)+`\\b`),ipAddrFromPing=memoize(async e=>opt(await ping(e).catch(e=>{console.warn(`failed to ping: `+e)})).filter(notBlank).flatMap(e=>ipv4Re.exec(toS(e))).map(e=>e[0]).get(),{name:`net.ipAddrFromPing`,maxSize:255,timeoutMs:ShortCommandTimeoutMs,clearEveryMs:10*minuteMs}),octetRE=RegExp(`^`+ipv4Re.source+`$`),friendlyName=memoize(async e=>toS(octetRE.exec(e)==null?e:await nslookup(e)).toLowerCase().normalize(),{name:`net.friendlyName`,maxSize:128,timeoutMs:ShortCommandTimeoutMs}),loopbackRE=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function isLoopback(e){return loopbackRE.exec(e)!=null}function octets(e){let n=e.split(`.`).map(e=>toInt(e)).filter(e=>within(0,255,e));return n.length===4?n:void 0}var resolve4=memoize(async e=>{if(!blank(e)){if(octets(e)!=null)return[e];try{return await import_node_dns.promises.resolve4(e)}catch{logger40().warn(`No name found for `+e);return}}},{name:`net.resolve4`,maxSize:256,timeoutMs:ShortCommandTimeoutMs,clearEveryMs:10*minuteMs}),logger40=lazy2(()=>mkLogger(`net.nslookup`)),nslookup=memoize(async e=>{try{let n=await thenOrTimeout(isLoopback(e)?e.startsWith(`127.`)?[`localhost`]:[`127.0.0.1`]:octets(e)==null?import_node_dns.promises.resolve4(e):import_node_dns.promises.reverse(e),5*secondMs);return n===Timeout?(logger40().info(`nslookup(`+e+`): timeout`),e):n.find(notBlank)??(logger40().warn(`No name found for `+e),e)}catch(n){return logger40().warn(`Failed to look up name`,{nameOrIp:e,error:n}),e}},{name:`net.nslookup`,maxSize:256,timeoutMs:ShortCommandTimeoutMs,clearEveryMs:10*minuteMs});async function isEquivalentHost(e,n){if(blank(e)||blank(n))return!1;if(equalsIgnoreCase(e,n)||isLoopback(e)&&isLoopback(n))return!0;let r=await resolve4(e);if(r==null)return!1;let a=await resolve4(n);return a!=null&&r.some(e=>a.includes(e))}var logger41=lazy2(()=>mkLogger(`uri.psnet`));async function nativePathToPsnet(e,n){if(blank(e))return;if(isUNC(e))return{nativePath:e,uri:URI.file(e).with({scheme:PS_NETWORK_FILESYSTEM_SCHEME})};let r=n??await bestVolumeForPath(e);if(r!=null&&r.remote===!0&¬Blank(r.remoteHost)&¬Blank(r.remoteShare))return{nativePath:e,uri:URI.from({scheme:PS_NETWORK_FILESYSTEM_SCHEME,authority:r.remoteHost,path:_path15.posix.join(`/`+r.remoteShare,stripPrefix(native2posix(e),native2posix(r.mountPoint)))})}}function pathSegments(e){return e.split(`/`).filter(e=>e.length>0)}function psnetSegments_(e){if(e.scheme!==PS_NETWORK_FILESYSTEM_SCHEME)return logger41().throw(new InvalidURIError(`Invalid scheme: `+e));if(blank(e.authority))return logger41().throw(new InvalidURIError(`Missing authority: `+e));let n=pathSegments(e.path);return n.length===0?logger41().throw(new InvalidURIError(`Missing share: `+e)):n.flatMap(e=>e.split(/[\\/]/)).some(e=>e===`.`||e===`..`)?logger41().throw(new InvalidURIError(`Invalid path: `+e)):n}function sameShareName(e,n){return e.normalize().toLowerCase()===n.normalize().toLowerCase()}function matchExport(e,n){if(n.remote!==!0)return;let r=pathSegments(n.remoteShare??``);if(r.length===0||r.length>e.length)return;let a=!0;for(let[n,o]of r.entries()){let r=e[n];if(r!==o){if(!sameShareName(r,o))return;a=!1}}let o=_path15.join(n.mountPoint,...e.slice(r.length));if(!containedByNativePath({ancestor:n.mountPoint,descendant:o,acceptSelf:!0}))logger41().warn(`matchExport(): URI resolves outside its share`,{mountPoint:n.mountPoint,nativePath:o});else return{vol:n,nativePath:o,depth:r.length,exactCase:a}}async function isPsnetShareMountedAt({uri:e,mountPoint:n,ttlMs:r}){if(await mountPointIdForPath(n)!==n)return!1;let a=psnetSegments_(e),o=await refreshVolumeMetadata(n,r);return o?.ok===!0&&matchExport(a,o)!=null&&await isEquivalentHost(e.authority,o.remoteHost)}async function psnetToNativePath_({uri:e,volume:n,preferredNativePath:r}){let a=psnetSegments_(e),o=[];for await(let r of chainAsyncIterators(compact([n]),remoteVolumes)){let n=matchExport(a,r);n!=null&&await isEquivalentHost(e.authority,r.remoteHost)&&o.push(n)}let s=o.length>1&&r!=null?o.find(e=>sameNativePath(e.nativePath,r)):void 0,c=(s!=null&&await exists(s.nativePath)?s:void 0)??(o.length<=1?o[0]:at(await sortByAsync({iter:o,f:async e=>[e.depth,e.exactCase,await exists(e.nativePath),-e.vol.mountPoint.length]}),-1));return c==null?isWin?{nativePath:`\\\\${e.authority}\\${a.join(`\\`)}`}:logger41().tap({msg:`psnetToNativePath_(): no mounted share serves this URI`,level:`debug`,result:void 0,meta:{uri:e.toString()}}):{nativePath:c.nativePath,mountPoint:c.vol.mountPoint}}var logger42=lazy2(()=>mkLogger(`uri.FileURI`)),warnedUnmintableDirs=new Set;function anyUriSchemeDisabled(){let e=Settings2.assetFileUriSchemes.values;return!AssetFileUriSchemes.values.every(n=>e.includes(n))}async function nativePathToUri(e,n){if(e==null||blank(e))return logger42().throw(`empty nativePath passed to nativePathToUri()`,{retriable:!1});let r=Settings2.assetFileUriSchemes.values,a=e=>r.includes(e),o=(a(PS_LIBRARY_SCHEME)?nativePathToPslib(e):void 0)??(a(PS_LOCAL_FILE_SCHEME)?await nativePathToPsfile(e,n):void 0)??(a(PS_NETWORK_FILESYSTEM_SCHEME)?await nativePathToPsnet(e,n):void 0)??(a(PLAIN_FILE_SCHEME)?{nativePath:e,uri:URI.file(e)}:void 0);if(o==null){let n=(0,import_node_path38.dirname)(e);warnedUnmintableDirs.has(n)||(warnedUnmintableDirs.add(n),logger42().warn(`nativePathToUri(): no enabled URI scheme can identify this file, so it cannot be imported`,{file:e,assetFileUriSchemes:r,note:`further files in this directory will not repeat this warning; see the sync report for the full list`}))}return o}async function nativePathToUris(e,n){let r=n??await bestVolumeForPath(e),a=await nativePathToPsfile(e,r),o=[];if(a!=null){let e=r?.volshas??compact([r?.volsha]);if(e.length>1)for(let n of e)o.push(n===a.uri.authority?a.uri:URI.from({scheme:PS_LOCAL_FILE_SCHEME,authority:n,path:a.uri.path}));else o.push(a.uri)}return compact([nativePathToPslib(e)?.uri,nativePathToLegacyPslib(e),...o,(await nativePathToPsnet(e,r))?.uri,URI.file(e)])}async function nativePathToUriStrings(e,n){return sortURIs(uniq(flatten((await nativePathToUris(e,n)).map(uriEncodingVariants))))}function toURI2(e){try{return URI.isUri(e)?e:URI.parse(e,!0)}catch(n){logger42().warn(`bad URI`,{uri:e,error:n});return}}async function uriToNativePath(e){return uriToNativePath_(e).catch(()=>void 0)}async function uriToNativePath_(e){return(await uriToNativePathAndMountpoint_(e))?.nativePath}async function uriToNativePathAndMountpoint_(e){if(blank(e))return;let n=toURI2(e);if(n!=null)switch(n.scheme){case`file`:return{nativePath:n.fsPath};case PS_LOCAL_FILE_SCHEME:return await psfileToNativePath_(n);case PS_NETWORK_FILESYSTEM_SCHEME:return await psnetToNativePath_({uri:n});case PS_LIBRARY_SCHEME:return pslibToNativePath_({uri:n});default:return logger42().throw(new InvalidURIError(`unsupported URI: `+e))}}async function uriExists(e){let n=await uriToNativePath(e);return n!=null&&await exists(n)}var import_batch_cluster4=require("batch-cluster"),import_node_fs21=require("node:fs"),import_promises18=require("node:fs/promises"),import_node_timers6=require("node:timers"),import_sqlite=require("@photostructure/sqlite"),import_node_fs20=require("node:fs"),FsLockGuard=class e{constructor(e,n){this.file=e,this.#e=n}file;static suffix=`.owner.sqlite`;static fileFor(e){return e.sibling(e.base+this.suffix)}static tryAcquire_(n){let r=this.fileFor(n),a=new import_sqlite.DatabaseSync(r.nativePath,{timeout:0});try{return a.exec(`PRAGMA journal_mode=OFF; BEGIN EXCLUSIVE`),new e(r,a)}catch(e){if(a.close(),isSqliteBusyError(e))return;throw e}}static isHeld_(e){if((0,import_node_fs20.statSync)(this.fileFor(e).nativePath,{throwIfNoEntry:!1})==null)return;let n=this.tryAcquire_(e);return n==null||(n.close(),!1)}#e;close(){this.#e.isOpen&&this.#e.close()}remove_(){this.close(),this.file.unlinkSync_()}},PsLockExt=`.pslock`;function fsLockDir(e){return e.sibling(`.`+e.base+PsLockExt)}function fsLockFileBasename(e){return e+PsLockExt}var HolderMarkerExt=`.holder`;function fsLockHolderMarker(e){return e.sibling(e.base+HolderMarkerExt)}function isFsLockHolderMarker(e){if(blank(e))return!1;let n=basename2(e);return!n.startsWith(`._`)&&n.endsWith(PsLockExt+HolderMarkerExt)}function fsLockfileOfHolderMarker(e){return stripSuffix(e,HolderMarkerExt)}function isPsLockFileOrDir(e){return!blank(e)&&basenameIsPsLockFileOrDir(basename2(e))}function basenameIsPsLockFileOrDir(e){return notBlank(e)&&!e.startsWith(`._`)&&e.endsWith(PsLockExt)}var ProcessLifetimeLockTimeoutMs=2*minuteMs,ClaimSettleTimeoutMs=5*secondMs,ClaimSettleIntervalMs=10,LastNumberRe=RegExp(`-(?<pid>\\d+)`+escapeRegExp(PsLockExt)+`$`),FsLock=class e extends EndableWrapper{constructor(n){super(n.name??`FsLock`,()=>this.#h(),n.endableRank??EndableRanks.last,commandTimeoutMs()),this.opts=n,this.lockdir=fsLockDir(this.opts.file),n.name??this.setName(`fs.FsLock(`+n.file+`)#`+this.#r),this.staleMs=round(this.opts.timeoutMs/randomFloat(1.5,3)),e.#n.push(this)}opts;static#e=0;static internalErrors=0;static#t=0;static newUid(e=process.pid,n=9){return this.#e=Math.max(Date.now(),this.#e+1),compactBlanks([toS(n),TokenRadix.encode(this.#e),serviceName.prior(),toS(e)]).join(`-`)}static pidFromLockfile(n){return e.pidFromBasename(basename2(n))}static pidFromBasename(e){return toInt(LastNumberRe.exec(toS(e))?.groups?.pid)}static#n=[];static for(n){return filterInPlace(this.#n,e=>!e.ended),this.#n.find(e=>e.opts.file.$eql(n.file))??new e(n)}#r=++e.#t;lockdir;#i=!1;lockfile;#a;#o;#s;staleMs;#c;#l=0;get acquired(){return this.#i}toLogJSON(){return{name:this.name,acquired:this.acquired}}vacuum=rateLimited({name:`fs.FsLock.vacuum:`+this.name,nullOnBusy:!0,minCallDelayMs:()=>(toGt0(this.staleMs)??Settings2.statTimeoutMs.valueOrDefault)/2,f:async()=>{let n=[],r=await this.#u(),a=r.filter(e=>isPsLockFileOrDir(e));for(let r of a){let a=this.lockdir.join(r),o=FsLockGuard.isHeld_(a);if(o===!0){n.push(r);continue}if(o===!1){await a.unlink_(),FsLockGuard.fileFor(a).unlinkSync_(),fsLockHolderMarker(a).unlinkSync_();continue}let s=!1,c=``;if(this.opts.processLifetime!==!0&>0(this.opts.timeoutMs)){let e=Math.round((Date.now()-(this.opts.timeoutMs+secondMs))/1e3)*1e3,n=await a.mtimeMs({refresh:!0});n!=null&&n<e&&(s=!0,c=`stale by ${fmtDuration(e-n)}`)}if(!s){let n=e.pidFromLockfile(a);n==null?(s=!0,c=`no pid`,e.internalErrors++):(0,import_batch_cluster4.pidExists)(n)||(s=!0,c=`pid gone`)}s?(this.logger.warn(`#vacuum(): Removing ${a.base} - ${c}`),await a.unlink(),fsLockHolderMarker(a).unlinkSync_()):n.push(r)}return[...n,...r.filter(e=>isFsLockHolderMarker(e))]}});async#u(){try{return(await(0,import_promises18.readdir)(this.lockdir.nativePath,{withFileTypes:!1,encoding:`utf8`})).filter(e=>isPsLockFileOrDir(e)||isFsLockHolderMarker(e))}catch(e){if(e.code===`ENOENT`)return[];throw this.logger.warn(`readdir() failed`,{error:e}),e}}async#d(e){return!0===e?.vacuum?await this.vacuum.force()??[]:await this.vacuum()??await this.#u()}#f(e,n){return e.filter(e=>isFsLockHolderMarker(e)).map(e=>fsLockfileOfHolderMarker(e)).filter(r=>r!==n&&e.includes(r)).sort()}async selfAndSiblingNames_(e){return(await this.#d(e)).filter(e=>isPsLockFileOrDir(e)).sort()}async iAmNext(n){let r=this.lockfile;if(r==null)return this.release(),!1;let a=await this.#d(n),o=a.filter(e=>isPsLockFileOrDir(e)).sort();if(this.lockfile!==r||this.lockfile==null)return this.release(),!1;if(!o.includes(r.base)){if(isTest())e.internalErrors++,this.logger.throw(`iAmNext_(): missing lockfile, `+r+InternalErrorFlag,{children:o,lockfile:r});else return this.release(),!1}if(this.#i)return!0;let s=this.#f(a,r.base)[0];if(s==null&&o[0]===r.base)return this.#p(r);if(!0!==n?.vacuum){let n=e.pidFromBasename(s??o[0]);if(gt0(n)&&!(0,import_batch_cluster4.pidExists)(n))return this.logger.info(`iAmNext_(): auto-vacuuming, owner pid is gone`),this.iAmNext({vacuum:!0})}return!1}async#p(e){let n=this.#l,r=fsLockHolderMarker(e);await r.touch_();let a=Date.now()+ClaimSettleTimeoutMs;for(;;){let o=this.#f(await this.#u(),e.base)[0];if(this.#l!==n)return r.unlinkSync_(),!1;if(o==null)return this.#i=!0,!0;if(o<e.base||Date.now()>=a)return r.unlinkSync_(),!1;await delay(ClaimSettleIntervalMs)}}async iAmOnly_(e){return this.lockfile!=null&&eql(await this.selfAndSiblingNames_(e),[this.lockfile.base])}async isOwner_(e){let n=this.lockfile;return n!=null&&(await this.selfAndSiblingNames_(e))[0]===n.base}tryAcquire_=serialized(async()=>{if(this.#i)return!0;let n=this.#l,r=this.lockfile??=this.lockdir.join(fsLockFileBasename(e.newUid(process.pid,this.opts.priority??9)));try{if(this.opts.processLifetime===!0&&this.#o==null){if(await this.lockdir.mkdirp_(),this.#l!==n)return!1;if(this.#o=FsLockGuard.tryAcquire_(r),this.#o==null)throw Error(`Could not guard new lockfile: `+r)}for(let e=0;;e++)try{await r.touch_();break}catch(n){if(this.opts.oneShot!==!0||n.code!==`ENOENT`||e>=3)throw n}return this.#l===n?(this.startRefreshTimer_(),await this.iAmNext()):(r.unlinkSync_(),!1)}catch(e){throw this.release(),this.logger.error(`tryAcquire() failed`,e),e}});startRefreshTimer_(){if(this.opts.processLifetime!==!0&&this.#a==null&&this.staleMs>0){let e=Math.max(this.staleMs/2,isTest()?10:secondMs);this.#a=setInterval(()=>this.refreshLockfile_(),e)}}async refreshLockfile_(){if(this.opts.processLifetime===!0)return;let e=this.lockfile;if(e==null||await e.notExists({refresh:!0}))this.logger.warn(`#refreshLockfile_(): null or missing lockfile`),this.release();else if(this.lockfile!==e)this.logger.debug(`#refreshLockfile_(): lockfile changed, aborting`);else try{await e.touch_()}catch(e){throw this.logger.warn(`#refreshLockfile_(): failed, force-releasing.`,e),this.release(),e}}acquire_=sequential(async({releaseOnFailure:e=!0,timeoutMs:n=this.opts.timeoutMs}={})=>{if(this.#i)return!0;try{if(!0===await this.tryAcquire_.ifIdle())return!0;let r=clamp(50,5*secondMs,Math.min(this.staleMs,n)/7);return await this.lockdir.watchUntil({watcherOwner:`FsLock.acquire_`,f:async(e,n)=>n!=null&&n===this.lockfile?.base?!1:!0===await this.tryAcquire_.ifIdle(),persistent:!1,recursive:!1,timeoutMs:n,intervalMs:r}),!this.acquired&&e&&this.release(),this.acquired}catch(n){throw e&&this.release(),this.logger.warn(`acquire_() failed`,{error:n}),n}});async#m(){await this.vacuum()}#h(){filterInPlace(e.#n,e=>e.#r!==this.#r),ending()&&this.release()}release(){this.#l++,this.#a!=null&&(clearInterval(this.#a),this.#a=void 0),map(this.#s,e=>(0,import_node_timers6.clearTimeout)(e));let e=this.lockfile,n=!0;try{e!=null&&(fsLockHolderMarker(e).unlinkSync_(),e.unlinkSync_()),this.#i=!1,this.lockfile=void 0;let n=this.#o;this.#o=void 0,n?.remove_()}catch(e){e.code===`ENOENT`?(this.logger.debug(`#release() lockfile already deleted`),n=!0):(this.logger.warn(`#release() failed to delete lockfile`,e),n=!1)}if(this.opts.oneShot===!0)try{(0,import_node_fs21.rmdirSync)(this.lockdir.nativePath),this.lockdir.clear()}catch(e){[`ENOTEMPTY`,`EEXIST`,`ENOENT`].includes(e.code)||this.logger.warn(`#release() failed to remove one-shot lockdir`,e)}return this.opts.dirty!==!0&&(ending()||this.ended?this.#m():(this.#s=setTimeout(()=>this.#m(),toGt0(this.staleMs)??secondMs),this.#s.unref())),n}async withLock_(e){if(this.opts.skipFsLock===!0)return e(this);if(this.#i)return this.logger.warn(`nested withLock() with acquired lock`,{caller:shortStack()}),e(this);let n=shortStack();this.#c!=null&&this.logger.throw(`Re-entrant withLock_() detected - this will deadlock!`+InternalErrorFlag,{previousStack:this.#c,currentStack:n});try{return this.#c=n,await(this.opts.noopIfContested===!0?this.tryAcquire_():this.acquire_())?await thenOrTimeoutError(e(this),this.opts.timeoutMs):void 0}catch(e){throw this.logger.warn(`withLock_() rejected`,e),e}finally{this.#c=void 0,this.release()}}};async function withLock_(e,n){if(e.skipFsLock===!0)return n();{let r=new FsLock(e);try{return await r.withLock_(n)}finally{await r.end()}}}var cache3=lazy2(()=>new FileCache({name:`fs.PosixFile`,clearOnFileChange:!0})),NoOp2=Symbol(`no-op`),PosixFile=class e extends BaseFile{constructor(e,n){super(e,n),this.nativePath=e}nativePath;bflog=lazy2(()=>mkLogger(`fs.PosixFile`,{file:this.nativePath}));static forDirectoryEntry(n){return e.for(n.nativePath,n)}static forMaybe(n){return blank(n)?void 0:e.for(n)}static for(n,r){if(n instanceof e)return n;let a=toNativePath_(n),o=cache3().get(a);if(o!=null)return o.clearIfChanged();let s=isString(n)?resolve2(a):a,c=new e(s,r);return cache3().set(a,c),cache3().set(s,c),c}static forPosix(n){return e.for(n.replace(/\//g,import_node_path39.default.sep))}static async forUri(e){return this.forMaybe(await uriToNativePath(e))}for(n,r){return e.for(n,r)}forDirectoryEntry(n){return e.for(n.nativePath,n)}clearable(){return super.clearable()||this.uriObject_.hasPrior()||this.uri_.hasPrior()||this.fileuri.hasPrior()||this.#e!=null||this.#t!=null||this.unlock.hasPrior()}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.fileuri.unset(),this.#e=void 0,this.#t=void 0,this.unlock.unset(),this}uriObject_=lazy2(()=>nativePathToUri(this.nativePath));uri_=lazy2(async()=>{let e=await this.uriObject_();if(e==null)throw new InvalidURIError(`No enabled assetFileUriSchemes can identify `+this.nativePath);return e.uri.toString()});uri(){return this.trap(`uri`,()=>this.uri_())}fileuri=lazy2(()=>URI.file(this.nativePath).toString());mountPoint=lazy2(async()=>{if(!(containedByNativePath({ancestor:libraryDir(),descendant:this,acceptSelf:!0})||containedByNativePath({ancestor:originalsDir(),descendant:this,acceptSelf:!0})))return(await bestMountPointForPath(this.nativePath))?.mountPoint});async assertReadWriteExecutable(){let e=await this.readWriteExecutableError();if(e!=null)throw Error([e.code,`Please check directory permissions for ${this.nativePath}`,`it must be read/write${isWin?``:`/execute`} by ${await userDesc()}`,e.message].filter(e=>e!=null).join(`: `))}hide(){if(isWin||isMac)return this.trap(`hide`,async()=>(await hide_(this),this))}isMountpoint=lazy2(async()=>await this.isDirectory()&&(await getMountPoints()).some(e=>e.mountPoint===this.nativePath));isSidecar(){return isSidecarExt(this.ext)}#e;#t;async existingSidecars(){let n=await this.parent().childDirectoryEntries();if(n!=null&&this.#e?.listing===n)return this.#e.result.map(n=>e.for(n.nativePath));this.#e=void 0;let r=await existingSidecars(this);return n!=null&&(this.#e={listing:n,result:r}),r}async existingDirectorySidecars(){let n=await this.parent().childDirectoryEntries(),r=compactBlanks(Settings2.directorySidecars.valueOrDefault),a=this.#t;if(n==null||a?.listing!==n||r.length!==a.names.length||r.some((e,n)=>e!==a?.names[n])){if(this.#t=void 0,n==null)return[];let e=new Set(n.map(e=>e.base));a={listing:n,names:r,candidates:r.filter(n=>e.has(n)).map(e=>this.sibling(e)),result:[]},this.#t=a}let o=await filterAsync({arr:a.candidates.map(n=>e.for(n.nativePath)),f:e=>e.isNonEmptyFile()});return(o.length!==a.result.length||o.some((e,n)=>e!==a.result[n]))&&(a.result=o),a.result}async existingExifSidecars(){return(await this.existingSidecars()).filter(e=>!isJsonExt(e))}async sidecar(){return(await this.existingExifSidecars()).find(e=>equalsIgnoreCase(e.ext,defaultSidecarExt()))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+defaultSidecarExt())}async jsonSidecars(){return(await this.existingSidecars()).filter(e=>isJsonExt(e))}async sidecarStats(e){e?.refresh===!0&&(this.#e=void 0,this.#t=void 0);let n=flatten(await Promise.all([this.existingSidecars(),this.existingDirectorySidecars()]));return compact(await Promise.all([this,...n].map(n=>n.stat(e))))}async thisOrSidecarMaxMtimeMs(e){return max2((await this.sidecarStats(e)).map(e=>e.mtimeMs))}async writeStream_(e){return await(0,import_promises20.pipeline)(e,import_node_fs22.default.createWriteStream(this.nativePath,{autoClose:!0})),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:n=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:a,skipWip:o=!1,skipFsLock:s=!1,retries:c=2,dirty:l=!1}){return retryOnReject_(async()=>{let c=await this.clear().isNonEmptyFile(n);if(!c){if(o&&s)return e(this);if(await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(n)?NoOp2:e(r),skipFsLock:s,minSizeBytes:n,timeoutMs:a,dirty:l})===NoOp2&&r)return}return c&&r?void 0:this.utimes()},{maxRetries:c,timeoutMs:a*2,retryDelay:3*secondMs,errorIsRetriable:e=>errorCode(e)===`EBUSY`})}wip(){return this.sibling(addWipPrefix(this.base))}isWip(){return isWip(this.name)}async wipIsRecent(e=WipTimeoutMs){return await this.wip().isFile()&>e(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling(rmWipPrefix(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:n=0,skipFsLock:r=!1,timeoutMs:a,dirty:o=!1,preserveDestOnError:s=!1,beforeRename_:c}){return await this.parent().mkdirp_(),withLock_({file:this,skipFsLock:r,timeoutMs:a,dirty:o},async()=>{let r=this.wip();try{await r.unlink(`trace`);let o=await thenOrTimeoutError(e(r),a);if(o===NoOp2)return o;if(await untilTrue(()=>r.clear().isNonEmptyFile(n),{timeoutMs:ShortCommandTimeoutMs,intervalMs:250})){let e=await import_promises19.default.open(r.nativePath,`r+`);try{await e.datasync()}finally{await e.close()}return await c?.(r),await r.mv_(this),o}throw Error(this+`applyWip(): still empty after waiting `+fmtDuration(ShortCommandTimeoutMs))}catch(e){throw this.bflog().warn(`applyWip() threw error`,{error:e}),await r.unlink(`trace`),s||await this.unlink(`trace`),e}})}copyFile_(e,n){return timeExcludingNested({name:`fs.copyFile`,thunk:async()=>{let r=this.dest(e);return this.nativePath===r.nativePath?this:this.#n(r,Settings2.fileCopyStrategy.valueOrDefault,n?.skipProgressWatchdog)}})}async#n(e,n,r){switch(await e.parent().mkdirp_(),n){case FileCopyStrategies.builtin:return this.#r(e,{useReflink:!1,atomic:!0,skipProgressWatchdog:r});case FileCopyStrategies[`builtin-reflink`]:return this.#r(e,{useReflink:!0,atomic:!0,skipProgressWatchdog:r});case FileCopyStrategies[`builtin-no-wip`]:return this.#r(e,{useReflink:!1,atomic:!1,skipProgressWatchdog:r});case FileCopyStrategies.native:return this.#i(e,{preserveMetadata:!1});case FileCopyStrategies[`native-preserve`]:return this.#i(e,{preserveMetadata:!0});case FileCopyStrategies.auto:default:try{return await this.#r(e,{useReflink:!1,atomic:!0,skipProgressWatchdog:r})}catch(n){if(isNonRetriableError(n)===!0)return this.bflog().throw(`_copyFile failed, but error wasn't retriable`,{error:n,dest:e.nativePath});this.bflog().warn(`_copyFile failed, trying _nativeCopyFile`,{dest:e.nativePath,error:n})}return this.#i(e,{preserveMetadata:!1})}}async maybeVerifySameOrThrow_(e){let n=performance.now();Settings2.fileCopyVerify.valueOrDefault&&(await untilTrue(()=>this.matchesContent(e),{timeoutMs:commandTimeoutMs(),intervalMs:secondMs})||this.bflog().throw(`copyFile_() failed (contents did not match after copy)`,{dest:e,elapsedMs:roundMs(performance.now()-n)}))}async#r(e,n){let r,a=e,o=n.atomic?e.wip():e;try{let s=await this.stat_();if(s==null)return this.bflog().throw(`Can't copy missing files`+NonRetriableErrorFlag);if(s.size>0){if(Settings2.fileCopyVerify.valueOrDefault&&await this.sha()==null)return this.bflog().throw(`Can't copy file without SHA`+NonRetriableErrorFlag);if(await import_promises19.default.copyFile(this.nativePath,o.nativePath,n.useReflink?import_node_fs22.default.constants.COPYFILE_FICLONE:void 0),n.skipProgressWatchdog!==!0&&s.size>5*MiB&&(r=new PullProgressObserver({op:`Copying`,path:this.nativePath,dest:e.nativePath},s.size,()=>o.size({refresh:!0}))),!await untilTrue(async()=>approximates(s.size,await o.size({refresh:!0})),{intervalMs:secondMs,timeoutMs:minuteMs}))return this.bflog().throw(`copyFile_() failed`,{expectedSize:s.size,actualSize:await o.size({refresh:!0})});await this.maybeVerifySameOrThrow_(o),a=e.$eql(o)?e:await o.mv_(e,LogLevels.trace)}try{await touch_({file:a,btimeMs:s.birthtimeMs,mtimeMs:s.mtimeMs,ensureFile:!1})}catch(e){this.bflog().warn(`copyFile_(): couldn't set utimes to match source`,{dest:a.nativePath,error:e})}try{await import_promises19.default.chmod(a.nativePath,s.mode)}catch(e){this.bflog().warn(`copyFile_(): couldn't chmod`,{dest:a.nativePath,mode:s.mode,error:e})}return this.bflog().debug(`copyFile_(): success`,{dest:a.nativePath}),a}catch(n){throw this.bflog().warn(`copyFile_() failed`,{dest:o?.nativePath,error:n}),await o.unlink(),o.$eql(e)||await e.unlink(),n}finally{a?.clearThisAndParent(),map(r,e=>e.end())}}async zCopyFile_(e,n){await e.parent().mkdirp_();let r=e.wip();try{await zpipe_(this.nativePath,import_node_fs22.default.createWriteStream(r.nativePath,{autoClose:!0}),n),await r.unwip_()}catch(e){throw await r.unlink(),e}return e.clear()}async copyTimeoutMs(){return clamp(ShortCommandTimeoutMs,10*minuteMs,(await this.size()??0)*MinIoRate)}async#i(e,n){let r,a=e.wip();try{let o=await this.stat_(),s=o?.size;if(o==null||s==null)return this.bflog().throw(`Can't copy missing files`);s>5*MiB&&(r=new PullProgressObserver({op:`Copying`,path:this.nativePath,dest:a.nativePath},s,()=>e.clear().size()));let c=await this.copyTimeoutMs();if(isWin)await PowerShell.instance().execute(`Copy-Item -LiteralPath ${pwshQuote(this.nativePath)} -Destination ${pwshQuote(a.nativePath)}`,e=>e);else if(isMac){let e=n.preserveMetadata?[this.nativePath,a.nativePath]:[`--norsrc`,this.nativePath,a.nativePath];try{await stdout_(`ditto`,e,{timerName:`proc.copy`,timeoutMs:c})}catch(e){if(n.preserveMetadata&&isPermissionError(e))this.bflog().info(`ditto failed with permission error, retrying with --norsrc`),await stdout_(`ditto`,[`--norsrc`,this.nativePath,a.nativePath],{timerName:`proc.copy`,timeoutMs:c});else throw e}}else{let e=n.preserveMetadata?[`-a`,`-f`,this.nativePath,a.nativePath]:[`-f`,this.nativePath,a.nativePath];try{await stdout_(`cp`,e,{timerName:`proc.copy`,timeoutMs:c})}catch(e){if(n.preserveMetadata&&isPermissionError(e))this.bflog().info(`cp -a failed with permission error, retrying with cp -f`),await stdout_(`cp`,[`-f`,this.nativePath,a.nativePath],{timerName:`proc.copy`,timeoutMs:c});else throw e}}await this.maybeVerifySameOrThrow_(a),await a.mv_(e,LogLevels.trace);try{await touch_({file:e,reference:this,ensureFile:!1})}catch(n){this.bflog().warn(`_nativeCopyFile(): couldn't set utimes`,{dest:e.nativePath,error:n})}return e.clearThisAndParent()}catch(n){return await a.unlink(),this.bflog().throw(`_nativeCopyFile() failed`+DoNotSendErrorFlag,{dest:e.nativePath,error:n})}finally{map(r,e=>e.end())}}dest(e){let n=e.clear();return notBlank(this.ext)&&blank(n.ext)||n.isDirectorySync()?n.join(this.base):n}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw Error(`Cannot rename: `+this+` doesn't exist.`);let n=fmtYMDHMS(e.ts??await this.mtime()??Date.now()),r=mapOr(e.subdir,e=>this.parent().join(e),()=>this.parent());return this.mv_(r.join(this.name+`-`+n+this.ext))}async saveIfNewOrDelete(e){if(await this.clear().isEmptyOrMissing()){await this.unlink(`trace`);return}let n=await this.siblingWithSameContents();if(n!=null)return await this.unlink(),n;let r=await this.sibling(e).ensureNew_();return this.mv_(r)}unlock=lazy2(()=>isMac?stdout_(`chflags`,[`nouchg`,this.nativePath],{quiet:!0,timeoutMs:ShortCommandTimeoutMs}):void 0);relativePathTo(e){return import_node_path39.default.relative(this.nativePath,toNativePath_(e))}async mv_(e,n=LogLevels.debug){let r=isString(e)?this.parent().join(e):this.dest(e);if(this.nativePath===r.nativePath)return this.bflog().warn(`mv(): no-op`,{error:Error(`internal error`)}),this;this.dir!==r.dir&&await r.parent().mkdirp_(),this.bflog().log(n,`mv_()`,{dest:r.relativePathTo(this)});try{await move_(this.nativePath,r.nativePath)}catch(e){this.bflog().warn(`mv() failed. Calling unlock() and retrying...`,{error:e}),await Promise.all([this.unlock(),r.unlock()]),await move_(this.nativePath,r.nativePath)}return this.dir!==r.dir&&this.clearThisAndParent(),r.clearThisAndParent()}};function randomDirname(){return`ps-test-`+AlphaRadix.randomUid(6,3)}var TestTmpKeepMarker=`.ps-keep`,tmpBaseDir=defer(()=>{let e=PosixFile.for(tmpBaseDirParent()).join(randomDirname()).mkdirpSync_(),n=PosixFile.for((0,import_node_fs23.realpathSync)(e.nativePath));return rmTestTmpfiles()||n.join(TestTmpKeepMarker).ensureFileSync_(),n});function tmpBaseDirParent(){if(isDocker())return`/data`;let e=(0,import_node_os12.tmpdir)();return!isTest()||[process.env.TMPDIR,process.env.TMP,process.env.TEMP].some(notBlank)?e:tmpdirIsItsOwnMountPoint(e)?(0,import_node_path40.join)(repoRoot(),`tmp`):e}function tmpdirIsItsOwnMountPoint(e){let n=PosixFile.for(e).mkdirpSync_().nativePath;return(0,import_node_fs23.statSync)(n).dev!==(0,import_node_fs23.statSync)((0,import_node_path40.dirname)(n)).dev}isTest()&&rmTestTmpfiles()&&new EndableWrapper(`_tmp() cleanup`,()=>{if(getDevEnvFlag(`PS_SKIP_CLEANUP`))console.log(`PS_SKIP_CLEANUP: keeping `,{tmpDir:tmpBaseDir.prior()});else return tmpBaseDir.reset()?.rmrf()},`last`);var _currentTestDir;function tmp(e={}){let n=e.prefix??process.env.PS_TMPDIR_PREFIX;return(_currentTestDir??tmpBaseDir()).join(compactBlanks([n,randomChars(12,LowercaseChars),e?.postfix]).map(e=>stripPrefixSuffix(e,{prefix:`-`,suffix:`-`})).join(`-`))}function tmpDir(e){let n=tmp(e);if(n.mkdirpSync()==null)throw Error(`Could not mkdirsync `+n);return n}function tmpDirName(e){return tmpDir(e).nativePath}function tmpFileName(e){return(_currentTestDir??tmpBaseDir()).mkdirpSync_().join(e)}var import_node_path43=require("node:path");function defaultLibraryDir(){return isDocker()?DefaultDockerLibraryDir:void 0}function defaultOriginalsDir(e=`/ps/originals`){return isDocker()&&isReadableDirectorySync(e)?e:`.`}var import_node_fs25=require("node:fs"),import_node_path41=require("node:path"),SettingsToml=`settings.toml`;function systemSettingsFile(){let e=configDir();return e==null?void 0:(0,import_node_path41.join)(e,SettingsToml)}function systemSettingsFile_(){return(0,import_node_path41.join)(configDir_(),SettingsToml)}var import_node_fs24=require("node:fs"),import_promises21=require("node:fs/promises"),import_toml=__toESM(require_toml());function parseTomlBuffer(e){let n=debom(e);if(n.trim().length!==0)try{return(0,import_toml.parse)(dumbquote(n))}catch(e){throw tomlErrorWithoutSource(e)}}function tomlErrorForLog(e){if(typeof e!=`object`||!e)return e;let n=e;return n.fromTOML===!0?{name:typeof n.name==`string`?n.name:`TomlError`,...typeof n.line==`number`?{row:n.line+1}:{},...typeof n.col==`number`?{column:n.col+1}:{}}:e}function tomlErrorWithoutSource(e){let n=tomlErrorForLog(e);if(n===e)return e;let{row:r,column:a}=n,o=typeof r==`number`?` at row ${r}`:``,s=typeof a==`number`?`${o===``?` at`:`,`} column ${a}`:``,c=Error(`Invalid TOML${o}${s}`);return Object.assign(c,n),c}function readTomlFileSync(e){let n=mapNotBlank(e,toNativePath_);if(n!=null)try{return isFileSync(n)?parseTomlBuffer((0,import_node_fs24.readFileSync)(n)):void 0}catch(e){mkLogger(`settings.Toml`).warn(`readTomlFileSync() failed`,{nativePath:n,error:tomlErrorForLog(e)});return}}async function readTomlFile_(e){return mapNotBlank(e,async e=>parseTomlBuffer(await(0,import_promises21.readFile)(toNativePath_(e))))}function libraryLogDir(e){return resolve2(e,`.photostructure`,`logs`)}function defaultLogDirs(){return isDocker()?[{dir:`/ps/logs`,preexistingDir:`/ps/logs`},{dir:`/ps/log`,preexistingDir:`/ps/log`},{dir:libraryLogDir(DefaultDockerLibraryDir),preexistingDir:`/ps/library`},{dir:`/tmp/photostructure-logs`,preexistingDir:`/tmp`}]:isMac?[{dir:resolve2(homeDir(),`Library`,`Logs`,SimpleAppName),preexistingDir:homeDir()}]:compact(cacheDirs()).map(e=>({dir:map(e.dir,e=>resolve2(e,`logs`)),preexistingDir:e.preexistingDir}))}function defaultLogDir_(){let e=firstDir({dirs:defaultLogDirs(),desc:`logs`});if(e==null)throw Error(`No suitable log directory found`);return e}var logDir=lazy2(()=>{try{let e=getEnv(`logDir`);if(notBlank(e))return e;let n=readTomlFileSync(systemSettingsFile()),r=toS(n?.logDir);if(notBlank(r))return r;if(isTest()&&process.env.PS_SKIP_CLEANUP!=null){let e=getEnv(`libraryDir`),r=notBlank(n?.libraryDir)?toS(n?.libraryDir):notBlank(e)?e:void 0;if(r!=null&&(0,import_node_fs25.existsSync)(r))return libraryLogDir(r)}return defaultLogDir_()}catch(e){return console.error(`defaultLogDir_() failed`,e),resolve2(homeDir(),`logs`)}});ee().on(`resetDirectories`,()=>logDir.unset());var import_node_path42=require("node:path");async function picturesDirWindows(){return isWin?PowerShell.instance().executeJson(`Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"`):void 0}var picturesDir=lazy2(async()=>{if(isWin){let e=await picturesDirWindows();if(notBlank(e))return e}return defaultPicturesDir()}),defaultPicturesDir=lazy2(()=>process.env.XDG_PICTURES_DIR??(0,import_node_path42.resolve)(homeDir(),`Pictures`)),setSettingsDefaults=lazy2(()=>{let e=getDevEnvFlag(`PS_SETTINGS_IO_TEST`);Settings2.logDir.opts.defaultValue=defaultLogDir_,Settings2.logServerLevel.opts.defaultValue=()=>Settings2.logLevel.valueOrDefault,Settings2.logContextLimit.opts.defaultValue=()=>isDefaultLogLevelAtLeast(`debug`)?64:32,e||(Settings2.pidFile.opts.defaultValue=()=>{let e=isElectron()||isDocker()?void 0:configDir();return e==null?void 0:(0,import_node_path43.join)(e,`main.pid`)},Settings2.cacheDir.opts.defaultValue=defaultCacheDir,Settings2.libraryDir.opts.defaultValue=defaultLibraryDir,Settings2.originalsDir.opts.defaultValue=defaultOriginalsDir,Settings2.libraryDir.opts.exampleValue=()=>isProd()&&isDocker()?DefaultDockerLibraryDir:defaultPicturesDir(),Settings2.toolPaths.opts.exampleValue=defaultPaths),Settings2.scanPaths.opts.exampleValue=()=>[defaultPicturesDir()],Settings2.taskListCap.opts.defaultValue=()=>e?1:Math.max(8,Math.round(maxConcurrentImports()*3)),Settings2.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round(maxCpus()/4)),Settings2.syncMaxTimeoutsBeforeRestart.opts.defaultValue=()=>e?1:Math.max(4,maxCpus()*2),Settings2.useFsWatch.watch(useFsWatch),isElectron()&&(Settings2.autoUpdateCheck.opts.defaultValue=!0),setDefaultElapsedErrorLogMs(Settings2.statTimeoutMs.valueOrDefault),Settings2.imageHashCrossFormatThresholdPct.opts.defaultValue=()=>Settings2.imageHashRelaxedThresholdPct.valueOrDefault,Settings2.imageHashRotationThresholdPct.opts.defaultValue=()=>Settings2.imageHashRelaxedThresholdPct.valueOrDefault,addSensitiveSettings()}),uidSuffix2=lazy2(()=>mapGte0(userid(),e=>`-`+e)??``);function tmpCacheDirs(){let e=(0,import_node_os13.tmpdir)();return[{dir:(0,import_node_path44.join)(e,`.photostructure-cache`+uidSuffix2()),preexistingDir:e}]}var envCacheDirs=defer(()=>uniq(compactBlankish([...getEnvs(`cacheDir`),...getEnvs(`PS_TMP_DIR`),...getEnvs(`PS_TEMP_DIR`)])).map(e=>({dir:e,preexistingDir:e}))),cacheDirs=defer(_cacheDirs);function _cacheDirs(){if(isDocker())return uniqBy([...envCacheDirs(),map(process.env.XDG_CACHE_HOME,e=>({dir:(0,import_node_path44.join)(e,SimpleAppNameLC),preexistingDir:e})),{dir:`/ps/tmp`,preexistingDir:`/ps/tmp`},{dir:`/ps/cache`,preexistingDir:`/ps/cache`},{dir:DefaultDockerLibraryDir+`/.photostructure/cache`+uidSuffix2(),preexistingDir:DefaultDockerLibraryDir},...tmpCacheDirs()],e=>e.dir);let e=compactBlanks(isWin?[getEnv(`LOCALAPPDATA`),resolve2(homeDir(),`AppData`,`Local`)]:isMac?[resolve2(homeDir(),`Library`,`Caches`)]:[process.env.XDG_CACHE_HOME,(0,import_node_path44.join)(homeDir(),`.cache`)]),n=isLinux?SimpleAppNameLC:SimpleAppName,r=e.map(e=>({dir:(0,import_node_path44.join)(e,n),preexistingDir:e}));return r.unshift(...envCacheDirs()),r.push(...tmpCacheDirs()),r}var defaultCacheDir=lazy2(()=>firstDir({dirs:cacheDirs(),desc:`cache`})),addSettingsListener=lazy2(()=>{setSettingsDefaults(),Settings2.cacheDir.watchLater(resetCacheDir)}),cacheDir=lazy2(()=>{try{return cacheDir_()}catch(e){onError(`cacheDir_() failed`,{error:e});return}}),cacheDir_=lazy2(()=>{addSettingsListener();let e=Settings2.cacheDir.value??(isTest()?tmpDirName({prefix:`ps-cache-test`}):Settings2.cacheDir.defaultValue);try{return mkdirpSync_(e),postProcess(e),e}catch(n){throw new WrappedError(`Failed to set up cacheDir, `+e,{path:e,fatal:!0,cause:n})}});async function postProcess(e){try{await writeCachedirTag_(e)}catch(n){mkLogger(`dir.CacheDir`).warn(`postProcess(): writeCachedirTag_() failed for `+e,n)}try{await mkNoMedia_(e)}catch(n){mkLogger(`dir.CacheDir`).warn(`postProcess(): mkNoMedia_() failed for `+e,n)}}function resetCacheDir(){Settings2.cacheDir.unsetCachedEnvValue(),envCacheDirs.reset(),cacheDirs.reset(),phstrInternalDirs.reset(),defaultCacheDir.unset(),cacheDir.unset(),cacheDir_.unset()}ee().on(`resetDirectories`,resetCacheDir);function normalizeDirPath(e){let n=ensureSuffix(resolve2(e),import_node_path44.sep);return isCaseSensitiveFs?n:n.toLowerCase()}var phstrInternalDirs=defer(()=>{let e=cacheDirs().map(e=>e.dir);return e.push(Settings2.cacheDir.value,libraryPreviewsDir(),logDir(),...DockerInternalDirs),uniq(compactBlankish(e).map(normalizeDirPath))});function isInInternalDir(e){let n=toNativePath(e);if(n==null)return!1;let r=normalizeDirPath(n);return(toPathnames(r.toLowerCase())?.some(e=>e.startsWith(`.photostructure`))??!1)||phstrInternalDirs().some(e=>r.startsWith(e))}var import_promises22=require("node:fs/promises"),import_node_path45=require("node:path"),PsEnvKeys=[`PS_ENV_FILE`,`PSENVFILE`,`PS_ENV`,`PSENV`];function psEnvFilesFor(e,n){let r=[`/.psenv`,(0,import_node_path45.join)(n,`.psenv`),...PsEnvKeys.flatMap(n=>(e[n]??``).split(import_node_path45.delimiter))],a=[],o=new Set;for(let e of r){let n=e.trim();n.length>0&&!o.has(n)&&(o.add(n),a.push(n))}return a}function mergePsEnv(e,n){for(let[r,a]of Object.entries(e))n[r]=a;return n}async function mergePsEnvFiles(e,n){let r=new Set(Object.keys(e));for await(let r of readPsEnvFiles(n))mergePsEnv(r,e);return Object.keys(e).filter(e=>!r.has(e))}async function*readPsEnvFiles(e){for(let n of e)try{yield parseEnvTokenPairs(debom(await(0,import_promises22.readFile)(n)))}catch{}}var readAndMergePsEnv=lazy2(async()=>await _readAndMergePsEnv(process.env));function _readAndMergePsEnv(e,n=psEnvFiles()){return mergePsEnvFiles(e,n)}function psEnvFiles(){return psEnvFilesFor(process.env,homeDir())}var import_node_path50=require("node:path"),import_node_os15=require("node:os"),import_node_process24=require("node:process"),import_node_child_process5=require("node:child_process"),import_node_fs26=require("node:fs"),import_node_os14=__toESM(require("node:os")),logger43=lazy2(()=>mkLogger(`os`));function osName(){switch(import_node_os14.default.platform()){case`linux`:return osNameLinux();case`darwin`:return osNameMac();case`win32`:return osNameWin();default:return osNameDefault()}}var osArch=lazy2(()=>`${osName()} on ${import_node_os14.default.arch()}`),osFullName=lazy2(()=>osArch()+(isDocker()?` (Docker)`:``));function osNameDefault(){return import_node_os14.default.platform()+` `+import_node_os14.default.release()}var OsReleaseFiles=[`/etc/os-release`,`/usr/lib/os-release`],osReleaseTokens=lazy2(()=>{if(isLinux)for(let e of OsReleaseFiles)try{let n=(0,import_node_fs26.readFileSync)(e).toString();if(notBlank(n))return parseEnvTokens({input:n,lowerCaseKeys:!0})}catch(n){logger43().warn(`failed to read os-release file`,{filename:e,error:n})}}),osNameLinux=lazy2(()=>{let e=osReleaseTokens();return notBlank(e?.pretty_name)?e?.pretty_name:map2Or(e?.name,e?.version??e?.version_id,(e,n)=>e+` `+n,osNameDefault)}),osDistributionLinux=lazy2(()=>isLinux?osReleaseTokens()?.id?.toLowerCase():void 0);function isDebian(){return osDistributionLinux()===`debian`}function isUbuntu(){return osDistributionLinux()===`ubuntu`}function hasApt(){return isDebian()||isUbuntu()||isMint()}function isFedora(){return osDistributionLinux()===`fedora`}function isMint(){return osDistributionLinux()===`linuxmint`}var MacCodenames={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`,15:`Sequoia`,26:`Tahoe`},WinReleaseToVersions={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 majorMinor(e){return e.split(`.`).slice(0,2)}function versionToCodename(e,n){let[r,a]=majorMinor(e),o=n[r];return isString(o)?o:o?.[a]}var macProductVersion=lazy2(()=>{if(isMac)try{return(0,import_node_child_process5.execSync)(`/usr/bin/sw_vers -productVersion`).toString().trim()}catch(e){logger43().warn(`macProductVersion(): sw_vers failed`,{error:e});return}});function macCodename(e=macProductVersion()){return e==null?void 0:versionToCodename(e,MacCodenames)}function osNameMac(e=macProductVersion()){try{return mapNotBlankOr(macCodename(e),n=>`macOS ${n} (${e})`,osNameDefault)}catch(e){return logger43().warn(`osNameMac(): unknown release`,e),osNameDefault()}}function osNameWin(e=import_node_os14.default.release()){let n=semverLt(e,`10.0.22000`)?versionToCodename(e,WinReleaseToVersions):`11`;return n==null?(logger43().warn(`osNameWin(): unknown release: `+e),`Windows (${e})`):`Windows ${n} (${e})`}var CPUs=lazy2(()=>uniqCount(cpuInfo().map(e=>e.model)).map(e=>`${e.count} \xD7 ${e.t.trim()}`).join(`, `),minuteMs),whyOsNotSupported=lazy2(()=>{if(isWin)return import_node_os14.default.arch()===`x64`&&/^Windows (?:10|11) /i.test(osNameWin())?void 0:`Windows 10 and 11 on x64`;if(isMac)return semVerSatisfies(macProductVersion(),`>=12`)?void 0:`macOS 12 (Monterey) or later`;if(isLinux){let e=[`x64`,`arm64`].includes(import_node_os14.default.arch()),n=toSemVer(osReleaseTokens()?.version_id);if(isDebian())return e&&semVerSatisfies(n,`>=12`)?void 0:`Debian 12 or later on x64/ARM64`;if(isUbuntu())return e&&semVerSatisfies(n,`22 || 24 || 26`)?void 0:`Ubuntu LTS (22.04, 24.04, or 26.04) on x64/ARM64`;if(isMint())return e&&semVerSatisfies(n,`>=22`)?void 0:`Linux Mint 22 or later on x64/ARM64`;if(isFedora())return e&&semVerSatisfies(n,`>=40`)?void 0:`Fedora 40 or later on x64/ARM64`}return`recent versions of Debian/Ubuntu, Fedora, macOS, and Windows 11`});function isSensitiveKey(e){return!blank(e)&&(keyWords(e).some(e=>SensitiveWords.has(e))||isSensitiveEnvKey(e))}function loggableArgv(e){return e.map((n,r)=>{let a=e[r-1];if(a?.startsWith(`--`)===!0&&!a.includes(`=`)&&isSensitiveKey(a))return`(hidden)`;let o=/^(--[^=]+)=/.exec(n)?.[1];return o!=null&&isSensitiveKey(o)?`${o}=(hidden)`:n})}var logStartup=defer(()=>{mkLogger(`LogStartup`).info(`setup(): starting `+serviceName(),{version,StartTs,argv:loggableArgv(import_node_process24.argv),arch:(0,import_node_os15.arch)(),platform:(0,import_node_os15.platform)(),os:osFullName(),isPacked:isPacked(),isElectron:isElectron(),versions:pick(import_node_process24.versions,`electron`,`node`),settings:{logLevel:Settings2.logLevel.valueOrDefault,logServer:Settings2.logServer.valueOrDefault,httpPort:Settings2.httpPort.valueOrDefault,libraryDir:Settings2.libraryDir.valueOrDefault,copyAssetsToLibrary:Settings2.copyAssetsToLibrary.value??`(unset)`,UV_THREADPOOL_SIZE:import_node_process24.env.UV_THREADPOOL_SIZE},...mapEntries(psenv(),(e,n)=>[e,isSensitiveEnvKey(e)?`(hidden)`:n])})}),import_node_stream5=require("node:stream"),import_node_perf_hooks=require("node:perf_hooks");function logTs(){return Math.round((import_node_perf_hooks.performance.timeOrigin+import_node_perf_hooks.performance.now())*100)/100}function isLogEntry(e){return e!=null&&isNumber(e?.ts)&&isString(e?.msg)&&LogLevels.includes(e.l)}var PromisePlaceholder=`(promise)`;function prepMeta(e,n=4){if(e==null)return null;if(n<0)return`…`;if(isString(e)||Buffer.isBuffer(e))return ellipsize(e.toString(),256,32);if(isError(e))return errorToVerbose(e);if(isObject(e)&&e.constructor?.name===`Sharp`)return`(sharp)`;if(Array.isArray(e)){let r=LoggingSettings.logContextLimit.valueOrDefault,a=Math.floor(r/2);return e.length<=r?e.map(e=>prepMeta(e,n-1)):[...e.slice(0,a).map(e=>prepMeta(e,n-1)),`\u2026 (${e.length} total entries)`,...e.slice(-a).map(e=>prepMeta(e,n-1))]}if(typeof e==`function`)return`(function: ${notBlank(e.name)?e.name:`anonymous`})`;if(typeof e==`object`){for(let r of[`toLogJSON`,`toJSON`])if(typeof e[r]==`function`)return prepMeta(e[r](),n-1);if(isPromiseLike(e))return PromisePlaceholder;if(`…`in e)return e;let r=mapNullEntries(e,(e,r)=>e===`sql`?r:prepMeta(r,n-1),LoggingSettings.logContextLimit.valueOrDefault),a=diff(keys(e),keys(r));return isNotEmpty(a)&&(r[`…`]=`omitted: `+ellipsize(a.join(`, `),128,32)),r}return e}var LogStream=class{constructor(e,n=logFilter){this.from=e,this.filter=n}from;filter;stream=new import_node_stream5.Transform({objectMode:!0});isEnabled(e,n){return this.filter().enabled(e,n)}log(e,n,r,a){this.isEnabled(e,n)&&this._logEntry({from:this.from,ts:logTs(),l:e,ctx:n,msg:r,meta:prepMeta(a)})}_logEntry(e){this.stream.push(e)}maybeFlush(){}},import_node_fs27=require("node:fs"),import_promises23=require("node:fs/promises"),import_node_zlib3=require("node:zlib"),LogContentReader=class{#e=mkLogger(`LogContentReader`);async readFrom(e,n){try{if(!/\.jsonl(?:\.gz)?$/i.test(e))throw Error(`${e} is not a log file (expected *.jsonl or *.jsonl.gz)`);let r=(await(0,import_promises23.stat)(e)).size,a=n>r,o=a?0:n;return a&&this.#e.debug(`File truncated, re-reading from beginning`,{path:e,previousPosition:n,newSize:r}),o>=r?{lines:[],newPosition:o,fileSize:r}:(this.#e.trace(`Reading file content`,{path:e,startPosition:o,fileSize:r,bytesToRead:r-o,wasTruncated:a}),{lines:await this.#t(e,o,r),newPosition:r,fileSize:r})}catch(r){return this.#e.warn(`Error reading file content`,{path:e,startPosition:n,error:r}),{lines:[],newPosition:n,fileSize:void 0}}}async#t(e,n,r){return new Promise((a,o)=>{let s=[],c;try{c=this.#n(e)?(0,import_node_fs27.createReadStream)(e,{autoClose:!0}):(0,import_node_fs27.createReadStream)(e,{autoClose:!0,start:n,end:r-1}),c.on(`error`,o),e.toLowerCase().endsWith(`.gz`)&&(c=c.pipe((0,import_node_zlib3.createGunzip)()).on(`error`,o));let l=new LineReader({trimStart:!0,trimEnd:!0,onlyStreamFullLines:!0});c.pipe(l).on(`data`,e=>s.push(e)).on(`end`,()=>a(s)).on(`error`,o)}catch(e){o(e)}})}#n(e){return e.toLowerCase().endsWith(`.gz`)}async getFileSize(e){try{return(await(0,import_promises23.stat)(e)).size}catch(n){return this.#e.trace(`Cannot get file size`,{path:e,error:n}),null}}async isReadable(e){try{return(await(0,import_promises23.stat)(e)).isFile()}catch{return!1}}},import_node_path46=require("node:path");function chunkToLogEntry(e){let n=parseJSON(e);return isLogEntry(n)?n:void 0}var LogEntryParser=class{#e=mkLogger(`LogEntryParser`);#t=new Map;parse(e,n){if(e.trim().length===0)return null;try{let r=chunkToLogEntry(e);return r==null?(this.#r(e,n,`chunkToLogEntry returned null`),null):{...r,from:this.#n(n)}}catch(r){return this.#r(e,n,r),null}}parseLines(e,n){let r=[];for(let a of e){let e=this.parse(a,n);e!=null&&r.push(e)}return r}getErrorStats(){return Object.fromEntries(this.#t)}clearErrorStats(){this.#t.clear()}#n(e){return(0,import_node_path46.basename)(e)}#r(e,n,r){let a=`${n}:parse_error`,o=this.#t.get(a)??0;this.#t.set(a,o+1),o<5?this.#e.warn(`Failed to parse log entry`,{sourcePath:n,line:ellipsize(e,256,32),error:r?.message??String(r),errorCount:o+1}):o===5&&this.#e.warn(`Suppressing further parse errors for file`,{sourcePath:n,totalErrors:o+1})}},import_promises24=require("node:fs/promises"),import_node_path48=require("node:path"),import_watcher=require("@parcel/watcher"),logger44=defer(()=>mkLogger(`fs.DirWatcher`)),DirWatcher=class e extends EndableWrapper{constructor(e,n,r){super(`fs.DirWatcher(`+e+`)`,()=>this.close(),r),this.nativePath=e,this.subscription=n}nativePath;subscription;static async for(n,r,a=EndableRanks.first){let o=toNativePath_(n);await mkdirp_(o);let s=await(0,import_watcher.subscribe)(o,async(e,n)=>{logger44().trace(`callback`,{file:o,error:e,arr:n}),e!=null&&onError(`FsWatcher error`,{cause:e,path:o});let a=[];for(let e of toA(n)){if(isHiddenBasename(e.path))continue;let n=statSync(e.path);(n==null||n.isFile())&&a.push(e)}(e!=null||isNotEmpty(a))&&r(e,a)},{backend:isWin?`windows`:void 0});return new e(o,s,a)}close=defer(()=>this.subscription.unsubscribe())},import_node_path47=require("node:path");function datedLogDir(e,n){return(0,import_node_path47.join)(e??LoggingSettings.logDir.valueOrDefault,fmtIsoDate(n??new Date))}var JsonlLogFileRegex=/\.jsonl(?:\.gz)?$/i;function isJsonlLogFile(e){return JsonlLogFileRegex.test(e)}function parseLogfileName(e){let n=toS(e).split(/[-.]/);return toCompactObj({serviceName:ServiceNames.toValid(n[0]),pid:toInt(n[1]),count:toInt(n[2])})}function sameFile(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.birthtimeMs===n.birthtimeMs}var LogFileDiscovery=class{#e=mkLogger(`LogFileDiscovery`);#t;#n;#r;#i;#a;#o=Promise.resolve();#s=new Set;#c=new Map;constructor(e,n,r,a){this.#t=e,this.#n=n,this.#r=r,this.#i=a}async discover(){let e=datedLogDir(this.#t);await mkdirp_(e),this.#e.trace(`Scanning for existing log files`,{logDir:e});let n=[];for await(let r of iterateDir_(e)){if(!this.#u(r.name))continue;if(this.#s.add(r.name),parseLogfileName(r.name)?.pid===process.pid){this.#e.trace(`Skipping own log file`,{name:r.name});continue}let a=(0,import_node_path48.join)(e,r.name),o;try{o=await(0,import_promises24.stat)(a),this.#c.set(r.name,o)}catch(e){if(this.#e.warn(`Could not stat file`,{path:a,error:e}),this.#n>0)continue;n.push(a);continue}this.#n>0&&this.#d(o)<this.#n?this.#e.trace(`Skipping file due to timestamp filter`,{path:a,minTimestamp:this.#n}):(n.push(a),this.#e.trace(`Discovered log file`,{file:a}))}return this.#e.debug(`Discovery complete`,{fileCount:n.length,logDir:e}),n}async startWatching(){if(ending())return;let e=datedLogDir(this.#t);await mkdirp_(e),this.#e.debug(`Starting file system watcher`,{logDir:e}),this.#a=await DirWatcher.for(e,(e,n)=>this.onFileSystemEvent(e,n),EndableRanks.logtail),this.#e.trace(`File system watcher started`)}async stop(){this.#e.debug(`Stopping file discovery`),this.#a!=null&&!this.#a.ended&&await this.#a.end()}async onFileSystemEvent(e,n){let r=this.#o.then(()=>this.#l(e,n));return this.#o=r.catch(e=>{this.#e.warn(`Error processing file system events`,{error:e})}),r}async#l(e,n){if(e!=null)this.#e.warn(`File system watcher error`,{error:e}),this.#i?.(e);else if(!ending())for(let e of n){let n=(0,import_node_path48.basename)(e.path);if(this.#u(n))try{let r=!this.#s.has(n);if(e.type!==`create`&&!(e.type===`update`&&r))continue;let a;try{a=await(0,import_promises24.stat)(e.path)}catch(n){this.#e.trace(`Could not stat watcher file`,{file:e.path,error:n});continue}let o=this.#c.get(n);if(this.#s.add(n),this.#c.set(n,a),o!=null&&sameFile(o,a)||parseLogfileName(n)?.pid===process.pid)continue;if(this.#n>0&&this.#d(a)<this.#n){this.#e.trace(`Skipping file due to timestamp filter`,{file:e.path,minTimestamp:this.#n});continue}this.#e.trace(`New log file detected`,{file:e.path}),this.#r(e.path)}catch(n){this.#e.warn(`Error processing file system event`,{file:e.path,error:n})}}}#u(e){return isJsonlLogFile(e)}#d(e){return e.birthtimeMs===0?e.mtimeMs:e.birthtimeMs}},import_node_events2=require("node:events"),import_promises25=require("node:fs/promises"),LogFileMonitor=class extends import_node_events2.EventEmitter{#e=mkLogger(`LogFileMonitor`);#t=new Map;#n=new Map;async watch(e){if(this.#t.has(e))this.#e.trace(`Already watching file`,{path:e});else try{let n=await(0,import_promises25.stat)(e);this.#n.set(e,n.size),this.#e.trace(`Starting file monitor`,{path:e,initialSize:n.size});let r=watchWithDiagnostics(e,{},(n,r)=>{this.#r(e,n,r)},`LogFileMonitor`);r.on(`error`,n=>{this.#e.warn(`File watcher error`,{path:e,error:n}),this.emit(`error`,e,n)}),this.#t.set(e,r)}catch(n){this.#e.warn(`Failed to start watching file`,{path:e,error:n}),this.emit(`error`,e,n)}}unwatch(e){let n=this.#t.get(e);n&&(n.close(),this.#t.delete(e),this.#n.delete(e),this.#e.trace(`Stopped watching file`,{path:e}))}unwatchAll(){this.#e.debug(`Stopping all file monitors`,{watchedFiles:this.#t.size});for(let[e,n]of this.#t)n.close(),this.#e.trace(`Stopped watching file`,{path:e});this.#t.clear(),this.#n.clear(),this.removeAllListeners()}getWatchedFiles(){return Array.from(this.#t.keys())}isWatching(e){return this.#t.has(e)}getStats(){return{watchedFileCount:this.#t.size,watchedFiles:this.getWatchedFiles()}}async#r(e,n,r){try{this.#e.trace(`File change detected`,{path:e,eventType:n,filename:r});let a=(await(0,import_promises25.stat)(e)).size,o=this.#n.get(e)??0;a===o?this.#e.trace(`File change event but no size change`,{path:e,size:a}):(this.#e.trace(`File size changed`,{path:e,lastSize:o,currentSize:a,sizeChange:a-o}),this.#n.set(e,a),this.emit(`change`,e,a,o))}catch(n){n?.code===`ENOENT`?(this.#e.debug(`File no longer exists`,{path:e}),this.emit(`removed`,e),this.unwatch(e)):(this.#e.warn(`Error checking file change`,{path:e,error:n}),this.emit(`error`,e,n))}}},LogFileTracker=class{#e=new Map;#t=new Map;#n=new Map;#r=new Set;addFile(e){this.#r.add(e),this.#e.has(e)||this.#e.set(e,0)}removeFile(e){this.#r.delete(e),this.#e.delete(e),this.#t.delete(e),this.#n.delete(e)}getPosition(e){return this.#e.get(e)??0}setPosition(e,n){if(n<0)throw Error(`Invalid position ${n} for ${e}`);this.#e.set(e,n)}getFileSize(e){return this.#t.get(e)}setFileSize(e,n){this.#t.set(e,n)}getLastModified(e){return this.#n.get(e)}setLastModified(e,n){this.#n.set(e,n)}hasFile(e){return this.#r.has(e)}getFiles(){return Array.from(this.#r)}getFilesWithPotentialUpdates(){return this.getFiles().filter(e=>{let n=this.getPosition(e),r=this.getFileSize(e);return r!=null&&n<r})}clear(){this.#r.clear(),this.#e.clear(),this.#t.clear(),this.#n.clear()}getStats(){return{fileCount:this.#r.size,totalBytesRead:Array.from(this.#e.values()).reduce((e,n)=>e+n,0),filesWithUpdates:this.getFilesWithPotentialUpdates().length}}},LogTail=class e extends EndableWrapper{#e;#t;#n;#r;#i;#a;#o;#s;#c=[];#l=!1;#u;#d;#f=new Set;constructor(e=Settings2.logDir.valueOrDefault,n=DefaultLogEntryWriter,r=StartTs,a=200,o){super(`LogTail`,()=>this.#w(),EndableRanks.logtail,3e3),this.#a=n,this.#o=a,this.#s=o??Math.min(Settings2.logFlushMs.valueOrDefault+100,500),this.#e=new LogFileDiscovery(e,r,e=>void this.#m(e),e=>this.logger.warn(`Discovery error`,{error:e})),this.#t=new LogFileMonitor,this.#n=new LogContentReader,this.#r=new LogEntryParser,this.#i=new LogFileTracker,this.#t.on(`change`,e=>void this.#h(e)),this.#t.on(`removed`,e=>this.#g(e)),this.#t.on(`error`,(e,n)=>this.logger.warn(`Monitor error`,{path:e,error:n}))}async setup(){try{this.logger.info(`Setting up LogTail`);let e=await this.#e.discover();this.logger.debug(`Discovered existing files`,{count:e.length});for(let n of e)await this.#p(n);await this.#e.startWatching(),this.#y(),this.logger.info(`LogTail setup complete`,{trackedFiles:this.#i.getFiles().length})}catch(e){throw this.logger.error(`Error setting up LogTail`,{error:e}),e}}async#p(e){try{if(this.#i.hasFile(e))return;this.logger.trace(`Adding file`,{path:e}),this.#i.addFile(e),await this.#t.watch(e),await this.#_(e)}catch(n){this.logger.warn(`Error adding file`,{path:e,error:n})}}async#m(e){this.logger.debug(`New file detected`,{path:e}),await this.#p(e)}async#h(e){this.logger.trace(`File changed`,{path:e}),await this.#_(e)}#g(e){this.logger.debug(`File removed`,{path:e}),this.#i.removeFile(e),this.#t.unwatch(e)}async#_(e){if(!this.#f.has(e)){this.#f.add(e);try{await this.#v(e)}finally{this.#f.delete(e)}}}async#v(e){try{let n=this.#i.getPosition(e),r=await this.#n.readFrom(e,n);if(this.#i.setPosition(e,r.newPosition),r.fileSize!=null&&this.#i.setFileSize(e,r.fileSize),r.lines.length===0)return;this.logger.trace(`Read file updates`,{path:e,lineCount:r.lines.length,oldPosition:n,newPosition:r.newPosition}),this.#i.setLastModified(e,Date.now());let a=this.#r.parseLines(r.lines,e);a.length>0&&(this.#c.push(...a),this.logger.trace(`Added entries to buffer`,{count:a.length}))}catch(n){this.logger.warn(`Error reading file updates`,{path:e,error:n})}}#y(){this.#l||this.ended||(this.#l=!0,this.logger.debug(`Starting processing with interval`),this.#u=setInterval(()=>{this.#b()},this.#s),this.#x())}async#b(){if(!(this.ended||this.#c.length===0))try{let e=Date.now()-this.#s,n=[];for(this.#S();this.#c.length>0&&this.#c[0].ts<=e;)n.push(this.#c.shift());await this.#C(n),n.length>0&&this.logger.trace(`Processed entries from buffer`,{count:n.length})}catch(e){this.logger.warn(`Error processing buffer`,{error:e})}}#x(){this.#d=setInterval(async()=>{if(!this.ended)try{for(let e of this.#i.getFiles()){let n=await this.#n.getFileSize(e);n!=null&&this.#i.getPosition(e)<n&&await this.#_(e)}}catch(e){this.logger.warn(`Error in polling`,{error:e})}},this.#o)}#S(){this.#c.sort((e,n)=>{let r=e.ts-n.ts;return r===0?(e.from??``).localeCompare(n.from??``):r})}async#C(e,n=`Error writing log entry`){for(let r of e)try{await this.#a(r)}catch(e){this.logger.warn(n,{error:e})}}async flush(){for(let e of this.#i.getFiles())await this.#_(e);if(this.#c.length===0)return;this.logger.debug(`Flushing buffer`,{count:this.#c.length}),this.#S();let e=[...this.#c];this.#c.length=0,await this.#C(e,`Error writing log entry during flush`),this.logger.debug(`Flush complete`,{processedCount:e.length})}async endWhenIdle(){this.logger.debug(`endWhenIdle called`),await this.flush(),await this.end()}async#w(){this.logger.debug(`Cleaning up LogTail`),this.#u&&clearInterval(this.#u),this.#d&&clearInterval(this.#d),this.#l=!1,await this.flush(),await this.#e.stop(),this.#t.unwatchAll(),this.#i.clear(),this.logger.trace(`LogTail cleanup complete`)}getStats(){return{tracker:this.#i.getStats(),monitor:this.#t.getStats(),parser:this.#r.getErrorStats(),bufferSize:this.#c.length,isProcessing:this.#l}}static instance=defer(async()=>{let n=new e,r=new LogStream(serviceName());return rootLoggers().push(r),filterInPlace(rootLoggers(),e=>e!==ConsoleLogger.instance()),r.stream.on(`data`,e=>{n.#c.push(e)}),await n.setup(),n})},import_toml2=__toESM(require_toml()),import_node_crypto6=require("node:crypto"),import_promises28=require("node:fs/promises"),fsp4=__toESM(require("node:fs/promises")),logger45=lazy2(()=>mkLogger(`fs.Unlink`));async function unlink4(e,n=`warn`){for(let r of toA(e))try{r!=null&&(await thenOrTimeoutError(fsp4.unlink(toNativePath_(r)),statTimeoutMs()),logger45().debug(`unlink()`,{path:r}))}catch(e){logger45().log(n,`Failed to unlink`,{path:r,error:e})}}var baseVersion=()=>[versionMajor,versionMinor,versionPatch].join(`.`),versionMajorMinor=versionMajor+`.`+versionMinor,logger46=defer(()=>mkLogger(`settings.LibrarySettings`));function librarySettingsFile(e){return libraryDataDirPosixFile(e)?.join(SettingsToml)}var libraryHasSettings=lazy2(()=>_libraryHasSettings(),minuteMs);libraryHasSettings.unset=()=>libraryHasSettings.refresh();var SetupOnlyKeys=[`authMode`,`libraryName`,...keys(EmailSettings),...keys(OidcSettings)];function _libraryHasSettings(e){let n=librarySettingsFile(e),r=n?.clear().existsSync()??!1,a=r?readTomlFileSync(n):void 0,o=a==null?[]:Object.keys(a),s=o.length>0&&o.every(e=>SetupOnlyKeys.includes(e));return logger46().tap({msg:`_libraryHasSettings`,result:r&&!s,meta:{libraryDir_arg:e,libraryDir_settings:PathSettings.libraryDir.valueOrDefault,librarySettingsFile:n?.nativePath}})}function onSettingsChange(){libraryHasSettings.refresh()}later(()=>{ee().on(`clearCache`,onSettingsChange),ee().on(`settingsChanged`,onSettingsChange),PathSettings.libraryDir.watchLater(onSettingsChange)});var logger47=lazy2(()=>mkLogger(`settings.MetaSettings`));function getSettingValue(e,n){return Settings2[e].value??n.find(n=>n.name===e)?.value??Settings2[e].defaultValue}function wasExplicitlySet(e,n){return Settings2[e].value!=null||n.some(n=>n.name===e&&n.value!=null)}function handleMetaSettings(e){setQuickSyncMode(Settings2.quickSyncMode.valueOrDefault),setPreviewCacheProfile(getSettingValue(`previewCacheProfile`,e)),getSettingValue(`disableAllFilters`,e)&&disableAllFilters(),setAggregationMode(getSettingValue(`aggregationMode`,e)),optedOut()&&disableTelemetry(),Settings2.noNetwork.valueOrDefault&&(Settings2.autoUpdateCheck.cliValue=!1,Settings2.autoRefreshLicense.cliValue=!1)}function setPreviewCacheProfile(e){let n=previewCacheProfileOption(e);Settings2.maxThumbnailLongEdge.defaultValue=n.maxThumbnailLongEdge,Settings2.previewPixelWastePct.defaultValue=n.previewPixelWastePct}function settingsValueWarnings(e){let n=[],r=getSettingValue(`logFlightRecorderTriggerLevel`,e),a=getSettingValue(`logFlightRecorderMinLevel`,e),o=wasExplicitlySet(`logFlightRecorderTriggerLevel`,e),s=wasExplicitlySet(`logFlightRecorderMinLevel`,e);o&&levelIndex(r)>=levelIndex(a??Settings2.logFlightRecorderMinLevel.valueOrDefault)&&(n.push(`logFlightRecorderTriggerLevel (${Settings2.logFlightRecorderTriggerLevel.value}) is more verbose than logFlightRecorderMinLevel (${Settings2.logFlightRecorderMinLevel.valueOrDefault}); adjusting trigger level to ${Settings2.logFlightRecorderTriggerLevel.defaultValue}`),Settings2.logFlightRecorderTriggerLevel.unset()),s&&levelIndex(a)<=levelIndex(r??Settings2.logFlightRecorderTriggerLevel.valueOrDefault)&&(n.push(`logFlightRecorderTriggerLevel (${Settings2.logFlightRecorderTriggerLevel.valueOrDefault}) is more verbose than logFlightRecorderMinLevel (${Settings2.logFlightRecorderMinLevel.value}); adjusting min level to ${Settings2.logFlightRecorderMinLevel.defaultValue}`),Settings2.logFlightRecorderMinLevel.unset());for(let e of Settings2.sensitiveWordsAdd.valueOrDefault){let r=keyWords(e);if(r.length>1){n.push(`sensitiveWordsAdd entry "${e}" holds ${r.length} words and is matched as the single word "${r.join(``)}"; list ${r.map(e=>`"${e}"`).join(` and `)} separately to match either.`);continue}let a=envKeysRemovedByWord(r.join(``));isNotEmpty(a)&&n.push(`sensitiveWordsAdd entry "${e}" removes ${a.sort().join(`, `)} from child processes.`)}return n}async function handleDeprecatedSettings(){{let e=Settings2.writeVolumeUuidMountpointBlocklist.fileValue;if(e!=null){let n=[],r=[];for(let a of e)isLegacyWriteVolumeUuidFilesystemBlocklistEntry(a)?n.push(a):r.push(a);let a=Settings2.writeVolumeUuidFilesystemBlocklist.fileValue,o=new CaseInsensitiveSet(a??[]),s=n.filter(e=>!o.has(e));(a==null||s.length>0)&&(Settings2.writeVolumeUuidFilesystemBlocklist.value=[...a??[],...s]);let c=Settings2.writeVolumeUuidPathBlocklist.fileValue,l=new CaseInsensitiveSet(c??[]),u=r.filter(e=>!l.has(e));(c==null||u.length>0)&&(Settings2.writeVolumeUuidPathBlocklist.value=[...c??[],...u]),logger47().warn(`Splitting deprecated writeVolumeUuidMountpointBlocklist into writeVolumeUuidFilesystemBlocklist and writeVolumeUuidPathBlocklist`,{prior:e,filesystems:n,paths:r,addedFilesystems:s,addedPaths:u}),Settings2.writeVolumeUuidMountpointBlocklist.unsetFileValue()}}if(isTrue(Settings2.scanMyPictures.fileValue)){Settings2.scanMyPictures.unsetFileValue();let e=await picturesDir();logger47().warn(`Upgrading setting scanMyPictures to scanPaths`,{priorValues:Settings2.scanPaths.values,newPath:e}),Settings2.scanPaths.push(e)}{let e=Settings2.strictDeduping.fileValue;e===!0&&Settings2.aggregationMode.fileValue==null&&(logger47().warn(`Upgrading setting strictDeduping to aggregationMode`,{prior:e}),Settings2.aggregationMode.value=`strict`)}{let e=Settings2.assetSubdirectoryDatestampFormat.fileValue;if(blank(Settings2.assetPathnameFormat.fileValue)&¬Blank(e)){Settings2.assetSubdirectoryDatestampFormat.unsetFileValue();let n=ensureSuffix(e,`/`)+`BASE`;logger47().warn(`Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat`,{prior:e,newValue:n}),Settings2.assetPathnameFormat.value=n}}{let e=Settings2.dbBackupIntervalMinutes.fileValue;if(e!=null&&Settings2.dbBackupIntervalMs.fileValue==null){let n=e*minuteMs;logger47().warn(`Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs`,{newValue:n}),Settings2.dbBackupIntervalMs.value=n}}{let e=Settings2.siblingInferenceBasenameCoeff.fileValue;if(e!=null&&Settings2.siblingInferenceBasenameCoeffPct.fileValue==null){let n=Math.round(e*100);logger47().warn(`Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct`,{newValue:n}),Settings2.siblingInferenceBasenameCoeffPct.value=n}}{let e=Settings2.siblingInference.fileValue;if(e!=null&&Settings2.inferenceSiblingRadius.fileValue==null){let n=e===`never`?0:void 0;n!=null&&(logger47().warn(`Upgrading setting siblingInference to inferenceSiblingRadius`,{priorEnum:e,newValue:n}),Settings2.inferenceSiblingRadius.value=n)}let n=Settings2.enableSiblingInference.fileValue;if(n!=null&&Settings2.inferenceSiblingRadius.fileValue==null&&n===!1){let e=0;logger47().warn(`Upgrading setting enableSiblingInference to inferenceSiblingRadius`,{priorBool:n,newValue:0}),Settings2.inferenceSiblingRadius.value=0}}{let e=Settings2.rejectRatingsLessThan.fileValue;if(e!=null&&Settings2.rejectRating.fileValue==null){let n=e-1,r=`-`+(n>0?`+`:``)+n;logger47().warn(`Upgrading setting rejectRatingsLessThan to rejectRating`,{newValue:r}),Settings2.rejectRating.value=r}}{let e=Settings2.fileCopyOnlyNative.fileValue,n=Settings2.fileCopyWithReflink.fileValue;if((e!=null||n!=null)&&Settings2.fileCopyStrategy.fileValue==null){let r;r=e===!0?FileCopyStrategies[`native-preserve`]:n===!0?FileCopyStrategies[`builtin-reflink`]:FileCopyStrategies.builtin,logger47().warn(`Upgrading file copy settings to fileCopyStrategy`,{fileCopyOnlyNative:e,fileCopyWithReflink:n,newStrategy:r}),Settings2.fileCopyStrategy.value=r,Settings2.fileCopyOnlyNative.unsetFileValue(),Settings2.fileCopyWithReflink.unsetFileValue()}}}function disableAllFilters(){Settings2.respectFileExtensions.cliValue=!1,Settings2.requireMakeModel.cliValue=!1,Settings2.rejectRating.cliValue=``,Settings2.minImageDimension.cliValue=0,Settings2.minVideoDimension.cliValue=0,Settings2.minVideoDurationSec.cliValue=0,Settings2.maxVideoDurationSec.cliValue=0,Settings2.minAssetFileSizeBytes.cliValue=0,Settings2.maxAssetFileSizeBytes.cliValue=0,Settings2.validateJpegImages.cliValue=!1,Settings2.validateRawImages.cliValue=!1,Settings2.validateVideos.cliValue=!1}var aggregationProfileSettings=[Settings2.imageHashThresholdPct,Settings2.imageHashRelaxedThresholdPct,Settings2.imageHashFuzzyDateThresholdPct,Settings2.allowFuzzyDateImageHashMatches,Settings2.checkBasenameMatches,Settings2.requireSameColorSpace,Settings2.imageHashMatchK,Settings2.minCapturedAtPrecisionDifferentMimetypes,Settings2.fuzzyDatePrecisionFactor];function setAggregationMode(e){for(let e of aggregationProfileSettings)e.resetDefaultValue();e===`strict`?setStrictDeduping():e===`lenient`&&setLenientDeduping()}function setStrictDeduping(){Settings2.imageHashThresholdPct.defaultValue=95,Settings2.imageHashRelaxedThresholdPct.defaultValue=80,Settings2.imageHashFuzzyDateThresholdPct.defaultValue=95,Settings2.allowFuzzyDateImageHashMatches.defaultValue=!1,Settings2.checkBasenameMatches.defaultValue=!1,Settings2.requireSameColorSpace.defaultValue=!0,Settings2.imageHashMatchK.defaultValue=50,Settings2.minCapturedAtPrecisionDifferentMimetypes.defaultValue=0,Settings2.fuzzyDatePrecisionFactor.defaultValue=1}function setLenientDeduping(){Settings2.imageHashThresholdPct.defaultValue=60,Settings2.imageHashRelaxedThresholdPct.defaultValue=30,Settings2.imageHashFuzzyDateThresholdPct.defaultValue=70,Settings2.allowFuzzyDateImageHashMatches.defaultValue=!0,Settings2.checkBasenameMatches.defaultValue=!0,Settings2.requireSameColorSpace.defaultValue=!1,Settings2.imageHashMatchK.defaultValue=200,Settings2.minCapturedAtPrecisionDifferentMimetypes.defaultValue=minuteMs,Settings2.fuzzyDatePrecisionFactor.defaultValue=4}var quickSyncSettings=[Settings2.validateJpegImages,Settings2.validateRawImages,Settings2.validateVideos,Settings2.transcodeVideos,Settings2.previewMinimized,Settings2.previewProgressive,Settings2.previewSharpen];function setQuickSyncMode(e){for(let n of quickSyncSettings)n.cliValue=!e&&void 0;e?Settings2.inferenceSiblingRadius.cliValue=0:Settings2.inferenceSiblingRadius.cliValue=void 0,Settings2.dominantColorDeltaE.cliValue=e?ColorDistanceFunctions.cie76:ColorDistanceFunctions.ciede2000}function optOutRequested(){return doNotTrack()||Settings2.optOut.valueOrDefault}function optedOut(){return optOutRequested()||Settings2.noNetwork.valueOrDefault}function disableTelemetry(){Settings2.allowUserAgent.cliValue=!1,Settings2.reportErrors.cliValue=!1}var import_fs_metadata3=require("@photostructure/fs-metadata"),import_promises27=require("node:fs/promises"),import_promises26=require("node:fs/promises"),SQLiteSuffixes=[`-wal`,`-journal`],logger48=lazy2(()=>mkLogger(`db.SQLiteFiles`));function sqliteFiles(e,n={}){return[e,...(n.includeShm===!1?SQLiteSuffixes:[...SQLiteSuffixes,`-shm`]).map(n=>e.sibling(e.base+n))].filter(e=>e.existsSync({refresh:!0}))}async function removeDbOtherAccess_(e,n){if(isWin){warnWindowsDbAclsUnchanged();return}let r=sqliteFiles(e);if(r.length!==0){await removeOtherAccess_(e.parent(),n);for(let e of r)await removeOtherAccess_(e,n)}}async function removeDbDirOtherAccess_(e,n){isWin?warnWindowsDbAclsUnchanged():await removeOtherAccess_(e,n)}var warnWindowsDbAclsUnchanged=lazy2(()=>logger48().warn(`Windows ACLs are not adjusted for the library database: its files keep the access their folder grants`)),OtherAccess=7,GroupAndOtherAccess=63,loggedOtherAccessFailures=new Set;async function removeOtherAccess_(e,n){let r=n?GroupAndOtherAccess:OtherAccess,a,o;try{a=(await(0,import_promises26.stat)(e.nativePath)).mode&4095,(a&r)!==0&&(await(0,import_promises26.chmod)(e.nativePath,a&~r),a=(await(0,import_promises26.stat)(e.nativePath)).mode&4095)}catch(e){o=e}o==null&&(a&r)===0||loggedOtherAccessFailures.has(e.nativePath)||(loggedOtherAccessFailures.add(e.nativePath),logger48().error(`Could not remove other users' access to database storage`,{file:e.nativePath,observedMode:a?.toString(8).padStart(4,`0`),error:o}))}async function sqliteSizeBytes(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+`-wal`).size({refresh:!0})??0)}var SQLiteFileSuffixes=[SqliteExt,`.sqlite`].flatMap(e=>[e,...[...SQLiteSuffixes,`-shm`].map(n=>e+n)]),logger49=defer(()=>mkLogger(`settings.OwnerOnlyFile`)),nativeOwnerOnly=isWin||isMac;async function createOwnerOnlyFile_(e){let n=PosixFile.for(e);nativeOwnerOnly?await bestEffortOwnerOnly_(n.base,n.parent().nativePath,()=>(0,import_fs_metadata3.createOwnerOnlyFile)(e)):await(0,import_promises27.writeFile)(e,Buffer.alloc(0),{flush:!0,mode:384})}async function bestEffortOwnerOnly_(e,n,r){try{await r()}catch(r){let a=errorCode(r);if(a==null)throw r;let o=a===`ENOTSUP`,s=!o&&(isUNC(n)||(await bestVolumeForPath(n))?.remote===!0);if(!o&&!s)throw r;logger49().warn(`Could not make ${e} readable only by its owner: ${o?`its volume keeps no access control lists`:`it is on a network share`}`,{error:r})}}async function setPersistedLibraryDir_(e,{onlyIfUnset:n=!1}={}){let r=PosixFile.for(systemSettingsFile_()),a=toNotBlank(e),o=await readSettingsFileSnapshot_(r),s={libraryDir:a};if(eql(o.values,patchSettingsSnapshot(o,s)))return!1;let c,l=await r.applyWip_({timeoutMs:ShortCommandTimeoutMs,skipFsLock:!1,preserveDestOnError:!0,fn_:async e=>{let a=await readSettingsFileSnapshot_(r);if(n&&toNotBlank(snapshotSettingValue(a,Settings2.libraryDir))!=null)throw Error(`A library directory is already selected. Reload Settings.`);let o=patchSettingsSnapshot(a,s);return eql(o,a.values)?NoOp2:(c=await writeSettingsReplacement_(r,e,async()=>{await writeSettingsFileContents_(e,persistedSystemSettings(),a,o,[Settings2.libraryDir])}),!0)},beforeRename_:()=>c()});if(l==null)throw Error(`Could not acquire the system settings lock.`);return l===!0}var SyncPorts=`sync↔web IPC no longer uses TCP loopback ports`,SuspendBackup=`it never took effect: nothing has read it since 2024, so a system suspend never started a backup. Library database backups follow dbBackupIntervalMs`,ExposureFuzziness=`exposure tolerances now follow aggregationMode: strict uses 1/16 stop, default uses 1/3 stop, and lenient uses 1 stop`,RemovedSettingsByName=new Map([[`updateChannel`,`updates now follow stable releases, and Linux desktops follow their configured apt or dnf repository. The Settings page no longer selects a release channel`],[`stopSyncSensorNames`,`only CPU, HDD, and SSD categories may pause sync. Use maxCpuTempCelsius, maxHddTempCelsius, or maxSsdTempCelsius; set a category to 0 to disable all its pauses. Other sensors are diagnostic only`],[`maxTempCelsius`,`temperature pauses use maxCpuTempCelsius, maxHddTempCelsius, and maxSsdTempCelsius. Set a category to 0 to disable all its pauses; other sensors use only hardware-provided limits for diagnostics`],[`syncPort`,SyncPorts],[`syncEventsPort`,SyncPorts],[`singleThreaded`,`worker delegation is required for crash and hang recovery. To reduce load, lower cpuBusyPercent or set maxConcurrentImports to 1`],[`placeholderThumbs`,`it was a support-only latency hack that galleries stopped reaching once thumbnails moved to their own route. A missing preview now schedules its own rebuild`],[`sensitiveEnvRegExp`,`use "sensitiveWordsAdd" instead. It takes whole words, one per entry, and adds them to PhotoStructure's built-in list rather than replacing it, so a word added in a later release still applies. A regex is not converted into words: guessing at its anchors would either strip a variable a child process needs or leak the one it was hiding`],[`exposureThresholdPct`,ExposureFuzziness],[`minExposureSettingsCoeffPct`,ExposureFuzziness],[`dbRepairMode`,`it never took effect. Database repair always rebuilds with SQLite's .recover, and fails without replacing your database if the rebuilt copy is missing rows`],[`imageDataHashType`,`image data hashing slowed every metadata read and rarely changed how photos were grouped. PhotoStructure groups copies by their full-file SHA, metadata, and perceptual image hashes, which also match copies with a different orientation`],[`dbBackupRemoteOnSuspend`,SuspendBackup],[`backupRemoteDbOnSuspend`,SuspendBackup],[`videoFrameAtSec`,`video previews now use the first frame with content, so a video's preview matches what plays when it starts. Clips that open on black or white use their first frame with content in the first second`]]),RemovedSettings=new CaseInsensitiveMap([...RemovedSettingsByName].flatMap(([e,n])=>[[e,n],[envFromName(e),n]]));function whyRemovedSetting(e){return RemovedSettings.get(e)}var logger50=defer(()=>mkLogger(`settings.SettingsIO`));async function writeSettingsReplacement_(e,n,r,a=!1){let o;try{o=(await(0,import_promises28.stat)(e.nativePath)).mode&511}catch(e){if(errorCode(e)!==`ENOENT`)throw e}if(a){await createOwnerOnlyFile_(n.nativePath),await r();let e=o==null?384:o&448;return async()=>{e!==384&&await n.chmod_(e)}}if(o==null)return await r(),async()=>{};let s=o,c=s|128;return await(0,import_promises28.writeFile)(n.nativePath,Buffer.alloc(0),{flush:!0,mode:384}),await n.chmod_(c),await r(),async()=>{c!==s&&await n.chmod_(s)}}async function readSettingsFileSnapshot_(e){let n=PosixFile.forMaybe(e),r;if(n!=null)try{r=await(0,import_promises28.readFile)(n.nativePath)}catch(e){if(errorCode(e)!==`ENOENT`||(await classifyMissingSettingsFile(n.nativePath)).unread!==`absent`)throw e}return{file:n,sha:(0,import_node_crypto6.createHash)(`sha256`).update(n?.nativePath??``).update(r==null?`\0absent`:`\0present`).update(r??Buffer.alloc(0)).digest(`hex`),values:r==null?{}:parseTomlBuffer(r)??{}}}function snapshotSettingValue(e,n){let r;for(let[a,o]of entries(e.values))getSettingByNameOrKey(a)===n&&(r=n.normalizeValue(o));return r}function patchSettingsSnapshot(e,n){let r={...e.values};for(let[e,a]of entries(n)){let n=getSettingByNameOrKey(e);for(let a of Object.keys(r))(a===e||n!=null&&getSettingByNameOrKey(a)===n)&&delete r[a];a!=null&&(r[e]=a)}return r}var readSettings=lazy2(async()=>{await readAndMergePsEnv.refresh();for(let e of allSettings())e.refreshEnvValue();await readSystemSettings(),await maybeResetLibraryDir(),librarySettingsFile()!=null&&await readLibrarySettings(),handleMetaSettings([])},minuteMs);async function readSystemSettings(e=systemSettingsFile()){if(setSettingsDefaults(),e==null)logger50().warn(`readSystemSettings(): systemSettingsFile() returned null: no-op`);else return _readSettings(BaseFile.for(e),persistedSystemSettings())}function onSettingsChange2(){readSettings.unset()}later(()=>{ee().on(`clearCache`,onSettingsChange2),ee().on(`settingsChanged`,onSettingsChange2),Settings2.libraryDir.watchLater(onSettingsChange2)});var versionForSettings=lazy2(()=>baseVersion());function preservedToml(e){let n={},r={};for(let[a,o]of entries(e))typeof o==`object`&&o&&!Array.isArray(o)&&!(o instanceof Date)||Array.isArray(o)&&o.some(e=>typeof e==`object`&&!!e)?r[a]=o:n[a]=o;return[...entries(n).map(([e,n])=>`${/^[\w-]+$/.test(e)?e:JSON.stringify(e)} = ${escapeSmartQuotes(import_toml2.stringify.value(n))}`),(0,import_toml2.stringify)(r)].join(`
|
|
518
|
+
`)}async function _writeToml_(e,n,r,a,o=[],s=!1){let c=[padding(`#`,80)],l=!s||Object.hasOwn(r.values,`version`);c.push(...wrapComments(``,`Howdy!`,``,`These are ${n[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.`,``,...l?[`This is the version of PhotoStructure that wrote this file--please don't edit the following line.`]:[])),l&&c.push(...stringifyToml({version:s?r.values.version:versionForSettings()})),c.push(``,``);let u={...a};delete u.version;let d=``;for(let e of n){let n=`${capitalize(e.categoryType)}.${e.category.toLowerCase()}`;if(n!==d){d=n;let r=SettingCategoryDescriptions[e.category],a=e.categoryType===`library`?`(stored per-library)`:`(system-wide)`,o=`${e.category} settings ${a}`;c.push(``,padding(`#`,78),`#`,`# ${o}`,`#`,...wrapComments(r),`#`,``)}let s=!o.includes(e)&&(e===Settings2.authMode||a==null&&e===Settings2.libraryDir);if(c.push(...e.toTomlLines({includeValue:a==null&&!s})),a!=null)for(let[n,r]of entries(u))getSettingByNameOrKey(n)===e&&(s||c.push(`${n} = ${escapeSmartQuotes(import_toml2.stringify.value(r))}`),delete u[n]);if(s)for(let[n,a]of entries(r.values))getSettingByNameOrKey(n)===e&&c.push(`${JSON.stringify(n)} = ${escapeSmartQuotes(import_toml2.stringify.value(a))}`);c.push(``,``)}a!=null&&c.push(preservedToml(u)),await e.writeText_(`
|
|
519
|
+
`+c.map(trimRight).join(`
|
|
520
|
+
`)+`
|
|
521
|
+
|
|
522
|
+
`),ee().emitThrottled(`settingsChanged`)}async function writeSettingsFileContents_(e,n,r,a,o){await _writeToml_(e,n,r,a,o,!0)}var lastLibrarySettingsReadStatus;function librarySettingsReadStatus(){return lastLibrarySettingsReadStatus}async function readLibrarySettings(e){let n=await readSettingsImport_(librarySettingsFile(e),persistedLibrarySettings());return lastLibrarySettingsReadStatus=n.unread??`readable`,n.unread===`absent`&&clearAbsentFileInputs(persistedLibrarySettings()),n.settings}var UnreadableSettingsFileMsg=`Cannot read settings file: no settings were loaded from it`;async function _readSettings(e,n){return(await readSettingsImport_(e,n)).settings}async function readSettingsImport_(e,n){if(e==null)return logger50().info(`_readSettings(null): no-op`),absentSettingsFile();let r=logger50().child(`.importFileSettings(`+e.nativePath+`)`);try{let a=await importFileSettings_(e,n);return a.unread===`absent`?r.debug(`No settings file to read`,{file:e.nativePath}):a.unread===`unreadable`?r.warn(UnreadableSettingsFileMsg,{file:e.nativePath,warnings:a.warnings}):isNotEmpty(a.warnings)&&r.info(`Problems during import`,a.warnings),a}catch(n){return r.warn(UnreadableSettingsFileMsg,{file:e.nativePath,code:errorCode(n),error:tomlErrorForLog(n)}),{settings:[],unread:`unreadable`}}}function absentSettingsFile(){return{settings:[],unread:`absent`}}function unreadableSettingsFile(e){return{settings:[],unread:`unreadable`,warnings:[`Cannot read: `+e]}}async function classifyMissingSettingsFile(e){let n;try{n=await(0,import_promises28.lstat)(e)}catch(n){let r=errorCode(n);if(r!==`ENOENT`)return unreadableSettingsFile(r??errorToS2(n));for(let n of ancestorG(e))try{let e=await(0,import_promises28.lstat)(n);if(e.isSymbolicLink())try{e=await(0,import_promises28.stat)(n)}catch(e){let n=errorCode(e);return unreadableSettingsFile(n===`ENOENT`?`broken symlink`:n??errorToS2(e))}return e.isDirectory()?absentSettingsFile():unreadableSettingsFile(`ENOTDIR`)}catch(e){let n=errorCode(e);if(n!==`ENOENT`)return unreadableSettingsFile(n??errorToS2(e))}return absentSettingsFile()}return n.isSymbolicLink()?unreadableSettingsFile(`broken symlink`):absentSettingsFile()}async function importFileSettings_(e,n){let r=logger50().child(`.importFileSettings_(`+e.nativePath+`)`),a;try{a=await e.stat_()}catch(n){let r=errorCode(n);return r===`ENOENT`?await classifyMissingSettingsFile(e.nativePath):unreadableSettingsFile(r??errorToS2(n))}if(a.size===0)return clearAbsentFileInputs(n),{settings:[],warnings:[`Cannot read empty file`]};let o=await readTomlFile_(e);if(o==null)return clearAbsentFileInputs(n),{settings:[],warnings:[`No settings found`]};let s=[],c=[],l=n==null?void 0:new Set(n),u=new Set,d=compact(entries(o).map(([e,n])=>{if(e===`version`)return;let r=getSettingByNameOrKey(e);if(r==null){let n=whyRemovedSetting(e);if(n!=null){let r=`Setting "${e}" was removed: ${n}. The value is ignored and the line can be deleted from settings.toml.`;s.push(r),c.push(r)}else s.push(`Failed to import "${e}"${mapOr(ciSettings().lookupNearest(e),e=>`: did you mean "${e.key}"?`,``)}`)}else if(l!=null&&!l.has(r))s.push(`Setting "${e}" belongs in the ${r.categoryType} settings file and was ignored`);else if(blank(n)&&r.opts.blankIsValue!==!0)u.add(r),r.fileValue=void 0,s.push(`Blank value for "${r.name}" is ignored; the line has no effect. Remove it or give it a value.`);else{u.add(r);let e=r.whyInvalidValue(n);if(e!=null)r.noteInvalidFileInput(),s.push(r.shouldRedactInvalidValue()?`Invalid value for setting "${r.key}"`:e);else return r.fileValue=n,r}}));return clearAbsentFileInputs(n,u),r.info(`loaded`,{settings:settingsToLogObj(d),warnings:toNotEmpty(s)}),await handleDeprecatedSettings(),handleMetaSettings(d),s.push(...settingsValueWarnings(d)),{settings:d,warnings:s,removed:c}}function clearAbsentFileInputs(e,n=new Set){for(let r of e??[])n.has(r)||(r.fileValue=void 0)}var UnclearableSettings=defer(()=>new Set([Settings2.noNetwork,Settings2.httpPort,Settings2.license,Settings2.logStdout,Settings2.logLevel].map(e=>e.key)));async function maybeResetLibraryDir(){isTrue(process.env[PS_RESET_LIBRARY_DIR])&&!isChildProcess()&&(logger50().info(`PS_RESET_LIBRARY_DIR: clearing libraryDir`),delete process.env[PS_RESET_LIBRARY_DIR],Settings2.libraryDir.deleteFromEnv(),Settings2.libraryDir.refreshEnvValue({broadcastChange:!0}),Settings2.libraryDir.unsetFileValue(),systemSettingsFile()!=null&&await setPersistedLibraryDir_(void 0),logger50().info(`PS_RESET_LIBRARY_DIR: done`,{libraryDirValue:Settings2.libraryDir.value}))}function wrapComments(...e){return flatten(e.map(e=>wrap(e,WrapComments)))}var import_node_util14=require("node:util"),procColors=defer(()=>[{re:/web/,fn:green},{re:/worker/,fn:cyan},{re:/sync/,fn:blue},{re:/log/,fn:blueBright},{re:/info/,fn:blueBright},{re:/main/,fn:yellow},{re:/test/,fn:blueBright},{re:/billing/,fn:cyan}]);function colorProcessName(e){if(blank(e))return``;let n=procColors().find(n=>n.re.test(e));return n==null?e:bgBlack(n.fn(e))}var ColoredLogFormatter=class{constructor(e={}){this._inspectOptions=e,this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:null,processName,...this._inspectOptions},isTest()&&(this.inspectOptions.breakLength=255),this.inspectOptions.processName.watch(e=>this.defaultProcessName=colorProcessName(e))}_inspectOptions;logLevels={trace:`trace`,debug:darkGrey(`debug`),info:cyan(`info_`),warn:yellowBright(`warn_`),error:redBright(`error_`),fatal:bgRedBright(black(`fatal`))};inspectOptions;defaultProcessName;formatMeta(e){if(e==null)return;let n=prepMeta(e);return n==null?void 0:(0,import_node_util14.inspect)(n,this.inspectOptions)}colorContext(e){if(!logFilter().highlight(e))return blue(e);let n=e.match(/[^.\w-]/);if(!gt0(n?.index))return blue(e);let r=e.slice(0,n.index),a=e.slice(n.index);return yellow(r)+blue(a)}formatLogEntry(e){return compactBlanks([darkGrey(new Date(e.ts).toISOString()),e.from==null?this.defaultProcessName:colorProcessName(e.from),this.logLevels[e.l],this.colorContext(e.ctx),e.msg,this.formatMeta(e.meta)]).map(e=>toS(e)).join(` `)}format(e,n,r,a){return this.formatLogEntry({ts:Date.now(),l:e,from:processName(),ctx:n,msg:r,meta:a})}},import_node_net=require("node:net"),defaultFrom=defer(()=>({_service:serviceName(),_pid:process.pid}));later(()=>serviceName.watchLater(()=>defaultFrom.reset()));function extractFrom(e){if(e==null)return defaultFrom();{let[n,r]=e.split(`-`,2);return blank(n)?defaultFrom():{_service:n,_pid:toInt(r)}}}var GelfLogFormatter=class{formatLogEntry(e){return stringify({version:`1.1`,level:level2syslog(e.l)??7,host:SimpleAppName,timestamp:e.ts/1e3,short_message:stripAnsiEsc(uniq(compactBlanks([e.ctx,e.msg])).join(` `)),full_message:map(e.meta?.error,errorToVerbose),...extractFrom(e.from),...fromEntries(entries(prepMeta(e.meta,3)??{}).map(([e,n])=>e===`id`?void 0:[`_`+e,stringify(n)]))})}format(e,n,r,a){return this.formatLogEntry({ts:Date.now(),l:e,ctx:n,msg:r,meta:a})}},LogLevelRe=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i,LogFilterImpl=class{constructor(e=LoggingSettings.logLevel){this.setting=e,e.watch(()=>this.#t.refresh()),this.#t()}setting;silent=!1;defaultLevelIndex;#e=[];#t=lazy2(()=>{this.#e.length=0;let e=this.setting.valueOrDefault;this.defaultLevelIndex=LogLevels.indexOf(e)??LogLevels.indexOf(this.setting.defaultValue)??LogLevels.indexOf(LogLevels.warn);let n=compactBlanks(e.split(/[,;]/));for(let r of n){let n=LogLevelRe.exec(r.trim());if(n==null)isProd()&&console.error(`LogFilterImpl: Ignoring '`+r+`' from `+e);else{let e=toS(n[1]).toLowerCase(),r=levelIndex(n[2]);blank(e)?this.defaultLevelIndex=r:this.#e.push({prefix:e,levelIndex:r})}}});#n(e){if(e==null||this.#e.length===0||blank(e))return;let n=toS(e).toLowerCase();for(let e of this.#e)if(n.startsWith(e.prefix))return e;for(let e of this.#e)if(n.includes(e.prefix))return e}enabled(e,n){if(this.silent)return!1;let r=levelIndex(e);if(n!=null){let e=this.#n(n);if(e!=null)return r<=e.levelIndex}return r<=this.defaultLevelIndex}highlight(e){let n=this.#n(e);return n!=null&&n.levelIndex>=this.defaultLevelIndex}},consoleLogger2=lazy2(()=>mkConsoleLogger(`log.LogBroadcaster`)),nul=`\0`,HostPortRE=/^(?<host>[^:]+):(?<port>\d+)$/;function parseLogServerSetting(){let e=LoggingSettings.logServer.valueOrDefault?.match(HostPortRE)?.groups,n=e?.host,r=toInt(e?.port);return!blank(n)&>0(r)?{host:n,port:r}:void 0}var logBroadcaster=lazy2(()=>{let e=parseLogServerSetting();if(e==null)LoggingSettings.logServer.hasValue()&&consoleLogger2().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${stringify(LoggingSettings.logServer.valueOrDefault)})`);else return new LogBroadcaster(e.host,e.port)});later(()=>LoggingSettings.logServer.watchLater(()=>logBroadcaster.unset()));var LogBroadcaster=class extends EndableWrapper{constructor(e,n){super(`log.LogBroadcaster(`+e+`:`+n+`)`,()=>this.socket?.end(),EndableRanks.logtail),this.host=e,this.port=n,this.#e()}host;port;logFormatter=new GelfLogFormatter;logFilter=new LogFilterImpl(LoggingSettings.logServerLevel);socket;isEnabled(e,n){return this.logFilter.enabled(e,n)}log(e,n,r,a){this.isEnabled(e,n)&&this._logEntry({ts:Date.now(),l:e,ctx:n,msg:r,meta:a})}_logEntry(e){try{let n=this.socket;n==null?this.#e():n.write(this.logFormatter.formatLogEntry(e)+nul)}catch(n){consoleLogger2().warn(`Failed to write log entry to socket`,{logEntry:e,error:n})}}maybeFlush(){let e=new Latch;return this.socket?.write(``,()=>e.resolve()),e.promise}#e=rateLimited({f:async()=>{try{let e=this.socket=(0,import_node_net.createConnection)({host:this.host,port:this.port});e.on(`close`,()=>{this.socket=void 0}),e.on(`error`,n=>{consoleLogger2().warn(`Error from logging server`,n);try{e.end()}catch{}})}catch(e){consoleLogger2().warn(`Failed to connect to the log server`,e)}},minCallDelayMs:minuteMs,name:`#mkSocket`})},import_node_fs28=__toESM(require("node:fs")),import_node_path49=require("node:path"),CircularBuffer=class{#e;#t;#n=0;#r=0;constructor(e){if(e<0)throw Error(`Capacity must be non-negative`);this.#e=e,this.#t=Array(e)}get capacity(){return this.#e}set capacity(e){if(e<0)throw Error(`Capacity must be non-negative`);if(e===this.#e)return;let n=e===0?[]:[...this].slice(-e);this.#t=Array(e);for(let e=0;e<n.length;e++)this.#t[e]=n[e];this.#e=e,this.#n=0,this.#r=n.length}get size(){return this.#r}push(e){if(this.#e===0)return;let n=(this.#n+this.#r)%this.#t.length,r=this.#r>=this.#t.length?this.#t[n]:void 0;return this.#t[n]=e,this.#r++>=this.#t.length&&(this.#r=this.#t.length,this.#n=(this.#n+1)%this.#t.length),r}*[Symbol.iterator](){for(let e=0;e<this.#r;e++){let n=(this.#n+e)%this.#t.length;yield this.#t[n]}}forEach(e){for(let n=0;n<this.#r;n++){let r=(this.#n+n)%this.#t.length;e(this.#t[r],n)}}map(e){let n=[];return this.forEach(r=>n.push(e(r))),n}clear(){this.#t.length=0,this.#t.length=this.capacity,this.#n=0,this.#r=0}toArray(){return this.map(e=>e)}},DefaultLogFlushMs=750;function defaultLogWriterOptions(){return{errorLogger:ConsoleLogger.instance(),flushEveryMs:DefaultLogFlushMs,processName,logFilter,flightRecorderCapacity:LoggingSettings.logFlightRecorderCapacity.valueOrDefault,flightRecorderMinLevel:LoggingSettings.logFlightRecorderMinLevel.valueOrDefault,flightRecorderTriggerLevel:LoggingSettings.logFlightRecorderTriggerLevel.valueOrDefault,maxLinesPerFile:LoggingSettings.logMaxLinesPerFile.valueOrDefault}}var LogFileWriter=class extends EndableInterval{constructor(e,n={}){super({name:`LogWriter(`+e+`)`,callback:()=>this.#d(),intervalMs:DefaultLogFlushMs,rank:EndableRanks.logger,unref:!0,onEnd:()=>this.#u()}),this.logDir=e,this.logOpts={...defaultLogWriterOptions(),...n},gt0(this.logOpts.flushEveryMs)?this.setIntervalMs(this.logOpts.flushEveryMs):LoggingSettings.logFlushMs.watch(this.setIntervalMs),this.flightRecorderTriggerLevel=levelIndex(this.logOpts.flightRecorderTriggerLevel),this.flightRecorderMinLevel=levelIndex(this.logOpts.flightRecorderMinLevel),this.#t=new CircularBuffer(this.logOpts.flightRecorderCapacity),this.maxLinesPerFile=this.logOpts.maxLinesPerFile}logDir;logOpts;pendingWrites=[];#e=new Set;_nextForcedRotateTs=nextMidnightTs();_linesSinceRotate=0;_logfile;_startIndex=0;maxLinesPerFile;#t;flightRecorderMinLevel;flightRecorderTriggerLevel;#n=0;#r;#i;#a=!1;endTimeoutMs=15*secondMs;get flushEveryMs(){return this.opts.intervalMs}get flightRecorderCapacity(){return this.#t.capacity}set flightRecorderCapacity(e){let n=this.#t.size-e;if(n>0){let e=0;for(let r of this.#t){if(e++>=n)break;this.#o(r)}}this.#t.capacity=e}#o(e){this.#n++,this.#r??=e.ts,this.#i=e.ts}setIntervalMs=e=>{let n=super._setIntervalMs(e);return this.#d(),n};toJSON(){return{logDir:this.logDir}}isEnabled(e,n){return this.logOpts.logFilter().enabled(e,n)}log(e,n,r,a){let o={ts:logTs(),l:e,from:this.logOpts.processName(),ctx:n,msg:r,meta:a},s=this.isEnabled(e,n),c=levelIndex(e);if(!s&&!this.logOpts.logFilter().silent&&c>=this.flightRecorderTriggerLevel&&c<=this.flightRecorderMinLevel){let e=this.#t.push(o);e!=null&&this.#o(e)}s&&(c<=this.flightRecorderTriggerLevel&&this.#s(),this._logEntry(o))}#s(){let e=this.#n;if(e>0){let n=this.#r,r=this.#i;this.#c({ts:r,l:`info`,from:this.logOpts.processName(),ctx:`LogFileWriter.flightRecorder`,msg:`Flight recorder overflow: ${e} entries dropped, spanning ${((r-n)/secondMs).toFixed(1)}s`,meta:{dropped:e,firstTs:n,lastTs:r,capacity:this.#t.capacity}})}this.#n=0,this.#r=void 0,this.#i=void 0;for(let e of this.#t)this.#c(e);this.#t.clear()}_logEntry(e){this.ended?levelIndex(e.l)<=levelIndex(`warn`)&&this.logOpts.errorLogger._logEntry(e):this.#c(e)}#c(e){this.#a||(e.meta!=null&&(e.meta=prepMeta(e.meta)),(e.l===`error`||e.l===`fatal`)&&(e.meta==null?e.meta={caller:prepMeta(shortStack())}:isRecord(e.meta)&&e.meta.caller==null&&(e.meta={...e.meta,caller:prepMeta(shortStack())})),e.l===`fatal`&&this.#l(e),this.pendingWrites.push(e))}async#l(e){let n=new Latch;this.#e.add(n);try{let n=datedLogDir(this.logDir),r=this.logOpts.processName(),a=e.ts,o=`fatal-${r}-${TokenRadix.encode(a)}.jsonl`;await writeFile_((0,import_node_path49.join)(n,o),stringify(e)+`
|
|
523
|
+
`)}catch(n){this.logOpts.errorLogger.log(`error`,`LogFileWriter.#writeFatalEntry`,`Failed to write fatal error file`,{error:n,entry:e})}finally{n.resolve(),this.#e.delete(n)}}#u=defer(async()=>{this.#s(),this.#a=!0,await this.#d(),await this.#h(),await Promise.all(this.#e),LoggingSettings.logFlushMs.unWatch(this.setIntervalMs)});maybeFlush(){return this.#d.ifIdle()}#d=serialized(async()=>{let e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.#f()&&(await this.#h(),await this.#p(),this._nextForcedRotateTs=nextMidnightTs());let n=this.#m(e);if(n<=0)break;e.splice(0,n)}});onError(e,n){let r=isIgnorableError(n)===!0?`debug`:`error`;this.logOpts.errorLogger.log(r,`Caught error from `+e,n)}#f(){return this._logfile==null||this._linesSinceRotate>=this.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}async#p(){let e=mkValidFilename(this.logOpts.processName()),n=await ensureNewNativePath_({nativePath:(0,import_node_path49.join)(datedLogDir(this.logDir),e+`.jsonl`),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),r=import_node_fs28.default.createWriteStream(n).on(`error`,e=>{this.onError(`file write stream`,e),this.#h()});this._logfile={stream:r,nativePath:n}}#m(e){let n=this._logfile?.stream;if(n==null)return this.onError(`LogFileWriter.#writeBatch()`,Error(`no open stream after rotation`)),e.length;let r=clamp(0,e.length,this.maxLinesPerFile-this._linesSinceRotate),a=e.slice(0,r);return this._linesSinceRotate+=a.length,n.write(a.map(e=>stringify(e)+`
|
|
524
|
+
`).join(``)),a.length}async#h(){let e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,e!=null)try{await disposeStream(e.stream,{force:!1})}catch(e){this.onError(`#closeTarget()`,e)}}},readme=`PhotoStructure writes files with logging entries to dated subdirectories.
|
|
525
|
+
|
|
526
|
+
Although you _can_ directly read these .json files, you don't need to!
|
|
527
|
+
|
|
528
|
+
Use PhotoStructure's "logcat" and "logtail" tools to merge, chronologically
|
|
529
|
+
sort, and pretty-print these files.
|
|
530
|
+
|
|
531
|
+
See https://photostructure.com/server/tools/#logging for details.
|
|
532
|
+
`;async function setupLogger(){await readSystemSettings(),logFilter()instanceof LogFilterImpl||logFilter.set(new LogFilterImpl),setupLogFormatter();let e=LoggingSettings.tailLogs.valueOrDefault&&canTailLogs();e&&await LogTail.instance();let n=logDir(),r=rootLoggers().find(e=>e instanceof LogFileWriter);r!=null&&r.logDir===n||(r?.end(),filterInPlace(rootLoggers(),e=>!(e instanceof LogFileWriter)),writeTextfile_((0,import_node_path50.join)(n,`README.txt`),readme).catch(()=>null),rootLoggers().push(new LogFileWriter(n))),!e&&LoggingSettings.logStdout.valueOrDefault?pushNotSame(rootLoggers(),ConsoleLogger.instance()):filterInPlace(rootLoggers(),e=>!(e instanceof ConsoleLogger)),filterInPlace(rootLoggers(),e=>!(e instanceof LogBroadcaster));let a=logBroadcaster();a!=null&&rootLoggers().push(a),e||logStartup()}function setupLogFormatter(){let e=LoggingSettings.logColor.valueOrDefault;setColorEnabled(e),DefaultLogFormatter.set(e?new ColoredLogFormatter:new PlaintextLogFormatter)}var CliDesc=Object.freeze({auth:`Configure or recover this library's access from the local machine. On Node and Docker, a setup link opens a page in your browser to choose the sign-in mode: PhotoStructure prints one at start while no mode is saved, and setup-link prints one at any time.`,main:`PhotoStructure's main process manager. Runs and manages web and sync services.`,desktop:`PhotoStructure for Desktops. Manages web and sync services.`,fix:`PhotoStructure's library settings and database check and repair tool.`,info:`PhotoStructure's configuration, file metadata and aggregation diagnostics tool.`,doctor:`Report PhotoStructure's health checks.`,list:`List items in a PhotoStructure Library.`,logcat:`Chronologically sort and pretty-print PhotoStructure's log files.`,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. For more details see https://photostructure.com/tools`,sync:`PhotoStructure's directory synchronization service. Automatically started by main, but can be run manually. For more details see https://photostructure.com/go/sync`,"docker-env":`PhotoStructure for Docker's startup environment resolver. For internal use.`,test:`Test harness. For internal use.`,worker:`PhotoStructure's worker process. For internal use.`}),import_node_process25=require("node:process"),EditionType=lazy2(()=>isElectron()?`Desktops`:isDocker()?`Docker`:`Servers`),EditionName=lazy2(()=>SimpleAppName+` for `+EditionType());function cliWrap(e,n){return wrap(e,{maxLineLen:n?.maxLineLen??toInt(import_node_process25.env.maxLineLen)??import_node_process25.stdout.columns??75,prefix:n?.prefix??``})}function cliWrapVersion(){return EditionName().replace(SimpleAppName,SimpleAppName+`®`)+` v`+version}function cliWrapWithFooter(...e){return joinLines(...cliWrap([...e,``,`Copyright \xA9 2017-${gitDate.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/`,``]))}function addHelpFooter(e){return e.addHelpText(`afterAll`,cliWrapWithFooter())}var import_node_process26=__toESM(require("node:process")),groupids=lazy2(()=>uniq([import_node_process26.default.getegid?.(),import_node_process26.default.getgid?.(),passwdEntry()?.gid,...import_node_process26.default.getgroups?.()??[]]).filter(gte0)),groupid=lazy2(()=>groupids()[0]);function whyMismatched(e,n,r){let a=toGt0(process.env[n]);return a!=null&&!r.includes(a)?`WARNING: ${e} is running as ${r} but $${n}=${a}`:void 0}function whyUidGidMismatched(){if(!isDocker())return;let e=compactBlanks([whyMismatched(`user id`,`PUID`,userids()),whyMismatched(`group id`,`PGID`,groupids())]);return e.length===0?void 0:e}var verifyUidGid=lazy2(()=>{isDocker()&&map(whyUidGidMismatched(),e=>console.log([``,...e,`This may result in file permission issues!`,`See https://photostructure.com/go/puid for details.`,``].join(`
|
|
533
|
+
`)))});function resetDirsAfterEnvMerge(){resetConfigDir(),resetCacheDir(),logDir.unset()}var CLI=class{constructor(e,n,r=new import_commander.Command){this.serviceName=e,this.additionalDescription=n,this.cmd=r,process.on(`SIGHUP`,()=>exit({reason:`SIGHUP`,status:0})),process.on(`SIGINT`,()=>exit({reason:`SIGINT`,status:0})),process.on(`SIGTERM`,()=>exit({reason:`SIGTERM`,status:0}))}serviceName;additionalDescription;cmd;#e=[];setup=defer(async()=>{handleDeprecatedEnv(),setServiceName(this.serviceName),await setupLogger(),verifyUidGid()});add(...e){return this.#e.push(...e),this}async parse(e=process.argv,n){addHelpFooter(this.cmd).description(cliWrap(CliDesc[this.serviceName]+mapNotBlankOr(this.additionalDescription,e=>`
|
|
534
|
+
|
|
535
|
+
`+e,()=>``)).join(`
|
|
536
|
+
`));for(let e of this.#e)await e.beforeParse(this.cmd);this.cmd.version(isTest()?`1.2.3-test`:cliWrapWithFooter(cliWrapVersion()),`-V, --version`,`Output version information (spoiler: it's `+(isTest()?`1.2.3-test)`:version)),this.cmd.parse(e,n??{from:isMainElectron?`electron`:`node`});let r=this.cmd.opts();if(r.help!==!0&&r.version!==!0){let e=this.cmd.opts();isChildProcess()||(await readAndMergePsEnv(),resetDirsAfterEnvMerge());for(let n of this.#e)await n.afterParse?.(e);await this.setup()}return this.cmd}},logger51=lazy2(()=>mkLogger(`dir.IsLibraryDir`));function pathToS(e){return e==null?`(null)`:stringify(toNativePath_(e))}async function whyNotLibraryDir(e){return logger51().tap({msg:`whyNotLibraryDir(`+e+`)`,result:await _whyNotLibraryDir(e)})}async function _whyNotLibraryDir(e){if(blank(e))return`blank path`;let n=toNativePath_(e);try{let e=await stat_(n);if(e==null||!e.isDirectory())return`not a directory`}catch(e){return`cannot read: `+errorToS2(e)}let r=libraryDataDirPosixFile(n);if(!0!==await r?.isDirectory({refresh:!0,logLevel:`trace`}))return`library data directory, `+pathToS(r)+`, is not a directory`;let a=librarySettingsFile(n)?.clear();if(a==null||!await a.isNonEmptyFile())return`library settings, `+pathToS(a)+`, is empty or missing`;let o=pathToDb(r,`models`)?.clear();if(o==null||!await o?.isNonEmptyFile(KB))return`library database, `+pathToS(o)+`, is empty or missing`;let s=libraryPreviewsDirPosixFile(n);if(!0!==await s?.isDirectory({refresh:!0,logLevel:`trace`}))return`library previews, `+pathToS(s)+`, is empty or missing`}var import_node_path51=require("node:path");function writeLibraryAuthMode_(e,n){return writeLibrarySetting_(e,Settings2.authMode,n)}async function writeLibrarySetting_(e,n,r){let a=PosixFile.for((0,import_node_path51.join)(e,`.photostructure`,SettingsToml)),o;if(await a.applyWip_({timeoutMs:ShortCommandTimeoutMs,skipFsLock:!1,preserveDestOnError:!0,fn_:async e=>{let s=await readSettingsFileSnapshot_(a);return o=await writeSettingsReplacement_(a,e,async()=>{await writeSettingsFileContents_(e,persistedLibrarySettings(),s,patchSettingsSnapshot(s,{[n.name]:r}),[n])},!0),!0},beforeRename_:()=>o()})!==!0)throw Error(`Could not acquire the library settings lock`)}async function writeSystemLibraryIfMissing_(e,n){let r=PosixFile.for(e),a;if(await r.applyWip_({timeoutMs:ShortCommandTimeoutMs,skipFsLock:!1,preserveDestOnError:!0,fn_:async e=>{let o=await readSettingsFileSnapshot_(r);return snapshotSettingValue(o,Settings2.libraryDir)==null?(a=await writeSettingsReplacement_(r,e,async()=>{await writeSettingsFileContents_(e,persistedSystemSettings(),o,patchSettingsSnapshot(o,{libraryDir:n}),[Settings2.libraryDir])}),!0):NoOp2},beforeRename_:()=>a()})==null)throw Error(`Could not acquire the system settings lock`)}var HostSignInSettingNames=[`externalOrigin`,`trustProxy`],LibrarySignInSettingNames=[...keys(EmailSettings),...keys(OidcSettings)],SignInSettingNames=[...HostSignInSettingNames,...LibrarySignInSettingNames];function pick2(e,n){let r=Object.fromEntries(Object.entries(e).filter(([e])=>n.includes(e)));return Object.keys(r).length===0?void 0:r}async function writeSignInSettings_({configRoot:e,libraryRoot:n},r){let a=pick2(r,LibrarySignInSettingNames);a!=null&&await writeSettingsPatch_(PosixFile.for((0,import_node_path51.join)(n,`.photostructure`,SettingsToml)),persistedLibrarySettings(),a,!0,`Could not acquire the library settings lock`);let o=pick2(r,HostSignInSettingNames);o!=null&&await writeSettingsPatch_(PosixFile.for((0,import_node_path51.join)(e,SettingsToml)),persistedSystemSettings(),o,!1,`Could not acquire the system settings lock`)}async function writeSettingsPatch_(e,n,r,a,o){let s=Object.keys(r).map(e=>Settings2[e]),c;if(await e.parent().mkdirp_(),await e.applyWip_({timeoutMs:ShortCommandTimeoutMs,skipFsLock:!1,preserveDestOnError:!0,fn_:async o=>{let l=await readSettingsFileSnapshot_(e);return c=await writeSettingsReplacement_(e,o,()=>writeSettingsFileContents_(o,n,l,patchSettingsSnapshot(l,r),s),a),!0},beforeRename_:async()=>{await c?.()}})!==!0)throw Error(o)}var import_node_net3=require("node:net"),import_node_os16=require("node:os"),myIpAddresses=lazy2(()=>uniq(compactBlanks(flatten(values((0,import_node_os16.networkInterfaces)())).map(e=>e.address))),minuteMs),networkMacAddresses=lazy2(()=>uniq(compactBlanks(flatten(values((0,import_node_os16.networkInterfaces)())).map(e=>e.mac))).filter(e=>e!==`00:00:00:00:00:00`),minuteMs);function myExternalIpAddresses(){return myIpAddresses().filter(e=>!isLoopback2(e))}function myExternalIp4Addresses(){return myExternalIpAddresses().filter(e=>!e.includes(`:`))}var logger52=lazy2(()=>mkLogger(`net.ip`)),loopbackPatterns=[/^(?:::ffff:)?127(?:\.\d{1,3}){3}$/i,/^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/i,/^::1$/];function isLoopback2(e){return notBlank(e)&&(parseQuad(e)?.[0]===127||loopbackPatterns.some(n=>n.exec(e)!=null))}function parseQuad(e){let n=e.split(`.`).map(e=>toIntWithin(toFloat(e,{strict:!0}),0,255));return n.length!==4||n.some(e=>e==null)?void 0:n}var import_node_net2=require("node:net"),import_node_url=require("node:url");function formatUrl({protocol:e,hostname:n,port:r,pathname:a=`/`,search:o=``,hash:s=``}){let c=new import_node_url.URL(`http://a`);if(c.protocol=e,c.hostname=(0,import_node_net2.isIP)(n)===6?`[${n}]`:n,mapGt0(r,e=>c.port=String(e)),mapNotBlank(a,e=>c.pathname=e),o instanceof URLSearchParams)for(let[e,n]of o.entries())c.searchParams.set(e,n);else notBlank(o)&&(c.search=o);return mapNotBlank(s,e=>c.hash=e),c}var logger53=defer(()=>mkLogger(`core.SafeURLs`));function libraryUrl(e={}){return logger53().tap({msg:`libraryUrl()`,result:formatUrl({pathname:`/`,...e,protocol:`http`,hostname:Settings2.localhost.valueOrDefault,port:Settings2.httpPort.valueOrDefault}).toString(),meta:e})}var baseLibraryUrl=lazy2(()=>libraryUrl()),splashLibraryUrl=lazy2(()=>libraryUrl({pathname:`/splash`})),aboutLibraryUrl=lazy2(()=>libraryUrl({pathname:`/about`})),plansLibraryUrl=lazy2(()=>libraryUrl({pathname:`/plans/`}));function clearLibraryUriCache(){baseLibraryUrl.unset(),splashLibraryUrl.unset(),aboutLibraryUrl.unset(),plansLibraryUrl.unset()}later(()=>{Settings2.localhost.watchLater(clearLibraryUriCache),Settings2.httpPort.watchLater(clearLibraryUriCache)});function savedAuthModeFromSettings(){if(librarySettingsReadStatus()===`unreadable`)return{failure:`librarySettingsUnreadable`,present:!1};if(Settings2.authMode.rawEnvValue()!=null)return{present:!0,value:Settings2.authMode.getState().env};let e=Settings2.authMode.fileValue;return{present:e!=null||Settings2.authMode.hasInvalidFileInput(),value:e}}function selectedExternalOrigin(){if(Settings2.externalOrigin.rawEnvValue()!=null)return{present:!0,value:Settings2.externalOrigin.getState().env};let e=Settings2.externalOrigin.fileValue;return{present:e!=null||Settings2.externalOrigin.hasInvalidFileInput(),value:e}}function configuredBindIsLoopback(e){return e.toLowerCase()===`localhost`||(0,import_node_net3.isIP)(e)!==0&&isLoopback2(e)}function authListenerProfileFromSettings({bindHost:e=Settings2.localhost.valueOrDefault,exposeNetwork:n=Settings2.exposeNetworkWithoutAuth.valueOrDefault,originPresent:r=selectedExternalOrigin().present}={}){return n||r||!configuredBindIsLoopback(e)?AuthListenerProfiles.network:AuthListenerProfiles.loopback}function authCanonicalOriginFromSettings(e=authListenerProfileFromSettings(),{bindHost:n=Settings2.localhost.valueOrDefault,httpPort:r=Settings2.httpPort.valueOrDefault}={}){return e===AuthListenerProfiles.loopback?configuredBindIsLoopback(n)?formatUrl({hostname:n,port:r,protocol:`http:`}).origin:void 0:externalOriginDetails(selectedExternalOrigin().value).canonicalOrigin}var SignInSetupFieldError=class extends Error{constructor(e,n){super(n),this.field=e}field},MaxFieldLength=1024;function labeler(e){return(n,r)=>{let a=e[n];return a==null?r:`${r} (${a})`}}function text(e,n,r){let a=e[n];if(typeof a!=`string`)throw new SignInSetupFieldError(n,`Enter the ${r}.`);if(a.length>MaxFieldLength)throw new SignInSetupFieldError(n,`The ${r} is too long.`);return a}function required(e,n,r){let a=text(e,n,r).trim();if(a.length===0)throw new SignInSetupFieldError(n,`Enter the ${r}.`);return a}function emailSignInSettings(e,n={}){let r=labeler(n),a=e.emailSmtpPort;if(typeof a!=`number`||Settings2.emailSmtpPort.whyInvalidValue(a)!=null)throw new SignInSetupFieldError(`emailSmtpPort`,`Enter a ${r(`emailSmtpPort`,`email server port`)} from 1 to 65535.`);let o=text(e,`emailSmtpSecurity`,r(`emailSmtpSecurity`,`connection security`));if(!EmailSmtpSecurities.includes(o))throw new SignInSetupFieldError(`emailSmtpSecurity`,`Choose the ${r(`emailSmtpSecurity`,`email server's connection security`)}.`);let s=text(e,`emailSmtpUser`,r(`emailSmtpUser`,`email server username`)).trim(),c=text(e,`emailSmtpPassword`,r(`emailSmtpPassword`,`email server password`)).trim();if(c.length>0&&s.length===0)throw new SignInSetupFieldError(`emailSmtpUser`,`Enter the ${r(`emailSmtpUser`,`email server username`)} for this password.`);let l=required(e,`emailFromAddress`,r(`emailFromAddress`,`sender address`));if(Settings2.emailFromAddress.whyInvalidValue(l)!=null)throw new SignInSetupFieldError(`emailFromAddress`,`Enter only an email address as the ${r(`emailFromAddress`,`sender address`)}, with no name around it; the name goes in the ${r(`emailFromName`,`sender name`)}. Addresses at example domains such as example.com can't send mail.`);let u=text(e,`emailFromName`,r(`emailFromName`,`sender name`)).trim();return{emailSmtpHost:required(e,`emailSmtpHost`,r(`emailSmtpHost`,`email server host name`)),emailSmtpPort:a,emailSmtpSecurity:o,emailSmtpUser:blank(s)?void 0:s,emailSmtpPassword:c.length===0?void 0:c,emailFromAddress:l,emailFromName:blank(u)?void 0:u}}function oidcSignInSettings(e,n={}){let r=labeler(n),a=required(e,`oidcIssuer`,r(`oidcIssuer`,`issuer URL`)),o=whyInvalidIssuer(a);if(o!=null)throw new SignInSetupFieldError(`oidcIssuer`,`Check the ${r(`oidcIssuer`,`issuer URL`)}: ${o}.`);let s=text(e,`oidcClientSecret`,r(`oidcClientSecret`,`client secret`));if(blank(s))throw new SignInSetupFieldError(`oidcClientSecret`,`Enter the ${r(`oidcClientSecret`,`client secret`)}.`);return{oidcIssuer:a,oidcClientId:required(e,`oidcClientId`,r(`oidcClientId`,`client ID`)),oidcClientSecret:s}}var LibraryRoles=strEnum(`viewer`,`editor`,`admin`),DbClosedError=class extends Error{name=`DbClosedError`},import_sqlite2=require("@photostructure/sqlite"),seededRandom=__toESM(require("@photostructure/sqlite-seeded-random")),sqliteVec=__toESM(require("@photostructure/sqlite-vec")),import_node_os17=require("node:os"),import_node_path52=require("node:path"),NoOpLogger=new ContextualLogger(`NoOp`,()=>[]),seededRandomLoadError;function setSeededRandomLoadError(e){seededRandomLoadError=e}function isSeededRandomAvailable(){return seededRandomLoadError==null}var vec0LoadError,vec0SchemaError;function setVec0LoadError(e){vec0LoadError=e}function setVec0SchemaError(e){vec0SchemaError=e}function clearVec0SchemaError(){vec0SchemaError=void 0}function canInitializeVec0(){return vec0LoadError==null&&DbSettings.enableSimilaritySearch.valueOrDefault}function isVec0Available(){return vec0SchemaError==null&&canInitializeVec0()}var DbCacheScalar=1,BaselineOverheadMb=160;function computeDbSizingLimits(e){let n=Math.round(e/MiB),r=Math.ceil(DbCacheScalar*n),a=!1,o=DbSettings.dbMaxCacheRamPercent.valueOrDefault;if(o>0){let e=Math.round((0,import_node_os17.totalmem)()/MiB*o/100);r>e&&(r=e,a=!0)}let s=BaselineOverheadMb+n*DbCacheScalar,c=ProcessesSettings.maxMemoryErrorMultiplier.valueOrDefault,l=Math.round(s*c);return{cacheMb:r,mmapMb:n,wasCapped:a,minMaxMemoryMb:l}}function maybeRaiseMaxMemoryMb(e){let n=ProcessesSettings.maxMemoryMb.valueOrDefault;if(!(!gt0(n)||e<=n))return ProcessesSettings.maxMemoryMb.cliValue=e,{priorMb:n,raisedMb:e}}function mkdb_({nativePath:e,timeoutMs:n=DbSettings.dbBusyTimeoutMs.valueOrDefault,quiet:r=!1,synchronous:a=DbSettings.dbSynchronousMode.valueOrDefault}){e=resolve2(e),mkdirpSync_((0,import_node_path52.dirname)(e));let o=nativePathSizeSync(e),s=r?NoOpLogger:mkLogger(`db.mkdb(`+e+`)`);if(o!=null){let n=computeDbSizingLimits(o),r=Math.round(o/MiB);n.wasCapped&&s.info(`Capping cache_size at `+n.cacheMb+` MB (`+DbSettings.dbMaxCacheRamPercent.valueOrDefault+`% of RAM)`,{db:e,dbFileSizeMb:r}),n.cacheMb>DbSettings.dbCacheSizeMb.valueOrDefault&&(s.info(`Dynamically setting dbCacheSize to `+n.cacheMb+` MB`,{db:e,dbFileSizeMb:r}),DbSettings.dbCacheSizeMb.cliValue=n.cacheMb),n.mmapMb>DbSettings.dbMMapSizeMb.valueOrDefault&&(s.info(`Dynamically setting dbMMapSize to `+n.mmapMb+` MB`,{db:e,dbFileSizeMb:r}),DbSettings.dbMMapSizeMb.cliValue=n.mmapMb);let a=maybeRaiseMaxMemoryMb(n.minMaxMemoryMb);a!=null&&s.warn(`Large database: setting maxMemoryMb to `+a.raisedMb,{dbFileSizeMb:r,"Settings.maxMemoryMb":a.priorMb})}s.info(`Opening `+e+`...`);let c={allowExtension:!0,enableForeignKeyConstraints:!0};gt0(n)&&(c.timeout=Math.ceil(n));let l=(0,import_sqlite2.enhance)(new import_sqlite2.DatabaseSync(e,c));try{s.info(`Open. Setting PRAGMAs...`);for(let e of compact([`encoding = "UTF-8"`,`threads = `+maxCpus(),`page_size = `+pageSizeBytes(),`trusted_schema = 0`,`cache_size = -`+Math.round(DbSettings.dbCacheSizeMb.valueOrDefault*MiB/1024),`locking_mode = NORMAL`,`temp_store = MEMORY`,`synchronous = `+a,`case_sensitive_like = 0`,`wal_autocheckpoint = `+(isWebService()?DbSettings.dbWalAutoCheckpointPages.valueOrDefault:`0`),`auto_vacuum = NONE`,`mmap_size = `+DbSettings.dbMMapSizeMb.valueOrDefault*MiB]))s.tapThunk({msg:`PRAGMA `+e,result:()=>l.pragma(e)});if(s.tapThunk({msg:`PRAGMA journal_mode = WAL`,result:()=>enableWalMode_(l)}),s.tapThunk({msg:`PRAGMA journal_size_limit`,result:()=>setJournalSizeLimit(l)}),DbSettings.enableSimilaritySearch.valueOrDefault===!1&&!dbHasVec0VirtualTable(l))s.info(`Similarity search is disabled by settings and no vec0 tables exist; skipping sqlite-vec load`);else try{loadSqliteVec(l,s),s.info(DbSettings.enableSimilaritySearch.valueOrDefault?`Loaded sqlite-vec extension`:`Similarity search is disabled, but the database already contains a vec0 table; loading sqlite-vec so the schema stays verifiable (the index will not be updated or queried)`)}catch(e){let n=e instanceof Error?e:Error(String(e));setVec0LoadError(n),s.warn(`Failed to load sqlite-vec extension; disabling similarity search`,{error:n})}try{loadSeededRandom(l,s),s.info(`Loaded sqlite-seeded-random extension`)}catch(e){let n=e instanceof Error?e:Error(String(e));setSeededRandomLoadError(n),s.warn(`Failed to load sqlite-seeded-random extension; gallery ordering will use RANDOM()`,{error:n})}let e=l;return e.$uid=uidCounter++,e}catch(e){try{l.close()}catch(e){s.warn(`Failed to close database after setup failure`,{closeError:e})}return s.throw(`Failed to set up database`,{error:e})}}var uidCounter=0;function pageSizeBytes(){let e=DbSettings.dbPageSizeBytes.valueOrDefault;return 2**clamp(1,28,Math.round(Math.log2(e)))}function enableWalMode_(e){let n=e.pragma(`journal_mode = WAL`,{simple:!0});if(n!==`wal`)throw Error(`SQLite did not enter WAL mode: `+n)}function setJournalSizeLimit(e){e.pragma(`journal_size_limit = 0`)}function dbHasVec0VirtualTable(e){return(e.prepare(`SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND sql LIKE '%USING vec0%'`).get()?.n??0)>0}function loadSqliteVec(e,n){let r=sqliteVec.getLoadablePath();isPacked()&&r.includes(`.asar/`)&&(r=r.replace(`.asar/`,`.asar.unpacked/`));let a=(0,import_node_path52.extname)(r);(a===`.so`||a===`.dylib`||a===`.dll`)&&(r=r.slice(0,-a.length)),n.info(`Loading sqlite-vec extension`,{extensionPath:r}),e.enableLoadExtension(!0);try{e.loadExtension(r)}finally{e.enableLoadExtension(!1)}}function loadSeededRandom(e,n){let r=seededRandom.getLoadablePath();isPacked()&&r.includes(`.asar/`)&&(r=r.replace(`.asar/`,`.asar.unpacked/`)),n.info(`Loading sqlite-seeded-random extension`,{extensionPath:r}),e.enableLoadExtension(!0);try{e.loadExtension(r,`sqlite3_seededrandom_init`)}finally{e.enableLoadExtension(!1)}}var logger54=defer(()=>mkLogger(`db.SQLiteUtils`));async function retryIfSqliteBusy({fn:e,retries:n=5,closed:r,msg:a,logLevel:o=`debug`}){let s=null;for(let c=0;c<=n;c++){let l=performance.now();try{if(!0===r?.ended)throw new DbClosedError;let n=await e(c),s=roundMs(performance.now()-l);return logger54().tap({level:o,msg:a,result:n,meta:{elapsedMs:s}})}catch(e){let r=isSqliteBusyError(e);if(logger54().info(a+` failed`,{error:e,retryCount:c,isBusyError:r}),r)s=e,c<n&&await delay(100*(c+1));else throw e}}throw s}function pragma(e,n){return retryIfSqliteBusy({logLevel:`info`,msg:`PRAGMA `+n,fn:()=>e.pragma(n)})}function walCheckpointPassive(e){return pragma(e,`wal_checkpoint(PASSIVE)`)}async function optimize(e){await pragma(e,`analysis_limit=1000`);let n=e.$optimized!==!0,r=plannerStats(e);await pragma(e,`optimize`+(n?`=0x10002`:``)),e.$optimized=!0,plannerStats(e)!==r&&await retryIfSqliteBusy({logLevel:`info`,msg:`reload planner statistics on other connections`,fn:()=>e.transaction(()=>{e.exec(`CREATE VIEW ps_reload_planner_stats AS SELECT 1`),e.exec(`DROP VIEW ps_reload_planner_stats`)}).immediate()})}function plannerStats(e){return e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`).get()==null?``:JSON.stringify(e.prepare(`SELECT tbl, idx, stat FROM sqlite_stat1 ORDER BY tbl, idx`).all())}function readCacheSizeMb(e){let n=e.pragma(`cache_size`,{simple:!0}),r=e.pragma(`page_size`,{simple:!0}),a=n<0?Math.abs(n)*1024:n*r;return Math.round(a/MiB)}function readMmapSizeMb(e){let n=e.pragma(`mmap_size`,{simple:!0});return n<=0?0:Math.round(n/MiB)}var ResizeThreshold=.25;async function maybeResizeCacheAndMmap(e,n){let r=await statMaybe(n);if(!gt0(r?.size))return;let a=computeDbSizingLimits(r.size),o=a.mmapMb,s=readCacheSizeMb(e);a.cacheMb>s*(1+ResizeThreshold)&&(logger54().info(`Resizing cache_size: `+s+` → `+a.cacheMb+` MB`,{dbFileSizeMb:o}),DbSettings.dbCacheSizeMb.cliValue=a.cacheMb,e.pragma(`cache_size = -`+Math.round(a.cacheMb*MiB/1024)));let c=readMmapSizeMb(e);a.mmapMb>c*(1+ResizeThreshold)&&(logger54().info(`Resizing mmap_size: `+c+` → `+a.mmapMb+` MB`,{dbFileSizeMb:o}),DbSettings.dbMMapSizeMb.cliValue=a.mmapMb,e.pragma(`mmap_size = `+a.mmapMb*MiB));let l=maybeRaiseMaxMemoryMb(a.minMaxMemoryMb);l!=null&&logger54().info(`Adjusting maxMemoryMb health check threshold to `+l.raisedMb+` MB`,{dbFileSizeMb:o,priorMaxMemoryMb:l.priorMb})}var LibraryVersionJson=`version.json`;function libraryVersionFile(e){return libraryDataDirPosixFile(e)?.join(LibraryVersionJson)}function stampHostname(){if(!(isDocker()&&Settings2.hostname.value==null))return toNotBlank(Settings2.hostname.valueOrDefault)}var MaxDateMs=864e13;async function readLibraryVersionStamp(e){let n=await libraryVersionFile(e)?.readJson(`debug`);if(typeof n!=`object`||!n)return;let r=n,a=toNotBlank(r.version);if(a==null||!within(-MaxDateMs,MaxDateMs,r.openedAt))return;let o=toNotBlank(r.hostname);return{version:a,openedAt:r.openedAt,...o==null?{}:{hostname:o}}}async function writeLibraryVersionStamp_(e){let n=libraryVersionFile(e);if(n==null)return;let r=stampHostname(),a=await readLibraryVersionStamp(e);if(a?.version===version&&a.hostname===r)return a;let o={version,openedAt:Date.now(),...r==null?{}:{hostname:r}};return await n.writeJson_(o,{spaces:2}),o}var logger55=lazy2(()=>mkLogger(`fs.ActualPath`)),actualPathCache=lazy2(()=>new FileCache({name:`fs.Path.actualPathCache`}));function nativePathsEqlSync(e,n){if(e==null||n==null)return!1;if(e===n)return!0;try{let r=toNativePath_(e),a=toNativePath_(n);return r!=null&&a!=null&&r===a}catch{return!1}}function code(e){return blank(e)?``:"```"+toS(e).replace(/&/g,`&`).replace(/`/g,```).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`)+"```"}function codeLines(e){return toS(e).split(/\r?\n/).map(e=>code(e)).join(`[br]`)}var Critical={"desktop-thermal":!0,"library-db":!0,"library-directories":!0,"library-free-space":!0,"nodejs-version":!0,"system-temp":!0,"tools-changes":!0,"tools-exiftool":!0,"test-health-check":!0,"tools-sharp":!0,"tools-sqlite-version":!0},CriticalHealthCheckIds=Object.keys(Critical),ProcessStatusHealthCheckIds=[...CriticalHealthCheckIds,`proc-memory-use`],UnreachableCaseError=class extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name=`UnreachableCaseError`}},LibraryLocationLink={type:`link`,text:`How to change your library's location`,title:`Use Desktop’s Change Library menu, or stop PhotoStructure for Node and run --reset-library.`,url:`https://photostructure.com/guide/how-do-i-change-my-library/`,icon:`docs`,method:`GET`},DockerVolumeLink={type:`link`,text:`Read about PhotoStructure docker bind-mounts`,url:`https://photostructure.com/go/docker-volumes/`,icon:`docs`},WhatIsALibraryLink={type:`link`,text:`What's a "PhotoStructure library?"`,url:`https://photostructure.com/faq/library/`,icon:`docs`};function restartResetOrShutdownButtons(){return compact([libraryHasSettings()?{text:`Try again`,title:`Restart the current library`,type:`button`,method:`POST`,url:`/admin/restart`,icon:`refresh`}:void 0,isDocker()?{...DockerVolumeLink,method:`GET`}:LibraryLocationLink,{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`}])}var HealthCheckLevelToLogLevel={error:`error`,"no-library":`info`,pending:`debug`,installing:`info`,"stop-sync":`info`,warn:`warn`,ok:`info`,disabled:`debug`,"user-disabled":`debug`},HealthCheckLevelOrder=[`error`,`no-library`,`pending`,`stop-sync`,`warn`];function summaryForLevel(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:restartResetOrShutdownButtons()};case`no-library`:return isDocker()&&!0!==libraryDirPosixFile()?.isReadWriteExecutableSync()?{level:e,state:`failed`,msg:[`Your docker container is missing a bind mount for `+code(Settings2.libraryDir.valueOrDefault)],links:[DockerVolumeLink],buttons:[{text:`Shut down and add a bind mount for `+Settings2.libraryDir.valueOrDefault,type:`button`,method:`POST`,url:`/admin/shutdown`,icon:`power`}]}:{level:e,state:`welcome`,msg:[`No PhotoStructure library is open`],links:[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 UnreachableCaseError(e)}}var logger56=defer(()=>mkLogger(`health.SummarizeHealthChecks`)),base=lazy2(()=>({...BaseHealthCheckSummary,libraryDir:libraryHasSettings()?Settings2.libraryDir.valueOrDefault??null:null,from:{pid:process.pid,title:serviceName.prior()??process.title}}));later(()=>{Settings2.libraryDir.watchLater(()=>base.unset())});function healthCheckToggles(){return libraryHasSettings()?Settings2.skipHealthCheckIds.isFileValueOverridden()?`overridden`:`available`:`no-library`}function summaryBase(){return{...base(),healthCheckToggles:healthCheckToggles()}}function summarizeHealthChecksSync(e){let n=uniqBy(e.healthCheckResults,e=>e.id),r=n.filter(e=>e.level===`pending`),a=r.length,o=r.map(e=>e.id),s=n.length-a,c=a===0,l=uniq(compactBlanks(e.errors));if(l.length>0)return{...summaryBase(),level:HealthCheckLevels.error,settled:c,pendingIds:o,pendingCount:a,settledCount:s,ts:Date.now(),state:RunStates.failed,msg:[`Errors encountered during setup:`,l.join(`
|
|
537
|
+
---
|
|
538
|
+
`)],buttons:restartResetOrShutdownButtons()};for(let r of HealthCheckLevelOrder){if(e.skipPending&&r===HealthCheckLevels.pending)continue;let l=n.filter(e=>e.level===r);if(isNotEmpty(l)){let u=n.filter(e=>!l.includes(e)&&levelIsNotOK(e.level)),d=summaryForLevel(r),f=[...l,...u].map(e=>({id:e.id,level:e.level,...e.timedOut===!0?{timedOut:e.timedOut}:{}}));return logger56().tap({msg:`summary() found `+l.length+` `+d.level+` checks`,level:HealthCheckLevelToLogLevel[d.level],result:{...summaryBase(),level:d.level,state:d.state,links:d.links,buttons:d.buttons,settled:c,pendingIds:o,pendingCount:a,settledCount:s,linkIds:[...l.map(e=>e.id),...u.filter(e=>SyncBlockingLevels.includes(e.level)).map(e=>e.id)],contributors:f,ts:Date.now(),msg:uniq([...d.msg,...d.level===HealthCheckLevels.pending?[]:flatten([...l,...u].map(e=>e.msg[0]))])},meta:{checks:l.map(e=>e.id),args:e}})}}return logger56().tap({msg:`summary(): all are passing`,result:{...summaryBase(),level:HealthCheckLevels.ok,state:RunStates.ready,settled:c,pendingIds:o,pendingCount:a,settledCount:s,ts:Date.now(),msg:[`All critical health checks pass`,`Last updated: `+fmtDateShort(Date.now())]}})}var logger57=defer(()=>mkLogger(`health.HealthCheck`)),TimedOutResultTtlMs=minuteMs,HealthCheck=class e{constructor(n,r,a,o,s,c,l,u,d,f,h,_,y,x=commandTimeoutMs){this.section=n,this.id=r,this.pendingMsg=a,this.evalMode=s,this.ordinal=c,this.links=l,this.okLinks=u,this.warnLinks=d,this.noLibraryLinks=f,this.errorLinks=h,this.onReset=_,this.ttlMs=y,this.timeoutMs=x,this.logger=mkLogger(`health.HealthCheck.`+this.id),this.isCritical=CriticalHealthCheckIds.includes(this.id),this.sortBy=[HealthCheckSections.ordinal(this.section),c??999,this.id],this.#p=lazyAsync({desc:this.pendingMsg,later:()=>this.#y(()=>o(this.logger)),ttlMs:y}),this.isCritical&&this.#p.watchLater({onChange:e.onCriticalResult,onError:e.onCriticalResult})}section;id;pendingMsg;evalMode;ordinal;links;okLinks;warnLinks;noLibraryLinks;errorLinks;onReset;ttlMs;timeoutMs;static#e=[];static#t(){return filterInPlace(this.#e,e=>!e.isPending),this.#e}static traceLater_(e,n){let r=new Deferred2(e);r.catch(n=>{this.addError(e+`: failed: `+errorToS2(n))}),this.#t().push(r);try{return r.observe(tot(n))}catch(e){throw r.reject(e),e}}static#n=new BoundedList(10);static#r=!1;static#i=new BoundedList(10);static priorRunStates(){return this.#i.toA()}static#a=new BoundedList(100);static#o=new CountingSet;static#s=[];static all=defer(()=>Object.freeze(sortBy(this.#s,e=>e.sortBy)));static allCritical(){return this.all().filter(e=>e.isCritical)}static addError(e){this.#n.push(codeLines(isString(e)?e:errorToS2(e))),this.summary.refresh()}static lastErrors(){return this.#n.toA()}static addLoadingMsg(e){this.#a.push({at:Date.now(),msg:e})}static normalizeMsg(e){return compact(toA(e)).map(toS).map(e=>e.trim()).filter(e=>e.length>0)}static unseenOrOldestPendingTrace(){let e=this.allCritical().map(e=>e.result()).filter(e=>e.isPending);return logger57().info(`unseenOrOldestPendingTrace`,{pending:e.map(e=>({name:e.name,id:e.id})),shownCounts:this.#o.entriesByCountDesc()}),map(leastBy(e,e=>[this.#o.get(e.name),e.startedAt]),e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt}))}static loadingMsg(){let e=this.#a.shift()??this.unseenOrOldestPendingTrace();return map(e,e=>this.#o.incr(e.msg)),logger57().tap({msg:`loadingMsg`,level:`info`,result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(n=!0){let r=n?HealthCheckIds.values:[];return Settings2.skipHealthCheckIds.value=r,e.reset()}static findById(e){return this.#s.find(n=>n.id===e)}static applySkipHealthCheckIds(e){let n=new Set(this.all().filter(e=>e.isSkipped()));Settings2.skipHealthCheckIds.values=e;let r=this.all().filter(e=>n.has(e)!==e.isSkipped());for(let e of r)e.isSkipped()?e.refresh():(e.reset(),e.result());return r}static injectResults(e){let n=this.#l(e);return this.#c=n,n}static#c=[];static clearLastInjectedResults(){this.#c=[]}static#l(e){let n=[],r=[],a=[];for(let o of e){let e=this.findById(o.id);e==null?r.push(o.id):e.injectResult(o)?n.push(o):a.push(o.id)}return logger57().info(`injectResults`,{found:n.map(e=>e.id),notFound:r,rejected:a}),n}static#u=[];static addResultWatcher(e){this.#u.push(e)}static removeResultWatcher(e){remove(this.#u,e)}static testResults(){return this.all().map(e=>e.result())}static enabledTestCount(){return count(this.all(),e=>!e.isSkipped()&&e.toLevelSync()!==`disabled`)}static testResultsCritical(){return this.allCritical().map(e=>e.result())}static testResultsCriticalAsync(e){return Deferred2.toAsyncIterable(this.testResultsCritical(),e)}static async errorResults(){return(await Promise.all(this.testResults())).filter(e=>e.level===`error`)}static async notOkResults(){return(await Promise.all(this.testResults())).filter(e=>levelIsNotOK(e.level))}static runState(){return this.summary().state}static onCriticalResult=trailingThrottle({fn:()=>{logger57().info(`onCriticalResult()`,this.summary.refresh())},minDelayMs:250});static summary=lazy2(()=>this.#f());static#d(e){let n=this.#f(e);return this.summary.set(n),n}static#f(e){let n=e??this.allCritical().map(e=>e.toResultSync()),r=summarizeHealthChecksSync({errors:this.#n,skipPending:this.#r,healthCheckResults:n});return r.settled&&(this.#r=!0),r.state!==this.#i.last?.state&&this.#i.push({state:r.state,ts:Date.now()}),logger57().tap({msg:`#summary`,result:r,level:levelIsNotOK(r.level)?`warn`:`info`,meta:{healthCheckResults:n}})}static async awaitSettled(n){let r=e.allCritical();if(r.every(e=>e.isSkipped()))return logger57().info(`awaitSettled(): all critical checks are skipped`),e.#d([]);let a=12e4,o=r.map(e=>e.id),s=[];for await(let r of e.testResultsCriticalAsync(a))remove(o,r.id),s.push(r),n?.(r),logger57().info(`awaitSettled(): critical result`,{result:r,pendingIds:o});return o.length>0&&logger57().warn(`awaitSettled(): timed out with pending checks`,{pendingIds:o,globalTimeoutMs:a}),logger57().tap({msg:`awaitSettled(): done`,level:`info`,result:e.#d(s),meta:{results:s}})}static rerunSetup(){return this.resetDebounced.reset(),this.reset(),this.awaitSettled()}static onResultChange(){e.summary.unset()}static resetDebounced=trailingThrottle({fn:()=>e.reset(),minDelayMs:500});static abort(){for(let e of this.#s)e.isPending()&&e.logger.abortable.abort(`HealthCheck.abort()`)}static reset(){if(ending())logger57().warn(`Rejecting reset() when ending()`,shortStack());else{this.abort(),this.onResultChange(),this.#n.clear(),this.#a.clear(),this.#o.clear(),this.#i.clear(),this.summary.clear(),this.#r=!1;for(let e of this.#s)e.reset();this.#c.length>0&&this.#l(this.#c)}}static async evaluateAll(e){let n=e?.concurrency??3,r=this.all().filter(e=>!e.isSkipped()&&e.isPending());for(let e of batches(r,n))await Promise.allSettled(e.map(e=>e.result()))}static for(n){let r=this.findById(n.id);if(r!=null)throw Error(`Health check with id ${n.id} already exists in section ${r.section}`);let a=new e(n.section,n.id,n.pendingMsg,n.later,n.evalMode,n.ordinal,n.links,n.okLinks,n.warnLinks,n.noLibraryLinks,n.errorLinks,n.onReset,n.ttlMs,n.timeoutMs);return this.#s.push(a),this.all.reset(),a}logger;isCritical;sortBy;#p;#m=0;#h=0;#g;#_;isStale(){return this.#p.isStale()||this.#v()}#v(){if(this.isDeferredToSync())return!1;let e=this.#p.prior(),n=e?.isResolved===!0?e.value:void 0;return n?.timedOut===!0&&Date.now()-n.ts>TimedOutResultTtlMs}isPending(){return this.#p.lastValue()==null}isRefreshing(){return this.#g===this.#h}isDeferredToSync(){return isWebService()&&(this.evalMode===`syncRequired`||this.evalMode===`deferrable`&&isChildProcess())}resolvedAtLeastOnce(){return this.#p.resolvedCount()>=1}stats(){return{id:this.id,level:this.toLevelSync(),msg:this.toResultSync().msg,resolvedCount:this.#p.resolvedCount(),rejectedCount:this.#p.rejectedCount(),lastValue:this.#p.lastValue()}}reset(){if(ending())this.logger.warn(`Rejecting reset() when ending()`,shortStack());else return this.onReset?.(),this.#h++,this.#p.clear(),this.logger.resetAbortable(),this}setTTL(e){this.#p.setTTL(e)}injectResult(e){return this.evalMode===`local`||e.level===`user-disabled`!==this.isSkipped()?!1:(this.#h++,this.#p.set(e,hourMs),!0)}refresh(){if(!ending())return this.#p.refresh()}result(){return this.#v()?this.#p.refresh():this.#p()}isSkipped(){return Settings2.skipHealthCheckIds.values.some(e=>e===this.id)}async#y(e){let n=performance.now(),r=++this.#h,a=this.timeoutMs()??commandTimeoutMs()??3e4,o=a>0?a*2:3e4;logger57().debug(`#wrapLater() starting`,{id:this.id,timeoutMs:o}),this.#g=r;try{if(getDevEnvFlag(`PS_SLOMO`)&&await delay(randomInt(o*.3,o*.7)),this.isSkipped())return this.#b({generation:r,test:{level:`user-disabled`,msg:[`Disabled: `+stripSuffix(this.pendingMsg,`…`),`Turned off by the `+Settings2.skipHealthCheckIds.name+` setting`]},elapsedMs:roundMs(performance.now()-n)});if(this.isDeferredToSync())return this.#b({generation:r,test:{level:`disabled`,msg:[this.pendingMsg]},elapsedMs:roundMs(performance.now()-n)});if(ending())return this.#b({generation:r,test:{level:`disabled`,msg:[`Disabled: ending`]},elapsedMs:roundMs(performance.now()-n)});let a=await this.logger.awaitOrAbort(thenOrTimeoutError(e(),o));return this.#b({generation:r,test:a,elapsedMs:roundMs(performance.now()-n)})}catch(e){return isAbortError(e)||ending()?(this.logger.info(`#wrapLater() aborted`),this.#b({generation:r,test:{level:`disabled`,msg:[`Aborted: shutting down`]},elapsedMs:roundMs(performance.now()-n)})):this.#S({generation:r,error:e,elapsedMs:roundMs(performance.now()-n)})}finally{this.#g===r&&(this.#g=void 0),pushTime({name:`health.`+this.id,elapsedMs:roundMs(performance.now()-n)})}}#b({test:n,src:r=`#toResult`,elapsedMs:a,generation:o,timedOut:s}){let c=e.normalizeMsg(n.msg),l=n.level??(toS(c).toLowerCase().includes(`error`)?`error`:toS(c).toLowerCase().includes(`warn`)?`warn`:`ok`),u=compact([...n?.links??(l===`ok`||l===`pending`?this.okLinks:l===`warn`?this.warnLinks:l===`no-library`?this.noLibraryLinks:l===`error`?this.errorLinks:[])??[],...this.links??[]]),d={section:this.section,id:this.id,ts:Date.now(),level:l,msg:c,elapsedMs:a,meta:{...n.meta,from:processName()},critical:this.isCritical,...partitionLinks(u),...s===!0?{timedOut:s}:{}};d.runCount=this.#m++;let f=ending(),h=o==null||o===this.#h;if(!f&&h&&this.#x(d),h)for(let n of e.#u)n(d);return f?d:this.logger.tap({level:`debug`,msg:r,result:d})}#x(e){let n=this.#_;e.level===`stop-sync`?n==null?(this.logger.warn(`Health check stopped sync`,{id:this.id,reasons:e.msg}),this.#_={reasons:e.msg,since:e.ts}):n.reasons=e.msg:n!=null&&(e.level===`pending`||SyncBlockingLevels.includes(e.level)?e.level!==`pending`&&(n.reasons=e.msg):(this.#_=void 0,this.logger.info(`Health check recovered from stop-sync`,{id:this.id,priorReasons:n.reasons,blockedMs:Math.max(0,e.ts-n.since),resultLevel:e.level,reasons:e.msg})))}#S({error:e,level:n,elapsedMs:r,generation:a}){this.logger.warn(`#toErrorResult`,{error:e,level:n});let o=stripSuffix(this.pendingMsg,`…`)+` failed:
|
|
539
|
+
`+(toNotBlank(errorToS2(e))??`(missing error)`);return n??=this.isCritical&&!isTest()&&(isFatalError(e)||!o.toLowerCase().includes(`warn`))?`error`:`warn`,this.#b({test:{msg:o,level:n},src:`#toErrorResult`,elapsedMs:r,generation:a,timedOut:isTimeoutError2(e)?!0:void 0})}toLevelSync(){return this.#p.lastValue()?.level??`pending`}toResultSyncMaybe(){return this.#p.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:`pending`,msg:[this.pendingMsg],critical:this.isCritical}}};function partitionLinks(e){if(isEmpty(e))return{};let[n,r]=partition(e,e=>e.type===`button`||e.method===`POST`),a={};return isNotEmpty(r)&&(a.links=uniqBy(r)),isNotEmpty(n)&&(a.buttons=uniqBy(n)),a}var import_node_path59=__toESM(require("node:path")),import_node_util17=require("node:util"),MediaInfoFieldNames=strEnum(`nativePath`,`uri`,`basename`,`mtime`,`fileSize`,`mimetype`,`capturedAtLocal`,`capturedAtZone`,`capturedAtPrecisionMs`,`capturedAtSrc`,`capturedAtSrcDetail`,`capturedAtZoneSrc`,`width`,`height`,`rotation`,`sha`,`metadataDate`,`rating`,`latitude`,`longitude`,`make`,`model`,`lensId`,`cameraId`,`imageId`,`durationMs`,`fps`,`aperture`,`focalLength`,`iso`,`shutterSpeed`,`monochrome`,`pHash`,`rHash`,`wHash`,`pHash0`,`rHash0`,`wHash0`),AssetFileFieldNames=strEnum(`id`,`assetId`,`isPrimary`,`nativePath`,`uri`,`basename`,...MediaInfoFieldNames);function knownNativePath(e){try{return toNotBlank(e.nativePath)}catch{return}}async function getNativePathFromUriDetails(e){return knownNativePath(e)??await uriToNativePath(e.uri)}function simpleGlobToRegexp(e,n){return RegExp(`^`+escapeRegExp(e).replace(/\\\?/g,`.`).replace(/\\\*/g,`.*`)+`$`,n)}var SimpleGlobArray=class{#e;constructor(e,n){this.#e=e.map(e=>simpleGlobToRegexp(e,n))}get length(){return this.#e.length}indexOf(e){if(e!=null){for(let n=0;n<this.#e.length;n++)if(this.#e[n].test(e))return n}}},logger58=lazy2(()=>mkLogger(`uri.LibraryUriRoots`)),pslibRoot=PSLIB_ROOT_URI.toString(),roots=[pslibRoot];function libraryUriRoots(){return roots}async function refreshLibraryUriRoots(){let e=originalsDir(),n=e==null||!originalsDirIsOutsideLibrary()?[pslibRoot]:[pslibRoot,...(await nativePathToUriStrings(e)).filter(e=>!e.startsWith(PS_LIBRARY_PROTOCOL))];return logger58().debug(`refreshLibraryUriRoots()`,{roots:n}),roots=n}function libraryRootContaining(e){return roots.find(n=>{let r=treeBase(n);return e===r||e.startsWith(r+`/`)})}function treeBase(e){return e.endsWith(`/`)?e.slice(0,-1):e}function isLibraryUri(e){return libraryRootContaining(e)!=null}function libraryRelativePath(e){let n=libraryRootContaining(e);if(n==null)return;let r=toURI(e).path;return n===pslibRoot?r:ensurePrefix(r.slice(toURI(treeBase(n)).path.length),`/`)}var logger59=lazy2(()=>mkLogger(`img.AssetFileSorter`)),UriSchemes=strEnum(`file`,PS_NETWORK_FILESYSTEM_SCHEME,PS_LOCAL_FILE_SCHEME,PS_LIBRARY_SCHEME),mimetypeGlobArray=defer(()=>new SimpleGlobArray(AggregationSettings.assetVariationMimetypeSortOrder.values)),FileExtSortOrder=defer(()=>{let e=mimetypeGlobArray();return sortBy(sort(AssetFileExts()),n=>e.indexOf(extMimetype(n)))});function dim2sort(e){return map2Numeric(e?.width,e?.height,(e,n)=>sortScale(e*n))}function sortScale(e){if(gt0(e))return Math.floor(Math.log2(e)/Math.log2(AggregationSettings.assetVariationResolutionTolerance.valueOrDefault))}function mtime2sort(e){return Math.round(e/(5*minuteMs))}function sortAssetFilesInPlace(e,n={}){return sortByInPlace(e,e=>assetFileSortCriteria(e,n)).reverse()}function assetFileSortCriteriaPojo(e){let n=URI.parse(e.uri);if(blank(n?.scheme)||blank(n?.path)){logger59().warn(`assetFileSortCriteriaPojo(): skipping (invalid URI)`,{uri_scheme:n?.scheme,uri_path:n?.path,af:e,parsedURI:n});return}let r=dim2sort(e);if(r==null){logger59().warn(`assetFileSortCriteriaPojo(): skipping (invalid resolution)`,{resolution:r,af:e,parsedURI:n});return}let a=isLibraryUri(e.uri)?UriSchemes.indexOf(PS_LIBRARY_SCHEME):UriSchemes.indexOf(n.scheme);if(a==null){logger59().warn(`assetFileSortCriteriaPojo(): skipping (invalid URI scheme)`,{uri_scheme:n.scheme,af:e,parsedURI:n});return}let o=e.mtime??0,s=parsePosixPath(n.path),c={resolution:r,isBrowserSupported:isSupportedByCurrentBrowserExt(s.ext),mimetype:-(mimetypeGlobArray().indexOf(e.mimetype)??mimetypeGlobArray().length),schemeIdx:a,metadataDate:e.metadataDate??0,capturedAtPrecisionMs:-(e.capturedAtPrecisionMs??0),isEditOrUpdate:/edit|update/i.test(s.base),isCover:/cover/i.test(s.base),fileSize:e.fileSize,sha:e.sha??``,uri:CmpReverseFlag+e.uri,count:-Math.abs(copySuffixCountFromName(s.name)??0),mtime:mtime2sort(o),basename:CmpReverseFlag+s.base,parentBasename:CmpReverseFlag+parentBasename(n.path)};return logger59().tap({msg:`assetFileSortCriteriaPojo()`,result:toReqValued(c)})}function assetFileSortFields(){return uniq([...AggregationSettings.assetVariationSortCriteria.values,`uri`])}var ContentTieBreakerCriteria=new Set([`schemeIdx`,`fileSize`,`sha`,`uri`,`count`,`mtime`,`basename`,`parentBasename`]);function assetFileSortCriteria(e,n={}){let r=assetFileSortCriteriaPojo(e);if(r==null)return;let a=assetFileSortFields(),o=+(n.pinnedUri!=null&&e.uri===n.pinnedUri);if(!((n.preferredShas?.size??0)>0))return[o,...a.map(e=>r[e])];let s=a.findIndex(e=>ContentTieBreakerCriteria.has(e));return[o,...a.slice(0,s).map(e=>r[e]),+(n.preferredShas?.has(e.sha??``)===!0),...a.slice(s).map(e=>r[e])]}async function bestExistingAssetFile(e){for(let n of sortAssetFilesInPlace(e)){let r=knownNativePath(n);if(r!=null&&await isNonEmptyFile(r)||await uriExists(n.uri))return logger59().tap({msg:`bestExistingAssetFile()`,result:n,meta:{files:e.map(e=>e.uri)}})}return logger59().tap({msg:`bestExistingAssetFile(): no existing uris`,result:void 0,meta:{files:e}})}var HeifMimeTypes=[`image/heic`,`image/heif`,`image/avif`];function isHeifMimeType(e){return e!=null&&HeifMimeTypes.includes(e)}var chromeRE=/\bChrome\b/,firefoxRE=/\bFirefox\b/;function matches(e,n){return e!=null&&String(e).match(n)!=null}function isChrome(e){return matches(e,chromeRE)}function isFirefox(e){return matches(e,firefoxRE)}var logger60=defer(()=>mkLogger(`platform.Apt`));async function aptInstalledVersion(e){if(!hasApt())return;let n=[];for(let r of compactBlanks(await dpkgSearch(e))){let e=await aptCachePolicyVersion(r);n.push({pkg:r,version:e,semver:toSemVer(e)})}return logger60().tap({msg:`aptInstalledVersion(`+e+`)`,result:n})}var DebPackageNameRe=/^[a-z][a-z\d+\-.]+/;async function dpkgSearch(e){if(!hasApt()||blank(e))return;let n=await stdoutResult_(`dpkg`,[`-S`,e],{timeoutMs:commandTimeoutMs(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return logger60().debug(`dpkg -S`,{file:e,result:n}),n.code===0?uniq(splitLines(n.result).map(e=>DebPackageNameRe.exec(e)?.[0])):void 0}async function aptCachePolicyVersion(e){if(!hasApt()||blank(e))return;let n=await stdoutResult_(`apt-cache`,[`policy`,e],{timeoutMs:commandTimeoutMs(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(logger60().debug(`apt-cache policy`,{packageName:e,result:n}),n.code===0)for(let e of splitLines(n.result)){let n=/^\s*Installed: (.*)$/.exec(e);if(n!=null)return n[1]}}var logger61=defer(()=>mkLogger(`platform.Pacman`)),hasPacman=defer(()=>isLinux&&isNonEmptyFileSync(`/etc/pacman.conf`));async function pacmanInstalledVersion(e){if(hasPacman())try{let n=parsePacmanQo((await stdoutResult_(`pacman`,[`-Qo`,e],{timeoutMs:commandTimeoutMs(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:`C`,LOCALE:`C`}})).result);return logger61().tap({msg:`pacmanInstalledVersion(`+e+`)`,result:n,meta:{nativePathOrBasename:e}})}catch(n){logger61().debug(`pacman doesn't seem to know about `+e,{error:n});return}}var VersionRe=/is owned by (?<pkg>\S+) (?<version>\S+)/i;function parsePacmanQo(e){return e.match(VersionRe)?.groups}var import_exiftool_vendored2=require("exiftool-vendored"),import_node_path53=__toESM(require("node:path")),logger62=defer(()=>mkLogger(`tags.ExifTool`));function exiftoolProcsPerChild(){return toGt0(Settings2.exiftoolProcsPerChild.valueOrDefault)??(isWorkerService()?2:maxCpus())}async function _exiftoolPath(){return logger62().tap({msg:`exiftoolPath()`,level:`info`,result:isElectron()&&isPacked()?import_node_path53.default.join(ProjectDir.Root(),`exiftool-vendored`+(isWin?`.exe`:`.pl`),`bin`,`exiftool`+(isWin?`.exe`:``)):await(0,import_exiftool_vendored2.exiftoolPath)()})}var _exiftool=lazy2(()=>{let e={useMWG:Settings2.useMWG.valueOrDefault,backfillTimezones:!0,ignoreZeroZeroLatLon:!0,inferTimezoneFromDatestamps:!0,defaultVideosToUTC:Settings2.defaultVideosToUTC.valueOrDefault,exiftoolPath:_exiftoolPath,geolocation:Settings2.tagGeo.valueOrDefault,numericTags:Settings2.numericTags.valueOrDefault,preferTimezoneInferenceFromGps:Settings2.preferTimezoneInferenceFromGps.valueOrDefault,...batchClusterOptions(exiftoolProcsPerChild(),`exif.ExifTool`)};return logger62().info(`ExifTool options`,e),new BatchClusterObserver(`ExifTool`,new import_exiftool_vendored2.ExifTool(e)).t});function exiftool(){let e=_exiftool();return e.ended?_exiftool.refresh():e}function extractBinaryTag(e,n,r){return time({name:`exif.extractBinary`,meta:{tagname:e},p:()=>exiftool().extractBinaryTag(e,n,r)})}function ver(e){return blank(e)?`(missing version)`:e.replace(/^(?:v(?:er(?:sion)?)?)?\s*/,`version `)}function newFfmpegProgressState(){return{carry:``,pending:{}}}function feedFfmpegProgress(e,n){let r=[],a=(e.carry+n).split(`
|
|
540
|
+
`);e.carry=a.pop()??``;for(let n of a){let a=n.trim();if(a.length===0)continue;let o=a.indexOf(`=`);if(o<=0)continue;let s=a.slice(0,o).trim(),c=a.slice(o+1).trim();assignField(e.pending,s,c),s===`progress`&&(r.push(e.pending),e.pending={})}return r}function assignField(e,n,r){switch(n){case`frame`:{let n=toInt(r);n!=null&&(e.frame=n);return}case`fps`:{let n=toFloat(r);n!=null&>0(n)&&(e.fps=n);return}case`out_time_us`:case`out_time_ms`:{let n=toInt(r);n!=null&&(e.outTimeMs=n/1e3);return}case`bitrate`:{let n=/^(-?\d+(?:\.\d+)?)\s*kbits\/s$/.exec(r);if(n!=null){let r=toFloat(n[1]);r!=null&&(e.bitrateKbps=r)}return}case`speed`:{let n=/^(\d+(?:\.\d+)?)x$/.exec(r);if(n!=null){let r=toFloat(n[1]);r!=null&&(e.speed=r)}return}case`progress`:(r===`continue`||r===`end`)&&(e.progress=r);return}}var FfmpegLiveSpeedThreshold=.01;function isLiveTick(e){return e.speed!=null&&e.speed>FfmpegLiveSpeedThreshold}var FfmpegStallWatcher=class{constructor(e){this.opts=e}opts;#e;arm(){this.disarm();let e=this.opts.schedule??setTimeout;this.#e=e(()=>{this.#e=void 0,this.opts.onStall()},this.opts.timeoutMs),this.#e?.unref?.()}disarm(){this.#e!=null&&((this.opts.clear??clearTimeout)(this.#e),this.#e=void 0)}onTick(e){isLiveTick(e)&&this.arm()}};function ffmpegEtaMs(e,n){return n==null||!gt0(n)||e.outTimeMs==null||e.speed==null||e.speed<=FfmpegLiveSpeedThreshold?void 0:Math.max(0,n-e.outTimeMs)/e.speed}var logger63=lazy2(()=>mkLogger(`img.ValidationError`)),noisyErrorLines=[/Nothing was written into output file.*received no packets/i,/Error marking filters as finished/i,/^\s*at\s+/i];function cleanValidationError(e){return e.split(`
|
|
541
|
+
`).filter(e=>!noisyErrorLines.some(n=>n.test(e))).join(`: `).trim()}function classifyValidationError(e){let n=cleanValidationError(errorToS2(e,{maxLen:512})),r=validationErrorAllowlist().test(n),a=validationErrorBlocklist().test(n);return logger63().tap({msg:`classifyValidationError`,level:r?`debug`:`info`,result:r?`allowed`:a?`blocked`:`unrecognized`,meta:{error:e,allow:r,block:a}})}function isIgnorableValidationError(e){return classifyValidationError(e)!==`blocked`}function isExpectedValidationError(e){return classifyValidationError(e)===`allowed`}var validationErrorBlocklist=lazy2(()=>orRegExpPatterns(compactBlanks(FiltersSettings.validationErrorBlocklist.values),`i`)),validationErrorAllowlist=lazy2(()=>orRegExpPatterns(compactBlanks(FiltersSettings.validationErrorAllowlist.values),`i`));later(()=>{FiltersSettings.validationErrorBlocklist.watchLater(()=>validationErrorBlocklist.unset()),FiltersSettings.validationErrorAllowlist.watchLater(()=>validationErrorAllowlist.unset())});var logger64=defer(()=>mkLogger(`img.ffprobe`));function ffprobeNativePath(){return pathTo2({tool:`ffprobe`})}var isFFprobeAvailable=lazy2(async()=>{try{return!0===(await ffprobeVersion_())?.isSupportedVersion}catch{return!1}}),ffprobeVersionRe=/ffprobe version n?(?<version>\S+)/i,ffprobeVersion_=lazy2(async()=>{let e=await ffprobeNativePath();if(e==null)return;let n=await stdoutResult_(e,[`-version`],{timerName:`proc.ffprobe`,timeoutMs:commandTimeoutMs(),ignoreStderr:!0}),r=ffprobeVersionRe.exec(n.result)?.[1];return logger64().debug(`ffprobeVersion`,{version:r,code:n.code,stdout:n.result.split(`
|
|
542
|
+
`,1)[0]}),{desc:`ffprobe`,path:e,version:r??`(unknown)`,isSupportedVersion:semVerSatisfies(r,`>=3.2`)}});function isHdrColorspace(e){let n=e.colorTransfer===`smpte2084`||e.colorTransfer===`arib-std-b67`,r=e.colorPrimaries===`bt2020`||e.colorSpace===`bt2020nc`;return n||r}function isBt601Colorspace(e){let n=[`bt601`,`bt470bg`,`smpte170m`,`pal`,`ntsc`];return n.includes(e.colorSpace??``)||n.includes(e.colorPrimaries??``)}function isBt709Colorspace(e){return e.colorSpace===`bt709`||e.colorPrimaries===`bt709`}function extractVideoColorspace(e){if(!Array.isArray(e?.streams))return{colorRange:void 0,colorSpace:void 0,colorTransfer:void 0,colorPrimaries:void 0,height:void 0,pixFmt:void 0};let n=e.streams.find(e=>e?.codec_type===`video`);return{colorRange:n?.color_range,colorSpace:n?.color_space??void 0,colorTransfer:n?.color_transfer??void 0,colorPrimaries:n?.color_primaries??void 0,height:n?.height,pixFmt:n?.pix_fmt??void 0}}var browserCompatiblePixFmts=new Set([`yuv420p`,`yuv420p10le`]);function isBrowserCompatiblePixFmt(e){return e==null||browserCompatiblePixFmts.has(e)}function hasConsistentColorspaceMetadata(e){return isHdrColorspace(e)?!0:e.colorSpace!=null||e.colorPrimaries!=null||e.colorTransfer!=null?isBt709Colorspace(e)?e.colorTransfer===`bt709`||e.colorTransfer==null:!isBt601Colorspace(e)||e.colorTransfer==null||[`bt601`,`bt470bg`,`smpte170m`,`pal`,`ntsc`].includes(e.colorTransfer):!1}var videoCodecNameToFourCC={h264:`avc1`,hevc:`hvc1`,vp9:`vp09`,av1:`av01`,mjpeg:`mjpg`,mpeg4:`mp4v`,mpeg2video:`mp2v`,prores:`apcn`},audioCodecNameToFourCC={aac:`mp4a`,mp3:`mp3`,pcm_s16le:`sowt`,pcm_s16be:`twos`,pcm_u8:`raw `,ac3:`ac-3`,eac3:`ec-3`,opus:`Opus`,vorbis:`vorb`,flac:`fLaC`},containerVideoCodecTags={HDMV:`avc1`,HDPR:`avc1`};function extractVideoCodec(e){if(e==null)return;let n=e.codec_tag_string;if(n!=null&&n in containerVideoCodecTags)return containerVideoCodecTags[n];if(n!=null&&n.length>0&&!n.includes(`[0]`))return n;let r=e.codec_name?.toLowerCase();return r==null?void 0:videoCodecNameToFourCC[r]??r}function extractAudioCodec(e){if(e==null)return;let n=e.codec_tag_string;if(n!=null&&n.length>0&&!n.includes(`[0]`))return n;let r=e.codec_name?.toLowerCase();return r==null?void 0:audioCodecNameToFourCC[r]??r}function ffprobeResultToTags(e){if(!Array.isArray(e?.streams))return{};let n=e.streams.find(e=>e?.codec_type===`video`),r=e.streams.find(e=>e?.codec_type===`audio`);return{AspectRatio:n?.display_aspect_ratio,AudioChannels:r?.channels,AudioCodec:extractAudioCodec(r),AudioSampleRate:toFloat(r?.sample_rate),Duration:toFloat(n?.duration),FrameRate:extractFraction(n?.avg_frame_rate),ImageHeight:toInt(n?.height),ImageWidth:toInt(n?.width),Rotation:first(n?.side_data_list,e=>normalizeRotation(e?.rotation,!0))??0,VideoCodec:extractVideoCodec(n)}}var ffprobeRawCache=lazy2(()=>new FileCache({name:`img.ffprobe.raw`,...metadataCacheOptions(),maxSize:256,timeoutMs:minuteMs}));async function ffprobeRaw_(e){return ffprobeRawCache().getOrSet(toNativePath_(e),async()=>{let n=await ffprobeNativePath();if(n==null)return;let r=toNativePath_(e),{result:a,code:o,stderr:s}=await stdoutResult_(n,[`-v`,`error`,`-print_format`,`json`,`-show_format`,`-show_streams`,`-show_entries`,`stream_side_data=rotation`,r],{timerName:`proc.ffprobe`,timeoutMs:commandTimeoutMs(),ignoreExitCode:!0,isIgnorableError:()=>!0,quiet:!0});if(o!==0){logger64().warn(`ffprobeRaw_() failed`,{ffprobe:n,file:r,code:o,stderr:s});let e=cleanValidationError((s??``).trim());throw Error(`${n} exit code ${o} for ${r}`+(notBlank(e)?`: `+e:``))}return notBlank(s)&&logger64().debug(`ffprobeRaw_() stderr`,{ffprobe:n,file:r,stderr:s}),parseJSON_(a)},await fileStamp(e))}var ffprobeCache=lazy2(()=>new FileCache({name:`img.ffprobe`,...metadataCacheOptions(),maxSize:256,timeoutMs:minuteMs}));async function ffprobe_(e){return ffprobeCache().getOrSet(toNativePath_(e),async()=>logger64().tap({msg:`ffprobe()`,result:ffprobeResultToTags(await ffprobeRaw_(e)??{streams:[],format:{}}),meta:{f:e}}),await fileStamp(e))}async function ffprobeColorspace_(e){let n=extractVideoColorspace(await ffprobeRaw_(e));return logger64().debug(`ffprobeColorspace()`,{f:e,colorspace:n}),n}var logger65=lazy2(()=>mkLogger(`img.ffmpeg`)),MinFfmpegVideoVersion=`3.2`;function ffmpegNativePath(){return pathTo2({tool:`ffmpeg`})}var ffmpegVersionRe=/ffmpeg version n?(?<version>\S+)/i,_ffmpegVersion_=lazy2(async()=>{let e=await ffmpegNativePath();if(e==null)return{desc:`FFmpeg`,version:`(not found)`,isSupportedVersion:!1};let n=await stdoutResult_(e,[`-version`],{timerName:`proc.ffmpeg`,timeoutMs:commandTimeoutMs(),ignoreStderr:!0}),r=ffmpegVersionRe.exec(n.result)?.[1];return logger65().debug(`ffmpegVersion`,{version:r,code:n.code,stdout:n.result.split(`
|
|
543
|
+
`,1)[0]}),{desc:`FFmpeg`,path:e,version:r??`(unknown)`,isSupportedVersion:semVerSatisfies(r,`>=`+MinFfmpegVideoVersion)}}),ffmpegVersionDescription=lazy2(async()=>{try{return ver((await _ffmpegVersion_()).version)}catch{return`(error detecting version)`}});function clearCaches2(){_ffmpegVersion_.unset(),ffmpegVersionDescription.unset(),ffprobeVersion_.unset(),isFFprobeAvailable.unset()}later(()=>{ee().on(`clearCache`,clearCaches2),ee().on(`clearToolCache`,clearCaches2)});async function ffmpegVersion_(){return await _ffmpegVersion_.prior()??_ffmpegVersion_.refresh()}function refreshFfmpegVersion_(){_ffmpegVersion_.unset()}async function isFFmpegSupported(){try{return(await _ffmpegVersion_()).isSupportedVersion===!0}catch(e){return logger65().warn(`isFFmpegSupported failed`,{err:e}),!1}}var NotBlackFilter=`blackframe=amount=0:threshold=48,metadata=mode=select:key=lavfi.blackframe.pblack:value=98:function=less`,ContentFrameGraph=`[0:V]split=2[a][b];[a]trim=end=1,${NotBlackFilter},negate,${NotBlackFilter},negate[a1];[b]trim=end_frame=1[b1];[a1][b1]concat=n=2:v=1:a=0[frame]`;function ffmpegFrameArgs(e){return[`-loglevel`,`error`,`-threads`,`1`,`-i`,e.src.nativePath,`-threads`,String(Settings2.ffmpegThreads.valueOrDefault),`-filter_complex`,ContentFrameGraph,`-map`,`[frame]`,`-vframes`,`1`,`-pix_fmt`,`yuvj420p`,`-y`,e.dest.nativePath]}async function ffmpegFrame_(e){if(await e.dest.parent().mkdirp_(),await stdoutResult_(await ffmpegNativePath(),ffmpegFrameArgs(e),{timerName:`proc.ffmpeg`,timeoutMs:minuteMs,cleanError:cleanValidationError,isIgnorableError:isIgnorableValidationError,isExpectedError:isExpectedValidationError}),!await untilTrue(()=>e.dest.clear().isNonEmptyFile(),{timeoutMs:3*secondMs,intervalMs:25}))throw Error(`Failed to extract frame for `+e.src)}function hwaccel(e){let n=e?.ffmpegHwaccel??Settings2.ffmpegHwaccel.valueOrDefault;return blank(n)||isDisabled(n)?[]:[`-hwaccel`,n]}var FFMPEG_COLOR={RANGE_TV:`1`,RANGE_PC:`2`,BT709:`1`,BT2020NC:`9`,TRC_BT709:`1`,TRC_PQ:`16`,TRC_HLG:`18`},BT601_TO_BT709_FILTER=`colorspace=all=bt709:iall=bt601-6-625,format=yuv420p`,PIXEL_FORMAT_FILTER=`format=yuv420p`;function buildColorspaceArgs(e){let n=mkLogger(`ffmpeg.buildColorspaceArgs`);if(isHdrColorspace(e)){n.info(`HDR detected - preserving source colorspace`,{colorspace:e});let r=e.colorTransfer===`arib-std-b67`?FFMPEG_COLOR.TRC_HLG:FFMPEG_COLOR.TRC_PQ;return[`-color_range`,e.colorRange===`pc`?FFMPEG_COLOR.RANGE_PC:FFMPEG_COLOR.RANGE_TV,`-colorspace`,FFMPEG_COLOR.BT2020NC,`-color_primaries`,FFMPEG_COLOR.BT2020NC,`-color_trc`,r]}if(isBt709Colorspace(e)){let r=!isBrowserCompatiblePixFmt(e.pixFmt);n.info(`BT.709 detected`,{colorspace:e,needsPixFmtConversion:r});let a=[`-color_range`,FFMPEG_COLOR.RANGE_TV,`-colorspace`,FFMPEG_COLOR.BT709,`-color_primaries`,FFMPEG_COLOR.BT709,`-color_trc`,FFMPEG_COLOR.TRC_BT709];return r?[`-vf`,PIXEL_FORMAT_FILTER,...a]:a}if(isBt601Colorspace(e))return n.info(`BT.601 detected - converting to BT.709`,{colorspace:e}),[`-vf`,BT601_TO_BT709_FILTER,`-color_range`,FFMPEG_COLOR.RANGE_TV,`-colorspace`,FFMPEG_COLOR.BT709,`-color_primaries`,FFMPEG_COLOR.BT709,`-color_trc`,FFMPEG_COLOR.TRC_BT709];if((e.height??0)>=720){let r=!isBrowserCompatiblePixFmt(e.pixFmt);n.info(`Unknown colorspace, HD resolution - assuming BT.709`,{colorspace:e,needsPixFmtConversion:r});let a=[`-color_range`,FFMPEG_COLOR.RANGE_TV,`-colorspace`,FFMPEG_COLOR.BT709,`-color_primaries`,FFMPEG_COLOR.BT709,`-color_trc`,FFMPEG_COLOR.TRC_BT709];return r?[`-vf`,PIXEL_FORMAT_FILTER,...a]:a}return n.info(`Unknown colorspace, SD resolution - converting BT.601→BT.709`,{colorspace:e}),[`-vf`,BT601_TO_BT709_FILTER,`-color_range`,FFMPEG_COLOR.RANGE_TV,`-colorspace`,FFMPEG_COLOR.BT709,`-color_primaries`,FFMPEG_COLOR.BT709,`-color_trc`,FFMPEG_COLOR.TRC_BT709]}function avcArgs(e){let n=Settings2.ffmpegAvcTranscodeArgs.values,r=[];for(let e=0;e<n.length;e++){let a=n[e];a===`-c:v`?e++:r.push(a)}let a=Settings2.transcodeVideoCodec.valueOrDefault;r.push(`-c:v`,a),a===`libx265`&&r.push(`-tag:v`,`hvc1`),r.push(`-preset`,Settings2.ffmpegPreset.valueOrDefault);let o=Settings2.transcodeCrf.valueOrDefault;return gt0(o)&&r.push(`-crf`,String(o)),!gt0(e.width)||!gt0(e.height)?r:mergeArgsWithFilters(r,[`-vf`,`scale=${roundEven(e.width)}:${roundEven(e.height)}`])}function framerateArgs(e){let n=Settings2.transcodeFrameRate.valueOrDefault;return!gt0(n)||lte(e?.fps,n)?[]:[`-r`,String(Math.round(n))]}function mergeArgsWithFilters(e,n){let r,a,o=[],s=[];for(let n=0;n<e.length;n++)e[n]===`-vf`&&n+1<e.length?(r=e[n+1],n++):o.push(e[n]);for(let e=0;e<n.length;e++)n[e]===`-vf`&&e+1<n.length?(a=n[e+1],e++):s.push(n[e]);let c=[...o,...s];return r!=null&&a!=null?c.push(`-vf`,`${r},${a}`):r==null?a!=null&&c.push(`-vf`,a):c.push(`-vf`,r),c}function buildTranscodeArgs(e,n,r){let a=r==null?[]:buildColorspaceArgs(r);switch(e){case`none`:throw Error(`buildTranscodeArgs called with strategy 'none'`);case`remux`:return[`-c`,`copy`,`-movflags`,`+faststart`];case`video-only`:return mergeArgsWithFilters([...avcArgs(n).filter((e,n,r)=>e!==`-c:a`&&r[n-1]!==`-c:a`),`-c:a`,`copy`,...framerateArgs(n),...hwaccel(n)],a);case`audio-only`:return[`-c:v`,`copy`,`-c:a`,`aac`,`-movflags`,`+faststart`];default:return mergeArgsWithFilters([...avcArgs(n),...framerateArgs(n),...hwaccel(n)],a)}}var FFMPEG_STALL_ABORT_PREFIX=`ffmpeg stalled`;function isFfmpegStallAbort(e){return e?.startsWith(FFMPEG_STALL_ABORT_PREFIX)??!1}async function ffmpegTranscode_(e){let n=e.strategy??`full`;try{await e.dest.parent().mkdirp_();let r=buildTranscodeArgs(n,e,e.colorspace);logger65().info(`ffmpegTranscode_()`,{strategy:n,colorspace:e.colorspace,src:e.src.nativePath,dest:e.dest.nativePath});let a=e.stallTimeoutMs,o=e.onProgress!=null||gt0(a),s=o?[`-progress`,`pipe:1`,`-nostats`]:[],c=o?newFfmpegProgressState():void 0,l=gt0(a)?new FfmpegStallWatcher({timeoutMs:a,onStall:()=>{logger65().warn(`ffmpegTranscode_() stall detected; aborting via halt`,{src:e.src.nativePath,dest:e.dest.nativePath,stallTimeoutMs:a}),e.halt.abort(FFMPEG_STALL_ABORT_PREFIX+`: no progress for `+a+`ms`)}}):void 0,u=o?n=>{if(c==null)return;let r=feedFfmpegProgress(c,n);for(let n of r)e.onProgress?.(n),l?.onTick(n)}:void 0;l?.arm();try{return await stdoutResult_(await ffmpegNativePath(),compactBlanks([`-loglevel`,`error`,`-i`,e.src.nativePath,...r,`-threads`,String(Settings2.ffmpegThreads.valueOrDefault),...s,`-y`,e.dest.nativePath]),{halt:e.halt,timeoutMs:e.timeoutMs??0,cleanError:cleanValidationError,isIgnorableError:isIgnorableValidationError,isExpectedError:isExpectedValidationError,onStdoutChunk:u})}finally{l?.disarm()}}catch(r){logger65().warn(`ffmpegTranscode_() failed`,{args:e,strategy:n,error:r}),await unlink4(e.dest,`debug`);let a=errorToS2(r,{maxLen:1024});if(!isDisabled(e.ffmpegHwaccel??Settings2.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(a))return logger65().warn(`ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...`,{args:e,error:r}),ffmpegTranscode_({...e,ffmpegHwaccel:`disabled`});throw r}}async function ffmpegValidVideo_(e){return logger65().tap({msg:`ffmpegValidVideo`,meta:{src:e.nativePath},result:await stdoutResult_(await ffmpegNativePath(),[`-xerror`,`-err_detect`,Settings2.ffmpegErrDetect.valueOrDefault,`-v`,`error`,`-nostats`,`-i`,e.nativePath,`-threads`,String(Settings2.ffmpegThreads.valueOrDefault),`-f`,`null`,`-`],{timerName:`proc.ffmpeg`,timeoutMs:0,cleanError:cleanValidationError,isIgnorableError:isIgnorableValidationError,isExpectedError:isExpectedValidationError,ignoreExitCode:!1,quiet:!1})})}var logger66=lazy2(()=>mkLogger(`img.HeifConvert`)),HEIF_THUMBNAIL_MAX_SIZE=320,heifThumbnailerPath=lazy2(async()=>{let e=await pathTo2({tool:`heif-thumbnailer`});return heifThumbnailerPath.setTTL(e==null?minuteMs:void 0),e}),HeifFfmpegDesc=`ffmpeg`,MinFfmpegHeifVersion=`8.1`,getFfmpegHeifToolDetails=lazy2(async()=>{let e=await ffmpegVersion_();if(e?.path!=null)return{desc:HeifFfmpegDesc,path:e.path,version:e.version,isSupportedVersion:semVerSatisfies(e.version,`>=`+MinFfmpegHeifVersion)}}),ffmpegHeifDetails=lazy2(async()=>{let e=await getFfmpegHeifToolDetails();return e?.isSupportedVersion===!0?e:void 0}),FfmpegHeifExt=`.tif`;function ffmpegHeifArgs(e,n){return[`-loglevel`,`error`,`-i`,e.nativePath,`-threads`,String(Settings2.ffmpegThreads.valueOrDefault),`-frames:v`,`1`,`-update`,`1`,`-pix_fmt`,`rgb24`,`-y`,n.nativePath]}async function ffmpegHeif2img_(e){if(await ffmpegHeifDetails()!=null)return withImageCache_(e,`heif-ff`,FfmpegHeifExt,n=>ffmpegHeif2imgTo_(e,n))}async function ffmpegHeif2imgTo_(e,n){let r=(await ffmpegHeifDetails())?.path;if(r!=null){try{await stdoutResult_(r,ffmpegHeifArgs(e,n),{timerName:`proc.ffmpegHeif`,timeoutMs:Settings2.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await n.clear().isEmptyFile(KB)&&logger66().throw(`ffmpegHeif2img_() failed: destination file was empty`,{src:e,dest:n})}catch(n){logger66().throw(`ffmpegHeif2img_() failed`,{error:n,src:e.nativePath})}await copyIccProfile_(e,n)}}async function srcHasIccProfile_(e){let n=await exiftool().read(e.nativePath,{readArgs:[`-ICC_Profile`]});if(n.ICC_Profile!=null)return!0;let r=n.warnings??[];return r.length>0&&logger66().info(`copyIccProfile_(): no ICC profile, and the read was dirty`,{src:e.nativePath,warnings:r}),!1}async function copyIccProfile_(e,n){return timeExcludingNested({name:`img.heif.icc`,thunk:async()=>{if(!await srcHasIccProfile_(e))return logger66().debug(`copyIccProfile_(): source has no ICC profile`,{src:e.nativePath}),!1;let r=await tmpImageFile_({src:e,tag:`icc`,ext:`.icc`});await r.unlink(`trace`);try{await extractBinaryTag(`ICC_Profile`,e.nativePath,r.nativePath);let{updated:a}=await exiftool().write(n.nativePath,{},{writeArgs:[`-overwrite_original`,`-icc_profile<=`+r.nativePath]});return a!==1&&logger66().throw(`copyIccProfile_() wrote no ICC profile`,{src:e.nativePath,dest:n.nativePath,updated:a}),n.clear(),!0}finally{await r.unlink(`trace`)}}})}function clearCache(){heifThumbnailerPath.unset(),getFfmpegHeifToolDetails.unset(),ffmpegHeifDetails.unset()}later(()=>{ee().on(`clearCache`,clearCache),ee().on(`clearToolCache`,clearCache)});async function heif2Thumb(e,n){if(!(isMac||await heifThumbnailerPath()==null)){n=Math.max(512,n??512);try{return await timeExcludingNested({name:`img.heif.thumb`,thunk:()=>withImageCache_(e,`heif-`+n,`.png`,r=>_heifThumb2png_(e,r,n))})}catch(n){logger66().info(`heif2Thumb_(): no thumbnail available`,{src:e.nativePath,error:n});return}}}async function _heifThumb2png_(e,n,r){let a=await heifThumbnailerPath();if(a!=null)try{await stdoutResult_(a,[`-s`,r.toFixed(),e.nativePath,n.base],{timerName:`proc.heifConvert`,cwd:n.dir,timeoutMs:Settings2.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await n.clear().isEmptyFile(KB)&&logger66().throw(`heif2Thumb_() failed: destination file was empty`,{src:e,dest:n})}catch(n){logger66().throw(`heif2Thumb_() failed`,{error:n,src:e.nativePath})}}var sipsPath=lazy2(async()=>isMac?pathTo2({tool:`sips`}):void 0);async function sips2jpeg_(e){return withImageCache_(e,`heif`,`.jpeg`,n=>sips2jpegTo_(e,n))}function sips2jpegTo_(e,n){return stdoutResult_(`sips`,[`-s`,`format`,`jpeg`,`-s`,`formatOptions`,String(Settings2.previewQuality.valueOrDefault),e.nativePath,`--out`,n.base],{timerName:`proc.sips`,cwd:n.dir,timeoutMs:Settings2.taskTimeoutMs.valueOrDefault})}var logger67=lazy2(()=>mkLogger(`img.Heif`)),getHeifSupportDetails=lazy2(async()=>{try{if(isMac){try{let e=await sipsPath();if(!blank(e))return{desc:`sips`,path:e,version:osNameMac(),isSupportedVersion:!0}}catch(e){logger67().warn(`Failed to find the sips tool (either in PATH or /usr/bin).`,e)}return}return await getFfmpegHeifToolDetails()}catch(e){logger67().warn(`Failed to get HEIF decoder details`,{error:e});return}});async function isHeifSupported(){return(await getHeifSupportDetails())?.isSupportedVersion===!0}var macSupportsAvif=lazy2(()=>!isMac||semVerSatisfies(macProductVersion(),`>=13`));async function heif2img_(e){return isMac?sips2jpeg_(e):(await throwUnlessHeifSupported_(e),ffmpegHeif2img_(e))}async function throwUnlessHeifSupported_(e){(await getHeifSupportDetails())?.isSupportedVersion!==!0&&logger67().throw(`HEIF support is missing`,{src:e.nativePath})}function clearCache2(){getHeifSupportDetails.unset(),getHeifThumbnailerDetails.unset()}later(()=>{ee().on(`clearCache`,clearCache2),ee().on(`clearToolCache`,clearCache2)});var getHeifThumbnailerDetails=lazy2(async()=>{try{let e=await heifThumbnailerPath();if(blank(e))return;{let n;return hasApt()&&(n=(await aptInstalledVersion(e))?.find(e=>e.pkg===`heif-thumbnailer`)?.version),blank(n)&&hasPacman()&&(n=(await pacmanInstalledVersion(e))?.version),{desc:`heif-thumbnailer`,path:e,version:toNotBlank(n)??`(unknown)`,isSupportedVersion:blank(n)?void 0:semVerSatisfies(n,`>=1.18.0`)}}}catch(e){logger67().warn(`Failed to get heif-thumbnailer tool details`,{error:e});return}}),import_luxon3=require("luxon"),import_node_fs29=require("node:fs");function filestamp({when:e=new Date,includeMillis:n=!1}={}){return[e.getFullYear(),pad2(e.getMonth()+1),pad2(e.getDate()),`-`,pad2(e.getHours()),pad2(e.getMinutes()),pad2(e.getSeconds()),...n?[pad3(e.getMilliseconds())]:[]].join(``)}var import_node_os18=__toESM(require("node:os"));function isTooBusy(){if(Settings2.cpuBusyPercent.valueOrDefault===0)return!1;let e=tooBusyFor(CpuUsage.instance().busyPct());return e&&ee().emitRateLimited(`cpuTooBusy`),e}function tooBusyFor(e){return Settings2.cpuBusyPercent.valueOrDefault!==0&>e(e,busyLimitPct())}function busyLimitPct(){return clamp(1,100,Math.round(Settings2.cpuBusyPercent.valueOrDefault*4/3))}var notBusyLatch;function resolveOnNotBusy(){return isTooBusy()?notBusyLatch??=new Latch:Promise.resolve()}var CpuUsage=class e extends EndableInterval{#e=new Average(5);#t=new CpuTimes;#n=new Set;static instance=defer(()=>new e);constructor(){super({name:`CpuUsage()`,callback:()=>this.#i(),intervalMs:(isWin?20:10)*secondMs,rank:EndableRanks.first}),this.onEnds.push(()=>this.#n.clear())}get cpuCount(){return this.#t.cpuCount}idlePct(){return map(this.busyPct(),e=>100-e)}busyPct(){return this.#e.sampleAvg}onSample(e){this.#n.add(e),this.#t=new CpuTimes,this._setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0);for(let e of this.#n)e({kind:`rebase`});return()=>this.#n.delete(e)}#r=!1;#i(){let e=new CpuTimes,n=e.sample(this.#t);if(n.kind!==`unchanged`){this.#t=e,n.kind===`valid`&&this.#e.push(n.busyPct);for(let e of this.#n)e(n)}let r=tooBusyFor(this.busyPct());notBusyLatch!=null&&!r&&(notBusyLatch.resolve(),notBusyLatch=void 0),this.#r!==r&&ee().emitSync(`syncStateChanged`),this.#r=r}},CpuTimes=class{cpuCount;busyMs;idleMs;constructor(e=import_node_os18.default.cpus()){let n=0,r=0;for(let a of e)n+=a.times.user+a.times.nice+a.times.sys+a.times.irq,r+=a.times.idle;this.busyMs=n,this.idleMs=r,this.cpuCount=e.length}busyPct(e){let n=this.sample(e);return n.kind===`valid`?n.busyPct:void 0}sample(e){if(e.cpuCount!==this.cpuCount)return{kind:`rebase`};let n=this.busyMs-e.busyMs,r=this.idleMs-e.idleMs,a=n+r;return n<0||r<0?{kind:`rebase`}:gt0(a)?{busyPct:sigFigs(n/a*100,3),kind:`valid`}:{kind:`unchanged`}}};function busyPctFromLoad(){return isWin?void 0:sigFigs(100*(import_node_os18.default.loadavg()[0]/cpuInfo().length),3)}var FirstRepeatIntervalMs=minuteMs,MaxRepeatIntervalMs=30*minuteMs;function rowIdentity(e){return[e.from,e.state,e.type,e.path,e.url,e.details].map(e=>toS(e)).join(` `)}function repeatIntervalMs(e){return Math.min(MaxRepeatIntervalMs,FirstRepeatIntervalMs*2**e)}function pendingTally(e,n){return e==null||e.repeats===0?void 0:{repeats:e.repeats,elapsedMs:n-e.reportedAt,from:e.from,state:e.state}}function collapseRepeats(e){let{row:n,prior:r,now:a}=e,o=rowIdentity(n),s=r?.identity===o;return s&&a-r.reportedAt<repeatIntervalMs(r.restatements)?{write:!1,state:{...r,repeats:r.repeats+1}}:{tally:pendingTally(r,a),write:!0,state:{identity:o,from:n.from,state:n.state,reportedAt:a,repeats:0,restatements:s?r.restatements+1:0}}}function fmtRepeatTally(e){let n=`Last message repeated ${plur(e.repeats,`time`)}`;return gt0(e.elapsedMs)?n+` in `+fmtDuration(e.elapsedMs,{units:2,sep:` `}):n}var AssetFileSyncStates=strEnum(`unchanged`,`deleted`,`absent`,`trashed`,`unavailable`,`imported`,`updated`,`unknown`),SyncFileStates=strEnum(...AssetFileSyncStates.values,`canceled`,`excluded`,`failed`,`timeout`,`stalled`,`enqueued`,`started`,`validated`,`copied`,`blocklisted`,`note`,`warning`,`completed`),FileDoneStates=diff2(SyncFileStates.values,[`enqueued`,`started`,`validated`,`note`]),SyncDirStates=strEnum(`scanning`,`canceled`,`failed`,`timeout`,`stalled`,`unavailable`,`excluded`,`scanned`,`completed`),SyncReportStates=strEnum(...SyncFileStates.values,...SyncDirStates.values),AbortRegex=/\babort(?:ed|ing)?\b/i,TimeoutRegex=/\btimeout\b/i;function errorToState(e){let n=errorToS2(e);return isAbortError(e)||AbortRegex.test(n)?`canceled`:isTimeoutError(e)||TimeoutRegex.test(n)?`timeout`:`failed`}var FileStateDescriptions={enqueued:`the file looks promising, and will be attempted to be imported soon.`,excluded:`the file was excluded by import settings (extension, size, glob pattern, etc.). The details column will explain why.`,started:`the file was dequeued from the work queue, and is now going to be processed.`,unchanged:`the current file metadata already matches your library database, so no changes were needed.`,deleted:`the file was rejected by filters or deleted by the user.`,absent:`the file was previously imported but no longer exists on disk (the mountpoint is accessible but the file is gone).`,trashed:`the file was moved to the trash by request of the user.`,unavailable:`the file is temporarily inaccessible (e.g., the volume isn't currently mounted or the URI can't be resolved).`,validated:`the file's contents were checked for corruption, or the details column explains why they were not (validation is off by default for videos).`,imported:`the file was newly imported into the library.`,updated:`the file was already in the database but was re-imported because it changed on disk (e.g., mtime or file size differs).`,completed:`the current task was completed.`,blocklisted:`the file was blocklisted and files with the same SHA will not be imported in the future.`,failed:`something went wrong. The details column will explain why.`,timeout:`the file wasn't processed in a reasonable amount of time.`,stalled:`the file has been processing for an unusually long time. The details column will show how long.`,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:`something PhotoStructure did or found that is not an import, update, or failure, such as a tag rename or a check of an asset's files. The details column will explain what.`,warning:`something unexpected happened. The details column will explain what's going on.`,canceled:`PhotoStructure was shut down while the file was processed.`,unknown:`an internal error occurred during processing.`},DirStateDescriptions={scanning:`the directory contents are about to be read.`,scanned:`the directory contents were processed. Note that files within the directory will have been enqueued for processing, and may still be in progress.`,unavailable:`the directory is temporarily inaccessible (e.g., the volume isn't currently mounted, or a nested mountpoint is scanned separately).`,excluded:`the directory was excluded by settings (hidden, .nomedia, glob pattern). The details column will explain why.`,completed:`the root scanned directory and all its contents were processed.`,canceled:`PhotoStructure was shut down before the directory was processed.`,failed:`reading the directory contents failed.`,timeout:`reading the directory contents took too long.`,stalled:`the directory scan has been running for an unusually long time. The details column will show how long.`};function recordToBullets(e){return entries(e).map(([e,n])=>` - "${e}": ${n}`).join(`
|
|
544
|
+
`)}var StateLogLevels=new Map([[SyncFileStates.absent,LogLevels.info],[SyncFileStates.deleted,LogLevels.info],[SyncFileStates.warning,LogLevels.warn],[SyncFileStates.failed,LogLevels.warn],[SyncFileStates.timeout,LogLevels.warn],[SyncFileStates.stalled,LogLevels.warn],[SyncFileStates.canceled,LogLevels.warn]]);function logLevelForProgress(e){return e.state===`failed`&&PermissionErrorRegex.test(toS(e.details))?LogLevels.debug:StateLogLevels.get(e.state)??LogLevels.debug}var SyncReportClass=class{constructor(e,n,r,a,o,s,c,l,u,d={}){this.ts=e,this.at=n,this.path=r,this.type=a,this.state=o,this.from=s,this.elapsedMs=c,this.details=l,this.url=u,this.meta=d}ts;at;path;type;state;from;elapsedMs;details;url;meta},SyncReportHeaders=strEnum(...keys(new SyncReportClass(0,``,``,`file`,`unknown`,``,0,``,``)));function syncReportDir(){return librarySyncReportsDir()??PosixFile.for(logDir()).join(`sync-reports`)}function syncReportReadme(){return syncReportDir().join(`README.txt`)}var ensureSyncReportReadme=lazy2(()=>writeTextfile_(syncReportReadme().nativePath,wrap(`
|
|
545
|
+
|
|
546
|
+
Howdy from PhotoStructure!
|
|
547
|
+
|
|
548
|
+
This directory contains your recent "sync reports".
|
|
549
|
+
|
|
550
|
+
These files are written as your scan paths are examined for photos and videos.
|
|
551
|
+
|
|
552
|
+
PhotoStructure creates a new file when it restarts, when it completes importing a given scan path folder, and whenever the current file reaches "syncReportMaxLinesPerFile" rows. A single scan can therefore span several files: the first uses the plain name, and each later one adds a "-001", "-002", ... suffix counting the rolls so far. Every file is also stamped with the time it was opened, so the timestamps differ too -- sort by name to read a scan in order.
|
|
553
|
+
|
|
554
|
+
These are JSON Lines (.jsonl) files: each line is a complete JSON object describing one event. You can:
|
|
555
|
+
|
|
556
|
+
- open them in VSCode or any text editor (each line is one event).
|
|
557
|
+
- filter them with ripgrep: rg '"state":"failed"' *.jsonl
|
|
558
|
+
- process them with jq: jq 'select(.state=="imported")' *.jsonl
|
|
559
|
+
- convert to CSV for Excel/LibreOffice:
|
|
560
|
+
jq -r '[.ts,.at,.path,.state,.from,.elapsedMs,.details,.url]|@csv' *.jsonl
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
Field descriptions
|
|
564
|
+
==================
|
|
565
|
+
|
|
566
|
+
The "ts" field is the timestamp for the row, in millis from 1970-01-01.
|
|
567
|
+
|
|
568
|
+
The "at" field is ts in ISO format with only second resolution.
|
|
569
|
+
|
|
570
|
+
The "path" field is the native path of the directory or file. It will be empty for messages about system state.
|
|
571
|
+
|
|
572
|
+
The "state" field explains why that row was added.
|
|
573
|
+
|
|
574
|
+
The "from" field specifies which codepath added the sync report row.
|
|
575
|
+
|
|
576
|
+
The "elapsedMs" field is only added to rows completing a given path, and records how long that process took.
|
|
577
|
+
|
|
578
|
+
The "details" field will include information about the path, like why a given file or folder was rejected.
|
|
579
|
+
|
|
580
|
+
The "url" field 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).
|
|
581
|
+
|
|
582
|
+
The "meta" field contains any additional structured metadata as a nested object.
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
Directory state values
|
|
586
|
+
======================
|
|
587
|
+
|
|
588
|
+
The "state" field for directories will be
|
|
589
|
+
|
|
590
|
+
${recordToBullets(DirStateDescriptions)}
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
File state values
|
|
594
|
+
=================
|
|
595
|
+
|
|
596
|
+
The "state" field for files will be
|
|
597
|
+
|
|
598
|
+
${recordToBullets(FileStateDescriptions)}
|
|
599
|
+
|
|
600
|
+
For more details see https://photostructure.com/go/sync-reports
|
|
601
|
+
|
|
602
|
+
`,{maxLineLen:80}).join(`
|
|
603
|
+
`))),SyncReportExt=`.jsonl`;function mkSyncReportPath(){let e=import_luxon3.DateTime.now();return syncReportDir().join(e.toFormat(`y-MM-dd`),filestamp({when:e.toJSDate(),includeMillis:!0})+`-sync-report`+SyncReportExt)}var syncReport=lazy2(()=>new SyncReport),SyncReport=class extends EndableWrapper{#e;#t;#n;#r=0;#i=new BoundedList(64);#a=[];disposeRolled(e){return disposeStream(e)}#o=0;#s=0;publishOpened(e,n){e<this.#o||(this.#o=e,this.#t=n,this.ee.emitSync(`open`,n))}#c=new Set;#l=0;ee=new TypedEventEmitterImpl;#u;constructor(){super(`fs.SyncReport()`,()=>this.close(),EndableRanks.predb),ensureSyncReportReadme()}get outputNativePath(){return this.#e?.nativePath??this.#i.last}get openedOutputNativePath(){return this.#t}get rowCount(){return this.#r}get outputFiles(){return[...this.#i]}get outputFilesSinceClose(){return[...this.#a]}maybeSystemData(e){isSyncService()&&this.writeSystemData(e)}writeSystemData(e){this.onProgress(e)}onProgress(e){if(this.ended){this.logger.warn(`onProgress() called after sync report ended`,{s:e,from:stack()});return}let n=fmtElapsedMs2(e);if(e==null||blank(e.state))return this.logger.error(`.onProgress(): invalid input`,{s:e,from:stack()});{this.logger.log(logLevelForProgress(e),`onProgress()`,e);let r=n.ts??Date.now(),a={path:toS(n.path),state:e.state,details:toS(e.details).trim().replace(/\r?\n/g,`; `)},o={ts:r,at:n.at??new Date(r).toISOString(),...a,...pick(n,`from`,`url`,`elapsedMs`,`meta`,`type`)};getDevEnvFlag(PS_SYNC_REPORT_STDOUT)&&process.stdout.write(stringify(e)+Newline),this.#d(o)}}#d(e){let n=Date.now(),{tally:r,write:a,state:o}=collapseRepeats({row:e,prior:this.#u,now:n});r!=null&&(this.emitRow(this.#f(r,e.ts)),this.#u=void 0),a&&this.emitRow(e),this.#u=o}#f(e,n){return{ts:n,at:new Date(n).toISOString(),path:``,state:e.state,from:e.from,details:fmtRepeatTally(e),meta:{repeats:e.repeats}}}onStreamError(e){this.#u=void 0,this.logger.error(`Write stream error`,e)}emitRow(e){e=fmtElapsedMs2(e),this.#m(),this.#h().write(stringify(e)+Newline),this.#r++}#p(){let e=Settings2.syncReportMaxLinesPerFile.valueOrDefault;return e>0&&this.#r>=e}#m(){if(this.#n==null||!this.#p())return;let e=this.#n;this.#n=void 0,this.#r=0,this.#l++,this.logger.info(`Rolling sync report`,{outputFile:this.#e});let n=this.disposeRolled(e).catch(e=>this.logger.warn(`Error disposing rolled sync report`,e)).finally(()=>this.#c.delete(n));this.#c.add(n)}#h(){if(this.#n==null||!this.#n.writable){let e=mkSyncReportPath().ensureNewSync_(this.#l>0?{emptyIsNew:!1,requireNumber:!0,startIndex:this.#l,leftPad:3}:{emptyIsNew:!1});this.#e=e,this.#i.push(e.nativePath),this.#a.push(e.nativePath),this.logger.info(`Opening new report: `+e),getDevEnvFlag(PS_SYNC_REPORT_STDOUT)&&stdoutWrite({syncReport:e.nativePath},!1);let n=this.#n=(0,import_node_fs29.createWriteStream)(e.nativePath);n.on(`error`,e=>{n===this.#n?this.onStreamError(e):this.logger.error(`Write stream error on a retired report`,e)});let r=++this.#s;this.#n.once(`open`,()=>this.publishOpened(r,e.nativePath))}return this.#n}async close(){try{this.logger.info(`Closing sync report`,{outputFile:this.#e});let e=Date.now(),n=pendingTally(this.#u,e);if(this.#u=void 0,n!=null)try{this.emitRow(this.#f(n,e))}catch(e){this.logger.warn(`Failed to write the closing repeat tally`,e)}let r=this.#n,a=r!=null||this.#a.length>0;return this.#n=void 0,this.#r=0,this.#l=0,this.#a=[],await Promise.all([...this.#c]),await disposeStream(r),a?this.#e:void 0}catch(e){this.logger.warn(`Error closing sync report`,e);return}}async wrapSystemOp_({from:e,fn_:n,meta:r}){let a=performance.now();this.writeSystemData({from:e,state:`started`,ts:Date.now()});try{let o=await n();return this.writeSystemData(fmtElapsedMs2({from:e,state:`completed`,elapsedMs:performance.now()-a,details:isString(o)?o:void 0,meta:{...r,result:o}})),o}catch(n){throw this.logger.warn(`wrapSystemOp_() caught error`,{error:n}),this.writeSystemData(fmtElapsedMs2({from:e,state:errorToState(n),details:errorToS2(n),elapsedMs:performance.now()-a,meta:r})),n}}async wrap_({path:e,from:n,type:r,fn_:a}){let o=performance.now();this.onProgress({path:e,from:n,type:r,state:SyncFileStates.started});try{let s=await a();s.elapsedMs=toGt0f(s.elapsedMs)??performance.now()-o;let c=s.state??(s.error==null?SyncFileStates.unknown:SyncFileStates.failed);return c===SyncFileStates.unknown&&this.logger.error(n+` returned result with no state!`+InternalErrorFlag,{path:e,result:s}),this.onProgress({path:e,from:n,type:r,...s,state:c}),s}catch(a){throw this.onProgress({path:e,from:n,type:r,state:errorToState(a),details:errorToS2(a),elapsedMs:performance.now()-o}),operationOwner()?.onFailureReported?.(a),a}}},reportIfCpuTooBusy=lazy2(()=>{ee().on(`cpuTooBusy`,()=>logTooBusy())}),logger68=defer(()=>mkLogger(`fs.SyncReport`)),logTooBusy=lazy2(()=>{let e=CpuUsage.instance().busyPct();syncReport().maybeSystemData({from:`cpuUsage`,state:`note`,details:`Current system load is too high to schedule more work`,meta:compactValues({loadCpuPct:busyPctFromLoad(),cpuBusyPct:e})}),logger68().warn(`Current system load is too high to schedule more work`,{cpuBusyPct:e,max:Settings2.cpuBusyPercent.valueOrDefault})},(isTest()?15:60)*secondMs),reportIfDoNotRun=lazy2(()=>{ee().on(`doNotRun`,e=>{syncReport().maybeSystemData(e)})});function fmtElapsedMs2(e){if(e.elapsedMs!=null){let n=toGt0f(e.elapsedMs);return n==null?delete e.elapsedMs:e.elapsedMs=roundMs(n),e}return e}var logger69=defer(()=>mkLogger(`tags.Orientation`));function extractRotation(e){if(e!=null)return isHeifMimeType(e.MIMEType)||isVideoMimeType(e.MIMEType)?orientationToRotation(e.Rotation)??normalizeRotation(e.Rotation):orientationToRotation(e.Orientation)??normalizeRotation(e.Rotation)}var NumericExifOrientationToRotation=new Map([[1,0],[6,90],[3,180],[8,270]]),ExifOrientationDescToRotation={"Horizontal (normal)":0,"Horizontal (Normal)":0,"Rotate 90 CW":90,"Rotate 180":180,"Rotate 270 CW":270};function orientationRequiresMirroring(e){return[2,4,5,7].includes(e)||toS(e).startsWith(`Mirror`)}function orientationToRotation(e){return logger69().tap({msg:`orientationToRotation`,result:blank(e)?void 0:isNumber(e)?NumericExifOrientationToRotation.get(e)??normalizeRotation(e):ExifOrientationDescToRotation[toS(e)],meta:{orientation:e}})}var import_node_path54=__toESM(require("node:path")),import_exiftool_vendored11=require("exiftool-vendored"),import_luxon11=require("luxon"),import_exiftool_vendored10=require("exiftool-vendored"),import_luxon10=require("luxon");function isJson(e){return e==null||isPrimitive(e)?!0:Array.isArray(e)?e.every(isJson):isObject(e)?e.constructor===Object&&Object.entries(e).every(([e,n])=>isJson(e)&&isJson(n)):!1}function isJsonObject(e){return isObject(e)&&!Array.isArray(e)&&isJson(e)}var import_exiftool_vendored9=require("exiftool-vendored"),import_exiftool_vendored8=require("exiftool-vendored"),import_luxon9=require("luxon");function datedToMillis(e){if(!(e==null||isString(e)))return isNumber(e)?e:e instanceof Date?e.getTime():e.toMillis?.()}var import_exiftool_vendored7=require("exiftool-vendored"),import_luxon8=require("luxon"),import_node_util15=require("node:util"),import_exiftool_vendored3=require("exiftool-vendored");function hasTime(e){if(!isObject(e))return!1;if(e instanceof Date)return!0;let n=e;return gt0(n.hour)||gt0(n.minute)||gt0(n.second)||gt0(n.millisecond)}function isExifDateTime(e){return e instanceof import_exiftool_vendored3.ExifDateTime}function getYear(e){return e instanceof Date?e.getFullYear():e?.year}function getMonth(e){return e instanceof Date?e.getMonth()+1:e?.month}function getDay(e){return e instanceof Date?e.getDate():e?.day}function getHour(e){return e instanceof Date?e.getHours():e?.hour}function getMinute(e){return e instanceof Date?e.getMinutes():e?.minute}function getSecond(e){return e instanceof Date?e.getSeconds():e?.second}function getMillisecond(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}function getCentisecond(e){return map(getMillisecond(e),e=>Math.floor(e/10))}var import_exiftool_vendored4=require("exiftool-vendored"),import_luxon4=require("luxon");function isDateTime(e){return import_luxon4.DateTime.isDateTime(e)??!1}function hasZone(e){return e==null||isNumber(e)?!1:isExifDateTime(e)||isDateInterval(e)?e.hasZone:isDateTime(e)?e.zone!=null&&e.zone.type!==`local`&&(0,import_exiftool_vendored4.isZoneValid)(e.zone):!1}function getZone(e){if(!(e==null||e instanceof Date)){if(isDateTime(e))return!e.isValid||e.zone==null||(0,import_exiftool_vendored4.isZoneUnset)(e.zone)?void 0:e.zone;if(isExifDateTime(e)||isDateInterval(e))return(0,import_exiftool_vendored4.normalizeZone)(e.zone)}}function getZoneName(e){return getZone(e)?.name}var import_exiftool_vendored5=require("exiftool-vendored"),import_luxon5=require("luxon");function isValidZone(e){return(0,import_exiftool_vendored5.normalizeZone)(e)!=null}function zoneToTzOffsetMinutes(e,n){if(e==null||n==null)return;let r=(0,import_exiftool_vendored5.normalizeZone)(n);return!0===r?.isValid?r.offset(e):void 0}var TimezoneOffsetRE=import_exiftool_vendored5.TimezoneOffsetRE;function isoToOffsetMinutes(e){if((0,import_exiftool_vendored5.isUTC)(e))return 0;let n=(0,import_exiftool_vendored5.parseTimezoneOffsetToMinutes)(e);if(n!=null)return n;let r=(0,import_exiftool_vendored5.extractZone)(e);return r==null?void 0:(0,import_exiftool_vendored5.normalizeZone)(r.zone)?.offset(Date.now())}function timezoneOffsetFromRegExpMatch(e){let n=(0,import_exiftool_vendored5.parseTimezoneOffsetMatch)(e);return n!=null&&isValidZone(n.offsetMinutes)?n.offsetMinutes:void 0}var import_luxon7=require("luxon"),import_exiftool_vendored6=require("exiftool-vendored"),import_luxon6=require("luxon"),datesBeforeAreEstimated=lazy2(()=>isoToLocal(Settings2.datesBeforeAreEstimated.valueOrDefault)??isoToLocal(Settings2.datesBeforeAreEstimated.defaultValue));function localToDateObject(e,n){if(!gt0(e))return;let r=e,a=()=>{let e=r%100;return r=Math.floor(r/100),e},o=a(),s=a(),c=a(),l=a(),u=a(),d=a(),f=r;if(!within(1800,2100,f))return;let h=(0,import_exiftool_vendored6.normalizeZone)(n);if(d===0)return{year:f,month:void 0,day:void 0,hour:void 0,minute:void 0,second:void 0,millisecond:void 0,zone:h};if(u===0)return within(1,12,d)?{year:f,month:d,day:void 0,hour:void 0,minute:void 0,second:void 0,millisecond:void 0,zone:h}:void 0;if(l===0&&c===0&&s===0&&o===0)return within(1,12,d)&&within(1,31,u)?{year:f,month:d,day:u,hour:void 0,minute:void 0,second:void 0,millisecond:void 0,zone:h}:void 0;if(within(1,12,d)&&within(1,31,u)&&within(0,23,l)&&within(0,59,c)&&within(0,59,s)&&within(0,99,o))return{year:f,month:d,day:u,hour:l,minute:c,second:s,millisecond:o*10,zone:h}}function localIsFuzzy(e){return localIsImprecise(e)||localIsBeforeDigitalCameras(e)}function localIsImprecise(e){return e==null||e%1e6==0}function localIsBeforeDigitalCameras(e){return e==null||e<datesBeforeAreEstimated()}function isoToLocal(e){let n=isoToDated(e);if(n)return`toMillis`in n&&typeof n.toMillis==`function`?tsToLocal(n.toMillis()):datedToLocal(n)}function datedToLocalMinute(e){if(isNumber(e))return Math.floor(tsToLocal(e)/1e4);let n=0;for(let r of[getYear,getMonth,getDay,getHour,getMinute])n=n*100+(r(e)??0);return n}function datedToLocalSec(e){return isNumber(e)?Math.floor(tsToLocal(e)/100):datedToLocalMinute(e)*100+(getSecond(e)??0)}function datedToLocal(e){return isNumber(e)?tsToLocal(e):datedToLocalSec(e)*100+(getCentisecond(e)??0)}function localToDateTime({local:e,zone:n,precisionMs:r}){let a=localToDateObject(e,n);if(a){if(a.month==null||a.day==null)return FuzzyDate.for(a);if(gt0(a.hour)||gte0(a.minute)||gte0(a.second)||gte0(a.millisecond)||lt(r,dayMs)){let e=dateObjectToDateTime(a);if(e)return e}return FuzzyDate.for(a)}}function tsToLocal(e,n){return datedToLocal(n==null?import_luxon6.DateTime.fromMillis(e).toLocal():import_luxon6.DateTime.fromMillis(e,{zone:n}))}var logger70=lazy2(()=>mkLogger(`date.ValidDate`)),badDates=lazy2(()=>compact(Settings2.badDates.values.map(e=>isoToDated(e)))),badDatesLocal=lazy2(()=>compact(badDates().map(e=>datedToLocal(e)))),badDatesTs=lazy2(()=>compact(badDates().map(e=>datedToMillis(e))));function toValidMillis(e){return isValidDate(e)?e:void 0}function isValidDate(e){if(e==null)return!1;let n=whyNotValidDate(e);return logger70().tap({msg:`isValidDate()`,result:n==null,meta:{d:e,why:n}})}var BadDateString=String(new Date(`bad`)),MaxValidTs=lazy2(()=>{let e=Settings2.maxValidFutureMs.valueOrDefault;return gt0(e)?Date.now()+Math.max(e,hourMs):void 0},10*minuteMs);function whyNotValidDate(e){try{if(!isDated(e)&&!isNumber(e))return`not Dated`;if(String(e)===BadDateString)return BadDateString;let n=compact([e.invalidExplanation]);if(n.length===0&&n.push(...whyInvalidYMD(getYear(e),getMonth(e),getDay(e))),e instanceof Date&&isNaN(e.getTime())&&n.push(`not valid js Date`),n.length===0){let r=MaxValidTs();r!=null&>2(datedToMillis(e),r)&&n.push(`date is too far in the future: see `+Settings2.maxValidFutureMs.key)}return badDatesTs().includes(datedToMillis(e))?n.push(`bad date (via millis)`):badDatesLocal().includes(datedToLocal(e))&&n.push(`bad date (via localtime)`),toNotBlank(uniq(compactBlanks(n)).join(`; `))}catch(n){return logger70().warn(`whyNotValidDate() caught error`,{input:e,error:n}),errorToS2(n)}}function whyInvalidYMD(e,n,r){let a=[];if(isNumber(e)||a.push(`year is not a number`),lt(e,Settings2.minValidYear.valueOrDefault)&&a.push(`year is less than `+Settings2.minValidYear.key),n==null&&r!=null&&a.push(`year and day is set but month is not`),(lt(n,1)||gt2(n,12))&&a.push(`month is invalid`),n!=null&&(lt(n,1)||gt2(n,12))&&a.push(`month is invalid`),isNumber(e)&&isNumber(n)&&isNumber(r)){let o=import_luxon7.DateTime.fromObject({year:e,month:n,day:r});o.isValid||a.push(o.invalidExplanation??`not valid`)}return compact(a)}function validYMD(e,n,r){return e!=null&&whyNotValidDate({year:e,month:n,day:r})==null}var FuzzyDate=class e{constructor(e,n,r){this.year=e,this.month=n,this.day=r}year;month;day;static fromISO(e){if(!blank(e))return this.for(ISO_YMD_RE.exec(e)?.groups??ISO_YMD_LAX_RE.exec(e)?.groups)}static fromJSON(e){return this.for(e)}toJSON(){return pick(this,`year`,`month`,`day`)}static for(n){let r=toGt0(n?.year);if(n==null||r==null||r<Settings2.minValidYear.valueOrDefault)return;let a=n instanceof e?n:new e(r,toGt0(n.month),toGt0(n.day));return a.isValid?a:void 0}static localToday(){return toFuzzyDate(new Date)}#e=lazy2(()=>whyNotValidDate(this.toDateTime()));get invalidExplanation(){return this.#e()}get isValid(){return this.#e()==null}toString(){return this.toISOString()}[import_node_util15.inspect.custom](){return this.toISOString()}toISOString(){return compact([this.year,this.month,this.day]).map(e=>pad2(e)).join(`-`)}toLocal(){return(this.year*1e4+(this.month??0)*100+(this.day??0))*1e8}toDateTime(){return import_luxon8.DateTime.fromObject(pick(this,`year`,`month`,`day`))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}plus(n){let r=this.toDateTime().plus(n);return new e(r.year,this.month==null?void 0:r.month,this.day==null?void 0:r.day)}following(){let n=this.toDateTime(),r=this.day==null?this.month==null?pick(n.plus({year:1}),`year`):pick(n.plus({month:1}),`year`,`month`):pick(n.plus({day:1}),`year`,`month`,`day`);return new e(r.year,r.month,r.day)}},ignorableSubpaths=[];function toExifDateTime(e,n){if(e instanceof import_exiftool_vendored7.ExifDateTime&&(n==null||e.zone===n))return e;if(e==null||!hasTime(e))return;let r=mapNotBlank(n,n=>zoneToTzOffsetMinutes(datedToMillis(e),n));if(n==null||r!=null)return map(getYear(e),a=>map(getMonth(e),o=>map(getDay(e),s=>map(getHour(e),c=>dateObjectToExifDateTime({year:a,month:o,day:s,hour:c,minute:getMinute(e)??0,second:getSecond(e)??0,millisecond:getMillisecond(e),tzoffsetMinutes:r,rawValue:e.rawValue,zone:n})))))}function toFuzzyDate(e){return map(e,e=>map(getYear(e),n=>new FuzzyDate(n,getMonth(e),getDay(e))))}function diffMillis(e,n){let[r,a]=[e,n].map(datedToMillis);return r==null||a==null?void 0:r-a}function closeTo2(e,n,r){return mapOr(diffMillis(e,n),e=>Math.abs(e)<r,()=>!1)}function setZone(e,n,r){let a={...compactValues(r),keepLocalTime:r?.keepLocalTime??!hasZone(e)},o=(0,import_exiftool_vendored7.normalizeZone)(n);return e==null||o==null||!hasTime(e)?void 0:e instanceof DateInterval?e.setZone(o,a):toExifDateTime(e)?.setZone(o,a)}var logger71=defer(()=>mkLogger(`date.Dated`));function isDated(e){return e!=null&&(e instanceof FuzzyDate||e instanceof import_exiftool_vendored8.ExifDate||e instanceof import_exiftool_vendored8.ExifDateTime||e instanceof Date||e instanceof DateInterval||isDateTime(e)||isDateObject(e))}function toDated(e){return isDated(e)?e:void 0}function toDate2(e){if(e!=null)return typeof e==`number`?new Date(e):e instanceof Date?e:maybeCall(e,`toJSDate`)??maybeCall(e,`toDate`)}function datedToStartTs(e){if(e!=null)return e instanceof DateInterval?e.start.toMillis():e instanceof import_exiftool_vendored8.ExifDate?e.toMillis(0):datedToMillis(e)}function datedToEndTs(e){if(e!=null)return e instanceof DateInterval?e.end.toMillis():e instanceof import_exiftool_vendored8.ExifDate?e.toMillis(dayMs):e instanceof FuzzyDate?e.following().toMillis()-1:map2Numeric(datedToMillis(e),datedToPrecisionMs(e),(e,n)=>e+n)}function datedToStartDateTime(e){return e instanceof DateInterval?e.start.toDateTime():e instanceof import_exiftool_vendored8.ExifDate?import_luxon9.DateTime.fromObject(e):datedToDateTime(e)}function datedToDateTime(e){try{return e==null||isString(e)||isNumber(e)?void 0:isDateTime(e)?e:e instanceof import_exiftool_vendored8.ExifDateTime||e instanceof FuzzyDate?e.toDateTime():e instanceof DateInterval?e.middle.toDateTime():e instanceof Date?import_luxon9.DateTime.fromJSDate(e):dateObjectToExifDateTime(e)?.toDateTime()}catch(n){logger71().warn(`datedToDateTime() failed`,{d:e,error:n});return}}function datedToPrecisionMs(e){if(e instanceof DateInterval)return e.precisionMs;if(hasTime(e)){if(gt0(getMillisecond(e)))return 0;if(gt0(getSecond(e)))return secondMs-1;if(gt0(getMinute(e)))return minuteMs-1;if(gt0(getHour(e)))return hourMs-1}return gt0(getDay(e))?dayMs-1:gt0(getMonth(e))?monthMs-1:yearMs-1}var Precisions=[yearMs,monthMs,dayMs,hourMs,minuteMs,secondMs].map(e=>e-1),MAX_PRECISION_MS=Precisions[0];function datedOverlap({a:e,b:n,aPrecisionMs:r,bPrecisionMs:a}){if(e==null||n==null)return!1;if(r??=datedToPrecisionMs(e),a??=datedToPrecisionMs(n),_datedOverlap(e,n,r,a))return!0;let o=getZone(e),s=getZone(n);return o==null&&s!=null&&(e=setZone(e,s)??e),s==null&&o!=null&&(n=setZone(n,o)??n),_datedOverlap(e,n,r,a)}function datedToBoundaries(e,n){let r=datedToStartTs(e),a=datedToEndTs(e);if(r!=null&&a!=null)return gt0(n)&&n>a-r?{start:Math.round((r+a)/2-n/2),end:Math.round((r+a)/2+n/2)}:{start:r,end:a}}function _datedOverlap(e,n,r,a){let[o,s]=sortBy([datedToBoundaries(e,r),datedToBoundaries(n,a)],e=>e?.start);return o==null||s==null?!1:o!=null&&s!=null&&(o.start===s.start||o.end>=Math.min(s.start,s.end))}function isoToDated(e,n){return blank(e)?void 0:DateInterval.fromISO(e,n)??parseExifDateTime(e,n)??FuzzyDate.fromISO(e)}function datedToRawValue(e){if(isObject(e)&&`rawValue`in e){let n=e.rawValue;if(!blank(n))return n}}function datedToYMD(e,n=`-`){return compact([getYear(e),getMonth(e),getDay(e)]).map(e=>pad2(e)).join(n)}function datedToISO(e,n,r){if(e!=null)return e instanceof DateInterval?e.toString({includeOffset:n}):!hasTime(e)||(r??datedToPrecisionMs(e))>=dayMs?datedToYMD(e):toExifDateTime(e,getZoneName(e))?.toISOString({includeOffset:n})}var ExifFmt=`yyyy:MM:dd HH:mm:ss.SSS`,ExifFmtWithZone=ExifFmt+`ZZ`;function datedToEXIF(e){if(e==null)return;if(e instanceof DateInterval)return datedToEXIF(e.middle);let n=isNumber(e)?import_luxon9.DateTime.fromMillis(e):datedToDateTime(e);return n==null||!n.isValid?void 0:n.toFormat(hasZone(e)?ExifFmtWithZone:ExifFmt)}var dateIntervalRE=lazy2(()=>concatRegexp([/^/,/(?<start>\d{2,}[-+\dTZ:.,]+?)/i,/(?<solidus>:--|\/)/,/(?<end>\d{2}[-+\dTZ:.,]+)/,RegExpOptional.from(/\/(?<index>\d+)\/(?<splits>\d+)/),/$/]));function edtField({start:e,end:n,middle:r,field:a}){return e[a]!=null&&n[a]!=null?r[a]:void 0}var Fields=[`year`,`month`,`day`,`hour`,`minute`,`second`,`millisecond`];function isDateInterval(e){return e instanceof DateInterval}var DateInterval=class e{constructor(e,n,r,a=0,o=1){this.start=e,this.middle=n,this.end=r,this.index=a,this.splits=o,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=Fields.map(a=>edtField({start:e,middle:n,end:r,field:a}))}start;middle;end;index;splits;static fromISO(n,r){let a=dateIntervalRE().exec(toS(n).trim())?.groups;return a==null?void 0:e.for(parseExifDateTime(a.start,r),parseExifDateTime(a.end,r),toInt(a.index),toInt(a.splits))}toJSON(){return{start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for(map(e.start,e=>import_exiftool_vendored9.ExifDateTime.fromJSON(e)),map(e.end,e=>import_exiftool_vendored9.ExifDateTime.fromJSON(e)),e.index,e.splits)}static for(n,r,a=0,o=1){if(n==null||!n.isValid||r==null||!r.isValid)return;o=clamp(1,1e3,toInt(o,{defaultValue:1})),a=clamp(0,o-1,toInt(a,{defaultValue:0})),n.hasZone&&!r.hasZone&&n.zone!=null?r=r.setZone(n.zone)??r:!n.hasZone&&r.hasZone&&r.zone!=null&&(n=n.setZone(r.zone)??n);let s=n.toMillis(),c=(r.toMillis()-s)/(o+1)*(a+1),l=n.plus({milliseconds:c});return l==null?void 0:new e(n,l,r,a,o)}year;month;day;hour;minute;second;millisecond;get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max(datedToPrecisionMs(this.end),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={}){let n=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return(this.index!==0||this.splits!==1)&&n.push(this.index.toString(),this.splits.toString()),n.join(`/`)}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===datedOverlap({a:this,b:e})}setZone(n,r){return new e(this.start.setZone(n,r)??this.start,this.middle.setZone(n,r)??this.middle,this.end.setZone(n,r)??this.end,this.index,this.splits)}},m=lazy2(()=>{let e=new CaseInsensitiveMap;for(let n of[`en-US`,void 0]){e.set(`Sept`,9),e.set(`Sept.`,9);for(let r of[`short`,`long`]){let a=new Intl.DateTimeFormat(n,{month:r});times(12,o=>{let s=a.format(new Date(2017,o));e.set(s,o+1),r===`short`&&n===`en-US`&&e.set(s+`.`,o+1)})}}return e});function monthName2index(e){return e==null?void 0:m().get(e)}function monthNames(){return sort([...m().keys()])}var logger72=lazy2(()=>mkLogger(`date.FuzzyDateParser`));function extractDateFromPath(e){return logger72().tap({msg:`extractDateFromPath`,result:FuzzyDateParser.instance().extractDateFromPath(e),meta:{path:e}})}var nonNumericLookbackRE=/(?<!\d)/,yearRE=/(?<year>(?:18|19|20)\d{2})/,yearishRE=/(?<year>(?:18|19|20)?\d{2})/,monthRE=/(?<month>[0-3]\d)/,monthishRE=/(?<month>[0-3]?\d)/,dayRE=/(?<day>[1-3]\d|0[1-9])/,dayishRE=/(?<day>[1-3]\d|0?[1-9])/,hourRE=/(?<hour>1\d|2[0-3]|0\d)/,minuteRE=/(?<minute>[0-5]\d)/,secondRE=/(?<second>[0-5]\d)/,seps=/([-.,:_/ |])/,optSeps=RegExp(seps.source+`?`),subsecRE=/(?<subsec>\.\d+)?/,ISO_YMD_RE=concatRegexp([/^/,yearRE,RegExpOptional.from(/-/,monthRE,RegExpOptional.from(/-/,dayRE)),/$/]),ISO_YMD_LAX_RE=concatRegexp([/^/,yearishRE,RegExpOptional.from(/-/,monthishRE,RegExpOptional.from(/-/,dayishRE)),/$/]);function parseDateTime(e,n){let r=parseDated({input:e,defaultZone:n,descPredicate:e=>/DateTime/i.test(e)});return isDateTime(r)?r:isExifDateTime(r)?r.toDateTime():void 0}var format2regex=new Map,systemLocale=lazy2(()=>new Intl.DateTimeFormat().resolvedOptions().locale);function parseLocales(){return uniq(compactBlanks([import_luxon10.Settings.defaultLocale,systemLocale(),`en-US`]))}var leadingLetterRE=RegExp(`^\\p{L}`,`u`);function matchWithoutTrailingLetter(e,n){e.lastIndex=0;let r;for(;(r=e.exec(n))!=null;){let a=n.slice(r.index+r[0].length);if(!leadingLetterRE.test(a)){let n={value:r[0],index:r.index};return e.lastIndex=0,n}e.lastIndex=r.index+1}}function extractDateTime(e,n,r){try{let a=parseLocales();for(let o of a){let a=parseExifDateTimeFormat({input:e,format:n,defaultZone:r,locale:o});if(a!=null)return a}let o;for(let s of a){let a=getOrSet(format2regex,s+`|`+n,()=>{let e=import_luxon10.DateTime.fromFormatExplain(import_luxon10.DateTime.now().toFormat(n,{locale:s}),n,{locale:s});if(!(e.regex instanceof RegExp)){logger72().warn(`extractDateTime() failed to parse format`,{format:n,locale:s});return}let r=stripPrefixSuffix(e.regex.source,{prefix:`^`,suffix:`$`});return new RegExp(r,`gi`)}),c=a==null?void 0:matchWithoutTrailingLetter(a,e);if(c==null)continue;let l=parseExifDateTimeFormat({input:c.value,format:n,defaultZone:r,locale:s});l!=null&&(o==null||c.index===o.index&&c.value.length>o.length)&&(o={dateTime:l,index:c.index,length:c.value.length})}return o?.dateTime}catch(r){logger72().debug(`unexpected error thrown from extractDateTime()`,{input:e,format:n,error:r});return}}function*parsers(e){yield{desc:`DateInterval.fromISO`,f:e=>DateInterval.fromISO(e)},yield{desc:`parseExifDateTime`,f:n=>parseExifDateTime(n,e.defaultZone)},yield{desc:`ExifDateTime.fromRFC2822`,f:parseExifDateTimeFromRFC2822};for(let n of uniq([...compactBlanks(Settings2.extraDateTimeZoneSuffixes.values),``]))for(let r of compactBlanks(Settings2.extraDateTimeFormats.values)){let a=blank(n)?r:r+` `+n;yield{desc:`extractDateTime(${a})`,f:r=>extractDateTime(r,a,blank(n)?e.defaultZone:void 0)}}if(e.includeDate===!0&&(yield{desc:`ExifDate.fromExifStrict`,f:e=>import_exiftool_vendored10.ExifDate.fromExifStrict(e)}),e.includeFuzzyDate===!0)for(let e of FuzzyDateParser.instance().allParsers)yield{desc:`FuzzyDateParser `+e.source,f:n=>e.apply(n)}}function parseDated({input:e,defaultZone:n,includeDate:r=!0,includeFuzzyDate:a=!0,descPredicate:o=()=>!0}){if(e==null)return;if(isJsonObject(e)&&!isString(e)&&(e=fromJsonObject(e)),isDated(e))return e;let s=uniq(compactBlanks(toA(e)).map(stripDSC));if(s.length!==0){for(let{desc:e,f:c}of parsers({defaultZone:n,includeDate:r,includeFuzzyDate:a}))if(o(e))for(let e of s){let n=c(e);if(n!=null&&isValidDate(n))return n}}}var FuzzyDateParser=class e{constructor(e={}){this.opts=e,e.fuzzyDateParsing??Settings2.fuzzyDateParsing.watchLater(()=>this.#t()),e.fuzzyYearParsing??Settings2.fuzzyYearParsing.watchLater(()=>this.#t()),this.#t()}opts;static instance=lazy2(()=>new e);ymdParsers=[];ymParsers=[];yParsers=[];allParsers=[];get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??Settings2.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??Settings2.fuzzyYearParsing.valueOrDefault}parse(e,n=this.allParsers){for(let r of n){let n=r.apply(e);if(n!=null)return n}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}#e(e){let n=new Parser2(e);n.hasDay?this.ymdParsers.push(n):n.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(n):this.fuzzyYearParsing&&this.yParsers.push(n)}#t(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;let e=new RegExpEscaped(`(?<monthname>`+monthNames().map(escapeRegExp).join(`|`)+`)`),n=new RegExpEscaped(`\\2`);this.#e([yearRE,seps,monthishRE,n,dayishRE]),this.#e([yearRE,optSeps,monthRE,n,dayRE]),this.#e([yearRE,optSeps,e,n,dayishRE]);let r=new RegExpEscaped(`,?\\2`);this.#e([e,optSeps,dayishRE,r,yearRE]),this.#e([dayishRE,optSeps,e,r,yearRE]),this.#e([/^(?<year>\d\d\d\d):(?<month> {2}|\d\d):(?<day> {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),this.#e([yearRE,seps,monthishRE]),this.#e([e,seps,yearRE]),this.#e([yearRE,seps,e]),this.#e([yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){logger72().error(`Failed to setup fuzzy date parsers`,{error:e})}}extractDateFromPath(e){if(!Settings2.usePathsToInferDates.valueOrDefault)return;ignorableSubpaths.forEach(n=>{startsWith(e,n)&&e.splice(0,n.length)}),e=e.filter(e=>notBlank(e)&&e.match(ignorableDCF)==null);let n=[...e].reverse();for(let e of n){let n=parseDated({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(n!=null)return n}return this.parseYMD(n.slice(1,4).join(` `))??this.parseYMD(e.slice(0,-1).join(` `))??first(n,e=>this.parseYM(e))??this.parseYM(e.join(` `))??first(n.slice(1),e=>this.parseY(e))}},Parser2=class{regex;constructor(e){this.regex=concatRegexp([nonNumericLookbackRE,...e,/(?:$|\D)/],`i`)}get source(){return this.regex.source}get hasDay(){return this.source.includes(`(?<day>`)}get hasMonth(){return this.source.includes(`(?<month>`)||this.source.includes(`(?<monthname>`)}apply(e){let n=this.regex.exec(e)?.groups;if(n!=null)return FuzzyDate.for({year:toInt(n.year),month:toInt(n.month)??monthName2index(n.monthname),day:toInt(n.day)})}},ignorableDCF=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i;function concatDateTime(e,n){if(!(e instanceof import_exiftool_vendored11.ExifDate)||!e.isFullDate()||!(n instanceof import_exiftool_vendored11.ExifTime))return;let r=new import_exiftool_vendored11.ExifDateTime(e.year,e.month,e.day,n.hour,n.minute,n.second,n.millisecond,void 0,e.rawValue+` `+n.rawValue,n.zone,n.inferredZone);return r.isValid?r:void 0}function parseExifDateTimeFormat({input:e,format:n,defaultZone:r,locale:a}){return blank(e)?void 0:import_exiftool_vendored11.ExifDateTime.fromDateTime(import_luxon11.DateTime.fromFormat(e,n,{zone:r??import_exiftool_vendored11.UnsetZone,setZone:!0,locale:a}),{rawValue:e,unsetMilliseconds:!0})}function parseExifDateTimeFromRFC2822(e){return blank(e)?void 0:import_exiftool_vendored11.ExifDateTime.fromDateTime(import_luxon11.DateTime.fromRFC2822(e,{zone:import_exiftool_vendored11.UnsetZone,setZone:!0}))}function parseExifDateTime(e,n){return blank(e)?void 0:import_exiftool_vendored11.ExifDateTime.from(e,n)??parseExifDateTimeRe(e,ymd_hmsRegExp(),n)}function parseExifDateTimeRe(e,n,r){let a=n.exec(e);if(a==null||isEmptyObj(a.groups))return;let{year:o,month:s,day:c,hour:l,minute:u,second:d}=mapEntries(a.groups,(e,n)=>toInt(n));if(o==null||s==null||c==null||!Settings2.fuzzyDateParsing.valueOrDefault&&(l==null||u==null))return;let f=map(toFloat(a.groups.subsec),e=>within(0,1,e)?Math.round(e*1e3):void 0),h=timezoneOffsetFromRegExpMatch(a),_=(0,import_exiftool_vendored11.normalizeZone)(h)?.formatOffset(import_luxon11.DateTime.fromObject({year:o,month:s,day:c}).toMillis(),`short`)??r;return dateObjectToExifDateTime({year:o,month:s,day:c,hour:l??0,minute:u??0,second:d??0,millisecond:f,zone:_,rawValue:e,tzoffsetMinutes:h})}var sep5=/[-:_\s]?/,ymd_hmsRegExp=lazy2(()=>concatRegexp([nonNumericLookbackRE,yearRE,sep5,monthRE,sep5,dayRE,/[T\s]/,hourRE,sep5,minuteRE,sep5,secondRE,subsecRE,/\s?/,RegExpOptional.from(TimezoneOffsetRE)]));function dateObjectToExifDateTime(e){if(e!=null&&hasTime(e)){if(e instanceof import_exiftool_vendored11.ExifDateTime&&e.isValid)return e;try{let n=e.tzoffsetMinutes??zoneToTzOffsetMinutes(new Date(e.year,e.month-1,e.day).getTime(),e.zone),r=import_exiftool_vendored11.ExifDateTime.fromJSON({...e,tzoffsetMinutes:n,zoneName:map(e.zone,toS)});return r.isValid?r:void 0}catch{return}}}var rawTagsCache=lazy2(()=>new FileCache({name:`exif.raw`,maxSize:512,timeoutMs:0,keepPending:!0,...metadataCacheOptions()})),logger73=defer(()=>mkLogger(`tags.ReadRawTags`)),OpenError=`Error opening file`;function couldntOpen(e){return e?.Error===OpenError||(e?.errors??[]).some(e=>toS(e).includes(OpenError))}var forceNumericFields=new Set([`VideoFrameRate`]),tagTypeSets=lazyAsync({desc:`TagMetadata.json type sets`,async later(){try{let e=require("exiftool-vendored/data/TagMetadata.json"),n=new Set,r=new Set;for(let[a,o]of Object.entries(e))o.typed===!0&&(forceNumericFields.has(a)||o.type===`number`?r.add(a):o.type===`string`&&n.add(a));return{stringFields:n,numberFields:r}}catch(e){logger73().error(`tagTypeSets(): Failed to read TagMetadata.json`,{error:e});return}}});function exifReadArgs(e){return[...isVideoExt(import_node_path54.default.extname(e))?[]:[`-fast`],...ParsingSettings.excludedExifTags.values.flatMap(e=>[`-x`,e])]}async function __readRawTags(e){let n=PosixFile.forMaybe(e);if(n==null||!await n.isNonEmptyFile(0)){logger73().debug(`_readRawTags(): !isNonEmptyFile(), returning null.`,{file:e}),rawTagsCache().delete(e);return}logger73().debug(`_readRawTags() not cached, reading now.`,{file:e});let r=await time({name:`proc.exiftool`,post:(e,n)=>{e instanceof Error&&pushTime({name:`proc.exiftool`,elapsedMs:n})},p:()=>exiftool().read(n.nativePath,{readArgs:exifReadArgs(e)})}).catch(n=>{logger73().warn(`ExifTool failed to read`,{file:e,error:n})});if(r==null){logger73().warn(`_readRawTags() exiftool returned null/undefined`,{file:e});return}if(couldntOpen(r)&&rawTagsCache().delete(e),r.MIMEType=mapNotBlank(r.MIMEType,normalizeMimetype),r.GPSDateTime??=concatDateTime(r.GPSDateStamp,r.GPSTimeStamp),r.Rotation=orientationToRotation(r.Rotation),isVideoMimeType(r.MIMEType)&&await isFFprobeAvailable()){let n=await ffprobe_(e);logger73().debug(`readRawTags()`,{file:e,ffprobe:n,tags:pick(r,`Rotation`,`ImageWidth`,`ImageHeight`)}),assignFields(r,n)}await coerceTagTypes(r);let a=uniq(compactBlanks([r.Error,...r.errors??[],r.Warning].map(toS)));return isNotEmpty(a)&&(r.problems=a),isTest()&&addInstanceIds(r),r}var _readRawTags=shim({cache:rawTagsCache,stamp:e=>fileStamp(e),impl:__readRawTags,toKey:e=>e});async function readRawTags(e){let n=toNativePath_(e),r=await excludeWaitFromEnclosingTimer(()=>_readRawTags(n));return couldntOpen(r)&&_readRawTags.cacheDelete(n),r}async function readRawField_(e,n){let r=toNativePath_(e),a=await time({name:`exif.readRaw`,meta:{tagName:n},p:()=>exiftool().readRaw(r,{readArgs:[`-`+n]})});if(couldntOpen(a))throw Error(OpenError+`: `+r);return pluckCaseInsensitive(a,n)}async function coerceTagTypes(e){let n=await tagTypeSets();if(n==null)return logger73().warn(`coerceTagTypes(): Missing tag type sets, skipping type coercion.`),e;let{stringFields:r,numberFields:a}=n;for(let n of keys(e)){let o=e[n];if(typeof o==`string`){if(o===`0000:00:00`||o===`0000:00:00 00:00:00`)delete e[n];else if(a.has(n)){let r=forceNumericFields.has(n)?extractFraction(o):toFloat(o);r==null?forceNumericFields.has(n)&&delete e[n]:e[n]=r}}else typeof o==`number`&&r.has(n)&&(e[n]=String(o))}return e}var import_exiftool_vendored20=require("exiftool-vendored");function splitBits(e,n){let r=2**n,a=[];for(;e>0;)a.unshift(e%r),e=Math.floor(e/r);return a}var BitZip=class{constructor(e){this.dims=e}dims;clampValue(e){return e.map((e,n)=>clamp(this.dims[n].min,this.dims[n].max,e))}randomValue(){return this.dims.map(e=>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,n){let r=this.dims.map(e=>e.min),a=this.dims.map(e=>e.max),o=this.clampValue(e),s=0;for(let e=0;e<n;e++){s*=2;let n=e%r.length,c=(r[n]+a[n])/2;o[n]>c?(s+=1,r[n]=c):a[n]=c}return s}unzip(e,n){let r=this.dims.map(e=>e.min),a=this.dims.map(e=>e.max);for(let o=0;o<n;o++){let s=o%r.length,c=(r[s]+a[s])/2;isBitSet(e,n-o-1)?r[s]=c:a[s]=c}return times(r.length,e=>(r[e]+a[e])/2)}},BitShiftMax=2**32-1;function isBitSet(e,n,r){return r!==!0&&e<BitShiftMax&&n<32?(e>>n&1)==1:Math.floor(e/2**n)%2==1}var GpsCoordinateDecimalPlaces=6,LegacyGeohash30BitMaxErrorMeters=683,DefaultBitDepth=30;function toNearestBitDepth(e){return Math.floor(e/5)*5}function validLat(e){let n=toFloat(e);return within(-90,90,n)&&n!==0}function validLon(e){let n=toFloat(e);return within(-180,180,n)&&n!==0}function toLatLon(e,n){return e=toFloat(e),n=toFloat(n),validLat(e)&&validLon(n)?{latitude:e,longitude:n}:void 0}function normalizedGpsCoordinates(e,n){return map(toLatLon(e,n),e=>({latitude:roundToDecimalPlaces(e.latitude,GpsCoordinateDecimalPlaces),longitude:roundToDecimalPlaces(e.longitude,GpsCoordinateDecimalPlaces)}))}function coordinatesToGeoLocation(e){let n=toFloat(e?.latitude),r=toFloat(e?.longitude);return within(-90,90,n)&&within(-180,180,r)?{lat:n,lon:r}:void 0}var GeoHashBitZip=new BitZip([{min:-180,max:180},{min:-90,max:90}]);function ungeohash_num(e,n=DefaultBitDepth){return GeoHashBitZip.unzip(e,toNearestBitDepth(n))?.reverse()}function geoHashToLocation(e,n=DefaultBitDepth){let[r,a]=ungeohash_num(e,n);return{lat:r,lon:a}}var EarthDiaMeters=12742e3;function distanceMeters(e,n){let r=e.lat*Math.PI/180,a=n.lat*Math.PI/180,o=(n.lat-e.lat)*Math.PI/180,s=(n.lon-e.lon)*Math.PI/180,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(r)*Math.cos(a)*Math.sin(s/2)*Math.sin(s/2);return EarthDiaMeters*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}var import_exiftool_vendored18=require("exiftool-vendored"),CapturedAtSrcTypes=strEnum(`tags`,`bname+stat`,`path+stat`,`bname`,`path`,`siblings`,`stat`,`unknown`);function capturedAtSrcFromStat(e){return e===`stat`}async function awaitFields(e){let n=entries(e),r=await Promise.all(n.map(([,e])=>Promise.resolve(e))),a={};for(let e=0;e<n.length;e++)a[n[e][0]]=r[e];return a}var import_exiftool_vendored12=require("exiftool-vendored"),import_luxon12=require("luxon"),import_node_buffer=require("node:buffer"),import_node_path55=require("node:path"),logger74=lazy2(()=>mkLogger(`settings.PathToLibraryAsset`)),SingleQuote=`′`;function esc(e){return blank(e)?``:`'`+e.replace(/'/g,SingleQuote)+`'`}function unesc(e){return replaceAll(e,SingleQuote,`'`)}function filenameSafeSha(e,n=8){return blank(e)?``:TokenRadix.encodeBuffer(import_node_buffer.Buffer.from(e,`base64`)).slice(0,n)}function originalStem(e){let n=toNotBlank(e);if(n!=null)return toNotBlank((0,import_node_path55.basename)(n,(0,import_node_path55.extname)(n)))}var ProbeDates=[import_exiftool_vendored12.ExifDateTime.fromISO(`2001-02-05T04:05:06.007`),import_exiftool_vendored12.ExifDateTime.fromISO(`2012-11-28T15:36:47.258`)],ProbeSha=`AAAAAAAAAAAAAAAAAAAAAAAAAAA=`;function libraryFilenameEncodesDate(e){let[n,r]=ProbeDates.map(n=>pathToLibraryAsset(n,e,ProbeSha)?.at(-1));return n!==r}function pathToLibraryAsset(e,n,r,a){let o=datedToDateTime(e)??map(datedToISO(e),e=>import_luxon12.DateTime.fromISO(e));if(o==null||!o.isValid)return logger74().tap({msg:`pathToLibraryAsset(): failed to convert to a valid date`,result:void 0,meta:{capturedAt:e,src:n,dt:o}});let s=hasZone(e),c=Settings2.assetPathnameFormat.valueOrDefault,l=originalStem(a),u=splitKeep(c,/(GRANDPARENT|PARENT|BASE|NAME|EXT|ISO|DECADE|SHORTSHA)/g);for(let e=0;e<u.length;e++)switch(u[e]){case`GRANDPARENT`:u[e]=esc(grandParentBasename(n));break;case`PARENT`:u[e]=esc(parentBasename(n));break;case`BASE`:u[e]=esc(map(l,e=>e+n.ext)??n.base);break;case`NAME`:u[e]=esc(l??n.name);break;case`EXT`:u[e]=esc(stripPrefix(n.ext,`.`));break;case`ISO`:u[e]=`yyyy-MM-dd'T'HH-mm-ss.SSS`+(s?`ZZZ`:``);break;case`DECADE`:{let n=Math.floor(o.year/10)*10;u[e]=esc(`${n}-${n+9}`);break}case`SHORTSHA`:u[e]=esc(filenameSafeSha(r));break;default:countChars(u[e],`'`)%2==1&&(u[e]=replaceAll(u[e],`'`,SingleQuote))}let d=unesc(o.toFormat(u.join(``))).split(`/`).map(e=>mkValidFilename(e));return logger74().tap({msg:`pathToLibraryAsset()`,result:compactBlanks(d),meta:{capturedAt:e,src:n,dt:o,assetPathnameFormat:c,tokens:u,originalBase:a}})}var CapturedAtFieldNames=strEnum(`mimetype`,`capturedAtLocal`,`capturedAtZone`,`capturedAtPrecisionMs`,`capturedAtSrc`,`capturedAtSrcDetail`,`capturedAtZoneSrc`,`capturedAtRaw`),import_file_type=require("file-type"),logger75=defer(()=>mkLogger(`fs.FileType`)),FileTypeBadMimes=new Set([`audio/mpeg`,`image/tiff`]);function mimeTypeNeedsExifTool(e){return isRawImageExt(e)||isVideoExt(e)}async function readFileType_(e){try{let n=PosixFile.for(e),r=await n.stat_();if(r==null||r.size===0||!r.isFile())return logger75().tap({msg:`readFileType(): empty or not a file`,result:void 0,meta:{nativePath:e,stat:r}});if(mimeTypeNeedsExifTool(n.ext))logger75().debug(`readFileType(): can't use file-type (untrustworthy with this file)`,{nativePath:e,caller:shortStack()});else{let{buffer:n}=await readFilePart_({nativePath:e,position:0,length:256}),r=await(0,import_file_type.fileTypeFromBuffer)(n);if(r!=null&&!r.mime.startsWith(`image/x-`)&&!FileTypeBadMimes.has(r.mime))return logger75().tap({msg:`readFileType(): used file-type`,result:{ext:normalizeExt(r.ext)??r.ext,mime:normalizeMimetype(r.mime)},meta:{nativePath:e,file_type_result:r}});logger75().debug(`readFileType(): can't use file-type (untrustworthy)`,{nativePath:e,result:r})}let a=await readRawField_(e,`MIMEType`),o=mapNotBlank(a,normalizeMimetype),s=normalizeExt(PosixFile.for(e))??mimetypeExt(o);return logger75().tap({msg:`readFileType(): resorted to ExifTool`,result:blank(o)||blank(s)?void 0:{ext:s,mime:o},meta:{nativePath:e,raw:a}})}catch(n){return n?.code===`EISDIR`?void 0:logger75().throw(`readFileType() failed for `+e,{error:n,ignorable:!0,retriable:!1,fatal:!1,path:e})}}var logger76=defer(()=>mkLogger(`tags.ReadMimeType`)),mimetypeCache=lazy2(()=>new FileCache({name:`tags.mimetype`,...metadataCacheOptions(),maxSize:2048,timeoutMs:commandTimeoutMs()}));async function readMimeType_(e){if(blank(e))return;let n=PosixFile.forMaybe(e);if(n==null)return;let r=await fileStamp(n);return mimetypeCache().getOrSet(n.nativePath,async()=>map(rawTagsCache().peek(n.nativePath,r)?.MIMEType??(await readFileType_(n.nativePath))?.mime,normalizeMimetype),r)}async function readMimeType(e){return readMimeType_(e).catch(n=>{logger76().warn(`Failed to read mimetype from `+e,{nativePath:toNativePath_(e),error:n})})}var import_exiftool_vendored17=require("exiftool-vendored"),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`];function intToRoman(e){return RomanNumerals[toInt(e)]??toS(e)}var NotSetRe=/undefined|null|none|n\/a|unknown/i;function isExifUnset(e){return e==null||blank(e)||NotSetRe.test(toS(e))}function toExifDefined(e){return isExifUnset(e)?void 0:e}var SamsungModelsByPrefix={"SM-A013":`Galaxy A01 Core`,"SM-A015":`Galaxy A01`,"SM-A022":`Galaxy A02`,"SM-A025":`Galaxy A02s`,"SM-A032":`Galaxy A03 Core`,"SM-A035":`Galaxy A03`,"SM-A037":`Galaxy A03s`,"SM-A042":`Galaxy A04e`,"SM-A045":`Galaxy A04`,"SM-A047":`Galaxy A04s`,"SM-A055":`Galaxy A05`,"SM-A057":`Galaxy A05s`,"SM-A065":`Galaxy A06`,"SM-A066":`Galaxy A06 5G`,"SM-A075":`Galaxy A07`,"SM-A076":`Galaxy A07 5G`,"SM-A077":`Galaxy A07s`,"SM-A085":`Galaxy A08`,"SM-A102":`Galaxy A10e`,"SM-A105":`Galaxy A10`,"SM-A107":`Galaxy A10s`,"SM-A115":`Galaxy A11`,"SM-A125":`Galaxy A12`,"SM-A127":`Galaxy A12`,"SM-A135":`Galaxy A13`,"SM-A136":`Galaxy A13 5G`,"SM-A137":`Galaxy A13`,"SM-A145":`Galaxy A14`,"SM-A146":`Galaxy A14 5G`,"SM-A155":`Galaxy A15`,"SM-A156":`Galaxy A15 5G`,"SM-A156L":`Galaxy Buddy3`,"SM-A165":`Galaxy A16`,"SM-A166":`Galaxy A16 5G`,"SM-A166L":`Galaxy Buddy4`,"SM-A175":`Galaxy A17`,"SM-A176":`Galaxy A17 5G`,"SM-A176L":`Galaxy Buddy5`,"SM-A185":`Galaxy A18`,"SM-A202":`Galaxy A20e`,"SM-A202K":`Galaxy Jean2`,"SM-A205":`Galaxy A20`,"SM-A205S":`Galaxy Wide4`,"SM-A207":`Galaxy A20s`,"SM-A215":`Galaxy A21`,"SM-A217":`Galaxy A21s`,"SM-A225":`Galaxy A22`,"SM-A226":`Galaxy A22 5G`,"SM-A226L":`Galaxy Buddy`,"SM-A233":`Galaxy A23 5G`,"SM-A235":`Galaxy A23`,"SM-A236":`Galaxy A23 5G`,"SM-A245":`Galaxy A24`,"SM-A253":`Galaxy A25 5G`,"SM-A256":`Galaxy A25 5G`,"SM-A260":`Galaxy A2 Core`,"SM-A266":`Galaxy A26 5G`,"SM-A276":`Galaxy A27 5G`,"SM-A276K":`Galaxy Jump5`,"SM-A300":`Galaxy A3`,"SM-A305":`Galaxy A30`,"SM-A3050":`Galaxy A40s`,"SM-A3051":`Galaxy A40s`,"SM-A3058":`Galaxy A40s`,"SM-A307":`Galaxy A30s`,"SM-A310":`Galaxy A3 (2016)`,"SM-A315":`Galaxy A31`,"SM-A320":`Galaxy A3 (2017)`,"SM-A325":`Galaxy A32`,"SM-A326":`Galaxy A32 5G`,"SM-A336":`Galaxy A33 5G`,"SM-A346":`Galaxy A34 5G`,"SM-A356":`Galaxy A35 5G`,"SM-A366":`Galaxy A36 5G`,"SM-A376":`Galaxy A37 5G`,"SM-A405":`Galaxy A40`,"SM-A415":`Galaxy A41`,"SM-A426":`Galaxy A42 5G`,"SM-A500":`Galaxy A5`,"SM-A505":`Galaxy A50`,"SM-A507":`Galaxy A50s`,"SM-A510":`Galaxy A5 (2016)`,"SM-A515":`Galaxy A51`,"SM-A516":`Galaxy A51 5G`,"SM-A520":`Galaxy A5 (2017)`,"SM-A525":`Galaxy A52`,"SM-A526":`Galaxy A52 5G`,"SM-A528":`Galaxy A52s 5G`,"SM-A530":`Galaxy A8 (2018)`,"SM-A536":`Galaxy A53 5G`,"SM-A546":`Galaxy A54 5G`,"SM-A546S":`Galaxy Quantum4`,"SM-A556":`Galaxy A55 5G`,"SM-A556S":`Galaxy Quantum5`,"SM-A566":`Galaxy A56 5G`,"SM-A566S":`Galaxy Quantum6`,"SM-A576":`Galaxy A57 5G`,"SM-A576S":`Galaxy Quantum7`,"SM-A600":`Galaxy A6`,"SM-A605":`Galaxy A6+`,"SM-A6058":`Galaxy A9 Star Lite`,"SM-A605K":`Galaxy Jean`,"SM-A605X":`Galaxy A9 Star Lite`,"SM-A606":`Galaxy A60`,"SM-A700":`Galaxy A7`,"SM-A705":`Galaxy A70`,"SM-A707":`Galaxy A70s`,"SM-A710":`Galaxy A7 (2016)`,"SM-A715":`Galaxy A71`,"SM-A716":`Galaxy A71 5G`,"SM-A716S":`Galaxy A Quantum`,"SM-A720":`Galaxy A7 (2017)`,"SM-A725":`Galaxy A72`,"SM-A730":`Galaxy A8+(2018)`,"SM-A736":`Galaxy A73 5G`,"SM-A750":`Galaxy A7 (2018)`,"SM-A800":`Galaxy A8`,"SM-A805":`Galaxy A80`,"SM-A810":`Galaxy A8 (2016)`,"SM-A900":`Galaxy A9 (2016)`,"SM-A908":`Galaxy A90 5G`,"SM-A910":`Galaxy A9 Pro`,"SM-A920":`Galaxy A9 (2018)`,"SM-E025":`Galaxy F02s`,"SM-E045":`Galaxy F04`,"SM-E055":`Galaxy F05`,"SM-E066":`Galaxy F06 5G`,"SM-E075":`Galaxy F07`,"SM-E076":`Galaxy F70e 5G`,"SM-E085":`Galaxy F08`,"SM-E135":`Galaxy F13`,"SM-E145":`Galaxy F14`,"SM-E146":`Galaxy F14 5G`,"SM-E156":`Galaxy F15 5G`,"SM-E166":`Galaxy F16 5G`,"SM-E176":`Galaxy F17 5G`,"SM-E225":`Galaxy F22`,"SM-E236":`Galaxy F23 5G`,"SM-E346":`Galaxy F34 5G`,"SM-E366":`Galaxy F36 5G`,"SM-E426":`Galaxy F42 5G`,"SM-E426S":`Galaxy Wide5`,"SM-E526":`Galaxy F52 5G`,"SM-E546":`Galaxy F54 5G`,"SM-E556":`Galaxy F55 5G`,"SM-E566":`Galaxy F56 5G`,"SM-E625":`Galaxy F62`,"SM-F700":`Galaxy Z Flip`,"SM-F707":`Galaxy Z Flip`,"SM-F711":`Galaxy Z Flip 3`,"SM-F721":`Galaxy Z Flip 4`,"SM-F731":`Galaxy Z Flip 5`,"SM-F741":`Galaxy Z Flip 6`,"SM-F761":`Galaxy Z Flip 7 FE`,"SM-F766":`Galaxy Z Flip 7`,"SM-F776":`Galaxy Z Flip 8`,"SM-F900":`Galaxy Fold`,"SM-F907":`Galaxy Fold`,"SM-F916":`Galaxy Z Fold 2`,"SM-F926":`Galaxy Z Fold 3`,"SM-F936":`Galaxy Z Fold 4`,"SM-F946":`Galaxy Z Fold 5`,"SM-F956":`Galaxy Z Fold 6`,"SM-F958":`Galaxy Z Fold Special Edition`,"SM-F966":`Galaxy Z Fold 7`,"SM-F968":`Galaxy Z TriFold`,"SM-F971":`Galaxy Z Fold 8`,"SM-F976":`Galaxy Z Fold 8 Ultra`,"SM-G3812":`Galaxy Win Pro`,"SM-G3812B":`Galaxy S3 Slim`,"SM-G3815":`Galaxy Express2`,"SM-G3818":`Galaxy Win Pro`,"SM-G3819":`Galaxy Win Pro`,"SM-G730":`Galaxy S3 Mini`,"SM-G770":`Galaxy S10 Lite`,"SM-G780":`Galaxy S20 FE`,"SM-G781":`Galaxy S20 FE`,"SM-G800":`Galaxy S5 mini`,"SM-G870":`Galaxy S5 Active`,"SM-G892":`Galaxy S8 Active`,"SM-G900":`Galaxy S5`,"SM-G901":`Galaxy S5 LTE-A`,"SM-G903":`Galaxy S5 Neo`,"SM-G906":`Galaxy S5`,"SM-G920":`Galaxy S6`,"SM-G925":`Galaxy S6 Edge`,"SM-G928":`Galaxy S6 Edge+`,"SM-G930":`Galaxy S7`,"SM-G935":`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":`Galaxy S10`,"SM-G975":`Galaxy S10+`,"SM-G977":`Galaxy S10`,"SM-G980":`Galaxy S20`,"SM-G981":`Galaxy S20`,"SM-G985":`Galaxy S20+`,"SM-G986":`Galaxy S20+`,"SM-G988":`Galaxy S20 Ultra`,"SM-G990":`Galaxy S21 FE`,"SM-G991":`Galaxy S21`,"SM-G996":`Galaxy S21+`,"SM-G998":`Galaxy S21 Ultra`,"SM-J100":`Galaxy J1`,"SM-J105":`Galaxy J1 Mini`,"SM-J106":`Galaxy J1 Mini Prime`,"SM-J110":`Galaxy J1 Ace`,"SM-J111":`Galaxy J1 Ace`,"SM-J120":`Galaxy J1`,"SM-J200":`Galaxy J2`,"SM-J210":`Galaxy J2 Pro`,"SM-J250":`Galaxy J2 Pro`,"SM-J260":`Galaxy J2 Core`,"SM-J260AZ":`Galaxy J2 Pure`,"SM-J310":`Galaxy J3`,"SM-J311":`Galaxy J3 Pro`,"SM-J320":`Galaxy J3 (2016)`,"SM-J327":`Galaxy J3`,"SM-J330":`Galaxy J3 (2017)`,"SM-J330G":`Galaxy J3 Pro`,"SM-J337":`Galaxy J3`,"SM-J400":`Galaxy J4`,"SM-J410":`Galaxy J4 Core`,"SM-J415":`Galaxy J4+`,"SM-J500":`Galaxy J5`,"SM-J510":`Galaxy J5 (2016)`,"SM-J530":`Galaxy J5`,"SM-J600":`Galaxy J6`,"SM-J600GF":`Galaxy On6`,"SM-J610":`Galaxy J6+`,"SM-J700":`Galaxy J7`,"SM-J701":`Galaxy J7 Neo`,"SM-J710":`Galaxy J7 (2016)`,"SM-J710FN":`Galaxy On8`,"SM-J720":`Galaxy J7 Duo`,"SM-J727":`Galaxy J7`,"SM-J727S":`Galaxy Wide2`,"SM-J730":`Galaxy J7`,"SM-J737":`Galaxy J7`,"SM-J737S":`Galaxy Wide3`,"SM-J810":`Galaxy J8`,"SM-J810GF":`Galaxy On8`,"SM-M013":`Galaxy M01 Core`,"SM-M015":`Galaxy M01`,"SM-M017":`Galaxy M01s`,"SM-M022":`Galaxy M02`,"SM-M025":`Galaxy M02s`,"SM-M045":`Galaxy M04`,"SM-M055":`Galaxy M05`,"SM-M066":`Galaxy M06 5G`,"SM-M075":`Galaxy M07`,"SM-M076":`Galaxy M17e 5G`,"SM-M085":`Galaxy M08`,"SM-M105":`Galaxy M10`,"SM-M107":`Galaxy M10s`,"SM-M115":`Galaxy M11`,"SM-M127":`Galaxy M12`,"SM-M135":`Galaxy M13`,"SM-M136":`Galaxy M13 5G`,"SM-M145":`Galaxy M14`,"SM-M146":`Galaxy M14 5G`,"SM-M156":`Galaxy M15 5G`,"SM-M156S":`Galaxy Wide7`,"SM-M166":`Galaxy M16 5G`,"SM-M166S":`Galaxy Wide8`,"SM-M176":`Galaxy M17 5G`,"SM-M176S":`Galaxy Wide9`,"SM-M205":`Galaxy M20`,"SM-M215":`Galaxy M21`,"SM-M225":`Galaxy M22`,"SM-M236":`Galaxy M23 5G`,"SM-M236L":`Galaxy Buddy2`,"SM-M305":`Galaxy M30`,"SM-M307":`Galaxy M30s`,"SM-M315":`Galaxy M31`,"SM-M317":`Galaxy M31s`,"SM-M325":`Galaxy M32`,"SM-M326":`Galaxy M32 5G`,"SM-M336":`Galaxy M33 5G`,"SM-M336K":`Galaxy Jump2`,"SM-M346":`Galaxy M34 5G`,"SM-M356":`Galaxy M35 5G`,"SM-M366":`Galaxy M36 5G`,"SM-M366K":`Galaxy Jump4`,"SM-M405":`Galaxy M40`,"SM-M426":`Galaxy M42 5G`,"SM-M515":`Galaxy M51`,"SM-M526":`Galaxy M52 5G`,"SM-M536":`Galaxy M53 5G`,"SM-M536S":`Galaxy Quantum3`,"SM-M546":`Galaxy M54 5G`,"SM-M556":`Galaxy M55 5G`,"SM-M558":`Galaxy M55s 5G`,"SM-M566":`Galaxy M56 5G`,"SM-M625":`Galaxy M62`,"SM-N750":`Galaxy Note 3 Neo`,"SM-N770":`Galaxy Note 10 Lite`,"SM-N900":`Galaxy Note 3`,"SM-N910":`Galaxy Note 4`,"SM-N915":`Galaxy Note Edge`,"SM-N916":`Galaxy Note 4`,"SM-N920":`Galaxy Note 5`,"SM-N930":`Galaxy Note 7`,"SM-N935":`Galaxy Note Fan Edition`,"SM-N950":`Galaxy Note 8`,"SM-N960":`Galaxy Note 9`,"SM-N970":`Galaxy Note 10`,"SM-N971":`Galaxy Note 10`,"SM-N975":`Galaxy Note 10+`,"SM-N976":`Galaxy Note 10+`,"SM-N980":`Galaxy Note 20`,"SM-N981":`Galaxy Note 20`,"SM-N985":`Galaxy Note 20 Ultra`,"SM-N986":`Galaxy Note 20 Ultra`,"SM-S711":`Galaxy S23 FE`,"SM-S721":`Galaxy S24 FE`,"SM-S731":`Galaxy S25 FE`,"SM-S741":`Galaxy S26 FE`,"SM-S901":`Galaxy S22`,"SM-S903":`Galaxy S5`,"SM-S906":`Galaxy S22+`,"SM-S906L":`Galaxy S6`,"SM-S907":`Galaxy S6`,"SM-S908":`Galaxy S22 Ultra`,"SM-S911":`Galaxy S23`,"SM-S916":`Galaxy S23+`,"SM-S918":`Galaxy S23 Ultra`,"SM-S921":`Galaxy S24`,"SM-S926":`Galaxy S24+`,"SM-S928":`Galaxy S24 Ultra`,"SM-S931":`Galaxy S25`,"SM-S936":`Galaxy S25+`,"SM-S937":`Galaxy S25 Edge`,"SM-S938":`Galaxy S25 Ultra`,"SM-S942":`Galaxy S26`,"SM-S947":`Galaxy S26+`,"SM-S948":`Galaxy S26 Ultra`,"SM-S975":`Galaxy S4`,"SM-T500":`Galaxy Tab A7`,"SM-T503":`Galaxy Tab A7`,"SM-T505":`Galaxy Tab A7`,"SM-T507":`Galaxy Tab A7`,"SM-T509":`Galaxy Tab A7`,"SM-X400":`Galaxy Tab S10 Lite`,"SM-X406":`Galaxy Tab S10 Lite 5G`,"SM-X510":`Galaxy Tab S9 FE`,"SM-X516":`Galaxy Tab S9 FE 5G`,"SM-X518":`Galaxy Tab S9 FE 5G`,"SM-X520":`Galaxy Tab S10 FE`,"SM-X526":`Galaxy Tab S10 FE 5G`,"SM-X528":`Galaxy Tab S10 FE 5G`,"SM-X610":`Galaxy Tab S9 FE+`,"SM-X616":`Galaxy Tab S9 FE+ 5G`,"SM-X620":`Galaxy Tab S10 FE+`,"SM-X626":`Galaxy Tab S10 FE+ 5G`,"SM-X700":`Galaxy Tab S8`,"SM-X706":`Galaxy Tab S8 5G`,"SM-X710":`Galaxy Tab S9`,"SM-X716":`Galaxy Tab S9 5G`,"SM-X730":`Galaxy Tab S11`,"SM-X736":`Galaxy Tab S11 5G`,"SM-X800":`Galaxy Tab S8+`,"SM-X806":`Galaxy Tab S8+ 5G`,"SM-X808":`Galaxy Tab S8+ 5G`,"SM-X810":`Galaxy Tab S9+`,"SM-X816":`Galaxy Tab S9+ 5G`,"SM-X818":`Galaxy Tab S9+ 5G`,"SM-X820":`Galaxy Tab S10+`,"SM-X826":`Galaxy Tab S10+ 5G`,"SM-X828":`Galaxy Tab S10+ 5G`,"SM-X840":`Galaxy Tab S12+`,"SM-X846":`Galaxy Tab S12+ 5G`,"SM-X848":`Galaxy Tab S12+ 5G`,"SM-X900":`Galaxy Tab S8 Ultra`,"SM-X906":`Galaxy Tab S8 Ultra 5G`,"SM-X910":`Galaxy Tab S9 Ultra`,"SM-X916":`Galaxy Tab S9 Ultra 5G`,"SM-X920":`Galaxy Tab S10 Ultra`,"SM-X926":`Galaxy Tab S10 Ultra 5G`,"SM-X930":`Galaxy Tab S11 Ultra`,"SM-X936":`Galaxy Tab S11 Ultra 5G`,"SM-X940":`Galaxy Tab S12 Ultra`,"SM-X946":`Galaxy Tab S12 Ultra 5G`},PhoneModelsByMake={Xiaomi:{"11 Lite 5G NE":[`2109119DG`],"11 Lite NE":[`2109119DI`],"11i":[`21091116I`],"11i HyperCharge":[`21091116UI`],"11T":[`21081111RG`],"11T Pro":[`2107113SG`,`2107113SI`,`2107113SR`],12:[`2201123C`,`2201123G`],"12 Lite":[`2203129G`],"12 Pro":[`2201122C`,`2201122G`],"12 Pro Dimensity":[`2207122MC`],"12S":[`2206123SC`],"12S Pro":[`2206122SC`],"12S Ultra":[`2203121C`],"12T":[`22071212AG`],"12T Pro":[`22081212C`,`22081212R`,`22081212UG`,`22200414R`,`A201XM`],"12X":[`2112123AC`],13:[`2211133C`,`2211133G`],"13 Lite":[`2210129SG`],"13 Pro":[`2210132C`,`2210132G`],"13 Ultra":[`2304FPN6DC`,`2304FPN6DG`],"13T":[`2306EPN60G`,`XIG04`],"13T Pro":[`23078PND5G`,`23088PND5R`,`A301XM`],14:[`23127PN0CC`,`23127PN0CG`],"14 Civi":[`24053PY09I`],"14 Pro":[`23116PN5BC`,`2311BPN23C`],"14 Ultra":[`24030PN60G`,`24031PN0DC`],"14T":[`2406APNFAG`,`XIG07`],"14T Pro":[`2407FPN8EG`,`2407FPN8ER`,`A402XM`],15:[`24129PN74C`,`24129PN74G`,`24129PN74I`],"15 Pro":[`2410DPN6CC`],"15 Ultra":[`25010PN30C`,`25010PN30G`,`25010PN30I`,`25019PNF3C`],"15S Pro":[`25042PN24C`],"15T":[`25069PTEBG`],"15T Pro":[`2506BPN68G`,`2506BPN68R`],17:[`25113PN0EC`,`25113PN0EG`,`25113PN0EI`],"17 Max":[`2605EPN8EC`],"17 Pro":[`25098PN5AC`],"17 Pro Max":[`2509FPN0BC`],"17 Ultra":[`2512BPNDAC`,`2512BPNDAG`,`2512BPNDAI`],"17T":[`2602DPT53G`,`2602DPT53I`,`M531DA`],"17T Pro":[`2602EPTC0G`,`2602EPTC0R`,`M025EC`],Civi:[`2109119BC`],"Civi 2":[`2209129SC`],"Civi 3":[`23046PNC9C`],"Civi 4":[`24053PY09C`],"Civi 5 Pro":[`25067PYE3C`],"Mi 10 Lite 5G":[`M2002J9G`,`M2002J9S`,`XIG01`],"Mi 10 Lite Zoom":[`M2002J9E`],"Mi 10 Ultra":[`M2007J1SC`],"Mi 10i":[`M2007J17I`],"Mi 10S":[`M2102J2SC`],"Mi 10T":[`M2007J3SP`,`M2007J3SY`],"Mi 10T Lite":[`M2007J17G`],"Mi 10T Pro":[`M2007J3SG`,`M2007J3SI`],"Mi 11":[`M2011K2C`,`M2011K2G`],"Mi 11 LE":[`2107119DC`],"Mi 11 Lite":[`M2101K9AG`,`M2101K9AI`],"Mi 11 Lite 5G":[`M2101K9C`,`M2101K9G`],"Mi 11 Pro":[`M2102K1AC`],"Mi 11 Ultra":[`M2102K1C`,`M2102K1G`],"Mi 11i":[`M2012K11G`],"Mi 11X Pro":[`M2012K11I`],"Mi 4c":[`MI-4C`],"MIX 4":[`2106118C`],"MIX Flip":[`2405CPX3DC`,`2405CPX3DG`],"MIX Fold":[`M2011J18C`],"MIX Fold 2":[`22061218C`],"MIX Fold 3":[`2308CPXD0C`],"MIX Fold 4":[`24072PX77C`],"POCO C3":[`M2006C3MI`],"POCO C31":[`211033MI`],"POCO C50":[`220733SPI`],"POCO C51":[`2302EPCC4H`,`2305EPCC4G`],"POCO C55":[`22127PC95I`],"POCO C61":[`2312BPC51H`,`2312BPC51X`],"POCO C65":[`2310FPCA4G`,`2310FPCA4I`],"POCO C71":[`25028PC03G`,`25028PC03I`],"POCO C75":[`2410FPCC5G`],"POCO C75 5G":[`24116PCC1I`],"POCO C81":[`25128PC17I`],"POCO C81 Pro":[`25128PC17G`,`25128PC17L`,`25128PC17Y`],"POCO C81x":[`26020PCB4I`],"POCO C85":[`25078PC3EE`,`25078PC3EG`],"POCO C85 5G":[`2508CPC2BI`],"POCO C85x 5G":[`26020PC1AI`],"POCO F3":[`M2012K11AG`],"POCO F3 GT":[`M2104K10I`],"POCO F4":[`22021211RG`,`22021211RI`],"POCO F4 GT":[`21121210G`],"POCO F5":[`23049PCD8G`,`23049PCD8I`],"POCO F6":[`24069PC21G`,`24069PC21I`],"POCO F6 Pro":[`23113RKC6G`],"POCO F7":[`25053PC47G`,`25053PC47I`],"POCO F7 Pro":[`24117RK2CG`],"POCO F7 Ultra":[`24122RKC7G`],"POCO F8 Pro":[`2510DPC44G`],"POCO F8 Ultra":[`25102PCBEG`],"POCO F9 Pro":[`2607APCA5G`],"POCO F9 Ultra":[`26077PC53G`],"POCO M2":[`M2004J19PI`],"POCO M3":[`M2010J19CG`,`M2010J19CI`],"POCO M3 Pro 5G":[`M2103K19PG`,`M2103K19PI`],"POCO M4 5G":[`22041219PG`,`22041219PI`],"POCO M4 Pro":[`2201117PG`,`2201117PI`],"POCO M4 Pro 5G":[`21091116AG`],"POCO M5":[`22071219CG`,`22071219CI`],"POCO M5s":[`2207117BPG`],"POCO M6":[`2404APC5FG`],"POCO M6 Plus 5G":[`24066PC95I`],"POCO M6 Pro":[`2312FPCA6G`],"POCO M6 Pro 5G":[`23076PC4BI`],"POCO M7":[`25062PC34E`,`25062PC34G`],"POCO M7 5G":[`24108PCE2I`],"POCO M7 Plus 5G":[`25057PC09I`],"POCO M7 Pro 5G":[`2409FPCC4G`,`2409FPCC4I`],"POCO M8 5G":[`25118PC98G`,`25118PC98I`],"POCO M8 Power 5G":[`26021PC18I`],"POCO M8 Pro 5G":[`2510EPC8BG`],"POCO X3":[`M2007J20CI`],"POCO X3 NFC":[`M2007J20CG`],"POCO X3 Pro":[`M2102J20SG`,`M2102J20SI`],"POCO X4 GT":[`22041216G`],"POCO X4 Pro 5G":[`2201116PG`,`2201116PI`],"POCO X5 Pro 5G":[`22101320G`,`22101320I`],"POCO X6 5G":[`23122PCD1G`,`23122PCD1I`],"POCO X6 Pro 5G":[`2311DRK48G`,`2311DRK48I`],"POCO X7":[`24095PCADG`,`24095PCADI`],"POCO X7 Pro":[`2412DPC0AG`,`2412DPC0AI`],"POCO X8":[`2607DPC18G`],"POCO X8 Pro":[`2511FPC34G`,`2511FPC34I`],"POCO X8 Pro Max":[`2602BPC18G`,`2602BPC18I`],"Redmi 10":[`21061119DG`,`22011119UY`,`220333QBI`],"Redmi 10 2022":[`21061119AG`,`21061119AL`,`21121119SG`,`21121119VL`],"Redmi 10 5G":[`22041219G`,`22041219NY`],"Redmi 10A":[`220233L2C`],"Redmi 10A Sport":[`220233L2I`],"Redmi 10C":[`220333QAG`,`220333QL`,`220333QNY`],"Redmi 10X":[`M2004J7AC`],"Redmi 10X Pro":[`M2004J7BC`],"Redmi 11 Prime":[`22071219AI`],"Redmi 11 Prime 5G":[`22041219I`],"Redmi 12":[`23053RN02A`,`23053RN02I`,`23053RN02L`,`23053RN02Y`],"Redmi 12 5G":[`23076RA4BR`,`23076RN8DY`,`A401XM`,`XIG03`],"Redmi 12C":[`22120RN86G`,`22120RN86I`,`22126RN91Y`,`2212ARNC4L`],"Redmi 13":[`24040RN64Y`,`24049RN28L`,`2404ARN45A`],"Redmi 13 5G":[`2406ERN9CI`],"Redmi 13C":[`23100RN82L`,`23106RN0DA`,`23108RN04Y`,`2311DRN14I`],"Redmi 13C 5G":[`23124RN87G`,`23124RN87I`],"Redmi 14C":[`2409BRN2CA`,`2409BRN2CL`,`2409BRN2CY`],"Redmi 14C 5G":[`2411DRN47I`],"Redmi 15":[`25062RN2DE`,`25062RN2DL`,`25062RN2DY`],"Redmi 15 5G":[`25057RN09E`,`25057RN09G`,`25057RN09I`,`25057RN09R`,`A501XM`],"Redmi 15A 5G":[`2602BRNA4I`],"Redmi 15C":[`25078RA3EA`,`25078RA3EE`,`25078RA3EL`,`25078RA3EY`],"Redmi 15C 5G":[`2508CRN2BE`,`2508CRN2BI`],"Redmi 17 5G":[`26062RN92G`,`26062RN92I`],"Redmi 9":[`M2004J19C`,`M2004J19G`,`M2006C3MII`],"Redmi 9 Power":[`M2010J19SI`],"Redmi 9 Prime":[`M2004J19I`],"Redmi 9A":[`220233L2G`,`M2006C3LC`,`M2006C3LG`,`M2006C3LI`,`M2006C3LVG`],"Redmi 9C":[`M2006C3MG`],"Redmi 9C NFC":[`M2006C3MNG`],"Redmi 9T":[`M2010J19SG`,`M2010J19SL`,`M2010J19SY`],"Redmi K100 Pro":[`M511CD`],"Redmi K100 Pro Max":[`M098FE`],"Redmi K30 Ultra":[`M2006J10C`],"Redmi K30S Ultra":[`M2007J3SC`],"Redmi K40":[`M2012K11AC`],"Redmi K40 Gaming":[`M2012K10C`],"Redmi K40 Pro":[`M2012K11C`],"Redmi K40S":[`22021211RC`],"Redmi K50":[`22041211AC`],"Redmi K50 Pro":[`22011211C`],"Redmi K50G":[`21121210C`],"Redmi K50i":[`22041216I`],"Redmi K60":[`23013RK75C`],"Redmi K60 Pro":[`22127RK46C`],"Redmi K60 Ultra":[`23078RKD5C`],"Redmi K60E":[`22122RK93C`],"Redmi K70":[`23113RKC6C`],"Redmi K70 Pro":[`23117RK66C`],"Redmi K70 Ultra":[`2407FRK8EC`],"Redmi K70E":[`2311DRK48C`],"Redmi K80":[`24117RK2CC`],"Redmi K80 Pro":[`24122RKC7C`],"Redmi K80 Ultra":[`25060RK16C`],"Redmi K90":[`2510DRK44C`],"Redmi K90 Pro Max":[`25102RK69C`,`25102RKBEC`],"Redmi Note 10":[`M2101K7AG`,`M2101K7AI`,`M2103K19C`],"Redmi Note 10 5G":[`M2103K19G`],"Redmi Note 10 JE":[`XIG02`],"Redmi Note 10 Pro":[`21061110AG`,`M2101K6G`,`M2101K6P`,`M2104K10AC`],"Redmi Note 10 Pro Max":[`M2101K6I`],"Redmi Note 10S":[`M2101K7BG`,`M2101K7BI`,`M2101K7BL`,`M2101K7BNY`],"Redmi Note 10T":[`M2103K19Y`],"Redmi Note 10T 5G":[`M2103K19I`],"Redmi Note 11":[`2201117TG`,`2201117TI`,`2201117TL`,`2201117TY`],"Redmi Note 11 4G":[`21121119SC`],"Redmi Note 11 5G":[`21091116AC`],"Redmi Note 11 Pro":[`21091116C`,`2201116TG`,`2201116TI`],"Redmi Note 11 Pro 5G":[`2201116SG`,`2201116SR`],"Redmi Note 11 Pro+":[`21091116UC`],"Redmi Note 11 Pro+ 5G":[`21091116UG`,`2201116SI`],"Redmi Note 11 SE":[`22087RA4DI`],"Redmi Note 11E":[`22041219C`],"Redmi Note 11E Pro":[`2201116SC`],"Redmi Note 11S":[`2201117SG`,`2201117SI`,`2201117SL`,`2201117SY`],"Redmi Note 11S 5G":[`22031116BG`],"Redmi Note 11T 5G":[`21091116AI`],"Redmi Note 11T Pro":[`22041216C`],"Redmi Note 11T Pro +":[`22041216UC`],"Redmi Note 12":[`23021RAA2Y`,`23021RAAEG`,`23027RAD4I`,`23028RA60L`],"Redmi Note 12 5G":[`22101317C`],"Redmi Note 12 DISCOVERY EDITION":[`22101316UC`],"Redmi Note 12 Pro":[`2209116AG`,`22101316C`],"Redmi Note 12 Pro + 5G":[`22101316UP`],"Redmi Note 12 Pro 5G":[`22101316G`,`22101316I`],"Redmi Note 12 Pro Speed":[`22101320C`],"Redmi Note 12 Pro+":[`22101316UCP`],"Redmi Note 12 Pro+ 5G":[`22101316UG`],"Redmi Note 12 Turbo":[`23049RAD8C`],"Redmi Note 12S":[`23030RAC7Y`,`2303CRA44A`,`2303ERA42L`],"Redmi Note 12T Pro":[`23054RA19C`],"Redmi Note 13":[`23124RA7EO`,`23129RA5FL`,`23129RAA4G`],"Redmi Note 13 5G":[`2312DRAABC`,`2312DRAABG`,`2312DRAABI`],"Redmi Note 13 Pro":[`23117RA68G`],"Redmi Note 13 Pro 5G":[`2312CRAD3C`,`2312DRA50C`,`2312DRA50G`,`2312DRA50I`,`XIG05`],"Redmi Note 13 Pro+":[`23090RA98C`],"Redmi Note 13 Pro+ 5G":[`23090RA98G`,`23090RA98I`,`24040RA98R`],"Redmi Note 13R":[`2406ERN9CC`],"Redmi Note 13R Pro":[`2311FRAFDC`],"Redmi Note 14":[`24117RN76E`,`24117RN76G`,`24117RN76L`,`24117RN76O`],"Redmi Note 14 5G":[`24094RAD4C`,`24094RAD4G`,`24094RAD4I`],"Redmi Note 14 Pro":[`24090RA29C`,`24116RACCG`],"Redmi Note 14 Pro 5G":[`24090RA29G`,`24090RA29I`],"Redmi Note 14 Pro+":[`24115RA8EC`],"Redmi Note 14 Pro+ 5G":[`24115RA8EG`,`24115RA8EI`],"Redmi Note 14S":[`2502FRA65G`],"Redmi Note 15":[`25098RA98C`,`2510DRA23E`,`2510DRA23G`,`2510DRA23L`],"Redmi Note 15 5G":[`25098RA98G`,`25098RA98I`,`25098RA98T`],"Redmi Note 15 Pro":[`25080RABDC`,`25100RA69G`],"Redmi Note 15 Pro 5G":[`25080RABDG`,`25080RABDI`,`25080RABDR`],"Redmi Note 15 Pro+":[`25104RADAC`,`2510ERA8BC`],"Redmi Note 15 Pro+5G":[`2510ERA8BG`,`2510ERA8BI`],"Redmi Note 15 SE 5G":[`26022PCACI`],"Redmi Note 15R":[`25057RA09C`],"Redmi Note 17":[`26012RN62A`,`26012RN62L`,`26012RN62Y`,`26021RN18C`],"Redmi Note 17 5G":[`26021RN18I`,`26081RA18G`,`26081RA18L`],"Redmi Note 17 Pro":[`2607DRA18C`],"Redmi Note 17 Pro 5G":[`2607DRA18G`,`2607DRA18T`],"Redmi Note 17 Pro Max 5G":[`2609FRA74G`],"Redmi Note 8":[`M1908C3JGG`],"Redmi Note 9":[`M2003J15SC`,`M2003J15SG`,`M2003J15SI`,`M2003J15SS`,`M2007J22C`],"Redmi Note 9 4G":[`M2010J19SC`],"Redmi Note 9 pro":[`M2007J17C`],"Redmi Note 9T":[`A001XM`,`M2007J22G`]},Huawei:{"Honor 10":[`COL-AL00`,`COL-AL10`,`COL-L29`,`COL-TL10`],"Honor 10 Lite":[`HRY-AL00`,`HRY-AL00A`,`HRY-LX1`,`HRY-LX1MEB`,`HRY-LX2`],"Honor 10i":[`HRY-LX1T`],"Honor 20":[`YAL-AL00`,`YAL-TL00`],"Honor 20 Lite":[`MAR-LX1R`],"Honor 20 Pro":[`YAL-AL10`],"Honor 20i":[`HRY-AL00TA`],"Honor 20S":[`MAR-LX1H`],"Honor 4A":[`SCC-U21`,`SCL-AL00`,`SCL-CL00`,`SCL-TL00`,`SCL-TL00H`],"Honor 4X":[`CHE2-L12`],"Honor 5A":[`LYO-L21`],"Honor 5C":[`NEM-L21`,`NEM-L22`,`NEM-L51`],"Honor 5X":[`KIW-L21`,`KIW-L22`,`KIW-L23`,`KIW-L24`,`KIW-TL00H`],"Honor 6A":[`DLI-L22`,`DLI-TL20`],"Honor 6A Pro":[`DLI-L42`],"Honor 6C":[`DIG-L21HN`],"Honor 6C Pro":[`JMM-L22`],"Honor 6X":[`BLN-L21`,`BLN-L22`,`BLN-L24`],"Honor 7":[`PLK-AL10`,`PLK-CL00`,`PLK-L01`,`PLK-TL00`,`PLK-TL01H`,`PLK-UL00`],"Honor 7A":[`AUM-AL00`,`AUM-AL20`,`AUM-L29`,`AUM-L33`,`AUM-TL00`,`AUM-TL20`,`DUA-L22`],"Honor 7C":[`AUM-L41`,`LND-AL30`,`LND-AL40`,`LND-L29`,`LND-TL30`,`LND-TL40`],"Honor 7i":[`ATH-AL00`,`ATH-CL00`],"Honor 7S":[`DRA-LX5`,`DUA-AL00`,`DUA-LX3`],"Honor 7X":[`BND-L21`,`BND-L24`,`BND-L31`],"Honor 8":[`FRD-AL00`,`FRD-AL10`,`FRD-DL00`,`FRD-L04`,`FRD-L09`,`FRD-L14`,`FRD-L19`,`FRD-L24`,`FRD-TL00`],"Honor 8 Lite":[`PRA-LX1`],"Honor 8 Pro":[`DUK-L09`],"Honor 8 Smart":[`VEN-L22`],"Honor 8A":[`JAT-AL00`,`JAT-L29`,`JAT-L41`,`JAT-LX1`,`JAT-LX3`],"Honor 8C":[`BKK-AL10`,`BKK-L21`,`BKK-L22`,`BKK-LX2`],"Honor 8S":[`KSA-LX2`,`KSA-LX3`,`KSA-LX9`],"Honor 8X":[`JSN-L21`,`JSN-L22`,`JSN-L23`,`JSN-L42`],"Honor 8X Max":[`ARE-L22HN`],"Honor 9":[`STF-AL00`,`STF-AL10`,`STF-L09`,`STF-L09S`,`STF-TL10`],"Honor 9 Lite":[`LLD-L21`,`LLD-L31`],"Honor 9A":[`DUB-LX1`],"Honor 9N":[`LLD-AL20`],"Honor 9X":[`STK-L22`,`STK-LX1`,`STK-LX3`],"Honor Magic":[`NTS-AL00`],"Honor Magic 2":[`TNY-AL00`,`TNY-TL00`],"Honor Note 10":[`RVL-AL09`],"Honor Play":[`COR-AL00`,`COR-AL10`,`COR-L29`,`COR-TL10`],"Honor V10":[`BKL-AL00`,`BKL-AL20`,`BKL-TL10`],"Honor V20":[`PCT-TL10`],"Honor V8":[`KNT-AL10`,`KNT-AL20`,`KNT-TL10`,`KNT-UL10`],"Honor V9":[`DUK-AL20`,`DUK-TL30`],"Honor View 10":[`BKL-L04`,`BKL-L09`],"Honor View 20":[`PCT-AL10`,`PCT-L29`],"Mate 10":[`ALP-AL00`,`ALP-L09`,`ALP-L29`,`ALP-TL00`],"Mate 10 lite":[`RNE-L01`,`RNE-L03`,`RNE-L21`,`RNE-L23`],"Mate 10 Pro":[`BLA-A09`,`BLA-AL00`,`BLA-L09`,`BLA-L29`,`BLA-TL00`],"Mate 2":[`MT2-C00`],"Mate 20":[`HMA-AL00`,`HMA-L09`,`HMA-L29`,`HMA-TL00`],"Mate 20 lite":[`SNE-LX1`,`SNE-LX2`,`SNE-LX3`],"Mate 20 Pro":[`LYA-AL00`,`LYA-AL10`,`LYA-L09`,`LYA-L0C`,`LYA-L29`,`LYA-TL00`],"Mate 20 RS":[`LYA-AL00P`],"Mate 20 X":[`EVR-L29`,`EVR-TL00`],"Mate 20 X (5G)":[`EVR-AN00`,`EVR-N29`],"Mate 7":[`MT7-CL00`,`MT7-J1`,`MT7-L09`,`MT7-TL00`,`MT7-TL10`,`MT7-UL00`],"Mate 8":[`NXT-AL10`,`NXT-CL00`,`NXT-DL00`,`NXT-L09`,`NXT-L29`,`NXT-TL00`,`NXT-TL00B`],"Mate 9":[`MHA-AL00`,`MHA-L09`,`MHA-L29`,`MHA-TL00`],"Mate 9 lite":[`BLL-L23`],"Mate 9 Pro":[`LON-AL00`,`LON-L29`],"Mate S":[`CRR-CL00`,`CRR-CL20`,`CRR-L09`,`CRR-TL00`,`CRR-UL00`,`CRR-UL20`],"Mate SE":[`BND-L34`],"nova 2":[`HWV31`,`PIC-AL00`,`PIC-LX9`,`PIC-TL00`],"nova 2 lite":[`LDN-LX2`],"nova 2 Plus":[`BAC-AL00`,`BAC-L01`,`BAC-L03`,`BAC-L21`,`BAC-L22`,`BAC-L23`,`BAC-TL00`],"nova 2i":[`RNE-L02`,`RNE-L22`],"nova 2s":[`HWI-AL00`,`HWI-TL00`],"nova 3":[`PAR-AL00`,`PAR-L21`,`PAR-L29`,`PAR-LX1`,`PAR-LX1M`,`PAR-LX9`,`PAR-TL00`,`PAR-TL20`],"nova 3e":[`ANE-AL00`,`ANE-TL00`],"nova 3i":[`INE-AL00`,`INE-LX1`,`INE-LX1R`,`INE-LX2`,`INE-LX2R`,`INE-TL00`],"nova 4":[`VCE-AL00`,`VCE-L22`,`VCE-TL00`],"nova 4e":[`MAR-AL00`,`MAR-TL00`],"nova 5T":[`YAL-L21`],"nova 5T Pro":[`YAL-L41`],"P smart":[`FIG-LA1`,`FIG-LX2`,`FIG-LX3`],"P smart 2019":[`POT-LX1`,`POT-LX1AF`,`POT-LX3`],"P smart 2020":[`POT-LX1A`],"P smart Pro":[`STK-L21`],"P smart+ 2019":[`POT-LX1T`],P10:[`VTR-AL00`,`VTR-L09`,`VTR-L29`,`VTR-TL00`],"P10 lite":[`WAS-L03T`,`WAS-LX1`,`WAS-LX1A`,`WAS-LX2`,`WAS-LX2J`,`WAS-LX3`],"P10 Plus":[`VKY-AL00`,`VKY-L09`,`VKY-L29`,`VKY-TL00`],P2:[`P2-6070`],P20:[`EML-AL00`,`EML-L09`,`EML-L29`,`EML-TL00`],"P20 lite":[`ANE-LX1`,`ANE-LX2`,`ANE-LX2J`,`ANE-LX3`,`HWV32`],"P20 Pro":[`CLT-AL00`,`CLT-AL00L`,`CLT-AL01`,`CLT-L04`,`CLT-L09`,`CLT-L29`,`CLT-TL00`,`CLT-TL01`,`HW-01K`],P30:[`ELE-AL00`,`ELE-L04`,`ELE-L09`,`ELE-L14`,`ELE-L29`,`ELE-L39`,`ELE-L49`,`ELE-TL00`],"P30 lite":[`HWV33`,`MAR-LX1A`,`MAR-LX1AM`,`MAR-LX1B`,`MAR-LX1M`,`MAR-LX1MM`,`MAR-LX2`,`MAR-LX2B`,`MAR-LX2J`,`MAR-LX2M`,`MAR-LX3A`,`MAR-LX3AM`,`MAR-LX3BM`],"P30 Pro":[`HW-02L`,`VOG-AL00`,`VOG-AL10`,`VOG-L04`,`VOG-L09`,`VOG-L29`,`VOG-TL00`],P6:[`P6-C00`,`P6-T00`,`P6-T00V`,`P6-U06`,`P6-U06-ORANGE`],P7:[`P7-L00`,`P7-L05`,`P7-L07`,`P7-L10`,`P7-L11`,`P7-L12`],P8:[`GRA-CL00`,`GRA-CL10`,`GRA-L09`,`GRA-TL00`,`GRA-UL00`,`GRA-UL10`],"P8 Lite":[`503HW`,`ALE-CL00`,`ALE-L02`,`ALE-L04`,`ALE-L21`,`ALE-L23`],"P8 lite 2017":[`PRA-LA1`],"P8 Max":[`P8MAX`],P9:[`EVA-AL00`,`EVA-AL10`,`EVA-CL00`,`EVA-DL00`,`EVA-L09`,`EVA-L19`,`EVA-L29`,`EVA-TL00`],"P9 lite":[`VNS-L21`,`VNS-L22`,`VNS-L23`,`VNS-L31`,`VNS-L53`,`VNS-L62`],"P9 lite mini":[`SLA-L02`,`SLA-L22`,`SLA-L23`],"P9 Lite PREMIUM":[`VNS-L52`],"P9 lite smart":[`DIG-L03`,`DIG-L23`],"P9 Plus":[`VIE-AL10`,`VIE-L09`,`VIE-L29`]},Honor:{"100 Pro":[`MAA-AN10`],"200 Lite":[`LLY-NX1`,`LLY-NX3`],"200 Pro":[`ELP-AN00`,`ELP-NX9`],"400 Lite":[`ABR-NX1`,`ABR-NX3`],"400 Pro":[`DNP-NX9`],"400 Smart":[`LGN-NX1`,`LGN-NX3`],50:[`NTH-NX9`],"50 Lite":[`NTN-L22`,`NTN-LX1`,`NTN-LX3`],"600 Elite":[`MRK-NX3`],"600 Lite":[`LNA-NX1`],"600 Pro":[`VKP-NX9`],"600 Smart 5G":[`MRK-NX1`],70:[`FNE-NX9`],"70 Lite":[`RBN-NX1`],90:[`REA-NX9`],"90 GT":[`MAG-AN00`],"90 Lite":[`CRT-NX1`,`CRT-NX3`],"90 Smart":[`CLK-NX3`],"Magic V2":[`VER-N49`],"Magic V3":[`FCP-N49`],"Magic V5":[`MBH-N49`],"Magic V6":[`PNM-N49`],"Magic Vs":[`FRI-NX9`],"Magic4 Pro":[`LGE-NX9`],Magic5:[`PGT-N09`],"Magic5 Lite 5G":[`RMO-NX3`],"Magic5 Pro":[`PGT-N19`],Magic6:[`BVL-AN00`],"Magic6 Lite 5G":[`ALI-NX3`],"Magic6 Pro":[`BVL-AN16`,`BVL-N49`],Magic7:[`PTP-N29`],"Magic7 Lite":[`BRP-NX1M`,`BRP-NX3`],"Magic7 Pro":[`PTP-N49`],"Magic8 Lite":[`MTN-NX1M`],"Magic8 Pro":[`BKQ-N49`],X5:[`VNA-LX2`,`VNA-LX3`],"X5 Plus":[`WOD-LX1`,`WOD-LX2`,`WOD-LX3`],X5b:[`GFY-LX2`,`GFY-LX3`],"X5b Plus":[`GFY-LX2P`],X5c:[`NLA-LX2`,`NLA-LX3`],"X5c Plus":[`NLA-LX1`,`NLA-LX2P`],X5d:[`NAA-LX2`,`NAA-LX3`],"X5d Plus":[`NAA-LX2P`],"X5e s":[`MLD-LX2`],X6:[`VNE-LX1`,`VNE-LX2`,`VNE-LX3`],X6a:[`WDY-LX1`,`WDY-LX2`,`WDY-LX3`],X6b:[`JDY-LX1`,`JDY-LX2`,`JDY-LX3P`],"X6b 5G":[`ALT-NX3`],"X6b Plus":[`JDY-LX3`],X6c:[`NIC-LX1`,`NIC-LX2`,`NIC-LX3`],"X6d 5G":[`NLA-NX1`,`NLA-NX3`],X6e:[`LBU-LX1`,`LBU-LX2`,`LBU-LX3`],X7:[`CMA-LX1`,`CMA-LX2`,`CMA-LX3`],X7a:[`RKY-LX1`,`RKY-LX2`,`RKY-LX3`],X7b:[`CLK-LX1`,`CLK-LX2`,`CLK-LX3`],"X7b 5G":[`CLK-NX1`,`CLK-NX2`],X7c:[`ALT-LX1`,`ALT-LX2`,`ALT-LX3`],"X7c 5G":[`ALT-NX1`],X7d:[`LGN-LX1`,`LGN-LX2`,`LGN-LX3`],X7e:[`LAB-LX1`,`LAB-LX2`,`LAB-LX3`],"X7e Plus":[`MRK-LX2`],X8:[`TFY-LX1`,`TFY-LX2`,`TFY-LX3`],"X8 5G":[`VNE-N41`],X8a:[`CRT-LX1`,`CRT-LX2`,`CRT-LX3`],"X8a 5G":[`RBN-NX3`],X8b:[`LLY-LX1`,`LLY-LX2`,`LLY-LX3`],X8c:[`ABR-LX1`,`ABR-LX2`,`ABR-LX3`],X8d:[`LNA-LX2`,`LNA-LX3`],X8e:[`MRK-LX1`],"X8e s":[`MRK-LX3`],X9:[`ANY-LX1`,`ANY-LX2`,`ANY-LX3`],"X9 5G":[`ANY-NX1`],"X9a 5G":[`RMO-NX1`],"X9b 5G":[`ALI-NX1`,`ALI-NX3P`],X9c:[`BRP-NX1`],"X9c Smart":[`BRC-NX1`],X9d:[`MTN-NX1`],"X9e s":[`MTN-NX3`]},Oppo:{"Find N":[`PEUM00`],"Find N2 Flip":[`CPH2437`],"Find N3":[`CPH2499`,`PHN110`],"Find N3 Flip":[`CPH2519`,`PHT110`],"Find N5":[`CPH2671`,`PKH110`],"Find N6":[`CPH2765`,`PLP110`],"Find X":[`CPH1871`,`CPH1875`,`PAFM00`,`PAFT00`],"Find X2":[`CPH2023`],"Find X2 Lite":[`CPH2005`],"Find X2 Pro":[`CPH2025`,`OPG01`],"Find X3 Pro":[`CPH2173`,`OPG03`],"Find X5":[`CPH2307`],"Find X5 Pro":[`CPH2305`],"Find X6":[`PGFM10`],"Find X6 Pro":[`PGEM10`],"Find X7":[`PHZ110`],"Find X7 Ultra":[`PHY110`],"Find X8":[`CPH2651`,`PKB110`],"Find X8 Pro":[`CPH2659`,`PKC110`],"Find X8 Ultra":[`PKJ110`],"Find X8s":[`PKT110`],"Find X8s+":[`PLB110`],"Find X9":[`CPH2797`,`OPG07`,`PLJ110`],"Find X9 Pro":[`CPH2791`,`PLG110`],"Find X9 Ultra":[`CPH2841`,`PMA110`],"Find X9s":[`CPH2873`],"Find X9s Pro":[`PME110`],Find5:[`X909`,`X909T`],Reno:[`CPH1917`],"Reno 10x Zoom":[`CPH1919`,`CPH1919RU`,`CPH1921`],"Reno 11":[`CPH2599`],"Reno 11 Pro":[`CPH2607`],"Reno 2":[`CPH1907`],"Reno 4Z 5G":[`CPH2065`],"Reno A":[`CPH1983`],"Reno Ace":[`PCLM10`],"Reno Ace2":[`PDHM00`],"Reno Z":[`CPH1979`],"Reno10 5G":[`CPH2531`,`PHW110`],"Reno10 Pro 5G":[`A302OP`,`CPH2525`,`CPH2541`,`PHV110`],"Reno10 Pro+ 5G":[`CPH2521`,`PHU110`],Reno11:[`PJH110`],"Reno11 A":[`A401OP`],"Reno11 F 5G":[`CPH2603`],"Reno11 Pro":[`PJJ110`],Reno12:[`PJV110`],"Reno12 5G":[`CPH2625`],"Reno12 F":[`CPH2687`],"Reno12 F 5G":[`CPH2637`],"Reno12 Pro":[`PJW110`],"Reno12 Pro 5G":[`CPH2629`],Reno13:[`PKM110`],"Reno13 5G":[`CPH2689`],"Reno13 A":[`A501OP`,`OPG05`],"Reno13 F":[`CPH2701`],"Reno13 F 5G":[`CPH2699`],"Reno13 Pro":[`PKK110`],"Reno13 Pro 5G":[`CPH2697`],Reno14:[`PLA110`],"Reno14 5G":[`CPH2737`],"Reno14 F 5G":[`CPH2743`],"Reno14 Pro":[`PKZ110`],"Reno14 Pro 5G":[`CPH2739`],Reno15:[`PLW110`],"Reno15 5G":[`CPH2825`],"Reno15 A":[`A601OP`,`OPG08`],"Reno15 C 5G":[`CPH2801`],"Reno15 Pro":[`PLV110`],"Reno15 Pro 5G":[`CPH2811`,`CPH2813`],Reno15c:[`PMD110`],"Reno16 5G":[`CPH2865`],"Reno16 F 5G":[`CPH2967`],"Reno16 Pro":[`PMK110`],"Reno16 Pro 5G":[`CPH2863`],"Reno16c 5G":[`CPH2859`],"Reno2 Z":[`CPH1945`,`CPH1951`],Reno3:[`CPH2043`],"Reno3 5G":[`A001OP`],"Reno3 A":[`A002OP`,`CPH2013`],"Reno3 Pro":[`CPH2009`,`CPH2035`,`CPH2036`,`CPH2037`],"Reno4 5G":[`CPH2091`],"Reno4 F":[`CPH2209`],"Reno4 Lite":[`CPH2125`],"Reno4 Pro":[`CPH2089`,`PDNT00`],Reno5:[`CPH2159`],"Reno5 A":[`A101OP`,`CPH2199`],"Reno5 A (eSIM)":[`A103OP`],"Reno5 F":[`CPH2217`],"Reno5 Lite":[`CPH2205`],"Reno5 Pro":[`CPH2201`],"Reno5 Pro 5G":[`PDSM00`],"Reno5 Pro+ 5G":[`PDRM00`],"Reno6 Pro+ 5G":[`PENM00`],"Reno6 Z 5G":[`CPH2237`],Reno7:[`CPH2363`],"Reno7 5G":[`CPH2371`],"Reno7 A":[`A201OP`,`CPH2353`,`OPG04`],"Reno7 Z 5G":[`CPH2343`],"Reno8 5G":[`CPH2359`],"Reno8 Pro 5G":[`CPH2357`],"Reno8 T":[`CPH2481`],"Reno8 T 5G":[`CPH2505`],"Reno9 A":[`A301OP`,`CPH2523`],"Reno9 Pro 5G":[`PGX110`]},Vivo:{V25:[`V2202`,`V2228`],"V25 Pro":[`V2158`],V25e:[`V2201`,`V2209`,`V2242`],V27:[`V2231`,`V2246`],"V27 Pro":[`V2230`],V27e:[`V2237`],V29:[`V2250`],"V29 Lite 5G":[`V2244`],V29e:[`V2303`],"V29e 5G":[`V2317`],V30:[`V2318`],"V30 Lite":[`V2314`],"V30 Lite 5G":[`V2327`],"V30 Pro":[`V2319`],"V30 SE":[`V2349`],V30e:[`V2339`],V40:[`V2348`],"V40 Lite":[`V2340`,`V2341`,`V2417`,`V2424`],"V40 Pro":[`V2347`],"V40 SE":[`V2342`,`V2418`],"V40 SE 5G":[`V2337`],V40e:[`V2403`],V50:[`V2427`,`V2448`,`V2451`],"V50 Lite":[`V2441`,`V2453`],"V50 Lite 5G":[`V2440`,`V2450`],V50e:[`V2428`],V60:[`V2511`,`V2512`],"V60 Lite":[`V2530`,`V2549`],"V60 Lite 5G":[`V2529`],V60e:[`V2513`],V70:[`V2538`,`V2539`,`V2540`,`V2588`],"V70 Elite":[`V2548`],"V70 FE":[`V2550`,`V2551`,`V2552`,`V2558`],"V70 Lite":[`V2584`,`V2604`,`V2627`,`V2634`,`V2635`],"V70 Lite 5G":[`V2615`,`V2637`],"V80 Lite 5G":[`V2576`,`V2626`,`V2643`,`V2644`,`V2655`],"X Fold":[`V2178A`],"X Fold 2":[`V2266A`],"X Fold 3":[`V2303A`],"X Fold 3 Pro":[`V2330`,`V2337A`],"X Fold 5":[`V2429`,`V2436A`],"X Fold 6":[`V2545A`],"X Fold+":[`V2229A`],"X Note":[`V2170A`],"X100 Pro":[`V2309`,`V2324A`],"X100 Ultra":[`V2366GA`,`V2366HA`],"X100s Pro":[`V2324HA`],X20:[`PD1709`,`X20A`],"X20 Plus":[`PD1710`],"X20 Plus UD":[`PD1721`],X200:[`V2415`,`V2415A`],"X200 FE":[`V2503`,`V2505`],"X200 Pro":[`V2405A`,`V2413`],"X200 Pro mini":[`V2419A`],"X200 Ultra":[`V2454A`,`V2454DA`],X200s:[`V2458A`],"X300 E":[`V2612A`],"X300 FE":[`V2537`,`V2542`,`V2633`],"X300 Pro":[`V2502A`,`V2514`],"X300 Ultra":[`V2547A`,`V2547DA`,`V2562`],X50:[`2004`],"X50 Pro":[`2006`],"X70 Pro+":[`V2114`],X80:[`V2144`,`V2183A`],"X80 Lite 5G":[`V2208`],"X80 Pro":[`V2145`,`V2185A`],X90:[`V2218`,`V2241A`],"X90 Pro":[`V2219`,`V2242A`],"X90 Pro+":[`V2227A`],X90s:[`V2241HA`]},Realme:{10:[`RMX3615`,`RMX3630`],"10 Pro":[`RMX3663`],"10 Pro 5G":[`RMX3660`,`RMX3661`,`RMX3771`],"10 Pro+":[`RMX3687`],"10 Pro+ 5G":[`RMX3686`],"10s":[`RMX3617`],11:[`RMX3636`,`RMX3751`],"11 5G":[`RMX3780`],"11 Pro+":[`RMX3740`],"11 Pro+ 5G":[`RMX3741`],"11x 5G":[`RMX3785`],12:[`RMX3871`],"12 5G":[`RMX3999`],"12 Lite":[`RMX3890`],"12 Pro 5G":[`RMX3842`],"12 Pro+ 5G":[`RMX3840`],"12x 5G":[`RMX3997`],"13 5G":[`RMX3951`],"13 Pro 5G":[`RMX3988`],"13 Pro+ 5G":[`RMX3921`],"14 5G":[`RMX5070`],"14 Pro 5G":[`RMX5056`,`RMX5057`],"14 Pro+ 5G":[`RMX5051`,`RMX5054`],"14T 5G":[`RMX5074`,`RMX5078`],"14x 5G":[`RMX3943`],"15 5G":[`RMX5106`],"15 Pro 5G":[`RMX5101`],"15T":[`RMX5111`],"15x 5G":[`RMX5250`],"16 5G":[`RMX5171`],"16 Pro 5G":[`RMX5120`],"16 Pro+ 5G":[`RMX5131`],"16T 5G":[`RMX5268`],"16x 5G":[`RMX5270`],"2 Pro":[`RMX1801`],"3 Pro":[`RMX1851`],5:[`RMX1911`,`RMX1915`,`RMX1919`,`RMX1925`,`RMX1926`,`RMX1927`],"5 Pro":[`RMX1971`,`RMX1973`],"5i":[`RMX2030`,`RMX2031`,`RMX2032`],6:[`RMX2001`,`RMX2002`,`RMX2003`],"6 Pro":[`RMX2061`,`RMX2063`],"6i":[`RMX2040`,`RMX2041`,`RMX2042`,`RMX2190`],7:[`RMX2151`],"7 5G":[`RMX2111`],"7 Pro":[`RMX2170`],"7i":[`RMX2103`,`RMX2104`,`RMX2193`],8:[`RMX3085`],"8 5G":[`RMX3241`],"8 Pro":[`RMX3081`],"8i":[`RMX3151`],"8s 5G":[`RMX3381`],9:[`RMX3521`],"9 5G":[`RMX3388`,`RMX3474`],"9 5G Speed Edition":[`RMX3461`],"9 Pro 5G":[`RMX3471`,`RMX3472`],"9 Pro+":[`RMX3392`,`RMX3393`],"9i":[`RMX3491`,`RMX3492`,`RMX3493`],"9i 5G":[`RMX3612`],"GT 2":[`RMX3312`],"GT 2 Pro":[`RMX3301`],"GT 5G":[`RMX2202`],"GT 6":[`RMX3851`],"GT 6T":[`RMX3853`],"GT 7 Pro":[`RMX5011`],"GT 7T":[`RMX5085`],"GT Explorer Master Edition":[`RMX3366`],"GT Master Edition":[`RMX3360`,`RMX3361`,`RMX3363`],"GT Neo 3":[`RMX3561`],"GT Neo 3 150W":[`RMX3563`],"GT Neo 3T":[`RMX3371`],"GT Neo 5 SE":[`RMX3701`],"GT Neo2 5G":[`RMX3370`],"GT3 240W":[`RMX3709`],GT5:[`RMX3820`],"GT5 240W":[`RMX3823`],"GT5 Pro":[`RMX3888`]},Sony:{"Xperia 1":[`802SO`,`J8110`,`J8170`,`J9110`,`J9180`,`SO-03L`,`SOV40`],"Xperia 1 II":[`SO-51A`,`SOG01`,`XQ-AT42`,`XQ-AT51`,`XQ-AT52`,`XQ-AT72`],"Xperia 1 III":[`A101SO`,`SO-51B`,`SOG03`,`XQ-BC42`,`XQ-BC52`,`XQ-BC62`,`XQ-BC72`],"Xperia 1 IV":[`A201SO`,`SO-51C`,`SOG06`,`XQ-CT44`,`XQ-CT54`,`XQ-CT62`,`XQ-CT72`],"Xperia 1 Professional Edition":[`J9150`],"Xperia 1 V":[`A301SO`,`SO-51D`,`SOG10`,`XQ-DQ44`,`XQ-DQ54`,`XQ-DQ62`,`XQ-DQ72`],"Xperia 1 VI":[`A401SO`,`SO-51E`,`SOG13`,`XQ-EC44`,`XQ-EC54`,`XQ-EC72`],"Xperia 1 VII":[`A501SO`,`SO-51F`,`SOG15`,`XQ-FS44`,`XQ-FS54`,`XQ-FS72`],"Xperia 1 VIII":[`A601SO`,`SO-51G`,`SOG17`,`XQ-GE44`,`XQ-GE54`,`XQ-GE74`],"Xperia 10":[`I3113`,`I3123`,`I4113`,`I4193`],"Xperia 10 II":[`A001SO`,`SO-41A`,`SOV43`,`XQ-AU42`,`XQ-AU51`,`XQ-AU52`],"Xperia 10 III":[`A102SO`,`SO-52B`,`SOG04`,`XQ-BT52`],"Xperia 10 III Lite":[`XQ-BT44`],"Xperia 10 IV":[`A202SO`,`SO-52C`,`SOG07`,`XQ-CC44`,`XQ-CC54`,`XQ-CC72`],"Xperia 10 Plus":[`I3213`,`I3223`,`I4213`,`I4293`],"Xperia 10 V":[`A302SO`,`SO-52D`,`SOG11`,`XQ-DC44`,`XQ-DC54`,`XQ-DC72`],"Xperia 10 VI":[`A402SO`,`SO-52E`,`SOG14`,`XQ-ES44`,`XQ-ES54`,`XQ-ES72`],"Xperia 10 VII":[`A502SO`,`SO-52F`,`SOG16`,`XQ-FE44`,`XQ-FE54`,`XQ-FE72`],"Xperia 10 VIII":[`XQ-GH54`,`XQ-GH74`],"Xperia 5":[`901SO`,`J8210`,`J8270`,`J9210`,`J9260`,`SO-01M`,`SOV41`],"Xperia 5 II":[`A002SO`,`SO-52A`,`SOG02`,`XQ-AS42`,`XQ-AS52`,`XQ-AS62`,`XQ-AS72`],"Xperia 5 III":[`A103SO`,`SO-53B`,`SOG05`,`XQ-BQ42`,`XQ-BQ52`,`XQ-BQ62`,`XQ-BQ72`],"Xperia 5 IV":[`A204SO`,`SO-54C`,`SOG09`,`XQ-CQ44`,`XQ-CQ54`,`XQ-CQ62`,`XQ-CQ72`],"Xperia 5 V":[`SO-53D`,`SOG12`,`XQ-DE44`,`XQ-DE54`,`XQ-DE72`],"Xperia 8":[`902SO`,`SOV42`,`SOV42-U`],"Xperia 8 Lite":[`J3273`],"Xperia A":[`SO-04E`],"Xperia A2":[`SO-04F`],"Xperia A4":[`SO-04G`],"Xperia Ace":[`J3173`,`SO-02L`],"Xperia Ace II":[`SO-41B`],"Xperia Ace III":[`A203SO`,`SO-53C`,`SOG08`],"Xperia acro HD":[`SO-03D`],"Xperia acro S":[`LT26W`],"Xperia active":[`ST17I`],"Xperia arc S":[`LT18I`],"Xperia C":[`C2304`,`C2305`],"Xperia C3":[`D2533`],"Xperia C3 Dual":[`D2502`],"Xperia C4":[`E5303`,`E5306`,`E5353`],"Xperia C4 Dual":[`E5333`,`E5343`,`E5363`],"Xperia C5 Ultra":[`E5506`,`E5553`],"Xperia C5 Ultra Dual":[`E5533`,`E5563`],"Xperia E":[`C1504`,`C1505`],"Xperia E dual":[`C1604`,`C1605`],"Xperia E1":[`D2004`,`D2005`,`D2114`],"Xperia E1 dual":[`D2104`,`D2105`],"Xperia E3":[`D2202`,`D2203`,`D2206`,`D2243`],"Xperia E3 Dual":[`D2212`],"Xperia E4":[`E2104`,`E2105`],"Xperia E4 Dual":[`E2115`,`E2124`],"Xperia E4g":[`E2003`,`E2006`,`E2053`],"Xperia E4g Dual":[`E2033`,`E2043`],"Xperia E5":[`F3311`,`F3313`],"Xperia Go":[`ST27A`,`ST27I`],"Xperia ion":[`LT28H`,`LT28I`],"Xperia J":[`ST26A`,`ST26I`],"Xperia J1 Compact":[`D5788`],"Xperia L":[`C2104`,`C2105`],"Xperia L1":[`G3311`,`G3312`,`G3313`],"Xperia L2":[`H3311`,`H3321`,`H4311`,`H4331`],"Xperia L3":[`I3312`,`I4312`,`I4332`],"Xperia L4":[`XQ-AD51`,`XQ-AD52`],"Xperia M":[`C1904`,`C1905`],"Xperia M dual":[`C2004`,`C2005`],"Xperia M2":[`D2303`,`D2305`,`D2306`],"Xperia M2 Aqua":[`D2403`,`D2406`],"Xperia M2 Dual":[`D2302`],"Xperia M4 Aqua":[`E2303`,`E2306`,`E2353`],"Xperia M4 Aqua Dual":[`E2312`,`E2333`,`E2363`],"Xperia M5":[`E5603`,`E5606`,`E5653`],"Xperia M5 Dual":[`E5633`,`E5643`,`E5663`],"Xperia mini pro":[`SK17A`],"Xperia miro":[`ST23A`,`ST23I`],"Xperia neo L":[`MT25I`],"Xperia P":[`LT22I`],"Xperia PLAY":[`R800A`,`R800I`],"Xperia PRO":[`XQ-AQ52`,`XQ-AQ62`],"Xperia PRO-I":[`XQ-BE42`,`XQ-BE52`,`XQ-BE62`,`XQ-BE72`],"Xperia R1":[`G2199`],"Xperia R1 Plus":[`G2299`],"Xperia ray":[`ST18I`],"Xperia S":[`LT26I`],"Xperia SL":[`LT26II`],"Xperia sola":[`MT27I`],"Xperia SP":[`C5302`,`C5303`,`C5306`,`M35H`,`M35T`],"Xperia T":[`LT30A`,`LT30P`],"Xperia T2 Ultra":[`D5303`,`D5306`,`D5316`,`D5316N`,`D5322`],"Xperia T3":[`D5102`,`D5103`,`D5106`],"Xperia Tipo":[`ST21A`,`ST21I`,`ST21I2`],"Xperia tipo dual":[`ST21A2`],"Xperia TX":[`LT29I`],"Xperia U":[`ST25A`,`ST25I`],"Xperia V":[`LT25I`],"Xperia X":[`F5121`,`F5122`],"Xperia X Compact":[`F5321`,`SO-02J`],"Xperia X Performance":[`502SO`,`F8131`,`F8132`,`SO-04H`,`SOV33`],"Xperia XA":[`F3111`,`F3112`,`F3113`,`F3115`,`F3116`],"Xperia XA Ultra":[`F3211`,`F3212`,`F3213`,`F3215`,`F3216`],"Xperia XA1":[`G3112`,`G3116`,`G3121`,`G3123`,`G3125`],"Xperia XA1 Plus":[`G3412`,`G3416`,`G3421`,`G3423`,`G3426`],"Xperia XA1 Ultra":[`G3212`,`G3221`,`G3223`,`G3226`],"Xperia XA2":[`H3113`,`H3123`,`H3133`,`H4113`,`H4133`],"Xperia XA2 Plus":[`H3413`,`H4413`,`H4493`],"Xperia XA2 Ultra":[`H3213`,`H3223`,`H4213`,`H4233`],"Xperia XZ":[`601SO`,`F8331`,`F8332`,`SO-01J`,`SOV34`],"Xperia XZ Premium":[`G8141`,`G8142`,`G8188`,`SO-04J`],"Xperia XZ1":[`701SO`,`G8341`,`G8342`,`G8343`,`SO-01K`,`SOV36`],"Xperia XZ1 Compact":[`G8441`,`SO-02K`],"Xperia XZ2":[`702SO`,`H8216`,`H8266`,`H8276`,`H8296`,`SO-03K`,`SOV37`],"Xperia XZ2 Compact":[`H8314`,`H8324`,`SO-05K`],"Xperia XZ2 Premium":[`H8116`,`H8166`,`SO-04K`,`SOV38`],"Xperia XZ3":[`801SO`,`H8416`,`H9436`,`H9493`,`SO-01L`,`SOV39`],"Xperia XZs":[`602SO`,`G8231`,`G8232`,`SO-03J`,`SOV35`],"Xperia Z":[`C6602`,`C6603`,`C6606`,`C6616`,`L36H`,`SO-02E`],"Xperia Z Ultra":[`C6802`,`C6806`,`C6833`,`C6843`,`SGP412`,`SOL24`,`XL39H`],"Xperia Z1":[`C6902`,`C6903`,`C6906`,`C6916`,`C6943`,`L39H`,`L39T`,`L39U`,`SO-01F`,`SOL23`],"Xperia Z1 Compact":[`D5503`,`M51W`],"Xperia Z1f":[`SO-02F`],"Xperia Z2":[`D6502`,`D6503`,`D6543`,`SO-03F`],"Xperia Z2a":[`D6563`],"Xperia Z3":[`401SO`,`D6603`,`D6616`,`D6643`,`D6646`,`D6653`,`SO-01G`,`SOL26`],"Xperia Z3 Compact":[`D5803`,`D5833`,`SO-02G`],"Xperia Z3 Dual":[`D6633`,`D6683`],"Xperia Z3+":[`E6553`],"Xperia Z3+ Dual":[`E6533`],"Xperia Z3v":[`D6708`],"Xperia Z4":[`402SO`,`SO-03G`,`SOV31`],"Xperia Z4v":[`E6508`],"Xperia Z5":[`501SO`,`E6603`,`E6653`,`SO-01H`,`SOV32`],"Xperia Z5 Compact":[`E5803`,`E5823`,`SO-02H`],"Xperia Z5 dual":[`E6633`,`E6683`],"Xperia Z5 Premium":[`E6853`,`E6883`,`SO-03H`],"Xperia Z5 Premium Dual":[`E6833`],"Xperia ZL":[`C6502`,`C6503`,`C6506`,`L35H`],"Xperia ZL2":[`SOL25`],"Xperia ZR":[`C5502`,`C5503`]},Asus:{"PadFone mini":[`ASUS_T00E`],"PadFone S":[`ASUS_T00N`],"PadFone X mini":[`ASUS_T00T`],"ROG Phone":[`ASUS_Z01QD`,`ZS600KL`],"ROG Phone 3":[`ASUS_I003D`,`ASUS_I003DD`,`ZS661KS`],"ROG Phone 5":[`ASUS_I005D`,`ASUS_I005DA`,`ASUS_I005DB`,`ZS673KS`,`ZS676KS`],"ROG Phone 6":[`ASUS_AI2201_A`,`ASUS_AI2201_B`,`ASUS_AI2201_C`,`ASUS_AI2201_D`],"ROG Phone 6D":[`ASUS_AI2203_B`],"ROG Phone 6D Ultimate":[`ASUS_AI2203_C`,`ASUS_AI2203_D`],"ROG Phone 7":[`ASUS_AI2205_A`,`ASUS_AI2205_C`],"ROG Phone 8":[`ASUS_AI2401_A`,`ASUS_AI2401_C`,`ASUS_AI2401_D`],"ROG Phone 9":[`ASUSAI2501A`,`ASUSAI2501B`],"ROG Phone 9 FE":[`ASUS_AI2401_N`],"ROG Phone 9 Pro":[`ASUSAI2501C`],"ROG Phone II":[`ASUS_I001D`,`ASUS_I001DC`,`ASUS_I001DE`,`ZS660KL`],"Zenfone 10":[`ASUS_AI2302`],"Zenfone 11 Ultra":[`ASUS_AI2401_H`],"Zenfone 12 Ultra":[`ASUSAI2501H`],"ZenFone 2":[`ASUS_Z008D`,`ASUS_Z00AD`,`ASUS_Z00ADA`,`ASUS_Z00ADB`,`Z00D`],"ZenFone 2 Laser":[`ASUS_Z00ED`,`ASUS_Z00EDB`,`ASUS_Z00LD`,`ASUS_Z00LDC`,`ASUS_Z00MD`,`ASUS_Z00RD`,`ASUS_Z00TD`,`ASUS_Z00WD`,`ASUS_Z011D`],"ZenFone 3":[`ASUS_Z012D`,`ASUS_Z012DA`,`ASUS_Z012DE`,`ASUS_Z012S`,`ASUS_Z017D`,`ASUS_Z017DA`],"ZenFone 3 Deluxe":[`ASUS_Z016D`,`ASUS_Z016DA`,`ASUS_Z016S`,`ASUS_Z01FD`],"ZenFone 3 Laser":[`ASUS_Z01BD`,`ASUS_Z01BDA`,`ASUS_Z01BDC`,`ASUS_Z01BS`],"ZenFone 3 Max":[`ASUS_X008D`,`ASUS_X008DA`,`ASUS_X008DB`,`ASUS_X008DC`,`ASUS_X00DD`,`ASUS_X00DDA`],"ZenFone 3 Ultra":[`ASUS_A001`],"ZenFone 3 Zoom":[`ASUS_Z01HD`,`ASUS_Z01HDA`],"ZenFone 3s Max":[`ASUS_X00GD`],"ZenFone 4":[`ASUS_T00I`,`ASUS_T00I-D`,`ASUS_T00Q`,`ASUS_Z01KD`,`ASUS_Z01KDA`,`ASUS_Z01KS`],"ZenFone 4 Max":[`ASUS_X00HD`,`ASUS_X00ID`],"ZenFone 4 Pro":[`ASUS_Z01GD`],"ZenFone 4 Selfie":[`ASUS_X00LD`],"ZenFone 4 Selfie Lite":[`ASUS_X00HDA`],"ZenFone 4 Selfie Pro":[`ASUS_Z01MD`,`ASUS_Z01MDA`],"ZenFone 5":[`ASUS_T00F`,`ASUS_T00J`,`ASUS_T00K`,`ASUS_X00QD`,`ASUS_X00QSA`,`ZE620KL`],"ZenFone 5 Lite":[`ASUS_X017D`,`ASUS_X017DA`,`ZC600KL`],"ZenFone 5 LTE":[`ASUS_T00P`],"ZenFone 5Z":[`ASUS_Z01RD`,`ZS620KL`],"ZenFone 6":[`ASUS_I01WD`,`ASUS_T00G`,`ASUS_Z002`,`ZS630KL`],"ZenFone 7":[`ASUS_I002D`,`ZS670KS`,`ZS671KS`],"Zenfone 8":[`ASUS_I006D`,`ZS590KS`],"Zenfone 8 Flip":[`ASUS_I004D`,`ZS672KS`],"Zenfone 9":[`ASUS_AI2202`],"ZenFone AR":[`ASUS_A002`,`ASUS_A002A`],"ZenFone C":[`ASUS_Z007`],"ZenFone Go":[`ASUS_L001`,`ASUS_X003`,`ASUS_X007D`,`ASUS_X009DB`,`ASUS_X00AD`,`ASUS_X00BD`,`ASUS_X013DA`,`ASUS_X013DB`,`ASUS_X014D`,`ASUS_Z00SD`,`ASUS_Z00VD`],"ZenFone Lite L1":[`ASUS_X00RD`,`G553KL`],"ZenFone Live":[`ASUS_A007`],"ZenFone Live L1":[`G552KL`,`ZA550KL`],"ZenFone Live Plus":[`ASUS_X00LDA`,`ASUS_X00LDB`,`ZB553KL`],"ZenFone Max":[`ASUS_Z010D`,`ASUS_Z010DA`,`ASUS_Z010DB`,`ASUS_Z010DD`],"ZenFone Max M1":[`ASUS_X00PD`,`ZB555KL`],"ZenFone Max M2":[`ASUS_X01AD`,`ZB633KL`],"ZenFone Max Plus M1":[`ASUS_X018D`],"ZenFone Max Pro M1":[`ASUS_X00TD`,`ASUS_X00TDB`,`ZB602KL`],"ZenFone Max Pro M2":[`ASUS_X01BDA`,`ZB631KL`],"ZenFone Max Shot":[`ASUS_A001D`],"ZenFone Selfie":[`ASUS_Z00UD`,`ASUS_Z00UDA`],"ZenFone V":[`ASUS_A006`],"ZenFone V Live":[`ASUS_A009`],"ZenFone Zoom":[`ASUS_Z00XS`,`ASUS_Z00XSA`,`ASUS_Z00XSB`]},HTC:{"Amaze 4G":[`HTC_AMAZE_4G`],Butterfly:[`DLXUB1`,`DLX_U`,`X920E`],"Butterfly 2":[`HTC_B810X`],"Butterfly 3":[`HTC_B830X`],"Butterfly S":[`HTC_BUTTERFLY_S_901S`],"Butterfly s 9060":[`9060`],Desire:[`PB99400`,`X06HT`],"Desire 10 compact":[`2PZS1`],"Desire 10 lifestyle":[`HTC_D10U`],"Desire 10 pro":[`2PYA3`,`HTC_D10I`],"Desire 12":[`2Q5V1`,`2Q5V200`],"Desire 12+":[`2Q5W1`,`2Q5W2`,`ZQ5W10000`],"Desire 12s":[`2Q721`],"Desire 19+":[`2Q74100`],"Desire 19s":[`2Q8L10000`],"Desire 20 Pro":[`2Q9J100`,`2Q9J10000`],"Desire 20+":[`2Q9U100`],"Desire 200":[`HTC_DESIRE_200`],"Desire 21 Pro 5G":[`2QAG100`],"Desire 22 5G":[`2QBK100`,`2QBK10000`],"Desire 300":[`301E`,`HTC_0P6A1`,`HTC_DESIRE_300`],"Desire 310":[`D310W`,`HTC_D310N`,`HTC_V1`],"Desire 320":[`0PF11`,`0PF120`,`HTC_DESIRE_320`],"Desire 326G dual sim":[`2PNT1`],"Desire 500":[`HTC_DESIRE_500`],"Desire 500 dual sim":[`5060`],"Desire 501":[`HTC_603H`],"Desire 5088":[`5088`],"Desire 510":[`0PCV1`,`0PCV20`,`HTC_0PCV2`],"Desire 516":[`D516D`,`D516T`,`D516W`],"Desire 520":[`0PGQ1`],"Desire 526":[`0PM31`,`HTCD100LVW`,`HTCD100LVWPP`],"Desire 526G+ dual sim":[`0PL4100`,`HTC_D526H`],"Desire 526GPLUS":[`0PL41`],"Desire 530":[`2PST1`,`2PST2`,`2PST3`,`HTCD160LVW`,`HTCD160LVWPP`,`HTC_D530U`],"Desire 601":[`HTC0P4E1`,`HTC_0P4E2`],"Desire 606w":[`606W`],"Desire 608t":[`608T`],"Desire 609d":[`609D`],"Desire 610":[`HTC_0P9O2`,`HTC_D610X`],"Desire 612":[`0P9O30`],"Desire 616 dual sim":[`D616W`],"Desire 620":[`0PE64`],"Desire 620 dual sim":[`HTC_D620U`],"Desire 620G dual sim":[`0PE65`,`HTC_D620H`],"Desire 626":[`0PKX2`,`D626D`,`HTCD200LVW`,`HTCD200LVWPP`,`HTC_0PKX2`,`HTC_D626X`,`HTC_D630X`],"Desire 626G+ dual sim":[`0PM11`,`HTC_D626PH`],"Desire 626s":[`0PM912`,`0PM92`],"Desire 628 dual sim":[`2PVG2`],"Desire 630 dual sim":[`2PST5`],"Desire 650":[`2PYR1`,`HTC_D650H`],"Desire 700 dual sim":[`HTC_709D`],"Desire 7060":[`HTC_7060`],"Desire 7088":[`7088`],"Desire 709d":[`709D`],"Desire 728":[`2PQ84`],"Desire 728G dual sim":[`2PQ83`],"Desire 816":[`HTC_0P9C2`,`HTC_D816X`],"Desire 816G dual sim":[`D816H`],"Desire 820":[`0PFJ4`],"Desire 820G PLUS dual sim":[`HTC_D820PI`],"Desire 820s":[`D820TS`,`D820US`],"Desire 825":[`2PUK2`,`HTC_D825U`],"Desire 825 dual sim":[`2PUK1`],"Desire 826":[`D826D`,`D826W`,`HTC_D826Y`],"Desire 828":[`2PRE4`,`D828W`,`HTC_D828G`,`HTC_D828X`],"Desire 828 dual sim":[`2PRE2`],"Desire 830":[`HTC_D830X`],"Desire 830 dual sim":[`2PVD1`,`D830U`],"Desire D626w":[`D626W`],"Desire D820 Mini":[`D820MT`,`D820MU`],"Desire EYE":[`0PFH11`,`0PFH2`,`HTC_M910X`],"Desire HD":[`001HT`],"Desire V":[`PROMIN_U`,`PRO_DS`,`T327W`,`T328W`],"Desire VC":[`PRO_DD`,`T328D`],"Desire X":[`POO_U`],"Droid DNA":[`HTC6435LRA`,`HTC6435LVW`],"Droid Incredible":[`ADR6300`],"Droid Incredible 4G LTE":[`ADR6410LRA`,`ADR6410LVW`,`ADR6410OM`],"EVO 3D":[`HTCEVOV4G`,`PG86100`],"EVO 3D ISW12HT":[`ISW12HT`],"Evo 4G":[`PC36100`],"EVO Shift 4G":[`PG06100`],Hero:[`HERO200`,`T-MOBILE_G2_TOUCH`],"Incredible 2":[`ADR6350`],"Incredible S":[`HTC_S710E`],"myTouch 4G Slide":[`MYTOUCH_4G_SLIDE`],"One (E8)":[`0PAJ5`,`HTC_M8SX`,`M8SD`,`M8ST`,`ONE_E8`],"One (E8) dual sim":[`0PAJ4`,`HTC_M8SY`],"One (M8 EYE)":[`0P6B9`,`0P6B900`],"One (M8)":[`831C`,`HTC6525LVW`,`HTC_0P6B`,`HTC_0P6B6`,`HTC_M8X`,`M8D`,`M8W`,`ONE_M8`],"One A9":[`2PQ93`,`A9W`,`HTC_A9U`],"One A9s":[`2PWD2`,`HTC_A9SX`],"One E8 dual":[`HTC_M8SD`],"One E9 dual sim":[`0PL31`],"One E9s dual sim":[`D826SW`,`HTC_E9SX`],"One M8 eye 4G LTE":[`M8ET`,`M8EW`],"One M8s":[`HTC_0PKV1`],"One M9":[`0PJA10`,`0PJA2`,`HTC6535LRA`,`HTC6535LVW`,`HTC_0PJA10`,`HTC_M9U`],"One M9+":[`0PK71`,`HTC_M9PW`,`M9PT`],"One max":[`HTC0P3P7`,`HTC_ONE_MAX`],"One ME dual sim":[`0PLA1`],"One mini":[`HTC_ONE_MINI_601E`,`HTC_PO582`],"One mini 2":[`HTC_M8MINX`,`HTC_ONE_MINI_2`],"One remix":[`HTC6515LVW`],"One S":[`VLE_U`,`Z560E`],"One S9":[`2PRG100`,`HTC_S9U`],"One SV":[`C525C`,`K2_U`,`K2_UL`],"One X":[`S720E`],"One X10":[`2PXH1`,`2PXH2`,`2PXH3`,`HTC_X10U`],"One X9":[`2PS5200`],"One X9 dual sim":[`HTC_X9U`,`X9U`],"One XL":[`EVA_UTL`,`HTC_ONE_XL`],"Sensation 4G":[`HTC-Z710A`],"Sensation XL with Beats Audio X315e":[`HTC-X315E`],Thunderbolt:[`ADR6400L`],"U Play":[`2PWD1`,`2PZM3`,`HTC_U-2U`],"U Ultra":[`2PZF1`,`HTC_U-1U`,`U-1W`],U11:[`2PZC100`,`2PZC5`,`601HT`,`HTC_U-3U`,`HTV33`,`U-3W`,`U11`],"U11 EYEs":[`2Q4R1`,`2Q4R100`,`2Q4R300`,`2Q4R400`],"U11+":[`2Q4D200`,`HTC_2Q4D100`],"U12 Life":[`2Q6E1`],"U12+":[`2Q551`,`2Q551+`,`2Q55100`,`2Q552`,`2Q55300`,`U12+`],U19e:[`2Q7A100`],"U20 5G":[`2Q9F100`],"U23 pro":[`2QC9100`],"Velocity 4G":[`HTC-X710A`,`PH39100`],"Wildfire S":[`HTC-A510A`],"Wildfire S A515c":[`HTC-PG762`,`USCCADR6230US`]},ZTE:{"Axon 11":[`A2021E`,`A2021L`],"Axon 11 5G":[`A2021`,`A2021G`,`A2021H`],"Axon 11 SE 5G":[`9000N`],"Axon 20 5G":[`A2121G`],"Axon 30 5G":[`A2022`,`A2022H`],"Axon 30 Pro 5G":[`A2022P`],"Axon 30 Ultra 5G":[`A2022PG`],"Axon 60":[`Z2356`],"Axon 60 Lite":[`Z2350`],Blade:[`003Z`,`BLADE_N880`,`MF8604`,`N880`,`V8502`,`V880`,`XCD35`,`ZTE-BLADE`,`ZTE-LIBRA`],"Blade A3 2019":[`P500`],"Blade A35e":[`Z2466`],"Blade A3v":[`Z5157V`,`Z5157Y`],"Blade A460":[`A460-T`,`T610`],"Blade A5 2020":[`Z-ULTRA`],"Blade A512":[`Z10`],"Blade A53+":[`P630`],"Blade A56":[`Z2473`],"Blade A72s":[`A7050`],"Blade A73":[`7060`],"Blade A75 5G":[`Z2357N`],"Blade A76":[`Z2474`],"Blade A76 5G":[`Z2469N`],"Blade A7s 2020":[`A7020`,`A7020RU`],"Blade C340":[`T220`,`V812`],"Blade Force":[`N9517`],"Blade G Lux":[`V830W`],"Blade L3":[`X8607`],"Blade Q Lux":[`T311`],"Blade Q3":[`T230`],"Blade S6":[`LS-5008`],"Blade S6 Lite":[`T912`],"Blade V 2020":[`9000`,`9000RU`],"Blade V2020 Vita":[`8000`],"Blade V50 Design":[`8050`],"Blade V50 Design 5G":[`8150N`],"Blade V50 Vita":[`8550`],"Blade V6":[`T660`,`T663`],"Blade V70 Max":[`Z2467`],"Blade V70 Vita":[`Z2458`],"Blade V9":[`V0900`],"Blade X Max":[`Z983`],"Blade X1 5G":[`Z6750M`],"Blade X10":[`T1002`],"Blade X10 II":[`T1006`],"Blade X10 II Pro+":[`T1004`],"Blade X10 Pro":[`T1003`],"Blade X1001":[`X1001`],"Blade X1101":[`X1101`],"Blade X2 Max":[`Z6400C`],"Blade X8 II":[`T0805`],"Blade X8 Pro":[`T0802`],"Blade X8701":[`X8701`],"Blade ZMax":[`Z982`],"Grand S II":[`S221`],"Grand X":[`V970`,`V970M`],"Grand X 2":[`V968`,`V969`],"Grand X Max 2":[`Z988`],"Grand X Quad Lite":[`V8602`,`V967S`],"Grand X View 3":[`K83CA`],"Kis 3":[`V811`],Racer:[`MTS-SP100`,`V8402`,`X850`,`ZTE-LINK`,`ZTE-RACER`],Skate:[`ZTE-SKATE`],"ZMax 3":[`Z978`],"ZMax One":[`Z719DL`],"ZMax Pro":[`Z981`]},Nothing:{"CMF by Nothing Phone 1":[`A015`],"CMF Phone 2 Pro":[`A001`],"Phone (1)":[`A063`],"Phone (2)":[`A065`,`AIN065`],"Phone (2a)":[`A142`],"Phone (2a) Plus":[`A142P`],"Phone (3)":[`A024`],"Phone (3a)":[`A059`],"Phone (3a) Lite":[`A001T`],"Phone (3a) Pro":[`A059P`],"Phone (4a)":[`A069`],"Phone (4a) Pro":[`A069P`],"Phone (4b)":[`A009P`]}},ModelsByMake=lazy2(()=>{let e=new Map;for(let[n,r]of entries(PhoneModelsByMake)){let a=new Map;for(let[e,n]of entries(r))for(let r of n)a.set(r,e);e.set(n,a)}return e});function phoneModel(e,n){let r=n.toUpperCase();if(e!==`Samsung`)return ModelsByMake().get(e)?.get(r);for(let e=9;e>=7;e--){let n=SamsungModelsByPrefix[r.slice(0,e)];if(n!=null)return n}}function replaceAll2(e,n,r=``){let a=e.replace(n,r);return a===e?e:replaceAll2(a,n,r)}var CamelCasedCos=[`BenQ`,`GoPro`,`HTC`,`LG`,`NEC`,`OnePlus`,`Sony`,`TrueHDR`],Lower2Camel=new Map(CamelCasedCos.map(e=>[e.toLowerCase(),e]));function companyCased(e){let n=e.trim();return Lower2Camel.get(n.toLowerCase())??(n.length<4?n:n.toLowerCase().replace(/(?:^|\s|-)\S/g,e=>e.toUpperCase()))}var Constants=class{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`.split(`.`).join(`|`);ignorableSep=`[\\s\\.,_-]*`;IgnorableMakePatterns=RegExp(`${this.ignorableSep}(?:${this.ignorables})${this.ignorableSep}$`,`i`);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];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+/,`Galaxy S5`],[/^SC-03|SCV41/,`Galaxy S10`],[/^SC-04|SC-05|SCV42/,`Galaxy S10+`]];lgPatterns=[[/LG-D80[0-35]|LS98|VS980|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|VS988/,`G6`],[/^(?:LG-|LM-)?G71\d/i,`G7`],[/^LM-G81\d/i,`G8s`],[/^LM-G82\d/i,`G8`],[/^LM-G85\d|^901LG$/i,`G8X`],[/^LG-(?:H90[01]|H96[0-8]|F600)|^RS987$|^VS990$/i,`V10`],[/^LG-(?:H91[058]|H990|LS997|US996|F800)|^LGV34$|^VS995$/i,`V20`],[/^LGV35$|^L-01K$/i,`V30+`],[/^LG-(?:AS|LS|US|H)9(?:3[0-3]|98)|^LGM-V300|^VS996$/i,`V30`],[/^LM-V35\d/i,`V35`],[/^LM-V40[59]/i,`V40`],[/^LM-V(?:450|500)/i,`V50`],[/^LM-V60\d|^L-51A$/i,`V60`],[/^LM-G9[01]0|^L-52A$/i,`Velvet`],[/^LM-F100/i,`Wing`]];onePlusPatterns=[[/A0001/,`One`],[/A100\d|E100\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|GM1905/,`7`],[/GM1910|GM1911|GM1913|GM1915|GM1917|GM1920|GM1925/,`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`],[/KB2000|KB2001|KB2003|KB2005/,`8T`],[/KB2007/,`8T+`],[/LE2110|LE2111|LE2113|LE2115|LE2117/,`9`],[/LE2120|LE2121|LE2123|LE2125|LE2127/,`9 Pro`],[/LE2100|LE2101/,`9R`],[/MT2110|MT2111/,`9RT`],[/NE2210|NE2211|NE2213|NE2215|NE2217/,`10 Pro`],[/CPH2411|CPH2423/,`10R`],[/CPH2413|CPH2415|CPH2417|CPH2419/,`10T`],[/PHB110|CPH2447|CPH2449|CPH2451/,`11`],[/CPH2487/,`11R`],[/PJD110|CPH2573|CPH2581|CPH2583/,`12`],[/CPH2585|CPH2609|CPH2611/,`12R`],[/PJZ110|CPH2649|CPH2653|CPH2655/,`13`],[/CPH2645|CPH2647|CPH2691/,`13R`],[/CPH2723/,`13s`],[/PKX110/,`13T`],[/PLK110|CPH2745|CPH2747|CPH2749/,`15`],[/CPH2767|CPH2769|CPH2771/,`15R`],[/PLZ110/,`15T`],[/CPH2551/,`Open`],[/PGP110/,`Ace Pro`],[/AC2001|AC2003/,`Nord`],[/DN2101|DN2103/,`Nord 2`],[/CPH2399|CPH2401/,`Nord 2T`],[/CPH2491|CPH2493/,`Nord 3`],[/CPH2661|CPH2663/,`Nord 4`],[/CPH2707|CPH2709/,`Nord 5`],[/CPH2793|CPH2795/,`Nord 6`],[/EB2101|EB2103/,`Nord CE`],[/IV2201/,`Nord CE 2`],[/CPH2381|CPH2409/,`Nord CE 2 Lite`],[/CPH2465|CPH2467/,`Nord CE 3 Lite`],[/CPH2613/,`Nord CE 4`],[/CPH2619|CPH2621/,`Nord CE 4 Lite`],[/CPH2717|CPH2719/,`Nord CE 5`],[/CPH2805|CPH2807/,`Nord CE 6`],[/CPH2943/,`Nord CE 6 Lite`],[/BE2011|BE2012|BE2013|BE2015/,`Nord N100`],[/BE2025|BE2026|BE2028|BE2029/,`Nord N10`],[/CPH2459|GN2200/,`Nord N20`],[/DE2117|DE2118/,`Nord N200`],[/CPH2513|CPH2515/,`Nord N30`],[/CPH2605/,`Nord N30 SE`],[/CPH2389/,`Nord N300`]];CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}},i=lazy2(()=>new Constants),GoProRe=/\bgopro\b/i;function goProMakeMaybe(e){return GoProRe.test(toS(e.HandlerDescription))||GoProRe.test(toS(e.CompressorName))?`GoPro`:void 0}function extractMakeAndModel(e){if(e==null)return{};let n=make(e.Make)??makeFromSoftware(e.Software)??makeFromSoftware(e.CreatorTool)??goProMakeMaybe(e);return compactValues({Make:n,Model:model(n,toExifDefined(e.Model)??toExifDefined(e.CameraModel))})??{}}function invalidCameraIdentifier(e){return hasEncodingCorruption(e)||isPlaceholderOnly(e)||lacksContentBearingChars(e)}function make(e){if(isExifUnset(e))return;let n=stripQuotes(e);if(!(isExifUnset(n)||invalidCameraIdentifier(n)))return/Hewlett[- ]Packard/i.test(n)?`HP`:(n=replaceAll2(n,i().IgnorableMakePatterns),n=n.replace(/\s+app on Apple iDevice$/i,``),n=n.replace(/\bLGE\b/,`LG`),n=n.replace(/\bEastman Kodak\b/i,`Kodak`),n=companyCased(n),n=n.replace(/^OM$/i,`OM System`),n)}var SoftwarePatterns={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 makeFromSoftware(e){if(!blank(e)){for(let[n,r]of entries(SoftwarePatterns))if(r.test(e))return n}}var AncientSamsungModel=/<\s*(\S[^,/]+)[,/]/;function model(e,n){if(isExifUnset(e)||isExifUnset(n))return;let r=stripQuotes(n);if(isExifUnset(r)||invalidCameraIdentifier(r))return;if(e===`Samsung`){let e=AncientSamsungModel.exec(r);e!=null&&(r=e[1].trim())}r=r.replace(RegExp(`^${escapeRegExp(e)}\\s+`,`i`),``);let a=phoneModel(e,r);if(a!=null)return a;let o=map(i().CommonNamesByMake[e],e=>e.find(([e])=>r.match(e)!=null));if(o!=null)return o[1].trim();if(e===`Xiaomi`&&(r=r.replace(/^MI[ _-]?(?=\d)/,`Mi `).replace(/^MI\b/,`Mi`).replace(/\bNOTE\b/g,`Note`).replace(/\bMAX\b/g,`Max`).replace(/\bPLAY\b/g,`Play`)),e===`Sony`&&(r=r.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,`α`).replace(/7CL?/i,`7c`),r=r.replace(/(\d[A-Za-z]?)M(\d+)$/,(e,n,r)=>`${n} ${intToRoman(r)}`)),e===`Kodak`&&(r=r.replace(/Kodak|digital|science|zoom|camera/gi,``).replace(/\s+/g,` `)),(e===`Olympus`||e===`OM System`)&&(r=mapOr(/^(.+?\d)mark(i.+)$/i.exec(r),e=>`${e[1]} Mark ${e[2]}`,()=>r)),e===`Panasonic`&&(r=r.replace(/^(?:DC|DMC)-(.{2,})$/i,`$1`)),e===`Motorola`&&(r=r.replace(/DROID ?/i,`Droid `)),e===`Canon`){r=r.replace(/\bDIGITAL\b/i,``).trim().replace(/EOS\s+REBEL/i,`EOS Rebel`);let e=r.match(/^EOS R(\d+)\s*m(\d+)$/i);e!=null&&(r=`EOS R${e[1]} Mark ${intToRoman(e[2])}`)}for(let e of i().IgnorableModelPatterns)r=replaceAll2(r,e).trim();return e.match(/^HP|Hewlett.Packard$/i)!=null&&r.match(/^hp\b/i)!=null&&(r=r.slice(2).trim()),r}function makeModel(e){let n=make(e.Make);return{Make:n,Model:model(n,e.Model)}}var import_node_path58=require("node:path");function sigFigsDeep(e,n=5){return e==null?e:typeof e==`number`?isInvalidNumber(e)?e:within(-180,180,e)?roundToDecimalPlaces(e,n):Number.isInteger(e)?e:sigFigs(e,n):typeof e==`bigint`||isDate(e)?e:Array.isArray(e)?e.map(e=>sigFigsDeep(e,n)):isObject(e)?mapNullEntries(e,(e,r)=>sigFigsDeep(r,n)):e}var InternalFieldRe=/^__.+?__$/;function pickInternalFields(e){let n={};for(let[r,a]of Object.entries(e))InternalFieldRe.test(r)&&(n[r]=a);return n}var import_exiftool_vendored13=require("exiftool-vendored"),import_luxon13=require("luxon"),import_sqlite3=require("@photostructure/sqlite"),import_node_path56=require("node:path"),import_node_buffer2=require("node:buffer");function isPlistUID(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.UID==`number`}var AppleEpochMs=9783072e5,Header=`bplist`,TrailerBytes=32,MaxObjectSize=1e8,MaxObjectCount=32768,MaxTotalEntries=1e6,MaxDecodedBytes=67108864,BinaryPlistError=class extends Error{};function fail(e){throw new BinaryPlistError(e)}function readInt(e,n,r,a){if((n<0||n+r>e.length)&&fail(`integer at ${n} (${r} bytes) runs past the end of the plist`),r<=6){let a=0;for(let o=0;o<r;o++)a=a*256+e[n+o];return a}let o=0n;for(let a=0;a<r;a++)o=o<<8n|BigInt(e[n+a]);if(a){let e=BigInt(r*8);o>=1n<<e-1n&&(o-=1n<<e)}return o>=BigInt(-(2**53-1))&&o<=BigInt(2**53-1)?Number(o):o}function readIndex(e,n,r){let a=readInt(e,n,r,!1);return typeof a!=`number`&&fail(`plist offset or reference ${a} is too large to use`),a}var Utf8=new TextDecoder(`utf-8`),Utf16BE=new TextDecoder(`utf-16be`);function parseBinaryPlist(e){let n=e;n.length<Header.length+TrailerBytes&&fail(`too short to be a binary plist (${n.length} bytes)`);let r=import_node_buffer2.Buffer.from(n.buffer,n.byteOffset,Header.length).toString(`latin1`);r!==Header&&fail(`expected "${Header}" at offset 0, found "${r}"`);let a=n.length-TrailerBytes,o=n[a+6],s=n[a+7],c=readIndex(n,a+8,8),l=readIndex(n,a+16,8),u=readIndex(n,a+24,8);(o<1||o>8)&&fail(`bad offset size ${o}`),(s<1||s>8)&&fail(`bad object reference size ${s}`),c>MaxObjectCount&&fail(`${c} objects exceeds the ${MaxObjectCount} limit`),u+c*o>a&&fail(`the offset table runs past the end of the plist`),l>=c&&fail(`top object ${l} is not among the ${c} objects`);let d=[];for(let e=0;e<c;e++){let r=readIndex(n,u+e*o,o);r>=a&&fail(`object #${e} starts past the end of the plist`),d[e]=r}let f=new DataView(n.buffer,n.byteOffset,n.byteLength),h=new Set,_=new Map,y=(e,r)=>((r<0||e+r>a)&&fail(`value at ${e} (${r} bytes) runs past the end of the plist`),r>=MaxObjectSize&&fail(`value at ${e} is implausibly large`),n.subarray(e,e+r)),x=0,C=0,w=e=>{C+=e,C>MaxDecodedBytes&&fail(`more than ${MaxDecodedBytes} decoded bytes`)},T=(e,n,r,o)=>{let c=r*o*s;e+n+c>a&&fail(`a collection of ${r} runs past the end of the plist`),x+=r,x>MaxTotalEntries&&fail(`more than ${MaxTotalEntries} collection entries`)},E=(e,r)=>{if(r!==15)return{count:r,dataOffset:1};let a=n[e+1];(a&240)!=16&&fail(`expected an integer count marker, found 0x${a.toString(16)}`);let o=2**(a&15);return{count:readIndex(n,e+2,o),dataOffset:2+o}},D=e=>{if(e>=d.length&&fail(`reference to missing object #${e}`),_.has(e))return _.get(e);h.has(e)&&fail(`object #${e} refers back to itself`),h.add(e);try{let n=O(e);return _.set(e,n),n}finally{h.delete(e)}},O=e=>{let r=d[e],a=n[r],o=(a&240)>>4,c=a&15;switch(o){case 0:switch(c){case 0:case 15:return null;case 8:return!1;case 9:return!0;default:return fail(`unhandled simple type 0x${c.toString(16)}`)}case 1:{let e=2**c;return readInt(n,r+1,e,c>=3)}case 2:{let e=2**c;return e===4?f.getFloat32(r+1,!1):e===8?f.getFloat64(r+1,!1):fail(`unhandled real width of ${e} bytes`)}case 3:return new Date(AppleEpochMs+1e3*f.getFloat64(r+1,!1));case 4:{let{count:e,dataOffset:n}=E(r,c);return w(e),Uint8Array.from(y(r+n,e))}case 5:{let{count:e,dataOffset:n}=E(r,c);return w(e),Utf8.decode(y(r+n,e))}case 6:{let{count:e,dataOffset:n}=E(r,c);return w(e*2),Utf16BE.decode(y(r+n,e*2))}case 8:return{UID:readIndex(n,r+1,c+1)};case 10:{let{count:e,dataOffset:a}=E(r,c);T(r,a,e,1);let o=[];for(let c=0;c<e;c++)o.push(D(readIndex(n,r+a+c*s,s)));return o}case 13:{let{count:e,dataOffset:a}=E(r,c);T(r,a,e,2);let o={};for(let c=0;c<e;c++){let l=readIndex(n,r+a+c*s,s),u=readIndex(n,r+a+(e+c)*s,s),d=D(l);typeof d!=`string`&&fail(`dictionary key #${l} is not a string`),o[d]=D(u)}return o}default:return fail(`unhandled type 0x${o.toString(16)}`)}};return D(l)}var logger77=defer(()=>mkLogger(`tags.ApplePhotosLegacyDb`)),MasterFields=[`modelId`,`uuid`,`fileName`,`imagePath`,`originalFileName`,`fileSize`,`width`,`height`,`duration`,`fileIsReference`],VersionFields=[`modelId`,`uuid`,`imageDate`,`imageTimeZoneOffsetSeconds`,`imageTimeZoneName`,`name`,`extendedDescription`,`latitude`,`longitude`,`isFavorite`,`isHidden`,`isInTrash`,`curationScore`],ApplePhotosLegacyDb=class{#e;#t=new Map;#n=new Map;#r;#i;#a;#o;#s;#c;#l;#u=[];constructor(e,n){this.#e=e,this.#f(`LiGlobals`,`keyPath`,`value`),this.#f(`RKMaster`,`modelId`,`uuid`,`fileName`,`imagePath`),this.#f(`RKVersion`,`modelId`,`uuid`,`masterUuid`),this.#r=`select ${this.#p(`RKMaster`,MasterFields)} from RKMaster where fileName = ? and imagePath = ? limit 2`;let r=[`masterUuid`,`rawMasterUuid`,`nonRawMasterUuid`].filter(e=>this.#d(`RKVersion`,e));this.#a=r.length,this.#i=`select ${this.#p(`RKVersion`,VersionFields)} from RKVersion where ${r.map(e=>`${e} = ?`).join(` or `)} limit 2`,this.#d(`RKKeyword`,`modelId`,`name`)&&this.#d(`RKKeywordForVersion`,`versionId`,`keywordId`)?this.#o=`select distinct k.name as value from RKKeywordForVersion j join RKKeyword k on k.modelId = j.keywordId where j.versionId = ?`:this.#u.push(`keywords`),this.#d(`RKAlbum`,`modelId`,`name`,`albumType`,`albumSubclass`,`isInTrash`,`folderUuid`)&&this.#d(`RKAlbumVersion`,`versionId`,`albumId`)?this.#s=`select distinct a.name as value from RKAlbumVersion j join RKAlbum a on a.modelId = j.albumId where j.versionId = ? and a.albumType = 1 and a.albumSubclass = 3 and coalesce(a.isInTrash, 0) = 0 and (a.folderUuid is null or a.folderUuid <> 'LibraryFolder')`:this.#u.push(`albums`),this.#d(`RKPerson`,`modelId`,`name`)&&this.#d(`RKFace`,`imageModelId`,`personId`,`isInTrash`)?this.#c=`select distinct p.name as value from RKFace f join RKPerson p on p.modelId = f.personId where f.imageModelId = ? and coalesce(f.isInTrash, 0) = 0`:this.#u.push(`personNames`),this.#d(`RKVersion`,`extendedDescription`)||this.#u.push(`description`),this.#d(`RKPlace`,`modelId`,`type`,`defaultName`,`area`,`countryCode`)&&this.#d(`RKPlaceForVersion`,`versionId`,`placeId`)&&(this.#l=`select p.type, p.defaultName, p.area, p.countryCode from RKPlaceForVersion j join RKPlace p on p.modelId = j.placeId where j.versionId = ? order by case when p.area > 0 then 0 else 1 end, p.area, p.modelId`);let a={dbPath:n,libraryVersion:toNotBlank(this.#e.prepare(`select value from LiGlobals where keyPath = 'libraryVersion' limit 1`).get()?.value),unavailableFields:this.#u};this.#u.length>0?logger77().warn(`Apple Photos legacy schema has unavailable metadata`,a):logger77().debug(`Read Apple Photos legacy schema`,a)}#d(e,...n){let r=this.#t.get(e);if(r==null){let n=this.#e.prepare(`select name from pragma_table_info(?)`).all(e);r=new Set(n.map(e=>e.name.toLowerCase())),this.#t.set(e,r)}return n.every(e=>r.has(e.toLowerCase()))}#f(e,...n){if(!this.#d(e,...n))throw Error(`Unsupported Apple Photos legacy identity schema: ${e}`)}#p(e,n){return n.filter(n=>this.#d(e,n)).map(e=>`${e} as ${e}`).join(`, `)}#m(e){let n=this.#n.get(e);return n??(n=this.#e.prepare(e),this.#n.set(e,n)),n}#h(e,n){return e==null?[]:compactBlanks(this.#m(e).all(n).map(e=>toNotBlank(e.value)))}#g(e){if(this.#l==null)return;let n=this.#m(this.#l).all(e),r=new Map,a,o;for(let e of n){let n=toNotBlank(e.defaultName);if(a??=toNotBlank(e.countryCode),n==null)continue;r.has(e.type)||r.set(e.type,n);let s=toFloat(e.area);e.type===45&&o==null&&s!=null&&s>0&&(o=n)}if(r.size!==0||a!=null)return{countryCode:a,country:r.get(1),state:r.get(2),county:r.get(4),city:r.get(16),subLocality:r.get(43),placeName:o,street:void 0,postalCode:void 0,addressString:void 0}}rowFor(e,n){let r=e.length===0?n:`${e}/${n}`,a=this.#m(this.#r).all(n,r);if(a.length!==1)return;let o=a[0];if(toInt(o.fileIsReference)===1)return;let s=toNotBlank(o.uuid);if(s==null)return;let c=this.#m(this.#i).all(...Array(this.#a).fill(s));if(c.length!==1){c.length>1&&logger77().warn(`Omitting ambiguous Apple Photos legacy versions`,{masterUuid:s});return}let l=c[0],u=toInt(l.modelId);if(u==null)return;let d=toFloat(l.latitude),f=toFloat(l.longitude),h=d!=null&&f!=null&&d>=-90&&d<=90&&f>=-180&&f<=180,_=toFloat(l.imageDate);return{...this.#u.length===0?{}:{unavailableFields:[...this.#u]},uuid:toNotBlank(l.uuid),originalFilename:toNotBlank(o.originalFileName),dateCreatedMs:_==null?void 0:Math.round((_+AppleEpochOffsetSec)*1e3),tzOffsetSec:toInt(l.imageTimeZoneOffsetSeconds),tzName:toNotBlank(l.imageTimeZoneName),exifTimestampString:void 0,dateCreatedSource:void 0,latitude:h?d:void 0,longitude:h?f:void 0,altitude:void 0,speed:void 0,course:void 0,title:toNotBlank(l.name),caption:void 0,description:toNotBlank(l.extendedDescription),keywords:this.#h(this.#o,u),albums:this.#h(this.#s,u),personNames:this.#h(this.#c,u),favorite:toInt(l.isFavorite)===1,hidden:toInt(l.isHidden)===1,trashed:(toInt(l.isInTrash)??0)!==0,originalWidth:toInt(o.width),originalHeight:toInt(o.height),originalFileSize:toInt(o.fileSize),durationSec:toFloat(o.duration),aestheticScore:toFloat(l.curationScore),revGeo:this.#g(u)}}close(){this.#n.clear(),this.#e.close()}},logger78=defer(()=>mkLogger(`tags.AppleRevGeo`));function uidIndex(e){return isPlistUID(e)?e.UID:void 0}var Archive=class e{#e;constructor(e){this.#e=e}static for(n){let r=parseBinaryPlist(n),a=r?.$objects;if(!Array.isArray(a))return;let o=new e(a),s=o.deref(r?.$top?.root);return s==null?void 0:{archive:o,root:s}}deref(e){let n=uidIndex(e);return n==null?e:n===0?void 0:this.#e[n]}get(e,n){if(typeof e==`object`&&e)return this.deref(e[n])}str(e,n){let r=this.get(e,n);return typeof r==`string`?toNotBlank(r):void 0}array(e){let n=this.get(e,`NS.objects`);return Array.isArray(n)?n.map(e=>this.deref(e)):[]}},PlaceType={country:1,state:2,county:3,city:4,subLocality:6,pointOfInterest:8};function smallestPlacesByType(e,n){let r=e.array(e.get(n,`sortedPlaceInfos`)),a=new Map;for(let n of r){let r=e.str(n,`name`),o=e.get(n,`area`),s=e.get(n,`placeType`);if(r==null||!isNumber(o)||o<=0||!isNumber(s))continue;let c=a.get(s);(c==null||o<c.area)&&a.set(s,{name:r,area:o})}return a}function parseAppleRevGeo(e){if(e==null||e.byteLength===0)return;let n;try{n=Archive.for(e)}catch(n){logger78().warn(`parseAppleRevGeo() could not read the archive`,{error:errorToS2(n),byteLength:e.byteLength});return}if(n==null)return;let{archive:r,root:a}=n,o=r.get(a,`postalAddress`),s=smallestPlacesByType(r,r.get(a,`mapItem`)),c={countryCode:r.str(o,`_ISOCountryCode`)??r.str(a,`countryCode`),country:r.str(o,`_country`)??s.get(PlaceType.country)?.name,state:r.str(o,`_state`)??s.get(PlaceType.state)?.name,county:r.str(o,`_subAdministrativeArea`)??s.get(PlaceType.county)?.name,city:r.str(o,`_city`)??s.get(PlaceType.city)?.name,subLocality:r.str(o,`_subLocality`)??s.get(PlaceType.subLocality)?.name,street:r.str(o,`_street`),postalCode:r.str(o,`_postalCode`),placeName:s.get(PlaceType.pointOfInterest)?.name,addressString:r.str(a,`addressString`)};return Object.values(c).some(e=>e!=null)?c:void 0}var logger79=defer(()=>mkLogger(`tags.ApplePhotosDb`)),AppleEpochOffsetSec=978307200,DateCreatedSourceFileModifyTime=3,NoLocationSentinel=-180,LocationDataBytes=64,DbBusyTimeoutMs=5e3;function measured(e){return e===0||e===-1?void 0:e}function parseAppleLocationData(e){if(e==null||e.byteLength<LocationDataBytes)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);return{altitude:measured(n.getFloat64(16,!0)),course:measured(n.getFloat64(40,!0)),speed:measured(n.getFloat64(48,!0))}}function tableNames(e){return e.prepare(`select name from sqlite_master where type = 'table'`).all().map(e=>e.name)}function columnNames(e,n){let r=e.prepare(`select name from pragma_table_info(?)`).all(n);return new Set(r.map(e=>e.name))}var JoinColumnRE=/^Z_\d+[A-Z]+$/;function isJoinColumn(e){return JoinColumnRE.test(e)}function readSchema(e){let n=tableNames(e),r=new Map,a=n=>{let a=r.get(n);return a??(a=columnNames(e,n),r.set(n,a)),a},o=(e,...n)=>n.every(n=>a(e).has(n)),s=[`ZASSET`,`ZGENERICASSET`].filter(e=>o(e,`Z_PK`,`ZDIRECTORY`,`ZFILENAME`));if(s.length!==1)throw Error(`Apple Photos schema must have one supported asset table`);if(!o(`ZADDITIONALASSETATTRIBUTES`,`Z_PK`,`ZASSET`))throw Error(`Apple Photos schema lacks required asset attributes`);let c=s[0],l=[];for(let e of n.filter(e=>/^Z_\d+KEYWORDS$/.test(e))){let n=[...a(e)].filter(isJoinColumn),r=n.filter(e=>e.endsWith(`KEYWORDS`)),o=n.filter(e=>e.endsWith(`ASSETATTRIBUTES`));r.length===1&&o.length===1&&l.push({table:e,keywordCol:r[0],attrCol:o[0]})}let u=l.length===1&&o(`ZKEYWORD`,`Z_PK`,`ZTITLE`)?l[0]:void 0,d=[];for(let e of n.filter(e=>/^Z_\d+ASSETS$/.test(e))){let n=[...a(e)].filter(isJoinColumn),r=n.filter(e=>e.endsWith(`ALBUMS`)),o=n.filter(e=>e.endsWith(`ASSETS`));r.length===1&&o.length===1&&d.push({table:e,albumCol:r[0],assetCol:o[0]})}let f=d.length===1&&o(`ZGENERICALBUM`,`Z_PK`,`ZTITLE`)?d[0]:void 0,h=[{assetCol:`ZASSETFORFACE`,personCol:`ZPERSONFORFACE`},{assetCol:`ZASSET`,personCol:`ZPERSON`}].filter(({assetCol:e,personCol:n})=>o(`ZDETECTEDFACE`,e,n)),_=h.length===1&&o(`ZPERSON`,`Z_PK`,`ZFULLNAME`)?h[0]:void 0,y=o(`ZADDITIONALASSETATTRIBUTES`,`ZASSETDESCRIPTION`)&&o(`ZASSETDESCRIPTION`,`Z_PK`,`ZLONGDESCRIPTION`),x=[];return u??x.push(`keywords`),f??x.push(`albums`),_??x.push(`personNames`),y||x.push(`description`),{assetTable:c,assetCols:a(c),attrCols:a(`ZADDITIONALASSETATTRIBUTES`),hasAssetDescription:y,detectedFace:_,albumCols:a(`ZGENERICALBUM`),join:{keywords:u,albums:f},unavailableFields:x}}function modelVersion(e){if(columnNames(e,`Z_METADATA`).has(`Z_PLIST`))try{let n=e.prepare(`select Z_PLIST from Z_METADATA order by Z_VERSION desc limit 1`).get();if(!(n?.Z_PLIST instanceof Uint8Array))return;let r=parseBinaryPlist(n.Z_PLIST);return isRecord(r)?toInt(r.PLModelVersion):void 0}catch(e){logger79().warn(`Cannot read Apple Photos model version`,{error:errorToS2(e)});return}}var ApplePhotosDb=class{#e;#t;#n=new Map;#r;constructor(e,n){this.#e=e,this.#t=readSchema(this.#e),this.#r=this.#s();let r={dbPath:n,modelVersion:modelVersion(this.#e),assetTable:this.#t.assetTable,unavailableFields:this.#t.unavailableFields};this.#t.unavailableFields.length>0?logger79().warn(`Apple Photos schema has unavailable metadata fields`,r):logger79().debug(`Read Apple Photos schema`,r)}#i(e){let n=this.#n.get(e);return n??(n=this.#e.prepare(e),this.#n.set(e,n)),n}#a(e,n=e){return this.#t.assetCols.has(e)?`a.${e} as ${n}`:void 0}#o(e,n=e){return this.#t.attrCols.has(e)?`aa.${e} as ${n}`:void 0}#s(){let e=this.#t.hasAssetDescription&&this.#t.attrCols.has(`ZASSETDESCRIPTION`),n=compactBlanks([`a.Z_PK as pk`,`aa.Z_PK as attrPk`,this.#a(`ZUUID`),this.#a(`ZDATECREATED`),this.#a(`ZLATITUDE`),this.#a(`ZLONGITUDE`),this.#a(`ZLOCATIONDATA`),this.#a(`ZFAVORITE`),this.#a(`ZHIDDEN`),this.#a(`ZTRASHEDSTATE`),this.#a(`ZDURATION`),this.#a(`ZOVERALLAESTHETICSCORE`),this.#o(`ZORIGINALFILENAME`),this.#o(`ZTIMEZONEOFFSET`),this.#o(`ZTIMEZONENAME`),this.#o(`ZEXIFTIMESTAMPSTRING`),this.#o(`ZDATECREATEDSOURCE`),this.#o(`ZTITLE`),this.#o(`ZACCESSIBILITYDESCRIPTION`),this.#o(`ZORIGINALWIDTH`),this.#o(`ZORIGINALHEIGHT`),this.#o(`ZORIGINALFILESIZE`),this.#o(`ZREVERSELOCATIONDATA`),e?`ad.ZLONGDESCRIPTION as ZLONGDESCRIPTION`:void 0]),r=compactBlanks([`left join ZADDITIONALASSETATTRIBUTES aa on aa.ZASSET = a.Z_PK`,e?`left join ZASSETDESCRIPTION ad on ad.Z_PK = aa.ZASSETDESCRIPTION`:void 0]);return`select ${n.join(`, `)} from ${this.#t.assetTable} a ${r.join(` `)} where a.ZDIRECTORY = ? and a.ZFILENAME = ? limit 1`}#c(e,...n){return compactBlanks(this.#i(e).all(...n).map(e=>toNotBlank(e.v)))}#l(e){let n=this.#t.join.keywords;return n==null||e==null?[]:this.#c(`select k.ZTITLE as v from ${n.table} j join ZKEYWORD k on k.Z_PK = j.${n.keywordCol} where j.${n.attrCol} = ?`,e)}#u(e){let n=this.#t.join.albums;if(n==null)return[];let r=[`g.ZTITLE is not null`];return this.#t.albumCols.has(`ZKIND`)&&r.push(`g.ZKIND in (2, 1505)`),this.#t.albumCols.has(`ZTRASHEDSTATE`)&&r.push(`coalesce(g.ZTRASHEDSTATE, 0) = 0`),this.#c(`select g.ZTITLE as v from "${n.table}" j join ZGENERICALBUM g on g.Z_PK = j.${n.albumCol} where j.${n.assetCol} = ? and ${r.join(` and `)}`,e)}#d(e){let n=this.#t.detectedFace;return n==null?[]:this.#c(`select distinct p.ZFULLNAME as v from ZDETECTEDFACE f join ZPERSON p on p.Z_PK = f.${n.personCol} where f.${n.assetCol} = ? and p.ZFULLNAME is not null and p.ZFULLNAME <> ''`,e)}rowFor(e,n){let r=this.#i(this.#r).get(e,n);if(r==null)return;let a=toInt(r.pk);if(a==null)return;let o=toFloat(r.ZLATITUDE),s=toFloat(r.ZLONGITUDE),c=o!=null&&s!=null&&o>NoLocationSentinel&&s>NoLocationSentinel,l=c?parseAppleLocationData(r.ZLOCATIONDATA):void 0,u=toFloat(r.ZDATECREATED);return{...this.#t.unavailableFields.length===0?{}:{unavailableFields:[...this.#t.unavailableFields]},uuid:toNotBlank(r.ZUUID),originalFilename:toNotBlank(r.ZORIGINALFILENAME),dateCreatedMs:u==null?void 0:Math.round((u+AppleEpochOffsetSec)*1e3),tzOffsetSec:toInt(r.ZTIMEZONEOFFSET),tzName:toNotBlank(r.ZTIMEZONENAME),exifTimestampString:toNotBlank(r.ZEXIFTIMESTAMPSTRING),dateCreatedSource:toInt(r.ZDATECREATEDSOURCE),latitude:c?o:void 0,longitude:c?s:void 0,altitude:l?.altitude,speed:l?.speed,course:l?.course,title:toNotBlank(r.ZTITLE),caption:toNotBlank(r.ZACCESSIBILITYDESCRIPTION),description:toNotBlank(r.ZLONGDESCRIPTION),keywords:this.#l(toInt(r.attrPk)),albums:this.#u(a),personNames:this.#d(a),favorite:toInt(r.ZFAVORITE)===1,hidden:toInt(r.ZHIDDEN)===1,trashed:(toInt(r.ZTRASHEDSTATE)??0)!==0,originalWidth:toInt(r.ZORIGINALWIDTH),originalHeight:toInt(r.ZORIGINALHEIGHT),originalFileSize:toInt(r.ZORIGINALFILESIZE),durationSec:toFloat(r.ZDURATION),aestheticScore:toFloat(r.ZOVERALLAESTHETICSCORE),revGeo:parseAppleRevGeo(r.ZREVERSELOCATIONDATA)}}close(){this.#n.clear(),this.#e.close()}},dbs=new Map,retryAfter=new Map;function postponeBusyLibrary(e,n){let r=isRecord(n)?toInt(n.errcode):void 0;return!isSqliteBusyError(n)&&!(r!=null&&[5,6].includes(r&255))?!1:(retryAfter.set(e,performance.now()+minuteMs),!0)}function openApplePhotosDb(e){let n=new import_sqlite3.DatabaseSync(e,{readOnly:!0,timeout:DbBusyTimeoutMs});try{return tableNames(n).includes(`LiGlobals`)?new ApplePhotosLegacyDb(n,e):new ApplePhotosDb(n,e)}catch(e){throw n.close(),e}}function dbFor(e){let n=retryAfter.get(e.dbPath);if(n!=null){if(performance.now()<n)return;retryAfter.delete(e.dbPath)}if(dbs.has(e.dbPath))return dbs.get(e.dbPath);let r;try{r=openApplePhotosDb(e.dbPath)}catch(n){if(logger79().warn(`Cannot read Apple Photos database`,{dbPath:e.dbPath,error:errorToS2(n)}),postponeBusyLibrary(e.dbPath,n))return;r=void 0}return dbs.set(e.dbPath,r),r}function assetKeyFor(e,n){let r=(0,import_node_path56.relative)(e.mediaRoot,n);if(blank(r)||r.startsWith(`..`))return;let a=r.split(import_node_path56.sep),o=a.pop();if(!blank(o))return{zDirectory:a.join(`/`),zFilename:o}}function applePhotosRowFor(e,n){let r=assetKeyFor(e,n);if(r==null)return;let a=dbFor(e);if(a!=null)try{return a.rowFor(r.zDirectory,r.zFilename)}catch(r){postponeBusyLibrary(e.dbPath,r),logger79().warn(`applePhotosRowFor() failed`,{nativePath:n,dbPath:e.dbPath,error:errorToS2(r)});return}}var import_node_path57=require("node:path"),logger80=defer(()=>mkLogger(`tags.ApplePhotosLibrary`)),MaxAncestors=10,MacOsBundleSuffixes=[`.photoslibrary`,`.photolibrary`],NotAnApplePhotosLibrary=Symbol(`NotAnApplePhotosLibrary`),cache4=defer(()=>new Cache({name:`ApplePhotosLibrary`,maxSize:1024}));async function libraryAt(e){let n=(0,import_node_path57.basename)(e).toLowerCase();if(MacOsBundleSuffixes.some(e=>n.endsWith(e))){let n=(0,import_node_path57.join)(e,`database`,`Photos.sqlite`);if(await isNonEmptyFile(n)){let r=(0,import_node_path57.join)(e,`originals`);if(await isDirectory(r))return{root:e,dbPath:n,mediaRoot:r,kind:`macos`}}let r=(0,import_node_path57.join)(e,`database`,`photos.db`),a=(0,import_node_path57.join)(e,`Masters`);return await isNonEmptyFile(r)&&await isDirectory(a)?{root:e,dbPath:r,mediaRoot:a,kind:`macos`}:void 0}let r=(0,import_node_path57.join)(e,`PhotoData`,`Photos.sqlite`);if(await isNonEmptyFile(r))return{root:e,dbPath:r,mediaRoot:e,kind:`ios`}}async function applePhotosLibraryFor(e){if(!blank(e))return applePhotosLibraryForDir((0,import_node_path57.dirname)(e))}async function applePhotosLibraryForDir(e){if(blank(e))return;let n=[],r=e;for(let a=0;a<MaxAncestors;a++){let a=cache4().get(r);if(a!=null){for(let e of n)cache4().set(e,a);return a===NotAnApplePhotosLibrary?void 0:a}n.push(r);let o=await libraryAt(r);if(o!=null){for(let e of n)cache4().set(e,o);return logger80().debug(`applePhotosLibraryFor()`,{dir:e,found:o}),o}let s=(0,import_node_path57.dirname)(r);if(s===r)break;r=s}for(let e of n)cache4().set(e,NotAnApplePhotosLibrary)}var logger81=defer(()=>mkLogger(`tags.ApplePhotosTags`)),ZoneQuantumMin=15,MaxZoneOffsetMin=840,MaxResidualMin=1,ExifTimestampRE=/^(\d{4})[:-](\d{2})[:-](\d{2})[ T](\d{2}):(\d{2}):(\d{2})/;function zoneOffsetMinFromExifTimestamp(e,n){if(blank(e)||!isNumber(n))return;let r=ExifTimestampRE.exec(e);if(r==null)return;let[,a,o,s,c,l,u]=r,d=Date.UTC(+a,o-1,+s,+c,+l,+u);if(!isFinite(d))return;let f=(d-n)/minuteMs,h=Math.round(f/ZoneQuantumMin)*ZoneQuantumMin;if(!(Math.abs(f-h)>MaxResidualMin))return Math.abs(h)>MaxZoneOffsetMin?void 0:h}function hasUsableCaptureTime(e){return isNumber(e.dateCreatedMs)&&!(e.dateCreatedSource===DateCreatedSourceFileModifyTime&&blank(e.exifTimestampString))}function zoneForRow(e){let n=(0,import_exiftool_vendored13.normalizeZone)(e.tzName);if(n!=null)return n;if(isNumber(e.tzOffsetSec)){let n=(0,import_exiftool_vendored13.normalizeZone)(Math.round(e.tzOffsetSec/60));if(n!=null)return n}return(0,import_exiftool_vendored13.normalizeZone)(zoneOffsetMinFromExifTimestamp(e.exifTimestampString,e.dateCreatedMs))}function applePhotosRowToTags(e){let n=zoneForRow(e)??`UTC`,r=hasUsableCaptureTime(e)?import_exiftool_vendored13.ExifDateTime.fromDateTime(import_luxon13.DateTime.fromMillis(e.dateCreatedMs,{zone:n}),{rawValue:e.exifTimestampString}):void 0,a=validLat(e.latitude)&&validLon(e.longitude);return compactValues({applePhotosDateCreated:r?.isValid===!0?r:void 0,PreservedFileName:e.originalFilename,OriginalFileName:e.originalFilename,GPSLatitude:a?e.latitude:void 0,GPSLongitude:a?e.longitude:void 0,GPSAltitude:a?e.altitude:void 0,Title:e.title,Description:e.description??e.caption,applePhotosCountryCode:e.revGeo?.countryCode,applePhotosCountry:e.revGeo?.country,applePhotosState:e.revGeo?.state,applePhotosCounty:e.revGeo?.county,applePhotosCity:e.revGeo?.city,applePhotosSubLocality:e.revGeo?.subLocality,applePhotosPOI:e.revGeo?.placeName,Keywords:isNotEmpty(e.keywords)?e.keywords:void 0,applePhotosAlbums:isNotEmpty(e.albums)?e.albums:void 0,PersonInImage:isNotEmpty(e.personNames)?e.personNames:void 0,applePhotos:compactValues({unavailableFields:isNotEmpty(e.unavailableFields)?e.unavailableFields:void 0,uuid:e.uuid,favorite:e.favorite,hidden:e.hidden,trashed:e.trashed,speed:e.speed,course:e.course,originalWidth:e.originalWidth,originalHeight:e.originalHeight,originalFileSize:e.originalFileSize,aestheticScore:e.aestheticScore,address:e.revGeo?.addressString})})}async function readApplePhotosTags(e){if(!ParsingSettings.applePhotosMetadata.valueOrDefault||blank(e))return;let n=await applePhotosLibraryFor(e);if(n==null)return;let r=applePhotosRowFor(n,e);if(r!=null)return logger81().tap({msg:`readApplePhotosTags()`,level:`debug`,result:applePhotosRowToTags(r),meta:{nativePath:e,library:n.root,kind:n.kind}})}var import_exiftool_vendored15=require("exiftool-vendored"),import_exiftool_vendored14=require("exiftool-vendored"),rawMergedTagsCache=lazy2(()=>new FileCache({name:`exif.rawMerged`,maxSize:512,...metadataCacheOptions(),timeoutMs:0,keepPending:!0})),sizeInfoCache=lazy2(()=>new FileCache({name:`tags.sizeInfo`,...metadataCacheOptions(),maxSize:256,timeoutMs:minuteMs})),tagsCache=lazy2(()=>new FileCache({name:`exif.parsed`,maxSize:512,...metadataCacheOptions(),timeoutMs:0,keepPending:!0}));function deleteAllByPrefix(e){tagsCache.prior()?.deleteByPrefix(e),rawMergedTagsCache.prior()?.deleteByPrefix(e),rawTagsCache.prior()?.deleteByPrefix(e),mimetypeCache.prior()?.deleteByPrefix(e),sizeInfoCache.prior()?.deleteByPrefix(e)}function clearTagsCacheForDir(e){deleteAllByPrefix(e);let n=macSymlinkAltPath(e);n!=null&&deleteAllByPrefix(n)}var logger82=defer(()=>mkLogger(`tags.WriteTags`));async function overwriteTags_(e,n){try{await time({name:`exif.overwriteTags`,meta:{src:e},p:async()=>{await exiftool().write(e.nativePath,n,{writeArgs:writeTagArgs()}),e.clearThisAndParent(),clearTagsCacheForDir(e.dir)}})}catch(r){logger82().throw(`failed to overwrite tags to `+e,{error:r,tags:n})}}async function deleteAllTags_(e,n){await time({name:`exif.deleteAllTags`,meta:{src:e},p:async()=>{let r=[`-all=`];e.$eql(n)?r.push(`-overwrite_original`):r.push(`-o`,n.nativePath),await exiftool().write(e.nativePath,{},{writeArgs:r}),n.clear(),clearTagsCacheForDir(n.dir)}})}function writeTagArgs(){let e=[];return Settings2.overwriteOriginal.valueOrDefault&&e.push(`-overwrite_original`),e}var Actions=strEnum(`infer`,`set`,`add`,`delete`);function mkHistoryRecords(e,n){return entries(n??{}).map(([n,r])=>mkHistoryRecord({action:e,key:n,value:r}))}function mkHistoryRecord({action:e,key:n,value:r,ts:a}){return{Action:e,Changed:toS(n).replace(/[#+]$/,``),Parameters:stringify(r),When:import_exiftool_vendored15.ExifDateTime.fromMillis(a??Date.now()),SoftwareAgent:AppNameVersion()}}var logger83=lazy2(()=>mkLogger(`tags.History`));function tagsContainHistory(e,n){if(e==null||e.History==null||isString(e.History))return!1;let r=e.History;return Array.isArray(r)?r.some(n):n(r)}function inferredHistoryOldestFirst(e){return sortBy((isString(e)?[]:toA(e)).filter(e=>startsWithIgnoreCase(e.SoftwareAgent,`PhotoStructure`)&&e.Action===Actions.infer),e=>datedToMillis(mapNotBlank(e.When,e=>import_exiftool_vendored15.ExifDateTime.from(e)))??0)}function getInferredHistoricValues(e,n,r){let a=inferredHistoryOldestFirst(e),o={},s=[],c=[];for(let e of a){let a=e.Changed;if(blank(a))continue;let l=parseResourceEventValue(e,r),u=l.value;if(u==null){l.status===`invalidJson`?pushNotSame(s,a):l.status===`unrestorable`&&pushNotSame(c,a);continue}let d=l.nativePath??u.nativePath;!blank(d)&&!eqlNameWithoutExt(d,n)?logger83().debug(`getInferredHistoricValues(): skipping mismatching filename (without file extension)`,{ea:e,src:n}):o[a]=u}return isNotEmpty(s)&&logger83().warn(`getInferredHistoricValues(): ignoring inferred history records whose Parameters are not JSON`,{src:n,fields:s}),isNotEmpty(c)&&logger83().warn(`getInferredHistoricValues(): ignoring inferred history records whose valid JSON Parameters could not be restored`,{src:n,fields:c}),o}function legacyCapturedAt(e,n){if(!isObject(e)||e._ctor!==`CapturedAt`||!isString(e.nativePath)||!isString(e.date)||!CapturedAtSrcTypes.has(e.src)||blank(n))return;let r=parseDated({input:e.date});if(r==null)return;let a=CapturedAt.fromFields({mimetype:n,date:r,capturedAtRaw:e.date,capturedAtSrc:e.src,capturedAtPrecisionMs:toFinite(e.precisionMs)});if(a!=null)return{nativePath:e.nativePath.split(/[\\/]/).filter(e=>e.length>0).at(-1)??e.nativePath,value:a}}function parseResourceEventValue(e,n){let r=e?.Parameters;if(r==null||blank(r))return{status:`empty`};if(isNumber(r))return{status:`parsed`,value:r};if(!isString(r))return{status:`unrestorable`};let a;try{a=JSON.parse(r)}catch{return{status:`invalidJson`}}if(a==null)return{status:`empty`};let o=isObject(a)&&isString(a.nativePath)?a.nativePath:void 0,s=legacyCapturedAt(a,n);if(s!=null)return{nativePath:s.nativePath,status:`parsed`,value:s.value};try{let e=fromJsonObject(a);return e==null?{nativePath:o,status:`unrestorable`}:{nativePath:o,status:`parsed`,value:e}}catch{return{nativePath:o,status:`unrestorable`}}}function inferredToTags(e){if(e==null)return;let n={};for(let[r,a]of entries(e))isFirstCharAZ(r)&&(n[r]=a);return`duration`in e&&(n.Duration=toGt0f(e.duration)),`rating`in e&&(n.Rating=e.rating),assignFields(n,e.capturedAt?.asExifTag()),n}async function ensureInferredHistoryRecords(e,n,r){let a=mkHistoryRecords(Actions.infer,r),o=(Settings2.writeInferredTagsToLibraryCopies.valueOrDefault?inferredToTags(r):void 0)??{};return Settings2.writeSourceTagToLibraryCopies.valueOrDefault&&(o.Source=e.nativePath),logger83().debug(`ensureInferredHistoryRecords()`,{sidecar:n,historyRecords:a,additionalTags:o}),ensureHistoryRecords(n,a,o)}function tagValueAsExif(e,n){if(n===`DateTimeOriginal`&&(isString(e)||isNumber(e))){let n=import_exiftool_vendored15.ExifDate.from(e);if(n?.isPartial())return n.toExifString()}let r=isString(e)?import_exiftool_vendored15.ExifDateTime.fromEXIF(e):e;return isDated(r)?getDay(r)==null?datedToYMD(r,`:`):datedToEXIF(r):void 0}function eqlTagValue(e,n,r){if(eql(e,n))return!0;if(isNumber(e)&&isNumber(n)){if(r===`GPSLatitude`||r===`GPSLongitude`)return closeTo(e,n,5.00001e-7);if(r===`GPSAltitude`)return closeTo(e,n,1e-6)}let a=tagValueAsExif(e,r);return a!=null&&a===tagValueAsExif(n,r)}async function ensureHistoryRecords(e,n,r){if(e==null||blank(e)){logger83().warn(`ensureHistoryRecords(): no-op: empty path`,{sidecar:e});return}let a=await readRawTags(toNativePath_(e)),o=new Map(inferredHistoryOldestFirst(a?.History).map(e=>[e.Changed,e])),s=toA(n).filter(e=>{if(e.Action!==Actions.infer||!startsWithIgnoreCase(e.SoftwareAgent,`PhotoStructure`))return!0;let n=o.get(e.Changed);return n!=null&&eql(pick(e,`Changed`,`Parameters`),pick(n,`Changed`,`Parameters`))?!1:(o.set(e.Changed,e),!0)}),c={};for(let[e,n]of entries(r??{})){let r=e===`DateTimeOriginal`||e===`SubSecDateTimeOriginal`,o=r?a?.SubSecDateTimeOriginal??a?.DateTimeOriginal:a?.[e],s=r&&o instanceof import_exiftool_vendored15.ExifDateTime?o.rawValue??o:o;n==null&&s==null||eqlTagValue(s,n,e)||(c[e]=n)}if(isNotEmpty(s)&&(c[`History+`]=s),isEmptyObj(c)){logger83().debug(`ensureHistoryRecords(): no-op: nothing to write`,{sidecar:e,historyRecords:n,newHistoryRecords:s,additionalTags:r,tagsToWrite:c});return}logger83().debug(`ensureHistoryRecords(): write`,{sidecar:e,tagsToWrite:c,historyRecords:n,additionalTags:r});let l=PosixFile.for(e);return await overwriteTags_(l,c),l.clearThisAndParent(),s}var import_exiftool_vendored16=require("exiftool-vendored"),TimezoneOffsetEndRE=RegExp(import_exiftool_vendored16.TimezoneOffsetRE.source+`$`);function extractTrailingZone(e){if(e==null)return;let n=TimezoneOffsetEndRE.exec(e),r=(0,import_exiftool_vendored16.parseTimezoneOffsetMatch)(n);if(r!=null)return(0,import_exiftool_vendored16.normalizeZone)(r.offsetMinutes)}function parseTimestamp(e,n){if(e==null)return;let r=toInt(e?.timestamp);if(isNumber(r)){let a=extractTrailingZone(e?.formatted)??(0,import_exiftool_vendored16.normalizeZone)(n),o=import_exiftool_vendored16.ExifDateTime.fromMillis(r*1e3,{rawValue:e.formatted,zone:a??import_exiftool_vendored16.UnsetZone});if(!0===o?.isValid)return o}return parseDated({input:e.formatted,defaultZone:n})}async function readJsonSidecar(e,n){let r=await e.readText(`info`);if(r==null)return;let a;try{a=JSON.parse(r)}catch{return}if(a!=null)return compactValues({Title:toNotBlank(a.title),Description:toNotBlank(a.description),GPSLatitude:first([a.geoData?.latitude,a.geoDataExif?.latitude],e=>validLat(e)?e:void 0),GPSLongitude:first([a.geoData?.longitude,a.geoDataExif?.longitude],e=>validLon(e)?e:void 0),GPSAltitude:first([a.geoData?.altitude,a.geoDataExif?.altitude],e=>isNumber(e)?e:void 0),favorited:map(a.favorited,isTrue),peopleNames:mapNotEmpty([...toA(a.people),...toA(a.person)],e=>compactBlanks(e.map(e=>e.name))),creationTime:parseTimestamp(a.creationTime,n),modificationTime:parseTimestamp(a.modificationTime,n),photoTakenTime:parseTimestamp(a.photoTakenTime,n),imageViews:mapInt(a.imageViews,e=>e),googlePhotosOrigin:!0})}var logger84=defer(()=>mkLogger(`tags.ReadRawMergedTags`));async function mergeApplePhotosTags(e,n){let r=await readApplePhotosTags(n);if(r==null)return;let{Keywords:a,applePhotosAlbums:o,PersonInImage:s,...c}=r,l=e;for(let[e,n]of[[`Keywords`,a],[`applePhotosAlbums`,o],[`PersonInImage`,s]]){let r=uniq([...toA(l[e]),...toA(n)]);isNotEmpty(r)&&(l[e]=r)}assignNullishFields(e,c)}function mergeInvalidUtf8Bytes(e,n,r){let a={...e.invalidUtf8Bytes};for(let e of Object.keys(n)){let n=r?.[e];n==null?delete a[e]:a[e]=n}e.invalidUtf8Bytes=Object.keys(a).length>0?a:void 0}function readRawMergedTags(e){return excludeWaitFromEnclosingTimer(()=>_readRawMergedTags(toNativePath_(e)))}var possibleSidecarsCache=lazy2(()=>new FileCache({name:`tags.possibleSidecars`,maxSize:512,...metadataCacheOptions()}));async function possibleSidecars(e,n,r){if(n===MissingFileStamp)return[];let a=async()=>toA(await readdir2(e)).filter(n=>mayBeSidecar(DirectoryEntry.fromSimpleDirent(e,n)));return(r?await a():await possibleSidecarsCache().getOrSet(e,a,n)).map(n=>DirectoryEntry.fromSimpleDirent(e,n))}var sidecarBasenamesCache=lazy2(()=>new FileCache({name:`tags.sidecarBasenames`,...metadataCacheOptions()}));async function mergedTagsStamp(e){let{dir:n,base:r}=parseNativePath(e),a=await fileStats(n),o=Date.now(),s=a==null?MissingFileStamp:JSON.stringify(a),c=a!=null&&isRacyMtime(a.mtimeMs,o),l=[s,Settings2.matchSidecarsCaseInsensitively.valueOrDefault,Settings2.matchSidecarsFuzzily.valueOrDefault,...compactBlanks(Settings2.directorySidecars.valueOrDefault)].join(`\0`),u=async()=>{let e=DirectoryEntry.fromSimpleDirent(n,{basename:r,isFile:!0,isDirectory:!1}),{own:a,shared:o}=new ListedSidecars((await possibleSidecars(n,s,c)).filter(e=>e.base!==r)).candidatesOf(e);return uniq([...a,...o]).map(e=>e.base)},d=[r,...c?await u():await sidecarBasenamesCache().getOrSet(e,u,l)];return(await Promise.all(d.map(async e=>`${e}=${await fileStamp((0,import_node_path58.join)(n,e))}`))).join(`\0`)}var _readRawMergedTags=shim({cache:rawMergedTagsCache,stamp:mergedTagsStamp,impl:__readRawMergedTags,toKey:e=>e});async function __readRawMergedTags(e){let n=PosixFile.for(e);if(!await n.isNonEmptyFile(128)){rawTagsCache().delete(n.nativePath),logger84().debug(`readRawTags(`+n+`): invalid file, returning null.`);return}let r=await readRawTags(n.nativePath);if(n.isSidecar())return r;if(r==null){logger84().debug(`readRawMergedTags(): no file tags, returning null.`,{pf:n});return}let a=mapNotBlank(r.MIMEType,normalizeMimetype);if(blank(a)){logger84().debug(`readRawMergedTags(): no MIMEType, returning null.`,{pf:n});return}logger84().trace(`readRawTags()`,{pf:n,pickedFileTags:pick(r,`zone`,`zoneSource`,...Settings2.capturedAtTagsPrimary.values,...Settings2.capturedAtTagsSecondary.values,...Settings2.capturedAtTagsTertiary.values,...Settings2.capturedAtTagsFallback.values)});let o=[[n,r]];for(let e of await n.existingDirectorySidecars())o.push([e,readRawTags(e.nativePath)]);for(let e of await n.jsonSidecars())o.push([e,readJsonSidecar(e,r.zone)]);for(let e of await n.existingExifSidecars())o.push([e,readRawTags(e.nativePath)]);let s={original:{},MIMEType:a},c=await sortByAsync({iter:o,f:async([e,n])=>{let r=await n;return max3([datedToMillis(r?.MetadataDate),datedToMillis(r?.FileModifyDate),await e.mtimeMs()])}}),l=[];for(let[e,r]of c){if(r==null)continue;let a=await r;if(a==null)continue;let{invalidUtf8Bytes:o,...c}=e===n?a:omit(a,...IgnoredSidecarFields);isNotEmpty(values(c))?(e!==n&&(s.sidecars??=[],s.sidecars.push(e.base)),l.push(...toA(a.History)),assignNullishFields(s.original,pick(s,...keys(c))),assignFields(s,c),mergeInvalidUtf8Bytes(s,c,o),logger84().debug(`_readRawTags() sidecar had values`,{sidecar:e.base})):logger84().debug(`_readRawTags() sidecar was empty`,{sidecar:e.base})}s.inferred=getInferredHistoricValues(l,e,a),assignNullishFields(s,s.inferred),await mergeApplePhotosTags(s,e);for(let[e,n]of entries(s.original??{}))s[e]===n&&delete s.original?.[e];return isTest()&&addInstanceIds(s),logger84().debug(`readRawTags() final`,{pf:n,inferred:s.inferred,internalFields:pickInternalFields(s),pickedResult:pick(s,`MIMEType`,`ImageWidth`,`ImageHeight`,`Orientation`,`Rotation`,`zone`,`zoneSource`,...Settings2.capturedAtTagsPrimary.values,...Settings2.capturedAtTagsSecondary.values,...Settings2.capturedAtTagsTertiary.values,...Settings2.capturedAtTagsFallback.values)}),s}var logger85=lazy2(()=>mkLogger(`tags.TagInference`));async function readSiblingTags({file:e,sibling:n,operation:r,read:a}){try{return await a(n)}catch(a){if(isAbortError(a))throw a;logger85().warn(`Skipping unreadable sibling during tag inference`,{file:e.nativePath,sibling:n.nativePath,operation:r,error:a});return}}async function canInferForDir(e){return isSiblingInferenceEnabled()?!0!==isInInternalDir(e)||(logger85().debug(`canInferForDir(`+e+`): disabled (PhotoStructure directory)`),!1):(logger85().debug(`canInferForDir(`+e+`): disabled: `+Settings2.inferenceSiblingRadius.toEnvLine()),!1)}async function inferMakeAndModel({pf:e,tags:n,siblings:r}){let a=extractMakeAndModel(n);if(a.Make!=null&&a.Model!=null)return a;if(!await canInferForDir(e.parent()))return logger85().debug(`inferMakeAndModel(`+e+`): cannot infer for this directory`,e.parent()),a;let o=zipSibling(r??await nearestSiblings(e));logger85().debug(`inferMakeAndModel(`+e+`): looking at nearby siblings`,o.map(e=>e.base));for(let n of o){let r=extractMakeAndModel(await readSiblingTags({file:e,sibling:n,operation:`make/model`,read:readRawTags}));if(definedAndNotEql(r.Make,a.Make))logger85().debug(`inferMakeAndModel(`+e+`): skipping sibling (mismatching Make)`,{mm:a,fromSibling:r});else if(definedAndNotEql(r.Model,a.Model))logger85().debug(`inferMakeAndModel(`+e+`): skipping sibling (mismatching Model)`,{mm:a,fromSibling:r});else if(r.Make!=null&&r.Model!=null)return logger85().tap({msg:`inferMakeAndModel(`+e+`)`,level:LogLevels.info,result:r,meta:{sibling:n.base}})}return a}async function inferCapturedAtFromSiblings(e,n){if(!await canInferForDir(e.parent()))return;let r=await beforeAfterCapturedAt(e,n);if(r!=null&&closeTo2(r.before.date,r.after.date,2*dayMs))return map(DateInterval.for(toExifDateTime(r.before.date,getZoneName(r.before.date)),toExifDateTime(r.after.date,getZoneName(r.after.date)),r.index,r.slots),e=>({date:e,src:`before:${r.before.capturedAtSrc},after:${r.after.capturedAtSrc}`}))}async function firstWithCapturedAt(e,n){n=toA(n);for(let r=0;r<n.length;r++){let a=n[r],o=await readSiblingTags({file:e,sibling:a,operation:`captured-at`,read:readRawMergedTags}),s=CapturedAt.fromFields(capturedAtFromTags(o));if(s!=null)return{...s,index:r}}}async function majorityZoneName(e,n){let r=[];for(let a of n){let n=await readSiblingTags({file:e,sibling:a,operation:`timezone`,read:readRawMergedTags});n!=null&¬Blank(n.zone)&&n.zoneSource!==import_exiftool_vendored17.defaultVideosToUTC&&r.push({zoneName:n.zone,path:a.nativePath,base:a.base,src:n.zoneSource??`tags.zone`})}if(r.length===0){logger85().debug(`majorityZoneName(): no zone name found`,{arr:n});return}let a=new Map;for(let e of r)a.set(e.zoneName,(a.get(e.zoneName)??0)+1);let o=``,s=0;for(let[e,n]of a)n>s&&(o=e,s=n);if(s/r.length<2/3){logger85().debug(`majorityZoneName(): siblings disagree on timezone`,{counts:Object.fromEntries(a),totalWithZone:r.length});return}let c=r.find(e=>e.zoneName===o);return logger85().tap({msg:`majorityZoneName()`,result:c,meta:{counts:Object.fromEntries(a),totalWithZone:r.length}})}var bacaCache=lazy2(()=>new FileCache({name:`tags.beforeAfterCapturedAt`}));function beforeAfterCapturedAt(e,n){return bacaCache().getOrSet(e.nativePath,async()=>{let r=n??await nearestSiblings(e),a=await firstWithCapturedAt(e,r?.younger),o=await firstWithCapturedAt(e,r?.older);return r==null||a==null||o==null?null:{before:a,after:o,index:a.index,slots:a.index+o.index+1}})}function zipSibling(e){return e==null?[]:compact(flatZip(toA(e.younger),toA(e.older)))}async function nearestSiblings(e,n=Settings2.inferenceSiblingRadius.valueOrDefault){if(!await canInferForDir(e.parent()))return;let r=e.parent().nativePath,a;try{a=await time({name:`tag.nearestSiblings`,meta:{file:e},p:async()=>(await readdirSortedMaybe_(r,{expectBasename:e.base}))?.filter(e=>e.isFile&&!e.basename.startsWith(`.`)&&isMediaExt(e.basename))})}catch(n){if(isAbortError(n))throw n;logger85().warn(`nearestSiblings(): can't readdir parent`,{file:e.nativePath,dir:r,error:n});return}if(a==null){logger85().info(`nearestSiblings(): no sortable siblings (empty dir or over sort threshold)`,{file:e.nativePath,dir:r});return}let o=a.findIndex(n=>eqlDirentBasename(n.basename,e.base));if(o<0){logger85().warn(`nearestSiblings(): can't find self in siblings: `+e,{dirents:a.map(e=>e.basename)});return}let s=Settings2.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[c,l]=[a.slice(o-n*2,o),a.slice(o+1,o+1+n*2)],u=[],d=[];for(;isNotEmpty(c)&&u.length<n;){let n=c.pop(),r=e.sibling(n.basename);diceCoeff2(e.name,r.name)>=s&&u.push(r)}for(;isNotEmpty(l)&&d.length<n;){let n=l.shift(),r=e.sibling(n.basename);diceCoeff2(e.name,r.name)>=s&&d.push(r)}return logger85().tap({msg:`nearestSiblings()`,level:`trace`,result:{younger:u,older:d},meta:{f:e}})}async function nearestSiblingTzOffset(e,n){if(!await canInferForDir(e.parent()))return;let r=zipSibling(n??await nearestSiblings(e)),a=await majorityZoneName(e,r);return logger85().tap({msg:`nearestSiblingTzOffset()`,result:a,meta:{f:e,sibs:r.map(e=>e.base)}})}async function extractStatBnameTime(e){let n=bname(e),r=parseDated({input:n});if(r==null)logger85().debug(`extractStatBname(): no date in basename`,{file:e.nativePath,input:n});else return statIfOverlaps({desc:`extractStatBname()`,needle:r,f:e})}async function extractStatPathTime(e){let n=extractDateFromPath(e.pathsForDateParsing());if(n==null)logger85().debug(`extractStatPathTime(): no date in basename`,{file:e.nativePath});else return statIfOverlaps({desc:`extractStatPathTime()`,needle:n,f:e})}async function statIfOverlaps({desc:e,needle:n,f:r}){let a=await r.stat();if(a==null)logger85().debug(e+`: cannot stat `+r);else{for(let r of[`birthtime`,`mtime`,`ctime`]){let o=a[r];if(datedOverlap({a:n,b:o}))return o.setMilliseconds(0),logger85().tap({msg:e+`: overlap with `+r+` stat time`,result:{src:r,date:o},meta:{needle:n,stat:a}})}return logger85().tap({msg:e+`: no stat overlap`,result:void 0,meta:{needle:n,stat:a}})}}var logger86=defer(()=>mkLogger(`tags.CapturedAt`)),CapturedAt=class e{mimetype;date;capturedAtLocal;zone;capturedAtSrc;capturedAtSrcDetail;capturedAtZoneSrc;capturedAtPrecisionMs;capturedAtRaw;static async fromFile_(e,n){let r=PosixFile.for(e);return extractCapturedAt_(r,n??await readRawTags(r))}static fromJSON(e){let n=isValidDate(e.date)?e.date:fromJsonObject(e.date);if(n!=null&&isValidDate(n))return this.fromFields({...e,date:n})}static fromFields(n){if(n==null||n.mimetype==null||blank(n.mimetype))return;let r={...n};if(blank(r.capturedAtSrc))return logger86().tap({msg:`CapturedAt.fromFields(): missing required capturedAtSrc field`,result:void 0,meta:{ctorArgs:r}});if(r.capturedAtLocal==null&&r.date!=null?r.capturedAtLocal=datedToLocal(r.date):r.date==null&&r.capturedAtLocal!=null&&(r.date=localToDateTime({local:r.capturedAtLocal,zone:(0,import_exiftool_vendored18.normalizeZone)(r.zone)??(0,import_exiftool_vendored18.normalizeZone)(r.capturedAtZone)})),r.capturedAtLocal==null)return logger86().tap({msg:`CapturedAt.fromFields(): missing required capturedAtLocal field`,result:void 0,meta:{ctorArgs:r}});let a=new e(r),o=a.whyNotValid();return logger86().tap({msg:`CapturedAt.fromFields(): created instance`,result:o==null?a:void 0,meta:{why:o,ctorArgs:r}})}constructor(e){this.mimetype=e.mimetype,this.date=e.date,this.capturedAtRaw=toNotBlank(e.capturedAtRaw)??datedToRawValue(this.date),this.capturedAtLocal=e.capturedAtLocal,this.zone=(0,import_exiftool_vendored18.normalizeZone)(e.zone)??(0,import_exiftool_vendored18.normalizeZone)(e.capturedAtZone)??getZone(this.date),this.capturedAtSrc=e.capturedAtSrc,this.capturedAtSrcDetail=toNotBlank(e.capturedAtSrcDetail),this.capturedAtZoneSrc=toNotBlank(e.capturedAtZoneSrc),this.capturedAtPrecisionMs=e.capturedAtPrecisionMs??datedToPrecisionMs(e.date)}get zoneName(){return this.zone?.name}get capturedAtZone(){return this.zone?.name}toLogJSON(){return{_ctor:`CapturedAt`,mimetype:this.mimetype,local:this.capturedAtLocal,zoneName:this.capturedAtZone,src:this.capturedAtSrc,srcDetail:this.capturedAtSrcDetail,zoneSrc:this.capturedAtZoneSrc,precisionMs:this.capturedAtPrecisionMs}}toShortString(){return this.toISOString()+(this.capturedAtZone==null?``:` (${this.capturedAtZone})`)}toJSON(){return{mimetype:this.mimetype,date:toJsonObject(this.date),capturedAtLocal:this.capturedAtLocal,capturedAtZone:this.capturedAtZone,capturedAtPrecisionMs:this.capturedAtPrecisionMs,capturedAtSrc:this.capturedAtSrc,capturedAtSrcDetail:this.capturedAtSrcDetail,capturedAtZoneSrc:this.capturedAtZoneSrc,capturedAtRaw:this.capturedAtRaw}}toISOString(){return datedToISO(this.date)}toExifString(){return datedToEXIF(this.date)}toLocaleString(e){return toDate2(this.date)?.toLocaleString(e)??``}get isFromTags(){return this.capturedAtSrc===`tags`}get isFromStat(){return this.capturedAtSrc===`stat`||this.capturedAtSrc===`bname+stat`||this.capturedAtSrc===`path+stat`}get isInferred(){return!this.isFromTags&&!this.isFromStat}static isFuzzyFields(e){let n=CapturedAtSrcTypes.ordinal(e.capturedAtSrc),r=CapturedAtSrcTypes.ordinal(ReliableCapturedAtSrcFloor);return n>r||!(n<r)&&localIsBeforeDigitalCameras(e.capturedAtLocal)}get isFuzzy(){return e.isFuzzyFields(this)}get isImprecise(){return localIsImprecise(this.capturedAtLocal)}toISOStringWithPrecision(){return datedToISO(this.date,!0,this.capturedAtPrecisionMs)+(this.capturedAtPrecisionMs==null?``:` (±`+fmtMs(this.capturedAtPrecisionMs)+`)`)}hasZone(){return this.capturedAtZone!=null}isUTC(){return(0,import_exiftool_vendored18.isUTC)(this.capturedAtZone)}hasTime(){return hasTime(this.date)}hasMillis(){return gt0(getMillisecond(this.date))}toMillis(){return datedToMillis(this.date)}whyNotValid(){return blank(this.mimetype)?`missing mimetype`:blank(this.capturedAtSrc)?`missing capturedAtSrc`:isValidDate(this.date)?void 0:`invalid date`}get isValid(){return this.whyNotValid()==null}asExifTag(){if(this.date instanceof FuzzyDate)return;let e=this.toExifString();return e==null?void 0:{DateTimeOriginal:e,SubSecDateTimeOriginal:e}}fuzzyPrecisionMs(){return(this.isFuzzy||this.isImprecise?AggregationSettings.fuzzyDatePrecisionFactor.valueOrDefault:1)*(this.capturedAtPrecisionMs??secondMs)}localBoundaries(e){let n=(e?.precisionMs??0)+this.fuzzyPrecisionMs(),r=datedToStartDateTime(this.date)??datedToDateTime(this.date);if(r==null)logger86().warn(`localBoundaries() failed`,{date:this.date,args:e,d:r});else return{start:datedToLocal(r.minus(n)),end:datedToLocal(r.plus(n))}}overlaps(e){if(e==null)return!1;if(this.capturedAtLocal===e.capturedAtLocal)return!0;let n=this.mimetype===e.mimetype?0:AggregationSettings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,r=Math.max(n,this.fuzzyPrecisionMs()),a=Math.max(n,e.fuzzyPrecisionMs());return logger86().tap({level:`trace`,msg:`overlaps()`,result:this.capturedAtLocal===e.capturedAtLocal||datedOverlap({a:this.date,b:e.date,aPrecisionMs:r,bPrecisionMs:a}),meta:{a:this,b:e,aPrecisionMs:r,bPrecisionMs:a}})}toCapturedAtFields(){return pick(this,...CapturedAtFieldNames)}static async fromMediaInfoAsync(e){return this.fromMediaInfo(await awaitFields(pick(e,...CapturedAtFieldNames.values.filter(e=>e!==`capturedAtRaw`))))}static fromMediaInfo(n){if(!(n.capturedAtLocal==null||blank(n.capturedAtSrc)||blank(n.mimetype)))return e.fromFields(n)}},ReliableCapturedAtSrcFloor=`tags`;function skipLibraryName(e,n){return!ParsingSettings.useLibraryDirsToInferDates.valueOrDefault&&containedByNativePath({ancestor:PathSettings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})&&(n===`directory`||libraryFilenameEncodesDate(e))}async function extractCapturedAt(e){try{return await extractCapturedAt_(e,await readRawTags(e))}catch(n){logger86().warn(`readCapturedAt() failed`,{nativePath:toNativePath_(e),error:n});return}}var readCapturedAt=extractCapturedAt;async function extractCapturedAt_(e,n,r=!1,a){let o=PosixFile.for(e),s=toNotBlank(n?.MIMEType)??await readMimeType_(o);function c(e,n){return n!=null&&n.capturedAtLocal==null&&(n.capturedAtLocal=map(n?.date,datedToLocal)),logger86().tap({msg:`extractCapturedAt_()`,result:CapturedAt.fromFields({mimetype:s,capturedAtSrc:n?.capturedAtSrc??e,...n}),meta:{src:e,f:o,mimetype:s}})}let l=r||!ParsingSettings.usePathsToInferDates.valueOrDefault,u=defer(()=>l||skipLibraryName(o,`filename`)),d=defer(()=>l||skipLibraryName(o,`directory`)),f=c(`tags`,_capturedAtFromTags(n,ParsingSettings.capturedAtTagsPrimary.values))??c(`tags`,_capturedAtFromTags(n,ParsingSettings.capturedAtTagsSecondary.values))??c(`tags`,_capturedAtFromTags(n,ParsingSettings.capturedAtTagsTertiary.values))??c(`tags`,_capturedAtFromTags(n,ParsingSettings.capturedAtTagsFallback.values))??(r?void 0:c(`siblings`,await inferCapturedAtFromSiblings(o,a)))??(u()?void 0:c(`bname+stat`,await extractStatBnameTime(o)))??(d()?void 0:c(`path+stat`,await extractStatPathTime(o)))??(u()?void 0:c(`bname`,capturedAtFromBasename(o,n)))??(d()?void 0:c(`path`,capturedAtFromPath(o)))??(ParsingSettings.useStatToInferDates.valueOrDefault?c(`stat`,await capturedAtFromStat(o)):void 0);return f==null?logger86().throw(`Failed to extract capturedAt from `+o):logger86().tap({level:LogLevels.debug,msg:`extractCapturedAt()`,result:f,meta:{nativePath:o.nativePath}})}function capturedAtFromTags(e){return _capturedAtFromTags(e,ParsingSettings.capturedAtTagsPrimary.values)}function _capturedAtFromTags(e,n){if(e==null)return;let r=toNotBlank(e.MIMEType);if(r==null)return;if(e!=null&&`capturedAt`in e&&e.capturedAt instanceof CapturedAt)return e.capturedAt;let a=[];for(let o of n){let n=o in e?e[o]:void 0;if(isNumber(n)&&n>=ParsingSettings.minValidYear.valueOrDefault&&(n=FuzzyDate.for({year:n})),isValidDate(n)){let s=n,c=s,l;OverrideUTCZoneTags.includes(o)?(c=setZone(s,`UTC`)??s,l=`forced`):isValidZone(e.zone)&&!hasZone(s)&&(c=setZone(s,e.zone)??s,l=toNotBlank(blank(e.zoneSource)?void 0:stripPrefix(e.zoneSource,`from `)));let u=datedToLocal(c);if(u==null)continue;a.push({mimetype:r,capturedAtLocal:u,date:c,capturedAtSrc:`tags`,capturedAtSrcDetail:o,capturedAtZoneSrc:l})}}let o=leastBy(a,e=>datedToStartTs(e.date));if(o==null){logger86().debug(`capturedAtFromTags(): no candidate passed leastBy: returning null`,{candidates:a});return}let s=a.filter(e=>eql(e.date,o.date)||datedOverlap({a:e.date,b:o.date,aPrecisionMs:e.capturedAtPrecisionMs,bPrecisionMs:o.capturedAtPrecisionMs})),c=leastBy(s,e=>[Math.floor((e.capturedAtLocal??0)/1e6),+!hasZone(e.date),e.capturedAtPrecisionMs??MAX_PRECISION_MS,-1*(e.capturedAtRaw?.length??0),e.capturedAtSrc??``]);return logger86().debug(`capturedAtFromTags()`,{candidates:a,least:o,overlapsWithLeast:s,earliest:c}),c}function capturedAtFromBasename(e,n){if(ParsingSettings.usePathsToInferDates.valueOrDefault)for(let r of[bname(e),bname(toNotBlank(n?.PreservedFileName))])for(let e of sortBy(r,e=>-e.length)){let r=parseDated({input:e,defaultZone:n?.zone});if(r!=null)return{date:r,precisionMs:max2([datedToPrecisionMs(r),secondMs])}}}function capturedAtFromPath(e){if(ParsingSettings.usePathsToInferDates.valueOrDefault)return{date:extractDateFromPath(e.pathsForDateParsing())}}async function capturedAtFromStat(e){if(ParsingSettings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}function isUtcTagName(e){return e.includes(`UTC`)||e.startsWith(`GPS`)}var logger87=lazy2(()=>mkLogger(`tags.LensMakeModel`)),KnownLensBrands={nikkor:`Nikon`,"m.zuiko":`Olympus`,zuiko:`Olympus`},ZeissBatisHackRe=/^zeiss batis (?<f>[\d.]+)\/(?<mm>[\d.]+)(?<etc>.*)/i;function extractLensMakeModel(e){let n=make(e.LensMake),r=make(e.Make),a=[],o=first([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],justLengthAndAperture),s=uniq([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);logger87().debug(`extractLensMakeModel`,{lensMake:n,lensInfo:o,lensModels:s});for(let e of s){{let n=ZeissBatisHackRe.exec(e)?.groups;n!=null&&a.push({lensMake:`Zeiss`,lensModel:`Batis ${n.mm}mm F${n.f} ${n.etc.trim()}`.trim(),lensInfo:`${n.mm}mm f/${n.f}`})}if(justLengthAndAperture(e)==null)continue;notBlank(n)&&a.push({lensMake:n,lensModel:e,lensInfo:o});let s=e.toLowerCase();for(let[n,r]of entries(KnownLensBrands))s.includes(n)&&a.push({lensMake:r,lensModel:e,lensInfo:o});for(let r of compactBlanks([n,...Settings2.lensMakes.values]))e.toLowerCase().includes(r.toLowerCase())&&a.push({lensMake:r,lensModel:e,lensInfo:o});s.startsWith(`vr `)&&r===`Nikon`&&a.push({lensMake:`Nikon`,lensModel:e,lensInfo:o})}for(let e of a)e.lensMake=KnownLensBrands[e.lensMake.toLowerCase()]??e.lensMake,e.lensModel=cleanBogusPrecision(e.lensModel.replace(RegExp(`\\b`+e.lensMake+`\\b`,`i`),``)),e.lensInfo=map(e.lensInfo,cleanBogusPrecision);return greatestBy(a,e=>[e.lensModel.match(/\bor\b/i)==null,e.lensModel.length])}function nonZeroish(e){return e!=null&&e.match(/^0+$/)==null}var mmRangeRE=/([\d. -]+)\s?mm\b/i,apertureRE=/\bf\/?([\d.-]+)/i;function justLengthAndAperture(e){if(typeof e!=`string`||blank(e)||toS(e).toLowerCase().includes(`unknown`))return;e=e.replace(/\s+/g,` `).trim();let n=mmRangeRE.exec(e)?.[1].replace(/\s/g,``),r=apertureRE.exec(e)?.[1];return nonZeroish(n)&&nonZeroish(r)?cleanBogusPrecision(`${n}mm f/${r}`):void 0}function cleanBogusPrecision(e,n=3){return e.replace(/\d+\.\d+/g,e=>mapOr(toFloat(e),e=>String(sigFigs(e,n)),e)).replace(/\s+/g,` `).trim()}var ShutterCountSynonyms=[`ShutterCount`,`ShutterCount2`,`ShutterCount3`],CameraSerialNumberSynonyms=[`CameraSerialNumber`,`SerialNumber`,`BodySerialNumber`,`InternalSerialNumber`],TagSynonymGroups=[ShutterCountSynonyms,CameraSerialNumberSynonyms],Tag2SynonymGroup=lazy2(()=>{let e=new Map;for(let n of TagSynonymGroups){let r=n[0];for(let a of n)e.set(a,r)}return e}),zeroesRe=/^[\s0]*1?$/,UnknownUidCharactersRE=/\?{4,}/;function rubbish(e){return e==null||blankish(e)||isNumber(e)&&(e===0||e===1)||zeroesRe.exec(toS(e))!=null||UnknownUidCharactersRE.test(toS(e).replace(/\s/g,``))||hasCorruptionMarkers(toS(e))}function stringifyExifUid(e){let n=e==null?[]:e.filter(([,e])=>!blank(e));return n.length===0?void 0:stringify(fromEntries(n))}function normalizeString(e){return toS(e).trim().replace(/\s+/g,` `)}function renderExifUidId(e){let n=new MultiMap,r=[];for(let a of sortIgnoreCase(keys(e))){if(rubbish(e[a]))continue;let o=e[a],s=normalizeString(e[a]),c=Tag2SynonymGroup().get(a);if(c!=null){if(n.includes(c,o)||n.includes(c,s))continue;n.add(c,o)}r.push([a,gt0(o)?o:s])}return stringifyExifUid(r)}function splitToEntry(e){let n=splitFirst(e,`:`);return n.length===2?n:void 0}function decodeExifUid(e){if(blank(e))return;let n=parseJSON(e);return n==null?fromEntries([splitToEntry(e)]):Array.isArray(n)?fromEntries(n.map(splitToEntry)):compactBlankValues(n)}function findInequalFields(e,n){let r=decodeExifUid(e),a=decodeExifUid(n);if(r==null||a==null||e===n)return;let o=intersection(keys(r),keys(a)).filter(e=>!Tag2SynonymGroup().has(e));for(let e of o){let n=r[e],o=a[e];if(normalizeString(n)!==normalizeString(o))return{aKey:e,aValue:n,bKey:e,bValue:o}}for(let e of TagSynonymGroups){let n=pick(r,...e);if(isEmptyObj(n))continue;let o=pick(a,...e);if(isEmptyObj(o)||includesAny(values(n).map(toS),values(o).map(toS)))continue;let s=least(keys(n)),c=least(keys(o));return{aKey:s,aValue:r[s],bKey:c,bValue:a[c]}}}function exposureThresholds(){switch(AggregationSettings.aggregationMode.valueOrDefault){case`strict`:return{exposureStops:1/16,focalLengthRatio:.98};case`default`:case`manual`:return{exposureStops:1/3,focalLengthRatio:.9};case`lenient`:return{exposureStops:1,focalLengthRatio:.7}}}function exposureStopDistance(e,n,r=1){return r*Math.abs(Math.log2(e/n))}function whyDefinedNotSimilar({a:e,b:n,field:r,desc:a,parser:o,similar:s}){let c=o(e[r]),l=o(n[r]);return c==null||l==null||s(c,l)?void 0:`Different `+a+`: `+e[r]+` ≠ `+n[r]}function whyExposureSettingsNotSimilar(e,n){if(e==null||n==null)return;let{exposureStops:r,focalLengthRatio:a}=exposureThresholds();return whyDefinedNotSimilar({a:e,b:n,field:`focalLength`,desc:`focal length`,parser:extractFloat,similar:(e,n)=>approximates(e,n,a)===!0})??whyDefinedNotSimilar({a:e,b:n,field:`aperture`,desc:`aperture`,parser:extractFloat,similar:(e,n)=>exposureStopDistance(e,n,2)<=r})??whyDefinedNotSimilar({a:e,b:n,field:`shutterSpeed`,desc:`shutter speed`,parser:extractFraction,similar:(e,n)=>exposureStopDistance(e,n)<=r})??whyDefinedNotSimilar({a:e,b:n,field:`iso`,desc:`ISO`,parser:extractFloat,similar:(e,n)=>exposureStopDistance(e,n)<=r})}function cameraIdFromTags(e){return renderExifUidId(pick(e,...CameraSerialNumberSynonyms))}function lensIdFromLensInfo(e){let n=pick(e,`LensSerialNumber`);return e!=null&&!blank(e.lensMake)&&!blank(e?.lensInfo)&&(n.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),renderExifUidId(n)}function imageIdFromTags(e){return renderExifUidId(pick(e,`ImageNumber`,...ShutterCountSynonyms,`BurstUUID`,`RunTimeValue`))}var logger88=lazy2(()=>mkLogger(`tags.ExposureSettings`));function extractExposureSettings(e){let n={focalLength:e.FocalLength,iso:firstNonZero(e.ISO,e.ISOSpeed,e.SonyISO),aperture:firstNonZero(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:firstNotBlank(toS(e.ExposureTime),toS(e.ShutterSpeed),toS(e.ShutterSpeedValue),toS(e.SonyExposureTime))};return logger88().debug(`extracted from `+e.FileName,{exposureSettings:n}),reqValuedOrElse(n)}var import_tz_lookup=__toESM(require("@photostructure/tz-lookup")),import_exiftool_vendored19=require("exiftool-vendored"),logger89=defer(()=>mkLogger(`tags.InferTimezone`)),GpsZoneSource=`GPSLatitude/GPSLongitude`;async function maybeInferTimezone({pf:e,tags:n,skipSiblingInference:r,siblings:a}){return logger89().tap({msg:`maybeInferTimezone()`,result:await _maybeInferTimezone(e,n,r,a)})}async function _maybeInferTimezone(e,n,r,a){{let e=zoneFromLatLon(n);if(e!=null){let r={zone:e.name,zoneSource:GpsZoneSource};return eqlSubset(r,n)?void 0:r}}if(!(isValidZone(n.zone)&&n.zoneSource!==import_exiftool_vendored19.defaultVideosToUTC)){if(Settings2.inferTimezoneFromDatestamps.valueOrDefault)for(let e of compactBlanks([...Settings2.capturedAtTagsPrimary.values,...Settings2.capturedAtTagsSecondary.values,...Settings2.capturedAtTagsTertiary.values,...Settings2.capturedAtTagsFallback.values])){let r=n[e];if(r instanceof import_exiftool_vendored19.ExifDateTime&&isValidZone(r.zone)&&!isUtcTagName(e)&&r.zone!==`UTC`)return{zone:r.zone,zoneSource:`infer:tag.`+e+`.zone`}}if(!r){let r=inferTzOffsetMinutesFromFilename(e,n);if(r!=null)return r}if(!r){let n=await nearestSiblingTzOffset(e,a);if(n!=null)return{zone:n.zoneName,zoneSource:`infer:nearestSibling:`+n.base}}}}function zoneFromLatLon(e={}){let n=e.GPSLatitude,r=e.GPSLongitude;if(!validLat(n)||!validLon(r))return logger89().tap({msg:`zoneFromLatLon(): invalid lat/lon`,result:void 0,meta:{lat:n,lon:r}});try{let e=(0,import_tz_lookup.default)(n,r);return logger89().tap({msg:`zoneFromLatLon()`,result:(0,import_exiftool_vendored19.normalizeZone)(e),meta:{lat:n,lon:r,zoneName:e}})}catch(e){return logger89().tap({msg:`zoneFromLatLon(): invalid lat/lon`,result:void 0,meta:{lat:n,lon:r,error:e}})}}function inferTzOffsetMinutesFromFilename(e,n){let r=parseDateTime(bname(e.name))?.setZone(`UTC`,{keepLocalTime:!0});if(r!=null&&isValidDate(r))for(let a of Settings2.capturedAtTagsPrimary.values){let o=toDated(n[a]);if(o==null||!isValidDate(o))continue;let s=datedToMillis(o);if(s==null)continue;let c=Math.round((r.toMillis()-s)/6e4),l=(0,import_exiftool_vendored19.inferLikelyOffsetMinutes)(c),u=l===0?void 0:(0,import_exiftool_vendored19.normalizeZone)(l);if(u!=null)return logger89().tap({msg:`inferTzOffsetMinutesFromFilename(`+e.name+`)`,result:{zone:u.name,zoneSource:`infer:filename (diff with `+a+`)`},meta:{dt:datedToISO(o),rawTzoffsetMinutes:c,normalizedOffsetMinutes:l}})}}function clampRating(e){let n=toInt(e);return n==null?void 0:clamp(-1,5,n)}function extractRating(e){return clampRating(e?.Rating)??mapNumeric(toInt(e?.RatingPercent),e=>Math.ceil(e*5/100))??map(e?.favorited,e=>e===!0?Settings2.likeRating.valueOrDefault:void 0)}var import_sharp2=__toESM(require("sharp")),Ratios=uniqBy(flatMap([[3,2],[4,3],[16,9],[1,1]],([e,n])=>[{i:e/n,s:e+`:`+n},{i:n/e,s:n+`:`+e}]),e=>e.s),StandardAspectRatios=Ratios.map(e=>e.i),RatioEpsilon=.06;function toRatio(e,n){if(e!=null){if(gt0(e))return swappableRotation(n)?1/e:e;if(isDimensions(e)){let r=swappableRotation(n)?dimSwap(e):e;return r.height===0?void 0:r.width/r.height}}}function roundToNearestRatio(e,n=RatioEpsilon){let r=toRatio(e);return r==null?void 0:leastBy(StandardAspectRatios,e=>{let a=Math.abs(r-e);return a>n?void 0:a})??r}function similarRatios(e,n,r=RatioEpsilon){return e==null||n==null?!1:lte(absdiff(roundToNearestRatio(e),roundToNearestRatio(n)),r)}function nearestAspectRatio(e,n){return leastByCtx(Ratios,r=>{let a=Math.abs(r.i-e);return a<n?a:void 0})}function roundAspectRatio(e,n=.05){return n<=0?e:nearestAspectRatio(e,n)?.result.i??e}function ltBoth(e,n){return lt(e.width,n.width)&<(e.height,n.height)}function lteBoth(e,n){return lte(e?.width,n?.width)&<e(e?.height,n?.height)}function aspectRatio(e,n){if(e!=null&>0(e.width)&>0(e.height))return sigFigs(roundAspectRatio(e.width/e.height,n),3)}async function pathToTool_(e){return await pathTo2({tool:e})??throwNewError(`Cannot find path for `+e)}var dcrawEmuNativePath_=lazy2(()=>pathToTool_(`dcraw_emu`)),rawIdentifyNativePath_=lazy2(()=>pathToTool_(`raw-identify`)),jpegtranNativePath_=lazy2(()=>pathToTool_(`jpegtran`)),sqliteNativePath_=lazy2(()=>pathToTool_(`sqlite3`)),rgNativePath_=lazy2(()=>pathToTool_(`rg`)),logger90=lazy2(()=>mkLogger(`img.RawInfo`)),cache5=lazy2(()=>new FileCache({maxSize:512,name:`img.RawInfoCache`,timeoutMs:Settings2.taskTimeoutMs.valueOrDefault,...metadataCacheOptions()}));async function rawInfo(e){try{return await rawInfo_(e)}catch(n){logger90().warn(`rawInfo() failed`,{error:n,file:e});return}}async function rawInfo_(e){return cache5().getOrSet(e.nativePath,async()=>{let n=await rawIdentifyNativePath_(),r=await stdoutResult_(n,[`-s`,e.nativePath],{timerName:`proc.libraw`,timeoutMs:statTimeoutMs()});if(logger90().debug(`rawInfo()`,{cmd:n,src:e.nativePath,result:r}),notBlank(r.stderr)){let n=r.stderr.trim();return n.includes(e.nativePath)||(n=e.nativePath+`: `+n),logger90().throw(`rawInfo() failed`,{error:n})}return parseRawInfoOutput_(e,r.result)},await fileStamp(e))}function parseRawInfoOutput_(e,n){let[r,a,o,s,c]=n.split(` `),l=toGt0(s),u=toGt0(c);return l==null||u==null?logger90().throw(`parseRawInfoOutput_ failed (missing dimensions)`,{src:e.nativePath,cause:n}):logger90().tap({msg:`parseRawInfoOutput()`,result:{Filename:r,...makeModel({Make:a,Model:o}),ImageSize:{width:l,height:u}},meta:{input:n}})}var import_sharp=__toESM(require("sharp")),ModeBits=12,epsilon=216/24389,kappa=24389/27,LabBitZip=lazy2(()=>new BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]));function toLabhash(e,n=ModeBits){return LabBitZip().zip(e,n)}var labhash2lab=new Map;function unlabhash(e,n=ModeBits){return n===ModeBits?getOrSet(labhash2lab,e,()=>_unlabhash(e,n)):_unlabhash(e,n)}function _unlabhash(e,n=ModeBits){return LabBitZip().unzip(e,n)}var minLabhash=lazy2(()=>LabBitZip().zipMin(ModeBits)),maxLabhash=lazy2(()=>LabBitZip().zipMax(ModeBits)),logger91=lazy2(()=>mkLogger(`img.Sharp`));function isSharp(e){return e!=null&&(e.constructor?.name===`Sharp`||typeof e==`object`&&typeof e.metadata==`function`&&typeof e.jpeg==`function`&&typeof e.raw==`function`&&typeof e.toBuffer==`function`)}var Colorspaces=strEnum(`hsl`,`hsv`,`lab`,`labq`,`labs`,`lch`,`rgb`,`srgb`,`xyz`);async function sharpToColorspaceBuffer(e,n=`char`,r=`lab`){if(n===`char`&&r!==`lab`)throw Error(`char precision causes clipping issues with `+r);let{data:a,info:o}=await e.clone().removeAlpha().toColorspace(r).raw({depth:n}).toBuffer({resolveWithObject:!0});return{data:n===`char`?new Int8Array(a.buffer,a.byteOffset,a.length):new Float32Array(a.buffer,a.byteOffset,a.length/Float32Array.BYTES_PER_ELEMENT),info:o}}async function sharpClone(e){try{return sharpFromBufferResult(await e.clone().raw().toBuffer({resolveWithObject:!0}))}catch(e){return logger91().throw(`clone via sharp.raw().toBuffer() failed`,{error:e,retriable:!1,doNotSend:!0,logLevel:`warn`})}}function sharpFromBufferResult(e){return(0,import_sharp.default)(e.data,{raw:e.info,failOn:`none`})}function sharpRenderOptions(){return{quality:Settings2.previewQuality.valueOrDefault,progressive:Settings2.previewProgressive.valueOrDefault,mozjpeg:Settings2.previewMinimized.valueOrDefault}}var setupSharp=lazy2(()=>{(0,import_sharp.block)({operation:[`VipsForeignLoadUhdr`]}),(0,import_sharp.simd)(Settings2.enableSIMD.valueOrDefault),(0,import_sharp.cache)(Settings2.enableVipsCache.valueOrDefault?{files:32,memory:64,items:128}:!1),(0,import_sharp.concurrency)(sharpThreadsPerProcess())});later(()=>{Settings2.enableSIMD.watchLater(()=>setupSharp.refresh()),Settings2.enableVipsCache.watchLater(()=>setupSharp.refresh())});function isSharpWithOptions(e){return`options`in e&&isObject(e.options)&&isSharp(e)}function sharpGetRotation(e){return normalizeRotation(isSharpWithOptions(e)?e.options.angle:0)}function sharpAddRotation(e,n){if(n===0)return e;if(isSharpWithOptions(e)&&e.options.useExifOrientation===!0)throw Error(`sharp will ignore this rotation`);return e.rotate(normalizeRotation((sharpGetRotation(e)??0)+n))}function sharpClearRotation(e){if(isSharpWithOptions(e)){let n=e.options.angle;return e.options.angle=0,e.options.rotateBeforePreExtract=!1,e.options.useExifOrientation=!1,n}}function sharpResize(e,n){if(n.width!==n.height)return logger91().throw(`use .resize() for non-square dimensions`);if(![`fill`,`cover`].includes(toS(n.fit)))return logger91().throw(`use .resize() with {fit: 'fill'} or {fit: 'cover'}: passed `+stringify(n));let r=sharpClearRotation(e);return e.resize({fastShrinkOnLoad:!0,...n}),gt0(r)&&e.rotate(r),e}var logger92=lazy2(()=>mkLogger(`tags.SizeInfo`));async function extractSizeInfoFromFile(e,n){if(e==null)return;let r=PosixFile.for(e);return sizeInfoCache().getOrSet(r.nativePath,()=>_extractSizeInfoFromFile(r,n),await fileStamp(r))}async function extractSizeInfoFromSharp(e,n){setupSharp();try{let r=await(0,import_sharp2.default)(e.nativePath).metadata();return logger92().tap({msg:`extractSizeInfoFromSharp()`,result:extractSizeInfoFromTags({MIMEType:n,ImageHeight:r.height,ImageWidth:r.width,Orientation:r.orientation}),meta:omit(r,`exif`,`icc`,`iptc`,`xmp`)})}catch(n){logger92().info(`extractSizeInfoFromSharp() failed, falling back to ExifTool`,{error:String(n),nativePath:e.nativePath});return}}async function _extractSizeInfoFromFile(e,n){if(e==null)return;let r=n?.MIMEType??await readMimeType(e);if(r!=null&&isSharpMimeType(r)){let n=await extractSizeInfoFromSharp(e,r);if(n!=null)return n}let a=n==null||!gt0(n.ImageHeight)?await readRawTags(e):n;if(a==null)return;let o=extractRotation(n)??extractRotation(a),s=isLibrawMimeType(a.MIMEType)?await rawInfo(e):void 0;return logger92().tap({msg:`_extractSizeInfoFromFile() from tags`,result:extractSizeInfoFromTags(a,o,s),meta:{nativePath:e.nativePath,pickedDefaultTags:pick(n,`ImageHeight`,`ImageWidth`,`MIMEType`,`Orientation`,`Rotation`),pickedTags:pick(a,`ImageHeight`,`ImageWidth`,`MIMEType`,`Orientation`,`Rotation`),rotation:o,raw:s}})}function extractSizeInfoFromTags(e,n,r){n=normalizeRotation(n)??extractRotation(e)??0;let a=[r?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}].find(isDimensions);if(a==null)return logger92().tap({msg:`extractSizeInfoFromTags(`+e?.FileName+`) (undefined fileDimensions)`,result:void 0,meta:{mimetype:e?.MIMEType,_rawInfo:r,fileDimensions:a}});let o=maybeDimSwap(a,n);return logger92().tap({msg:`extractSizeInfoFromTags(`+e?.FileName+`)`,result:{ImageHeight:o.height,ImageWidth:o.width,aspectRatio:aspectRatio(o),dimensions:o,rotation:n,fileDimensions:a,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,_rawInfo:r}})}var logger93=defer(()=>mkLogger(`tags.ReadTags`));function readTags(e){return e==null?void 0:_readTags(toNativePath_(e))}var _readTags=shim({impl:async e=>{let n=PosixFile.for(e),r=await readRawMergedTags(n);return timeExcludingNested({name:`exif.parseTags`,thunk:()=>parseTags(n,r)})},cache:tagsCache,stamp:mergedTagsStamp,toKey:e=>e});async function parseTags(e,n){return n==null?void 0:_parseTags(e,n)}function wrap2(e){return(n,r)=>{try{return e(r)}catch(r){logger93().warn(`Extractor `+e.name+` failed for `+n,{error:r});return}}}var _extractLensMakeModel=wrap2(extractLensMakeModel),_extractExposureSettings=wrap2(extractExposureSettings),_extractRating=wrap2(extractRating),_extractDurationSec=wrap2(extractDurationSec),_extractDurationMs=wrap2(extractDurationMs);function charsetForCamera(e,n){let r=Settings2.exifCharsetByCamera;if(r.isEmpty())return;let a=(e==null?[]:n==null?[e]:[`${e}/${n}`,e]).map(e=>e.toLowerCase());for(let e of a)for(let[n,a]of r.entries())if(n.toLowerCase()===e)return a}function withoutBlankStrings(e){let n={...e};for(let e of Object.keys(n)){if(e===`original`)continue;let r=n[e];isString(r)&&blank(r)&&delete n[e]}return n}async function _parseTags(e,n){try{let r=e.nativePath,a=mapNotBlank(n.MIMEType,normalizeMimetype);if(blank(a)){logger93().debug(`No mimetype`,{file:r});return}let o={...n.inferred??{},...n};o.inferred??={},o.original??={};let{tags:s,charsetByPath:c}=recoverInvalidUtf8Tags(o,{cameraCharset:charsetForCamera(o.Make,o.Model)});if(Object.assign(o,s),Object.keys(c).length>0&&logger93().debug(`parseTags() recovered invalid-UTF-8 text`,{file:r,charsetByPath:c}),Settings2.fuzzyDateParsing.valueOrDefault)for(let e of[...Settings2.capturedAtTagsPrimary.values,...Settings2.capturedAtTagsSecondary.values,...Settings2.capturedAtTagsTertiary.values,...Settings2.capturedAtTagsFallback.values]){let n=o[e];if(isString(n)){let a=parseDated({input:n,includeDate:!0,includeFuzzyDate:!0});a!=null&&(logger93().debug(`parseTags() fuzzy date`,{file:r,fuzzy:a,k:e,v:n}),o[e]=a)}}let l=!await canInferForDir(e.parent()),u=!0===isInInternalDir(e.parent()),d=l?void 0:await nearestSiblings(e),f=await maybeInferTimezone({pf:e,tags:o,skipSiblingInference:l,siblings:d}),h=o.zoneSource===import_exiftool_vendored20.GeolocationTagNames.GeolocationTimeZone||o.zoneSource===GpsZoneSource,_=f?.zone!=null||h?{...o}:void 0;if(logger93().debug(`parseTags()`,{file:r,tzMeta:f,skipSiblingInference:l}),f?.zone!=null){let e=o.zoneSource!==import_exiftool_vendored20.defaultVideosToUTC&&void 0;for(let n of[...Settings2.capturedAtTagsPrimary.values,...Settings2.capturedAtTagsSecondary.values,...Settings2.capturedAtTagsTertiary.values,...Settings2.capturedAtTagsFallback.values])if(!isUtcTagName(n)){let r=o[n];r instanceof import_exiftool_vendored20.ExifDateTime&&(o[n]=setZone(r,f.zone,{keepLocalTime:e})??r)}assignUndefinedFields(o.original,o,`zone`,`zoneSource`),assignFields(o,f)}let y=l?extractMakeAndModel(o):await inferMakeAndModel({pf:e,tags:o,siblings:d});y.Make!==make(o.Make)&&(o.original.Make=o.Make,o.inferred.Make=y.Make),y.Model!==model(y.Make,o.Model)&&(o.original.Model=o.Model,o.inferred.Model=y.Model),!blank(Settings2.defaultCopyright.valueOrDefault)&&isExifUnset(o.Copyright)&&(o.Copyright=Settings2.defaultCopyright.valueOrDefault);let x=_extractLensMakeModel(e,o),C;try{C=await extractCapturedAt_(e,o,u,d)}catch(n){logger93().info(`No capturedAt for `+e,{error:n});return}let w=C.capturedAtSrcDetail,T=_?.capturedAt instanceof CapturedAt?_.capturedAt:C.isFromTags&&w!=null?_capturedAtFromTags(_,[w]):void 0,E=T instanceof CapturedAt?T.capturedAtZone:T!=null&&hasZone(T.date)?getZoneName(T.date):void 0,D=h&&!(T instanceof CapturedAt),O=C.isFromTags&&C.capturedAtZone!=null&&(f?.zone!=null&&C.capturedAtZone!==E||D);!u&&(C.isInferred||O)&&(o.inferred.capturedAt=C);let k=_extractExposureSettings(e,o),A=await extractSizeInfoFromFile(e,o);if(A==null){logger93().info(`No size info`,{file:r});return}let j=normalizedGpsCoordinates(n.GPSLatitude,n.GPSLongitude)??{latitude:null,longitude:null},M={...y,mimetype:a,capturedAt:C,exposureSettings:k,make:y.Make,model:y.Model,...x,cameraId:cameraIdFromTags(o),imageId:imageIdFromTags(o),lensId:lensIdFromLensInfo({...x,...pick(o,`LensSerialNumber`)}),...A,duration:_extractDurationSec(e,o),zone:o.zone,rating:_extractRating(e,o),metadataDate:map(datedToMillis(n.MetadataDate),Math.round),...j,durationMs:_extractDurationMs(e,o),fps:mapFloat(n.VideoFrameRate,e=>sigFigs(e,4))};isTest()&&addInstanceIds(M);let N=withoutBlankStrings({...o,...M});return logger93().debug(`parsedTags`,{file:r,skipInference:l,...M,inferred:o.inferred,original:o.original,pickedResult:pick(N,`capturedAt`,`zone`,`zoneSource`,`Make`,`Model`,`UserComment`)}),N}catch(n){logger93().warn(`parseTags() failed`,{file:e.nativePath,error:n});return}}var logger94=lazy2(()=>mkLogger(`img.FileDimensions`));async function dimensions(e){try{let n=await extractSizeInfoFromFile(e);return n==null?void 0:{width:n.ImageWidth,height:n.ImageHeight}}catch(e){logger94().warn(`dimensions() failed`,{error:e});return}}var PreviewRenderPolicyVersion=1,VideoFramePolicyVersion=1;function previewSourceStatsUnchanged(e,n){return e?.mtime!=null&&e.fileSize!=null&&isEquivalentNumber(e.mtime,n.mtime,Settings2.mtimeMsEpsilon.valueOrDefault)&&isEquivalentNumber(e.fileSize,n.fileSize,Settings2.fileSizeEpsilon.valueOrDefault)}function previewFingerprint(e){let{source:n,recipe:r}=e;return`pf1:`+shortStringSha(JSON.stringify([n.assetFileId,n.sha,n.renderWidth,n.renderHeight,normalizeMimetype(n.mimetype),n.rotation,r.mediaKind,r.canIncludeInputDim,r.fitInside.map(({width:e,height:n})=>[e,n]),r.maxThumbnailLongEdge,r.previewPixelWastePct,r.renderPolicyVersion,...r.mediaKind===`video`?[VideoFramePolicyVersion]:[]]))}function validDimensions2(e){return Number.isSafeInteger(e.width)&&e.width>0&&Number.isSafeInteger(e.height)&&e.height>0}function fitWithoutEnlargement(e,n){let r=Math.min(1,n.width/e.width,n.height/e.height);return{width:Math.max(1,Math.round(e.width*r)),height:Math.max(1,Math.round(e.height*r))}}function pixelCount(e){return e.width*e.height}function endpointLadder(e,n,r,a){if(!validDimensions2(n))return[];if(!validDimensions2(r))return[n];let o=pixelCount(n),s=pixelCount(r);if(o<=s||a===0)return[n];let c=maxPixelRatio(a),l=Math.max(1,Math.ceil(Math.log(o/s)/Math.log(c))),u=[n],d=e.width>=e.height,f=d?n.height:n.width,h=d?r.height:r.width;for(let n=1;n<l;n++){let r=n/l,a=Math.max(1,Math.round(f*(h/f)**r)),o=d?{width:Math.max(1,Math.round(a*e.width/e.height)),height:a}:{width:a,height:Math.max(1,Math.round(a*e.height/e.width))},c=pixelCount(o);c<pixelCount(u[u.length-1])&&c>s&&u.push(o)}return dimEql(u[u.length-1],r)||u.push(r),u}function validFitInside(e){return Array.isArray(e)&&e.length>=1&&e.length<=2&&e.every(validDimensions2)&&new Set(e.map(e=>`${e.width}x${e.height}`)).size===e.length}function thumbnailRungs(e,n,r){let a=[];for(let o of thumbnailWidthsForPixelWaste(n,{maxThumbnailLongEdge:r,maxOutputLongEdge:Math.max(e.width,e.height)})){let n=fitWithoutEnlargement(e,{width:o,height:o});a.some(e=>dimEql(e,n))||a.push(n)}return a}function greatestFitInside(e,n){let r=fitWithoutEnlargement(e,n[0]);for(let a of n.slice(1)){let n=fitWithoutEnlargement(e,a);n.width*n.height>r.width*r.height&&(r=n)}return r}function previewFitInsideForMimeType(e){return isVideoMimeType(e)?VideoSettings.videoPreviewFitInside.valueOrDefault:PreviewsSettings.photoPreviewFitInside.valueOrDefault}function previewLadder({dim:e,fitInside:n,maxThumbnailLongEdge:r,previewPixelWastePct:a,canIncludeInputDim:o}){if(!validDimensions2(e))throw Error(`previewLadder(): dimensions must be positive integers`);if(!validFitInside(n))throw Error(`previewLadder(): fitInside must contain one or two unique positive integer dimensions`);if(!Number.isSafeInteger(r)||r<MinMaxThumbnailLongEdge||r>MaxMaxThumbnailLongEdge)throw Error(`previewLadder(): maxThumbnailLongEdge must be between ${MinMaxThumbnailLongEdge} and ${MaxMaxThumbnailLongEdge}`);if(n.some(e=>Math.max(e.width,e.height)<MinFitPreviewLongEdge))throw Error(`previewLadder(): fitInside long edge must be at least ${MinFitPreviewLongEdge}`);if(!isNumber(a)||a!==0&&(a<MinPreviewPixelWastePct||a>MaxPreviewPixelWastePct))throw Error(`previewLadder(): previewPixelWastePct must be 0 or between ${MinPreviewPixelWastePct} and ${MaxPreviewPixelWastePct}`);let s=e.width*e.height,c=greatestFitInside(e,n),l=fitWithoutEnlargement(e,{width:r,height:r}),u=thumbnailRungs(e,a,r),d;if(pixelCount(c)>pixelCount(l)){let n=endpointLadder(e,c,l,a);d=[...n,...dimEql(n[n.length-1],l)?u.slice(1):u]}else d=[...u],d.some(e=>dimEql(e,c))||(d.push(c),d.sort((e,n)=>pixelCount(n)-pixelCount(e)));if(o){if(a===0&&d.length>1)d=d.filter(e=>!dimEql(e,c));else if(a!==0){let e=maxPixelRatio(a);for(;d.length>1&&pixelCount(d[0])>pixelCount(l)&&s/pixelCount(d[1])<=e;)d.shift()}}return d.map(e=>({outputSize:e,role:u.some(n=>dimEql(n,e))?`thumbnail`:`display`}))}var logger95=lazy2(()=>mkLogger(`img.Video`));async function mergeCodecInfo(e,n){let r=n.VideoCodec!=null||n.CompressorID!=null,a=n.AudioFormat!=null;if(r&&a)return n;let o=await ffprobe_(e);if(o==null)return n;let s={...n};return!r&&o.VideoCodec!=null&&(s.VideoCodec=o.VideoCodec),!a&&o.AudioCodec!=null&&(s.AudioFormat=o.AudioCodec),logger95().debug(`mergeCodecInfo()`,{file:e.nativePath,original:{video:n.VideoCodec??n.CompressorID,audio:n.AudioFormat},merged:{video:s.VideoCodec??s.CompressorID,audio:s.AudioFormat}}),s}function determineTranscodeStrategy(e,n){let r=e.MIMEType,a=compactBlanks([e.VideoCodec,e.CompressorID,e.CompressorName]),o=compactBlanks([e.AudioFormat,e.AudioCodec]),s=a.some(e=>includesIgnoreCase(Settings2.doNotTranscodeVideoCodecs.values,e)),c=o.some(e=>includesIgnoreCase(Settings2.doNotTranscodeAudioCodecs.values,e)),l=r!=null&&includesIgnoreCase(Settings2.browserCompatibleContainers.values,r),u=n?.pixFmt,d=!isBrowserCompatiblePixFmt(u),f=n!=null&&!hasConsistentColorspaceMetadata(n),h=s&&!d&&!f;return logger95().debug(`determineTranscodeStrategy()`,{mimetype:r,videoCodecs:a,audioCodecs:o,pixFmt:u,isBrowserCompatibleVideoCodec:s,pixFmtNeedsConversion:d,colorspaceNeedsCorrection:f,isBrowserCompatibleVideo:h,isBrowserCompatibleAudio:c,isBrowserCompatibleContainer:l}),h&&c&&l?`none`:h&&c?`remux`:!h&&c?`video-only`:h&&!c?`audio-only`:`full`}function mkLog(e,n){return mkLogger(`img/Video.`+e+`(`+toNativePath_(n)+`)`)}async function getFfmpegToolDetails_(e){if(isProd()&&(e=e?.forceRefresh===!0?{forceRefresh:!0}:void 0),!isTrue(e?.ignoreffmpeg))return e?.forceRefresh===!0&&refreshFfmpegVersion_(),await ffmpegVersion_()}var isVideoSupported=lazy2(async()=>{try{return(await getFfmpegToolDetails_())?.isSupportedVersion===!0}catch(e){return logger95().warn(`isVideoSupported`,{error:e}),!1}});later(()=>{ee().on(`clearCache`,()=>isVideoSupported.unset()),ee().on(`clearToolCache`,()=>isVideoSupported.unset())});function extractVideoDimensions(e,n){let r=mkLog(`extractVideoDimensions`,e),a=Settings2.minVideoDimension.valueOrDefault,o=n.ImageWidth;if(o!=null&&!gte(o,a))return r.throw(`invalid width: `+o,{ignorable:!0});let s=n.ImageHeight;if(s!=null&&!gte(s,a))return r.throw(`invalid height: `+s,{ignorable:!0});let c={width:o,height:s};return r.debug(`extractVideoDimensions()`,{file:e,result:c}),c}var cache7=lazy2(()=>new FileCache({name:`img.videoFrame`,...metadataCacheOptions(),timeoutMs:minuteMs}));async function extractVideoFrame_(e){return await isVideoSupported()?PosixFile.for(await _extractVideoFrame_(toNativePath_(e))):void 0}var _extractVideoFrame_=shim({name:`img.extractVideoFrame`,toKey:e=>e,stamp:e=>fileStamp(e),cache:cache7,impl:e=>__extractVideoFrame_(e)});async function __extractVideoFrame_(e,n){let r=mkLog(`extractVideoFrame`,e),a=PosixFile.for(e);if(!await isFFmpegSupported())return r.throw(`no video implementation`);let o=PosixFile.forMaybe(n)??await cachedImageFile_(a,`frame-v`+VideoFramePolicyVersion,`.jpg`);r.debug(`extractVideoFrame(`+o+`)`);let s=await a.mtimeMs();if(s==null)return r.throw(`null mtime for `+e);let c=await readRawTags(a);if(c==null)return r.throw(`no tags`);let l=extractRotation(c);r.debug(`video orientation:`+l);let u=extractSizeInfoFromTags(c,l)?.dimensions,d=await o.stat(),f=d==null?void 0:await dimensions(o);return d!=null&&d.mtimeMs>s&&f!=null&&(u==null||f.height===u.height&&f.width===u.width)?(r.debug(`prior dest, `+o+` seems reasonable`,{srcDim:u,destDim:f}),o.nativePath):(await o.applyIfEmpty_({fn_:async e=>{await ffmpegFrame_({src:a,dest:e,...u}),!1===await untilTrue(async()=>r.tap({msg:`frame extracted?`,result:await e.clear().isNonEmptyFile()}),{timeoutMs:5*secondMs,intervalMs:500})&&r.throw(`ffmpeg failed to extract frame`),await deleteAllTags_(e,e)},timeoutMs:commandTimeoutMs()}),o.nativePath)}async function isVideoTranscodingSupported(){return Settings2.transcodeVideos.valueOrDefault&&await isFFmpegSupported()}function targetTranscodeDimensions(e){let n=greatestFitInside(e,Settings2.videoPreviewFitInside.valueOrDefault);return{width:Math.floor(n.width/2)*2,height:Math.floor(n.height/2)*2}}async function isTranscodeOf(e,n){if(!await n.isNonEmptyFile())return logger95().tap({msg:`isTranscodeOf()`,result:!1,meta:{reason:`dest does not exist`,dest:n.nativePath}});let r=await readTags(n),a=await readTags(e),o=extractDurationSec(a),s=extractDurationSec(r),c=a?.dimensions==null?void 0:targetTranscodeDimensions(a.dimensions),l=c!=null&&r?.dimensions!=null&&r.dimensions.width<=c.width&&r.dimensions.height<=c.height&&closeTo(r.dimensions.width,c.width,2)&&closeTo(r.dimensions.height,c.height,2),u=closeTo(o,s,1.5);return logger95().tap({msg:`isTranscodeOf()`,result:u&&l,meta:{srcDurationSec:o,destDurationSec:s,durationMatches:u,dimensionsMatch:l,targetDimensions:c,destDimensions:r?.dimensions,src:e.nativePath,dest:n.nativePath}})}var currentTranscodes=new Map;function vacuumCurrentTranscodes(){for(let[e,n]of currentTranscodes)n.isResolved()&¤tTranscodes.delete(e)}async function transcode_(e,n,r){if(!await isVideoTranscodingSupported())return;let a=performance.now(),o=mkLog(`transcode`,e);r.halt!=null&&(o.abortable=r.halt);function s(){o.throwIfAborted_(),vacuumCurrentTranscodes();let r=currentTranscodes.get(n.nativePath);if(r!=null)return o.info(`already transcoding`,{src:e,dest:n,elapsedMs:r.elapsedMs}),o.awaitOrAbort(r).then(()=>n)}{let e=s();if(e)return e}let c=await readTags(e);if(c==null)return o.throw(`Cannot transcode files that exiftool can't read`);let l=c.MIMEType;if(!isVideoMimeType(l)){o.info(`not transcoding (unsupported mimetype)`,{mimetype:l});return}let u=extractDurationSec(c);if(!gt2(u,Settings2.minVideoDurationSec.valueOrDefault)){o.info(`not transcoding (video duration is too short)`,{durationSec:u});return}let d=await mergeCodecInfo(e,c),f=await ffprobeColorspace_(e),h=determineTranscodeStrategy(d,f);if(h===`none`){o.info(`no transcoding needed (already browser-compatible)`,{strategy:h,pixFmt:f.pixFmt}),await n.unlink_();return}let _=await e.size();if(!gt0(_))return o.throw(`source is empty or cannot read`);let y=extractSizeInfoFromTags(c);if(y==null)return o.throw(`failed: missing video metadata`,{sizeInfo:y,durationSec:u});if(y.dimensions!=null){let e=greatestFitInside(y.dimensions,Settings2.videoPreviewFitInside.valueOrDefault);(e.width!==y.dimensions.width||e.height!==y.dimensions.height)&&(h===`remux`?(o.info(`upgrading strategy from remux to video-only (videoPreviewFitInside)`,{strategy:h,fitInside:Settings2.videoPreviewFitInside.valueOrDefault,source:y.dimensions,fitted:e}),h=`video-only`):h===`audio-only`&&(o.info(`upgrading strategy from audio-only to full (videoPreviewFitInside)`,{strategy:h,fitInside:Settings2.videoPreviewFitInside.valueOrDefault,source:y.dimensions,fitted:e}),h=`full`))}{let e=s();if(e)return e}extractVideoDimensions(e,c);let x=c.dimensions,C=new Latch;return currentTranscodes.set(n.nativePath,C),await C.observe((async()=>{!0!==r?.force&&await isTranscodeOf(e,n)?o.info(`no-op, dest duration and dimensions match`,{dest:n}):await time({name:`img.video.transcode`,meta:{src:e},post:(e,n)=>{e instanceof Error&&pushTime({name:`img.video.transcode`,elapsedMs:n})},p:async()=>{let s=guessExpectedSize(_,u,h);async function c(c){o.info(`starting...`,{destWip:c,strategy:h,colorspace:f});let l=h===`remux`?`Remuxing video`:h===`audio-only`?`Transcoding audio`:h===`video-only`?`Transcoding video (copying audio)`:`Transcoding video`,d=new PullProgressObserver({path:e.nativePath,op:l},s,async()=>await n.clear().size()??0),_=r.stallTimeoutMs??Settings2.ffmpegStallTimeoutMs.valueOrDefault,y=r.onProgress,C=(u??0)*1e3,w=y==null?void 0:e=>{let n=e.outTimeMs!=null&>0(C)?Math.min(100,Math.max(0,e.outTimeMs/C*100)):void 0;y({pct:n,etaMs:ffmpegEtaMs(e,C),speed:e.speed,frame:e.frame})},T={src:e,dest:c,halt:o.abortable,strategy:h,colorspace:f,onProgress:w,stallTimeoutMs:_,width:void 0,height:void 0},E=targetTranscodeDimensions(x);E==null?o.warn(`Cannot determine transcoded video dimensions: fitInside() returned null`,{input:x,fitInside:Settings2.videoPreviewFitInside.valueOrDefault}):(E.width!==x.width||E.height!==x.height)&&(T.width=E.width,T.height=E.height,o.info(`Downsampling transcoded video`,{original:x,output:E}));try{let n=await d.observe(ffmpegTranscode_(T));n.code!==0&&o.throw(compactBlanks([`non-zero ffmpeg exit code `+n.code,n.stderr]).join(`: `)),syncReport().onProgress({path:e.nativePath,from:`videoTranscode()`,type:`file`,state:`note`,details:`Transcode complete`,elapsedMs:roundMs(performance.now()-a)})}catch(n){throw syncReport().onProgress({path:e.nativePath,from:`videoTranscode()`,type:`file`,state:`failed`,details:`Transcode failed: `+errorToS2(n),elapsedMs:roundMs(performance.now()-a)}),o.error(`transcode failed`,{error:n}),n}}return await n.applyWip_({fn_:e=>c(e),skipFsLock:!1,timeoutMs:0,preserveDestOnError:!0}),n}})})()),o.info(`transcode complete`,{src:e,dest:n,elapsedMs:C.elapsedMs}),n}function guessExpectedSize(e,n,r){if(r===`remux`||r===`audio-only`)return e;let a=.3,o=Math.max(1e6,(n??10)*1e5),s=Math.round(e*.3);return Math.min(e,Math.max(o,s))}async function validVideo_(e){return ffmpegValidVideo_(e)}var MimetypeAliases={"video/m2ts":`video/mp2t`,"video/avi":`video/x-msvideo`,"video/vnd.avi":`video/x-msvideo`,"video/msvideo":`video/x-msvideo`};function isMimeTypeSupportedByBrowser(e,n=``){return(isChrome(n)||isFirefox(n)?CurrentBrowserMimetypes:OldBrowserMimetypes).includes(toS(e))}var NonStandardVideoMimeTypes=[`application/mp4`,`application/ogg`];function isVideoMimeType(e){return notBlank(e)&&(e.startsWith(`video/`)||NonStandardVideoMimeTypes.includes(e))}function normalizeMimetype(e){let n=toS(e).toLowerCase();return MimetypeAliases[n]??n}function isSharpMimeType(e){return!blank(e)&&normalizeMimetype(e)in SharpImageFiletypes}function isLibrawMimeType(e){return!blank(e)&&normalizeMimetype(e)in RawImageFiletypes}async function whyAssetFileMimeTypeRejected(e){let n=await readMimeType(e);return blank(n)?`not supported mime type`:isVideoMimeType(n)?await isVideoSupported()?null:`Video codec tools are unavailable. See the Tools section on the Health page (/health).`:isHeifMimeType(n)?await isHeifSupported()?null:`HEIF codec tools are unavailable. See the Tools section on the Health page (/health).`:n in MediaFiletypes?null:`not supported mime type`}function isMimeTypeIncluded(e,n){if(e==null)return!1;for(let r of n)if(r.includes(`*`)){if(RegExp(`^`+r.replace(/\*/g,`.*`)+`$`,`i`).exec(e)!=null)return!0}else if(r.toLowerCase()===e)return!0;return!1}function extractDurationSec(e){if(e!=null&&isVideoMimeType(e?.MIMEType))for(let n of[`duration`,`Duration`,`MediaDuration`,`TrackDuration`]){let r=toGt0f(e[n]);if(r!=null)return r}}function extractDurationMs(e){return mapGt0f(extractDurationSec(e),e=>Math.round(e*1e3))}var import_exiftool_vendored21=require("exiftool-vendored"),import_fast_xml_parser=require("fast-xml-parser"),logger96=lazy2(()=>mkLogger(`tags.KeywordTags`)),pathSepRe=lazy2(()=>mapNotBlank(Settings2.keywordPathSeparators.valueOrDefault,e=>RegExp(`[${escapeRegExp(e)}]+`,`g`)));later(()=>{Settings2.keywordPathSeparators.watchLater(()=>pathSepRe.unset())});function keywordToPath(e){let n=pathSepRe();return compactBlanks(n==null?[e]:e.split(n))}var delimRe=lazy2(()=>mapNotBlank(Settings2.keywordDelimiters.valueOrDefault,e=>RegExp(`[${escapeRegExp(e)}]+`,`g`)));Settings2.keywordDelimiters.watchLater(()=>delimRe.unset());function splitKeyword(e){let n=delimRe();return n==null?[e]:compactBlanks(e.split(n))}function splitKeywords(e){return e==null||e instanceof import_exiftool_vendored21.BinaryField?[]:compactBlanks(Array.isArray(e)?flatten(e.map(splitKeywords)):splitKeyword(e))}function catToS(e){return e==null?[]:isString(e)?blank(e)?[]:[[e]]:flatten(toA(e.Category).map(catToS).map(n=>n.map(n=>compact([e._,...n]))))}var BlankCategoryRE=/^\(?none\)?$/i;function parseCategories(e){if(!(blank(e)||BlankCategoryRE.exec(e)!=null))try{return flatten(toA(new import_fast_xml_parser.XMLParser({textNodeName:`_`,parseTagValue:!1}).parse(e)?.Categories?.Category).map(catToS))}catch(n){logger96().warn(`parseCategories() failed:`,{error:n,s:e});return}}function isKeywordStruct(e){return Array.isArray(e)&&e.every(isKeywordStruct)||e!=null&&isString(e.Keyword)&&(e.Children==null||Array.isArray(e.Children)&&e.Children.every(isKeywordStruct))}function parseKeywordStruct(e){if(e==null)return[];if(Array.isArray(e)&&e.every(isKeywordStruct))return flatMap(e,parseKeywordStruct);if(blank(e.Keyword))return[];let n=toA(e.Children);return isEmpty(n)?[[e.Keyword]]:flatMap(n,parseKeywordStruct).map(n=>[e.Keyword,...n])}function rawTagKeywords(e){let n=[];if(e!=null){let r=[...Settings2.keywordTags.values];if(r.includes(`Categories`)){remove(r,`Categories`);let a=parseCategories(e.Categories);a!=null&&n.push(...a)}for(let a of r){let r=pluckDeep(e,a)?.value;blank(r)||(isKeywordStruct(r)?n.push(...parseKeywordStruct(r)):n.push(...Array.isArray(r)?r:splitKeywords(r)))}}return logger96().tap({msg:`rawTagKeywords()`,result:compactBlankish(uniq(n)),meta:{t:e==null?void 0:pick(e,...Settings2.keywordTags.values)}})}var TagSep=``,TagSepRe=RegExp(`[/`+TagSep+`]`,`g`);function tagRefToS(e){return toS(isString(e)?e:e?.name).normalize()}function tagPathToStringArray(e){return compact(toA(e).map(tagRefToS))}function joinTagPath(e,n=TagSep){return tagPathToStringArray(e).map(e=>replaceAll(e,n,``)).join(n)+(n===TagSep?n:``)}function splitTagPath(e,n=TagSep){return toS(e).split(n).filter(notBlank)}function normalizeTagPath(e){return joinTagPath(splitTagPath(e))}function uniqTagPaths(e){return uniqBy(toA(e),e=>isEmpty(e)?void 0:joinTagPath(e))}function tagPathToLowerStr(e){return tagPathToStringArray(e).join(TagSep).toLowerCase()}function tagPathEql(e,n){return e!=null&&n!=null&&tagPathToLowerStr(e)===tagPathToLowerStr(n)}function tagDiff(e,n){let r=new Set(compact(n).map(e=>tagPathToLowerStr(e)));return compact(e).filter(e=>!r.has(tagPathToLowerStr(e)))}function tagPathsInclude(e,n){let r=tagPathToLowerStr(e);return n.some(e=>r===tagPathToLowerStr(e))}function tagPathLeaf(e){return blank(e)?void 0:Array.isArray(e)?tagRefToS(last(e)):last(splitTagPath(e))}function leafIsExcluded(e,n){return mapOr(tagPathLeaf(e),e=>includesIgnoreCase(n,e),()=>!1)}function isTagPathDescendant(e,n){if(isEmpty(e)||isEmpty(n)||e.length>n.length)return!1;let r=tagPathToStringArray(n);return tagPathToStringArray(e).every((e,n)=>equalsIgnoreCase(e,r[n]))}function omitAncestorTags(e){if(!Settings2.omitAncestorTags.valueOrDefault)return e;let n=[];for(let r of sortBy(e.filter(isNotEmpty),e=>-e.length))n.some(e=>isTagPathDescendant(r,e))||n.push(r);return sortBy(n,n=>e.indexOf(n))}function extFilter(e){return n=>Settings2.respectFileExtensions.valueOrDefault?isExtType(n?.ext,e):null}var isBrowserExtension=extFilter(ExtTypes.SupportedByCurrentBrowser),isVideoExtension=extFilter(ExtTypes.Video),isAssetFileExtension=extFilter(ExtTypes.Media);function mkTagFilter(e){return async n=>{let r=await readRawTags(n);return r==null?!1:e(r)??!1}}async function notDimensionsTooSmall(e){if(!gt0(Settings2.minVideoDimension.valueOrDefault)&&!gt0(Settings2.minImageDimension.valueOrDefault))return null;let n=await readMimeType(e);if(n==null||!n.startsWith(`image/`)&&!n.startsWith(`video/`))return!1;let r=n.startsWith(`video/`)?Settings2.minVideoDimension.valueOrDefault:Settings2.minImageDimension.valueOrDefault;if(!gt0(r))return null;let a=await extractSizeInfoFromFile(e);return a==null?!1:(gte(a.ImageWidth,r)&>e(a.ImageHeight,r))??!1}async function notVideoTooShort(e){if(!gt0(Settings2.minVideoDurationSec.valueOrDefault))return null;let n=await readMimeType(e);return n==null?!1:isVideoMimeType(n)?gte(extractDurationSec(await readRawTags(e)),Settings2.minVideoDurationSec.valueOrDefault):null}async function notVideoTooLong(e){if(!gt0(Settings2.maxVideoDurationSec.valueOrDefault))return null;let n=await readMimeType(e);return n==null?!1:isVideoMimeType(n)?lte(extractDurationSec(await readRawTags(e)),Settings2.maxVideoDurationSec.valueOrDefault):null}async function notMissingMimeType(e){return!blank(await readMimeType(e))}async function notRejectedRating(e){if(blank(Settings2.rejectRating.valueOrDefault))return null;let n=toInt((await readTags(e))?.Rating);return n==null||!Settings2.rejectRating.test(n)}async function notExcludedKeyword(e){return Settings2.keywordBlocklist.values.length===0?null:rawTagKeywords(await readTags(e)).every(e=>leafIsExcluded(e,Settings2.keywordBlocklist.values)!==!0)}var hasBrowserImgMimeType=mkTagFilter(e=>includes([`image/jpeg`,`image/png`],toS(e.MIMEType)));async function notMissingMakeAndModelTags(e){if(!Settings2.requireMakeModel.valueOrDefault)return null;let n=await readRawTags(e);return n==null||blank(n.MIMEType)?null:n.MIMEType.startsWith(`image/`)?n!=null&¬Blank(n.Make)&¬Blank(n.Model):null}async function notFileMissing(e){return e instanceof DirectoryEntry&&e.hasStats()?!0:isBaseFile(e)?e.exists():exists(e.nativePath)}async function notFileTooSmall(e){let n=Settings2.minAssetFileSizeBytes.valueOrDefault;return n<=0?null:gte(await e.size(),n)}async function notFileTooBig(e){let n=Settings2.maxAssetFileSizeBytes.valueOrDefault;return n<=0?null:lte(await e.size(),n)}function fileNameFiltersFor(e){return[{isSupportedFileExtension:isAssetFileExtension},...excludedFilePredicates(e)]}var FileStatFilters=[{notFileMissing},{notFileTooSmall,notFileTooBig}];function whyRejectFileByName(e){return Predicates.whyRejected(e,...fileNameFiltersFor(e))}function whyRejectFileByStat(e){return Predicates.whyRejected(e,...FileStatFilters)}function simpleFileFiltersFor(e){return[...fileNameFiltersFor(e),...FileStatFilters]}function expensiveFileFiltersFor(e){return[...simpleFileFiltersFor(e),{notMissingMimeType},{supportedMimeType:whyAssetFileMimeTypeRejected},{notMissingMakeAndModelTags},{notDimensionsTooSmall},{notVideoTooShort},{notVideoTooLong},{notRejectedRating},{notExcludedKeyword}]}async function whyRejectFile(e,n){return await Predicates.whyRejected(e,...n??expensiveFileFiltersFor(e))}var PushProgressObserver=class{constructor(e,n){this.context=e,this.total=n,this.#t=!1,this.#e=0}context;total;#e;#t;toJSON(){}incrProgress(e=1){return this.#e+=e,this.#n()}onProgress(e){return this.#e=e??this.#e+1,this.#n()}#n(){return gte(this.#e,this.total)&&(this.#t=!0),this.#t===!0?this.#r():this.emit()}completed(){this.#t=!0,this.#e=this.total,this.#r()}#r=()=>{this.emit.reset(),ProgressWatchdog.instance.progressEvent({...this.context,pct:pct(this.#e,this.total),done:this.#t})};emit=trailingThrottle({minDelayMs:100,fn:this.#r})},ForceContextKeysList=[`forceSync`,`forceFilters`,`forceCheckLibraryCopy`,`skipPreviews`,`forceRebuildPreviews`,`skipAssetTagging`,`recountAllTags`,`skipAssetRepair`],ForceContextKeys=strEnum(...ForceContextKeysList);function forceContextOrSetting(e){let n={...fromEntries(ForceContextKeys.values.map(n=>[n,e?.[n]??isTrue(Settings2[n]?.valueOrDefault)])),...pick(e??{},`retries`,`halt`,`path`,`scanGeneration`)};return n.retries??=0,n.halt??=new Abortable,n}var ReducerNames=strEnum(`fit`,`sq`);function fitPlanRung(e){let n=Math.max(e.outputSize.width,e.outputSize.height);return{reducer:ReducerNames.fit,role:e.role,outputSize:e.outputSize,longEdge:n,key:`fit:${n}`,suffix:`fit-${n}.jpg`}}function squarePlanRung(e){return{reducer:ReducerNames.sq,role:`thumbnail`,outputSize:{width:e,height:e},longEdge:e,key:`sq:${e}`,suffix:`sq-${e}.jpg`}}function previewPlan(e){if(blank(e.mimetype))throw Error(`previewPlan(): mimetype must not be empty`);let n=previewLadder(e).map(fitPlanRung),r=Math.min(e.dim.width,e.dim.height),a=thumbnailWidthsForPixelWaste(e.previewPixelWastePct,{maxThumbnailLongEdge:e.maxThumbnailLongEdge,maxOutputLongEdge:r}).map(squarePlanRung),o=[...n,...a];return{sourceSize:e.dim,mimetype:e.mimetype,fit:n,sq:a,all:o}}function previewPlanForCurrentSettings(e){return previewPlan({...e,fitInside:previewFitInsideForMimeType(e.mimetype),maxThumbnailLongEdge:PreviewsSettings.maxThumbnailLongEdge.valueOrDefault,previewPixelWastePct:PreviewsSettings.previewPixelWastePct.valueOrDefault})}var import_node_util16=require("node:util");function fitInside(e,n){return fitRatioInside(e.width/e.height,n)}function fitRatioInside(e,n){if(e>=n.width/n.height){let r=n.width;return{width:r,height:Math.round(r/e)}}{let r=n.height;return{width:Math.round(r*e),height:r}}}var SharpFits=strEnum(`cover`,`contain`,`fill`,`inside`,`outside`),Square;(e=>{let n=lazy2(()=>mkLogger(`img.Reducers.Square`));e.name=ReducerNames.sq,e.fit=`cover`;function r(e,r){let a=lteBoth(e,r)?{...e,fit:SharpFits.cover}:void 0;return n().tap({msg:`reduce()`,result:a,meta:{max:e,input:pick(r,`width`,`height`,`nativePath`)}})}e.reduce=r})(Square||={});var Fit;(e=>{let n=lazy2(()=>mkLogger(`img.Reducers.Fit`));e.name=ReducerNames.fit,e.fit=`inside`;function r(e,r){if(ltBoth(r,e))n().trace(`reduce(): input ${fmtDim(r)} is too small for ${fmtDim(e)}`);else return fitInside(r,e)}e.reduce=r})(Fit||={});var ImageSize=class e{constructor(e,n,r,a){this.name=e,this.maxWidth=n,this.maxHeight=r,this.reducer=a,this.max={width:n,height:r}}name;maxWidth;maxHeight;reducer;static#e(n){return new e(`s${n}`,n,n,Square)}static sq(e){return thumbnailWidthsForPixelWaste(PreviewsSettings.previewPixelWastePct.valueOrDefault,{maxThumbnailLongEdge:PreviewsSettings.maxThumbnailLongEdge.valueOrDefault,maxOutputLongEdge:e==null?void 0:Math.min(e.width,e.height)}).map(this.#e)}static largestSq(e){return greatestBy(this.sq(e),e=>e.megapixels())}static all(){return this.sq()}static S720=e.#e(720);static S120=e.#e(120);static S60=e.#e(60);max;[import_node_util16.inspect.custom](){return{ctor:`ImageSize`,name:this.name+` (`+this.reducer.name+`)`,maxDim:this.maxWidth+`×`+this.maxHeight,maxMP:this.megapixels()}}get maxPixels(){return this.maxWidth*this.maxHeight}megapixels=defer(()=>megapixels(this.maxPixels));outputSize(e){return this.reducer.reduce(this.max,e)}toString(){return this.name}},logger97=lazy2(()=>mkLogger(`img.includePreviewTags`));function withoutEncodingDamagedStrings(e){let n={...e};for(let[e,r]of entries(n))isString(r)&&hasEncodingCorruption(r)&&(logger97().info(`not copying encoding-damaged preview metadata`,{key:e,value:r}),delete n[e]);return n}async function includePreviewTags_(e,n){!1===Settings2.includePreviewTags.valueOrDefault||Settings2.includedPreviewTags.isEmpty()||isEmpty(n)||(logger97().info(`Re-adding metadata to previews...`),await timeExcludingNested({name:`img.includePreviewTags`,thunk:async()=>{let r=withoutEncodingDamagedStrings(pick(await readTags(e),...Settings2.includedPreviewTags.values)),a=r?.capturedAt;a!=null&&(delete r.capturedAt,assignFields(r,a.asExifTag()));let o=r?.exposureSettings;o!=null&&(delete r.exposureSettings,r.FocalLength=o.focalLength,r.FNumber=o.aperture,r.ExposureTime=o.shutterSpeed,r.ISO=o.iso),Settings2.includedPreviewTags.has(`Source`)&&(r.Source=e.nativePath),isEmptyObj(r)?logger97().warn(`not adding tags to previews: no values for tags in source file`,{src:e,includedPreviewTags:Settings2.includedPreviewTags.values}):(logger97().info(`Overwriting preview tags...`,{src:e,writeTags:r}),await excludeWaitFromEnclosingTimer(()=>Promise.all(n.map(e=>overwriteTags_(e,r)))))}}))}function resizePreview(e,n,r){let a=Math.max(n.width,n.height);return r.resize({...n,width:a,height:a,fit:e.fit,withoutEnlargement:!0})}function writePreviewJpeg({path:e,sharp:n,outputSize:r}){return(dmegapixels(r)<2||Settings2.previewSharpen.valueOrDefault)&&(n=n.sharpen()),n.jpeg(sharpRenderOptions()).toFile(e)}function canIncludeKnownInputDim({mimetype:e,nativePath:n,libraryDir:r,libraryOriginalsDir:a}){if(!isMimeTypeSupportedByBrowser(e))return!1;let o=PosixFile.for(n);return PreviewsSettings.previewOriginalDirectly.valueOrDefault??(o.isDescendantOf(a)||o.isDescendantOf(r))}var import_sharp5=__toESM(require("sharp")),import_exiftool_vendored22=require("exiftool-vendored");function isBinaryField(e){return e instanceof import_exiftool_vendored22.BinaryField||e!=null&&isObject(e)&>0(e.bytes)&&`rawValue`in e}var import_sharp4=__toESM(require("sharp")),import_sharp3=__toESM(require("sharp")),logger98=lazy2(()=>mkLogger(`img.SharpTrim`));async function safeTrim(e,n={}){let r={background:`black`,threshold:4,maxTrimPct:Settings2.maxThumbTrimPct.valueOrDefault,trimAliasPixels:Settings2.thumbTrimAliasPixels.valueOrDefault,...n};if(r.maxTrimPct<0||r.maxTrimPct>100)throw Error(`maxTrimPct must be 0-100, got ${r.maxTrimPct}`);if(r.maxTrimPct===0)return logger98().tap({msg:`Trim skipped due to maxTrimPct=0`,result:{sharp:e,maxReductionRatio:0,trimApplied:!1,skipReason:`maxTrimPct is set to 0`}});let a=r.maxTrimPct/100;try{let n=typeof e==`object`&&`metadata`in e?e:(0,import_sharp3.default)(e,{failOn:Settings2.imageFailOn.valueOrDefault}),o=await(await sharpClone(n)).metadata(),s={width:o.width,height:o.height};if(!isDimensions(s))throw Error(`Cannot determine original image dimensions`);let c=n.clone().trim({background:r.background,threshold:r.threshold}),l=await(await sharpClone(c)).metadata(),u={width:l.width,height:l.height};if(!isDimensions(u))throw Error(`Cannot determine trimmed image dimensions`);let d=1-u.width/s.width,f=1-u.height/s.height,h=Math.max(d,f);if(h>a)return logger98().info(`Trim skipped: would reduce dimensions too much`,{maxReductionRatio:h,maxTrimRatio:a,maxTrimPct:r.maxTrimPct,widthReductionRatio:d,heightReductionRatio:f,originalDimensions:s,trimmedDimensions:u}),logger98().tap({msg:`Trim skipped due to safety limits`,result:{sharp:n,originalDimensions:s,trimmedDimensions:s,maxReductionRatio:0,trimApplied:!1,skipReason:`Max reduction ${(h*100).toFixed(1)}% exceeds limit ${r.maxTrimPct.toFixed(1)}%`}});let _=c,y=u;if(r.trimAliasPixels&&r.trimAliasPixels>0){let e=s.width>u.width,n=s.height>u.height;if(e||n){let a={left:e?r.trimAliasPixels:0,top:n?r.trimAliasPixels:0,width:u.width-(e?r.trimAliasPixels*2:0),height:u.height-(n?r.trimAliasPixels*2:0)};a.width>0&&a.height>0?(_=(await sharpClone(c)).extract(a),y={width:a.width,height:a.height},logger98().info(`Applied additional alias pixel trimming`,{trimAliasPixels:r.trimAliasPixels,widthTrimmed:e,heightTrimmed:n,extractRegion:a,trimmedDimensions:u,finalDimensions:y})):logger98().warn(`Skipped alias pixel trimming - would result in invalid dimensions`,{trimAliasPixels:r.trimAliasPixels,extractRegion:a,trimmedDimensions:u})}else logger98().debug(`Skipped alias pixel trimming - no dimensions were trimmed`,{trimAliasPixels:r.trimAliasPixels,originalDimensions:s,trimmedDimensions:u})}return logger98().tap({msg:`Trim applied successfully`,result:{sharp:_,originalDimensions:s,trimmedDimensions:y,maxReductionRatio:h,trimApplied:!0}})}catch(e){return logger98().throw(`safeTrim failed`,{error:e,options:r})}}async function removeLetterbox(e,n=10){return safeTrim(typeof e==`object`&&`metadata`in e?e:(0,import_sharp3.default)(e),{background:`black`,threshold:n,maxTrimPct:Settings2.maxThumbTrimPct.valueOrDefault,trimAliasPixels:Settings2.thumbTrimAliasPixels.valueOrDefault})}var logger99=defer(()=>mkLogger(`img.EmbeddedImages`)),embeddedImageCache=new Cache({name:`EmbeddedImages`,maxSize:512,...metadataCacheOptions(),timeoutMs:Settings2.taskTimeoutMs.valueOrDefault});isTest()&&ee().on(`clearCache`,()=>{logger99().debug(`Clearing embeddedImageCache on clearCache event`),embeddedImageCache.clear()});async function imgFromExif_(e,n,r,a,o){let s=n?.[r];if(!isBinaryField(s))return;let c=extractRotation(n)??0,l=[];try{let n=await extractImageForThumbs_(e,r),s=(0,import_sharp4.default)(n.nativePath,{failOn:Settings2.imageFailOn.valueOrDefault}).removeAlpha().rotate(c),u=await s.metadata(),d=map2Gt0(u.width,u.height,(e,n)=>maybeDimSwap({width:e,height:n},c));if(!isDimensions(d)){l.push(`REJECTED: ${r} has invalid dimensions`),logger99().debug(`imgFromExif(`+e+`, `+r+`): rejecting, invalid dimensions`,{metadata:u,width:u.width,height:u.height});return}let f=.1,h=aspectRatio(d),_=a!=null&&h!=null&&!closeTo(a,h,f);if(_){let u=Settings2.maxThumbTrimPct.valueOrDefault/100,d=h/(1-u),_=h<a&&d>=a*.9;if(_){logger99().debug(`imgFromExif(`+e+`, `+r+`): aspect ratio mismatch, attempting trim`,{fileAspectRatio:a,renderedAspectRatio:h,tolerance:f,maxTrimRatio:u,maxPossibleAspectRatio:d,couldTrimFixAspectRatio:_});try{let e=await removeLetterbox(s);if(e.trimApplied&&e.trimmedDimensions){let s=aspectRatio(e.trimmedDimensions);if(s!=null&&closeTo(a,s,f)){if(o==null||lteBoth(o,e.trimmedDimensions))return l.push(`SUCCESS: ${r} fixed by trimming (${e.trimmedDimensions.width}\xD7${e.trimmedDimensions.height})`),{sharp:e.sharp,rotation:c,file:PosixFile.for(n),dimensions:e.trimmedDimensions,diagnostics:l};l.push(`REJECTED: ${r} trimmed dimensions too small for minDim`);return}l.push(`REJECTED: ${r} trimming didn't fix aspect ratio (${s?.toFixed(2)} vs ${a?.toFixed(2)})`)}else l.push(`REJECTED: ${r} trimming not applied (${e.skipReason})`)}catch(e){l.push(`REJECTED: ${r} trimming failed (${e.message})`)}}else logger99().debug(`imgFromExif(`+e+`, `+r+`): NOT attempting trim`,{fileAspectRatio:a,renderedAspectRatio:h,maxTrimRatio:u,maxPossibleAspectRatio:d,couldTrimFixAspectRatio:_,check1:h<a,check2:d>=a*.9});l.push(`REJECTED: ${r} aspect ratio mismatch (${h?.toFixed(2)} vs ${a?.toFixed(2)})`);return}let y=o==null||lteBoth(o,d),x=a==null||h==null||closeTo(a,h,f);if(logger99().debug(`imgFromExif(`+e+`, `+r+`)`,{valid:y,minDim:o,fileAspectRatio:a,renderedAspectRatio:h,dim:d,sourceDimensions:{width:u.width,height:u.height},rotation:c,tolerance:f,aspectRatioMatch:x,hasAspectRatioMismatch:_}),y)return l.push(`SUCCESS: ${r} extracted (${d.width}\xD7${d.height})`),{sharp:s,rotation:c,file:PosixFile.for(n),dimensions:d,diagnostics:l};l.push(`REJECTED: ${r} dimensions too small for minDim`);return}catch(n){l.push(`ERROR: ${r} extraction failed (${n.message})`),logger99().info(`imgFromExif(): failed to read image from EXIF tag `+r,{nativePath:e.nativePath,error:n});return}}async function extractImageForThumbs_(e,n){let r=n.toLowerCase().endsWith(`tiff`)?`.tiff`:`.jpg`,a=`${e.nativePath}:${n}`,o=await embeddedImageCache.getOrSet(a,async()=>{try{let a=await tmpImageFile_({src:e,tag:n,ext:r});return await extractBinaryTag(n,e.nativePath,a.nativePath),a}catch(r){return logger99().throw(`Failed to extract embedded `+n+` from `+e.nativePath,{error:r})}},await fileStamp(e));return await o.exists()?o:(logger99().debug(`Cached embedded image file no longer exists, removing from cache and re-extracting`,{file:o.nativePath,tag:n}),embeddedImageCache.delete(a),extractImageForThumbs_(e,n))}async function extractThumbnailWithTrimming(e,n,r,a,o,s){let c=logger99().child(`.extractThumbnailWithTrimming(${String(r)})`),l=[];try{c.debug(`Extracting embedded thumbnail for potential trimming`,{tag:r,targetDim:o,fileAspectRatio:s});let u=await imgFromExif_(e,n,r,s,o);if(u==null){l.push(`FAILED: ${r} could not be extracted`),c.debug(`imgFromExif_ returned null for thumbnail tag`,{tag:r});return}u.diagnostics&&l.push(...u.diagnostics);let d=aspectRatio(u.dimensions),f=s!=null&&d!=null&&Math.abs(d-s)/s<.02;if(!(s!=null&&d!=null&&!f&&Math.abs(d-1)<Math.abs(s-1))){let e=f?`aspect ratios already match closely`:`thumbnail is not more square than original`;return c.info(`Skipping trim: ${e}`,{tag:r,thumbnailAspectRatio:d,fileAspectRatio:s,aspectRatioDiff:s!=null&&d!=null?Math.abs(d-s)/s:null,thumbnailSquareness:d==null?null:Math.abs(d-1),fileSquareness:s==null?null:Math.abs(s-1),aspectRatiosMatch:f}),l.push(`SUCCESS: ${r} used without trimming (${u.dimensions.width}\xD7${u.dimensions.height})`),{sharp:u.sharp,rotation:u.rotation,dimensions:u.dimensions,file:u.file,desc:`embedded:${r}`,sizeInfo:a,mimetype:`image/jpeg`,diagnostics:l}}c.debug(`Thumbnail appears letterboxed, attempting trim`,{tag:r,thumbnailAspectRatio:d,fileAspectRatio:s,aspectRatioDiff:Math.abs(d-s)/s,thumbnailSquareness:Math.abs(d-1),fileSquareness:Math.abs(s-1),originalDimensions:u.dimensions});let h=await removeLetterbox(u.sharp);if(!h.trimApplied){c.info(`Vetoing thumbnail: trim could not be safely applied`,{tag:r,skipReason:h.skipReason,maxReductionRatio:h.maxReductionRatio,originalDimensions:h.originalDimensions,thumbnailAspectRatio:d,fileAspectRatio:s});return}c.debug(`Successfully trimmed letterboxing from thumbnail`,{tag:r,originalDimensions:h.originalDimensions,trimmedDimensions:h.trimmedDimensions,maxReductionRatio:h.maxReductionRatio});let _=await tmpImageFile_({src:e,tag:`${r}-trimmed`,ext:`.jpg`});return await h.sharp.toFile(_.nativePath),c.debug(`Saved trimmed thumbnail to new file`,{originalFile:u.file.nativePath,trimmedFile:_.nativePath,dimensions:h.trimmedDimensions}),l.push(`SUCCESS: ${r} trimmed (${h.trimmedDimensions?.width}\xD7${h.trimmedDimensions?.height})`),{sharp:h.sharp,rotation:u.rotation,dimensions:h.trimmedDimensions||u.dimensions,file:_,desc:`embedded:trimmed:${r}`,sizeInfo:a,mimetype:`image/jpeg`,diagnostics:l}}catch(e){l.push(`ERROR: ${r} trimming failed (${e.message})`),c.debug(`Failed to extract and trim embedded thumbnail`,{tag:r,error:e.message});return}}var import_promises29=require("node:stream/promises"),logger100=lazy2(()=>mkLogger(`img.libraw`));async function raw2tiff_(e){let n=await rawDecodeMode_(e);return readableToFile_({src:e,desc:`dcraw-`+n,suffix:`.tiff`,f:r=>dcraw_emu_(e,r,n)})}var TiffOutput=[`-T`],WriteToStdout=[`-Z`,`-`],Colorspace=[`-o`,`1`],IgnoreOrientation=[`-t`,`0`,`-j`];function rawDecodeModeForDimensions(e){let n=previewLadder({dim:e,canIncludeInputDim:!1,fitInside:Settings2.photoPreviewFitInside.valueOrDefault,maxThumbnailLongEdge:Settings2.maxThumbnailLongEdge.valueOrDefault,previewPixelWastePct:Settings2.previewPixelWastePct.valueOrDefault})[0]?.outputSize;return n!=null&&4*dmegapixels(n)<dmegapixels(e)?`half`:`full`}async function rawDecodeMode_(e){let n=await dimensions(e);return n==null?logger100().throw(`Cannot decode `+e+`: no EXIF dimensions.`+DoNotSendErrorFlag+NonRetriableErrorFlag):rawDecodeModeForDimensions(n)}async function readDecoderStderrLines(e,n){let r=new LineReader({trimEnd:!0});r.on(`data`,e=>n(e));try{await(0,import_promises29.pipeline)(e,r)}catch(e){return toWrappedError(e,{fatal:!1})}}async function dcraw_emu_(e,n,r){r??=await rawDecodeMode_(e);let a=r===`half`?[`-h`]:[];r===`half`&&logger100().debug(`Large original source: using -h`);let o=await dcrawEmuNativePath_(),s=[...TiffOutput,...WriteToStdout,...Colorspace,...a,...IgnoreOrientation,...Settings2.dcrawEmuArgs.values,e.nativePath],c={encoding:`buffer`,timeout:Settings2.taskTimeoutMs.valueOrDefault,maxBuffer:250*MB};logger100().debug(`dcraw_emu()`,{cmd:o,args:s,opts:c});let l=execFile2(o,s,void 0,c),u=[],d=[];function f(n){let r=isError(n)?errorToS2(n):toS(n),a=classifyValidationError(r);if(a===`blocked`){logger100().warn(`dcraw_emu(): error`,{file:e,msg:r});let a=isError(n)?n:toWrappedError(r,{fatal:!1});u.push(a)}else logger100().log(a===`allowed`?`info`:`warn`,`dcraw_emu(): warning`,{file:e,msg:r,validationErrorClass:a}),d.push(r)}let h=new Latch,_=new Latch;l.on(`error`,f),(async()=>{let n=await readDecoderStderrLines(l.stderr,f);n!=null&&(logger100().warn(`dcraw_emu(): could not read stderr`,{file:e,error:n}),u.push(n)),h.resolve()})(),l.on(`exit`,()=>_.resolve()),l.on(`close`,()=>_.resolve());try{if(await n.writeStream_(l.stdout),await Promise.race([Promise.all([h,_]),delay(ShortCommandTimeoutMs)]),isNotEmpty(u))throw new WrappedError(`Failed to convert RAW image `+e,{causes:u,path:e.nativePath});let{exitCode:r,signalCode:a}=l,o=!await n.clear().isNonEmptyFile();if(o||r!==0||a!=null)throw new WrappedError(`Failed to convert RAW image `+e+`: dcraw_emu `+(o?`wrote no output`:`wrote partial output before failing`),{causes:d,path:e.nativePath,doNotSend:d.some(isCorruptMediaError)?!0:void 0,meta:{exitCode:r,signalCode:a}});return d}finally{endProcess(l)}}var logger101=lazy2(()=>mkLogger(`img.SharpReadable`)),MIN_DIM_BUFFER_FACTOR=1.2,PREVIEW_SIZE_FACTOR=.9;async function orientedDimensions_(e,n){let r=await(0,import_sharp5.default)(e.nativePath).metadata();if(!gt0(r.width)||!gt0(r.height))throw Error(`Cannot read render source dimensions from `+e);return maybeDimSwap({width:r.width,height:r.height},n)}var SharpReadable=class{#e;diagnostics=[];requestId=Math.random().toString(36).substring(2,9);src;minDim;skipEmbedded;heif2img;constructor(e){setupSharp(),this.src=e.src,this.minDim=e.minDim,this.skipEmbedded=e.skipEmbedded,this.heif2img=e.heif2img??heif2img_,this.#e=logger101().child(`(${this.src.nativePath}:${this.requestId})`),this.diagnostics.push(`Request ID: ${this.requestId}, minDim: ${this.minDim?`${this.minDim.width}\xD7${this.minDim.height}`:`unset`}`)}mimetype_=defer(async()=>{let e=await readMimeType(this.src);return blank(e)?this.#e.throw(`blank mimetype`,{retriable:!1,doNotSend:!0}):e});sizeInfo_=defer(async()=>await extractSizeInfoFromFile(this.src)??this.#e.throw(`blank sizeInfo`,{retriable:!1,doNotSend:!0}));async sharp_(){return(await this.sharpDetails_()).sharp.clone()}async sharpUnrotated_(){let e=await this.sharpDetails_();return e.unrotated==null?{sharp:e.sharp.clone(),orient:e=>e}:{...e.unrotated,sharp:e.unrotated.sharp.clone()}}async sharpFile_(){return(await this.sharpDetails_()).file}async sharpDetails_(){try{return await this.#t()}catch(e){return this.#e.throw(`Failed to render `+this.src,{error:e,retriable:isTransientRenderError(e),doNotSend:!0})}}[Symbol.dispose](){this.#t.unset()}async renderDimensions_(){return(await this.sharpDetails_()).dimensions}#t=lazy2(async()=>{let e=await this.mimetype_(),n=await this.sizeInfo_(),r=await this.resultFromEmbeddedBinaryField_();if(r!=null)return this.#e.tap({msg:`sharp from embedded image`,result:r});if(isSharpMimeType(e))return this.#e.tap({msg:`sharp can directly read this file`,result:{desc:`sharp:direct`,...orientedSharp(this.src,n.rotation),rotation:n.rotation,file:this.src,mimetype:e,sizeInfo:n,dimensions:n.dimensions}});if(isHeifMimeType(e)){let r=this.minDim==null?void 0:Math.max(this.minDim.width,this.minDim.height);if(within(0,HEIF_THUMBNAIL_MAX_SIZE,r)){let a=await this.#e.tapAsync_({msg:`sharp from heif thumbnail`,result:heif2Thumb(this.src,r),timeoutMs:Settings2.taskTimeoutMs.valueOrDefault});if(a!=null)return this.#e.tap({msg:`sharp from heif thumbnail`,result:{desc:`heif-thumb`,sharp:(0,import_sharp5.default)(a.nativePath,{failOn:Settings2.imageFailOn.valueOrDefault}),rotation:0,file:a,mimetype:e,sizeInfo:n,dimensions:await orientedDimensions_(a,0)}})}let a=await this.#e.tapAsync_({level:`info`,msg:`sharp from heif fullsize`,result:this.heif2img(this.src)});if(a!=null)return this.#e.tap({msg:`sharp from heif fullsize`,level:`info`,result:{desc:`heif`,...orientedSharp(a,isMac?n.rotation:0),rotation:0,file:a,mimetype:e,sizeInfo:n,dimensions:await orientedDimensions_(a,isMac?n.rotation:0)}})}let a,o;if(isLibrawMimeType(e))try{let r=await raw2tiff_(this.src);if(r!=null)return this.#e.tap({msg:`convert raw to TIFF`,result:{desc:`raw`,...orientedSharp(r,n.rotation),rotation:n.rotation,file:r,mimetype:e,sizeInfo:n,dimensions:await orientedDimensions_(r,n.rotation)}})}catch(e){this.#e.warn(`convert raw to TIFF failed`,{error:e}),a=e?.message??String(e),o=e}let s,c;if(isVideoMimeType(e)&&await isVideoSupported())try{let r=await extractVideoFrame_(this.src);if(r!=null)return this.#e.tap({msg:`extracting video frame`,result:{desc:`video`,sharp:(0,import_sharp5.default)(r.nativePath,{failOn:Settings2.imageFailOn.valueOrDefault}),rotation:0,file:r,mimetype:e,sizeInfo:n,dimensions:await orientedDimensions_(r,0)}})}catch(e){this.#e.warn(`video frame extraction failed`,{error:e}),s=e?.message??String(e),c=e}let l=s==null?a==null?`Failed to render with any strategy`:`Failed to render raw: `+a:`Failed to render video: `+s;return this.#e.throw(l,{error:c??o,mimetype:e,sizeInfo:n,src:this.src.nativePath,retriable:isTransientRenderError(c??o),doNotSend:!0})},2*minuteMs);async whyNotUseEmbeddedBinaryField(){if(this.skipEmbedded===!0)return this.#e.tap({msg:`whyNotUseEmbeddedBinaryField`,result:`this.skipEmbedded == true`});let e=await this.mimetype_();if(isSharpMimeType(e)&&Settings2.skipEmbeddedImageMimeTypes.valueOrDefault.includes(e))return this.#e.tap({msg:`whyNotUseEmbeddedBinaryField`,result:`sharp-supported mimetype in `+Settings2.skipEmbeddedImageMimeTypes.key,meta:{mimetype:e}});if(isSharpMimeType(e)&&this.minDim==null)return this.#e.tap({msg:`whyNotUseEmbeddedBinaryField`,result:`sharp-supported mimetype, and null minDim: must load original`,meta:{mimetype:e}});if(isVideoMimeType(e))return this.#e.tap({msg:`whyNotUseEmbeddedBinaryField`,result:`video file: not using embedded`,meta:{mimetype:e}});let n=await this.sizeInfo_();if(lt(aspectRatio(n.fileDimensions),1))return this.#e.tap({msg:`whyNotUseEmbeddedBinaryField`,result:`rastered portrait aspect ratio: embedded are ineligible`,meta:{sizeInfo:n}});if(orientationRequiresMirroring(n.orientation))return this.#e.tap({msg:`whyNotUseEmbeddedBinaryField`,result:`file is mirrored: embedded are ineligible`,meta:{orientation:n.orientation}})}async resultFromEmbeddedBinaryField_(){let e=performance.now(),n=await this.whyNotUseEmbeddedBinaryField();if(!blank(n)){this.diagnostics.push(`Embedded images skipped: ${n}`);return}this.#e.debug(`Starting readRawTags for embedded preview extraction`);let r,a=0,o=3;for(;a<3;){a++;try{let e=performance.now(),n=await readRawTags(this.src),o=performance.now()-e;if(this.#e.debug(`readRawTags completed`,{durationMs:o,attempt:a,gotResult:n!=null}),n==null){let e=this.src.statSync();if(this.#e.warn(`readRawTags returned null`,{src:this.src.nativePath,mimetype:await this.mimetype_(),fileExists:this.src.existsSync(),fileSize:e?.size,fileModified:e?.mtime,durationMs:o,requestId:this.requestId,minDim:this.minDim,attempt:a,willRetry:a<3}),this.diagnostics.push(`readRawTags returned null after ${o}ms (attempt ${a}/3)`),a<3){await delay(50*a);continue}this.diagnostics.push(`readRawTags failed after ${a} attempts - falling back to raw conversion`);return}r=n;break}catch(n){let r=performance.now()-e;if(this.#e.error(`readRawTags threw error`,{error:n.message,stack:n.stack,src:this.src.nativePath,durationMs:r,attempt:a}),this.diagnostics.push(`readRawTags error after ${r}ms (attempt ${a}): ${n.message}`),a>=3)throw n;await delay(50*a)}}if(r==null){this.diagnostics.push(`Failed to read tags after ${a} attempts`);return}let s=await this.sizeInfo_(),c=s.dimensions,l=this.minDim==null?{width:Math.round(c.width*PREVIEW_SIZE_FACTOR),height:Math.round(c.height*PREVIEW_SIZE_FACTOR)}:{width:this.minDim.width*MIN_DIM_BUFFER_FACTOR,height:this.minDim.height*MIN_DIM_BUFFER_FACTOR};this.#e.debug(`Embedded preview dimension calculation`,{originalMinDim:this.minDim,calculatedDim:l,sidDimensions:c,bufferFactor:MIN_DIM_BUFFER_FACTOR,previewFactor:PREVIEW_SIZE_FACTOR});let u=this.minDim==null?void 0:Math.max(this.minDim.width,this.minDim.height),d=u!=null&&u<100;this.#e.debug(`Embedded preview evaluation`,{originalMinDim:this.minDim,calculatedDim:l,maxRequestedDim:u,useSmallThumbnails:d});let f=[];for(let e of Settings2.embeddedPreviews.values)if(e in r&&isBinaryField(r[e])){let n=r[e],a=n.bytes>51200;this.#e.debug(`Evaluating embedded preview tag`,{tag:e,bytes:n.bytes,isLargeEnough:a,isThumbnail:!1}),this.diagnostics.push(`Found preview tag ${e}: ${n.bytes} bytes ${a?`(large enough)`:`(too small)`}`),a&&f.push({tag:e,bytes:n.bytes,isThumbnail:!1})}if(d){this.diagnostics.push(`Using small thumbnails (maxRequestedDim: ${u}px)`);for(let e of Settings2.embeddedThumbnails.values)if(e in r&&isBinaryField(r[e])){let n=r[e];this.#e.debug(`Evaluating embedded thumbnail tag`,{tag:e,bytes:n.bytes,isThumbnail:!0}),this.diagnostics.push(`Found thumbnail tag ${e}: ${n.bytes} bytes`),f.push({tag:e,bytes:n.bytes,isThumbnail:!0})}}else this.diagnostics.push(`Skipping small thumbnails: `+stringify({maxRequestedDim:u}));sortByInPlace(f,e=>e.bytes),this.#e.debug(`Trying to extract embedded preview from these tags`,{binaryFields:f});for(let e of f){let n=performance.now();try{if(this.#e.debug(`Attempting to extract embedded image`,{tag:e.tag,bytes:e.bytes,isThumbnail:e.isThumbnail,fileAspectRatio:aspectRatio(s.dimensions),targetDim:l,totalCandidates:f.length}),this.diagnostics.push(`Trying ${e.isThumbnail?`thumbnail`:`preview`} tag ${e.tag} (${e.bytes} bytes)`),e.isThumbnail){let a=await extractThumbnailWithTrimming(this.src,r,e.tag,s,l,aspectRatio(s.dimensions));if(a!=null){let r=performance.now()-n;return this.#e.debug(`Successfully extracted thumbnail with smart trimming`,{tag:e.tag,desc:a.desc,dimensions:a.dimensions,durationMs:r}),this.diagnostics.push(...a.diagnostics),this.diagnostics.push(`SUCCESS: ${e.tag} extracted in ${r}ms`),{...a,mimetype:await this.mimetype_()}}{let r=performance.now()-n;this.#e.debug(`extractThumbnailWithTrimming vetoed thumbnail for tag`,{tag:e.tag,durationMs:r}),this.diagnostics.push(`VETOED: ${e.tag} was rejected by smart trimming logic after ${r}ms`)}}else{let a=await imgFromExif_(this.src,r,e.tag,aspectRatio(s.dimensions),l);if(a!=null){let r=performance.now()-n;return this.#e.debug(`Successfully extracted embedded preview`,{tag:e.tag,resultDimensions:a.dimensions,rotation:a.rotation,durationMs:r}),a.diagnostics&&this.diagnostics.push(...a.diagnostics),this.diagnostics.push(`SUCCESS: ${e.tag} extracted in ${r}ms`),{desc:`embedded:`+e.tag,...a,sizeInfo:s,mimetype:await this.mimetype_()}}{let r=performance.now()-n;this.#e.debug(`imgFromExif_ returned null for tag`,{tag:e.tag,durationMs:r}),this.diagnostics.push(`FAILED: ${e.tag} rejected by imgFromExif_ after ${r}ms`)}}}catch(r){let a=performance.now()-n;this.#e.debug(`Failed to extract embedded preview from `+e.tag,{error:r.message,stack:r.stack,durationMs:a}),this.diagnostics.push(`ERROR: ${e.tag} extraction failed after ${a}ms: ${r.message}`)}}let h=performance.now()-e;this.#e.debug(`No valid embedded previews were found`,{totalCandidates:f.length,tags:f.map(e=>e.tag),totalDurationMs:h}),this.diagnostics.push(`No embedded images could be used (tried ${f.length} candidates in ${h}ms)`)}};function isTransientRenderError(e){return isTimeoutError2(e)||isRetriableError(e)===!0}function orientedSharp(e,n){let r=(0,import_sharp5.default)(e.nativePath,{failOn:Settings2.imageFailOn.valueOrDefault});return{sharp:r.clone().rotate(n),unrotated:{sharp:r,orient:e=>e.rotate(n)}}}var import_promises30=require("node:fs/promises"),devnull=isWin?`NUL`:`/dev/null`,logger102=lazy2(()=>mkLogger(`img.jpegtran`));async function validJpeg_(e){if(!Settings2.validateJpegImages.valueOrDefault)return;let n=PosixFile.for(e),r=await jpegtranNativePath_();try{let e=await(0,import_promises30.open)(n.nativePath,`r`);try{await stdoutResult_(r,[`-outfile`,devnull],{stdinFileDescriptor:e.fd,timerName:`proc.jpegtran`,timeoutMs:commandTimeoutMs(),cleanError:cleanValidationError,isIgnorableError:isIgnorableValidationError,isExpectedError:isExpectedValidationError,ignoreExitCode:!1})}finally{await e.close()}}catch(e){throw logger102().warn(`validJpeg caught invalid file`,{file:n,error:e}),new WrappedError(`Invalid JPEG: `+n,{cause:e,path:n.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}}var logger103=lazy2(()=>mkLogger(`img.ValidFile`)),valid=()=>({validity:`valid`}),invalid=e=>({validity:`invalid`,why:e}),unchecked=e=>({validity:`unchecked`,why:e});function fileValidationToS(e){return e.validity===`valid`?`OK`:e.validity.toUpperCase()+`: `+e.why}async function isValidFile(e){return(await validateFile(toNativePath_(e))).validity!==`invalid`}async function throwIfInvalidFile_(e){if(!Settings2.validateJpegImages.valueOrDefault&&!Settings2.validateRawImages.valueOrDefault&&!Settings2.validateVideos.valueOrDefault){logger103().debug(`file validation is disabled for `+e,{validateJpegImages:Settings2.validateJpegImages.valueOrDefault,validateRawImages:Settings2.validateRawImages.valueOrDefault,validateVideos:Settings2.validateVideos.valueOrDefault});return}let n=toNativePath_(e),r=logger103().tap({msg:`validateFile(`+n+`)`,result:await validateFile(n)});r.validity===`invalid`&&logger103().throw(r.why,{path:n,retriable:!1,doNotSend:!0,ignorable:!0})}var cache8=lazy2(()=>new FileCache({name:`img.validFile`,...metadataCacheOptions(),maxSize:256,timeoutMs:Math.max(minuteMs,Settings2.validateVideos.valueOrDefault?5*minuteMs:commandTimeoutMs())})),validateFile=shim({name:`img.validateFile`,cache:cache8,toKey:toNativePath_,stamp:e=>fileStamp(e),impl:async e=>{let n=PosixFile.for(e);if(!await n.isFile()||!await n.isReadable())return invalid(n+` is not a readable file`);if(await n.isEmptyOrMissing())return invalid(n+` is empty`);try{let e=await readMimeType(n);if(e==null)throw Error(`Cannot validate, no mimetype`);if(isVideoMimeType(e)){if(!Settings2.validateVideos.valueOrDefault)return unchecked(Settings2.validateVideos.name+` is false`);logger103().debug(`validating `+n),await validVideo_(n)}else if(e.startsWith(`image/`)){if(e===`image/jpeg`){if(!Settings2.validateJpegImages.valueOrDefault)return unchecked(Settings2.validateJpegImages.name+` is false`);await validJpeg_(n)}else if(!Settings2.validateRawImages.valueOrDefault)return unchecked(Settings2.validateRawImages.name+` is false`);else if(includesIgnoreCase(Settings2.validateMimetypeSkiplist.values,e))return logger103().info(`Skipping validation of `+n+`: validateMimetypeSkiplist matches`,{mime:e}),unchecked(Settings2.validateMimetypeSkiplist.name+` matches `+e);else await(await new SharpReadable({src:n,skipEmbedded:!0}).sharp_()).raw().toBuffer()}else throw Error(`Unsupported mimetype `+stringify(e));return valid()}catch(e){return invalid(cleanValidationError(String(e)))}}});function canIncludeInputDim(e,n){return canIncludeKnownInputDim({mimetype:n,nativePath:e.nativePath,libraryDir:libraryDirPosixFile(),libraryOriginalsDir:libraryOriginalsDirPosixFile()})}function previewSourceMinDim(e){let n=ImageSize.largestSq(e.dim),r=previewPlanForCurrentSettings(e).fit[0]?.outputSize;return r==null||dmegapixels(r)<n.megapixels()?n.max:r}var AssetPreviewBuilder=class{constructor(e,n,r,a={},o={}){this.ap=e,this.assetFiles=n,this.prior=o,this.logger=mkLogger(`AssetPreviewBuilder(`+e.assetId+`)`),this.ctx=forceContextOrSetting(r),this.assetFiles=sortAssetFilesInPlace(this.assetFiles,a)}ap;assetFiles;prior;logger;ctx;[import_node_util17.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=>pick(e,`id`,`uri`)));let e=[];for(let n of this.assetFiles){let r=PosixFile.forMaybe(await getNativePathFromUriDetails(n));if(r==null)this.logger.info(`skipping: failed to get PosixFile`,{af:n}),e.push(Error(`Cannot get path from URI `+stringify({uri:n.uri,nativePath:knownNativePath(n)})));else{{let e=await whyRejectFile(r);blank(e)||this.logger.info(`skipping: rejected`,{pf:r,whyRejected:e})}try{return await this.#r(r,n)}catch(a){e.push(a),this.logger.warn(`Failed to set shown file to `,{nativePath:r.nativePath,best:n,error:a})}finally{this.ap.parent.clear()}}}return this.logger.throw(`Cannot build previews: none of the files are valid`,{logLevel:`warn`,doNotSend:!0,retriable:!1,files:this.assetFiles.map(e=>knownNativePath(e)??e.uri),causes:e})}async#e(e,n){let r=await e.size(),a=await e.thisOrSidecarMaxMtimeMs(),o=a==null?void 0:Math.floor(a);this.logger.debug(`_build`,{filesize:r,mtime:o,best:n.uri});let{uri:s,width:c,height:l,mimetype:u,sha:d,rotation:f}=n;if(n.assetId==null||n.id==null||s==null||c==null||l==null||u==null||d==null||f==null)return this.logger.throw(`build(): internal error: missing fields for best file `+e,{ignorable:!0,best:n});let h=canIncludeInputDim(e,u),_=previewFitInsideForMimeType(u),y=Settings2.maxThumbnailLongEdge.valueOrDefault,x=Settings2.previewPixelWastePct.valueOrDefault,C={canIncludeInputDim:h,mimetype:u};return{planArgs:C,minDim:previewSourceMinDim({...C,dim:{width:c,height:l}}),stats:r==null||o==null?void 0:{mtime:o,fileSize:r},revision:{assetId:n.assetId,assetFileId:n.id,uri:s,source:{sha:d,width:c,height:l,mimetype:u,rotation:f}},fingerprintFor:e=>previewFingerprint({source:{assetFileId:n.id,sha:d,renderWidth:e.width,renderHeight:e.height,mimetype:u,rotation:f},recipe:{mediaKind:isVideoMimeType(n.mimetype)?`video`:`photo`,canIncludeInputDim:h,fitInside:_,maxThumbnailLongEdge:y,previewPixelWastePct:x,renderPolicyVersion:PreviewRenderPolicyVersion}})}}async#t(e,n,r){let a=await this.ap.existingFiles(),o=await this.ap.previewSetStatus(e,a);if(o.complete)return await this.#n(o.obsolete.map(e=>e.file)),await unlink4(o.inventory.legacySidecars),{render:n,previewFingerprint:r,noop:!0}}async#n(e){for(let n of e)try{await retryOnReject_(()=>n.unlink_(),{maxRetries:3,timeoutMs:statTimeoutMs(),errorIsRetriable:e=>isRetriableError(e)===!0})}catch(e){this.logger.warn(`Failed to prune obsolete preview`,{file:n,error:e})}}async#r(e,n){this.logger.info(`_build(`+e+`)`,{uri:n.uri});let{revision:r,stats:a,planArgs:o,minDim:s,fingerprintFor:c}=await this.#e(e,n),l=this.prior.mtime==null||this.prior.fileSize==null?void 0:{mtime:this.prior.mtime,fileSize:this.prior.fileSize},u=a??l;if(u==null)return this.logger.throw(`build(): missing stat info for best file`,{ignorable:!0,best:n});let d={...r,source:{...r.source,...u}},f=!this.ctx.forceSync&&!this.ctx.forceRebuildPreviews&&previewSourceStatsUnchanged(this.prior,d.source),h=this.prior.renderDimensions;if(f&&h!=null&&this.prior.previewFingerprint===c(h)){let e=await this.#t(previewPlanForCurrentSettings({...o,dim:h}),h,this.prior.previewFingerprint);if(e!=null)return{...d,...e}}if(a==null)return this.logger.throw(`build(): cannot rebuild previews from an unreadable source`,{ignorable:!0,best:n});await throwIfInvalidFile_(e);let _=new SharpReadable({src:e,minDim:s}),y=await _.renderDimensions_(),x=previewPlanForCurrentSettings({...o,dim:y}),C=c(y);if(f&&this.prior.previewFingerprint===C){let e=await this.#t(x,y,C);if(e!=null)return{...d,...e}}let w={...d,render:y,previewFingerprint:C},T=x.fit,E=ImageSize.largestSq(y),D={path:e.nativePath,op:`Building previews`},O=x.all.length,k=new PushProgressObserver(D,O),A=0,j=async()=>{A++,await k.onProgress(A),operationOwner()?.onProgress?.({...D,pct:pct(A,O),step:A})};if(this.logger.debug(`Rebuilding all previews from `+n.uri,{assetId:n.assetId,result:w,plan:x}),await this.ap.parent.mkdirp()==null)throw Error(`build(): Failed to create previews directory, `+this.ap.parent+` for `+n);let M=await this.ap.existingFiles(),N=await _.sharp_(),P=[],F=[],I,R,z=leastBy(T,e=>map(E.outputSize(e.outputSize),()=>dmegapixels(e.outputSize)));{let e=N.clone(),n=y;for(let r of T){let a=performance.now(),{outputSize:o}=r,s=n,c=this.ap.fileForSuffix(r.suffix).wip();e=resizePreview(Fit,o,e),n=o,r===z&&(R=e.clone(),I=o),dmegapixels(o)>=1&&Settings2.includePreviewTags.valueOrDefault&&F.push(c),await writePreviewJpeg({path:c.nativePath,sharp:e,outputSize:o}),await j(),this.logger.debug(`resize(fit) `+fmtDim(s)+` -> `+fmtDim(o)+` in `+roundMs(performance.now()-a)+` ms`),P.push(c)}}{R==null?(this.logger.debug(`square resize(): resorting to `,{sourceSize:y,bestFitForSq:z}),R=N,I=y):this.logger.debug(`square resize(): using to `,{sqDim:I,bestFitForSq:z});let e=!1;for(let n of x.sq){let r=performance.now(),a=I,o=e?{...n.outputSize}:{...n.outputSize,position:Settings2.squareThumbStrategy.valueOrDefault};e=!0,this.logger.debug(`Applying `,{outputSize:o});let s=this.ap.fileForSuffix(n.suffix).wip();R=resizePreview(Square,o,R),I=o,await writePreviewJpeg({path:s.nativePath,sharp:R,outputSize:o}),await j(),P.push(s),this.logger.debug(`resize(`+Square.name+`) `+fmtDim(a)+` -> `+fmtDim(o)+` in `+roundMs(performance.now()-r)+` ms`)}}try{await includePreviewTags_(e,F).catch(n=>{this.logger.warn(`Failed to restore metadata tags into previews for `+e,{error:n})});let n=new Map(M.filter(e=>e.ext===`.jpg`).map(e=>[e.nativePath,e]));for(let e of P){let r=await e.unwip_();n.delete(r.nativePath)}await this.#n(n.values()),this.logger.debug(`Previews unwipped`,{result:w})}catch(n){throw await unlink4(P),new WrappedError(`Failed to create previews from `+e,{cause:n,path:e.nativePath,fatal:!1})}return w}};function id2id(e){if(e!=null){if(isNumber(e))return e;if(`id`in e&&isNumber(e.id))return e.id;if(`assetId`in e&&isNumber(e.assetId))return e.assetId;if(`tagId`in e&&isNumber(e.tagId))return e.tagId}}function toQuery(e,n){let r=n==null?void 0:mergeURLSearchParams(...n),a=toS(e.v);return blank(a)||(r??=new URLSearchParams).append(`v`,a),r}function assetPath(e){return gt0(e)?`/asset/${e}`:void 0}function assetImgLink({assetId:e,reducer:n,longEdge:r,params:a}){return assembleFullPath(`/img/${id2id(e)}/${n}/${toGt0(r)??320}`,toQuery(e,a))}function assetThumbnailImgLink({assetId:e,reducer:n,longEdge:r,params:a}){return assembleFullPath(`/img/${id2id(e)}/thumb/${n}/${toGt0(r)??320}`,toQuery(e,a))}function assetImgActualLink({assetId:e,assetFileId:n,params:r}){return assembleFullPath(`/img/${compact([id2id(e),n]).join(`/`)}/actual`,toQuery(e,r))}function assetVideoLink({assetId:e,assetFileId:n,params:r}){return assembleFullPath(`/video/${id2id(e)}-${n}`,toQuery(e,r))}var epilog=mkLogger(`extractPreviewInfo`),PreviewPathRE=/^(?<assetId>\d+)-(?:(?<reducer>fit|sq)-(?:w(?<legacyWidth>\d+)|(?<dimensions>\d+\s*[x×]\s*\d+)|(?<longEdge>\d+))\.jpg|video\.mp4|info\.json)$/i;function extractPreviewInfo(e,n){let r=n.posixPathFrom(e).replace(/\//g,``),a=PreviewPathRE.exec(r),o=toInt(a?.groups?.assetId),s=ReducerNames.getCI(a?.groups?.reducer),c=parseDimensions(a?.groups?.dimensions),l=c?.width??toInt(a?.groups?.legacyWidth),u=toInt(a?.groups?.longEdge);if(!gt0(o)||s!=null&&!gt0(l??u))epilog.warn(`Failed to extract preview info`,{file:n,previewsRoot:e,normalizedPath:r,assetId:o,reducer:s,width:l,longEdge:u});else return{file:n,assetId:o,reducer:s,width:l,...c==null?{}:{height:c.height},...u==null?{}:{longEdge:u}}}function planRungDownloadable({basename:e,assetId:n,file:r,rung:a}){if(!gt0(n))return;let o=a.outputSize,s=dimToSize(o);return{size:s,basename:`${stripSuffix(e,extname(e))}-${s}${r.ext}`,title:mkDownloadableTitle(r,s,`image`,o),description:`Download ${s}`,details:`(${fmtDim(o)} ${r.ext})`,href:assetImgLink({assetId:n,reducer:ReducerNames.fit,longEdge:a.longEdge})}}async function previewToDownloadable(e,n){if(!gt0(n.assetId))return;let r=await physicalPreviewDimensions(n);if(r==null)return;let a=dimToSize(r),o=stripSuffix(e,extname(e)),s=n.height==null?n.width:void 0;return{size:a,basename:`${o}-${a}${n.file.ext}`,title:mkDownloadableTitle(n.file,a,`image`,r),description:`Download ${a}`,details:`(${fmtDim(r)} ${n.file.ext})`,href:assetImgLink({assetId:n.assetId,reducer:ReducerNames.fit,longEdge:s??Math.max(r.width,r.height)})}}async function physicalPreviewDimensions(e){return gt0(e.width)&>0(e.height)?{width:e.width,height:e.height}:dimensions(e.file)}function mkDownloadableTitle(e,n,r,a){return`Download ${n} ${e.ext} ${r}`+(a==null?``:` (${fmtDim(a)})`)}function inventoryKey(e){if(e.reducer!=null){if(e.longEdge!=null)return`${e.reducer}:${e.longEdge}`;if(e.width!=null)return e.height==null?`${e.reducer}:w${e.width}`:`${e.reducer}:${e.width}x${e.height}`}}function previewSetInventory({previewsRoot:e,files:n}){let r=[],a=[],o=[];for(let s of n){let n=extractPreviewInfo(e,s);if(n!=null){if(n.reducer!=null){let e=inventoryKey(n);r.push({...n,key:e})}else s.ext.toLowerCase()===`.mp4`?a.push(s):s.ext.toLowerCase()===`.json`&&o.push(s)}}return{images:r,videos:a,legacySidecars:o}}function dimensionsEqual(e,n){return e.width===n.width&&e.height===n.height}function isMisaddressed(e,n){return e.reducer===n.reducer?n.height==null?n.width!=null&&e.reducer===`sq`&&e.longEdge===n.width:dimensionsEqual(e.outputSize,n):!1}function previewSetStatus({plan:e,previewsRoot:n,files:r}){let a=previewSetInventory({previewsRoot:n,files:r}),o=[],s=[],c=[],l=new Set;for(let n of e.all){let e=a.images.find(e=>!l.has(e)&&e.key===n.key);if(e!=null){o.push({required:n,actual:e}),l.add(e);continue}s.push(n);let r=a.images.find(e=>!l.has(e)&&isMisaddressed(n,e));r!=null&&(l.add(r),c.push({required:n,actual:r}))}return{complete:s.length===0,present:o,missing:s,misaddressed:c,obsolete:a.images.filter(e=>!l.has(e)),inventory:a}}function assetPreviewPathParts(e){let n=splitEvery(leftPad(e,8,`0`),3);return{dirs:n,basename:n.pop()+`-`}}function longEdgeSuffix(e,n){return`${e}-${n}.jpg`}var AssetPreviews=class{constructor(e,n){this.previewsRoot=e,this.assetId=id2id(n);let{dirs:r,basename:a}=assetPreviewPathParts(this.assetId);this.basename=a,this.parent=e.join(...r)}previewsRoot;assetId;parent;basename;parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles(e=>e.base.startsWith(this.basename))??[]}async previewSetInventory(e){return previewSetInventory({previewsRoot:this.previewsRoot,files:e??await this.existingFiles()})}async previewSetStatus(e,n){return previewSetStatus({plan:e,previewsRoot:this.previewsRoot,files:n??await this.existingFiles()})}async existingJpgs(){return(await this.existingFiles()).filter(e=>e.ext===`.jpg`)}async deleteAll(){let e=await this.existingFiles();for(let n of e)await n.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix(`video.mp4`)}legacyInfoJson(){return this.fileForSuffix(`info.json`)}fileForLongEdge(e,n){return this.fileForSuffix(longEdgeSuffix(e,n))}fileForWidth(e,n){return this.fileForSuffix(e+`-w`+n+`.jpg`)}fileForDimensions(e,n){return this.fileForSuffix(e+`-`+dimensionsToString(n)+`.jpg`)}},Previews=class e{constructor(e){this.root=e}root;static instance=lazy2(()=>(mkLogger(`Previews`).info(`.instance()`,{libraryPreviewsDir:libraryPreviewsDirPosixFile()}),map(libraryPreviewsDirPosixFile(),n=>new e(n))));static instanceRequired(){let n=e.instance();if(n==null)throw Error(`Previews.instance() is not set (no library yet?)`+NoLibraryErrorFlag);return n}apb(e,n,r){return new AssetPreviewBuilder(this.ap(e),n,r,{preferredShas:new Set(r.preferredShas),pinnedUri:r.pinnedUri},r.prior)}ap(e){return new AssetPreviews(this.root,e)}nativePathForLongEdge(e,n,r){let{dirs:a,basename:o}=assetPreviewPathParts(e);return import_node_path59.default.join(this.root.nativePath,...a,o+longEdgeSuffix(n,r))}},buildAssetPreviews_=shim({name:`img.buildAssetPreviews`,impl:e=>Previews.instance().apb(e.assetId,e.assetFiles,e).build_()});function expedite(e){return Settings2.expedite.withValue(!0,e)}function mkExpired(){return Date.now()+AuthSettings.sessionTimeout.valueOrDefault}function wrap3(e,n){try{let r=e();n?.(void 0,r)}catch(e){n?.(e)}}var DbSessionStore=class extends EndableInterval{#e;constructor(e){super({name:`DbSessionStore`,callback:()=>{try{this.cleanup()}catch(e){this.logger.warn(`cleanup() failed`,{error:e})}},intervalMs:5*minuteMs,rank:EndableRanks.first}),this.#e=e}get db(){return this.#e}cleanupStmt=lazy2(()=>this.db.prepare(`DELETE FROM Session WHERE expired <= :now`));cleanup(){this.cleanupStmt().run({now:Date.now()})}getStmt=lazy2(()=>this.db.prepare(`SELECT * FROM Session WHERE sid = :sid AND expired > :now`));get(e,n){wrap3(()=>parseJSON(this.getStmt().get({sid:e,now:Date.now()})?.sess),n)}setStmt=lazy2(()=>this.db.prepare(`INSERT OR REPLACE INTO Session (sid, createdAt, expired, sess) VALUES (:sid, :createdAt, :expired, :sess)`));set(e,n,r){wrap3(()=>this.setStmt().run({sid:e,createdAt:Date.now(),sess:stringify(n),expired:mkExpired()}),r)}delStmt=lazy2(()=>this.db.prepare(`DELETE FROM Session WHERE sid = :sid`));destroy(e,n){wrap3(()=>this.delStmt().run({sid:e}),n)}allStmt=lazy2(()=>this.db.prepare(`SELECT * FROM Session`));all(e){wrap3(()=>{let e={};for(let n of this.allStmt().all())e[n.sid]=parseJSON(n.sess)??{};return e},e)}lengthStmt=lazy2(()=>this.db.prepare(`SELECT count(*) FROM Session`));length(e){wrap3(()=>this.lengthStmt().pluck().get(),e)}clearStmt=lazy2(()=>this.db.prepare(`DELETE FROM Session`));clear(e){wrap3(()=>this.clearStmt().run(),e)}touch(e,n,r){this.set(e,n,r)}async getAsync(e){return new Promise((n,r)=>{this.get(e,(e,a)=>{e==null?n(a):r(e)})})}async setAsync(e,n){return new Promise((r,a)=>{this.set(e,n,e=>{e==null?r():a(e)})})}async clearAsync(){return new Promise((e,n)=>{this.clear(r=>{r==null?e():n(r)})})}async lengthAsync(){return new Promise((e,n)=>{this.length((r,a)=>{r==null?e(a??0):n(r)})})}async destroyAsync(e){return new Promise((n,r)=>{this.destroy(e,e=>{e==null?n():r(e)})})}async allAsync(){return new Promise((e,n)=>{this.all((r,a)=>{r==null?e(a):n(r)})})}async touchAsync(e,n){return new Promise((r,a)=>{this.touch(e,n,e=>{e==null?r():a(e)})})}},LibraryUserError=class extends Error{constructor(e,n){super(n),this.kind=e,this.name=`LibraryUserError`}kind};function complete(e,n){let r;try{r=e()}catch(e){if(n==null)throw e;n(e);return}n?.(void 0,r)}var UserColumns=`id, email, role, oidcIssuer, oidcSubject, createdAt, updatedAt`,LiveSessionWhere=`Session.sid = :sid AND Session.expired > :now
|
|
604
|
+
AND Session.createdAt + :absoluteTimeout > :now`;function touchWriteIntervalMs(){return Math.min(minuteMs,Settings2.sessionTimeout.valueOrDefault/100)}function normalizeUserEmail(e){return e.trim().replace(/[A-Z]/g,e=>e.toLowerCase())}var LibraryAuthStore=class extends DbSessionStore{#e;constructor(e){super(e),this.#e=e}get db(){if(this.ended||this.#e.ended)throw Error(`Library authentication store has ended`);return this.#e}cleanup(){this.db.prepare(`DELETE FROM Session WHERE expired <= :now OR createdAt + :absoluteTimeout <= :now`).run({now:Date.now(),absoluteTimeout:Settings2.sessionAbsoluteTimeout.valueOrDefault})}getSync(e){return parseJSON(this.db.prepare(`SELECT sess FROM Session WHERE ${LiveSessionWhere}`).get({sid:e,now:Date.now(),absoluteTimeout:Settings2.sessionAbsoluteTimeout.valueOrDefault})?.sess)}get(e,n){complete(()=>this.getSync(e),n)}sessionPrincipal(e,n){let r=this.db.prepare(`SELECT Session.sess, Session.userId, User.email, User.role
|
|
605
|
+
FROM Session LEFT JOIN User ON User.id = Session.userId
|
|
606
|
+
WHERE ${LiveSessionWhere}`).get({sid:e,now:Date.now(),absoluteTimeout:Settings2.sessionAbsoluteTimeout.valueOrDefault});if(r!=null&&parseJSON(r.sess)?.ownerRealm===n&&r.userId!=null&&r.email!=null&&r.role!=null)return{role:r.role,user:{id:r.userId,email:r.email}}}ownerSessionGeneration(){return this.db.prepare(`SELECT generation FROM LibrarySignIn WHERE singleton = 1`).pluck().get()}endSessionsIfSignInModeChanged(e){return this.db.db.transaction(()=>this.db.prepare(`SELECT signInMode FROM LibrarySignIn WHERE singleton = 1`).pluck().get()!==e&&(this.db.prepare(`UPDATE LibrarySignIn
|
|
607
|
+
SET generation = generation + 1, signInMode = :mode
|
|
608
|
+
WHERE singleton = 1`).run({mode:e}),this.#c(),!0)).immediate()}clearOidcLinksForNewIssuer(e){return this.db.db.transaction(()=>this.db.prepare(`SELECT oidcLinksIssuer FROM LibrarySignIn WHERE singleton = 1`).pluck().get()===e?0:(this.db.prepare(`UPDATE LibrarySignIn SET oidcLinksIssuer = ? WHERE singleton = 1`).run(e),Number(this.db.prepare(`UPDATE User SET oidcIssuer = NULL, oidcSubject = NULL,
|
|
609
|
+
updatedAt = :now WHERE oidcSubject IS NOT NULL`).run({now:Date.now()}).changes))).immediate()}endAllSessions(){this.db.db.transaction(()=>{this.db.prepare(`UPDATE LibrarySignIn SET generation = generation + 1 WHERE singleton = 1`).run(),this.#c()})()}async establishUserSessionAsync(e,n,r,a=this.ownerSessionGeneration(),o){return typeof n.ownerRealm==`string`&&this.db.db.transaction(()=>{if(this.ownerSessionGeneration()!==a)return!1;let s=this.userById(r);return s==null||o!=null&&(s.oidcIssuer!==o.issuer||s.oidcSubject!==o.subject)?!1:(this.#t(e,n,r),!0)}).immediate()}#t(e,n,r){let a=Date.now();this.db.prepare(`INSERT INTO Session (sid, createdAt, expired, sess, userId)
|
|
610
|
+
VALUES (:sid, :now, :expired, :sess, :userId)`).run({sid:e,now:a,expired:a+Math.min(Settings2.sessionTimeout.valueOrDefault,Settings2.sessionAbsoluteTimeout.valueOrDefault),sess:stringify(n),userId:r})}hasUsers(){return this.db.prepare(`SELECT 1 FROM User LIMIT 1`).get()!=null}listUsers(){return this.db.prepare(`SELECT ${UserColumns} FROM User ORDER BY email`).all()}userById(e){return this.db.prepare(`SELECT ${UserColumns} FROM User WHERE id = ?`).get(e)}userByEmail(e){return this.db.prepare(`SELECT ${UserColumns} FROM User WHERE email = ?`).get(normalizeUserEmail(e))}userByOidcSubject(e,n){return this.db.prepare(`SELECT ${UserColumns} FROM User WHERE oidcIssuer = ? AND oidcSubject = ?`).get(e,n)}linkUserOidcSubject(e,n,r){return this.db.prepare(`UPDATE User SET oidcIssuer = :issuer, oidcSubject = :subject,
|
|
611
|
+
updatedAt = :now WHERE id = :id AND oidcSubject IS NULL`).run({id:e,issuer:n,subject:r,now:Date.now()}).changes===1}addUser({email:e,role:n}){let r=normalizeUserEmail(e);if(!isPlainMailbox(r))throw new LibraryUserError(`invalidEmail`,`A user needs a valid email address`);return this.#n(()=>{if(this.userByEmail(r)!=null)throw new LibraryUserError(`duplicateEmail`,`That email address is already a user`);let e=Date.now(),{lastInsertRowid:a}=this.db.prepare(`INSERT INTO User (email, role, createdAt, updatedAt)
|
|
612
|
+
VALUES (:email, :role, :now, :now)`).run({email:r,role:n,now:e});return this.userById(Number(a))})}changeUserRole(e,n){return this.#n(()=>{let r=this.#r(e);return n!==LibraryRoles.admin&&this.#i(r,`demote`),this.db.prepare(`UPDATE User SET role = :role, updatedAt = :now WHERE id = :id`).run({id:e,role:n,now:Date.now()}),this.#a(e),this.userById(e)})}removeUser(e){this.#n(()=>{this.#i(this.#r(e),`remove`),this.#a(e),this.db.prepare(`DELETE FROM User WHERE id = ?`).run(e)})}clearUserOidcLink(e){return this.#n(()=>(this.#r(e),this.db.prepare(`UPDATE User SET oidcIssuer = NULL, oidcSubject = NULL,
|
|
613
|
+
updatedAt = :now WHERE id = :id`).run({id:e,now:Date.now()}),this.#a(e),this.userById(e)))}#n(e){return this.db.db.transaction(e).immediate()}#r(e){let n=this.userById(e);if(n==null)throw new LibraryUserError(`userNotFound`,`No such user`);return n}#i(e,n){if(e.role===LibraryRoles.admin&&this.db.prepare(`SELECT count(*) FROM User WHERE role = 'admin'`).pluck().get()<=1)throw new LibraryUserError(`lastAdmin`,`Cannot ${n} the library's last admin`)}#a(e){this.db.prepare(`DELETE FROM Session WHERE userId = ?`).run(e)}set(e,n,r){complete(()=>this.#s(e,n),r)}touch(e,n,r){complete(()=>{typeof n.ownerRealm==`string`&&(this.#o(e)||this.#s(e,n))},r)}#o(e){let n=Date.now(),r=this.db.prepare(`SELECT Session.expired AS expired,
|
|
614
|
+
min(:idleExpired, Session.createdAt + :absoluteTimeout) AS target
|
|
615
|
+
FROM Session WHERE ${LiveSessionWhere}`).get({sid:e,now:n,idleExpired:n+Settings2.sessionTimeout.valueOrDefault,absoluteTimeout:Settings2.sessionAbsoluteTimeout.valueOrDefault});return r==null||Math.abs(r.target-r.expired)<touchWriteIntervalMs()}#s(e,n){if(typeof n.ownerRealm!=`string`)return;let r=Date.now();this.db.prepare(`UPDATE Session
|
|
616
|
+
SET expired = min(:idleExpired, createdAt + :absoluteTimeout), sess = :sess
|
|
617
|
+
WHERE ${LiveSessionWhere}`).run({sid:e,now:r,sess:stringify(n),idleExpired:r+Settings2.sessionTimeout.valueOrDefault,absoluteTimeout:Settings2.sessionAbsoluteTimeout.valueOrDefault})}#c(){this.db.prepare(`DELETE FROM Session`).run()}clear(e){complete(()=>this.endAllSessions(),e)}};function hourlyErrorReporter(e){let n=lazy2(()=>!0,hourMs);return r=>{n.prior()!==!0&&(n(),onError(e,{error:r,fatal:!1}))}}var TTLArray=class{constructor(e,n){this.ttlMs=e,this.maxLength=n}ttlMs;maxLength;times=[];a=[];expirationListeners=[];[Symbol.iterator](){this.vacuum();let e=[...this.a];function*n(){for(let n of e)yield n}return n()}push(...e){times(e.length,()=>this.times.push(performance.now())),this.a.push(...e),this.maxLength!=null&&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)}filter(e){return this.vacuum(),this.a.filter(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,n){return this.vacuum(),this.a.slice(e,n)}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(this.a.length===0)return;let e=this.a.length;if(this.maxLength!=null){let e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}let n=performance.now()-this.ttlMs,r=this.times.findIndex(e=>e>n);if(r===-1?this.clear():r>0&&(this.times.splice(0,r),this.a.splice(0,r)),e!==this.a.length)for(let e of this.expirationListeners)e()}},SortedSet=class{constructor(e){this.valueOf=e}valueOf;#e=[];[Symbol.iterator](){return this.#e[Symbol.iterator]()}map(e){return this.#e.map(e)}some(e){return this.#e.some(e)}filter(e){return this.#e.filter(e)}get length(){return this.#e.length}addAll(...e){for(let n of e)this.add(n)}#t(e){if(e==null)return;let n=0,r=this.#e.length-1;for(;n<=r;){let a=n+r>>>1,o=this.valueOf(this.#e[a]);if(e===o)return{found:!0,index:a};e>o?n=a+1:r=a-1}return{found:!1,index:n}}findIndex(e){return e==null?void 0:this.#t(this.valueOf(e))}add(e){let n=this.findIndex(e);return n?.found===!1&>e0(n?.index)&&this.#e.splice(n.index,0,e),n}nearest({t:e,limit:n,diff:r}){if(n>=this.length)return[...this.#e];let a=n=>n<0||n>this.#e.length-1?null:r(this.#e[n],e),o=this.findIndex(e);if(o==null)return;let s=o.index-1,c=a(s),l=o.index,u=a(l),d=[];for(;d.length<n&&(c!=null||u!=null);)c!=null&&(u==null||c<=u)&&(d.push(this.#e[s--]),c=a(s)),d.length<n&&u!=null&&(c==null||u<c)&&(d.push(this.#e[l++]),u=a(l));return sortBy(d,e=>this.valueOf(e))}clear(){this.#e.length=0}at(e){return at(this.#e,e)}toA(){return[...this.#e]}shift(){return this.#e.shift()}shiftLte(e){let n=this.#t(e);if(n==null||n.index===0&&!n.found)return[];if(n.index===this.#e.length-1){let e=[...this.#e];return this.clear(),e}return this.#e.splice(0,n.index+ +!!n.found)}splice(e,n){return e<0&&(e=this.#e.length+e),n==null?this.#e.splice(e):this.#e.splice(e,n)}retainLastN(e){return e<this.length&&this.splice(0,this.#e.length-e),this}deleteIf(e){for(let n=this.#e.length-1;n>=0;n--)e(this.#e[n])&&this.#e.splice(n,1)}delete(e){let n=this.#e.indexOf(e);n>=0&&this.#e.splice(n,1)}},doNotRun=shimSync({name:`doNotRun`,impl:doNotRunBasic});function doNotRunBasic(e,n={}){return!0===e?.ended||ending()||!n.userInitiated&&(isTooBusy()||(n.ignoredPauseReasons==null?isPaused():pauseReasonsExcept(n.ignoredPauseReasons).length>0))}var DoNotRunRetryMs=isTest()?25:3e3,Job=class{constructor(e,n,r=!1){this.d=e,this.l=n,this.userInitiated=r}d;l;userInitiated;get id(){return this.d.id}get name(){return this.d.name}started(){return this.d.isObserved}notStarted(){return!this.started()}isRunning(){return this.d.isObserved&&this.d.isPending}isSettled(){return this.d.isSettled}then(e,n){return this.d.then(e,n)}},Promises=class e extends EndableWrapper{ee=new TypedEventEmitterImpl;#e;#t;#n;#r;#i;#a=new Average;#o=new Average;#s=0;#c=0;#l=performance.now();#u=this.#l;#d=0;lastWorkTs=0;settleMsAvg=new Average;#f=0;#p;lastRunNames=new BoundedList(16);static for({name:n,maxConcurrency:r,sortByDesc:a=e=>e.id,lowWaterMark:o,highWaterMark:s,reserveToStart:c}){return new e(n,r,a,o,s,c)}constructor(e,n,r=e=>e.id,a,o,s){super(e),this.#e=s,this.#t=n,this.#i=a,this.#r=o,this.#p=new SortedSet(e=>r(e.d)),this.onEnds.push(()=>{this.#b(),this.deletePending(()=>!0,`Promises(${this.name}) ended`)})}nuke(){let e=this.#p.toA();this.#p.clear(),this.#g(0);for(let n of e)n.d.reject(new AbortError(`Promises.nuke() called`))}deletePending(e,n){let r=[];for(let n of this.#p)n.notStarted()&&e(n.d)&&r.push(n);for(let e of r)this.#p.delete(e),e.d.reject(new AbortError(n));return r.length>0&&this.#h(),r.length}get maxConcurrency(){return this.#n=this.#m(this.#t?.())}get lastMaxConcurrency(){return this.#n??this.#m(void 0)}#m(e){return Math.floor(clamp(1,maxCpus(),e??maxCpus()))}get highWaterMark(){return this.#r?.()??Settings2.taskListCap.valueOrDefault}get lowWaterMark(){return this.#i?.()??Math.floor(this.highWaterMark/2)}enqueueCapacity(e){if(e!=null){let n=0;for(let r of this.#p)r.d.serialIds.includes(e)&&n++;return Math.max(0,this.lowWaterMark-n)}return Math.max(0,this.highWaterMark-this.#p.length)}runCapacity(){return Math.max(0,this.maxConcurrency-this.runningCount())}#h(){let e=this.runningCount();this.#g(e),this.#a.push(e),this.#o.push(this.notStartedCount()),this.#p.length<=this.lowWaterMark&&this.ee.emitThrottled(`lowWaterMark`),this.#p.length===0&&this.ee.emitSync(`drain`)}get settledCount(){return this.#f}get notStartedLengthAvg(){return this.#o}get runningLengthAvg(){return this.#a}#g(e,n=performance.now()){let r=Math.max(0,n-this.#u);return this.#c+=this.#s*r,this.#s=e,this.#u=n,this.#d=Math.max(this.#d,e),n}takeRunningCountSample(){let e=this.#g(this.runningCount()),n=e-this.#l,r=n>0?{averageRunningCount:this.#c/n,elapsedMs:n,maxRunningCount:this.#d}:void 0;return this.#c=0,this.#l=e,this.#d=this.#s,r}runningJobNames(){let e=[];for(let n of this.#p)n.isRunning()&&e.push(n.d.name);return e}runningJobDetails(){let e=[];for(let n of this.#p)n.isRunning()&&e.push({name:n.d.name,startedAt:n.d.startedAt,elapsedMs:n.d.elapsedMs});return e}stats(){let e=this.lastMaxConcurrency;return{maxConcurrency:e,capacity:this.enqueueCapacity(),lastWorkMsAgo:performance.now()-this.lastWorkTs,freeSlots:Math.max(0,e-this.runningCount()),unsettledCount:this.unsettledCount(),queuedBackgroundCount:count(this.#p,e=>e.notStarted()&&!e.userInitiated),runningJobNames:this.runningJobNames(),runningJobDetails:this.runningJobDetails(),notStartedJobNamesLimit10:this.notStartedJobNames(10),totalWorkCount:this.#f,notStartedLengthAvg:this.#o.stats(),runningLengthAvg:this.#a.stats()}}enqueueDeferred(e,n,{userInitiated:r=!1}={}){this.#p.add(new Job(e,n,r)),this.#h(),this.maybePopPendingWork()}enqueue({name:e,l:n,payload:r,serialIds:a,userInitiated:o=!1}){let s=new Deferred2(e,{payload:r,serialIds:a});return this.#p.add(new Job(s,n,o)),this.#h(),this.maybePopPendingWork(),s}enqueueAll(e,n){let r=[];for(let a of n){let n=new Deferred2(e);this.#p.add(new Job(n,a)),r.push(n.promise)}return this.#h(),this.maybePopPendingWork(),Promise.all(r)}serial(e,n,r){return this.enqueue({name:e,l:n,serialIds:[e],payload:r})}run(e,n,r){let a=new Job(new Deferred2(e,{payload:r}),n);return this.#p.add(a),this.#h(),this.#_(a)}get runningJobs(){return this.#p.filter(e=>e.isRunning())}get runningSerialIds(){let e=new Set;for(let n of this.runningJobs)for(let r of n.d.serialIds??[])e.add(r);return e}#_(e){let n=this.lastWorkTs=performance.now();return e.notStarted()&&(this.#g(this.runningCount()+1),e.d.observe(e.l).finally(()=>{this.#p.delete(e),this.#h(),this.#f++,this.settleMsAvg.push(performance.now()-n),this.maybePopPendingWork()}),this.lastRunNames.push(e.d.name)),this.#h(),this.maybePopPendingWork(),e}maybePopPendingWork=()=>setTimeout(()=>this.#v(),1);onPaused=defer(async()=>{await resolveOnPauseChange(),this.maybePopPendingWork(),this.#h(),this.onPaused.reset()});onTooBusy=defer(async()=>{await resolveOnNotBusy(),this.maybePopPendingWork(),this.#h(),this.onTooBusy.reset()});#v(){if(this.ended||ending())return;let e=pauseReasons().length>0,n=!e&&isTooBusy();e&&this.onPaused(),n&&this.onTooBusy();let r=e||n||doNotRun(this);if(r){let r=this.#p.some(e=>e.notStarted()&&e.userInitiated),a=r&&doNotRun(this,{userInitiated:!0});if(this.hasSomeNotStartedJobs()&&(!e&&!n||a)&&this.#x(),!r||a)return}let a=this.maxConcurrency,o=this.runningCount();if(o<a&&this.hasSomeNotStartedJobs()){let e=this.runningSerialIds,n=!1;for(let s of this.#p)if(!(s.started()||r&&!s.userInitiated||s.d.serialIds.some(n=>e.has(n)))){if(this.#e!=null&&!this.#e(s.d.id,s.userInitiated))n=!0;else{this.#_(s);for(let n of s.d.serialIds)e.add(n);if(o++,o>=a)break}}n&&this.#x()}}#y;#b(){this.#y!=null&&(clearTimeout(this.#y),this.#y=void 0)}#x(){this.#y!=null||this.ended||(this.#y=setUnrefTimeout(()=>{this.#y=void 0,this.ended||this.#v()},DoNotRunRetryMs))}isTaskRunning(e){return this.#p.some(n=>n.d.name===e)}maybeRun(e,n){return this.availableConcurrency()>0&&!this.isTaskRunning(e)?this.run(e,n):void 0}runningCount(){return count(this.#p,e=>e.isRunning())}hasSomeRunningJobs(){for(let e of this.#p)if(e.isRunning())return!0;return!1}hasSomeNotStartedJobs(){for(let e of this.#p)if(e.notStarted())return!0;return!1}notStartedCount(){return count(this.#p,e=>e.notStarted())}unsettledCount(){return count(this.#p,e=>!e.isSettled())}get size(){return this.unsettledCount()}hasPending(){for(let e of this.#p)if(!e.isSettled())return!0;return!1}isIdle(){return this.#p.length===0}availableConcurrency(){return Math.max(0,this.maxConcurrency-this.runningCount())}isMaxBusy(){return this.runningCount()>=this.maxConcurrency}notStartedJobNames(e){let n=[];for(let r of this.#p)if(r.notStarted()&&(n.push(r.d.name),gte(n.length,e)))break;return n}get deferreds(){return this.#p.map(e=>e.d)}enqueuedWithNameCount(e){return count(this.#p,n=>n.d.name===e&&!n.isSettled())}pendingWithName(e){return this.#p.filter(n=>n.d.name===e&&!n.isSettled()).map(e=>e.d)}pendingPayloadsWithName(e){return this.pendingWithName(e).filter(e=>e.payload!=null).map(e=>e.payload)}get pendingPromises(){return this.deferreds.map(e=>e.promise)}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async#S(e){let n=new Latch(e),r=()=>n.resolve();this.ee.once(e,r);try{await Promise.race([n,this.awaitEnd()])}finally{this.ee.off(e,r)}}async awaitDrain(){for(;!this.isIdle()&&!this.ended;)await this.#S(`drain`)}async awaitLowWaterMark(){for(;this.#p.length>this.lowWaterMark&&!this.ended;)await this.#S(`lowWaterMark`)}async awaitAll(){await Promise.all(this.pendingPromises)}countByName(){let e=new CountingSet;for(let n of this.#p)n.isSettled()||e.incr(n.d.name);return e}async awaitAllByName(e){await Promise.all(this.deferreds.filter(n=>n.name===e).map(e=>e.promise))}};function normalizedCeiling(e){return Math.max(1,Math.floor(e))}var AdaptiveConcurrency=class{#e=1/0;limit(e){return Math.min(this.#e,normalizedCeiling(e))}reset(){this.#e=1/0}update(e){let n=normalizedCeiling(e.ceiling);if(e.targetPct<=0)return this.reset(),n;let r=this.limit(n);if(e.maxRunningCount>r)return r;if(e.busyPct>e.targetPct&&e.averageRunningCount>0){let n=Math.floor(e.averageRunningCount*e.targetPct/e.busyPct);this.#e=Math.max(1,Math.min(r,n))}else{let r=Math.min(10,e.targetPct/2);e.busyPct<e.targetPct-r&&e.hasPendingWork&&e.maxRunningCount>=this.#e&&(this.#e=this.#e+1<n?this.#e+1:1/0)}return this.limit(n)}},userAgentSuffix=lazy2(async()=>void 0);async function userAgent(){let e=doNotTrack()||PrivacySettings.optOut.valueOrDefault;return PrivacySettings.allowUserAgent.valueOrDefault&&!e?systemUserAgent():simpleUserAgent()}function simpleUserAgent(){return SimpleAppName+version}async function systemUserAgent(){let e=simpleUserAgent()+` (`+osFullName()+`)`,n=await userAgentSuffix();return notBlank(n)?e+` `+n:e}var HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,Conflict:409,EnhanceYourCalm:420,TooManyRequests:429,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),HttpStatusIs=Object.freeze({ok(e){return within(200,299,e)},success(e){return within(200,299,e)},redirect(e){return within(300,399,e)},clientError(e){return within(400,499,e)},serverError(e){return within(500,599,e)},error(e){return within(400,599,e)}}),http=__toESM(require("node:http")),https=__toESM(require("node:https")),logger104=defer(()=>mkLogger(`net.get`)),HttpMethods=strEnum(`GET`,`PUT`,`POST`,`PATCH`,`DELETE`);async function get_(e,n){return httpRequest_({...n,url:e})}async function httpRequest_(e){let n=toURI(e.url),r=new Deferred2(`get `+n.toString()),a=n.scheme===`http`?http.request:n.scheme===`https`?https.request:logger104().throw(`unsupported scheme: `+n.scheme),o=e?.maxRedirects??8,s=e?.timeoutMs??ShortCommandTimeoutMs,c={...e?.headers};c[`User-Agent`]??=await userAgent();let l=e?.method??`GET`,u=e?.agent??!1,d=a(n.toString(),{method:l,headers:c,timeout:s,agent:u},e=>{let a=``;e.setEncoding(`utf8`).on(`data`,e=>a+=e.toString()).resume().on(`end`,()=>{let c={url:toNotBlank(e.url)??n.toString(),contentType:e.headers[`content-type`],statusCode:e.statusCode??-1,data:a};o>0&&HttpStatusIs.redirect(c.statusCode)&&!blank(e.headers.location)?(logger104().info(`Following redirect`,{from:n.toString(),to:e.headers.location,statusCode:c.statusCode}),r.observe(get_(e.headers.location,{timeoutMs:s,maxRedirects:o}))):(logger104().debug(`complete`,{...c,data:ellipsize(a,64),data_length:a.length}),r.resolve(c))})}).on(`error`,e=>r.reject(e));return blank(e.body)||d.write(e.body),d.end(),r}var logger105=defer(()=>mkLogger(`health.GetHealthSummary`)),getRemoteHealthSummary=lazyAsync({desc:`health.getRemoteHealthSummary`,later:async()=>{try{if(isWebService())return;let e=await get_(URI.from({scheme:`http`,authority:`127.0.0.1:`+Settings2.httpPort.valueOrDefault,path:`/api/health`}),{headers:{"User-Agent":simpleUserAgent()},timeoutMs:ShortCommandTimeoutMs}),n=parseJSON_(e.data);if(HttpStatusIs.ok(e.statusCode)&&isHealthCheckSummary(n))return n.state===`ready`&&toNotBlank(n.libraryDir)!==toNotBlank(Settings2.libraryDir.valueOrDefault)&&(logger105().error(`getHealthSummary(): libraryDir mismatch! Switching to that library directory...`,{local:Settings2.libraryDir.valueOrDefault,remote:n.libraryDir}),Settings2.libraryDir.value=n.libraryDir??void 0),logger105().debug(`getHealthSummary()`,{response:e}),n;logger105().warn(`getHealthSummary(): invalid response`,{response:e})}catch(e){logger105().warn(`Failed to get health check summary from web service`,{error:e})}}}),getLocalHealthSummary=lazyAsync({desc:`health.getLocalHealthSummary`,later:()=>HealthCheck.awaitSettled()}),localHealthGateSummary;function getLocalHealthGateSummarySync(){let e=getLocalHealthSummary.syncValue();return localHealthGateSummary??e}later(()=>{Settings2.healthCheckIntervalMs.watch(e=>{getRemoteHealthSummary.setTTL(e),getLocalHealthSummary.setTTL(e)}),HealthCheck.summary.watchLater(e=>{let n=e?.settled===!0?e:summarizeHealthChecksSync({healthCheckResults:HealthCheck.allCritical().map(e=>e.toResultSync()),errors:HealthCheck.lastErrors(),skipPending:!0});(e?.settled===!0||SyncBlockingLevels.includes(n.level))&&(localHealthGateSummary=n,ee().emitSync(`syncStateChanged`))})});var installDoNotRunImpl=defer(()=>{doNotRun.setShim(doNotRunImpl)});function doNotRunImpl(e,n){return whyDoNotRun(e,n)!=null}function reportWhy(e,n){e!=null&&syncReport().maybeSystemData({from:`whyDoNotRun`,state:`note`,details:`Tasks are paused: `+e,meta:{paused:!0,...omit(n??{},`links`,`buttons`)}})}var whyOversizedPendingWrite=shimSync({name:`whyOversizedPendingWrite`,impl:()=>void 0}),reserveFreeSpaceToStart=shimSync({name:`reserveFreeSpaceToStart`,impl:(e,n)=>!0}),libraryFreeSpaceState=shimSync({name:`libraryFreeSpaceState`,impl:()=>void 0});function whyDoNotRun(e,n={}){let r=pauseReasonsExcept(n.ignoredPauseReasons),a=!n.userInitiated&&r.length>0?`paused: ${r.join(`, `)}`:void 0,o=!0===e?.ended?`endable ended`:ending()?`service is ending`:!n.userInitiated&&isTooBusy()?`system is too busy`:a,s=n.userInitiated===!0?void 0:whyOversizedPendingWrite(),c=getLocalHealthGateSummarySync(),l=c!=null&&SyncBlockingLevels.includes(c.level)&&!(n.userInitiated&&c.level===`stop-sync`)?c:void 0,u=describeDoNotRun(o??s,l);return reportWhy(u,l),u}function describeDoNotRun(e,n){let r=compactBlankish([e,...n?.msg??[]]).map(e=>stripSuffix(e.trim(),`:`)),a=``;for(let e of r)a.length>0&&(a+=SentenceEnd.test(a)?` `:`: `),a+=e;return toNotBlank(a)}var SentenceEnd=/[.!?]$/,DeferredTaskError=class extends Error{constructor(e,n){super(`File is problematic (timed out recently)`),this.path=e,this.notBefore=n}path;notBefore;name=`DeferredTaskError`},import_sqlite4=require("@photostructure/sqlite"),JsonFileStore=class{constructor(e,n,r){this.file=e,this.mkObject=n,this.onWrite=r}file;mkObject;onWrite;#e=lazy2(async()=>{try{return await this.file.readJson(`debug`)??await withLock_({file:this.file,timeoutMs:ShortCommandTimeoutMs,oneShot:!0},async()=>await this.file.clear().readJson(`debug`)??await map(await this.mkObject(),e=>this.write_(e)))}catch(e){throw this.#e.unset(),e}});get cached(){return this.#e.priorSync()??void 0}async read_(){return this.#e()}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.#e.set(Promise.resolve(e)),mkLogger(`fs.JsonFileStore`).info(`wrote to `+this.file,e),this.onWrite!=null&&await this.onWrite(this.file,e),e}catch(e){throw new WrappedError(`Failed to write to `+this.file,{cause:e,path:this.file.nativePath})}}};function mkuid(){return TokenRadix.randomUid(24,4)}var cache9=new Cache({name:`UIDStore`,ttlMs:0,maxSize:4});later(()=>{ee().on(`clearCache`,()=>{cache9.clear()})});var UIDStore=class e extends JsonFileStore{constructor(e,n){super(e.join(`.`+n+`-uid.json`),()=>({uid:mkuid(),version,type:this.type,createdAt:Date.now()}),async e=>{try{await hide_(e)}catch(n){mkLogger(`fs.UIDStore`).warn(`failed to hide UID file, `+e,{error:n})}}),this.rootDir=e,this.type=n}rootDir;type;static for(n,r){let a=PosixFile.forMaybe(n);if(a==null)return;let o=a.nativePath+`:`+r;return cache9.getOrSet(o,()=>new e(a,r))}static clearCache(){cache9.clear()}async readUid_(){return(await this.read_())?.uid}};function systemUidStore(){return UIDStore.for(configDir(),`system`)}function libraryUidStore(e=Settings2.libraryDir.valueOrDefault){return UIDStore.for(e,`library`)}var modelDb=lazy2(()=>void 0),ProblematicFilesHealthCheckId=`problematic-files`,logger106=mkLogger(`db.QuarantineDb`),quarantineDb=lazy2(()=>void 0);function quarantineDbRequired_(){let e=quarantineDb.prior();if(e==null||e.ended)throw Error(`Quarantine database has not been initialized`);return e}var import_node_fs33=require("node:fs"),import_node_path71=require("node:path"),import_exiftool_vendored23=require("exiftool-vendored"),logger107=lazy2(()=>mkLogger(`tags.MergedTags`));function isBaseRevision(e){return isNumber(e?.createdAt)&¬Blank(e?.field)}function isPrimitiveRevision(e){return e?.op==null&&isBaseRevision(e)}var MergedTags=class{constructor(e){this.name=e,this.logger=mkLogger(`MergedTags(${e})`)}name;logger;revisions=[];tags=[];addRevision(...e){this.revisions.push(...e)}sortedTags=defer(()=>sortBy(uniqBy(this.tags,e=>e.SourceFile),e=>[!e.sourceIsPrimary,-e.sourceModifiedTime]));async addFile(e,n){let r=toNativePath(e);if(blank(r)){this.logger.warn(`No SourceFile for `+e);return}let a=await readTags(e);a==null?this.logger.warn(`Failed to read tags from `+e):this.addTag({...a,SourceFile:r,sourceIsPrimary:n,sourceModifiedTime:await mtimeMs(r)})}addTag(e){blank(e.SourceFile)?this.logger.warn(`No SourceFile for tag`,{name:this.name}):e.sourceIsPrimary==null?this.logger.warn(`No sourceIsPrimary for tag`,{nativePath:e.SourceFile}):e.sourceModifiedTime==null?this.logger.warn(`No sourceModifiedTime for tag`,{nativePath:e.SourceFile}):(this.sortedTags.reset(),this.tags.push(e))}get(e){let n=sortBy(this.revisions.filter(n=>n.field===e),e=>e.createdAt),r=this.sortedTags().find(n=>n[e]!=null),a=r?.[e],o=[];if(a!=null&&mapNotBlank(r?.SourceFile,e=>o.push(e)),n.every(isPrimitiveRevision)&&this.tags.every(n=>!Array.isArray(n[e]))){for(let r of n)a!=null&&a!==r.priorValue&&a!==r.newValue?this.logger.info(`get(`+e+`): skipping revision because expected prior or new value didn't match current value`,{name:this.name,revision:r}):(a=r.newValue,o.push(`Revision@${r.createdAt}`));return a==null?void 0:{value:a,source:o}}{let e=toA(a);for(let r of n)if(r.op===`add`&&r.newValue!=null)o.push(`Revision@${r.createdAt}`),pushUniq(e,...toA(r.newValue));else if(r.op===`delete`&&r.priorValue!=null){o.push(`Revision@${r.createdAt}`);for(let n of toA(r.priorValue))remove(e,n)}return{value:e,source:o}}}},import_posix2=require("node:path/posix");function extractUriDirectory_(e){if(blank(e))throw Error(`extractUriDirectory_: blank URI`);let n=toURI(e);return n.with({path:(0,import_posix2.dirname)(n.path),query:null,fragment:null}).toString()}function extractUriBasename_(e){if(blank(e))throw Error(`extractUriBasename_: blank URI`);return(0,import_posix2.basename)(toURI(e).path)}function extractUriAuthority_(e){if(blank(e))throw Error(`extractUriAuthority_: blank URI`);return toURI(e).authority}var ThumbsPerSample=80,BeforeAfterStreamLimit=8,TagRoots=strEnum(`When`,`Who`,`Where`,`What`,`Event`,`Camera`,`Lens`,`Albums`,`Keywords`,`Type`,`fs`),LibraryTagName=`Library`,NotInfoPanelTags=[TagRoots.When,TagRoots.Camera,TagRoots.Lens,TagRoots.Type,TagRoots.fs],dtf=lazy2(()=>new Intl.DateTimeFormat(localeSync(),{month:`short`})),months=lazy2(()=>{let e=dtf();return range(0,12,n=>e.format(new Date(2016,n,1))).map(e=>stripSuffix(e,`.`))});ee().on(`clearCache`,()=>{dtf.unset(),months.unset()});function yearToOrdinal(e){return 1e4-e}function monthToOrdinal(e){return 13-e}function dayToOrdinal(e){return 33-e}function yearTagRef(e){return mapGt0(e,e=>({name:toS(e),ordinal:yearToOrdinal(e)}))}function monthTagRef(e){if(within(1,12,e))return map(months()[e-1],n=>({name:String(e),displayName:n,ordinal:monthToOrdinal(e)}))}function dayTagRef(e){if(within(1,31,e))return{name:toS(e),ordinal:dayToOrdinal(e)}}function dateTag(e){if(e==null||Settings2.tagYMD.isDisabled())return;let n=toS(Settings2.tagYMD.valueOrDefault).toLowerCase(),r=[TagRoots.When];if(n.startsWith(`y`)){let n=map(getYear(e),yearTagRef);if(n==null)return;r.push(n)}if(n.startsWith(`ym`)){let n=map(getMonth(e),monthTagRef);if(n==null)return r;r.push(n)}if(n.startsWith(`ymd`)){let n=map(getDay(e),dayTagRef);if(n==null)return r;r.push(n)}return r}async function dateTagFile(e,n){if(isDisabled(Settings2.tagYMD.valueOrDefault))return;let r=n??await readCapturedAt(e);if(!(r==null||capturedAtSrcFromStat(r.capturedAtSrc)&&!Settings2.tagDateFromStat.valueOrDefault))return dateTag(r.date)}var import_BatchClusterOptions=require("batch-cluster/dist/BatchClusterOptions"),import_node_stream6=require("node:stream"),logger108=defer(()=>mkLogger(`stream.JSONLinesTransform`)),nativeLibraryNoiseRe=/^\(process:\d+\): (?:GLib|Gtk|GObject|Gdk)|^Fontconfig error:/,JsonLinesTransform=class extends import_node_stream6.Transform{lineReader;strictJson;constructor(e){super({objectMode:!0,...e}),this.strictJson=e?.strictJson??!1,this.lineReader=new LineReader,this.lineReader.on(`data`,e=>this.#e(e)),this.lineReader.on(`error`,e=>this.emit(`error`,e))}#e(e){let n=toS(e).trim();if(n.length!==0)try{let e=parseJSON_(n);if(e==null){logger108().warn(`Ignoring bare null JSON line (would end the stream)`,{line:n});return}this.push(e)}catch(e){if(!this.strictJson&&nativeLibraryNoiseRe.test(n)){logger108().debug(`Native library noise from child process`,{line:n});return}logger108().warn(`Non-JSON output from child process`,{line:n,error:e}),this.strictJson&&this.emit(`error`,e)}}_transform(e,n,r){this.lineReader.write(e,n,r)}_flush(e){this.lineReader.end(e)}},logger109=lazy2(()=>mkLogger(`child.ChildService`));async function pathToService(e){let n=ensureSuffix(e,`.js`),r=BaseFile.for(ProjectDir.Root()),a=BaseFile.for(process.cwd()),o=isElectron()&&!isPacked(),s=a.join(`.webpack`,`main`,n),c=isPacked()?[BaseFile.for(ProjectDir.Bin()).join(n)]:o?[s,a.join(`dist`,`library`,n)]:[a.join(`dist`,`library`,n),a.join(`dist`,`core`,n),a.join(`lib`,`library`,n)];!isPacked()&&!o&&c.push(r.join(`src`,`library`,`dist`,`library`,n));for(let e of c)if(e!=null&&!0===await e.isNonEmptyFile(isPacked()?KB:128))return logger109().tap({msg:`pathToService()`,level:`info`,result:e,meta:{cmd:n,isPacked:isPacked(),paths:c.map(toS)}});return logger109().throw(`Failed to find path to `+e,{paths:c.map(toS),fatal:!0})}var ChildServiceNames=strEnum(...ServiceNames.pick(`web`,`sync`));function assertValidBitArray(e,n){for(let r=0;r<e.length;r++)if(e[r]!==0&&e[r]!==1)throw TypeError(`${n}: invalid argument: bits[${r}] must be 0 or 1`)}function b64encodeBitsFixedWidth(e,n){if(e.length!==n)throw TypeError(`b64encodeBitsFixedWidth: expected ${n} bits but got ${e.length}`);return assertValidBitArray(e,`b64encodeBitsFixedWidth`),b64encodeBigIntFixedWidth(BigInt(`0b0`+e.join(``)),n)}function b64encodeBigIntFixedWidth(e,n){let r=Math.ceil(n/8)*2,a=e.toString(16);return a.length<r&&(a=`0`.repeat(r-a.length)+a),Buffer.from(a,`hex`).toString(`base64`)}function b64decode(e){let n=Buffer.from(e,`base64`);return BigInt(`0x0`+n.toString(`hex`))}function toBigInt(e){if(typeof e==`bigint`)return e;if(typeof e==`number`){if(isFinite(e))return BigInt(e);throw TypeError(`Invalid number: `+String(e))}if(typeof e==`string`){if(blank(e))throw TypeError(`Invalid string for BigInt conversion: empty string`);return BigInt(e)}throw TypeError(`Invalid type for BigInt conversion`)}function popcountBigInt(e){let n=0;for(;e;)e&=e-1n,n++;return n}function hammingBigInt(e,n){return e===n?0:popcountBigInt(e^n)}function hammingDistance(e,n){return hammingBigInt(toBigInt(e),toBigInt(n))}var eps=.15,OPTIMAL_THRESHOLDS={pHash:.64-eps,rHash:.79-eps,wHash:.87-eps},SEPARATION_SCORES={pHash:.296,rHash:.29,wHash:.312},ImageHashTypes=strEnum(`pHash`,`rHash`,`wHash`);function hashRecordToHashRecord0(e){let n={};for(let[r,a]of entries(e))blank(a)||(n[`${r}0`]=a);return n}function hashRecord0ToHashRecord(e){let n={};for(let[r,a]of entries(e))r.endsWith(`0`)&&!blank(a)&&(n[r.slice(0,-1)]=a);return n}function applyThresholdAdjustment(e,n,r=16){if(e=clamp(0,1,e),n=clamp(.1,.9,n),e===1)return 1;let a=clamp(-15,15,r*(e-n));return 1/(1+Math.exp(-a))}function simpleConfidence(e){let n=(e.isMonochrome?64:192)/2,r={},a=[];for(let[o,s]of entries(e.hashDistances)){let e=applyThresholdAdjustment(clamp(0,1,(n-s)/n),OPTIMAL_THRESHOLDS[o]??.75),c=SEPARATION_SCORES[o]??.1;r[o]=e,a.push({value:e,weight:c})}return a.length===0?{confidence:0,confidences:r}:{confidence:clamp(0,1,weightedMean(a)),confidences:r}}function computeConfidence(e){return sigFigsDeep(simpleConfidence(e),4)}var MASK_64=(1n<<64n)-1n;function extractLuminanceBits(e){return e>MASK_64?e>>128n&MASK_64:e&MASK_64}function hashRecordToLHashHex(e){let{pHash:n,rHash:r,wHash:a}=e;if(blank(n)||blank(r)||blank(a))return;let o=extractLuminanceBits(b64decode(n)),s=extractLuminanceBits(b64decode(r)),c=extractLuminanceBits(b64decode(a));return(o<<128n|s<<64n|c).toString(16).padStart(48,`0`)}function compareHashRecords(e,n,r){let a={};for(let o of ImageHashTypes.values){let s=e[o],c=n[o];if(blank(s)||blank(c)){a={};break}let l=b64decode(s),u=b64decode(c);r&&(l=extractLuminanceBits(l),u=extractLuminanceBits(u)),a[o]=hammingDistance(l,u)}return{distances:a,...computeConfidence({hashDistances:a,isMonochrome:r})}}var repairRequiredBeforeMatching=!1;function assetFileHashReadyForMatching(){return!isVec0Available()||!repairRequiredBeforeMatching}function markAssetFileHashReadyForMatching(){repairRequiredBeforeMatching=!1}var import_knex_sqlite=__toESM(require("@photostructure/knex-sqlite")),import_knex=__toESM(require("knex")),knex=lazy2(()=>{let e=(0,import_knex.default)({client:import_knex_sqlite.default,useNullAsDefault:!0});return e.client.logger=mkLogger(`knex.client`),e}),AssetFileHashOrientations=strEnum(`rendered`,`canonical`);function assetFileHashRowId(e,n){if(!Number.isSafeInteger(e)||e<=0)throw Error(`AssetFileHash row ids require a positive AssetFile id: `+e);return n===`rendered`?e:-e}var assetFileHashDeleteByRowIdSql=`DELETE FROM AssetFileHash WHERE rowid = ? AND assetFileId = ?`,assetFileHashSelectByRowIdsSql=`
|
|
618
|
+
SELECT AssetFileHash.rowid, assetFileId, hex(lHash) AS lHashHex,
|
|
619
|
+
capturedAtLocal, capturedAtFuzzy, bname
|
|
620
|
+
FROM json_each(?) CROSS JOIN AssetFileHash
|
|
621
|
+
ON AssetFileHash.rowid = json_each.value`;function assetFileHashRowIdsJson(e){return JSON.stringify(e.flatMap(e=>AssetFileHashOrientations.values.map(n=>assetFileHashRowId(e,n))))}var assetFileHashMisplacedRowCountSql=`
|
|
622
|
+
SELECT COUNT(*) FROM AssetFileHash
|
|
623
|
+
WHERE rowid <> assetFileId AND rowid <> -assetFileId`;function assetFileHashCreateTableSql(e=!0){return`
|
|
624
|
+
CREATE VIRTUAL TABLE ${e?`IF NOT EXISTS `:``}AssetFileHash USING vec0(
|
|
625
|
+
assetFileId INTEGER,
|
|
626
|
+
lHash bit[192],
|
|
627
|
+
capturedAtLocal INTEGER,
|
|
628
|
+
capturedAtFuzzy INTEGER,
|
|
629
|
+
bname TEXT
|
|
630
|
+
)
|
|
631
|
+
`}function assetFileHashMetadata(e){let n=e.capturedAtLocal??0;return{capturedAtLocal:n,capturedAtFuzzy:e.capturedAtSrc!==`tags`||localIsFuzzy(n)?1:0,bname:shortestBname(e.basename)}}function assertLHashHex(e){if(!/^[0-9a-f]{48}$/i.test(e))throw Error(`Invalid lHashHex: expected 48 hex characters`)}function assetFileHashInsertSql(e,n,r,a){assertLHashHex(n);let o=assetFileHashMetadata(r);return knex()(`AssetFileHash`).insert({rowid:assetFileHashRowId(e,a),assetFileId:e,lHash:knex().raw(`vec_bit(X'${n}')`),capturedAtLocal:o.capturedAtLocal,capturedAtFuzzy:o.capturedAtFuzzy,bname:o.bname}).toQuery()}function assetFileHashInsertsSql(e,n){let r=hashRecordToLHashHex(n);if(r==null)return;let a=[assetFileHashInsertSql(e,r,n,`rendered`)],o=hashRecordToLHashHex(hashRecord0ToHashRecord(n));return o!=null&&o!==r&&a.push(assetFileHashInsertSql(e,o,n,`canonical`)),a}var logger110=lazy2(()=>mkLogger(`db.AssetFileHashSchema`));function assetFileHashTableExists(e){return e.prepare(`SELECT COUNT(*) FROM sqlite_master
|
|
632
|
+
WHERE type = 'table' AND name = 'AssetFileHash'`).pluck().get()===1}function ensureAssetFileHashTable(e){if(!canInitializeVec0())return!1;if(assetFileHashTableExists(e))return clearVec0SchemaError(),!1;try{e.exec(assetFileHashCreateTableSql())}catch(e){let n=e instanceof Error?e:Error(String(e));return setVec0SchemaError(n),logger110().warn(`Failed to create AssetFileHash table; disabling similarity search`,{error:n}),!1}return clearVec0SchemaError(),logger110().info(`Created AssetFileHash table`),!0}var logger111=lazy2(()=>mkLogger(`db.SqliteVecMaintenance`)),vectorTables=[{tableName:`AssetFileHash`,description:`Image perceptual hash similarity (bit vectors)`}];function getVectorTables(){return vectorTables}function optimizeVectorTable(e,n){if(!isVec0Available())return logger111().debug(`Skipping vector table optimize: sqlite-vec not available`),!1;try{return e.exec(`INSERT INTO ${n}(${n}) VALUES('optimize')`),logger111().info(`Optimized sqlite-vec table: ${n}`),!0}catch(e){return logger111().warn(`Failed to optimize sqlite-vec table: ${n}`,{error:e}),!1}}function vectorTableSlots(e,n){let{slots:r,chunkSize:a}=e.prepare(`SELECT coalesce(sum(size), 0) AS slots, coalesce(max(size), 0) AS chunkSize FROM ${n}_chunks`).get(),o=e.prepare(`SELECT count(*) FROM ${n}_rowids`).pluck().get();return{slots:r,live:o,reclaimable:r-(a===0?0:Math.ceil(o/a)*a)}}var logger112=lazy2(()=>mkLogger(`db.AssetFileHash`)),contentVerifiedDbs=new WeakSet,ContentVerificationBatchSize=1e4,eligibleAssetFileHashWhereSql=`
|
|
633
|
+
pHash GLOB '*[A-Za-z0-9+/]*'
|
|
634
|
+
AND rHash GLOB '*[A-Za-z0-9+/]*'
|
|
635
|
+
AND wHash GLOB '*[A-Za-z0-9+/]*'
|
|
636
|
+
AND isPrimary = 1
|
|
637
|
+
AND assetId IS NOT NULL`;function refreshAssetFileHashHealthCheck(){HealthCheck.findById(`library-asset-file-hash-index`)?.refresh()}async function rebuildAssetFileHashTable(e,n){return isVec0Available()?time({name:`db.assetFileHash.rebuild`,p:async()=>{let r=performance.now();logger112().info(`Starting AssetFileHash index rebuild`);let a=0,o=0,s=Settings2.dbBatchSelectSize.valueOrDefault;try{e.transaction(()=>{e.exec(`DROP TABLE IF EXISTS AssetFileHash`),e.exec(assetFileHashCreateTableSql(!1)),a=e.prepare(`SELECT COUNT(*) FROM AssetFile
|
|
638
|
+
WHERE ${eligibleAssetFileHashWhereSql}`).pluck().get(),logger112().info(`Found ${a} AssetFiles with complete hash values to index`);let r=e.prepare(`SELECT id, pHash, rHash, wHash, pHash0, rHash0, wHash0,
|
|
639
|
+
capturedAtLocal, capturedAtSrc, basename
|
|
640
|
+
FROM AssetFile
|
|
641
|
+
WHERE ${eligibleAssetFileHashWhereSql}
|
|
642
|
+
AND id > ?
|
|
643
|
+
ORDER BY id ASC
|
|
644
|
+
LIMIT ?`),c=0;for(;;){let a=r.all(c,s);if(a.length===0)break;let l=[];for(let e of a){let n=assetFileHashInsertsSql(e.id,e);if(n==null)throw Error(`AssetFileHash selected incomplete hashes for AssetFile ${e.id}`);l.push(...n),o+=n.length}l.length>0&&e.exec(l.join(`; `)),c=a[a.length-1].id,n?.()}let l=verifyAssetFileHashTable(e,!0,n);if(!l.matches||l.uniqueAssetFileCount!==a||l.rowCount!==o)throw Error(`AssetFileHash rebuild verification failed: `+JSON.stringify({total:a,inserted:o,...l}))}).immediate()}catch(e){throw logger112().error(`AssetFileHash index rebuild failed; prior index preserved`,{error:e}),e}markAssetFileHashReadyForMatching(),contentVerifiedDbs.add(e),refreshAssetFileHashHealthCheck();let c=performance.now()-r;return logger112().info(`AssetFileHash index rebuild complete`,{total:a,inserted:o,elapsedMs:c}),optimizeVectorTable(e,`AssetFileHash`),{total:a,inserted:o,elapsedMs:c}}}):(logger112().info(`Skipping AssetFileHash rebuild: sqlite-vec extension not available`),{total:0,inserted:0,elapsedMs:0})}function verifyAssetFileHashTable(e,n=!0,r){r?.();let a=e.prepare(`SELECT COUNT(*) FROM AssetFile
|
|
645
|
+
WHERE ${eligibleAssetFileHashWhereSql}`).pluck().get(),o=assetFileHashTableExists(e);if(!o)return{tableExists:o,contentsVerified:!1,assetFileCount:a,rowCount:0,uniqueAssetFileCount:0,missingAssetFileCount:a,extraAssetFileCount:0,contentMismatchCount:0,misplacedRowCount:0,matches:!1};r?.();let s=e.prepare(`SELECT COUNT(*) FROM AssetFileHash`).pluck().get();r?.();let c=e.prepare(`SELECT COUNT(DISTINCT assetFileId) FROM AssetFileHash`).pluck().get();r?.();let l=e.prepare(`SELECT COUNT(*) FROM (
|
|
646
|
+
SELECT id FROM AssetFile
|
|
647
|
+
WHERE ${eligibleAssetFileHashWhereSql}
|
|
648
|
+
EXCEPT
|
|
649
|
+
SELECT DISTINCT assetFileId FROM AssetFileHash
|
|
650
|
+
)`).pluck().get();r?.();let u=e.prepare(`SELECT COUNT(*) FROM (
|
|
651
|
+
SELECT DISTINCT assetFileId FROM AssetFileHash
|
|
652
|
+
EXCEPT
|
|
653
|
+
SELECT id FROM AssetFile
|
|
654
|
+
WHERE ${eligibleAssetFileHashWhereSql}
|
|
655
|
+
)`).pluck().get(),d=0;n&&(r?.(),d=e.prepare(assetFileHashMisplacedRowCountSql).pluck().get());let f=n?assetFileHashContentMismatchCount(e,r):0;return{tableExists:o,contentsVerified:n,assetFileCount:a,rowCount:s,uniqueAssetFileCount:c,missingAssetFileCount:l,extraAssetFileCount:u,contentMismatchCount:f,misplacedRowCount:d,matches:l===0&&u===0&&f===0&&d===0}}function assetFileHashContentMismatchCount(e,n){let r=e.prepare(`SELECT id, pHash, rHash, wHash, pHash0, rHash0, wHash0,
|
|
656
|
+
capturedAtLocal, capturedAtSrc, basename
|
|
657
|
+
FROM AssetFile
|
|
658
|
+
WHERE ${eligibleAssetFileHashWhereSql}
|
|
659
|
+
AND id > ?
|
|
660
|
+
ORDER BY id
|
|
661
|
+
LIMIT ?`),a=e.prepare(assetFileHashSelectByRowIdsSql),o=0,s=0,c=e.transaction(()=>{let e=r.all(o,ContentVerificationBatchSize);if(e.length===0)return;o=e[e.length-1].id;let s=new Map;for(let n of e){let e=new Map,r=assetFileHashMetadata(n),a=(a,o)=>{let s=assetFileHashContentSignature({rowid:assetFileHashRowId(n.id,o),lHashHex:a,...r});e.set(s,(e.get(s)??0)+1)},o=hashRecordToLHashHex(n);if(o==null)throw Error(`AssetFileHash verifier selected incomplete hashes for AssetFile ${n.id}`);a(o,`rendered`);let c=hashRecordToLHashHex(hashRecord0ToHashRecord(n));c!=null&&c!==o&&a(c,`canonical`),s.set(n.id,e)}let c=new Set,l=new Set,u=a.iterate(assetFileHashRowIdsJson(e.map(e=>e.id)));for(let e of u){if(Math.abs(e.rowid)!==e.assetFileId)continue;l.add(e.assetFileId);let n=s.get(e.assetFileId);if(n==null)throw Error(`AssetFileHash verifier selected unexpected AssetFile ${e.assetFileId}`);let r=assetFileHashContentSignature(e),a=n.get(r)??0;a<=0?c.add(e.assetFileId):n.set(r,a-1)}for(let[e,n]of s)if(l.has(e)){for(let r of n.values())if(r!==0){c.add(e);break}}return n?.(),c.size});for(;;){let e=c.deferred();if(e==null)return s;s+=e}}function assetFileHashContentSignature(e){return JSON.stringify([e.rowid,e.lHashHex.toUpperCase(),e.capturedAtLocal,e.capturedAtFuzzy,e.bname])}function checkAssetFileHashTable(e,n=10,r=!contentVerifiedDbs.has(e),a){if(!isVec0Available())return logger112().info(`Skipping AssetFileHash health check: sqlite-vec extension not available`),{countMatch:!0,contentsVerified:!1,assetFileCount:0,rowCount:0,uniqueAssetFileCount:0,missingAssetFileCount:0,extraAssetFileCount:0,contentMismatchCount:0,misplacedRowCount:0,selfQuery:{tested:0,passed:0,failed:0},orphanedRows:0,isHealthy:!0,issues:[]};let o=[],{tableExists:s,contentsVerified:c,assetFileCount:l,rowCount:u,uniqueAssetFileCount:d,missingAssetFileCount:f,extraAssetFileCount:h,contentMismatchCount:_,misplacedRowCount:y,matches:x}=verifyAssetFileHashTable(e,r,a);s?x||((f>0||h>0)&&o.push(`ID-set mismatch: ${f} eligible AssetFiles missing and ${h} ineligible AssetFiles indexed (${l} eligible IDs, ${d} indexed IDs, ${u} total rows)`),_>0&&o.push(`Content mismatch: ${_} AssetFiles have unexpected index rows`),y>0&&o.push(`Row-id mismatch: ${y} index rows are not at their AssetFile's row id`)):o.push(`AssetFileHash table is missing`);let C={tested:0,passed:0,failed:0};if(!s){let e={countMatch:x,contentsVerified:c,assetFileCount:l,rowCount:u,uniqueAssetFileCount:d,missingAssetFileCount:f,extraAssetFileCount:h,contentMismatchCount:_,misplacedRowCount:y,selfQuery:C,orphanedRows:0,isHealthy:!1,issues:o};return logger112().info(`AssetFileHash table health check complete`,e),e}let w=()=>{try{let r=e.prepare(`SELECT id, pHash, rHash, wHash, pHash0, rHash0, wHash0 FROM AssetFile
|
|
662
|
+
WHERE ${eligibleAssetFileHashWhereSql}
|
|
663
|
+
ORDER BY RANDOM() LIMIT ?`).all(n);for(let n of r){C.tested++;try{let r=hashRecordToLHashHex(n);if(r==null){C.failed++;continue}let a=e.prepare(`SELECT assetFileId FROM AssetFileHash
|
|
664
|
+
WHERE vec_distance_hamming(lHash, vec_bit(X'${r}')) = 0
|
|
665
|
+
LIMIT 1`).pluck().get();if(a!=null)C.passed++,a!==n.id&&logger112().debug(`Self-query found different id with same hash`,{assetFileId:n.id,foundId:a});else{C.failed++;let a=e.prepare(`SELECT hex(lHash) FROM AssetFileHash WHERE assetFileId = ?`).pluck().get(n.id);logger112().warn(`Self-query failed: lHash not found in AssetFileHash table`,{assetFileId:n.id,queryHex:r,storedHex:a,inAssetFileHashTable:a!=null})}let o=hashRecordToLHashHex(hashRecord0ToHashRecord(n));if(o!=null&&o!==r){C.tested++;let r=e.prepare(`SELECT assetFileId FROM AssetFileHash
|
|
666
|
+
WHERE vec_distance_hamming(lHash, vec_bit(X'${o}')) = 0
|
|
667
|
+
LIMIT 1`).pluck().get();r==null?(C.failed++,logger112().warn(`Self-query failed: lHash0 (canonical orientation) not found in AssetFileHash table`,{assetFileId:n.id,queryHex:o})):(C.passed++,r!==n.id&&logger112().debug(`Self-query (HashRecord0) found different id with same hash`,{assetFileId:n.id,foundId:r}))}}catch(e){C.failed++,logger112().warn(`Self-query error`,{assetFileId:n.id,error:e})}a?.()}C.failed>0&&o.push(`Self-query test failed: ${C.failed}/${C.tested} hashes could not find themselves`)}catch(e){o.push(`Self-query test error: ${e}`),logger112().warn(`Self-query test failed`,{error:e})}};u>0&&(r?e.transaction(w).deferred():w());let T=e.prepare(`SELECT COUNT(*) FROM AssetFileHash h
|
|
668
|
+
WHERE NOT EXISTS (SELECT 1 FROM AssetFile a WHERE a.id = h.assetFileId)`).pluck().get();T>0&&o.push(`Referential integrity: ${T} AssetFileHash rows reference non-existent AssetFile ids`);let E=x&&C.failed===0&&T===0;return E&&c&&contentVerifiedDbs.add(e),logger112().info(`AssetFileHash table health check complete`,{isHealthy:E,countMatch:x,contentsVerified:c,assetFileCount:l,rowCount:u,uniqueAssetFileCount:d,missingAssetFileCount:f,extraAssetFileCount:h,contentMismatchCount:_,misplacedRowCount:y,selfQuery:C,orphanedRows:T,issues:o}),{countMatch:x,contentsVerified:c,assetFileCount:l,rowCount:u,uniqueAssetFileCount:d,missingAssetFileCount:f,extraAssetFileCount:h,contentMismatchCount:_,misplacedRowCount:y,selfQuery:C,orphanedRows:T,isHealthy:E,issues:o}}function syncAssetFileHash(e,n,r){if(!isVec0Available())return!1;let a=assetFileHashInsertsSql(n,r);return a==null?(deleteAssetFileHash(e,n),!1):(e.transaction(()=>{deleteAssetFileHashRows(e,n),e.exec(a.join(`; `))})(),!0)}function deleteAssetFileHash(e,n){isVec0Available()&&deleteAssetFileHashRows(e,n)}function deleteAssetFileHashRows(e,n){let r=e.prepare(assetFileHashDeleteByRowIdSql);for(let e of AssetFileHashOrientations)r.run(assetFileHashRowId(n,e),n)}var ensureAssetFileHashHealthy=lazyAsync({desc:`ensureAssetFileHashHealthy`,later:_ensureAssetFileHashHealthy,ttlMs:7*import_BatchClusterOptions.secondMs});async function _ensureAssetFileHashHealthy(){if(!canInitializeVec0())return markAssetFileHashReadyForMatching(),!1;let e=Library.instance();if(e==null)return!1;let n=await e.modelDb(),r=ensureAssetFileHashTable(n.db);if(!isVec0Available())return markAssetFileHashReadyForMatching(),!1;let a=isSyncService()&&!contentVerifiedDbs.has(n.db)?await validateAssetFileHashTableInFixProcess_():checkAssetFileHashTable(n.db,10);return a.isHealthy?(a.contentsVerified&&contentVerifiedDbs.add(n.db),markAssetFileHashReadyForMatching(),r&&refreshAssetFileHashHealthCheck(),r):(isSyncService()?await rebuildAssetFileHashTableInFixProcess_(e,n.db):await rebuildAssetFileHashTable(n.db),markAssetFileHashReadyForMatching(),!0)}var ValidateAssetFileHashCommand=`validate-asset-file-hash`,RebuildAssetFileHashCommand=`asset-file-hash`;async function validateAssetFileHashTableInFixProcess_(){return fixCheckResult_(await runFixChild_(ValidateAssetFileHashCommand))}async function rebuildAssetFileHashTableInFixProcess_(e,n){throwUnlessFixSucceeded_(RebuildAssetFileHashCommand,await(await e.dbMaintenanceWindow()).runWithWriterLockHeld(()=>runFixChild_(RebuildAssetFileHashCommand))),contentVerifiedDbs.add(n),refreshAssetFileHashHealthCheck()}async function runFixChild_(e){let n=await pathToService(`fix`),r={};Settings2.libraryDir.addToEnv(r);let a=Settings2.dbMaintenanceTimeoutMs.valueOrDefault,o=new Abortable,s,c=()=>{clearTimeout(s),s=setTimeout(()=>o.abort(`fix --${e} printed nothing for ${a}ms`),a)};c();try{return await stdoutResult_(process.execPath,[n.nativePath,`--`+e,`--skip-open-checks`],{timeoutMs:0,halt:o,onStdoutChunk:c,env:r,quiet:!0,isIgnorableError:()=>!0,ignoreExitCode:!0})}finally{clearTimeout(s)}}function fixCheckResult_(e){return throwUnlessFixSucceeded_(ValidateAssetFileHashCommand,e),parseJSON_(e.result.trimEnd().split(`
|
|
669
|
+
`).pop())}function throwUnlessFixSucceeded_(e,{code:n,stderr:r}){if(n!==0)throw Error(`fix --${e}: exit code ${n}: ${r}`)}var mayExist=!0;function legacyPslibRowsMayExist(){return mayExist}var logger113=defer(()=>mkLogger(`uri.UriDeleted`));async function isUriDeleted(e){let n=toURI(e),r=await candidatePaths(n);if(r.length===0)return logger113().tap({msg:`isUriDeleted(): URI resolves to no path`,result:void 0,meta:{uri:n}});for(let e of r)if(await e.f.exists())return logger113().tap({msg:`isUriDeleted(): file exists`,result:{...e,result:!1}});let a=await canProveDeletion(n,r);return logger113().tap({msg:`isUriDeleted(): no candidate exists`,result:{...r[0],result:a?!0:void 0}})}async function candidatePaths(e){let n=uriEncodingVariantURIs(e);if(e.scheme===`file`)return n.map(e=>({uri:e,f:PosixFile.for(e.fsPath)}));if(e.scheme===PS_LIBRARY_SCHEME)return libraryAssetDirPosixFiles().flatMap(e=>n.map(n=>({uri:n,f:e.join(n.relativeFsPath),mountPoint:e.nativePath})));if(e.scheme===PS_NETWORK_FILESYSTEM_SCHEME){let e=[];for(let r of n)try{let n=await psnetToNativePath_({uri:r});if(n==null)continue;e.push({uri:r,f:PosixFile.for(n.nativePath),mountPoint:n.mountPoint})}catch(e){logger113().debug(`isUriDeleted(): psnet variant did not resolve`,{uri:r,error:e})}return e}let r;try{r=await volshaToMountPoints(e.authority)}catch(n){return logger113().warn(`isUriDeleted(): cannot resolve mount points for authority`,{uri:e,error:n}),[]}return r.filter(isNativePath).flatMap(e=>n.map(n=>({uri:n,f:PosixFile.for(e).join(n.relativeFsPath),mountPoint:e})))}async function canProveDeletion(e,n){if(e.scheme===`file`)return!0;if(e.scheme===PS_LIBRARY_SCHEME)return!originalsDirIsOutsideLibrary()||!legacyPslibRowsMayExist();let r=FilesystemSettings.missingFileVolumeProofTtlMs.valueOrDefault;for(let a of uniq(compactBlanks(n.map(e=>e.mountPoint))))if(e.scheme===PS_NETWORK_FILESYSTEM_SCHEME?await isPsnetShareMountedAt({uri:e,mountPoint:a,ttlMs:r}):await isVolumeAuthorityMountedAt({mountPoint:a,volumeSha:e.authority}))return!0;return!1}var import_node_fs30=require("node:fs"),import_promises32=require("node:fs/promises"),fs7=__toESM(require("node:fs")),logger114=lazy(()=>void 0),SystemTrashPath=`/usr/bin/trash`,trashCliPath=lazy(()=>{if(isMac)try{return fs7.accessSync(SystemTrashPath,fs7.constants.X_OK|fs7.constants.R_OK),SystemTrashPath}catch{return}}),trashMac=sequential(async(e,n=64)=>{if(!isMac)throw Error(`trashMac() only works on macOS`);let r=new Set;for(let n of e)if(!blank(n)){let e=resolve2(n);fs7.existsSync(e)?r.add(e):logger114()?.warn(`Ignoring non-existent path`,{input:n,resolved:e})}if(r.size===0)return new Map;let a=trashCliPath();return a==null?trashViaOsascript([...r],n):trashViaCli(a,[...r],n)});async function trashBatched(e,n,r,a){let o=new Map;for(let s of batches(e,n))try{let e=await a(s);logger114()?.info(`Sent files to trash via `+r,{out:e,batch:s})}catch(e){logger114()?.warn(`Batch trash via `+r+` failed, retrying individually`,{batch:s,error:e});for(let e of s)if(fs7.existsSync(e))try{let n=await a([e]);logger114()?.info(`Sent file to trash via `+r,{out:n,path:e})}catch(n){logger114()?.warn(`Failed to trash file via `+r,{path:e,error:n}),o.set(e,toError(n)??Error(String(n)))}}return o}async function trashViaCli(e,n,r){let a=statTimeoutMs()*clamp(1,4,r/8);return trashBatched(n,r,`CLI`,n=>stdoutResult_(e,n,{timeoutMs:a,ignoreStderr:!0}))}async function trashViaOsascript(e,n){let r=statTimeoutMs()*clamp(1,4,n/8),a=e=>`the POSIX file "`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)+`"`;return trashBatched(e,n,`osascript`,e=>stdoutResult_(`osascript`,[`-e`,`tell app "Finder" to move {${e.map(a).join(`, `)}} to trash`],{timeoutMs:r,ignoreStderr:!0}))}var logger115=lazy(()=>void 0);async function trashWin_(e,n=64){if(!isWin)throw Error(`trashWin_() only works on Windows`);let r=new Map,a=await pathToTool_(`recycle-bin`);for(let o of batches([...e],n))try{let e=await stdoutResult_(a,o,{timeoutMs:3e4});logger115()?.info(`Sent files to recycle bin`,{out:e,batch:o})}catch(e){let n=toError(e)??Error(String(e));for(let e of o)r.set(e,n)}return r}var import_node_crypto7=require("node:crypto"),import_promises31=require("node:fs/promises"),import_node_path61=require("node:path"),import_node_path60=require("node:path"),import_node_process27=require("node:process");function xdg_data_home(){return toNotBlank(import_node_process27.env.XDG_DATA_HOME)??(0,import_node_path60.join)(homeDir(),`.local`,`share`)}function xdg_home_trash(){return(0,import_node_path60.join)(xdg_data_home(),`Trash`)}var logger116=lazy(()=>void 0);async function mkdirp_700(e,n){if(await isReadWriteableDirectory(e))return e;try{return await(0,import_promises31.mkdir)(e,{recursive:!0,mode:448}),e}catch(r){logger116()?.warn(`Failed to mkdirp `+n,{dir:e,error:r})}}async function trashPathForMountpoint(e){if(blank(e))return;let n=await mkdirp_700((0,import_node_path61.join)(e,`.Trash-`+userid()),`user-specific device trash directory`);if(n!=null){let e=await(0,import_promises31.lstat)(n).catch(()=>null);if(e!=null&&!e.isSymbolicLink()&&userids().includes(e.uid))return n;logger116()?.warn(`Ignoring unsuitable trash directory`,{uidTrash:n})}return mkdirp_700((0,import_node_path61.join)(e,`.Trash`,toS(userid())),`device trash directory`)}var devId2trashPath=defer(()=>new FifoCache({timeoutMs:Settings2.statTimeoutMs.valueOrDefault,maxSize:64,clearEveryMs:5*minuteMs}));async function trashPathForDevice(e,n){return devId2trashPath().getOrSet(toS(n),async()=>{let r=xdg_home_trash();isDocker()||await(0,import_promises31.mkdir)(r,{recursive:!0,mode:448});let a=await statMaybe(r),o=isStatRWX(a,r);if(o&&a?.dev===n)return r;let s=await bestMountPointForPath(e),c=await trashPathForMountpoint(toNativePath(s?.mountPoint));if(c!=null)return c;if(o)return r;logger116()?.warn(`No suitable trash directory found`,{nativePath:e,homeTrash:r,mountpoint:s,dev:n})})}async function trashXDG_(e,n){let r=await(0,import_promises31.stat)(e);if(n=toNotBlank(n??await trashPathForDevice(e,r.dev)),n==null)throw Error(`No suitable XDG trash directory found`);let a=(0,import_node_crypto7.randomUUID)(),o=(0,import_node_path61.join)(n,`files`);await mkdirp_700(o,`Trash/files`);let s=(0,import_node_path61.join)(o,a),c=(0,import_node_path61.join)(n,`info`);await mkdirp_700(c,`Trash/info`);let l=(0,import_node_path61.join)(c,`${a}.trashinfo`),u=`[Trash Info]
|
|
670
|
+
Path=${encodeURIComponent(e)}
|
|
671
|
+
DeletionDate=${fmtIsoDateTime(new Date)}`;return await(0,import_promises31.writeFile)(l,u,{flush:!0}),await move_(e,s),{nativePath:e,destination:s,trashInfoPath:l}}async function trashMultiXDG(e,n){let r=new Map,a=await thenCollectParallel({iter:compactBlanks(e),f:e=>trashXDG_(e,n)});for(let[e,n]of a)e instanceof Error&&r.set(n,e);return r}var logger117=lazy2(()=>void 0);function waitForFileToDisappear(e){return untilTrue(()=>(0,import_node_fs30.lstatSync)(e,{throwIfNoEntry:!1})==null,{intervalMs:500,timeoutMs:1e4})}async function trashOrRm({nativePaths:e,trySoftDeletes:n,skipDirectories:r}){logger117()?.info(`trashOrRm`,{nativePaths:e,trySoftDeletes:n});let a=uniq(compactBlanks(e)),o=[],s=[];for(let e of a)try{let n=await(0,import_promises32.lstat)(e);r&&n.isDirectory()?o.push({nativePath:e,action:`error`,error:Error(`refusing to delete directory`)}):s.push(e)}catch(n){o.push({nativePath:e,action:`error`,error:toError(n)})}let c=new Map;if(n){logger117()?.info(`attempting to soft-delete`,{existing:s});try{if(isMac)c=await trashMac(s);else if(isWin)c=await trashWin_(s);else if(isLinux)c=await trashMultiXDG(s);else throw Error(`No trash implementation for this platform`)}catch(e){let n=toError(e)??Error(String(e));for(let e of s)c.set(e,n)}}for(let e of s)try{n&&((0,import_node_fs30.lstatSync)(e,{throwIfNoEntry:!1})==null||!c.has(e)&&await waitForFileToDisappear(e))?(logger117()?.info(`soft-deleted`,{file:e}),o.push({nativePath:e,action:`trash`})):(logger117()?.info(`needing to rm`,{file:e}),await(0,import_promises32.rm)(e,{recursive:!0,force:!0,maxRetries:3,retryDelay:1e3}),o.push({nativePath:e,action:`rm`,trashError:c.get(e)}))}catch(n){o.push({nativePath:e,action:`error`,error:toError(n),trashError:c.get(e)})}return sortByInPlace(o,n=>e.indexOf(n.nativePath)),logger117()?.info(`trashOrRm()`,{results:o}),o}var from=`fs.Trash`,logger118=defer(()=>mkLogger(from));async function trashOrRmUris(e,{allowMissing:n=!1,allowedPaths:r}={}){logger118().info(`trashOrRmUris()`,{arr:e});let a=new Map,o=r==null?void 0:new Set(r),s=new Map,c=[];for(let[n,r]of[...e].entries()){s.set(r.uri,n);try{let e=toNotBlank(r.nativePath)??await uriToNativePath_(r.uri);if(blank(e))c.push({uri:r.uri,action:`error`,error:Error(`Could not resolve URI to a native path`)});else{if(o!=null&&!o.has(e))throw Error(`File location changed or became available after deletion was requested. Empty Trash again to retry.`);let n=a.get(e)??[];n.push(r.uri),a.set(e,n)}}catch(e){c.push({uri:r.uri,action:`error`,error:e instanceof Error?e:Error(errorToS2(e))})}}let l=await trashOrRm({nativePaths:[...a.keys()],trySoftDeletes:Settings2.trySoftDeletes.valueOrDefault,skipDirectories:!0}),u=l.flatMap(e=>(a.get(e.nativePath)??[]).map(n=>({...e,uri:n}))),d=new Set;for(let e of u)n&&e.action===`error`&&errorCode(e.error)===`ENOENT`&&await isAbsentForDeletion(e.uri)&&(e.action=`rm`,e.error=void 0,d.add(e.uri));for(let e of l)await ee().emit(`fileChanged`,e.nativePath);for(let e of c)logger118().warn(`Failed to convert URI to nativePath`,{uri:e.uri,error:e.error}),syncReport().onProgress({from,type:`file`,state:`unavailable`,details:`not deleted: `+errorToS2(e.error),path:e.uri});let f=c.concat(u.map(e=>(e.action===`error`?(logger118().error(`Failed to delete file`,e),syncReport().onProgress({from,type:`file`,state:`failed`,details:`Failed to delete: `+errorToS2(e.error)+(e.trashError==null?``:`; moving to trash also failed: `+errorToS2(e.trashError)),path:e.nativePath})):(e.trashError!=null&&logger118().warn(`Moving to trash failed; permanently deleted`,e),syncReport().onProgress({from,type:`file`,state:e.action===`rm`?`deleted`:`trashed`,details:e.action===`rm`?e.trashError==null?d.has(e.uri)?`Already absent`:`Deleted`:`Moved to trash failed (`+errorToS2(e.trashError)+`), permanently deleted`:`Moved to trash`,path:e.nativePath})),e)));return sortBy(f,e=>s.get(e.uri)??f.length)}async function isAbsentForDeletion(e){let n=await isUriDeleted(e);return n?.result===!0||n!=null&&n.result===void 0&&n.uri.scheme===PS_LIBRARY_SCHEME}var import_node_path66=require("node:path"),import_sharp6=__toESM(require("sharp")),LIGHTNESS_WEIGHT=.5,COMPLEXITY_WEIGHT=.3,CHROMA_WEIGHT=.2;function computeDirectionalGradients(e,n,r){let a=n/2,o=r/2,s={topLeft:{lightness:0,complexity:0,chroma:0,count:0},topRight:{lightness:0,complexity:0,chroma:0,count:0},bottomLeft:{lightness:0,complexity:0,chroma:0,count:0},bottomRight:{lightness:0,complexity:0,chroma:0,count:0}};for(let c=0;c<r;c++)for(let r=0;r<n;r++){let l=(c*n+r)*3,u=e[l],d=e[l+1],f=e[l+2],h=Math.sqrt(d*d+f*f),_=c<o?r<a?s.topLeft:s.topRight:r<a?s.bottomLeft:s.bottomRight;_.lightness+=u,_.chroma+=h,_.count++}for(let c=1;c<r-1;c++)for(let r=1;r<n-1;r++){let l=(c*n+(r-1))*3,u=(c*n+(r+1))*3,d=((c-1)*n+r)*3,f=((c+1)*n+r)*3,h=e[u]-e[l],_=e[f]-e[d],y=Math.sqrt(h*h+_*_),x=c<o?r<a?s.topLeft:s.topRight:r<a?s.bottomLeft:s.bottomRight;x.complexity+=y}for(let e of Object.values(s))e.count>0&&(e.lightness/=e.count,e.chroma/=e.count,e.complexity/=e.count);let c={lightness:(s.topLeft.lightness+s.topRight.lightness)/2,complexity:(s.topLeft.complexity+s.topRight.complexity)/2,chroma:(s.topLeft.chroma+s.topRight.chroma)/2},l={lightness:(s.bottomLeft.lightness+s.bottomRight.lightness)/2,complexity:(s.bottomLeft.complexity+s.bottomRight.complexity)/2,chroma:(s.bottomLeft.chroma+s.bottomRight.chroma)/2},u={lightness:(s.topLeft.lightness+s.bottomLeft.lightness)/2,complexity:(s.topLeft.complexity+s.bottomLeft.complexity)/2,chroma:(s.topLeft.chroma+s.bottomLeft.chroma)/2},d={lightness:(s.topRight.lightness+s.bottomRight.lightness)/2,complexity:(s.topRight.complexity+s.bottomRight.complexity)/2,chroma:(s.topRight.chroma+s.bottomRight.chroma)/2};return{lightness:{up:c.lightness-l.lightness,down:l.lightness-c.lightness,left:u.lightness-d.lightness,right:d.lightness-u.lightness},complexity:{up:c.complexity-l.complexity,down:l.complexity-c.complexity,left:u.complexity-d.complexity,right:d.complexity-u.complexity},chroma:{up:c.chroma-l.chroma,down:l.chroma-c.chroma,left:u.chroma-d.chroma,right:d.chroma-u.chroma}}}function scoreRotations(e){return[{rotation:0,upDir:`up`},{rotation:90,upDir:`left`},{rotation:180,upDir:`down`},{rotation:270,upDir:`right`}].map(({rotation:n,upDir:r})=>{let a=e.lightness[r],o=-e.complexity[r],s=-e.chroma[r];return{rotation:n,score:LIGHTNESS_WEIGHT*a+COMPLEXITY_WEIGHT*o+CHROMA_WEIGHT*s,lightnessScore:a,complexityScore:o,chromaScore:s}})}async function computeGradientCanonicalOrientation(e){let{data:n,info:r}=await sharpToColorspaceBuffer(e.clone(),`float`,`lab`),{width:a,height:o}=r,s=computeDirectionalGradients(n,a,o),c=scoreRotations(s);c.sort((e,n)=>n.score-e.score);let l=c[0],u=c[1],d=l.score-u.score,f=Math.max(Math.abs(l.score),1),h=Math.min(1,Math.abs(d)/f);return{canonicalRotation:l.rotation,confidence:h,debug:{gradients:s,scores:c}}}var import_sharp7=__toESM(require("sharp")),ImageHashResizeOpts={fit:import_sharp7.default.fit.fill,kernel:import_sharp7.default.kernel.lanczos3},logger119=lazy2(()=>mkLogger(`color.Lab`));function calculateLabHue(e,n){let r=Math.atan2(n,e)*180/Math.PI;return r<0?r+360:r}function extractValidLabPixel(e,n){let r=e[n*3],a=e[n*3+1],o=e[n*3+2];return{L:isNaN(r)?50:Math.max(0,Math.min(100,r)),a:isNaN(a)?0:Math.max(-100,Math.min(100,a)),b:isNaN(o)?0:Math.max(-100,Math.min(100,o))}}function calculateAngularDistance(e,n){let r=(e%360+360)%360,a=(n%360+360)%360;return Math.min(Math.abs(r-a),Math.abs(r-a+360),Math.abs(r-a-360))}var SEPIA_CENTER_HUE=67,SEPIA_HUE_RANGE=40,SEPIA_MIN_HUE=SEPIA_CENTER_HUE-SEPIA_HUE_RANGE/2,SEPIA_MAX_HUE=SEPIA_CENTER_HUE+SEPIA_HUE_RANGE/2,VARIANCE_THRESHOLD=5,CHROMA_THRESHOLD=3,HISTORICAL_VARIANCE_THRESHOLD=50,SEPIA_CHROMA_THRESHOLD=21,SEPIA_VARIANCE_THRESHOLD=10,DEFAULT_RESIZE=64;async function isMonochrome(e,n={}){let{isHistorical:r=!1}=n,{data:a,info:o}=await sharpToColorspaceBuffer(sharpResize(e,{width:DEFAULT_RESIZE,height:DEFAULT_RESIZE,fit:`fill`}),`float`,`lab`),s=o.width*o.height,c=a,l=0,u=0,d=0,f=0;for(let e=0;e<s;e++){let{a:n,b:r}=extractValidLabPixel(c,e);l+=n,u+=r}let h=l/s,_=u/s,y=Math.sqrt(h*h+_*_),x=null;x=y<1e-6?null:calculateLabHue(h,_);let C=x!==null&&x>=SEPIA_MIN_HUE&&x<=SEPIA_MAX_HUE,{variance:w,chroma:T,mode:E}=getThresholds(r,C);for(let e=0;e<s;e++){let{a:n,b:r}=extractValidLabPixel(c,e),a=n-h,o=r-_,s=a*a+o*o;d+=s,calculateAngularDistance(calculateLabHue(n,r),SEPIA_CENTER_HUE)<=SEPIA_HUE_RANGE/2&&f++}let D=d/s,O=f/s,k=Math.sqrt(D+y*y),A=generateExplanation({mse:D,meanChroma:k,varianceThreshold:w,chromaThreshold:T,isLikelySepia:C,sepiaSimilarity:O,dominantHue:x,mode:E}),j=A.isMonochromatic,M=A.explanation;return{isMonochromatic:j,dominantHue:x,meanChroma:k,mse:D,sepiaSimilarity:O,explanation:M,mode:E}}function getThresholds(e,n){return e?{variance:HISTORICAL_VARIANCE_THRESHOLD,chroma:SEPIA_CHROMA_THRESHOLD,mode:`historical`}:n?{variance:SEPIA_VARIANCE_THRESHOLD,chroma:SEPIA_CHROMA_THRESHOLD,mode:`modern`}:{variance:VARIANCE_THRESHOLD,chroma:CHROMA_THRESHOLD,mode:`modern`}}function generateExplanation(e){let{mse:n,meanChroma:r,varianceThreshold:a,chromaThreshold:o,isLikelySepia:s,sepiaSimilarity:c,dominantHue:l,mode:u}=e,d=n<=a&&r<=o,f=d?`Monochrome`:`Color`,h=s?`sepia`:u,_=`${f}: MSE=${n.toFixed(2)}, chroma=${r.toFixed(1)}, mode=${h}`;return d&&s?_+=`, sepia similarity=${(c*100).toFixed(0)}%`:d||(_+=n>a&&r>o?` (high variance and chroma)`:n>a?` (high variance: ${n.toFixed(2)} > ${a.toFixed(1)})`:` (high chroma: ${r.toFixed(1)} > ${o.toFixed(1)})`),l!==null&&(_+=`, hue=${l.toFixed(0)}\xB0`),{isMonochromatic:d,explanation:_}}var tableCache=new Map;function lookupTable(e){return getOrSet(tableCache,e,()=>createTable(e))}function createTable(e){let n=Array(e*2);for(let r=0;r<n.length;r+=2){let a=Math.PI*r/e;n[r]=Math.cos(a),n[r+1]=-Math.sin(a)}return tableCache.set(e,n),n}var FFT=class{size;_csize;table;_width;_bitrev;_out=null;_data=null;_inv=0;constructor(e){if(this.size=e|0,this.size<=1||this.size&this.size-1)throw Error(`FFT size must be a power of two and bigger than 1`);this._csize=e<<1,this.table=lookupTable(this.size);let n=0;for(let e=1;this.size>e;e<<=1)n++;this._width=n%2==0?n-1:n,this._bitrev=Array(1<<this._width);for(let e=0;e<this._bitrev.length;e++){this._bitrev[e]=0;for(let n=0;n<this._width;n+=2){let r=this._width-n-2;this._bitrev[e]|=(e>>>n&3)<<r}}}fromComplexArray(e,n,r){let a=n??(r==null?Array(e.length>>>1):new r(e.length>>>1));for(let n=0;n<e.length;n+=2)a[n>>>1]=e[n];return a}createComplexArray(e){if(e!=null){let n=new e(this._csize);for(let e=0;e<n.length;e++)n[e]=0;return n}let n=Array(this._csize);for(let e=0;e<n.length;e++)n[e]=0;return n}toComplexArray(e,n,r){let a=n??(r==null?this.createComplexArray():new r(this._csize));for(let n=0;n<a.length;n+=2)a[n]=e[n>>>1],a[n+1]=0;return a}completeSpectrum(e){let n=this._csize,r=n>>>1;for(let a=2;a<r;a+=2)e[n-a]=e[a],e[n-a+1]=-e[a+1]}transform(e,n){if(e===n)throw Error(`Input and output buffers must be different`);this._out=e,this._data=n,this._inv=0,this._transform4(),this._out=null,this._data=null}realTransform(e,n){if(e===n)throw Error(`Input and output buffers must be different`);this._out=e,this._data=n,this._inv=0,this._realTransform4(),this._out=null,this._data=null}inverseTransform(e,n){if(e===n)throw Error(`Input and output buffers must be different`);this._out=e,this._data=n,this._inv=1,this._transform4();for(let n=0;n<e.length;n++)e[n]/=this.size;this._out=null,this._data=null}_transform4(){let e=this._out,n=this._csize,r=1<<this._width,a=n/r<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<n;o+=a,s++){let e=c[s];this._singleTransform2(o,e,r)}else for(o=0,s=0;o<n;o+=a,s++){let e=c[s];this._singleTransform4(o,e,r)}let l=this._inv?-1:1,u=this.table;for(r>>=2;r>=2;r>>=2){a=n/r<<1;let s=a>>>2;for(o=0;o<n;o+=a){let n=o+s;for(let a=o,c=0;a<n;a+=2,c+=r){let n=a,r=n+s,o=r+s,d=o+s,f=e[n],h=e[n+1],_=e[r],y=e[r+1],x=e[o],C=e[o+1],w=e[d],T=e[d+1],E=f,D=h,O=u[c],k=l*u[c+1],A=_*O-y*k,j=_*k+y*O,M=u[2*c],N=l*u[2*c+1],P=x*M-C*N,F=x*N+C*M,I=u[3*c],R=l*u[3*c+1],z=w*I-T*R,B=w*R+T*I,H=E+P,U=D+F,W=E-P,G=D-F,K=A+z,q=j+B,J=l*(A-z),Y=l*(j-B),X=H+K,Z=U+q,Q=H-K,$=U-q,te=W+Y,ne=G-J,re=W-Y,ie=G+J;e[n]=X,e[n+1]=Z,e[r]=te,e[r+1]=ne,e[o]=Q,e[o+1]=$,e[d]=re,e[d+1]=ie}}}}_singleTransform2(e,n,r){let a=this._out,o=this._data,s=o[n],c=o[n+1],l=o[n+r],u=o[n+r+1],d=s+l,f=c+u,h=s-l,_=c-u;a[e]=d,a[e+1]=f,a[e+2]=h,a[e+3]=_}_singleTransform4(e,n,r){let a=this._out,o=this._data,s=this._inv?-1:1,c=r*2,l=r*3,u=o[n],d=o[n+1],f=o[n+r],h=o[n+r+1],_=o[n+c],y=o[n+c+1],x=o[n+l],C=o[n+l+1],w=u+_,T=d+y,E=u-_,D=d-y,O=f+x,k=h+C,A=s*(f-x),j=s*(h-C),M=w+O,N=T+k,P=E+j,F=D-A,I=w-O,R=T-k,z=E-j,B=D+A;a[e]=M,a[e+1]=N,a[e+2]=P,a[e+3]=F,a[e+4]=I,a[e+5]=R,a[e+6]=z,a[e+7]=B}_realTransform4(){let e=this._out,n=this._csize,r=1<<this._width,a=n/r<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<n;o+=a,s++){let e=c[s];this._singleRealTransform2(o,e>>>1,r>>>1)}else for(o=0,s=0;o<n;o+=a,s++){let e=c[s];this._singleRealTransform4(o,e>>>1,r>>>1)}let l=this._inv?-1:1,u=this.table;for(r>>=2;r>=2;r>>=2){a=n/r<<1;let s=a>>>1,c=s>>>1,d=c>>>1;for(o=0;o<n;o+=a)for(let n=0,a=0;n<=d;n+=2,a+=r){let r=o+n,f=r+c,h=f+c,_=h+c,y=e[r],x=e[r+1],C=e[f],w=e[f+1],T=e[h],E=e[h+1],D=e[_],O=e[_+1],k=y,A=x,j=u[a],M=l*u[a+1],N=C*j-w*M,P=C*M+w*j,F=u[2*a],I=l*u[2*a+1],R=T*F-E*I,z=T*I+E*F,B=u[3*a],H=l*u[3*a+1],U=D*B-O*H,W=D*H+O*B,G=k+R,K=A+z,q=k-R,J=A-z,Y=N+U,X=P+W,Z=l*(N-U),Q=l*(P-W),$=G+Y,te=K+X,ne=q+Q,re=J-Z;if(e[r]=$,e[r+1]=te,e[f]=ne,e[f+1]=re,n===0){let n=G-Y,r=K-X;e[h]=n,e[h+1]=r;continue}if(n===d)continue;let ie=q,ae=-J,oe=G,se=-K,ce=-l*Q,le=-l*Z,ue=-l*X,de=-l*Y,fe=ie+ce,pe=ae+le,me=oe+de,he=se-ue,ge=o+c-n,_e=o+s-n;e[ge]=fe,e[ge+1]=pe,e[_e]=me,e[_e+1]=he}}}_singleRealTransform2(e,n,r){let a=this._out,o=this._data,s=o[n],c=o[n+r],l=s+c,u=s-c;a[e]=l,a[e+1]=0,a[e+2]=u,a[e+3]=0}_singleRealTransform4(e,n,r){let a=this._out,o=this._data,s=this._inv?-1:1,c=r*2,l=r*3,u=o[n],d=o[n+r],f=o[n+c],h=o[n+l],_=u+f,y=u-f,x=d+h,C=s*(d-h),w=_+x,T=y,E=-C,D=_-x,O=y,k=C;a[e]=w,a[e+1]=0,a[e+2]=T,a[e+3]=E,a[e+4]=D,a[e+5]=0,a[e+6]=O,a[e+7]=k}};function dct1d(e){let n=e.length,r=new FFT(n*2),a=new Float64Array(n*2);for(let r=0;r<n;r++)a[r]=e[r],a[2*n-1-r]=e[r];let o=r.createComplexArray();r.realTransform(o,a);let s=new Float64Array(n);s[0]=o[0];for(let e=1;e<n;e++)s[e]=o[2*e];return s}function dct2d(e,n){let r=new Float64Array(e.length),a=new Float64Array(n);for(let o=0;o<n;o++)e.subarray(o*n,(o+1)*n).forEach((e,n)=>a[n]=e),dct1d(a).forEach((e,a)=>r[o*n+a]=e);let o=new Float64Array(e.length);for(let e=0;e<n;e++){for(let o=0;o<n;o++)a[o]=r[o*n+e];dct1d(a).forEach((r,a)=>o[a*n+e]=r)}return o}function deinterleaveTypedArray(e,n){let r=[],a=Math.floor(e.length/n);for(let o=0;o<n;o++){let s=e.constructor,c=new s(a);for(let r=0;r<a;r++)c[r]=e[r*n+o];r.push(c)}return r}var HASH_SIZE=8,HIGHFREQ_FACTOR=4,DIM=HASH_SIZE*HIGHFREQ_FACTOR;function compute_pHash(e){let n=HASH_SIZE*HIGHFREQ_FACTOR,r=dct2d(Float64Array.from(e),n),a=new Float64Array(HASH_SIZE*HASH_SIZE),o=0;for(let e=0;e<HASH_SIZE;e++)for(let s=0;s<HASH_SIZE;s++)a[o++]=r[e*n+s];let s=[...a].sort((e,n)=>e-n),c=s[Math.floor(s.length*.2)],l=s[Math.floor(s.length*.4)],u=s[Math.floor(s.length*.6)],d=s[Math.floor(s.length*.8)],f=Array(HASH_SIZE*HASH_SIZE);for(let e=0;e<a.length;e++){let n=a[e];n<=c?f[e]=0:n<=l?f[e]=1:n<=u?f[e]=2:n<=d?f[e]=3:f[e]=4}let h=Array(HASH_SIZE*HASH_SIZE);for(let e=0;e<a.length;e++){let n=e<a.length/2?2:2.5;h[e]=+(f[e]>=n)}return h}function resize(e){return sharpResize(e,{width:DIM,height:DIM,...ImageHashResizeOpts})}async function pHash(e){return b64encodeBitsFixedWidth(compute_pHash(await resize(e.clone().greyscale()).raw().toBuffer()),64)}async function pHashCIELAB(e){let{data:n}=await sharpToColorspaceBuffer(resize(e.clone()),`char`);return b64encodeBitsFixedWidth(deinterleaveTypedArray(n,3).flatMap(compute_pHash),192)}var DIM2=8;function compute_rHash(e){let n=Array(DIM2*DIM2),r=0,a=DIM2+2;for(let o=1;o<=DIM2;o++)for(let s=1;s<=DIM2;s++){let c=o*a+s,l=(e[c-1]+e[c+1]+e[c-a]+e[c+a])/4;n[r++]=+(l>e[c])}return n}function resize2(e){return sharpResize(e,{width:DIM2+2,height:DIM2+2,...ImageHashResizeOpts})}async function rHash(e){return b64encodeBitsFixedWidth(compute_rHash(await resize2(e.clone().greyscale()).raw().toBuffer()),64)}async function rHashCIELAB(e){let{data:n}=await sharpToColorspaceBuffer(resize2(e.clone()),`char`);return b64encodeBitsFixedWidth(deinterleaveTypedArray(n,3).flatMap(compute_rHash),192)}var import_sharp8=__toESM(require("sharp")),HASH_SIZE2=8,HIGHFREQ_FACTOR2=4,DIM3=HASH_SIZE2*HIGHFREQ_FACTOR2,removeMaxLL=!0;function compute_wHash(e){let n=Float64Array.from(e);if(removeMaxLL){let e=n.reduce((e,n)=>e+n,0)/n.length;for(let r=0;r<n.length;r++)n[r]-=e}let r=DIM3;for(;r>HASH_SIZE2;){let e=r>>1,a=new Float64Array(e*e);for(let o=0;o<e;o++)for(let s=0;s<e;s++){let c=2*o*r+2*s,l=n[c],u=n[c+1],d=n[c+r],f=n[c+r+1];a[o*e+s]=(l+u+d+f)*.25}n=a,r=e}let a=Array.from(n),o=[...a].sort((e,n)=>e-n)[a.length>>1],s=0n;for(let e of a)s=s<<1n|(e>o?1n:0n);return s}async function wHashBigint(e){return compute_wHash(await sharpResize(e.greyscale(),{width:DIM3,height:DIM3,fit:import_sharp8.default.fit.fill,kernel:import_sharp8.default.kernel.nearest}).raw().toBuffer())}async function wHash(e){return b64encodeBigIntFixedWidth(await wHashBigint(e),64)}async function wHashCIELAB(e){let{data:n}=await sharpToColorspaceBuffer(sharpResize(e,{width:DIM3,height:DIM3,...ImageHashResizeOpts}),`char`),[r,a,o]=deinterleaveTypedArray(n,3),s=compute_wHash(r),c=compute_wHash(a),l=compute_wHash(o);return b64encodeBigIntFixedWidth(s<<128n|c<<64n|l,192)}var logger120=defer(()=>mkLogger(`img.ImageHashes`)),RATIO_EPSILON=.1,WRITE_SQUARES=!1,MonochromeHashes={pHash,rHash,wHash},ColorHashes={pHash:pHashCIELAB,rHash:rHashCIELAB,wHash:wHashCIELAB};async function buildHashRecord(e,n,r=0){return time({name:`img.buildHashRecord`,p:async()=>{let a=r===0?e:sharpAddRotation(e.clone(),r),o=n?MonochromeHashes:ColorHashes,s=await Promise.all(entries(o).map(async([e,n])=>[e,await n(a.clone())]));return logger120().tap({msg:`buildHashRecord()`,result:fromEntries(s),meta:{rotation:r,monochrome:n}})}})}var ImageHashes=class e{#e;src;sr;static assetHashes_=shim({name:`img.assetHashes`,cache:lazy2(()=>new Cache({name:`ImageHashFields`})),toKey:e=>toNativePath_(e),stamp:e=>fileStamp(toNativePath_(e)),impl:async n=>{var r=[];try{return await __using(r,new e(n)).assetHashes_()}catch(e){var a=e,o=!0}finally{__callDispose(r,a,o)}}});constructor(e){this.src=PosixFile.for(e),this.#e=logger120().child(`: `+this.src.baseWithGrandparent),this.sr=new SharpReadable({src:this.src,minDim:{width:64,height:64},skipEmbedded:!1})}[Symbol.dispose](){this.#t.unset(),this.sr[Symbol.dispose]()}toLogJSON(){return{_ctor:`ImageHashes`,src:this.src.nativePath}}sizeInfo_(){return this.sr.sizeInfo_()}mimetype_(){return this.sr.mimetype_()}#t=lazy2(async()=>sharpClone(sharpResize(await this.sr.sharp_(),{width:96,height:96,...ImageHashResizeOpts})),2*minuteMs);async writeSq(e){return(await this.#t()).clone().png({quality:100,compressionLevel:9}).toFile(e.nativePath)}assetHashes_=defer(async()=>{let e=await this.#t(),n=(await isMonochrome(e)).isMonochromatic,r=await this.sr.sizeInfo_();if(WRITE_SQUARES){let e=tmpFileName(this.src.baseWithParent.replace(/\//g,`_`)+`-`+randomChars(4)+`.png`);await this.writeSq(e),console.log(`Wrote image square`,{src:this.src.baseWithGrandparent,dest:e.nativePath})}let a=await buildHashRecord(e,n,0),o=(await computeGradientCanonicalOrientation(e.clone())).canonicalRotation,s=o===0?{}:await buildHashRecord(e,n,o);return{mimetype:await this.mimetype_(),monochrome:n,...a,...hashRecordToHashRecord0(s),canonicalRotation:o,...r.dimensions}});searchHashes=defer(async()=>{let e=await this.assetHashes_(),n=await this.#t(),r=e.monochrome;return[{rotation:0,hashes:e},...await Promise.all([90,180,270].map(async e=>({rotation:e,hashes:await buildHashRecord(n.clone(),r,e)})))]});async searchHashArrays(){let e=await this.searchHashes();return fromEntries(ImageHashTypes.values.map(n=>[n,e.flatMap(e=>e.hashes[n])]))}async compare(n,r){let a=n instanceof e?await n.assetHashes_():n,o=await this.mimetype_(),s=!blank(o)&&!blank(a.mimetype)&&o===a.mimetype;r??=(s?Settings2.imageHashThresholdPct.valueOrDefault:Settings2.imageHashCrossFormatThresholdPct.valueOrDefault)/100;let c=await this.sizeInfo_();if(r>0&&!similarRatios(c.dimensions,a,RATIO_EPSILON)&&!similarRatios(c.dimensions,toRatio(a,90),RATIO_EPSILON))return this.#e.debug(`compare(): aspect ratios are too different to be similar images`,{this:this.src.nativePath,this_dim:c.dimensions,other_dim:pickDims(a)}),{sameMimetype:s,details:`aspect ratios are too different`};let l=await this.assetHashes_(),u=(l.monochrome??!1)||(a.monochrome??!1),d={rotation:0,...compareHashRecords(l,a,u)};if(this.#e.debug(`compare()`,{comparison:d}),r>0&>e2(d.confidence,r))return this.#e.tap({msg:`compare()`,result:{details:`images with current rotation are similar enough`,result:d,comparisons:[d],monochrome:u,sameMimetype:s,confidenceThreshold:r}});let f=[d];for(let{rotation:e,hashes:n}of await this.searchHashes())f.push({rotation:e,...compareHashRecords(n,a,u)});let h=greatestBy(f,e=>gte2(e.confidence,r)?[e.confidence,e.rotation]:void 0),_=f.map(fmtConfidence).join(`, `),y=h==null?`No rotation produced similar image hashes: `+_:fmtConfidence(h);return this.#e.tap({msg:`compare()`,result:{result:h,details:y,monochrome:u,sameMimetype:s,confidenceThreshold:r,comparisons:f}})}};function fmtConfidence(e){return`${e.rotation}\xB0 = ${fmtPct(e.confidence*100)}`}function fileStatFieldsFromListing(e,n){let r=[e,...listedSidecarsOf(e,n)].map(e=>e.mtimeMs());return{fileSize:e.size(),mtime:Math.floor(max3(r))}}var MediaInfoFactory=class e{constructor(e){this.f=e,this.#t=mkLogger(`sync-file.MediaInfoFactory(`+this.f.nativePath+`)`)}f;static#e=new FileCache({name:`MediaInfoFactory`,clearOnFileChange:!0});#t;static for(n){return this.#e.getOrSet(toNativePath_(n),()=>new e(PosixFile.for(n)))}async pick(...e){let n={};for(let r of e)n[r]=await this[r];return n}asMediaInfo_(){return excludeWaitFromEnclosingTimer(()=>this.#n())}#n=defer(async()=>{if(await this.f.stat_()==null)throw Error(`Failed to stat file: `+this.f.nativePath);let[e,n,r,a]=await Promise.all([this.fileStatFields_(),ImageHashes.assetHashes_(this.f.nativePath),this.mediaInfoFromTags_(),this.sha]);return{nativePath:this.nativePath,uri:await this.uri,basename:this.basename,...e,sha:a,...r,...n}});fileStatFields_=defer(async()=>{let e=await this.f.stat_();return{fileSize:e.size,mtime:Math.floor(await this.f.thisOrSidecarMaxMtimeMs()??e.mtimeMs)}});mediaInfoFromTags_=defer(async()=>{try{let e=await readTags(this.f);if(e==null)throw Error(`Failed to read tags`);if(e.capturedAt==null)throw Error(`Failed to read capturedAt`);let n=e.capturedAt.toCapturedAtFields();return n==null?this.#t.throw(`Failed to render assetFileFields from capturedAt`,{capturedAt:e.capturedAt}):{...omit(n,`capturedAtRaw`),...e.exposureSettings,...e.dimensions,...pick(e,`mimetype`,`rotation`,`metadataDate`,`make`,`model`,`rating`,`cameraId`,`imageId`,`lensId`,`latitude`,`longitude`,`durationMs`,`fps`)}}catch(e){return this.#t.throw(`readMediaInfoFromTags failed`,{error:e})}});get basename(){return this.f.base}get nativePath(){return this.f.nativePath}get uri(){return this.f.uri_()}get mtime(){return this.fileStatFields_().then(e=>e.mtime)}get fileSize(){return this.fileStatFields_().then(e=>e.fileSize)}get capturedAtLocal(){return this.mediaInfoFromTags_().then(e=>e.capturedAtLocal)}get capturedAtZone(){return this.mediaInfoFromTags_().then(e=>e.capturedAtZone)}get capturedAtPrecisionMs(){return this.mediaInfoFromTags_().then(e=>e.capturedAtPrecisionMs)}get capturedAtSrc(){return this.mediaInfoFromTags_().then(e=>e.capturedAtSrc)}get capturedAtSrcDetail(){return this.mediaInfoFromTags_().then(e=>e.capturedAtSrcDetail)}get capturedAtZoneSrc(){return this.mediaInfoFromTags_().then(e=>e.capturedAtZoneSrc)}get width(){return this.mediaInfoFromTags_().then(e=>e.width)}get height(){return this.mediaInfoFromTags_().then(e=>e.height)}get sha(){return this.f.sha_()}get rotation(){return this.mediaInfoFromTags_().then(e=>e.rotation)}get mimetype(){return this.mediaInfoFromTags_().then(e=>e.mimetype)}get monochrome(){return this.assetImageHashes_().then(e=>e.monochrome)}get metadataDate(){return this.mediaInfoFromTags_().then(e=>e.metadataDate??this.mtime)}get rating(){return this.mediaInfoFromTags_().then(e=>e.rating)}get latitude(){return this.mediaInfoFromTags_().then(e=>e.latitude)}get longitude(){return this.mediaInfoFromTags_().then(e=>e.longitude)}get make(){return this.mediaInfoFromTags_().then(e=>e.make)}get model(){return this.mediaInfoFromTags_().then(e=>e.model)}get cameraId(){return this.mediaInfoFromTags_().then(e=>e.cameraId)}get imageId(){return this.mediaInfoFromTags_().then(e=>e.imageId)}get lensId(){return this.mediaInfoFromTags_().then(e=>e.lensId)}get focalLength(){return this.mediaInfoFromTags_().then(e=>e.focalLength)}get aperture(){return this.mediaInfoFromTags_().then(e=>e.aperture)}get shutterSpeed(){return this.mediaInfoFromTags_().then(e=>e.shutterSpeed)}get iso(){return this.mediaInfoFromTags_().then(e=>e.iso)}get durationMs(){return this.mediaInfoFromTags_().then(e=>e.durationMs)}get fps(){return this.mediaInfoFromTags_().then(e=>e.fps)}assetImageHashes_=defer(()=>ImageHashes.assetHashes_(this.f.nativePath));get pHash(){return this.assetImageHashes_().then(e=>e.pHash)}get rHash(){return this.assetImageHashes_().then(e=>e.rHash)}get wHash(){return this.assetImageHashes_().then(e=>e.wHash)}get pHash0(){return this.assetImageHashes_().then(e=>e.pHash0)}get rHash0(){return this.assetImageHashes_().then(e=>e.rHash0)}get wHash0(){return this.assetImageHashes_().then(e=>e.wHash0)}};async function whyIsMediaInfoStale(e,n,r){if(e.forceSync)return`forceSync`;let a=[];if(gt0(n.id)||a.push(`id`),gt0(n.assetId)||a.push(`assetId`),blank(n.uri)&&a.push(`uri`),blank(n.basename)&&a.push(`basename`),n.fileSize??a.push(`fileSize`),n.mtime??a.push(`mtime`),blank(n.mimetype)&&a.push(`mimetype`),gt0(n.width)||a.push(`width`),gt0(n.height)||a.push(`height`),blank(n.sha)&&a.push(`sha`),gt0(n.capturedAtLocal)||a.push(`capturedAtLocal`),a.length>0)return`missing fields: `+a.join(`, `);{let e=await r.fileSize;if(!isEquivalentNumber(n.fileSize,e,Settings2.fileSizeEpsilon.valueOrDefault))return`file size changed since last sync: `+stringify({prior:n.fileSize,current:e,fileSizeEpsilon:Settings2.fileSizeEpsilon.valueOrDefault})}{let e=await r.mtime;if(!isEquivalentNumber(n.mtime,e,Settings2.mtimeMsEpsilon.valueOrDefault))return`file mtime changed since last sync: `+stringify({prior:n.mtime,current:e,mtimeMsEpsilon:Settings2.mtimeMsEpsilon.valueOrDefault})}}var import_node_path63=__toESM(require("node:path")),import_node_path62=__toESM(require("node:path"));function hostPathFor(e){let n=max(Settings2.hostPaths.entries().filter(([,n])=>containedByNativePath({ancestor:n,descendant:e,acceptSelf:!0})),([,e])=>import_node_path62.default.resolve(e).length);if(n==null)return;let[r,a]=n;return import_node_path62.default.join(r,import_node_path62.default.relative(a,e))}function fileBrowserFolderUrl(e){let n=hostPathFor(e);if(n==null)return;let r=max(Settings2.fileBrowserUrls.entries().filter(([e])=>containedByNativePath({ancestor:e,descendant:n})),([e])=>import_node_path63.default.resolve(e).length);if(r==null)return;let[a,o]=r,s=import_node_path63.default.relative(a,import_node_path63.default.dirname(n)).split(import_node_path63.default.sep).filter(e=>e!==``);return[o.replace(/\/+$/,``),...s.map(encodeURIComponent)].join(`/`)}function tagPathHead(e){if(e.scheme===PS_LIBRARY_SCHEME)return[LibraryTagName];if(e.scheme===PS_LOCAL_FILE_SCHEME)return blank(e.authority)?void 0:[e.authority];if(e.scheme===PLAIN_FILE_SCHEME&&anyUriSchemeDisabled())return[]}function originalsLibraryTagPath({uri:e,isFile:n}){if(toURI(e).scheme===PS_LIBRARY_SCHEME)return;let r=libraryRelativePath(e);if(r==null)return;let a=r.split(`/`);return compactBlanks([TagRoots.fs,LibraryTagName,...n?a.slice(0,-1):a])}function uriToTagPath({uri:e,isFile:n}){if(e==null)return;let r=toURI(e),a=tagPathHead(r);if(a==null)return;let o=r.path.split(`/`);return compactBlanks([TagRoots.fs,...a,...n?o.slice(0,-1):o])}var import_node_util18=require("node:util");function pojoKeys(e){if(e?.constructor?.name==null)return Object.keys(e);let n=new Set,r=e,a=new Set;for(;r!==null&&r!==Object.prototype;){let e=Object.getOwnPropertyDescriptors(r);for(let[r,o]of Object.entries(e))a.has(r)||(a.add(r),!r.startsWith(`$`)&&(!o.get||o.set)&&typeof o.value!=`function`&&(!o.get&&!o.set&&o.enumerable===!0||o.get&&o.set)&&n.add(r));r=Object.getPrototypeOf(r)}return[...n]}function toPojo(e,n){let r={},a=n?.undefinedToNull??!1;for(let o of n?.fieldNames??pojoKeys(e)){if(n?.omitKey?.(o)===!0||n?.omitKeys?.includes(o)===!0)continue;let s=e[o];s===void 0?a&&(r[o]=null):isDated(s)?r[o]=datedToMillis(s):n?.convertBooleanToInt===!0&&typeof s==`boolean`?r[o]=+!!s:(s==null||isPrimitive(s))&&(r[o]=s)}return r}var SafeRe=/^\w+$/;function dbValueToEscapedString(e){if(isNumber(e))return e.toString();let n=toS(e);return SafeRe.test(n)?n:`'${n.replace(/'/g,`''`)}'`}function escapeIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}var CommentRe=/--.*$/gm,WhitespaceRe=/\s+/g;function normalizeSql(...e){return compactBlanks(e).join(`
|
|
672
|
+
`).replace(CommentRe,``).replace(WhitespaceRe,` `).trim()}function patternSortOrderCase(e,n){if(n.length===0)return`1`;let r=escapeIdentifier(e);return`CASE ${n.map((e,n)=>{if(e.includes(`*`)||e.includes(`?`)){let a=e.replace(/'/g,`''`).replace(/\\/g,`\\\\`).replace(/%/g,`\\%`).replace(/_/g,`\\_`).replace(/\*/g,`%`).replace(/\?/g,`_`);return`WHEN ${r} LIKE '${a}' ESCAPE '\\' THEN ${n+1}`}{let a=e.replace(/'/g,`''`);return`WHEN ${r} = '${a}' THEN ${n+1}`}}).join(` `)} ELSE ${n.length+1} END`}var ReportedCounters=[`fullscanStep`,`sort`,`autoindex`,`vmStep`];function statementStats(e){let n={};for(let r of ReportedCounters)n[r]=e.stat(r);return n}function isDbValue(e){let n=typeof e;return n===`number`||n===`string`||n===`boolean`}function isMaybeNullDbValue(e){return e==null||isDbValue(e)}function isDbValued(e){return e!=null&&Array.isArray(e)?e.every(isDbValued):values(e).every(isMaybeNullDbValue)}var logger121=defer(()=>mkLogger(`db.SqlQuery`));function isSqlQuery(e){return e!=null&&isString(e.sql)&&(e.bindings==null||isDbValued(e.bindings))}function sqlBindingArgs(e){return e==null?[]:Array.isArray(e)?e.map(e=>e===void 0?null:e):[e]}function assertValidBindings(e){if(Array.isArray(e))for(let n=0;n<e.length;n++)isMaybeNullDbValue(e[n])||logger121().throw(`invalid bindings`,{bindings:e,invalid:e.filter(e=>!isMaybeNullDbValue(e))});else isDbValued(e)||logger121().throw(`invalid bindings`,{bindings:e})}function toSqlQuery(e){if(e==null)return logger121().throw(`toSqlQuery(): null query`);if(isString(e))return{sql:e};if(isSqlQuery(e))return e;let n=pick(e.toSQL?.()??e,`sql`,`bindings`,`method`);if(assertValidBindings(n.bindings),isSqlQuery(n))return n;throw Error(`not queryish: `+stringify(e))}function sqlWhereInJsonClauseNamed(e){return`(SELECT value from json_each(:${e}))`}function sqlWhereInClause(e){return`(`+times(e,()=>`?`).join(`,`)+`)`}var SlowQueryThresholdMs=100,DbRequest=class{logger=defer(()=>mkLogger(`db.`+this.tableName));db;tableName;#e;constructor(e){this.db=e.db,this.tableName=e.tableName,this.#e=new Cache({name:`db.`+this.tableName,maxSize:250}),isNotEmpty(e.primaryKeys)&&this.primaryKeys.set([...e.primaryKeys]),isNotEmpty(e.businessKeys)&&this.businessKeys.set([...e.businessKeys]),this.db()?.onClose?.(()=>this.#e.clear())}columnNames=lazy(()=>{let e=this.db().tableInfo_().find(e=>equalsIgnoreCase(e.tableName,this.tableName));return e==null?this.logger().throw(`columnNames(): table not found`,{tableName:this.tableName,retriable:!1}):e.columns.map(e=>e.name)});qb(){return knex()(this.tableName)}#t(e,n=!1){let r=toSqlQuery(e);try{let e=this.db();if(e==null)throw Error(isTest()?`Database already disposed (test teardown)`:`Database is unexpectedly null`);let a=this.#e.getOrSet(e.db.$uid+`:`+(n===!0?`pluck:`:``)+r.sql,()=>{let a=e.prepare(r.sql);return n===!0?a.pluck():a});if(e.db.isOpen)return{sq:r,stmt:a};throw this.#e.clear(),Error(`Database is closed`)}catch(e){return this.logger().throw(`prep() failed`,{error:e,sqlQuery:r,retriable:!1})}}#n({q:e,pluck:n,method:r}){try{let{sq:a,stmt:o}=this.#t(e,n);Settings2.logSql.valueOrDefault&&this.logger().trace(r+`()`,a);let s=o[r].bind(o);o.resetStats();let c=performance.now();try{return s(...sqlBindingArgs(a.bindings))}finally{let e=performance.now()-c;pushTime({name:`sql.`+this.tableName+`.`+r,elapsedMs:e}),e>SlowQueryThresholdMs&&this.logger().warn(`slow query`,{method:r,elapsedMs:roundMs(e),sql:a.sql,...statementStats(o)})}}catch(n){this.logger().throw(n,{method:r,...toSqlQuery(e)})}}primaryKeys=lazy(()=>{let e=this.all({sql:`PRAGMA table_info(${dbValueToEscapedString(this.tableName)})`}),n=e.filter(e=>isTrue(e.pk)).map(e=>e.name);if(isNotEmpty(n))return sort(n);let r=this.all({sql:`PRAGMA foreign_key_list(${dbValueToEscapedString(this.tableName)})`}),a=e.filter(e=>isTrue(e.notnull)).map(e=>e.name),o=intersection(r.map(e=>e.from),a);return isNotEmpty(o)?sort(o):this.logger().throw(`primaryKeys() failed`,{tableInfo:e,foreignKeyList:r,retriable:!1})});businessKeys=lazy(()=>{let e=this.all({sql:`PRAGMA index_list(${dbValueToEscapedString(this.tableName)})`}),n=[];for(let r of e.filter(e=>isTrue(e.unique))){let e=this.all({sql:`PRAGMA index_info(${dbValueToEscapedString(r.name)})`});n.push(...e.map(e=>e.name))}return toNotEmpty(sort(uniq(n)))??this.primaryKeys()});immutableKeys=lazy(()=>uniq(this.primaryKeys(),this.businessKeys(),intersection([`createdAt`],this.columnNames())));pickModelUcn(e){return pickRequired(e,...this.primaryKeys())??pickRequired(e,...this.businessKeys())}modelSupportsUpsert=lazy(()=>!eql(this.businessKeys(),[`id`]));modelSupportsUpdate=lazy(()=>eql(this.primaryKeys(),[`id`]));upsert(e){for(let n of e)this.upsertOne(n)}upsertOne(e){let n=sort(intersection(this.columnNames(),keysWithDefinedOrNullValues(e))),r=diff(n,this.immutableKeys());if(this.modelSupportsUpdate()&&this.primaryKeys().every(n=>e[n]!=null)&&!isEmptyObj(r))return{method:`update`,runResult:this.runf(n=>n.where(pick(e,...this.primaryKeys())).update(pick(e,...r)))};let a=intersection(n,this.businessKeys()),o=normalizeSql(`INSERT INTO `+this.tableName,`(`+n.join(`,`)+`)`,`VALUES (`+n.map(e=>`:`+e).join(`,`)+`)`,`ON CONFLICT(`+a.join(`,`)+`) DO`,isEmpty(r)?`NOTHING`:`UPDATE SET `+r.map(e=>`${e} = excluded.${e}`).join(`, `));return{method:`upsert`,runResult:this.run({sql:o,bindings:pick(e,...n)})}}run(e){return this.#n({q:e,method:`run`})}runScript(e){for(let n of e)blank(n)||n.trim().startsWith(`--`)||this.run({sql:n})}txn(e){let n=this.db();if(n==null)throw Error(`txn: database not available`);return n.db.transaction(e).immediate()}mapRun(e){return e.map(e=>this.run(e))}runf(e){return this.#n({q:e(this.qb()),method:`run`})}first(e){return this.#n({q:e,method:`get`})}firstf(e){return this.#n({q:e(this.qb()),method:`get`})}mapAll(e){return flatten(e.map(e=>this.all(e)))}all(e){return this.#n({q:e,method:`all`})}allf(e){return this.#n({q:e(this.qb()),method:`all`})}async*batched(e){let n;for(;;){if(ending()||(await e.runLatch?.(),ending()))return;let r=e.maxBatchSize();if(r<1)throw Error(`maxBatchSize must be > 0`);let a=e.qb(this.qb()).orderBy(e.primaryColumn,`asc`).limit(r);n!=null&&a.andWhere(e.primaryColumn,`>`,n);let o=this.#n({q:a,method:`all`});if(isEmpty(o))break;yield o,n=max2(o.map(e.rowToId))}}pluckFirst(e){return this.#n({q:e,pluck:!0,method:`get`})}pluckFirstf(e){return this.#n({q:e(this.qb()),pluck:!0,method:`get`})}count(e){return this.pluckFirstf(n=>e(n).count())}pluckAll(e){return this.#n({q:e,pluck:!0,method:`all`})}pluckAllf(e){return this.#n({q:e(this.qb()),pluck:!0,method:`all`})}async*pluckBatched(e){let n;for(;;){if(ending()||(await e.runLatch?.(),ending()))return;let r=e.maxBatchSize();if(r<1)throw Error(`maxBatchSize must be > 0`);let a=e.qb(this.qb()).select(e.pluckedColumn).distinct().orderBy(e.pluckedColumn,`asc`).limit(r);n!=null&&a.andWhere(e.pluckedColumn,`>`,n);let o=this.#n({q:a,pluck:!0,method:`all`});if(isEmpty(o))break;yield o,n=max2(o)}}insertOrReplaceBatch(e){if(isEmpty(e))return;let n=keysWithDefinedOrNullValues(e[0]),r=normalizeSql(`INSERT OR REPLACE INTO `+this.tableName,`(`+n.join(`,`)+`)`,`SELECT `,n.map(e=>`json_extract(value, '$.`+e+`')`).join(`,`),`FROM json_each(?)`);return this.run({sql:r,bindings:[stringify(e)]})}},ModelOps=class{constructor(e,n){this.model=e,this.db=n;let r=`ModelOps(${e.$tableName})`;this.#e=mkLogger(r),this.dbl=new DbRequest({db:this.db,tableName:e.$tableName,primaryKeys:e.$primaryKeys,businessKeys:e.$businessKeys})}model;db;dbl;#e;assignFromPojo(e,n){let r=e;if(n==null||r===n)return e;let a=n,o=this.dbl.businessKeys(),s=this.model.$booleanFields??[];for(let n of sortBy(keys(a),e=>[e!==`uri`,e])){let c=a[n];if(c!==void 0){if(isObject(c))this.#e.debug(`assignFromPojo(): ignoring non-primitive value`,{k:n,v:c,dest:e});else if(n!==`uri`||typeof e.setUri!=`function`)try{o.includes(n)?r[n]??=c:r[n]=s.includes(n)?c==null?c:isTrue(c):c}catch(e){if(e instanceof TypeError&&e.message.includes(`Cannot set property`)){this.#e.debug(`assignFromPojo(): skipping getter-only property`,{k:n,v:c,error:e.message});continue}throw e}}}return e}$pickPrimaryKeys(e){return pickRequired(e,...this.dbl.primaryKeys())}$pickBusinessKeys(e){return pickRequired(e,...this.dbl.businessKeys())}updatableColumnNames=lazy2(()=>diff(this.dbl.columnNames(),[...this.dbl.primaryKeys(),...this.dbl.businessKeys()]));columnNames(){return this.dbl.columnNames()}query(){return this.model.query()}fromJSON(e){if(!isEmptyObj(e))return this.model.fromJSON(e)}fromJSONs(e){return compact(e.map(e=>this.fromJSON(e)))}all(e=this.query()){return this.fromJSONs(this.dbl.all(e))}allf(e){return this.all(e(this.query()))}findOnef(e){return this.findOne(e(this.query()))}findOne(e){return this.fromJSON(this.dbl.first(e))}findOneBy(e){return this.findOne(this.model.query().where(e))}findById(e,n){return gt0(e)?this.findOneBy({...n,id:e}):void 0}findByIds(e){e=toA(e).filter(gt0);let n=batches(e,Settings2.dbBatchSelectSize.valueOrDefault).map(e=>this.dbl.all(this.query().whereIn(`id`,e)));return sortBy(this.fromJSONs(flatten(n)),n=>e.indexOf(n.id))}findBy(e){return this.all(this.model.query().where(e))}rows(e){return this.count(e??this.model.query().count())}count(e){return toGt0(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return toA(e).map(e=>this.insertOne(e))}upsertOne(e){if(!this.dbl.modelSupportsUpsert())return this.insertOrUpdateOne(e);let n=this.fromJSON(e);if(n==null)return this.#e.throw(`upsertOne(): fromJSON returned null`+InternalErrorFlag,{t:e});n.$beforeSave();let r=this.dbl.upsertOne(this.toDbJson(n)),a=toGt0(r.runResult.lastInsertRowid);return eql(this.dbl.primaryKeys(),[`id`])&&n.id==null&&a!=null&&(this.#e.debug(`upsertOne(): assigned .id`,{lastInsertRowid:a}),n.id=a),r.method===`upsert`&&this.reloadOne(n),n.$afterSave(),this.#e.tap({msg:`upsertOne()`,result:n,meta:{input:e}})}insertOrUpdateOne(e){return pickRequired(e,...this.dbl.primaryKeys())==null?this.insertOne(e):this.updateOne(e)}insertOne(e){let n=this.fromJSON(e);if(n==null)return this.#e.throw(`insertOne(): fromJSON returned null`+InternalErrorFlag,{t:e});n.$beforeSave();let r=n.$toDbJSON(this.columnNames()),a=this.dbl.runf(e=>e.insert(r));return this.dbl.primaryKeys().includes(`id`)?n.id=toGt0(a.lastInsertRowid):n=this.reloadOne(n),n.$afterSave(),this.#e.tap({msg:`insertOne()`,result:n,meta:{input:e}})}unsetField(e,n){return this.#e.debug(`unsetField()`,{id:e,fieldName:n}),this.dbl.runf(r=>r.where({id:e}).update(n,null))}updateOne(e){let n=this.fromJSON(e);if(n==null)return this.#e.throw(`Invalid arg passed to updateOne`,{arg:e,nonRetriable:!0,internal:!0});let r=this.$pickPrimaryKeys(n)??this.$pickBusinessKeys(n);if(r==null)return this.#e.throw(`Invalid arg passed to updateOne`,{arg:e,nonRetriable:!0,internal:!0});n.$beforeSave();let a=n.$toDbJSON(this.updatableColumnNames());return this.dbl.runf(e=>e.where(r).update(a)),n.$afterSave(),this.#e.tap({msg:`updateOne()`,result:n,meta:{input:e}})}pickModelUcn(e){return this.dbl.pickModelUcn(e)}findByUcn(e){let n=this.pickModelUcn(e);return n==null?void 0:this.findOneBy(n)}reloadOne(e){let n=this.$pickBusinessKeys(e)??this.$pickPrimaryKeys(e);if(n==null){this.#e.warn(`reloadOne(): insufficient partial model`,{m:e});return}let r=this.dbl.first(this.query().where(n));if(r==null)this.#e.warn(`reloadOne(): failed to find result in db`,{ucn:n,m:e});else return this.assignFromPojo(e,r)}reload(e){return compact(e.map(e=>this.reloadOne(e)))}toDbJson(e,n){return toPojo(e,{convertBooleanToInt:!0,fieldNames:n??this.columnNames(),omitKey:n=>e[n]===void 0||n.startsWith(`$`)||n.startsWith(`__`)&&n.endsWith(`__`)})}upsert(e){return e=compact(e),this.dbl.modelSupportsUpsert()?e.map(e=>this.upsertOne(e)):e.map(e=>this.insertOrUpdateOne(e))}delete(e){let n=toA(e).filter(gt0);if(n.length===0)this.#e.debug(`delete(): no rows to delete`,{ids:e});else return this.dbl.run(this.model.query().delete().whereIn(`id`,n))}async batched(e){let n=e.batchSize??Settings2.dbBatchSelectSize.valueOrDefault,r=`${this.model.$tableName}.id`,a,o;do a=this.allf(a=>(a=e.qb(a),o!=null&&(a=a.andWhere(r,`>`,o)),a.orderBy(r,`asc`).limit(n))),isNotEmpty(a)&&(o=Math.max(...a.map(e=>e.id)),await e.onResults(a));while(isNotEmpty(a))}},idCount=0,loggerByCtor=new Map,Model=class{static $tableName;static $schema=`models`;static db=modelDb;static $logger(){return getOrSet(loggerByCtor,this.$ctor,()=>mkLogger(this.$ctor))}static $primaryKeys;static $businessKeys;static $booleanFields;static get $ctor(){return this.$schema+`.`+this.$tableName}static query(){return knex()(this.$tableName)}static ops(){return this._ops??=new ModelOps(this,this.db)}static get dbl(){return this.ops().dbl}$ucn(){return this.class().dbl.pickModelUcn(this)}$eql(e){if(this===e)return!0;if(e==null||this.constructor!==e.constructor)return!1;let n=this.class().dbl;return eql(n.pickModelUcn(this),n.pickModelUcn(e))}$ops(){return this.class().ops()}id;class(){return this.constructor}$tableName(){return this.class().$tableName}$instanceId=isTest()?++idCount:void 0;$uid(){return this.$tableName()+`(`+stringify(this.id??this.$ucn())+`)`}logger(){return mkLogger(this.class().$schema+`.`+toS(this.$uid()))}toString(){return this.$uid()}toJSON(){return toPojo(this,{undefinedToNull:!1,omitKey:e=>e.startsWith(`$`)||e.startsWith(`__`)})}toLogJSON(){return toPojo(this,{undefinedToNull:!1})}[import_node_util18.inspect.custom](){return this.toLogJSON()}$toDbJSON(e){return this.$ops().toDbJson(this,e)}static fromJSON(e){return e instanceof this?e:this.ops().assignFromPojo(new this,e)}insert(){return this.logger().debug(`insert()`,{self:this}),this.class().ops().insertOne(this)}update(e){return this.$ops().assignFromPojo(this,e),this.logger().debug(`update()`,{self:this,arg:e}),this.class().ops().updateOne(this)}upsert(e){return e!=null&&this.$ops().assignFromPojo(this,e),this.logger().debug(`upsert()`,{self:this,arg:e}),this.class().ops().upsertOne(this)}$beforeSave(){}$afterSave(){}reload(){return this.class().ops().reloadOne(this)}remove(){gt0(this.id)&&this.class().dbl.runf(e=>e.delete().where({id:this.id}))}isDeleted(){return this.class().ops().findByUcn(this)==null}},logger122=defer(()=>mkLogger(`model.ShaBlocklist`)),ShaBlocklist=class extends Model{static $tableName=`ShaBlocklist`;static $primaryKeys=[`sha`];static $businessKeys=[`sha`];static exists(e){return modelDb()==null||blank(e)?!1:logger122().tap({msg:`isShaBlocklisted`,result:this.dbl.pluckFirstf(n=>n.where({sha:e}))!=null,meta:{sha:e}})}sha};async function notShaBlocklistedFile(e){return modelDb()==null?null:!ShaBlocklist.exists(await fileSha_(e))}function upsertToShaBlocklist(...e){if(modelDb()==null)return;let n=uniq(e).map(e=>({sha:e}));return isEmpty(n)?void 0:ShaBlocklist.dbl.upsert(n)}function libraryFileFiltersFor(e,{validateFile:n=!1}={}){let r=expensiveFileFiltersFor(e);return modelDb()!=null&&r.push({notShaBlocklistedFile}),n&&r.push({isValidFile}),r}async function whyUriUnmintable(e){return await e.uriObject_()==null?`no enabled assetFileUriSchemes (${Settings2.assetFileUriSchemes.values.join(`, `)}) can identify this file`:void 0}async function whyFileRejected(e){let{file:n,forceFilters:r}=e,a=await whyUriUnmintable(n);if(a!=null)return a;let o=await whyRejectFile(n,libraryFileFiltersFor(n));if(o!=null)return o;if(r){let e=n.parent();if(e!=null){let n=await whyExcludedDirectoryRecursive(e);if(n!=null)return n}}}var import_node_net4=require("node:net"),UserFacingError=class extends Error{userMessage;constructor(e,...n){super(e+n.join(``)),this.name=`UserFacingError`,this.userMessage=e}},RpcErrorCode={MethodNotFound:-32601,InternalError:-32603,PendingResponseRejected:-32097},NEWLINE=10,DEFAULT_MAX_LINE_BYTES=8388608,DEFAULT_STALL_TIMEOUT_MS=1e4,DEFAULT_REQUEST_TIMEOUT_MS=6e4,RpcResponseError=class extends Error{constructor(e,n,r){super(n),this.code=e,this.data=r}code;data;name=`RpcResponseError`},PendingResponseRejectedError=class extends RpcResponseError{name=`PendingResponseRejectedError`;constructor(e){super(RpcErrorCode.PendingResponseRejected,`RpcPeer closed: pending request rejected`),e!=null&&(this.cause=e)}},RpcLineTooLargeError=class extends Error{constructor(e,n,r){super(`RpcPeer ${e} line ${n} bytes exceeds ${r} byte limit`),this.direction=e,this.bytes=n,this.maxBytes=r}direction;bytes;maxBytes;name=`RpcLineTooLargeError`},RpcStallError=class extends Error{constructor(e,n){super(`RpcPeer read buffer stalled: ${e} unterminated bytes for ${n}ms`),this.bufferedBytes=e,this.stallTimeoutMs=n}bufferedBytes;stallTimeoutMs;name=`RpcStallError`},RpcPeer=class extends EndableWrapper{#e;#t;#n;#r;#i;#a;#o;#s=new Map;#c=new SequentialTaskQueue;#l=[];#u=0;#d=0;#f;#p=!1;#m;constructor(e){super(e.name==null?`jsonrpc.RpcPeer`:`jsonrpc.RpcPeer.${e.name}`,()=>this.close(),EndableRanks.service),this.#n=e,this.#e=e.stream,this.#i=e.maxLineBytes??DEFAULT_MAX_LINE_BYTES,this.#a=e.stallTimeoutMs??DEFAULT_STALL_TIMEOUT_MS,this.#o=e.defaultTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS,this.#r=mkLogger(`jsonrpc.RpcPeer`,e.name==null?void 0:{peer:e.name}),this.#t=new JsonLinesTransform({strictJson:!0}),this.#t.on(`data`,e=>this.#b(e)),this.#t.on(`error`,e=>this.#h(e)),this.#e.on(`data`,e=>this.#g(e)),this.#e.on(`error`,e=>this.#h(e)),this.#e.once(`close`,()=>this.close())}get closed(){return this.#p}request(e,n,r=this.#o){if(this.#p)return Promise.reject(new PendingResponseRejectedError(this.#m));let a=++this.#u,o=stringify({id:a,method:e,params:n}),s=Buffer.byteLength(o);if(s>this.#i)return Promise.reject(new RpcLineTooLargeError(`outbound`,s,this.#i));let c=new Deferred,l={deferred:c,method:e,startedAt:Date.now()};if(r>0){let n=new TimeoutError(`RPC timeout: ${e} (${r}ms)`);l.timer=setTimeout(()=>{this.#s.delete(a)&&(this.#r.warn(`request timed out`,{method:e,id:a,timeoutMs:r}),c.reject(n))},r),l.timer.unref()}return this.#s.set(a,l),this.#D({direction:`send`,kind:`request`,method:e,id:a}),this.#E(o,()=>!this.#s.has(a)).catch(e=>{this.#s.delete(a)&&(l.timer!=null&&clearTimeout(l.timer),c.reject(new PendingResponseRejectedError(e))),this.close(toError(e))}),c.promise}notify(e,n){try{if(this.#p)return;let r=stringify({method:e,params:n}),a=Buffer.byteLength(r);if(a>this.#i){this.#r.warn(`dropping oversize notification`,{name:e,bytes:a,maxBytes:this.#i});return}this.#D({direction:`send`,kind:`notification`,method:e}),this.#E(r).catch(e=>this.close(toError(e)))}catch(n){this.#r.warn(`notify() failed`,{name:e,err:n})}}async flush(){await this.#c.awaitSettled()}onClose(e){this.#p?queueMicrotask(()=>{try{e(this.#m)}catch(e){this.#r.warn(`onClose callback threw`,{err:e})}}):this.#l.push(e)}close(e){if(this.#p)return;this.#p=!0,this.#m=e,this.#y();for(let[,n]of this.#s)n.timer!=null&&clearTimeout(n.timer),n.deferred.reject(new PendingResponseRejectedError(e));this.#s.clear();try{this.#e.destroy()}catch{}try{this.#t.destroy()}catch{}let n=this.#l;this.#l=[];for(let r of n)try{r(e)}catch(e){this.#r.warn(`onClose callback threw`,{cbErr:e})}this.end()}#h(e){let n=toError(e)??Error(String(e));this.#p?this.#r.debug(`stream error after close`,{err:n}):(this.#r.debug(`stream error; closing`,{err:n}),this.close(n))}#g(e){this.#p||this.#_(e)&&this.#t.write(e)}#_(e){let n=this.#d,r=0,a=!1,o=e.indexOf(NEWLINE,r);for(;o!==-1;){a=!0;let s=(r===0?n:0)+(o-r);if(s>this.#i)return this.close(new RpcLineTooLargeError(`inbound`,s,this.#i)),!1;r=o+1,o=e.indexOf(NEWLINE,r)}return this.#d=r===0?n+e.length:e.length-r,this.#d>this.#i?(this.close(new RpcLineTooLargeError(`inbound`,this.#d,this.#i)),!1):(this.#v(n,a),!0)}#v(e,n){this.#a<=0||(this.#d===0?this.#y():(n||e===0||this.#f==null)&&(this.#y(),this.#f=setTimeout(()=>{this.close(new RpcStallError(this.#d,this.#a))},this.#a),this.#f.unref()))}#y(){this.#f!=null&&(clearTimeout(this.#f),this.#f=void 0)}#b(e){if(this.#p)return;let n=typeof e.method==`string`,r=typeof e.id==`number`;n&&r?this.#x(e):r?this.#C(e):n?this.#T(e):this.#r.warn(`dropping unrecognized message`,{msg:e})}async#x(e){let{id:n,method:r}=e,a=Date.now();this.#D({direction:`recv`,kind:`request`,method:r,id:n});let o=this.#n.handlers,s=Object.prototype.hasOwnProperty.call(o,r)?o[r]:void 0;if(s==null)this.#r.warn(`no handler for method`,{method:r,id:n}),this.#S(n,{error:{code:RpcErrorCode.MethodNotFound,message:`unknown method: ${r}`}},r,a);else try{let o=await s(e.params);this.#S(n,{result:o??null},r,a)}catch(e){this.#r.warn(`handler threw`,{method:r,id:n,err:e}),this.#S(n,{error:{code:RpcErrorCode.InternalError,message:errorToS(e),data:errorToJson(toError(e)??Error(errorToS(e)))}},r,a)}}#S(e,n,r,a){let o=stringify({id:e,...n}),s=Buffer.byteLength(o);s>this.#i&&(this.#r.error(`response exceeds maxLineBytes; sending InternalError`,{method:r,id:e,bytes:s,maxBytes:this.#i}),o=stringify({id:e,error:{code:RpcErrorCode.InternalError,message:`response exceeds maxLineBytes (${s} > ${this.#i})`}}),s=Buffer.byteLength(o),s>this.#i)?(this.#r.error(`InternalError envelope also exceeds maxLineBytes; closing`,{method:r,id:e,bytes:s,maxBytes:this.#i}),this.close(new RpcLineTooLargeError(`outbound`,s,this.#i))):(this.#D({direction:`send`,kind:`response`,method:r,id:e,elapsedMs:Date.now()-a}),this.#E(o).catch(e=>this.close(toError(e))))}#C(e){let n=this.#s.get(e.id);n==null?this.#r.warn(`response for unknown request id`,{id:e.id}):(this.#s.delete(e.id),n.timer!=null&&clearTimeout(n.timer),this.#D({direction:`recv`,kind:`response`,method:n.method,id:e.id,elapsedMs:Date.now()-n.startedAt}),e.error==null?n.deferred.resolve(e.result):n.deferred.reject(this.#w(e.error)))}#w(e){let n=new RpcResponseError(e.code,e.message,e.data);if(e.data!=null)try{n.cause=errorFromJson(e.data)}catch(n){this.#r.debug(`error.data was not a serialized error`,{data:e.data,e:n})}let r=n.cause;return r instanceof Error&&r.name===`UserFacingError`?Object.assign(new UserFacingError(r.userMessage),{message:r.message,stack:r.stack}):n}#T(e){this.#D({direction:`recv`,kind:`notification`,method:e.method});let n=this.#n.onNotification;if(n==null)this.#r.warn(`dropping notification: no onNotification handler`,{method:e.method});else try{Promise.resolve(n(e.method,e.params)).catch(n=>this.#r.warn(`onNotification handler rejected`,{method:e.method,err:n}))}catch(n){this.#r.warn(`onNotification handler threw`,{method:e.method,err:n})}}#E(e,n){return this.#c.enqueue(()=>{if(this.#p)throw Error(`RpcPeer closed`);if(n?.()!==!0)return writeAsync(this.#e,e+`
|
|
673
|
+
`)})}#D(e){this.#r.debug(`trace`,e);try{this.#n.trace?.(e)}catch(e){this.#r.warn(`trace hook threw`,{err:e})}}},import_node_fs31=require("node:fs"),import_node_os19=require("node:os"),import_node_path64=require("node:path"),MAX_UNIX_SOCKET_BYTES=100,IpcAddressTooLongError=class extends Error{constructor(e,n){super(`UDS path too long for sun_path (${n} > ${MAX_UNIX_SOCKET_BYTES}): ${e}. Override TMPDIR to a shorter path.`),this.address=e,this.byteLength=n,this.name=`IpcAddressTooLongError`}address;byteLength},IpcAddress=class e{static socketDir(){return(0,import_node_path64.join)((0,import_node_os19.tmpdir)(),`ps-${process.getuid?.()??`u`}`)}static libHash(e){return shortFsStringSha(e,16)}static forLibrary(n){let r=e.libHash(n);if(process.platform===`win32`)return`\\\\.\\pipe\\photostructure-${r}-sync`;let a=(0,import_node_path64.join)(e.socketDir(),`${r}-sync.sock`),o=Buffer.byteLength(a,`utf8`);if(o>MAX_UNIX_SOCKET_BYTES)throw new IpcAddressTooLongError(a,o);return a}static prepareSocketDir_(){if(process.platform===`win32`)return;let n=e.socketDir();(0,import_node_fs31.mkdirSync)(n,{recursive:!0,mode:448}),(0,import_node_fs31.chmodSync)(n,448)}},INITIAL_RECONNECT_MS=250,MAX_RECONNECT_MS=3e4,STABLE_CONNECTION_MS=5e3,SyncOfflineError=class extends Error{constructor(e,n){super(`Sync service is offline (could not connect for RPC "${e}")`),this.method=e,n!=null&&(this.cause=n)}method;name=`SyncOfflineError`},SyncRpcClient=class e extends EndableWrapper{static#e;static#t=!1;static instance=defer(()=>e.forLibrary(Settings2.libraryDir.valueOrDefault));static{ee().on(`syncShutdown`,()=>e.resetInstance())}static resetInstance(){let n=e.instance.prior();if(n!=null&&(n.#o=!1),n?.close(),n?.end(),e.instance.reset(),e.#t){let n=e.instance();n.#o=!0,n.ensureConnected()}}static watchLibraryDir(n){let r=Settings2.libraryDir.valueOrDefault,a=a=>{a!==r&&(r=a,e.resetInstance(),n?.())};return Settings2.libraryDir.watchLater(a),()=>Settings2.libraryDir.unWatch(a)}static enablePersistentConnection(n){e.#e=n,e.#t=!0;let r=e.instance(),a=r.isHealthy();r.#o=!0,a&&(r.close(),r.stopReconnect()),r.ensureConnected()}static disablePersistentConnection(){e.#t=!1,e.#e=void 0;let n=e.instance.prior();n!=null&&(n.#o=!1,n.stopReconnect())}static forLibrary(n){return new e({libraryDir:n})}static forOptions(n){return new e({options:n})}#n;#r;#i;#a=0;#o=!1;#s;#c=0;#l=0;#u=(n,r)=>{if(this.#o)return e.#e?.(n,r)};constructor(e){super(`sync-rpc.SyncRpcClient`,()=>this.close(),EndableRanks.service),this.#n=e}isHealthy(){return this.#r!=null&&!this.#r.closed}close(e){this.#a++,this.#i=void 0,this.#r?.close(e),this.#r=void 0,this.ended&&this.stopReconnect()}#d(){if(`libraryDir`in this.#n)return IpcAddress.forLibrary(this.#n.libraryDir);let e=this.#n.options;if(`path`in e)return e.path;throw Error(`SyncRpcClient: stream target has no connectable path`)}async#f(){if(this.ended)throw new PendingResponseRejectedError(Error(`SyncRpcClient has ended`));let e=this.#r;return e!=null&&!e.closed?e:this.#i??=this.#p(this.#a)}async#p(e){try{return await this.#m(e)}catch(n){throw this.#o&&!this.ended&&!this.#_(e)&&this.#y(),n}finally{this.#_(e)||(this.#i=void 0)}}#m(e){if(`options`in this.#n&&`stream`in this.#n.options){let n=this.#n.options.stream;return this.#_(e)?(n.destroy(),Promise.reject(this.#v())):Promise.resolve(this.#h(n))}let n=this.#d();this.logger.debug(`connecting to sync`,{path:n});let r=(0,import_node_net4.connect)({path:n});return new Promise((n,a)=>{let o=e=>{r.removeListener(`connect`,s),a(e)},s=()=>{r.removeListener(`error`,o),this.#_(e)?(r.destroy(),a(this.#v())):n(this.#h(r))};r.once(`connect`,s),r.once(`error`,o)})}#h(e){let n=new RpcPeer({stream:e,handlers:{},onNotification:this.#u,name:`sync-client`});return this.#r=n,this.#l=Date.now(),this.stopReconnect(),n.onClose(e=>{this.logger.debug(`peer closed`,{err:e}),this.#r===n&&(this.#r=void 0),Date.now()-this.#l>=STABLE_CONNECTION_MS&&(this.#c=0),this.#o&&!this.ended&&this.#y()}),this.#o&&this.#g(n),n}async#g(e){try{await e.request(`reloadLicenses`,void 0)}catch(e){this.logger.debug(`license invalidation after connect failed`,{err:e})}}#_(e){return e!==this.#a}#v(){return new PendingResponseRejectedError(Error(`SyncRpcClient closed during connect`))}ensureConnected(){this.#o&&!this.ended&&(this.isHealthy()||this.#i!=null||this.#s!=null||this.#f().catch(e=>this.logger.debug(`persistent connect failed`,{err:e})))}#y(){if(!this.#o||this.ended||this.#s!=null)return;let e=this.#b(this.#c++);this.#s=setUnrefTimeout(()=>{this.#s=void 0,this.#o&&!this.ended&&this.#f().catch(e=>this.logger.debug(`persistent reconnect failed`,{err:e}))},e)}#b(e){let n=Math.min(MAX_RECONNECT_MS,INITIAL_RECONNECT_MS*2**e);return Math.round(n*(.5+Math.random()*.5))}stopReconnect(){this.#s!=null&&(clearTimeout(this.#s),this.#s=void 0)}get reconnectScheduledForTest(){return assertIsTest(),this.#s!=null}get reconnectAttemptForTest(){return assertIsTest(),this.#c}async request(e,n,r){let a;try{a=await this.#f()}catch(n){throw this.#x(e,n)}return a.request(e,n,r)}#x(e,n){let r=n?.code;return r===`ECONNREFUSED`||r===`ENOENT`?new SyncOfflineError(e,n):n}async ping(e){return this.request(`ping`,void 0,e)}async status(){return this.request(`status`,void 0)}async enqueueTask(e){await this.request(`enqueueTask`,{task:e})}async getTaskListState(){return this.request(`getTaskListState`,void 0)}async getProblematicFiles(e={}){return this.request(`getProblematicFiles`,e)}async retryProblematicFile(e){return this.request(`retryProblematicFile`,{path:e})}async retryAllProblematicFiles(){return this.request(`retryAllProblematicFiles`,void 0)}async isPaused(){return this.request(`isPaused`,void 0)}async gateConditions(){return this.request(`gateConditions`,void 0)}async operationalState(){return this.request(`operationalState`,void 0)}async getTimings(){return this.request(`getTimings`,void 0)}async setPaused(e,n){await this.request(`setPaused`,{paused:e,reason:n})}async setThermalState(e){await this.request(`setThermalState`,{state:e})}async applyTagRenames(){return this.request(`applyTagRenames`,void 0)}removeAssets(e){return this.request(`removeAssets`,{createdAt:e})}changeAssetState(e,n){return this.request(`changeAssetState`,{assetId:e,patch:n})}emptyTrash(e){return this.request(`emptyTrash`,{createdAt:e})}async runMaintenance(){await this.request(`runMaintenance`,void 0)}async resetHealthChecks(){await this.request(`resetHealthChecks`,void 0)}async setSkipHealthCheckIds(e){await this.request(`setSkipHealthCheckIds`,e)}async rerunToolChangeTracker(){await this.request(`rerunToolChangeTracker`,void 0)}async resyncPaths(e){await this.request(`resyncPaths`,{paths:e})}async reloadLicenses(){await this.request(`reloadLicenses`,void 0)}},UnknownDimensionsPixels=12e7;function fullFrameBytesPerPixel(e){return e&&Settings2.dcrawEmuArgs.values.includes(`-6`)?6:3}function estimatedWriteBytes(e){let n=gt0(e.fileSize)?e.fileSize:0,r=Settings2.copyAssetsToLibrary.valueOrDefault?n:0,a=isRawImageExt(e.basename);return!a&&!isHeifExt(e.basename)?n+r:(gt0(e.width)&>0(e.height)?e.width*e.height:UnknownDimensionsPixels)*fullFrameBytesPerPixel(a)+n+r}async function resolveAssetTaskArgs(e){let n=Asset.ops().findById(e),r=n==null?[]:uniqBy([n.getPrimary(),...n.getAssetFiles()],e=>e.id);return{assetId:e,paths:await resolveNativePaths(r),bytes:r.reduce((e,n)=>e+estimatedWriteBytes(n),0)}}async function prepareAssetTaskPaths(e){switch(e.method){case`deleteAsset`:case`finalizeAsset`:case`refreshAssetDerivatives`:case`retagAsset`:case`validateAssetSiblings`:{let n=e.args;return{...e,args:{...n,...await resolveAssetTaskArgs(n.assetId)}}}default:return e}}var logger123=defer(()=>mkLogger(`library.task`));function addLocalTask(e,n,r={}){let a=Task2.for(e,n,r);return TaskList.instance().add(a),a}async function addTask(e,n,r={}){if(!isSyncService()&&await syncClientOK())return SyncRpcClient.instance().enqueueTask({method:e,args:n,...r.source==null?{}:{source:r.source}});{logger123().warn(`addTask(): no syncClient or isSyncService: running locally`,{fn:e,args:n});let a=await prepareAssetTaskPaths({method:e,args:n});return addLocalTask(a.method,a.args,r)}}var syncClientOK=lazy2(async()=>{try{let e=SyncRpcClient.instance();return await e.isPaused(),e.isHealthy()}catch{return!1}},1e3);function assetIdColumns(){return{assetId:`Asset.id`,capturedAtLocal:`Asset.capturedAtLocal`,updateCount:`Asset.updateCount`,durationMs:`Asset.durationMs`,renderWidth:`Asset.renderWidth`,renderHeight:`Asset.renderHeight`}}function toAssetId(e){let n=toGt0(e?.assetId)??toGt0(e?.id);if(e==null||n==null||!isNumber(e?.capturedAtLocal))return;let r=(toGt0(e.v)??toGt0(e.updateCount)??toGt0(e.updatedAt)??0)%1e6,a={assetId:n,capturedAtLocal:e.capturedAtLocal,v:r};gt0(e.durationMs)&&(a.durationHMS=durationHMS(e.durationMs));let o=toGt0(e.renderWidth),s=toGt0(e.renderHeight);return o!=null&&s!=null&&(a.renderWidth=o,a.renderHeight=s),a}function whereDirUriInTree(e,n){let r=n.endsWith(`/`)?n.slice(0,-1):n,a=r+`/`;return e.where(e=>e.where(`DirUri.uri`,r).orWhereRaw(`substr(DirUri.uri, 1, length(?)) = ?`,[a,a])),e}function whereDirUriInTrees(e,n){return e.where(e=>{for(let r of n)e.orWhere(e=>whereDirUriInTree(e,r))}),e}var ModelDao=class{constructor(e){this.modelClass=e,this.logger=mkLogger(`${e.name}Dao`)}modelClass;logger;db(){return this.modelClass.db()}get dbl(){return this.modelClass.dbl}ops(){return this.modelClass.ops()}query(){return this.modelClass.query()}},AssetFileDao=class extends ModelDao{constructor(){super(AssetFile)}orphan(...e){let n=e.filter(gt0),r=n.length>0?AssetFile.dbl.runf(e=>e.update({assetId:null,isPrimary:0,updatedAt:Date.now()}).whereIn(`id`,n)):void 0;return gt0(r?.changes)&&ee().emitThrottled(`notifyWorkAvailable`,`adoptAssetFile`),r}primaryAssetFileId(e){return this.dbl.pluckFirstf(n=>n.where({assetId:e,isPrimary:1}).limit(1))}primaryForAssetId(e){return gt0(e)?this.ops().findOne(Asset.dao.shownUnhidden().join(`AssetFile`,`AssetFile.assetId`,`Asset.id`).select(`AssetFile.*`).where({assetId:e,"AssetFile.isPrimary":1})):void 0}shownUnhidden({uriRoot:e}={}){let n=Asset.dao.shownUnhidden().join(`AssetFile`,`AssetFile.assetId`,`Asset.id`);return blank(e)||(n=whereDirUriInTree(n.join(`DirUri`,`AssetFile.dirUriId`,`DirUri.id`),e)),n}recentAssetsByUriRoot(e,n,r=64){return compact(AssetFile.dbl.all(this.recentAssetsQuery(e,Date.now()-n,r)).map(e=>toAssetId(e)))}recentAssetsQuery(e,n,r){return this.shownUnhidden({uriRoot:e}).select(assetIdColumns()).max({recentAt:`AssetFile.updatedAt`}).where(`AssetFile.updatedAt`,`>`,n).groupBy(`Asset.id`).orderBy(`recentAt`,`desc`).orderBy(`Asset.id`,`desc`).limit(r)}assetFileCountByMimeType(e){let n=this.shownUnhidden({uriRoot:e}).select(`AssetFile.mimetype`).countDistinct({assetFileCount:`AssetFile.id`,assetCount:`Asset.id`}).groupBy(`AssetFile.mimetype`).orderBy(`AssetFile.mimetype`);return AssetFile.dbl.all(n)}assetFileCountWithMimeType(e,n){let r=this.shownUnhidden({uriRoot:n}).countDistinct({assetFileCount:`AssetFile.id`,assetCount:`Asset.id`});return r=e.endsWith(`/`)?r.andWhereLike(`AssetFile.mimetype`,e+`%`):r.andWhere(`AssetFile.mimetype`,e),this.dbl.first(r)}assetFileCountByMimeTypeRoots(e=[`image/`,`video/`],n){return e.map(e=>({mimeTypeRoot:e,assetFileCount:this.assetFileCountWithMimeType(e,n)?.assetFileCount??0}))}async sameShaInLibrary(e){if(this.db()==null)return;let n=await e.sha(),r=await e.size();if(n!=null&&r!=null)return this.ops().all(this.query().join(`DirUri`,`AssetFile.dirUriId`,`DirUri.id`).select(`AssetFile.*`).where({sha:n,fileSize:r}).andWhere(e=>whereDirUriInTrees(e,libraryUriRoots())))}sameAssetFileInLibrary(e){return this.ops().all(this.query().join(`DirUri`,`AssetFile.dirUriId`,`DirUri.id`).select(`AssetFile.*`).where(pick(e,`sha`,`fileSize`)).andWhere(e=>whereDirUriInTrees(e,libraryUriRoots())).andWhereNot(`AssetFile.id`,e.id))}countByState(e){let n=whereDirUriInTree(this.query().select(knex().raw(`
|
|
674
|
+
SUM(CASE WHEN AssetFile.assetId IS NULL THEN 1 ELSE 0 END) as orphans,
|
|
675
|
+
SUM(CASE WHEN AssetFile.assetId IS NOT NULL
|
|
676
|
+
AND Asset.shown = 1
|
|
677
|
+
AND COALESCE(Asset.flags, 0) = 0
|
|
678
|
+
THEN 1 ELSE 0 END) as done,
|
|
679
|
+
SUM(CASE WHEN AssetFile.assetId IS NOT NULL
|
|
680
|
+
AND (Asset.shown != 1 OR COALESCE(Asset.flags, 0) != 0)
|
|
681
|
+
THEN 1 ELSE 0 END) as pending,
|
|
682
|
+
COUNT(*) as total`)).join(`DirUri`,`AssetFile.dirUriId`,`DirUri.id`).leftJoin(`Asset`,`AssetFile.assetId`,`Asset.id`),e),r=this.dbl.first(n);return{orphans:toInt(r?.orphans)??0,pending:toInt(r?.pending)??0,done:toInt(r?.done)??0,total:toInt(r?.total)??0}}},Bitfield=class{constructor(e,n,r){if(this.tableName=e,this.columnName=n,this.names=r,r.values.length>32)throw Error(`Too many flags (${r.values.length}): JavaScript bitwise operations limited to 32 bits (0-31). Consider using a different storage approach.`)}tableName;columnName;names;toBit(e){let n=this.names.indexOf(e);return n==null?0:1<<n}has(e,n){return e!=null&&(e&this.toBit(n))!==0}add(e,...n){e??=0;for(let r of n)e|=this.toBit(r);return e}remove(e,...n){if(e==null)return 0;for(let r of n)e&=~this.toBit(r);return e}decode(e){if(e==null)return[];let n=[];for(let r of this.names.values)this.has(e,r)&&n.push(r);return n}toContext(e){if(e==null)return{};let n={};for(let r of this.names.values)this.has(e,r)&&(n[r]=!0);return n}get qualifiedColumn(){return`${this.tableName}.${this.columnName}`}whereCondition(e,n=!0){return{sql:n?`(${this.qualifiedColumn} & ?) != 0`:`(COALESCE(${this.qualifiedColumn}, 0) & ?) = 0`,bindings:[this.toBit(e)]}}toMask(e){let n=0;for(let r of e)n|=this.toBit(r);return n}whereAny({flags:e,qb:n=knex()(this.tableName)}){return n.whereRaw(`(${this.qualifiedColumn} & ?) != 0`,[this.toMask(e)])}where({flag:e,isSet:n=!0,qb:r=knex()(this.tableName)}){let{sql:a,bindings:o}=this.whereCondition(e,n);return r.whereRaw(a,o)}clearAll({flag:e,qb:n=knex()(this.tableName)}){let{sql:r,bindings:a}=this.whereCondition(e,!0);return n.whereRaw(r,a).update({[this.columnName]:knex().raw(`COALESCE(${this.qualifiedColumn}, 0) & ~?`,[this.toBit(e)])})}update({flag:e,isSet:n=!0,qb:r=knex()(this.tableName)}){return r.update({[this.columnName]:knex().raw(`COALESCE(${this.qualifiedColumn}, 0) ${n?`|`:`& ~`} ?`,[this.toBit(e)])})}},AssetFileFlagList=[`forceSync`,`forceFilters`,`forceCheckLibraryCopy`,`forceUpdate`,`contentChanged`,`locationIsApproximate`,`unused-imageDataHashPending`],AssetFileFlagNames=strEnum(...AssetFileFlagList),AssetFileFlags=new Bitfield(`AssetFile`,`flags`,AssetFileFlagNames),AssetFlagNames=strEnum(`unused-reaggregate`,`finalize`,`validateSiblings`,`failedFinalize`,`refreshDerivatives`,`failedRefreshDerivatives`,`retag`,`failedRetag`,`repair`,`failedRepair`,`finalizePathTags`,`deleting`),PathTagsOnlyBlockingAssetFlags=[`finalize`,`validateSiblings`,`failedFinalize`,`retag`,`refreshDerivatives`],AssetFlags=new Bitfield(`Asset`,`flags`,AssetFlagNames),AssetTag=class extends Model{static $tableName=`AssetTag`;assetId;tagId};later(()=>{ee().on(`clearCache`,()=>DirUri._cache.clear()),ee().on(`clearDbCache`,()=>DirUri._cache.clear())});var DirUriCacheMaxSize=4096,DirUri=class e extends Model{static $tableName=`DirUri`;static $businessKeys=[`uri`];static _cache=new Cache({name:`model.DirUri`,maxSize:DirUriCacheMaxSize});uri;nativePath;rememberNativePath_(n){let r=this.uriObject().scheme;if(r!==PS_LOCAL_FILE_SCHEME&&r!==PS_NETWORK_FILESYSTEM_SCHEME)return;let a=resolve2(n);e.dbl.runf(e=>e.where(`id`,this.id).whereRaw(`?? IS NOT ?`,[`nativePath`,a]).update({nativePath:a})),this.nativePath=a}static findOrCreateByUri_(n){typeof n.uri==`string`&&blank(n.uri)&&this.$logger().throw(`Invalid blank URI string`,{args:n});let r=toURI(n.uri);(blank(r)||blank(r.scheme))&&this.$logger().throw(`Invalid URI (missing scheme)`,{args:n});let a=n.nativePath!=null&&(r.scheme===PS_LOCAL_FILE_SCHEME||r.scheme===PS_NETWORK_FILESYSTEM_SCHEME)?PosixFile.for(n.nativePath).nativePath:void 0,o=this._cache.getOrSet(r.toString(),()=>e.ops().upsertOne({uri:r.toString(),nativePath:a}));return blank(a)||o.rememberNativePath_(a),o}static async findByDirectory_(e){let n=PosixFile.for(e),r=await n.uri_();return r==null?this.$logger().throw(`findByDirectory_(): failed to make URI for directory: `+n):this.findByUri_(r)}static findByUri_(n){let r=toS(n);return this._cache.getOrMaybeSet(r,()=>e.ops().findOneBy({uri:r}))}uriObject=defer(()=>URI.parse(this.uri));joinPath(e){return URI.joinPath(this.uriObject(),e).toString()}};function previewProvenanceColumns(e){return{previewFingerprint:e.previewFingerprint,renderWidth:e.render.width,renderHeight:e.render.height,previewSourceMtime:e.source.mtime,previewSourceSize:e.source.fileSize}}function previewPlanDimensions(e,n){let r=e?.renderWidth,a=e?.renderHeight;return gt0(r)&>0(a)?{width:r,height:a}:n}function publishedPreviewProvenance(e){return{previewFingerprint:e.previewFingerprint??void 0,renderDimensions:gt0(e.renderWidth)&>0(e.renderHeight)?{width:e.renderWidth,height:e.renderHeight}:void 0,mtime:e.previewSourceMtime??void 0,fileSize:e.previewSourceSize??void 0}}var logger124=defer(()=>mkLogger(`tag.TagAssetCounts`)),TagAssetCountQuery=compressWhitespace(`SELECT`,` count(DISTINCT Asset.id) AS assetCount`,`FROM`,` TagHierarchy th`,` JOIN AssetTag ON AssetTag.tagId = th.descendantId`,` JOIN Asset ON Asset.id = AssetTag.assetId`,`WHERE`,` th.tagId = :tagId`,` AND Asset.shown = 1`,` AND Asset.hidden = 0`,` AND Asset.excludedAt IS NULL`,` AND Asset.deletedAt IS NULL`);function updateTagAssetCount(e,n){if(gt0(n)){if(logger124().isDebugEnabled()){let r=splitTagPath(e.prepare(`SELECT _path FROM Tag WHERE id = ?`).pluck().get(n)),a=performance.now(),o=e.prepare(TagAssetCountQuery).pluck().get({tagId:n}),s=performance.now()-a;logger124().debug(`Count query for tag ${r} completed in ${fmtMs(s)}`,{tagId:n,tagText:r,assetCount:o,queryTime:s});let c=performance.now();e.prepare(`UPDATE Tag SET assetCount = ?, updatedAt = ? WHERE id = ?`).run(o,Date.now(),n),logger124().debug(`Tag update completed in ${fmtMs(performance.now()-c)}`)}else{let r=e.prepare(TagAssetCountQuery).pluck().get({tagId:n});e.prepare(`UPDATE Tag SET assetCount = ?, updatedAt = ? WHERE id = ?`).run(r,Date.now(),n)}}}var BulkAssetCountUpdateQuery=compressWhitespace(`UPDATE Tag`,`SET assetCount = counts.assetCount, updatedAt = :now`,`FROM (`,` SELECT th.tagId, COUNT(DISTINCT Asset.id) as assetCount`,` FROM TagHierarchy th`,` LEFT JOIN AssetTag ON AssetTag.tagId = th.descendantId`,` LEFT JOIN Asset ON Asset.id = AssetTag.assetId`,` AND Asset.shown = 1`,` AND Asset.hidden = 0`,` AND Asset.excludedAt IS NULL`,` AND Asset.deletedAt IS NULL`,` GROUP BY th.tagId`,`) AS counts`,`WHERE Tag.id = counts.tagId`);async function rebuildTagAssetCounts(e){return time({name:`db.rebuildTagAssetCounts`,p:async()=>{let n=performance.now();logger124().info(`Starting bulk tag asset count rebuild using TagHierarchy`);let r=new PushProgressObserver({op:`Rebuilding tag asset counts`},100);try{let a=e.prepare(`SELECT COUNT(*) FROM Tag`).pluck().get();logger124().info(`Updating asset counts for ${a} tags`),await r.incrProgress(10);let o=performance.now(),s=e.prepare(BulkAssetCountUpdateQuery).run({now:Date.now()}),c=performance.now()-o;logger124().info(`Bulk update completed in ${fmtMs(c)} for ${s.changes} rows`),await r.incrProgress(80),await ee().emit(`clearTagCache`),r.completed();let l=performance.now()-n;logger124().info(`Bulk tag asset count rebuild completed in ${fmtMs(l)}`,{totalTags:a,totalTimeMs:l,perTagMs:a>0?l/a:0,updateTimeMs:c})}catch(e){throw logger124().error(`Failed to rebuild tag asset counts`,e),e}}})}async function rebuildNullTagAssetCounts(e){logger124().info(`Starting NULL tag asset count rebuild`);let n=new PushProgressObserver({op:`Rebuilding NULL tag asset counts`},e.prepare(`SELECT count(*) FROM Tag WHERE assetCount IS NULL`).pluck().get());for(;;){let r=e.prepare(`SELECT id FROM Tag WHERE assetCount IS NULL LIMIT 1000`).all();if(r.length===0)break;for(let a of r)updateTagAssetCount(e,a.id),n.incrProgress(),a.id%50==0&&(logger124().throwIfAborted_(),await delay(1))}n.completed()}var logger125=defer(()=>mkLogger(`tag.TagDisplayPath`));function displayPathCte(...e){return compressWhitespace(`WITH RECURSIVE dp(id, ppath, dpath) AS (`,` SELECT id, _path, SUBSTR(_path, 1, LENGTH(_path) - 1) || :sep`,` FROM Tag WHERE parentId IS NULL`,` UNION ALL`,` SELECT t.id, t._path,`,` dp.dpath || COALESCE(NULLIF(t._displayName, ''),`,` SUBSTR(t._path, LENGTH(dp.ppath) + 1,`,` LENGTH(t._path) - LENGTH(dp.ppath) - 1)) || :sep`,` FROM Tag t JOIN dp ON t.parentId = dp.id`,`)`,...e)}function rebuildTagDisplayPaths(e){timeSync({name:`db.Tag.rebuildDisplayPaths`,t:()=>{e.prepare(displayPathCte(`UPDATE Tag SET _displayPath =`,` (SELECT dpath FROM dp WHERE dp.id = Tag.id)`)).run({sep:TagSep}),e.exec(`UPDATE Tag SET _displayPath = _path WHERE _displayPath IS NULL`)}})}function mkDisplayPath(e,n,r){let a=e!=null&&r!=null&&r.length>0?r:n;return(e??``)+a+TagSep}function withLeafSegment(e,n){return joinTagPath([...splitTagPath(e).slice(0,-1),n])}function replaceDisplayPathPrefix(e,n){let{pathPrefix:r,priorPrefix:a,newPrefix:o}=n;a!==o&&a.length!==0&&e.prepare(compressWhitespace(`UPDATE Tag SET`,` _displayPath = :new || SUBSTR(_displayPath, LENGTH(:prior) + 1),`,` updatedAt = :now`,`WHERE _path LIKE :pathLike ESCAPE '\\'`,` AND _displayPath LIKE :like ESCAPE '\\'`)).run({new:o,prior:a,pathLike:escapeLike(r)+`%`,like:escapeLike(a)+`%`,now:Date.now()})}function escapeLike(e){return e.replace(/[\\%_]/g,e=>`\\`+e)}function staleTagDisplayPathCount(e){return e.prepare(displayPathCte(`SELECT COUNT(*) FROM Tag LEFT JOIN dp ON dp.id = Tag.id`,` WHERE Tag._displayPath IS NOT COALESCE(dp.dpath, Tag._path)`)).pluck().get({sep:TagSep})}function repairTagDisplayPathsIfNeeded(e){let n=staleTagDisplayPathCount(e);return n>0&&(logger125().warn(`repairTagDisplayPathsIfNeeded(): rebuilding`,{stale:n}),rebuildTagDisplayPaths(e)),{stale:n}}function filterRootTags(e){let n=new CaseInsensitiveSet(Settings2.hiddenRootTags.valueOrDefault);return e.filter(e=>!n.has(e.name)&&!n.hasAny((e.description??``).split(/\s+/)))}var MaxCompoundTagCount=4;function canonicalTagContext(e){let n=[...new Set(e.map(e=>e.id))].sort((e,n)=>e-n);return n.length===0?void 0:`tags:${n.join(`,`)}`}var TaggedAssetStream=class{constructor(e,n,r,a,o=canonicalTagContext(e),s=o??`timeline`){this.tags=e,this.before=n,this.after=r,this.limit=a,this.context=o,this.identity=s,this.logger().debug(`new`,this.toJSON())}tags;before;after;limit;context;identity;logger=()=>mkLogger(`model.TaggedAssetStream(`+this.toString()+`)`);vacuum(){sortByInPlace(this.before,e=>[-e.capturedAtLocal,-e.assetId]),retainFirstN(this.before,this.limit),sortByInPlace(this.after,e=>[-e.capturedAtLocal,-e.assetId]),retainLastN(this.after,this.limit)}toString(){return this.tags.map(e=>e.path.join(`/`)).join(`,`)}valueOf(){return this.toString()}get length(){return toA(this.before).length+toA(this.after).length}leftPad(e){return[...times(this.limit-e.length,e=>({assetId:-(e+1),capturedAtLocal:-1,v:0})),...e]}rightPad(e){return[...e,...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}}async toApi(){return this.vacuum(),this.logger().tap({msg:`toApi()`,result:{tags:await thenCollect(this.tags,e=>e.toApiTag({includeChildren:!1})),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before),context:this.context,identity:this.identity}})}streamCoeff(e){return this.logger().tap({msg:`streamCoeff`,meta:{this:this.tags.map(e=>e.path),tas:e.tags.map(e=>e.path)},result:diceCoeff([...this.before,...this.after],[...e.before,...e.after],e=>e.assetId)})}};function streamTagIds(e){return e.tags.map(e=>e.id).sort((e,n)=>e-n)}function groupKey(e){return e.flatMap(streamTagIds).sort((e,n)=>e-n).join(`,`)}function groupTagCount(e){return new Set(e.flatMap(streamTagIds)).size}function windowIntersectionSize(e){let[n,...r]=e;if(n==null)return 0;let a=new Set([...n.before,...n.after].map(e=>e.assetId));for(let e of r){let n=new Set([...e.before,...e.after].map(e=>e.assetId));for(let e of a)n.has(e)||a.delete(e)}return a.size}function groupCorrelatedStreams(e){let n=Settings2.minStreamCorrPct.valueOrDefault/100,r=[],a=e.filter(e=>e.length>5).sort((e,n)=>groupKey([e]).localeCompare(groupKey([n])));for(let e of a){let a,o=-1/0,s=``;for(let c of r){let r=[...c,e];if(groupTagCount(r)>MaxCompoundTagCount)continue;let l=1/0,u=!0;for(let r of c){let a=r.streamCoeff(e);if(a<n){u=!1;break}l=Math.min(l,a)}if(!u||windowIntersectionSize(r)<=5)continue;let d=groupKey(c);(l>o||l===o&&d<s)&&(a=c,o=l,s=d)}a==null?r.push([e]):a.push(e)}return r}var TagAssetScope=class{tags;tagIds;constructor(e){let n=new Map;for(let r of e){if(!gt0(r.id))throw Error(`TagAssetScope requires persisted tags`);n.set(r.id,r)}if(n.size===0||n.size>MaxCompoundTagCount)throw Error(`TagAssetScope requires 1-${MaxCompoundTagCount} distinct tags`);this.tags=[...n.values()].sort((e,n)=>e.id-n.id),this.tagIds=this.tags.map(e=>e.id)}get context(){return`tags:${this.tagIds.join(`,`)}`}get identity(){return this.context}#e(e){return e.getChildrenCount()>0}#t(e){return this.#e(e)?e.$descendantAssetsQuery():e.$assetsQuery()}#n(e,n){let r=`CompoundAssetTag${n}`,a=AssetTag.query().clearSelect().select(`${r}.assetId`).from(`AssetTag as ${r}`).whereRaw(`${r}.assetId = Asset.id`);if(this.#e(e)){let o=`CompoundTagHierarchy${n}`;a=a.join(`TagHierarchy as ${o}`,`${o}.descendantId`,`${r}.tagId`).where(`${o}.tagId`,e.id)}else a=a.where(`${r}.tagId`,e.id);return a}#r(){return[...this.tags].sort((e,n)=>(e.assetCount??2**53-1)-(n.assetCount??2**53-1)||e.id-n.id)}$assetIdQuery(){let[e,...n]=this.#r(),r=this.#t(e).clearSelect().select(assetIdColumns()).distinct();for(let e=0;e<n.length;e++)r=r.whereExists(this.#n(n[e],e));return r}$neighborQuery(e,n,r){let a=r===`before`,o=a?`<`:`>`,s=a?`<`:`>`,c=a?`desc`:`asc`;return this.$assetIdQuery().andWhereRaw(`(Asset.capturedAtLocal ${o} ? OR (Asset.capturedAtLocal = ? AND Asset.id ${s} ?))`,[e.capturedAtLocal,e.capturedAtLocal,e.id]).orderBy([{column:`Asset.capturedAtLocal`,order:c},{column:`Asset.id`,order:c}]).limit(n)}queryBeforeAfter(e,n){return n=gt0(n)?n:BeforeAfterStreamLimit,{before:compact(Asset.dbl.all(this.$neighborQuery(e,n,`before`)).map(toAssetId)),after:compact(Asset.dbl.all(this.$neighborQuery(e,n,`after`)).map(toAssetId))}}getAssetStream(e,n){n=gt0(n)?n:BeforeAfterStreamLimit;let{before:r,after:a}=this.queryBeforeAfter(e,n);return new TaggedAssetStream(this.tags,r,a.reverse(),n)}},RootsByName={When:{name:TagRoots.When,description:`Dates come from DateTimeOriginal, CreateDate, filename patterns, and the file's modification time.`,helpUrl:`https://photostructure.com/guide/captured-at/`,ordinal:1,icon:`event`,title:`Year and month`,label:`When`},Albums:{name:TagRoots.Albums,description:`Albums come from Album, Collections.CollectionName, or Google Takeout albumData.title metadata. (Lightroom CatalogSets show up under Keywords, not Albums.)`,helpUrl:`https://photostructure.com/guide/albums/`,ordinal:2,icon:`collections`,title:`Album`,label:`Album`},fs:{name:TagRoots.fs,description:`Directory hierarchy mirroring your original folder structure.`,ordinal:3,icon:`folder`,title:`Directories on your computer`,label:`Directory`},Who:{name:TagRoots.Who,description:`People come from MWG 2.0 face regions (RegionInfo), Google Takeout peopleNames, and tags like PersonInImage.`,helpUrl:`https://photostructure.com/guide/people/`,ordinal:4,icon:`face`,title:`Who`,label:`Who`},Where:{name:TagRoots.Where,description:`Places come from GPS coordinates (reverse-geocoded by ExifTool's bundled geo database) and from explicit Country, State, and City metadata.`,helpUrl:`https://photostructure.com/guide/places/`,ordinal:5,icon:`location`,title:`Location`,label:`Where`},Event:{name:TagRoots.Event,description:`Events come from keywords under Event, Activity, or Occasion (e.g. the keyword Occasion/Birthday becomes Event/Birthday).`,helpUrl:`https://photostructure.com/guide/keywords/`,ordinal:6,icon:`newspaper`,title:`Event`,label:`Event`},Camera:{name:TagRoots.Camera,description:`Cameras come from the Make and Model metadata fields.`,ordinal:7,icon:`camera_alt`,title:`Camera make and model`,label:`Camera`},Lens:{name:TagRoots.Lens,description:`Lenses come from the LensMake, LensModel, and LensInfo metadata fields.`,ordinal:8,icon:`camera`,title:`Camera lens`,label:`Lens`},What:{name:TagRoots.What,description:`What comes from keywords under Subject, Object, Item, or Article (e.g. the keyword Subject/Nature becomes What/Nature).`,helpUrl:`https://photostructure.com/guide/keywords/`,ordinal:9,icon:`category`,title:`Subject or topic`,label:`What`},Keywords:{name:TagRoots.Keywords,description:`Keywords come from tags like Keywords, Subject, HierarchicalSubject, CatalogSets, and others.`,helpUrl:`https://photostructure.com/guide/keywords/`,ordinal:10,icon:`tag`,title:`Keyword`,label:`Keyword`},Type:{name:TagRoots.Type,description:`Type comes from the media type of the file (e.g. image/jpeg, video/mp4).`,ordinal:11,icon:`video_file`,title:`Media type (image/jpeg, video/mp4, etc.)`,label:`Media type`}},WhenRoot=RootsByName.When,AlbumsRoot=RootsByName.Albums,FsRoot=RootsByName.fs,WhoRoot=RootsByName.Who,WhereRoot=RootsByName.Where,EventRoot=RootsByName.Event,CameraRoot=RootsByName.Camera,LensRoot=RootsByName.Lens,WhatRoot=RootsByName.What,KwRoot=RootsByName.Keywords,TypeRoot=RootsByName.Type,Roots=Object.values(RootsByName);function rootTagDef(e){return RootsByName[e]}var rootNamesLowerCase=defer(()=>new CaseInsensitiveSet([...TagRoots.values,...RootTagAliasConfigs.flatMap(e=>e.setting.values)]));function hasTagRoot(e){return rootNamesLowerCase().has(tagRefToS(e[0]))}function stripTagRoot(e){return hasTagRoot(e)?e.slice(1):e}later(()=>ee().on(`clearCache`,()=>rootNamesLowerCase.reset()));var logger126=defer(()=>mkLogger(`db.SQLiteIndexes`));function withoutIndexes(e,n,r){let a=e.prepare(`SELECT name, sql FROM sqlite_master
|
|
683
|
+
WHERE type = 'index'
|
|
684
|
+
AND tbl_name = ?
|
|
685
|
+
AND sql IS NOT NULL`).all(n);logger126().debug(`withoutIndexes(): dropping indexes`,{tableName:n,indexCount:a.length,indexNames:a.map(e=>e.name)});for(let{name:r}of a)/^[\w$]+$/.test(r)?e.exec(`DROP INDEX IF EXISTS ${escapeIdentifier(r)}`):logger126().warn(`Skipping index with unusual name`,{tableName:n,name:r});try{return r()}finally{logger126().debug(`withoutIndexes(): restoring indexes`,{tableName:n,indexCount:a.length});for(let{sql:r,name:o}of a)try{e.exec(r)}catch(e){logger126().throw(`Failed to restore index ${o} after withoutIndexes()`,{tableName:n,sql:r,error:e})}}}var logger127=defer(()=>mkLogger(`model.TagHierarchy`)),TagHierarchy=class e extends Model{static $tableName=`TagHierarchy`;static $primaryKeys=[`tagId`,`descendantId`];static $businessKeys=[`tagId`,`descendantId`];tagId;descendantId;depth;static maxUpdateDepth=100;static updateForTag(n,r,a=0){if(!gt0(n))return;if(a>e.maxUpdateDepth)throw Error(`Tag hierarchy recursion depth ${a} exceeds limit ${e.maxUpdateDepth} for tag ${n}. This may indicate a cycle in Tag.parentId. Use TagHierarchy.rebuild() instead.`);let o=e.dbl;try{let s=Tag.dbl.pluckAll({sql:`SELECT id FROM Tag WHERE parentId = :tagId AND id != :tagId`,bindings:{tagId:n}});o.runf(e=>e.delete().where({descendantId:n}).orWhere({tagId:n})),o.upsertOne({tagId:n,descendantId:n,depth:0}),gt0(r)&&r!==n&&o.run({sql:compressWhitespace(`INSERT INTO TagHierarchy (tagId, descendantId, depth)`,`SELECT tagId, :tagId, depth + 1`,`FROM TagHierarchy`,`WHERE descendantId = :parentId`),bindings:{tagId:n,parentId:r}});for(let r of s)e.updateForTag(r,n,a+1);logger127().debug(`Updated tag hierarchy for tag`,{tagId:n,parentId:r})}catch(e){throw logger127().error(`Failed to update tag hierarchy`,{tagId:n,parentId:r,recursionDepth:a,error:e}),e}}static rebuild(){timeSync({name:`db.TagHierarchy.rebuild`,t:()=>{logger127().info(`Starting complete TagHierarchy table rebuild`);try{e.dbl.txn(()=>{withoutIndexes(e.dbl.db().db,e.$tableName,()=>{logger127().debug(`Clearing existing TagHierarchy data`),e.dbl.runf(e=>e.delete()),logger127().debug(`Rebuilding tag hierarchy using recursive CTE`),e.dbl.run(`INSERT INTO TagHierarchy (tagId, descendantId, depth) SELECT id, id, 0 FROM Tag`),e.dbl.run(compressWhitespace(`WITH RECURSIVE hierarchy(ancestor, descendant, depth) AS (`,` SELECT parentId, id, 1`,` FROM Tag`,` WHERE parentId IS NOT NULL`,` `,` UNION ALL`,` `,` SELECT h.ancestor, t.id, h.depth + 1`,` FROM hierarchy h`,` JOIN Tag t ON t.parentId = h.descendant`,` WHERE h.ancestor IS NOT NULL`,`)`,`INSERT OR IGNORE INTO TagHierarchy (tagId, descendantId, depth)`,`SELECT ancestor, descendant, depth`,`FROM hierarchy`)),logger127().info(`TagHierarchy table rebuild completed successfully`)})})}catch(e){throw logger127().error(`Failed to rebuild TagHierarchy table`,{error:e}),e}}})}static getAncestorIds(n){return gt0(n)?e.dbl.pluckAll({sql:compressWhitespace(`SELECT tagId FROM TagHierarchy`,`WHERE descendantId = :tagId AND tagId != :tagId`,`ORDER BY depth ASC`),bindings:{tagId:n}}):[]}static getDescendantIds(n){return gt0(n)?e.dbl.pluckAll({sql:compressWhitespace(`SELECT descendantId FROM TagHierarchy`,`WHERE tagId = :tagId AND descendantId != :tagId`,`ORDER BY depth ASC`),bindings:{tagId:n}}):[]}static ValidationResult=class{constructor(e,n,r,a,o,s){this.missingSelfRef=e,this.missingParent=n,this.incompleteTransitive=r,this.cycles=a,this.spuriousEntries=o,this.orphanedEntries=s}missingSelfRef;missingParent;incompleteTransitive;cycles;spuriousEntries;orphanedEntries;get isValid(){return this.missingSelfRef.length===0&&this.missingParent.length===0&&this.incompleteTransitive.length===0&&this.cycles.length===0&&this.spuriousEntries.length===0&&this.orphanedEntries===0}get totalIssues(){return this.missingSelfRef.length+this.missingParent.length+this.incompleteTransitive.length+this.cycles.length+this.spuriousEntries.length+ +(this.orphanedEntries>0)}get affectedTagIds(){return[...new Set([...this.missingSelfRef,...this.missingParent,...this.incompleteTransitive,...this.cycles,...this.spuriousEntries])]}};static validate(){let n=e.dbl,r=n.pluckAll({sql:compressWhitespace(`SELECT t.id FROM Tag t`,`WHERE NOT EXISTS (`,` SELECT 1 FROM TagHierarchy th`,` WHERE th.descendantId = t.id AND th.tagId = t.id AND th.depth = 0`,`)`)}),a=n.pluckAll({sql:compressWhitespace(`SELECT t.id FROM Tag t`,`WHERE t.parentId IS NOT NULL`,`AND NOT EXISTS (`,` SELECT 1 FROM TagHierarchy th`,` WHERE th.descendantId = t.id`,` AND th.tagId = t.parentId`,` AND th.depth = 1`,`)`)}),o=n.pluckAll({sql:compressWhitespace(`SELECT DISTINCT t.id FROM Tag t`,`WHERE t.parentId IS NOT NULL`,`AND EXISTS (`,` SELECT 1 FROM TagHierarchy parent_anc`,` WHERE parent_anc.descendantId = t.parentId`,` AND NOT EXISTS (`,` SELECT 1 FROM TagHierarchy th`,` WHERE th.descendantId = t.id`,` AND th.tagId = parent_anc.tagId`,` AND th.depth = parent_anc.depth + 1`,` )`,`)`)}),s=n.pluckAll({sql:compressWhitespace(`SELECT DISTINCT tagId FROM TagHierarchy`,`WHERE tagId = descendantId AND depth > 0`)}),c=n.pluckAll({sql:compressWhitespace(`SELECT DISTINCT th.descendantId FROM TagHierarchy th`,`WHERE th.depth = 1`,`AND NOT EXISTS (`,` SELECT 1 FROM Tag t`,` WHERE t.id = th.descendantId`,` AND t.parentId = th.tagId`,`)`)}),l=n.pluckFirst({sql:compressWhitespace(`SELECT COUNT(*) FROM TagHierarchy th`,`WHERE NOT EXISTS (SELECT 1 FROM Tag WHERE id = th.tagId)`,`OR NOT EXISTS (SELECT 1 FROM Tag WHERE id = th.descendantId)`)})??0,u=new e.ValidationResult(r,a,o,s,c,l);return u.isValid||logger127().warn(`TagHierarchy validation found issues`,{missingSelfRef:r.length,missingParent:a.length,incompleteTransitive:o.length,cycles:s.length,spuriousEntries:c.length,orphanedEntries:l}),u}static repairIfNeeded(){let n=e.validate();if(n.isValid)return{action:`none`,issueCount:0};let r=n.affectedTagIds;if(r.length>20||n.orphanedEntries>0)return logger127().info(`TagHierarchy: too many issues, performing full rebuild`,{affectedTags:r.length,orphanedEntries:n.orphanedEntries}),e.rebuild(),{action:`full`,issueCount:n.totalIssues};logger127().info(`TagHierarchy: repairing individual tags`,{tagIds:r});for(let n of r){let r=Tag.dbl.pluckFirst({sql:`SELECT parentId FROM Tag WHERE id = :tagId`,bindings:{tagId:n}});e.updateForTag(n,r??null)}return{action:`partial`,issueCount:n.totalIssues,repairedTagIds:r}}},TagCacheMaxSize=512,TagDao=class extends ModelDao{_cache=new Cache({name:`model.Tag`,maxSize:TagCacheMaxSize,ttlMs:TagCacheTtlMs});constructor(){super(Tag)}_upsertDefaultRoots=lazy(()=>{if(!isDbJanitorService()&>0(Tag.dbl.count(e=>e.whereNull(`parentId`))))return;let e=Tag.dbl.allf(e=>e.whereNull(`parentId`)),n=[];for(let r of Roots){let a=joinTagPath([r.name]),o=e.find(e=>equalsIgnoreCase(e._path,a)),s=toInt(o?.ordinal)??r.ordinal,c=toNotBlank(o?.description)??r.description;(o==null||o._path!==a||toInt(o.ordinal)!==s||toNotBlank(o.description)!==c)&&n.push({_path:a,_displayPath:a,ordinal:s,description:c})}Tag.ops().upsert(n)});validate_(){return timeSync({name:`db.tag.validate`,t:()=>{Tag.clear();for(let e of this.ops().allf(e=>e.whereRaw(`id = parentId`))){this.logger.warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);let n=e.path.slice(0,-1),r=(isEmpty(n)?void 0:this.findOrCreate(n))?.id??null;Tag.dbl.runf(n=>n.where({id:e.id}).update({parentId:r})),e.parentId=r}for(let e of Tag.roots())e.validate_([])}})}deltaAssetCountAndAncestors(e,n=1){return Tag.dao.incrAssetCount(Tag.dao.selfAndAncestorIds(e),n)}incrAssetCount(e,n=1){isEmpty(e)||Tag.dbl.runf(r=>r.whereIn(`id`,e).update({assetCount:knex().raw(`COALESCE(assetCount, 0) + ?`,[Math.round(n)]),updatedAt:Date.now()}))}selfAndAncestorIds(e){let n=toA(e).filter(gt0);return isEmpty(n)?[]:Tag.dbl.pluckAll({sql:compressWhitespace(`SELECT DISTINCT tagId`,`FROM TagHierarchy`,`WHERE descendantId IN `+sqlWhereInClause(n.length)),bindings:n})}findByIdOrPath(e,n){return e===0?Tag.root():gt0(e)?this.findById(e):this.findByPath(n)}findById(e){return e===0?Tag.root():this.ops().findById(e)}findByPath(e){if(isEmpty(e))return Tag.root();let n=joinTagPath(e);return this._cache.getOrMaybeSet(n.toLowerCase(),()=>this.ops().findOnef(e=>e.where({_path:n})))}findByPathN(e){return compact(uniqBy(e.filter(isNotEmpty),e=>toNotBlank(joinTagPath(e))).map(e=>this.findByPath(e)))}getPagedAssets(e,n){let r=new Tag;return r.id=e,r.getPagedAssetIds(n)}_newTag(e){let n=new Tag;n._path=joinTagPath(e);let r=e[e.length-1];return typeof r==`object`&&(mapNotBlank(r.displayName,e=>n._displayName=e),mapNumeric(r.ordinal,e=>n.ordinal=e),mapNotBlank(r.description,e=>n.description=e),mapNumeric(r.releasedAt,e=>n.releasedAt=e)),n}findOrCreate(e){if(isEmpty(e))throw Error(`Tag.findOrCreate(): tagPath is empty`);let n=this.findByPath(e);if(n!=null)return n;let r=this._newTag(e),a=r.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));map(a,n=>{r.parentId=n.id,r._path=joinTagPath([...n.path,e[e.length-1]])}),r._displayPath=mkDisplayPath(a?._displayPath,r.name,r._displayName);let o=this.ops().upsertOne(r);return this._cache.set(joinTagPath(e).toLowerCase(),o),o}findOrCreateByPathN(e){return uniqBy(e.filter(isNotEmpty),e=>joinTagPath(e)).map(e=>this.findOrCreate(e))}changePath(e,n,r=!0){let a=e._path,o=Tag.dao.findByPath(splitTagPath(n));this.logger.info(`changePath(): `,{target:e,newPath:n,existingSibling:o});let s=e._displayPath,c=splitTagPath(n).slice(0,-1),l=tagPathEql(splitTagPath(a).slice(0,-1),c),u=o==null&&s!=null&&l;try{if(o==null){let r=Tag.dbl.txn(()=>{if(Tag.dbl.runf(e=>e.whereLike(`_path`,a+`%`).update({updatedAt:Date.now(),_path:knex().raw(`REPLACE(_path, ?, ?)`,[a,n])})),l)return e.parentId??null;Tag.clear();let r=isEmpty(c)?null:this.findOrCreate(c).id;return Tag.dbl.runf(n=>n.where({id:e.id}).update({parentId:r})),r});e._path=n,e.parentId=r,e.clear(),e.displayPath.unset(),u&&(e._displayPath=withLeafSegment(s,toNotBlank(e._displayName)??e.name),replaceDisplayPathPrefix(Tag.dbl.db().db,{pathPrefix:e._path,priorPrefix:s,newPrefix:e._displayPath}))}else{n=o._path,this.logger.info(`changePath(): replacing with sibling`,n),AssetTag.dbl.run({sql:compressWhitespace(`INSERT OR REPLACE INTO AssetTag (assetId, tagId)`,`SELECT assetId, :newTagId`,`FROM AssetTag`,`WHERE tagId = :oldTagId`),bindings:{newTagId:o.id,oldTagId:e.id}}),AssetTag.dbl.runf(n=>n.where({tagId:e.id}).delete());for(let n of e.getChildren())this.changePath(n,joinTagPath([...o.path,n.name]),!1);Tag.dbl.runf(n=>n.where({parentId:e.id}).update({parentId:o.id})),e.remove()}!u&&r&&(TagHierarchy.repairIfNeeded(),rebuildTagDisplayPaths(Tag.dbl.db().db),e._displayPath=this.findById(e.id)?._displayPath)}finally{r&&Tag.clear()}}},TimestampedModel=class extends Model{static touch(e,n={}){n.updatedAt??=Date.now(),delete n.id;let r=toA(e).filter(gt0);return isEmpty(r)?void 0:this.dbl.runf(e=>e.whereIn(`id`,r).update(n))}createdAt;updatedAt;get createdAtDate(){return mapGt0(this.createdAt,e=>new Date(e))}get updatedAtDate(){return mapGt0(this.updatedAt,e=>new Date(e))}touch(e={}){e.updatedAt??=Date.now();let n=this.id;n==null?this.upsert():this.class().dbl.runf(r=>r.where({id:n}).update(e))}$beforeSave(){if(super.$beforeSave(),this.createdAt??=Date.now(),this.updatedAt=Date.now(),Object.hasOwn(this,`updateCount`)){let e=this,n=e.updateCount;e.updateCount=(toGt0(e.updateCount)??0)+1,this.logger().debug(`$beforeSave(): incr updateCount`,{prior:n,now:e.updateCount})}}},TagCacheTtlMs=4*secondMs,SampleModuli=[256,64,16,4,1];later(()=>{ee().on(`clearCache`,()=>Tag.clear()),ee().on(`clearDbCache`,()=>Tag.clear()),ee().on(`clearTagCache`,()=>Tag.clear())});var Tag=class e extends TimestampedModel{static $tableName=`Tag`;static $primaryKeys=[`id`];static $businessKeys=[`_path`];static#e;static get dao(){return this.#e??=new TagDao}static get _cache(){return this.dao._cache}static orderBy(e){return e.orderByRaw(`COALESCE(ordinal, _path) COLLATE NOCASE`)}static clear(){this.root.unset(),this.roots.unset(),this.dao._upsertDefaultRoots.unset(),this.dao._cache.clear()}validate_(e){let n=this.path;if(!tagPathEql(n.slice(0,-1),e))throw Error(`Tag:${this.id} path ${n.join(`/`)} does not match expected parent ${e.join(`/`)}`);for(let e of this.getChildren())e.validate_(n)}static root=lazy2(()=>{let n=new e;return n.id=0,n._path=TagSep,n.parentId=void 0,n.children=filterRootTags(e.roots()),n.ancestors=[],n.assetCount=Asset.dao.shownCount(),n.upsert=()=>{throw Error(`upsert not supported on root`)},n},TagCacheTtlMs);static roots=lazy2(()=>{e.dao._upsertDefaultRoots();let n=e.ops().all(e.orderBy(e.query().whereNull(`parentId`)));for(let e of n)e.parentId=void 0,e.ancestors=[];return n},TagCacheTtlMs);parentId;ordinal;_path;_displayName;_displayPath;description;releasedAt;assetCount;parent;root;children;ancestors;clear(){return this.parent=void 0,this.root=void 0,this.children=void 0,this.ancestors=void 0,this.ancestorIds.unset(),this}$afterSave(){if(TagHierarchy.updateForTag(this.id,this.parentId??null),this.parentId==null)e.root.unset(),e.roots.unset();else{let n=this.path.slice(0,-1);n.length>0&&e._cache.delete(joinTagPath(n).toLowerCase())}}remove(){gt0(this.id)&&(this.class().ops().delete([this.id]),e.clear())}siblingPath(e){return joinTagPath([...this.parentPath,e])}changeName(n){return e.dao.changePath(this,this.siblingPath(n))}changePath(n,r){return e.dao.changePath(this,n,r)}maybeUpsertDisplayName(n){if(blank(n)||n===this._displayName)return;let r=this._displayPath;this._displayName=n,this._displayPath=this.parentId==null?this._path:withLeafSegment(toS(r??this._path),n);let a=this.upsert();return notBlank(r)&&replaceDisplayPathPrefix(e.dbl.db().db,{pathPrefix:this._path,priorPrefix:r,newPrefix:this._displayPath}),e.clear(),a}get name(){return this.path.at(-1)}get path(){return splitTagPath(this._path)}get displayName(){return toNotBlank(this._displayName)??this.name}displayPath=lazy2(()=>{let e=this.getParent();return compactBlanks([...e==null?[]:e.displayPath(),this.displayName])});get isRoot(){return this.id===0}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}$childrenQuery(){return e.orderBy(e.query().where({parentId:this.id}))}$assetsQuery(){return Asset.dao.shownUnhidden().columns(`Asset.*`).join(`AssetTag`,`AssetTag.assetId`,`Asset.id`).where({tagId:this.id}).distinct()}$descendantAssetsQuery(){return Asset.dao.shownUnhidden().columns(`Asset.*`).join(`AssetTag`,`AssetTag.assetId`,`Asset.id`).join(`TagHierarchy`,`TagHierarchy.descendantId`,`AssetTag.tagId`).where(`TagHierarchy.tagId`,this.id).distinct()}$selectAssetIdColumns(e){return e.clearSelect().select(assetIdColumns())}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],map(this.parent,n=>n.setAncestors(e.slice(0,-1)))}async toApiPathElements(){return thenCollect(this.getAncestorsAndSelf(),e=>e.toPathTag())}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(e){let n={tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount??0,allChildren:e?.includeChildren===!1?[]:this.getChildren().map(e=>({name:e.name,display:e.displayName}))};return e?.includeSiblings===!0&&(n.pathSiblings=this.getPathSiblings()),n}getPathSiblings(){isEmpty(this.ancestors)&>0(this.parentId)&&(this.ancestors=void 0);let n=[...this.getAncestors(),this];return n.map((r,a)=>a===0?filterRootTags(e.roots()).map(e=>({name:e.name,display:e.displayName})):n[a-1].$childNameDisplayPairs())}$childNameDisplayPairs(){return e.dbl.allf(e=>e.select(`_path`,`_displayName`).where(`parentId`,this.id).orderByRaw(`COALESCE(ordinal, _path) COLLATE NOCASE`)).map(e=>{let n=splitTagPath(e._path).at(-1);return{name:n,display:toNotBlank(e._displayName)??n}})}toStringId(){return`Tag(`+this.path.join(`/`)+`)`}getParent(){if(!this.isRoot)return this.parentId!=null&&this.parent==null?this.parent=e.dao.findById(this.parentId):this.parent}getPagedChildren(n){if(this.isRoot&&(this.children??=e.roots()),this.children!=null){let e=n.offset??0,r=e+(n.limit??this.children.length);return this.children.slice(e,r)}let r=this.$childrenQuery();return mapGt0(n.offset,e=>{r.offset(e)}),mapGt0(n.limit,e=>void r.limit(e)),e.ops().all(r)}getChildrenCount(){return this.children==null?e.dbl.pluckFirstf(e=>(this.isRoot?e.whereNull(`parentId`):e.where({parentId:this.id})).count()):this.children.length}getChildren(){if(!this.isRoot&&this.children==null){this.children=e.ops().all(this.$childrenQuery());for(let e of this.children)e.parent=this}return this.children}get rootName(){return this.path[0]}getAncestors(){return this.ancestors??=this._getAncestors()}getAncestorsAndSelf(){return[...this.getAncestors(),this]}_getAncestors(){return this.parentId===0||this.parentId==null?[]:e.ops().all({sql:compressWhitespace(`SELECT Tag.*`,`FROM Tag`,`JOIN TagHierarchy th ON th.tagId = Tag.id`,`WHERE th.descendantId = :tagId`,` AND th.tagId != :tagId`,`ORDER BY th.depth DESC`),bindings:{tagId:this.id}})}ancestorIds=lazy2(()=>this.parentId===0||this.parentId==null?[]:TagHierarchy.getAncestorIds(this.id).reverse());getPagedAssetIds(e){let n=this.$assetIdsQuery();return n=n.limit(e.limit??ThumbsPerSample),gt0(e.offset)&&(n=n.offset(e.offset)),n=n.orderBy([{column:`capturedAtLocal`,order:`desc`},{column:`assetId`}]),compact(Asset.dbl.all(n).map(toAssetId))}getAssets(){let e=this.$assetsQuery().orderBy(`capturedAtLocal`,`desc`);return Asset.ops().all(e)}firstNonInterstitialTagId=lazy2(()=>{if(!this.isRoot&&this.directAssetCount()===0&&this.getChildrenCount()===1){let e=this.getChildren();if(e?.length===1)return e[0].firstNonInterstitialTagId()}return this.id});directAssetCount=lazy2(()=>this.id===0?0:Asset.dbl.pluckFirst(Asset.dao.shownUnhidden().join(`AssetTag`,`AssetTag.assetId`,`Asset.id`).where(`AssetTag.tagId`,this.id).countDistinct(`Asset.id`)));getAssetCount(){return this.id===0?e.dbl.pluckFirst({sql:compressWhitespace(`SELECT`,` count(DISTINCT Asset.id) AS assetCount`,`FROM`,` Asset`,`WHERE`,` Asset.shown = 1`,` AND Asset.excludedAt IS NULL`,` AND Asset.hidden = 0`,` AND Asset.deletedAt IS NULL`)}):e.dbl.pluckFirst({sql:TagAssetCountQuery,bindings:{tagId:this.id}})}getAssetStream(e,n){return new TagAssetScope([this]).getAssetStream(e,n)}getRelatedAssetIds({seed:e,limit:n=ThumbsPerSample}){let r=this.id??0,a=this.#t(e,r,n);return this.logger().debug(this.path+`: Found `+a.length+` related assets`),a}#t(e,n,r){return isSeededRandomAvailable()?this.#n(e,n,r):compact(AssetTag.dbl.allf(e=>Asset.dao.shownUnhidden(this.$selectAssetIdColumns(e)).distinct().join(`Asset`,`Asset.id`,`AssetTag.assetId`).whereIn(`AssetTag.tagId`,e=>e.select(`descendantId`).from(`TagHierarchy`).where(`TagHierarchy.tagId`,n)).orderByRaw(`RANDOM()`).limit(r)).map(toAssetId))}#n(e,n,r){let a=e+n;for(let e of SampleModuli){let o=compact(AssetTag.dbl.all({sql:compressWhitespace(`WITH candidates AS (`,` SELECT DISTINCT AssetTag.assetId`,` FROM AssetTag`,` WHERE AssetTag.tagId IN (`,` SELECT descendantId FROM TagHierarchy`,` WHERE TagHierarchy.tagId = :tagId`,` )`,` AND ABS(seeded_random(:seed, AssetTag.assetId)) % :modulus = 0`,`)`,`SELECT c.assetId, a.capturedAtLocal,`,` a.updateCount, a.durationMs,`,` a.renderWidth, a.renderHeight`,`FROM candidates c`,`JOIN Asset a ON a.id = c.assetId`,`WHERE a.shown = 1 AND a.hidden = 0`,` AND a.excludedAt IS NULL AND a.deletedAt IS NULL`,`LIMIT :limit`),bindings:{tagId:n,seed:a,modulus:e,limit:r}}).map(toAssetId));if(o.length>=r||e===1)return o}return[]}},import_node_path65=__toESM(require("node:path")),Volume=class e extends Model{static $tableName=`Volume`;static $primaryKeys=[`id`];static $businessKeys=[`authority`,`mountPoint`];authority;mountPoint;label;lastSeenAt;static#e=new Cache({name:`model.Volume`,maxSize:512});static#t=new Cache({name:`model.Volume.mountPoints`,maxSize:512});static setupLookupShim=defer(()=>{volshaToMountPointFallback.setShim(n=>e.mountPointsForVolsha(n)),onHealthyVolumeDiscovered.setShim(n=>e.onVolumeGet(n))});static findByVolsha(n){if(e.db()!=null)return this.#e.getOrMaybeSet(n,()=>e.ops().allf(e=>e.where({authority:n}).orderBy(`lastSeenAt`,`DESC`)).find(e=>e.isNativePath()))}static volshaToMountPoint(n){return compact([e.findByVolsha(n)?.mountPoint])}static mountPointsForVolsha(n){return e.db()==null?[]:this.#t.getOrMaybeSet(n,()=>uniq(e.ops().allf(e=>e.where({authority:n}).orderBy(`lastSeenAt`,`DESC`)).filter(e=>e.isNativePath()).map(e=>e.mountPoint)))??[]}static#n(n,r){let a=e.mountPointsForVolsha(n.authority);if(a.length<=1)return a[0];let o=DirUri.ops().findOneBy({uri:extractUriDirectory_(n)})?.nativePath,s=PosixFile.forMaybe(o)?.join(extractUriBasename_(n))?.nativePath,c=[];for(let e of a){let n=PosixFile.forMaybe(e)?.join(r);n!=null&&c.push({mountPoint:e,nativePath:n.nativePath,exists:n.existsSync()})}return selectPsfileMountPoint(c,{missingFallback:`first`,preferredNativePath:s})?.mountPoint??a[0]}static#r(n){return e.ops().allf(e=>e.where({authority:n}).whereNotNull(`label`).orderBy(`lastSeenAt`,`DESC`)).find(e=>e.isNativePath()&¬Blank(e.label))?.label}static onVolumeGet(n){let{volsha:r,mountPoint:a}=n;if(blank(r)){this.$logger().info(`Skipping volume with blank volsha`,{volume:n});return}if(e.db()==null){this.$logger().warn(`Skipping volume upsert: no database available`,{volume:n});return}this.#e.delete(r),this.#t.delete(r);let o=toNotBlank(n.label?.trim())??this.#r(r),s=e.ops().upsertOne({authority:r,mountPoint:a,...o==null?{}:{label:o},lastSeenAt:Date.now()});this.#e.set(r,s)}displayName(){return Settings2.tagDisplayNameFSLabels.valueOrDefault&¬Blank(this.label)?this.label:this.mountPoint===`/`?Settings2.tagDisplayNameFSRoot.valueOrDefault+(Settings2.tagDisplayNameFSRootWithHostname.valueOrDefault?` on `+Settings2.hostname.valueOrDefault:``):notBlankOr(stripPrefixSuffix(this.mountPoint,{prefix:import_node_path65.default.sep,suffix:import_node_path65.default.sep}),import_node_path65.default.sep)}static async upsertForScannedVolumes(){invalidateMountPointLists({force:!0}),e.setupLookupShim();for await(let n of scannedVolumes())e.onVolumeGet(n)}static resolve_(n){let r=()=>this.$logger().throw(`Volume.resolve(): cannot resolve invalid uri`,{uri:n,logLevel:`warn`}),a=toURI(n);if(a.scheme===`file`)return toNotBlank(a.fsPath)??r();if(a.scheme===PS_LIBRARY_SCHEME)return pslibToNativePath_({uri:a}).nativePath;if(a.scheme===PS_NETWORK_FILESYSTEM_SCHEME)return this.$logger().throw(`Volume.resolve(): psnet URIs must be resolved asynchronously`,{uri:n,logLevel:`warn`});{let n=a.path.startsWith(`/`)?a.path.slice(1):a.path,o=e.#n(a,n)??r(),s=PosixFile.forMaybe(o)?.join(n)?.nativePath??r();return canonicalizeMacPathSync(s)??s}}isNativePath(){return isNativePath(this.mountPoint)}},AssetFileOps=class extends ModelOps{insertOne(e){return this.dbl.txn(()=>super.insertOne(e))}updateOne(e){return this.dbl.txn(()=>super.updateOne(e))}upsertOne(e){return this.dbl.txn(()=>super.upsertOne(e))}},AssetFile=class e extends TimestampedModel{static $tableName=`AssetFile`;static $businessKeys=[`dirUriId`,`basename`];static $booleanFields=[`isPrimary`,`monochrome`];static ops(){return this._ops??=new AssetFileOps(this,this.db)}static#e;static get dao(){return this.#e??=new AssetFileDao}static unsaved(n){let{uri:r,...a}=n,o=e.ops().assignFromPojo(new e,a);return o.#r=r,o.basename=extractUriBasename_(toURI(r)),o}static async resolveUriNativePath_(e){let n=URI.parse(e);if(n.scheme===PS_NETWORK_FILESYSTEM_SCHEME){let e=DirUri.db()==null?void 0:DirUri.ops().findOneBy({uri:extractUriDirectory_(n)})?.nativePath,r=PosixFile.forMaybe(e)?.join(extractUriBasename_(n))?.nativePath;return(await psnetToNativePath_({uri:n,preferredNativePath:r}))?.nativePath}try{let n=Volume.resolve_(e);if(n!=null)return n}catch{}return await uriToNativePath_(e)}assetId;dirUriId;basename;isPrimary;mtime;fileSize;mimetype;width;height;rotation;durationMs;cameraId;lensId;imageId;metadataDate;sha;capturedAtLocal;capturedAtPrecisionMs;capturedAtZone;capturedAtSrc;capturedAtSrcDetail;capturedAtZoneSrc;make;model;rating;aperture;focalLength;fps;latitude;longitude;iso;shutterSpeed;monochrome;pHash;rHash;wHash;pHash0;rHash0;wHash0;flags;lastVisitedGeneration;updateCount;#t;$syncState;#n;#r;#i;#a;#o;$clear(){this.#t=void 0,this.$syncState=void 0,this.#n=void 0,this.#r=void 0,this.#i=void 0,this.#a=void 0,this.#o=void 0}getFlags(){return AssetFileFlags.decode(this.flags)}hasFlag(e){return AssetFileFlags.has(this.flags,e)}get locationIsApproximate(){return this.hasFlag(`locationIsApproximate`)}addFlag(e){this.flags=AssetFileFlags.add(this.flags,e)}clearFlag(e){this.flags=AssetFileFlags.remove(this.flags,e)}ctx(e){return forceContextOrSetting({...e,...AssetFileFlags.toContext(this.flags)})}get $asset(){if(this.#t!=null)return this.#t;if(gt0(this.assetId))return this.#t=Asset.ops().findById(this.assetId)}set $asset(e){this.assetId!=null&&e?.id!==this.assetId&&this.logger().throw(`set $asset(): mismatched .assetId`,{currentAssetId:this.assetId,newAssetId:e?.id}),this.#t=e,this.assetId=e?.id}get nativePath(){return this.#i==null?this.#i??=Volume.resolve_(this.uri):this.#i}async resolveNativePath_(){return this.#i==null?this.#i??=await e.resolveUriNativePath_(this.uri):this.#i}withDirUri(e){return e.id===this.dirUriId?(this.#n=e,this):this.logger().throw(`withDirUri(): DirUri id mismatch`,{dirUriId:this.dirUriId,given:e.id})}get dirUri(){return this.#n==null&>0(this.dirUriId)&&(this.#n=DirUri.ops().findById(this.dirUriId)),this.#n}get uri(){if(this.#r!=null)return this.#r;if(blank(this.basename))return this.logger().throw(`uri(): basename is not set`,{self:this});let e=this.dirUri;return e==null?this.logger().throw(`uri(): dirUriId is not set`,{self:this}):this.#r??=e.joinPath(this.basename)}toJSON(){let e=super.toJSON();try{(this.#r!=null||gt0(this.dirUriId)&¬Blank(this.basename))&&(e.uri=this.uri)}catch{}try{(this.#i!=null||e.uri!=null)&&(e.nativePath=this.nativePath)}catch{}return e}$afterSave(){super.$afterSave(),this.#s()}#s(){this.id!=null&&(this.isPrimary!==!0||this.assetId==null?deleteAssetFileHash(e.db().db,this.id):syncAssetFileHash(e.db().db,this.id,this))}get uriObject(){return this.#a??=URI.parse(this.uri)}mediaInfo_(){return this.#o??=MediaInfoFactory.for(this.posixFile_())}setUri(e,n){blank(e)&&this.logger().throw(`setUri(): uri cannot be null, undefined or blank`);let r=toURI(e);!blank(this.#r)&&!uriEqlSync(this.#r,r)&&this.logger().throw(`setUri(): Cannot change URI after initialization - URIs are business keys and should be immutable`,{currentUri:this.#r,newUri:e});let a=extractUriDirectory_(r);blank(a)&&this.logger().throw(`setUri(): failed to extract directory from URI`,{uri:e});let o=extractUriBasename_(r);blank(o)&&this.logger().throw(`setUri(): failed to extract basename from URI`,{uri:e}),gt0(this.id)&>0(this.dirUriId)?o===this.basename&&uriEqlSync(this.uri,r)||this.logger().throw(`setUri(): Cannot change URI after initialization - URIs are business keys and should be immutable`,{currentUri:this.uri,newUri:e}):(this.#n??=DirUri.findOrCreateByUri_({uri:a,nativePath:n}),this.dirUriId=this.#n.id,this.basename=o,this.#r=r.toString()),n!=null&&this.dirUri?.rememberNativePath_(n)}async setFile_(e){return this.#i===e.nativePath?this.dirUri?.rememberNativePath_(e.dir):(this.#i=e.nativePath,this.setUri(await e.uri_(),e.dir)),this}deleteFromArray(e){e!=null&>0(this.id)&&filterInPlace(e,e=>e.id!==this.id&&e.uri!==this.uri)}librarySiblings(){return this.getAsset()?.getAssetFiles().filter(e=>e.id!==this.id&&isLibraryUri(e.uri))}get posixPathFromGrandparent(){return map(this.uriObject?.fsPath,posixPathFromGrandparent)}isInLibrary(){return isLibraryUri(this.uri??``)}async inSyncWithFile(e){return blank(await this.whyNeedsUpsert(e))}async whyNeedsUpsert(e){return this.locationIsApproximate?`approximate location`:(await this.resolveNativePath_(),whyIsMediaInfoStale(this.ctx(e),this,this.mediaInfo_()))}async siblingCount(){return e.dbl.pluckFirstf(e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id}))}async upsertIfNeeded_(e,n){if(e!=null&&await this.setFile_(e),await this.whyNeedsUpsert(n)==null){this.$syncState??=AssetFileSyncStates.unchanged;return}let r=this.sha;return await this.updateFromFile_(),gt0(this.id)&>0(this.assetId)&&!blank(r)&&!blank(this.sha)&&r!==this.sha&&this.addFlag(`contentChanged`),this.$syncState===AssetFileSyncStates.deleted?await this.remove():this.$syncState===AssetFileSyncStates.imported&&this.upsert(),this.$syncState===AssetFileSyncStates.unchanged?void 0:this}async updateFileFields_(){assignFields(this,await awaitFields(pick(this.mediaInfo_(),`mtime`,`fileSize`)))}async updateFromFile_(e){if(e!=null&&await this.setFile_(e),await this.exists_()){let e=pick(await this.mediaInfo_().asMediaInfo_(),...MediaInfoFieldNames.omit(`uri`,`nativePath`,`basename`));return assignFields(this,e),assignFields(this,fromEntries(ImageHashTypes.values.map(n=>[`${n}0`,e[`${n}0`]??null])),{assignNullish:!0}),assignFields(this,pick(e,`latitude`,`longitude`),{assignNullish:!0}),this.clearFlag(`forceSync`),this.clearFlag(`locationIsApproximate`),this.$syncState=SyncFileStates.imported,this}return!0===await this.isUriDeleted()?(this.$syncState=AssetFileSyncStates.deleted,this.logger().info(`updateFromFile_() file is deleted`,{uri:this.uri,basename:this.basename}),await this.remove(),this):(this.$syncState=AssetFileSyncStates.unavailable,this)}async updateFromShaSibling_(e){let n=await e.whyNeedsUpsert();if(n!=null)return this.logger().warn(`updateFromShaSibling() sibling is invalid`,{whySiblingIsInvalid:n,uri:this.uri,siblingUri:e.uri}),this.updateFromFile_();let r=omit(e,`id`,`$instanceId`,`dirUriId`,`basename`,`isPrimary`,`mtime`,`createdAt`,`updatedAt`,`updateCount`,`flags`,`dirUri`,`uri`,`$syncState`,`nativePath`,`posixFile`);if(!await this.exists_())this.logger().warn(`updateFromShaSibling(): fail: file is missing`,{uri:this.uri,basename:this.basename});else return this.logger().debug(`updateFromShaSibling`,{safeSiblingFields:r}),this.sha==null||this.sha===e.sha?(assignFields(this,r),assignFields(this,pick(r,`latitude`,`longitude`),{assignNullish:!0}),this.clearFlag(`locationIsApproximate`),this.updateFileFields_()):this.updateFromFile_()}getAsset(){return this.$asset}getAsset_(){return this.$asset??this.logger().throw(`getAsset_(): no parent Asset`,{assetId:this.assetId,uri:this.uri,basename:this.basename})}async exists_(){let e=await this.resolveNativePath_();return e!=null&&await exists(e)}async isUriDeleted(){return(await isUriDeleted(this.uri))?.result}async whyRejected(e){return!0===await this.isUriDeleted()?`deleted`:(await this.resolveNativePath_(),whyFileRejected({file:this.posixFile_(),forceFilters:this.ctx(e).forceFilters}))}async accepted(){return blank(await this.whyRejected())}get $bname(){return mapNotBlank(this.basename,bname)}posixFile_(){return PosixFile.for(this.nativePath)}posixFile(){try{return this.posixFile_()}catch{return}}get $canIncludeInputDim(){let e=this.posixFile();return e!=null&&canIncludeInputDim(e,this.mimetype)}previewPlan(){return previewPlanForCurrentSettings({dim:previewPlanDimensions(this.$asset,this),mimetype:this.mimetype,canIncludeInputDim:this.$canIncludeInputDim})}async upgradeUri(n){if(!gt0(this.id))return this.logger().throw(`upgradeUri(): unset .id`+InternalErrorFlag);if(!await uriIsEquivalent(this.uri,n))return this.logger().throw(`upgradeUri(): non-equivalent URIs`+InternalErrorFlag,{this_uri:this.uri,newUri:n});if(!blank(this.#r)){let r=extractUriDirectory_(n),a=extractUriBasename_(n),o=DirUri.ops().findOneBy({uri:r}),s=o?e.ops().findOneBy({dirUriId:o.id,basename:a}):void 0;if(s?.id===this.id)return s;if(s!=null)return this.logger().warn(`upgradeUri(): prior row with URI exists`,{uri:n,prior_id:s.id,old_uri:this.uri}),await this.remove(),s}this.logger().info(`upgradeUri()`,{prior_uri:this.uri,newUri:n});let r=toURI(n),a=extractUriDirectory_(r),o=extractUriBasename_(r);return this.#r=void 0,this.#i=void 0,this.#a=void 0,this.#o=void 0,this.#n=DirUri.findOrCreateByUri_({uri:a}),this.dirUriId=this.#n.id,this.basename=o,this.#r=r.toString(),this.updatedAt=Date.now(),e.dbl.runf(e=>e.update(pick(this,`dirUriId`,`basename`,`updatedAt`)).where({id:this.id})),this}async originalDownloadable({brief:e=!1}={}){let n=this.basename;if(e===!0)return n==null?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:`original`,title:`Download ${n}`,basename:n,description:`Download original`};await resolveNativePaths([this]);let r=this.posixFile_();return this.logger().tap({msg:`originalDownloadable()`,level:`info`,result:r==null||await r.isEmptyOrMissing()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:`original`,title:mkDownloadableTitle(r,`original`,this.$isVideo?`video`:`image`,this),basename:this.basename,description:`Download original`,details:`(${fmtDim(this)} ${r.ext})`},meta:{posixFile:r}})}async downloadables(e,n){try{await resolveNativePaths([this]);let r=this.posixFile_(),a=e.ap(this.assetId),o=[],s=await this.originalDownloadable();if(s!=null&&o.push(s),this.$isVideo||!(isTrue(this.isPrimary)||this.sha===n))return o;let c=await a.existingFiles(),l=await a.previewSetStatus(this.previewPlan(),c),u=[];for(let{required:e,actual:n}of l.present){if(e.reducer!==ReducerNames.fit)continue;let a=planRungDownloadable({basename:r.base,assetId:this.assetId,file:n.file,rung:e});a!=null&&u.push({downloadable:a,pixelCount:pixels(e.outputSize)})}if(u.length===0){let e=await a.previewSetInventory(c);for(let n of e.images){if(n.reducer!==ReducerNames.fit)continue;let e=await physicalPreviewDimensions(n);if(e==null)continue;let a=await previewToDownloadable(r.base,n);a!=null&&u.push({downloadable:a,pixelCount:pixels(e)})}}return u.sort((e,n)=>n.pixelCount-e.pixelCount),o.push(...uniqBy(u.map(e=>e.downloadable),e=>e.size)),o}catch(e){return onError(`AssetFile.downloadables failed for `+this.uri,e),[]}}async pathInfo(){try{let e=map(originalsLibraryTagPath({uri:this.uri,isFile:!0}),e=>Tag.dao.findByPath(e)),n=e!=null&&AssetTag.dbl.pluckAllf(n=>n.select(`AssetTag.tagId`).join(`TagHierarchy`,`TagHierarchy.descendantId`,`AssetTag.tagId`).where({"AssetTag.assetId":this.assetId,"TagHierarchy.tagId":e.id}).limit(1)).length>0,r=n?e:map(uriToTagPath({uri:URI.parse(this.uri),isFile:!0}),e=>Tag.dao.findByPath(e));return this._pathInfo_(await r?.toApiPathElements(),n)}catch(e){this.logger().warn(`pathInfo(): failed`,{error:e,uri:this.uri,basename:this.basename});return}}async _pathInfo_(e,n=!1){let r=await this.resolveNativePath_();if(r==null){this.logger().info(`pathInfo(): the volume or share this file is on is not mounted`,{uri:this.uri});return}let a=PosixFile.for(r),o=URI.parse(this.uri);if(e==null||isEmpty(e))return this.logger().warn(`pathInfo(): failed to find existing Tag. Returning a simple path.`,{uri:this.uri,nativePath:r,tagLineage:e}),{nativePath:r,pathElements:[],nativePathSuffix:r,pathSep:import_node_path66.sep,exists:await a.exists()};eql(e[0]?.tagPath,[TagRoots.fs])&&(e=e.slice(1));function s(){return at(at(e,-1)?.tagPath,-1)}let c=o.scheme===PS_LIBRARY_SCHEME||n?libraryRelativePath(this.uri):void 0,l=c==null?a.pathnames:c.split(`/`).slice(1),u=l.pop(),d=[];for(;l.length>0&&equalsIgnoreCase(s(),at(l,-1));){l.pop();let n=e.pop();d.unshift(n),this.logger().debug(`added matching tag`,n)}let f=c!=null&&s()===LibraryTagName;if(f){l.pop();let n=e.pop();d.unshift(n),this.logger().debug(`added matching library tag`,n)}if(!f&&o.scheme===PS_LOCAL_FILE_SCHEME){let n=URI.parse(this.uri).authority;if(this.logger().debug(`psfile: pop last?`,{lastTagName:s(),thisVolSha:n}),s()===n){l.pop();let n=e.pop();d.unshift(n)}else this.logger().warn(`weird: I expected to be able to include the volsha tag element, but it doesn't seem to match`,{thisVolSha:n,tagVolSha:s()})}return this.logger().tap({msg:`pathInfo()`,result:{nativePath:r,pathElements:d,nativePathSuffix:u,pathSep:import_node_path66.sep,exists:await a.exists()}})}async toApi(e,n){let r=await this.pathInfo();if(r==null)return;let a=fileBrowserFolderUrl(r.nativePath),o=hostPathFor(r.nativePath);return reqValuedOrElse({...a==null?{}:{fileBrowserUrl:a},...o==null?{}:{hostPath:o},assetId:this.assetId,assetFileId:this.id,...r,mimetype:this.mimetype,isPrimary:isTrue(this.isPrimary),name:this.basename,width:this.width,height:this.height,rotation:this.rotation??0,fileSize:this.fileSize,mtime:this.mtime,downloadables:await this.downloadables(e,n),createdAtLocale:fmtMillis(this.createdAt),updatedAt:this.updatedAt})}get $isVideo(){return isVideoMimeType(this.mimetype)}async remove(){if(this.id==null)this.logger().warn(`remove() called on an AssetFile without an id`,{uri:this.uri,basename:this.basename});else{if(this.assetId!=null){if(e.dbl.count(e=>e.where({assetId:this.assetId}).andWhereNot({id:this.id}))===0)this.logger().info(`.remove(): Deleting now-empty asset`,{assetId:this.assetId}),await Asset.dao.remove({assetId:this.assetId,blocklistShas:!1,unlinkAssetFiles:!1});else if(isTrue(this.isPrimary)){let e=this.getAsset();e==null?this.logger().warn(`.remove(): Could not find asset to repair after removing primary AssetFile`,{assetId:this.assetId,assetFileId:this.id,uri:this.uri}):(e.update({shown:!1,flags:AssetFlags.add(e.flags,`validateSiblings`)}),e.deletedAt==null&&e.excludedAt==null?(this.logger().info(`.remove(): Repairing asset because I was the preview source`,{assetId:this.assetId}),addTask(`repairAsset`,{assetId:this.assetId})):this.logger().info(`.remove(): Asset is deleted or excluded, not repairing`,{assetId:this.assetId}))}else this.logger().debug(`.remove(): AssetFile removed without impacting the asset.`,{assetId:this.assetId,assetFileId:this.id})}super.remove()}}};function fmtMillis(e){return map(e,e=>fmtDuration(Date.now()-e,{units:1})+` ago`)}async function resolveNativePaths(e){let n=[];for(let r of e)try{let e=await r?.resolveNativePath_();e!=null&&n.push(e)}catch(e){AssetFile.$logger().warn(`resolveNativePaths(): source unavailable`,{assetFileId:r?.id,uri:r?.uri,error:e})}return n}var VisibleAsset={"Asset.excludedAt":null,"Asset.deletedAt":null},AssetRevision=class e extends Model{static $tableName=`AssetRevision`;static insert(...n){return e.ops().insert(n.map(e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:stringify(e.priorValue),_newValueJson:stringify(e.newValue)})))}assetId;createdAt;field;op;_priorValueJson;_newValueJson;get priorValue(){return parseJSON(this._priorValueJson)}get newValue(){return parseJSON(this._newValueJson)}},Unhidden={"Asset.shown":1,"Asset.hidden":0,...VisibleAsset},AssetDao=class extends ModelDao{constructor(){super(Asset)}shownUnhidden(e){return e==null?Asset.query().where(Unhidden):e.andWhere(Unhidden)}assetsByIds(e){return isEmpty(e)?[]:compact(Asset.dbl.all(this.shownUnhidden().select(assetIdColumns()).whereIn(`Asset.id`,e)).map(e=>toAssetId(e)))}shownRemovable(e,n){return(n??Asset.query()).whereNotNull(e).andWhere({"Asset.shown":1})}shownCount(){return Asset.ops().count(this.shownUnhidden().countDistinct(`Asset.id`))}deletePreviews(e){return Library.instance().previews().ap(e).deleteAll()}async remove({assetId:e,blocklistShas:n,unlinkAssetFiles:r,deletionPaths:a,retainFailedFiles:o=!1}){let s=mkLogger(`Asset(`+e+`).remove()`),c=Asset.ops().findById(e);if(c==null){s.warn(`asset not found`);return}let l=c.isActive(),u=c.tagIds();s.info(`starting`,{unlinkAssetFiles:r});let d=c.getAssetFiles({refresh:!0});r&&await resolveNativePaths(d);let f=r?await trashOrRmUris(d.map(e=>({uri:e.uri,nativePath:e.posixFile()?.nativePath})),{allowMissing:!0,allowedPaths:a}):[],h=new Set(f.filter(e=>e.action!==`error`).map(e=>e.uri)),_=r&&o?d.filter(e=>!h.has(e.uri)):[];if(n){let e=new Set(_.map(e=>e.sha)),n=d.filter(n=>!e.has(n.sha));upsertToShaBlocklist(...n.map(e=>e.sha));for(let e of n)syncReport().onProgress({from:`Asset.remove`,path:e.posixFile()?.nativePath??e.uri,type:`file`,state:`blocklisted`,details:`sha blocklisted (files with the same sha will not be imported)`})}let y=new Set(_.map(e=>e.id));if(Asset.dbl.txn(()=>{for(let e of d)y.has(e.id)||(deleteAssetFileHash(Asset.db().db,e.id),AssetFile.dbl.runf(n=>n.delete().where({id:e.id})));_.length>0?(_.some(e=>e.isPrimary)||_[0].upsert({isPrimary:!0}),Asset.dbl.runf(n=>n.where({id:e}).update({updatedAt:Date.now()}))):(AssetTag.dbl.runf(n=>n.delete().where({assetId:e})),AssetRevision.dbl.runf(n=>n.delete().where({assetId:e})),Asset.dbl.runf(n=>n.delete().where({id:e})),l&&Tag.dao.deltaAssetCountAndAncestors(u,-1))}),_.length>0)return{removed:!1,deletedMeta:f,assetFileMeta:d};try{await this.deletePreviews(e)}catch(n){s.error(`Failed to delete previews`,{error:n,assetId:e})}return{removed:!0,deletedMeta:f,assetFileMeta:d}}getTags(e){return Tag.ops().all(Tag.query().select(`Tag.*`).join(`AssetTag`,`AssetTag.tagId`,`Tag.id`).where(`AssetTag.assetId`,e).orderByRaw(`COALESCE(Tag.ordinal, Tag._path)`))}setFlag(e,n){this.updateFlag({assetId:e,flag:n,isSet:!0})}clearFlag(e,n){this.updateFlag({assetId:e,flag:n,isSet:!1})}updateFlag({assetId:e,flag:n,isSet:r}){Asset.dbl.runf(a=>AssetFlags.update({qb:a,flag:n,isSet:r}).where(`id`,e))}scheduleFinalizeAsset(e){this.setFlag(e,`finalize`),this.clearFlag(e,`failedFinalize`),ee().emitThrottled(`notifyWorkAvailable`,`finalizeAsset`)}},Asset=class e extends TimestampedModel{static $tableName=`Asset`;static $booleanFields=[`shown`,`hidden`];static#e;static get dao(){return this.#e??=new AssetDao}shown;hidden;excludedAt;deletedAt;updateCount;previewFingerprint;renderWidth;renderHeight;previewSourceMtime;previewSourceSize;capturedAtLocal;mimetype;rating;durationMs;assetFiles;tags;streams;afterId;beforeId;globalAfterId;globalBeforeId;assetIdish=lazy2(()=>toAssetId(this)??this.logger().throw(`assetIdish(): asset has no id or capturedAtLocal`,{assetId:this.id}));flags;getFlags(){return AssetFlags.decode(this.flags)}hasFlag(e){return AssetFlags.has(this.flags,e)}addFlag(e){this.flags=AssetFlags.add(this.flags,e)}clearFlag(e){this.flags=AssetFlags.remove(this.flags,e)}markUnshownAndUpsert(){if(gt0(this.id)){let n=this.isActive(),r=n?this.tagIds():[];e.dbl.runf(e=>e.where({id:this.id}).update({shown:0,updatedAt:Date.now()})),this.shown=!1,n&&r.length>0&&Tag.dao.deltaAssetCountAndAncestors(r,-1)}else this.shown=!1}#t(){return{...this.toJSON(),primaryAfId:this.getPrimary({refresh:!1})?.id}}snapshotForUpdateCount(){return this.#t()}upsertIfChanged(e,n){return eql(e,this.#t())?(this.logger().info(n+`: no changes, skipping upsert`),!1):(this.logger().info(n+`: upserting`),this.upsert(),!0)}async markShownAndUpsert_(n,r=this.snapshotForUpdateCount()){await this.setPrimary_(n,{skipAssetUpsert:!0});let a=e.ops().findById(this.id);return AssetFlags.has(a?.flags,`validateSiblings`)?(this.logger().warn(`markShownAndUpsert_(): validateSiblings set during operation, aborting`),r):this.getPrimary({refresh:!0})==null?(this.logger().warn(`markShownAndUpsert_(): no primary after setPrimary_, aborting`),r):(this.shown=!0,this.upsertIfChanged(r,`markShownAndUpsert_()`),this.snapshotForUpdateCount())}mergedTags=lazy2(async()=>{let e=new MergedTags(`Asset:`+this.id);await resolveNativePaths(this.getAssetFiles());for(let n of this.getAssetFiles()){let r=n.posixFile();r!=null&&await e.addFile(r,isTrue(n.isPrimary))}return e.addRevision(...AssetRevision.ops().allf(e=>e.where({assetId:this.id}))),e});async updateFromFiles(){map((await this.mergedTags()).get(`rating`),e=>{this.logger().info(`updateFromFiles()`,{rating:e}),this.rating=e.value})}isActive(){return gt0(this.id)&&this.shown===!0&&this.hidden!==!0&&this.excludedAt==null&&this.deletedAt==null&&(this.rating==null||!Settings2.rejectRating.test(this.rating))}async whenApiTag(){let e=dateTag(localToDateObject(this.capturedAtLocal));return e==null?void 0:Tag.dao.findOrCreate(e).toApiTag({includeChildren:!1})}findAssetFileByUri(e){return this.getAssetFiles()?.find(n=>n.uri===e)}addAssetFile(e){(e.$asset!==this||e.assetId!==this.id)&&e.deleteFromArray(e.$asset?.assetFiles),e.assetId=this.id,e.$asset=this;let n=this.getAssetFiles();e.deleteFromArray(n),n.push(e),e.basename??(e.isPrimary=!1),this.clear()}async assetFileForFile_(e,n){let r=await e.uri_(),a=this.getAssetFiles().find(e=>e.uri===r);if(a!=null)return a;let o=new AssetFile;return this.addAssetFile(o),n?.skipUpsert===!0?await o.setFile_(e):await o.upsertIfNeeded_(e),o}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map(e=>e.id)??AssetTag.dbl.pluckAllf(e=>e.select(`tagId`).where({assetId:this.id}))}getTags(n){return!0===n?.refresh&&(this.tags=void 0),this.tags??=e.dao.getTags(this.id)}tagPaths(){return this.getTags().map(e=>e.path.join(`/`)).sort()}setTagIds(e){let n=this.tagIds({refresh:!0});if(eqlUnordered(n,e)){this.logger().debug(`setTagIds(): no-op, tagIds unchanged`);return}let r=e.filter(e=>!n.includes(e)),a=n.filter(n=>!e.includes(n));return this.applyTagIdDeltas({tagIdsToAdd:r,tagIdsToRemove:a})}applyTagPathDeltas(e,n){return this.applyTagIdDeltas({tagIdsToAdd:Tag.dao.findOrCreateByPathN(e.add??[]).map(e=>e.id),tagIdsToRemove:Tag.dao.findByPathN(e.remove??[]).map(e=>e.id)},n)}applyTagIdDeltas(e={},n){let r=n?.priorIsActive??this.isActive(),a=this.tagIds({refresh:!0}),o=uniq(toA(e.tagIdsToAdd).filter(e=>gt0(e)&&!a.includes(e))),s=uniq(toA(e.tagIdsToRemove).filter(e=>gt0(e)&&a.includes(e)));if(isEmpty(o)&&isEmpty(s))return this.logger().info(`applyTagIdDeltas(): no-op, no changes`,{currentTagIds:a,...e}),a;r&&Tag.dao.deltaAssetCountAndAncestors(a,-1),isEmpty(o)||AssetTag.dbl.upsert(o.map(e=>({assetId:this.id,tagId:e}))),isEmpty(s)||AssetTag.dbl.runf(e=>e.whereIn(`tagId`,s).andWhere({assetId:this.id}).delete()),this.tags=void 0;let c=uniq([...a,...o]).filter(e=>!s.includes(e));return this.isActive()&&Tag.dao.deltaAssetCountAndAncestors(c,1),c}getStreams(e){if(this.streams==null){let n=this.getTags();this.logger().debug(`getStreams()`,{tagCount:n.length,limit:e});let r=n.map(n=>n.getAssetStream(this,e));this.streams=groupCorrelatedStreams(compact(r)).map(n=>n.length===1?n[0]:new TagAssetScope(n.flatMap(e=>e.tags)).getAssetStream(this,e));for(let e of this.streams)for(let n of e.tags)n.getAncestors()}return this.streams}static#n(){return e.dao.shownUnhidden().clearSelect().select({assetId:`id`,v:`updateCount`,capturedAtLocal:`capturedAtLocal`,renderWidth:`renderWidth`,renderHeight:`renderHeight`})}getBeforeAfterId(){let n=e.dbl.all(e.#n().andWhere(`capturedAtLocal`,this.capturedAtLocal).orderBy(`assetId`)),r=n.filter(e=>e.assetId>this.id);this.afterId=r[0];let a=n.filter(e=>e.assetId<this.id).reverse();this.beforeId=a[0],this.afterId??this.#i(),this.beforeId??this.#r()}#r(){let n=e.dbl.all(e.#n().andWhere(`capturedAtLocal`,`<`,this.capturedAtLocal).orderBy([{column:`capturedAtLocal`,order:`desc`},{column:`assetId`,order:`desc`}]).limit(1));this.beforeId??=n[0]}#i(){let n=e.dbl.all(e.#n().andWhere(`capturedAtLocal`,`>`,this.capturedAtLocal).orderBy([{column:`capturedAtLocal`,order:`asc`},{column:`assetId`,order:`asc`}]).limit(1));this.afterId??=n[0]}static getChronologicalStream(n,r){r=gt0(r)?r:BeforeAfterStreamLimit;let a=compact(e.dbl.all(e.#n().andWhere(`capturedAtLocal`,`<`,n.capturedAtLocal).orderBy([{column:`capturedAtLocal`,order:`desc`},{column:`assetId`,order:`desc`}]).limit(r)).map(toAssetId)),o=compact(e.dbl.all(e.#n().andWhere(`capturedAtLocal`,n.capturedAtLocal).andWhereNot(`id`,n.id).orderBy(`assetId`)).map(toAssetId)),s=compact(e.dbl.all(e.#n().andWhere(`capturedAtLocal`,`>`,n.capturedAtLocal).orderBy([{column:`capturedAtLocal`,order:`asc`},{column:`assetId`,order:`asc`}]).limit(r)).map(toAssetId));for(let e of o)e.assetId<n.id?a.push(e):s.push(e);return new TaggedAssetStream([],a,s.reverse(),r)}getTagPaths(){return this.getTags().map(e=>e.path)}getAssetFiles({refresh:e=!1}={}){if(gt0(this.id)&&(this.assetFiles==null||e===!0)){let e=AssetFile.ops();this.assetFiles=e.allf(e=>e.where({assetId:this.id}).orderBy(`id`)),sortAssetFilesInPlace(this.assetFiles);for(let e of this.assetFiles)e.$asset=this}return this.assetFiles??[]}async setPrimary_(n,r){let a=n instanceof AssetFile?n:AssetFile.ops().findById(n);if(a==null)return this.logger().throw(`setPrimary_(): asset file not found`,{af:a});if(await a.resolveNativePath_(),a.posixFile_()==null)return this.logger().throw(`setPrimary_(): asset file has no native path`,{af:a});let o=this.getAssetFiles();this.addAssetFile(a);let s=a instanceof AssetFile?a.id:a,c=this.id;if(!gt0(c)||!gt0(s))return this.logger().throw(`setPrimary_(): invalid IDs: `+stringify({assetId:this.id,assetFileId:s})+InternalErrorFlag);let l=o.find(e=>e.id===s);if(l==null)return this.logger().throw(`setPrimary_(): failed to find shown asset file`,{af:a});this.logger().info(`setPrimary_()`,{assetId:this.id,assetFileId:s});for(let e of o)e.id??e.upsert();if(isTrue(l.isPrimary)&&l.assetId===c){this.logger().debug(`setPrimary_(): file is already primary, skipping DB update`);for(let e of o)e.isPrimary=e.id===s;e.ops().assignFromPojo(this,{...pick(a,`mimetype`,`rating`,`durationMs`),capturedAtLocal:this.getCapturedAt()?.capturedAtLocal??a.capturedAtLocal}),r?.skipAssetUpsert!==!0&&this.upsert();return}let u=Date.now(),d=o.find(e=>isTrue(e.isPrimary)&&e.id!==s),f=AssetFile.db().db;AssetFile.dbl.txn(()=>{AssetFile.dbl.runf(e=>e.where({id:s}).update({assetId:c,isPrimary:0,updatedAt:u})),AssetFile.dbl.runf(e=>e.where({assetId:c,isPrimary:1}).update({isPrimary:0,updatedAt:u})),AssetFile.dbl.runf(e=>e.where({id:s}).update({isPrimary:1,updatedAt:u})),d?.id!=null&&deleteAssetFileHash(f,d.id),syncAssetFileHash(f,s,{...pick(l,`pHash`,`rHash`,`wHash`,`pHash0`,`rHash0`,`wHash0`),capturedAtLocal:l.capturedAtLocal??0,capturedAtSrc:l.capturedAtSrc??`unknown`,basename:l.basename})});for(let e of o)e.isPrimary=e.id===s,e.updatedAt=u;e.ops().assignFromPojo(this,{...pick(a,`mimetype`,`rating`,`durationMs`),capturedAtLocal:this.getCapturedAt()?.capturedAtLocal??a.capturedAtLocal}),r?.skipAssetUpsert!==!0&&this.upsert()}getPrimary(e){let n=this.getAssetFiles(e).find(e=>isTrue(e.isPrimary));return this.logger().debug(`getPrimary()`,{opts:e,assetFileId:n?.id}),n}getOrSetPrimary(){let e=this.getPrimary({refresh:!0});if(e!=null)return e;let n=this.getAssetFiles({refresh:!0});if(n.length===0)return;let r=n[0];this.logger().info(`getOrSetPrimary(): setting primary on asset with none`,{assetId:this.id,bestFileId:r.id,bestFileUri:r.uri,fileCount:n.length});try{return r.isPrimary=!0,r.upsert(),r}catch(e){return this.logger().warn(`getOrSetPrimary(): failed to set primary`,{assetId:this.id,bestFileId:r.id,error:e}),this.getPrimary({refresh:!0})}}getPrimaryNativePath(){return this.getPrimary()?.posixFile()?.nativePath}getCapturedAt(){let e=this.getCapturedAtFile();return e==null?void 0:CapturedAt.fromMediaInfo(e)}getCapturedAtFile(){return sortBy(this.getAssetFiles().map(e=>({file:e,date:CapturedAt.fromMediaInfo(e)})).filter(e=>e.date!=null),e=>[CapturedAtSrcTypes.ordinal(e.date.capturedAtSrc),e.date.capturedAtLocal,e.file.sha??``,e.file.uri??``])[0]?.file}link(){return`/asset/`+this.id}#a(e){return e.role===`thumbnail`?assetThumbnailImgLink({assetId:this.assetIdish(),reducer:ReducerNames.fit,longEdge:e.longEdge}):assetImgLink({assetId:this.assetIdish(),reducer:ReducerNames.fit,longEdge:e.longEdge})}async fitAttrs(e){let n=this.getPrimary();if(n==null)return this.logger().throw(`fitAttrs(): asset has no primary AssetFile`,{assetId:this.id});await resolveNativePaths([n]);let r=n.previewPlan(),a=new Map;for(let e of r.fit){let n=e.outputSize.width,r=pixels(e.outputSize),o=a.get(n);(o==null||r>o.pixelCount)&&a.set(n,{width:n,pixelCount:r,link:this.#a(e)})}let o=[...a.values()].sort((e,n)=>e.width-n.width);n.posixFile()!=null&&!a.has(r.sourceSize.width)&&a.set(r.sourceSize.width,{width:r.sourceSize.width,pixelCount:pixels(r.sourceSize),link:assetImgActualLink({assetId:this.assetIdish(),assetFileId:n.id})});let s=[...a.values()].sort((e,n)=>e.width-n.width),c=fmtLocalToShort(this.capturedAtLocal),l={width:o[0].width.toString(),src:o[0].link,srcSet:s.map(e=>`${e.link} ${e.width}w`).join(`,`),loading:`eager`,decoding:`async`};return o.length>1&&(l.sizes=o[0].width+`px`),c!=null&&(l.title=c),l}isVideo(){return this.getAssetFiles().some(e=>e.$isVideo)}async videoAttrs(e){let n=this.getPrimary(),r;return n?.$isVideo===!0&&(r=map(greatestBy(n.previewPlan().fit,e=>pixels(e.outputSize)),e=>this.#a(e))),{controls:!0,autoplay:!1,poster:r}}async videoSources(){let e=[],n;await resolveNativePaths(this.getAssetFiles());for(let r of this.getAssetFiles()){if(e.some(e=>e.type===r.mimetype))continue;let a=r.posixFile();a!=null&&await a.exists()&&(n??=r,e.push({src:assetVideoLink({assetId:this.assetIdish(),assetFileId:r.id}),type:r.mimetype}))}return!e.some(e=>e.type===`video/mp4`)&&n!=null&&e.unshift({src:assetVideoLink({assetId:this.assetIdish(),assetFileId:n.id})+`.mp4`,type:`video/mp4`}),e}async getExistingAssetFiles(){return filterAsync({arr:this.getAssetFiles(),f:async e=>{try{return await e.exists_()}catch(n){return this.logger().warn(`getExistingAssetFiles(): source unavailable`,{assetFileId:e.id,uri:e.uri,error:n}),!1}}})}async findOrCreateByFile(e){let n=await e.uri_();if(n==null){this.logger().warn(`findOrCreateByFile(): null uri`,{nativePath:e.nativePath});return}let r=extractUriDirectory_(n),a=extractUriBasename_(n),o=DirUri.findOrCreateByUri_({uri:r,nativePath:e.dir}),s=AssetFile.ops().findOneBy({assetId:this.id,dirUriId:o.id,basename:a});if(s!=null)return s;let c=new AssetFile;return this.addAssetFile(c),await c.upsertIfNeeded_(e),c}partialSimpleAsset(){return{assetId:this.id,liked:gte(this.rating,Settings2.likeRating.valueOrDefault),hidden:isTrue(this.hidden),excluded:this.excludedAt!=null,deleted:this.deletedAt!=null}}clear(){return this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}};function assetMutationLockFile(e){let n=libraryDataDirPosixFile();if(n==null)throw Error(`Library is not available`);return n.join(`asset-actions`,String(e%64))}async function withAssetMutationLock_(e,n){let r=new FsLock({file:assetMutationLockFile(e),processLifetime:!0,timeoutMs:0});try{if(!await r.acquire_({timeoutMs:ProcessLifetimeLockTimeoutMs}))throw new UserFacingError(`Asset is busy; try again after the current operation finishes`);return await n()}finally{r.release(),await r.end()}}var AssetQueryOrderByColumns=strEnum(`capturedAt`),MIN_SEED=1,MAX_SEED=99;function prngSeed(){return randomInt(MIN_SEED,MAX_SEED+1)}var urlSeed=lazy(prngSeed,100);function ensureSeed(e,n){let r=toURLSearchParams(e);if(n||!isDigits(r?.get(`seed`))){let e=urlSeed().toString();return r?.set(`seed`,e),r??{seed:e}}return r}function mkTagUri(e,n,r=!1){return{path:`/tag/`+(isEmpty(e)?``:e.map(encodeURIComponent).join(`/`)),query:ensureSeed(n,r)}}var UriDefaults=lazy2(()=>({protocol:`http`,host:NetworkingSettings.hostname.valueOrDefault??`localhost`,url:`/`})),logger128=lazy2(()=>mkLogger(`express.ServerToastHelpers`)),SyncStatuses=strEnum(`processing`,`paused`,`done`,`failed`),SyncFolderURI=`syncfolder://`;function isTerminalSyncStatus(e){return e===`done`||e===`failed`}var import_node_os20=require("node:os"),import_node_process28=require("node:process"),DirSyncProgressMetaNames=strEnum(`lastScannedDirectory`,`scannedDirectoryCount`,`completedDirectoryScan`,`enqueuedStaleFiles`,`processedImageCount`,`processedVideoCount`,`completedDirectorySync`,`scanGeneration`,`totalFilesDiscovered`,`excludedByFilterCount`,`excludedByImporterCount`,`erroredCount`,`excludedDirCount`,`newImageCount`,`newVideoCount`,`updatedImageCount`,`updatedVideoCount`,`unchangedImageCount`,`unchangedVideoCount`,`absentCount`,`resumed`,`syncReportFilename`,`syncReportFilenames`),AssetActionProgressMetaNames=strEnum(`assetId`,`errorDetails`,`nonAdminErrorDetails`),ProgressMetaNames=strEnum(...DirSyncProgressMetaNames.values,...AssetActionProgressMetaNames.values),ProgressMeta=class extends TimestampedModel{static $tableName=`ProgressMeta`;static $businessKeys=[`name`,`progressId`];progressId;name;value},logger129=defer(()=>mkLogger(`model.Progress`));function toPct(e){return e==null||!isNumber(e)||e<0||e>100?void 0:sigFigs(e,3)}var ProgressTimesQuery=compressWhitespace(`
|
|
686
|
+
SELECT
|
|
687
|
+
p1.uri,
|
|
688
|
+
p1.id as lastProgressId,
|
|
689
|
+
p1.createdAt as lastStartedAt,
|
|
690
|
+
p1.updatedAt as lastUpdatedAt,
|
|
691
|
+
p3.lastCompletedAt,
|
|
692
|
+
p3.lastCompletedProgressId
|
|
693
|
+
FROM
|
|
694
|
+
Progress AS p1
|
|
695
|
+
JOIN (
|
|
696
|
+
SELECT
|
|
697
|
+
uri,
|
|
698
|
+
max(updatedAt) AS lastUpdatedAt
|
|
699
|
+
FROM
|
|
700
|
+
Progress
|
|
701
|
+
GROUP BY
|
|
702
|
+
1
|
|
703
|
+
) AS p2 ON p1.uri = p2.uri
|
|
704
|
+
AND p1.updatedAt = p2.lastUpdatedAt
|
|
705
|
+
LEFT JOIN (
|
|
706
|
+
SELECT
|
|
707
|
+
p.uri,
|
|
708
|
+
p.completedAt AS lastCompletedAt,
|
|
709
|
+
p.id AS lastCompletedProgressId
|
|
710
|
+
FROM
|
|
711
|
+
Progress p
|
|
712
|
+
JOIN (
|
|
713
|
+
SELECT uri, max(completedAt) AS maxCompletedAt
|
|
714
|
+
FROM Progress
|
|
715
|
+
WHERE completedAt > 0
|
|
716
|
+
GROUP BY uri
|
|
717
|
+
) latest ON p.uri = latest.uri AND p.completedAt = latest.maxCompletedAt
|
|
718
|
+
) AS p3 ON p1.uri = p3.uri
|
|
719
|
+
GROUP BY
|
|
720
|
+
p1.uri`);function stringifyDek(e){return stringify(compactBlanks(toA(e)))}function defaultMinCreatedAt(){let e=Settings2.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*dayMs}var Progress=class e extends TimestampedModel{static $tableName=`Progress`;uri;hostname;pid;volume;state;hed;dekJSON;completePct;incompletePct;scanningPct;completedAt;static vacuum(n=Settings2.progressRetentionDays.valueOrDefault*dayMs){let r=Date.now()-n,a=this.dbl.pluckAllf(e=>e.select(`id`).where(`createdAt`,`<=`,r));for(let n of batches(a,Settings2.dbBatchSelectSize.valueOrDefault))ProgressMeta.dbl.runf(e=>e.whereIn(`progressId`,n).delete()),e.dbl.runf(e=>e.whereIn(`id`,n).delete())}static lazyVacuum=lazy2(()=>e.vacuum(),dayMs);static times(){return logger129().tap({msg:`times()`,result:this.dbl.all({sql:ProgressTimesQuery})})}static insertNew(e){let n=map(e.dek,stringify);return this.ops().insertOne({...omit(e,`dek`),dekJSON:n})}upsert(e){return e!=null&&(e.dek!=null&&(this.dek=e.dek),this.assignFromPojo(e)),super.upsert()}$beforeSave(){super.$beforeSave(),this.id??(this.pid??=import_node_process28.pid,this.hostname??=(0,import_node_os20.hostname)()),isTerminalSyncStatus(this.state)&&(this.completedAt??=Date.now()),this.completePct=toPct(this.completePct),this.incompletePct=toPct(this.incompletePct),this.scanningPct=toPct(this.scanningPct)}$afterSave(){super.$afterSave(),ee().emit(`progressUpdated`),ee().emitSyncRateLimited(`syncStateChanged`)}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 compactBlanks(parseJSON(this.dekJSON))}set dek(e){this.dekJSON=stringifyDek(e)}assignFromPojo(e){return this.$ops().assignFromPojo(this,omit(e,`volume`,`uri`))}getMeta(){return ProgressMeta.ops().allf(e=>e.where({progressId:this.id}).orderBy(`createdAt`))}getPriorIncomplete(n=defaultMinCreatedAt()){let r=Math.max(n,this.getLastCompletedAt(n)??0);return this.logger().tap({msg:`priorIncompleteProgress()`,result:e.ops().findOnef(e=>e.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere(`createdAt`,`>`,r).modify(e=>{this.id!=null&&e.whereNot(`id`,this.id)}).orderBy(`updatedAt`,`desc`))})}getLastCompletedAt(n=defaultMinCreatedAt()){return e.dbl.pluckFirstf(e=>e.max(`completedAt`).where({uri:this.uri}).andWhere(`createdAt`,`>`,n))}getLastIncompleteStartAt(){return e.dbl.pluckFirstf(e=>e.min(`createdAt`).where({uri:this.uri}).andWhere(`createdAt`,`>`,this.getLastCompletedAt()??0))}setMeta(e,n){return this.logger().debug(`setMeta()`,{progressId:this.id,name:e,value:n}),ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:n})}setMetaRecord(e){let n=diff(this.getMeta().map(e=>e.name),Object.keys(e));this.logger().debug(`setMetaRecord()`,{progressId:this.id,keysToDelete:n,record:e}),ProgressMeta.ops().upsert(entries(e).map(([e,n])=>({progressId:this.id,name:e,value:toS(n)}))),isNotEmpty(n)&&ProgressMeta.dbl.runf(e=>e.where({progressId:this.id}).whereIn(`name`,n).delete())}deleteMeta(...e){return this.logger().debug(`deleteMeta()`,{progressId:this.id,names:e}),ProgressMeta.dbl.runf(n=>n.whereIn(`name`,e).andWhere({progressId:this.id}).delete())}deleteAllMeta(){return this.logger().debug(`deleteAllMeta()`,{progressId:this.id}),ProgressMeta.dbl.runf(e=>e.where({progressId:this.id}).delete())}getMetaAsRecord(){return this.logger().tap({msg:`getMetaAsRecord()`,result:fromEntries(this.getMeta().map(e=>[e.name,e.value]))??{}})}},ProgressRateMs=lazy2(()=>secondMs*(isRaspberryPi()||maxCpus()<=4?5:1.5)),logger130=mkLogger(`ops.AssetActionProgress`);async function deleteAsset(e){return withAssetMutationLock_(e.assetId,()=>deleteAsset_(e))}async function deleteAsset_(e){let n=Asset.ops().findById(e.assetId);if(n!=null&&n.deletedAt!=null&&n.deletedAt===e.deletedAt){Asset.dbl.txn(()=>{Asset.dao.setFlag(e.assetId,`deleting`),Asset.dbl.runf(n=>n.where({id:e.assetId}).update({shown:0}))});try{return await Asset.dao.remove({assetId:e.assetId,blocklistShas:!0,unlinkAssetFiles:!0,retainFailedFiles:!0,deletionPaths:e.paths??[]})}finally{Asset.dbl.txn(()=>{Asset.dao.clearFlag(e.assetId,`deleting`),Asset.dbl.runf(n=>n.where({id:e.assetId}).update({shown:1}))})}}}var RejectedFileTtlMs=weekMs,RejectedFile=class e extends Model{static $tableName=`RejectedFile`;static $businessKeys=[`dirUriId`,`basename`];dirUriId;basename;mtime;fileSize;why;updatedAt;static async findRejectedFile_(n){let r=await n.parent().uri_(),a=DirUri.findByUri_(r);if(a==null)return;let o=e.ops().findOneBy({dirUriId:a.id,basename:n.base});if(o!=null){if(o.updatedAt>Date.now()-RejectedFileTtlMs&&o.mtime===await n.mtimeMs()&&o.fileSize===await n.size())return o;o.remove()}}static async removeRejectedFile_(n){let r=await n.parent().uri_(),a=DirUri.findByUri_(r);a!=null&&e.ops().findOneBy({dirUriId:a.id,basename:n.base})?.remove()}static removeByExts(n){n.length!==0&&e.dbl.runf(e=>{for(let r of n)e.orWhere(`basename`,`like`,`%.`+r);return e.delete()})}static async addRejectedFile_(n,r){let a=DirUri.findOrCreateByUri_({uri:await n.parent().uri_(),nativePath:n.dir});return e.ops().upsertOne({dirUriId:a.id,basename:n.base,fileSize:await n.size(),mtime:await n.mtimeMs(),why:r,updatedAt:Date.now()})}},BaseTaskProducer=class extends EndableWrapper{constructor(e,n,r=EndableRanks.first,a=TaskList.instance(),o=`active`){super(e,()=>this.#n(),r),this.defaultTaskName=n,this.taskList=a,this.#e=o}defaultTaskName;taskList;#e;#t=new Set;get state(){return this.ended?`completed`:this.#e}#n(){this.#e=`completed`}runnable(){return modelDb()?.isOpen??!1}excludeUnavailable_(e,n){let r=quarantineDbRequired_();return r.deferrals.exclude(r.producers.exclude(e,this.name,n),this.name,n)}async#r(e,n){let r=quarantineDb.prior();if(r==null||r.degraded||!r.probeUnusable())throw n;return this.logger.warn(`Retrying producer query without the quarantine index`,{error:n}),await this.queryIds(e,this.#t)}reportTaskConstructionFailure(e,n){syncReport().onProgress({...n,type:`file`,state:errorToState(e),from:this.defaultTaskName,details:`Task could not be constructed: `+errorToS2(e)})}async awaitIdle(e){if(!await untilTrue(()=>this.isIdle(),{intervalMs:500,timeoutMs:e})&&e!=null)throw Error(`${this.name}.awaitIdle() timed out after ${e}ms (inFlightCount: ${this.#t.size})`)}async isIdle(){return this.runnable()===!1?!0:this.#e===`idle`||this.ended?this.#t.size===0:this.#t.size===0&&(await this.queryIds(1,this.#t)).length===0}resetForTest(e=`idle`){assertIsTest();let n=quarantineDb.prior();n!=null&&!n.ended&&n.producers.clearProducerForTest(this.name),this.#t.clear(),n!=null&&!n.ended&&n.deferrals.clearProducerForTest(this.name),this.#e=e}async produceTasks(e){if(e<=0||this.ended||this.#e!==`active`||!this.runnable())return[];let n;try{n=await this.queryIds(e,this.#t)}catch(r){n=await this.#r(e,r)}if(n.length===0)return this.#e=`idle`,[];for(let e of n)this.#t.add(e);this.logger.info(`Producing tasks`,{count:n.length,inFlightTotal:this.#t.size});let r=[];for(let e of uniq(n))try{let n=await this.mkTask(e);n._producerId=e,n._producerName=this.name,r.push(n)}catch(n){this.#t.delete(e),this.logger.warn(`mkTask failed`,{id:e,error:n})}return r}async notifyWorkAvailable(){this.#e=`active`,this.taskList.pullFromProducers()}get inFlightCount(){return this.#t.size}onTaskComplete(e){this.#t.delete(e)}onTaskDeferred(e,n,r){quarantineDbRequired_().deferrals.set(this.name,e,Number.isFinite(n)?n:void 0,r),this.#t.delete(e)}onTaskConstructionFailed(e){try{quarantineDbRequired_().producers.add(this.name,e)}finally{this.#t.delete(e)}}},ProtocolKeywordUrlPattern=String.raw`\w{2,7}:\/\/\S+`,WwwKeywordUrlPattern=String.raw`www\.\S+`,KeywordUrlsRE=new RegExp(String.raw`(?:${ProtocolKeywordUrlPattern}|(?<![\p{L}\p{N}_.@/-])${WwwKeywordUrlPattern})`,`giu`),KeywordUrlRE=new RegExp(String.raw`^(?:${ProtocolKeywordUrlPattern}|${WwwKeywordUrlPattern})$`,`iu`);function isKeywordUrl(e){return KeywordUrlRE.test(e)}var _nameToCode=new CaseInsensitiveMap([[`Andorra`,`AD`],[`United Arab Emirates`,`AE`],[`Afghanistan`,`AF`],[`Antigua and Barbuda`,`AG`],[`Anguilla`,`AI`],[`Albania`,`AL`],[`Armenia`,`AM`],[`Angola`,`AO`],[`Argentina`,`AR`],[`American Samoa`,`AS`],[`Austria`,`AT`],[`Australia`,`AU`],[`Aruba`,`AW`],[`Aland Islands`,`AX`],[`Azerbaijan`,`AZ`],[`Bosnia and Herzegovina`,`BA`],[`Barbados`,`BB`],[`Bangladesh`,`BD`],[`Belgium`,`BE`],[`Burkina Faso`,`BF`],[`Bulgaria`,`BG`],[`Bahrain`,`BH`],[`Burundi`,`BI`],[`Benin`,`BJ`],[`Saint Barthelemy`,`BL`],[`Bermuda`,`BM`],[`Brunei`,`BN`],[`Bolivia`,`BO`],[`Bonaire Saint Eustatius and Saba`,`BQ`],[`Brazil`,`BR`],[`Bahamas`,`BS`],[`Bhutan`,`BT`],[`Botswana`,`BW`],[`Belarus`,`BY`],[`Belize`,`BZ`],[`Canada`,`CA`],[`Democratic Republic of the Congo`,`CD`],[`Central African Republic`,`CF`],[`Republic of the Congo`,`CG`],[`Switzerland`,`CH`],[`Ivory Coast`,`CI`],[`Cook Islands`,`CK`],[`Chile`,`CL`],[`Cameroon`,`CM`],[`China`,`CN`],[`Colombia`,`CO`],[`Costa Rica`,`CR`],[`Cuba`,`CU`],[`Cabo Verde`,`CV`],[`Curacao`,`CW`],[`Cyprus`,`CY`],[`Czechia`,`CZ`],[`Germany`,`DE`],[`Djibouti`,`DJ`],[`Denmark`,`DK`],[`Dominica`,`DM`],[`Dominican Republic`,`DO`],[`Algeria`,`DZ`],[`Ecuador`,`EC`],[`Estonia`,`EE`],[`Egypt`,`EG`],[`Western Sahara`,`EH`],[`Eritrea`,`ER`],[`Spain`,`ES`],[`Ethiopia`,`ET`],[`Finland`,`FI`],[`Fiji`,`FJ`],[`Falkland Islands`,`FK`],[`Micronesia`,`FM`],[`Faroe Islands`,`FO`],[`France`,`FR`],[`Gabon`,`GA`],[`United Kingdom`,`GB`],[`Grenada`,`GD`],[`Georgia`,`GE`],[`French Guiana`,`GF`],[`Guernsey`,`GG`],[`Ghana`,`GH`],[`Gibraltar`,`GI`],[`Greenland`,`GL`],[`Gambia`,`GM`],[`Guinea`,`GN`],[`Guadeloupe`,`GP`],[`Equatorial Guinea`,`GQ`],[`Greece`,`GR`],[`Guatemala`,`GT`],[`Guam`,`GU`],[`Guinea-Bissau`,`GW`],[`Guyana`,`GY`],[`Hong Kong`,`HK`],[`Honduras`,`HN`],[`Croatia`,`HR`],[`Haiti`,`HT`],[`Hungary`,`HU`],[`Indonesia`,`ID`],[`Ireland`,`IE`],[`Israel`,`IL`],[`Isle of Man`,`IM`],[`India`,`IN`],[`Iraq`,`IQ`],[`Iran`,`IR`],[`Iceland`,`IS`],[`Italy`,`IT`],[`Jersey`,`JE`],[`Jamaica`,`JM`],[`Jordan`,`JO`],[`Japan`,`JP`],[`Kenya`,`KE`],[`Kyrgyzstan`,`KG`],[`Cambodia`,`KH`],[`Kiribati`,`KI`],[`Comoros`,`KM`],[`Saint Kitts and Nevis`,`KN`],[`North Korea`,`KP`],[`South Korea`,`KR`],[`Kuwait`,`KW`],[`Cayman Islands`,`KY`],[`Kazakhstan`,`KZ`],[`Laos`,`LA`],[`Lebanon`,`LB`],[`Saint Lucia`,`LC`],[`Liechtenstein`,`LI`],[`Sri Lanka`,`LK`],[`Liberia`,`LR`],[`Lesotho`,`LS`],[`Lithuania`,`LT`],[`Luxembourg`,`LU`],[`Latvia`,`LV`],[`Libya`,`LY`],[`Morocco`,`MA`],[`Monaco`,`MC`],[`Moldova`,`MD`],[`Montenegro`,`ME`],[`Saint Martin`,`MF`],[`Madagascar`,`MG`],[`Marshall Islands`,`MH`],[`North Macedonia`,`MK`],[`Mali`,`ML`],[`Myanmar`,`MM`],[`Mongolia`,`MN`],[`Macao`,`MO`],[`Northern Mariana Islands`,`MP`],[`Martinique`,`MQ`],[`Mauritania`,`MR`],[`Montserrat`,`MS`],[`Malta`,`MT`],[`Mauritius`,`MU`],[`Maldives`,`MV`],[`Malawi`,`MW`],[`Mexico`,`MX`],[`Malaysia`,`MY`],[`Mozambique`,`MZ`],[`Namibia`,`NA`],[`New Caledonia`,`NC`],[`Niger`,`NE`],[`Nigeria`,`NG`],[`Nicaragua`,`NI`],[`The Netherlands`,`NL`],[`Norway`,`NO`],[`Nepal`,`NP`],[`Nauru`,`NR`],[`New Zealand`,`NZ`],[`Oman`,`OM`],[`Panama`,`PA`],[`Peru`,`PE`],[`French Polynesia`,`PF`],[`Papua New Guinea`,`PG`],[`Philippines`,`PH`],[`Pakistan`,`PK`],[`Poland`,`PL`],[`Saint Pierre and Miquelon`,`PM`],[`Puerto Rico`,`PR`],[`Palestinian Territory`,`PS`],[`Portugal`,`PT`],[`Palau`,`PW`],[`Paraguay`,`PY`],[`Qatar`,`QA`],[`Reunion`,`RE`],[`Romania`,`RO`],[`Serbia`,`RS`],[`Russia`,`RU`],[`Rwanda`,`RW`],[`Saudi Arabia`,`SA`],[`Solomon Islands`,`SB`],[`Seychelles`,`SC`],[`Sudan`,`SD`],[`Sweden`,`SE`],[`Singapore`,`SG`],[`Saint Helena`,`SH`],[`Slovenia`,`SI`],[`Svalbard and Jan Mayen`,`SJ`],[`Slovakia`,`SK`],[`Sierra Leone`,`SL`],[`San Marino`,`SM`],[`Senegal`,`SN`],[`Somalia`,`SO`],[`Suriname`,`SR`],[`South Sudan`,`SS`],[`Sao Tome and Principe`,`ST`],[`El Salvador`,`SV`],[`Sint Maarten`,`SX`],[`Syria`,`SY`],[`Eswatini`,`SZ`],[`Turks and Caicos Islands`,`TC`],[`Chad`,`TD`],[`Togo`,`TG`],[`Thailand`,`TH`],[`Tajikistan`,`TJ`],[`Tokelau`,`TK`],[`Timor Leste`,`TL`],[`Turkmenistan`,`TM`],[`Tunisia`,`TN`],[`Tonga`,`TO`],[`Turkey`,`TR`],[`Trinidad and Tobago`,`TT`],[`Tuvalu`,`TV`],[`Taiwan`,`TW`],[`Tanzania`,`TZ`],[`Ukraine`,`UA`],[`Uganda`,`UG`],[`United States`,`US`],[`Uruguay`,`UY`],[`Uzbekistan`,`UZ`],[`Saint Vincent and the Grenadines`,`VC`],[`Venezuela`,`VE`],[`British Virgin Islands`,`VG`],[`U.S. Virgin Islands`,`VI`],[`Vietnam`,`VN`],[`Vanuatu`,`VU`],[`Wallis and Futuna`,`WF`],[`Samoa`,`WS`],[`Kosovo`,`XK`],[`Yemen`,`YE`],[`Mayotte`,`YT`],[`South Africa`,`ZA`],[`Zambia`,`ZM`],[`Zimbabwe`,`ZW`],[`Netherlands`,`NL`],[`Czech Republic`,`CZ`],[`Türkiye`,`TR`],[`East Timor`,`TL`],[`Cape Verde`,`CV`],[`Swaziland`,`SZ`],[`Burma`,`MM`],[`دولة الإمارات العربية المتحدة`,`AE`],[`افغانستان`,`AF`],[`Shqipëria`,`AL`],[`Հայաստան`,`AM`],[`Österreich`,`AT`],[`Azərbaycan`,`AZ`],[`Bosna i Hercegovina`,`BA`],[`België`,`BE`],[`България`,`BG`],[`البحرين`,`BH`],[`Brasil`,`BR`],[`Беларусь`,`BY`],[`Schweiz`,`CH`],[`Suisse`,`CH`],[`Svizzera`,`CH`],[`中国`,`CN`],[`Κύπρος`,`CY`],[`Česká republika`,`CZ`],[`Česko`,`CZ`],[`Deutschland`,`DE`],[`Danmark`,`DK`],[`مصر`,`EG`],[`España`,`ES`],[`Suomi`,`FI`],[`Føroyar`,`FO`],[`საქართველო`,`GE`],[`Ελλάδα`,`GR`],[`Haïti`,`HT`],[`Magyarország`,`HU`],[`Éire`,`IE`],[`יִשְׂרָאֵל`,`IL`],[`भारत`,`IN`],[`Ísland`,`IS`],[`Italia`,`IT`],[`日本`,`JP`],[`한국`,`KR`],[`대한민국`,`KR`],[`Latvija`,`LV`],[`Lietuva`,`LT`],[`ليبيا`,`LY`],[`المغرب`,`MA`],[`Madagasikara`,`MG`],[`Северна Македонија`,`MK`],[`မြန်မာ`,`MM`],[`Монгол улс`,`MN`],[`澳門`,`MO`],[`موريتانيا`,`MR`],[`Maurice`,`MU`],[`México`,`MX`],[`Nederland`,`NL`],[`Norge`,`NO`],[`عمان`,`OM`],[`Panamá`,`PA`],[`Perú`,`PE`],[`Polska`,`PL`],[`România`,`RO`],[`Србија`,`RS`],[`Россия`,`RU`],[`المملكة العربية السعودية`,`SA`],[`Sverige`,`SE`],[`سوريا`,`SY`],[`ประเทศไทย`,`TH`],[`Тоҷикистон`,`TJ`],[`Türkmenistan`,`TM`],[`تونس`,`TN`],[`臺灣`,`TW`],[`台灣`,`TW`],[`Україна`,`UA`],[`O'zbekiston`,`UZ`],[`Việt Nam`,`VN`],[`اليَمَن`,`YE`]]),_codeToName=new Map;for(let[e,n]of _nameToCode.entries())_codeToName.has(n)||_codeToName.set(n,e);var _alpha3ToAlpha2=new CaseInsensitiveMap([[`AFG`,`AF`],[`ALA`,`AX`],[`ALB`,`AL`],[`DZA`,`DZ`],[`ASM`,`AS`],[`AND`,`AD`],[`AGO`,`AO`],[`AIA`,`AI`],[`ATG`,`AG`],[`ARG`,`AR`],[`ARM`,`AM`],[`ABW`,`AW`],[`AUS`,`AU`],[`AUT`,`AT`],[`AZE`,`AZ`],[`BHS`,`BS`],[`BHR`,`BH`],[`BGD`,`BD`],[`BRB`,`BB`],[`BLR`,`BY`],[`BEL`,`BE`],[`BLZ`,`BZ`],[`BEN`,`BJ`],[`BMU`,`BM`],[`BTN`,`BT`],[`BOL`,`BO`],[`BES`,`BQ`],[`BIH`,`BA`],[`BWA`,`BW`],[`BRA`,`BR`],[`BRN`,`BN`],[`BGR`,`BG`],[`BFA`,`BF`],[`BDI`,`BI`],[`CPV`,`CV`],[`KHM`,`KH`],[`CMR`,`CM`],[`CAN`,`CA`],[`CYM`,`KY`],[`CAF`,`CF`],[`TCD`,`TD`],[`CHL`,`CL`],[`CHN`,`CN`],[`COL`,`CO`],[`COM`,`KM`],[`COD`,`CD`],[`COG`,`CG`],[`COK`,`CK`],[`CRI`,`CR`],[`CIV`,`CI`],[`HRV`,`HR`],[`CUB`,`CU`],[`CUW`,`CW`],[`CYP`,`CY`],[`CZE`,`CZ`],[`DNK`,`DK`],[`DJI`,`DJ`],[`DMA`,`DM`],[`DOM`,`DO`],[`ECU`,`EC`],[`EGY`,`EG`],[`SLV`,`SV`],[`GNQ`,`GQ`],[`ERI`,`ER`],[`EST`,`EE`],[`SWZ`,`SZ`],[`ETH`,`ET`],[`FLK`,`FK`],[`FRO`,`FO`],[`FJI`,`FJ`],[`FIN`,`FI`],[`FRA`,`FR`],[`GUF`,`GF`],[`PYF`,`PF`],[`GAB`,`GA`],[`GMB`,`GM`],[`GEO`,`GE`],[`DEU`,`DE`],[`GHA`,`GH`],[`GIB`,`GI`],[`GRC`,`GR`],[`GRL`,`GL`],[`GRD`,`GD`],[`GLP`,`GP`],[`GUM`,`GU`],[`GTM`,`GT`],[`GGY`,`GG`],[`GIN`,`GN`],[`GNB`,`GW`],[`GUY`,`GY`],[`HTI`,`HT`],[`VAT`,`VA`],[`HND`,`HN`],[`HKG`,`HK`],[`HUN`,`HU`],[`ISL`,`IS`],[`IND`,`IN`],[`IDN`,`ID`],[`IRN`,`IR`],[`IRQ`,`IQ`],[`IRL`,`IE`],[`IMN`,`IM`],[`ISR`,`IL`],[`ITA`,`IT`],[`JAM`,`JM`],[`JPN`,`JP`],[`JEY`,`JE`],[`JOR`,`JO`],[`KAZ`,`KZ`],[`KEN`,`KE`],[`KIR`,`KI`],[`PRK`,`KP`],[`KOR`,`KR`],[`KWT`,`KW`],[`KGZ`,`KG`],[`LAO`,`LA`],[`LVA`,`LV`],[`LBN`,`LB`],[`LSO`,`LS`],[`LBR`,`LR`],[`LBY`,`LY`],[`LIE`,`LI`],[`LTU`,`LT`],[`LUX`,`LU`],[`MAC`,`MO`],[`MKD`,`MK`],[`MDG`,`MG`],[`MWI`,`MW`],[`MYS`,`MY`],[`MDV`,`MV`],[`MLI`,`ML`],[`MLT`,`MT`],[`MHL`,`MH`],[`MTQ`,`MQ`],[`MRT`,`MR`],[`MUS`,`MU`],[`MYT`,`YT`],[`MEX`,`MX`],[`FSM`,`FM`],[`MDA`,`MD`],[`MCO`,`MC`],[`MNG`,`MN`],[`MNE`,`ME`],[`MSR`,`MS`],[`MAR`,`MA`],[`MOZ`,`MZ`],[`MMR`,`MM`],[`NAM`,`NA`],[`NRU`,`NR`],[`NPL`,`NP`],[`NLD`,`NL`],[`NCL`,`NC`],[`NZL`,`NZ`],[`NIC`,`NI`],[`NER`,`NE`],[`NGA`,`NG`],[`MNP`,`MP`],[`NOR`,`NO`],[`OMN`,`OM`],[`PAK`,`PK`],[`PLW`,`PW`],[`PSE`,`PS`],[`PAN`,`PA`],[`PNG`,`PG`],[`PRY`,`PY`],[`PER`,`PE`],[`PHL`,`PH`],[`POL`,`PL`],[`PRT`,`PT`],[`PRI`,`PR`],[`QAT`,`QA`],[`REU`,`RE`],[`ROU`,`RO`],[`RUS`,`RU`],[`RWA`,`RW`],[`BLM`,`BL`],[`SHN`,`SH`],[`KNA`,`KN`],[`LCA`,`LC`],[`MAF`,`MF`],[`SPM`,`PM`],[`VCT`,`VC`],[`WSM`,`WS`],[`SMR`,`SM`],[`STP`,`ST`],[`SAU`,`SA`],[`SEN`,`SN`],[`SRB`,`RS`],[`SYC`,`SC`],[`SLE`,`SL`],[`SGP`,`SG`],[`SXM`,`SX`],[`SVK`,`SK`],[`SVN`,`SI`],[`SLB`,`SB`],[`SOM`,`SO`],[`ZAF`,`ZA`],[`SSD`,`SS`],[`ESP`,`ES`],[`LKA`,`LK`],[`SDN`,`SD`],[`SUR`,`SR`],[`SJM`,`SJ`],[`SWE`,`SE`],[`CHE`,`CH`],[`SYR`,`SY`],[`TWN`,`TW`],[`TJK`,`TJ`],[`TZA`,`TZ`],[`THA`,`TH`],[`TLS`,`TL`],[`TGO`,`TG`],[`TKL`,`TK`],[`TON`,`TO`],[`TTO`,`TT`],[`TUN`,`TN`],[`TUR`,`TR`],[`TKM`,`TM`],[`TCA`,`TC`],[`TUV`,`TV`],[`UGA`,`UG`],[`UKR`,`UA`],[`ARE`,`AE`],[`GBR`,`GB`],[`USA`,`US`],[`URY`,`UY`],[`UZB`,`UZ`],[`VUT`,`VU`],[`VEN`,`VE`],[`VNM`,`VN`],[`VGB`,`VG`],[`VIR`,`VI`],[`WLF`,`WF`],[`ESH`,`EH`],[`YEM`,`YE`],[`ZMB`,`ZM`],[`ZWE`,`ZW`]]);function alpha3ToAlpha2(e){if(e!=null)return e.length===2?_codeToName.has(e.toUpperCase())?e.toUpperCase():void 0:_alpha3ToAlpha2.get(e)}function countryNameToCode(e){return _nameToCode.get(e)}function countryCodeToName(e){return _codeToName.get(e.toUpperCase())}function countryCodeToFlag(e){if(e.length!==2)return;let n=e.toUpperCase(),r=n.charCodeAt(0),a=n.charCodeAt(1);if(!(r<65||r>90||a<65||a>90))return String.fromCodePoint(127462+r-65,127462+a-65)}function flaggedCountryName(e,n){if(n==null)return e;let r=countryCodeToFlag(n);return r==null?e:r+` `+e}var logger131=defer(()=>mkLogger(`curators.Taggers`)),aliasLookup=defer(()=>{let e=new CaseInsensitiveMap;for(let{root:n,setting:r}of RootTagAliasConfigs){let a=rootTagDef(n);e.set(n,a);for(let n of r.values)e.set(n,a)}return e});function resolvedTagRoot(e){return aliasLookup().get(e)}function normalizeTagRoot(e){let n=resolvedTagRoot(tagRefToS(e[0]));return n==null?e:[n,...e.slice(1)]}function getAliasRenames(){let e={};for(let{root:n,setting:r}of RootTagAliasConfigs){let a=n.toLowerCase();for(let o of r.values)o.toLowerCase()!==a&&(e[`/`+o]=n)}return e}function getEffectiveTagPathRenames(){return{...getAliasRenames(),...Settings2.tagPathRenames.valueOrDefault}}function applyTagPathRenames(e){let n=getEffectiveTagPathRenames();if(isEmptyObj(n))return e;let r=e.map(e=>tagRefToS(e)),a=r.map(e=>e.toLowerCase()),o=!1;for(let[e,s]of Object.entries(n)){let n=e.startsWith(`/`),c=splitTagPath(n?e.slice(1):e,`/`),l=c.map(e=>e.toLowerCase()),u=splitTagPath(s.replace(/^\//,``),`/`);if(isEmpty(c))continue;let d=findMatchIndex(a,l,n);d<0||(r=[...r.slice(0,d),...u,...r.slice(d+c.length)],a=r.map(e=>e.toLowerCase()),o=!0)}return o?r:e}function findMatchIndex(e,n,r){if(n.length>e.length)return-1;let a=r?0:e.length-n.length;for(let r=0;r<=a;r++)if(n.every((n,a)=>n===e[r+a]))return r;return-1}var SkipSoftGarbageCheckRoots=new Set([`camera`,`lens`,`when`,`type`,`fs`]),SkipExifValueCheckRoots=new Set([`when`,`type`,`fs`]),AlphaNumRunRE=RegExp(`(?:\\p{L}\\p{M}*|\\p{N}){2,}`,`u`),SymbolNoiseRE=/[^\p{L}\p{M}\p{N}\s.'\-\p{Extended_Pictographic}]/u,LossyDecodeMarkerRE=/\?[\p{L}\p{N}]/gu,ExactLossyDecodeMarkerRE=/^\?[\p{L}\p{N}]$/u;function hasLikelyLossyDecodeMarkers(e){let n=e.match(LossyDecodeMarkerRE)?.length??0;return ExactLossyDecodeMarkerRE.test(e)||n>2}function reasonRejectingTagSegment(e,n,r=!1){if(blank(e))return`blank`;if(e.includes(`�`))return`unicodeReplacementCharacter`;if(!r){if(hasEncodingCorruption(e))return`encodingCorruption`;if(isPlaceholderOnly(e))return`placeholderOnly`;if(lacksContentBearingChars(e))return`noContentChars`}if(!n){if(hasLikelyLossyDecodeMarkers(e)&&!isKeywordUrl(e))return`lossyDecodeMarker`;if(SymbolNoiseRE.test(e)&&!AlphaNumRunRE.test(e))return`symbolNoiseWithoutWordRun`}}function canonicalizeWhereCountry(e){if(e.length<3||tagRefToS(e[0])!==TagRoots.Where)return e;let n=tagRefToS(e[1]),r=alpha3ToAlpha2(n)??countryNameToCode(n);return r==null?e:[e[0],r,...e.slice(2)]}function normalizeTagPath2(e){let n=normalizeTagRoot(e),r=applyTagPathRenames(n),a=r===n?canonicalizeWhereCountry(r):r,o=tagRefToS(a[0]).toLowerCase(),s=SkipSoftGarbageCheckRoots.has(o),c=SkipExifValueCheckRoots.has(o),l=[];for(let e=0;e<a.length;e++){let n=tagRefToS(a[e]),r=reasonRejectingTagSegment(n,s,c);if(r!=null){logger131().warn(`normalizeTagPath(): truncating at garbage tag segment`,{segment:n,reason:r,path:a.map(tagRefToS)});break}l.push(a[e])}return l.length>1?l:void 0}function tagDeltas(e,n){let r=tagDiff(n,e),a=tagDiff(e,n),o=Settings2.excludedRootTags.valueOrDefault;return filterInPlace(r,e=>{let n=o.includes(tagRefToS(e[0]).toLowerCase());return n&&!tagPathsInclude(e,a)&&(a.push(e),logger131().info(`tagDeltas(): removing excluded tag`,e)),!n}),{add:r,remove:a}}var logger132=lazy2(()=>mkLogger(`tags.Names`)),_surnameSetSource=[],_surnameSet;function knownSurnameSet(){let e=Settings2.tagNamesSurnames.values;return eql(e,_surnameSetSource)||(_surnameSetSource=e,_surnameSet=e.length===0?void 0:new CaseInsensitiveSet(e)),_surnameSet}function escRE(e){return matchQuotes(escapeRegExp(e))}function familyNameREs(){return Settings2.tagNamesSurnames.values.map(e=>RegExp(`\\b(`+escRE(e)+`)\\b`,`i`))}function givenNameREs(){return Settings2.tagNamesGiven.values.map(e=>RegExp(`\\b(`+escRE(e)+`)\\b`,`i`))}function familyNamePrefixeREs(){return mapNotEmpty(compactBlanks(Settings2.tagNamesSurnamePrefixes.values),e=>sortBy(e,e=>-e.length).map(e=>RegExp(`\\b(${escRE(e)}\\s+\\S+)`,`i`)))}function givenNameSurroundREs(){let e=compactBlanks(Settings2.tagNamesGivenSurrounds.values);for(let n of e)n.length!==2&&logger132().warn(`Settings.tagNamesFamilySurrounds has an invalid value:`,n);return e.map(e=>RegExp(`(${escapeRegExp(e.charAt(0))}\\s*[^${escapeRegExp(e.charAt(0))}]+\\s*${escapeRegExp(e.charAt(1))})`,`i`))}function familyNameSurroundREs(){let e=compactBlanks(Settings2.tagNamesFamilySurrounds.values);for(let n of e)n.length!==2&&logger132().warn(`Settings.tagNamesFamilySurrounds has an invalid value:`,n);return e.map(e=>RegExp(`${escapeRegExp(e.charAt(0))}\\s*([^${escapeRegExp(e.charAt(0))}]*)\\s*${escapeRegExp(e.charAt(1))}`,`i`))}var lifespanRE=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,modifierRE=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,uppercaseWordsRE=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,ignorableNameRE=/^[()[\]/.\-_]+$/;function parseName(e){if(blank(e))return;let n=e.replace(/\s+/g,` `).replace(/\(\s+/g,`(`).replace(/\s+\)/g,`)`).trim(),r=map(spliceCapture(n,lifespanRE),e=>(n=e.unmatched.trim(),e.captured.replace(/\s+/g,``))),a=map(spliceCapture(n,modifierRE),e=>(n=e.unmatched.trim(),e.captured.trim())),o=[],s=[],c=[];for(let e of givenNameREs()){let r=spliceCapture(n,e);r!=null&&(o.push(r.captured),n=r.unmatched.trim())}for(let e of givenNameSurroundREs()){let r;do r=spliceCapture(n,e),r!=null&&(s.push(r.captured),n=r.unmatched.trim());while(r!=null)}let l;function u(e){(l==null||l>e.matchedIndex)&&(l=min([l,e.matchedIndex]))}if(Settings2.tagNamesCapitalizedAsFamily.valueOrDefault&&Settings2.tagNamesOrder.valueOrDefault===`givenFirst`){let e;do e=spliceCapture(n,uppercaseWordsRE),e!=null&&(u(e),c.push(e.captured),n=e.unmatched.trim());while(e!=null)}for(let e of familyNameSurroundREs()){let r;do r=spliceCapture(n,e),r!=null&&(u(r),c.push(r.captured),n=r.unmatched.trim());while(r!=null)}if(Settings2.tagNamesLexical.valueOrDefault){let e=n.indexOf(`,`);e>=0&&(l=void 0,c.push(n.substring(0,e).trim()),o.push(n.substring(e+1).trim()),n=``)}for(let e of familyNameREs()){let r=spliceCapture(n,e);r!=null&&(u(r),c.push(r.captured),n=r.unmatched.trim())}for(let e of toA(familyNamePrefixeREs())){let r=spliceCapture(n,e);r!=null&&(u(r),c.push(r.captured),n=r.unmatched.trim())}if(l!=null&&l>0&&n.length>l){let e=Settings2.tagNamesOrder.valueOrDefault===`givenFirst`;mapNotEmpty(compactBlanks(n.slice(l).split(/\s+/)),r=>{e?c.push(...r):o.push(...r),n=n.slice(0,l)})}let d=compactBlanks(n.split(/\s+/)),f=o.length,h=c.length;if(d.length>0){if(f===0&&h>0)o.push(...d);else if(h===0&&f>0&&d.length===1)c.push(...d);else if(d.length===1){let e=Settings2.tagNamesOrder.valueOrDefault===`givenFirst`;l!=null&&!e?c.push(...d):o.push(...d)}else{let e=Settings2.tagNamesOrder.valueOrDefault===`givenFirst`;c.push(e?d.pop():d.shift()),o.push(...d)}}let _=knownSurnameSet();if(_!=null)for(let e=0;e<c.length;e++){let n=_.lookup(c[e]);n!=null&&(c[e]=n)}return{givenNames:cleanupNames([...o,...s]),modifier:a,lifespan:r,familyNames:cleanupNames(c),minFamilyNameIndex:l}}function cleanupNames(e){return uniq(compactBlanks(e).filter(e=>ignorableNameRE.exec(e)==null))}function join30(e){let n=``;for(let r of compactBlanks(e))n+=r.startsWith(`,`)?r:` `+r;return n.trim()}function renderNameTag(e){if(blank(e))return[];let n=Settings2.tagNamesFormatter.valueOrDefault,r=n===`family/fullname`,a=n===`family/given`;if(r||a){let n=parseName(e);if(n==null)return[];{let e=join30([n.modifier,n.lifespan]),r=join30(n.givenNames),o=compactBlanks(n.familyNames);if(isEmpty(o)){let n=Settings2.tagNamesDefaultFamily.valueOrDefault,a=join30([r,e]);return blank(a)?[]:blank(n)?[[TagRoots.Who,a]]:[[TagRoots.Who,n,a]]}return o.map(n=>compactBlanks([TagRoots.Who,n,a?join30([r,e]):renderName(n,r,e)]))}}return[[TagRoots.Who,e.trim()]]}function renderName(e,n,r){return join30(Settings2.tagNamesOrder.valueOrDefault===`givenFirst`?[n,e,r]:[e,n,r])}var logger133=lazy2(()=>mkLogger(`curators.WhoTagger`));async function whoTagFiles(e){let n=[];if(Settings2.tagJsonFaces.valueOrDefault){let r=[];for(let n of e)r.push(...toA(await n.jsonSidecars()));for(let e of r){let r=(await readJsonSidecar(e))?.peopleNames;isNotEmpty(r)&&n.push(...r)}}if(Settings2.tagFaceRegions.valueOrDefault)for(let r of e){let e=await readTags(r);if(e!=null)for(let r of values(e)){let e=r?.RegionList;if(Array.isArray(e)){for(let r of e)if(r.Type===`Face`){let e=r.Name;n.push(typeof e==`number`||typeof e==`boolean`?String(e):e)}}}}if(isNotEmpty(Settings2.whoTags.values))for(let r of e){let e=await readTags(r);for(let r of Settings2.whoTags.values)n.push(...toA(pluckDeep(e,r)?.value).map(e=>typeof e==`number`||typeof e==`boolean`?String(e):e))}let r=uniq(flatten(uniq(n).map(nameTag)));return logger133().tap({msg:`whoTagFiles()`,level:`info`,result:r,meta:{names:n,files:e.map(e=>e.nativePath)}})}function isWhoTag(e){return resolvedTagRoot(tagRefToS(e[0]))?.name===TagRoots.Who}function nameTag(e){if(!blank(e))return Array.isArray(e)?(isWhoTag(e)&&e.shift(),e.length===0?void 0:e.length===1?renderNameTag(e[0]):[[TagRoots.Who,...e]]):renderNameTag(e)}var logger134=lazy2(()=>mkLogger(`curators.KeywordTagger`)),delimSpaceRe=lazy2(()=>mapNotBlank(Settings2.keywordDashDashDelimiters.valueOrDefault,e=>RegExp(`[${escapeRegExp(e)}]+`,`i`)));later(()=>{Settings2.keywordDashDashDelimiters.watchLater(()=>delimSpaceRe.unset())});function extractDashDashTags(e){return logger134().tap({msg:`extractDashDashTags()`,result:mapOr(toS(e).split(`--`)[1],e=>compactBlanks(mapOr(delimSpaceRe(),n=>e.split(n),[e])),()=>[]),meta:{nativePath:e}})}function extractPathnameTags(e){return[...extractDashDashTags(e.parent().posixPath),...extractDashDashTags(e.name)]}function normalizeKeywordPaths(e){let n=[],r=[],a=[];for(let n of compact(e))if(Array.isArray(n))a.push(n);else{let e=toS(n).replace(KeywordUrlsRE,e=>(r.push(e),``));a.push(...mapOr(delimRe(),n=>e.split(n),[e]))}let[o,s]=partition(a.map(e=>isString(e)?keywordToPath(e):e).map(e=>Array.isArray(e)&&e.length===1?e[0]:e),Array.isArray),c=o.map(e=>compactBlanks(e.map(e=>e.trim()))).filter(isNotEmpty),l=uniqIgnoreCase(flatten(c));n.push(...c);let u=[...s,...r].map(e=>e.trim()).filter(e=>notBlank(e)&&!includesIgnoreCase(l,e)),d=Settings2.keywordReparenting.valueOrDefault===`copy`,f=Settings2.keywordReparenting.valueOrDefault===`retain`,h=Settings2.rootTagKeywordsAliases.values;for(let e of[...n])includesIgnoreCase(h,e[0])&&(e[0]=TagRoots.Keywords),e[0]!==TagRoots.Keywords&&(d?n.push([TagRoots.Keywords,...e]):f&&e.unshift(TagRoots.Keywords));for(let e of u)n.push([TagRoots.Keywords,e]);return uniq(n)}function dedupeKeywordPaths(e){return uniqBy2(sortBy(e.map(normalizeTagRoot),e=>{let n=joinTagPath(e);return[n.normalize().toLowerCase(),-1*lcdiff(n)]}),(e,n)=>equalsIgnoreCase(joinTagPath(e),joinTagPath(n)))}function processKeywords(e,n){let[r,a]=partition(normalizeKeywordPaths(e),isWhoTag),o=flatten(r.map(nameTag)),s=uniq(flatten([...o,...n].map(e=>{let n=stripTagRoot(e);return[n.join(`, `),n.join(` `),[...n].reverse().join(` `)]}))),c=dedupeKeywordPaths([...a.filter(e=>!includesIgnoreCase(s,stripTagRoot(e).join(` `))),...o]);return logger134().tap({msg:`processKeywords()`,level:`info`,result:c})}async function keywordTagFiles(e,n){let r=Settings2.tagKeywordsFromPath.valueOrDefault?flatten(e.map(extractPathnameTags)):[],a=Settings2.tagKeywordsFromMetadata.valueOrDefault?flatten(await mapAsyncSerial({name:`keywordTagFiles`,arr:e,f:async e=>{let n=await readTags(e);return n==null?void 0:rawTagKeywords(n)}})):[];return processKeywords([...r,...a],n)}var MetaError=class extends Error{constructor(e,n){super(e),this.message=e,assignFields(this,n)}message;name=`MetaError`;code;errno},S=strEnum(`plus`,`lite`);function normalize(e){return toS(e).replace(/[^a-z\d]+/gi,``).toLowerCase()}var PlaceholderValues=new Set(`To Be Filled By O.E.M.,None,N/A,Not Specified,Unknown,Unknow,Uknown,Unkn,Not Available,Not Present,Default string,Default,INVALID,System manufacturer,System Product Name,System Serial Number,Not Applicable,Chassis Serial Number,Chassis Manufacturer,Base Board Serial Number,No Asset Tag,No Asset Information,System Version,Chassis Version,Product Name,OEM,empty,(null string),null,EVAL,IATPASS,Tulip Computers,Serial Number xxxxxx,OEM_Serial,SystemSerialNumb,System Name,All Series,Not Installed,Unknown Product,$(PROJECT_SKU_NAME),MB serial number,PCA serial,no string,reserved,<BAD INDEX>,<OUT OF SPEC>,<OUT OF SPEC><OUT OF SPEC>,Not Settable,uninitialized,b08dfa6083e7567a1921a715000001fb,undefined,generic,7783-7084-3265-9085-8269-3286-77`.split(`,`).map(normalize)),PlaceholderUuids=new Set([`03000200-0400-0500-0006-000700080009`,`03020100-0504-0706-0809-0a0b0c0d0e0f`,`10000000-0000-8000-0040-000000000000`,`6AB5B300-538D-1014-9FB5-B0684D007B53`].map(normalize)),MinTwoCharLength=8;function hasTooFewDistinctChars(e){let n=new Set(e).size;return n===1||n===2&&e.length>=MinTwoCharLength}function isVersionShaped(e){return/^\d+(?:\.\d+){1,3}$/.test(e)}function isAscendingDigitRun(e){if(e.length<4||!/^\d+$/.test(e))return!1;let n=!1;for(let r=1;r<e.length;r++){let a=Number(e[r-1]),o=Number(e[r]);if(o!==a+1){if(a===9&&o===0&&!n)n=!0;else return!1}}return!0}function isPlaceholderId(e){let n=toS(e).trim();if(isVersionShaped(n))return!0;let r=normalize(n);return r.length===0||PlaceholderValues.has(r)||PlaceholderUuids.has(r)||hasTooFewDistinctChars(r)||isAscendingDigitRun(r)}var S2=strEnum(`cu`,`lc`,`lm`,`lp`,`lb`,`ls`,`lh`,`ln`,`lr`,`mp`,`ms`,`wm`,`cm`,`bm`,`nm`,`li`,`si`,`vl`),SchemeNames=Object.freeze({cu:`customerUid`,lc:`linuxCpuUid`,lm:`linuxMachineUid`,lp:`linuxProductUid`,lb:`linuxBoardSerial`,ls:`linuxSystemSerial`,lh:`linuxChassisSerial`,ln:`linuxCmdlineSerialNumber`,lr:`linuxRootUuid`,mp:`macOsPlatformUid`,ms:`macOsPlatformSerial`,wm:`windowsMachineUid`,cm:`cpuModel`,bm:`boardModel`,nm:`networkMac`,li:`libraryUid`,si:`systemUid`,vl:`volumeUid`});function getScheme(e){let n=e.split(`:`,1)[0];return S2.has(n)?n:void 0}function sortUids(e){return sortBy(uniq(e.filter(isValidUid)),e=>[S2.indexOf(getScheme(e))??S2.length+1,e])}function prefix2scheme(e){return SchemeNames[e]}var UidLength=15;function canonicalize(e){return e.replace(/[^a-z\d=/+]+/gi,``)}function toUID(e,n){try{let r=toS(n);if(isPlaceholderId(r))return;let a=canonicalize(r);return a.length===0?void 0:e+`:`+shortStringSha(a,UidLength,Radix58)}catch(n){mkLogger(`toUID`).warn(`failed`,{pfx:e,error:n});return}}var uidRE=defer(()=>RegExp(`^(?:${S2.values.join(`|`)}):[0-9a-zA-Z]{${UidLength}}$`));function isValidUid(e){return e!=null&&uidRE().exec(e)!=null}var L=class{constructor(e,n,r,a){this.s=e,this._l=n,this._sids=r,this.meta={src:a}}s;_l;_sids;static for(e){return new this(e.str,e.l,e.sids,e.src)}meta;get l(){return this._l}get ok(){if(this._l==null)return!1;let e=compact(uniq(intersection(this._sids,this._l.uids).map(getScheme)).map(e=>prefix2scheme(e))),n=e.length>=this._l.mat,r=Date.now(),a=this._l.activationId==null?within(this._l.iat?.getTime(),this._l.exp?.getTime()+dayMs,r):this._l.iat.getTime()<=r&&r<this._l.exp.getTime();return this.meta.dateOK=a,this.meta.uidsOK=n,this.meta.matchedSchemes=e,a&&n}cmpVal(){return[this.ok,-(S.indexOf(this.l?.tier)??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes??[]]}cmp(e){return cmp(this.cmpVal(),e.cmpVal())}},import_paseto=__toESM(require_lib()),PemFlavors=strEnum(`PRIVATE KEY`,`PUBLIC KEY`),armorRe=/\n?-----(?:BEGIN|END) (?:PRIVATE KEY|PUBLIC KEY)-----\n?/gi;function addPemArmor(e,n){return[`-----BEGIN ${n}-----`,rmPemArmor(e),`-----END ${n}-----`].join(`
|
|
721
|
+
`)+`
|
|
722
|
+
`}function rmPemArmor(e){return toS(e).replace(armorRe,``).trim()}var verificationKeys=[{format:`pem`,k:`2SoVY4nUP`,key:`MCowBQYDK2VwAyEAb3JzxWd0rNW8Sft1X9FgEXcbPmCtKT/Eqmh+qx3wczk=`,signingStoppedAt:`2026-09-15T17:32:50.672Z`,type:`spki`},{format:`pem`,k:`2SejK9mQF`,key:`MCowBQYDK2VwAyEALk0hjhWgruhRGyG9vDlZjIjtsDkNkKLvYl0SD+ZkXXo=`,licenseProtocol:2,maximumTokenLifetimeMs:36294e5,publishedAt:`2026-08-21T17:58:34.433Z`,type:`spki`}];for(let[e,n]of Object.entries(import_paseto.errors))Object.defineProperty(n,"name",{value:e,configurable:!0});var PasetoV2PublicPrefix=`v2.public.`;async function V(e){let n=(0,import_paseto.decode)(e).payload;if(n==null)throw new MetaError(`Missing payload`,{code:`ERR_LICENSE_MISSING_PAYLOAD`});let r=verificationKeys.find(e=>e.k===n.k);if(r==null)throw new MetaError(`Unknown key`,{code:`ERR_LICENSE_UNKNOWN_KEY`});let a=await import_paseto.V2.verify(e,{format:r.format,key:addPemArmor(r.key,`PUBLIC KEY`),type:r.type});if(r.maximumTokenLifetimeMs!=null){let e=new Date(a.iat).getTime(),n=new Date(a.exp).getTime();if(!Number.isFinite(e)||!Number.isFinite(n)||n<=e||n-e>r.maximumTokenLifetimeMs)throw new MetaError(`Invalid token lifetime`,{code:`ERR_LICENSE_TOKEN_LIFETIME`})}return a}var import_windows_registry=require("@photostructure/windows-registry"),import_node_fs32=require("node:fs"),import_node_stream7=require("node:stream"),import_promises33=require("node:stream/promises"),GrepReader=class extends import_node_stream7.Transform{constructor(e){super({objectMode:!0,autoDestroy:!0}),this.pattern=e}pattern;result;_transform(e,n,r){let a=toS(e),o=this.pattern.exec(a);o!=null&&(this.result??=o,this.push(null)),r()}};async function fileGrep_(e,n,r={}){let a=new GrepReader(n);return await(0,import_promises33.pipeline)([(0,import_node_fs32.createReadStream)(toNativePath_(e)),new LineReader(r),a]),a.result}var logger135=defer(()=>mkLogger(`SystemIds`)),ProcCpuinfoPath=`/proc/cpuinfo`,ProcCmdlinePath=`/proc/cmdline`,IoregCommand=`ioreg`,IoregArgs=[`-rd1`,`-c`,`IOPlatformExpertDevice`],WindowsMachineGuidHive=`HKEY_LOCAL_MACHINE`,WindowsMachineGuidKey=`SOFTWARE\\Microsoft\\Cryptography`,WindowsMachineGuidValue=`MachineGuid`,LinuxMachineIdPaths=[`/etc/machine-id`,`/var/lib/dbus/machine-id`],DockerHostMachineIdPaths=[`/ps/host/machine-id`],DmiPaths=Object.freeze({productUuid:[`/sys/class/dmi/id/product_uuid`,`/run/photostructure/dmi/product_uuid`],boardSerial:[`/sys/devices/virtual/dmi/id/board_serial`,`/run/photostructure/dmi/board_serial`],productSerial:[`/sys/class/dmi/id/product_serial`,`/run/photostructure/dmi/product_serial`],chassisSerial:[`/sys/class/dmi/id/chassis_serial`,`/run/photostructure/dmi/chassis_serial`]}),BoardModelPaths=[`/sys/devices/virtual/dmi/id/board_vendor`,`/sys/devices/virtual/dmi/id/board_name`];async function readInfo(e=ProcCpuinfoPath){if(isLinux)try{return(await fileGrep_(e,/^\s*serial\s*[:=]\s*(?!0+$)(?<uid>\w{9,})/i,{trimEnd:!0}))?.groups?.uid}catch{return}}var cpuinfoSerial=defer(async()=>toUID(S2.lc,await readInfo()));async function readNonblankFiles(e){return uniq((await Promise.all(e.map(e=>readFileMaybe(e,LogLevels.trace)))).map(e=>toS(e).trim()).filter(e=>e.length>0))}async function readFiles(e){return(await readNonblankFiles(e)).filter(e=>!isPlaceholderId(e))}async function linuxMachineUid(){if(isLinux)return(await readFiles(isDocker()?DockerHostMachineIdPaths:LinuxMachineIdPaths)).map(e=>toUID(S2.lm,e))}async function linuxProductUid(){return isLinux?(await readFiles(DmiPaths.productUuid)).map(e=>toUID(S2.lp,e)):void 0}async function linuxBoardSerial(){return isLinux?(await readFiles(DmiPaths.boardSerial)).map(e=>toUID(S2.lb,e)):void 0}async function linuxSystemSerial(){return isLinux?(await readFiles(DmiPaths.productSerial)).map(e=>toUID(S2.ls,e)):void 0}async function linuxChassisSerial(){return isLinux?(await readFiles(DmiPaths.chassisSerial)).map(e=>toUID(S2.lh,e)):void 0}function rootUuidFromCmdline(e){let n=parseEnvTokens({input:toS(e),lowerCaseKeys:!1}).root;return/^(?:PART)?UUID=(.+)$/i.exec(toS(n))?.[1]}function serialFromCmdline(e){return parseEnvTokens({input:toS(e),lowerCaseKeys:!1}).sn}function uidsFromLinuxCmdline(e){return[toUID(S2.ln,serialFromCmdline(e)),toUID(S2.lr,rootUuidFromCmdline(e))].filter(isString)}async function linuxCmdlineUids(){if(isLinux)return uidsFromLinuxCmdline(toS(await readFileMaybe(ProcCmdlinePath,LogLevels.trace)))}async function mac_IOPlatformUUID_(){let e=await stdout_(IoregCommand,IoregArgs,{timeoutMs:5*secondMs});return{mp:e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],ms:e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1]}}var macUids=rolazy(async()=>{if(isMac)try{return entries(await mac_IOPlatformUUID_()).map(([e,n])=>toUID(e,n))}catch(e){logger135().warn(IoregCommand+` failed`,e);return}});function win_machineGuid_(){try{return(0,import_windows_registry.GetStringRegKey)(WindowsMachineGuidHive,WindowsMachineGuidKey,WindowsMachineGuidValue)}catch(e){logger135().warn(`reading `+WindowsMachineGuidHive+` failed`,e);return}}function winMachineUid(){return isWin?toUID(S2.wm,win_machineGuid_()):void 0}var cpuModel=defer(()=>toUID(S2.cm,cpuInfo()[0].model));function boardModelUid(e){let n=e.filter(e=>!/o\.e\.m\./i.test(e));return n.some(isPlaceholderId)?void 0:toUID(S2.bm,n.join(`
|
|
723
|
+
`))}async function boardModel(){return isLinux?boardModelUid(await readNonblankFiles(BoardModelPaths)):[]}async function libraryUid(){return toUID(S2.li,await libraryUidStore()?.readUid_())}async function systemUid(){return toUID(S2.si,await systemUidStore()?.readUid_())}function networkMacUids(){return isDocker()?[]:networkMacAddresses().map(e=>toUID(S2.nm,e))}async function libraryVolumeIds(){let e=[];for await(let n of libraryVolumeUUIDs())e.push(toUID(S2.vl,n));return e}async function homeDirVolumeId(){if(!isDocker())return toUID(S2.vl,(await bestVolumeForPath(homeDir()))?.uuid)}var priorSids=new Set;async function sids({timeoutMs:e}){let n=performance.now(),r={cpuModel,cpuinfoSerial,macUids,libraryUid,systemUid,boardModel,linuxMachineUid,linuxProductUid,linuxBoardSerial,linuxSystemSerial,linuxChassisSerial,linuxCmdlineUids,winMachineUid,networkMacUids,libraryVolumeIds,homeDirVolumeId},a=await timeOrTimeout(r,{timeoutMs:e}),o=Object.keys(r);for(let[e,n]of a.entries())n instanceof Error&&logger135().warn(o[e]+`() failed; its uid is missing from sids()`,{error:n});let s=flatten(a).filter(isString);for(let e of s)priorSids.add(e);return logger135().tap({msg:`sids()`,result:sortUids([...priorSids,...s]),meta:{timeoutMs:e,elapsedMs:roundMs(performance.now()-n)}})}function clearSids(){isTest()&&priorSids.clear()}later(()=>{isTest()&&ee().on(`clearCache`,clearSids)});var UserTimeoutMs=7*secondMs,LicensesDirname=`licenses`,logger136=defer(()=>mkLogger(`Licensing`));async function v_(e){let n=await V(ensurePrefix(toS(e).trim(),PasetoV2PublicPrefix)),r=utcIsoToTs(n.iat);if(r==null)throw new MetaError(`bad iat`,{code:`ERR_LICENSE_BAD_IAT`});let a=utcIsoToTs(n.exp);if(a==null)throw new MetaError(`bad exp`,{code:`ERR_LICENSE_BAD_EXP`});let o=n.activationId,s;if(o!==void 0){if(typeof o!=`number`||!Number.isSafeInteger(o)||o<=0)throw new MetaError(`bad activationId`,{code:`ERR_LICENSE_BAD_ACTIVATION_ID`});s=o}let c=n.refreshAt,l;if(c!==void 0){if(s==null)throw new MetaError(`refreshAt requires activationId`,{code:`ERR_LICENSE_REFRESH_AT_REQUIRES_ACTIVATION_ID`});if(l=utcIsoToTs(c),l==null)throw new MetaError(`bad refreshAt`,{code:`ERR_LICENSE_BAD_REFRESH_AT`});if(l<=r||l>=a)throw new MetaError(`bad refreshAt ordering`,{code:`ERR_LICENSE_BAD_REFRESH_AT_ORDERING`})}let u=n.subscriptionEndsAt,d;if(u!==void 0&&(d=utcIsoToTs(u),d==null))throw new MetaError(`bad subscriptionEndsAt`,{code:`ERR_LICENSE_BAD_SUBSCRIPTION_ENDS_AT`});return getDevEnvFlag(`PS_FORCE_TRIAL`)&&(n.trial=!0),n.mat=toGte0(n.mat)??2,n.iat=new Date(r),n.exp=new Date(a),s!=null&&(n.activationId=s),l!=null&&(n.refreshAt=new Date(l)),d!=null&&(n.subscriptionEndsAt=new Date(d)),n.uids=toS(n.uids).split(`,`),n}async function v(e,n,r,a){try{return blank(e)||e===S.lite?void 0:L.for({str:e,l:await v_(e),sids:a??await sids({timeoutMs:r}),src:n})}catch(n){let r=n,a={msg:`validate`,result:{s:e,ok:!1,meta:{error:n}}};return logger136().debug(`validate`,{error:{code:r?.code,name:r?.name}}),a.result}}var m2=rolazy(async()=>{if(isEnvTrue(`PS_FORCE_LITE`)||getEnv(`PS_FORCE_LITE`)===S.lite)return[];let e=await sids({timeoutMs:UserTimeoutMs}),n=map(configDir(),e=>BaseFile.for(e)),r=sorted(flatten((await someOrTimeout([()=>rawLicenseFromSettings(e),()=>rawFromDir(n?.join(LicensesDirname),e),()=>rawFromDir(libraryDataDirPosixFile()?.join(LicensesDirname),e),()=>rawFromDir(n?.sibling(AppName().toLowerCase()).join(LicensesDirname),e)],{timeoutMs:UserTimeoutMs})).filter(e=>!(e instanceof Error))));return logger136().debug(LicensesDirname+`()`,{count:r.length}),r});function rawLicenseFromSettings(e){return v(Settings2.license.value,`Settings`,UserTimeoutMs,e)}async function rawFromDir(e,n){let r=[],a=await sortByAsync({iter:e?.childFiles(),f:e=>e.mtimeMs()});for(let e of a.reverse()){let a=await v(toA(await e.readLines()).map(e=>e.trim()).join(``),e.nativePath,UserTimeoutMs,n);a!=null&&r.push(a)}return r}function sorted(e){return sortBy(e.filter(e=>e!=null&&(isError(e)&&logger136().warn(LicensesDirname+`: `,e),e!=null&&!isError(e)&&e?.l!=null)),e=>[!e.ok,S.indexOf(e.l?.tier)??S.length+1,-(e.l?.exp?.getTime()??1)])}later(()=>{ee().on(`clearCache`,()=>m2.unset()),ee().on(`reloadLicenses`,()=>m2.unset())});async function b(){let e=await m2();return e[0]?.ok?e[0]:void 0}async function t(){return(await b())?.l?.tier??S.lite}async function p(){try{return await t()===S.plus}catch{return!1}}var import_exiftool_vendored24=require("exiftool-vendored");function captureTagDate(e){let n=isNumber(e)&&e>=ParsingSettings.minValidYear.valueOrDefault?FuzzyDate.for({year:e}):isString(e)?Settings2.fuzzyDateParsing.valueOrDefault?parseDated({input:e,includeDate:!0,includeFuzzyDate:!0}):void 0:e;return isValidDate(n)?n:void 0}function earliestDate(e,n){let r=e;return leastBy(compact(n.map(e=>captureTagDate(r?.[e]))),e=>datedToMillis(e)??2**53-1)}function fileCaptureTimeFromTags(e){for(let n of[ParsingSettings.capturedAtTagsPrimary,ParsingSettings.capturedAtTagsSecondary,ParsingSettings.capturedAtTagsTertiary,ParsingSettings.capturedAtTagsFallback]){let r=earliestDate(e,n.values);if(r!=null)return r}}function sidecarCaptureTime(e,n,r){let a=e.applePhotosDateCreated,o=fileCaptureTimeFromTags(n);if(o==null){let e=a??r;return e!=null&&getDay(e)==null?datedToYMD(e,`:`):datedToEXIF(e)}if(a!=null){if(isVideoMimeType(n?.MIMEType)&&o instanceof import_exiftool_vendored24.ExifDateTime&&o.inferredZone===!0&&o.zone===`UTC`&&a.zone!=null)return datedToEXIF(o.setZone(a.zone,{keepLocalTime:!1}));if(!hasZone(o)&&hasZone(a))return datedToLocal(o)===datedToLocal(a)?datedToEXIF(a):void 0}}function collectionUri(e){return`photostructure:album/`+encodeURIComponent(e)}var ListFields=new Set([`Keywords`,`PersonInImage`,`Collections`]),UnavailableSidecarFields={keywords:`Keywords`,albums:`Collections`,personNames:`PersonInImage`,description:`Description`},ProvenanceKey=`applePhotosSidecar`;function prepareSidecar(e,n,r){let a=n?.inferred?.applePhotosSidecar,o={...a?.original},s={...a?.written},c={...n},l=new Set,u=new Set((e.applePhotos?.unavailableFields??[]).map(e=>UnavailableSidecarFields[e]));for(let[e,n]of entries(s)){if(u.has(e))continue;let r=c[e];ListFields.has(e)?c[e]=toA(r).filter(r=>toA(o[e]).some(e=>eqlTagValue(e,r))||!toA(n).some(e=>eqlTagValue(e,r))):eqlTagValue(r??null,n,e)?c[e]=o[e]:l.add(e)}let d=toA(c.Collections),f=(e,n)=>uniq([...toA(c[e]),...toA(n)]),h=uniq(toA(e.applePhotosAlbums)).filter(e=>!d.some(n=>n.CollectionName===e)),_=e=>!blank(c[e]),y={PreservedFileName:_(`PreservedFileName`)?void 0:e.PreservedFileName,Keywords:f(`Keywords`,e.Keywords),PersonInImage:f(`PersonInImage`,e.PersonInImage),Collections:[...d,...h.map(e=>({CollectionName:e,CollectionURI:collectionUri(e)}))],Title:_(`Title`)?void 0:e.Title,Description:_(`Description`)?void 0:e.Description,Country:e.applePhotosCountry,CountryCode:e.applePhotosCountryCode,State:e.applePhotosState,City:e.applePhotosCity,Location:e.applePhotosPOI??e.applePhotosSubLocality,GPSLatitude:_(`GPSLatitude`)?void 0:e.GPSLatitude,GPSLongitude:_(`GPSLongitude`)?void 0:e.GPSLongitude,GPSAltitude:_(`GPSAltitude`)?void 0:e.GPSAltitude,DateTimeOriginal:sidecarCaptureTime(e,c,r)},x={};for(let[e,n]of entries(y)){if(l.has(e)||u.has(e))continue;let r=blank(n)||Array.isArray(n)&&n.length===0?void 0:n;(r!=null||e in s)&&(x[e]=r??(ListFields.has(e)?null:c[e]??null),o[e]=ListFields.has(e)?toA(c[e]):c[e]??null,s[e]=x[e])}return{tags:x,provenance:{original:o,written:s}}}function holdsApplePhotosProvenance(e){return tagsContainHistory(e,e=>e.Changed===ProvenanceKey)}async function ensureApplePhotosSidecar(e,n,r,a){if(r==null||!Settings2.writeInferredTagsToLibraryCopies.valueOrDefault)return;let{tags:o,provenance:s}=prepareSidecar(r,await readRawMergedTags(e),a);if(!isEmptyObj(o))return ensureHistoryRecords(n,[mkHistoryRecord({action:Actions.infer,key:ProvenanceKey,value:s})],o)}var import_node_net5=require("node:net"),LanOnlyHostnameSuffixes=[`.local`,`.home.arpa`,`.internal`,`.lan`];function lanOnlyHostname(e){return!e.includes(`.`)||LanOnlyHostnameSuffixes.some(n=>e.endsWith(n))}function signInOffServesHostname(e,n){return(0,import_node_net5.isIP)(e.replace(/^\[(.*)\]$/u,`$1`))!==0||e.endsWith(`.localhost`)||lanOnlyHostname(e)||n.includes(e)}function signInOffConfiguredHostnames(e){return compactBlanks([e,Settings2.localhost.valueOrDefault?.toLowerCase()])}function myWebUrls(e=Settings2.httpPort.valueOrDefault){let n=authCanonicalOriginFromSettings(void 0,{httpPort:e});if(n!=null)return[toURI(n)];let r=[Settings2.localhost.valueOrDefault];Settings2.exposeNetworkWithoutAuth.valueOrDefault&&r.push(...compactBlanks([...myExternalIp4Addresses(),Settings2.hostname.valueOrDefault]).filter(e=>signInOffServesHostname(e.toLowerCase(),signInOffConfiguredHostnames(void 0))));let a=toURI(`http://a`);return uniqBy(r.map(n=>a.with({authority:n+`:`+e})),e=>e.toString())}var myWebUrl=lazy2(()=>myWebUrls()[0]);function mkFolderUrl(e){let n=originalsLibraryTagPath({uri:e.uri.toString(),isFile:!1})??uriToTagPath({uri:e.uri,isFile:!1});if(isEmpty(n))return;let r=mkTagUri(tagPathToStringArray(n));return myWebUrl()?.with(r)}function mkAssetUrl(e){return gt0(e)?myWebUrl()?.with({path:`/asset/`+e}):void 0}var import_node_crypto8=require("node:crypto"),PasetoHeader=Buffer.from(`v2.public.`,`ascii`),Ed25519SignatureBytes=64,LegacyExpirationGraceMs=864e5,wetCopyTextSalt=[47,116,5,152,204,130,5,0,36,218,75,139,169,133,70,191,36,217,57,69,85,15,239,53,34,137,152,65,31,141,108,145];function wetCopyText(e){let n=e.map((e,n)=>e^wetCopyTextSalt[n%wetCopyTextSalt.length]);return Buffer.from(n).toString(`utf8`)}var wetCopySchemeCodes=new Set([12168,61742,36960,36079,18345,35198,16583,14821,57337,4591,3710,18272,58208,24160,39520,59980,36172,6363]);function wetCopySchemeIsRecognized(e){if(e.length!==2)return!1;let n=e.charCodeAt(0)<<8|e.charCodeAt(1),r=Math.imul(n,43397)+18111&65535;return wetCopySchemeCodes.has(r)}var copyLicenseKeys=new Map([[wetCopyText([29,39,106,206,149,182,107,85,116]),{spkiBase64:wetCopyText([98,55,106,239,142,211,92,68,111,232,29,252,232,252,3,254,70,234,115,63,45,88,139,5,80,199,207,121,76,235,24,160,119,77,67,255,137,218,102,98,116,183,8,255,226,209,105,250,85,180,81,110,36,119,220,66,65,243,243,124])}],[wetCopyText([29,39,96,242,135,187,104,81,98]),{maximumTokenLifetimeMs:36294e5,spkiBase64:wetCopyText([98,55,106,239,142,211,92,68,111,232,29,252,232,252,3,254,104,178,9,45,63,103,184,82,80,252,240,19,88,244,43,168,89,48,105,194,166,203,111,116,87,158,32,197,194,206,10,201,125,181,9,22,17,36,181,94,122,209,247,124])}]]);async function copyLicenseCandidates(){let e=new Map,n=n=>{let r=n?.split(/\r?\n/).map(e=>e.trim()).join(``);r!=null&&r.length>0&&r!==`lite`&&e.set(r,!0)};n(Settings2.license.value);let r=configDir(),a=r==null?void 0:BaseFile.for(r),o=[a?.join(`licenses`),libraryDataDirPosixFile()?.join(`licenses`),a?.sibling(AppName().toLowerCase()).join(`licenses`)];for(let e of o){let r=await e?.childFiles()??[];for(let e of r)n(toA(await e.readLines()).map(e=>e.trim()).join(``))}return Array.from(e.keys())}function littleEndianUint64(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`PASETO input is too large`);let n=Buffer.allocUnsafe(8);return n.writeBigUInt64LE(BigInt(e)),n}function preAuthenticationEncode(e){let n=[littleEndianUint64(e.length)];for(let r of e)n.push(littleEndianUint64(r.byteLength),r);return Buffer.concat(n)}function decodeBase64Url(e){if(!/^[\w-]*={0,2}$/.test(e))throw Error(`invalid PASETO base64url`);let n=e.replace(/={1,2}$/,``),r=Buffer.from(e,`base64url`);if(r.toString(`base64url`)!==n)throw Error(`non-canonical PASETO base64url`);return r}function parseClaims(e){let n=JSON.parse(e.toString(`utf8`));if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`PASETO payload is not an object`);return n}function splitPaseto(e){let n=e.trim(),r=(n.startsWith(`v2.public.`)?n:`v2.public.`+n).split(`.`);if(r.length!==3&&r.length!==4||r[0]!==`v2`||r[1]!==`public`)throw Error(`license is not a PASETO v2.public token`);let a=decodeBase64Url(r[2]);if(a.byteLength<=Ed25519SignatureBytes)throw Error(`PASETO body is too short`);return{footer:decodeBase64Url(r[3]??``),message:a.subarray(0,-Ed25519SignatureBytes),signature:a.subarray(-Ed25519SignatureBytes)}}function verifyCopyLicense(e,n,r){let a=r.get(e);if(a!=null)return a;let{footer:o,message:s,signature:c}=splitPaseto(e),l=parseClaims(s);if(typeof l.k!=`string`)throw Error(`copy license has no signing key`);let u=l.k,d=n.get(u);if(d==null)throw Error(`copy license key is not trusted`);let f=(0,import_node_crypto8.createPublicKey)({format:`der`,key:Buffer.from(d.spkiBase64,`base64`),type:`spki`}),h=preAuthenticationEncode([PasetoHeader,s,o]),_=Buffer.from(c);if(_[0]^=1,(0,import_node_crypto8.verify)(null,h,f,_))throw Error(`signature verifier accepted an invalid copy license`);if(!(0,import_node_crypto8.verify)(null,h,f,c))throw Error(`copy license signature is invalid`);let y=parseClaims(s);if(y.k!==u)throw Error(`copy license signing key changed during verification`);let x=typeof y.iat==`string`?Date.parse(y.iat):NaN,C=typeof y.exp==`string`?Date.parse(y.exp):NaN;if(!Number.isFinite(x)||!Number.isFinite(C)||C<=x)throw Error(`copy license timestamps are invalid`);if(d.maximumTokenLifetimeMs!=null&&C-x>d.maximumTokenLifetimeMs)throw Error(`copy license lifetime is too long`);let w={claims:y,expiresAtMs:C,issuedAtMs:x};return r.set(e,w),w}function forceLiteForCopy(){let e=process.env.PS_FORCE_LITE?.trim().toLowerCase();return e===`1`||e===`true`||e===`lite`}function verifiedLicenseAllowsCopy(e,n,r){let{claims:a,expiresAtMs:o,issuedAtMs:s}=e;if(a.tier!==`plus`||typeof a.uids!=`string`)return!1;let c=typeof a.mat==`number`&&Number.isFinite(a.mat)&&a.mat>=0?a.mat:2,l=new Set(a.uids.split(`,`)),u=new Set;for(let e of n){if(!l.has(e))continue;let n=e.indexOf(`:`);if(n<=0)continue;let r=e.slice(0,n);wetCopySchemeIsRecognized(r)&&u.add(r)}if(u.size<c||a.subscriptionEndsAt!==void 0&×tamp(a.subscriptionEndsAt)==null)return!1;if(a.activationId===void 0)return a.refreshAt===void 0&&s<=r&&r<=o+LegacyExpirationGraceMs;if(typeof a.activationId!=`number`||!Number.isSafeInteger(a.activationId)||a.activationId<=0)return!1;if(a.refreshAt!==void 0){let e=timestamp(a.refreshAt);if(e==null||e<=s||e>=o)return!1}return s<=r&&r<o}function timestamp(e){if(typeof e!=`string`)return;let n=Date.parse(e);return Number.isFinite(n)?n:void 0}async function copyPlusLicenseDenial(e,n){if(forceLiteForCopy())return`PLUS is disabled by PS_FORCE_LITE`;let r,a;try{r=await copyLicenseCandidates(),a=await sids({timeoutMs:UserTimeoutMs})}catch{return`copy-to-library could not verify a PLUS license`}let o=Date.now();for(let s of r)try{if(verifiedLicenseAllowsCopy(verifyCopyLicense(s,e,n),a,o))return}catch{}return`copy-to-library requires a current PLUS license`}function createCopyPlusLicensePolicy(e){let n=new Map(e),r=new Map;return{clear:()=>r.clear(),whyDenied:async()=>await copyPlusLicenseDenial(n,r)}}var productionCopyPolicy=createCopyPlusLicensePolicy(copyLicenseKeys);async function whyCopyPlusLicenseDenied(){return await productionCopyPolicy.whyDenied()}async function mayCopyAssetsToLibrary(){return Settings2.copyAssetsToLibrary.valueOrDefault&&await p()}var AssetFileRepository=class{constructor(e,n){this.originalsDir=e,this.libraryDir=n}originalsDir;libraryDir;logger=mkLogger(`AssetFileRepository`);async shouldCopy(e){let n=await this.whyNotCopyFile(e);return this.logger.tap({level:`info`,msg:`shouldCopy()`,result:n==null,meta:{file:e?.nativePath,whyNot:n}})}async whyNotCopyFile(e){if(e==null||blank(e.nativePath))return`blank nativePath`;if(Settings2.copyAssetsToLibrary.value!==!0)return`copyAssetsToLibrary !== true`;{let e=await whyCopyPlusLicenseDenied();if(e!=null)return e}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(this.libraryDir))return e+` already contained by `+Settings2.libraryDir.valueOrDefault;let n=await readMimeType(e);return n==null?`readMimeType(`+e+`) was null`:isMimeTypeIncluded(n,Settings2.copyToLibraryMimeTypes.values)?null:`mimetype `+n+` is not included in copyToLibraryMimeTypes`}async existingLibraryAssetFile(e){if(e.isInLibrary())return e;let n=uniqBy(toA(e.librarySiblings()?.filter(n=>n.sha===e.sha)).concat(AssetFile.dao.sameAssetFileInLibrary(e)),e=>e.id);for(let r of n)if(await r.exists_()){if(r.assetId!==e.assetId){syncReport().onProgress({from:`existingLibraryAssetFile()`,path:r.nativePath,type:`file`,state:SyncFileStates.warning,details:`Found a library asset file with a matching SHA that is associated to a different asset. Skipping.`,meta:{nonLibraryAssetFile:pick(e,`id`,`uri`,`assetId`),libraryAssetFile:pick(r,`id`,`uri`,`assetId`)}}),r.assetId!=null&&(Asset.dbl.runf(e=>AssetFlags.update({qb:e,flag:`validateSiblings`,isSet:!0}).where(`id`,r.assetId)),ee().emitThrottled(`notifyWorkAvailable`,`validateAssetSiblings`));continue}return this.logger.info(`whyNotCopyAssetFile(`+e.uri+`): found existing db record`,{af:e,prior:r}),r}return null}async findLibraryFileWithSameContents(e,n){if(await e.matchesContent(n))return n;let r=n.parent();for(;r.isSelfOrDescendantOf(this.originalsDir);){let n=r.childWithSameContents(e);if(n!=null)return n;r=r.parent()}}async importFile_(e,n,r){let{dest:a,copied:o}=await this.#e(e,n,r);return await this.#r(e,a,o),await this.#o(e,a,o),a}async#e(e,n,r){let a=n??await readCapturedAt(e),o=pathToLibraryAsset(a?.date,e,r,(await readTags(e))?.PreservedFileName);if(this.logger.debug(`importFile(`+e+`)`,{capturedAt:a,assetPath:o}),o==null)throw Error(e.nativePath+` failed to create a library path`);let s=this.originalsDir.join(...o),c=await this.findLibraryFileWithSameContents(e,s);if(c!=null)return this.logger.debug(`#importFile_(`+e+`): found existing file`,{src:e,existing:c}),{dest:c,copied:!1};let l=await s.ensureNew_();return this.logger.info(`#importFile_(`+e+`): copying...`,{uniqDest:l,dest:s}),{dest:await e.copyFile_(l),copied:!0}}async#t(e){return toA(await e.siblings(n=>!isSidecarExt(n.ext)&&equalsIgnoreCase(n.name,e.name)))}async#n(e,n){let r=await this.#t(e);for(let e of await this.#t(n)){let n=!1;for(let a of r)if(await a.matchesContent(e)){n=!0;break}if(!n)return!1}return!0}async#r(e,n,r){let a=await this.#n(e,n),o=(await e.existingSidecars()).reverse(),s=[];for(let c of o)s.push(await this.#i(e,c,n,r,a));return compact(s)}async#i(e,n,r,a,o){let s=n.ext,c=o&&equalsIgnoreCase(n.name,e.name)?r.name+s:r.base+s,l=a?[c]:[r.base+s,r.name+s];for(let e of await r.existingSidecars())if(l.some(n=>equalsIgnoreCase(e.base,n))){this.logger.info(`handleSidecar(): library copy has a sidecar.`,{srcSidecar:n,destSidecar:e,dest:r});return}let u=await r.parent().join(c).ensureNew_({emptyIsNew:!0});return n.copyFile_(u)}async#a(e,n,r){let a=defaultSidecarExt(),o=await n.existingExifSidecars(),s=e=>o.find(n=>equalsIgnoreCase(n.base,e)),c=s(n.base+a),l=s(n.name+a),u=l!=null&&(!r&&c==null||await this.#n(e,n)),d=o.filter(e=>e===c||u&&e===l),f=[],h=[];for(let e of d){let n=await readRawTags(e);holdsApplePhotosProvenance(n)&&f.push(e),tagsContainHistory(n,e=>startsWithIgnoreCase(e.SoftwareAgent,`PhotoStructure`))&&h.push(e)}return f.at(-1)??h.at(-1)??d.at(-1)??n.defaultSidecar()}async#o(e,n,r){if(e==null||n==null||e.$eql(n))return;let a=await readTags(e);if(a==null){this.logger.warn(`#handleInferred(): Failed to read tags from `+e,{dest:n});return}let o=Settings2.writeInferredTagsToLibraryCopies.valueOrDefault?await readApplePhotosTags(e.nativePath):void 0,s=await this.#a(e,n,r),{capturedAt:c,...l}=a.inferred??{},u=await ensureInferredHistoryRecords(e,s,o==null?a.inferred:l),d=await ensureApplePhotosSidecar(n,s,o,c?.date);return u??d}async maybeCopyToLibrary_(e,n,r){let a=performance.now();await e.resolveNativePath_();let o=e.posixFile_();o??this.logger.throw(`maybeCopyToLibrary_(`+e.uri+`): posixFile is null`,{ignorable:!1,retriable:!1});{let e=await this.whyNotCopyFile(o);if(!blank(e))return this.logger.tap({level:LogLevels.info,msg:`maybeCopyToLibrary_(): not copying: `+e,result:void 0})}let s=e.getAsset();s??this.logger.throw(`maybeCopyToLibrary_(`+e.uri+`): null asset`);let c=await whyCopyPlusLicenseDenied();if(c!=null)return this.logger.tap({level:LogLevels.info,msg:`maybeCopyToLibrary_(): not copying: `+c,result:void 0});{let c=await this.existingLibraryAssetFile(e);if(c!=null){let e=c.posixFile_();if(e==null)this.logger.warn(`existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile`,{prior:c});else{let l=await this.#r(o,e,!1),u=await this.#o(o,e,!1)!=null,d=await c.upsertIfNeeded_(void 0,n)!=null;return!u&&isEmpty(l)&&!d||(syncReport().onProgress({path:e.nativePath,from:`maybeCopyToLibrary()`,type:`file`,state:SyncFileStates.imported,details:`Found and imported prior replica already in your library`,meta:{src:o.nativePath,upsertNeeded:d,copiedSidecars:l,copiedInferredMetadata:u},elapsedMs:roundMs(performance.now()-a),url:mkAssetUrl(s.id)?.toString()}),r?r(s.id):addLocalTask(`repairAsset`,{assetId:s.id})),c}}}let l=CapturedAt.fromMediaInfo({mimetype:e.mimetype,capturedAtLocal:e.capturedAtLocal,capturedAtZone:e.capturedAtZone,capturedAtSrc:e.capturedAtSrc,capturedAtPrecisionMs:e.capturedAtPrecisionMs}),u=await this.importFile_(o,l,e.sha);if(u==null){this.logger.info(`importFile() returned null`,{srcAssetFile:e});return}if(u.nativePath===o.nativePath){this.logger.info(`importFile() returned the same nativePath as src`,{srcAssetFile:e,dest:u});return}let d=await s.assetFileForFile_(u,{skipUpsert:!0});await d.updateFromShaSibling_(e);let f=d.upsert();return syncReport().onProgress({path:u.nativePath,from:`maybeCopyToLibrary()`,type:`file`,state:SyncFileStates.copied,details:`Copied into your library from `+o.nativePath,elapsedMs:roundMs(performance.now()-a),url:mkAssetUrl(s.id)?.toString()}),f}},logger137=lazy2(()=>mkLogger(`sync-file.AssetFileComparator`));function whyInequal(e,n,r,a=(e,n)=>[e,n]){let o=e[r],s=n[r];if(blank(o)||blank(s)||eql(o,s))return;let[c,l]=a(o,s);return eql(c,l)||eql(o,l)||eql(c,s)?void 0:`Different ${String(r)}: ${o} \u2260 ${s}`}function lc(e){return mapNotBlank(e,e=>e.toLowerCase().trim().normalize())}function lc2(e,n){return[lc(e),lc(n)]}var VideoImageMismatchMsg=`Videos ≠ images`;function whyExifUidNotEql(e,n,r){let a=findInequalFields(e[r],n[r]);return a==null?void 0:`Different ${r} (${a.aKey}:${a.aValue} \u2260 ${a.bKey}:${a.bValue})`}var CapturedAtMismatchMsg=`captured-at mismatch`;function isSimilarMedia(e,n){return whyNotSimilarMedia_(e,n,!1)==null}function similarityProbe(e){let n=!1,r,a=()=>(n||=(r=e==null?void 0:CapturedAt.fromMediaInfo(e),!0),r);return n=>whyNotSimilarMedia_(e,n,!1,a)==null}function missingFields(e,...n){if(e==null)return n.map(e=>toS(e));let r=[];for(let a of n)e[a]??r.push(toS(a));return r.length===0?void 0:r}function definedNonBlankEql(e,n){return e==null||n==null||blank(e)||blank(n)?!1:eql(e,n)}function whyNotSimilarMedia(e,n){return whyNotSimilarMedia_(e,n,!0)}function whyNotSimilarMedia_(e,n,r,a){if(e==null&&n==null)return`both a and b are undefined`;if(e==null)return`a is undefined`;if(n==null)return`b is undefined`;let o=missingFields(e,`uri`,`width`,`height`,`mimetype`);if(o!=null)return`a was missing fields: `+o.join(`, `);let s=missingFields(n,`uri`,`width`,`height`,`mimetype`);if(s!=null)return`b was missing fields: `+s.join(`, `);if(definedNonBlankEql(e.sha,n.sha)){logger137().debug(`whyNotSimilarMedia(): same sha: same asset`,{a:e.uri,b:n.uri});return}let c=isVideoMimeType(e.mimetype),l=isVideoMimeType(n.mimetype);if(c!==l)return logger137().tap({msg:`whyNotIsSimilar`,result:VideoImageMismatchMsg,meta:{a:e.uri,b:n.uri,aIsVideo:c,bIsVideo:l}});if(isTrue(e.monochrome)!==isTrue(n.monochrome)&&Settings2.requireSameColorSpace.valueOrDefault)return`Greyscale ≠ color (set requireSameColorSpace to possibly group them)`;let u=whyInequal(e,n,`make`,lc2)??whyInequal(e,n,`model`,lc2);if(!(CapturedAt.isFuzzyFields(e)||CapturedAt.isFuzzyFields(n)||localIsImprecise(e.capturedAtLocal)||localIsImprecise(n.capturedAtLocal))&&u!=null)return u;let d=a==null?CapturedAt.fromMediaInfo(e):a(),f=CapturedAt.fromMediaInfo(n);if(d==null)return`a missing capturedAt metadata`;if(f==null)return`b missing capturedAt metadata`;if((d.isFuzzy||f.isFuzzy||d.isImprecise||f.isImprecise)&&Settings2.allowFuzzyDateImageHashMatches.valueOrDefault){let r=Settings2.imageHashFuzzyDateThresholdPct.valueOrDefault/100,a=compareHashRecords(e,n,isTrue(e.monochrome)||isTrue(n.monochrome));if(a?.confidence>=r){logger137().info(`allowFuzzyDateImageHashMatches mode: image hashes match`,{a:e.uri,b:n.uri,comparison:a});return}if(whyImageHashesNotSimilar(e,n,r,r)==null){logger137().info(`allowFuzzyDateImageHashMatches mode: rotation-aware match`,{a:e.uri,b:n.uri});return}}if(d.isFuzzy||f.isFuzzy||d.isImprecise||f.isImprecise){let r=shortestBname(e.basename),a=shortestBname(n.basename);if(!blank(r)&&r===a){let a=Math.max(Settings2.imageHashFuzzyDateThresholdPct.valueOrDefault,Settings2.imageHashThresholdPct.valueOrDefault)/100;if(whyImageHashesNotSimilar(e,n,a,a)==null){logger137().info(`same bname and fuzzy captured-at image hashes match`,{a:e.uri,b:n.uri,bname:r});return}}}if(!d.overlaps(f))return r?`captured-at ${d.toISOStringWithPrecision()} != ${f.toISOStringWithPrecision()}`:CapturedAtMismatchMsg;if(u!=null)return u;let h=coordinatesToGeoLocation(e),_=coordinatesToGeoLocation(n),y=h==null||_==null?void 0:sigFigs(distanceMeters(h,_),2),x=isTrue(e.locationIsApproximate)===isTrue(n.locationIsApproximate)?0:LegacyGeohash30BitMaxErrorMeters,C={cameraId:whyExifUidNotEql(e,n,`cameraId`)??null,imageId:whyExifUidNotEql(e,n,`imageId`)??null,lensId:whyExifUidNotEql(e,n,`lensId`)??null,exposureSettings:whyExposureSettingsNotSimilar(e,n)??null,closeCoordinates:gt(y,Settings2.gpsErrorMeters.valueOrDefault+x)?`coordinates are `+fmt(y)+`m different: too far apart`:null};logger137().debug(`whyNotSimilar()`,{fields:C});let w=compact(values(C));return isNotEmpty(w)?w.join(`;`):whyImageHashesNotSimilar(e,n)}function whyImageHashesNotSimilar(e,n,r,a){if(e==null)return`a is undefined`;if(n==null)return`b is undefined`;let o=e.mimetype===n.mimetype;r??=(o?Settings2.imageHashThresholdPct.valueOrDefault:Settings2.imageHashCrossFormatThresholdPct.valueOrDefault)/100,a??=Settings2.imageHashRotationThresholdPct.valueOrDefault/100;let s=!o||isTrue(e.monochrome)||isTrue(n.monochrome);for(let o of[e,hashRecord0ToHashRecord(e)])for(let c of[n,hashRecord0ToHashRecord(n)]){let l=o!==e!=(c!==n),u=l?a:r,d=compareHashRecords(o,c,s);if(logger137().debug(`whyImageHashesNotSimilar(): comparison`,{a:e.uri,b:n.uri,luminanceOnly:s,isRotated:l,threshold:u,ihc:d}),d.confidence>=u)return}return`image hashes do not match with confidence \u2265 ${sigFigs(r*100,3)}%`}function sortBySha(e){return sortBy(e,e=>gt0(e.width)&>0(e.height)&¬Blank(e.uri)?toNotBlank(e.sha):void 0)}function whyNotSimilarShaGroups(e,n){let r;for(let a of e)for(let e of n){let n=whyNotSimilarMedia(a,e);if(n==null)return;r??=n}return r}function whyNotValidShaGroup(e,n){for(let r of n){let n=whyNotSimilarShaGroups(e,r);if(n!=null)return n}}function seedShaOrder(e){return sortBy(e,e=>{let n=sortBySha(e.getAssetFiles())[0];return n==null?[1,``]:[0,n.sha]})}var logger138=defer(()=>mkLogger(`sync.AssetMatcher`));function clusterShaGroups(e){let n=sortBySha(e);if(n.length===0)return;let r=groupBySha(n),a=[r[0]],o=[{group:r[0],survivorCount:0}];for(let e of r.slice(1)){let n=a.length,r=whyNotValidShaGroup(e,a);r??a.push(e),o.push({group:e,why:r,survivorCount:n})}let s=new Set(a),c=[],l=[];for(let e of r)s.has(e)?c.push(...e):l.push(...e);return{survivors:c,evicted:l,groupDecisions:o}}function groupBySha(e){let n=new Map;for(let r of e){let e=n.get(r.sha);e==null?n.set(r.sha,[r]):e.push(r)}for(let e of n.values())e.sort((e,n)=>(e.id??0)-(n.id??0));return[...n.values()]}var AssetMatcher=class{static async findMatchingAsset(e,n={}){if(!assetFileHashReadyForMatching())throw Error(`AssetFileHash index is not ready for matching`);let{rejectedAssetIds:r}=n;logger138().info(`AssetMatcher: Searching for match`,{assetFileId:e.id,basename:e.basename,uri:e.uri,monochrome:e.monochrome,capturedAtLocal:e.capturedAtLocal,sha:e.sha?.substring(0,8)});let a=gt0(e.capturedAtLocal)?CapturedAt.fromFields(e):void 0,o=a?.localBoundaries(),s=a?.localBoundaries({precisionMs:Settings2.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault});if(notBlank(e.sha)){let a=this.#e(e.sha,r);if(a.length>0){let r=n.readOnly===!0?a[0]:await this.#t(e.sha,a),o=Asset.ops().findById(r);if(o!=null)return logger138().info(`Matched asset by SHA`,{assetFileId:e.id,assetId:o.id,sha:e.sha,collisionCount:a.length}),{asset:o,created:!1,matchedBy:`sha`}}}if(o!=null){let r=await this.#n(e,o,n);if(r!=null)return logger138().info(`Matched asset by basename + similarity`,{assetFileId:e.id,assetId:r.id,basename:e.basename}),{asset:r,created:!1,matchedBy:`basename`}}if(o!=null){let r=await this.#r(e,o,s??o,n);if(r!=null)return logger138().info(`Matched asset by capturedAt + similarity`,{assetFileId:e.id,assetId:r.id,capturedAtLocal:e.capturedAtLocal}),{asset:r,created:!1,matchedBy:`capturedAt`}}if(isVec0Available()){let r=await this.findAssetByBnameImageHashes(e,n);if(r!=null)return logger138().info(`Matched asset by bname + image hash`,{assetFileId:e.id,assetId:r.id}),{asset:r,created:!1,matchedBy:`bnameImageHash`}}if(Settings2.allowFuzzyDateImageHashMatches.valueOrDefault&&isVec0Available()){let r=await this.findAssetByImageHashes(e,n,o);if(r!=null)return logger138().info(`Matched asset by image hash`,{assetFileId:e.id,assetId:r.id}),{asset:r,created:!1,matchedBy:`imageHash`}}logger138().debug(`AssetMatcher: No match found`,{assetFileId:e.id,basename:e.basename})}static async findOrCreateAsset(e,n={}){let r=await this.findMatchingAsset(e,n);if(r!=null)return r;logger138().info(`AssetMatcher: No match found, creating NEW asset`,{assetFileId:e.id,basename:e.basename,monochrome:e.monochrome,capturedAtLocal:e.capturedAtLocal});let a=Asset.ops().insertOne({capturedAtLocal:e.capturedAtLocal,mimetype:e.mimetype,shown:!1});return e.assetId=a.id,e.isPrimary=!0,e.upsert(),logger138().info(`AssetMatcher: Created new asset`,{assetFileId:e.id,assetId:a.id,capturedAtLocal:e.capturedAtLocal}),{asset:a,created:!0,matchedBy:`created`}}static#e(e,n){if(blank(e))return[];let r=Asset.query().select(`Asset.id`).join(`AssetFile`,`Asset.id`,`AssetFile.assetId`).where(`AssetFile.sha`,e).orderBy(`Asset.id`).distinct();return n!=null&&n.size>0&&(r=r.whereNotIn(`Asset.id`,Array.from(n))),Asset.dbl.pluckAll(r)}static async#t(e,n){let r=n[0];if(n.length===1)return r;let a=n.slice(1);logger138().warn(`SHA collision across multiple Assets — dissolving duplicates`,{sha:e,keeperId:r,dupIds:a});for(let n of a){let a=AssetFile.ops().allf(e=>e.where(`assetId`,n)).map(e=>e.id).filter(gt0);a.length>0&&AssetFile.dao.orphan(...a),await Asset.dao.remove({assetId:n,blocklistShas:!1,unlinkAssetFiles:!1}),logger138().info(`SHA-collision duplicate dissolved`,{sha:e,keeperId:r,dissolvedAssetId:n,orphanedFileCount:a.length})}return r}static async#n(e,n,r){let{rejectedAssetIds:a}=r;if(!Settings2.checkBasenameMatches.valueOrDefault||blank(e.basename))return;let o=stripExt(e.basename).toLowerCase();if(blank(o))return;let s=Settings2.maxContemporaryAdoptionAssets.valueOrDefault,c=Asset.query().select(`Asset.id`).join(`AssetFile`,`Asset.id`,`AssetFile.assetId`).whereBetween(`Asset.capturedAtLocal`,[n.start,n.end]).whereRaw(`"AssetFile"."basename" LIKE ?`,[o+`.%`]).orderBy(`Asset.id`).limit(s).distinct();e.id!=null&&(c=c.whereNot(`AssetFile.id`,e.id)),a!=null&&a.size>0&&(c=c.whereNotIn(`Asset.id`,Array.from(a)));let l=Asset.dbl.pluckAll(c);if(l.length!==0)return logger138().debug(`Found candidates by basename`,{assetFileId:e.id,basename:e.basename,basenameWithoutExt:o,candidateCount:l.length}),this.validateCandidates(e,l,r,`basename`)}static async#r(e,n,r,a){let{rejectedAssetIds:o}=a,s=Settings2.maxContemporaryAdoptionAssets.valueOrDefault,c=Asset.query().select(`Asset.*`).join(`AssetFile`,`AssetFile.assetId`,`Asset.id`).join(`DirUri`,`DirUri.id`,`AssetFile.dirUriId`).where(a=>a.whereBetween(`Asset.capturedAtLocal`,[n.start,n.end]).orWhere(n=>n.whereBetween(`Asset.capturedAtLocal`,[r.start,r.end]).whereNot(`AssetFile.mimetype`,e.mimetype).whereNotExists(function(){this.select(1).from(`AssetFile as SameFormatAssetFile`).whereRaw(`?? = ??`,[`SameFormatAssetFile.assetId`,`Asset.id`]).where(`SameFormatAssetFile.mimetype`,e.mimetype)}))).orderByRaw(`abs(Asset.capturedAtLocal - ?), DirUri.uri, AssetFile.basename`,[e.capturedAtLocal]).limit(s).distinct();o!=null&&o.size>0&&(c=c.whereNotIn(`Asset.id`,Array.from(o)));let l=Asset.dbl.pluckAll(c.select(`Asset.id`));if(l.length===0)logger138().info(`Strategy 3: No candidate Assets found in capturedAt window`,{assetFileId:e.id,basename:e.basename,capturedAtLocal:e.capturedAtLocal,bounds:n,crossFormatBounds:r,limit:s});else return logger138().info(`Strategy 3: Found candidate Assets for capturedAt matching`,{assetFileId:e.id,basename:e.basename,candidateCount:l.length,candidateAssetIds:l,bounds:n,crossFormatBounds:r}),this.validateCandidates(e,l,a,`capturedAt`)}static async findAssetByImageHashes(e,n,r){if(!isVec0Available())return;let a=Settings2.imageHashMatchK.valueOrDefault,o=Settings2.maxContemporaryAdoptionAssets.valueOrDefault;return this.#i(e,a,o,n,r)}static async findAssetByBnameImageHashes(e,n){if(!isVec0Available()||!(e.capturedAtSrc!==`tags`||localIsFuzzy(e.capturedAtLocal)))return;let r=shortestBname(e.basename);if(blank(r))return;let a=Settings2.imageHashMatchK.valueOrDefault,o=Settings2.maxContemporaryAdoptionAssets.valueOrDefault;return this.#i(e,a,o,n,void 0,r,`bnameImageHash`)}static async#i(e,n,r,a,o,s,c=`imageHash`){if(!isVec0Available())return;let{rejectedAssetIds:l}=a,u=hashRecordToLHashHex(e);if(u==null){logger138().debug(`Missing hashes for hamming distance search`,{assetFileId:e.id});return}let d=192,f=Math.max(Settings2.imageHashRelaxedThresholdPct.valueOrDefault+20,60),h=Math.floor(192*(100-f)/100),_=[{hex:u,source:`HashRecord`}],y=hashRecordToLHashHex(hashRecord0ToHashRecord(e));y!=null&&y!==u&&_.push({hex:y,source:`HashRecord0`});let x=e.capturedAtSrc!==`tags`||localIsFuzzy(e.capturedAtLocal);for(let{hex:u,source:d}of _)try{assertLHashHex(u);let f=blank(s)?``:` AND bname = :bname`,_=blank(s)?{}:{bname:s},y=[];if(o!=null&&!x){let r=`
|
|
724
|
+
SELECT assetFileId, distance
|
|
725
|
+
FROM AssetFileHash
|
|
726
|
+
WHERE lHash MATCH vec_bit(X'${u}')
|
|
727
|
+
AND k = :matchK
|
|
728
|
+
AND distance <= :maxHammingDistance
|
|
729
|
+
AND capturedAtLocal BETWEEN :boundsStart AND :boundsEnd
|
|
730
|
+
${f}
|
|
731
|
+
ORDER BY distance
|
|
732
|
+
`,a=Asset.dbl.all({sql:r,bindings:{matchK:n,maxHammingDistance:h,boundsStart:o.start,boundsEnd:o.end,..._}}),s=`
|
|
733
|
+
SELECT assetFileId, distance
|
|
734
|
+
FROM AssetFileHash
|
|
735
|
+
WHERE lHash MATCH vec_bit(X'${u}')
|
|
736
|
+
AND k = :matchK
|
|
737
|
+
AND distance <= :maxHammingDistance
|
|
738
|
+
AND capturedAtFuzzy = 1
|
|
739
|
+
${f}
|
|
740
|
+
ORDER BY distance
|
|
741
|
+
`,c=Asset.dbl.all({sql:s,bindings:{matchK:n,maxHammingDistance:h,..._}}),l=new Map;for(let e of[...a,...c]){let n=l.get(e.assetFileId);(n==null||e.distance<n)&&l.set(e.assetFileId,e.distance)}y=Array.from(l.entries()).map(([e,n])=>({assetFileId:e,distance:n})).sort((e,n)=>e.distance-n.distance).slice(0,n),logger138().debug(`Phase 1 with metadata filtering`,{assetFileId:e.id,boundedCount:a.length,fuzzyCount:c.length,combinedCount:y.length,bounds:o,orphanIsFuzzy:x,source:d})}else{let r=`
|
|
742
|
+
SELECT assetFileId, distance
|
|
743
|
+
FROM AssetFileHash
|
|
744
|
+
WHERE lHash MATCH vec_bit(X'${u}')
|
|
745
|
+
AND k = :matchK
|
|
746
|
+
AND distance <= :maxHammingDistance
|
|
747
|
+
${f}
|
|
748
|
+
ORDER BY distance
|
|
749
|
+
`;y=Asset.dbl.all({sql:r,bindings:{matchK:n,maxHammingDistance:h,..._}}),o!=null&&x&&logger138().debug(`Phase 1 without filtering (orphan is fuzzy)`,{assetFileId:e.id,rowCount:y.length,orphanIsFuzzy:x,source:d})}if(y.length===0)continue;let C=y.map(e=>e.assetFileId),w={assetFileIds:JSON.stringify(C)},T=l!=null&&l.size>0?` AND af.assetId NOT IN ${sqlWhereInJsonClauseNamed(`rejectedAssetIds`)}`:``;l!=null&&l.size>0&&(w.rejectedAssetIds=JSON.stringify(Array.from(l))),w.limit=r;let E=`
|
|
750
|
+
SELECT DISTINCT af.assetId
|
|
751
|
+
FROM AssetFile af
|
|
752
|
+
WHERE af.id IN ${sqlWhereInJsonClauseNamed(`assetFileIds`)}
|
|
753
|
+
AND af.assetId IS NOT NULL
|
|
754
|
+
${T}
|
|
755
|
+
LIMIT :limit
|
|
756
|
+
`,D=Asset.dbl.all({sql:E,bindings:w}).map(e=>e.assetId);if(D.length>0){logger138().debug(`Found candidates by hamming distance (MATCH)`,{assetFileId:e.id,phase1Count:y.length,candidateCount:D.length,matchK:n,maxHammingDistance:h,bname:s,source:d});let r=await this.validateCandidates(e,D,a,c);if(r!=null)return r}}catch(n){logger138().debug(`Hamming distance MATCH query failed`,{assetFileId:e.id,source:d,error:n})}logger138().debug(`No candidate Assets found by hamming distance (MATCH)`,{assetFileId:e.id,queriedHashes:_.length})}static async validateCandidates(e,n,r,a){let{rejectedAssetIds:o}=r,s=Asset.ops().findByIds(n),c=s.map(e=>e.id).filter(gt0);if(c.length>0){let e=AssetFile.ops().allf(e=>e.whereIn(`assetId`,c).orderBy(`id`));for(let n of s){let r=e.filter(e=>e.assetId===n.id);sortAssetFilesInPlace(r);for(let e of r)e.$asset=n;n.assetFiles=r}}for(let n of seedShaOrder(s)){let s=n.id;if((n.getPrimary()??(r.readOnly===!0?n.getAssetFiles()[0]:n.getOrSetPrimary()))==null){logger138().debug(`Candidate Asset has no files, skipping`,{assetId:s,strategy:a});continue}let c=n.getAssetFiles(),l=!1;for(let n of c)if(whyNotSimilarMedia(e,n)==null){l=!0;break}if(!l){logger138().debug(`Doesn't match any file (single-link gate)`,{assetFileId:e.id,candidateAssetId:s,fileCount:c.length,strategy:a}),o?.add(s);continue}let u=clusterShaGroups([...c,e]),d=u?.survivors??[];if(d.some(n=>n===e))return logger138().debug(`Would survive revalidation`,{assetFileId:e.id,matchedAssetId:s,survivorCount:d.length,totalTentative:d.length+(u?.evicted.length??0),strategy:a}),n;logger138().debug(`Would not survive revalidation`,{assetFileId:e.id,candidateAssetId:s,survivorCount:d.length,strategy:a}),o?.add(s)}}};async function removeProblematicAssetFiles(e,n,r){let a=e.id,o=e.getAssetFiles();await resolveNativePaths(o);let s=[],c=[];for(let e of o){let o=e.posixFile()?.nativePath;if(o!=null&&ProblematicFile.isProblematic(o)){c.push(e.id),s.push(o);let l=ProblematicFile.getStrikeCount(o);r.info(`Removing problematic AssetFile`,{assetId:a,assetFileId:e.id,path:o,strikeCount:l}),syncReport().onProgress({path:o,type:`file`,state:SyncFileStates.excluded,from:n,details:`Removed due to ${plur(l,`strike`)} from prior timeouts`})}}if(c.length===0)return{removedCount:0,removedPaths:[],remainingFiles:o,assetDeleted:!1};let l=AssetFile.db().db;AssetFile.dbl.txn(()=>{for(let e of c)deleteAssetFileHash(l,e);AssetFile.dbl.runf(e=>e.whereIn(`id`,c).delete())}),r.info(`Removed problematic AssetFiles`,{assetId:a,removedCount:c.length,removedPaths:s});let u=e.getAssetFiles({refresh:!0});return u.length===0?(r.info(`Asset has no files after removing problematic ones, deleting`,{assetId:a}),await Asset.dao.remove({assetId:a,blocklistShas:!1,unlinkAssetFiles:!1}),{removedCount:c.length,removedPaths:s,remainingFiles:[],assetDeleted:!0}):{removedCount:c.length,removedPaths:s,remainingFiles:u,assetDeleted:!1}}var logger139=defer(()=>mkLogger(`sync.ValidateAssetSiblings`));function revalidateAssetSiblings(e,n){let r=logger139(),a=Asset.ops().findById(e);if(a==null)return;let o=a.getAssetFiles({refresh:!0});if(o.length===0)return;let s=clusterShaGroups(o);if(s==null)return;let{survivors:c,evicted:l,groupDecisions:u}=s;for(let{group:a,why:o,survivorCount:s}of u){let c=a[0];r.debug(`revalidateAssetSiblings: similarity check`,{assetId:e,groupUri:c.uri,groupSize:a.length,similar:o==null,survivorCount:s,reason:o,caller:n}),o!=null&&syncReport().onProgress({from:n,path:c.posixFile()?.nativePath??c.uri,type:`file`,state:`note`,details:`Evicting SHA group containing AssetFile:${c.id} from Asset:${e}: non-similar`,meta:{why:o,caller:n}})}let d=l.map(e=>e.id).filter(gt0);return d.length>0&&AssetFile.dao.orphan(...d),{evicted:l,survivors:c}}async function validateAssetSiblings(e){let n=performance.now(),{assetId:r}=e,a=logger139().child(`.validateAssetSiblings(Asset:${r})`),o=getTaskAbortable(e);o!=null&&(a.abortable=o);let s=Asset.ops().findById(r);if(s==null){a.warn(`Asset not found during validation`,{assetId:r});return}let{assetDeleted:c,removedCount:l}=await removeProblematicAssetFiles(s,`validateAssetSiblings`,a);if(c)return{assetId:r,filesOrphaned:l,totalFiles:l};let u=revalidateAssetSiblings(r,`validateAssetSiblings`);if(u==null)return a.warn(`validateAssetSiblings: no valid files after revalidation, removing asset`,{assetId:r}),await Asset.dao.remove({assetId:r,blocklistShas:!1,unlinkAssetFiles:!0}),{assetId:r,filesOrphaned:0,totalFiles:0};let{survivors:d,evicted:f}=u,h=f.length,_=d[0];if(a.info(`validateAssetSiblings: revalidation complete`,{assetId:r,survivorCount:d.length,orphanedCount:h,primaryUri:_.uri}),await maybeDissolveDuplicate(s,_,d))return h>0&&syncReport().onProgress({from:`validateAssetSiblings`,path:_.posixFile()?.nativePath??_.uri,type:`file`,state:`note`,details:`Asset ${r}: orphaned ${h} non-similar siblings before dissolving`,url:assetPath(r)}),{assetId:r,filesOrphaned:h+d.length,totalFiles:d.length+f.length,dissolved:!0};Asset.dao.clearFlag(r,`validateSiblings`),e.skipFinalizeScheduling!==!0&&Asset.dao.scheduleFinalizeAsset(r);let y=d.length+f.length;return syncReport().onProgress({from:`validateAssetSiblings`,path:_.posixFile()?.nativePath??_.uri,type:`file`,state:`note`,details:`Asset ${r}: validated ${y} files`,url:assetPath(r),elapsedMs:performance.now()-n,meta:{orphaned:h}}),{assetId:r,filesOrphaned:h,totalFiles:y}}async function maybeDissolveDuplicate(e,n,r){let a=logger139(),o=e.id,s=await AssetMatcher.findMatchingAsset(n,{rejectedAssetIds:new Set([o])});return s==null||!gt0(s.asset.id)?!1:(a.info(`Dissolving duplicate asset`,{assetId:o,matchAssetId:s.asset.id,matchedBy:s.matchedBy,fileCount:r.length}),AssetFile.dao.orphan(...r.map(e=>e.id)),await Asset.dao.remove({assetId:o,blocklistShas:!1,unlinkAssetFiles:!1}),syncReport().onProgress({from:`validateAssetSiblings`,path:n.posixFile()?.nativePath??n.uri,type:`file`,state:`note`,details:`Asset ${o}: dissolved into asset ${s.asset.id} (matched by ${s.matchedBy}), ${r.length} files orphaned`,url:assetPath(s.asset.id)}),!0)}var logger140=defer(()=>mkLogger(`sync.AdoptAssetFile`));async function adoptAssetFile(e){let{assetFileId:n}=e,r=logger140(),a=AssetFile.ops().findById(n);if(a==null){r.warn(`Orphan AssetFile not found`,{assetFileId:n});return}if(gt0(a.assetId)){r.debug(`AssetFile already has assetId, skipping`,{assetFileId:n,assetId:a.assetId});return}let o=await AssetMatcher.findOrCreateAsset(a),s=0;if(!o.created){a.assetId=o.asset.id,a.isPrimary=!1,a.upsert();let e=revalidateAssetSiblings(o.asset.id,`adoptAssetFile`);e!=null&&e.evicted.length>0&&(s=e.evicted.length,r.info(`Post-adoption revalidation evicted siblings`,{assetId:o.asset.id,evictedCount:s,evictedUris:e.evicted.map(e=>e.uri)}))}r.info(`Adopted orphan AssetFile`,{assetFileId:a.id,assetId:o.asset.id,created:o.created,matchedBy:o.matchedBy});let c=o.created||o.matchedBy!==`sha`?`not a SHA match to an existing asset`:await whyNotPathTagsOnlyAdoption(a,o.asset,s);c==null?setFinalizePathTagsFlagAndNotify(o.asset.id):(r.info(`adoptAssetFile(): full finalize`,{assetFileId:a.id,assetId:o.asset.id,whyNotPathTagsOnly:c}),setFinalizeFlagAndNotify(o.asset.id));let l=a.uri;try{l=a.nativePath}catch(e){r.warn(`Could not resolve adopted AssetFile path; reporting its URI`,{assetFileId:a.id,assetId:o.asset.id,uri:l,error:e})}try{syncReport().onProgress({path:l,from:`adoptAssetFile`,type:`file`,state:`note`,details:o.created?`Created new asset (matched by: ${o.matchedBy})`:`Matched to existing asset #${o.asset.id} (matched by: ${o.matchedBy})`,meta:{assetFileId:a.id,assetId:o.asset.id,created:o.created,matchedBy:o.matchedBy,whyNotPathTagsOnly:c},url:assetPath(o.asset.id)})}catch(e){r.warn(`Could not report adopted AssetFile`,{assetFileId:a.id,assetId:o.asset.id,path:l,error:e})}return{assetId:o.asset.id,created:o.created,matchedBy:o.matchedBy,whyNotPathTagsOnly:c}}var PATH_TAGS_ONLY_ROW_FIELDS=[`mimetype`,`rating`,`capturedAtLocal`,`capturedAtSrc`,`capturedAtPrecisionMs`,`metadataDate`,`width`,`height`,`rotation`];function rowMetadataMatches(e,n){return PATH_TAGS_ONLY_ROW_FIELDS.every(r=>(e[r]??null)===(n[r]??null))}function distinctShaOrder(e){let n=[],r=new Set;for(let a of sortAssetFilesInPlace([...e]))r.has(a.sha)||(r.add(a.sha),n.push(a.sha));return n}async function whyNotPathTagsOnlyAdoption(e,n,r){try{if(r>0)return`revalidation evicted siblings`;if(n.shown!==!0)return`asset not shown`;for(let e of PathTagsOnlyBlockingAssetFlags)if(n.hasFlag(e))return`asset has pending ${e}`;if(n.isVideo())return`video asset`;let a=n.getAssetFiles({refresh:!0}),o=a.find(n=>n.id!==e.id&&n.sha===e.sha);if(o==null)return`no same-SHA twin row`;if(!rowMetadataMatches(e,o))return`row metadata differs from twin`;if(await mayCopyAssetsToLibrary()){let n=!1;for(let r of a)if(r.sha===e.sha&&r.isInLibrary()&&await r.exists_()){n=!0;break}if(!n)return`no library replica of this SHA`}let s=a.find(e=>e.isPrimary);if(s==null)return`no current primary`;let c=sortAssetFilesInPlace([...a]),l=c[0];if(l?.id!==s.id)return`new head-of-sort (AssetFile:${l?.id} over primary AssetFile:${s.id})`;let u=distinctShaOrder(a.filter(n=>n.id!==e.id)),d=distinctShaOrder(c);if(u.length!==d.length||u.some((e,n)=>e!==d[n]))return`content variation order changed`;if(await s.resolveNativePath_(),await e.resolveNativePath_(),!0!==await s.posixFile_().exists())return`primary not readable`;for(let e of a){let n=await e.whyNeedsUpsert();if(n!=null)return`${e.id===s.id?`primary`:`AssetFile:${e.id}`} ${n}`}let f=e.posixFile_();if(Settings2.tagKeywordsFromPath.valueOrDefault&&extractPathnameTags(f).length>0)return`path contributes dash-dash keywords`;if((await f.existingSidecars()).length>0)return`sidecar present`;if((await f.existingDirectorySidecars()).length>0)return`directory sidecar present`;for(let e of Settings2.tagAlbumFilenames.values)if(!0===await f.sibling(e).exists())return`album file present (${e})`;return}catch(r){return logger140().warn(`whyNotPathTagsOnlyAdoption() failed; using a full finalize`,{assetFileId:e.id,assetId:n.id,error:r}),`eligibility probe failed: `+r}}function setFinalizePathTagsFlagAndNotify(e){Asset.dbl.runf(n=>n.where(`id`,e).update({flags:knex().raw(`COALESCE(Asset.flags, 0) | ?`,[AssetFlags.toBit(`finalizePathTags`)]),updatedAt:Date.now()})),ee().emitThrottled(`notifyWorkAvailable`,`finalizeAsset`)}function setFinalizeFlagAndNotify(e){let n=AssetFlags.toBit(`finalize`),r=AssetFlags.toBit(`failedFinalize`);Asset.dbl.runf(a=>a.where(`id`,e).update({flags:knex().raw(`(COALESCE(Asset.flags, 0) | ?) & ~?`,[n,r]),updatedAt:Date.now()})),ee().emitThrottled(`notifyWorkAvailable`,`finalizeAsset`)}var AdoptAssetFileProducer=class e extends BaseTaskProducer{static instance=lazy(()=>new e);constructor(){super(`AdoptAssetFileProducer`,`adoptAssetFile`)}runnable(){return assetFileHashReadyForMatching()&&super.runnable()}queryIds(e,n){let r=AssetFile.query().join(`DirUri`,`DirUri.id`,`AssetFile.dirUriId`).whereNull(`AssetFile.assetId`).orderByRaw(`${patternSortOrderCase(`mimetype`,AggregationSettings.assetVariationMimetypeSortOrder.values)}, DirUri.uri, AssetFile.basename`).limit(e).select(`AssetFile.id`);return n.size>0&&(r=r.whereNotIn(`AssetFile.id`,[...n])),r=this.excludeUnavailable_(r,`AssetFile.id`),AssetFile.dbl.pluckAll(r)}async mkTask(e){let n=AssetFile.ops().findById(e);n??this.logger.throw(`Orphan AssetFile not found`,{assetFileId:e});let r;try{r=await n.resolveNativePath_()}catch(r){let a=isInvalidURIError(r);throw this.logger.warn(`mkTask(): could not resolve this orphan`,{assetFileId:e,quarantined:a,error:r}),a?this.onTaskConstructionFailed(e):this.onTaskDeferred(e,Date.now()+minuteMs,n.uri),this.reportTaskConstructionFailure(r,{path:n.uri,url:assetPath(n.assetId)}),r}return{method:`adoptAssetFile`,args:r==null?{assetFileId:e}:{assetFileId:e,path:r}}}onNewOrphan(e){this.notifyWorkAvailable()}onUpdatedAssetFile(e){let n=AssetFile.ops().findById(e)?.assetId;gt0(n)&&setFinalizeFlagAndNotify(n)}async recoverOrphans(){let n=e.orphanCount();n>0&&(this.logger.info(`Recovering ${n} orphan AssetFiles from interrupted sync`),syncReport().onProgress({from:`AdoptAssetFileProducer.recoverOrphans`,state:`note`,details:`Recovering ${n} orphan AssetFiles from interrupted sync`}),this.notifyWorkAvailable())}static orphanCount(){return AssetFile.ops().count(AssetFile.query().whereNull(`assetId`).count())}},import_node_path67=require("node:path"),TestDelayPattern=/delay_(\d+)\./,TestTimeoutPattern=/timeout_(\d+)\./,testDelayOverride;async function maybeDelayIfNotProd(e){if(isProd()||isPacked())return;let n=(0,import_node_path67.basename)(e),r=n.match(TestTimeoutPattern);if(r!=null){let e=parseInt(r[1],10);if(e>0)throw await delay(e*secondMs),new TimeoutError(`Test timeout triggered for ${n} after ${e}s`)}let a=n.match(TestDelayPattern);if(a!=null){let n=parseInt(a[1],10);n>0&&(testDelayOverride==null?await delay(n*secondMs):await testDelayOverride(e))}}function maybeThrowTestFinalizeError(e){if(isProd()||isPacked())return;let n=process.env.PS_TEST_FINALIZE_ERROR;if(n!=null&&e.includes(n))throw Error(`Test finalize error triggered for ${(0,import_node_path67.basename)(e)}`)}function differsStructurally(e,n){try{let r=toURI(e),a=toURI(n);return r.scheme!==a.scheme||r.authority!==a.authority||r.scheme===PS_LIBRARY_SCHEME&&r.path.normalize(`NFC`)!==a.path.normalize(`NFC`)}catch{return!1}}function findAssetFileByUri(e){if(blank(e))return;let n=toURI(e),r=extractUriDirectory_(n),a=extractUriBasename_(n),o=DirUri.ops().findOneBy({uri:r});if(o!=null)return AssetFile.ops().findOneBy({dirUriId:o.id,basename:a})}async function findVariantRow(e,n){let r=findAssetFileByUri(e);return r==null||r.uriObject?.scheme!==PS_LIBRARY_SCHEME||await uriIsEquivalent(r.uri,n)?r:void 0}var AssetFileFinder=class{constructor(e,n=forceContextOrSetting()){this.file=e,this.ctx=n,this.#e=mkLogger(`sync-file.AssetFileFinder(`+e.baseWithGrandparent+`)`)}file;ctx;start=performance.now();#e;set abortable(e){this.#e.abortable=e}async prior(){let e=findAssetFileByUri(await this.file.uri_());if(e!=null)return e;for(let e of await nativePathToUriStrings(this.file.nativePath)){let n=await findVariantRow(e,this.file.fileuri());if(n!=null)return n}}async canonicalize_(e){let n=await this.file.uri_(),r=differsStructurally(e.uri,n)&&await uriIsEquivalent(e.uri,n)?await e.upgradeUri(n):e;return r.dirUri?.rememberNativePath_(this.file.dir),r}mediaInfo=defer(()=>MediaInfoFactory.for(this.file));newAssetFile_=defer(async()=>{let{uri:e,...n}=await this.mediaInfo().asMediaInfo_(),r=new AssetFile;return e!=null&&r.setUri(e,this.file.dir),r.update(n),r});apply_=timedLazy({name:`sync.assetFileFinder`,thunk:async()=>{let e=await this.file.uri_();if(blank(e))throw Error(`Cannot import, file URI is blank for `+this.file);let n=await this.prior();if(n!=null){this.#e.info(`Previously imported`,{uri:e});let r=await this.canonicalize_(n);return await r.upsertIfNeeded_()??r}this.#e.throwIfAborted_();let r=await this.newAssetFile_();return r.assetId=void 0,r.$syncState=AssetFileSyncStates.imported,r.upsert()}})},toolChangesHealthCheck=defer(()=>HealthCheck.for({section:`Tools`,id:`tools-changes`,pendingMsg:`Checking that FFmpeg responds…`,evalMode:`local`,later:async()=>{let e=toolProbeTimeout();return e==null?{level:`ok`,msg:`Sync is not stopped for an unanswered tool check`}:{level:`stop-sync`,msg:[`FFmpeg did not report its version in time`,codeLines(errorToS2(e)),`This usually means this computer is overloaded. Sync is stopped, and checks again every minute.`]}}}));function refreshToolChangesHealthCheck(){let e=toolChangesHealthCheck();e.reset(),e.result()}var ReprobeIntervalMs=minuteMs,probeTimeout,reprobeTimer,reprobed=new Latch;function recordToolProbeResult(e){let n=isTimeoutError(e)?e:void 0;n!==probeTimeout&&(probeTimeout=n,n??(clearTimeout(reprobeTimer),reprobeTimer=void 0),scheduleReprobe(),wakeWaiters(),refreshToolChangesHealthCheck())}function scheduleReprobe(){probeTimeout!=null&&(reprobeTimer??=setUnrefTimeout(()=>void reprobe(),ReprobeIntervalMs))}function wakeWaiters(){let e=reprobed;reprobed=new Latch,e.resolve()}function toolProbeTimeout(){return probeTimeout}async function probe(){try{await getFfmpegToolDetails_(),recordToolProbeResult(void 0)}catch(e){recordToolProbeResult(e)}}async function reprobe(){clearTimeout(reprobeTimer),reprobeTimer=void 0,await ee().emit(`clearToolCache`),await probe(),scheduleReprobe(),wakeWaiters()}async function probeTimedOut(){return await awaitOutsideDeadline(probe()),probeTimeout!=null}async function awaitProbeAfterTimeout(){for(;probeTimeout!=null;)await awaitOutsideDeadline(reprobed)}function needsTools(e){return isVideoMimeType(e)||!isMac&&isHeifMimeType(e)}async function awaitToolProbeFor(e){await probeTimedOut()&&needsTools(await readMimeType(e))&&await awaitProbeAfterTimeout()}async function awaitToolProbeForAsset(e){await probeTimedOut()&&AssetFile.ops().allf(n=>n.where({assetId:e})).some(e=>needsTools(e.mimetype))&&await awaitProbeAfterTimeout()}async function importFileToResult_(e){let n=e.path;if(ProblematicFile.isProblematic(n)){let e=ProblematicFile.getStrikeCount(n),r=ProblematicFile.getLastStrike(n),a=r==null?``:` (last: ${new Date(r.timestamp).toISOString()} - ${r.reason})`,o=`Skipped: ${plur(e,`strike`)} from previous timeouts${a}`;return syncReport().onProgress({from:`AssetFileImporter`,path:n,type:`file`,state:SyncFileStates.excluded,details:o}),{path:n,state:SyncFileStates.excluded,details:o}}let r=Library.instanceRequired_();return syncReport().wrap_({path:n,from:`AssetFileImporter`,type:`file`,fn_:()=>new AssetFileImporter(PosixFile.for(n),r.assetFileRepository(),e).apply_()})}var AssetFileImporter=class{constructor(e,n,r){this.file=e,this.repo=n,this.ctx=forceContextOrSetting(r),this.#e=mkLogger(`sync-file.`+this.toString()),this.#t=new AssetFileFinder(e,this.ctx),this.#t.abortable=this.#e.abortable}file;repo;#e;#t;ctx;#n=0;toString(){return`AssetFileImporter(`+this.file.nativePath+`)`}newAssetFile(){return this.#t.newAssetFile_()}whyRejected=lazy2(async()=>{let e=[];if(await this.file.uriObject_()==null)e.push(`Cannot make URI: `+(await whyUriUnmintable(this.file)??``)+DoNotSendErrorFlag+NonRetriableErrorFlag);else{let n=await this.prior();if(await n?.isUriDeleted()===!0)e.push(`File was deleted`);else{await awaitToolProbeFor(this.file);let r=n!=null&&AssetFileFlags.has(n.flags??0,`forceFilters`),a=this.ctx.forceFilters||r;if(!a){let n=await RejectedFile.findRejectedFile_(this.file);if(n!=null)return this.#e.info(`whyRejected(): using cached rejection`,{why:n.why,cachedAt:new Date(n.updatedAt).toISOString(),nativePath:this.file.nativePath}),e.push(n.why),e}if(a||n==null){let a=performance.now(),o=await whyFileRejected({file:this.file,forceFilters:!0});o!=null&&(e.push(o),this.#n=performance.now()-a),r&&n.id!=null&&(AssetFile.dbl.runf(e=>AssetFileFlags.update({qb:e.where(`id`,n.id),flag:`forceFilters`,isSet:!1})),this.#e.debug(`Cleared forceFilters flag`,{assetFileId:n.id,nativePath:this.file.nativePath}))}}if(this.#e.throwIfAborted_(),e.length===0&&(n==null||!await n.inSyncWithFile())){let n=performance.now(),r=await validateFile(this.file.nativePath);syncReport().onProgress({from:`AssetFileImporter.validate`,path:this.file.nativePath,type:`file`,state:`validated`,details:fileValidationToS(r)}),r.validity===`invalid`?(e.push(r.why),this.#n=performance.now()-n):r.validity===`unchecked`&&this.#e.debug(`whyRejected(): file contents were not validated`,{nativePath:this.file.nativePath,why:r.why})}isNotEmpty(e)&&n!=null&&(this.#e.info(`whyRejected(): removing rejected asset file`,{why:e,prior:n}),await n.remove())}return e});assetFile_=lazy2(async()=>await this.#t.apply_());prior=lazy2(async()=>{let e=await this.#t.prior();return e?.dirUri?.rememberNativePath_(this.file.dir),e});apply_=lazy2(()=>this.#r());async#r(){await maybeDelayIfNotProd(this.file.nativePath),this.#e.throwIfAborted_();let e=await this.#e.tapAsync_({msg:`whyRejected`,result:this.whyRejected()});if(isNotEmpty(e)){let n=e.join(`, `),r=Settings2.rejectedFileCacheThresholdMs.valueOrDefault,a=this.#n;if(!this.ctx.forceFilters&&r>0&&a>=r&&await this.file.isReadable())try{await RejectedFile.addRejectedFile_(this.file,n),this.#e.info(`Cached rejection for future syncs`,{elapsedMs:a,thresholdMs:r})}catch(e){this.#e.warn(`Failed to cache rejection`,{error:e})}return{path:this.file.nativePath,state:SyncFileStates.excluded,details:n}}this.#e.throwIfAborted_();let n=await this.#e.tapAsync_({msg:`prior()`,result:this.prior(),timeoutMs:Settings2.taskTimeoutMs.valueOrDefault}),r=n==null?void 0:await this.#t.canonicalize_(n);if(r!=null&&await r.inSyncWithFile(this.ctx))return this.ctx.scanGeneration!=null&&AssetFile.dbl.runf(e=>e.where(`id`,r.id).update({lastVisitedGeneration:this.ctx.scanGeneration})),AssetFileFlags.has(r.flags,`contentChanged`)&&AdoptAssetFileProducer.instance().onUpdatedAssetFile(r.id),r.$syncState=SyncFileStates.unchanged,{path:this.file.nativePath,state:`unchanged`,assetFileId:r.id,assetFile:r};this.#e.throwIfAborted_();let a=await this.#e.tapAsync_({msg:`assetFile()`,result:this.assetFile_()});if(a==null)return this.#e.throw(`_apply(): unexpected null assetFile`);let o=a.id;if(o==null)return this.#e.throw(`_apply(): unexpected null assetFileId`);if(a.uri==null)return this.#e.throw(`_apply(): unexpected null assetFile.uri`);await this.#e.tapAsync_({msg:`assetFile.upsertIfNeeded_()`,result:a.upsertIfNeeded_()}),this.ctx.scanGeneration!=null&&AssetFile.dbl.runf(e=>e.where(`id`,o).update({lastVisitedGeneration:this.ctx.scanGeneration})),this.#e.throwIfAborted_(),a.assetId==null?(AdoptAssetFileProducer.instance().onNewOrphan(o),this.#e.info(`Created orphan AssetFile, notifying AdoptAssetFileProducer`,{assetFileId:o})):(AdoptAssetFileProducer.instance().onUpdatedAssetFile(o),this.#e.info(`Updated AssetFile with existing asset, notifying AdoptAssetFileProducer`,{assetFileId:o,assetId:a.assetId}));try{await RejectedFile.removeRejectedFile_(this.file)}catch{}return{path:this.file.nativePath,state:r==null?`imported`:`updated`,assetFileId:o,assetFile:a}}},logger141=defer(()=>mkLogger(`sync-file.UpdateAssetFile`));function getAssetFile_(e){return`af`in e?e.af instanceof AssetFile?e.af:logger141().throw(`Invalid cmd: missing af: AssetFile`,{cmd:e}):`assetFileId`in e?gt0(e.assetFileId)?AssetFile.ops().findById(e.assetFileId)??logger141().throw(`Invalid cmd: db missing AssetFile`,{cmd:e}):logger141().throw(`Invalid cmd: invalid assetFileId`,{cmd:e}):logger141().throw(`Invalid cmd: missing af or assetFileId`,{cmd:e})}async function updateAssetFile_(e){let n=performance.now(),r=getAssetFile_(e),a=r.id,o=mkLogger(`updateAssetFile(${r.id})`),s=`unavailableAtAdmission`in e&&e.unavailableAtAdmission===!0,c=toNotBlank(e.path),l=s?void 0:await r.resolveNativePath_(),u=c!=null&&l!=null&&c!==l,d=s||u?void 0:l??c,f=forceContextOrSetting(e),h={id:a,assetFileId:a,path:d??c,uri:r?.uri};if(d==null)return o.info(`no-op: file path is unavailable under its task lock`,h),syncReport().onProgress({path:r.uri,elapsedMs:roundMs(performance.now()-n),from:`updateAssetFile_()`,type:`file`,details:u?`share mount changed after task admission`:`cannot resolve URI to nativePath`,state:SyncFileStates.unavailable}),clearForceUpdate(r),{...h,skipped:!0};let _=PosixFile.for(d),y=await r.isUriDeleted();if(y==null)return o.info(`no-op: file URI points to an unmounted volume`,h),syncReport().onProgress({path:_.nativePath,elapsedMs:roundMs(performance.now()-n),from:`updateAssetFile_()`,type:`file`,state:SyncFileStates.unavailable}),clearForceUpdate(r),{...h,skipped:!0};y===!1&&e.whyReject==null&&await awaitToolProbeFor(_);let x=e.whyReject??(y===!0?`deleted`:await r.whyRejected(f));if(y||!blank(x)){let e={...h,rejected:x,deleted:y};return o.info(`file was deleted or rejected. Deleting.`,e),syncReport().onProgress({path:_.nativePath,elapsedMs:roundMs(performance.now()-n),from:`updateAssetFile_()`,type:`file`,details:y?`file no longer exists`:`rejected: `+x,state:y?SyncFileStates.absent:SyncFileStates.deleted}),await r.remove(),f.skipAssetRepair!==!0&&r.assetId!=null&&(Asset.dbl.runf(e=>AssetFlags.update({qb:e,flag:`validateSiblings`,isSet:!0}).where(`id`,r.assetId)),ee().emitThrottled(`notifyWorkAvailable`,`validateAssetSiblings`)),e}let C=await _.uri_();if(!await uriIsEquivalent(C,r.uri)){let e=await handleAssetFileUriChange(r,C,f);if(e!=null)return{...h,...e}}if(clearForceUpdate(r),!f.forceSync&&await r.whyNeedsUpsert()==null){o.info(`no-op: file already matches db record`,h);let e={updatedAt:Date.now()};return f.scanGeneration!=null&&(e.lastVisitedGeneration=f.scanGeneration),AssetFile.dbl.runf(n=>n.where(`id`,r.id).update(e)),{...h,skipped:!0}}return{...h,...await updateAssetFileIfNeeded(r,f)}}function clearForceUpdate(e){AssetFileFlags.has(e.flags??0,`forceUpdate`)&&(e.clearFlag(`forceUpdate`),AssetFile.dbl.runf(n=>AssetFileFlags.update({qb:n.where(`id`,e.id),flag:`forceUpdate`,isSet:!1})))}async function handleAssetFileUriChange(e,n,r){let a=mkLogger(`handleAssetFileUriChange(${e.id})`),o=uniq([...uriEncodingVariants(e.uri),...uriEncodingVariants(n)]);a.warn(`URI is changing. Avoiding duplicate keys.`,{priorUri:e.uri,variants:o});let s=uniqBy(compact(o.map(findAssetFileByUri)).filter(n=>n.id!==e.id),e=>e.id);if(isNotEmpty(s)){a.warn(`Found other AssetFiles with equivalent URIs.`,{afIds:s.map(e=>e.id)});let n=[e,...s],c=sortAssetFilesInPlace(n);if(isEmpty(c))return a.warn(`sortAssetFiles returned undefined`,{arr:n.map(e=>pick(e,`id`,`uri`)),variants:o}),{error:`sortAssetFiles returned undefined`};let l=n.map(e=>e.id);for(let e of c)if(await e.exists_()){AssetFile.dbl.runf(n=>n.whereIn(`id`,l.filter(n=>n!==e.id)).delete());let a=updateAssetFileIfNeeded(e,r);return Asset.dbl.runf(e=>AssetFlags.update({qb:e.whereIn(`id`,uniq(n.map(e=>e.assetId))),flag:`validateSiblings`,isSet:!0})),ee().emitThrottled(`notifyWorkAvailable`,`validateAssetSiblings`),a}}a.info(`no-op, no duplicate URIs.`)}async function updateAssetFileIfNeeded(e,n){let r=performance.now();return await e.upsertIfNeeded_(void 0,n)!=null&&e.assetId!=null&&(Asset.touch([e.assetId]),n.skipAssetRepair!==!0&&Asset.dao.scheduleFinalizeAsset(e.assetId)),syncReport().onProgress({path:e.nativePath,elapsedMs:roundMs(performance.now()-r),from:`updateAssetFileIfNeeded()`,type:`file`,state:e.$syncState??SyncFileStates.unknown,url:assetPath(e.assetId)}),{assetFileId:e.id}}var import_luxon14=require("luxon");function parseJsonDateToMillis(e){if(e==null)return;let n=isString(e)?e:e.formatted;return(isObject(e)&&isNumber(e.timestamp)?toValidMillis(e.timestamp*secondMs):void 0)??parseDateTime(n)?.toMillis()}var logger142=lazy2(()=>mkLogger(`curators.AlbumTagger`));async function tagFilesWithAlbums(e){let n=[];for(let r of e){n.push(...albumsFromTags(await readTags(r)));for(let e of Settings2.tagAlbumFilenames.values)n.push(...albumsFromTags(await readRawTags(r.sibling(e))))}return logger142().tap({msg:`tagFilesWithAlbums()`,result:uniqTagPaths(n),meta:{files:e}})}function albumNameToPath(e){return blank(e)?void 0:Settings2.tagAlbumTitleHierarchies.valueOrDefault?keywordToPath(e):[e]}function albumsFromTags(e){if(e==null)return[];let n=compact(uniq(flatMap(Settings2.tagAlbumTitle.values,n=>pluckDeep(e,n)?.value)).map(albumNameToPath));if(isEmpty(n))return[];if(n.length>1)return logger142().tap({level:`info`,msg:`albumFromFile()`,result:n.map(e=>[TagRoots.Albums,...e])});let r=n[0],a=mapNotBlank(first(Settings2.tagAlbumDescription.values,n=>pluckDeep(e,n)?.value),e=>e.trim()),o=isEmpty(r)?`(blank title)`:firstSubstringIgnoreCase(Settings2.tagAlbumsExcluded.values,[...r,toS(a)].join(` `)),s=o==null?[TagRoots.Albums,...r]:void 0;if(s!=null){let n=a;n!=null&&hasEncodingCorruption(n)&&(logger142().info(`albumsFromTags(): dropping corrupt album description`,{description:n}),n=void 0);let r={name:s[s.length-1],...blank(n)?{}:{description:n}};for(let n of Settings2.tagAlbumDate.values){let a=parseJsonDateToMillis(pluckDeep(e,n)?.value);if(a!=null){r.releasedAt=a;break}}s[s.length-1]=r}return logger142().tap({level:`info`,msg:`albumFromFile()`,result:compact([s]),meta:{titles:n,desc:a,whyExclude:o}})}function cameraTag(e){return e==null||blank(e.Make)?void 0:compactBlankish([TagRoots.Camera,e.Make,e.Model])}async function cameraTagFile(e){return cameraTag(await readTags(e))}var logger143=lazy2(()=>mkLogger(`tag.TagSql`)),MinCallDelayMs=(isTest()?5:30)*secondMs,runTagMaintenance=rateLimited({name:`runTagMaintenance`,minCallDelayMs:MinCallDelayMs,f:async e=>{let n=forceContextOrSetting(e),r=logger143().child(`.runTagMaintenance()`);if(n.halt?.aborted||ending()){r.info(`ending(): no-op`);return}let a=performance.now();r.info(`starting`,{ctx:n});try{if(r.info(`validating all tags...`),Tag.dao.validate_(),r.throwIfAborted_(n?.halt),n.forceSync||n.recountAllTags)r.info(`Rebuilding entire TagHierarchy closure table...`,{ctx:n}),TagHierarchy.rebuild();else{let e=TagHierarchy.repairIfNeeded();e.action!==`none`&&r.info(`TagHierarchy repaired`,e)}if(r.throwIfAborted_(n?.halt),await updateTagMountpoints(),n.forceSync)rebuildTagDisplayPaths(Tag.dbl.db().db);else{let e=repairTagDisplayPathsIfNeeded(Tag.dbl.db().db);e.stale>0&&r.info(`Tag display paths repaired`,e)}r.throwIfAborted_(n?.halt),n.recountAllTags?(r.info(`rebuilding optimized hierarchical tag asset counts...`),await rebuildTagAssetCounts(Tag.dbl.db().db)):await rebuildNullTagAssetCounts(Tag.dbl.db().db)}catch(e){let n=String(e?.message??e);if(!n.includes(`Cannot read`)||!n.includes(`undefined`))throw e;logger143().warn(`runTagMaintenance() failed (test-teardown race)`,e)}let o=roundMs(performance.now()-a),s=clamp(MinCallDelayMs,15*minuteMs,o*20);runTagMaintenance.setMinCallDelayMs(s),logger143().info(`runTagMaintenance(): complete.`,{newMinCallDelayMs:s,elapsedMs:o})}}),updateTagMountpoints=lazyAsync({desc:`updateTagMountpoints`,later:async()=>{logger143().info(`updating tag mountpoints...`);let e=Tag.dao.findByPath([TagRoots.fs]);if(e==null)mkLogger(`updateTagMountpoints()`).info(`No root filesystem tag (new db, I hope?)`);else{e.maybeUpsertDisplayName(Settings2.tagDisplayNameFS.valueOrDefault);for(let n of e.getChildren())fixFileRootTag(n)}}});function _reset(){updateTagMountpoints.clear(),runTagMaintenance.clear()}later(()=>{ee().on(`clearCache`,_reset),Settings2.libraryDir.watchLater(_reset)});function fixFileRootTag(e){if(e==null||e.depth!==2||!e._path.startsWith(TagRoots.fs+TagSep))return;let n=mkLogger(`fixFileRootTag(`+e+`)`);if(e.name===LibraryTagName){e.ordinal!==1&&(n.info(`fixing library ordinal`,{id:e.id,path:e.path}),e.upsert({ordinal:1}),Tag.clear());return}if(!forceContextOrSetting().forceSync&¬Blank(e.displayName)&>2(e.updatedAt,Date.now()-volumeMetadataTtlMs())){n.info(`no-op: tag recently updated`,{id:e.id,path:e.path,updated:fmtDuration(Date.now()-e.updatedAt)+` ago`});return}let r=displayNameForVolsha(e.name);r==null?n.debug(`cannot update tag: no Volume row for this volsha.`,{id:e.id,path:e.path}):(e.maybeUpsertDisplayName(r),n.info(`updated tag`,{id:e.id,path:e.path,displayName:r}),Tag.clear())}function displayNameForVolsha(e){return Volume.findByVolsha(e)?.displayName()}var logger144=lazy2(()=>mkLogger(`curators.FilePathTagger`));async function tagAssetPaths(e){let n=[];for(let r of e)try{let e=originalsLibraryTagPath({uri:r,isFile:!0});e!=null&&n.push(e);let a=uriToTagPath({uri:r,isFile:!0});if(a==null)continue;if(r.startsWith(PS_LOCAL_FILE_SCHEME)&&modelDb()!=null){let e=tagRefToS(a[1]);a[1]={name:e,displayName:displayNameForVolsha(e)},logger144().info(`tagAssetPaths()`,{uri:r,tp:a})}n.push(a)}catch{logger144().warn(`Failed to parse asset file URI`,{uri:r})}return n}function isFsTag(e){return tagRefToS(e[0]).toLowerCase()===TagRoots.fs}var import_GeolocationTags=require("exiftool-vendored/dist/GeolocationTags"),logger145=defer(()=>mkLogger(`curators.GeoTagger`)),CountryCodeTags={applePhotosCountry:[`applePhotosCountryCode`],Country:[`CountryCode`,`Country-PrimaryLocationCode`],"LocationShown.CountryName":[`LocationShown.CountryCode`],"LocationCreated.CountryName":[`LocationCreated.CountryCode`],GeolocationCountry:[`GeolocationCountryCode`]};function collapseAdjacentDuplicates(e){return e.filter((n,r)=>r===0||!equalsIgnoreCase(n,e[r-1]))}function geoTag(e){let n=Settings2.tagGeoMaxDistanceKm.valueOrDefault,r=n>0&>(toFloat(e.GeolocationDistance),n);r&&logger145().debug(`geoTag(): GeolocationDistance too large, Geolocation* synonyms skipped`,pickDeep(e,...import_GeolocationTags.GeolocationTagNames));let a=e=>!(r&&e.startsWith(`Geolocation`)),o=Settings2.tagGeoSynonyms.synonymMap(),s=Settings2.tagGeoTemplate.valueOrDefault,c=s.map(n=>first(o.get(n)??[n],n=>{let r=a(n)?pluckDeep(e,n)?.value:void 0;return r==null?void 0:{tagName:n,value:r}})),l=c.map(e=>toS(e?.value).trim());if(l.every(e=>e.length===0))return;let u=s.map(e=>o.get(e)??[e]),d=u.findIndex(e=>e.some(e=>CountryCodeTags[e]!=null)),f,h;if(d>=0){let n=c[d]?.tagName,r=l[d];f=first(n==null?u[d].filter(a).flatMap(e=>CountryCodeTags[e]??[]):CountryCodeTags[n]??[],n=>alpha3ToAlpha2(toS(pluckDeep(e,n)?.value).trim()))??countryNameToCode(r),f!=null&&(h=r.length===0||reasonRejectingTagSegment(r,!1)!=null?countryCodeToName(f):r,l[d]=f)}let _=compactBlanks(l),y=Settings2.tagGeoCollapseRepeatedLevels.valueOrDefault?collapseAdjacentDuplicates(_):_,x=compact([TagRoots.Where,...y]);return logger145().tap({msg:`geoTag`,result:{tagPath:x,countryCode:f,countryName:h},meta:{picked:c}})}async function geoTagFile(e){let n=await readTags(e);return n==null?void 0:geoTag(n)}function lensTag(e){return map(e,e=>mapNotBlank(e.lensMake,n=>mapNotBlank(compactBlanks(Settings2.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],e=>[TagRoots.Lens,n,e])))}async function lensTagFile(e){let n=await readTags(e);return n==null?void 0:lensTag(n)}var logger146=lazy2(()=>mkLogger(`curators.TypeTagger`));async function typeTagFiles(e){return compact(uniq(await mapAsyncSerial({name:`typeTagFiles`,arr:e,f:readMimeType})).map(mimeTypeToTag))}var Cases=new Map([`M2TS`,`JPEG`,`QuickTime`].map(e=>[e.toLowerCase(),e]));function mimeTypeToTag(e){let[n,r]=e.split(`/`);if(!(blank(n)||blank(r)))return logger146().tap({msg:`mimetypeToTag(`+e+`)`,result:map(friendlySubtype(r,e),e=>compactBlanks([TagRoots.Type,capitalize(n),...e]))})}var Subtypes=lazy2(()=>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 friendlySubtype(e,n){return firstDefinedThunk([()=>Subtypes().get(n.trim().toLowerCase()),()=>map(e.match(/^x-(\w{4,})-\w{3}/),e=>[`Raw`,capitalize(e[1])]),()=>[fixCase(e.replace(/^(?:x-|vnd\.|prs\.)/i,``).replace(/-/g,` `))]])}function fixCase(e){return e.match(/[a-z\d]{3,4}/i)==null?Cases.get(e.trim().toLowerCase())??capitalize(e):e.toUpperCase()}var logger147=lazy2(()=>mkLogger(`curators.AssetTagger`));async function mostDetailedTag(e,n){let r,a;for(let o of e){let e=await n(o);if(e!=null){let n=joinTagPath(e);(a==null||n.length>a.length||n.length===a.length&&n<a)&&(r=e,a=n)}}return r}async function tagAndUpsertAsset_(e,n){let r=n?.priorForUpdateCount??e.snapshotForUpdateCount(),a=await e.getExistingAssetFiles();logger147().info(`tagAndUpsertAsset()`,{asset:e,existing_uris:a.map(e=>e.uri)});let o=a.find(e=>e.isPrimary);if(o==null)return logger147().throw(`tagAndUpsertAsset(): no existing or primary asset file`+InternalErrorFlag,{asset:e,existingPrimaryAssetFile:o,doNotSend:!0,fatal:!1});let s=e.getPrimary();s?.id!==o.id&&(logger147().warn(`Primary asset changed; using a different variant for tagging.`,{newPrimary:o.uri,priorPrimary:s?.uri}),await e.setPrimary_(o));let c=o.posixFile_(),l=await thenCollect(a,e=>e.posixFile_()),u=e.getAssetFiles().map(e=>e.uri),d=await tagAsset({primaryVariation:c,files:l,priorTagPaths:e.getTagPaths(),capturedAt:e.getCapturedAt(),uris:u});logger147().info(`tagAndUpsertAsset`,d);let{geoResult:f}=d;if(f?.countryName!=null){let e=Settings2.tagGeoCountryFlags.valueOrDefault?f.countryCode:void 0,n=flaggedCountryName(f.countryName,e);Tag.dao.findOrCreate(f.tagPath.slice(0,2)).maybeUpsertDisplayName(n)}let h=e.isActive(),_=d.add.find(e=>leafIsExcluded(e,Settings2.keywordBlocklist.values));if(_!=null){if(e.shown===!0)logger147().info(`this asset has an excluded tag, marking excluded`,{excludedTag:_}),e.excludedAt=Date.now();else return logger147().info(`this asset has an excluded tag, and it wasn't shown yet, so we're removing it.`,{excludedTag:_}),await Asset.dao.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),logger147().throw(`tagAndUpsertAsset(): asset had excluded tag. Removed.`,{excludedTag:_,uris:u,files:l.map(e=>e.nativePath)})}return e.applyTagPathDeltas(d,{priorIsActive:h}),n?.updateFromFiles!==!1&&await e.updateFromFiles(),e.upsertIfChanged(r,`tagAndUpsertAsset_()`),d}async function fsTagDeltas(e,n){let r=(await tagAssetPaths(n)).map(normalizeTagPath2).filter(e=>e!=null),a=tagDeltas(e,omitAncestorTags(uniqBy([...e.filter(e=>!isFsTag(e)),...r],joinTagPath)));if(!(a.add.some(e=>leafIsExcluded(e,Settings2.keywordBlocklist.values))||[...a.add,...a.remove].some(e=>!isFsTag(e))))return a}async function tagAsset({primaryVariation:e,files:n,priorTagPaths:r,capturedAt:a,uris:o}){let s=[],c=uniqBy([e,...n],e=>e.nativePath);if(Settings2.tagCamera.valueOrDefault){let e=await mostDetailedTag(c,cameraTagFile);e!=null&&(logger147().debug(`Camera tag:`,e),s.push(e))}if(Settings2.tagLens.valueOrDefault){let e=await mostDetailedTag(c,lensTagFile);e!=null&&(logger147().debug(`Lens tag:`,e),s.push(e))}let l;if(Settings2.tagGeo.valueOrDefault)for(let e of c){let n=await geoTagFile(e);if(n!=null){s.push(n.tagPath),l=n;break}}let u=await dateTagFile(e,a);u!=null&&(logger147().debug(`Date tag for `+e+`:`,u),s.push(u));let d=await whoTagFiles(c)??[];logger147().debug(`whoTagFiles for `+e+`:`,d),s.push(...d);let f=await keywordTagFiles(Settings2.tagKeywordsFromVariations.valueOrDefault===`primary`?[e]:c,d);if(f!=null&&(logger147().debug(`Keyword tags for `+e+`:`,f),s.push(...f)),Settings2.tagFileType.valueOrDefault){let n=await typeTagFiles(c);n!=null&&(logger147().debug(`MIME type tags for `+e+`:`,n),s.push(...n))}let h=await tagAssetPaths(o);h!=null&&(logger147().debug(`file paths for uris`,{uris:o,arr:h}),s.push(...h));let _=await tagFilesWithAlbums(c);_!=null&&(logger147().debug(`Album tags for `+e+`:`,_),s.push(..._));let y=omitAncestorTags(uniqBy(s.map(normalizeTagPath2).filter(e=>e!=null),joinTagPath)),x=tagDeltas(r,y);return logger147().info(`tagAsset(`+e+`)`,{priorTagPaths:r,after:y,result:x}),{...x,geoResult:l}}var logger148=defer(()=>mkLogger(`sync-file.UpdateAssetPreviews`)),PreviewSourceRevisionChangedError=class extends Error{name=`PreviewSourceRevisionChangedError`},LegacyPreviewCleanupError=class extends Error{constructor(e,n){super(`Failed to delete legacy preview metadata for Asset:${e}`),this.assetId=e,this.cause=n}assetId;cause;name=`LegacyPreviewCleanupError`};function derivativeStatsChanged(e,n){return e?.size!==n?.size||e?.mtimeMs!==n?.mtimeMs}async function deleteLegacyPreviewInfo_(e){try{await e.legacyInfoJson().unlink_()}catch(n){throw new LegacyPreviewCleanupError(e.assetId,n)}}async function updateAssetPreviews_(e){let n=performance.now(),r=e.assetId??e.asset?.id??toA(e.assetFiles).find(e=>gt0(e.assetId))?.assetId,a=forceContextOrSetting(e),o=logger148().child(`.Asset:`+r);if(a.skipPreviews){o.warn(`skipPreviews is true: no-op`,{assetId:r});return}if(!gt0(r))return o.throw(`invalid assetId`,{assetId:r});let s=e.asset??Asset.ops().findById(r);if(s==null)return o.throw(`Asset:`+r+` not found`);o.throwIfAborted_(a.halt);try{o.throwIfAborted_(a.halt);let c=sortAssetFilesInPlace(e.assetFiles??s.getAssetFiles());await resolveNativePaths(c);let l=c.map(e=>({id:e.id,assetId:e.assetId,uri:e.uri})),u=await buildAssetPreviews_({...a,assetId:r,assetFiles:c,preferredShas:e.preferredShas,pinnedUri:e.pinnedUri,prior:publishedPreviewProvenance(s)});await validatePreviewBuildResult_(r,u);let d=c.find(e=>e.id===u?.assetFileId)??await findAsync(c,e=>uriIsEquivalent(u?.uri,e.uri)),f=c.find(e=>e.id===u?.assetFileId),h=f!=null&&f.assetId!==r;syncReport().onProgress({path:`Asset:${r}`,type:`file`,state:h?`warning`:`note`,from:`updateAssetPreviews_`,details:h?`CROSS-ASSET: Preview selected AssetFile:${u?.assetFileId} which belongs to Asset:${f?.assetId}, not Asset:${r}`:`Preview generated from AssetFile:${u?.assetFileId}`,elapsedMs:performance.now()-n,meta:{selectedAssetFileId:u?.assetFileId,selectedUri:u?.uri,selectedFileAssetId:f?.assetId,expectedAssetId:r,inputFiles:l,wrongAsset:h},url:assetPath(r)}),o.info(`buildAssetPreviews_()`,{result:u,primaryAssetFile:d});let _=d?.posixFile(),y=u?.noop!==!0;return d==null||y&&(_==null||!0!==await _.exists())?o.throw(`buildAssetPreviews_() returned invalid assetFileId`+InternalErrorFlag,{newInfo:u,assetFiles:c.map(e=>pick(e,`id`,`uri`)),primaryAssetFile:d,primaryPosixFile:_}):u}catch(e){throw!ending()&&!(e instanceof PreviewSourceRevisionChangedError)&&(o.warn(`Failed to update previews. Un-showing asset `+r,{error:e}),s.markUnshownAndUpsert()),e}}function exactRevisionOf(e){return{sha:e.sha,width:e.width,height:e.height,mimetype:e.mimetype,rotation:e.rotation}}async function validatePreviewBuildResult_(e,n){let r=AssetFile.ops().findById(n.assetFileId);try{await r?.resolveNativePath_()}catch(r){logger148().info(`validatePreviewBuildResult_(): source did not resolve`,{assetId:e,assetFileId:n.assetFileId,error:r})}let a=r?.posixFile(),o=await a?.stat({refresh:!0}),s=await a?.thisOrSidecarMaxMtimeMs({refresh:!0}),c=n.noop===!0&&(o==null||s==null),l=r==null?void 0:exactRevisionOf(r),u=c||s!=null&&o!=null&&previewSourceStatsUnchanged(n.source,{mtime:Math.floor(s),fileSize:o.size});if(!(n.assetId===e&&r?.id===n.assetFileId&&r.assetId===e&&await uriIsEquivalent(n.uri,r.uri))||!u||!eql(l,exactRevisionOf(n.source))){let a=new PreviewSourceRevisionChangedError(`Preview source revision changed while previews were building`+InternalErrorFlag);throw logger148().warn(a.message,{error:a,assetId:e,result:n,currentRevision:l,currentPhysicalStat:{mtime:s==null?void 0:Math.floor(s),fileSize:o?.size},currentAssetFileId:r?.id,currentAssetId:r?.assetId,currentUri:r?.uri}),a}}var logger149=defer(()=>mkLogger(`sync.FinalizeAsset`));async function finalizeAsset(e){let n=performance.now(),{assetId:r}=e;if(!gt0(r))return logger149().throw(`finalizeAsset(): invalid assetId`,{args:e});let a=Asset.ops().findById(r);if(a==null)return logger149().throw(`finalizeAsset(): Asset not found`,{assetId:r,logLevel:`warn`});let o=logger149().child(`.finalizeAsset(Asset:${r})`),s=getTaskAbortable(e);s!=null&&(o.abortable=s);let c=getTaskReportProgress(e);try{let{assetDeleted:e,removedCount:s}=await removeProblematicAssetFiles(a,`finalizeAsset`,logger149());if(e)return{newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:!1};if(AssetFlags.has(a.flags,`validateSiblings`))return Asset.dbl.runf(e=>e.where(`id`,r).update({flags:knex().raw(`COALESCE(flags, 0) & ~?`,[AssetFlags.toBit(`finalize`)|AssetFlags.toBit(`finalizePathTags`)])})),logger149().info(`finalizeAsset(): skipped, validateSiblings pending`,{assetId:r}),{newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:!1};if(await awaitToolProbeForAsset(r),s===0&&AssetFlags.has(a.flags,`finalizePathTags`)&&!AssetFlags.has(a.flags,`finalize`)){let e=await _finalizePathTagsOnly(o,a);if(e!=null)return syncReport().onProgress({path:a.getPrimaryNativePath()??`Asset:${r}`,type:`file`,state:SyncFileStates.completed,from:`finalizeAsset`,elapsedMs:performance.now()-n,details:`finalized (path-tags only): tags=${a.tagPaths().join(`, `)}`,url:assetPath(r)}),e;o.info(`path-tags-only fast path escalated to full finalization`,{assetId:r})}let l=await _finalizeAsset(o,a,c);return syncReport().onProgress({path:a.getPrimaryNativePath()??`Asset:${r}`,type:`file`,state:SyncFileStates.completed,from:`finalizeAsset`,elapsedMs:performance.now()-n,details:`finalized: tags=${a.tagPaths().join(`, `)}`,url:assetPath(r)}),l}catch(e){if(e instanceof LegacyPreviewCleanupError)throw e;if(e instanceof PreviewSourceRevisionChangedError){if(!AssetFlags.has(a.flags,`failedFinalize`)){try{Asset.dbl.runf(e=>e.where(`id`,r).update({flags:knex().raw(`COALESCE(flags, 0) | ?`,[AssetFlags.toBit(`failedFinalize`)])}))}catch(e){o.warn(`Could not record a preview-source race`,{assetId:r,flagError:e})}throw e}o.warn(`Preview source revision changed again; retiring asset `+r,{error:e,assetId:r})}if(!ending()&&(!isTest()||modelDb()!=null)){let s=a.getPrimaryNativePath(),c=s??`Asset:${r}`,l=AssetFlags.has(a.flags,`failedFinalize`),u=a.isActive(),d=u?a.tagIds():[];o.warn(`Failed to finalize asset, marking unshown`,{error:e,assetId:r,primaryPath:s,alreadyFailed:l});try{let e=AssetFlags.toBit(`finalize`)|AssetFlags.toBit(`finalizePathTags`),n=l?0:AssetFlags.toBit(`failedFinalize`);Asset.dbl.runf(a=>a.where(`id`,r).update({shown:0,updatedAt:Date.now(),flags:knex().raw(`(COALESCE(flags, 0) & ~?) | ?`,[e,n])})),u&&!isEmpty(d)&&Tag.dao.deltaAssetCountAndAncestors(d,-1)}catch(e){o.warn(`Failed to update asset flags after finalization error`,{upsertError:e,assetId:r,primaryPath:s})}try{syncReport().onProgress({path:c,type:`file`,state:errorToState(e),from:`finalizeAsset`,details:errorToS2(e),elapsedMs:performance.now()-n,url:assetPath(r)})}catch(e){o.warn(`Could not write finalization failure report`,{assetId:r,primaryPath:s,reportError:e})}}throw e}}async function _finalizePathTagsOnly(e,n){let r=n.id;if(n.shown!==!0)return;for(let e of PathTagsOnlyBlockingAssetFlags)if(n.hasFlag(e))return;let a=n.getAssetFiles({refresh:!0});if(isEmpty(a)||a.some(e=>AssetFileFlags.has(e.flags,`contentChanged`))||!a.some(e=>e.isPrimary))return;try{for(let e of a){if(await e.whyNeedsUpsert()!=null)return;let n=e.posixFile_();for(let e of Settings2.tagAlbumFilenames.values)if(!0===await n.sibling(e).exists())return}if(await mayCopyAssetsToLibrary())for(let e of new Set(a.map(e=>e.sha))){let n=!1;for(let r of a)if(r.sha===e&&r.isInLibrary()&&await r.exists_()){n=!0;break}if(!n)return}}catch(n){e.warn(`path-tags-only eligibility recheck failed; escalating`,{assetId:r,error:n});return}let o=await fsTagDeltas(n.getTagPaths(),a.map(e=>e.uri));if(o==null)return;let s=o.add.length>0||o.remove.length>0;if(s){let e=n.snapshotForUpdateCount(),r=n.isActive();n.applyTagPathDeltas(o,{priorIsActive:r}),n.upsertIfChanged(e,`_finalizePathTagsOnly()`)}return Asset.dbl.runf(e=>AssetFlags.update({qb:e,flag:`finalizePathTags`,isSet:!1}).where(`id`,r)),e.tap({msg:`finalizeAsset() complete (path-tags only)`,result:{newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:s,pathTagsOnly:!0},meta:{deltas:o}})}async function _finalizeAsset(e,n,r){let a=n.id,o=n.getAssetFiles(),s=new Set(o.map(e=>e.id));await resolveNativePaths(o);let c=o.filter(e=>AssetFileFlags.has(e.flags,`contentChanged`)).map(e=>({id:e.id,sha:e.sha})),l=[...new Set(c.map(e=>e.sha))],u=n.getPrimaryNativePath();u!=null&&await maybeDelayIfNotProd(u);for(let e of o){let n=e.posixFile()?.nativePath;n!=null&&maybeThrowTestFinalizeError(n)}let d={newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:!1};if(e.throwIfAborted_(),o.length===0)return await Asset.dao.remove({assetId:a,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${a} had no asset files. Deleted.`,{doNotSend:!0,retriable:!1});if(await mayCopyAssetsToLibrary()){await copyFilesToLibrary(o,d,e),o=n.getAssetFiles({refresh:!0});for(let e of o)d.newAssetFileUris.includes(e.uri)&&s.add(e.id)}e.throwIfAborted_();let{previewResult:f,readableAssetFiles:h,deferred:_}=await updatePreviewsForFinalization_({asset:n,assetFiles:o,changedShas:l});if(d.previewsUpdated=!0!==f?.noop,_)return Asset.dbl.runf(e=>e.where(`id`,a).update({flags:knex().raw(`COALESCE(flags, 0) & ~?`,[AssetFlags.toBit(`finalize`)|AssetFlags.toBit(`finalizePathTags`)])})),e.info(`_finalizeAsset(): deferred after preview reuse proof`,{assetId:a,shown:n.shown,previewSourceUri:f?.uri,assetFileCount:o.length}),d;let{af:y,source:x}=await primaryOrShownAssetFile(n,f,h);if(y==null)return e.throw(`null primaryOrShownAssetFile()`,{asset:n});e.info(`Selected primary file`,{assetFileId:y.id,source:x,assetFileCount:o.length});let C=n.snapshotForUpdateCount();await n.setPrimary_(y,{skipAssetUpsert:!0}),await y.resolveNativePath_();let w=y.posixFile_();if(n.isVideo()){if(w==null)return e.throw(`null primary.posixFile()`,{asset:n,assetFiles:n.getAssetFiles()});let o=r==null?void 0:e=>r({pct:e.pct,etaMs:e.etaMs,speed:e.speed,label:`Transcoding video`}),s=Previews.instance().ap(a).mp4(),c=await s.stat({refresh:!0});await transcode_(w,s,{force:!1,halt:e.abortable,onProgress:o}),d.transcoded=derivativeStatsChanged(c,await s.stat({refresh:!0}))}e.throwIfAborted_(),await tagAndUpsertAsset_(n,{priorForUpdateCount:await n.markShownAndUpsert_(y,C)}),d.tagged=!0;let T=AssetFlags.toBit(`finalize`)|AssetFlags.toBit(`finalizePathTags`)|AssetFlags.toBit(`failedFinalize`)|AssetFlags.toBit(`refreshDerivatives`)|AssetFlags.toBit(`failedRefreshDerivatives`)|AssetFlags.toBit(`retag`)|AssetFlags.toBit(`failedRetag`),E=Asset.ops().findById(a)?.getPrimary();if(f!=null&&E?.id!==f.assetFileId)throw new PreviewSourceRevisionChangedError(`Selected primary changed before preview publication for Asset:${a}`);f!=null&&await validatePreviewBuildResult_(a,f);let D=new Set(h.map(e=>e.sha));if(AssetFile.dbl.txn(()=>{let e=AssetFile.dbl.pluckAllf(e=>e.select(`id`).where({assetId:a})).some(e=>!s.has(e))?AssetFlags.toBit(`finalize`)|AssetFlags.toBit(`finalizePathTags`):0;Asset.dbl.runf(n=>n.where(`id`,a).update({flags:knex().raw(`COALESCE(flags, 0) & ~?`,[T&~e]),...f==null?{}:previewProvenanceColumns(f),...d.previewsUpdated||d.transcoded?{updateCount:knex().raw(`COALESCE(updateCount, 0) + 1`)}:{},updatedAt:Date.now()}));for(let{id:e,sha:n}of c)D.has(n)&&AssetFile.dbl.runf(r=>AssetFileFlags.update({qb:r.where({id:e,sha:n}),flag:`contentChanged`,isSet:!1}))}),f!=null)try{await deleteLegacyPreviewInfo_(Previews.instanceRequired().ap(a))}catch(e){throw Asset.dbl.runf(e=>AssetFlags.update({qb:e.where(`id`,a),flag:`refreshDerivatives`,isSet:!0})),e}return e.tap({msg:`finalizeAsset() complete`,result:d,meta:{asset_assetFiles:n.getAssetFiles().map(e=>pick(e,`id`,`uri`)),assetFiles:o.map(e=>pick(e,`id`,`uri`))}})}async function primaryOrShownAssetFile(e,n,r){if(gt0(n?.assetFileId)){let r=e.getAssetFiles().find(e=>e.id===n.assetFileId)??e.getAssetFiles({refresh:!0}).find(e=>e.id===n.assetFileId);return r==null?logger149().throw(`PreviewBuildResult referenced unknown assetFileId`,{asset:e,previewResult:n}):{af:r,source:`previewResult`}}let a=r.find(e=>e.isPrimary);return a==null?{af:await bestExistingAssetFile(r),source:`bestExisting`}:{af:a,source:`getPrimary`}}async function updatePreviewsForFinalization_({asset:e,assetFiles:n,changedShas:r}){let a=await e.getExistingAssetFiles(),o=isEmpty(a)?n:a,s=a.filter(e=>!e.isInLibrary()).map(e=>e.sha),c=await updateAssetPreviews_({asset:e,assetFiles:o,preferredShas:[...new Set([...r,...s])],forceSync:!1,forceRebuildPreviews:r.length>0||void 0});return{previewResult:c,readableAssetFiles:a,deferred:e.shown===!0&&isEmpty(a)&&c?.noop===!0}}async function copyFilesToLibrary(e,n,r){let a=[...groupBy(e,e=>e.sha).entries()].sort(([e],[n])=>(e??``).localeCompare(n??``));for(let[e,o]of a){r.throwIfAborted_();let a=sortAssetFilesInPlace([...o]);try{for(let e of a)if(await e.exists_()){let r=await Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,forceContextOrSetting({}),()=>{});if(r!=null){n.newAssetFileUris.push(r.uri);break}}}catch(n){r.warn(`Failed to copy variation to library, but continuing`,{sha:e,uris:a.map(e=>e.uri),error:n})}}}var logger150=mkLogger(`sync.RefreshAssetDerivatives`);async function existingPosterFiles(e){return e.existingJpgs()}async function createPosterSnapshot_(e){let n=[];try{for(let r of await existingPosterFiles(e)){let e=r.wip();await r.copyFile_(e,{skipProgressWatchdog:!0}),n.push({original:r,backup:e}),await e.touch_()}return n}catch(e){throw await unlink4(n.map(e=>e.backup),`debug`),e}}async function restorePosterSnapshot_(e,n){let r=new Set(n.map(e=>e.original.nativePath));for(let{backup:e,original:r}of n)await e.copyFile_(r,{skipProgressWatchdog:!0});for(let n of await existingPosterFiles(e))r.has(n.nativePath)||await n.unlink_()}async function discardPosterSnapshot(e){await unlink4(e.map(e=>e.backup),`debug`)}function setRefreshState(e,n){Asset.dbl.runf(r=>AssetFlags.update({qb:r.where(`id`,e),flag:`refreshDerivatives`,isSet:n})),Asset.dbl.runf(r=>AssetFlags.update({qb:r.where(`id`,e),flag:`failedRefreshDerivatives`,isSet:n}))}function commitRefresh(e,n,r){let a=AssetFlags.toBit(`refreshDerivatives`)|AssetFlags.toBit(`failedRefreshDerivatives`);Asset.dbl.runf(o=>o.where(`id`,e).update({flags:knex().raw(`COALESCE(Asset.flags, 0) & ~?`,[a]),...previewProvenanceColumns(n),...r?{updateCount:knex().raw(`COALESCE(Asset.updateCount, 0) + 1`)}:{},updatedAt:Date.now()}))}async function refreshAssetDerivatives(e){let{assetId:n}=e,r=Asset.ops().findById(n);if(r==null||!AssetFlags.has(r.flags,`refreshDerivatives`))return;await awaitToolProbeForAsset(n);let a=getTaskAbortable(e)??new Abortable,o=getTaskReportProgress(e),s,c=!1,l=!0;try{let e=await r.getExistingAssetFiles(),l=Previews.instanceRequired().ap(n);r.isVideo()&&(s=await createPosterSnapshot_(l));let u=await buildAssetPreviews_({assetId:n,assetFiles:e,halt:a,forceRebuildPreviews:void 0,prior:publishedPreviewProvenance(r),pinnedUri:r.getPrimary()?.uri});await validatePreviewBuildResult_(n,u);let d=e.find(e=>e.id===u.assetFileId);await d?.resolveNativePath_();let f=d?.posixFile_();if(d==null||f==null)throw Error(`Derivative refresh selected missing AssetFile:${u.assetFileId}`);let h=u.noop!==!0;if(r.isVideo()){let e=l.mp4(),n=await e.stat({refresh:!0}),r=await isVideoTranscodingSupported(),s=await isTranscodeOf(f,e);if(!r&&!s&&await e.exists())throw Error(`Cannot replace the existing video preview because transcoding is unavailable`);r&&await transcode_(f,e,{force:!1,halt:a,onProgress:o==null?void 0:e=>o({...e,label:`Refreshing video preview`})}),h||=derivativeStatsChanged(n,await e.stat({refresh:!0}))}await validatePreviewBuildResult_(n,u),commitRefresh(n,u,h),c=!0,await deleteLegacyPreviewInfo_(l)}catch(e){let r=e;if(s!=null&&!c)try{await restorePosterSnapshot_(Previews.instanceRequired().ap(n),s)}catch(n){l=!1,r=AggregateError([e,n],`Derivative refresh and poster restoration both failed`)}if(ending()||a.aborted&&!isFfmpegStallAbort(a.reason))throw e;setRefreshState(n,!0),logger150.warn(`Failed to refresh derivatives`,{assetId:n,error:r}),syncReport().onProgress({path:`Asset:${n}`,type:`file`,state:`warning`,from:`refreshAssetDerivatives`,details:errorToS2(r),url:assetPath(n)})}finally{s!=null&&l&&await discardPosterSnapshot(s)}ee().emitSync(`notifyWorkAvailable`,`refreshAssetDerivatives`)}var import_node_path70=require("node:path");function isSyncFileSuccess(e){return e?.state===`imported`||e?.state===`updated`||e?.state===`unchanged`}function isSyncFileError(e){let n=e?.state;return n===`failed`||n===`timeout`||n===`canceled`}async function settleInBatches(e,n){let r=[];for(let a of batches(e,Settings2.taskListCap.valueOrDefault))r.push(...await Promise.allSettled(a.map(n)));return r}var import_node_path69=require("node:path"),import_node_path68=require("node:path"),DoneWrapper=class extends EndableWrapper{doneLatch=new Latch;constructor(e,n,r=EndableRanks.first,a){super(e,n,r,a);let o=()=>{this.ended||this.end()};this.doneLatch.promise.then(o,o)}isDone(){return this.doneLatch.isSettled()||this.ended}donePromise(){return this.doneLatch.promise}},Done2={done:!0},Undone={done:!1},Listening=Symbol(`Listening`),DirectoryIterator=class e extends DoneWrapper{constructor(e,n,r){super(`dir.DirectoryIterator(`+e+`)`,()=>this.cancel({details:`DirectoryIterator was ended`})),this.dir=e,this.ctx=n,this.parent=r,syncReport().onProgress({path:e.nativePath+import_node_path68.sep,from:`DirectoryIterator`,type:`dir`,state:SyncDirStates.scanning})}dir;ctx;parent;start=performance.now();#e=[];#t=[];#n=[];#r=[];#i=!1;#a=0;#o;#s=defer(()=>iterateDir_(this.dir.nativePath));#c=0;#l=0;#u=0;#d=0;#f=0;#p;#m=0;#h=!1;#g;get isRoot(){return this.parent==null}rootDir=lazy2(()=>this.parent?.rootDir()??this.dir);pathFromRoot=lazy2(()=>posixPathFrom({nativePath:this.rootDir().dir},this.dir));status(){return{root:this.rootDir().nativePath,path:this.pathFromRoot(),isDone:this.isDone()}}cancel(e){return this.#s().return(void 0),this.doneLatch.isSettled()||(syncReport().onProgress({path:this.dir.nativePath+import_node_path68.sep,from:`DirectoryIterator`,type:`dir`,state:SyncDirStates.canceled,...e,elapsedMs:performance.now()-this.start}),this.doneLatch.resolve()),Done2}depth(){return countChars(this.dir.nativePath,import_node_path68.sep)}async run(e=ShortCommandTimeoutMs){for(;!this.isDone();)await this.next(performance.now()+e),await delay(1)}nextTimeout=lazy2(()=>{let e=Settings2.statTimeoutMs.valueOrDefault;return e<=0?0:e+clamp(0,512,(512-this.depth())*10)});async next(e){if(this.#x())return Undone;try{return await this.#v(e,n=>Promise.race([n,new Promise(e=>{this.#g=e}).then(async()=>(await delay(e-performance.now()),Listening))]))}finally{this.#g=void 0}}#_(e){return this.#v(e,e=>e)}async#v(e,n){let r=e-performance.now();try{this.logger.trace(`next() starting`,{runMs:r}),this.#p??=(this.#m=performance.now(),this.#S(e));let a=await thenOrTimeout(n(this.#p),this.nextTimeout());return this.logger.trace(`next() finished`,{result:a}),a===Listening?Undone:a===Timeout?this.#x()?(this.logger.info(`next() still waiting for directoryListener`),Undone):(this.#f++,this.logger.warn(`.next() timed out`,{runMs:r,timeoutCount:this.#f}),this.#f>3?(this.logger.warn(`.next(): too many timeouts, giving up on this directory.`),this.#p?.catch(e=>this.logger.warn(`next() failed after this directory timed out`,{error:e})),this.cancel({state:SyncDirStates.timeout,details:`Failed to scan, even after 3 retries`})):Undone):(this.#p=void 0,this.#f=0,a)}catch(e){this.#p=void 0;let n=isVolumeGoneError(e),r=n?`info`:this.isRoot?`warn`:`info`;return this.logger.log(r,`next() failed`,{error:e}),this.cancel({state:n?SyncDirStates.unavailable:SyncDirStates.failed,details:(n?`Volume no longer available: `:`Error thrown during scan: `)+errorToS2(e)})}}async settled(e=-1/0){this.#m>=e&&await Promise.allSettled([this.#p]),await this.#o?.settled(e),await Promise.all([...this.#y].map(n=>n.settled(e)))}#y=new Set;#b(e){this.#y.add(e),e.settled().then(()=>this.#y.delete(e))}#x(){return this.#h?!0:this.#o!=null&&this.#o.#x()}async#S(e){return(this.isDone()?Done2:void 0)??await this.#C()??await this.#w(e)}#C=defer(async()=>{let e=await this.ctx.whyExcludeDirectory(this.dir);if(e!=null)return this.logger.info(`skipping excluded dir, `+this.dir,{details:e}),await this.ctx.onExcludedDirectory?.(this.dir,e),this.cancel({state:SyncDirStates.excluded,details:e}),Done2;if(!this.isRoot&&await isMountPoint(this.dir.nativePath))return this.logger.info(`skipping nested mountpoint, `+this.dir),this.cancel({state:SyncDirStates.unavailable,details:`nested mountpoint (scanned separately)`}),Done2});isEnded(){return this.ended||this.ctx.ended?.()===!0}async#w(e){do{if(!this.ctx.hasCapacity())return this.logger.debug(`hasCapacity() returned false`),Undone;if(this.isEnded())return this.cancel({details:`DirectoryIterator was ended`});let n=this.#o;if(n!=null&&((await n.#_(e))?.done??n.isDone())===!0&&(this.#o=void 0,this.#b(n)),this.#o==null){let e=await this.#T();if(e!=null)return e}}while(performance.now()<=e);return Undone}async#T(){if(this.#i)return this.#D();let e=await this.#s().next();if(e.done===!0)return await this.#E(),this.#i=!0,this.#r.length===0?this.#D():Undone;let n=e.value;if(n instanceof Error){this.logger.warn(`Failed to read directory entry`,{error:n});return}if(n.isDirectory()){if(this.ctx.skipSubdirectories===!0)return;this.#d++,this.#u++,this.#r.push(n.name);return}let r=DirectoryEntry.fromDirent(this.dir.nativePath,n);if(n.isSymbolicLink())mayBeSidecar(r)&&this.#n.push(r);else if(n.isFile()){let e=await this.ctx.whyExcludeFileByName?.(r),n=mayBeSidecar(r);if((e==null||n)&&await r.stat(),n&&this.#t.push(r),isSidecarExt(r))return;this.#l++;let a=e??await this.ctx.whyExcludeFile(r);a==null?(this.#c++,this.#e.push(r),await this.ctx.fileHandler(r)):(this.logger.debug(`processEntries()`,{child:r,whyReject:a}),await this.ctx.onExcludedFile?.(r,a),syncReport().onProgress({path:r.nativePath,from:`DirectoryIterator`,type:`file`,state:SyncFileStates.excluded,details:a}))}}#E=defer(async()=>{if(this.doneLatch.isSettled())return;let e=await nativePathToUri(this.dir.nativePath),n=(e==null?void 0:mkFolderUrl(e))?.with({query:null}).toString(),r=mapNotBlank(andList([this.#l===0?``:`${this.#c}/${plur(this.#l,`file`)}`,this.#d===0?``:`${this.#u}/${plur(this.#d,`directory`,`directories`)}`]),e=>`Accepted `+e)??`No files or directories found`;syncReport().onProgress({path:this.dir.nativePath+import_node_path68.sep,type:`dir`,state:SyncDirStates.scanned,from:`DirectoryIterator`,details:r,url:n,elapsedMs:performance.now()-this.start});let a={accepted:this.#e,possibleSidecars:this.#t,possibleSidecarSymlinks:this.#n,uriPath:e};this.#e=[],this.#t=[],this.#n=[],this.#h=!0;for(let e=this;e!=null;e=e.parent)e.#g?.();try{await this.ctx.directoryListener(this.dir,a)}finally{this.#h=!1}});#D(){if(this.isDone())return Done2;let n=this.#r[this.#a++];if(n==null)return this.doneLatch.resolve(),Done2;this.#o=new e(DirectoryEntry.fromSimpleDirent(this.dir.nativePath,{basename:n,isFile:!1,isDirectory:!0}),this.ctx,this)}},import_promises34=require("node:timers/promises"),ScreenYieldIntervalMs=50;async function partitionUnchangedFiles_({listing:e,scanGeneration:n,abortable:r,reportProgress:a}){let o=forceContextOrSetting(),s=e.uriPath?.uri.toString(),c=s==null?void 0:DirUri.findByUri_(s);if(o.forceSync||o.forceFilters||c==null)return{unchanged:[],needsSync:[...e.accepted]};let l=compactBlanks(Settings2.directorySidecars.valueOrDefault),u=n=>e.possibleSidecarSymlinks.some(e=>isSidecarOf(n,e)||l.includes(e.base)),d=new ListedSidecars(e.possibleSidecars),f=e.possibleSidecars.filter(e=>!e.hasStats()),h=e=>f.some(n=>isSidecarOf(e,n)||l.includes(n.base)),_=[],y=[],x=performance.now(),C=0,w=()=>a?.({label:`Screening folder`,step:C});for(let a of batches(e.accepted,Settings2.dbBatchSelectSize.valueOrDefault)){let e=a.map(e=>e.base),o=new Map(AssetFile.ops().all(AssetFile.query().where({dirUriId:c.id}).whereIn(`basename`,e)).map(e=>[e.basename,e.withDirUri(c)])),s=new Set(RejectedFile.dbl.pluckAllf(n=>n.select(`basename`).where({dirUriId:c.id}).whereIn(`basename`,e))),l=[];for(let e of a){performance.now()-x>ScreenYieldIntervalMs&&(w(),await(0,import_promises34.setImmediate)(),x=performance.now()),C++;let n=o.get(e.base);n!=null&&!n.hasFlag(`forceFilters`)&&!n.hasFlag(`contentChanged`)&&!n.locationIsApproximate&&!s.has(e.base)&&!ProblematicFile.isProblematic(e.nativePath)&&!u(e)&&e.hasStats()&&!h(e)&&await whyIsMediaInfoStale(n.ctx(),n,fileStatFieldsFromListing(e,d))==null?l.push({file:e,assetFileId:n.id}):y.push(e)}w(),r?.throwIfAborted_(),l.length>0&&AssetFile.dbl.runf(e=>e.whereIn(`id`,l.map(e=>e.assetFileId)).update({lastVisitedGeneration:n}));for(let{file:e}of l)syncReport().onProgress({path:e.nativePath,from:`partitionUnchangedFiles`,type:`file`,state:SyncFileStates.unchanged}),_.push(e)}return{unchanged:_,needsSync:y}}var ForceUpdateProducer=class e extends BaseTaskProducer{static instance=lazy(()=>new e);static producerName=`ForceUpdateProducer`;constructor(){super(e.producerName,`updateAssetFile`,void 0,void 0,`idle`)}queryIds(e,n){return AssetFile.dbl.pluckAllf(r=>(r=AssetFileFlags.where({qb:r.select(`AssetFile.id`).orderBy(`AssetFile.id`).limit(e),flag:`forceUpdate`}),n.size>0&&(r=r.whereNotIn(`AssetFile.id`,[...n])),this.excludeUnavailable_(r,`AssetFile.id`)))}async mkTask(e){let n={assetFileId:e,forceFilters:!0},r;try{r=await resolveUpdateAssetFilePath(n)}catch(n){let r=isInvalidURIError(n);this.logger.warn(`mkTask(): could not resolve this row`,{assetFileId:e,quarantined:r,error:n}),r&&this.onTaskConstructionFailed(e);let a=AssetFile.ops().findById(e),o=a?.uri??`AssetFile:${e}`;throw r||this.onTaskDeferred(e,Date.now()+minuteMs,o),this.reportTaskConstructionFailure(n,{path:o,url:assetPath(a?.assetId)}),n}return{method:`updateAssetFile`,args:r==null?{...n,unavailableAtAdmission:!0}:{...n,path:r}}}static pendingCount(){return AssetFile.dbl.pluckFirstf(e=>AssetFileFlags.where({qb:e,flag:`forceUpdate`}).count(`* as count`))??0}},logger151=defer(()=>mkLogger(`sync.SyncFolder`));async function syncFolder(e){let n=new SyncFolderProgress(e.path),r;try{r=await filesToSyncIn_(e.path,{abortable:getTaskAbortable(e),reportProgress:getTaskReportProgress(e)})}catch(e){throw n.failed(),e}logger151().info(`syncFolder: queueing syncFile tasks`,{path:e.path,count:r.length}),n.processing(r.length);let a=getTaskContext(e);settleInBatches(r,async e=>{try{return await addLocalTask(`syncFile`,{path:e},a).d.promise}finally{n.settled()}}).then(a=>{let o=a.filter(e=>e.status===`rejected`||isSyncFileError(e.value)).length;logger151().info(`syncFolder: done`,{path:e.path,count:r.length,failed:o}),n.done(o)})}var SyncFolderProgress=class{#e;#t;#n=0;#r=0;constructor(e){this.#e=`Just the files in `+(0,import_node_path69.basename)(e),this.#t=Progress.insertNew({uri:SyncFolderURI,volume:e,state:`processing`,hed:`Processing`,dek:[this.#e]})}processing(e){this.#n=e,this.#i()}settled(){this.#r++,gt(this.#t.updatedAt,Date.now()-secondMs)||this.#i()}done(e){let n=[this.#e];this.#n===0?n.push(`No new or changed files`):(n.push(`Processed `+plur(this.#n-e,`file`)),e>0&&n.push(plur(e,`file`)+` failed`)),this.#t.upsert({state:`done`,hed:`Done`,completePct:100,incompletePct:0,dek:n})}failed(){this.#t.upsert({state:`failed`,hed:`Failed`,dek:[this.#e]})}#i(){let e=this.#n-this.#r,n=100*this.#r/Math.max(1,this.#n);this.#t.upsert({completePct:n,incompletePct:100-n,dek:[this.#e,plur(e,`file`)+(e===1?` remains`:` remain`)+` to be processed`]})}};async function filesToSyncIn_(e,n={}){await ee().emit(`fileChanged`,e);let r=await listingOf(e,n);if(n.abortable?.throwIfAborted_(),r==null)return[];let a=await dirUriIdsOf_(e),{needsSync:o}=await partitionUnchangedFiles_({listing:r,scanGeneration:AssetFile.dbl.pluckFirstf(e=>e.whereIn(`dirUriId`,a).max(`lastVisitedGeneration`))??0,abortable:n.abortable,reportProgress:n.reportProgress});return n.abortable?.throwIfAborted_(),flagRowsNotListed_(a,new Set(r.accepted.map(e=>e.base.normalize(`NFC`))),e),o.map(e=>e.nativePath)}var ProgressEveryFiles=100;async function listingOf(e,{abortable:n,reportProgress:r}){let a=await DirectoryEntry.for_(e),o,s=0;return await new DirectoryIterator(a,{whyExcludeFileByName:whyRejectFileByName,whyExcludeFile:whyRejectFileByStat,whyExcludeDirectory:whyExcludedDirectory,hasCapacity:()=>!0,fileHandler:()=>{++s%ProgressEveryFiles===0&&r?.({label:`Listing folder`,step:s})},directoryListener:(e,n)=>{o=n},ended:()=>ending()||n?.aborted===!0,skipSubdirectories:!0}).run(),o}async function dirUriIdsOf_(e){let n=await nativePathToUriStrings(e);return DirUri.dbl.pluckAllf(e=>e.select(`id`).whereIn(`uri`,n))}function flagRowsNotListed_(e,n,r,a=()=>!0){let o=AssetFile.dbl.allf(n=>n.select(`id`,`basename`).whereIn(`dirUriId`,e)).flatMap(e=>n.has(e.basename.normalize(`NFC`))||!a(e.basename)?[]:[e.id]);if(o.length!==0){for(let e of batches(o,Settings2.dbBatchSelectSize.valueOrDefault))for(let n of[`forceFilters`,`forceUpdate`])AssetFile.dbl.runf(r=>AssetFileFlags.update({qb:r.whereIn(`id`,e),flag:n,isSet:!0}));logger151().info(`flagged files no longer listed`,{dir:r,count:o.length}),ForceUpdateProducer.instance().notifyWorkAvailable()}}var logger152=defer(()=>mkLogger(`sync.RepairAsset`));async function repairAsset(e){let n=performance.now(),{assetId:r}=e,a={from:`repairAsset`,path:`Asset:${r}`},o=logger152().child(`.repairAsset(Asset:${r})`),s=getTaskAbortable(e),c=getTaskContext(e);s!=null&&(o.abortable=s);let l=Asset.ops().findById(r);if(l==null){syncReport().onProgress({...a,type:`file`,state:SyncFileStates.excluded,details:`no such Asset`,elapsedMs:roundMs(performance.now()-n)});return}let u=l.getAssetFiles({refresh:!0});if(u.length===0){await Asset.dao.remove({assetId:r,blocklistShas:!1,unlinkAssetFiles:!1}),syncReport().onProgress({...a,type:`file`,state:SyncFileStates.deleted,details:`Asset has no files. Removed.`,elapsedMs:roundMs(performance.now()-n)});return}await resolveNativePaths(u);let d=e.syncFilesBeside===!0?await filesToSyncBeside(u):[],f=u.map(e=>{let n=e.posixFile()?.nativePath;return addLocalTask(`updateAssetFile`,{assetFileId:e.id,path:n,unavailableAtAdmission:n==null,forceSync:!0,skipAssetRepair:!0},c)});o.info(`repairAsset: Scheduled repair`,{assetId:r,updateCount:u.length,filesBeside:d}),awaitRepairCompletion(n,r,f,d,c)}async function filesToSyncBeside(e){let n=compact(e.map(e=>e.posixFile()?.nativePath)),r=new Set(n.map(e=>e.normalize(`NFC`))),a=new Set(e.flatMap(e=>bname(e.basename))),o=e=>bname(e).some(e=>a.has(e)),s=[];for(let e of uniq(n.map(e=>(0,import_node_path70.dirname)(e)))){if(await ee().emit(`fileChanged`,e),!await PosixFile.for(e).isDirectory({refresh:!0}))continue;let n=await readdir2(e);if(n==null)continue;let a=new Set;for(let c of n){if(!c.isFile)continue;a.add(c.basename.normalize(`NFC`));let n=(0,import_node_path70.join)(e,c.basename);o(c.basename)&&!r.has(n.normalize(`NFC`))&&await whyRejectFileByName(PosixFile.for(n))==null&&s.push(n)}flagRowsNotListed_(await dirUriIdsOf_(e),a,e,o)}return s}async function awaitRepairCompletion(e,n,r,a,o){let s=logger152().child(`.awaitRepairCompletion(Asset:${n})`),c=assetPath(n),l={from:`repairAsset`,path:`Asset:${n}`,url:c};syncReport().onProgress({...l,type:`file`,state:SyncFileStates.started,elapsedMs:roundMs(performance.now()-e)});try{let c=(await Promise.allSettled(r.map(e=>e.d.promise))).filter(e=>e.status===`rejected`).length;c>0&&s.warn(`awaitRepairCompletion: some updateAssetFile tasks failed`,{assetId:n,failed:c,total:r.length});let u=await settleInBatches(a,e=>addLocalTask(`syncFile`,{path:e},o).d.promise),d=u.flatMap(e=>e.status===`fulfilled`&&isSyncFileSuccess(e.value)?[e.value]:[]),f=u.filter(e=>e.status===`rejected`||isSyncFileError(e.value)).length;if(f>0&&s.warn(`awaitRepairCompletion: some files beside the asset were not synced`,{assetId:n,notImported:f,total:a.length}),!assetFileHashReadyForMatching()){Asset.dao.setFlag(n,`validateSiblings`),ee().emitThrottled(`notifyWorkAvailable`,`validateAssetSiblings`),syncReport().onProgress({...l,type:`file`,state:SyncFileStates.warning,details:`Metadata repair complete; sibling validation deferred until the AssetFileHash index is ready`,elapsedMs:roundMs(performance.now()-e)});return}let h=(await settleInBatches(d,e=>addLocalTask(`adoptAssetFile`,{assetFileId:e.assetFileId,path:e.path},o).d.promise)).filter(e=>e.status===`rejected`).length;h>0&&s.warn(`awaitRepairCompletion: some files beside the asset were not adopted`,{assetId:n,adoptFailed:h,total:d.length});let _=await addLocalTask(`validateAssetSiblings`,{...await resolveAssetTaskArgs(n),skipFinalizeScheduling:!0},o).d.promise;if(Asset.ops().findById(n)==null){syncReport().onProgress({...l,type:`file`,state:SyncFileStates.deleted,details:_?.dissolved?`Merged into a duplicate asset`:`Asset has no files. Removed.`,elapsedMs:roundMs(performance.now()-e)});return}await addLocalTask(`finalizeAsset`,await resolveAssetTaskArgs(n),o).d.promise,syncReport().onProgress({...l,type:`file`,state:SyncFileStates.completed,details:`Repair complete`,elapsedMs:roundMs(performance.now()-e)})}catch(r){s.error(`awaitRepairCompletion: failed`,{assetId:n,err:r}),syncReport().onProgress({...l,type:`file`,state:SyncFileStates.failed,details:`Repair failed: ${r}`,elapsedMs:roundMs(performance.now()-e)})}}var logger153=mkLogger(`sync.RetagAsset`);function setRetagState(e,n){Asset.dbl.txn(()=>{Asset.dbl.runf(r=>AssetFlags.update({qb:r.where(`id`,e),flag:`retag`,isSet:n})),Asset.dbl.runf(r=>AssetFlags.update({qb:r.where(`id`,e),flag:`failedRetag`,isSet:n}))})}async function retagAsset({assetId:e}){let n=Asset.ops().findById(e);if(n!=null&&AssetFlags.has(n.flags,`retag`))try{await tagAndUpsertAsset_(n,{updateFromFiles:!1}),setRetagState(e,!1)}catch(n){if(ending())throw n;setRetagState(e,!0),logger153.warn(`Failed to retag asset`,{assetId:e,error:n}),syncReport().onProgress({path:`Asset:${e}`,type:`file`,state:`warning`,from:`retagAsset`,details:errorToS2(n),url:assetPath(e)})}}var Clusters=class{constructor(e,n){this.cmp=e,this.prepare=n}cmp;prepare;#e=new Map;#t=new Map;#n=1;add(e){let n=this.#e.get(e);if(n!=null)return n;let r=this.prepare?.(e)??(n=>this.cmp(e,n));for(let[n,a]of this.#t)for(let o of a)if(r(o))return a.add(e),this.#e.set(e,n),n;let a=this.#n++;return this.#t.set(a,new Set([e])),this.#e.set(e,a),a}remove(e){let n=this.#e.get(e);if(n==null)return!1;this.#e.delete(e);let r=this.#t.get(n);return r.delete(e),r.size===0&&this.#t.delete(n),!0}clear(){this.#e.clear(),this.#t.clear()}items(){return this.#e.keys()}getClusterItems(e){return this.#t.get(e)}getClusterId(e){return this.#e.get(e)}getClusterIdByPredicate(e){for(let[n,r]of this.#e)if(e(n))return r}get clusterCount(){return this.#t.size}get itemCount(){return this.#e.size}},clusterLockName=e=>`clusterId:${e}`,VacuumIntervalMs=7*secondMs,AssetFileClusters=class e extends EndableInterval{static instance=lazy(()=>new e);clusters=new Clusters(isSimilarMedia,similarityProbe);#e=mkLogger(`task.AssetFileClusters`);#t=new Map;inPlaySerialIds;#n=!1;#r=0;#i=0;#a=0;get stats(){return{addCount:this.#r,totalAddMs:this.#i,avgAddMs:this.#r>0?this.#i/this.#r:0,reapedCount:this.#a,clusterCount:this.clusters.clusterCount,itemCount:this.clusters.itemCount}}constructor(){super({name:`AssetFileClusters.vacuum`,callback:()=>this.#o(),intervalMs:VacuumIntervalMs})}add(e){let n=performance.now(),r=this.clusters.add(e);return this.#r++,this.#i+=performance.now()-n,this.#t.set(e.id,e),r}getClusterIdByAssetFileId(e){let n=this.#t.get(e);if(n!=null){let r=this.clusters.getClusterId(n);if(r!=null)return r;this.#t.delete(e)}let r=AssetFile.ops().findById(e);if(r!=null)return this.add(r)}resetForTest(){assertIsTest(),this.clusters.clear(),this.#t.clear()}#o(){let e=this.inPlaySerialIds;e==null?this.#n||(this.#n=!0,this.#e.warn(`vacuum(): inPlaySerialIds supplier is not wired, so no cluster entries can be reaped. Call initializeTaskProducers().`)):this.vacuum(e())}vacuum(e){let n=0;for(let[r,a]of[...this.#t]){let o=this.clusters.getClusterId(a);o!=null&&e.has(clusterLockName(o))||(o!=null&&this.clusters.remove(a),this.#t.delete(r),n++)}return this.#a+=n,n}},FFMPEG_SOLO_LOCK=`ffmpeg-solo`;function pathLock(e){return blank(e)?[]:[`path:`+e]}function assetFileLocks(e){if(e==null)return[];let n=[...pathLock(e.nativePath)];if(gt0(e.id)){n.push(`assetFileId:`+e.id);let r=AssetFileClusters.instance().getClusterIdByAssetFileId(e.id);r!=null&&n.push(clusterLockName(r))}return uniq(n)}function adoptAssetFileLocks(e){let n=toGt0(e?.assetFileId),r=AssetFile.ops().findById(n);return r==null?[]:assetFileLocks({id:r.id,nativePath:toNotBlank(e?.path)??r.posixFile()?.nativePath})}function assetIdLock(e){return gt0(e)?[`assetId:`+e]:[]}function assetLocksWithRef(e,n){let r=Asset.ops().findById(e.assetId),a=assetIdLock(e.assetId);if(r==null)return{locks:a};n&&e.paths!=null&&a.push(...e.paths.flatMap(pathLock));for(let e of r.getAssetFiles())a.push(...assetFileLocks({id:e.id,nativePath:n&&e.uriObject.scheme!==PS_NETWORK_FILESYSTEM_SCHEME?e.posixFile()?.nativePath:void 0}));return{locks:uniq(a),asset:r}}function assetLockNames(e){return assetLocksWithRef(e,!0).locks}function repairAssetLocks(e){return assetLocksWithRef(e,!1).locks}function finalizeAssetLocks(e){let{locks:n,asset:r}=assetLocksWithRef(e,!0);return r!=null&&Settings2.ffmpegThreads.valueOrDefault===0&&r.isVideo()&&n.push(FFMPEG_SOLO_LOCK),n}function getPathLocks(e){return`path`in e&&!blank(e.path)?pathLock(e.path):pathLock((e instanceof AssetFile?e:getAssetFile_(e))?.posixFile()?.nativePath)}var testTask=shim({name:`testTask`,impl:async e=>({id:uid(),arg:e,ts:Date.now()})}),Tasks={adoptAssetFile,deleteAsset,repairAsset,retagAsset,refreshAssetDerivatives,updateAssetFile:updateAssetFile_,finalizeAsset,syncFile:importFileToResult_,syncFolder,testTask,validateAssetSiblings},TaskNames=strEnum(...keys(Tasks));function getFileTimerName(e,n){return`${e}:${getMediaCategory((0,import_node_path71.extname)(n).slice(1).toLowerCase())??`unknown`}`}function getFileSize(e){try{return(0,import_node_fs33.statSync)(e).size}catch{return}}function getAssetFilesForSize(e){try{let n=Asset.ops().findById(e);if(n==null)return;let r=n.getAssetFiles();return uniqBy([n.getPrimary(),...r],e=>e.id)}catch{return}}function getAssetTimerName(e,n,r){try{let a=r?.map(e=>({nativePath:e}))??getAssetFilesForSize(n);if(a!=null)for(let n of a){let r=n.nativePath;if(r!=null)return getFileTimerName(e,r)}}catch{}return e}function getAssetFileSize(e,n){try{let r=n?.map(e=>({nativePath:e}))??getAssetFilesForSize(e);if(r==null)return;for(let e of r){let n=e.nativePath;if(n!=null){let e=getFileSize(n);if(e!=null)return e}}}catch{}}function getUpdateAssetFilePath(e){try{return e.path==null?getAssetFile_(e).nativePath:e.path}catch{return}}async function resolveUpdateAssetFilePath(e){return getUpdateAssetFilePath(e)??await getAssetFile_(e).resolveNativePath_()}function getAdoptAssetFilePath(e){if(e.path!=null)return e.path;try{return AssetFile.ops().findById(e.assetFileId)?.nativePath}catch{return}}function getUpdateAssetFileTimerName(e,n){let r=getUpdateAssetFilePath(n);return r==null?e:getFileTimerName(e,r)}function getUpdateAssetFileSize(e){let n=getUpdateAssetFilePath(e);return n==null?void 0:getFileSize(n)}var TaskImpls={adoptAssetFile:{fn:adoptAssetFile,lockNamesFn:adoptAssetFileLocks,timerNameFn:e=>{let n=getAdoptAssetFilePath(e);return n==null?`adoptAssetFile`:getFileTimerName(`adoptAssetFile`,n)},fileSizeFn:e=>{let n=getAdoptAssetFilePath(e);return n==null?void 0:getFileSize(n)}},deleteAsset:{fn:deleteAsset,lockNamesFn:assetLockNames,awaitNativeCompletion:!0},repairAsset:{fn:repairAsset,lockNamesFn:repairAssetLocks,timerNameFn:e=>getAssetTimerName(`repairAsset`,e.assetId),fileSizeFn:e=>getAssetFileSize(e.assetId)},retagAsset:{fn:retagAsset,lockNamesFn:assetLockNames,timerNameFn:e=>getAssetTimerName(`retagAsset`,e.assetId,e.paths),fileSizeFn:e=>getAssetFileSize(e.assetId,e.paths)},refreshAssetDerivatives:{fn:refreshAssetDerivatives,lockNamesFn:finalizeAssetLocks,timerNameFn:e=>getAssetTimerName(`refreshAssetDerivatives`,e.assetId,e.paths),fileSizeFn:e=>getAssetFileSize(e.assetId,e.paths)},updateAssetFile:{fn:updateAssetFile_,lockNamesFn:getPathLocks,timerNameFn:e=>getUpdateAssetFileTimerName(`updateAssetFile`,e),fileSizeFn:e=>getUpdateAssetFileSize(e)},finalizeAsset:{fn:finalizeAsset,lockNamesFn:finalizeAssetLocks,timerNameFn:e=>getAssetTimerName(`finalizeAsset`,e.assetId,e.paths),fileSizeFn:e=>getAssetFileSize(e.assetId,e.paths)},syncFile:{fn:importFileToResult_,lockNamesFn:getPathLocks,timerNameFn:e=>getFileTimerName(`syncFile`,e.path),fileSizeFn:e=>getFileSize(e.path)},syncFolder:{fn:syncFolder,lockNamesFn:getPathLocks},testTask:{fn:testTask,lockNamesFn:e=>[`test`+e]},validateAssetSiblings:{fn:validateAssetSiblings,lockNamesFn:assetLockNames,awaitNativeCompletion:!0,timerNameFn:e=>getAssetTimerName(`validateAssetSiblings`,e.assetId,e.paths),fileSizeFn:e=>getAssetFileSize(e.assetId,e.paths)}};function getTaskContext(e){if(typeof e==`object`&&e&&`_taskContext`in e)return e._taskContext}function getTaskAbortable(e){if(typeof e==`object`&&e&&`_abortable`in e)return e._abortable}function getTaskReportProgress(e){if(typeof e==`object`&&e&&`_reportProgress`in e)return e._reportProgress}function getTaskPath(e){if(typeof e==`object`&&e&&`path`in e)return e.path}function getTaskAssetId(e){if(typeof e==`object`&&e&&`assetId`in e)return e.assetId}var Task2=class e{constructor(e,n,r,a,o,s){this.method=e,this.args=n,this.source=s,this.lockNames=uniq(r),this.producerName=a,this.producerId=o;let c=TaskImpls[e],l=`task.`+(c.timerNameFn?.(n)??e);this.fileSize=c.fileSizeFn?.(n),this.d=new Deferred2(e,{serialIds:r,payload:this,timer:PromiseTimer.instance(),timerName:l,fileSize:this.fileSize})}method;args;source;d;lockNames;producerName;producerId;fileSize;abortable=new Abortable;liveProgress;onProgressChanged;waitingOutsideDeadline=!1;static for(n,r,a={}){let o=TaskImpls[n].lockNamesFn(r);return new e(n,r,o,void 0,void 0,a.source)}static fromJson(n){let r=TaskImpls[n.method].lockNamesFn(n.args);return new e(n.method,n.args,r,n._producerName,n._producerId,n.source)}async run(){if(isTest()&&(ending()||modelDb()==null))return;let e;try{let n=e=>{let n=!eql(e,this.liveProgress);this.liveProgress=e,n&&this.onProgressChanged?.()},r=this.args!=null&&typeof this.args==`object`?{...this.args,_abortable:this.abortable,_reportProgress:n,_taskContext:{source:this.source}}:this.args;return await runWithOperationOwner({onProgress:e=>n(e.pct==null?{label:e.op,step:e.step}:{label:e.op,pct:e.pct,step:e.step}),awaitOutsideDeadline:async e=>{this.d.clearTimeout(),this.waitingOutsideDeadline=!0;let n=Date.now();try{return await e}finally{this.waitingOutsideDeadline=!1,this.d.startedAt+=Date.now()-n,this.onProgressChanged?.()}},onFailureReported:n=>{e={error:n}}},()=>Tasks[this.method](r))}catch(n){let r=getTaskPath(this.args);if(!blank(r)){let a=errorToState(n);if(a===SyncFileStates.timeout&&ProblematicFile.add(r,`Timed out after ${this.d.elapsedMs}ms`),e==null||e.error!==n){let e=getTaskAssetId(this.args);syncReport().onProgress({path:r,from:this.method,state:a,elapsedMs:this.d.elapsedMs,details:errorToS2(n),url:assetPath(e)})}}throw n}}toString(){return this.d.name+`(${stringify(this.args)}): ${this.d.state}`}toJSON(){return{method:this.method,args:this.args,...this.source==null?{}:{source:this.source}}}},logger154=defer(()=>mkLogger(`task.ProblematicFile`));function refreshProblematicFilesHealthCheck(){HealthCheck.findById(ProblematicFilesHealthCheckId)?.refresh()}var ProblematicFile=class{static#e=lazy2(()=>this.#i());static{ee().on(`clearCache`,()=>this.clearCache())}static clearCache(){this.#e.unset()}static#t(){return quarantineDbRequired_().problematicFiles}static#n(e=Date.now()){let n=Settings2.problematicDecayMs.valueOrDefault;return n===0?void 0:e-n}static#r(e){return{path:e.path,strikes:e.strikes.map(e=>({timestamp:e.struckAt,reason:e.reason}))}}static#i(){let e=this.#n();e!=null&&this.#t().cleanup(e);let n=new Map;for(let r of this.#t().load(e)){let e=this.#r(r);n.set(e.path,e)}return n}static#a(e,n=Date.now()){let r=this.#n(n);return r==null?e.strikes:e.strikes.filter(e=>e.timestamp>=r)}static#o(e){return e.length===0?0:Math.max(...e.map(e=>e.timestamp))+Settings2.problematicCooldownMs.valueOrDefault*e.length}static#s(e,n){if(e.length===0)return!1;let r=Settings2.problematicMaxStrikes.valueOrDefault;return r>0&&e.length>=r||n<this.#o(e)}static#c(e,n){let r=Settings2.problematicDecayMs.valueOrDefault,a=new Set,o=this.#a(e,n);a.add(this.#o(o));for(let n of o){let o=n.timestamp+r+1;a.add(o),a.add(this.#o(this.#a(e,o)))}for(let r of[...a].sort((e,n)=>e-n))if(r>=n&&!this.#s(this.#a(e,r),r))return r;return Math.max(...o.map(e=>e.timestamp))+r+1}static add(e,n){return this.#l(e,n,Date.now(),!0)}static addWedgedTasks(e){for(let n of e){if(n.waitingOutsideDeadline)continue;let e=getTaskPath(n.args);e!=null&&this.add(e,`Sync was wedged (no progress detected). This file was running when the wedge was detected.`)}}static#l(e,n,r,a){if(blank(e))return;let o=this.#e(),s=o.get(e),c={timestamp:r,reason:n};this.#t().addStrike(e,r,n);let l=s??{path:e,strikes:[]};return l.strikes.push(c),o.set(e,l),a&&logger154().info(`Adding strike to problematic file`,{path:e,reason:n,strikeCount:this.#a(l).length}),l}static isProblematic(e){return this.getStatus(e)?.blocked===!0}static getStatus(e,n=Date.now()){if(blank(e))return;let r=this.#e().get(e);if(r==null)return;let a=this.#a(r,n),o=a.length,s=this.#s(a,n),c=Settings2.problematicMaxStrikes.valueOrDefault,l=Settings2.problematicDecayMs.valueOrDefault,u=c>0&&o>=c;return{strikeCount:o,blocked:s,expiresAt:u&&l===0?null:u&&s?this.#c(r,n):this.#o(a)}}static getStrikeCount(e){return this.getStatus(e)?.strikeCount??0}static getAllStrikes(e){return blank(e)?[]:this.#e().get(e)?.strikes??[]}static getLastStrike(e){let n=this.getAllStrikes(e);if(n.length!==0)return n.reduce((e,n)=>e.timestamp>=n.timestamp?e:n)}static cleanup(){let e=this.#n();if(e==null)return 0;let n=this.#t().cleanup(e);return this.#u(e),n>0&&logger154().info(`Cleaned up fully-decayed problematic files`,{deleted:n}),n}static#u(e){let n=this.#e.priorSync();if(n!=null)for(let[r,a]of n)a.strikes=a.strikes.filter(n=>n.timestamp>=e),a.strikes.length===0&&n.delete(r)}static removePath(e){if(blank(e))return!1;let n=this.#t().remove(e),r=this.#e.priorSync()?.delete(e)??!1;return quarantineDbRequired_().deferrals.removeByPath(e),!n&&!r?!1:(logger154().info(`Removed problematic file`,{path:e}),refreshProblematicFilesHealthCheck(),!0)}static getPage(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error(`Problematic-file page limit must be a positive integer`);let n=this.#t().page(e.limit,e.cursor,this.#n());return{entries:n.entries.map(e=>this.#r(e)),nextCursor:n.nextCursor}}static getAll(e){let n=this.#n(),r=e??this.#t().countPaths(n);return r===0?[]:this.getPage({limit:r}).entries}static count(){return this.#t().countPaths(this.#n())}static countBlocked(e=Date.now()){return this.#t().countBlocked({cutoff:this.#n(e),maxStrikes:Settings2.problematicMaxStrikes.valueOrDefault,cooldownMs:Settings2.problematicCooldownMs.valueOrDefault,now:e})}static clear(){this.#t().clear(),this.#e.priorSync()?.clear(),quarantineDbRequired_().deferrals.clearAll(),logger154().info(`Cleared all problematic files`),refreshProblematicFilesHealthCheck()}static async reload(){this.#e.set(this.#i())}static addStrikeAt(e,n,r){return this.#l(e,n,r,!1)}},logger155=defer(()=>mkLogger(`task.StallWatcher`)),TimerBootstrapSampleThreshold=5,StallWatcher=class extends EndableInterval{constructor(e,n=minuteMs){super({name:`task.StallWatcher`,intervalMs:n,rank:EndableRanks.service,unref:!0,callback:()=>this.check()}),this.getRunningTasks=e,logger155().debug(`StallWatcher initialized`,{checkIntervalMs:n})}getRunningTasks;#e=new Set;check(){let e=this.getRunningTasks(),n=new Set(e.map(e=>e.d.id));for(let e of this.#e)n.has(e)||this.#e.delete(e);for(let n of e)this.#t(n)}#t(e){if(this.#e.has(e.d.id)||e.waitingOutsideDeadline)return;let n=e.d.timerName,r=e.d.elapsedMs,a=e.fileSize,o=PromiseTimer.instance();if(a!=null&&(o.getDurationEstimator(n)?.sampleCount??0)<TimerBootstrapSampleThreshold)return;let s=o.estimate(n,a,`p50`),c=o.estimate(n,a,`p99`),l=Settings2.stallWarningFloorMs.valueOrDefault;if(r<=(c==null?l:Math.max(c,l)))return;let u=this.#n(e);if(u==null){logger155().debug(`StallWatcher: no path for task`,{method:e.method,timerName:n,elapsedMs:r});return}let d=c==null||l>c,f=`Stalled: ${fmtElapsedMs(r)} elapsed`;s==null?d&&(f+=` (min warning: ${fmtElapsedMs(l)})`):(f+=` (expected ~${fmtElapsedMs(s)}`,f+=d?`, min warning: ${fmtElapsedMs(l)})`:c==null?`)`:`, p99: ${fmtElapsedMs(c)})`),logger155().warn(`Task stalled`,{method:e.method,timerName:n,elapsedMs:r,p50Ms:s,p99Ms:c,floorMs:l,path:u});let h=getTaskAssetId(e.args);syncReport().onProgress({path:u,from:e.method,state:SyncFileStates.stalled,details:f,elapsedMs:r,meta:{p50Ms:s,p99Ms:c,floorMs:d?l:void 0,fileSize:a},url:assetPath(h)}),this.#e.add(e.d.id)}#n(e){let n=e.args;if(typeof n==`object`&&n){if(`path`in n)return n.path;if(`assetId`in n)return getPathForAssetTask(e)}}get problematicFilesCount(){return ProblematicFile.count()}get warnedCount(){return this.#e.size}clearTracking(){this.#e.clear()}clearProblematicFiles(){ProblematicFile.clear()}};function getPathForAssetTask(e){let n=e.args;if(gt0(n?.assetId))try{return Asset.ops().findById(n.assetId)?.getPrimary()?.nativePath}catch{return}}var bailAfterTaskCount=lazy2(()=>isTest()?toGt0(process.env[PS_BAIL_AFTER_TASK_COUNT]):void 0),MaxBarrenRefills=8,TaskList=class e extends EndableInterval{#e=0;#t=0;static instance=lazy2(()=>new e);#n=mkLogger(`task.TaskList`);ee=new TypedEventEmitterImpl;#r;#i=new AdaptiveConcurrency;#a=!1;#o;p;recentlyProcessed=new TTLArray(minuteMs);#s=new Set;#c=new Set;#l;#u=new Set;#d=-1/0;#f=new Set;#p=new Map;#m=0;static get ee(){return this.instance().ee}constructor(){super({name:`task.TaskList`,intervalMs:(isTest()?1:60)*secondMs,rank:EndableRanks.first,callback:()=>this.pullFromProducers()});let e=`TaskList()`;this.p=Promises.for({name:`TaskList()`,reserveToStart:reserveFreeSpaceToStart,maxConcurrency:()=>this.#E(),sortByDesc(e){return[e.id]}}),this.p.ee.on(`lowWaterMark`,()=>void this.pullFromProducers()),this.p.ee.on(`drain`,()=>{this.pullFromProducers(),setUnrefTimeout(()=>void this.#S(),2*secondMs)}),ee().on(`notifyWorkAvailable`,e=>{this.#C();let n=this.#p.get(e);n?.notifyWorkAvailable!=null&&n.notifyWorkAvailable()}),this.#r=new StallWatcher(()=>this.currentTasks()),Settings2.cpuBusyPercent.watchLater(this.#h),this.#h(Settings2.cpuBusyPercent.valueOrDefault),this.onEnds.push(()=>{Settings2.cpuBusyPercent.unWatch(this.#h),this.#o?.()})}#h=e=>{if(e===0){this.#o?.(),this.#o=void 0,this.#a=!1;let e=this.#g(),n=this.#i.limit(e);this.#i.reset(),this.#i.limit(e)>n&&this.p.maybePopPendingWork()}else this.#o==null&&!this.ended&&(this.#a=!1,this.#o=CpuUsage.instance().onSample(e=>this.onCpuSample(e)))};#g(){return effectiveMaxConcurrentImports()}onCpuSample=e=>{let n=this.p.takeRunningCountSample();if(!this.#a||e.kind===`rebase`){this.#n.debug(`Realigned import concurrency CPU interval`,{priorWindowAligned:this.#a,sampleKind:e.kind}),this.#a=!0;return}if(n==null)return;let r=e.busyPct,a=this.#g(),o=this.#i.limit(a),s=this.p.hasSomeNotStartedJobs(),c=Settings2.cpuBusyPercent.valueOrDefault,l=this.#i.update({busyPct:r,ceiling:a,hasPendingWork:s,averageRunningCount:n.averageRunningCount,maxRunningCount:n.maxRunningCount,targetPct:c}),u={averageRunningCount:n.averageRunningCount,busyPct:r,ceiling:a,current:l,elapsedMs:n.elapsedMs,hasPendingWork:s,maxRunningCount:n.maxRunningCount,prior:o,targetPct:c};this.#n.debug(`Observed import concurrency CPU interval`,u),l!==o&&(this.#n.info(`Adjusted import concurrency for CPU utilization`,u),l>o&&this.p.maybePopPendingWork(),ee().emitSyncRateLimited(`syncStateChanged`))};#_(){let e=Settings2.cpuBusyPercent.valueOrDefault,n=e===0?void 0:CpuUsage.instance().busyPct(),r=this.#g();return{cap:this.#i.limit(r),ceiling:r,ceilingBound:importCeilingBound(),cpuCount:cpuCount(),targetPct:e,busyPct:n,tooBusy:tooBusyFor(n)}}get timeoutCount(){return this.#t}nuke(){this.recentlyProcessed.clear(),this.#e=0,this.#t=0,this.#m=0,this.#p.clear(),this.#f.clear(),this.#r.clearTracking(),this.p.nuke(),this.#s.clear(),this.#c.clear(),this.#T(),this.#u.clear(),this.#d=-1/0,this.#i.reset(),this.#a=!1}registerProducer(e){this.#f.has(e)||(this.#f.add(e),e.defaultTaskName!=null&&this.#p.set(e.defaultTaskName,e),this.#n.info(`Registered producer`,{name:e.name,state:e.state,producerCount:this.#f.size}),this.pullFromProducers())}unregisterProducer(e){this.#f.delete(e)&&(this.#v(e),e.defaultTaskName!=null&&this.#p.delete(e.defaultTaskName),this.#n.info(`Unregistered producer`,{name:e.name,producerCount:this.#f.size}))}#v(e){let n=e.awaitDetachedWork?.(this.#d);if(n==null)return;this.#u.add(n);let r=()=>this.#u.delete(n);n.then(r,r)}#y(e){return[...this.#f].find(n=>n.name===e)}#b(e){if(!this.#f.has(e))this.#n.warn(`producerIfActive(): producer not registered`,{name:e.name});else if(e.ended)this.#f.delete(e),this.#v(e),this.#n.info(`producerIfActive():Auto-unregistered ended producer`,{name:e.name});else if(e.state===`completed`)this.#f.delete(e),this.#v(e),this.#n.info(`producerIfActive(): Auto-unregistered completed producer`,{name:e.name});else return e.state===`active`?e:void 0}pullFromProducers=serialized(async()=>{if(this.#f.size===0||isPausedFor(`maintenance`))return;let e=this.capacity();if(e<=0)return;if(this.p.size>this.p.lowWaterMark){this.#n.debug(`pullFromProducers(): no-op: running above low water mark`,{queueSize:this.p.size,lowWaterMark:this.p.lowWaterMark});return}let n=count(this.#f,e=>this.#b(e)!=null);if(n===0){this.#n.trace(`No active producers, waiting for notifications`);return}let r=Math.max(1,Math.floor(e/n)),a=[];for(let e of this.#f)if(this.#b(e)!=null){if(this.ended)return;if(isPausedFor(`maintenance`))break;try{let n=await e.produceTasks(r);n.length>0&&(this.#n.debug(`Pulled tasks from producer`,{producer:e.name,state:e.state,requested:r,produced:n.length}),a.push(n))}catch(n){this.#n.warn(`Producer failed to produce tasks`,{producer:e.name,error:n})}}let o=compact(flatZip(...a)),s=[],c=!1;for(let e of o)try{s.push(Task2.fromJson(e))}catch(n){let r=e._producerName,a=e._producerId;if(this.#n.warn(`Produced task could not be constructed`,{method:e.method,producerName:r,producerId:a,error:n}),r!=null&&a!=null){let e=this.#y(r);if(e?.onTaskConstructionFailed!=null)try{e.onTaskConstructionFailed(a),c=!0}catch(e){this.#n.warn(`Could not quarantine unconstructable task`,{producerName:r,producerId:a,error:e})}}try{let r=getTaskAssetId(e.args);syncReport().onProgress({path:getTaskPath(e.args)??(r==null?`${e.method}:${a??`unknown`}`:`Asset:${r}`),type:`file`,state:errorToState(n),from:e.method,details:`Task could not be constructed: `+errorToS2(n),url:assetPath(r)})}catch(n){this.#n.warn(`Could not write task construction failure report`,{method:e.method,producerName:r,producerId:a,error:n})}}return(s.length>0||!c)&&(this.#m=0),this.add(...s),c&&this.#x(),s});#x(){++this.#m>MaxBarrenRefills?this.#m===MaxBarrenRefills+1&&this.#n.warn(`Pausing construction-failure refills: no task could be constructed from the last ${MaxBarrenRefills} allocations. Producers will still be polled on the usual interval.`,{producers:[...this.#f].map(e=>e.name)}):setUnrefTimeout(()=>void this.pullFromProducers(),0)}add(...e){e.length>0&&this.#C();for(let n of e){let e=TaskImpls[n.method].awaitNativeCompletion===!0?0:Settings2.taskMaxDurationMs.valueOrDefault;e>0&&(n.onProgressChanged=()=>n.d.setTimeout(e)),n.d.promise.then(e=>{this.#e++,this.recentlyProcessed.push(n);let r={task:n,result:e,elapsedMs:roundMs(n.d.elapsedMs)};this.#n.info(`Completed task`,r),gt(this.#e,bailAfterTaskCount())&&exit({reason:PS_BAIL_AFTER_TASK_COUNT}),this.ee.emitSync(`resolved`,r)},e=>{if(isTimeoutError(e)){this.#t++,n.abortable.abort(`Task timed out after `+roundMs(n.d.elapsedMs)+`ms`),this.#n.warn(`Task timed out`,{task:n,timeoutCount:this.#t,elapsedMs:roundMs(n.d.elapsedMs)});let e=Settings2.syncMaxTimeoutsBeforeRestart.valueOrDefault;e>0&&this.#t>=e&&!isTest()&&(this.#n.warn(`Proactive restart: syncMaxTimeoutsBeforeRestart exceeded`,{timeoutCount:this.#t,maxTimeouts:e}),exit({reason:`proactive restart: ${this.#t} task timeouts (max ${e})`,status:0}))}let r=isIgnorableError(e)===!0||isCorruptMediaError(e);this.#n.log(r?`info`:`warn`,`Rejected task`,{task:n,error:e}),this.ee.emitSync(`rejected`,{task:n,error:e})}).finally(()=>{try{n.producerName!=null&&n.producerId!=null&&this.#y(n.producerName)?.onTaskComplete?.(n.producerId)}catch(e){this.#n.warn(`onTaskComplete failed`,{task:n,error:e})}ee().emitSyncRateLimited(`syncStateChanged`)});let r=getTaskPath(n.args),a=r==null?void 0:ProblematicFile.getStatus(r);if(r!=null&&a?.blocked===!0){let e=a.expiresAt??1/0;this.#n.warn(`Deferring problematic task`,{task:n,path:r,notBefore:e}),n.producerName!=null&&n.producerId!=null&&this.#y(n.producerName)?.onTaskDeferred?.(n.producerId,e,r);try{syncReport().onProgress({path:r,type:`file`,state:`timeout`,from:n.method,details:`Skipped: this file timed out recently. `+(e===1/0?`It will not be retried until its problematic-file block is cleared.`:`It will be retried after `+fmtIsoDateTimeSpace(e)+`.`),url:assetPath(getTaskAssetId(n.args))})}catch(e){this.#n.warn(`Could not record the deferral in the sync report`,{task:n,path:r,error:e})}n.d.reject(new DeferredTaskError(r,e))}else this.ee.emit(`admitted`,{task:n}),this.p.enqueueDeferred(n.d,()=>{e>0&&n.d.setTimeout(e);let r=n.run();this.#s.add(n);let a=()=>{this.#s.delete(n),this.#c.delete(n),this.#T()};return r.then(a,a),r},{userInitiated:n.source===`user`})}e.length>0&&ee().emitThrottled(`syncStateChanged`)}async#S(){this.isIdle()&&await this.#w()&&this.hasTimer()&&(this.#n.debug(`Idling down: pausing TaskList and StallWatcher intervals`),this.pauseInterval(),this.#r.pauseInterval())}#C(){this.hasTimer()||(this.#n.debug(`Resuming TaskList and StallWatcher intervals`),this.resumeInterval(),this.#r.resumeInterval())}async#w(){for(let e of this.#f)if(!await e.isIdle())return!1;return!0}async awaitQuiescent(){let e=0,n=2;for(;!this.ended;){await this.p.awaitDrain();for(let e of this.#f)e.notifyWorkAvailable?.();let n=await this.pullFromProducers(),r=await this.#w();if(isEmpty(n)&&this.p.isIdle()&&r){if(e++,this.#n.debug(`awaitQuiescent: idle observation`,{idleCounter:e,requiredIdleCount:2}),e>=2)return}else e=0;await delay(500)}}async awaitLowWaterMark(){return this.p.awaitLowWaterMark()}async awaitProducersHeld(){if(!isPausedFor(`maintenance`))throw Error(`awaitProducersHeld() requires the maintenance reason`);await this.pullFromProducers(),await Promise.all([...[...this.#f].map(e=>e.awaitDetachedWork?.(this.#d)),...this.#u])}runningBackgroundTaskCount(){return count(this.#s,e=>e.source!==`user`&&!this.#c.has(e))}awaitBackgroundTasksFinished(){return this.runningBackgroundTaskCount()===0?Promise.resolve():this.#l??=new Latch}#T(){this.#l!=null&&this.runningBackgroundTaskCount()===0&&(this.#l.resolve(),this.#l=void 0)}stopWaitingForStuckWork(){for(let e of this.#s)e.d.isRejected&&isTimeoutError(e.d.error)&&this.#c.add(e);this.#u.clear(),this.#d=performance.now(),this.#T()}taskCount(){return this.p.unsettledCount()}isIdle(){return this.p.isIdle()}pendingWorkCount(){return this.p.notStartedCount()}blockedPendingWorkCount(){let e=this.p.runningSerialIds;return count(this.p.deferreds,n=>n.serialIds.some(n=>e.has(n)))}capacity(e){return this.p.enqueueCapacity(e)}hasCapacity(e){return this.capacity(e)>0}currentTasks(){return this.p.runningJobs.map(e=>e.d.payload)}inPlaySerialIds(){let e=new Set;for(let n of this.p.deferreds)for(let r of n.serialIds??[])e.add(r);return e}unsettledTasksFor(e){return this.p.deferreds.filter(n=>n.payload?.producerName===e.name).map(e=>e.payload)}#E(){return this.#i.limit(this.#g())}state(){let e=this.#E();return{...this.p.stats(),maxConcurrency:e,freeSlots:Math.max(0,e-this.p.runningCount()),runningJobDetails:this.#D(),isIdle:this.isIdle(),capacity:this.capacity(),taskCount:this.taskCount(),concurrency:this.#_(),freeSpace:libraryFreeSpaceState(),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map(e=>e.toString())}}#D(){return this.p.runningJobs.map(e=>{let n=e.d.payload;return{name:e.d.name,startedAt:e.d.startedAt,elapsedMs:e.d.elapsedMs,path:n==null?void 0:getTaskPath(n.args),liveProgress:n?.liveProgress}})}},import_promises36=require("node:fs/promises"),logger156=defer(()=>mkLogger(`db.DbBackupCold`));async function dbBackupCold_(e,n,r){await removeDbDirOtherAccess_(await n.mkdirp_(),r);let a=[],o=[];try{for(let r of sqliteFiles(e,{includeShm:!1})){let e=n.join(r.base).wip();a.push(e),o.push(r.copyFile_(e,{skipProgressWatchdog:!0}))}await Promise.all(o);let s=await Promise.all(a.map(e=>e.unwip_()));return await removeDbOtherAccess_(n.join(e.base),r),logger156().tap({msg:`completed`,level:`info`,result:s,meta:{srcDbFile:e,destDir:n}})}catch(e){throw await Promise.all(a.map(e=>e.unlink())),e}}var _dbSetupErrors=new Map,listeners=[];function dbSetupErrors(){return[..._dbSetupErrors.keys()]}function addDbSetupError(e){if(isError(e)||!blank(e)){_dbSetupErrors.set(errorToS2(e),e);for(let e of listeners)e()}}function clearDbSetupErrors({notifyListeners:e=!0}={}){if(_dbSetupErrors.clear(),e)for(let e of listeners)e()}function hasDbSetupErrors(){return _dbSetupErrors.size>0}var import_node_crypto9=require("node:crypto"),import_promises35=require("node:fs/promises"),import_node_os21=require("node:os"),import_node_stream8=require("node:stream");function computeSizeBasedTimeout({sizeBytes:e,minTimeoutMs:n=12e4,bytesPerSecond:r=1048576}){if(!gt0(e))return n;let a=Math.ceil(e/r*1e3*4);return Math.max(n,a)}var logger157=defer(()=>mkLogger(`db.DbRetries`));function handleDbRetries_(e,n,r,a){let o=performance.now(),s=0,c=o+Settings2.dbMaintenanceTimeoutMs.valueOrDefault;return time({name:e,p:async()=>{for(;performance.now()<c;)try{return await r(n())}catch(n){if(isRetriableError(n)===!1||!isSqliteBusyError(n)||performance.now()>=c)throw logger157().error(e+`: Caught db error. Not retrying.`,{error:n}),n;{let r=randomInt(500,1500)*++s;logger157().warn(e+`: Caught db error. Retrying in `+r+`ms.`,{name:e,error:n}),a?.(),await delay(r)}}return n().close(),logger157().throw(e+`: handleDbRetries(): timeout after `+Settings2.dbMaintenanceTimeoutMs.valueOrDefault+`ms`)}})}var RepairModes=strEnum(`dump`,`recover`);async function withDb(e,n,r=Settings2.dbBusyTimeoutMs.valueOrDefault){let a=lazy(()=>mkdb_({nativePath:toS(e),timeoutMs:r}));try{return await n(a)}finally{a.prior()?.close()}}var logger158=lazy2(()=>mkLogger(`db.SQLite`));async function sqlite({dbFile:e,sql:n,args:r,timeoutMs:a=1*minuteMs}){let o=await elapsedAsync(stdout_(await sqliteNativePath_(),[`-init`,import_node_os21.devNull,...toA(r),e.nativePath,n],{timeoutMs:a}));return logger158().debug(`sqlite(`+n+`) on `+e+` in `+o.elapsedMs+`ms`,o.result),o.result}var BackupCopyTimeoutMs=8*minuteMs;async function backupDbFile_(e,n){if(!gt0(await e.size_()))throw Error(`Cannot backup empty database file: `+e);await n.applyWip_({fn_:n=>sqlite({dbFile:e,args:[`-readonly`],sql:`VACUUM INTO `+dbValueToEscapedString(n.nativePath),timeoutMs:BackupCopyTimeoutMs}),timeoutMs:BackupCopyTimeoutMs+minuteMs,skipFsLock:!0,preserveDestOnError:!0})}function pragmaOrThrow_({db:e,pragma:n,okResult:r}){logger158().debug(`pragmaOrThrow_()`,{db:dbToPath(e),db_open:e?.isOpen,pragma:n,okResult:r});let a=isString(r)?e.pragma(n,{simple:!0}):e.pragma(n);eql(a,r)||logger158().throw(`${n} failed for ${dbToPath(e)}: ${stringify({result:a})}`)}function dbToPath(e){return ellipsizePath({p:e.location()??`:memory:`,maxLength:80})}function quickCheck_(e){return pragmaOrThrow_({db:e,pragma:`quick_check`,okResult:`ok`})}function integrityCheck_(e){return pragmaOrThrow_({db:e,pragma:`integrity_check`,okResult:`ok`})}function foreignKeyCheckStrict_(e){let n=toA(e.pragma(`foreign_key_check`));n.length>0&&logger158().throw(`Foreign key violations detected`,{badRowsCount:n.length,badRows:n})}function foreignKeyCheckAndRepair_(e){let n=toA(e.pragma(`foreign_key_check`));n.length>Settings2.dbInvalidFKThreshold.valueOrDefault&&logger158().throw(`foreignKeyCheckAndRepair_(): too many invalid foreign keys to repair`,{dbInvalidForeignKeyThreshold:Settings2.dbInvalidFKThreshold.valueOrDefault,badRowsCount:n.length,badRows:n});for(let r of n)logger158().warn(`foreignKeyCheckAndRepair_(): deleting row with invalid foreign key`,{row:r}),e.prepare(`DELETE FROM ${escapeIdentifier(r.table)} WHERE rowid = ?`).run(r.rowid)}async function verifyDb_(e){await handleDbRetries_(`db.quickCheck`,e,quickCheck_),await delay(1),await handleDbRetries_(`db.integrityCheck`,e,integrityCheck_),await delay(1),await handleDbRetries_(`db.foreignKeyCheck`,e,foreignKeyCheckAndRepair_)}function verifyDbFile_(e){return withDb(e,verifyDb_,commandTimeoutMs())}async function invalidateOwnerSessionsInDbFile_(e){await withDb(e,async e=>{e().transaction(()=>{let n=e().prepare(`SELECT generation FROM LibrarySignIn WHERE singleton = 1`).pluck().get();if(n==null)throw Error(`Restored LibrarySignIn singleton is missing`);let r;do r=(0,import_node_crypto9.randomInt)(1,2**48);while(r===n);e().prepare(`UPDATE LibrarySignIn SET generation = :generation WHERE singleton = 1`).run({generation:r}),e().prepare(`DELETE FROM Session`).run();for(let n of[`EmailSignInChallenge`,`OidcSignInTransaction`])e().prepare(`DELETE FROM ${n}`).run()})()},commandTimeoutMs())}var IgnorableDumpErrorRe=/no such table: sqlite_\w+/i,LostAndFound=`lost_and_found`,RepairCommands={dump:`.dump`,recover:`.recover --ignore-freelist --lost-and-found ${LostAndFound}`},TableRowCountsSql=`SELECT s.name AS name, sum(d.ncell) AS n
|
|
757
|
+
FROM sqlite_schema AS s JOIN dbstat AS d ON d.name = s.name
|
|
758
|
+
WHERE s.type = 'table' AND d.pagetype = 'leaf'
|
|
759
|
+
GROUP BY s.name`,MinKeptRowFraction=.9;async function sqliteJson(e){let n=await sqlite({...e,args:[`-json`]});return blank(n)?[]:JSON.parse(n)}async function tableRowCounts(e,n){let r=await sqliteJson({dbFile:e,sql:TableRowCountsSql,timeoutMs:n});return new Map(r.map(e=>[e.name,e.n]))}async function dropLostAndFound(e,n){let[{tables:r}]=await sqliteJson({dbFile:e,sql:`SELECT count(*) AS tables FROM sqlite_schema WHERE name = '${LostAndFound}'`,timeoutMs:n});if(r===0)return 0;let[{orphanedRows:a}]=await sqliteJson({dbFile:e,sql:`SELECT count(id) AS orphanedRows FROM ${LostAndFound}; DROP TABLE ${LostAndFound}`,timeoutMs:n});return a}function spawned(e){return new Promise((n,r)=>{e.once(`spawn`,()=>n()),e.once(`error`,r)})}function assertKeptRows({readable:e,kept:n,orphanedRows:r}){let a=[];for(let[r,o]of e){let e=n.get(r)??0;e<o*MinKeptRowFraction&&a.push(`${r} kept ${e} of ${o} rows`)}if(r>0&&a.push(`${r} rows could not be matched to a table`),a.length>0)throw Error(`The rebuilt database is missing rows the original still had: `+a.join(`; `))}async function repairDbFile_(e,n=RepairModes.recover,{holdsSignInState:r}){let a=PosixFile.for(e),o=await a.parent().join(`db-`+n,filestamp()).mkdirp_();await removeDbDirOtherAccess_(o,r);let s=o.join(a.base);logger158().info(`repairDbFile_(${a} -> ${s})`);let c=await sqliteSizeBytes(a),l=computeSizeBasedTimeout({sizeBytes:c,bytesPerSecond:1048576,minTimeoutMs:Settings2.dbMaintenanceTimeoutMs.valueOrDefault}),u,d;try{let e=await tableRowCounts(a,l),o=await sqliteNativePath_(),f=new PushProgressObserver({path:toS(a),op:`Repairing your database`},2*c),h=new Latch,_=new Latch;if(u=spawn(o,[`-init`,import_node_os21.devNull,a.nativePath,RepairCommands[n]],l,{stdio:[`ignore`,`pipe`,`ignore`]}),u.on(`exit`,()=>_.resolve()),await spawned(u),u.on(`error`,e=>void h.reject(e)),u.stdout==null)throw Error(`dumpProc.stdout is unexpectedly null`);if(u.stdout.on(`error`,e=>{let r=toS(e);IgnorableDumpErrorRe.test(r)?logger158().info(`repairDbFile_(): ignoring stdout error`,{error:r}):h.reject(Error(`sqlite `+n+` failed: `+r))}),d=spawn(o,[`-init`,import_node_os21.devNull,s.nativePath],l,{stdio:[`pipe`,`ignore`,`ignore`]}),d.on(`exit`,()=>h.resolve()),await spawned(d),d.on(`error`,e=>void h.reject(e)),d.stdin==null)throw Error(`load.stdin is unexpectedly null`);d.stdin.on(`error`,e=>void h.reject(e));let y=new import_node_stream8.Transform({transform(e,n,r){f.incrProgress(e.length),r(null,e)}});y.on(`error`,e=>void h.reject(e)),u.stdout.pipe(y).pipe(d.stdin),await h,await _,logger158().info(`repairDbFile_(): recovered to ${s}.`),await removeDbOtherAccess_(s,r);let x=await dropLostAndFound(s,l);await verifyDbFile_(s),assertKeptRows({readable:e,kept:await tableRowCounts(s,l),orphanedRows:x}),r&&await invalidateOwnerSessionsInDbFile_(s),logger158().info(`repairDbFile_(): ${s} is valid, finishing repair.`);let C=await thenCollect(sqliteFiles(a),e=>e.renameYMDHMS_({subdir:`needed-repair`}));for(let e of C)await removeDbOtherAccess_(e,r);{let e=a.parent().join(s.base);try{await s.mv_(e)}catch(n){logger158().warn(`repairDbFile_(): mv_ failed for ${s.base}, falling back to copy`,{mvErr:n}),await(0,import_promises35.copyFile)(s.nativePath,e.nativePath),await s.unlink(`trace`)}}let w=C.find(e=>e.ext===`.db`||e.ext.startsWith(`.sqlite`));if(w==null)throw Error(`repairDbFile_(): Expected .db/.sqlite file in renamed files: ${stringify(C)}`);return w}catch(e){return logger158().throw(`failed to recover DB via sqlite3 .${n}. Please see https://photostructure.com/faq/restore-db-from-backup/ `+FatalErrorFlag,{error:e})}finally{u?.kill(),d?.kill()}}var NoWriteLock=Symbol(`NoWriteLock`),NoOp3=Symbol(`NoOp`),Contested=Symbol(`Contested`),BackupGenerationNameRegex=/^\d{8}-\d{6}$/,ModelDbJanitor=class e extends EndableWrapper{#e;#t;#n;static for(n){return new e(n)}constructor(e){super(`db.DbModelJanitor`,()=>this.#r(),EndableRanks.db,5*minuteMs),this.#t=e,this.#e=e.openLock,this.#n=mapSchemas(n=>{let r={writeCount:0,dataVersion:void 0,connectionReset:!1};return e.dbs[n].onClose(()=>{r.dataVersion=void 0,r.connectionReset=!0}),r})}get db(){return this.#t.db}get libraryDbFile(){return this.#t.libraryDbFile}get backupDir(){return this.#t.libraryDbBackupDir}get useReplica(){return this.#t.useReplica}async backupIfOwner_(e){return await this.#e.isOwner_()?this.backup_(e):NoOp3}async#r(){return this.#t.teardown_(()=>this.backupIfOwner_(!0))}forceBackup_(){return this.backup_(!0)}#i=lazy2(()=>{let e=dbSetupErrors();isEmpty(e)||this.logger.warn(`backup_(): db has setup errors, skipping backup`,{errors:e})},hourMs);#a(e){let n=this.#t.dbs[e],r=this.#n[e],a=n.db.pragma(`data_version`,{simple:!0});return{own:r.connectionReset||n.writeCount!==r.writeCount,peer:a!==r.dataVersion,dataVersion:a,writeCount:n.writeCount}}#o(e,n){let r=this.#n[e];r.writeCount=n.writeCount,r.dataVersion=n.dataVersion,r.connectionReset=!1}async#s({backupDir:e,dbBase:n,retentionCount:r,retainedBackup:a}){try{let o=[];for(let r of await e.children_())BackupGenerationNameRegex.test(r.base)&&await r.join(n).isNonEmptyFile()&&o.push(r);o.sort((e,n)=>e.base.localeCompare(n.base));let s=new Set;a!=null&&s.add(a.parent().nativePath);for(let e=o.length-1;e>=0&&s.size<r;e--)s.add(o[e].nativePath);let c=0;for(let e of o)if(!s.has(e.nativePath))try{await e.rmrf_(),c++}catch(n){this.logger.warn(`Failed to prune completed database backup`,{file:e,error:n})}c>0&&this.logger.info(`Pruned completed database backups`,{pruned:c,retained:r})}catch(n){this.logger.warn(`Failed to inspect completed database backups`,{file:e,error:n})}}async#c(e,n){let r=this.#t.dbs[e],a=this.#t.libraryDbFiles[e];return r.backup_(dbBackupDir(a).join(n),!this.useReplica,async e=>{try{this.useReplica&&await dbBackupCold_(e,a.parent(),r.ownerOnly),r.trait.holdsSignInState&&await invalidateOwnerSessionsInDbFile_(e)}catch(n){throw await e.parent().rmrf_(),n}})}async#l(e,n){let r=this.#t.dbs[e],a=this.#t.libraryDbFiles[e];await this.#s({backupDir:dbBackupDir(a),dbBase:a.base,retentionCount:Settings2.dbBackupRetentionCount.valueOrDefault,retainedBackup:n}),this.useReplica&&await this.#s({backupDir:r.localBackupDir(),dbBase:r.dbFile.base,retentionCount:1})}async#u(e){let n=this.#t.dbs[e],r=this.#t.libraryDbFiles[e],a=n.localBackupDir();await a.mkdirp_();let o=PosixFile.for(await(0,import_promises36.mkdtemp)(a.nativePath+`/peer-`));try{return await dbBackupCold_(await n.backup_(o,!0),r.parent(),n.ownerOnly),this.logger.info(`backup_(): replica copyback successful`,{libraryDbFile:r}),r}finally{await o.rmrf_()}}async backup_(e=!1){if(hasDbSetupErrors())return this.#i(),NoOp3;let n=n=>e||n.own||n.peer;return Schemas.values.some(e=>n(this.#a(e)))?await withLock_({file:this.backupDir,timeoutMs:BackupCopyTimeoutMs+2*minuteMs,noopIfContested:!e},async()=>{let n=mapSchemas(e=>this.#a(e));if(e||Schemas.values.some(e=>n[e].own))return time({name:`db.backup`,p:async()=>{let e=filestamp(),r={};try{for(let n of Schemas.values)r[n]=await this.#c(n,e)}catch(e){for(let e of Object.values(r))await e.parent().rmrf_();throw e}for(let e of Schemas.values)await this.#l(e,r[e]),this.#o(e,n[e]);return this.logger.info(`backup_(): backup successful`,{generations:r}),r.models}});let r=NoOp3;for(let e of Schemas.values)if(n[e].peer){if(this.useReplica){let n=await this.#u(e);r===NoOp3&&(r=n)}this.#o(e,n[e])}return r})??Contested:(this.logger.debug(`backup_(): no update to any db since last backup`),NoOp3)}},DbMaintenanceDeadlineMs=5*minuteMs,DbVacuumFreelistFraction=.25,DbCliBusyTimeoutMs=secondMs,CheckpointTimeoutMs=10*minuteMs,VacuumTimeoutMs=30*minuteMs,MaintenanceWindowEnded=`maintenance window ended`,DbMaintenanceIntervalMs=hourMs,cliWriterStep,DbMaintenanceWindow=class e extends EndableInterval{#e;#t;#n;#r;#i;#a=0;#o;#s=hourlyErrorReporter(`Library database checkpoint failed`);#c={vecOptimize:hourlyErrorReporter(`Library database sqlite-vec optimize failed`),vacuum:hourlyErrorReporter(`Library database VACUUM failed`),optimize:hourlyErrorReporter(`Library database optimize failed`),backup:hourlyErrorReporter(`Scheduled database backup failed`),passive:this.#s,truncate:this.#s};static for({janitor:n,checkpointer:r,deadlineMs:a=DbMaintenanceDeadlineMs}){return new e(n,r,a)}constructor(e,n,r){super({name:`db.DbMaintenanceWindow`,callback:()=>this.run().catch(e=>onError(e,{fatal:!1})),intervalMs:DbMaintenanceIntervalMs,rank:EndableRanks.service,endTimeoutMs:5*minuteMs,onEnd:()=>(this.#r?.resolve(),this.#i?.result)}),this.pauseInterval(),this.#e=e,this.#t=n,this.#n=r}runAfterSync(){return this.#l(`schedule`,!0)}onTaskSettled(){if(!(++this.#a<Settings2.dbMaintenanceEveryTasks.valueOrDefault))return this.#a=0,this.run(`tasks`)}run(e=`schedule`){return this.#l(e,!1)}runWithWriterLockHeld(e){let n=this.#u(async()=>{let n=await this.#p(()=>this.#x(e));if(!n.drained)throw Error(n.skipReason);return n.value});return this.#d({trigger:`writer`,result:n}),n}#l(e,n){let r=this.#i;if(!n&&r!=null&&r.trigger!==`writer`&&(r.trigger===`schedule`||e===`tasks`))return r.result;let a=this.#u(()=>this.#f(e,n));return this.#d({trigger:e,result:a}),a}#u(e){return(this.#i?.result??Promise.resolve()).then(e,e)}#d(e){this.#i=e;let n=()=>{this.#i===e&&(this.#i=void 0)};e.result.then(n,n)}async#f(e,n){this.#a=0;let r=[],a,o=!1;if(isPaused())a=`sync is paused: `+pauseReasons().join(`, `);else{let s=await this.#p(async()=>{await this.#g(r),await this.#_(r),await this.#S(r,`optimize`,async()=>{let e=this.#e.db;return await optimize(e.db),await maybeResizeCacheAndMmap(e.db,e.dbFile.nativePath),{outcome:`ran`,detail:`Query planner statistics updated`}}),e===`schedule`&&await this.#v(r,n),await this.#y(r)});if(s.drained)return{trigger:e,drained:!0,steps:r};({skipReason:a,missedDeadline:o}=s)}return this.logger.log(o?`warn`:`info`,`Skipping VACUUM, optimize, and checkpoints until the next window`,{trigger:e,skipReason:a,deadlineMs:this.#n}),r.push(...skipped([`vecOptimize`,`vacuum`,`optimize`],a)),e===`schedule`&&await this.#v(r,n),r.push(...skipped([`passive`,`truncate`],a)),{trigger:e,drained:!1,steps:r}}async#p(e){pause(!0,`maintenance`);try{let n=await this.#h();if(n==null)return{drained:!0,value:await e()};let r=!this.#m();return r&&TaskList.instance().stopWaitingForStuckWork(),{drained:!1,missedDeadline:r,skipReason:r?`${n} outlasted the maintenance deadline`:MaintenanceWindowEnded}}finally{pause(!1,`maintenance`),TaskList.instance().pullFromProducers()}}#m(){return this.ended||ending()}async#h(){let e=performance.now()+this.#n,n=TaskList.instance(),r=this.#r=new Latch;this.#m()&&r.resolve();let a=async n=>await thenOrTimeout(Promise.race([n.then(()=>!0),r.then(()=>!1)]),Math.max(1,e-performance.now()))===!0;try{return await a(n.awaitProducersHeld())?await a(n.awaitBackgroundTasksFinished())?void 0:`running tasks`:`the producer hold`}finally{r.resolve(),this.#r=void 0}}async#g(e){await this.#S(e,`vecOptimize`,async()=>{if(!isVec0Available())return{outcome:`skipped`,detail:`sqlite-vec is unavailable`};let e=this.#e.db.db,n=[],r=!1;for(let{tableName:a}of getVectorTables()){let{slots:o,live:s,reclaimable:c}=vectorTableSlots(e,a),l=`${a}: optimize would free ${c} of ${o} slots (${s} live)`;if(c===0||c<o*DbVacuumFreelistFraction)n.push(l);else{if(!optimizeVectorTable(e,a))throw Error(`sqlite-vec optimize failed: `+l);r=!0,n.push(`Optimized `+l)}}return{outcome:r?`ran`:`skipped`,detail:n.join(`; `)}})}async#_(e){await this.#S(e,`vacuum`,async()=>{let e=this.#e.db.db,n=e.pragma(`page_count`,{simple:!0}),r=e.pragma(`freelist_count`,{simple:!0}),a=`${r} of ${n} pages free`;return r<=n*DbVacuumFreelistFraction?{outcome:`skipped`,detail:a}:(await this.#x(()=>sqlite({dbFile:this.#e.db.dbFile,args:[`-cmd`,`.timeout `+DbCliBusyTimeoutMs,`-cmd`,`PRAGMA journal_size_limit = 0`],sql:`VACUUM`,timeoutMs:VacuumTimeoutMs})),{outcome:`ran`,detail:`Vacuumed: `+a})})}async#v(e,n){let r=this.#e.useReplica?`dbReplicaBackupIntervalMs`:`dbBackupIntervalMs`,a=Settings2[r].valueOrDefault-DbMaintenanceIntervalMs/2;!n&&this.#o!=null&&performance.now()-this.#o<a?e.push({step:`backup`,outcome:`skipped`,detail:r+` hasn't passed since the last backup`}):await this.#S(e,`backup`,async()=>{let e=performance.now(),n=await this.#e.backupIfOwner_();return n!==Contested&&n!==NoWriteLock&&(this.#o=e),n===NoOp3?{outcome:`skipped`,detail:`no writes since the last backup`}:n===Contested||n===NoWriteLock?{outcome:`skipped`,detail:`another backup holds the lock`}:{outcome:`ran`,detail:`Database backup completed`}})}async#y(e){this.#m()?e.push(...skipped([`passive`,`truncate`],MaintenanceWindowEnded)):await this.#t.hold(async()=>{let n=!1;await this.#S(e,`passive`,async()=>{let[e,r,a]=await this.#b(`PASSIVE`);return n=e===0&&r===a,{outcome:`ran`,detail:`PASSIVE checkpoint copied ${a} of ${r} WAL frames`}}),n?await this.#S(e,`truncate`,async()=>{let e=await this.#x(()=>this.#b(`TRUNCATE`));if(e[0]===1)return{outcome:`skipped`,detail:`another connection holds the WAL or the writer lock`};if(e.join(`|`)!==`0|0|0`)throw Error(`TRUNCATE checkpoint returned `+e.join(`|`));return{outcome:`ran`,detail:`TRUNCATE checkpoint emptied the WAL`}}):e.push(...skipped([`truncate`],`a reader holds frames PASSIVE couldn't copy`))})}async#b(e){let n=await sqlite({dbFile:this.#e.db.dbFile,args:[`-cmd`,`.timeout `+DbCliBusyTimeoutMs],sql:`PRAGMA wal_checkpoint(${e})`,timeoutMs:CheckpointTimeoutMs}),r=n.trim().split(`|`).map(Number);if(r.length!==3||r.some(isNaN))throw Error(`Unexpected wal_checkpoint(${e}) output: ${n}`);return r}async#x(e){let n=e();try{return await n}finally{}}async#S(e,n,r){if(this.#m())e.push(...skipped([n],MaintenanceWindowEnded));else try{let a=`ran`,o=await syncReport().wrapSystemOp_({from:`DbMaintenance:`+n,fn_:async()=>{let e=await r();return a=e.outcome,e.detail}});e.push({step:n,outcome:a,detail:o})}catch(r){this.logger.warn(n+` failed`,{error:r}),this.#c[n](r),e.push({step:n,outcome:`failed`,detail:String(r)})}}};function skipped(e,n){return e.map(e=>({step:e,outcome:`skipped`,detail:n}))}var import_node_crypto10=require("node:crypto"),ModeCount=7,logger159=defer(()=>mkLogger(`migrations.FixRootTags`));function fix_root_tags(e){for(let n of e.prepare(`SELECT id, parentId, _path FROM Tag WHERE id = parentId`).iterate())logger159().warn(`fix_root_tags(): broken tag`,{broken:n}),countChars(n._path,TagSep)<2&&e.prepare(`UPDATE Tag set parentId = null where id = ?`).run(n.id)}var import_exiftool_vendored25=require("exiftool-vendored"),logger160=defer(()=>mkLogger(`migrations.SchemaV3Backfill`));function schemaV3Backfill(e){if(logger160().info(`Starting schema v3 backfill migration`),e.prepare(`SELECT COUNT(*) FROM pragma_table_info('AssetFile') WHERE name = 'uri'`).pluck().get()===0){logger160().info(`Schema is already v3, skipping backfill migration`);return}e.function(`extractUriDir`,{deterministic:!0},e=>e==null||e===``?null:extractUriDirectory_(e)),e.function(`extractBasename`,{deterministic:!0},e=>e==null||e===``?null:extractUriBasename_(e)),e.function(`extractAuthority`,{deterministic:!0},e=>e==null||e===``?null:extractUriAuthority_(e)),logger160().info(`Populating DirUri table`);let n=e.prepare(`SELECT COUNT(*) FROM AssetFile WHERE uri IS NOT NULL`).pluck().get();logger160().info(`Processing ${n} AssetFile URIs`),e.exec(`
|
|
760
|
+
INSERT INTO DirUri (uri)
|
|
761
|
+
SELECT DISTINCT extractUriDir(uri) as uri
|
|
762
|
+
FROM AssetFile
|
|
763
|
+
WHERE uri IS NOT NULL
|
|
764
|
+
ORDER BY uri
|
|
765
|
+
ON CONFLICT (uri) DO NOTHING;
|
|
766
|
+
`);let r=e.prepare(`SELECT COUNT(*) FROM DirUri`).pluck().get();logger160().info(`Created ${r} DirUri entries`),logger160().info(`Populating Volume table from AssetFile URIs and mountpoints`),e.exec(`
|
|
767
|
+
INSERT INTO Volume (authority, mountPoint, lastSeenAt)
|
|
768
|
+
SELECT
|
|
769
|
+
extractAuthority(uri) as authority,
|
|
770
|
+
mountpoint as mountPoint,
|
|
771
|
+
MAX(updatedAt) as lastSeenAt
|
|
772
|
+
FROM AssetFile
|
|
773
|
+
WHERE uri IS NOT NULL
|
|
774
|
+
AND mountpoint IS NOT NULL
|
|
775
|
+
AND extractAuthority(uri) IS NOT NULL
|
|
776
|
+
AND extractAuthority(uri) != ''
|
|
777
|
+
GROUP BY extractAuthority(uri), mountPoint
|
|
778
|
+
ORDER BY authority, mountPoint;
|
|
779
|
+
`);let a=e.prepare(`SELECT COUNT(*) FROM Volume`).pluck().get();logger160().info(`Created ${a} Volume entries`);let o=new Map;function s(e){return e==null?null:getOrSet(o,e,()=>toNotBlank((0,import_exiftool_vendored25.offsetMinutesToZoneName)(e)))??null}e.function(`getTimezone`,{deterministic:!0},s),logger160().info(`Populating Asset_new table`);let c=e.prepare(`SELECT COUNT(*) FROM Asset`).pluck().get();logger160().info(`Migrating ${c} assets`),e.exec(`
|
|
780
|
+
INSERT INTO Asset_new (
|
|
781
|
+
id, shown, hidden, rating,
|
|
782
|
+
capturedAtLocal, mimetype, durationMs,
|
|
783
|
+
deletedAt, excludedAt, createdAt, updatedAt, updateCount
|
|
784
|
+
)
|
|
785
|
+
SELECT
|
|
786
|
+
a.id, a.shown, a.hidden, a.rating,
|
|
787
|
+
af.capturedAtLocal, af.mimetype, af.durationMs,
|
|
788
|
+
a.deletedAt, a.excludedAt, a.createdAt, a.updatedAt, a.updateCount
|
|
789
|
+
FROM Asset a
|
|
790
|
+
INNER JOIN AssetFile af ON af.assetId = a.id AND af.shown = 1
|
|
791
|
+
WHERE a.shown = 1;
|
|
792
|
+
`),logger160().info(`Creating URI to DirUri mapping`),e.exec(`
|
|
793
|
+
CREATE TEMP TABLE UriToDirUri AS
|
|
794
|
+
SELECT af.id as assetFileId, d.id as dirUriId, extractBasename(af.uri) as basename
|
|
795
|
+
FROM AssetFile af
|
|
796
|
+
INNER JOIN DirUri d ON d.uri = extractUriDir(af.uri)
|
|
797
|
+
WHERE af.uri IS NOT NULL;
|
|
798
|
+
`),logger160().info(`Populating AssetFile_new table`);let l=e.prepare(`SELECT COUNT(*) FROM AssetFile WHERE uri IS NOT NULL`).pluck().get();logger160().info(`Migrating ${l} asset files`);let u=AssetFileFlags.toBit(`forceSync`);e.exec(`
|
|
799
|
+
INSERT INTO AssetFile_new (
|
|
800
|
+
id, assetId, isPrimary, dirUriId, basename,
|
|
801
|
+
mtime, fileSize, mimetype, width, height, rotation, durationMs,
|
|
802
|
+
cameraId, lensId, imageId, sha,
|
|
803
|
+
capturedAtLocal, capturedAtPrecisionMs, capturedAtZone, capturedAtSrc,
|
|
804
|
+
make, model, rating, aperture, focalLength, fps, geohash, iso, shutterSpeed,
|
|
805
|
+
flags, createdAt, updatedAt, updateCount
|
|
806
|
+
)
|
|
807
|
+
SELECT
|
|
808
|
+
af.id, af.assetId, af.shown as isPrimary,
|
|
809
|
+
m.dirUriId, m.basename,
|
|
810
|
+
af.mtime, af.fileSize, af.mimetype, af.width, af.height,
|
|
811
|
+
COALESCE(af.rotation, 0), af.durationMs,
|
|
812
|
+
af.cameraId, af.lensId, af.imageId, af.sha,
|
|
813
|
+
af.capturedAtLocal, af.capturedAtPrecisionMs,
|
|
814
|
+
getTimezone(af.capturedAtOffset), af.capturedAtSrc,
|
|
815
|
+
af.make, af.model, af.rating, af.aperture, af.focalLength, af.fps,
|
|
816
|
+
af.geohash, af.iso, af.shutterSpeed,
|
|
817
|
+
${u}, af.createdAt, af.updatedAt, af.updateCount
|
|
818
|
+
FROM AssetFile af
|
|
819
|
+
INNER JOIN UriToDirUri m ON m.assetFileId = af.id
|
|
820
|
+
WHERE EXISTS (SELECT 1 FROM Asset_new WHERE id = af.assetId);
|
|
821
|
+
`),e.exec(`DROP TABLE UriToDirUri;`),logger160().info(`Replacing tables`),e.exec(`
|
|
822
|
+
DROP TABLE IF EXISTS Asset;
|
|
823
|
+
ALTER TABLE Asset_new RENAME TO Asset;
|
|
824
|
+
|
|
825
|
+
DROP TABLE IF EXISTS AssetFile;
|
|
826
|
+
ALTER TABLE AssetFile_new RENAME TO AssetFile;
|
|
827
|
+
`),logger160().info(`Cleaning up orphaned rows in related tables`);let d=e.prepare(`DELETE FROM AssetRevision WHERE assetId NOT IN (SELECT id FROM Asset)`).run().changes,f=e.prepare(`DELETE FROM AssetTag WHERE assetId NOT IN (SELECT id FROM Asset)`).run().changes;(d>0||f>0)&&logger160().info(`Deleted orphaned rows`,{deletedRevisions:d,deletedTags:f}),logger160().info(`Recreating indexes on renamed tables`),logger160().info(`Schema v3 migration completed successfully`,{assets:e.prepare(`SELECT COUNT(*) FROM Asset`).pluck().get(),files:e.prepare(`SELECT COUNT(*) FROM AssetFile`).pluck().get(),dirPaths:e.prepare(`SELECT COUNT(*) FROM DirUri`).pluck().get(),volumes:e.prepare(`SELECT COUNT(*) FROM Volume`).pluck().get()})}var ValidCapturedAtSrcTypes=new Set([`tags`,`bname+stat`,`path+stat`,`bname`,`path`,`siblings`,`stat`,`unknown`]),CapturedAtSrcAliases={"stat+bname":`bname+stat`,"stat+path":`path+stat`};function parseCapturedAtSrcType(e){if(e==null||e===``)return`unknown`;let n=CapturedAtSrcAliases[e];if(n!=null)return n;if(ValidCapturedAtSrcTypes.has(e))return e;let r=e.indexOf(`(`),a=r>0?e.substring(0,r).trim():e,o=a.indexOf(`:`),s=o>0?a.substring(0,o):a;return CapturedAtSrcAliases[s]??(ValidCapturedAtSrcTypes.has(s)?s:`unknown`)}function parseCapturedAtSrcDetail(e){if(e==null||e===``)return null;let n=e.indexOf(`:`);if(n<=0)return null;let r=e.substring(0,n),a=e.substring(n+1);if(r===`tags`){let e=a.indexOf(` (`);return(e>0?a.substring(0,e):a).trim()||null}return r===`siblings`&&a.trim()||null}function parseCapturedAtSrcZoneSrc(e){if(e==null||e===``||!e.includes(`(`))return null;if(e.includes(`forced)`))return`forced`;if(e.includes(`tz inferred`)||e.includes(`.tz:`))return`siblings`;let n=e.match(/\(zone .+ from (.+)\)/);return n==null?null:n[1]}var TableNames=strEnum(`AssetFile`,`AssetRevision`,`AssetTag`,`ProgressMeta`,`RejectedFile`,`TagHierarchy`,`Asset`,`Tag`,`Volume`,`DirUri`,`Progress`,`Example`,`Heartbeat`,`Operation`,`ShaBlocklist`),LibraryModelNames=Object.freeze(TableNames.values),Vec0TableNames=[`AssetFileHash`],Vec0ShadowSuffixes=[`_info`,`_chunks`,`_rowids`,`_auxiliary`],Vec0ShadowPatterns=[`_vector_chunks`,`_metadatachunks`,`_metadatatext`];function isVec0ShadowTable(e){for(let n of Vec0TableNames){if(Vec0ShadowSuffixes.some(r=>e===n+r))return!0;for(let r of Vec0ShadowPatterns){let a=n+r;if(e.startsWith(a)&&/^\d+$/.test(e.slice(a.length)))return!0}}return!1}function parseSqliteColumn(e){return{name:e.name,type:e.type.toUpperCase().trim().replace(/\s+/g,``),notnull:e.notnull===1,pk:e.pk===1}}function parseTableInfo(e){let n=new MultiMap;for(let r of e)r.tableName.includes(`fts`)||r.tableName.includes(`sqlite_`)||Vec0TableNames.some(e=>r.tableName===e)||isVec0ShadowTable(r.tableName)||blank(r.name)||blank(r.type)||n.add(r.tableName,parseSqliteColumn(r));return n.entriesArray().map(([e,n])=>({tableName:e,columns:n}))}var sql=compressWhitespace(`SELECT m.tbl_name as tableName, p.*`,`FROM sqlite_master AS m`,`JOIN pragma_table_info(m.name) AS p`,`ORDER BY m.tbl_name, p.cid`);function localTableInfo(e){return parseTableInfo(e.prepare(sql).all())}function getColumnInfo(e,n){return e.pragma(`table_info(`+dbValueToEscapedString(n)+`)`).map(parseSqliteColumn)}var logger161=lazy2(()=>mkLogger(`db.DedupeTags`));function mergeTags_(e,n,r){n=toA(n).filter(gt0),isEmpty(n)&&logger161().warn(`mergeTags(): empty tagIds`,{tagIds:n}),logger161().info(`mergeTags() starting`,{tagIds:n});function a(n){return e.prepare(n).run()}let o=e.prepare(normalizeSql(`
|
|
828
|
+
SELECT id, _path, parentId
|
|
829
|
+
FROM Tag
|
|
830
|
+
WHERE id IN (${n.join(`,`)})
|
|
831
|
+
ORDER BY ID`)).all(),s=compactBlanks(o.map(e=>tagPathLeaf(e._path)).sort()),c=o[0],l=o.slice(1),u=c?.id;if(isEmpty(s)||isEmpty(l)||c==null||!gt0(u)){logger161().warn(`mergeTags(): missing winner`,{winner:c,winnerId:u,leafs:s,losers:l});return}let d=splitTagPath(c._path).slice(0,-1),f=[...d,s[0]];c._path=joinTagPath(f),c.parentId=d.length===0?null:e.prepare(`SELECT id from Tag where _path LIKE ?`).pluck().get(joinTagPath(d))??c.parentId,logger161().info(`mergeTags()`,{winner:c,losers:l,winnerTagPath:f,leafs:s});let h=l.map(e=>e.id).join(`,`);a(`UPDATE OR IGNORE AssetTag SET tagId = ${u} WHERE tagId in (${h})`),a(`UPDATE OR IGNORE Tag SET parentId = ${u} WHERE parentId in (${h})`),a(`DELETE FROM AssetTag WHERE tagId in (${h})`),a(`DELETE FROM Tag WHERE id in (${h})`),e.prepare(`UPDATE Tag SET parentId = :parentId, _path = :path, updatedAt = :updatedAt WHERE id = :id`).run({parentId:c.parentId,path:c._path,updatedAt:Date.now(),id:u});let _=e.prepare(`SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE`).all({winnerId:u,like:c._path+`%`});for(let n of _){let r=splitTagPath(n._path).slice(f.length),a=joinTagPath([...f,...r]);n._path!==a&&(logger161().info(`mergeTags(): repairing tag path`,{ea:n,newPath:a}),e.prepare(`UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id`).run({id:n.id,updatedAt:Date.now(),path:a}))}return(r??getColumnInfo(e,`Tag`).some(e=>e.name===`assetCount`))&&a(`UPDATE Tag SET assetCount = NULL WHERE id = `+u),ee().emitSync(`clearDbCache`),logger161().tap({msg:`mergeTags()`,level:`info`,result:{winner:c,losers:l}})}function dedupeTags_(e){let n=new MultiMap;for(let{id:r,_path:a}of e.prepare(`SELECT id, _path FROM Tag ORDER BY id`).iterate())n.add(stripSuffix(toS(a).trim(),TagSep).toLowerCase().normalize(),r);let r=sortBy(n.entriesArray().filter(([,e])=>e.length>1),([e])=>[-countChars(e,TagSep),-e.length,e]);logger161().info(`dedupeTags()`,{dupes:r.entries()});for(let[,n]of r)mergeTags_(e,n);getColumnInfo(e,`Tag`).some(e=>e.name===`_displayPath`)&&rebuildTagDisplayPaths(e)}var logger162=defer(()=>mkLogger(`db.Migrations`)),psnetRe=RegExp(`^(${escapeRegExp(PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`),lowercase_psnet_function=e=>opt(e).filter(isString).flatMap(e=>psnetRe.exec(e)).map(e=>e[1].toLowerCase()+e[2]).getOrElse(()=>e);function splitLabs(e,n=ModeBits){return splitBits(e,n).map(e=>unlabhash(e,n))}function plucklabmodeb6(e,n){return mapGt0(e,()=>map(splitLabs(e,6)[n],e=>toLabhash(e,ModeBits)))}function migrationNameToDate(e){let[n,r,a]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map(e=>toInt(e));return validYMD(n,r,a)?new Date(n,r-1,a):void 0}function tag_path_suffix(e){return e.endsWith(TagSep)?e:e+TagSep}function isoToPrecisionMs(e){return map(isoToDated(e),datedToPrecisionMs)??-1}function migrateAssetFileCoordinates(e){let n=getColumnInfo(e,`AssetFile`);n.some(e=>e.name===`latitude`)||e.exec(`ALTER TABLE AssetFile ADD COLUMN latitude REAL`),n.some(e=>e.name===`longitude`)||e.exec(`ALTER TABLE AssetFile ADD COLUMN longitude REAL`),n.some(e=>e.name===`geohash`)&&(e.function(`_geohashLatitude`,{deterministic:!0},(e=>roundToDecimalPlaces(geoHashToLocation(e,30).lat,GpsCoordinateDecimalPlaces))),e.function(`_geohashLongitude`,{deterministic:!0},(e=>roundToDecimalPlaces(geoHashToLocation(e,30).lon,GpsCoordinateDecimalPlaces))),e.exec(`UPDATE AssetFile SET
|
|
832
|
+
latitude = _geohashLatitude(geohash),
|
|
833
|
+
longitude = _geohashLongitude(geohash)
|
|
834
|
+
WHERE geohash IS NOT NULL
|
|
835
|
+
AND (latitude IS NULL OR longitude IS NULL)`),e.exec(`UPDATE AssetFile SET flags = COALESCE(flags, 0) | `+AssetFileFlags.toBit(`locationIsApproximate`)+` WHERE geohash IS NOT NULL`),e.exec(`ALTER TABLE AssetFile DROP COLUMN geohash`))}var Migrations={fix_root_tags,asset_file_hash0_columns:e=>{let n=getColumnInfo(e,`AssetFile`);for(let r of[`pHash0`,`rHash0`,`wHash0`])n.some(e=>e.name===r)||e.exec(`ALTER TABLE AssetFile ADD COLUMN ${r} TEXT`)},asset_file_coordinates:migrateAssetFileCoordinates,asset_file_location_provenance:migrateAssetFileCoordinates,lowercase_psnet_hostname:e=>{e.function(`lowercase_psnet_hostname`,{deterministic:!0},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},isoToLocal),e.function(`isoToOffsetMinutes`,{deterministic:!0},isoToOffsetMinutes),e.function(`isoToPrecisionMs`,{deterministic:!0},isoToPrecisionMs),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},plucklabmodeb6),times(ModeCount,n=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${n} integer`)),e.exec(`UPDATE AssetFile SET `+times(ModeCount,e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`).join(`, `))},normalize_asset_file_uris:e=>{e.function(`normalizeURI`,{deterministic:!0},normalizeURI);let n=e.prepare(`SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1`).all(),r=[];for(let a of n){let n=toS(a.ids).split(`,`),o=e.prepare(`SELECT id, shown as isPrimary, version, updatedAt FROM AssetFile WHERE id in (`+n.join(`,`)+`)`).all(),s=greatestBy(o,e=>[e.isPrimary,e.version,e.updatedAt]),c=o.filter(e=>e.id!==s?.id);r.push(...c.map(e=>e.id))}for(let n of batches(r,256))e.exec(`DELETE FROM AssetFile WHERE id in (`+n.join(`,`)+`)`);e.exec(`UPDATE AssetFile SET uri = normalizeURI(uri)`)},dedupe_tag_paths:dedupeTags_,suffix_tag_paths:e=>{e.function(`tag_path_suffix`,{deterministic:!0},tag_path_suffix),dedupeTags_(e),e.exec(`UPDATE Tag SET _path = tag_path_suffix(_path)`)},normalize_tag_paths:async e=>{let n=e.prepare(`SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'`).all(),r=getColumnInfo(e,`Tag`).some(e=>e.name===`assetCount`);logger162().info(`normalize_tag_paths():`,{badTags:n});let a=!1;for(let o of n){let n=normalizeTagPath(o._path),s=e.prepare(`SELECT id FROM Tag WHERE _path LIKE ?`).pluck().all(n),c=mergeTags_(e,compact([o.id,...s]),r);gt0(c?.losers.length)&&(logger162().info(`normalize_tag_paths(): at least one tag lost: we need to rebuild asset tag counts`,{result:c}),a=!0)}r&&a&&await rebuildNullTagAssetCounts(e)},drop_tc_tables:e=>{let n=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,r=e.prepare(`SELECT name FROM sqlite_master WHERE type='table'`).pluck().all(),a=r.filter(e=>n.exec(e)!=null);logger162().info(`drop_tc_tables()`,{tables:r,victims:a});for(let n of a)e.exec(`DROP TABLE `+n)},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)`)},rebuild_tag_asset_counts:e=>{if(e.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='TagHierarchy'`).get()!=null)return rebuildTagAssetCounts(e)},create_tag_fts:e=>{e.exec(`DROP TABLE IF EXISTS tag_fts`),e.exec(`CREATE VIRTUAL TABLE tag_fts USING fts5 (root, path, content='', contentless_delete=1, tokenize='unicode61');`)},rebuild_null_island:e=>{let n=e.prepare(`SELECT Tag.id FROM Tag WHERE _path = '`+joinTagPath([`Where`,`Ghana`,`Western`,`Takoradi`])+`'`).pluck().get();n!=null&&e.exec(`UPDATE Asset SET flags = COALESCE(flags, 0) | `+AssetFlags.toBit(`finalize`)+` WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = `+n+`)`)},schema_v3_backfill_nofk:schemaV3Backfill,tag_display_path:e=>{getColumnInfo(e,`Tag`).some(e=>e.name===`_displayPath`)||e.exec(`ALTER TABLE Tag ADD COLUMN _displayPath TEXT`),rebuildTagDisplayPaths(e)},captured_at_src_detail:e=>{let n=getColumnInfo(e,`AssetFile`);n.some(e=>e.name===`capturedAtSrcDetail`)||e.exec(`ALTER TABLE AssetFile ADD COLUMN capturedAtSrcDetail TEXT`),n.some(e=>e.name===`capturedAtZoneSrc`)||e.exec(`ALTER TABLE AssetFile ADD COLUMN capturedAtZoneSrc TEXT`)},captured_at_src_backfill:e=>{e.function(`_parseSrcType`,{deterministic:!0},parseCapturedAtSrcType),e.function(`_parseSrcDetail`,{deterministic:!0},parseCapturedAtSrcDetail),e.function(`_parseSrcZoneSrc`,{deterministic:!0},parseCapturedAtSrcZoneSrc),e.exec(`UPDATE AssetFile SET
|
|
836
|
+
capturedAtSrcDetail = _parseSrcDetail(capturedAtSrc),
|
|
837
|
+
capturedAtZoneSrc = _parseSrcZoneSrc(capturedAtSrc),
|
|
838
|
+
capturedAtSrc = _parseSrcType(capturedAtSrc)
|
|
839
|
+
WHERE capturedAtSrc LIKE '%:%'
|
|
840
|
+
OR capturedAtSrc LIKE '%(%'
|
|
841
|
+
OR capturedAtSrc IN ('stat+bname', 'stat+path')`)}},CreateMigration=`
|
|
842
|
+
CREATE TABLE IF NOT EXISTS migrations (
|
|
843
|
+
id INTEGER NOT NULL PRIMARY KEY,
|
|
844
|
+
name TEXT NOT NULL,
|
|
845
|
+
migration_time INTEGER NOT NULL
|
|
846
|
+
) STRICT
|
|
847
|
+
`,RetiredMigrations={models:[`20190427_force_stable_channel`,`20190522_on_new_exif_uid`,`20190706_on_new_exif_uid`,`20190729_on_new_exif_uid`,`20191008_asset_version_nofk`,`20200127_update_labhash_6_to_10`,`20200128_drop_mode8b6_nofk`,`20201007_user_op`,`20201105_normalize_tag_paths`,`20220923_add_asset_file_mode_scores copy`,`20221031_add_asset_file_hashes_`,`20231116_recount_tag_asset_counts`,`20250423_schema_v3_backfill`,`20250929_sync_file2_indexes`,`20260122_problematic_path`,`20261020_rejected_file_analysis`,`20261024_library_sign_in`,`20261023_ps_uris`],auth:[]};function isDisabledForeignKeysMigration(e){return e.name.includes(`_nofk`)}function migrationError(e,n){let r=isTimeoutError(n)?` timed out.`:` failed`;return new WrappedError(`Migration `+e+r,{cause:n,fatal:!0,ignorable:!1})}var UnknownMigrationsError=class extends WrappedError{};function isUnknownMigrationsError(e){for(let n=e;n!=null;n=n.cause)if(n instanceof UnknownMigrationsError)return!0;return!1}var Migration=class{constructor(e,n,r){this.schema=e,this.db=n,this.dbFile=r,this.logger=mkLogger(`db.Migration(`+stringify({schema:e,db:r.nativePath})+`)`),this.migrationsDir=PosixFile.for(ProjectDir.Migrations()).join(this.schema)}schema;db;dbFile;logger;migrationsDir;async pendingMigrationFiles_(){let e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter(n=>!e.includes(n.name))}fsMigrations_=lazy2(()=>this.migrationsDir.children_(e=>e.isFile&&e.basename.endsWith(`.sql`)).then(e=>e.sort((e,n)=>e.base<n.base?-1:1)).catch(e=>this.logger.throw(`Failed to read migration directory, `+this.migrationsDir+InternalErrorFlag,{error:e})));ensureMigrationTable_=lazy2(()=>{this.db.exec(CreateMigration)});migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare(`SELECT name from migrations`).pluck().all()}unknownMigrations_=lazy2(async()=>{let e=(await this.fsMigrations_()).map(e=>e.name),n=new Set([...e,...RetiredMigrations[this.schema]]);return this.migrationsInDatabase_().filter(e=>(migrationNameToDate(e)??this.logger.throw(`Migration has invalid name (expected YYYYMMDD prefix): `+e+InternalErrorFlag,{migration:e}),!n.has(e)))});assertKnownMigrations_=lazy2(async()=>{let e=await this.unknownMigrations_();if(isNotEmpty(e)){let n=new UnknownMigrationsError(`Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: `+e.join(`,`));throw onError(n),n}});async apply_(e){let n=Settings2.dbMaintenanceTimeoutMs.valueOrDefault,r=getDevEnvFlag(`PS_SLOMO`)?Math.max(n,30*minuteMs):n;return withLock_({file:this.dbFile.sibling(`migrate`),timeoutMs:r},()=>this.#e(e))}async#e(e){try{this.ensureMigrationTable_(),isProd()&&await this.assertKnownMigrations_();let n=[],r=this.db.prepare(`INSERT INTO migrations (name, migration_time) VALUES (?, ?)`);for(let a of await this.pendingMigrationFiles_())await HealthCheck.traceLater_(`Upgrading database (`+a.name+`)`,async()=>{if(getDevEnvFlag(`PS_FAIL_DB_HEALTH_CHECK`))throw Error(`PS_FAIL_DB_HEALTH_CHECK`);getDevEnvFlag(`PS_SLOMO`)&&await delay((0,import_node_crypto10.randomInt)(secondMs,3*secondMs)),await e?.(a),await thenOrTimeoutError2({p:this.applyMigration_(a,r),timeoutMs:Settings2.dbMaintenanceTimeoutMs.valueOrDefault*5}).catch(e=>{throw migrationError(a.name,e)})}),n.push(a.base);return this.logger.info(`Migration complete`,{appliedMigrations:n}),n}catch(e){let n=new WrappedError(`Migrating the `+this.schema+` db failed`,{cause:e});throw addDbSetupError(n),HealthCheck.addError(n),n}}async applyMigration_(e,n){try{let r=performance.now(),a=e.name.replace(/^[\d_-]+/,``),o=Migrations[a],s=isFunction(o);if(isTest()){let n=notBlank(normalizeSql(await e.readText_()));s&&n&&this.logger.throw(`JS migration ${e.name} has executable SQL statements that will be ignored`,{migration:e.baseWithParent,key:a,fatal:!0}),!s&&!n&&this.logger.throw(`Migration ${e.name} has no SQL and no matching Migrations.${a} function`,{migration:e.baseWithParent,key:a,fatal:!0})}let c=s?``:normalizeSql(await e.readText()),l=await this.#t(e,()=>this.#n(async()=>(s?await o(this.db):this.#r(e,c),isDisabledForeignKeysMigration(e)&&foreignKeyCheckStrict_(this.db),n?.run(e.name,Date.now()))));return this.logger.elapsed(`applyMigration() completed`,{elapsedMs:roundMs(performance.now()-r),codeMigration:s,migration:e.baseWithParent}),l}finally{ee().emitSync(`clearDbCache`)}}async#t(e,n){if(!isDisabledForeignKeysMigration(e))return n();this.db.pragma(`foreign_keys = OFF`);try{return await n()}finally{this.db.pragma(`foreign_keys = ON`)}}async#n(e){this.db.exec(`BEGIN IMMEDIATE`);try{let n=await e();return this.db.exec(`COMMIT`),n}catch(e){throw this.db.isTransaction&&this.db.exec(`ROLLBACK`),e}}#r(e,n){if(blank(n))this.logger.info(`No-op migration: `+e);else try{this.db.exec(n)}catch(n){this.logger.throw(`Failed to apply SQL`,{migration:e.baseWithParent,path:e.nativePath,cause:n,fatal:!0})}}},import_node_path72=require("node:path");async function cacheDbDir_(e=Settings2.libraryDir.valueOrDefault,n=Schemas.models){let r=libraryUidStore(e);if(r==null)throw Error(`Library directory is not set`+NoLibraryErrorFlag);let a=await r.readUid_(),o=PosixFile.for(cacheDir_()).join(n+`-live-db`,a);return await o.mkdirp_(),await writeTextfile_(o.join(`README.txt`).nativePath,...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(`
|
|
848
|
+
|
|
849
|
+
`))),o}var logger163=lazy2(()=>mkLogger(`db.SQLiteReadWrite`)),probeCache=new Cache({name:`db.SQLiteReadWrite.probe`,ttlMs:5*minuteMs});async function isDirSQLiteReadWrite(e){try{return await assertDirSQLiteReadWrite_(e),logger163().info(`isDirSQLiteReadWrite(): true`,{dirNativePath:e}),!0}catch(n){return logger163().warn(`isDirSQLiteReadWrite(): false`,{dirNativePath:e,error:n}),!1}}async function assertDirSQLiteReadWrite_(e,n={}){let r=PosixFile.for(e);n.force===!0&&probeCache.delete(r.nativePath);let a=await probeCache.getOrSet(r.nativePath,()=>runProbe_(r));if(a!=null)throw a}async function runProbe_(e){let n=e.child(`.test-`+Radix36.randomChars(12)+SqliteExt),r=null;try{await e.mkdirp_(),r=mkdb_({nativePath:n.nativePath,timeoutMs:1e3,quiet:!0,synchronous:`OFF`}),r.exec(`CREATE TABLE t (s VARCHAR(16) NOT NULL)`);let a=Radix36.randomChars(8);r.prepare(`INSERT INTO t (s) VALUES (?)`).run(a);{let e=r.prepare(`SELECT s FROM t`).all();eql(e,[{s:a}])||logger163().throw(`unexpected rows`,{rows:e})}r.exec(`VACUUM`),r.close(),r=mkdb_({nativePath:n.nativePath,timeoutMs:1e3,quiet:!0,synchronous:`OFF`});{let e=Radix36.randomChars(8);r.prepare(`INSERT INTO t (s) VALUES (?)`).run(e);let n=r.prepare(`SELECT s FROM t ORDER BY s`).pluck().all();eql(n,[a,e].sort())||logger163().throw(`unexpected rows`,{rows:n})}return}catch(e){return toError(e)}finally{try{r?.close()}catch{}await Promise.all(sqliteFiles(n).map(e=>e.unlink(`debug`)))}}var logger164=defer(()=>mkLogger(`db.CheckLocalDbReplica`));async function cacheDbFile_({libraryDir:e=Settings2.libraryDir.valueOrDefault,schema:n=Schemas.models}={}){return(await cacheDbDir_(e,n)).join(SqliteBase)}var import_node_events3=__toESM(require("node:events")),Example=class e extends TimestampedModel{static $tableName=`Example`;static $businessKeys=[`name`];static $booleanFields=[`isExample`];static ee=new import_node_events3.default;name;isExample;$transientField;$beforeSave(){super.$beforeSave(),e.ee.emit(`beforeSave`,this)}$afterSave(){super.$afterSave(),e.ee.emit(`afterSave`,this)}},Heartbeat=class e extends TimestampedModel{static $tableName=`Heartbeat`;static $businessKeys=[`name`];name;static ping(n){return e.ops().upsertOne({name:n})}static assertPing_(n=`ping-`+Date.now()){e.db()??e.$logger().throw(`no library is open`+NoLibraryErrorFlag,{logLevel:`warn`});try{let r=Date.now();e.ping(n);let a=e.ops().findOneBy({name:n});a!=null&&a.name===n&&within(r,Date.now(),a.updatedAt)||e.$logger().throw(`Heartbeat row wasn't inserted`)}finally{try{e.dbl.runf(e=>e.delete().where({name:n}))}catch(n){e.$logger().warn(`Failed to clean up Heartbeat row`,{error:n})}}}},OperationNames=strEnum(`rebuildLibrary`,`forceRestartSync`,`forceSyncPath`,`checkLibraryCopy`,`reaggregate`,`forceFilters`,`forceSync`,`country_flag_displaynames`,`country_code_paths`,`toolChangeResync`,`toolPaths`,`photoPreviewResolution`,`videoPreviewResolution`,`keywordVariationScope`,`previewSetConversion`,`supportedMimetypeChange`,`assetFileUriSchemes`,`videoFramePolicy`,`legacyPslibRekey`),logger165=lazy2(()=>mkLogger(`model.Operation`)),inFlightOps=new Map,Operation=class e extends TimestampedModel{static $tableName=`Operation`;name;value;completedAt;static incomplete(){return this.ops().allf(n=>n.whereIn(`id`,n=>n.table(e.$tableName).min(`id`).whereNull(`completedAt`)))}static ensurePendingOp(n){return e.getFirstPendingOp(n)??e.ops().insertOne(n)}static getFirstPendingOp(e){return logger165().tap({msg:`getFirstPendingOp`,result:this.ops().findOnef(n=>{let r=n.whereNull(`completedAt`).orderBy(`createdAt`,`asc`);return e==null?r:r.andWhere(e)}),meta:{crit:e}})}static getAllPending(e){return this.ops().allf(n=>n.whereNull(`completedAt`).andWhere(e).orderBy(`createdAt`,`asc`))}static markOpCompleted(e,n){return blank(e?.name)?logger165().throw(`markOpCompleted(): bad query`,{crit:e}):this.dbl.runf(r=>r.whereNull(`completedAt`).andWhere(e).update({completedAt:Date.now(),...n}))}static async applyIfPending(e,n){let r=this.ops().findOnef(n=>n.whereNull(`completedAt`).andWhere(e));return logger165().info(`applyIfPending()`,{crit:e,op:r}),r==null?void 0:n(r)}static async applyOnce_(e,n){let r=`${e.name}:${e.value??``}`,a=inFlightOps.get(r);if(a!=null){logger165().debug(`applyOnce(): waiting for in-flight operation`,{crit:e}),await a.catch(()=>{});return}let o=this.ops().findOnef(n=>n.whereNotNull(`completedAt`).andWhere(e));if(o!=null){logger165().debug(`applyOnce(): already done`,{priorCompleted:o});return}let s=this.ensurePendingOp(e),c,l,u=new Promise((e,n)=>{c=e,l=n});inFlightOps.set(r,u);try{let e=await n(s);return ending()||s.markCompleted(),c(e),e}catch(n){if(l(n),!0===isRetriableError(n)){logger165().info(`applyOnce(): retriable error`,{crit:e,error:n});return}throw onError(`Operation.applyOnce(): `+stringify(e),n),n}finally{inFlightOps.delete(r)}}markCompleted(){this.completedAt??(this.completedAt=Date.now(),this.upsert())}},modelJsonSetup=lazy2(()=>{for(let[e,n]of[[`Asset`,Asset],[`AssetFile`,AssetFile],[`AssetRevision`,AssetRevision],[`AssetTag`,AssetTag],[`DirUri`,DirUri],[`Example`,Example],[`Heartbeat`,Heartbeat],[`Operation`,Operation],[`Progress`,Progress],[`ProgressMeta`,ProgressMeta],[`RejectedFile`,RejectedFile],[`ShaBlocklist`,ShaBlocklist],[`Tag`,Tag],[`TagHierarchy`,TagHierarchy],[`Volume`,Volume]])JsonRevivableClasses.add(e,n)}),skipOpenChecks=!1,Db=class extends EndableWrapper{constructor(e,n,r){super(`db.Db(`+e+`)`,()=>this.closeDb(),EndableRanks.db),this.schema=e,this.dbFile=n,this.isReplica=r,this.logger.info(`new Db`,this.toJSON())}schema;dbFile;isReplica;#e;endTimeoutMs=minuteMs;#t=[];#n=0;#r=0;get lastWriteAt(){return this.#n}get writeCount(){return this.#r}onClose(e){this.#t.push(e)}toJSON(){return pick(this,`schema`,`dbFile`)}get isOpen(){return!0===this.#e?.isOpen}get inTransaction(){return this.isOpen&&!0===this.#e?.isTransaction}prepare(e){return this.db.prepare(e)}pragma(e,n){return this.logger.tapThunk({msg:`PRAGMA `+e,result:()=>this.db.pragma(e,n)})}get db(){let e=this.#e==null;if(e||!this.isOpen){this.logger.info(`setting up new db connection to `+this.dbFile,{priorWasNull:e});try{this.#e=mkdb_({nativePath:this.dbFile.nativePath}),this.#i(this.#e)}catch(e){this.logger.throw(`Failed to set up `+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return this.#e}#i(e){let n=e.prepare.bind(e);Object.defineProperty(e,"prepare",{value:e=>{let r=n(e),a=r.run.bind(r);return Object.defineProperty(r,"run",{value:(...e)=>{let n=a(...e);return this.#n=performance.now(),this.#r++,n},writable:!0,configurable:!0,enumerable:!1}),r},writable:!0,configurable:!0});let r=e.exec.bind(e);Object.defineProperty(e,"exec",{value:e=>(this.#n=performance.now(),this.#r++,r(e)),writable:!0,configurable:!0})}async verify_(){await verifyDb_(()=>this.db)}assertHeartbeat_(){let e=randomChars(64),n=Date.now();try{if(this.db.prepare(`INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)`).run(e,n,n),this.db.prepare(`SELECT * FROM heartbeat WHERE name = ?`).get(e)?.name!==e)throw Error(`heartbeat INSERT/SELECT roundtrip failed`)}finally{try{this.db.prepare(`DELETE FROM heartbeat WHERE name = ?`).run(e)}catch{}}}async closeDb(){try{if(this.logger.info(`closing db`,{db:this.#e}),!0===this.#e?.isOpen)try{await walCheckpointPassive(this.#e)}catch(e){this.logger.warn(`closeDb(): WAL checkpoint failed`,{error:e})}await retryOnReject_(()=>{!0===this.#e?.isOpen&&this.#e?.close()},{timeoutMs:Settings2.dbBusyTimeoutMs.valueOrDefault+secondMs,maxRetries:5,errorIsRetriable:isSqliteBusyError,retryDelay:secondMs})}catch(e){this.logger.warn(`closeDb(): .close() failed`,e)}this.#e=void 0,this.#n=0,this.#r=0;for(let e of this.#t)try{e()}catch(e){this.logger.warn(`closeDb(): listener threw`,e)}}onRetry=lazy2(()=>this.closeDb(),Settings2.maxBusyDbMs.valueOrDefault/2);#a(...e){let n=[];for(let r of e)try{n.push(this.db.prepare(`SELECT MAX(updatedAt) FROM `+dbValueToEscapedString(r)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${r}`,e)}return max2(n)}maxUpdatedAt=lazy2(()=>this.schema===`models`?this.#a(`Asset`,`AssetFile`,`Example`):0,5*secondMs);async repair_(){this.logger.warn(`repair_(): Attempting restore of `+this.dbFile),await this.closeDb(),await repairDbFile_(this.dbFile,RepairModes.recover,{holdsSignInState:this.trait.holdsSignInState}),this.logger.info(`repair_(): Database restoration was successful!`)}get trait(){return SchemaTraits[this.schema]}get ownerOnly(){return this.trait.holdsSignInState}localBackupDir(){return dbBackupDir(this.dbFile)}async backup_(e,n,r){let a=n??await isDirSQLiteReadWrite(e),o=(a?e:this.localBackupDir().join(filestamp())).join(this.dbFile.base);return await removeDbDirOtherAccess_(await o.parent().mkdirp_(),this.ownerOnly),await backupDbFile_(this.dbFile,o),await removeDbOtherAccess_(o,this.ownerOnly),await r?.(o),a||await dbBackupCold_(o,e,this.ownerOnly),e.join(this.dbFile.base)}migrate_=lazy2(async()=>{let e=this.dbFile;if(this.dbFile==null)throw Error(`Cannot migrate database: missing db`);let n=[];if(await this.dbFile.isNonEmptyFile()&&(!isWebService()||this.trait.verifiedWhenWebOpens)&&!skipOpenChecks)try{await verifyDb_(()=>this.db)}catch(e){this.logger.error(`verifyDb() failed before attempting Migration.`,{error:e}),addDbSetupError(e),n.push(e)}let r=!this.trait.verifiedWhenWebOpens&&Settings2.dbForceRepair.valueOrDefault;(n.length>0||r)&&(HealthCheck.addLoadingMsg(`Repairing database...`),await this.repair_());let a=new Migration(this.schema,this.db,e);return{appliedMigrations:await a.apply_(),migration:a}});tableInfo_=lazy2(()=>localTableInfo(this.db))},logger166=lazy2(()=>mkLogger(`db.ModelDbLifecycle`)),ModelDbLifecycle=class e{constructor(e,n,r,a,o,s){this.libraryDir=e,this.openLock=n,this.dbs=r,this.useReplica=a,this.libraryDbFiles=o,this.dbInfoFile=s}libraryDir;openLock;dbs;useReplica;libraryDbFiles;dbInfoFile;get db(){return this.dbs.models}get authDb(){return this.dbs.auth}get libraryDbFile(){return this.libraryDbFiles.models}get libraryDbBackupDir(){return dbBackupDir(this.libraryDbFile)}static async forLibraryDir_(n,{allowAuthSetup:r=!1}={}){if(logger166().info(`forLibraryDir() starting`,{libraryDir:n}),HealthCheck.addLoadingMsg(`Opening database…`),modelJsonSetup(),blank(n))return logger166().throw(`Library directory is not set`+NoLibraryErrorFlag);n=(0,import_node_path72.resolve)(n);let{dataDir:a,libraryDbFiles:o}=libraryDbObjects_(n,r),s=a.join(`db-open`),c=a.join(`db-setup`),l=a.join(`db-info.json`),u=FsLock.for({file:s,timeoutMs:ProcessLifetimeLockTimeoutMs,processLifetime:!0,noopIfContested:!1,priority:janitorPriority()}),d={};for(let e of Schemas.values)d[e]=await cacheDbFile_({libraryDir:n,schema:e});await u.tryAcquire_();let f,h=modelDb(),_={};h?.ended===!0&&(logger166().info(`forLibraryDir_(): clearing ended modelDb`),h=void 0,modelDb.unset()),h!=null&&!h.dbFile.isDescendantOf(n)&&(logger166().info(`forLibraryDir_(): clearing stale modelDb from different library`,{priorDbFile:h.dbFile.nativePath,newLibraryDir:n}),h=void 0,modelDb.unset());let y=h;try{await withLock_({file:c,timeoutMs:5*minuteMs,noopIfContested:!1},async()=>{let e=await l.readJson(`info`),r;if(y!=null)f=y.dbFile.$eql(d.models),r=f?recordedReplicas_(e):o;else{let n=await validateSetupInfo_(e,o);if(n!=null)logger166().info(`setup_(): using existing db-info.json`,{setupInfo:e}),f=n.useReplica,r=n.liveDbFiles;else{f=await decideUseReplica_(o.models,d.models);for(let e of Schemas.values)await bringNewerCopy_(o[e],d[e],f,SchemaTraits[e].holdsSignInState);r=f?d:o;let e={pid:process.pid,useReplica:f,liveDbNativePaths:f?mapSchemas(e=>r[e].nativePath):void 0};await l.writeJson_(e),logger166().info(`setup_(): wrote db-info.json`,{newSetupInfo:e})}}HealthCheck.addLoadingMsg(`Upgrading the database…`);for(let e of Schemas.values){let n=e===Schemas.models&&y!=null?y:new Db(e,r[e],f);_[e]=n,await n.dbFile.parent().mkdirp_(),await n.migrate_(),await removeDbOtherAccess_(n.dbFile,n.ownerOnly),f&&await removeDbOtherAccess_(o[e],n.ownerOnly)}ensureAssetFileHashTable(_.models.db);try{await writeLibraryVersionStamp_(n)}catch(e){logger166().warn(`setup_(): failed to write the version stamp`,{libraryDir:n,error:e})}})}catch(e){logger166().error(`Failed to set up model db`,{error:e}),addDbSetupError(e);for(let n of Object.values(_)){if(n===y)continue;let r=n.isOpen?n.db:void 0;if(await end(n),r?.isOpen===!0)throw e}throw u.release(),e}let x=_;clearDbSetupErrors(),modelDb.set(x.models);let C=new e(n,u,x,f,o,l);return logger166().info(`setup_() complete`,{useReplica:f,liveDbFiles:mapSchemas(e=>x[e].dbFile.nativePath)}),C}async assertValid_(){await assertDirSQLiteReadWrite_(this.db.dbFile.parent(),{force:!0})}async teardown_(e){if(!this.useReplica){logger166().info(`teardown_(): not using replica, nothing to do`);return}if(!await this.openLock.iAmOnly_({vacuum:!0})){logger166().info(`teardown_(): other processes are still running`);return}logger166().info(`teardown_(): I'm the last one out. Running backup and cleanup.`);let n=await e();if(!(n instanceof PosixFile)){logger166().warn(`teardown_(): Replica backup did not complete; retaining replica artifacts`,{backupResult:n});return}let r=Object.values(this.dbs).flatMap(e=>sqliteFiles(e.dbFile));logger166().info(`teardown_(): Removing replica artifacts`,{victims:r});for(let e of r)await e.unlink();await this.dbInfoFile.unlink(),logger166().info(`teardown_(): Removed db-info.json`)}};function recordedReplicas_(e){return mapSchemas(n=>{let r=e?.liveDbNativePaths?.[n];if(r==null)throw Error(`db-info.json records no `+n+` replica`+DbSetupErrorFlag);return PosixFile.for(r)})}async function validateSetupInfo_(e,n){if(e==null){logger166().info(`validateSetupInfo_(): no db-info.json found`);return}if(typeof e.useReplica!=`boolean`){logger166().warn(`validateSetupInfo_(): useReplica is not a boolean`,{setupInfo:e});return}let r=n;if(e.useReplica){let n=e.liveDbNativePaths??{};if(Schemas.values.some(e=>n[e]==null)){logger166().warn(`validateSetupInfo_(): a replica is not recorded`,{setupInfo:e});return}r=mapSchemas(e=>PosixFile.for(n[e]));for(let e of Schemas.values)if(await r[e].notExists()){logger166().warn(`validateSetupInfo_(): a replica doesn't exist`,{replica:r[e]});return}}else if(await n.models.notExists()){logger166().warn(`validateSetupInfo_(): live db file doesn't exist`,{liveDbFile:n.models});return}if(!await isDirSQLiteReadWrite(r.models.parent()))logger166().warn(`validateSetupInfo_(): SQLite can't write to db directory`,{liveDbFile:r.models});else return logger166().info(`validateSetupInfo_(): db-info.json is valid`,{setupInfo:e,liveDbFiles:r}),{liveDbFiles:r,useReplica:e.useReplica}}async function decideUseReplica_(e,n,r=Settings2.forceLocalDbReplica.value){let a=r===!0||!await isDirSQLiteReadWrite(e.parent());return logger166().info(`decideUseReplica_()`,{forceReplica:r,useReplica:a}),a&&!await isDirSQLiteReadWrite(n.parent())&&logger166().throw(`SQLite cannot write to library or cache directory`+DbSetupErrorFlag,{libraryDbFile:e,cacheDbFile:n}),a}async function bringNewerCopy_(e,n,r,a){let[o,s]=r?[n,e]:[e,n],c=await o.mtimeMs(),l=await s.mtimeMs();if(!(l==null||c!=null&&!gt(l,c))){logger166().info(`bringNewerCopy_(): copying the newer copy`,{from:s.nativePath,to:o.nativePath});try{await HealthCheck.traceLater_(r?`Setting up local replica database`:`Copying the local replica database back to the library`,dbBackupCold_(s,o.parent(),a))}catch(e){return logger166().throw(`Failed to copy the newer database`+DbSetupErrorFlag,{from:s.nativePath,to:o.nativePath,error:e})}}}function libraryDbObjects_(e=Settings2.libraryDir.valueOrDefault,n=!1){if(blank(e))throw Error(`Library directory is not set`+NoLibraryErrorFlag);let r=libraryDataDirPosixFile(e);if(r==null)throw Error(`missing library dataDir`+NoLibraryErrorFlag);if(!n&&!_libraryHasSettings(e))throw Error(`Library at ${e} does not have a settings file`+NoLibraryErrorFlag);let a=mapSchemas(e=>pathToDb(r,e));return{dataDir:r,libraryDbFiles:a,libraryDbFile:a.models,libraryDbBackupDir:dbBackupDir(a.models)}}var import_experimental=require("@photostructure/sqlite/experimental"),WalCheckpointPauseMs=5*secondMs,WalCheckpointer=class e extends EndableWrapper{#e;#t=new SequentialTaskQueue;#n;#r;#i=hourlyErrorReporter(`Library database checkpoint failed`);static async open(n){let r=await import_experimental.DatabasePool.open(n.nativePath,{connections:1,authorizer:`none`,connectionSetup:[{sql:`PRAGMA synchronous = `+DbSettings.dbSynchronousMode.valueOrDefault}]});return new e(n,r)}constructor(e,n){super(`db.WalCheckpointer(`+e.nativePath+`)`,()=>this.#s(),EndableRanks.predb,5*minuteMs),this.#e=n,this.#n=this.#a()}hold(e){return this.#t.enqueue(e)}async#a(){for(;!this.ended;){if(await this.#t.enqueue(()=>this.#o()),this.ended)return;await new Promise(e=>{let n=setTimeout(e,WalCheckpointPauseMs);n.unref(),this.#r=()=>{clearTimeout(n),e()}})}}async#o(){try{let e=await this.#e.get(`PRAGMA wal_checkpoint(PASSIVE)`);this.logger.debug(`checkpointed`,{row:e})}catch(e){this.logger.warn(`PASSIVE checkpoint failed`,{error:e}),this.#i(e)}}async#s(){this.#r?.(),await this.#n,await this.#t.awaitSettled(),await this.#e.close()}},Library=class e extends EndableWrapper{constructor(n,r=!1){super(`library.Library(${n})`,()=>this.onEnd(),EndableRanks.predb),this.allowManagedDb=r,this.rootDir=PosixFile.for(n),this.dataDir=libraryDataDirPosixFile(this.rootDir),this.#n=_libraryHasSettings(this.rootDir.nativePath),this.logger.info(`new()`),this.readyLatch.then(()=>{if(!this.ended&&this.isReadySync())for(let n of e.readyObservers)n(this)},()=>{}),this.#r()}allowManagedDb;start=Date.now();static#e;static#t;static readyObservers=[];static instance(){let n=Settings2.libraryDir.valueOrDefault,r=this.#e?.rootDir.nativePath,a=this.#e?.isReadySync()===!0,o=this.#e?.ended===!0;if(nativePathsEqlSync(r,n)&&!o)return this.#e.#n?this.#e:void 0;if(isSyncService()&&a)exit({reason:`Library changed mid-run. Shutting down to pick up new library at ${n}.`,status:0});else return end(this.#e),this.#e=blank(n)||!_libraryHasSettings(n)?void 0:new e(n)}static observeReady(e){this.readyObservers.push(e)}static get priorInstance(){return this.#e}static endPriorInstance(){let e=this.#e;return this.#e=void 0,end(e)}static async instanceReady(){!ending()&&!0===e.instance()?.ended&&e.endPriorInstance();let n=e.instance();return await n?.ready(),n}static async instanceForRootReady_(n){let r=PosixFile.for(n),a=this.#t;if(a!=null){if(nativePathsEqlSync(a.rootDir,r.nativePath))return a.promise;throw Error(`Cannot open the library at ${r.nativePath} while ${a.rootDir} is open`)}let o=this.#e;if(o!=null&&!o.ended&&!nativePathsEqlSync(o.rootDir.nativePath,r.nativePath))throw Error(`Cannot open the library at ${r.nativePath} while ${o.rootDir.nativePath} is open`);if(o!=null&&!o.ended&&nativePathsEqlSync(o.rootDir.nativePath,r.nativePath)){let e=(async()=>{try{if(o.allowManagedDb=!0,await o.readyLatch.promise,o.ended||(await o.dbLifecycle_(),await o.dbModelJanitor(),o.ended))throw Error(`Library ended while opening its managed database`);return o}catch(e){throw await o.end(),e}})();this.#t={rootDir:r.nativePath,promise:e};try{return await e}finally{this.#t?.promise===e&&(this.#t=void 0)}}let s=(async()=>{await end(o);let n=this.#e=new e(r,!0);try{await n.readyLatch.promise}catch(e){throw await n.end(),e}if(n.ended)throw Error(`Library ended while opening its managed database`);return n})();this.#t={rootDir:r.nativePath,promise:s};try{return await s}finally{this.#t?.promise===s&&(this.#t=void 0)}}static instanceRequired_(){let n=e.instance();if(n==null)throw Error(`Library is undefined`+FatalErrorFlag);return n}readyLatch=new Latch;rootDir;dataDir;#n;get isPendingSetup(){return this.readyLatch.isPending()}#r=lazy2(async()=>{let e=e=>this.logger.awaitOrAbort(e);try{if(this.logger.debug(`setup() started`),await e(readLibrarySettings(this.rootDir.nativePath)),await e(setupLibraryDirs_(this.rootDir)),await e(imageCacheDir_()),isTrue((await map(libraryPreviewsDir(this.rootDir),n=>e(bestVolumeForPath(n))))?.remote)){let e=Settings2.maxConcurrentImportsWhenRemote.valueOrDefault;Settings2.maxConcurrentImports.hasValue()||(Settings2.maxConcurrentImports.cliValue=e,clearMaxWorkCaches()),this.logger.warn(`Library previews are on a remote volume. Setting maxConcurrentImports to ${e}.`)}(isDbService()||this.allowManagedDb)&&(await e(this.dbLifecycle_()),await e(this.dbModelJanitor()),isWebService()&&await e(this.webDbResizer())),await e(refreshLibraryUriRoots()),this.previews(),this.readyLatch.isPending()&&(this.logger.info(`Library.setup() finished.`),this.readyLatch.resolve(),isWebService()&&this.#n&&stdoutWrite({libraryStartupReady:!0,pid:process.pid}))}catch(e){let n=isUnknownMigrationsError(e),r=isWebService()&&n?(await readLibraryVersionStamp(this.rootDir))?.version:void 0;!this.ended&&!ending()&&(this.logger.warn(`setup() failed:`,{error:e}),HealthCheck.addError(e),this.readyLatch.reject(new WrappedError(`Failed to start library`,{cause:e})),isWebService()&&stdoutWrite({libraryStartupFailed:errorToS(e),libraryHasUnknownMigrations:n,libraryLastOpenedBy:r,pid:process.pid}))}});ready(){return this.readyLatch.promise.then(()=>this,()=>void 0)}isReadySync(){return this.readyLatch.isResolved()&&this.#n}previews=lazy2(()=>tap(new Previews(libraryPreviewsDirPosixFile(this.rootDir)),e=>Previews.instance.set(e)));originalsDir=lazy2(()=>libraryOriginalsDirPosixFile(this.rootDir));assetFileRepository=lazy2(()=>new AssetFileRepository(this.originalsDir(),this.rootDir));libraryDbFile=lazy2(()=>pathToDb(this.dataDir,`models`));dbLifecycle_=lazy2(async()=>{if(isDbService()||this.allowManagedDb)return ModelDbLifecycle.forLibraryDir_(this.rootDir.nativePath,{allowAuthSetup:this.allowManagedDb});this.logger.throw(`Library.dbLifecycle_: not a db service`)});useReplica=lazy2(async()=>(await this.dbLifecycle_()).useReplica);dbFsLock=lazy2(async()=>(await this.dbLifecycle_()).openLock);modelDb=lazy2(async()=>(await this.dbLifecycle_()).db);authDb=lazy2(async()=>(await this.dbLifecycle_()).authDb);authStore=lazy2(async()=>new LibraryAuthStore(await this.authDb()));dbModelJanitor=lazy2(async()=>ModelDbJanitor.for(await this.dbLifecycle_()));walCheckpointer=lazy2(async()=>WalCheckpointer.open((await this.modelDb()).dbFile));webDbResizer=lazy2(async()=>{let e=await this.modelDb();return new EndableInterval({name:`db.webDbResizer`,callback:()=>maybeResizeCacheAndMmap(e.db,e.dbFile.nativePath).catch(e=>onError(e,{fatal:!1})),intervalMs:hourMs,rank:EndableRanks.service,unref:!0})});dbMaintenanceWindow=lazy2(async()=>DbMaintenanceWindow.for({janitor:await this.dbModelJanitor(),checkpointer:await this.walCheckpointer()}));async pauseDbMaintenanceSchedule(){return(await this.dbMaintenanceWindow()).pauseInterval()}async resumeDbMaintenanceSchedule(){return(await this.dbMaintenanceWindow()).resumeInterval()}async runDbBackup_(){return(await this.dbModelJanitor())?.forceBackup_()}onEnd=lazy2(async()=>{this.logger.abortable.abort(`Library.onEnd()`),this.readyLatch.reject(new AbortError(`.onEnd()`)),ending()||await expedite(async()=>{await end(tryAsync(()=>this.authStore.prior()),commandTimeoutMs()),await end(tryAsync(()=>this.webDbResizer.prior()),commandTimeoutMs()),await end(tryAsync(()=>this.dbMaintenanceWindow.prior()),5*minuteMs),await end(tryAsync(()=>this.walCheckpointer.prior()),5*minuteMs),await end(tryAsync(()=>this.dbModelJanitor.prior()),5*minuteMs);let e=await tryAsync(()=>this.dbLifecycle_.prior());for(let n of Object.values(e?.dbs??{}))await end(n,commandTimeoutMs());await end(e?.openLock,commandTimeoutMs())}),this.logger.info(`onEnd(): finished.`)})},import_fs_metadata4=require("@photostructure/fs-metadata"),import_node_crypto11=require("node:crypto"),import_promises37=require("node:fs/promises"),import_node_path73=require("node:path"),AuthCredentialError=class extends Error{constructor(e,n){super(e,n),this.name=`AuthCredentialError`}},logger167=defer(()=>mkLogger(`auth.AuthPersistence`)),SecretPattern=/^v1:[\w-]{43}$/,SetupTokenPattern=/^v1:([\da-f]{64}):(\d+)$/,SetupSessionPattern=/^v1:([\da-f]{64}):([\w-]{43}):(claim|token)$/,SetupSavedPattern=/^v1:([\da-f]{64}):(\d+):([\w-]*)$/;function verifyFileType(e,n){if(e.isSymbolicLink()||!(n?e.isDirectory():e.isFile()))throw new AuthCredentialError(`Authentication requires private regular files and directories`)}var ownerOnlyAcl=process.platform===`win32`||process.platform===`darwin`,warnedOwnerOnlyUnsupported=!1;async function setOwnerOnlyIfSupported(e){try{await(0,import_fs_metadata4.setOwnerOnly)(e)}catch(e){if(errorCode(e)!==`ENOTSUP`)throw e;if(warnedOwnerOnlyUnsupported)return;warnedOwnerOnlyUnsupported=!0,logger167().warn(`Could not make authentication storage readable only by its owner: its volume does not support it`,{error:e})}}function verifyMode(e,n){if(process.platform!==`win32`&&(e.mode&511)!==n)throw new AuthCredentialError(`Could not make authentication storage private`)}function privateStorageFailure(e){throw e instanceof AuthCredentialError?e:new AuthCredentialError(`Could not access private authentication storage`,{cause:e})}async function ensurePrivateAuthDirectory(e){try{await(0,import_promises37.mkdir)(e,{recursive:!0,mode:448}),verifyFileType(await(0,import_promises37.lstat)(e),!0),await(0,import_promises37.chmod)(e,448),ownerOnlyAcl&&await setOwnerOnlyIfSupported(e),verifyMode(await(0,import_promises37.lstat)(e),448)}catch(e){privateStorageFailure(e)}}async function ensurePrivateAuthFile(e){try{verifyFileType(await(0,import_promises37.lstat)(e),!1),await(0,import_promises37.chmod)(e,384),ownerOnlyAcl&&await setOwnerOnlyIfSupported(e),verifyMode(await(0,import_promises37.lstat)(e),384)}catch(e){privateStorageFailure(e)}}var RecordMaxBytes=256,SetupSavedMaxBytes=RecordMaxBytes+Math.ceil(MaxMailboxLength*4/3)*4;async function readOptionalPrivate(e,n=RecordMaxBytes){try{try{verifyFileType(await(0,import_promises37.lstat)(e),!1)}catch(e){if(errorCode(e)===`ENOENT`)return;throw e}await ensurePrivateAuthFile(e);let r=await(0,import_promises37.open)(e,`r`);try{if((await r.stat()).size>n)throw new AuthCredentialError(`The persisted authentication record is invalid`);return(await r.readFile(`utf8`)).replace(/\n$/,``)}finally{await r.close()}}catch(e){privateStorageFailure(e)}}var AuthPersistence=class{paths;constructor({configRoot:e}){this.paths={configRoot:e}}get sessionSecretPath(){return(0,import_node_path73.join)(this.paths.configRoot,`auth`,`session-secret-v1`)}async getOrCreateSessionSecret(){let e=PosixFile.for(this.sessionSecretPath);await ensurePrivateAuthDirectory((0,import_node_path73.dirname)(e.nativePath));let n;if(await e.applyWip_({timeoutMs:ShortCommandTimeoutMs,skipFsLock:!1,preserveDestOnError:!0,fn_:async r=>{let a=await readOptionalPrivate(e.nativePath);if(a!=null){if(!SecretPattern.test(a))throw new AuthCredentialError(`The persisted session secret is invalid`);return n=a,NoOp2}return n=`v1:`+(0,import_node_crypto11.randomBytes)(32).toString(`base64url`),await(0,import_promises37.writeFile)(r.nativePath,n+`
|
|
850
|
+
`,{mode:384,flag:`wx`}),await ensurePrivateAuthFile(r.nativePath),!0}})==null||n==null)throw Error(`Could not acquire the session secret lock`);return n}get setupTokenPath(){return(0,import_node_path73.join)(this.paths.configRoot,`auth`,`setup-token-v1`)}async writeSetupToken_(e){await writePrivateRecord_(this.setupTokenPath,`v1:${e.sha256}:${e.createdAtMs}`,`Could not acquire the setup token lock`)}async readSetupToken_(){await ensurePrivateAuthDirectory((0,import_node_path73.dirname)(this.setupTokenPath));let e=await readOptionalPrivate(this.setupTokenPath);if(e==null)return;let n=SetupTokenPattern.exec(e);if(n==null)throw new AuthCredentialError(`The persisted sign-in setup token record is invalid`);return{sha256:n[1],createdAtMs:Number(n[2])}}async deleteSetupToken_(){await(0,import_promises37.rm)(this.setupTokenPath,{force:!0})}get setupSessionPath(){return(0,import_node_path73.join)(this.paths.configRoot,`auth`,`setup-session-v1`)}async writeSetupSession_(e){await writePrivateRecord_(this.setupSessionPath,[`v1`,e.idSha256,e.formToken,e.claimed?`claim`:`token`].join(`:`),`Could not acquire the setup session lock`)}async readSetupSession_(){await ensurePrivateAuthDirectory((0,import_node_path73.dirname)(this.setupSessionPath));let e=await readOptionalPrivate(this.setupSessionPath);if(e==null)return;let n=SetupSessionPattern.exec(e);if(n==null)throw new AuthCredentialError(`The persisted sign-in setup session record is invalid`);return{idSha256:n[1],formToken:n[2],claimed:n[3]===`claim`}}async deleteSetupSession_(){await(0,import_promises37.rm)(this.setupSessionPath,{force:!0})}get setupSavedPath(){return(0,import_node_path73.join)(this.paths.configRoot,`auth`,`setup-saved-v1`)}async writeSetupSaved_(e){await writePrivateRecord_(this.setupSavedPath,[`v1`,e.idSha256,e.savedAtMs,Buffer.from(e.email??``,`utf8`).toString(`base64url`)].join(`:`),`Could not acquire the saved setup lock`)}async readSetupSaved_(){await ensurePrivateAuthDirectory((0,import_node_path73.dirname)(this.setupSavedPath));let e=await readOptionalPrivate(this.setupSavedPath,SetupSavedMaxBytes);if(e==null)return;let n=SetupSavedPattern.exec(e);if(n==null)throw new AuthCredentialError(`The persisted saved setup record is invalid`);let r={idSha256:n[1],savedAtMs:Number(n[2])};return n[3]===``?r:{...r,email:Buffer.from(n[3],`base64url`).toString(`utf8`)}}};async function writePrivateRecord_(e,n,r){let a=PosixFile.for(e);if(await ensurePrivateAuthDirectory((0,import_node_path73.dirname)(a.nativePath)),await a.applyWip_({timeoutMs:ShortCommandTimeoutMs,skipFsLock:!1,preserveDestOnError:!0,fn_:async e=>(await(0,import_promises37.writeFile)(e.nativePath,n+`
|
|
851
|
+
`,{mode:384,flag:`wx`}),await ensurePrivateAuthFile(e.nativePath),!0)})==null)throw Error(r)}var MailSettingKeys=keys(EmailSettings);function savedSettingInvalid(e){return Settings2[e].rawEnvValue()==null&&Settings2[e].hasInvalidFileInput()}function authNoneSetByEnvironment(){return Settings2.authMode.rawEnvValue()!=null&&Settings2.authMode.envValue===AuthModes.none&&!savedSettingInvalid(`externalOrigin`)&&!savedSettingInvalid(`trustProxy`)}function authNoneSetByEnvironmentText(e=e=>e){return`${e(`PS_AUTH_MODE=none`)} sets how people sign in. To change it, change or remove ${e(`PS_AUTH_MODE`)}, then restart PhotoStructure.`}var ExampleDomainUserText=`Addresses at reserved example domains, such as example.com, can't receive email, so they can't be users.`,import_node_crypto12=require("node:crypto"),AuthSetupPath=`/auth/setup`;function sha256(e){return(0,import_node_crypto12.createHash)(`sha256`).update(e).digest()}function mintAuthSetupToken(){let e=(0,import_node_crypto12.randomBytes)(32).toString(`base64url`);return{token:e,record:{sha256:sha256(e).toString(`hex`),createdAtMs:Date.now()}}}async function issueAuthSetupToken_(e){let{token:n,record:r}=mintAuthSetupToken();return await e.writeSetupToken_(r),await e.deleteSetupSession_(),{token:n}}function authSetupTokenOrigin(e){return isDocker()?void 0:new URL(String(myWebUrls(e)[0])).origin}function authSetupLinkCommandLine(e){return`To set up sign-in, ${openSetupLink(e)}. It works once, until ${restartWhat(e.origin)} restarts.`}function openSetupLink({token:e,origin:n}){let r=`${AuthSetupPath}?token=${e}`;return n==null?`open ${r} at the address and port mapped to this container`:`open ${n}${r} (or ${r} at the address you use)`}function restartWhat(e){return e==null?`the container`:`PhotoStructure`}var EmailSignInCodeLifetimeMs=15*minuteMs,EmailSignInCodeLifetimeMinutes=EmailSignInCodeLifetimeMs/minuteMs,logger168=defer(()=>mkLogger(`auth.EmailSignIn`)),Rejected=Object.freeze({accepted:!1});function addFirstAdmin(e,n){return e.db.db.transaction(()=>e.listUsers().length===0?e.addUser({email:n,role:LibraryRoles.admin}):void 0).immediate()}var import_openid_client=require("openid-client"),OidcCallbackPath=`/auth/oidc/callback`,OidcProviderResponseLimitBytes=1048576,SelectExistingLibraryMessage=`Select an existing library directory before configuring authentication`,PassLibraryAdvice=`Pass --library with your library's directory.`;async function withCredentialLock(e,n,{existingLibrary:r=!1}={}){if(e==null)throw Error(SelectExistingLibraryMessage);let a;try{a=await(0,import_promises38.stat)(e)}catch(n){throw errorCode(n)===`ENOENT`?Error(`The library directory ${e} does not exist. ${r?PassLibraryAdvice:`Create it, or pass --library with an existing library.`}`):n}if(!a.isDirectory())throw Error(SelectExistingLibraryMessage);if(r){let n=await whyNotLibraryDir(e);if(n!=null)throw Error(`The directory ${e} is not a PhotoStructure library: ${n}. ${PassLibraryAdvice}`)}let o=await withLock_({file:PosixFile.for(e).join(`.photostructure`,`auth`).join(`credential-change-v1`),timeoutMs:ShortCommandTimeoutMs*3},async()=>({result:await n(e)}));if(o==null)throw Error(`Could not acquire the library credential lock`);return o.result}async function configureAuthMode(e,n){await withCredentialLock(e.libraryRoot,async r=>{(await(await Library.instanceForRootReady_(r)).authStore()).endAllSessions(),await writeLibraryAuthMode_(r,n),Settings2.libraryDir.rawEnvValue()??await writeSystemLibraryIfMissing_((0,import_node_path74.join)(e.configRoot,SettingsToml),r)});let r=new AuthPersistence({configRoot:e.configRoot});await r.deleteSetupToken_(),await r.deleteSetupSession_()}async function configureAuthNone(e){await configureAuthMode(e,`none`)}async function libraryHasUsers(e){return await whyNotLibraryDir(e)==null&&withCredentialLock(e,async e=>(await(await Library.instanceForRootReady_(e)).authStore()).hasUsers(),{existingLibrary:!0})}async function configureUserSignIn(e,n){let{adminEmail:r}=e;if(r==null){if(!await libraryHasUsers(e.libraryRoot))throw Error(`set-${n} requires --admin-email <address>: this library has no users yet.`)}else if(isExampleDomainMailbox(r))throw Error(`Check --admin-email: ${ExampleDomainUserText}`);else if(!isPlainMailbox(r))throw Error(`--admin-email needs a valid email address`);return e.settings!=null&&await writeSignInSettings_(e,e.settings),await configureAuthMode(e,n),r==null?void 0:addFirstAdmin(await(await Library.instanceForRootReady_(e.libraryRoot)).authStore(),r)}function configureAuthEmail(e){return configureUserSignIn(e,AuthModes.email)}function configureAuthOidc(e){return configureUserSignIn(e,AuthModes.oidc)}var UserActions=[`list-users`,`add-user`,`remove-user`,`set-role`,`clear-oidc-link`];function requireOption(e,n,r){if(r==null)throw Error(`${e} requires ${n}`);return r}function existingUser(e,n){let r=e.userByEmail(n);if(r==null)throw new LibraryUserError(`userNotFound`,`${n.trim()} is not a user of this library`);return r}function formatUsers(e){if(e.length===0)return`This library has no users.`;let n=Math.max(...e.map(e=>e.email.length)),r=Math.max(...e.map(e=>e.role.length));return e.map(e=>[e.email.padEnd(n),e.role.padEnd(r),e.oidcSubject==null?``:`OIDC linked`].join(` `).trimEnd()).join(`
|
|
852
|
+
`)}function userChange(e,{email:n,role:r}){if(e===`list-users`)return e=>formatUsers(e.listUsers());let a=requireOption(e,`--email`,n);if(e===`add-user`){let n=requireOption(e,`--role`,r);return e=>{let r=e.addUser({email:a,role:n});return`Added ${r.email} as ${r.role}.`}}if(e===`set-role`){let n=requireOption(e,`--role`,r);return e=>{let r=existingUser(e,a);return e.changeUserRole(r.id,n),`Changed ${r.email} to ${n}. Their sessions have ended.`}}return e===`remove-user`?e=>{let n=existingUser(e,a);return e.removeUser(n.id),`Removed ${n.email}. Their sessions have ended.`}:e=>{let n=existingUser(e,a);return e.clearUserOidcLink(n.id),`Cleared the OIDC link for ${n.email}. Their sessions have ended.`}}async function changeAuthStore(e,n){let r=await withCredentialLock(e,async e=>n(await(await Library.instanceForRootReady_(e)).authStore()),{existingLibrary:!0});console.info(r)}function reportConfiguredMode(e,n){let r=`the library at ${n}`;if(Settings2.authMode.rawEnvValue()!=null&&Settings2.authMode.envValue!==e){let n=Settings2.authMode.envValue;console.info(n==null?`Saved authMode=${e} for ${r}. The auth mode environment override is invalid; correct or remove it, then restart PhotoStructure.`:`Saved authMode=${e} for ${r}. PS_AUTH_MODE=${n} still overrides it; change or remove the environment override, then restart PhotoStructure.`)}else console.info(e===`email`?`Email sign-in configured for ${r}. Restart PhotoStructure.`:e===`oidc`?`OIDC sign-in configured for ${r}. Restart PhotoStructure.`:`Access without sign-in configured for ${r}. Restart PhotoStructure: then everyone who can reach it uses this library as an Admin, as releases before sign-in did.`)}function warnNoMode(e){let n=e===`list-users`?`listed this library's users anyway.`:`changed this library's users anyway. Users sign in only once email or OIDC sign-in is set.`;console.warn(savedAuthModeFromSettings().failure===`librarySettingsUnreadable`?`PhotoStructure can't read this library's .photostructure/settings.toml, so it pauses access until that file is corrected.`:`No sign-in mode is set for this library, so PhotoStructure pauses access until one is chosen: photostructure auth set-email, set-oidc or set-none. This command ${n}`)}var SignInOptions={"set-email":{emailSmtpHost:`--smtp-host`,emailSmtpPort:`--smtp-port`,emailSmtpSecurity:`--smtp-security`,emailSmtpUser:`--smtp-user`,emailSmtpPassword:`--smtp-password`,emailFromAddress:`--from-address`,emailFromName:`--from-name`},"set-oidc":{oidcIssuer:`--oidc-issuer`,oidcClientId:`--oidc-client-id`,oidcClientSecret:`--oidc-client-secret`}},SecretOptions=[`--smtp-password`,`--oidc-client-secret`];function optionKey(e){return e.slice(2).replace(/-(\w)/g,(e,n)=>n.toUpperCase())}async function signInSettingsFromOptions(e,n){let r=SignInOptions[e],a={};for(let[e,o]of Object.entries(r)){let r=n[optionKey(o)];if(r==null)continue;let s=Settings2[e];if(s.rawEnvValue()!=null)throw Error(`${o} would be saved to the library's settings.toml, but ${s.envKeyWithValue()} in the environment overrides it. Change or remove that variable instead.`);if(r!==`-`||!SecretOptions.includes(o)){a[e]=e===`emailSmtpPort`?Number(r):r;continue}let c=(await(0,import_consumers.text)(process.stdin)).replace(/\r?\n$/,``);if(c.length===0)throw Error(`${o} - read nothing from stdin`);a[e]=c}if(Object.keys(a).length===0)return;let o=Object.fromEntries(Object.keys(r).map(e=>[e,a[e]??Settings2[e].valueOrDefault??``])),s=(e===`set-oidc`?oidcSignInSettings:emailSignInSettings)(o,r);return Object.fromEntries(Object.keys(a).map(e=>[e,s[e]]))}async function printSetupLink(){if(isElectron())throw Error(`PhotoStructure for Desktop sets up sign-in in its own window: choose Set Up Sign-in… in the PhotoStructure menu on macOS, or the File menu on Windows and Linux.`);if(authNoneSetByEnvironment())throw Error(authNoneSetByEnvironmentText());let{token:e}=await issueAuthSetupToken_(new AuthPersistence({configRoot:configDir_()}));console.info(authSetupLinkCommandLine({token:e,origin:authSetupTokenOrigin()}))}async function runAuth(e=process.argv){let n=await new CLI(ServiceNames.auth).add({beforeParse(e){e.name(`photostructure auth`).addArgument(new import_commander2.Argument(`<action>`,`choose emailed-code or OIDC sign-in, or access without sign-in, print a sign-in setup link, or list and change users`).choices([`set-email`,`set-oidc`,`set-none`,`setup-link`,...UserActions])).option(`--admin-email <address>`,`set-email, set-oidc: the first Admin, required and added only while the library has no users`).option(`--library <directory>`,`library to configure (defaults to the configured library)`).option(`--config-dir <directory>`,`deployment configuration directory`).option(`--email <address>`,`the user's email address (add-user, remove-user, set-role, clear-oidc-link)`).addOption(new import_commander2.Option(`--role <role>`,`the user's role (add-user, set-role)`).choices(LibraryRoles.values)).option(`--smtp-host <host>`,`set-email: the outgoing mail server. The mail server and provider options left out keep their saved or environment values`).option(`--smtp-port <port>`,`set-email: the mail server port (587)`).addOption(new import_commander2.Option(`--smtp-security <security>`,`set-email: how to protect the connection to the mail server (starttls)`).choices(EmailSmtpSecurities.values)).option(`--smtp-user <user>`,`set-email: the mail server username`).option(`--smtp-password <password>`,`set-email: the mail server password, or - to read it from stdin`).option(`--from-address <address>`,`set-email: the address that sends sign-in codes`).option(`--from-name <name>`,`set-email: the sender name users see beside that address`).option(`--oidc-issuer <url>`,`set-oidc: the identity provider's issuer URL`).option(`--oidc-client-id <id>`,`set-oidc: PhotoStructure's client ID at the provider`).option(`--oidc-client-secret <secret>`,`set-oidc: PhotoStructure's client secret, or - to read it from stdin`)},afterParse(e){typeof e.configDir==`string`&&(process.env.PS_CONFIG_DIR=(0,import_node_path74.resolve)(e.configDir),resetConfigDir()),typeof e.library==`string`&&(Settings2.libraryDir.cliValue=(0,import_node_path74.resolve)(e.library))}}).parse(e,{from:`node`}),[r]=n.args;if(await readSettings(),r===`setup-link`){await printSetupLink();return}let a=libraryDir();if(a==null)throw Error(`No library is selected. Provide --library or select a library in PhotoStructure first.`);let o={configRoot:configDir_(),libraryRoot:(0,import_node_path74.resolve)(a)},s=UserActions.find(e=>e===r);if(s!=null)await changeAuthStore(o.libraryRoot,userChange(s,n.opts()));else if(r===`set-none`)await configureAuthNone(o),await readLibrarySettings(o.libraryRoot),reportConfiguredMode(`none`,o.libraryRoot);else if(r===`set-email`||r===`set-oidc`){let e=n.opts().adminEmail,a=await signInSettingsFromOptions(r,n.opts()),s=await(r===`set-email`?configureAuthEmail:configureAuthOidc)({...o,adminEmail:e,settings:a});if(await(a==null?readLibrarySettings(o.libraryRoot):readSettings()),s==null?e!=null&&console.info(`This library already has users, so ${e} was not added.`):console.info(`Added ${s.email} as the library's first Admin.`),r===`set-email`)emailSenderFromSettings()===`relay`?console.info(`photostructure.com will email this library's sign-in codes. To send them from your own mail server instead, set PS_EMAIL_SMTP_HOST and PS_EMAIL_FROM_ADDRESS, plus the other PS_EMAIL_SMTP_* settings it needs, before restarting.`):emailDeliveryConfigFromSettings()??console.info(`Before restarting, complete the outgoing mail server settings: PS_EMAIL_SMTP_HOST and PS_EMAIL_FROM_ADDRESS, plus the other PS_EMAIL_SMTP_* settings your server needs.`),reportConfiguredMode(AuthModes.email,o.libraryRoot);else{oidcClientConfigFromSettings()??console.info(`Before restarting, set the OIDC provider: PS_OIDC_ISSUER, PS_OIDC_CLIENT_ID and PS_OIDC_CLIENT_SECRET.`);let e=authCanonicalOriginFromSettings();console.info(`Your OIDC provider must allow the redirect URI ${e==null?`made of PS_EXTERNAL_ORIGIN followed by `+OidcCallbackPath:new URL(OidcCallbackPath,e).href}.`),reportConfiguredMode(AuthModes.oidc,o.libraryRoot)}}s!=null&&!savedAuthModeFromSettings().present&&warnNoMode(r)}async function run(){try{await runAuth(),await exit({status:0})}catch(e){console.error(e instanceof Error?e.message:String(e)),await exit({status:1,reason:`Authentication configuration failed`})}}run();
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
//# debugId=87b33af5-bf87-595b-9a2a-589b2b45fd73
|