photostructure 0.6.0-alpha.2 → 2026.4.7-beta
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/LICENSE.md +31 -29
- package/README.md +20 -8
- package/SECURITY.md +29 -0
- package/VERSION.json +12 -0
- package/bin/bootstrap.js +9 -0
- package/bin/fix.js +9 -0
- package/bin/info.js +9 -0
- package/bin/list.js +9 -0
- package/bin/logcat.js +9 -0
- package/bin/logtail.js +9 -0
- package/bin/main.js +9 -0
- package/bin/photostructure.js +9 -0
- package/bin/sync.js +9 -0
- package/bin/web.js +9 -0
- package/bin/worker.js +9 -0
- package/data/cuss.txt.br +0 -0
- package/data/icc/AdobeCompat-v2.icc +0 -0
- package/data/icc/AppleCompat-v2.icc +0 -0
- package/data/icc/ColorMatchCompat-v2.icc +0 -0
- package/data/icc/DisplayP3-v2-magic.icc +0 -0
- package/data/icc/DisplayP3-v2-micro.icc +0 -0
- package/data/icc/DisplayP3-v4.icc +0 -0
- package/data/icc/DisplayP3Compat-v2-magic.icc +0 -0
- package/data/icc/DisplayP3Compat-v2-micro.icc +0 -0
- package/data/icc/DisplayP3Compat-v4.icc +0 -0
- package/data/icc/ProPhoto-v2-magic.icc +0 -0
- package/data/icc/ProPhoto-v2-micro.icc +0 -0
- package/data/icc/ProPhoto-v4.icc +0 -0
- package/data/icc/Rec2020-v2-magic.icc +0 -0
- package/data/icc/Rec2020-v2-micro.icc +0 -0
- package/data/icc/Rec2020-v4.icc +0 -0
- package/data/icc/Rec2020Compat-v2-magic.icc +0 -0
- package/data/icc/Rec2020Compat-v2-micro.icc +0 -0
- package/data/icc/Rec2020Compat-v4.icc +0 -0
- package/data/icc/Rec709-v2-magic.icc +0 -0
- package/data/icc/Rec709-v2-micro.icc +0 -0
- package/data/icc/Rec709-v4.icc +0 -0
- package/data/icc/WideGamutCompat-v2.icc +0 -0
- package/data/icc/_info.md +49 -0
- package/data/icc/license +116 -0
- package/data/icc/readme.md +142 -0
- package/data/icc/sGrey-v2-magic.icc +0 -0
- package/data/icc/sGrey-v2-micro.icc +0 -0
- package/data/icc/sGrey-v2-nano.icc +0 -0
- package/data/icc/sGrey-v4.icc +0 -0
- package/data/icc/sRGB-v2-magic.icc +0 -0
- package/data/icc/sRGB-v2-micro.icc +0 -0
- package/data/icc/sRGB-v2-nano.icc +0 -0
- package/data/icc/sRGB-v4.icc +0 -0
- package/data/icc/scRGB-v2.icc +0 -0
- package/data/migrations/models/20181030_models.sql +151 -0
- package/data/migrations/models/20190417_rotation.sql +2 -0
- package/data/migrations/models/20190425_merged_assets.sql +11 -0
- package/{migrations → data/migrations}/models/20190426_clean_sha.sql +4 -4
- package/data/migrations/models/20190426_lowercase_psnet_hostname.sql +1 -0
- package/{migrations → data/migrations}/models/20190727_find_by_ca_and_geo.sql +3 -1
- package/data/migrations/models/20190730_session.sql +7 -0
- package/data/migrations/models/20190922_numeric_captured_at.sql +1 -0
- package/data/migrations/models/20190923_asset_file_v2_nofk.sql +107 -0
- package/data/migrations/models/20191013_asset_v2_nofk.sql +81 -0
- package/data/migrations/models/20200104_video_duration.sql +9 -0
- package/data/migrations/models/20200116_heartbeat.sql +9 -0
- package/data/migrations/models/20200127_spread_modes.sql +1 -0
- package/data/migrations/models/20200128_asset_file_v3_nofk.sql +143 -0
- package/data/migrations/models/20200130_advisory_lock.sql +21 -0
- package/data/migrations/models/20200211_updateCount.sql +2 -0
- package/data/migrations/models/20200512_asset_file_v4_nofk.sql +145 -0
- package/data/migrations/models/20200515_drop_merged_asset.sql +1 -0
- package/data/migrations/models/20200816_normalize_asset_file_uris.sql +1 -0
- package/data/migrations/models/20200823_add_asset_excluded.sql +11 -0
- package/data/migrations/models/20200825_fix_root_tags.sql +1 -0
- package/data/migrations/models/20200826_dedupe_tag_paths.sql +1 -0
- package/data/migrations/models/20200827_tag_v2_nofk.sql +35 -0
- package/data/migrations/models/20200923_suffix_tag_paths.sql +1 -0
- package/data/migrations/models/20200927_progress_v2.sql +23 -0
- package/data/migrations/models/20201006_progress_meta.sql +16 -0
- package/data/migrations/models/20201007_operation.sql +12 -0
- package/data/migrations/models/20201023_dedupe_tag_paths.sql +1 -0
- package/data/migrations/models/20201026_normalize_asset_file_uris.sql +1 -0
- package/data/migrations/models/20201030_add_tag_counts.sql +5 -0
- package/data/migrations/models/20201106_normalize_tag_paths.sql +1 -0
- package/data/migrations/models/20201112_tag_display_name.sql +2 -0
- package/data/migrations/models/20201113_drop_tc_tables.sql +1 -0
- package/data/migrations/models/20201211_tag_description.sql +5 -0
- package/data/migrations/models/20210322_sha_blocklist.sql +6 -0
- package/data/migrations/models/20210323_create_tag_fts.sql +1 -0
- package/data/migrations/models/20210324_asset_fave_delete.sql +20 -0
- package/data/migrations/models/20210531_asset_duration.sql +20 -0
- package/data/migrations/models/20210604_changed_tag.sql +7 -0
- package/data/migrations/models/20210627_changed_tag_updated_at.sql +2 -0
- package/data/migrations/models/20210827_asset_excluded_at.sql +19 -0
- package/data/migrations/models/20210930_asset_file_rating.sql +2 -0
- package/data/migrations/models/20210930_asset_revision.sql +16 -0
- package/data/migrations/models/20211025_ts_cleanup.sql +11 -0
- package/data/migrations/models/20220222_rebuild_rotated_heic.sql +2 -0
- package/data/migrations/models/20220922_rebuild_videos.sql +3 -0
- package/data/migrations/models/20220923_add_asset_file_mode_pct.sql +63 -0
- package/data/migrations/models/20221031_add_asset_file_hashes.sql +5 -0
- package/data/migrations/models/20231105_copy_asset_duration.sql +3 -0
- package/data/migrations/models/20231115_strict_nofk.sql +674 -0
- package/data/migrations/models/20231116_rebuild_tag_asset_counts.sql +1 -0
- package/data/migrations/models/20240115_task.sql +18 -0
- package/data/migrations/models/20240131_drop_operation_version.sql +35 -0
- package/data/migrations/models/20240201_create_tag_fts.sql +1 -0
- package/data/migrations/models/20240307_rebuild_progress_nofk.sql +59 -0
- package/data/migrations/models/20240313_rebuild_null_island.sql +3 -0
- package/data/migrations/models/20240723_add_asset_file_image_data_hash.sql +2 -0
- package/data/migrations/models/20240920_drop_task.sql +1 -0
- package/data/migrations/models/20240929_metadata_local.sql +3 -0
- package/data/migrations/models/20250421_asset_tag_fk_indexes.sql +21 -0
- package/data/migrations/models/20250421_tag_hierarchy.sql +13 -0
- package/data/migrations/models/20250422_schema_v3.sql +170 -0
- package/data/migrations/models/20250423_schema_v3_backfill_nofk.sql +1 -0
- package/data/migrations/models/20250929_indexes.sql +80 -0
- package/data/migrations/models/20260117_scan_generation.sql +31 -0
- package/data/migrations/models/20260122_fix_scan_generation_idx.sql +5 -0
- package/data/migrations/models/20260204_vec0_captured_at_local.sql +10 -0
- package/data/migrations/models/20260217_reaggregate_to_validate_siblings.sql +8 -0
- package/data/migrations/models/20260321_captured_at_src_detail.sql +3 -0
- package/data/migrations/models/20260322_captured_at_src_backfill.sql +2 -0
- package/data/migrations/models/20260403_drop_tag_fts.sql +5 -0
- package/data/migrations/models/20260425_volume_label.sql +5 -0
- package/data/migrations/models/20260426_vec0_bname.sql +6 -0
- package/data/models-schema.json +907 -0
- package/data/models-schema.sql +268 -0
- package/data/words.txt.br +0 -0
- package/defaults.env +6376 -0
- package/package.json +47 -25
- package/photostructure +26 -27
- package/public/192.png.gz +0 -0
- package/public/3rd-party-licenses.html.gz +0 -0
- package/public/3rd-party-licenses.txt.gz +0 -0
- package/public/512.png.gz +0 -0
- package/public/app/Array.js +8 -0
- package/public/app/Array.js.gz +0 -0
- package/public/app/BabyMarkdown.js +14 -0
- package/public/app/BabyMarkdown.js.gz +0 -0
- package/public/app/DropDown.vue_vue_type_script_setup_true_lang.js +12 -0
- package/public/app/DropDown.vue_vue_type_script_setup_true_lang.js.gz +0 -0
- package/public/app/HealthChecks.js +8 -0
- package/public/app/HealthChecks.js.gz +0 -0
- package/public/app/Lazy.js +8 -0
- package/public/app/Lazy.js.gz +0 -0
- package/public/app/PageActionsMenu.vue_vue_type_script_setup_true_lang.js +8 -0
- package/public/app/PageActionsMenu.vue_vue_type_script_setup_true_lang.js.gz +0 -0
- package/public/app/ProgressState.js +8 -0
- package/public/app/Random.js +8 -0
- package/public/app/SSEChannels.js +8 -0
- package/public/app/SSEChannels.js.gz +0 -0
- package/public/app/Search.js +8 -0
- package/public/app/Search.js.gz +0 -0
- package/public/app/StickyHeader.js +8 -0
- package/public/app/StickyHeader.js.gz +0 -0
- package/public/app/Tag.js +8 -0
- package/public/app/Tag.js.gz +0 -0
- package/public/app/_plugin-vue_export-helper.js +8 -0
- package/public/app/_plugin-vue_export-helper.js.gz +0 -0
- package/public/app/about.css +8 -0
- package/public/app/about.css.gz +0 -0
- package/public/app/about.js +8 -0
- package/public/app/about.js.gz +0 -0
- package/public/app/app.css +8 -0
- package/public/app/app.css.gz +0 -0
- package/public/app/app.js +12 -0
- package/public/app/app.js.gz +0 -0
- package/public/app/health.css +8 -0
- package/public/app/health.css.gz +0 -0
- package/public/app/health.js +10 -0
- package/public/app/health.js.gz +0 -0
- package/public/app/logs.css +8 -0
- package/public/app/logs.css.gz +0 -0
- package/public/app/logs.js +8 -0
- package/public/app/logs.js.gz +0 -0
- package/public/app/onReady.js +8 -0
- package/public/app/platform.js +8 -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-v30-latin-700.woff2.gz +0 -0
- package/public/app/roboto-v30-latin-700italic.woff2.gz +0 -0
- package/public/app/roboto-v30-latin-italic.woff2.gz +0 -0
- package/public/app/roboto-v30-latin-regular.woff2.gz +0 -0
- package/public/app/settings.css +8 -0
- package/public/app/settings.css.gz +0 -0
- package/public/app/settings.js +8 -0
- package/public/app/settings.js.gz +0 -0
- package/public/app/splash.css +8 -0
- package/public/app/splash.css.gz +0 -0
- package/public/app/splash.js +8 -0
- package/public/app/splash.js.gz +0 -0
- package/public/app/sse-worker.js +8 -0
- package/public/app/sse-worker.js.gz +0 -0
- package/public/app/sync.css +8 -0
- package/public/app/sync.css.gz +0 -0
- package/public/app/sync.js +12 -0
- package/public/app/sync.js.gz +0 -0
- package/public/app/toast.js +9 -0
- package/public/app/toast.js.gz +0 -0
- package/public/app/useAnchorHighlight.js +8 -0
- package/public/app/useSectionPersistence.js +8 -0
- package/public/app/useSectionPersistence.js.gz +0 -0
- package/public/apple-touch-icon.png.gz +0 -0
- package/public/browserconfig.xml +9 -0
- package/public/eula.html +25 -26
- package/public/favicon-16x16.png.gz +0 -0
- package/public/favicon-32x32.png.gz +0 -0
- package/public/favicon.ico +0 -0
- package/public/fonts/roboto-mono-v22-latin-700.woff2.gz +0 -0
- package/public/fonts/roboto-mono-v22-latin-regular.woff2.gz +0 -0
- package/public/fonts/roboto-v30-latin-700.woff2.gz +0 -0
- package/public/fonts/roboto-v30-latin-700italic.woff2.gz +0 -0
- package/public/fonts/roboto-v30-latin-italic.woff2.gz +0 -0
- package/public/fonts/roboto-v30-latin-regular.woff2.gz +0 -0
- package/public/icon.svg.gz +0 -0
- package/public/images/1.png.gz +0 -0
- package/public/images/128.png +0 -0
- package/public/images/22-Template.png.gz +0 -0
- package/public/images/22-Template@2x.png.gz +0 -0
- package/public/images/22-Template@3x.png.gz +0 -0
- package/public/images/22-blue.png.gz +0 -0
- package/public/images/22-blue@2x.png.gz +0 -0
- package/public/images/22-blue@3x.png.gz +0 -0
- package/public/images/22-dark.png +0 -0
- package/public/images/22-dark@2x.png +0 -0
- package/public/images/22-dark@3x.png +0 -0
- package/public/images/22-gradient.png.gz +0 -0
- package/public/images/22-gradient@2x.png.gz +0 -0
- package/public/images/22-gradient@3x.png.gz +0 -0
- package/public/images/22-light.png +0 -0
- package/public/images/22-light@2x.png +0 -0
- package/public/images/22-light@3x.png +0 -0
- package/public/images/256.png +0 -0
- package/public/images/512.png.gz +0 -0
- package/public/images/64.png +0 -0
- package/public/images/antenna.svg.gz +0 -0
- package/public/images/article.svg.gz +0 -0
- package/public/images/baby.svg.gz +0 -0
- package/public/images/ballot-box.svg.gz +0 -0
- package/public/images/bank.svg.gz +0 -0
- package/public/images/bar-chart.svg.gz +0 -0
- package/public/images/beetle.svg.gz +0 -0
- package/public/images/birthday.svg.gz +0 -0
- package/public/images/bookmark-tabs.svg.gz +0 -0
- package/public/images/books-desat.svg.gz +0 -0
- package/public/images/books.svg.gz +0 -0
- package/public/images/busy-circle.svg.gz +0 -0
- package/public/images/busy-circles.svg.gz +0 -0
- package/public/images/busy-dots.svg.gz +0 -0
- package/public/images/busy.svg.gz +0 -0
- package/public/images/calendar.svg.gz +0 -0
- package/public/images/camera.svg.gz +0 -0
- package/public/images/card-box.svg.gz +0 -0
- package/public/images/card-index-dividers.svg.gz +0 -0
- package/public/images/cd.svg.gz +0 -0
- package/public/images/chart.svg.gz +0 -0
- package/public/images/check.svg.gz +0 -0
- package/public/images/checkered-flag.svg.gz +0 -0
- package/public/images/clear-256.png.gz +0 -0
- package/public/images/clear-64.png.gz +0 -0
- package/public/images/clock.svg.gz +0 -0
- package/public/images/computer.svg.gz +0 -0
- package/public/images/cpu.svg.gz +0 -0
- package/public/images/crane.svg.gz +0 -0
- package/public/images/cross-mark.svg.gz +0 -0
- package/public/images/disabled.svg.gz +0 -0
- package/public/images/dvd.svg.gz +0 -0
- package/public/images/emergency-light.svg.gz +0 -0
- package/public/images/error.svg.gz +0 -0
- package/public/images/expressionless-desat.svg.gz +0 -0
- package/public/images/expressionless.svg.gz +0 -0
- package/public/images/file-cabinet.svg.gz +0 -0
- package/public/images/fill.svg.gz +0 -0
- package/public/images/floppy.svg.gz +0 -0
- package/public/images/gift.svg.gz +0 -0
- package/public/images/green-check.svg.gz +0 -0
- package/public/images/green-radio.svg.gz +0 -0
- package/public/images/handshake.svg.gz +0 -0
- package/public/images/health.svg.gz +0 -0
- package/public/images/heart.svg.gz +0 -0
- package/public/images/home.svg.gz +0 -0
- package/public/images/homebrew-installer.png.gz +0 -0
- package/public/images/info.svg.gz +0 -0
- package/public/images/library.svg.gz +0 -0
- package/public/images/logo-blue.svg.gz +0 -0
- package/public/images/logo-circle.svg.gz +0 -0
- package/public/images/logo-dark-700pt.svg.gz +0 -0
- package/public/images/logo-dark.svg.gz +0 -0
- package/public/images/logo-gradient-gloss-512w.png.gz +0 -0
- package/public/images/logo-gradient-gloss.svg.gz +0 -0
- package/public/images/logo-gradient-square-512w.png.gz +0 -0
- package/public/images/logo-gradient.svg.gz +0 -0
- package/public/images/logo-horizontal-600w.png.gz +0 -0
- package/public/images/logo-horizontal-white.svg.gz +0 -0
- package/public/images/logo-horizontal.svg.gz +0 -0
- package/public/images/logo-lite.svg.gz +0 -0
- package/public/images/logo-plus-512w.png.gz +0 -0
- package/public/images/logo-plus-horizontal.svg.gz +0 -0
- package/public/images/logo-plus.svg.gz +0 -0
- package/public/images/logo-square.svg.gz +0 -0
- package/public/images/logo-white.svg.gz +0 -0
- package/public/images/logo.ico +0 -0
- package/public/images/logo.png +0 -0
- package/public/images/logo@2x.png.gz +0 -0
- package/public/images/logo@3x.png.gz +0 -0
- package/public/images/logo@4x.png.gz +0 -0
- package/public/images/logo@5x.png +0 -0
- package/public/images/maximize.svg.gz +0 -0
- package/public/images/microscope.svg.gz +0 -0
- package/public/images/minidisc.svg.gz +0 -0
- package/public/images/movie-camera.svg.gz +0 -0
- package/public/images/navigate_next.svg.gz +0 -0
- package/public/images/new-yellow.svg.gz +0 -0
- package/public/images/new.svg.gz +0 -0
- package/public/images/open-book.svg.gz +0 -0
- package/public/images/open-folder.svg.gz +0 -0
- package/public/images/pause.svg.gz +0 -0
- package/public/images/photostructure-black.svg.gz +0 -0
- package/public/images/photostructure-white.svg.gz +0 -0
- package/public/images/refresh.svg.gz +0 -0
- package/public/images/rocket.svg.gz +0 -0
- package/public/images/sad-cat.svg.gz +0 -0
- package/public/images/safe.svg.gz +0 -0
- package/public/images/scales.svg.gz +0 -0
- package/public/images/seedling.svg.gz +0 -0
- package/public/images/shield.svg.gz +0 -0
- package/public/images/sleeping-face-desat.svg.gz +0 -0
- package/public/images/sleeping-face.svg.gz +0 -0
- package/public/images/sparkles.svg.gz +0 -0
- package/public/images/speed.svg.gz +0 -0
- package/public/images/splash.svg +1 -1
- package/public/images/splashbg1-1024w.jpg +0 -0
- package/public/images/splashbg2-1024w.jpg +0 -0
- package/public/images/splashbg3-1024w.jpg +0 -0
- package/public/images/splashbg4-1024w.jpg +0 -0
- package/public/images/splashbg5-1024w.jpg +0 -0
- package/public/images/splashbg6-1024w.jpg +0 -0
- package/public/images/star2.svg.gz +0 -0
- package/public/images/starry-night.svg.gz +0 -0
- package/public/images/stethoscope.svg.gz +0 -0
- package/public/images/stop.svg.gz +0 -0
- package/public/images/surf.svg.gz +0 -0
- package/public/images/sync.svg.gz +0 -0
- package/public/images/tada.svg.gz +0 -0
- package/public/images/terminal.svg.gz +0 -0
- package/public/images/thinking.svg.gz +0 -0
- package/public/images/thumbs-down.svg.gz +0 -0
- package/public/images/thumbs-up.svg.gz +0 -0
- package/public/images/toolbox.svg.gz +0 -0
- package/public/images/tools.svg.gz +0 -0
- package/public/images/umbrella.svg.gz +0 -0
- package/public/images/warning.svg.gz +0 -0
- package/public/images/wave.svg.gz +0 -0
- package/public/images/wrench.svg.gz +0 -0
- package/public/images/xray.svg.gz +0 -0
- package/public/images/zzz.svg.gz +0 -0
- package/public/mstile-144x144.png.gz +0 -0
- package/public/mstile-150x150.png.gz +0 -0
- package/public/mstile-310x150.png.gz +0 -0
- package/public/mstile-310x310.png.gz +0 -0
- package/public/mstile-70x70.png.gz +0 -0
- package/public/safari-pinned-tab.svg.gz +0 -0
- package/public/sw.js +5 -0
- package/server/bin/install-codec-tools.sh +48 -0
- package/server/sudoers.d/photostructure-codec-install +18 -0
- package/tools/README.md +23 -0
- package/tools/build.sh +30 -0
- package/tools/download-rg.sh +61 -0
- package/tools/license-overrides/photostructure-sqlite-vec-MIT.txt +21 -0
- package/tools/licenses/d3-color-difference/LICENSE.txt +29 -0
- package/tools/licenses/deep-eql/LICENSE.txt +21 -0
- package/tools/licenses/exiftool/{license.txt → LICENSE.txt} +140 -140
- package/tools/licenses/fft.js/LICENSE.txt +9 -0
- package/tools/licenses/libjpeg-turbo/LICENSE.md +7 -16
- package/tools/licenses/libraw/COPYRIGHT.txt +27 -0
- package/tools/licenses/moveable-type/LICENSE.txt +6 -0
- package/tools/licenses/noto-emoji/LICENSE.txt +201 -0
- package/tools/licenses/sharp-phash/LICENSE.txt +21 -0
- package/tools/licenses/{twemoji → type-detect}/LICENSE.txt +1 -1
- package/tools/linux-arm64/dcraw_emu +0 -0
- package/tools/linux-arm64/jpegtran +0 -0
- package/tools/linux-arm64/raw-identify +0 -0
- package/tools/linux-arm64/rg +0 -0
- package/tools/linux-arm64/sqlite3 +0 -0
- package/tools/linux-x64/dcraw_emu +0 -0
- package/tools/linux-x64/jpegtran +0 -0
- package/tools/linux-x64/raw-identify +0 -0
- package/tools/linux-x64/rg +0 -0
- package/tools/linux-x64/sqlite3 +0 -0
- package/tools/mac-arm64/dcraw_emu +0 -0
- package/tools/mac-arm64/jpegtran +0 -0
- package/tools/mac-arm64/jpegtran-README.md +31 -0
- package/tools/mac-arm64/libraw-README.md +42 -0
- package/tools/mac-arm64/raw-identify +0 -0
- package/tools/mac-arm64/rg +0 -0
- package/tools/mac-arm64/sqlite3 +0 -0
- package/tools/mac-arm64/sqlite3-README.md +35 -0
- package/tools/mac-x64/dcraw_emu +0 -0
- package/tools/mac-x64/jpegtran +0 -0
- package/tools/mac-x64/jpegtran-README.md +30 -0
- package/tools/mac-x64/libraw-README.md +52 -0
- package/tools/mac-x64/raw-identify +0 -0
- package/tools/mac-x64/rg +0 -0
- package/tools/mac-x64/sqlite3 +0 -0
- package/tools/mac-x64/sqlite3-README.md +6 -0
- package/tools/win-x64/dcraw_emu.exe +0 -0
- package/tools/{win-ia32/jpegtran → win-x64}/jpegtran.exe +0 -0
- package/tools/{win-ia32/jpegtran → win-x64}/libjpeg-62.dll +0 -0
- package/tools/win-x64/libraw-README.md +6 -0
- package/tools/win-x64/libraw.dll +0 -0
- package/tools/win-x64/raw-identify.exe +0 -0
- package/tools/win-x64/recycle-bin-README.md +3 -0
- package/tools/win-x64/recycle-bin.exe +0 -0
- package/tools/win-x64/rg.exe +0 -0
- package/tools/win-x64/sqlite3-README.md +4 -0
- package/tools/win-x64/sqlite3.exe +0 -0
- package/views/_fouc-prevention.ejs +13 -0
- package/views/error.ejs +64 -0
- package/views/eula.html +57 -0
- package/views/settings.ejs +958 -0
- package/views/spa.ejs +54 -0
- package/views/splash.ejs +30 -0
- package/views/welcome-tools.ejs +201 -0
- package/views/welcome.ejs +89 -0
- package/app/info.js +0 -3
- package/app/logtail.js +0 -3
- package/app/main.js +0 -3
- package/app/sync-file.js +0 -3
- package/app/sync.js +0 -3
- package/app/web.js +0 -3
- package/migrations/models/20181030_models.sql +0 -145
- package/migrations/models/20190417_rotation.sql +0 -1
- package/migrations/models/20190425_merged_assets.sql +0 -10
- package/migrations/models/20190426_lowercase_psnet_hostname.sql +0 -1
- package/migrations/models/20190522_on_new_exif_uid.sql +0 -1
- package/migrations/models/20190729_on_new_exif_uid.sql +0 -1
- package/migrations/models/20190730_session.sql +0 -6
- package/migrations/stats/20181030_stats.sql +0 -16
- package/migrations/stats/20190312_files_not_bytes.sql +0 -23
- package/migrations/stats/20190515_rebuild_queue.sql +0 -21
- package/public/app/latest.js.gz +0 -0
- package/public/fonts/roboto-mono-v5-latin-regular.woff.gz +0 -0
- package/public/fonts/roboto-mono-v5-latin-regular.woff2.gz +0 -0
- package/public/fonts/roboto-v18-latin-300.woff.gz +0 -0
- package/public/fonts/roboto-v18-latin-300.woff2.gz +0 -0
- package/public/fonts/roboto-v18-latin-500.woff.gz +0 -0
- package/public/fonts/roboto-v18-latin-500.woff2.gz +0 -0
- package/public/fonts/roboto-v18-latin-700.woff.gz +0 -0
- package/public/fonts/roboto-v18-latin-700.woff2.gz +0 -0
- package/public/fonts/roboto-v18-latin-900.woff.gz +0 -0
- package/public/fonts/roboto-v18-latin-900.woff2.gz +0 -0
- package/public/fonts/roboto-v18-latin-italic.woff.gz +0 -0
- package/public/fonts/roboto-v18-latin-italic.woff2.gz +0 -0
- package/public/fonts/roboto-v18-latin-regular.woff.gz +0 -0
- package/public/fonts/roboto-v18-latin-regular.woff2.gz +0 -0
- package/public/images/128.png.gz +0 -0
- package/public/images/256-gradient.png +0 -0
- package/public/images/256-gradient.png.gz +0 -0
- package/public/images/256.png.gz +0 -0
- package/public/images/64.png.gz +0 -0
- package/public/images/bg.svg.gz +0 -0
- package/public/images/bg10.jpg.gz +0 -0
- package/public/images/blue-splash-1024w.png.gz +0 -0
- package/public/images/blue-tri-bg.svg.gz +0 -0
- package/public/images/boom.svg.gz +0 -0
- package/public/images/dark-cyan-fuschia-bg.svg.gz +0 -0
- package/public/images/fit.svg.gz +0 -0
- package/public/images/light-cyan-fuschia-bg.svg.gz +0 -0
- package/public/images/line-logo-top-cuts-filled.svg.gz +0 -0
- package/public/images/line-logo-top-cuts.svg.gz +0 -0
- package/public/images/link.svg.gz +0 -0
- package/public/images/logo-gradient-gloss-sq.svg.gz +0 -0
- package/public/images/logo-gradient.svg +0 -1
- package/public/images/logo-icon-path.svg.gz +0 -0
- package/public/images/logo-text-path.svg.gz +0 -0
- package/public/images/logo-text-white.svg.gz +0 -0
- package/public/images/navigate_prev.svg.gz +0 -0
- package/public/images/no-entry.svg.gz +0 -0
- package/public/images/phone.svg.gz +0 -0
- package/public/images/private.svg.gz +0 -0
- package/public/images/profile.svg.gz +0 -0
- package/public/images/public.svg.gz +0 -0
- package/public/images/show-in-folder-black.svg.gz +0 -0
- package/public/images/show-in-folder.svg.gz +0 -0
- package/public/images/shrug.svg.gz +0 -0
- package/public/images/splash-1024w.png +0 -0
- package/public/images/splash-1024w.png.gz +0 -0
- package/public/images/splash-512w.png +0 -0
- package/public/images/splash-512w.png.gz +0 -0
- package/public/images/splash-blue.svg +0 -1
- package/public/images/splashbg01-1024w.jpg +0 -0
- package/public/images/splashbg01-1024w.jpg.gz +0 -0
- package/public/images/splashbg02-1024w.jpg +0 -0
- package/public/images/splashbg02-1024w.jpg.gz +0 -0
- package/public/images/text-logo-blue.svg.gz +0 -0
- package/public/images/transparent-white.svg.gz +0 -0
- package/public/images/trash.svg.gz +0 -0
- package/public/release-notes.html +0 -581
- package/public/splash.html +0 -360
- package/tools/licenses/dcraw/dcraw.txt +0 -24
- package/tools/licenses/vue-my-dropdown/LICENSE.txt +0 -19
- package/tools/linux-arm/dcraw/dcraw +0 -0
- package/tools/linux-arm/dcraw/install.sh +0 -5
- package/tools/linux-arm/jpegtran/README.md +0 -11
- package/tools/linux-arm/jpegtran/jpegtran +0 -0
- package/tools/linux-arm/sqlite3/sqlite3 +0 -0
- package/tools/linux-ia32/sqlite3/sqlite3 +0 -0
- package/tools/linux-x64/dcraw/dcraw +0 -0
- package/tools/linux-x64/jpegtran/jpegtran +0 -0
- package/tools/mac-x64/dcraw/dcraw +0 -0
- package/tools/mac-x64/dcraw/install.sh +0 -8
- package/tools/mac-x64/jpegtran/jpegtran +0 -0
- package/tools/mac-x64/sqlite3/README.md +0 -33
- package/tools/mac-x64/sqlite3/sqlite3 +0 -0
- package/tools/win-ia32/dcraw/README.md +0 -30
- package/tools/win-ia32/dcraw/dcraw.exe +0 -0
- package/tools/win-ia32/sqlite3/sqlite3.exe +0 -0
package/bin/info.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// Copyright © 2026, PhotoStructure Inc. All rights reserved.
|
|
4
|
+
|
|
5
|
+
// BY USING THIS SOFTWARE, YOU ACCEPT ALL OF THE TERMS IN
|
|
6
|
+
// https://photostructure.com/eula
|
|
7
|
+
// IF YOU DO NOT ACCEPT THESE TERMS, DO NOT USE THIS SOFTWARE
|
|
8
|
+
|
|
9
|
+
(()=>{var e={60308(e){const t={PasetoNotSupported:"ERR_PASETO_NOT_SUPPORTED",PasetoDecryptionFailed:"ERR_PASETO_DECRYPTION_FAILED",PasetoInvalid:"ERR_PASETO_INVALID",PasetoVerificationFailed:"ERR_PASETO_VERIFICATION_FAILED",PasetoClaimInvalid:"ERR_PASETO_CLAIM_INVALID"};class i extends Error{constructor(e){super(e),this.name=this.constructor.name,this.code=t[this.constructor.name],Error.captureStackTrace(this,this.constructor)}}e.exports.PasetoError=i,e.exports.PasetoNotSupported=class extends i{},e.exports.PasetoDecryptionFailed=class extends i{},e.exports.PasetoInvalid=class extends i{},e.exports.PasetoVerificationFailed=class extends i{},e.exports.PasetoClaimInvalid=class extends i{}},78972(e,t,i){const{PasetoInvalid:r,PasetoNotSupported:s}=i(60308),{decode:n}=i(47859),a=i(40816);e.exports=(e,{parse:t=!0}={})=>{if("string"!=typeof e)throw new TypeError("token must be a string");const{0:i,1:o,2:l,3:u,length:c}=e.split(".");if(3!==c&&4!==c)throw new r("token is not a PASETO formatted value");if("v1"!==i&&"v2"!==i&&"v3"!==i&&"v4"!==i)throw new s("unsupported PASETO version");if("local"!==o&&"public"!==o)throw new s("unsupported PASETO purpose");const d={footer:u?n(u):void 0,payload:void 0,version:i,purpose:o};if("local"===o)return d;const h="v1"===i?256:"v3"===i?96:64;let f;try{f=n(l).subarray(0,-h)}catch{throw new r("token is not a PASETO formatted value")}return d.payload=t?a(f):f,d}},2744(e,t,i){const r=i(78972);e.exports={decode:r}},67814(e,t,i){const r=i(85223);e.exports=({audience:e,expiresIn:t,iat:i=!0,issuer:s,jti:n,kid:a,notBefore:o,now:l=new Date,subject:u},c)=>{if(!(l instanceof Date&&l.getTime()))throw new TypeError("options.now must be a valid Date object");const d=l.getTime();if(void 0!==i){if("boolean"!=typeof i)throw new TypeError("options.iat must be a boolean");i&&(c.iat=new Date(d))}if(void 0!==t){if("string"!=typeof t)throw new TypeError("options.expiresIn must be a string");c.exp=new Date(d+r(t))}if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.notBefore must be a string");c.nbf=new Date(d+r(o))}if(void 0!==e){if("string"!=typeof e)throw new TypeError("options.audience must be a string");c.aud=e}if(void 0!==s){if("string"!=typeof s)throw new TypeError("options.issuer must be a string");c.iss=s}if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.subject must be a string");c.sub=u}if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.kid must be a string");c.kid=a}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.jti must be a string");c.jti=n}return c}},10968(e,t,i){const{PasetoClaimInvalid:r}=i(60308),s=i(85223);e.exports=({ignoreExp:e,ignoreNbf:t,ignoreIat:i,maxTokenAge:n,subject:a,issuer:o,clockTolerance:l,audience:u,now:c=new Date},d)=>{if(!(c instanceof Date&&c.getTime()))throw new TypeError("options.now must be a valid Date object");const h=c.getTime();if("iss"in d&&"string"!=typeof d.iss)throw new r("payload.iss must be a string");if(void 0!==o){if("string"!=typeof o)throw new TypeError("options.issuer must be a string");if(d.iss!==o)throw new r("issuer mismatch")}if("sub"in d&&"string"!=typeof d.sub)throw new r("payload.sub must be a string");if(void 0!==a){if("string"!=typeof a)throw new TypeError("options.subject must be a string");if(d.sub!==a)throw new r("subject mismatch")}if("aud"in d&&"string"!=typeof d.aud)throw new r("payload.aud must be a string");if(void 0!==u){if("string"!=typeof u)throw new TypeError("options.audience must be a string");if(d.aud!==u)throw new r("audience mismatch")}if(void 0!==l&&"string"!=typeof l)throw new TypeError("options.clockTolerance must be a string");const f=l?s(l):0;let m;if("iat"in d){if("string"!=typeof d.iat)throw new r("payload.iat must be a string");if(m=new Date(d.iat).getTime(),!m)throw new r("payload.iat must be a valid ISO8601 string");if(!i&&m>h+f)throw new r("token issued in the future")}if("nbf"in d){if("string"!=typeof d.nbf)throw new r("payload.nbf must be a string");const e=new Date(d.nbf).getTime();if(!e)throw new r("payload.nbf must be a valid ISO8601 string");if(!t&&e>h+f)throw new r("token is not active yet")}if("exp"in d){if("string"!=typeof d.exp)throw new r("payload.exp must be a string");const t=new Date(d.exp).getTime();if(!t)throw new r("payload.exp must be a valid ISO8601 string");if(!e&&t<=h-f)throw new r("token is expired")}if(void 0!==n){if("string"!=typeof n)throw new TypeError("options.maxTokenAge must be a string");if(!("iat"in d))throw new r("missing iat claim");if(m+s(n)<h+f)throw new r("maxTokenAge exceeded")}}},47859(e){e.exports.encode=e=>e.toString("base64url"),e.exports.decode=e=>Buffer.from(e,"base64")},80608(e){e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if("string"!=typeof e)throw new TypeError("options.assertion must be a string, or a Buffer");return Buffer.from(e,"utf8")}},83561(e,t,i){const r=i(65825);e.exports=function(e){if(void 0===e)return Buffer.from("");if(Buffer.isBuffer(e))return e;if(r(e))return Buffer.from(JSON.stringify(e),"utf8");if("string"!=typeof e)throw new TypeError("options.footer must be a string, Buffer, or a plain object");return Buffer.from(e,"utf8")}},1658(e,t,i){const r=i(67814),s=i(65825);e.exports=(e,t)=>{if(Buffer.isBuffer(e)){if(0!==Object.keys(t).length)throw new TypeError("options cannot contain claims when payload is a Buffer");return e}if(!s(e))throw new TypeError("payload must be a Buffer or a plain object");return e=(e=>JSON.parse(JSON.stringify(e)))(e),e=r(t,e),Buffer.from(JSON.stringify(e),"utf-8")}},82115(e){e.exports=e=>{const{x:t,y:i}=e.export({format:"jwk"}),r=Buffer.from(i,"base64"),s=2+(1&r[r.length-1]);return Buffer.concat([Buffer.alloc(1,s),Buffer.from(t,"base64")])}},88965(e,t,i){const r=i(64770),{PasetoInvalid:s}=i(60308),n=i(10968),{decode:a}=i(47859),o=i(40816);e.exports={post:function(e,t,i,r,s,a,l){if(t){if(0!==Object.keys(i).length)throw new TypeError("options cannot contain claims when options.buffer is true");return r?{payload:s,footer:a?.length?a:void 0,version:e,purpose:l}:s}const u=o(s);return n(i,u),r?{payload:u,footer:a?.length?a:void 0,version:e,purpose:l}:u},pre:function(e,t){if("string"!=typeof t)throw new TypeError("token must be a string, got: "+typeof t);if(t.slice(0,e.length)!==e)throw new s(`token is not a ${e.slice(0,e.length-1)} PASETO`);let{0:i,1:n="",length:o}=t.slice(e.length).split(".");try{r(o<=2),i=a(i),n=a(n)}catch{throw new s("token is not a PASETO formatted value")}return{raw:i,f:n}}}},56463(e,t,i){const r=i(76982),s=i(92460),n=i(70761),a=i(29534),{PasetoDecryptionFailed:o}=i(60308),l=i(82682),{webcrypto:{subtle:u}}=r,c=s.promisify(r.hkdf),d=Buffer.from("paseto-encryption-key"),h=Buffer.from("paseto-auth-key-for-aead"),f=Buffer.alloc(0),m=(e,t)=>r.createHmac("sha384",t).update(e).digest(),p=async(e,t,i,r)=>u[e]({name:"AES-CTR",counter:r,length:16},await u.importKey("raw",i,"AES-CTR",!1,[e]),t).then(Buffer.from),g=p.bind(void 0,"encrypt"),y=p.bind(void 0,"decrypt");e.exports={sign:s.promisify(r.sign),verify:s.promisify(r.verify),"v1.local-encrypt":async function(e,t,i){const s="v1.local.",o=m(e,r.randomBytes(32)).subarray(0,32),l=o.subarray(0,16),[u,f]=await Promise.all([c("sha384",i,l,d,32).then(Buffer.from),c("sha384",i,l,h,32).then(Buffer.from)]),p=await g(e,u,o.subarray(16)),y=n(s,o,p,t),v=m(y,f);return a(s,t,o,p,v)},"v1.local-decrypt":async function(e,t,i){const r=e.subarray(0,32),s=e.subarray(-48),a=e.subarray(32,-48),u=r.subarray(0,16),[f,p]=await Promise.all([c("sha384",i,u,d,32).then(Buffer.from),c("sha384",i,u,h,32).then(Buffer.from)]),g=n("v1.local.",r,a,t),v=m(g,p);if(!l(s,v))throw new o("decryption failed");const b=await y(a,f,r.subarray(16));if(!b)throw new o("decryption failed");return b},"v3.local-encrypt":async function(e,t,i,s){const o="v3.local.",l=r.randomBytes(32),[u,p]=await Promise.all([c("sha384",i,f,Buffer.concat([d,l]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,l]),48).then(Buffer.from)]),y=u.subarray(0,32),v=u.subarray(32),b=await g(e,y,v),w=n(o,l,b,t,s),S=m(w,p);return a(o,t,l,b,S)},"v3.local-decrypt":async function(e,t,i,r){const s=e.subarray(0,32),a=e.subarray(-48),u=e.subarray(32,-48),[p,g]=await Promise.all([c("sha384",i,f,Buffer.concat([d,s]),48).then(Buffer.from),c("sha384",i,f,Buffer.concat([h,s]),48).then(Buffer.from)]),v=p.subarray(0,32),b=p.subarray(32),w=n("v3.local.",s,u,t,r),S=m(w,g);if(!l(a,S))throw new o("decryption failed");const P=await y(u,v,b);if(!P)throw new o("decryption failed");return P}}},70981(e,t,i){const{KeyObject:r}=i(76982);let{isKeyObject:s}=i(75162);s||(s=e=>null!=e&&e instanceof r),e.exports=s},65825(e){e.exports=e=>!!e&&e.constructor===Object},41726(e,t,i){const{PasetoNotSupported:r}=i(60308);e.exports=e=>{if(!Number.isSafeInteger(e))throw new r("message is too long for Node.js to safely process");const t=~~(e/4294967295),i=e%4294967295-t,s=Buffer.allocUnsafe(8);return s.writeUInt32LE(t,4),s.writeUInt32LE(i,0),s}},85223(e){const t=36e5,i=24*t,r=7*i,s=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;e.exports=e=>{const n=s.exec(e);if(!n)throw new TypeError(`invalid time period format ("${e}")`);const a=parseFloat(n[1]);switch(n[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(1e3*a);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(6e4*a);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(a*t);case"day":case"days":case"d":return Math.round(a*i);case"week":case"weeks":case"w":return Math.round(a*r);case"year":case"years":case"yr":case"yrs":case"y":return Math.round(315576e5*a)}}},29534(e,t,i){const{encode:r}=i(47859);e.exports=function(e,t,...i){let s=`${e}${r(Buffer.concat(i))}`;return t.byteLength&&(s+=`.${r(t)}`),s}},70761(e,t,i){const r=i(41726);e.exports=(...e)=>{e=e.filter(Boolean);let t=r(e.length);for(let i of e){i=Buffer.from(i,"utf8");const e=r(Buffer.byteLength(i));t=Buffer.concat([t,e,i])}return t}},40816(e,t,i){const{PasetoInvalid:r}=i(60308),{strict:s}=i(64770),n=i(65825);e.exports=e=>{try{const t=JSON.parse(e);return s(n(t)),t}catch{throw new r("All PASETO payloads MUST be a JSON object")}}},92366(e,t,i){const{sign:r}=i(56463),s=i(70761),n=i(29534);e.exports=async function(e,t,i,a,o,l,u){const c=s(u,e,t,i,l),d=await r(a,c,o);return n(e,i,t,d)}},495(e,t,i){const{createSecretKey:r}=i(76982),s=i(70981);e.exports=function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}`)&&(t=Buffer.from(t.slice(e.length),"base64url")),!s(t))try{t=r(t)}catch{}if(!s(t))throw new TypeError("invalid key provided");if("secret"!==t.type||32!==t.symmetricKeySize)throw new TypeError(`${e} secret key must be 32 bytes long symmetric key`);return t}},82682(e,t,i){const{timingSafeEqual:r}=i(76982),s=(e,t)=>{if(e.length===t)return e;const i=Buffer.alloc(t);return e.copy(i),i};e.exports=(e,t)=>{const i=Math.max(e.length,t.length);return r(s(e,i),s(t,i))}},49826(e,t,i){const{PasetoVerificationFailed:r}=i(60308),{verify:s}=i(56463),n=i(70761),{pre:a}=i(88965);e.exports=async function(e,t,i,o,l,u,c){const{raw:d,f:h}=a(e,t),f=d.subarray(0,-o),m=d.subarray(-o),p=n(c,e,f,h,u);if(!await s(i,p,l,m))throw new r("invalid signature");return{m:f,footer:h.length?h:void 0}}},91227(e,t,i){const r=i(60308),s=i(79665),n=i(56120),a=i(50015),o=i(64230),{decode:l}=i(2744);e.exports={decode:l,V1:s,V2:n,V3:a,V4:o,errors:r}},39324(e,t,i){const{"v1.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v1.local"),{pre:n,post:a}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:o=!1,...l}={}){const{raw:u,f:c}=n("v1.local.",e),d=(t=s(t)).export(),h=await r(u,c,d);return a("v1",o,l,i,h,c,"local")}},21472(e,t,i){const r=i(83561),s=i(495).bind(void 0,"v1.local"),n=i(1658),{"v1.local-encrypt":a}=i(56463);e.exports=async function(e,t,{footer:i,...o}={}){const l=n(e,o);t=s(t);const u=r(i),c=t.export();return a(l,u,c)}},79665(e,t,i){const r=i(77868),s=i(77256),n=i(21472),a=i(39324),o=i(70866);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o}},70866(e,t,i){const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=s(r.generateKeyPair),o=s(r.generateKey);e.exports=async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await o("aes",{length:256});return"paserk"===t?`k1.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await a("rsa",{modulusLength:2048});return"paserk"===t?{secretKey:`k1.secret.${e.export({format:"der",type:"pkcs1"}).toString("base64url")}`,publicKey:`k1.public.${i.export({format:"der",type:"pkcs1"}).toString("base64url")}`}:e}default:throw new n("unsupported v1 purpose")}}},77868(e,t,i){const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPrivateKey:n}=i(76982),a=i(83561),o=i(1658),l=i(92366),u=i(70981);e.exports=async function(e,t,{footer:i,...c}={}){const d=o(e,c),h=a(i);return t=function(e){if("string"==typeof e&&e.startsWith("k1.secret."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!u(e))try{e=n(e)}catch{}if(!u(e))throw new TypeError("invalid key provided");if("private"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public signing key must be a private RSA key with 2048 bit modulus length");return e}(t),l("v1.public.",d,h,"sha384",{key:t,padding:r,saltLength:s})}},77256(e,t,i){const{constants:{RSA_PKCS1_PSS_PADDING:r,RSA_PSS_SALTLEN_DIGEST:s},createPublicKey:n}=i(76982),a=i(49826),o=i(70981),{post:l}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:u=!1,...c}={}){t=function(e){if("string"==typeof e&&e.startsWith("k1.public."))try{const t=Buffer.from(e.slice(10),"base64url");e={key:t,format:"der",type:"pkcs1"}}catch{}if(!o(e)||"private"===e.type)try{e=n(e)}catch{}if(!o(e))throw new TypeError("invalid key provided");if("public"!==e.type||"rsa"!==e.asymmetricKeyType||2048!==e.asymmetricKeyDetails.modulusLength)throw new TypeError("v1.public verify key must be a public RSA key with 2048 bit modulus length");return e}(t);const{m:d,footer:h}=await a("v1.public.",e,"sha384",256,{key:t,padding:r,saltLength:s});return l("v1",u,c,i,d,h,"public")}},56120(e,t,i){const r=i(88451),s=i(859),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(62827);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},62827(e,t,i){const r=i(64770),s=i(76982),{promisify:n}=i(92460),{PasetoNotSupported:a}=i(60308),o=i(70981),l=n(s.generateKeyPair);async function u(e,t,{format:i="keyobject"}={}){if("keyobject"!==i&&"paserk"!==i)throw new TypeError("invalid format");if("public"===t){const{privateKey:t,publicKey:r}=await l("ed25519");return"paserk"===i?{secretKey:`k${e.slice(1)}.secret.${h(t).toString("base64url")}`,publicKey:`k${e.slice(1)}.public.${h(r).toString("base64url")}`}:t}throw new a(`unsupported ${e} purpose`)}function c(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 64:{const t=s.createPrivateKey({key:Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),e.subarray(0,32)]),format:"der",type:"pkcs8"});if(!e.subarray(32).equals(Buffer.from(t.export({format:"jwk"}).x,"base64")))throw new TypeError("invalid byte sequence");return t}case 32:return s.createPublicKey({key:Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 64 bytes (private key), or 32 bytes (public key)")}}function d(e,t){if(!o(t))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public key must be an Ed25519 key`);switch(t.type){case"public":return Buffer.from(t.export({format:"jwk"}).x,"base64");case"private":{const{d:e,x:i}=t.export({format:"jwk"});return Buffer.concat([Buffer.from(e,"base64"),Buffer.from(i,"base64")])}}}function h(...e){return d("v2",...e)}e.exports={_checkPrivateKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.secret.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,64)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t))try{t=s.createPrivateKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("private"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public signing key must be a private ed25519 key`);return t},_checkPublicKey:function(e,t){if("string"==typeof t&&t.startsWith(`k${e.slice(1)}.public.`))try{t=Buffer.from(t.slice(10),"base64url"),r.strictEqual(t.byteLength,32)}catch{}if(Buffer.isBuffer(t))try{t=c(t)}catch{}if(!o(t)||"private"===t.type)try{t=s.createPublicKey(t)}catch{}if(!o(t))throw new TypeError("invalid key provided");if("public"!==t.type||"ed25519"!==t.asymmetricKeyType)throw new TypeError(`${e}.public verify key must be a public ed25519 key`);return t},_generateKey:u,_keyObjectToBytes:d,bytesToKeyObject:c,generateKey:async function(...e){return u("v2",...e)},keyObjectToBytes:h}},88451(e,t,i){const r=i(83561),s=i(1658),n=i(92366),{_checkPrivateKey:a}=i(62827),o=a.bind(void 0,"v2");e.exports=async function(e,t,{footer:i,...a}={}){const l=s(e,a);t=o(t);const u=r(i);return n("v2.public.",l,u,void 0,t)}},859(e,t,i){const r=i(49826),{_checkPublicKey:s}=i(62827),{post:n}=i(88965),a=s.bind(void 0,"v2");e.exports=async function(e,t,{complete:i=!1,buffer:s=!1,...o}={}){t=a(t);const{m:l,footer:u}=await r("v2.public.",e,void 0,64,t);return n("v2",s,o,i,l,u,"public")}},18582(e,t,i){const{"v3.local-decrypt":r}=i(56463),s=i(495).bind(void 0,"v3.local"),n=i(80608),{pre:a,post:o}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:l=!1,assertion:u,...c}={}){const{raw:d,f:h}=a("v3.local.",e);t=s(t);const f=n(u),m=t.export(),p=await r(d,h,m,f);return o("v3",l,c,i,p,h,"local")}},43406(e,t,i){const r=i(83561),s=i(495).bind(void 0,"v3.local"),n=i(1658),a=i(80608),{"v3.local-encrypt":o}=i(56463);e.exports=async function(e,t,{footer:i,assertion:l,...u}={}){const c=n(e,u);t=s(t);const d=r(i),h=a(l),f=t.export();return o(c,d,f,h)}},50015(e,t,i){const r=i(42438),s=i(65466),n=i(43406),a=i(18582),{generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}=i(80568);e.exports={sign:r,verify:s,encrypt:n,decrypt:a,generateKey:o,bytesToKeyObject:l,keyObjectToBytes:u}},80568(e,t,i){const r=i(76982),{promisify:s}=i(92460),{PasetoNotSupported:n}=i(60308),a=i(70981),o=i(82115),l=s(r.generateKeyPair),u=s(r.generateKey);function c(e){if(!a(e))throw new TypeError("keyObject must be a KeyObject instance");if("secret"===e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public key must be an EC P-384 key");switch(e.type){case"public":return o(e);case"private":return Buffer.from(e.export({format:"jwk"}).d,"base64")}}e.exports={generateKey:async function(e,{format:t="keyobject"}={}){if("keyobject"!==t&&"paserk"!==t)throw new TypeError("invalid format");switch(e){case"local":{const e=await u("aes",{length:256});return"paserk"===t?`k3.local.${e.export().toString("base64url")}`:e}case"public":{const{privateKey:e,publicKey:i}=await l("ec",{namedCurve:"P-384"});return"paserk"===t?{secretKey:`k3.secret.${c(e).toString("base64url")}`,publicKey:`k3.public.${c(i).toString("base64url")}`}:e}default:throw new n("unsupported v3 purpose")}},bytesToKeyObject:function(e){if(!Buffer.isBuffer(e))throw new TypeError("bytes must be a Buffer");switch(e.byteLength){case 48:return r.createPrivateKey({key:Buffer.concat([Buffer.from("303e0201010430","hex"),e,Buffer.from("a00706052b81040022","hex")]),format:"der",type:"sec1"});case 49:if(2!==e[0]&&3!==e[0])throw new TypeError("invalid compressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3046301006072a8648ce3d020106052b81040022033200","hex"),e]),format:"der",type:"spki"});case 97:if(4!==e[0])throw new TypeError("invalid uncompressed public key");return r.createPublicKey({key:Buffer.concat([Buffer.from("3076301006072a8648ce3d020106052b81040022036200","hex"),e]),format:"der",type:"spki"});default:throw new TypeError("bytes must be 48 bytes (private key), 49 bytes (compressed public key), or 97 bytes (uncompressed public key)")}},keyObjectToBytes:c}},42438(e,t,i){const{createPrivateKey:r}=i(76982),s=i(83561),n=i(1658),a=i(80608),o=i(92366),l=i(70981),{bytesToKeyObject:u}=i(80568),c=i(82115);e.exports=async function(e,t,{footer:i,assertion:d,...h}={}){const f=n(e,h),m=s(i),p=a(d);return t=function(e){if("string"==typeof e&&e.startsWith("k3.secret."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,48)}catch{}if(Buffer.isBuffer(e))try{e=u(e)}catch{}if(!l(e))try{e=r(e)}catch{}if(!l(e))throw new TypeError("invalid key provided");if("private"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public signing key must be a private EC P-384 key");return e}(t),o("v3.public.",f,m,"sha384",{key:t,dsaEncoding:"ieee-p1363"},p,c(t))}},65466(e,t,i){const{createPublicKey:r}=i(76982),s=i(80608),n=i(49826),a=i(70981),{bytesToKeyObject:o}=i(80568),l=i(82115),{post:u}=i(88965);e.exports=async function(e,t,{complete:i=!1,buffer:c=!1,assertion:d,...h}={}){t=function(e){if("string"==typeof e&&e.startsWith("k3.public."))try{e=Buffer.from(e.slice(10),"base64url"),assert.strictEqual(e.byteLength,49)}catch{}if(Buffer.isBuffer(e))try{e=o(e)}catch{}if(!a(e)||"private"===e.type)try{e=r(e)}catch{}if(!a(e))throw new TypeError("invalid key provided");if("public"!==e.type||"ec"!==e.asymmetricKeyType||"secp384r1"!==e.asymmetricKeyDetails.namedCurve)throw new TypeError("v3.public verify key must be a public EC P-384 key");return e}(t);const f=s(d),{m,footer:p}=await n("v3.public.",e,"sha384",96,{key:t,dsaEncoding:"ieee-p1363"},f,l(t));return u("v3",c,h,i,m,p,"public")}},64230(e,t,i){const r=i(29901),s=i(77933),{generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}=i(24961);e.exports={sign:r,verify:s,generateKey:n,bytesToKeyObject:a,keyObjectToBytes:o}},24961(e,t,i){const{_checkPrivateKey:r,_checkPublicKey:s,_generateKey:n,_keyObjectToBytes:a,bytesToKeyObject:o}=i(62827);e.exports={_checkPrivateKey:r,_checkPublicKey:s,bytesToKeyObject:o,generateKey:async function(...e){return n("v4",...e)},keyObjectToBytes:function(...e){return a("v4",...e)}}},29901(e,t,i){const r=i(83561),s=i(1658),n=i(80608),a=i(92366),{_checkPrivateKey:o}=i(24961),l=o.bind(void 0,"v4");e.exports=async function(e,t,{footer:i,assertion:o,...u}={}){const c=s(e,u),d=n(o);t=l(t);const h=r(i);return a("v4.public.",c,h,void 0,t,d)}},77933(e,t,i){const r=i(80608),s=i(49826),{_checkPublicKey:n}=i(24961),{post:a}=i(88965),o=n.bind(void 0,"v4");e.exports=async function(e,t,{complete:i=!1,buffer:n=!1,assertion:l,...u}={}){t=o(t);const c=r(l),{m:d,footer:h}=await s("v4.public.",e,void 0,64,t,c);return a("v4",n,u,i,d,h,"public")}},37975(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bgWhite=t.bgCyanBright=t.bgMagentaBright=t.bgBlueBright=t.bgYellowBright=t.bgGreenBright=t.bgRedBright=t.bgDarkGrey=t.bgLightGrey=t.bgCyan=t.bgMagenta=t.bgBlue=t.bgYellow=t.bgGreen=t.bgRed=t.bgBlack=t.white=t.cyanBright=t.magentaBright=t.blueBright=t.yellowBright=t.greenBright=t.redBright=t.darkGrey=t.lightGrey=t.cyan=t.magenta=t.blue=t.yellow=t.green=t.red=t.black=t.strikethrough=t.hidden=t.inverse=t.overline=t.underline=t.italic=t.dim=t.bold=t.reset=void 0,t.noColor=a,t.setColorEnabled=function(e){o=e??!a()},t.isColorEnabled=l;const r=i(1708),s=i(22573),n=i(38639);function a(){return(0,n.toNotBoolean)(r.env.PS_LOG_COLOR)??(!(0,s.blank)(r.env.NO_COLOR)||["dumb","unknown"].includes(r.env.TERM))}let o=!a();function l(){return o}function u(e,t){return function(i){return l()?`[${e}m${i}[${t}m`:i}}t.reset=u(0,0),t.bold=u(1,22),t.dim=u(2,22),t.italic=u(3,23),t.underline=u(4,24),t.overline=u(53,55),t.inverse=u(7,27),t.hidden=u(8,28),t.strikethrough=u(9,29),t.black=u(30,39),t.red=u(31,39),t.green=u(32,39),t.yellow=u(33,39),t.blue=u(34,39),t.magenta=u(35,39),t.cyan=u(36,39),t.lightGrey=u(37,39),t.darkGrey=u(90,39),t.redBright=u(91,39),t.greenBright=u(92,39),t.yellowBright=u(93,39),t.blueBright=u(94,39),t.magentaBright=u(95,39),t.cyanBright=u(96,39),t.white=u(97,39),t.bgBlack=u(40,49),t.bgRed=u(41,49),t.bgGreen=u(42,49),t.bgYellow=u(43,49),t.bgBlue=u(44,49),t.bgMagenta=u(45,49),t.bgCyan=u(46,49),t.bgLightGrey=u(47,49),t.bgDarkGrey=u(100,49),t.bgRedBright=u(101,49),t.bgGreenBright=u(102,49),t.bgYellowBright=u(103,49),t.bgBlueBright=u(104,49),t.bgMagentaBright=u(105,49),t.bgCyanBright=u(106,49),t.bgWhite=u(107,49)},72993(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AppNameVersion=t.AppName=t.SimpleAppNameLC=t.SimpleShortAppName=t.SimpleAppName=void 0;const r=i(19851),s=i(7282),n=i(37805);t.SimpleAppName="PhotoStructure",t.SimpleShortAppName="phstr",t.SimpleAppNameLC=t.SimpleAppName.toLowerCase(),t.AppName=(0,r.lazy)(()=>t.SimpleAppName+((0,s.isProd)()?"":`-${(0,s.nodeEnv)()}`)),t.AppNameVersion=(0,r.lazy)(()=>(0,t.AppName)()+" "+n.version)},48884(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.remove=t.flatMap=t.diff=void 0,t.diffEql=function(e,t){return e.filter(e=>!t.some(t=>(0,o.eql)(e,t)))},t.allDefined=g,t.mapAllDefined=function(e,t){return g(e)?t(e):void 0},t.mapAll=function(e,t){return g(e)?t(e):void 0},t.allNotDefined=function(e){return null==e||e.every(e=>null==e)},t.allNotBlank=function(...e){return null!=e&&e.every(a.notBlank)},t.anyNotDefined=function(e){return null==e||e.some(e=>null==e)},t.anyDefined=function(e){return null!=e&&e.some(e=>null!=e)},t.findAsync=async function(e,t){for(const i of(0,f.toA)(e))if(null!=i&&!0===await t(i))return i},t.findLastAsync=async function(e,t){for(let i=(e=(0,f.toA)(e)).length-1;i>=0;i--){const r=e[i];if(null!=r&&!0===await t(r))return r}},t.first=function(e,t){if(null!=e)for(const i of(0,f.toA)(e))if(null!=i){const e=t(i);if(null!=e)return e}},t.firstAsync=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null!=r){const e=await t(r,i);if(null!=e)return e}}catch(e){}}}},t.firstNonEmptyThunk=function(...e){for(const t of e){const e=t();if((0,r.isNotEmpty)(e))return e}},t.findFromIndex=function(e,t,i){for(let r=i;r<=e.length-1;r++)if(t(e[r]))return r},t.findLast=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},t.findLastIndex=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},t.concat=function(...e){const t=[];for(const i of e)if(Array.isArray(i))for(const e of i)null!=e&&t.push(e);else null!=i&&t.push(i);return t},t.moveToEnd=function(e,t){return(0,r.remove)(e,t),e.push(t),e},t.moveIndexToEnd=function(e,t){const i=e[t];if(null==i)return e;e.push(i);for(let i=t;i<e.length-1;i++)e[i]=e[i+1];return e.length=e.length-1,e},t.intersection=y,t.diceCoeff=function(e,t,i=r.primitiveValueOfOrElse){return(0,r.isEmpty)(e)&&(0,r.isEmpty)(t)?1:2*y(e,t,i).length/(e.length+t.length)},t.eqlUnordered=function(e,t){return null!=e&&null!=t&&b((0,n.sortBy)(e,m.stringifySorted),(0,n.sortBy)(t,m.stringifySorted)).every(([e,t])=>(0,o.eql)(e,t))},t.removeFirst=function(e,t){const i=e.findIndex(t);return i>=0?e.splice(i,1)[0]:void 0},t.uniqInPlace=function(e,t=e=>(0,l.stringify)(e)){(0,s.copyArrayTo)((0,r.uniqBy)(e,t),e)},t.partition=function(e,t){const i=[],r=[];let s=0;for(const n of e)(t(n,s++)?i:r).push(n);return[i,r]},t.isUniq=function(e){return e.every((t,i)=>e.indexOf(t)===i)},t.uniqCount=function(e){return v(e.sort())},t.mapCompact=function(e,t){return(0,r.compact)((0,r.compact)(e).map(t))},t.compactRight=function(e){for(let t=e.length-1;t>=0&&null==e[t];t--)e.splice(t,1);return e},t.toMapEntries=function(e,t){return new Map(e.map(t).filter(u.defined))},t.retainLastN=function(e,t){return e.length>t&&e.splice(0,e.length-t),e},t.retainFirstN=function(e,t){return e.length=Math.min(e.length,t),e},t.zip=b,t.flatZip=function(...e){const t=Math.max(...e.map(e=>e?.length??0)),i=[];return(0,c.times)(t,t=>e.map(e=>i.push(e?.[t]))),i},t.deinterleave=function(e,t=3){if(e.length%t!==0)throw new Error("Buffer length must be a multiple of "+t);const i=Math.floor(e.length/t),r=Array.from({length:t},()=>new Array(i));for(let s=0,n=0;s<i;s++,n+=t)for(let i=0;i<t;i++)r[i][s]=e[n+i];return r},t.ancestry=function(e){return(0,c.times)(e.length,t=>e.slice(0,t+1))},t.min=function(e){return e[w(e)]},t.leastIndex=w,t.max=function(e){return e[S(e)]},t.greatestIndex=S,t.leastIndexBy=P,t.greatestIndexBy=M,t.greatestBy=function(e,t){return(0,r.isEmpty)(e)?void 0:e[M(e,t)]},t.leastByCtx=function(e,t){const i=_(e??[],t,h.lt);return null==e||null==i||i.index<0||null==i.value?void 0:{result:e[i.index],index:i.index,value:i.value}},t.reverse=function(e){const t=[];for(let i=e.length-1;i>=0;i--)t.push(e[i]);return t},t.reverseG=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},t.batches=E,t.collectBatched=function(e,t,i){const s=[];for(const n of E((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(i(n)));return s},t.collectBatchedAsync=async function(e,t,i){const s=[];for(const n of E((0,r.compact)((0,f.toA)(e)),t))s.push(...(0,r.compact)(await i(n)));return s},t.contextFilter=function(e,t){let i;return e.filter((e,r)=>(0,d.tap)(t(e,r,i),t=>{t&&(i=e)}))},t.clusterSome=function(e,t){const i=[];for(const r of e){const e=i.find(e=>e.some(e=>t(r,e)));e?e.push(r):i.push([r])}return i},t.clusterEvery=function(e,t){const i=[];for(const r of e){const e=i.find(e=>e.every(e=>t(r,e)));e?e.push(r):i.push([r])}return i},t.clusterFirst=function(e,t){const i=[];e:for(const r of e){for(const e of i)if(null!=r&&t(r,e[0])){e.push(r);continue e}null!=r&&i.push([r])}return i},t.leftPadArray=function(e,t,i){if(e.length<t){const r=new Array(t-e.length).fill(i);e.unshift(...r)}return e},t.rightPadArray=function(e,t,i){if(e.length<t){const r=new Array(t-e.length).fill(i);e.push(...r)}return e};const r=i(40958),s=i(36783),n=i(76790),a=i(22573),o=i(50357),l=i(98553),u=i(55835),c=i(31586),d=i(68708),h=i(34666),f=i(59455),m=i(84885);var p=i(40958);function g(e){return(0,u.defined)(e)&&e.every(u.defined)}function y(e,t,i=r.primitiveValueOfOrElse){const s=new Set(t.map(i));return e.filter(e=>s.has(i(e)))}function v(e){if(null==e||0===e.length)return[];const t=e[0],i=e.lastIndexOf(t);return[{t,count:i+1},...v(e.slice(i+1))]}function b(...e){const t=[],i=Math.max(...e.map(e=>e?.length??0));for(let r=0;r<i;r++)t.push(e.map(e=>e?.[r]));return t}function w(e){return P(e,e=>e.valueOf())}function S(e){return M(e,e=>e.valueOf())}function P(e,t){return T(e,t,(e,t)=>(0,h.lt)(e,t))}function M(e,t){return T(e,t,(e,t)=>(0,h.gt)(e,t))}function T(e,t,i){return _(e,t,i).index}function _(e,t,i){if((0,r.isEmpty)(e))return{index:-1,value:void 0};let s,n=-1;for(let r=0;r<e.length;r++){const a=e[r];if(null!=a){const e=t(a);null!=e&&(null!=s&&!0!==i(e,s)||(n=r,s=e))}}return{index:n,value:s}}function E(e,t){return t<1&&(t=1),(0,r.stepRange)(0,e.length,Math.round(t),i=>e.slice(i,i+t))}Object.defineProperty(t,"diff",{enumerable:!0,get:function(){return p.diff}}),Object.defineProperty(t,"flatMap",{enumerable:!0,get:function(){return p.flatMap}}),Object.defineProperty(t,"remove",{enumerable:!0,get:function(){return p.remove}})},36557(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BatchClusterObserver=void 0,t.batchClusterOptions=function(e,t){return{maxProcs:e,maxIdleMsPerProcess:o.minuteMs,maxTasksPerProcess:T.Settings.maxTasksPerProcess.valueOrDefault,minDelayBetweenSpawnMillis:T.Settings.minDelayBetweenSpawnMs.valueOrDefault,streamFlushMillis:T.Settings.streamFlushMs.valueOrDefault,logger:(0,a.lazy)(()=>(0,h.mkLogger)(t)),spawnTimeoutMillis:(0,_.commandTimeoutMs)(),taskTimeoutMillis:T.Settings.taskTimeoutMs.valueOrDefault}};const s=i(77988),n=r(i(1708)),a=i(19851),o=i(42659),l=i(55835),u=i(31586),c=i(85556),d=i(54993),h=i(50213),f=i(79089),m=i(45255),p=i(25764),g=i(38836),y=i(99331),v=i(95937),b=i(98314),w=i(38835),S=i(70025),P=i(8769),M=i(95402),T=i(28874),_=i(63870);class E extends g.EndableWrapper{t;lastStartError;lastInternalError;lastTaskError;constructor(e,t,i=p.EndableRanks.service){super(`proc.BatchClusterObserver(${e})`,()=>this.#e(),i,"worker"===e?(0,_.commandTimeoutMs)():m.ShortCommandTimeoutMs),this.t=t;const r=t;r.on("childStart",async i=>{null!=i.pid?(this.logger.info("Started child process",{pid:i.pid}),(0,f.renice)(i.pid).catch(e=>this.onError("renice failed",e)),(0,M.addPid)({pid:i.pid,ppid:n.default.pid,cmd:e,timeoutMs:t.options.maxProcAgeMillis+o.minuteMs},new Date)?.catch(t=>this.onError("addPid failed for "+e,t))):this.onError("No PID returned for "+e,new c.TimeoutError)}),r.on("startError",e=>{this.lastStartError=e,this.onError("failed to start",e)}),r.on("taskError",(e,t)=>{null!=(0,b.errorToS)(e).match(/\btimeout\b/)&&(0,v.onTimeout)(),this.lastTaskError=e,this.onError("failed to run "+(0,l.map)(t,e=>e.command),e)}),r.on("internalError",e=>{this.lastInternalError=e,this.onError("internal error",e)}),r.on("noTaskData",(e,i,r)=>{const s=t.options.streamFlushMillis;s<o.secondMs&&(t.options.streamFlushMillis+=100,this.logger.warn("on(noTaskData): bumping up streamFlushMillis.",{prior:s,new:t.options.streamFlushMillis,stout:(0,d.toS)(e),stderr:(0,d.toS)(i),child_pid:r?.pid}))}),r.on("endError",e=>{this.logger.error("observeBatchCluster.endError()",e)}),r.on("childEnd",(t,i)=>{const{exitCode:r,exitSignal:s}=t;if(this.logger.info("on(childEnd)",{pid:t?.pid,name:t?.name,reason:i,exitCode:r,exitSignal:s}),(0,u.gt0)(t?.pid)&&M.Pids.instance()?.onKill(t.pid),(0,y.ending)()||this.t.ended||!t.unexpectedExit)return;if(null==s&&(null==r||0===r))return;const n=null!=s?`${e} terminated by ${s}`:`${e} exited with code ${r}`;(0,P.onError)(n+w.FatalErrorFlag,{signal:s??void 0,exitCode:r??void 0,service:e,fatal:!0})})}childEndCounts(){return this.t instanceof s.ExifTool?this.t.childEndCounts():this.t.stats?.().childEndCounts}#e(){return this.logger.info("onEnd()",{childEndCounts:this.childEndCounts()}),this.t.end(!0)}onError(e,t){this.t.ended||(0,y.ending)()||!0===(0,S.isIgnorableError)(t)?this.logger.warn("onError() (ending or ignorable)",{reason:e,error:t}):(0,P.onError)(this.name+": "+e,t)}}t.BatchClusterObserver=E},71371(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedGreatestSet=void 0;const r=i(92322);t.BoundedGreatestSet=class{maxLength;toValue;sortedArray;constructor(e,t){this.maxLength=e,this.toValue=t,this.sortedArray=new r.SortedSet(t)}toA(){return this.vacuum(),this.sortedArray.toA()}vacuum(){return this.sortedArray.retainLastN(this.maxLength)}add(...e){this.maxLength<=0||(this.sortedArray.addAll(...e),this.sortedArray.length>=2*this.maxLength&&this.vacuum())}}},45132(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedMap=void 0;const r=i(57975);class s{capacity;#t;#i;constructor(e){if(this.capacity=e,e<1)throw new Error("BoundedMap.capacity must be >= 1: "+e);this.#t=new Map}get size(){return this.#t.size}get lastKey(){return this.#i}get lastValue(){return null!=this.#i?this.#t.get(this.#i):void 0}has(e){return this.#t.has(e)}get(e){return this.#t.get(e)}set(e,t){if(this.#t.has(e))this.#t.delete(e);else if(this.#t.size>=this.capacity){const e=this.#t.keys().next();!0!==e.done&&this.#t.delete(e.value)}return this.#t.set(e,t),this.#i=e,this}delete(e){return this.#t.delete(e)}clear(){this.#t.clear(),this.#i=void 0}keys(){return this.#t.keys()}values(){return this.#t.values()}entries(){return this.#t.entries()}forEach(e){this.#t.forEach((t,i)=>e(t,i,this))}[Symbol.iterator](){return this.#t[Symbol.iterator]()}get[Symbol.toStringTag](){return"BoundedMap"}[r.inspect.custom](){return Object.fromEntries(this.#t)}}t.BoundedMap=s},76850(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.debom=n,t.bufferToString=function(e){return Buffer.isBuffer(e)?n(e):(0,r.toS)(e)},t.bufferStartsWith=a;const r=i(54993),s=[{bom:[239,187,191],encoding:"utf8"},{bom:[255,254],encoding:"utf16le"}];function n(e){for(const{bom:t,encoding:i}of s)if(a(e,t))return e.subarray(t.length).toString(i);return e.toString()}function a(e,t){return t.every((t,i)=>e[i]===t)}},55139(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Cache=void 0,t.summarizeCacheStats=function(e){let t=0,i=0,r=0,s=0;for(const n of Object.values(e))t+=n.size,i+=n.hits,r+=n.misses,s+=n.errors;const n=i+r;return{size:t,hitRate:(0,a.gt0)(n)?i/n:0,errorRate:(0,a.gt0)(n)?s/n:0}},t.memoize=function(e,t){return new y(t).memoize(e)};const r=i(76790),s=i(45599),n=i(54900),a=i(31586),o=i(20214),l=i(13538),u=i(85556),c=i(34102),d=i(7282),h=i(65211),f=i(48299),m={hits:0,misses:0,sets:0,errors:0,timeouts:0},p=new f.WeakCache,g=(0,s.defer)(()=>{(0,d.isTest)()&&(0,c.ee)().on("clearCache",()=>{for(const e of p.values())e.reset()})});class y{[Symbol.toStringTag]="Cache";#r=[];#s;#n;#a;#o;#l=new Map;#u={...m};#c=0;constructor(e){this.#s={maxSize:256,...e},this.setOptions({}),(0,d.isTest)()&&(p.set((0,h.uid)(),this),g())}[Symbol.iterator](){return this.entries()}get opts(){return{...this.#s}}setTTL(e){this.setOptions({ttlMs:e})}setOptions(e){const t={...this.#s};function i(e,t,i){return null!=e&&clearInterval(e),(0,a.gt0)(t)?setInterval(()=>i(),t).unref():void 0}Object.assign(this.#s,e),e.clearEveryMs!==t.clearEveryMs&&(this.#n=i(this.#n,e.clearEveryMs,()=>this.clear())),e.ttlMs!==t.ttlMs&&(this.#a=i(this.#a,(0,a.gt0)(e.ttlMs)?Math.round(e.ttlMs/4):void 0,()=>this.vacuum())),e.maxSize===t.maxSize&&e.ttlMs===t.ttlMs||this.vacuum()}lastSetTs(e){return this.vacuum(),null!=e?this.#l.get(e)?.ts:this.#o}#d(e,t){if(null==t)return!1;if((0,a.gt0)(this.#s.ttlMs)&&t.ts+this.#s.ttlMs<Date.now()){const i=t.v;return(0,o.isPromiseLike)(i)||this.#r.forEach(t=>t(e,i)),this.delete(e),!1}return!0}destroy(){null!=this.#n&&(clearInterval(this.#n),this.#n=void 0),null!=this.#a&&(clearInterval(this.#a),this.#a=void 0),this.clear()}clear(){return this.#l.clear(),this.#c++,this}reset(){return Object.assign(this.#u,m),this.clear()}delete(e){return this.#l.delete(e)}deleteAll(e){for(const t of e)this.delete(t)}deleteByPrefix(e){let t=0;for(const i of this.#l.keys())i.startsWith(e)&&(this.#l.delete(i),t++);return t}async deleteIf(e){for(const[t,i]of this.#l.entries())await e(t,i.v)&&this.#l.delete(t)}deleteValueIfSync(e){let t=!1;for(const[i,r]of this.#l.entries())!(0,o.isPromiseLike)(r.v)&&e(r.v)&&(t||=this.#l.delete(i));return t}deleteResolved(){for(const[e,t]of this.#l.entries())this.#d(e,t)&&(0,n.isDeferred)(t.v)||this.#l.delete(e)}forEach(e){for(const[t,i]of this.#l.entries())this.#d(t,i)&&!(0,o.isPromiseLike)(i.v)&&e(i.v,t,this)}find(e){for(const[t,i]of this.#l.entries())if(this.#d(t,i)&&!(0,o.isPromiseLike)(i.v)&&e(i.v,t))return i.v}get(e){const t=this.#l.get(e);if(this.#d(e,t)&&!(0,o.isPromiseLike)(t.v))return this.#u.hits++,t.v;this.#u.misses++}getAsync(e){const t=this.#l.get(e);return this.#d(e,t)?(this.#u.hits++,t.v):void this.#u.misses++}peek(e){const t=this.#l.get(e);if(this.#d(e,t)){const e=t.v;if(!(0,o.isPromiseLike)(e))return e??null}}peekAsync(e){const t=this.#l.get(e);if(this.#d(e,t))return t.v}getOrMaybeSet(e,t){const i=this.#l.get(e);if(this.#d(e,i)&&!(0,o.isPromiseLike)(i.v))return this.#u.hits++,i.v;const r=t();return null!=r&&this.set(e,r),r}getOrSet(e,t){if(!0===this.#s.noop)return this.#u.misses++,t();const i=this.#l.get(e);return this.#d(e,i)?(this.#u.hits++,i.v):this.setAndGet(e,t())}has(e){const t=this.#l.get(e);return this.#d(e,t)}hasSync(e){const t=this.#l.get(e);return null!=t&&!(0,o.isPromiseLike)(t.v)}set(e,t){return this.setAndGet(e,t),this}setAndGet(e,t){const i=Date.now(),r=this.#c;if(this.#o=i,this.#u.sets++,null==t)return this.#l.delete(e),t;if(!(0,o.isPromiseLike)(t))return this.#l.set(e,{ts:i,v:t}),t;const s=(0,n.isDeferred)(t)?t:(new n.Deferred).observe((0,l.thenOrTimeoutError)(t,this.#s.timeoutMs));return s.then(t=>{if(this.#c===r){const r=this.#l.get(e);null!=r&&r.ts===i&&this.#l.set(e,{ts:i,v:t})}}).catch(t=>{if(this.#u.errors++,(0,u.isTimeoutError)(t)&&this.#u.timeouts++,this.#c===r){const t=this.#l.get(e);null!=t&&t.ts===i&&this.#l.delete(e)}}),this.#l.set(e,{ts:i,v:s}),s}get size(){return this.vacuum(),this.#l.size}stats(){return{size:this.size,...this.#u}}mergeStats(e){for(const[t,i]of Object.entries(e))t in this.#u&&(this.#u[t]+=i)}*keys(){for(const[e]of this.#l.entries())this.#d(e,this.#l.get(e))&&(yield e)}*values(){for(const[e,t]of this.#l.entries())this.#d(e,t)&&!(0,o.isPromiseLike)(t.v)&&(yield t.v)}*valuesAsync(){for(const[e,t]of this.#l.entries())this.#d(e,t)&&(yield t.v)}valuesByRecency(){return this.vacuum(),(0,r.sortBy)(Array.from(this.values()),(e,t)=>-t)}*entries(){for(const[e,t]of this.#l.entries())this.#d(e,t)&&!(0,o.isPromiseLike)(t.v)&&(yield[e,t.v])}*entriesAsync(){for(const[e,t]of this.#l.entries())this.#d(e,t)&&(yield[e,t.v])}on(e,t){"expire"===e&&this.#r.push(t)}vacuum(){if((0,a.gt0)(this.#s.ttlMs)){const e=Date.now()-this.#s.ttlMs;for(const[t,i]of this.#l.entries())if(i.ts<=e){const e=i.v;(0,o.isPromiseLike)(e)||this.#r.forEach(i=>i(t,e)),this.#l.delete(t)}}if((0,a.gt0)(this.#s.maxSize)){const e=this.#l.keys();for(;this.#l.size>this.#s.maxSize;){const t=e.next().value;if(null==t)break;this.#l.delete(t)}}}memoize(e){const t=(...t)=>{const i=JSON.stringify(t);return this.getOrMaybeSet(i,()=>e(...t))};return t.cache=this,t}}t.Cache=y},9092(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveMap=void 0;const r=i(94863);class s{normalizer;store=new Map;constructor(e=[],t=r.NoBlanksStringNormalizer){this.normalizer=t;for(const[t,i]of e)this.set(t,i)}get(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)?.[1]}lookup(e){const t=this.normalizer(e);return null==t?void 0:this.store.get(t)}has(e){const t=this.normalizer(e);return null!=t&&this.store.has(t)}set(e,t){const i=this.normalizer(e);return null!=e&&null!=i&&this.store.set(i,[e,t]),this}clear(){this.store.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.store.delete(t)}forEach(e){this.store.forEach(t=>e(t[1],t[0],this))}get size(){return this.store.size}entries(){return this.store.values()}keys(){return[...this.store.values()].map(e=>e[0])[Symbol.iterator]()}values(){return[...this.store.values()].map(e=>e[1])[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e&&(t[e[0]]=e[1])}return t}}t.CaseInsensitiveMap=s},36638(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveSet=void 0;const r=i(94863);class s{normalizer;#t=new Map;constructor(e=[],t=r.NoBlanksStringNormalizer){this.normalizer=t;for(const t of e)this.add(t)}add(e){const t=this.normalizer(e);return null!=t&&null!=e&&this.#t.set(t,e),this}clear(){this.#t.clear()}delete(e){const t=this.normalizer(e);return null!=t&&this.#t.delete(t)}forEach(e){this.#t.forEach((t,i)=>e(t,t,this))}has(e){if(null==e)return!1;const t=this.normalizer(e);return null!=t&&this.#t.has(t)}hasAny(e){for(const t of e)if(this.has(t))return!0;return!1}lookup(e){if(null==e)return;const t=this.normalizer(e);return null==t?void 0:this.#t.get(t)}get size(){return this.#t.size}entries(){return new Set(this.#t.values()).entries()}keys(){return this.#t.values()}values(){return this.#t.values()}[Symbol.iterator](){return this.#t.values()[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}t.CaseInsensitiveSet=s},40583(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaseInsensitiveValued=void 0;const r=i(40958),s=i(23838),n=i(68708),a=i(59455),o=i(54993),l=i(96859);t.CaseInsensitiveValued=class{obj;synonyms;m;constructor(e,t=()=>{}){this.obj=e,this.synonyms=t,this.m=new s.MultiMap,this.rebuild()}rebuild(){this.m.clear();for(const[e,t]of(0,n.entries)(this.obj))for(const i of(0,r.uniq)([e,...(0,a.toA)(this.synonyms(e,t))].map(e=>e.toLowerCase())))this.m.add(i,e);this.m.vacuum()}lookup(e){if(null==e)return;const t=this.obj[e];return null!=t?{key:e,value:t}:this.getFirst(this.m.get(e.toLowerCase()))}findKeys(e){return this.m.get(e.toLowerCase())??[]}lookupNearest(e,t=.4){const i=this.lookup(e);if(null!=i)return i;let r,s=-1;for(const[i,n]of this.m.entries()){const a=(0,l.diceCoeff)(i,e);if(a>t&&a>s){const e=this.getFirst(n);null!=e&&(r=e,s=a)}}return r}get(e){return this.lookup(e)?.value}set(e,t){this.obj[e]=t,this.rebuild()}getFirst(e){if(null!=e)for(const t of e){const e=this.obj[t];if(null!=e)return{key:t,value:e}}}delete(e){const t=(0,o.toS)(e).toLowerCase(),i=this.m.get(t)??[];for(const e of i)delete this.obj[e];return this.m.delete(t),i}pick(...e){const t={};for(const i of e){const e=this.lookup(i);null!=e?.key&&(t[e.key]=e.value)}return t}}},4034(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CircularBuffer=void 0;class i{#h;#f;#m=0;#p=0;constructor(e){if(e<0)throw new Error("Capacity must be non-negative");this.#h=e,this.#f=new Array(e)}get capacity(){return this.#h}set capacity(e){if(e<0)throw new Error("Capacity must be non-negative");if(e===this.#h)return;const t=[...this].slice(0,e);this.#f=new Array(e);for(let e=0;e<t.length;e++)this.#f[e]=t[e];this.#h=e,this.#m=0,this.#p=t.length}get size(){return this.#p}push(e){0!==this.#h&&(this.#f[(this.#m+this.#p)%this.#f.length]=e,this.#p++>=this.#f.length&&(this.#p=this.#f.length,this.#m=(this.#m+1)%this.#f.length))}*[Symbol.iterator](){for(let e=0;e<this.#p;e++){const t=(this.#m+e)%this.#f.length;yield this.#f[t]}}forEach(e){for(let t=0;t<this.#p;t++){const i=(this.#m+t)%this.#f.length;e(this.#f[i],t)}}map(e){const t=new Array;return this.forEach(i=>t.push(e(i))),t}clear(){this.#f.length=0,this.#f.length=this.capacity,this.#m=0,this.#p=0}toArray(){return this.map(e=>e)}}t.CircularBuffer=i},65594(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Clusters=void 0,t.Clusters=class{cmp;#g=new Map;#y=new Map;#v=1;constructor(e){this.cmp=e}add(e){const t=this.#g.get(e);if(null!=t)return t;for(const[t,i]of this.#y)for(const r of i)if(this.cmp(e,r))return i.add(e),this.#g.set(e,t),t;const i=this.#v++;return this.#y.set(i,new Set([e])),this.#g.set(e,i),i}remove(e){const t=this.#g.get(e);if(null==t)return!1;this.#g.delete(e);const i=this.#y.get(t);return i.delete(e),0===i.size&&this.#y.delete(t),!0}items(){return this.#g.keys()}getClusterItems(e){return this.#y.get(e)}getClusterIdByPredicate(e){for(const[t,i]of this.#g)if(e(t))return i}get clusterCount(){return this.#y.size}get itemCount(){return this.#g.size}}},50321(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.writeStdout=function(e,...t){(0,n.streamEnded)(r.stdout)||console.log((0,s.crlf)(e),...t)},t.writeStderr=function(e){(0,n.streamEnded)(r.stderr)||r.stderr.write(e)};const r=i(1708),s=i(84542),n=i(14810)},22454(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CountingSet=void 0;const r=i(73429),s=i(76790),n=i(31586),a=i(68708),o=i(54993),l=i(82647),u=i(70417);class c{#b=new Map;static fromJSON(e){if(!(0,r.isMap)(e?.m))return;const t=new c;for(const[i,r]of e.m)(0,n.gt0)(r)&&t.incr(i,r);return t}merge(e){for(const[t,i]of e.entries())this.incr(t,i);return this}incr(e,t=1){const i=this.get(e)+t;return 0===i?this.#b.delete(e):this.#b.set(e,i),i}get(e){return this.#b.get(e)??0}max(...e){return Math.max(...0===e.length?this.#b.values():e.map(e=>this.get(e)))}has(e){return this.#b.has(e)}delete(e){return this.#b.delete(e)}get size(){return this.#b.size}get countSum(){return(0,u.sum)(this.#b.values())}keys(){return this.#b.keys()}keyAvg(){const e=new l.Average(0);for(const t of this.keys()){if(!(0,n.isNumber)(t))return;e.push(t)}return e.avg}entries(){return this.#b.entries()}toJSON(){return{m:this.#b}}toRecord(){const e={};for(const[t,i]of this.#b.entries())e[(0,o.toS)(t)]=i;return e}entriesByCountDesc(){const e=this.keyAvg();return(0,s.sortBy)([...this.entries()],([t,i])=>[-i,(0,n.mapNumericOr)(e,e=>Math.abs(t-e),0)])}top(e=1){return this.entriesByCountDesc().slice(0,e)}topKeys(e=1){return this.top(e).map(e=>e[0])}get averageCounts(){return(0,a.tap)(new l.Average(this.size),e=>[...this.#b.values()].forEach(t=>e.push(t)))}forEach(e){this.#b.forEach(e)}clear(){this.#b.clear()}sortedByKey(){const e=new c;for(const[t,i]of(0,s.sortBy)(this.#b.entries(),e=>e[0]))e.incr(t,i);return e}addAll(e){for(const[t,i]of e.entries())this.incr(t,i);return this}get toS(){return(0,s.sort)([...this.keys()]).map(e=>e+" "+this.get(e)).join("\n")}valuesToA(e){const t=[];t.length=(0,u.sum)(this.#b.values());let i=0;for(const[r,s]of this.#b.entries()){const n=e(r);t.fill(n,i,i+s),i+=s}return t}}t.CountingSet=c},62556(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.alpha3ToAlpha2=function(e){return null==e?void 0:2===e.length?n.has(e.toUpperCase())?e.toUpperCase():void 0:a.get(e)},t.countryNameToCode=function(e){return s.get(e)},t.countryCodeToName=function(e){return n.get(e.toUpperCase())},t.countryCodeToFlag=o,t.flaggedCountryName=function(e,t){if(null==t)return e;const i=o(t);return null==i?e:i+" "+e};const r=i(9092),s=new r.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"]]),n=new Map;for(const[e,t]of s.entries())n.has(t)||n.set(t,e);const a=new r.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 o(e){if(2!==e.length)return;const t=e.toUpperCase(),i=t.charCodeAt(0),r=t.charCodeAt(1);return i<65||i>90||r<65||r>90?void 0:String.fromCodePoint(127462+i-65,127462+r-65)}},79840(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSensitiveEnvRegexPattern=void 0,t.DefaultSensitiveEnvRegexPattern="(?:^|[^a-z])(?:"+["credentials?","dsn","keys?","aws","npm","pass","passwd","password","private","secret","token"].join("|")+")(?:$|[^a-z])"},17344(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EditionName=t.EditionType=void 0;const r=i(19851),s=i(72993),n=i(45969),a=i(43334);t.EditionType=(0,r.lazy)(()=>(0,a.isElectron)()?"Desktops":(0,n.isDocker)()?"Docker":"Servers"),t.EditionName=(0,r.lazy)(()=>s.SimpleAppName+" for "+(0,t.EditionType)())},14121(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Elapsed=void 0,t.elapsed=function(e){const t=performance.now(),i=e();return{elapsedMs:(0,s.roundMs)(performance.now()-t),result:i}},t.elapsedAsync=async function(e){const t=performance.now(),i=await e;return{elapsedMs:(0,s.roundMs)(performance.now()-t),result:i}};const r=i(55835),s=i(3685);t.Elapsed=class{l;listener;ts=performance.now();constructor(e,t){this.l=e,this.listener=t}elapsed(e){const t=performance.now(),i=(0,s.roundMs)(t-this.ts);this.ts=t,(0,r.map)(this.listener,t=>t(e,i)),i>2&&this.l.log(i>500?"warn":i>100?"info":"debug",e,{elapsedMs:i})}}},23467(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eql=void 0,t.definedAndEql=function(e,t){return null!=e&&null!=t&&(0,r.eql)(e,t)},t.definedAndNotEql=function(e,t){return null!=e&&null!=t&&!(0,r.eql)(e,t)},t.eqlAsync=async function(e,t){return(0,s.map2Or)(await e,await t,r.eql,()=>!1)},t.eqlPicked=function(e,t,...i){if(null==e||null==t)return!1;for(const s of i)if(!(0,r.eql)(e[s],t[s]))return!1;return!0},t.eqlOmit=function(e,t,...i){return null!=e&&null!=t&&(0,r.eql)((0,n.omit)(e,...i),(0,n.omit)(t,...i))},t.eqlAsyncPicked=async function(e,t,...i){return(0,s.map2Or)(await e,await t,(e,t)=>(0,r.eql)((0,n.pick)(e,...i),(0,n.pick)(t,...i)),()=>!1)};const r=i(50357),s=i(55835),n=i(68708);var a=i(50357);Object.defineProperty(t,"eql",{enumerable:!0,get:function(){return a.eql}})},19935(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examples=void 0;const r=i(31658),s=i(19851),n=i(95696);t.examples=(0,s.lazy)(()=>n.PosixFile.for((0,r.examplesNativePath_)()))},88329(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExamplesDirVolSHA=t.ExamplesDirVolumeUUID=void 0,t.ExamplesDirVolumeUUID="b1a92aaa-99c5-11ec-8456-e3f25737e4ab",t.ExamplesDirVolSHA="2wq8NtxvR"},31658(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.examplesNativePath_=void 0;const r=i(45599),s=i(29882),n=i(49517);t.examplesNativePath_=(0,r.defer)(()=>(0,s.joinNativePath)([(0,n.repoRoot)(),"examples"]))},62344(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleFunction=void 0,t.ExtensibleFunction=class extends Function{_self;constructor(){super("...args","return this._self._call(...args)");const e=this.bind(this);return this._self=e,e}}},54557(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FifoCache=void 0,t.summarizeFifoCacheStats=function(e){let t=0,i=0,r=0,n=0;for(const s of Object.values(e))t+=s.size,i+=s.hits,r+=s.misses,n+=s.errors;const a=i+r;return{size:t,hitRate:(0,s.gt0)(a)?i/a:0,errorRate:(0,s.gt0)(a)?n/a:0}};const r=i(73429),s=i(31586),n=i(20214),a=i(13538),o=i(85556);t.FifoCache=class{#s;#n;#a;#w=new Map;#u={hits:0,misses:0,errors:0,timeouts:0};constructor(e){this.#s=e,this.setOptions({})}get opts(){return{...this.#s}}setOptions(e){const t={...this.#s};Object.assign(this.#s,e);const i=(e,t,i)=>(null!=e&&clearInterval(e),(0,s.gt0)(t)?setInterval(()=>i(),t).unref():void 0);e.clearEveryMs!==t.clearEveryMs&&(this.#n=i(this.#n,e.clearEveryMs,()=>this.clear())),e.ttlMs!==t.ttlMs&&(this.#a=i(this.#a,(0,s.gt0)(e.ttlMs)?Math.round(e.ttlMs/3):void 0,()=>this.vacuum())),e.maxSize===t.maxSize&&e.ttlMs===t.ttlMs||this.vacuum()}has(e){return this.#w.has(e)}hasSync(e){return this.#w.has(e)&&!(0,r.isPromise)(this.#w.get(e)?.v)}getSync(e){const t=this.#w.get(e)?.v;if(null!=t&&!(0,n.isPromiseLike)(t))return this.#u.hits++,t??null;this.#u.misses++}_get(e){return this.#w.get(e)?.v}get(e){const t=this.#w.get(e)?.v;if(null!=t)return this.#u.hits++,t;this.#u.misses++}clear(){this.#w.clear()}delete(e){return this.#w.delete(e)}async deleteIf(e){for(const[t,i]of this.#w.entries())await e(t,i.v)&&this.delete(t)}entries(){return this.#w.entries()}values(){return this.#w.values()}get size(){return this.#w.size}stats(){return{size:this.size,...this.#u}}vacuum(){if((0,s.gt0)(this.#s.ttlMs)){const e=performance.now()-this.#s.ttlMs;for(const[t,i]of this.#w.entries())i.ts<=e&&this.#w.delete(t)}if((0,s.gt0)(this.#s.maxSize)){const e=this.#w.keys();for(;this.size>this.#s.maxSize;){const t=e.next().value;if(null==t)break;this.#w.delete(t)}}}set(e,t){if(this.vacuum(),null==t)return this.#w.delete(e),t;if((0,r.isPromise)(t)){const i=(0,a.thenOrTimeoutError)(t,this.#s.timeoutMs);return i.then(t=>{this.#w.get(e)?.v===i&&this.#w.set(e,{ts:performance.now(),v:t})}).catch(e=>{this.#u.errors++,(0,o.isTimeoutError)(e)&&this.#u.timeouts++}),this.#w.set(e,{ts:performance.now(),v:i}),i}return this.#w.set(e,{ts:performance.now(),v:t}),t}getOrSet(e,t){if(!0===this.#s.noop)return this.#u.misses++,t();const i=this.#w.get(e)?.v;return null!=i?(this.#u.hits++,i):this.set(e,t())}mergeStats(e){for(const[t,i]of Object.entries(e))t in this.#u&&(this.#u[t]+=i)}}},53507(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Fixed=void 0,t.parseFixed=function(e,t,i=!0){return new m(e,t,i).entries};const r=i(19851),s=i(40958),n=i(22573),a=i(31586),o=i(68708),l=i(50213),u=i(68852),c=i(81168),d=i(84542);class h{text;greedyLeft;indexOf;leftIdx;rightIdx;constructor(e){this.text=(0,c.isString)(e)?e:e.text,this.greedyLeft=!(0,c.isString)(e)&&(e.greedyLeft??!1)}toEntry(e){return[this.text,e.substring(this.leftIdx,this.rightIdx).trim()]}}const f=(0,r.lazy)(()=>(0,l.mkLogger)("Fixed"));class m{warnIfMissingHeaders;headers;headerRow;skippedHeaders=[];rows;entries;blankColumns;constructor(e,t,i=!0){this.warnIfMissingHeaders=i,this.rows=(0,d.splitLines)(t),this.headerRow=this.rows.shift();const r=(0,a.max_)(...this.rows.map(e=>e.length));this.blankColumns=new Set((0,s.range)(0,r).filter(e=>this.rows.every(t=>(0,n.blank)(t[e])))),this.headers=this.extractHeaders(e.map(e=>new h(e))),this.entries=this.rows.map(e=>this.headers.map(t=>t.toEntry(e))).map(e=>(0,o.fromEntries)(e)).filter(e=>(0,o.values)(e).some(n.notBlank))}firstBlankColumn(e,t){for(let i=e;i!==t;t>e?i++:i--)if(this.blankColumns.has(i))return i;return this.blankColumns.has(t)?t:0===e||0===t?0:void 0}extractHeaders(e){const t=new RegExp(e.map(e=>(e.greedyLeft?"\\s+":"\\b")+(0,u.escapeRegExp)(e.text)+"\\b").join("|"),"gi"),i=[];let r,o=0;for(;null!=(r=t.exec(this.headerRow));){const l=this.headerRow.substring(o,r.index);(0,n.blank)(l)||(f().debug("extractHeaders: skipping over unknown header",{skippedOver:l,m_index:r.index}),this.skippedHeaders.push(l.trim()));const u=this.headerRow.substring(r.index,t.lastIndex),d=r.index+((0,c.indexOfNonSpace)(u)??0),h=r.index+((0,c.lastIndexOfNonSpace)(u)??u.length),m=u.trim(),p=e.find(e=>e.text===m);if(null==p||null==d||null==h)this.skippedHeaders.push(m),f().debug("extractHeaders: internal error",{matched:u,match:r,left:d,right:h});else{const e=(0,s.last)(i);if(i.push(p),null!=e){const t=e.rightIdx+((0,c.indexOfNonSpace)(l)??l.length)+1;e.rightIdx=p.greedyLeft?this.firstBlankColumn(e.rightIdx,t):this.firstBlankColumn(t,e.rightIdx)}const t=(0,a.max_)(e?.rightIdx,r.index-((0,c.lastIndexOfNonSpace)(l)??l.length));p.leftIdx=p.greedyLeft?this.firstBlankColumn(t,d):this.firstBlankColumn(d,t),p.rightIdx=h}o=t.lastIndex}const l=(0,s.last)(i);return null!=l&&((0,n.blank)(this.headerRow.slice(o))?l.rightIdx=(0,a.max_)(...this.rows.map(e=>e.length)):l.rightIdx=o),i}}t.Fixed=m},73168(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validLat=u,t.validLon=c,t.toLatLon=d,t.locationToGeohash=function(e,t=30){return h(e?.lat,e?.lon,t)},t.geohash=h,t.geohashNumericShort=function(e,t){return m(e,t,30)},t.geohashNumeric=m,t.ungeohash=function(e,t=30){return(0,r.map)(a.GeoRadix.decode(e),e=>p(e,t))},t.ungeohash_num=p,t.geoHashToLocation=g,t.geohashDistanceMeters=function(e,t){if(null!=e&&null!=t)return e===t?0:y(g(e),g(t))},t.distanceMeters=y;const r=i(55835),s=i(31586),n=i(20014),a=i(55222),o=i(97352);function l(e){return 5*Math.floor(e/5)}function u(e){const t=(0,s.toFloat)(e);return(0,o.within)(-90,90,t)&&0!==t}function c(e){const t=(0,s.toFloat)(e);return(0,o.within)(-180,180,t)&&0!==t}function d(e,t){return e=(0,s.toFloat)(e),t=(0,s.toFloat)(t),u(e)&&c(t)?{latitude:e,longitude:t}:void 0}function h(e,t,i=30){return(0,r.map)(m(e,t,l(i)),e=>a.GeoRadix.encode(e))}const f=new n.BitZip([{min:-180,max:180},{min:-90,max:90}]);function m(e,t,i=30){const r=d(e,t);return null==r?void 0:f.zip([r.longitude,r.latitude],l(i))}function p(e,t=30){return f.unzip(e,l(t))?.reverse()}function g(e,t=30){const[i,r]=p(e,t);return{lat:i,lon:r}}function y(e,t){const i=e.lat*Math.PI/180,r=t.lat*Math.PI/180,s=(t.lat-e.lat)*Math.PI/180,n=(t.lon-e.lon)*Math.PI/180,a=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(r)*Math.sin(n/2)*Math.sin(n/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}},44142(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.groupid=t.groupids=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(40958),o=i(31586),l=i(19851);t.groupids=(0,l.lazy)(()=>(0,a.uniq)([n.default.getegid?.(),n.default.getgid?.(),s.default.userInfo().gid,...n.default.getgroups?.()??[]]).filter(o.gte0)),t.groupid=(0,l.lazy)(()=>(0,t.groupids)()[0])},73913(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HashBits=void 0,t.HashBits=192},66364(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSuspended=void 0;const r=i(19851);t.isSuspended=(0,r.lazy)(()=>!1)},19851(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=function(e,t){return new l(e,t)},t.rolazy=function(e,t){return new u(e,t)};const r=i(57975),s=i(50357),n=i(31586),a=i(65812),o=i(62344);class l extends o.ExtensibleFunction{fn;ttlMs;#o;#S;#P=null;watchers=[];constructor(e,t){super(),this.fn=e,this.ttlMs=t}_call(){return this.isStale()&&this.#M(this.fn()),this.#S}async#T(e,t){let i,r;try{i=await t}catch{return}if(t===this.#S){this.#P=i;try{r=await e}catch{}if(!(0,s.eql)(r,i))for(const e of this.watchers)e(i);null!=this.ttlMs&&this.ttlMs>0&&void 0!==i&&(0,a.setUnrefTimeout)(()=>this.vacuum(),this.ttlMs)}}setFn(e){this.fn=e,this.unset()}vacuum(){this.isStale()&&this.unset()}#M(e){return this.#P=null,this.#o=performance.now(),this.#T(this.#S,e),this.#S=e}isStale(){return null==this.#o||(0,n.gt0)(this.ttlMs)&&this.#o+this.ttlMs<performance.now()}set(e){this.#M(e)}unset(){this.#M(void 0),this.#o=void 0}clear(){const e=this.#S;return this.unset(),e}prior(){return this.vacuum(),this.#S}priorSync(){return this.vacuum(),this.#P}refresh(){return this.#M(this.fn())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,n.gt0)(e)?e:void 0}watchLater(e){this.watchers.push(e)}watch(e){this.watchers.push(e)}toString(){return"[Lazy]"}[r.inspect.custom](){return"[Lazy]"}lastSetAgoMs(){return null==this.#o?void 0:performance.now()-this.#o}hasPrior(){return null!=this.#o}}class u extends l{set(e){}}},19043(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envLocale=t.locale=t.DefaultLocale=void 0,t.localeSync=function(){return t.locale.lastValue()??(0,t.envLocale)()??t.DefaultLocale},t.lc2locale=b,t.localeWin=w,t.localeMac=P,t.localePosix=M,t.childProcLocale=function(){return{LANG:"C",LC_ALL:"C"}};const r=i(19851),s=i(40958),n=i(22573),a=i(42659),o=i(50213),l=i(81168),u=i(5916),c=i(84777),d=i(6012),h=i(43334),f=i(24399),m=i(63870);t.DefaultLocale="en";const p=(0,r.lazy)(()=>(0,o.mkLogger)("Locale"));function g(e=process.env){for(const t of[e.LC_ALL,e.LC_MESSAGES,e.LANG,e.LANGUAGE]){const e=v(t);if(null!=e)return e}}t.locale=(0,u.lazyAsync)({desc:"locale",later:async()=>b(g()??await(h.isWin?w():h.isMac?P():M()).catch(e=>(p().warn("Failed to get locale",{error:e}),t.DefaultLocale))),timeoutMs:(0,m.commandTimeoutMs)()}),t.envLocale=(0,r.lazy)(g);const y=/^(?<lang>[a-z]{2,3})(?:[_-](?<country>[a-z]{2,3}))?\b/i;function v(e){if((0,n.blank)(e))return;if(e===t.DefaultLocale||(0,l.equalsIgnoreCase)("c",e)||(0,l.equalsIgnoreCase)("posix",e))return t.DefaultLocale;const i=y.exec(e.trim())?.groups;return null==i?void 0:(0,s.compact)([i.lang,i.country]).join("-")}function b(e){return v(e)??t.DefaultLocale}async function w(){const e=await f.PowerShell.instance().executeJson("Get-WinSystemLocale | Select-Object -Property Name");return null==e?void 0:e.Name}const S={timeoutMs:10*a.secondMs};async function P(){return v(await(0,c.stdout_)("defaults",["read","-globalDomain","AppleLocale"],S))}async function M(){return b(g((0,d.parseEnvTokens)({lowerCaseKeys:!1,input:await(0,c.stdout_)("locale",[],S)})))}},57150(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logStartup=void 0;const r=i(48161),s=i(1708),n=i(45599),a=i(68708),o=i(50213),l=i(88158),u=i(96175),c=i(23560),d=i(84968),h=i(37805),f=i(9727),m=i(3790),p=i(29325),g=i(43334),y=i(28874);t.logStartup=(0,n.defer)(()=>{(0,o.mkLogger)("LogStartup").info("setup(): starting "+(0,c.serviceName)(),{version:h.version,StartTs:d.StartTs,argv:s.argv,arch:(0,r.arch)(),platform:(0,r.platform)(),os:(0,u.osFullName)(),isPacked:(0,p.isPacked)(),isElectron:(0,g.isElectron)(),versions:(0,a.pick)(s.versions,"electron","node"),settings:{logLevel:y.Settings.logLevel.valueOrDefault,logServer:y.Settings.logServer.valueOrDefault,httpPort:y.Settings.httpPort.valueOrDefault,libraryDir:y.Settings.libraryDir.valueOrDefault,copyAssetsToLibrary:y.Settings.copyAssetsToLibrary.value??"(unset)",UV_THREADPOOL_SIZE:s.env.UV_THREADPOOL_SIZE},...(0,l.mapEntries)((0,f.psenv)(),(e,t)=>[e,(0,m.isSensitiveEnvKey)(e)?"(hidden)":t])})})},50213(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rootLoggers=void 0,t.mkLogger=function(e,i){return new n.ContextualLogger(e,t.rootLoggers,void 0,i)},t.mkConsoleLogger=function(e){return new n.ContextualLogger(e,a)};const r=i(45599),s=i(32105),n=i(14593);t.rootLoggers=(0,r.defer)(()=>[s.ConsoleLogger.instance()]);const a=(0,r.defer)(()=>[s.ConsoleLogger.instance()])},31578(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.memoryUsageBytes=o,t.memoryUsageMb=function(){return(0,s.sigFigs)(o()/n.MB,2)},t.memoryUsageRssBytes=l,t.memoryUsageRssMb=function(){return(0,s.sigFigs)(l()/n.MB,2)};const r=i(1708),s=i(31586),n=i(12168),a=i(70417);function o(){const e=(0,r.memoryUsage)();return(0,a.sum)([e.external,e.heapUsed,e.arrayBuffers])}function l(){return(0,r.memoryUsage)().rss}},7282(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodeEnv=void 0,t.isDev=function(){return"development"===(0,t.nodeEnv)()},t.isTest=c,t.isProd=function(){return"production"===(0,t.nodeEnv)()},t.isSingleSpecTests=function(){return c()&&(0,n.isTrue)(s.default.env.SINGLE_SPEC_TESTS)},t.setSingleSpecTests=function(e){s.default.env.SINGLE_SPEC_TESTS=e?"true":"false"};const s=r(i(1708)),n=i(38639),a=i(54993),o=i(19851),l=i(29325),u=/mocha(?:\.js)?$|\.spec(\.js)?$/;function c(){return"test"===(0,t.nodeEnv)()}t.nodeEnv=(0,o.lazy)(()=>s.default.env.NODE_ENV=function(){if((0,l.isPacked)())return"production";switch((0,a.toS)(s.default.env.NODE_ENV).toLowerCase()){case"test":return"test";case"dev":case"development":return"development";case"prod":case"production":return"production";default:return s.default.argv.some(e=>null!=u.exec(e))?"test":"development"}}())},26033(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RequiredNodeRange=t.isSupportedNode=void 0,t._isSupportedNode=n;const r=i(45599),s=i(76280);function n(e=process.versions.node){return(0,s.semVerSatisfies)(e,t.RequiredNodeRange)}t.isSupportedNode=(0,r.defer)(n),t.RequiredNodeRange=">=22.13 <23 || >=24"},97352(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Array2D=t.within=void 0,t.firstGt0=function(...e){return e.find(a.gt0)},t.firstNonZero=function(...e){for(const t of(0,s.flatten)(e)){const e=(0,a.toFloat)(t);if(null!=e&&0!==e)return e}},t.mapGte0=function(e,t){return(0,a.mapInt)(e,e=>e>=0?t(e):void 0)},t.mapGte0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>=0?t(i):void 0},t.mapGt0f=function(e,t){const i=(0,a.toFloat)(e);return null!=i&&i>0?t(i):void 0},t.mapGt0=function(e,t){const i=(0,a.toInt)(e);return null!=i&&i>0?t(i):void 0},t.map2Gt0=function(e,t,i){const r=(0,a.toInt)(e),s=(0,a.toInt)(t);return null!=r&&r>0&&null!=s&&s>0?i(r,s):void 0},t.extractFloat=c,t.extractInt=function(e){return(0,a.toInt)(c(e))},t.extractFraction=function(e){if((0,a.isNumber)(e)||null==e)return e;if(d.test(e)){const t=(0,o.toS)(e).split(d,2);return(0,a.map2Numeric)(c(t[0]),c(t[1]),(e,t)=>e/t)}return c(e)},t.assertPositive=function(e,t){if(null==t||t<=0)throw new Error(e+" must be positive")},t.sqrt=function(e){return(0,a.gt0)(e)?Math.sqrt(e):0},t.multiply=function(...e){let t=1;for(const i of e){if(null==i)return;t*=i}return t};const r=i(22573),s=i(96249),n=i(55835),a=i(31586),o=i(54993);var l=i(31586);Object.defineProperty(t,"within",{enumerable:!0,get:function(){return l.within}});const u=/[+-]?[\d,.]+/;function c(e){if((0,a.isNumber)(e))return e;if((0,r.blank)(e))return;const t=String(e);return(0,n.map)(u.exec(t),e=>(0,a.toFloat)(t.substr(e.index)))}const d=/[:/]/;t.Array2D=class{columns;store=[];constructor(e){this.columns=e}get(e,t){return e<0||t<0?0:this.store[e*this.columns+t]??0}set(e,t,i){this.store[e*this.columns+t]=i}}},88158(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.definedThunks=function(...e){return e.every(e=>(0,o.defined)(e()))},t.firstThunk=function(...e){for(const t of e){const e=t();if(null!=e)return e}},t.firstTrueThunk=function(e,t){for(const i of e){const e=i();if(null!=e&&(null==t||t(e)))return e}},t.firstDefined=function(...e){return e.find(o.defined)},t.firstDefinedField=function(e,...t){return(0,o.map)(t.find(t=>null!=e[t]),t=>e[t])},t.firstFieldLike=function(e,t){return(0,h.first)((0,u.keys)(e),i=>t(i,e[i])?e[i]:void 0)},t.ornull=function(e){return void 0===e?null:e},t.mapAnd=function(e,t){return null!=e&&t(e)},t.mapOrThrow=function(e,t,i){if(null!=e)return t(e);throw new Error(i)},t.Try=m,t.tryEach=function(e,t){[...e].forEach(e=>m(()=>t(e)))},t.identity=function(e){return e},t.ctor=function(e){return(0,o.map)(e.constructor,e=>e.name)},t.hasKeys=function(e){return Object.keys(e).some(t=>"string"==typeof t&&e.propertyIsEnumerable(t))},t.primitiveEntries=p,t.spread=function(e,...t){return Object.assign({},e,...(0,r.compact)(t))},t.assignMissingPrimitives=function(e,t){if(null==t)return e;for(const[i,r]of p(t))null==e[i]&&(e[i]=r);return e},t.assignNullishFields=function(e,t){if(null==t)return e;for(const[i,r]of(0,u.entries)(t))(null==e[i]||(0,s.blank)(e[i]))&&(e[i]=r);return e},t.pickMap=function(e,t,i){const r={};for(const s of t)r[s]=i(s,e[s]);return r},t.mapEntries=g,t.mapNullEntries=function(e,t,i){const r={};let s=0;for(const n of(0,u.keys)(e))if(r[n]=t(n,e[n]),s++,(0,l.gt)(s,i))break;return r},t.sortedKeys=function e(t){if(null==t||(0,c.isPrimitive)(t))return t;if(Array.isArray(t))return t.map(t=>e(t));if("object"==typeof t){const i={};for(const r of(0,f.sortIgnoreCase)((0,u.keys)(t)))i[r]=e(t[r]);return i}return t},t.deepDelete=function e(t,...i){return null==t||"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e(t,...i)):g(t,(t,r)=>i.includes(t)?void 0:e(r,...i))},t.pluckCaseInsensitive=function(e,t){if("object"==typeof e){if(void 0!==e[t])return e[t];for(const i of(0,u.keys)(e).filter(e=>(0,f.equalsIgnoreCase)(e,t)))if(void 0!==e[i])return e[i]}},t.pairToObject=function(e,t){const i={};return i[e]=t,i},t.zipPojos=function(...e){const t={};for(const i of(0,r.uniq)((0,a.flatten)(e.map(u.keys))))t[i]=e.map(e=>e?.[i]);return t},t.downcaseObjectKeys=function e(t){if(null==t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(t=>e(t));const i={};for(const[r,s]of(0,u.entries)(t))i[r.toLowerCase()]=e(s);return i};const r=i(40958),s=i(22573),n=i(42659),a=i(96249),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(70978),h=i(48884),f=i(81168);function m(e,t){try{return e()}catch(e){return t?.((0,d.toError)(e))}}function p(e){return(0,u.keys)(e).filter(t=>(0,c.isPrimitive)(e[t])||(0,n.isDate)(e[t])).map(t=>[t,e[t]])}function g(e,t){const i={};for(const[r,s]of(0,u.entries)(e)){const e=t(r,s);null!=e&&(i[r]=e)}return i}},96175(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.whyOsNotSupported=t.CPUs=t.osDistributionLinux=t.osNameLinux=t.osReleaseTokens=t.osFullName=t.osArch=void 0,t.isDebian=P,t.isUbuntu=M,t.hasApt=function(){return P()||M()},t.isFedora=T,t.isAlpine=_,t.osNameMac=C,t.osNameWin=A;const s=i(31421),n=i(73024),a=r(i(48161)),o=i(19851),l=i(22573),u=i(42659),c=i(55835),d=i(51926),h=i(48884),f=i(50213),m=i(6012),p=i(45969),g=i(43334),y=i(76280),v=i(30933),b=(0,o.lazy)(()=>(0,f.mkLogger)("os"));function w(){return a.default.platform()+" "+a.default.release()}t.osArch=(0,o.lazy)(()=>`${function(){switch(a.default.platform()){case"linux":return(0,t.osNameLinux)();case"darwin":return C();case"win32":return A();default:return w()}}()} on ${a.default.arch()}`),t.osFullName=(0,o.lazy)(()=>(0,t.osArch)()+((0,p.isDocker)()?" (Docker)":""));const S=["/etc/os-release","/usr/lib/os-release"];function P(){return"debian"===(0,t.osDistributionLinux)()}function M(){return"ubuntu"===(0,t.osDistributionLinux)()}function T(){return"fedora"===(0,t.osDistributionLinux)()}function _(){return"alpine"===(0,t.osDistributionLinux)()}t.osReleaseTokens=(0,o.lazy)(()=>{if(g.isLinux)for(const e of S)try{const t=(0,n.readFileSync)(e).toString();if((0,l.notBlank)(t))return(0,m.parseEnvTokens)({input:t,lowerCaseKeys:!0})}catch(t){b().warn("failed to read os-release file",{filename:e,error:t})}}),t.osNameLinux=(0,o.lazy)(()=>{const e=(0,t.osReleaseTokens)();return(0,l.notBlank)(e?.pretty_name)?e?.pretty_name:(0,c.map2Or)(e?.name,e?.version??e?.version_id,(e,t)=>e+" "+t,w)}),t.osDistributionLinux=(0,o.lazy)(()=>g.isLinux?(0,t.osReleaseTokens)()?.id?.toLowerCase():void 0);const E={10:{6:"Snow Leopard",7:"Lion",8:"Mountain Lion",9:"Mavericks",10:"Yosemite",11:"El Capitan",12:"Sierra",13:"High Sierra",14:"Mojave",15:"Catalina"},11:"Big Sur",12:"Monterey",13:"Ventura",14:"Sonoma",15:"Sequoia",26:"Tahoe"},k={10:"10",6:{3:"8.1",2:"8",1:"7",0:"Vista"},5:{2:"Server 2003",1:"XP",0:"2000"},4:{9:"ME",1:"98",0:"95"}};function D(e,t){const[i,r]=function(e){return e.split(".").slice(0,2)}(e),s=t[i];return(0,d.isString)(s)?s:s?.[r]}const I=(0,o.lazy)(()=>(0,s.execSync)("sw_vers -productVersion").toString().trim());function C(e=I()){try{return(0,l.mapNotBlankOr)(function(e=I()){return D(e,E)}(e),t=>`macOS ${t} (${e})`,w)}catch(e){return b().warn("osNameMac(): unknown release",e),w()}}function A(e=a.default.release()){const t=(0,y.semverLt)(e,"10.0.22000")?D(e,k):"11";return null!=t?`Windows ${t} (${e})`:(b().warn("osNameWin(): unknown release: "+e),`Windows (${e})`)}t.CPUs=(0,o.lazy)(()=>(0,h.uniqCount)((0,v.cpuInfo)().map(e=>e.model)).map(e=>`${e.count} × ${e.t.trim()}`).join(", "),u.minuteMs),t.whyOsNotSupported=(0,o.lazy)(()=>{if(g.isWin)return"x64"===a.default.arch()&&/^Windows (?:10|11) /i.test(A())?void 0:"Windows 10 and 11 on x64";if(g.isMac){const e=I();return(0,y.semVerSatisfies)(e,">=12")?void 0:"macOS 12 (Monterey) or later"}if(g.isLinux){const e=["x64","arm64"].includes(a.default.arch()),i=(0,y.toSemVer)((0,t.osReleaseTokens)()?.version_id);if(P())return e&&(0,y.semVerSatisfies)(i,">=11")?void 0:"Debian 11 or later on x64/ARM64";if(M())return e&&(0,y.semVerSatisfies)(i,"20 || 22 || 24")?void 0:"Ubuntu LTS on x64/ARM64";if(T())return e&&(0,y.semVerSatisfies)(i,"37 || 38")?void 0:"Fedora 37 or 38 on x64/ARM64";if(_())return e&&(0,y.semVerSatisfies)(i,">=3.15")?void 0:"Alpine >= 3.15 on x64/ARM64"}return"recent versions of Windows 10/11, Debian/Ubuntu, and Fedora are supported on x64/ARM64, and macOS."})},12801(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PriorityClassToNode=t.PriorityClassToPosix=t.PriorityClasses=void 0,t.priorityPosixToClass=function(e){return null!=e&&isFinite(e)?e<t.PriorityClassToPosix.BelowNormal?t.PriorityClasses.Normal:e<t.PriorityClassToPosix.Idle?t.PriorityClasses.BelowNormal:t.PriorityClasses.Idle:void 0};const s=r(i(48161)),n=i(50989);t.PriorityClasses=(0,n.strEnum)("Normal","BelowNormal","Idle","Low"),t.PriorityClassToPosix=Object.freeze({Normal:0,BelowNormal:10,Low:19,Idle:19}),t.PriorityClassToNode=Object.freeze({AboveNormal:s.default.constants.priority.PRIORITY_ABOVE_NORMAL,Normal:s.default.constants.priority.PRIORITY_NORMAL,BelowNormal:s.default.constants.priority.PRIORITY_BELOW_NORMAL,Idle:s.default.constants.priority.PRIORITY_LOW,Low:s.default.constants.priority.PRIORITY_LOW})},92782(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.safeRandomChars=function({radix:e=n.TokenRadix,length:t}){return(0,a.decuss)(()=>e.randomChars(t))},t.safeRandomUid=function(e){return(0,a.decuss)(()=>(e?.radix??n.TokenRadix).randomUid(e?.chars??20,e?.splitEveryN??4,e?.sepChar??"-"))},t.randomIntBits=function(e=53){if(e>53)throw new Error("This function can only generate up to 53-bit numbers safely.");const t=Math.ceil(e/8),i=s.default.randomBytes(t);let r=0;for(let e=0;e<t;e++)r*=256,r+=i[e];return r%2**e};const s=r(i(77598)),n=i(55222),a=i(65713)},409(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rateLimited=function({f:e,minCallDelayMs:t,timeoutMs:i,nullOnBusy:c,name:d}){let h,f,m=!1,p=0;const g=[];function y(){return m||p>performance.now()}function v(){if(null!=f){const e=f;f=void 0,w(...e)}}async function b(...r){m=!0,p=performance.now()+(0,n.max_)((0,a.tot)(t),i);const s=h=new o.Deferred(d);(0,n.gt0)(i)&&s.setTimeout(i);try{s.resolve(await e(...r))}catch(e){s.reject(new u.WrappedError("RateLimited("+d+") failed",{cause:e}))}finally{m=!1,p=performance.now()+(0,a.tot)(t),(0,l.setUnrefTimeout)(v,(0,a.tot)(t)+1),g.forEach(e=>e.resolve()),g.length=0}return s.promise}const w=(...e)=>{if(y()){if(!0===c)return null;const t=h?.promise;return f=e,(0,r.delay)(1).then(()=>t)}return b(...e)};return w.clear=()=>{f=void 0},w.donePromise=()=>{if(!m)return Promise.resolve();const e=new s.Latch;return g.push(e),e},w.force=async(...e)=>(f=void 0,m&&await w.donePromise(),b(...e)),w.isRateLimited=()=>y(),w.status=()=>({running:m,needToDelay:p>performance.now(),minNextDelayMs:Math.max(0,performance.now()-p)}),w.minCallDelayMs=()=>t,w.setMinCallDelayMs=e=>{t=e},w};const r=i(41400),s=i(56409),n=i(31586),a=i(42279),o=i(22911),l=i(73614),u=i(57159)},68852(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RegExpOptional=t.RegExpEscaped=t.NothingRegExp=void 0,t.captures=function(e,t){const i=[];if(!e.global)throw new Error("must provide global regex");let s;for(e.lastIndex=0;null!=(s=e.exec(t));)s.index===e.lastIndex?e.lastIndex++:i.push((0,r.pick)(s,"index","groups"));return i},t.escapeRegExp=a,t.matchQuotes=function(e){return e.replace(/[‘’']/g,"[‘’']").replace(/[“”„«»〃"]/g,'[“”„”«»〃"]')},t.orRegExpPatterns=function(e,i){const r=[];for(const t of e)try{r.push(t instanceof RegExp?t.source:new RegExp(t).source)}catch{r.push(a(t))}const s=0===r.length?t.NothingRegExp:r.map(e=>"(?:"+e+")").join("|");return new RegExp(s,i)},t.concatRegexp=u;const r=i(68708),s=i(54993);t.NothingRegExp=/$^/;const n=/[-.,\\^$*+?()|[\]{}]/g;function a(e){return e instanceof o?e.source:(0,s.toS)(e).replace(n,"\\$&")}class o{source;flags;constructor(e,t){this.source=e,this.flags=t}get global(){return this.flags?.includes("g")??!1}get ignoreCase(){return this.flags?.includes("m")??!1}get multiline(){return this.flags?.includes("i")??!1}}t.RegExpEscaped=o;class l extends o{static from(...e){const t=u(e);return new l("(?:"+t.source+")?",t.flags)}}function u(e,t){let i="",r=t?.includes("g")??!1,n=t?.includes("i")??!1,l=t?.includes("m")??!1;for(const t of e)t instanceof o||t instanceof RegExp?(i+=t.source,r||=t.global,n||=t.ignoreCase,l||=t.multiline):i+=a((0,s.toS)(t));return new RegExp(i,t??(r?"g":"")+(n?"i":"")+(l?"m":""))}t.RegExpOptional=l},79089(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.niceable=function(e,t){return(0,o.compactBlanks)([n.default.basename(e),...t.map(e=>n.default.basename(e))]).some(e=>M().includes(e.toLowerCase()))},t.renice=async function(e,t){if(!(0,d.gt0)(e)||_().has(e))return;const i=(0,p.priorityPosixToClass)(t)??S.Settings.processPriority.valueOrDefault;if(t??=p.PriorityClassToNode[i],t!==s.default.constants.priority.PRIORITY_NORMAL){if(_().add(e),T)try{return s.default.setPriority(e,t),t}catch(i){const r=-13===i?.errno||"EACCES"===i?.info?.code;if(P().warn("Failed to renice using node:os",{pid:e,priority:t,permissionDenied:r,error:i}),r)return;T=!1}try{return await(b.isWin?async function(e,t){(0,d.gt0)(e)&&p.PriorityClasses.includes(t)&&await w.PowerShell.instance().execute(`(Get-Process -Id ${e}).PriorityClass = "${t}"`,e=>e).catch(e=>P().info("reniceWin() failed",e))}(e,i):async function(e,t=19){await(0,y.stdoutResult_)("renice",[t,"-p",e].map(f.toS),{timerName:"proc.renice",timeoutMs:10*l.secondMs,isIgnorableError:()=>!0,ignoreExitCode:!0}).catch(e=>P().info("renicePosix() failed",e))}(e,p.PriorityClassToPosix[i]??p.PriorityClassToPosix.BelowNormal)),P().info("Renice pid "+e+" to "+i),t}catch(t){return void P().info("Failed to renice pid "+e,{error:t})}}else P().debug("renice(): no-op as priority === normal",{priority:t,priorityClass:i})};const s=r(i(48161)),n=r(i(76760)),a=i(19851),o=i(40958),l=i(42659),u=i(41400),c=i(96249),d=i(31586),h=i(51926),f=i(54993),m=i(50213),p=i(12801),g=i(22277),y=i(84777),v=i(34102),b=i(43334),w=i(24399),S=i(28874),P=(0,a.lazy)(()=>(0,m.mkLogger)("Renice"));(0,u.later)(()=>(0,v.ee)().on("clearCache",()=>_.prior()?.clear()));const M=(0,a.lazy)(()=>["sync.js","worker.js",...(0,c.flatten)(["dcraw_emu","ffmpeg","heif-convert"].map(e=>b.isWin?[e,(0,h.ensureSuffix)(e,".exe")]:e))]);let T=!0;const _=(0,a.lazy)(()=>new g.TTLSet(l.minuteMs))},49517(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repoRoot=void 0;const r=i(45599),s=i(65843);t.repoRoot=(0,r.defer)(()=>{const e=(0,s.ancestorWithChildren)(__dirname,["src",".git","docs","examples","tools"]);if(null==e)throw new Error("Couldn't find the PhotoStructure project root directory");return e})},55476(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rmTestTmpfiles=void 0;const r=i(19851),s=i(77740);t.rmTestTmpfiles=(0,r.lazy)(()=>!(0,s.getDevEnvFlag)("PS_SKIP_CLEANUP"))},3685(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.roundMs=function(e){return Math.round(10*e)/10}},23560(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDbJanitorService=t.DbServices=t.MainServices=t.processName=t.serviceName=void 0,t.serviceNameIndex=function(e){return c.ServiceNames.indexOf(e)??c.ServiceNames.length+1},t.isDbService=function(){return t.DbServices.includes((0,t.serviceName)())},t.isLibraryRequiredService=function(e){return[c.ServiceNames.sync,c.ServiceNames.list].includes(e??(0,t.serviceName)())},t.isPermaService=function(e){return p(e)||g(e)},t.isMainService=p,t.isWebService=g,t.isBillingService=function(e){return(e??(0,t.serviceName)())===c.ServiceNames.billing},t.isWorkerService=y,t.isSyncService=v,t.isInfoService=b,t.isTestService=w,t.isLogtailService=S,t.isTrashService=function(){return v()||w()||g()},t.isDbManager=function(){return v()||g()||((0,f.isTest)()||w())&&!y()},t.janitorPriority=function(){return v()?0:g()?1:9},t.isTaskListManager=function(){return v()||w()},t.canTailLogs=function(e){return p(e)||v(e)||g(e)||b(e)||w(e)||S(e)};const s=i(76760),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(26905),c=i(5670),d=i(51926),h=i(54993),f=i(7282),m=i(43334);function p(e){return t.MainServices.includes(e??(0,t.serviceName)())}function g(e){return(e??(0,t.serviceName)())===c.ServiceNames.web}function y(e){return(e??(0,t.serviceName)())===c.ServiceNames.worker}function v(e){return(e??(0,t.serviceName)())===c.ServiceNames.sync}function b(e){return(e??(0,t.serviceName)())===c.ServiceNames.info}function w(e){return(e??(0,t.serviceName)())===c.ServiceNames.test}function S(e){return(e??(0,t.serviceName)())===c.ServiceNames.logtail}t.serviceName=(0,a.lazy)(()=>{if(m.isMainElectron)return c.ServiceNames.main;const e=n.default.argv[1];if((0,l.blank)(e))return"test";const t=(0,d.stripSuffix)((0,s.basename)(e),".js"),i=c.ServiceNames.toValid(t);return null!=i?i:(0,f.isTest)()?c.ServiceNames.test:t.endsWith("Mk")?c.ServiceNames.tool:(console.error("Unknown service name",{result:t,caller:(0,u.shortStack)()}),"unknown")}),t.processName=(0,a.lazy)(()=>(0,o.compactBlanks)([t.serviceName.prior(),(0,h.toS)(n.default.pid)]).join("-")),t.serviceName.watchLater(()=>{t.processName.unset()}),t.MainServices=[c.ServiceNames.main,c.ServiceNames.desktop],t.DbServices=[c.ServiceNames.fix,c.ServiceNames.info,c.ServiceNames.list,c.ServiceNames.sync,c.ServiceNames.test,c.ServiceNames.web],t.isDbJanitorService=(0,a.lazy)(()=>v()||w())},77377(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asSet=s,t.setEql=function(e,t){return(0,r.toA)(e.keys()).every(e=>t.has(e))&&(0,r.toA)(t.keys()).every(t=>e.has(t))},t.getOrAdd=function(e,t,i){if(null==t)throw new Error("null key");return e.has(t)?void 0:(e.add(t),i())},t.union=function(e,t){return new Set([...e,...t])},t.intersection=function(e,t){const i=s(t);return new Set([...e].filter(e=>i.has(e)))},t.diff=function(e,t){const i=s(t);return new Set([...e].filter(e=>!i.has(e)))};const r=i(59455);function s(e){return e instanceof Set?e:new Set((0,r.toA)(e))}},19913(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceName=function(e){(0,n.isMainService)(e)&&(e=r.ServiceNames.main);const t=n.serviceName.prior();t!==e&&((0,s.isTest)()||null==t||t===e||console.error("Don't set service name twice",{prior:t,new:e}),n.serviceName.set(e))};const r=i(5670),s=i(7282),n=i(23560)},79136(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shim=function(e){return new l(e.name,e.impl,e.cache,e.toKey)};const r=i(98553),s=i(34666),n=i(54993),a=i(62344),o=i(56038);class l extends a.ExtensibleFunction{impl;cache;toKey;#_;#E;constructor(e,t,i,r){super(),this.impl=t,this.cache=i,this.toKey=r,this.#_=e}#k(...e){return this.toKey?.(...e)??((0,s.isPrimitive)(e)?(0,n.toS)(e):(0,r.stringify)(e))}#D(...e){return null==this.#E?(0,o.time)({name:this.#_,p:this.impl(...e)}):this.#E(...e)}async _call(...e){const t=this.#k(...e);return null==this.cache?this.#D(...e):this.cache().getOrSet(t,()=>this.#D(...e))}setShim(e){this.#E=e}hasShim(){return null!=this.#E}clearShim(){this.#E=void 0}cacheDelete(...e){this.cache?.().delete(this.#k(...e))}}},30495(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimSync=function(e){return new l(e.name,e.impl,e.cache,e.toKey)};const r=i(98553),s=i(34666),n=i(54993),a=i(62344),o=i(56038);class l extends a.ExtensibleFunction{impl;cache;toKey;#_;#E;constructor(e,t,i,r){super(),this.impl=t,this.cache=i,this.toKey=r,this.#_=e}#k(...e){return this.toKey?.(...e)??((0,s.isPrimitive)(e)?(0,n.toS)(e):(0,r.stringify)(e))}#D(...e){return(0,o.timeSync)({name:this.#_,t:()=>null!=this.#E?this.#E(...e):this.impl(...e)})}_call(...e){return null==this.cache?this.#D(...e):this.cache().getOrSet(this.#k(...e),()=>this.#D(...e))}setShim(e){this.#E=e}hasShim(){return null!=this.#E}clearShim(){this.#E=void 0}cacheDelete(e){this.cache?.().delete(this.#k(...e))}}},45255(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShortCommandTimeoutMs=void 0;const r=i(42659);t.ShortCommandTimeoutMs=7*r.secondMs},64712(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleGlobArray=t.SimpleGlobs=void 0,t.simpleGlobToRegexp=s;const r=i(68852);function s(e,t){return new RegExp("^"+(0,r.escapeRegExp)(e).replace(/\\\?/g,".").replace(/\\\*/g,".*")+"$",t)}t.SimpleGlobs=class{#I;constructor(e,t){this.#I=(0,r.orRegExpPatterns)(e.map(e=>s(e)),t)}test(e){return this.#I.test(e)}},t.SimpleGlobArray=class{#C;constructor(e,t){this.#C=e.map(e=>s(e,t))}get length(){return this.#C.length}indexOf(e){if(null!=e)for(let t=0;t<this.#C.length;t++)if(this.#C[t].test(e))return t}}},25636(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sortNatural=function(e){return(0,s.sortBy)(e,p)},t.sortNaturalByRegExp=d,t.sortNaturalBy=p;const r=i(76760),s=i(76790),n=i(22573),a=i(31586),o=i(54993),l=i(4001),u=i(76280),c=/[-._/\\]|(?<=\d)(?=\D)|(?<=\D)(?=\d)/;function d(e,t){return(0,o.toS)(e).split(t).map(e=>(0,a.toInt)(e)??e)}const h=/\.[^.]{1,5}$/;function f(e){if(e.includes(r.sep)||e.includes("/")){const t=h.exec(e);if(null==t)return;const i=(0,l.stripCopySuffixFromName)(e,{aggressive:!1}).replace(h,"");if((0,n.blank)(i))return;const r=(0,l.copySuffixCountFromName)(e);return[...d(i,c),r??-1,t[0],e]}}function m(e){return/\s/.test(e)?d(e,/[-\s_./\\]/):void 0}function p(e){return[...(0,u.semverSortBy)(e)??f(e)??m(e)??d(e,c),e.length]}},92322(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SortedSet=void 0;const r=i(76790),s=i(17586),n=i(31586);class a{valueOf;#t=[];constructor(e){this.valueOf=e}[Symbol.iterator](){return this.#t[Symbol.iterator]()}map(e){return this.#t.map(e)}some(e){return this.#t.some(e)}filter(e){return this.#t.filter(e)}get length(){return this.#t.length}addAll(...e){for(const t of e)this.add(t)}#A(e){if(null==e)return;let t=0,i=this.#t.length-1;for(;t<=i;){const r=t+i>>>1,s=this.valueOf(this.#t[r]);if(e===s)return{found:!0,index:r};e>s?t=r+1:i=r-1}return{found:!1,index:t}}findIndex(e){return null==e?void 0:this.#A(this.valueOf(e))}add(e){const t=this.findIndex(e);return!1===t?.found&&(0,n.gte0)(t?.index)&&this.#t.splice(t.index,0,e),t}nearest({t:e,limit:t,diff:i}){if(t>=this.length)return[...this.#t];const s=t=>t<0||t>this.#t.length-1?null:i(this.#t[t],e),n=this.findIndex(e);if(null==n)return;let a=n.index-1,o=s(a),l=n.index,u=s(l);const c=[];for(;c.length<t&&(null!=o||null!=u);)null!=o&&(null==u||o<=u)&&(c.push(this.#t[a--]),o=s(a)),c.length<t&&null!=u&&(null==o||u<o)&&(c.push(this.#t[l++]),u=s(l));return(0,r.sortBy)(c,e=>this.valueOf(e))}clear(){this.#t.length=0}at(e){return(0,s.at)(this.#t,e)}toA(){return[...this.#t]}shift(){return this.#t.shift()}shiftLte(e){const t=this.#A(e);if(null==t||0===t.index&&!t.found)return[];if(t.index===this.#t.length-1){const e=[...this.#t];return this.clear(),e}return this.#t.splice(0,t.index+(t.found?1:0))}splice(e,t){return e<0&&(e=this.#t.length+e),null==t?this.#t.splice(e):this.#t.splice(e,t)}retainLastN(e){return e<this.length&&this.splice(0,this.#t.length-e),this}deleteIf(e){for(let t=this.#t.length-1;t>=0;t--)e(this.#t[t])&&this.#t.splice(t,1)}delete(e){const t=this.#t.indexOf(e);t>=0&&this.#t.splice(t,1)}}t.SortedSet=a},40296(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sigFigsDeep=o,t.stableJson=l,t.stableJsonStringify=function(e){return JSON.stringify(l(e))},t.pickInternalFields=function(e){const t={};for(const[i,r]of Object.entries(e))u.test(i)&&(t[i]=r);return t};const r=i(42659),s=i(31586),n=i(68708),a=i(88158);function o(e,t=5){return null==e?e:"number"==typeof e?(0,s.isInvalidNumber)(e)?e:(0,s.within)(-180,180,e)?(0,s.roundToDecimalPlaces)(e,t):Number.isInteger(e)?e:(0,s.sigFigs)(e,t):"bigint"==typeof e||(0,r.isDate)(e)?e:Array.isArray(e)?e.map(e=>o(e,t)):(0,n.isObject)(e)?(0,a.mapNullEntries)(e,(e,i)=>o(i,t)):e}function l(e){return(0,n.omitDeep)(o((0,a.sortedKeys)((0,n.compactValuesDeep)(e))),u)}const u=/^__.+?__$/},84968(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StartTs=void 0,t.runtimeMs=function(){return Date.now()-t.StartTs},t.StartTs=Date.now()},82328(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stdoutEnded=function(){return(0,s.streamEnded)(r.stdout)};const r=i(1708),s=i(14810)},71567(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StdoutWrite=t.ReadyStr=void 0,t.stdoutWriteReady=function(e=!0){(0,l.stdoutEnded)()||s.default.stdout.write(JSON.stringify({ready:e})+"\n")},t.stdoutWrite=f,t.stderrWrite=function(e){return m({obj:e,stream:s.default.stderr})},t.writeTTY=m,t.stdoutWriteSettings=function(...e){const t={};for(const i of e)i.addToEnv(t);f(t)},t.stdoutWriteMigration=function(e){return f({migration:e.name})},t.isMigrationEvent=function(e){return null!=e&&(0,n.notBlank)(e.migration)};const s=r(i(1708)),n=i(22573),a=i(98553),o=i(23560),l=i(82328),u=i(38835),c=i(70025),d=i(34102),h=i(14810);function f(e,t){return m({obj:e,ready:t,stream:s.default.stdout})}function m({obj:e,ready:i,stream:r}){if(null==r||(0,h.streamEnded)(r))return;const s=(0,a.stringify)(e,(0,o.isInfoService)()||(0,o.isMainService)()?2:void 0);r.write(s+"\n"),(0,o.isWorkerService)()&&null!=i&&(s.includes(u.FailStr)||(0,c.isFatalError)(s)||(0,c.isHealthCheckError)(s)?r.write(u.FailStr+"\n"):r.write(t.ReadyStr+"\n"))}t.ReadyStr=JSON.stringify({ready:!0}),t.StdoutWrite={shutdownSync:()=>{(0,d.ee)().emitSync("syncShutdown"),f({shutdownSync:!0})},startSync:()=>f({startSync:!0}),restartSync:()=>{(0,d.ee)().emitSync("syncShutdown"),f({restartSync:!0})},shutdown:e=>f({shutdown:!0,reason:e})}},81168(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wrap=t.stripSuffix=t.stripPrefix=t.isString=t.includesIgnoreCase=t.equalsIgnoreCase=t.ensureSuffix=t.ensurePrefix=t.ellipsize=t.splitFirst=void 0,t.ensureSuffixIgnoreCase=function(e,t){return null==t||""===t?e:(e=(0,f.toS)(e),t=(0,f.toS)(t),e.endsWith(t)||(0,d.equalsIgnoreCase)(e.slice(-t.length),t)?e:e+t)},t.rightPad=function(e,t,i){if(!i||0===i.length)throw new Error("rightPad() requires a non-empty pad character");const r=String(e);if(r.length>=t)return r;const s=t-r.length;if(i.length>1){let e="";for(let t=0;t<s;t++)e+=i[t%i.length];return r+e}return r+i.repeat(s)},t.padReplace=function(e,t,i,r){return(0,d.strslice)(e,0,t)+(0,u.padding)(r,i)+(0,d.strslice)(e,t+i)},t.contains=function(e,t,i){return null!=e&&null!=t&&(""===e&&""===t||(0,f.toS)(e).indexOf((0,f.toS)(t),i)>-1)},t.countChars=function e(t,i,r=0){if(null==i||0===i.length)return 0;const s=t.indexOf(i,r);return-1===s?0:1+e(t,i,s+i.length)},t.maybeToS=function(e){return null==e?void 0:String(e)},t.trim=function(e){return e.map(f.toS).filter(e=>(0,a.notBlank)(e))},t.splitEvery=function(e,t,i){const r=Math.min(Math.ceil(e.length/t),i??e.length)-1;return r<=0?[e]:[...(0,l.times)(r,i=>e.slice(i*t,(i+1)*t)),e.slice(r*t)]},t.spliceCapture=function(e,t){const i=t.exec(e);if(null==i||null==i[1])return;const r=i[0].indexOf(i[1])+i.index;return{captured:i[1],uncaptured:e.substring(0,r)+e.substring(r+i[1].length),unmatched:e.substring(0,i.index)+e.substring(i.index+i[0].length),matchedIndex:r}},t.stripPrefixIgnoreCase=function(e,t){return M(e=(0,f.toS)(e),t=(0,f.toS)(t))?e.slice(t.length):e},t.stripSuffixIgnoreCase=function(e,t,i={}){if(null==t)return e;const r=(0,f.toS)(e),s=(0,f.toS)(t);return s.length>0&&(0,d.equalsIgnoreCase)(r.slice(-s.length),s,i)?r.slice(0,-s.length):r},t.gist=function(e,t=80,i=80){if(!e)return e;const r=(0,f.toS)(e),s=r.length-(t+i);if(s<=0)return r;const n=r.slice(0,t).trim(),a=r.slice(-i).trim();return`${n} …(+${s.toLocaleString()} chars)… ${a}`},t.isLowerCase=function(e){return(0,f.toS)(e).toLocaleLowerCase()===e},t.isUpperCase=function(e){return(0,f.toS)(e).toLocaleUpperCase()===e},t.isFirstCharAZ=function(e){return b.test((0,f.toS)(e))},t.capitalize=function(e){return e=(0,f.toS)(e),(0,a.blank)(e)?e:(0,d.strslice)(e,0,1).toLocaleUpperCase()+(0,d.strslice)(e,1)},t.compareIgnoreCase=w,t.uniqIgnoreCase=function(e){return(0,s.uniqBy2)(e,d.equalsIgnoreCase)},t.sortIgnoreCase=S,t.firstString=P,t.deepSortIgnoreCase=function e(t){return t.map((t,i)=>({idx:i,ea:Array.isArray(t)?e(t):t})).sort((e,t)=>{const i=P(e.ea),r=P(t.ea);if(null==i)return null==r?0:-1;if(null==r)return 1;const s=w(i,r);if(0!==s)return s;if(Array.isArray(e.ea)&&Array.isArray(t.ea)){const i=e.ea.length-t.ea.length;if(0!==i)return i}return(0,c.cmp)(e.idx,t.idx)}).map(e=>e.ea)},t.sortByCaseInsensitive=function(e,t){return(0,h.toA)(e).filter(e=>null!=e).map((e,i)=>({item:e,idx:i,f:t(e,i)})).filter(e=>null!=e.f).sort((e,t)=>{const i=w(e.f,t.f);return 0!==i?i:(0,c.cmp)(e.idx,t.idx)}).map(e=>e.item)},t.startsWithIgnoreCase=M,t.firstSubstringIgnoreCase=function(e,t){if((0,s.isEmpty)(e)||(0,a.blank)(t))return;for(const i of e)if((0,d.equalsIgnoreCase)(i,t))return{index:0,match:i};for(const i of e){const e=t.indexOf(i);if(e>=0)return{index:e,match:i}}const i=t.normalize();for(const t of e){{const e=i.indexOf(t);if(e>=0)return{index:e,match:t}}const e=t.normalize();{const t=i.indexOf(e);if(t>=0)return{index:t,match:e}}{const t=i.toLowerCase(),r=e.toLowerCase(),s=t.indexOf(r);if(s>=0)return{index:s,match:r}}}},t.reverse=function(e){return null==e?e:[...e].reverse().join("")},t.longestPrefix=function(e,t){return(0,m.greatestBy)(t.filter(t=>e.startsWith(t)),e=>e.length)},t.stripAnsiEsc=function(e){return(0,f.toS)(e).replace(/\u001B\[[\d;]+[a-z]/gi,"")},t.dumbquote=_,t.stripQuotes=function(e){return(0,a.blank)(e)||(e=(0,f.toS)(e).trim(),null!=E.exec(_(e))&&(e=e.slice(1,-1).trim())),e},t.trimQuotes=function(e){return e=(0,f.toS)(e).trim(),k.test(e)||D.test(e)?e.slice(1,-1).trim():e},t.wbrPath=function(e){return e.split(/(?<=[\\/_,:=-])/).map(e=>(0,r.escape)(e.normalize())).join("<wbr>")},t.zipStrings=function(...e){let t="";const i=(0,s.compactBlanks)(e),r=Math.max(...i.map(e=>e.length));for(let e=0;e<r;e++)for(let r=0;r<i.length;r++)(0,o.map)(i[r],i=>(0,o.map)(i[e],e=>t+=e));return t},t.yieldSplit=function*(e,t){if(!e)return;if(!t.global)throw new Error("yieldSplit requires a global regex (with g flag)"+g.NonRetriableErrorFlag);let i,r=0;for(t.lastIndex=0;null!==(i=t.exec(e));)i.index!==t.lastIndex?(yield e.substring(r,t.lastIndex),r=t.lastIndex):t.lastIndex++;r<e.length&&(yield e.substring(r))},t.splitKeep=function(e,t){const i=I(e,t);return(0,m.flatZip)(i.nonSeparators,i.separators).filter(e=>null!=e&&e.length>0)},t.splitUp=I,t.stripDiacritics=function(e){return(0,f.toS)(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"")},t.isGarbageString=function(e,t=2){const i=(0,f.toS)(e).trim();if(i.length<t)return!0;if(A.test(i))return!0;if(i.includes("�"))return!0;const r=i.replace(/\s/g,"");return 0===r.length||(r.match(x)??[]).length/r.length<.5},t.stripEmoji=function(e){e=(0,f.toS)(e);for(const t of C)e=e.replace(t,"");return e},t.uniqSubstr=function(e){const t=S((0,s.compactBlanks)(e)),i=t.filter((e,i)=>!M(t[i+1],e));return(0,n.sortBy)(i,t=>e.indexOf(t))},t.commonPrefix=function(e,t){if((0,a.blank)(e)||(0,a.blank)(t))return"";const i=Math.min(e.length,t.length);for(let r=0;r<i;r++)if(e[r]!==t[r])return e.slice(0,r);return e.slice(0,i)},t.commonPrefixIgnoreCase=function(e,t,i={}){if((0,a.blank)(e)||(0,a.blank)(t))return"";const r=Math.min(e.length,t.length);for(let s=0;s<r;s++)if(!(0,d.equalsIgnoreCase)(e[s],t[s],i))return e.slice(0,s);return e.slice(0,r)},t.commonPrefixLengthIgnoreCase=function(e,t,i={}){if(i.normalize??=!1,(0,a.blank)(e)||(0,a.blank)(t))return 0;const r=Math.min(e.length,t.length);for(let s=0;s<r;s++)if(!(0,d.equalsIgnoreCase)(e[s],t[s],i))return s;return r},t.indexOfNonSpace=function(e){return e.match(/\S/)?.index},t.lastIndexOfNonSpace=function(e){return e.match(/\S\s*$/)?.index},t.trimLeftPadding=function(e){return e.replace(/^[-0_\s]+/,"")},t.unoctal=function(e){return e.replace(/\\([0-7]{1,3})/g,(e,t)=>{const i=parseInt(t,8);if(i>255||i<32)throw new Error(`Invalid octal sequence: ${e}`);return String.fromCharCode(i)})},t.stripComments=function(e){return e.replace(F,"")},t.uniqPath=function(e,t=":"){const i=new Set;for(const r of(0,h.toA)(e))if(null!=r&&!(0,a.blank)(r))for(const e of r.split(t))(0,a.blank)(e)||i.add(e);return[...i].join(t)},t.dedupeNeedle=function(e,t,i){if((0,a.blank)(t))return e;const r=new RegExp("(['\"]?)"+(0,p.escapeRegExp)(t)+"\\1","gm"),s=e.findIndex(e=>r.test(e)),n=new RegExp("("+(0,p.escapeRegExp)(i)+"[,:\\s]*){2,}","gim");if(s<0)return e;for(let t=s+1;t<e.length;t++)e[t]=e[t].replace(r,i).replace(/\s{2,}/g," ").replace(n,i).trim();return e},t.splitUniq=function(e,t){return(0,s.uniq)((0,s.compactBlanks)(e.join(t).split(t).map(e=>e.trim())))};const r=i(28787),s=i(40958),n=i(76790),a=i(22573),o=i(55835),l=i(31586),u=i(39926),c=i(34666),d=i(51926),h=i(59455),f=i(54993),m=i(48884),p=i(68852),g=i(38835);var y=i(38453);Object.defineProperty(t,"splitFirst",{enumerable:!0,get:function(){return y.splitFirst}});var v=i(51926);Object.defineProperty(t,"ellipsize",{enumerable:!0,get:function(){return v.ellipsize}}),Object.defineProperty(t,"ensurePrefix",{enumerable:!0,get:function(){return v.ensurePrefix}}),Object.defineProperty(t,"ensureSuffix",{enumerable:!0,get:function(){return v.ensureSuffix}}),Object.defineProperty(t,"equalsIgnoreCase",{enumerable:!0,get:function(){return v.equalsIgnoreCase}}),Object.defineProperty(t,"includesIgnoreCase",{enumerable:!0,get:function(){return v.includesIgnoreCase}}),Object.defineProperty(t,"isString",{enumerable:!0,get:function(){return v.isString}}),Object.defineProperty(t,"stripPrefix",{enumerable:!0,get:function(){return v.stripPrefix}}),Object.defineProperty(t,"stripSuffix",{enumerable:!0,get:function(){return v.stripSuffix}}),Object.defineProperty(t,"wrap",{enumerable:!0,get:function(){return v.wrap}});const b=/^[A-Z]/;function w(e,t){return e.localeCompare(t,void 0,{sensitivity:"base"})}function S(e){return(0,n.sortBy)(e,e=>null==e?void 0:[e.toLocaleLowerCase(),e])}function P(e){return null==e?void 0:(0,d.isString)(e)?e:Array.isArray(e)?(0,m.first)(e,P):void 0}function M(e,t){return null!=e&&null!=t&&0!==t.length&&0!==e.length&&(0,d.equalsIgnoreCase)(e.substring(0,t.length),t)}const T=[[/[‘’]/g,"'"],[/[“”„«»〃]/g,'"']];function _(e){return T.reduce((e,[t,i])=>e.replace(t,i),e).normalize()}const E=/^(['"]).+\1$/,k=/^['‘’].*['‘’]$/,D=/^["“”„«»〃].*["“”„«»〃]$/;function I(e,t){if(!t.global)throw new Error("bad regex (missing global flag)"+g.NonRetriableErrorFlag);const i=[],r=[];let s,n=0;for(;null!=(s=t.exec(e));)s.index===t.lastIndex?t.lastIndex++:(t.lastIndex=s[0].length+s.index,i.push(e.substring(n,s.index)),r.push(e.substring(s.index,t.lastIndex)),n=t.lastIndex);return n<e.length&&i.push(e.substring(n)),{nonSeparators:i,separators:r}}const C=[/\ud83d[\ude00-\ude4f]/g,/\ud83c[\udf00-\udfff]/g,/\ud83d[\udc00-\uddff]/g,/\ud83d[\ude80-\udeff]/g,/\ud83c[\udde6-\uddff]/g,/[\u2600-\u27ff]\ufe0f?/g,/\ud83c[\ude01\ude02]/g,/\ud83c[\ude1a-\ude1f]/g,/[\u0023-\u0039]\ufe0f?\u20e3/g,/[\u3299\u3297\u303d\u3030\u24c2]|\ud83c[\udd70\udd71]/g,/\ud83c[\udd7e\udd7f]/g,/\ud83c\udd8e/g,/\ud83c[\udd91-\udd9a]/g,/\ud83c[\udde6-\uddff]/g,/[\u2702-\u27b0]/g,/\ud83e[\udd00-\uddff]/g,/[\u200D\uFE0F\u20E3]/g,/[\u2640\u2642\u26A7]/g,/\ud83c[\udffb-\udfff]/g],A=/[\x00-\x1f\x7f-\x9f]/,x=/[\p{L}\p{N}]/gu,F=/#.*$/gm},83556(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.camel2snake=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,(e,t,i)=>"_"+t.toLowerCase()+i).replace(/[A-Z]+|\d+/g,e=>"_"+e).replace(/^_/,"").replace(/_+/g,"_")},t.camel2words=function(e){return(0,r.toS)(e).replace(/([A-Z])([a-z])/g,(e,t,i)=>" "+t.toLowerCase()+i).replace(/[A-Z]+|\d+/g,e=>" "+e).trim()},t.snake2camel=s,t.asObjectKey=function(e){return s(e.replace(/^[A-Z]+/,e=>e.toLowerCase()).replace(/[^a-z]+/gi,"_"))};const r=i(54993);function s(e){return(0,r.toS)(e).replace(/_([A-Z])/gi,(e,t)=>t.toUpperCase())}},37628(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.stringShaToBuffer=o,t.shortStringSha=l,t.shortFsStringSha=function(e,t=24,i=a.GeoRadix,r=224){return l(e,t,i,r)},t.stringSha512_b64=function(e){return s.default.createHash("sha512").update(e).digest().toString("base64")};const s=r(i(77598)),n=i(73913),a=i(55222);function o(e,t=n.HashBits){return s.default.createHash("sha512").update(e).digest().subarray(0,t/8)}function l(e,t=9,i=a.Radix58,r=224){return i.encodeBuffer(o(e,r)).substring(0,t)}},94863(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoBlanksStringNormalizer=function(e){return null==e||(0,r.blank)(e)?void 0:n(e)},t.StringNormalizer=n;const r=i(22573),s=i(54993);function n(e){return(0,s.toS)(e).toLowerCase().normalize()}},96859(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonSubstringRatio=function(e,t){return[e,t].some(n.blank)?0:p(e,t).length/Math.max(e.length,t.length)},t.lcs=p,t.hamming=g,t.diceCoeff=v,t.bigrams=b,t.nonUniqIntersection=w,t.lnsDiff=M,t.radixDiff=_,t.str=function(e,t){return{pref:(0,r.commonPrefixLength)(e,t),ham:g(e,t),dice:v(e,t),lns:M(e,t),radixDiff:_(e,t)}},t.lcdiff=function(e){return(0,r.count)([...e.normalize()],e=>0!==e.toLowerCase().localeCompare(e))},t.positionalDiff=E,t.paddedPositionalDiff=function(e,t,i=8){return E((0,o.leftPad)(e,i," "),(0,o.leftPad)(t,i," "))};const r=i(40958),s=i(76790),n=i(22573),a=i(31586),o=i(39926),l=i(51926),u=i(54993),c=i(55222),d=i(97352),h=i(88158),f=i(77377),m=i(81168);function p(e,t){if(null==e)return t;if(null==t)return e;if((e=e.normalize())===(t=t.normalize())||t.includes(e))return e;if(e.includes(t))return t;const i=new d.Array2D(e.length);let r=0,s="";for(let n=0;n<e.length;n++)for(let a=0;a<t.length;a++)e[n]===t[a]&&(0===n||0===a?i.set(n,a,1):i.set(n,a,i.get(n-1,a-1)+1),i.get(n,a)>=r&&(r=i.get(n,a),s=(0,l.substr)(e,n-r+1,r)));return s}function g(e,t){if(null==e||null==t)return;if(e===t)return 0;const i=y(e,t);if(null!=i)return i;const r=e.normalize(),s=t.normalize();return e!==r||t!==s?y(r,s):void 0}function y(e,t){return e.length!==t.length?void 0:[...e].reduce((e,i,r)=>i===t.charAt(r)?e:e+1,0)}function v(e,t){const i=e.toUpperCase().normalize(),r=t.toUpperCase().normalize();return(0,h.firstThunk)(()=>i===r?1:void 0,()=>(0,n.blank)(e)!==(0,n.blank)(t)?0:void 0,()=>1===e.length&&1===t.length?0:void 0,()=>{const e=b(i),t=b(r);return 2*w(e,t).length/(e.length+t.length)})}function b(e){if(null==e||0===e.length)return[];const t=[...e];return t.slice(0,-1).map((e,i)=>e+t[i+1])}function w(e,t){const i=(0,f.intersection)(e,t),s=[];return i.forEach(i=>{const n=Math.min((0,r.count)(e,e=>e===i),(0,r.count)(t,e=>e===i));(0,a.times)(n,()=>s.push(i))}),s}function S(e,t,i){const s=(0,r.commonPrefixLength)(e,t);return i((0,l.strslice)(e,s))-i((0,l.strslice)(t,s))}function P(e){const t=(0,r.compactBlanks)((0,u.toS)(e).split(/\D+/));return(0,s.sortBy)(t,e=>-e.length)[0]}function M(e,t){const[i,r]=[e,t].map(P).map(e=>(0,n.blank)(e)?"":e);return S(i,r,e=>(0,a.toInt)(e,{defaultValue:0}))}const T=/[^\da-z]+/gi;function _(e,t){const[i,r]=[e,t].map(e=>(0,m.stripDiacritics)(e).replace(T,"").toLowerCase());return S(i,r,e=>c.Radix36.decode(e))}function E(e,t){let i;for(let r=Math.max(e.length,t.length);r>=0;r--){const s=(0,a.mapNumericOr)(e.charCodeAt(r),e=>e,256),n=(0,a.mapNumericOr)(t.charCodeAt(r),e=>e,256),o=(0,a.clamp)(-256,256,s-n);i=null==i?o:(i+o)/2}return i}},84885(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifySorted=function(e){return(0,r.stringify)((0,s.sortedKeys)(e))};const r=i(98553),s=i(88158)},15890(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SubstringMatcher=void 0;const r=i(68852);t.SubstringMatcher=class{#x;constructor(e){e.length>0&&(this.#x=new RegExp(e.map(e=>(0,r.escapeRegExp)(e)).join("|"),"i"))}test(e){return null!=this.#x&&this.#x.test(e)}}},88264(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLArray=void 0;const r=i(31586);class s{ttlMs;maxLength;times=[];a=[];expirationListeners=[];constructor(e,t){this.ttlMs=e,this.maxLength=t}[Symbol.iterator](){this.vacuum();const e=[...this.a];return function*(){for(const t of e)yield t}()}push(...e){(0,r.times)(e.length,()=>this.times.push(performance.now())),this.a.push(...e),null!=this.maxLength&&this.vacuum()}pushUniq(...e){e.forEach(e=>{this.includes(e)||this.push(e)})}includes(e){return this.vacuum(),this.a.indexOf(e)>=0}find(e){return this.vacuum(),this.a.find(e)}some(e){return this.vacuum(),this.a.some(e)}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,t){return this.vacuum(),this.a.slice(e,t)}get length(){return this.vacuum(),this.a.length}clear(){return this.times.length=0,this.a.length=0,this}get values(){return this.vacuum(),[...this.a]}map(e){return this.vacuum(),this.a.map(e)}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;const e=this.a.length;if(null!=this.maxLength){const e=this.a.length-this.maxLength;this.times.splice(0,e),this.a.splice(0,e)}const t=performance.now()-this.ttlMs,i=this.times.findIndex(e=>e>t);if(-1===i?this.clear():i>0&&(this.times.splice(0,i),this.a.splice(0,i)),e!==this.a.length)for(const e of this.expirationListeners)e()}}t.TTLArray=s},22277(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TTLSet=void 0;const r=i(73614);class s{ttlMs;scheduleExpirationTimers;[Symbol.toStringTag]="TTLSet";expireListeners=[];delegate=new Map;constructor(e,t=!1){this.ttlMs=e,this.scheduleExpirationTimers=t}get size(){return this.#F(),this.delegate.size}add(e){return this.delegate.set(e,performance.now()),this.scheduleExpirationTimers&&(0,r.setUnrefTimeout)(()=>this.#F(),this.ttlMs+1),this}addAll(e){for(const t of e)this.add(t)}addIfMissing(e,t){const i=this.delegate.get(e);return null==i||this.#O(e,i)?(this.add(e),t()):void 0}clear(){return this.delegate.clear(),this}delete(e){return this.delegate.delete(e)}forEach(e){for(const[t,i]of this.delegate)this.#O(t,i)||e(t,t,this)}has(e){return null!=e&&!this.#O(e)}*values(){for(const[e,t]of this.delegate)this.#O(e,t)||(yield e)}keys=this.values.bind(this);*entries(){for(const[e,t]of this.delegate)this.#O(e,t)||(yield[e,e])}toA(){return this.#F(),[...this.delegate.keys()]}[Symbol.iterator](){return this.values()}on(e,t){this.expireListeners.push(t)}#O(e,t){if(t??=this.delegate.get(e),null==t||!this.delegate.has(e))return!0;const i=t<=performance.now()-this.ttlMs;if(i){this.delegate.delete(e);for(const t of this.expireListeners)t(e)}return i}#F(){for(const[e,t]of this.delegate)this.#O(e,t)}}t.TTLSet=s},84699(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TestLibraryDirPrefix=void 0,t.TestLibraryDirPrefix="test-ps-lib-"},90400(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deinterleaveTypedArray=function(e,t){const i=[],r=Math.floor(e.length/t);for(let s=0;s<t;s++){const n=new(0,e.constructor)(r);for(let i=0;i<r;i++)n[i]=e[i*t+s];i.push(n)}return i}},65211(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uidSuffix=t.UidRadix=void 0,t.uid=d,t.uidForTs=h,t.isUID=function(e){return f.test((0,o.toS)(e))},t.tsFromUid=m,t.sortByUid=function(e){return(0,n.sortBy)(e,e=>m(e.uid))},t.resetUid=function(){if(!(0,l.isTest)())throw new Error("unsupported");t.uidSuffix.unset(),c=0},t.addInstanceIds=function(e){const t=e;return(0,a.isObject)(t)&&(t.__pid__=r.pid,t.__uid__=d()),t};const r=i(1708),s=i(19851),n=i(76790),a=i(68708),o=i(54993),l=i(7282),u=i(55222);let c=0;function d(){return c=Math.max(Date.now(),c+1),h(c)}function h(e){return t.UidRadix.encode(e)+(0,t.uidSuffix)()}t.UidRadix=u.TokenRadix,t.uidSuffix=(0,s.lazy)(()=>"-"+t.UidRadix.randomChars(7));const f=/^(?<ts>[\da-z]{9})-[\da-z]{7}$/i;function m(e){const i=f.exec((0,o.toS)(e));return t.UidRadix.decode(i?.groups?.ts)}},24526(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.userid=t.userids=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(40958),o=i(31586),l=i(19851);t.userids=(0,l.lazy)(()=>(0,a.uniq)([n.default.geteuid?.(),n.default.getuid?.(),s.default.userInfo().uid]).filter(o.gte0)),t.userid=(0,l.lazy)(()=>(0,t.userids)()[0])},94174(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isRootUser=t.username=t.userNameFromWindowsAccessToken=t.userNameFromWhoami=t.usernameFromUserInfo=t.usernameFromEnv=void 0,t.userDesc=async function(){let e="user "+await(0,t.username)();return(0,u.gte0)((0,h.userid)())&&(e+=" (userid "+(0,h.userid)()+")"),e};const s=r(i(48161)),n=i(19851),a=i(40958),o=i(22573),l=i(38639),u=i(31586),c=i(50213),d=i(45255),h=i(24526),f=i(84777),m=i(96706),p=i(43334),g=i(24399),y=(0,n.lazy)(()=>(0,c.mkLogger)("UserInfo"));t.usernameFromEnv=(0,n.lazy)(()=>{for(const e of["SUDO_USER","C9_USER","LOGNAME","USER","LNAME","USERNAME"]){const t=(0,m.getEnv)(e);if(!(0,o.blank)(t))return t}}),t.usernameFromUserInfo=(0,n.lazy)(()=>(0,o.toNotBlank)(s.default.userInfo()?.username)),t.userNameFromWhoami=(0,n.lazy)(async()=>(0,f.stdout_)("whoami",[],{ignoreExitCode:!0,timeoutMs:d.ShortCommandTimeoutMs,isIgnorableError:()=>!0}).then(o.toNotBlank).catch(e=>y().warn("$(whoami) failed",{error:e}))),t.userNameFromWindowsAccessToken=(0,n.lazy)(async()=>p.isWin?(0,a.last)((await g.PowerShell.instance().execute("[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",o.toNotBlank))?.trim().split("\\")):void 0),t.username=(0,n.lazy)(async()=>(0,o.toNotBlank)((0,t.usernameFromEnv)())??(0,o.toNotBlank)((0,t.usernameFromUserInfo)())??(0,o.toNotBlank)(await(0,t.userNameFromWhoami)())??(0,o.toNotBlank)(await(0,t.userNameFromWindowsAccessToken)())),t.isRootUser=(0,n.lazy)(async()=>p.isWin?async function(){return p.isWin?await g.PowerShell.instance().execute("(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",l.toBoolean)??!1:void 0}():0===(0,h.userid)())},37805(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gitDate=t.gitSha=t.release=t.versionPrerelease=t.versionPatch=t.versionMinor=t.versionMajor=t.version=void 0,t.version="2026.4.7-beta",t.versionMajor=2026,t.versionMinor=4,t.versionPatch=7,t.versionPrerelease=["beta"],t.release="2026.4.7-beta+20260427190951",t.gitSha="ba011df2caf92da189a009f6c41c4185bb4e4c90",t.gitDate=new Date(1777342191e3),t.default={version:t.version,versionMajor:t.versionMajor,versionMinor:t.versionMinor,versionPatch:t.versionPatch,versionPrerelease:t.versionPrerelease,release:t.release,gitSha:t.gitSha,gitDate:t.gitDate}},48299(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WeakCache=void 0;class i{[Symbol.toStringTag]="WeakCache";#l=new Map;clear(){return this.#l.clear(),this}delete(e){return this.#l.delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){for(const[t,i]of this.entries())e(i,t,this)}findEntry(e){for(const[t,i]of this.entries())if(e(i,t,this))return i}deleteValueIf(e){let t=!1;for(const[i,r]of this.entries())e(r,i,this)&&(t||=this.#l.delete(i));return t}get(e){const t=this.#l.get(e),i=t?.deref();return null==i&&null!=t&&this.#l.delete(e),i}getOrMaybeSet(e,t){const i=this.#l.get(e)?.deref();if(null!=i)return i;const r=t();return null!=r&&this.set(e,r),r}set(e,t){return this.#l.set(e,new WeakRef(t)),this}has(e){return null!=this.#l.get(e)?.deref()}get size(){return this.#F(),this.#l.size}*keys(){for(const[e,t]of this.#l.entries())null==t.deref()?this.#l.delete(e):yield e}*values(){for(const[e,t]of this.#l.entries()){const i=t.deref();null==i?this.#l.delete(e):yield i}}*entries(){for(const[e,t]of this.#l.entries()){const i=t.deref();null==i?this.#l.delete(e):yield[e,i]}}#F(){for(const[e,t]of this.#l.entries())null==t.deref()&&this.#l.delete(e)}[Symbol.iterator](){return this.entries()}}t.WeakCache=i},79184(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aggregateAssetFiles=function(e){const t=(0,n.sortAssetFilesInPlace)(e);return(0,r.clusterEvery)(t,s.isSimilarMedia)};const r=i(48884),s=i(79781),n=i(92434)},79781(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VideoImageMismatchMsg=void 0,t.isSimilarMedia=function(e,t){return null==D(e,t)},t.whyNotSimilarMedia=D,t.whyImageHashesNotSimilar=I;const r=i(19851),s=i(40958),n=i(22573),a=i(38639),o=i(50357),l=i(55835),u=i(31586),c=i(68708),d=i(12168),h=i(54993),f=i(73168),m=i(50213),p=i(11512),g=i(28874),y=i(65162),v=i(28544),b=i(75767),w=i(16170),S=(0,r.lazy)(()=>(0,m.mkLogger)("sync-file.AssetFileComparator"));function P(e,t,i,r=(e,t)=>[e,t]){const s=e[i],a=t[i];if((0,n.blank)(s)||(0,n.blank)(a)||(0,o.eql)(s,a))return;const[l,u]=r(s,a);return(0,o.eql)(l,u)||(0,o.eql)(s,u)||(0,o.eql)(l,a)?void 0:`Different ${String(i)}: ${s} ≠ ${a}`}function M(e){return(0,n.mapNotBlank)(e,e=>e.toLowerCase().trim().normalize())}function T(e,t){return[M(e),M(t)]}function _(e,t,i){const r=(0,b.findInequalFields)(e[i],t[i]);return null==r?void 0:`Different ${i} (${r.aKey}:${r.aValue} ≠ ${r.bKey}:${r.bValue})`}function E(e,...t){if(null==e)return t.map(e=>(0,h.toS)(e));const i=[];for(const r of t)null==e[r]&&i.push((0,h.toS)(r));return 0===i.length?void 0:i}function k(e,t){return null!=e&&null!=t&&!(0,n.blank)(e)&&!(0,n.blank)(t)&&(0,o.eql)(e,t)}function D(e,i){if(null==e&&null==i)return"both a and b are undefined";if(null==e)return"a is undefined";if(null==i)return"b is undefined";const r=E(e,"uri","width","height","mimetype");if(null!=r)return"a was missing fields: "+r.join(", ");const o=E(i,"uri","width","height","mimetype");if(null!=o)return"b was missing fields: "+o.join(", ");if(k(e.sha,i.sha))return void S().debug("whyNotSimilarMedia(): same sha: same asset",{a:e.uri,b:i.uri});if(k(e.imageDataHash,i.imageDataHash))return void S().debug("whyNotSimilarMedia(): same imageDataHash: same asset",{a:e.uri,b:i.uri});const h=(0,w.isVideoMimeType)(e.mimetype),m=(0,w.isVideoMimeType)(i.mimetype);if(h!==m)return S().tap({msg:"whyNotIsSimilar",result:t.VideoImageMismatchMsg,meta:{a:e.uri,b:i.uri,aIsVideo:h,bIsVideo:m}});if((0,a.isTrue)(e.monochrome)!==(0,a.isTrue)(i.monochrome)&&g.Settings.requireSameColorSpace.valueOrDefault)return"Greyscale ≠ color (set requireSameColorSpace to possibly group them)";const M=v.CapturedAt.fromMediaInfo(e),D=v.CapturedAt.fromMediaInfo(i);if(null==M)return"a missing capturedAt metadata";if(null==D)return"b missing capturedAt metadata";if((M.isFuzzy||D.isFuzzy)&&g.Settings.allowFuzzyDateImageHashMatches.valueOrDefault){const t=g.Settings.imageHashFuzzyDateThresholdPct.valueOrDefault/100,r=(0,p.compareHashRecords)(e,i,(0,a.isTrue)(e.monochrome)||(0,a.isTrue)(i.monochrome));if(r?.confidence>=t)return void S().info("allowFuzzyDateImageHashMatches mode: image hashes match",{a:e.uri,b:i.uri,comparison:r});if(null==I(e,i,t,t))return void S().info("allowFuzzyDateImageHashMatches mode: rotation-aware match",{a:e.uri,b:i.uri})}if(M.isFuzzy||D.isFuzzy){const t=(0,y.shortestBname)(e.basename),r=(0,y.shortestBname)(i.basename);if(!(0,n.blank)(t)&&t===r){const r=Math.max(g.Settings.imageHashFuzzyDateThresholdPct.valueOrDefault,g.Settings.imageHashThresholdPct.valueOrDefault)/100;if(null==I(e,i,r,r))return void S().info("same bname and fuzzy captured-at image hashes match",{a:e.uri,b:i.uri,bname:t})}}if(!M.overlaps(D))return`captured-at ${M.toISOStringWithPrecision()} != ${D.toISOStringWithPrecision()}`;const C=P(e,i,"make",T)??P(e,i,"model",T);if(null!=C)return C;const A=(0,l.map)((0,f.geohashDistanceMeters)(e.geohash,i.geohash),e=>(0,u.sigFigs)(e,2)),x={cameraId:_(e,i,"cameraId")??null,imageId:_(e,i,"imageId")??null,lensId:_(e,i,"lensId")??null,exposureSettings:(0,b.whyExposureSettingsNotSimilar)(e,i)??null,closeGeoHash:(0,u.gt)(A,g.Settings.gpsErrorMeters.valueOrDefault)?"geohashes are "+(0,d.fmt)(A)+"m different: too far apart":null};S().debug("whyNotSimilar()",{fields:x});const F=(0,s.compact)((0,c.values)(x));return(0,s.isNotEmpty)(F)?F.join(";"):I(e,i)}function I(e,t,i,r){if(null==e)return"a is undefined";if(null==t)return"b is undefined";const s=e.mimetype===t.mimetype;i??=(s?g.Settings.imageHashThresholdPct.valueOrDefault:g.Settings.imageHashCrossFormatThresholdPct.valueOrDefault)/100,r??=g.Settings.imageHashRotationThresholdPct.valueOrDefault/100;const n=(0,a.isTrue)(e.monochrome)||(0,a.isTrue)(t.monochrome);for(const s of[e,(0,p.hashRecord0ToHashRecord)(e)])for(const a of[t,(0,p.hashRecord0ToHashRecord)(t)]){const o=s!==e!=(a!==t),l=o?r:i,u=(0,p.compareHashRecords)(s,a,n);if(S().debug("whyImageHashesNotSimilar(): comparison",{a:e.uri,b:t.uri,monochrome:n,isRotated:o,threshold:l,ihc:u}),u.confidence>=l)return}return`image hashes do not match with confidence ≥ ${(0,u.sigFigs)(100*i,3)}%`}t.VideoImageMismatchMsg="Videos ≠ images"},84196(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFieldNames=void 0,t.getNativePathFromUriDetails=async function(e){return(0,r.toNotBlank)(e.nativePath)??await(0,n.uriToNativePath)(e.uri)};const r=i(22573),s=i(50989),n=i(45200),a=i(27248);t.AssetFileFieldNames=(0,s.strEnum)("id","assetId","isPrimary","nativePath","uri","basename",...a.MediaInfoFieldNames)},92434(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileExtSortOrder=void 0,t.dim2sort=E,t.sortScale=k,t.mtime2sort=D,t.sortAssetFilesInPlace=I,t.assetFileSortCriteriaPojo=C,t.assetFileSortFields=A,t.assetFileSortCriteria=x,t.bestExistingAssetFile=async function(e){for(const t of I(e))if(await(0,p.isNonEmptyFile)(t.nativePath)||await(0,S.uriExists)(t.uri))return M().tap({msg:"bestExistingAssetFile()",result:t,meta:{files:e.map(e=>e.uri)}});return M().tap({msg:"bestExistingAssetFile(): no existing uris",result:void 0,meta:{files:e}})};const r=i(40958),s=i(76790),n=i(22573),a=i(42659),o=i(45599),l=i(31586),u=i(68708),c=i(34666),d=i(50989),h=i(89937),f=i(4001),m=i(29882),p=i(16287),g=i(19851),y=i(50213),v=i(39056),b=i(64712),w=i(14036),S=i(45200),P=i(34238),M=(0,g.lazy)(()=>(0,y.mkLogger)("img.AssetFileSorter")),T=(0,d.strEnum)("file",h.PS_NETWORK_FILESYSTEM_SCHEME,h.PS_LOCAL_FILE_SCHEME,h.PS_LIBRARY_SCHEME),_=(0,o.defer)(()=>new b.SimpleGlobArray(v.AggregationSettings.assetVariationMimetypeSortOrder.values));function E(e){return(0,l.map2Numeric)(e?.width,e?.height,(e,t)=>k(e*t))}function k(e){if((0,l.gt0)(e))return Math.floor(Math.log2(e)/Math.log2(v.AggregationSettings.assetVariationResolutionTolerance.valueOrDefault))}function D(e){return Math.round(e/(5*a.minuteMs))}function I(e){return(0,s.sortByInPlace)(e,x).reverse()}function C(e){const t=P.URI.parse(e.uri);if((0,n.blank)(t?.scheme)||(0,n.blank)(t?.path))return void M().warn("assetFileSortCriteriaPojo(): skipping (invalid URI)",{uri_scheme:t?.scheme,uri_path:t?.path,af:e,parsedURI:t});const i=E(e);if(null==i)return void M().warn("assetFileSortCriteriaPojo(): skipping (invalid resolution)",{resolution:i,af:e,parsedURI:t});const r=T.indexOf(t.scheme);if(null==r)return void M().warn("assetFileSortCriteriaPojo(): skipping (invalid URI scheme)",{uri_scheme:t.scheme,af:e,parsedURI:t});const s=e.mtime??0,a=(0,m.parsePosixPath)(t.path),o={resolution:i,isBrowserSupported:(0,w.isSupportedByCurrentBrowserExt)(a.ext),mimetype:-(_().indexOf(e.mimetype)??_().length),schemeIdx:r,metadataDate:e.metadataDate??0,capturedAtPrecisionMs:-(e.capturedAtPrecisionMs??0),isEditOrUpdate:/edit|update/i.test(a.base),isCover:/cover/i.test(a.base),fileSize:e.fileSize,sha:e.sha??"",uri:c.CmpReverseFlag+e.uri,count:-Math.abs((0,f.copySuffixCountFromName)(a.name)??0),mtime:D(s),basename:c.CmpReverseFlag+a.base,parentBasename:c.CmpReverseFlag+(0,m.parentBasename)(e.nativePath??t.path)};return M().tap({msg:"assetFileSortCriteriaPojo()",result:(0,u.toReqValued)(o)})}function A(){return(0,r.uniq)([...v.AggregationSettings.assetVariationSortCriteria.values,"uri"])}function x(e){const t=C(e);if(null==t)return;const i=[];for(const e of A())i.push(t[e]);return i}t.FileExtSortOrder=(0,o.defer)(()=>{const e=_();return(0,s.sortBy)((0,s.sort)((0,w.AssetFileExts)()),t=>e.indexOf((0,w.extMimetype)(t)))})},27248(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MediaInfoFieldNames=void 0;const r=i(50989);t.MediaInfoFieldNames=(0,r.strEnum)("nativePath","uri","basename","mtime","fileSize","mimetype","capturedAtLocal","capturedAtZone","capturedAtPrecisionMs","capturedAtSrc","capturedAtSrcDetail","capturedAtZoneSrc","width","height","rotation","imageDataHash","sha","metadataDate","rating","geohash","make","model","lensId","cameraId","imageId","durationMs","fps","aperture","focalLength","iso","shutterSpeed","monochrome","pHash","rHash","wHash","pHash0","rHash0","wHash0")},85527(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MediaInfoFactory=void 0,t.readMediaInfo_=async function(e){return f.for(e).asMediaInfo_()},t.hashRecordAsync=async function(e){return(0,n.awaitFields)((0,s.pick)(e,...c.ImageHashTypes.values))},t.imageHashFieldsAsync=async function(e){return(0,n.awaitFields)((0,s.pick)(e,"mimetype","width","height","rotation","monochrome",...c.ImageHashTypes.values))};const r=i(45599),s=i(68708),n=i(27313),a=i(50213),o=i(88561),l=i(95696),u=i(17217),c=i(32319),d=i(53244),h=i(40538);class f{f;static#w=new o.FileCache({name:"MediaInfoFactory",clearOnFileChange:!0});#R;static for(e){return this.#w.getOrSet((0,u.toNativePath_)(e),()=>new f(l.PosixFile.for(e)))}constructor(e){this.f=e,this.#R=(0,a.mkLogger)("sync-file.MediaInfoFactory("+this.f.nativePath+")")}async pick(...e){const t={};for(const i of e)t[i]=await this[i];return t}asMediaInfo_=(0,r.defer)(async()=>{if(null==await this.f.stat_())throw new Error("Failed to stat file: "+this.f.nativePath);const[e,t,i,r]=await Promise.all([this.fileStatFields_(),d.ImageHashes.for(this.f).assetHashes_(),this.mediaInfoFromTags_(),this.sha]);return{nativePath:this.nativePath,uri:await this.uri,basename:this.basename,...e,sha:r,...i,...t}});fileStatFields_=(0,r.defer)(async()=>{const e=await this.f.stat_();return{fileSize:e.size,mtime:Math.floor(await this.f.thisOrSidecarMaxMtimeMs()??e.mtimeMs)}});mediaInfoFromTags_=(0,r.defer)(async()=>{try{const e=await(0,h.readTags)(this.f);if(null==e)throw new Error("Failed to read tags");if(null==e.capturedAt)throw new Error("Failed to read capturedAt");const t=e.capturedAt.toCapturedAtFields();return null==t?this.#R.throw("Failed to render assetFileFields from capturedAt",{capturedAt:e.capturedAt}):{...(0,s.omit)(t,"capturedAtRaw"),...e.exposureSettings,...e.dimensions,...(0,s.pick)(e,"mimetype","rotation","imageDataHash","metadataDate","make","model","rating","cameraId","imageId","lensId","geohash","durationMs","fps")}}catch(e){return this.#R.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 imageDataHash(){return this.mediaInfoFromTags_().then(e=>e.imageDataHash)}get metadataDate(){return this.mediaInfoFromTags_().then(e=>e.metadataDate??this.mtime)}get rating(){return this.mediaInfoFromTags_().then(e=>e.rating)}get geohash(){return this.mediaInfoFromTags_().then(e=>e.geohash)}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_=(0,r.defer)(()=>d.ImageHashes.for(this.f).assetHashes_());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)}}t.MediaInfoFactory=f},74800(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyIsMediaInfoStale=async function(e,t,i){if(e.forceSync)return"forceSync";const o=[];if((0,n.gt0)(t.id)||o.push("id"),(0,n.gt0)(t.assetId)||o.push("assetId"),(0,r.blank)(t.uri)&&o.push("uri"),(0,r.blank)(t.basename)&&o.push("basename"),null==t.fileSize&&o.push("fileSize"),null==t.mtime&&o.push("mtime"),(0,r.blank)(t.mimetype)&&o.push("mimetype"),(0,n.gt0)(t.width)||o.push("width"),(0,n.gt0)(t.height)||o.push("height"),(0,r.blank)(t.sha)&&o.push("sha"),(0,n.gt0)(t.capturedAtLocal)||o.push("capturedAtLocal"),o.length>0)return"missing fields: "+o.join(", ");{const e=await i.fileSize;if(!(0,n.isEquivalentNumber)(t.fileSize,e,a.Settings.fileSizeEpsilon.valueOrDefault))return"file size changed since last sync: "+(0,s.stringify)({prior:t.fileSize,current:e,fileSizeEpsilon:a.Settings.fileSizeEpsilon.valueOrDefault})}{const e=await i.mtime;if(!(0,n.isEquivalentNumber)(t.mtime,e,a.Settings.mtimeMsEpsilon.valueOrDefault))return"file mtime changed since last sync: "+(0,s.stringify)({prior:t.mtime,current:e,mtimeMsEpsilon:a.Settings.mtimeMsEpsilon.valueOrDefault})}};const r=i(22573),s=i(98553),n=i(31586),a=i(28874)},73568(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbortError=void 0,t.isAbortError=function(e){return e instanceof i||String(e).includes("AbortError")};class i extends Error{name="AbortError"}t.AbortError=i},76740(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Abortable=void 0;const r=i(45599),s=i(56409),n=i(73568);t.Abortable=class{_aborted=!1;_abortReason;#L;#N=(0,r.defer)(()=>new s.Latch);abort(e){this._aborted||(this._aborted=!0,this._abortReason=e,this.#N().reject(new n.AbortError(e)).catch(()=>{}))}throwIfAborted_(e){if(!0===e?.aborted||this.aborted){const t=e?.reason??this._abortReason??"(no reason given)";throw new n.AbortError(t)}}get aborted(){return this._aborted}get reason(){return this._abortReason}abortPromise_(){return this.#N().promise}awaitOrAbort(e){return this.throwIfAborted_(),Promise.race([e,this.#N().promise])}setAbortTimeout(e,t){this.clearAbortTimeout(),this.#L=setTimeout(()=>this.abort(t),e).unref()}clearAbortTimeout(){null!=this.#L&&clearTimeout(this.#L),this.#L=void 0}observeRejections(e){e.catch(e=>this.abort(e.message))}observeResolutions(e,t){e.then(()=>this.abort(t))}}},22911(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0;const s=r(i(87997)),n=r(i(57975)),a=i(40958),o=i(22573),l=i(45599),u=i(26905),c=i(55835),d=i(31586),h=i(20214),f=i(57153),m=i(85556),p=i(32639),g=i(50213),y=i(70025),v=i(46596),b=i(95937),w="TIMEOUT",S=(0,l.defer)(()=>(0,g.mkLogger)("async.Deferred"));class P{name;static observe(e){return new P(".observe()").observe(e)}static async*toAsyncIterable(e,t){const i=(0,a.compact)([...e]).reverse(),r=(0,d.gt0)(t)?new P(w).setTimeout(t):void 0;for(null!=r&&i.push(r);;){for(let e=i.length-1;e>=0;e--){const r=i[e];if(r.isSettled){if(r.name===w)return void S().warn("toAsyncIterable(): timeout",{timeoutMs:t,pending:i.map(e=>e.name)});i.splice(e,1),yield r.value}}if(i.every(e=>e.name===w))break;try{await Promise.race(i)}catch{}}r?.clearTimeout()}static#j=0;static resolve(e,t){return new P(".resolved()",t).resolve(e)}id;payload;serialIds;startedAt=Date.now();observeStartedAt;#B;#z=f.PromiseStates.pending;#V;promise;#H;#U;#W;#q;#$;#G;#K;#J;constructor(e,t){this.name=e,this.id=P.#j++,this.promise=new Promise((e,t)=>{this.#H=e,this.#U=t}),this.payload=t?.payload,this.serialIds=t?.serialIds??[],this.#G=t?.timer,this.#K=t?.timerName,this.#J=t?.fileSize}get logger(){return this.#$??(0,g.mkLogger)("async.Deferred("+this.name+")")}eql(e){return e instanceof P&&e.id===this.id}toLogJSON(){return{name:this.name,state:this.#z,value:this.value,serialIds:(0,o.toNotBlank)(this.serialIds),payload:this.payload,elapsedMs:this.elapsedMs,settledMs:this.settledMs}}[n.default.inspect.custom](){return this.toLogJSON()}get settledAt(){return this.#B}get elapsedMs(){return(this.#B??Date.now())-this.startedAt}get timerName(){return this.#K??this.name}get[Symbol.toStringTag](){return"async.Deferred("+this.name+")"}#Y(e,t){if(null!=this.observeStartedAt)throw new v.InvalidStateError("observe() called multiple times");this.observeStartedAt=this.startedAt=Date.now();try{const i=(0,p.isFunction)(e)?e():e;(0,h.isPromise)(i)?i.then(e=>this.maybeResolve(e)).catch(e=>{t?(this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)):this.maybeReject(e)}):this.maybeResolve(i)}catch(e){t?(this.logger.warn("observeQuietly.reject()",e),this.maybeResolve(void 0)):this.maybeReject(e)}return this}observeQuietly(e){return this.#Y(e,!0)}observe(e){return this.#Y(e,!1)}clearTimeout(){return null!=this.#q&&(s.default.clearTimeout(this.#q),this.#q=void 0,!0)}setTimeout(e){this.clearTimeout();const t=new m.TimeoutError("Timeout "+this.name);return(0,d.gt0)(e)&&(this.#q=s.default.setTimeout(()=>{this.isPending&&(this.reject(t),(0,b.onTimeout)())},Math.ceil(e)),this.#q.unref()),this}get state(){return this.#z}get isPending(){return this.#z===f.PromiseStates.pending}get isObserved(){return null!=this.observeStartedAt}get value(){return this.isResolved?this.#V:void 0}get error(){return this.#W}get isSettled(){return this.#z!==f.PromiseStates.pending}get isResolved(){return this.#z===f.PromiseStates.resolved}get isRejected(){return this.#z===f.PromiseStates.rejected}get settledMs(){return null==this.#B?void 0:this.#B-this.startedAt}resolve(e){return this.#Z(()=>{this.#z=f.PromiseStates.resolved,this.#V=e,this.#H(e)})}maybeResolve(e){return this.isPending?this.resolve(e):this}reject(e){const t=!0===(0,y.isIgnorableError)(e)||!0===(0,y.isDoNotSendError)(e);this.logger.log(t?"info":"warn",".reject()",e);const i=(0,u.asError)(e);return this.#Z(()=>{this.#W=i,this.#z=f.PromiseStates.rejected,this.#U(i)})}maybeReject(e){return this.isPending?this.reject(e):this}finally(e){return this.promise.finally(e).catch(()=>{}),this}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(t=>e(t))}#Z(e){if(this.#z===f.PromiseStates.pending){(0,c.map)(this.#q,s.default.clearTimeout),this.#B=Date.now();const t=this.#B-this.startedAt;this.#G?.push(this.timerName,t,this.#J),e(),this.isResolved&&t>5e3&&this.logger.info("Completed in "+t+"ms")}else this.logger.warn("settled multiple times (already "+this.state+")",{value:this.#V});return this}}t.Deferred=P},27395(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endEndables=t.DefaultEndTimeoutMs=void 0,t.addEndable=function(e,t){if(!f.EndableRanks.includes(e))throw new Error("internal error: invalid rank "+e);return y.add(e,t),t},t.endAll=function(...e){return Promise.all(e.map(e=>v(e)))},t.end=v,t.endAllEndables=async function(){return(0,m.setEnding)(!0),Promise.all((0,s.compact)(y.valuesFlat()).map(e=>v(e)))},t.endablesStats=function(){const e={};for(const t of f.EndableRanks.values){const i=y.get(t)??[];e[t]=i.map(e=>({name:e.name,ended:e.ended}))}return e};const r=i(19851),s=i(40958),n=i(42659),a=i(45599),o=i(23838),l=i(13538),u=i(50213),c=i(7282),d=i(97352),h=i(77740),f=i(25764),m=i(99331),p=i(73614),g=(0,a.defer)(()=>(0,u.mkLogger)("async.Endable")),y=new o.MultiMap;async function v(e,i){const r=await e;if(null==r||!0===r?.ended)return;const s=(0,c.isTest)()&&(0,h.getDevEnvFlag)("PS_SINGLE_SPEC_TESTS")?500:(0,d.firstGt0)(i,r.endTimeoutMs,t.DefaultEndTimeoutMs);g().trace(r.name+" ending...",{timeoutMs:s});try{await(0,l.thenOrTimeoutError)(r.end(),s,(0,c.isTest)())}catch(e){try{g().warn(r.name+".end() failed",e)}catch{}}}function b(){y.filterInPlace((e,t)=>!0!==t.ended),g().debug("vacuumEndables()",y.entriesArray().map(([e,t])=>[e,t.map(e=>e.name)]))}(0,p.setUnrefInterval)(()=>b(),10*n.minuteMs),t.DefaultEndTimeoutMs=5*n.secondMs,t.endEndables=(0,r.lazy)(async()=>{const e=(0,c.isSingleSpecTests)()?500:void 0;g().debug("endEndables()",{isTest:(0,c.isTest)(),isSingleSpecTests:(0,c.isSingleSpecTests)()}),(0,c.isTest)()||(0,m.setEnding)(!0),b();for(const t of f.EndableRanks.values){const i=y.get(t)??[];(0,s.isNotEmpty)(i)&&(g().debug("endEndables(): ending "+t),await Promise.allSettled(i.map(t=>v(t,e))))}})},78406(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableInterval=void 0;const r=i(87997),s=i(55835),n=i(31586),a=i(68708),o=i(25764),l=i(38836),u=i(99331);class c extends l.EndableWrapper{opts;#G;#X;#Q=!1;constructor(e){super(e.name,()=>this.#ee(),e.rank??o.EndableRanks.first,e.endTimeoutMs),this.opts=e,null!=e.onEnd&&this.onEnds.push(e.onEnd),this._setIntervalMs(this.opts.intervalMs,this.opts.initialDelayMs,!0)}#ee(){(0,s.map)(this.#G,r.clearInterval),this.#G=void 0,(0,s.map)(this.#X,r.clearTimeout),this.#X=void 0}hasTimer(){return null!=this.#G}hasTimeout(){return null!=this.#X}get timingOpts(){return(0,a.pick)(this.opts,"intervalMs","initialDelayMs")}#te=()=>{(0,u.ending)()||this.ended||this.opts.callback()};get#ie(){return!(0,u.ending)()&&!this.ended}pauseInterval(){this.#Q||(this.#Q=!0,this.#ee())}resumeInterval(){this.#Q&&(this.#Q=!1,this.#re())}setIntervalMs=e=>this._setIntervalMs(e);_setIntervalMs(e,t,i=!1){return!((0,u.ending)()||this.ended||(e=(0,n.toInt)(e)??0,t=(0,n.toInt)(t)??0,(0,n.gt0)(e)||(t=0),!i&&this.opts.intervalMs===e&&(this.opts.initialDelayMs??0)===t||(this.opts.intervalMs=e,this.opts.initialDelayMs=t,this.#ee(),this.#Q||((0,n.gt0)(this.opts.initialDelayMs)?(this.#X=(0,r.setTimeout)(()=>{this.#ie&&(this.#te(),this.#re())},this.opts.initialDelayMs),!0===this.opts.unref&&this.#X.unref()):this.#re()),0)))}#re(){this.#ie&&(0,n.gt0)(this.opts.intervalMs)&&(this.#G=(0,r.setInterval)(this.#te,this.opts.intervalMs),!0===this.opts.unref&&this.#G.unref())}}t.EndableInterval=c},25764(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableRanks=void 0;const r=i(50989);t.EndableRanks=(0,r.strEnum)("first","stats","service","predb","db","postdb","logger","logtail","last")},38836(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EndableWrapper=void 0;const r=i(45599),s=i(56409),n=i(13538),a=i(61848),o=i(50213),l=i(27395),u=i(25764),c=i(99331);t.EndableWrapper=class{endTimeoutMs;#se;logger;#ne=new a.TypedEventEmitterImpl;onEnds=[];#ae=(0,r.defer)(()=>new s.Latch);#oe=!1;#le=!1;constructor(e,t,i=u.EndableRanks.first,r){this.endTimeoutMs=r,this.setName(e),null!=t&&this.onEnds.push(t),(0,l.addEndable)(i,this)}setName(e){this.#se=e,this.logger=(0,o.mkLogger)(e)}get name(){return this.#se}get endStarted(){return this.#oe}get endEnded(){return this.#le}get ended(){return this.endStarted}on=this.#ne.on.bind(this.#ne);off=this.#ne.off.bind(this.#ne);listenerCount=this.#ne.listenerCount.bind(this.#ne);end=(0,r.defer)(async()=>{this.#oe=!0,await this.#ne.emit("end"),this.logger.abortable.abort((0,c.ending)()?"service ending":"onEnd()");for(const e of this.onEnds)try{await(0,n.thenOrTimeoutError)(e(),this.endTimeoutMs??l.DefaultEndTimeoutMs)}catch(e){this.logger.warn("onEnd() error",e)}this.#ae.prior()?.resolve(),this.#ne.clear(),this.#le=!0});awaitEnd(){return this.#ae()}awaitOrAbort(e){return this.logger.awaitOrAbort(e)}get aborted(){return this.logger.abortable.aborted}}},99331(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ending=function(){return s},t.setEnding=function(e){s=(0,r.isTest)()?e:e||s};const r=i(7282);let s=!1},45608(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.exitOnStdStream=t.onFatalHandlers=void 0,t.getExitStatus=function(){return w},t.ensureExit=async function(e){(0,y.ending)()||await P(e)},t.exit=P;const s=r(i(1708)),n=i(22573),a=i(45599),o=i(98553),l=i(37975),u=i(50213),c=i(23560),d=i(71567),h=i(57159),f=i(57902),m=i(39951),p=i(28874),g=i(27395),y=i(99331),v=i(56038),b=(0,a.defer)(()=>(0,u.mkLogger)((0,l.magenta)("Exit")));let w;t.onFatalHandlers=[];const S=(0,a.defer)(()=>{p.Settings.emitTimingsOnExit.valueOrDefault&&((0,c.isInfoService)()?console.dir(v.PromiseTimer.instance().report()):(0,d.stdoutWrite)((0,o.stringify)(v.PromiseTimer.instance())))});async function P(e){w??=e.status,(0,m.sdNotifyStopping)(),b().log(0===e.status?f.LogLevels.debug:f.LogLevels.warn,"exit()",{...e,ending:(0,y.ending)()});const i=(0,y.ending)();(0,y.setEnding)(!0),S();const r=(0,h.toWrappedError)(e.error,{message:e.reason,errno:e.status});if(0!==r.errno||!0===r.fatal||0!==e.status){const i=(0,n.toNotBlank)(e?.reason)??r.toString();for(const e of t.onFatalHandlers)await e(i)}i||(await(0,g.endEndables)(),s.default.exit(e.status))}t.exitOnStdStream=(0,a.defer)(()=>{for(const e of["stdin","stdout","stderr"])for(const t of["close","error","disconnect","end"])s.default[e].on(t,i=>{P({reason:`${e}:${t}`,status:0,error:i})})})},46596(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidStateError=void 0,t.isInvalidStateError=function(e){return e instanceof i||String(e).includes("InvalidStateError")};class i extends Error{name="InvalidStateError"}t.InvalidStateError=i},5916(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazyAsync=function({later:e,desc:t,ttlMs:i,timeoutMs:r}){return new d(e,t,i,r)};const r=i(45599),s=i(50357),n=i(31586),a=i(70978),o=i(62344),l=i(50213),u=i(22911),c=(0,r.defer)(()=>(0,l.mkLogger)("async.LazyAsync"));class d extends o.ExtensibleFunction{later;desc;ttlMs;timeoutMs;#o;#ue=0;#ce=0;#de=0;#he;#fe;#me=[];constructor(e,t,i,r){super(),this.later=e,this.desc=t,this.ttlMs=i,this.timeoutMs=r}_call(){return this.isStale()?this.#M(this.later()):this.#he}async#pe(e){try{const t=await e,i=this.#fe;if(this.#he!==e)return;if(this.#fe=t,this.#ue++,!(0,s.eql)(i,t))for(const e of this.#me)await(e.onChange?.(t))}catch(t){if(this.#he===e){this.#ce++;const e=(0,a.toError)(t);if(c().warn(this.desc+": onSetResult failed",{error:e}),null!=e)for(const t of this.#me)t.onError?.(e)}}finally{this.#he===e&&this.#de++}}#M(e){this.#o=performance.now();const t=this.#he=e instanceof u.Deferred?e:new u.Deferred(this.toString()).observe(e);return(0,n.gt0)(this.timeoutMs)&&t.setTimeout(this.timeoutMs),this.#pe(t),t}clear(){this.#de=0,this.#ue=0,this.#ce=0,this.#fe=void 0,this.#o=void 0,this.#he=void 0}set(e,t){const i=this.#M(u.Deferred.resolve(e));return null!=t&&(this.#o=performance.now()+(t-(this.ttlMs??0))),i}refresh(){return this.#M(this.later())}ttl(){return this.ttlMs}setTTL(e){this.ttlMs=(0,n.gt0)(e)?e:void 0}watchLater(e){this.#me.push(e)}prior(){return this.isStale()?void 0:this.#he}lastValue(){return this.#fe}syncValue(){const e=this.lastValue();return this._call(),e}settledCount(){return this.#de}resolvedCount(){return this.#ue}rejectedCount(){return this.#ce}isStale(){return null==this.#o||(0,n.gt0)(this.ttlMs)&&performance.now()-this.#o>this.ttlMs}lastSetAgoMs(){return null==this.#o?void 0:performance.now()-this.#o}elapsedMs(){return this.#he?.settledMs??this.#he?.elapsedMs}toString(){return this.desc??"[LazyAsync]"}toJSON(){return this.toString()}}},56519(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTryAllTimeoutMs=void 0,t.someOrTimeout=async function(e,t){return Promise.all(e.map(e=>(0,d.thenOrTimeoutError)((0,h.tol)(e),t.timeoutMs).catch(e=>e)))},t.timeOrTimeout=async function(e,t){return Promise.all(Object.entries(e).map(([e,i])=>(0,b.time)({name:e,p:i,post:void 0,timeoutMs:t?.timeoutMs}).catch(e=>e)))},t.thenCompact=w,t.thenCollectBatched=async function(e,t,i){const r=[];for(const s of(0,p.batches)((0,f.toA)(await e),t)){const e=await w(s);r.push(...await w(i(e)))}return r},t.resolvedWithin=function(e,t){return Promise.race([e.then(()=>!0),(0,o.delay)(t).then(()=>!1)]).catch(()=>!1)},t.resolved=S,t.rejected=async function(e){return!await S(e)},t.thenDefined=async function(e){return null!=await e},t.allSerial=async function(e){const t=[];for(const i of(0,r.compact)(e)){const e=await i();null!=e&&t.push(e)}return t},t.awaitAll=async function(e){for(const t of(0,f.toA)(e))null!=t&&await t},t.awaitSettled=async function(e){for(const t of(0,f.toA)(e))try{null!=t&&await t}catch{}},t.thenFlatten=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;if(null!=e)if(Array.isArray(e))for(const i of e){const e=await i;null!=e&&t.push(e)}else t.push(e)}return t},t.thenUniq=async function(e){const t=[];for(const i of(0,f.toA)(await e)){const e=await i;null!=e&&t.push(e)}return(0,r.uniq)(t)},t.asyncFind=async function(e,t){for(const i of e)if(await t(i))return i},t.thenCollectSerial=P,t.mapAsyncSerial=async function(e){return(await P(e)).map(e=>e[0])},t.thenCollectParallel=M,t.mapAsync=async function({iter:e,f:t,maxConcurrent:i,timeoutMs:r}){return(await M({iter:e,f:t,maxConcurrent:i,timeoutMs:r})).filter(e=>null!=e[0]&&!(e[0]instanceof Error)).map(e=>e[0])},t.filterAsync=async function({arr:e,f:t,maxConcurrent:i,timeoutMs:r}){return(await M({iter:e,f:t,maxConcurrent:i,timeoutMs:r})).filter(([e])=>(0,n.isTrue)(e)).map(([,e])=>e)},t.partitionAsync=async function(e,t){const i=await M({iter:e,f:t});return[i.filter(([e])=>(0,n.isTrue)(e)).map(([,e])=>e),i.filter(([e])=>(0,n.isFalse)(e)).map(([,e])=>e)]},t.tryAsync=async function(e){try{return await e()}catch{return}},t.tryAll=async function(e,i=e=>console.error(e),r=t.DefaultTryAllTimeoutMs){for(const t of e)try{await(0,d.thenOrTimeout)(t,r)}catch(e){i((0,m.toError)(e))}},t.thenFinally=async function(e,t=()=>{},i=()=>{}){let r,s=null;try{r=await((0,l.isFunction)(e)?e():e)}catch(e){s=(0,m.toError)(e);try{await t(e)}catch{}}try{await i(s??r)}catch{}if(null!=s)throw s;return r},t.thenNot=async function(e,t=!0){if(null==e)return t;const i=await e;return null==i?t:!(0,n.isTrue)(i)},t.thenAnd=async function(e,t){return null!=e&&(0,n.isTrue)(await e)?t():void 0},t.thenOrElse=async function(e,t){return await e??t()},t.first=async function(e,t){if(null!=e){let i=-1;for(const r of e){i++;try{if(null==r)continue;const e=await t(r,i);if(null!=e)return e}catch{}}}},t.firstDefinedPromise=async function(e,t=y.identity){for(const i of e){const e=await i();if(null!=e){const i=await t(e);if(null!=i)return i}}},t.firstResolvedDefinedPromise=async function(e,t){for(const i of e)try{const e=await i();if(null!=e)return e}catch(e){t((0,m.toError)(e))}},t.firstTruePromise=async function(e,...t){for(const i of t)try{const t=await i();if(null!=t&&!0===await e(t))return t}catch(e){}},t.sortByAsync=async function({iter:e,f:t}){const i=(await M({iter:e,f:t})).filter(e=>null!=e[0]&&!(e[0]instanceof Error));return(0,s.sortBy)(i,e=>e[0]).map(e=>e[1])},t.awaitValues=async function(e){const t=Object.keys(e);return await Promise.all(t.map(async t=>{const i=e[t];e[t]=await i})),e};const r=i(40958),s=i(76790),n=i(38639),a=i(42659),o=i(41400),l=i(32639),u=i(41801),c=i(31586),d=i(13538),h=i(42279),f=i(59455),m=i(70978),p=i(48884),g=i(50213),y=i(88158),v=i(15674),b=i(56038);async function w(e){if(null==e)return[];const t=(0,r.compact)(await e);return(0,r.isEmpty)(t)?[]:(0,r.compact)(await Promise.all(t))}async function S(e){try{return await e,!0}catch(e){return!1}}async function P({name:e,arr:t,f:i,timeoutMs:s}){const n=[];for(const a of(0,r.compact)(await t))try{const e=await((0,c.gt0)(s)?(0,d.thenOrTimeoutError)(i(a),s):i(a));null!=e&&n.push([e,a])}catch(t){(0,g.mkLogger)(e).warn("failed to apply",{ea:a,error:t})}return n}async function M({iter:e,f:t,maxConcurrent:i=(0,v.maxCpus)(),timeoutMs:r}){if(!(0,c.gt0)(i))throw new Error(`maxConcurrency must be a positive integer, got: ${i}`);if("function"!=typeof t)throw new TypeError("fn must be a function, got: "+typeof t);const s=[],n=new Set;let a=-1;for await(const o of(0,u.iterate)(e)){for(a++;n.size>=i;)await Promise.race(n);const e=s[a]=(0,d.thenOrTimeoutError)(t(o),r).catch(e=>e).then(e=>[e,o]);n.add(e),e.finally(()=>n.delete(e))}return Promise.all(s)}t.DefaultTryAllTimeoutMs=30*a.secondMs},56038(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseTimer=t.MinMs=void 0,t.isPromiseTimer=function(e){return e instanceof T},t.mkElapsed=function(e){return T.instance().mkElapsed((0,p.mkLogger)(e))},t.time=_,t.timeSync=function({name:e,t}){const i=performance.now(),r=t();return E({name:e,elapsedMs:(0,y.roundMs)(performance.now()-i)}),r},t.pushTime=E,t.timeStatsWithPrefix=function(e){return T.instance().statsWithPrefix(e)},t.timeStatsWithName=function(e){return T.instance().statsWithName(e)},t.timedLazy=function({name:e,thunk:t,ttlMs:i,meta:s}){return(0,r.lazy)(async()=>_({name:(0,c.tot)(e),p:t,meta:s}),i)};const r=i(19851),s=i(76790),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(13538),c=i(42279),d=i(70978),h=i(32639),f=i(22454),m=i(14121),p=i(50213),g=i(7282),y=i(3685),v=i(34102),b=i(82647),w=i(42686),S=i(25764),P=i(38836),M=i(73614);t.MinMs=15;class T{static fromJSON(e){const t=new T(e?.errors,e?.times);return null!=e?.durationEstimators&&t.loadDurationEstimators(e.durationEstimators),t}static instance=(0,r.lazy)(()=>{const e=new T;return new P.EndableWrapper("PromiseTimer",()=>{const t=(0,p.mkLogger)("async.PromiseTimer");(0,l.mapCompactObj)(e.report(),e=>t.info("timings:",e)),e.hasErrors()&&t.info("error counts:",e.errorCounts())},S.EndableRanks.stats),(0,g.isTest)()&&(0,v.ee)().on("clearCache",()=>e.clear()),e});#ge;#ye;#ve;constructor(e,t){this.#ge=e??new f.CountingSet,this.#ye=t??new Map,this.#ve=new Map}clear(){this.#ge.clear(),this.#ye.clear(),this.#ve.clear()}async time(e){const{name:t,p:i,post:r,timeoutMs:s,meta:a}=e,l=performance.now(),c=(0,o.clamp)(10*n.secondMs,n.minuteMs,Math.round(this.#ye.get(t)?.p98??(s??n.minuteMs)/4)),f=(0,M.setUnrefTimeout)(()=>{(0,p.mkLogger)("time("+t+")").info("unsettled",{...a,elapsedMs:(0,y.roundMs)(performance.now()-l),timeoutMs:s,expectedMs:c})},c);try{const e=await i,n=await(0,u.thenOrTimeoutError)((0,h.isFunction)(e)?e():e,s),a=(0,y.roundMs)(performance.now()-l);return r?.(n,a),this.push(t,a),n}catch(e){throw this.#ge.incr(t),r?.((0,d.toError)(e),(0,y.roundMs)(performance.now()-l)),e}finally{clearTimeout(f)}}get entriesBySumDesc(){return(0,s.sortBy)([...this.#ye.entries()],([,e])=>-e.sum)}statsWithName(e){return this.#ye.get(e)?.stats()}statsWithPrefix(e){const t=this.entriesBySumDesc.filter(([t])=>t.startsWith(e)),i=t.reduce((e,t)=>b.Average.merge(t[1],e),new b.Average),r=t.map(([e,t])=>[e,t.stats()]);return(0,l.fromEntries)([["merged",i.stats()],...r])}mkElapsed(e){return new m.Elapsed(e,(e,t)=>this.push(e,t))}push(e,i,r){i<t.MinMs||(i=(0,y.roundMs)(i),null!=r&&r>0?(0,a.getOrSet)(this.#ve,e,()=>new w.DurationEstimator).push(r,i):(0,a.getOrSet)(this.#ye,e,()=>new b.Average).push(i))}estimate(e,t,i="p50"){if(null!=t&&t>0){const r=this.#ve.get(e);if(null!=r)return r.estimate(t,i)}return this.#ye.get(e)?.p(i)}getDurationEstimator(e){return this.#ve.get(e)}get totalDurationEstimatorSampleCount(){let e=0;for(const t of this.#ve.values())e+=t.sampleCount;return e}getDurationEstimators(){return this.#ve}loadDurationEstimators(e){const t=e instanceof Map?e.entries():Object.entries(e??{});for(const[e,i]of t){const t=i instanceof w.DurationEstimator?i:w.DurationEstimator.fromJSON(i);if(null==t)continue;const r=this.#ve.get(e);null!=r?r.merge(t):this.#ve.set(e,t)}}pushError(e){this.#ge.incr(e)}weightedAvg(e){return this.#ye.get(e)?.sampleEma}hasErrors(){return this.#ge.size>0}errorCounts(){return(0,l.fromEntries)(this.#ge.top(10))}callCounts(){return[...this.#ye.entries()].reduce((e,[t,i])=>({...e,[t]:i.n}),{})}weightedAvgs(){return(0,l.compactValues)([...this.#ye.entries()].reduce((e,[t,i])=>({...e,[t]:(0,o.mapFinite)(i.sampleEma,o.round)}),{}))}toJSON(){const e={};for(const[t,i]of this.#ve)e[t]=i.toJSON();return{errors:this.#ge,times:this.#ye,durationEstimators:e}}report(){return this.entriesBySumDesc.reduce((e,[t,i])=>({...e,[t]:{...(0,l.omit)(i.stats(),"sum"),sumSec:(0,o.sigFigs)(i.sum/n.secondMs,3)}}),{})}merge(e,t){this.#ge.merge(e.#ge);const i=t??"";for(const[t,r]of e.#ye.entries())(0,a.getOrSet)(this.#ye,i+t,()=>new b.Average).merge(r);for(const[t,r]of e.#ve.entries()){const e=i+t,s=this.#ve.get(e);if(null!=s)s.merge(r);else{const t=w.DurationEstimator.fromJSON(r.toJSON());null!=t&&this.#ve.set(e,t)}}}}function _(e){return T.instance().time(e)}function E({name:e,elapsedMs:t}){T.instance().push(e,t)}t.PromiseTimer=T},42638(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PermissivePromises=t.Promises=t.PopDelayMs=void 0,t.toName=function(e){return e?.name??(0,o.toS)(e)},t.withBoundedConcurrency=async function({name:e,laters:t,maxConcurrent:i}){return S.for({name:e,maxConcurrency:()=>i}).enqueueAll(e,t)};const r=i(40958),s=i(74310),n=i(45599),a=i(31586),o=i(54993),l=i(22454),u=i(61848),c=i(82647),d=i(28874),h=i(92322),f=i(14854),m=i(73328),p=i(69385),g=i(15674),y=i(73568),v=i(22911),b=i(38836);t.PopDelayMs=7;class w{d;l;constructor(e,t){this.d=e,this.l=t}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,t){return this.d.then(e,t)}}class S extends b.EndableWrapper{ee=new u.TypedEventEmitterImpl;#be;#we;#Se;#Pe=new c.Average;#Me=new c.Average;lastWorkTs=0;settleMsAvg=new c.Average;#de=0;#Te;lastRunNames=new s.BoundedList(16);static for({name:e,maxConcurrency:t,sortByDesc:i=e=>e.id,lowWaterMark:r,highWaterMark:s}){return new S(e,t,i,r,s)}constructor(e,t,i=e=>e.id,r,s){super(e),this.#be=t,this.#Se=r,this.#we=s,this.#Te=new h.SortedSet(e=>i(e.d))}nuke(){const e=this.#Te.toA();this.#Te.clear();for(const t of e)t.d.reject(new y.AbortError("Promises.nuke() called"))}deletePending(e){const t=[];for(const i of this.#Te)i.notStarted()&&e(i.d)&&t.push(i);for(const e of t)this.#Te.delete(e),e.d.reject(new y.AbortError("Task deleted by producer"));return t.length>0&&this.#_e(),t.length}get maxConcurrency(){return Math.floor((0,a.clamp)(1,(0,g.maxCpus)(),this.#be?.()??(0,g.maxCpus)()))}get highWaterMark(){return this.#we?.()??d.Settings.taskListCap.valueOrDefault}get lowWaterMark(){return this.#Se?.()??Math.floor(this.highWaterMark/2)}enqueueCapacity(e){if(null!=e){let t=0;for(const i of this.#Te)i.d.serialIds.includes(e)&&t++;return Math.max(0,this.lowWaterMark-t)}return Math.max(0,this.highWaterMark-this.#Te.length)}runCapacity(){return Math.max(0,this.maxConcurrency-this.runningCount())}#_e(){this.#Pe.push(this.runningCount()),this.#Me.push(this.notStartedCount()),this.#Te.length<=this.lowWaterMark&&this.ee.emitSyncRateLimited("lowWaterMark"),0===this.#Te.length&&this.ee.emitSync("drain")}get settledCount(){return this.#de}get notStartedLengthAvg(){return this.#Me}get runningLengthAvg(){return this.#Pe}runningJobNames(){const e=[];for(const t of this.#Te)t.isRunning()&&e.push(t.d.name);return e}runningJobDetails(){const e=[];for(const t of this.#Te)t.isRunning()&&e.push({name:t.d.name,startedAt:t.d.startedAt,elapsedMs:t.d.elapsedMs});return e}stats(){return{maxConcurrency:this.maxConcurrency,capacity:this.enqueueCapacity(),lastWorkMsAgo:performance.now()-this.lastWorkTs,freeSlots:this.availableConcurrency(),unsettledCount:this.unsettledCount(),runningJobNames:this.runningJobNames(),runningJobDetails:this.runningJobDetails(),notStartedJobNamesLimit10:this.notStartedJobNames(10),totalWorkCount:this.#de,notStartedLengthAvg:this.#Me.stats(),runningLengthAvg:this.#Pe.stats()}}enqueueDeferred(e,t){this.#Te.add(new w(e,t)),this.#_e(),this.maybePopPendingWork()}enqueue({name:e,l:t,payload:i,serialIds:r}){const s=new v.Deferred(e,{payload:i,serialIds:r});return this.#Te.add(new w(s,t)),this.#_e(),this.maybePopPendingWork(),s}enqueueAll(e,t){const i=[];for(const r of t){const t=new v.Deferred(e);this.#Te.add(new w(t,r)),i.push(t.promise)}return this.#_e(),this.maybePopPendingWork(),Promise.all(i)}serial(e,t,i){return this.enqueue({name:e,l:t,serialIds:[e],payload:i})}run(e,t,i){const r=new w(new v.Deferred(e,{payload:i}),t);return this.#Te.add(r),this.#_e(),this.#Ee(r)}get runningJobs(){return this.#Te.filter(e=>e.isRunning())}get runningSerialIds(){const e=new Set;for(const t of this.runningJobs)for(const i of t.d.serialIds??[])e.add(i);return e}#Ee(e){const t=this.lastWorkTs=performance.now();return e.notStarted()&&(e.d.observe(e.l).finally(()=>{this.#Te.delete(e),this.#_e(),this.#de++,this.settleMsAvg.push(performance.now()-t),this.maybePopPendingWork()}),this.lastRunNames.push(e.d.name)),this.#_e(),this.maybePopPendingWork(),e}maybePopPendingWork=()=>setTimeout(()=>this.#ke(),1);onPaused=(0,n.defer)(async()=>{await(0,p.resolveOnResume)(),this.maybePopPendingWork(),this.#_e(),this.onPaused.reset()});onTooBusy=(0,n.defer)(async()=>{await(0,f.resolveOnNotBusy)(),this.maybePopPendingWork(),this.#_e(),this.onTooBusy.reset()});#ke(){if((0,p.isPaused)())return void this.onPaused();if((0,f.isTooBusy)())return void this.onTooBusy();const e=this.maxConcurrency;let t=this.runningCount();if(!(0,m.doNotRun)()&&t<e&&this.hasSomeNotStartedJobs()){const i=this.runningSerialIds;for(const r of this.#Te)if(!r.started()&&!r.d.serialIds.some(e=>i.has(e))){this.#Ee(r);for(const e of r.d.serialIds)i.add(e);if(t++,t>=e)break}}}isTaskRunning(e){return this.#Te.some(t=>t.d.name===e)}maybeRun(e,t){return this.availableConcurrency()>0&&!this.isTaskRunning(e)?this.run(e,t):void 0}runningCount(){return(0,r.count)(this.#Te,e=>e.isRunning())}hasSomeRunningJobs(){for(const e of this.#Te)if(e.isRunning())return!0;return!1}hasSomeNotStartedJobs(){for(const e of this.#Te)if(e.notStarted())return!0;return!1}notStartedCount(){return(0,r.count)(this.#Te,e=>e.notStarted())}unsettledCount(){return(0,r.count)(this.#Te,e=>!e.isSettled())}get size(){return this.unsettledCount()}hasPending(){for(const e of this.#Te)if(!e.isSettled())return!0;return!1}isIdle(){return 0===this.#Te.length}availableConcurrency(){return Math.max(0,this.maxConcurrency-this.runningCount())}isMaxBusy(){return this.runningCount()>=this.maxConcurrency}notStartedJobNames(e){const t=[];for(const i of this.#Te)if(i.notStarted()&&(t.push(i.d.name),(0,a.gte)(t.length,e)))break;return t}get deferreds(){return this.#Te.map(e=>e.d)}enqueuedWithNameCount(e){return(0,r.count)(this.#Te,t=>t.d.name===e&&!t.isSettled())}pendingWithName(e){return this.#Te.filter(t=>t.d.name===e&&!t.isSettled()).map(e=>e.d)}pendingPayloadsWithName(e){return this.pendingWithName(e).filter(e=>null!=e.payload).map(e=>e.payload)}get pendingPromises(){return this.deferreds.map(e=>e.promise)}async awaitSettled(){await Promise.allSettled(this.pendingPromises)}async awaitDrain(){return this.isIdle()?void 0:this.ee.waitOnce("drain")}async awaitLowWaterMark(){return this.#Te.length<=this.lowWaterMark?void 0:this.ee.waitOnce("lowWaterMark")}async awaitAll(){await Promise.all(this.pendingPromises)}countByName(){const e=new l.CountingSet;for(const t of this.#Te)t.isSettled()||e.incr(t.d.name);return e}async awaitAllByName(e){await Promise.all(this.deferreds.filter(t=>t.name===e).map(e=>e.promise))}}t.Promises=S,t.PermissivePromises={enqueueAll:(e,t)=>Promise.all(t.map(e=>e()))}},85970(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serialized=function(e){return new s(e)};const r=i(62344);class s extends r.ExtensibleFunction{fn;#De;#Ie;#Ce;constructor(e){super(),this.fn=e}_call(...e){return null==this.#De?this.#Ae(e):(null!=this.#Ie||(this.#Ce=e,this.#Ie=this.#xe()),this.#Ie)}async#xe(){try{await this.#De}catch{}const e=this.#Ce;return this.#Ie=void 0,this.#Ce=void 0,this.#Ae(e)}#Ae(e){return this.#De=(async()=>{try{return await this.fn(...e)}finally{this.#De=void 0}})(),this.#De}ifIdle(...e){return this.isIdle()?this(...e):void 0}isIdle(){return null==this.#De&&null==this.#Ie}}},4867(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timeoutStacks=void 0,t.thenOrTimeoutError=async function({p:e,timeoutMs:t,halt:i}){let o=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally(()=>o=!1),(0,a.gt0)(t)?(0,n.delay)(t).then(()=>{if(o)throw new l.TimeoutError}):void 0,i?.abortPromise_().then(()=>{if(o)throw new u.AbortError})]))},t.thenOrTimeout=async function({p:e,timeoutMs:t,halt:i}){let l=!0;return Promise.race((0,r.compact)([(0,s.asPromise)(e).finally(()=>l=!1),(0,a.gt0)(t)?(0,n.delay)(t).then(()=>o.Timeout):void 0,i?.abortPromise_().then(()=>{if(l)throw new u.AbortError})]))};const r=i(40958),s=i(34546),n=i(41400),a=i(31586),o=i(83104),l=i(85556),u=i(73568);t.timeoutStacks=[]},8141(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.computeSizeBasedTimeout=function({sizeBytes:e,minTimeoutMs:t=12e4,bytesPerSecond:i=1048576}){if(!(0,r.gt0)(e))return t;const s=Math.ceil(e/i*1e3*4);return Math.max(t,s)};const r=i(31586)},95937(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setTimeoutHandler=function(e){i=e},t.onTimeout=function({soft:e}={}){i(e)};let i=e=>null},73614(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=function(e,t,...i){return(0,r.setTimeout)(e,Math.round(t),...i).unref()},t.setUnrefInterval=function(e,t,...i){return(0,r.setInterval)(e,Math.round(t),...i).unref()};const r=i(87997)},85296(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.trailingThrottle=function(e){return new l(e.fn,e.minDelayMs)};const s=r(i(87997)),n=i(31586),a=i(62344),o=i(85970);class l extends a.ExtensibleFunction{#Fe;#Oe;#Re=0;#Le;#Ce=void 0;constructor(e,t){super(),this.#Oe=t,this.#Fe=(0,o.serialized)(async(...t)=>(this.#Re=performance.now(),e(...t)))}get applying(){return!this.#Fe.isIdle()}#Ne=async()=>{const e=this.#Oe-(performance.now()-this.#Re);if(e>0)return void(this.#Le=s.default.setTimeout(this.#Ne,Math.ceil(e)+1));const t=this.#Ce;if(this.#Ce=void 0,null!=t&&!this.applying)try{await this.#Fe(...t)}catch{}this.#Le=void 0};_call(...e){if(!(0,n.gt0)(this.#Oe))return this.#Fe(...e);const t=performance.now()-this.#Re;if(t>this.#Oe&&!this.applying&&null==this.#Le)return this.#Fe(...e);this.#Ce=e,this.#Le??=s.default.setTimeout(this.#Ne,Math.max(1,1+this.#Oe-t))}reset(){null!=this.#Le&&s.default.clearTimeout(this.#Le),this.#Le=void 0}minDelayMs(){return this.#Oe}}},31562(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.until=c,t.untilTrue=async function(e,t={}){return c(e,{...t,acceptable:r.isTrue,timeoutResult:!1})};const r=i(38639),s=i(42659),n=i(41400),a=i(32639),o=i(31586),l=i(45255),u=i(95937);async function c(e,{timeoutMs:t,intervalMs:i,acceptable:r,timeoutResult:c,unref:d}={}){let h=!1;const f=null==t?void 0:t+performance.now();let m=1;for(;null==f||performance.now()<f;){const c=performance.now(),f=await e();if(null!=f&&((0,a.isFunction)(r)?r(f):!1!==f))return f;{const e=performance.now()-c;null!=t&&e>t/2&&!h&&(h=!0,(0,u.onTimeout)({soft:!0}));const r=i??(0,o.clamp)(10*m,l.ShortCommandTimeoutMs,(t??s.minuteMs)/5);await(0,n.delay)(r,d),m++}}return h||(0,u.onTimeout)({soft:!1}),c}},9727(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sanitizedEnv=void 0,t.psenv=function(){return(0,y.sortedKeys)((0,c.filter)(n.default.env,e=>D(e)))},t.childProcEnvSettings=F,t.spawnOptions=function(e){const t=e??{};return{...(0,c.omit)(t,"forceCLocale","forWorker"),env:R({overrides:t.env,forceCLocale:t.forceCLocale,forWorker:t.forWorker}),detached:!1,shell:!1}},t.childEnv=R;const s=i(76760),n=r(i(1708)),a=i(22573),o=i(45599),l=i(41400),u=i(55835),c=i(68708),d=i(48884),h=i(36638),f=i(19851),m=i(19043),p=i(50213),g=i(7282),y=i(88158),v=i(34580),b=i(59958),w=i(34102),S=i(8103),P=i(66184),M=i(45969),T=i(43334),_=i(28874),E=i(69385),k=i(3790);function D(e){return I().has(e)||e.startsWith("LC_")||e.startsWith("PS_")}const I=(0,o.defer)(()=>{const e=new h.CaseInsensitiveSet;for(const t of(0,c.values)(_.Settings)){for(const i of t.names)e.add(i);for(const i of t.keys)e.add(i)}return e.add("NODE_ENV"),e.add(b.UV_THREADPOOL_SIZE),e.add("TZ"),e.add(b.ELECTRON_RUN_AS_NODE),e});(0,l.later)(()=>{function e(){t.sanitizedEnv.unset()}(0,w.ee)().on("clearCache",e),(0,w.ee)().on("settingsChanged",e);for(const t of(0,_.allSettings)())t.watchLater(e)});const C=["HOME","LANG","USER"],A=["APPDATA","HOME","HOMEDRIVE","LOCALAPPDATA","SYSTEMDRIVE","SYSTEMROOT","TEMP"],x=(0,f.lazy)(()=>{const e=(0,c.pick)(n.default.env,...T.isPosix?C:A,...v.DO_NOT_TRACK_ENV_KEYS);return e.PATH=(0,S.pathDirectories)().join(s.delimiter),e});function F(e){const t={NODE_ENV:(0,g.nodeEnv)(),NO_COLOR:"1",PS_LOG_STDOUT:"0"};if(t[b.PS_IS_CHILD_PROCESS]="1",t[b.PS_IS_DOCKER]=(0,M.isDocker)()?"1":"0",(0,T.isElectron)()){t[b.ELECTRON_RUN_AS_NODE]="1";const e=_.Settings.projectDir.value;(0,a.notBlank)(e)&&_.Settings.projectDir.addToEnv(t,e)}for(const i of(0,_.persistedSettings)())i.addToChildProcessEnv(t,e);return t}t.sanitizedEnv=(0,f.lazy)(()=>(0,c.filter)(n.default.env,e=>D(e)||!(0,k.isSensitiveEnvKey)(e)));let O=!1;function R({overrides:e,forceCLocale:i=!0,forWorker:r=!1}={}){const s=(0,c.compactValues)({...(0,t.sanitizedEnv)(),...x(),...i?(0,m.childProcLocale)():{},...F(r),...e??{}});(0,E.isPaused)()!==_.Settings.startPaused.defaultValue?_.Settings.startPaused.addToEnv(s,(0,E.isPaused)()):_.Settings.startPaused.deleteFromEnv(s),(0,g.isTest)()&&((0,u.map)(n.default.env.PS_CONFIG_DIR,e=>s.PS_CONFIG_DIR=e),_.Settings.libraryDir.addToEnv(s));for(const e of(0,_.allSettings)())e.propagateToChildren||e.deleteFromEnv(s);if((0,P.isLogged)("debug")&&!O){O=!0;const e=(0,p.mkLogger)("child.ChildEnv"),t=(0,c.entries)(s).map(([e,t])=>[e,(0,k.isSensitiveEnvKey)(e)?"(hidden)":t]),[i,r]=(0,d.partition)(t,([e])=>D(e));e.debug("PS env:",(0,c.fromEntries)(i)),e.debug("non PS env:",(0,c.fromEntries)(r))}return s}},84777(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AddPidAfterMs=t.ReniceAfterMs=void 0,t.endProcess=O,t.spawn=function(e,t,i,r,n){const a=(0,A.spawnOptions)(r);return x().debug("spawn()",{command:e,args:t,maxAgeMs:i}),R(s.default.spawn(e,t,a),e,t,i,n)},t.execFile=L,t.stdoutResult_=N,t.stdout_=async function(e,t,i){const r=await(0,M.thenOrTimeoutError)({p:N(e,t,i),timeoutMs:i.timeoutMs});return x().tap({level:"trace",msg:"stdout_()",result:(0,m.trimLastNewline)(r.result),meta:{cmd:e,args:t,opts:i,result:r}})};const s=r(i(31421)),n=r(i(1708)),a=i(19851),o=i(40958),l=i(22573),u=i(42659),c=i(98553),d=i(56409),h=i(31586),f=i(68708),m=i(51926),p=i(50213),g=i(7282),y=i(88158),v=i(79089),b=i(3685),w=i(45255),S=i(22911),P=i(56038),M=i(4867),T=i(73614),_=i(70025),E=i(57159),k=i(66184),D=i(45643),I=i(95402),C=i(21027),A=i(9727),x=(0,a.lazy)(()=>(0,p.mkLogger)("child.ChildProcess"));function F(e){return(0,f.pick)(e,"pid","killed","connected","exitCode","signalCode","spawnfile","spawnargs")}async function O(e,t=30*u.secondMs){if(null==e)return!1;x().debug("endProcess()",F(e));const i=e.pid;if(null==i||i<=0)return x().warn("endProcess(): asked to end invalid pid",F(e)),!1;if(i===n.default.pid)return x().warn("endProcess(): asked to end MY pid",F(e)),!1;if(i===n.default.ppid)return x().warn("endProcess(): asked to end my parent pid",F(e)),!1;(0,C.closeStreams)(e);{const t=e.kill();x().debug("endProcess("+i+")",{killResult:t,childGotSigterm:e.killed}),!t&&(0,D.pidExists)(i)&&await(0,I.killPid)(i).catch(e=>{x().warn("endProcess(): kill("+i+",false) failed: "+e)})}(0,y.Try)(()=>e.unref());const r=(0,g.isSingleSpecTests)()?500:t;if(await(0,D.waitForPidExit)(i,r))return x().debug("endProcess(): exitted",F(e)),!0;{I.Pids.instance()?.onKill(i);const t=e.kill("SIGKILL");x().warn("endProcess("+i+") had to resort to SIGKILL",{killResult:t}),!t&&(0,D.pidExists)(i)&&await(0,I.killPid)(i,!0).catch(e=>{x().warn("endProcess(): kill("+i+",true) failed: "+e)})}return(0,D.waitForPidExit)(i,5e3)}function R(e,i,r,s=0,a){const o=new Date,l=[];return(0,v.niceable)(i,r)&&l.push((0,T.setUnrefTimeout)(()=>{(0,h.gt0)(e.pid)&&(0,v.renice)(e.pid)},(0,t.ReniceAfterMs)())),(0,h.gt)(s,u.secondMs)&&l.push((0,T.setUnrefTimeout)(()=>{(0,h.gt0)(e.pid)&&O(e)},s-250)),l.push((0,T.setUnrefTimeout)(()=>{if((0,h.gt0)(e.pid))return(0,I.addPid)({pid:e.pid,cmd:i,timeoutMs:a??s,ppid:n.default.pid},o)},(0,t.AddPidAfterMs)())),e.on("exit",()=>l.forEach(clearTimeout)),e}function L(e,t,i,r){const n=(0,A.spawnOptions)(r);return(0,k.isLogged)("trace",x().context)?x().debug("execFile()",{command:e,args:t,timeoutMs:i,opts:n}):x().debug("execFile()",{command:e,args:t,timeoutMs:i}),R(s.default.execFile(e,t,n),e,t,i)}async function N(e,t,i){const r=performance.now(),s=i.quiet??!1,a=i.ignoreStderr??!1,u=i.ignoreExitCode??!1,m=L(e,t,i.timeoutMs,(0,f.omit)(i,"timeout","quiet","ignoreStderr","ignoreExitCode","timerName","onStdoutChunk")),p=i.isIgnorableError??_.isIgnorableError,g=m.pid;if(null!=g){const t=(0,I.addPid)({pid:g,ppid:n.default.pid,cmd:e,timeoutMs:i.timeoutMs},new Date);null!=t&&t.catch(()=>{})}try{if(!0===i.disconnect){try{m.disconnect?.()}catch{}return{result:"",pid:m.pid}}const n=(0,c.stringify)({pid:g,cmd:e,args:t});let f=0;const y=[],v=[],T=[],k=new S.Deferred(n);m.on("error",e=>T.push(e)),m.on("exit",e=>{(0,h.isNumber)(e)&&k.isPending&&k.resolve(e)}),m.on("close",e=>{(0,h.isNumber)(e)&&k.isPending&&k.resolve(e)});const D=new d.Latch;null==m.stdout?D.resolve():(m.stdout.on("error",e=>T.push(e)),m.stdout.on("data",r=>{if(y.push(r),f+=r.length,null!=i.onStdoutChunk){const e="string"==typeof r?r:r.toString("utf8");try{i.onStdoutChunk(e)}catch(e){x().warn("stdoutResult_() onStdoutChunk threw",{error:e})}}(0,h.gt0)(i.maxBytes)&&(0,h.gt)(f,i.maxBytes)&&(x().warn("stdoutResult_() maxBytes exceeded",{bytesRead:f,maxBytes:i.maxBytes,cmd:e,args:t}),m.kill("SIGINT"),i.halt?.abort("maxBytes exceeded"),k.resolve(1))}),m.stdout.on("end",()=>D.resolve()));const I=new d.Latch;null==m.stderr||a?I.resolve():(m.stderr?.on("error",e=>T.push(e)),m.stderr?.on("data",e=>v.push(e)),m.stderr?.on("end",()=>I.resolve())),x().debug("stdoutResult_() invoked and waiting for completion...",{name:n}),await(0,C.disposeStream)(m.stdin),await(0,M.thenOrTimeoutError)({p:k.promise,timeoutMs:i.timeoutMs,halt:i.halt}),x().debug("stdoutResult_() exitCode settled...",{name:n,exitCode:k.value,stdout:D.state(),stderr:I.state()}),await(0,M.thenOrTimeoutError)({p:D.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt}),await(0,M.thenOrTimeoutError)({p:I.promise,timeoutMs:w.ShortCommandTimeoutMs,halt:i.halt});const A=v.join("");(0,l.notBlank)(A)&&T.push(new Error(A));const F=null!=i.cleanError?T.map(e=>new Error(i.cleanError(e.message))):T;if(!s&&(0,o.isNotEmpty)(F)){const t=F.every(e=>!0===p(e)||(0,_.isCorruptMediaError)(e));x().log(t?"info":"warn",e+" resulted in errors:",F)}const O=F.filter(e=>!0!==p(e));if(O.length>0)throw 1===O.length?O[0]:new E.WrappedError("Failed to run "+e+" "+t.join(" "),{causes:O});if(!u&&0!==k.value&&(0,o.isEmpty)(F))throw new Error(e+": exit code "+k.value);const R=y.join("");return null!=i.timerName&&(0,P.pushTime)({name:i.timerName,elapsedMs:(0,b.roundMs)(performance.now()-r)}),{result:R,pid:g,code:k.value,stderr:A}}catch(e){throw null!=i.timerName&&(0,P.pushTime)({name:i.timerName,elapsedMs:(0,b.roundMs)(performance.now()-r)}),x().warn("stdoutResult_() failed",e),await O(m),e}}t.ReniceAfterMs=(0,a.lazy)(()=>15*u.secondMs),t.AddPidAfterMs=(0,a.lazy)(()=>30*u.secondMs)},3790(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSensitiveEnvKey=c,t.addSensitiveSettings=function(){for(const e of(0,o.allSettings)())!e.isSensitive()&&e.envKeys().some(c)&&(l().warn("Forcing "+e.name+" to be sensitive."),e.opts.sensitive=!0)};const r=i(22573),s=i(41400),n=i(19851),a=i(50213),o=i(28874),l=(0,n.lazy)(()=>(0,a.mkLogger)("SensitiveEnvKey"));(0,s.later)(()=>o.Settings.sensitiveEnvRegExp.watchLater(()=>u.unset()));const u=(0,n.lazy)(()=>{try{return new RegExp(o.Settings.sensitiveEnvRegExp.valueOrDefault,"i")}catch(e){return console.error(`Invalid setting: ${o.Settings.sensitiveEnvRegExp.toEnvLine()}: ${e}. Using default.`),new RegExp(o.Settings.sensitiveEnvRegExp.defaultValue,"i")}});function c(e){return!(0,r.blank)(e)&&(d().has(e)||u().test(e))}const d=(0,n.lazy)(()=>new Set((0,o.allSettings)().filter(e=>e.isSensitive()).flatMap(e=>e.envKeys())))},46199(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.stableBasename=x,t.ciSafePathFromUri=async function(e){return F(await(0,C.uriToNativePath)((0,m.toS)(e)))},t.ciSafePath=F,t.unCiSafePath=function(e){const t=e.replace(/^\$examples\b/,(0,p.examples)().nativePath).replace(/^\$library\b/,(0,M.originalsDir)()??I.Settings.libraryDir.valueOrDefault).replace(/^\$cache\b/,(0,P.cacheDir_)()).replace(/^SCAN_PATH\b/,(0,f.toA)(I.Settings.scanPaths.valueOrDefault)[0]??"").replace(/(\w)\/$/,"$1");return D.isWin?t.replace(/\//g,o.sep):t},t.ciSafeUriToFile=R,t.unCiSafeUri=async function(e){return(await(0,C.nativePathToUri)(await R(e))).uri},t.ciSafeUri=function(e){const t=(0,A.toURI)(e);if(t.authority===g.ExamplesDirVolSHA||t.scheme===h.PS_EXAMPLES_SCHEME||(0,_.posixPathIncludesPathElement)(t.path,"examples"))return t.with({scheme:h.PS_EXAMPLES_SCHEME,authority:null,path:O(t.path.replace(/.*\/examples/,""))}).toString();if("http"===t.scheme)return t.with({authority:"localhost"}).toString();if((0,h.isPhotoStructureScheme)(t.scheme)){let e;for(const i of(0,f.toA)(I.Settings.scanPaths.valueOrDefault)){const r=E.PosixFile.for(i).base,s=t.path.match(new RegExp(`^.*/${(0,b.escapeRegExp)(r)}/(.*)$`));if(null!=s){e=s[1];break}}if(null==e){const i=t.path.match(/^.*\/sync-(tiny|small|full)-[^/]+\/(.*)$/);null!=i&&(e=i[2])}const i=null!=e?"/SCAN_PATH/"+O(e):O(t.path);return t.with({authority:(0,d.notBlank)(t.authority)?"volsha":void 0,path:i}).toString()}return t.toString()},t.sortCiSafePaths=function(e){return(0,c.sortBy)((0,f.toA)(e),e=>(0,m.toS)(e).split("/").map(e=>e.toLowerCase()))};const o=i(76760),l=a(i(53916)),u=i(40958),c=i(76790),d=i(22573),h=i(89937),f=i(59455),m=i(54993),p=i(19935),g=i(88329),y=i(31658),v=i(7282),b=i(68852),w=i(49517),S=i(84699),P=i(49776),M=i(9595),T=i(4001),_=i(29882),E=i(95696),k=i(17217),D=i(43334),I=i(28874),C=i(45200),A=i(34238);function x(e){return(0,T.stripCopySuffixFromName)(e,{aggressive:!1})+e.ext}function F(e,t){if(!(0,v.isTest)())return(0,k.toNativePath_)(e);const i=E.PosixFile.for(e),r=(0,d.blank)(i.ext),s=t?.stableBasename??!r?x(i):i.base.normalize(),n=i.sibling(s),a=i.existsSync(),o=n.isDirectorySync()||!a&&r?"/":"",u=E.PosixFile.for((0,w.repoRoot)()).join("src");if(n.isSelfOrDescendantOf(u)){let e=n.posixPathFrom(u);return e=e.replace(/^(\w+)\/dist\/\1\//,"$1/"),e=e.replace(/\.js$/,".ts"),"$src/"+e+o}for(const{desc:e,dir:t}of[{desc:"$examples",dir:(0,p.examples)()},{desc:"$library",dir:E.PosixFile.forMaybe(I.Settings.libraryDir.valueOrDefault)},{desc:"$library",dir:E.PosixFile.forMaybe((0,M.originalsDir)())},{desc:"$cache",dir:E.PosixFile.for((0,P.cacheDir_)())},{desc:"$library",dir:i.findSelfOrAncestor(e=>e.base.startsWith(S.TestLibraryDirPrefix))},...(0,f.toA)(I.Settings.scanPaths.valueOrDefault).map(e=>({desc:"SCAN_PATH",dir:E.PosixFile.forMaybe(e)})),{desc:"SCAN_PATH",dir:i.findSelfOrAncestor(e=>/^sync-(?:tiny|small|full)-/.test(e.base))}])if(null!=t&&n.isSelfOrDescendantOf(t)){const i=n.posixPathFrom(t);return l.join(e,i)+o}return i.baseWithGrandparent+o}function O(e){const t=e.split("/"),i=t.pop();if((0,d.blank)(i))return e;const r=(0,_.parsePosixPath)(i),s=(0,T.stripCopySuffixFromName)(r,{aggressive:!1});return[...t,s+r.ext].join("/").normalize()}function R(e){const t=(0,A.toURI)(e);return t.scheme===h.PS_EXAMPLES_SCHEME?(0,_.joinNativePath)([(0,y.examplesNativePath_)(),...(0,u.compactBlanks)(t.path.split("/"))]):(0,C.uriToNativePath)(e)}},69554(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI=void 0;const r=i(6858),s=i(37805),n=i(22573),a=i(45599),o=i(7282),l=i(19913),u=i(45608),c=i(44198),d=i(17181),h=i(43334),f=i(41269),m=i(80061),p=i(94361);t.CLI=class{serviceName;additionalDescription;cmd;#je=[];constructor(e,t,i=new r.Command){this.serviceName=e,this.additionalDescription=t,this.cmd=i,process.on("SIGHUP",()=>(0,u.exit)({reason:"SIGHUP",status:0})),process.on("SIGINT",()=>(0,u.exit)({reason:"SIGINT",status:0})),process.on("SIGTERM",()=>(0,u.exit)({reason:"SIGTERM",status:0}))}setup=(0,a.defer)(async()=>{(0,c.handleDeprecatedEnv)(),(0,l.setServiceName)(this.serviceName),await(0,d.setupLogger)(),(0,p.verifyUidGid)()});add(...e){return this.#je.push(...e),this}async parse(e=process.argv,t){(0,m.addHelpFooter)(this.cmd).description((0,m.cliWrap)(f.CliDesc[this.serviceName]+(0,n.mapNotBlankOr)(this.additionalDescription,e=>"\n\n"+e,()=>"")).join("\n"));for(const e of this.#je)await e.beforeParse(this.cmd);this.cmd.version((0,o.isTest)()?"1.2.3-test":(0,m.cliWrapWithFooter)((0,m.cliWrapVersion)()),"-V, --version","Output version information (spoiler: it's "+((0,o.isTest)()?"1.2.3-test)":s.version)),this.cmd.parse(e,t??{from:h.isMainElectron?"electron":"node"});const i=this.cmd.opts();if(!0!==i.help&&!0!==i.version){const e=this.cmd.opts();for(const t of this.#je)await(t.afterParse?.(e));await this.setup()}return this.cmd}}},41269(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CliDesc=void 0,t.CliDesc={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.",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",test:"Test harness. For internal use.",worker:"PhotoStructure's worker process. For internal use."}},80061(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cliWrap=u,t.cliWrapVersion=function(){return(0,a.EditionName)()+" v"+o.version},t.cliWrapWithFooter=c,t.addHelpFooter=function(e){return e.addHelpText("afterAll",c())};const r=i(1708),s=i(31586),n=i(51926),a=i(17344),o=i(37805),l=i(84542);function u(e,t){const i=t?.maxLineLen??(0,s.toInt)(r.env.maxLineLen)??r.stdout.columns??75;return(0,n.wrap)(e,{maxLineLen:i,prefix:t?.prefix??""})}function c(...e){return(0,l.joinLines)(...u([...e,"",`Copyright © 2017-${o.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/",""]))}},38790(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorArgs=void 0;const r=i(28874);t.ColorArgs={beforeParse:e=>e.option("--color","Enable ASCII terminal colors. This overrides NO_COLOR, if set.").option("--no-color","Disable ASCII terminal colors."),afterParse:e=>{"boolean"==typeof e.color&&(r.Settings.logColor.cliValue=e.color,process.env.PS_LOG_COLOR=String(e.color))}}},83210(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isDaemon=function(e){return(0,a.isTrue)(s.default.env.__is_daemon)||(0,a.isTrue)(e?.daemon)||!(0,n.blank)(e?.pidfile)};const s=r(i(1708)),n=i(22573),a=i(38639)},53978(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimingArg=void 0;const r=i(28874),s=i(38639);t.TimingArg={beforeParse:e=>e.option("--timing","On exit, emit timing information to stdout."),afterParse:async e=>{(0,s.isTrue)(e.timing)&&(r.Settings.emitTimingsOnExit.value=!0)}}},94361(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyUidGid=void 0,t.whyUidGidMismatched=d;const r=i(19851),s=i(40958),n=i(55835),a=i(31586),o=i(44142),l=i(24526),u=i(45969);function c(e,t,i){const r=(0,a.toGt0)(process.env[t]);return null==r||i.includes(r)?void 0:`WARNING: ${e} is running as ${i} but $${t}=${r}`}function d(){if(!(0,u.isDocker)())return;const e=(0,s.compactBlanks)([c("user id","PUID",(0,l.userids)()),c("group id","PGID",(0,o.groupids)())]);return 0===e.length?void 0:e}t.verifyUidGid=(0,r.lazy)(()=>{(0,u.isDocker)()&&(0,n.map)(d(),e=>console.log(["",...e,"This may result in file permission issues!","See https://photostructure.com/go/puid for details.",""].join("\n")))})},47086(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorEncodings=void 0;const r=i(50989);t.ColorEncodings=(0,r.strEnum)("labhash","rgboctal")},85810(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxLabhash=t.minLabhash=t.LabBitZip=void 0,t.rgbhex2Lab=function(e){return(0,o.map)((0,f.rgbhex2triplet)(e),y)},t.rgbhex2Labhash=function(e,t=h.ModeBits){return(0,o.map)((0,f.rgbhex2triplet)(e),e=>D(y(e),t))},t.lab2rgbhex=function(e){return(0,f.rgbTriplet2hex)(v(e))},t.labhash2rgbOctal=function(e){return(0,o.map)(C(e),g)},t.lab2rgbOctal=g,t.rgb2labTriplets=function(e){return(0,s.stepRange)(0,e.length,3).map(t=>y([e[t],e[t+1],e[t+2]]))},t.rgb2labArray=function(e){const t=[],i=[],r=[];for(let s=0;s<e.length;s+=3){const n=y([e[s],e[s+1],e[s+2]]);t.push(n[0]),i.push(n[1]),r.push(n[2])}return[t,i,r]},t.rgb2lab=y,t.lab2rgb=v,t.clampLab=b,t.rgb2xyz=w,t.xyz2lab=_,t.lab2xyz=E,t.xyz2rgb=k,t.toLabhash=D,t.unlabhash=C,t.closestLab=function(e,t){return(0,n.leastBy)(e,e=>(0,d.ciede2000_delta_e)(e,t))},t.rgb2hsv=x,t.rgbhex2hsl=function(e){return F((0,f.rgbhex2triplet)(e))},t.rgb2hsl=F,t.hsl2rgb=function(e){return L(R(e))},t.hsv2hsl=O,t.hsl2hsv=R,t.hsv2rgb=L,t.xyz2oklab=N,t.oklab2oklch=j,t.xyz2oklch=function(e,t,i,r={}){return j(N(e,t,i,r))};const r=i(19851),s=i(40958),n=i(76790),a=i(49769),o=i(55835),l=i(31586),u=i(20014),c=i(75503),d=i(3048),h=i(42022),f=i(85042),m=[[.4124564,.3575761,.1804375],[.2126729,.7151522,.072175],[.0193339,.119192,.9503041]],p=[[3.2404542,-1.5371385,-.4985314],[-.969266,1.8760108,.041556],[.0556434,-.2040259,1.0572252]];function g(e){return(0,f.rgbTriplet2rgbOctal)(v(e))}function y(e){return _(w(e))}function v(e){return(0,f.clampRGB)(k(E(e)))}function b(e){return(0,t.LabBitZip)().clampValue(e)}function w(e){const t=(0,f.clampRGB)(e).map(e=>e/255).map(e=>e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92);return(0,c.matXvec)(m,t)}const S=.95047,P=1.08883,M=216/24389,T=24389/27;function _(e){const[t,i,r]=(0,c.vecXvec)(e,[1/S,1,1/P]).map(e=>e>M?Math.pow(e,1/3):(T*e+16)/116);return b([116*i-16,500*(t-i),200*(i-r)])}function E(e){const[t,i,r]=b(e),s=(t+16)/116,n=i/500+s,a=s-r/200,o=n*n*n,l=a*a*a,u=o>M?o:(116*n-16)/T,c=t>8?Math.pow(s,3):t/T;return[u*S,1*c,(l>M?l:(116*a-16)/T)*P]}function k(e){return(0,c.matXvec)(p,e).map(e=>{const t=e<0?-1:1,i=e*t;return(0,l.round)(255*t*(i<=.0031308?12.92*i:1.055*Math.pow(i,1/2.4)-.055))})}function D(e,i=h.ModeBits){return(0,t.LabBitZip)().zip(e,i)}t.LabBitZip=(0,r.lazy)(()=>new u.BitZip([{min:0,max:100},{min:-79,max:90},{min:-102,max:89}]));const I=new Map;function C(e,t=h.ModeBits){return t===h.ModeBits?(0,a.getOrSet)(I,e,()=>A(e,t)):A(e,t)}function A(e,i=h.ModeBits){return(0,t.LabBitZip)().unzip(e,i)}function x(e){const[t,i,r]=(0,f.clampRGB)(e),s=Math.max(t,i,r),n=s-Math.min(t,i,r),a=n?s===t?(i-r)/n:s===i?2+(r-t)/n:4+(t-i)/n:0;return[60*(a<0?a+6:a),s?n/s*100:0,s/255*100]}function F(e){return O(x(e))}function O(e){const[t,i,r]=e,s=(200-i)*r/100;return[t,s>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,s/2]}function R(e){const[t,i,r]=e,s=i*(r<50?r:100-r)/100;return[t,s>0?2*s/(r+s)*100:0,r+s]}function L(e){const t=e[0]/360*6,i=e[1]/100,r=e[2]/100,s=Math.floor(t),n=r*(1-i),a=r*(1-(t-s)*i),o=r*(1-(1-t+s)*i),l=s%6;return(0,f.clampRGB)([255*[r,a,n,n,o,r][l],255*[o,r,r,a,n,n][l],255*[n,n,o,r,r,a][l]])}function N(e,t,i,r={}){const{fromSharp:s=!0}=r;s&&(e/=242.36985,t/=255,i/=277.65165);const n=.8189330101*e+.3618667424*t-.1288597137*i,a=.0329845436*e+.9293118715*t+.0361456387*i,o=.0482003018*e+.2643662691*t+.633851707*i,l=Math.cbrt(n),u=Math.cbrt(a),c=Math.cbrt(o);return[.2104542553*l+.793617785*u-.0040720468*c,1.9779984951*l-2.428592205*u+.4505937099*c,.0259040371*l+.7827717662*u-.808675766*c]}function j(e){const[t,i,r]=e,s=Math.hypot(i,r);let n=Math.atan2(r,i)*(180/Math.PI);return n<0&&(n+=360),[t,s,n]}t.minLabhash=(0,r.lazy)(()=>(0,t.LabBitZip)().zipMin(h.ModeBits)),t.maxLabhash=(0,r.lazy)(()=>(0,t.LabBitZip)().zipMax(h.ModeBits))},3048(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MaxCie=t.MinCie=void 0,t.cie76_delta_e=function(e,t){return Math.sqrt((t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2)},t.cie94_delta_e=function(e,t){const[i,r,n]=e,[a,o,l]=t,u=i-a,c=r-o,d=n-l,h=(0,s.sqrt)(r**2+n**2),f=h-(0,s.sqrt)(o**2+l**2),m=(0,s.sqrt)(c**2+d**2-f**2);return(0,s.sqrt)((u/1)**2+(f/(1+.045*h))**2+(m/(1+.015*h))**2)},t.diffCIECorr=function(e,i){return null==e||null==i?1:(0,r.clamp)(0,t.MaxCie,n(e,i)-t.MinCie)/t.MaxCie},t.ciede2000_delta_e=n;const r=i(31586),s=i(97352);function n(e,t){const[i,r,n]=e,a=(0,s.sqrt)(r**2+n**2),[o,l,u]=t,c=(a+(0,s.sqrt)(l**2+u**2))/2,d=.5*(1-(0,s.sqrt)(Math.pow(c,7)/(Math.pow(c,7)+Math.pow(25,7)))),h=r*(1+d),f=l*(1+d),m=(0,s.sqrt)(h*h+n*n),p=(0,s.sqrt)(f*f+u*u);let g=Math.abs(h)+Math.abs(n)===0?0:Math.atan2(n,h);g+=2*(g<0?1:0)*Math.PI;let y=Math.abs(f)+Math.abs(u)===0?0:Math.atan2(u,f);y+=2*(y<0?1:0)*Math.PI;const v=o-i,b=p-m;let w=m*p===0?0:y-g;w-=2*(w>Math.PI?1:0)*Math.PI,w+=2*(w<-Math.PI?1:0)*Math.PI;const S=2*(0,s.sqrt)(m*p)*Math.sin(w/2),P=(i+o)/2,M=(m+p)/2;let T;m*p===0?T=g+y:(T=(g+y)/2,T-=(Math.abs(g-y)>Math.PI?1:0)*Math.PI,T+=2*(T<0?1:0)*Math.PI);const _=(P-50)**2,E=1-.17*Math.cos(T-Math.PI/6)+.24*Math.cos(2*T)+.32*Math.cos(3*T+Math.PI/30)-.2*Math.cos(4*T-63*Math.PI/180),k=1+.015*_/(0,s.sqrt)(20+_),D=1+.045*M,I=1+.015*M*E,C=30*Math.PI/180*Math.exp(-1*((180/Math.PI*T-275)/25)**2),A=2*(0,s.sqrt)(Math.pow(M,7)/(Math.pow(M,7)+Math.pow(25,7))),x=-1*Math.sin(2*C)*A;return(0,s.sqrt)(Math.pow(v/(1*k),2)+Math.pow(b/(1*D),2)+Math.pow(S/(1*I),2)+x*b/(1*D)*S/(1*I))}t.MinCie=2,t.MaxCie=20},86758(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLab=function(e){return Array.isArray(e)&&3===e.length&&(0,s.within)(0,100,e[0])&&(0,s.within)(-110,110,e[1])&&(0,s.within)(-110,110,e[2])},t.labsAreGreyscale=function(e){const t=o.Settings.colorVarianceThreshold.valueOrDefault,i=new a.Average,r=new a.Average;for(const t of e){const e=(0,l.clampLab)(t);i.push(e[1]),r.push(e[2])}const s=(i.stdDev??0)+(r.stdDev??0),n=s<t;return u().tap({msg:"labsAreGreyscale()",result:n,meta:{value:s,thresh:t}})},t.calculateLabHue=function(e,t){const i=180*Math.atan2(t,e)/Math.PI;return i<0?i+360:i},t.extractValidLabPixel=function(e,t){const i=e[3*t],r=e[3*t+1],s=e[3*t+2];return{L:isNaN(i)?50:Math.max(0,Math.min(100,i)),a:isNaN(r)?0:Math.max(-100,Math.min(100,r)),b:isNaN(s)?0:Math.max(-100,Math.min(100,s))}};const r=i(19851),s=i(31586),n=i(50213),a=i(82647),o=i(28874),l=i(85810),u=(0,r.lazy)(()=>(0,n.mkLogger)("color.Lab"))},42022(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeBits=void 0,t.ModeBits=12},1971(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeCount=void 0,t.ModeCount=7},85434(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModeDataKeys=void 0,t.isModeData=function(e){return(0,r.gt0)(e.mode0)&&(0,r.gt0)(e.mode0pct)},t.pickModeData=function(e){return(0,s.pick)(e,...t.ModeDataKeys.values)},t.omitModeData=function(e){return(0,s.omit)(e,...t.ModeDataKeys.values)};const r=i(31586),s=i(68708),n=i(50989);t.ModeDataKeys=(0,n.strEnum)("mode0","mode0pct","mode1","mode1pct","mode2","mode2pct","mode3","mode3pct","mode4","mode4pct","mode5","mode5pct","mode6","mode6pct")},85042(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.normalizeRgbHex=function(e){const t=(0,a.toS)(e).trim();return o.test(t)?(0,n.ensurePrefix)(t,"#").toUpperCase():void 0},t.rgbhex2triplet=function(e){const t=(0,a.toS)(e).trim().match(o);if(null!=t)try{return[t[1],t[2],t[3]].map(e=>(0,r.clamp)(0,255,parseInt(e,16)))}catch{return}},t.rgbTriplet2hex=function(e){return"#"+l(e).map(e=>(0,s.leftPad)(Math.round(e).toString(16).toUpperCase(),2,"0")).join("")},t.rgbTriplet2rgbOctal=function(e){const t=l(e).map(e=>(0,r.clamp)(0,7,Math.floor(e/256*8)));return 100*t[0]+10*t[1]+t[2]},t.rgbOctal2rgbTriplet=function(e){return l([Math.floor(e/100),Math.floor(e%100/10),Math.floor(e%10)].map(e=>e/8*256))},t.clampRGB=l;const r=i(31586),s=i(39926),n=i(51926),a=i(54993),o=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;function l(e){return[e[0],e[1],e[2]].map(e=>(0,r.clamp)(0,255,Math.round(e)))}},76596(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateObject=f,t.toDateObject=function(e){if(f(e)&&(0,l.within)(1800,2100,e.year))return 0===e.month?{year:e.year,zone:e.zone,rawValue:e.rawValue,tzoffsetMinutes:e.tzoffsetMinutes}:0===e.day&&null!=e.month&&e.month>0?(0,l.within)(1,12,e.month)?{year:e.year,month:e.month,zone:e.zone,rawValue:e.rawValue,tzoffsetMinutes:e.tzoffsetMinutes}:void 0:null==e.month||!(0,l.within)(1,12,e.month)||null==e.day||!(0,l.within)(1,31,e.day)||null!=e.hour&&!(0,l.within)(0,23,e.hour)||null!=e.minute&&!(0,l.within)(0,59,e.minute)||null!=e.second&&!(0,l.within)(0,59,e.second)||null!=e.millisecond&&!(0,l.within)(0,999,e.millisecond)?void 0:(0,u.pick)(e,"year","month","day","hour","minute","second","millisecond","zone","rawValue","tzoffsetMinutes")},t.cmpDate=function(e,t){const i=(0,o.mapOr)(e,e=>e.getTime(),()=>0),r=(0,o.mapOr)(t,e=>e.getTime(),()=>0);return(0,c.cmp)(i,r)},t.msUntil=function(e){if(null==e)return 0;const t=e.getTime(),i=Date.now();return t<=i?0:t-i},t.closeTo=m,t.nowish=function(e,t=2500){return null!=e&&((0,a.isDate)(e)?m(e,new Date,t):Math.abs(e-Date.now())<t)},t.isRecentMs=function(e,t){return(0,l.closeTo)(Date.now(),e,t)},t.fmtMs=function(e){return p(e,r.Duration.fromMillis(Math.abs(e)).toFormat("m:ss.SSS"))},t.durationToPaddedHMS=function(e){return p(e,r.Duration.fromMillis(Math.abs(e)).toFormat("hhhh:mm:ss.SSS"))},t.durationHMS=function(e){const t=Math.abs(e);return p(e,r.Duration.fromMillis((0,l.round)(t/a.secondMs)*a.secondMs).toFormat(t<a.hourMs?"m:ss":"h:mm:ss"))},t.isoNow=function(){return(new Date).toISOString()},t.utcIsoToTs=function(e){if((0,n.blank)(e))return;const t=r.DateTime.fromISO(e,{zone:"utc"});return t.isValid?t.toMillis():void 0},t.dateObjectToDateTime=function(e,t=!1){if(null!=e)try{if(e instanceof r.DateTime)return e.isValid?e:void 0;if(null!=e.month&&null!=e.day){const i={year:e.year,month:e.month,day:e.day};null!=e.hour&&(i.hour=e.hour),null!=e.minute&&(i.minute=e.minute),null!=e.second&&(i.second=e.second),null!=e.millisecond&&(i.millisecond=e.millisecond);const s=r.DateTime.fromObject(i,{zone:e.zone});return null==s||s.isValid||h().debug("dateObjectToDateTime() invalid",{obj:e,why:s.invalidExplanation}),t||s?.isValid?s:void 0}return}catch(t){return void h().debug("dateObjectToDateTime() failed",{obj:e,error:t})}};const r=i(51168),s=i(19851),n=i(22573),a=i(42659),o=i(55835),l=i(31586),u=i(68708),c=i(34666),d=i(50213),h=(0,s.lazy)(()=>(0,d.mkLogger)("date.Date"));function f(e){return(0,u.isObject)(e)&&"number"==typeof e.year}function m(e,t,i){return null!=e&&null!=t&&Math.abs(e.getTime()-t.getTime())<=i}function p(e,t){return(e<0?"-":"")+t}},24689(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateInterval=void 0,t.isDateInterval=function(e){return e instanceof f};const r=i(77988),s=i(19851),n=i(55835),a=i(31586),o=i(54993),l=i(68852),u=i(79842),c=i(98247),d=(0,s.lazy)(()=>(0,l.concatRegexp)([/^/,/(?<start>\d{2,}[-+\dTZ:.,]+?)/i,/(?<solidus>:--|\/)/,/(?<end>\d{2}[-+\dTZ:.,]+)/,l.RegExpOptional.from(/\/(?<index>\d+)\/(?<splits>\d+)/),/$/])),h=["year","month","day","hour","minute","second","millisecond"];class f{start;middle;end;index;splits;static fromISO(e,t){const i=d().exec((0,o.toS)(e).trim()),r=i?.groups;return null==r?void 0:f.for((0,c.parseExifDateTime)(r.start,t),(0,c.parseExifDateTime)(r.end,t),(0,a.toInt)(r.index),(0,a.toInt)(r.splits))}toJSON(){return{start:this.start?.toJSON(),end:this.end?.toJSON(),index:this.index,splits:this.splits}}static fromJSON(e){return this.for((0,n.map)(e.start,e=>r.ExifDateTime.fromJSON(e)),(0,n.map)(e.end,e=>r.ExifDateTime.fromJSON(e)),e.index,e.splits)}static for(e,t,i=0,r=1){if(null==e||!e.isValid||null==t||!t.isValid)return;r=(0,a.clamp)(1,1e3,(0,a.toInt)(r,{defaultValue:1})),i=(0,a.clamp)(0,r-1,(0,a.toInt)(i,{defaultValue:0})),e.hasZone&&!t.hasZone&&null!=e.zone?t=t.setZone(e.zone)??t:!e.hasZone&&t.hasZone&&null!=t.zone&&(e=e.setZone(t.zone)??e);const s=e.toMillis(),n=(t.toMillis()-s)/(r+1)*(i+1),o=e.plus({milliseconds:n});return null==o?void 0:new f(e,o,t,i,r)}year;month;day;hour;minute;second;millisecond;constructor(e,t,i,r=0,s=1){this.start=e,this.middle=t,this.end=i,this.index=r,this.splits=s,[this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond]=h.map(r=>function({start:e,end:t,middle:i,field:r}){return null!=e[r]&&null!=t[r]?i[r]:void 0}({start:e,middle:t,end:i,field:r}))}get intervalMs(){return this.end.toMillis()-this.start.toMillis()}get precisionMs(){return Math.max((0,u.datedToPrecisionMs)(this.end),(0,u.datedToPrecisionMs)(this.start))}toDate(){return this.middle.toDate()}toMillis(){return this.middle.toMillis()}get isValid(){return!0}get zone(){return this.start.zone??this.end.zone}get hasZone(){return this.start.hasZone||this.end.hasZone}toString(e={}){const t=[this.start.toISOString({includeOffset:this.start.hasZone,...e}),this.end.toISOString({includeOffset:this.end.hasZone,...e})];return 0===this.index&&1===this.splits||t.push(this.index.toString(),this.splits.toString()),t.join("/")}toISOString(e={}){return this.toString(e)}overlaps(e){return!0===(0,u.datedOverlap)({a:this,b:e})}setZone(e,t){return new f(this.start.setZone(e,t)??this.start,this.middle.setZone(e,t)??this.middle,this.end.setZone(e,t)??this.end,this.index,this.splits)}}t.DateInterval=f},79842(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_PRECISION_MS=void 0,t.isDated=k,t.toDated=function(e){return k(e)?e:void 0},t.mapDated=function(e,t){return k(e)?t(e):void 0},t.toDate=function(e){if(null!=e)return"number"==typeof e?new Date(e):e instanceof Date?e:(0,f.maybeCall)(e,"toJSDate")??(0,f.maybeCall)(e,"toDate")},t.datedToStartTs=D,t.datedToEndTs=I,t.datedToStartDateTime=function(e){return e instanceof v.DateInterval?e.start.toDateTime():e instanceof r.ExifDate?s.DateTime.fromObject(e):C(e)},t.datedToDateTime=C,t.datedToPrecisionMs=A,t.isPrecisionMs=function(e){return null!=e&&x.includes(e)},t.isoToPrecisionMs=function(e){return(0,d.map)(R(e),A)},t.datedOverlap=function({a:e,b:t,aPrecisionMs:i,bPrecisionMs:r}){if(null==e||null==t)return!1;if(i??=A(e),r??=A(t),O(e,t,i,r))return!0;const s=(0,M.getZone)(e),n=(0,M.getZone)(t);return null==s&&null!=n&&(e=(0,S.setZone)(e,n)??e),null==n&&null!=s&&(t=(0,S.setZone)(t,s)??t),O(e,t,i,r)},t.isoToDated=R,t.datedToJson=function(e){const t="toJSON"in e?e.toJSON():void 0;return null!=t?t:e instanceof s.DateTime?{...e.toObject(),zone:e.zoneName}:(0,c.isJson)(e)?e:void 0},t.datedToOffsetMinutes=function(e){return(0,d.map)(e,e=>e instanceof r.ExifDateTime?e.tzoffsetMinutes:(0,_.isDateTime)(e)?e.offset:void 0)},t.datedToRawValue=function(e){if((0,f.isObject)(e)&&"rawValue"in e){const t=e.rawValue;if(!(0,o.blank)(t))return t}},t.datedToYMD=L,t.datedToISO=function(e,t,i){return null==e?void 0:e instanceof v.DateInterval?e.toString({includeOffset:t}):!(0,T.hasTime)(e)||(i??A(e))>=l.dayMs?L(e):(0,S.toExifDateTime)(e,(0,M.getZoneName)(e))?.toISOString({includeOffset:t})},t.datedToEXIF=function e(t){if(null==t)return;if(t instanceof v.DateInterval)return e(t.middle);const i=(0,h.isNumber)(t)?s.DateTime.fromMillis(t):C(t);return null!=i&&i.isValid?i.toFormat((0,M.hasZone)(t)?j:N):void 0};const r=i(77988),s=i(51168),n=i(40958),a=i(76790),o=i(22573),l=i(42659),u=i(45599),c=i(57702),d=i(55835),h=i(31586),f=i(68708),m=i(39926),p=i(51926),g=i(50213),y=i(76596),v=i(24689),b=i(66649),w=i(98247),S=i(21330),P=i(928),M=i(93515),T=i(21404),_=i(73389),E=(0,u.defer)(()=>(0,g.mkLogger)("date.Dated"));function k(e){return null!=e&&(e instanceof S.FuzzyDate||e instanceof r.ExifDate||e instanceof r.ExifDateTime||e instanceof Date||e instanceof v.DateInterval||(0,_.isDateTime)(e)||(0,y.isDateObject)(e))}function D(e){return null==e?void 0:e instanceof v.DateInterval?e.start.toMillis():e instanceof r.ExifDate?e.toMillis(0):(0,b.datedToMillis)(e)}function I(e){if(null!=e)return e instanceof v.DateInterval?e.end.toMillis():e instanceof r.ExifDate?e.toMillis(l.dayMs):e instanceof S.FuzzyDate?e.following().toMillis()-1:(0,h.map2Numeric)((0,b.datedToMillis)(e),A(e),(e,t)=>e+t)}function C(e){try{if(null==e||(0,p.isString)(e)||(0,h.isNumber)(e))return;return(0,_.isDateTime)(e)?e:e instanceof r.ExifDateTime||e instanceof S.FuzzyDate?e.toDateTime():e instanceof v.DateInterval?e.middle.toDateTime():e instanceof Date?s.DateTime.fromJSDate(e):(0,w.dateObjectToExifDateTime)(e)?.toDateTime()}catch(t){return void E().warn("datedToDateTime() failed",{d:e,error:t})}}function A(e){if(e instanceof v.DateInterval)return e.precisionMs;if((0,T.hasTime)(e)){if((0,h.gt0)((0,P.getMillisecond)(e)))return 0;if((0,h.gt0)((0,P.getSecond)(e)))return l.secondMs-1;if((0,h.gt0)((0,P.getMinute)(e)))return l.minuteMs-1;if((0,h.gt0)((0,P.getHour)(e)))return l.hourMs-1}return(0,h.gt0)((0,P.getDay)(e))?l.dayMs-1:(0,h.gt0)((0,P.getMonth)(e))?l.monthMs-1:l.yearMs-1}const x=[l.yearMs,l.monthMs,l.dayMs,l.hourMs,l.minuteMs,l.secondMs].map(e=>e-1);function F(e,t){const i=D(e),r=I(e);if(null!=i&&null!=r)return(0,h.gt0)(t)&&t>r-i?{start:Math.round((i+r)/2-t/2),end:Math.round((i+r)/2+t/2)}:{start:i,end:r}}function O(e,t,i,r){const[s,n]=(0,a.sortBy)([F(e,i),F(t,r)],e=>e?.start);return null!=s&&null!=n&&null!=s&&null!=n&&(s.start===n.start||s.end>=Math.min(n.start,n.end))}function R(e,t){return(0,o.blank)(e)?void 0:v.DateInterval.fromISO(e,t)??(0,w.parseExifDateTime)(e,t)??S.FuzzyDate.fromISO(e)}function L(e,t="-"){return(0,n.compact)([(0,P.getYear)(e),(0,P.getMonth)(e),(0,P.getDay)(e)]).map(e=>(0,m.pad2)(e)).join(t)}t.MAX_PRECISION_MS=x[0];const N="yyyy:MM:dd HH:mm:ss.SSS",j=N+"ZZ"},66649(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedToMillis=function(e){if(null!=e&&!(0,s.isString)(e))return(0,r.isNumber)(e)?e:e instanceof Date?e.getTime():e.toMillis?.()};const r=i(31586),s=i(81168)},4328(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTimezoneSuffixes=t.DefaultDateTimeFormats=void 0,t.DefaultDateTimeFormats=["y-M-d 'at' HH.mm.ss","y-M-d HH-mm-ss","y-MM-dd HH-mm-ss","y-MMM-d HH-mm-ss","y-MMM-dd HH-mm-ss","y-MMMM-d HH-mm-ss","y-MMMM-dd HH-mm-ss","y-MM-dd HHmmss","yMMdd_HHmmss","yMMdd-HHmmss","y_MMdd_HHmmss","MM.dd.yyyy HH:mm:ss","y-MM-dd'T'HH-mm-ss","F","FF"],t.DefaultTimezoneSuffixes=["ZZ","z"]},70488(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodeDuration=a,t.encodeDuration=function(e){return null==(0,r.toNotBlank)(e)?void 0:(0,s.fmtDuration)((0,n.isNumber)(e)?e:a(e))||void 0};const r=i(22573),s=i(6875),n=i(31586);function a(e){return(0,n.isNumber)(e)?e:(0,r.blank)(e)?void 0:(0,s.parseDuration)(e)}},98247(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnsetZone=void 0,t.concatDateTime=function(e,t){if(!(e instanceof r.ExifDate&&e.isFullDate()&&t instanceof r.ExifTime))return;const i=new r.ExifDateTime(e.year,e.month,e.day,t.hour,t.minute,t.second,t.millisecond,void 0,e.rawValue+" "+t.rawValue,t.zone,t.inferredZone);return i.isValid?i:void 0},t.parseExifDateTimeFormat=function({input:e,format:t,defaultZone:i}){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromFormat(e,t,{zone:i??r.UnsetZone,setZone:!0}),{rawValue:e,unsetMilliseconds:!0})},t.parseExifDateTimeFromRFC2822=function(e){return(0,a.blank)(e)?void 0:r.ExifDateTime.fromDateTime(s.DateTime.fromRFC2822(e,{zone:r.UnsetZone,setZone:!0}))},t.parseExifDateTime=function(e,t){return(0,a.blank)(e)?void 0:r.ExifDateTime.from(e,t)??y(e,b(),t)},t.parseExifDateTimeRe=y,t.dateObjectToExifDateTime=w;const r=i(77988);Object.defineProperty(t,"UnsetZone",{enumerable:!0,get:function(){return r.UnsetZone}});const s=i(51168),n=i(19851),a=i(22573),o=i(55835),l=i(31586),u=i(68708),c=i(54993),d=i(88158),h=i(68852),f=i(28874),m=i(98725),p=i(21404),g=i(17415);function y(e,t,i){const n=t.exec(e);if(null==n||(0,u.isEmptyObj)(n.groups))return;const{year:a,month:c,day:h,hour:m,minute:p,second:y}=(0,d.mapEntries)(n.groups,(e,t)=>(0,l.toInt)(t));if(null==a||null==c||null==h)return;if(!f.Settings.fuzzyDateParsing.valueOrDefault&&(null==m||null==p))return;const v=(0,o.map)((0,l.toFloat)(n.groups.subsec),e=>(0,l.within)(0,1,e)?Math.round(1e3*e):void 0),b=(0,g.timezoneOffsetFromRegExpMatch)(n);return w({year:a,month:c,day:h,hour:m??0,minute:p??0,second:y??0,millisecond:v,zone:(0,r.normalizeZone)(b)?.formatOffset(s.DateTime.fromObject({year:a,month:c,day:h}).toMillis(),"short")??i,rawValue:e,tzoffsetMinutes:b})}const v=/[-:_\s]?/,b=(0,n.lazy)(()=>(0,h.concatRegexp)([m.nonNumericLookbackRE,m.yearRE,v,m.monthRE,v,m.dayRE,/[T\s]/,m.hourRE,v,m.minuteRE,v,m.secondRE,m.subsecRE,/\s?/,h.RegExpOptional.from(g.TimezoneOffsetRE)]));function w(e){if(null!=e&&(0,p.hasTime)(e)){if(e instanceof r.ExifDateTime&&e.isValid)return e;try{const t=e.tzoffsetMinutes??(0,g.zoneToTzOffsetMinutes)(new Date(e.year,e.month-1,e.day).getTime(),e.zone),i=r.ExifDateTime.fromJSON({...e,tzoffsetMinutes:t,zoneName:(0,o.map)(e.zone,c.toS)});return i.isValid?i:void 0}catch{return}}}},74417(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.recent=function(e,t=5*n.secondMs){return(0,c.isRecentMs)((0,h.datedToMillis)(e),t)},t.fmtDateTime=function(e,t,i=r.DateTime.DATETIME_MED){return(0,m.mapValidDate)(e,e=>((0,s.mapNotBlank)(t,t=>e=e.setLocale(t)),e.toLocaleString(i)))},t.isoToDateTime=function(e){if((0,s.blank)(e))return;if(e.includes("/")){const t=d.DateInterval.fromISO(e)?.middle.toDateTime();if(null!=t)return t}const t=r.DateTime.fromISO(e.replace(p,(e,t)=>t),{setZone:!0});return t.isValid?t:void 0},t.shortDateTimeFormat=y,t.fmtDateShort=function(e,t="en-US"){return y(t).format((0,h.datedToMillis)(e))},t.parseJsonDateToMillis=function(e){if(null==e)return;const t=(0,u.isString)(e)?e:e.formatted;return((0,l.isObject)(e)&&(0,o.isNumber)(e.timestamp)?(0,m.toValidMillis)(e.timestamp*n.secondMs):void 0)??(0,f.parseDateTime)(t)?.toMillis()};const r=i(51168),s=i(22573),n=i(42659),a=i(49769),o=i(31586),l=i(68708),u=i(81168),c=i(76596),d=i(24689),h=i(66649),f=i(98725),m=i(88600),p=/(\.\d\d\d)\d+/,g=new Map;function y(e="en-US"){return(0,a.getOrSet)(g,e,()=>new Intl.DateTimeFormat(e,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"}))}},12959(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filestamp=function({when:e=new Date,includeMillis:t=!1}={}){return[e.getFullYear(),(0,r.pad2)(e.getMonth()+1),(0,r.pad2)(e.getDate()),"-",(0,r.pad2)(e.getHours()),(0,r.pad2)(e.getMinutes()),(0,r.pad2)(e.getSeconds()),...t?[(0,r.pad3)(e.getMilliseconds())]:[]].join("")},t.filestampUTC=function(e=new Date){return[e.getUTCFullYear(),(0,r.pad2)(e.getUTCMonth()+1),(0,r.pad2)(e.getUTCDate()),"-",(0,r.pad2)(e.getUTCHours()),(0,r.pad2)(e.getUTCMinutes()),(0,r.pad2)(e.getUTCSeconds())].join("")};const r=i(39926)},21330(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ignorableSubpaths=t.FuzzyDate=void 0,t.addIgnorableSubpath=function(e){t.ignorableSubpaths.push(e)},t.clearIgnorableSubpaths=function(){t.ignorableSubpaths.length=0},t.toExifDateTime=E,t.toFuzzyDate=k,t.sameDay=function(e,t){return(0,c.lte)(D(e,t),l.dayMs)},t.diffMillis=D,t.closeTo=function(e,t,i){return(0,u.mapOr)(D(e,t),e=>Math.abs(e)<i,()=>!1)},t.gtDated=function(e,t){if(null==e||null==t)return!1;for(const i of[w.getYear,w.getMonth,w.getDay,w.getHour,w.getMinute,w.getSecond,w.getMillisecond])if((0,c.lte)(i(e),i(t)))return!1;return!0},t.dateBetween=function(e,t,i=1,r=1){if(null==(0,y.datedToMillis)(e)||null==(0,y.datedToMillis)(t))return;const[n,a]=[e,t].map(e=>(0,y.datedToMillis)(e)).sort(),o=(a-n)/(r+1),l=(0,S.getZoneName)(e),u=l===(0,S.getZoneName)(t)?l:void 0,c=s.DateTime.fromMillis(n+o*i,{zone:u});return[e,t].some(e=>!(0,P.hasTime)(e))?k(c):c},t.setZone=function(e,t,i){const s={...(0,d.compactValues)(i),keepLocalTime:i?.keepLocalTime??!(0,S.hasZone)(e)},n=(0,r.normalizeZone)(t);return null!=e&&null!=n&&(0,P.hasTime)(e)?e instanceof p.DateInterval?e.setZone(n,s):E(e)?.setZone(n,s):void 0},t.toIsoDate=function(e){if(null==e)return;const t=[(0,w.getYear)(e),(0,w.getMonth)(e),(0,w.getDay)(e)];return(0,c.gt0)(t[0])?(0,a.compact)(t).map(h.pad2).join("-"):void 0},t.utcToZone=function(e,t){let i=(0,g.datedToDateTime)(e);if(null==i)return;const r=(0,S.getZoneName)(e);return null!=r&&"UTC"!==r||(i=i.toUTC(0,{keepLocalTime:!0})),i.setZone(t)};const r=i(77988),s=i(51168),n=i(57975),a=i(40958),o=i(22573),l=i(42659),u=i(55835),c=i(31586),d=i(68708),h=i(39926),f=i(19851),m=i(28874),p=i(24689),g=i(79842),y=i(66649),v=i(98247),b=i(98725),w=i(928),S=i(93515),P=i(21404),M=i(17415),T=i(88600);class _{year;month;day;constructor(e,t,i){this.year=e,this.month=t,this.day=i}static fromISO(e){if(!(0,o.blank)(e))return this.for(b.ISO_YMD_RE.exec(e)?.groups??b.ISO_YMD_LAX_RE.exec(e)?.groups)}static fromJSON(e){return this.for(e)}toJSON(){return(0,d.pick)(this,"year","month","day")}static for(e){const t=(0,c.toGt0)(e?.year);if(null==e||null==t||t<m.Settings.minValidYear.valueOrDefault)return;const i=e instanceof _?e:new _(t,(0,c.toGt0)(e.month),(0,c.toGt0)(e.day));return i.isValid?i:void 0}static localToday(){return k(new Date)}#Be=(0,f.lazy)(()=>(0,T.whyNotValidDate)(this.toDateTime()));get invalidExplanation(){return this.#Be()}get isValid(){return null==this.#Be()}toString(){return this.toISOString()}[n.inspect.custom](){return this.toISOString()}toISOString(){return(0,a.compact)([this.year,this.month,this.day]).map(e=>(0,h.pad2)(e)).join("-")}toLocal(){return 1e8*(1e4*this.year+100*(this.month??0)+(this.day??0))}toDateTime(){return s.DateTime.fromObject((0,d.pick)(this,"year","month","day"))}toDate(){return this.toDateTime().toJSDate()}toMillis(){return this.toDateTime().toMillis()}plus(e){const t=this.toDateTime().plus(e);return new _(t.year,null!=this.month?t.month:void 0,null!=this.day?t.day:void 0)}following(){const e=this.toDateTime(),t=null!=this.day?(0,d.pick)(e.plus({day:1}),"year","month","day"):null!=this.month?(0,d.pick)(e.plus({month:1}),"year","month"):(0,d.pick)(e.plus({year:1}),"year");return new _(t.year,t.month,t.day)}}function E(e,t){if(e instanceof r.ExifDateTime&&(null==t||e.zone===t))return e;if(null==e||!(0,P.hasTime)(e))return;const i=(0,o.mapNotBlank)(t,t=>(0,M.zoneToTzOffsetMinutes)((0,y.datedToMillis)(e),t));return null==t||null!=i?(0,u.map)((0,w.getYear)(e),r=>(0,u.map)((0,w.getMonth)(e),s=>(0,u.map)((0,w.getDay)(e),n=>(0,u.map)((0,w.getHour)(e),a=>(0,v.dateObjectToExifDateTime)({year:r,month:s,day:n,hour:a,minute:(0,w.getMinute)(e)??0,second:(0,w.getSecond)(e)??0,millisecond:(0,w.getMillisecond)(e),tzoffsetMinutes:i,rawValue:e.rawValue,zone:t}))))):void 0}function k(e){return(0,u.map)(e,e=>(0,u.map)((0,w.getYear)(e),t=>new _(t,(0,w.getMonth)(e),(0,w.getDay)(e))))}function D(e,t){const[i,r]=[e,t].map(y.datedToMillis);return null==i||null==r?void 0:i-r}t.FuzzyDate=_,t.ignorableSubpaths=[]},98725(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FuzzyDateParser=t.ISO_YMD_LAX_RE=t.ISO_YMD_RE=t.subsecRE=t.optSeps=t.seps=t.secondRE=t.minuteRE=t.hourRE=t.dayishRE=t.dayRE=t.monthishRE=t.monthRE=t.yearishRE=t.yearRE=t.nonNumericLookbackRE=void 0,t.extractDateFromPath=function(e){return D().tap({msg:"extractDateFromPath",result:x.instance().extractDateFromPath(e),meta:{path:e}})},t.parseYMD=function(e){return x.instance().parseYMD(e)},t.parseFuzzyDate=function(e){return x.instance().parse(e)},t.dateTimeBetween=function(e,t){const i=e.until(t).divideEqually(2)[0].end;return null==i?e:i},t.agoMs=function(e){return(0,d.mapNumeric)((0,S.datedToMillis)(e),e=>Date.now()-e)},t.parseDateTime=function(e,t){const i=A({input:e,defaultZone:t,descPredicate:e=>/DateTime/i.test(e)});return(0,_.isDateTime)(i)?i:(0,T.isExifDateTime)(i)?i.toDateTime():void 0},t.parseDated=A;const r=i(77988),s=i(51168),n=i(19851),a=i(40958),o=i(22573),l=i(98553),u=i(57702),c=i(49769),d=i(31586),h=i(51926),f=i(59455),m=i(48884),p=i(50213),g=i(68852),y=i(4001),v=i(28874),b=i(24689),w=i(79842),S=i(66649),P=i(98247),M=i(21330),T=i(21404),_=i(73389),E=i(16400),k=i(88600),D=(0,n.lazy)(()=>(0,p.mkLogger)("date.FuzzyDateParser"));t.nonNumericLookbackRE=/(?<!\d)/,t.yearRE=/(?<year>(?:18|19|20)\d{2})/,t.yearishRE=/(?<year>(?:18|19|20)?\d{2})/,t.monthRE=/(?<month>[0-3]\d)/,t.monthishRE=/(?<month>[0-3]?\d)/,t.dayRE=/(?<day>[1-3]\d|0[1-9])/,t.dayishRE=/(?<day>[1-3]\d|0?[1-9])/,t.hourRE=/(?<hour>1\d|2[0-3]|0\d)/,t.minuteRE=/(?<minute>[0-5]\d)/,t.secondRE=/(?<second>[0-5]\d)/,t.seps=/([-.,:_/ |])/,t.optSeps=new RegExp(t.seps.source+"?"),t.subsecRE=/(?<subsec>\.\d+)?/,t.ISO_YMD_RE=(0,g.concatRegexp)([/^/,t.yearRE,g.RegExpOptional.from(/-/,t.monthRE,g.RegExpOptional.from(/-/,t.dayRE)),/$/]),t.ISO_YMD_LAX_RE=(0,g.concatRegexp)([/^/,t.yearishRE,g.RegExpOptional.from(/-/,t.monthishRE,g.RegExpOptional.from(/-/,t.dayishRE)),/$/]);const I=new Map;function C(e,t,i){try{const r=(0,P.parseExifDateTimeFormat)({input:e,format:t,defaultZone:i});if(null!=r)return r;const n=(0,c.getOrSet)(I,t,()=>{const e=s.DateTime.fromFormatExplain(s.DateTime.now().toFormat(t),t);if(!(e.regex instanceof RegExp))return void D().warn("extractDateTime() failed to parse format",{format:t});const i=(0,h.stripPrefixSuffix)(e.regex.source,{prefix:"^",suffix:"$"});return new RegExp(i,"i")});return(0,P.parseExifDateTimeFormat)({input:n?.exec(e)?.[0],format:t,defaultZone:i})}catch(i){return void D().debug("unexpected error thrown from extractDateTime()",{input:e,format:t,error:i})}}function A({input:e,defaultZone:t,includeDate:i=!0,includeFuzzyDate:s=!0,descPredicate:n=()=>!0}){if(null==e)return;if((0,u.isJsonObject)(e)&&!(0,h.isString)(e)&&(e=(0,l.fromJsonObject)(e)),(0,w.isDated)(e))return e;const c=(0,a.uniq)((0,a.compactBlanks)((0,f.toA)(e)).map(y.stripDSC));if(0!==c.length)for(const{desc:e,f:l}of function*(e){yield{desc:"DateInterval.fromISO",f:e=>b.DateInterval.fromISO(e)},yield{desc:"parseExifDateTime",f:t=>(0,P.parseExifDateTime)(t,e.defaultZone)},yield{desc:"ExifDateTime.fromRFC2822",f:P.parseExifDateTimeFromRFC2822};for(const t of(0,a.uniq)([...(0,a.compactBlanks)(v.Settings.extraDateTimeZoneSuffixes.values),""]))for(const i of(0,a.compactBlanks)(v.Settings.extraDateTimeFormats.values)){const r=(0,o.blank)(t)?i:i+" "+t;yield{desc:`extractDateTime(${r})`,f:i=>C(i,r,(0,o.blank)(t)?e.defaultZone:void 0)}}if(!0===e.includeDate&&(yield{desc:"ExifDate.fromExifStrict",f:e=>r.ExifDate.fromExifStrict(e)}),!0===e.includeFuzzyDate)for(const e of x.instance().allParsers)yield{desc:"FuzzyDateParser "+e.source,f:t=>e.apply(t)}}({defaultZone:t,includeDate:i,includeFuzzyDate:s}))if(n(e))for(const e of c){const t=l(e);if(null!=t&&(0,k.isValidDate)(t))return t}}class x{opts;static instance=(0,n.lazy)(()=>new x);ymdParsers=[];ymParsers=[];yParsers=[];allParsers=[];constructor(e={}){this.opts=e,null==e.fuzzyDateParsing&&v.Settings.fuzzyDateParsing.watchLater(()=>this.#ze()),null==e.fuzzyYearParsing&&v.Settings.fuzzyYearParsing.watchLater(()=>this.#ze()),this.#ze()}get fuzzyDateParsing(){return this.opts.fuzzyDateParsing??v.Settings.fuzzyDateParsing.valueOrDefault}get fuzzyYearParsing(){return this.opts.fuzzyYearParsing??v.Settings.fuzzyYearParsing.valueOrDefault}parse(e,t=this.allParsers){for(const i of t){const t=i.apply(e);if(null!=t)return t}}parseYMD(e){return this.parse(e,this.ymdParsers)}parseYM(e){return this.parse(e,this.ymParsers)}parseY(e){return this.parse(e,this.yParsers)}#Ve(e){const t=new F(e);t.hasDay?this.ymdParsers.push(t):t.hasMonth?this.fuzzyDateParsing&&this.ymParsers.push(t):this.fuzzyYearParsing&&this.yParsers.push(t)}#ze(){try{this.ymdParsers.length=0,this.ymParsers.length=0,this.yParsers.length=0,this.allParsers.length=0;const e=new g.RegExpEscaped("(?<monthname>"+(0,E.monthNames)().map(g.escapeRegExp).join("|")+")"),i=new g.RegExpEscaped("\\2");this.#Ve([t.yearRE,t.seps,t.monthishRE,i,t.dayishRE]),this.#Ve([t.yearRE,t.optSeps,t.monthRE,i,t.dayRE]),this.#Ve([t.yearRE,t.optSeps,e,i,t.dayishRE]);const r=new g.RegExpEscaped(",?\\2");this.#Ve([e,t.optSeps,t.dayishRE,r,t.yearRE]),this.#Ve([t.nonNumericLookbackRE,t.dayishRE,t.optSeps,e,r,t.yearRE]),this.#Ve([/^(?<year>\d\d\d\d):(?<month> {2}|\d\d):(?<day> {2}|\d\d)( ( {2}|00):( {2}|00):( {2}|00))?$/]),this.#Ve([t.yearRE,t.seps,t.monthishRE]),this.#Ve([e,t.seps,t.yearRE]),this.#Ve([t.yearRE,t.seps,e]),this.#Ve([t.nonNumericLookbackRE,t.yearRE]),this.allParsers.push(...this.ymdParsers,...this.ymParsers,...this.yParsers)}catch(e){D().error("Failed to setup fuzzy date parsers",{error:e})}}extractDateFromPath(e){if(!v.Settings.usePathsToInferDates.valueOrDefault)return;M.ignorableSubpaths.forEach(t=>{(0,a.startsWith)(e,t)&&e.splice(0,t.length)}),e=e.filter(e=>(0,o.notBlank)(e)&&null==e.match(O));const t=[...e].reverse();for(const e of t){const t=A({input:e,includeDate:!1,includeFuzzyDate:!1})??this.parseYMD(e);if(null!=t)return t}return this.parseYMD(t.slice(1,4).join(" "))??this.parseYMD(e.slice(0,-1).join(" "))??(0,m.first)(t,e=>this.parseYM(e))??this.parseYM(e.join(" "))??(0,m.first)(t.slice(1),e=>this.parseY(e))}}t.FuzzyDateParser=x;class F{regex;constructor(e){this.regex=e instanceof RegExp?e:(0,g.concatRegexp)([...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){const t=this.regex.exec(e)?.groups;if(null!=t)return M.FuzzyDate.for({year:(0,d.toInt)(t.year),month:(0,d.toInt)(t.month)??(0,E.monthName2index)(t.monthname),day:(0,d.toInt)(t.day)})}}const O=/^((DCIM)|(DSC[_F]?|IMG[-_]|GOPRO|MOV[-_]|MVI[-_]|P_?)\d+)$/i},928(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getYear=function(e){return e instanceof Date?e.getFullYear():e?.year},t.getMonth=function(e){return e instanceof Date?e.getMonth()+1:e?.month},t.getDay=function(e){return e instanceof Date?e.getDate():e?.day},t.getHour=function(e){return e instanceof Date?e.getHours():e?.hour},t.getMinute=a,t.getSecond=o,t.getMillisecond=l,t.getCentisecond=function(e){return(0,r.map)(l(e),e=>Math.floor(e/10))},t.hasSeconds=function(e){return(0,n.hasTime)(e)&&((0,s.gt0)(a(e))||(0,s.gt0)(o(e))||(0,s.gt0)(l(e)))},t.getSecMs=function(e){return(0,r.map)(o(e),t=>{const i=l(e)??0;let r=(t+i/1e3).toString();for(t<10&&(r="0"+r),0===i&&(r+=".");r.length<6;)r+="0";return r})};const r=i(55835),s=i(31586),n=i(21404);function a(e){return e instanceof Date?e.getMinutes():e?.minute}function o(e){return e instanceof Date?e.getSeconds():e?.second}function l(e){return e instanceof Date?e.getMilliseconds():e?.millisecond}},93515(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasZone=function(e){return null!=e&&!(0,s.isNumber)(e)&&((0,a.isExifDateTime)(e)||(0,n.isDateInterval)(e)?e.hasZone:!!(0,o.isDateTime)(e)&&(null!=e.zone&&"local"!==e.zone.type&&(0,r.isZoneValid)(e.zone)))},t.getZone=l,t.getZoneName=function(e){return l(e)?.name};const r=i(77988),s=i(31586),n=i(24689),a=i(21404),o=i(73389);function l(e){if(!(null==e||e instanceof Date))return(0,o.isDateTime)(e)?!e.isValid||null==e.zone||(0,r.isZoneUnset)(e.zone)?void 0:e.zone:(0,a.isExifDateTime)(e)||(0,n.isDateInterval)(e)?(0,r.normalizeZone)(e.zone):void 0}},21404(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasTime=function(e){if(!(0,n.isObject)(e))return!1;if(e instanceof Date)return!0;const t=e;return(0,s.gt0)(t.hour)||(0,s.gt0)(t.minute)||(0,s.gt0)(t.second)||(0,s.gt0)(t.millisecond)},t.isExifDateTime=function(e){return e instanceof r.ExifDateTime};const r=i(77988),s=i(31586),n=i(68708)},73389(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDateTime=function(e){return r.DateTime.isDateTime(e)??!1};const r=i(51168)},89724(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.localToDateObject=g,t.localIsFuzzy=function(e){return null==e||e%1e6==0||e<p()},t.isoToLocal=y,t.maybeDatedToLocal=function(e){return(0,o.map)(e,w)},t.datedToLocalMinute=v,t.datedToLocalSec=b,t.datedToLocal=w,t.fmtLocalDateShort=function(e,t){const i=(0,a.localToDate)(e);return null==i?"":i.toLocaleDateString(t??"en-US",{year:"numeric",month:"2-digit",day:"2-digit"})},t.localToDateTime=S,t.localToTs=function(e,t){return(0,o.map)(S({local:e,zone:t}),h.datedToMillis)},t.nowLocal=function(e){return P(0,e)},t.agoLocal=P,t.tsToLocal=M,t.localPlusMs=function({local:e,deltaMs:t,zone:i,precisionMs:r}){const s=S({local:e,zone:i,precisionMs:r});return null==s?void 0:w(s.plus(t))},t.isLocal=function(e){return!(!(0,l.gt0)(e)||e<1e15||e>=1e16||null==g(e))},t.localNoCentiseconds=function(e){return 100*Math.floor(e/100)};const r=i(77988),s=i(51168),n=i(19851),a=i(42659),o=i(55835),l=i(31586),u=i(28874),c=i(76596),d=i(79842),h=i(66649),f=i(21330),m=i(928),p=(0,n.lazy)(()=>y(u.Settings.datesBeforeAreEstimated.valueOrDefault)??y(u.Settings.datesBeforeAreEstimated.defaultValue));function g(e,t){if(!(0,l.gt0)(e))return;let i=e;const s=()=>{const e=i%100;return i=Math.floor(i/100),e},n=s(),a=s(),o=s(),u=s(),c=s(),d=s(),h=i;if(!(0,l.within)(1800,2100,h))return;const f=(0,r.normalizeZone)(t);return 0===d?{year:h,month:void 0,day:void 0,hour:void 0,minute:void 0,second:void 0,millisecond:void 0,zone:f}:0===c?(0,l.within)(1,12,d)?{year:h,month:d,day:void 0,hour:void 0,minute:void 0,second:void 0,millisecond:void 0,zone:f}:void 0:0===u&&0===o&&0===a&&0===n?(0,l.within)(1,12,d)&&(0,l.within)(1,31,c)?{year:h,month:d,day:c,hour:void 0,minute:void 0,second:void 0,millisecond:void 0,zone:f}:void 0:(0,l.within)(1,12,d)&&(0,l.within)(1,31,c)&&(0,l.within)(0,23,u)&&(0,l.within)(0,59,o)&&(0,l.within)(0,59,a)&&(0,l.within)(0,99,n)?{year:h,month:d,day:c,hour:u,minute:o,second:a,millisecond:10*n,zone:f}:void 0}function y(e){const t=(0,d.isoToDated)(e);if(t)return"toMillis"in t&&"function"==typeof t.toMillis?M(t.toMillis()):w(t)}function v(e){if((0,l.isNumber)(e))return Math.floor(M(e)/1e4);let t=0;for(const i of[m.getYear,m.getMonth,m.getDay,m.getHour,m.getMinute])t=100*t+(i(e)??0);return t}function b(e){return(0,l.isNumber)(e)?Math.floor(M(e)/100):100*v(e)+((0,m.getSecond)(e)??0)}function w(e){return(0,l.isNumber)(e)?M(e):100*b(e)+((0,m.getCentisecond)(e)??0)}function S({local:e,zone:t,precisionMs:i}){const r=g(e,t);if(r){if(null==r.month||null==r.day)return f.FuzzyDate.for(r);if((0,l.gt0)(r.hour)||(0,l.gte0)(r.minute)||(0,l.gte0)(r.second)||(0,l.gte0)(r.millisecond)||(0,l.lt)(i,a.dayMs)){const e=(0,c.dateObjectToDateTime)(r);if(e)return e}return f.FuzzyDate.for(r)}}function P(e,t){return M(Date.now()-e,t)}function M(e,t){return w(null!=t?s.DateTime.fromMillis(e,{zone:t}):s.DateTime.fromMillis(e).toLocal())}},16400(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.monthName2index=function(e){return null==e?void 0:o().get(e)},t.monthNames=function(){return(0,s.sort)([...o().keys()])};const r=i(19851),s=i(76790),n=i(31586),a=i(9092),o=(0,r.lazy)(()=>{const e=new a.CaseInsensitiveMap;for(const t of["en-US",void 0]){e.set("Sept",9),e.set("Sept.",9);for(const i of["short","long"]){const r=new Intl.DateTimeFormat(t,{month:i});(0,n.times)(12,s=>{const n=r.format(new Date(2017,s));e.set(n,s+1),"short"===i&&"en-US"===t&&e.set(n+".",s+1)})}}return e})},17415(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimezoneOffsetRE=void 0,t.isValidZone=o,t.toValidIanaZone=function(e){return!(0,n.blank)(e)&&s.Info.isValidIANAZone(e)?e:void 0},t.zoneOffsetMinutes=function(e){return(0,a.map)(e.tzoffsetMinutes,r.inferLikelyOffsetMinutes)??(0,a.map)(e.offset,r.inferLikelyOffsetMinutes)??(0,a.map)(e.zone,t=>t.offset(e.toMillis()))},t.zoneToTzOffsetMinutes=l,t.zoneToExifOffsetMinutes=function(e,t){const i=l(e,t);return null==i?void 0:(0,r.offsetMinutesToZoneName)(i)},t.isoToOffsetMinutes=function(e){if((0,r.isUTC)(e))return 0;const t=(0,r.parseTimezoneOffsetToMinutes)(e);if(null!=t)return t;const i=(0,r.extractZone)(e);if(null==i)return;const s=(0,r.normalizeZone)(i.zone);return s?.offset(Date.now())},t.timezoneOffsetFromRegExpMatch=function(e){const t=(0,r.parseTimezoneOffsetMatch)(e);return null!=t&&o(t.offsetMinutes)?t.offsetMinutes:void 0},t.luxonTzOffsetToOffsetMinutes=function(e,t){if((0,n.blank)(e))return;const i=(0,r.parseTimezoneOffsetToMinutes)(e);if(null!=i)return(0,r.offsetMinutesToZoneName)(i);if(null!=t){const i=(0,r.normalizeZone)(e);if(null!=i)return(0,r.offsetMinutesToZoneName)(i.offset(t))}};const r=i(77988),s=i(51168),n=i(22573),a=i(55835);function o(e){return null!=(0,r.normalizeZone)(e)}function l(e,t){if(null==e||null==t)return;const i=(0,r.normalizeZone)(t);return!0===i?.isValid?i.offset(e):void 0}t.TimezoneOffsetRE=r.TimezoneOffsetRE},88600(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MaxValidTs=void 0,t.toValidMillis=function(e){return P(e)?e:void 0},t.isValidDate=P,t.whyNotValidDate=T,t.mapValidDate=function(e,t){return P(e)?t(e):void 0},t.validYMD=function(e,t,i){return null!=e&&null==T({year:e,month:t,day:i})};const r=i(51168),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(31586),u=i(34666),c=i(50213),d=i(98314),h=i(28874),f=i(79842),m=i(66649),p=i(928),g=i(89724),y=(0,s.lazy)(()=>(0,c.mkLogger)("date.ValidDate")),v=(0,s.lazy)(()=>(0,n.compact)(h.Settings.badDates.values.map(e=>(0,f.isoToDated)(e)))),b=(0,s.lazy)(()=>(0,n.compact)(v().map(e=>(0,f.datedToISO)(e)))),w=(0,s.lazy)(()=>(0,n.compact)(v().map(e=>(0,g.datedToLocal)(e)))),S=(0,s.lazy)(()=>(0,n.compact)(v().map(e=>(0,m.datedToMillis)(e))));function P(e){if(null==e)return!1;const t=T(e);return y().tap({msg:"isValidDate()",result:null==t,meta:{d:e,why:t}})}const M=String(new Date("bad"));function T(e){try{if(!(0,f.isDated)(e)&&!(0,l.isNumber)(e))return"not Dated";if(String(e)===M)return M;const i=(0,n.compact)([e.invalidExplanation]);if(0===i.length&&i.push(...function(e,t,i){const s=[];if((0,l.isNumber)(e)||s.push("year is not a number"),(0,l.lt)(e,h.Settings.minValidYear.valueOrDefault)&&s.push("year is less than "+h.Settings.minValidYear.key),null==t&&null!=i&&s.push("year and day is set but month is not"),((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),null!=t&&((0,l.lt)(t,1)||(0,u.gt)(t,12))&&s.push("month is invalid"),(0,l.isNumber)(e)&&(0,l.isNumber)(t)&&(0,l.isNumber)(i)){const n=r.DateTime.fromObject({year:e,month:t,day:i});n.isValid||s.push(n.invalidExplanation??"not valid")}return(0,n.compact)(s)}((0,p.getYear)(e),(0,p.getMonth)(e),(0,p.getDay)(e))),e instanceof Date&&isNaN(e.getTime())&&i.push("not valid js Date"),0===i.length){const r=(0,t.MaxValidTs)();null!=r&&(0,u.gt)((0,m.datedToMillis)(e),r)&&i.push("date is too far in the future: see "+h.Settings.maxValidFutureMs.key)}return S().includes((0,m.datedToMillis)(e))?i.push("bad date (via millis)"):w().includes((0,g.datedToLocal)(e))?i.push("bad date (via localtime)"):b().includes((0,f.datedToISO)(e))&&i.push("bad date (via ISO)"),(0,a.toNotBlank)((0,n.uniq)((0,n.compactBlanks)(i)).join("; "))}catch(t){return y().warn("whyNotValidDate() caught error",{input:e,error:t}),(0,d.errorToS)(t)}}t.MaxValidTs=(0,s.lazy)(()=>{const e=h.Settings.maxValidFutureMs.valueOrDefault;return(0,l.gt0)(e)?Date.now()+Math.max(e,o.hourMs):void 0},10*o.minuteMs)},68440(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pwshJsonDate=function(e){return(0,n.opt)(e).flatMap(e=>o.exec(e)).flatMap(e=>e[1]).flatMap(s.toInt).filter(e=>(0,a.within)(0,Date.now()+r.dayMs,e)).map(e=>new Date(e)).get()};const r=i(42659),s=i(31586),n=i(97790),a=i(97352),o=/Date\((\d+)\)/},23079(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Bitfield=void 0;const r=i(70974);t.Bitfield=class{tableName;columnName;names;constructor(e,t,i){if(this.tableName=e,this.columnName=t,this.names=i,i.values.length>32)throw new Error(`Too many flags (${i.values.length}): JavaScript bitwise operations limited to 32 bits (0-31). Consider using a different storage approach.`)}toBit(e){const t=this.names.indexOf(e);return null==t?0:1<<t}has(e,t){return null!=e&&0!==(e&this.toBit(t))}add(e,...t){e??=0;for(const i of t)e|=this.toBit(i);return e}remove(e,...t){if(null==e)return 0;for(const i of t)e&=~this.toBit(i);return e}decode(e){if(null==e)return[];const t=[];for(const i of this.names.values)this.has(e,i)&&t.push(i);return t}toContext(e){if(null==e)return{};const t={};for(const i of this.names.values)this.has(e,i)&&(t[i]=!0);return t}get qualifiedColumn(){return`${this.tableName}.${this.columnName}`}whereCondition(e,t=!0){return{sql:`(${this.qualifiedColumn} & ?) ${t?"!=":"="} 0`,bindings:[this.toBit(e)]}}where({flag:e,isSet:t=!0,qb:i=(0,r.knex)()(this.tableName)}){const{sql:s,bindings:n}=this.whereCondition(e,t);return i.whereRaw(s,n)}clearAll({flag:e,qb:t=(0,r.knex)()(this.tableName)}){const{sql:i,bindings:s}=this.whereCondition(e,!0);return t.whereRaw(i,s).update({[this.columnName]:(0,r.knex)().raw(`COALESCE(${this.qualifiedColumn}, 0) & ~?`,[this.toBit(e)])})}update({flag:e,isSet:t=!0,qb:i=(0,r.knex)()(this.tableName)}){return i.update({[this.columnName]:(0,r.knex)().raw(`COALESCE(${this.qualifiedColumn}, 0) ${t?"|":"& ~"} ?`,[this.toBit(e)])})}}},82261(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbDir_=async function(e=u.Settings.libraryDir.valueOrDefault,t=c.Schemas.models){const i=(0,o.libraryUidStore)(e);if(null==i)throw new Error("Library directory is not set"+n.NoLibraryErrorFlag);const d=await i.readUid_(),h=a.PosixFile.for((0,s.cacheDir_)()).join(t+"-live-db",d);await h.mkdirp_();const f=h.join("README.txt");return await(0,l.writeTextfile_)(f.nativePath,...(0,r.wrap)(["This folder is used by PhotoStructure for your library stored in",e,"You will corrupt your library if you remove this directory while PhotoStructure is running.","See https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837 for details."].join("\n\n"))),h};const r=i(51926),s=i(49776),n=i(38835),a=i(95696),o=i(70854),l=i(73428),u=i(28874),c=i(15056)},92407(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDbFile_=h,t.getLiveDbDir_=async function({forceReplica:e=a.Settings.forceLocalDbReplica.value,libraryDir:t=a.Settings.libraryDir.valueOrDefault,libraryDbFile:i,cacheDbFile:r}={}){if(!0!==e){i??=(0,l.pathToDb)(await(0,s.setupLibraryDataDir_)(t),l.Schemas.models);try{return await(0,c.assertDirSQLiteReadWrite_)(i.parent()),d().tap({msg:"getLiveDbDir_()",result:{db:i,useReplica:!1},meta:{args:{useReplica:e,libraryDir:t}}})}catch(e){d().info("SQLite cannot directly write to the library: trying to use a local db replica.",{libraryDb:i,error:e})}}r??=await h({libraryDir:t,schema:l.Schemas.models});try{return await(0,c.assertDirSQLiteReadWrite_)(r.parent()),{db:r,useReplica:!0}}catch(e){return d().throw("SQLite cannot directly write to the library or the cacheDir.",{cacheDbFile:r,error:e})}};const r=i(45599),s=i(87290),n=i(50213),a=i(28874),o=i(82261),l=i(15056),u=i(7311),c=i(44955),d=(0,r.defer)(()=>(0,n.mkLogger)("db.CheckLocalDbReplica"));async function h({libraryDir:e=a.Settings.libraryDir.valueOrDefault,schema:t=l.Schemas.models}={}){return(await(0,o.cacheDbDir_)(e,t)).join(u.SqliteBase)}},55332(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbBackupCold_=async function(e,t){await t.mkdirp_();const i=[],r=[];try{for(const s of(0,n.sqliteFiles)(e)){const e=t.join(s.base).wip();i.push(e),r.push(s.copyFile_(e,{skipProgressWatchdog:!0}))}await Promise.all(r);const s=await Promise.all(i.map(e=>e.unwip_()));return a().tap({msg:"completed",level:"info",result:s,meta:{srcDbFile:e,destDir:t}})}catch(e){throw await Promise.all(i.map(e=>e.unlink())),e}};const r=i(45599),s=i(50213),n=i(76187),a=(0,r.defer)(()=>(0,s.mkLogger)("db.DbBackupCold"))},61060(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbClosedError=void 0;class i extends Error{name="DbClosedError"}t.DbClosedError=i},91872(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleDbRetries_=function(e,t,i,r){const a=performance.now();let d=0;const h=a+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,u.time)({name:e,p:async()=>{for(;performance.now()<h;)try{return await i(t())}catch(t){if(!1===(0,s.isRetriableError)(t)||!(0,s.isSqliteBusyError)(t)||performance.now()>=h)throw c().error(e+": Caught db error. Not retrying.",{error:t}),t;{const i=(0,l.randomInt)(500,1500)*++d;c().warn(e+": Caught db error. Retrying in "+i+"ms.",{name:e,error:t}),r?.(),await(0,o.delay)(i)}}return t().close(),c().throw(e+": handleDbRetries(): timeout after "+n.Settings.dbMaintenanceTimeoutMs.valueOrDefault+"ms")}})};const r=i(50213),s=i(70025),n=i(28874),a=i(45599),o=i(41400),l=i(30976),u=i(56038),c=(0,a.defer)(()=>(0,r.mkLogger)("db.DbRetries"))},12943(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDbValue=s,t.isMaybeNullDbValue=n,t.isDbValued=function e(t){return null!=t&&Array.isArray(t)?t.every(e):(0,r.values)(t).every(n)};const r=i(68708);function s(e){const t=typeof e;return"number"===t||"string"===t||"boolean"===t}function n(e){return null==e||s(e)}},70974(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.knex=void 0;const s=r(i(61177)),n=r(i(31832)),a=i(19851),o=i(50213);t.knex=(0,a.lazy)(()=>{const e=(0,n.default)({client:s.default,useNullAsDefault:!0});return e.client.logger=(0,o.mkLogger)("knex.client"),e})},80632(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.BaselineOverheadMb=t.DbCacheScalar=void 0,t.computeDbSizingLimits=k,t.mkdb_=function({nativePath:e,timeoutMs:t=P.DbSettings.dbBusyTimeoutMs.valueOrDefault,quiet:i=!1}){e=(0,v.resolve)(e),(0,y.mkdirpSync_)((0,d.dirname)(e));const r=(0,b.nativePathSizeSync)(e),s=i?w.NoOpLogger:(0,p.mkLogger)("db.mkdb("+e+")");if(null!=r){const t=k(r),i=Math.round(r/m.MiB);t.wasCapped&&s.info("Capping cache_size at "+t.cacheMb+" MB ("+P.DbSettings.dbMaxCacheRamPercent.valueOrDefault+"% of RAM)",{db:e,dbFileSizeMb:i}),t.cacheMb>P.DbSettings.dbCacheSizeMb.valueOrDefault&&(s.info("Dynamically setting dbCacheSize to "+t.cacheMb+" MB",{db:e,dbFileSizeMb:i}),P.DbSettings.dbCacheSizeMb.cliValue=t.cacheMb),t.mmapMb>P.DbSettings.dbMMapSizeMb.valueOrDefault&&(s.info("Dynamically setting dbMMapSize to "+t.mmapMb+" MB",{db:e,dbFileSizeMb:i}),P.DbSettings.dbMMapSizeMb.cliValue=t.mmapMb),t.minMaxMemoryMb>M.ProcessesSettings.maxMemoryMb.valueOrDefault&&(s.warn("Large database: setting maxMemoryMb to "+t.minMaxMemoryMb,{dbFileSizeMb:i,"Settings.maxMemoryMb":M.ProcessesSettings.maxMemoryMb.valueOrDefault}),M.ProcessesSettings.maxMemoryMb.cliValue=t.minMaxMemoryMb)}s.info("Opening "+e+"...");const n={allowExtension:!0,enableForeignKeyConstraints:!0};(0,f.gt0)(t)&&(n.timeout=Math.ceil(t));const a=(0,o.enhance)(new o.DatabaseSync(e,n));s.info("Open. Setting PRAGMAs...");for(const e of(0,h.compact)(['encoding = "UTF-8"',"threads = "+(0,T.maxCpus)(),"page_size = "+I(),"trusted_schema = 0","cache_size = -"+Math.round(P.DbSettings.dbCacheSizeMb.valueOrDefault*m.MiB/1024),"locking_mode = NORMAL","journal_mode = WAL","temp_store = MEMORY","synchronous = "+P.DbSettings.dbSynchronousMode.valueOrDefault,"case_sensitive_like = 0","wal_autocheckpoint = "+((0,g.isDbJanitorService)()?P.DbSettings.dbWalAutoCheckpointPages.valueOrDefault:"0"),"auto_vacuum = NONE","mmap_size = "+P.DbSettings.dbMMapSizeMb.valueOrDefault*m.MiB]))s.tapThunk({msg:"PRAGMA "+e,result:()=>a.pragma(e)});if(!1===P.DbSettings.enableSimilaritySearch.valueOrDefault)s.info("Similarity search is disabled by settings; skipping sqlite-vec load");else try{!function(e,t){let i=u.getLoadablePath();(0,S.isPacked)()&&i.includes(".asar/")&&(i=i.replace(".asar/",".asar.unpacked/"));const r=(0,d.extname)(i);".so"!==r&&".dylib"!==r&&".dll"!==r||(i=i.slice(0,-r.length)),t.info("Loading sqlite-vec extension",{extensionPath:i}),e.enableLoadExtension(!0);try{e.loadExtension(i)}finally{e.enableLoadExtension(!1)}}(a,s),s.info("Loaded sqlite-vec extension")}catch(e){const t=e instanceof Error?e:new Error(String(e));(0,E.setVec0LoadError)(t),s.warn("Failed to load sqlite-vec extension; disabling similarity search",{error:t})}try{!function(e,t){let i=l.getLoadablePath();(0,S.isPacked)()&&i.includes(".asar/")&&(i=i.replace(".asar/",".asar.unpacked/")),t.info("Loading sqlite-seeded-random extension",{extensionPath:i}),e.enableLoadExtension(!0);try{e.loadExtension(i,"sqlite3_seededrandom_init")}finally{e.enableLoadExtension(!1)}}(a,s),s.info("Loaded sqlite-seeded-random extension")}catch(e){const t=e instanceof Error?e:new Error(String(e));(0,_.setSeededRandomLoadError)(t),s.warn("Failed to load sqlite-seeded-random extension; gallery ordering will use RANDOM()",{error:t})}const c=a;return c.$uid=D++,c},t.pageSizeBytes=I;const o=i(86558),l=a(i(9227)),u=a(i(29693)),c=i(48161),d=i(76760),h=i(40958),f=i(31586),m=i(12168),p=i(50213),g=i(23560),y=i(29882),v=i(53265),b=i(66430),w=i(22474),S=i(29325),P=i(83496),M=i(23135),T=i(15674),_=i(39904),E=i(7723);function k(e){const i=Math.round(e/m.MiB);let r=Math.ceil(t.DbCacheScalar*i),s=!1;const n=P.DbSettings.dbMaxCacheRamPercent.valueOrDefault;if(n>0){const e=Math.round((0,c.totalmem)()/m.MiB*n/100);r>e&&(r=e,s=!0)}const a=t.BaselineOverheadMb+i*t.DbCacheScalar,o=M.ProcessesSettings.maxMemoryErrorMultiplier.valueOrDefault;return{cacheMb:r,mmapMb:i,wasCapped:s,minMaxMemoryMb:Math.round(a*o)}}t.DbCacheScalar=1,t.BaselineOverheadMb=160;let D=0;function I(){const e=P.DbSettings.dbPageSizeBytes.valueOrDefault;return Math.pow(2,(0,f.clamp)(1,28,Math.round(Math.log2(e))))}},99315(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RepairModes=void 0;const r=i(50989);t.RepairModes=(0,r.strEnum)("dump","recover")},76187(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteFiles=function(e){return[e,...s.SQLiteSuffixes.map(t=>e.sibling(e.base+t))].filter(e=>e.existsSync({refresh:!0}))},t.sqliteSizeBytes=async function(e){return(await e.size({refresh:!0})??0)+(await e.sibling(e.base+"-wal").size({refresh:!0})??0)},t.isSqliteFile=function(e){const t=(0,r.basename)(e);for(const e of a)if(t.endsWith(e))return!0;return!1};const r=i(17217),s=i(87391),n=i(7311),a=[n.SqliteExt,...[...s.SQLiteSuffixes,"-shm"].map(e=>n.SqliteExt+e)]},49924(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withoutIndexes=function(e,t,i){const r=e.prepare("SELECT name, sql FROM sqlite_master\n WHERE type = 'index'\n AND tbl_name = ?\n AND sql IS NOT NULL").all(t);a().debug("withoutIndexes(): dropping indexes",{tableName:t,indexCount:r.length,indexNames:r.map(e=>e.name)});for(const{name:i}of r)/^[\w$]+$/.test(i)?e.exec(`DROP INDEX IF EXISTS ${(0,n.escapeIdentifier)(i)}`):a().warn("Skipping index with unusual name",{tableName:t,name:i});try{return i()}finally{a().debug("withoutIndexes(): restoring indexes",{tableName:t,indexCount:r.length});for(const{sql:i,name:s}of r)try{e.exec(i)}catch(e){a().throw(`Failed to restore index ${s} after withoutIndexes()`,{tableName:t,sql:i,error:e})}}};const r=i(45599),s=i(50213),n=i(51040),a=(0,r.defer)(()=>(0,s.mkLogger)("db.SQLiteIndexes"))},51040(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dbValueToEscapedString=function(e){if((0,s.isNumber)(e))return e.toString();const t=(0,n.toS)(e);return a.test(t)?t:`'${t.replace(/'/g,"''")}'`},t.escapeIdentifier=o,t.normalizeSql=c,t.patternSortOrderCase=function(e,t){if(0===t.length)return"1";const i=o(e);return`CASE ${t.map((e,t)=>{if(e.includes("*")||e.includes("?")){const r=e.replace(/'/g,"''").replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_").replace(/\*/g,"%").replace(/\?/g,"_");return`WHEN ${i} LIKE '${r}' ESCAPE '\\' THEN ${t+1}`}{const r=e.replace(/'/g,"''");return`WHEN ${i} = '${r}' THEN ${t+1}`}}).join(" ")} ELSE ${t.length+1} END`},t.splitBatchSql=function(e){const t=(0,r.compactBlanks)((0,n.toS)(e).split(";").map(e=>c(e))),i=[];let s;for(let e=0;e<t.length;e++){const r=t[e];null!=s?"END"===r.trim()&&(i.push(t.slice(s,e+1).join("; ")),s=void 0):/\bBEGIN\b/.test(t[e])?s=e:i.push(t[e])}if(null!=s)throw new Error("BEGIN without END (see statement "+s+")");return i};const r=i(40958),s=i(31586),n=i(54993),a=/^\w+$/;function o(e){return`"${e.replace(/"/g,'""')}"`}const l=/--.*$/gm,u=/\s+/g;function c(...e){return(0,r.compactBlanks)(e).join("\n").replace(l,"").replace(u," ").trim()}},44955(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDirSQLiteReadWrite=async function(...e){for(const t of e)if(null!=t&&await d(t))return t},t.isDirSQLiteReadWrite=d,t.assertDirSQLiteReadWrite_=h;const r=i(19851),s=i(50357),n=i(50213),a=i(95696),o=i(55222),l=i(80632),u=i(76187),c=(0,r.lazy)(()=>(0,n.mkLogger)("db.SQLiteReadWrite"));async function d(e){try{return await h(e),c().info("isDirSQLiteReadWrite(): true",{dirNativePath:e}),!0}catch(t){return c().warn("isDirSQLiteReadWrite(): false",{dirNativePath:e,error:t}),!1}}async function h(e){const t=a.PosixFile.for(e),i=t.child(".test-"+o.Radix36.randomChars(8)+".sqlite");let r=null;try{await t.mkdirp_(),r=(0,l.mkdb_)({nativePath:i.nativePath,timeoutMs:1e3,quiet:!0}),r.exec("CREATE TABLE t (s VARCHAR(16) NOT NULL)");const e=o.Radix36.randomChars(8);r.prepare("INSERT INTO t (s) VALUES (?)").run(e);{const t=r.prepare("SELECT s FROM t").all();(0,s.eql)(t,[{s:e}])||c().throw("unexpected rows",{rows:t})}r.exec("VACUUM"),r.close(),r=(0,l.mkdb_)({nativePath:i.nativePath,timeoutMs:1e3,quiet:!0});{const t=o.Radix36.randomChars(8);r.prepare("INSERT INTO t (s) VALUES (?)").run(t);const i=r.prepare("SELECT s FROM t ORDER BY s").pluck().all();(0,s.eql)(i,[e,t].sort())||c().throw("unexpected rows",{rows:i})}}finally{try{r?.close()}catch{}await Promise.all((0,u.sqliteFiles)(i).map(e=>e.rmrf()))}}},87391(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SQLiteSuffixes=void 0,t.SQLiteSuffixes=["-wal","-journal"]},14277(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.walFile=function(e){return(0,l.toNativePath_)(e)+"-wal"},t.safeTableName=function(e){let t=e.replace(/\W/g,"_");return/^\d/.test(t)&&(t="_"+t),t.slice(0,63)},t.retryIfSqliteBusy=y,t.walCheckpointPassive=function(e){return v(e,"wal_checkpoint(PASSIVE)")},t.walCheckpointTruncate=b,t.optimize=w,t.readCacheSizeMb=S,t.readMmapSizeMb=P,t.maybeResizeCacheAndMmap=async function(e,t){const i=await(0,u.statMaybe)(t);if(!(0,n.gt0)(i?.size))return;const r=(0,p.computeDbSizingLimits)(i.size),s=r.mmapMb,o=S(e);r.cacheMb>1.25*o&&(g().info("Resizing cache_size: "+o+" → "+r.cacheMb+" MB",{dbFileSizeMb:s}),h.DbSettings.dbCacheSizeMb.cliValue=r.cacheMb,e.pragma("cache_size = -"+Math.round(r.cacheMb*a.MiB/1024)));const l=P(e);r.mmapMb>1.25*l&&(g().info("Resizing mmap_size: "+l+" → "+r.mmapMb+" MB",{dbFileSizeMb:s}),h.DbSettings.dbMMapSizeMb.cliValue=r.mmapMb,e.pragma("mmap_size = "+r.mmapMb*a.MiB)),r.minMaxMemoryMb>f.ProcessesSettings.maxMemoryMb.valueOrDefault&&(g().info("Adjusting maxMemoryMb health check threshold to "+r.minMaxMemoryMb+" MB",{dbFileSizeMb:s}),f.ProcessesSettings.maxMemoryMb.cliValue=r.minMaxMemoryMb)},t.vacuum=async function(e){await y({logLevel:"info",msg:"VACUUM",fn:()=>e.exec("VACUUM")}),await b(e),await w(e)};const r=i(45599),s=i(41400),n=i(31586),a=i(12168),o=i(70025),l=i(17217),u=i(16287),c=i(50213),d=i(3685),h=i(83496),f=i(23135),m=i(61060),p=i(80632),g=(0,r.defer)(()=>(0,c.mkLogger)("db.SQLiteUtils"));async function y({fn:e,retries:t=5,closed:i,msg:r,logLevel:n="debug"}){let a=null;for(let l=0;l<=t;l++){const u=performance.now();try{if(!0===i?.ended)throw new m.DbClosedError;const t=await e(l),s=(0,d.roundMs)(performance.now()-u);return g().tap({level:n,msg:r,result:t,meta:{elapsedMs:s}})}catch(e){const i=(0,o.isSqliteBusyError)(e);if(g().info(r+" failed",{error:e,retryCount:l,isBusyError:i}),!i)throw e;a=e,l<t&&await(0,s.delay)(100*(l+1))}}throw a}function v(e,t){return y({logLevel:"info",msg:"PRAGMA "+t,fn:()=>e.pragma(t)})}function b(e){return v(e,"wal_checkpoint(TRUNCATE)")}async function w(e){await v(e,"analysis_limit=1000");const t=!0!==e.$optimized;await v(e,"optimize"+(t?"=0x10002":"")),e.$optimized=!0}function S(e){const t=e.pragma("cache_size",{simple:!0}),i=e.pragma("page_size",{simple:!0}),r=t<0?1024*Math.abs(t):t*i;return Math.round(r/a.MiB)}function P(e){const t=e.pragma("mmap_size",{simple:!0});return t<=0?0:Math.round(t/a.MiB)}},27180(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteVersion_=void 0;const r=i(86558),s=i(5916),n=i(84777),a=i(89966),o=i(63870);t.sqliteVersion_=(0,s.lazyAsync)({desc:"db.sqliteVersion",later:async function(){let e;try{e=(0,r.enhance)(new r.DatabaseSync(":memory:"));const t=e.prepare("select sqlite_version()").pluck().get(),i=await(0,a.sqliteNativePath_)(),s=(await(0,n.stdout_)(i,["-version"],{timerName:"proc.sqlite",timeoutMs:(0,o.commandTimeoutMs)()})).trim();return{libraryVersion:t,toolVersion:s.split(/\s+/,1)[0],fullToolVersion:s,sqliteNativePath:i}}finally{e?.close()}},timeoutMs:(0,o.commandTimeoutMs)()})},15056(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Schemas=void 0,t.pathToDbDir=n,t.pathToDb=function(e,t){return n(e,t).join(s.SqliteBase)},t.dbBackupDir=function(e){return e.sibling("backups")};const r=i(50989),s=i(7311);function n(e,t){return e.join(t)}t.Schemas=(0,r.strEnum)("models")},39904(e,t){"use strict";let i;Object.defineProperty(t,"__esModule",{value:!0}),t.setSeededRandomLoadError=function(e){i=e},t.getSeededRandomLoadError=function(){return i},t.isSeededRandomAvailable=function(){return null==i},t.resetSeededRandomState=function(){i=void 0}},31302(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqlWhereInJsonClause=void 0,t.isSqlQuery=g,t.toSqlQuery=function(e){if(null==e)return p().throw("toSqlQuery(): null query");if((0,f.isString)(e))return{sql:e};if(g(e))return e;const t=(0,o.pick)(e.toSQL?.()??e,"sql","bindings","method");if(function(e){if(Array.isArray(e))for(let t=0;t<e.length;t++)(0,m.isMaybeNullDbValue)(e[t])||p().throw("invalid bindings",{bindings:e,invalid:e.filter(e=>!(0,m.isMaybeNullDbValue)(e))});else(0,m.isDbValued)(e)||p().throw("invalid bindings",{bindings:e})}(t.bindings),g(t))return t;throw new Error("not queryish: "+(0,n.stringify)(e))},t.sqlQueryToS=function(e){if(null==e.bindings)return e.sql;if(Array.isArray(e.bindings))return(0,s.flatten)((0,c.zip)(e.sql.split("?"),e.bindings.map(e=>(0,n.stringify)(e)))).join("");{let t=e.sql;for(const i of(0,o.keys)(e.bindings))t=t.replace(new RegExp("[@:$]"+(0,h.escapeRegExp)(i),"gi"),(0,u.toS)(e.bindings[i]));return t}},t.isQueryBuilder=function(e){return(0,l.isFunction)(e?.where)&&(0,l.isFunction)(e?.limit)},t.sqlWhereInJsonClauseNamed=function(e){return`(SELECT value from json_each(:${e}))`},t.sqlWhereInClause=function(e){return"("+(0,a.times)(e,()=>"?").join(",")+")"};const r=i(45599),s=i(96249),n=i(98553),a=i(31586),o=i(68708),l=i(32639),u=i(54993),c=i(48884),d=i(50213),h=i(68852),f=i(81168),m=i(12943),p=(0,r.defer)(()=>(0,d.mkLogger)("db.SqlQuery"));function g(e){return null!=e&&(0,f.isString)(e.sql)&&(null==e.bindings||(0,m.isDbValued)(e.bindings))}t.SqlWhereInJsonClause="(SELECT value from json_each(?))"},7311(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqliteBase=t.SqliteExt=void 0,t.SqliteExt=".sqlite3",t.SqliteBase="db"+t.SqliteExt},34365(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynchronousModes=void 0;const r=i(50989);t.SynchronousModes=(0,r.strEnum)("OFF","NORMAL","FULL","EXTRA")},7723(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setVec0LoadError=function(e){s=e},t.getVec0LoadError=function(){return s},t.isVec0Available=function(){return null==s&&r.DbSettings.enableSimilaritySearch.valueOrDefault},t.resetVec0State=function(){s=void 0};const r=i(83496);let s},49776(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cacheDir_=t.cacheDir=t.defaultCacheDir=t.cacheDirs=void 0,t.tmpCacheDirs=L,t.tmpDirs=function(){return(0,A.filterDirs)({dirs:L(),desc:"tmp"})},t.resetCacheDir=B,t.isInInternalDir=function(e){const t=(0,v.toNativePath)(e);if(null==t)return!1;const i=z(t);return((0,g.toPathnames)(i.toLowerCase())?.some(e=>e.startsWith(".photostructure"))??!1)||V().some(e=>i.startsWith(e))};const r=i(48161),s=i(76760),n=i(40958),a=i(45599),o=i(55835),l=i(72993),u=i(96706),c=i(8769),d=i(57159),h=i(34102),f=i(70698),m=i(64680),p=i(29882),g=i(51704),y=i(53265),v=i(17217),b=i(77772),w=i(19851),S=i(50213),P=i(7282),M=i(97352),T=i(45969),_=i(43334),E=i(28874),k=i(41692),D=i(81168),I=i(24526),C=i(32774),A=i(80612),x=i(32551),F=i(9595),O=i(46296),R=(0,w.lazy)(()=>(0,M.mapGte0)((0,I.userid)(),e=>"-"+e)??"");function L(){const e=(0,r.tmpdir)();return[{dir:(0,s.join)(e,".photostructure-cache"+R()),preexistingDir:e}]}const N=(0,a.defer)(()=>(0,n.uniq)((0,n.compactBlankish)([...(0,u.getEnvs)("cacheDir"),...(0,u.getEnvs)("PS_TMP_DIR"),...(0,u.getEnvs)("PS_TEMP_DIR")])).map(e=>({dir:e,preexistingDir:e})));t.cacheDirs=(0,a.defer)(function(){if((0,T.isDocker)())return(0,n.uniqBy)([...N(),(0,o.map)(process.env.XDG_CACHE_HOME,e=>({dir:(0,s.join)(e,l.SimpleAppNameLC),preexistingDir:e})),{dir:"/ps/tmp",preexistingDir:"/ps/tmp"},{dir:"/ps/cache",preexistingDir:"/ps/cache"},{dir:C.DefaultDockerLibraryDir+"/.photostructure/cache"+R(),preexistingDir:C.DefaultDockerLibraryDir},...L()],e=>e.dir);const e=(0,n.compactBlanks)(_.isWin?[(0,u.getEnv)("LOCALAPPDATA"),(0,y.resolve)((0,x.homeDir)(),"AppData","Local")]:_.isMac?[(0,y.resolve)((0,x.homeDir)(),"Library","Caches")]:[process.env.XDG_CACHE_HOME,(0,s.join)((0,x.homeDir)(),".cache")]),t=_.isLinux?l.SimpleAppNameLC:l.SimpleAppName,i=e.map(e=>({dir:(0,s.join)(e,t),preexistingDir:e}));return i.unshift(...N()),i.push(...L()),i}),t.defaultCacheDir=(0,w.lazy)(()=>(0,A.firstDir)({dirs:(0,t.cacheDirs)(),desc:"cache"}));const j=(0,w.lazy)(()=>{(0,k.setSettingsDefaults)(),E.Settings.cacheDir.watchLater(B)});function B(){E.Settings.cacheDir.unsetCachedEnvValue(),N.reset(),t.cacheDirs.reset(),V.reset(),t.defaultCacheDir.unset(),t.cacheDir.unset(),t.cacheDir_.unset()}function z(e){const t=(0,D.ensureSuffix)((0,y.resolve)(e),s.sep);return _.isCaseSensitiveFs?t:t.toLowerCase()}t.cacheDir=(0,w.lazy)(()=>{try{return(0,t.cacheDir_)()}catch(e){return void(0,c.onError)("cacheDir_() failed",{error:e})}}),t.cacheDir_=(0,w.lazy)(()=>{j();const e=E.Settings.cacheDir.value??((0,P.isTest)()?(0,b.tmpDirName)({prefix:"ps-cache-test"}):E.Settings.cacheDir.defaultValue);try{return(0,p.mkdirpSync_)(e),async function(e){try{await(0,f.writeCachedirTag_)(e)}catch(t){(0,S.mkLogger)("dir.CacheDir").warn("postProcess(): writeCachedirTag_() failed for "+e,t)}try{await(0,m.mkNoMedia_)(e)}catch(t){(0,S.mkLogger)("dir.CacheDir").warn("postProcess(): mkNoMedia_() failed for "+e,t)}}(e),e}catch(t){throw new d.WrappedError("Failed to set up cacheDir, "+e,{path:e,fatal:!0,cause:t})}}),(0,h.ee)().on("resetDirectories",B);const V=(0,a.defer)(()=>{const e=(0,t.cacheDirs)().map(e=>e.dir);return e.push((0,F.libraryPreviewsDir)(),(0,O.logDir)(),...C.DockerInternalDirs),(0,n.uniq)((0,n.compactBlankish)(e).map(z))})},46292(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.configDir=void 0,t.resetConfigDir=f,t.osConfigDirs=function(){return((0,o.isDocker)()?h:(0,u.desktopConfigDirs)()).map(e=>e.dir)},t.resetSystemConfig_=async function(){const e=(0,t.configDir)();if(null==e)throw new Error("No config directory found");const i=n.PosixFile.for(e),s=[i.join("settings.toml"),i.join("pids"),i.join("archive"),i.join("main-window.json"),i.join("about-window.json"),i.join("splash-window.json")],a=[];for(const e of s)await e.exists()&&a.push(e);if(0===a.length)return null;const o=i.join(".archive").join((0,r.fmtYMDHMS)(Date.now())),l=[];for(const e of a)await e.mv_(o.join(e.base)),l.push(e.nativePath);return{archiveDir:o.nativePath,archived:l}};const r=i(42659),s=i(34102),n=i(95696),a=i(19851),o=i(45969),l=i(32774),u=i(10924),c=i(84373),d=i(80612);t.configDir=(0,a.lazy)(()=>(0,c.envConfigDir)()??((0,o.isDocker)()?(0,d.firstDir)({dirs:h,desc:"config"}):(0,u.desktopConfigDir)())),(0,s.ee)().on("resetDirectories",f);const h=[{dir:"/ps/config",preexistingDir:"/ps/config"},{dir:l.DefaultDockerLibraryDir+"/.photostructure/docker-config",preexistingDir:l.DefaultDockerLibraryDir}];function f(){t.configDir.unset()}},79960(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultApplePhotosLibrary=async function(){if(!h.isMac)return;try{const e=await(0,u.stdout_)("defaults",m,{timeoutMs:l.ShortCommandTimeoutMs,quiet:!0,ignoreStderr:!0,ignoreExitCode:!0});if(!(0,a.blank)(e)&&await(0,c.isReadableDirectory)(e))return f().tap({msg:"defaultApplePhotosLibrary()",level:d.LogLevels.info,result:e,meta:{source:"defaults"}})}catch{}const e=await(0,c.isReadableDirectory)(p);return f().tap({msg:"defaultApplePhotosLibrary()",level:d.LogLevels.info,result:e?p:void 0,meta:{source:"fallback",isReadable:e}})};const r=i(48161),s=i(76760),n=i(19851),a=i(22573),o=i(50213),l=i(45255),u=i(84777),c=i(16287),d=i(57902),h=i(43334),f=(0,n.lazy)(()=>(0,o.mkLogger)("dir.DefaultApplePhotosLibrary")),m=["read","com.apple.photolibraryd","SystemLibraryPath"],p=(0,s.join)((0,r.homedir)(),"Pictures","Photos Library.photoslibrary")},32774(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DockerInternalDirs=t.DefaultDockerLibraryDir=void 0,t.DefaultDockerLibraryDir="/ps/library",t.DockerInternalDirs=["/ps/cache","/ps/config","/ps/log","/ps/logs","/ps/temp","/ps/tmp"]},55086(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultLibraryDir=function(){return(0,s.isDocker)()?n.DefaultDockerLibraryDir:void 0},t.defaultOriginalsDir=function(){return(0,s.isDocker)()&&(0,r.isReadWriteableDirectorySync)("/ps/originals")?"/ps/originals":"."};const r=i(66430),s=i(45969),n=i(32774)},10924(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.desktopConfigDir=function(){return(0,d.firstDir)({dirs:f(),desc:"config"})},t.desktopConfigDirs=f;const s=r(i(76760)),n=i(40958),a=i(72993),o=i(96706),l=i(72544),u=i(53265),c=i(43334),d=i(80612),h=i(32551);function f(){const e=[];return c.isWin?e.push((0,o.getEnv)("APPDATA"),(0,u.resolve)((0,h.homeDir)(),"AppData","Roaming"),(0,o.getEnv)("LOCALAPPDATA")):c.isMac?e.push((0,u.resolve)((0,h.homeDir)(),"Library","Application Support")):e.push((0,l.xdg_config_home)()),(0,n.compactBlanks)(e).map(e=>({dir:s.default.join(e,(0,a.AppName)()),preexistingDir:e}))}},84373(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.envConfigDir=function(){const e=(0,s.getEnv)("PS_CONFIG_DIR");if(!(0,r.blank)(e))try{return(0,n.mkdirpSync_)(e),e}catch(t){console.error("The environment variable PS_CONFIG_DIR is set to "+e+", but mkdir failed.",t)}};const r=i(22573),s=i(96706),n=i(29882)},80612(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.firstDir=o,t.filterDirs=function({dirs:e,desc:t}){return(0,s.compact)(e.map(e=>o({dirs:[e],desc:t})))};const r=i(73024),s=i(40958),n=i(22573),a=i(66430);function o({dirs:e,desc:t}){for(const{dir:i,preexistingDir:o}of(0,s.compact)(e))if(!(0,n.blank)(i)){if((0,a.isReadWriteableDirectorySync)(i))return i;if((0,n.blank)(o)||(0,a.isReadWriteableDirectorySync)(o))try{return(0,r.mkdirSync)(i,{recursive:!0}),i}catch(e){console.error("Failed to mkdir for "+t,e)}}}},32551(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.homeDir=void 0;const r=i(48161),s=i(76760),n=i(1708),a=i(40958),o=i(45599),l=i(68284),u=i(43334);t.homeDir=(0,o.defer)(()=>{const e=[];u.isWin?e.push(n.env.USERPROFILE):e.push(n.env.HOME);for(const t of(0,a.compactBlanks)(e)){const e=(0,s.resolve)(t);if((0,l.isDirectorySync)(e))return e}return(0,r.homedir)()})},48195(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLibraryDir=async function(e){return null==await g(e)},t.whyNotLibraryDir=g;const r=i(19851),s=i(22573),n=i(98553),a=i(12168),o=i(50213),l=i(15056),u=i(98314),c=i(17217),d=i(16287),h=i(2858),f=i(87290),m=(0,r.lazy)(()=>(0,o.mkLogger)("dir.IsLibraryDir"));function p(e){return null==e?"(null)":(0,n.stringify)((0,c.toNativePath_)(e))}async function g(e){return m().tap({msg:"whyNotLibraryDir("+e+")",result:await y(e)})}async function y(e){if((0,s.blank)(e))return"blank path";const t=(0,c.toNativePath_)(e);try{const e=await(0,d.stat_)(t);if(null==e||!e.isDirectory())return"not a directory"}catch(e){return"cannot read: "+(0,u.errorToS)(e)}const i=(0,f.libraryDataDirPosixFile)(t);if(!0!==await(i?.isDirectory({refresh:!0,logLevel:"trace"})))return"library data directory, "+p(i)+", is not a directory";const r=(0,h.librarySettingsFile)(t)?.clear();if(null==r||!await r.isNonEmptyFile())return"library settings, "+p(r)+", is empty or missing";const n=(0,l.pathToDb)(i,"models")?.clear();if(null==n||!await(n?.isNonEmptyFile(a.KB)))return"library database, "+p(n)+", is empty or missing";const o=(0,f.libraryPreviewsDirPosixFile)(t);return!0!==await(o?.isDirectory({refresh:!0,logLevel:"trace"}))?"library previews, "+p(o)+", is empty or missing":void 0}},9595(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDir=l,t.originalsDir=function(e){const t=l(e);if(null==t)return;const i=o.Settings.originalsDir.valueOrDefault;return(0,r.blank)(i)?t:(0,n.isAbsolute)(i)?i:(0,a.resolve)(t,i)},t.libraryDataDir=function(e){return(0,n.resolveMaybe)(l(e),".photostructure")},t.libraryPreviewsDir=function(e){return(0,n.resolveMaybe)(l(e),o.Settings.previewsDir.valueOrDefault)};const r=i(22573),s=i(54993),n=i(29882),a=i(53265),o=i(28874);function l(e){return(0,r.toNotBlank)((0,s.toS)(e))??o.Settings.libraryDir.valueOrDefault}},87290(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirPosixFile=P,t.libraryDataDirPosixFile=M,t.libraryDirs_=T,t.setupLibraryDirs_=async function(e){const t=P(e);await _(t,!1);const i=await E(t);return(0,r.uniq)([t,i,await D(t),await C(t),await x(t),await F(t),await(0,y.imageCacheDir_)()])},t.setupLibraryDataDir_=E,t.libraryOriginalsDirPosixFile=k,t.setupLibraryOriginalsDir_=D,t.libraryAssetDirPosixFiles=function(e){const t=[],i=k(e);null!=i&&t.push(i);const s=P(e);return null!=s&&!0!==i?.$eql(s)&&t.push(s),(0,r.uniqBy)(t,e=>e.nativePath)},t.libraryPreviewsDirPosixFile=I,t.setupLibraryPreviewsDir_=C,t.librarySyncReportsDir=A,t.setupLibrarySyncReportsDir_=x,t.setupLibraryDbDir_=F,t.libraryVolumes=O,t.libraryVolumeUUIDs=async function*(e){const t=new Set;for await(const i of O(e))(0,s.blank)(i.uuid)?i.isReadOnly?w().info("libraryVolshas_(): no volsha for volume (readonly)",{volume:i}):w().warn("libraryVolshas_(): no volsha for volume",{volume:i}):t.has(i.uuid)?w().info("libraryVolshas_(): skipping already-yielded volsha",{volume:i}):(t.add(i.uuid),w().info("libraryVolshas_(): yielding volume",{volume:i}),yield i.uuid)};const r=i(40958),s=i(22573),n=i(45599),a=i(55835),o=i(50213),l=i(37805),u=i(15056),c=i(38835),d=i(70698),h=i(34075),f=i(64680),m=i(95696),p=i(17217),g=i(73428),y=i(13940),v=i(28874),b=i(9595),w=(0,n.defer)(()=>(0,o.mkLogger)("dir.LibraryDirs")),S=`\nHello, and thank you for using PhotoStructure!\n\nThe files in this folder support your PhotoStructure Library, including\n\n * a database with the filepaths to your photos and movies\n * previews and thumbnails of your photos and movies\n * content metadata about these assets, like ratings and sharing information\n * albums that both you and PhotoStructure Curators have assembled\n * synchronization reports describing what directories and files were synced (and why)\n\nMoving or deleting any files here will cause problems using your library.\n\nSee https://photostructure.com for more information.\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${l.version}\n`;function P(e){return m.PosixFile.forMaybe((0,b.libraryDir)(e))}function M(e){return m.PosixFile.forMaybe((0,b.libraryDataDir)(e))}function T(e){return(0,r.uniqBy)([P(e),M(e),k(e),I(e),A(e),(0,a.map)(M(e),e=>(0,u.pathToDbDir)(e,u.Schemas.models)),(0,y.imageCacheDirSync_)()],e=>e?.nativePath)}async function _(e,t=!0){if(null!=e)return await(e?.mkdirp_()),await(e?.assertReadWriteExecutable()),t&&await(e?.join(".metadata_never_index").touch()),e}async function E(e){const t=M(e);if(null==t)throw new Error("empty libraryDataDir"+c.NoLibraryErrorFlag);return await _(t),await(0,f.mkNoMedia_)(t),await(0,d.writeCachedirTag_)(t),await(0,g.writeTextfile_)(t.join("README.txt").nativePath,S),t}function k(e){return m.PosixFile.forMaybe((0,b.originalsDir)(e))}async function D(e){return _(k(e),!1)}function I(e){return m.PosixFile.forMaybe((0,b.libraryPreviewsDir)(e))}async function C(e){return _(I(e))}function A(e){return P(e)?.join(v.Settings.syncReportsDir.valueOrDefault)}async function x(e){return _(A(e))}async function F(e){return _((0,a.map)(M(e),e=>(0,u.pathToDbDir)(e,u.Schemas.models)))}async function*O(e){const t=new Set;for(const i of T(e))try{const e=(0,p.toNativePath_)(i),r=await(0,h.bestMountPointForPath)(e);if(null==r)w().warn("libraryVolshas_(): no mount point",{file:e});else if(t.has(r.mountPoint))w().debug("libraryVolshas_(): skipping already-yielded mount point",{file:e,mountPoint:r.mountPoint});else{t.add(r.mountPoint);const i=await(0,h.getVolumeMetadata)(r.mountPoint);null==i?w().warn("libraryVolshas_(): no volume metadata",{file:e,mountPoint:r.mountPoint}):yield i}}catch(e){w().warn("libraryVolshas_(): error from directory",{dir:i,error:e})}}},46296(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logDir=void 0,t.libraryLogDir=P,t.defaultLogDirs=M,t.defaultLogDir_=T;const r=i(73024),s=i(40958),n=i(22573),a=i(55835),o=i(54993),l=i(72993),u=i(96706),c=i(34102),d=i(53265),h=i(19851),f=i(7282),m=i(45969),p=i(43334),g=i(32707),y=i(6707),v=i(49776),b=i(32774),w=i(80612),S=i(32551);function P(e){return(0,d.resolve)(e,".photostructure","logs")}function M(){return(0,m.isDocker)()?[{dir:"/ps/logs",preexistingDir:"/ps/logs"},{dir:"/ps/log",preexistingDir:"/ps/log"},{dir:P(b.DefaultDockerLibraryDir),preexistingDir:"/ps/library"},{dir:"/tmp/photostructure-logs",preexistingDir:"/tmp"}]:p.isMac?[{dir:(0,d.resolve)((0,S.homeDir)(),"Library","Logs",l.SimpleAppName),preexistingDir:(0,S.homeDir)()}]:(0,s.compact)((0,v.cacheDirs)()).map(e=>({dir:(0,a.map)(e.dir,e=>(0,d.resolve)(e,"logs")),preexistingDir:e.preexistingDir}))}function T(){const e=(0,w.firstDir)({dirs:M(),desc:"logs"});if(null==e)throw new Error("No suitable log directory found");return e}t.logDir=(0,h.lazy)(()=>{try{const e=(0,u.getEnv)("logDir");if((0,n.notBlank)(e))return e;const t=(0,y.readTomlFileSync)((0,g.systemSettingsFile)()),i=(0,o.toS)(t?.logDir);if((0,n.notBlank)(i))return i;if((0,f.isTest)()&&null!=process.env.PS_SKIP_CLEANUP){const e=(0,u.getEnv)("libraryDir"),i=(0,n.notBlank)(t?.libraryDir)?(0,o.toS)(t?.libraryDir):(0,n.notBlank)(e)?e:void 0;if(null!=i&&(0,r.existsSync)(i))return P(i)}return T()}catch(e){return console.error("defaultLogDir_() failed",e),(0,d.resolve)((0,S.homeDir)(),"logs")}}),(0,c.ee)().on("resetDirectories",()=>t.logDir.unset())},55939(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultPicturesDir=t.picturesDir=void 0,t.picturesDirWindows=u;const r=i(76760),s=i(19851),n=i(22573),a=i(43334),o=i(24399),l=i(32551);async function u(){return a.isWin?o.PowerShell.instance().executeJson('Get-ItemPropertyValue "Registry::HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders" -name "My Pictures"'):void 0}t.picturesDir=(0,s.lazy)(async()=>{if(a.isWin){const e=await u();if((0,n.notBlank)(e))return e}return(0,t.defaultPicturesDir)()}),t.defaultPicturesDir=(0,s.lazy)(()=>process.env.XDG_PICTURES_DIR??(0,r.resolve)((0,l.homeDir)(),"Pictures"))},63458(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExplicitScanPath=a,t.isCurrentScanPath=function(e){return s.Settings.argvScanPaths.isNotEmpty()?s.Settings.argvScanPaths.values.some(t=>(0,r.eqlPath)(t,e)):!!s.Settings.scanAllDrives.valueOrDefault||a(e)};const r=i(29882),s=i(28874),n=i(9595);function a(e){if(s.Settings.argvScanPaths.values.some(t=>(0,r.eqlPath)(t,e)))return!0;if(s.Settings.scanPaths.values.some(t=>(0,r.eqlPath)(t,e)))return!0;const t=(0,n.originalsDir)();return!(null==t||!(0,r.eqlPath)(t,e)||!s.Settings.scanLibraryFirst.valueOrDefault&&!s.Settings.scanLibraryLast.valueOrDefault)}},89412(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.suggestedLibraryDirs=t.SuggestedLibraryDir=void 0,t._suggestedLibraryDirs=O;const s=r(i(76760)),n=r(i(1708)),a=i(40958),o=i(76790),l=i(22573),u=i(41400),c=i(41801),d=i(31586),h=i(12168),f=i(72993),m=i(19851),p=i(50213),g=i(7282),y=i(81168),v=i(5916),b=i(64660),w=i(83278),S=i(92423),P=i(34075),M=i(29882),T=i(65238),_=i(17217),E=i(16287),k=i(45969),D=i(28874),I=i(32551),C=i(48195),A=i(55939),x=(0,m.lazy)(()=>(0,p.mkLogger)("core.dir.SuggestedLibraryDir"));class F{nativePath;isLibrary;vol;static async for(e,t){const i=(0,_.toNativePath)(e);if((0,l.blank)(i))return;if(t??=await(0,P.bestVolumeForPath)(i),null==t)return void x().warn("Skipping library directory suggestion: failed to find mountpoint volume",{nativePath:i});const r=await(0,C.isLibraryDir)(i);return new F(i,r,t)}isCurrentLibrary;constructor(e,t,i){this.nativePath=e,this.isLibrary=t,this.vol=i,this.isCurrentLibrary=D.Settings.libraryDir.value===this.nativePath}async whyExcluded(e=D.Settings.minDiskFreeGb.valueOrDefault*h.GB){if(this.isLibrary)return;const t=await(0,E.statMaybe)(this.nativePath,"trace"),i={msg:"whyExcluded()",meta:{nativePath:this.nativePath,stat:t,availableBytes:this.availableBytes,minAvailableBytes:e}};if((0,M.containsHiddenPathname)(this.nativePath))return x().tap({...i,result:"contains hidden path"});{const e=await(0,S.whyExcludedDirectoryRecursive)(w.BaseFile.for(this.nativePath));if(null!=e)return x().tap({...i,result:e})}return null==t||t.isDirectory()?await(0,b.canRWXFirstExistingAncestor)(this.nativePath)?(0,d.gt0)(e)&&this.availableBytes<e?x().tap({...i,result:"volume has insufficient free space for a new library"}):void 0:x().tap({...i,result:"no write access to directory"}):x().tap({...i,result:"not a directory"})}get mountPoint(){return this.vol.mountPoint}get availableBytes(){return this.vol.available}get free(){return(0,h.fmtBytes)(this.vol.available,2)}get label(){return this.vol.label}get uuid(){return this.vol.uuid}get remote(){return this.vol.remote}get remoteHost(){return this.vol.remoteHost}get remoteShare(){return this.vol.remoteShare}get wbrPath(){return(0,y.wbrPath)(this.nativePath)}}async function O({minAvailableBytes:e=D.Settings.minDiskFreeGb.valueOrDefault*h.GB,maxSuggestionCount:t=6,timeoutMs:i=4e3}={}){const r=performance.now(),u=n.default.env[D.SuggestedDirsEnvKey];if(!(0,g.isProd)()&&null!=u)return x().tap({msg:"using ENV",result:(0,a.compactBlanks)(u.split(s.default.delimiter)).map(e=>new F(e,!1,{mountPoint:"/test",available:64*h.GB}))});const d=[],m=[];async function p(t,i){if((0,l.blank)(t))return;const r=await F.for(t,i);return null!=r?r.isLibrary||r.isCurrentLibrary?(x().info("addSuggestion(): path is a library",r),void d.push(r)):void(null==await r.whyExcluded(e)&&m.push(r)):void 0}if(await p(D.Settings.libraryDir.value),(0,k.isDocker)())return[...d,...m];function y(){return Date.now()-r>i?(x().debug("...ran out of time, stopping."),!0):d.length>=t?(x().debug("...found enough prior libraries, stopping."),!0):m.length>=t&&(x().debug("...found enough suggestions, stopping."),!0)}const v=e=>x().debug("Failed to iterate suggested directory",e);async function*b(e){for await(const t of(0,c.iterateQuietlyAsync)((0,T.iterateDir_)(e),v))t.isDirectory()&&(yield s.default.join(e,t.name))}const w=(0,c.chainAsyncIterators)([D.Settings.libraryDir.value,n.default.cwd()],()=>[(0,A.picturesDir)()],b((0,I.homeDir)()));for await(const e of w){if(y())break;await(0,C.isLibraryDir)(e)&&(x().info("current working dir is a library",e),await p(e))}async function S(e){try{if(await(0,C.isLibraryDir)(e.mountPoint))return x().info("addVolume(): vol.mountPoint is a library",e.mountPoint),void await p(e.mountPoint);for await(const t of b(e.mountPoint)){if(y())break;await(0,C.isLibraryDir)(t)&&(x().info("addVolume(): dir is a library",t),await p(t,e))}const t=s.default.join(e.mountPoint,(0,f.AppName)());x().info("addVolume(): adding default suggestion",t),await p(t)}catch(t){x().warn("addVolume(): Failed to add suggestion",{error:t,vol:e})}}if(await p(s.default.join((0,I.homeDir)(),(0,f.AppName)())),y())x().debug("Early return - timeout, or enough suggestions",{suggestions:m.length,maxSuggestionCount:t});else for await(const e of(0,P.volumesWithUUIDs)())if(await S(e),y())break;x().debug("Finished gathering suggestions. Filtering...",{priorLibraries:d,suggestions:m});const M=d;for(const e of(0,o.sortBy)(m,e=>[-e.availableBytes,-e.nativePath.length])){if(M.length>=t)break;M.some(t=>t.nativePath===e.nativePath||t.mountPoint===e.mountPoint)||(x().debug("adding new path",e),M.push(e))}return(0,a.uniqBy)((0,o.sortBy)(M,e=>[!e.isCurrentLibrary,!e.isLibrary,-e.free,e.nativePath]),e=>e.nativePath)}t.SuggestedLibraryDir=F,t.suggestedLibraryDirs=(0,v.lazyAsync)({desc:"library.suggestedLibraryDirs",later:()=>O()}),(0,u.later)(()=>D.Settings.libraryDir.watchLater(()=>t.suggestedLibraryDirs.clear()))},20603(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemStoreDir=l,t.libraryStoreFile=u,t.lazyLibraryStoreFile=function(e){const t=(0,a.lazy)(()=>u(e));return(0,r.ee)().on("clearCache",()=>t.unset()),t};const r=i(34102),s=i(95696),n=i(70854),a=i(19851),o=i(46292);function l(e){const t=(0,o.configDir)();return null!=t?s.PosixFile.for(t).join(e):void 0}async function u(e){const t=await((0,n.LibraryUIDStore)()?.readUid_());if(null==t)return;const i=l(e);return null!=i?i.join(t+".json"):void 0}},77740(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDevEnvFlag=function(e){return!(0,s.isProd)()&&!(0,n.isPacked)()&&((0,r.toBoolean)(process.env[e])??!1)};const r=i(38639),s=i(7282),n=i(29325)},34580(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DO_NOT_TRACK_ENV_KEYS=void 0,t.doNotTrack=function(){for(const e of t.DO_NOT_TRACK_ENV_KEYS)if((0,r.isTrue)(process.env[e]))return!0;return!1};const r=i(38639);t.DO_NOT_TRACK_ENV_KEYS=["DO_NOT_TRACK","DNT","GPC"]},44198(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciEnv=void 0,t.handleDeprecatedEnv=function(){"lite"===process.env.PS_LICENSE&&(process.env.PS_FORCE_LITE="true",delete process.env.PS_LICENSE)};const r=i(19851),s=i(40583);t.ciEnv=(0,r.lazy)(()=>new s.CaseInsensitiveValued(process.env))},59958(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnorableEnvKeys=t.DevEnvKeys=t.DevEnvFlags=t.PS_BAIL_AFTER_TASK_COUNT=t.PS_EXPECT_TEST_ERRORS=t.PS_SYNC_REPORT_STDOUT=t.PS_FIX_JSON_MANIFEST=t.PS_FORCE_FIX_JSON=t.PS_FIX_JSON=t.UV_THREADPOOL_SIZE=t.ELECTRON_RUN_AS_NODE=t.PS_RESET_LIBRARY_DIR=t.PS_IS_UTILITY_PROCESS=t.PS_IS_PACKED=t.PS_IS_ELECTRON=t.PS_IS_DOCKER=t.PS_IS_CHILD_PROCESS=void 0;const r=i(50989);t.PS_IS_CHILD_PROCESS="PS_IS_CHILD_PROCESS",t.PS_IS_DOCKER="PS_IS_DOCKER",t.PS_IS_ELECTRON="PS_IS_ELECTRON",t.PS_IS_PACKED="PS_IS_PACKED",t.PS_IS_UTILITY_PROCESS="PS_IS_UTILITY_PROCESS",t.PS_RESET_LIBRARY_DIR="PS_RESET_LIBRARY_DIR",t.ELECTRON_RUN_AS_NODE="ELECTRON_RUN_AS_NODE",t.UV_THREADPOOL_SIZE="UV_THREADPOOL_SIZE",t.PS_FIX_JSON="PS_FIX_JSON",t.PS_FORCE_FIX_JSON="PS_FORCE_FIX_JSON",t.PS_FIX_JSON_MANIFEST="PS_FIX_JSON_MANIFEST",t.PS_SYNC_REPORT_STDOUT="PS_SYNC_REPORT_STDOUT",t.PS_EXPECT_TEST_ERRORS="PS_EXPECT_TEST_ERRORS",t.PS_BAIL_AFTER_TASK_COUNT="PS_BAIL_AFTER_TASK_COUNT",t.DevEnvFlags=(0,r.strEnum)("PS_BAIL_ON_ERROR",t.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",t.PS_FIX_JSON,t.PS_FORCE_FIX_JSON,t.PS_SYNC_REPORT_STDOUT,t.PS_BAIL_AFTER_TASK_COUNT,"PS_SETTINGS_IO_TEST"),t.DevEnvKeys=["PS_NO_PUID_CHOWN","PS_TEST_VOLUME_UUIDS"],t.IgnorableEnvKeys=["PS_CONFIG_DIR",t.PS_IS_DOCKER,t.PS_IS_ELECTRON,t.PS_IS_PACKED,t.PS_IS_CHILD_PROCESS,t.PS_IS_UTILITY_PROCESS,t.PS_RESET_LIBRARY_DIR,...t.DevEnvKeys,...t.DevEnvFlags.values]},6012(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseEnvTokens=function({input:e,lowerCaseKeys:t}){if((0,r.blank)(e))return{};const i=function(e){const t={},i=e.replace(/\r\n?/g,"\n");let r;for(;null!=(r=a().exec(i));){const e=r.groups?.key;if(null==e)continue;let i=(r.groups?.qval??r.groups?.val??"").trim();'"'===r.groups?.quote&&(i=i.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\"/g,'"')),t[e]=i}return t}(e);return t?(0,n.downcaseObjectKeys)(i):i};const r=i(22573),s=i(19851),n=i(88158),a=(0,s.lazy)(()=>/\s*#.*$|(?:export[\t ]*)?(?<key>[\w.-]+)[\t ]*[:=](?:(?<quote>["'`])(?<qval>(?:\\.|(?!\2)[\s\S])*)\2|(?<val>[^\s#]*))(?:[\t ]*#.*$)?(?:$|\s)/gim)},96706(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEnv=o,t.getEnvs=function(e){const t=[];for(const i of a(e)){const e=process.env[i];null!=e&&t.push(e)}return t},t.isEnvTrue=function(e){return(0,r.isTrue)(o(e))},t.isEnvFalse=function(e){return(0,r.isFalse)(o(e))},t.setEnv=function(e,t){null==t?l(e):process.env[e]=t},t.deleteEnv=l;const r=i(38639),s=i(81168),n=i(83556);function a(e){return[e,(0,s.ensurePrefix)((0,n.camel2snake)(e).toUpperCase(),"PS_")]}function o(e){for(const t of a(e)){const e=process.env[t];if(null!=e)return e}}function l(e){delete process.env[e]}},19485(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readAndMergePsEnv=void 0,t._readAndMergePsEnv=h,t.mergeEnv=f,t.psEnvKeys=m,t.psEnvFiles=p,t.readPsEnvFiles=g;const r=i(51455),s=i(76760),n=i(40958),a=i(68708),o=i(54993),l=i(76850),u=i(32551),c=i(19851),d=i(6012);async function h(e,t){const i=(0,a.keys)(e);for await(const i of g(t))f(i,e);return(0,n.diff)((0,a.keys)(e),i)}function f(e,t){for(const[i,r]of(0,a.entries)(e))t[i]=r;return t}function m(){return["PS_ENV_FILE","PS_ENV"].flatMap(e=>[e,e.replace(/_/g,"")])}function p(){return(0,n.compactBlanks)((0,n.uniq)(["/.psenv",(0,s.join)((0,u.homeDir)(),".psenv"),...m().flatMap(e=>(0,o.toS)(process.env[e]).split(s.delimiter))]))}async function*g(e){for(const t of e??p())try{const e=await(0,r.readFile)(t);yield(0,d.parseEnvTokens)({input:(0,l.debom)(e),lowerCaseKeys:!1})}catch{}}t.readAndMergePsEnv=(0,c.lazy)(async()=>await h(process.env))},72544(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.xdg_data_home=o,t.xdg_home_trash=function(){return(0,r.join)(o(),"Trash")},t.xdg_config_home=function(){return(0,n.toNotBlank)(s.env.XDG_CONFIG_HOME)??(0,r.join)((0,a.homeDir)(),".config")};const r=i(76760),s=i(1708),n=i(22573),a=i(32551);function o(){return(0,n.toNotBlank)(s.env.XDG_DATA_HOME)??(0,r.join)((0,a.homeDir)(),".local","share")}},98314(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MissingError=t.lastInternalErrors=t.internalErrorRate=t.errorRate=void 0,t.toErrors=function(...e){return(0,r.compact)((0,h.toA)(e).map(c.toError))},t.splitErrorMessage=w,t.normalizeErrorMessages=S,t.joinErrorMessages=P,t.errorToS=M,t.errorToVerbose=function(e,i=256,r=7){return(0,s.blank)(e)&&(e=t.MissingError),M(e,{maxLen:i})+" at "+(0,a.shortStack)(e?.stack,r).join("; ")};const r=i(40958),s=i(22573),n=i(74310),a=i(26905),o=i(96249),l=i(68708),u=i(51926),c=i(70978),d=i(23541),h=i(59455),f=i(54993),m=i(81168),p=i(84542),g=i(976),y=i(41954),v=i(38835),b=i(70025);function w(...e){if((0,r.isEmpty)(e))return[];const t=(0,r.compact)(e).flatMap(e=>(0,d.isError)(e)?(0,y.getErrorDescriptions)(e):(0,m.isString)(e)?e:(0,u.isBuffer)(e)?e.toString():(0,l.isObject)(e)?w(...Object.values(e)):(0,f.toS)(e)),i=[...e.filter(d.isError).map(a.errorName),...e.map(a.errorCode),...(0,r.compactBlanks)(t).map(m.stripAnsiEsc).flatMap(e=>(0,p.splitCompactLines)(e)).flatMap(e=>e.split(a.ErrorDelimiter))];return(0,r.uniqSubstrings)(S((0,o.flatten)(i)))}function S(e){return(0,r.compact)(e).filter(e=>!a.IgnoredErrorNames.includes(e)).map(e=>e.replace(/\s+/g," ").trim().replace(/^code ([A-Z]+)$/i,"$1").trim()).filter(s.notBlank)}function P(e,t){const i=(0,r.uniq)(S(e)),s=t?.maxLen??400,n=t?.trailingChars??64,o=(0,v.sortErrorFlags)([...t?.flags??[],...(0,b.extractErrorFlags)(e.join(""))]);return(0,m.ellipsize)((0,b.stripErrorFlags)(i.join(a.ErrorDelimiter)),s-o.length,n)+o.join("")}function M(e,t){return(0,s.blank)(e)?"":"WrappedError"===e?.constructor?.name?e.toString():P(w(e),t)}t.errorRate=new g.Rate,t.internalErrorRate=new g.Rate,t.lastInternalErrors=new n.BoundedList(10),t.MissingError="(missing error)"},41954(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.describeError=u,t.getErrorDescriptions=function(...e){const t=[];for(const i of e)(0,a.map)((0,n.errorErrno)(i),e=>t.push(d.get(e))),(0,a.map)((0,n.errorCode)(i),e=>t.push(c[e]?.description)),(0,s.mapNotBlank)(i?.message,e=>{t.push(e),t.push(u(e))});return(0,r.uniq)(t)};const r=i(40958),s=i(22573),n=i(26905),a=i(55835),o=i(54993),l=i(81168);function u(e){const t=(0,l.stripSuffix)((0,o.toS)(e).trim().toUpperCase(),":");return c[t]?.description??e}const c={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"}},d=new Map(Object.values(c).map(e=>[e.errno,e.description]))},38835(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalErrorRe=t.FatalErrorRe=t.FailStr=t.ErrorFlagsRE=t.ErrorFlagDescriptions=t.DbSetupErrorFlag=t.NoLibraryErrorFlag=t.HealthCheckWarningFlag=t.HealthCheckErrorFlag=t.InternalErrorFlag=t.PleaseSendErrorFlag=t.DoNotSendErrorFlag=t.NonRetriableErrorFlag=t.RetriableErrorFlag=t.NonIgnorableErrorFlag=t.IgnorableErrorFlag=t.NonFatalErrorFlag=t.FatalErrorFlag=t.ErrorFlags=void 0,t.sortErrorFlags=function(e){return(0,s.sortBy)((0,r.uniq)(e),e=>t.ErrorFlags.indexOf(e))};const r=i(40958),s=i(76790),n=i(50989),a=i(68852);t.ErrorFlags=(0,n.strEnum)("¹","²","³","⁴","⁵","⁶","⁷","⁸","⁹","₀","₁","₂","₄"),t.FatalErrorFlag=t.ErrorFlags["¹"],t.NonFatalErrorFlag=t.ErrorFlags["₂"],t.IgnorableErrorFlag=t.ErrorFlags["³"],t.NonIgnorableErrorFlag=t.ErrorFlags["₄"],t.RetriableErrorFlag=t.ErrorFlags["⁷"],t.NonRetriableErrorFlag=t.ErrorFlags["²"],t.DoNotSendErrorFlag=t.ErrorFlags["⁶"],t.PleaseSendErrorFlag=t.ErrorFlags["⁴"],t.InternalErrorFlag=t.ErrorFlags["⁹"],t.HealthCheckErrorFlag=t.ErrorFlags["⁵"],t.HealthCheckWarningFlag=t.ErrorFlags["⁸"],t.NoLibraryErrorFlag=t.ErrorFlags["₀"],t.DbSetupErrorFlag=t.ErrorFlags["₁"],t.ErrorFlagDescriptions={[t.FatalErrorFlag]:"FatalErrorFlag",[t.NonFatalErrorFlag]:"NonFatalErrorFlag",[t.IgnorableErrorFlag]:"IgnorableErrorFlag",[t.NonIgnorableErrorFlag]:"NonIgnorableErrorFlag",[t.RetriableErrorFlag]:"RetriableErrorFlag",[t.NonRetriableErrorFlag]:"NonRetriableErrorFlag",[t.DoNotSendErrorFlag]:"DoNotSendErrorFlag",[t.PleaseSendErrorFlag]:"PleaseSendErrorFlag",[t.InternalErrorFlag]:"InternalErrorFlag",[t.HealthCheckErrorFlag]:"HealthCheckErrorFlag",[t.HealthCheckWarningFlag]:"HealthCheckWarningFlag",[t.NoLibraryErrorFlag]:"NoLibraryErrorFlag",[t.DbSetupErrorFlag]:"DbSetupErrorFlag"},t.ErrorFlagsRE=new RegExp("("+t.ErrorFlags.values.join("|")+")","g"),t.FailStr=JSON.stringify({fatal:!0});const o=["EADDRINUSE","SQLITE_FULL","SQLITE_CORRUPT","SQLITE_IOERR","SQLITE_NOMEM","SQLITE_NOTADB","ON CONFLICT","SQLITE_CONSTRAINT_NOTNULL","Error: Cannot find module",t.FatalErrorFlag,t.FailStr];t.FatalErrorRe=new RegExp(o.map(a.escapeRegExp).join("|"),"i"),t.InternalErrorRe=/⁹|internal ?error/i},59039(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MaxErrorAgeMs=t.MaxErrorsToCollect=void 0,t.groupingKey=l,t.groupErrors=function(e){const t=(0,s.groupBy)(e,l),i=[];for(const[,e]of t.entries()){const t=e[0],r=u(t);let s=t.ts,n=t.ts;for(const t of e)t.ts<s&&(s=t.ts),t.ts>n&&(n=t.ts);i.push({service:r.service,message:t.msg,userMessage:r.userMessage,code:r.code,signal:r.signal,exitCode:r.exitCode,href:r.href,linkText:r.linkText,category:r.category,count:e.length,firstTs:s,latestTs:n})}return i.sort((e,t)=>t.latestTs-e.latestTs)},t.formatErrorTable=function(e,t=15){if(0===e.length)return[];const i=[];let s=0,n=1/0;const a=new Set;for(const t of e)s+=t.count,a.add(t.service),t.firstTs<n&&(n=t.firstTs);const o=[...a].sort().join(", "),l=Math.ceil((Date.now()-n)/r.dayMs),u=l<=1?"today":`last ${l} days`;i.push(`${s} fatal error${1!==s?"s":""} from ${o} (${u})`),i.push(""),i.push("| Service | Error | # | Latest |"),i.push("|---|---|---:|---|");const d=e.slice(0,t);for(const e of d){let t=e.userMessage??e.message;null==e.code||t.includes(e.code)?null==e.signal||t.includes(e.signal)||(t=`${t} (${e.signal})`):t=`${t} (${e.code})`;const s=(0,r.fmtAgoCompact)(e.latestTs);i.push(`| ${c(e.service)} | ${c(t)} | ${e.count} | ${s} |`)}if(e.length>t){const r=e.length-t,s=e.slice(t).reduce((e,t)=>e+t.count,0);i.push(""),i.push(`...and ${r} more error type${1!==r?"s":""} (${s} total)`)}return i},t.determineLevel=function(e,t=Date.now()){if(0===e.length)return"ok";let i=0;const r=new Set;for(const t of e)i+=t.count,r.add(t.category);return r.has("dependency")||(r.has("crash")||r.has("resource"))&&function(e,t){let i=!1,r=0;for(const s of e)"crash"!==s.category&&"resource"!==s.category||(r+=s.count,t-s.latestTs<d&&(i=!0));return i&&r>=3}(e,t)||i>15||e.length>10?"error":"warn"},t.extractLinks=function(e){const t=new Set,i=[];for(const r of e)null==r.href||t.has(r.href)||(t.add(r.href),i.push({url:r.href,text:r.linkText??r.href,icon:"link",method:"GET"}));return i};const r=i(42659),s=i(23838),n=i(36324),a=i(10340);function o(e){return{service:e.meta?.service??e.ctx??"unknown",code:e.meta?.code,signal:e.meta?.signal,exitCode:e.meta?.exitCode,rawHref:e.meta?.href}}function l(e){const{service:t,code:i,signal:r}=o(e);return null!=i?`${t}:code:${i}`:null!=r?`${t}:signal:${r}`:`${t}:msg:${e.msg.slice(0,100)}`}function u(e){const{service:t,code:i,signal:r,exitCode:s,rawHref:l}=o(e),u=(0,a.enrichError)({service:t,code:i,signal:r,exitCode:s,message:e.msg}),c=(null!=l&&(0,n.isSafeExternalUrl)(l)?l:void 0)??u.href;return{service:t,userMessage:u.userMessage,code:i,signal:r,exitCode:s,href:c,linkText:u.linkText,category:u.category}}function c(e){return e.replace(/\|/g,"\\|")}t.MaxErrorsToCollect=50,t.MaxErrorAgeMs=7*r.dayMs;const d=10*r.minuteMs},10340(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorLookup=void 0,t.enrichError=function(e,i=(0,t.errorLookup)()){for(const t of i)if(n(e,t.match))return{userMessage:t.userMessage,href:t.href,linkText:t.linkText,remediation:t.remediation,category:t.category};return{category:"unknown"}},t.formatEnrichedError=function(e,t,i,r="FATAL ERROR"){const s=[],n=null!=i.service?` (${i.service})`:"";if(s.push(""),s.push("=".repeat(70)),s.push(`${r}${n}`),s.push("=".repeat(70)),s.push(""),null!=t.userMessage&&(s.push(t.userMessage),s.push("")),s.push("Technical details:"),s.push(` Message: ${e}`),(null!=i.errno||null!=i.code)&&s.push(` Code: ${i.errno??i.code}`),null!=i.signal&&s.push(` Signal: ${i.signal}`),null!=i.exitCode&&s.push(` Exit code: ${i.exitCode}`),s.push(""),null!=t.remediation&&t.remediation.length>0){s.push("To resolve this issue:");for(const e of t.remediation)s.push(` - ${e}`);s.push("")}if(null!=t.href){const e=t.linkText??"More information";s.push(`${e}: ${t.href}`),s.push("")}return s.push("=".repeat(70)),s.push(""),s.join("\n")};const r=i(19851),s=i(28874);function n(e,t){return(null==t.service||e.service===t.service)&&((null==t.errno||(e.errno??e.code)===t.errno)&&!(null!=t.signal&&e.signal!==t.signal||null!=t.exitCode&&e.exitCode!==t.exitCode||null==t.service&&null==t.errno&&null==t.signal&&null==t.exitCode))}t.errorLookup=(0,r.lazy)(()=>[{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 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_SYNC_PORT"],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:{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 ${s.Settings.cpuBusyPercent.key} or ${s.Settings.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 ${s.Settings.cpuBusyPercent.key} or ${s.Settings.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 ${s.Settings.cpuBusyPercent.key} or ${s.Settings.exiftoolProcsPerChild.key}`,"Check system logs for OOM killer activity"],category:"resource"}])},70025(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PermissionErrorRegex=void 0,t.addErrorFlags=function(e,...t){const i=(0,o.toS)(e)+(0,r.compact)(t).join("");return p(i)+g(i).join("")},t.stripErrorFlags=p,t.extractErrorFlags=g,t.hasErrorFlag=function(e){return m.ErrorFlags.values.some(t=>e.includes(t))},t.isHealthCheckError=function(e){return(0,f.errorToS)(e).includes(m.HealthCheckErrorFlag)},t.isPleaseSendError=y,t.isIgnorableError=function(e){if(null==e)return!0;const t=e?.ignorable;if("boolean"==typeof t)return t;const i=(0,f.errorToS)(e);return!v.test(i)&&(i.includes("BatchCluster has ended")?!!(0,h.ending)():!!b.test(i)||void 0)},t.isSqliteBusyError=S,t.isSqliteDisconnectedError=P,t.isSqliteConstraintError=T,t.isTimeoutError=function(e){return e instanceof a.TimeoutError||_.test((0,f.errorToS)(e))},t.isRetriableError=function(e){if(null==e)return;if(!0===E(e))return!1;const t=e?.retriable;if("boolean"==typeof t)return t;if("EBUSY"===(0,n.errorCode)(e)||S(e)||P(e))return!0;const i=(0,f.errorToS)(e);return!(!i.includes("EBUSY")&&!i.includes(m.RetriableErrorFlag))||void 0},t.isNonRetriableError=E,t.isPermissionError=function(e){if(null==e)return!1;const i=(0,n.errorCode)(e);return"EPERM"===i||"EACCES"===i||t.PermissionErrorRegex.test((0,f.errorToS)(e))},t.isClientDisconnectError=function(e){if(null==e)return!1;const t=(0,n.errorCode)(e);return"ECONNABORTED"===t||"ECONNRESET"===t||"EPIPE"===t},t.isVolumeGoneError=function(e){if(null==e)return!1;const t=(0,n.errorCode)(e);return"ENOENT"===t||"ENOTDIR"===t||"ENXIO"===t||"ENODEV"===t||"EIO"===t||"ESTALE"===t},t.isCorruptMediaError=function(e){return D.test((0,f.errorToS)(e))},t.isDoNotSendError=function(e){const t=e?.doNotSend;return"boolean"==typeof t?t:!y(e)&&(!!I.test((0,f.errorToS)(e))||void 0)},t.isFatalError=function(e){if(null==e)return!1;if((0,s.isTrue)(e.fatal))return!0;const t=(0,f.errorToS)(e);return!!t.includes(m.FatalErrorFlag)||!t.includes(m.NonFatalErrorFlag)&&m.FatalErrorRe.test(t)},t.isInternalError=function(e){return null!=e&&((0,s.isTrue)(e.internal)||(0,s.isTrue)(e.internalError)||m.InternalErrorRe.test((0,f.errorToS)(e)))};const r=i(40958),s=i(38639),n=i(26905),a=i(85556),o=i(54993),l=i(7282),u=i(68852),c=i(15890),d=i(73568),h=i(99331),f=i(98314),m=i(38835);function p(e){return(0,o.toS)(e).replace(m.ErrorFlagsRE,"").trim()}function g(e){return m.ErrorFlags.values.filter(t=>e.includes(t))}function y(e){return(0,f.errorToS)(e).includes(m.PleaseSendErrorFlag)}const v=(0,u.orRegExpPatterns)([m.NonIgnorableErrorFlag,/Can't write [a-z\d]+ files/i]),b=(0,u.orRegExpPatterns)((0,r.compact)([m.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 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",(0,l.isTest)()?/pretendMemUsageIsHigh|PS_FAIL_VOLUMES|throwIfInvalidFile_/:void 0,/\bwarning\b/i]),"i"),w=/SQLITE_BUSY|database is locked|busy executing a query/i;function S(e){return null!=e&&((0,o.toS)(e?.code).startsWith("SQLITE_BUSY")||w.test((0,f.errorToS)(e)))}function P(e){return/database .+ not open/i.test((0,f.errorToS)(e))}const M=/SQLITE_CONSTRAINT|constraint failed/i;function T(e){return(0,o.toS)(e?.code).startsWith("SQLITE_CONSTRAINT")||M.test((0,f.errorToS)(e))}const _=/time[d -]?out/i;function E(e){return!!((0,s.isFalse)(e?.retriable)||(0,d.isAbortError)(e)||(0,f.errorToS)(e).includes(m.NonRetriableErrorFlag)||T(e))||void 0}t.PermissionErrorRegex=/\bEPERM\b|\bEACCES\b|operation not permitted|preserving permissions|permission denied/i;const k=["Corrupt JPEG data","Premature end of JPEG file","VipsJpeg","VipsPng","VipsHeif","VipsTiff","VipsWebp","Invalid data found when processing input","moov atom not found","File format error"],D=new c.SubstringMatcher(k),I=new c.SubstringMatcher([m.DoNotSendErrorFlag,"ENOSPC",...k])},51837(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalError=void 0;const r=i(38835);class s extends Error{name="InternalError";constructor(e){super(e+r.InternalErrorFlag)}}t.InternalError=s},8769(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.errorHistory=void 0,t.onError=M,t.onInternalError=function(e,t,i){return M(e+y.InternalErrorFlag,{...i,cause:t})};const s=r(i(1708)),n=i(22573),a=i(74310),o=i(45599),l=i(68708),u=i(50321),c=i(50213),d=i(7282),h=i(23560),f=i(71567),m=i(34102),p=i(89206),g=i(98314),y=i(38835),v=i(10340),b=i(70025),w=i(57159),S=i(5012),P=(0,o.defer)(()=>(0,c.mkLogger)("error.OnError"));function M(e,i){try{if("function"==typeof e){const t=e.name||"anonymous";e=new Error(`onError: received function instead of error: ${t}`)}if("function"==typeof i){const e=i.name||"anonymous";i=new Error(`onError: received function instead of meta: ${e}`)}if((0,n.blank)(e)&&(0,l.isEmptyObj)(i))return P().warn("onError() with no args",(0,S.stack)()),!1;const r=(0,w.toWrappedError)(e,i);(0,b.isInternalError)(r)&&(g.internalErrorRate.onEvent(),g.lastInternalErrors.push(r));const a=!0===r.fatal,o=!0===r.ignorable;if(!a&&o)return P().info("onError(): (ignorable)",{error:e}),!1;g.errorRate.onEvent(),a&&(0,m.ee)().emit("fatal",r),P().log(a?"error":"warn","onError()",{error:r});const d=function(e){if(null==e||"object"!=typeof e)return!1;if(e instanceof Error)return!1;const t=e;return"string"==typeof t.userMessage||"string"==typeof t.code||"string"==typeof t.signal||"number"==typeof t.exitCode||"string"==typeof t.service||"string"==typeof t.href||"boolean"==typeof t.fatal||"boolean"==typeof t.doNotSend}(i)?i:{},{userMessage:y,code:M,signal:T,exitCode:_,href:E,service:k}=d,D=k??(0,h.serviceName)(),I=(0,b.stripErrorFlags)(y??r.message);if((0,t.errorHistory)()?.push({service:D,message:I,code:M,ts:Date.now(),fatal:a}),a){if((0,p.isChildProcess)()){const e={service:D,message:I,code:M,ts:Date.now(),fatal:!0};(0,f.stderrWrite)({serviceError:e})}else{const e={errno:M,signal:T,exitCode:_,service:D},t=(0,v.enrichError)(e);(0,u.writeStderr)((0,v.formatEnrichedError)(I,t,e))}(0,c.mkLogger)("ServiceError").fatal(I,{service:D,code:M,signal:T,exitCode:_,href:E,pid:s.default.pid})}return a}catch{return console.error("onError() threw an error!",{error:e,meta:i}),!1}}t.errorHistory=(0,o.defer)(()=>(0,d.isTest)()?new a.BoundedList(10):null)},57159(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrappedError=void 0,t.toWrappedError=function(e,t){const i=null==t?{}:t instanceof Error?{cause:t}:{cause:t?.error,...t};if(e instanceof v){if(null==t||(0,n.blank)(i.message)&&null==i.cause&&(null==i.meta||(0,u.isEmptyObj)(i.meta)))return e;const r=[...e.causes??[],...i.causes??[],e.cause].filter(e=>null!=e),s=[e,...r,t];return new v((0,n.firstNotBlank)(i.message,e.message)??"(missing error message)",{...i,causes:r,code:i.code??e.code,path:i.path??e.path,syscall:i.syscall??e.syscall,errno:i.errno??e.errno,meta:(0,u.mergeObjectsDeep)({},e.meta,i.meta),retriable:(0,a.maybeAnd)([i.retriable,...s.map(y.isRetriableError)]),ignorable:(0,a.maybeAnd)([i.ignorable,...s.map(y.isIgnorableError)]),fatal:(0,a.maybeOr)([i.fatal,...s.map(y.isFatalError)]),doNotSend:(0,a.maybeAnd)([i.doNotSend,...s.map(y.isDoNotSendError)]),internal:(0,a.maybeOr)([i.internal,...s.map(y.isInternalError)])})}const r=(0,n.firstNotBlank)((0,m.isString)(e)?e:void 0,e?.message,i?.message);return new v(r??"(missing error message)",i)};const r=i(57975),s=i(40958),n=i(22573),a=i(38639),o=i(26905),l=i(98553),u=i(68708),c=i(59455),d=i(54993),h=i(48884),f=i(36638),m=i(81168),p=i(98314),g=i(38835),y=i(70025);class v extends Error{code;codes;errno;syscall;path;cause;causes;meta;constructor(e,t={}){super(e);const i=(0,s.uniqBy)((0,p.toErrors)(t.cause,t.meta?.error,...(0,c.toA)(t.causes)),e=>e.message);this.cause=i[0],this.causes=(0,s.toNotEmpty)(i.slice(1)),this.name=(0,o.errorName)(t)??(0,h.first)(i,o.errorName)??"Error",this.codes=(0,m.splitUniq)([t.code,...i.map(o.errorCode)],o.ErrorDelimiter),this.code=this.codes[0],this.codes.length<=1&&(this.codes=void 0),this.errno=t.errno??(0,h.first)(i,e=>(0,o.errorErrno)(e)),this.syscall=t.syscall??(0,h.first)(i,e=>(0,n.toNotBlank)(e.syscall)),this.path=t.path??(0,h.first)(i,e=>(0,n.toNotBlank)(e.path));let r=t?.flags??[];const v=[e,t,r.join(""),...i],b=t.fatal??v.some(y.isFatalError),w=t.internal??(0,a.maybeOr)(v.map(y.isInternalError)),S=t.retriable??(0,a.maybeAnd)(v.map(y.isRetriableError)),P=t.ignorable??(0,a.maybeAnd)(v.map(y.isIgnorableError)),M=t.doNotSend??(0,a.maybeAnd)(v.map(y.isDoNotSendError));r=(0,g.sortErrorFlags)([...r,!0===b?g.FatalErrorFlag:void 0,!0===w?g.InternalErrorFlag:void 0,!0===S?g.RetriableErrorFlag:void 0,!1===S?g.NonRetriableErrorFlag:void 0,!0===P?g.IgnorableErrorFlag:void 0,!1===P?g.NonIgnorableErrorFlag:void 0,!1===M?g.PleaseSendErrorFlag:void 0,!0===M?g.DoNotSendErrorFlag:void 0]),this.meta=(0,u.omit)((0,u.mergeObjectsDeep)(...(t.causes??[]).map(e=>e.meta),t.cause?.meta,t.meta,t),"_ctor","name","message","stack","code","codes","errno","syscall","path","cause","causes","retriable","ignorable","internal","fatal","doNotSend","flags","meta"),this.message=(0,y.stripErrorFlags)(function(e,t){let i=(0,p.splitErrorMessage)(e,t?.message,t?.cause,...t?.causes??[]);const r=new f.CaseInsensitiveSet(o.IgnoredErrorNames);(0,n.blank)(t?.name)||r.add(t.name),(0,s.filterInPlace)(i,e=>!r.has(e));const a=t?.path;(0,n.blank)(a)||(i=(0,m.dedupeNeedle)(i,a,"file")),(0,u.notEmptyObj)(t?.meta)&&i.push((0,l.stringify)(t.meta));for(const e of(0,s.uniq)((0,s.compact)([t?.syscall,t?.code,...(0,c.toA)(t?.codes)])))i.join("\n").includes(e)||i.unshift(e);return(0,p.joinErrorMessages)(i)}(e,this))+r.join("");let T=t.stack??this.stack;if(null==T){const e=new Error;Error.captureStackTrace(e),T=e.stack}const _=T?.split("\n")??[];for(const e of i)"stack"in e&&_.push(...(0,d.toS)(e.stack).split("\n"));(0,s.filterInPlace)(_,e=>!(0,n.blank)(e)&&!e.trim().startsWith("at new WrappedError")&&!e.trim().startsWith("at toWrappedError"));const E=new Set,k=[];for(let e=_.length-1;e>=1;e--)E.has(_[e])||(E.add(_[e]),k.unshift(_[e]));this.stack=_[0]+"\n"+k.join("\n")}get fatal(){return this.message.includes(g.FatalErrorFlag)&&!this.message.includes(g.NonFatalErrorFlag)}get internal(){return!!this.message.includes(g.InternalErrorFlag)||void 0}get retriable(){return!!this.message.includes(g.RetriableErrorFlag)||!this.message.includes(g.NonRetriableErrorFlag)&&void 0}get ignorable(){return!this.message.includes(g.NonIgnorableErrorFlag)&&(!!this.message.includes(g.IgnorableErrorFlag)||void 0)}get doNotSend(){return!!this.message.includes(g.DoNotSendErrorFlag)||!this.message.includes(g.PleaseSendErrorFlag)&&void 0}get flags(){return(0,y.extractErrorFlags)(this.message)}[r.inspect.custom](){return this.stack}toString(){return(o.IgnoredErrorNames.includes(this.name)?"":this.name+o.ErrorDelimiter)+this.message}toJSON(){return(0,u.pick)(this,"name","message","stack","ignorable","retriable","fatal","doNotSend","code","codes","errno","syscall","path","flags")}static fromJSON(e){return new v(e.message,(0,u.omit)(e,"message"))}}t.WrappedError=v},5012(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stack=function e(){const t={};return Error.captureStackTrace?.(t,e),null==t.stack?(new Error).stack?.split(/\n(?:\s*at\s+)?/).slice(1)??[]:t.stack.split(/\n(?:\s*at\s+)?/).slice(1)}},34102(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ee=void 0;const r=i(45599),s=i(61848);t.ee=(0,r.defer)(()=>new s.CapturingEventEmitter),t.ee.reset=()=>{throw new Error("ee.reset() is not allowed")}},61848(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CapturingEventEmitter=t.WeakRefEventEmitter=t.TypedEventEmitterImpl=t.EventDebounceMs=void 0;const r=i(40958),s=i(74310),n=i(45599),a=i(54900),o=i(49769),l=i(23838),u=i(99331),c=i(85296),d=i(50213),h=i(7282),f=i(22277),m=(0,n.defer)(()=>(0,d.mkLogger)("event.TypedEventEmitter"));class p{fn;once;constructor(e,t){this.fn=e,this.once=t}}t.EventDebounceMs=50;class g{listeners=new l.MultiMap;#He=new f.TTLSet(t.EventDebounceMs);once(e,t){return this.listeners.add(e,new p(t,!0)),this}waitOnce(e){const t=new a.Deferred;return this.once(e,(...e)=>t.resolve(e)),t}on(e,t){return this.listeners.add(e,new p(t,!1)),this}off(e,t){const i=this.listeners.get(e)??[];for(const e of i)e.fn===t&&(0,r.removeSame)(i,e);return this}async emit(e,...t){if((0,u.ending)())return!1;this.#He.add(e);let i=!1;const s=this.listeners.get(e)??[];for(const n of s){n.once&&(0,r.removeSame)(s,n);try{await n.fn(...t)}catch(t){m().warn("TypedEventEmitterImpl listener failed",{eventName:e,error:t})}i=!0}return i}emitSync(e,...t){if((0,u.ending)())return!1;this.#He.add(e);let i=!1;const s=this.listeners.get(e)??[];for(const n of s){n.once&&(0,r.removeSame)(s,n);try{n.fn(...t)}catch(t){m().warn("TypedEventEmitterImpl listener failed",{eventName:e,error:t})}i=!0}return i}emitRateLimited(e,...t){return this.#He.has(e)?void 0:this.emit(e,...t)}emitSyncRateLimited(e,...t){return this.#He.has(e)?void 0:this.emitSync(e,...t)}#Ue=new Map;emitThrottled(e,...i){(0,o.getOrSet)(this.#Ue,e,()=>(0,c.trailingThrottle)({fn:(...t)=>this.emit(e,...t),minDelayMs:t.EventDebounceMs}))(...i)}clear(){this.removeAllListeners(),this.#He.clear();for(const e of this.#Ue.values())e.reset();this.#Ue.clear()}removeAllListeners(e){return null!=e?this.listeners.delete(e):this.listeners.clear(),this}listenerCount(e){return this.listeners.get(e)?.length??0}}t.TypedEventEmitterImpl=g,t.WeakRefEventEmitter=class{listeners=new l.MultiMap;#He=new f.TTLSet(t.EventDebounceMs);once(e,t){return this.listeners.add(e,new WeakRef(new p(t,!0))),this}waitOnce(e){const t=new a.Deferred;return this.once(e,(...e)=>t.resolve(e)),t}on(e,t){return this.listeners.add(e,new WeakRef(new p(t,!1))),this}off(e,t){const i=this.listeners.get(e)??[];for(const e of i){const s=e.deref();null!=s&&s?.fn!==t||(0,r.removeSame)(i,e)}return this}async emit(e,...t){if((0,u.ending)())return!1;this.#He.add(e);let i=!1;for(const r of this.listeners.get(e)??[]){const s=r.deref();(null==s||s.once)&&this.listeners.delete(e,r),null!=s&&(await s.fn(...t),i=!0)}return i}emitRateLimited(e,...t){return this.#He.has(e)?void 0:this.emit(e,...t)}#Ue=new Map;emitThrottled(e,...i){(0,o.getOrSet)(this.#Ue,e,()=>(0,c.trailingThrottle)({fn:(...t)=>this.emit(e,...t),minDelayMs:t.EventDebounceMs}))(...i)}clear(){this.#He.clear();for(const e of this.#Ue.values())e.reset();return this.#Ue.clear(),this.removeAllListeners()}removeAllListeners(e){return null!=e?this.listeners.delete(e):this.listeners.clear(),this}listenerCount(e){return this.listeners.get(e)?.length??0}},t.CapturingEventEmitter=class extends g{eventsToRetain;priorEvents;constructor(e=((0,h.isTest)()?10:0)){super(),this.eventsToRetain=e,this.priorEvents=e>0?new s.BoundedList(e):void 0}#t(e,...t){this.eventsToRetain>0&&this.priorEvents?.push({event:e,args:t})}emit(e,...t){return this.#t(e,...t),super.emit(e,...t)}emitSync(e,...t){return this.#t(e,...t),super.emitSync(e,...t)}}},64660(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isStatRWX=p,t.isStatRX=g,t.canRWXFirstExistingAncestor=async function(e){let t=!1;for(const i of(0,u.selfAndAncestorG)(e)){const e=await(0,c.statMaybe)(i);if(null!=e){if(!e.isDirectory())return!1;if(t){if(!g(e))return!1}else if(t=!0,!p(e,i))return!1}}return!0},t.access=y;const s=r(i(73024)),n=i(76760),a=r(i(1708)),o=i(19851),l=i(22573),u=i(65843),c=i(16287),d=i(43334),h=i(29882),f=(0,o.lazy)(()=>a.default.geteuid?.()),m=(0,o.lazy)(()=>a.default.getgroups?.());function p(e,t){return d.isWin?!(0,l.blank)(t)&&(!0===e?.isDirectory()?function(e){if((0,l.blank)(e))return!1;const t=(0,n.join)(e,".ps-write-test");try{return(0,h.ensureFileSync_)(t),!0}catch{return!1}finally{try{s.default.unlinkSync(t)}catch{}}}(t):null!=e):y({stat:e,r:!0,w:!0,x:!0})}function g(e,t){return d.isWin?null!=e:y({stat:e,r:!0,x:!0})}function y({stat:e,r:t=!1,w:i=!1,x:r=!1,processUid:s,processGid:n}){if(null==e)return!1;const a=s??f(),o=null!=n?[n]:m()??[],l=!d.isWin&&0===a,u=!d.isWin&&(l||e.uid===a),c=!d.isWin&&(l||o.includes(e.gid));return!(t&&!(((u?256:0)|(c?32:0)|4)&e.mode))&&(!(i&&!(((u?128:0)|(c?16:0)|2)&e.mode))&&!!(!r||d.isWin||((u?64:0)|(c?8:0)|1)&e.mode))}},21144(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.actualPath=async function(...e){try{return await g(...e)}catch(t){return m().warn("actualPath() failed, reverting to resolve()",{nativePath:e,error:t}),(0,f.resolve)(...e)}},t.actualPath_=g;const s=r(i(76760)),n=i(19851),a=i(50213),o=i(81168),l=i(57159),u=i(43334),c=i(88561),d=i(29882),h=i(65238),f=i(53265),m=(0,n.lazy)(()=>(0,a.mkLogger)("fs.ActualPath")),p=(0,n.lazy)(()=>new c.FileCache({name:"fs.Path.actualPathCache"}));async function g(...e){const t=(0,f.resolve)(...e);return u.isLinux||(0,d.pathIsRoot)(t)?t:p().getOrSet(t,async()=>{const i=(0,d.parseNativePath)((0,f.resolve)(...e)),r=await g(i.dir);for await(const e of(0,h.iterateDir_)(r))if((0,o.equalsIgnoreCase)(e.name,i.base))return s.default.join(r,e.name);throw new l.WrappedError(t+" not found",{code:"ENOENT",path:t})})}},65843(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ancestors=a,t.ancestorG=o,t.selfAndAncestorG=function*(e){yield e,yield*o(e)},t.childrenSync=l,t.hasChildrenSync=u,t.ancestorWithChildren=function(e,t){return a(e).find(e=>u(e,t))};const r=i(73024),s=i(76760),n=i(22573);function a(e){return[...o(e)]}function*o(e){if(!(0,n.blank)(e))for(;e!==(0,s.dirname)(e);)e=(0,s.dirname)(e),yield e}function l(e){try{return(0,r.readdirSync)(e)}catch(e){return[]}}function u(e,t){if((0,n.blank)(e))return!1;const i=l(e);return t.every(e=>i.includes(e))}},83278(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t}),o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseFile=void 0,t.isBaseFile=function(e){return(0,oe.isSimpleFile)(e)&&e instanceof pe},t.useFsWatch=function(e){ge=e},t.execDir=function(){return pe.for(h.default.execPath).parent()};const l=i(77598),u=i(73024),c=i(51455),d=a(i(76760)),h=o(i(1708)),f=i(46466),m=o(i(57975)),p=o(i(38522)),g=i(40958),y=i(5233),v=i(22573),b=i(42659),w=i(50357),S=i(96249),P=i(41801),M=i(98553),T=i(55835),_=i(31586),E=i(68708),k=i(97790),D=i(54993),I=i(76790),C=i(48884),A=i(22911),x=i(99331),F=i(56519),O=i(56038),R=i(85296),L=i(31562),N=i(76850),j=i(70025),B=i(34102),z=i(19851),V=i(50213),H=i(70417),U=i(88158),W=i(43334),q=i(81168),$=i(96859),G=i(65162),K=i(64660),J=i(84542),Y=i(89968),Z=i(20197),X=i(88561),Q=i(32144),ee=i(50597),te=i(29882),ie=i(91987),re=i(51704),se=i(78133),ne=i(65238),ae=i(53265),oe=i(17217),le=i(16287),ue=i(68284),ce=i(27794),de=i(73428),he=i(13047),fe=(0,z.lazy)(()=>new X.FileCache({name:"fs.BaseFile",clearOnFileChange:!0}));let me=0;class pe{dirent;$id=me++;bflog=(0,z.lazy)(()=>(0,V.mkLogger)("fs.BaseFile",{file:this.nativePath}));static attrTTL=3*b.minuteMs;posixPath;nativePath;dir;base;name;ext;constructor(e,t){if(this.dirent=t,null!=t)this.nativePath=t.nativePath,this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext;else{this.nativePath=e;const t=(0,te.parseNativePath)(this.nativePath);this.dir=t.dir,this.base=t.base,this.name=t.name,this.ext=t.ext}this.posixPath=(0,se.native2posix)(this.nativePath)}toJSON(){return{nativePath:this.nativePath}}toLogJSON(){return this.nativePath}[m.default.inspect.custom](){return this.toLogJSON()}static async withFastestAccess(e){const t=(0,g.compact)(e),i=await Promise.all(t.map(e=>e.shaMs()));return t[(0,C.leastIndex)(i)]}static forPosix(e){return e instanceof pe?e:this.for(e.split("/").join(d.default.sep))}static forDirectoryEntry(e){return this.for(e.nativePath,e)}static for(e,t){if(e instanceof pe)return e;const i=(0,oe.isSimpleFile)(e)?e.nativePath:(0,D.toS)(e);if((0,v.blank)(i))throw new Error("BaseFile.for(): empty nativePathOrFile");const r=fe().get(i);if(null!=r)return r;const s=(0,ae.resolve)(i),n=new pe(s,t);return fe().set(i,n),fe().set(s,n),n}static forMaybe(e){return(0,v.notBlank)(e)?pe.for(e):void 0}static clear(e){return(0,B.ee)().emit("fileChanged",e)}for(e,t){return pe.for(e,t)}forDirectoryEntry(e){return pe.for(e.nativePath,e)}forChildDirent(e){return this.forDirectoryEntry(Y.DirectoryEntry.fromSimpleDirent(this.nativePath,e))}forSiblingSimpleDirent(e){return this.forDirectoryEntry(Y.DirectoryEntry.fromSimpleDirent(this.dir,e))}forSiblingDirent(e){return this.forDirectoryEntry(Y.DirectoryEntry.fromDirent(this.dir,e))}clearIfChanged(){if(!this.clearable())return this;const e=(0,ue.statSync)(this.nativePath);return null!=this.#We&&!(0,Y.eqlFileMeta)(this.#We,e)||null!=this.dirent&&!(0,Y.eqlFileMeta)(this.dirent,e)?this.clear({emit:!0}):this}clearable(){return null!=this.#We||null!=this.dirent}clear({emit:e}={}){return!0===e&&(0,B.ee)().emitSync("fileChanged",this.nativePath),this.dirent=void 0,this.#qe.unset(),this.#We=void 0,this}clearThisAndParent(){return(0,B.ee)().emitSync("fileChanged",this.dir),this.clear({emit:!1})}toString(){return this.nativePath}valueOf(){return this.pathnames}resolve(){const e=(0,ae.resolve)(this.nativePath);return e===this.nativePath?this:this.for(e)}$eql(e){return null!=e&&(0,te.eqlPath)(this,e)}get isUNC(){return(0,te.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(0,te.posixPathFrom)(e,this)}async directoryEntry(){const e=await this.stat();return this.dirent??=null==e?void 0:new Y.DirectoryEntry(this.dir,new Y.StatDirent(this.base,e))}directoryEntrySync(){return this.dirent??=(0,T.map)(this.statSync(),e=>new Y.DirectoryEntry(this.dir,new Y.StatDirent(this.base,e)))}#qe=(0,z.lazy)(async()=>(await this.directoryEntry())?.children());async childDirectoryEntries(e){const t=await this.#qe();if(null==t||null==e||(0,g.isEmpty)(t))return t;const i=[];for(const r of t)!0===await e(r)&&i.push(r);return i}_directoryEntryChild(e){return this.for(d.default.join(this.nativePath,e.base),e)}async childNames(){const e=await this.childDirectoryEntries();return null==e?void 0:e.map(e=>e.base)}async resolve_(){const e=await this.#$e();return null!=e?e:(this.clearThisAndParent(),this.#$e())}async#$e(){const e=(await(0,ne.readdir_)(this.dir)).filter(e=>(0,q.equalsIgnoreCase)(e.basename,this.base)),t=(0,I.leastBy)(e,e=>(0,$.hamming)(e.basename,this.base));return this.bflog().tap({msg:"resolve()",result:t?.basename===this.base?this:(0,T.map)(t,e=>this.forSiblingSimpleDirent(e)),meta:{sibs:e}})}async*iterateDir_(){for await(const e of(0,ne.iterateDir_)(this.nativePath))yield this.forSiblingDirent(e)}async children_(e){const t=await(0,ne.readdir_)(this.nativePath);return null!=e&&await(0,g.filterInPlaceAsync)(t,e),t.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){const t=await this.childDirectoryEntries(async t=>t.isFile()&&(null==e||!0===await e(t)));return null==t?void 0:t.map(e=>this._directoryEntryChild(e))}async childDirectories(e){const t=await this.childDirectoryEntries(async t=>t.isDirectory()&&(null==e||!0===await e(t)));return null==t?void 0:t.map(e=>this._directoryEntryChild(e))}childrenSync(){return this.descendantsSync(void 0,()=>!1)}childFilesSync(){return this.descendantsSync(e=>e.isFileSync(),()=>!1)}descendantsSync(e,t){const i=[];return this.trapSync("childrenSync",()=>{for(const r of(0,u.readdirSync)(this.nativePath,{withFileTypes:!0})){const s=Y.DirectoryEntry.fromDirent(this.nativePath,r);r.isDirectory()&&!1!==t?.(s)&&i.push(...this.join(r.name).descendantsSync(e,t)),!1!==e?.(s)&&i.push(this.join(r.name))}}),i}async hasChildren(e){if((0,g.isEmpty)(e))try{if(await this.isDirectory())for await(const e of(0,ne.iterateDir_)(this.nativePath))return!0;return!1}catch(e){return this.bflog().warn("hasChildren()",e),!1}for(const t of e)if(!await(0,le.exists)((0,d.join)(this.nativePath,t)))return!1;return!0}async*descendantsIterable(e,t){for await(const i of(0,ne.iterateDir_)(this.nativePath)){const r=Y.DirectoryEntry.fromDirent(this.nativePath,i),s=this._directoryEntryChild(r);i.isDirectory()&&!1!==await(t?.(r))&&(yield*s.descendantsIterable(e,t)),!1!==await(e?.(r))&&(yield s)}}async*descendantFilesIterable(e,t){for await(const i of this.descendantsIterable(e,t))await i.isFile()&&(yield i)}async descendants(e,t){return(0,P.iterToA)(this.descendantsIterable(e,t))}async siblings(e){const t=this.parent();return(await this.siblingDirectoryEntries(e))?.map(e=>t._directoryEntryChild(e))}async siblingDirectoryEntries(e){return this.parent().childDirectoryEntries(async t=>t.base!==this.base&&(null==e||!0===await e(t)))}get pathnames(){return(0,te.splitNativePath)(this.nativePath)}pathsForDateParsing(){return(0,g.compactBlanks)([...this.isRoot?[]:this.parent().pathnamesWithoutDrive,(0,I.leastBy)((0,G.bname)(this.name),e=>e.length)])}get pathnamesWithoutDrive(){return W.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return(0,re.pathDepth)(this)}get isRoot(){return(0,te.pathIsRoot)(this)}root(e=0){return this.depth<=e?this:this.parent().root(e)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(e,t){return(0,ie.containedByNativePath)({ancestor:this,descendant:e,...t})}isDescendantOf(e){return(0,ie.containedByNativePath)({descendant:this,ancestor:e})}isSelfOrDescendantOf(e){return null!=e&&(this.nativePath===(0,oe.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:0===e?this:this.parent().ancestor(e-1)}findSelfOrAncestor(e){return e(this)?this:this.isRoot?void 0:this.parent().findSelfOrAncestor(e)}parents(){const 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){const t=(0,Q.normalizeExt)(e);return null==t?this.sibling(this.name):this.sibling(this.name+"."+t)}siblingOf(e){return this.nativePath!==e.nativePath&&this.dir===e.dir}join(...e){return(0,g.isEmpty)(e)||(0,w.eql)(["."],e)||e.every(v.blank)?this:(0,te.isAbsolute)(e[0])?this.for(d.default.join(...e)):this.for(d.default.join(this.nativePath,...e))}child(...e){if((0,g.isEmpty)(e))return this;const t=(0,S.flatten)(e.map(e=>e.split(d.default.sep))).filter(e=>".."!==e);return this.join(...t)}async trap(e,t,i="warn"){try{return await(0,O.time)({name:"fs."+e,p:t,meta:{path:this.nativePath}})}catch(t){return void this.bflog().log(i,`trap: ${e}() failed`,{error:t})}}trapSync(e,t,i){try{return(0,O.timeSync)({name:"fs."+e,t})}catch(t){return void this.bflog().log(i??"warn",`${e}() failed`,{error:t})}}stat_(){return(0,le.stat_)(this.nativePath)}#We=void 0;async stat(e){return e?.refresh&&(this.#We=void 0),this.#We??=await(0,le.statMaybe)(this.nativePath,e?.logLevel??"trace")}statSync(e){return e?.refresh&&(this.#We=void 0),this.#We??=(0,ue.statSync)(this.nativePath)}async exists(e){return e?.refresh&&(this.dirent=void 0),null!=this.dirent||null!=await this.stat(e)}existsSync(e){return(e?.refresh??1)&&(this.dirent=void 0),null!=this.dirent||null!=this.statSync(e)}async notExists(e){return null==await this.stat({refresh:!0,...e})}async isDeleted(e=3){if(e=(0,_.clamp)(0,25,e),await this.exists({refresh:!0}))return this.bflog().tap({result:!1,msg:"isDeleted(): file exists"});if(this.isRoot||e<=0)return this.bflog().tap({result:void 0,msg:"isDeleted(): isRoot() and doesn't exist (volume is just unmounted)"});const t=await this.parent().isDeleted(e-1);return null==t?this.bflog().tap({result:void 0,msg:"isDeleted(): parent().isDeleted was undefined",meta:{parentIsDeleted:t}}):this.bflog().tap({result:!0,msg:"isDeleted(): parent was either deleted or not deleted: either way, that means I am deleted.",meta:{parentIsDeleted:t}})}async mtime(){const e=await this.stat();return null==e?void 0:e.mtime}async mtimeMs(e){const t=await this.stat(e);return null==t?void 0:Math.floor(t.mtimeMs)}mtimeMsSync(e){return(0,_.mapNumeric)(this.statSync(e)?.mtimeMs,Math.floor)}async statTimes(){const e=await this.stat();return null==e?void 0:(0,le.statTimes)(e)}async maxStatMs(){const e=await this.statTimes();return null==e?void 0:(0,C.max)(e)}async minStatMs(){const e=await this.statTimes();return null==e?void 0:(0,H.min)(e)}async minStatDate(){const e=await this.minStatMs();return null==e?void 0:new Date(e)}async size(e){const t=await this.stat(e);return null==t?void 0:t.size}async size_(){return(await this.stat_()).size}async isExecutable(){return(0,K.access)({stat:await this.stat(),r:!0,x:!0})}async isReadable(){return(0,K.access)({stat:await this.stat(),r:!0})}isNotReadable(){return(0,F.thenNot)(this.isReadable())}async isReadWritable(){return(0,K.access)({stat:await this.stat(),r:!0,w:!0})}isNotReadWritable(){return(0,F.thenNot)(this.isReadWritable())}async isReadWriteExecutable(){return(0,K.isStatRWX)(await this.stat(),this.nativePath)}isReadWriteExecutableSync(){return(0,K.isStatRWX)(this.statSync(),this.nativePath)}async isReadWriteExecutable_(){return(0,K.isStatRWX)(await this.stat_(),this.nativePath)}async isReadWriteDirectory(){const e=await this.stat();return!0===e?.isDirectory()&&(0,K.isStatRWX)(e,this.nativePath)}async maybeReadWriteDirectory(){return!0!==await this.isFile()&&(await this.isDirectory()?this.isReadWriteExecutable():this.parent().maybeReadWriteDirectory())}isHiddenBasename(){return(0,te.isHiddenBasename)(this.base)}async isEmptyOrMissing(e=0){if(await this.isDirectory())return(0,g.isNotEmpty)(await this.childNames());{const t=await this.size();return null==t||t<=e}}isNonEmpty(e=1){return(0,F.thenNot)(this.isEmptyOrMissing(e))}async isEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null==t||t.isFile()&&t.size<e}async isNonEmptyFile(e=1){const t=await this.stat({logLevel:"trace"});return null!=t&&t.isFile()&&t.size>=e}async isDirectory_(){return null!=this.dirent?this.dirent.isDirectory():(await this.stat_()).isDirectory()}async isDirectory(e){return!0===e?.refresh&&(this.dirent=void 0),this.dirent?.isDirectory()??(await this.stat(e))?.isDirectory()??!1}async isNotDirectory(){return(0,F.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(null!=this.dirent)return this.dirent.isFile();const e=await this.stat_();return null!=e&&e.isFile()}async isFile(){return!0===await this.trap("isFile()",()=>this.isFile_())}isFileSync(){return null!=this.dirent?this.dirent.isFile():(0,k.opt)(this.statSync()).filter(e=>e.isFile()).isDefined}async rmdir(e="warn"){return this.clear(),await this.trap("rmdir",async()=>(await(0,y.retryOnReject_)(()=>(0,c.rmdir)(this.nativePath),{maxRetries:8,retryDelay:500,errorIsRetriable:j.isRetriableError}),!0),e)??!1}rmdirSync(e="warn"){return this.clear(),this.trapSync("rmdirSync",()=>{for(let e=0;e<=8;e++)try{return(0,u.rmdirSync)(this.nativePath),!0}catch(t){if(e<8&&!0===(0,j.isRetriableError)(t))continue;throw t}return!0},e)??!1}async mkdirp_(){if(this.isRoot||await this.isDirectory({refresh:!0}))return this;if(await(0,te.mkdirp_)(this.nativePath),!1===await(0,L.untilTrue)(()=>this.isDirectory({refresh:!0}),{timeoutMs:2*b.secondMs,intervalMs:200}))throw new 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(0,te.mkdirpSync_)(this.nativePath),this.clearThisAndParent()}mkdirpSync(){return this.isRoot?this:this.trapSync("mkdirpSync",()=>this.mkdirpSync_())}sha_(){return(0,ee.fileSha_)(this.nativePath)}async sha(){return this.trap("sha",()=>this.sha_())}async shaMs(){return this.trap("shaMs",async()=>(await(0,ee.fileShaMeta_)(this,{autoInvalidate:!1})).elapsedMs)}async sha256_(){const e=(0,l.createHash)("sha256");return await(0,f.pipeline)([(0,u.createReadStream)(this.nativePath),e]),e.digest("hex")}async readJson_(){return(0,M.parseJSON)((await(0,c.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",()=>(0,M.parseJSON)((0,u.readFileSync)(this.nativePath).toString()),e)??void 0}readFileSync_(){return(0,u.readFileSync)(this.nativePath)}readFile_(){return(0,c.readFile)(this.nativePath)}readFile(e="warn"){return this.trap("readFile",()=>this.readFile_(),e)}async readText_(){return(0,N.bufferToString)(await this.readFile_())}readText(e="warn"){return this.trap("readTextFile",()=>this.readText_(),e)}async zReadFile_(e){return(0,he.zCopyToBuffer_)(this.nativePath,e)}async zcat(e){return this.trap("zcat",async()=>{const t=await this.zReadFile_(e);return null==t?void 0:(0,D.toS)(t)})}async readLines(e="warn"){const t=await this.readText(e);return null==t?void 0:(0,J.splitLines)(t)}readFileSync(e="warn"){try{return(0,u.readFileSync)(this.nativePath).toString()}catch(t){return void this.bflog().log(e,"readFileSync() failed",{error:t})}}async writeText_(...e){return await(0,de.writeText_)(this.nativePath,...e),this}writeTextSync_(...e){return(0,de.writeTextSync_)(this.nativePath,...e),this}async writeFile_(e){return await(0,de.writeFile_)(this.nativePath,e),this}writeJsonSync(e,t){return this.trapSync("writeJsonSync",()=>this.writeJsonSync_(e,t))}writeJsonSync_(e,t){const i=!0===t?.sortKeys?(0,U.sortedKeys)(e):e;(0,de.writeFileSync_)(this.nativePath,(0,M.stringify)(i,t?.spaces)+"\n")}async writeJson(e,t){return this.trap("writeJson",()=>this.writeJson_(e,t))}async writeJson_(e,t){await(0,te.mkdirp_)(this.dir);const i=!0===t?.sortKeys?(0,U.sortedKeys)(e):e;return await(0,c.writeFile)(this.nativePath,(0,M.stringify)(i,t?.spaces)+"\n",{...(0,E.omit)(t??{},"spaces","sortKeys"),flush:!0}),this.clearThisAndParent(),this}async matchesContent(e){const t=await Promise.all([this.stat({refresh:!0}),e.stat({refresh:!0})]);if(null==t[0]||null==t[1]||t[0].size!==t[1].size)return!1;const i=await Promise.all([this.sha(),e.sha()]);return i[0]===i[1]}async touch(e={}){return this.trap("touch",()=>this.touch_(e))}async touch_(e={}){return await(0,ce.touch_)({...e,file:this,ensureFile:!0}),this.clearThisAndParent()}async utimes(e={}){return this.trap("utimes",async()=>(await(0,ce.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,u.unlinkSync)(this.nativePath)}catch(e){if("ENOENT"!==e.code)throw e}finally{this.clearThisAndParent()}}unlinkSync(e="info"){return this.trapSync("unlinkSync",()=>this.unlinkSync_(),e)}async unlink_(){try{await(0,c.unlink)(this.nativePath)}catch(e){if("ENOENT"!==e.code)throw e}return this.clearThisAndParent()}async rmrf(e="info"){return this.trap("rmrf",()=>this.rmrf_(),e)}async rmrf_(){const e=await this.isDirectory({refresh:!0});return await(0,y.retryOnReject_)(()=>(0,c.rm)(this.nativePath,{recursive:e,force:!0}),{maxRetries:(0,x.ending)()?1:3,timeoutMs:0,retryDelay:b.secondMs,errorIsRetriable:j.isRetriableError}),this.clearThisAndParent()}async#Ge(e,t){return this.trap("pipeTo("+e+")",async()=>{const i=await this.sibling(e).ensureNew_();return await(0,f.pipeline)([(0,u.createReadStream)(this.nativePath,{autoClose:!0}),t,(0,u.createWriteStream)(i.nativePath,{autoClose:!0})]),await this.unlink(),i})}async gzip(){return this.#Ge(this.base+".gz",p.default.createGzip())}async compressBrotli(){return this.#Ge(this.base+".br",p.default.createBrotliCompress())}async ensureFile_(){return await(0,te.ensureFile_)(this.nativePath),this.clearThisAndParent()}ensureFile(){return this.trap("ensureFile",()=>this.ensureFile_())}ensureFileSync_(){return(0,te.ensureFileSync_)(this.nativePath),this.clearThisAndParent()}ensureNewNativePath_(e){return(0,Z.ensureNewNativePath_)({nativePath:this.nativePath,...e})}async ensureNew_(e={}){return this.for(await this.ensureNewNativePath_(e)).clearThisAndParent()}ensureNewSync_(e={}){return this.for((0,Z.ensureNewNativePathSync_)({nativePath:this.nativePath,...e}))}async chmod_(e){return await(0,c.chmod)(this.nativePath,e),this.clear()}async chmod(e){try{return await this.chmod_(e),this}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}chmodSync(e){try{return(0,u.chmodSync)(this.nativePath,e),this.clear()}catch(t){return void this.bflog().warn("failed to chmod to "+e.toString(8),t)}}async siblingWithSameContents(){return this.parent().childWithSameContents(this)}async childWithSameContents(e){return(0,O.time)({name:"fs.childWithSameContents",p:async()=>{if(!await this.isDirectory())return;const t=await e.size();if(null==t)return;if(!this.$eql(e.parent())){const t=this.join(e.base);if(await e.matchesContent(t))return t}const i=await this.children(async i=>!i.isNameHidden()&&t===i.size()&&i.nativePath!==e.nativePath);if((0,g.isEmpty)(i))return;const r=await e.sha();if(null!=r)for(const e of i.sort((e,t)=>-(0,$.diceCoeff)(e.base,t.base)).slice(0,64))if(await e.sha()===r)return e}})}watchUntil(e){const t=new A.Deferred("watchUntil("+this.nativePath+")");e.timeoutMs>0&&t.setTimeout(e.timeoutMs);const i=Math.ceil((0,_.toGt0)(e.intervalMs)??500),r=(0,R.trailingThrottle)({minDelayMs:(0,_.clamp)(25,b.secondMs,Math.ceil(i/5)),fn:async(i,r)=>{try{if(t.isResolved)return;const s=await e.f(i,(0,T.denull)(r));this.bflog().debug("watchUntil().debouncedApply",{result:s,event:i,filename:r}),null!=s&&!1!==s&&(e.accept?.(s)??1)&&t.resolve(s)}catch(e){t.reject(e)}}});if(r(),ge)try{const i=(0,u.watch)(this.nativePath,{persistent:e.persistent,recursive:e.recursive,encoding:"utf8"},r);return t.finally(()=>{i.close()}),t}catch(t){this.bflog().warn("fs.watch failed, we need to resort to polling",{error:t,opts:e}),e.intervalMs=i}if(!ge||(0,_.gt0)(e.intervalMs)){const s=setInterval(()=>r(),i);e.persistent||s.unref(),t.finally(()=>{r.reset(),clearInterval(s)})}return t}}t.BaseFile=pe;let ge=!0},19748(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAssetFileExtension=t.isVideoExtension=t.isBrowserExtension=void 0,t.excludedPathFilter=function(e){const t=new r.CaseInsensitiveSet(e);return e=>(0,o.toPathnames)(e.nativePath)?.every(e=>!t.has(e))??!1},t.extFilter=l;const r=i(36638),s=i(28874),n=i(88840),a=i(14036),o=i(51704);function l(e){return t=>s.Settings.respectFileExtensions.valueOrDefault?(0,a.isExtType)(t?.ext,e):null}t.isBrowserExtension=l(n.ExtTypes.SupportedByCurrentBrowser),t.isVideoExtension=l(n.ExtTypes.Video),t.isAssetFileExtension=l(n.ExtTypes.Media)},84542(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Newline=void 0,t.crlf=function(...e){const t=e.map(a.toS).join("\n");return o.isWin?t.replace((0,n.newlineRe)(),"\r\n"):t},t.splitLines=l,t.joinLines=function(...e){return l(...e).join(t.Newline)},t.splitCompactLines=function(...e){return(0,r.compactBlanks)(l(...e))};const r=i(40958),s=i(96249),n=i(51926),a=i(54993),o=i(43334);function l(...e){return(0,s.flatten)(e.map(e=>Array.isArray(e)?l(...e):(0,a.toS)(e).split((0,n.newlineRe)())))}t.Newline=o.isWin?"\r\n":"\n"},70698(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CACHEDIR_TAG_CONTENT=t.CACHEDIR_TAG=void 0,t.isCachedirTagDirectory=async function(e){return h((0,r.join)((0,u.toNativePath_)(e),t.CACHEDIR_TAG))},t.isCachedirTagFile=h,t.writeCachedirTag_=async function(e){const i=(0,u.toNativePath_)(e);await(0,o.mkdirp_)(i),await(0,c.writeTextfile_)((0,o.joinNativePath)([i,t.CACHEDIR_TAG]),t.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 "+a.version,"#","# See https://bford.info/cachedir/ for details about this file")};const r=i(76760),s=i(19851),n=i(50213),a=i(37805),o=i(29882),l=i(93854),u=i(17217),c=i(73428);t.CACHEDIR_TAG="CACHEDIR.TAG",t.CACHEDIR_TAG_CONTENT="Signature: 8a477f597d28d172789f06886806bc55";const d=(0,s.lazy)(()=>(0,n.mkLogger)("fs.CachedirTag"));async function h(e){if((0,u.basename)(e)!==t.CACHEDIR_TAG)return!1;try{const i=(await(0,l.readFilePart_)({nativePath:(0,u.toNativePath_)(e),position:0,length:t.CACHEDIR_TAG_CONTENT.length}))?.buffer?.toString();return i===t.CACHEDIR_TAG_CONTENT}catch(t){return d().trace("isCachedirTagFile(): failed to read "+e,t),!1}}},92234(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.removeBlanksAndDuplicates=p,t.defaultMacOSPaths=g,t.defaultPosixPaths=y,t.defaultDockerPaths=v,t.systemDrive=function(){return m.isWin?(0,u.toNotBlank)(o.env.SystemDrive)??"C:":"/"},t.defaultWinPaths=M,t.defaultPaths=function(){const e=(0,f.isDocker)()?v():m.isWin?M():m.isMac?g():y();if((0,m.isElectron)()){const t=process.resourcesPath;(0,u.blank)(t)||e.push(n.default.join(t,"tools"))}return p(e)};const s=i(51455),n=r(i(76760)),a=r(i(58152)),o=i(1708),l=i(40958),u=i(22573),c=i(41400),d=i(34102),h=i(19851),f=i(45969),m=i(43334);function p(e){return(0,l.compactBlanks)((0,l.uniq)(e))}function g(){return p(["/opt/homebrew/bin","/opt/homebrew/sbin",...y()])}function y(){return p(["/usr/local/bin","/usr/local/sbin","/opt/local/bin","/opt/local/sbin","/usr/lib/libraw","/usr/sbin","/usr/bin","/sbin","/bin"])}function v(){return["/opt/photostructure/tools",...y()]}const b=(0,h.lazy)(()=>[]);async function w(e){try{return await(0,s.readdir)(e)}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return[];throw e}}async function S(e){try{return(await(0,s.stat)(e)).isDirectory()}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}async function P(){const e=(0,l.compactBlanks)([(0,u.mapNotBlank)(o.env.LOCALAPPDATA,e=>a.default.join(e,"Microsoft","WinGet","Packages")),(0,u.mapNotBlank)(o.env.ProgramFiles,e=>a.default.join(e,"WinGet","Packages"))]),t=[];for(const i of e)for(const e of await w(i)){if(!e.startsWith("Gyan.FFmpeg_"))continue;const r=a.default.join(i,e);for(const e of await w(r)){if(!e.startsWith("ffmpeg-"))continue;const i=a.default.join(r,e,"bin");await S(i)&&t.push(i)}}b.set(t)}function M(){const e=m.isWin?(0,u.toNotBlank)(o.env.SystemDrive)??"C:":"C:",t=(0,u.toNotBlank)(o.env.SystemRoot)??"C:\\WINDOWS",i=(0,u.toNotBlank)(o.env.ProgramData)??"C:\\ProgramData";return p([t,a.default.join(t,"System32"),a.default.join(e,"msys64","mingw64","bin"),...b(),(0,u.mapNotBlank)(o.env.ChocolateyInstall,e=>a.default.join(e,"bin")),a.default.join(i,"chocolatey","bin")])}(0,c.later)(()=>{P(),(0,d.ee)().on("clearToolCache",()=>{P()})})},67732(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirWatcher=void 0;const r=i(16242),s=i(40958),n=i(45599),a=i(59455),o=i(25764),l=i(38836),u=i(8769),c=i(50213),d=i(29882),h=i(17217),f=i(68284),m=(0,n.defer)(()=>(0,c.mkLogger)("fs.DirWatcher"));class p extends l.EndableWrapper{nativePath;subscription;static async for(e,t,i=o.EndableRanks.first){const n=(0,h.toNativePath_)(e);await(0,d.mkdirp_)(n);const l=await(0,r.subscribe)(n,async(e,i)=>{m().trace("callback",{file:n,error:e,arr:i}),null!=e&&(0,u.onError)("FsWatcher error",{cause:e,path:n});const r=[];for(const e of(0,a.toA)(i)){if((0,d.isHiddenBasename)(e.path))continue;const t=(0,f.statSync)(e.path);(null==t||t.isFile())&&r.push(e)}(null!=e||(0,s.isNotEmpty)(r))&&t(e,r)});return new p(n,l,i)}constructor(e,t,i){super("fs.DirWatcher("+e+")",()=>this.close(),i),this.nativePath=e,this.subscription=t}close=(0,n.defer)(()=>this.subscription.unsubscribe())}t.DirWatcher=p},89968(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DirectoryEntry=t.StatDirent=void 0,t.toFileMeta=M,t.getFileType=function(e){return e instanceof s.default.Stats?{isFile:e.isFile(),isDirectory:e.isDirectory()}:(0,u.pick)(e,"isFile","isDirectory")},t.eqlFileMeta=function(e,t){return null!=e&&null!=t&&(0,h.eql)(M(e),M(t))};const s=r(i(73024)),n=r(i(51455)),a=i(76760),o=i(57975),l=i(19851),u=i(68708),c=i(32639),d=i(59455),h=i(23467),f=i(50213),m=i(81168),p=i(34102),g=i(29882),y=i(65238),v=i(14427),b=i(17217),w=i(16287),S=i(68284);class P{base;isFile;isDirectory;size;mtimeMs;constructor(e,t){this.base=e,(0,v.isSimpleDirent)(t)?(this.isFile=t.isFile,this.isDirectory=t.isDirectory):(this.isFile=t.isFile(),this.isDirectory=t.isDirectory()),t instanceof s.default.Stats&&(this.size=t.size,this.mtimeMs=t.mtimeMs)}}function M(e){return{size:(0,c.isFunction)(e.size)?e.size():e.size,mtimeMs:(0,c.isFunction)(e.mtimeMs)?e.mtimeMs():e.mtimeMs,isFile:(0,c.isFunction)(e.isFile)?e.isFile():e.isFile,isDirectory:(0,c.isFunction)(e.isDirectory)?e.isDirectory():e.isDirectory}}t.StatDirent=P;const T=(0,l.lazy)(()=>(0,f.mkLogger)("fs.DirectoryEntry"));class _{dir;dirent;nativePath;ext;constructor(e,t){this.dir=e,this.dirent=t,this.nativePath=(0,a.join)(this.dir,t.base),this.ext=(0,g.parseNativePath)(t.base).ext}static fromSimpleDirent(e,t){return new _(e,new P(t.basename,t))}static fromDirent(e,t){return new _(e,new P(t.name,t))}static fromJSON(e){const t=(0,a.join)(e.dir,e.base),i=(0,S.statSync)(t);return null==i?e:new _(e.dir,new P(e.base,i))}static async for(e){try{return await this.for_(e)}catch{return}}static async for_(e){const{nativePath:t,dir:i,base:r}=(0,b.isSimpleFile)(e)?e:{nativePath:e,...(0,g.parseNativePath)(e)},s=await n.default.stat(t);return new _(i,new P(r,s))}clear(){return(0,p.ee)().emitSync("fileChanged",this.nativePath),this.dirent.size=void 0,this.dirent.mtimeMs=void 0,this}async join(...e){return _.for((0,a.join)(this.nativePath,...e))}get base(){return this.dirent.base}get name(){return(0,m.stripSuffix)(this.base,this.ext)}get pathnames(){return this.nativePath.split(a.sep)}get parentAndBase(){return this.pathnames.slice(-2).join("/")}get parentBasename(){return(0,g.parentBasename)(this.nativePath)}toJSON(){return{dir:this.dir,base:this.base}}toLogJSON(){return this.nativePath}[o.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,a.parse)(this.dir).dir}isNameHidden(){return this.name.startsWith(".")}parent(){const e=(0,g.parseNativePath)(this.dir);return e.dir===this.dir?this:new _(e.dir,{base:e.base,isFile:!1,isDirectory:!0,mtimeMs:void 0,size:void 0})}async childNames(){try{return this.isDirectory()?(await(0,y.readdir)(this.nativePath))?.map(e=>e.basename):void 0}catch(e){return void T().warn("childNames() failed to readdir("+this.nativePath+")",e)}}async children(){try{if(!this.isDirectory())return;const e=await(0,y.readdir)(this.nativePath);return e?.map(e=>_.fromSimpleDirent(this.nativePath,e))}catch(e){return void T().warn("children() failed to readdir("+this.nativePath+")",e)}}childFromDirent(e){return new _(this.nativePath,new P(e.name,e))}childrenSync(){try{if(!this.isDirectory())return;const e=s.default.readdirSync(this.nativePath,{withFileTypes:!0});return(0,m.sortByCaseInsensitive)(e,e=>e.name).map(e=>new _(this.nativePath,new P(e.name,e)))}catch(e){return void T().warn("children() failed to readdir("+this.nativePath+")",e)}}async childDirectories(){return(0,d.toA)(await this.children()).filter(e=>e.isDirectory())}async childFiles(){return(0,d.toA)(await this.children()).filter(e=>e.isFile())}visitDescendantsSync(e){const t=this.childrenSync();if(null!=t){for(const i of t)i.isFile()&&e(i);for(const i of t)i.isDirectory()&&(i.visitDescendantsSync(e),e(i))}}async*descendantsIterable_(){const e=await n.default.readdir(this.nativePath,{withFileTypes:!0});(0,m.sortByCaseInsensitive)(e,e=>e.name);for(const t of e)t.isDirectory()&&(yield*this.childFromDirent(t).descendantsIterable_());for(const t of e)yield this.childFromDirent(t)}async*descendantsIterable(){const e=await this.children();for(const t of e??[])t.isDirectory()&&(yield*t.descendantsIterable());for(const t of e??[])yield t}statDirent(){const e=(0,S.statSync)(this.nativePath);return null==e?void 0:this.dirent=new P(this.base,e)}async stat(){try{const e=await(0,w.stat_)(this.nativePath);return this.dirent=new P(this.base,e),e}catch{return}}size(){return this.dirent?.size??this.statDirent()?.size}mtimeMs(){return this.dirent?.mtimeMs??this.statDirent()?.mtimeMs}async unlink_(){try{await n.default.unlink(this.nativePath)}catch(e){if("ENOENT"!==e.code)throw e}await(0,p.ee)().emit("fileChanged",this.nativePath)}async rmdir_(){await n.default.rmdir(this.nativePath),await(0,p.ee)().emit("fileChanged",this.nativePath)}}t.DirectoryEntry=_},20197(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultEnsureNewOptions=void 0,t.ensureNewNativePath_=async function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if(await(0,a.mkdirp_)(r.dir),!i.requireNumber&&await(0,o.isEmptyFile)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if(await(0,o.isEmptyFile)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)},t.ensureNewNativePathSync_=function(e){const i={...t.DefaultEnsureNewOptions,...e},r=(0,a.parseNativePath)(i.nativePath);if((0,a.mkdirpSync_)(r.dir),!i.requireNumber&&(0,l.isEmptyFileSync)(i.nativePath,i))return i.nativePath;for(let e=i.startIndex;e<=i.maxVersions;e++){const t=s.default.join(r.dir,`${r.name}-${(0,n.leftPad)(e,i.leftPad,"0")}${r.ext}`);if((0,l.isEmptyFileSync)(t,i))return t}throw new Error("There are already more than "+i.maxVersions+" of "+i.nativePath)};const s=r(i(76760)),n=i(39926),a=i(29882),o=i(16287),l=i(68284);t.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1})},92423(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.notExcludedDirs=t.shouldDescendIntoDirectory=t.excludeBundles=t.excludeGlobs=t.defaultFilePredicates=t.defaultDirPredicates=void 0,t.formatPathForGlob=L,t.excludedFilePredicates=G,t.whyExcludedFile=K,t.isExcludedFile=function(e){return null!=K(e)},t.excludedDirPredicates=J,t.whyExcludedDirectory=Y,t.isExcludedDirectory=async function(e){return null!=await Y(e)},t.whyExcludedDirectoryRecursive=async function(e){const i=(0,t.notExcludedDirs)();for(let t=e;null!=t&&!t.isRoot;t=await(t?.parent())){if(i.includes(t?.nativePath))return;const e=await Y(t);if(null!=e)return e}},t.notInInternalPhotoStructureDir=Q;const s=r(i(83058)),n=i(19851),a=i(40958),o=i(76790),l=i(22573),u=i(55835),c=i(51926),d=i(54993),h=i(48884),f=i(9092),m=i(54557),p=i(50213),g=i(88158),y=i(56519),v=i(49776),b=i(46292),w=i(32551),S=i(87290),P=i(57902),M=i(43334),T=i(78984),_=i(33995),E=i(28874),k=i(83278),D=i(48313),I=i(85772),C=i(78133),A=i(46356),x=i(17217),F=(0,n.lazy)(()=>(0,p.mkLogger)("fs.ExcludeGlobs")),O=new m.FifoCache({maxSize:256}),R=/[\\/]$/;function L(e){const t=(0,d.toS)(e),i=O.getSync(t);if(null!=i)return i;const r=(0,x.isSimpleFile)(e)?e:k.BaseFile.for(e),s=R.test(t)||r.isDirectorySync(),n=(0,C.native2posix)(r.nativePath),a=s?(0,c.ensureSuffix)(n,"/"):n;return O.set(t,a),O.set(a,a),O.set(r.nativePath,a),a}class N{pattern;desc;exclude;reason;re;bundle;valid;constructor(e,t,i=!0){if(this.pattern=e,this.desc=t,this.exclude=i,e.includes("\\")){const t=e;e=(0,C.native2posix)(t),F().warn("globToPredicate(): backslash in patterns aren't supported: assuming you meant forward-slash?",{given:t,input:e})}this.reason=(0,a.compactBlanks)([this.exclude?"not":"",t,"("+(0,c.ellipsize)(e,48,12)+")"]).join(" ");try{this.re=s.default.makeRe(this.pattern,{nocase:E.Settings.globsCaseInsensitive.valueOrDefault,dot:!0}),this.valid=!0}catch(e){this.valid=!1,F().warn("Cannot parse pattern",{glob:this.pattern,error:e})}this.bundle=this.valid&&null!=this.re?(0,g.pairToObject)(this.reason,this.#D.bind(this)):{}}#D(e){const t=L(e),i=this.re?.test(t)??this.exclude,r=i?!this.exclude:this.exclude;return F().tap({msg:"apply()",level:P.LogLevels.trace,result:r,meta:{desc:this.desc,pattern:this.pattern,exclude:this.exclude,posixPath:t,matched:i}})}}class j{#Ke=[];push(...e){for(const t of e){if(!t.valid){F().warn("Ignoring invalid glob",{glob:t});continue}const e=this.#Ke.find(e=>e.pattern===t.pattern);null==e?this.#Ke.push(t):F().debug("Ignoring duplicate glob",{glob:t,prior:e})}}pushNativePath(e,t){this.push(new N((0,C.native2posix)(e),t))}toA(){return this.#Ke}}const B=new N("**/.*","hidden file"),z=new N("**/.*/","hidden directory"),V=(0,n.lazy)(()=>{const e=new j;e.push(z,B);for(const t 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 N((M.isWin?"*":"")+"/"+t.s+"/",t.desc));if(M.isWin)for(const t of["ProgramFiles","ProgramFiles(x86)","ProgramW6432","SystemRoot","windir"]){const i=process.env[t];(0,l.blank)(i)||e.pushNativePath(i,`%${t}%`)}M.isLinux&&(e.push(new N(`${(0,w.homeDir)()}/snap/`,"Snap software")),e.push(new N("/run/","Linux runtime data")));for(const t of[{s:"__MACOSX",desc:"macOS resource fork"},{s:"_includes",desc:"code"},{s:"@eaDir",desc:"Synology thumbnail"},{s:"@Recently-Snapshot",desc:"QNAP snapshot"},{s:"@Recycle",desc:"QNAP trash"},{s:"@SynoResource",desc:"Synology metadata"},{s:"#recycle",desc:"Synology trash"},{s:"#snapshot",desc:"Synology snapshot"},{s:"$Recycle.Bin",desc:"Windows trash"},{s:"$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 N("**/"+t.s+"/",t.desc));function t(t,i,r){if(!(0,l.blank)(t)){const s=(0,o.sort)((0,a.uniq)((0,a.compactBlanks)(i).map(e=>e.toLowerCase())));1===s.length&&e.push(new N(`**/${t}/${s[0]}/`,r)),s.length>1&&e.push(new N(`**/${t}/(${s.join("|")})/`,r))}}(0,u.map)((0,b.configDir)(),t=>e.pushNativePath(t,"PhotoStructure configuration")),t("nix",["store"],"NixOS package"),e.push(new N("**/*.(photo|photos|ap)library/!(master|masters|modified|original|originals)/","Apple Photos/Aperture library")),t("PhotoData",["Metadata"],"iOS Photos metadata"),e.push(new N("**/facetile*","face thumbnail"));const i=["bin","cygdrive","dev","etc","games","include","lib?(32|64|x64)","libexec","local","locale","man","proc","sbin","share","src","tmp","usr","var"];t("usr",i,"FHS system"),t("cygwin?(64)",i,"Cygwin"),t("local",i,"FHS system"),t("Windows",["assembly","Boot","Containers","Cursors","Fonts","Help","Installer","Logs","Microsoft.NET","Servicing","SoftwareDistribution","System32","SystemApps","SysWOW64","Temp","WinSxS"],"Windows"),t("Recovery",["Customizations","OEM"],"Windows"),t("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"],"Linux system package"),t("opt",["google","x11",...i],"FHS package"),t("lfs",["incomplete","objects"],"Git LFS object");const r=["cache","crash","games","lib","local","lock","log","logs","mail","run","snap","spool","tmp"];t("var",r,"Linux /var"),t("mnt",r,"Linux /mnt"),t("dev",["block","bsg","bus","char","cpu","disk","dri","fd","hugepages","input","lightnvm","mapper","mqueue","net","pts","shm","snd","ubuntu-vg","usb","vfio"],"Linux /dev backup"),t("proc",["acpi","asound","bus","driver","fs","ipmi","irq","net","scsi","self","sys","sysvipc","thread-self","tty"],"Linux /proc backup"),t("library",["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"],"macOS Library"),t("packages",["*.pkg","*.mpkg"],"macOS package"),t("src/**",["bin","ci","dist","doc?(s)","etc","lib?(s)","main","spec?(s)","src","test?(s)","tools","util"],"code"),t("docs",["admin","content","general","generated","sql"],"code"),t("pkg",["acceptance","ccl","cli","cmd","server","sql","storage","ui","util","workload"],"code"),t("osv",["apps","arch","compiler","external","include","java","modules","musl","tests"],"code"),t("go",["bin","blog","cmd","doc","lib","misc","pkg","src","test","vt"],"code"),t("Perl?(64)",["bin","eg","etc","html","lib","site"],"code"),t("Python*",["dlls","doc?(s)","include","lib?(s)","scripts","tools","tcl"],"code"),t("Ruby*",["bin","include","lib","msys*","packages","share","ssl"],"code"),t("msys*",["clang*","dev","etc","mingw*","tmp","ucrt*","var"],"code"),t("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"],"code"),t("test",["fixtures"],"code"),t("data",["$of"],"windows backup"),t("System",["Applications","Developer","DriverKit","Library","iOSSupport","Update","Preboot"],"macOS System"),t("Volumes/Data",["Applications","etc","mnt","private","sw","System","tftpboot","tmp","usr","var"],"macOS System"),t("contents",["frameworks","plugins","resources","sharedsupport"],"macOS application"),t("pg",["pgsql"],"code");for(const e of["local","locallow","roaming"])t("appdata",[e],"Windows default AppData");return e.toA()}),H=()=>{t.excludeGlobs.unset(),t.excludeBundles.unset()},U=()=>{t.notExcludedDirs.unset()},W=(0,n.lazy)(()=>{E.Settings.excludeGlobsOmitDefaults.watchLater(H),E.Settings.excludeGlobsAdd.watchLater(H),E.Settings.excludeGlobsOmit.watchLater(H),E.Settings.globsCaseInsensitive.watchLater(H),E.Settings.libraryDir.watchLater(U),E.Settings.originalsDir.watchLater(U),E.Settings.scanPaths.watchLater(U),E.Settings.argvScanPaths.watchLater(U)});t.defaultDirPredicates=(0,n.lazy)(()=>[{notSymlinkLoop:Z,notInInternalPhotoStructureDir:Q,whyNoMedia:I.whyNoMedia,notHidden:X}]),t.defaultFilePredicates=(0,n.lazy)(()=>[{notInInternalPhotoStructureDir:Q}]),t.excludeGlobs=(0,n.lazy)(()=>{W();const e=new f.CaseInsensitiveMap;function t(t){if(null!=t&&t.valid){const i=t.pattern.trim();e.has(i)&&F().warn("Duplicate glob:",{glob:t}),e.set(i,t)}}function i(t){const i=t.trim();e.has(i)?e.delete(i):F().warn(`Failed to find and remove glob specified in ${E.Settings.excludeGlobsOmit.key}`,{glob:t})}if(!E.Settings.excludeGlobsOmitDefaults.valueOrDefault)for(const e of V())t(e);for(const e of E.Settings.excludeGlobsOmit.values)i(e);for(const e of E.Settings.excludeGlobsAdd.values)t(new N(e,`(from ${E.Settings.excludeGlobsAdd.key})`));const r=(0,o.sortBy)(e.values(),e=>(0,a.compactBlanks)(e.pattern.toLowerCase().split("/"))),[s,n]=(0,h.partition)(r,e=>e.pattern.endsWith("/"));return{dir:s,file:n}}),t.excludeBundles=(0,n.lazy)(()=>{const e=(0,t.excludeGlobs)();return{dir:[...(0,t.defaultDirPredicates)(),...e.dir.map(e=>e.bundle)],file:[...(0,t.defaultFilePredicates)(),...e.file.map(e=>e.bundle)]}});const q=[{disableAllFilters:()=>!0}],$=[{notBlank:()=>!1}];function G(e){return E.Settings.disableAllFilters.valueOrDefault?q:(0,l.blank)(e)?$:(0,t.excludeBundles)().file}function K(e){return _.SyncPredicates.whyRejected(e,...G(e))}function J(e){return E.Settings.disableAllFilters.valueOrDefault?q:(0,l.blank)(e)?$:(0,t.excludeBundles)().dir}async function Y(e){return E.Settings.disableAllFilters.valueOrDefault?void 0:T.Predicates.whyRejected(e,...J(e))}function Z(e){return!(0,A.seemsLikeSymlinkLoop)(e)}function X(e){return M.isLinux||!E.Settings.excludeHidden.valueOrDefault||(0,y.thenNot)((0,D.isHidden_)(e))}function Q(e){return!(0,v.isInInternalDir)(e)}t.shouldDescendIntoDirectory=async e=>null==await Y(e),t.notExcludedDirs=(0,n.lazy)(()=>F().tap({msg:"notExcludedDirs() (these directories will never be excluded)",level:"info",result:(0,a.uniq)((0,a.compactBlanks)([(0,S.libraryDirPosixFile)(),(0,S.libraryOriginalsDirPosixFile)(),...E.Settings.argvScanPaths.values,...E.Settings.scanPaths.values]))}))},88561(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileCache=t.InstanceCacheMaxSize=void 0,t.isClearable=f;const r=i(40958),s=i(22573),n=i(68708),a=i(25764),o=i(38836),l=i(55139),u=i(34102),c=i(50213),d=i(88158),h=i(28874);function f(e){return"object"==typeof e&&"function"==typeof e?.clear}t.InstanceCacheMaxSize=256;class m extends l.Cache{clearOnFileChange;constructor(e){super({timeoutMs:h.Settings.taskTimeoutMs.valueOrDefault,ttlMs:h.Settings.metadataCacheMs.valueOrDefault,maxSize:t.InstanceCacheMaxSize,...e}),this.clearOnFileChange=e.clearOnFileChange??!1,(0,u.ee)().on("fileChanged",e=>this.#Je(e)),(0,u.ee)().on("clearCache",()=>this.clear()),h.Settings.emitTimingsOnExit.valueOrDefault&&new o.EndableWrapper(e.name+" stats",async()=>{const t=(0,d.mapEntries)(this.stats(),(e,t)=>t>0?t:void 0);(0,r.isNotEmpty)((0,n.keys)(t))&&(0,c.mkLogger)(e.name).info("stats",t)},a.EndableRanks.stats)}async#Je(e){if((0,s.blank)(e))if(this.clearOnFileChange)for(const[e,t]of this.entries())f(t)?t.clear({emit:!1}):this.delete(e);else this.clear();else await this.deleteIf((t,i)=>!(!t.startsWith(e)||this.clearOnFileChange&&f(i)&&(i.clear({emit:!1}),1)))}}t.FileCache=m},79267(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileCleanup=void 0;const r=i(40958),s=i(42659),n=i(6875),a=i(31586),o=i(78406),l=i(99331),u=i(71371),c=i(34102),d=i(409),h=i(23560),f=i(89968),m=i(85772);class p extends o.EndableInterval{rootNativePath;staleMs;isPrunable;minRetained;cleanup;static for(e){return(0,a.gt0)(e.minRetained)||(0,a.gt0)(e.staleMs)?new p(e.name,e.rootNativePath,e.staleMs,e.isPrunable,e.minRetained):void 0}constructor(e,t,i,r,n=0){super({name:"fs.FileCleanup("+e+")",intervalMs:(0,h.isSyncService)()?(0,a.clamp)(5*s.minuteMs,s.dayMs,i/2):0,callback:()=>this.cleanup()}),this.rootNativePath=t,this.staleMs=i,this.isPrunable=r,this.minRetained=n,this.cleanup=(0,d.rateLimited)({name:this.name,minCallDelayMs:s.minuteMs,f:()=>this.#Ye()})}async#Ze(e){if(!(0,a.gt0)(this.minRetained))return new Set;const t=new u.BoundedGreatestSet(this.minRetained??0,e=>e.mtimeMs()??0);for await(const i of e.descendantsIterable_())i.isFile()&&null!=i.mtimeMs()&&t.add(i);return new Set(t.vacuum().map(e=>e.nativePath))}async#Ye(){try{if((0,l.ending)())return;const e=await this.rootNativePath();if(null==e)return this.logger.debug("_cleanup(): no-op, root is null",e);const t=await f.DirectoryEntry.for(e);if(null==t)return this.logger.debug("_cleanup(): no-op, root is missing",{rootNativePath:e});this.logger.info("cleanup(): starting",{rootNativePath:e,staleMs:(0,n.fmtDuration)(this.staleMs,{sep:" "})});const i=await this.#Ze(t),s=Date.now()-this.staleMs,a=[],o=new Set;for await(const e of t.clear().descendantsIterable())if(this.logger.debug("_cleanup(): visiting "+e),(0,m.isNoMediaName)(e.base)||e.name.toUpperCase().startsWith("README"))this.logger.trace("_cleanup(): skipping NoMedia/README"+e);else if(i.has(e.nativePath))this.logger.trace("_cleanup(): skipping recent file "+e);else if(e.isFile()&&!1===await(this.isPrunable?.(e)))this.logger.trace("_cleanup(): skipping non-prunable file "+e);else{if(!o.has(e.nativePath)){const t=e.mtimeMs();if(null==t){this.logger.warn("_cleanup(): skipping file with no mtime "+e);continue}if(t>=s){this.logger.trace("_cleanup(): skipping file with mtime >= minMtimeTs "+e);continue}}try{e.isDirectory()?(this.logger.trace("_cleanup(): attempting to rmdir "+e),await e.rmdir_(),this.logger.debug("_cleanup(): rmdir "+e)):(this.logger.trace("_cleanup(): attempting to unlink "+e),await e.unlink_(),this.logger.debug("_cleanup(): unlinked "+e)),o.add(e.dir),a.push(e.nativePath)}catch(t){"ENOENT"===t.code&&(this.logger.warn("cleanup(): ENOENT",{file:e,error:t}),await(0,c.ee)().emit("clearCache")),"ENOTEMPTY"!==t.code&&this.logger.warn("cleanup(): failed to rmdir",{file:e,error:t})}}return(0,r.isNotEmpty)(a)&&t.clear(),this.logger.tap({msg:"cleanup("+e+"): done",result:a})}catch(e){return void this.logger.error("cleanup() failed",{error:e})}}}t.FileCleanup=p},32144(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=t.SidecarFiletypes=void 0,t.normalizeExt=p,t.isJpegExt=function(e){return p(e)===c.JpegExts[0]},t.isJsonExt=function(e){return"json"===p(e)},t.isCsvExt=function(e){return"csv"===p(e)},t.isLogExt=function(e){return(0,u.isExtOrCompressedExt)((0,l.toS)(e),".jsonl")||"db"===p(e)},t.isSidecarExt=function(e){return function(e,...t){e=p(e);for(const i of t)if(i===e)return!0;return!1}(e,...t.SidecarExts)},t.isSidecarMimetype=function(e){return null!=e&&e in t.SidecarFiletypes};const r=i(73024),s=i(22573),n=i(45599),a=i(96249),o=i(68708),l=i(54993),u=i(53252),c=i(49047),d=i(17217),h=[c.JpegExts,["tif","tiff"],["heic","heif"],["html","htm"],["jp2","jp2k"]],f=(0,n.defer)(()=>{const e={};for(const[t,...i]of h)for(const r of i)e[r]=t;return e}),m=/(?:^\.?|.\.)(?<ext>[a-z\d]{2,4})(?:_original)?$/i;function p(e){const t=(0,d.isSimpleFile)(e)?e.ext:e instanceof r.Dirent||null!=e&&"object"==typeof e&&"name"in e?(0,l.toS)(e.name):(0,l.toS)(e),i=m.exec(t)?.groups?.ext?.toLowerCase();return(0,s.blank)(i)?void 0:f()[i]??i}t.SidecarFiletypes={"application/rdf+xml":["xmp"],"application/json":["json"],"application/x-mie":["mie"],"application/x-exif":["exif"],"application/vnd.apple.photos":["aae"],"image/x-exv":["exv"]},t.SidecarExts=(0,a.flatten)((0,o.values)(t.SidecarFiletypes))},43624(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toFileStats=o,t.fileStats_=l,t.fileStats=async function(e){try{return await l(e)}catch{return}},t.fileStatsSync=function(e){return o((0,a.statSync)((0,s.toNativePath)(e)))};const r=i(68708),s=i(17217),n=i(16287),a=i(68284);function o(e){return null==e?void 0:(0,r.pick)(e,"size","mtimeMs","ino","birthtimeMs")}async function l(e){return o(await(0,n.stat_)((0,s.toNativePath_)(e)))}},78923(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileType_=async function(e){try{const t=h.PosixFile.for(e),i=await t.stat_();if(null==i||0===i.size||!i.isFile())return m().tap({msg:"readFileType(): empty or not a file",result:void 0,meta:{nativePath:e,stat:i}});if((0,u.isRawImageExt)(t.ext)||(0,u.isVideoExt)(t.ext))m().debug("readFileType(): can't use file-type (untrustworthy with this file)",{nativePath:e,caller:(0,a.shortStack)()});else{const{buffer:t}=await(0,f.readFilePart_)({nativePath:e,position:0,length:256}),i=await(0,r.fileTypeFromBuffer)(t);if(null!=i&&!i.mime.startsWith("image/x-")&&!p.has(i.mime))return m().tap({msg:"readFileType(): used file-type",result:{ext:(0,l.normalizeExt)(i.ext)??i.ext,mime:(0,c.normalizeMimetype)(i.mime)},meta:{nativePath:e,file_type_result:i}});m().debug("readFileType(): can't use file-type (untrustworthy)",{nativePath:e,result:i})}const n=await(0,d.readRawField_)(e,"MIMEType"),o=(0,s.mapNotBlank)(n,c.normalizeMimetype),g=(0,l.normalizeExt)(h.PosixFile.for(e))??(0,u.mimetypeExt)(o);return m().tap({msg:"readFileType(): resorted to ExifTool",result:(0,s.blank)(o)||(0,s.blank)(g)?void 0:{ext:g,mime:o},meta:{nativePath:e,raw:n}})}catch(t){return"EISDIR"===t?.code?void 0:m().throw("readFileType() failed for "+e,{error:t,ignorable:!0,retriable:!1,fatal:!1,path:e})}};const r=i(68817),s=i(22573),n=i(45599),a=i(26905),o=i(50213),l=i(32144),u=i(14036),c=i(16170),d=i(38148),h=i(95696),f=i(93854),m=(0,n.defer)(()=>(0,o.mkLogger)("fs.FileType")),p=new Set(["audio/mpeg","image/tiff"])},76699(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileWatcherExhaustedError=void 0,t.checkFileWatcherStatus=c,t.assertFileWatcherAvailable=async function(){const e=await c();if(!e.available){const t=[`Cannot create file watcher: system resources exhausted (${e.errorCode}).`,e.suggestion].filter(Boolean).join("\n");throw new u(t,e.errorCode,e.limits,e.suggestion,{cause:e.error})}};const r=i(31421),s=i(73024),n=i(51455),a=i(48161),o=i(1708),l=(0,i(50213).mkLogger)("FileWatcherCheck");class u extends Error{errorCode;limits;suggestion;name="FileWatcherExhaustedError";constructor(e,t,i,r,s){super(e,s),this.errorCode=t,this.limits=i,this.suggestion=r}}async function c(){let e;try{const t=(0,a.tmpdir)();e=(0,s.watch)(t,()=>{});const i=await d();return{available:!0,platform:o.platform,limits:i}}catch(e){const i=e,r=i.code;if(null!=(t=r)&&["ENOSPC","EMFILE","ENFILE","ENOMEM"].includes(t)){const e=await d().catch(()=>{}),t=function(e,t){const i=[];switch(o.platform){case"linux":null==t?.maxWatches&&null==t?.maxInstances||i.push(`Current limits: max_user_watches=${t.maxWatches??"?"}, max_user_instances=${t.maxInstances??"?"}`),"ENOSPC"===e?i.push("","inotify watches exhausted. To increase:"," echo 524288 | sudo tee /proc/sys/fs/inotify/max_user_watches","","To make permanent, add to /etc/sysctl.conf:"," fs.inotify.max_user_watches=524288"):"EMFILE"!==e&&"ENFILE"!==e||i.push("","File descriptor limit reached. To increase:"," echo 512 | sudo tee /proc/sys/fs/inotify/max_user_instances"," ulimit -n 65536");break;case"darwin":null!=t?.maxFilesSoft&&i.push(`Current limits: maxfiles soft=${t.maxFilesSoft}, hard=${t.maxFilesHard===1/0?"unlimited":t.maxFilesHard}`),i.push("","FSEvents client limit reached. To increase:"," sudo launchctl limit maxfiles 524288 1048576","","Or restart fseventsd:"," sudo pkill -9 -x fseventsd");break;case"win32":i.push("","File handle limit reached. Try:"," - Closing unused applications"," - Reducing the number of watched directories"," - Increasing system virtual memory")}return i.length>0?i.join("\n"):void 0}(r,e);return l.warn("File watcher resources exhausted",{platform:o.platform,code:r,limits:e}),{available:!1,platform:o.platform,limits:e,error:i,errorCode:r,suggestion:t}}return l.warn("Unexpected error checking file watcher",{error:i}),{available:!0,platform:o.platform}}finally{e?.close()}var t}async function d(){switch(o.platform){case"linux":return async function(){try{const[e,t]=await Promise.all([(0,n.readFile)("/proc/sys/fs/inotify/max_user_watches","utf-8"),(0,n.readFile)("/proc/sys/fs/inotify/max_user_instances","utf-8")]);return{maxWatches:parseInt(e.trim(),10),maxInstances:parseInt(t.trim(),10)}}catch{return}}();case"darwin":return async function(){try{const e=(0,r.execSync)("launchctl limit maxfiles",{encoding:"utf-8",timeout:5e3}).match(/maxfiles\s+(\d+)\s+(\d+|unlimited)/);if(e)return{maxFilesSoft:parseInt(e[1],10),maxFilesHard:"unlimited"===e[2]?1/0:parseInt(e[2],10)}}catch{}}();default:return}}t.FileWatcherExhaustedError=u},73209(e,t,i){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.FsLock=void 0,t.withLock_=async function(e,t){if(!0===e.skipFsLock)return t();{const i=new x(e);try{return await i.withLock_(t)}finally{await i.end()}}};const s=i(58587),n=i(51455),a=i(87997),o=i(40958),l=i(42659),u=i(6875),c=i(50357),d=i(26905),h=i(55835),f=i(31586),m=i(30976),p=i(13538),g=i(54993),y=i(7282),v=i(409),b=i(68852),w=i(23560),S=i(25764),P=i(38836),M=i(99331),T=i(85970),_=i(38835),E=i(55222),k=i(28874),D=i(63870),I=i(62188),C=i(17217),A=new RegExp("-(?<pid>\\d+)"+(0,b.escapeRegExp)(I.PsLockExt)+"$");class x extends P.EndableWrapper{opts;static#Xe=0;static internalErrors=0;static#Qe=0;static newUid(e=process.pid,t=9){return this.#Xe=Math.max(Date.now(),this.#Xe+1),(0,o.compactBlanks)([(0,g.toS)(t),E.TokenRadix.encode(this.#Xe),w.serviceName.prior(),(0,g.toS)(e)]).join("-")}static pidFromLockfile(e){return r.pidFromBasename((0,C.basename)(e))}static pidFromBasename(e){return(0,f.toInt)(A.exec((0,g.toS)(e))?.groups?.pid)}static#et=[];static for(e){return(0,o.filterInPlace)(this.#et,e=>!e.ended),this.#et.find(t=>t.opts.file.$eql(e.file))??new r(e)}#tt=++r.#Qe;lockdir;#it=!1;lockfile;#rt;#st;staleMs;#nt;constructor(e){super(e.name??"FsLock",()=>this.#e(),e.endableRank??S.EndableRanks.last,(0,D.commandTimeoutMs)()),this.opts=e,this.lockdir=(0,I.fsLockDir)(this.opts.file),null==e.name&&this.setName("fs.FsLock("+e.file+")#"+this.#tt),this.staleMs=(0,f.round)(this.opts.timeoutMs/(0,m.randomFloat)(1.5,3)),r.#et.push(this)}get acquired(){return this.#it}toLogJSON(){return{name:this.name,acquired:this.acquired}}vacuum=(0,v.rateLimited)({name:"fs.FsLock.vacuum:"+this.name,nullOnBusy:!0,minCallDelayMs:()=>((0,f.toGt0)(this.staleMs)??k.Settings.statTimeoutMs.valueOrDefault)/2,f:async()=>{const e=[];let t;try{t=(await(0,n.readdir)(this.lockdir.nativePath,{withFileTypes:!1,encoding:"utf8"})).filter(e=>(0,I.isPsLockFileOrDir)(e))}catch(e){if("ENOENT"!==e.code)throw this.logger.warn("readdir() failed",{error:e}),e;t=[]}for(const i of t){const t=this.lockdir.join(i);let n=!1,a="";if((0,f.gt0)(this.staleMs)){const e=1e3*Math.round((Date.now()-(this.staleMs+l.secondMs))/1e3),i=await t.mtimeMs({refresh:!0});null!=i&&i<e&&(n=!0,a=`stale by ${(0,u.fmtDuration)(e-i)}`)}if(!n){const e=r.pidFromLockfile(t);null==e?(n=!0,a="no pid",r.internalErrors++):(0,s.pidExists)(e)||(n=!0,a="pid gone")}n?(this.logger.warn(`#vacuum(): Removing ${t.base} - ${a}`),await t.unlink()):e.push(i)}return e.sort()}});async selfAndSiblingNames_(e){if(!0===e?.vacuum)return await this.vacuum.force()??[];const t=await this.vacuum();if(null!=t)return t;try{return(await(0,n.readdir)(this.lockdir.nativePath,{withFileTypes:!1,encoding:"utf8"})).filter(e=>(0,I.isPsLockFileOrDir)(e)).sort()}catch(e){if("ENOENT"===e.code)return[];throw this.logger.warn("readdir() failed",{error:e}),e}}async iAmNext(e){const t=this.lockfile;if(null==t)return this.release(),!1;const i=await this.selfAndSiblingNames_(e);if(this.lockfile!==t||null==this.lockfile)return this.release(),!1;if(!i.includes(t.base)){if(!(0,y.isTest)())return this.release(),!1;r.internalErrors++,this.logger.throw("iAmNext_(): missing lockfile, "+t+_.InternalErrorFlag,{children:i,lockfile:t})}const n=i[0]===t.base;if(n){if(this.lockfile!==t)return this.release(),!1;this.#it=!0}else if(!0!==e?.vacuum){const e=r.pidFromBasename(i[0]);if((0,f.gt0)(e)&&!(0,s.pidExists)(e))return this.logger.info("iAmNext_(): auto-vacuuming, owner pid is gone"),this.iAmNext({vacuum:!0})}return n}async iAmOnly_(e){return null!=this.lockfile&&(0,c.eql)(await this.selfAndSiblingNames_(e),[this.lockfile.base])}async isOwner_(e){const t=this.lockfile;return null!=t&&(await this.selfAndSiblingNames_(e))[0]===t.base}tryAcquire_=(0,T.serialized)(async()=>{if(this.#it)return!0;if(await(this.lockfile??=this.lockdir.join((0,I.fsLockFileBasename)(r.newUid(process.pid,this.opts.priority??9)))).touch_(),this.startRefreshTimer_(),null==this.lockfile)return!1;try{return await this.iAmNext()}catch(e){return this.release(),this.logger.error("tryAcquire() failed",e),!1}});startRefreshTimer_(){if(null==this.#rt&&this.staleMs>0){const e=Math.max(this.staleMs/2,(0,y.isTest)()?10:l.secondMs);this.#rt=setInterval(()=>this.refreshLockfile_(),e)}}async refreshLockfile_(){const e=this.lockfile;if(null==e||await e.notExists({refresh:!0}))return this.logger.warn("#refreshLockfile_(): null or missing lockfile"),void this.release();if(this.lockfile===e)try{await e.touch_()}catch(e){throw this.logger.warn("#refreshLockfile_(): failed, force-releasing.",e),this.release(),e}else this.logger.debug("#refreshLockfile_(): lockfile changed, aborting")}acquire_=(0,T.serialized)(async({releaseOnFailure:e=!0,timeoutMs:t=this.opts.timeoutMs}={})=>{if(this.#it)return!0;try{if(!0===await this.tryAcquire_.ifIdle())return!0;const i=(0,f.clamp)(50,5*l.secondMs,Math.min(this.staleMs,t)/7);return await this.lockdir.watchUntil({f:async()=>!0===await this.tryAcquire_.ifIdle(),persistent:!1,recursive:!1,timeoutMs:t,intervalMs:i}),!this.acquired&&e&&this.release(),this.acquired}catch(t){throw e&&this.release(),this.logger.warn("acquire_() failed",{error:t}),t}});async#at(){await this.vacuum()}#e(){(0,o.filterInPlace)(r.#et,e=>e.#tt!==this.#tt),(0,M.ending)()&&this.release()}release(){null!=this.#rt&&(clearInterval(this.#rt),this.#rt=void 0),(0,h.map)(this.#st,e=>(0,a.clearTimeout)(e));const e=this.lockfile;let t=!0;try{null!=e&&e.unlinkSync_()}catch(e){"ENOENT"===e.code?(this.logger.debug("#release() lockfile already deleted"),t=!0):(this.logger.warn("#release() failed to delete lockfile",e),t=!1)}return t&&(this.#it=!1,this.lockfile=void 0),!0!==this.opts.dirty&&((0,M.ending)()||this.ended?this.#at():(this.#st=setTimeout(()=>this.#at(),(0,f.toGt0)(this.staleMs)??l.secondMs),this.#st.unref())),t}async withLock_(e){if(!0===this.opts.skipFsLock)return e(this);if(this.#it)return this.logger.warn("nested withLock() with acquired lock",{caller:(0,d.shortStack)()}),e(this);const t=(0,d.shortStack)();null!=this.#nt&&this.logger.throw("Re-entrant withLock_() detected - this will deadlock!"+_.InternalErrorFlag,{previousStack:this.#nt,currentStack:t});try{return this.#nt=t,await(!0===this.opts.noopIfContested?this.tryAcquire_():this.acquire_())?await(0,p.thenOrTimeoutError)(e(this),this.opts.timeoutMs):void 0}catch(e){throw this.logger.warn("withLock_() rejected",e),e}finally{this.#nt=void 0,this.release()}}}t.FsLock=x,r=x},62188(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PsLockExt=void 0,t.fsLockDir=function(e){return e.sibling("."+e.base+t.PsLockExt)},t.fsLockFileBasename=function(e){return e+t.PsLockExt},t.uidFromFsLockfile=function(e){if(null==e||(0,r.blank)((0,s.toS)(e)))return;const i=(0,a.basename)(e);return o(i)?(0,n.stripSuffix)(i,t.PsLockExt):void 0},t.isPsLockFileOrDir=function(e){return!(0,r.blank)(e)&&o((0,a.basename)(e))};const r=i(22573),s=i(54993),n=i(81168),a=i(17217);function o(e){return(0,r.notBlank)(e)&&e.endsWith(t.PsLockExt)}t.PsLockExt=".pslock"},34075(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getVolumeMetadata_=t.volshaToMountPointFallback=t.onHealthyVolumeDiscovered=t.getMountPoints=void 0,t.clearFsMetadataCaches=function(){R.clear(),L.clear(),t.getMountPoints.clear(),V.clear(),H.clear()},t.addMountPointVolsha=N,t.cachedMountPointToVolsha=j,t.mountPointToVolsha=async function(e){return j(e)??(await U(e))?.volsha},t.mountPointToVolshas=async function(){for await(const e of Y());return new Map([...R.tuples()].map(([e,t])=>[t,e]))},t.volshaToMountPoints=B,t.volshaToVolume=async function(e){const t=await B(e);for(const i of t){const t=await U(i);if(t?.volsha===e)return t}},t.isOK=z,t.getVolumeMetadata=U,t.setVolumeMetadataTTL=W,t.getExcludedMountpointPaths=q,t.isMountPoint=async function(e){const i=await(0,t.getMountPoints)(),r=await(0,F.canonicalizeMacPath)(e);return i.some(t=>t.mountPoint===e||t.mountPoint===r)},t.bestMountPointForPath=G,t.bestVolumeForPath=K,t.volumes=J,t.remoteVolumes=async function*(){for await(const e of J(e=>!0!==e.isSystemVolume))!0===e.remote&&(yield e)},t.volumesWithUUIDs=Y,t.rootVolume=async function(){return K((0,A.systemDrive)())},t.whyNotScanMountPoint=Z,t.scannableMountPoints=X,t.scannableVolumes=Q,t.libraryVolumes=ee,t.scannedVolumes=async function*(){yield*(0,m.asyncUniqBy)(async function*(){if(_.Settings.argvScanPaths.isNotEmpty())yield*te((0,u.compactBlanks)(_.Settings.argvScanPaths.values));else{for await(const e of ee())yield e.volume;yield*te((0,u.compactBlanks)(_.Settings.scanPaths.values)),_.Settings.scanAllDrives.valueOrDefault&&(yield*Q())}}(),e=>e.mountPoint)};const o=a(i(29365)),l=i(76760),u=i(40958),c=i(76790),d=i(22573),h=i(45599),f=i(41400),m=i(41801),p=i(23838),g=i(31586),y=i(68708),v=i(89937),b=i(5916),w=i(56519),S=i(56038),P=i(55139),M=i(87290),T=i(50213),_=i(28874),E=i(30495),k=i(34238),D=i(85087),I=i(86848),C=i(83278),A=i(92234),x=i(92423),F=i(9029),O=(0,h.defer)(()=>(0,T.mkLogger)("fs.FsMetadata"));t.getMountPoints=(0,b.lazyAsync)({desc:"getVolumeMountPoints",later:async function(){const e=await(0,S.time)({name:"fs.volumeMountPoints",p:(0,w.mapAsync)({iter:await o.getVolumeMountPoints($()),f:async e=>(0,y.compactValues)({...e,ok:z(e)})})}),t=(0,M.libraryDirs_)(),i=_.Settings.scanPaths.valueOrDefault.map(e=>C.BaseFile.for(e));return(0,c.sortBy)(e,e=>[!t.some(t=>t.isSelfOrDescendantOf(e.mountPoint)),!i.some(t=>t.isSelfOrDescendantOf(e.mountPoint)),e.mountPoint])}});const R=new p.MultiMap,L=new Map;function N(e){R.add(e.volsha,e.mountPoint),!0===e.fromCache&&L.has(e.mountPoint)||L.set(e.mountPoint,e.volsha)}function j(e){return L.get(e)}async function B(e){const i=R.get(e);if(null!=i)return i;for await(const t of Y())if(t.volsha===e)return R.add(e,t.mountPoint),[t.mountPoint];return(0,t.volshaToMountPointFallback)(e)}function z(e){return(0,d.blank)(e?.error)&&"healthy"===(e?.status??"healthy")}t.onHealthyVolumeDiscovered=(0,E.shimSync)({name:"FsMetadata.onHealthyVolumeDiscovered",impl:e=>{}}),t.volshaToMountPointFallback=(0,E.shimSync)({name:"volshaToMountPointFallback",impl:e=>[]});const V=new P.Cache({name:"fs.FsMetadata.getVolumeMetadata",ttlMs:0,maxSize:256}),H=new P.Cache({name:"fs.FsMetadata.getMountPointUUID",ttlMs:0,maxSize:256});async function U(e){try{return await(0,t.getVolumeMetadata_)(e)}catch(t){return void O().warn("getVolumeMetadata() failed",{mountPoint:e,error:t})}}function W(e){t.getMountPoints.setTTL(e),V.setTTL(e),H.setTTL(e)}function q(){const e=new Set(_.Settings.excludedMountpointPaths.valueOrDefault);for(const t of _.Settings.excludedMountpointPathsOmit.values)e.delete(t);for(const t of _.Settings.excludedMountpointPathsAdd.values)e.add(t);return[...e]}function $(){return o.optionsWithDefaults({systemFsTypes:_.Settings.excludedFilesystemTypes.valueOrDefault,systemPathPatterns:q(),timeoutMs:_.Settings.statTimeoutMs.valueOrDefault})}async function G(e,i){if((0,d.blank)(e))return;const r=(0,u.toNotEmpty)(i)??await(0,t.getMountPoints)(),s={mountPoints:r,...$()};let n=e;for(;;){try{const e=await o.getMountPointForPath(n,s);if(null!=e)return r.find(t=>t.mountPoint===e)??{mountPoint:e,ok:!0}}catch(t){const i=t?.code;if("ENOENT"!==i)return void O().warn("bestMountPointForPath(): error checking mount point",{nativePath:e,pathToResolve:n,error:t});O().info("bestMountPointForPath(): path does not exist, trying parent",{nativePath:e,pathToResolve:n})}const t=(0,l.dirname)(n);if(t===n)break;n=t}}async function K(e,t){const i=await G(e,t);if(null==i)return;const r=await U(i.mountPoint);return null==r&&O().warn("bestVolumeForPath(): no volume metadata found",{nativePath:e}),r}async function*J(e=()=>!0){for(const i of await(0,t.getMountPoints)())try{i.ok&&await e(i)&&(yield await(0,t.getVolumeMetadata_)(i.mountPoint))}catch(e){O().warn("volumes(): skipping volume",{mp:i,error:e})}}async function*Y(){for await(const e of J())(0,d.notBlank)(e.volsha)&&(yield e)}async function Z(e){if(!e.ok)return e.status??e.error??"unknown";if(await o.isHidden(e.mountPoint))return"hidden directory";const t=await(0,x.whyExcludedDirectory)(e.mountPoint);return(0,d.blank)(t)?void 0:t}async function*X(){for(const e of await(0,t.getMountPoints)()){const t=await Z(e);null==t?yield e:O().info("scannableMountPoints(): skipping mount point",{mountPoint:e.mountPoint,why:t})}}async function*Q(){for await(const e of X()){const t=await U(e.mountPoint);null!=t&&(yield t)}}async function*ee(){const e=new Set;for(const t of(0,M.libraryDirs_)()){const i=await G(t.nativePath);if(null!=i&&!e.has(i.mountPoint)){e.add(i.mountPoint);const r=await U(i.mountPoint);null!=r&&(yield{volume:r,dir:t})}}}async function*te(e){for(const t of e){const e=await G(t);if(null==e){O().warn("scannedVolumes(): no mount point found",{file:t});continue}const i=await U(e.mountPoint);null!=i&&(yield i)}}t.getVolumeMetadata_=V.memoize(e=>(0,S.time)({name:"fs.volumeMetadata",meta:{volume:e},p:async()=>{const i=await o.getVolumeMetadata(e,$());if(!(0,g.gte0)(i.available))return O().throw("getVolumeMetadata(): invalid available",{vol:i});const r=await(0,I.addVolumeUUID)(i),s=[k.URI.file(i.mountPoint).toString()],n=(0,D.volsha)(r);return null!=n&&(i.volsha=n,s.push(k.URI.from({scheme:v.PS_LOCAL_FILE_SCHEME,authority:i.volsha,path:"/"}).toString()),N({mountPoint:i.mountPoint,volsha:i.volsha,fromCache:!1})),i.uris=(0,v.sortURIs)((0,u.uniq)(s,i.uris)),i.ok=z(i),i.ok&&(0,t.onHealthyVolumeDiscovered)(i),i}})),(0,f.later)(()=>{_.Settings.volumeMetadataTtlMs.watch(W)})},4001(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ymdIsoRE=void 0,t.stripCopySuffixFromName=d,t._stripCopySuffixFromName=h,t.copySuffixCountFromName=function(e){const t=((0,a.isString)(e)?e:e.name).toLowerCase().normalize(),i=d(t),r=(0,a.stripPrefix)(t.toLowerCase().normalize(),i);return(0,s.map)((0,l.extractInt)(r),Math.abs)},t.stripDSC=function(e){let t=((0,a.isString)(e)?e:e.name).trim().replace(m,"").trim();return(0,s.map)(f.exec(t),e=>t=e[1].trim()),(0,s.map)(p.exec(t),e=>t=e[1].trim()),t};const r=i(22573),s=i(55835),n=i(31586),a=i(51926),o=i(54993),l=i(97352),u=[/\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}$/],c=[...u,/\s*-?edit(?:ed)?$/i];function d(e,t={aggressive:!0}){return h((0,r.toNotBlank)(e.name)??(0,o.toS)(e),t).normalize()}function h(e,i){if(t.ymdIsoRE.test(e))return e;let r=e;for(const e of i.aggressive?c:u){const t=r.match(e);if((0,n.gt0)(t?.index)){const e=r.slice(0,t.index).trim();e.length>0&&(r=e)}}return e===r?e:h(r,i)}t.ymdIsoRE=/^(?:\d\d){1,2}-\d\d-\d\d$/;const f=/burst\s*([\w-]{8,})\s*$/i,m=/(?<=.{6})_cover$/i,p=/^(?:dsc|dscf|img|gpfr|gopro?|gf|gh|gp|mov|mvi|mvimg|p|vid)[-_ ]{0,2}e?(\d.+)$/i},50597(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.shimmedFileSha_=void 0,t.fileShaMeta_=M,t.fileSha_=async function(e){return(await M(e)).sha},t.uncachedFileSha_=T,t.streamSha_=_,t.numericSha=function(e,t=48){return parseInt((0,y.stringShaToBuffer)((0,u.stringify)(e),t).toString("hex"),16)},t.randomSha=function(){return s.default.randomBytes(f.HashBits/8).toString("base64")};const s=r(i(77598)),n=r(i(73024)),a=i(46466),o=i(19851),l=i(42659),u=i(98553),c=i(68708),d=i(55139),h=i(23467),f=i(73913),m=i(50213),p=i(3685),g=i(79136),y=i(37628),v=i(43624),b=i(17217),w=i(16287),S=(0,o.lazy)(()=>(0,m.mkLogger)("fs.Hash")),P=(0,o.lazy)(()=>new d.Cache({name:"fs.Hash",maxSize:1024,timeoutMs:0,clearEveryMs:0,ttlMs:10*l.minuteMs}));async function M(e,{autoInvalidate:i=!0}={}){const r=(0,b.toNativePath_)(e);if(i){const t=await P().getAsync(r);if(null!=t){if((0,h.eql)(t.stats,await(0,v.fileStats_)(e)))return S().debug("fileSha_() cache matches current Stats",{nativePath:r,prior:t}),t;S().debug("fileSha_() prior cache is invalid, re-reading SHA",{nativePath:r,prior:t}),P().delete(r)}}return(0,t.shimmedFileSha_)(e)}async function T(e,t,i){const r=performance.now(),s=(0,b.toNativePath_)(e);return{sha:await _({source:n.default.createReadStream(s),hashAlgorithm:i,bits:t}),stats:(0,c.pick)(await(0,w.stat_)(s),"size","mtimeMs","birthtimeMs","ino"),elapsedMs:(0,p.roundMs)(performance.now()-r)}}async function _({source:e,transforms:t=[],hashAlgorithm:i="sha512",bits:r=f.HashBits}){const n=s.default.createHash(i);await(0,a.pipeline)([e,...t,n]);let o=n.digest();return null!=r&&r>0&&(o=o.subarray(0,f.HashBits/8)),o.toString("base64")}t.shimmedFileSha_=(0,g.shim)({name:"fs.Hash",cache:P,impl:T})},48313(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hide_=async function(e){if(!n.isWin&&!n.isMac)return;const t=(0,o.toNativePath_)(e),i=await(0,r.setHidden)(t,!0);return await(0,s.ee)().emit("fileChanged",i.pathname),i.pathname},t.isHidden_=async function(e){const t=(0,o.toNativePath_)(e);return!(0,a.pathIsRoot)(t)&&await(0,r.isHidden)(t)};const r=i(29365),s=i(34102),n=i(43334),a=i(29882),o=i(17217)},75742(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPhotoStructureDmg=function(e){return null!=n?.exec((0,r.toS)(e))};const r=i(54993),s=i(7282),n=i(43334).isMac||(0,s.isTest)()?/^\/Volumes\/PhotoStructure v?[\d.]{3,}/i:void 0},49047(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JpegExts=void 0,t.JpegExts=["jpg","jpeg","jpe"]},87128(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonFileStore=void 0;const r=i(19851),s=i(55835),n=i(57159),a=i(50213);t.JsonFileStore=class{file;mkObject;onWrite;constructor(e,t,i){this.file=e,this.mkObject=t,this.onWrite=i}prior=(0,r.lazy)(()=>this.file.readJson("debug"));async read_(){return await this.prior()??(0,s.map)(await this.mkObject(),e=>this.write_(e))}async write_(e){try{return await this.file.writeJson_(e,{spaces:2}),this.prior.set(Promise.resolve(e)),(0,a.mkLogger)("fs.JsonFileStore").info("wrote to "+this.file,e),null!=this.onWrite&&await this.onWrite(this.file,e),e}catch(e){throw new n.WrappedError("Failed to write to "+this.file,{cause:e,path:this.file.nativePath})}}}},9029(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getFirmlinks=void 0,t.canonicalizeMacPathSync=function(e){if(!d.isMac)return e;const i=t.getFirmlinks.lastValue();if(void 0===i)return;if(!e.startsWith(i.mountPoint))return e;const r=e.slice(i.mountPoint.length);for(const e of i.links){const t=m(r,e);if(null!=t)return e.visiblePath+t}return e},t.canonicalizeMacPath=async function(e){if(!d.isMac)return e;const i=await(0,t.getFirmlinks)();if(null==i||!e.startsWith(i.mountPoint))return e;const r=e.slice(i.mountPoint.length);for(const e of i.links){const t=m(r,e);if(null!=t)return e.visiblePath+t}return e},t.dataVolumePath=async function(e){const i=await(0,t.getFirmlinks)();if(null!=i)for(const t of i.links){const r=f(e,t);if(null!=r)return i.mountPoint+"/"+t.targetPath+r}},t.clearFirmlinksCache=function(){t.getFirmlinks.clear()};const r=i(29365),s=i(51455),n=i(76760),a=i(22573),o=i(45599),l=i(51926),u=i(5916),c=i(50213),d=i(43334),h=(0,o.defer)(()=>(0,c.mkLogger)("fs.MacFirmlinks"));function f(e,t){return e===t.visiblePath?"":e.startsWith(t.visiblePath+"/")?e.slice(t.visiblePath.length):void 0}function m(e,t){const i="/"+t.targetPath;return e===i?"":e.startsWith(i+"/")?e.slice(i.length):void 0}t.getFirmlinks=(0,u.lazyAsync)({desc:"getFirmlinks",later:async()=>{if(!d.isMac)return;const e=[];for await(const t of async function*(){const e=(await(0,s.readFile)("/usr/share/firmlinks","utf-8")).split("\n");for(const t of e){if(0===t.length||t.startsWith("#"))continue;const[e,i]=t.split("\t",2);(0,a.notBlank)(e)&&(0,a.notBlank)(i)&&(yield{visiblePath:(0,l.stripSuffix)(e,n.sep),targetPath:(0,l.stripSuffix)(i,n.sep)})}}())e.push(t);let t;for(const e of["/Users","/Library","/opt"])try{t??=await(0,r.getMountPointForPath)(e);break}catch(t){h().warn("getFirmlinks: error getting mount point for path",{path:e,error:t})}return null==t&&(h().warn("getFirmlinks: could not determine mount point for firmlinked paths, defaulting to /System/Volumes/Data"),t="/System/Volumes/Data"),{links:e,mountPoint:t}}})},64680(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.mkNoMedia_=function(e){return(0,a.writeTextfile_)(s.default.join((0,n.toNativePath_)(e),".NoMedia"),"This directory's contents are excluded from PhotoStructure libraries.","","See https://photostructure.com/nomedia/ for details.")};const s=r(i(76760)),n=i(17217),a=i(73428)},61704(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathsEqlSync=function(e,t){if(null==e||null==t)return!1;if(e===t)return!0;try{const i=(0,s.toNativePath_)(e),r=(0,s.toNativePath_)(t);return null!=i&&null!=r&&i===r}catch{return!1}},t.nativePathsEql=async function(e,t){try{return null!=e&&null!=t&&await(0,r.actualPath_)((0,s.toNativePath_)(e))===await(0,r.actualPath_)((0,s.toNativePath_)(t))}catch{return!1}};const r=i(21144),s=i(17217)},85772(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.isNoMediaName=E,t.hasNoMedia=async function(e,t){return null!=await D(e,t)},t.whyNoMedia=D,t.whyNoMediaDir=I,t._dirHasNoMediaChild=C;const o=a(i(76760)),l=i(19851),u=i(40958),c=i(50213),d=i(68852),h=i(46199),f=i(63458),m=i(57902),p=i(43334),g=i(83278),y=i(70698),v=i(88561),b=i(34075),w=i(16287),S=(0,l.lazy)(()=>(0,c.mkLogger)("fs.hasNoMedia()")),P="NoMedia",M=new RegExp("(?:^|["+(0,u.uniq)([(0,d.escapeRegExp)(o.default.sep),"/"]).join("")+"])\\.?"+P+"$","im"),T=Object.freeze(["."+P,P]),_=Object.freeze(T.flatMap(function(e){return[e,e.toLowerCase(),e.toUpperCase()]}));function E(e){return null!=M.exec(e)}const k=(0,l.lazy)(()=>new v.FileCache({name:"fs.noMediaDirsCache"}));async function D(e,t){if(null==e)return null;const i=g.BaseFile.for(e),r=await i.stat();if(null==r||!r.isFile()&&!r.isDirectory())return null;if(r.isFile())return E(i.base)||await(0,y.isCachedirTagFile)(i)?k().setAndGet(i.parent().nativePath,(0,h.ciSafePath)(i.nativePath)):D(i.parent());{const e=await k().getOrSet(i.nativePath,()=>I(i));return null!=e||!1===t?.recurse||i.isRoot||(0,f.isExplicitScanPath)(i.nativePath)||await(0,b.isMountPoint)(i.nativePath)?e:D(i.parent())}}async function I(e){if(E(e.base))return k().set(e.dir,e.nativePath),S().tap({msg:"whyNoMedia()",result:(0,h.ciSafePath)(e.nativePath)});const t=await C(e.nativePath);return null!=t?(k().set(e.nativePath,t),t):await(0,y.isCachedirTagDirectory)(e)?S().tap({msg:"whyNoMedia()",result:(0,h.ciSafePath)((0,o.join)(e.nativePath,y.CACHEDIR_TAG))}):null}async function C(e){for(const t of p.isCaseSensitiveFs?_:T){const i=o.default.join(e,t);if(await(0,w.exists)(i,m.LogLevels.trace))return S().tap({msg:"_dirHasNoMediaChild",result:(0,h.ciSafePath)(i)})}return null}},29882(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isNativePath=function(e){return e.includes(a.default.sep)},t.isNonNativePath=function(e){const t=g.isPosix?o.win32.sep:o.posix.sep;return e.includes(t)},t.isHiddenBasename=M,t.containsHiddenPathname=function(e){return(0,y.toPathnames)(e)?.some(M)??!1},t.isNotHiddenPosixPath=function(e){return(0,y.toPathnames)(e)?.every(e=>!M(e))??!1},t.resolveSimpleFile=function(e){return(0,w.isSimpleFile)(e)?e.nativePath:(0,b.resolve)(e.toString())},t.resolveMaybe=function(...e){return e.some(c.blank)?void 0:(0,b.resolve)(...e)},t.parsePosixPath=function(e){return k((0,v.posix2native)(e))},t.extname=function(e){return k(e).ext},t.dirname_=T,t.pathIsRoot=_,t.extMatches=function(e,t){return!(0,c.blank)(e)&&!(0,c.blank)(t)&&(0,m.equalsIgnoreCase)(a.default.parse(e).ext,a.default.parse(t).ext)},t.parseNativePath=k,t.parentBasename=D,t.grandParentBasename=function(e){return D(a.default.parse((0,w.toNativePath_)(e)).dir)},t.eqlBasename=function(e,t){return I(w.basename,e,t)},t.eqlNameWithoutExt=function(e,t){return I(w.nameWithoutExt,e,t)},t.eqlPath=function(e,t){return I(w.toNativePath_,e,t)},t.posixPathFrom=function(e,t){const i=(0,w.toNativePath_)(e),r=(0,w.toNativePath_)(t);if((0,c.blank)(i)||(0,c.blank)(r))throw new Error("posixPathFrom empty args "+(0,d.stringify)({parent:e,child:t}));return i===r?"":(0,m.stripPrefix)((0,v.native2posix)(r).normalize(),(0,m.ensureSuffix)((0,v.native2posix)(i),"/").normalize()).normalize()},t.ellipsizePath=C,t.ellipsizePaths=function({arr:e,maxPathLength:t,sampleSize:i=4,arrLength:r=e.length}){const s=[];for(const r of e.slice(0,i))s.push(C({p:r,maxLength:t}));return s.join(", ")+(r>i?`, and ${r-i} more…`:"")},t.posixPathFromParent=function(e){return(0,y.toPathnames)(e)?.slice(-2).join("/")??""},t.posixPathFromGrandparent=function(e){return(0,y.toPathnames)(e)?.slice(-3).join("/")??""},t.addNameSuffix=function(e,t){const i=k(e);return`${i.base}${t}${i.ext}`},t.isUNC=A,t.isAbsolute=function(e){return g.isPosix&&e.startsWith("/")||g.isWin&&(A(e)||x.test(e))},t.mkdirp_=F,t.mkdirpSync_=O,t.move_=async function(e,t){return(0,u.retryOnReject_)(()=>async function(e,t){try{await(0,n.rename)(e,t)}catch(i){if("EXDEV"!==i?.code)throw i;{const i=await(0,n.stat)(e);await(0,n.copyFile)(e,t),await(0,n.chmod)(t,i.mode),await(0,n.unlink)(e)}}}(e,t),{errorIsRetriable:p.isRetriableError,maxRetries:5,retryDelay:250})},t.splitNativePath=function(e){return(0,w.toNativePath_)(e).split(a.default.sep).filter(e=>null!=e&&""!==e)},t.joinNativePath=R,t.joinNativePathMaybe=function(...e){return e.some(c.blank)?void 0:R(e)},t.posixPathIncludesPathElement=function(e,t){return e.split("/").includes(t)},t.pathMatchesPlatform=function(e){const t=g.isPosix?o.win32.sep:o.posix.sep;return(0,c.notBlank)(e)&&!e.includes(t)},t.fsSafeBasename=function(e){const t=(0,f.toS)((0,m.stripDiacritics)(e)).replace(/[^a-z\d\s.-]+/gi,"-").trim().replace(/[\s-]+/g,"-").replace(/^-+|-+$/g,"").normalize().toLowerCase();return""===t&&e.includes("-")?"-":t},t.ensureFile_=async function(e){await F(T(e)),await(0,n.appendFile)(e,"")},t.ensureFileSync_=function(e){O(T(e)),(0,s.appendFileSync)(e,"")};const s=i(73024),n=i(51455),a=r(i(76760)),o=i(23236),l=i(40958),u=i(5233),c=i(22573),d=i(98553),h=i(51926),f=i(54993),m=i(81168),p=i(70025),g=i(43334),y=i(51704),v=i(78133),b=i(53265),w=i(17217),S=i(16287),P=i(66430);function M(e){return((0,w.isSimpleFile)(e)?e.base:a.default.basename((0,b.resolve)(e))).startsWith(".")}function T(e){return a.default.dirname((0,w.toNativePath_)(e))}function _(e){const t=(0,w.toNativePath)(e);return!(0,c.blank)(t)&&t===a.default.dirname(t)}const E=/^(?<path>.*?)(?<ext2>\.(?:gz|z|7z|xz|bz2|br))?$/i;function k(e){const t=E.exec(e)?.groups,i=t?.ext2??"",r=a.default.parse(t?.path??e);return{...r,ext:(r.ext??"")+i,base:(r.base??"")+i}}function D(e){const t=a.default.parse((0,w.toNativePath_)(e));return(t.root===t.dir?t.root:(0,h.splitLast)(t.dir,a.default.sep)).normalize()}function I(e,t,i){if(null==t||null==i)return!1;const r=e(t),s=e(i);return null!=r&&null!=s&&(0,m.equalsIgnoreCase)(r,s)}function C({p:e,maxLength:t}){const i=(0,w.toNativePath_)(e);if(i.length<=t)return i;const r=(0,y.toPathnames)(e)??[],s=[],n=[r.pop()];for(;r.length>0;)if(s.length<n.length){if(s.push(r.shift()),R([...s,...n]).length>=t){r.unshift(s.pop());break}}else if(n.unshift(r.pop()),R([...s,...n]).length>=t){r.push(n.shift());break}return r.length>0&&s.push("…"),R([...s,...n])}function A(e){return null!=e&&"string"==typeof e&&(!!g.isWin&&/^\\\\[^\\]+\\[^\\]+/.test(e))}const x=/^[A-Z]:\\$/i;async function F(e){try{if(_(e)||await(0,S.isReadableDirectory)(e))return;await(0,n.mkdir)(e,{recursive:!0})}catch(t){if(await(0,S.isReadableDirectory)(e))return;throw t}}function O(e,t){try{if(_(e)||(0,P.isReadWriteableDirectorySync)(e))return;(0,s.mkdirSync)(e,{recursive:!0,...t})}catch(t){if((0,P.isReadWriteableDirectorySync)(e))return;throw t}}function R(e){return(0,h.ensurePrefix)((0,l.compactBlanks)(e).join(a.default.sep),g.isWin?"":a.default.sep)}},91987(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.containedByNativePath=function(e){try{if(null==e.descendant||null==e.ancestor)return!1;const t=(0,u.toNativePath_)(e.ancestor),i=(0,u.toNativePath_)(e.descendant);if((0,a.blank)(t)||(0,a.blank)(i))return!1;const r=e.acceptSelf??!1;return t===i?r:i.startsWith((0,l.ensureSuffix)(t,s.default.sep))}catch(t){return c().warn("containedByNativePath() failed (returning false)",{args:e,error:t}),!1}};const s=r(i(76760)),n=i(19851),a=i(22573),o=i(50213),l=i(81168),u=i(17217),c=(0,n.lazy)(()=>(0,o.mkLogger)("fs.PathContains"))},8103(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.arpWin=t.pingWin=t.nslookupWin=t.fsutil=void 0,t.isRXFile=S,t.pathDirectories=M,t.pathTo=async function({tool:e}){const t=m.isWin?(0,c.ensureSuffix)(e,".exe"):e,i=M();for(const e of i){const i=s.default.join(e,t);if(await S(i))return i}b().info("Failed to find tool",{tool:e,base:t,dirs:i})},t.pathIfExists=async function(e){if(null==e)return;const t=await e.stat({logLevel:"debug"});return null!=t&&t.isFile()&&t.size>w&&(0,g.isStatRX)(t,e.nativePath)?e.nativePath:void 0};const s=r(i(76760)),n=i(1708),a=i(19851),o=i(40958),l=i(96249),u=i(31586),c=i(51926),d=i(12168),h=i(50213),f=i(92234),m=i(43334),p=i(28874),g=i(64660),y=i(46473),v=i(16287),b=(0,a.lazy)(()=>(0,h.mkLogger)("fs.PathTo")),w=d.KiB;async function S(e,t=w){const i=await(0,v.statMaybe)(e,"trace");return null!=i&&i.isFile()&&(0,u.gte)(i.size,t)&&(0,g.isStatRX)(i,e)}function P(){try{return y.ProjectDir.Tools()}catch{return}}function M(){return(0,o.uniq)((0,o.compactBlanks)((0,l.flatten)((0,o.compactBlanks)([...p.Settings.toolPaths.values,P(),n.env.PATH,...(0,f.defaultPaths)()]).map(e=>e.split(s.default.delimiter)))))}t.fsutil=()=>"fsutil",t.nslookupWin=()=>"nslookup",t.pingWin=()=>"ping",t.arpWin=()=>"arp"},51704(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.toPathnames=u,t.pathDepth=function(e){const t=u(e);return null==t?void 0:t.length-(a.isWin?1:0)};const s=r(i(76760)),n=i(22573),a=i(43334),o=i(81168),l=i(17217);function u(e){if(!(0,n.blank)(e)){if(!(0,o.isString)(e)&&"pathnames"in e){const t=e.pathnames;if(Array.isArray(t))return t}return(0,l.toNativePath)(e)?.split(s.default.sep).filter(e=>null!=e&&""!==e)}}},95696(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PosixFile=t.NoOp=void 0,t.uniquePrefixes=function(e){return(0,S.contextFilter)(function(e){return(0,c.sortBy)(e,e=>e.nativePath)}(e),(e,t,i)=>null==i||!e.isDescendantOf(i))};const s=r(i(73024)),n=r(i(51455)),a=r(i(76760)),o=i(46466),l=i(19851),u=i(40958),c=i(76790),d=i(5233),h=i(22573),f=i(42659),m=i(6875),p=i(26905),g=i(96249),y=i(55835),v=i(31586),b=i(13538),w=i(12168),S=i(48884),P=i(50213),M=i(3685),T=i(45255),_=i(81168),E=i(94174),k=i(56519),D=i(56038),I=i(31562),C=i(84777),A=i(9595),x=i(38835),F=i(70025),O=i(57902),R=i(55222),L=i(43334),N=i(33847),j=i(24399),B=i(27449),z=i(28874),V=i(79915),H=i(45200),U=i(34238),W=i(63870),q=i(83278),$=i(88561),G=i(32144),K=i(73209),J=i(34075),Y=i(48313),Z=i(29882),X=i(91987),Q=i(53265),ee=i(17217),te=i(27794),ie=i(70257),re=i(13047),se=(0,l.lazy)(()=>new $.FileCache({name:"fs.PosixFile",clearOnFileChange:!0}));t.NoOp=Symbol("no-op");class ne extends q.BaseFile{nativePath;bflog=(0,l.lazy)(()=>(0,P.mkLogger)("fs.PosixFile",{file:this.nativePath}));constructor(e,t){super(e,t),this.nativePath=e}static forDirectoryEntry(e){return ne.for(e.nativePath,e)}static forMaybe(e){return(0,h.blank)(e)?void 0:ne.for(e)}static for(e,t){if(e instanceof ne)return e;const i=(0,ee.toNativePath_)(e),r=se().get(i);if(null!=r)return r.clearIfChanged();const s=(0,_.isString)(e)?(0,Q.resolve)(i):i,n=new ne(s,t);return se().set(i,n),se().set(s,n),n}static forPosix(e){return ne.for(e.replace(/\//g,a.default.sep))}static async forUri(e){return this.forMaybe(await(0,H.uriToNativePath)(e))}for(e,t){return ne.for(e,t)}forDirectoryEntry(e){return ne.for(e.nativePath,e)}clearable(){return super.clearable()||this.uriObject_.hasPrior()||this.uri_.hasPrior()||this.fileuri.hasPrior()||this.etag.hasPrior()||this.existingSidecars.hasPrior()||this.unlock.hasPrior()}clear({emit:e}={emit:!0}){return super.clear({emit:e}),this.uriObject_.unset(),this.uri_.unset(),this.fileuri.unset(),this.etag.unset(),this.existingSidecars.unset(),this.unlock.unset(),this}uriObject_=(0,l.lazy)(()=>(0,H.nativePathToUri)(this.nativePath));uri_=(0,l.lazy)(async()=>(await this.uriObject_()).uri.toString());uri(){return this.trap("uri",()=>this.uri_())}fileuri=(0,l.lazy)(()=>U.URI.file(this.nativePath).toString());mountPoint=(0,l.lazy)(async()=>(0,X.containedByNativePath)({ancestor:(0,A.libraryDir)(),descendant:this,acceptSelf:!0})||(0,X.containedByNativePath)({ancestor:(0,A.originalsDir)(),descendant:this,acceptSelf:!0})?void 0:(await(0,J.bestMountPointForPath)(this.nativePath))?.mountPoint);etag=(0,l.lazy)(async()=>{const e=await this.stat();return null==e?void 0:[e.size,e.mtime.getTime()].map(e=>R.Radix58.encode(e)).join("-")});async assertReadWriteExecutable(){if(!await this.isReadWriteExecutable())throw new Error(`Please check directory permissions for ${this.nativePath}: it must be read/write${L.isWin?"":"/execute"} by ${await(0,E.userDesc)()}`)}hide(){if(L.isWin||L.isMac)return this.trap("hide",async()=>(await(0,Y.hide_)(this),this))}isMountpoint=(0,l.lazy)(async()=>await this.isDirectory()&&(await(0,J.getMountPoints)()).some(e=>e.mountPoint===this.nativePath));isSidecar(){return(0,G.isSidecarExt)(this.ext)}existingSidecars=(0,l.lazy)(()=>(0,V.existingSidecars)(this));async existingDirectorySidecars(){return(0,k.filterAsync)({arr:(0,u.compactBlanks)(z.Settings.directorySidecars.valueOrDefault).map(e=>this.sibling(e)),f:e=>e.isNonEmptyFile()})}async existingExifSidecars(){return(await this.existingSidecars()).filter(e=>!(0,G.isJsonExt)(e))}async sidecar(){return(await this.existingExifSidecars()).find(e=>(0,_.equalsIgnoreCase)(e.ext,(0,V.defaultSidecarExt)()))??this.defaultSidecar()}defaultSidecar(){return this.sibling(this.base+(0,V.defaultSidecarExt)())}async jsonSidecars(){return(await this.existingSidecars()).filter(e=>(0,G.isJsonExt)(e))}async sidecarStats(e){e?.refresh&&this.existingSidecars.unset();const t=(0,g.flatten)(await Promise.all([this.existingSidecars(),this.existingDirectorySidecars()]));return(0,u.compact)(await Promise.all([this,...t].map(t=>t.stat(e))))}async thisOrSidecarMaxMtimeMs(e){const t=await this.sidecarStats(e);return(0,S.max)(t.map(e=>e.mtimeMs))}async writeStream_(e){return await(0,o.pipeline)(e,s.default.createWriteStream(this.nativePath,{autoClose:!0})),this.clearThisAndParent()}async applyIfEmpty_({fn_:e,minSizeBytes:i=0,returnUndefinedIfNotEmpty:r=!1,timeoutMs:s,skipWip:n=!1,skipFsLock:a=!1,retries:o=2,dirty:l=!1}){return(0,d.retryOnReject_)(async()=>{const o=await this.clear().isNonEmptyFile(i);if(!o){if(n&&a)return e(this);await this.applyWip_({fn_:async r=>await this.clear().isNonEmptyFile(i)?t.NoOp:e(r),skipFsLock:a,minSizeBytes:i,timeoutMs:s,dirty:l})}return o&&r?void 0:this.utimes()},{maxRetries:o,timeoutMs:2*s,retryDelay:3*f.secondMs,errorIsRetriable:e=>"EBUSY"===(0,p.errorCode)(e)})}wip(){return this.sibling((0,ie.addWipPrefix)(this.base))}isWip(){return(0,ie.isWip)(this.name)}async wipIsRecent(e=ie.WipTimeoutMs){return await this.wip().isFile()&&(0,v.gte)(await this.wip().clear().maxStatMs(),Date.now()-e)}unwip_(){return this.isWip()?this.mv_(this.sibling((0,ie.rmWipPrefix)(this.base))):Promise.resolve(this)}async applyWip_({fn_:e,minSizeBytes:i=0,skipFsLock:r=!1,timeoutMs:s,dirty:n=!1,preserveDestOnError:a=!1}){return await this.parent().mkdirp_(),(0,K.withLock_)({file:this,skipFsLock:r,timeoutMs:s,dirty:n},async()=>{const r=this.wip();try{await r.unlink("trace");const n=await(0,b.thenOrTimeoutError)(e(r),s);if(n===t.NoOp)return n;if(await(0,I.untilTrue)(()=>r.clear().isNonEmptyFile(i),{timeoutMs:T.ShortCommandTimeoutMs,intervalMs:250}))return await r.mv_(this),n;throw new Error(this+"applyWip(): still empty after waiting "+(0,m.fmtDuration)(T.ShortCommandTimeoutMs))}catch(e){throw this.bflog().warn("applyWip() threw error",{error:e}),await r.unlink("trace"),a||await this.unlink("trace"),e}})}copyFile_(e,t){return(0,D.time)({name:"fs.copyFile",p:async()=>{const i=this.dest(e);return this.nativePath===i.nativePath?this:this.#ot(i,z.Settings.fileCopyStrategy.valueOrDefault,t?.skipProgressWatchdog)}})}async#ot(e,t,i){switch(await e.parent().mkdirp_(),t){case B.FileCopyStrategies.builtin:return this.#lt(e,{useReflink:!1,atomic:!0,skipProgressWatchdog:i});case B.FileCopyStrategies["builtin-reflink"]:return this.#lt(e,{useReflink:!0,atomic:!0,skipProgressWatchdog:i});case B.FileCopyStrategies["builtin-no-wip"]:return this.#lt(e,{useReflink:!1,atomic:!1,skipProgressWatchdog:i});case B.FileCopyStrategies.native:return this.#ut(e,{preserveMetadata:!1});case B.FileCopyStrategies["native-preserve"]:return this.#ut(e,{preserveMetadata:!0});case B.FileCopyStrategies.auto:default:try{return await this.#lt(e,{useReflink:!1,atomic:!0,skipProgressWatchdog:i})}catch(t){if(!0===(0,F.isNonRetriableError)(t))return this.bflog().throw("_copyFile failed, but error wasn't retriable",{error:t,dest:e.nativePath});this.bflog().warn("_copyFile failed, trying _nativeCopyFile",{dest:e.nativePath,error:t})}return this.#ut(e,{preserveMetadata:!1})}}async maybeVerifySameOrThrow_(e){const t=performance.now();z.Settings.fileCopyVerify.valueOrDefault&&(await(0,I.untilTrue)(()=>this.matchesContent(e),{timeoutMs:(0,W.commandTimeoutMs)(),intervalMs:f.secondMs})||this.bflog().throw("copyFile_() failed (contents did not match after copy)",{dest:e,elapsedMs:(0,M.roundMs)(performance.now()-t)}))}async#lt(e,t){let i,r=e;const a=t.atomic?e.wip():e;try{const o=await this.stat_();if(null==o)return this.bflog().throw("Can't copy missing files"+x.NonRetriableErrorFlag);if(o.size>0){if(z.Settings.fileCopyVerify.valueOrDefault&&null==await this.sha())return this.bflog().throw("Can't copy file without SHA"+x.NonRetriableErrorFlag);if(await n.default.copyFile(this.nativePath,a.nativePath,t.useReflink?s.default.constants.COPYFILE_FICLONE:void 0),!0!==t.skipProgressWatchdog&&o.size>5*w.MiB&&(i=new N.PullProgressObserver({op:"Copying",path:this.nativePath,dest:e.nativePath},o.size,()=>a.size({refresh:!0}))),!await(0,I.untilTrue)(async()=>(0,v.approximates)(o.size,await a.size({refresh:!0})),{intervalMs:f.secondMs,timeoutMs:f.minuteMs}))return this.bflog().throw("copyFile_() failed",{expectedSize:o.size,actualSize:await a.size({refresh:!0})});await this.maybeVerifySameOrThrow_(a),r=e.$eql(a)?e:await a.mv_(e,O.LogLevels.trace)}try{await(0,te.touch_)({file:r,btimeMs:o.birthtimeMs,mtimeMs:o.mtimeMs,ensureFile:!1})}catch(e){this.bflog().warn("copyFile_(): couldn't set utimes to match source",{dest:r.nativePath,error:e})}try{await n.default.chmod(r.nativePath,o.mode)}catch(e){this.bflog().warn("copyFile_(): couldn't chmod",{dest:r.nativePath,mode:o.mode,error:e})}return this.bflog().debug("copyFile_(): success",{dest:r.nativePath}),r}catch(t){throw this.bflog().warn("copyFile_() failed",{dest:a?.nativePath,error:t}),await a.unlink(),a.$eql(e)||await e.unlink(),t}finally{r?.clearThisAndParent(),(0,y.map)(i,e=>e.end())}}async zCopyFile_(e,t){await e.parent().mkdirp_();const i=e.wip();try{await(0,re.zpipe_)(this.nativePath,s.default.createWriteStream(i.nativePath,{autoClose:!0}),t),await i.unwip_()}catch(e){throw await i.unlink(),e}return e.clear()}async copyTimeoutMs(){return(0,v.clamp)(T.ShortCommandTimeoutMs,10*f.minuteMs,(await this.size()??0)*W.MinIoRate)}async#ut(e,t){let i;const r=e.wip();try{const s=await this.stat_(),n=s?.size;if(null==s||null==n)return this.bflog().throw("Can't copy missing files");n>5*w.MiB&&(i=new N.PullProgressObserver({op:"Copying",path:this.nativePath,dest:r.nativePath},n,()=>e.clear().size()));const a=await this.copyTimeoutMs();if(L.isWin)await j.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,j.pwshQuote)(this.nativePath)} -Destination ${(0,j.pwshQuote)(r.nativePath)}`,e=>e);else if(L.isMac){const e=t.preserveMetadata?[this.nativePath,r.nativePath]:["--norsrc",this.nativePath,r.nativePath];try{await(0,C.stdout_)("ditto",e,{timerName:"proc.copy",timeoutMs:a})}catch(e){if(!t.preserveMetadata||!(0,F.isPermissionError)(e))throw e;this.bflog().info("ditto failed with permission error, retrying with --norsrc"),await(0,C.stdout_)("ditto",["--norsrc",this.nativePath,r.nativePath],{timerName:"proc.copy",timeoutMs:a})}}else{const e=t.preserveMetadata?["-a","-f",this.nativePath,r.nativePath]:["-f",this.nativePath,r.nativePath];try{await(0,C.stdout_)("cp",e,{timerName:"proc.copy",timeoutMs:a})}catch(e){if(!t.preserveMetadata||!(0,F.isPermissionError)(e))throw e;this.bflog().info("cp -a failed with permission error, retrying with cp -f"),await(0,C.stdout_)("cp",["-f",this.nativePath,r.nativePath],{timerName:"proc.copy",timeoutMs:a})}}await this.maybeVerifySameOrThrow_(r),await r.mv_(e,O.LogLevels.trace);try{await(0,te.touch_)({file:e,reference:this,ensureFile:!1})}catch(t){this.bflog().warn("_nativeCopyFile(): couldn't set utimes",{dest:e.nativePath,error:t})}return e.clearThisAndParent()}catch(t){return await r.unlink(),this.bflog().throw("_nativeCopyFile() failed"+x.DoNotSendErrorFlag,{dest:e.nativePath,error:t})}finally{(0,y.map)(i,e=>e.end())}}dest(e){const t=e.clear();return(0,h.notBlank)(this.ext)&&(0,h.blank)(t.ext)||t.isDirectorySync()?t.join(this.base):t}async renameYMDHMS_(e={}){if(await this.clear().notExists())throw new Error("Cannot rename: "+this+" doesn't exist.");const t=(0,f.fmtYMDHMS)(e.ts??await this.mtime()??Date.now()),i=(0,y.mapOr)(e.subdir,e=>this.parent().join(e),()=>this.parent());return this.mv_(i.join(this.name+"-"+t+this.ext))}async saveIfNewOrDelete(e){if(await this.clear().isEmptyOrMissing())return void await this.unlink("trace");const t=await this.siblingWithSameContents();if(null!=t)return await this.unlink(),t;const i=await this.sibling(e).ensureNew_();return this.mv_(i)}unlock=(0,l.lazy)(()=>L.isMac?(0,C.stdout_)("chflags",["nouchg",this.nativePath],{quiet:!0,timeoutMs:T.ShortCommandTimeoutMs}):void 0);relativePathTo(e){return a.default.relative(this.nativePath,(0,ee.toNativePath_)(e))}async mv_(e,t=O.LogLevels.debug){const i=(0,_.isString)(e)?this.parent().join(e):this.dest(e);if(this.nativePath===i.nativePath)return this.bflog().warn("mv(): no-op",{error:new Error("internal error")}),this;this.dir!==i.dir&&await i.parent().mkdirp_(),this.bflog().log(t,"mv_()",{dest:i.relativePathTo(this)});try{await(0,Z.move_)(this.nativePath,i.nativePath)}catch(e){this.bflog().warn("mv() failed. Calling unlock() and retrying...",{error:e}),await Promise.all([this.unlock(),i.unlock()]),await(0,Z.move_)(this.nativePath,i.nativePath)}return this.dir!==i.dir&&this.clearThisAndParent(),i.clearThisAndParent()}}t.PosixFile=ne},62105(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasBrowserImgMimeType=void 0,t.requiredTagsFilter=function(e){return P(t=>(0,o.allNotBlank)(...e.map(e=>t[e])))},t.notDimensionsTooSmall=M,t.notFileMissing=C,t.notFileTooSmall=A,t.notFileTooBig=x,t.simpleFileFiltersFor=F,t.whyRejectFileSimple=function(e){return l.Predicates.whyRejected(e,...F(e))},t.acceptFileSimple=function(e){return l.Predicates.accepted(e,...F(e))},t.acceptParentAndFileAndSimple=async function(e){const t=await e.parent();return null!=t&&!await(0,w.isExcludedDirectory)(t)&&await l.Predicates.accepted(e,...F(e))},t.expensiveFileFiltersFor=O,t.whyRejectFile=R,t.acceptFile=async function(e){return null==await R(e)};const r=i(40958),s=i(22573),n=i(31586),a=i(54993),o=i(48884),l=i(78984),u=i(28874),c=i(43207),d=i(97573),h=i(16170),f=i(54979),m=i(38148),p=i(40538),g=i(1078),y=i(42231),v=i(83278),b=i(19748),w=i(92423),S=i(16287);function P(e){return async t=>{const i=await(0,m.readRawTags)(t);if(null==i)return!1;const r=e(i);return null!=r&&r}}async function M(e){if(!(0,n.gt0)(u.Settings.minVideoDimension.valueOrDefault)&&!(0,n.gt0)(u.Settings.minImageDimension.valueOrDefault))return null;const t=await(0,f.readMimeType)(e);if(null==t||!t.startsWith("image/")&&!t.startsWith("video/"))return!1;const i=t.startsWith("video/")?u.Settings.minVideoDimension.valueOrDefault:u.Settings.minImageDimension.valueOrDefault;if(!(0,n.gt0)(i))return null;const r=await(0,g.extractSizeInfoFromFile)(e);if(null==r)return!1;const s=(0,n.gte)(r.ImageWidth,i)&&(0,n.gte)(r.ImageHeight,i);return null!=s&&s}async function T(e){if(!(0,n.gt0)(u.Settings.minVideoDurationSec.valueOrDefault))return null;const t=await(0,f.readMimeType)(e);return null!=t&&((0,h.isVideoMimeType)(t)?(0,n.gte)((0,c.extractDurationSec)(await(0,m.readRawTags)(e)),u.Settings.minVideoDurationSec.valueOrDefault):null)}async function _(e){if(!(0,n.gt0)(u.Settings.maxVideoDurationSec.valueOrDefault))return null;const t=await(0,f.readMimeType)(e);return null!=t&&((0,h.isVideoMimeType)(t)?(0,n.lte)((0,c.extractDurationSec)(await(0,m.readRawTags)(e)),u.Settings.maxVideoDurationSec.valueOrDefault):null)}async function E(e){return!(0,s.blank)(await(0,f.readMimeType)(e))}async function k(e){if((0,s.blank)(u.Settings.rejectRating.valueOrDefault))return null;const t=await(0,p.readTags)(e),i=(0,n.toInt)(t?.Rating);return null==i||!u.Settings.rejectRating.test(i)}async function D(e){return 0===u.Settings.keywordBlocklist.values.length?null:(0,d.rawTagKeywords)(await(0,p.readTags)(e)).every(e=>!0!==(0,y.leafIsExcluded)(e,u.Settings.keywordBlocklist.values))}async function I(e){if(!u.Settings.requireMakeModel.valueOrDefault)return null;const t=await(0,m.readRawTags)(e);return null==t||(0,s.blank)(t.MIMEType)?null:t.MIMEType.startsWith("image/")?null!=t&&(0,s.notBlank)(t.Make)&&(0,s.notBlank)(t.Model):null}async function C(e){return(0,v.isBaseFile)(e)?e.exists():(0,S.exists)(e.nativePath)}async function A(e){const t=u.Settings.minAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.gte)(i,t)}async function x(e){const t=u.Settings.maxAssetFileSizeBytes.valueOrDefault;if(t<=0)return null;const i=await e.size();return(0,n.lte)(i,t)}function F(e){return[{isSupportedFileExtension:b.isAssetFileExtension},...(0,w.excludedFilePredicates)(e),{notFileMissing:C},{notFileTooSmall:A,notFileTooBig:x}]}function O(e){return[...F(e),{notMissingMimeType:E},{supportedMimeType:h.isAssetFileMimeType},{notMissingMakeAndModelTags:I},{notDimensionsTooSmall:M},{notVideoTooShort:T},{notVideoTooLong:_},{notRejectedRating:k},{notExcludedKeyword:D}]}async function R(e,t){return await l.Predicates.whyRejected(e,...t??O(e))}t.hasBrowserImgMimeType=P(e=>(0,r.includes)(["image/jpeg","image/png"],(0,a.toS)(e.MIMEType)))},78133(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.posix2native=function(e,t){if((0,n.blank)(e))return e;if(s.default.sep===s.default.posix.sep)return e;const i=(0,n.notBlank)(t)?s.default.sep+s.default.sep+t+s.default.sep:"",r=e.split(s.default.posix.sep);return(0,a.equalsIgnoreCase)(r[0],t)&&r.unshift(),i+r.join(s.default.sep)},t.native2posix=function(e){return(0,n.blank)(e)||s.default.sep===s.default.posix.sep||s.default.posix.sep===s.default.sep?e:e.split(s.default.sep).join(s.default.posix.sep)};const s=r(i(76760)),n=i(22573),a=i(81168)},46473(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ProjectDir=void 0;const s=r(i(76760)),n=r(i(1708)),a=i(40958),o=i(38835),l=i(19851),u=i(50213),c=i(45969),d=i(29325),h=i(43334),f=i(65843),m=i(75742),p=i(53265),g=i(66430),y=["data","public","views","tools"],v=(0,l.lazy)(()=>b([(0,p.execDir)(),n.default.cwd(),__dirname]));function b(e,t=y){const i=(0,a.uniq)((0,a.compactBlanks)(e));for(const e of i)if((0,f.hasChildrenSync)(e,t))return e;for(const e of i)for(const i of(0,f.ancestors)(e).slice(0,(0,d.isPacked)()?2:6))if((0,f.hasChildrenSync)(i,t))return i}const w=(0,l.lazy)(()=>{const e=(0,a.compactBlanks)([n.default.env.PS_PROJECT_DIR]);return(0,c.isDocker)()?e.push("/opt/photostructure"):(0,h.isElectron)()&&(h.isMac?e.push(s.default.join((0,p.execDir)(),"..","Resources")):e.push(s.default.join((0,p.execDir)(),"resources"))),b(e)??(h.isMainElectron&&(0,d.isPacked)()?void 0:v())??(0,u.mkLogger)("fs.ProjectDir").throw("Failed to find project root."+o.FatalErrorFlag,{dirs:e})});function S(...e){return(0,l.lazy)(()=>{const t=s.default.join(w(),...(0,a.compact)(e));return t.includes(".asar")||(0,g.isReadableDirectorySync)(t)||(0,u.mkLogger)("fs.ProjectDir").throw("Not a readable directory:"+t,{fatal:!0}),t})}t.ProjectDir={Root:w,CwdRoot:v,Bin:(0,h.isElectron)()?S("app.asar",".webpack","main"):S("bin"),Data:S("data"),ICC:S("data","icc"),Migrations:S("data","migrations"),Public:S("public"),Tools:(0,c.isDocker)()||(0,h.isElectron)()&&(0,d.isPacked)()?S("tools"):S("tools",h.platformArch),Views:S("views"),isInDMG:function(e){return!!h.isMac&&(0,m.isPhotoStructureDmg)(e??t.ProjectDir.Root())}}},45879(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFileMaybe=async function(e,t=o.LogLevels.debug){try{return await(0,r.readFile)(e)}catch(i){return void u().log(t,".readFileMaybe("+e+")",i)}},t.intFromFileSync=function(e){return u().tap({msg:"intFromFileSync()",result:(0,n.toInt)((0,l.readFileSync)(e)?.toString(),{defaultValue:void 0}),meta:{nativePath:e}})};const r=i(51455),s=i(19851),n=i(31586),a=i(50213),o=i(57902),l=i(69428),u=(0,s.lazy)(()=>(0,a.mkLogger)("fs.ReadFile"))},93854(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readFilePart_=async function({nativePath:e,position:t=0,length:i}){let s;try{const n=i??(await(0,r.stat)(e)).size-t,a=Buffer.alloc(n);return s=await(0,r.open)(e,"r"),await s.read(a,0,n,t)}finally{await(s?.close())}};const r=i(51455)},69428(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.readFileSync=function(e){try{return o.readFileSync(e)}catch{}};const o=a(i(73024))},65238(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readdirCacheDir=t.ReadDirCacheName=void 0,t.readdir=async function(e,t){try{return await m(e,t)}catch(t){return void f().warn("readdir() failed",{file:e,error:t})}},t.readdir_=m,t.iterateDir_=p,t.recurseDir_=async function*e(t,i){for await(const r of p(t,i)){const n=(0,s.join)(t,r.name);if(r.isDirectory()){if(null!=i?.acceptDir&&!i.acceptDir(n))continue;yield*e(n,i)}yield r}},t.readdirSortedMaybe_=async function(e){return g().getOrSet(e,async()=>{const t=[];for await(const i of p(e,{onlyYieldIfSorted:!0}))t.push({basename:i.name,isFile:i.isFile(),isDirectory:i.isDirectory()});return 0===t.length?void 0:t})};const r=i(51455),s=i(76760),n=i(76790),a=i(45599),o=i(13538),l=i(50213),u=i(28874),c=i(25636),d=i(88561),h=i(16287);t.ReadDirCacheName="readdircache",t.readdirCacheDir=(0,a.defer)(()=>(0,s.join)(u.Settings.cacheDir.valueOrDefault,t.ReadDirCacheName));const f=(0,a.defer)(()=>(0,l.mkLogger)("fs.Readdir"));async function m(e,t){const i=[];for await(const r of p(e,{...t,sortThreshold:0}))i.push({basename:r.name,isFile:r.isFile(),isDirectory:r.isDirectory()});const r=(0,n.sortBy)(i,e=>[e.isDirectory,...(0,c.sortNaturalBy)(e.basename)]);return!0===t?.reverse&&r.reverse(),r}async function*p(e,t){const i=t?.sortThreshold??u.Settings.directorySortThreshold.valueOrDefault,s=t?.directorySortThresholdMs??u.Settings.directorySortThresholdMs.valueOrDefault,l=performance.now();let d,m=t?.retries??u.Settings.statRetries.valueOrDefault;const p=t?.timeoutMs??u.Settings.statTimeoutMs.valueOrDefault,g=(0,a.defer)(async()=>{try{await(d?.close())}catch(t){f().warn("Failed to close directory handle",{file:e,error:t})}}),y=async()=>{for(;;)try{return await(0,o.thenOrTimeoutError)(d.read(),p)}catch(t){if(f().warn("dir.read() failed for a child entry",{error:t,file:e}),--m<=0)throw t}};try{if(d=await(0,h.fsOperation_)(()=>(0,r.opendir)(e,t)),i<=0){let e;for(;null!=(e=await y());)yield e;return}const a=[];let o;for(;null!=(o=await y());)if(a.push(o),a.length>i||performance.now()-l>s){if(!0===t?.onlyYieldIfSorted)return;for(yield*a;null!=(o=await y());)yield o;return}const u=(0,n.sortBy)(a,e=>[e.isDirectory(),...(0,c.sortNaturalBy)(e.name)]);!0===t?.reverse&&u.reverse(),yield*u}finally{await g()}}const g=(0,a.defer)(()=>new d.FileCache({name:"readdirSorted"}))},53265(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.execDir=void 0,t.resolve=function(...e){const t=(0,a.compact)(e);if((0,a.isEmpty)(t))return(0,n.cwd)();if(!l.isWin||(0,c.isUNC)(t.join("\\")))return s.default.resolve(...t);const i=d.exec(t.join("/"))?.groups;return null!=i?s.default.resolve(f(i.drive+":\\"+i.path)):s.default.resolve(...t.map(f))},t.upcaseDriveLetters=f;const s=r(i(76760)),n=i(1708),a=i(40958),o=i(45599),l=i(43334),u=i(81168),c=i(29882),d=/^(?:\/cygdrive)?\/(?<drive>[a-z])\/(?<path>.*)$/i;t.execDir=(0,o.defer)(()=>s.default.dirname(process.execPath));const h=/^(?<drive>[A-Z]:)(?<path>.*)$/i;function f(e){if(!l.isWin)return e;const t=h.exec(e)?.groups;return null==t?e:t.drive.toUpperCase()+(0,u.ensurePrefix)((t.path??"").replace(/\//g,s.default.sep),s.default.sep)}},46356(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.seemsLikeSymlinkLoop=function(e){const t=new r.CountingSet;for(const i of(0,n.toPathnames)(e)??[])t.incr(i.toLowerCase().normalize());return t.max()>s.Settings.maxDuplicatePathElements.valueOrDefault};const r=i(22454),s=i(28874),n=i(51704)},50274(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarExts=void 0;const r=i(50989);t.SidecarExts=(0,r.strEnum)("xmp","mie","exv")},14427(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleDirent=function(e){return null!=e&&(0,r.notBlank)(e.basename)&&(0,s.isBoolean)(e.isFile)&&(0,s.isBoolean)(e.isDirectory)};const r=i(22573),s=i(38639)},17217(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.isSimpleFile=g,t.toNativePath=function(e){try{return null==e?void 0:y(e)}catch{return}},t.toNativePath_=y,t.basename=v,t.nameWithoutExt=function(e){return(0,f.parseNativePath)(v(e)).name},t.dirname=function(e){return g(e)?e.dir:l.default.dirname(y(e))},t.rootDir=function(e){if(g(e)){const t=e.pathnames;return h.isWin&&null!=t[0].match(b)?t[1]:t[0]}{const t=(0,d.stripPrefix)(e,"/"),i=t.indexOf(l.default.sep);return i>0?t.slice(1,i):void 0}},t.findFileIndex=function(e,t){for(let i=0;i<t.length;i++)if(t[i].nativePath===e.nativePath)return i;for(let i=0;i<t.length;i++)if((0,d.equalsIgnoreCase)(t[i].nativePath,e.nativePath))return i;return-1},t.isFileSync=function(e){if((0,u.blank)(e))return!1;if(e instanceof o.default.Dirent)return e.isFile();for(const t of[e,e.dirent])if((0,p.isSimpleDirent)(t))return t.isFile;try{return o.default.statSync(y(e)).isFile()}catch{return!1}},t.someSelfOrAncestor=async function e(t,i){if(null==t)return!1;const r=await i(t);return!0===r||t.isRoot?r:e(await t.parent(),i)},t.firstSelfOrAncestor=async function e(t,i){if(null==t)return;const r=await i(t);return null!=r||t.isRoot?r:e(await t.parent(),i)};const o=a(i(73024)),l=a(i(76760)),u=i(22573),c=i(98553),d=i(81168),h=i(43334),f=i(29882),m=i(53265),p=i(14427);function g(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.nativePath&&"string"==typeof e.base&&"string"==typeof e.ext&&"string"==typeof e.base&&"string"==typeof e.dir&&"function"==typeof e.isFile}function y(e){if(null==e)throw new TypeError("toNativePath(null)");if((0,u.blank)(e))throw new TypeError("toNativePath(blank)");if((0,d.isString)(e))return(0,m.resolve)(e);if(e instanceof o.Dirent){const t=e.parentPath;return(0,l.join)(t,e.name)}if((0,u.blank)(e.nativePath))throw new TypeError(`toNativePath(): blank nativePath: ${(0,c.stringify)(e)}`);return e.nativePath}function v(e){return e instanceof o.default.Dirent?e.name:g(e)?e.base:l.default.basename(String(e))}const b=/^[a-z]:$/i},16287(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RetriableFsCodes=void 0,t.fsOperation_=b,t.stat_=w,t.statMaybe=S,t.statToType=P,t.whyStatNotEql=T,t.statEql=function(e,t){return null==T(e,t)},t.exists=async function(e,t=m.LogLevels.info){return null!=await S(e,t)},t.isEmptyFile=async function(e,t){const i=await S(e,t?.logLevel??m.LogLevels.trace);return!(null!=i&&!(t?.emptyIsNew??1))&&(0,y.isEmptyStats)(i)},t.isNonEmptyFile=async function(e,t=0){const i=await S(e);return null!=i&&i.isFile()&&i.size>=t},t.nativePathIsFile=async function(e,t=m.LogLevels.info){return!0===(await S(e,t))?.isFile()},t.isDirectory=async function(e){return!0===(await S(e))?.isDirectory()},t.isReadableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,g.access)({stat:i,r:!0,x:!0})},t.isReadWriteableDirectory=async function(e,t=m.LogLevels.trace){const i=await S(e,t);return null!=i&&i.isDirectory()&&(0,g.isStatRWX)(i,e)},t.mtimeMs=_,t.isMtimeRecent=async function(e,t){return(0,f.isRecentMs)(await _(e),t)},t.statTimes=function(e){return(0,a.uniq)([e.birthtimeMs,e.mtimeMs].filter(e=>null!=e&&0!==e))};const s=r(i(51455)),n=i(19851),a=i(40958),o=i(5233),l=i(22573),u=i(42659),c=i(26905),d=i(31586),h=i(50213),f=i(76596),m=i(57902),p=i(28874),g=i(64660),y=i(68284),v=(0,n.lazy)(()=>(0,h.mkLogger)("fs.Stat"));function b(e,i){return(0,o.retryOnReject_)(e,{timeoutMs:p.Settings.statTimeoutMs.valueOrDefault,maxRetries:p.Settings.statRetries.valueOrDefault,retryDelay:u.secondMs,errorIsRetriable:e=>t.RetriableFsCodes.has((0,c.errorCode)(e)??""),...i})}function w(e){return(0,l.blank)(e)?v().throw("stat_() for blank path",{nativePath:e,retriable:!1,fatal:!1}):b(()=>s.default.stat(e))}function S(e,t=m.LogLevels.debug){return(0,l.blank)(e)?void 0:w(e).catch(i=>{v().log(t,"stat() failed",{nativePath:e,error:i})})}function P(e){return e.isDirectory()?"directory":e.isFile()?"file":"special"}function M(e){return(0,u.isDate)(e)?(0,u.unixtime)(e):(0,d.isNumber)(e)?e:void 0}function T(e,t){if(null==e||null==t)return"both must be defined: "+(null==e?"null":"stat")+" ≠ "+(null==t?"null":"stat");const i=P(e),r=P(t);if(i!==r)return"inconsistent file type: "+i+" ≠ "+r;for(const i of["size","mtime"]){const r=e[i],s=t[i],n=(0,d.diff)(M(r),M(s));if(null==n||n>1)return"unmatched "+i+": "+r+" ≠ "+s}}async function _(e){return(await S(e))?.mtimeMs}t.RetriableFsCodes=new Set(["EAGAIN","EALREADY","EBUSY","ECONNABORTED","ECONNRESET","ECONNREFUSED","EHOSTDOWN","EHOSTUNREACH","EINPROGRESS","EINTR","EMFILE","ENETDOWN","ENETRESET","ENETUNREACH","ESTALE","ETIMEDOUT","EWOULDBLOCK"])},68284(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.statSync=a,t.isEmptyStats=o,t.isFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isEmptyFileSync=function(e,t={emptyIsNew:!0}){const i=a(e);return t.emptyIsNew?null==i:o(i)},t.isNonEmptyFileSync=function(e,t=0){const i=a(e);return null!=i&&i.isFile()&&i.size>=t},t.isDirectorySync=function(e){return!0===a(e)?.isDirectory()};const s=r(i(73024)),n=i(22573);function a(e){try{return(0,n.blank)(e)?void 0:s.default.statSync(e,{throwIfNoEntry:!1})}catch{return}}function o(e){return null==e||e.isFile()&&0===e.size}},41080(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statTimeoutMs=function(){return r.Settings.statTimeoutMs.valueOrDefault};const r=i(28874)},66430(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathExistsSync=d,t.nativePathSizeSync=function(e){return(0,c.statSync)(e)?.size},t.isMtimeRecentSync=function(e,t){return(0,o.isRecentMs)((0,c.statSync)(e)?.mtimeMs,t)},t.isReadableDirectorySync=function(e){const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,x:!0})},t.isReadWriteableDirectorySync=function(e){if((0,a.blank)(e))return!1;const t=(0,c.statSync)(e);return null!=t&&t.isDirectory()&&(0,l.access)({stat:t,r:!0,w:!0,x:!0})},t.firstExistingDirectory=function(e){for(const t of e)if((0,a.notBlank)(t)){const e=(0,n.resolve)(t);if((0,c.isDirectorySync)(e))return e}},t.posixPathExistsSync=function(e){return!(0,a.blank)(e)&&d((0,u.posix2native)(e))};const s=r(i(73024)),n=i(76760),a=i(22573),o=i(76596),l=i(64660),u=i(78133),c=i(68284);function d(e){if((0,a.blank)(e))return!1;try{return s.default.existsSync(e)}catch{return!1}}},74128(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reportIfDoNotRun=t.reportIfCpuTooBusy=t.SyncReport=t.syncReport=t.SyncReportExt=t.ensureSyncReportReadme=t.SyncReportHeaders=t.SyncReportStates=t.SyncDirStates=t.FileDoneStates=t.SyncFileStates=t.AssetFileSyncStates=void 0,t.isUnsuccessfulState=function(e){return null==e||["canceled","deleted","absent","failed","excluded","timeout","unknown"].includes(e)},t.errorToState=Z,t.parseSyncReportLine=function(e){const i=e.trim();if(0!==i.length)try{const e=JSON.parse(i);if(!(0,f.isObject)(e)||null==(0,h.toInt)(e.ts))return;const r=e,s=(0,y.toS)(r.state),n=ie[s]??t.SyncReportStates.toValid(s)??"unknown",a=(0,y.toS)(r.path);return{...r,ts:(0,h.toInt)(r.ts)??-1,state:n,type:r.type??(a.endsWith("/")||a.endsWith("\\")?"dir":"file"),elapsedMs:(0,h.toInt)(r.elapsedMs),meta:r.meta}}catch{return}},t.syncReportDir=re,t.syncReportReadme=se,t.recentSyncReports=async function*(e){const i=re().nativePath;for await(const r of(0,O.recurseDir_)(i,{acceptDir:(0,L.acceptDateDirNewerThan)(e),reverse:!0}))if(r.isFile()&&r.name.endsWith(t.SyncReportExt)){const t=(0,n.join)(r.parentPath,r.name),i=await(0,R.statMaybe)(t);(0,h.gt)(i?.mtimeMs,e)&&(yield F.PosixFile.for(t))}};const r=i(51168),s=i(73024),n=i(76760),a=i(19851),o=i(22573),l=i(74310),u=i(42659),c=i(45599),d=i(98553),h=i(31586),f=i(68708),m=i(50989),p=i(51926),g=i(85556),y=i(54993),v=i(73568),b=i(25764),w=i(38836),S=i(99331),P=i(12959),M=i(87290),T=i(46296),_=i(77740),E=i(59958),k=i(98314),D=i(38835),I=i(70025),C=i(5012),A=i(34102),x=i(61848),F=i(95696),O=i(65238),R=i(16287),L=i(21727),N=i(57902),j=i(50213),B=i(7282),z=i(3685),V=i(23560),H=i(77377),U=i(28874),W=i(71567),q=i(21027),$=i(14854),G=i(84542),K=i(73428);t.AssetFileSyncStates=(0,m.strEnum)("unchanged","deleted","absent","trashed","unavailable","imported","updated","unknown"),t.SyncFileStates=(0,m.strEnum)(...t.AssetFileSyncStates.values,"canceled","excluded","failed","timeout","stalled","enqueued","started","copied","blocklisted","note","warning","completed"),t.FileDoneStates=(0,H.diff)(t.SyncFileStates.values,["enqueued","started","note"]),t.SyncDirStates=(0,m.strEnum)("scanning","canceled","failed","timeout","stalled","unavailable","excluded","scanned","completed"),t.SyncReportStates=(0,m.strEnum)(...t.SyncFileStates.values,...t.SyncDirStates.values);const J=/\babort(ed|ing)?\b/i,Y=/\btimeout\b/i;function Z(e){const t=(0,k.errorToS)(e);return(0,v.isAbortError)(e)||J.test(t)?"canceled":e instanceof g.TimeoutError||Y.test(t)?"timeout":"failed"}const X={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).",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:"sidecars will be referenced here. The details column will specify which source file(s) it will be associated with.",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."},Q={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 ee(e){return(0,f.entries)(e).map(([e,t])=>` - "${e}": ${t}`).join("\n")}const te=new Set([t.AssetFileSyncStates.deleted,t.AssetFileSyncStates.absent,t.SyncFileStates.failed,t.SyncFileStates.timeout,t.SyncFileStates.stalled,t.SyncDirStates.canceled]);t.SyncReportHeaders=(0,m.strEnum)(...(0,f.keys)(new class{ts;at;path;type;state;from;elapsedMs;details;url;meta;constructor(e,t,i,r,s,n,a,o,l,u={}){this.ts=e,this.at=t,this.path=i,this.type=r,this.state=s,this.from=n,this.elapsedMs=a,this.details=o,this.url=l,this.meta=u}}(0,"","","file","unknown","",0,"","")));const ie={rejected:"excluded",skipped:"unavailable",excludedDir:"excluded",synced:"imported",noop:"unchanged"};function re(){return(0,M.librarySyncReportsDir)()??F.PosixFile.for((0,T.logDir)()).join("sync-reports")}function se(){return re().join("README.txt")}t.ensureSyncReportReadme=(0,a.lazy)(()=>(0,K.writeTextfile_)(se().nativePath,(0,p.wrap)(`\n\nHowdy from PhotoStructure!\n\nThis directory contains your recent "sync reports".\n\nThese files are written as your scan paths are examined for photos and videos.\n\nPhotoStructure creates a new file when it restarts and when it completes importing a given scan path folder.\n\nThese are JSON Lines (.jsonl) files: each line is a complete JSON object describing one event. You can:\n\n - open them in VSCode or any text editor (each line is one event).\n - filter them with ripgrep: rg '"state":"failed"' *.jsonl\n - process them with jq: jq 'select(.state=="imported")' *.jsonl\n - convert to CSV for Excel/LibreOffice:\n jq -r '[.ts,.at,.path,.state,.from,.elapsedMs,.details,.url]|@csv' *.jsonl\n\n\nField descriptions\n==================\n\nThe "ts" field is the timestamp for the row, in millis from 1970-01-01.\n\nThe "at" field is ts in ISO format with only second resolution.\n\nThe "path" field is the native path of the directory or file. It will be empty for messages about system state.\n\nThe "state" field explains why that row was added.\n\nThe "from" field specifies which codepath added the sync report row.\n\nThe "elapsedMs" field is only added to rows completing a given path, and records how long that process took.\n\nThe "details" field will include information about the path, like why a given file or folder was rejected.\n\nThe "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).\n\nThe "meta" field contains any additional structured metadata as a nested object.\n\n\nDirectory state values\n======================\n\nThe "state" field for directories will be\n\n${ee(Q)}\n\n\nFile state values\n=================\n\nThe "state" field for files will be\n\n${ee(X)}\n\nFor more details see https://photostructure.com/go/sync-reports\n\n`,{maxLineLen:80}).join("\n"))),t.SyncReportExt=".jsonl",t.syncReport=(0,a.lazy)(()=>new ne);class ne extends w.EndableWrapper{#ct;#dt;#ht=0;#ft=new l.BoundedList(64);ee=new x.TypedEventEmitterImpl;recentRows=new l.BoundedList(200);constructor(){super("fs.SyncReport()",()=>this.close(),b.EndableRanks.predb),(0,t.ensureSyncReportReadme)()}get outputNativePath(){return this.#ct?.nativePath??this.#ft.last}get rowCount(){return this.#ht}get outputFiles(){return[...this.#ft]}getRecentRows(e=0,t=100){const i=[];for(const t of this.recentRows)t.ts>e&&i.push(t);return i.slice(-t)}maybeSystemData(e){(0,V.isSyncService)()&&this.writeSystemData(e)}writeSystemData(e){this.onProgress(e)}onProgress(e){if(this.ended)return void this.logger.warn("onProgress() called after sync report ended",{s:e,from:(0,C.stack)()});const t=le(e);if(null==e||(0,o.blank)(e.state))return this.logger.error(".onProgress(): invalid input",{s:e,from:(0,C.stack)()});{this.logger.log(!te.has(e.state)||"failed"===e.state&&I.PermissionErrorRegex.test((0,y.toS)(e.details))?N.LogLevels.debug:N.LogLevels.warn,"onProgress()",e);const i=t.ts??Date.now(),r={path:(0,y.toS)(t.path),state:e.state,details:(0,y.toS)(e.details).trim().replace(/\r?\n/g,"; ")},s={ts:i,at:t.at??new Date(i).toISOString(),...r,...(0,f.pick)(t,"from","url","elapsedMs","meta","type")};(0,_.getDevEnvFlag)(E.PS_SYNC_REPORT_STDOUT)&&process.stdout.write((0,d.stringify)(e)+G.Newline),this.#mt(s)}}#mt(e){e=le(e),this.recentRows.push(e),this.ee.emitSync("row",e),this.#pt().write((0,d.stringify)(e)+G.Newline),this.#ht++}#pt(){return null!=this.#dt&&this.#dt.writable||(this.#ct=function(){const e=r.DateTime.now();return re().join(e.toFormat("y-MM-dd"),(0,P.filestamp)({when:e.toJSDate(),includeMillis:!0})+"-sync-report"+t.SyncReportExt)}().ensureNewSync_({emptyIsNew:!1}),this.#ft.push(this.#ct.nativePath),this.logger.info("Opening new report: "+this.#ct),(0,_.getDevEnvFlag)(E.PS_SYNC_REPORT_STDOUT)&&(0,W.stdoutWrite)({syncReport:this.#ct.nativePath},!1),this.#dt=(0,s.createWriteStream)(this.#ct.nativePath),this.#dt.on("error",e=>{this.logger.error("Write stream error",e)})),this.#dt}async close(){try{this.logger.info("Closing sync report",{outputFile:this.#ct});const e=this.#dt;return this.#dt=void 0,this.#ht=0,await(0,q.disposeStream)(e),null==e?void 0:this.#ct}catch(e){return void this.logger.warn("Error closing sync report",e)}}async wrapSystemOp_({from:e,fn_:t,meta:i}){const r=performance.now();this.writeSystemData({from:e,state:"started",ts:Date.now()});try{const s=await t();return this.writeSystemData(le({from:e,state:"completed",elapsedMs:performance.now()-r,details:(0,p.isString)(s)?s:void 0,meta:{...i,result:s}})),s}catch(t){throw this.logger.warn("wrapSystemOp_() caught error",{error:t}),this.writeSystemData(le({from:e,state:Z(t),details:(0,k.errorToS)(t),elapsedMs:performance.now()-r,meta:i})),t}}async wrap_({path:e,from:i,type:r,fn_:s}){const n=performance.now();this.onProgress({path:e,from:i,type:r,state:t.SyncFileStates.started});try{const a=await s();a.elapsedMs=(0,h.toGt0f)(a.elapsedMs)??performance.now()-n;const o=a.state??(null!=a.error?t.SyncFileStates.failed:t.SyncFileStates.unknown);return o===t.SyncFileStates.unknown&&this.logger.error(i+" returned result with no state!"+D.InternalErrorFlag,{path:e,result:a}),this.onProgress({path:e,from:i,type:r,...a,state:o}),a}catch(t){throw this.onProgress({path:e,from:i,type:r,state:Z(t),details:(0,S.ending)()?void 0:(0,k.errorToS)(t),elapsedMs:performance.now()-n}),t}}}t.SyncReport=ne,t.reportIfCpuTooBusy=(0,a.lazy)(()=>{(0,A.ee)().on("cpuTooBusy",()=>oe())});const ae=(0,c.defer)(()=>(0,j.mkLogger)("fs.SyncReport")),oe=(0,a.lazy)(()=>{const e=$.CpuUsage.instance().busyPct();(0,t.syncReport)().maybeSystemData({from:"cpuUsage",state:"note",details:"Current system load is too high to schedule more work",meta:(0,f.compactValues)({loadCpuPct:(0,$.busyPctFromLoad)(),cpuBusyPct:e})}),ae().warn("Current system load is too high to schedule more work",{cpuBusyPct:e,max:U.Settings.cpuBusyPercent.valueOrDefault})},((0,B.isTest)()?15:60)*u.secondMs);function le(e){if(null!=e.elapsedMs){const t=(0,h.toGt0f)(e.elapsedMs);return null!=t?e.elapsedMs=(0,z.roundMs)(t):delete e.elapsedMs,e}return e}t.reportIfDoNotRun=(0,a.lazy)(()=>{(0,A.ee)().on("doNotRun",e=>{(0,t.syncReport)().maybeSystemData(e)})})},77772(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tmpBaseDir=void 0,t.randomDirname=y,t.setCurrentTestTmpDir=function(e){if(!(0,c.isTest)())throw new Error("setCurrentTestTmpDir() only valid in tests");v=e},t.tmp=b,t.tmpDir=w,t.tmpDirName=function(e){return w(e).nativePath},t.tmpFile=function(e){return b(e).ensureFileSync_()},t.tmpFileName=function(e){return(v??(0,t.tmpBaseDir)()).mkdirpSync_().join(e)},t.tmpCopySync_=function(e){const t=w().mkdirpSync_().join(e.base);return(0,r.copyFileSync)(e.nativePath,t.nativePath),t},t.tmpTree=async function(e,t){const i=w({prefix:e});for(const e of t)await S(i.join(e));return await g.PosixFile.clear(),i.clear()};const r=i(73024),s=i(48161),n=i(40958),a=i(22573),o=i(45599),l=i(30976),u=i(51926),c=i(7282),d=i(55476),h=i(38836),f=i(77740),m=i(55222),p=i(45969),g=i(95696);function y(){return"ps-test-"+m.AlphaRadix.randomUid(6,3)}let v;function b(e={}){const i=e.prefix??process.env.PS_TMPDIR_PREFIX;return(v??(0,t.tmpBaseDir)()).join((0,n.compactBlanks)([i,(0,l.randomChars)(12,l.LowercaseChars),e?.postfix]).map(e=>(0,u.stripPrefixSuffix)(e,{prefix:"-",suffix:"-"})).join("-"))}function w(e){const t=b(e);if(null==t.mkdirpSync())throw new Error("Could not mkdirsync "+t);return t}function S(e){return(0,a.notBlank)(e.ext)?e.touch():e.mkdirp()}t.tmpBaseDir=(0,o.defer)(()=>g.PosixFile.for((0,p.isDocker)()?"/data":(0,s.tmpdir)()).join(y()).mkdirpSync_()),(0,c.isTest)()&&(0,d.rmTestTmpfiles)()&&new h.EndableWrapper("_tmp() cleanup",()=>(0,f.getDevEnvFlag)("PS_SKIP_CLEANUP")?void console.log("PS_SKIP_CLEANUP: keeping ",{tmpDir:t.tmpBaseDir.prior()}):t.tmpBaseDir.prior()?.rmrf(),"last")},89966(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.rgNativePath_=t.sqliteNativePath_=t.jpegtranNativePath_=t.rawIdentifyNativePath_=t.dcrawEmuNativePath_=void 0,t.toolsDir=h,t.osToolsDir=function(){return s.default.join(d.ProjectDir.Root(),"tools",l.platformArch)},t.pathToTool_=f;const s=r(i(76760)),n=i(19851),a=i(26905),o=i(51926),l=i(43334),u=i(83278),c=i(8103),d=i(46473);function h(){return u.BaseFile.forMaybe(d.ProjectDir.Tools())}async function f(e){return l.isWin&&(e=(0,o.ensureSuffix)(e,".exe")),await(0,c.pathIfExists)(h()?.join(e))??await(0,c.pathTo)({tool:e})??(0,a.throwNewError)("Cannot find path for "+e)}t.dcrawEmuNativePath_=(0,n.lazy)(()=>f("dcraw_emu")),t.rawIdentifyNativePath_=(0,n.lazy)(()=>f("raw-identify")),t.jpegtranNativePath_=(0,n.lazy)(()=>f("jpegtran")),t.sqliteNativePath_=(0,n.lazy)(()=>f("sqlite3")),t.rgNativePath_=(0,n.lazy)(()=>f("rg"))},27794(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.touch_=async function e(t){const i=t.ensureFile??!0;if(null==t.file||(0,s.blank)(t.file))throw new Error("can't touch blank path");const n=(0,h.basename)(t.file);if(!(0,p.isValidFilename)(n))throw new Error(`Invalid filename: ${JSON.stringify(n)}`);const o=(0,h.toNativePath_)(t.file);i&&await(0,d.mkdirp_)((0,h.dirname)(t.file));const u=(0,a.defer)(()=>(0,f.statMaybe)(t.reference?.nativePath)),y=Math.round(g(t.mtimeMs)??(await u())?.mtimeMs??Date.now()),v=Math.round(g(t.atimeMs)??(await u())?.atimeMs??y),b=g(t.btimeMs);try{if(c.isMac&&null!=b){const e=(await(0,f.statMaybe)(o))?.birthtimeMs;null!=e&&e>b&&await(0,l.thenOrTimeoutError)((0,r.utimes)(o,new Date(b),new Date(b)),(0,m.statTimeoutMs)())}await(0,l.thenOrTimeoutError)((0,r.utimes)(o,new Date(v),new Date(y)),(0,m.statTimeoutMs)())}catch(s){if(!i||"ENOENT"!==s.code)throw s;await(0,l.thenOrTimeoutError)((0,r.appendFile)(o,""),(0,m.statTimeoutMs)()),!1!==t.ensureFile&&("atimeMs"in t||"mtimeMs"in t||"btimeMs"in t||"reference"in t)&&await e({...t,ensureFile:!1})}};const r=i(51455),s=i(22573),n=i(42659),a=i(45599),o=i(31586),l=i(13538),u=i(7282),c=i(43334),d=i(29882),h=i(17217),f=i(16287),m=i(41080),p=i(10234);function g(e){const t=null==e?void 0:(0,n.isDate)(e)?e.getTime():(0,o.isNumber)(e)?e:void 0;return(0,u.isTest)()&&null!=t?Math.round(t):t}},98216(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.trashMac=t.logger=void 0;const o=a(i(73024)),l=i(22573),u=i(30301),c=i(31586),d=i(70978),h=i(48884),f=i(85970),m=i(84777),p=i(43334),g=i(53265),y=i(41080);t.logger=(0,u.lazy)(()=>{});const v="/usr/bin/trash",b=(0,u.lazy)(()=>{if(p.isMac)try{return o.accessSync(v,o.constants.X_OK|o.constants.R_OK),v}catch{return}});async function w(e,i,r,s){const n=new Map;for(const a of(0,h.batches)(e,i))try{const e=await s(a);(0,t.logger)()?.info("Sent files to trash via "+r,{out:e,batch:a})}catch(e){(0,t.logger)()?.warn("Batch trash via "+r+" failed, retrying individually",{batch:a,error:e});for(const e of a)if(o.existsSync(e))try{const i=await s([e]);(0,t.logger)()?.info("Sent file to trash via "+r,{out:i,path:e})}catch(i){(0,t.logger)()?.warn("Failed to trash file via "+r,{path:e,error:i}),n.set(e,(0,d.toError)(i)??new Error(String(i)))}}return n}t.trashMac=(0,f.serialized)(async(e,i=64)=>{if(!p.isMac)throw new Error("trashMac() only works on macOS");const r=new Set;for(const i of e)if(!(0,l.blank)(i)){const e=(0,g.resolve)(i);o.existsSync(e)?r.add(e):(0,t.logger)()?.warn("Ignoring non-existent path",{input:i,resolved:e})}if(0===r.size)return new Map;const s=b();return null!=s?async function(e,t,i){const r=(0,y.statTimeoutMs)()*(0,c.clamp)(1,4,i/8);return w(t,i,"CLI",t=>(0,m.stdoutResult_)(e,t,{timeoutMs:r,ignoreStderr:!0}))}(s,[...r],i):async function(e,t){const i=(0,y.statTimeoutMs)()*(0,c.clamp)(1,4,t/8),r=e=>'the POSIX file "'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"';return w(e,t,"osascript",e=>(0,m.stdoutResult_)("osascript",["-e",`tell app "Finder" to move {${e.map(r).join(", ")}} to trash`],{timeoutMs:i,ignoreStderr:!0}))}([...r],i)})},50083(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.trashOrRm=async function({nativePaths:e,trySoftDeletes:i,skipDirectories:r}){(0,t.logger)()?.info("trashOrRm",{nativePaths:e,trySoftDeletes:i});const l=(0,n.uniq)((0,n.compactBlanks)(e)),u=[],p=[];for(const e of l)try{const t=await(0,s.lstat)(e);r&&t.isDirectory()?u.push({nativePath:e,action:"error",error:new Error("refusing to delete directory")}):p.push(e)}catch(t){u.push({nativePath:e,action:"error",error:(0,o.toError)(t)})}let g=new Map;if(i){(0,t.logger)()?.info("attempting to soft-delete",{existing:p});try{c.isMac?g=await(0,d.trashMac)(p):c.isWin?await(0,h.trashWin)(p):c.isLinux?await(0,f.trashMultiXDG)(p):(0,t.logger)()?.warn("No trash implementation for this platform")}catch(e){(0,t.logger)()?.warn("Failed to trash",{error:e})}}for(const e of p)try{i&&await m(e)?((0,t.logger)()?.info("soft-deleted",{file:e}),u.push({nativePath:e,action:"trash"})):((0,t.logger)()?.info("needing to rm",{file:e}),await(0,s.rm)(e,{recursive:!0,force:!0,maxRetries:3,retryDelay:1e3}),u.push({nativePath:e,action:"rm",trashError:g.get(e)}))}catch(t){u.push({nativePath:e,action:"error",error:(0,o.toError)(t)})}return(0,a.sortByInPlace)(u,t=>e.indexOf(t.nativePath)),(0,t.logger)()?.info("trashOrRm()",{results:u}),u};const r=i(73024),s=i(51455),n=i(40958),a=i(76790),o=i(70978),l=i(19851),u=i(31562),c=i(43334),d=i(98216),h=i(70345),f=i(89030);function m(e){return(0,u.untilTrue)(()=>null==(0,r.lstatSync)(e,{throwIfNoEntry:!1}),{intervalMs:500,timeoutMs:1e4})}t.logger=(0,l.lazy)(()=>{})},63793(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.trashOrRmUris=async function(e){f().info("trashOrRmUris()",{arr:e});const t=new Map;for(const i of e)try{const e=(0,r.toNotBlank)(i.nativePath)??await(0,u.uriToNativePath_)(i.uri);(0,r.blank)(e)?f().warn("Failed to convert URI to nativePath",{uri:i.uri}):t.set(e,i.uri)}catch(e){f().warn("Failed to convert URI to nativePath",{uri:i.uri,error:e})}const i=await(0,d.trashOrRm)({nativePaths:[...t.keys()],trySoftDeletes:l.Settings.trySoftDeletes.valueOrDefault,skipDirectories:!0});for(const e of i)await(0,o.ee)().emit("fileChanged",e.nativePath);return i.map(e=>("error"===e.action?(0,c.syncReport)().onProgress({from:h,type:"file",state:"failed",details:"Failed to move to trash: "+(0,a.errorToS)(e.error),path:e.nativePath}):(0,c.syncReport)().onProgress({from:h,type:"file",state:"rm"===e.action?"deleted":"trashed",details:"rm"===e.action?null!=e.trashError?"Moved to trash failed ("+(0,a.errorToS)(e.trashError)+"), permanently deleted":"Deleted":"Moved to trash",path:e.nativePath}),{...e,uri:t.get(e.nativePath)}))};const r=i(22573),s=i(45599),n=i(50213),a=i(98314),o=i(34102),l=i(28874),u=i(45200),c=i(74128),d=i(50083),h="fs.Trash",f=(0,s.defer)(()=>(0,n.mkLogger)(h))},70345(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.trashWin=async function(e,i=64){if(!a.isWin)throw new Error("trashWin() only works on Windows");const r=await(0,o.pathToTool_)("recycle-bin");for(const a of(0,s.batches)([...e],i))try{const e=await(0,n.stdoutResult_)(r,a,{timeoutMs:3e4});(0,t.logger)()?.info("Sent files to recycle bin",{out:e,batch:a})}catch(e){(0,t.logger)()?.warn("Failed to send batch of files to recycle bin",{batch:a,error:e})}};const r=i(30301),s=i(48884),n=i(84777),a=i(43334),o=i(89966);t.logger=(0,r.lazy)(()=>{})},89030(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.trashXDG_=_,t.trashMultiXDG=async function(e,t){return(0,m.mapAsync)({iter:(0,a.compactBlanks)(e),f:e=>_(e,t).catch(t=>({nativePath:e,error:t})),timeoutMs:3e4})};const r=i(77598),s=i(51455),n=i(76760),a=i(40958),o=i(22573),l=i(42659),u=i(45599),c=i(30301),d=i(54993),h=i(54557),f=i(24526),m=i(56519),p=i(72544),g=i(45969),y=i(28874),v=i(64660),b=i(34075),w=i(29882),S=i(17217),P=i(16287);async function M(e,i){if(await(0,P.isReadWriteableDirectory)(e))return e;try{return await(0,s.mkdir)(e,{recursive:!0,mode:448}),e}catch(r){(0,t.logger)()?.warn("Failed to mkdirp "+i,{dir:e,error:r})}}t.logger=(0,c.lazy)(()=>{});const T=(0,u.defer)(()=>new h.FifoCache({timeoutMs:y.Settings.statTimeoutMs.valueOrDefault,maxSize:64,clearEveryMs:5*l.minuteMs}));async function _(e,i){const a=await(0,s.stat)(e);if(null==(i=(0,o.toNotBlank)(i??await async function(e,i){return T().getOrSet((0,d.toS)(i),async()=>{const r=(0,p.xdg_home_trash)();(0,g.isDocker)()||await(0,s.mkdir)(r,{recursive:!0,mode:448});const a=await(0,P.statMaybe)(r),l=(0,v.isStatRWX)(a,r);if(l&&a?.dev===i)return r;const u=await(0,b.bestMountPointForPath)(e),c=await async function(e){if((0,o.blank)(e))return;const i=await M((0,n.join)(e,".Trash-"+(0,f.userid)()),"user-specific device trash directory");if(null!=i){const e=await(0,s.lstat)(i).catch(()=>null);if(null!=e&&!e.isSymbolicLink()&&(0,f.userids)().includes(e.uid))return i;(0,t.logger)()?.warn("Ignoring unsuitable trash directory",{uidTrash:i})}return M((0,n.join)(e,".Trash",(0,d.toS)((0,f.userid)())),"device trash directory")}((0,S.toNativePath)(u?.mountPoint));return null!=c?c:l?r:void(0,t.logger)()?.warn("No suitable trash directory found",{nativePath:e,homeTrash:r,mountpoint:u,dev:i})})}(e,a.dev))))throw new Error("No suitable XDG trash directory found");const u=(0,r.randomUUID)(),c=(0,n.join)(i,"files");await M(c,"Trash/files");const h=(0,n.join)(c,u),m=(0,n.join)(i,"info");await M(m,"Trash/info");const y=(0,n.join)(m,`${u}.trashinfo`),_=`[Trash Info]\nPath=${encodeURIComponent(e)}\nDeletionDate=${(0,l.fmtIsoDateTime)(new Date)}`;return await(0,s.writeFile)(y,_,{flush:!0}),await(0,w.move_)(e,h),{nativePath:e,destination:h,trashInfoPath:y}}},70854(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LibraryUIDStore=t.SystemUIDStore=t.UIDStore=void 0,t.mkuid=y,t.libraryUidStore=b;const r=i(22573),s=i(41400),n=i(55835),a=i(19851),o=i(50213),l=i(92782),u=i(37805),c=i(46292),d=i(34102),h=i(55222),f=i(28874),m=i(48313),p=i(87128),g=i(95696);function y(){return(0,l.safeRandomUid)({radix:h.GeoRadix,chars:24,splitEveryN:4})}class v extends p.JsonFileStore{rootDir;type;constructor(e,t){super(e.join("."+t+"-uid.json"),()=>({uid:y(),version:u.version,type:this.type,createdAt:Date.now()}),async e=>{try{await(0,m.hide_)(e)}catch(t){(0,o.mkLogger)("fs.UIDStore").warn("failed to hide UID file, "+e,{error:t})}}),this.rootDir=e,this.type=t}readUid_=(0,a.lazy)(async()=>(await this.read_())?.uid)}function b(e=f.Settings.libraryDir.valueOrDefault){return(0,r.blank)(e)?void 0:new v(g.PosixFile.for(e),"library")}t.UIDStore=v,t.SystemUIDStore=(0,a.lazy)(()=>(0,n.map)((0,c.configDir)(),e=>new v(g.PosixFile.for(e),"system"))),t.LibraryUIDStore=(0,a.lazy)(b),(0,s.later)(()=>{(0,d.ee)().on("clearCache",()=>{t.SystemUIDStore.unset(),t.LibraryUIDStore.unset()}),f.Settings.libraryDir.watchLater(()=>{t.LibraryUIDStore.unset()})})},84258(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.unlink=async function(e,t="warn"){for(const i of(0,u.toA)(e))try{null!=i&&(await(0,l.thenOrTimeoutError)(o.unlink((0,h.toNativePath_)(i)),(0,f.statTimeoutMs)()),m().debug("unlink()",{path:i}))}catch(e){m().log(t,"Failed to unlink",{path:i,error:e})}};const o=a(i(51455)),l=i(13538),u=i(59455),c=i(19851),d=i(50213),h=i(17217),f=i(41080),m=(0,c.lazy)(()=>(0,d.mkLogger)("fs.Unlink"))},10234(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidBasenameCharacters=t.InvalidFilesystemCharacters=void 0,t.isValidFilename=function(e){return c(e)===e},t.mkValidFilename=c;const s=r(i(76760)),n=i(68852),a=i(81168),o=i(43334);t.InvalidFilesystemCharacters=["<",">",":",'"',"/","\\","|","?","*"],t.InvalidBasenameCharacters=t.InvalidFilesystemCharacters.filter(e=>e!==s.default.posix.sep&&e!==s.default.win32.sep);const l=new RegExp(`[\\x00-\\x1f${(0,n.escapeRegExp)(t.InvalidFilesystemCharacters.join(""))}]+`,"g"),u=/^(?:CON|PRN|AUX|NUL|COM\d|LPT\d)(?:$|\.)/i;function c(e,t="_"){let i=(0,a.stripAnsiEsc)(e).replace(l,t);return o.isWin&&i.endsWith(".")&&(i=i.replace(/\.$/,t)),"."===i||".."===i||u.test(i)?t+i:i}},70257(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WipPrefix=t.WipTimeoutMs=void 0,t.addWipPrefix=function(e){return t.WipPrefix+(0,r.randomChars)(5).toUpperCase()+"-"+e},t.rmWipPrefix=function(e){return e.replace(a,"")},t.isWip=function(e){return a.test((0,n.basename)(e)??"")};const r=i(30976),s=i(45255),n=i(17217);t.WipTimeoutMs=s.ShortCommandTimeoutMs,t.WipPrefix=".WIP-";const a=/^.WIP-[\da-z]{5}-/i},73428(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.writeFile_=h,t.writeText_=async function(e,...t){return h(e,(0,c.crlf)((0,o.ensureSuffix)(t.map(l.toS).join("\n"),"\n")))},t.writeTextfile_=async function(e,...t){const i=(0,c.crlf)(...(0,o.wrap)(t));await h(e,i)},t.writeFileSync_=f,t.writeTextSync_=function(e,...t){return f(e,(0,c.crlf)((0,o.ensureSuffix)(t.map(l.toS).join("\n"),"\n")))};const s=i(73024),n=i(51455),a=r(i(76760)),o=i(51926),l=i(54993),u=i(34102),c=i(84542),d=i(29882);async function h(e,t){const i=a.default.dirname(e);await(0,d.mkdirp_)(i),await(0,n.writeFile)(e,t,{flush:!0}),(0,u.ee)().emit("fileChanged",i)}function f(e,t){const i=a.default.dirname(e);(0,d.mkdirpSync_)(i);const r=(0,s.openSync)(e,"w");try{"string"==typeof t?(0,s.writeSync)(r,t):(0,s.writeSync)(r,t,0,t.length),(0,s.fsyncSync)(r)}finally{(0,s.closeSync)(r)}(0,u.ee)().emitSync("fileChanged",i)}},13047(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.zcat_=b,t.zcat=async function(e,t){try{return await b(e,t)}catch(t){return void v().warn("zcat failed to read",{file:e,error:t})}},t.zpipe_=w,t.zCopyToBuffer_=S,t.readLinesGz_=function(e,t){const i=new p.LineReader;return w(e,i,t),i},t.readJsonGz_=P,t.readJsonGz=async function(e,t=m.LogLevels.warn){try{return await P(e)}catch(i){return void v().log(t,"readJsonGz("+e+"): failed",i)}},t.outputJsonGz_=M,t.outputJsonGz=async function(e,t,i=m.LogLevels.warn){try{await M(e,t)}catch(t){v().log(i,"outputJsonGz("+e+"): failed",t)}};const s=r(i(73024)),n=i(76760),a=i(46466),o=i(38522),l=i(19851),u=i(40958),c=i(98553),d=i(50213),h=i(57159),f=i(29882),m=i(57902),p=i(90753),g=i(1034),y=i(97867),v=(0,l.lazy)(()=>(0,d.mkLogger)("fs.zcat"));async function b(e,t){const i=await S(e);if(void 0!==t?.start||void 0!==t?.end){const e=t?.start??0,r=t?.end??i.length;return i.toString().substring(e,r+1)}return i.toString()}async function w(e,t,i){const r=await S(e);if(void 0!==i?.start||void 0!==i?.end){const e=i?.start??0,s=i?.end??r.length,n=r.subarray(e,s+1);return(0,a.pipeline)(new g.ReadableBuffer(n),t)}const n=[],l=s.default.createReadStream(e,{autoClose:!0}).on("error",e=>n.push(e)),c=e.toLowerCase(),d=c.endsWith(".gz")?(0,o.createGunzip)().on("error",e=>n.push(e)):c.endsWith(".br")?(0,o.createBrotliDecompress)().on("error",e=>n.push(e)):null;return(d?(0,a.pipeline)(l,d,t):(0,a.pipeline)(l,t)).finally(()=>{if((0,u.isNotEmpty)(n))throw new h.WrappedError("zPipe("+e+") failed",{causes:n,path:e})})}async function S(e,t){const i=new y.WritableToBuffer;if(void 0!==t?.start||void 0!==t?.end)return await w(e,i,t),await i.buffer;const r=s.default.createReadStream(e,{autoClose:!0}),n=e.toLowerCase(),l=n.endsWith(".gz")?(0,o.createGunzip)():n.endsWith(".br")?(0,o.createBrotliDecompress)():null;return l?await(0,a.pipeline)(r,l,i):await(0,a.pipeline)(r,i),await i.buffer}async function P(e){return(0,c.parseJSON)(await S(e))}async function M(e,t){const i=(0,c.stringify)(t);await(0,f.mkdirp_)((0,n.parse)(e).dir),await(0,a.pipeline)(new g.ReadableBuffer(i),(0,o.createGzip)(),s.default.createWriteStream(e,{autoClose:!0}))}},680(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessStatusHealthCheckIds=t.CriticalHealthCheckIds=void 0,t.CriticalHealthCheckIds=Object.keys({"library-db":!0,"library-directories":!0,"library-free-space":!0,"nodejs-version":!0,"proc-not-in-dmg":!0,"tools-exiftool":!0,"test-health-check":!0,"tools-sharp":!0,"tools-sqlite-version":!0}),t.ProcessStatusHealthCheckIds=[...t.CriticalHealthCheckIds,"proc-memory-use"]},60526(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exiftoolHealthCheck=void 0;const r=i(45599),s=i(47783),n=i(18454),a=i(58443);t.exiftoolHealthCheck=(0,r.defer)(()=>n.HealthCheck.for({section:"Tools",id:"tools-exiftool",ordinal:1,pendingMsg:"Checking ExifTool…",evalMode:"local",later:async()=>({level:"ok",msg:["ExifTool is OK",(0,a.toolDetailsToMsg)({desc:"ExifTool",path:await(0,s.exiftool)().exiftoolPath(),version:await(0,s.exiftoolVersion_)()}),"ExifTool reads and writes metadata in photos, videos, and sidecars."]})}))},19652(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirectoryCheck=async function(){const e=await(0,f.platformFolders)(),t=(0,s.uniq)([(0,d.homeDir)(),e.pictures,e.videos,e.desktop,await(0,c.defaultApplePhotosLibrary)()]).sort(),i=new Map,o=[];for(const e of(0,s.uniq)(t.filter(a.notBlank)).sort())try{await(0,r.readdir)(e,{withFileTypes:!0}),o.push(e)}catch(t){if(["ENOTDIR","ENOENT"].includes(t?.code))continue;i.set(e,t)}const u=0===i.size?{level:"ok",msg:["Default media directories are OK","The following directories are readable:",(0,n.ul)(o.map(n.code))]}:{level:"warn",msg:["Error reading "+(0,l.plur)(i.size,"media directory")+":",(0,n.ul)([...i.entries()].map(([e,t])=>(0,n.code)(e)+":"+(0,h.errorToS)(t,{maxLen:80})))]};return m().tap({msg:"externalDirectoryCheck",result:u})};const r=i(51455),s=i(40958),n=i(82950),a=i(22573),o=i(45599),l=i(12168),u=i(50213),c=i(79960),d=i(32551),h=i(98314),f=i(74041),m=(0,o.defer)(()=>(0,u.mkLogger)("health.externalDirectoryCheck"))},79483(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.externalDirsHealthCheck=void 0;const r=i(45599),s=i(45969),n=i(19652),a=i(18454);t.externalDirsHealthCheck=(0,r.defer)(()=>(0,s.isDocker)()?void 0:a.HealthCheck.for({section:"System",id:"media-directories",evalMode:"deferrable",pendingMsg:"Checking default photo directories…",later:n.externalDirectoryCheck}))},80779(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fileCopyHealthCheck=void 0;const s=r(i(73024)),n=r(i(51455)),a=i(76760),o=i(40958),l=i(82950),u=i(42659),c=i(45599),d=i(30976),h=i(84777),f=i(9595),m=i(98314),p=i(70025),g=i(84258),y=i(43334),v=i(24399),b=i(27449),w=i(28874),S=i(2858),P=i(18454),M=i(33866);async function T(e,t){const i=(0,d.randomChars)(6),r=(0,a.join)(e,`src-${i}.bin`),o=(0,a.join)(e,`dest-${t}-${i}.bin`),l=(0,a.join)(e,`.WIP-${i}-dest-${t}.bin`);try{switch(await n.default.writeFile(r,`test-${i}`),t){case b.FileCopyStrategies.builtin:case b.FileCopyStrategies["builtin-reflink"]:case b.FileCopyStrategies["builtin-no-wip"]:{const e=t===b.FileCopyStrategies["builtin-reflink"],i=t!==b.FileCopyStrategies["builtin-no-wip"],a=i?l:o;await n.default.copyFile(r,a,e?s.default.constants.COPYFILE_FICLONE:void 0),i&&await n.default.rename(l,o);break}case b.FileCopyStrategies.native:case b.FileCopyStrategies["native-preserve"]:{const e=t===b.FileCopyStrategies["native-preserve"];if(y.isWin)await v.PowerShell.instance().execute(`Copy-Item -LiteralPath ${(0,v.pwshQuote)(r)} -Destination ${(0,v.pwshQuote)(l)}`,e=>e);else if(y.isMac){const t=e?[r,l]:["--norsrc",r,l];await(0,h.stdout_)("ditto",t,{timeoutMs:3e4})}else{const t=e?["-a","-f",r,l]:["-f",r,l];await(0,h.stdout_)("cp",t,{timeoutMs:3e4})}await n.default.rename(l,o);break}case b.FileCopyStrategies.auto:return{strategy:t,success:!0}}return{strategy:t,success:!0}}catch(e){return{strategy:t,success:!1,error:((0,p.isPermissionError)(e)?"(permission error): ":"")+(0,m.errorToS)(e)}}finally{await(0,g.unlink)([r,o,l],"debug")}}function _(e){return e.map(e=>{const t=e.success?"✅":"❌",i=e.success?"":` (${e.error})`;return`${e.strategy}: ${t}${i}`}).join(", ")}t.fileCopyHealthCheck=(0,c.defer)(()=>P.HealthCheck.for({section:"Library",id:M.HealthCheckIds["library-file-copy"],ordinal:5,evalMode:"deferrable",pendingMsg:"Testing file copy capabilities…",ttlMs:u.hourMs,links:[{text:"File copy strategies",icon:"docs",url:"https://photostructure.com/faq/file-copy-strategies/"}],later:async()=>{const e=(0,f.originalsDir)();if(null==e||!(0,S.libraryHasSettings)())return{level:"no-library",msg:["No library is open"]};const t=(0,a.join)(e,".ps-copy-test");try{await n.default.mkdir(t,{recursive:!0});const e=w.Settings.fileCopyStrategy.valueOrDefault,i=[];if(e===b.FileCopyStrategies.auto){for(const e of b.FileCopyStrategies.values.filter(e=>e!==b.FileCopyStrategies.auto)){const r=await T(t,e);if(i.push(r),r.success){w.Settings.fileCopyStrategy.value=e;break}}const e=i.find(e=>e.success);return null==e?{level:"error",msg:["File copy test failed","No file copy strategy works on your originals directory.",`Tested: ${_(i)}`,"Please check filesystem permissions and mount options."]}:{level:"ok",msg:(0,o.compact)(["File copy is OK",`Strategy: ${(0,l.code)(e.strategy)} (auto-detected)`,`Tested: ${_(i)}`])}}{const r=await T(t,e);return i.push(r),r.success?{level:"ok",msg:["File copy is OK",`Strategy: ${(0,l.code)(e)}`,`Tested: ${_(i)}`]}:{level:"error",msg:["File copy test failed",`Strategy ${(0,l.code)(e)} failed: ${r.error}`,"Consider setting fileCopyStrategy to 'auto' to auto-detect a working strategy."]}}}catch(e){return{level:"error",msg:["File copy test failed",`Could not create test directory: ${e.message}`,`Directory: ${(0,l.code)(t)}`]}}finally{await n.default.rm(t,{recursive:!0,force:!0}).catch(()=>{})}}}))},70770(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileWatcherHealthCheck=void 0;const r=i(82950),s=i(42659),n=i(45599),a=i(76699),o=i(18454);t.fileWatcherHealthCheck=(0,n.defer)(()=>o.HealthCheck.for({section:"System",id:"system-file-watchers",pendingMsg:"Checking file watcher availability…",evalMode:"local",ttlMs:5*s.minuteMs,errorLinks:[{text:"How to fix file watcher limits",url:"https://forum.photostructure.com/t/fixing-file-watcher-limits/2618"}],later:async()=>{const e=await(0,a.checkFileWatcherStatus)();if(!e.available)return{level:"error",msg:["File watchers are currently unavailable","",e.suggestion??""].filter(Boolean)};const t=function(e){const t=["File watchers are available"];if(e.limits)switch(e.platform){case"linux":null!=e.limits.maxWatches&&t.push("","inotify limits:",` ${(0,r.code)("max_user_watches")}: ${e.limits.maxWatches.toLocaleString()}`,` ${(0,r.code)("max_user_instances")}: ${e.limits.maxInstances?.toLocaleString()??"?"}`);break;case"darwin":null!=e.limits.maxFilesSoft&&t.push("","File limits:",` soft: ${e.limits.maxFilesSoft.toLocaleString()}`,` hard: ${e.limits.maxFilesHard===1/0?"unlimited":e.limits.maxFilesHard?.toLocaleString()??"?"}`);break;case"win32":t.push("","Using ReadDirectoryChangesW")}return t}(e);return{level:"ok",msg:t}}}))},63664(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getLocalHealthSummary=t.getRemoteHealthSummary=void 0,t.getRemoteOrLocalHealthSummary=async function(){return await(0,t.getRemoteHealthSummary)()??await(0,t.getLocalHealthSummary)()},t.getRemoteOrLocalHealthSummarySync=function(){return t.getRemoteHealthSummary.syncValue()??t.getLocalHealthSummary.syncValue()};const r=i(22573),s=i(45599),n=i(41400),a=i(50268),o=i(98553),l=i(50213),u=i(23560),c=i(45255),d=i(5916),h=i(43205),f=i(28874),m=i(34238),p=i(51140),g=i(4988),y=i(18454),v=(0,s.defer)(()=>(0,l.mkLogger)("health.GetHealthSummary"));t.getRemoteHealthSummary=(0,d.lazyAsync)({desc:"health.getRemoteHealthSummary",later:async()=>{try{if((0,u.isWebService)())return;const e=await(0,g.get_)(m.URI.from({scheme:"http",authority:"127.0.0.1:"+f.Settings.httpPort.valueOrDefault,path:"/api/health"}),{headers:{"User-Agent":(0,h.simpleUserAgent)()},timeoutMs:c.ShortCommandTimeoutMs}),t=(0,o.parseJSON_)(e.data);if(p.HttpStatusIs.ok(e.statusCode)&&(0,a.isHealthCheckSummary)(t))return"ready"===t.state&&(0,r.toNotBlank)(t.libraryDir)!==(0,r.toNotBlank)(f.Settings.libraryDir.valueOrDefault)&&(v().error("getHealthSummary(): libraryDir mismatch! Switching to that library directory...",{local:f.Settings.libraryDir.valueOrDefault,remote:t.libraryDir}),f.Settings.libraryDir.envValue=t.libraryDir??void 0),v().debug("getHealthSummary()",{response:e}),t;v().warn("getHealthSummary(): invalid response",{response:e})}catch(e){v().warn("Failed to get health check summary from web service",{error:e})}}}),t.getLocalHealthSummary=(0,d.lazyAsync)({desc:"health.getLocalHealthSummary",later:()=>y.HealthCheck.awaitSettled()}),(0,n.later)(()=>{f.Settings.healthCheckIntervalMs.watch(e=>{t.getRemoteHealthSummary.setTTL(e),t.getLocalHealthSummary.setTTL(e)})})},18454(e,t,i){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheck=void 0;const s=i(40958),n=i(76790),a=i(22573),o=i(74310),l=i(42659),u=i(45599),c=i(41400),d=i(26905),h=i(50268),f=i(55835),m=i(30976),p=i(51926),g=i(13538),y=i(42279),v=i(59455),b=i(54993),w=i(76790),S=i(48884),P=i(22454),M=i(19851),T=i(50213),_=i(7282),E=i(3685),k=i(23560),D=i(73568),I=i(22911),C=i(99331),A=i(5916),x=i(56038),F=i(85296),O=i(77740),R=i(98314),L=i(70025),N=i(89206),j=i(28874),B=i(63870),z=i(680),V=i(33866),H=i(82638),U=(0,u.defer)(()=>(0,T.mkLogger)("health.HealthCheck"));class W{section;id;pendingMsg;evalMode;ordinal;links;okLinks;warnLinks;noLibraryLinks;errorLinks;onReset;ttlMs;timeoutMs;static#gt=[];static#yt(){return(0,s.filterInPlace)(this.#gt,e=>!e.isPending),this.#gt}static traceLater_(e,t){const i=new I.Deferred(e);i.catch(t=>{this.#ge.push(e+": failed: "+(0,R.errorToS)(t)),this.onResultChange()}),this.#yt().push(i);try{return i.observe((0,y.tot)(t))}catch(e){throw i.reject(e),e}}static#ge=new o.BoundedList(10);static#vt=!1;static#bt=new o.BoundedList(10);static priorRunStates(){return this.#bt.toA()}static#wt=new o.BoundedList(100);static#St=new P.CountingSet;static#et=[];static all=(0,u.defer)(()=>Object.freeze((0,n.sortBy)(this.#et,e=>e.sortBy)));static allCritical(){return this.all().filter(e=>e.isCritical)}static addError(e){this.#ge.push((0,p.isString)(e)?e:(0,R.errorToS)(e)),this.onResultChange()}static lastErrors(){return this.#ge.toA()}static addLoadingMsg(e){this.#wt.push({at:Date.now(),msg:e})}static normalizeMsg(e){return(0,s.compact)((0,v.toA)(e)).map(b.toS).map(e=>e.trim()).filter(e=>e.length>0)}static unseenOrOldestPendingTrace(){const e=this.allCritical().map(e=>e.result()).filter(e=>e.isPending);return U().info("unseenOrOldestPendingTrace",{pending:e.map(e=>({name:e.name,id:e.id})),shownCounts:this.#St.entriesByCountDesc()}),(0,f.map)((0,w.leastBy)(e,e=>[this.#St.get(e.name),e.startedAt]),e=>({msg:this.findById(e.name)?.pendingMsg??e.name,at:e.startedAt}))}static loadingMsg(){const e=this.#wt.shift()??this.unseenOrOldestPendingTrace();return(0,f.map)(e,e=>this.#St.incr(e.msg)),U().tap({msg:"loadingMsg",level:"info",result:e?.msg,meta:{runState:this.summary().state}})}static enableAll(){return this.disableAll(!1)}static disableAll(e=!0){const t=e?V.HealthCheckIds.values:[];return j.Settings.skipHealthCheckIds.value=t,r.reset()}static findById(e){return this.#et.find(t=>t.id===e)}static injectResults(e){this.#Pt=e,this.#Mt(e)}static#Pt=[];static clearLastInjectedResults(){this.#Pt=[]}static#Mt(e){const t=[],i=[];for(const r of e){const e=this.findById(r.id);null!=e?(e.injectResult(r),t.push(r.id)):i.push(r.id)}U().info("injectResults",{found:t,notFound:i})}static#Tt=[];static addResultWatcher(e){this.#Tt.push(e)}static removeResultWatcher(e){(0,s.remove)(this.#Tt,e)}static testResults(){return this.all().map(e=>e.result())}static enabledTestCount(){return(0,s.count)(this.all(),e=>!e.isSkipped()&&"disabled"!==e.toLevelSync())}static testResultsCritical(){return this.allCritical().map(e=>e.result())}static testResultsCriticalAsync(e){return I.Deferred.toAsyncIterable(this.testResultsCritical(),e)}static async errorResults(){return(await Promise.all(this.testResults())).filter(e=>"error"===e.level)}static async notOkResults(){return(await Promise.all(this.testResults())).filter(e=>(0,h.levelIsNotOK)(e.level))}static runState(){return this.summary().state}static onCriticalResult=(0,F.trailingThrottle)({fn:()=>{U().info("onCriticalResult()",this.summary.refresh())},minDelayMs:250});static summary=(0,M.lazy)(()=>this.#_t());static#Et(e){const t=this.#_t(e);return this.summary.set(t),t}static#_t(e){const t=e??this.allCritical().map(e=>e.toResultSync()),i=(0,H.summarizeHealthChecksSync)({errors:this.#ge,skipPending:this.#vt,healthCheckResults:t});return i.settled&&(this.#vt=!0),i.state!==this.#bt.last?.state&&this.#bt.push({state:i.state,ts:Date.now()}),U().tap({msg:"#summary",result:i,level:(0,h.levelIsNotOK)(i.level)?"warn":"info",meta:{healthCheckResults:t}})}static async awaitSettled(){const e=r.allCritical();if(e.every(e=>e.isSkipped()))return U().info("awaitSettled(): all critical checks are skipped"),r.#Et([]);const t=12e4,i=e.map(e=>e.id),n=[];for await(const e of r.testResultsCriticalAsync(t))(0,s.remove)(i,e.id),n.push(e),U().info("awaitSettled(): critical result",{result:e,pendingIds:i});return i.length>0&&U().warn("awaitSettled(): timed out with pending checks",{pendingIds:i,globalTimeoutMs:t}),U().tap({msg:"awaitSettled(): done",level:"info",result:r.#Et(n),meta:{results:n}})}static rerunSetup(){return this.resetDebounced.reset(),this.reset(),this.awaitSettled()}static onResultChange(){r.summary.unset()}static resetDebounced=(0,F.trailingThrottle)({fn:()=>r.reset(),minDelayMs:500});static abort(){for(const e of this.#et)e.isPending()&&e.logger.abortable.abort("HealthCheck.abort()")}static reset(){if((0,C.ending)())U().warn("Rejecting reset() when ending()",(0,d.shortStack)());else{this.abort(),this.onResultChange(),this.#ge.clear(),this.#wt.clear(),this.#St.clear(),this.#bt.clear(),this.summary.clear(),this.#vt=!1;for(const e of this.#et)e.reset();this.#Pt.length>0&&this.#Mt(this.#Pt)}}static async evaluateAll(e){const t=e?.concurrency??3,i=this.all().filter(e=>!e.isSkipped()&&e.isPending());for(const e of(0,S.batches)(i,t))await Promise.allSettled(e.map(e=>e.result()))}static for(e){const t=this.findById(e.id);if(null!=t)throw new Error(`Health check with id ${e.id} already exists in section ${t.section}`);const i=new r(e.section,e.id,e.pendingMsg,e.later,e.evalMode,e.ordinal,e.links,e.okLinks,e.warnLinks,e.noLibraryLinks,e.errorLinks,e.onReset,e.ttlMs,e.timeoutMs);return this.#et.push(i),this.all.reset(),i}logger;isCritical;sortBy;#S;#kt=0;constructor(e,t,i,s,n,a,o,l,u,c,d,f,m,p=B.commandTimeoutMs){this.section=e,this.id=t,this.pendingMsg=i,this.evalMode=n,this.ordinal=a,this.links=o,this.okLinks=l,this.warnLinks=u,this.noLibraryLinks=c,this.errorLinks=d,this.onReset=f,this.ttlMs=m,this.timeoutMs=p,this.logger=(0,T.mkLogger)("health.HealthCheck."+this.id),this.isCritical=z.CriticalHealthCheckIds.includes(this.id),this.sortBy=[h.HealthCheckSections.ordinal(this.section),a??999,this.id],this.#S=(0,A.lazyAsync)({desc:this.pendingMsg,later:()=>this.#Dt(()=>s(this.logger)),ttlMs:m}),this.isCritical&&this.#S.watchLater({onChange:r.onCriticalResult,onError:r.onCriticalResult})}isStale(){return this.#S.isStale()}isPending(){return null==this.#S.lastValue()}resolvedAtLeastOnce(){return this.#S.resolvedCount()>=1}stats(){return{id:this.id,level:this.toLevelSync(),msg:this.toResultSync().msg,resolvedCount:this.#S.resolvedCount(),rejectedCount:this.#S.rejectedCount(),lastValue:this.#S.lastValue()}}reset(){if(!(0,C.ending)())return this.onReset?.(),this.#S.clear(),this.logger.resetAbortable(),this;this.logger.warn("Rejecting reset() when ending()",(0,d.shortStack)())}setTTL(e){this.#S.setTTL(e)}injectResult(e){this.#S.set(e,l.hourMs)}refresh(){if(!(0,C.ending)())return this.#S.refresh()}result(){return this.#S()}isSkipped(){return j.Settings.skipHealthCheckIds.values.some(e=>e===this.id)}async#Dt(e){const t=performance.now(),i=this.timeoutMs()??(0,B.commandTimeoutMs)()??3e4,r=i>0?2*i:3e4;U().debug("#wrapLater() starting",{id:this.id,timeoutMs:r});try{if((0,O.getDevEnvFlag)("PS_SLOMO")&&await(0,c.delay)((0,m.randomInt)(.3*r,.7*r)),this.isSkipped())return this.#It({test:{level:"disabled",msg:["Disabled by "+j.Settings.skipHealthCheckIds.key]},elapsedMs:(0,E.roundMs)(performance.now()-t)});if((0,k.isWebService)()&&("syncRequired"===this.evalMode||"deferrable"===this.evalMode&&(0,N.isChildProcess)()))return this.#It({test:{level:"disabled",msg:[this.pendingMsg]},elapsedMs:(0,E.roundMs)(performance.now()-t)});if((0,C.ending)())return this.#It({test:{level:"disabled",msg:["Disabled: ending"]},elapsedMs:(0,E.roundMs)(performance.now()-t)});const i=await this.logger.awaitOrAbort((0,g.thenOrTimeoutError)(e(),r));return this.#It({test:i,elapsedMs:(0,E.roundMs)(performance.now()-t)})}catch(e){return(0,D.isAbortError)(e)||(0,C.ending)()?(this.logger.info("#wrapLater() aborted"),this.#It({test:{level:"disabled",msg:["Aborted: shutting down"]},elapsedMs:(0,E.roundMs)(performance.now()-t)})):this.#Ct({error:e,elapsedMs:(0,E.roundMs)(performance.now()-t)})}finally{(0,x.pushTime)({name:"health."+this.id,elapsedMs:(0,E.roundMs)(performance.now()-t)})}}#It({test:e,src:t="#toResult",elapsedMs:i}){const n=r.normalizeMsg(e.msg),a=e.level??((0,b.toS)(n).toLowerCase().includes("error")?"error":(0,b.toS)(n).toLowerCase().includes("warn")?"warn":"ok"),o=(0,s.compact)([...e?.links??("ok"===a||"pending"===a?this.okLinks:"warn"===a?this.warnLinks:"no-library"===a?this.noLibraryLinks:"error"===a?this.errorLinks:[])??[],...this.links??[]]),l={section:this.section,id:this.id,ts:Date.now(),level:a,msg:n,elapsedMs:i,meta:{from:(0,k.processName)()},...q(o)};l.runCount=this.#kt++;for(const e of r.#Tt)e(l);return(0,C.ending)()?l:this.logger.tap({level:"debug",msg:t,result:l})}#Ct({error:e,level:t,elapsedMs:i}){this.logger.warn("#toErrorResult",{error:e,level:t});const r=(0,p.stripSuffix)(this.pendingMsg,"…")+" failed:\n"+((0,a.toNotBlank)((0,R.errorToS)(e))??"(missing error)");return t??=!this.isCritical||(0,_.isTest)()||!(0,L.isFatalError)(e)&&r.toLowerCase().includes("warn")?"warn":"error",this.#It({test:{msg:r,level:t},src:"#toErrorResult",elapsedMs:i})}toLevelSync(){return this.#S.lastValue()?.level??"pending"}toResultSyncMaybe(){return this.#S.lastValue()}toResultSync(){return this.toResultSyncMaybe()??{section:this.section,id:this.id,ts:Date.now(),level:"pending",msg:[this.pendingMsg]}}async resultOrTimeout(e){const t=performance.now();return await(0,g.thenOrTimeoutMaybe)(this.result(),e)??this.#Ct({error:"Timeout",level:"warn",elapsedMs:(0,E.roundMs)(performance.now()-t)})}}function q(e){if((0,s.isEmpty)(e))return{};const[t,i]=(0,S.partition)(e,e=>"button"===e.type||"POST"===e.method),r={};return(0,s.isNotEmpty)(i)&&(r.links=(0,s.uniqBy)(i)),(0,s.isNotEmpty)(t)&&(r.buttons=(0,s.uniqBy)(t)),r}t.HealthCheck=W,r=W},33866(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckIds=void 0;const r=i(50989);t.HealthCheckIds=(0,r.strEnum)("library-db","library-directories","library-file-copy","library-free-space","library-tag-fts","library-tag-hierarchy","library-asset-file-hash-index","ps-version","media-directories","nodejs-version","problematic-files","proc-memory-use","proc-not-in-dmg","proc-security","progress-watchdog","service-errors","settings-env","settings-library","settings-system","cache-service","sync-rpc","systemd","system-file-watchers","system-load","system-temp","system-version","system-volumes","system-workers","tools-exiftool","tools-heif","tools-jpegtran","tools-powershell","tools-sharp","tools-sqlite-version","tools-ripgrep","tools-video","volume-uuids")},21525(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthCheckLevelOrder=t.HealthCheckLevelToLogLevel=void 0,t.isHealthCheckLevelFatal=function(e,t){return!(0,a.isPermaService)(t)&&(e===s.HealthCheckLevels.error||(0,a.isLibraryRequiredService)(t)&&e===s.HealthCheckLevels["no-library"])},t.summaryForLevel=function(e){switch(e){case"error":return{level:e,state:"failed",msg:["Some health checks failed","Your library won't be synced until these issues are addressed."],buttons:(0,c.restartResetOrShutdownButtons)()};case"no-library":return(0,l.isDocker)()&&!0!==(0,o.libraryDirPosixFile)()?.isReadWriteExecutableSync()?{level:e,state:"failed",msg:["Your docker container is missing a bind mount for "+(0,r.code)(u.Settings.libraryDir.valueOrDefault)],links:[c.DockerVolumeLink],buttons:[{text:"Shut down and add a bind mount for "+u.Settings.libraryDir.valueOrDefault,type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}]}:{level:e,state:"welcome",msg:["No PhotoStructure library is open"],links:[c.WhatIsALibraryLink],buttons:[{text:"Set up your library",type:"button",method:"GET",url:"/welcome",icon:"rocket_launch"}]};case"pending":return{level:e,state:"loading",msg:["Some health checks are still pending"]};case"stop-sync":return{level:e,state:"ready",msg:["Some health checks are preventing your library from being synced.","You should still be able to view your library, however."]};case"warn":return{level:e,state:"ready",msg:["Some health checks are not OK","Your library will still be synced, but you may want to address these issues."]};default:throw new n.UnreachableCaseError(e)}};const r=i(82950),s=i(50268),n=i(459),a=i(23560),o=i(87290),l=i(45969),u=i(28874),c=i(42495);t.HealthCheckLevelToLogLevel={error:"error","no-library":"info",pending:"debug",installing:"info","stop-sync":"info",warn:"warn",ok:"info",disabled:"debug"},t.HealthCheckLevelOrder=["error","no-library","pending","stop-sync","warn"]},88625(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.healthCheckSetup=void 0;const r=i(19851),s=i(34102),n=i(23560),a=i(60526),o=i(79483),l=i(80779),u=i(70770),c=i(18454),d=i(39214),h=i(86403),f=i(42482),m=i(35675),p=i(89035),g=i(31974),y=i(20752),v=i(85200),b=i(37301),w=i(28690),S=i(90721),P=i(15024),M=i(3956),T=i(29332),_=i(61274),E=i(38372),k=i(65756),D=i(12865),I=i(49913),C=i(60487),A=i(17714),x=i(84728),F=i(7245),O=i(16264),R=i(14156);t.healthCheckSetup=(0,r.lazy)(()=>{(0,a.exiftoolHealthCheck)(),(0,l.fileCopyHealthCheck)(),(0,n.isWebService)()&&((0,d.heifHealthCheck)(),(0,F.videoHealthCheck)()),(0,f.libraryDirectoriesCheck)(),(0,m.libraryFreeSpaceCheck)(),(0,M.settingsEnvHealthCheck)(),(0,_.settingsSystemHealthCheck)(),(0,T.settingsLibraryHealthCheck)(),(0,o.externalDirsHealthCheck)(),(0,p.memoryHealthCheck)(),(0,g.nodejsHealthCheck)(),(0,y.notInDMGHealthCheck)(),(0,v.osHealthCheck)(),(0,b.powershellHealthCheck)(),(0,w.progressWatchdogHealthCheck)(),(0,E.sharpHealthCheck)(),(0,h.jpegtranHealthCheck)(),(0,S.ripgrepHealthCheck)(),(0,P.securityHealthCheck)(),(0,k.sqliteHealthCheck)(),(0,D.systemdHealthCheck)(),(0,u.fileWatcherHealthCheck)(),(0,I.systemLoadHealthCheck)(),(0,C.systemTempHealthCheck)(),(0,O.volumeHealthCheck)(),(0,x.versionHealthCheck)(),(0,R.workerHealthCheck)(),(0,A.testHealthCheck)(),(0,s.ee)().on("error",()=>c.HealthCheck.resetDebounced()),(0,s.ee)().on("fatal",e=>c.HealthCheck.addError(e))})},58443(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toolDetailsToMsg=function(e){return(0,r.compactBlanks)([(0,s.b)(e.desc)+" "+(0,o.ver)(e.version),(0,s.code)(e.path),!1===e.isSupportedVersion?"(unsupported)":null]).join("\n")},t.mediaCodecDocsUrl=function(){return"https://photostructure.com/getting-started/media-codec-support/#"+((0,n.isDocker)()?"install-docker":a.isMac?"install-macos":a.isWin?"install-windows":"install-linux")};const r=i(40958),s=i(82950),n=i(45969),a=i(43334),o=i(63335)},39214(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifHealthCheck=void 0;const r=i(45599),s=i(41400),n=i(34102),a=i(277),o=i(38337),l=i(45969),u=i(76280),c=i(18454),d=i(58443);t.heifHealthCheck=(0,r.defer)(()=>c.HealthCheck.for({section:"Tools",id:"tools-heif",evalMode:"local",pendingMsg:"Checking HEIF tooling…",links:[{text:"Manage photo and video tools",url:"/welcome/tools",icon:"build"},{text:"HEIF support",url:(0,d.mediaCodecDocsUrl)(),icon:"docs"}],warnLinks:[{text:"View install log",url:"/logs?filter=install",icon:"article"},...(0,l.isDocker)()?[]:[{text:"Re-check for HEIF tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}]],later:async()=>{const e=await(0,a.getHeifSupportDetails)(),t=await(0,a.getHeifThumbnailerDetails)();return null==e?"running"===o.InstallState.instance().phase?{level:"installing",msg:["Installing HEIF tooling…"]}:{level:"warn",msg:["HEIF images will not be imported","No HEIF tooling was found."]}:!1===e.isSupportedVersion?{level:"warn",msg:["HEIF images will not import correctly",(0,d.toolDetailsToMsg)(e),"Minimum libheif version: v1.18.0","Earlier versions crash from recent iPhone photos."]}:"sips"===e.desc||(0,u.semVerSatisfies)(e.version,">=1.19.0")?{level:"ok",msg:["HEIF processing is OK",(0,d.toolDetailsToMsg)(e),null==t?void 0:(0,d.toolDetailsToMsg)(t)]}:{level:"warn",msg:["HEIF images may have visual quality issues",(0,d.toolDetailsToMsg)(e),"Earlier versions produce wrong pixel values.","Upgrade to libheif v1.19.0 or later for improved decoding."]}}})),(0,s.later)(()=>{(0,n.ee)().on("clearToolCache",()=>t.heifHealthCheck.prior()?.reset())})},86403(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.jpegtranHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(89966),a=i(51210),o=i(76280),l=i(18454),u=i(58443);async function c(){const e=await(0,a.jpegtranVersion_)(),t=(0,o.semVerSatisfies)(e,">=1.5");return{desc:"jpegtran",path:await(0,n.jpegtranNativePath_)(),version:e,satisfies:t}}t.jpegtranHealthCheck=(0,s.defer)(()=>l.HealthCheck.for({section:"Tools",id:"tools-jpegtran",ordinal:2,evalMode:"deferrable",pendingMsg:"Checking "+(0,r.code)("jpegtran")+"…",later:async()=>({level:"ok",msg:["jpegtran is OK",(0,u.toolDetailsToMsg)(await c()),(0,r.code)("jpegtran")+" checks JPEG images for corruption."]})}))},42495(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WhatIsALibraryLink=t.DockerVolumeLink=void 0,t.restartResetOrShutdownButtons=function(){return(0,r.compact)([(0,s.libraryHasSettings)()?{text:"Try again",title:"Restart the current library",type:"button",method:"POST",url:"/admin/restart",icon:"refresh"}:void 0,{text:"Change PhotoStructure library",title:"Create a new library or switch to an existing library",type:"button",method:"POST",url:"/admin/clear-library",icon:"switch_folder"},{text:"Exit PhotoStructure",title:"Shut down PhotoStructure. Your library will no longer be accessible until you re-launch PhotoStructure.",type:"button",method:"POST",url:"/admin/shutdown",icon:"power"}])};const r=i(40958),s=i(2858);t.DockerVolumeLink={type:"link",text:"Read about PhotoStructure docker bind-mounts",url:"https://photostructure.com/go/docker-volumes/",icon:"docs"},t.WhatIsALibraryLink={type:"link",text:'What\'s a "PhotoStructure library?"',url:"https://photostructure.com/faq/library/",icon:"docs"}},42482(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDirectoriesCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(31586),l=i(94174),u=i(87290),c=i(98314),d=i(34075),h=i(45969),f=i(43334),m=i(28874),p=i(2858),g=i(18454),y=i(42495);async function v(){const e=await(0,u.setupLibraryDirs_)();return(0,p.libraryHasSettings)()?{level:"ok",msg:["Library directories are OK","Verified directory permissions for the following directories:",(0,s.ul)(...e.map(e=>(0,s.code)(e)))]}:{level:"no-library",msg:["Your PhotoStructure library hasn't been set up yet"]}}t.libraryDirectoriesCheck=(0,a.defer)(()=>g.HealthCheck.for({section:"Library",id:"library-directories",ordinal:0,pendingMsg:"Checking library directories…",evalMode:"local",ttlMs:n.minuteMs,links:[{text:'What\'s a "PhotoStructure library?"',icon:"docs",url:"https://photostructure.com/faq/library/"},...(0,h.isDocker)()?[{text:"Read how to setup up Docker",icon:"docs",url:"https://photostructure.com/server/photostructure-for-docker/"}]:[]],later:async()=>(await(0,p.readSettings)(),(0,h.isDocker)()?async function(){const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"error",msg:[`Something's amiss: ${(0,s.code)("PS_LIBRARY_DIR")} is blank`,`The default is ${(0,s.code)(m.Settings.libraryDir.toEnvLine(m.Settings.libraryDir.defaultValue))}`]};const t=await(0,d.bestMountPointForPath)(e.nativePath);if(null==t||"/"===t.mountPoint)return{level:"warn",msg:[e.nativePath+" is not a bind-mount",`Your library directory, ${(0,s.code)(e)}, does not seem to be a bind mount.`,"Your library contents will disappear when you shut down this container."],links:[y.DockerVolumeLink]};try{if(!await e.isReadWriteExecutable_()){const t=await e.stat(),i=[`Your library directory, ${(0,s.code)(e)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`];return null!=t&&(0,o.gte0)(t.uid)&&i.push("The owner of this directory is userid "+(0,s.code)(t.uid)+", groupid "+(0,s.code)(t.gid)),{level:"error",msg:[...i,"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}return await v()}catch(t){return{level:"error",msg:[`Your library directory, ${(0,s.code)(e)}, can't be set up for ${await(0,l.userDesc)()}.`,(0,c.errorToS)(t,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."],links:[y.DockerVolumeLink]}}}():async function(){const e=(0,p.librarySettingsFile)()?.clear(),t=(0,u.libraryDirPosixFile)()?.clear();if(null==e||null==t)return{level:"no-library",msg:["No PhotoStructure library is open"]};if(await e.notExists())return{level:"no-library",msg:(0,r.compact)(["No PhotoStructure library is open",(0,s.code)(e)+" does not exist"])};try{return await t.isReadWriteExecutable_()?await v():{level:"no-library",msg:[`Your library directory, ${(0,s.code)(t)}, is not read/write${f.isWin?"":"/execute"} by ${await(0,l.userDesc)()}`,"Please fix the permissions or pick a new library directory."]}}catch(e){return{level:"no-library",msg:[`Your library directory, ${(0,s.code)(t)}, can't be set up for ${await(0,l.userDesc)()}`,(0,c.errorToS)(e,{maxLen:80}),"Please fix the permissions for this bind mount and restart the container."]}}}())}))},35675(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFreeSpaceCheck=void 0;const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(31586),l=i(12168),u=i(87290),c=i(77740),d=i(34075),h=i(28874),f=i(18454);t.libraryFreeSpaceCheck=(0,a.defer)(()=>f.HealthCheck.for({section:"Library",id:"library-free-space",pendingMsg:"Checking free space on library volume(s)…",evalMode:"local",ttlMs:n.dayMs,later:async()=>{if(!(0,o.gt0)(h.Settings.minDiskFreeGb.valueOrDefault))return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.code)(h.Settings.minDiskFreeGb.key+"=0")}`};const e=(0,u.libraryDirPosixFile)();if(null==e)return{level:"disabled",msg:"Library disk free test disabled: no library is open"};if(!0!==await e.isDirectory())return{level:"disabled",msg:`Library disk free test disabled: ${(0,s.code)(e)} is not a directory`};const t=[];for(const e of await(0,u.setupLibraryDirs_)()){const i=await(0,d.bestVolumeForPath)(e.nativePath);if(null==i)return{level:"warn",msg:`Could not check for minimum disk free: no volume found for library path ${(0,s.code)(e)}`};let r=t.find(e=>e.vol.mountPoint===i.mountPoint);null==r&&(r={vol:i,paths:[]},t.push(r)),r.paths.push(e.nativePath)}const i=h.Settings.minDiskFreeGb.valueOrDefault*l.GB,n=[];for(const{vol:e,paths:a}of t){if(!(0,o.gte0)(e.available))return{level:"warn",msg:"Could not check for minimum disk free: available space on "+e.mountPoint+" was missing"};const t=(0,s.b)(`Volume ${(0,s.code)(e.mountPoint)} has ${(0,l.fmtBytes)(e.available)} free.`)+`\nThis volume is used for these PhotoStructure directories:\n${(0,s.ul)((0,r.uniq)(a).sort().map(s.code))}`;if(e.available<i||(0,c.getDevEnvFlag)("PS_FORCE_FULLDISK"))return{level:"stop-sync",msg:"Library volume is almost full\n"+(0,s.code)(h.Settings.minDiskFreeGb.key)+" is set to "+(0,l.fmtBytes)(i)+".\n"+t+"\nPhotoStructure sync is automatically paused until you free up at least "+(0,l.fmtBytes)(i-e.available)+" on "+e.mountPoint};if(n.push(t),e.available<.75*i)return{level:"warn",msg:"Library volume is almost full"+t}}return{level:"ok",msg:["Library free disk space is OK",...n,"","PhotoStructure sync will pause if free space drops below "+(0,s.code)(h.Settings.minDiskFreeGb.key)+", set to "+(0,l.fmtBytes)(i)+"."]}}}))},89035(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.memoryHealthCheck=t.memoryUsageIsHigh=void 0,t.memoryUsageTest=g;const s=r(i(48161)),n=i(19851),a=i(82950),o=i(42659),l=i(45599),u=i(31586),c=i(12168),d=i(31578),h=i(23560),f=i(28874),m=i(18454);function p({desc:e,bytes:t,level:i,thresholdBytes:r}){return{level:i,msg:[e+" from "+(0,h.serviceName)()+" is "+("ok"===i?"OK":"high"),(0,a.ul)(["Current: "+(0,c.fmtBytes)(t,2),"Threshold: "+(0,c.fmtBytes)(r,2)])]}}function g(){if(s.default.totalmem()<c.GB)return{level:"warn",msg:"PhotoStructure may need more than a GB of RAM to run, especially if your library is large."};const e=f.Settings.maxMemoryMb.valueOrDefault,t=e*c.MB,i=(0,d.memoryUsageBytes)(),r=(0,d.memoryUsageMb)();return(0,u.gt0)(e)&&r>2*e?p({level:"error",desc:"Memory usage critically high",bytes:i,thresholdBytes:2*t}):(0,u.gt0)(e)&&r>e?p({level:"error",desc:"Used memory exceeds limit",bytes:i,thresholdBytes:t}):(0,u.gt0)(e)&&r>.75*e?p({level:"warn",desc:"Used memory elevated",bytes:i,thresholdBytes:t}):p({level:"ok",desc:"Used memory",bytes:i,thresholdBytes:t})}t.memoryUsageIsHigh=(0,n.lazy)(()=>"ok"!==g().level,o.secondMs),t.memoryHealthCheck=(0,l.defer)(()=>m.HealthCheck.for({section:"System",id:"proc-memory-use",pendingMsg:"Checking memory usage…",evalMode:"local",errorLinks:[{text:"Restart web service",type:"button",method:"POST",url:"/admin/web-restart",icon:"refresh"}],ttlMs:o.minuteMs,later:async()=>g()}))},31974(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.nodejsHealthCheck=void 0;const s=r(i(1708)),n=i(82950),a=i(45599),o=i(26033),l=i(18454),u=i(58443);t.nodejsHealthCheck=(0,a.defer)(()=>l.HealthCheck.for({section:"Tools",id:"nodejs-version",ordinal:4,pendingMsg:"Checking Node.js…",evalMode:"local",links:[{text:"Read about PhotoStructure Node.js support",icon:"docs",url:"https://photostructure.com/server/photostructure-for-node/#prerequisites"}],later:async()=>{const e=[(0,u.toolDetailsToMsg)({desc:"Node.js",version:s.default.versions.node,path:s.default.execPath}),"PhotoStructure requires Node.js version "+(0,n.code)(o.RequiredNodeRange),"Node.js is used to run PhotoStructure's server and background tasks."];return(0,o.isSupportedNode)()?{level:"ok",msg:["Node.js is OK",...e]}:{level:"warn",msg:["Node.js is not a supported version",...e]}}}))},20752(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.notInDMGHealthCheck=void 0;const r=i(45599),s=i(46473),n=i(43334),a=i(18454);t.notInDMGHealthCheck=(0,r.defer)(()=>n.isMac&&(0,n.isElectron)()?a.HealthCheck.for({section:"System",id:"proc-not-in-dmg",pendingMsg:"Checking PhotoStructure's installation directory…",evalMode:"local",later:async()=>s.ProjectDir.isInDMG()?{level:"warn",msg:["PhotoStructure may be running from a read-only disk image.","Please quit, drag and drop the PhotoStructure icon onto your Applications folder, and launch PhotoStructure from that directory."],checkboxLabel:"Open https://photostructure.com/getting-started/installation/ in your browser"}:{level:"ok",msg:"PhotoStructure is installed correctly."}}):void 0)},85200(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.osHealthCheck=void 0;const s=r(i(48161)),n=i(45599),a=i(96175),o=i(18454);t.osHealthCheck=(0,n.defer)(()=>o.HealthCheck.for({section:"System",id:"system-version",pendingMsg:"Checking operating system…",evalMode:"local",links:[{text:"What do I need to run PhotoStructure?",icon:"docs",url:"https://forum.photostructure.com/t/what-do-i-need-to-run-photostructure/44"}],later:async()=>{const e=(0,a.whyOsNotSupported)();return null==e?{level:"ok",msg:["Operating system is OK","PhotoStructure supports "+(0,a.osFullName)()]}:{level:"warn",msg:["The current OS and CPU are not supported",(0,a.osFullName)()+" on "+s.default.arch()+" was detected.","PhotoStructure is only supported on "+e+"."]}}}))},37301(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.powershellHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(13538),a=i(98314),o=i(43334),l=i(24399),u=i(63870),c=i(18454),d=i(58443);t.powershellHealthCheck=(0,s.defer)(()=>o.isWin?c.HealthCheck.for({section:"Tools",id:"tools-powershell",pendingMsg:"Checking PowerShell…",evalMode:"local",ttlMs:r.minuteMs,links:[{text:"How to fix PowerShell issues",url:"https://photostructure.com/fix-pwsh/"}],later:async()=>{try{const e=await(0,n.thenOrTimeoutError)((0,l.checkPowerShell_)(),(0,u.commandTimeoutMs)());return{level:"ok",msg:["PowerShell is OK",(0,d.toolDetailsToMsg)(e)],meta:{version:e}}}catch(e){return{level:"warn",msg:"PowerShell isn't working correctly: "+(0,a.errorToS)(e)}}}}):void 0)},28690(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.progressWatchdogHealthCheck=void 0;const r=i(42659),s=i(45599),n=i(26037),a=i(23560),o=i(18454);function l(e){return(0,r.fmtElapsedMs)(e,{suffix:""})}t.progressWatchdogHealthCheck=(0,s.defer)(()=>{if((0,a.isSyncService)())return o.HealthCheck.for({section:"System",id:"progress-watchdog",pendingMsg:"Verifying recent progress...",evalMode:"local",ttlMs:30*r.secondMs,later:async()=>{const e=n.ProgressWatchdog.instance,t=e.lastPing,i=null==t?void 0:Date.now()-t.ts;if(!e.isInWorkingMode)return{level:"ok",msg:null!=t&&null!=i?["Sync idle",`Last activity ${l(i)} ago`]:["Sync idle","No recent activity"]};if(e.isWedged()){const t=e.pendingCount;return e.triggerOnWedged(),{level:"error",msg:[null!=i?`No progress for ${l(i)}`:"No progress",`${t} task(s) pending`]}}return{level:"ok",msg:null!=i?["Sync active",`Last activity ${l(i)} ago`]:["Sync active",`Operations: ${e.activeOperations.join(", ")}`]}}})})},27100(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderEnvSetting=function(e){return h(e.key,e.isSensitive()?d:e.envValue)},t.renderEnvKeyValue=h,t.renderTomlFileValue=f,t.validateSettingsToml=async function(e,t){try{if(null==e)return{level:"disabled",msg:"No "+t+" settings file is set."};if(await e.notExists())return{level:"disabled",msg:(0,o.capitalize)(t)+" settings file "+(0,s.code)(e)+" does not exist."};const i=await(0,c.importFileSettings_)(e);return(0,r.isNotEmpty)(i.warnings)?{level:"warn",msg:(0,s.code)(e)+": "+i.warnings.join(", ")}:{level:"ok",msg:[(0,o.capitalize)((0,a.plur)(i.settings.length,t+" setting override")),(0,s.b)("Source:"),(0,s.code)(e),(0,s.b)("Settings:"),0===i.settings.length?"(using all defaults)":(0,s.ul)(i.settings.map(e=>f(e)))]}}catch(t){return{level:"error",msg:"Failed to parse "+e+":\n"+(0,u.errorToS)(t)}}};const r=i(40958),s=i(82950),n=i(98553),a=i(12168),o=i(81168),l=i(3790),u=i(98314),c=i(2858),d="********";function h(e,t){const i=null==t?"":t===d||(0,l.isSensitiveEnvKey)(e)?d:(0,n.stringify)(t);return(0,s.code)(e+"="+i)}function f(e){if(null!=e.fileValue){const t=e.envKeyWithValue();return(0,s.code)(e.name+" = "+(e.isSensitive()?"********":(0,n.stringify)(e.fileValue))+(null==t?"":` # (overridden by $${t}=${e.isSensitive()?d:(0,n.stringify)(e.envValue)})`))}}},90721(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ripgrepHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(84777),a=i(89966),o=i(45255),l=i(18454),u=i(58443);t.ripgrepHealthCheck=(0,s.defer)(()=>l.HealthCheck.for({section:"Tools",id:"tools-ripgrep",ordinal:3,pendingMsg:"Checking "+(0,r.code)("ripgrep")+"…",evalMode:"local",later:async()=>{try{const e=await(0,a.rgNativePath_)(),t=(await(0,n.stdout_)(e,["--version"],{timerName:"proc.ripgrep",timeoutMs:o.ShortCommandTimeoutMs})).trim(),i=t.split("\n")[0]?.replace("ripgrep ","");return{level:"ok",msg:["ripgrep is OK",(0,u.toolDetailsToMsg)({desc:"ripgrep",path:e,version:i}),(0,r.code)("ripgrep")+" provides fast log searching with context for the Logs page."]}}catch{return{level:"warn",msg:["ripgrep ("+(0,r.code)("rg")+") is not found",(0,r.code)("rg")+" enables fast log and sync report searching on admin pages. It should be bundled with PhotoStructure. Please report this issue.","Log queries will fall back to a slower built-in search."]}}}}))},65756(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqliteHealthCheck=void 0;const r=i(45599),s=i(27180),n=i(98314),a=i(18454),o=i(58443);t.sqliteHealthCheck=(0,r.defer)(()=>a.HealthCheck.for({section:"Tools",id:"tools-sqlite-version",ordinal:0,pendingMsg:"Checking SQLite…",evalMode:"local",links:[{text:"Read about PhotoStructure SQLite support",url:"https://forum.photostructure.com/t/whats-ps-force-local-db-replica/837",icon:"docs"}],async later(){try{const e=await s.sqliteVersion_.refresh();return null==e?{level:"error",msg:"SQLite version could not be found"}:{level:"ok",msg:["SQLite is OK",(0,o.toolDetailsToMsg)({desc:"SQLite",path:"",version:e.libraryVersion}),(0,o.toolDetailsToMsg)({desc:"SQLite tools",path:e.sqliteNativePath,version:e.toolVersion}),"SQLite is used for your PhotoStructure library database."]}}catch(e){return{level:"error",msg:"Something's amiss with SQLite: "+(0,n.errorToS)(e)}}}}))},15024(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.securityHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(44142),o=i(97352),l=i(24526),u=i(94174),c=i(94361),d=i(77740),h=i(59958),f=i(43334),m=i(18454);t.securityHealthCheck=(0,n.defer)(()=>{const e=f.isWin?"an administrator":"root";return m.HealthCheck.for({section:"System",id:"proc-security",pendingMsg:"Checking user/group security…",evalMode:"local",later:async()=>{if("0"===process.env.PUID)return{level:"disabled",msg:`User/group security health check is disabled (${(0,s.code)("PUID=0")}).`,links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]};const t=(0,r.compact)([(0,o.mapGte0)((0,l.userid)(),e=>"Current user id: "+(0,s.b)((0,s.code)(e))),(0,o.mapGte0)((0,a.groupid)(),e=>"Current group id: "+(0,s.b)((0,s.code)(e))),"Current user name: "+(0,s.b)((0,s.code)(await(0,u.username)()??"(unknown)"))]);if(!0===await(0,u.isRootUser)()||(0,d.getDevEnvFlag)(h.DevEnvFlags.PS_FAIL_SECURITY_HEALTH_CHECK))return{level:"warn",msg:["PhotoStructure should not be run as "+e,...t],links:[{text:"Read why PhotoStructure should not be run as "+e,url:"https://photostructure.com/server/photostructure-for-docker/#why-not-run-as-root"}]};{const e=(0,c.whyUidGidMismatched)();return(0,r.isNotEmpty)(e)?{level:"warn",msg:["PhotoStructure is not running as the correct user",...e,...t],links:[{text:"Read more about PUID/PGID",url:"https://photostructure.com/go/puid"}]}:{msg:["PhotoStructure's user is OK",...t],level:"ok"}}}})})},3956(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsEnvHealthCheck=void 0;const r=i(1708),s=i(82950),n=i(22573),a=i(45599),o=i(12168),l=i(45969),u=i(28874),c=i(63225),d=i(18454),h=i(27100);t.settingsEnvHealthCheck=(0,a.defer)(()=>d.HealthCheck.for({section:"Library",id:"settings-env",pendingMsg:"Checking environment settings…",evalMode:"local",links:[{text:"Read about PhotoStructure environment settings",url:"https://photostructure.com/faq/environment-variables/",icon:"docs"}],later:async()=>{const e=[];for(const t of(0,u.allSettings)())t._envValue.refresh(),t.hasEnvValue()&&e.push((0,h.renderEnvSetting)(t));for(const t of["TZ",...(0,l.isDocker)()?["PUID","PGID"]:[]]){const i=r.env[t];(0,n.blank)(i)||e.push((0,h.renderEnvKeyValue)(t,i))}const t=[(0,o.plur)(e.length,"environment setting"),(0,s.ul)(e)],i=(0,c.verifyPsEnvSettings)();return i.length>0?{level:"warn",msg:["Some environment settings may be misconfigured:",(0,s.ul)(i.map(e=>(0,s.code)(e.envKey)+": "+e.msg)),"---",...t]}:{level:"ok",msg:t}}}))},29332(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsLibraryHealthCheck=void 0;const r=i(45599),s=i(2858),n=i(18454),a=i(27100);t.settingsLibraryHealthCheck=(0,r.defer)(()=>n.HealthCheck.for({section:"Library",id:"settings-library",pendingMsg:"Checking library settings…",evalMode:"local",links:[{text:"Read about PhotoStructure library settings",url:"https://photostructure.com/getting-started/advanced-settings/#library-settings",icon:"docs"}],later:()=>(0,a.validateSettingsToml)((0,s.librarySettingsFile)(),"library")}))},61274(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settingsSystemHealthCheck=void 0;const r=i(45599),s=i(95696),n=i(32707),a=i(18454),o=i(27100);t.settingsSystemHealthCheck=(0,r.defer)(()=>a.HealthCheck.for({section:"Library",id:"settings-system",pendingMsg:"Checking system settings…",evalMode:"local",links:[{text:"Read about PhotoStructure system settings",url:"https://photostructure.com/getting-started/advanced-settings/#system-settings",icon:"docs"}],later:()=>(0,o.validateSettingsToml)(s.PosixFile.forMaybe((0,n.systemSettingsFile)()),"system")}))},38372(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sharpHealthCheck=void 0;const r=i(9288),s=i(45599),n=i(12168),a=i(14121),o=i(98314),l=i(21473),u=i(18454),c=i(58443);t.sharpHealthCheck=(0,s.defer)(()=>u.HealthCheck.for({section:"Tools",id:"tools-sharp",ordinal:2,pendingMsg:"Checking Sharp…",evalMode:"local",later:async()=>{try{const e=await(0,a.elapsedAsync)((0,l.testSharp_)());return{level:"ok",msg:["Image processing is OK",(0,c.toolDetailsToMsg)({desc:"libvips",version:r.versions.vips}),"Image resize test took "+(0,n.fmt)(e.elapsedMs)+" ms"]}}catch(e){return{level:"error",msg:["Something's amiss with image processing",(0,o.errorToS)(e)]}}}}))},82638(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.summarizeHealthChecks=async function(e){return S({...e,healthCheckResults:await b(e)})},t.summarizeHealthChecksSync=S;const r=i(40958),s=i(42659),n=i(45599),a=i(41400),o=i(96249),l=i(50268),u=i(62220),c=i(19851),d=i(50213),h=i(23560),f=i(22911),m=i(28874),p=i(2858),g=i(21525),y=i(42495),v=(0,n.defer)(()=>(0,d.mkLogger)("health.SummarizeHealthChecks"));async function b({healthChecks:e,healthCheckResults:t,refresh:i}){const r=new Map;for(const e of t??[])r.set(e.id,e);if(null!=e)for await(const t of f.Deferred.toAsyncIterable(e.map(e=>!0===i?e.refresh():e.result())))r.set(t.id,t);return[...r.values()]}const w=(0,c.lazy)(()=>({...l.BaseHealthCheckSummary,libraryDir:(0,p.libraryHasSettings)()?m.Settings.libraryDir.valueOrDefault??null:null,from:{pid:process.pid,title:h.serviceName.prior()??process.title}}));function S(e){const t=(0,r.uniqBy)(e.healthCheckResults,e=>e.id),i=t.filter(e=>"pending"===e.level),n=i.length,a=i.map(e=>e.id),c=t.length-n,d=0===n,h=(0,r.uniq)((0,r.compactBlanks)(e.errors));if(h.length>0)return{...w(),level:l.HealthCheckLevels.error,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),state:u.RunStates.failed,msg:["Errors encountered during setup:",h.join("\n---\n")],buttons:(0,y.restartResetOrShutdownButtons)()};for(const i of g.HealthCheckLevelOrder){if(e.skipPending&&i===l.HealthCheckLevels.pending)continue;const s=t.filter(e=>e.level===i);if((0,r.isNotEmpty)(s)){const u=t.filter(e=>!s.includes(e)&&(0,l.levelIsNotOK)(e.level)),h=(0,g.summaryForLevel)(i);return v().tap({msg:"summary() found "+s.length+" "+h.level+" checks",level:g.HealthCheckLevelToLogLevel[h.level],result:{...w(),level:h.level,state:h.state,links:h.links,buttons:h.buttons,settled:d,pendingIds:a,pendingCount:n,settledCount:c,linkIds:s.map(e=>e.id),ts:Date.now(),msg:(0,r.uniq)([...h.msg,...h.level===l.HealthCheckLevels.pending?[]:(0,o.flatten)([...s,...u].map(e=>e.msg[0]))])},meta:{checks:s.map(e=>e.id),args:e}})}}return v().tap({msg:"summary(): all are passing",result:{...w(),level:l.HealthCheckLevels.ok,state:u.RunStates.ready,settled:d,pendingIds:a,pendingCount:n,settledCount:c,ts:Date.now(),msg:["All critical health checks pass","Last updated: "+(0,s.fmtDateShort)(Date.now())]}})}(0,a.later)(()=>{m.Settings.libraryDir.watchLater(()=>w.unset())})},49913(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemLoadHealthCheck=void 0,t.systemLoadTest=h;const r=i(82950),s=i(42659),n=i(45599),a=i(31586),o=i(12168),l=i(23135),u=i(30933),c=i(14854),d=i(18454);function h(){if(l.ProcessesSettings.singleThreaded.valueOrDefault)return{level:"ok",msg:["CPU utilization is not monitored",(0,r.code)(l.ProcessesSettings.singleThreaded.key)+" is enabled — sync runs serially in a single process"]};if(0===l.ProcessesSettings.cpuBusyPercent.valueOrDefault)return{level:"ok",msg:["CPU utilization is not monitored",(0,r.code)(l.ProcessesSettings.cpuBusyPercent.key)+" is set to 0 (no throttling)"]};const e=c.CpuUsage.instance().busyPct(),t=(0,c.isTooBusy)(),i=t?"stop-sync":"ok",s=(0,o.plur)((0,u.cpuCount)(),"CPU")+" detected";return{level:i,msg:["CPU utilization is "+((0,a.fmtPct)(e)??"(loading…)"),s,t?"PhotoStructure sync is paused until CPU utilization drops below":"PhotoStructure sync will pause while CPU utilization exceeds",(0,r.code)(l.ProcessesSettings.cpuBusyPercent.key)+": "+(0,a.fmtPct)(l.ProcessesSettings.cpuBusyPercent.valueOrDefault)]}}t.systemLoadHealthCheck=(0,n.defer)(()=>d.HealthCheck.for({section:"System",id:"system-load",pendingMsg:"Checking system load…",evalMode:"local",ttlMs:s.minuteMs,later:async()=>{const e=h();return(0,t.systemLoadHealthCheck)().setTTL(("stop-sync"===e.level?6:60)*s.secondMs),e}}))},60487(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemTempHealthCheck=void 0;const r=i(76790),s=i(82950),n=i(42659),a=i(45599),o=i(68708),l=i(5494),u=i(82647),c=i(43334),d=i(28874),h=i(77503),f=i(18454);function m(e){return(0,s.b)(Math.round(e)+"°C")+" ("+Math.round((0,h.celsiusToFahrenheit)(e))+"°F)"}function p(e){return 0===e.length?"":["| Temperature | Sensor |","|---|---|",...e.map(([e,t])=>`| ${m(t)} | ${e} |`)].join("\n")}function g(e){const t=[`${e.n} sensors`,`mean ${m(e.avg)}`,`max ${m(e.max)}`];return e.n>2&&null!=e.p84&&t.push(`p84 ${m(e.p84)}`),t.join(", ")}t.systemTempHealthCheck=(0,a.defer)(()=>{const e=f.HealthCheck.for({section:"System",id:"system-temp",evalMode:"deferrable",pendingMsg:"Checking system temps…",ttlMs:n.minuteMs,links:[{text:"How to set up temperature monitoring",url:"https://photostructure.com/server/temperature-monitoring/",icon:"docs"}],later:async()=>{if(!await(0,l.sensorsAvailable)()&&!(0,l.hwmonAvailable)()&&!(0,l.thermalZoneAvailable)())return{level:"disabled",msg:c.isLinux?["Install lm-sensors or ensure /sys/class/hwmon is accessible to monitor system temperatures"]:["System temperature monitoring is not available on this platform"]};const t=d.Settings.maxTempCelsius.valueOrDefault,i=["PhotoStructure sync will pause while system temperatures exceed "+(0,s.b)((0,s.code)(d.Settings.maxTempCelsius.key))];if(t<=0)return{level:"disabled",msg:["Temperature monitoring is disabled","Set maxTempCelsius to > 0 to enable",...i]};const a=[[(0,s.b)((0,s.code)(d.Settings.maxTempCelsius.key)),t]],h=await(0,l.sensorTemps_)();if(null==h||(0,o.isEmptyObj)(h))return{level:"disabled",msg:["Failed to read system temperatures"]};const f=(0,r.sortBy)((0,o.entries)(h),([e,t])=>-t),m=f.filter(([e,i])=>i>=t),y=new u.Average;if(y.pushAll((0,o.values)(h)),0===m.length){e.setTTL(15*n.minuteMs);const t=f.slice(0,5),r=f.length-t.length;return{level:"ok",msg:["System temperatures are OK",g(y),p([...t,...a]),...r>0?[`(${r} cooler sensor${1!==r?"s":""} not shown)`]:[],...i]}}return e.setTTL(30*n.secondMs),{level:"stop-sync",msg:["System temperatures are high",g(y),p([...m,...a]),...i]}}})})},12865(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemdHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(45969),a=i(43334),o=i(39951),l=i(18454);t.systemdHealthCheck=(0,s.defer)(()=>!a.isLinux||(0,n.isDocker)()?void 0:l.HealthCheck.for({section:"System",id:"systemd",pendingMsg:"Checking systemd…",evalMode:"local",links:[{text:"systemd setup guide",icon:"docs",url:"https://photostructure.com/server/systemd/"}],later:async()=>{if(!(0,o.sdNotifyAvailable)())return{level:"disabled",msg:"Not running under systemd"};const e=(0,o.sdNotifyVersion)(),t=(0,o.sdNotifyMajorVersion)();return null==e?{level:"warn",msg:["Running under systemd but "+(0,r.code)("systemd-notify")+" binary not found","Watchdog and readiness notifications will not work"]}:null!=t&&t<243?{level:"warn",msg:[e,"systemd 243+ is required for "+(0,r.code)("NotifyAccess=exec"),"Readiness and watchdog notifications may not work"]}:{level:"ok",msg:[e,"sd_notify readiness and watchdog are active"]}}}))},17714(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testHealthCheck=void 0;const r=i(82950),s=i(45599),n=i(50268),a=i(7282),o=i(18454);t.testHealthCheck=(0,s.defer)(()=>(0,a.isTest)()?o.HealthCheck.for({section:"System",id:"test-health-check",ordinal:0,pendingMsg:"Test check…",evalMode:"local",later:async()=>{const e=n.HealthCheckLevels.toValid(process.env.PS_TEST_HEALTH_CHECK_LEVEL)??n.HealthCheckLevels.ok;return{level:e,msg:[`Test health check: ${e.toUpperCase()}`,`These are ${(0,r.b)("details")}:`,(0,r.ul)("alpha",(0,r.code)("bravo"),"charlie")]}}}):void 0)},84728(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionHealthCheck=void 0;const r=i(45599),s=i(56507),n=i(40044),a=i(18454);t.versionHealthCheck=(0,r.defer)(()=>a.HealthCheck.for({section:"System",id:"ps-version",pendingMsg:"Checking PhotoStructure version…",evalMode:"local",ttlMs:s.UpdateSettings.updateCheckTtlMs.valueOrDefault,links:[{text:"Change auto-update setting",icon:"settings",url:"/settings#update-check-section"},{text:"What's new?",icon:"docs",url:"https://photostructure.com/whats-new/"},{text:"Update checking & privacy",icon:"docs",url:"https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956"}],later:()=>(0,n.versionCheck_)()}))},7245(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.videoHealthCheck=void 0;const r=i(45599),s=i(41400),n=i(34102),a=i(66106),o=i(6327),l=i(38337),u=i(45969),c=i(18454),d=i(58443);t.videoHealthCheck=(0,r.defer)(()=>c.HealthCheck.for({section:"Tools",id:"tools-video",evalMode:"local",pendingMsg:"Checking video tooling…",links:[{text:"Manage photo and video tools",url:"/welcome/tools",icon:"build"},{text:"Video support",url:(0,d.mediaCodecDocsUrl)(),icon:"docs"}],warnLinks:[{text:"View install log",url:"/logs?filter=install",icon:"article"},...(0,u.isDocker)()?[]:[{text:"Re-check for video tooling",icon:"refresh",method:"POST",type:"button",url:"/admin/recheck-tools"}]],later:async()=>{const[e,t]=await Promise.all([(0,a.getFfmpegToolDetails_)(),(0,o.getFFprobeToolDetails_)()]);return null!=e&&!1!==e.isSupportedVersion?null!=t&&!1!==t.isSupportedVersion?{level:"ok",msg:["Video processing is OK",(0,d.toolDetailsToMsg)({...e,desc:"ffmpeg"}),(0,d.toolDetailsToMsg)({...t,desc:"ffprobe"}),"FFmpeg is used to transcode videos to be compatible with browsers.","FFprobe is used to extract metadata from videos."]}:{level:"warn",msg:["Some videos formats will be imported. Install ```ffprobe``` for full video support.",(0,d.toolDetailsToMsg)({...e,desc:"FFmpeg"})]}:"running"===l.InstallState.instance().phase?{level:"installing",msg:["Installing video tooling…"]}:{level:"warn",msg:["Videos will not be imported","Please install ```ffmpeg``` and ```ffprobe```."]}}})),(0,s.later)(()=>{(0,n.ee)().on("clearToolCache",()=>t.videoHealthCheck.prior()?.reset())})},16264(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeHealthCheck=void 0;const r=i(40958),s=i(82950),n=i(45599),a=i(68708),o=i(34075),l=i(43334),u=i(28874),c=i(18454);t.volumeHealthCheck=(0,n.defer)(()=>c.HealthCheck.for({section:"System",id:"system-volumes",ordinal:0,evalMode:"deferrable",pendingMsg:"Checking volumes…",timeoutMs:()=>u.Settings.statTimeoutMs.valueOrDefault,links:[{text:"What's a “volume”?",url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],warnLinks:l.isWin?[{text:"Check this page for troubleshooting tips",url:"https://photostructure.com/faq/windows-troubleshooting/#unhealthy-network-shares"}]:void 0,later:async()=>{const e=await(0,o.getMountPoints)(),t=e.filter(e=>null!=e.error||"healthy"!==e.status);return(0,r.isNotEmpty)(t)?{level:"warn",msg:["One or more volumes are not healthy","Check the following:",(0,s.ul)(...t.map(e=>(0,a.pickCompact)(e,"mountPoint","status","error")))]}:{level:"ok",msg:["All relevant mountpoints are OK",(0,s.ul)(e.map(e=>(0,s.code)(e.mountPoint)))]}}}))},14156(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.workerHealthCheck=void 0;const s=r(i(1708)),n=i(42659),a=i(45599),o=i(26905),l=i(15674),u=i(83966),c=i(18454);t.workerHealthCheck=(0,a.defer)(()=>c.HealthCheck.for({section:"System",id:"system-workers",pendingMsg:"Checking background workers…",evalMode:"local",ttlMs:30*n.secondMs,later:async()=>{const e=(0,l.maxCpus)();try{const t=await(0,u.ping)({input:"healthcheck"});return(0,l.singleThreadedMode)()?{level:"disabled",msg:["Task processing is in-process (no worker delegation)","Single-threaded mode is enabled"]}:t.pid===s.default.pid?{level:"ok",msg:["Task processing is in-process (no worker delegation)",`${e} worker(s) configured`]}:{level:"ok",msg:["Background workers are OK",`Worker PID ${t.pid} responded normally`,`${e} worker(s) configured`]}}catch(t){return{level:"error",msg:["Background workers are not responding",`${e} worker(s) configured`,"Image processing and other tasks may not work correctly",(0,o.errorToS)(t)]}}}}))},5494(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thermalZoneAvailable=t.hwmonAvailable=void 0,t.sensorsAvailable=v,t.isReasonableHardwareTemperature=b,t.lmSensorsChipNames=w,t.sensorTemps_=async function(){const e=new g.SimpleGlobs(p.Settings.excludedSensorNames.valueOrDefault,"i"),t={};if(await v())try{const i=await y();if(!(0,n.blank)(i)){const r=await(0,d.stdout_)(i,["-j"],{timeoutMs:p.Settings.statTimeoutMs.valueOrDefault});Object.assign(t,P({data:(0,o.parseJSON_)(r),excludeGlobs:e}))}}catch{}const i=w(Object.keys(t));Object.assign(t,D({excludeGlobs:e,skipChipNames:i}));const r=function(e){const t=new Set;for(const i of e){const e=i.split("/")[0],r=e.indexOf("-");t.add(r>0?e.slice(0,r):e)}return t}(Object.keys(t));return Object.assign(t,k({excludeGlobs:e,skipChipNames:r})),(0,c.isEmptyObj)(t)?void 0:t},t.extractTemperatures=P,t.thermalZoneTemps=k,t.hwmonTemps=D;const r=i(73024),s=i(76760),n=i(22573),a=i(45599),o=i(98553),l=i(30301),u=i(31586),c=i(68708),d=i(84777),h=i(8103),f=i(69428),m=i(43334),p=i(28874),g=i(64712),y=(0,a.defer)(()=>(0,h.pathTo)({tool:"sensors"}));async function v(){return m.isLinux&&!(0,n.blank)(await y())}function b(e){return e>5&&e<110}function w(e){const t=new Set;for(const i of e){const e=i.split("/")[0],r=e.indexOf("-");t.add(r>0?e.slice(0,r):e)}return t}const S=/temp.*?_input/i;function P({data:e,prefix:t,excludeGlobs:i}){const r={};for(const[s,n]of Object.entries(e)){const e=s.trim().replace(/\s/g,"_"),a=null==t?e:`${t}/${e}`;!0!==i?.test(a)&&("number"==typeof n&&S.test(s)?b(n)&&(r[a]=n):(0,c.isObject)(n)&&Object.assign(r,P({data:n,prefix:a,excludeGlobs:i})))}return r}const M="/sys/class/hwmon",T=/^temp\d+_input$/;t.hwmonAvailable=(0,l.lazy)(()=>{if(!m.isLinux)return!1;try{return(0,r.readdirSync)(M).some(e=>e.startsWith("hwmon"))}catch{return!1}});const _="/sys/class/thermal",E=/^thermal_zone\d+$/;function k(e){const t=e?.basePath??_;if(null==e?.basePath&&!m.isLinux)return;let i;try{i=(0,r.readdirSync)(t)}catch{return}const n=i.filter(e=>E.test(e));if(0===n.length)return;const a=new Map,o=new Map;for(const e of n){const i=(0,f.readFileSync)((0,s.join)(t,e,"type"))?.toString().trim()??e;o.set(e,i),a.set(i,(a.get(i)??0)+1)}const l={};for(const i of n){const r=o.get(i);if(e?.skipChipNames?.has(r))continue;const n=(a.get(r)??0)>1?`${r}-${i}`:r,c=(0,f.readFileSync)((0,s.join)(t,i,"temp")),d=(0,u.toInt)(c?.toString());if(null==d)continue;const h=d/1e3;if(!b(h))continue;const m=`${n}/temp`;!0!==e?.excludeGlobs?.test(m)&&(l[m]=h)}return(0,c.isEmptyObj)(l)?void 0:l}function D(e){const t=e?.basePath??M;if(null==e?.basePath&&!m.isLinux)return;let i;try{i=(0,r.readdirSync)(t)}catch{return}const a=i.filter(e=>e.startsWith("hwmon"));if(0===a.length)return;const o=new Map,l=new Map;for(const e of a){const i=(0,f.readFileSync)((0,s.join)(t,e,"name"))?.toString().trim();(0,n.blank)(i)||(l.set(e,i),o.set(i,(o.get(i)??0)+1))}const d={};for(const i of a){const n=l.get(i);if(null==n)continue;if(e?.skipChipNames?.has(n))continue;const a=(o.get(n)??0)>1?`${n}-${i}`:n,c=(0,s.join)(t,i);let h;try{h=(0,r.readdirSync)(c)}catch{continue}for(const t of h){if(!T.test(t))continue;const i=(0,f.readFileSync)((0,s.join)(c,t)),r=(0,u.toInt)(i?.toString());if(null==r)continue;const n=r/1e3;if(!b(n))continue;const o=`${a}/${t}`;!0!==e?.excludeGlobs?.test(o)&&(d[o]=n)}}return(0,c.isEmptyObj)(d)?void 0:d}t.thermalZoneAvailable=(0,l.lazy)(()=>{if(!m.isLinux)return!1;try{return(0,r.readdirSync)(_).some(e=>E.test(e))}catch{return!1}})},15207(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregationModes=void 0;const r=i(50989);t.AggregationModes=(0,r.strEnum)("default","strict","lenient","manual")},95242(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviewBuilder=void 0,t.canIncludeInputDim=x;const r=i(57975),s=i(40958),n=i(22573),a=i(33374),o=i(98553),l=i(55835),u=i(76790),c=i(68708),d=i(50213),h=i(3685),f=i(84196),m=i(92434),p=i(87290),g=i(51837),y=i(57159),v=i(95696),b=i(62105),w=i(84258),S=i(38156),P=i(69589),M=i(28874),T=i(16170),_=i(54979),E=i(29990),k=i(42725),D=i(4192),I=i(32876),C=i(50961),A=i(181);async function x(e){const t=await(0,_.readMimeType)(e);return!(null==t||!(0,T.isMimeTypeSupportedByBrowser)(t))&&(M.Settings.previewOriginalDirectly.valueOrDefault??(e.isDescendantOf((0,p.libraryOriginalsDirPosixFile)())||e.isDescendantOf((0,p.libraryDirPosixFile)())))}class F{ap;assetFiles;logger;ctx;constructor(e,t,i){this.ap=e,this.assetFiles=t,this.logger=(0,d.mkLogger)("AssetPreviewBuilder("+e.assetId+")"),this.ctx=(0,P.forceContextOrSetting)(i),this.assetFiles=(0,m.sortAssetFilesInPlace)(this.assetFiles)}[r.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}async build_(){this.logger.info("build_(): asset file candidates:",this.assetFiles.map(e=>(0,c.pick)(e,"id","uri")));const e=[];for(const t of this.assetFiles){const i=v.PosixFile.forMaybe(await(0,f.getNativePathFromUriDetails)(t));if(null!=i){{const e=await(0,b.whyRejectFile)(i);(0,n.blank)(e)||this.logger.info("skipping: rejected",{pf:i,whyRejected:e})}try{return await this.#At(i,t)}catch(r){e.push(r),this.logger.warn("Failed to set shown file to ",{nativePath:i.nativePath,best:t,error:r})}finally{this.ap.parent.clear()}}else this.logger.info("skipping: failed to get PosixFile",{af:t}),e.push(new Error("Cannot get path from URI "+(0,o.stringify)((0,c.pick)(t,"uri","nativePath"))))}return this.logger.throw("Cannot build previews: none of the files are valid",{logLevel:"warn",doNotSend:!0,retriable:!1,files:this.assetFiles.map(e=>e.nativePath??e.uri),causes:e})}async#xt(e,t){await(0,A.throwIfInvalidFile_)(e);const i=await e.size(),r=await e.thisOrSidecarMaxMtimeMs();if(this.logger.debug("_build",{filesize:i,mtime:r,best:t.uri}),null==i||null==r)return this.logger.throw("build(): missing stat info for best file",{ignorable:!0,best:t});const{uri:n,width:a,height:o,mimetype:l}=t;if(null==n||null==a||null==o||null==l)return this.logger.throw("build(): internal error: missing fields for best file "+e,{ignorable:!0,best:t});const u=(0,E.fitSizes)(t,await x(e));return{assetId:t.assetId,assetFileId:t.id,uri:n,uris:this.assetFiles.map(e=>e.uri),path:e.nativePath,mtime:r,filesize:i,width:a,height:o,mimetype:l,fitSizes:u.map(([,e])=>e.name).join(","),sqWidths:(0,s.compact)(k.ImageSize.sq().map(e=>e.outputSize(t)?.width)),fitWidths:u.map(([e])=>e.width)}}async#Ft(e,t){if(this.ctx.forceSync||this.ctx.forceRebuildPreviews)return;const i=await this.ap.readInfo.refresh();if(null!=i){if(i.assetId!==t.assetId)throw new g.InternalError("priorIfValid_(): mismatched asset IDs for "+e+": "+(0,o.stringify)({priorInfo:i,info:t}));const r=i.fitSizes.split(","),n=t.fitSizes.split(",");if(i.assetFileId===t.assetFileId&&i.width===t.width&&i.height===t.height&&i.rotation===t.rotation&&(0,E.equivalentFitSizes)(r,n)){const a=(0,E.fitSizes)(e,await x(v.PosixFile.for(t.path))),o=(0,s.diff)(r,n);if((0,s.isNotEmpty)(o)){this.logger.info("priorIfValid_(): removing previews that aren't required anymore.",{leftovers:o});for(const e of o){const t=a.find(([,t])=>t.name===e);if(null==t)this.logger.warn("priorIfValid_(): Failed to clean up: missing fit size",{fitsize:t,fits:a});else{const e=this.ap.fileForWidth(t[1].reducer.name,t[0].width);this.logger.debug("priorIfValid_(): unlinking unwanted preview "+e,{fitsize:t}),await e.unlink("warn")}}}return this.logger.debug("priorIfValid_(): source file, dimensions, and rotation match. Reusing previews.",{info:t,priorInfo:i}),await this.ap.writeInfo(t),t}}}async#At(e,t){this.logger.info("_build("+e+")",{uri:t.uri});const i=await this.#xt(e,t),r=await this.#Ft(t,i);if(null!=r)return{...r,noop:!0};if(null==await(0,_.readMimeType)(e))throw new Error("Failed to read mimetype for "+e);const s=new S.PushProgressObserver({path:e.nativePath,op:"Building previews"},k.ImageSize.sq().length+k.ImageSize.fit().length);if(this.logger.debug("Rebuilding all previews from "+t.uri,{assetId:t.assetId,info:i}),null==await this.ap.parent.mkdirp())throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const n=await this.ap.existingFiles(),o=new C.SharpReadable({src:e,minDim:k.ImageSize.largestFit().max}),d=await o.sharp_(),f=await x(e),m=(0,E.fitSizes)(t,f),p=[],g=[];let v,b;const P=k.ImageSize.largestSq(),T=(0,u.leastBy)(m,([e,t])=>(0,l.map)(P.outputSize(e),()=>t.megapixels()))?.[1].name,A=(0,c.pick)(t,"width","height");{let e=d.clone(),t=A;for(const[i,r]of m){if(f&&"original"===r.name){this.logger.debug("resize("+r.name+") no-op: we'll let web directly stream the original file");continue}const n=performance.now(),o=t,l=this.ap.fileForWidth(r.reducer.name,i.width).wip();e=r.resize(i,e),t=i,r.name===T&&(b=e.clone(),v=i),(0,a.dmegapixels)(i)>=1&&r.reducer===I.Fit&&M.Settings.includePreviewTags.valueOrDefault&&g.push(l),await r.toJpeg({path:l.nativePath,sh:e,outputSize:i}),await s.onProgress(),this.logger.debug("resize("+r.name+") "+(0,a.fmtDim)(o)+" -> "+(0,a.fmtDim)(i)+" in "+(0,h.roundMs)(performance.now()-n)+" ms"),p.push(l)}}{null==b?(this.logger.debug("square resize(): resorting to ",{origDim:A,bestFitNameForSq:T}),b=d,v=A):this.logger.debug("square resize(): using to ",{sqDim:v,bestFitNameForSq:T});let e=!1;for(const t of k.ImageSize.sq()){const i=performance.now(),r=v,n=t.outputSize(v??A);if(null==n){this.logger.debug("skipping square output for "+t.max);continue}e||(n.position=M.Settings.squareThumbStrategy.valueOrDefault,e=!0),this.logger.debug("Applying ",{outputSize:n});const o=this.ap.fileForWidth(t.reducer.name,n.width).wip();t.resize(n,b),v=n,await t.toJpeg({path:o.nativePath,sh:b,outputSize:n}),await s.onProgress(),p.push(o),this.logger.debug("resize("+t.name+") "+(0,a.fmtDim)(r)+" -> "+(0,a.fmtDim)(n)+" in "+(0,h.roundMs)(performance.now()-i)+" ms")}}try{await(0,D.includePreviewTags_)(e,g).catch(t=>{this.logger.warn("Failed to restore metadata tags into previews for "+e,{error:t})});const t=new Set(n.map(e=>e.nativePath));for(const e of p){const i=await e.unwip_();t.delete(i.nativePath)}await(0,w.unlink)(t),await this.ap.writeInfo(i),this.logger.debug("Previews unwipped and info written",{info:i})}catch(t){throw await(0,w.unlink)(p),new y.WrappedError("Failed to create previews from "+e,{cause:t,path:e.nativePath,fatal:!1})}return i}}t.AssetPreviewBuilder=F},35721(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractPreviewInfo=function(e,t){const i=t.posixPathFrom(e).replace(/\//g,"").split("-"),r=(0,o.toInt)(i[0]),s=n.ReducerNames.getCI(i[1]),a=(0,c.extractInt)(i[2]);return(0,o.gt0)(r)?{file:t,assetId:r,reducer:s,width:a}:void f.warn("Failed to extract preview info",{file:t,previewsRoot:e,arr:i,assetId:r,reducer:s,width:a})},t.previewToDownloadable=async function(e,t){return(0,a.map2)(t.assetId,t.width,async(i,a)=>{const o=await(0,h.dimensions)(t.file);if(null==o)return;const u=(0,s.dimToSize)(o);return{size:u,basename:`${(0,d.stripSuffix)(e,(0,l.extname)(e))}-${u}${t.file.ext}`,title:m(t.file,u,"image",o),description:`Download ${u}`,details:`(${(0,s.fmtDim)(o)} ${t.file.ext})`,href:(0,r.assetImgLink)({assetId:i,reducer:n.ReducerNames.fit,width:a})}})},t.mkDownloadableTitle=m;const r=i(75761),s=i(33374),n=i(11371),a=i(55835),o=i(31586),l=i(29882),u=i(50213),c=i(97352),d=i(81168),h=i(89782),f=(0,u.mkLogger)("extractPreviewInfo");function m(e,t,i,r){return`Download ${t} ${e.ext} ${i}`+(null==r?"":` (${(0,s.fmtDim)(r)})`)}},16524(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetPreviews=void 0;const r=i(19851),s=i(40958),n=i(75761),a=i(11371),o=i(68708),l=i(39926),u=i(58939),c=i(76790),d=i(48884),h=i(50213),f=i(81168),m=i(56519),p=i(38835),g=i(70417),y=i(35721);t.AssetPreviews=class{previewsRoot;logger;assetId;parent;basename;constructor(e,t){this.previewsRoot=e,this.logger=(0,h.mkLogger)("AssetPreviews(assetId:"+(0,u.id2id)(t)+")"),this.assetId=(0,u.id2id)(t);const i=(0,l.leftPad)(this.assetId,8,"0"),r=(0,f.splitEvery)(i,3);this.basename=r.pop()+"-",this.parent=e.join(...r)}parentNotExists(){return this.parent.clear().notExists()}async existingFiles(){return await this.parent.clear().childFiles(e=>e.base.startsWith(this.basename))??[]}async existingJpgs(){return(await this.existingFiles()).filter(e=>".jpg"===e.ext)}async#Ot(){const e=[];for(const t of await this.existingFiles()){const i=(0,y.extractPreviewInfo)(this.previewsRoot,t);null!=i&&e.push(i)}return e}async previewInfos(){return(0,m.sortByAsync)({iter:this.#Ot(),f:e=>e?.file.size()})}async deleteAll(){const e=await this.existingFiles();if(e.length>20)throw new Error("deleteAll(): rejected: > 20 existing files?!"+p.InternalErrorFlag);for(const t of e)await t.unlink();return e}fileForSuffix(e){return this.parent.join(this.basename+e)}mp4(){return this.fileForSuffix("video.mp4")}infoJson(){return this.fileForSuffix("info.json")}readInfo=(0,r.lazy)(()=>this.infoJson().readJson("debug"));writeInfo(e){this.readInfo.unset();const t=(0,o.pick)(e,"assetId","assetFileId","uri","uris","path","mimetype","width","height","mtime","filesize","rotation","sqWidths","fitSizes","fitWidths");return this.infoJson().writeJson(t)}fileForWidth(e,t){return this.fileForSuffix(e+"-w"+t+".jpg")}async filesForReducer(e){const t=this.basename+e+"-";return this.logger.tap({msg:"filesForReducer("+e+")",result:(await this.existingFiles()).filter(e=>e.base.startsWith(t))})}async smallestFileForReducer(e){return(0,c.leastBy)(await this.filesForReducer(e),e=>(0,y.extractPreviewInfo)(this.previewsRoot,e)?.width)}async largestFileForReducer(e){return(0,d.greatestBy)(await this.filesForReducer(e),e=>(0,y.extractPreviewInfo)(this.previewsRoot,e)?.width)}async widths(e){const t=await this.readInfo(),i=e===a.ReducerNames.sq?"sqWidths":"fitWidths",r=t?.[i];if(!(0,s.isEmpty)(r))return r;const n=(0,s.compact)((await this.previewInfos()).filter(t=>t.reducer===e).map(e=>e.width));return null!=t&&(t[i]=n,await this.writeInfo(t)),n}async posterLink(){const e=await this.widths(a.ReducerNames.fit);return(0,n.assetImgLink)({assetId:this.assetId,reducer:a.ReducerNames.fit,width:(0,g.max)(e)})}async imgAttrs(e,t=!1,i=!1){if(t||e!==a.ReducerNames.sq){const t=e===a.ReducerNames.fit?await this.readInfo():void 0;return(0,n.assetImgAttrs)({assetId:this.assetId,reducer:e,widths:await this.widths(e),lazyLoad:i,af:t})}return(0,n.assetSqImgAttrs)({assetId:this.assetId,lazyLoad:i})}}},19918(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isBinaryField=function(e){return e instanceof r.BinaryField||null!=e&&(0,n.isObject)(e)&&(0,s.gt0)(e.bytes)&&"rawValue"in e};const r=i(77988),s=i(31586),n=i(68708)},52086(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CropStrategies=void 0;const r=i(50989);t.CropStrategies=(0,r.strEnum)("center","entropy","attention")},86580(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tmegapixels=function(e){return null!=e.dimensions?(0,s.dmegapixels)(e.dimensions):(0,n.gt0)(e.Megapixels)?e.Megapixels:void 0},t.ltBoth=function(e,t){return(0,n.lt)(e.width,t.width)&&(0,n.lt)(e.height,t.height)},t.lteBoth=function(e,t){return(0,n.lte)(e?.width,t?.width)&&(0,n.lte)(e?.height,t?.height)},t.ltEither=function(e,t){return(0,n.lt)(e.width,t.width)||(0,n.lt)(e.height,t.height)},t.parseDimensions=function(e){const t=(0,r.compact)((0,o.toS)(e).split(/[x×]/).map(e=>(0,n.toInt)(e)));return 2===t.length?{width:t[0],height:t[1]}:void 0},t.fitToResolution=function(e,t){if(e.width*e.height<=t)return e;const i=e.width/e.height,r=Math.round(Math.sqrt(t*i));return{width:r,height:Math.round(r/i)}},t.aspectRatio=u,t.rotateDimensions=c,t.validRotations=function(e,t,i=.2){const r=u(e,i);return null==r?[]:a.Rotations.filter(e=>u(c(t,e),i)===r)};const r=i(40958),s=i(33374),n=i(31586),a=i(21605),o=i(54993),l=i(2090);function u(e,t){if(null!=e&&(0,n.gt0)(e.width)&&(0,n.gt0)(e.height))return(0,n.sigFigs)((0,l.roundAspectRatio)(e.width/e.height,t),3)}function c(e,t){return 0===t||180===t?e:{width:e.height,height:e.width}}},533(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.imgFromExif_=k,t.extractImageForThumbs_=D,t.analyzeEmbeddedImages=async function(e){try{const t=await(0,v.readRawTags)(e),i=await(0,b.extractSizeInfoFromFile)(e),r=await(0,y.readMimeType)(e);if(null==t)return{file:e.nativePath,error:"Failed to read EXIF tags"};const s=[...m.Settings.embeddedPreviews.values,...m.Settings.embeddedThumbnails.values],n=[];for(const i of s){const r=t[i];if((0,w.isBinaryField)(r))try{const t=await D(e,i);n.push({tagName:i,bytes:r.bytes,sizeInfo:await(0,b.extractSizeInfoFromFile)(t),extractedFile:t.nativePath})}catch(e){n.push({tagName:i,bytes:r.bytes,error:`Failed to extract: ${e.message}`})}}return{file:e.nativePath,mimetype:r??void 0,sizeInfo:i,embeddedImages:n.sort((e,t)=>(t.bytes||0)-(e.bytes||0))}}catch(t){return{file:e.nativePath,error:`Failed to process: ${t.message}`}}},t.extractThumbnailWithTrimming=async function(e,t,i,r,s,n){const a=_().child(`.extractThumbnailWithTrimming(${String(i)})`),o=[];try{a.debug("Extracting embedded thumbnail for potential trimming",{tag:i,targetDim:s,fileAspectRatio:n});const l=await k(e,t,i,n,s);if(null==l)return o.push(`FAILED: ${i} could not be extracted`),void a.debug("imgFromExif_ returned null for thumbnail tag",{tag:i});l.diagnostics&&o.push(...l.diagnostics);const u=(0,S.aspectRatio)(l.dimensions),c=null!=n&&null!=u&&Math.abs(u-n)/n<.02;if(null==n||null==u||c||!(Math.abs(u-1)<Math.abs(n-1))){const e=c?"aspect ratios already match closely":"thumbnail is not more square than original";return a.info(`Skipping trim: ${e}`,{tag:i,thumbnailAspectRatio:u,fileAspectRatio:n,aspectRatioDiff:null!=n&&null!=u?Math.abs(u-n)/n:null,thumbnailSquareness:null!=u?Math.abs(u-1):null,fileSquareness:null!=n?Math.abs(n-1):null,aspectRatiosMatch:c}),o.push(`SUCCESS: ${i} used without trimming (${l.dimensions.width}×${l.dimensions.height})`),{sharp:l.sharp,rotation:l.rotation,dimensions:l.dimensions,file:l.file,desc:`embedded:${i}`,sizeInfo:r,mimetype:"image/jpeg",diagnostics:o}}a.debug("Thumbnail appears letterboxed, attempting trim",{tag:i,thumbnailAspectRatio:u,fileAspectRatio:n,aspectRatioDiff:Math.abs(u-n)/n,thumbnailSquareness:Math.abs(u-1),fileSquareness:Math.abs(n-1),originalDimensions:l.dimensions});const d=await(0,T.removeLetterbox)(l.sharp);if(!d.trimApplied)return void a.info("Vetoing thumbnail: trim could not be safely applied",{tag:i,skipReason:d.skipReason,maxReductionRatio:d.maxReductionRatio,originalDimensions:d.originalDimensions,thumbnailAspectRatio:u,fileAspectRatio:n});a.debug("Successfully trimmed letterboxing from thumbnail",{tag:i,originalDimensions:d.originalDimensions,trimmedDimensions:d.trimmedDimensions,maxReductionRatio:d.maxReductionRatio});const h=await(0,P.tmpImageFile_)({src:e,tag:`${i}-trimmed`,ext:".jpg"});return await d.sharp.toFile(h.nativePath),a.debug("Saved trimmed thumbnail to new file",{originalFile:l.file.nativePath,trimmedFile:h.nativePath,dimensions:d.trimmedDimensions}),o.push(`SUCCESS: ${i} trimmed (${d.trimmedDimensions?.width}×${d.trimmedDimensions?.height})`),{sharp:d.sharp,rotation:l.rotation,dimensions:d.trimmedDimensions||l.dimensions,file:h,desc:`embedded:trimmed:${i}`,sizeInfo:r,mimetype:"image/jpeg",diagnostics:o}}catch(e){return o.push(`ERROR: ${i} trimming failed (${e.message})`),void a.debug("Failed to extract and trim embedded thumbnail",{tag:i,error:e.message})}};const s=r(i(9288)),n=i(45599),a=i(33374),o=i(31586),l=i(55139),u=i(34102),c=i(95696),d=i(50213),h=i(7282),f=i(97352),m=i(28874),p=i(47783),g=i(95141),y=i(54979),v=i(38148),b=i(1078),w=i(19918),S=i(86580),P=i(13940),M=i(5733),T=i(32721),_=(0,n.defer)(()=>(0,d.mkLogger)("img.EmbeddedImages")),E=new l.Cache({name:"EmbeddedImages",maxSize:512,ttlMs:m.Settings.metadataCacheMs.valueOrDefault,timeoutMs:m.Settings.taskTimeoutMs.valueOrDefault});async function k(e,t,i,r,n){const l=t?.[i];if(!(0,w.isBinaryField)(l))return;const u=(0,g.extractRotation)(t)??0,d=[];try{const t=await D(e,i),l=(0,s.default)(t.nativePath,{failOn:m.Settings.imageFailOn.valueOrDefault}).removeAlpha().rotate(u),h=await(0,M.sharpClone)(l),p=await h.metadata(),g=(0,f.map2Gt0)(p.width,p.height,(e,t)=>({width:e,height:t}));if(!(0,a.isDimensions)(g))return d.push(`REJECTED: ${i} has invalid dimensions`),void _().debug("imgFromExif("+e+", "+i+"): rejecting, invalid dimensions",{metadata:p,width:p.width,height:p.height});const y=.1,v=(0,S.aspectRatio)(p),b=null!=r&&null!=v&&!(0,o.closeTo)(r,v,y);if(b){const s=m.Settings.maxThumbTrimPct.valueOrDefault/100,a=v/(1-s),h=v<r&&a>=r*(1-y);if(h){_().debug("imgFromExif("+e+", "+i+"): aspect ratio mismatch, attempting trim",{fileAspectRatio:r,renderedAspectRatio:v,tolerance:y,maxTrimRatio:s,maxPossibleAspectRatio:a,couldTrimFixAspectRatio:h});try{const e=await(0,T.removeLetterbox)(l);if(e.trimApplied&&e.trimmedDimensions){const s=(0,S.aspectRatio)(e.trimmedDimensions);if(null!=s&&(0,o.closeTo)(r,s,y))return null==n||(0,S.lteBoth)(n,e.trimmedDimensions)?(d.push(`SUCCESS: ${i} fixed by trimming (${e.trimmedDimensions.width}×${e.trimmedDimensions.height})`),{sharp:e.sharp,rotation:u,file:c.PosixFile.for(t),dimensions:e.trimmedDimensions,diagnostics:d}):void d.push(`REJECTED: ${i} trimmed dimensions too small for minDim`);d.push(`REJECTED: ${i} trimming didn't fix aspect ratio (${s?.toFixed(2)} vs ${r?.toFixed(2)})`)}else d.push(`REJECTED: ${i} trimming not applied (${e.skipReason})`)}catch(e){d.push(`REJECTED: ${i} trimming failed (${e.message})`)}}else _().debug("imgFromExif("+e+", "+i+"): NOT attempting trim",{fileAspectRatio:r,renderedAspectRatio:v,maxTrimRatio:s,maxPossibleAspectRatio:a,couldTrimFixAspectRatio:h,check1:v<r,check2:a>=r*(1-y)});return void d.push(`REJECTED: ${i} aspect ratio mismatch (${v?.toFixed(2)} vs ${r?.toFixed(2)})`)}const w=null==n||(0,S.lteBoth)(n,g),P=null==r||null==v||(0,o.closeTo)(r,v,y);return _().debug("imgFromExif("+e+", "+i+")",{valid:w,minDim:n,fileAspectRatio:r,renderedAspectRatio:v,dim:g,metadata:{width:p.width,height:p.height},rotation:u,tolerance:y,aspectRatioMatch:P,hasAspectRatioMismatch:b}),w?(d.push(`SUCCESS: ${i} extracted (${g.width}×${g.height})`),{sharp:l,rotation:u,file:c.PosixFile.for(t),dimensions:g,diagnostics:d}):void d.push(`REJECTED: ${i} dimensions too small for minDim`)}catch(t){return d.push(`ERROR: ${i} extraction failed (${t.message})`),void _().info("imgFromExif(): failed to read image from EXIF tag "+i,{nativePath:e.nativePath,error:t})}}async function D(e,t){const i=t.toLowerCase().endsWith("tiff")?".tiff":".jpg",r=`${e.nativePath}:${t}`,s=await E.getOrSet(r,async()=>{try{const r=await(0,P.tmpImageFile_)({src:e,tag:t,ext:i});return await(0,p.extractBinaryTag)(t,e.nativePath,r.nativePath),r}catch(i){return _().throw("Failed to extract embedded "+t+" from "+e.nativePath,{error:i})}});return await s.exists()?s:(_().debug("Cached embedded image file no longer exists, removing from cache and re-extracting",{file:s.nativePath,tag:t}),E.delete(r),D(e,t))}(0,h.isTest)()&&(0,u.ee)().on("clearCache",()=>{_().debug("Clearing embeddedImageCache on clearCache event"),E.clear()})},52306(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FFmpegPresets=void 0;const r=i(50989);t.FFmpegPresets=(0,r.strEnum)("ultrafast","superfast","veryfast","faster","fast","medium","slow","slower","veryslow")},26978(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FFmpegVideoCodecs=void 0;const r=i(50989);t.FFmpegVideoCodecs=(0,r.strEnum)("libx264","libx265")},50827(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FfmpegStallWatcher=t.FfmpegLiveSpeedThreshold=void 0,t.newFfmpegProgressState=function(){return{carry:"",pending:{}}},t.feedFfmpegProgress=function(e,t){const i=[],r=(e.carry+t).split("\n");e.carry=r.pop()??"";for(const t of r){const r=t.trim();if(0===r.length)continue;const n=r.indexOf("=");if(n<=0)continue;const a=r.slice(0,n).trim(),o=r.slice(n+1).trim();s(e.pending,a,o),"progress"===a&&(i.push(e.pending),e.pending={})}return i},t.isLiveTick=n,t.ffmpegEtaMs=function(e,i){if(null!=i&&(0,r.gt0)(i)&&null!=e.outTimeMs&&null!=e.speed&&!(e.speed<=t.FfmpegLiveSpeedThreshold))return Math.max(0,i-e.outTimeMs)/e.speed};const r=i(31586);function s(e,t,i){switch(t){case"frame":{const t=(0,r.toInt)(i);return void(null!=t&&(e.frame=t))}case"fps":{const t=(0,r.toFloat)(i);return void(null!=t&&(0,r.gt0)(t)&&(e.fps=t))}case"out_time_us":case"out_time_ms":{const t=(0,r.toInt)(i);return void(null!=t&&(e.outTimeMs=t/1e3))}case"bitrate":{const t=/^(-?\d+(?:\.\d+)?)\s*kbits\/s$/.exec(i);if(null!=t){const i=(0,r.toFloat)(t[1]);null!=i&&(e.bitrateKbps=i)}return}case"speed":{const t=/^(\d+(?:\.\d+)?)x$/.exec(i);if(null!=t){const i=(0,r.toFloat)(t[1]);null!=i&&(e.speed=i)}return}case"progress":return void("continue"!==i&&"end"!==i||(e.progress=i))}}function n(e){return null!=e.speed&&e.speed>t.FfmpegLiveSpeedThreshold}t.FfmpegLiveSpeedThreshold=.01,t.FfmpegStallWatcher=class{opts;#G;constructor(e){this.opts=e}arm(){this.disarm();const e=this.opts.schedule??setTimeout;this.#G=e(()=>{this.#G=void 0,this.opts.onStall()},this.opts.timeoutMs),this.#G?.unref?.()}disarm(){null!=this.#G&&((this.opts.clear??clearTimeout)(this.#G),this.#G=void 0)}onTick(e){n(e)&&this.arm()}}},89782(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dimensions=async function(e){try{const t=await(0,n.extractSizeInfoFromFile)(e);return null==t?void 0:{width:t.ImageWidth,height:t.ImageHeight}}catch(e){return void a().warn("dimensions() failed",{error:e})}};const r=i(19851),s=i(50213),n=i(1078),a=(0,r.lazy)(()=>(0,s.mkLogger)("img.FileDimensions"))},29990(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fitSizes=function(e,t){const i=[];if(t){const t=c.ImageSize.originalFit(e);i.push([t.outputSize(e),t])}for(const t of u.Settings.exactFitResolutions.valueOrDefault){const r=c.ImageSize.byName(t);if(null==r){d().trace("fitSizes(): rejecting unknown exactFitResolution",{dim:e,exactFitResolution:t});continue}const s=r?.outputSize(e);null!=s?i.some(([e,t])=>t.justFits(s))?d().trace("fitSizes(): rejecting duplicate exactFit",{dim:e,size:r}):i.push([s,r]):d().trace("fitSizes(): rejecting null exact outputSize",{dim:e,size:r})}for(const t of(0,s.sortBy)(c.ImageSize.fit(),e=>e.megapixels())){const r=t.outputSize(e);if(null==r){d().trace("fitSizes(): rejecting candidate: null outputSize",{dim:e,candidate:t});continue}const s=h(r,i);null==s?i.push([r,t]):d().trace("fitSizes(): rejecting close candidate",{dim:e,found:s})}const n=(0,r.uniqBy)(i,([e,t])=>t.name),a=(0,s.sortBy)(n,([e,t])=>-t.megapixels());return d().tap({msg:"fitSizes()",result:a,meta:{dim:e}})},t.equivalentFitSizes=function(e,t){return(0,r.includesAll)((0,r.compactBlanks)(e).map(f),(0,r.compactBlanks)(t).map(f))};const r=i(40958),s=i(76790),n=i(45599),a=i(33374),o=i(31586),l=i(50213),u=i(28874),c=i(42725),d=(0,n.defer)(()=>(0,l.mkLogger)("img.FitSizes"));function h(e,t,i=u.Settings.previewScaleThreshold.valueOrDefault){const r=(0,a.dmegapixels)(e);for(const[s,n]of t){const t=(0,a.dmegapixels)(s),l=Math.max(t/r,r/t);if(l<i)return{why:"min pixel coeff: "+(0,o.sigFigs)(l,2),close:n,needleOutputSize:e,needleMP:r,hayMP:t}}}function f(e){return"qhd"===e?"wvga":"uhd"===e?"uhd4k":e}},76709(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.computeGradientCanonicalOrientation=a,t.computeGradientCanonicalOrientationFromFile=async function(e,t){const i=t?.size??64;return a((0,s.default)(e,{failOnError:!1}).rotate().resize(i,i,{fit:"fill"}))};const s=r(i(9288)),n=i(5733);async function a(e){const{data:t,info:i}=await(0,n.sharpToColorspaceBuffer)(e.clone(),"float","lab"),{width:r,height:s}=i,a=function(e,t,i){const r=t/2,s=i/2,n={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 a=0;a<i;a++)for(let i=0;i<t;i++){const o=3*(a*t+i),l=e[o],u=e[o+1],c=e[o+2],d=Math.sqrt(u*u+c*c),h=a<s?i<r?n.topLeft:n.topRight:i<r?n.bottomLeft:n.bottomRight;h.lightness+=l,h.chroma+=d,h.count++}for(let a=1;a<i-1;a++)for(let i=1;i<t-1;i++){const o=3*(a*t+(i-1)),l=3*((a-1)*t+i),u=3*((a+1)*t+i),c=e[3*(a*t+(i+1))]-e[o],d=e[u]-e[l],h=Math.sqrt(c*c+d*d);(a<s?i<r?n.topLeft:n.topRight:i<r?n.bottomLeft:n.bottomRight).complexity+=h}for(const e of Object.values(n))e.count>0&&(e.lightness/=e.count,e.chroma/=e.count,e.complexity/=e.count);const a=(n.topLeft.lightness+n.topRight.lightness)/2,o=(n.topLeft.complexity+n.topRight.complexity)/2,l=(n.topLeft.chroma+n.topRight.chroma)/2,u=(n.bottomLeft.lightness+n.bottomRight.lightness)/2,c=(n.bottomLeft.complexity+n.bottomRight.complexity)/2,d=(n.bottomLeft.chroma+n.bottomRight.chroma)/2,h=(n.topLeft.lightness+n.bottomLeft.lightness)/2,f=(n.topLeft.complexity+n.bottomLeft.complexity)/2,m=(n.topLeft.chroma+n.bottomLeft.chroma)/2,p=(n.topRight.lightness+n.bottomRight.lightness)/2,g=(n.topRight.complexity+n.bottomRight.complexity)/2,y=(n.topRight.chroma+n.bottomRight.chroma)/2;return{lightness:{up:a-u,down:u-a,left:h-p,right:p-h},complexity:{up:o-c,down:c-o,left:f-g,right:g-f},chroma:{up:l-d,down:d-l,left:m-y,right:y-m}}}(t,r,s),o=function(e){return[{rotation:0,upDir:"up"},{rotation:90,upDir:"left"},{rotation:180,upDir:"down"},{rotation:270,upDir:"right"}].map(({rotation:t,upDir:i})=>{const r=e.lightness[i],s=-e.complexity[i],n=-e.chroma[i];return{rotation:t,score:.5*r+.3*s+.2*n,lightnessScore:r,complexityScore:s,chromaScore:n}})}(a);o.sort((e,t)=>t.score-e.score);const l=o[0],u=o[1],c=l.score-u.score,d=Math.max(Math.abs(l.score),1),h=Math.min(1,Math.abs(c)/d);return{canonicalRotation:l.rotation,confidence:h,debug:{gradients:a,scores:o}}}},277(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getHeifThumbnailerDetails=t.getHeifSupportDetails=void 0,t.extractHeifConvertVersion=b,t.isHeifSupported=w,t.heif2img_=async function(e){return m.isMac?(0,y.sips2jpeg_)(e):await w()?(0,g.heif2png_)(e):void v().throw("HEIF support is missing",{src:e.nativePath})};const r=i(22573),s=i(41400),n=i(54993),a=i(19851),o=i(50213),l=i(96175),u=i(45255),c=i(84777),d=i(34102),h=i(78330),f=i(46305),m=i(43334),p=i(76280),g=i(91354),y=i(36192),v=(0,a.lazy)(()=>(0,o.mkLogger)("img.Heif"));function b(e){return(0,n.toS)(e).match(/(?:heif-convert|heif-dec|libheif)\s+version[^\d.]*(?<version>[\d.]{5,})/i)?.groups?.version}async function w(){return!0===(await(0,t.getHeifSupportDetails)())?.isSupportedVersion}function S(){t.getHeifSupportDetails.unset(),t.getHeifThumbnailerDetails.unset()}t.getHeifSupportDetails=(0,a.lazy)(async()=>{try{if(m.isMac)try{const e=await(0,y.sipsPath)();if(!(0,r.blank)(e))return{desc:"sips",path:e,version:(0,l.osNameMac)(),isSupportedVersion:!0}}catch(e){v().warn("Failed to find the sips tool (either in PATH or /usr/bin).",e)}const e=await(0,g.heifConvertPath)();if((0,r.blank)(e))return;{let t="",i=b(await(0,c.stdout_)(e,[],{timeoutMs:u.ShortCommandTimeoutMs,quiet:!0,ignoreExitCode:!0,isIgnorableError:e=>(t+=e.message,!0)})+t);if((0,r.blank)(i)&&(0,l.hasApt)()){const t=await(0,h.aptInstalledVersion)(e);i=t?.find(e=>"libheif-examples"===e.pkg)?.version}return(0,r.blank)(i)&&(0,f.hasPacman)()&&(i=(await(0,f.pacmanInstalledVersion)(e))?.version),{desc:/heif-dec/i.test(e)?"heif-dec":"heif-convert",path:e,version:(0,r.toNotBlank)(i),isSupportedVersion:(0,p.semVerSatisfies)(i,">=1.18.0")}}}catch(e){return void v().warn("Failed to get heif-convert tool details",{error:e})}}),(0,s.later)(()=>{(0,d.ee)().on("clearCache",S),(0,d.ee)().on("clearToolCache",S)}),t.getHeifThumbnailerDetails=(0,a.lazy)(async()=>{try{const e=await(0,g.heifThumbnailerPath)();if((0,r.blank)(e))return;{let t;if((0,l.hasApt)()){const i=await(0,h.aptInstalledVersion)(e);t=i?.find(e=>"heif-thumbnailer"===e.pkg)?.version}return(0,r.blank)(t)&&(0,f.hasPacman)()&&(t=(await(0,f.pacmanInstalledVersion)(e))?.version),{desc:"heif-thumbnailer",path:e,version:(0,r.toNotBlank)(t)??"(unknown)",isSupportedVersion:(0,r.blank)(t)?void 0:(0,p.semVerSatisfies)(t,">=1.18.0")}}}catch(e){return void v().warn("Failed to get heif-thumbnailer tool details",{error:e})}})},91354(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heifThumbnailerPath=t.HEIF_THUMBNAIL_MAX_SIZE=t.heifConvertPath=void 0,t.isHeifConvertSupported=async function(){return(0,r.notBlank)(await(0,t.heifConvertPath)())},t.heif2Thumb=async function(e,i){if(null!=await(0,t.heifThumbnailerPath)()){i=Math.max(512,i??512);try{return await(0,u.time)({name:"img.heif.thumb",p:(0,m.withImageCache_)(e,"heif-"+i,".png",r=>async function(e,i,r){const s=await(0,t.heifThumbnailerPath)();if(null!=s)try{await(0,c.stdoutResult_)(s,["-s",r.toFixed(),e.nativePath,i.base],{timerName:"proc.heifConvert",cwd:i.dir,timeoutMs:f.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await i.clear().isEmptyFile(a.KB)&&p().throw("heif2Thumb_() failed: destination file was empty",{src:e,dest:i})}catch(t){p().throw("heif2Thumb_() failed",{error:t,src:e.nativePath})}}(e,r,i))})}catch(t){return void p().info("heif2Thumb_(): no thumbnail available",{src:e.nativePath,error:t})}}},t.heif2png_=async function(e){if(null!=await(0,t.heifConvertPath)())return(0,m.withImageCache_)(e,"heif",".png",i=>async function(e,i){const r=await(0,t.heifConvertPath)();if(null!=r)try{await(0,c.stdoutResult_)(r,[e.nativePath,i.base],{timerName:"proc.heifConvert",cwd:i.dir,timeoutMs:f.Settings.taskTimeoutMs.valueOrDefault,ignoreStderr:!0}),await i.clear().isEmptyFile(a.KB)&&p().throw("heif2png() failed: destination file was empty",{src:e,dest:i})}catch(t){p().throw("heif2png() failed",{error:t,src:e.nativePath})}}(e,i))};const r=i(22573),s=i(42659),n=i(41400),a=i(12168),o=i(19851),l=i(50213),u=i(56038),c=i(84777),d=i(34102),h=i(8103),f=i(28874),m=i(13940),p=(0,o.lazy)(()=>(0,l.mkLogger)("img.HeifConvert"));function g(){t.heifConvertPath.unset(),t.heifThumbnailerPath.unset()}t.heifConvertPath=(0,o.lazy)(async()=>{const e=await(0,h.pathTo)({tool:"heif-dec"})??await(0,h.pathTo)({tool:"heif-convert"});return t.heifConvertPath.setTTL(null==e?s.minuteMs:void 0),e}),t.HEIF_THUMBNAIL_MAX_SIZE=320,t.heifThumbnailerPath=(0,o.lazy)(async()=>{const e=await(0,h.pathTo)({tool:"heif-thumbnailer"});return t.heifThumbnailerPath.setTTL(null==e?s.minuteMs:void 0),e}),(0,n.later)(()=>{(0,d.ee)().on("clearCache",g),(0,d.ee)().on("clearToolCache",g)})},13940(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imageCacheDir_=t.imageCacheDirSync_=t.ImageCacheName=void 0,t.rmImageCacheDir=async function(){if((0,u.isProd)())throw new Error("rmImgCacheDir is for tests");await(0,p.ee)().emit("clearCache"),await(0,p.ee)().emit("fileChanged");for(const e of(0,n.toA)(await(await(0,t.imageCacheDir_)()).clear().children()))await(0,r.rm)(e.nativePath,{recursive:e.isDirectorySync(),maxRetries:32,retryDelay:250,force:!0})},t.tmpImageFile_=async function(e){const i=await(0,t.imageCacheDir_)(),r=(0,m.getDevEnvFlag)("PS_NO_RANDOM_IMAGE_CACHE")?i.join("tmp",(0,d.shortStringSha)((0,h.ciSafePath)(e.src),10,y.Radix36)+"-"+e.tag+e.ext):i.join("tmp-"+y.Radix36.randomChars(2),y.Radix36.randomChars(16)+(0,a.toS)(e.ext));return await r.parent().mkdirp_(),r},t.cachedImageFile_=S,t.readableToFile_=async function({src:e,desc:t,suffix:i,f:r,minSizeBytes:n=256}){return(await S(e,t,i)).applyIfEmpty_({fn_:r,timeoutMs:2*s.minuteMs,minSizeBytes:n})},t.withImageCache_=async function(e,t,i,r){try{const s=await S(e,t,i);return await s.applyIfEmpty_({fn_:r,skipFsLock:!1,skipWip:!1,timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault,minSizeBytes:256,dirty:!0}),s}catch(r){return b().throw("withImgCache_() failed",{error:r,src:e.nativePath,desc:t,ext:i})}};const r=i(51455),s=i(42659),n=i(59455),a=i(54993),o=i(19851),l=i(50213),u=i(7282),c=i(81168),d=i(37628),h=i(46199),f=i(49776),m=i(77740),p=i(34102),g=i(95696),y=i(55222),v=i(28874),b=(0,o.lazy)(()=>(0,l.mkLogger)("img.ImgCache"));t.ImageCacheName="image-cache",t.imageCacheDirSync_=(0,o.lazy)(()=>(w(),g.PosixFile.for((0,f.cacheDir_)()).join(t.ImageCacheName))),(0,p.ee)().on("resetDirectories",()=>t.imageCacheDirSync_.unset()),t.imageCacheDir_=(0,o.lazy)(()=>(0,t.imageCacheDirSync_)().mkdirp_()),(0,p.ee)().on("resetDirectories",()=>t.imageCacheDir_.unset());const w=(0,o.lazy)(()=>{f.cacheDir_.watchLater(()=>{t.imageCacheDirSync_.unset(),t.imageCacheDir_.unset()})});async function S(e,i,r){const s=await(0,t.imageCacheDir_)();i??=e.name,r=(0,c.ensurePrefix)(r??e.ext,".");const n=s.join(...function(e){const t=e.statSync({refresh:!0}),i=(0,d.shortFsStringSha)(JSON.stringify({np:(0,u.isTest)()?(0,h.ciSafePath)(e):e.nativePath,size:t?.size,mtime:(0,u.isTest)()?0:t?.mtime}),24);return(0,c.splitEvery)(i.slice(0,24),2,3)}(e));await n.mkdirp_(),await n.utimes();const a=n.join(i+r);return b().debug("cachedImgFile("+e.baseWithGrandparent+")",{desc:i,ext:r,result:a}),a}},5852(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ImageDataHashes=void 0,t.toExifToolOption=function(e){return s.getCI(e)??!1};const r=i(50989),s=(0,r.strEnum)("MD5","SHA256","SHA512");t.ImageDataHashes=(0,r.strEnum)(...s.values,"disabled")},78078(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SEPARATION_SCORES=t.OPTIMAL_THRESHOLDS=void 0,t.OPTIMAL_THRESHOLDS={pHash:.49,rHash:.64,wHash:.72},t.SEPARATION_SCORES={pHash:.296,rHash:.29,wHash:.312}},11512(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hashRecordToHashRecord0=function(e){const t={};for(const[i,s]of(0,a.entries)(e))(0,r.blank)(s)||(t[`${i}0`]=s);return t},t.hashRecord0ToHashRecord=function(e){const t={};for(const[i,s]of(0,a.entries)(e))i.endsWith("0")&&!(0,r.blank)(s)&&(t[i.slice(0,-1)]=s);return t},t.simpleConfidence=y,t.computeConfidence=v,t.extractLuminanceBits=w,t.hashRecordToLHashHex=function(e){const{pHash:t,rHash:i,wHash:s}=e;if((0,r.blank)(t)||(0,r.blank)(i)||(0,r.blank)(s))return;return(w((0,c.b64decode)(t))<<128n|w((0,c.b64decode)(i))<<64n|w((0,c.b64decode)(s))).toString(16).padStart(48,"0")},t.compareHashRecords=function(e,t,i){const s={},n=(0,l.intersection)((0,a.keys)(e),(0,a.keys)(t)).filter(e=>(0,o.toS)(e).endsWith("Hash"));for(const a of n){if((0,r.blank)(e[a])||(0,r.blank)(t[a])){p().warn("compareHashRecords(): one of the hashes is null",{key:a,a:e[a],b:t[a]});continue}let n=(0,c.b64decode)(e[a]),o=(0,c.b64decode)(t[a]);i&&(n=w(n),o=w(o)),s[a]=(0,d.hammingDistance)(n,o)}return{distances:s,...v({hashDistances:s,isMonochrome:i})}};const r=i(22573),s=i(45599),n=i(31586),a=i(68708),o=i(54993),l=i(48884),u=i(50213),c=i(23624),d=i(57515),h=i(70417),f=i(40296),m=i(78078),p=(0,s.defer)(()=>(0,u.mkLogger)("img.ImageHashComparisons"));function g(e,t,i=16){if(e=(0,n.clamp)(0,1,e),t=(0,n.clamp)(.1,.9,t),1===e)return 1;const r=(0,n.clamp)(-15,15,i*(e-t));return 1/(1+Math.exp(-r))}function y(e){const t=(e.isMonochrome?64:192)/2,i={},r=[];for(const[s,o]of(0,a.entries)(e.hashDistances)){const e=g((0,n.clamp)(0,1,(t-o)/t),m.OPTIMAL_THRESHOLDS[s]??.75),a=m.SEPARATION_SCORES[s]??.1;i[s]=e,r.push({value:e,weight:a})}return 0===r.length?{confidence:0,confidences:i}:{confidence:(0,n.clamp)(0,1,(0,h.weightedMean)(r)),confidences:i}}function v(e){const t=y(e);return(0,f.sigFigsDeep)(t,4)}const b=(1n<<64n)-1n;function w(e){return e>b?e>>128n&b:e&b}},90354(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageHashResizeOpts=void 0;const s=r(i(9288));t.ImageHashResizeOpts={fit:s.default.fit.fill,kernel:s.default.kernel.lanczos3}},32319(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ImageHashTypes=void 0;const r=i(50989);t.ImageHashTypes=(0,r.strEnum)("pHash","rHash","wHash")},53244(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ImageHashes=void 0,t.isImageHashFields=function(e){return null!=e&&!(0,n.blank)(e.mimetype)&&(0,l.gt0)(e.width)&&(0,l.gt0)(e.height)&&P.ImageHashTypes.values.some(t=>!(0,n.blank)(e[t]))};const s=r(i(9288)),n=i(22573),a=i(45599),o=i(33374),l=i(31586),u=i(68708),c=i(34666),d=(i(30976),i(48884)),h=i(56038),f=i(55139),m=i(95696),p=i(17217),g=(i(77772),i(19851)),y=i(50213),v=i(28874),b=i(76709),w=i(11512),S=i(90354),P=i(32319),M=i(10144),T=i(8081),_=i(2090),E=i(65891),k=i(5733),D=i(50961),I=i(34264),C=(0,a.defer)(()=>(0,y.mkLogger)("img.ImageHashes")),A={pHash:T.pHash,rHash:E.rHash,wHash:I.wHash},x={pHash:T.pHashCIELAB,rHash:E.rHashCIELAB,wHash:I.wHashCIELAB};async function F(e,t,i=0){return(0,h.time)({name:"img.buildHashRecord",p:async()=>{const r=0===i?e:(0,k.sharpAddRotation)(e.clone(),i),s=t?A:x,n=await Promise.all((0,u.entries)(s).map(async([e,t])=>{try{return[e,await t(r.clone())]}catch(t){return C().warn(`Failed to compute ${e}`,{error:t}),[e,void 0]}}));return C().tap({msg:"buildHashRecord()",result:(0,u.fromEntries)(n),meta:{rotation:i,monochrome:t}})}})}class O{#R;src;sr;static cache=(0,a.defer)(()=>new f.Cache({name:"ImageHashes"}));static for(e){return this.cache().getOrSet((0,p.toNativePath_)(e),()=>new O(e))}constructor(e,t){this.src=m.PosixFile.for(e),this.#R=C().child(": "+this.src.baseWithGrandparent),this.sr=new D.SharpReadable({src:this.src,minDim:{width:64,height:64},skipEmbedded:!1}),t&&this.#Rt.set((0,k.sharpClone)((0,k.sharpResize)(t,{fit:s.default.fit.fill,width:64,height:64})))}toLogJSON(){return{_ctor:"ImageHashes",src:this.src.nativePath}}sizeInfo_(){return this.sr.sizeInfo_()}mimetype_(){return this.sr.mimetype_()}#Rt=(0,g.lazy)(async()=>(0,k.sharpClone)((0,k.sharpResize)(await this.sr.sharp_(),{width:96,height:96,...S.ImageHashResizeOpts})));async writeSq(e){return(await this.#Rt()).clone().png({quality:100,compressionLevel:9}).toFile(e.nativePath)}assetHashes_=(0,a.defer)(async()=>{const e=await this.#Rt(),t=(await(0,M.isMonochrome)(e)).isMonochromatic,i=await this.sr.sizeInfo_(),r=await F(e,t,0),s=(await(0,b.computeGradientCanonicalOrientation)(e.clone())).canonicalRotation,n=0!==s?await F(e,t,s):{};return{mimetype:await this.mimetype_(),monochrome:t,...r,...(0,w.hashRecordToHashRecord0)(n),canonicalRotation:s,...i.dimensions}});searchHashes=(0,a.defer)(async()=>{const e=await this.assetHashes_(),t=await this.#Rt(),i=e.monochrome;return[{rotation:0,hashes:e},...await Promise.all([90,180,270].map(async e=>({rotation:e,hashes:await F(t.clone(),i,e)})))]});async searchHashArrays(){const e=await this.searchHashes();return(0,u.fromEntries)(P.ImageHashTypes.values.map(t=>[t,e.flatMap(e=>e.hashes[t])]))}async compare(e,t){const i=e instanceof O?await e.assetHashes_():e,r=await this.mimetype_(),s=!(0,n.blank)(r)&&!(0,n.blank)(i.mimetype)&&r===i.mimetype;t??=(s?v.Settings.imageHashThresholdPct.valueOrDefault:v.Settings.imageHashCrossFormatThresholdPct.valueOrDefault)/100;const a=await this.sizeInfo_();if(t>0&&!(0,_.similarRatios)(a.dimensions,i,.1)&&!(0,_.similarRatios)(a.dimensions,(0,_.toRatio)(i,90),.1))return this.#R.debug("compare(): aspect ratios are too different to be similar images",{this:this.src.nativePath,this_dim:a.dimensions,other_dim:(0,o.pickDims)(i)}),{sameMimetype:s,details:"aspect ratios are too different"};const l=await this.assetHashes_(),u=(l.monochrome??!1)||(i.monochrome??!1),h={rotation:0,...(0,w.compareHashRecords)(l,i,u)};if(this.#R.debug("compare()",{comparison:h}),t>0&&(0,c.gte)(h.confidence,t))return this.#R.tap({msg:"compare()",result:{details:"images with current rotation are similar enough",result:h,comparisons:[h],monochrome:u,sameMimetype:s,confidenceThreshold:t}});const f=[h];for(const{rotation:e,hashes:t}of await this.searchHashes())f.push({rotation:e,...(0,w.compareHashRecords)(t,i,u)});const m=(0,d.greatestBy)(f,e=>(0,c.gte)(e.confidence,t)?[e.confidence,e.rotation]:void 0),p=f.map(R).join(", "),g=null==m?"No rotation produced similar image hashes: "+p:R(m);return this.#R.tap({msg:"compare()",result:{result:m,details:g,monochrome:u,sameMimetype:s,confidenceThreshold:t,comparisons:f}})}}function R(e){return`${e.rotation}° = ${(0,l.fmtPct)(100*e.confidence)}`}t.ImageHashes=O},42725(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ImageSize=void 0;const r=i(57975),s=i(45599),n=i(33374),a=i(55835),o=i(12168),l=i(76790),u=i(48884),c=i(28874),d=i(32876),h=i(5733);class f{name;maxWidth;maxHeight;reducer;rotational;static#Lt=[];static sq(){return this.#Lt.filter(e=>e.reducer===d.Square)}static largestSq(){return(0,u.greatestBy)(this.sq(),e=>e.megapixels())}static fit(){const e=c.Settings.previewResolutions.values;return this.#Lt.filter(t=>t.reducer===d.Fit&&e.some(e=>e===t.name))}static largestFit(){return(0,u.greatestBy)(this.fit(),e=>e.megapixels())}static all(){return[...this.#Lt]}static UHD8k=new f("uhd8k",7680,4320,d.Fit,!1);static UHD5k=new f("uhd5k",5120,2880,d.Fit,!1);static UHD=new f("uhd4k",4096,2160,d.Fit);static QHD=new f("qhd",3120,1440,d.Fit);static FHD=new f("fhd",1920,1080,d.Fit);static HD=new f("hd",1280,720,d.Fit);static WVGA=new f("wvga",720,480,d.Fit);static QVGA=new f("qvga",320,240,d.Fit);static QQVGA=new f("qqvga",160,120,d.Fit);static S480=new f("s480",480,480,d.Square);static S240=new f("s240",240,240,d.Square);static S120=new f("s120",120,120,d.Square);static S60=new f("s60",60,60,d.Square);static byName(e){return this.#Lt.find(t=>t.name===e)}static originalFit(e){return new f("original",e.width,e.height,d.Fit,!1)}static nearestFit(e){if(e.width<=0||e.height<=0)return;const t=(0,a.map)((0,n.pixels)(e),o.megapixels);return null==t?void 0:(0,l.leastBy)(this.fit(),e=>Math.abs(t-e.megapixels()))}max;constructor(e,t,i,r,s=!0){this.name=e,this.maxWidth=t,this.maxHeight=i,this.reducer=r,this.rotational=s,this.max={width:t,height:i},"original"!==e&&f.#Lt.push(this)}[r.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"×"+this.maxHeight,maxMP:this.megapixels()}}get aspectRatio(){return this.maxWidth/this.maxHeight}get maxPixels(){return this.maxWidth*this.maxHeight}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}megapixels=(0,s.defer)(()=>(0,o.megapixels)(this.maxWidth*this.maxHeight));outputSize(e){return this.reducer.reduce(this.rotational&&(0,n.isPortrait)(e)?(0,n.dimSwap)(this.max):this.max,e)}contains(e){return e.width<=this.maxWidth&&e.height<=this.maxHeight}justFits(e){if(!this.contains(e))return!1;const t=this.outputSize(e);return null!=t&&(e.width===t.width||e.height===t.height)}resize(e,t){return t.resize({...e,fit:this.reducer.fit,withoutEnlargement:!0})}toJpeg({path:e,sh:t,outputSize:i}){return((0,n.dmegapixels)(i)<2||c.Settings.previewSharpen.valueOrDefault)&&(t=t.sharpen()),t.jpeg((0,h.sharpRenderOptions)()).toFile(e)}toString(){return this.name}}t.ImageSize=f},4192(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.includePreviewTags_=async function(e,t){!1===l.Settings.includePreviewTags.valueOrDefault||l.Settings.includedPreviewTags.isEmpty()||(0,s.isEmpty)(t)||(d().info("Re-adding metadata to previews..."),await(0,o.time)({name:"img.includePreviewTags",p:async()=>{const i=(0,n.pick)(await(0,u.readTags)(e),...l.Settings.includedPreviewTags.values),r=i?.capturedAt;null!=r&&(delete i.capturedAt,(0,n.assignFields)(i,r.asExifTag()));const s=i?.exposureSettings;null!=s&&(delete i.exposureSettings,i.FocalLength=s.focalLength,i.FNumber=s.aperture,i.ExposureTime=s.shutterSpeed,i.ISO=s.iso),l.Settings.includedPreviewTags.has("Source")&&(i.Source=e.nativePath),(0,n.isEmptyObj)(i)?d().warn("not adding tags to previews: no values for tags in source file",{src:e,includedPreviewTags:l.Settings.includedPreviewTags.values}):(d().info("Overwriting preview tags...",{src:e,writeTags:i}),await Promise.all(t.map(e=>(0,c.overwriteTags_)(e,i))))}}))};const r=i(19851),s=i(40958),n=i(68708),a=i(50213),o=i(56038),l=i(28874),u=i(40538),c=i(80985),d=(0,r.lazy)(()=>(0,a.mkLogger)("img.includePreviewTags"))},10144(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMonochrome=async function(e,t={}){const{isHistorical:i=!1}=t,{data:a,info:o}=await(0,n.sharpToColorspaceBuffer)((0,n.sharpResize)(e,{width:64,height:64,fit:"fill"}),"float","lab"),l=o.width*o.height,u=a;let c=0,d=0,h=0,f=0;for(let e=0;e<l;e++){const{a:t,b:i}=(0,r.extractValidLabPixel)(u,e);c+=t,d+=i}const m=c/l,p=d/l,g=Math.sqrt(m*m+p*p);let y=null;y=g<1e-6?null:(0,r.calculateLabHue)(m,p);const v=null!==y&&y>=47&&y<=87,{variance:b,chroma:w,mode:S}=function(e,t){return e?{variance:50,chroma:21,mode:"historical"}:t?{variance:10,chroma:21,mode:"modern"}:{variance:5,chroma:3,mode:"modern"}}(i,v);for(let e=0;e<l;e++){const{a:t,b:i}=(0,r.extractValidLabPixel)(u,e),n=t-m,a=i-p;h+=n*n+a*a;const o=(0,r.calculateLabHue)(t,i);(0,s.calculateAngularDistance)(o,67)<=20&&f++}const P=h/l,M=f/l,T=Math.sqrt(P+g*g),_=function(e){const{mse:t,meanChroma:i,varianceThreshold:r,chromaThreshold:s,isLikelySepia:n,sepiaSimilarity:a,dominantHue:o,mode:l}=e,u=t<=r&&i<=s,c=n?"sepia":l;let d=`${u?"Monochrome":"Color"}: MSE=${t.toFixed(2)}, chroma=${i.toFixed(1)}, mode=${c}`;return u&&n?d+=`, sepia similarity=${(100*a).toFixed(0)}%`:u||(d+=t>r&&i>s?" (high variance and chroma)":t>r?` (high variance: ${t.toFixed(2)} > ${r.toFixed(1)})`:` (high chroma: ${i.toFixed(1)} > ${s.toFixed(1)})`),null!==o&&(d+=`, hue=${o.toFixed(0)}°`),{isMonochromatic:u,explanation:d}}({mse:P,meanChroma:T,varianceThreshold:b,chromaThreshold:w,isLikelySepia:v,sepiaSimilarity:M,dominantHue:y,mode:S});return{isMonochromatic:_.isMonochromatic,dominantHue:y,meanChroma:T,mse:P,sepiaSimilarity:M,explanation:_.explanation,mode:S}};const r=i(86758),s=i(71290),n=i(5733)},48604(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildAssetPreviews_=t.Previews=void 0;const r=i(19851),s=i(55835),n=i(50213),a=i(79136),o=i(87290),l=i(38835),u=i(95242),c=i(16524);class d{root;static instance=(0,r.lazy)(()=>((0,n.mkLogger)("Previews").info(".instance()",{libraryPreviewsDir:(0,o.libraryPreviewsDirPosixFile)()}),(0,s.map)((0,o.libraryPreviewsDirPosixFile)(),e=>new d(e))));static instanceRequired(){const e=d.instance();if(null==e)throw new Error("Previews.instance() is not set (no library yet?)"+l.NoLibraryErrorFlag);return e}constructor(e){this.root=e}apb(e,t,i){return new u.AssetPreviewBuilder(this.ap(e),t,i)}ap(e){return new c.AssetPreviews(this.root,e)}}t.Previews=d,t.buildAssetPreviews_=(0,a.shim)({name:"img.buildAssetPreviews",impl:e=>d.instance().apb(e.assetId,e.assetFiles,e).build_()})},2090(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RatioEpsilon=t.StandardAspectRatios=t.Ratios=void 0,t.toRatio=u,t.roundToNearestRatio=c,t.similarRatios=d,t.similarRatiosWithRotation=function(e,i,r=t.RatioEpsilon){return(0,n.isDimensions)(e.dimensions)&&(0,n.isDimensions)(i.dimensions)?d(u(e.dimensions,e.rotation),u(i.dimensions,i.rotation),r):void 0},t.roundAspectRatio=function(e,t=.05){return t<=0?e:h(e,t)?.result.i??e},t.fmtAspectRatio=function(e,i=t.RatioEpsilon/2){return h(e,i)?.result.s??String((0,a.sigFigs)(e,3))};const r=i(40958),s=i(76790),n=i(33374),a=i(31586),o=i(21605),l=i(48884);function u(e,t){if(null!=e){if((0,a.gt0)(e))return(0,o.swappableRotation)(t)?1/e:e;if((0,n.isDimensions)(e)){const i=(0,o.swappableRotation)(t)?(0,n.dimSwap)(e):e;return 0===i.height?void 0:i.width/i.height}}}function c(e,i=t.RatioEpsilon){const r=u(e);return null==r?void 0:(0,s.leastBy)(t.StandardAspectRatios,e=>{const t=Math.abs(r-e);return t>i?void 0:t})??r}function d(e,i,r=t.RatioEpsilon){if(null==e||null==i)return!1;const s=c(e),n=c(i),o=(0,a.absdiff)(s,n);return(0,a.lte)(o,r)}function h(e,i){return(0,l.leastByCtx)(t.Ratios,t=>{const r=Math.abs(t.i-e);return r<i?r:void 0})}t.Ratios=(0,r.uniqBy)((0,l.flatMap)([[3,2],[4,3],[16,9],[1,1]],([e,t])=>[{i:e/t,s:e+":"+t},{i:t/e,s:t+":"+e}]),e=>e.s),t.StandardAspectRatios=t.Ratios.map(e=>e.i),t.RatioEpsilon=.06},34943(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rawInfo=async function(e){try{return await p(e)}catch(t){return void f().warn("rawInfo() failed",{error:t,file:e})}},t.rawInfo_=p,t.parseRawInfoOutput_=g;const r=i(19851),s=i(22573),n=i(31586),a=i(50213),o=i(84777),l=i(88561),u=i(41080),c=i(89966),d=i(28874),h=i(30748),f=(0,r.lazy)(()=>(0,a.mkLogger)("img.RawInfo")),m=(0,r.lazy)(()=>new l.FileCache({maxSize:512,name:"img.RawInfoCache",timeoutMs:d.Settings.taskTimeoutMs.valueOrDefault,clearEveryMs:d.Settings.metadataCacheMs.valueOrDefault}));async function p(e){return m().getOrSet(e.nativePath,async()=>{const t=await(0,c.rawIdentifyNativePath_)(),i=await(0,o.stdoutResult_)(t,["-s",e.nativePath],{timerName:"proc.libraw",timeoutMs:(0,u.statTimeoutMs)()});if(f().debug("rawInfo()",{cmd:t,src:e.nativePath,result:i}),(0,s.notBlank)(i.stderr)){let t=i.stderr.trim();return t.includes(e.nativePath)||(t=e.nativePath+": "+t),f().throw("rawInfo() failed",{error:t})}return g(e,i.result)})}function g(e,t){const[i,r,s,a,o]=t.split("\t"),l=(0,n.toGt0)(a),u=(0,n.toGt0)(o);return null==l||null==u?f().throw("parseRawInfoOutput_ failed (missing dimensions)",{src:e.nativePath,cause:t}):f().tap({msg:"parseRawInfoOutput()",result:{Filename:i,...(0,h.makeModel)({Make:r,Model:s}),ImageSize:{width:l,height:u}},meta:{input:t}})}},32876(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Reducers=t.Fit=t.Square=t.SharpFits=void 0,t.fitInsideToAspectRatio=function(e,t){return e.width/e.height>=t?{width:Math.floor(e.height*t),height:e.height}:{width:e.width,height:Math.floor(e.width/t)}},t.fitInsideToMaxPixels=function(e,t){if(null==e||!(0,o.gt0)(e.width)||!(0,o.gt0)(e.height))return;if((0,s.pixels)(e)<t)return;const i=e.width/e.height,r=Math.floor(Math.sqrt(t/i));return{width:Math.floor(i*r),height:r}};const r=i(19851),s=i(33374),n=i(4188),a=i(11371),o=i(31586),l=i(68708),u=i(50989),c=i(50213),d=i(86580);var h,f;t.SharpFits=(0,u.strEnum)("cover","contain","fill","inside","outside"),function(e){const i=(0,r.lazy)(()=>(0,c.mkLogger)("img.Reducers.Square"));e.name=a.ReducerNames.sq,e.fit="cover",e.reduce=function(e,r){const s=(0,d.lteBoth)(e,r)?{...e,fit:t.SharpFits.cover}:void 0;return i().tap({msg:"reduce()",result:s,meta:{max:e,input:(0,l.pick)(r,"width","height","nativePath")}})}}(h||(t.Square=h={})),function(e){const t=(0,r.lazy)(()=>(0,c.mkLogger)("img.Reducers.Fit"));e.name=a.ReducerNames.fit,e.fit="inside",e.reduce=function(e,i){if(!(0,d.ltBoth)(i,e))return(0,n.fitInside)(i,e);t().trace(`reduce(): input ${(0,s.fmtDim)(i)} is too small for ${(0,s.fmtDim)(e)}`)}}(f||(t.Fit=f={})),t.Reducers=[h,f]},5733(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.setupSharp=t.Colorspaces=void 0,t.isSharp=P,t.isToBufferResult=M,t.sharpToRawBuffer=function(e,t){return M(e)?e:(null==t?e.removeAlpha().toColorspace("srgb"):e=t(e),e.raw().toBuffer({resolveWithObject:!0}))},t.sharpToColorspaceBuffer=T,t.sharpToOklabBuffer=async function(e){const t=await T(e,"float","xyz"),i=new Float32Array(t.data.length);for(let e=0;e<t.data.length;e+=3){const r=(0,y.xyz2oklab)(t.data[e],t.data[e+1],t.data[e+2],{fromSharp:!0});i[e]=r[0],i[e+1]=r[1],i[e+2]=r[2]}return{data:i,info:t.info}},t.sharpToOklchBuffer=async function(e){const t=await T(e,"float","xyz"),i=new Float32Array(t.data.length);for(let e=0;e<t.data.length;e+=3){const r=(0,y.xyz2oklch)(t.data[e],t.data[e+1],t.data[e+2],{fromSharp:!0});i[e]=r[0],i[e+1]=r[1],i[e+2]=r[2]}return{data:i,info:t.info}},t.sharpClone=async function(e){try{return _(await e.clone().raw().toBuffer({resolveWithObject:!0}))}catch(e){return S().throw("clone via sharp.raw().toBuffer() failed",{error:e,logLevel:"warn"})}},t.sharpFromBufferResult=_,t.sharpFromRawBuffer=function(e,t){return(0,o.default)(e,{raw:t,failOnError:!1})},t.sharpRenderOptions=function(){return{quality:b.Settings.previewQuality.valueOrDefault,progressive:b.Settings.previewProgressive.valueOrDefault,mozjpeg:b.Settings.previewMinimized.valueOrDefault}},t.isSharpWithOptions=E,t.sharpGetRotation=k,t.sharpAddRotation=function(e,t){if(0===t)return e;if(E(e)&&!0===e.options.useExifOrientation)throw new Error("sharp will ignore this rotation");return e.rotate((0,m.normalizeRotation)((k(e)??0)+t))},t.sharpClearRotation=D,t.sharpSetRotateBeforePreExtract=function(e,t){return E(e)&&(e.options.rotateBeforePreExtract=t),e},t.sharpResize=function(e,t){if(t.width!==t.height)return S().throw("use .resize() for non-square dimensions");if(!["fill","cover"].includes((0,g.toS)(t.fit)))return S().throw("use .resize() with {fit: 'fill'} or {fit: 'cover'}: passed "+(0,d.stringify)(t));const i=D(e);return e.resize({fastShrinkOnLoad:!0,...t}),(0,h.gt0)(i)&&e.rotate(i),e},t.affineRotation=function(e,t){switch(t){case 0:default:return e;case 90:return I(e).flip();case 180:return e.flip().flop();case 270:return I(e).flop()}},t.sharpTranspose=I;const o=a(i(9288)),l=i(19851),u=i(41400),c=i(33374),d=i(98553),h=i(31586),f=i(68708),m=i(21605),p=i(50989),g=i(54993),y=i(85810),v=i(50213),b=i(28874),w=i(15674),S=(0,l.lazy)(()=>(0,v.mkLogger)("img.Sharp"));function P(e){return null!=e&&("Sharp"===e.constructor?.name||"object"==typeof e&&"function"==typeof e.metadata&&"function"==typeof e.jpeg&&"function"==typeof e.raw&&"function"==typeof e.toBuffer)}function M(e){return(0,f.isObject)(e)&&Buffer.isBuffer(e.data)&&(0,c.isDimensions)(e.info)}async function T(e,t="char",i="lab"){if("char"===t&&"lab"!==i)throw new Error("char precision causes clipping issues with "+i);const{data:r,info:s}=await e.clone().removeAlpha().toColorspace(i).raw({depth:t}).toBuffer({resolveWithObject:!0});return{data:"char"===t?new Int8Array(r.buffer,r.byteOffset,r.length):new Float32Array(r.buffer,r.byteOffset,r.length/Float32Array.BYTES_PER_ELEMENT),info:s}}function _(e){return(0,o.default)(e.data,{raw:e.info,failOnError:!1})}function E(e){return"options"in e&&(0,f.isObject)(e.options)&&P(e)}function k(e){return(0,m.normalizeRotation)(E(e)?e.options.angle:0)}function D(e){if(E(e)){const t=e.options.angle;return e.options.angle=0,e.options.rotateBeforePreExtract=!1,e.options.useExifOrientation=!1,t}}function I(e){return e.affine([0,1,1,0],{interpolator:"nearest"})}t.Colorspaces=(0,p.strEnum)("hsl","hsv","lab","labq","labs","lch","rgb","srgb","xyz"),t.setupSharp=(0,l.lazy)(()=>{(0,o.simd)(b.Settings.enableSIMD.valueOrDefault),(0,o.cache)(!!b.Settings.enableVipsCache.valueOrDefault&&{files:32,memory:64,items:128}),(0,o.concurrency)((0,w.sharpThreadsPerProcess)())}),(0,u.later)(()=>{b.Settings.enableSIMD.watchLater(()=>t.setupSharp.refresh()),b.Settings.enableVipsCache.watchLater(()=>t.setupSharp.refresh())})},48584(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SharpFailOns=void 0;const r=i(50989);t.SharpFailOns=(0,r.strEnum)("none","truncated","error","warning")},50961(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SharpReadable=void 0,t.toSharp_=async function(e,t){return(0,I.isSharp)(e)?e:(0,g.isSimpleFile)(e)||(0,m.isString)(e)?new O({src:p.PosixFile.for(e),...t}).sharp_():(0,I.isToBufferResult)(e)?(0,I.sharpFromRawBuffer)(e.data,e.info):x().throw("toSharp_(): unexpected input",{img:e})};const s=r(i(9288)),n=i(19851),a=i(76790),o=i(22573),l=i(45599),u=i(41400),c=i(29825),d=i(98553),h=i(31586),f=i(50213),m=i(81168),p=i(95696),g=i(17217),y=i(43334),v=i(28874),b=i(16170),w=i(95141),S=i(54979),P=i(38148),M=i(1078),T=i(19918),_=i(86580),E=i(533),k=i(277),D=i(91354),I=i(5733),C=i(66106),A=i(19350),x=(0,n.lazy)(()=>(0,f.mkLogger)("img.SharpReadable"));function F(e){return!0===e.message?.includes("files could not be read")||!0===e.message?.includes("output files created")||!0===e.message?.includes("extractBinaryTag")}class O{#R;diagnostics=[];requestId=Math.random().toString(36).substring(2,9);src;minDim;skipEmbedded;constructor(e){(0,I.setupSharp)(),this.src=e.src,this.minDim=e.minDim,this.skipEmbedded=e.skipEmbedded,this.#R=x().child(`(${this.src.nativePath}:${this.requestId})`),this.diagnostics.push(`Request ID: ${this.requestId}, minDim: ${this.minDim?`${this.minDim.width}×${this.minDim.height}`:"unset"}`)}mimetype_=(0,l.defer)(async()=>{const e=await(0,S.readMimeType)(this.src);return(0,o.blank)(e)?this.#R.throw("blank mimetype",{retriable:!1,doNotSend:!0}):e});sizeInfo_=(0,l.defer)(async()=>{const e=await(0,M.extractSizeInfoFromFile)(this.src);return null==e?this.#R.throw("blank sizeInfo",{retriable:!1,doNotSend:!0}):e});async sharp_(){return(await this.sharpDetails_()).sharp.clone()}async sharpFile_(){return(await this.sharpDetails_()).file}async sharpDetails_(){try{return await this.#Nt()}catch(e){return this.#R.throw("Failed to render "+this.src,{error:e,retriable:!1,doNotSend:!0})}}#Nt=(0,l.defer)(async()=>{const e=await this.mimetype_(),t=await this.sizeInfo_(),i=await this.resultFromEmbeddedBinaryField_();if(null!=i)return this.#R.tap({msg:"sharp from embedded image",result:i});if((0,b.isSharpMimeType)(e))return this.#R.tap({msg:"sharp can directly read this file",result:{desc:"sharp:direct",sharp:(0,s.default)(this.src.nativePath,{failOn:v.Settings.imageFailOn.valueOrDefault}).rotate(t.rotation),rotation:t.rotation,file:this.src,mimetype:e,sizeInfo:t}});if((0,c.isHeifMimeType)(e)){const i=null==this.minDim?void 0:Math.max(this.minDim.width,this.minDim.height);if((0,h.within)(0,D.HEIF_THUMBNAIL_MAX_SIZE,i)){const r=await this.#R.tapAsync_({msg:"sharp from heif thumbnail",result:(0,D.heif2Thumb)(this.src,i),timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault});if(null!=r)return this.#R.tap({msg:"sharp from heif thumbnail",result:{desc:"heif-thumb",sharp:(0,s.default)(r.nativePath,{failOn:v.Settings.imageFailOn.valueOrDefault}),rotation:0,file:r,mimetype:e,sizeInfo:t}})}const r=await this.#R.tapAsync_({level:"info",msg:"sharp from heif fullsize",result:(0,k.heif2img_)(this.src)});if(null!=r)return this.#R.tap({msg:"sharp from heif fullsize",level:"info",result:{desc:"heif",sharp:(0,s.default)(r.nativePath,{failOn:v.Settings.imageFailOn.valueOrDefault}).rotate(y.isMac?t.rotation:0),rotation:0,file:r,mimetype:e,sizeInfo:t}})}let r,n;if((0,b.isLibrawMimeType)(e))try{const i=await(0,A.raw2tiff_)(this.src);if(null!=i)return this.#R.tap({msg:"convert raw to TIFF",result:{desc:"raw",sharp:(0,s.default)(i.nativePath,{failOn:v.Settings.imageFailOn.valueOrDefault}).rotate(t.rotation),rotation:t.rotation,file:i,mimetype:e,sizeInfo:t}})}catch(e){this.#R.warn("convert raw to TIFF failed",{error:e}),r=e?.message??String(e)}if((0,b.isVideoMimeType)(e)&&await(0,C.isVideoSupported)())try{const i=await(0,C.extractVideoFrame_)(this.src);if(null!=i)return this.#R.tap({msg:"extracting video frame",result:{desc:"video",sharp:(0,s.default)(i.nativePath,{failOn:v.Settings.imageFailOn.valueOrDefault}),rotation:0,file:i,mimetype:e,sizeInfo:t}})}catch(e){this.#R.warn("video frame extraction failed",{error:e}),n=e?.message??String(e)}const a=null!=n?"Failed to render video: "+n:null!=r?"Failed to render raw: "+r:"Failed to render with any strategy";return this.#R.throw(a,{mimetype:e,sizeInfo:t,src:this.src.nativePath,retriable:!1,doNotSend:!0})});async whyNotUseEmbeddedBinaryField(){if(!0===this.skipEmbedded)return this.#R.tap({msg:"whyNotUseEmbeddedBinaryField",result:"this.skipEmbedded == true"});const e=await this.mimetype_();if((0,b.isSharpMimeType)(e)&&v.Settings.skipEmbeddedImageMimeTypes.valueOrDefault.includes(e))return this.#R.tap({msg:"whyNotUseEmbeddedBinaryField",result:"sharp-supported mimetype in "+v.Settings.skipEmbeddedImageMimeTypes.key,meta:{mimetype:e}});if((0,b.isSharpMimeType)(e)&&null==this.minDim)return this.#R.tap({msg:"whyNotUseEmbeddedBinaryField",result:"sharp-supported mimetype, and null minDim: must load original",meta:{mimetype:e}});if((0,b.isVideoMimeType)(e))return this.#R.tap({msg:"whyNotUseEmbeddedBinaryField",result:"video file: not using embedded",meta:{mimetype:e}});const t=await this.sizeInfo_(),i=(0,_.aspectRatio)(t.fileDimensions);return(0,h.lt)(i,1)?this.#R.tap({msg:"whyNotUseEmbeddedBinaryField",result:"rastered portrait aspect ratio: embedded are ineligible",meta:{sizeInfo:t}}):(0,w.orientationRequiresMirroring)(t.orientation)?this.#R.tap({msg:"whyNotUseEmbeddedBinaryField",result:"file is mirrored: embedded are ineligible",meta:{orientation:t.orientation}}):void 0}async resultFromEmbeddedBinaryField_(){const e=performance.now(),t=await this.whyNotUseEmbeddedBinaryField();if(!(0,o.blank)(t))return void this.diagnostics.push(`Embedded images skipped: ${t}`);let i;this.#R.debug("Starting readRawTags for embedded preview extraction");let r=0;for(;r<3;){r++;try{const e=performance.now(),t=await(0,P.readRawTags)(this.src),s=performance.now()-e;if(this.#R.debug("readRawTags completed",{durationMs:s,attempt:r,gotResult:null!=t}),null==t){const e=this.src.statSync();if(this.#R.warn("readRawTags returned null",{src:this.src.nativePath,mimetype:await this.mimetype_(),fileExists:this.src.existsSync(),fileSize:e?.size,fileModified:e?.mtime,durationMs:s,requestId:this.requestId,minDim:this.minDim,attempt:r,willRetry:r<3}),this.diagnostics.push(`readRawTags returned null after ${s}ms (attempt ${r}/3)`),r<3){await(0,u.delay)(50*r);continue}return void this.diagnostics.push(`readRawTags failed after ${r} attempts - falling back to raw conversion`)}i=t;break}catch(t){const i=performance.now()-e;if(this.#R.error("readRawTags threw error",{error:t.message,stack:t.stack,src:this.src.nativePath,durationMs:i,attempt:r}),this.diagnostics.push(`readRawTags error after ${i}ms (attempt ${r}): ${t.message}`),r>=3)throw t;await(0,u.delay)(50*r)}}if(null==i)return void this.diagnostics.push(`Failed to read tags after ${r} attempts`);const s=await this.sizeInfo_(),n=s.dimensions,l=null!=this.minDim?{width:1.2*this.minDim.width,height:1.2*this.minDim.height}:{width:Math.round(.9*n.width),height:Math.round(.9*n.height)};this.#R.debug("Embedded preview dimension calculation",{originalMinDim:this.minDim,calculatedDim:l,sidDimensions:n,bufferFactor:1.2,previewFactor:.9});const c=null==this.minDim?void 0:Math.max(this.minDim.width,this.minDim.height),h=null!=c&&c<100;this.#R.debug("Embedded preview evaluation",{originalMinDim:this.minDim,calculatedDim:l,maxRequestedDim:c,useSmallThumbnails:h});const f=[];for(const e of v.Settings.embeddedPreviews.values)if(e in i&&(0,T.isBinaryField)(i[e])){const t=i[e],r=t.bytes>51200;this.#R.debug("Evaluating embedded preview tag",{tag:e,bytes:t.bytes,isLargeEnough:r,isThumbnail:!1}),this.diagnostics.push(`Found preview tag ${e}: ${t.bytes} bytes ${r?"(large enough)":"(too small)"}`),r&&f.push({tag:e,bytes:t.bytes,isThumbnail:!1})}if(h){this.diagnostics.push(`Using small thumbnails (maxRequestedDim: ${c}px)`);for(const e of v.Settings.embeddedThumbnails.values)if(e in i&&(0,T.isBinaryField)(i[e])){const t=i[e];this.#R.debug("Evaluating embedded thumbnail tag",{tag:e,bytes:t.bytes,isThumbnail:!0}),this.diagnostics.push(`Found thumbnail tag ${e}: ${t.bytes} bytes`),f.push({tag:e,bytes:t.bytes,isThumbnail:!0})}}else this.diagnostics.push("Skipping small thumbnails: "+(0,d.stringify)({maxRequestedDim:c}));(0,a.sortByInPlace)(f,e=>e.bytes),this.#R.debug("Trying to extract embedded preview from these tags",{binaryFields:f});for(const e of f){const t=performance.now();try{if(this.#R.debug("Attempting to extract embedded image",{tag:e.tag,bytes:e.bytes,isThumbnail:e.isThumbnail,fileAspectRatio:(0,_.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 r=null,n=0;const a=3;for(;n<a&&null==r;){n++;try{if(r=await(0,E.extractThumbnailWithTrimming)(this.src,i,e.tag,s,l,(0,_.aspectRatio)(s.dimensions)),null!=r)break}catch(t){const i=n<a&&F(t);if(this.#R.warn("extractThumbnailWithTrimming failed, will retry",{tag:e.tag,attempt:n,maxAttempts:a,error:t.message,willRetry:i}),!i)throw t;await(0,u.delay)(100*n)}}if(null!=r){const i=performance.now()-t;return this.#R.debug("Successfully extracted thumbnail with smart trimming",{tag:e.tag,desc:r.desc,dimensions:r.dimensions,durationMs:i}),this.diagnostics.push(...r.diagnostics),this.diagnostics.push(`SUCCESS: ${e.tag} extracted in ${i}ms`),{...r,mimetype:await this.mimetype_()}}{const i=performance.now()-t;this.#R.debug("extractThumbnailWithTrimming vetoed thumbnail for tag",{tag:e.tag,durationMs:i}),this.diagnostics.push(`VETOED: ${e.tag} was rejected by smart trimming logic after ${i}ms`)}}else{let r=null,n=0;const a=3;for(;n<a&&null==r;){n++;try{if(r=await(0,E.imgFromExif_)(this.src,i,e.tag,(0,_.aspectRatio)(s.dimensions),l),null!=r)break}catch(t){const i=n<a&&F(t);if(this.#R.warn("imgFromExif_ failed, will retry",{tag:e.tag,attempt:n,maxAttempts:a,error:t.message,willRetry:i}),!i)throw t;await(0,u.delay)(100*n)}}if(null!=r){const i=performance.now()-t;return this.#R.debug("Successfully extracted embedded preview",{tag:e.tag,resultDimensions:r.dimensions,rotation:r.rotation,durationMs:i}),r.diagnostics&&this.diagnostics.push(...r.diagnostics),this.diagnostics.push(`SUCCESS: ${e.tag} extracted in ${i}ms`),{desc:"embedded:"+e.tag,...r,sizeInfo:s,mimetype:await this.mimetype_()}}{const i=performance.now()-t;this.#R.debug("imgFromExif_ returned null for tag",{tag:e.tag,durationMs:i}),this.diagnostics.push(`FAILED: ${e.tag} rejected by imgFromExif_ after ${i}ms`)}}}catch(i){const r=performance.now()-t;this.#R.debug("Failed to extract embedded preview from "+e.tag,{error:i.message,stack:i.stack,durationMs:r}),this.diagnostics.push(`ERROR: ${e.tag} extraction failed after ${r}ms: ${i.message}`)}}const m=performance.now()-e;this.#R.debug("No valid embedded previews were found",{totalCandidates:f.length,tags:f.map(e=>e.tag),totalDurationMs:m}),this.diagnostics.push(`No embedded images could be used (tried ${f.length} candidates in ${m}ms)`)}}t.SharpReadable=O},32721(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTrimResult=function(e){return null!=e&&"object"==typeof e&&"sharp"in e&&"object"==typeof e.sharp&&(!("originalDimensions"in e)||null==e.originalDimensions||(0,n.isDimensions)(e.originalDimensions))&&(!("trimmedDimensions"in e)||null==e.trimmedDimensions||(0,n.isDimensions)(e.trimmedDimensions))&&"maxReductionRatio"in e&&"number"==typeof e.maxReductionRatio&&"trimApplied"in e&&"boolean"==typeof e.trimApplied},t.safeTrim=d,t.removeLetterbox=async function(e,t=10){return d("object"==typeof e&&"metadata"in e?e:(0,s.default)(e),{background:"black",threshold:t,maxTrimPct:l.Settings.maxThumbTrimPct.valueOrDefault,trimAliasPixels:l.Settings.thumbTrimAliasPixels.valueOrDefault})};const s=r(i(9288)),n=i(33374),a=i(19851),o=i(50213),l=i(28874),u=i(5733),c=(0,a.lazy)(()=>(0,o.mkLogger)("img.SharpTrim"));async function d(e,t={}){const i={background:"black",threshold:4,maxTrimPct:l.Settings.maxThumbTrimPct.valueOrDefault,trimAliasPixels:l.Settings.thumbTrimAliasPixels.valueOrDefault,...t};if(i.maxTrimPct<0||i.maxTrimPct>100)throw new Error(`maxTrimPct must be 0-100, got ${i.maxTrimPct}`);if(0===i.maxTrimPct)return c().tap({msg:"Trim skipped due to maxTrimPct=0",result:{sharp:e,maxReductionRatio:0,trimApplied:!1,skipReason:"maxTrimPct is set to 0"}});const r=i.maxTrimPct/100;try{const t="object"==typeof e&&"metadata"in e?e:(0,s.default)(e,{failOn:l.Settings.imageFailOn.valueOrDefault}),a=await(0,u.sharpClone)(t),o=await a.metadata(),d={width:o.width,height:o.height};if(!(0,n.isDimensions)(d))throw new Error("Cannot determine original image dimensions");const h=t.clone().trim({background:i.background,threshold:i.threshold}),f=await(0,u.sharpClone)(h),m=await f.metadata(),p={width:m.width,height:m.height};if(!(0,n.isDimensions)(p))throw new Error("Cannot determine trimmed image dimensions");const g=1-p.width/d.width,y=1-p.height/d.height,v=Math.max(g,y);if(v>r)return c().info("Trim skipped: would reduce dimensions too much",{maxReductionRatio:v,maxTrimRatio:r,maxTrimPct:i.maxTrimPct,widthReductionRatio:g,heightReductionRatio:y,originalDimensions:d,trimmedDimensions:p}),c().tap({msg:"Trim skipped due to safety limits",result:{sharp:t,originalDimensions:d,trimmedDimensions:d,maxReductionRatio:0,trimApplied:!1,skipReason:`Max reduction ${(100*v).toFixed(1)}% exceeds limit ${i.maxTrimPct.toFixed(1)}%`}});let b=h,w=p;if(i.trimAliasPixels&&i.trimAliasPixels>0){const e=d.width>p.width,t=d.height>p.height;if(e||t){const r={left:e?i.trimAliasPixels:0,top:t?i.trimAliasPixels:0,width:p.width-(e?2*i.trimAliasPixels:0),height:p.height-(t?2*i.trimAliasPixels:0)};r.width>0&&r.height>0?(b=(await(0,u.sharpClone)(h)).extract(r),w={width:r.width,height:r.height},c().info("Applied additional alias pixel trimming",{trimAliasPixels:i.trimAliasPixels,widthTrimmed:e,heightTrimmed:t,extractRegion:r,trimmedDimensions:p,finalDimensions:w})):c().warn("Skipped alias pixel trimming - would result in invalid dimensions",{trimAliasPixels:i.trimAliasPixels,extractRegion:r,trimmedDimensions:p})}else c().debug("Skipped alias pixel trimming - no dimensions were trimmed",{trimAliasPixels:i.trimAliasPixels,originalDimensions:d,trimmedDimensions:p})}return c().tap({msg:"Trim applied successfully",result:{sharp:b,originalDimensions:d,trimmedDimensions:w,maxReductionRatio:v,trimApplied:!0}})}catch(e){return c().throw("safeTrim failed",{error:e,options:i})}}},21473(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testSharp_=async function e(t){try{(0,h.setupSharp)();const e=t??(0,n.join)(c.ProjectDir.Public(),"images","logo@5x.png"),i=(0,a.default)(e,{failOn:"error"}),r=await i.resize(24,32,{fit:"cover",position:"attention"}).toFormat("jpeg").toBuffer({resolveWithObject:!0});(0,s.default)((0,o.eql)((0,u.pick)(r.info,"format","width","height","channels"),{format:"jpeg",width:24,height:32,channels:3}),"Unexpected sharp output: "+(0,l.stringify)(r.info))}catch(i){if(d.Settings.enableSIMD.valueOrDefault)return d.Settings.enableSIMD.cliValue=!1,h.setupSharp.unset(),e(t);throw i}};const s=r(i(34589)),n=i(76760),a=r(i(9288)),o=i(50357),l=i(98553),u=i(68708),c=i(46473),d=i(28874),h=i(5733)},181(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyInvalidFile=void 0,t.isValidFile=async function(e){return(0,s.blank)(await(0,t.whyInvalidFile)((0,h.toNativePath_)(e)))},t.throwIfInvalidFile_=async function(e){if(!f.Settings.validateJpegImages.valueOrDefault&&!f.Settings.validateRawImages.valueOrDefault&&!f.Settings.validateVideos.valueOrDefault)return void S().debug("file validation is disabled for "+e,{validateJpegImages:f.Settings.validateJpegImages.valueOrDefault,validateRawImages:f.Settings.validateRawImages.valueOrDefault,validateVideos:f.Settings.validateVideos.valueOrDefault});const i=(0,h.toNativePath_)(e),r=S().tap({msg:"whyInvalidFile("+i+")",result:await(0,t.whyInvalidFile)(i)});(0,s.notBlank)(r)&&S().throw(r,{path:i,retriable:!1,doNotSend:!0,ignorable:!0})},t.clearInvalidFileCache=function(){return P().clear()};const r=i(19851),s=i(22573),n=i(42659),a=i(98553),o=i(50213),l=i(79136),u=i(81168),c=i(88561),d=i(95696),h=i(17217),f=i(28874),m=i(16170),p=i(54979),g=i(63870),y=i(50961),v=i(19769),b=i(66106),w=i(51210),S=(0,r.lazy)(()=>(0,o.mkLogger)("img.ValidFile")),P=(0,r.lazy)(()=>new c.FileCache({name:"img.validFile",maxSize:256,timeoutMs:Math.max(n.minuteMs,f.Settings.validateVideos.valueOrDefault?5*n.minuteMs:(0,g.commandTimeoutMs)())}));t.whyInvalidFile=(0,l.shim)({name:"img.whyInvalidFile",cache:P,toKey:h.toNativePath_,impl:async e=>{const t=d.PosixFile.for(e);if(!await t.isFile()||!await t.isReadable())return t+" is not a readable file";if(await t.isEmptyOrMissing())return t+" is empty";try{const e=await(0,p.readMimeType)(t);if(null==e)throw new Error("Cannot validate, no mimetype");if((0,m.isVideoMimeType)(e))f.Settings.validateVideos.valueOrDefault&&(S().debug("validating "+t),await(0,b.validVideo_)(t));else{if(!e.startsWith("image/"))throw new Error("Unsupported mimetype "+(0,a.stringify)(e));if("image/jpeg"===e)f.Settings.validateJpegImages.valueOrDefault&&await(0,w.validJpeg_)(t);else if(f.Settings.validateRawImages.valueOrDefault)if((0,u.includesIgnoreCase)(f.Settings.validateMimetypeSkiplist.values,e))S().info("Skipping validation of "+t+": validateMimetypeSkiplist matches",{mime:e});else{const e=await new y.SharpReadable({src:t,skipEmbedded:!0}).sharp_();await e.raw().toBuffer()}}return""}catch(e){return(0,v.cleanValidationError)(String(e))}}})},19769(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cleanValidationError=h,t.isIgnorableValidationError=function(e){const t=h((0,l.errorToS)(e,{maxLen:512}));return c().tap({msg:"isIgnorableValidationError",level:"info",result:m().test(t)||!f().test(t),meta:{err:t,allow:m().test(t),block:f().test(t),validationErrorAllowlist:m().source,validationErrorBlocklist:f().source}})};const r=i(19851),s=i(40958),n=i(41400),a=i(50213),o=i(68852),l=i(98314),u=i(13797),c=(0,r.lazy)(()=>(0,a.mkLogger)("img.ValidationError")),d=[/Nothing was written into output file.*received no packets/i,/Error marking filters as finished/i,/^\s*at\s+/i];function h(e){return e.split("\n").filter(e=>!d.some(t=>t.test(e))).join(": ").trim()}const f=(0,r.lazy)(()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.FiltersSettings.validationErrorBlocklist.values),"i")),m=(0,r.lazy)(()=>(0,o.orRegExpPatterns)((0,s.compactBlanks)(u.FiltersSettings.validationErrorAllowlist.values),"i"));(0,n.later)(()=>{u.FiltersSettings.validationErrorBlocklist.watchLater(()=>f.unset()),u.FiltersSettings.validationErrorAllowlist.watchLater(()=>m.unset())})},66106(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._extractVideoFrame_=t.isVideoSupported=void 0,t.determineTranscodeStrategy=U,t.getFfmpegToolDetails_=q,t.extractVideoFrame_=async function(e){return await(0,t.isVideoSupported)()?P.PosixFile.for(await(0,t._extractVideoFrame_)((0,M.toNativePath_)(e))):void 0},t.__extractVideoFrame_=G,t.isVideoTranscodingSupported=K,t.needsTranscoding=async function(e){const t=W("needsTranscoding",e);if(!await K())return t.tap({msg:"videoTranscodingSupported is false",result:!1});const i=await(0,A.readRawTags)(e);if(null==i)return t.tap({msg:"Cannot transcode files that exiftool can't read",result:!1});const r=i.MIMEType;if(!(0,I.isVideoMimeType)(r))return t.tap({msg:"not transcoding (unsupported mimetype)",result:!1,meta:{mimetype:r}});const s=(0,D.extractDurationSec)(i);if(!(0,d.gt)(s,k.Settings.minVideoDurationSec.valueOrDefault))return t.tap({msg:"not transcoding (video duration is too short)",result:!1,meta:{duration:s}});const n=await H(e,i),a=await(0,z.ffprobeColorspace_)(e),o=U(n,a);return t.tap({level:"info",msg:"result",result:"none"!==o,meta:{strategy:o,pixFmt:a.pixFmt}})},t.transcode_=async function(e,t,i){if(!await K())return;const r=performance.now(),n=W("transcode",e);function a(){n.throwIfAborted_(),function(){for(const[e,t]of J)t.isResolved()&&J.delete(e)}();const i=J.get(t.nativePath);if(null!=i)return n.info("already transcoding",{src:e,dest:t,elapsedMs:i.elapsedMs}),n.awaitOrAbort(i).then(()=>t)}null!=i.halt&&(n.abortable=i.halt);{const e=a();if(e)return e}const o=await(0,x.readTags)(e);if(null==o)return n.throw("Cannot transcode files that exiftool can't read");const h=o.MIMEType;if(!(0,I.isVideoMimeType)(h))return void n.info("not transcoding (unsupported mimetype)",{mimetype:h});const f=(0,D.extractDurationSec)(o);if(!(0,d.gt)(f,k.Settings.minVideoDurationSec.valueOrDefault))return void n.info("not transcoding (video duration is too short)",{durationSec:f});const p=await H(e,o),g=await(0,z.ffprobeColorspace_)(e);let v=U(p,g);if("none"===v)return void n.info("no transcoding needed (already browser-compatible)",{strategy:v,pixFmt:g.pixFmt});const w=await e.size();if(!(0,c.gt0)(w))return n.throw("source is empty or cannot read");const S=(0,F.extractSizeInfoFromTags)(o);if(null==S)return n.throw("failed: missing video metadata",{sizeInfo:S,durationSec:f});const P=k.Settings.transcodeMaxDim.valueOrDefault;if((0,c.gt0)(P)&&null!=S.dimensions){const e=(0,_.max)([S.dimensions.height,S.dimensions.width]);(0,d.gt)(e,P)&&("remux"===v?(n.info("upgrading strategy from remux to video-only (transcodeMaxDim)",{strategy:v,maxDim:P,srcMaxDim:e}),v="video-only"):"audio-only"===v&&(n.info("upgrading strategy from audio-only to full (transcodeMaxDim)",{strategy:v,maxDim:P,srcMaxDim:e}),v="full"))}{const e=a();if(e)return e}const M=function(e,t){const i=W("extractVideoDimensions",e),r=k.Settings.minVideoDimension.valueOrDefault,s=t.ImageWidth;if(null!=s&&!(0,c.gte)(s,r))return i.throw("invalid width: "+s,{ignorable:!0});const n=t.ImageHeight;if(null!=n&&!(0,c.gte)(n,r))return i.throw("invalid height: "+n,{ignorable:!0});const a={width:s,height:n};return i.debug("extractVideoDimensions()",{file:e,result:a}),a}(e,o),C=o.dimensions,O=new u.Latch;return J.set(t.nativePath,O),await O.observe((async()=>{if(!0===i?.force)await t.unlink();else if(await async function(e,t){if(!await t.isNonEmptyFile())return V().tap({msg:"isTranscodeOf()",result:!1,meta:{reason:"dest does not exist",dest:t.nativePath}});const i=await(0,A.readRawTags)(t),r=await(0,A.readRawTags)(e),s=(0,D.extractDurationSec)(r),n=(0,D.extractDurationSec)(i);return V().tap({msg:"isTranscodeOf()",result:(0,c.closeTo)(s,n,1.5),meta:{srcDurationSec:s,destDurationSec:n,src:e.nativePath,dest:t.nativePath}})}(e,t))return void n.info("no-op, dest duration looks reasonable",{dest:t});await(0,y.time)({name:"img.video.transcode",meta:{src:e},p:async()=>{const a=Y(w,f,v);return await t.applyWip_({fn_:o=>async function(o){n.info("starting...",{destWip:o,strategy:v,colorspace:g});const u="remux"===v?"Remuxing video":"audio-only"===v?"Transcoding audio":"video-only"===v?"Transcoding video (copying audio)":"Transcoding video",h=new E.PullProgressObserver({path:e.nativePath,op:u},a,async()=>await t.clear().size()??0),p=i.stallTimeoutMs??k.Settings.ffmpegStallTimeoutMs.valueOrDefault,y=i.onProgress,w=1e3*(f??0),S=null!=y?e=>{const t=null!=e.outTimeMs&&(0,c.gt0)(w)?Math.min(100,Math.max(0,e.outTimeMs/w*100)):void 0;y({pct:t,etaMs:(0,L.ffmpegEtaMs)(e,w),speed:e.speed,frame:e.frame})}:void 0,P={src:e,dest:o,halt:n.abortable,strategy:v,colorspace:g,onProgress:S,stallTimeoutMs:p,...M},D=k.Settings.transcodeMaxDim.valueOrDefault,I=(0,_.max)([C.height,C.width]);if((0,c.gt0)(D)&&(0,d.gt)(I,D)){const e=(0,l.fitInside)(C,{width:D,height:D});null==e?n.warn("Cannot downsample transcoded video: fitInside() returned null",{input:C,maxPixels:D}):(P.width=(0,c.roundEven)(e.width),P.height=(0,c.roundEven)(e.height),n.info("Downsampling transcoded video",{original:C,output:e}))}try{const t=await h.observe((0,B.ffmpegTranscode_)(P));0!==t.code&&n.throw((0,s.compactBlanks)(["non-zero ffmpeg exit code "+t.code,t.stderr]).join(": ")),(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",type:"file",state:"note",details:"Transcode complete",elapsedMs:(0,m.roundMs)(performance.now()-r)})}catch(t){throw(0,T.syncReport)().onProgress({path:e.nativePath,from:"videoTranscode()",type:"file",state:"failed",details:"Transcode failed: "+(0,b.errorToS)(t),elapsedMs:(0,m.roundMs)(performance.now()-r)}),n.error("transcode failed",{error:t}),t}}(o),skipFsLock:!1,timeoutMs:0}),t}})})()),n.info("transcode complete",{src:e,dest:t,elapsedMs:O.elapsedMs}),t},t.guessExpectedSize=Y,t.validVideo_=async function(e){return(0,B.ffmpegValidVideo_)(e)};const r=i(19851),s=i(40958),n=i(38639),a=i(42659),o=i(41400),l=i(4188),u=i(56409),c=i(31586),d=i(34666),h=i(50213),f=i(7282),m=i(3685),p=i(79136),g=i(81168),y=i(56038),v=i(31562),b=i(98314),w=i(34102),S=i(88561),P=i(95696),M=i(17217),T=i(74128),_=i(70417),E=i(33847),k=i(28874),D=i(43207),I=i(16170),C=i(95141),A=i(38148),x=i(40538),F=i(1078),O=i(80985),R=i(63870),L=i(50827),N=i(89782),j=i(13940),B=i(34592),z=i(6327),V=(0,r.lazy)(()=>(0,h.mkLogger)("img.Video"));async function H(e,t){const i=null!=t.VideoCodec||null!=t.CompressorID,r=null!=t.AudioFormat;if(i&&r)return t;const s=await(0,z.ffprobe_)(e);if(null==s)return t;const n={...t};return i||null==s.VideoCodec||(n.VideoCodec=s.VideoCodec),r||null==s.AudioCodec||(n.AudioFormat=s.AudioCodec),V().debug("mergeCodecInfo()",{file:e.nativePath,original:{video:t.VideoCodec??t.CompressorID,audio:t.AudioFormat},merged:{video:n.VideoCodec??n.CompressorID,audio:n.AudioFormat}}),n}function U(e,t){const i=e.MIMEType,r=(0,s.compactBlanks)([e.VideoCodec,e.CompressorID,e.CompressorName]),n=(0,s.compactBlanks)([e.AudioFormat,e.AudioCodec]),a=r.some(e=>(0,g.includesIgnoreCase)(k.Settings.doNotTranscodeVideoCodecs.values,e)),o=n.some(e=>(0,g.includesIgnoreCase)(k.Settings.doNotTranscodeAudioCodecs.values,e)),l=null!=i&&(0,g.includesIgnoreCase)(k.Settings.browserCompatibleContainers.values,i),u=t?.pixFmt,c=!(0,z.isBrowserCompatiblePixFmt)(u),d=null!=t&&!(0,z.hasConsistentColorspaceMetadata)(t),h=a&&!c&&!d;return V().debug("determineTranscodeStrategy()",{mimetype:i,videoCodecs:r,audioCodecs:n,pixFmt:u,isBrowserCompatibleVideoCodec:a,pixFmtNeedsConversion:c,colorspaceNeedsCorrection:d,isBrowserCompatibleVideo:h,isBrowserCompatibleAudio:o,isBrowserCompatibleContainer:l}),h&&o&&l?"none":h&&o?"remux":!h&&o?"video-only":h&&!o?"audio-only":"full"}function W(e,t){return(0,h.mkLogger)("img/Video."+e+"("+(0,M.toNativePath_)(t)+")")}async function q(e){if((0,f.isProd)()&&(e=!0===e?.forceRefresh?{forceRefresh:!0}:void 0),!(0,n.isTrue)(e?.ignoreffmpeg))return!0===e?.forceRefresh&&(0,B.refreshFfmpegVersion_)(),await(0,B.ffmpegVersion_)()}t.isVideoSupported=(0,r.lazy)(async()=>{try{return!0===(await q())?.isSupportedVersion}catch(e){return V().warn("isVideoSupported",{error:e}),!1}}),(0,o.later)(()=>(0,w.ee)().on("clearCache",()=>t.isVideoSupported.unset()));const $=(0,r.lazy)(()=>new S.FileCache({name:"img.videoFrame",timeoutMs:a.minuteMs}));async function G(e,t){const i=W("extractVideoFrame",e),r=P.PosixFile.for(e);if(!await(0,B.isFFmpegSupported)())return i.throw("no video implementation");const s=P.PosixFile.forMaybe(t)??await(0,j.cachedImageFile_)(r,"frame",".jpg");i.debug("extractVideoFrame("+s+")");const n=await r.mtimeMs();if(null==n)return i.throw("null mtime for "+e);const o=await(0,A.readRawTags)(r);if(null==o)return i.throw("no tags");const l=(0,C.extractRotation)(o);i.debug("video orientation:"+l);const u=(0,F.extractSizeInfoFromTags)(o,l)?.dimensions,c=await s.stat(),d=null==c?void 0:await(0,N.dimensions)(s);if(null!=c&&c.mtimeMs>n&&null!=d&&(null==u||d.height===u.height&&d.width===u.width))return i.debug("prior dest, "+s+" seems reasonable",{srcDim:u,destDim:d}),s.nativePath;const h=(0,D.extractDurationSec)(o),f=Math.min(h??0,k.Settings.videoFrameAtSec.valueOrDefault);return i.info("extracted metadata",{startAtSec:f,duration:h}),await s.applyIfEmpty_({fn_:async e=>{const t={src:r,dest:e,startAtSec:f,...u};await(0,B.ffmpegFrame_)(t),!1===await(0,v.untilTrue)(async()=>i.tap({msg:"frame extracted?",result:await e.clear().isNonEmptyFile()}),{timeoutMs:5*a.secondMs,intervalMs:500})&&i.throw("ffmpeg failed to extract frame"),await(0,O.deleteAllTags_)(e,e)},timeoutMs:(0,R.commandTimeoutMs)()}),s.nativePath}async function K(){return k.Settings.transcodeVideos.valueOrDefault&&await(0,B.isFFmpegSupported)()}t._extractVideoFrame_=(0,p.shim)({name:"img.extractVideoFrame",cache:$,impl:e=>G(e)});const J=new Map;function Y(e,t,i){if("remux"===i||"audio-only"===i)return e;const r=Math.max(1e6,1e5*(t??10)),s=Math.round(.3*e);return Math.min(e,Math.max(r,s))}},34592(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffmpegVersionDescription=void 0,t.ffmpegNativePath=E,t.ffmpegVersion_=async function(){return await D.prior()??D.refresh()},t.refreshFfmpegVersion_=function(){D.unset()},t.isFFmpegSupported=async function(){try{return!0===(await D()).isSupportedVersion}catch(e){return _().warn("isFFmpegSupported failed",{err:e}),!1}},t.ffmpegFrame_=async function(e){if(await e.dest.parent().mkdirp_(),await(0,f.stdoutResult_)(await E(),(0,r.compact)(["-loglevel","error","-i",e.src.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...(0,d.mapGte0f)(e.startAtSec,e=>["-ss",e.toFixed(1)])??[],"-vframes","1","-y",e.dest.nativePath]),{timerName:"proc.ffmpeg",timeoutMs:a.minuteMs,cleanError:M.cleanValidationError,isIgnorableError:M.isIgnorableValidationError}),!await(0,h.untilTrue)(()=>e.dest.clear().isNonEmptyFile(),{timeoutMs:3*a.secondMs}))throw new Error("Failed to extract frame for "+e.src)},t.buildColorspaceArgs=L,t.avcArgs=N,t.buildTranscodeArgs=z,t.ffmpegTranscode_=async function e(t){const i=t.strategy??"full";try{await t.dest.parent().mkdirp_();const e=z(i,t,t.colorspace);_().info("ffmpegTranscode_()",{strategy:i,colorspace:t.colorspace,src:t.src.nativePath,dest:t.dest.nativePath});const s=t.stallTimeoutMs,n=null!=t.onProgress||(0,l.gt0)(s),a=n?["-progress","pipe:1","-nostats"]:[],o=n?(0,P.newFfmpegProgressState)():void 0,u=(0,l.gt0)(s)?new P.FfmpegStallWatcher({timeoutMs:s,onStall:()=>{_().warn("ffmpegTranscode_() stall detected; aborting via halt",{src:t.src.nativePath,dest:t.dest.nativePath,stallTimeoutMs:s}),t.halt.abort("ffmpeg stalled: no progress for "+s+"ms")}}):void 0,c=n?e=>{if(null==o)return;const i=(0,P.feedFfmpegProgress)(o,e);for(const e of i)t.onProgress?.(e),u?.onTick(e)}:void 0;u?.arm();try{return await(0,f.stdoutResult_)(await E(),(0,r.compactBlanks)(["-loglevel","error","-i",t.src.nativePath,...e,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),...a,"-y",t.dest.nativePath]),{timerName:"proc.ffmpeg",halt:t.halt,timeoutMs:t.timeoutMs??0,cleanError:M.cleanValidationError,isIgnorableError:M.isIgnorableValidationError,onStdoutChunk:c})}finally{u?.disarm()}}catch(r){_().warn("ffmpegTranscode_() failed",{args:t,strategy:i,error:r}),await(0,y.unlink)(t.dest,"debug");const s=(0,m.errorToS)(r,{maxLen:1024});if(!(0,n.isDisabled)(t.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault)&&/hwaccel.*error/i.test(s))return _().warn("ffmpegTranscode_() failed: bad -hwaccel arg? Disabling hwaccel and retrying...",{args:t,error:r}),e({...t,ffmpegHwaccel:"disabled"});throw r}},t.ffmpegValidVideo_=async function(e){return _().tap({msg:"ffmpegValidVideo",meta:{src:e.nativePath},result:await(0,f.stdoutResult_)(await E(),["-xerror","-err_detect",v.Settings.ffmpegErrDetect.valueOrDefault,"-v","error","-nostats","-i",e.nativePath,"-threads",String(v.Settings.ffmpegThreads.valueOrDefault),"-f","null","-"],{timerName:"proc.ffmpeg",timeoutMs:0,cleanError:M.cleanValidationError,isIgnorableError:M.isIgnorableValidationError,ignoreExitCode:!1,quiet:!1})})};const r=i(40958),s=i(22573),n=i(38639),a=i(42659),o=i(41400),l=i(31586),u=i(19851),c=i(50213),d=i(97352),h=i(31562),f=i(84777),m=i(98314),p=i(34102),g=i(8103),y=i(84258),v=i(28874),b=i(76280),w=i(63335),S=i(63870),P=i(50827),M=i(19769),T=i(6327),_=(0,u.lazy)(()=>(0,c.mkLogger)("img.ffmpeg"));function E(){return(0,g.pathTo)({tool:"ffmpeg"})}const k=/ffmpeg version n?(?<version>\S+)/i,D=(0,u.lazy)(async()=>{const e=await E();if(null==e)return{desc:"FFmpeg",version:"(not found)",isSupportedVersion:!1};const t=await(0,f.stdoutResult_)(e,["-version"],{timerName:"proc.ffmpeg",timeoutMs:(0,S.commandTimeoutMs)(),ignoreStderr:!0}),i=k.exec(t.result)?.[1];return _().debug("ffmpegVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{desc:"FFmpeg",path:e,version:i??"(unknown)",isSupportedVersion:(0,b.semVerSatisfies)(i,">=3.2")}});function I(){D.unset(),t.ffmpegVersionDescription.unset(),T.ffprobeVersion_.unset(),T.isFFprobeAvailable.unset()}function C(e){const t=e?.ffmpegHwaccel??v.Settings.ffmpegHwaccel.valueOrDefault;return(0,s.blank)(t)||(0,n.isDisabled)(t)?[]:["-hwaccel",t]}t.ffmpegVersionDescription=(0,u.lazy)(async()=>{try{const e=await D();return(0,w.ver)(e.version)}catch{return"(error detecting version)"}}),(0,o.later)(()=>{(0,p.ee)().on("clearCache",I),(0,p.ee)().on("clearToolCache",I)});const A="1",x="1",F="1",O="colorspace=all=bt709:iall=bt601-6-625,format=yuv420p",R="format=yuv420p";function L(e){const t=(0,c.mkLogger)("ffmpeg.buildColorspaceArgs");if((0,T.isHdrColorspace)(e)){t.info("HDR detected - preserving source colorspace",{colorspace:e});const i="arib-std-b67"===e.colorTransfer?"18":"16";return["-color_range","pc"===e.colorRange?"2":A,"-colorspace","9","-color_primaries","9","-color_trc",i]}if((0,T.isBt709Colorspace)(e)){const i=!(0,T.isBrowserCompatiblePixFmt)(e.pixFmt);t.info("BT.709 detected",{colorspace:e,needsPixFmtConversion:i});const r=["-color_range",A,"-colorspace",x,"-color_primaries",x,"-color_trc",F];return i?["-vf",R,...r]:r}if((0,T.isBt601Colorspace)(e))return t.info("BT.601 detected - converting to BT.709",{colorspace:e}),["-vf",O,"-color_range",A,"-colorspace",x,"-color_primaries",x,"-color_trc",F];if((e.height??0)>=720){const i=!(0,T.isBrowserCompatiblePixFmt)(e.pixFmt);t.info("Unknown colorspace, HD resolution - assuming BT.709",{colorspace:e,needsPixFmtConversion:i});const r=["-color_range",A,"-colorspace",x,"-color_primaries",x,"-color_trc",F];return i?["-vf",R,...r]:r}return t.info("Unknown colorspace, SD resolution - converting BT.601→BT.709",{colorspace:e}),["-vf",O,"-color_range",A,"-colorspace",x,"-color_primaries",x,"-color_trc",F]}function N(e){const t=v.Settings.ffmpegAvcTranscodeArgs.values,i=[];for(let e=0;e<t.length;e++){const r=t[e];"-c:v"!==r?i.push(r):e++}const r=v.Settings.transcodeVideoCodec.valueOrDefault;i.push("-c:v",r),"libx265"===r&&i.push("-tag:v","hvc1"),i.push("-preset",v.Settings.ffmpegPreset.valueOrDefault);const s=v.Settings.transcodeCrf.valueOrDefault;if((0,l.gt0)(s)&&i.push("-crf",String(s)),!(0,l.gt0)(e.width)||!(0,l.gt0)(e.height)||!(0,l.gt0)(v.Settings.transcodeMaxDim.valueOrDefault))return i;const n=(0,l.roundEven)(e.width),a=(0,l.roundEven)(e.height);return i.unshift("-s",n+"x"+a),i}function j(e){const t=v.Settings.transcodeFrameRate.valueOrDefault;return!(0,l.gt0)(t)||(0,l.lte)(e?.fps,t)?[]:["-r",String(Math.round(t))]}function B(e,t){let i,r;const s=[],n=[];for(let t=0;t<e.length;t++)"-vf"===e[t]&&t+1<e.length?(i=e[t+1],t++):s.push(e[t]);for(let e=0;e<t.length;e++)"-vf"===t[e]&&e+1<t.length?(r=t[e+1],e++):n.push(t[e]);const a=[...s,...n];return null!=i&&null!=r?a.push("-vf",`${i},${r}`):null!=i?a.push("-vf",i):null!=r&&a.push("-vf",r),a}function z(e,t,i){const r=null!=i?L(i):[];switch(e){case"none":throw new Error("buildTranscodeArgs called with strategy 'none'");case"remux":return["-c","copy","-movflags","+faststart"];case"video-only":return B([...N(t).filter((e,t,i)=>!("-c:a"===e||"-c:a"===i[t-1])),"-c:a","copy",...j(t),...C(t)],r);case"audio-only":return["-c:v","copy","-c:a","aac","-movflags","+faststart"];default:return B([...N(t),...j(t),...C(t)],r)}}},6327(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ffprobeCache=t.FfprobeFields=t.ffprobeVersion_=t.isFFprobeAvailable=void 0,t.ffprobeNativePath=w,t.getFFprobeToolDetails_=async function(){return await t.ffprobeVersion_.prior()??t.ffprobeVersion_.refresh()},t.isHdrColorspace=P,t.isBt601Colorspace=M,t.isBt709Colorspace=T,t.extractVideoColorspace=_,t.isBrowserCompatiblePixFmt=function(e){return null==e||E.has(e)},t.hasConsistentColorspaceMetadata=function(e){if(P(e))return!0;if(null==e.colorSpace&&null==e.colorPrimaries&&null==e.colorTransfer)return!1;if(T(e))return"bt709"===e.colorTransfer||null==e.colorTransfer;if(M(e)){const t=["bt601","bt470bg","smpte170m","pal","ntsc"];return null==e.colorTransfer||t.includes(e.colorTransfer)}return!0},t.ffprobeResultToTags=x,t.ffprobe_=async function(e){return(0,t.ffprobeCache)().getOrSet((0,p.toNativePath_)(e),async()=>b().tap({msg:"ffprobe()",result:x(await O(e)??{streams:[],format:{}}),meta:{f:e}}))},t.ffprobeColorspace_=async function(e){const t=_(await O(e));return b().debug("ffprobeColorspace()",{f:e,colorspace:t}),t};const r=i(42659),s=i(45599),n=i(98553),a=i(31586),o=i(21605),l=i(48884),u=i(19851),c=i(50213),d=i(97352),h=i(84777),f=i(88561),m=i(8103),p=i(17217),g=i(76280),y=i(63870),v=i(19769),b=(0,s.defer)(()=>(0,c.mkLogger)("img.ffprobe"));function w(){return(0,m.pathTo)({tool:"ffprobe"})}t.isFFprobeAvailable=(0,u.lazy)(async()=>{try{const e=await(0,t.ffprobeVersion_)();return!0===e?.isSupportedVersion}catch{return!1}});const S=/ffprobe version n?(?<version>\S+)/i;function P(e){const t="smpte2084"===e.colorTransfer||"arib-std-b67"===e.colorTransfer,i="bt2020"===e.colorPrimaries||"bt2020nc"===e.colorSpace;return t||i}function M(e){const t=["bt601","bt470bg","smpte170m","pal","ntsc"];return t.includes(e.colorSpace??"")||t.includes(e.colorPrimaries??"")}function T(e){return"bt709"===e.colorSpace||"bt709"===e.colorPrimaries}function _(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};const t=e.streams.find(e=>"video"===e?.codec_type);return{colorRange:t?.color_range,colorSpace:t?.color_space??void 0,colorTransfer:t?.color_transfer??void 0,colorPrimaries:t?.color_primaries??void 0,height:t?.height,pixFmt:t?.pix_fmt??void 0}}t.ffprobeVersion_=(0,u.lazy)(async()=>{const e=await w();if(null==e)return;const t=await(0,h.stdoutResult_)(e,["-version"],{timerName:"proc.ffprobe",timeoutMs:(0,y.commandTimeoutMs)(),ignoreStderr:!0}),i=S.exec(t.result)?.[1];return b().debug("ffprobeVersion",{version:i,code:t.code,stdout:t.result.split("\n",1)[0]}),{desc:"ffprobe",path:e,version:i??"(unknown)",isSupportedVersion:(0,g.semVerSatisfies)(i,">=3.2")}});const E=new Set(["yuv420p","yuv420p10le"]);t.FfprobeFields=["AspectRatio","AudioChannels","AudioCodec","AudioSampleRate","Duration","FrameRate","ImageHeight","ImageWidth","Rotation","VideoCodec"];const k={h264:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01",mjpeg:"mjpg",mpeg4:"mp4v",mpeg2video:"mp2v",prores:"apcn"},D={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"},I={HDMV:"avc1",HDPR:"avc1"};function C(e){if(null==e)return;const t=e.codec_tag_string;if(null!=t&&t in I)return I[t];if(null!=t&&t.length>0&&!t.includes("[0]"))return t;const i=e.codec_name?.toLowerCase();return null!=i?k[i]??i:void 0}function A(e){if(null==e)return;const t=e.codec_tag_string;if(null!=t&&t.length>0&&!t.includes("[0]"))return t;const i=e.codec_name?.toLowerCase();return null!=i?D[i]??i:void 0}function x(e){if(!Array.isArray(e?.streams))return{};const t=e.streams.find(e=>"video"===e?.codec_type),i=e.streams.find(e=>"audio"===e?.codec_type);return{AspectRatio:t?.display_aspect_ratio,AudioChannels:i?.channels,AudioCodec:A(i),AudioSampleRate:(0,a.toFloat)(i?.sample_rate),Duration:(0,a.toFloat)(t?.duration),FrameRate:(0,d.extractFraction)(t?.avg_frame_rate),ImageHeight:(0,a.toInt)(t?.height),ImageWidth:(0,a.toInt)(t?.width),Rotation:(0,l.first)(t?.side_data_list,e=>(0,o.normalizeRotation)(e?.rotation,!0))??0,VideoCodec:C(t)}}const F=(0,u.lazy)(()=>new f.FileCache({name:"img.ffprobe.raw",maxSize:256,timeoutMs:r.minuteMs}));async function O(e){return F().getOrSet((0,p.toNativePath_)(e),async()=>{const t=await w();if(null==t)return;const i=await(0,h.stdout_)(t,["-v","quiet","-print_format","json","-show_format","-show_streams","-show_entries","stream_side_data=rotation",(0,p.toNativePath_)(e)],{timerName:"proc.ffprobe",timeoutMs:(0,y.commandTimeoutMs)(),isIgnorableError:v.isIgnorableValidationError});return(0,n.parseJSON_)(i)})}t.ffprobeCache=(0,u.lazy)(()=>new f.FileCache({name:"img.ffprobe",maxSize:256,timeoutMs:r.minuteMs}))},51210(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.jpegtranVersion_=async function(){const e=await(0,o.stdoutResult_)(await(0,c.jpegtranNativePath_)(),["-version"],{timerName:"proc.jpegtran",quiet:!0,timeoutMs:(0,f.commandTimeoutMs)(),isIgnorableError:()=>!0});return(e.stderr??e.result).replace(/^libjpeg-turbo version/,"").trim()},t.validJpeg_=async function(e){if(!h.Settings.validateJpegImages.valueOrDefault)return;const t=u.PosixFile.for(e),i=await(0,c.jpegtranNativePath_)();try{await(0,o.stdoutResult_)(i,["-outfile",p,t.nativePath],{timerName:"proc.jpegtran",timeoutMs:(0,f.commandTimeoutMs)(),cleanError:m.cleanValidationError,isIgnorableError:m.isIgnorableValidationError,ignoreExitCode:!1})}catch(e){throw g().warn("validJpeg caught invalid file",{file:t,error:e}),new l.WrappedError("Invalid JPEG: "+t,{cause:e,path:t.nativePath,doNotSend:!0,fatal:!1,retriable:!1})}},t.rotateInPlace_=async function(e,t){g().info("rotateInPlace("+e+")",t),await e.applyWip_({fn_:i=>y(e,i,t),skipFsLock:!1,minSizeBytes:512,timeoutMs:r.minuteMs})},t.rotate_=y;const r=i(42659),s=i(21605),n=i(19851),a=i(50213),o=i(84777),l=i(57159),u=i(95696),c=i(89966),d=i(43334),h=i(28874),f=i(63870),m=i(19769),p=d.isWin?"NUL":"/dev/null",g=(0,n.lazy)(()=>(0,a.mkLogger)("img.jpegtran"));async function y(e,t,i){const n=await(0,c.jpegtranNativePath_)();if(!(0,s.isRotation)(i))throw new Error("refusing to rotate("+e+", "+i+")");await(0,o.stdout_)(n,["-copy","all","-trim","-rotate",i.toFixed(0),"-outfile",t.nativePath,e.nativePath],{timerName:"proc.jpegtran",timeoutMs:r.minuteMs}),t.clear()}},19350(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLibrawFile=async function(e){try{return(0,g.isLibrawMimeType)(await(0,y.readMimeType)(e))}catch(t){return P().warn("librawSupported("+e+"): failed to read filetype",t),!1}},t.raw2tiff_=async function(e){return(0,b.readableToFile_)({src:e,desc:"dcraw",suffix:".tiff",f:t=>k(e,t)})},t.dcraw_emu_=k;const r=i(19851),s=i(40958),n=i(33374),a=i(12168),o=i(23541),l=i(54993),u=i(50213),c=i(84777),d=i(98314),h=i(38835),f=i(57159),m=i(89966),p=i(28874),g=i(16170),y=i(54979),v=i(89782),b=i(13940),w=i(42725),S=i(19769),P=(0,r.lazy)(()=>(0,u.mkLogger)("img.libraw")),M=["-T"],T=["-Z","-"],_=["-o","1"],E=["-t","0","-j"];async function k(e,t){const i=await(0,v.dimensions)(e);if(null==i)return P().throw("Cannot decode "+e+": no EXIF dimensions."+h.DoNotSendErrorFlag+h.NonRetriableErrorFlag);const r=w.ImageSize.largestFit().outputSize(i),u=[];null!=r&&4*(0,n.dmegapixels)(r)<(0,n.dmegapixels)(i)&&(P().debug("Large original source: using -h"),u.push("-h"));const g=await(0,m.dcrawEmuNativePath_)(),y=[...M,...T,..._,...u,...E,...p.Settings.dcrawEmuArgs.values,e.nativePath],b={encoding:"buffer",timeout:p.Settings.taskTimeoutMs.valueOrDefault,maxBuffer:250*a.MB};P().debug("dcraw_emu()",{cmd:g,args:y,opts:b});const k=(0,c.execFile)(g,y,void 0,b),D=[];function I(t){const i=(0,o.isError)(t)?(0,d.errorToS)(t):(0,l.toS)(t);if((0,S.isIgnorableValidationError)(i))P().info("dcraw_emu(): warning",{file:e,msg:i});else{P().warn("dcraw_emu(): error",{file:e,msg:i});const r=(0,o.isError)(t)?t:(0,f.toWrappedError)(i,{fatal:!1});D.push(r)}}if(k.on("error",I),k.stderr.on("data",I),await t.writeStream_(k.stdout),(0,s.isNotEmpty)(D))throw new f.WrappedError("Failed to convert RAW image "+e,{causes:D,path:e.nativePath});(0,c.endProcess)(k)}},8081(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pHash=async function(e){const t=await u(e.clone().greyscale()).raw().toBuffer();return(0,r.b64encodeBitsFixedWidth)(l(t),64)},t.pHashCIELAB=async function(e){const{data:t}=await(0,o.sharpToColorspaceBuffer)(u(e.clone()),"char");return(0,r.b64encodeBitsFixedWidth)((0,n.deinterleaveTypedArray)(t,3).flatMap(l),192)};const r=i(23624),s=i(84427),n=i(90400),a=i(90354),o=i(5733);function l(e){const t=Float64Array.from(e),i=(0,s.dct2d)(t,32),r=new Float64Array(64);let n=0;for(let e=0;e<8;e++)for(let t=0;t<8;t++)r[n++]=i[32*e+t];const a=[...r].sort((e,t)=>e-t),o=a[Math.floor(.2*a.length)],l=a[Math.floor(.4*a.length)],u=a[Math.floor(.6*a.length)],c=a[Math.floor(.8*a.length)],d=new Array(64);for(let e=0;e<r.length;e++){const t=r[e];d[e]=t<=o?0:t<=l?1:t<=u?2:t<=c?3:4}const h=new Array(64);for(let e=0;e<r.length;e++){const t=e<r.length/2?2:2.5;h[e]=d[e]>=t?1:0}return h}function u(e){return(0,o.sharpResize)(e,{width:32,height:32,...a.ImageHashResizeOpts})}},65891(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DIM=void 0,t.rHash=async function(e){const t=l(e.clone().greyscale()),i=o(await t.raw().toBuffer());return(0,r.b64encodeBitsFixedWidth)(i,64)},t.rHashCIELAB=async function(e){const{data:t}=await(0,a.sharpToColorspaceBuffer)(l(e.clone()),"char");return(0,r.b64encodeBitsFixedWidth)((0,s.deinterleaveTypedArray)(t,3).flatMap(o),192)};const r=i(23624),s=i(90400),n=i(90354),a=i(5733);function o(e){const i=new Array(t.DIM*t.DIM);let r=0;const s=t.DIM+2;for(let n=1;n<=t.DIM;n++)for(let a=1;a<=t.DIM;a++){const t=n*s+a,o=(e[t-1]+e[t+1]+e[t-s]+e[t+s])/4;i[r++]=o>e[t]?1:0}return i}function l(e){return(0,a.sharpResize)(e,{width:t.DIM+2,height:t.DIM+2,...n.ImageHashResizeOpts})}t.DIM=8},36192(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sipsPath=void 0,t.sips2jpeg_=async function(e){return(0,l.withImageCache_)(e,"heif",".jpeg",t=>(0,s.stdoutResult_)("sips",["-s","format","jpeg","-s","formatOptions",String(o.Settings.previewQuality.valueOrDefault),e.nativePath,"--out",t.base],{timerName:"proc.sips",cwd:t.dir,timeoutMs:o.Settings.taskTimeoutMs.valueOrDefault}))};const r=i(19851),s=i(84777),n=i(8103),a=i(43334),o=i(28874),l=i(13940);t.sipsPath=(0,r.lazy)(async()=>a.isMac?(0,n.pathTo)({tool:"sips"}):void 0)},34264(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.wHash=async function(e){return(0,n.b64encodeBigIntFixedWidth)(await async function(e){return c(await(0,l.sharpResize)(e.greyscale(),{width:u,height:u,fit:s.default.fit.fill,kernel:s.default.kernel.nearest}).raw().toBuffer())}(e),64)},t.wHashCIELAB=async function(e){const{data:t}=await(0,l.sharpToColorspaceBuffer)((0,l.sharpResize)(e,{width:u,height:u,...o.ImageHashResizeOpts}),"char"),[i,r,s]=(0,a.deinterleaveTypedArray)(t,3),d=c(i),h=c(r),f=c(s);return(0,n.b64encodeBigIntFixedWidth)(d<<128n|h<<64n|f,192)};const s=r(i(9288)),n=i(23624),a=i(90400),o=i(90354),l=i(5733),u=32;function c(e){let t=Float64Array.from(e);{const e=t.reduce((e,t)=>e+t,0)/t.length;for(let i=0;i<t.length;i++)t[i]-=e}let i=u;for(;i>8;){const e=i>>1,r=new Float64Array(e*e);for(let s=0;s<e;s++)for(let n=0;n<e;n++){const a=2*s*i+2*n,o=t[a],l=t[a+1],u=t[a+i],c=t[a+i+1];r[s*e+n]=.25*(o+l+u+c)}t=r,i=e}const r=Array.from(t),s=[...r].sort((e,t)=>e-t)[r.length>>1];let n=0n;for(const e of r)n=n<<1n|(e>s?1n:0n);return n}},38337(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InstallState=void 0;const r=i(74310),s=(0,i(50213).mkLogger)("install.InstallState");class n{static#jt;static instance(){return this.#jt??=new n}#Bt="idle";#zt;#Vt;#Ht;#Ut;#W;#R=new r.BoundedList(200);#De;constructor(){}get phase(){return this.#Bt}currentRun(){return this.#De}snapshot(){return{phase:this.#Bt,toolLabel:this.#zt,statusLabel:this.#Vt,startedAt:this.#Ht,terminalAt:this.#Ut,error:this.#W,log:this.#R.toA()}}setStatusLabel(e){const t=e.trim();this.#Vt=0===t.length?void 0:t}appendLog(e){const t=e.replace(/\r?\n$/,"");0!==t.length&&this.#R.push(t)}run(e,t){if("running"===this.#Bt)throw new Error(`Install already in progress (${this.#zt})`);const i=this.#Wt(e,t);return this.#De=i,i.finally(()=>{this.#De===i&&(this.#De=void 0)})}async#Wt(e,t){this.#Bt="running",this.#zt=e,this.#Vt=void 0,this.#Ht=Date.now(),this.#Ut=void 0,this.#W=void 0,this.#R.clear(),s.info("Install started",{tool:e});try{await t(),this.#Bt="succeeded",this.#Ut=Date.now(),s.info("Install succeeded",{tool:e})}catch(t){throw this.#Bt="failed",this.#Ut=Date.now(),this.#W=t instanceof Error?t.message:String(t),s.warn("Install failed",{tool:e,error:this.#W}),t}}reset(){this.#Bt="idle",this.#zt=void 0,this.#Vt=void 0,this.#Ht=void 0,this.#Ut=void 0,this.#W=void 0,this.#R.clear(),this.#De=void 0}}t.InstallState=n},97490(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseJsonRpcClient=void 0;const r=i(77030),s=i(22573),n=i(45599),a=i(54900),o=i(98553),l=i(56409),u=i(31586),c=i(85556),d=i(50213),h=i(65211),f=i(25764),m=i(38836),p=i(12084),g=i(21027),y=i(11924),v=(0,n.defer)(()=>(0,d.mkLogger)("jsonrpc.BaseJsonRpcClient"));class b extends m.EndableWrapper{options;#qt;pending=new Map;constructor(e,t){super(e,()=>this.close(),f.EndableRanks.service),this.options=t}isHealthy(){return null!=this.#qt&&!this.#qt.destroyed&&(this.#qt.writable??!1)}close(e){e??=new Error("closed"),(0,g.disposeStream)(this.#qt);for(const t of this.pending.values())t.reject(e);this.#qt=void 0}async connect(){const e="stream"in this.options?this.options.stream:void 0,t=e??new r.Socket,i="port"in this.options?this.options.port:void 0;if(null==e&&!(0,u.gt0)(i))return this.logger.throw("connect(): no stream or port",this.options);const s=new l.Latch;t.once("error",e=>{this.close(e),s.reject(e)}),t.once("close",()=>{this.close()}),t.on("data",e=>{for(const t of e.toString().split("\n"))0!==t.length&&this.#$t(t)}),null==e&&(0,p.isTcpSocketConnectOpts)(this.options)&&t instanceof r.Socket&&t.connect(this.options,()=>s.resolve()),await s.promise,this.#qt=t}async maybeReconnect(){return null!=this.#qt&&this.isHealthy()||await this.connect(),this.#qt}request(e,t,i=6e4){const r={id:(0,h.uid)(),method:e,params:t},s=new a.Deferred,n=new c.TimeoutError(`RPC timeout: ${String(e)}`);let l;return i>0&&(l=setTimeout(()=>{s.isPending()&&(this.logger.warn("request() timeout",{method:e,timeoutMs:i}),s.reject(n))},i),l.unref()),this.pending.set(r.id,s),this.maybeReconnect().then(e=>(0,g.writeAsync)(e,(0,o.stringify)(r)+"\n")).catch(e=>s.reject(e)),s.promise.finally(()=>{null!=l&&clearTimeout(l),this.pending.delete(r.id)})}#$t(e){try{this.logger.debug("#onMessage()",{data:e});const t=(0,o.parseJSON)(e);if(!(0,y.isJsonRpcResponse)(t))return void this.logger.error("#onMessage(): invalid payload",{response:t,data:e});this.logger.debug("#onMessage()",{response:t});const i=this.pending.get(t.id);if(!i)return void v().warn("Received response for unknown or previous request",{response:t});(0,s.blank)(t.error)?i.resolve(t):(v().warn("Response was rejected",{response:t}),i.reject(new Error(t.error)))}catch(t){v().error("Failed to parse response",{error:t,data:e})}}async ready_(){await this.connect()}}t.BaseJsonRpcClient=b},11924(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isJsonRpcRequest=function(e){return"object"==typeof e&&null!==e&&(void 0!==e.method||(n().warn("Invalid JSON-RPC request",{value:e}),!1))},t.isJsonRpcResponse=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return("string"==typeof t.id||void 0===t.id)&&("result"in t||"error"in t)};const r=i(45599),s=i(50213),n=(0,r.defer)(()=>(0,s.mkLogger)("jsonrpc.JsonRpcApi"))},71706(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.j=function(e){return JSON.parse((0,r.brotliDecompressSync)(Buffer.from(e,"base64")).toString("utf8"))};const r=i(38522)},83950(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.L=void 0;const r=i(79114),s=i(40958),n=i(42659),a=i(34666),o=i(48884),l=i(97352),u=i(81674),c=i(84194);t.L=class{s;_l;_sids;static for(e){return new this(e.str,e.l,e.sids,e.src)}meta;constructor(e,t,i,r){this.s=e,this._l=t,this._sids=i,this.meta={src:r}}get l(){return this._l}get ok(){if(null==this._l)return!1;const e=(0,o.intersection)(this._sids,this._l.uids),t=(0,s.uniq)(e.map(c.getScheme)),i=(0,s.compact)(t.map(e=>(0,c.prefix2scheme)(e))),r=i.length>=this._l.mat,a=(0,l.within)(this._l.iat?.getTime(),this._l.exp?.getTime()+n.dayMs,Date.now());return this.meta[(0,u.k)().o]=a,this.meta[(0,u.k)().u]=r,this.meta[(0,u.k)().m]=i,a&&r}cmpVal(){return[this.ok,-(r.S.indexOf(this.l?.[(0,u.k)().T])??0),this.l?.exp?.getTime()??1,this.meta.matchedSchemes]}cmp(e){return(0,a.cmp)(this.cmpVal(),e.cmpVal())}}},81674(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.m=t.k=void 0,t.v_=O,t.v=R,t.vok=async function(e,t,i){if((0,s.blank)(e))return;const r=await R(e,t,i);return(0,n.isTrue)(r?.ok)&&r instanceof I.L?r:void 0},t.b=N,t.t=j,t.l=async function(){try{return await j()===(0,t.k)().f}catch{return!0}},t.p=async function(){try{return await j()===(0,t.k)().g}catch{return!1}};const r=i(76790),s=i(22573),n=i(38639),a=i(45599),o=i(41400),l=i(96249),u=i(55835),c=i(31586),d=i(51926),h=i(79114),f=i(23541),m=i(59455),p=i(54993),g=i(72993),y=i(19851),v=i(50213),b=i(56519),w=i(76596),S=i(46292),P=i(87290),M=i(77740),T=i(96706),_=i(34102),E=i(83278),k=i(28874),D=i(71706),I=i(83950),C=i(72042),A=i(33603),x=i(48132);t.k=(0,y.rolazy)(()=>(0,D.j)("G1UBABwHdkz4hUIkFCfPXW5LlfvrWKSr9W3AIyIhUiw68NDfvLLHVop/bGoNnRxQlnqi2TZp0IJaX+lUHBoi+vMy2LMNpHCv8xVkUGsmQsgB8ldHoDqJeUQzbdybwikWVRs2KSWKjE5LnuqhTNSp3gTLhNfE9EqBLeaXP+UM9YqTGSXcyrcL03rIPMDAVyJplSZC0xoUgguOYJKvrcYFbNArN7BrQsnnsJ4hMtcSxOTxxRdxzETtL93qa3vjDw=="));const F=(0,a.defer)(()=>(0,v.mkLogger)((0,t.k)().l));async function O(e){const i=await(0,C.V)((0,d.ensurePrefix)((0,p.toS)(e).trim(),(0,t.k)().p)),r=(0,w.utcIsoToTs)(i[(0,t.k)().i]);if(null==r)throw new Error("bad "+(0,t.k)().i+": "+i[(0,t.k)().i]+" ("+e+")");const s=(0,w.utcIsoToTs)(i[(0,t.k)().r]);if(null==s)throw new Error("bad "+(0,t.k)().r+": "+i[(0,t.k)().r]+" ("+e+")");return(0,M.getDevEnvFlag)((0,t.k)().y)&&(i[(0,t.k)().t]=!0),i[(0,t.k)().a]=(0,c.toGte0)(i[(0,t.k)().a])??2,i[(0,t.k)().i]=new Date(r),i[(0,t.k)().r]=new Date(s),i[(0,t.k)().b]=(0,p.toS)(i.uids).split(","),i}async function R(e,i,r,n){try{return(0,s.blank)(e)||e===(0,t.k)().f?void 0:I.L.for({str:e,l:await O(e),sids:null!=n?n:await(0,A.sids)({timeoutMs:r}),src:i})}catch(i){return F().tap({msg:(0,t.k)().v,result:{s:e,ok:!1,meta:{error:i}}})}}async function L(e,t){const i=[],r=await(0,b.sortByAsync)({iter:e?.childFiles(),f:e=>e.mtimeMs()});for(const e of r.reverse()){const r=await R((0,m.toA)(await e.readLines()).map(e=>e.trim()).join(""),e.nativePath,x.UserTimeoutMs,t);null!=r&&i.push(r)}return i}async function N(){const e=await(0,t.m)();return e[0]?.ok?e[0]:void 0}async function j(){return(await N())?.l?.[(0,t.k)().T]??(0,t.k)().f}t.m=(0,y.rolazy)(async()=>{if((0,T.isEnvTrue)((0,t.k)().x)||(0,T.getEnv)((0,t.k)().x)===(0,t.k)().f)return[];const e=await(0,A.sids)({timeoutMs:x.UserTimeoutMs}),i=(0,u.map)((0,S.configDir)(),e=>E.BaseFile.for(e)),s=(n=(0,l.flatten)((await(0,b.someOrTimeout)([()=>function(e){return R(k.Settings[(0,t.k)().L].value,"Settings",x.UserTimeoutMs,e)}(e),()=>L(i?.join((0,t.k)().d),e),()=>L((0,P.libraryDataDirPosixFile)()?.join((0,t.k)().d),e),()=>L(i?.sibling((0,g.AppName)().toLowerCase()).join((0,t.k)().d),e)],{timeoutMs:x.UserTimeoutMs})).filter(e=>!(e instanceof Error))),(0,r.sortBy)(n.filter(e=>null!=e&&((0,f.isError)(e)&&F().warn((0,t.k)().d+": ",e),null!=e&&!(0,f.isError)(e)&&null!=e?.l)),e=>[!e.ok,h.S.indexOf(e.l?.[(0,t.k)().T])??h.S.length+1,-(e.l?.exp?.getTime()??1)]));var n;return F().tap({msg:(0,t.k)().d+"()",result:s})}),(0,o.later)(()=>{(0,_.ee)().on("clearCache",()=>t.m.unset()),(0,_.ee)().on((0,t.k)().c,()=>t.m.unset())})},72042(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.l=void 0,t.V=function(e){const i=(0,r.decode)(e).payload;if(null==i)throw new Error("Missing payload");const s=(0,n.notBlankOr)(i.k,(0,t.l)().d),a=(0,t.l)().o.find(e=>e.k===s);if(null==a)throw new Error("Unknown key");return r.V2.verify(e,a)};const r=i(91227),s=i(19851),n=i(22573),a=i(71706);t.l=(0,s.lazy)(()=>(0,a.j)("G54BgBwHzrkukKDR8Ar6KkW29gbXlfrqQX46gTu5Wfq6dELYTjfBokB0d5+E2SAINBtxlmPquWe3PMUoNgaJrD982QMslkNeZ4BEqcBbQT59DVl9RnoTNi50diuT7NQg0YHxkr8SwDwtmFUOf+LwNVDDnPXUrzTOU++M3b+lcyfr7PXZndKHzho8iztNkZgt+/19//aXe+gvmC0HIdnn64wdLeYeLM7S9jmjTp52SzFsvIVbd4D0+rdtdjiz6R4vc2cmY398kuXiKG7fNXWS/I93etxXiVNPd4RXJF+k6JnuMUKk03GWHQQ="))},84194(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SchemeCounts=t.UidLength=t.S=void 0,t.getScheme=g,t.sortUids=function(e){return(0,s.sortBy)((0,r.uniq)(e.filter(b)),e=>[t.S.indexOf(g(e))??t.S.length+1,e])},t.prefix2scheme=function(e){return p()[e]},t.toUID=function(e,i){try{const r=(0,l.toS)(i).replace(/[^a-z\d=/+]+/gi,"");return(0,n.blank)(r)||y.includes(r.toLowerCase())||null!=r.match(/^[\s0:_/-]*$/)?void 0:e+":"+(0,h.shortStringSha)(r,t.UidLength,f.Radix58)}catch(t){return void(0,d.mkLogger)("toUID").warn("failed",{pfx:e,error:t})}},t.isValidUid=b;const r=i(40958),s=i(76790),n=i(22573),a=i(45599),o=i(50989),l=i(54993),u=i(22454),c=i(19851),d=i(50213),h=i(37628),f=i(55222),m=i(71706),p=(0,a.defer)(()=>(0,m.j)("GyABAIzUYs0Z7mSuLfVL1SwGefr+3nCwyXBMg6nD0qduA8HycFjUGK1N/ikYqhiqYLGbs7oxTBbzRPxteP9gA3L9DS0EJ2BJ1pYNa/DtEE2aPI2o03hHx3k9MhdE7jAeRUvKQ6tY3Q1fcIPe8GBMZvOeKibTymyo3Cw/7Ua42DKPjpL3wxWv+7TCGA=="));function g(e){const i=e.split(":",1)[0];return t.S.has(i)?i:void 0}t.S=(0,o.strEnum)("cu","lc","lm","lp","lb","mp","ms","wm","cm","bm","nm","li","si","vl");const y=["uninitialized","b08dfa6083e7567a1921a715000001fb"];t.UidLength=15;const v=(0,a.defer)(()=>new RegExp(`^(?:${t.S.values.join("|")}):[0-9a-zA-Z]{${t.UidLength}}$`));function b(e){return null!=e&&null!=v().exec(e)}t.SchemeCounts=class{#Gt=new Set;constructor(e){null!=e&&this.addUids(e)}get size(){return this.#Gt.size}addUids(e){for(const t of e)null==g(t)||this.#Gt.has(t)||(this.#Gt.add(t),this.schemeCounts.unset())}count(e){return this.schemeCounts().get(e)}schemeCounts=(0,c.lazy)(()=>{const e=new u.CountingSet;for(const t of this.#Gt){const i=g(t);null!=i&&e.incr(i)}return e})}},33603(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.k=void 0,t.readInfo=O,t.win_machineGuid_=H,t.sids=async function({timeoutMs:e}){const t=performance.now(),i=await(0,y.timeOrTimeout)({cpuModel:W,cpuinfoSerial:R,macUids:V,libraryUid:$,systemUid:G,boardModel:q,linuxMachineUid:j,linuxProductUid:B,linuxBoardSerial:z,winMachineUid:U,networkMacUids:K,libraryVolumeIds:J,homeDirVolumeId:Y},{timeoutMs:e}),r=(0,u.flatten)(i).filter(d.isString);for(const e of r)Z.add(e);return F().tap({msg:"sids()",result:(0,x.sortUids)([...Z,...r]),meta:{timeoutMs:e,elapsedMs:(0,g.roundMs)(performance.now()-t)}})},t.addSids=function(e){if((0,p.isTest)())for(const t of e)Z.add(t)},t.clearSids=X;const r=i(77773),s=i(40958),n=i(22573),a=i(42659),o=i(45599),l=i(41400),u=i(96249),c=i(68708),d=i(51926),h=i(54993),f=i(19851),m=i(50213),p=i(7282),g=i(3685),y=i(56519),v=i(84777),b=i(32551),w=i(87290),S=i(34102),P=i(34075),M=i(45879),T=i(70854),_=i(57902),E=i(72308),k=i(45969),D=i(43334),I=i(81595),C=i(30933),A=i(71706),x=i(84194);t.k=(0,o.defer)(()=>(0,A.j)("GxoCgBwHdkP3iUvwkVnStJhT+ej+ZeBmAYUqMDSLTlffFHnamrrJbfIoosz/vzXP27ZsbpA8o8BTz29Xn4MT5ez5DSYNJm1b2lEhI4L7DXqQoqjuwti5jW/7bLrap9+MdYaALy4a0gVniA++nTAS9EkJ/zJEOkVRYguGg8+q/iFpADi5HYvUY+CNfRRMQzRJv/akVZ1BmTIN5o5njyOO8cTeMcnEJI8azLb7sEvdggevRPzraQcBUh9m3ZuRdzjIATFJGKOJxKae5EV5M4wXGN8bxn76zDDu3doMtcZ5AEeMQFTpBAVuxnGxxZDlnyVmg3oH81k+/6dqP/zYtD8LMYzBLteKhkDsKjlIYe0="));const F=(0,o.defer)(()=>(0,m.mkLogger)((0,t.k)().n));async function O(e=(0,t.k)().pc){if(D.isLinux)try{const t=await(0,I.fileGrep_)(e,/^\s*serial\s*[:=]\s*(?!0+$)(?<uid>\w{9,})/i,{trimEnd:!0});return t?.groups?.uid}catch{return}}const R=(0,o.defer)(async()=>(0,x.toUID)(x.S.lc,await O())),L=/o\.e\.m\./i;async function N(e){return(0,s.uniq)(await Promise.all((0,t.k)()[e].map(e=>(0,M.readFileMaybe)(e,_.LogLevels.trace)))).map(h.toS).filter(e=>(0,n.notBlank)(e)&&null==e.match(L))}async function j(){if(D.isLinux&&!(0,k.isDocker)())return(await N("lm")).map(e=>(0,x.toUID)(x.S.lm,e))}async function B(){return D.isLinux?(await N("lp")).map(e=>(0,x.toUID)(x.S.lp,e)):void 0}async function z(){return D.isLinux?(await N("lb")).map(e=>(0,x.toUID)(x.S.lb,e)):void 0}const V=(0,f.rolazy)(async()=>{if(D.isMac)try{return(0,c.entries)(await async function(){const e=await(0,v.stdout_)((0,t.k)().i,(0,t.k)().ia,{timeoutMs:5*a.secondMs}),i=e.match(/uuid" = "([a-z\d-]{12,})"/i)?.[1],r=e.match(/SerialNumber" = "([a-z\d-]{10,})"/i)?.[1];return{mp:i,ms:r}}()).map(([e,t])=>(0,x.toUID)(e,t))}catch(e){return void F().warn((0,t.k)().i+" failed",e)}});function H(){try{return(0,r.GetStringRegKey)((0,t.k)().w1,(0,t.k)().w2,(0,t.k)().w3)}catch(e){return void F().warn("reading "+(0,t.k)().w1+" failed",e)}}function U(){return D.isWin?(0,x.toUID)(x.S.wm,H()):void 0}const W=(0,o.defer)(()=>(0,x.toUID)(x.S.cm,(0,C.cpuInfo)()[0].model));async function q(){return D.isLinux?(0,x.toUID)(x.S.bm,(0,s.compactBlanks)(await N("bm")).map(e=>e.trim()).join("\n")):[]}async function $(){return(0,x.toUID)(x.S.li,await((0,T.LibraryUIDStore)()?.readUid_()))}async function G(){return(0,x.toUID)(x.S.si,await((0,T.SystemUIDStore)()?.readUid_()))}function K(){return(0,k.isDocker)()?[]:(0,E.networkMacAddresses)().map(e=>(0,x.toUID)(x.S.nm,e))}async function J(){const e=[];for await(const t of(0,w.libraryVolumeUUIDs)())e.push((0,x.toUID)(x.S.vl,t));return e}async function Y(){if(!(0,k.isDocker)())return(0,x.toUID)(x.S.vl,(await(0,P.bestVolumeForPath)((0,b.homeDir)()))?.uuid)}const Z=new Set;function X(){(0,p.isTest)()&&Z.clear()}(0,l.later)(()=>{(0,p.isTest)()&&(0,S.ee)().on("clearCache",X)})},48132(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserTimeoutMs=void 0;const r=i(42659);t.UserTimeoutMs=7*r.secondMs},86214(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CaptureLogger=void 0,t.CaptureLogger=class{logEntries=[];log(e,t,i,r){this._logEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}_logEntry(e){this.logEntries.push(e)}isEnabled(){return!0}end(){}async maybeFlush(){}}},49794(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColoredLogFormatter=void 0,t.colorProcessName=p;const r=i(57975),s=i(40958),n=i(22573),a=i(45599),o=i(31586),l=i(54993),u=i(37975),c=i(7282),d=i(23560),h=i(66184),f=i(93475),m=(0,a.defer)(()=>[{re:/web/,fn:u.green},{re:/worker/,fn:u.cyan},{re:/sync/,fn:u.blue},{re:/log/,fn:u.blueBright},{re:/info/,fn:u.blueBright},{re:/main/,fn:u.yellow},{re:/test/,fn:u.blueBright},{re:/billing/,fn:u.cyan}]);function p(e){if((0,n.blank)(e))return"";const t=m().find(t=>t.re.test(e));return null!=t?(0,u.bgBlack)(t.fn(e)):e}t.ColoredLogFormatter=class{_inspectOptions;logLevels={trace:"trace",debug:(0,u.darkGrey)("debug"),info:(0,u.cyan)("info_"),warn:(0,u.yellowBright)("warn_"),error:(0,u.redBright)("error_"),fatal:(0,u.bgRedBright)((0,u.black)("fatal"))};inspectOptions;defaultProcessName;constructor(e={}){this._inspectOptions=e,this.inspectOptions={colors:!0,showHidden:!1,depth:5,compact:!0,customInspect:!0,maxArrayLength:null,processName:d.processName,...this._inspectOptions},(0,c.isTest)()&&(this.inspectOptions.breakLength=255),this.inspectOptions.processName.watch(e=>this.defaultProcessName=p(e))}formatMeta(e){if(null==e)return;const t=(0,f.prepMeta)(e);return null==t?void 0:(0,r.inspect)(t,this.inspectOptions)}colorContext(e){if(!(0,h.logFilter)().highlight(e))return(0,u.blue)(e);const t=e.match(/[^.\w-]/);if(!(0,o.gt0)(t?.index))return(0,u.blue)(e);const i=e.slice(0,t.index),r=e.slice(t.index);return(0,u.yellow)(i)+(0,u.blue)(r)}formatLogEntry(e){return(0,s.compactBlanks)([(0,u.darkGrey)(new Date(e.ts).toISOString()),null==e.from?this.defaultProcessName:p(e.from),this.logLevels[e.l],this.colorContext(e.ctx),e.msg,this.formatMeta(e.meta)]).map(e=>(0,l.toS)(e)).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,d.processName)(),ctx:t,msg:i,meta:r})}}},32105(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleLogger=void 0;const r=i(57975),s=i(45599),n=i(23560),a=i(36940),o=i(66184);class l{static instance=(0,s.defer)(()=>new l);log(e,t,i,r){this.isEnabled(e,t)&&this._logEntry({ts:Date.now(),l:e,from:(0,n.processName)(),ctx:t,msg:i,meta:r})}_logEntry(e){(0,a.DefaultLogEntryWriter)(e)}isEnabled(e,t){return(0,o.logFilter)().enabled(e,t)}async maybeFlush(){}toLogJSON(){return"ConsoleLogger()"}[r.inspect.custom](){return this.toLogJSON()}}t.ConsoleLogger=l},14593(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContextualLogger=void 0;const r=i(57975),s=i(22573),n=i(26905),a=i(55835),o=i(31586),l=i(68708),u=i(13538),c=i(50213),d=i(3685),h=i(45255),f=i(73568),m=i(76740),p=i(99331),g=i(70025),y=i(57159),v=i(57902),b=/logger|lazy|defer/i;class w{loggers;abortable;defaultMeta;context;constructor(e,t=c.rootLoggers,i=new m.Abortable,r){this.loggers=t,this.abortable=i,this.defaultMeta=r,this.context=(0,s.toNotBlank)(e)??(0,n.shortStack)().find(e=>!b.test(e))??""}get aborted(){return this.abortable.aborted}abort(e){this.abortable.abort(e)}toLogJSON(){return"CtxLogger("+this.context+")"}[r.inspect.custom](){return this.toLogJSON()}child(e){return new w(this.context+e,this.loggers,this.abortable,this.defaultMeta)}throwIfAborted_(e){(0,p.ending)()&&this.throw(new f.AbortError("throwIfAborted_(): ending"),{logLevel:"warn"});try{e?.throwIfAborted_(),this.abortable.throwIfAborted_()}catch(e){throw this.log((0,g.isIgnorableError)(e)?"debug":"warn","throwIfAborted_()",{error:e}),e}}async awaitOrAbort(e){try{return await this.abortable.awaitOrAbort(e)}catch(e){throw this.log((0,g.isIgnorableError)(e)?"debug":"warn","awaitOrAbort()",{error:e}),e}}resetAbortable(){this.abortable.aborted&&(this.abortable=new m.Abortable)}throw(e,t){const i=e instanceof Error&&(0,l.isEmptyObj)((0,l.omit)(t??{},"logLevel"))?e:(0,y.toWrappedError)(e,{...this.defaultMeta,...t,message:this.context}),r=(0,g.isIgnorableError)(i),n=(0,g.isDoNotSendError)(i);throw(0,s.blank)(i.stack)&&Error.captureStackTrace?.(i),this.log(t?.logLevel??(!0===r||!0===n?"warn":"error"),".throw() "+i.message,{stack:i.stack,...(0,l.omit)(t??{},"name")}),i}tap(e){const t=e.level??(0,v.maxSevereLevel)(v.LogLevels.debug,null!=e.meta?.error?"warn":void 0,(0,o.gt0)(e.meta?.elapsedMs)?(0,v.msToLevel)(e.meta.elapsedMs):void 0);return this.log(t,e.msg,{result:e.result,...e.meta}),e.result}tapThunk(e){const t=performance.now();let i;try{i=setTimeout(()=>this.log("warn","slow: "+e.msg),h.ShortCommandTimeoutMs);const r=e.result(),s=(0,d.roundMs)(performance.now()-t);return this.tap({level:s>500?"info":e.level,msg:e.msg,result:r,meta:{...e.meta,elapsedMs:s}})}catch(t){throw this.log("error","error: "+e.msg,{error:t,...e.meta}),t}finally{(0,a.map)(i,clearTimeout)}}async tapAsync_(e){try{const t=performance.now(),i=await(0,u.thenOrTimeoutError)(e.result,e.timeoutMs),r=(0,d.roundMs)(performance.now()-t);return this.tap({...e,result:i,meta:(0,o.gt0)(r)?{...e.meta,elapsedMs:r}:e.meta})}catch(t){if(t instanceof y.WrappedError)throw t;return this.throw(t,{...(0,l.pick)(e,"errorMsg","msg","timeoutMs","meta"),logLevel:e.errorLevel})}}isEnabled(e,t){for(const i of this.loggers())if(i.isEnabled(e,t??this.context))return!0;return!1}isDebugEnabled(e){return this.isEnabled(v.LogLevels.debug,e??this.context)}log(e,t,i){null!=this.defaultMeta&&(null==i?i={...this.defaultMeta}:"object"!=typeof i||Array.isArray(i)||(i={...this.defaultMeta,...i}));for(const r of this.loggers())r.log(e,this.context,t,i)}_logEntry(e){for(const t of this.loggers())t._logEntry(e)}elapsed(e,t){this.log((0,v.maxSevereLevel)((0,v.msToLevel)(t.elapsedMs),t.level),e,t)}async maybeFlush(){for(const e of this.loggers())await e.maybeFlush()}fatal(e,t){this.log("fatal",e,t)}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}trace(e,t){this.log("trace",e,t)}deprecate(e,t){this.warn(`${e} is deprecated, use ${t} instead`)}}t.ContextualLogger=w},81125(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_FLIGHT_RECORDER_CAPACITY=void 0,t.DEFAULT_FLIGHT_RECORDER_CAPACITY=250},36940(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogEntryWriter=function(e){(0,r.writeStdout)((0,s.DefaultLogFormatter)().formatLogEntry(e))};const r=i(50321),s=i(28981)},28981(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFormatter=void 0;const r=i(19851),s=i(51879);t.DefaultLogFormatter=(0,r.lazy)(()=>new s.PlaintextLogFormatter)},19259(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findFatalFilesForPid=h,t.deleteFatalFilesForPid=async function(e,t,i){const s=await h(e,t,i);let n=0;for(const e of s)try{await(0,r.unlink)(e),n++}catch{}return n},t.readFatalLogEntry=f,t.readFatalLogsForPid=async function(e,t,i){const r=await h(e,t,i),s=await Promise.all(r.map(f));return(0,n.compact)(s)},t.findRecentFatalLogEntries=async function(e,t){const i=Date.now()-t,r=[];try{for await(const t of(0,u.recurseDir_)((0,o.logDir)(),{reverse:!0,acceptDir:(0,c.acceptDateDirNewerThan)(i)})){if(!t.isFile())continue;if(!t.name.startsWith("fatal-"))continue;if(!t.name.endsWith(".jsonl"))continue;const n=(0,s.join)(t.parentPath,t.name),a=await f(n);if(null!=a&&a.ts>=i&&(r.push(a),r.length>=e))break}}catch{}return r},t.archiveRecentFatalLogs=async function(e){const t=Date.now()-e;let i=0;try{for await(const e of(0,u.recurseDir_)((0,o.logDir)(),{acceptDir:(0,c.acceptDateDirNewerThan)(t)})){if(!e.isFile())continue;if(!e.name.startsWith("fatal-"))continue;if(!e.name.endsWith(".jsonl"))continue;const t=(0,s.join)(e.parentPath,e.name),n=(0,s.join)(e.parentPath,"ack-"+e.name);try{await(0,r.rename)(t,n),i++}catch{}}}catch{}return i};const r=i(51455),s=i(76760),n=i(40958),a=i(98553),o=i(46296),l=i(83278),u=i(65238),c=i(21727),d=i(4904);async function h(e,t,i){const n=(0,c.datedLogDir)(i),a=null!=t?`fatal-${t}-${e}-`:void 0,o=`-${e}-`;try{const e=await(0,r.readdir)(n,{withFileTypes:!0}),t=[];for(const i of e)if(i.isFile()&&i.name.startsWith("fatal-")&&i.name.endsWith(".jsonl")){if(null!=a){if(!i.name.startsWith(a))continue}else if(!i.name.includes(o))continue;t.push((0,s.join)(n,i.name))}return t.sort()}catch{return[]}}async function f(e){try{const t=await l.BaseFile.for(e).readText_(),i=(0,a.parseJSON)(t.trim());return(0,d.isLogEntry)(i)&&"fatal"===i.l?i:void 0}catch{return}}},31256(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GelfLogFormatter=void 0;const r=i(40958),s=i(22573),n=i(45599),a=i(41400),o=i(98553),l=i(55835),u=i(31586),c=i(68708),d=i(72993),h=i(23560),f=i(81168),m=i(98314),p=i(57902),g=i(93475),y=(0,n.defer)(()=>({_service:(0,h.serviceName)(),_pid:process.pid}));function v(e){if(null==e)return y();{const[t,i]=e.split("-",2);return(0,s.blank)(t)?y():{_service:t,_pid:(0,u.toInt)(i)}}}(0,a.later)(()=>h.serviceName.watchLater(()=>y.reset())),t.GelfLogFormatter=class{formatLogEntry(e){const t={version:"1.1",level:(0,p.level2syslog)(e.l)??7,host:d.SimpleAppName,timestamp:e.ts/1e3,short_message:(0,f.stripAnsiEsc)((0,r.uniq)((0,r.compactBlanks)([e.ctx,e.msg])).join(" ")),full_message:(0,l.map)(e.meta?.error,m.errorToVerbose)};return(0,o.stringify)({...t,...v(e.from),...(0,c.fromEntries)((0,c.entries)((0,g.prepMeta)(e.meta,3)??{}).map(([e,t])=>"id"===e?void 0:["_"+e,(0,o.stringify)(t)]))})}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}}},68332(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultInactiveLogIdleMs=void 0,t.compressInactiveLogs=async function(e){const i={compressed:[],skipped:0,errors:[]};if(!c.LoggingSettings.logCompression.valueOrDefault)return i;const o=(e.now??Date.now)(),d=e.mtimeIdleMs??t.DefaultInactiveLogIdleMs,m=e.pidAlive??r.pidExists,p=function(e){const t=new Map;for(const i of e){const e=`${i.parsed.service}-${i.parsed.pid}`;let r=t.get(e);null==r&&(r=[],t.set(e,r)),r.push(i)}return t}(await async function(e){const t=[];try{for await(const i of(0,u.recurseDir_)(e)){if(!i.isFile())continue;if(!i.name.endsWith(".jsonl"))continue;const e=(0,h.parseLogFilename)(i.name);if(null==e)continue;const r=(0,n.join)(i.parentPath,i.name);try{const n=await(0,s.stat)(r);t.push({parentPath:i.parentPath,name:i.name,nativePath:r,parsed:e,mtimeMs:n.mtimeMs})}catch{}}}catch{}return t}(e.logDir));for(const e of p.values()){const t=(0,a.sortBy)(e,e=>[l.CmpReverseFlag+e.parentPath,-e.parsed.index]),[r,...s]=t;for(const e of s)await f(e,o,d,i);null==r||m(r.parsed.pid)?null!=r&&i.skipped++:await f(r,o,d,i)}return i};const r=i(58587),s=i(51455),n=i(76760),a=i(76790),o=i(42659),l=i(34666),u=i(65238),c=i(2171),d=i(53252),h=i(11547);async function f(e,t,i,r){if(t-e.mtimeMs<i)r.skipped++;else try{if(null!=await async function(e){const t=e+".gz";return(await(0,s.stat)(t).catch(()=>{}))?.isFile()?t:void 0}(e.nativePath))return await(0,s.unlink)(e.nativePath),void r.compressed.push(e.nativePath);await(0,d.gzip_)(e.nativePath),r.compressed.push(e.nativePath)}catch(t){r.errors.push({nativePath:e.nativePath,error:t})}}t.DefaultInactiveLogIdleMs=4*o.hourMs},51576(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogBroadcaster=t.logBroadcaster=void 0;const r=i(77030),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(98553),u=i(56409),c=i(31586),d=i(25764),h=i(38836),f=i(50213),m=i(409),p=i(28874),g=i(31256),y=i(6157),v=(0,s.lazy)(()=>(0,f.mkConsoleLogger)("log.LogBroadcaster")),b=String.fromCharCode(0),w=/^(?<host>[^:]+):(?<port>\d+)$/;t.logBroadcaster=(0,s.lazy)(()=>{const e=function(){const e=p.Settings.logServer.valueOrDefault?.match(w)?.groups,t=e?.host,i=(0,c.toInt)(e?.port);return!(0,n.blank)(t)&&(0,c.gt0)(i)?{host:t,port:i}:void 0}();return null==e?void(p.Settings.logServer.hasValue()&&v().info(`setup(): no-op: invalid PS_LOG_SERVER setting (expecting "host:port", got ${(0,l.stringify)(p.Settings.logServer.valueOrDefault)})`)):new S(e.host,e.port)}),(0,o.later)(()=>p.Settings.logServer.watchLater(()=>t.logBroadcaster.unset()));class S extends h.EndableWrapper{host;port;logFormatter=new g.GelfLogFormatter;logFilter=new y.LogFilterImpl(p.Settings.logServerLevel);socket;constructor(e,t){super("log.LogBroadcaster("+e+":"+t+")",()=>this.socket?.end(),d.EndableRanks.logtail),this.host=e,this.port=t,this.#Kt()}isEnabled(e,t){return this.logFilter.enabled(e,t)}log(e,t,i,r){this.isEnabled(e,t)&&this._logEntry({ts:Date.now(),l:e,ctx:t,msg:i,meta:r})}_logEntry(e){try{const t=this.socket;null==t?this.#Kt():t.write(this.logFormatter.formatLogEntry(e)+b)}catch(t){v().warn("Failed to write log entry to socket",{logEntry:e,error:t})}}maybeFlush(){const e=new u.Latch;return this.socket?.write("",()=>e.resolve()),e.promise}#Kt=(0,m.rateLimited)({f:async()=>{try{const e=this.socket=(0,r.createConnection)({host:this.host,port:this.port});e.on("close",()=>{this.socket=void 0}),e.on("error",t=>{v().warn("Error from logging server",t);try{e.end()}catch{}})}catch(e){v().warn("Failed to connect to the log server",e)}},minCallDelayMs:a.minuteMs,name:"#mkSocket"})}t.LogBroadcaster=S},20839(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLogFlushMs=void 0,t.DefaultLogFlushMs=750},21727(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.datedLogDir=function(e,t){return(0,r.join)(e??n.Settings.logDir.valueOrDefault,(0,s.fmtIsoDate)(t??new Date))},t.parseDateDir=o,t.acceptDateDirNewerThan=function(e){const t=e-2*s.dayMs;return e=>{const i=o(e);return null==i||i>=t}};const r=i(76760),s=i(42659),n=i(28874),a=/^\d{4}-\d{2}-\d{2}$/;function o(e){const t=(0,r.basename)(e);if(!a.test(t))return;const i=Date.parse(t);return isNaN(i)?void 0:i}},12495(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logDirCleanup=void 0,t.isPrunableLogDirFile=u;const r=i(31586),s=i(19851),n=i(79267),a=i(32144),o=i(16287),l=i(28874);async function u(e){if((0,a.isLogExt)(e.ext))return!0;if(!e.base.endsWith(".meta.json"))return!1;const t=await(0,o.statMaybe)(function(e){return e.nativePath.slice(0,-10)+".jsonl.gz"}(e));return!0!==t?.isFile()}t.logDirCleanup=(0,s.lazy)(()=>{const e=l.Settings.logRetention.valueOrDefault;return(0,r.gt0)(e)?n.FileCleanup.for({name:"logDirCleanup",rootNativePath:()=>l.Settings.logDir.valueOrDefault,staleMs:e,isPrunable:u}):void 0})},4904(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logTs=function(){return Math.round(100*(r.performance.timeOrigin+r.performance.now()))/100},t.isLogEntry=function(e){return null!=e&&(0,n.isNumber)(e?.ts)&&(0,a.isString)(e?.msg)&&o.LogLevels.includes(e.l)},t.logEntrySorter=function(e){return e?.ts},t.sortLogEntriesInPlace=function(e){(0,s.sortByInPlace)(e,e=>e.ts)};const r=i(643),s=i(76790),n=i(31586),a=i(51926),o=i(57902)},11547(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseLogFilename=function(e){const t=n.exec(e);if(null==t?.groups)return;const i=(0,r.toInt)(t.groups.pid),s=(0,r.toInt)(t.groups.index);return null==i||null==s?void 0:{service:t.groups.service,pid:i,index:s}};const r=i(31586),s=[...i(5670).ServiceNames.values].sort((e,t)=>t.length-e.length).join("|"),n=new RegExp(`^(?<service>${s})-(?<pid>\\d+)-(?<index>\\d+)\\.jsonl(?:\\.gz)?$`)},69831(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isJsonlLogFile=p,t.recentLogFiles=async function*(e){const t=p,i=h.Settings.logDir.valueOrDefault;if((0,s.blank)(i))throw new Error("no log directory found: "+(0,n.stringify)(h.Settings.logDir.dump()));const a=new Set;for await(const s of(0,c.recurseDir_)(i,{acceptDir:(0,f.acceptDateDirNewerThan)(e),reverse:!0}))if(s.isFile()&&t(s.name)){const t=(0,r.join)(s.parentPath,s.name),i=await g(t);!a.has(i)&&await y(t,i,e)&&(a.add(i),yield i)}},t.logFiles=async function*(e){const t=await(0,d.statMaybe)(e);if(null!=t)if(t.isFile())p(e)&&(yield await g(e));else if(t.isDirectory()){const t=new Set;for await(const i of(0,c.recurseDir_)(e,{reverse:!0}))if(i.isFile()&&p(i.name)){const e=await g((0,r.join)(i.parentPath,i.name));t.has(e)||(t.add(e),yield e)}}},t.parseLogfileName=function(e){const t=(0,u.toS)(e).split(/[-.]/);return(0,o.toCompactObj)({serviceName:l.ServiceNames.toValid(t[0]),pid:(0,a.toInt)(t[1]),count:(0,a.toInt)(t[2])})};const r=i(76760),s=i(22573),n=i(98553),a=i(31586),o=i(68708),l=i(5670),u=i(54993),c=i(65238),d=i(16287),h=i(28874),f=i(21727),m=/\.jsonl(?:\.gz)?$/i;function p(e){return m.test(e)}async function g(e){if(!/\.jsonl$/i.test(e))return e;const t=e+".gz";return(await(0,d.statMaybe)(t))?.isFile()?t:e}async function y(e,t,i){const[r,s]=await Promise.all([(0,d.statMaybe)(e),t===e?void 0:(0,d.statMaybe)(t)]);return(0,a.gt)(Math.max(r?.mtimeMs??-1/0,s?.mtimeMs??-1/0),i)}},66184(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.defaultLogLevel=t.logFilter=t.SimpleLogFilter=void 0,t.isDefaultLogLevelAtLeast=function(e){return(0,t.logFilter)().defaultLevelIndex>=(0,s.levelIndex)(e)},t.silently=function(e){try{return(0,t.logFilter)().silent=!0,e()}finally{(0,t.logFilter)().silent=!1}},t.silentlyAsync=async function(e){try{return(0,t.logFilter)().silent=!0,await e()}finally{(0,t.logFilter)().silent=!1}},t.ifLog=function(e,i){return(0,t.logFilter)().enabled(e)?i():void 0},t.isLogged=function(e,i){return(0,t.logFilter)().enabled(e,i)};const r=i(19851),s=i(57902),n=i(47832);class a{minLogLevel;defaultLevelIndex;constructor(e){this.minLogLevel=e,this.defaultLevelIndex=(0,s.levelIndex)(e)}highlight(){return!1}enabled(e){return(0,s.levelIndex)(e)<=this.defaultLevelIndex}silent=!1}t.SimpleLogFilter=a,t.logFilter=(0,r.lazy)(()=>new a((0,n.logLevelDefaultValue)())),t.defaultLogLevel=(0,r.lazy)(()=>s.LogLevels.values[(0,t.logFilter)().defaultLevelIndex])},6157(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogFilterImpl=void 0;const r=i(19851),s=i(40958),n=i(22573),a=i(54993),o=i(7282),l=i(2171),u=i(57902),c=/^(?:(.+?):)?(fatal|error|warn|info|debug|trace)$/i;t.LogFilterImpl=class{setting;silent=!1;defaultLevelIndex;#Jt=[];constructor(e=l.LoggingSettings.logLevel){this.setting=e,e.watch(()=>this.#ze.refresh()),this.#ze()}#ze=(0,r.lazy)(()=>{this.#Jt.length=0;const e=this.setting.valueOrDefault;this.defaultLevelIndex=u.LogLevels.indexOf(e)??u.LogLevels.indexOf(this.setting.defaultValue)??u.LogLevels.indexOf(u.LogLevels.warn);const t=(0,s.compactBlanks)(e.split(/[,;]/));for(const i of t){const t=c.exec(i.trim());if(null==t)(0,o.isProd)()&&console.error("LogFilterImpl: Ignoring '"+i+"' from "+e);else{const e=(0,a.toS)(t[1]).toLowerCase(),i=(0,u.levelIndex)(t[2]);(0,n.blank)(e)?this.defaultLevelIndex=i:this.#Jt.push({prefix:e,levelIndex:i})}}});#Yt(e){if(null==e||0===this.#Jt.length||(0,n.blank)(e))return;const t=(0,a.toS)(e).toLowerCase();for(const e of this.#Jt)if(t.startsWith(e.prefix))return e;for(const e of this.#Jt)if(t.includes(e.prefix))return e}enabled(e,t){if(this.silent)return!1;const i=(0,u.levelIndex)(e);if(null!=t){const e=this.#Yt(t);if(null!=e)return i<=e.levelIndex}return i<=this.defaultLevelIndex}highlight(e){const t=this.#Yt(e);return null!=t&&t.levelIndex>=this.defaultLevelIndex}}},57902(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevels=void 0,t.levelIndex=function(e){return s.LogLevels.indexOf(e)??s.LogLevels.indexOf(e.trim().split(/[^a-z]/i)[0]?.toLowerCase())??o},t.maxSevereLevel=function(e,...t){let i=e;for(const e of t)null!=e&&s.LogLevels.lt(e,i)&&(i=e);return i},t.levelGte=function(e,t){return(0,n.gte)(s.LogLevels.indexOf(e),s.LogLevels.indexOf(t))},t.level2syslog=function(e){return l.get(e)},t.setDefaultElapsedErrorLogMs=function(e){u=(0,n.toGt0)(e)??u},t.msToLevel=function(e,t){const i=(0,n.toGt0)(t)??u;return e>=i?"error":e>=.5*i?"warn":e>=.25*i?"info":"debug"};const r=i(42659),s=i(44803),n=i(31586);var a=i(44803);Object.defineProperty(t,"LogLevels",{enumerable:!0,get:function(){return a.LogLevels}});const o=s.LogLevels.indexOf("trace"),l=new Map([[s.LogLevels.fatal,1],[s.LogLevels.error,3],[s.LogLevels.warn,4],[s.LogLevels.info,6],[s.LogLevels.debug,7]]);let u=r.minuteMs},47832(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logLevelDefaultValue=function(){return(0,r.isTest)()?"error":"warn"};const r=i(7282)},93475(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePlaceholder=void 0,t.prepMeta=function e(i,h=4){if(null==i)return null;if(h<0)return"…";if((0,a.isString)(i)||Buffer.isBuffer(i))return(0,a.ellipsize)(i.toString(),256,32);if((0,o.isError)(i))return(0,c.errorToVerbose)(i);if((0,s.isObject)(i)&&"Sharp"===i.constructor?.name)return"(sharp)";if(Array.isArray(i)){const t=d.Settings.logContextLimit.valueOrDefault,r=Math.floor(t/2);return i.length<=t?i.map(t=>e(t,h-1)):[...i.slice(0,r).map(t=>e(t,h-1)),`… (${i.length} total entries)`,...i.slice(-r).map(t=>e(t,h-1))]}if("function"==typeof i)return`(function: ${i.name||"anonymous"})`;if("object"==typeof i){for(const t of["toLogJSON","toJSON"])if("function"==typeof i[t])return e(i[t](),h-1);if((0,n.isPromiseLike)(i))return t.PromisePlaceholder;if("…"in i)return i;const o=(0,u.mapNullEntries)(i,(t,i)=>"sql"===t?i:e(i,h-1),d.Settings.logContextLimit.valueOrDefault),c=(0,l.diff)((0,s.keys)(i),(0,s.keys)(o));return(0,r.isNotEmpty)(c)&&(o["…"]="omitted: "+(0,a.ellipsize)(c.join(", "),128,32)),o}return i};const r=i(40958),s=i(68708),n=i(20214),a=i(51926),o=i(23541),l=i(48884),u=i(88158),c=i(98314),d=i(28874);t.PromisePlaceholder="(promise)"},31726(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogStream=void 0;const r=i(57075),s=i(4904),n=i(66184),a=i(93475);t.LogStream=class{from;filter;stream=new r.Transform({objectMode:!0});constructor(e,t=n.logFilter){this.from=e,this.filter=t}isEnabled(e,t){return this.filter().enabled(e,t)}log(e,t,i,r){this.isEnabled(e,t)&&this._logEntry({from:this.from,ts:(0,s.logTs)(),l:e,ctx:t,msg:i,meta:(0,a.prepMeta)(r)})}_logEntry(e){this.stream.push(e)}maybeFlush(){}}},43705(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogWriter=t.LogFileWriter=t.CaptureLogger=void 0;const s=r(i(73024)),n=i(76760),a=i(42659),o=i(45599),l=i(26905),u=i(98553),c=i(31586),d=i(4034),h=i(23560),f=i(78406),m=i(25764),p=i(85970),g=i(70025),y=i(20197),v=i(10234),b=i(73428),w=i(55222),S=i(2171),P=i(21027),M=i(32105),T=i(20839),_=i(21727),E=i(4904),k=i(66184),D=i(57902),I=i(93475);var C=i(86214);Object.defineProperty(t,"CaptureLogger",{enumerable:!0,get:function(){return C.CaptureLogger}});class A extends f.EndableInterval{logDir;logOpts;pendingWrites=[];_nextForcedRotateTs=(0,a.nextMidnightTs)();_linesSinceRotate=0;_logfile;_startIndex=0;maxLinesPerFile;#Zt;flightRecorderMinLevel;flightRecorderTriggerLevel;endTimeoutMs=15*a.secondMs;constructor(e,t={}){super({name:"LogWriter("+e+")",callback:()=>this.#Xt(),intervalMs:T.DefaultLogFlushMs,rank:m.EndableRanks.logger,unref:!0,onEnd:()=>this.#Qt()}),this.logDir=e,this.logOpts={errorLogger:M.ConsoleLogger.instance(),flushEveryMs:T.DefaultLogFlushMs,processName:h.processName,logFilter:k.logFilter,flightRecorderCapacity:S.LoggingSettings.logFlightRecorderCapacity.valueOrDefault,flightRecorderMinLevel:S.LoggingSettings.logFlightRecorderMinLevel.valueOrDefault,flightRecorderTriggerLevel:S.LoggingSettings.logFlightRecorderTriggerLevel.valueOrDefault,maxLinesPerFile:S.LoggingSettings.logMaxLinesPerFile.valueOrDefault,...t},(0,c.gt0)(this.logOpts.flushEveryMs)?this.setIntervalMs(this.logOpts.flushEveryMs):S.LoggingSettings.logFlushMs.watch(this.setIntervalMs),this.flightRecorderTriggerLevel=(0,D.levelIndex)(this.logOpts.flightRecorderTriggerLevel),this.flightRecorderMinLevel=(0,D.levelIndex)(this.logOpts.flightRecorderMinLevel),this.#Zt=new d.CircularBuffer(this.logOpts.flightRecorderCapacity),this.maxLinesPerFile=this.logOpts.maxLinesPerFile}get flushEveryMs(){return this.opts.intervalMs}get flightRecorderCapacity(){return this.#Zt.capacity}set flightRecorderCapacity(e){this.#Zt.capacity=e}setIntervalMs=e=>{const t=super._setIntervalMs(e);return this.#Xt(),t};toJSON(){return{logDir:this.logDir}}isEnabled(e,t){return this.logOpts.logFilter().enabled(e,t)}log(e,t,i,r){const s={ts:(0,E.logTs)(),l:e,from:this.logOpts.processName(),ctx:t,msg:i,meta:r},n=this.isEnabled(e,t),a=(0,D.levelIndex)(e);!n&&a<=this.flightRecorderMinLevel&&a>this.flightRecorderTriggerLevel&&this.#Zt.push(s),n&&(a<=this.flightRecorderTriggerLevel&&this.#ei(),this._logEntry(s))}#ei(){for(const e of this.#Zt)this._logEntry(e);this.#Zt.clear()}_logEntry(e){this.ended&&(0,D.levelIndex)(e.l)<=(0,D.levelIndex)("error")?this.logOpts.errorLogger._logEntry(e):("error"!==e.l&&"fatal"!==e.l||(e.meta??={},e.meta.caller??=(0,l.shortStack)()),null!=e.meta&&(e.meta=(0,I.prepMeta)(e.meta)),"fatal"===e.l&&this.#ti(e),this.pendingWrites.push(e))}async#ti(e){try{const t=(0,_.datedLogDir)(this.logDir),i=this.logOpts.processName(),r=e.ts,s=`fatal-${i}-${w.TokenRadix.encode(r)}.jsonl`,a=(0,n.join)(t,s),o=(0,u.stringify)(e)+"\n";await(0,b.writeFile_)(a,o)}catch(t){this.logOpts.errorLogger.log("error","LogFileWriter.#writeFatalEntry","Failed to write fatal error file",{error:t,entry:e})}}#Qt=(0,o.defer)(async()=>{await this.#Xt(),await this.#ii(),S.LoggingSettings.logFlushMs.unWatch(this.setIntervalMs)});maybeFlush(){return this.#Xt.ifIdle()}#Xt=(0,p.serialized)(async()=>{const e=[...this.pendingWrites];for(this.pendingWrites.length=0;e.length>0;){this.#ri()&&(await this.#ii(),await this.#si(),this._nextForcedRotateTs=(0,a.nextMidnightTs)());const t=this.#ni(e);if(t<=0)break;e.splice(0,t)}});onError(e,t){const i=(0,g.isIgnorableError)(t)?"debug":"error";this.logOpts.errorLogger.log(i,"Caught error from "+e,t)}#ri(){return null==this._logfile||this._linesSinceRotate>=this.maxLinesPerFile||Date.now()>=this._nextForcedRotateTs}async#si(){const e=(0,v.mkValidFilename)(this.logOpts.processName()),t=await(0,y.ensureNewNativePath_)({nativePath:(0,n.join)((0,_.datedLogDir)(this.logDir),e+".jsonl"),emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),i=s.default.createWriteStream(t).on("error",e=>{this.onError("file write stream",e),this.#ii()});this._logfile={stream:i,nativePath:t}}#ni(e){const t=this._logfile?.stream;if(null==t)return this.onError("LogFileWriter.#writeBatch()",new Error("no open stream after rotation")),e.length;const i=(0,c.clamp)(0,e.length,this.maxLinesPerFile-this._linesSinceRotate),r=e.slice(0,i);return this._linesSinceRotate+=r.length,t.write(r.map(e=>(0,u.stringify)(e)+"\n").join("")),r.length}async#ii(){const e=this._logfile;if(this._logfile=void 0,this._linesSinceRotate=0,null!=e)try{await(0,P.disposeStream)(e.stream)}catch(e){this.onError("#closeTarget()",e)}}}t.LogFileWriter=A,t.LogWriter=A},22474(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpLogger=void 0;const r=i(14593);t.NoOpLogger=new r.ContextualLogger("NoOp",()=>[])},51879(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlaintextLogFormatter=void 0;const r=i(57975),s=i(40958),n=i(55835),a=i(68708),o=i(54993),l=i(23560),u=i(81168),c=i(57902);t.PlaintextLogFormatter=class{inspectOptions;constructor(e={colors:!1,showHidden:!1,depth:5,compact:!0,customInspect:!0}){this.inspectOptions=e}paddedLogLevels=(0,a.fromEntries)(c.LogLevels.values.map(e=>[e,(0,u.rightPad)(e,5," ")]));formatLogEntry(e){return(0,s.compactBlanks)([new Date(e.ts).toISOString(),e.from??(0,l.processName)(),this.paddedLogLevels[e.l],(0,u.stripAnsiEsc)(e.ctx),(0,u.stripAnsiEsc)(e.msg),(0,n.map)(e.meta,e=>(0,r.inspect)(e,this.inspectOptions))]).map(e=>(0,o.toS)(e)).join(" ")}format(e,t,i,r){return this.formatLogEntry({ts:Date.now(),l:e,from:(0,l.processName)(),ctx:t,msg:i,meta:r})}}},98192(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readLogEntries=async function*(e,t){const i=(0,o.toNativePath_)(e),r=d(i),s=await(0,l.zcat)(i,t);if(null!=s)for(const e of(0,n.splitLines)(s)){const t=c(e);null!=t&&(yield{...t,from:r})}},t.chunkToLogEntry=c,t.fromForPath=d;const r=i(76760),s=i(98553),n=i(84542),a=i(4001),o=i(17217),l=i(13047),u=i(4904);function c(e){const t=(0,s.parseJSON)(e);return(0,u.isLogEntry)(t)?t:void 0}function d(e){return(0,a.stripCopySuffixFromName)((0,r.parse)(e).name)}},17181(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupLogger=async function(){await(0,f.readSystemSettings)(),(0,v.logFilter)()instanceof b.LogFilterImpl||v.logFilter.set(new b.LogFilterImpl),P();const e=h.LoggingSettings.tailLogs.valueOrDefault&&(0,l.canTailLogs)();e&&await d.LogTail.instance();const t=(0,u.logDir)(),i=(0,o.rootLoggers)().find(e=>e instanceof w.LogWriter);null!=i&&i.logDir===t||(i?.end(),(0,s.filterInPlace)((0,o.rootLoggers)(),e=>!(e instanceof w.LogWriter)),(0,c.writeTextfile_)((0,r.join)(t,"README.txt"),'PhotoStructure writes files with logging entries to dated subdirectories.\n\nAlthough you _can_ directly read these .json files, you don\'t need to!\n\nUse PhotoStructure\'s "logcat" and "logtail" tools to merge, chronologically\nsort, and pretty-print these files.\n\nSee https://photostructure.com/server/tools/#logging for details.\n').catch(()=>null),(0,o.rootLoggers)().push(new w.LogWriter(t))),!e&&h.LoggingSettings.logStdout.valueOrDefault?(0,s.pushNotSame)((0,o.rootLoggers)(),p.ConsoleLogger.instance()):(0,s.filterInPlace)((0,o.rootLoggers)(),e=>!(e instanceof p.ConsoleLogger)),(0,s.filterInPlace)((0,o.rootLoggers)(),e=>!(e instanceof y.LogBroadcaster));const n=(0,y.logBroadcaster)();null!=n&&(0,o.rootLoggers)().push(n),e||(0,a.logStartup)()},t.setupLogFormatter=P;const r=i(76760),s=i(40958),n=i(37975),a=i(57150),o=i(50213),l=i(23560),u=i(46296),c=i(73428),d=i(27074),h=i(2171),f=i(2858),m=i(49794),p=i(32105),g=i(28981),y=i(51576),v=i(66184),b=i(6157),w=i(43705),S=i(51879);function P(){const e=h.LoggingSettings.logColor.valueOrDefault;(0,n.setColorEnabled)(e),g.DefaultLogFormatter.set(e?new m.ColoredLogFormatter:new S.PlaintextLogFormatter)}},83420(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogContentReader=void 0;const r=i(73024),s=i(51455),n=i(38522),a=i(50213),o=i(90753);t.LogContentReader=class{#$=(0,a.mkLogger)("LogContentReader");async readFrom(e,t){try{if(!/\.jsonl(?:\.gz)?$/i.test(e))throw new Error(`${e} is not a log file (expected *.jsonl or *.jsonl.gz)`);const i=(await(0,s.stat)(e)).size,r=t>i,n=r?0:t;return r&&this.#$.debug("File truncated, re-reading from beginning",{path:e,previousPosition:t,newSize:i}),n>=i?{lines:[],newPosition:n,fileSize:i}:(this.#$.trace("Reading file content",{path:e,startPosition:n,fileSize:i,bytesToRead:i-n,wasTruncated:r}),{lines:await this.#ai(e,n,i),newPosition:i,fileSize:i})}catch(i){return this.#$.warn("Error reading file content",{path:e,startPosition:t,error:i}),{lines:[],newPosition:t,fileSize:void 0}}}async#ai(e,t,i){return new Promise((s,a)=>{const l=[];let u;try{u=this.#oi(e)?(0,r.createReadStream)(e,{autoClose:!0}):(0,r.createReadStream)(e,{autoClose:!0,start:t,end:i-1}),u.on("error",a),e.toLowerCase().endsWith(".gz")&&(u=u.pipe((0,n.createGunzip)()).on("error",a));const c=new o.LineReader({trimStart:!0,trimEnd:!0,onlyStreamFullLines:!0});u.pipe(c).on("data",e=>l.push(e)).on("end",()=>s(l)).on("error",a)}catch(e){a(e)}})}#oi(e){return e.toLowerCase().endsWith(".gz")}async getFileSize(e){try{return(await(0,s.stat)(e)).size}catch(t){return this.#$.trace("Cannot get file size",{path:e,error:t}),null}}async isReadable(e){try{return(await(0,s.stat)(e)).isFile()}catch(e){return!1}}}},41813(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogEntryParser=void 0;const r=i(76760),s=i(98192),n=i(50213),a=i(81168);t.LogEntryParser=class{#$=(0,n.mkLogger)("LogEntryParser");#li=new Map;parse(e,t){if(0===e.trim().length)return null;try{const i=(0,s.chunkToLogEntry)(e);return null==i?(this.#ui(e,t,"chunkToLogEntry returned null"),null):{...i,from:this.#ci(t)}}catch(i){return this.#ui(e,t,i),null}}parseLines(e,t){const i=[];for(const r of e){const e=this.parse(r,t);null!=e&&i.push(e)}return i}getErrorStats(){return Object.fromEntries(this.#li)}clearErrorStats(){this.#li.clear()}#ci(e){return(0,r.basename)(e)}#ui(e,t,i){const r=`${t}:parse_error`,s=this.#li.get(r)??0;this.#li.set(r,s+1),s<5?this.#$.warn("Failed to parse log entry",{sourcePath:t,line:(0,a.ellipsize)(e,256,32),error:i?.message??String(i),errorCount:s+1}):5===s&&this.#$.warn("Suppressing further parse errors for file",{sourcePath:t,totalErrors:s+1})}}},47386(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogFileDiscovery=void 0;const r=i(51455),s=i(76760),n=i(25764),a=i(99331),o=i(67732),l=i(29882),u=i(65238),c=i(21727),d=i(69831),h=i(50213);t.LogFileDiscovery=class{#$=(0,h.mkLogger)("LogFileDiscovery");#di;#hi;#fi;#mi;#pi;constructor(e,t,i,r){this.#di=e,this.#hi=t,this.#fi=i,this.#mi=r}async discover(){const e=(0,c.datedLogDir)(this.#di);await(0,l.mkdirp_)(e),this.#$.trace("Scanning for existing log files",{logDir:e});const t=[];for await(const i of(0,u.iterateDir_)(e)){if(!this.#gi(i.name))continue;const r=(0,d.parseLogfileName)(i.name);if(r?.pid===process.pid){this.#$.trace("Skipping own log file",{name:i.name});continue}const n=(0,s.join)(e,i.name);if(this.#hi>0)try{if(await this.#yi(n)<this.#hi){this.#$.trace("Skipping file due to timestamp filter",{path:n,minTimestamp:this.#hi});continue}}catch(e){this.#$.warn("Could not stat file",{path:n,error:e});continue}t.push(n),this.#$.trace("Discovered log file",{file:n})}return this.#$.debug("Discovery complete",{fileCount:t.length,logDir:e}),t}async startWatching(){if((0,a.ending)())return;const e=(0,c.datedLogDir)(this.#di);await(0,l.mkdirp_)(e),this.#$.debug("Starting file system watcher",{logDir:e}),this.#pi=await o.DirWatcher.for(e,(e,t)=>this.#vi(e,t),n.EndableRanks.logtail),this.#$.trace("File system watcher started")}async stop(){this.#$.debug("Stopping file discovery"),null==this.#pi||this.#pi.ended||await this.#pi.end()}async#vi(e,t){if(null!=e)return this.#$.warn("File system watcher error",{error:e}),void this.#mi?.(e);if(!(0,a.ending)())for(const i of t)if(this.#gi((0,s.basename)(i.path)))try{if("create"!==i.type)continue;const t=(0,d.parseLogfileName)((0,s.basename)(i.path));if(t?.pid===process.pid)continue;if(this.#hi>0)try{if(await this.#yi(i.path)<this.#hi){this.#$.trace("Skipping file due to timestamp filter",{file:i.path,minTimestamp:this.#hi});continue}}catch(e){this.#$.trace("Could not stat watcher file",{file:i.path,error:e});continue}this.#$.trace("New log file detected",{file:i.path}),this.#fi(i.path)}catch(e){this.#$.warn("Error processing file system event",{file:i.path,error:e})}}#gi(e){return(0,d.isJsonlLogFile)(e)}async#yi(e){const t=await(0,r.stat)(e);return 0!==t.birthtimeMs?t.birthtimeMs:t.mtimeMs}}},27522(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogFileMonitor=void 0;const r=i(78474),s=i(73024),n=i(51455),a=i(50213);class o extends r.EventEmitter{#$=(0,a.mkLogger)("LogFileMonitor");#me=new Map;#bi=new Map;async watch(e){if(this.#me.has(e))this.#$.trace("Already watching file",{path:e});else try{const t=await(0,n.stat)(e);this.#bi.set(e,t.size),this.#$.trace("Starting file monitor",{path:e,initialSize:t.size});const i=(0,s.watch)(e,(t,i)=>{this.#wi(e,t,i)});i.on("error",t=>{this.#$.warn("File watcher error",{path:e,error:t}),this.emit("error",e,t)}),this.#me.set(e,i)}catch(t){this.#$.warn("Failed to start watching file",{path:e,error:t}),this.emit("error",e,t)}}unwatch(e){const t=this.#me.get(e);t&&(t.close(),this.#me.delete(e),this.#bi.delete(e),this.#$.trace("Stopped watching file",{path:e}))}unwatchAll(){this.#$.debug("Stopping all file monitors",{watchedFiles:this.#me.size});for(const[e,t]of this.#me)t.close(),this.#$.trace("Stopped watching file",{path:e});this.#me.clear(),this.#bi.clear(),this.removeAllListeners()}getWatchedFiles(){return Array.from(this.#me.keys())}isWatching(e){return this.#me.has(e)}getStats(){return{watchedFileCount:this.#me.size,watchedFiles:this.getWatchedFiles()}}async#wi(e,t,i){try{this.#$.trace("File change detected",{path:e,eventType:t,filename:i});const r=(await(0,n.stat)(e)).size,s=this.#bi.get(e)??0;r!==s?(this.#$.trace("File size changed",{path:e,lastSize:s,currentSize:r,sizeChange:r-s}),this.#bi.set(e,r),this.emit("change",e,r,s)):this.#$.trace("File change event but no size change",{path:e,size:r})}catch(t){"ENOENT"===t?.code?(this.#$.debug("File no longer exists",{path:e}),this.emit("removed",e),this.unwatch(e)):(this.#$.warn("Error checking file change",{path:e,error:t}),this.emit("error",e,t))}}}t.LogFileMonitor=o},33668(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogFileTracker=void 0,t.LogFileTracker=class{#Si=new Map;#Pi=new Map;#Mi=new Map;#Ti=new Set;addFile(e){this.#Ti.add(e),this.#Si.has(e)||this.#Si.set(e,0)}removeFile(e){this.#Ti.delete(e),this.#Si.delete(e),this.#Pi.delete(e),this.#Mi.delete(e)}getPosition(e){return this.#Si.get(e)??0}setPosition(e,t){if(t<0)throw new Error(`Invalid position ${t} for ${e}`);this.#Si.set(e,t)}getFileSize(e){return this.#Pi.get(e)}setFileSize(e,t){this.#Pi.set(e,t)}getLastModified(e){return this.#Mi.get(e)}setLastModified(e,t){this.#Mi.set(e,t)}hasFile(e){return this.#Ti.has(e)}getFiles(){return Array.from(this.#Ti)}getFilesWithPotentialUpdates(){return this.getFiles().filter(e=>{const t=this.getPosition(e),i=this.getFileSize(e);return null!=i&&t<i})}clear(){this.#Ti.clear(),this.#Si.clear(),this.#Pi.clear(),this.#Mi.clear()}getStats(){return{fileCount:this.#Ti.size,totalBytesRead:Array.from(this.#Si.values()).reduce((e,t)=>e+t,0),filesWithUpdates:this.getFilesWithPotentialUpdates().length}}}},27074(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogTail=void 0;const r=i(40958),s=i(45599),n=i(25764),a=i(38836),o=i(32105),l=i(36940),u=i(31726),c=i(50213),d=i(23560),h=i(28874),f=i(84968),m=i(83420),p=i(41813),g=i(47386),y=i(27522),v=i(33668);class b extends a.EndableWrapper{#_i;#Ei;#ki;#Di;#Ii;#Ci;#Ai;#xi;#f=[];#Fi=!1;#Oi;#Ri;#Li=new Set;constructor(e=h.Settings.logDir.valueOrDefault,t=l.DefaultLogEntryWriter,i=f.StartTs,r=200,s){super("LogTail",()=>this.#Ye(),n.EndableRanks.logtail,3e3),this.#Ci=t,this.#Ai=r,this.#xi=s??Math.min(h.Settings.logFlushMs.valueOrDefault+100,500),this.#_i=new g.LogFileDiscovery(e,i,e=>{this.#fi(e)},e=>this.logger.warn("Discovery error",{error:e})),this.#Ei=new y.LogFileMonitor,this.#ki=new m.LogContentReader,this.#Di=new p.LogEntryParser,this.#Ii=new v.LogFileTracker,this.#Ei.on("change",e=>{this.#Ni(e)}),this.#Ei.on("removed",e=>this.#ji(e)),this.#Ei.on("error",(e,t)=>this.logger.warn("Monitor error",{path:e,error:t}))}async setup(){try{this.logger.info("Setting up LogTail");const e=await this.#_i.discover();this.logger.debug("Discovered existing files",{count:e.length});for(const t of e)await this.#Bi(t);await this.#_i.startWatching(),this.#zi(),this.logger.info("LogTail setup complete",{trackedFiles:this.#Ii.getFiles().length})}catch(e){throw this.logger.error("Error setting up LogTail",{error:e}),e}}async#Bi(e){try{if(this.#Ii.hasFile(e))return;this.logger.trace("Adding file",{path:e}),this.#Ii.addFile(e),await this.#Ei.watch(e),await this.#Vi(e)}catch(t){this.logger.warn("Error adding file",{path:e,error:t})}}async#fi(e){this.logger.debug("New file detected",{path:e}),await this.#Bi(e)}async#Ni(e){this.logger.trace("File changed",{path:e}),await this.#Vi(e)}#ji(e){this.logger.debug("File removed",{path:e}),this.#Ii.removeFile(e),this.#Ei.unwatch(e)}async#Vi(e){if(!this.#Li.has(e)){this.#Li.add(e);try{await this.#Hi(e)}finally{this.#Li.delete(e)}}}async#Hi(e){try{const t=this.#Ii.getPosition(e),i=await this.#ki.readFrom(e,t);if(this.#Ii.setPosition(e,i.newPosition),null!=i.fileSize&&this.#Ii.setFileSize(e,i.fileSize),0===i.lines.length)return;this.logger.trace("Read file updates",{path:e,lineCount:i.lines.length,oldPosition:t,newPosition:i.newPosition}),this.#Ii.setLastModified(e,Date.now());const r=this.#Di.parseLines(i.lines,e);r.length>0&&(this.#f.push(...r),this.logger.trace("Added entries to buffer",{count:r.length}))}catch(t){this.logger.warn("Error reading file updates",{path:e,error:t})}}#zi(){this.#Fi||this.ended||(this.#Fi=!0,this.logger.debug("Starting processing with interval"),this.#Oi=setInterval(()=>{this.#Ui()},this.#xi),this.#Wi())}async#Ui(){if(!this.ended&&0!==this.#f.length)try{const e=Date.now()-this.#xi,t=[];for(this.#qi();this.#f.length>0&&this.#f[0].ts<=e;)t.push(this.#f.shift());await this.#$i(t),t.length>0&&this.logger.trace("Processed entries from buffer",{count:t.length})}catch(e){this.logger.warn("Error processing buffer",{error:e})}}#Wi(){this.#Ri=setInterval(async()=>{if(!this.ended)try{for(const e of this.#Ii.getFiles()){const t=await this.#ki.getFileSize(e);null!=t&&this.#Ii.getPosition(e)<t&&await this.#Vi(e)}}catch(e){this.logger.warn("Error in polling",{error:e})}},this.#Ai)}#qi(){this.#f.sort((e,t)=>{const i=e.ts-t.ts;return 0!==i?i:(e.from??"").localeCompare(t.from??"")})}async#$i(e,t="Error writing log entry"){for(const i of e)try{await this.#Ci(i)}catch(e){this.logger.warn(t,{error:e})}}async flush(){for(const e of this.#Ii.getFiles())await this.#Vi(e);if(0===this.#f.length)return;this.logger.debug("Flushing buffer",{count:this.#f.length}),this.#qi();const e=[...this.#f];this.#f.length=0,await this.#$i(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#Ye(){this.logger.debug("Cleaning up LogTail"),this.#Oi&&clearInterval(this.#Oi),this.#Ri&&clearInterval(this.#Ri),this.#Fi=!1,await this.flush(),await this.#_i.stop(),this.#Ei.unwatchAll(),this.#Ii.clear(),this.logger.trace("LogTail cleanup complete")}getStats(){return{tracker:this.#Ii.getStats(),monitor:this.#Ei.getStats(),parser:this.#Di.getErrorStats(),bufferSize:this.#f.length,isProcessing:this.#Fi}}static instance=(0,s.defer)(async()=>{const e=new b,t=new u.LogStream((0,d.serviceName)());return(0,c.rootLoggers)().push(t),(0,r.filterInPlace)((0,c.rootLoggers)(),e=>e!==o.ConsoleLogger.instance()),t.stream.on("data",t=>{e.#f.push(t)}),await e.setup(),e})}t.LogTail=b},71290(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateAngularDistance=function(e,t){const i=(e%360+360)%360,r=(t%360+360)%360;return Math.min(Math.abs(i-r),Math.abs(i-r+360),Math.abs(i-r-360))}},82647(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Average=void 0,t.p84=function(e){return null!=e&&(0,o.isNumber)(e.mean)&&(0,o.isNumber)(e.sd)?e.mean+e.sd:0},t.averageStats=function(e){return(new h).pushAll(e).stats()};const r=i(57975),s=i(40958),n=i(74310),a=i(55835),o=i(31586),l=i(68708),u=i(59455),c=i(22454),d=i(70417);class h{maxSamples;static#Gi(e,t){const i=Math.max(e.maxSamples,t.maxSamples),r=new h(i);r._n=e._n+t._n,r._min=(0,d.min)([e._min,t._min]),r._max=(0,d.max)([e._max,t._max]),null!=e._m&&null!=t._m?r._m=(e._m*e._n+t._m*t._n)/r._n:null!=e._m?r._m=e._m:null!=t._m&&(r._m=t._m),null!=e._s&&null!=t._s?r._s=(e._s*e._n+t._s*t._n)/r._n:null!=e._s?r._s=e._s:null!=t._s&&(r._s=t._s),r._ema=(0,d.avg)([e._ema,t._ema]);const s=e.samples,n=t.samples;if(s.length+n.length<=i)r._samples.push(...s,...n);else{const e=Math.floor(i/2),t=i-e;r._samples.push(...s.slice(-e),...n.slice(-t))}return r}static merge(e,t){return e===t?e:null==e?t?.clone()??new h:null==t?e?.clone()??new h:0===e.n&&0===t.n?new h(Math.max(e.maxSamples,t.maxSamples)):0===e.n?t.clone():0===t.n?e.clone():h.#Gi(e,t)}_n;_min;_max;_m;_s;_ema;_samples;constructor(e=20){this.maxSamples=e,this._n=0,this._samples=new n.BoundedList(e)}[r.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(e){return(0,l.isObject)(e)?new h((0,o.toGte0)(e.maxSamples)).with(e):void 0}with(e){return this._n=(0,o.toInt)(e?.n)??0,this._m=(0,o.toFloat)(e?.m),this._s=(0,o.toFloat)(e?.s),this._min=(0,o.toFloat)(e?.min),this._max=(0,o.toFloat)(e?.max),this._ema=(0,o.toFloat)(e?.ema),this._samples.push(...(0,s.compact)((0,u.toA)(e?.samples).map(e=>(0,o.toFloat)(e)))),this}merge(e){if(null==e||0===e.n)return this;if(0===this.n)return this.with(e.toJSON());const t=h.#Gi(this,e);return this._n=t._n,this._m=t._m,this._s=t._s,this._min=t._min,this._max=t._max,this._ema=t._ema,this._samples.clear(),this._samples.push(...t._samples),this}push(e){if(!isFinite(e))throw new Error("Average.push("+e+"): not a number");if(this._n++,this._samples.push(e),this._min=null==this._min?e:Math.min(e,this._min),this._max=null==this._max?e:Math.max(e,this._max),1===this._n||null==this._m||null==this._s||null==this._ema)this._m=e,this._s=0,this._ema=e;else{const t=this._m;this._m+=(e-t)/this._n,this._s+=((e-this._m)*(e-this._m)-this._s)/this._n,this._ema=(this._ema+e)/2}return e}clone(){return(0,l.tap)(new h(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(null!=e)for(const t of e)(0,o.isNumber)(t)&&this.push(t);return this}stats(e=2){const t=t=>(0,a.map)(t,t=>t>100?Math.round(t):(0,o.sigFigs)(t,e)),i={};return i.n=t(this.n),this.empty||(i.mean=t(this.avg),i.sum=t(this.sum),i.sd=t(this.stdDev),i.max=t(this.max),i.min=t(this.min),i.p84=t(this.p84)),i}get empty(){return 0===this._n}get n(){return this._n}get count(){return this._n}get avg(){return this.empty?void 0:(0,o.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}#Ki(e){return null==this._m||null==this._s?void 0:(0,o.sigFigs)(this._m+Math.sqrt(this._s)*e,4)}get p16(){return this.#Ki(-1)}get p29(){return this.#Ki(-.5)}get p38(){return this.#Ki(-.25)}get p50(){return this.avg}get p69(){return this.#Ki(.5)}get p84(){return this.#Ki(1)}get p98(){return this.#Ki(2)}get p99(){return this.#Ki(3)}p(e){switch(e){case"p16":return this.#Ki(-1);case"p50":return this.#Ki(0);case"p69":return this.#Ki(.5);case"p84":return this.#Ki(1);case"p98":return this.#Ki(2);case"p99":return this.#Ki(3)}}get stdDevOverMean(){return null==this._m||null==this._s?void 0:(0,o.sigFigs)(Math.sqrt(this._s)/this._m,4)}get variance(){return this._s}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get sampleMode(){return this.sampleModes(1)?.[0]}sampleModes(e){if(this.empty)return;const t=new c.CountingSet;return this._samples.forEach(e=>t.incr(e)),t.topKeys(e)}get sampleVariance(){return(0,s.mapNotEmpty)(this._samples,d.variance)}get sampleStdDev(){return(0,s.mapNotEmpty)(this._samples,d.stdDev)}get sampleAvg(){return(0,s.mapNotEmpty)(this._samples,d.avg)}get sampleSlope(){return(0,d.slope)(this._samples)??0}get samples(){return[...this._samples]}get sampleEma(){const e=this._samples.toA();if(0!==e.length)return(0,o.sigFigs)((0,d.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}}t.Average=h},93173(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toBigInt=function(e){if("bigint"==typeof e)return e;if("number"==typeof e){if(isFinite(e))return BigInt(e);throw new TypeError("Invalid number: "+String(e))}if("string"==typeof e){if((0,r.blank)(e))throw new TypeError("Invalid string for BigInt conversion: empty string");return BigInt(e)}throw new TypeError("Invalid type for BigInt conversion")};const r=i(22573)},20014(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BitZip=void 0,t.concatBits=function(e,t){const i=Math.pow(2,t);return e.reduce((e,t)=>e*i+(0,n.clamp)(0,i,(0,n.toInt)(t,{defaultValue:0})),0)},t.splitBits=u,t.diffConcattedBits=function(e,t,i){return(0,s.map2)(e,t,(e,t)=>(0,r.sum)((0,o.zip)(u(e,i),u(t,i)),([e,t])=>(0,n.absdiff)(e,t)))},t.isBitSet=d,t.bitZip=function(e){e.dims.forEach(e=>e.value=(0,n.clamp)(e.min,e.max,e.value));let t=0;for(let i=0;i<e.bitDepth;i++){t*=2;const r=i%e.dims.length,s=e.dims[r],n=(0,l.avg)([s.min,s.max]);s.value>n?(t+=1,s.min=n):s.max=n}return t},t.bitUnzip=function(e,t){if(t.bitDepth>52||t.bitDepth<0)return;const i=h(e);for(let e=0;e<t.bitDepth;e++){const r=e%t.dims.length,s=t.dims[r],n=(0,l.avg)([s.min,s.max]);i.includes(t.bitDepth-e-1)?s.min=n:s.max=n}return t.dims.map(e=>(0,l.avg)([e.min,e.max]))},t.bitsSetBig=h,t.countSetBits=function(e){if(!Number.isSafeInteger(e))throw new Error("Input must be a safe integer");e>>>=0;let t=0;for(;e;)e&=e-1,t++;return t},t.bits=function(e,t){return(0,r.sum)(e,(i,r)=>t(i,r)?Math.pow(2,e.length-r-1):0)};const r=i(40958),s=i(55835),n=i(31586),a=i(30976),o=i(48884),l=i(70417);function u(e,t){const i=Math.pow(2,t),r=[];for(;e>0;)r.unshift(e%i),e=Math.floor(e/i);return r}t.BitZip=class{dims;constructor(e){this.dims=e}clampValue(e){return e.map((e,t)=>(0,n.clamp)(this.dims[t].min,this.dims[t].max,e))}randomValue(){return this.dims.map(e=>(0,a.randomInt)(e.min,e.max))}zipMin(e){return this.zip(this.dims.map(e=>e.min),e)}zipMax(e){return this.zip(this.dims.map(e=>e.max),e)}zip(e,t){const i=this.dims.map(e=>e.min),r=this.dims.map(e=>e.max),s=this.clampValue(e);let n=0;for(let e=0;e<t;e++){n*=2;const t=e%i.length,a=(i[t]+r[t])/2;s[t]>a?(n+=1,i[t]=a):r[t]=a}return n}unzip(e,t){const i=this.dims.map(e=>e.min),r=this.dims.map(e=>e.max);for(let s=0;s<t;s++){const n=s%i.length,a=(i[n]+r[n])/2;d(e,t-s-1)?i[n]=a:r[n]=a}return(0,n.times)(i.length,e=>(i[e]+r[e])/2)}};const c=Math.pow(2,32)-1;function d(e,t,i){return!0!==i&&e<c&&t<32?1==(e>>t&1):1==Math.floor(e/Math.pow(2,t))%2}function h(e){return[...e.toString(2)].reverse().map((e,t)=>"1"===e?t:-1).filter(e=>-1!==e)}},84427(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dct1d=s,t.dct2d=function(e,t){const i=new Float64Array(e.length),r=new Float64Array(t);for(let n=0;n<t;n++)e.subarray(n*t,(n+1)*t).forEach((e,t)=>r[t]=e),s(r).forEach((e,r)=>i[n*t+r]=e);const n=new Float64Array(e.length);for(let e=0;e<t;e++){for(let s=0;s<t;s++)r[s]=i[s*t+e];s(r).forEach((i,r)=>n[r*t+e]=i)}return n};const r=i(23060);function s(e){const t=e.length,i=new r.FFT(2*t),s=new Float64Array(2*t);for(let i=0;i<t;i++)s[i]=e[i],s[2*t-1-i]=e[i];const n=i.createComplexArray();i.realTransform(n,s);const a=new Float64Array(t);a[0]=n[0];for(let e=1;e<t;e++)a[e]=n[2*e];return a}},42686(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DurationEstimator=void 0,t.isLandmarkJSON=o;const r=i(57975),s=i(31586),n=i(68708),a=i(3685);function o(e){return(0,n.isObject)(e)&&(0,s.isNumber)(e.x)&&(0,s.isNumber)(e.y)&&(0,s.isNumber)(e.s)&&(0,s.isNumber)(e.n)}class l{#Ji=[];#Yi;#Zi;constructor(e=15,t=.2){this.#Yi=e,this.#Zi=t}estimate(e,t){return this.#Xi(e,t)}push(e,t){(0,s.gt0)(e)&&(0,s.gt0)(t)&&this.#Qi(e,t)}#Qi(e,t){const i=this.#er(e),r=e*this.#Zi;if(null!=i&&Math.abs(i.x-e)<r){const r=i.n,s=r+1,n=i.y;i.x=(i.x*r+e)/s,i.y=n+(t-n)/s,i.s=i.s+((t-i.y)*(t-n)-i.s)/s,i.n=s}else for(this.#Ji.push({x:e,y:t,s:0,n:1}),this.#Ji.sort((e,t)=>e.x-t.x);this.#Ji.length>this.#Yi;)this.#tr()}#Xi(e,t){const i=this.#Ji;if(0===i.length)return;if(1===i.length)return this.#ir(i[0],t);const r=i.findIndex(t=>t.x>=e);if(0===r)return this.#rr(i[0],i[1],e,t);if(-1===r){const r=i.length;return this.#rr(i[r-2],i[r-1],e,t)}return this.#rr(i[r-1],i[r],e,t)}#ir(e,t){const i=Math.sqrt(Math.max(0,e.s));switch(t){case"p16":return Math.max(0,e.y-i);case"p50":return e.y;case"p69":return e.y+.5*i;case"p84":return e.y+i;case"p98":return e.y+2*i;case"p99":return e.y+3*i}}get landmarkCount(){return this.#Ji.length}get sampleCount(){return this.#Ji.reduce((e,t)=>e+t.n,0)}get n(){return this.sampleCount}get sum(){return this.#Ji.reduce((e,t)=>e+t.y*t.n,0)}get mean(){const e=this.sampleCount;if(0!==e)return this.sum/e}get variance(){const e=this.#Ji;if(0===e.length)return;if(1===e.length)return e[0].s;let t=e[0].y,i=e[0].s,r=e[0].n;for(let s=1;s<e.length;s++){const n=e[s],a=r+n.n,o=n.y-t,l=i*r+n.s*n.n+o*o*(r*n.n/a);t+=o*(n.n/a),i=l/a,r=a}return i}get stdDev(){const e=this.variance;return null==e?void 0:Math.sqrt(e)}get min(){if(0!==this.#Ji.length)return Math.min(...this.#Ji.map(e=>e.y))}get max(){if(0!==this.#Ji.length)return Math.max(...this.#Ji.map(e=>e.y))}get p84(){const e=this.mean,t=this.stdDev;if(null!=e&&null!=t)return e+t}get p16(){const e=this.mean,t=this.stdDev;if(null!=e&&null!=t)return Math.max(0,e-t)}get p50(){return this.mean}stats(){const e={n:this.sampleCount};return this.#Ji.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.#Ji=[]}toJSON(){return{maxLandmarks:this.#Yi,mergeRadiusPct:this.#Zi,landmarks:this.#Ji.map(e=>({x:e.x,y:e.y,s:e.s,n:e.n}))}}static fromJSON(e){if(!(0,n.isObject)(e))return;const t=new l((0,s.toGt0)(e?.maxLandmarks),(0,s.toGt0)(e?.mergeRadiusPct));if((0,n.isObject)(e)&&Array.isArray(e.landmarks)){for(const i of e.landmarks){if(!o(i))continue;const e=(0,s.toFloat)(i?.x),r=(0,s.toFloat)(i?.y),n=(0,s.toFloat)(i?.s)??0,a=(0,s.toInt)(i?.n)??1;null!=e&&null!=r&&e>0&&r>0&&a>0&&t.#Ji.push({x:e,y:r,s:Math.max(0,n),n:a})}t.#Ji.sort((e,t)=>e.x-t.x)}return t}merge(e){if(null==e)return this;for(const t of e.#Ji){const e=this.#er(t.x),i=t.x*this.#Zi;null!=e&&Math.abs(e.x-t.x)<i?this.#sr(e,t):(this.#Ji.push({...t}),this.#Ji.sort((e,t)=>e.x-t.x))}for(;this.#Ji.length>this.#Yi;)this.#tr();return this}#sr(e,t){const i=e.n+t.n,r=t.y-e.y,s=e.s*e.n+t.s*t.n+r*r*(e.n*t.n/i);e.x=(e.x*e.n+t.x*t.n)/i,e.y=e.y+r*(t.n/i),e.s=s/i,e.n=i}[r.inspect.custom](){return{landmarkCount:this.landmarkCount,sampleCount:this.sampleCount,stats:this.stats(),landmarks:this.#Ji.map(e=>({x:e.x,y:e.y,s:e.s,p50:this.#ir(e,"p50"),p84:this.#ir(e,"p84"),n:e.n}))}}#rr(e,t,i,r){const s=this.#ir(e,r),n=this.#ir(t,r);if(e.x===t.x)return(0,a.roundMs)((s*e.n+n*t.n)/(e.n+t.n));const o=(i-e.x)/(t.x-e.x);return(0,a.roundMs)(s+o*(n-s))}#er(e){if(0===this.#Ji.length)return;let t,i=1/0;for(const r of this.#Ji){const s=Math.abs(r.x-e);s<i&&(i=s,t=r)}return t}#tr(){if(this.#Ji.length<2)return;let e=0,t=1/0;for(let i=0;i<this.#Ji.length-1;i++){const r=this.#Ji[i+1].x-this.#Ji[i].x;r<t&&(t=r,e=i)}const i=this.#Ji[e],r=this.#Ji[e+1],s=i.n+r.n,n=r.y-i.y,a=i.s*i.n+r.s*r.n+n*n*(i.n*r.n/s),o={x:(i.x*i.n+r.x*r.n)/s,y:i.y+n*(r.n/s),s:a/s,n:s};this.#Ji.splice(e,2,o)}}t.DurationEstimator=l},23060(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FFT=void 0;const r=i(49769),s=new Map;t.FFT=class{size;_csize;table;_width;_bitrev;_out=null;_data=null;_inv=0;constructor(e){if(this.size=0|e,this.size<=1||this.size&this.size-1)throw new Error("FFT size must be a power of two and bigger than 1");this._csize=e<<1,this.table=function(e){return(0,r.getOrSet)(s,e,()=>function(e){const t=new Array(2*e);for(let i=0;i<t.length;i+=2){const r=Math.PI*i/e;t[i]=Math.cos(r),t[i+1]=-Math.sin(r)}return s.set(e,t),t}(e))}(this.size);let t=0;for(let e=1;this.size>e;e<<=1)t++;this._width=t%2==0?t-1:t,this._bitrev=new Array(1<<this._width);for(let e=0;e<this._bitrev.length;e++){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){const i=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<i}}}fromComplexArray(e,t,i){const r=t??(null!=i?new i(e.length>>>1):new Array(e.length>>>1));for(let t=0;t<e.length;t+=2)r[t>>>1]=e[t];return r}createComplexArray(e){if(null!=e){const t=new e(this._csize);for(let e=0;e<t.length;e++)t[e]=0;return t}const t=new Array(this._csize);for(let e=0;e<t.length;e++)t[e]=0;return t}toComplexArray(e,t,i){const r=t??(null!=i?new i(this._csize):this.createComplexArray());for(let t=0;t<r.length;t+=2)r[t]=e[t>>>1],r[t+1]=0;return r}completeSpectrum(e){const t=this._csize,i=t>>>1;for(let r=2;r<i;r+=2)e[t-r]=e[r],e[t-r+1]=-e[r+1]}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._out=e,this._data=t,this._inv=0,this._transform4(),this._out=null,this._data=null}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._out=e,this._data=t,this._inv=0,this._realTransform4(),this._out=null,this._data=null}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._out=e,this._data=t,this._inv=1,this._transform4();for(let t=0;t<e.length;t++)e[t]/=this.size;this._out=null,this._data=null}_transform4(){const e=this._out,t=this._csize;let i,r,s=1<<this._width,n=t/s<<1;const a=this._bitrev;if(4===n)for(i=0,r=0;i<t;i+=n,r++){const e=a[r];this._singleTransform2(i,e,s)}else for(i=0,r=0;i<t;i+=n,r++){const e=a[r];this._singleTransform4(i,e,s)}const o=this._inv?-1:1,l=this.table;for(s>>=2;s>=2;s>>=2){n=t/s<<1;const r=n>>>2;for(i=0;i<t;i+=n){const t=i+r;for(let n=i,a=0;n<t;n+=2,a+=s){const t=n,i=t+r,s=i+r,u=s+r,c=e[t],d=e[t+1],h=e[i],f=e[i+1],m=e[s],p=e[s+1],g=e[u],y=e[u+1],v=c,b=d,w=l[a],S=o*l[a+1],P=h*w-f*S,M=h*S+f*w,T=l[2*a],_=o*l[2*a+1],E=m*T-p*_,k=m*_+p*T,D=l[3*a],I=o*l[3*a+1],C=g*D-y*I,A=g*I+y*D,x=v+E,F=b+k,O=v-E,R=b-k,L=P+C,N=M+A,j=o*(P-C),B=o*(M-A),z=x+L,V=F+N,H=x-L,U=F-N,W=O+B,q=R-j,$=O-B,G=R+j;e[t]=z,e[t+1]=V,e[i]=W,e[i+1]=q,e[s]=H,e[s+1]=U,e[u]=$,e[u+1]=G}}}}_singleTransform2(e,t,i){const r=this._out,s=this._data,n=s[t],a=s[t+1],o=s[t+i],l=s[t+i+1],u=n+o,c=a+l,d=n-o,h=a-l;r[e]=u,r[e+1]=c,r[e+2]=d,r[e+3]=h}_singleTransform4(e,t,i){const r=this._out,s=this._data,n=this._inv?-1:1,a=2*i,o=3*i,l=s[t],u=s[t+1],c=s[t+i],d=s[t+i+1],h=s[t+a],f=s[t+a+1],m=s[t+o],p=s[t+o+1],g=l+h,y=u+f,v=l-h,b=u-f,w=c+m,S=d+p,P=n*(c-m),M=n*(d-p),T=g+w,_=y+S,E=v+M,k=b-P,D=g-w,I=y-S,C=v-M,A=b+P;r[e]=T,r[e+1]=_,r[e+2]=E,r[e+3]=k,r[e+4]=D,r[e+5]=I,r[e+6]=C,r[e+7]=A}_realTransform4(){const e=this._out,t=this._csize;let i,r,s=1<<this._width,n=t/s<<1;const a=this._bitrev;if(4===n)for(i=0,r=0;i<t;i+=n,r++){const e=a[r];this._singleRealTransform2(i,e>>>1,s>>>1)}else for(i=0,r=0;i<t;i+=n,r++){const e=a[r];this._singleRealTransform4(i,e>>>1,s>>>1)}const o=this._inv?-1:1,l=this.table;for(s>>=2;s>=2;s>>=2){n=t/s<<1;const r=n>>>1,a=r>>>1,u=a>>>1;for(i=0;i<t;i+=n)for(let t=0,n=0;t<=u;t+=2,n+=s){const s=i+t,c=s+a,d=c+a,h=d+a,f=e[s],m=e[s+1],p=e[c],g=e[c+1],y=e[d],v=e[d+1],b=e[h],w=e[h+1],S=f,P=m,M=l[n],T=o*l[n+1],_=p*M-g*T,E=p*T+g*M,k=l[2*n],D=o*l[2*n+1],I=y*k-v*D,C=y*D+v*k,A=l[3*n],x=o*l[3*n+1],F=b*A-w*x,O=b*x+w*A,R=S+I,L=P+C,N=S-I,j=P-C,B=_+F,z=E+O,V=o*(_-F),H=o*(E-O),U=R+B,W=L+z,q=N+H,$=j-V;if(e[s]=U,e[s+1]=W,e[c]=q,e[c+1]=$,0===t){const t=R-B,i=L-z;e[d]=t,e[d+1]=i;continue}if(t===u)continue;const G=N+-o*H,K=-o*V-j,J=R+-o*B,Y=-L- -o*z,Z=i+a-t,X=i+r-t;e[Z]=G,e[Z+1]=K,e[X]=J,e[X+1]=Y}}}_singleRealTransform2(e,t,i){const r=this._out,s=this._data,n=s[t],a=s[t+i],o=n+a,l=n-a;r[e]=o,r[e+1]=0,r[e+2]=l,r[e+3]=0}_singleRealTransform4(e,t,i){const r=this._out,s=this._data,n=this._inv?-1:1,a=2*i,o=3*i,l=s[t],u=s[t+i],c=s[t+a],d=s[t+o],h=l+c,f=l-c,m=u+d,p=n*(u-d),g=h+m,y=f,v=-p,b=h-m,w=f,S=p;r[e]=g,r[e+1]=0,r[e+2]=y,r[e+3]=v,r[e+4]=b,r[e+5]=0,r[e+6]=w,r[e+7]=S}}},57515(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.popcountBigInt=l,t.hammingBigInt=u,t.hammRatioImageHashes=function(e,t,i){if(i){const i=(1n<<64n)-1n;return 1-u(e&=i,t&=i)/64}return 1-u(e,t)/192},t.hammingDistance=c,t.binaryBits=d,t.hammPValue=h,t.hammConfidence=f,t.b64hammConfidence=function(e,t){return(0,r.blank)(e)||(0,r.blank)(t)?void 0:f((0,n.b64decode)(e),(0,n.b64decode)(t))};const r=i(22573),s=i(31586),n=i(23624),a=i(93173),o=i(48167);function l(e){let t=0;for(;e;)e&=e-1n,t++;return t}function u(e,t){return e===t?0:l(e^t)}function c(e,t){return u((0,a.toBigInt)(e),(0,a.toBigInt)(t))}function d(e){return(0,s.isNumeric)(e)?"number"==typeof e?0===(e=Math.abs(e))?1:Math.floor(Math.log2(e))+1:(e<0n&&(e=-e),0n===e?1:e.toString(2).length):0}function h(e,t){const i=(e-t/2)/Math.sqrt(t/4);return.5*(0,o.erfc)(Math.abs(i)/Math.SQRT2)}function f(e,t,i){if(null==e||null==t)return 0;const r=c(e,t);if(null==r)return 0;const n=Math.max(i??0,d(e),d(t));if(n<=0)return 0;const a=h(r,n);return(0,s.clamp)(0,1,1-a)}},75503(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.vecXvec=function(e,t){return e.map((e,i)=>e*t[i])},t.matXvec=function(e,t){return e.map((e,i)=>{if(e.length!==t.length)throw new Error("misshaped matrix on row "+i);return(0,o.sumf)(e,(e,i)=>e*t[i])})},t.slice=function(e,t,i){const s=Math.max(0,t.row),n=Math.min(e.length,i.row),a=Math.max(0,t.col),o=Math.min(e[0].length,i.col);return(0,r.range)(s,n,t=>e[t].slice(a,o))},t.index1D=function(e,t,i){return t*e.col+i},t.submatrixForEach=l,t.submatrixMagnitude=u,t.submatrixStdDev=c,t.submatrixMode=d,t.leastMagQuarter=function(e,t){const i=t.col,r=t.row,s=[u(e,t,{col:i/2,row:0},{col:i,row:r/2}),u(e,t,{col:0,row:0},{col:i/2,row:r/2}),u(e,t,{col:0,row:r/2},{col:i/2,row:r}),u(e,t,{col:i/2,row:r/2},{col:i,row:r})];return(0,n.leastIndex)(s)},t.leastVariantQuarter=function(e,t){const i=t.col,r=t.row;return(0,n.leastIndex)([c(e,t,{col:i/2,row:0},{col:i,row:r/2}),c(e,t,{col:0,row:0},{col:i/2,row:r/2}),c(e,t,{col:0,row:r/2},{col:i/2,row:r}),c(e,t,{col:i/2,row:r/2},{col:i,row:r})])},t.greatestHalf=function(e,t){const i=t.col,r=t.row,s=[d(e,t,{col:0,row:0},{col:i,row:r/2}),d(e,t,{col:0,row:0},{col:i/2,row:r}),d(e,t,{col:0,row:r/2},{col:i,row:r}),d(e,t,{col:i/2,row:0},{col:i,row:r})];return(0,n.greatestIndex)(s)},t.submatrixCollect=function(e,t,i){const r=[];return l(e,t,i,e=>r.push(e)),r},t.modeReduce=function(e,t,i){const o=Math.floor(t.col/i.col),u=Math.floor(t.row/i.row),c=new a.Average(Math.ceil(o*u));return(0,n.concat)(...(0,r.stepRange)(0,t.row,u,i=>(0,r.stepRange)(0,t.col,o,r=>(c.clear(),l(t,{col:r,row:i},{col:r+o,row:i+u},t=>(0,s.mapFinite)(e[t],e=>c.push(e))),c.sampleMode))))},t.transpose=function({data:e,dest:t,width:i,height:r}){for(let s=0;s<r;s++)for(let n=0;n<i;n++)t[n*r+s]=e[s*i+n]};const r=i(40958),s=i(31586),n=i(48884),a=i(82647),o=i(70417);function l(e,t,i,r){const s=Math.floor(Math.max(0,t.row)),n=Math.ceil(Math.min(e.row,i.row)),a=Math.floor(Math.max(0,t.col)),o=Math.ceil(Math.min(e.col,i.col));for(let t=s;t<n;t++)for(let i=a;i<o;i++)r(t*e.col+i)}function u(e,t,i,r){let n=0;return l(t,i,r,t=>(0,s.mapFinite)(e[t],e=>n+=e*e)),Math.sqrt(n)}function c(e,t,i,r){const n=new a.Average;return l(t,i,r,t=>(0,s.mapFinite)(e[t],e=>n.push(e))),n.stdDev}function d(e,t,i,r){const n=[];return l(t,i,r,t=>(0,s.mapFinite)(e[t],e=>n.push(e))),(0,o.mode)(n)}},48167(e,t){"use strict";function i(e){if(!isFinite(e))return e>0?0:2;const t=Math.abs(e),i=1/(1+.5*t),r=i*Math.exp(-t*t-1.26551223+i*(1.00002368+i*(.37409196+i*(.09678418+i*(i*(.27886807+i*(i*(1.48851587+i*(.17087277*i-.82215223))-1.13520398))-.18628806)))));return e>=0?r:2-r}Object.defineProperty(t,"__esModule",{value:!0}),t.erfc=i,t.erf=function(e){return 1-i(e)},t.combineLogOdds=function(e){if(0===e.length)throw new Error("Input array must not be empty.");if(!e.every(e=>e>=0&&e<=1))throw new Error("All confidence values must be in range [0, 1]");const t=e.reduce((e,t)=>e+Math.log(t/(1-t+1e-12)),0);return 1/(1+Math.exp(-t))},t.geometricMeanConfidence=function(e){if(0===e.length)return 0;let t=0;for(const i of e){if(i<=0)return 0;t+=Math.log(Math.min(i,1))}return Math.exp(t/e.length)}},55222(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRadix=t.AlphaRadix=t.TokenRadix=t.GeoRadix=t.Radix36=t.Base64=t.Radix58=t.Hex=t.Radix=void 0,t.encodeDigits=c;const r=i(77598),s=i(22573),n=i(55835),a=i(32639),o=i(88158),l=i(81168),u=BigInt(0);function c(e,t,i=0){if(!isFinite(t)||e<=1)return[];const r=[];if(0===t)r.unshift(0);else for(;t>0;)r.unshift(t%e),t=Math.floor(t/e);for(;r.length<i;)r.unshift(0);return r}class d{name;numerals;decodePreparser;base;constructor(e,t,i=o.identity){this.name=e,this.numerals=t,this.decodePreparser=i,this.base=t.length}digitsToNumerals(e){return e.map(e=>this.numerals[e]).join("")}encode(e,t=0){if(!isFinite(e))return"";const i=e<0;return i&&(e=Math.abs(e),t--),(i?"-":"")+this.digitsToNumerals(c(this.base,e,t))}encodeBigInt(e){if("bigint"!=typeof e)throw new Error("bad input");if(e===u)return this.numerals[0];const t=[],i=BigInt(this.base);let r=e;for(;r>u;)t.push(Number(r%i)),r/=i;return this.digitsToNumerals(t.reverse())}encodeBuffer(e){if(null==e||0===e.length)return"";const t=[0];for(let i of e)for(t.forEach((e,r)=>{i+=e<<8,t[r]=i%this.base,i=Math.floor(i/this.base)});i>0;)t.push(i%this.base),i=Math.floor(i/this.base);return this.digitsToNumerals(t.reverse())}decode(e){return(0,n.map)(this.decodeBigInt(e),t=>{if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("decode("+e+") is > 2^53");return Number(t)})}normalize(e){return this.decodePreparser(e)}decodeBigInt(e){if(null==e||(0,s.blank)(e))return;const t="-"===(e=(0,a.isFunction)(this.decodePreparser)?this.decodePreparser(e):e)[0];t&&(e=e.slice(1));const i=BigInt(this.base);let r=BigInt(0);for(const t of e){const e=this.numerals.indexOf(t);if(e<0)return;r=r*i+BigInt(e)}return t?BigInt(-1)*r:r}randomChars(e){return this.encodeBuffer((0,r.randomBytes)(Math.ceil(Math.log2(this.base)*(e+4)/8))).slice(2,2+e)}randomUid(e=20,t=5,i="-"){return(0,l.splitEvery)(this.randomChars(e),t).join(i)}tokenEql(e,t,i){const r=this.normalizeToken(e),s=this.normalizeToken(t);return r.length>=i&&r===s}normalizeToken(e){return[...this.decodePreparser(e.trim())].filter(e=>this.numerals.includes(e)).join("")}}t.Radix=d,t.Hex=new d("hex","0123456789abcdef",e=>e.toLowerCase()),t.Radix58=new d("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.Base64=new d("Radix64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t.Radix36=new d("Radix36","0123456789abcdefghijklmnopqrstuvwxyz",e=>e.toLowerCase()),t.GeoRadix=new d("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",e=>e.toLowerCase()),t.TokenRadix=new d("TokenRadix","0123456789abcdefghjkmnpqrtuvwxyz",e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/s/g,"5")),t.AlphaRadix=new d("AlphaRadix","abcdefghjkmnopqrtuvwxyz",e=>e.toLowerCase().replace(/0/g,"o").replace(/2/g,"z").replace(/5/g,"s").replace(/9/g,"g")),t.NumericRadix=new d("NumericRadix","0123456789",e=>e.toLowerCase().replace(/o/g,"0").replace(/[il]/g,"1").replace(/z/g,"2").replace(/s/g,"5").replace(/g/g,"9"))},976(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Rate=void 0;const r=i(42659),s=i(31586);class n{periodMs;warmupMs;#nr=performance.now();#ar=performance.now();#or=0;#lr=0;#ur=0;#cr=null;#G=null;constructor(e=r.minuteMs,t=r.secondMs){this.periodMs=e,this.warmupMs=t,this.#dr()}#dr(){this.#hr(),this.#G=setInterval(()=>this.#fr(),this.periodMs),this.#G.unref()}#hr(){null!=this.#G&&(clearInterval(this.#G),this.#G=null)}#fr(){this.#lr=this.#or,this.#or=0,this.#ar=performance.now()}onEvent(){this.#ur++,this.#or++,this.#cr=performance.now()}get eventCount(){return this.#ur}get msSinceLastEvent(){return null==this.#cr?null:performance.now()-this.#cr}#mr(){return null!=this.#cr&&performance.now()-this.#nr>=this.warmupMs}#pr(){return Math.min(this.periodMs,performance.now()-this.#nr)}#gr(){const e=performance.now()-this.#ar,t=Math.max(0,this.periodMs-e)/this.periodMs;return this.#lr*t+this.#or}get eventsPerMs(){if(!this.#mr())return 0;const e=this.#gr();return 0===e?0:e/this.#pr()}get eventsPerSecond(){return this.eventsPerMs*r.secondMs}get eventsPerMinute(){return this.eventsPerMs*r.minuteMs}clear(){return this.#nr=performance.now(),this.#ar=performance.now(),this.#or=0,this.#lr=0,this.#cr=null,this.#ur=0,this.#dr(),this}stats(){return{eventCount:this.eventCount,eventsPerSecond:(0,s.sigFigs)(this.eventsPerSecond,2),msSinceLastEvent:this.msSinceLastEvent}}[Symbol.dispose](){this.#hr()}}t.Rate=n},56946(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RomanNumerals=void 0,t.romanToInt=function(e){const i=t.RomanNumerals.indexOf(e);return-1===i?void 0:i},t.intToRoman=function(e){return t.RomanNumerals[(0,r.toInt)(e)]??(0,s.toS)(e)};const r=i(31586),s=i(54993);t.RomanNumerals=[void 0,"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII","XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX","XL","XLI","XLII","XLIII","XLIV","XLV","XLVI","XLVII","XLVIII","XLIX","L","LI","LII","LIII","LIV","LV","LVI","LVII","LVIII","LIX","LX"]},70417(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Mean=void 0,t.min=function(e){let t;for(const i of e)(0,n.isComparable)(i)&&(null==t||i<t)&&(t=i);return t},t.max=function(e){let t;for(const i of(0,a.toA)(e))(0,n.isComparable)(i)&&(null==t||i>t)&&(t=i);return t},t.deltas=function(e){if(null==e||e.length<=1)return[];const t=new Array(e.length-1);for(let i=1;i<e.length;i++)t[i-1]=e[i]-e[i-1];return t},t.modes=c,t.mode=function(e){return c(e,1)[0]},t.sum=function(e){let t=0;for(const i of e??[])(0,s.isNumber)(i)&&(t+=i);return t},t.sumf=d,t.avg=f,t.slope=function(e){const t=(0,a.toA)(e).filter(s.isNumber),i=f(t);if(null!=i){const e=(t.length-1)/2,r=d(t,(t,r)=>(t-i)*(r-e)),s=d(t,e=>(e-i)**2);return 0===s?0:r/s}},t.variance=m,t.stdDev=function(e){return(0,r.map)(m(e),Math.sqrt)},t.p84=function(e){return(new u.Average).pushAll(e).p84},t.ema=function(e,t=.5){if(0===e.length)throw new Error("values must contain at least one number");if(!(t>0&&t<=1))throw new Error("carryForward must be in the range (0, 1]");const i=1-t;let r=e[0];for(let s=1;s<e.length;s++)r=t*r+i*e[s];return r},t.weightedMean=function(e){if(0===e.length)throw new Error("samples must contain at least one element");let t=0,i=0;for(const{value:r,weight:s}of e){if(s<0)throw new Error("weights must be non‑negative");if(!isFinite(s)||!isFinite(r))throw new Error("values and weights must be finite numbers");0!==s&&(i+=s,t+=s*(r-t)/i)}if(0===i)throw new Error("total weight must be greater than zero");return t},t.euclidean=function(e,t){return Math.sqrt((0,a.toA)(e).reduce((e,i,r)=>e+Math.pow(i-t[r],2),0))},t.centroid=function(e){if(!e.length)return[];const t=e[0].length,i=new Array(t).fill(0);let r=0;for(const n of e){r++;for(let e=0;e<t;e++)(0,s.isNumber)(n[e])&&(i[e]+=n[e])}return i.map(e=>e/r)},t.l2norm=p,t.dot=g,t.cosineSimilarity=function(e,t){const i=p(e),r=p(t);return(0,s.toFinite)(g(e,t)/(i*r))},t.jaccard=function(e,t){return null==e||0===e.length||null==t||0===t.length?0:(0,s.toFinite)((0,l.intersection)(e,t).size/(0,l.union)(e,t).size)},t.median=function(e){if(0===e.length)throw new Error("medianOfArray: empty array");const t=[...e].sort((e,t)=>e-t),i=t.length>>1;return 1&t.length?t[i]:(t[i-1]+t[i])/2};const r=i(55835),s=i(31586),n=i(34666),a=i(59455),o=i(22454),l=i(77377),u=i(82647);function c(e,t){if(null==e)return[];const i=new o.CountingSet;for(const t of e)(0,s.isNumber)(t)&&i.incr(t);return i.topKeys(t)}function d(e,t){let i=0,r=0;for(const n of e){if(null!=n){const e=t(n,i);(0,s.isNumber)(e)&&(r+=e)}i++}return r}class h{#yr=0;#vr;push(e){(0,s.isNumber)(e)&&(this.#vr=null==this.#vr?e:this.#vr*this.#yr/(this.#yr+1)+e/(this.#yr+1),this.#yr++)}get mean(){return this.#vr}}function f(e){if(null!=e){if(Array.isArray(e)){const t=e.length;if(0===t)return;let i=0,r=0;for(let n=0;n<t;++n){const t=e[n];(0,s.isNumber)(t)&&(r++,i+=(t-i)/r)}return r>0?i:void 0}{const t=new h;for(const i of e)t.push(i);return t.mean}}}function m(e){if(null==e)return;const t=f(e);if(null==t)return;let i=0,r=0;for(const n of e)(0,s.isNumber)(n)&&(r++,i+=(n-t)*(n-t));return i/r}function p(e){let t=0;for(const i of e)t+=i*i;return Math.sqrt(t)}function g(e,t){let i=0;for(let r=0;r<e.length;r++)i+=e[r]*t[r];return i}t.Mean=h},23624(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gz64decodeString=void 0,t.hex2b64=n,t.b64encode=a,t.b64encodeBits=function(e){return s(e,"b64encodeBits"),a(BigInt("0b0"+e.join("")))},t.b64encodeBitsFixedWidth=function(e,t){if(e.length!==t)throw new TypeError(`b64encodeBitsFixedWidth: expected ${t} bits but got ${e.length}`);return s(e,"b64encodeBitsFixedWidth"),o(BigInt("0b0"+e.join("")),t)},t.b64encodeBigIntFixedWidth=o,t.b64decode=l,t.b64toHex=function(e){return Buffer.from(e,"base64").toString("hex")},t.b64toBuffer=function(e){return Buffer.from(e,"base64")},t.b64decodeToBits=function(e,t){const i=l(e);if(i>(1n<<BigInt(t))-1n)throw new TypeError(`b64decodeToBits: value requires more than ${t} bits`);const r=[];for(let e=t-1;e>=0;e--)r.push(i>>BigInt(e)&1n?1:0);return r},t.gz64encodeString=function(e){return(0,r.gzipSync)(Buffer.from(e,"utf8")).toString("base64")},t.d=u;const r=i(38522);function s(e,t){for(let i=0;i<e.length;i++)if(0!==e[i]&&1!==e[i])throw new TypeError(`${t}: invalid argument: bits[${i}] must be 0 or 1`)}function n(e){return e.length%2==1&&(e="0"+e),Buffer.from(e,"hex").toString("base64")}function a(e){return n(e.toString(16))}function o(e,t){const i=2*Math.ceil(t/8);let r=e.toString(16);return r.length<i&&(r="0".repeat(i-r.length)+r),Buffer.from(r,"hex").toString("base64")}function l(e){const t=Buffer.from(e,"base64");return BigInt("0x0"+t.toString("hex"))}function u(e){return(0,r.gunzipSync)(Buffer.from(e,"base64")).toString("utf8")}t.gz64decodeString=u},57643(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpPort=void 0,t.DefaultHttpPort=1787},12084(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isTcpSocketConnectOpts=function(e){return(0,s.isObject)(e)&&(0,r.gt0)(e.port)};const r=i(31586),s=i(68708)},43205(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.userAgent=async function(){return l.Settings.allowUserAgent.valueOrDefault?c():u()},t.simpleUserAgent=u,t.systemUserAgent=c;const r=i(72993),s=i(17344),n=i(96175),a=i(37805),o=i(81674),l=i(28874);function u(){return r.SimpleAppName+a.version}async function c(){return u()+" ("+(0,n.osFullName)()+") "+(0,s.EditionType)().toLowerCase()+"/"+await(0,o.t)()}},72308(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.networkMacAddresses=t.myIpAddresses=void 0,t.myExternalIpAddresses=f,t.myExternalIp4Addresses=function(){return f().filter(e=>!e.includes(":"))},t.isLoopback=g,t.isLocalhost=function(e){return m().tap({msg:"isLocalhost",level:"info",result:!(0,a.blank)(e)&&((0,t.myIpAddresses)().includes(e)||(0,t.myIpAddresses)().includes((0,h.stripPrefix)(e,"::ffff:"))||g(e)),meta:{address:e}})};const r=i(48161),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(96249),u=i(31586),c=i(68708),d=i(50213),h=i(81168);function f(){return(0,t.myIpAddresses)().filter(e=>!g(e))}t.myIpAddresses=(0,s.lazy)(()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map(e=>e.address))),o.minuteMs),t.networkMacAddresses=(0,s.lazy)(()=>(0,n.uniq)((0,n.compactBlanks)((0,l.flatten)((0,c.values)((0,r.networkInterfaces)())).map(e=>e.mac))).filter(e=>"00:00:00:00:00:00"!==e),o.minuteMs);const m=(0,s.lazy)(()=>(0,d.mkLogger)("net.ip")),p=[/^(?:::ffff:)?127\.\d{1,3}.\d{1,3}.\d{1,3}$/i,/^::1$/];function g(e){return(0,a.notBlank)(e)&&(127===function(e){const t=e.split(".").map(e=>(0,u.toIntWithin)(e,0,255));return 4!==t.length||t.some(e=>null==e)?void 0:t}(e)?.[0]||p.some(t=>null!=t.exec(e)))}},96128(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nslookup=t.resolve4=t.friendlyName=void 0,t.isLoopback=b,t.octets=w,t.isEquivalentHost=async function(e,i){if((0,n.blank)(e)||(0,n.blank)(i))return!1;if((0,p.equalsIgnoreCase)(e,i))return!0;if(b(e)&&b(i))return!0;const r=await(0,t.resolve4)(e);if(null==r)return!1;const s=await(0,t.resolve4)(i);return null!=s&&r.some(e=>s.includes(e))};const r=i(40610),s=i(19851),n=i(22573),a=i(42659),o=i(31586),l=i(13538),u=i(83104),c=i(54993),d=i(55139),h=i(50213),f=i(97352),m=i(45255),p=i(81168),g=i(26293),y=new RegExp("^"+g.ipv4Re.source+"$");t.friendlyName=(0,d.memoize)(async e=>{const i=null==y.exec(e)?e:await(0,t.nslookup)(e);return(0,c.toS)(i).toLowerCase().normalize()},{name:"net.friendlyName",maxSize:128,timeoutMs:m.ShortCommandTimeoutMs});const v=/^(?:localhost\.?(?:localdomain\.?)?|127(?:\.\d{1,3}){3})$/i;function b(e){return null!=v.exec(e)}function w(e){const t=e.split(".").map(e=>(0,o.toInt)(e)).filter(e=>(0,f.within)(0,255,e));return 4===t.length?t:void 0}t.resolve4=(0,d.memoize)(async e=>{if(!(0,n.blank)(e)){if(null!=w(e))return[e];try{return await r.promises.resolve4(e)}catch(t){return void S().warn("No name found for "+e)}}},{name:"net.resolve4",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs});const S=(0,s.lazy)(()=>(0,h.mkLogger)("net.nslookup"));t.nslookup=(0,d.memoize)(async e=>{try{const t=await(0,l.thenOrTimeout)(b(e)?e.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=w(e)?r.promises.reverse(e):r.promises.resolve4(e),5*a.secondMs);if(t===u.Timeout)return S().info("nslookup("+e+"): timeout"),e;const i=t.find(n.notBlank);return null==i?(S().warn("No name found for "+e),e):i}catch(t){return S().warn("Failed to look up name",{nameOrIp:e,error:t}),e}},{name:"net.nslookup",maxSize:256,timeoutMs:m.ShortCommandTimeoutMs,clearEveryMs:10*a.minuteMs})},26293(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipAddrFromPing=t.ipv4Re=t.ping=void 0;const r=i(22573),s=i(42659),n=i(31586),a=i(97790),o=i(54993),l=i(55139),u=i(84777),c=i(8103),d=i(43334),h=i(45255);t.ping=(0,l.memoize)(async e=>{const t=d.isWin?(0,c.pingWin)():"ping";return(0,u.stdout_)(t,[d.isWin?"-n":"-c","1",e],{timeoutMs:5*s.secondMs})},{name:"net.ping",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs}),t.ipv4Re=new RegExp("\\b"+(0,n.times)(4,()=>"[0-9]{1,3}").join("\\.")+"\\b"),t.ipAddrFromPing=(0,l.memoize)(async e=>(0,a.opt)(await(0,t.ping)(e).catch(e=>{console.warn("failed to ping: "+e)})).filter(r.notBlank).flatMap(e=>t.ipv4Re.exec((0,o.toS)(e))).map(e=>e[0]).get(),{name:"net.ipAddrFromPing",maxSize:255,timeoutMs:h.ShortCommandTimeoutMs,clearEveryMs:10*s.minuteMs})},78330(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.aptInstalledVersion=async function(e){if(!(0,o.hasApt)())return;const t=[];for(const i of(0,r.compactBlanks)(await async function(e){if(!(0,o.hasApt)()||(0,s.blank)(e))return;const t=await(0,l.stdoutResult_)("dpkg",["-S",e],{timeoutMs:(0,d.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});return h().debug("dpkg -S",{file:e,result:t}),0!==t.code?void 0:(0,r.uniq)((0,u.splitLines)(t.result).map(e=>f.exec(e)?.[0]))}(e))){const e=await m(i);t.push({pkg:i,version:e,semver:(0,c.toSemVer)(e)})}return h().tap({msg:"aptInstalledVersion("+e+")",result:t})},t.aptCachePolicyVersion=m;const r=i(40958),s=i(22573),n=i(45599),a=i(50213),o=i(96175),l=i(84777),u=i(84542),c=i(76280),d=i(63870),h=(0,n.defer)(()=>(0,a.mkLogger)("platform.Apt")),f=/^[a-z][a-z\d+\-.]+/;async function m(e){if(!(0,o.hasApt)()||(0,s.blank)(e))return;const t=await(0,l.stdoutResult_)("apt-cache",["policy",e],{timeoutMs:(0,d.commandTimeoutMs)(),ignoreExitCode:!0,ignoreStderr:!0,isIgnorableError:()=>!0});if(h().debug("apt-cache policy",{packageName:e,result:t}),0===t.code)for(const e of(0,u.splitLines)(t.result)){const t=/^\s*Installed: (.*)$/.exec(e);if(null!=t)return t[1]}}},89206(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isChildProcess=void 0;const r=i(19851),s=i(38639),n=i(59958);t.isChildProcess=(0,r.lazy)(()=>(0,s.isTrue)(process.env[n.PS_IS_CHILD_PROCESS]))},45969(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDocker=void 0;const r=i(73024),s=i(38639),n=i(19851),a=i(59958),o=i(43334);t.isDocker=(0,n.lazy)(()=>o.isLinux&&((0,s.toBoolean)(process.env[a.PS_IS_DOCKER])??(0,r.existsSync)("/.running-in-container")))},29325(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPacked=void 0;const r=i(38639),s=i(45599),n=i(59958);t.isPacked=(0,s.defer)(()=>{const e=(0,r.toBoolean)(process.env[n.PS_IS_PACKED]);return null==e||e})},46305(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hasPacman=void 0,t.pacmanInstalledVersion=async function(e){if((0,t.hasPacman)())try{const t=d((await(0,n.stdoutResult_)("pacman",["-Qo",e],{timeoutMs:(0,o.commandTimeoutMs)(),ignoreExitCode:!1,ignoreStderr:!1,isIgnorableError:()=>!0,env:{LC_ALL:"C",LOCALE:"C"}})).result);return u().tap({msg:"pacmanInstalledVersion("+e+")",result:t,meta:{nativePathOrBasename:e}})}catch(t){return void u().debug("pacman doesn't seem to know about "+e,{error:t})}},t.parsePacmanQo=d;const r=i(45599),s=i(50213),n=i(84777),a=i(68284),o=i(63870),l=i(43334),u=(0,r.defer)(()=>(0,s.mkLogger)("platform.Pacman"));t.hasPacman=(0,r.defer)(()=>l.isLinux&&(0,a.isNonEmptyFileSync)("/etc/pacman.conf"));const c=/is owned by (?<pkg>\S+) (?<version>\S+)/i;function d(e){return e.match(c)?.groups}},43334(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.platformArch=t.platformName=t.isElectron=t.isMainElectron=t.isCaseSensitiveFs=t.isPosix=t.isLinux_arm=t.isArm=t.isLinux_x64=t.isLinux=t.isMac=t.isWinPortable=t.isWin=t.isCI=t.inspectFlag=void 0;const s=r(i(48161)),n=r(i(1708)),a=i(22573),o=i(38639),l=i(30301),u=i(59958),c=s.default.platform();t.inspectFlag=n.default.argv.includes("--inspect")||(0,o.isTrue)(n.default.env.NODE_INSPECT),t.isCI=(0,o.isTrue)(n.default.env.CI),t.isWin="win32"===c||"cygwin"===c,t.isWinPortable=t.isWin&&(0,a.notBlank)(n.default.env.PORTABLE_EXECUTABLE_DIR),t.isMac="darwin"===c,t.isLinux="linux"===c,t.isLinux_x64=t.isLinux&&"x64"===s.default.arch(),t.isArm=null!=/^arm\b/i.exec(s.default.arch()),t.isLinux_arm=t.isLinux&&t.isArm,t.isPosix=t.isMac||t.isLinux,t.isCaseSensitiveFs=t.isLinux,t.isMainElectron=null!=n.default.versions.electron&&!(0,o.isTrue)(n.default.env[u.ELECTRON_RUN_AS_NODE])&&"1"!==n.default.env[u.PS_IS_UTILITY_PROCESS],t.isElectron=(0,l.lazy)(()=>(0,o.isTrue)(n.default.env[u.PS_IS_ELECTRON])||null!=n.default.versions.electron||(0,o.isTrue)(n.default.env[u.ELECTRON_RUN_AS_NODE])),t.platformName=t.isWin?"win":t.isMac?"mac":t.isLinux?"linux":c,t.platformArch=t.platformName+"-"+s.default.arch()},74041(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.platformFolders=void 0;const r=i(34589),s=i(76760),n=i(22573),a=i(68708),o=i(50989),l=i(5916),u=i(32551),c=i(6012),d=i(72544),h=i(45879),f=i(24399),m=i(43334),p=(0,o.strEnum)("desktop","documents","download","pictures","videos");t.platformFolders=(0,l.lazyAsync)({desc:"PlatformFolders",later:async()=>m.isLinux?async function(){const e={XDG_DOCUMENTS_DIR:"$HOME/Documents",XDG_DESKTOP_DIR:"$HOME/Desktop",XDG_DOWNLOAD_DIR:"$HOME/Downloads",XDG_MUSIC_DIR:"$HOME/Music",XDG_PICTURES_DIR:"$HOME/Pictures",XDG_VIDEOS_DIR:"$HOME/Videos"},t=(0,d.xdg_config_home)(),i=(0,u.homeDir)(),r=(0,s.join)(t,"user-dirs.dirs"),o=await(0,h.readFileMaybe)(r),l=(0,c.parseEnvTokens)({input:o?.toString(),lowerCaseKeys:!1});l.XDG_DOWNLOAD_DIR??=l.XDG_DOWNLOADS_DIR;for(const[t,i]of(0,a.entries)(l))(0,n.blank)(i)||(e[t]=i);for(const[t,r]of(0,a.entries)(e))(0,n.blank)(r)?delete e[t]:r.startsWith("$HOME")&&(e[t]=r.replace("$HOME",i));const f={};for(const t of p.values)f[t]=e[("XDG_"+t+"_DIR").toUpperCase()];return f}():m.isWin?async function(){const e=f.PowerShell.ensureInstance();return{desktop:await e.getWindowsPath("Desktop"),documents:await e.getWindowsPath("MyDocuments"),download:await e.executeJson("(New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path"),pictures:await e.getWindowsPath("MyPictures"),videos:await e.getWindowsPath("MyVideos")}}():m.isMac?function(){const e=(0,u.homeDir)();return{desktop:(0,s.join)(e,"Desktop"),documents:(0,s.join)(e,"Documents"),download:(0,s.join)(e,"Downloads"),pictures:(0,s.join)(e,"Pictures"),videos:(0,s.join)(e,"Movies")}}():(0,r.fail)("Unsupported platform")})},39951(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sdNotifyVersion=void 0,t.sdNotifyAvailable=l,t.sdNotifyReady=function(){u("READY=1")},t.sdNotifyStopping=function(){!function(...e){if(l())try{(0,s.execFileSync)("systemd-notify",e,{timeout:1e3})}catch{}}("STOPPING=1")},t.sdNotifyWatchdog=function(){u("WATCHDOG=1")},t.sdNotifyStatus=function(e){u("STATUS="+e)},t.sdNotifyMajorVersion=function(){const e=(0,t.sdNotifyVersion)();if(null==e)return;const i=/^systemd\s+(\d+)/.exec(e);return null!=i?parseInt(i[1],10):void 0};const s=i(31421),n=r(i(1708)),a=i(19851),o=i(43334);function l(){return o.isLinux&&null!=n.default.env.NOTIFY_SOCKET}function u(...e){if(l())try{(0,s.execFile)("systemd-notify",e,{timeout:5e3},e=>{})}catch{}}t.sdNotifyVersion=(0,a.lazy)(()=>{if(o.isLinux)try{const e=(0,s.execFileSync)("systemd-notify",["--version"],{timeout:2e3});return e.toString().split("\n")[0]?.trim()}catch{return}})},24540(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.procDeviceModel=t.isRaspberryPi=void 0,t.containsRpiModel=o;const s=r(i(73024)),n=i(19851),a=i(43334);function o(e="/proc/cpuinfo"){if(a.isWin||a.isMac)return!1;try{return null!=s.default.readFileSync(e).toString().match(/^\s*model\s*:\s*Raspberry Pi/im)}catch{return!1}}t.isRaspberryPi=(0,n.lazy)(()=>a.isLinux_arm&&o()),t.procDeviceModel=(0,n.lazy)(()=>{try{return a.isLinux?s.default.readFileSync("/proc/device-tree/model").toString():void 0}catch{return}})},94137(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.negateFilterName=function(e){if((0,r.blank)(e))return;const t=/\s/.test(e)?e:(0,n.camel2words)(e).replace(/\bphoto structure\b/gi,"PhotoStructure");return t.match(/^not\b/)?t.replace(/^not\b/,"").trim():"not "+(0,s.stripPrefix)(t,"is ")};const r=i(22573),s=i(51926),n=i(83556)},78984(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Predicates=void 0;const r=i(19851),s=i(40958),n=i(68708),a=i(51926),o=i(50213),l=i(94137),u=(0,r.lazy)(()=>(0,o.mkLogger)("predicates.Predicates"));class c{static async accepted(e,...t){for(const i of t)for(const t of(0,n.values)(i)){const i=await t(e);if(!1===i||(0,a.isString)(i))return!1}return!0}static async rejected(e,...t){return!await c.accepted(e,...t)}static async explain(e,...t){const i=[],r=[],s=[];for(const o of t)for(const[t,l]of(0,n.entries)(o)){const n=await l(e);!0===n?i.push(t):!1===n||(0,a.isString)(n)?r.push(t):s.push(t)}return{accepted:i,rejected:r,notApplicable:s}}static async whyRejected(e,...t){for(const i of t)for(const[t,r]of(0,n.entries)(i))try{const i=await r(e);if(null==i||!0===i)continue;return(0,a.isString)(i)?i:(0,l.negateFilterName)(t)}catch(e){u().warn("whyRejected() caught from "+t,{error:e})}}static async logged({a:e,logger:t,msg:i,predicates:r}){const{accepted:n,rejected:a}=await c.explain(e,...r);return t.tap({msg:i,result:(0,s.isEmpty)(a),meta:{a:e,accepted:n,rejected:a}})}}t.Predicates=c},33995(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncPredicates=void 0;const r=i(68708),s=i(94137);class n{static firstFalse(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!1===s(e))return t}static firstTrue(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i))if(!0===s(e))return t}static firstDefined(e,...t){for(const i of t)for(const[t,s]of(0,r.entries)(i)){const i=s(e);if(null!=i)return{name:t,result:i}}}static accepted(e,...t){return null==n.firstFalse(e,...t)}static whyRejected(e,...t){return(0,s.negateFilterName)(n.firstFalse(e,...t))}}t.SyncPredicates=n},45643(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pidExists=void 0,t.existingPids=function(e){return(0,s.toA)(e).filter(e=>(0,r.pidExists)(e))},t.waitForPidExit=function(e,t){return(0,n.untilTrue)(()=>!(0,r.pidExists)(e),{timeoutMs:t,intervalMs:250})};const r=i(58587);Object.defineProperty(t,"pidExists",{enumerable:!0,get:function(){return r.pidExists}});const s=i(59455),n=i(31562)},95402(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Pids=void 0,t.killPid=L,t.addPid=function(e,t){return N.instance()?.addPid_(e,t)};const s=i(58587),n=r(i(31421)),a=r(i(1708)),o=i(40958),l=i(22573),u=i(42659),c=i(55835),d=i(31586),h=i(97790),f=i(59455),m=i(54993),p=i(54557),g=i(19851),y=i(50213),v=i(88158),b=i(409),w=i(23560),S=i(78406),P=i(25764),M=i(99331),T=i(46292),_=i(8769),E=i(83278),k=i(32144),D=i(29882),I=i(43334),C=i(24399),A=i(58261),x=(0,g.lazy)(()=>(0,y.mkLogger)("proc.Pids")),F=10*u.secondMs;function O(e,t){if(null==e||null==t||e.pid!==t.pid)return!1;const i=(0,c.map)(t.start,e=>e.getTime()),r=e.startTime;return(0,d.gt0)(i)&&(0,d.gt0)(r)&&Math.abs(i-r)<F}function R(e,t=!1){const i=["/PID",(0,m.toS)((0,d.toInt)(e)),"/T"];t&&i.push("/F"),n.default.execFile("taskkill",i)}async function L(e,t=!1,i=!0){return(0,d.gt0)(e)?1===e?x().warn("killPid(): refusing to kill init",{pid:e}):e===a.default.pid||e===a.default.ppid?x().warn("killPid(): cannot self-terminate",{pid:e}):(x().log(t?"warn":"debug","killPid",{pid:e,force:t}),t&&i&&await(N.instance()?.onKill(e)),I.isWin?async function(e,t=!1){if((0,M.ending)()||C.PowerShell.instance().ended)R(e,t);else try{const i=(0,o.compact)(["Stop-Process","-Id",(0,d.toInt)(e),t?"-Force":void 0]).join(" ");await C.PowerShell.instance().execute(i,v.identity)}catch(i){x().warn("killWin(): pwsh error, using TASKKILL",{error:i}),R(e,t)}}(e,t):async function(e,t=!1){try{a.default.kill(e,t?"SIGKILL":"SIGTERM")}catch(e){if(!String(e).includes("ESRCH"))throw e}}(e,t)):x().warn("killPid(): invalid pid",{pid:e})}class N extends S.EndableInterval{pidsDir;static instance=(0,g.lazy)(()=>(0,c.map)((0,T.configDir)(),e=>new N(E.BaseFile.for(e).join("pids"))));#br=new p.FifoCache({maxSize:256});constructor(e){super({name:"proc.Pids",intervalMs:(0,w.isSyncService)()?5*u.minuteMs:0,initialDelayMs:u.minuteMs,callback:()=>this.killOldProcs(),rank:P.EndableRanks.postdb}),this.pidsDir=e,null==this.pidsDir.mkdirpSync()&&x().warn("Failed to create PID directory",{pidsDir:this.pidsDir.nativePath})}async addPid_(e,t,i=!1){if(null==e)throw new Error("undefined info");const r=e.pid;if(!(0,d.gt0)(r))throw new Error("undefined pid");const n=e.ppid+":"+e.pid;i&&this.#br.delete(n);const a=this.#br.getOrSet(n,async()=>{if(!(0,s.pidExists)(r))throw x().debug("addPid(): no-op, pid already gone during write",{info:e,start:t}),new Error("Process no longer exists");const i=this.#wr(e.pid),n=(0,h.opt)((0,v.Try)(()=>(0,D.parseNativePath)(e.cmd).base)).filter(l.notBlank).getOrElse(()=>e.cmd),a=t.getTime(),o={...e,cmd:n,startTime:a};try{return await i.writeJson_(o),x().debug("addPid() wrote "+i,o),i}catch(e){throw x().warn("addPid(): failed to write pidfile",{error:e,pid:r,file:i.nativePath}),e}});return a instanceof Promise?a.catch(e=>{if(!String(e).includes("Process no longer exists"))throw e;this.#br.delete(n)}):a}#wr(e){return this.pidsDir.join(e+".json")}pidfiles(){return this.pidsDir.clear().children(e=>{const t=(0,d.toInt)(e.name);return".json"===e.ext&&null!=t&&t!==a.default.pid})}async pids(e=this.pidfiles()){return(0,o.compact)((0,f.toA)(await e).map(e=>(0,d.toInt)(e.name)))}async onKill(e){const t=this.#wr(e),i=await t.readJson();if(null!=i)return this.addPid_({...i,timeoutMs:1},(0,u.ago)(u.minuteMs),!0).catch(t=>{x().info("onKill(): failed to rewrite pidfile",{pid:e,error:t})})}vacuumOldWip=(0,b.rateLimited)({name:"Pids.vacuumOldWip()",minCallDelayMs:u.minuteMs,f:async()=>{const e=Date.now()-2*u.minuteMs,t=await this.pidsDir.childFiles(async t=>(0,k.isJsonExt)(t)&&(0,D.isHiddenBasename)(t.base)&&(0,d.lt)(t.mtimeMs(),e));for(const e of(0,f.toA)(t))x().warn("killOldProcs(): deleting old pid WIP, "+e.base),await e.unlink("debug")}});killOldProcs=(0,b.rateLimited)({name:"Pids.killOldProcs()",minCallDelayMs:u.minuteMs,f:async(e={})=>{x().info("killOldProcs()",e),await this.vacuumOldWip();const t=e.everything??!1,i=e.force??I.isWin,r=await this.pidfiles(),s=await this.pids(r??[]);if((0,o.isEmpty)(s))return x().info("killOldProcs(): no pidfiles"),[];const n=[],a=[],l=await(0,A.pidInfos)(s);if(null!=l){for(const s of r){const r=await s.readJson();if(null==r){x().warn("killOldProcs(): failed to read pidfile "+s.base),await s.unlink("debug");continue}const o=r.pid;if(!(0,d.gt0)(o)){x().warn("killOldProcs(): invalid json.pid: unlinking pidfile "+s.base,{json:r,pid:o}),await s.unlink("debug");continue}const u=l.find(e=>e.pid===o);if(null==u||!O(r,u)){x().debug("killOldProcs(): pid no longer present: unlinking "+s.base,{json:r,pidEntry:u}),await s.unlink("debug"),n.push(r);continue}const c=(0,d.gt0)(r.timeoutMs)?r.startTime+r.timeoutMs:void 0,h=t?"all pids are being shut down":(0,d.gt)(Date.now(),c)?`timed out ${Date.now()-c} ms ago`:(0,d.lt)(r.startTime,e.everythingBefore)?"cleanup everything before "+new Date(e.everythingBefore).toISOString():void 0;null!=h&&(x().info("killOldProcs(): killing",{reason:h,json:r}),a.push(L(o,i,!1)),n.push({...r,...u}))}return a.length>0&&await Promise.allSettled(a),n}(0,_.onError)("Pids.killOldProcs(): failed to get process information")}})}t.Pids=N},58261(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isProcEntry=_,t.pidInfo=async function(e){const t=await E([e]);return null==t?void 0:(0,h.toA)(t).find(t=>t.pid===e)},t.notExistingPids=async function(e){if((0,l.isEmpty)(e))return[];const t=(0,M.existingPids)(e);if(null==t)return;const i=[o.default.pid,...t];return e.filter(e=>!i.includes(e))},t.pidInfos=E,t.parseProcStat=N;const s=i(31421),n=i(73024),a=i(48161),o=r(i(1708)),l=i(40958),u=i(22573),c=i(42659),d=i(31586),h=i(59455),f=i(54993),m=i(48884),p=i(53507),g=i(19851),y=i(50213),v=i(84777),b=i(68440),w=i(45879),S=i(43334),P=i(24399),M=i(45643),T=(0,g.lazy)(()=>(0,y.mkLogger)("proc.ps"));function _(e){return null!=e&&(0,d.gt0)(e.pid)&&null!=e.start&&(0,u.notBlank)(e.cmd)}async function E(e){if(S.isLinux)return async function(e){const t=[];for(const i of e)t.push(N(await(0,w.readFileMaybe)("/proc/"+i+"/stat")));return T().tap({msg:"pidInfoProc",result:(0,l.compact)(t)})}(e);const t=(0,M.existingPids)(e),i=(await(0,m.collectBatchedAsync)(t,20,S.isWin?C:x)).filter(e=>_(e)&&t.includes(e.pid));return T().tap({msg:"pidInfos()",result:i,meta:{pids:e}})}const k="Get-Process",D="| Select-Object -Property Id,ProcessName,StartTime";function I(e){return(0,l.uniq)([...e.filter(d.gt0),o.default.pid]).join(",")}async function C(e){if(P.PowerShell.instance().ended)return;const t=[k,"-Id",I(e),"-ErrorAction SilentlyContinue",D].join(" "),i=await P.PowerShell.instance().executeJsonToA(t);return null==i?void 0:i.map(e=>({pid:e.Id,start:(0,b.pwshJsonDate)(e.StartTime),cmd:e.ProcessName}))}const A={maxBuffer:1048576,timeoutMs:15*c.secondMs,ignoreExitCode:!0,ignoreStderr:!0};async function x(e){return t=(await(0,v.stdoutResult_)("ps",["-p",I(e),"-wwwo","pid,lstart,command"],{...A,timerName:"proc.ps",ignoreExitCode:!0})).result,(0,u.blank)(t)?[]:(0,p.parseFixed)(["PID",{text:"STARTED",greedyLeft:!0},"COMMAND"],t).map(e=>({pid:(0,d.toInt)(e.PID,{defaultValue:-1}),start:new Date(e.STARTED),cmd:(0,f.toS)(e.COMMAND)}));var t}const F=(0,g.lazy)(()=>{try{if(S.isLinux){const e=(0,s.spawnSync)("getconf",["CLK_TCK"],{shell:!1});return(0,d.toGt0)(e.stdout?.toString())??100}}catch(e){T().warn("clk_tck failed",{error:e})}return 100}),O=/^btime (?<btime>\d+)$/m,R=(0,g.lazy)(()=>{if(S.isLinux)try{const e=(0,n.readFileSync)("/proc/stat","utf8"),t=(0,d.toGt0)(O.exec(e)?.groups?.btime);if(null!=t)return t*c.secondMs}catch{}return Date.now()-(0,a.uptime)()*c.secondMs}),L=/(?<pid>\d+) \((?<comm>.+)\) (?<state>[A-Z]) (?:-?\d+ ){18}(?<starttime>\d+)/i;function N(e){const t=L.exec((0,f.toS)(e))?.groups,i=(0,d.toInt)(t?.pid),r=t?.comm,s=(0,d.toInt)(t?.starttime);return(0,d.gt0)(i)&&!(0,u.blank)(r)&&(0,d.gt0)(s)?{pid:i,cmd:r,start:new Date(R()+s/F()*c.secondMs),state:t?.state}:void 0}},87445(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.progressEvtToS=function(e){const t=(0,s.blank)(e.path)?null:(0,a.ellipsizePath)({p:e.path,maxLength:80});return(0,r.compactBlanks)([t,e.op,!0===e.done?"done":(0,n.fmtPct)(e.pct)]).join(": ")},t.isProgressEvt=function(e){return null!=e&&(0,s.notBlank)(e.op)&&(0,o.within)(0,100,e.pct)};const r=i(40958),s=i(22573),n=i(31586),a=i(29882),o=i(97352)},26037(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWatchdog=void 0;const r=i(42659),s=i(45599),n=i(45132),a=i(50213),o=i(28874),l=i(84968),u=i(69385),c=i(87445),d=(0,s.defer)(()=>(0,a.mkLogger)("progress.ProgressWatchdog"));class h{#Sr;#Pr=new Set;#Mr;#Tr;#_r;static instance=new h;constructor(){this.#Sr=new n.BoundedMap(10),this.#Mr=()=>!1,this.#Tr=()=>0,d().debug("ProgressWatchdog initialized")}setIsWorkPending(e){this.#Mr=e}setPendingCount(e){this.#Tr=e}setOnWedged(e){this.#_r=(0,s.defer)(()=>{d().warn("triggerOnWedged: invoking callback to mark tasks as problematic");try{e()}catch(e){d().error("triggerOnWedged: callback failed",{error:e})}})}triggerOnWedged(){null!=this.#_r?this.#_r.applied()?d().debug("triggerOnWedged: already triggered, skipping"):this.#_r():d().warn("triggerOnWedged: no callback set")}ping(e){this.#Sr.set(e,Date.now()),this.#_r?.reset()}progressEvent(e){this.ping((0,c.progressEvtToS)(e))}get lastPing(){const e=this.#Sr.lastValue,t=this.#Sr.lastKey;return null==e||null==t?void 0:{ts:e,desc:t}}get recentPings(){return[...this.#Sr.entries()].map(([e,t])=>({desc:e,ts:t}))}enterOperation(e){this.#Pr.add(e),this.ping(`enter: ${e}`),d().debug("enterOperation",{name:e,active:[...this.#Pr]})}exitOperation(e){this.#Pr.delete(e),d().debug("exitOperation",{name:e,active:[...this.#Pr]})}get isInWorkingMode(){return this.#Pr.size>0}get activeOperations(){return[...this.#Pr]}isWedged(){if(!this.isInWorkingMode)return!1;const e=o.Settings.progressWatchdogTimeoutMs.valueOrDefault;if(e<=0)return!1;if(!this.#Mr())return!1;if((0,u.isPaused)())return!1;const t=this.#Sr.lastValue??l.StartTs-r.minuteMs,i=Math.max(t,(0,u.lastResumeTs)());return Date.now()-i>e}get pendingCount(){return this.#Tr()}}t.ProgressWatchdog=h},33847(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullProgressObserver=void 0;const r=i(98553),s=i(31586),n=i(78406),a=i(25764),o=i(99331),l=i(98314),u=i(26037);class c extends n.EndableInterval{ctx;total;progress;throttleMs;done;constructor(e,t,i,s=5e3){super({name:"PullProgressObserver("+(0,r.stringify)(e)+")",callback:()=>this.#Er(),intervalMs:s,rank:a.EndableRanks.first}),this.ctx=e,this.total=t,this.progress=i,this.throttleMs=s}toJSON(){}observe(e){return e.then(()=>this.completed(),e=>{this.logger.warn("failed",{error:e}),this.ctx.op+=" (failed: "+(0,l.errorToS)(e)+")",this.end()}),e}async#Er(){(0,o.ending)()?this.end():this.onResult(await this.progress())}onResult(e){u.ProgressWatchdog.instance.progressEvent({...this.ctx,pct:(0,s.pct)(e,this.total),done:this.done})}completed(){const e=this.done;this.done=!0,this.ended||(!0!==e&&this.onResult(this.total),this.end())}}t.PullProgressObserver=c},38156(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushProgressObserver=void 0;const r=i(31586),s=i(85296),n=i(26037);t.PushProgressObserver=class{context;total;#kr;#Dr;constructor(e,t){this.context=e,this.total=t,this.#Dr=!1,this.#kr=0}toJSON(){}incrProgress(e=1){return this.#kr+=e,this.#Ir()}onProgress(e){return this.#kr=e??this.#kr+1,this.#Ir()}#Ir(){return(0,r.gte)(this.#kr,this.total)&&(this.#Dr=!0),!0===this.#Dr?this.#Cr():this.emit()}completed(){this.#Dr=!0,this.#kr=this.total,this.#Cr()}#Cr=()=>{this.emit.reset(),n.ProgressWatchdog.instance.progressEvent({...this.context,pct:(0,r.pct)(this.#kr,this.total),done:this.#Dr})};emit=(0,s.trailingThrottle)({minDelayMs:100,fn:this.#Cr})}},24399(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PowerShell=void 0,t.pwshQuote=D,t.checkPowerShell_=async function(){const e=I.ensureInstance();if(e.ended)throw new Error("PowerShell batchcluster ended");const t=await(0,u.thenOrTimeoutError)(e.version(),(0,_.commandTimeoutMs)());if((0,n.blank)(t)){const t=await(0,b.until)(()=>e.lastStartError??e.lastTaskError,{timeoutMs:m.ShortCommandTimeoutMs,intervalMs:250});if(null!=t)throw t;let i,r;try{i=await e.pwshPath()}catch(e){r=String(e)}throw new Error(`PowerShell returned no version. path=${i??"(unknown)"}, spawned=${e.spawnedProcCount}, ended=${e.ended}`+(null!=r?`, pathError=${r}`:""))}return{desc:"PowerShell",version:t,path:await e.pwshPath()}};const r=i(58587),s=i(19851),n=i(22573),a=i(42659),o=i(41400),l=i(55835),u=i(13538),c=i(36557),d=i(14121),h=i(50213),f=i(7282),m=i(45255),p=i(81168),g=i(25764),y=i(38836),v=i(99331),b=i(31562),w=i(84777),S=i(34102),P=i(8103),M=i(43334),T=i(28874),_=i(63870),E="{ready}",k=" | ConvertTo-Json -Compress";function D(e){return'"'+e.replace(/['`"“”#]/g,e=>"`"+e).replace(/\0/g,"`0").replace(/\n/g,"`n").replace(/\r/g,"`r").replace(/\t/g,"`t").replace(/\v/g,"`v")+'"'}(0,o.later)(()=>(0,S.ee)().on("clearCache",()=>I._instance?.clearMockResults()));class I extends y.EndableWrapper{static ensureInstance(){return!0===this._instance?.ended&&(this._instance=void 0),this.instance()}static _instance;static instance(){if(!M.isWin)throw new Error("PowerShell isn't available on this platform");return(0,f.isTest)()&&!0===this._instance?.ended&&(this._instance=void 0),this._instance??=new I}static async endInstance(){await(this._instance?.end()),this._instance=void 0}bco;pwsh;mockResults=new Map;constructor(){super("PowerShell",()=>this.bco.end(),g.EndableRanks.postdb),this.bco=new c.BatchClusterObserver("PowerShell",new r.BatchCluster({processFactory:async()=>(0,w.execFile)(await this.pwshPath(),T.Settings.powerShellArgs.values),logger:()=>(0,h.mkLogger)("PowerShell"),versionCommand:[`function prompt {"${E}"}`,...(0,n.mapNotBlankOr)(T.Settings.powerShellCulture.valueOrDefault,e=>[`[System.Threading.Thread]::CurrentThread.CurrentCulture = '${e}'`,`[System.Threading.Thread]::CurrentThread.CurrentUICulture = '${e}'`],[])].join(";"),pass:E,fail:/\bError\b/i,exitCommand:"exit",maxProcs:T.Settings.powerShellProcs.valueOrDefault,taskTimeoutMillis:(0,_.commandTimeoutMs)(),maxIdleMsPerProcess:a.minuteMs,cleanupChildProcs:!1}),g.EndableRanks.postdb),T.Settings.powerShellProcs.watch(()=>this.bco.t.setMaxProcs(T.Settings.powerShellProcs.valueOrDefault)),this.pwsh=this.bco.t}pwshPath=(0,s.lazy)(async()=>await(0,P.pathTo)({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(){const e=await this.executeJson("$PSVersionTable.PSVersion");return null==e?void 0:`${e.Major}.${e.Minor}.${e.Build}`}get spawnedProcCount(){return this.pwsh.spawnedProcCount}pushMockJsonResult(e,t){this.pushMockResult((0,p.ensureSuffix)(e,k),t)}pushMockResult(e,t){this.mockResults.set(e,t)}clearMockResults(){this.mockResults.clear()}async execute(e,t){if(this.pwsh.ended||(0,v.ending)())this.logger.warn("execute() failed (ended)",{cmd:e});else{if((0,f.isTest)()&&this.mockResults.has(e)){const i=this.mockResults.get(e);return t(i.stdout,i.stderr,i.passed)}try{const i=await(0,d.elapsedAsync)(this.pwsh.enqueueTask(new r.Task(e,(i,r,s)=>t((0,l.map)(i,t=>(0,p.stripPrefix)(t,e)),r,s))));return this.logger.tap({msg:"execute()",result:i.result,meta:{elapsedMs:i.elapsedMs,cmd:e}})}catch(t){return void this.logger.warn("execute() failed",{cmd:e,error:t})}}}async executeJson(e){const t=await this.execute((0,p.ensureSuffix)(e,k),(e,t,i)=>({stdout:e,stderr:t,passed:i}));if(null!=t)if((0,n.blank)(t.stdout)||(0,n.notBlank)(t.stderr)||!t.passed)this.logger.warn("executeJson(): failed result",{cmd:e,...t});else try{return JSON.parse(t.stdout)}catch(e){const i=t.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:(0,p.ellipsize)(t.stdout),after:(0,p.ellipsize)(i)}),JSON.parse(i)}else this.logger.warn("executeJson(): null result",{cmd:e})}async executeJsonToA(e){const t=await this.executeJson(e);return null==t?void 0:Array.isArray(t)?t:[t]}async getWindowsPath(e){try{const t=`[Environment]::GetFolderPath('${e.replace(/[^a-z]/gi,"")}', 'DoNotVerify')`,i=await this.executeJson(t);if((0,n.blank)(i))return;return i}catch(t){return void this.logger.warn("Failed to get Windows path",{folderId:e,error:t})}}async which(e){const t=await this.executeJson("Get-Command -ErrorAction SilentlyContinue "+D(e)+" | Select-Object -Property Source");return Array.isArray(t)?t[0]?.Source:t?.Source}}t.PowerShell=I},39056(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AggregationSettings=void 0;const r=i(15207),s=i(5852),n=i(71988),a=i(38483),o=i(90536),l=i(22812),u=i(9945),c=i(74589),d=i(81075),h=i(58305),f=i(57571),m=i(72564),p=i(80372);t.AggregationSettings={strictDeduping:new a.BooleanSetting({category:d.SettingCategories.Aggregation,deprecated:!0,description:"Use aggregationMode=strict instead of setting this to true.",defaultValue:!1}),aggregationMode:new f.StringEnumSetting({category:d.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:r.AggregationModes.default,strEnum:r.AggregationModes}),assetVariationSortCriteria:new m.StringEnumsSetting({category:d.SettingCategories.Aggregation,aliases:["assetFileSortCriteria","variantSortCriteria"],description:'How should PhotoStructure pick the "best" asset file variation for a given asset?\nDetails about these fields are here: https://photostructure.com/faq/what-do-you-mean-by-dedupe/#variantSortCriteria',strEnum:n.AssetFileSortCriteria}),assetVariationResolutionTolerance:new o.BoundedFloatSetting({category:d.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 h.StringArraySetting({category:d.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 "RAW" image types (assuming that these file types contain a superset of information from other file types).',defaultValue:l.DefaultMimetypeSortOrder}),imageDataHashType:new f.StringEnumSetting({category:d.SettingCategories.Aggregation,description:"What algorithm should be used to hash image data? Use \"disabled\" to disable image data hashes.\nThis slows file imports slightly but improves deduplication quality. The default is MD5, which provides 128-bit hashes. Using the birthday problem formula, the probability of any two files colliding in a 1 million asset library is approximately 1 in 6.8 × 10^26.\nWhile MD5 is cryptographically broken (vulnerable to deliberate collision attacks), this is a non-adversarial use case—you're comparing your own trusted files, not defending against attackers crafting malicious inputs. The smaller hash size (16 bytes vs 32-64 for SHA variants) helps constrain database growth at scale. If this concerns you, change to SHA256 or SHA512 and rebuild your library.\nNote that some formats (e.g., Olympus ORF) don't support image data hashing, so this field may be empty for some media.",defaultValue:s.ImageDataHashes.MD5,strEnum:s.ImageDataHashes}),checkBasenameMatches:new a.BooleanSetting({category:d.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?\nNote that image hash and other asset file comparisons will still be performed before determining a given asset is a match.',defaultValue:!0}),allowFuzzyDateImageHashMatches:new a.BooleanSetting({category:d.SettingCategories.Aggregation,description:'For images that don\'t have a reliable precise captured-at time (say, from "stat" or datestamp from pathname), can we aggregate assets purely by exact image hash matches?\nSee https://forum.photostructure.com/t/deduplicate-shenanigans/1732/11 for more details.',defaultValue:!1}),requireSameColorSpace:new a.BooleanSetting({category:d.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 c.IntegerSetting({category:d.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?\nMonitor the "sync.AssetFileFinder.assetByCapturedAtOrImageHash" timer to see how long adoption is taking on your machine.\nHigher values will slow down imports, but may result in more accurate de-duplication results.',defaultValue:512}),imageHashMatchK:new c.IntegerSetting({category:d.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 p.StringSetting({category:d.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."\nWhen assets have an estimated captured-at time, tighter image correlation is required to prevent different images as being incorrectly aggregated into the same asset.\nThe default value is the release date for the Nikon Coolpix 950, which was one of the first prosumer digital cameras with ~2MP resolution.',defaultValue:"1999-02-15"}),exposureThresholdPct:new o.BoundedFloatSetting({category:d.SettingCategories.Aggregation,aliases:["minExposureSettingsCoeffPct"],description:"This is the minimum similarity between exposure setting values two images must be to be considered equivalent. Many cameras actually report different exposure setting values between JPG and RAW: values within 90% of each other should avoid false-positives.",defaultValue:()=>90,min:0,max:100}),imageHashThresholdPct:new o.BoundedFloatSetting({category:d.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 o.BoundedFloatSetting({category:d.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 o.BoundedFloatSetting({category:d.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 o.BoundedFloatSetting({category:d.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 o.BoundedFloatSetting({category:d.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 c.IntegerSetting({category:d.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.\nGPS position error is ~10-100m. Cellular position error is ~500-750m.",defaultValue:500}),minCapturedAtPrecisionDifferentMimetypes:new c.IntegerSetting({category:d.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 u.FloatSetting({category:d.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})}},71988(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileSortCriteria=void 0;const r=i(50989);t.AssetFileSortCriteria=(0,r.strEnum)("resolution","isBrowserSupported","mimetype","schemeIdx","metadataDate","capturedAtPrecisionMs","isEditOrUpdate","isCover","fileSize","sha","uri","count","mtime","basename","parentBasename")},47688(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AuthSettings=void 0;const r=i(38483),s=i(57039),n=i(74589),a=i(9868),o=i(81075);t.AuthSettings={enableArchive:new r.BooleanSetting({category:o.SettingCategories.Auth,description:'If true, the "Archive" button in Asset views will be visible and enabled for all visitors.',defaultValue:()=>!0}),enableDelete:new r.BooleanSetting({category:o.SettingCategories.Auth,description:'If true, the "Delete" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableEmptyTrash:new r.BooleanSetting({category:o.SettingCategories.Auth,description:'If true, the "Empty Trash" button will be enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!a.SecuritySettings.exposeNetworkWithoutAuth.valueOrDefault}),enableRemove:new r.BooleanSetting({category:o.SettingCategories.Auth,description:'If true, the "Remove asset" button in Asset views will be visible and enabled for all visitors.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!0}),enableRemoveAssets:new r.BooleanSetting({category:o.SettingCategories.Auth,description:'If true, the "Remove Assets" buttons will be visible and enabled for all visitors.\nUntil PhotoStructure has visitor user levels, if you don\'t trust all your users, disable this!\nThis setting is disabled by default if exposeNetworkWithoutAuth is true.\nThis is a temporary setting until PhotoStructure enforces authentication/authorization.',defaultValue:()=>!a.SecuritySettings.exposeNetworkWithoutAuth.valueOrDefault}),argon2TimeCost:new n.IntegerSetting({category:o.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "time" cost parameter.',defaultValue:8}),argon2MemoryCostMB:new n.IntegerSetting({category:o.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "memory" cost parameter, and is specified in megabytes. Each parallel thread will consume this amount of RAM: don\'t exceed your system memory.',defaultValue:64}),argon2Parallelism:new n.IntegerSetting({category:o.SettingCategories.Auth,description:'PhotoStructure encrypts user passwords with Argon2. This value sets the Argon2 "parallelism" parameter. RAM consumption will be ((this value) × argon2MemoryCost) KB of RAM: don\'t exceed your system memory.',defaultValue:1}),sessionTimeout:new s.DurationSetting({category:o.SettingCategories.Auth,description:"How long user sessions remain valid without activity. After this period, users must log in again.",defaultValue:"1d"})}},38483(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toBoolean})}}t.BooleanSetting=a},90536(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{options;constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).flatMap(parseFloat).map(t=>(0,s.clamp)(e.min,e.max,t)).get()}),this.options=e}addToJsonDocs(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedFloatSetting=o},75164(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(97790),a=i(83179);class o extends a.Setting{options;constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:t=>(0,n.opt)(t).filter(r.notBlank).flatMap(s.toInt).map(t=>(0,s.clamp)(e.min,e.max,t)).get()}),this.options=e}get min(){return this.options.min}get max(){return this.options.max}clamp(e){return(0,s.clamp)(this.min,this.max,e??this.min)}addToJsonDocs(){return{"minimum value":this.options.min,"maximum value":this.options.max}}}t.BoundedIntegerSetting=o},8400(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CacheSettings=void 0;const r=i(57039),s=i(81075),n=i(76989);t.CacheSettings={fsCacheSlowMs:new r.DurationSetting({category:s.SettingCategories.Cache,description:"If a cache entry takes longer than this value to compute, cache results for later reuse to the filesystem.\nThe default is very short, under the assumption that cache filesystem read/writes are <10ms.\nSet this to 0 to never cache to the filesystem.",defaultValue:()=>(0,n.isNotProd)()?"1":"25"}),imageCacheMs:new r.DurationSetting({category:s.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 r.DurationSetting({category:s.SettingCategories.Cache,description:"How long can file metadata be safely cached?\nSet to 0 to disable metadata caching.",defaultValue:"10m"})}},10546(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorDistanceFunctions=void 0;const r=i(50989);t.ColorDistanceFunctions=(0,r.strEnum)("cie76","cie94","ciede2000")},24325(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ColorSettings=void 0;const r=i(47086),s=i(90536),n=i(75164),a=i(10546),o=i(67958),l=i(81075),u=i(57571);t.ColorSettings={colorVarianceThreshold:new n.BoundedIntegerSetting({aliases:["colourVarianceThreshold"],category:l.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 s.BoundedFloatSetting({category:l.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 u.StringEnumSetting({aliases:["delta_e","dominantColourDeltaE"],category:l.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:a.ColorDistanceFunctions.ciede2000,strEnum:a.ColorDistanceFunctions}),dominantColorKmeansRuns:new n.BoundedIntegerSetting({category:l.SettingCategories.Color,aliases:["modeRuns","dominantColourKmeansRuns"],description:'PhotoStructure uses k-means clustering to extract dominant colors from your images.\nLarger values will allow PhotoStructure to run k-means with more random seeds and different pre-merged k values, which should result in higher quality results.\nUsing 0 will revert to posterizing the image and using the top-n colors, which is fast and deterministic, but has lower quality results.\nChanging this value will subtly change many image\'s dominant color lists.\nThis defaults to 0 run when "quickSyncMode" is enabled.',defaultValue:o.DominantColorKmeansRunsDefault,max:64,min:0}),dominantColorMergeThreshold:new n.BoundedIntegerSetting({aliases:["dominantColourMergeThreshold"],category:l.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 n.BoundedIntegerSetting({category:l.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.\nSet 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 u.StringEnumSetting({aliases:["colourEncoding"],category:l.SettingCategories.Color,strEnum:r.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"})}},90967(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CronSetting=void 0;const r=i(36507),s=i(22573),n=i(45599),a=i(50213),o=i(81168),l=i(98314),u=i(8769),c=i(80372),d=(0,n.defer)(()=>(0,a.mkLogger)("settings.CronSetting"));function h(e){try{const t=(0,o.trimQuotes)(e);return void((0,s.blank)(t)||new r.Cron(t))}catch(e){return e?.message??(0,l.errorToS)(e)}}function f(e,t,i){try{return(0,s.blank)(t)?void 0:new r.Cron(t,{name:e,unref:!0,protect:!0,catch:i=>(0,u.onError)(i,{name:e,crontab:t}),...i})}catch(i){return void d().warn("invalid cron",{name:e,crontab:t,error:i})}}class m extends c.StringSetting{constructor(e){super({whyInvalid:h,...e})}cron(e){return f(this.name,this.value,e)??f(this.name,this.defaultValue,e)}}t.CronSetting=m},83496(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbSettings=void 0;const r=i(99315),s=i(34365),n=i(38483),a=i(90536),o=i(75164),l=i(57039),u=i(74589),c=i(81075),d=i(76989),h=i(57571);t.DbSettings={forceLocalDbReplica:new n.BooleanSetting({category:c.SettingCategories.Paths,description:"Libraries on remote filesystems can suffer from bad performance and inconsistent transactions due to slow file I/O and missing file locking mechanics. When opening libraries on remote filesystems, or if this setting is `true`, PhotoStructure will copy the library database to the `cacheDir` and perform I/O against this local replica. Changes made to the local db replica are then periodically copied back to the remote library.\nIf you've overridden this value in the past, know that v23.5 and after should automatically set this to the correct value for you.\nFor more details, see https://forum.photostructure.com/t/whats-force-local-db-replica/837 and https://photostructure.com/about/2023-release-notes/#-sqlite-improvements",defaultValue:()=>!1}),dbRetries:new u.IntegerSetting({category:c.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 o.BoundedIntegerSetting({aliases:["dbBackupsCount"],category:c.SettingCategories.Db,description:"How many prior backups should PhotoStructure retain? These will typically be 10-500 MB, depending on the size of your library.\nWe don't retain that many backups by default because they get stale pretty quickly, as they fall out of sync with your filesystem and previews directory contents.",advanced:()=>!0,defaultValue:3,max:128,min:1}),dbInvalidFKThreshold:new u.IntegerSetting({category:c.SettingCategories.Db,description:"When PhotoStructure runs a database recovery, it will check for foreign key violations. If there are fewer than this number of invalid rows, PhotoStructure will drop those rows, with the hope that the next sync will finish the recovery.\nSet this to 0 to disable this recovery step, which will make any foreign key violation fatal.",defaultValue:64}),dbSynchronousMode:new h.StringEnumSetting({category:c.SettingCategories.Db,description:'Change SQLite\'s synchronous mode.\n"OFF" will cause data corruption. "FULL" and "EXTRA" may be required if you\'re seeing dataloss.\nFor more details, see https://sqlite.org/pragma.html#pragma_synchronous',strEnum:s.SynchronousModes,defaultValue:s.SynchronousModes.NORMAL}),dbWalAutoCheckpointPages:new u.IntegerSetting({category:c.SettingCategories.Db,aliases:["dbWalAutoCheckpoint"],description:"SQLite's WAL (Write-Ahead Logging) mode appends changes to a separate file. When the 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. Note: PhotoStructure also runs explicit checkpoints after each directory sync and during cleanup.\\nFor more details, see https://sqlite.org/pragma.html#pragma_wal_autocheckpoint",advanced:()=>!0,defaultValue:()=>5e3}),dbRepairMode:new h.StringEnumSetting({category:c.SettingCategories.Db,description:'PhotoStructure will automatically attempt to repair library databases that don\'t pass validation tests. SQLite has two repair strategies:\n- "dump", which will recover from minor errors and normally retains the current schema\n- "recover", which will recover as much data as possible from corrupt db. Unfortunately, this can result in an invalid and unusable schema, which is why PhotoStructure defaults to "dump".\nNote that PhotoStructure validates the schema after a repair, and will report via logs and the health check system if there are any issues.',strEnum:r.RepairModes,defaultValue:r.RepairModes.dump}),maxBusyDbMs:new l.DurationSetting({category:c.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 l.DurationSetting({category:c.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 l.DurationSetting({category:c.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?\nNote 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 l.DurationSetting({category:c.SettingCategories.Db,description:"How frequently should PhotoStructure backup your library database?",advanced:()=>!0,defaultValue:()=>(0,d.isNotProd)()?"30s":"1h"}),dbBackupIntervalMinutes:new a.BoundedFloatSetting({category:c.SettingCategories.Db,deprecated:!0,description:'This setting was replaced by "dbBackupIntervalMs".',min:(0,d.isNotProd)()?.5:1,max:1440,advanced:()=>!0,defaultValue:()=>(0,d.isNotProd)()?.5:30}),dbPageSizeBytes:new u.IntegerSetting({category:c.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.\nFor more details, see https://sqlite.org/pragma.html#pragma_page_size",advanced:()=>!0,defaultValue:8192}),dbCacheSizeMb:new u.IntegerSetting({category:c.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.\nFor more details, see https://sqlite.org/pragma.html#pragma_cache_size",advanced:()=>!0,defaultValue:256}),dbMaxCacheRamPercent:new o.BoundedIntegerSetting({category:c.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.\nFor more details, see https://sqlite.org/pragma.html#pragma_cache_size",advanced:()=>!0,defaultValue:25,min:0,max:100}),dbMMapSizeMb:new u.IntegerSetting({category:c.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.\nFor more details, see https://sqlite.org/pragma.html#pragma_mmap_size",advanced:()=>!0,defaultValue:256}),dbBatchSelectSize:new o.BoundedIntegerSetting({category:c.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 o.BoundedIntegerSetting({category:c.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 n.BooleanSetting({category:c.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.\nThis can take a while to perform, especially on large libraries or slow computers: don't set this value to true normally.\nFor more details, see https://sqlite.org/recovery.html",defaultValue:()=>!1}),dbBackupRemoteOnSuspend:new n.BooleanSetting({aliases:["backupRemoteDbOnSuspend"],category:c.SettingCategories.Db,description:"Run a database backup when system suspend is requested and the database is on a remote volume.",defaultValue:()=>!0}),enableSimilaritySearch:new n.BooleanSetting({category:c.SettingCategories.Db,description:"Enable or disable similarity searches via the sqlite-vec extension. This must be enabled for allowFuzzyDateImageHashMatches to work.\nDisabling this setting will drop the AssetFileHash index and prevent similarity searches from working.",defaultValue:()=>!0})}},22812(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultMimetypeSortOrder=void 0,t.DefaultMimetypeSortOrder=["image/jpeg","image/heic","image/x-*","image/*","video/*"]},23299(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DesktopsSettings=void 0;const r=i(38483),s=i(81075);t.DesktopsSettings={autoHideMenuBar:new r.BooleanSetting({category:s.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 r.BooleanSetting({category:s.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will not open the main window when launched. The tray icon will still be visible.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),pauseSyncOnBattery:new r.BooleanSetting({category:s.SettingCategories.Desktops,description:"If true, PhotoStructure for Desktops will pause sync when the system is on battery power.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!1}),closeToTray:new r.BooleanSetting({category:s.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.\nThis setting is ignored by PhotoStructure for Server editions.",defaultValue:!0})}},67958(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DominantColorKmeansRunsDefault=void 0,t.DominantColorKmeansRunsDefault=7},57039(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalDurationSetting=t.DurationSetting=void 0;const r=i(6875),s=i(70488),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:s.encodeDuration,...e,fromEnv:s.decodeDuration})}get valueOrDefault(){return(0,s.decodeDuration)(super.valueOrDefault)}get value(){return(0,s.decodeDuration)(super.value)}set value(e){super.userValue=(0,s.decodeDuration)(e)}get humanValue(){return(0,r.fmtDuration)(this.value)}get fileValue(){return(0,s.encodeDuration)(super.fileValue)}set fileValue(e){super.fileValue=(0,s.decodeDuration)(e)}}t.DurationSetting=a;class o extends n.Setting{constructor(e){super({...e,toEnv:s.encodeDuration,fromEnv:s.decodeDuration,defaultValue:void 0})}get valueOrDefault(){return this.value??(0,s.decodeDuration)(this.defaultValue)}get fileValue(){return(0,s.encodeDuration)(super.fileValue)}}t.OptionalDurationSetting=o},34217(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.expedite=function(e){return r.Settings.expedite.withValue(!0,e)};const r=i(28874)},27449(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileCopyStrategies=void 0;const r=i(50989);t.FileCopyStrategies=(0,r.strEnum)("auto","builtin-reflink","builtin","builtin-no-wip","native-preserve","native")},57549(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FilesystemSettings=void 0;const r=i(29365),s=i(45969),n=i(43334),a=i(1485),o=i(38483),l=i(57039),u=i(27449),c=i(74589),d=i(81075),h=i(76989),f=i(58305),m=i(57571);t.FilesystemSettings={useFsWatch:new o.BooleanSetting({category:d.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.\nFor more details see https://nodejs.org/api/fs.html#availability",defaultValue:()=>!0}),statTimeoutMs:new l.DurationSetting({aliases:["commandTimeoutMs","fsTimeoutMs"],category:d.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.\nSet to 0 to disable.',defaultValue:()=>"30s"}),statRetries:new c.IntegerSetting({category:d.SettingCategories.Filesystem,description:"If a stat or readdir times out, how many times can PhotoStructure retry before giving up?.\nSet to 0 to disable retries.",defaultValue:()=>3}),watchDebounceMs:new l.DurationSetting({category:d.SettingCategories.Filesystem,description:'How long to wait for a file to "settle down" and stop changing before the file watcher notifies listeners that the file changed. Some applications (like PhotoStructure) use work-in-progress "atomic" writes, but many applications overwrite in-place, which can cause the file watcher to see incomplete results until the write process is complete.\nThe default is 500ms (½ second) to handle slow remote NASes and slow-writing applications.\nSet to 0 to disable.',defaultValue:()=>"500ms"}),excludedFilesystemTypes:new f.StringArraySetting({aliases:["ignoredFilesystemTypes"],category:d.SettingCategories.Filesystem,description:"Volumes with these filesystem types will never be scanned or imported.\nThese are only relevant to Linux and macOS systems.\nDefaults to @photostructure/fs-metadata's `SystemFsTypesDefault`: see https://photostructure.github.io/fs-metadata/variables/index.SystemFsTypesDefault.html",defaultValue:()=>[...r.SystemFsTypesDefault]}),excludedMountpointPaths:new f.StringArraySetting({aliases:["ignoredMountpoints"],category:d.SettingCategories.Filesystem,description:"PhotoStructure won't descend into mountpoints that match these paths.\nDefaults to @photostructure/fs-metadata's `SystemPathPatternsDefault` (https://photostructure.github.io/fs-metadata/variables/index.SystemPathPatternsDefault.html) plus Docker bind-mount paths when running in a container.",defaultValue:()=>(0,s.isDocker)()?a.ExcludedMountpointPathsDocker:a.ExcludedMountpointPathsBase}),excludedMountpointPathsAdd:new f.StringArraySetting({category:d.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 f.StringArraySetting({category:d.SettingCategories.Filesystem,description:"Mountpoint paths to remove from the default exclusion list.\nIf you want to scan a path that's excluded by default, add it here."}),validateMountpoints:new o.BooleanSetting({category:d.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}),mountpointsTtlMs:new l.DurationSetting({category:d.SettingCategories.Filesystem,description:"How frequently should PhotoStructure scan for new volumes (so PhotoStructure can detect when drives are inserted or ejected)? Shorter than 10-15 seconds may cause issues on Windows. A value of 0 will cache indefinitely. This defaults to 15 minutes on Windows, which relies on polling. On Linux and macOS this is set to 0 because findmnt/gio and diskutil notify mountpoint changes without polling.",defaultValue:()=>n.isWin?"15m":"0"}),fileCopyStrategy:new m.StringEnumSetting({category:d.SettingCategories.Filesystem,strEnum:u.FileCopyStrategies,description:"File copy strategy. See https://photostructure.com/faq/file-copy-strategies/ for details on each strategy.",defaultValue:u.FileCopyStrategies.auto}),fileCopyOnlyNative:new o.BooleanSetting({aliases:["onlyNativeFileCopy"],category:d.SettingCategories.Filesystem,description:'DEPRECATED: Use "fileCopyStrategy" instead. This setting will be auto-migrated.\nShould PhotoStructure skip the built-in file copy code, and only use the "OS native" file copy mechanism?\nPhotoStructure is typically faster than native file copies by 2x or more.\nIf true, PhotoStructure will use "ditto" on macOS, "cp" on Linux, and "Copy-Item" via PowerShell on Windows.',defaultValue:!1}),fileCopyVerify:new o.BooleanSetting({aliases:["verifyFileCopy","verifyFileCopies"],category:d.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 o.BooleanSetting({envAliases:["PS_COPYFILE_FICLONE"],category:d.SettingCategories.Filesystem,description:'DEPRECATED: Use "fileCopyStrategy" instead. This setting will be auto-migrated.\nShould 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 o.BooleanSetting({category:d.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").\nThis setting defaults to false on docker. For more details, see https://photostructure.com/go/docker-soft-delete',defaultValue:()=>!!(0,h.isNotProd)()||!(0,s.isDocker)()}),directorySortThreshold:new c.IntegerSetting({category:d.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 l.DurationSetting({category:d.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"})}},13797(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FiltersSettings=void 0;const r=i(12168),s=i(48584),n=i(38483),a=i(57039),o=i(74589),l=i(3964),u=i(23561),c=i(69005),d=i(81075),h=i(58305),f=i(57571);t.FiltersSettings={disableAllFilters:new n.BooleanSetting({category:d.SettingCategories.Filters,description:"Setting this to true will force all other filter settings to their most permissive value. Note that this also disables file validation tests and the file SHA blocklist, so corrupt files and previously removed files will be attempted to be imported as well.\nIf you have to resort to using this setting, please consider hopping onto the PhotoStructure Forum or PhotoStructure Discord and describe your situation.",defaultValue:!1}),excludeGlobsAdd:new h.StringArraySetting({aliases:["excludedGlobsAdd"],category:d.SettingCategories.Filters,description:"This setting adds glob patterns for files and directories that should be excluded from your library.\nThese patterns will be added to PhotoStructure's default set of (several hundred!) exclusion globs.\nSee https://forum.photostructure.com/t/1458 for details.",exampleValue:()=>["**/tmp/"],defaultValue:()=>[]}),excludeGlobsOmitDefaults:new n.BooleanSetting({aliases:["omitDefaultExcludeGlobs","disableIgnorableFilters"],category:d.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 h.StringArraySetting({aliases:["excludedGlobsOmit"],category:d.SettingCategories.Filters,description:'PhotoStructure has several hundred default "exclusion globs" to avoid scanning system and application directories and otherwise irrelevant directories and files.\nIf you don\'t like one or two of them, add them here, and they will be removed from the excluded globs list.\nIf you don\'t want ANY of the default exclusion globs, see "excludeGlobsOmitDefaults".\nSee https://forum.photostructure.com/t/1458 for details.'}),globsCaseInsensitive:new n.BooleanSetting({category:d.SettingCategories.Filters,description:'Should "globs" match case-insensitively?',defaultValue:!0}),excludeHidden:new n.BooleanSetting({category:d.SettingCategories.Filters,description:'PhotoStructure may check for filesystem "hidden" metadata flags on macOS and Windows filesystems, and automatically skip importing those files.\nAs 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.\nThis setting is ignored on Linux systems.',defaultValue:!1}),respectFileExtensions:new n.BooleanSetting({category:d.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 n.BooleanSetting({category:d.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 o.IntegerSetting({category:d.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.\nNote: if you change this value, be sure to recount tag asset counts by clicking the "perform maintenance" button on the health check page.\nThis setting is deprecated: use "rejectRating" instead.\n ',defaultValue:0}),rejectRating:new l.NumericRangesSetting({category:d.SettingCategories.Filters,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."\nThis 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 h.StringArraySetting({category:d.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 o.IntegerSetting({category:d.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 o.IntegerSetting({category:d.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 u.OptionalFloatSetting({category:d.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.\nBrowsers 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 c.OptionalIntegerSetting({category:d.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 o.IntegerSetting({aliases:["minAssetSizeBytes","minAssetSize","minFileSizeBytes"],category:d.SettingCategories.Filters,description:"What's the minimum photo or video size you want imported into your library?\nThis setting can prevent small GIFs and screenshots from being imported.\nValues less than 1000 will be ignored.\nA 20-year-old 1600x1200 JPEG at 50% quality is more than 150k, so 50k is a very conservative default.",defaultValue:50*r.KB}),maxAssetFileSizeBytes:new o.IntegerSetting({aliases:["maxAssetSizeBytes","maxAssetSize","maxFileSizeBytes"],category:d.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*r.GB}),validateJpegImages:new n.BooleanSetting({category:d.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 f.StringEnumSetting({category:d.SettingCategories.Filters,description:'How sensitive should PhotoStructure be with warnings or errors when loading images?\nUse "none" to try loading images with best efforts, even if the file may be corrupt.\nUse "warning" to be conservative--any defects in the image will prevent it from being imported. \nThe default, "truncated," will allow images with minor encoding defects to be imported.',defaultValue:s.SharpFailOns.truncated,strEnum:s.SharpFailOns}),validateRawImages:new n.BooleanSetting({category:d.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.\nIf a camera produces raw files that LibRaw cannot decode yet, add its mimetype to "validateMimetypeSkiplist" rather than disabling this setting.',defaultValue:!0}),validateMimetypeSkiplist:new h.StringArraySetting({category:d.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 n.BooleanSetting({category:d.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 h.StringArraySetting({category:d.SettingCategories.Filters,description:'If any of the following patterns match a validation error found in a photo or video, and *doesn\'t* match any of the patterns in the validationErrorAllowlist, the file will be considered corrupt and not be imported into your library.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message, so, for example, a value of "caution" will ignore any error message that contains the string (not the word!) "caution".\nAlso see "validationErrorAllowlist".',defaultValue:()=>["cannot decode","cannot determine format of input","corrupt","error while decoding","failed","invalid","not a jpeg file","not raw file","nothing was written into output file","partial file","premature end of .*?file","unsupported file format"]}),validationErrorAllowlist:new h.StringArraySetting({category:d.SettingCategories.Filters,description:'All validation errors that match any of these values they will be ignored, EVEN IF they match a "validationErrorBlocklist" pattern, so all of these patterns should be specific enough to not cause false-negatives.\nNote the patterns are case-insensitive, will be converted into a regular expression, and only need to partially match the error message.\nAlso see "validationErrorBlocklist".',defaultValue:()=>["warning: ignored non-standard exif","invalid SOS parameters for sequential jpeg","referenced qt chapter track not found","non monotonically increasing dts"]}),rejectedFileCacheThresholdMs:new a.DurationSetting({category:d.SettingCategories.Filters,description:"Files rejected by expensive filters (like MIME type detection or file validation) will be cached if the filter chain took longer than this threshold (in milliseconds). This speeds up subsequent syncs by skipping re-evaluation of unchanged rejected files. Set to 0 to disable caching.",defaultValue:500})}},9945(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.FloatSetting=a},69589(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ForceContextKeys=t.ForceContextKeysList=void 0,t.pickForceContext=function(e){return(0,s.pick)(e,...t.ForceContextKeys.values)},t.forceContextOrSetting=function(e){const i={...(0,s.fromEntries)(t.ForceContextKeys.values.map(t=>[t,e?.[t]??(0,r.isTrue)(o.Settings[t]?.valueOrDefault)])),...(0,s.pick)(e??{},"retries","halt","path","scanGeneration")};return i.retries??=0,i.halt??=new a.Abortable,i};const r=i(38639),s=i(68708),n=i(50989),a=i(76740),o=i(28874);t.ForceContextKeysList=["forceSync","forceFilters","forceCheckLibraryCopy","skipPreviews","forceRebuildPreviews","skipAssetTagging","recountAllTags","skipAssetRepair"],t.ForceContextKeys=(0,n.strEnum)(...t.ForceContextKeysList)},82782(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HardwareSettings=void 0;const r=i(74589),s=i(81075),n=i(58305);t.HardwareSettings={maxTempCelsius:new r.IntegerSetting({category:s.SettingCategories.Hardware,description:"If PhotoStructure detects any hardware exceeds this temperature value, sync will pause until the system hardware cools down.\nMost CPUs have a maximum safe operating temperature of around 95°C (203°F), but sustained temperatures exceeding 80°C (176°F) can cause damage or reduce component lifespan.\nSupported on Linux. Uses lm-sensors if available, and also reads directly from /sys/class/hwmon/ and /sys/class/thermal/.\nSet to 0 to disable this check.",defaultValue:80,aliases:["criticalTempCelsius","warnTempCelsius"]}),excludedSensorNames:new n.StringArraySetting({category:s.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. If you see a sensor that is always reporting a temperature that is incorrect, you can add the sensor name to this list.",defaultValue:["*calibration*","*fan*"]}),minDiskFreeGb:new r.IntegerSetting({category:s.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).\nSet this value to 0 to disable free disk space health checks.",defaultValue:16})}},26272(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HealthSettings=void 0;const r=i(33866),s=i(81075),n=i(72564);t.HealthSettings={skipHealthCheckIds:new n.StringEnumsSetting({category:s.SettingCategories.Health,description:"List of health check IDs to skip.",defaultValue:[],strEnum:r.HealthCheckIds})}},74589(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt})}}t.IntegerSetting=a},2171(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingSettings=void 0;const r=i(37975),s=i(81125),n=i(57902),a=i(47832),o=i(38483),l=i(57039),u=i(74589),c=i(87652),d=i(81075),h=i(57571),f=i(80372);t.LoggingSettings={quiet:new o.BooleanSetting({category:d.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 f.StringSetting({envAliases:["PS_LOG","LOG","LOG_LEVEL"],category:d.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:a.logLevelDefaultValue}),logDir:new f.StringSetting({category:d.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>""}),logRetention:new l.DurationSetting({category:d.SettingCategories.Logging,description:"How long should we retain old log files? If set to 0, logs are never deleted.",defaultValue:"10d"}),logCompression:new o.BooleanSetting({category:d.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 o.BooleanSetting({category:d.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1}),logWebDir:new c.OptionalStringSetting({category:d.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir."}),logStdout:new o.BooleanSetting({envAliases:["LOG_STDOUT","PS_STDOUT"],category:d.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 l.DurationSetting({category:d.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 u.IntegerSetting({category:d.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 o.BooleanSetting({category:d.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 o.BooleanSetting({aliases:["logColour"],category:d.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:()=>!(0,r.noColor)()}),logContextLimit:new u.IntegerSetting({category:d.SettingCategories.Logging,description:"PhotoStructure will only log, at most, this number of elements or key/value pairs.",defaultValue:()=>32}),logSql:new o.BooleanSetting({category:d.SettingCategories.Logging,description:"Log SQL queries to the default log level. **Enabling this negatively impacts performance.**.\nThis defaults to false.",defaultValue:()=>!1}),logServer:new c.OptionalStringSetting({category:d.SettingCategories.Logging,description:'Format as hostname:port or ip_address:port.\nIf set, processes will emit log entries, formatted as GELF and separated by null bytes, via TCP.\nIf this is set, the default PS_LOG_LEVEL drops from "error" to "info".\nFor more details see https://docs.greylog.org/v1/docs/gelf',exampleValue:()=>"localhost:12201"}),logServerLevel:new f.StringSetting({category:d.SettingCategories.Logging,description:'This is the log level used to filter logs before sending them to "PS_LOG_SERVER".\nIf unset, we\'ll use the value of "PS_LOG_LEVEL".',defaultValue:a.logLevelDefaultValue}),logFlightRecorderCapacity:new u.IntegerSetting({category:d.SettingCategories.Logging,description:"Maximum log entries to buffer in the flight recorder. When a trigger-level event occurs, buffered entries are flushed first to provide debugging context. Set to 0 to disable.",defaultValue:s.DEFAULT_FLIGHT_RECORDER_CAPACITY}),logFlightRecorderTriggerLevel:new h.StringEnumSetting({category:d.SettingCategories.Logging,description:'Log level that triggers a flight recorder flush. Events at this level or more severe cause buffered entries to be written first. Set to "warn" to capture context around warnings (useful for debugging stalls). Must be more severe than logFlightRecorderMinLevel.',strEnum:n.LogLevels,defaultValue:"warn"}),logFlightRecorderMinLevel:new h.StringEnumSetting({category:d.SettingCategories.Logging,description:'Least severe level the flight recorder captures. Default "debug" excludes trace entries. Must be less severe than logFlightRecorderTriggerLevel.',strEnum:n.LogLevels,defaultValue:"debug"})}},4175(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.handleMetaSettings=function(e){switch(_(p.Settings.quickSyncMode.valueOrDefault),y("disableAllFilters",e)&&b(),y("aggregationMode",e)){case"strict":w();break;case"lenient":S()}((0,d.doNotTrack)()||y("optOut",e)||y("noNetwork",e))&&E()},t.settingsValueWarnings=function(e){const t=[],i=y("logFlightRecorderTriggerLevel",e),r=y("logFlightRecorderMinLevel",e),s=v("logFlightRecorderTriggerLevel",e),n=v("logFlightRecorderMinLevel",e);return s&&(0,h.levelIndex)(i)>=(0,h.levelIndex)(r??p.Settings.logFlightRecorderMinLevel.valueOrDefault)&&(t.push(`logFlightRecorderTriggerLevel (${p.Settings.logFlightRecorderTriggerLevel.value}) is more verbose than logFlightRecorderMinLevel (${p.Settings.logFlightRecorderMinLevel.valueOrDefault}); adjusting trigger level to ${p.Settings.logFlightRecorderTriggerLevel.defaultValue}`),p.Settings.logFlightRecorderTriggerLevel.unset()),n&&(0,h.levelIndex)(r)<=(0,h.levelIndex)(i??p.Settings.logFlightRecorderTriggerLevel.valueOrDefault)&&(t.push(`logFlightRecorderTriggerLevel (${p.Settings.logFlightRecorderTriggerLevel.valueOrDefault}) is more verbose than logFlightRecorderMinLevel (${p.Settings.logFlightRecorderMinLevel.value}); adjusting min level to ${p.Settings.logFlightRecorderMinLevel.defaultValue}`),p.Settings.logFlightRecorderMinLevel.unset()),t},t.handleDeprecatedSettings=async function(){if((0,s.isTrue)(p.Settings.scanMyPictures.fileValue)){p.Settings.scanMyPictures.unsetFileValue();const e=await(0,c.picturesDir)();g().warn("Upgrading setting scanMyPictures to scanPaths",{priorValues:p.Settings.scanPaths.values,newPath:e}),p.Settings.scanPaths.push(e)}{const e=p.Settings.strictDeduping.fileValue;!0===e&&null==p.Settings.aggregationMode.fileValue&&(g().warn("Upgrading setting strictDeduping to aggregationMode",{prior:e}),p.Settings.aggregationMode.value="strict")}{const e=p.Settings.assetSubdirectoryDatestampFormat.fileValue;if((0,r.blank)(p.Settings.assetPathnameFormat.fileValue)&&(0,r.notBlank)(e)){p.Settings.assetSubdirectoryDatestampFormat.unsetFileValue();const t=(0,o.ensureSuffix)(e,"/")+"BASE";g().warn("Upgrading setting assetSubdirectoryDatestampFormat to assetPathnameFormat",{prior:e,newValue:t}),p.Settings.assetPathnameFormat.value=t}}{const e=p.Settings.dbBackupIntervalMinutes.fileValue;if(null!=e&&null==p.Settings.dbBackupIntervalMs.fileValue){const t=e*n.minuteMs;g().warn("Upgrading setting dbBackupIntervalMinutes to dbBackupIntervalMs",{newValue:t}),p.Settings.dbBackupIntervalMs.value=t}}{const e=p.Settings.siblingInferenceBasenameCoeff.fileValue;if(null!=e&&null==p.Settings.siblingInferenceBasenameCoeffPct.fileValue){const t=Math.round(100*e);g().warn("Upgrading setting siblingInferenceBasenameCoeff to siblingInferenceBasenameCoeffPct",{newValue:t}),p.Settings.siblingInferenceBasenameCoeffPct.value=t}}{const e=p.Settings.siblingInference.fileValue;if(null!=e&&null==p.Settings.inferenceSiblingRadius.fileValue){const t="never"===e?0:void 0;null!=t&&(g().warn("Upgrading setting siblingInference to inferenceSiblingRadius",{priorEnum:e,newValue:t}),p.Settings.inferenceSiblingRadius.value=t)}const t=p.Settings.enableSiblingInference.fileValue;if(null!=t&&null==p.Settings.inferenceSiblingRadius.fileValue&&!1===t){const e=0;g().warn("Upgrading setting enableSiblingInference to inferenceSiblingRadius",{priorBool:t,newValue:e}),p.Settings.inferenceSiblingRadius.value=e}}{const e=p.Settings.rejectRatingsLessThan.fileValue;if(null!=e&&null==p.Settings.rejectRating.fileValue){const t=e-1,i="-"+(t>0?"+":"")+t;g().warn("Upgrading setting rejectRatingsLessThan to rejectRating",{newValue:i}),p.Settings.rejectRating.value=i}}{const e=p.Settings.fileCopyOnlyNative.fileValue,t=p.Settings.fileCopyWithReflink.fileValue;if((null!=e||null!=t)&&null==p.Settings.fileCopyStrategy.fileValue){let i;i=!0===e?m.FileCopyStrategies["native-preserve"]:!0===t?m.FileCopyStrategies["builtin-reflink"]:m.FileCopyStrategies.builtin,g().warn("Upgrading file copy settings to fileCopyStrategy",{fileCopyOnlyNative:e,fileCopyWithReflink:t,newStrategy:i}),p.Settings.fileCopyStrategy.value=i,p.Settings.fileCopyOnlyNative.unsetFileValue(),p.Settings.fileCopyWithReflink.unsetFileValue()}}},t.disableAllFilters=b,t.setStrictDeduping=w,t.setLenientDeduping=S,t.setQuickSyncMode=_,t.disableExternalNetworkRequests=E;const r=i(22573),s=i(38639),n=i(42659),a=i(68708),o=i(51926),l=i(19851),u=i(50213),c=i(55939),d=i(34580),h=i(57902),f=i(10546),m=i(27449),p=i(28874),g=(0,l.lazy)(()=>(0,u.mkLogger)("settings.MetaSettings"));function y(e,t){return p.Settings[e].value??t.find(t=>t.name===e)?.value??p.Settings[e].defaultValue}function v(e,t){return null!=p.Settings[e].value||t.some(t=>t.name===e&&null!=t.value)}function b(){p.Settings.respectFileExtensions.cliValue=!1,p.Settings.requireMakeModel.cliValue=!1,p.Settings.rejectRating.cliValue="",p.Settings.minImageDimension.cliValue=0,p.Settings.minVideoDimension.cliValue=0,p.Settings.minVideoDurationSec.cliValue=0,p.Settings.maxVideoDurationSec.cliValue=0,p.Settings.minAssetFileSizeBytes.cliValue=0,p.Settings.maxAssetFileSizeBytes.cliValue=0,p.Settings.validateJpegImages.cliValue=!1,p.Settings.validateRawImages.cliValue=!1,p.Settings.validateVideos.cliValue=!1}function w(){p.Settings.aggregationMode.cliValue="strict",p.Settings.exposureThresholdPct.defaultValue=98,p.Settings.imageHashThresholdPct.defaultValue=95,p.Settings.imageHashRelaxedThresholdPct.defaultValue=80,p.Settings.imageHashFuzzyDateThresholdPct.defaultValue=95,p.Settings.allowFuzzyDateImageHashMatches.defaultValue=!1,p.Settings.checkBasenameMatches.defaultValue=!1,p.Settings.requireSameColorSpace.defaultValue=!0,p.Settings.imageHashMatchK.defaultValue=50,p.Settings.minCapturedAtPrecisionDifferentMimetypes.defaultValue=0,p.Settings.fuzzyDatePrecisionFactor.defaultValue=1}function S(){p.Settings.aggregationMode.cliValue="lenient",p.Settings.exposureThresholdPct.defaultValue=70,p.Settings.imageHashThresholdPct.defaultValue=60,p.Settings.imageHashRelaxedThresholdPct.defaultValue=30,p.Settings.imageHashFuzzyDateThresholdPct.defaultValue=70,p.Settings.allowFuzzyDateImageHashMatches.defaultValue=!0,p.Settings.checkBasenameMatches.defaultValue=!0,p.Settings.requireSameColorSpace.defaultValue=!1,p.Settings.imageHashMatchK.defaultValue=200,p.Settings.minCapturedAtPrecisionDifferentMimetypes.defaultValue=n.minuteMs,p.Settings.fuzzyDatePrecisionFactor.defaultValue=4}const P=[p.Settings.validateJpegImages,p.Settings.validateRawImages,p.Settings.validateVideos,p.Settings.transcodeVideos,p.Settings.previewMinimized,p.Settings.previewProgressive,p.Settings.previewSharpen],M={argon2TimeCost:8,argon2MemoryCostMB:64,argon2Parallelism:1},T={argon2TimeCost:4,argon2MemoryCostMB:32,argon2Parallelism:1};function _(e){for(const t of P)t.cliValue=!e&&void 0;p.Settings.inferenceSiblingRadius.cliValue=e?0:void 0;const t=e?T:M;for(const[e,i]of(0,a.entries)(t))p.Settings[e].cliValue=i;p.Settings.dominantColorDeltaE.cliValue=e?f.ColorDistanceFunctions.cie76:f.ColorDistanceFunctions.ciede2000}function E(){p.Settings.autoUpdateCheck.cliValue=!1,p.Settings.allowUserAgent.cliValue=!1,p.Settings.reportErrors.cliValue=!1,p.Settings.autoRefreshLicense.cliValue=!1,p.Settings.noNetwork.cliValue=!0}},14112(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NetworkingSettings=void 0;const r=i(48161),s=i(57643),n=i(38483),a=i(74589),o=i(81075),l=i(80372);t.NetworkingSettings={hostname:new l.StringSetting({category:o.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,r.hostname)()}),localhost:new l.StringSetting({category:o.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 a.IntegerSetting({category:o.SettingCategories.Networking,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:s.DefaultHttpPort}),syncPort:new a.IntegerSetting({category:o.SettingCategories.Networking,description:"Localhost-only JSON RPC port for task enqueuing, progress status, and control of the PhotoStructure sync process. Defaults to httpPort + 100 (to avoid collisions from multiple libraries).",defaultValue:()=>0}),syncEventsPort:new a.IntegerSetting({category:o.SettingCategories.Networking,description:"Localhost-only port for push-based sync events (JSON Lines over TCP). The sync service uses this to stream real-time state and row updates to the web service. Defaults to syncPort + 1.",defaultValue:()=>0}),noNetwork:new n.BooleanSetting({category:o.SettingCategories.Networking,description:"If set, PhotoStructure will assume all outbound network requests will fail.",defaultValue:!1})}},89302(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRanges=void 0;const r=i(22573),s=i(54993),n=/^(?<lhs>[-+]?\d+(?:\.\d+)?)?\s*-\s*(?<rhs>[-+]?\d+(?:\.\d+)?)?$/;function a(e){if((0,r.blank)(e))return;const t=Number(e);if(isNaN(t))throw new Error("Invalid number: "+JSON.stringify(e));return t}class o{encodedString;static UnsetValue="empty";#Ar=new Set;#xr=[];constructor(e){this.encodedString=e;const t=(0,s.toS)(e).trim();this.encodedString=(0,r.blank)(t)||o.UnsetValue===t.toLowerCase()?o.UnsetValue:t;const i=this.encodedString===o.UnsetValue?[]:this.encodedString.split(",");for(const e of i){const t=Number(e);if(isNaN(t)){const t=n.exec(e.trim())?.groups;if(null==t)throw new Error(`Invalid part: ${JSON.stringify(e)}`);const i=a(t.lhs),r=a(t.rhs);if(null==i&&null==r)throw new Error(`Invalid range format (missing both lhs and rhs of a range): ${JSON.stringify(e)}`);i===r?this.#Ar.add(i):(null!=i&&this.#Ar.add(i),null!=r&&this.#Ar.add(r),this.#xr.push([i,r]))}else this.#Ar.add(t)}}test(e){if(!this.encodedString)return!1;if(this.#Ar.has(e))return!0;for(const[t,i]of this.#xr)if((null==t||e>=t)&&(null==i||e<=i))return!0;return!1}toString(){return this.encodedString}}t.NumericRanges=o},3964(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NumericRangesSetting=void 0;const r=i(45599),s=i(70978),n=i(89302),a=i(80372);class o extends a.StringSetting{constructor(e){super({...e,whyInvalid:e=>{try{return void new n.NumericRanges(e)}catch(e){return(0,s.toError)(e)?.message??"Invalid format: "+String(e)}}}),this.watchLater(()=>this.#Di.reset())}hasValue(){return null!=this.value}#Di=(0,r.defer)(()=>{try{const e=this.value;if(null!=e)return new n.NumericRanges(e)}catch{}try{return new n.NumericRanges(this.defaultValue)}catch{}return new n.NumericRanges("")});test(e){return this.#Di().test(e)}}t.NumericRangesSetting=o},66915(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalBooleanSetting=void 0;const r=i(22573),s=i(38639),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:r.notBlankToS,fromEnv:s.toBoolean,defaultValue:void 0,...e})}}t.OptionalBooleanSetting=a},23561(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalFloatSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({defaultValue:void 0,...e,toEnv:r.notBlankToS,fromEnv:s.toFloat})}}t.OptionalFloatSetting=a},69005(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalIntegerSetting=void 0;const r=i(22573),s=i(31586),n=i(83179);class a extends n.Setting{constructor(e){super({...e,toEnv:r.notBlankToS,fromEnv:s.toInt,defaultValue:void 0})}}t.OptionalIntegerSetting=a},87652(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalStringSetting=void 0;const r=i(83179);class s extends r.Setting{constructor(e){super({toEnv:e=>e?.trim(),fromEnv:e=>e,defaultValue:void 0,...e})}hasValue(){return null!=this.value}}t.OptionalStringSetting=s},65573(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OrganizationSettings=void 0;const r=i(38483),s=i(81075),n=i(58305),a=i(80372);t.OrganizationSettings={copyAssetsToLibrary:new r.BooleanSetting({aliases:["copyToLibrary"],category:s.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.\nRead more about this setting here: https://photostructure.com/getting-started/automatic-library-organization/ .',defaultValue:!0,advanced:()=>!1}),copyToLibraryMimeTypes:new n.StringArraySetting({category:s.SettingCategories.Organization,description:'When "automatic organization" is enabled, files whose mimetypes are included in this list will be copied into your originals directory.\nNote that MIME types can include an asterisk to do glob-matching.\nSee the related system setting "copyAssetsToLibrary".\nA list of MIME types are here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types .',defaultValue:()=>["image/*","video/*"]}),assetPathnameFormat:new a.StringSetting({category:s.SettingCategories.Organization,description:'If you opt into "automatic organization" (see the setting "copyAssetsToLibrary"), they will be copied into <originals directory>/<result of assetPathnameFormat>.\n- See the originalsDir system setting for what your <originals directory> is (it defaults to your library root directory).\n- Please encode this path with forward-slashes, even if you\'re on Windows.\n- If any patterns resolve to including forward-slashes, know that will be interpreted as subdirectories.\n- If you want to add a static path, escape the pathname with single quotes (like "\'photos\'/y/MM/dd").\n- The result of this will always be interpreted as a relative path from your PhotoStructure originals directory.\n- Use token "BASE" as a shorthand for the original basename ("photo.jpg" for "/path/to/photo.jpg").\n- Use token "NAME" as a shorthand for the original filename, without the file extension ("photo" for "/path/to/photo.jpg").\n- Use token "PARENT" as a shorthand for the original file\'s parent directory name ("to" for "/path/to/photo.jpg").\n- Use token "GRANDPARENT" as a shorthand for the original file\'s grandparent directory name ("path" for "/path/to/photo.jpg").\n- Use token "EXT" for the filename\'s extension without the "." prefix (like "jpg" for "/path/to/photo.jpg").\n- Use token "ISO" as a shorthand for "yyyy-MM-dd\'T\'HH-mm-ss.SSSZZ" (the time separators are dashes here as colon is an illegal character for some filesystems).\n- 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.\n- You can escape other static text by wrapping with single quotes.\n- For other tokens, see https://moment.github.io/luxon/#/formatting?id=table-of-tokens .\n- For more details, see https://forum.photostructure.com/t/how-to-change-the-naming-structure/1184/2',defaultValue:"y/y-MM-dd/BASE"}),assetSubdirectoryDatestampFormat:new a.StringSetting({category:s.SettingCategories.Organization,envAliases:["PS_ASSET_SUBDIR_FORMAT"],description:'This setting has been replaced by "assetPathnameFormat".\nIf this setting is provided, and assetPathnameFormat is _not_ provided, we will give assetPathnameFormat the value of this setting + "/BASE".',defaultValue:"",deprecated:!0}),writeSourceTagToLibraryCopies:new r.BooleanSetting({category:s.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 r.BooleanSetting({category:s.SettingCategories.Organization,description:"When enabled, inferred metadata will be stored as _actual_ metadata in the library copy.",defaultValue:!0}),overwriteOriginal:new r.BooleanSetting({category:s.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})}},57414(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.ParsingSettings=void 0,t.isSiblingInferenceEnabled=function(){return(0,l.gt0)(t.ParsingSettings.inferenceSiblingRadius.valueOrDefault)};const o=a(i(77988)),l=i(31586),u=i(4328),c=i(71300),d=i(48987),h=i(38483),f=i(75164),m=i(57039),p=i(9945),g=i(74589),y=i(87652),v=i(81075),b=i(58305),w=i(57571),S=i(80496);t.ParsingSettings={capturedAtTagsPrimary:new b.StringArraySetting({category:v.SettingCategories.Parsing,aliases:["capturedAtTags"],description:'The following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsSecondary" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:c.CapturedAtTagsPrimary}),capturedAtTagsSecondary:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:'If no capturedAtTagsPrimary are defined, the following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsTertiary" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:c.CapturedAtTagsSecondary}),capturedAtTagsTertiary:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:'If no capturedAtTagsPrimary or capturedAtTagsSecondary are defined, the following tags are examined to determine when a file was captured at.\nThe tag with the oldest valid value is returned: order here doesn\'t matter.\nIf none of these tags have a valid datetime stamp, PhotoStructure will fall back to "capturedAtTagsFallback" tags.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:c.CapturedAtTagsTertiary}),capturedAtTagsFallback:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:'If none of the "capturedAtTags" have a valid value, PhotoStructure will fallback to look at these tags. These tags are only "fallbacks" as they sometimes contain spurious values.\nSee https://photostructure.com/faq/captured-at/ for details.',defaultValue:c.CapturedAtTagsFallback}),useMWG:new h.BooleanSetting({category:v.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 b.StringArraySetting({category:v.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 h.BooleanSetting({category:v.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 y.OptionalStringSetting({category:v.SettingCategories.Parsing,description:"If PhotoStructure doesn't find a value for Copyright in a source image or source video, it will apply the given string as the copyright holder.\nThis has no default."}),likeRating:new g.IntegerSetting({category:v.SettingCategories.Parsing,description:'What\'s the minimum "rating" for an asset to be considered "liked"?\nKnow that metadata "ratings" are stored in both EXIF and XMP "Rating" and "RatingPercent" tags. Ratings are typically encoded as a value between -1 and 5 (where -1 is used by some DAMs to mark "rejected").\nPhotoStructure will prefer the XMP Rating tag.\nIf the only tag with a rating is a "RatingPercent", it will be converted to a 5-point scale.\nIf you want only ratings of 5 to be considered a "liked" asset, set this to 5.\nThis value will be used when assets are liked via the PhotoStructure UI.\nNote that PhotoStructure doesn\'t import assets with a negative Rating (to respect the "rejected" rating).',defaultValue:()=>3}),lensMakes:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:"Used to extract and parse lens metadata (useful when Google Takeout has stripped metadata).",defaultValue:()=>d.DefaultLensMakes}),numericTags:new b.StringArraySetting({category:v.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.\nCaution: 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:()=>o.DefaultExifToolOptions.numericTags}),extraDateTimeFormats:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:'These formats are used to parse datetime strings in EXIF metadata and in file pathnames. Note that we will try each format with each value from "extraDateTimeZoneSuffixes," and once without a timezone suffix. See https://moment.github.io/luxon/#/formatting?id=table-of-tokens for a description of these tokens.',defaultValue:()=>u.DefaultDateTimeFormats}),extraDateTimeZoneSuffixes:new b.StringArraySetting({category:v.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:()=>u.DefaultTimezoneSuffixes}),preferTimezoneInferenceFromGps:new h.BooleanSetting({category:v.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?\nNote 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 h.BooleanSetting({category:v.SettingCategories.Parsing,description:'Allow parsing of archaic timezone offsets that are no longer in use.\n\nThese include historical offsets like:\n- "-10:30" (Hawaii 1896-1947)\n- "-04:30" (Venezuela 1912-1965, 2007-2016)\n- "+04:51" (Bombay until 1955)\n- and others from\n https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\n\n**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:()=>o.Settings.allowArchaicTimezoneOffsets.defaultValue,onChange:e=>o.Settings.allowArchaicTimezoneOffsets.value=e}),allowBakerIslandTime:new h.BooleanSetting({category:v.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:()=>o.Settings.allowBakerIslandTime.defaultValue,onChange:e=>o.Settings.allowBakerIslandTime.value=e}),fuzzyDateParsing:new h.BooleanSetting({category:v.SettingCategories.Parsing,description:'When enabled, PhotoStructure will first attempt to parse datetime strings with strict ISO-compliant parsers, and then use additional, "fuzzy" datetime parsers. When disabled, only ISO-compliant parsers are used.',defaultValue:!0}),fuzzyYearParsing:new h.BooleanSetting({category:v.SettingCategories.Parsing,description:'When enabled, PhotoStructure will use directories starting with a number that looks year-like (four digits, 1826-the present) to infer the captured-at time, if all other date parsers have failed. Note that setting this to true "forces" the "fuzzyDateParsing" setting to be true.\nTo elaborate: PhotoStructure first looks for metadata with a date, then looks for an ISO-compliant YMD timestamp in the filename or path, and then, if "fuzzyDateParsing" or this setting is enabled, a YMD or YM datestamp, and then finally, if this setting is enabled, it looks for a directory that begins with a number that is between 1826-2020.',defaultValue:!1}),twoDigitCutoffYear:new g.IntegerSetting({category:v.SettingCategories.Parsing,description:'If "yy" is used in extraDateTimeFormats, and a year is only 2 digits, what threshold value should be used to consider the date to be in the 1900s vs 2000s?\nAs an example, a value of "50" would make "49" be interpreted as 1949, and "50" as 2050.\nSee https://moment.github.io/luxon/api-docs/index.html#settingstwodigitcutoffyear for details.\nThis defaults to 3 years in the future (modulus 100) and is updated automatically.',defaultValue:()=>((new Date).getFullYear()+3)%100}),minValidYear:new g.IntegerSetting({category:v.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.\nFor 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 ).\nYou should set this to the earliest year you expect to find in your library.",defaultValue:()=>1880}),maxValidFutureMs:new m.DurationSetting({category:v.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.\nSet to 0 to disable future date filtering.",defaultValue:()=>"2d"}),omittedDescriptions:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:'Olympus sometimes adds OLYMPUS DIGITAL CAMERA as the ImageDescription--if the title or description matches the camera id, or "OLYMPUS DIGITAL CAMERA", it\'s not valid, and we will look elsewhere for the title or description.',defaultValue:()=>["OLYMPUS DIGITAL CAMERA"]}),descriptionTags:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:"Look in these tag names, in this order, for the description of a given media file.\nDefault order rationale:\n1. XPSubject: Windows-specific EXIF tag for explicit user annotations (~0.07% of photos)\n2. Description: XMP dc:description - modern standard preferred by DAM software (~20% of photos)\n3. ImageDescription: EXIF tag, more common (~40%) but often contains camera-generated boilerplate\n4. Caption-Abstract: Legacy IPTC IIM field (2:120), limited to ~2000 chars\nXMP Description is prioritized over EXIF ImageDescription because XMP typically contains user-intentional metadata, while ImageDescription often contains camera-embedded defaults.\nReferences: https://iptc.org/std/photometadata/documentation/mappingguidelines/ , https://exiftool.org/forum/index.php?topic=12940.0 , https://photo.stackexchange.com/questions/128015",defaultValue:()=>["XPSubject","Description","ImageDescription","Caption-Abstract"]}),titleTags:new b.StringArraySetting({category:v.SettingCategories.Parsing,description:"Look in these tag names, in this order, for the title of a given media file.",defaultValue:()=>["XPTitle","Title","ObjectName"]}),useStatToInferDates:new h.BooleanSetting({category:v.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in the file "birthtime" (on Windows), or the lesser value of "mtime" and "ctime" (on macOS and Linux). Note that these values are not very reliable, as file transfers and backups frequently don\'t retain these values correctly.',defaultValue:!0}),usePathsToInferDates:new h.BooleanSetting({category:v.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 h.BooleanSetting({category:v.SettingCategories.Parsing,description:'When enabled, and the "captured-at" time isn\'t found in metadata, PhotoStructure will also look for the captured-at datetime encoded in file paths *for files that are in your PhotoStructure library. This defaults to false, as prior versions of PhotoStructure may have placed files into incorrect datestamped directories.',defaultValue:!1}),backfillTimezones:new h.BooleanSetting({category:v.SettingCategories.Parsing,description:"Should we try to backfill timezones for date-times that don't have them? If set to true, and {@link defaultVideosToUTC} is also true, we'll try backfilling timezones for date-times that are UTC, as well.\nSetting this to false removes **all** timezone inference--only those date-times with an explicit offset will have a defined timezone.\nPrior versions of exiftool-vendored would use the file's \".zone\" as a backstop even if this was set to false.\nAs of version 2023.10, this now defaults to true, as it's more likely to be what people expect.",defaultValue:!0}),inferTimezoneFromDatestamps:new h.BooleanSetting({category:v.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.\nIf these strategies fail, and this is enabled, we'll try to infer the timezone from non-UTC datestamps included in the {@link capturedAtTags} and {@link capturedAtTagsFallback} settings.\nThis defaults to true as of version 2023.10.",defaultValue:!0}),enableSiblingInference:new h.BooleanSetting({category:v.SettingCategories.Parsing,deprecated:!0,description:'This setting has been replaced by "inferenceSiblingRadius". Set inferenceSiblingRadius to 0 to disable sibling inference.',defaultValue:!0}),siblingInference:new w.StringEnumSetting({category:v.SettingCategories.Parsing,deprecated:!0,description:'This setting has been replaced by "inferenceSiblingRadius". Set inferenceSiblingRadius to 0 to disable sibling inference.',strEnum:S.TagInferenceSettingValues,defaultValue:S.TagInferenceSettingValues.auto}),siblingInferenceBasenameCoeff:new p.FloatSetting({category:v.SettingCategories.Parsing,deprecated:!0,description:'This setting has been replaced by the siblingInferenceBasenameCoeffPct" setting.',defaultValue:.6}),siblingInferenceBasenameCoeffPct:new f.BoundedIntegerSetting({category:v.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?\n0 will accept all siblings, 100 will only accept exact matches.",defaultValue:60,max:100,min:0}),inferenceSiblingRadius:new f.BoundedIntegerSetting({category:v.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})}},29985(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PathSettings=void 0;const r=i(38483),s=i(87652),n=i(81075),a=i(58305),o=i(80372);t.PathSettings={libraryDir:new s.OptionalStringSetting({aliases:["libraryPath","library"],category:n.SettingCategories.Paths,description:"This is the absolute path to your PhotoStructure library. If missing, or set to an empty string, the welcome page will be shown when PhotoStructure launches. Use native file separators (so on windows, use back-slashes).",defaultValue:()=>"",advanced:()=>!1}),previewsDir:new o.StringSetting({category:n.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store preview images. This defaults to the ".photostructure/previews" directory inside your PhotoStructure library. Absolute paths here are supported, but if you keep your library and previews directory separated, take care when you open your library on different computers, as this setting needs to be adjusted for those computers as well.\nNOTE: "originalDirs" is recommended instead of this setting; If you get "previewsDir" wrong, your library won\'t work. If you get "originalsDir" wrong, you just break full-screen asset zooming and playback for non-transcoded videos.\nFor more details see https://forum.photostructure.com/t/hybrid-photostructure-libraries/775',defaultValue:()=>".photostructure/previews"}),originalsDir:new o.StringSetting({aliases:["originalDir"],category:n.SettingCategories.Paths,description:'This is the directory that PhotoStructure uses to store original images when "copyAssetsToLibrary" is enabled. Absolute paths are supported. Relative paths are evaluated from your libraryDir. This setting defaults to ".", which is the same as your PhotoStructure library directory, unless you are on docker, and a /ps/originals directory exists.\nIf you open your PhotoStructure library on a different computer, and that computer doesn\'t have access to your originals volume, full-screen zoom won\'t work, and non-transcoded videos will not play.\nThis system setting needs to be set appropriately on different computers (it won\'t be set automatically!)\nIf you have a large library and want to use an SSD, we recommend you set your libraryDir to your SSD, and use this setting to store your originals on a larger volume, rather than using the "previewsDir" setting.\nFor 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 s.OptionalStringSetting({category:n.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 r.BooleanSetting({category:n.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 r.BooleanSetting({category:n.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 a.StringArraySetting({aliases:["scanPath"],category:n.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 a.StringArraySetting({category:n.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 s.OptionalStringSetting({category:n.SettingCategories.Paths,envAliases:["PIDFILE"],description:"This is the absolute path to the PID file for the main process. This is optional and only used by PhotoStructure for Servers. Make sure the UID/GID that PhotoStructure runs as can read and write to this file.",exampleValue:()=>"/var/run/photostructure.pid"}),cacheDir:new o.StringSetting({category:n.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.\nNote that if PS_FORCE_LOCAL_DB_REPLICA is enabled, the local DB replica will be stored in this directory while PhotoStructure is running: don't delete it!\nIf this is set to /tmp PhotoStructure will write to a user-specific /tmp/.photostructure-cache-$UID directory.",defaultValue:()=>""})}},4936(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filenameSafeSha=S,t.pathToLibraryAsset=function(e,t,i){const s=(0,h.datedToDateTime)(e)??(0,l.map)((0,h.datedToISO)(e),e=>r.DateTime.fromISO(e));if(null==s||!s.isValid)return v().tap({msg:"pathToLibraryAsset(): failed to convert to a valid date",result:void 0,meta:{capturedAt:e,src:t,dt:s}});const n=(0,f.hasZone)(e),o=y.Settings.assetPathnameFormat.valueOrDefault,c=(0,d.splitKeep)(o,/(GRANDPARENT|PARENT|BASE|NAME|EXT|ISO|SHORTSHA)/g);for(let e=0;e<c.length;e++)switch(c[e]){case"GRANDPARENT":c[e]=w((0,m.grandParentBasename)(t));break;case"PARENT":c[e]=w((0,m.parentBasename)(t));break;case"BASE":c[e]=w(t.base);break;case"NAME":c[e]=w(t.name);break;case"EXT":c[e]=w((0,u.stripPrefix)(t.ext,"."));break;case"ISO":c[e]="yyyy-MM-dd'T'HH-mm-ss.SSS"+(n?"ZZZ":"");break;case"SHORTSHA":c[e]=w(S(i));break;default:(0,d.countChars)(c[e],"'")%2==1&&(c[e]=(0,u.replaceAll)(c[e],"'","′"))}const g=(P=s.toFormat(c.join("")),(0,u.replaceAll)(P,b,"'")).split("/").map(e=>(0,p.mkValidFilename)(e));var P;return v().tap({msg:"pathToLibraryAsset()",result:(0,a.compactBlanks)(g),meta:{capturedAt:e,src:t,dt:s,assetPathnameFormat:o,tokens:c}})};const r=i(51168),s=i(4573),n=i(19851),a=i(40958),o=i(22573),l=i(55835),u=i(51926),c=i(50213),d=i(81168),h=i(79842),f=i(93515),m=i(29882),p=i(10234),g=i(55222),y=i(28874),v=(0,n.lazy)(()=>(0,c.mkLogger)("settings.PathToLibraryAsset")),b="′";function w(e){return(0,o.blank)(e)?"":"'"+e.replace(/'/g,b)+"'"}function S(e,t=8){return(0,o.blank)(e)?"":g.TokenRadix.encodeBuffer(s.Buffer.from(e,"base64")).slice(0,t)}},63972(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PerformanceSettings=void 0;const r=i(38483),s=i(81075);t.PerformanceSettings={emitTimingsOnExit:new r.BooleanSetting({category:s.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 r.BooleanSetting({category:s.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 r.BooleanSetting({category:s.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})}},13759(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PreviewsSettings=void 0;const r=i(40958),s=i(73722),n=i(52086),a=i(33209),o=i(30933),l=i(38483),u=i(90536),c=i(75164),d=i(9945),h=i(66915),f=i(81075),m=i(76989),p=i(58305),g=i(57571),y=i(72564);t.PreviewsSettings={previewQuality:new c.BoundedIntegerSetting({aliases:["jpegQuality"],category:f.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 l.BooleanSetting({category:f.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 l.BooleanSetting({aliases:["jpegMinimized","previewMinimised","jpegMinimised"],category:f.SettingCategories.Previews,description:'Should preview JPEGs be optimized? If set, preview generation can take 50% longer, but can result in up to ~30% smaller images. This saves disk space and network transport time.\nThis setting controls the "mozjpeg" option: see https://sharp.pixelplumbing.com/api-output#jpeg for details.\nThis automatically defaults to true if at least 4 CPU cores are present.',defaultValue:()=>!!(0,m.isNotProd)()||(0,o.cpuCount)()>=4}),dcrawEmuArgs:new p.StringArraySetting({category:f.SettingCategories.Previews,description:'What options do you want to pass to dcraw_emu? Note that "-T -o 1 -j -Z -" will always be added (as we need TIFF, sRGB, raw pixels send to stdout). The "-h" arg will be added if the preview image needed is less than half the resolution of the original.\nRun "dcraw_emu" with no arguments to get usage help.\n"-q 1" sets interpolation quality to "0".\n"-H 2" turns on highlight blending.\n"-w" uses the camera-set white balance.\nNote: changing these values can dramatically (> 10x!) increase the time it takes to render RAW images.',defaultValue:["-q","0","-w"]}),iccProfileMappings:new p.StringArraySetting({category:f.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 g.StringEnumSetting({category:f.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:n.CropStrategies.attention,strEnum:n.CropStrategies}),videoFrameAtSec:new d.FloatSetting({category:f.SettingCategories.Previews,description:"When capturing a frame from videos for thumbnails, how many seconds should be passed over before capturing a frame? A value of 0 means capture from the start of the video. Frequently, though, videos start out of focus, so we default to 1.5 for better frame clarity.\nNote that if a video is shorter than this value, the frame will be captured from the middle of the video.",defaultValue:1.5}),previewSharpen:new l.BooleanSetting({aliases:["sharpen"],category:f.SettingCategories.Previews,description:'Should previews be sharpened? This can make the images "pop" a bit more, but almost doubles the time it takes to make the thumbnails.',defaultValue:!1}),previewResolutions:new y.StringEnumsSetting({category:f.SettingCategories.Previews,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with <= previewMinPixelCoeff pixel count, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.",defaultValue:(0,r.diff)(s.FitSizes.values,["uhd8k","uhd5k"]),strEnum:s.FitSizes}),exactFitResolutions:new y.StringEnumsSetting({category:f.SettingCategories.Previews,description:'When PhotoStructure builds a set of preview images, it ensures there is a preview that fits for all the resolutions specified in this setting. If, completely hypothetically, you\'re working on a Chromecast implementation, you\'d set this to ["fhd", "hd", "qvga", "qqvga"].\nPhotoStructure will never scale previews to be larger than the native asset\'s resolution.\nSee https://en.wikipedia.org/wiki/Graphics_display_resolution for a description of these resolution codes.',defaultValue:["qvga","qqvga"],strEnum:s.FitSizes}),previewScaleThreshold:new d.FloatSetting({category:f.SettingCategories.Previews,aliases:["previewMinPixelCoeff"],description:"When calculating which preview sizes should be calculated, PhotoStructure will skip previewResolutions that are not in exactFitResolutions, and are less than this pixels different from other preview sizes being built.\nSet this to 1 to not skip any preview resolutions, and higher numbers to save disk space (at the cost of having fewer preview sizes available).",defaultValue:2.5}),previewOriginalDirectly:new h.OptionalBooleanSetting({category:f.SettingCategories.Previews,description:"Can PhotoStructure skip generating a preview size for assets that are in a natively-supported browser format (like JPEG)?\nIf you know you'll never eject any synced directories and you aren't using copyAssetsToLibrary, set this to true.\nIf 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 p.StringArraySetting({category:f.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 p.StringArraySetting({category:f.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.\nNote that this does not include ThumbnailImage or ThumbnailTIFF, as those can be letterboxed.\nSet this to an empty array to disable using embedded previews.",defaultValue:["PreviewImage","PreviewTIFF","JpgFromRaw","JpgFromRaw2"]}),embeddedThumbnails:new p.StringArraySetting({category:f.SettingCategories.Previews,description:"Should embedded image thumbnails be used when available? This speeds up image hashing, but if the embedded image thumbnail doesn't match the full-sized image, the image hash will be incorrect.\nSet this to an empty array to disable using embedded previews.",defaultValue:["ThumbnailImage","ThumbnailTIFF"]}),maxThumbTrimPct:new u.BoundedFloatSetting({category:f.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 c.BoundedIntegerSetting({category:f.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 l.BooleanSetting({category:f.SettingCategories.Previews,description:"Only used for tests.",advanced:()=>!0,defaultValue:!1,transient:!0,propagateToChildren:!1}),includePreviewTags:new l.BooleanSetting({category:f.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 p.StringArraySetting({category:f.SettingCategories.Previews,description:'If "includePreviewTags" is true, what tags should PhotoStructure retain when building preview images? A partial list of tags is here: https://photostructure.github.io/exiftool-vendored.js/interfaces/Tags.html . Note that not all files contain all (or even some!) of those tags.\n- "capturedAt" is a special meta-tag which will retain whatever tag contains the "best" time that PhotoStructure could find that encoded the date and time when the image was captured, and will store that value in DateTimeOriginal.\n- "exposureSettings" is a special meta-tag that will retain shutter time (ExposureTime), aperture (FNumber), and ISO (ISOSpeed) metadata (but may be encoded with different values).\n- including "GPSLatitude" and "GPSLongitude" will mean previews will contain location metadata if the source image had location metadata.',defaultValue:()=>a.DefaultIncludedPreviewTags})}},22834(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PrivacySettings=void 0;const r=i(34580),s=i(38483),n=i(81075);t.PrivacySettings={allowUserAgent:new s.BooleanSetting({category:n.SettingCategories.Privacy,description:"Can PhotoStructure include a User-Agent header that includes basic installation information when it makes external requests, like for the version update check?\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.",defaultValue:!0}),optOut:new s.BooleanSetting({aliases:["doNotTrack"],envAliases:r.DO_NOT_TRACK_ENV_KEYS,category:n.SettingCategories.Privacy,description:'If set to true, your library will not originate external network requests.\nThis is a "meta" setting that currently sets "reportErrors=false", "autoUpdateCheck=false", and "allowUserAgent=false".\nThis setting will be kept up to date with any other feature that could result in an external network request (like, for example, reverse geocoding).\nTechnically speaking, this is **not** the same as "DNT" (Do Not Track) or "GPC" (Global Privacy Control), because PhotoStructure, Inc. **never shares or sells any user telemetry or data** (so "DNT" is always _technically_ true!), but we check and respect "DO_NOT_TRACK", "DNT" and "GPC" as aliases for this setting.\nSee https://photostructure.com/legal/privacy/ for more details about PhotoStructure\'s privacy policies.',defaultValue:()=>(0,r.doNotTrack)()})}},23135(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProcessesSettings=void 0;const r=i(58587),s=i(70488),n=i(79840),a=i(43334),o=i(12801),l=i(38483),u=i(75164),c=i(57039),d=i(9945),h=i(74589),f=i(69005),m=i(81075),p=i(76989),g=i(57571),y=i(80372);t.ProcessesSettings={shortProcessNames:new l.BooleanSetting({category:m.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:()=>!(0,a.isElectron)()}),minDelayBetweenSpawnMs:new c.DurationSetting({category:m.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:()=>(0,s.encodeDuration)((new r.BatchClusterOptions).minDelayBetweenSpawnMillis)}),minDelayBetweenRetriesMs:new c.DurationSetting({category:m.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 h.IntegerSetting({category:m.SettingCategories.Processes,description:"If a task has an error, how many times should we retry before giving up?\nIf you have a flaky network, this can help ensure imports are comprehensive.\nSet this to 0 to disable retries.",defaultValue:()=>2}),problematicCooldownMs:new c.DurationSetting({category:m.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 h.IntegerSetting({category:m.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 c.DurationSetting({category:m.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 c.DurationSetting({category:m.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:()=>(0,p.isNotProd)()?"30s":"5m"}),streamFlushMs:new c.DurationSetting({category:m.SettingCategories.Processes,aliases:["streamFlushMillis"],description:"See https://photostructure.github.io/batch-cluster.js/classes/BatchClusterOptions.html#streamFlushMillis",defaultValue:()=>"10ms"}),healthCheckIntervalMs:new c.DurationSetting({category:m.SettingCategories.Processes,description:"How often should the main process check on the health of the web and sync subprocesses?",defaultValue:()=>"2m"}),exiftoolProcsPerChild:new f.OptionalIntegerSetting({category:m.SettingCategories.Processes,description:'Controls the number of exiftool child processes allowed by the sync process. Note that each PhotoStructure process may spin up an ExifTool child process if needed. The "web" and "worker" services are limited to a single exiftool child process.\nIf this is unset, "sync" will default to the number of supported concurrent imports.'}),sensitiveEnvRegExp:new y.StringSetting({category:m.SettingCategories.Processes,description:'PhotoStructure spawns several external processes, including "exiftool" and "ffmpeg".\nPhotoStructure filters out environment keys that are likely to contain sensitive information (like API access tokens or passwords) from these child processes so they aren\'t accidentally logged or accessible by external tools.\nThis regex is applied case-insensitively.',defaultValue:()=>n.DefaultSensitiveEnvRegexPattern}),syncExitTimeoutMs:new c.DurationSetting({category:m.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 c.DurationSetting({category:m.SettingCategories.Processes,description:"If a service (like web or sync) is restarted due to an error, how many milliseconds must elapse before another restart is allowed? This helps prevent system load due to service flapping.",defaultValue:"7s"}),maxRestartsPerMinute:new h.IntegerSetting({category:m.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.",defaultValue:10}),singleThreaded:new l.BooleanSetting({category:m.SettingCategories.Processes,description:"Run the sync process in single-process mode: no external worker processes will be spawned, and file imports will be done serially. This is useful for debugging or on very constrained systems.\nPreviously, this was triggered by setting cpuBusyPercent to 1.",defaultValue:!1}),cpuBusyPercent:new u.BoundedIntegerSetting({category:m.SettingCategories.Processes,aliases:["cpuLoadPercent","cpuPct"],description:'This setting is a rough goal for PhotoStructure to load the system during library synchronization. A higher value here will allow PhotoStructure to run more tasks in parallel, but may impact your system\'s responsiveness.\nUnder normal circumstances, setting this to any value over 100 will result in full CPU saturation, and is not recommended, as it will cause spurious timeouts leading to some percentage of failed imports.\nWhile syncing, PhotoStructure will not dequeue sync file jobs if the current system busy percent exceeds this value.\nSetting this value to 0 will disable CPU load-based throttling, and allow the sync process to run up to maxConcurrentImports concurrent imports.\nTo run in single-process mode, set the "singleThreaded" setting to true.',defaultValue:75,min:0,max:100}),timeoutThrottleCoeff:new d.FloatSetting({category:m.SettingCategories.Processes,description:"When timeouts are detected, PhotoStructure throttles back concurrency automatically, with the assumption that some system is currently being overwhelmed and that less load should result in fewer failures due to timeouts.\nSpecifically, concurrency will be set to 1 / current rate of timeouts per minute over the past several minutes.\nThrottling will be more aggressive as this value approaches 0. For example a value of 0.1 will be very aggressive throttling. A value of 8 will only slow down sync after many soft timeouts.\nDisable throttling by setting to 0.",defaultValue:1}),maxConcurrentImports:new f.OptionalIntegerSetting({category:m.SettingCategories.Processes,aliases:["maxSyncFileJobs"],advanced:()=>!0,description:'How many imports can PhotoStructure schedule concurrently?\nIf not set, a sensible value will be computed based on "cpuBusyPercent" and available memory.\nIf set explicitly, this is taken at face value — PhotoStructure will not clamp it down — and overrides "cpuBusyPercent" and "maxConcurrentImportsWhenRemote". Use with care: oversubscribing CPU or memory may cause sync to erroneously timeout import tasks or crash. Dogs and cats, living together. Mass hysteria.'}),maxConcurrentImportsWhenRemote:new h.IntegerSetting({category:m.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 u.BoundedIntegerSetting({category:m.SettingCategories.Processes,aliases:["sharpThreadsPerJob"],advanced:()=>!0,description:"How many image processing threads can be spun per process?\nIf set to 0 (the default), PhotoStructure will pick an optimal value based on available memory and CPU cores.",min:0,max:8,defaultValue:0}),processPriority:new g.StringEnumSetting({category:m.SettingCategories.Processes,description:'By default, PhotoStructure runs child processes with a "below normal" priority, so your system remains usable while imports run. Changing this value to "normal" or "above normal" may speed up imports but cause your system to be unresponsive. Changing this value to "idle" may prevent imports from running at all.\nFor Linux and macOS systems, see https://en.wikipedia.org/wiki/Nice_%28Unix%29 .\nFor Windows, see https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processpriorityclass?view=netframework-4.8 .',defaultValue:()=>o.PriorityClasses.BelowNormal,strEnum:o.PriorityClasses}),maxMemoryMb:new h.IntegerSetting({category:m.SettingCategories.Processes,description:"PhotoStructure will restart services if they use more than this value (measured in megabytes, or 1,000,000 bytes).\nSet to 0 to deactivate this check.",defaultValue:()=>2048}),maxMemoryErrorMultiplier:new d.FloatSetting({category:m.SettingCategories.Processes,description:"How much larger than expected memory usage before reporting an error in health checks?\n\nExpected memory scales with database size: ~160 MB baseline + 1.0x DB file size.\nThis multiplier provides headroom for platform differences and legitimate memory usage patterns.\n\nValidated values (from MemoryScaling.stress.spec.ts benchmarks):\n- Linux: 5.0x (benchmark shows 1.0x scaling, 5x provides safety margin)\n- macOS: TODO - needs benchmark (expected 10-25x due to 2-5x higher memory usage)\n- Windows: TODO - needs benchmark\n\nTo determine the correct value for your platform, see instructions in:\nsrc/library/health/MemoryScaling.stress.spec.ts",defaultValue:()=>"linux"===process.platform?5:10}),maxTasksPerProcess:new u.BoundedIntegerSetting({category:m.SettingCategories.Processes,description:"PhotoStructure will recycle threads and worker processes after they handle this number of requests. Smaller values may reduce overall memory pressure. Larger values amortize startup costs over fewer restarts.",defaultValue:()=>(0,p.isNotProd)()?50:500,min:1,max:5e3})}},28283(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nameFromEnv=function(e){return(0,s.snake2camel)(e.replace(/^PS_/,"").toLowerCase())},t.envFromName=function(e){return(0,r.ensurePrefix)((0,s.camel2snake)(e).toUpperCase(),"PS_")};const r=i(51926),s=i(83556)},48032(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReportingSettings=void 0;const r=i(38483),s=i(75164),n=i(87652),a=i(81075);t.ReportingSettings={email:new n.OptionalStringSetting({category:a.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 r.BooleanSetting({aliases:["enableSentry"],category:a.SettingCategories.Reporting,description:"If true, PhotoStructure will send crash reports when it encounters errors. Crash reports may include the path to the file that caused an error, system metadata, and recent log messages.",defaultValue:!1,advanced:()=>!1}),maxErrorsPerDay:new s.BoundedIntegerSetting({category:a.SettingCategories.Reporting,description:"Set this to zero to remove all bugs in PhotoStructure.\nHUR HUR #DADJOKE\nIf your system generates more than this number of errors in the course of a day, the subsequent error reports will not be reported.",defaultValue:3,min:0,max:16})}},9868(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SecuritySettings=void 0;const r=i(45969),s=i(55111),n=i(38483),a=i(87652),o=i(81075),l=i(76989),u=i(72564),c=i(80372);t.SecuritySettings={exposeNetworkWithoutAuth:new n.BooleanSetting({category:o.SettingCategories.Security,description:"Normally the web service is only accessible to the computer running PhotoStructure. Setting this to true will expose your library to all computers on your network. You should own or trust all systems on that network, as there is no auth in PhotoStructure currently. Future versions of PhotoStructure will add authorization mechanisms, at which point this setting will be deleted.\n**Don't enable this unless you know what you are doing**.",defaultValue:()=>(0,r.isDocker)()||(0,l.isNotProd)()}),trustProxy:new c.StringSetting({category:o.SettingCategories.Security,description:'What reverse proxies should PhotoStructure "trust"? See <http://expressjs.com/en/guide/behind-proxies.html>.\nThis setting should either be "false" (don\'t trust any proxies), "loopback", (only trust loopback/localhost), a single subnet (like "192.168.1.0/24"), or a comma-delimited set of subnets.',defaultValue:"loopback"}),cspReportOnly:new n.BooleanSetting({category:o.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 n.BooleanSetting({category:o.SettingCategories.Security,description:"May PhotoStructure send the Upgrade-Insecure-Requests header? PhotoStructure will set the default to true automatically if it sees _any_ request is via https.\nSet this explicitly to false if you access PhotoStructure via both http (inside your LAN) and https (outside your LAN).",defaultValue:()=>!1}),cspDirective:new a.OptionalStringSetting({category:o.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 u.StringEnumsSetting({category:o.SettingCategories.Security,description:'What Helmet middleware should PhotoStructure disable?\nBy default, PhotoStructure enables all middleware, but if your reverse proxy is handling HTTP headers, you may want to remove some of Helmet\'s functionality.\nDisable all middleware by using the value "all", but know that CSP management is handled by the "cspDirective" and "cspReportOnly" settings.\nFor more details see https://github.com/helmetjs/helmet#reference',defaultValue:[],strEnum:s.HelmetPlugins})}},83179(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Setting=void 0,t.settingsToObj=function(e){const t={};for(const i of e)i.hasValue()&&(t[i.name]=i.value);return t};const r=i(57975),s=i(19851),n=i(40958),a=i(22573),o=i(79666),l=i(50357),u=i(57924),c=i(98553),d=i(55835),h=i(68708),f=i(39926),m=i(46891),p=i(42279),g=i(59455),y=i(40583),v=i(7282),b=i(81168),w=i(44198),S=i(34102),P=i(28283),M=i(81075),T=i(98778),_=i(10357);class E{opts;_name;_names;_key;_keys;_testValue;_cliValue;_envValue=(0,s.lazy)(()=>this.readFromEnv());_userValue;_fileValue;watchers=[];optsOverrides={};constructor(e){this.opts=e,(0,v.isTest)()&&(0,a.notBlank)(e.name)&&this._setName(e.name),null!=e.onChange&&this.watch(e.onChange)}isSensitive(){return!0===this.opts.sensitive}getState(){return{user:this._userValue,cli:this._cliValue,env:this.envValue,file:this._fileValue,test:this._testValue}}[r.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 null!=this.opts.whyInvalid?.(e)?void 0:this.opts.toEnv(e)}fromEnv(e){if(null==e)return;const t=this.opts.fromEnv(e);return null==t||null!=this.opts.whyInvalid?.(t)?void 0:t}normalizeValue(e){return null==e?void 0:this.fromEnv(this.toEnv(e))}#Fr(e){return`Invalid value for ${this.constructor.name} "${this.key}": ${(0,c.stringify)(e)}`}whyInvalidValue(e){const t=this.opts.whyInvalid?.(e);return null!=t?this.#Fr(e)+": "+t:this.whyInvalidEnvValue(this.toEnv(e),e)}whyInvalidEnvValue(e,t){const i=this.opts.whyInvalid?.(e);return null!=i?this.#Fr(e??t)+": "+i:null==this.fromEnv(e)?this.#Fr(e??t):void 0}get testValue(){return this._testValue}set testValue(e){if(!(0,v.isTest)())throw new 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){null==this._cliValue&&(this.cliValue=e)}get fileValue(){return this._userValue??this._fileValue}set fileValue(e){this.onChange(e,e=>this._fileValue=e)}get envValue(){return this._envValue()}set envValue(e){this.onChange(e,t=>{null==e?this.deleteFromEnv():this.addToEnv(void 0,t),this._envValue.unset()})}refreshEnvValue(e={}){const t=(0,o.shallowClone)(this.valueOrDefault);this._envValue.unset(),!0===e?.broadcastChange&&this.maybeBroadcastChange(t)}get value(){return this._testValue??this._cliValue??this._envValue()??this._userValue??this._fileValue}async withValue(e,t){const i=this._testValue,r=this._cliValue;this._testValue=void 0,this._cliValue=e;try{return await t()}finally{this._testValue=i,this._cliValue=r}}set value(e){this.userValue=null==e?void 0:e}get humanValue(){return this.value}get userValue(){return this._userValue}set userValue(e){this.onChange(e,e=>this._userValue=e)}get valueOrThrow(){const e=this.value;if(null==e)throw new Error("Missing value for setting "+this.name);return e}hasValue(){return null!=this.value}isUnset(){return null==this.value}includesEnvKey(e){return(0,b.includesIgnoreCase)(this.envKeys(),e)}envKeys(){return(0,n.uniq)([...this.keys??[],...this.names??[]])}#Or(e){return(null==e?(0,w.ciEnv)():new y.CaseInsensitiveValued(e)).getFirst(this.envKeys())}envKeyWithValue(e){return this.#Or(e)?.key}#Rr(e){return this.#Or(e)?.value}readFromEnv(e){return(0,d.map)(this.#Rr(e),e=>this.fromEnv(e))}hasEnvValue(){return null!=this.readFromEnv()}setFromEnv(e){return this.envValue=this.readFromEnv(e)}setValueIfDefined(e){null!=e&&(this.value=e)}watchLater(e){this.watchers.push(e)}watch(e){this.watchLater(e),setImmediate(()=>this.broadcastChange())}unWatch(e){(0,n.filterInPlace)(this.watchers,t=>t!==e)}broadcastChange(){const e=this.valueOrDefault;for(const t of this.watchers)t(e);return(0,S.ee)().emitThrottled("settingsChanged")}onChange(e,t){if(null!=e){const t=this.whyInvalidValue(e);if(null!=t)return void console.warn("Settings."+this.name+" rejected value:"+t,{value:e})}const i=(0,o.shallowClone)(this.valueOrDefault);t(this.normalizeValue(e)),this.maybeBroadcastChange(i)}maybeBroadcastChange(e){return(0,l.eql)(this.valueOrDefault,e)?void 0:this.broadcastChange()}get name(){return this._name}get names(){return this._names}_setName(e){if(null!=this._name&&!(0,v.isTest)())throw new Error("cannot set name twice");this._name=e,this._names=(0,n.uniq)([e,...(0,g.toA)(this.opts.aliases)]),this._key=(0,P.envFromName)(e),this._keys=(0,n.uniq)([this._key,...(0,g.toA)(this.opts.envAliases),...this._names.map(P.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 M.LibraryCategories.includes(this.category)?"library":"system"}get transient(){return!0===this.opts.transient}get propagateToChildren(){return!1!==this.opts.propagateToChildren}get advanced(){return(0,d.mapOr)(this.opts.advanced,e=>e(),()=>!0)}get envValueOrDefault(){return this.toEnv(this.valueOrDefault)}set testValueIfUnset(e){this.isUnset()&&(this.testValue=e)}addToChildProcessEnv(e,t){const i=t?this.value:this._testValue??this._cliValue??this._envValue();return null==i||(0,l.eql)(i,this.defaultValue)||this.addToEnv(e,i),e}get defaultValue(){return(0,p.tot)(this.optsOverrides.defaultValue)??(0,p.tot)(this.opts.defaultValue)}set defaultValue(e){const t=(0,o.shallowClone)(this.valueOrDefault);this.optsOverrides.defaultValue=e,this.maybeBroadcastChange(t)}resetDefaultValue(){this.optsOverrides.defaultValue=void 0}get exampleValue(){return(0,p.tot)(this.optsOverrides.exampleValue??this.opts.exampleValue)}set exampleValue(e){this.optsOverrides.exampleValue=e}get valueOrDefault(){return this.value??this.defaultValue}addToEnvMaybe(e,t){const i=e??process.env,r=t??this.value;return null!=r&&(i[this.key]=this.toEnv(r)),i}toEnvValue(e){return this.toEnv(e??this.valueOrDefault)}addToEnv(e,t){const i=e??process.env,r=this.toEnvValue(t);return null!=r&&(i[this.key]=r),i}deleteFromEnv(e){const t=e??process.env;for(const e of[...this.names,...this.keys])delete t[e];return t}unsetCliValue(){this._cliValue=void 0}unsetTestValue(){this._testValue=void 0}unsetCachedEnvValue(){this._envValue.unset()}unsetFileValue(){this._userValue=void 0,this._fileValue=void 0}unset(e){return!0!==e?.preserveTestValue&&(this._testValue=void 0),this._cliValue=void 0,this._envValue.unset(),!0!==e?.preserveEnv&&this.deleteFromEnv(),this._userValue=void 0,this._fileValue=void 0,this.broadcastChange(),this}factoryReset(){return this.unset(),this.resetDefaultValue(),this}addToJsonDocs(){return{}}toJSON(){return{key:this.key,value:this.value,valueOrDefault:this.valueOrDefault}}toCommentedLines(){const e=this.name+" or "+this.key,t=(0,b.wrap)([(0,f.padding)("-",e.length),e,(0,f.padding)("-",e.length),"",...!0===this.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],`${this.opts.description.replace(/\n+/g,"\n\n")}`],_.WrapComments);function i(e,i){(0,n.isEmpty)(i)||t.push(...(0,b.wrap)(["",(1===i.length?e:(0,m.pluralize)(e))+": "+(0,u.orList)(i.map(e=>(0,c.stringify)(e)))],_.WrapComments))}i("alias",this.opts.aliases),i("environment alias",this.altKeys);for(const[e,i]of(0,h.entries)(this.addToJsonDocs())){const r=Array.isArray(i)?(0,u.orList)(i.map(e=>(0,c.stringify)(e))):(0,c.stringify)(i);t.push(...(0,b.wrap)(["",e+": "+r],_.WrapComments))}return t}toEnvLine(e){return this.key+"="+((0,d.map)(e,e=>this.toEnv(e))??this.envValueOrDefault)}toTomlLine({lines:e,value:t}={}){return(0,T.wrapTomlToLines)({lines:e??[],key:this.name,value:(0,p.tot)(t??this.fileValue)})}toTomlLines(){const e=this.toCommentedLines();return(0,T.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Example value:"],key:this.name,value:(0,p.tot)(this.exampleValue)}),(0,T.wrapTomlToLines)({lines:e,wrap:_.WrapComments,prepend:["Default value:"],key:this.name,value:(0,p.tot)(this.defaultValue)}),this.toTomlLine({lines:e,value:this.fileValue}),e}}t.Setting=E},81075(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingCategoryDescriptions=t.SystemCategories=t.LibraryCategories=t.SettingCategories=void 0;const r=i(50989);t.SettingCategories=(0,r.strEnum)("Paths","Desktops","Filesystem","Cache","Logging","Networking","Processes","Security","Tools","Update","Hardware","Performance","Aggregation","Auth","Color","Db","Filters","Health","Organization","Parsing","Previews","Privacy","Reporting","Sidecars","Subscription","Sync","Tagging","Video","Volumes","Web"),t.LibraryCategories=Object.freeze([t.SettingCategories.Aggregation,t.SettingCategories.Auth,t.SettingCategories.Color,t.SettingCategories.Db,t.SettingCategories.Filters,t.SettingCategories.Health,t.SettingCategories.Organization,t.SettingCategories.Parsing,t.SettingCategories.Previews,t.SettingCategories.Privacy,t.SettingCategories.Reporting,t.SettingCategories.Sidecars,t.SettingCategories.Subscription,t.SettingCategories.Sync,t.SettingCategories.Tagging,t.SettingCategories.Video,t.SettingCategories.Volumes,t.SettingCategories.Web].sort()),t.SystemCategories=Object.freeze(t.SettingCategories.values.filter(e=>!t.LibraryCategories.includes(e)).sort()),t.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.",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 user authorization and password encryption for asset modification operations.",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, release channels, 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."})},28874(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ciSettings=t.persistedLibrarySettings=t.persistedSystemSettings=t.persistedSettings=t.allSettings=t.SuggestedDirsEnvKey=t.Settings=t.DefaultMaxEmbeddedBuffer=void 0,t.getSettingByNameOrKey=function(e){return V().get((0,a.toS)(e).toLowerCase())},t.unsetAllTestSettings=function(){for(const e of(0,t.allSettings)())e.unsetTestValue()};const r=i(19851),s=i(76790),n=i(68708),a=i(54993),o=i(9092),l=i(40583),u=i(39056),c=i(47688),d=i(8400),h=i(24325),f=i(83496),m=i(23299),p=i(57549),g=i(13797),y=i(82782),v=i(26272),b=i(2171),w=i(14112),S=i(65573),P=i(57414),M=i(29985),T=i(63972),_=i(13759),E=i(22834),k=i(23135),D=i(48032),I=i(9868),C=i(81075),A=i(28538),x=i(2319),F=i(10697),O=i(70905),R=i(99989),L=i(56507),N=i(2329),j=i(20029),B=i(24660);t.DefaultMaxEmbeddedBuffer=25e4,t.Settings={...M.PathSettings,...m.DesktopsSettings,...p.FilesystemSettings,...d.CacheSettings,...b.LoggingSettings,...w.NetworkingSettings,...k.ProcessesSettings,...I.SecuritySettings,...R.ToolsSettings,...L.UpdateSettings,...y.HardwareSettings,...T.PerformanceSettings,...c.AuthSettings,...h.ColorSettings,...f.DbSettings,...u.AggregationSettings,...g.FiltersSettings,...v.HealthSettings,...S.OrganizationSettings,...P.ParsingSettings,..._.PreviewsSettings,...E.PrivacySettings,...D.ReportingSettings,...A.SidecarsSettings,...x.SubscriptionSettings,...F.SyncSettings,...O.TaggingSettings,...N.VideoSettings,...j.VolumesSettings,...B.WebSettings};for(const[e,i]of(0,n.entries)(t.Settings))i._setName(e);function z(e){return["system"===e.categoryType?0:1,C.SettingCategories.indexOf(e.category)??C.SettingCategories.length+1,e.advanced,e.name]}t.SuggestedDirsEnvKey="SUGGESTED_DIRS",t.allSettings=(0,r.lazy)(()=>(0,s.sortBy)((0,n.values)(t.Settings),z)),t.persistedSettings=(0,r.lazy)(()=>(0,t.allSettings)().filter(e=>!e.transient)),t.persistedSystemSettings=(0,r.lazy)(()=>(0,t.persistedSettings)().filter(e=>C.SystemCategories.includes(e.category))),t.persistedLibrarySettings=(0,r.lazy)(()=>(0,t.persistedSettings)().filter(e=>C.LibraryCategories.includes(e.category)));const V=(0,r.lazy)(()=>{const e=new o.CaseInsensitiveMap;for(const i of(0,t.persistedSettings)()){for(const t of i.names)e.set(t,i);for(const t of i.keys)e.set(t,i)}return e});t.ciSettings=(0,r.lazy)(()=>new l.CaseInsensitiveValued(t.Settings,(e,t)=>[...t.names,...t.keys]))},41692(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setSettingsDefaults=void 0;const r=i(19851),s=i(7282),n=i(23560),a=i(3790),o=i(49776),l=i(32774),u=i(55086),c=i(46296),d=i(55939),h=i(77740),f=i(83278),m=i(92234),p=i(66184),g=i(57902),y=i(45969),v=i(43334),b=i(60865),w=i(30933),S=i(15674),P=i(28874);t.setSettingsDefaults=(0,r.lazy)(()=>{const e=(0,h.getDevEnvFlag)("PS_SETTINGS_IO_TEST");P.Settings.logDir.opts.defaultValue=c.defaultLogDir_,P.Settings.logServerLevel.opts.defaultValue=()=>P.Settings.logLevel.valueOrDefault,P.Settings.logContextLimit.opts.defaultValue=()=>(0,p.isDefaultLogLevelAtLeast)("debug")?64:32,P.Settings.syncPort.opts.defaultValue=()=>P.Settings.httpPort.valueOrDefault+100,P.Settings.syncEventsPort.opts.defaultValue=()=>P.Settings.syncPort.valueOrDefault+1,e||(P.Settings.cacheDir.opts.defaultValue=o.defaultCacheDir,P.Settings.libraryDir.opts.defaultValue=u.defaultLibraryDir,P.Settings.originalsDir.opts.defaultValue=u.defaultOriginalsDir,P.Settings.libraryDir.opts.exampleValue=()=>(0,s.isProd)()&&(0,y.isDocker)()?l.DefaultDockerLibraryDir:(0,d.defaultPicturesDir)(),P.Settings.toolPaths.opts.exampleValue=m.defaultPaths,P.Settings.emitTimingsOnExit.opts.defaultValue=()=>(0,n.isWorkerService)()),P.Settings.scanPaths.opts.exampleValue=()=>[(0,d.defaultPicturesDir)()],P.Settings.taskListCap.opts.defaultValue=()=>e?1:Math.max(128,Math.round(4*(0,w.cpuCount)())),P.Settings.powerShellProcs.opts.defaultValue=()=>Math.max(2,Math.round((0,S.maxCpus)()/4)),P.Settings.syncMaxTimeoutsBeforeRestart.opts.defaultValue=()=>e?1:Math.max(4,2*(0,S.maxCpus)()),P.Settings.useFsWatch.watch(f.useFsWatch),P.Settings.updateChannel.opts.defaultValue=b.channel,(0,v.isElectron)()&&(P.Settings.autoUpdateCheck.opts.defaultValue=!0),(0,g.setDefaultElapsedErrorLogMs)(P.Settings.statTimeoutMs.valueOrDefault),P.Settings.imageHashCrossFormatThresholdPct.opts.defaultValue=()=>P.Settings.imageHashRelaxedThresholdPct.valueOrDefault,P.Settings.imageHashRotationThresholdPct.opts.defaultValue=()=>P.Settings.imageHashRelaxedThresholdPct.valueOrDefault,(0,a.addSensitiveSettings)()})},2858(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionForSettings=t.libraryHasSettings=t.readSettings=void 0,t.librarySettingsFile=J,t.readSystemSettings=Y,t.envOrSavedLibraryDir=async function(){return z.Settings.libraryDir.valueOrDefault??Z()},t.savedLibraryDir=Z,t.systemSettingsVersion=Q,t.librarySettingsVersion=ee,t.maybeUpgradeSystemSettings=async function(){z.Settings.autoUpgradeSettings.valueOrDefault?(0,t.versionForSettings)()!==await Q()&&await se():K().info("Skipping system settings upgrade: "+z.Settings.autoUpgradeSettings.toEnvLine())},t.maybeUpgradeLibrarySettings=async function(){(0,t.libraryHasSettings)()&&(0,t.versionForSettings)()!==await ee()&&(z.Settings.autoUpgradeSettings.valueOrDefault?await ae():K().info("Skipping library settings upgrade: "+z.Settings.autoUpgradeSettings.toEnvLine()))},t._libraryHasSettings=ie,t.writeSystemSettings_=se,t.writeAllSettings_=function(e){return re(F.PosixFile.for(e),(0,z.persistedSettings)())},t.readLibrarySettings=ne,t.writeLibrarySettings_=ae,t._readSettings=oe,t.importFileSettings_=le,t.maybeResetLibraryDir=ce,t.clearLibraryDirSetting=async function(){await Y(),z.Settings.libraryDir.unsetTestValue(),z.Settings.libraryDir.unsetFileValue(),z.Settings.libraryDir.deleteFromEnv(),z.Settings.libraryDir.refreshEnvValue({broadcastChange:!0}),await se()},t.clearSettings=de,t.nukeSettings=async function(){if(!(0,S.isTest)())throw new Error("nukeSettings() is only for tests");const e=(0,_.envConfigDir)();return K().info("nukeSettings(): unlinking system settings.toml: "+(0,U.systemSettingsFile)()),await(F.PosixFile.forMaybe((0,U.systemSettingsFile)())?.unlink("trace")),K().info("nukeSettings(): unlinking default system settings.toml: "+(0,U.systemSettingsFile)()),(0,k.getDevEnvFlag)("PS_KEEP_ENV")||await(0,O.unlink)((0,U.systemSettingsFile)(),"trace"),(0,I.setEnv)("PS_CONFIG_DIR",e),(0,k.getDevEnvFlag)("PS_KEEP_ENV")||await(0,O.unlink)(J(),"trace"),(0,I.deleteEnv)("PS_CONFIG_DIR"),T.configDir.unset(),de(),await(0,A.ee)().emit("clearCache"),t.readSettings.unset(),void V.setSettingsDefaults.refresh()},t.writeEnv=async function(e,t){const i=[];i.push(...he("",`Welcome to PhotoStructure! These are the settings for version ${L.versionMajorMinor}.`,"","Please see https://photostructure.com/environment-variables for more information about using environment variables with PhotoStructure.","",'As of version 2.1, ".env" files (like this one) can be imported by PhotoStructure. For more details see https://photostructure.com/go/psenv')),i.push("",""),i.push(...he("","The following settings categories are stored in the system settings.toml:","",...(0,s.sort)([...B.SystemCategories]).map(e=>"* System."+e),"","The following settings categories are stored in the library settings.toml:","",...(0,s.sort)([...B.LibraryCategories]).map(e=>"* Library."+e),"","Please visit https://forum.photostructure.com if you find anything that may be a bug or have any questions, ideas, or feedback. We'd love to hear from you!")),i.push("",""),i.push(...he("-----------","PS_ENV_FILE","-----------","","PhotoStructure will attempt to read an .env-formatted filename specified by this environment variable. This must be a full pathname.","","Any value set by this file will override values in settings.toml files.","","For more details see https://photostructure.com/go/psenv")),i.push("",""),i.push(...he("-------------","PS_CONFIG_DIR","-------------","","If the environment variable PS_CONFIG_DIR is set, PhotoStructure will use that value as your system configuration directory. This can't be overridden in the system settings.toml, as it's used to _find_ the system settings.toml!","","PhotoStructure's system configuration directory is different for every operating system:","","- Windows defaults to %APPDATA%PhotoStructure (%APPDATA% is normally set to %HOME%/AppData/Roaming)","","- macOS defaults to ~/Library/Application Support/PhotoStructure","","- Linux defaults to ${XDG_CONFIG_DIR:-$HOME/.config}/PhotoStructure")),i.push("","");let n="";for(const e of t){const t=`${(0,P.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;if(t!==n){n=t;const r=B.SettingCategoryDescriptions[e.category],s="library"===e.categoryType?"(stored per-library)":"(system-wide)",a=`${e.category} settings ${s}`;i.push("",(0,g.padding)("#",78),"#",`# ${a}`,"#",...he(r),"#","")}const s=e.key+(e.transient?"":" or "+e.name),a={...e.addToJsonDocs()};(0,r.mapNotEmpty)(e.altKeys,e=>a.aliases=(0,h.orList)(e));const o=(0,p.entries)(a).map(([e,t])=>`${(0,P.capitalize)((0,M.camel2snake)(e)).replace(/_+/g," ")}: ${(0,$.valueToS)(t)}`);(0,r.isNotEmpty)(o)&&o.push(""),i.push(...he((0,g.padding)("-",s.length),s,(0,g.padding)("-",s.length),"",...!0===e.opts.deprecated?["NOTE: this setting has been deprecated and will be removed in a future version of PhotoStructure.",""]:[],e.opts.description.replace(/\n+/g,"\n\n"),"",...e.transient?["This setting is transient and only set via environment variables.\n"]:[],...o,`${e.key}=${(0,f.stringify)((0,v.toS)(e.opts.toEnv(e.fileValue??e.defaultValue)))}`)),i.push("","")}const a=(0,y.ensureSuffix)(i.map(e=>(0,y.trimRight)(e)).join("\n"),"\n");await e.writeFile_(a)};const r=i(40958),s=i(76790),n=i(22573),a=i(38639),o=i(42659),l=i(45599),u=i(41400),c=i(50357),d=i(96249),h=i(57924),f=i(98553),m=i(55835),p=i(68708),g=i(39926),y=i(51926),v=i(54993),b=i(19851),w=i(50213),S=i(7282),P=i(81168),M=i(83556),T=i(46292),_=i(84373),E=i(87290),k=i(77740),D=i(59958),I=i(96706),C=i(19485),A=i(34102),x=i(83278),F=i(95696),O=i(84258),R=i(89206),L=i(60865),N=i(4175),j=i(83179),B=i(81075),z=i(28874),V=i(41692),H=i(84438),U=i(32707),W=i(6707),q=i(98778),$=i(55018),G=i(10357),K=(0,l.defer)(()=>(0,w.mkLogger)("settings.SettingsIO"));function J(e){return(0,E.libraryDataDirPosixFile)(e)?.join(H.SettingsToml)}async function Y(e=(0,U.systemSettingsFile)()){if((0,V.setSettingsDefaults)(),null!=e)return oe(x.BaseFile.for(e));K().warn("readSystemSettings(): systemSettingsFile() returned null: no-op")}async function Z(){try{const e=(0,U.systemSettingsFile)(),t=await(0,W.readTomlFile_)(e);return(0,n.toNotBlank)(t?.[z.Settings.libraryDir.name])}catch(e){return void K().warn("savedLibraryDir(): failed to read system settings",{error:e})}}async function X(e){try{const t=await(0,W.readTomlFile_)(e);return t?.version}catch(t){return void K().warn("readTomlVersion(): failed to read settings file",{file:e,error:t})}}function Q(){return X((0,U.systemSettingsFile)())}function ee(e){return X(J(e))}function te(){t.readSettings.unset(),t.libraryHasSettings.refresh()}function ie(e){const t=J(e);return K().tap({msg:"_libraryHasSettings",result:t?.clear().existsSync()??!1,meta:{libraryDir_arg:e,libraryDir_settings:z.Settings.libraryDir.valueOrDefault,librarySettingsFile:t?.nativePath}})}async function re(e,i){if(null==e)return void K().warn("writeToml(): null file, failed to write settings",{file:e,settings:i});const r=await e.clear().isNonEmpty(),s=r?e.wip():e;if(await async function(e,i){const r=[(0,g.padding)("#",80)];r.push(...he("","Howdy!","",`These are ${i[0].categoryType} settings for PhotoStructure.`,""," - Please shut down PhotoStructure before editing this file.",""," - PhotoStructure has TWO settings files! See"," https://photostructure.com/getting-started/advanced-settings/#omg-why-2"," to see why.","",' - NOTE: lines starting with a "#" are commented out.',"",' - To override a setting, uncomment the line by removing the "# " from'," the beginning of the line, and change the value.","",' - All duration settings end with "Duration" or "Ms" (for milliseconds).'," See https://photostructure.com/getting-started/advanced-settings#duration"," for details.",""," - See https://photostructure.com/settings/ for more documentation.","Thanks for using PhotoStructure! Visit https://forum.photostructure.com/ if you find any bugs or have any questions, ideas, or feedback. We'd love to hear from you.","","This is the version of PhotoStructure that wrote this file--please don't edit the following line.")),r.push(...(0,q.stringifyToml)({version:(0,t.versionForSettings)()})),r.push("","");let s="";for(const e of i){const t=`${(0,P.capitalize)(e.categoryType)}.${e.category.toLowerCase()}`;if(t!==s){s=t;const i=B.SettingCategoryDescriptions[e.category],n="library"===e.categoryType?"(stored per-library)":"(system-wide)",a=`${e.category} settings ${n}`;r.push("",(0,g.padding)("#",78),"#",`# ${a}`,"#",...he(i),"#","")}r.push(...e.toTomlLines()),r.push("","")}await e.writeText_("\n"+r.map(y.trimRight).join("\n")+"\n\n"),(0,A.ee)().emitThrottled("settingsChanged")}(s,i),K().info("writeToml(): wrote settings",{dest:s,file:e,nonDefaults:(0,j.settingsToObj)(i),wip:r}),r){const t=await(0,W.readTomlFile_)(s),i=await(0,W.readTomlFile_)(e);(0,c.eql)(t,i)?(K().info("Equivalent contents",{dest:s,file:e,a:t,b:i}),await s.unlink()):(K().info("Archiving prior, different contents",{dest:s,file:e}),await e.renameYMDHMS_({subdir:"archive"}),await s.unwip_())}}async function se(e=(0,U.systemSettingsFile)()){const t=F.PosixFile.forMaybe(e);return null!=t&&await re(t,(0,z.persistedSystemSettings)()),t}function ne(e){return oe(J(e))}async function ae(e){await(0,E.setupLibraryDataDir_)(e);const i=J(e);return K().info("writeLibrarySettings()",{file:i}),null!=i&&(await re(i,(0,z.persistedLibrarySettings)()),t.libraryHasSettings.refresh()),i}async function oe(e){if(null==e)return K().info("_readSettings(null): no-op"),[];const t=K().child(".importFileSettings("+e.nativePath+")");try{const i=await le(e);return(0,r.isNotEmpty)(i.warnings)&&t.info("Problems during import",i.warnings),i.settings}catch(i){return t.warn("Cannot read",{file:e.nativePath,error:i}),[]}}async function le(e){const t=K().child(".importFileSettings_("+e.nativePath+")"),i=await e.stat();if(null==i)return{settings:[],warnings:["Cannot read"]};if(0===i.size)return{settings:[],warnings:["Cannot read empty file"]};const s=await(0,W.readTomlFile_)(e);if(null==s)return{settings:[],warnings:["No settings found"]};const n=[],a=(0,r.compact)((0,p.entries)(s).map(([e,t])=>{if("version"===e)return;const i=(0,z.getSettingByNameOrKey)(e);if(null==i)n.push(`Failed to import "${e}"${(0,m.mapOr)((0,z.ciSettings)().lookupNearest(e),e=>`: did you mean "${e.key}"?`,"")}`);else{const e=i.whyInvalidValue(t);if(null==e)return i.fileValue=t,i;n.push(e)}}));return t.info("loaded",{settings:(0,j.settingsToObj)(a),warnings:(0,r.toNotEmpty)(n)}),await(0,N.handleDeprecatedSettings)(),(0,N.handleMetaSettings)(a),n.push(...(0,N.settingsValueWarnings)(a)),{settings:a,warnings:n}}t.readSettings=(0,b.lazy)(async()=>{await C.readAndMergePsEnv.refresh();for(const e of(0,z.allSettings)())e.refreshEnvValue();await Y(),await ce(),(0,t.libraryHasSettings)()&&await ne()},o.minuteMs),t.libraryHasSettings=(0,b.lazy)(()=>ie(),o.minuteMs),t.libraryHasSettings.unset=()=>t.libraryHasSettings.refresh(),(0,u.later)(()=>{(0,A.ee)().on("clearCache",te),(0,A.ee)().on("settingsChanged",te),z.Settings.libraryDir.watchLater(te)}),t.versionForSettings=(0,b.lazy)(()=>(0,L.baseVersion)());const ue=(0,l.defer)(()=>new Set([z.Settings.noNetwork,z.Settings.httpPort,z.Settings.syncPort,z.Settings.license,z.Settings.logStdout,z.Settings.logLevel].map(e=>e.key)));async function ce(){(0,a.isTrue)(process.env[D.PS_RESET_LIBRARY_DIR])&&((0,R.isChildProcess)()||(K().info("PS_RESET_LIBRARY_DIR: clearing libraryDir"),delete process.env[D.PS_RESET_LIBRARY_DIR],z.Settings.libraryDir.deleteFromEnv(),z.Settings.libraryDir.refreshEnvValue({broadcastChange:!0}),z.Settings.libraryDir.unsetFileValue(),await se(),K().info("PS_RESET_LIBRARY_DIR: done",{libraryDirValue:z.Settings.libraryDir.value})))}function de(){for(const e of(0,p.values)(z.Settings)){const t=ue().has(e.key);e.unset({preserveEnv:t,preserveTestValue:t})}(0,A.ee)().emitSync("settingsChanged")}function he(...e){return(0,d.flatten)(e.map(e=>(0,P.wrap)(e,G.WrapComments)))}},76989(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNotProd=t.isProd=void 0;const r=i(19851),s=i(7282);t.isProd=(0,r.lazy)(s.isProd),t.isNotProd=()=>!(0,t.isProd)()},84438(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingsToml=void 0,t.SettingsToml="settings.toml"},28538(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SidecarsSettings=void 0;const r=i(50274),s=i(38483),n=i(81075),a=i(58305),o=i(57571);t.SidecarsSettings={matchSidecarsCaseInsensitively:new s.BooleanSetting({category:n.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match file basenames (with or without the file extension), regardless of case (for example: "IMAGE.XMP" will be a sidecar for "image.jpg").\nIf set to false, sidecars must match case (so only "image.jpg.xmp" and "image.xmp" will match for "image.jpg").',defaultValue:!0}),matchSidecarsFuzzily:new s.BooleanSetting({category:n.SettingCategories.Sidecars,description:'If set to true, PhotoStructure will look for sidecar files that match the basename of the asset, plus some common suffixes (like "-edit", "-edited", or variant copies, like "-2").\nThis setting only impacts .XMP, .MIE, and .EXIF sidecars.\nNote that PhotoStructure always matches .JSON files fuzzily, as that is required to handle Google Takeouts properly.',defaultValue:!1}),defaultSidecarType:new o.StringEnumSetting({category:n.SettingCategories.Sidecars,description:'What type of sidecar file do you want to generate for non-destructive edits?\n- "XMP" is a popular and well-adopted format.\n-"MIE" is defined at https://exiftool.org/TagNames/MIE.html .\n- "EXIF" and "EXV" should only be used if required, as they have substantial limitations.\nCase is preserved.',strEnum:r.SidecarExts,defaultValue:r.SidecarExts.xmp}),writeMetadataToSidecarsIfImage:new s.BooleanSetting({category:n.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 a.StringArraySetting({category:n.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 a.StringArraySetting({category:n.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).\nNote that these are case-sensitive.',defaultValue:()=>["album.xmp","metadata.xmp"]}),writeMetadataToSidecarsIfVideo:new s.BooleanSetting({category:n.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 s.BooleanSetting({category:n.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})}},58305(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringArraySetting=void 0,t._join=d,t.splitStringArray=h;const r=i(76760),s=i(40958),n=i(22573),a=i(98553),o=i(55835),l=i(59455),u=i(19851),c=i(83179);function d(e){return null==e?void 0:(0,a.stringify)(e)}function h(e){return(0,o.map)(function(e){const t=(0,n.notBlankToS)(e);if(null!=t){if(t.startsWith("[")&&t.endsWith("]"))try{return(0,s.compact)((0,l.toA)(JSON.parse(t)).map(n.notBlankToS))}catch{}for(const e of["¦",r.delimiter])if(t.includes(e))return(0,s.compactBlankish)(t.split(e));return[t]}}(e),s.compactBlankish)}class f extends c.Setting{constructor(e){super({defaultValue:[],fromEnv:h,toEnv:d,...e}),this.watchLater(()=>{this.synonymMap.clear()})}toValidValue(e){return(0,n.notBlankToS)(e)}toValidValues(e){return null==e?void 0:(0,s.uniq)(e.map(e=>this.toValidValue(e)))}push(...e){(0,s.isEmpty)(e)||(this.value=this.toValidValues((0,s.uniq)([...(0,l.toA)(this.value),...(0,l.toA)(e)])))}has(e){return(0,l.toA)(this.values).includes(e)}get values(){return(0,l.optToA)(this.value)??this.defaultValue}set values(e){this.userValue=this.toValidValues(e)}set testValues(e){this.testValue=null==e?void 0:e}isEmpty(){return(0,s.isEmpty)(this.values)}isNotEmpty(){return(0,s.isNotEmpty)(this.values)}toNotEmpty(){return(0,s.toNotEmpty)((0,s.compactBlanks)(this.values))}synonymMap=(0,u.lazy)(()=>{const e=new Map;for(const t of this.values){const i=t.split("|");for(const t of i)e.set(t,i)}return e})}t.StringArraySetting=f},57571(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumSetting=void 0;const r=i(38639),s=i(83179);function n(e,t,i){if(null!=e)return t.getCI(e)??i?.get(e.toLowerCase())}class a extends s.Setting{strEnum;_valueAliases;constructor(e){const t=null!=e.valueAliases?new Map(Object.entries(e.valueAliases).map(([e,t])=>[e.toLowerCase(),t])):void 0;super({...e,toEnv:i=>n(i,e.strEnum,t),fromEnv:i=>function(e,t,i){const s=t.values.find(r.isDisabled);return null!=s&&(0,r.isDisabled)(e)?s:n(e,t,i)}(i,e.strEnum,t)}),this.strEnum=e.strEnum,this._valueAliases=e.valueAliases;const i=this.defaultValue;if(!this.strEnum.has(i))throw new Error(`${this.strEnum.values}, doesn't include defaultValue, ${e.defaultValue}`)}isDisabled(){return(0,r.isDisabled)(this.valueOrDefault)}isEnabled(){return!this.isDisabled()}addToJsonDocs(){return{"valid values":this.strEnum.values}}toCommentedLines(){const e=super.toCommentedLines();if(null!=this._valueAliases){e.push("#","# deprecated aliases:");for(const[t,i]of Object.entries(this._valueAliases))e.push(`# - "${t}" -> "${i}"`)}return e}}t.StringEnumSetting=a},72564(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringEnumsSetting=void 0;const r=i(40958),s=i(98553),n=i(55835),a=i(58305);class o extends a.StringArraySetting{strEnum;constructor(e){super({toEnv:e=>(0,n.map)(e,e=>(0,s.stringify)((0,r.uniq)(e))),fromEnv:t=>{return i=t,s=e.strEnum,(0,r.compact)((0,a.splitStringArray)(i)?.map(e=>s.getCI(e)));var i,s},defaultValue:e.defaultValue??e.strEnum.values,...e}),this.strEnum=e.strEnum}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}}}t.StringEnumsSetting=o},96948(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringMapSetting=void 0;const r=i(22573),s=i(98553),n=i(68708),a=i(83179),o=i(98778),l=i(10357);function u(e){if((0,r.notBlank)(e))try{return function(e){if(null!=e&&(0,n.isObject)(e)&&!Array.isArray(e)){for(const[t,i]of(0,n.entries)(e)){if("string"!=typeof t)return;if("string"!=typeof i)return}return e}}(JSON.parse(e))}catch{return}}function c(e){if(null!=e)return(0,s.stringify)(e)}function d(e){const t=(0,n.entries)(e).map(([e,t])=>`${JSON.stringify(e)} = ${JSON.stringify(t)}`);return 0===t.length?"{}":`{ ${t.join(", ")} }`}class h extends a.Setting{constructor(e){super({defaultValue:{},fromEnv:u,toEnv:c,...e})}toTomlLine({lines:e=[],value:t}={}){const i=t??this.fileValue;return null==i||e.push(`${this.name} = ${d(i)}`),e}toTomlLines(){const e=this.toCommentedLines();return(0,o.wrapTomlToLines)({lines:e,wrap:l.WrapComments,prepend:["Example value:"],key:this.name,value:void 0}),null!=this.exampleValue&&e.push(`# ${this.name} = ${d(this.exampleValue)}`),(0,o.wrapTomlToLines)({lines:e,wrap:l.WrapComments,prepend:["Default value:"],key:this.name,value:void 0}),e.push(`# ${this.name} = ${d(this.defaultValue)}`),this.toTomlLine({lines:e,value:this.fileValue}),e}isEmpty(){const e=this.valueOrDefault;return null==e||0===Object.keys(e).length}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(0,n.entries)(this.valueOrDefault)}}t.StringMapSetting=h},80372(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringSetting=void 0;const r=i(22573),s=i(81168),n=i(83179);class a extends n.Setting{constructor(e){super({toEnv:o,fromEnv:o,...e})}hasValue(){return(0,r.notBlank)(this.value)}}function o(e){return null==e?void 0:(0,s.trimQuotes)(e)}t.StringSetting=a},2319(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SubscriptionSettings=void 0;const r=i(38483),s=i(57039),n=i(87652),a=i(81075);t.SubscriptionSettings={subscriptionTimeoutMs:new s.DurationSetting({category:a.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 r.BooleanSetting({category:a.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 n.OptionalStringSetting({category:a.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.\nThe example value is a valid coupon code: thanks for reading!)\nNote that you can apply a coupon after your free trial starts by visiting https://account.photostructure.com .",exampleValue:()=>"RTFM15"}),autoRefreshLicense:new r.BooleanSetting({category:a.SettingCategories.Subscription,description:'PhotoStructure uses cryptographically signed licenses to locally store your current plan subscription status. These licenses are only valid for the current subscription period, and must be refreshed when your subscription renews or converts from a free trial to a paid subscription. To minimize the hassle of license renewals, PhotoStructure can automatically renew expired licenses in the background.\nIf the current license has expired and this value is true, PhotoStructure will make one secure POST request to https://account.photostructure.com/ that contains several lossy one-way hashes of current system metadata. We hash all identifying metadata to only 15 characters to alleviate any privacy concerns. If your plan subscription is active, a new license will be added to your library.\nSet this to false and set the "reportErrors" setting to false if you don\'t want PhotoStructure "phoning home" for any reason.\nNote that if this is disabled, license renewals will require manual intervention: click "Upgrade" from the main menu, pick your plan, authenticate, and the license will automatically refresh.',defaultValue:!0}),license:new n.OptionalStringSetting({category:a.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.'})}},10697(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncSettings=void 0;const r=i(51168),s=i(22573),n=i(42659),a=i(24540),o=i(38483),l=i(75164),u=i(90967),c=i(57039),d=i(74589),h=i(87652),f=i(81075),m=i(80372);t.SyncSettings={expedite:new o.BooleanSetting({category:f.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 l.BoundedIntegerSetting({category:f.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.\nThe 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 m.StringSetting({category:f.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 c.DurationSetting({category:f.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 d.IntegerSetting({category:f.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}),quickSyncMode:new o.BooleanSetting({category:f.SettingCategories.Sync,description:"Should PhotoStructure disable a bunch of features to make imports faster? Note that this disables image validation, video transcoding, image hashing (required for good deduplication), metadata inference, and more efficient preview encoding. It is true by default on Raspberry Pis and false everywhere else.",defaultValue:()=>(0,a.isRaspberryPi)()}),taskTimeoutMs:new c.DurationSetting({category:f.SettingCategories.Sync,aliases:["taskTimeoutMillis"],description:"What's the longest time it can validly take to fetch a file SHA, generate image previews for an asset, compute an image hash, or extract tags for a file?\nNote that this does not impact video transcoding timeouts.\nOn 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.\nSet this to 0 to disable task timeouts.",defaultValue:()=>"2m"}),taskMaxDurationMs:new c.DurationSetting({category:f.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.\nSet to 0 to disable.",defaultValue:()=>"10m"}),stallWarningFloorMs:new c.DurationSetting({category:f.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 c.DurationSetting({category:f.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 d.IntegerSetting({category:f.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.\nThe sync process will finish in-flight tasks before restarting.\nSet to 0 to disable timeout-count-based restart.",defaultValue:1}),scanLibraryFirst:new o.BooleanSetting({aliases:["syncLibraryFirst"],category:f.SettingCategories.Sync,description:"Should PhotoStructure scan your library before all other paths are synchronized?\nThis defaults to true if you are using automatic organization, to make sure existing files in your library are in sync with your library database. This prevents additional copies of the same SHA being copied into your library directory if you have automatic organization enabled.",defaultValue:!0}),scanLibraryLast:new o.BooleanSetting({aliases:["syncLibraryLast"],category:f.SettingCategories.Sync,description:"Should PhotoStructure scan your library after all other paths are synchronized?",defaultValue:!1}),progressRetentionDays:new d.IntegerSetting({category:f.SettingCategories.Sync,description:"How many days of sync progress should we keep around in the database before it's removed?",defaultValue:180}),progressStaleDays:new d.IntegerSetting({category:f.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 o.BooleanSetting({category:f.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have to manually resume processing via the system tray or nav menu.",defaultValue:!1}),syncCron:new u.CronSetting({category:f.SettingCategories.Sync,description:"This is a crontab entry that defines when sync will start work.\nIf the value you provide is not a valid crontab entry, the default value will be used instead (which is to run at 2AM, nightly).\nSee 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 h.OptionalStringSetting({category:f.SettingCategories.Sync,whyInvalid:e=>(0,s.blank)(e)?"(blank)":r.Info.isValidIANAZone(e)?void 0:"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 o.BooleanSetting({category:f.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 o.BooleanSetting({category:f.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 o.BooleanSetting({category:f.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 o.BooleanSetting({category:f.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 o.BooleanSetting({category:f.SettingCategories.Sync,description:"When set, previews and transcoded videos will always be rebuilt.",defaultValue:!1,transient:!0,propagateToChildren:!1}),skipAssetRepair:new o.BooleanSetting({category:f.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 o.BooleanSetting({category:f.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 o.BooleanSetting({aliases:["noModelUpdates"],category:f.SettingCategories.Sync,description:"When set, skip any pending library database updates (only used for tests).",defaultValue:!1,transient:!0,propagateToChildren:!1}),exitWhenDone:new o.BooleanSetting({category:f.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 d.IntegerSetting({category:f.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 o.BooleanSetting({category:f.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 l.BoundedIntegerSetting({category:f.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. \nMuch larger values will incur cache misses and increase sync RAM consumption. Much smaller values may cause backpressure that slows sync throughput.\nNote that until the last batch of work is scheduled, sync ETAs will be inaccurate.\nThis defaults to the bigger value of 128 and 4 x max file import concurrency.',defaultValue:1,min:1,max:32768}),fileSizeEpsilon:new d.IntegerSetting({category:f.SettingCategories.Sync,description:"How many bytes can a file's size be different from prior synchronization runs and still be considered \"untouched\"?\nSet this to 0 to require exactly the same filesize.\nSet 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 d.IntegerSetting({category:f.SettingCategories.Sync,description:'How many milliseconds can a file\'s "mtimeMs" be different from prior synchronization runs and still be considered "untouched"?\nA 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.\nSet 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:n.secondMs}),findUriEquivalents:new o.BooleanSetting({category:f.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.\n\nmacOS 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.\n\nWarning: Enabling this slows down sync because PhotoStructure must check multiple equivalent paths for every file.\n\nLeave this disabled if you only use one operating system or only have ASCII filenames.",defaultValue:()=>!1})}},32707(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.systemSettingsFile=function(){const e=(0,s.configDir)();return null==e?void 0:(0,r.join)(e,n.SettingsToml)};const r=i(76760),s=i(46292),n=i(84438)},80496(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagInferenceSettingValues=void 0;const r=i(50989);t.TagInferenceSettingValues=(0,r.strEnum)("never","always","auto")},70905(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RootTagAliasConfigs=t.TaggingSettings=void 0;const r=i(40958),s=i(45969),n=i(70379),a=i(68268),o=i(61208),l=i(99023),u=i(38483),c=i(9945),d=i(87652),h=i(81075),f=i(76989),m=i(58305),p=i(57571),g=i(96948),y=i(80372);t.TaggingSettings={recountAllTags:new u.BooleanSetting({category:h.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 u.BooleanSetting({category:h.SettingCategories.Tagging,description:"Should assets be tagged with cameras' make and model?",defaultValue:!0}),tagLens:new u.BooleanSetting({category:h.SettingCategories.Tagging,description:"Should assets be tagged with lens' make and model?",defaultValue:!0}),tagFullLensModel:new u.BooleanSetting({category:h.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 p.StringEnumSetting({category:h.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)?\nSetting this to "disabled" will disable date tagging.',defaultValue:n.DateTagFormats.ym,strEnum:n.DateTagFormats}),tagDateFromStat:new u.BooleanSetting({category:h.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:()=>!(0,f.isNotProd)()}),tagKeywordsFromPath:new u.BooleanSetting({category:h.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file pathnames?",defaultValue:!0}),tagKeywordsFromMetadata:new u.BooleanSetting({category:h.SettingCategories.Tagging,description:"Should assets be tagged with keywords extracted from file metadata, as well as sidecar metadata?",defaultValue:!0}),keywordTags:new m.StringArraySetting({category:h.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 p.StringEnumSetting({category:h.SettingCategories.Tagging,description:'How should PhotoStructure handle hierarchical keywords?\nIf this is set to "move", PhotoStructure will try to put hierarchical keywords into their "correct" root tag, like "Who," "Album," or "Where."\nIf this is set to "retain," PhotoStructure will always place hierarchical keywords under the "Keyword" root tag.\nIf this is set to "copy," PhotoStructure will add both the "correct" root tag _and_ the "Keyword" tag. For example, "Person|Doe|Jane" will be tagged as "Who|Doe|Jane" as well as "Keyword|Person|Doe|Jane".\nSee https://forum.photostructure.com/t/prefix-for-keywords-tag/499 for details.',defaultValue:a.KeywordReparentingStrategies.move,strEnum:a.KeywordReparentingStrategies}),rootTagAlbumsAliases:new m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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:()=>(0,r.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 m.StringArraySetting({category:h.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:()=>(0,r.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"])}),rootTagWhoAliases:new m.StringArraySetting({category:h.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:()=>(0,r.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"])}),rootTagEventAliases:new m.StringArraySetting({category:h.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:()=>(0,r.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"])}),keywordDelimiters:new d.OptionalStringSetting({category:h.SettingCategories.Tagging,description:'PhotoStructure splits apart keywords, by default, when they are delimited by a comma or semicolon. For example, "car, blue, tree" will be interpreted as having the keywords "car", "blue", and "tree".\nNote that some software doesn\'t encode lists of keywords properly, so we have to include the comma and semicolon by default to handle these cases: but this makes keywords that contain a comma be split incorrectly. If the files in your library don\'t have this encoding issue, you can replace this setting with just an empty string to disable splitting.\nSee https://forum.photostructure.com/t/incorrect-handling-of-keywords-with-comma/992 for more discussion.\nAfter changing this value, you must force-resync your library for the changes to take affect.',defaultValue:",;"}),keywordDashDashDelimiters:new y.StringSetting({category:h.SettingCategories.Tagging,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).\nWindows pathnames are converted to forward-slash for this use, so you don\'t need to include backward-slash.\nAfter changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:",; /"}),keywordPathSeparators:new y.StringSetting({category:h.SettingCategories.Tagging,description:'PhotoStructure interprets keywords as hierarchical if a path separator character is found in a keyword. This allows for tags like "Family/Einstein/Albert", "Flora|Fruit|Orange", "Objects⊃Tools⊃Hammer", or "Fauna>Oceanic>Pelican". By default, these separators are the forward-slash, vertical-bar, and greater-than characters. If you don\'t want to interpret keywords as hierarchical, change this value to an empty string (""). After changing this value, you must force-resync your entire library for the changes to take affect.',defaultValue:"/|>⊃"}),tagFileType:new u.BooleanSetting({category:h.SettingCategories.Tagging,aliases:["tagType"],description:'Should assets be tagged with their file type (like "Type/Image/JPEG")?',defaultValue:!0}),tagGeo:new u.BooleanSetting({category:h.SettingCategories.Tagging,description:"Should we add geolocation tags to assets that have latitude/longitude?",defaultValue:!0}),tagGeoCountryFlags:new u.BooleanSetting({category:h.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 c.FloatSetting({category:h.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 m.StringArraySetting({category:h.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.',defaultValue:()=>["GeolocationCountry|Country|LocationShown.CountryName|LocationCreated.CountryName","GeolocationRegion|State|LocationShown.ProvinceState|LocationCreated.ProvinceState","GeolocationSubregion|County","GeolocationCity|City|LocationShown.City|LocationCreated.City","Location|LocationShown.SubLocation|LocationCreated.SubLocation"]}),tagGeoTemplate:new m.StringArraySetting({category:h.SettingCategories.Tagging,description:'How should geo tags be rendered into a hierarchy? These will be attached to the "Where" root tag.',defaultValue:["Country","State","County","City","Location"]}),tagJsonFaces:new u.BooleanSetting({category:h.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 u.BooleanSetting({category:h.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 m.StringArraySetting({category:h.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 p.StringEnumSetting({category:h.SettingCategories.Tagging,description:'How should PhotoStructure format the "Who" tags for assets whose files are tagged with "people" strings?\n- "as-is" will tag names directly to "Who", so, "Who/Albert Einstein".\n- "family/given" will tag "Who/Einstein/Albert" (for regions that provide given names first).\n- "family/fullname" will tag "Who/Einstein/Albert Einstein".\nThe default is "as-is," because discerning given and family names aren\'t reliably inferable.\nSee https://en.wikipedia.org/wiki/Personal_name#Name_order .',defaultValue:o.NameTagFormats["as-is"],strEnum:o.NameTagFormats}),tagNamesDefaultFamily:new y.StringSetting({category:h.SettingCategories.Tagging,description:'If a name is missing a family name, if this value is not blank, it will be provided as a default. If this value is blank, the name tag will be Who/given. Note that this setting is only used if "tagNamesFormatter" is set to "family/given".',defaultValue:"-"}),tagNamesCapitalizedAsFamily:new u.BooleanSetting({category:h.SettingCategories.Tagging,description:"Assume uppercased names are family names (this is common practice in geneology).",defaultValue:!0}),tagNamesOrder:new p.StringEnumSetting({category:h.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:l.NameTagOrders,valueAliases:{western:"givenFirst",eastern:"surnameFirst"}}),tagNamesSurnamePrefixes:new m.StringArraySetting({category:h.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"]}),tagNamesSurnames:new m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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 u.BooleanSetting({category:h.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 m.StringArraySetting({category:h.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 y.StringSetting({category:h.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 y.StringSetting({category:h.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 u.BooleanSetting({category:h.SettingCategories.Tagging,description:"On non-docker hosts (which typically don't have reliable hostnames), should the root directory tag have the hostname appended?",defaultValue:()=>!!(0,f.isNotProd)()||!(0,s.isDocker)()}),tagDisplayNameFSLabels:new u.BooleanSetting({category:h.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 m.StringArraySetting({aliases:["tagAlbumJsonFilenames"],category:h.SettingCategories.Tagging,description:'PhotoStructure will look for files in the same directory with these names for album metadata. This can be JSON, XMP, MIE, or EXIF encoded, and is case-sensitive if your filesystem is case sensitive.\nSet this to an empty array ("[]") to disable this feature.',defaultValue:["metadata.json"]}),tagAlbumTitle:new m.StringArraySetting({category:h.SettingCategories.Tagging,description:'What\'s the name of the field encoding the album file?\nThe first defined field will win.\nObject hierarchies are separated with a ".".\nGoogle Takeout uses "albumData.title" for album titles.\n"Album" will pull in the XMP "Album" tag.\nThe MWG 2.0 specification added Collections tags, whose names are encoded as a "CollectionName". See https://exiftool.org/TagNames/MWG.html#Collections for details.\nNote that if you edit this setting, you need to rebuild your library to see the changes take effect.',defaultValue:["Album","albumData.title","Collections.CollectionName"]}),tagAlbumTitleHierarchies:new u.BooleanSetting({category:h.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 m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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 m.StringArraySetting({category:h.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 g.StringMapSetting({category:h.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. \n\nPattern matching:\n- Patterns starting with "/" are anchored to the beginning of the path\n- Patterns without "/" match anywhere in the path (first match wins)\n- All matching is case-insensitive\n- Matched prefix/segment is replaced; remaining path segments are preserved\n\nExamples:\n- "/Album/Wrong": "Album/Correct" - renames Album/Wrong/* to Album/Correct/*\n- "/Who/John Doe": "Who/Doe/John" - reorganizes a person\'s tag hierarchy\n- "USA": "United States" - renames any "USA" segment anywhere in the path\n- "Australia/Victoria/Saint Albans": "Australia/Victoria/St Albans" - fixes a misspelling\n\nChanges require a library rebuild to take effect.',defaultValue:{},exampleValue:()=>({"Australia/Victoria/Saint Albans":"Australia/Victoria/St Albans"})}),vacuumOrphanTags:new u.BooleanSetting({category:h.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 m.StringArraySetting({category:h.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 u.BooleanSetting({category:h.SettingCategories.Tagging,description:'PhotoStructure\'s hierarchical tags assume implicit inheritance: that is, if you tag an asset with "nature/sky", "nature" is implicitly assumed.\nIf this setting is true, PhotoStructure will omit tags that are already inferred from deeper descendant tags--that is, if an asset is tagged with "nature/sky" and "nature", and this setting is true, the "nature" tag will be omitted.',defaultValue:!0})},t.RootTagAliasConfigs=[{root:"Albums",setting:t.TaggingSettings.rootTagAlbumsAliases},{root:"Keywords",setting:t.TaggingSettings.rootTagKeywordsAliases},{root:"What",setting:t.TaggingSettings.rootTagWhatAliases},{root:"Where",setting:t.TaggingSettings.rootTagWhereAliases},{root:"Who",setting:t.TaggingSettings.rootTagWhoAliases},{root:"Event",setting:t.TaggingSettings.rootTagEventAliases}]},77503(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TemperatureScales=void 0,t.celsiusToFahrenheit=function(e){return 9*e/5+32},t.fahrenheitToCelsius=function(e){return 5/9*(e-32)};const r=i(50989);t.TemperatureScales=(0,r.strEnum)("Celsius","Fahrenheit")},6707(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readTomlFileSync=function(e){const t=(0,a.mapNotBlank)(e,d.toNativePath_);if(null!=t)try{return(0,h.isFileSync)(t)?m((0,s.readFileSync)(t)):void 0}catch(e){return void(0,l.mkLogger)("settings.Toml").warn("readTomlFileSync() failed",{nativePath:t,error:e})}},t.readTomlFile_=async function(e){return(0,a.mapNotBlank)(e,async e=>m(await(0,n.readFile)((0,d.toNativePath_)(e))))},t.writeTomlFile_=function(e,t){return(0,n.writeFile)((0,d.toNativePath_)(e),(0,c.joinLines)(...(0,f.stringifyToml)(t)),{flush:!0})};const r=i(90858),s=i(73024),n=i(51455),a=i(22573),o=i(76850),l=i(50213),u=i(81168),c=i(84542),d=i(17217),h=i(68284),f=i(98778);function m(e){return t=(0,o.debom)(e),(0,a.blank)(t)?void 0:(0,r.parse)((0,u.dumbquote)(t));var t}},98778(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifyToml=function(e){return(0,s.flatten)((0,a.entries)(e).map(([e,t])=>l(e,t)))},t.kvToToml=l,t.wrapTomlToLines=function(e){return(0,r.blank)(e.key)||null==e.value||(null!=e.prepend&&e.lines.push(...(0,o.wrap)(["",...e.prepend],e.wrap)),e.lines.push(...l(e.key,e.value,e.wrap))),e.lines};const r=i(22573),s=i(96249),n=i(98553),a=i(68708),o=i(51926);function l(e,t,i){if((0,r.blank)(e))throw new Error("kvToToml(): Blank key");const s=e+" = "+(0,n.stringifyPretty)(t);return(0,r.blank)(i?.prefix)?[s]:(0,o.wrap)(s.split("\n"),i)}},99989(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolsSettings=void 0;const r=i(92234),s=i(43334),n=i(38483),a=i(74589),o=i(81075),l=i(58305),u=i(80372);t.ToolsSettings={showFileInFolderUsesThunar:new n.BooleanSetting({category:o.SettingCategories.Tools,description:'If we\'re on Linux, should we use Thunar (via dbus) to "show file in folder"?',defaultValue:!1}),showFileInFolderUsesFileUri:new n.BooleanSetting({category:o.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:()=>s.isLinux}),showFileInFolderCommand:new l.StringArraySetting({category:o.SettingCategories.Tools,description:'If set, the first argument will be used as a command (or path to command), and the subsequent arguments (if present) will be used as arguments. The native path to the file or the file: URI will be appended, based on the value given to the "showFileInFolderUsesFileUri" setting. If this is set to an empty array, the default tool for your platform will be used instead: "nautilus -s" on linux, "open -R" on mac, and "explorer /select" on Windows.\nThis is provided to support Linux desktops that don\'t use Gnome.',defaultValue:[]}),powerShellArgs:new l.StringArraySetting({category:o.SettingCategories.Tools,description:'The following are the default arguments added to spin up PowerShell on Windows devices.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1 for all arguments that PowerShell.exe accepts.\nSee https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1 for a description of Bypass.\nSee https://forum.photostructure.com/t/eliminate-powershell-profile-and-execution-policy-related-errors/184 for more details about why this needs to be configurable.\n(Versions prior to v1.0.0 only specified "-NoLogo").',defaultValue:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass"]}),powerShellCulture:new u.StringSetting({category:o.SettingCategories.Tools,description:"If set to a non-blank value, PhotoStructure on Windows machines will set PowerShell's `[System.Threading.Thread]::CurrentThread.CurrentCulture` to this value. This allows PhotoStructure to parse PowerShell output reliably.",defaultValue:()=>"en-US"}),powerShellProcs:new a.IntegerSetting({category:o.SettingCategories.Tools,description:"How many PowerShell child processes may each PhotoStructure process run? Defaults to max(2, (maxCpus() / 4)).",defaultValue:()=>2}),toolPaths:new l.StringArraySetting({category:o.SettingCategories.Tools,description:`These paths are prepended to the PATH environment variable to ensure PhotoStructure can find and run external tools like ffmpeg.\nYou can encode this as a JSON array, or use your operating system's separator to separate paths (":" for mac and linux, ";" for windows).\nOn Windows, this defaults to ${(0,r.defaultWinPaths)().join(";")}\nOn macOS, this defaults to ${(0,r.defaultMacOSPaths)().join(":")}\nOn Linux, this defaults to ${(0,r.defaultPosixPaths)().join(":")}\nNote that PhotoStructure will look in a series of standard directories specific to your operating system as a backstop after examining both this array and the PATH environment variable.`})}},56507(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UpdateSettings=void 0;const r=i(30577),s=i(38483),n=i(57039),a=i(81075),o=i(57571);t.UpdateSettings={autoUpgradeSettings:new s.BooleanSetting({category:a.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}),updateChannel:new o.StringEnumSetting({category:a.SettingCategories.Update,description:'This setting controls which builds of PhotoStructure you are eligible to update to. On desktops, upgrades are automated.\n"beta" builds have new features but may have bugs. "stable" builds are thoroughly tested. See https://forum.photostructure.com/t/alpha-beta-stable-and-latest-what-should-you-use/274 for details.',defaultValue:()=>r.UpdateChannels.stable,strEnum:r.UpdateChannels}),autoUpdateCheck:new s.BooleanSetting({category:a.SettingCategories.Update,description:'While running, PhotoStructure will check periodically for updates.\nSee https://forum.photostructure.com/t/new-in-v2023-10-automated-photostructure-version-checking/1956 for details.\nSet this to "false" to disable automatic update checking.\nNote that automatic upgrades are only supported on PhotoStructure for Desktops on macOS and Windows.',defaultValue:!1}),updateCheckTtlMs:new n.DurationSetting({category:a.SettingCategories.Update,description:"How frequently should PhotoStructure check for updates when running?",defaultValue:()=>"6h"})}},55018(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.valueToS=function(e){return(0,r.stringify)(e,2)};const r=i(98553)},63225(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyPsEnvSettings=function(e=process.env,t=.25){const i=[];for(const o of(0,r.keys)(e).filter(e=>{const t=e.toUpperCase();return t.startsWith("PS_")&&!n.IgnorableEnvKeys.includes(t)})){const r=e[o],n=(0,a.ciSettings)().lookup(o);if(null!=n){const e=n.value.whyInvalidEnvValue(r);null!=e&&i.push({envKey:o,msg:e})}else{const e=(0,a.ciSettings)().lookupNearest(o,t);null==e?i.push({envKey:o,msg:`No setting was found like "${o}"`}):(0,s.equalsIgnoreCase)(e.key,o)||i.push({envKey:o,msg:`Did you mean setting "${e.value.key}"?`})}}return i};const r=i(68708),s=i(81168),n=i(59958),a=i(28874)},2329(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VideoSettings=void 0;const r=i(52306),s=i(26978),n=i(38483),a=i(75164),o=i(74589),l=i(69005),u=i(81075),c=i(58305),d=i(57571),h=i(80372);t.VideoSettings={transcodeVideos:new n.BooleanSetting({aliases:["transcodeVideo"],category:u.SettingCategories.Video,description:"Whether to transcode videos during import so every browser can play them. Requires ffmpeg.\n\n**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.\n\n**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:\n- **Non-mp4 containers** (video/quicktime/MOV, MKV, AVI, etc.) — only video/mp4 and video/webm stream universally.\n- **`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.\n- **Non-H.264 video codecs** (HEVC/h265, VP9, AV1, ProRes, etc.) — depends on the specific browser + OS + hardware.\n- **Non-AAC audio codecs** (AC-3, DTS, etc.) — require transcoding for browser playback.\n\nUse `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 h.StringSetting({category:u.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.\nRun "ffmpeg -hwaccels" to see supported acceleration methods.\nNote that some hardware acceleration is only relevant for a handful of video codecs, so what might help for one transcode may not for another.\nNote that PhotoStructure will automatically retry without hwaccel if there are hwaccel errors.\nFor 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 a.BoundedIntegerSetting({category:u.SettingCategories.Video,description:'How many threads should ffmpeg use per transcode? Values are clamped to 0–6.\n\nSet 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.\n\nSet 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 o.IntegerSetting({category:u.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 d.StringEnumSetting({category:u.SettingCategories.Video,strEnum:r.FFmpegPresets,description:'Encoding preset for x264/x265. Faster presets encode more quickly but produce larger files.\nOptions: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow.\n"veryfast" offers an excellent speed/quality tradeoff (3-5x faster than "medium" with minimal quality difference).\nNote: These presets work for both libx264 and libx265 encoders.\nSee https://trac.ffmpeg.org/wiki/Encode/H.264#Preset for more details.',defaultValue:"veryfast"}),transcodeVideoCodec:new d.StringEnumSetting({category:u.SettingCategories.Video,strEnum:s.FFmpegVideoCodecs,description:"Video codec for transcoding. Choose based on your browser/device mix:\n\n**libx264 (H.264)** - Default, recommended for most users\n- Universal support: Works in ALL browsers on ALL platforms\n- Fast encoding speed\n- Larger files than HEVC\n\n**libx265 (HEVC/H.265)** - For Apple-only or storage-constrained setups\n- 25-40% smaller files than H.264\n- 2-5x slower encoding\n\nHEVC browser support:\n- Safari (macOS/iOS): Full support since Safari 11\n- Chrome (macOS/Windows only): Supported since v107 (NO Linux support)\n- Edge (Windows): Supported with hardware decode\n- Firefox: NO native support (requires OS-level codecs)\n - macOS: Works if system HEVC codec available\n - Windows: Firefox 134+ with HEVC Video Extensions from Microsoft Store\n - Linux: Firefox 137+ with VA-API hardware decode\n\n**Choose HEVC if:** You only use Safari/Chrome, or Apple devices, and want smaller files.\n**Stick with H.264 if:** You use Firefox on Linux/Windows, or need universal compatibility.\n\nIf switching to libx265, also set transcodeCrf to 28 for equivalent quality.\nSee https://photostructure.com/getting-started/video-support/ for details.",defaultValue:"libx264"}),transcodeCrf:new a.BoundedIntegerSetting({category:u.SettingCategories.Video,description:"Constant Rate Factor (CRF) for quality-based video encoding. Lower values = higher quality and larger files.\n\n**For libx264 (H.264, default):** 0 = lossless, 18 = visually transparent, 23 = good quality (default), 28 = acceptable for web.\n**For libx265 (HEVC):** 0 = lossless, 22 = visually transparent, 28 = good quality, 32 = acceptable for web.\n\nNote: HEVC CRF values are ~5 higher than H.264 for equivalent quality (HEVC 28 ≈ H.264 23).\nCRF 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 c.StringArraySetting({category:u.SettingCategories.Video,aliases:["ffmpegTranscodeArgs"],description:'Base arguments for ffmpeg video transcoding. These follow "ffmpeg -loglevel error -i INPUT".\n\n**Note**: Colorspace handling is now automatic based on source video metadata:\n- HDR (BT.2020/PQ/HLG): Preserved without conversion\n- BT.709 (most HD): Tagged correctly, no conversion\n- BT.601 (SD): Converted to BT.709 for browser compatibility\n- Unknown: Height-based heuristic (HD=BT.709, SD=BT.601)\n\nSee https://forum.photostructure.com/t/poor-transcoding-of-videos-in-wider-color-spaces-rec-2020/646\nCAUTION: 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 h.StringSetting({category:u.SettingCategories.Video,description:'PhotoStructure applies the given option to FFmpeg\'s "-err_detect" option. Available levels:\n- "crccheck" - Verify embedded CRCs\n- "bitstream" - Detect bitstream specification deviations\n- "buffer" - Detect improper bitstream length\n- "explode" - Abort decoding on minor error detection\n- "ignore_err" - Ignore decoding errors and continue (useful for analysis, but may produce unwatchable videos)\n- "careful" - Consider things that violate the spec but haven\'t been seen in the wild as errors\n- "compliant" - Consider all spec non-compliances as errors (strictest)\n- "aggressive" - Consider things a sane encoder shouldn\'t do as errors\n\nYou can combine multiple options with "+" (e.g., "crccheck+bitstream+buffer").\nThe default "crccheck+bitstream+buffer" provides strict but reasonable error detection.',defaultValue:"crccheck+bitstream+buffer"}),transcodeMaxDim:new o.IntegerSetting({category:u.SettingCategories.Video,description:"If a video that needs transcoding exceeds this setting's value, the transcoded version will be downsampled such that the long side will equal this setting. A value of 1920 is good for 1080p, and 1280 would transcode to 720p resolution.\nSet this to 0 to disable this setting.",defaultValue:1920}),transcodeFrameRate:new l.OptionalIntegerSetting({category:u.SettingCategories.Video,description:"If set, transcoded videos will be bounded to this framerate. Videos that are lower than this framerate will retain their original (lower) framerate.\nNote that framerate reduction does not reduce the final transcoded video size linearly: it may only reduce file sizes by ~20% to go from 60 FPS to 30 FPS.\nUnset this or set to 0 to disable bounded frame rates.",exampleValue:()=>30}),doNotTranscodeMimeTypes:new c.StringArraySetting({category:u.SettingCategories.Video,description:'Videos are transcoded when the "transcodeVideos" is set to true and is not one of the following MIME types.\nSee https://www.iana.org/assignments/media-types/media-types.xhtml#video for a complete list.\nIf you are setting this via an environment variable, you can separate the values either like a PATH (like "video/quicktime:video/mp4") or use JSON encoding (like "[\'video/quicktime\',\'video/mp4\']").',defaultValue:()=>["video/quicktime","video/mp4","video/mpv","video/mp2t"]}),doNotTranscodeVideoCodecs:new c.StringArraySetting({category:u.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.\n\n**Browser Compatibility:**\n- "avc1" (H.264): Universal support - all browsers, all platforms\n- "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)\n- "vp09" (VP9): Chrome/Firefox/Edge (full), Safari 14+ (hardware only on newer Apple chips)\n\n**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).\n\nVP9 is NOT included by default because older iOS devices lack hardware VP9 decode.\nSee https://photostructure.com/getting-started/video-support/ for details.',defaultValue:()=>["avc1"]}),doNotTranscodeAudioCodecs:new c.StringArraySetting({category:u.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.\n\n**Browser Compatibility (2025):**\n- "mp4a" (AAC): Universal support across all browsers and devices\n- "sowt" (PCM/Linear): Universal support (uncompressed audio)\n- Opus: Supported by Chrome, Firefox, Edge, Safari 15.4+\n\nNote: AC-3, DTS, and other surround codecs require transcoding to AAC for browser playback.',defaultValue:()=>["mp4a","sowt"]}),browserCompatibleContainers:new c.StringArraySetting({category:u.SettingCategories.Video,description:'MIME types of video containers that browsers can play directly without transcoding.\nThis is used to determine if a video only needs remuxing (container change) vs full transcoding.\nRemuxing is lossless and very fast compared to transcoding.\n\n**Browser Compatibility (2025):**\n- "video/mp4": Universal support across all browsers and devices\n- "video/webm": Chrome, Firefox, Edge (full), Safari 14.1+ (partial - VP8/VP9 only, no AV1 on older devices)\n\nNote: This is different from doNotTranscodeMimeTypes - that setting controls whether to transcode at all,\nwhile this setting helps optimize HOW to transcode (remux vs full re-encode).',defaultValue:()=>["video/mp4","video/webm"]})}},20029(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VolumesSettings=void 0;const r=i(38483),s=i(57039),n=i(81075),a=i(58305);t.VolumesSettings={volumeUuidFilePaths:new a.StringArraySetting({category:n.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).\nPrior versions included "System Volume Information/IndexerVolumeGuid" but read permissions for that directory under Windows requires admin privileges, which we don\'t want.\nWindows users should use a forward slash as a path separator.',defaultValue:()=>[".uuid"]}),readVolumeUuidFiles:new r.BooleanSetting({category:n.SettingCategories.Volumes,description:'When true, PhotoStructure uses ".uuid" files found in the root directory of volumes as the volume universally unique identifier (UUID), which supports cross-host and cross-OS library portability. Set this to false if you don\'t want PhotoStructure to read these ".uuid" files.\nNote that "globally unique identifier," or "GUID," is synonymous with "UUID" in this case. Microsoft tends to use the term "GUID" instead of "UUID."\nFor more details see https://photostructure.com/faq/what-is-a-volume',defaultValue:!0}),skipWriteVolumeUuidFilesWithNoMedia:new r.BooleanSetting({category:n.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 r.BooleanSetting({category:n.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}),writeVolumeUuidMountpointBlocklist:new a.StringArraySetting({category:n.SettingCategories.Volumes,description:"Never try to write a volume UUID file to these directories.",defaultValue:["sshfs","s3fs"]}),volumeMetadataTtlMs:new s.DurationSetting({category:n.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. A value of 0 will cache indefinitely.",defaultValue:"15m"})}},24660(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebSettings=void 0;const r=i(50989),s=i(38483),n=i(90536),a=i(75164),o=i(74589),l=i(81075),u=i(58305),c=i(57571),d=i(80372);t.WebSettings={webUvThreads:new a.BoundedIntegerSetting({category:l.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 n.BoundedFloatSetting({category:l.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 o.IntegerSetting({category:l.SettingCategories.Web,description:'PhotoStructure only loads photos as they come close to the viewport. This setting determines what "close to the viewport" means, and is measured in "vh" units, or percentage points of your visitor\'s browsers view height.\nThe default is 50, so approximately the next 50% of the screen will be pre-loaded before the user scrolls.\nIf you have fast hardware and fast network, you could try bumping this up to 200.\nIf you have very slow network, you might want to set this to 0.',defaultValue:50}),hiddenRootTags:new u.StringArraySetting({category:l.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 o.IntegerSetting({category:l.SettingCategories.Web,description:"When generating OpenGraph header metadata, include the preview image closest to this number of pixels wide.\nSee https://forum.photostructure.com/t/image-thumbnail-in-link-preview/1950 for details.",defaultValue:800}),placeholderThumbs:new s.BooleanSetting({category:l.SettingCategories.Web,description:"Render missing asset previews as placeholder images (only useful for customer support).",defaultValue:!1,transient:!0,propagateToChildren:!1}),fastForwardEmptyTags:new s.BooleanSetting({category:l.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 c.StringEnumSetting({category:l.SettingCategories.Web,description:'Should the /site.webmanifest send you to "/splash", or just directly to the home page, "/tag"?\n(IMHO /splash is more fun, but it slows down getting to the home page).',strEnum:(0,r.strEnum)("/tag","/splash"),defaultValue:()=>"/tag"}),webAppName:new d.StringSetting({category:l.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 d.StringSetting({category:l.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"})}},10357(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WrapComments=void 0,t.WrapComments={maxLineLen:78,prefix:"# "}},81595(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileGrep_=async function(e,t,i={}){const s=new u(t);return await(0,n.pipeline)([(0,r.createReadStream)((0,o.toNativePath_)(e)),new l.LineReader(i),s]),s.result};const r=i(73024),s=i(57075),n=i(46466),a=i(54993),o=i(17217),l=i(90753);class u extends s.Transform{pattern;result;constructor(e){super({objectMode:!0,autoDestroy:!0}),this.pattern=e}_transform(e,t,i){const r=(0,a.toS)(e),s=this.pattern.exec(r);null!=s&&(this.result??=s,this.push(null)),i()}}},53252(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.gzip_=async function(e){if(e.endsWith(".gz"))return e;const t=e+".gz",i=(0,a.join)((0,a.dirname)(t),(0,h.addWipPrefix)((0,a.basename)(t)));try{if(0===(await n.default.stat(e)).size){const e=l.default.gzipSync(Buffer.alloc(0));await n.default.writeFile(i,e,{flush:!0})}else await(0,o.pipeline)(s.default.createReadStream(e,{autoClose:!0}),l.default.createGzip(),s.default.createWriteStream(i,{autoClose:!0}));return await n.default.rename(i,t),await n.default.unlink(e),t}catch(e){try{await n.default.unlink(i)}catch(e){"ENOENT"!==(0,c.errorCode)(e)&&p().warn("gzip_ cleanup failed",{tmp:i,unlinkError:e})}throw e}},t.isExtOrCompressedExt=function(e,t){return y(t).test(e)},t.regexForExtOrCompressedExt=y;const s=r(i(73024)),n=r(i(51455)),a=i(76760),o=i(46466),l=r(i(38522)),u=i(45599),c=i(26905),d=i(49769),h=i(70257),f=i(50213),m=i(68852),p=(0,u.defer)(()=>(0,f.mkLogger)("stream.Gzip")),g=new Map;function y(e){return(0,d.getOrSet)(g,e,()=>new RegExp((0,m.escapeRegExp)(e)+"(?:\\.(gz|br))?$","i"))}},90753(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LineReader=void 0;const r=i(57075),s=i(81168),n={trimStart:!1,trimEnd:!1,onlyStreamFullLines:!1};class a extends r.Transform{#Lr="";#Nr;constructor(e={}){super({objectMode:!0}),this.#Nr={...n,...e}}#jr(e){if(null==e)return;let t=this.#Nr.trimStart?e.trimStart():e;return t=this.#Nr.trimEnd?t.trimEnd():t,""===t?void 0:t}_transform(e,t,i){try{let r=Buffer.isBuffer(e)?e.toString(t):String(e);this.#Lr&&(r=this.#Lr+r,this.#Lr="");for(const e of(0,s.yieldSplit)(r,/\n/g)){if(!e.endsWith("\n")){this.#Lr=e;break}const t=this.#jr(e);void 0!==t&&this.push(t)}i()}catch(e){i(e)}}_flush(e){if(!this.#Nr.onlyStreamFullLines){const e=this.#jr(this.#Lr);null!=e&&(this.push(e),this.#Lr="")}e()}}t.LineReader=a},1034(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReadableBuffer=void 0;const r=i(57075);class s extends r.Readable{constructor(e){super(),this.push(e),this.push(null)}}t.ReadableBuffer=s},14810(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.streamEnded=function(e){return null==e||!e.writable||e.destroyed||e.writableEnded||e.writableFinished}},21027(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.writeAsync=async function(e,t){return null==e||!0!==e.writable||!0===e.destroyed?Promise.reject(new Error("target is not writable")):new Promise((i,r)=>{e.write(t,e=>{null!=e?r(e):i()})})},t.disposeStream=f,t.onChildError=function(e,t){for(const{name:i,ea:r}of[{name:"cp",ea:e},{name:"stdin",ea:e.stdin},{name:"stdout",ea:e.stdout},{name:"stderr",ea:e.stderr}])(0,u.map)(r,e=>e.on("error",e=>{!1===(0,h.isIgnorableError)(e)&&t(i,e)}))},t.closeStreams=function(e){for(const t of[e?.stdin,e?.stdout,e?.stderr])try{!1===t?.destroyed&&t?.destroy()}catch{}},t.remoteDesc=function(e){return e.destroyed?"destroyed":`${e.remoteFamily}:${e.remoteAddress}:${e.remotePort}`},t.streamToGenerator=async function*(e){const t=e instanceof o.Readable?e:function(e){return null!=e&&"readable"in e&&e.readable instanceof o.Readable}(e)?e.readable:null;if(null==t)throw new Error("Input must be a readable stream or have a readable property");try{if(!0===t.readableObjectMode){for await(const e of t)yield e;return}const e="getReader"in t?t.getReader():t;for(;;){const{done:t,value:i}=await e.read();if(!0===t)break;yield i}}finally{await f(t)}};const o=a(i(57075)),l=i(41400),u=i(55835),c=i(42279),d=i(99331),h=i(70025);async function f(e,t={}){if(null==e)return;const{delayMs:i=50,force:r=(0,d.ending)()}=t;try{"allowHalfOpen"in e&&(e.allowHalfOpen=!1)}catch{}try{e.unref?.()}catch{}if(!("end"in e)||"function"!=typeof e.end||!0!==e.readable&&!0!==e.writable||!0===e.destroyed||(r?e.end():await new Promise(t=>e.end(t)),r||await(0,l.delay)(i)),"close"in e&&"function"==typeof e.close&&!0!==e.closed){if(r)try{e.close(c.NoOp)}catch{}else await new Promise(t=>e.close(t));r||await(0,l.delay)(i)}try{e.closeAllConnections?.()}catch{}try{"destroy"in e&&"function"==typeof e.destroy&&!0!==e.destroyed&&e.destroy()}catch{}}},97867(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WritableToBuffer=void 0;const r=i(57075),s=i(22911);class n extends r.Writable{deferred=new s.Deferred("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,t,i){this._buf.push(Buffer.isBuffer(e)?e:Buffer.from(e,t)),i()}}t.WritableToBuffer=n},65162(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bname=c,t.shortestBname=function(e){return(0,s.leastBy)(c(e),(e,t)=>[e.length,t])??""};const r=i(76760),s=i(76790),n=i(22573),a=i(54993),o=i(4001),l=i(81168),u=i(14036);function c(e){if((0,n.blank)(e))return[];const t=(0,l.isString)(e)?(0,u.stripExt)((0,r.basename)(e)):(0,a.toS)(e?.name);if((0,n.blank)(t))return[];const i=t.toLowerCase().normalize(),s=new Set([i]);for(const e of[o.stripCopySuffixFromName,o.stripDSC,l.trimLeftPadding,e=>(0,o.stripDSC)((0,o.stripCopySuffixFromName)(e)),e=>(0,l.trimLeftPadding)((0,o.stripCopySuffixFromName)(e)),e=>(0,l.trimLeftPadding)((0,o.stripDSC)(e)),e=>(0,l.trimLeftPadding)((0,o.stripDSC)((0,o.stripCopySuffixFromName)(e)))]){const t=e(i);(0,n.blank)(t)||s.add(t)}return[...s].sort()}},28544(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readCapturedAt=t.CapturedAt=void 0,t.bestCapturedAt=function(e){const t=(0,s.sortBy)(e,e=>e?.capturedAtLocal);return(0,g.first)(a.CapturedAtSrcTypes.values,e=>t.find(t=>t.capturedAtSrc===e))??t[0]},t.extractCapturedAt=q,t.extractCapturedAt_=$,t.capturedAtFromTags=function(e){return G(e,O.ParsingSettings.capturedAtTagsPrimary.values)},t._capturedAtFromTags=G,t.capturedAtFromBasename=K,t.capturedAtFromPath=J,t.capturedAtFromStat=Y;const r=i(77988),s=i(76790),n=i(22573),a=i(7016),o=i(42659),l=i(45599),u=i(50357),c=i(98553),d=i(55835),h=i(31586),f=i(68708),m=i(27313),p=i(76790),g=i(48884),y=i(76596),v=i(79842),b=i(66649),w=i(21330),S=i(98725),P=i(928),M=i(93515),T=i(21404),_=i(89724),E=i(17415),k=i(88600),D=i(91987),I=i(95696),C=i(17217),A=i(57902),x=i(50213),F=i(39056),O=i(57414),R=i(29985),L=i(81168),N=i(65162),j=i(66321),B=i(71300),z=i(54979),V=i(38148),H=i(61424),U=(0,l.defer)(()=>(0,x.mkLogger)("tags.CapturedAt"));class W{mimetype;date;capturedAtLocal;zone;capturedAtSrc;capturedAtSrcDetail;capturedAtZoneSrc;capturedAtPrecisionMs;capturedAtRaw;static async fromFile_(e,t){const i=I.PosixFile.for(e);return $(i,t??await(0,V.readRawTags)(i))}static fromJSON(e){const t=(0,k.isValidDate)(e.date)?e.date:(0,c.fromJsonObject)(e.date);if(null!=t&&(0,k.isValidDate)(t))return this.fromFields({...e,date:t})}static fromFields(e){if(null==e||null==e.mimetype||(0,n.blank)(e.mimetype))return;const t={...e};if((0,n.blank)(t.capturedAtSrc))return U().tap({msg:"CapturedAt.fromFields(): missing required capturedAtSrc field",result:void 0,meta:{ctorArgs:t}});if(null==t.capturedAtLocal&&null!=t.date?t.capturedAtLocal=(0,_.datedToLocal)(t.date):null==t.date&&null!=t.capturedAtLocal&&(t.date=(0,_.localToDateTime)({local:t.capturedAtLocal,zone:(0,r.normalizeZone)(t.zone)??(0,r.normalizeZone)(t.capturedAtZone)})),null==t.capturedAtLocal)return U().tap({msg:"CapturedAt.fromFields(): missing required capturedAtLocal field",result:void 0,meta:{ctorArgs:t}});const i=new W(t);return U().tap({msg:"CapturedAt.fromFields(): created instance",result:i.isValid?i:void 0,meta:{why:i.whyNotValid(),ctorArgs:t}})}constructor(e){this.mimetype=e.mimetype,this.date=e.date,this.capturedAtRaw=(0,n.toNotBlank)(e.capturedAtRaw)??(0,v.datedToRawValue)(this.date),this.capturedAtLocal=e.capturedAtLocal,this.zone=(0,r.normalizeZone)(e.zone)??(0,r.normalizeZone)(e.capturedAtZone)??(0,M.getZone)(this.date),this.capturedAtSrc=e.capturedAtSrc,this.capturedAtSrcDetail=(0,n.toNotBlank)(e.capturedAtSrcDetail),this.capturedAtZoneSrc=(0,n.toNotBlank)(e.capturedAtZoneSrc),this.capturedAtPrecisionMs=e.capturedAtPrecisionMs??(0,v.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()+(null!=this.capturedAtZone?` (${this.capturedAtZone})`:"")}toJSON(){return{mimetype:this.mimetype,date:(0,c.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(0,v.datedToISO)(this.date)}toExifString(){return(0,v.datedToEXIF)(this.date)}toLocaleString(e){const t=(0,v.toDate)(this.date);return t?.toLocaleString(e)??""}get isFromTags(){return"tags"===this.capturedAtSrc}get isFromStat(){return"stat"===this.capturedAtSrc||"bname+stat"===this.capturedAtSrc||"path+stat"===this.capturedAtSrc}get isInferred(){return!this.isFromTags&&!this.isFromStat}get isFuzzy(){return!this.isFromTags||(0,_.localIsFuzzy)(this.capturedAtLocal)}toISOStringWithPrecision(){return(0,v.datedToISO)(this.date,!0,this.capturedAtPrecisionMs)+(null==this.capturedAtPrecisionMs?"":" (±"+(0,y.fmtMs)(this.capturedAtPrecisionMs)+")")}hasZone(){return null!=this.capturedAtZone}isUTC(){return(0,r.isUTC)(this.capturedAtZone)}hasTime(){return(0,T.hasTime)(this.date)}hasMillis(){return(0,h.gt0)((0,P.getMillisecond)(this.date))}toMillis(){return(0,b.datedToMillis)(this.date)}whyNotValid(){return(0,n.blank)(this.mimetype)?"missing mimetype":(0,n.blank)(this.capturedAtSrc)?"missing capturedAtSrc":(0,k.isValidDate)(this.date)?void 0:"invalid date"}get isValid(){return null==this.whyNotValid()}asExifTag(){const e=this.toExifString();return null==e?void 0:{DateTimeOriginal:e,TimeZone:this.capturedAtZone}}fuzzyPrecisionMs(){return(this.isFuzzy?F.AggregationSettings.fuzzyDatePrecisionFactor.valueOrDefault:1)*(this.capturedAtPrecisionMs??o.secondMs)}localBoundaries(e){const t=(e?.precisionMs??0)+this.fuzzyPrecisionMs(),i=(0,v.datedToStartDateTime)(this.date)??(0,v.datedToDateTime)(this.date);if(null!=i)return{start:(0,_.datedToLocal)(i.minus(t)),end:(0,_.datedToLocal)(i.plus(t))};U().warn("localBoundaries() failed",{date:this.date,args:e,d:i})}overlaps(e){if(null==e)return!1;if(this.capturedAtLocal===e.capturedAtLocal)return!0;const t=this.mimetype===e.mimetype?0:F.AggregationSettings.minCapturedAtPrecisionDifferentMimetypes.valueOrDefault,i=Math.max(t,this.fuzzyPrecisionMs()),r=Math.max(t,e.fuzzyPrecisionMs());return U().tap({level:"trace",msg:"overlaps()",result:this.capturedAtLocal===e.capturedAtLocal||(0,v.datedOverlap)({a:this.date,b:e.date,aPrecisionMs:i,bPrecisionMs:r}),meta:{a:this,b:e,aPrecisionMs:i,bPrecisionMs:r}})}toCapturedAtFields(){return(0,f.pick)(this,...j.CapturedAtFieldNames)}static async fromMediaInfoAsync(e){return this.fromMediaInfo(await(0,m.awaitFields)((0,f.pick)(e,...j.CapturedAtFieldNames.values.filter(e=>"capturedAtRaw"!==e))))}static fromMediaInfo(e){return null==e.capturedAtLocal||(0,n.blank)(e.capturedAtSrc)||(0,n.blank)(e.mimetype)?void 0:W.fromFields(e)}}async function q(e){try{return await $(e,await(0,V.readRawTags)(e))}catch(t){return void U().warn("readCapturedAt() failed",{nativePath:(0,C.toNativePath_)(e),error:t})}}async function $(e,t,i=!1,r){const s=I.PosixFile.for(e),a=(0,n.toNotBlank)(t?.MIMEType)??await(0,z.readMimeType_)(s);function o(e,t){return null!=t&&null==t.capturedAtLocal&&(t.capturedAtLocal=(0,d.map)(t?.date,_.datedToLocal)),U().tap({msg:"extractCapturedAt_()",result:W.fromFields({mimetype:a,capturedAtSrc:t?.capturedAtSrc??e,...t}),meta:{src:e,f:s,mimetype:a}})}const l=function(e,t){return null==e||t||!O.ParsingSettings.usePathsToInferDates.valueOrDefault||!O.ParsingSettings.useLibraryDirsToInferDates.valueOrDefault&&(0,D.containedByNativePath)({ancestor:R.PathSettings.libraryDir.value,descendant:e.nativePath,acceptSelf:!0})}(s,i),u=o("tags",G(t,O.ParsingSettings.capturedAtTagsPrimary.values))??o("tags",G(t,O.ParsingSettings.capturedAtTagsSecondary.values))??o("tags",G(t,O.ParsingSettings.capturedAtTagsTertiary.values))??o("tags",G(t,O.ParsingSettings.capturedAtTagsFallback.values))??(i?void 0:o("siblings",await(0,H.inferCapturedAtFromSiblings)(s,r)))??(l?void 0:o("bname+stat",await(0,H.extractStatBnameTime)(s)))??(l?void 0:o("path+stat",await(0,H.extractStatPathTime)(s)))??(l?void 0:o("bname",K(s,t)))??(l?void 0:o("path",J(s)))??(O.ParsingSettings.useStatToInferDates.valueOrDefault?o("stat",await Y(s)):void 0);return null==u?U().throw("Failed to extract capturedAt from "+s):U().tap({level:A.LogLevels.debug,msg:"extractCapturedAt()",result:u,meta:{nativePath:s.nativePath}})}function G(e,t){if(null==e)return;const i=(0,n.toNotBlank)(e.MIMEType);if(null==i)return;if(null!=e&&"capturedAt"in e&&e.capturedAt instanceof W)return e.capturedAt;const r=[];for(const s of t){let t=s in e?e[s]:void 0;if((0,h.isNumber)(t)&&t>=O.ParsingSettings.minValidYear.valueOrDefault&&(t=w.FuzzyDate.for({year:t})),(0,k.isValidDate)(t)){const a=t;let o,l=a;B.OverrideUTCZoneTags.includes(s)?(l=(0,w.setZone)(a,"UTC")??a,o="forced"):(0,E.isValidZone)(e.zone)&&!(0,M.hasZone)(a)&&(l=(0,w.setZone)(a,e.zone)??a,o=(0,n.toNotBlank)((0,n.blank)(e.zoneSource)?void 0:(0,L.stripPrefix)(e.zoneSource,"from ")));const u=(0,_.datedToLocal)(l);if(null==u)continue;r.push({mimetype:i,capturedAtLocal:u,date:l,capturedAtSrc:"tags",capturedAtSrcDetail:s,capturedAtZoneSrc:o})}}const s=(0,p.leastBy)(r,e=>(0,v.datedToStartTs)(e.date));if(null==s)return void U().debug("capturedAtFromTags(): no candidate passed leastBy: returning null",{candidates:r});const a=r.filter(e=>(0,u.eql)(e.date,s.date)||(0,v.datedOverlap)({a:e.date,b:s.date,aPrecisionMs:e.capturedAtPrecisionMs,bPrecisionMs:s.capturedAtPrecisionMs})),o=(0,p.leastBy)(a,e=>[Math.floor((e.capturedAtLocal??0)/1e6),(0,M.hasZone)(e.date)?0:1,e.capturedAtPrecisionMs??v.MAX_PRECISION_MS,-1*(e.capturedAtRaw?.length??0),e.capturedAtSrc??""]);return U().debug("capturedAtFromTags()",{candidates:r,least:s,overlapsWithLeast:a,earliest:o}),o}function K(e,t){if(O.ParsingSettings.usePathsToInferDates.valueOrDefault)for(const i of(0,s.sortBy)((0,N.bname)(e),e=>-e.length)){const e=(0,S.parseDated)({input:i,defaultZone:t?.zone});if(null!=e)return{date:e,precisionMs:(0,g.max)([(0,v.datedToPrecisionMs)(e),o.secondMs])}}}function J(e){if(O.ParsingSettings.usePathsToInferDates.valueOrDefault)return{date:(0,S.extractDateFromPath)(e.pathsForDateParsing())}}async function Y(e){if(O.ParsingSettings.useStatToInferDates.valueOrDefault)return{date:await e.minStatDate()}}t.CapturedAt=W,t.readCapturedAt=q},66321(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CapturedAtFieldNames=void 0,t.isCapturedAtFields=o,t.pickCapturedAtFields=function(e){return o(e)?(0,n.pick)(e,...t.CapturedAtFieldNames):void 0};const r=i(22573),s=i(31586),n=i(68708),a=i(50989);function o(e){return null!=e&&!(0,r.blank)(e.mimetype)&&(0,s.isNumber)(e.capturedAtLocal)&&(null==e.capturedAtPrecisionMs||(0,s.isNumber)(e.capturedAtPrecisionMs))&&!(0,r.blank)(e.capturedAtSrc)}t.CapturedAtFieldNames=(0,a.strEnum)("mimetype","capturedAtLocal","capturedAtZone","capturedAtPrecisionMs","capturedAtSrc","capturedAtSrcDetail","capturedAtZoneSrc","capturedAtRaw")},97069(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTagsCache=async function(){o.tagsCache.prior()?.clear(),n.rawMergedTagsCache.prior()?.clear(),a.rawTagsCache.prior()?.clear(),s.mimetypeCache.prior()?.clear(),l.sizeInfoCache.prior()?.clear()},t.clearTagsCacheForDir=function(e){u(e);const t=function(e){if(!r.isMac)return;const t="/private";if(e.startsWith(t+"/"))return e.slice(8);for(const i of["/var","/tmp","/etc"])if(e.startsWith(i+"/")||e===i)return t+e}(e);null!=t&&u(t)};const r=i(43334),s=i(54979),n=i(35332),a=i(38148),o=i(40538),l=i(1078);function u(e){o.tagsCache.prior()?.deleteByPrefix(e),n.rawMergedTagsCache.prior()?.deleteByPrefix(e),a.rawTagsCache.prior()?.deleteByPrefix(e),s.mimetypeCache.prior()?.deleteByPrefix(e),l.sizeInfoCache.prior()?.deleteByPrefix(e)}},70379(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateTagFormats=void 0;const r=i(38639),s=i(50989);t.DateTagFormats=(0,s.strEnum)("y","ym","ymd",r.DISABLED)},71300(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CapturedAtTagsFallback=t.CapturedAtTagsTertiary=t.CapturedAtTagsSecondary=t.CapturedAtTagsPrimary=t.OverrideUTCZoneTags=t.CapturedAtTagsIgnored=void 0;const r=i(81168);t.CapturedAtTagsIgnored=["creationTime","HistoryWhen","MediaModifyDate","MetadataDate","SubSecTime","TrackModifyDate"],t.OverrideUTCZoneTags=["DateTimeUTC","GPSDateTime"],t.CapturedAtTagsPrimary=(0,r.sortIgnoreCase)(["CreationDate","DateTimeOriginal","SubSecDateTimeOriginal","OriginalCreateDateTime"]),t.CapturedAtTagsSecondary=(0,r.sortIgnoreCase)(["SubSecCreateDate","SubSecModifyDate","ModifyDate","DateTime","DateTimeCreated","CreateDate","MediaCreateDate","CreationTime"]),t.CapturedAtTagsTertiary=(0,r.sortIgnoreCase)(["DigitalCreationDateTime","DateTimeDigitized","TrackCreateDate"]),t.CapturedAtTagsFallback=(0,r.sortIgnoreCase)(["photoTakenTime",...t.OverrideUTCZoneTags])},33209(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultIncludedPreviewTags=void 0,t.DefaultIncludedPreviewTags=["AttributionName","AttributionURL","capturedAt","Copyright","exposureSettings","GPSLatitude","GPSLongitude","License","Make","Model","Permits","Prohibits","Rating","Requires","Source"]},48987(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultLensMakes=void 0,t.DefaultLensMakes=["7artisans","Bower","Canon","Carl Zeiss","Cosina","Fuji","Fujifilm","Goerz","Hasselblad","Hirox","Hoya","Kodak","Konica","Leica","Leidolf","Lensbaby","Lumix","Meike","Meopta","Minolta","Neewer","Nikon","Olympus","Opteka","Panasonic","Pentacon","Pentax","Ricoh","Rodenstock","Rokinon","Ross","Samsung","Samyang","Seiko","Sigma","Silor","Soligor","Sony","Sunpak","Tamron","Tiffen","Tokina","Topcon","Venus","Voigtländer","Wray","Yongnuo","Zeiss","Zhong Yi","Zuiko"]},43207(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractDurationSec=l,t.extractDurationMs=function(e){return(0,s.mapGt0f)(l(e),e=>Math.round(1e3*e))},t.extractDuration=async function(e){if(null==e)return;const t=n.PosixFile.for(e);return l(await(0,o.readRawTags)(t))};const r=i(31586),s=i(97352),n=i(95696),a=i(16170),o=i(38148);function l(e){if(null!=e&&(0,a.isVideoMimeType)(e?.MIMEType))for(const t of["duration","Duration","MediaDuration","TrackDuration"]){const i=(0,r.toGt0f)(e[t]);if(null!=i)return i}}},72180(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUtcTagName=function(e){return e.includes("UTC")||e.startsWith("GPS")}},47783(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setExifToolProcs=function(e){return b.Settings.exiftoolProcsPerChild.cliValue=e,k()},t.exiftoolProcsPerChild=M,t.exiftool=E,t.exiftoolVersion_=async function(){return(0,m.thenOrTimeoutError)({p:E().version(),timeoutMs:b.Settings.statTimeoutMs.valueOrDefault})},t.exiftoolVersionMaybe=function(){return(0,o.map)(_.prior(),e=>e.ended?void 0:(0,m.thenOrTimeoutError)({p:e.version(),timeoutMs:(0,w.commandTimeoutMs)()}))},t.shutdownExiftool=k,t.extractBinaryTag=function(e,t,i){return(0,f.time)({name:"exif.extractBinary",meta:{tagname:e},p:E().extractBinaryTag(e,t,i)})};const s=i(77988),n=r(i(76760)),a=i(45599),o=i(55835),l=i(31586),u=i(36557),c=i(19851),d=i(50213),h=i(23560),f=i(56038),m=i(4867),p=i(46473),g=i(5852),y=i(29325),v=i(43334),b=i(28874),w=i(63870),S=i(15674),P=(0,a.defer)(()=>(0,d.mkLogger)("tags.ExifTool"));function M(){const e=(0,l.toGt0)(b.Settings.exiftoolProcsPerChild.valueOrDefault);return null!=e?e:(0,h.isWorkerService)()?2:(0,S.maxCpus)()}async function T(){return P().tap({msg:"exiftoolPath()",level:"info",result:(0,v.isElectron)()&&(0,y.isPacked)()?n.default.join(p.ProjectDir.Root(),"exiftool-vendored"+(v.isWin?".exe":".pl"),"bin","exiftool"+(v.isWin?".exe":"")):await(0,s.exiftoolPath)()})}const _=(0,c.lazy)(()=>{const e={useMWG:b.Settings.useMWG.valueOrDefault,backfillTimezones:!0,ignoreZeroZeroLatLon:!0,inferTimezoneFromDatestamps:!0,defaultVideosToUTC:b.Settings.defaultVideosToUTC.valueOrDefault,imageHashType:(0,g.toExifToolOption)(b.Settings.imageDataHashType.valueOrDefault),exiftoolPath:T,geolocation:b.Settings.tagGeo.valueOrDefault,numericTags:b.Settings.numericTags.valueOrDefault,preferTimezoneInferenceFromGps:b.Settings.preferTimezoneInferenceFromGps.valueOrDefault,...(0,u.batchClusterOptions)(M(),"exif.ExifTool")};return P().info("ExifTool options",e),new u.BatchClusterObserver("ExifTool",new s.ExifTool(e)).t});function E(){const e=_();return e.ended?_.refresh():e}function k(e=!1){return(0,o.map)(_.clear(),t=>t.end(e))}},75767(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.zeroesRe=t.Tag2Synonyms=t.Tag2SynonymGroup=t.CameraSerialNumberSynonyms=t.ImageNumberSynonyms=void 0,t.stringifyExifUid=S,t.renderExifUidId=M,t.decodeExifUid=_,t.findInequalFields=function(e,i){const r=_(e),n=_(i);if(null==r||null==n||e===i)return;const a=(0,f.intersection)((0,u.keys)(r),(0,u.keys)(n)).filter(e=>!(0,t.Tag2SynonymGroup)().has(e));for(const e of a){const t=r[e],i=n[e];if(P(t)!==P(i))return{aKey:e,aValue:t,bKey:e,bValue:i}}for(const e of b){const t=(0,u.pick)(r,...e);if((0,u.isEmptyObj)(t))continue;const i=(0,u.pick)(n,...e);if((0,u.isEmptyObj)(i))continue;const a=(0,u.values)(t).map(d.toS),o=(0,u.values)(i).map(d.toS);if((0,s.includesAny)(a,o))continue;const l=(0,h.least)((0,u.keys)(t)),c=(0,h.least)((0,u.keys)(i));return{aKey:l,aValue:r[l],bKey:c,bValue:n[c]}}},t.whyExposureSettingsNotSimilar=function(e,t){if(null!=e&&null!=t)return E({a:e,b:t,field:"focalLength",desc:"focal length",parser:p.extractFloat})??E({a:e,b:t,field:"aperture",desc:"aperture",parser:p.extractFloat})??E({a:e,b:t,field:"shutterSpeed",desc:"shutter speed",parser:p.extractFraction})??E({a:e,b:t,field:"iso",desc:"ISO",parser:p.extractFloat})},t.cameraIdFromTags=function(e){return M((0,u.pick)(e,...t.CameraSerialNumberSynonyms))},t.lensIdFromTags=function(e){return k({...(0,v.extractLensMakeModel)(e),...e})},t.lensIdFromLensInfo=k,t.imageIdFromTags=function(e){return M((0,u.pick)(e,...t.ImageNumberSynonyms,"BurstUUID","RunTimeValue"))},t.uidGeoHash=function(e,t){return(0,m.geohash)((0,l.toFixed)(e,4),(0,l.toFixed)(t,4))};const r=i(19851),s=i(40958),n=i(22573),a=i(98553),o=i(23838),l=i(31586),u=i(68708),c=i(67478),d=i(54993),h=i(76790),f=i(48884),m=i(73168),p=i(97352),g=i(81168),y=i(28874),v=i(15912);t.ImageNumberSynonyms=["ImageNumber","ShutterCount","ShutterCount2","ShutterCount3"],t.CameraSerialNumberSynonyms=["CameraSerialNumber","SerialNumber","BodySerialNumber","InternalSerialNumber"];const b=[t.ImageNumberSynonyms,t.CameraSerialNumberSynonyms];function w(e){return null==e||(0,n.blankish)(e)||(0,l.isNumber)(e)&&(0===e||1===e)||null!=t.zeroesRe.exec((0,d.toS)(e))||(0,g.isGarbageString)((0,d.toS)(e),1)}function S(e){const t=null==e?[]:e.filter(([,e])=>!(0,n.blank)(e));return 0===t.length?void 0:(0,a.stringify)((0,u.fromEntries)(t))}function P(e){return(0,d.toS)(e).trim().replace(/\s+/g," ")}function M(e){const i=new o.MultiMap,r=[];for(const s of(0,g.sortIgnoreCase)((0,u.keys)(e))){if(w(e[s]))continue;const n=e[s],a=P(e[s]),o=(0,t.Tag2SynonymGroup)().get(s);if(null!=o){if(i.includes(o,n)||i.includes(o,a))continue;i.add(o,n)}r.push([s,(0,l.gt0)(n)?n:a])}return S(r)}function T(e){const t=(0,g.splitFirst)(e,":");return 2===t.length?t:void 0}function _(e){if((0,n.blank)(e))return;const t=(0,c.parseJSON)(e);return null==t?(0,u.fromEntries)([T(e)]):Array.isArray(t)?(0,u.fromEntries)(t.map(T)):(0,u.compactBlankValues)(t)}function E({a:e,b:t,field:i,desc:r,parser:s}){const n=s(e[i]),a=s(t[i]),o=y.Settings.exposureThresholdPct.valueOrDefault/100;return null==n||null==a||!0===(0,l.approximates)(n,a,o)?void 0:"Different "+r+": "+e[i]+" ≠ "+t[i]}function k(e){const t=(0,u.pick)(e,"LensSerialNumber");return null==e||(0,n.blank)(e.lensMake)||(0,n.blank)(e?.lensInfo)||(t.mli=`${e.lensMake.toLowerCase()}/${e.lensInfo}`),M(t)}t.Tag2SynonymGroup=(0,r.lazy)(()=>{const e=new Map;for(const t of b){const i=t[0];for(const r of t)e.set(r,i)}return e}),t.Tag2Synonyms=(0,r.lazy)(()=>{const e=new Map;for(const t of b)for(const i of t)e.set(i,t);return e}),t.zeroesRe=/^[\s0]*1?$/},12788(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isExifUnset=a,t.toExifDefined=function(e){return a(e)?void 0:e};const r=i(22573),s=i(54993),n=/undefined|null|none|n\/a|unknown/i;function a(e){return null==e||(0,r.blank)(e)||n.test((0,s.toS)(e))}},80495(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractExposureSettings=function(e){const t={focalLength:e.FocalLength,iso:(0,u.firstNonZero)(e.ISO,e.ISOSpeed,e.SonyISO),aperture:(0,u.firstNonZero)(e.FNumber,e.Fnumber,e.ApertureValue,e.Aperture,e.SonyFNumber),shutterSpeed:(0,s.firstNotBlank)((0,o.toS)(e.ExposureTime),(0,o.toS)(e.ShutterSpeed),(0,o.toS)(e.ShutterSpeedValue),(0,o.toS)(e.SonyExposureTime))};return c().debug("extracted from "+e.FileName,{exposureSettings:t}),(0,a.reqValuedOrElse)(t)},t.exposureTimeToFloat=function(e){if((0,n.gt0)(e))return e;const[t,i]=(0,o.toS)(e).split("/").map(e=>(0,n.toInt)(e));return(0,n.gt0)(t)&&(0,n.gt0)(i)?t/i:void 0},t.focalLengthToInt=function(e){const t=(0,n.toFloat)(e);return(0,n.gt0)(t)?Math.round(t):void 0};const r=i(19851),s=i(22573),n=i(31586),a=i(68708),o=i(54993),l=i(50213),u=i(97352),c=(0,r.lazy)(()=>(0,l.mkLogger)("tags.ExposureSettings"))},88840(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtTypes=void 0;const r=i(50989);t.ExtTypes=(0,r.strEnum)("Sharp","HEIF","RawImage","Video","Sidecar","Media","Exif","SupportedByCurrentBrowser","SupportedByOldBrowser")},14036(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CurrentBrowserMimetypes=t.OldBrowserMimetypes=t.AssetFileExts=t.MediaFileExts=t.AllFileExts=t.ExifFiletypes=t.MediaFiletypes=t.AllFiletypes=t.VideoFiletypes=t.ImageFiletypes=t.RawImageFiletypes=t.HeifFiletypes=t.SharpImageFiletypes=t.BrowserFiletypes=void 0,t.extMimetype=function(e){const t=(0,d.normalizeExt)(e);return null!=t?m()[t]:void 0},t.mimetypeExt=function(e){return t.AllFiletypes[(0,u.toS)(e).trim().toLowerCase()]?.[0]},t.getExtAliases=g,t.equivalentExts=function(e,t){const i=(0,d.normalizeExt)(e),r=(0,d.normalizeExt)(t);return null!=i&&null!=r&&(i===r||(g(i)?.includes(r)??!1))},t.extTypes=v,t.isExtType=b,t.mimeRootType=function(e){const t=v(e);return null==t?void 0:t.includes(f.ExtTypes.Sharp)||t.includes(f.ExtTypes.RawImage)?"image":t.includes(f.ExtTypes.Video)?"video":void 0},t.isHeifExt=w,t.isRawImageExt=S,t.isSharpExt=P,t.isVideoExt=M,t.isMediaExt=function(e){return b(e,f.ExtTypes.Media)},t.isExifExt=function(e){return b(e,f.ExtTypes.Exif)},t.isSupportedByCurrentBrowserExt=function(e){return b(e,f.ExtTypes.SupportedByCurrentBrowser)},t.isSupportedByOldBrowserExt=function(e){return b(e,f.ExtTypes.SupportedByOldBrowser)},t.stripExt=function(e,i){const r=(0,l.splitLast)(e,".");return null==i?(0,t.MediaFileExts)().has(r)?(0,l.stripSuffix)(e,`.${r}`):e:b(r,i)?e.slice(0,-(r.length+1)):e},t.getMediaCategory=function(e){return w(e)?"heic":M(e)?"video":S(e)?"raw":P(e)?"image":void 0};const r=i(40958),s=i(45599),n=i(96249),a=i(23838),o=i(68708),l=i(51926),u=i(54993),c=i(36638),d=i(32144),h=i(49047),f=i(88840);t.BrowserFiletypes={"application/javascript":["js"],"application/toml":["toml"],"application/manifest+json":["webmanifest"],"application/xml":["xml"],"image/vnd.microsoft.icon":["ico"],"font/ttf":["ttf"],"font/woff2":["woff2"],"text/css":["css"],"text/html":["html","htm"],"text/plain":["txt"],"text/x-scss":["scss"]},t.SharpImageFiletypes={"image/jpeg":h.JpegExts,"image/gif":["gif"],"image/png":["png"],"image/svg+xml":["svg"],"image/tiff":["tif","tiff"],"image/webp":["webp"]},t.HeifFiletypes={"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"]},t.RawImageFiletypes={"image/x-adobe-dng":["dng"],"image/x-canon-cr2":["cr2"],"image/x-canon-cr3":["cr3"],"image/x-canon-crw":["crw"],"image/x-epson-erf":["erf"],"image/x-fuji-raf":["raf"],"image/x-fujifilm-raf":["raf"],"image/x-kodak-dcr":["dcr"],"image/x-kodak-k25":["k25"],"image/x-kodak-kdc":["kdc"],"image/x-hasselblad-3fr":["3fr"],"image/x-mamiya-mef":["mef"],"image/x-minolta-mrw":["mrw"],"image/x-nikon-nef":["nef"],"image/x-nikon-nrw":["nrw"],"image/x-olympus-orf":["orf"],"image/x-panasonic-raw":["rwl"],"image/x-panasonic-rw2":["rw2"],"image/x-pentax-pef":["pef"],"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"]},t.ImageFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes},t.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"]},t.AllFiletypes={...t.BrowserFiletypes,...d.SidecarFiletypes,...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.MediaFiletypes={...t.SharpImageFiletypes,...t.HeifFiletypes,...t.RawImageFiletypes,...t.VideoFiletypes},t.ExifFiletypes={...t.MediaFiletypes,...d.SidecarFiletypes};const m=(0,s.defer)(()=>{const e={};for(const[i,r]of(0,o.entries)(t.AllFiletypes))for(const t of r)e[t]=i;return e}),p=(0,s.defer)(()=>{const e={};for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e[t]=i;return e});function g(e){return p()[(0,d.normalizeExt)(e)??""]}t.AllFileExts=(0,s.defer)(()=>{const e=new c.CaseInsensitiveSet;for(const i of(0,o.values)(t.AllFiletypes))for(const t of i)e.add(t);return e}),t.MediaFileExts=(0,s.defer)(()=>{const e=new c.CaseInsensitiveSet;for(const i of(0,o.values)(t.MediaFiletypes))for(const t of i)e.add(t);return e}),t.AssetFileExts=(0,s.defer)(()=>(0,r.uniq)((0,n.flatten)((0,o.values)(t.MediaFiletypes)))),t.OldBrowserMimetypes=["image/gif","image/jpeg","image/png"],t.CurrentBrowserMimetypes=[...t.OldBrowserMimetypes,"image/svg+xml","image/webp","video/mp4","video/webm"];const y=(0,s.defer)(()=>{const e=new a.MultiMap;for(const{exts:i,type:r}of[{exts:t.SharpImageFiletypes,type:f.ExtTypes.Sharp},{exts:t.HeifFiletypes,type:f.ExtTypes.HEIF},{exts:t.RawImageFiletypes,type:f.ExtTypes.RawImage},{exts:t.VideoFiletypes,type:f.ExtTypes.Video},{exts:d.SidecarFiletypes,type:f.ExtTypes.Sidecar},{exts:t.MediaFiletypes,type:f.ExtTypes.Media},{exts:t.ExifFiletypes,type:f.ExtTypes.Exif}])for(const t of(0,n.flatten)((0,o.values)(i)))e.add(t,r);for(const i of t.OldBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,f.ExtTypes.SupportedByOldBrowser);for(const i of t.CurrentBrowserMimetypes)for(const r of t.AllFiletypes[i]??[])e.add(r,f.ExtTypes.SupportedByCurrentBrowser);return e});function v(e){const t=(0,d.normalizeExt)(e);return null==t?void 0:y().get(t)}function b(e,t){return v(e)?.includes(t)??!1}function w(e){return b(e,f.ExtTypes.HEIF)}function S(e){return b(e,f.ExtTypes.RawImage)}function P(e){return b(e,f.ExtTypes.Sharp)}function M(e){return b(e,f.ExtTypes.Video)}},67083(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InferAction=t.Actions=void 0,t.mkHistoryRecords=k,t.mkHistoryRecord=D,t.tagsContainHistory=C,t.getInferredHistoricValues=function(e,i){if(null==e)return{};const s=(0,m.toA)(e);if((0,n.isEmpty)(s))return{};const l=(0,a.sortBy)(s.filter(e=>(0,v.startsWithIgnoreCase)(e.SoftwareAgent,"PhotoStructure")&&e.Action===t.Actions.infer),e=>(0,b.datedToMillis)((0,o.mapNotBlank)(e.When,e=>r.ExifDateTime.from(e)))??0),u={};for(const e of l){const t=e.Changed;if((0,o.notBlank)(t)){const r=A(e);(0,o.blank)(r.nativePath)||(0,S.eqlNameWithoutExt)(r.nativePath,i)?u[t]=r:I().debug("getInferredHistoricValues(): skipping mismatching filename (without file extension)",{ea:e,src:i})}}return u},t.valueFromResourceEvent=A,t.inferredToTags=x,t.ensureInferredHistoryRecords=async function(e,i,r){const s=k(t.Actions.infer,r),n=(T.Settings.writeInferredTagsToLibraryCopies.valueOrDefault?x(r):void 0)??{};return T.Settings.writeSourceTagToLibraryCopies.valueOrDefault&&(n.Source=e.nativePath),I().debug("ensureInferredHistoryRecords()",{sidecar:i,historyRecords:s,additionalTags:n}),F(i,s,n)},t.ensureHistoryRecords=F;const r=i(77988),s=i(19851),n=i(40958),a=i(76790),o=i(22573),l=i(50357),u=i(98553),c=i(31586),d=i(68708),h=i(50989),f=i(51926),m=i(59455),p=i(54993),g=i(72993),y=i(50213),v=i(81168),b=i(66649),w=i(17415),S=i(29882),P=i(95696),M=i(17217),T=i(28874),_=i(38148),E=i(80985);function k(e,t){return(0,d.entries)(t??{}).map(([t,i])=>D({action:e,key:t,value:i}))}function D({action:e,key:t,value:i,ts:s}){return{Action:e,Changed:(0,p.toS)(t).replace(/[#+]$/,""),Parameters:(0,u.stringify)(i),When:r.ExifDateTime.fromMillis(s??Date.now()),SoftwareAgent:(0,g.AppNameVersion)()}}t.Actions=(0,h.strEnum)("infer","set","add","delete"),t.InferAction="infer";const I=(0,s.lazy)(()=>(0,y.mkLogger)("tags.History"));function C(e,t){if(null==e||null==e.History||(0,f.isString)(e.History))return!1;const i=e.History;return Array.isArray(i)?i.some(t):t(i)}function A(e){if(null==e?.Parameters)return;if((0,c.isNumber)(e?.Parameters))return e.Parameters;const t=(0,p.toS)(e);return(0,o.blank)(t)?void 0:(0,u.parseJSON)(e.Parameters)}function x(e){if(null==e)return;const t={};for(const[i,r]of(0,d.entries)(e))(0,v.isFirstCharAZ)(i)&&(t[i]=r);"duration"in e&&(t.Duration=(0,c.toGt0f)(e.duration)),"title"in e&&(t.Title=e.title),"description"in e&&(t.Description=e.description),"rating"in e&&(t.Rating=e.rating),(0,d.assignFields)(t,e.capturedAt?.asExifTag());const i=(0,w.luxonTzOffsetToOffsetMinutes)(e.zone??e.capturedAt?.capturedAtZone,e.capturedAt?.toMillis());return null!=i&&(t.OffsetTime=i),t}async function F(e,i,r){if(null==e||(0,o.blank)(e))return void I().warn("ensureHistoryRecords(): no-op: empty path",{sidecar:e});const s=(0,M.toNativePath_)(e),a=await(0,_._readRawTags)(s),u=(0,m.toA)(i).filter(e=>{if(e.Action!==t.Actions.infer)return!0;const i=(0,d.pick)(e,"Changed","Parameters");return!C(a,e=>(0,l.eql)(i,(0,d.pick)(e,"Changed","Parameters")))}),c={};for(const[e,t]of(0,d.entries)(r??{}))(0,l.eql)(a?.[e],t)||(c[e]=t);if((0,n.isNotEmpty)(u)&&(c["History+"]=u),(0,d.isEmptyObj)(c))return void I().debug("ensureHistoryRecords(): no-op: nothing to write",{sidecar:e,historyRecords:i,newHistoryRecords:u,additionalTags:r,tagsToWrite:c});I().debug("ensureHistoryRecords(): write",{sidecar:e,tagsToWrite:c,historyRecords:i,additionalTags:r});const h=P.PosixFile.for(e);return await(0,E.overwriteTags_)(h,c),h.clearThisAndParent(),u}},3432(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.maybeInferTimezone=async function({pf:e,tags:t,skipSiblingInference:i,siblings:r}){return w().tap({msg:"maybeInferTimezone()",result:await S(e,t,i,r)})},t.zoneFromLatLon=P,t.inferTzOffsetMinutesFromFilename=M;const s=r(i(53705)),n=i(77988),a=i(40958),o=i(45599),l=i(50357),u=i(79842),c=i(66649),d=i(98725),h=i(17415),f=i(88600),m=i(73168),p=i(50213),g=i(28874),y=i(65162),v=i(72180),b=i(61424),w=(0,o.defer)(()=>(0,p.mkLogger)("tags.InferTimezone"));async function S(e,t,i,r){{const e=P(t);if(null!=e){const i={zone:e.name,zoneSource:"GPSLatitude/GPSLongitude"};return(0,l.eqlSubset)(i,t)?void 0:i}}if(!(0,h.isValidZone)(t.zone)||t.zoneSource===n.defaultVideosToUTC){if(g.Settings.inferTimezoneFromDatestamps.valueOrDefault)for(const e of(0,a.compactBlanks)([...g.Settings.capturedAtTagsPrimary.values,...g.Settings.capturedAtTagsSecondary.values,...g.Settings.capturedAtTagsTertiary.values,...g.Settings.capturedAtTagsFallback.values])){const i=t[e];if(i instanceof n.ExifDateTime&&(0,h.isValidZone)(i.zone)&&!(0,v.isUtcTagName)(e)&&"UTC"!==i.zone)return{zone:i.zone,zoneSource:"infer:tag."+e+".zone"}}if(!i){const i=M(e,t);if(null!=i)return i}if(!i){const t=await(0,b.nearestSiblingTzOffset)(e,r);if(null!=t)return{zone:t.zoneName,zoneSource:"infer:nearestSibling:"+t.base}}}}function P(e={}){const t=e.GPSLatitude,i=e.GPSLongitude;if(!(0,m.validLat)(t)||!(0,m.validLon)(i))return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i}});try{const e=(0,s.default)(t,i);return w().tap({msg:"zoneFromLatLon()",result:(0,n.normalizeZone)(e),meta:{lat:t,lon:i,zoneName:e}})}catch(e){return w().tap({msg:"zoneFromLatLon(): invalid lat/lon",result:void 0,meta:{lat:t,lon:i,error:e}})}}function M(e,t){const i=(0,d.parseDateTime)((0,y.bname)(e.name))?.setZone("UTC",{keepLocalTime:!0});if(null!=i&&(0,f.isValidDate)(i))for(const r of g.Settings.capturedAtTagsPrimary.values){const s=(0,u.toDated)(t[r]);if(null==s||!(0,f.isValidDate)(s))continue;const a=(0,c.datedToMillis)(s);if(null==a)continue;const o=Math.round((i.toMillis()-a)/6e4),l=(0,n.inferLikelyOffsetMinutes)(o),d=0===l?void 0:(0,n.normalizeZone)(l);if(null!=d)return w().tap({msg:"inferTzOffsetMinutesFromFilename("+e.name+")",result:{zone:d.name,zoneSource:"infer:filename (diff with "+r+")"},meta:{dt:(0,u.datedToISO)(s),rawTzoffsetMinutes:o,normalizedOffsetMinutes:l}})}}},28630(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readJsonSidecar=async function(e,t){const i=await e.readJson("info");return null==i?void 0:(0,u.compactValues)({Title:(0,n.toNotBlank)(i.title),Description:(0,n.toNotBlank)(i.description),GPSLatitude:(0,d.first)([i.geoData?.latitude,i.geoDataExif?.latitude],e=>(0,h.validLat)(e)?e:void 0),GPSLongitude:(0,d.first)([i.geoData?.longitude,i.geoDataExif?.longitude],e=>(0,h.validLon)(e)?e:void 0),GPSAltitude:(0,d.first)([i.geoData?.altitude,i.geoDataExif?.altitude],e=>(0,l.isNumber)(e)?e:void 0),favorited:(0,o.map)(i.favorited,a.isTrue),peopleNames:(0,s.mapNotEmpty)([...(0,c.toA)(i.people),...(0,c.toA)(i.person)],e=>(0,s.compactBlanks)(e.map(e=>e.name))),creationTime:p(i.creationTime,t),modificationTime:p(i.modificationTime,t),photoTakenTime:p(i.photoTakenTime,t),imageViews:(0,l.mapInt)(i.imageViews,e=>e),googlePhotosOrigin:!0})};const r=i(77988),s=i(40958),n=i(22573),a=i(38639),o=i(55835),l=i(31586),u=i(68708),c=i(59455),d=i(48884),h=i(73168),f=i(98725),m=new RegExp(r.TimezoneOffsetRE.source+"$");function p(e,t){if(null==e)return;const i=(0,l.toInt)(e?.timestamp);if((0,l.isNumber)(i)){const s=function(e){if(null==e)return;const t=m.exec(e),i=(0,r.parseTimezoneOffsetMatch)(t);return null!=i?(0,r.normalizeZone)(i.offsetMinutes):void 0}(e?.formatted)??(0,r.normalizeZone)(t),n=r.ExifDateTime.fromMillis(1e3*i,{rawValue:e.formatted,zone:s??r.UnsetZone});if(!0===n?.isValid)return n}return(0,f.parseDated)({input:e.formatted,defaultZone:t})}},68268(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordReparentingStrategies=void 0;const r=i(50989);t.KeywordReparentingStrategies=(0,r.strEnum)("move","copy","retain")},97573(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.delimRe=void 0,t.keywordToPath=function(e){const t=v();return(0,a.compactBlanks)(null==t?[e]:e.split(t))},t.splitKeyword=b,t.splitKeywords=w,t.parseCategories=M,t.isKeywordStruct=T,t.parseKeywordStruct=_,t.rawTagKeywords=function(e){const t=[];if(null!=e){const i=[...g.Settings.keywordTags.values];if(i.includes("Categories")){(0,h.remove)(i,"Categories");const r=M(e.Categories);null!=r&&t.push(...r)}for(const r of i){const i=(0,c.pluckDeep)(e,r)?.value;(0,o.blank)(i)||(T(i)?t.push(..._(i)):t.push(...Array.isArray(i)?i:w(i)))}}return y().tap({msg:"rawTagKeywords()",result:(0,a.compactBlankish)((0,a.uniq)(t)),meta:{t:null==e?void 0:(0,c.pick)(e,...g.Settings.keywordTags.values)}})};const r=i(77988),s=i(66150),n=i(19851),a=i(40958),o=i(22573),l=i(41400),u=i(96249),c=i(68708),d=i(59455),h=i(48884),f=i(50213),m=i(68852),p=i(81168),g=i(28874),y=(0,n.lazy)(()=>(0,f.mkLogger)("tags.KeywordTags")),v=(0,n.lazy)(()=>(0,o.mapNotBlank)(g.Settings.keywordPathSeparators.valueOrDefault,e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g")));function b(e){const i=(0,t.delimRe)();return null==i?[e]:(0,a.compactBlanks)(e.split(i))}function w(e){return null==e||e instanceof r.BinaryField?[]:(0,a.compactBlanks)(Array.isArray(e)?(0,u.flatten)(e.map(w)):b(e))}function S(e){return null==e?[]:(0,p.isString)(e)?(0,o.blank)(e)?[]:[[e]]:(0,u.flatten)((0,d.toA)(e.Category).map(S).map(t=>t.map(t=>(0,a.compact)([e._,...t]))))}(0,l.later)(()=>{g.Settings.keywordPathSeparators.watchLater(()=>v.unset())}),t.delimRe=(0,n.lazy)(()=>(0,o.mapNotBlank)(g.Settings.keywordDelimiters.valueOrDefault,e=>new RegExp(`[${(0,m.escapeRegExp)(e)}]+`,"g"))),g.Settings.keywordDelimiters.watchLater(()=>t.delimRe.unset());const P=/^\(?none\)?$/i;function M(e){if(!(0,o.blank)(e)&&null==P.exec(e))try{const t=new s.XMLParser({textNodeName:"_",parseTagValue:!1}).parse(e);return(0,u.flatten)((0,d.toA)(t?.Categories?.Category).map(S))}catch(t){return void y().warn("parseCategories() failed:",{error:t,s:e})}}function T(e){return Array.isArray(e)&&e.every(T)||null!=e&&(0,p.isString)(e.Keyword)&&(null==e.Children||Array.isArray(e.Children)&&e.Children.every(T))}function _(e){if(null==e)return[];if(Array.isArray(e)&&e.every(T))return(0,h.flatMap)(e,_);if((0,o.blank)(e.Keyword))return[];const t=(0,d.toA)(e.Children);return(0,a.isEmpty)(t)?[[e.Keyword]]:(0,h.flatMap)(t,_).map(t=>[e.Keyword,...t])}},15912(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractLensMakeModel=function(e){const t=(0,f.make)(e.LensMake),i=(0,f.make)(e.Make),r=[],o=(0,c.first)([e.LensInfo,e.DNGLensInfo,e.LensSpec,e.LensModel,e.LensID],w),u=(0,s.uniq)([e.LensModel,e.LensID,e.LensSpec,e.LensInfo,e.LensType,e.LensType2,e.LensType3,e.Lens]);m().debug("extractLensMakeModel",{lensMake:t,lensInfo:o,lensModels:u});for(const e of u){{const t=g.exec(e)?.groups;null!=t&&r.push({lensMake:"Zeiss",lensModel:`Batis ${t.mm}mm F${t.f} ${t.etc.trim()}`.trim(),lensInfo:`${t.mm}mm f/${t.f}`})}if(null==w(e))continue;(0,n.notBlank)(t)&&r.push({lensMake:t,lensModel:e,lensInfo:o});const a=e.toLowerCase();for(const[t,i]of(0,l.entries)(p))a.includes(t)&&r.push({lensMake:i,lensModel:e,lensInfo:o});for(const i of(0,s.compactBlanks)([t,...h.Settings.lensMakes.values]))e.toLowerCase().includes(i.toLowerCase())&&r.push({lensMake:i,lensModel:e,lensInfo:o});a.startsWith("vr ")&&"Nikon"===i&&r.push({lensMake:"Nikon",lensModel:e,lensInfo:o})}for(const e of r){const t=p[e.lensMake.toLowerCase()];e.lensMake=t??e.lensMake,e.lensModel=S(e.lensModel.replace(new RegExp("\\b"+e.lensMake+"\\b","i"),"")),e.lensInfo=(0,a.map)(e.lensInfo,S)}return(0,c.greatestBy)(r,e=>[null==e.lensModel.match(/\bor\b/i),e.lensModel.length])},t.justLengthAndAperture=w,t.cleanBogusPrecision=S,t.normalizeLensModel=function(e){return S(e).replace(/(\d) - (\d)/g,(e,t,i)=>`${t}-${i}`).replace(/(\d)\s+mm\b/,(e,t)=>t+"mm").replace(/\s+f\/?(\d)/i,(e,t)=>" f/"+t)};const r=i(19851),s=i(40958),n=i(22573),a=i(55835),o=i(31586),l=i(68708),u=i(54993),c=i(48884),d=i(50213),h=i(28874),f=i(30748),m=(0,r.lazy)(()=>(0,d.mkLogger)("tags.LensMakeModel")),p={nikkor:"Nikon","m.zuiko":"Olympus",zuiko:"Olympus"},g=/^zeiss batis (?<f>[\d.]+)\/(?<mm>[\d.]+)(?<etc>.*)/i;function y(e){return null!=e&&null==e.match(/^0+$/)}const v=/([\d. -]+)\s?mm\b/i,b=/\bf\/?([\d.-]+)/i;function w(e){if("string"!=typeof e)return;if((0,n.blank)(e)||(0,u.toS)(e).toLowerCase().includes("unknown"))return;e=e.replace(/\s+/g," ").trim();const t=v.exec(e)?.[1].replace(/\s/g,""),i=b.exec(e)?.[1];return y(t)&&y(i)?S(`${t}mm f/${i}`):void 0}function S(e,t=3){return e.replace(/\d+\.\d+/g,e=>(0,a.mapOr)((0,o.toFloat)(e),e=>String((0,o.sigFigs)(e,t)),e)).replace(/\s+/g," ").trim()}},30748(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.companyCased=m,t.extractMakeAndModel=function(e){if(null==e)return{};const t=v(e.Make)??w(e.Software)??w(e.CreatorTool)??function(e){return y.test((0,o.toS)(e.HandlerDescription))||y.test((0,o.toS)(e.CompressorName))?"GoPro":void 0}(e),i=P(t,(0,d.toExifDefined)(e.Model)??(0,d.toExifDefined)(e.CameraModel));return(0,a.compactValues)({Make:t,Model:i})??{}},t.make=v,t.makeFromSoftware=w,t.model=P,t.makeModel=function(e){const t=v(e.Make);return{Make:t,Model:P(t,e.Model)}};const r=i(19851),s=i(22573),n=i(55835),a=i(68708),o=i(54993),l=i(68852),u=i(81168),c=i(56946),d=i(12788);function h(e,t,i=""){const r=e.replace(t,i);return r===e?e:h(r,t,i)}const f=new Map(["BenQ","GoPro","HTC","LG","NEC","OnePlus","Sony","TrueHDR"].map(e=>[e.toLowerCase(),e]));function m(e){const t=e.trim(),i=f.get(t.toLowerCase());return null!=i?i:t.length<4?t:t.toLowerCase().replace(/(?:^|\s|-)\S/g,e=>e.toUpperCase())}class p{ignorables=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","solutions","system","technologies","technology","techwin"].join("|");ignorableSep="[\\s\\.,_-]*";IgnorableMakePatterns=new 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+|SM-G90/,"Galaxy S5"],[/^SM-G870A/,"Galaxy S5 Active"],[/^SM-A30\S+/,"Galaxy A3"],[/^SM-A530/,"Galaxy A8"],[/^SM-A700\S+/,"Galaxy A7"],[/^SM-A730/,"Galaxy A8+"],[/^SM-G920\S+/,"Galaxy S6"],[/^SM-G925\S+/,"Galaxy S6 Edge"],[/^SM-G928/,"Galaxy S6 Edge+"],[/^SM-G930\S+/,"Galaxy S7"],[/^SM-G935\S+/,"Galaxy S7 Edge"],[/^SM-G950/,"Galaxy S8"],[/^SM-G955/,"Galaxy S8+"],[/^SM-G960/,"Galaxy S9"],[/^SM-G965/,"Galaxy S9+"],[/^SM-G970/,"Galaxy S10e"],[/^SM-G973|SM-G977|SC-03|SCV41/,"Galaxy S10"],[/^SM-G975|SC-04|SC-05|SCV42/,"Galaxy S10+"],[/^SM-G98[01]/,"Galaxy S20"],[/^SM-G98[56]/,"Galaxy S20+"],[/^SM-G988/,"Galaxy S20 Ultra"],[/^SM-J510\S+/,"Galaxy J5"],[/^SM-N900/,"Galaxy Note 3"],[/^SM-N910/,"Galaxy Note 4"],[/^SM-N920/,"Galaxy Note 5"],[/^SM-N930/,"Galaxy Note 7"],[/^SM-N950/,"Galaxy Note 8"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-G991/,"Galaxy S21"],[/^SM-G996/,"Galaxy S21+"],[/^SM-G998/,"Galaxy S21 Ultra"],[/^SM-S901/,"Galaxy S22"],[/^SM-S906/,"Galaxy S22+"],[/^SM-S908/,"Galaxy S22 Ultra"],[/^SM-S911/,"Galaxy S23"],[/^SM-S916/,"Galaxy S23+"],[/^SM-S918/,"Galaxy S23 Ultra"],[/^SM-A245/,"Galaxy A24 4G"],[/^SM-E146B/,"Galaxy F14"],[/^SM-F711/,"Galaxy Z Flip 3"],[/^SM-F721/,"Galaxy Z Flip 4"],[/^SM-F936/,"Galaxy Z Fold 4"],[/^SM-E546B/,"Galaxy F54"],[/^SM-X700|SM-X706/,"Galaxy Tab S8"],[/^SM-X800|SM-X806/,"Galaxy Tab S8+"],[/^SM-X900|SM-X906/,"Galaxy Tab S8 Ultra"],[/SM-T509/,"Galaxy Tab A7"]];lgPatterns=[[/LG-D80[0-35]|LS98|VS98|L-01F/,"G2"],[/D85|F400|LS990|US990|VS985/,"G3"],[/H81\d|F500|LS991|US991|VS986/,"G4"],[/H850|H858|VS987|H820|LS992|H830|US992|H860N/,"G5"],[/H87[0-3]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]];onePlusPatterns=[[/A0001/,"One"],[/A100\d/,"X"],[/A20\d\d/,"2"],[/A30\d\d/,"3(T)"],[/A40\d\d/,"4"],[/A500\d/,"5"],[/A501\d/,"5T"],[/A600\d/,"6"],[/A601\d/,"6T"],[/GM1900|GM1901|GM1903/,"7"],[/GM1910|GM1911|GM1913|GM1915|GM1917/,"7 Pro"],[/HD1900|HD1901|HD1903|HD1905|HD1907/,"7T"],[/HD1910|HD1911|HD1913/,"7T Pro"],[/HD1925/,"7T Pro 5G"],[/IN2010|IN2011|IN2013|IN2015|IN2017|IN2019/,"8"],[/IN2020|IN2021|IN2023|IN2025/,"8 Pro"],[/LE2115|LE2113|LE2111/,"9"],[/LE2121|LE2125|LE2123|LE2120/,"9 Pro"],[/LE2101/,"9r"],[/CPH2389/,"Nord N300"],[/CPH2415|CPH2413|CPH2417/,"10T"],[/NE2210|NE2211|NE2213|NE2215|NE2217/,"10 Pro"],[/PGP110/,"Ace Pro"],[/PHB110|CPH2449|CPH2447|CPH2451/,"11"]];CommonNamesByMake={Samsung:this.samsungPatterns,LG:this.lgPatterns,OnePlus:this.onePlusPatterns}}const g=(0,r.lazy)(()=>new p),y=/\bgopro\b/i;function v(e){if((0,d.isExifUnset)(e))return;let t=(0,u.stripQuotes)(e);return/Hewlett[- ]Packard/i.test(t)?"HP":(t=h(t,g().IgnorableMakePatterns),t=t.replace(/\s+app on Apple iDevice$/i,""),t=t.replace(/\bLGE\b/,"LG"),t=t.replace(/\bEastman Kodak\b/i,"Kodak"),t=m(t),t=t.replace(/^OM$/i,"OM System"),t)}const b={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 w(e){if(!(0,s.blank)(e))for(const[t,i]of(0,a.entries)(b))if(i.test(e))return t}const S=/<\s*(\S[^,/]+)[,/]/;function P(e,t){if((0,d.isExifUnset)(e)||(0,d.isExifUnset)(t))return;let i=(0,u.stripQuotes)(t);if("Samsung"===e){const e=S.exec(i);null!=e&&(i=e[1].trim())}const r=(0,n.map)(g().CommonNamesByMake[e],e=>e.find(([e])=>null!=i.match(e)));if(null!=r)return r[1].trim();if(i=i.replace(new RegExp(`^${(0,l.escapeRegExp)(e)}\\s+`,"i"),""),"Sony"===e){i=i.replace(/^(?:DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/7CL?/i,"7c");const e=/M(\d+)$/.exec(i);null!=e&&(i=i.slice(0,e.index)+" "+(0,c.intToRoman)(e[1]))}if("Kodak"===e&&(i=i.replace(/Kodak|digital|science|zoom|camera/gi,"").replace(/\s+/g," ")),"Olympus"!==e&&"OM System"!==e||(i=(0,n.mapOr)(/^(.+?\d)mark(i.+)$/i.exec(i),e=>`${e[1]} Mark ${e[2]}`,()=>i)),"Panasonic"===e&&(i=i.replace(/^(?:DC|DMC)-(.{2,})$/i,"$1")),"Motorola"===e&&(i=i.replace(/DROID/i,"Droid ")),"Canon"===e){i=i.replace(/\bDIGITAL\b/i,"").trim().replace(/EOS\s+REBEL/i,"EOS Rebel");const e=i.match(/^EOS R(\d+)\s*m(\d+)$/i);null!=e&&(i=`EOS R${e[1]} Mark ${(0,c.intToRoman)(e[2])}`)}for(const e of g().IgnorableModelPatterns)i=h(i,e).trim();return null!=e.match(/^HP|Hewlett.Packard$/i)&&null!=i.match(/^hp\b/i)&&(i=i.slice(2).trim()),i}},38010(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MergedTags=void 0,t.isBaseRevision=T,t.isPrimitiveRevision=_,t.isSetRevision=function(e){return["add","delete"].includes(e?.op)&&T(e)},t.resourceEventToRevision=function(e){if(null==e||!(0,f.toS)(e.SoftwareAgent).startsWith((0,m.AppName)()))return M().tap({msg:"resourceEventToRevision() invalid",result:void 0,meta:{resourceEvent:e}});const t=e.Changed;if((0,a.blank)(t))return M().tap({msg:"resourceEventToRevision() missing Changed field name",result:void 0,meta:{resourceEvent:e}});const i=(0,c.pick)((0,a.mapNotBlank)(e.Parameters,d.parseJSON)??{},"newValue","priorValue");if((0,c.isEmptyObj)(i))return M().tap({msg:"resourceEventToRevision() missing Parameter fields",result:void 0,meta:{resourceEvent:e}});const r=(0,v.datedToMillis)((0,b.parseDated)({input:e.When}));return null==r?M().tap({msg:"resourceEventToRevision() missing createdAt (When)",result:void 0,meta:{resourceEvent:e}}):(0,a.blank)(e.Action)?M().tap({msg:"resourceEventToRevision() missing op (Action)",result:void 0,meta:{resourceEvent:e}}):M().tap({msg:"resourceEventToRevision()",result:{createdAt:r,field:t,op:"assign"===e.Action?void 0:e.Action,...i},meta:{resourceEvent:e}})},t.revisionToResourceEvent=function(e){return{Action:e.op??"assign",Changed:e.field,InstanceID:(0,l.map)(e.id,f.toS),Parameters:(0,y.stringifySorted)((0,c.pick)(e,"newValue","priorValue")),SoftwareAgent:(0,m.AppNameVersion)(),When:r.ExifDateTime.fromMillis(e.createdAt??Date.now())}};const r=i(77988),s=i(40958),n=i(76790),a=i(22573),o=i(45599),l=i(55835),u=i(31586),c=i(68708),d=i(67478),h=i(59455),f=i(54993),m=i(72993),p=i(19851),g=i(50213),y=i(84885),v=i(66649),b=i(98725),w=i(17217),S=i(16287),P=i(40538),M=(0,p.lazy)(()=>(0,g.mkLogger)("tags.MergedTags"));function T(e){return(0,u.isNumber)(e?.createdAt)&&(0,a.notBlank)(e?.field)}function _(e){return null==e?.op&&T(e)}t.MergedTags=class{name;logger;constructor(e){this.name=e,this.logger=(0,g.mkLogger)(`MergedTags(${e})`)}revisions=[];tags=[];addRevision(...e){this.revisions.push(...e)}sortedTags=(0,o.defer)(()=>(0,n.sortBy)((0,s.uniqBy)(this.tags,e=>e.SourceFile),e=>[!e.sourceIsPrimary,-e.sourceModifiedTime]));async addFile(e,t){const i=(0,w.toNativePath)(e);if((0,a.blank)(i))return void this.logger.warn("No SourceFile for "+e);const r=await(0,P.readTags)(e);null!=r?this.addTag({...r,SourceFile:i,sourceIsPrimary:t,sourceModifiedTime:await(0,S.mtimeMs)(i)}):this.logger.warn("Failed to read tags from "+e)}addTag(e){(0,a.blank)(e.SourceFile)?this.logger.warn("No SourceFile for tag",{name:this.name}):null!=e.sourceIsPrimary?null!=e.sourceModifiedTime?(this.sortedTags.reset(),this.tags.push(e)):this.logger.warn("No sourceModifiedTime for tag",{nativePath:e.SourceFile}):this.logger.warn("No sourceIsPrimary for tag",{nativePath:e.SourceFile})}get(e){const t=(0,n.sortBy)(this.revisions.filter(t=>t.field===e),e=>e.createdAt),i=this.sortedTags().find(t=>null!=t[e]);let r=i?.[e];const o=[];if(null!=r&&(0,a.mapNotBlank)(i?.SourceFile,e=>o.push(e)),t.every(_)&&this.tags.every(t=>!Array.isArray(t[e]))){for(const i of t)null!=r&&r!==i.priorValue&&r!==i.newValue?this.logger.info("get("+e+"): skipping revision because expected prior or new value didn't match current value",{name:this.name,revision:i}):(r=i.newValue,o.push(`Revision@${i.createdAt}`));return null==r?void 0:{value:r,source:o}}{const e=(0,h.toA)(r);for(const i of t)if("add"===i.op&&null!=i.newValue)o.push(`Revision@${i.createdAt}`),(0,s.pushUniq)(e,...(0,h.toA)(i.newValue));else if("delete"===i.op&&null!=i.priorValue){o.push(`Revision@${i.createdAt}`);for(const t of(0,h.toA)(i.priorValue))(0,s.remove)(e,t)}return{value:e,source:o}}}}},16170(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NonStandardVideoMimeTypes=void 0,t.isMimeTypeSupportedByBrowser=function(e,t=""){return((0,n.isChrome)(t)||(0,n.isFirefox)(t)?u.CurrentBrowserMimetypes:u.OldBrowserMimetypes).includes((0,a.toS)(e))},t.isImageMimeType=function(e){return(0,a.toS)(e).startsWith("image/")},t.isVideoMimeType=h,t.normalizeMimetype=f,t.isSharpMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.SharpImageFiletypes},t.isLibrawMimeType=function(e){return!(0,r.blank)(e)&&f(e)in u.RawImageFiletypes},t.isFileMimeTypeIncluded=async function(e,t){return m(await(0,c.readMimeType)(e),t)},t.isAssetFileMimeType=async function(e){const t=await(0,c.readMimeType)(e);return!(0,r.blank)(t)&&(h(t)?await(0,l.isVideoSupported)():(0,s.isHeifMimeType)(t)?await(0,o.isHeifSupported)():t in u.MediaFiletypes)},t.isMimeTypeIncluded=m;const r=i(22573),s=i(29825),n=i(2322),a=i(54993),o=i(277),l=i(66106),u=i(14036),c=i(54979),d={"video/m2ts":"video/mp2t","video/avi":"video/x-msvideo","video/vnd.avi":"video/x-msvideo","video/msvideo":"video/x-msvideo"};function h(e){return(0,r.notBlank)(e)&&(e.startsWith("video/")||t.NonStandardVideoMimeTypes.includes(e))}function f(e){const t=(0,a.toS)(e).toLowerCase();return d[t]??t}function m(e,t){if(null==e)return!1;for(const i of t)if(i.includes("*")){if(null!=new RegExp("^"+i.replace(/\*/g,".*")+"$","i").exec(e))return!0}else if(i.toLowerCase()===e)return!0;return!1}t.NonStandardVideoMimeTypes=["application/mp4","application/ogg"]},61208(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagFormats=void 0;const r=i(50989);t.NameTagFormats=(0,r.strEnum)("as-is","family/given","family/fullname")},99023(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NameTagOrders=void 0;const r=i(50989);t.NameTagOrders=(0,r.strEnum)("givenFirst","surnameFirst")},66039(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseName=_,t.renderNameTag=function(e){if((0,a.blank)(e))return[];const t=g.Settings.tagNamesFormatter.valueOrDefault,i="family/given"===t;if("family/fullname"===t||i){const t=_(e);if(null==t)return[];{const e=k([t.modifier,t.lifespan]),r=k(t.givenNames);return(0,s.compactBlanks)((0,s.notEmptyOr)(t.familyNames,[g.Settings.tagNamesDefaultFamily.valueOrDefault])).map(t=>[u.TagRoots.Who,t,i?k([r,e]):D(t,r,e)])}}return[[u.TagRoots.Who,e.trim()]]};const r=i(19851),s=i(40958),n=i(76790),a=i(22573),o=i(50357),l=i(55835),u=i(75020),c=i(59455),d=i(36638),h=i(50213),f=i(68852),m=i(81168),p=i(70417),g=i(28874),y=(0,r.lazy)(()=>(0,h.mkLogger)("tags.Names"));let v,b=[];function w(e){return(0,f.matchQuotes)((0,f.escapeRegExp)(e))}const S=/(\(\s*\d+\s*-\s*[\d?]{0,4}\s*\)?)/,P=/([,\s]+(?:jr\.?|junior|sr\.?|senior|[iv]+\.?))$/i,M=/\b([A-Z‘’']+[-A-Z‘’']{2})\b/,T=/^[()[\]/.\-_]+$/;function _(e){if((0,a.blank)(e))return;let t=e.replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").trim();const i=(0,l.map)((0,m.spliceCapture)(t,S),e=>(t=e.unmatched.trim(),e.captured.replace(/\s+/g,""))),r=(0,l.map)((0,m.spliceCapture)(t,P),e=>(t=e.unmatched.trim(),e.captured.trim())),u=[],h=[],T=[];for(const e of g.Settings.tagNamesGiven.values.map(e=>new RegExp("\\b("+w(e)+")\\b","i"))){const i=(0,m.spliceCapture)(t,e);null!=i&&(u.push(i.captured),t=i.unmatched.trim())}for(const e of function(){const e=(0,s.compactBlanks)(g.Settings.tagNamesGivenSurrounds.values);for(const t of e)2!==t.length&&y().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map(e=>new RegExp(`(${(0,f.escapeRegExp)(e.charAt(0))}\\s*[^${(0,f.escapeRegExp)(e.charAt(0))}]+\\s*${(0,f.escapeRegExp)(e.charAt(1))})`,"i"))}()){let i;do{i=(0,m.spliceCapture)(t,e),null!=i&&(h.push(i.captured),t=i.unmatched.trim())}while(null!=i)}let _;function k(e){(null==_||_>e.matchedIndex)&&(_=(0,p.min)([_,e.matchedIndex]))}if(g.Settings.tagNamesCapitalizedAsFamily.valueOrDefault&&"givenFirst"===g.Settings.tagNamesOrder.valueOrDefault){let e;do{e=(0,m.spliceCapture)(t,M),null!=e&&(k(e),T.push(e.captured),t=e.unmatched.trim())}while(null!=e)}for(const e of function(){const e=(0,s.compactBlanks)(g.Settings.tagNamesFamilySurrounds.values);for(const t of e)2!==t.length&&y().warn("Settings.tagNamesFamilySurrounds has an invalid value:",t);return e.map(e=>new RegExp(`${(0,f.escapeRegExp)(e.charAt(0))}\\s*([^${(0,f.escapeRegExp)(e.charAt(0))}]*)\\s*${(0,f.escapeRegExp)(e.charAt(1))}`,"i"))}()){let i;do{i=(0,m.spliceCapture)(t,e),null!=i&&(k(i),T.push(i.captured),t=i.unmatched.trim())}while(null!=i)}if(g.Settings.tagNamesLexical.valueOrDefault){const e=t.indexOf(",");e>=0&&(_=void 0,T.push(t.substring(0,e).trim()),u.push(t.substring(e+1).trim()),t="")}for(const e of g.Settings.tagNamesSurnames.values.map(e=>new RegExp("\\b("+w(e)+")\\b","i"))){const i=(0,m.spliceCapture)(t,e);null!=i&&(k(i),T.push(i.captured),t=i.unmatched.trim())}for(const e of(0,c.toA)((0,s.mapNotEmpty)((0,s.compactBlanks)(g.Settings.tagNamesSurnamePrefixes.values),e=>(0,n.sortBy)(e,e=>-e.length).map(e=>new RegExp(`\\b(${w(e)}\\s+\\S+)`,"i"))))){const i=(0,m.spliceCapture)(t,e);null!=i&&(k(i),T.push(i.captured),t=i.unmatched.trim())}if(null!=_&&_>0&&t.length>_){const e="givenFirst"===g.Settings.tagNamesOrder.valueOrDefault;(0,s.mapNotEmpty)((0,s.compactBlanks)(t.slice(_).split(/\s+/)),i=>{e?T.push(...i):u.push(...i),t=t.slice(0,_)})}const D=(0,s.compactBlanks)(t.split(/\s+/)),I=u.length,C=T.length;if(D.length>0)if(0===I&&C>0)u.push(...D);else if(0===C&&I>0&&1===D.length)T.push(...D);else if(1===D.length){const e="givenFirst"===g.Settings.tagNamesOrder.valueOrDefault;null==_||e?u.push(...D):T.push(...D)}else{const e="givenFirst"===g.Settings.tagNamesOrder.valueOrDefault;T.push(e?D.pop():D.shift()),u.push(...D)}const A=function(){const e=g.Settings.tagNamesSurnames.values;return(0,o.eql)(e,b)||(b=e,v=0===e.length?void 0:new d.CaseInsensitiveSet(e)),v}();if(null!=A)for(let e=0;e<T.length;e++){const t=A.lookup(T[e]);null!=t&&(T[e]=t)}return{givenNames:E([...u,...h]),modifier:r,lifespan:i,familyNames:E(T),minFamilyNameIndex:_}}function E(e){return(0,s.uniq)((0,s.compactBlanks)(e).filter(e=>null==T.exec(e)))}function k(e){let t="";for(const i of(0,s.compactBlanks)(e))t+=i.startsWith(",")?i:" "+i;return t.trim()}function D(e,t,i){return k("givenFirst"===g.Settings.tagNamesOrder.valueOrDefault?[t,e,i]:[e,t,i])}},95141(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractRotation=function(e){if(null!=e)return(0,n.isHeifFamilyMimeType)(e.MIMEType)||(0,c.isVideoMimeType)(e.MIMEType)?m(e.Rotation)??(0,o.normalizeRotation)(e.Rotation):m(e.Orientation)??(0,o.normalizeRotation)(e.Rotation)},t.orientationRequiresMirroring=function(e){return[2,4,5,7].includes(e)||(0,l.toS)(e).startsWith("Mirror")},t.orientationToRotation=m,t.rotationToExifOrientation=function(e){return p.get((0,o.normalizeRotation)(e))},t.rotationToWriteTag=function(e,t){if((0,n.isHeifFamilyMimeType)(t)){const t=(0,o.normalizeRotation)(e);if(null==t)return;const i=p.get(t)??null;return 0===t?{"Orientation#":i,Rotation:"Horizontal (normal)"}:{"Orientation#":i,Rotation:t}}const i=(0,o.normalizeRotation)(e);return null==i?void 0:{"Orientation#":p.get(i),Rotation:i}};const r=i(22573),s=i(45599),n=i(29825),a=i(31586),o=i(21605),l=i(54993),u=i(50213),c=i(16170),d=(0,s.defer)(()=>(0,u.mkLogger)("tags.Orientation")),h=new Map([[1,0],[6,90],[3,180],[8,270]]),f={"Horizontal (normal)":0,"Horizontal (Normal)":0,"Rotate 90 CW":90,"Rotate 180":180,"Rotate 270 CW":270};function m(e){return d().tap({msg:"orientationToRotation",result:(0,r.blank)(e)?void 0:(0,a.isNumber)(e)?h.get(e)??(0,o.normalizeRotation)(e):f[(0,l.toS)(e)],meta:{orientation:e}})}const p=new Map([[0,1],[90,6],[180,3],[270,8]])},7330(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clampRating=a,t.extractRating=o,t.extractLiked=function(e){const t=o(e);return null==t?void 0:t>=n.Settings.likeRating.valueOrDefault};const r=i(55835),s=i(31586),n=i(28874);function a(e){const t=(0,s.toInt)(e);return null==t?void 0:(0,s.clamp)(-1,5,t)}function o(e){return a(e?.Rating)??(0,s.mapNumeric)((0,s.toInt)(e?.RatingPercent),e=>Math.ceil(5*e/100))??(0,r.map)(e?.favorited,e=>!0===e?n.Settings.likeRating.valueOrDefault:void 0)}},54979(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mimetypeCache=void 0,t.readMimeType_=v,t.readMimeType=async function(e){return v(e).catch(t=>{y().warn("Failed to read mimetype from "+e,{nativePath:(0,c.toNativePath_)(e),error:t})})};const r=i(19851),s=i(22573),n=i(45599),a=i(55835),o=i(88561),l=i(78923),u=i(95696),c=i(17217),d=i(50213),h=i(63870),f=i(16170),m=i(35332),p=i(38148),g=i(40538),y=(0,n.defer)(()=>(0,d.mkLogger)("tags.ReadMimeType"));async function v(e){if((0,s.blank)(e))return;const i=u.PosixFile.forMaybe(e);return null!=i?(0,t.mimetypeCache)().getOrSet(i.nativePath,async()=>(0,a.map)((0,p.rawTagsCache)().peek(i.nativePath)?.MIMEType??(0,m.rawMergedTagsCache)().peek(i.nativePath)?.MIMEType??(0,g.tagsCache)().peek(i.nativePath)?.MIMEType??(await(0,l.readFileType_)(i.nativePath))?.mime,f.normalizeMimetype)):void 0}t.mimetypeCache=(0,r.lazy)(()=>new o.FileCache({name:"tags.mimetype",maxSize:2048,timeoutMs:(0,h.commandTimeoutMs)()}))},35332(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._readRawMergedTags=t.rawMergedTagsCache=void 0,t.readRawMergedTags=function(e){return(0,t._readRawMergedTags)((0,h.toNativePath_)(e))};const r=i(40958),s=i(22573),n=i(45599),a=i(68708),o=i(59455),l=i(56519),u=i(66649),c=i(88561),d=i(95696),h=i(17217),f=i(19851),m=i(50213),p=i(70417),g=i(7282),y=i(88158),v=i(28874),b=i(79136),w=i(40296),S=i(65211),P=i(67083),M=i(28630),T=i(16170),_=i(38148),E=i(79915),k=(0,n.defer)(()=>(0,m.mkLogger)("tags.ReadRawMergedTags"));t.rawMergedTagsCache=(0,f.lazy)(()=>new c.FileCache({name:"exif.rawMerged",maxSize:512,timeoutMs:v.Settings.taskTimeoutMs.valueOrDefault})),t._readRawMergedTags=(0,b.shim)({name:"exif.readRawMergedTags",cache:t.rawMergedTagsCache,impl:async function(e){const t=d.PosixFile.for(e);if(!await t.isNonEmptyFile(128))return(0,_.rawTagsCache)().delete(t.nativePath),void k().debug("readRawTags("+t+"): invalid file, returning null.");const i=await(0,_._readRawTags)(t.nativePath);if(t.isSidecar())return i;if(null==i)return void k().debug("readRawMergedTags(): no file tags, returning null.",{pf:t});const n=(0,s.mapNotBlank)(i.MIMEType,T.normalizeMimetype);if((0,s.blank)(n))return void k().debug("readRawMergedTags(): no MIMEType, returning null.",{pf:t});k().trace("readRawTags()",{pf:t,pickedFileTags:(0,a.pick)(i,"zone","zoneSource",...v.Settings.capturedAtTagsPrimary.values,...v.Settings.capturedAtTagsSecondary.values,...v.Settings.capturedAtTagsTertiary.values,...v.Settings.capturedAtTagsFallback.values)});const c=[[t,i]];for(const e of await t.existingDirectorySidecars())c.push([e,(0,_._readRawTags)(e.nativePath)]);for(const e of await t.jsonSidecars())c.push([e,(0,M.readJsonSidecar)(e,i.zone)]);for(const e of await t.existingExifSidecars())c.push([e,(0,_._readRawTags)(e.nativePath)]);const h={original:{},imageDataHash:(0,s.toNotBlank)(i.ImageDataHash),MIMEType:n},f=await(0,l.sortByAsync)({iter:c,f:async([e,t])=>{const i=await t;return(0,p.max)([(0,u.datedToMillis)(i?.MetadataDate),(0,u.datedToMillis)(i?.FileModifyDate),await e.mtimeMs()])}}),m=[];for(const[e,i]of f){if(null==i)continue;const s=await i;if(null==s)continue;const n=e===t?s:(0,a.omit)(s,...E.IgnoredSidecarFields);(0,r.isNotEmpty)((0,a.values)(n))?(e!==t&&(h.sidecars??=[],h.sidecars.push(e.base)),m.push(...(0,o.toA)(s.History)),(0,y.assignNullishFields)(h.original,(0,a.pick)(h,...(0,a.keys)(n))),(0,a.assignFields)(h,n),k().debug("_readRawTags() sidecar had values",{sidecar:e.base})):k().debug("_readRawTags() sidecar was empty",{sidecar:e.base})}h.inferred=(0,P.getInferredHistoricValues)(m,e),(0,y.assignNullishFields)(h,h.inferred);for(const[e,t]of(0,a.entries)(h.original??{}))h[e]===t&&delete h.original?.[e];return(0,g.isTest)()&&(0,S.addInstanceIds)(h),k().debug("readRawTags() final",{pf:t,inferred:h.inferred,internalFields:(0,w.pickInternalFields)(h),pickedResult:(0,a.pick)(h,"MIMEType","ImageWidth","ImageHeight","Orientation","Rotation","zone","zoneSource",...v.Settings.capturedAtTagsPrimary.values,...v.Settings.capturedAtTagsSecondary.values,...v.Settings.capturedAtTagsTertiary.values,...v.Settings.capturedAtTagsFallback.values)}),h},toKey:e=>e})},38148(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t._readRawTags=t.rawTagsCache=void 0,t.readRotation=async function(e){return(0,C.extractRotation)(await R(e))},t.__readRawTags=O,t.readRawTags=R,t.readRawField_=async function(e,t){const i=await(0,h.time)({name:"exif.readRaw",meta:{tagName:t},p:(0,k.exiftool)().readRaw((0,g.toNativePath_)(e),{readArgs:["-"+t]})});return(0,M.pluckCaseInsensitive)(i,t)},t.coerceTagTypes=L;const s=r(i(76760)),n=i(40958),a=i(22573),o=i(45599),l=i(31586),u=i(68708),c=i(54993),d=i(5916),h=i(56038),f=i(98247),m=i(88561),p=i(95696),g=i(17217),y=i(6327),v=i(19851),b=i(50213),w=i(23624),S=i(7282),P=i(97352),M=i(88158),T=i(28874),_=i(79136),E=i(65211),k=i(47783),D=i(14036),I=i(16170),C=i(95141),A=(0,o.defer)(()=>(0,b.mkLogger)("tags.ReadRawTags")),x=new Set(["VideoFrameRate"]),F=(0,d.lazyAsync)({desc:"TagMetadata.json type sets",async later(){try{const e=i(85721),t=new Set,r=new Set;for(const[i,s]of Object.entries(e))s.typed&&(x.has(i)||"number"===s.type?r.add(i):"string"===s.type&&t.add(i));return{stringFields:t,numberFields:r}}catch(e){return void A().error("tagTypeSets(): Failed to read TagMetadata.json",{error:e})}}});async function O(e){const i=p.PosixFile.forMaybe(e);if(null==i||!await i.isNonEmptyFile(0))return A().debug("_readRawTags(): !isNonEmptyFile(), returning null.",{file:e}),void(0,t.rawTagsCache)().delete(e);A().debug("_readRawTags() not cached, reading now.",{file:e});const r=[...(0,D.isVideoExt)(s.default.extname(e))?[]:["-fast"]],o=await(0,k.exiftool)().read(i.nativePath,{readArgs:r}).catch(t=>{A().warn("ExifTool failed to read",{file:e,error:t})});if(null==o)return void A().warn("_readRawTags() exiftool returned null/undefined",{file:e});if(o.MIMEType=(0,a.mapNotBlank)(o.MIMEType,I.normalizeMimetype),o.GPSDateTime??=(0,f.concatDateTime)(o.GPSDateStamp,o.GPSTimeStamp),o.Rotation=(0,C.orientationToRotation)(o.Rotation),(0,a.notBlank)(o.ImageDataHash)&&(o.ImageDataHash=(0,w.hex2b64)(o.ImageDataHash).replace(/=+$/,"")),(0,I.isVideoMimeType)(o.MIMEType)&&await(0,y.isFFprobeAvailable)()){const t=await(0,y.ffprobe_)(e);A().debug("readRawTags()",{file:e,ffprobe:t,tags:(0,u.pick)(o,"Rotation","ImageWidth","ImageHeight")}),(0,u.assignFields)(o,t)}await L(o);const l=(0,n.uniq)((0,n.compactBlanks)([o.Error,...o.errors??[],o.Warning].map(c.toS)));return(0,n.isNotEmpty)(l)&&(o.problems=l),(0,S.isTest)()&&(0,E.addInstanceIds)(o),o}function R(e){return(0,t._readRawTags)((0,g.toNativePath_)(e))}async function L(e){const t=await F();if(null==t)return A().warn("coerceTagTypes(): Missing tag type sets, skipping type coercion."),e;const{stringFields:i,numberFields:r}=t;for(const t of(0,u.keys)(e)){const s=e[t];if("string"==typeof s){if("0000:00:00"===s||"0000:00:00 00:00:00"===s)delete e[t];else if(r.has(t)){const i=x.has(t)?(0,P.extractFraction)(s):(0,l.toFloat)(s);null!=i?e[t]=i:x.has(t)&&delete e[t]}}else"number"==typeof s&&i.has(t)&&(e[t]=String(s))}return e}t.rawTagsCache=(0,v.lazy)(()=>new m.FileCache({name:"exif.raw",maxSize:512,timeoutMs:T.Settings.taskTimeoutMs.valueOrDefault,ttlMs:T.Settings.metadataCacheMs.valueOrDefault})),t._readRawTags=(0,_.shim)({name:"exif.readRawTags",cache:t.rawTagsCache,impl:O,toKey:e=>e})},40538(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._readTags=t.tagsCache=void 0,t.readTags=function(e){return null==e?void 0:(0,t._readTags)((0,m.toNativePath_)(e))},t.parseTags=B;const r=i(77988),s=i(22573),n=i(45599),a=i(55835),o=i(31586),l=i(68708),u=i(66649),c=i(21330),d=i(98725),h=i(88561),f=i(95696),m=i(17217),p=i(73168),g=i(19851),y=i(50213),v=i(7282),b=i(28874),w=i(79136),S=i(81168),P=i(65211),M=i(28544),T=i(43207),_=i(72180),E=i(75767),k=i(12788),D=i(80495),I=i(3432),C=i(15912),A=i(30748),x=i(16170),F=i(7330),O=i(35332),R=i(1078),L=i(61424),N=i(8791),j=(0,n.defer)(()=>(0,y.mkLogger)("tags.ReadTags"));async function B(e,t){return null==t?void 0:async function(e,t){try{const i=e.nativePath,n=(0,s.mapNotBlank)(t.MIMEType,x.normalizeMimetype);if((0,s.blank)(n))return void j().debug("No mimetype",{file:i});const h={...t.inferred??{},...t};if(h.inferred??={},h.original??={},b.Settings.fuzzyDateParsing.valueOrDefault)for(const e of[...b.Settings.capturedAtTagsPrimary.values,...b.Settings.capturedAtTagsSecondary.values,...b.Settings.capturedAtTagsTertiary.values,...b.Settings.capturedAtTagsFallback.values]){const t=h[e];if((0,S.isString)(t)){const r=(0,d.parseDated)({input:t,includeDate:!0,includeFuzzyDate:!0});null!=r&&(j().debug("parseTags() fuzzy date",{file:i,fuzzy:r,k:e,v:t}),h[e]=r)}}const f=!await(0,L.canInferForDir)(e.parent()),m=f?void 0:await(0,L.nearestSiblings)(e),g=await(0,I.maybeInferTimezone)({pf:e,tags:h,skipSiblingInference:f,siblings:m});if(j().debug("parseTags()",{file:i,tzMeta:g,skipSiblingInference:f}),null!=g?.zone){const e=h.zoneSource!==r.defaultVideosToUTC&&void 0;for(const t of[...b.Settings.capturedAtTagsPrimary.values,...b.Settings.capturedAtTagsSecondary.values,...b.Settings.capturedAtTagsTertiary.values,...b.Settings.capturedAtTagsFallback.values])if(!(0,_.isUtcTagName)(t)){const i=h[t];i instanceof r.ExifDateTime&&(h[t]=(0,c.setZone)(i,g.zone,{keepLocalTime:e})??i)}(0,l.assignUndefinedFields)(h.original,h,"zone","zoneSource"),(0,l.assignFields)(h,g)}const y=f?(0,A.extractMakeAndModel)(h):await(0,L.inferMakeAndModel)({pf:e,tags:h,siblings:m});y.Make!==(0,A.make)(h.Make)&&(h.original.Make=h.Make,h.inferred.Make=y.Make),y.Model!==(0,A.model)(y.Make,h.Model)&&(h.original.Model=h.Model,h.inferred.Model=y.Model),!(0,s.blank)(b.Settings.defaultCopyright.valueOrDefault)&&(0,k.isExifUnset)(h.Copyright)&&(h.Copyright=b.Settings.defaultCopyright.valueOrDefault);const w=V(e,h);let T;try{T=await(0,M.extractCapturedAt_)(e,h,f,m)}catch(t){return void j().info("No capturedAt for "+e,{error:t})}!f&&T.isInferred&&(h.inferred.capturedAt=T);const D=H(e,h),C=await(0,R.extractSizeInfoFromFile)(e,h);if(null==C)return void j().info("No size info",{file:i});const F={...y,mimetype:n,capturedAt:T,exposureSettings:D,...U(e,h),make:y.Make,model:y.Model,...w,cameraId:(0,E.cameraIdFromTags)(h),imageId:(0,E.imageIdFromTags)(h),lensId:(0,E.lensIdFromLensInfo)({...w,...(0,l.pick)(h,"LensSerialNumber")}),...C,duration:q(e,h),zone:h.zone,rating:W(e,h),metadataDate:(0,a.map)((0,u.datedToMillis)(t.MetadataDate),Math.round),geohash:(0,p.geohashNumericShort)(t.GPSLatitude,t.GPSLongitude),durationMs:$(e,h),fps:(0,o.mapFloat)(t.VideoFrameRate,e=>(0,o.sigFigs)(e,4))};(0,v.isTest)()&&(0,P.addInstanceIds)(F);const O={...h,...F};return j().debug("parsedTags",{file:i,skipInference:f,...F,inferred:h.inferred,original:h.original,pickedResult:(0,l.pick)(O,"capturedAt","zone","zoneSource","Make","Model","imageDataHash","UserComment")}),O}catch(t){return void j().warn("parseTags() failed",{file:e.nativePath,error:t})}}(e,t)}function z(e){return(t,i)=>{try{return e(i)}catch(i){return void j().warn("Extractor "+e.name+" failed for "+t,{error:i})}}}t.tagsCache=(0,g.lazy)(()=>new h.FileCache({name:"exif.parsed",maxSize:512,timeoutMs:b.Settings.taskTimeoutMs.valueOrDefault})),t._readTags=(0,w.shim)({name:"exif.readTags",impl:async e=>{const t=f.PosixFile.for(e);return B(t,await(0,O.readRawMergedTags)(t))},cache:t.tagsCache,toKey:e=>e});const V=z(C.extractLensMakeModel),H=z(D.extractExposureSettings),U=z(N.extractTitleDescription),W=z(F.extractRating),q=z(T.extractDurationSec),$=z(T.extractDurationMs)},79915(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnoredSidecarFields=t.AllowedUncommonSuffixRe=void 0,t.isSidecarOf=w,t.existingSidecars=async function(e){return t=e,(0,h.isSidecarExt)(t.ext)||(0,d.isInInternalDir)(t)?[]:(0,c.sortByAsync)({iter:e.siblings(t=>w(e,t)),f:e=>e.mtimeMs()});var t},t.defaultSidecarExt=function(){return(0,u.ensurePrefix)(p.Settings.defaultSidecarType.valueOrDefault,".")},t.sidecarEql=async function(e,t){return await(0,l.eqlAsync)(e.sha(),t.sha())||await(0,l.eqlAsync)(S(e),S(t))},t.cachedTags=function(e){return(0,v.tagsCache)().get((0,m.toNativePath_)(e))};const r=i(76760),s=i(40958),n=i(22573),a=i(55835),o=i(68708),l=i(23467),u=i(81168),c=i(56519),d=i(49776),h=i(32144),f=i(4001),m=i(17217),p=i(28874),g=i(14036),y=i(38148),v=i(40538);function b(e,t,{ignoreCase:i}){return i?(0,u.equalsIgnoreCase)(e,t,{normalize:!0}):e===t}function w(e,i){if(!(0,h.isSidecarExt)(i.ext)||i.base.startsWith("."))return!1;const a=(0,h.isJsonExt)(i.ext),o=a||p.Settings.matchSidecarsCaseInsensitively.valueOrDefault;if(b(e.base,i.name,{ignoreCase:o}))return!0;if(b(e.name,i.name,{ignoreCase:o}))return!0;if((0,h.normalizeExt)(e)===(0,h.normalizeExt)(i.name)){const t=(0,r.parse)(i.name).name;if(b(e.name,t,{ignoreCase:o}))return!0}const l=a||p.Settings.matchSidecarsFuzzily.valueOrDefault;if(l)for(const t of(0,s.uniq)([e.base,e.name,(0,g.stripExt)(e.base)]))for(const e of(0,s.uniq)([i.base,i.name,(0,g.stripExt)(i.name)]))if(b((0,f.stripCopySuffixFromName)(t),(0,f.stripCopySuffixFromName)(e),{ignoreCase:l}))return!0;return a&&function(e,i){const r=(0,u.commonPrefixIgnoreCase)(e,i);if(r.length<8)return!1;function s(e){return(0,n.blank)(e)||null!=e.match(t.AllowedUncommonSuffixRe)}const a=s(e.slice(r.length)),o=s(i.slice(r.length));return a&&o}(e.name,i.name)}async function S(e){return(0,a.map)(await(0,y.readRawTags)(e),e=>(0,o.omit)(e,...t.IgnoredSidecarFields))}t.AllowedUncommonSuffixRe=/^((-edit(ed)?)|(-?\w{1,2})|(-?\(\d{1,2}\)))$/i,t.IgnoredSidecarFields=["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","errors","FileIndex2","FileInfoVersion","FileFormat","FileIndex","FileNumber","FileNumberMemory","FileNumberSequence"]},1078(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sizeInfoCache=void 0,t.extractSizeInfoFromFile=async function(e,i){if(null==e)return;const r=f.PosixFile.for(e);return(0,t.sizeInfoCache)().getOrSet(r.nativePath,()=>async function(e,t){if(null==e)return;const i=t?.MIMEType??await(0,v.readMimeType)(e);if(null!=i&&(0,g.isSharpMimeType)(i)){const t=await S(e,i);if(null!=t)return t}const r=null!=t&&(0,l.gt0)(t.ImageHeight)?t:await(0,b._readRawTags)(e.nativePath);if(null==r)return;const s=(0,y.extractRotation)(t)??(0,y.extractRotation)(r),n=(0,g.isLibrawMimeType)(r.MIMEType)?await(0,p.rawInfo)(e):void 0;return w().tap({msg:"_extractSizeInfoFromFile() from tags",result:P(r,s,n),meta:{nativePath:e.nativePath,pickedDefaultTags:(0,u.pick)(t,"ImageHeight","ImageWidth","MIMEType","Orientation","Rotation"),pickedTags:(0,u.pick)(r,"ImageHeight","ImageWidth","MIMEType","Orientation","Rotation"),rotation:s,raw:n}})}(r,i))},t.extractSizeInfoFromSharp=S,t.extractSizeInfoFromTags=P;const s=r(i(9288)),n=i(19851),a=i(42659),o=i(33374),l=i(31586),u=i(68708),c=i(21605),d=i(50213),h=i(88561),f=i(95696),m=i(86580),p=i(34943),g=i(16170),y=i(95141),v=i(54979),b=i(38148),w=(0,n.lazy)(()=>(0,d.mkLogger)("tags.SizeInfo"));async function S(e,t){try{const i=await(0,s.default)(e.nativePath).metadata();return w().tap({msg:"extractSizeInfoFromSharp()",result:P({MIMEType:t,ImageHeight:i.height,ImageWidth:i.width,Orientation:i.orientation}),meta:(0,u.omit)(i,"exif","icc","iptc","xmp")})}catch(t){return void w().info("extractSizeInfoFromSharp() failed, falling back to ExifTool",{error:String(t),nativePath:e.nativePath})}}function P(e,t,i){t=(0,c.normalizeRotation)(t)??(0,y.extractRotation)(e)??0;const r=[i?.ImageSize,{width:e?.ImageWidth,height:e?.ImageHeight}].find(o.isDimensions);if(null==r)return w().tap({msg:"extractSizeInfoFromTags("+e?.FileName+") (undefined fileDimensions)",result:void 0,meta:{mimetype:e?.MIMEType,_rawInfo:i,fileDimensions:r}});const s=(0,o.maybeDimSwap)(r,t);return w().tap({msg:"extractSizeInfoFromTags("+e?.FileName+")",result:{ImageHeight:s.height,ImageWidth:s.width,aspectRatio:(0,m.aspectRatio)(s),dimensions:s,rotation:t,fileDimensions:r,orientation:e?.Orientation},meta:{mimetype:e?.MIMEType,_rawInfo:i}})}t.sizeInfoCache=(0,n.lazy)(()=>new h.FileCache({name:"tags.sizeInfo",maxSize:256,timeoutMs:a.minuteMs}))},61424(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.canInferForDir=F,t.inferMakeAndModel=async function({pf:e,tags:t,siblings:i}){const r=(0,I.extractMakeAndModel)(t);if(null!=r.Make&&null!=r.Model)return r;if(!await F(e.parent()))return x().debug("inferMakeAndModel("+e+"): cannot infer for this directory",e.parent()),r;const s=N(i??await j(e));x().debug("inferMakeAndModel("+e+"): looking at nearby siblings",s.map(e=>e.base));for(const t of s){const i=(0,I.extractMakeAndModel)(await(0,A.readRawTags)(t));if((0,d.definedAndNotEql)(i.Make,r.Make))x().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Make)",{mm:r,fromSibling:i});else if((0,d.definedAndNotEql)(i.Model,r.Model))x().debug("inferMakeAndModel("+e+"): skipping sibling (mismatching Model)",{mm:r,fromSibling:i});else if(null!=i.Make&&null!=i.Model)return x().tap({msg:"inferMakeAndModel("+e+")",level:M.LogLevels.info,result:i,meta:{sibling:t.base}})}return r},t.inferCapturedAtFromSiblings=async function(e,t){if(!await F(e.parent()))return;const i=await L(e,t);return null!=i&&(0,y.closeTo)(i.before.date,i.after.date,2*o.dayMs)?(0,l.map)(p.DateInterval.for((0,y.toExifDateTime)(i.before.date,(0,b.getZoneName)(i.before.date)),(0,y.toExifDateTime)(i.after.date,(0,b.getZoneName)(i.after.date)),i.index,i.slots),e=>({date:e,src:`before:${i.before.capturedAtSrc},after:${i.after.capturedAtSrc}`})):void 0},t.beforeAfterCapturedAt=L,t.zipSibling=N,t.nearestSiblings=j,t.nearestSiblingTzOffset=async function(e,t){if(!await F(e.parent()))return;const i=N(t??await j(e)),s=await async function(e){const t=[];for(const i of e){const e=await(0,C.readRawMergedTags)(i);null!=e&&(0,a.notBlank)(e.zone)&&e.zoneSource!==r.defaultVideosToUTC&&t.push({zoneName:e.zone,path:i.nativePath,base:i.base,src:e.zoneSource??"tags.zone"})}if(0===t.length)return void x().debug("majorityZoneName(): no zone name found",{arr:e});const i=new Map;for(const e of t)i.set(e.zoneName,(i.get(e.zoneName)??0)+1);let s="",n=0;for(const[e,t]of i)t>n&&(s=e,n=t);if(n/t.length<2/3)return void x().debug("majorityZoneName(): siblings disagree on timezone",{counts:Object.fromEntries(i),totalWithZone:t.length});const o=t.find(e=>e.zoneName===s);return x().tap({msg:"majorityZoneName()",result:o,meta:{counts:Object.fromEntries(i),totalWithZone:t.length}})}(i);return x().tap({msg:"nearestSiblingTzOffset()",result:s,meta:{f:e,sibs:i.map(e=>e.base)}})},t.extractStatBnameTime=async function(e){const t=(0,E.bname)(e),i=(0,v.parseDated)({input:t});return null==i?void x().debug("extractStatBname(): no date in basename",{file:e.nativePath,input:t}):B({desc:"extractStatBname()",needle:i,f:e})},t.extractStatPathTime=async function(e){const t=(0,v.extractDateFromPath)(e.pathsForDateParsing());return null==t?void x().debug("extractStatPathTime(): no date in basename",{file:e.nativePath}):B({desc:"extractStatPathTime()",needle:t,f:e})};const r=i(77988),s=i(19851),n=i(40958),a=i(22573),o=i(42659),l=i(55835),u=i(59455),c=i(48884),d=i(23467),h=i(50213),f=i(96859),m=i(56038),p=i(24689),g=i(79842),y=i(21330),v=i(98725),b=i(93515),w=i(49776),S=i(88561),P=i(65238),M=i(57902),T=i(57414),_=i(28874),E=i(65162),k=i(28544),D=i(14036),I=i(30748),C=i(35332),A=i(38148),x=(0,s.lazy)(()=>(0,h.mkLogger)("tags.TagInference"));async function F(e){return(0,T.isSiblingInferenceEnabled)()?!0!==(0,w.isInInternalDir)(e)||(x().debug("canInferForDir("+e+"): disabled (PhotoStructure directory)"),!1):(x().debug("canInferForDir("+e+"): disabled: "+_.Settings.inferenceSiblingRadius.toEnvLine()),!1)}async function O(e){e=(0,u.toA)(e);for(let t=0;t<e.length;t++){const i=e[t],r=await(0,C.readRawMergedTags)(i),s=k.CapturedAt.fromFields((0,k.capturedAtFromTags)(r));if(null!=s)return{...s,index:t}}}const R=(0,s.lazy)(()=>new S.FileCache({name:"tags.beforeAfterCapturedAt"}));function L(e,t){return R().getOrSet(e.nativePath,async()=>{const i=t??await j(e),r=await O(i?.younger),s=await O(i?.older);return null==i||null==r||null==s?null:{before:r,after:s,index:r.index,slots:r.index+s.index+1}})}function N(e){return null==e?[]:(0,n.compact)((0,c.flatZip)((0,u.toA)(e.younger),(0,u.toA)(e.older)))}async function j(e,t=_.Settings.inferenceSiblingRadius.valueOrDefault){if(!await F(e.parent()))return;const i=e.parent().nativePath,r=await(0,m.time)({name:"tag.nearestSiblings",meta:{file:e},p:async()=>{const e=await(0,P.readdirSortedMaybe_)(i);return e?.filter(e=>e.isFile&&!e.basename.startsWith(".")&&(0,D.isMediaExt)(e.basename))}});if(null==r)return void x().info("nearestSiblings(): can't readdir parent, "+e.parent());const s=r.findIndex(t=>t.basename.toLowerCase()===e.base.toLowerCase());if(s<0)return void x().warn("nearestSiblings(): can't find self in siblings: "+e,{dirents:r.map(e=>e.basename)});const a=_.Settings.siblingInferenceBasenameCoeffPct.valueOrDefault/100,[o,l]=[r.slice(s-2*t,s),r.slice(s+1,s+1+2*t)],u=[],c=[];for(;(0,n.isNotEmpty)(o)&&u.length<t;){const t=o.pop(),i=e.sibling(t.basename);(0,f.diceCoeff)(e.name,i.name)>=a&&u.push(i)}for(;(0,n.isNotEmpty)(l)&&c.length<t;){const t=l.shift(),i=e.sibling(t.basename);(0,f.diceCoeff)(e.name,i.name)>=a&&c.push(i)}return x().tap({msg:"nearestSiblings()",level:"trace",result:{younger:u,older:c},meta:{f:e}})}async function B({desc:e,needle:t,f:i}){const r=await i.stat();if(null!=r){for(const i of["birthtime","mtime","ctime"]){const s=r[i];if((0,g.datedOverlap)({a:t,b:s}))return s.setMilliseconds(0),x().tap({msg:e+": overlap with "+i+" stat time",result:{src:i,date:s},meta:{needle:t,stat:r}})}return x().tap({msg:e+": no stat overlap",result:void 0,meta:{needle:t,stat:r}})}x().debug(e+": cannot stat "+i)}},42231(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagSepRe=t.TagSep=void 0,t.tagRefToS=f,t.tagPathToPathTag=function(e){return(0,c.ancestry)(m(e)).map((e,t)=>({tagPath:e,displayName:e[t].displayName}))},t.tagPathToStringArray=m,t.joinTagPath=p,t.joinedTagPathBasename=function(e){return(0,r.last)(g(e))},t.splitTagPath=g,t.normalizeTagPath=function(e){return p(g(e))},t.uniqTagPaths=function(e){return(0,r.uniqBy)((0,l.toA)(e),e=>(0,r.isEmpty)(e)?void 0:p(e))},t.tagPathEql=function(e,t){return null!=e&&null!=t&&y(e)===y(t)},t.tagDiff=function(e,t){const i=new Set((0,r.compact)(t).map(e=>y(e)));return(0,r.compact)(e).filter(e=>!i.has(y(e)))},t.tagPathsInclude=function(e,t){const i=y(e);return t.some(e=>i===y(e))},t.tagPathLeaf=v,t.leafIsExcluded=function(e,t){return(0,a.mapOr)(v(e),e=>(0,h.includesIgnoreCase)(t,e),()=>!1)},t.isTagPathDescendant=b,t.omitAncestorTags=function(e){if(!d.Settings.omitAncestorTags.valueOrDefault)return e;const t=[];for(const i of(0,s.sortBy)(e.filter(r.isNotEmpty),e=>-e.length))t.some(e=>b(i,e))||t.push(i);return(0,s.sortBy)(t,t=>e.indexOf(t))};const r=i(40958),s=i(76790),n=i(22573),a=i(55835),o=i(51926),l=i(59455),u=i(54993),c=i(48884),d=i(28874),h=i(81168);function f(e){return(0,u.toS)((0,o.isString)(e)?e:e?.name).normalize()}function m(e){return(0,r.compact)((0,l.toA)(e).map(f))}function p(e,i=t.TagSep){return m(e).map(e=>(0,o.replaceAll)(e,i,"")).join(i)+(i===t.TagSep?i:"")}function g(e,i=t.TagSep){return(0,u.toS)(e).split(i).filter(n.notBlank)}function y(e){return m(e).join(t.TagSep).toLowerCase()}function v(e){return(0,n.blank)(e)?void 0:Array.isArray(e)?f((0,r.last)(e)):(0,r.last)(g(e))}function b(e,t){if((0,r.isEmpty)(e)||(0,r.isEmpty)(t)||e.length>t.length)return!1;const i=m(t);return m(e).every((e,t)=>(0,h.equalsIgnoreCase)(e,i[t]))}t.TagSep=String.fromCharCode(31),t.TagSepRe=new RegExp("[/"+t.TagSep+"]","g")},8791(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractTitleDescription=function(e){const t=(0,r.uniq)([...o.ParsingSettings.omittedDescriptions.values,e.original?.Make,e.original?.Model,e.Model,e.Make,e.CameraID]).map(e=>(0,s.mapNotBlank)(e,e=>e.trim().toLowerCase().normalize())),i=(...i)=>{for(const r of i){const i=(0,a.toS)(e[r]).trim();if((0,s.notBlank)(i)&&!t.includes(i.toLowerCase().normalize()))return i}};return(0,n.compactValues)({title:i(...o.ParsingSettings.titleTags.values),description:i(...o.ParsingSettings.descriptionTags.values)})};const r=i(40958),s=i(22573),n=i(68708),a=i(54993),o=i(57414)},80985(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.moveOriginal=w,t.overwriteTags_=async function(e,t){try{await(0,u.time)({name:"exif.overwriteTags",meta:{src:e},p:async()=>{await(0,g.exiftool)().write(e.nativePath,t,{writeArgs:await S(e)}),e.clearThisAndParent(),(0,p.clearTagsCacheForDir)(e.dir)}})}catch(i){b().throw("failed to overwrite tags to "+e,{error:i,tags:t})}},t.deleteAllTags_=async function(e,t){await(0,u.time)({name:"exif.deleteAllTags",meta:{src:e},p:async()=>{const i=["-all="];e.$eql(t)?i.push("-overwrite_original"):i.push("-o",t.nativePath),await(0,g.exiftool)().write(e.nativePath,{},{writeArgs:i}),t.clear(),(0,p.clearTagsCacheForDir)(t.dir)}})},t.writeTagArgs=S,t.writeTagDest=P,t.writeTags_=function(e,t,i){const s=Date.now(),o=r.ExifDateTime.fromMillis(s).toExifString();return(0,u.time)({name:"exif.writeTags",meta:{src:e},p:async()=>{const r=new n.MultiMap;for(const[s,n]of(0,a.entries)(t)){const t=await P(e,s,i);r.add(t.nativePath,[s,n])}for(const[t,i]of r.entriesArray()){const r=d.PosixFile.for(t),s=(0,a.fromEntries)(i);s.MetadataDate=o,b().info("writeTags()",{file:e,dest:t,t:s}),await(0,g.exiftool)().write(r.nativePath,s,{writeArgs:await S(r)}),f.Settings.overwriteOriginal.valueOrDefault||await w(r),r.clearThisAndParent(),(0,p.clearTagsCacheForDir)(r.dir)}return{nowLocal:(0,c.datedToLocal)(s)}}})};const r=i(77988),s=i(45599),n=i(23838),a=i(68708),o=i(34666),l=i(12168),u=i(56038),c=i(89724),d=i(95696),h=i(50213),f=i(28874),m=i(81168),p=i(97069),g=i(47783),y=i(16170),v=i(54979),b=(0,s.defer)(()=>(0,h.mkLogger)("tags.WriteTags"));async function w(e,t="_original"){return e.sibling(e.base+t).saveIfNewOrDelete(e.name+t+e.ext)}async function S(e){const t=[];return f.Settings.overwriteOriginal.valueOrDefault&&t.push("-overwrite_original"),(0,o.gt)(await e.size(),2*l.GB)&&t.push("-api LargeFileSupport=1"),t}async function P(e,t,i){if((0,m.includesIgnoreCase)(f.Settings.sidecarTagBlocklist.values,(0,m.stripSuffix)(t,"#")))return b().tap({msg:"writeTagDest(): blocklisted tag, not writing to sidecar",result:e,meta:{src:e,tagName:t}});const r=i??await(0,v.readMimeType)(e),s=await e.sidecar(),n=(0,y.isImageMimeType)(r)&&f.Settings.writeMetadataToSidecarsIfImage.valueOrDefault,a=(0,y.isVideoMimeType)(r)&&f.Settings.writeMetadataToSidecarsIfVideo.valueOrDefault,o=f.Settings.writeMetadataToSidecarsIfSidecarExists.valueOrDefault&&await s.exists(),l=n||a||o;return b().tap({msg:"writeTagDest()",result:l?s:e,meta:{src:e,tagName:t,mimetype:r,writeMetadataToSidecarsIfImage:n,writeMetadataToSidecarsIfVideo:a,writeMetadataToSidecarsIfSidecarExists:o}})}},45200(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToUri=async function(e,t){return null==e||(0,s.blank)(e)?y().throw("empty nativePath passed to nativePathToUri()",{retriable:!1}):(0,p.nativePathToPslib)(e)??await(0,m.nativePathToPsfile)(e,t)??await(0,g.nativePathToPsnet)(e,t)??{nativePath:e,uri:h.URI.file(e)}},t.nativePathToUris=v,t.nativePathToUriStrings=async function(e,t){const i=await v(e,t);return(0,a.sortURIs)((0,r.uniq)((0,n.flatten)(i.map(f.uriEncodingVariants))))},t.uriToNativePath=b,t.uriToNativePath_=w,t.uriToNativePathAndMountpoint_=S,t.uriExists=async function(e){const t=await b(e);return null!=t&&await(0,c.exists)(t)},t.currentVolumeRoots=async function(){const e=[],t=[];for await(const i of(0,u.scannableVolumes)())t.push(i.mountPoint),e.push(i.uris[0]);return{uris:(0,r.uniq)(e),mountpoints:(0,r.uniq)(t)}};const r=i(40958),s=i(22573),n=i(96249),a=i(89937),o=i(19851),l=i(50213),u=i(34075),c=i(16287),d=i(85831),h=i(34238),f=i(87001),m=i(20237),p=i(5696),g=i(12228),y=(0,o.lazy)(()=>(0,l.mkLogger)("uri.FileURI"));async function v(e,t){return(0,r.compact)([(0,p.nativePathToPslib)(e)?.uri,(await(0,m.nativePathToPsfile)(e,t))?.uri,(await(0,g.nativePathToPsnet)(e,t))?.uri,h.URI.file(e)])}async function b(e){return w(e).catch(()=>{})}async function w(e){return(await S(e))?.nativePath}async function S(e){if((0,s.blank)(e))return;const t=function(e){try{return h.URI.isUri(e)?e:h.URI.parse(e,!0)}catch(t){return void y().warn("bad URI",{uri:e,error:t})}}(e);if(null!=t)switch(t.scheme){case"file":return{nativePath:t.fsPath};case a.PS_LOCAL_FILE_SCHEME:return await(0,m.psfileToNativePath_)(t);case a.PS_NETWORK_FILESYSTEM_SCHEME:return await(0,g.psnetToNativePath_)({uri:t});case a.PS_LIBRARY_SCHEME:return(0,p.pslibToNativePath_)({uri:t});default:return y().throw(new d.InvalidURIError("unsupported URI: "+e))}}},85831(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidURIError=void 0,t.isInvalidURIError=function(e){return e instanceof i||e instanceof Error&&"InvalidURIError"===e.name};class i extends Error{name="InvalidURIError";retriable=!1;doNotSend=!0}t.InvalidURIError=i},34238(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URI=void 0,t.encodeURIComponentFast=S,t.uriToFsPath=M,t.percentDecode=k,t.toURI=function(e){return y.isUri(e)?e:y.parse(e)};const r=i(76760),s=i(53916),n=i(57975),a=i(57160),o=i(22573),l=i(51926),u=i(29652),c=i(43334),d=/^\w[\w+.-]*$/,h=/^\//,f=/^\/\//,m="",p="/",g=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class y{static isUri(e){return e instanceof y||null!=e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"function"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}scheme;authority;path;query;fragment;constructor(e,t,i,r,s,n=!1){"object"==typeof e?(this.scheme=e.scheme||m,this.authority=e.authority||m,this.path=e.path||m,this.query=(0,u.toURLSearchParams)(e.query??""),this.fragment=e.fragment||m):(this.scheme=function(e,t){return e||t?e:"file"}(e,n),this.authority=t??m,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==p&&(t=p+t):t=p}return t}(this.scheme,i??m),this.query=(0,u.toURLSearchParams)(r??""),this.fragment=s??m,function(e,t){if(!e.scheme&&!0===t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!d.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!h.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(f.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,n))}get fsPath(){return M(this)}get relativeFsPath(){const e=this.fsPath;return c.isWin?e:(0,l.stripPrefix)(e,"/")}with(e){if(null==e)return this;let{scheme:t,authority:i,path:r,query:s,fragment:n}=e;return void 0===t?t=this.scheme:null===t&&(t=m),void 0===i?i=this.authority:null===i&&(i=m),void 0===r?r=this.path:null===r&&(r=m),void 0===s?s=this.query:null===s&&(s=m),void 0===n?n=this.fragment:null===n&&(n=m),t===this.scheme&&i===this.authority&&r===this.path&&s===this.query&&n===this.fragment?this:new b(t,i,r,s,n)}static parse(e,t=!1){const i=g.exec(e);if(!i)return new b(m,m,m,m,m);const r=i[2]||m,s=k(i[4]||m),n=(i[5]||m).split("/").map(k).join("/"),a="psfile"===r&&n.startsWith("//")?n.slice(1):n,o=(0,u.toURLSearchParams)(i[7]),l=k(i[9]||m);return new b(r,s,a,o,l,t)}static file(e){let t=m;if(c.isWin&&(e=e.replace(/\\/g,p)),e[0]===p&&e[1]===p){const i=e.indexOf(p,2);-1===i?(t=e.substring(2),e=p):(t=e.substring(2,i),e=e.substring(i)||p)}return new b("file",t,e,m,m)}static from(e){return new b(e.scheme,e.authority,e.path,e.query,e.fragment)}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPaths on URI without path");let i;return i=c.isWin&&"file"===e.scheme?y.file(r.win32.join(M(e),...t)).path:r.posix.join(e.path,...t),e.with({path:i})}isRootPath(){return null==this.path||this.path===p}get pathBase(){return(0,o.blank)(this.path)||this.isRootPath()?"":(0,s.basename)(this.path)}parent(){return this.isRootPath()?this:this.with({path:this.path.slice(0,this.path.lastIndexOf(p))})}join(...e){return this.with({path:(0,l.ensureSuffix)(this.path,p)+e.join(p)})}toString(e=!1){return T(this,e)}toJSON(){return this}[n.inspect.custom](){return this.toString()}}t.URI=y;const v=c.isWinPortable?1:void 0;class b extends y{_formatted=null;_fsPath=null;get fsPath(){return null==this._fsPath&&(this._fsPath=M(this)),this._fsPath}toString(e=!1){return e?T(this,!0):(null==this._formatted&&(this._formatted=T(this,!1)),this._formatted)}toJSON(){const e={};return null!=this._fsPath&&(e.fsPath=this._fsPath,e._sep=v),null!=this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),(0,o.mapNotBlank)(this.query,t=>e.query=t),this.fragment&&(e.fragment=this.fragment),e}}const w={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 S(e,t){let i,r=-1;for(let s=0;s<e.length;s++){const n=e.charCodeAt(s);if(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||45===n||46===n||95===n||126===n||t&&47===n)-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),void 0!==i&&(i+=e.charAt(s));else{void 0===i&&(i=e.slice(0,s));const t=w[n];void 0!==t?(-1!==r&&(i+=encodeURIComponent(e.substring(r,s)),r=-1),i+=t):-1===r&&(r=s)}}return-1!==r&&(i+=encodeURIComponent(e.substring(r))),void 0!==i?i:e}function P(e){let t;for(let i=0;i<e.length;i++){const r=e.charCodeAt(i);35===r||63===r?(void 0===t&&(t=e.slice(0,i)),t+=w[r]):void 0!==t&&(t+=e[i])}return void 0!==t?t:e}function M(e){let t;return t=e.authority&&e.path.length>1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?c.isWin?e.path[1].toUpperCase()+e.path.slice(2):e.path.slice(1):e.path,c.isWin&&(t=t.replace(/\//g,"\\")),t}function T(e,t){const i=t?P:S;let r="";const{scheme:s,query:n,fragment:a}=e;let{authority:l,path:u}=e;if(s&&(r+=s,r+=":"),(l||"file"===s)&&(r+=p,r+=p),l){let e=l.indexOf("@");if(-1!==e){const t=l.slice(0,e);l=l.slice(e+1),e=t.indexOf(":"),-1===e?r+=i(t,!1):(r+=i(t.slice(0,e),!1),r+=":",r+=i(t.slice(e+1),!1)),r+="@"}e=l.indexOf(":"),-1===e?r+=i(l,!1):(r+=i(l.slice(0,e),!1),r+=l.slice(e))}if(u){const e=/^\/?[a-z]:/i.exec(u);null!=e&&(r+=e[0].toUpperCase(),u=u.slice(e[0].length)),r+=i(u,!0)}return(0,o.mapNotBlank)(n,e=>r+="?"+e),a&&(r+="#",r+=t?a:S(a,!1)),r}function _(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.slice(0,3)+_(e.slice(3)):e}}const E=/(?:%[\dA-Z][\dA-Z])+/gi;function k(e){return e.startsWith("xn--")?(0,a.toUnicode)(e):e.match(E)?e.replace(E,e=>_(e)):e}},56625(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUriDeleted=async function(e){const t=(0,h.toURI)(e);if("file"===t.scheme)return m().tap({msg:"isUriDeleted(): file URI",result:await p((0,f.uriEncodingVariantURIs)(t).map(e=>({uri:e,f:u.PosixFile.for(e.fsPath)})))});if(t.scheme===n.PS_LIBRARY_SCHEME){const e=(0,a.libraryAssetDirPosixFiles)(),i=(0,f.uriEncodingVariantURIs)(t).flatMap(t=>e.map(e=>({uri:t,f:e.join(t.relativeFsPath)})));return m().tap({msg:"isUriDeleted(): library URI",result:await p(i)})}const i=await(0,o.volshaToMountPoints)(t.authority),r=i.filter(l.isNativePath);if(0===r.length)return m().tap({msg:"isUriDeleted(): no mount points found for authority",result:void 0,meta:{uri:t,mountPoints:i}});const s=r.map(e=>u.PosixFile.for(e)).flatMap(e=>(0,f.uriEncodingVariantURIs)(t).map(t=>({uri:t,f:u.PosixFile.for(e).join(t.relativeFsPath)})));return m().tap({msg:"isUriDeleted(): authority/volsha URI",result:await p(s)})};const r=i(76760),s=i(45599),n=i(89937),a=i(87290),o=i(34075),l=i(29882),u=i(95696),c=i(50213),d=i(81168),h=i(34238),f=i(87001),m=(0,s.defer)(()=>(0,c.mkLogger)("uri.UriDeleted"));async function p(e){for(const{uri:t,f:i}of e)if(await i.exists())return m().tap({msg:"isUriDeleted(): file exists",result:{result:!1,f:i,uri:t}});for(const{uri:t,f:i}of e){const e=await i.isDeleted((0,d.countChars)(t.fsPath,r.sep));if(null!=e)return m().tap({msg:"isUriDeleted(): file deletion check",result:{result:e,f:i,uri:t}})}const{uri:t,f:i}=e[0];return m().tap({msg:"isUriDeleted(): no checks succeeded, returning undefined",result:{result:void 0,f:i,uri:t}})}},28549(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractUriDirectory_=function(e){if((0,s.blank)(e))throw new Error("extractUriDirectory_: blank URI");const t=(0,n.toURI)(e);return t.with({path:(0,r.dirname)(t.path),query:null,fragment:null}).toString()},t.extractUriBasename_=function(e){if((0,s.blank)(e))throw new Error("extractUriBasename_: blank URI");return(0,r.basename)((0,n.toURI)(e).path)},t.extractUriAuthority_=function(e){if((0,s.blank)(e))throw new Error("extractUriAuthority_: blank URI");return(0,n.toURI)(e).authority};const r=i(53916),s=i(22573),n=i(34238)},87001(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUri=function(e){const t=(0,u.toS)(e).toLowerCase();return f.some(e=>t.startsWith(e))},t.normalizeURI=function(e){try{return h.URI.parse(e).toString()}catch(t){return m().warn("Failed to normalize invalid URI",{uri:e,error:t}),e}},t.uriEqlSync=g,t.uriIsEquivalent=async function(e,t){try{if(null==e||null==t)return!1;if((0,o.eql)(e,t)||g(e,t))return!0;const i=await(0,d.uriToNativePath)(e),s=await(0,d.uriToNativePath)(t);if(p(i,s))return!0;if(null!=i&&null!=s)try{const[e,t]=await Promise.all([(0,r.realpath)(i),(0,r.realpath)(s)]);return p(e,t)}catch{return!1}return!1}catch{return!1}},t.uriEncodingVariantURIs=y,t.stringEncodingVariants=function(e){return(0,n.uniq)([e,e.normalize("NFC"),e.normalize("NFD")])},t.uriEncodingVariants=function(e){return y(e).map(u.toS)};const r=i(51455),s=i(19851),n=i(40958),a=i(38639),o=i(50357),l=i(89937),u=i(54993),c=i(50213),d=i(45200),h=i(34238),f=["http:","https:","file:",l.PS_LOCAL_FILE_SCHEME,l.PS_NETWORK_FILESYSTEM_SCHEME].map(e=>e+"//"),m=(0,s.lazy)(()=>(0,c.mkLogger)("uri.UriNormalization"));function p(e,t){return null!=e&&null!=t&&(e===t||e.normalize()===t.normalize())}function g(e,t,i={}){try{if(null==e||null==t)return!1;const r=(0,h.toURI)(e),s=(0,h.toURI)(t);return r.scheme===s.scheme&&r.authority===s.authority&&p(r.path,s.path)&&(!(0,a.isTrue)(i.compareQuery)||(0,o.eql)(r.query,s.query))&&(!(0,a.isTrue)(i.compareFragment)||p(r.fragment,s.fragment))}catch{return!1}}function y(e){const t=(0,h.toURI)(e);return(0,n.uniqBy)([t,t.with({path:t.path.normalize("NFC")}),t.with({path:t.path.normalize("NFD")})],e=>e.toString())}},16817(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isUriPath=o,t.toUriPath=l,t.posixFileToUriPath=function(e,t){return l({nativePath:e.nativePath,volume:t})};const r=i(22573),s=i(68708),n=i(17217),a=i(45200);function o(e){return(0,s.isObject)(e)&&!(0,r.blank)(e.nativePath)&&!(0,r.blank)(e.uri)}async function l(e){if(o(e))return e;const t=(0,n.toNativePath)(e.nativePath);return(0,r.blank)(t)?void 0:(0,a.nativePathToUri)(t,e.volume)}},20237(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.psfileUri=function(e){const t=(0,a.toNotBlank)(e.path)??"/",i=(0,a.toNotBlank)(e.volsha)??(0,v.volsha)(e.volumeUUID);return(null==i?y.URI.file(t):y.URI.from({scheme:u.PS_LOCAL_FILE_SCHEME,authority:i,path:t})).toString()},t.nativePathToPsfile=async function(e,t){if((0,a.blank)(e))return;const i=t??await(0,d.bestVolumeForPath)(e);if(null==i)return void b().warn("nativePathToPsfile(): no volume UUID found",{file:e,volumeMetadata:i});if((0,a.blank)(i.volsha)){const t={file:e,volume:i};return void(i.isReadOnly?b().info("nativePathToPsfile(): no volsha for volume (readonly)",t):w.has(i.mountPoint)||(w.add(i.mountPoint),b().warn("nativePathToPsfile(): no volsha for volume",t)))}const r=(0,f.native2posix)(e),s=(0,f.native2posix)(i.mountPoint);let n=r;if(!n.normalize().startsWith(s.normalize())){const t=await(0,h.dataVolumePath)(e);null!=t&&(n=(0,f.native2posix)(t))}if(!n.normalize().startsWith(s.normalize())){const t=await S(e);if(t!==e&&(n=(0,f.native2posix)(t),!n.normalize().startsWith(s.normalize()))){const e=await(0,h.dataVolumePath)(t);null!=e&&(n=(0,f.native2posix)(e))}}if(!n.normalize().startsWith(s.normalize()))return;const o=(0,l.ensurePrefix)(n.slice(s.length),"/");return{nativePath:e,uri:y.URI.from({scheme:u.PS_LOCAL_FILE_SCHEME,authority:i.volsha,path:o})}},t.psfileToNativePath_=async function(e){if(e.scheme!==u.PS_LOCAL_FILE_SCHEME)return b().throw(new g.InvalidURIError("Invalid scheme: "+e));if((0,a.blank)(e.authority))return b().throw(new g.InvalidURIError("Missing authority: "+e));const t=await(0,d.volshaToMountPoints)(e.authority),i=await(0,c.sortByAsync)({iter:t,f:async t=>[await(0,m.exists)(P(t,e.path))]}),r=(0,n.at)(i,-1);return(0,a.blank)(r)?b().throw(new g.InvalidURIError("No mount point found for volsha: "+e)):{mountPoint:r,nativePath:await(0,h.canonicalizeMacPath)(P(r,e.path))}};const r=i(51455),s=i(76760),n=i(17586),a=i(22573),o=i(45599),l=i(51926),u=i(89937),c=i(56519),d=i(34075),h=i(9029),f=i(78133),m=i(16287),p=i(50213),g=i(85831),y=i(34238),v=i(85087),b=(0,o.defer)(()=>(0,p.mkLogger)("uri.psfile")),w=new Set;async function S(e){try{return await(0,r.realpath)(e)}catch{const t=(0,s.dirname)(e);if(t===e)return e;const i=await S(t);return(0,s.join)(i,(0,s.basename)(e))}}function P(e,t){return(0,s.join)(e,...(0,l.stripPrefix)(t,"/").split("/"))}},5696(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PSLIB_ROOT_URI=void 0,t.nativePathToPslib=function(e){if((0,s.blank)(e))return;const t=(0,r.uniq)([(0,o.originalsDir)(),(0,o.libraryDir)()]).find(t=>(0,c.containedByNativePath)({ancestor:t,descendant:e,acceptSelf:!0}));if(null==t)return;const i=(0,n.ensurePrefix)((0,u.posixPathFrom)(t,e),"/");return{nativePath:e,uri:m.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:i})}},t.pslibToNativePath_=function({uri:e}){if(e.scheme!==a.PS_LIBRARY_SCHEME)return p().throw(new f.InvalidURIError("Invalid scheme: "+e));const t=(0,n.stripPrefix)(e.path,"/"),i=(0,l.libraryAssetDirPosixFiles)().map(e=>{const i=e.join(t);return{nativePath:i.nativePath,mountPoint:e.nativePath,isFileSync:i.isFileSync()}});return i.find(e=>e.isFileSync)??i[0]??p().throw(new f.InvalidURIError("No library dirs configured"))};const r=i(40958),s=i(22573),n=i(51926),a=i(89937),o=i(9595),l=i(87290),u=i(29882),c=i(91987),d=i(19851),h=i(50213),f=i(85831),m=i(34238),p=(0,d.lazy)(()=>(0,h.mkLogger)("uri.pslib"));t.PSLIB_ROOT_URI=m.URI.from({scheme:a.PS_LIBRARY_SCHEME,path:"/"})},12228(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.nativePathToPsnet=async function(e,t){if((0,l.blank)(e))return;if((0,p.isUNC)(e))return{nativePath:e,uri:w.URI.file(e).with({scheme:c.PS_NETWORK_FILESYSTEM_SCHEME})};const i=t??await(0,m.bestVolumeForPath)(e);return null!=i&&!0===i.remote&&(0,l.notBlank)(i.remoteHost)&&(0,l.notBlank)(i.remoteShare)?{nativePath:e,uri:w.URI.from({scheme:c.PS_NETWORK_FILESYSTEM_SCHEME,authority:i.remoteHost,path:o.posix.join("/"+i.remoteShare,(0,f.stripPrefix)((0,g.native2posix)(e),(0,g.native2posix)(i.mountPoint)))})}:void 0},t.psnetToNativePath_=async function({uri:e,volume:t}){if(e.scheme!==c.PS_NETWORK_FILESYSTEM_SCHEME)return S().throw(new b.InvalidURIError("Invalid scheme: "+e));if((0,l.blank)(e.authority))return S().throw(new b.InvalidURIError("Missing authority: "+e));const i=e.path.split("/").slice(1),r=i[0];if((0,l.blank)(r))return S().throw(new b.InvalidURIError("Missing share: "+e));const s=i.slice(1);for await(const i of(0,u.chainAsyncIterators)([t],m.remoteVolumes))if((0,f.equalsIgnoreCase)(i.remoteShare,r)&&await(0,y.isEquivalentHost)(e.authority,i.remoteHost))return{nativePath:o.join(i.mountPoint,...s),mountPoint:i.mountPoint};return v.isWin?{nativePath:`\\\\${e.authority}\\${i.join("\\")}`}:S().throw(new b.InvalidURIError("Failed to resolve psnet URI: "+e))};const o=a(i(76760)),l=i(22573),u=i(41801),c=i(89937),d=i(19851),h=i(50213),f=i(81168),m=i(34075),p=i(29882),g=i(78133),y=i(96128),v=i(43334),b=i(85831),w=i(34238),S=(0,d.lazy)(()=>(0,h.mkLogger)("uri.psnet"))},85087(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volsha=void 0;const r=i(22573),s=i(42659),n=i(55139),a=i(37628);t.volsha=(0,n.memoize)(e=>(0,r.mapNotBlank)(e,a.shortStringSha),{name:"uri.volsha",ttlMs:5*s.minuteMs})},50036(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.channelVersionsCache=function(){return s.PosixFile.forMaybe((0,r.configDir)())?.join("channel-versions.json")};const r=i(46292),s=i(95696)},60865(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.versionMajorMinor=t.baseVersion=void 0,t.channel=function(){return(0,s.extractUpdateChannel)(r.version)};const r=i(37805),s=i(30577);t.baseVersion=()=>[r.versionMajor,r.versionMinor,r.versionPatch].join("."),t.versionMajorMinor=r.versionMajor+"."+r.versionMinor},76280(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isSemVer=y,t.toSemVer=v,t.semVerToString=b,t.semVerSatisfies=function(e,t){const i=v(e);if(null==i)return!1;const s=b(i,!0);return(0,r.satisfies)(s,t,{loose:!0,includePrerelease:!0})},t.semverSortBy=P,t.sortSemVer=function(e){return(0,n.sortBy)(e,P)},t.semVerCompare=M,t.semverLt=function(e,t){return M(e,t)<0},t.semverGte=function(e,t){return M(e,t)>=0},t.semverLatest=function(...e){return(0,d.greatestBy)(e,P)};const r=i(38064),s=i(40958),n=i(76790),a=i(22573),o=i(31586),l=i(34666),u=i(59455),c=i(54993),d=i(48884),h=i(81168),f=i(30577);function m(e){return(0,u.toA)(e).map(e=>(0,o.toGte0)(e)??(0,c.toS)(e).trim()).filter(e=>!(0,a.blank)(e))}const p=/^(?<epoch>\d+:)?[vn]?(?<major>\d+)(?:\.(?<minor>\d+))?(?:\.(?<patch>\d+))?(?:-(?<prerelease>[^+\s]+))?(?:\+(?<build>\S+))?/;function g(e){return m((0,c.toS)(e).split(/\s*\.\s*/)).map(e=>(0,o.toInt)(e,{strict:!0})??e)}function y(e){return null!=e&&"number"==typeof e.major}function v(e,t=!1){return y(e)?e:function(e,t=!1){if((0,a.blank)(e))return;const i=p.exec(e)?.groups;if(!i)return;const r={epoch:i.epoch?(0,o.toInt)(i.epoch.replace(":","")):void 0,major:(0,o.toInt)(i.major)??0,minor:(0,o.toInt)(i.minor),patch:(0,o.toInt)(i.patch)};return t||(i.prerelease&&(r.prerelease=g(i.prerelease)),i.build&&(r.build=g(i.build))),r}((0,c.toS)(e),t)}function b(e,t=!1){let i=`${(0,o.toGte0)(e.major)??0}.${(0,o.toGte0)(e.minor)??0}.${(0,o.toGte0)(e.patch)??0}`;if(!t){const t=m(e.prerelease);t.length>0&&(i+=`-${t.join(".")}`);const r=m(e.build);r.length>0&&(i+=`+${r.join(".")}`)}return i}function w(e){return(0,h.isString)(e)?f.UpdateChannels.indexOf(e):void 0}function S(e){const t=(0,s.compactBlanks)(e);return[(0,d.first)(t,w)??f.UpdateChannels.length+1,...(0,d.rightPadArray)(t.map(e=>w(e)??function(e){return(0,o.toInt)(e,{strict:!0})??e}(e)),2,-1)]}function P(e){const t=v(e);return null==t?void 0:[(0,o.toGte0)(t.major)??-1,(0,o.toGte0)(t.minor)??-1,(0,o.toGte0)(t.patch)??-1,...S(t.prerelease),...(i=t.build,(0,d.rightPadArray)((0,u.toA)(i).map(e=>(0,o.toInt)(e,{strict:!0})??-1),2,1/0))];var i}function M(e,t){return(0,l.cmp)(P(e),P(t))}},38244(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isChannelVersionsJson=a,t.toChannelVersionsJson=o,t.extractChannelVersionsJson=function(e){if(!(0,s.isObject)(e))return;const t={},i=Array.isArray(e)?e.map(e=>[e?.channel,e?.version]):Object.entries(e);for(const[e,s]of i)n.UpdateChannels.includes(e)&&(0,r.notBlank)(s)&&(t[e]=s);return o(t)};const r=i(22573),s=i(68708),n=i(30577);function a(e){return!!(0,s.isObject)(e)&&(0,r.notBlank)(e.stable)}function o(e){return a(e)?e:void 0}},30577(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UpdateChannels=void 0,t.extractUpdateChannel=function(e){return e.includes("-beta")?t.UpdateChannels.beta:t.UpdateChannels.stable},t.eligibleForChannel=function(e){return t.UpdateChannels.values.slice(t.UpdateChannels.ordinal(e))};const r=i(50989);t.UpdateChannels=(0,r.strEnum)("beta","stable")},63335(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ver=function(e){return(0,r.blank)(e)?"(missing version)":e.replace(/^(?:v(?:er(?:sion)?)?)?\s*/,"version ")};const r=i(22573)},40044(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getChannelVersions_=void 0,t.currentChannel=function(){const e=[v.UpdateSettings.updateChannel.valueOrDefault,(0,P.channel)()].map(e=>_.UpdateChannels.ordinal(e)).sort()[0];return _.UpdateChannels.values[e]??v.UpdateSettings.updateChannel.valueOrDefault},t.versionCheck_=async function(e){for(const e of[y.PrivacySettings.optOut,g.NetworkingSettings.noNetwork])if(!0===e.value)return{level:"disabled",msg:["PhotoStructure version checking is disabled","Set "+(0,s.code)(e.toEnvLine(!1))+" to enable."]};if(!v.UpdateSettings.autoUpdateCheck.valueOrDefault){const e=["PhotoStructure version checking is disabled"];return!0===y.PrivacySettings.optOut.value?e.push("Set "+(0,s.code)(y.PrivacySettings.optOut.toEnvLine(!1))+" to enable."):!1===v.UpdateSettings.autoUpdateCheck.value?e.push("Set "+(0,s.code)(v.UpdateSettings.autoUpdateCheck.toEnvLine(!0))+" to enable."):e.push("Finish setup, or set "+(0,s.code)(v.UpdateSettings.autoUpdateCheck.toEnvLine(!0))+" to enable."),{level:"disabled",msg:e}}const i=(0,f.configDir)();if(null==i||!await(0,m.isDirectory)(i))return{level:"warn",msg:["PhotoStructure version checking is disabled","No suitable configuration directory exists."]};const a=await(0,t.getChannelVersions_)();if(null==a)return{level:"warn",msg:["Failed to fetch PhotoStructure version information"]};const c=e?.installedVersion??d.version,h=(0,_.extractUpdateChannel)(c),p=(0,_.eligibleForChannel)(h),b=(0,l.values)((0,l.pick)(a,...p)),w=e?.latestVersion??(0,M.semverLatest)(...b);if(null==w)return{level:"warn",msg:["PhotoStructure version checking failed","No suitable version was found for "+v.UpdateSettings.updateChannel.toEnvLine()]};const S=(0,_.extractUpdateChannel)(w),P="You are running "+(0,u.EditionName)()+" "+(0,E.ver)(c),T="The latest published "+(0,s.code)(S)+" build is "+(0,E.ver)(w),k=S===h?void 0:"You should consider switching to the "+(0,s.code)(S)+" channel.",D=Date.now()-a.updatedAt,I="Last checked "+(D<n.minuteMs?"just now":(0,o.fmtDuration)(D,{units:1})+" ago")+" ("+new Date(a.updatedAt).toISOString()+")",C=(0,r.compact)([P,T,k,I]),A={installedVersion:c,installedChannel:h,latestVersion:w,latestChannel:S};return(0,M.semverGte)(c,w)?{level:"ok",msg:["PhotoStructure is up to date",...C],...A}:{level:"warn",msg:["PhotoStructure is out of date",...C],...A}};const r=i(40958),s=i(82950),n=i(42659),a=i(45599),o=i(6875),l=i(68708),u=i(17344),c=i(50213),d=i(37805),h=i(5916),f=i(46292),m=i(16287),p=i(43205),g=i(14112),y=i(22834),v=i(56507),b=i(63870),w=i(89372),S=i(50036),P=i(60865),M=i(76280),T=i(38244),_=i(30577),E=i(63335),k=(0,a.defer)(()=>(0,c.mkLogger)("VersionCheck"));t.getChannelVersions_=(0,h.lazyAsync)({desc:"version.getChannelVersions_",timeoutMs:(0,b.commandTimeoutMs)(),ttlMs:n.minuteMs,later:async()=>{const e=(0,S.channelVersionsCache)(),i=await(0,w.httpGetJson_)({url:"https://photostructure.com/channel-versions.json",headers:{"User-Agent":await(0,p.userAgent)()},cache:e,ttlMs:v.UpdateSettings.updateCheckTtlMs.valueOrDefault,preCacheTransform:e=>{const t=(0,T.extractChannelVersionsJson)(e);return null==t?void 0:{...t,updatedAt:Date.now(),updatedByVersion:d.version}}}),r=i.data;if(null==r||r.updatedByVersion!==d.version){if(i.fromCache)return k().info("getChannelVersions_(): Invalid or stale cached response. Retrying after wiping cache",{result:r,cache:e}),await e.unlink_(),t.getChannelVersions_.refresh();k().throw("getChannelVersions_(): Invalid response",{result:r})}return k().tap({msg:"getChannelVersions_()",result:r})}})},1485(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExcludedMountpointPathsDocker=t.ExcludedMountpointPathsBase=void 0;const r=i(29365),s=i(25636);t.ExcludedMountpointPathsBase=(0,s.sortNatural)([...r.SystemPathPatternsDefault]),t.ExcludedMountpointPathsDocker=(0,s.sortNatural)([...t.ExcludedMountpointPathsBase,"/","/etc/hostname","/etc/hosts","/etc/resolv.conf"])},63870(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MinIoRate=void 0,t.mountpointsTtlMs=function(){return n.FilesystemSettings.mountpointsTtlMs.valueOrDefault},t.volumeMetadataTtlMs=function(){return a.VolumesSettings.volumeMetadataTtlMs.valueOrDefault},t.commandTimeoutMs=function(){return n.FilesystemSettings.statTimeoutMs.valueOrDefault};const r=i(42659),s=i(12168),n=i(57549),a=i(20029);t.MinIoRate=s.MiB/r.secondMs},86848(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidNotExpected=E,t.addVolumeUUID=async function(e){if(E(e))return k(e.uuid);const t=await I(e);return null!=t&&(e.uuid=t),t},t.toVolumeUUID=k,t.readUuidFile_=D,t.readVolumeUUID=I,t.volumeUuidSubpath=C,t.writeVolumeUuid=A,t.volumeUuidText=x;const r=i(77598),s=i(76760),n=i(19851),a=i(22573),o=i(13538),l=i(55139),u=i(50213),c=i(7282),d=i(81168),h=i(37805),f=i(83278),m=i(84542),p=i(85772),g=i(95696),y=i(16287),v=i(73428),b=i(45969),w=i(43334),S=i(28874),P=i(20237),M=i(63870),T=(0,n.lazy)(()=>(0,u.mkLogger)("volumes.VolumeUUID")),_=new l.Cache({name:"VolumeUUID.warnedPaths",maxSize:256,ttlMs:36e5});function E(e){return w.isPosix&&!0===e.isSystemVolume||(0,b.isDocker)()&&"/"===e.mountPoint||(0,c.isTest)()&&"node_modules"===(0,s.basename)(e.mountPoint)}function k(e){if((0,a.blank)(e))return;const t=(0,d.stripComments)(e).replace(/[^\da-z-]+/gi,"").trim().replace(/^-|-$/g,"");return t.length<8||/^[0-]*$/.test(t)||/^[F-]*$/i.test(t)?void 0:t}async function D(e){const t=await(0,o.thenOrTimeoutError)(e.readText_(),(0,M.commandTimeoutMs)());for(const e of(0,m.splitLines)(t)){const t=k(e);if(null!=t)return t}throw new Error("No UUID found in "+e)}async function I(e){if(S.Settings.readVolumeUuidFiles.valueOrDefault)for(const t of S.Settings.volumeUuidFilePaths.values){const i=g.PosixFile.for(e.mountPoint).join(t),r=await D(i).catch(e=>{_.getOrSet("read:"+i.nativePath,()=>(T().info("Failed to read "+i,{error:e}),!0))});if(null!=r)return T().tap({msg:"readVolumeUUID(): serving UUID from "+t,result:r,meta:{mountpoint:e.mountPoint}})}const t=(0,s.join)(e.mountPoint,C());if("/"===e.mountPoint)return T().tap({msg:"readVolumeUUID(): not attempting to write "+t,result:e.uuid,meta:{volume:e}});if(S.Settings.skipWriteVolumeUuidFilesWithNoMedia.valueOrDefault){const i=await(0,p.whyNoMediaDir)(f.BaseFile.for(e.mountPoint));if(null!=i)return T().tap({msg:"readVolumeUUID(): not attempting to write "+t+": mountpoint is marked as NoMedia",result:e.uuid,meta:{volume:e,why:i}})}if(S.Settings.writeVolumeUuidFiles.valueOrDefault){const t=await A(e);if(!(0,a.blank)(t))return T().tap({msg:"readVolumeUUID(): wrote new "+C(),result:t,meta:{volume:e}})}return T().tap({msg:"readVolumeUUID(): serving UUID from volume metadata",result:k(e.uuid)})}function C(){return(0,a.toNotBlank)(S.Settings.volumeUuidFilePaths.values[0])??".uuid"}async function A({mountPoint:e,uuid:t}){const i=(0,s.join)(e,C());t=k(t)??(0,r.randomUUID)();const n=(0,s.dirname)(i);if(await(0,y.isReadWriteableDirectory)(n))try{return await(0,v.writeText_)(i,...x(t)),T().info("writeVolumeUuid(): Saved new UUID for "+e,{uuid:t}),t}catch(t){_.getOrSet("saveFail:"+i,()=>(T().warn("writeVolumeUuid(): Failed to save new UUID for "+e,{error:t}),!0))}else _.getOrSet("write:"+i,()=>(T().warn(`writeVolumeUuid(): cannot write to ${i}, directory is not read/write`),!0))}function x(e){return[e,"","# This volume UUID was written by PhotoStructure v"+h.version,"# See https://photostructure.com/faq/what-is-a-volume/ for details.","# Files found on this volume will have a URI that starts with","# "+(0,P.psfileUri)({volumeUUID:e,path:"/"})]}},55111(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HelmetPlugins=void 0;const r=i(50989);t.HelmetPlugins=(0,r.strEnum)("all","contentSecurityPolicy","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","dnsPrefetchControl","expectCt","frameguard","hidePoweredBy","hsts","ieNoOpen","noSniff","originAgentCluster","permittedCrossDomainPolicies","referrerPolicy","xssFilter")},89372(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.httpGetJson_=async function(e){const t=e.cache,i=await t.mtimeMs();if(null!=i&&(0,n.gt0)(await t.size())&&(0,n.gte)(i,Date.now()-e.ttlMs))return{data:await t.readJson_(),updatedAt:i,fromCache:!0};const r=await(0,l.get_)(e.url,{headers:e.headers});o.HttpStatusIs.success(r.statusCode)||u().throw("Failed",{url:e.url,response:r});const a=(0,s.parseJSON_)(r.data),c=e.preCacheTransform?.(a)??a;return u().info("Fetch success. Caching",{args:e,json:c,cache:t}),await t.writeJson_(c),{data:c,updatedAt:Date.now(),fromCache:!1}};const r=i(45599),s=i(98553),n=i(31586),a=i(50213),o=i(51140),l=i(4988),u=(0,r.defer)(()=>(0,a.mkLogger)("web.HttpGet"))},51140(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpStatusIs=t.HttpStatus=void 0;const r=i(31586);t.HttpStatus=Object.freeze({OK:200,Accepted:202,MovedPermanently:301,Found:302,SeeOther:303,BadRequest:400,Unauthorized:401,Forbidden:403,NotFound:404,EnhanceYourCalm:420,InternalServerError:500,NotImplemented:501,ServiceUnavailable:503}),t.HttpStatusIs=Object.freeze({ok:e=>(0,r.within)(200,299,e),success:e=>(0,r.within)(200,299,e),redirect:e=>(0,r.within)(300,399,e),clientError:e=>(0,r.within)(400,499,e),serverError:e=>(0,r.within)(500,599,e),error:e=>(0,r.within)(400,599,e)})},76642(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uriToTagPath=function({uri:e,isFile:t}){if(null==e)return;const i=(0,o.toURI)(e),l=i.scheme===a.PS_LIBRARY_SCHEME?r.LibraryTagName:i.scheme===a.PS_LOCAL_FILE_SCHEME?i.authority:void 0;if((0,n.blank)(l))return;const u=i.path.split("/");return(0,s.compactBlanks)([r.TagRoots.fs,l,...t?u.slice(0,-1):u])};const r=i(75020),s=i(40958),n=i(22573),a=i(89937),o=i(34238)},98604(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.myWebUrl=void 0,t.default=f,t.mkFolderUrl=async function(e){const{uri:i}=await(0,c.nativePathToUri)(e),r=(0,h.uriToTagPath)({uri:i,isFile:!1});if((0,s.isEmpty)(r))return;const n=(0,a.mkTagUri)((0,u.tagPathToStringArray)(r));return(0,t.myWebUrl)()?.with(n)},t.mkAssetUrl=function(e){return(0,n.gt0)(e)?(0,t.myWebUrl)()?.with({path:"/asset/"+e}):void 0};const r=i(19851),s=i(40958),n=i(31586),a=i(27776),o=i(72308),l=i(28874),u=i(42231),c=i(45200),d=i(34238),h=i(76642);function f(e=l.Settings.httpPort.valueOrDefault){const t=[l.Settings.localhost.valueOrDefault];l.Settings.exposeNetworkWithoutAuth.valueOrDefault&&t.push(...(0,s.compactBlanks)([...(0,o.myExternalIp4Addresses)(),l.Settings.hostname.valueOrDefault]));const i=(0,d.toURI)("http://a");return(0,s.uniqBy)(t.map(t=>i.with({authority:t+":"+e})),e=>e.toString())}t.myWebUrl=(0,r.lazy)(()=>f()[0])},4988(e,t,i){"use strict";var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),a=0;a<i.length;a++)"default"!==i[a]&&s(t,e,i[a]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HttpMethods=void 0,t.get_=w,t.httpRequest_=S;const o=a(i(37067)),l=a(i(44708)),u=i(22573),c=i(45599),d=i(50989),h=i(51926),f=i(50213),m=i(45255),p=i(22911),g=i(43205),y=i(34238),v=i(51140),b=(0,c.defer)(()=>(0,f.mkLogger)("net.get"));async function w(e,t){return S({...t,url:e})}async function S(e){const t=(0,y.toURI)(e.url),i=new p.Deferred("get "+t.toString()),r="http"===t.scheme?o.request:"https"===t.scheme?l.request:b().throw("unsupported scheme: "+t.scheme),s=e?.maxRedirects??8,n=e?.timeoutMs??m.ShortCommandTimeoutMs,a={...e?.headers};a["User-Agent"]??=await(0,g.userAgent)();const c=e?.method??"GET",d=e?.agent??!1,f=r(t.toString(),{method:c,headers:a,timeout:n,agent:d},e=>{let r="";e.setEncoding("utf8").on("data",e=>r+=e.toString()).resume().on("end",()=>{const a={url:(0,u.toNotBlank)(e.url)??t.toString(),contentType:e.headers["content-type"],statusCode:e.statusCode??-1,data:r};s>0&&v.HttpStatusIs.redirect(a.statusCode)&&!(0,u.blank)(e.headers.location)?(b().info("Following redirect",{from:t.toString(),to:e.headers.location,statusCode:a.statusCode}),i.observe(w(e.headers.location,{timeoutMs:n,maxRedirects:s}))):(b().debug("complete",{...a,data:(0,h.ellipsize)(r,64),data_length:r.length}),i.resolve(a))})}).on("error",e=>i.reject(e));return(0,u.blank)(e.body)||f.write(e.body),f.end(),i}t.HttpMethods=(0,d.strEnum)("GET","PUT","POST","PATCH","DELETE")},65713(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadCuss=t.CussNativePath=void 0,t.getCuss=f,t.isCussy=m,t.decuss=function(e){let t=10,i="";do{i=e()}while(t-- >0&&m(i.replace(/[^a-z]/gi,"")));return i};const r=i(76760),s=i(19851),n=i(23838),a=i(81168),o=i(84542),l=i(46473),u=i(13047),c=i(31589);t.CussNativePath=(0,s.lazy)(()=>(0,r.join)(l.ProjectDir.Data(),"cuss.txt.br")),t.loadCuss=(0,s.lazy)(async()=>{const e=(0,o.splitCompactLines)(await(0,u.zcat)((0,t.CussNativePath)()));d.set(h(e))});const d=(0,s.lazy)(()=>({trie:new n.MultiMap,small:[]}));function h(e){const t=new n.MultiMap,i=[];for(const r of e)r.length<3?i.push(r):t.add(r.slice(0,3),r);return{trie:t,small:i}}function f(e,t){const i=(0,a.stripEmoji)((0,a.stripDiacritics)(e.toLowerCase().normalize())),{small:r,trie:s}=null==t?d():h(t);for(const e of[i.replace(/[^a-z]/gi,""),...(0,c.unl33t)(i)]){const t=r.find(t=>e.includes(t));if(null!=t)return t;for(let t=0;t<e.length-2;t++){const i=s.get(e.slice(t,3));if(null!=i){const r=e.slice(t),s=i.find(e=>r.startsWith(e));if(null!=s)return s}}}}function m(e){return null!=f(e)}},31589(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.l33t=function(e){let t="";const i=l;for(const r of e)t+=i[r]?.[0]??r;return t},t.unl33t=function(e){return c((0,o.stripDiacritics)(e).normalize())};const r=i(22573),s=i(96249),n=i(23838),a=i(59455),o=i(81168),l={a:["4","@","Д"],b:["8","6","Ъ"],c:["[","(","©"],e:["3","€"],f:["ƒ"],g:["9"],i:["1","!","|"],l:["1","£"],o:["0"],s:["5","$"],t:["7","+","†"],x:["×"],z:["2"]},u=n.MultiMap.fromJSON(l).inverse().toJSON();function c(e){if((0,r.blank)(e))return[""];const t=e.substring(0,1),i=[t,...(0,a.toA)(u[t])],n=c(e.substring(1));return(0,s.flatten)(n.map(e=>i.map(t=>t+e)))}},30933(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.cpuCount=t.cpuInfo=void 0;const s=r(i(48161)),n=i(19851),a=i(42659),o=i(31586),l=i(50213),u=(0,n.lazy)(()=>(0,l.mkLogger)("work.CpuInfo"));t.cpuInfo=(0,n.lazy)(()=>s.default.cpus(),5*a.minuteMs),t.cpuCount=(0,n.lazy)(()=>{try{const e=s.default.availableParallelism?.(),i=(0,t.cpuInfo)().length;return u().tap({msg:"cpuCount()",result:(0,o.clamp)(1,128,Math.ceil(e??i)),meta:{availableParallelism:e,cpuInfoLength:i}})}catch(e){return u().warn("availableParallelism()/cpuCount() failed",{error:e}),1}})},14854(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CpuTimes=t.CpuUsage=void 0,t.isTooBusy=v,t.resolveOnNotBusy=function(){return v()?b??=new o.Latch:Promise.resolve()},t.busyPctFromLoad=P;const s=r(i(48161)),n=i(42659),a=i(45599),o=i(56409),l=i(55835),u=i(31586),c=i(78406),d=i(25764),h=i(34102),f=i(82647),m=i(43334),p=i(28874),g=i(30933),y=i(15674);function v(){if(0===p.Settings.cpuBusyPercent.valueOrDefault)return!1;const e=w.instance().busyPct(),t=(0,u.clamp)(1,150,Math.round(4*p.Settings.cpuBusyPercent.valueOrDefault/3));return!!(0,u.gte)(e,t)&&((0,h.ee)().emitRateLimited("cpuTooBusy"),!0)}let b;class w extends c.EndableInterval{#Br=new f.Average(5);#zr=new S;static instance=(0,a.defer)(()=>new w);constructor(){super({name:"CpuUsage()",callback:()=>this.#Vr(),intervalMs:((0,y.singleThreadedMode)()?60:m.isWin?20:10)*n.secondMs,rank:d.EndableRanks.first}),(0,u.mapFinite)(P(),e=>this.#Br.push(e)),this.#Vr()}get cpuCount(){return this.#zr.cpuCount}idlePct(){return(0,l.map)(this.busyPct(),e=>100-e)}busyPct(){return this.#Br.sampleAvg??P()}#Hr(e){(0,u.gte0)(e)&&this.#Br.push(e)}#Vr(){this.#Hr(P());const e=new S;this.#Hr(e.busyPct(this.#zr)),this.#zr=e,null==b||v()||(b.resolve(),b=void 0)}}t.CpuUsage=w;class S{cpuCount;busyMs;idleMs;constructor(e=s.default.cpus()){let t=0,i=0;for(const r of e)t+=r.times.user+r.times.nice+r.times.sys+r.times.irq,i+=r.times.idle;this.busyMs=t,this.idleMs=i,this.cpuCount=e.length}busyPct(e){if(e.cpuCount!==this.cpuCount)return;const t=this.busyMs-e.busyMs,i=this.idleMs-e.idleMs,r=t+i;return(0,u.gte0)(t)&&(0,u.gte0)(i)&&(0,u.gt0)(r)?(0,u.sigFigs)(t/r*100,3):void 0}}function P(){return m.isWin?void 0:(0,u.sigFigs)(s.default.loadavg()[0]/(0,g.cpuInfo)().length*100,3)}t.CpuTimes=S},73328(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.doNotRun=void 0;const r=i(99331),s=i(30495),n=i(14854),a=i(69385);t.doNotRun=(0,s.shimSync)({name:"doNotRun",impl:function(e){return!0===e?.ended||(0,r.ending)()||(0,n.isTooBusy)()||(0,a.isPaused)()}})},58444(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.estimatedFreeMem=void 0;const s=r(i(48161)),n=i(19851),a=i(31586),o=i(12168),l=i(50213),u=i(45879),c=i(70417),d=i(45969),h=(0,n.lazy)(()=>(0,l.mkLogger)("work.FreeMem"));t.estimatedFreeMem=(0,n.lazy)(()=>{const e=s.default.freemem(),t=s.default.totalmem(),i=(2*e+t)/3;if((0,d.isDocker)()){const r=(0,u.intFromFileSync)("/sys/fs/cgroup/memory/memory.limit_in_bytes");if((0,a.gt0)(r))return h().tap({msg:"estimatedFreeMem() (docker mode)",result:(0,c.avg)([r,i]),meta:{freemem:e,totalmem:t,cgroupMem:r}})}return h().tap({msg:"estimatedFreeMem() ",result:i,meta:{result:(0,o.fmtBytes)(i),freemem:(0,o.fmtBytes)(e),totalmem:(0,o.fmtBytes)(t)}})})},69385(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isPaused=function(){return o},t.pause=u,t.resume=function(){u(!1)},t.lastResumeTs=function(){return l},t.resolveOnResume=function(){return o?a??=new r.Latch:Promise.resolve()};const r=i(56409),s=i(34102),n=i(84968);let a,o=!1,l=n.StartTs;function u(e=!0){const t=o!==e;o=e,o||(l=Date.now(),a?.resolve(),a=void 0),t&&(0,s.ee)().emitSync("syncStateChanged")}},15674(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maxConcurrentImports=t.maxCpus=void 0,t.clearMaxWorkCaches=y,t.timeoutPenalization=b,t.targetCpuLoadPct=w,t.singleThreadedMode=function(){return 1===(0,t.maxCpus)()},t.sharpThreadsPerProcess=function(){return(0,a.toGt0)(h.Settings.sharpThreadsPerProcess.valueOrDefault)??((0,t.maxCpus)()<=6?2:1)};const r=i(19851),s=i(42659),n=i(41400),a=i(31586),o=i(12168),l=i(50213),u=i(7282),c=i(34102),d=i(57902),h=i(28874),f=i(30933),m=i(58444),p=i(22751),g=(0,r.lazy)(()=>(0,l.mkLogger)("work.MaxCpus"));function y(){m.estimatedFreeMem.unset(),t.maxCpus.unset(),t.maxConcurrentImports.unset(),p.timeoutRate.prior()?.clear(),f.cpuCount.unset()}(0,n.later)(()=>{(0,u.isTest)()&&(0,c.ee)().on("clearCache",()=>y()),(0,c.ee)().on("settingsChanged",y),h.Settings.singleThreaded.watchLater(y),h.Settings.cpuBusyPercent.watchLater(y),h.Settings.maxConcurrentImports.watchLater(y)});const v=(0,r.lazy)(()=>{const e=(0,a.clamp)(128,1024,h.Settings.maxMemoryMb.valueOrDefault)*o.MB;return g().tap({msg:"maxProcsForMem",result:Math.max(1,Math.floor((0,m.estimatedFreeMem)()/e)),meta:{estFreeMemMb:Math.floor((0,m.estimatedFreeMem)()/o.MB),worstCaseMemPerProcMb:Math.ceil(e/o.MB)}})},s.minuteMs);function b(){const e=Math.round(p.timeoutRate.prior()?.eventsPerMinute??0),t=h.Settings.timeoutThrottleCoeff.valueOrDefault,i=0===e||0===t?1:(0,a.sigFigs)(t/e,2);return g().tap({msg:"timeoutPenalization()",level:i>1?d.LogLevels.warn:d.LogLevels.debug,result:i,meta:{timeoutsPerMinute:e,timeoutThrottleCoeff:t}})}function w(){return((0,a.toGt0)(h.Settings.cpuBusyPercent.valueOrDefault)??1)/100}t.maxCpus=(0,r.lazy)(function(){if(h.Settings.singleThreaded.valueOrDefault)return 1;const e=0===h.Settings.cpuBusyPercent.valueOrDefault?(0,f.cpuCount)():Math.max(1,Math.floor(w()*(0,f.cpuCount)()));let t=e;const i=p.timeoutRate.prior()?.eventsPerMinute??0,r=b();if(1!==r){const e=t;t*=r,g().warn("Recent timeouts! Throttling down.",{penalization:r,resultBeforePenalization:e,resultAfterPenalization:t})}const s=Math.min(e,v()),n=Math.min(h.Settings.syncUvThreads.valueOrDefault/2,Math.floor(e/2));return t=(0,a.clamp)(1,s,Math.floor(t-n)),g().tap({msg:"maxCpus()",level:d.LogLevels.info,result:t,meta:{cpuLoadPct:w(),cpuCount:(0,f.cpuCount)(),cpuPortion:e,penalization:r,timeoutsPerSecond:i,maxProcsForMem:v()}})}),t.maxConcurrentImports=(0,r.lazy)(function(){return(0,a.toGt0)(h.Settings.maxConcurrentImports.valueOrDefault)??(0,t.maxCpus)()})},22751(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.timeoutRate=void 0,t.onTimeout=function(){const e=(0,t.timeoutRate)();e.onEvent(),f().warn("onTimeout()",e.stats()),p()};const r=i(87997),s=i(19851),n=i(42659),a=i(41400),o=i(50213),l=i(7282),u=i(45255),c=i(34102),d=i(976),h=i(15674),f=(0,s.lazy)(()=>(0,o.mkLogger)("work.WorkTimeout"));t.timeoutRate=(0,s.lazy)(()=>new d.Rate(5*n.minuteMs,(0,l.isTest)()?100:u.ShortCommandTimeoutMs));const m=(0,s.lazy)(()=>(0,r.setInterval)(p,n.minuteMs).unref());function p(){h.maxCpus.refresh(),h.maxConcurrentImports.refresh(),m()}(0,a.later)(()=>{(0,c.ee)().on("clearCache",()=>{h.maxCpus.unset(),h.maxConcurrentImports.unset(),t.timeoutRate.unset()})})},83966(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ping=void 0;const s=r(i(1708)),n=i(41400),a=i(31586),o=i(7282),l=i(79136),u=i(45608),c=i(57159),d=i(89035);t.ping=(0,l.shim)({name:"worker.ping",async impl(e){if((0,a.gt0)(e?.delay)&&await(0,n.delay)(e.delay),(0,o.isTest)()&&!0===e?.pretendMemUsageIsHigh&&d.memoryUsageIsHigh.set(!0),null!=e?.throw)throw new c.WrappedError(e.throw.message,e.throw);if((0,d.memoryUsageIsHigh)())throw(0,u.exit)({reason:"memory usage is high",status:1}),new c.WrappedError("Memory usage is high",{fatal:!0});return{pid:s.default.pid,input:e?.input??"(no input)"}}})},40958(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.primitiveValueOfOrElse=void 0,t.isNotEmpty=m,t.toNotEmpty=function(e){return m(e)?e:void 0},t.notEmptyOr=function(e,t){return m(e)?e:(0,c.tot)(t)},t.isEmpty=p,t.mapArray=function(e,t){return Array.isArray(e)?t(e):void 0},t.mapNotEmpty=function(e,t){return m(e)?t(e):void 0},t.mapNotEmptyOr=function(e,t,i){return m(e)?t(e):(0,c.tot)(i)},t.toPrimitive=g,t.startsWith=function(e,t){return y(e.slice(0,t.length),t)},t.filterInPlace=v,t.filterInPlaceAsync=async function(e,t){for(let i=0;i<e.length;)!0===await t(e[i],i,e)?i++:e.splice(i,1);return e},t.move=b,t.flatMap=function(e,t){const i=[];for(const r of e)i.push(...w(t(r)));return i},t.includes=function(e,t){if(null==e)return!1;for(const i of e)if(t.valueOf()===i.valueOf())return!0;return!1},t.indexOf=function(e,t){if(null==e)return;let i=0;for(const r of e){if(t(r,i))return i;i++}},t.indexOfPrimitive=function(e,t){if(null==e)return;let i=0;for(const r of e){if(r===t)return i;i++}},t.includesAny=function(e,t){return m(e)&&m(t)&&e.some(e=>t.includes(e))},t.includesAll=function(e,t){if(p(e)||p(t))return!1;for(const i of t)if(!e.includes(i))return!1;return!0},t.eqlPrimitiveUnordered=function(e,t){if(null==e||null==t||e.length!==t.length)return!1;const i=(0,r.sortBy)(e,g),s=(0,r.sortBy)(t,g);return i.every((e,t)=>e===s[t])},t.pushNotSame=function(e,...t){for(const i of t)null==i||e.includes(i)||e.push(i);return e},t.pushUniq=function(e,...t){for(const i of t)null!=i&&null==(0,n.findEql)(e,i)&&e.push(i);return e},t.pushUniqBy=function(e,t,i){const r=e.map(i);for(const s of t){const t=i(s);r.includes(t)||(e.push(s),r.push(t))}return e},t.insertAt=function(e,t,...i){return e.splice(t,0,...i),e},t.insertUniq=function(e,t,i){for(let t=0;t<e.length-1;t++)if(i(e[t],e[t+1])>0)throw new Error("badly sorted array: "+e);for(let r=0;r<e.length;r++){const s=i(e[r],t);if(0===s)return e;if(s>0)return e.splice(r,0,t),e}return e.push(t),e},t.remove=function(e,...t){const i=e.length;return v(e,e=>t.every(t=>!(0,n.eql)(e,t))),i!==e.length},t.removeSame=function(e,...t){const i=e.length;return v(e,e=>t.every(t=>e!==t)),i!==e.length},t.compact=w,t.compactBlanks=function(e){return null==e?[]:(0,h.toA)(e).map(e=>(0,f.toS)(e).trim()).filter(e=>e.length>0)},t.compactBlankish=function(e){return null==e?[]:[...e].filter(s.notBlankish)},t.uniq=function(...e){if(null==e)return[];const t=[];for(const i of e)if(null!=i)for(const e of i)null!=e&&t.push(e);return S(t,e=>(0,l.isPrimitive)(e)?e:(0,a.stringify)(e))},t.uniqFirst=function(e){if(null==e)return[];const t=[];for(const i of e)null==i||(0,n.eql)(t[t.length-1],i)||t.push(i);return t},t.uniqSubstrings=function(e){if(null==e)return[];const t=w(e);if(0===e.length)return[];const i=[];for(const e of(0,r.sortBy)(t,e=>[-e.length,e.toLowerCase()]))i.some(t=>t.includes(e))||i.push(e);return(0,r.sortBy)(i,e=>t.indexOf(e))},t.uniqBy=S,t.uniqByLast=function(e,t=e=>(0,a.stringify)(e)){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&i.set(e,r)}return[...i.values()]},t.uniqBy2=function(e,t){const i=[];for(const r of e)null!=r&&i.every(e=>!t(r,e))&&i.push(r);return i},t.clear=function(e){return e.length=0,e},t.count=function(e,t){let i=0;for(const r of e)t(r)&&i++;return i},t.sum=function(e,t){let i=0;for(let r=0;r<e.length;r++)i+=t(e[r],r);return i},t.firstMatch=function(e,t){for(const i of w(t)){const t=e.exec(i);if(null!=t)return t}},t.commonPrefixLength=function(e,t){if(null==e||null==t)return 0;if(e===t)return e.length;if("string"==typeof e&&(e=[...e]),"string"==typeof t&&(t=[...t]),y(e,t))return e.length;let i=0;for(;e[i]===t[i];)i++;return i},t.anneal=function({array:e,expense:t,allowedDelta:i}){const r=Math.round(i);if(r<2)return e;for(let i=0;i<e.length-1;i++){const s=(0,u.randomInt)(Math.max(0,i-r),Math.min(e.length,i+r),[i]);if(null==s)continue;const n=Math.max(0,Math.min(s,i)-1),a=Math.min(e.length,Math.max(s,i)+1),o=t(e,n,a);b(e,i,s);const c=t(e,n,a);(0,l.lt)(o,c)&&b(e,s,i)}return e},t.range=function(e,t,i=e=>e){return P(e,t,1,i)},t.stepRange=P,t.diff=function(e,i,r=t.primitiveValueOfOrElse){const s=new Set(i.map(r));return e.filter(e=>!s.has(r(e)))},t.last=function(e){return null!=e?e[e.length-1]:void 0},t.commaList=function(e,t="or"){return e.length<=1?e.join(""):2===e.length?e.join(" "+t+" "):e.slice(0,-1).join(", ")+", "+t+" "+e[e.length-1]},t.arrToIterator=function(e){return e[Symbol.iterator]()},t.arrayEndsWith=function(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[e.length-t.length+i]!==t[i])return!1;return!0},t.findIndexes=function(e,t){const i=[];for(let r=0;r<e.length;r++)t(e[r],r)&&i.push(r);return i};const r=i(76790),s=i(22573),n=i(50357),a=i(98553),o=i(49769),l=i(34666),u=i(30976),c=i(42279),d=i(32639),h=i(59455),f=i(54993);function m(e){return null!=e&&(0,h.toA)(e).length>0}function p(e){return null==e||0===(0,h.toA)(e).length}function g(e){return(0,l.isPrimitive)(e)||(0,l.isPrimitiveArray)(e)?e:e.valueOf()}function y(e,t){return null!=e&&null!=t&&e.length===t.length&&e.every((e,i)=>e===t[i])}function v(e,t,i=!1){for(let r=0;r<e.length;)if(t(e[r],r,e))r++;else if(e.splice(r,1),i)break;return e}function b(e,t,i){if(t===i||t<0||i<0||t>=e.length||i>=e.length)return e;const r=e[t];return e.splice(t,1),e.splice(i,0,r),e}function w(e){return null==e?[]:v((0,h.toA)(e),e=>null!=e)}function S(e,t=e=>(0,a.stringify)(e)){const i=new Map;for(const r of e)if(null!=r){const e=t(r);null!=e&&(0,o.getOrSet)(i,e,()=>r)}return[...i.values()]}function P(e,t,i=1,r=e=>e){const s=[];if(e<t)for(let n=e;n<t;n+=i)s.push(r(n));else for(let n=e;n>t;n-=i)s.push(r(n));return s}t.primitiveValueOfOrElse=e=>{if((0,l.isPrimitive)(e))return e;if(Array.isArray(e))return(0,a.stringify)(e);if((0,d.isFunction)(e.valueOf))return e.valueOf();throw new Error("Cannot get primitive value for "+JSON.stringify(e))}},36783(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.copyArrayTo=function(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t.length=e.length,t}},76790(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sort=function(e){return d((0,r.compact)(e),r.toPrimitive)},t.sortByInPlace=d,t.sortUniqBy=h,t.sortUniq=function(e){return h(e,e=>e)},t.sortUniqByInPlace=function(e,t){return(0,s.copyArrayTo)(h(e,t),e)},t.isSorted=f,t.sortedBy=function(e,t){return e.every((i,r)=>0===r||t(i)>=t(e[r-1]))},t.sortBy=m,t.leastBy=p,t.least=function(e){return p(e,e=>e)},t.sortByCmp=function(e,t){return(0,r.compact)((0,c.toA)(e)).sort(t)},t.deepSortBy=function e(t,i){return m(t,i).map(t=>(0,n.isIterable)(t)?e(t,i):t)},t.pushSorted=function(e,t,i){const r=e.findIndex(e=>i(t)<i(e));return-1===r?e.push(t):e.splice(r,0,t),e};const r=i(40958),s=i(36783),n=i(41801),a=i(98553),o=i(49769),l=i(55835),u=i(34666),c=i(59455);function d(e,t){return f(e,t)?e:(0,s.copyArrayTo)(m(e,t),e)}function h(e,t){const i=new Map;for(const r of e)(0,o.getOrSet)(i,(0,a.stringify)(t(r)),()=>r);return m(i.values(),t)}function f(e,t=e=>e){if(e.length<=1)return!0;let i=t(e[0],0);for(let r=0;r<e.length;r++){const s=t(e[r],r);if(null==s||(0,u.gt)(i,s))return!1;i=s}return!0}function m(e,t){return(0,c.toA)(e).filter(e=>null!=e).map((e,i)=>({item:e,cmp:(0,l.map)(t(e,i),e=>[e,i])})).filter(e=>null!=e.cmp).sort((e,t)=>(0,u.cmp)(e.cmp,t.cmp)).map(e=>e.item)}function p(e,t){let i,r;for(const[s,n]of(0,c.toA)(e).entries()){if(null==n)continue;const e=t(n,s);null!=e&&(void 0===r||(0,u.cmp)(e,r)<0)&&(i=n,r=e)}return i}},34546(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.asPromise=async function(e){const t=await e;return(0,r.isFunction)(t)?t():t};const r=i(32639)},75761(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetPath=function(e){return(0,u.gt0)(e)?`/asset/${e}`:void 0},t.assetUrl=m,t.assetLinkAttrs=function({assetId:e,params:t,context:i}){const r=m({assetId:e,params:t,context:i});return(0,n.blank)(r)?{}:{href:r}},t.assetImgLink=p,t.assetImgActualLink=g,t.assetVideoLink=function({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/video/${(0,r.id2id)(e)}-${t}`,f(e,i))},t.assetSqImgAttrs=function({assetId:e,params:t,lazyLoad:i,size:r="m"}){return{...y({assetId:e,params:t,reducer:"sq",widths:l.SqWidths,lazyLoad:i}),sizes:("s"===r?80:"m"===r?160:320)*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1)+"px"}},t.assetImgAttrs=y;const r=i(58939),s=i(40958),n=i(22573),a=i(42659),o=i(11371),l=i(73722),u=i(31586),c=i(54993),d=i(29652);function h(e,t){return e+" "+t+"w"}function f(e,t){let i=null==t?void 0:(0,d.mergeURLSearchParams)(...t);const r=(0,c.toS)(e.v);return(0,n.blank)(r)||"1"===r||(i??=new URLSearchParams).append("v",r),i}function m({assetId:e,params:t,context:i}){if(null==e)return"";const s=null!=i?{context:i}:void 0;return(0,d.assembleFullPath)("/asset/"+(0,r.id2id)(e),f(e,t),s)}function p({assetId:e,reducer:t,width:i,params:s}){return(0,d.assembleFullPath)(`/img/${(0,r.id2id)(e)}/${t}/${(0,u.toGt0)(i)??320}`,f(e,s))}function g({assetId:e,assetFileId:t,params:i}){return(0,d.assembleFullPath)(`/img/${(0,s.compact)([(0,r.id2id)(e),t]).join("/")}/actual`,f(e,i))}function y({assetId:e,params:t,reducer:i,widths:s,lazyLoad:n,af:l}){if(null==(0,r.id2id)(e))return{src:"/images/clear-64.png"};0===(s=(s??[]).filter(u.gt0)).length&&s.push(320);const d=Math.min(...s),f={width:(0,c.toS)(d)},m=(0,a.fmtLocalToShort)(e.capturedAtLocal);null!=m&&(f.title=m);const y=p({assetId:e,params:t,reducer:i,width:d});n??=!0,f.src=y,f.loading=n?"lazy":"eager",f.decoding="async",i===o.ReducerNames.sq?f.height=(0,c.toS)(d):s.length>1&&(f.sizes=Math.round(d*(0,u.numericOr)(globalThis?.window?.devicePixelRatio,1))+"px");const v=s.map(r=>h(p({assetId:e,params:t,reducer:i,width:r}),r));return null!=l&&v.push(h(g({assetId:e,params:t,assetFileId:l.assetFileId}),l.width)),f.srcSet=v.join(","),f}},5233(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.retryOnReject_=async function(e,t){const i=(0,s.gt0)(t.timeoutMs)?()=>(0,n.thenOrTimeoutError)(e(),t.timeoutMs):e,o=t.maxRetries??0;if(o<=0)return i();const l=t.onRetryWaitUntil??(e=>(0,r.delay)(Math.max(250,(t.retryDelay??250)*(e??1))));let u=0;const c=async()=>{try{return await i()}catch(e){const i=(0,a.toError)(e);if(!1===t.errorIsRetriable?.(i)||u>=o)throw i;return u++,await l(u),c()}};return c()};const r=i(41400),s=i(31586),n=i(13538),a=i(70978)},17586(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.at=function(e,t){if(null!=e)return(t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length?void 0:e[t]}},82950(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.md2html=function(e){const t=e.replace(/</g,"<").split("\n"),i=[];let r=0;for(;r<t.length;){const e=t[r];"---"!==e?null==o(e)?null==l(e)?null==u(e)?(i.push(g(e)),r++):r=d(t,r,i):r=c(t,r,"ol",i):r=c(t,r,"ul",i):(i.push("<hr/>"),r++)}return i.join("\n")},t.code=function(e){return(0,s.blank)(e)?"":"```"+(0,a.toS)(e).replace(/`/g,"`")+"```"},t.b=function(e){const t=(0,a.toS)(e).trim();return 0===t.length?"":"**"+t+"**"},t.table=function(e){if(0===e.length)return"";const t=e=>e.replace(/\|/g,"\\|"),i=e=>"| "+e.map(t).join(" | ")+" |",[r,...s]=e,n="| "+r.map(()=>"---").join(" | ")+" |";return[i(r),n,...s.map(i)].join("\n")},t.ul=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map(e=>"- "+(0,a.toS)(e)).join("\n")},t.ol=function(...e){return(0,r.compactBlankish)((0,n.flatten)(e)).map((e,t)=>`${t+1}. ${(0,a.toS)(e)}`).join("\n")};const r=i(40958),s=i(22573),n=i(96249),a=i(54993);function o(e){const t=/^ *- (.*)$/.exec(e);return null!=t?t[1].trim():null}function l(e){const t=/^ *\d+\. (.*)$/.exec(e);return null!=t?t[1].trim():null}function u(e){const t=/^\|(.+)\|$/.exec(e);return null!=t?t[1]:null}function c(e,t,i,r){const s="ul"===i?o:l,n=[];let a=t;for(;a<e.length;){const t=s(e[a]);if(null==t)break;n.push(`<li>${g(t)}</li>`),a++}return r.push(`<${i}>\n${n.join("\n")}\n</${i}>`),a}function d(e,t,i){const r=['<table class="bmd">'];let s=t,n=[],a=null,o=!1;for(;s<e.length;){const t=u(e[s]);if(null==t)break;if(/^[-:\s|]+$/.test(t)){n=h(t),null!=a&&(r.push(p(a,"th",n)),a=null,o=!0),s++;continue}const i=m(t);o||null!=a?(null!=a&&(r.push(p(a,"th",n)),a=null,o=!0),r.push(p(i,"td",n))):a=i,s++}return null!=a&&r.push(p(a,"th",n)),r.push("</table>"),i.push(r.join("\n")),s}function h(e){return e.split("|").map(f)}function f(e){const t=e.trim(),i=t.startsWith(":"),r=t.endsWith(":");return i&&r?"center":r?"right":"left"}function m(e){return e.split(/(?<!\\)\|/).map(e=>e.trim().replace(/\\\|/g,"|"))}function p(e,t,i){return"<tr>"+e.map((e,r)=>{const s=i[r];return`<${t}${"center"===s?' class="ta-center"':"right"===s?' class="ta-right"':""}>${g(e)}</${t}>`}).join("")+"</tr>"}function g(e){return S(y(e))}function y(e){const t=[];let i="",r=0;const s=()=>{i.length>0&&(t.push({t:"text",v:i}),i="")};for(;r<e.length;){if(e.startsWith("```",r)){const i=e.indexOf("```",r+3);if(-1!==i){s(),t.push({t:"code",v:e.slice(r+3,i)}),r=i+3;continue}}if(e.startsWith("**",r)){const i=e.indexOf("**",r+2);if(-1!==i&&i>r+2){const n=e.slice(r+2,i);if(!n.includes("*")){s(),t.push({t:"bold",c:y(n)}),r=i+2;continue}}}if(e.startsWith("![",r)){const i=/^!\[([^\]]*)\]\(([^)]+)\)/.exec(e.slice(r));if(null!=i){s(),t.push(b(i[1],i[2])),r+=i[0].length;continue}}if("["===e[r]){const i=/^\[(\/?(?:br|p))\]/i.exec(e.slice(r));if(null!=i){s();const e=i[1].toLowerCase();t.push("br"===e?{t:"br"}:"p"===e?{t:"pOpen"}:{t:"pClose"}),r+=i[0].length;continue}const n=v(e,r);if(null!=n){s(),t.push(w(n.text,n.url)),r=n.end;continue}}i+=e[r],r++}return s(),t}function v(e,t){let i=1,r=t+1;for(;r<e.length&&i>0;){const t=e[r];if("["===t?i++:"]"===t&&i--,0===i)break;r++}if(0!==i||"("!==e[r+1])return null;const s=e.indexOf(")",r+2);if(-1===s)return null;const n=e.slice(t+1,r),a=e.slice(r+2,s);return 0===n.length||0===a.length?null:{text:n,url:a,end:s+1}}function b(e,t){return{t:"img",alt:e,url:t.startsWith("/")||/^https?:/i.test(t)?t:null}}function w(e,t){const i=t.startsWith("/");return{t:"link",text:e,url:i||/^(?:https?:|mailto:)/i.test(t)?t:null,ext:!i}}function S(e){return e.map(P).join("")}function P(e){switch(e.t){case"text":return e.v;case"code":return`<code>${e.v}</code>`;case"bold":return`<b>${S(e.c)}</b>`;case"img":return null==e.url?"":`<img src="${M(e.url)}" alt="${M(e.alt)}">`;case"link":{const t=g(e.text);if(null==e.url)return t;const i=M(e.url);return e.ext?`<a class="external-link" href="${i}" target="_blank" rel="noopener">${t}</a>`:`<a href="${i}">${t}</a>`}case"br":return"<br>";case"pOpen":return"<p>";case"pClose":return"</p>"}}function M(e){return e.replace(/"/g,""")}},99130(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BasePromise=void 0,t.BasePromise=class{promise;_resolve;_reject;constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}_state="pending";isPending(){return"pending"===this._state}isSettled(){return!this.isPending()}isResolved(){return"resolved"===this._state}isRejected(){return"rejected"===this._state}state(){return this._state}toLogJSON(){return{_ctor:this[Symbol.toStringTag],state:this.state()}}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}}},22573(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.blank=a,t.notBlank=o,t.notBlankToS=function(e){return o(e)&&"undefined"!==e?(0,n.toS)(e).trim():void 0},t.toNotBlank=function(e){if(null==e)return;const t=(0,n.toS)(e);return 0===t.length||0===t.trim().length?void 0:t},t.notBlankOr=function(e,t){if(null==e)return(0,s.tot)(t);const i=(0,n.toS)(e).trim();return i.length>0?i:(0,s.tot)(t)},t.notBlankAnd=function(e,t){return!a(e)&&t(e)},t.mapNotBlank=l,t.mapNotBlankOr=function(e,t,i){return(0,r.orElse)(l(e,t),i)},t.firstNotBlank=function(...e){for(const t of e)if("string"==typeof t&&t.trim().length>0)return t},t.blankish=c,t.notBlankish=function(e){return!c(e)};const r=i(55835),s=i(42279),n=i(54993);function a(e){return null==e||"string"==typeof e&&0===e.trim().length}function o(e){return!a(e)}function l(e,t){if(!1===e||null==e||""===e)return;const i=(0,n.toS)(e);return o(i)?t(i):void 0}const u=/^\s*(?:(?:null|undefined)\s*)?$/i;function c(e){return null==e||u.test((0,n.toS)(e))}},38639(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DISABLED=void 0,t.isBoolean=function(e){return"boolean"==typeof e},t.isTrue=s,t.toBoolean=function(e){return!!s(e)||!n(e)&&void 0},t.toNotBoolean=function(e){return!s(e)&&(!!n(e)||void 0)},t.boolToInt=function(e){return s(e)?1:0},t.isFalse=n,t.isDisabled=function(e){return n(e)||a.includes((0,r.toS)(e).toLowerCase())},t.or=function(e){return e.some(e=>s(e))},t.and=function(e){return e.every(e=>s(e))},t.maybeOr=function(e){let t;for(const i of e){if(!0===i)return!0;!1===i&&(t??=!1)}return t},t.maybeAnd=function(e){let t;for(const i of e){if(!1===i)return!1;!0===i&&(t??=!0)}return t};const r=i(54993);function s(e){if("boolean"==typeof e)return e;if(null==e)return!1;if(1===e)return!0;{const t=String(e).toLowerCase().trim();return["true","1"].includes(t)}}function n(e){if("boolean"==typeof e)return!e;if(null==e)return!1;if(0===e)return!0;const t=String(e).toLowerCase();for(const e of["false","0"])if(t===e)return!0;return!1}t.DISABLED="disabled";const a=["disable",t.DISABLED,"never","no","none","off"]},74310(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BoundedList=void 0;const r=i(31586);class s{maxLength;#t;#Ur=0;#Wr=0;constructor(e){if(this.maxLength=e,e>1e4)throw new Error("BoundedList.maxLength of "+e);this.#t=new Array(...(0,r.times)(e,()=>null))}#qr(e,t){return(e=Math.trunc(e)??0)<0&&(e+=this.#Ur),e<0||e>=this.#Ur?void 0:t((e+this.#Wr+this.maxLength)%this.maxLength)}at(e){return this.#qr(e,e=>this.#t[e])}get last(){return this.at(-1)}set(e,t){return this.#qr(e,e=>this.#t[e]=t)}get length(){return this.#Ur}set length(e){this.#Ur=(0,r.clamp)(0,this.#Ur,e)}clear(){this.length=0}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.#qr(e,e=>this.#t[e])}push(...e){for(const t of e.slice(-this.maxLength))this.#Ur<this.maxLength?this.#Ur++:(this.#Wr++,this.#Wr=this.#Wr%this.maxLength),this.#qr(this.#Ur-1,e=>{this.#t[e]=t});return this.#Ur}pop(){return this.#qr(this.#Ur-1,e=>(this.#Ur--,this.#t[e]))}unshift(...e){for(const t of e.reverse())this.#Ur<this.maxLength&&this.#Ur++,this.#Wr--,this.#qr(0,e=>{this.#t[e]=t,this.#Wr=e});return this.#Ur}shift(){return this.#qr(0,e=>(this.#Wr++,this.#Ur--,this.#t[e]))}shiftOrFirst(){return this.length>1?this.shift():this.at(0)}every(e){for(let t=0;t<this.#Ur;t++)if(!e(this.at(t),t))return!1;return!0}some(e){for(let t=0;t<this.#Ur;t++)if(e(this.at(t),t))return!0;return!1}forEach(e){for(let t=0;t<this.#Ur;t++)e(this.at(t),t)}map(e){const t=[];for(let i=0;i<this.#Ur;i++)t.push(e(this.at(i),i));return t}reduce(e,t){let i=t;for(let t=0;t<this.#Ur;t++)i=e(i,this.at(t),t);return i}reverse(){for(let e=0;e<Math.floor(this.#Ur/2);e++)this.#qr(e,t=>{this.#qr(this.#Ur-1-e,e=>{const i=this.#t[e];this.#t[e]=this.#t[t],this.#t[t]=i})});return this}toJSON(){return this.toA()}toA(){return[...this]}slice(e,t){return[...this].slice(e,t)}}t.BoundedList=s},7016(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CapturedAtSrcTypes=void 0,t.capturedAtSrcFromStat=function(e){return"stat"===e};const r=i(50989);t.CapturedAtSrcTypes=(0,r.strEnum)("tags","bname+stat","path+stat","bname","path","siblings","stat","unknown")},79666(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clone=function(e){return null==e?e:JSON.parse((0,r.stringify)(e))},t.shallowClone=function(e){return null==e?e:Array.isArray(e)?[...e]:"object"==typeof e?{...e}:e};const r=i(98553)},42659(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.yearMs=t.monthMs=t.weekMs=t.dayMs=t.hourMs=t.minuteMs=t.secondMs=void 0,t.toDate=p,t.fmtDateShort=g,t.fmtDateOnly=y,t.fmtDateCompact=function(e){if(null==e)return;const t=e instanceof Date?e:new Date(e);return`${f().format(t)} @ ${m().format(t)}`},t.fmtTimeCompact=function(e){if(null==e)return;const t=e instanceof Date?e:new Date(e);return m().format(t)},t.splitHMS=function(e){return(0,a.mapOr)(/^[0:]{1,4}/.exec(e),t=>[t[0],e.slice(t[0].length)],()=>["",e])},t.isDate=v,t.thisYear=function(){return(new Date).getFullYear()},t.ago=b,t.hence=function(e,t){return b(-e,t)},t.unixtime=function(e){const i=v(e)?e.getTime():(0,o.isNumber)(e)?e:Date.now();return Math.floor(i/t.secondMs)},t.fmtYMDHMS=function(e){return w(e).join("")},t.fmtIsoTime=function(e){const[,,,t,i,r]=w(e);return`${t}:${i}:${r}`},t.fmtIsoTimeMs=function(e){const t=p(e),[,,,i,r,s]=w(e);return`${i}:${r}:${s}.${(0,l.pad3)(t.getMilliseconds())}`},t.fmtIsoDateTime=function(e){const[t,i,r,s,n,a]=w(e);return`${t}-${i}-${r}T${s}:${n}:${a}`},t.fmtIsoDateTimeSpace=function(e){const[t,i,r,s,n,a]=w(e);return`${t}-${i}-${r} ${s}:${n}:${a}`},t.fmtIsoDateTimeMs=function(e){const t=p(e),[i,r,s,n,a,o]=w(e);return`${i}-${r}-${s} ${n}:${a}:${o}.${(0,l.pad3)(t.getMilliseconds())}`},t.fmtHMS=function(e,i={includeMs:!0}){const r=Math.floor(e/t.hourMs);e-=r*t.hourMs;const s=Math.floor(e/t.minuteMs);e-=s*t.minuteMs;const n=Math.floor(e/t.secondMs),a=Math.floor(e-n*t.secondMs);return(0,l.pad2)(r)+":"+(0,l.pad2)(s)+":"+(0,l.pad2)(n)+(i.includeMs?"."+(0,l.pad3)(a):"")},t.fmtIsoDuration=function(e){if(0===e)return"PT0S";const i=[],s=[];for(const r of S.slice(S.findIndex(t=>t.ms<=e))){const n=Math.floor(e/r.ms);e-=n*r.ms,n>0&&(r.ms>=t.dayMs?i:s).push(n+r.s)}return e>0&&s.push((0,o.toFixedStr)(e/t.secondMs,3)+"S"),"P"+i.join("")+((0,r.isEmpty)(s)?"":"T"+s.join(""))},t.fmtIsoDate=function(e){const t=v(e)?e:new Date(e);return t.getFullYear()+"-"+(0,l.pad2)(t.getMonth()+1)+"-"+(0,l.pad2)(t.getDate())},t.localToDate=P,t.fmtLocalToShort=function(e){return(0,a.map)(P(e),g)},t.nextMidnightTs=M,t.msUntilMidnight=function(){return M()-Date.now()},t.fmtAgo=T,t.fmtAgoCompact=function(e){return T(e,{compact:!0,justNowMs:6e4})},t.fmtSubExp=function(e){if(!(null==e||e.getTime()<Date.now()))return y(e)+" (in "+_(e.getTime()-Date.now(),{suffix:"",compact:!1})+")"},t.fmtElapsedMs=_,t.floorTimeToSecond=function(e){const t=(0,o.isNumber)(e)?e:v(e)?e.getTime():void 0;return void 0===t?void 0:1e3*Math.floor(t/1e3)};const r=i(40958),s=i(22573),n=i(45599),a=i(55835),o=i(31586),l=i(39926),u=i(51926),c=i(12168);t.secondMs=1e3,t.minuteMs=60*t.secondMs,t.hourMs=60*t.minuteMs,t.dayMs=24*t.hourMs,t.weekMs=7*t.dayMs,t.monthMs=32*t.dayMs,t.yearMs=365.25*t.dayMs;const d=(0,n.defer)(()=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),h=(0,n.defer)(()=>new Intl.DateTimeFormat(void 0,{day:"numeric",year:"numeric",month:"short"})),f=(0,n.defer)(()=>new Intl.DateTimeFormat(void 0,{day:"numeric",month:"short"})),m=(0,n.defer)(()=>new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}));function p(e){return e instanceof Date?e:new Date(e)}function g(e){if(null!=e)return e instanceof Date&&0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds()?h().format(e):d().format(e)}function y(e){if(null!=e)return h().format(e instanceof Date?e:new Date(e))}function v(e){return e instanceof Date&&!isNaN(e.getTime())}function b(e,t){return new Date((t?.getTime()??Date.now())-e)}function w(e){const t=p(e);return[String(t.getFullYear()),(0,l.pad2)(t.getMonth()+1),(0,l.pad2)(t.getDate()),(0,l.pad2)(t.getHours()),(0,l.pad2)(t.getMinutes()),(0,l.pad2)(t.getSeconds())]}const S=[{ms:t.yearMs,s:"Y"},{ms:t.weekMs,s:"W"},{ms:t.dayMs,s:"D"},{ms:t.hourMs,s:"H"},{ms:t.minuteMs,s:"M"}];function P(e){if(null==e||e<0)return;let t=e;const i=()=>{const e=t%100;return t=Math.floor(t/100),e},r=10*i(),s=i(),n=i(),a=i(),o=i(),l=i();return new Date(t,l-1,o,a,n,s,r)}function M(){return(new Date).setHours(24,0,0,0)}function T(e,t="ago"){const i="string"==typeof t?{suffix:t}:t;return _(Date.now()-e,i)}function _(e,i="ago"){const r="string"==typeof i?{suffix:i}:i,{compact:n=!1,justNowMs:a=1e3,suffix:o="ago"}=r,l=(0,s.blank)(o)?"":(0,u.ensurePrefix)(o," ");return e<a?"just now":n?e>=t.yearMs?Math.floor(e/t.yearMs)+"y"+l:e>=t.weekMs?Math.floor(e/t.weekMs)+"w"+l:e>=t.dayMs?Math.floor(e/t.dayMs)+"d"+l:e>=t.hourMs?Math.floor(e/t.hourMs)+"h"+l:e>=t.minuteMs?Math.floor(e/t.minuteMs)+"m"+l:Math.floor(e/t.secondMs)+"s"+l:e<t.minuteMs?(0,c.plur)(Math.floor(e/t.secondMs),"second")+l:e<t.hourMs?(0,c.plur)(Math.floor(e/t.minuteMs),"minute")+l:e<t.dayMs?(0,c.plur)(Math.floor(e/t.hourMs),"hour")+l:e<t.weekMs?(0,c.plur)(Math.floor(e/t.dayMs),"day")+l:e<t.yearMs?(0,c.plur)(Math.floor(e/t.weekMs),"week")+l:(0,c.plur)(Math.floor(e/t.yearMs),"year")+l}},12487(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deepEql=function(e,t,i){return i??={},!1!==i.memoize&&(i.memoize??=new WeakMap),o(e,t,i)};const r=i(38639),s=i(71696);function n(e,t,i){if(null==i||y(e)||y(t))return null;const r=i.get(e)?.get(t);return"boolean"==typeof r?r:null}function a(e,t,i,r){if(null==i||y(e)||y(t))return;let s=i.get(e);null!=s?s.set(t,r):(s=new WeakMap,s.set(t,r),i.set(e,s))}function o(e,t,i,r){if(null!=i?.comparator)return u(e,t,i,r);const s=l(e,t);return null!==s?s:u(e,t,i)}function l(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t||!y(e)&&!y(t)&&null}function u(e,t,i,r){i??={};const u=!1===i.memoize?void 0:i.memoize??=new WeakMap,d=i?.comparator,f=n(e,t,u);if(null!==f)return f;const m=n(t,e,u);if(null!==m)return m;if(d){const i=d(e,t,r);if(!1===i||!0===i)return a(e,t,u,i),i;const s=l(e,t);if(null!==s)return s}const y=(0,s.typeDetect)(e);if(y!==(0,s.typeDetect)(t))return a(e,t,u,!1),!1;a(e,t,u,!0);const v=function(e,t,i,r){switch(i){case"String":case"Number":case"Boolean":case"Date":return o(e.valueOf(),t.valueOf());case"Promise":case"Symbol":case"function":case"WeakMap":case"WeakSet":return e===t;case"Error":return p(e,t,["name","message","code"],r);case"Arguments":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"Array":return c(e,t,r);case"RegExp":return function(e,t){return e.toString()===t.toString()}(e,t);case"Generator":return function(e,t,i){return c(h(e),h(t),i)}(e,t,r);case"DataView":return c(new Uint8Array(e.buffer),new Uint8Array(t.buffer),r);case"ArrayBuffer":return c(new Uint8Array(e),new Uint8Array(t),r);case"Set":case"Map":return function(e,t,i){if(e.size!==t.size)return!1;if(0===e.size)return!0;const r=[],s=[];return e.forEach(function(e,t){r.push([e,t])}),t.forEach(function(e,t){s.push([e,t])}),c(r.sort(),s.sort(),i)}(e,t,r);case"Temporal.PlainDate":case"Temporal.PlainTime":case"Temporal.PlainDateTime":case"Temporal.Instant":case"Temporal.ZonedDateTime":case"Temporal.PlainYearMonth":case"Temporal.PlainMonthDay":return e.equals(t);case"Temporal.Duration":return e.total("nanoseconds")===t.total("nanoseconds");case"Temporal.TimeZone":case"Temporal.Calendar":return e.toString()===t.toString();default:return g(e,t,r)}}(e,t,y,i);return a(e,t,u,v),v}function c(e,t,i){const r=e.length;if(r!==t.length)return!1;if(0===r)return!0;let s=-1;for(;++s<r;)if(!1===o(e[s],t[s],i))return!1;return!0}function d(e){if(function(e){return"undefined"!=typeof Symbol&&"object"==typeof e&&void 0!==Symbol.iterator&&"function"==typeof e[Symbol.iterator]}(e))try{return h(e[Symbol.iterator]())}catch(e){return[]}return[]}function h(e){let t=e.next();const i=[t.value];for(;!1===t.done;)t=e.next(),i.push(t.value);return i}function f(e){const t=[];for(const i in e)void 0!==e[i]&&t.push(i);return t}function m(e){const t=[],i=Object.getOwnPropertySymbols(e);for(let r=0;r<i.length;r+=1){const s=i[r];!0===Object.getOwnPropertyDescriptor(e,s)?.enumerable&&t.push(s)}return t}function p(e,t,i,r){const s=i.length;if(0===s)return!0;for(let n=0;n<s;n+=1){const s=i[n],a=e[s],l=t[s];if("function"==typeof a&&"function"==typeof l){if(a.toString()!==l.toString())return!1}else if(!1===o(a,l,r,s))return!1}return!0}function g(e,t,i){if("function"==typeof e.eql){const i=e.eql(t);if((0,r.isBoolean)(i))return i}if("function"==typeof t.eql){const i=t.eql(e);if((0,r.isBoolean)(i))return i}if("function"==typeof e.toJSON)return g(e.toJSON(),t,i);if("function"==typeof t.toJSON)return g(e,t.toJSON(),i);if("object"==typeof e&&"object"==typeof t&&"function"==typeof e.constructor&&"function"==typeof t.constructor&&!1===g(e.constructor,t.constructor,i))return!1;const s=[...f(e),...m(e)],n=[...f(t),...m(t)];if(s.length&&s.length===n.length)return!1!==c(v(s).sort(),v(n).sort())&&p(e,t,s,i);const a=d(e),o=d(t);return a.length&&a.length===o.length?(a.sort(),o.sort(),c(a,o,i)):0===s.length&&0===a.length&&0===n.length&&0===o.length}function y(e){return null===e||"object"!=typeof e}function v(e){return e.map(function(e){return"symbol"==typeof e?e.toString():e})}},45599(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDefer=function(e){return null!=e&&"function"==typeof e&&"DeferImpl"===e.name},t.defer=function(e){let t,i,s=!1;const n=function(){if(s){if(null!=i)throw i;return t}try{return s=!0,t=e()}catch(e){throw i=(0,r.toError)(e),i}};return n.prior=()=>t,n.hasPrior=()=>s,n.applied=()=>s,n.reset=()=>{const e=t;return t=void 0,i=void 0,s=!1,e},n};const r=i(70978)},54900(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Deferred=void 0,t.isDeferred=n,t.ifDeferred=function(e){return n(e)?e:void 0};const r=i(57153),s=i(70978);function n(e){return null!=e&&"object"==typeof e&&e instanceof a}class a{id;static observe(e){return(new a).observe(e)}[Symbol.toStringTag]="Deferred";promise;startedAt=Date.now();settledAt=void 0;_resolve;_reject;_state=r.PromiseStates.pending;constructor(e){this.id=e,this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get state(){return this._state}get elapsedMs(){return(this.settledAt??Date.now())-this.startedAt}isPending(){return this._state===r.PromiseStates.pending}isResolved(){return this._state===r.PromiseStates.resolved}isRejected(){return this._state===r.PromiseStates.rejected}isSettled(){return!this.isPending()}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}resolve(e){return!this.isSettled()&&(this._state=r.PromiseStates.resolved,this.settledAt??=Date.now(),this._resolve(e),!0)}reject(e){return!this.isSettled()&&(this._state=r.PromiseStates.rejected,this.settledAt??=Date.now(),this._reject(e),!0)}async observeFn(e){try{const t=await e();return this.resolve(t),t}catch(e){throw this.reject((0,s.toError)(e)),e}}observe(e){return e.then(e=>this.resolve(e),e=>this.reject(e)),this}observeQuietly(e){return null==e?this.resolve(void 0):e.then(e=>this.resolve(e),()=>this.resolve(void 0)),this}toJSON(){return{$ctor:"fe.Deferred",...null==this.id?{}:{id:this.id},state:this._state,elapsedMs:this.elapsedMs}}}t.Deferred=a},41400(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.delayUntil=function(e){const t=((0,n.gt0)(e)?e:e.getTime())-Date.now();if(t<0){if(t>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-t+"ms")}return o(t).then(()=>t)},t.delay=o,t.later=function(e,t=1){const i=Math.max(1,Math.ceil(t)),n=s.isNode&&i<=1?setImmediate(e):setTimeout(e,i);return s.isBrowser||t<=r.secondMs?n:(0,a.maybeCall)(n,"unref")??n};const r=i(42659),s=i(35556),n=i(31586),a=i(68708);function o(e,t=!0){return new Promise(i=>{if(e<=0)i();else{const n=setTimeout(()=>i(),Math.ceil(e+.5));e>r.secondMs&&t&&s.isNode&&n.unref?.()}})}},33374(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDimensions=function(e){return null!=e&&(0,r.gt0)(e.width)&&(0,r.gt0)(e.height)},t.pickDims=function(e){return(0,s.pick)(e,"width","height")},t.isCloseAspectRatio=function(e,t,i=.05){return(0,r.gt0)(e)&&(0,r.gt0)(t)&&e>1==t>1&&Math.abs(e-t)<=i},t.dimGte=function(e,t){return e.width>=t.width&&e.height>=t.height},t.dimEql=function(e,t){return e.width===t.width&&e.height===t.height},t.fmtDim=function(e,t=" "){return`${e.width}${t}×${t}${e.height}`},t.dimToSize=function(e){return(0,a.pixels2size)(e.width*e.height)},t.dimSwap=o,t.maybeDimSwap=function(e,t){return(0,n.swappableRotation)(t)?o(e):e},t.maybeFlipInPlace=function(e,t){(0,n.swappableRotation)(t)&&([e.width,e.height]=[e.height,e.width])},t.isPortrait=function(e){return e.width/e.height<1},t.dmegapixels=function(e){return(0,a.megapixels)(l(e))},t.pixels=l;const r=i(31586),s=i(68708),n=i(21605),a=i(12168);function o(e){return{width:e.height,height:e.width}}function l(e){return((0,r.toGt0)(e?.width)??0)*((0,r.toGt0)(e?.height)??0)}},6875(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtDuration=function e(t,i={}){if(!(0,n.isNumber)(t))return"";if(0===t)return"0";if(!(0,n.gte0)(t))return"-"+e(Math.abs(t),i);const{units:r,sep:s="",suffix:a}=i,l=[],u=o.findIndex(e=>e.ms<=t);if(-1===u)return"";const c=null!=r?u+r:o.length;for(const e of o.slice(u,c)){const i=Math.floor(t/e.ms);t-=i*e.ms,i>0&&l.push({n:i,s:e.s})}if(0===l.length)return"";const d=l.map(e=>e.n+e.s).join(s);if(null==a)return d;return d+" "+(1===l[l.length-1].n?a.singular:a.plural)},t.parseDuration=function(e){if(null==e||!(0,a.isString)(e)&&!(0,n.isNumber)(e))return;if((0,n.isNumber)(e))return e;if((0,n.isDigits)(e))return(0,n.toInt)(e);if(0===(e=e.trim().toUpperCase()).length)return;const t=[...e.matchAll(l)];if(0===t.length)return;const i=[];for(const e of t){const t=u(e.groups?.value,e.groups?.type);null!=t&&i.push(t)}if(0===i.length)return;const r=i[0];return(0,n.lt0)(r)?r-i.slice(1).reduce((e,t)=>e+t,0):i.reduce((e,t)=>e+t,0)};const r=i(22573),s=i(42659),n=i(31586),a=i(51926),o=[{ms:s.yearMs,s:"y"},{ms:s.weekMs,s:"w"},{ms:s.dayMs,s:"d"},{ms:s.hourMs,s:"h"},{ms:s.minuteMs,s:"m"},{ms:s.secondMs,s:"s"},{ms:1,s:"ms"}],l=/[\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 u(e,t){const i=(0,n.toFloat)(e);if(null!=i){if((0,r.blank)(t))return i;switch(t.toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return i*s.yearMs;case"weeks":case"week":case"w":return i*s.weekMs;case"days":case"day":case"d":return i*s.dayMs;case"hours":case"hour":case"hrs":case"hr":case"h":return i*s.hourMs;case"minutes":case"minute":case"mins":case"min":case"m":return i*s.minuteMs;case"seconds":case"second":case"secs":case"sec":case"s":return i*s.secondMs;case"milliseconds":case"millisecond":case"millis":case"msecs":case"msec":case"ms":return i;default:throw new Error(`parseDuration(): unit ${t} was matched, but no matching case exists.`)}}}},50357(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eql=l,t.findEql=function(e,t){for(const i of e)if(l(t,i))return i},t.eqlSubset=function(e,t){if(null==e||null==t||(0,a.isPrimitive)(e)||(0,a.isPrimitive)(t))return e===t;if(!(0,n.isObject)(e)||!(0,n.isObject)(t))return!1;for(const i of(0,n.keys)(e))if(!l(e[i],t[i]))return!1;return!0},t.dateComparator=u,t.objComparator=c,t.functionComparator=d,t.weakRefComparator=h,t.pushObjComparator=function(e){f.push(e)},t.unshiftObjComparator=function(e){f.unshift(e)},t.setFieldComparator=function(e,t){m.set(e,t)},t.whyNotEql=function(e,t,i=25){const r=[];return function e(t,s,n=""){if(r.length>=i)return;if(t===s)return;if(typeof t!=typeof s)return void r.push({path:n,a:t,b:s});if("object"!=typeof t||null===t||null===s)return void r.push({path:n,a:t,b:s});if(Array.isArray(t)!==Array.isArray(s))return void r.push({path:n,a:t,b:s});if(Array.isArray(t)){const i=Math.max(t.length,s.length);for(let r=0;r<i;r++)e(t[r],s[r],`${n}[${r}]`);return}const a=Object.keys(t),o=Object.keys(s);for(const i of new Set([...a,...o]))e(t[i],s[i],n?`${n}.${i}`:i)}(e,t),r.length>0?r:void 0};const r=i(38639),s=i(12487),n=i(68708),a=i(34666),o=i(32639);function l(e,t){return(0,s.deepEql)(e,t,{comparator:p})}function u(e,t){if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime()}function c(e,t){if((0,n.isObject)(e)&&(0,o.isFunction)(e.$eql)){const i=e.$eql(t);if((0,r.isBoolean)(i))return i}if((0,n.isObject)(t)&&(0,o.isFunction)(t.$eql)){const i=t.$eql(e);if((0,r.isBoolean)(i))return i}}function d(e,t){return(0,o.isFunction)(e)&&(0,o.isFunction)(t)?e.toString()===t.toString():void 0}function h(e,t){return(0,n.isObject)(e)&&(0,n.isObject)(t)&&"WeakRef"===e.constructor?.name&&"WeakRef"===t.constructor?.name?e.deref()===t.deref():void 0}const f=[c,u,d,h],m=new Map;function p(e,t,i){if(null==e||null==t)return e===t;if(null!=i){const r=m.get(i)?.(e,t);if(null!=r)return r}for(const i of f){const r=i(e,t);if(null!=r)return r}return null}},26905(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IgnoredErrorNames=t.ErrorDelimiter=void 0,t.errorName=u,t.errorCode=c,t.errorErrno=d,t.shortStack=function(e,t=9){try{if((0,s.blank)(e)){const t=new Error;Error.captureStackTrace?.(t),e=t.stack}const i=(0,l.toS)(e).split("\n").filter(e=>!(0,s.blank)(e)&&e.trim().startsWith("at ")&&!h.test(e)).slice(0,t).map(e=>e.replace(/^\s*at /i,""));return(0,r.isEmpty)(i)?["(missing stack)"]:i}catch(e){return["Failed to captured stacktrace: "+e]}},t.asError=function(e){if((0,s.blank)(e))throw new Error("undefined error");if(e instanceof Error)return e;if(Array.isArray(e)){const t=e[0];return t instanceof Error?(e.length>1&&(t.errors=e.slice(1)),t):new Error(e.map(e=>(0,l.toS)(e)).filter(s.notBlank).join(", "))}{const t=m(e).replace(/^Error: /i,"");return new Error(t)}},t.errorToJson=function(e){return(0,o.compactValues)({message:e.message??String(e),stack:e.stack,name:u(e),code:c(e),errno:d(e),...(0,o.omit)(e,"name","message","code","errno")})},t.errorFromJson=function(e){return(0,o.assignFields)(new Error,(0,o.omit)(e,"_ctor"))},t.errorToArr=f,t.errorToS=m,t.throwNewError=function(e){throw new Error(e)};const r=i(40958),s=i(22573),n=i(96249),a=i(31586),o=i(68708),l=i(54993);function u(e){return null==e?void 0:[e?.name,e?.constructor?.name].find(e=>null!=e&&!t.IgnoredErrorNames.includes(e))?.toString()}function c(e){return null==e?void 0:(0,s.toNotBlank)(e?.code)}function d(e){return null==e?void 0:(0,a.toInt)(e?.errno)}t.ErrorDelimiter=": ",t.IgnoredErrorNames=["Error","String","Object","WrappedError"];const h=/shortStack|errorToVerbose|LogWriter|ContextualLogger/;function f(...e){const i=[];for(const t of e)null!=t&&(t instanceof Error?i.push(u(t),c(t),t?.message):i.push((0,l.toS)(t)));return(0,r.uniq)((0,r.compactBlankish)((0,n.flatten)((0,r.compact)(i).map(e=>e.split(t.ErrorDelimiter)))))}function m(...e){return f(...e).join(t.ErrorDelimiter)}},4188(e,t){"use strict";function i(e,t){if(e>=t.width/t.height){const i=t.width;return{width:i,height:Math.floor(i/e)}}{const i=t.height;return{width:Math.floor(i*e),height:i}}}Object.defineProperty(t,"__esModule",{value:!0}),t.fitInside=function(e,t){return i(e.width/e.height,t)},t.fitRatioInside=i},96249(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flatten=function(e,t=[]){for(const i of(0,r.toA)(e))if(null!=i)for(const e of(0,r.toA)(i))null!=e&&t.push(e);return t};const r=i(59455)},57924(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fmtList=s,t.orList=function(e){return s(e,"or")},t.andList=function(e){return s(e,"and")};const r=i(40958);function s(e,t){return null==(e=(0,r.uniq)((0,r.compactBlanks)(e)))||0===e.length?"":1===e.length?e.join(""):e.slice(0,-1).join(", ")+" "+t.trim()+" "+e[e.length-1]}},50268(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseHealthCheckSummary=t.HealthCheckLevelDescription=t.HealthCheckLevelToEmoji=t.HealthCheckLevels=t.HealthCheckSections=void 0,t.levelIsNotOK=function(e){return!u.includes(e)},t.healthCheckLevelToEmoji=function(e){return t.HealthCheckLevelToEmoji[e]},t.isHealthCheckResult=c,t.isHealthCheckSummary=function(e){return(0,n.isObject)(e)&&a.RunStates.has(e.state)&&(0,s.isBoolean)(e.settled)&&c(e)},t.newHealthCheckSections=function(){return t.HealthCheckSections.values.map(e=>({section:e,emoji:l[e],results:"Summary"===e?[{...t.BaseHealthCheckSummary,level:"pending",settled:!1,ts:Date.now(),msg:["⌚ Requesting health check results..."]}]:[]}))};const r=i(22573),s=i(38639),n=i(68708),a=i(62220),o=i(50989);t.HealthCheckSections=(0,o.strEnum)("Summary","Library","System","Tools");const l={Summary:"bookmark-tabs",Library:"library",System:"computer",Tools:"wrench"};t.HealthCheckLevels=(0,o.strEnum)("error","no-library","pending","stop-sync","warn","ok","disabled","installing");const u=[t.HealthCheckLevels.ok,t.HealthCheckLevels.disabled,t.HealthCheckLevels.pending,t.HealthCheckLevels.installing,t.HealthCheckLevels["no-library"]];function c(e){return(0,n.isObject)(e)&&!(0,r.blank)(e.id)&&!(0,r.blank)(e.section)&&t.HealthCheckLevels.has(e.level)&&!(0,r.blank)(e.msg)}t.HealthCheckLevelToEmoji={pending:"busy-dots",installing:"busy-dots","no-library":"new-yellow",ok:"green-check",warn:"warning","stop-sync":"pause",error:"error",disabled:"sleeping-face-desat"},t.HealthCheckLevelDescription={pending:"Health checks are running...",installing:"Installing photo and video tools…","no-library":"No library is open",ok:"OK",warn:"Warning","stop-sync":"Some health checks are preventing sync from running",error:"Some health checks failed: sync will not run",disabled:"Some health checks are disabled"},t.BaseHealthCheckSummary={id:"summary",section:t.HealthCheckSections.Summary}},29825(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HeifFamilyMimeTypes=t.HeifMimeTypes=void 0,t.isHeifMimeType=function(e){return null!=e&&t.HeifMimeTypes.includes(e)},t.isHeifFamilyMimeType=function(e){return null!=e&&t.HeifFamilyMimeTypes.includes(e)},t.HeifMimeTypes=["image/heic","image/heif"],t.HeifFamilyMimeTypes=[...t.HeifMimeTypes,"image/avif"]},11371(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReducerNames=void 0;const r=i(50989);t.ReducerNames=(0,r.strEnum)("fit","sq")},73722(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqWidths=t.SqSizes=t.FitSizeValues=t.FitSizes=void 0;const r=i(50989);t.FitSizes=(0,r.strEnum)("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),t.FitSizeValues=t.FitSizes.values,t.SqSizes=(0,r.strEnum)("s480","s240","s120","s60"),t.SqWidths=[60,120,240,480]},41801(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isIterable=n,t.isIterator=a,t.isAsyncIterable=o,t.isIterableLike=function(e){return n(e)||a(e)||o(e)},t.sliceIterable=function(e,t,i){if((0,s.lt0)(t))return[...e].slice(t,i);const r=e[Symbol.iterator]();if((0,s.gt0)(t))for(let e=0;e<t;e++)r.next();const n=[];for(let e=t;!(0,s.gte0)(i)||e<i;e++){const e=r.next();if(null==e.value&&!0===e.done||n.push(e.value),!0===e.done)break}return(0,s.lt0)(i)?n.slice(0,i):n},t.countIterable=function(e){let t=0;const i=e[Symbol.iterator]();for(;!0!==i.next().done;)t++;return t},t.asyncUniqBy=async function*(e,t){const i=new Set;for await(const r of e){const e=t(r);i.has(e)||(i.add(e),yield r)}},t.max=function(e,t){let i,r;for(const s of e){const e=t(s);(null==r||r<e)&&(r=e,i=s)}return i},t.iterate=l,t.chainAsyncIterators=u,t.iterToA=async function(...e){const t=[];for await(const i of u(...e))null!=i&&t.push(i);return t},t.iterateQuietly=function*(e,t){for(;;)try{const{value:t,done:i}=e.next();if(!0===i)break;yield t}catch(e){t?.(e)}},t.iterateQuietlyAsync=async function*(e,t){for(;;)try{const{value:t,done:i}=await e.next();if(!0===i)break;yield t}catch(e){t?.(e)}};const r=i(32639),s=i(31586);function n(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.iterator]}function a(e){return null!=e&&"string"!=typeof e&&"function"==typeof e.next}function o(e){return null!=e&&"string"!=typeof e&&"function"==typeof e[Symbol.asyncIterator]}async function*l(e){if(null==e)return;if(null==(e=await e))return;const t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():Symbol.iterator in e?e[Symbol.iterator]():e;let i;do{i=await t.next();const e=await i.value;null!=e&&!0!==i.done&&(yield e)}while(!0!==i?.done)}async function*u(...e){for(const t of e){if(null==t)continue;const e=await t;if(null==e)continue;const i=await((0,r.isFunction)(e)?e():e);yield*l(i)}}},98553(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JsonRevivableClasses=void 0,t.toJsonObject=l,t.stringify=u,t.stringifyPretty=function(e,t=2){return u(e,t)},t.fromJsonObject=c,t.parseJSON_=d,t.parseJSON=function(e){try{return null==e||(0,r.blank)(e)?void 0:d(e)}catch{return}};const r=i(22573),s=i(45599),n=i(23838),a=i(31586),o=i(68708);function l(e){return(new b).apply(e)}function u(e,t){return JSON.stringify(l(e),void 0,t)}function c(e){return null==e?e:(new w).apply(e)}function d(e){return c(JSON.parse(e.toString().trim()))}class h{static classes=new Map;static add(e){this.classes.set(e.name,e),this.revivableClassNames.reset()}static getClass(e){return(0,r.blank)(e)?void 0:this.classes.get(e)}static revivableClassNames=(0,s.defer)(()=>["Map","Set","Array",...this.classes.keys()]);static isRevivable(e){return this.revivableClassNames().includes(e.constructor?.name)}static addDefaults(){this.add({name:"Date",is:e=>e instanceof Date,toJSON:e=>({ts:e.getTime()}),fromJSON:e=>(0,a.mapInt)(e?.ts,e=>new Date(e))}),this.add({name:"RegExp",is:e=>e instanceof RegExp,toJSON:e=>({source:e.source,flags:e.flags}),fromJSON:e=>new RegExp(e.source,e.flags)}),this.add({name:"Error",is:e=>e instanceof Error,toJSON:e=>(0,o.pick)(e,"message","stack","code","errno"),fromJSON(e){const t=new Error(e.message);return t.stack=e.stack,t.code=e.code,t.errno=e.errno,t}}),this.add({name:BigInt.name,is:e=>(0,a.isBigInt)(e),toJSON:e=>({n:e.toString()}),fromJSON:e=>BigInt(e.n)})}}t.JsonRevivableClasses=h,h.addDefaults();const f="_id",m="_ref",p="_ctor",g="_id[]",y=["object","bigint"];function v(e){return null!=e&&y.includes(typeof e)}class b{idCount=0;maxIdObjs=new Set;objects=new Map;idAdders=new n.MultiMap;usedRefIds=new Set;apply(e){this.findMaxId(e),this.maxIdObjs.clear();const t=this._decycle(e);return this.finalize(),this.objects.clear(),this.idAdders.clear(),this.usedRefIds.clear(),t}maybeIncrIdCount(e){(0,a.gt)(e,this.idCount)&&(this.idCount=e+1)}findMaxId(e){if(v(e)&&!this.maxIdObjs.has(e))if(this.maxIdObjs.add(e),Array.isArray(e)){let t=0;e.length>0&&(0,o.isObject)(e[t])&&g in e[t]&&(this.maybeIncrIdCount(e[t]?.[g]),t++);for(;t<e.length;t++)this.findMaxId(e[t])}else if((0,o.isObject)(e)){this.maybeIncrIdCount(e[f]);for(const t of(0,o.propertyNames)(e))this.findMaxId(e[t])}}getId(e){return Array.isArray(e)?(0,a.toGt0)(e[0]?.[g]):(0,o.isObject)(e)?(0,a.toGt0)(e[f]):void 0}_decycle(e){if(!v(e))return e;const t=this.objects.get(e);if(null!=t)return this.usedRefIds.add(t),(0,o.fromEntries)([[m,t]]);const i=this.getId(e),r=i??++this.idCount;if(this.objects.set(e,r),Array.isArray(e)){const t=[];for(let i=0;i<e.length;i++)t[i]=this._decycle(e[i]);return null==i&&this.idAdders.add(r,()=>t.unshift((0,o.fromEntries)([[g,r]]))),t}const s={};this.objects.set(s,r);const n=e.constructor?.name;if(e.constructor!==Object&&(s[p]=n),null==i&&this.idAdders.add(r,()=>s[f]=r),e instanceof Map)s._=[...e.entries()].map(([e,t])=>[this._decycle(e),this._decycle(t)]);else if(e instanceof Set)s._=[...e.values()].map(e=>this._decycle(e));else{const t=h.getClass(n),i=t?.toJSON?.(e)??e.toJSON?.()??e;for(const e of(0,o.propertyNames)(i))s[e]=this._decycle(i[e])}return s}finalize(){for(const e of this.usedRefIds)for(const t of this.idAdders.get(e)??[])t()}}class w{objectsById=new Map;later=new n.MultiMap;apply(e){const t=this.vivify(e);return this.resolveDeferredReferences(),t}getRefId(e){return(0,o.isObject)(e)?(0,a.toGt0)(e[m]):void 0}ifRefIdResolved(e,t){const i=this.getRefId(e);return null!=i&&(this.objectsById.has(i)?t(this.objectsById.get(i)):this.later.add(i,()=>t(this.objectsById.get(i))),!0)}vivify(e){if(!v(e))return e;if(null!=this.getRefId(e))throw new Error("Reference ID found in root object");if(Array.isArray(e)){const t=[];let i;e.length>0&&(0,o.isObject)(e[0])&&g in e[0]&&(i=e.shift()[g],this.objectsById.set(i,t));for(let i=0;i<e.length;i++)this.ifRefIdResolved(e[i],e=>t[i]=e)||(t[i]=this.vivify(e[i]));return t}const t=e[f],i=e[p],r=h.getClass(i),s="function"==typeof r?.fromJSON;let n;if(n="Map"===i?new Map:"Set"===i?new Set:{},(0,a.gt0)(t)&&!s&&this.objectsById.set(t,n),n instanceof Map)for(const[t,i]of e._){const e=this.vivify(t);this.ifRefIdResolved(i,t=>n.set(e,t))||n.set(e,this.vivify(i))}else if(n instanceof Set)for(const t of e._)this.ifRefIdResolved(t,e=>n.add(e))||n.add(this.vivify(t));else if(!(n instanceof Date||n instanceof RegExp))for(const t of Object.keys(e))t!==f&&t!==p&&(this.ifRefIdResolved(e[t],e=>n[t]=e)||(n[t]=this.vivify(e[t])));return s&&(n=r.fromJSON(n),(0,a.gt0)(t)&&this.objectsById.set(t,n)),n}resolveDeferredReferences(){const e=this.later.keyCount();for(let t=0;t<e;t++)for(const e of this.later.keys())if(this.objectsById.has(e)){const t=this.later.get(e);if(null!=t){this.later.delete(e);for(const e of t)e()}}}}},57702(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isJson=n,t.isJsonObject=function(e){return(0,r.isObject)(e)&&!Array.isArray(e)&&n(e)};const r=i(68708),s=i(34666);function n(e){return!(null!=e&&!(0,s.isPrimitive)(e))||(Array.isArray(e)?e.every(n):!!(0,r.isObject)(e)&&e.constructor===Object&&Object.entries(e).every(([e,t])=>n(e)&&n(t)))}},56409(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Latch=void 0;const r=i(99130);let s=0;class n extends r.BasePromise{id;startedAt=Date.now();settledAt=void 0;[Symbol.toStringTag]="Latch";error;constructor(e=s++){super(),this.id=e}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}}t.Latch=n},30301(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lazy=function(e,t){let i,o,l=null;const u=[];function c(){return c.isStale()&&c.setResult(e()),o}return c.vacuum=function(){c.isStale()&&c.unset()},c.setResult=function(e){const r=o;return i=Date.now(),o=e,l=null,async function(e,i){if(i!==o)return;const r=await e,n=await i;if(l=n,u.length>0&&!(0,s.eql)(r,n))for(const e of u)e(n);null!=t&&t>0&&void 0!==n&&(0,a.setUnrefTimeout)(()=>c.vacuum(),t)}(r,e),e},c.isStale=function(){return null==i||(0,n.gt0)(t)&&i+t<=Date.now()},c.set=function(e){c.setResult(e)},c.unset=function(){c.setResult(void 0),i=void 0,l=null},c.clear=function(){const e=o;return c.unset(),e},c.prior=function(){return c.vacuum(),o},c.priorSync=function(){return c.vacuum(),l},c.refresh=function(){return c.setResult(e())},c.ttl=function(){return t},c.setTTL=function(e){t=(0,n.gt0)(e)?e:void 0},c.watch=function(e){e(c()),(0,r.delay)(1).then(()=>u.push(e))},c.watchLater=function(e){u.push(e)},c.toString=function(){return"[Lazy]"},c.toJSON=function(){},c.lastSetAgoMs=function(){return null==i?void 0:Date.now()-i},c.hasPrior=function(){return null!=i},c.setFn=function(t){e=t,c.unset()},c};const r=i(41400),s=i(50357),n=i(31586),a=i(65812)},44803(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevels=void 0;const r=i(50989);t.LogLevels=(0,r.strEnum)("fatal","error","warn","info","debug","trace")},49769(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getOrSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.getOrMaybeSet=function(e,t,i){if(null==t)throw new Error("null key");if(e.has(t))return e.get(t);{const r=i();return null!=r&&e.set(t,r),r}},t.deleteIf=function(e,t){for(const[i,r]of e.entries())t(i,r)&&e.delete(i)}},55835(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.map=n,t.mapTry=function(e,t){try{return n(e(),t)}catch{return}},t.map2=a,t.map3=function(e,t,i,r){return null==e||null==t||null==i?void 0:r(e,t,i)},t.orElse=o,t.mapOr=function(e,t,i){return null!=e?t(e):(0,r.tot)(i)},t.map2Or=function(e,t,i,r){return o(a(e,t,i),r)},t.defined=l,t.ifDefined=function(e,t){return void 0===e?void 0:t(e)},t.allDefined=function(e){return null!=e&&e.every(l)},t.firstDefined=function(...e){return e.find(l)},t.denull=function(e){return null==e||"null"===(0,s.toS)(e)?void 0:e},t.nulled=function(e){return null==e?null:e};const r=i(42279),s=i(54993);function n(e,t){return null==e?void 0:t(e)}function a(e,t,i){return null==e||null==t?void 0:i(e,t)}function o(e,t){return null!=e?e:(0,r.tot)(t)}function l(e){return null!=e}},23838(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MultiMap=void 0,t.groupBy=h,t.groupByValues=function(e,t){const i=h(e,t);return(0,s.sortBy)((0,c.toA)(i.values()),e=>t(e[0]))};const r=i(40958),s=i(76790),n=i(50357),a=i(98553),o=i(49769),l=i(55835),u=i(51926),c=i(59455);class d{store;static fromJSON(e){const t=new d;for(const[i,r]of Object.entries(e))t.add(i,...r);return t}constructor(e=new Map){this.store=e}get(e){return this.store.get(e)}has(e){return this.store.has(e)}includes(e,t){return!0===this.store.get(e)?.includes(t)}keyCount(){return this.store.size}isEmpty(){for(const e of this.store.values())if(e.length>0)return!1;return!0}valueCount(){return(0,r.sum)([...this.store.values()].map(e=>e.length),e=>e)}add(e,...t){const i=(0,o.getOrSet)(this.store,e,()=>[]);return i.push(...t),i}addUniq(e,...t){return(0,r.pushUniq)((0,o.getOrSet)(this.store,e,()=>[]),...t)}set(e,t){this.store.set(e,t)}delete(e,t){if(null==t)return this.store.delete(e);{const i=this.store.get(e);if(null==i)return!1;{const r=i.filter(e=>!(0,n.eql)(e,t));return 0===r.length?this.store.delete(e):this.store.set(e,r),i.length!==r.length}}}clear(){return this.store.clear(),this}*keys(){for(const[e,t]of this.store.entries())t.length>0&&(yield e)}*values(){for(const e of this.store.values())e.length>0&&(yield e)}vacuum(e=(e,t)=>(0,r.uniq)(t)){for(const t of this.keys()){const i=this.store.get(t),s=null==i?[]:e(t,i);(0,r.isEmpty)(s)?this.store.delete(t):this.store.set(t,s)}}*valuesFlat(){for(const e of this.store.values())for(const t of e)yield t}entriesArray(){return[...this.store.entries()].filter(([,e])=>(0,r.isNotEmpty)(e))}*entries(){for(const[e,t]of this.store.entries())t.length>0&&(yield[e,t])}*tuples(){for(const[e,t]of this.store.entries())for(const i of(0,c.toA)(t))null!=i&&(yield[e,i])}filterInPlace(e){let t=!1;for(const[i,s]of this.store.entries()){const n=(0,r.findIndexes)(s,t=>!e(i,t,s));if(n.length>0){t=!0;for(const e of n.reverse())s.splice(e,1)}0===s.length&&this.store.delete(i)}return t}filterKeysInPlace(e){let t=!1;for(const[i,r]of this.store.entries())e(i,r)||(t=!0,this.store.delete(i));return t}inverse(){const e=new d;for(const[t,i]of this.store.entries())for(const r of i)e.add(r,t);return e}findKeyByTuple(e){for(const[t,i]of this.tuples())if(e(t,i))return t}filterKeysByTuple(e){const t=[];for(const[i,r]of this.entries())r.some(t=>e(i,t))&&t.push(i);return t}toJSON(){const e={};for(const[t,i]of this.entries())e[(0,u.isString)(t)?t:(0,a.stringify)(t)]=i;return e}}function h(e,t){const i=new d;return e.forEach(e=>(0,l.map)(t(e),t=>i.add(t,e))),i}t.MultiMap=d},35556(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNode=t.isBrowser=void 0;const i=globalThis;t.isBrowser="object"==typeof i?.window&&"object"==typeof i?.document,t.isNode="string"==typeof i?.process?.versions?.node},31586(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isNumber=l,t.isInvalidNumber=u,t.isDigits=function(e){return c.test((0,o.toS)(e))},t.isNumeric=h,t.isBigInt=f,t.isFloat=function(e){return l(e)&&!Number.isInteger(e)},t.mapFinite=m,t.lt=function(e,t){return l(e)&&l(t)&&e<t},t.lte=p,t.gt=function(e,t){return l(e)&&l(t)&&e>t},t.gte=g,t.toFinite=function(e){return l(e)?e:void 0},t.finiteOrElse=function(e,t){return l(e)?e:t},t.diff=function(e,t){return l(e)&&l(t)?e-t:void 0},t.absdiff=function(e,t){return l(e)&&l(t)?Math.abs(e-t):void 0},t.safeDivide=function(e,t){return e/(0===t?1e-8:t)},t.approximates=function(e,t,i=.95){if(!l(e)||!l(t))return;if(e===t)return!0;if(i>=1)return!1;const r=Math.max(e,t)*(1-i);return y(t-r,t+r,e)},t.within=y,t.max_=function(...e){let t;for(const i of e)l(i)&&(null==t||t<i)&&(t=i);if(null==t)throw new Error("no numbers given to max()");return t},t.closeTo=function(e,t,i){return!(!l(e)||!l(t))&&Math.abs(e-t)<=i},t.isEquivalentNumber=function(e,t,i){return i<0||l(e)&&l(t)&&Math.abs(e-t)<=i},t.trunc=v,t.isToNumber=b,t.toInt=S,t.toFloat=P,t.toIntWithin=function(e,t,i){const r=S(e);return null!=r&&r>=t&&r<=i?r:void 0},t.toGt0=M,t.toGt=T,t.toGt0f=function(e){return _(e,0)},t.toGtf=_,t.lt0=function(e){return l(e)&&e<0},t.gt0=E,t.firstGt0=function(...e){for(const t of e){if(E(t))return t;const e=S(t);if(E(e))return e}},t.gtOrElse=function(e,t){return l(e)&&l(t)&&e>t?e:void 0},t.lte0=function(e){return l(e)&&e<=0},t.gte0=k,t.toGte0=function(e){return k(e)?e:void 0},t.mapInt=function(e,t){const i=S(e);return null==i?void 0:t(i)},t.mapFloat=function(e,t){const i=P(e);return null==i?void 0:t(i)},t.id=function(e){const t=S(e);return E(t)?String(t):void 0},t.mapNumeric=D,t.map2Numeric=function(e,t,i){return D(e,e=>D(t,t=>i(e,t)))},t.mapNumericOr=function(e,t,i){return l(e)?t(e):i},t.numericOr=function(e,t){return l(e)?e:(0,a.tot)(t)},t.round=I,t.toFixed=function(e,t){try{return D(e,e=>I(e*10**t)/10**t)}catch(e){return}},t.toFixedStr=function(e,t){return e.toFixed(t).replace(/\.0*$|(?<=\d\.\d+)0+$/,"")},t.roundToDecimalPlaces=C,t.toPrecisionMaybe=function(e,t){return m(e,e=>C(e,t))},t.sigFigs=function(e,t){if(!l(e)||0===e||0===t)return 0;const i=t-I(Math.ceil(Math.log10(Math.abs(e)))),r=Math.pow(10,Math.abs(i));return i<0?I(e/r)*r:I(e*r)/r},t.base2Ceil=function(e){return Math.pow(2,Math.ceil(Math.log2(e)))},t.base10Ceil=function(e){return Math.pow(10,Math.ceil(Math.log10(e)))},t.clamp=A,t.times=function(e,t){if(!E(e))return[];const i=Math.round(e);return i<=0?[]:[...Array(i)].map((e,i)=>t(i))},t.pct=function(e,t){return A(0,100,E(t)?I(100*(M(e)??0)/t):0)},t.fmtPct=function(e,t){if(null==e)return;const i=Math.round(e);return null==t||y(0,t,i)?i+"%":void 0},t.roundEven=function(e){return Math.sign(e)*Math.round(Math.abs(e)/2)*2},t.toSum=function(...e){let t=0;for(const i of e){if(!l(i))return;t+=i}return t};const r=i(76790),s=i(22573),n=i(51926),a=i(42279),o=i(54993);function l(e){return"number"==typeof e&&isFinite(e)}function u(e){return"number"==typeof e&&(isNaN(e)||!isFinite(e))}const c=/^\d+$/,d=/^[+-]?[\d.]+$/;function h(e){if(l(e)||f(e))return!0;try{if((0,n.isString)(e)&&(e=e.trim(),d.test(e)))return isFinite(parseFloat(e))}catch{}return!1}function f(e){return"bigint"==typeof e}function m(e,t){return l(e)?t(e):void 0}function p(e,t){return l(e)&&l(t)&&e<=t}function g(e,t){return l(e)&&l(t)&&e>=t}function y(e,t,i){return!(null==i||!l(i))&&([e,t]=(0,r.sort)([e,t]),g(i,e)&&p(i,t))}function v(e){if(!l(e))return;const t=Math.trunc(e);return 0===t?Math.abs(t):t}function b(e){return"function"==typeof e?.toNumber}function w(e,t){if((0,s.blank)(e)||u(e))return t.defaultValue;if(!0===t.strict&&!h(e))return t.defaultValue;if(l(e))return t.nton(e);if(f(e)){if(e>BigInt(Number.MAX_SAFE_INTEGER)||e<BigInt(Number.MIN_SAFE_INTEGER))throw new Error("precision loss for "+e);return t.nton(Number(e))}if(b(e))return t.nton(e.toNumber());try{const i=t.ston((0,o.toS)(e).trim());return l(i)?t.nton(i):t.defaultValue}catch{return t.defaultValue}}function S(e,t){return w(e,{defaultValue:void 0,nton:e=>v(e),ston:parseInt,...t})}function P(e,t){return w(e,{defaultValue:void 0,nton:e=>e,ston:parseFloat,...t})}function M(e){return T(e,0)}function T(e,t){const i=S(e);return null!=i&&i>t?i:void 0}function _(e,t){const i=P(e);return null!=i&&i>t?i:void 0}function E(e){return l(e)&&e>0}function k(e){return l(e)&&e>=0}function D(e,t){return l(e)?t(e):void 0}function I(e){return l(e)?e<0?-Math.round(-e):Math.round(e):0}function C(e,t){if(null==e)return 0;const i=Math.pow(10,t);return I(e*i)/i}function A(e,t,i){if(e>t||!l(e)||!l(t))throw new Error(`invalid clamp(${e}, ${t}, ${i})`);return l(i)?i<e?e:i>t?t:i:(e+t)/2}},68708(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isObject=d,t.isRecord=h,t.tap=function(e,t){return null!=t?t(e):"string"==typeof e?console.log(e):console.dir(e,{depth:null}),e},t.keys=f,t.keysWithDefinedOrNullValues=function(e){return null==e?[]:f(e).filter(t=>void 0!==e[t])},t.propertyNames=function*(e){if(null!=e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(yield t)},t.isEmptyObj=m,t.notEmptyObj=p,t.toCompactObj=function(e){const t=b(e);return m(t)?void 0:t},t.mapCompactObj=function(e,t){const i=b(e);return p(i)?t(i):void 0},t.values=g,t.entries=y,t.fromEntries=v,t.assignFields=function(e,t,i){const r=i?.assignNullish??!1;if(!d(t))return e;if(!0===i?.deleteExtraFields&&h(e))for(const i of Object.keys(e))i in t&&(r||null!=t[i])||delete e[i];for(const[s,n]of y(t))!0!==i?.omitKeys?.includes(s)&&(null!=n||r)&&(e[s]=n);return e},t.assignUndefinedFields=function(e,t,...i){if(null==t)return e;for(const r of i){const i=t[r];void 0!==i&&void 0===e[r]&&(e[r]=i)}return e},t.assignAllFields=function(e,t){for(const[i,r]of y(t??{}))e[i]=r;return e},t.definedValues=function(e){if(null==e)return;const t=y(e);if(t.every(([,e])=>void 0!==e))return e;const i=t.filter(([,e])=>void 0!==e);return(0,r.isEmpty)(i)?void 0:v(i)},t.compactValues=b,t.compactValuesDeep=function e(t){if(null!=t){if((0,u.isPrimitive)(t))return t;if(Array.isArray(t))return(0,r.compact)(t.map(e));{const i=(0,r.compact)(y(t).map(([t,i])=>(0,o.map)(e(i),e=>[t,e])));return 0===i.length?void 0:v(i)}}},t.compactBlankValues=function(e){if(null==e)return;const t=y(e).filter(([e,t])=>null!=e&&(0,n.notBlank)(t));return(0,r.isEmpty)(t)?void 0:v(t)},t.mapFields=w,t.mergeObjectsDeep=S,t.pick=function(e,...t){if(!d(e))return e;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickRequired=function(e,...t){if(!d(e))return;const i={};for(const r of t){if(null==e[r])return;i[r]=e[r]}return i},t.pickCompact=function(e,...t){if(!d(e))return;const i={};for(const r of t)void 0!==e[r]&&(i[r]=e[r]);return i},t.pickNonBlank=function(e,...t){if(!d(e))return e;const i={};for(const r of t){const t=e[r];(0,n.notBlank)(t)&&(i[r]=t)}return i},t.pickFirst=function(e,t,i=o.defined){if(d(e))for(const r of t)if(i(e[r]))return e[r]},t.pickDeep=function e(t,...i){if(!d(t))return t;if(Array.isArray(t))return t.map(t=>e(t,...i));const r={};function s(e,t){if(null==t)return;const i=r[e];r[e]=null==i?t:S(i,t)}for(const r of i){const[i,a]=(0,c.splitFirst)(r,".");if(i.includes("*")){const r=i.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp("^"+r.replace(/\*/g,".*")+"$","i");for(const i of f(t))if(o.test(i)){const r=t[i];null!=r&&s(i,(0,n.blank)(a)?r:e(r,a))}}else{const r=P(t,i);null!=r?.value&&s(r.key,(0,n.blank)(a)?r.value:e(r.value,a))}}for(const r of f(t))((0,l.toInt)(r)??-1)>=0&&s(r,e(t[r],...i));return r},t.pluck=P,t.pluckDeep=function e(t,i){if(null==t||(0,n.blank)(i))return;if(Array.isArray(t)){const s=(0,r.compact)(t.map(t=>e(t,i)));return(0,r.isEmpty)(s)?void 0:{key:s[0].key,value:(0,r.flatMap)(s,e=>e.value)}}const[s,a]=(0,c.splitFirst)(i,"."),o=P(t,s);if(null==o)return;if((0,n.blank)(a))return o;const l=e(o.value,a);return null==l?void 0:{key:o.key+"."+l.key,value:l.value}},t.omit=function(e,...t){return null==e?e:v(y(e).filter(([e])=>!t.includes(e)))},t.omitDeep=function e(t,i){if(null==t)return t;if(Array.isArray(t))return t.map(t=>e(t,i));if("object"==typeof t){const r={};for(const[s,n]of Object.entries(t))i.test(s)||(r[s]=e(n,i));return r}return t},t.isReqValued=M,t.allKeysDefined=function(e,...t){return null!=e&&t.every(t=>null!=e[t])},t.toReqValued=function(e){return M(e)?e:void 0},t.reqValuedOrElse=function(e){return M(e)?e:void 0},t.mapReqValued=function(e,t){return M(e)?t(e):void 0},t.onlyReqValued=function(e){return e.filter(M)},t.filter=function(e,t){return null==e?e:v(y(e).filter(([e,i])=>t(e,i)))},t.allKeys=function(e){const t=f(e);for(;null!=(e=Reflect.getPrototypeOf(e));)t.push(...Reflect.ownKeys(e).filter(e=>"string"==typeof e));return(0,r.uniq)(t)},t.maybeCall=function(e,t,...i){const r=e?.[t];return(0,a.isFunction)(r)?r.bind(e)(...i):void 0},t.firstValueCaseInsensitive=function(e,t){if((0,n.blank)(t))return;if(null!=e[t])return e[t];const i=t.toLowerCase().normalize();for(const t of f(e))if(i===t.toLowerCase().normalize()&&null!=e[t])return e[t]},t.flattenObject=function e(t){if(Array.isArray(t))return t.map(e);if("object"!=typeof t)return t;const i=w(t,(t,i)=>[t,e(i)]),r=g(i);return 1===r.length?r[0]:i};const r=i(40958),s=i(76790),n=i(22573),a=i(32639),o=i(55835),l=i(31586),u=i(34666),c=i(38453);function d(e){return null!=e&&"object"==typeof e}function h(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}function f(e){return d(e)?Object.keys(e).filter(t=>"string"==typeof t&&[void 0,!0].includes(e.propertyIsEnumerable?.(t))):[]}function m(e){if(null==e||"object"!=typeof e)return!0;for(const t in e)if(void 0!==e[t])return!1;return!0}function p(e){return!m(e)}function g(e){return f(e).map(t=>e[t])}function y(e){return null==e?[]:Object.entries?.(e)??f(e??{}).map(t=>[t,e[t]])}function v(e,t){if(null==e)return t;for(const i of e)if(null!=i&&Array.isArray(i)){const[e,r]=i;null!=e&&void 0!==r&&("object"!=typeof t&&(t={}),t[e]=r)}return t}function b(e){if(null==e)return;const t=y(e);if(t.every(([,e])=>null!=e))return e;const i=t.filter(([,e])=>null!=e);return(0,r.isEmpty)(i)?void 0:v(i)}function w(e,t,i={}){return v((0,r.compact)((0,s.sort)(f(e)).map(i=>t(i,e[i]))).filter(([e,t])=>null!=e&&void 0!==t),i)}function S(...e){const t=(0,r.compact)(e);if(0===t.length)return;if(1===t.length)return t[0];const i=t.filter(d);if(t.length!==i.length)return t;const s={};for(const e of(0,r.uniq)((0,r.flatMap)(i,f)))s[e]=S(...i.map(t=>t[e]));return s}function P(e,t){if(!d(e)||(0,n.blank)(t))return;if(t in e)return{key:t,value:e[t]};const i=new RegExp("^"+t.replace(/\*/g,".*")+"$","i");for(const t of f(e))if(i.test(t))return{key:t,value:e[t]}}function M(e){return g(e).every(e=>null!=e)}},97790(e,t){"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.Some=t.None=void 0,t.isOpt=s,t.opt=n,function(e){e.isDefined=!1,e.isEmpty=!0,e.get=()=>{},e.exists=()=>!1;const t=()=>e;e.map=t,e.flatMap=t,e.filter=t,e.forEach=t,e.getOrElse=e=>e(),e.orElse=e=>n(e()),e.zip1=t,e.zip2=t,e.zip3=t}(i||(i={})),t.None=i;class r{a;isDefined=!0;isEmpty=!1;constructor(e){this.a=e}get(){return this.a}exists(e){return e(this.a)}map(e){return new r(e(this.a))}flatMap(e){const t=e(this.a);return s(t)?t:n(t)}filter(e){return n(e(this.a)?this.a:void 0)}forEach(e){return e(this.a),this}getOrElse(){return this.a}orElse(){return this}zip1(e,t){return n(e).flatMap(e=>t(this.a,e))}zip2(e,t,i){return n(e).flatMap(e=>n(t).flatMap(t=>i(this.a,e,t)))}zip3(e,t,i,r){return n(e).flatMap(e=>n(t).flatMap(t=>n(i).flatMap(i=>r(this.a,e,t,i))))}}function s(e){return e instanceof r||e===t.None}function n(e){return s(e)?e:null!=e?new r(e):t.None}t.Some=r},97238(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_SEED=t.MIN_SEED=void 0,t.prngSeed=function(){return(0,s.randomInt)(t.MIN_SEED,t.MAX_SEED+1)},t.toSeed=function(e){return(0,r.toIntWithin)(e,t.MIN_SEED,t.MAX_SEED)};const r=i(31586),s=i(30976);t.MIN_SEED=1,t.MAX_SEED=99},39926(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.padding=a,t.leftPad=o,t.padNumeric=l,t.pad2=function(e){return l(e,2)},t.pad3=function(e){return l(e,3)},t.pad4=function(e){return l(e,4)};const r=i(31586),s=i(54993),n={};function a(e,t){if(t<1)return"";if(!(0,r.gte)(n[e]?.length,t)){let i=n[e]??e;for(;i.length<t;)i+=e;n[e]=i}return n[e].substring(0,t)}function o(e,t,i){if(0===i.length)throw new Error("leftPad() given empty pad");if((0,r.lt)(e,0))return"-"+o(String(Math.abs(e)),t-1,i);const n=(0,s.toS)(e);return a(i,t-n.length)+n}function l(e,t){return o((0,r.isNumber)(e)?(0,r.round)(e):"0",t,"0")}},67478(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0;var r=i(98553);Object.defineProperty(t,"parseJSON",{enumerable:!0,get:function(){return r.parseJSON}})},46891(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pluralize=function(e){if((0,r.blank)(e))return e;const t=s.get(e);return null!=t?t:null!=e.match(n)?e+"es":null!=e.match(a)?e.replace(/y$/i,"ies"):null!=e.match(o)?e+"s":e.endsWith("o")?e+"es":null!=e.match(l)?e.replace(l,"es"):e+"s"};const r=i(22573),s=new Map([["child","children"],["photo","photos"],["video","videos"]]),n=/([sxz]|ss|sh|ch)$/,a=/[^aeiou]y$/,o=/[aeiou]y$/,l=/is$/},34666(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CmpReverseFlag=void 0,t.isPrimitive=n,t.mapPrimitive=function(e,t){return n(e)?t(e):void 0},t.mapPrimitiveOr=function(e,t,i){return n(e)?t(e):i()},t.isPrimitiveArray=function(e){return Array.isArray(e)&&e.every(n)},t.isComparable=function e(t){return n(t)||t instanceof Date||Array.isArray(t)&&t.every(e)},t.cmp=o,t.lt=function(e,t){return o(e,t)<0},t.lte=function(e,t){return o(e,t)<=0},t.gte=function(e,t){return o(e,t)>=0},t.gt=function(e,t){return o(e,t)>0},t.cmpArr=l;const r=i(40958),s=i(54993);function n(e){switch(typeof e){case"number":return isFinite(e);case"string":case"boolean":return!0;default:return!1}}const a=["boolean","number","bigint","symbol","string","object","function"];function o(e,i){if(e===i)return 0;if(null==e)return-1;if(null==i)return 1;const r=typeof e,n=typeof i;if(!("string"!==r&&"symbol"!==r||"string"!==n&&"symbol"!==n)){const r=(0,s.toS)(e),n=(0,s.toS)(i),a=r.localeCompare(n);return r[0]===t.CmpReverseFlag&&n[0]===t.CmpReverseFlag?-a:a}return Array.isArray(e)&&Array.isArray(i)?l(e,i):r!==n?a.indexOf(r)-a.indexOf(n):e>i?1:e<i?-1:0}function l(e,t,i=!0){if((0,r.isEmpty)(e)&&(0,r.isEmpty)(t))return 0;const s=Math.min(e.length,t.length);for(let i=0;i<s;i++){const r=o(e[i],t[i]);if(0!==r)return r}return o(e.length,t.length)*(i?1:-1)}t.CmpReverseFlag="⤹"},20214(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.thenCollect=async function(e,t){const i=[];for(const s of(0,r.toA)(await e))if(null!=s){const e=await s;if(null!=e){const r=await t(e);null!=r&&i.push(r)}}return i},t.isPromiseLike=s,t.isPromise=function(e){return s(e)&&"function"==typeof e.catch&&"function"==typeof e.finally};const r=i(59455);function s(e){return null!=e&&"object"==typeof e&&"function"==typeof e.then}},57153(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PromiseStates=void 0;const r=i(50989);t.PromiseStates=(0,r.strEnum)("pending","resolved","rejected")},30976(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RandomChars=t.LowercaseChars=t.NumericChars=void 0,t.randomInt=a,t.randomInts=o,t.randomBoolean=function(e=.5){return Math.random()<=e},t.randomFloat=l,t.randomChars=function(e,i=t.RandomChars){const r=[];for(let t=0;t<e;t++)r.push(i[n(0,i.length)]);return r.join("")},t.pickRandom=function(e){return e[a(0,e.length)]},t.shuffle=function e(t){const i=[...t];for(let e=i.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));e!==t&&([i[e],i[t]]=[i[t],i[e]])}return t.length>2&&i.every((e,i)=>e===t[i])?e(t):i},t.sample=function(e,t){if(t<=0)return[];if(0===e.length)return[];const i=Math.min(t,e.length),r=[];for(const t of o(0,e.length,i))r.push(e[t]);return r},t.pickWeightedRandom=function(e){if((0,r.isEmpty)(e))return;const t=e.filter(e=>(0,s.gt0)(e.priority));let i=l(0,(0,r.sum)(t,e=>e.priority));return t.find(e=>(i-=e.priority,i<=0))};const r=i(40958),s=i(31586);function n(e,t){return Math.floor(Math.random()*(t-e))+e}function a(e,t,i){return null==i||0===i.length?n(e,t):o(e,t,1,i)[0]}function o(e,t,i,r){if(e=Math.ceil(e),(t=Math.floor(t))<e)throw new Error(`randomInts(): invalid range: ${e} > ${t}`);const s=t-e,a=new Set(r??[]);if(t===e&&0===s&&0===a.size&&1===i)return[e];const o=s-a.size;if(i>o)throw new Error(`randomInts(): cannot satisfy request: ${JSON.stringify({max:t,min:e,range:s,size:i,slotsRemaining:o})}`);const l=new Set;for(;l.size<i;){const i=n(e,t);a.has(i)||l.add(i)}return[...l]}function l(e,t){return Math.random()*(t-e)+e}t.NumericChars="0123456789",t.LowercaseChars="abcdefghijkmnopqrstuvwxyz",t.RandomChars=t.NumericChars+t.LowercaseChars},21605(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Rotations=void 0,t.isRotation=function(e){return(0,r.isNumber)(e)&&t.Rotations.includes(e)},t.normalizeRotation=s,t.swappableRotation=function(e){if(null==e)return!1;const t=s(e);return 90===t||270===t},t.quantizeRotation=function(e){const t=(e%360+360)%360;return t<45||t>=315?0:t>=45&&t<135?90:t>=135&&t<225?180:270};const r=i(31586);function s(e,t=!1){if(!(0,r.isNumber)(e))return;t&&(e=-e);const i=90*Math.round((e%360+360)%360/90);return 360===i?0:i}t.Rotations=[0,90,270,180]},62220(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RunStates=void 0;const r=i(50989);t.RunStates=(0,r.strEnum)("loading","welcome","ready","failed")},36324(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SafeExternalDomains=t.AllowedEmails=t.SafeExternalURLs=void 0,t.isSafeExternalUrl=function(e){if((0,r.blank)(e))return!1;if(t.SafeExternalURLs.includes(e))return!0;try{const i=new URL(e);return"mailto:"===i.protocol&&t.AllowedEmails.includes(i.pathname)||"https:"===i.protocol&&t.SafeExternalDomains.includes(i.hostname)}catch{return!1}};const r=i(22573);t.SafeExternalURLs=["https://reddit.com/r/photostructure","https://github.com/strukturag/libheif"],t.AllowedEmails=["hello@photostructure.com","support@photostructure.com","security@photostructure.com"],t.SafeExternalDomains=["phstr.com","photostructure.com","forum.photostructure.com","brew.sh","ffmpeg.org","www.msys2.org"]},5670(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceNames=void 0;const r=i(50989);t.ServiceNames=(0,r.strEnum)("main","desktop","web","sync","fix","info","test","logcat","logtail","list","billing","worker","test-worker","tool")},38453(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitFirst=function(e,t){const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]}},50989(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.strEnum=function e(...t){const i=Object.freeze([...new Set(t)]),r=new Map(i.map(e=>[e.toLowerCase(),e])),s=new Map(i.map((e,t)=>[e,t])),n={};for(const e of i)n[e]=e;const a=e=>null==e?void 0:r.get(e?.toLowerCase()),o=e=>null!=e?s.get(e):void 0,l=e=>null!=o(e),u=e=>null==e?void 0:l(e)?e:a(e);return{...n,values:i,length:i.length,has:l,includes:l,getCI:a,pick:(...e)=>i.filter(t=>e.includes(t)),omit:(...e)=>i.filter(t=>!e.includes(t)),indexOf:o,ordinal:e=>o(e)??i.length,toValid:u,firstValid:(...e)=>{for(const t of e){const e=u(t);if(null!=e)return e}},mapValid:(e,t)=>l(e)?t(e):void 0,cmp:(e,t)=>{const i=o(e),r=o(t);return null==i||null==r?void 0:i>r?1:i<r?-1:0},lt:(e,t)=>{const i=o(e),r=o(t);return null!=i&&null!=r&&i<r},next:e=>{const t=o(e);return null==t?void 0:i[t]},toReversed:()=>e(...[...i].reverse()),[Symbol.iterator]:()=>i[Symbol.iterator]()}}},51926(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isString=d,t.isBuffer=function(e){return"Buffer"===e?.constructor?.name},t.isBMP=h,t.charAt=function(e,t){if(h(e)){if((t=Math.trunc(t)||0)<0&&(t+=e.length),t<0||t>=e.length)return;return e[t]}return(0,s.at)([...(0,c.toS)(e)],t)},t.strlen=function(e){const t=m();return null!=t?(0,o.countIterable)(t.segment(e)):h(e)?e.length:[...e].length},t.strslice=p,t.substr=function(e,t,i){return h(e)?e.slice(t,null==i?void 0:t+i):p(e,t,null==i?void 0:t+i)},t.charArr=g,t.trimRight=function(e){return(0,c.toS)(e).replace(/\s+$/,"")},t.stripPrefix=y,t.stripPrefixes=function e(t,i){if(null==t)return"";const r=(0,c.toS)(t);for(const t of i)if(null!=t&&t.length>0&&r.startsWith(t))return e(r.slice(t.length),i);return r},t.stripSuffix=v,t.stripPrefixSuffix=function(e,{prefix:t,suffix:i}){return v(y(e,t),i)},t.ensurePrefix=b,t.ensureSuffix=w,t.ensurePrefixSuffix=function(e,{prefix:t,suffix:i}){return w(b(e,t),i)},t.ellipsize=function(e,t=80,i=0){if(null==e)return"";t=Math.max(1,(0,l.round)(t)),i=(0,l.clamp)(0,t-1,(0,l.round)(i));const r=g(e);return r.length<=t?r.join(""):r.slice(0,t-1-i).join("")+"…"+(i>0?r.slice(-i).join(""):"")},t.newlineRe=function(){return/\r?\n/g},t.trimLastNewline=function(e){return(0,c.toS)(e).replace(/\r?\n$/,"")},t.leftIndexOf=S,t.wrap=function e(t,i){const r=i?.maxLineLen??80,s=i?.prefix??"";if(Array.isArray(t)||t.includes("\n")){const r=(0,a.flatten)((0,u.toA)(t).map(e=>(0,c.toS)(e).split(/\r?\n/g)));return(0,a.flatten)(r.map(t=>e(t,i)))}if((t=b((0,c.toS)(t),s).trim()).length<=r)return[t];const n=S(t," ",r);if(n>s.length)return[p(t,0,n),...e(p(t,n+1),i)];{const r=t.indexOf(" ",s.length+1);return r>0&&r<t.length-1?[p(t,0,r),...e(p(t,r+1),i)]:[t]}},t.eqlStrings=function(e,t){return d(e)&&d(t)?e===t||e.normalize()===t.normalize():void 0},t.replaceAll=function(e,t,i){return""===t?e:e.split(t).join(i)},t.compressWhitespace=function(...e){return e.join(" ").replace(/\s+/g," ").trim()},t.splitLast=function(e,t){const i=(e=(0,c.toS)(e)).lastIndexOf(t);return-1===i?e:e.slice(i+t.length)},t.equalsIgnoreCase=P,t.firstIgnoreCase=M,t.includesIgnoreCase=function(e,t){return null!=M(e,t)};const r=i(40958),s=i(17586),n=i(22573),a=i(96249),o=i(41801),l=i(31586),u=i(59455),c=i(54993);function d(e){return"string"==typeof e}function h(e){for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)!==e.codePointAt(t))return!1;return!0}let f;function m(){if(void 0===f)try{f=new Intl.Segmenter(void 0,{granularity:"grapheme"})}catch{f=null}return f??null}function p(e,t,i){if(h(e))return t<0&&(t+=e.length),e.slice(t,i);{const r=m();return null!=r?(0,o.sliceIterable)(r.segment(e),t,i).map(e=>e.segment).join(""):[...(0,c.toS)(e)].slice(t,i).join("")}}function g(e){const t=m();return null==t?[...(0,c.toS)(e)]:[...t.segment(e)].map(e=>e.segment)}function y(e,t){const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.startsWith(r)?i.slice(r.length):i}function v(e,t){if(null==t)return e;const i=(0,c.toS)(e),r=(0,c.toS)(t);return r.length>0&&i.endsWith(r)?i.slice(0,-r.length):i}function b(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.startsWith(t)?e:t+e)}function w(e,t){return null==t||""===t?e:(e=(0,c.toS)(e),t=(0,c.toS)(t),e.endsWith(t)?e:e+t)}function S(e,t,i){null==i&&(i=e.length);for(let r=i;r>=0;r--)if(p(e,r).startsWith(t))return r;return-1}function P(e,t,{normalize:i=!0}={}){if(null==e||null==t)return!1;const r=(0,c.toS)(e),s=(0,c.toS)(t);return r.length===s.length&&(r===s||r.toLowerCase()===s.toLowerCase()||"function"==typeof r.localeCompare&&0===(i?r.normalize():r).localeCompare(i?s.normalize():s,void 0,{sensitivity:i?"base":"accent"}))}function M(e,t){return(0,r.isEmpty)(e)||(0,n.blank)(t)?void 0:e.find(e=>P(t,e))}},27313(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.awaitFields=async function(e){const t=(0,r.entries)(e),i=t.map(([e])=>e),s=await Promise.all(t.map(([,e])=>e)),n={};for(let e=0;e<i.length;e++)n[i[e]]=s[e];return n};const r=i(68708)},13538(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toNotTimeout=c,t.thenOrTimeoutMaybe=async function(e,t,i=!0){return c(await d(e,t,i))},t.thenOrTimeout=d,t.thenOrTimeoutAt=async function(e,t,i=!0){const r=t-Date.now();return r<=0?l.Timeout:d(e,r,i)},t.thenOrOnTimeout=async function(e,t,i){return t<=0?e:new Promise((r,s)=>{let n=!0;const o=setTimeout(()=>{n&&(n=!1,(async()=>{try{r(await i())}catch(e){s(e)}})())},t);(0,a.maybeCall)(o,"unref"),(async()=>{try{const t=await e;n&&(n=!1,clearTimeout(o),r(t))}catch(e){n&&(n=!1,s(e))}})()})},t.thenOrTimeoutError=h,t.thenOrTimeoutAtError=async function(e,t,i=!1){const r=t-Date.now();if(r<=0)throw new u.TimeoutError("timeout ("+(0,s.fmtHMS)(r)+")");return h(e,r,i)},t.thenOrTimeoutAs=async function({p:e,timeoutMs:t,as:i,unref:r=!1}){if(null==e)return(0,o.tot)(i);const s=await d(e,t,r);return s===l.Timeout?(0,o.tot)(i):s},t.raceOrTimeout=function(e,t){const i=(0,r.compact)(e);if(0!==i.length)return t>0&&i.push((0,n.delay)(t)),Promise.race(i)};const r=i(40958),s=i(42659),n=i(41400),a=i(68708),o=i(42279),l=i(83104),u=i(85556);function c(e){return e===l.Timeout?void 0:e}async function d(e,t,i=!1){return 1===(t=Math.round(t??0))?l.Timeout:t<=0?e:async function(e,t,i){return new Promise((r,s)=>{let n=!0;const a=setTimeout(()=>{n&&(n=!1,r(l.Timeout))},t);i&&a.unref?.(),(async()=>{try{const t=await e;n&&(n=!1,r(t))}catch(e){n&&(n=!1,s(e))}finally{clearTimeout(a)}})()})}(e,t,i)}async function h(e,t,i=!1){const r=await d(e,t,i);if(r===l.Timeout)throw new u.TimeoutError("timeout ("+(0,s.fmtHMS)(t)+")");return r}},42279(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOp=void 0,t.tot=function(e){return(0,r.isFunction)(e)?e():e},t.tol=async function(e){return(0,r.isFunction)(e)?e():e},t.firstDefinedThunk=function(e){for(const t of e){const e=t();if(null!=e)return e}},t.firstDefinedSuccess=function(e){for(const t of e)try{const e=t();if(null!=e)return e}catch{}};const r=i(32639);t.NoOp=()=>{}},83104(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0,t.Timeout=Symbol("timeout")},85556(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimeoutError=void 0,t.isTimeoutError=function(e){return e instanceof i||e instanceof Error&&"TimeoutError"===e.name};class i extends Error{name="TimeoutError"}t.TimeoutError=i},70978(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toError=function(e){return null==e?void 0:(0,r.isError)(e)?e:new Error(String(e))};const r=i(23541)},71696(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.typeDetect=function(e){const t=typeof e;if("object"!==t)return t;if(null===e)return"null";if(e===globalThis)return"global";if(Array.isArray(e)&&(!1===c||!(Symbol.toStringTag in e)))return"Array";if("object"==typeof window&&null!==window){if("object"==typeof window.location&&e===window.location)return"Location";if("object"==typeof window.document&&e===window.document)return"Document";if("object"==typeof window.navigator){if("object"==typeof window.navigator.mimeTypes&&e===window.navigator.mimeTypes)return"MimeTypeArray";if("object"==typeof window.navigator.plugins&&e===window.navigator.plugins)return"PluginArray"}if(("function"==typeof window.HTMLElement||"object"==typeof window.HTMLElement)&&e instanceof window.HTMLElement){if("BLOCKQUOTE"===e.tagName)return"HTMLQuoteElement";if("TD"===e.tagName)return"HTMLTableDataCellElement";if("TH"===e.tagName)return"HTMLTableHeaderCellElement"}}const r=c&&e[Symbol.toStringTag];if("string"==typeof r)return r;const u=Object.getPrototypeOf(e);return u===RegExp.prototype?"RegExp":u===Date.prototype?"Date":i&&u===Promise.prototype?"Promise":n&&u===Set.prototype?"Set":s&&u===Map.prototype?"Map":o&&u===WeakSet.prototype?"WeakSet":a&&u===WeakMap.prototype?"WeakMap":l&&u===DataView.prototype?"DataView":s&&u===m?"Map Iterator":n&&u===f?"Set Iterator":p&&u===g?"Array Iterator":y&&u===v?"String Iterator":null===u?"Object":Object.prototype.toString.call(e).slice(8,-1)};const i="function"==typeof Promise,r="undefined"!=typeof Symbol,s="undefined"!=typeof Map,n="undefined"!=typeof Set,a="undefined"!=typeof WeakMap,o="undefined"!=typeof WeakSet,l="undefined"!=typeof DataView,u=r&&void 0!==Symbol.iterator,c=r&&void 0!==Symbol.toStringTag,d=n&&"function"==typeof Set.prototype.entries,h=s&&"function"==typeof Map.prototype.entries,f=d&&Object.getPrototypeOf((new Set).entries()),m=h&&Object.getPrototypeOf((new Map).entries()),p=u&&"function"==typeof Array.prototype[Symbol.iterator],g=p&&Object.getPrototypeOf([][Symbol.iterator]()),y=u&&"function"==typeof String.prototype[Symbol.iterator],v=y&&Object.getPrototypeOf(""[Symbol.iterator]())},89937(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URI_SCHEME_ORDER_BY=t.PS_EXAMPLES_SCHEME=t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME=t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME=t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME=void 0,t.isFileUri=function(e){return null!=e&&String(e).startsWith("file://")},t.isPhotoStructureScheme=function(e){return null!=e&&s.includes(e)},t.isPhotoStructureUri=function(e){return null!=e&&n.some(t=>String(e).startsWith(t))},t.sortURIs=function(e){return(0,r.sortBy)(e,e=>{const i=e.split("://")[0],r=t.URI_SCHEME_ORDER_BY.indexOf(i);return[-1===r?t.URI_SCHEME_ORDER_BY.length:r,e]})};const r=i(76790);t.PS_LIBRARY_SCHEME="pslib",t.PS_LIBRARY_PROTOCOL=t.PS_LIBRARY_SCHEME+":",t.PS_LOCAL_FILE_SCHEME="psfile",t.PS_LOCAL_FILE_PROTOCOL=t.PS_LOCAL_FILE_SCHEME+":",t.PS_NETWORK_FILESYSTEM_SCHEME="psnet",t.PS_NETWORK_FILESYSTEM_PROTOCOL=t.PS_NETWORK_FILESYSTEM_SCHEME+":",t.PS_EXAMPLES_SCHEME="examples";const s=[t.PS_LIBRARY_SCHEME,t.PS_LOCAL_FILE_SCHEME,t.PS_NETWORK_FILESYSTEM_SCHEME],n=s.map(e=>e+"://");t.URI_SCHEME_ORDER_BY=[t.PS_LIBRARY_SCHEME,t.PS_LOCAL_FILE_SCHEME,t.PS_NETWORK_FILESYSTEM_SCHEME,t.PS_EXAMPLES_SCHEME,"file"]},29652(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isURLSearchParams=a,t.toURLSearchParams=o,t.mergeURLSearchParams=l,t.assembleFullPath=function(e,...t){const i=(0,n.toS)(l(...t));return e+((0,s.blank)(i)?"":"?"+i)},t.addQueryToFullpath=function(e,...t){const i=(0,n.toS)(l(...t));return(0,s.blank)(i)?e:e+(e.includes("?")?"&":"?")+i};const r=i(40958),s=i(22573),n=i(54993);function a(e){return"URLSearchParams"===e?.constructor?.name}function o(e){return null==e?void 0:a(e)?e:new URLSearchParams(e)}function l(...e){const t=(0,r.compact)(e.map(o)),i=t.shift();if(null!=i){for(const e of t)for(const[t,r]of e.entries())i.set(t,r);return i}}},12168(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SizeDescriptions=t.MP=t.TiB=t.GiB=t.MiB=t.KiB=t.TB=t.GB=t.MB=t.KB=t.decimalSep=t.thousandsSep=void 0,t.bytesToMB=function(...e){let i=0;for(const r of e)(0,n.isNumber)(r)&&(i+=r/t.MB);return(0,n.round)(i)},t.fmt=c,t.fmtToInt=function(e){return(0,r.mapNotBlank)(e,e=>(0,n.toInt)((0,l.replaceAll)(e,(0,t.thousandsSep)(),"")))},t.fmtMB=function(e,i=3){return f(e*t.MB,i)},t.fmtBytes=f,t.fmtMebi=function(e,t=3){if(0===e)return"0";const i=Math.floor(Math.log2(e)),r=Math.floor(i/10),s=Math.pow(2,10*r),a=h[r];return(0,n.sigFigs)(e/s,t)+" "+a},t.megapixels=function(e){return(0,n.sigFigs)(e/t.MP,2)},t.pixels2size=function(e){return e<76800?"tiny":e<345600?"small":e<2073600?"medium":"large"},t.plur=function(e,t,i){return null==e?"":(0,r.blank)(t)?c(e):(0===e?"no":c(e))+" "+(1===e?t:(i??(0,a.pluralize)(t)).trim())},t.plurMetric=function(e,t,i){return i??=(0,a.pluralize)(t),{count:c(e),desc:1===e?t:i}};const r=i(22573),s=i(45599),n=i(31586),a=i(46891),o=i(50989),l=i(51926),u=(0,s.defer)(()=>new Intl.NumberFormat);function c(e){return u().format(e)}t.thousandsSep=(0,s.defer)(()=>(0,l.replaceAll)(u().format(1111),"1","").charAt(0)),t.decimalSep=(0,s.defer)(()=>(0,l.replaceAll)(u().format(1.1),"1","").charAt(0)),t.KB=1e3,t.MB=1e3*t.KB,t.GB=1e3*t.MB,t.TB=1e3*t.GB,t.KiB=1024,t.MiB=1024*t.KiB,t.GiB=1024*t.MiB,t.TiB=1024*t.GiB;const d=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],h=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];function f(e,t=3){if(0===e)return"0";if(!(0,n.isNumber)(e))return"-";const i=Math.floor(Math.log10(e)),r=Math.floor(i/3),s=Math.pow(10,3*r),a=d[r];return(0,n.sigFigs)(e/s,t)+" "+a}t.MP=1e6,t.SizeDescriptions=(0,o.strEnum)("tiny","small","medium","large","original")},459(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UnreachableCaseError=void 0;class i extends Error{constructor(e){super(`Unreachable case: ${e}`),this.name="UnreachableCaseError"}}t.UnreachableCaseError=i},65812(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setUnrefTimeout=function(e,t){const i=setTimeout(e,t);return(0,r.maybeCall)(i,"unref")??i};const r=i(68708)},2322(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isChrome=l,t.isSafari=function(e){return o(e,r)&&!l(e)&&!u(e)},t.isFirefox=u,t.isIpad=function(e){return o(e,n)},t.isIphone=function(e){return o(e,a)};const i=/\bChrome\b/,r=/\bSafari\b/,s=/\bFirefox\b/,n=/\biPad\b/,a=/\biPhone\b/;function o(e,t){return null!=e&&null!=String(e).match(t)}function l(e){return o(e,i)}function u(e){return o(e,s)}},32790(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetQueryOrderByColumns=void 0,t.maybeQuote=function(e){return null!=(e=(0,s.toS)(e).trim()).match(/\s/)?`"${e}"`:e};const r=i(50989),s=i(54993);t.AssetQueryOrderByColumns=(0,r.strEnum)("capturedAt")},58939(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.id2id=n,t.idEql=function(e,t){return(0,r.map2Or)(n(e),n(t),(e,t)=>e===t,()=>!1)};const r=i(55835),s=i(31586);function n(e){if(null!=e)return(0,s.isNumber)(e)?e:"id"in e&&(0,s.isNumber)(e.id)?e.id:"assetId"in e&&(0,s.isNumber)(e.assetId)?e.assetId:"tagId"in e&&(0,s.isNumber)(e.tagId)?e.tagId:void 0}},12236(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressWithAssetsProps=t.InstallingToolsURI=t.EmptyRemovedURI=t.EmptyDeletedURI=t.RebuildingURI=t.SyncStatuses=void 0,t.isTerminalSyncStatus=function(e){return"done"===e||"failed"===e},t.isRebuildProgress=function(e){return t.RebuildingURI===e?.uri},t.noRecentAssetIdsProgress=function(e){return[t.EmptyDeletedURI,t.EmptyRemovedURI,t.InstallingToolsURI].includes(e?.uri)};const r=i(50989);t.SyncStatuses=(0,r.strEnum)("processing","paused","done","failed"),t.RebuildingURI="rebuilding://",t.EmptyDeletedURI="emptydeleted://",t.EmptyRemovedURI="emptyremoved://",t.InstallingToolsURI="installing://photo-and-video-tools",t.ProgressWithAssetsProps=["uri","volume","state","hed","dek","completePct","incompletePct","scanningPct","recentAssetIds"]},74607(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roots=t.TypeRoot=t.KwRoot=t.WhatRoot=t.LensRoot=t.CameraRoot=t.EventRoot=t.WhereRoot=t.WhoRoot=t.FsRoot=t.AlbumsRoot=t.WhenRoot=void 0,t.rootTagDef=function(e){return s[e]},t.maybeRootTagDef=function(e){return null==e?void 0:s[e]};const r=i(75020),s={When:{name:r.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:r.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:r.TagRoots.fs,description:"Directory hierarchy mirroring your original folder structure.",ordinal:3,icon:"folder",title:"Directories on your computer",label:"Directory"},Who:{name:r.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:r.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:r.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:r.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:r.TagRoots.Lens,description:"Lenses come from the LensMake, LensModel, and LensInfo metadata fields.",ordinal:8,icon:"camera",title:"Camera lens",label:"Lens"},What:{name:r.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:r.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:r.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"}};t.WhenRoot=s.When,t.AlbumsRoot=s.Albums,t.FsRoot=s.fs,t.WhoRoot=s.Who,t.WhereRoot=s.Where,t.EventRoot=s.Event,t.CameraRoot=s.Camera,t.LensRoot=s.Lens,t.WhatRoot=s.What,t.KwRoot=s.Keywords,t.TypeRoot=s.Type,t.Roots=Object.values(s)},79114(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.S=void 0;const r=i(50989);t.S=(0,r.strEnum)("plus","lite")},75020(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NotInfoPanelTags=t.LibraryTagName=t.TagRoots=t.TagGalleryProps=t.BeforeAfterStreamLimit=t.ThumbsPerSample=void 0,t.nextAssetsUrl=function(e,t){const i={};return(0,a.mapNumeric)(t.offset,e=>i.offset=e.toString()),(0,u.assembleFullPath)(`/api/t/${e}/assets`,i)},t.nextChildTagsUrl=function(e,t){const i={};return(0,a.gt0)(t.seed)&&(i.seed=t.seed.toString()),(0,a.gt0)(t.limit)&&(i.limit=t.limit.toString()),(0,a.gt0)(t.offset)&&(i.offset=t.offset.toString()),(0,a.gt0)(t.tc)&&(i.tc=t.tc.toString()),(0,u.assembleFullPath)(`/api/t/${e}/child-tags`,i)},t.ctxToS=function(e){return(0,n.stringify)({seed:e.seed,tagIds:(0,r.sort)([...e.tagIds])})},t.isTagRef=function(e){return null!=e&&!(0,l.isString)(e)&&(0,s.notBlank)(e.name)},t.isInfoTag=function(e){if(null==e)return!1;const i=(0,l.isString)(e)?e:e.tagPath?.[0];return!t.NotInfoPanelTags.includes(i)};const r=i(76790),s=i(22573),n=i(98553),a=i(31586),o=i(50989),l=i(51926),u=i(29652);t.ThumbsPerSample=80,t.BeforeAfterStreamLimit=8,t.TagGalleryProps=["tagId","tagPath","assetCount","assetIds","nextAssets","childTags","nextChildTags"],t.TagRoots=(0,o.strEnum)("When","Who","Where","What","Event","Camera","Lens","Albums","Keywords","Type","fs"),t.LibraryTagName="Library",t.NotInfoPanelTags=[t.TagRoots.When,t.TagRoots.Camera,t.TagRoots.Lens,t.TagRoots.Type,t.TagRoots.fs]},27776(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.urlSeed=void 0,t.mkHomeFullPath=c,t.mkTagFullPath=d,t.mkTagUri=h,t.mkTagSearchRoute=function(e){if(0===e.length)return{path:"/search"};if(1===e.length)return{path:"/search",query:{q:e[0]}};const t=e.slice(1).join("/");return{path:"/search",query:{q:`${e[0]}:${(0,r.maybeQuote)("/"+t+"/")}`}}},t.parentRoute=function(e,t){if("/tag"===e||e.startsWith("/tag/")){const i=(e.startsWith("/tag/")?e.substring(5):"").split("/").filter(e=>""!==e).map(decodeURIComponent);return i.length>0&&i.pop(),d(i,t,i.length>0)}return c()},t.contextToGalleryRoute=function(e){if(null!=e&&e.startsWith("search:"))return{name:"search",query:{q:e.substring(7)}};if(null!=e&&e.startsWith("tag:")){const t=e.substring(4).split("/");return{name:"tag",params:{path:t},query:f(t)}}return{name:"tag",query:f([])}};const r=i(32790),s=i(40958),n=i(30301),a=i(31586),o=i(97238),l=i(29652);function u(e,i){const r=(0,l.toURLSearchParams)(e);if(i||!(0,a.isDigits)(r?.get("seed"))){const e=(0,t.urlSeed)().toString();return r?.set("seed",e),r??{seed:e}}return r}function c(e){return d([],e,!0)}function d(e,t,i=!1){const r=h(e,t,i);return(0,l.assembleFullPath)(r.path,r.query)}function h(e,t,i=!1){return{path:"/tag/"+((0,s.isEmpty)(e)?"":e.map(encodeURIComponent).join("/")),query:u(t,i)}}function f(e){const{query:t}=h(e);return t instanceof URLSearchParams?Object.fromEntries(t.entries()):t}t.urlSeed=(0,n.lazy)(o.prngSeed,100)},23541(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isError=function(e){return null!=e&&e instanceof Error}},32639(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=function(e){return"function"==typeof e}},59455(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toA=function(e){return n(e)??[]},t.optToA=n;const r=i(41801),s=i(51926);function n(e){return Array.isArray(e)?e:null==e?void 0:(0,s.isString)(e)?[e]:(0,r.isIterable)(e)?Array.from(e):[e]}},54993(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toS=function(e){return n(e,",")},t.toStr=n;const r=i(98553),s={}.toString;function n(e,t=","){if(null==e)return"";switch(typeof e){case"string":return e;case"boolean":case"number":case"bigint":case"symbol":return String(e);default:return Array.isArray(e)?e.map(e=>n(e,t)).join(t):e.toString!==s?e.toString():(0,r.stringify)(e)}}},64526(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Library=void 0;const r=i(73568),s=i(27395),n=i(25764),a=i(38836),o=i(99331),l=i(45608),u=i(15056),c=i(9595),d=i(87290),h=i(38835),f=i(57159),m=i(34075),p=i(61704),g=i(95696),y=i(18454),v=i(13940),b=i(48604),w=i(19851),S=i(23560),P=i(34217),M=i(28874),T=i(2858),_=i(63870),E=i(15674),k=i(22573),D=i(38639),I=i(42659),C=i(56409),A=i(55835),x=i(68708),F=i(45678),O=i(74711),R=i(41844);class L extends a.EndableWrapper{start=Date.now();static#$r;static readyObservers=[];static instance(){const e=M.Settings.libraryDir.valueOrDefault,t=this.#$r?.rootDir.nativePath,i=!0===this.#$r?.isReadySync(),r=!0===this.#$r?.ended;return(0,p.nativePathsEqlSync)(t,e)&&!r?this.#$r:(0,S.isSyncService)()&&i?void(0,l.exit)({reason:`Library changed mid-run. Shutting down to pick up new library at ${e}.`,status:0}):((0,s.end)(this.#$r),this.#$r=(0,k.blank)(e)||!(0,T._libraryHasSettings)(e)?void 0:new L(e))}static observeReady(e){this.readyObservers.push(e)}static get priorInstance(){return this.#$r}static endPriorInstance(){const e=this.#$r;return this.#$r=void 0,(0,s.end)(e)}static async instanceReady(){(0,o.ending)()||!0!==L.instance()?.ended||L.endPriorInstance();const e=L.instance();return await(e?.ready()),e}static instanceRequired_(){const e=L.instance();if(null==e)throw new Error("Library is undefined"+h.FatalErrorFlag);return e}readyLatch=new C.Latch;rootDir;dataDir;constructor(e){super(`library.Library(${e})`,()=>this.onEnd(),n.EndableRanks.predb),this.rootDir=g.PosixFile.for(e),this.dataDir=(0,d.libraryDataDirPosixFile)(this.rootDir),this.logger.info("new()"),this.readyLatch.then(()=>{if(!this.ended)for(const e of L.readyObservers)e(this)},()=>{}),this.#ze()}get isPendingSetup(){return this.readyLatch.isPending()}#ze=(0,w.lazy)(async()=>{const e=e=>this.logger.awaitOrAbort(e);try{this.logger.debug("setup() started"),await e((0,T.readLibrarySettings)(this.rootDir.nativePath)),await e((0,d.setupLibraryDirs_)(this.rootDir)),await e((0,v.imageCacheDir_)());const t=await(0,A.map)((0,c.libraryPreviewsDir)(this.rootDir),t=>e((0,m.bestVolumeForPath)(t)));if((0,D.isTrue)(t?.remote)){const e=M.Settings.maxConcurrentImportsWhenRemote.valueOrDefault;M.Settings.maxConcurrentImports.hasValue()||(M.Settings.maxConcurrentImports.cliValue=e,(0,E.clearMaxWorkCaches)()),this.logger.warn(`Library previews are on a remote volume. Setting maxConcurrentImports to ${e}.`)}(0,S.isDbService)()&&(await e(this.dbLifecycle_()),await e(this.dbModelJanitor())),this.previews(),this.readyLatch.isPending()&&(this.logger.info("Library.setup() finished."),this.readyLatch.resolve())}catch(e){this.ended||(0,o.ending)()||(this.logger.warn("setup() failed:",{error:e}),y.HealthCheck.addError(e),this.readyLatch.reject(new f.WrappedError("Failed to start library",{cause:e})))}});ready(){return this.readyLatch.promise.then(()=>this,()=>{})}isReadySync(){return this.readyLatch.isResolved()}previews=(0,w.lazy)(()=>(0,x.tap)(new b.Previews((0,d.libraryPreviewsDirPosixFile)(this.rootDir)),e=>b.Previews.instance.set(e)));originalsDir=(0,w.lazy)(()=>(0,d.libraryOriginalsDirPosixFile)(this.rootDir));assetFileRepository=(0,w.lazy)(()=>new R.AssetFileRepository(this.originalsDir(),this.rootDir));libraryDbFile=(0,w.lazy)(()=>(0,u.pathToDb)(this.dataDir,"models"));dbLifecycle_=(0,w.lazy)(async()=>{if((0,S.isDbService)())return O.ModelDbLifecycle.forLibraryDir_(this.rootDir.nativePath);this.logger.throw("Library.dbLifecycle_: not a db service")});useReplica=(0,w.lazy)(async()=>(await this.dbLifecycle_()).useReplica);dbFsLock=(0,w.lazy)(async()=>(await this.dbLifecycle_()).openLock);modelDb=(0,w.lazy)(async()=>(await this.dbLifecycle_()).db);dbModelJanitor=(0,w.lazy)(async()=>F.ModelDbJanitor.for(await this.dbLifecycle_()));async pauseDbModelJanitor(){return(await this.dbModelJanitor())?.pauseInterval()}async resumeDbModelJanitor(){return(await this.dbModelJanitor())?.resumeInterval()}async runDbBackup_(){return(await this.dbModelJanitor())?.forceBackup_()}async maybeRunDbBackup_(){return(await this.dbModelJanitor())?.backup_()}onEnd=(0,w.lazy)(async()=>{this.logger.abortable.abort("Library.onEnd()"),this.readyLatch.reject(new r.AbortError(".onEnd()")),(0,o.ending)()||await(0,P.expedite)(async()=>{await(0,s.end)(this.dbModelJanitor.prior(),5*I.minuteMs),await(0,s.end)(this.modelDb.prior(),(0,_.commandTimeoutMs)()),await(0,s.end)(this.dbFsLock.prior(),(0,_.commandTimeoutMs)())}),this.logger.info("onEnd(): finished.")})}t.Library=L},87224(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.cleanupChildProcesses=k,t.cleanupStaleFiles=D,t.runPostLibraryCleanup_=async function({force:e,report:i=(0,m.syncReport)()}={}){await async function(e,i){if((0,a.isDbJanitorService)()){if(_.Progress.lazyVacuum.isStale()||e)try{await i.wrapSystemOp_({from:"Cleanup:Progress:vacuum",fn_:async()=>(_.Progress.lazyVacuum.refresh(),"Progress vacuum completed")})}catch(e){(0,t.logger)().warn("Failed to vacuum progress",{error:e})}try{await i.wrapSystemOp_({from:"Cleanup:problematicPaths",fn_:async()=>`Cleaned up ${E.ProblematicPath.cleanup()} expired problematic path(s)`})}catch(e){(0,t.logger)().warn("Failed to clean up problematic paths",{error:e})}}else i.writeSystemData({state:"unavailable",from:"Cleanup",details:"Skipping db cleanup: not a janitor service"})}(e,i);try{await i.wrapSystemOp_({from:"Cleanup:childProcesses",fn_:async()=>(await k(),"Child process cleanup completed")})}catch(e){(0,t.logger)().warn("Failed to clean up child processes",{error:e})}try{await i.wrapSystemOp_({from:"Cleanup:staleFiles",fn_:async()=>(await D(),"Stale file cleanup completed")})}catch(e){(0,t.logger)().warn("Failed to clean up stale files",{error:e})}try{await i.wrapSystemOp_({from:"Cleanup:compressLogs",fn_:async()=>{const e=await(0,y.compressInactiveLogs)({logDir:(0,d.logDir)()}),i=`Compressed ${e.compressed.length} log file(s); skipped ${e.skipped}, errors ${e.errors.length}`;return(0,t.logger)().tap({msg:i,result:i,meta:{errors:e.errors}})}})}catch(e){(0,t.logger)().warn("Failed to compress inactive logs",{error:e})}},t.fileCleanups=j,t.cancelFileAndProcCleanups=function(){b.Pids.instance()?.pauseInterval();for(const e of j())e.pauseInterval()},t.resumeFileAndProcCleanups=function(){b.Pids.instance()?.resumeInterval();for(const e of j())e.resumeInterval()};const r=i(76760),s=i(19851),n=i(50213),a=i(23560),o=i(56519),l=i(76187),u=i(49776),c=i(87290),d=i(46296),h=i(79267),f=i(32144),m=i(74128),p=i(70257),g=i(13940),y=i(68332),v=i(12495),b=i(95402),w=i(28874),S=i(40958),P=i(42659),M=i(64526),T=i(74711),_=i(49796),E=i(33978);async function k(){(0,t.logger)().info("Cleaning child processes..."),await(b.Pids.instance()?.killOldProcs())}async function D(){(0,t.logger)().info("Cleaning stale and temp files..."),await(0,o.mapAsync)({iter:j(),f:e=>e.cleanup()})}t.logger=(0,s.lazy)(()=>(0,n.mkLogger)("library.LibraryCleanup"));const I=(0,s.lazy)(()=>h.FileCleanup.for({name:"imageCacheCleanup",rootNativePath:g.imageCacheDir_,staleMs:w.Settings.imageCacheMs.valueOrDefault,isPrunable:e=>e.pathnames.includes(g.ImageCacheName)})),C=(0,s.lazy)(()=>h.FileCleanup.for({name:"previewWipCleanup",rootNativePath:c.libraryPreviewsDirPosixFile,staleMs:P.hourMs,isPrunable:e=>(0,p.isWip)(e)})),A=(0,s.lazy)(()=>h.FileCleanup.for({name:"syncReportCleanup",rootNativePath:()=>(0,c.librarySyncReportsDir)(),staleMs:w.Settings.syncReportRetention.valueOrDefault,minRetained:w.Settings.syncReportRetentionCount.valueOrDefault,isPrunable:e=>(0,p.isWip)(e)||e.ext===m.SyncReportExt||(0,f.isCsvExt)(e)})),x=(0,s.lazy)(()=>h.FileCleanup.for({name:"diagnosticsCacheCleanup",rootNativePath:()=>(0,r.join)((0,u.cacheDir_)(),"diagnostics"),staleMs:P.hourMs,isPrunable:e=>(0,p.isWip)(e)||".zip"===e.ext}));function F(e){return(0,p.isWip)(e)||(0,l.isSqliteFile)(e)}const O=(0,s.lazy)(()=>h.FileCleanup.for({name:"oldLibraryDbBackupCleanup",rootNativePath:()=>(0,T.libraryDbObjects_)().libraryDbBackupDir.sibling("backup"),staleMs:P.hourMs,isPrunable:F})),R=(0,s.lazy)(()=>h.FileCleanup.for({name:"libraryDbBackupCleanup",rootNativePath:()=>(0,T.libraryDbObjects_)().libraryDbBackupDir,staleMs:P.hourMs,minRetained:w.Settings.dbBackupRetentionCount.valueOrDefault,isPrunable:F}));async function L(){const e=await(M.Library.instance()?.dbLifecycle_());return null!=e&&e.useReplica?e.db.localBackupDir():void 0}const N=(0,s.lazy)(()=>h.FileCleanup.for({name:"libraryReplicaDbBackupCleanup",rootNativePath:L,staleMs:P.hourMs,minRetained:1,isPrunable:F}));function j(){return(0,S.compact)([I(),C(),(0,v.logDirCleanup)(),A(),x(),O(),R(),N()])}},19113(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryFileFiltersFor=function(e,{validateFile:t=!1}={}){const i=(0,r.expensiveFileFiltersFor)(e);return null!=(0,n.modelDb)()&&i.push({notShaBlocklistedFile:a.notShaBlocklistedFile}),t&&i.push({isValidFile:s.isValidFile}),i};const r=i(62105),s=i(181),n=i(94448),a=i(39604)},99335(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LibraryMaintenance=t.libraryMaintenance=void 0;const r=i(85970),s=i(74128),n=i(19851),a=i(50213),o=i(7282),l=i(23560),u=i(42659),c=i(15364),d=i(64526),h=i(87224),f=i(94448),m=(0,n.lazy)(()=>(0,a.mkLogger)("library.LibraryMaintenance"));t.libraryMaintenance=(0,n.lazy)(()=>new p);class p{#Gr=0;#Kr=!1;#Jr;#Yr=0;#Zr=0;#Xr;#Qr;#es;#ts;#is;#rs;#ss;constructor(e={}){this.#Xr=e.activeMaintenanceMinIntervalMs??((0,o.isTest)()?1e3:2*u.minuteMs),this.#Qr=e.activeTaskThreshold??((0,o.isTest)()?10:250),this.#es=e.isDbJanitorService??l.isDbJanitorService,this.#ts=e.library??(()=>d.Library.instance()),this.#is=e.modelDb??(()=>f.modelDb.prior()),this.#rs=e.runActiveLibraryDbMaintenance_??c.runActiveLibraryDbMaintenance_,this.#ss=e.runPostLibraryCleanup_??h.runPostLibraryCleanup_}onLibraryDbTaskResolved(){return this.#Gr++,this.runActiveMaintenance_.isIdle()?(null==this.#Jr?Number.POSITIVE_INFINITY:performance.now()-this.#Jr)>=this.#Xr||this.#Gr>=this.#Qr?this.#ns():void 0:(this.#Kr=!0,this.#ns())}async#ns(){try{await this.runActiveMaintenance_()}catch(e){m().warn("Active library maintenance failed",{error:e})}}runActiveMaintenance_=(0,r.serialized)(async(e={})=>{const{force:t,report:i=(0,s.syncReport)()}=e,r=this.#is(),n=null!=r&&r.writeCount<this.#Yr?0:this.#Yr;this.#Yr=n;const a=this.#as("LibraryMaintenance:active",{force:t,report:i,snapshot:n});if(this.#Jr=performance.now(),this.#Gr=0,null==a)return;this.#Kr=!1;const o=a.writeCount;await this.#rs({force:t,report:i}),this.#Yr=this.#Kr?o:a.writeCount});afterLibraryWorkBatch_=(0,r.serialized)(async(e={})=>{const{force:t,report:i=(0,s.syncReport)()}=e,r=this.#is(),n=null!=r&&r.writeCount<this.#Zr?0:this.#Zr;this.#Zr=n;const a=this.#as("LibraryMaintenance:postBatch",{force:t,report:i,snapshot:n});null!=a&&(await this.#ss({force:t,report:i}),this.#Zr=a.writeCount,await this.#os({force:t,report:i}))});async runAdminMaintenance_(e={}){const t=e.force??!0,i=e.report??(0,s.syncReport)();await this.runActiveMaintenance_({force:t,report:i}),await this.afterLibraryWorkBatch_({force:t,report:i})}async runFixCleanup_(e={}){const t=e.report??(0,s.syncReport)();await this.#ss({force:e.force??!0,report:t})}#as(e,t){const i=this.#is();if(null!=i)return!0===t.force||i.writeCount>t.snapshot?i:void m().debug("Skipping maintenance: no DB writes since last run",{from:e,writeCount:i.writeCount,snapshot:t.snapshot,lastWriteAt:i.lastWriteAt});t.report.writeSystemData({state:"unavailable",from:e,details:"Skipping maintenance: model DB is not open"})}async#os(e){if(!this.#es())return void e.report.writeSystemData({state:"unavailable",from:"LibraryMaintenance:dbBackup",details:"Skipping db backup: not a janitor service"});const t=this.#ts();if(null!=t)try{await e.report.wrapSystemOp_({from:"LibraryMaintenance:dbBackup",fn_:async()=>(!0===e.force?await t.runDbBackup_():await t.maybeRunDbBackup_(),"Database backup completed")})}catch(e){m().warn("Failed to run database backup",{error:e})}else e.report.writeSystemData({state:"unavailable",from:"LibraryMaintenance:dbBackup",details:"Skipping db backup: no library instance"})}}t.LibraryMaintenance=p},56992(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setVolumesTTL=async function(){const e=(0,u.volumeMetadataTtlMs)(),t=await m();(0,a.setVolumeMetadataTTL)(Math.max(t??e,e))},t.calcVolumesTTL=m;const r=i(19851),s=i(50213),n=i(76596),a=i(34075),o=i(28874),l=i(2858),u=i(63870),c=i(42659),d=i(31586),h=i(12168),f=(0,r.lazy)(()=>(0,s.mkLogger)("library.SetVolumesTTL"));async function m(){if(!(0,l.libraryHasSettings)())return;const e=[],t=o.Settings.minDiskFreeGb.defaultValue*h.GB;for await(const i of(0,a.libraryVolumes)()){if(!(0,d.gte)(i.volume.available,t))return void f().warn("Volume for "+i.dir+" is almost full (or unavailable): using default VolumeMetadataTTL",{free:(0,h.fmtBytes)(i.volume.available),minFree:(0,h.fmtBytes)(t)});e.push(i.volume.available)}const i=Math.min(...e)-t,r=Math.round(i/(25*h.MB)),s=(0,d.clamp)((0,u.volumeMetadataTtlMs)(),c.dayMs,r*c.secondMs);return f().info("Min free volume is "+(0,h.fmtBytes)(Math.min(...e))+". Extending VolumeMetadataTTL to "+(0,n.durationHMS)(s),{secondsUntilFull:r}),s}},77948(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryMetrics=A,t.systemInformation=async function(){const e=await(0,l.b)(),t=e?.l?.tier??"lite",i=o.HealthCheck.summary(),k=await A();return(0,S.compact)([{term:"Version",defn:v.version},{term:"Edition",defn:(0,n.EditionName)()},{term:"Health checks",defnClass:x[i.level],defnTitle:"Click to see all health checks",termURL:"/health",defn:i.msg[0]},{term:"Subscription",defnClass:t,defn:t,termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"},...(0,M.isTrue)(e?.ok)?[{term:"Licensed to",defn:e?.l?.sub},{term:"Expires or renews",defn:(0,_.mapOr)(e?.l?.exp,e=>(0,r.toIsoDate)(e),"--"),termURL:"/plans/billing?then=/about",defnTitle:"Click to manage your PhotoStructure subscription"}]:[],{term:"OS",defn:(0,c.osFullName)()},{term:"CPUs",defn:(0,c.CPUs)()},{term:"System load",defn:(0,_.map)(b.CpuUsage.instance().busyPct(),e=>(0,E.fmtPct)(e)+" busy")??"(unavailable)"},{term:"Concurrency",defn:`Target system use: ${Math.round(f.Settings.cpuBusyPercent.valueOrDefault)}% (${(0,w.maxConcurrentImports)()} concurrent imports, ${(0,w.sharpThreadsPerProcess)()} gfx/process)`},(0,h.isWebService)()?{term:"Web uptime",defn:(0,T.fmtDuration)((0,p.runtimeMs)())}:void 0,(0,P.mapNotBlank)((0,d.procDeviceModel)(),e=>({term:"Device",defn:e})),{term:"Current user",defn:await(0,y.username)()+((0,E.gte0)((0,g.userid)())?" (userid: "+(0,g.userid)()+", groupid: "+(0,a.groupid)()+")":"")},(0,m.libraryHasSettings)()?{term:"Library path",defn:f.Settings.libraryDir.valueOrDefault,defnClass:"library"}:void 0,null==k?void 0:{term:"Library metrics",termURL:"https://photostructure.com/faq/metrics/",defn:k},{term:"Log directory",defn:(0,s.logDir)()},{term:"Log level",termURL:"https://photostructure.com/faq/error-reports/#log-levels",defn:(0,u.defaultLogLevel)()}]).filter(({term:e,defn:t})=>(0,P.notBlank)(e)&&(0,P.notBlank)(t))};const r=i(21330),s=i(46296),n=i(17344),a=i(44142),o=i(18454),l=i(81674),u=i(66184),c=i(96175),d=i(24540),h=i(23560),f=i(28874),m=i(2858),p=i(84968),g=i(24526),y=i(94174),v=i(37805),b=i(14854),w=i(15674),S=i(40958),P=i(22573),M=i(38639),T=i(6875),_=i(55835),E=i(31586),k=i(51926),D=i(12168),I=i(43487),C=i(54017);async function A(){if(null==I.Asset.db())return;const e=[];e.push((0,D.plurMetric)(I.Asset.dao.shownCount(),"asset"));const t=C.AssetFile.dao.assetFileCountByMimeTypeRoots();for(const i of t){const t=(0,k.stripSuffix)(i.mimeTypeRoot,"/");e.push((0,D.plurMetric)(i.assetFileCount,t+" file"))}return e}const x={pending:"pending",installing:"pending",ok:"ok","no-library":"warn",warn:"warn","stop-sync":"warn",error:"fail",disabled:"ok"}},59727(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadLibrary_=async function(){const e=(0,s.mkLogger)("info"),t=(0,r.libraryDataDirPosixFile)();if(null==t)return e.throw("No library is currently set up.");if(!await t.isDirectory())return e.throw("Your library data dir, "+t+", is missing.");e.info("Waiting for library to spin up...");const i=n.Library.instanceRequired_();return await i.ready(),await i.dbLifecycle_(),i};const r=i(87290),s=i(50213),n=i(64526)},31503(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogArgs=void 0;const r=i(23560),s=i(83210),n=i(28874),a=i(38639);t.LogArgs={beforeParse:e=>{const t=((0,r.canTailLogs)()?', "PS_TAIL_LOGS=true"':"")+' and "PS_LOG_STDOUT=true".';return e.option("-v, --verbose",(0,r.canTailLogs)()?'Verbose logging from all processes. Shortcut for "--info --tail". Caution: noisy during imports!':"Verbose logging. Equivalent to --info."),e.option("--error",`Emit "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=error"${t}`),e.option("--warn",`Emit "warn" and "error" messages from this process to stdout. Sets "PS_LOG_LEVEL=warn"${t}`),e.option("--info",`Emit "info", "warn", and "error" messages from this process to stdout. CAUTION: NOISY. Sets "PS_LOG_LEVEL=info"${t}`),e.option("--debug",`Emit "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: VERY NOISY. Sets "PS_LOG_LEVEL=debug"${t}}`),e.option("--trace",`Emit "trace", "debug", "info", "warn", and "error" messages from this process to stdout. CAUTION: SUPER DUPER NOISY. Sets "PS_LOG_LEVEL=trace"${t}}`),(0,r.canTailLogs)()&&e.option("--tail",'Emit log messages from both this process and all other concurrently running PhotoStructure processes (including main, web, and sync!) on this host to stdout. This can be really helpful in seeing how PhotoStructure\'s processes are coordinating work. Caution: very noisy especially during imports. Sets "PS_TAIL_LOGS=true".'),e},afterParse:e=>{const t=(0,a.isTrue)(e.error),i=(0,a.isTrue)(e.warn),o=(0,a.isTrue)(e.info)||(0,a.isTrue)(e.verbose)||(0,a.isTrue)(e.v),l=(0,a.isTrue)(e.debug),u=(0,a.isTrue)(e.trace);u?n.Settings.logLevel.cliValue="trace":l?n.Settings.logLevel.cliValue="debug":o?n.Settings.logLevel.cliValue="info":i?n.Settings.logLevel.cliValue="warn":t&&(n.Settings.logLevel.cliValue="error"),(0,s.isDaemon)(e)?(n.Settings.tailLogs.cliValue=!1,n.Settings.logStdout.cliValue=!1):((0,a.isTrue)(e.tail)&&(n.Settings.tailLogs.cliValue=!0),(t||i||o||l||u)&&(n.Settings.logStdout.cliValue=!0,(0,r.canTailLogs)()&&(n.Settings.tailLogs.cliValue=!0)),(n.Settings.tailLogs.valueOrDefault||n.Settings.logStdout.valueOrDefault)&&n.Settings.logLevel.isUnset()&&(n.Settings.logLevel.cliValue="info"))}}},46628(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagFilesWithAlbums=async function(e){const t=[];for(const i of e){t.push(...w(await(0,d.readTags)(i)));for(const e of l.Settings.tagAlbumFilenames.values)t.push(...w(await(0,c.readRawTags)(i.sibling(e))))}return v().tap({msg:"tagFilesWithAlbums()",result:(0,h.uniqTagPaths)(t),meta:{files:e}})},t.albumsFromTags=w;const r=i(48884),s=i(19851),n=i(50213),a=i(81168),o=i(74417),l=i(28874),u=i(97573),c=i(38148),d=i(40538),h=i(42231),f=i(40958),m=i(22573),p=i(68708),g=i(75020),y=i(54993),v=(0,s.lazy)(()=>(0,n.mkLogger)("curators.AlbumTagger"));function b(e){return(0,m.blank)(e)?void 0:l.Settings.tagAlbumTitleHierarchies.valueOrDefault?(0,u.keywordToPath)(e):[e]}function w(e){if(null==e)return[];const t=(0,f.uniq)((0,r.flatMap)(l.Settings.tagAlbumTitle.values,t=>(0,p.pluckDeep)(e,t)?.value)),i=(0,f.compact)(t.map(b));if((0,f.isEmpty)(i))return[];if(i.length>1)return v().tap({level:"info",msg:"albumFromFile()",result:i.map(e=>[g.TagRoots.Albums,...e])});const s=i[0],n=(0,r.first)(l.Settings.tagAlbumDescription.values,t=>(0,p.pluckDeep)(e,t)?.value),u=(0,f.isEmpty)(s)?"(blank title)":(0,a.firstSubstringIgnoreCase)(l.Settings.tagAlbumsExcluded.values,[...s,(0,y.toS)(n)].join(" ")),c=null==u?[g.TagRoots.Albums,...s]:void 0;if(null!=c){const t={name:c[c.length-1],description:n};for(const i of l.Settings.tagAlbumDate.values){const r=(0,o.parseJsonDateToMillis)((0,p.pluckDeep)(e,i)?.value);if(null!=r){t.releasedAt=r;break}}c[c.length-1]=t}return v().tap({level:"info",msg:"albumFromFile()",result:(0,f.compact)([c]),meta:{titles:i,desc:n,whyExclude:u}})}},88224(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAndUpsertAsset_=async function(e){const t=await e.getExistingAssetFiles();M().info("tagAndUpsertAsset()",{asset:e,existing_uris:t.map(e=>e.uri)});const i=t.find(e=>e.isPrimary),s=i?.posixFile_();if(null==i||null==s)return M().throw("tagAndUpsertAsset(): no existing or primary asset file"+a.InternalErrorFlag,{asset:e,existingPrimaryAssetFile:i,primaryVariant:s,doNotSend:!0,fatal:!1});const n=e.getPrimary();n?.id!==i.id&&(M().warn("Primary asset changed; using a different variant for tagging.",{newPrimary:i.uri,priorPrimary:n?.uri}),await e.setPrimary_(i));const u=await(0,c.thenCollect)(t,e=>e.posixFile_()),f=e.getAssetFiles().map(e=>e.uri),m=e.getTagPaths(),p=e.getCapturedAt(),g=await _({primaryVariation:s,files:u,priorTagPaths:m,capturedAt:p,uris:f});M().info("tagAndUpsertAsset",g);const{geoResult:y}=g;if(null!=y?.countryName){const e=o.Settings.tagGeoCountryFlags.valueOrDefault?y.countryCode:void 0,t=(0,r.flaggedCountryName)(y.countryName,e);h.Tag.dao.findOrCreate(y.tagPath.slice(0,2)).maybeUpsertDisplayName(t)}const v=g.add.find(e=>(0,l.leafIsExcluded)(e,o.Settings.keywordBlocklist.values));if(null!=v){if(!0!==e.shown)return M().info("this asset has an excluded tag, and it wasn't shown yet, so we're removing it.",{excludedTag:v}),await d.Asset.dao.remove({assetId:e.id,blocklistShas:!1,unlinkAssetFiles:!1}),M().throw("tagAndUpsertAsset(): asset had excluded tag. Removed.",{excludedTag:v,uris:f,files:u.map(e=>e.nativePath)});M().info("this asset has an excluded tag, marking excluded",{excludedTag:v}),e.excludedAt=Date.now()}return e.applyTagPathDeltas(g),await e.updateFromFiles(),e.upsert(),g},t.tagAsset=_;const r=i(62556),s=i(19851),n=i(50213),a=i(38835),o=i(28874),l=i(42231),u=i(40958),c=i(20214),d=i(43487),h=i(48723),f=i(46628),m=i(63175),p=i(4407),g=i(58886),y=i(32646),v=i(48144),b=i(60047),w=i(6186),S=i(42003),P=i(43723),M=(0,s.lazy)(()=>(0,n.mkLogger)("curators.AssetTagger"));async function T(e,t){let i,r;for(const s of e){const e=await t(s);if(null!=e){const t=(0,l.joinTagPath)(e);(null==r||t.length>r.length||t.length===r.length&&t<r)&&(i=e,r=t)}}return i}async function _({primaryVariation:e,files:t,priorTagPaths:i,capturedAt:r,uris:s}){const n=[],a=(0,u.uniqBy)([e,...t],e=>e.nativePath);if(o.Settings.tagCamera.valueOrDefault){const e=await T(a,m.cameraTagFile);null!=e&&(M().debug("Camera tag:",e),n.push(e))}if(o.Settings.tagLens.valueOrDefault){const e=await T(a,b.lensTagFile);null!=e&&(M().debug("Lens tag:",e),n.push(e))}let c;if(o.Settings.tagGeo.valueOrDefault)for(const e of a){const t=await(0,y.geoTagFile)(e);if(null!=t){n.push(t.tagPath),c=t;break}}const d=await(0,p.dateTagFile)(e,r);null!=d&&(M().debug("Date tag for "+e+":",d),n.push(d));const h=await(0,P.whoTagFiles)(a)??[];M().debug("whoTagFiles for "+e+":",h),n.push(...h);const _=await(0,v.keywordTagFiles)(a,h);if(null!=_&&(M().debug("Keyword tags for "+e+":",_),n.push(..._)),o.Settings.tagFileType.valueOrDefault){const t=await(0,S.typeTagFiles)(a);null!=t&&(M().debug("MIME type tags for "+e+":",t),n.push(...t))}const E=await(0,g.tagAssetPaths)(s);null!=E&&(M().debug("file paths for uris",{uris:s,arr:E}),n.push(...E));const k=await(0,f.tagFilesWithAlbums)(a);null!=k&&(M().debug("Album tags for "+e+":",k),n.push(...k));const D=(0,l.omitAncestorTags)((0,u.uniqBy)(n.map(w.normalizeTagPath).filter(e=>null!=e),l.joinTagPath)),I=(0,w.tagDeltas)(i,D);return M().info("tagAsset("+e+")",{priorTagPaths:i,after:D,result:I}),{...I,geoResult:c}}},63175(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cameraTag=o,t.cameraTagFile=async function(e){return o(await(0,r.readTags)(e))};const r=i(40538),s=i(75020),n=i(40958),a=i(22573);function o(e){return null==e||(0,a.blank)(e.Make)?void 0:(0,n.compactBlankish)([s.TagRoots.Camera,e.Make,e.Model])}},4407(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.yearToOrdinal=w,t.monthToOrdinal=S,t.ordinalToMonth=function(e){return 13-e},t.dayToOrdinal=P,t.yearTagRef=M,t.monthTagRef=T,t.dayTagRef=_,t.dateTag=E,t.dateTagFile=async function(e,t){if((0,h.isDisabled)(u.Settings.tagYMD.valueOrDefault))return;const i=await(0,c.readCapturedAt)(e),r=(0,c.bestCapturedAt)([t,i]);return null==r||(0,f.capturedAtSrcFromStat)(r.capturedAtSrc)&&!u.Settings.tagDateFromStat.valueOrDefault?void 0:E(r.date)};const r=i(19851),s=i(19043),n=i(97352),a=i(81168),o=i(928),l=i(34102),u=i(28874),c=i(28544),d=i(40958),h=i(38639),f=i(7016),m=i(55835),p=i(31586),g=i(75020),y=i(54993),v=(0,r.lazy)(()=>new Intl.DateTimeFormat((0,s.localeSync)(),{month:"short"})),b=(0,r.lazy)(()=>{const e=v();return(0,d.range)(0,12,t=>e.format(new Date(2016,t,1))).map(e=>(0,a.stripSuffix)(e,"."))});function w(e){return 1e4-e}function S(e){return 13-e}function P(e){return 33-e}function M(e){return(0,n.mapGt0)(e,e=>({name:(0,y.toS)(e),ordinal:w(e)}))}function T(e){if((0,p.within)(1,12,e))return(0,m.map)(b()[e-1],t=>({name:String(e),displayName:t,ordinal:S(e)}))}function _(e){if((0,p.within)(1,31,e))return{name:(0,y.toS)(e),ordinal:P(e)}}function E(e){if(null==e||u.Settings.tagYMD.isDisabled())return;const t=(0,y.toS)(u.Settings.tagYMD.valueOrDefault).toLowerCase(),i=[g.TagRoots.When];if(t.startsWith("y")){const t=(0,m.map)((0,o.getYear)(e),M);if(null==t)return;i.push(t)}if(t.startsWith("ym")){const t=(0,m.map)((0,o.getMonth)(e),T);if(null==t)return i;i.push(t)}if(t.startsWith("ymd")){const t=(0,m.map)((0,o.getDay)(e),_);if(null==t)return i;i.push(t)}return i}(0,l.ee)().on("clearCache",()=>{v.unset(),b.unset()})},58886(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagAssetPaths=async function(e){const t=[];for(const i of e)try{const e=(0,a.uriToTagPath)({uri:i,isFile:!0});if(null==e)continue;if(i.startsWith(o.PS_LOCAL_FILE_SCHEME)&&null!=(0,u.modelDb)()){const t=(0,n.tagRefToS)(e[1]);e[1]={name:t,displayName:(0,c.displayNameForVolsha)(t)},d().info("tagAssetPaths()",{uri:i,tp:e})}t.push(e)}catch(e){d().warn("Failed to parse asset file URI",{uri:i})}return t},t.isFsTag=function(e){return(0,n.tagRefToS)(e[0]).toLowerCase()===l.TagRoots.fs};const r=i(19851),s=i(50213),n=i(42231),a=i(76642),o=i(89937),l=i(75020),u=i(94448),c=i(69032),d=(0,r.lazy)(()=>(0,s.mkLogger)("curators.FilePathTagger"))},32646(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.geoTag=p,t.geoTagFile=async function(e){const t=await(0,l.readTags)(e);return null==t?void 0:p(t)};const r=i(65793),s=i(48884),n=i(62556),a=i(50213),o=i(28874),l=i(40538),u=i(75020),c=i(40958),d=i(45599),h=i(31586),f=i(68708),m=(0,d.defer)(()=>(0,a.mkLogger)("curators.GeoTagger"));function p(e){const t=o.Settings.tagGeoMaxDistanceKm.valueOrDefault,i=t>0&&(0,h.gt)((0,h.toFloat)(e.GeolocationDistance),t);i&&m().debug("geoTag(): GeolocationDistance too large, Geolocation* synonyms skipped",(0,f.pickDeep)(e,...r.GeolocationTagNames));const a=o.Settings.tagGeoSynonyms.synonymMap(),l=o.Settings.tagGeoTemplate.valueOrDefault.map(t=>(0,s.first)(a.get(t)??[t],t=>i&&t.startsWith("Geolocation")?void 0:(0,f.pluckDeep)(e,t)?.value)),d=(0,c.compactBlanks)(l);if(0===d.length)return;const p=d[0],g=(i?void 0:e.GeolocationCountryCode)??e.CountryCode??(0,n.alpha3ToAlpha2)(e["Country-PrimaryLocationCode"])??(0,n.countryNameToCode)(p??"");let y;null!=g&&(y=p,d[0]=g);const v=(0,c.compact)([u.TagRoots.Where,...d]);return m().tap({msg:"geoTag",result:{tagPath:v,countryCode:g,countryName:y},meta:{picked:l}})}},48144(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extractDashDashTags=k,t.extractPathnameTags=D,t.normalizeKeywordPaths=C,t.dedupeKeywordPaths=A,t.processKeywords=x,t.keywordTagFiles=async function(e,t){return x([...c.Settings.tagKeywordsFromPath.valueOrDefault?(0,v.flatten)(e.map(D)):[],...c.Settings.tagKeywordsFromMetadata.valueOrDefault?(0,v.flatten)(await(0,u.mapAsyncSerial)({name:"keywordTagFiles",arr:e,f:async e=>{const t=await(0,h.readRawMergedTags)(e);return null==t?void 0:(0,d.rawTagKeywords)(t)}})):[]],t)};const r=i(48884),s=i(19851),n=i(50213),a=i(68852),o=i(81168),l=i(96859),u=i(56519),c=i(28874),d=i(97573),h=i(35332),f=i(42231),m=i(40958),p=i(76790),g=i(22573),y=i(41400),v=i(96249),b=i(55835),w=i(75020),S=i(54993),P=i(41893),M=i(6186),T=i(43723),_=(0,s.lazy)(()=>(0,n.mkLogger)("curators.KeywordTagger")),E=(0,s.lazy)(()=>(0,g.mapNotBlank)(c.Settings.keywordDashDashDelimiters.valueOrDefault,e=>new RegExp(`[${(0,a.escapeRegExp)(e)}]+`,"i")));function k(e){return _().tap({msg:"extractDashDashTags()",result:(0,b.mapOr)((0,S.toS)(e).split("--")[1],e=>(0,m.compactBlanks)((0,b.mapOr)(E(),t=>e.split(t),[e])),()=>[]),meta:{nativePath:e}})}function D(e){return[...k(e.parent().posixPath),...k(e.name)]}(0,y.later)(()=>{c.Settings.keywordDashDashDelimiters.watchLater(()=>E.unset())});const I=/\w{2,7}:\/\/\S+/g;function C(e){const t=[],i=[],s=[];for(const t of(0,m.compact)(e))if(Array.isArray(t))s.push(t);else{const e=(0,S.toS)(t).replace(I,e=>(i.push(e),""));s.push(...(0,b.mapOr)((0,d.delimRe)(),t=>e.split(t),[e]))}const n=s.map(e=>(0,o.isString)(e)?(0,d.keywordToPath)(e):e).map(e=>Array.isArray(e)&&1===e.length?e[0]:e),[a,l]=(0,r.partition)(n,Array.isArray),u=a.map(e=>(0,m.compactBlanks)(e.map(e=>e.trim()))).filter(m.isNotEmpty),h=(0,o.uniqIgnoreCase)((0,v.flatten)(u));t.push(...u);const f=[...l,...i].map(e=>e.trim()).filter(e=>(0,g.notBlank)(e)&&!(0,o.includesIgnoreCase)(h,e)),p="copy"===c.Settings.keywordReparenting.valueOrDefault,y="retain"===c.Settings.keywordReparenting.valueOrDefault,P=c.Settings.rootTagKeywordsAliases.values;for(const e of[...t])(0,o.includesIgnoreCase)(P,e[0])&&(e[0]=w.TagRoots.Keywords),e[0]!==w.TagRoots.Keywords&&(p?t.push([w.TagRoots.Keywords,...e]):y&&e.unshift(w.TagRoots.Keywords));for(const e of f)t.push([w.TagRoots.Keywords,e]);return(0,m.uniq)(t)}function A(e){return(0,m.uniqBy2)((0,p.sortBy)(e.map(M.normalizeTagRoot),e=>{const t=(0,f.joinTagPath)(e);return[t.normalize().toLowerCase(),-1*(0,l.lcdiff)(t)]}),(e,t)=>(0,o.equalsIgnoreCase)((0,f.joinTagPath)(e),(0,f.joinTagPath)(t)))}function x(e,t){const[i,s]=(0,r.partition)(C(e),T.isWhoTag),n=(0,v.flatten)(i.map(T.nameTag)),a=(0,m.uniq)((0,v.flatten)([...n,...t].map(e=>{const t=(0,P.stripTagRoot)(e);return[t.join(", "),t.join(" "),[...t].reverse().join(" ")]}))),l=A([...s.filter(e=>!(0,o.includesIgnoreCase)(a,(0,P.stripTagRoot)(e).join(" "))),...n]);return _().tap({msg:"processKeywords()",level:"info",result:l})}},60047(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lensTag=u,t.lensTagFile=async function(e){const t=await(0,s.readTags)(e);return null==t?void 0:u(t)};const r=i(28874),s=i(40538),n=i(75020),a=i(40958),o=i(22573),l=i(55835);function u(e){return(0,l.map)(e,e=>(0,o.mapNotBlank)(e.lensMake,t=>(0,o.mapNotBlank)((0,a.compactBlanks)(r.Settings.tagFullLensModel.valueOrDefault?[e.lensModel,e.lensInfo]:[e.lensInfo,e.lensModel])[0],e=>[n.TagRoots.Lens,t,e])))}},6186(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolvedTagRoot=y,t.resetRootTagCaches=function(){g.reset()},t.normalizeTagRoot=v,t.getAliasRenames=b,t.getEffectiveTagPathRenames=w,t.applyTagPathRenames=S,t.findMatchIndex=P,t.normalizeTagPath=function(e){const t=v(e),i=S(t),r=i===t?function(e){if(e.length<3||(0,u.tagRefToS)(e[0])!==d.TagRoots.Where)return e;const t=(0,u.tagRefToS)(e[1]),i=(0,s.alpha3ToAlpha2)(t)??(0,s.countryNameToCode)(t);return null==i?e:[e[0],i,...e.slice(2)]}(i):i,n=(0,u.tagRefToS)(r[0]).toLowerCase();if(M.has(n))return r;const a=[r[0]];for(let e=1;e<r.length;e++){const t=(0,u.tagRefToS)(r[e]);(0,l.isGarbageString)(t)?p().warn("normalizeTagPath(): rejected garbage tag segment",{segment:t,path:r.map(u.tagRefToS)}):a.push(r[e])}return a.length>1?a:void 0},t.tagDeltas=function(e,t){const i=(0,u.tagDiff)(t,e),r=(0,u.tagDiff)(e,t),s=a.Settings.excludedRootTags.valueOrDefault;return(0,h.filterInPlace)(i,e=>{const t=s.includes((0,u.tagRefToS)(e[0]).toLowerCase());return t&&!(0,u.tagPathsInclude)(e,r)&&(r.push(e),p().info("tagDeltas(): removing excluded tag",e)),!t}),{add:i,remove:r}};const r=i(9092),s=i(62556),n=i(50213),a=i(28874),o=i(70905),l=i(81168),u=i(42231),c=i(74607),d=i(75020),h=i(40958),f=i(45599),m=i(68708),p=(0,f.defer)(()=>(0,n.mkLogger)("curators.Taggers")),g=(0,f.defer)(()=>{const e=new r.CaseInsensitiveMap;for(const{root:t,setting:i}of o.RootTagAliasConfigs){const r=(0,c.rootTagDef)(t);e.set(t,r);for(const t of i.values)e.set(t,r)}return e});function y(e){return g().get(e)}function v(e){const t=y((0,u.tagRefToS)(e[0]));return null!=t?[t,...e.slice(1)]:e}function b(){const e={};for(const{root:t,setting:i}of o.RootTagAliasConfigs){const r=t.toLowerCase();for(const s of i.values)s.toLowerCase()!==r&&(e["/"+s]=t)}return e}function w(){return{...b(),...a.Settings.tagPathRenames.valueOrDefault}}function S(e){const t=w();if((0,m.isEmptyObj)(t))return e;let i=e.map(e=>(0,u.tagRefToS)(e)),r=i.map(e=>e.toLowerCase()),s=!1;for(const[e,n]of Object.entries(t)){const t=e.startsWith("/"),a=(0,u.splitTagPath)(t?e.slice(1):e,"/"),o=a.map(e=>e.toLowerCase()),l=(0,u.splitTagPath)(n.replace(/^\//,""),"/");if((0,h.isEmpty)(a))continue;const c=P(r,o,t);c<0||(i=[...i.slice(0,c),...l,...i.slice(c+a.length)],r=i.map(e=>e.toLowerCase()),s=!0)}return s?i:e}function P(e,t,i){if(t.length>e.length)return-1;const r=i?0:e.length-t.length;for(let i=0;i<=r;i++)if(t.every((t,r)=>t===e[i+r]))return i;return-1}const M=new Set(["camera","lens","when","type","fs"])},42003(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.typeTagFiles=async function(e){const t=(0,l.uniq)(await(0,a.mapAsyncSerial)({name:"typeTagFiles",arr:e,f:o.readMimeType}));return(0,l.compact)(t.map(p))},t.mimeTypeToTag=p,t.friendlySubtype=y,t.fixCase=v;const r=i(19851),s=i(50213),n=i(81168),a=i(56519),o=i(54979),l=i(40958),u=i(22573),c=i(55835),d=i(42279),h=i(75020),f=(0,r.lazy)(()=>(0,s.mkLogger)("curators.TypeTagger")),m=new Map(["M2TS","JPEG","QuickTime"].map(e=>[e.toLowerCase(),e]));function p(e){const[t,i]=e.split("/");if(!(0,u.blank)(t)&&!(0,u.blank)(i))return f().tap({msg:"mimetypeToTag("+e+")",result:(0,c.map)(y(i,e),e=>(0,l.compactBlanks)([h.TagRoots.Type,(0,n.capitalize)(t),...e]))})}const g=(0,r.lazy)(()=>new Map([["image/x-adobe-dng",["Raw","DNG"]],["image/x-fuji-raf",["Raw","Fujifilm"]],["video/m2ts",["MPEG-2"]],["video/mp2t",["MPEG-2"]],["video/mp4",["MPEG-4"]],["video/quicktime",["QuickTime"]],["video/x-msvideo",["AVI"]]]));function y(e,t){return(0,d.firstDefinedThunk)([()=>g().get(t.trim().toLowerCase()),()=>(0,c.map)(e.match(/^x-(\w{4,})-\w{3}/),e=>["Raw",(0,n.capitalize)(e[1])]),()=>[v(e.replace(/^(?:x-|vnd\.|prs\.)/i,"").replace(/-/g," "))]])}function v(e){return null!=e.match(/[a-z\d]{3,4}/i)?e.toUpperCase():m.get(e.trim().toLowerCase())??(0,n.capitalize)(e)}},43723(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whoTagFiles=async function(e){const t=[];if(n.Settings.tagJsonFaces.valueOrDefault){const i=[];for(const t of e)i.push(...(0,p.toA)(await t.jsonSidecars()));for(const e of i){const i=await(0,a.readJsonSidecar)(e),r=i?.peopleNames;(0,c.isNotEmpty)(r)&&t.push(...r)}}if(n.Settings.tagFaceRegions.valueOrDefault)for(const i of e){const e=await(0,l.readTags)(i);if(null!=e)for(const i of(0,f.values)(e)){const e=i?.RegionList;if(Array.isArray(e))for(const i of e)"Face"===i.Type&&t.push(i.Name)}}if((0,c.isNotEmpty)(n.Settings.whoTags.values))for(const i of e){const e=await(0,l.readTags)(i);for(const i of n.Settings.whoTags.values)t.push(...(0,p.toA)((0,f.pluckDeep)(e,i)?.value))}const i=(0,c.uniq)((0,h.flatten)((0,c.uniq)(t).map(b)));return y().tap({msg:"whoTagFiles()",level:"info",result:i,meta:{names:t,files:e.map(e=>e.nativePath)}})},t.isWhoTag=v,t.nameTag=b;const r=i(19851),s=i(50213),n=i(28874),a=i(28630),o=i(66039),l=i(40538),u=i(42231),c=i(40958),d=i(22573),h=i(96249),f=i(68708),m=i(75020),p=i(59455),g=i(6186),y=(0,r.lazy)(()=>(0,s.mkLogger)("curators.WhoTagger"));function v(e){return(0,g.resolvedTagRoot)((0,u.tagRefToS)(e[0]))?.name===m.TagRoots.Who}function b(e){if(!(0,d.blank)(e))return Array.isArray(e)?(v(e)&&e.shift(),0===e.length?void 0:1===e.length?(0,o.renderNameTag)(e[0]):[[m.TagRoots.Who,...e]]):(0,o.renderNameTag)(e)}},75914(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ensureAssetFileHashHealthy=void 0,t.ensureAssetFileHashTable=g,t.rebuildAssetFileHashTable=y,t.verifyAssetFileHashTable=v,t.checkAssetFileHashTable=b,t.syncAssetFileHash=function(e,t,i){if(!(0,a.isVec0Available)())return!1;const r=(0,o.hashRecordToLHashHex)(i);if(null==r)return w(e,t),!1;const s=[(0,f.assetFileHashInsertSql)(t,r,i)],n=(0,o.hashRecordToLHashHex)((0,o.hashRecord0ToHashRecord)(i));null!=n&&n!==r&&s.push((0,f.assetFileHashInsertSql)(t,n,i));try{return e.exec(`DELETE FROM AssetFileHash WHERE assetFileId = ${t}; ${s.join("; ")}`),!0}catch{return!1}},t.deleteAssetFileHash=w;const r=i(41991),s=i(5916),n=i(56038),a=i(7723),o=i(11512),l=i(19851),u=i(50213),c=i(3685),d=i(28874),h=i(64526),f=i(62324),m=i(30211),p=(0,l.lazy)(()=>(0,u.mkLogger)("db.AssetFileHash"));function g(e){if(!(0,a.isVec0Available)())return!1;try{return 1!==e.prepare("SELECT COUNT(*) FROM sqlite_master\n WHERE type='table' AND name='AssetFileHash'").pluck().get()&&(e.exec((0,f.assetFileHashCreateTableSql)()),p().info("Created AssetFileHash table"),!0)}catch(e){return p().warn("Failed to create AssetFileHash table",{error:e}),!1}}async function y(e){return(0,a.isVec0Available)()?(0,n.time)({name:"db.assetFileHash.rebuild",p:async()=>{const t=performance.now();p().info("Starting AssetFileHash index rebuild");let i=!1;try{e.exec("DROP TABLE IF EXISTS AssetFileHash"),i=!0,p().info("Dropped existing AssetFileHash table")}catch(e){p().warn("Failed to drop AssetFileHash table",{error:e})}let r=!1;try{e.exec((0,f.assetFileHashCreateTableSql)()),r=!0,p().info("Created AssetFileHash table")}catch(e){return p().error("Failed to create AssetFileHash table",{error:e}),{dropped:i,created:r,total:0,inserted:0,skipped:0,failed:0,elapsedMs:(0,c.roundMs)(performance.now()-t)}}const s=e.prepare("SELECT COUNT(*) FROM AssetFile\n WHERE pHash IS NOT NULL AND pHash != ''\n AND rHash IS NOT NULL AND rHash != ''\n AND wHash IS NOT NULL AND wHash != ''\n AND isPrimary = 1\n AND assetId IS NOT NULL").pluck().get();p().info(`Found ${s} AssetFiles with complete hash values to index`);let n=0,a=0,l=0;const u=d.Settings.dbBatchSelectSize.valueOrDefault,h=e.prepare("SELECT id, pHash, rHash, wHash, pHash0, rHash0, wHash0,\n capturedAtLocal, capturedAtSrc, basename\n FROM AssetFile\n WHERE pHash IS NOT NULL AND pHash != ''\n AND rHash IS NOT NULL AND rHash != ''\n AND wHash IS NOT NULL AND wHash != ''\n AND isPrimary = 1\n AND assetId IS NOT NULL\n AND id > ?\n ORDER BY id ASC\n LIMIT ?");e.transaction(()=>{let t=0;for(;;){const i=h.all(t,u);if(0===i.length)break;const r=[];for(const e of i)try{const t=(0,o.hashRecordToLHashHex)(e);if(null==t){a++;continue}r.push((0,f.assetFileHashInsertSql)(e.id,t,e)),n++;const i=(0,o.hashRecordToLHashHex)((0,o.hashRecord0ToHashRecord)(e));null!=i&&i!==t&&(r.push((0,f.assetFileHashInsertSql)(e.id,i,e)),n++)}catch(t){l++,p().warn("Failed to build lHash INSERT for AssetFile",{assetFileId:e.id,error:t})}if(r.length>0)try{e.exec(r.join("; "))}catch(t){p().warn("Batch insert failed, retrying individually",{error:t});for(const t of r)try{e.exec(t)}catch(e){l++,n--,p().warn("Individual insert failed",{error:e})}}t=i[i.length-1].id}})();const g=performance.now()-t;return p().info("AssetFileHash index rebuild complete",{total:s,inserted:n,skipped:a,failed:l,elapsedMs:g}),(0,m.optimizeVectorTable)(e,"AssetFileHash"),{dropped:i,created:r,total:s,inserted:n,skipped:a,failed:l,elapsedMs:g}}}):(p().info("Skipping AssetFileHash rebuild: sqlite-vec extension not available"),{dropped:!1,created:!1,total:0,inserted:0,skipped:0,failed:0,elapsedMs:0})}function v(e){const t=e.prepare("SELECT COUNT(*) FROM AssetFile\n WHERE pHash IS NOT NULL AND pHash != ''\n AND rHash IS NOT NULL AND rHash != ''\n AND wHash IS NOT NULL AND wHash != ''\n AND isPrimary = 1\n AND assetId IS NOT NULL").pluck().get();let i=0,r=0;try{i=e.prepare("SELECT COUNT(*) FROM AssetFileHash").pluck().get(),r=e.prepare("SELECT COUNT(DISTINCT assetFileId) FROM AssetFileHash").pluck().get()}catch{}return{assetFileCount:t,rowCount:i,uniqueAssetFileCount:r,matches:t===r}}function b(e,t=10){if(!(0,a.isVec0Available)())return p().info("Skipping AssetFileHash health check: sqlite-vec extension not available"),{countMatch:!0,assetFileCount:0,rowCount:0,uniqueAssetFileCount:0,selfQuery:{tested:0,passed:0,failed:0},orphanedRows:0,isHealthy:!0,issues:[]};const i=[],{assetFileCount:r,rowCount:s,uniqueAssetFileCount:n,matches:l}=v(e);l||i.push(`Count mismatch: ${r} PRIMARY AssetFiles with complete hashes, but ${n} unique assetFileIds in AssetFileHash (${s} total rows)`);const u={tested:0,passed:0,failed:0};if(s>0)try{const r=e.prepare("SELECT id, pHash, rHash, wHash, pHash0, rHash0, wHash0 FROM AssetFile\n WHERE pHash IS NOT NULL AND pHash != ''\n AND rHash IS NOT NULL AND rHash != ''\n AND wHash IS NOT NULL AND wHash != ''\n AND isPrimary = 1\n AND assetId IS NOT NULL\n ORDER BY RANDOM() LIMIT ?").all(t);for(const t of r){u.tested++;try{const i=(0,o.hashRecordToLHashHex)(t);if(null==i){u.failed++;continue}const r=e.prepare(`SELECT assetFileId FROM AssetFileHash\n WHERE vec_distance_hamming(lHash, vec_bit(X'${i}')) = 0\n LIMIT 1`).pluck().get();if(null!=r)u.passed++,r!==t.id&&p().debug("Self-query found different id with same hash",{assetFileId:t.id,foundId:r});else{u.failed++;const r=e.prepare("SELECT hex(lHash) FROM AssetFileHash WHERE assetFileId = ?").pluck().get(t.id);p().warn("Self-query failed: lHash not found in AssetFileHash table",{assetFileId:t.id,queryHex:i,storedHex:r,inAssetFileHashTable:null!=r})}const s=(0,o.hashRecordToLHashHex)((0,o.hashRecord0ToHashRecord)(t));if(null!=s&&s!==i){u.tested++;const i=e.prepare(`SELECT assetFileId FROM AssetFileHash\n WHERE vec_distance_hamming(lHash, vec_bit(X'${s}')) = 0\n LIMIT 1`).pluck().get();null!=i?(u.passed++,i!==t.id&&p().debug("Self-query (HashRecord0) found different id with same hash",{assetFileId:t.id,foundId:i})):(u.failed++,p().warn("Self-query failed: lHash0 (canonical orientation) not found in AssetFileHash table",{assetFileId:t.id,queryHex:s}))}}catch(e){u.failed++,p().warn("Self-query error",{assetFileId:t.id,error:e})}}u.failed>0&&i.push(`Self-query test failed: ${u.failed}/${u.tested} hashes could not find themselves`)}catch(e){i.push(`Self-query test error: ${e}`),p().warn("Self-query test failed",{error:e})}let c=0;try{c=e.prepare("SELECT COUNT(*) FROM AssetFileHash h\n WHERE NOT EXISTS (SELECT 1 FROM AssetFile a WHERE a.id = h.assetFileId)").pluck().get()}catch{}c>0&&i.push(`Referential integrity: ${c} AssetFileHash rows reference non-existent AssetFile ids`);const d=l&&0===u.failed&&0===c;return p().info("AssetFileHash table health check complete",{isHealthy:d,countMatch:l,assetFileCount:r,rowCount:s,uniqueAssetFileCount:n,selfQuery:u,orphanedRows:c,issues:i}),{countMatch:l,assetFileCount:r,rowCount:s,uniqueAssetFileCount:n,selfQuery:u,orphanedRows:c,isHealthy:d,issues:i}}function w(e,t){if((0,a.isVec0Available)())try{e.exec(`DELETE FROM AssetFileHash WHERE assetFileId = ${t}`)}catch{}}t.ensureAssetFileHashHealthy=(0,s.lazyAsync)({desc:"ensureAssetFileHashHealthy",later:async function(){if(!(0,a.isVec0Available)())return!1;const e=h.Library.instance();if(null==e)return!1;const t=await e.modelDb();return!!g(t.db)||!b(t.db).isHealthy&&(await y(t.db),!0)},ttlMs:7*r.secondMs,timeoutMs:d.Settings.dbMaintenanceTimeoutMs.valueOrDefault})},62324(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetFileHashCreateTableSql=function(e=!0){return`\n CREATE VIRTUAL TABLE ${e?"IF NOT EXISTS ":""}AssetFileHash USING vec0(\n assetFileId INTEGER,\n lHash bit[192],\n capturedAtLocal INTEGER,\n capturedAtFuzzy INTEGER,\n bname TEXT\n )\n `},t.assetFileHashMetadata=a,t.assertLHashHex=o,t.assetFileHashInsertSql=function(e,t,i){o(t);const r=a(i);return(0,s.knex)()("AssetFileHash").insert({assetFileId:e,lHash:(0,s.knex)().raw(`vec_bit(X'${t}')`),capturedAtLocal:r.capturedAtLocal,capturedAtFuzzy:r.capturedAtFuzzy,bname:r.bname}).toQuery()};const r=i(89724),s=i(70974),n=i(65162);function a(e){const t=e.capturedAtLocal??0;return{capturedAtLocal:t,capturedAtFuzzy:"tags"!==e.capturedAtSrc||(0,r.localIsFuzzy)(t)?1:0,bname:(0,n.shortestBname)(e.basename)}}function o(e){if(!/^[0-9a-fA-F]{48}$/.test(e))throw new Error("Invalid lHashHex: expected 48 hex characters")}},21167(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseCapturedAtSrcType=function(e){if(null==e||""===e)return"unknown";const t=r[e];if(null!=t)return t;if(i.has(e))return e;const s=e.indexOf("("),n=s>0?e.substring(0,s).trim():e,a=n.indexOf(":"),o=a>0?n.substring(0,a):n;return r[o]??(i.has(o)?o:"unknown")},t.parseCapturedAtSrcDetail=function(e){if(null==e||""===e)return null;const t=e.indexOf(":");if(t<=0)return null;const i=e.substring(0,t),r=e.substring(t+1);if("tags"===i){const e=r.indexOf(" (");return(e>0?r.substring(0,e):r).trim()||null}return"siblings"===i&&r.trim()||null},t.parseCapturedAtSrcZoneSrc=function(e){if(null==e||""===e)return null;if(!e.includes("("))return null;if(e.includes("forced)"))return"forced";if(e.includes("tz inferred")||e.includes(".tz:"))return"siblings";const t=e.match(/\(zone .+ from (.+)\)/);return null!=t?t[1]:null};const i=new Set(["tags","bname+stat","path+stat","bname","path","siblings","stat","unknown"]),r={"stat+bname":"bname+stat","stat+path":"path+stat"}},98348(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Db=t.DbInterfaceImpl=void 0;const r=i(86558),s=i(48884),n=i(19851),a=i(23560),o=i(25764),l=i(38836),u=i(99331),c=i(12959),d=i(55332),h=i(80632),f=i(51040),m=i(44955),p=i(14277),g=i(15056),y=i(70025),v=i(18454),b=i(28874),w=i(5233),S=i(42659),P=i(31586),M=i(68708),T=i(30976),_=i(45648),E=i(17036),k=i(27134),D=i(35052);let I=-1;t.DbInterfaceImpl=class{db;prepare;pragma;constructor(e){this.db=e,this.db.$uid??=I--,this.prepare=e.prepare.bind(e),this.pragma=e.pragma.bind(e)}tableInfo_=(0,n.lazy)(()=>(0,D.localTableInfo)(this.db))};class C extends l.EndableWrapper{schema;dbFile;isReplica;#ls;endTimeoutMs=S.minuteMs;#us=[];#cs=0;#ds=0;get lastWriteAt(){return this.#cs}get writeCount(){return this.#ds}constructor(e,t,i){super("db.Db("+e+")",()=>this.closeDb(),o.EndableRanks.db),this.schema=e,this.dbFile=t,this.isReplica=i,this.logger.info("new Db",this.toJSON())}onClose(e){this.#us.push(e)}toJSON(){return(0,M.pick)(this,"schema","dbFile")}get isOpen(){return!0===this.#ls?.isOpen}get inTransaction(){return this.isOpen&&!0===this.#ls?.isTransaction}prepare(e){return this.db.prepare(e)}pragma(e,t){return this.logger.tapThunk({msg:"PRAGMA "+e,result:()=>this.db.pragma(e,t)})}get db(){const e=null==this.#ls;if(e||!this.isOpen){this.logger.info("setting up new db connection to "+this.dbFile,{priorWasNull:e});try{this.#ls=(0,h.mkdb_)({nativePath:this.dbFile.nativePath}),this.#hs(this.#ls)}catch(e){this.logger.throw("Failed to set up "+this.dbFile,{cause:e,path:this.dbFile.nativePath})}}return this.#ls}#hs(e){const t=e.prepare.bind(e);Object.defineProperty(e,"prepare",{value:e=>{const i=t(e),r=i.run.bind(i);return Object.defineProperty(i,"run",{value:(...e)=>{const t=r(...e);return this.#cs=performance.now(),this.#ds++,t},writable:!0,configurable:!0,enumerable:!1}),i},writable:!0,configurable:!0});const i=e.exec.bind(e);Object.defineProperty(e,"exec",{value:e=>(this.#cs=performance.now(),this.#ds++,i(e)),writable:!0,configurable:!0})}async verify_(){await(0,k.verifyDb_)(()=>this.db)}assertHeartbeat_(){const e=(0,T.randomChars)(64),t=Date.now();try{this.db.prepare("INSERT INTO heartbeat (name, createdAt, updatedAt) VALUES (?,?,?)").run(e,t,t);const i=this.db.prepare("SELECT * FROM heartbeat WHERE name = ?").get(e);if(i?.name!==e)throw new Error("heartbeat INSERT/SELECT roundtrip failed")}finally{try{this.db.prepare("DELETE FROM heartbeat WHERE name = ?").run(e)}catch{}}}async closeDb(){try{if(this.logger.info("closing db",{db:this.#ls}),!0===this.#ls?.isOpen)try{await(0,p.walCheckpointPassive)(this.#ls)}catch(e){this.logger.warn("closeDb(): WAL checkpoint failed",{error:e})}await(0,w.retryOnReject_)(()=>{!0===this.#ls?.isOpen&&this.#ls?.close()},{timeoutMs:b.Settings.dbBusyTimeoutMs.valueOrDefault+S.secondMs,maxRetries:5,errorIsRetriable:y.isSqliteBusyError,retryDelay:S.secondMs})}catch(e){this.logger.warn("closeDb(): .close() failed",e)}this.#ls=void 0,this.#cs=0,this.#ds=0;for(const e of this.#us)try{e()}catch(e){this.logger.warn("closeDb(): listener threw",e)}}onRetry=(0,n.lazy)(()=>this.closeDb(),b.Settings.maxBusyDbMs.valueOrDefault/2);#fs(...e){const t=[];for(const i of e)try{t.push(this.db.prepare("SELECT MAX(updatedAt) FROM "+(0,f.dbValueToEscapedString)(i)).pluck().get())}catch(e){this.logger.warn(`#maxUpdatedAt(): failed to get max updatedAt for ${i}`,e)}return(0,s.max)(t)}maxUpdatedAt=(0,n.lazy)(()=>"models"===this.schema?this.#fs("Asset","AssetFile","Example"):0,5*S.secondMs);vacuum(){return(0,p.vacuum)(this.db)}checkpoint(){return(0,p.walCheckpointTruncate)(this.db)}async repair_(){this.logger.warn("repair_(): Attempting restore of "+this.dbFile),await this.closeDb(),await(0,k.repairDbFile_)(this.dbFile),this.logger.info("repair_(): Database restoration was successful!")}async#ms(e){await e.parent().mkdirp_(),await(0,r.backup)(this.db,e.nativePath,{rate:(0,u.ending)()?1e3:100,progress:e=>{this.logger.log((0,u.ending)()?"info":"debug","backup() "+(0,P.fmtPct)(100-e.remainingPages/e.totalPages*100)+" completed")}})}localBackupDir(){return(0,g.dbBackupDir)(this.dbFile)}async backup_(e,t){const i=t??await(0,m.isDirSQLiteReadWrite)(e),r=(i?e:this.localBackupDir().join((0,c.filestamp)())).join(this.dbFile.base);return await this.#ms(r),i||await(0,d.dbBackupCold_)(r,e),e.join(this.dbFile.base)}migrate_=(0,n.lazy)(async()=>{let e=!1;const t=this.dbFile;if(null==this.dbFile)throw new Error("Cannot migrate database: missing db");const i=[];if(await this.dbFile.isNonEmptyFile()&&!(0,a.isWebService)())try{await(0,k.verifyDb_)(()=>this.db)}catch(e){this.logger.error("verifyDb() failed before attempting Migration.",{error:e}),(0,_.addDbSetupError)(e),i.push(e)}(i.length>0||b.Settings.dbForceRepair.valueOrDefault)&&(v.HealthCheck.addLoadingMsg("Repairing database..."),await this.repair_(),e=!0);const r=new E.Migration(this.schema,this.db,t);return{appliedMigrations:await r.apply_(),migration:r,repaired:e,errors:i}});tableInfo_=(0,n.lazy)(()=>(0,D.localTableInfo)(this.db))}t.Db=C},86859(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DbRequest=void 0;const r=i(48884),s=i(55139),n=i(50213),a=i(7282),o=i(3685),l=i(99331),u=i(56038),c=i(70974),d=i(51040),h=i(31302),f=i(28874),m=i(40958),p=i(76790),g=i(22573),y=i(38639),v=i(45599),b=i(50357),w=i(96249),S=i(98553),P=i(30301),M=i(68708),T=i(51926);t.DbRequest=class{logger=(0,v.defer)(()=>(0,n.mkLogger)("db."+this.tableName));db;tableName;#ps;constructor(e){this.db=e.db,this.tableName=e.tableName,this.#ps=new s.Cache({name:"db."+this.tableName,maxSize:250}),(0,m.isNotEmpty)(e.primaryKeys)&&this.primaryKeys.set([...e.primaryKeys]),(0,m.isNotEmpty)(e.businessKeys)&&this.businessKeys.set([...e.businessKeys]),this.db()?.onClose?.(()=>this.#ps.clear())}columnNames=(0,P.lazy)(()=>{const e=this.db().tableInfo_().find(e=>(0,T.equalsIgnoreCase)(e.tableName,this.tableName));return null==e?this.logger().throw("columnNames(): table not found",{tableName:this.tableName,retriable:!1}):e.columns.map(e=>e.name)});qb(){return(0,c.knex)()(this.tableName)}#gs(e,t=!1){const i=(0,h.toSqlQuery)(e);try{const e=this.db();if(null==e)throw new Error((0,a.isTest)()?"Database already disposed (test teardown)":"Database is unexpectedly null");const r=this.#ps.getOrSet(e.db.$uid+":"+(!0===t?"pluck:":"")+i.sql,()=>{const r=e.prepare(i.sql);return!0===t?r.pluck():r});if(e.db.isOpen)return{sq:i,stmt:r};throw this.#ps.clear(),new Error("Database is closed")}catch(e){return this.logger().throw("prep() failed",{error:e,sqlQuery:i,retriable:!1})}}#ys({q:e,pluck:t,method:i}){try{const{sq:r,stmt:s}=this.#gs(e,t);f.Settings.logSql.valueOrDefault&&this.logger().trace(i+"()",r);const n=s[i].bind(s),a=performance.now();try{let e;return e=null==r.bindings?n():Array.isArray(r.bindings)?n(...r.bindings.map(e=>void 0===e?null:e)):n(r.bindings),e}finally{const e=performance.now()-a;(0,u.pushTime)({name:"sql."+this.tableName+"."+i,elapsedMs:e}),e>100&&this.logger().warn("slow query",{method:i,elapsedMs:(0,o.roundMs)(e),sql:r.sql})}}catch(t){this.logger().throw(t,{method:i,...(0,h.toSqlQuery)(e)})}}primaryKeys=(0,P.lazy)(()=>{const e=this.all({sql:`PRAGMA table_info(${(0,d.dbValueToEscapedString)(this.tableName)})`}),t=e.filter(e=>(0,y.isTrue)(e.pk)).map(e=>e.name);if((0,m.isNotEmpty)(t))return(0,p.sort)(t);const i=this.all({sql:`PRAGMA foreign_key_list(${(0,d.dbValueToEscapedString)(this.tableName)})`}),s=e.filter(e=>(0,y.isTrue)(e.notnull)).map(e=>e.name),n=(0,r.intersection)(i.map(e=>e.from),s);return(0,m.isNotEmpty)(n)?(0,p.sort)(n):this.logger().throw("primaryKeys() failed",{tableInfo:e,foreignKeyList:i,retriable:!1})});businessKeys=(0,P.lazy)(()=>{const e=this.all({sql:`PRAGMA index_list(${(0,d.dbValueToEscapedString)(this.tableName)})`}),t=[];for(const i of e.filter(e=>(0,y.isTrue)(e.unique))){const e=this.all({sql:`PRAGMA index_info(${(0,d.dbValueToEscapedString)(i.name)})`});t.push(...e.map(e=>e.name))}return(0,m.toNotEmpty)((0,p.sort)((0,m.uniq)(t)))??this.primaryKeys()});immutableKeys=(0,P.lazy)(()=>(0,m.uniq)(this.primaryKeys(),this.businessKeys(),(0,r.intersection)(["createdAt"],this.columnNames())));pickModelUcn(e){return(0,M.pickRequired)(e,...this.primaryKeys())??(0,M.pickRequired)(e,...this.businessKeys())}modelSupportsUpsert=(0,P.lazy)(()=>!(0,b.eql)(this.businessKeys(),["id"]));modelSupportsUpdate=(0,P.lazy)(()=>(0,b.eql)(this.primaryKeys(),["id"]));upsert(e){for(const t of e)this.upsertOne(t)}upsertOne(e){const t=(0,p.sort)((0,r.intersection)(this.columnNames(),(0,M.keysWithDefinedOrNullValues)(e))),i=(0,m.diff)(t,this.immutableKeys());if(this.modelSupportsUpdate()&&this.primaryKeys().every(t=>null!=e[t])&&!(0,M.isEmptyObj)(i))return{method:"update",runResult:this.runf(t=>t.where((0,M.pick)(e,...this.primaryKeys())).update((0,M.pick)(e,...i)))};const s=(0,r.intersection)(t,this.businessKeys()),n=(0,d.normalizeSql)("INSERT INTO "+this.tableName,"("+t.join(",")+")","VALUES ("+t.map(e=>":"+e).join(",")+")","ON CONFLICT("+s.join(",")+") DO",(0,m.isEmpty)(i)?"NOTHING":"UPDATE SET "+i.map(e=>`${e} = excluded.${e}`).join(", "));return{method:"upsert",runResult:this.run({sql:n,bindings:(0,M.pick)(e,...t)})}}run(e){return this.#ys({q:e,method:"run"})}runScript(e){for(const t of e)(0,g.blank)(t)||t.trim().startsWith("--")||this.run({sql:t})}txn(e){const t=this.db();if(null==t)throw new Error("txn: database not available");return t.db.transaction(e)()}mapRun(e){return e.map(e=>this.run(e))}runf(e){return this.#ys({q:e(this.qb()),method:"run"})}first(e){return this.#ys({q:e,method:"get"})}firstf(e){return this.#ys({q:e(this.qb()),method:"get"})}mapAll(e){return(0,w.flatten)(e.map(e=>this.all(e)))}all(e){return this.#ys({q:e,method:"all"})}allf(e){return this.#ys({q:e(this.qb()),method:"all"})}async*batched(e){let t;for(;;){if((0,l.ending)())return;if(await(e.runLatch?.()),(0,l.ending)())return;const i=e.maxBatchSize();if(i<1)throw new Error("maxBatchSize must be > 0");const s=e.qb(this.qb()).orderBy(e.primaryColumn,"asc").limit(i);null!=t&&s.andWhere(e.primaryColumn,">",t);const n=this.#ys({q:s,method:"all"});if((0,m.isEmpty)(n))break;yield n;const a=n.map(e.rowToId);t=(0,r.max)(a)}}pluckFirst(e){return this.#ys({q:e,pluck:!0,method:"get"})}pluckFirstf(e){return this.#ys({q:e(this.qb()),pluck:!0,method:"get"})}count(e){return this.pluckFirstf(t=>e(t).count())}pluckAll(e){return this.#ys({q:e,pluck:!0,method:"all"})}pluckAllf(e){return this.#ys({q:e(this.qb()),pluck:!0,method:"all"})}async*pluckBatched(e){let t;for(;;){if((0,l.ending)())return;if(await(e.runLatch?.()),(0,l.ending)())return;const i=e.maxBatchSize();if(i<1)throw new Error("maxBatchSize must be > 0");const s=e.qb(this.qb()).select(e.pluckedColumn).distinct().orderBy(e.pluckedColumn,"asc").limit(i);null!=t&&s.andWhere(e.pluckedColumn,">",t);const n=this.#ys({q:s,pluck:!0,method:"all"});if((0,m.isEmpty)(n))break;yield n,t=(0,r.max)(n)}}insertOrReplaceBatch(e){if((0,m.isEmpty)(e))return;const t=(0,M.keysWithDefinedOrNullValues)(e[0]),i=(0,d.normalizeSql)("INSERT OR REPLACE INTO "+this.tableName,"("+t.join(",")+")","SELECT ",t.map(e=>"json_extract(value, '$."+e+"')").join(","),"FROM json_each(?)");return this.run({sql:i,bindings:[(0,S.stringify)(e)]})}}},16185(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.schemaJsonFile=b,t.schemaSqlFile=w,t.schemaMermaidFile=S,t.assertValidDbSchema_=async function(e){try{await e.migrate_();const t=(0,y.localTableInfo)(e.db),i=t.map(e=>e.tableName),r=(await b(e.schema).readJson_()).tableInfo;{const e=r.map(e=>e.tableName),t=(0,d.diff)(e,i);(0,d.isNotEmpty)(t)&&v().throw("Db is missing "+(0,m.plur)(t.length,"table")+": "+(0,f.andList)(t))}for(const e of t){const t=r.find(t=>t.tableName===e.tableName);if(null==t)v().warn("Unexpected table in db",e);else{const i=(0,n.diffEql)(t.columns,e.columns);(0,d.isNotEmpty)(i)&&v().throw("Db is missing "+(0,m.plur)(i.length,"column")+" from table "+e.tableName+": "+(0,f.andList)(i.map(e=>e.name)))}}const s=e.db.prepare("SELECT name FROM sqlite_master\n WHERE type='table'\n AND name NOT LIKE 'sqlite_%'\n AND name NOT LIKE '%_fts%'\n AND sql NOT LIKE 'CREATE VIRTUAL TABLE%'\n AND (sql NOT LIKE '%) STRICT%' OR sql IS NULL)").pluck().all().filter(e=>!(0,g.isVec0ShadowTable)(e));(0,d.isNotEmpty)(s)&&v().throw("The following "+(0,m.plur)(s.length,"table")+" must be created in STRICT mode: "+(0,f.andList)(s)+". STRICT mode provides better data integrity and type safety."),v().info("Validated schema.",{from:(0,h.shortStack)()})}catch(e){throw(0,p.libraryDbHealthCheck)().reset(),e}},t.writeSchemaJsonFile_=function(e,t){return b(e).writeJson_({info:"This is used in validating PhotoStructure library databases after repair and restore operations.",generator:"src/library/db/DbSchemaValid.ts",tableInfo:(0,y.localTableInfo)(t)},{spaces:2})},t.writeSchemaSqlFile_=function(e,t){const i=t.prepare("SELECT name, sql FROM sqlite_master\n WHERE type='table'\n AND name NOT LIKE 'sqlite_%'\n AND name NOT LIKE '%_fts_config'\n AND name NOT LIKE '%_fts_data'\n AND name NOT LIKE '%_fts_docsize'\n AND name NOT LIKE '%_fts_idx'\n ORDER BY name").all().filter(e=>!(0,g.isVec0ShadowTable)(e.name)).map(e=>e.sql),r=t.prepare("SELECT sql FROM sqlite_master WHERE type='index' AND name NOT LIKE 'sqlite_%' ORDER BY name").pluck().all(),s=["-- PhotoStructure Database Schema","-- Generated by "+(0,l.posixPathFromGrandparent)(__filename),"-- Tables",...i.filter(e=>null!=e).map(e=>e+";"),"","-- Indices",...r.filter(e=>null!=e).map(e=>e+";")].join("\n");return w(e).writeText_(s)},t.writeSchemaMermaidFile_=function(e,t){const i=(0,y.localTableInfo)(t).filter(e=>!e.tableName.includes("_fts_")),r=function(e){const t=new Map,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '%_fts_%'").pluck().all();for(const r of i){const i=e.pragma(`foreign_key_list('${r}')`);i.length>0&&t.set(r,i.map(e=>({column:e.from,referencedTable:e.table,referencedColumn:e.to})))}return t}(t),s=[];for(const[e,t]of r.entries())for(const i of t){const t=` ${i.referencedTable} ||--o{ ${e} : "references"`;s.includes(t)||s.push(t)}const n=[];for(const e of i){n.push(` ${e.tableName} {`);for(const t of e.columns){let i=` ${t.type} ${t.name}`;t.pk?i+=" PK":!0===r.get(e.tableName)?.some(e=>e.column===t.name)&&(i+=" FK"),n.push(i)}n.push(" }"),n.push("")}const a=["# PhotoStructure Database Schema","","This document visualizes the PhotoStructure database schema using Mermaid ERD diagrams.","","## Entity Relationship Diagram","","```mermaid","erDiagram",...s,"",...n,"```","","**Generated by `"+(0,l.posixPathFromGrandparent)(__filename)+"**"].join("\n");return S().writeText_(a)};const s=r(i(76760)),n=i(48884),a=i(19851),o=i(50213),l=i(29882),u=i(95696),c=i(46473),d=i(40958),h=i(26905),f=i(57924),m=i(12168),p=i(24271),g=i(35340),y=i(35052),v=(0,a.lazy)(()=>(0,o.mkLogger)("db.DbSchemaValid"));function b(e){return u.PosixFile.for(s.default.join(c.ProjectDir.Data(),e+"-schema.json"))}function w(e){return u.PosixFile.for(s.default.join(c.ProjectDir.Data(),e+"-schema.sql"))}function S(){return u.PosixFile.for(s.default.join(c.ProjectDir.Root(),"docs","schema.md"))}},45648(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._dbSetupErrors=void 0,t.dbSetupErrors=function(){return[...t._dbSetupErrors.values()]},t.addDbSetupError=function(e){if((0,n.isError)(e)||!(0,s.blank)(e)){t._dbSetupErrors.add((0,r.errorToS)(e));for(const e of a)e()}},t.clearDbSetupErrors=function({notifyListeners:e=!0}={}){if(t._dbSetupErrors.clear(),e)for(const e of a)e()},t.hasDbSetupErrors=function(){return t._dbSetupErrors.size>0},t.addDbSetupErrorListener=function(e){a.push(e)};const r=i(98314),s=i(22573),n=i(23541);t._dbSetupErrors=new Set;const a=[]},36908(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeTags_=y,t.dedupeTags_=function(e){const t=new d.MultiMap;for(const{id:i,_path:r}of e.prepare("SELECT id, _path FROM Tag ORDER BY id").iterate())t.add((0,o.stripSuffix)((0,m.toS)(r).trim(),l.TagSep).toLowerCase().normalize(),i);const i=(0,c.sortBy)(t.entriesArray().filter(([,e])=>e.length>1),([e])=>[-(0,o.countChars)(e,l.TagSep),-e.length,e]);g().info("dedupeTags()",{dupes:i.entries()});for(const[,t]of i)y(e,t)};const r=i(51040),s=i(34102),n=i(19851),a=i(50213),o=i(81168),l=i(42231),u=i(40958),c=i(76790),d=i(23838),h=i(31586),f=i(59455),m=i(54993),p=i(35052),g=(0,n.lazy)(()=>(0,a.mkLogger)("db.DedupeTags"));function y(e,t,i){function n(t){return e.prepare(t).run()}t=(0,f.toA)(t).filter(h.gt0),(0,u.isEmpty)(t)&&g().warn("mergeTags(): empty tagIds",{tagIds:t}),g().info("mergeTags() starting",{tagIds:t});const a=e.prepare((0,r.normalizeSql)(`\n SELECT id, _path, parentId\n FROM Tag \n WHERE id IN (${t.join(",")}) \n ORDER BY ID`)).all(),o=(0,u.compactBlanks)(a.map(e=>(0,l.tagPathLeaf)(e._path)).sort()),c=a[0],d=a.slice(1),m=c?.id;if((0,u.isEmpty)(o)||(0,u.isEmpty)(d)||null==c||!(0,h.gt0)(m))return void g().warn("mergeTags(): missing winner",{winner:c,winnerId:m,leafs:o,losers:d});const y=(0,l.splitTagPath)(c._path).slice(0,-1),v=[...y,o[0]];c._path=(0,l.joinTagPath)(v),c.parentId=0===y.length?null:e.prepare("SELECT id from Tag where _path LIKE ?").pluck().get((0,l.joinTagPath)(y))??c.parentId,g().info("mergeTags()",{winner:c,losers:d,winnerTagPath:v,leafs:o});const b=d.map(e=>e.id).join(",");n(`UPDATE OR IGNORE AssetTag SET tagId = ${m} WHERE tagId in (${b})`),n(`UPDATE OR IGNORE Tag SET parentId = ${m} WHERE parentId in (${b})`),n(`DELETE FROM AssetTag WHERE tagId in (${b})`),n(`DELETE FROM Tag WHERE id in (${b})`),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:m});const w=e.prepare("SELECT id, _path FROM Tag WHERE id != :winnerId AND _path LIKE :like COLLATE NOCASE").all({winnerId:m,like:c._path+"%"});for(const t of w){const i=(0,l.splitTagPath)(t._path).slice(v.length),r=(0,l.joinTagPath)([...v,...i]);t._path!==r&&(g().info("mergeTags(): repairing tag path",{ea:t,newPath:r}),e.prepare("UPDATE OR IGNORE Tag SET _path = :path, updatedAt = :updatedAt WHERE id = :id").run({id:t.id,updatedAt:Date.now(),path:r}))}return(i??(0,p.getColumnInfo)(e,"Tag").some(e=>"assetCount"===e.name))&&n("UPDATE Tag SET assetCount = NULL WHERE id = "+m),(0,s.ee)().emitSync("clearDbCache"),g().tap({msg:"mergeTags()",level:"info",result:{winner:c,losers:d}})}},17036(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migration=void 0,t.isDisabledForeignKeysMigration=I;const r=i(77598),s=i(19851),n=i(50213),a=i(7282),o=i(3685),l=i(37805),u=i(4867),c=i(51040),d=i(77740),h=i(38835),f=i(8769),m=i(57159),p=i(34102),g=i(73209),y=i(95696),v=i(46473),b=i(18454),w=i(28874),S=i(40958),P=i(42659),M=i(41400),T=i(98553),_=i(32639),E=i(45648),k=i(94715),D=i(27134);function I(e){return e.name.includes("_nofk")}t.Migration=class{schema;db;dbFile;logger;migrationsDir;constructor(e,t,i){this.schema=e,this.db=t,this.dbFile=i,this.logger=(0,n.mkLogger)("db.Migration("+(0,T.stringify)({schema:e,db:i.nativePath})+")"),this.migrationsDir=y.PosixFile.for(v.ProjectDir.Migrations()).join(this.schema)}async pendingMigrationFiles_(){const e=this.migrationsInDatabase_();return(await this.fsMigrations_()).filter(t=>!e.includes(t.name))}fsMigrations_=(0,s.lazy)(()=>this.migrationsDir.children_(e=>e.isFile&&e.basename.endsWith(".sql")).catch(e=>this.logger.throw("Failed to read migration directory, "+this.migrationsDir+h.InternalErrorFlag,{error:e})));ensureMigrationTable_=(0,s.lazy)(()=>{this.db.exec("\nCREATE TABLE IF NOT EXISTS migrations (\n id INTEGER NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n migration_time INTEGER NOT NULL\n) STRICT\n")});migrationsInDatabase_(){return this.ensureMigrationTable_(),this.db.prepare("SELECT name from migrations").pluck().all()}unknownMigrations_=(0,s.lazy)(()=>this.migrationsInDatabase_().filter(e=>{const t=(0,k.migrationNameToDate)(e);return null==t&&this.logger.throw("Migration has invalid name (expected YYYYMMDD prefix): "+e+h.InternalErrorFlag,{migration:e}),t>=l.gitDate}));assertKnownMigrations_=(0,s.lazy)(()=>{const e=this.unknownMigrations_();if((0,S.isNotEmpty)(e)){const t=new m.WrappedError("Please upgrade PhotoStructure to a newer version to open this library: Unknown migrations: "+e.join(","));throw(0,f.onError)(t),t}});async apply_(e){const t=w.Settings.dbMaintenanceTimeoutMs.valueOrDefault,i=(0,d.getDevEnvFlag)("PS_SLOMO")?Math.max(t,30*P.minuteMs):t;return(0,g.withLock_)({file:this.dbFile.sibling("migrate"),timeoutMs:i},()=>this.#D(e))}async#D(e){try{this.ensureMigrationTable_(),(0,a.isProd)()&&this.assertKnownMigrations_();const t=[],i=this.db.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)");for(const s of await this.pendingMigrationFiles_())await b.HealthCheck.traceLater_("Upgrading database ("+s.name+")",async()=>{if((0,d.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");(0,d.getDevEnvFlag)("PS_SLOMO")&&await(0,M.delay)((0,r.randomInt)(P.secondMs,3*P.secondMs)),await(e?.(s)),await(0,u.thenOrTimeoutError)({p:this.applyMigration_(s,i),timeoutMs:5*w.Settings.dbMaintenanceTimeoutMs.valueOrDefault}).catch(e=>{throw new m.WrappedError("Migration "+s.name+" timed out.",{cause:e,fatal:!0,ignorable:!1})})}),t.push(s.base);return this.logger.info("Migration complete",{appliedMigrations:t}),t}catch(e){const t=new m.WrappedError("Migrating the "+this.schema+" db failed",{cause:e});throw(0,E.addDbSetupError)(t),b.HealthCheck.addError(t),t}}async applyMigration_(e,t){try{const i=performance.now(),r=e.name.replace(/^[\d_-]+/,""),s=k.Migrations[r],n=(0,_.isFunction)(s);if((0,a.isTest)()){const t=await e.readText_(),i=(0,c.splitBatchSql)(t);n&&(0,S.isNotEmpty)(i)&&this.logger.throw(`JS migration ${e.name} has executable SQL statements that will be ignored`,{migration:e.baseWithParent,key:r,fatal:!0}),!n&&(0,S.isEmpty)(i)&&this.logger.throw(`Migration ${e.name} has no SQL and no matching Migrations.${r} function`,{migration:e.baseWithParent,key:r,fatal:!0})}return await this.#vs(e,()=>n?s(this.db):this.#bs(e)),this.logger.elapsed("applyMigration() completed",{elapsedMs:(0,o.roundMs)(performance.now()-i),codeMigration:n,migration:e.baseWithParent}),t?.run(e.name,Date.now())}finally{(0,p.ee)().emitSync("clearDbCache")}}async#vs(e,t){const i=I(e);i&&this.db.pragma("foreign_keys = OFF");const r=await t();return i&&((0,D.foreignKeyCheckStrict_)(this.db),this.db.pragma("foreign_keys = ON")),r}async#bs(e){const t=await e.readText(),i=(0,c.splitBatchSql)(t);if((0,S.isEmpty)(i))this.logger.info("No-op migration: "+e);else for(const t of i)try{this.db.exec(t)}catch(i){this.logger.throw("Failed to apply SQL",{stmt:t,migration:e.baseWithParent,cause:i,fatal:!0})}}}},94715(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Migrations=t.lowercase_psnet_function=void 0,t.plucklabmodeb6=O,t.migrationNameToDate=function(e){const[t,i,r]=[e.slice(0,4),e.slice(4,6),e.slice(6,8)].map(e=>(0,S.toInt)(e));return(0,m.validYMD)(t,i,r)?new Date(t,i-1,r):void 0},t.tag_path_suffix=R,t.isoToPrecisionMs=L;const r=i(48884),s=i(50213),n=i(97352),a=i(68852),o=i(81168),l=i(85810),u=i(42022),c=i(1971),d=i(79842),h=i(89724),f=i(17415),m=i(88600),p=i(20014),g=i(42231),y=i(87001),v=i(40958),b=i(45599),w=i(55835),S=i(31586),P=i(97790),M=i(89937),T=i(54993),_=i(16737),E=i(9977),k=i(39656),D=i(7656),I=i(21167),C=i(36908),A=i(35052),x=(0,b.defer)(()=>(0,s.mkLogger)("db.Migrations")),F=new RegExp(`^(${(0,a.escapeRegExp)(M.PS_NETWORK_FILESYSTEM_SCHEME)}://.*?/)(.*)$`);function O(e,t){return(0,n.mapGt0)(e,()=>(0,w.map)(function(e,t=u.ModeBits){return(0,p.splitBits)(e,t).map(e=>(0,l.unlabhash)(e,t))}(e,6)[t],e=>(0,l.toLabhash)(e,u.ModeBits)))}function R(e){return e.endsWith(g.TagSep)?e:e+g.TagSep}function L(e){return(0,w.map)((0,d.isoToDated)(e),d.datedToPrecisionMs)??-1}t.lowercase_psnet_function=e=>(0,P.opt)(e).filter(o.isString).flatMap(e=>F.exec(e)).map(e=>e[1].toLowerCase()+e[2]).getOrElse(()=>e),t.Migrations={fix_root_tags:_.fix_root_tags,lowercase_psnet_hostname:e=>{e.function("lowercase_psnet_hostname",{deterministic:!0},t.lowercase_psnet_function),e.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),e.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),e.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")},numeric_captured_at:e=>{e.function("isoToLocal",{deterministic:!0},h.isoToLocal),e.function("isoToOffsetMinutes",{deterministic:!0},f.isoToOffsetMinutes),e.function("isoToPrecisionMs",{deterministic:!0},L),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},O),(0,S.times)(c.ModeCount,t=>e.exec(`ALTER TABLE AssetFile ADD COLUMN mode${t} integer`)),e.exec("UPDATE AssetFile SET "+(0,S.times)(c.ModeCount,e=>`mode${e} = plucklabmodeb6(mode8b6, ${e})`).join(", "))},normalize_asset_file_uris:e=>{e.function("normalizeURI",{deterministic:!0},y.normalizeURI);const t=e.prepare("SELECT normalizeURI(uri) AS nuri, count(*) AS cnt, GROUP_CONCAT(id) AS ids FROM AssetFile GROUP BY nuri HAVING cnt > 1").all(),i=[];for(const s of t){const t=(0,T.toS)(s.ids).split(","),n=e.prepare("SELECT id, shown as isPrimary, version, updatedAt FROM AssetFile WHERE id in ("+t.join(",")+")").all(),a=(0,r.greatestBy)(n,e=>[e.isPrimary,e.version,e.updatedAt]),o=n.filter(e=>e.id!==a?.id);i.push(...o.map(e=>e.id))}for(const t of(0,r.batches)(i,256))e.exec("DELETE FROM AssetFile WHERE id in ("+t.join(",")+")");e.exec("UPDATE AssetFile SET uri = normalizeURI(uri)")},dedupe_tag_paths:C.dedupeTags_,suffix_tag_paths:e=>{e.function("tag_path_suffix",{deterministic:!0},R),(0,C.dedupeTags_)(e),e.exec("UPDATE Tag SET _path = tag_path_suffix(_path)")},normalize_tag_paths:async e=>{const t=e.prepare("SELECT id, _path FROM Tag WHERE _path LIKE '%' || char(31) || char(31) || '%'").all(),i=(0,A.getColumnInfo)(e,"Tag").some(e=>"assetCount"===e.name);x().info("normalize_tag_paths():",{badTags:t});let r=!1;for(const s of t){const t=(0,g.normalizeTagPath)(s._path),n=e.prepare("SELECT id FROM Tag WHERE _path LIKE ?").pluck().all(t),a=(0,v.compact)([s.id,...n]),o=(0,C.mergeTags_)(e,a,i);(0,S.gt0)(o?.losers.length)&&(x().info("normalize_tag_paths(): at least one tag lost: we need to rebuild asset tag counts",{result:o}),r=!0)}i&&r&&await(0,D.rebuildNullTagAssetCounts)(e)},drop_tc_tables:e=>{const t=/^(ct|taf|tag_counts)_[a-z\d]{6}$/i,i=e.prepare("SELECT name FROM sqlite_master WHERE type='table'").pluck().all(),r=i.filter(e=>null!=t.exec(e));x().info("drop_tc_tables()",{tables:i,victims:r});for(const t of r)e.exec("DROP TABLE "+t)},rebuild_rotated_heic:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype = 'image/heif' AND rotation <> 0")},rebuild_videos:e=>{e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%'"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where mimetype LIKE 'video/%')")},copy_asset_duration:e=>{e.exec("CREATE INDEX tmp_af_idx ON AssetFile (assetId, durationMs)"),e.exec("UPDATE Asset SET durationMs = (SELECT durationMs FROM AssetFile WHERE assetId = Asset.id AND durationMs IS NOT NULL LIMIT 1) WHERE durationMs IS NULL"),e.exec("DROP INDEX tmp_af_idx"),e.exec("UPDATE AssetFile SET version = 0 WHERE mimetype LIKE 'video/%' and durationMs IS NULL"),e.exec("UPDATE Asset SET version = 0 WHERE id IN (SELECT DISTINCT assetId from AssetFile where version = 0)")},rebuild_tag_asset_counts:e=>{if(null!=e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='TagHierarchy'").get())return(0,D.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=>{const t=e.prepare("SELECT Tag.id FROM Tag WHERE _path = '"+(0,g.joinTagPath)(["Where","Ghana","Western","Takoradi"])+"'").pluck().get();null!=t&&e.exec("UPDATE Asset SET flags = COALESCE(flags, 0) | "+k.AssetFlags.toBit("finalize")+" WHERE id IN (SELECT assetId FROM AssetTag WHERE tagId = "+t+")")},schema_v3_backfill_nofk:E.schemaV3Backfill,captured_at_src_detail:e=>{const t=(0,A.getColumnInfo)(e,"AssetFile");t.some(e=>"capturedAtSrcDetail"===e.name)||e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtSrcDetail TEXT"),t.some(e=>"capturedAtZoneSrc"===e.name)||e.exec("ALTER TABLE AssetFile ADD COLUMN capturedAtZoneSrc TEXT")},captured_at_src_backfill:e=>{e.function("_parseSrcType",{deterministic:!0},I.parseCapturedAtSrcType),e.function("_parseSrcDetail",{deterministic:!0},I.parseCapturedAtSrcDetail),e.function("_parseSrcZoneSrc",{deterministic:!0},I.parseCapturedAtSrcZoneSrc),e.exec("UPDATE AssetFile SET\n capturedAtSrcDetail = _parseSrcDetail(capturedAtSrc),\n capturedAtZoneSrc = _parseSrcZoneSrc(capturedAtSrc),\n capturedAtSrc = _parseSrcType(capturedAtSrc)\n WHERE capturedAtSrc LIKE '%:%'\n OR capturedAtSrc LIKE '%(%'\n OR capturedAtSrc IN ('stat+bname', 'stat+path')")}}},45678(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelDbJanitor=t.Contested=t.NoOp=t.NoWriteLock=void 0;const r=i(66364),s=i(19851),n=i(23560),a=i(78406),o=i(25764),l=i(99331),u=i(56038),c=i(12959),d=i(55332),h=i(14277),f=i(73209),m=i(28874),p=i(40958),g=i(42659),y=i(6875),v=i(45648);t.NoWriteLock=Symbol("NoWriteLock"),t.NoOp=Symbol("NoOp"),t.Contested=Symbol("Contested");class b extends a.EndableInterval{#ws=0;#Ss;#Ps;#ls;#Ms;#Ts;static for(e){return new b(e)}constructor(e){super({name:"db.DbModelJanitor",callback:()=>this.#_s(),intervalMs:m.Settings.dbBackupIntervalMs.valueOrDefault,initialDelayMs:g.minuteMs,rank:o.EndableRanks.db,endTimeoutMs:5*g.minuteMs,onEnd:()=>this.#Es()}),this.#Ps=e,this.#Ss=e.openLock,this.#ls=e.db,this.#Ms=e.libraryDbFile,this.#Ts=e.libraryDbBackupDir,this.#Ss.tryAcquire_(),(0,n.isDbJanitorService)()||this.pauseInterval()}get db(){return this.#ls}get libraryDbFile(){return this.#Ms}get useReplica(){return this.#ls.isReplica}async#_s(e){try{return await this.#Ss.isOwner_()?this.backup_(e):t.NoOp}catch(e){return this.logger.error("backup_() failed",{error:e}),t.NoOp}}async#Es(){return this.#Ps.teardown_(()=>this.#_s())}#ks(){return this.ended||(0,l.ending)()||(0,r.isSuspended)()||m.Settings.expedite.valueOrDefault}forceBackup_(){return this.backup_(!0)}#Ds=(0,s.lazy)(()=>{const e=(0,v.dbSetupErrors)();(0,p.isEmpty)(e)||this.logger.warn("backup_(): db has setup errors, skipping backup",{errors:e})},g.hourMs);#Is(){return this.#ls.writeCount<this.#ws&&(this.#ws=0),this.#ls.writeCount}#Cs(e,t){return e||t>0&&t>this.#ws}async backup_(e=!1){if((0,v.hasDbSetupErrors)())return this.#Ds(),t.NoOp;e&&(this.#ws=0);const i=this.#Is();return this.#Cs(e,i)?await(0,f.withLock_)({file:this.#Ts,timeoutMs:10*g.minuteMs,noopIfContested:!e},async()=>{const i=this.#Is();return this.#Cs(e,i)?(!this.#ks()&&(0,n.isDbJanitorService)()&&(await(0,h.optimize)(this.#ls.db),await(0,h.maybeResizeCacheAndMmap)(this.#ls.db,this.#ls.dbFile.nativePath)),(0,u.time)({name:"db.backup",p:async()=>{this.#ks()||await this.#ls.checkpoint();const e=this.#Ts.join((0,c.filestamp)()),t=await this.#ls.backup_(e,!this.useReplica);return this.useReplica&&await(0,d.dbBackupCold_)(t,this.#Ms.parent()),this.#ws=this.#ls.writeCount,this.logger.info("backup_(): backup successful",{destDbFile:t}),t}})):(this.logger.debug("backup_(): no update to the db since last backup",{ago:(0,y.fmtDuration)(performance.now()-this.#ls.lastWriteAt),writeCount:this.#ls.writeCount,lastBackupWriteCount:this.#ws}),t.NoOp)})??t.Contested:(this.logger.debug("backup_(): no update to the db since last backup",{ago:(0,y.fmtDuration)(performance.now()-this.#ls.lastWriteAt),writeCount:this.#ls.writeCount,lastBackupWriteCount:this.#ws}),t.NoOp)}}t.ModelDbJanitor=b},74711(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelDbLifecycle=void 0,t.libraryDbObjects_=D;const r=i(76760),s=i(92407),n=i(55332),a=i(15056),o=i(76187),l=i(44955),u=i(87290),c=i(38835),d=i(73209),h=i(95696),f=i(18454),m=i(19851),p=i(50213),g=i(23560),y=i(28874),v=i(2858),b=i(22573),w=i(42659),S=i(31586),P=i(94448),M=i(43431),T=i(98348),_=i(45648),E=(0,m.lazy)(()=>(0,p.mkLogger)("db.ModelDbLifecycle"));class k{libraryDir;openLock;db;useReplica;libraryDbFile;libraryDbBackupDir;dbInfoFile;constructor(e,t,i,r,s,n,a){this.libraryDir=e,this.openLock=t,this.db=i,this.useReplica=r,this.libraryDbFile=s,this.libraryDbBackupDir=n,this.dbInfoFile=a}static async forLibraryDir_(e){if(E().info("forLibraryDir() starting",{libraryDir:e}),f.HealthCheck.addLoadingMsg("Opening database…"),(0,M.modelJsonSetup)(),(0,b.blank)(e))return E().throw("Library directory is not set"+c.NoLibraryErrorFlag);const t=D(e=(0,r.resolve)(e)),{dataDir:i,libraryDbFile:o,libraryDbBackupDir:u}=t,m=i.join("db-open"),p=i.join("db-setup"),v=i.join("db-info.json"),I=d.FsLock.for({file:m,timeoutMs:0,noopIfContested:!1,priority:(0,g.janitorPriority)()}),C=await(0,s.cacheDbFile_)({libraryDir:e,schema:a.Schemas.models});let A;await I.tryAcquire_();let x,F=(0,P.modelDb)();null==F||F.dbFile.isDescendantOf(e)||(E().info("forLibraryDir_(): clearing stale modelDb from different library",{priorDbFile:F.dbFile.nativePath,newLibraryDir:e}),F=void 0,P.modelDb.unset());try{if(await(0,d.withLock_)({file:p,timeoutMs:5*w.minuteMs,noopIfContested:!1},async()=>{if(null!=F)A=F.dbFile.$eql(C),x=F.dbFile;else{const e=await v.readJson("info"),t=await async function(e,t,i){if(null==e)return void E().info("validateSetupInfo_(): no db-info.json found");if("boolean"!=typeof e.useReplica)return void E().warn("validateSetupInfo_(): useReplica is not a boolean",{setupInfo:e});const r=e.useReplica?null!=e.liveDbNativePath?h.PosixFile.for(e.liveDbNativePath):i:t;if(await r.notExists())E().warn("validateSetupInfo_(): live db file doesn't exist",{liveDbFile:r});else{if(await(0,l.isDirSQLiteReadWrite)(r.parent()))return E().info("validateSetupInfo_(): db-info.json is valid",{setupInfo:e,liveDbFile:r}),{liveDbFile:r,useReplica:e.useReplica};E().warn("validateSetupInfo_(): SQLite can't write to db directory",{liveDbFile:r})}}(e,o,C);if(null!=t)E().info("setup_(): using existing db-info.json",{setupInfo:e}),x=t.liveDbFile,A=t.useReplica,F=new T.Db(a.Schemas.models,x,A);else{const e=await async function(e,t,i=y.Settings.forceLocalDbReplica.value){const r=await e.mtimeMs(),s=await t.mtimeMs();if(E().info("determineBestDatabase_(): checking db files",{libraryDbFile:e.nativePath,libraryMtime:r,cacheDbFile:t.nativePath,cacheMtime:s,forceReplica:i}),!0!==i){if((0,S.gt)(s,r)){E().info("determineBestDatabase_(): replica is newer, copying to library");try{await(0,n.dbBackupCold_)(t,e.parent()),E().info("determineBestDatabase_(): copied replica to library")}catch(e){E().warn("determineBestDatabase_(): failed to copy replica to library",{error:e})}}if(await(0,l.isDirSQLiteReadWrite)(e.parent()))return E().info("determineBestDatabase_(): using library db directly"),{liveDbFile:e,useReplica:!1};E().info("determineBestDatabase_(): library not writable, setting up replica")}else E().info("determineBestDatabase_(): forceReplica is set, using replica");if(await(0,l.isDirSQLiteReadWrite)(t.parent())||E().throw("SQLite cannot write to library or cache directory"+c.DbSetupErrorFlag,{libraryDbFile:e,cacheDbFile:t}),(0,S.gt)(r,s)||null==s)try{await f.HealthCheck.traceLater_("Setting up local replica database",(0,n.dbBackupCold_)(e,t.parent()))}catch(i){return E().throw("Failed to set up replica db"+c.DbSetupErrorFlag,{src:e.nativePath,dest:t.nativePath,error:i})}else E().info("determineBestDatabase_(): replica already exists and is current");return{liveDbFile:t,useReplica:!0}}(o,C);x=e.liveDbFile,A=e.useReplica,F=new T.Db(a.Schemas.models,x,A);const t={pid:process.pid,useReplica:A,liveDbNativePath:A?x.nativePath:void 0};await v.writeJson_(t),E().info("setup_(): wrote db-info.json",{newSetupInfo:t})}}if(null==F)return E().throw("Failed to open model db"+c.DbSetupErrorFlag+c.InternalErrorFlag,{libraryDir:e});f.HealthCheck.addLoadingMsg("Upgrading the database…");const t=await F.migrate_();t.errors.length>0&&E().throw("setup_(): db.migrate_() failed",{result:t})}),null==F)return E().throw("Failed to open model db"+c.DbSetupErrorFlag+c.InternalErrorFlag,{libraryDir:e});null==A&&E().throw("setup_(): useReplica is null"+c.DbSetupErrorFlag,{libraryDir:e}),(0,_.clearDbSetupErrors)(),P.modelDb.set(F)}catch(e){throw E().error("Failed to set up model db",{error:e}),(0,_.addDbSetupError)(e),I.release(),e}const O=new k(e,I,F,A,o,u,v);return E().info("setup_() complete",{useReplica:A,liveDbFile:F.dbFile.nativePath,libraryDbFile:o.nativePath}),O}async assertValid_(){await(0,l.assertDirSQLiteReadWrite_)(this.db.dbFile.parent())}async teardown_(e){if(!this.useReplica)return void E().info("teardown_(): not using replica, nothing to do");if(!await this.openLock.iAmOnly_({vacuum:!0}))return void E().info("teardown_(): other processes are still running");E().info("teardown_(): I'm the last one out. Running backup and cleanup."),null!=e&&await e();const t=(0,o.sqliteFiles)(this.db.dbFile);E().info("teardown_(): Removing replica artifacts",{victims:t});for(const e of t)await e.unlink();await this.dbInfoFile.unlink(),E().info("teardown_(): Removed db-info.json")}}function D(e=y.Settings.libraryDir.valueOrDefault){if((0,b.blank)(e))throw new Error("Library directory is not set"+c.NoLibraryErrorFlag);const t=(0,u.libraryDataDirPosixFile)(e);if(null==t)throw new Error("missing library dataDir"+c.NoLibraryErrorFlag);if(!(0,v._libraryHasSettings)(e))throw new Error(`Library at ${e} does not have a settings file`+c.NoLibraryErrorFlag);const i=(0,a.pathToDb)(t,"models");return{dataDir:t,libraryDbFile:i,libraryDbBackupDir:(0,a.dbBackupDir)(i)}}t.ModelDbLifecycle=k},15364(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runActiveLibraryDbMaintenance_=async function(e){await async function(e,t=(0,r.syncReport)()){try{await t.wrapSystemOp_({from:"Cleanup:tagMaintenance",fn_:async()=>(await(e?(0,l.forceRunTagMaintenance)():(0,l.runTagMaintenance)()),"Tag maintenance completed")})}catch(e){d().warn("Failed to run tag maintenance",{error:e})}try{await t.wrapSystemOp_({from:"Cleanup:assetFileVec0Index",fn_:async()=>await(0,u.ensureAssetFileHashHealthy)()?"AssetFileHash index rebuilt":"AssetFileHash index healthy"})}catch(e){d().warn("Failed to check/rebuild AssetFileHash index",{error:e})}try{await t.wrapSystemOp_({from:"Cleanup:sqliteVecMaintenance",fn_:async()=>{const e=(0,c.optimizeAllVectorTables)((0,o.modelDb)().db);return"Sqlite-vec table optimization completed: "+(0,a.stringify)(e)}})}catch(e){d().warn("Sqlite-vec table optimization failed",{error:e})}}(e?.force,e?.report)};const r=i(74128),s=i(50213),n=i(45599),a=i(98553),o=i(94448),l=i(69032),u=i(75914),c=i(30211),d=(0,n.defer)(()=>(0,s.mkLogger)("library.Maintenance"))},23559(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Base=void 0,t.pojoKeys=a,t.toPojo=function(e,t){const i={},o=t?.undefinedToNull??!1;for(const l of t?.fieldNames??a(e)){if(!0===t?.omitKey?.(l)||!0===t?.omitKeys?.includes(l))continue;const a=e[l];void 0===a?o&&(i[l]=null):(0,r.isDated)(a)?i[l]=(0,s.datedToMillis)(a):!0===t?.convertBooleanToInt&&"boolean"==typeof a?i[l]=a?1:0:(null==a||(0,n.isPrimitive)(a))&&(i[l]=a)}return i};const r=i(79842),s=i(66649),n=i(34666);function a(e){if(null==e?.constructor?.name)return Object.keys(e);const t=new Set;let i=e;const r=new Set;for(;null!==i&&i!==Object.prototype;){const e=Object.getOwnPropertyDescriptors(i);for(const[i,s]of Object.entries(e))r.has(i)||(r.add(i),i.startsWith("$")||s.get&&!s.set||"function"!=typeof s.value&&(!s.get&&!s.set&&!0===s.enumerable||s.get&&s.set)&&t.add(i));i=Object.getPrototypeOf(i)}return[...t]}t.Base=class{id;test(e){return e.id}}},27134(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sqlite=async function({dbFile:e,sql:t,args:i}){const r=await(0,b.sqliteNativePath_)(),s=await(0,n.elapsedAsync)((0,u.stdout_)(r,[...(0,F.toA)(i),e.nativePath,t],{timeoutMs:1*T.minuteMs}));return N().debug("sqlite("+t+") on "+e+" in "+s.elapsedMs+"ms",s.result),s.result},t.backupDbFile_=function(e,t,i){const r=i?.timeoutMs??S.Settings.dbMaintenanceTimeoutMs.valueOrDefault;return(0,M.retryOnReject_)(()=>async function(e,t,i){try{await t.parent().mkdirp_(),await t.unlink("trace");const r=await e.size();if(!(0,I.gt0)(r))throw new Error("Cannot backup empty database file: "+e.toString());await((0,R.modelDb)()?.end()),await(0,L.withDb)(e,async e=>e().exec("VACUUM INTO "+(0,m.dbValueToEscapedString)(t.nativePath)),i),N().info("backupDbFile_(): Finished "+e+" -> "+t)}catch(i){throw new g.WrappedError(`Could not back up db ${e} -> ${t}`,{cause:i})}}(e,t,r),{maxRetries:i?.maxRetries??S.Settings.dbRetries.valueOrDefault,retryDelay:i?.retryDelay??T.secondMs,timeoutMs:r,errorIsRetriable:()=>!0})},t.quickCheck_=z,t.integrityCheck_=V,t.foreignKeyCheckStrict_=function(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>0&&N().throw("Foreign key violations detected",{badRowsCount:t.length,badRows:t})},t.foreignKeyCheckAndRepair_=H,t.verifyDb_=U,t.verifyDbFile_=W,t.repairDbFile_=async function(e,t=h.RepairModes.dump){const i=v.PosixFile.for(e),n=(await i.parent().join("db-"+t,(0,c.filestamp)()).mkdirp_()).join(i.base);N().info(`repairDbFile_(${i} -> ${n})`);const a=await(0,f.sqliteSizeBytes)(i),o=(0,l.computeSizeBasedTimeout)({sizeBytes:a,bytesPerSecond:1048576,minTimeoutMs:S.Settings.dbMaintenanceTimeoutMs.valueOrDefault});let d,m;try{const e=await(0,b.sqliteNativePath_)(),l=4*Math.min(20*x.MiB,a),c=new w.PushProgressObserver({path:(0,O.toS)(i),op:"Repairing your database"},l),h=new D.Latch,p=new D.Latch;if(d=(0,u.execFile)(e,[i.nativePath,"."+t],o,{encoding:"buffer",maxBuffer:l}),null==d.stdout)throw new Error("dumpProc.stdout is unexpectedly null");if(d.on("exit",()=>p.resolve()),d.stdout.on("error",e=>{const i=(0,O.toS)(e);q.test(i)?N().info("repairDbFile_(): ignoring stdout error",{error:i}):h.reject(new Error("sqlite "+t+" failed: "+i))}),m=(0,u.execFile)(e,[n.nativePath],o,{encoding:"buffer",maxBuffer:l}),null==m.stdin)throw new Error("load.stdin is unexpectedly null");m.on("exit",()=>h.resolve()),m.stdin.on("error",e=>{h.reject(e)});const g=new s.Transform({transform(e,t,i){c.incrProgress(e.length),i(null,e)}});g.on("error",e=>{h.reject(e)}),d.stdout.pipe(g).pipe(m.stdin),await h,await p,N().info(`repairDbFile_(): recovered to ${n}.`),await W(n),N().info(`repairDbFile_(): ${n} is valid, finishing repair.`);const y=await(0,C.thenCollect)((0,f.sqliteFiles)(i),e=>e.renameYMDHMS_({subdir:"needed-repair"}));{const e=i.parent().join(n.base);try{await n.mv_(e)}catch(t){N().warn(`repairDbFile_(): mv_ failed for ${n.base}, falling back to copy`,{mvErr:t}),await(0,r.copyFile)(n.nativePath,e.nativePath),await n.unlink("trace")}}const v=y.find(e=>".db"===e.ext||e.ext.startsWith(".sqlite"));if(null==v)throw new Error(`repairDbFile_(): Expected .db/.sqlite file in renamed files: ${(0,k.stringify)(y)}`);return v}catch(e){return N().throw("failed to recover DB via dump and restore. Please see https://photostructure.com/faq/restore-db-from-backup/ "+p.FatalErrorFlag,{error:e})}finally{d?.kill(),m?.kill()}};const r=i(51455),s=i(57075),n=i(14121),a=i(19851),o=i(50213),l=i(8141),u=i(84777),c=i(12959),d=i(91872),h=i(99315),f=i(76187),m=i(51040),p=i(38835),g=i(57159),y=i(29882),v=i(95696),b=i(89966),w=i(38156),S=i(28874),P=i(63870),M=i(5233),T=i(42659),_=i(41400),E=i(50357),k=i(98553),D=i(56409),I=i(31586),C=i(20214),A=i(51926),x=i(12168),F=i(59455),O=i(54993),R=i(94448),L=i(9508),N=(0,a.lazy)(()=>(0,o.mkLogger)("db.SQLite"));function j({db:e,pragma:t,okResult:i}){N().debug("pragmaOrThrow_()",{db:B(e),db_open:e?.isOpen,pragma:t,okResult:i});const r=(0,A.isString)(i)?e.pragma(t,{simple:!0}):e.pragma(t);(0,E.eql)(r,i)||N().throw(`${t} failed for ${B(e)}: ${(0,k.stringify)({result:r})}`)}function B(e){return(0,y.ellipsizePath)({p:e.location()??":memory:",maxLength:80})}function z(e){return j({db:e,pragma:"quick_check",okResult:"ok"})}function V(e){return j({db:e,pragma:"integrity_check",okResult:"ok"})}function H(e){const t=(0,F.toA)(e.pragma("foreign_key_check"));t.length>S.Settings.dbInvalidFKThreshold.valueOrDefault&&N().throw("foreignKeyCheckAndRepair_(): too many invalid foreign keys to repair",{dbInvalidForeignKeyThreshold:S.Settings.dbInvalidFKThreshold.valueOrDefault,badRowsCount:t.length,badRows:t});for(const i of t)N().warn("foreignKeyCheckAndRepair_(): deleting row with invalid foreign key",{row:i}),e.prepare(`DELETE FROM ${(0,m.escapeIdentifier)(i.table)} WHERE rowid = ?`).run(i.rowid)}async function U(e){await(0,d.handleDbRetries_)("db.quickCheck",e,z),await(0,_.delay)(1),await(0,d.handleDbRetries_)("db.integrityCheck",e,V),await(0,_.delay)(1),await(0,d.handleDbRetries_)("db.foreignKeyCheck",e,H)}function W(e){return(0,L.withDb)(e,U,(0,P.commandTimeoutMs)())}const q=/no such table: sqlite_\w+/i},30211(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerVectorTable=function(e){o.some(t=>t.tableName===e.tableName)||(o.push(e),a().info("Registered sqlite-vec table for optimization",e))},t.getVectorTables=function(){return o},t.optimizeVectorTable=l,t.optimizeAllVectorTables=function(e){if(!(0,r.isVec0Available)())return a().debug("Skipping vector table optimization: sqlite-vec extension not available"),{optimized:[],skipped:[],failed:[]};if(0===o.length)return a().debug("No sqlite-vec tables registered for optimization"),{optimized:[],skipped:[],failed:[]};const t=[],i=[];a().info(`Optimizing ${o.length} sqlite-vec table(s)...`,{tables:o.map(e=>e.tableName)});for(const r of o)l(e,r.tableName)?t.push(r.tableName):i.push(r.tableName);const s={optimized:t,skipped:[],failed:i};return a().info("Sqlite-vec table optimization complete",s),s};const r=i(7723),s=i(19851),n=i(50213),a=(0,s.lazy)(()=>(0,n.mkLogger)("db.SqliteVecMaintenance")),o=[{tableName:"AssetFileHash",description:"Image perceptual hash similarity (bit vectors)"}];function l(e,t){if(!(0,r.isVec0Available)())return a().debug("Skipping vector table optimize: sqlite-vec not available"),!1;try{return e.exec(`INSERT INTO ${t}(${t}) VALUES('optimize')`),a().info(`Optimized sqlite-vec table: ${t}`),!0}catch(e){return a().warn(`Failed to optimize sqlite-vec table: ${t}`,{error:e}),!1}}},35052(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseTableInfo=u,t.localTableInfo=function(e){return u(e.prepare(c).all())},t.tableExists=function(e,t){return null!=e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(t)},t.getColumnInfo=function(e,t){return e.pragma("table_info("+(0,r.dbValueToEscapedString)(t)+")").map(l)},t.getIndexNames=function(e,t){return e.prepare("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name = ?").pluck().all(t)};const r=i(51040),s=i(22573),n=i(23838),a=i(51926),o=i(35340);function l(e){return{name:e.name,type:e.type.toUpperCase().trim().replace(/\s+/g,""),notnull:1===e.notnull,pk:1===e.pk}}function u(e){const t=new n.MultiMap;for(const i of e)i.tableName.includes("fts")||i.tableName.includes("sqlite_")||(0,o.isVec0ShadowTable)(i.tableName)||(0,s.blank)(i.name)||(0,s.blank)(i.type)||t.add(i.tableName,l(i));return t.entriesArray().map(([e,t])=>({tableName:e,columns:t}))}const c=(0,a.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")},9508(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.withDbSync=function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)(()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i}));try{return t(function(){const e=o();return e.isOpen?e:o.refresh()})}finally{o.prior()?.close()}},t.withDb=async function(e,t,i=s.Settings.dbBusyTimeoutMs.valueOrDefault){const o=(0,n.lazy)(()=>(0,r.mkdb_)({nativePath:(0,a.toS)(e),timeoutMs:i}));try{return await t(o)}finally{o.prior()?.close()}};const r=i(80632),s=i(28874),n=i(30301),a=i(54993)},52850(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assetFileHashHealthCheck=void 0;const r=i(7723),s=i(18454),n=i(28874),a=i(82950),o=i(42659),l=i(45599),u=i(75914),c=i(64526),d={text:"Run maintenance",title:"Run library maintenance, which includes rebuilding the AssetFileHash index",type:"button",method:"POST",url:"/admin/sync/maintenance",icon:"database"};t.assetFileHashHealthCheck=(0,l.defer)(()=>s.HealthCheck.for({section:"Library",id:"library-asset-file-hash-index",ordinal:5,pendingMsg:"Checking image hash index...",evalMode:"syncRequired",timeoutMs:()=>n.Settings.dbMaintenanceTimeoutMs.valueOrDefault,ttlMs:5*o.minuteMs,links:[{text:"Learn about image similarity search",icon:"docs",url:"https://photostructure.com/go/similarity-search"}],later:async e=>{const t=c.Library.instance();if(null==t)return{level:"disabled",msg:["Image hash index check disabled: no library is open"]};const i=await e.awaitOrAbort(t.modelDb());if(!n.Settings.enableSimilaritySearch.valueOrDefault)return{level:"disabled",msg:["Image similarity search is disabled","Set PS_ENABLE_SIMILARITY_SEARCH=true to enable image similarity search."]};if(!(0,r.isVec0Available)()){const e=["Image similarity search is disabled"],t=(0,r.getVec0LoadError)();return null!=t&&e.push("sqlite-vec extension failed to load: "+t.message),{level:"warn",msg:e}}const s=(0,u.checkAssetFileHashTable)(i.db);return s.isHealthy?{level:"ok",msg:["Image hash index is OK",(0,a.ul)([`${s.assetFileCount} image hashes indexed`,`Self-query test: ${s.selfQuery.passed}/${s.selfQuery.tested} passed`])]}:{level:"warn",msg:["Image hash index has issues",(0,a.ul)(s.issues),"","This may affect image similarity search. Click the maintenance button to rebuild the index."],links:[d]}}}))},24271(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryDbHealthCheck=void 0;const r=i(77740),s=i(98314),n=i(18454),a=i(3685),o=i(83496),l=i(82950),u=i(45599),c=i(16185),d=i(45648),h=i(64526),f=i(31687),m={text:"Attempt database repair",title:"Run a dump and reload of your library database to try to repair it",type:"button",method:"POST",url:"/admin/repair-db",icon:"database"};t.libraryDbHealthCheck=(0,u.defer)(()=>{const e=n.HealthCheck.for({section:"Library",id:"library-db",ordinal:1,pendingMsg:"Checking library database…",evalMode:"syncRequired",timeoutMs:()=>10*o.DbSettings.dbMaintenanceTimeoutMs.valueOrDefault,ttlMs:o.DbSettings.dbBackupIntervalMs.valueOrDefault,onReset:()=>(0,d.clearDbSetupErrors)({notifyListeners:!1}),links:[{text:"Read about PhotoStructure and SQLite",icon:"docs",url:"https://photostructure.com/go/sqlite-local-replica"}],later:async e=>{const t=h.Library.instance();if(null==t)return{level:"disabled",msg:["Library database tests disabled: no library is open"]};const i=()=>e.abortable.abort("library ending");t.on("end",i);let n,o=!1;try{const i=performance.now();if(o=!1,(0,d.hasDbSetupErrors)())return{level:"error",msg:["Something is wrong with your library database.",(0,l.ul)((0,d.dbSetupErrors)())],links:[m]};if(n=await e.awaitOrAbort(t.modelDb()),(0,r.getDevEnvFlag)("PS_FAIL_DB_HEALTH_CHECK"))throw new Error("PS_FAIL_DB_HEALTH_CHECK");await e.awaitOrAbort((0,c.assertValidDbSchema_)(n)),o=!0,await e.awaitOrAbort(n.verify_()),f.Heartbeat.assertPing_();const s=await e.awaitOrAbort(t.dbLifecycle_());return{level:"ok",msg:["Library database is OK",(0,l.ul)(["Schema validation and upsert round-trip took "+(0,a.roundMs)(performance.now()-i)+"ms","Live db is "+(0,l.code)(n.dbFile.nativePath),"Local replica mode is "+(0,l.code)(s.useReplica),s.useReplica?"Cold library db is "+(0,l.code)(s.libraryDbFile):void 0])]}}catch(e){return{level:"error",msg:["Library database validation failed",(o?"":"Unrecoverable: ")+(0,s.errorToS)(e),null==n?void 0:"Live db is "+(0,l.code)(n.dbFile.nativePath),null==t?void 0:"Local replica mode is "+(0,l.code)(await t.useReplica())],links:o?[m]:void 0}}finally{t.off("end",i)}}});return(0,d.addDbSetupErrorListener)(()=>e.refresh()),e})},86019(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.libraryHealthCheckSetup=void 0;const r=i(19851),s=i(23560),n=i(18454),a=i(88625),o=i(64526),l=i(52850),u=i(24271),c=i(52981),d=i(88312),h=i(6939),f=i(37191),m=i(40549);t.libraryHealthCheckSetup=(0,r.lazy)(async()=>{(0,a.healthCheckSetup)(),(0,u.libraryDbHealthCheck)(),(0,f.tagHierarchyHealthCheck)(),(0,m.volumeUuidHealthCheck)(),(0,l.assetFileHashHealthCheck)(),(0,h.syncOperationalHealthCheck)(),(0,c.problematicFilesHealthCheck)(),(0,s.isWebService)()&&(0,d.serviceErrorsHealthCheck)(),o.Library.observeReady(()=>n.HealthCheck.resetDebounced())})},52981(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.problematicFilesHealthCheck=void 0;const r=i(18454),s=i(42659),n=i(45599),a=i(33978);t.problematicFilesHealthCheck=(0,n.defer)(()=>r.HealthCheck.for({section:"System",id:"problematic-files",pendingMsg:"Checking for problematic files…",evalMode:"deferrable",ttlMs:30*s.secondMs,later:async()=>{await a.ProblematicPath.reload();const e=a.ProblematicPath.count();return 0===e?{level:"ok",msg:["No files blocked due to timeouts"]}:{level:"warn",msg:[`${e} file${1===e?"":"s"} blocked due to repeated timeouts`,"Visit the System Activity page to review and retry these files."]}},links:[{url:"/sync#problematic",text:"View problematic files",icon:"warning",method:"GET"}]}))},88312(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.serviceErrorsHealthCheck=void 0;const r=i(59039),s=i(18454),n=i(19259),a=i(42659),o=i(45599),l=i(13538),u=i(72914),c=5*a.secondMs;t.serviceErrorsHealthCheck=(0,o.defer)(()=>s.HealthCheck.for({id:"service-errors",section:"System",pendingMsg:"Checking for fatal service errors",evalMode:"local",ttlMs:5*a.minuteMs,links:[{url:"/sync#logs",text:"View logs",icon:"article",method:"GET"}],later:async()=>{const e=await(0,n.findRecentFatalLogEntries)(r.MaxErrorsToCollect,r.MaxErrorAgeMs);if(0===e.length)return{level:"ok",msg:"No recent fatal service errors"};const t=(0,r.groupErrors)(e),i=!!function(e){return e.some(e=>"sync"===e.service)}(t)&&await async function(){try{return null!=await(0,l.thenOrTimeoutMaybe)(u.SyncRpcClient.instance().status(),c)}catch{return!1}}(),s=t.filter(e=>!(function(e){return"web"===e.service&&"config"===e.category}(e)||i&&"sync"===e.service&&function(e){return"config"===e.category||"crash"===e.category||"resource"===e.category}(e))),a=(0,r.determineLevel)(s),o=(0,r.formatErrorTable)(t),d=o[0],h=o.slice(1).join("\n"),f=(0,r.extractLinks)(t);return{level:a,msg:[d,h].filter(Boolean),links:[...f,{text:"Acknowledge & restart sync",type:"button",method:"POST",url:"/admin/acknowledge-errors",icon:"check"}]}}}))},6939(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.syncOperationalHealthCheck=void 0,t.defaultDeps=y,t.checkSyncOperationalState=v;const r=i(29882),s=i(18454),n=i(23560),a=i(14112),o=i(28874),l=i(69385),u=i(82950),c=i(22573),d=i(42659),h=i(45599),f=i(50268),m=i(64526),p=i(72914),g=i(44076);function y(){return{getOperationalState:()=>p.SyncRpcClient.instance().operationalState(),isLibraryOpen:()=>null!=m.Library.instance()}}async function v(e){if(!(e.isLibraryOpen??(()=>null!=m.Library.instance()))())return{level:"disabled",msg:["Sync status check disabled: no library is open"]};try{const t=await e.getOperationalState(),i=o.Settings.libraryDir.valueOrDefault;if(null!=i&&!(0,r.eqlPath)(t.libraryDir,i))return{level:"error",msg:["Sync service library directory mismatch",`Expected: ${i}`,`Got: ${t.libraryDir}`,`If you're running concurrent libraries, either don't set ${(0,u.code)(a.NetworkingSettings.syncPort.key)}, or ensure each library has a unique port.`]};if((0,l.pause)(t.paused),t.paused)return{level:"stop-sync",msg:["Sync service is paused","Visit the System activity page to resume syncing."]};if(t.tooBusy)return{level:"stop-sync",msg:["Sync service reports system is too busy","Sync will resume when CPU utilization drops."]};if((0,c.notBlank)(t.whyDoNotRun))return{level:"stop-sync",msg:["Sync is not running: "+t.whyDoNotRun]};const s=t.healthSummary.level;return(0,f.levelIsNotOK)(s)||"no-library"===s?{level:s,msg:["Sync service reports health issues:",...t.healthSummary.msg]}:{level:"ok",msg:["Sync service is OK",(0,u.ul)("PID: "+(0,u.code)(t.pid),"Started at: "+(0,d.fmtDateShort)(Date.now()-t.uptimeMs),"Library dir: "+(0,u.code)(t.libraryDir))]}}catch(e){const t=e instanceof Error?e.message:"Unknown error",i=(0,g.getServiceError)(),r=["Cannot reach sync service","The sync service may still be starting, or may have stopped.",(0,u.code)("Error")+": "+t];return null!=i&&r.push((0,u.code)("Startup error")+": "+i.message),{level:"warn",msg:r}}}t.syncOperationalHealthCheck=(0,h.defer)(()=>{if((0,n.isWebService)())return s.HealthCheck.for({section:"System",id:"sync-rpc",pendingMsg:"Checking sync service status…",evalMode:"local",ttlMs:30*d.secondMs,later:()=>v(y()),links:[{url:"/activity",text:"View System activity",icon:"speed",method:"GET"}]})})},37191(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tagHierarchyHealthCheck=void 0,t.repairTagHierarchy=function(){const e=Date.now();if(e-u<c)return{success:!1,action:"rate-limited",message:`Repair rate-limited. Please wait ${Math.ceil((c-(e-u))/n.minuteMs)} more minute(s).`};const t=l.TagHierarchy.repairIfNeeded();switch(u=Date.now(),t.action){case"none":return{success:!0,action:"none",message:"Tag hierarchy is already valid. No repair needed."};case"partial":return{success:!0,action:"partial",message:`Repaired ${t.repairedTagIds?.length??0} tags.`};case"full":return{success:!0,action:"full",message:`Full rebuild completed. Fixed ${t.issueCount} issues.`}}};const r=i(18454),s=i(82950),n=i(42659),a=i(45599),o=i(64526),l=i(73716);let u=0;const c=5*n.minuteMs;t.tagHierarchyHealthCheck=(0,a.defer)(()=>r.HealthCheck.for({section:"Library",id:"library-tag-hierarchy",ordinal:10,pendingMsg:"Validating tag hierarchy...",evalMode:"syncRequired",ttlMs:5*n.minuteMs,links:[{text:"About tag hierarchy",icon:"docs",url:"https://photostructure.com/faq/tags/"}],later:async()=>{const e=o.Library.instance();if(null==e||!e.isReadySync())return{level:"disabled",msg:["Tag hierarchy check disabled: no library is open"]};const t=l.TagHierarchy.validate();if(t.isValid)return{level:"ok",msg:["Tag hierarchy is OK"]};const i=[];t.missingSelfRef.length>0&&i.push(`${t.missingSelfRef.length} tags missing self-reference`),t.missingParent.length>0&&i.push(`${t.missingParent.length} tags missing parent relationship`),t.incompleteTransitive.length>0&&i.push(`${t.incompleteTransitive.length} tags with incomplete ancestor chain`),t.cycles.length>0&&i.push(`${t.cycles.length} tags with cycle detected`),t.spuriousEntries.length>0&&i.push(`${t.spuriousEntries.length} tags with spurious entries`),t.orphanedEntries>0&&i.push(`${t.orphanedEntries} orphaned entries`);const r=Date.now(),a=r-u>c,d=Math.round((r-u)/n.minuteMs);return{level:"warn",msg:["Tag hierarchy has inconsistencies",(0,s.ul)(i),`Total affected tags: ${(0,s.code)(String(t.affectedTagIds.length))}`,a?void 0:`Auto-repair skipped (last repair ${d} min ago, min interval: 5 min)`],links:a?[{text:"Repair tag hierarchy",title:"Rebuild affected TagHierarchy entries",type:"button",method:"POST",url:"/admin/repair-tag-hierarchy",icon:"build"}]:void 0}}}))},40549(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.volumeUuidHealthCheck=t.defaultDeps=void 0,t.checkVolumeUuids=y,t.mkVolumeUuidHealthCheck=v;const r=i(34075),s=i(18454),n=i(50213),a=i(45969),o=i(28874),l=i(2858),u=i(40958),c=i(82950),d=i(22573),h=i(45599),f=i(23838),m=i(12168),p=i(94019),g=(0,h.defer)(()=>(0,n.mkLogger)("health.VolumeUUIDHealthCheck"));async function y(e){if(!e.libraryHasSettings())return{level:"disabled",msg:["Volume UUID test disabled: no library is open"]};const t=[],i=[],r=new f.MultiMap,s=[],n=[];function a(e){r.add(e.mountPoint,(0,u.compactBlanks)([e.status,e.error]).join(": "))}for await(const r of e.pathsToSync()){"file"===r.uri.scheme&&(e.isDocker()&&"/"===r.nativePath||t.push(r.nativePath));const o=await e.bestMountPointForPath(r.nativePath);if(null==o)i.push(r.nativePath);else if(!0!==o.ok)a(o);else{const t=await e.getVolumeMetadata(o.mountPoint);null==t?s.push(o.mountPoint):!0!==t.ok?a(t):n.push((0,c.code)(r.nativePath+" → "+r.uri.toString()))}}if(g().info("volumeHealthCheck result",{missingUUIDs:t,missingMountPoints:i,unhealthyMountPoints:r,missingVolumes:s,scanned:n}),(0,u.isEmpty)(t)&&(0,u.isEmpty)(i)&&r.isEmpty()&&(0,u.isEmpty)(s))return(0,u.isEmpty)(n)?{msg:["Nothing is configured to be scanned",(0,c.code)(o.Settings.scanAllDrives.key)+" is false, and "+(0,c.code)(o.Settings.scanPaths.key)+" is empty."],level:"warn"}:{msg:["All scanned paths are OK",(0,c.ul)(n)],level:"ok"};{const e=[];if(!r.isEmpty()){const t=r.keyCount();e.push((0,c.b)((0,m.plur)(t,"volume")+(1===t?" is":" are")+" unhealthy"));for(const t of r.keys()){const i=(0,d.toNotBlank)((0,u.uniq)(r.get(t)).join(","))??"(unknown error)";e.push((0,c.code)(t)+": "+i)}}return(0,u.isEmpty)(t)||e.push((0,c.b)("Some scan paths are missing volume UUIDs"),(0,c.ul)(t.map(e=>(0,c.code)(e))),"This can cause problems with library portability."),(0,u.isEmpty)(i)||e.push((0,c.b)("Internal error: some mount point metadata is unexpectedly missing"),(0,c.ul)((0,u.uniq)(i).map(e=>(0,c.code)(e)))),(0,u.isEmpty)(s)||e.push((0,c.b)("Internal error: some volume metadata is unexpectedly missing"),(0,c.ul)((0,u.uniq)(s).map(e=>(0,c.code)(e)))),{level:"warn",msg:e,links:[{text:"How to manually add a UUID",icon:"handyman",url:"https://photostructure.com/faq/what-is-a-volume/#add-uuid"},{text:"Rescan volumes",type:"button",method:"POST",url:"/admin/clear-caches",icon:"refresh"}]}}}function v(e=t.defaultDeps){return s.HealthCheck.for({section:"Library",id:"volume-uuids",pendingMsg:"Checking volumes…",evalMode:"syncRequired",links:[{text:'What\'s a "volume"?',url:"https://photostructure.com/faq/what-is-a-volume/",icon:"docs"}],onReset:async()=>(0,r.clearFsMetadataCaches)(),later:()=>y(e)})}t.defaultDeps={pathsToSync:p.pathsToSync,bestMountPointForPath:r.bestMountPointForPath,getVolumeMetadata:r.getVolumeMetadata,libraryHasSettings:l.libraryHasSettings,isDocker:a.isDocker},t.volumeUuidHealthCheck=(0,h.defer)(v)},86801(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(98424);process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION",e)}),process.on("uncaughtException",e=>{console.error("UNCAUGHT EXCEPTION",e)}),(0,r.run)()},18390(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fileInfo=async function(e,t){try{const i=f.PosixFile.for(e),r=await(0,S.readMimeType)(i);if(null==r)return{nativePath:i.nativePath,error:`Could not read mimetype for ${i.nativePath}`};if((0,d.isSidecarMimetype)(r))return{nativePath:i.nativePath,mimetype:r,error:"Skipping sidecar mimetype"};if(!await(0,w.isAssetFileMimeType)(i))return{nativePath:i.nativePath,mimetype:r,error:"Skipping non-asset file mimetype"};const u=i.parent();L().throwIfAborted_();const p=await(0,a.readMediaInfo_)(i),E=t?await v.Predicates.explain(u,...(0,c.excludedDirPredicates)(u)):void 0,N=t?await v.Predicates.explain(i,...(0,A.libraryFileFiltersFor)(i,{validateFile:!0})):void 0,j=await(0,x.tagAsset)({primaryVariation:i,files:[],priorTagPaths:[],capturedAt:{},uris:[await i.uri_()]}),B=null==(0,O.modelDb)()?void 0:await new R.AssetFileFinder(i).prior(),z=(null==B?"not found":await(0,o.whyIsMediaInfoStale)(B.ctx(),B,a.MediaInfoFactory.for(i)))??"(up to date)",V=await(0,D.thenCollect)(F.AssetFile.dao.sameShaInLibrary(i),e=>e.nativePath);L().throwIfAborted_();const H=await(0,P.readTags)(i),U=H?.capturedAt,W=(0,m.whyRejectFile)(i,!0===C.Library.instance()?.isReadySync()?(0,A.libraryFileFiltersFor)(i):void 0),q=await(0,h.bestVolumeForPath)(i.nativePath),$=(0,k.compactValues)({...(0,l.omitModeData)(p),uris:(await(0,M.nativePathToUris)(i.nativePath,q)).map(I.toS),capturedAtRaw:U?.capturedAtRaw,...(0,k.pick)(H,"zone","zoneSource","errors","inferred","durationMs"),dirFilters:E,fileFilters:N,mountpoint:await i.mountPoint(),needsTranscoding:await(0,y.needsTranscoding)(i),pathsInLibrary:V,pathToLibraryAsset:(0,b.pathToLibraryAsset)((0,_.localToDate)(p.capturedAtLocal),i),priorAssetFile:B?.toJSON(),whyPriorFileIsStale:z,sidecars:(await i.existingSidecars()).map(e=>e.base),tagResult:j,validFile:(0,T.notBlankOr)(await(0,g.whyInvalidFile)(i.nativePath),"OK"),variantSortCriteria:(0,n.assetFileSortCriteriaPojo)(p),whyExcludedDirectoryRecursive:await(0,c.whyExcludedDirectoryRecursive)(u),whyRejected:W});return(0,k.compactValues)({nativePath:i.nativePath,mimetype:r,...(0,s.sortedKeys)($)})}catch(t){return{nativePath:(0,p.toNativePath_)(e),error:(0,u.errorToS)(t)}}};const r=i(50213),s=i(88158),n=i(92434),a=i(85527),o=i(74800),l=i(85434),u=i(98314),c=i(92423),d=i(32144),h=i(34075),f=i(95696),m=i(62105),p=i(17217),g=i(181),y=i(66106),v=i(78984),b=i(4936),w=i(16170),S=i(54979),P=i(40538),M=i(45200),T=i(22573),_=i(42659),E=i(45599),k=i(68708),D=i(20214),I=i(54993),C=i(64526),A=i(19113),x=i(88224),F=i(54017),O=i(94448),R=i(3996),L=(0,E.defer)(()=>(0,r.mkLogger)("info.InfoImpl"))},64501(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InfoArgs=void 0;const r=i(38639);t.InfoArgs={beforeParse:e=>e.option("--volumes","Emit a table with currently mounted volume metadata. See https://photostructure.com/volumes for details.").option("--mountpoints","Emit a table with currently mountpoints. See https://photostructure.com/volumes for details.").option("--sync-paths","Emit a table listing the paths that will be synced next.").option("--plan","Emit subscription status information. To activate a subscription, visit your PhotoStructure library's About page and click the .").option("--licensing","Alias for --plan.").option("--subscription","Alias for --plan.").option("--child-env","Emit the environment variables provided to all spawned processes.").option("--validate","Only run file validation on the given filenames (requires current PLUS subscription).").option("-j, --json","Emit metadata as un-indented, uncolorized JSON.").option("--load-library","Load the library database so more metadata can be shown (like if a file is currently in your library). This adds a second or two (depending on the size of your library).").option("--filter <term>",'Case-insensitively filter keys by <term>. <term> may have dots. Note that .nativePath is always included. Repeat to filter for multiple terms ("--filter foo --filter bar").',(e,t)=>t.concat([e]),[]).option("--file-filters","Include an exhaustive list of file and directory filters for every filename provided. This is hundreds of lines long, so it's not included by default.").option("--image-hash",'Automatically filter image hash fields. Equivalent to "--filter imageHash --filter imageHashComparison"').option("--flat","Only return values for objects with only one field").option("--suggested-libraries","Emit the suggested library directories (as seen on the settings page).").option("--volumes-ttl","Emit the volume cache time-to-live (use with --debug to see details).").option("--is-library <DIR>","Run a couple quick checks to see if <DIR> looks like a PhotoStructure library.").option("--read-settings <FILE>","Read the given file and output the parsed settings.").option("--reindex","Rebuild the tag full-text index and recount every asset tag count. This may take a minute or two. Don't have a sync running concurrently. Implies --cleanup.").option("--exclude-globs","Emit all file and directory exclusion globs.").option("--globs","Alias for for --exclude-globs.").option("--health","Emit details for all health checks.").option("--doctor","Emit details for all health checks that aren't OK.").option("--skip-health","Disable health checks.").option("--version-check","Check now if the current version is the latest.").option("--table","Emit with console.table() (useful with --volumes or --filter).").option("--clear-caches","Delete all file caches. This includes image, volume, and metadata caches.").option("--cleanup","Run a bunch of maintenance tasks.").option("--why-excluded <DIR...>","Diagnose directory exclusion: show all exclusion predicates, mount point status, NoMedia, and scan path info for each directory (and its ancestors up to the scan root).").option("--embedded","Extract and analyze embedded images from the provided file(s). Tests both small (thumbnail) and large (full-size preview) extraction, showing dimensions, source description, and diagnostic details."),afterParse:e=>{((0,r.isTrue)(e.licensing)||(0,r.isTrue)(e.subscription))&&(e.plan=!0),(0,r.isTrue)(e.excludeGlobs)&&(e.globs=!0)}}},98424(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FilenameArgs=void 0,t._run=De,t.run=async function(){try{await De()}catch(e){console.error(e),(0,A.onError)((0,x.toWrappedError)("Failed",{cause:e,fatal:!0}))}finally{await(0,y.exit)({reason:"done",status:0})}};const s=i(73024),n=r(i(57975)),a=i(44142),o=i(19851),l=i(88158),u=i(23560),c=i(83556),d=i(24526),h=i(94174),f=i(79184),m=i(79781),p=i(92434),g=i(85527),y=i(45608),v=i(56519),b=i(31562),w=i(9727),S=i(69554),P=i(38790),M=i(53978),T=i(49776),_=i(48195),E=i(87290),k=i(46296),D=i(63458),I=i(89412),C=i(98314),A=i(8769),x=i(57159),F=i(83278),O=i(92423),R=i(34075),L=i(85772),N=i(95696),j=i(89966),B=i(63664),z=i(18454),V=i(13940),H=i(53244),U=i(50961),W=i(181),q=i(34592),$=i(81674),G=i(17181),K=i(43205),J=i(28874),Y=i(2858),Z=i(32707),X=i(63225),Q=i(50036),ee=i(40044),te=i(63870),ie=i(14854),re=i(40958),se=i(22573),ne=i(38639),ae=i(42659),oe=i(6875),le=i(41801),ue=i(55835),ce=i(68708),de=i(34666),he=i(5670),fe=i(12168),me=i(59455),pe=i(54993),ge=i(64526),ye=i(99335),ve=i(56992),be=i(77948),we=i(59727),Se=i(31503),Pe=i(86019),Me=i(94019),Te=i(92244),_e=i(18390),Ee=i(64501);class ke{filenames=[];beforeParse(e){e.argument("[FILE...]",["- Provide two or more file paths to see how PhotoStructure will aggregate them into assets.","- If no filenames are provided, info will output diagnostic information.","- File paths should be absolute resolved pathnames.","- To emit valid JSON use --no-color or --json."].join("\n")).action(e=>{this.filenames.push(...(0,re.uniq)(e))})}}async function De(){const e=new ke,t=new S.CLI(he.ServiceNames.info).add(e,Ee.InfoArgs,Se.LogArgs,P.ColorArgs,M.TimingArg),i=(await t.parse()).opts(),r=e.filenames,y=(0,ne.isTrue)(i.flat),A=(0,ne.isTrue)(i.table),x=!0===i.reindex;x&&(J.Settings.recountAllTags.cliValue=!0);const De=x||(0,ne.isTrue)(i.cleanup);(0,ne.isTrue)(i.imageHash)&&(i.filter??=[],i.filter.push("imageHash"),i.filter.push("imageHashComparison"));const Ie=(0,ne.isTrue)(i.fileFilters),Ce=(0,o.lazy)(()=>{if((0,re.isEmpty)(i.filter))return;const e=(0,me.toA)(i.filter);return y&&r.length<=1||e.unshift("nativePath"),2===r.length&&e.push(...e.map(e=>"a."+e),...e.map(e=>"b."+e)),e});function Ae(e){e=function(e){const t=Ce();return null==t?e:Array.isArray(e)?e.map(e=>(0,ce.pickDeep)(e,...t)):(0,ce.pickDeep)(e,...t)}(e),y&&(e=(0,ce.flattenObject)(e));const t=(0,ne.isTrue)(i.json);y&&(0,de.isPrimitive)(e)?console.log(e):t||(0,ne.isFalse)(J.Settings.logColor.value)?console.log(JSON.stringify(e,void 0,t?void 0:2)):A?console.table(e):console.log(n.default.inspect(e,{depth:7,colors:!0,maxArrayLength:1024}))}if((0,ne.isTrue)(i.skipHealth)&&z.HealthCheck.disableAll(!0),(0,se.notBlank)(i.readSettings)){const xe=await(0,Y.importFileSettings_)(F.BaseFile.for(i.readSettings));return Ae({settings:(0,ce.fromEntries)(xe.settings.map(e=>[e.name,e.value])),warnings:xe.warnings})}if(await(0,Y.readSettings)(),De&&(u.isDbJanitorService.set(!0),J.Settings.logLevel.isUnset()&&(J.Settings.logStdout.cliValue=!0,J.Settings.logLevel.cliValue="warn",await(0,G.setupLogger)())),(0,ne.isTrue)(i.clearCaches)){const Fe=(0,re.compact)([(0,V.imageCacheDirSync_)()]);console.log("--clear-caches: deleting ",Fe.map(pe.toS)),await Promise.all(Fe.map(e=>e.rmrf_()))}if((0,ne.isTrue)(i.versionCheck))return await((0,Q.channelVersionsCache)()?.unlink()),J.Settings.autoUpdateCheck.testValueIfUnset=!0,Ae(await(0,ee.versionCheck_)());if((0,ne.isTrue)(i.globs)||(0,ne.isTrue)(i.excludeGlobs)){const Oe=(0,O.excludeGlobs)();return Ae({excludeGlobs:{file:Oe.file.map(e=>(0,ce.pick)(e,"pattern","desc")),dir:Oe.dir.map(e=>(0,ce.pick)(e,"pattern","desc"))}})}if((0,re.isNotEmpty)(i.whyExcluded)){const Re=(0,O.excludeGlobs)(),Le=(0,O.notExcludedDirs)(),Ne=await(0,v.mapAsync)({iter:(0,me.toA)(i.whyExcluded),f:async e=>{const t=F.BaseFile.for(e),i=t.nativePath;try{const e=(0,s.statSync)(i,{bigint:!0}),r=[];for(let e=t.parent();null!=e&&!e.isRoot&&!Le.includes(e.nativePath);e=e.parent()){const t=await(0,O.whyExcludedDirectory)(e);null!=t&&r.push({path:e.nativePath,excluded:t})}return(0,ce.compactValues)({nativePath:i,dev:e.dev.toString(),isDirectory:e.isDirectory()||void 0,isMountPoint:await(0,R.isMountPoint)(i),isExplicitScanPath:(0,D.isExplicitScanPath)(i),isProtected:Le.includes(i)||void 0,excluded:await(0,O.whyExcludedDirectory)(t),excludedAncestors:(0,re.toNotEmpty)(r),noMedia:await(0,L.whyNoMedia)(t)})}catch(e){return{nativePath:i,error:e instanceof Error?e.message:"path is not accessible"}}}});return Ae({activeExcludeGlobs:Re.dir.map(e=>e.pattern),protectedDirs:Le,directories:Ne})}if((0,ne.isTrue)(i.volumes)){const je=await(0,le.iterToA)((0,R.volumes)(async e=>!await(0,O.isExcludedDirectory)(e.mountPoint)));if(null!=je)return Ae(je.map(e=>({...e,size:(0,ue.map)(e.size,fe.fmtBytes),used:(0,ue.map)(e.used,fe.fmtBytes),available:(0,ue.map)(e.available,fe.fmtBytes)})));console.error("--volumes failed. Please retry with --info for details.")}if((0,ne.isTrue)(i.mountpoints)){const Be=await(0,R.getMountPoints)();if(null!=Be)return Ae(Be);console.error("--mountpoints failed. Please retry with --info for details.")}if((0,ne.isTrue)(i.plan)||(0,ne.isTrue)(i.licensing)){const ze=(await(0,$.m)())[0],Ve=(0,ue.map)(ze?.l,e=>({email:e.sub,trial:e.trial,issued_at:e.iat,expires:e.exp,meta:ze.meta}));return Ae({plan:await(0,$.t)(),current_license:Ve})}if((0,ne.isTrue)(i.suggestedLibraries))return Ae(await(0,I.suggestedLibraryDirs)());if((0,ne.isTrue)(i.volumesTtl))return Ae({volumesTTL:await(0,ve.calcVolumesTTL)()??(0,te.volumeMetadataTtlMs)()});if((0,ne.isTrue)(i.childEnv))return Ae((0,w.childEnv)());if(((0,ne.isTrue)(i.loadLibrary)||De)&&await(0,we.loadLibrary_)(),De)return await(0,ye.libraryMaintenance)().runAdminMaintenance_(),Ae({cleanup:"OK"});if((0,ne.isTrue)(i.syncPaths))try{return await(0,we.loadLibrary_)(),Ae(await(0,Te.syncPathsForUI)())}catch(He){console.error("syncPaths: library unavailable, showing configured paths:",He);const Ue=(0,E.libraryOriginalsDirPosixFile)()?.nativePath,We=[];for await(const qe of(0,Me.pathsToSync)())We.push({path:qe.nativePath,library:qe.nativePath===Ue,status:"queued",isNext:!1});return Ae(We)}if((0,se.notBlank)(i.isLibrary)){const $e=await(0,_.whyNotLibraryDir)(i.isLibrary);return Ae((0,ce.compactValues)({isLibrary:null==$e,why:$e}))}if((0,ne.isTrue)(i.validate)){if((0,re.isEmpty)(r))throw new Error("--validate requires filenames");return J.Settings.validateVideos.cliValue=!0,J.Settings.validateJpegImages.cliValue=!0,J.Settings.validateRawImages.cliValue=!0,Ae(await Promise.all(r.map(async e=>[e,(0,se.notBlankOr)(await(0,W.whyInvalidFile)(e),"OK")])))}if((0,ne.isTrue)(i.embedded)){if((0,re.isEmpty)(r))throw new Error("--embedded requires filenames");async function Ge(e){try{const t=await e.sharpDetails_();return{result:{desc:t.desc,dimensions:t.sizeInfo?.dimensions,file:t.file?.nativePath},diagnostics:[...e.diagnostics]}}catch(t){return{result:{error:t.message},diagnostics:[...e.diagnostics]}}}const Ke=[];for(const Je of r)try{const Ye=N.PosixFile.for(Je),Ze=new U.SharpReadable({src:Ye,minDim:{width:80,height:80}}),Xe=new U.SharpReadable({src:Ye});Ke.push({file:Ye.nativePath,smallRequest:{description:"Small request (80x80) - tests thumbnail extraction with trimming",...await Ge(Ze)},largeRequest:{description:"Large request (no limit) - tests full-size preview extraction",...await Ge(Xe)}})}catch(Qe){Ke.push({file:Je,error:`Failed to analyze: ${Qe.message}`})}return Ae(Ke)}if((0,re.isEmpty)(r)){await(0,b.until)(()=>ie.CpuUsage.instance().busyPct(),{timeoutMs:2*ae.secondMs,intervalMs:250});const et={systemInfo:(0,ce.fromEntries)((await(0,be.systemInformation)()).map(({term:e,defn:t})=>[(0,c.asObjectKey)(e),t]))};if(et.versionCheck={userAgent:await(0,K.userAgent)(),...await(0,ee.versionCheck_)().catch(e=>({error:(0,C.errorToS)(e)})),currentChannel:(0,ee.currentChannel)()},et.user_ids=(0,d.userids)(),et.group_ids=(0,a.groupids)(),et.username=await(0,h.username)(),et.paths={libraryDir:J.Settings.libraryDir.valueOrDefault,originalsDir:(0,E.libraryOriginalsDirPosixFile)()?.nativePath,systemSettingsFile:(0,Z.systemSettingsFile)(),librarySettingsFile:(0,Y.librarySettingsFile)()?.nativePath,libraryPreviewsDir:(0,E.libraryPreviewsDirPosixFile)()?.nativePath,librarySyncReportsDir:(0,E.librarySyncReportsDir)()?.nativePath,cacheDir:(0,T.cacheDir)(),logDir:(0,k.logDir)(),toolsDir:(0,j.toolsDir)()?.nativePath,osToolsDir:(0,j.osToolsDir)(),ffmpeg:await(0,q.ffmpegNativePath)(),sqlite:await(0,j.sqliteNativePath_)().catch(e=>"not found: "+(0,C.errorToS)(e))},(0,ne.isTrue)(i.health)?(et.healthSummary=await(0,B.getLocalHealthSummary)(),et.healthChecks=await Promise.all(z.HealthCheck.testResults())):(0,ne.isTrue)(i.doctor)?(await(0,Pe.libraryHealthCheckSetup)(),et.healthChecks=(0,re.toNotEmpty)(await z.HealthCheck.notOkResults())??"all "+z.HealthCheck.enabledTestCount()+" health checks passed"):et.healthSummary=await(0,B.getRemoteOrLocalHealthSummary)(),et.wrongPsEnvValues=(0,X.verifyPsEnvSettings)(),(0,ne.isTrue)(i.loadLibrary)){et.libraryMetrics=(0,ce.fromEntries)((await(0,be.libraryMetrics)())?.map(e=>[(0,c.asObjectKey)(e.desc),e.count])??[]);const tt=await(ge.Library.instance()?.dbLifecycle_());et.libraryDb=null!=tt?{useReplica:tt.useReplica,libraryDbFile:tt.libraryDbFile,libraryDbBackupDir:tt.libraryDbBackupDir}:void 0}return et.volumesTTL=(0,oe.fmtDuration)(await(0,ve.calcVolumesTTL)()),et.nonDefaultSettings=(0,ce.fromEntries)((0,ce.values)(J.Settings).filter(e=>e.hasValue()).map(e=>[e.name,e.humanValue])),Ae(et)}if(2===r.length){const it=N.PosixFile.for(r[0]),rt=N.PosixFile.for(r[1]),st=await(0,g.readMediaInfo_)(it),nt=await(0,g.readMediaInfo_)(rt),at=[];if(null==st&&at.push("Failed to read "+it),null==nt&&at.push("Failed to read "+rt),(0,re.isNotEmpty)(at))return Ae({errors:at});const ot=(0,m.whyNotSimilarMedia)(st,nt),lt=null==ot?"These two files will be aggregated into a single asset.":"These files represent different assets: "+ot;let ut,ct;if(null==ot){const mt=(0,p.sortAssetFilesInPlace)([st,nt]);ut=mt[0]?.nativePath,ct=(0,l.zipPojos)(...mt.map(p.assetFileSortCriteriaPojo))}const dt={fileComparison:lt,primary:ut,a:await(0,_e.fileInfo)(it,Ie),b:await(0,_e.fileInfo)(rt,Ie),cmpArr:ct},ht=H.ImageHashes.for(it),ft=H.ImageHashes.for(rt);return dt.a_assetHashes=await ht.assetHashes_(),dt.b_assetHashes=await ft.assetHashes_(),dt.a_comparison=await ht.compare(ft),Ae(dt)}{const pt=await(0,v.mapAsync)({iter:r,f:e=>(0,_e.fileInfo)(e,Ie)}),gt=(0,ce.fromEntries)(pt?.map((e,t)=>[t,e]));if(pt.length>1){const yt=(0,re.compact)(await(0,v.mapAsync)({iter:r,f:e=>(0,g.readMediaInfo_)(N.PosixFile.for(e)).catch(t=>{console.error("Failed to read "+e,t)})})),vt=(0,f.aggregateAssetFiles)(yt);gt.clusters=vt.map(e=>e.map(e=>e.uri))}return Ae(gt)}}t.FilenameArgs=ke},16737(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fix_root_tags=function(e){for(const t of e.prepare("SELECT id, parentId, _path FROM Tag WHERE id = parentId").iterate())a().warn("fix_root_tags(): broken tag",{broken:t}),(0,s.countChars)(t._path,n.TagSep)<2&&e.prepare("UPDATE Tag set parentId = null where id = ?").run(t.id)};const r=i(50213),s=i(81168),n=i(42231),a=(0,i(45599).defer)(()=>(0,r.mkLogger)("migrations.FixRootTags"))},9977(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.schemaV3Backfill=function(e){if(c().info("Starting schema v3 backfill migration"),0===e.prepare("SELECT COUNT(*) FROM pragma_table_info('AssetFile') WHERE name = 'uri'").pluck().get())return void c().info("Schema is already v3, skipping backfill migration");e.function("extractUriDir",{deterministic:!0},e=>null==e||""===e?null:(0,n.extractUriDirectory_)(e)),e.function("extractBasename",{deterministic:!0},e=>null==e||""===e?null:(0,n.extractUriBasename_)(e)),e.function("extractAuthority",{deterministic:!0},e=>null==e||""===e?null:(0,n.extractUriAuthority_)(e)),c().info("Populating DirUri table");const t=e.prepare("SELECT COUNT(*) FROM AssetFile WHERE uri IS NOT NULL").pluck().get();c().info(`Processing ${t} AssetFile URIs`),e.exec("\nINSERT INTO DirUri (uri)\nSELECT DISTINCT extractUriDir(uri) as uri\nFROM AssetFile\nWHERE uri IS NOT NULL\nORDER BY uri\nON CONFLICT (uri) DO NOTHING;\n");const i=e.prepare("SELECT COUNT(*) FROM DirUri").pluck().get();c().info(`Created ${i} DirUri entries`),c().info("Populating Volume table from AssetFile URIs and mountpoints"),e.exec("\nINSERT INTO Volume (authority, mountPoint, lastSeenAt)\nSELECT\n extractAuthority(uri) as authority,\n mountpoint as mountPoint,\n MAX(updatedAt) as lastSeenAt\nFROM AssetFile\nWHERE uri IS NOT NULL\n AND mountpoint IS NOT NULL\n AND extractAuthority(uri) IS NOT NULL\n AND extractAuthority(uri) != ''\nGROUP BY extractAuthority(uri), mountPoint\nORDER BY authority, mountPoint;\n");const s=e.prepare("SELECT COUNT(*) FROM Volume").pluck().get();c().info(`Created ${s} Volume entries`);const o=new Map;e.function("getTimezone",{deterministic:!0},function(e){return null==e?null:(0,l.getOrSet)(o,e,()=>(0,a.toNotBlank)((0,r.offsetMinutesToZoneName)(e)))??null}),c().info("Populating Asset_new table");const d=e.prepare("SELECT COUNT(*) FROM Asset").pluck().get();c().info(`Migrating ${d} assets`),e.exec("\nINSERT INTO Asset_new (\n id, shown, hidden, rating,\n capturedAtLocal, mimetype, durationMs,\n deletedAt, excludedAt, createdAt, updatedAt, updateCount\n)\nSELECT\n a.id, a.shown, a.hidden, a.rating,\n af.capturedAtLocal, af.mimetype, af.durationMs,\n a.deletedAt, a.excludedAt, a.createdAt, a.updatedAt, a.updateCount\nFROM Asset a\nINNER JOIN AssetFile af ON af.assetId = a.id AND af.shown = 1\nWHERE a.shown = 1;\n"),c().info("Creating URI to DirUri mapping"),e.exec("\nCREATE TEMP TABLE UriToDirUri AS\nSELECT af.id as assetFileId, d.id as dirUriId, extractBasename(af.uri) as basename\nFROM AssetFile af\nINNER JOIN DirUri d ON d.uri = extractUriDir(af.uri)\nWHERE af.uri IS NOT NULL;\n"),c().info("Populating AssetFile_new table");const h=e.prepare("SELECT COUNT(*) FROM AssetFile WHERE uri IS NOT NULL").pluck().get();c().info(`Migrating ${h} asset files`);const f=u.AssetFileFlags.toBit("forceSync");e.exec(`\nINSERT INTO AssetFile_new (\n id, assetId, isPrimary, dirUriId, basename,\n mtime, fileSize, mimetype, width, height, rotation, durationMs,\n cameraId, lensId, imageId, sha,\n capturedAtLocal, capturedAtPrecisionMs, capturedAtZone, capturedAtSrc,\n make, model, rating, aperture, focalLength, fps, geohash, iso, shutterSpeed,\n flags, createdAt, updatedAt, updateCount\n)\nSELECT\n af.id, af.assetId, af.shown as isPrimary,\n m.dirUriId, m.basename,\n af.mtime, af.fileSize, af.mimetype, af.width, af.height,\n COALESCE(af.rotation, 0), af.durationMs,\n af.cameraId, af.lensId, af.imageId, af.sha,\n af.capturedAtLocal, af.capturedAtPrecisionMs,\n getTimezone(af.capturedAtOffset), af.capturedAtSrc,\n af.make, af.model, af.rating, af.aperture, af.focalLength, af.fps,\n af.geohash, af.iso, af.shutterSpeed,\n ${f}, af.createdAt, af.updatedAt, af.updateCount\nFROM AssetFile af\nINNER JOIN UriToDirUri m ON m.assetFileId = af.id\nWHERE EXISTS (SELECT 1 FROM Asset_new WHERE id = af.assetId);\n`),e.exec("DROP TABLE UriToDirUri;"),c().info("Replacing tables"),e.exec("\nDROP TABLE IF EXISTS Asset;\nALTER TABLE Asset_new RENAME TO Asset;\n\nDROP TABLE IF EXISTS AssetFile;\nALTER TABLE AssetFile_new RENAME TO AssetFile;\n"),c().info("Cleaning up orphaned rows in related tables");const m=e.prepare("DELETE FROM AssetRevision WHERE assetId NOT IN (SELECT id FROM Asset)").run().changes,p=e.prepare("DELETE FROM AssetTag WHERE assetId NOT IN (SELECT id FROM Asset)").run().changes;(m>0||p>0)&&c().info("Deleted orphaned rows",{deletedRevisions:m,deletedTags:p}),c().info("Recreating indexes on renamed tables"),c().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()})};const r=i(77988),s=i(50213),n=i(28549),a=i(22573),o=i(45599),l=i(49769),u=i(85018),c=(0,o.defer)(()=>(0,s.mkLogger)("migrations.SchemaV3Backfill"))},43487(e,t,i){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;const s=i(48884),n=i(19851),a=i(92434),o=i(56519),l=i(89724),u=i(38835),c=i(28874),d=i(28544),h=i(38010),f=i(28549),m=i(40958),p=i(75761),g=i(38639),y=i(50357),v=i(11371),b=i(98553),w=i(55835),S=i(31586),P=i(68708),M=i(75020),T=i(59455),_=i(4407),E=i(75914),k=i(63783),D=i(54017),I=i(39656),C=i(48722),A=i(37094),x=i(45295),F=i(54568),O=i(48723),R=i(41507),L=i(72761);class N extends L.TimestampedModel{static $tableName="Asset";static $booleanFields=["shown","hidden"];static#As;static get dao(){return this.#As??=new k.AssetDao}shown;hidden;excludedAt;deletedAt;updateCount;capturedAtLocal;mimetype;rating;durationMs;assetFiles;tags;streams;afterId;beforeId;globalAfterId;globalBeforeId;assetIdish=(0,n.lazy)(()=>({assetId:this.id,v:this.updateCount,capturedAtLocal:this.capturedAtLocal}));imgAttrs;poster;flags;getFlags(){return I.AssetFlags.decode(this.flags)}hasFlag(e){return I.AssetFlags.has(this.flags,e)}addFlag(e){this.flags=I.AssetFlags.add(this.flags,e)}clearFlag(e){this.flags=I.AssetFlags.remove(this.flags,e)}markUnshownAndUpsert(){if((0,S.gt0)(this.id)){const e=this.isActive(),t=e?this.tagIds():[];r.dbl.runf(e=>e.where({id:this.id}).update({shown:0,updatedAt:Date.now()})),this.shown=!1,e&&t.length>0&&O.Tag.dao.deltaAssetCountAndAncestors(t,-1)}else this.shown=!1}#xs(){return{...this.toJSON(),primaryAfId:this.getPrimary({refresh:!1})?.id}}async markShownAndUpsert_(e){const t=this.#xs();await this.setPrimary_(e,{skipAssetUpsert:!0});const i=r.ops().findById(this.id);if(I.AssetFlags.has(i?.flags,"validateSiblings"))return void this.logger().warn("markShownAndUpsert_(): validateSiblings set during operation, aborting");if(null==this.getPrimary({refresh:!0}))return void this.logger().warn("markShownAndUpsert_(): no primary after setPrimary_, aborting");this.shown=!0;const s=this.#xs(),n=this.getPrimary({refresh:!1});(0,y.eql)(t,s)?this.logger().info("markShownAndUpsert_(): no changes, skipping upsert"):(this.logger().info("markShownAndUpsert_(): upserting",{newShown:n}),this.upsert())}mergedTags=(0,n.lazy)(async()=>{const e=new h.MergedTags("Asset:"+this.id);for(const t of this.getAssetFiles()){const i=t.posixFile();null!=i&&await e.addFile(i,(0,g.isTrue)(t.isPrimary))}return e.addRevision(...A.AssetRevision.ops().allf(e=>e.where({assetId:this.id}))),e});async updateFromFiles(){const e=await this.mergedTags();(0,w.map)(e.get("rating"),e=>{this.logger().info("updateFromFiles()",{rating:e}),this.rating=e.value})}isActive(){return(0,S.gt0)(this.id)&&!0===this.shown&&null==this.excludedAt&&null==this.deletedAt&&(null==this.rating||!c.Settings.rejectRating.test(this.rating))}renderCaption(e){return(0,w.map)(this.capturedAtLocal,t=>"Taken "+(0,l.fmtLocalDateShort)(t,e))}async whenApiTag(){const e=(0,_.dateTag)((0,l.localToDateObject)(this.capturedAtLocal));return null==e?void 0:O.Tag.dao.findOrCreate(e).toApiTag({includeChildren:!1})}findAssetFileByUri(e){return this.getAssetFiles()?.find(t=>t.uri===e)}addAssetFile(e){e.$asset===this&&e.assetId===this.id||e.deleteFromArray(e.$asset?.assetFiles),e.assetId=this.id,e.$asset=this;const t=this.getAssetFiles();e.deleteFromArray(t),t.push(e),null==e.basename&&(e.isPrimary=!1),this.clear()}async assetFileForFile_(e,t){const i=await e.uri_(),r=this.getAssetFiles().find(e=>e.uri===i);if(null!=r)return r;const s=new D.AssetFile;return this.addAssetFile(s),!0!==t?.skipUpsert?await s.upsertIfNeeded_(e):await s.setFile_(e),s}tagIds(e){return!0===e?.refresh&&(this.tags=void 0),this.tags?.map(e=>e.id)??x.AssetTag.dbl.pluckAllf(e=>e.select("tagId").where({assetId:this.id}))}getTags(e){return!0===e?.refresh&&(this.tags=void 0),this.tags??=r.dao.getTags(this.id)}tagPaths(){return this.getTags().map(e=>e.path.join("/")).sort()}setTagIds(e){const t=this.tagIds({refresh:!0});if((0,s.eqlUnordered)(t,e))return void this.logger().debug("setTagIds(): no-op, tagIds unchanged");const i=e.filter(e=>!t.includes(e)),r=t.filter(t=>!e.includes(t));return this.applyTagIdDeltas({tagIdsToAdd:i,tagIdsToRemove:r})}applyTagPathDeltas(e){return this.applyTagIdDeltas({tagIdsToAdd:O.Tag.dao.findOrCreateByPathN(e.add??[]).map(e=>e.id),tagIdsToRemove:O.Tag.dao.findByPathN(e.remove??[]).map(e=>e.id)})}applyTagIdDeltas(e={}){const t=this.tagIds({refresh:!0}),i=(0,m.uniq)((0,T.toA)(e.tagIdsToAdd).filter(e=>(0,S.gt0)(e)&&!t.includes(e))),r=(0,m.uniq)((0,T.toA)(e.tagIdsToRemove).filter(e=>(0,S.gt0)(e)&&t.includes(e)));if((0,m.isEmpty)(i)&&(0,m.isEmpty)(r))return this.logger().info("applyTagIdDeltas(): no-op, no changes",{currentTagIds:t,...e}),t;this.isActive()&&O.Tag.dao.deltaAssetCountAndAncestors(t,-1),(0,m.isEmpty)(i)||x.AssetTag.dbl.upsert(i.map(e=>({assetId:this.id,tagId:e}))),(0,m.isEmpty)(r)||x.AssetTag.dbl.runf(e=>e.whereIn("tagId",r).andWhere({assetId:this.id}).delete()),this.tags=void 0;const s=(0,m.uniq)([...t,...i]).filter(e=>!r.includes(e));return this.isActive()&&O.Tag.dao.deltaAssetCountAndAncestors(s,1),s}getStreams(e){if(null==this.streams){const t=this.getTags();this.logger().debug("getStreams()",{tagCount:t.length,limit:e});const i=t.map(t=>t.getAssetStream(this,e));this.streams=(0,R.coalesceStreams)((0,m.compact)(i));for(const e of this.streams)for(const t of e.tags)t.getAncestors()}return this.streams}static#Fs(){return r.dao.shownUnhidden().clearSelect().select({assetId:"id",v:"updateCount",capturedAtLocal:"capturedAtLocal"})}getBeforeAfterId(){const e=r.dbl.all(r.#Fs().andWhere("capturedAtLocal",this.capturedAtLocal).orderBy("assetId")),t=e.filter(e=>e.assetId>this.id);this.afterId=t[0];const i=e.filter(e=>e.assetId<this.id).reverse();this.beforeId=i[0],null==this.afterId&&this.#Os(),null==this.beforeId&&this.#Rs()}#Rs(){const e=r.dbl.all(r.#Fs().andWhere("capturedAtLocal","<",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]).limit(1));this.beforeId??=e[0]}#Os(){const e=r.dbl.all(r.#Fs().andWhere("capturedAtLocal",">",this.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]).limit(1));this.afterId??=e[0]}getBeforeAfterIdInTag(e){const{before:t,after:i}=e.queryBeforeAfter(this,1);this.beforeId=t[0],this.afterId=i[0]}static getChronologicalStream(e,t){t=(0,S.gt0)(t)?t:M.BeforeAfterStreamLimit;const i=(0,m.compact)(r.dbl.all(r.#Fs().andWhere("capturedAtLocal","<",e.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId",order:"desc"}]).limit(t)).map(C.toAssetId)),s=(0,m.compact)(r.dbl.all(r.#Fs().andWhere("capturedAtLocal",e.capturedAtLocal).andWhereNot("id",e.id).orderBy("assetId")).map(C.toAssetId)),n=(0,m.compact)(r.dbl.all(r.#Fs().andWhere("capturedAtLocal",">",e.capturedAtLocal).orderBy([{column:"capturedAtLocal",order:"asc"},{column:"assetId",order:"asc"}]).limit(t)).map(C.toAssetId));for(const t of s)t.assetId<e.id?i.push(t):n.push(t);return new R.TaggedAssetStream([],i,n.reverse(),t)}getTagPaths(){return this.getTags().map(e=>e.path)}getAssetFiles({refresh:e=!1}={}){if((0,S.gt0)(this.id)&&(null==this.assetFiles||!0===e)){const e=D.AssetFile.ops();this.assetFiles=e.allf(e=>e.where({assetId:this.id}).orderBy("id")),(0,a.sortAssetFilesInPlace)(this.assetFiles);for(const e of this.assetFiles)e.$asset=this}return this.assetFiles??[]}async setPrimary_(e,t){const i=e instanceof D.AssetFile?e:D.AssetFile.ops().findById(e);if(null==i)return this.logger().throw("setPrimary_(): asset file not found",{af:i});if(null==i.posixFile_())return this.logger().throw("setPrimary_(): asset file has no native path",{af:i});const s=this.getAssetFiles();this.addAssetFile(i);const n=i instanceof D.AssetFile?i.id:i,a=this.id;if(!(0,S.gt0)(a)||!(0,S.gt0)(n))return this.logger().throw("setPrimary_(): invalid IDs: "+(0,b.stringify)({assetId:this.id,assetFileId:n})+u.InternalErrorFlag);const o=s.find(e=>e.id===n);if(null==o)return this.logger().throw("setPrimary_(): failed to find shown asset file",{af:i});this.logger().info("setPrimary_()",{assetId:this.id,assetFileId:n});for(const e of s)null==e.id&&e.upsert();if((0,g.isTrue)(o.isPrimary)&&o.assetId===a){this.logger().debug("setPrimary_(): file is already primary, skipping DB update");for(const e of s)e.isPrimary=e.id===n;return r.ops().assignFromPojo(this,(0,P.pick)(i,"capturedAtLocal","mimetype","rating","durationMs")),void(!0!==t?.skipAssetUpsert&&this.upsert())}const l=Date.now(),c=s.find(e=>(0,g.isTrue)(e.isPrimary)&&e.id!==n);D.AssetFile.dbl.txn(()=>{D.AssetFile.dbl.runf(e=>e.where({id:n}).update({assetId:a,isPrimary:0,updatedAt:l})),D.AssetFile.dbl.runf(e=>e.where({assetId:a,isPrimary:1}).update({isPrimary:0,updatedAt:l})),D.AssetFile.dbl.runf(e=>e.where({id:n}).update({isPrimary:1,updatedAt:l}))});const d=D.AssetFile.db().db;null!=c?.id&&(0,E.deleteAssetFileHash)(d,c.id),(0,E.syncAssetFileHash)(d,n,{...(0,P.pick)(o,"pHash","rHash","wHash","pHash0","rHash0","wHash0"),capturedAtLocal:o.capturedAtLocal??0,capturedAtSrc:o.capturedAtSrc??"unknown",basename:o.basename});for(const e of s)e.isPrimary=e.id===n,e.updatedAt=l;r.ops().assignFromPojo(this,(0,P.pick)(i,"capturedAtLocal","mimetype","rating","durationMs")),!0!==t?.skipAssetUpsert&&this.upsert()}getPrimary(e){const t=this.getAssetFiles(e).find(e=>(0,g.isTrue)(e.isPrimary));return this.logger().debug("getPrimary()",{opts:e,assetFileId:t?.id}),t}getOrSetPrimary(){const e=this.getPrimary({refresh:!0});if(null!=e)return e;const t=this.getAssetFiles({refresh:!0});if(0===t.length)return;const i=t[0];this.logger().info("getOrSetPrimary(): setting primary on asset with none",{assetId:this.id,bestFileId:i.id,bestFileUri:i.uri,fileCount:t.length});try{return i.isPrimary=!0,i.upsert(),i}catch(e){return this.logger().warn("getOrSetPrimary(): failed to set primary",{assetId:this.id,bestFileId:i.id,error:e}),this.getPrimary({refresh:!0})}}getPrimaryNativePath(){return this.getPrimary()?.nativePath}getCapturedAt(){return d.CapturedAt.fromMediaInfo(this)}link(){return"/asset/"+this.id}sqAttrs(e=!0){return{...(0,p.assetSqImgAttrs)({assetId:this.assetIdish(),lazyLoad:e}),title:this.renderCaption()}}async getImgAttrs(e,t,i=!1){if(null==this.imgAttrs&&(this.imgAttrs=new Map),null==this.imgAttrs.get(t)){const r=e.ap(this.id),s=await r.readInfo();null!=s&&s.mimetype.startsWith("video/")&&(this.poster=await r.posterLink()),this.imgAttrs.set(t,await r.imgAttrs(t,!0,i))}return this.imgAttrs.get(t)}async fitAttrs(e){return{...await this.getImgAttrs(e,v.ReducerNames.fit)}}isVideo(){return this.getAssetFiles().some(e=>e.$isVideo)}videoAttrs(){return{controls:!0,autoplay:!1,poster:this.poster}}async videoSources(){const e=[];let t;for(const i of this.getAssetFiles())e.some(e=>e.type===i.mimetype)||await i.exists_()&&(t??=i,e.push({src:(0,p.assetVideoLink)({assetId:this.assetIdish(),assetFileId:i.id}),type:i.mimetype}));return e.some(e=>"video/mp4"===e.type)||null==t||e.unshift({src:(0,p.assetVideoLink)({assetId:this.assetIdish(),assetFileId:t.id})+".mp4",type:"video/mp4"}),e}async getExistingAssetFiles(){return(0,o.filterAsync)({arr:this.getAssetFiles(),f:e=>e.exists_()})}async findOrCreateByFile(e){const t=await e.uri_();if(null==t)return void this.logger().warn("findOrCreateByFile(): null uri",{nativePath:e.nativePath});const i=(0,f.extractUriDirectory_)(t),r=(0,f.extractUriBasename_)(t),s=F.DirUri.findOrCreateByUri_({uri:i}),n=D.AssetFile.ops().findOneBy({assetId:this.id,dirUriId:s.id,basename:r});if(null!=n)return n;const a=new D.AssetFile;return this.addAssetFile(a),await a.upsertIfNeeded_(e),a}partialSimpleAsset(){return{assetId:this.id,liked:(0,S.gte)(this.rating,c.Settings.likeRating.valueOrDefault),hidden:(0,g.isTrue)(this.hidden),excluded:null!=this.excludedAt,deleted:null!=this.deletedAt}}clear(){return this.imgAttrs=void 0,this.streams=void 0,this.tags=void 0,this.mergedTags.unset(),this}}t.Asset=N,r=N},63783(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetDao=void 0;const r=i(50213),s=i(34102),n=i(74128),a=i(63793),o=i(64526),l=i(43487),u=i(54017),c=i(39656),d=i(71795),h=i(37094),f=i(45295),m=i(48804),p=i(39604),g=i(48723),y={"Asset.shown":1,"Asset.hidden":0,...d.VisibleAsset};class v extends m.ModelDao{constructor(){super(l.Asset)}shownUnhidden(e){return null==e?l.Asset.query().where(y):e.andWhere(y)}shownRemovable(e,t){return(t??l.Asset.query()).whereNotNull(e).andWhere({"Asset.shown":1})}shownCount(){return l.Asset.ops().count(this.shownUnhidden().countDistinct("Asset.id"))}deletePreviews(e){return o.Library.instance().previews().ap(e).deleteAll()}shasByAssetId(e){return u.AssetFile.dbl.pluckAllf(t=>t.select("sha").distinct().where({assetId:e}))}async remove({assetId:e,blocklistShas:t,unlinkAssetFiles:i}){const s=(0,r.mkLogger)("Asset("+e+").remove()"),o=l.Asset.ops().findById(e);if(null==o)return void s.warn("asset not found");const c=o.isActive(),d=o.tagIds();s.info("starting",{unlinkAssetFiles:i});const m=o.getAssetFiles({refresh:!0});if(t){(0,p.upsertToShaBlocklist)(...this.shasByAssetId(e));for(const e of m)(0,n.syncReport)().onProgress({from:"Asset.remove",path:e.nativePath??e.uri,type:"file",state:"blocklisted",details:"sha blocklisted (files with the same sha will not be imported)"})}f.AssetTag.dbl.runf(t=>t.delete().where({assetId:e})),u.AssetFile.dbl.runf(t=>t.delete().where({assetId:e})),h.AssetRevision.dbl.runf(t=>t.delete().where({assetId:e})),l.Asset.dbl.runf(t=>t.delete().where({id:e})),c&&g.Tag.dao.deltaAssetCountAndAncestors(d,-1);try{await this.deletePreviews(e)}catch(t){s.error("Failed to delete previews",{error:t,assetId:e})}return{deletedMeta:i?await(0,a.trashOrRmUris)(m):[],assetFileMeta:m}}getTags(e){return g.Tag.ops().all(g.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",e).orderByRaw("COALESCE(Tag.ordinal, Tag._path)"))}setFlag(e,t){this.updateFlag({assetId:e,flag:t,isSet:!0})}clearFlag(e,t){this.updateFlag({assetId:e,flag:t,isSet:!1})}updateFlag({assetId:e,flag:t,isSet:i}){l.Asset.dbl.runf(r=>c.AssetFlags.update({qb:r,flag:t,isSet:i}).where("id",e))}scheduleFinalizeAsset(e){this.setFlag(e,"finalize"),this.clearFlag(e,"failedFinalize"),(0,s.ee)().emitThrottled("notifyWorkAvailable","finalizeAsset")}}t.AssetDao=v},54017(e,t,i){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFile=void 0;const s=i(76760),n=i(81168),a=i(27248),o=i(85527),l=i(74800),u=i(38835),c=i(8769),d=i(29882),h=i(95696),f=i(16287),m=i(74128),p=i(35721),g=i(69589),y=i(65162),v=i(16170),b=i(34238),w=i(56625),S=i(28549),P=i(87001),M=i(76642),T=i(40958),_=i(17586),E=i(22573),k=i(38639),D=i(33374),I=i(6875),C=i(50357),A=i(11371),x=i(55835),F=i(31586),O=i(68708),R=i(27313),L=i(89937),N=i(75020),j=i(64526),B=i(75914),z=i(41844),V=i(96031),H=i(94761),U=i(43487),W=i(82265),q=i(85018),$=i(39656),G=i(54568),K=i(48723),J=i(72761),Y=i(72965);class Z extends J.TimestampedModel{static $tableName="AssetFile";static $businessKeys=["dirUriId","basename"];static $booleanFields=["isPrimary","monochrome"];static#As;static get dao(){return this.#As??=new W.AssetFileDao}assetId;dirUriId;basename;isPrimary;mtime;fileSize;mimetype;width;height;rotation;durationMs;cameraId;lensId;imageDataHash;imageId;metadataDate;sha;capturedAtLocal;capturedAtPrecisionMs;capturedAtZone;capturedAtSrc;capturedAtSrcDetail;capturedAtZoneSrc;make;model;rating;aperture;focalLength;fps;geohash;iso;shutterSpeed;monochrome;pHash;rHash;wHash;pHash0;rHash0;wHash0;flags;lastVisitedGeneration;updateCount;#Ls;$syncState;#Ns;#js;#Bs;#zs;#Vs;$clear(){this.#Ls=void 0,this.$syncState=void 0,this.#Ns=void 0,this.#js=void 0,this.#Bs=void 0,this.#zs=void 0,this.#Vs=void 0}getFlags(){return q.AssetFileFlags.decode(this.flags)}hasFlag(e){return q.AssetFileFlags.has(this.flags,e)}addFlag(e){this.flags=q.AssetFileFlags.add(this.flags,e)}clearFlag(e){this.flags=q.AssetFileFlags.remove(this.flags,e)}ctx(e){return(0,g.forceContextOrSetting)({...e,...q.AssetFileFlags.toContext(this.flags)})}get $asset(){return null!=this.#Ls?this.#Ls:(0,F.gt0)(this.assetId)?this.#Ls=U.Asset.ops().findById(this.assetId):void 0}set $asset(e){null!=this.assetId&&e?.id!==this.assetId&&this.logger().throw("set $asset(): mismatched .assetId",{currentAssetId:this.assetId,newAssetId:e?.id}),this.#Ls=e,this.assetId=e?.id}get nativePath(){return null!=this.#Bs?this.#Bs:this.#Bs??=Y.Volume.resolve_(this.uri)}get dirUri(){return null==this.#Ns&&(0,F.gt0)(this.dirUriId)&&(this.#Ns=G.DirUri.ops().findById(this.dirUriId)),this.#Ns}get uri(){if(null!=this.#js)return this.#js;if((0,E.blank)(this.basename))return this.logger().throw("uri(): basename is not set",{self:this});const e=this.dirUri;return null==e?this.logger().throw("uri(): dirUriId is not set",{self:this}):this.#js??=e.joinPath(this.basename)}toJSON(){const e=super.toJSON();try{(null!=this.#js||(0,F.gt0)(this.dirUriId)&&(0,E.notBlank)(this.basename))&&(e.uri=this.uri)}catch{}try{null==this.#Bs&&null==e.uri||(e.nativePath=this.nativePath)}catch{}return e}$afterSave(){super.$afterSave(),this.#Hs()}#Hs(){null!=this.id&&(!0!==this.isPrimary||null==this.assetId?(0,B.deleteAssetFileHash)(r.db().db,this.id):(0,B.syncAssetFileHash)(r.db().db,this.id,this))}get uriObject(){return this.#zs??=b.URI.parse(this.uri)}mediaInfo_(){return this.#Vs??=o.MediaInfoFactory.for(this.posixFile_())}setUri(e){(0,E.blank)(e)&&this.logger().throw("setUri(): uri cannot be null, undefined or blank");const t=(0,b.toURI)(e);(0,E.blank)(this.#js)||(0,P.uriEqlSync)(this.#js,t)||this.logger().throw("setUri(): Cannot change URI after initialization - URIs are business keys and should be immutable",{currentUri:this.#js,newUri:e});const i=(0,S.extractUriDirectory_)(t);(0,E.blank)(i)&&this.logger().throw("setUri(): failed to extract directory from URI",{uri:e});const r=(0,S.extractUriBasename_)(t);(0,E.blank)(r)&&this.logger().throw("setUri(): failed to extract basename from URI",{uri:e}),(0,F.gt0)(this.id)&&(0,F.gt0)(this.dirUriId)?r===this.basename&&(0,P.uriEqlSync)(this.uri,t)||this.logger().throw("setUri(): Cannot change URI after initialization - URIs are business keys and should be immutable",{currentUri:this.uri,newUri:e}):(this.#Ns??=G.DirUri.findOrCreateByUri_({uri:i}),this.dirUriId=this.#Ns.id,this.basename=r,this.#js=t.toString())}async setFile_(e){return this.#Bs===e.nativePath||(this.#Bs=e.nativePath,this.setUri(await e.uri_())),this}deleteFromArray(e){null!=e&&(0,F.gt0)(this.id)&&(0,T.filterInPlace)(e,e=>e.id!==this.id&&e.uri!==this.uri)}librarySiblings(){return this.getAsset()?.getAssetFiles().filter(e=>e.id!==this.id&&e.uri.startsWith(L.PS_LIBRARY_PROTOCOL))}get posixPathFromGrandparent(){return(0,x.map)(this.uriObject?.fsPath,d.posixPathFromGrandparent)}isInLibrary(){return(this.uri??"").startsWith(L.PS_LIBRARY_PROTOCOL)}async inSyncWithFile(e){return(0,E.blank)(await this.whyNeedsUpsert(e))}whyNeedsUpsert(e){return(0,l.whyIsMediaInfoStale)(this.ctx(e),this,this.mediaInfo_())}async needsLibraryCopy(){if(this.isInLibrary())return!1;if(!await(0,z.mayCopyAssetsToLibrary)())return!1;const e=j.Library.instanceRequired_().assetFileRepository(),t=await e.whyNotCopyFile(this.posixFile_());if((0,E.notBlank)(t))return this.logger().debug("needsLibraryCopy()",{whyNotCopyFile:t}),!1;const i=this.sha,s=this.imageDataHash,n=r.dbl.pluckAllf(e=>e.select("AssetFile.id").join("DirUri","DirUri.id","AssetFile.dirUriId").where(function(){this.where({sha:i}),null!=s&&this.orWhere({imageDataHash:s})}).andWhereLike("DirUri.uri",L.PS_LIBRARY_PROTOCOL+"/%"));return!!(0,T.isEmpty)(n)||(this.logger().debug("needsLibraryCopy(): found matching AssetFile in library",{matching:n}),!1)}async whyNotNoop(e){{const t=await this.whyNeedsUpsert(e);if(null!=t)return t}return await this.needsLibraryCopy()?"need to copy into library":!0!==(0,k.toBoolean)(this.getAsset()?.shown)?"asset is not shown":void(this.$syncState=m.AssetFileSyncStates.unchanged)}async siblingCount(){return r.dbl.pluckFirstf(e=>e.count().where({assetId:this.assetId}).andWhereNot({id:this.id}))}async upsertIfNeeded_(e,t){if(null!=e&&await this.setFile_(e),null!=await this.whyNeedsUpsert(t))return await this.updateFromFile_(),this.$syncState===m.AssetFileSyncStates.deleted?await this.remove():this.$syncState===m.AssetFileSyncStates.imported&&this.upsert(),this.$syncState===m.AssetFileSyncStates.unchanged?void 0:this;this.$syncState??=m.AssetFileSyncStates.unchanged}async updateFileFields_(){(0,O.assignFields)(this,await(0,R.awaitFields)((0,O.pick)(this.mediaInfo_(),"mtime","fileSize")))}async updateFromFile_(e){if(null!=e&&await this.setFile_(e),await this.exists_()){const e=(0,O.pick)(await this.mediaInfo_().asMediaInfo_(),...a.MediaInfoFieldNames.omit("uri","nativePath","basename"));return(0,O.assignFields)(this,e),this.clearFlag("forceSync"),this.$syncState=m.SyncFileStates.imported,this}return!0===await this.isUriDeleted()?(this.$syncState=m.AssetFileSyncStates.deleted,this.logger().warn("updateFromFile_() file is deleted",{uri:this.uri,basename:this.basename}),await this.remove(),this):(this.$syncState=m.AssetFileSyncStates.unavailable,this)}async updateFromShaSibling_(e){const t=await e.whyNeedsUpsert();if(null!=t)return void this.logger().warn("updateFromShaSibling() sibling is invalid",{whySiblingIsInvalid:t,uri:this.uri,siblingUri:e.uri});const i=(0,O.omit)(e,"id","$instanceId","dirUriId","basename","isPrimary","mtime","createdAt","updatedAt","updateCount","flags","dirUri","uri","$syncState","nativePath","posixFile");if(await this.exists_())return this.logger().debug("updateFromShaSibling",{safeSiblingFields:i}),null==this.sha||this.sha===e.sha?((0,O.assignFields)(this,i),this.updateFileFields_()):this.updateFromFile_();this.logger().warn("updateFromShaSibling(): fail: file is missing",{uri:this.uri,basename:this.basename})}getAsset(){return this.$asset}getAsset_(){const e=this.$asset;return null==e?this.logger().throw("getAsset_(): no parent Asset",{assetId:this.assetId,uri:this.uri,basename:this.basename}):e}async exists_(){return(0,f.exists)(this.nativePath)}async isUriDeleted(){return(await(0,w.isUriDeleted)(this.uri))?.result}async whyRejected(e){return!0===await this.isUriDeleted()?"deleted":(0,V.whyFileRejected)({file:this.posixFile_(),forceFilters:this.ctx(e).forceFilters})}async accepted(){return(0,E.blank)(await this.whyRejected())}get $bname(){return(0,E.mapNotBlank)(this.basename,y.bname)}posixFile_(){return h.PosixFile.for(this.nativePath)}posixFile(){try{return this.posixFile_()}catch{return}}async upgradeUri(e){if(!(0,F.gt0)(this.id))return this.logger().throw("upgradeUri(): unset .id"+u.InternalErrorFlag);if(!await(0,P.uriIsEquivalent)(this.uri,e))return this.logger().throw("upgradeUri(): non-equivalent URIs"+u.InternalErrorFlag,{this_uri:this.uri,newUri:e});if(!(0,E.blank)(this.#js)){const t=(0,S.extractUriDirectory_)(e),i=(0,S.extractUriBasename_)(e),s=G.DirUri.ops().findOneBy({uri:t}),n=s?r.ops().findOneBy({dirUriId:s.id,basename:i}):void 0;if(null!=n)return this.logger().warn("upgradeUri(): prior row with URI exists",{uri:e,prior_id:n.id,old_uri:this.uri}),await this.remove(),n}this.logger().info("upgradeUri()",{prior_uri:this.uri,newUri:e});const t=(0,b.toURI)(e),i=(0,S.extractUriDirectory_)(t),s=(0,S.extractUriBasename_)(t);return this.#js=void 0,this.#Bs=void 0,this.#zs=void 0,this.#Vs=void 0,this.#Ns=G.DirUri.findOrCreateByUri_({uri:i}),this.dirUriId=this.#Ns.id,this.basename=s,this.#js=t.toString(),this.updatedAt=Date.now(),r.dbl.runf(e=>e.update((0,O.pick)(this,"dirUriId","basename","updatedAt")).where({id:this.id})),this}async originalDownloadable({brief:e=!1}={}){const t=this.basename;if(!0===e)return null==t?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:`Download ${t}`,basename:t,description:"Download original"};const i=this.posixFile_();return this.logger().tap({msg:"originalDownloadable()",level:"info",result:null==i||await i.isEmptyOrMissing()?void 0:{href:`/dl/${this.assetId}/${this.id}`,size:"original",title:(0,p.mkDownloadableTitle)(i,"original",this.$isVideo?"video":"image",this),basename:this.basename,description:"Download original",details:`(${(0,D.fmtDim)(this)} ${i.ext})`},meta:{posixFile:i}})}async downloadables(e,t){try{const i=this.posixFile_(),r=e.ap(this.assetId),s=[],n=await this.originalDownloadable();if(null!=n&&s.push(n),this.$isVideo)return s;if(!(0,k.isTrue)(this.isPrimary)&&this.sha!==t)return s;const a=(0,T.compact)(await Promise.all([...await r.previewInfos()].reverse().filter(e=>e.reducer===A.ReducerNames.fit).map(e=>(0,p.previewToDownloadable)(i.base,e))));return s.push(...(0,T.uniqBy)(a,e=>e.size)),s}catch(e){return(0,c.onError)("AssetFile.downloadables failed for "+this.uri,e),[]}}async pathInfo(){try{const e=b.URI.parse(this.uri),t=(0,x.map)((0,M.uriToTagPath)({uri:e,isFile:!0}),e=>K.Tag.dao.findByPath(e));return this._pathInfo_(await(t?.toApiPathElements()))}catch(e){return void this.logger().warn("pathInfo(): failed",{error:e,uri:this.uri,basename:this.basename})}}async _pathInfo_(e){const t=this.posixFile_(),i=t.nativePath,r=b.URI.parse(this.uri);if(null==e||(0,T.isEmpty)(e))return this.logger().warn("pathInfo(): failed to find existing Tag. Returning a simple path.",{uri:this.uri,nativePath:i,tagLineage:e}),{nativePath:i,pathElements:[],nativePathSuffix:i,pathSep:s.sep,exists:await t.exists()};function a(){return(0,_.at)((0,_.at)(e,-1)?.tagPath,-1)}(0,C.eql)(e[0]?.tagPath,[N.TagRoots.fs])&&(e=e.slice(1));const o=r.scheme===L.PS_LIBRARY_SCHEME,l=o?r.path.split("/").slice(1):t.pathnames,u=l.pop(),c=[];for(;l.length>0&&(0,n.equalsIgnoreCase)(a(),(0,_.at)(l,-1));){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("added matching tag",t)}if(o&&a()===N.LibraryTagName){l.pop();const t=e.pop();c.unshift(t),this.logger().debug("pslib: added matching library tag",t)}if(r.scheme===L.PS_LOCAL_FILE_SCHEME){const t=b.URI.parse(this.uri).authority;if(this.logger().debug("psfile: pop last?",{lastTagName:a(),thisVolSha:t}),a()===t){l.pop();const t=e.pop();c.unshift(t)}else this.logger().warn("weird: I expected to be able to include the volsha tag element, but it doesn't seem to match",{thisVolSha:t,tagVolSha:a()})}return this.logger().tap({msg:"pathInfo()",result:{nativePath:i,pathElements:c,nativePathSuffix:u,pathSep:s.sep,exists:await t.exists()}})}async toApi(e,t){const i=await this.pathInfo();if(null!=i)return(0,O.reqValuedOrElse)({assetId:this.assetId,assetFileId:this.id,...i,mimetype:this.mimetype,isPrimary:(0,k.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,t),createdAtLocale:X(this.createdAt),updatedAtLocale:X(this.updatedAt)})}get $isVideo(){return(0,v.isVideoMimeType)(this.mimetype)}async remove(){if(null!=this.id){if(null!=this.assetId)if(0===r.dbl.count(e=>e.where({assetId:this.assetId}).andWhereNot({id:this.id})))this.logger().info(".remove(): Deleting now-empty asset",{assetId:this.assetId}),await U.Asset.dao.remove({assetId:this.assetId,blocklistShas:!1,unlinkAssetFiles:!1});else if((0,k.isTrue)(this.isPrimary)){const e=this.getAsset();null!=e?(e.update({shown:!1,flags:$.AssetFlags.add(e.flags,"validateSiblings")}),null==e.deletedAt&&null==e.excludedAt?(this.logger().info(".remove(): Repairing asset because I was the preview source",{assetId:this.assetId}),(0,H.addTask)("repairAsset",{assetId:this.assetId})):this.logger().info(".remove(): Asset is deleted or excluded, not repairing",{assetId:this.assetId})):this.logger().warn(".remove(): Could not find asset to repair after removing primary AssetFile",{assetId:this.assetId,assetFileId:this.id,uri:this.uri})}else this.logger().debug(".remove(): AssetFile removed without impacting the asset.",{assetId:this.assetId,assetFileId:this.id});super.remove()}else this.logger().warn("remove() called on an AssetFile without an id",{uri:this.uri,basename:this.basename})}}function X(e){return(0,x.map)(e,e=>(0,I.fmtDuration)(Date.now()-e,{units:1})+" ago")}t.AssetFile=Z,r=Z},82265(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileDao=void 0;const r=i(68852),s=i(34102),n=i(22573),a=i(31586),o=i(68708),l=i(89937),u=i(43487),c=i(54017),d=i(48804);class h extends d.ModelDao{constructor(){super(c.AssetFile)}orphan(...e){const t=e.filter(a.gt0),i=t.length>0?c.AssetFile.dbl.runf(e=>e.update({assetId:null,isPrimary:0,updatedAt:Date.now()}).whereIn("id",t)):void 0;return(0,a.gt0)(i?.changes)&&(0,s.ee)().emitThrottled("notifyWorkAvailable","adoptAssetFile"),i}primaryAssetFileId(e){return this.dbl.pluckFirstf(t=>t.where({assetId:e,isPrimary:1}).limit(1))}primaryForAssetId(e){return(0,a.gt0)(e)?this.ops().findOne(u.Asset.dao.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id").select("AssetFile.*").where({assetId:e,"AssetFile.isPrimary":1})):void 0}shownUnhidden({uriRoot:e}={}){let t=u.Asset.dao.shownUnhidden().join("AssetFile","AssetFile.assetId","Asset.id");return(0,n.blank)(e)||(t=t.join("DirUri","AssetFile.dirUriId","DirUri.id").andWhereLike("DirUri.uri",e+"%")),t}recentAssetIdsByUriRoot(e,t,i=64){const r=Date.now()-t;return c.AssetFile.dbl.pluckAll(this.shownUnhidden({uriRoot:e}).distinct("AssetFile.assetId").where("AssetFile.updatedAt",">",r).orderBy("AssetFile.updatedAt","desc").limit(i))}assetFileCountByMimeType(e){const t=this.shownUnhidden({uriRoot:e}).select("AssetFile.mimetype").countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"}).groupBy("AssetFile.mimetype").orderBy("AssetFile.mimetype");return c.AssetFile.dbl.all(t)}assetFileCountWithMimeType(e,t){let i=this.shownUnhidden({uriRoot:t}).countDistinct({assetFileCount:"AssetFile.id",assetCount:"Asset.id"});return i=e.endsWith("/")?i.andWhereLike("AssetFile.mimetype",e+"%"):i.andWhere("AssetFile.mimetype",e),this.dbl.first(i)}assetFileCountByMimeTypeRoots(e=["image/","video/"],t){return e.map(e=>({mimeTypeRoot:e,assetFileCount:this.assetFileCountWithMimeType(e,t)?.assetFileCount??0}))}children(e,t){const i=this.query().join("DirUri","AssetFile.dirUriId","DirUri.id").select("AssetFile.*").whereRaw("(DirUri.uri || '/' || AssetFile.basename) LIKE ?",[e+"/%"]).andWhereRaw("(DirUri.uri || '/' || AssetFile.basename) REGEXP ?",[`^${(0,r.escapeRegExp)(e)}/[^/]+$`]);return this.ops().all(null==t?i:t(i))}async sameShaInLibrary(e){if(null==this.db())return;const t=await e.sha(),i=await e.size();return null!=t&&null!=i?this.ops().all(this.query().join("DirUri","AssetFile.dirUriId","DirUri.id").select("AssetFile.*").where({sha:t,fileSize:i}).andWhereLike("DirUri.uri",l.PS_LIBRARY_PROTOCOL+"%")):void 0}sameAssetFileInLibrary(e){return this.ops().all(this.query().join("DirUri","AssetFile.dirUriId","DirUri.id").select("AssetFile.*").where((0,o.pick)(e,"sha","fileSize")).andWhereLike("DirUri.uri",l.PS_LIBRARY_PROTOCOL+"%").andWhereNot("AssetFile.id",e.id))}sameImageDataHashInLibrary(e){return(0,n.blank)(e.imageDataHash)?[]:this.ops().all(this.query().join("DirUri","AssetFile.dirUriId","DirUri.id").select("AssetFile.*").where("imageDataHash",e.imageDataHash).andWhereLike("DirUri.uri",l.PS_LIBRARY_PROTOCOL+"%").andWhereNot("AssetFile.id",e.id))}countByState(e){const t=this.dbl.first({sql:"\n SELECT\n SUM(CASE WHEN AssetFile.assetId IS NULL THEN 1 ELSE 0 END) as orphans,\n SUM(CASE WHEN AssetFile.assetId IS NOT NULL\n AND Asset.shown = 1\n AND COALESCE(Asset.flags, 0) = 0\n THEN 1 ELSE 0 END) as done,\n SUM(CASE WHEN AssetFile.assetId IS NOT NULL\n AND (Asset.shown != 1 OR COALESCE(Asset.flags, 0) != 0)\n THEN 1 ELSE 0 END) as pending,\n COUNT(*) as total\n FROM AssetFile\n JOIN DirUri ON AssetFile.dirUriId = DirUri.id\n LEFT JOIN Asset ON AssetFile.assetId = Asset.id\n WHERE DirUri.uri LIKE ?\n ",bindings:[e+"%"]});return{orphans:(0,a.toInt)(t?.orphans)??0,pending:(0,a.toInt)(t?.pending)??0,done:(0,a.toInt)(t?.done)??0,total:(0,a.toInt)(t?.total)??0}}}t.AssetFileDao=h},85018(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFlags=t.AssetFileFlagNames=void 0;const r=i(23079),s=i(50989);t.AssetFileFlagNames=(0,s.strEnum)("forceSync","forceFilters","forceCheckLibraryCopy","forceUpdate"),t.AssetFileFlags=new r.Bitfield("AssetFile","flags",t.AssetFileFlagNames)},39656(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFlags=t.AssetFlagNames=void 0;const r=i(23079),s=i(50989);t.AssetFlagNames=(0,s.strEnum)("unused-reaggregate","finalize","validateSiblings","failedFinalize"),t.AssetFlags=new r.Bitfield("Asset","flags",t.AssetFlagNames)},48722(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toAssetId=function(e){const t=(0,s.toGt0)(e?.assetId)??(0,s.toGt0)(e?.id);if(null==e||null==t||!(0,s.isNumber)(e?.capturedAtLocal))return;const i=((0,s.toGt0)(e.v)??(0,s.toGt0)(e.updateCount)??(0,s.toGt0)(e.updatedAt)??0)%1e6,n={assetId:t,capturedAtLocal:e.capturedAtLocal,v:i};return(0,s.gt0)(e.durationMs)&&(n.durationHMS=(0,r.durationHMS)(e.durationMs)),n};const r=i(76596),s=i(31586)},71795(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VisibleAsset=void 0,t.VisibleAsset={"Asset.excludedAt":null,"Asset.deletedAt":null}},37094(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetRevision=void 0;const r=i(98553),s=i(67478),n=i(55046);class a extends n.Model{static $tableName="AssetRevision";static insert(...e){return a.ops().insert(e.map(e=>({assetId:e.assetId,createdAt:Date.now(),field:e.field,op:e.op,_priorValueJson:(0,r.stringify)(e.priorValue),_newValueJson:(0,r.stringify)(e.newValue)})))}assetId;createdAt;field;op;_priorValueJson;_newValueJson;get priorValue(){return(0,s.parseJSON)(this._priorValueJson)}get newValue(){return(0,s.parseJSON)(this._newValueJson)}}t.AssetRevision=a},45295(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetTag=void 0;const r=i(55046);class s extends r.Model{static $tableName="AssetTag";assetId;tagId}t.AssetTag=s},54568(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DirUri=void 0;const r=i(55139),s=i(34102),n=i(95696),a=i(45200),o=i(34238),l=i(22573),u=i(45599),c=i(41400),d=i(54993),h=i(55046);(0,c.later)(()=>{(0,s.ee)().on("clearCache",()=>f._cache.clear()),(0,s.ee)().on("clearDbCache",()=>f._cache.clear())});class f extends h.Model{static $tableName="DirUri";static $businessKeys=["uri"];static _cache=new r.Cache({name:"model.DirUri"});uri;static findOrCreateByUri_(e){"string"==typeof e.uri&&(0,l.blank)(e.uri)&&this.$logger().throw("Invalid blank URI string",{args:e});const t=(0,o.toURI)(e.uri);return((0,l.blank)(t)||(0,l.blank)(t.scheme))&&this.$logger().throw("Invalid URI (missing scheme)",{args:e}),this._cache.getOrSet(t.toString(),()=>f.ops().upsertOne({uri:t.toString()}))}static async findByDirectory_(e){const t=n.PosixFile.for(e),i=await t.uri_();return null==i?this.$logger().throw("findByDirectory_(): failed to make URI for directory: "+t):this.findByUri_(i)}static findByUri_(e){const t=(0,d.toS)(e);return this._cache.getOrMaybeSet(t,()=>f.ops().findOneBy({uri:t}))}uriObject=(0,u.defer)(()=>o.URI.parse(this.uri));nativePath_=(0,u.defer)(()=>(0,a.uriToNativePath_)(this.uriObject()));joinPath(e){return o.URI.joinPath(this.uriObject(),e).toString()}}t.DirUri=f},81421(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Example=void 0;const s=r(i(78474)),n=i(72761);class a extends n.TimestampedModel{static $tableName="Example";static $businessKeys=["name"];static $booleanFields=["isExample"];static ee=new s.default;name;isExample;$transientField;$beforeSave(){super.$beforeSave(),a.ee.emit("beforeSave",this)}$afterSave(){super.$afterSave(),a.ee.emit("afterSave",this)}}t.Example=a},31687(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Heartbeat=void 0;const r=i(38835),s=i(31586),n=i(72761);class a extends n.TimestampedModel{static $tableName="Heartbeat";static $businessKeys=["name"];name;static ping(e){return a.ops().upsertOne({name:e})}static assertPing_(e="ping-"+Date.now()){null==a.db()&&a.$logger().throw("no library is open"+r.NoLibraryErrorFlag,{logLevel:"warn"});try{const t=Date.now();a.ping(e);const i=a.ops().findOneBy({name:e});null!=i&&i.name===e&&(0,s.within)(t,Date.now(),i.updatedAt)||a.$logger().throw("Heartbeat row wasn't inserted")}finally{try{a.dbl.runf(t=>t.delete().where({name:e}))}catch(e){a.$logger().warn("Failed to clean up Heartbeat row",{error:e})}}}}t.Heartbeat=a},55046(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Model=void 0;const r=i(57975),s=i(50213),n=i(7282),a=i(70974),o=i(45599),l=i(50357),u=i(98553),c=i(31586),d=i(54993),h=i(23559),f=i(94448),m=i(63872);let p=0;class g{static $tableName;static $schema="models";static $logger=(0,o.defer)(()=>(0,s.mkLogger)(this.$schema+"."+this.$tableName));static db=f.modelDb;static $primaryKeys;static $businessKeys;static $booleanFields;static get $ctor(){return this.$schema+"."+this.$tableName}static query(){return(0,a.knex)()(this.$tableName)}static ops(){return this._ops??=new m.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(null==e)return!1;if(this.constructor!==e.constructor)return!1;const t=this.class().dbl;return(0,l.eql)(t.pickModelUcn(this),t.pickModelUcn(e))}$ops(){return this.class().ops()}id;class(){return this.constructor}$tableName(){return this.class().$tableName}$instanceId=(0,n.isTest)()?++p:void 0;$uid(){return this.$tableName()+"("+(0,u.stringify)(this.id??this.$ucn())+")"}logger(){return(0,s.mkLogger)(this.class().$schema+"."+(0,d.toS)(this.$uid()))}toString(){return this.$uid()}toJSON(){return(0,h.toPojo)(this,{undefinedToNull:!1,omitKey:e=>e.startsWith("$")||e.startsWith("__")})}toLogJSON(){return(0,h.toPojo)(this,{undefinedToNull:!1})}[r.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 null!=e&&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(){(0,c.gt0)(this.id)&&this.class().dbl.runf(e=>e.delete().where({id:this.id}))}isDeleted(){return null==this.class().ops().findByUcn(this)}}t.Model=g},48804(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelDao=void 0;const r=i(50213);t.ModelDao=class{modelClass;logger;constructor(e){this.modelClass=e,this.logger=(0,r.mkLogger)(`${e.name}Dao`)}db(){return this.modelClass.db()}get dbl(){return this.modelClass.dbl}ops(){return this.modelClass.ops()}query(){return this.modelClass.query()}}},94448(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modelDb=void 0,t.libraryModelDbFile=function(e){return(0,a.map)((0,s.libraryDataDirPosixFile)(e),e=>(0,r.pathToDb)(e,"models"))};const r=i(15056),s=i(87290),n=i(19851),a=i(55835);t.modelDb=(0,n.lazy)(()=>{})},43431(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.modelJsonSetup=void 0;const r=i(19851),s=i(98553),n=i(43487),a=i(54017),o=i(37094),l=i(45295),u=i(54568),c=i(81421),d=i(31687),h=i(20958),f=i(49796),m=i(55009),p=i(2847),g=i(39604),y=i(48723),v=i(73716),b=i(72965);t.modelJsonSetup=(0,r.lazy)(()=>{for(const e of[n.Asset,a.AssetFile,o.AssetRevision,l.AssetTag,u.DirUri,c.Example,d.Heartbeat,h.Operation,f.Progress,m.ProgressMeta,p.RejectedFile,g.ShaBlocklist,y.Tag,v.TagHierarchy,b.Volume])s.JsonRevivableClasses.add(e)})},63872(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelOps=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(38835),o=i(28874),l=i(40958),u=i(76790),c=i(38639),d=i(50357),h=i(96249),f=i(31586),m=i(68708),p=i(59455),g=i(86859),y=i(23559);t.ModelOps=class{model;db;dbl;#$;constructor(e,t){this.model=e,this.db=t;const i=`ModelOps(${e.$tableName})`;this.#$=(0,n.mkLogger)(i),this.dbl=new g.DbRequest({db:this.db,tableName:e.$tableName,primaryKeys:e.$primaryKeys,businessKeys:e.$businessKeys})}assignFromPojo(e,t){const i=e;if(null==t||i===t)return e;const r=t,s=this.dbl.businessKeys(),n=this.model.$booleanFields??[];for(const t of(0,u.sortBy)((0,m.keys)(r),e=>["uri"!==e,e])){const a=r[t];if(void 0!==a)if((0,m.isObject)(a))this.#$.debug("assignFromPojo(): ignoring non-primitive value",{k:t,v:a,dest:e});else if("uri"!==t||"function"!=typeof e.setUri)try{s.includes(t)?i[t]??=a:n.includes(t)?i[t]=null==a?a:(0,c.isTrue)(a):i[t]=a}catch(e){if(e instanceof TypeError&&e.message.includes("Cannot set property")){this.#$.debug("assignFromPojo(): skipping getter-only property",{k:t,v:a,error:e.message});continue}throw e}}return e}$pickPrimaryKeys(e){return(0,m.pickRequired)(e,...this.dbl.primaryKeys())}$pickBusinessKeys(e){return(0,m.pickRequired)(e,...this.dbl.businessKeys())}updatableColumnNames=(0,s.lazy)(()=>(0,l.diff)(this.dbl.columnNames(),[...this.dbl.primaryKeys(),...this.dbl.businessKeys()]));columnNames(){return this.dbl.columnNames()}query(){return this.model.query()}fromJSON(e){if(!(0,m.isEmptyObj)(e))return this.model.fromJSON(e)}fromJSONs(e){return(0,l.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,t){return(0,f.gt0)(e)?this.findOneBy({...t,id:e}):void 0}findByIds(e){e=(0,p.toA)(e).filter(f.gt0);const t=(0,r.batches)(e,o.Settings.dbBatchSelectSize.valueOrDefault).map(e=>this.dbl.all(this.query().whereIn("id",e)));return(0,u.sortBy)(this.fromJSONs((0,h.flatten)(t)),t=>e.indexOf(t.id))}findBy(e){return this.all(this.model.query().where(e))}rows(e){return this.count(e??this.model.query().count())}count(e){return(0,f.toGt0)(this.dbl.pluckFirst(e))??0}countf(e){return this.count(e(this.query()))}insert(e){return(0,p.toA)(e).map(e=>this.insertOne(e))}upsertOne(e){if(!this.dbl.modelSupportsUpsert())return this.insertOrUpdateOne(e);const t=this.fromJSON(e);if(null==t)return this.#$.throw("upsertOne(): fromJSON returned null"+a.InternalErrorFlag,{t:e});t.$beforeSave();const i=this.dbl.upsertOne(this.toDbJson(t)),r=(0,f.toGt0)(i.runResult.lastInsertRowid);return(0,d.eql)(this.dbl.primaryKeys(),["id"])&&null==t.id&&null!=r&&(this.#$.debug("upsertOne(): assigned .id",{lastInsertRowid:r}),t.id=r),"upsert"===i.method&&this.reloadOne(t),t.$afterSave(),this.#$.tap({msg:"upsertOne()",result:t,meta:{input:e}})}insertOrUpdateOne(e){return null==(0,m.pickRequired)(e,...this.dbl.primaryKeys())?this.insertOne(e):this.updateOne(e)}insertOne(e){let t=this.fromJSON(e);if(null==t)return this.#$.throw("insertOne(): fromJSON returned null"+a.InternalErrorFlag,{t:e});t.$beforeSave();const i=t.$toDbJSON(this.columnNames()),r=this.dbl.runf(e=>e.insert(i));return this.dbl.primaryKeys().includes("id")?t.id=(0,f.toGt0)(r.lastInsertRowid):t=this.reloadOne(t),t.$afterSave(),this.#$.tap({msg:"insertOne()",result:t,meta:{input:e}})}unsetField(e,t){return this.#$.debug("unsetField()",{id:e,fieldName:t}),this.dbl.runf(i=>i.where({id:e}).update(t,null))}updateOne(e){const t=this.fromJSON(e);if(null==t)return this.#$.throw("Invalid arg passed to updateOne",{arg:e,nonRetriable:!0,internal:!0});const i=this.$pickPrimaryKeys(t)??this.$pickBusinessKeys(t);if(null==i)return this.#$.throw("Invalid arg passed to updateOne",{arg:e,nonRetriable:!0,internal:!0});t.$beforeSave();const r=t.$toDbJSON(this.updatableColumnNames());return this.dbl.runf(e=>e.where(i).update(r)),t.$afterSave(),this.#$.tap({msg:"updateOne()",result:t,meta:{input:e}})}pickModelUcn(e){return this.dbl.pickModelUcn(e)}findByUcn(e){const t=this.pickModelUcn(e);return null==t?void 0:this.findOneBy(t)}reloadOne(e){const t=this.$pickBusinessKeys(e)??this.$pickPrimaryKeys(e);if(null==t)return void this.#$.warn("reloadOne(): insufficient partial model",{m:e});const i=this.dbl.first(this.query().where(t));return null==i?void this.#$.warn("reloadOne(): failed to find result in db",{ucn:t,m:e}):this.assignFromPojo(e,i)}reload(e){return(0,l.compact)(e.map(e=>this.reloadOne(e)))}toDbJson(e,t){return(0,y.toPojo)(e,{convertBooleanToInt:!0,fieldNames:t??this.columnNames(),omitKey:t=>void 0===e[t]||t.startsWith("$")||t.startsWith("__")&&t.endsWith("__")})}upsert(e){return e=(0,l.compact)(e),this.dbl.modelSupportsUpsert()?e.map(e=>this.upsertOne(e)):e.map(e=>this.insertOrUpdateOne(e))}delete(e){const t=(0,p.toA)(e).filter(f.gt0);return 0===t.length?void this.#$.debug("delete(): no rows to delete",{ids:e}):this.dbl.run(this.model.query().delete().whereIn("id",t))}async batched(e){const t=e.batchSize??o.Settings.dbBatchSelectSize.valueOrDefault,i=`${this.model.$tableName}.id`;let r,s;do{r=this.allf(r=>(r=e.qb(r),null!=s&&(r=r.andWhere(i,">",s)),r.orderBy(i,"asc").limit(t))),(0,l.isNotEmpty)(r)&&(s=Math.max(...r.map(e=>e.id)),await e.onResults(r))}while((0,l.isNotEmpty)(r))}}},20958(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.OperationNames=void 0;const r=i(19851),s=i(50213),n=i(99331),a=i(70025),o=i(8769),l=i(22573),u=i(98553),c=i(50989),d=i(72761);t.OperationNames=(0,c.strEnum)("rebuildLibrary","forceRestartSync","forceSyncPath","checkLibraryCopy","reaggregate","forceFilters","forceSync","country_flag_displaynames","country_code_paths","toolChangeResync");const h=(0,r.lazy)(()=>(0,s.mkLogger)("model.Operation")),f=new Map;class m extends d.TimestampedModel{static $tableName="Operation";name;value;completedAt;static incomplete(){return this.ops().allf(e=>e.whereIn("id",e=>e.table(m.$tableName).min("id").whereNull("completedAt")))}static ensurePendingOp(e){return m.getFirstPendingOp(e)??m.ops().insertOne(e)}static getFirstPendingOp(e){return h().tap({msg:"getFirstPendingOp",result:this.ops().findOnef(t=>{const i=t.whereNull("completedAt").orderBy("createdAt","asc");return null!=e?i.andWhere(e):i}),meta:{crit:e}})}static getAllPending(e){return this.ops().allf(t=>t.whereNull("completedAt").andWhere(e).orderBy("createdAt","asc"))}static markOpCompleted(e,t){return(0,l.blank)(e?.name)?h().throw("markOpCompleted(): bad query",{crit:e}):this.dbl.runf(i=>i.whereNull("completedAt").andWhere(e).update({completedAt:Date.now(),...t}))}static async applyIfPending(e,t){const i=this.ops().findOnef(t=>t.whereNull("completedAt").andWhere(e));return h().info("applyIfPending()",{crit:e,op:i}),null==i?void 0:t(i)}static async applyOnce_(e,t){const i=`${e.name}:${e.value??""}`,r=f.get(i);if(null!=r)return h().debug("applyOnce(): waiting for in-flight operation",{crit:e}),void await r.catch(()=>{});const s=this.ops().findOnef(t=>t.whereNotNull("completedAt").andWhere(e));if(null!=s)return void h().debug("applyOnce(): already done",{priorCompleted:s});const l=this.ensurePendingOp(e);let c,d;const m=new Promise((e,t)=>{c=e,d=t});f.set(i,m);try{const e=await t(l);return(0,n.ending)()||l.markCompleted(),c(e),e}catch(t){if(d(t),!0===(0,a.isRetriableError)(t))return void h().info("applyOnce(): retriable error",{crit:e,error:t});throw(0,o.onError)("Operation.applyOnce(): "+(0,u.stringify)(e),t),t}finally{f.delete(i)}}markCompleted(){null==this.completedAt&&(this.completedAt=Date.now(),this.upsert())}}t.Operation=m},49796(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Progress=void 0,t.toPct=E,t.defaultMinCreatedAt=D;const r=i(48161),s=i(1708),n=i(48884),a=i(34102),o=i(19851),l=i(50213),u=i(28874),c=i(12236),d=i(40958),h=i(42659),f=i(45599),m=i(98553),p=i(55835),g=i(31586),y=i(68708),v=i(67478),b=i(51926),w=i(59455),S=i(54993),P=i(76386),M=i(55009),T=i(72761),_=(0,f.defer)(()=>(0,l.mkLogger)("model.Progress"));function E(e){return null==e||!(0,g.isNumber)(e)||e<0||e>100?void 0:(0,g.sigFigs)(e,3)}const k=(0,b.compressWhitespace)("\nSELECT\n p1.uri,\n p1.id as lastProgressId,\n p1.createdAt as lastStartedAt,\n p1.updatedAt as lastUpdatedAt,\n p3.lastCompletedAt,\n p3.lastCompletedProgressId\nFROM\n Progress AS p1\n JOIN (\n SELECT\n uri,\n max(updatedAt) AS lastUpdatedAt\n FROM\n Progress\n GROUP BY\n 1\n ) AS p2 ON p1.uri = p2.uri\n AND p1.updatedAt = p2.lastUpdatedAt\n LEFT JOIN (\n SELECT\n p.uri,\n p.completedAt AS lastCompletedAt,\n p.id AS lastCompletedProgressId\n FROM\n Progress p\n JOIN (\n SELECT uri, max(completedAt) AS maxCompletedAt\n FROM Progress\n WHERE completedAt > 0\n GROUP BY uri\n ) latest ON p.uri = latest.uri AND p.completedAt = latest.maxCompletedAt\n ) AS p3 ON p1.uri = p3.uri\nGROUP BY\n p1.uri");function D(){const e=u.Settings.progressStaleDays.valueOrDefault;return e<=0?0:Date.now()-e*h.dayMs}class I extends T.TimestampedModel{static $tableName="Progress";uri;hostname;pid;volume;state;hed;dekJSON;completePct;incompletePct;scanningPct;completedAt;static vacuum(e=u.Settings.progressRetentionDays.valueOrDefault*h.dayMs){const t=Date.now()-e,i=this.dbl.pluckAllf(e=>e.select("id").where("createdAt","<=",t));for(const e of(0,n.batches)(i,u.Settings.dbBatchSelectSize.valueOrDefault))M.ProgressMeta.dbl.runf(t=>t.whereIn("progressId",e).delete()),I.dbl.runf(t=>t.whereIn("id",e).delete())}static lazyVacuum=(0,o.lazy)(()=>I.vacuum(),h.dayMs);static times(){return _().tap({msg:"times()",result:this.dbl.all({sql:k})})}static insertNew(e){const t=(0,p.map)(e.dek,m.stringify);return this.ops().insertOne({...(0,y.omit)(e,"dek"),dekJSON:t})}upsert(e){return null!=e&&(null!=e.dek&&(this.dek=e.dek),this.assignFromPojo(e)),super.upsert()}$beforeSave(){super.$beforeSave(),null==this.id&&(this.pid??=s.pid,this.hostname??=(0,r.hostname)()),(0,c.isTerminalSyncStatus)(this.state)&&(this.completedAt??=Date.now()),this.completePct=E(this.completePct),this.incompletePct=E(this.incompletePct),this.scanningPct=E(this.scanningPct)}$afterSave(){super.$afterSave(),(0,P.tellWebProgressUpdated)(),(0,a.ee)().emit("progressUpdated"),(0,a.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(0,d.compactBlanks)((0,v.parseJSON)(this.dekJSON))}set dek(e){var t;this.dekJSON=(t=e,(0,m.stringify)((0,d.compactBlanks)((0,w.toA)(t))))}assignFromPojo(e){return this.$ops().assignFromPojo(this,(0,y.omit)(e,"volume","uri"))}getMeta(){return M.ProgressMeta.ops().allf(e=>e.where({progressId:this.id}).orderBy("createdAt"))}getPriorIncomplete(e=D()){return this.logger().tap({msg:"priorIncompleteProgress()",result:I.ops().findOnef(t=>t.where({hostname:this.hostname,uri:this.uri,completedAt:null}).andWhere("createdAt",">",e).orderBy("updatedAt","desc"))})}getLastCompletedAt(e=D()){return I.dbl.pluckFirstf(t=>t.max("completedAt").where({uri:this.uri}).andWhere("createdAt",">",e))}getLastIncompleteStartAt(){return I.dbl.pluckFirstf(e=>e.min("createdAt").where({uri:this.uri}).andWhere("createdAt",">",this.getLastCompletedAt()??0))}setMeta(e,t){return this.logger().debug("setMeta()",{progressId:this.id,name:e,value:t}),M.ProgressMeta.ops().upsertOne({progressId:this.id,name:e,value:t})}setMetaRecord(e){const t=this.getMeta(),i=(0,d.diff)(t.map(e=>e.name),Object.keys(e));this.logger().debug("setMetaRecord()",{progressId:this.id,keysToDelete:i,record:e}),M.ProgressMeta.ops().upsert((0,y.entries)(e).map(([e,t])=>({progressId:this.id,name:e,value:(0,S.toS)(t)}))),(0,d.isNotEmpty)(i)&&M.ProgressMeta.dbl.runf(e=>e.where({progressId:this.id}).whereIn("name",i).delete())}deleteMeta(...e){return this.logger().debug("deleteMeta()",{progressId:this.id,names:e}),M.ProgressMeta.dbl.runf(t=>t.whereIn("name",e).andWhere({progressId:this.id}).delete())}deleteAllMeta(){return this.logger().debug("deleteAllMeta()",{progressId:this.id}),M.ProgressMeta.dbl.runf(e=>e.where({progressId:this.id}).delete())}getMetaAsRecord(){return this.logger().tap({msg:"getMetaAsRecord()",result:(0,y.fromEntries)(this.getMeta().map(e=>[e.name,e.value]))??{}})}}t.Progress=I},55009(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProgressMeta=t.ProgressMetaNames=t.DirSyncProgressMetaNames=void 0;const r=i(50989),s=i(72761);t.DirSyncProgressMetaNames=(0,r.strEnum)("lastScannedDirectory","scannedDirectoryCount","completedDirectoryScan","enqueuedStaleFiles","processedImageCount","processedVideoCount","completedDirectorySync","scanGeneration","totalFilesDiscovered","excludedByFilterCount","excludedByImporterCount","erroredCount","excludedDirCount","newImageCount","newVideoCount","updatedImageCount","updatedVideoCount","unchangedImageCount","unchangedVideoCount","absentCount","resumed","syncReportFilename"),t.ProgressMetaNames=(0,r.strEnum)(...t.DirSyncProgressMetaNames.values);class n extends s.TimestampedModel{static $tableName="ProgressMeta";static $businessKeys=["name","progressId"];progressId;name;value}t.ProgressMeta=n},2847(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RejectedFile=void 0;const r=i(54568),s=i(55046);class n extends s.Model{static $tableName="RejectedFile";static $businessKeys=["dirUriId","basename"];dirUriId;basename;mtime;fileSize;why;updatedAt;static async findRejectedFile_(e){const t=await e.parent().uri_(),i=r.DirUri.findByUri_(t);if(null==i)return;const s=n.ops().findOneBy({dirUriId:i.id,basename:e.base});return null!=s?s.mtime===await e.mtimeMs()&&s.fileSize===await e.size()?s:void s.remove():void 0}static async removeRejectedFile_(e){const t=await e.parent().uri_(),i=r.DirUri.findByUri_(t);if(null==i)return;const s=n.ops().findOneBy({dirUriId:i.id,basename:e.base});null!=s&&s.remove()}static async addRejectedFile_(e,t){const i=r.DirUri.findOrCreateByUri_({uri:await e.parent().uri_()});return n.ops().upsertOne({dirUriId:i.id,basename:e.base,fileSize:await e.size(),mtime:await e.mtimeMs(),why:t,updatedAt:Date.now()})}}t.RejectedFile=n},39604(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShaBlocklist=void 0,t.notShaBlocklistedFile=async function(e){return null==(0,u.modelDb)()?null:!d.exists(await(0,s.fileSha_)(e))},t.upsertFileToShaBlocklist=async function(e){if(null!=(0,u.modelDb)())return h(await(0,s.fileSha_)(e))},t.upsertToShaBlocklist=h;const r=i(50213),s=i(50597),n=i(40958),a=i(22573),o=i(45599),l=i(55046),u=i(94448),c=(0,o.defer)(()=>(0,r.mkLogger)("model.ShaBlocklist"));class d extends l.Model{static $tableName="ShaBlocklist";static $primaryKeys=["sha"];static $businessKeys=["sha"];static exists(e){return null!=(0,u.modelDb)()&&!(0,a.blank)(e)&&c().tap({msg:"isShaBlocklisted",result:null!=this.dbl.pluckFirstf(t=>t.where({sha:e})),meta:{sha:e}})}sha}function h(...e){if(null==(0,u.modelDb)())return;const t=(0,n.uniq)(e).map(e=>({sha:e}));return(0,n.isEmpty)(t)?void 0:d.dbl.upsert(t)}t.ShaBlocklist=d},35340(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Vec0TableNames=t.LibraryModelNames=t.TableNames=void 0,t.isVec0ShadowTable=function(e){for(const i of t.Vec0TableNames){if(s.some(t=>e===i+t))return!0;for(const t of n){const r=i+t;if(e.startsWith(r)&&/^\d+$/.test(e.slice(r.length)))return!0}}return!1};const r=i(50989);t.TableNames=(0,r.strEnum)("AssetFile","AssetRevision","AssetTag","ProgressMeta","RejectedFile","TagHierarchy","Asset","Tag","Volume","DirUri","Progress","Example","Heartbeat","Operation","ShaBlocklist","Session"),t.LibraryModelNames=Object.freeze(t.TableNames.values),t.Vec0TableNames=["AssetFileHash"];const s=["_info","_chunks","_rowids","_auxiliary"],n=["_vector_chunks","_metadatachunks","_metadatatext"]},48723(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=void 0;const r=i(39904),s=i(34102),n=i(19851),a=i(97352),o=i(42231),l=i(75020),u=i(40958),c=i(22573),d=i(42659),h=i(41400),f=i(55835),m=i(31586),p=i(20214),g=i(51926),y=i(7656),v=i(21320),b=i(43487),w=i(48722),S=i(45295),P=i(7619),M=i(41507),T=i(73716),_=i(72761),E=4*d.secondMs,k=[256,64,16,4,1];(0,h.later)(()=>{(0,s.ee)().on("clearCache",()=>D.clear()),(0,s.ee)().on("clearDbCache",()=>D.clear()),(0,s.ee)().on("clearTagCache",()=>D.clear())});class D extends _.TimestampedModel{static $tableName="Tag";static $primaryKeys=["id"];static $businessKeys=["_path"];static#As;static get dao(){return this.#As??=new P.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){const t=this.path;if(!(0,o.tagPathEql)(t.slice(0,-1),e))throw new Error(`Tag:${this.id} path ${t.join("/")} does not match expected parent ${e.join("/")}`);for(const e of this.getChildren())e.validate_(t)}static root=(0,n.lazy)(()=>{const e=new D;return e.id=0,e._path=o.TagSep,e.parentId=void 0,e.children=(0,v.filterRootTags)(D.roots()),e.ancestors=[],e.assetCount=b.Asset.dao.shownCount(),e.upsert=()=>{throw new Error("upsert not supported on root")},e},E);static roots=(0,n.lazy)(()=>{D.dao._upsertDefaultRoots();const e=D.ops().all(D.orderBy(D.query().whereNull("parentId")));for(const t of e)t.parentId=void 0,t.ancestors=[];return e},E);parentId;ordinal;_path;_displayName;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(T.TagHierarchy.updateForTag(this.id,this.parentId??null),null==this.parentId)D.root.unset(),D.roots.unset();else{const e=this.path.slice(0,-1);e.length>0&&D._cache.delete((0,o.joinTagPath)(e).toLowerCase())}}remove(){(0,m.gt0)(this.id)&&(this.class().ops().delete([this.id]),D.clear())}siblingPath(e){return(0,o.joinTagPath)([...this.parentPath,e])}changeName(e){return D.dao.changePath(this,this.siblingPath(e))}changePath(e,t){return D.dao.changePath(this,e,t)}maybeUpsertDisplayName(e){if(!(0,c.blank)(e)&&e!==this._displayName)return this._displayName=e,this.upsert()}get name(){return this.path.at(-1)}get path(){return(0,o.splitTagPath)(this._path)}get displayName(){return(0,c.toNotBlank)(this._displayName)??this.name}displayPath=(0,n.lazy)(()=>{const e=this.getParent();return(0,u.compactBlanks)([...null==e?[]:e.displayPath(),this.displayName])});get isRoot(){return 0===this.id}get depth(){return this.path.length}get parentPath(){return this.path.slice(0,-1)}$childrenQuery(){return D.orderBy(D.query().where({parentId:this.id}))}$assetsQuery(){return b.Asset.dao.shownUnhidden().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id}).distinct()}$descendantAssetsQuery(){return b.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({assetId:"Asset.id",capturedAtLocal:"Asset.capturedAtLocal",updateCount:"Asset.updateCount",durationMs:"Asset.durationMs"})}$assetIdsQuery(){return this.$selectAssetIdColumns(this.$assetsQuery())}setAncestors(e){this.ancestors=e,this.parent=e[e.length-1],(0,f.map)(this.parent,t=>t.setAncestors(e.slice(0,-1)))}async toApiPathElements(){return(0,p.thenCollect)(this.getAncestorsAndSelf(),e=>e.toPathTag())}toPathTag(){return{tagPath:this.path,displayName:this.displayName}}toApiTag(e){const t={tagId:this.id,tagPath:this.path,displayPath:this.displayPath(),description:this.description,assetCount:this.assetCount??0,allChildren:!1!==e?.includeChildren?this.getChildren().map(e=>({name:e.name,display:e.displayName})):[]};return e?.includeSiblings&&(t.pathSiblings=this.getPathSiblings()),t}getPathSiblings(){(0,u.isEmpty)(this.ancestors)&&(0,m.gt0)(this.parentId)&&(this.ancestors=void 0);const e=[...this.getAncestors(),this];return e.map((t,i)=>0===i?(0,v.filterRootTags)(D.roots()).map(e=>({name:e.name,display:e.displayName})):e[i-1].$childNameDisplayPairs())}$childNameDisplayPairs(){return D.dbl.allf(e=>e.select("_path","_displayName").where("parentId",this.id).orderByRaw("COALESCE(ordinal, _path) COLLATE NOCASE")).map(e=>{const t=(0,o.splitTagPath)(e._path).at(-1);return{name:t,display:(0,c.toNotBlank)(e._displayName)??t}})}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(){if(!this.isRoot)return null!=this.parentId&&null==this.parent?this.parent=D.dao.findById(this.parentId):this.parent}getPagedChildren(e){if(this.isRoot&&(this.children??=D.roots()),null!=this.children){const t=e.offset??0,i=t+(e.limit??this.children.length);return this.children.slice(t,i)}const t=this.$childrenQuery();return(0,a.mapGt0)(e.offset,e=>{t.offset(e)}),(0,a.mapGt0)(e.limit,e=>{t.limit(e)}),D.ops().all(t)}getChildrenCount(){return null!=this.children?this.children.length:D.dbl.pluckFirstf(e=>(this.isRoot?e.whereNull("parentId"):e.where({parentId:this.id})).count())}getChildren(){if(!this.isRoot&&null==this.children){this.children=D.ops().all(this.$childrenQuery());for(const 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 0===this.parentId||null==this.parentId?[]:D.ops().all({sql:(0,g.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=(0,n.lazy)(()=>0===this.parentId||null==this.parentId?[]:T.TagHierarchy.getAncestorIds(this.id).reverse());getPagedAssetIds(e){let t=this.$assetIdsQuery();return t=t.limit(e.limit??l.ThumbsPerSample),(0,m.gt0)(e.offset)&&(t=t.offset(e.offset)),t=t.orderBy([{column:"capturedAtLocal",order:"desc"},{column:"assetId"}]),(0,u.compact)(b.Asset.dbl.all(t).map(w.toAssetId))}getAssets(){const e=this.$assetsQuery().orderBy("capturedAtLocal","desc");return b.Asset.ops().all(e)}firstNonInterstitialTagId=(0,n.lazy)(()=>{if(!this.isRoot&&0===this.directAssetCount()&&1===this.getChildrenCount()){const e=this.getChildren();if(1===e?.length)return e[0].firstNonInterstitialTagId()}return this.id});directAssetCount=(0,n.lazy)(()=>0===this.id?0:b.Asset.dbl.pluckFirst(b.Asset.dao.shownUnhidden().join("AssetTag","AssetTag.assetId","Asset.id").where("AssetTag.tagId",this.id).countDistinct("Asset.id")));getAssetCount(){return 0===this.id?D.dbl.pluckFirst({sql:(0,g.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")}):D.dbl.pluckFirst({sql:y.TagAssetCountQuery,bindings:{tagId:this.id}})}$assetStreamQuery(e,t,i){let r=this.getChildrenCount()>0?this.$descendantAssetsQuery():this.$assetsQuery();return r=r.where("capturedAtLocal",i,e.capturedAtLocal).andWhereNot("Asset.id",e.id).limit("="===i?2*t:t),"="===i?r.orderByRaw("ABS(Asset.id - ?)",[e.id]):r.orderBy([{column:"capturedAtLocal",order:">"===i?"asc":"desc"},"Asset.id"])}queryBeforeAfter(e,t){const[i,r,s]=["<","=",">"].map(i=>(0,u.compact)(b.Asset.ops().all(this.$assetStreamQuery(e,t,i)).map(w.toAssetId)));for(const t of r)t.assetId<e.id?i.push(t):s.push(t);return{before:i,after:s}}getAssetStream(e,t){t=(0,m.gt0)(t)?t:l.BeforeAfterStreamLimit;const{before:i,after:r}=this.queryBeforeAfter(e,t);return new M.TaggedAssetStream([this],i,r.reverse(),t)}getRelatedAssetIds({seed:e,limit:t=l.ThumbsPerSample}){const i=this.id??0,r=this.#Us(e,i,t);return this.logger().debug(this.path+": Found "+r.length+" related assets"),r}#Us(e,t,i){return(0,r.isSeededRandomAvailable)()?this.#Ws(e,t,i):(0,u.compact)(S.AssetTag.dbl.allf(e=>b.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",t)).orderByRaw("RANDOM()").limit(i)).map(w.toAssetId))}#Ws(e,t,i){const r=e+t;for(const e of k){const s=(0,u.compact)(S.AssetTag.dbl.all({sql:(0,g.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","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:t,seed:r,modulus:e,limit:i}}).map(w.toAssetId));if(s.length>=i||1===e)return s}return[]}}t.Tag=D},7619(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagDao=void 0;const r=i(56038),s=i(55139),n=i(70974),a=i(31302),o=i(23560),l=i(42231),u=i(40958),c=i(22573),d=i(30301),h=i(55835),f=i(31586),m=i(51926),p=i(59455),g=i(41893),y=i(45295),v=i(48804),b=i(48723);class w extends v.ModelDao{_cache=new s.Cache({name:"model.Tag",maxSize:512});constructor(){super(b.Tag)}_upsertDefaultRoots=(0,d.lazy)(()=>{if(!(0,o.isDbJanitorService)()&&(0,f.gt0)(b.Tag.dbl.count(e=>e.whereNull("parentId"))))return;const e=b.Tag.dbl.allf(e=>e.whereNull("parentId")),t=[];for(const i of g.Roots){const r=(0,l.joinTagPath)([i.name]),s=e.find(e=>(0,m.equalsIgnoreCase)(e._path,r)),n=(0,f.toInt)(s?.ordinal)??i.ordinal,a=(0,c.toNotBlank)(s?.description)??i.description;null!=s&&s._path===r&&(0,f.toInt)(s.ordinal)===n&&(0,c.toNotBlank)(s.description)===a||t.push({_path:r,ordinal:n,description:a})}b.Tag.ops().upsert(t)});validate_(){return(0,r.timeSync)({name:"db.tag.validate",t:()=>{b.Tag.clear();for(const e of this.ops().allf(e=>e.whereRaw("id = parentId"))){this.logger.warn(`Tag ${e.id} has itself as parentId. Attempting to fix...`);const t=e.path.slice(0,-1),i=(0,u.isEmpty)(t)?void 0:this.findOrCreate(t),r=i?.id??null;b.Tag.dbl.runf(t=>t.where({id:e.id}).update({parentId:r})),e.parentId=r}for(const e of b.Tag.roots())e.validate_([])}})}deltaAssetCountAndAncestors(e,t=1){return b.Tag.dao.incrAssetCount(b.Tag.dao.selfAndAncestorIds(e),t)}incrAssetCount(e,t=1){(0,u.isEmpty)(e)||b.Tag.dbl.runf(i=>i.whereIn("id",e).update({assetCount:(0,n.knex)().raw("COALESCE(assetCount, 0) + ?",[Math.round(t)]),updatedAt:Date.now()}))}selfAndAncestorIds(e){const t=(0,p.toA)(e).filter(f.gt0);return(0,u.isEmpty)(t)?[]:b.Tag.dbl.pluckAll({sql:(0,m.compressWhitespace)("SELECT DISTINCT tagId","FROM TagHierarchy","WHERE descendantId IN "+(0,a.sqlWhereInClause)(t.length)),bindings:t})}findByIdOrPath(e,t){return 0===e?b.Tag.root():(0,f.gt0)(e)?this.findById(e):this.findByPath(t)}findById(e){return 0===e?b.Tag.root():this.ops().findById(e)}findByPath(e){if((0,u.isEmpty)(e))return b.Tag.root();const t=(0,l.joinTagPath)(e);return this._cache.getOrMaybeSet(t.toLowerCase(),()=>this.ops().findOnef(e=>e.where({_path:t})))}findByPathN(e){const t=(0,u.uniqBy)(e.filter(u.isNotEmpty),e=>(0,c.toNotBlank)((0,l.joinTagPath)(e)));return(0,u.compact)(t.map(e=>this.findByPath(e)))}getPagedAssets(e,t){const i=new b.Tag;return i.id=e,i.getPagedAssetIds(t)}_newTag(e){const t=new b.Tag;t._path=(0,l.joinTagPath)(e);const i=e[e.length-1];return"object"==typeof i&&((0,c.mapNotBlank)(i.displayName,e=>t._displayName=e),(0,f.mapNumeric)(i.ordinal,e=>t.ordinal=e),(0,c.mapNotBlank)(i.description,e=>t.description=e),(0,f.mapNumeric)(i.releasedAt,e=>t.releasedAt=e)),t}findOrCreate(e){if((0,u.isEmpty)(e))throw new Error("Tag.findOrCreate(): tagPath is empty");const t=this.findByPath(e);if(null!=t)return t;const i=this._newTag(e),r=i.depth<=1?void 0:this.findOrCreate(e.slice(0,-1));(0,h.map)(r,t=>{i.parentId=t.id,i._path=(0,l.joinTagPath)([...t.path,e[e.length-1]])});const s=this.ops().upsertOne(i);return this._cache.set((0,l.joinTagPath)(e).toLowerCase(),s),s}findOrCreateByPathN(e){return(0,u.uniqBy)(e.filter(u.isNotEmpty),e=>(0,l.joinTagPath)(e)).map(e=>this.findOrCreate(e))}changePath(e,t,i=!0){const r=e._path,s=b.Tag.dao.findByPath((0,l.splitTagPath)(t));this.logger.info("changePath(): ",{target:e,newPath:t,existingSibling:s});try{if(null==s)b.Tag.dbl.runf(e=>e.whereLike("_path",r+"%").update({updatedAt:Date.now(),_path:(0,n.knex)().raw("REPLACE(_path, ?, ?)",[r,t])})),e._path=t;else{t=s._path,this.logger.info("changePath(): replacing with sibling",t),y.AssetTag.dbl.run({sql:(0,m.compressWhitespace)("INSERT OR REPLACE INTO AssetTag (assetId, tagId)","SELECT assetId, :newTagId","FROM AssetTag","WHERE tagId = :oldTagId"),bindings:{newTagId:s.id,oldTagId:e.id}}),y.AssetTag.dbl.runf(t=>t.where({tagId:e.id}).delete());for(const t of e.getChildren())this.changePath(t,(0,l.joinTagPath)([...s.path,t.name]),!1);b.Tag.dbl.runf(t=>t.where({parentId:e.id}).update({parentId:s.id})),e.remove()}}finally{i&&b.Tag.clear()}}}t.TagDao=w},73716(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagHierarchy=void 0;const r=i(56038),s=i(49924),n=i(50213),a=i(45599),o=i(31586),l=i(51926),u=i(55046),c=i(48723),d=(0,a.defer)(()=>(0,n.mkLogger)("model.TagHierarchy"));class h extends u.Model{static $tableName="TagHierarchy";static $primaryKeys=["tagId","descendantId"];static $businessKeys=["tagId","descendantId"];tagId;descendantId;depth;static maxUpdateDepth=100;static updateForTag(e,t,i=0){if(!(0,o.gt0)(e))return;if(i>h.maxUpdateDepth)throw new Error(`Tag hierarchy recursion depth ${i} exceeds limit ${h.maxUpdateDepth} for tag ${e}. This may indicate a cycle in Tag.parentId. Use TagHierarchy.rebuild() instead.`);const r=h.dbl;try{const s=c.Tag.dbl.pluckAll({sql:"SELECT id FROM Tag WHERE parentId = :tagId AND id != :tagId",bindings:{tagId:e}});r.runf(t=>t.delete().where({descendantId:e}).orWhere({tagId:e})),r.upsertOne({tagId:e,descendantId:e,depth:0}),(0,o.gt0)(t)&&t!==e&&r.run({sql:(0,l.compressWhitespace)("INSERT INTO TagHierarchy (tagId, descendantId, depth)","SELECT tagId, :tagId, depth + 1","FROM TagHierarchy","WHERE descendantId = :parentId"),bindings:{tagId:e,parentId:t}});for(const t of s)h.updateForTag(t,e,i+1);d().debug("Updated tag hierarchy for tag",{tagId:e,parentId:t})}catch(r){throw d().error("Failed to update tag hierarchy",{tagId:e,parentId:t,recursionDepth:i,error:r}),r}}static rebuild(){(0,r.timeSync)({name:"db.TagHierarchy.rebuild",t:()=>{d().info("Starting complete TagHierarchy table rebuild");try{h.dbl.txn(()=>{(0,s.withoutIndexes)(h.dbl.db().db,h.$tableName,()=>{d().debug("Clearing existing TagHierarchy data"),h.dbl.runf(e=>e.delete()),d().debug("Rebuilding tag hierarchy using recursive CTE"),h.dbl.run("INSERT INTO TagHierarchy (tagId, descendantId, depth) SELECT id, id, 0 FROM Tag"),h.dbl.run((0,l.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")),d().info("TagHierarchy table rebuild completed successfully")})})}catch(e){throw d().error("Failed to rebuild TagHierarchy table",{error:e}),e}}})}static getAncestorIds(e){return(0,o.gt0)(e)?h.dbl.pluckAll({sql:(0,l.compressWhitespace)("SELECT tagId FROM TagHierarchy","WHERE descendantId = :tagId AND tagId != :tagId","ORDER BY depth ASC"),bindings:{tagId:e}}):[]}static getDescendantIds(e){return(0,o.gt0)(e)?h.dbl.pluckAll({sql:(0,l.compressWhitespace)("SELECT descendantId FROM TagHierarchy","WHERE tagId = :tagId AND descendantId != :tagId","ORDER BY depth ASC"),bindings:{tagId:e}}):[]}static ValidationResult=class{missingSelfRef;missingParent;incompleteTransitive;cycles;spuriousEntries;orphanedEntries;constructor(e,t,i,r,s,n){this.missingSelfRef=e,this.missingParent=t,this.incompleteTransitive=i,this.cycles=r,this.spuriousEntries=s,this.orphanedEntries=n}get isValid(){return 0===this.missingSelfRef.length&&0===this.missingParent.length&&0===this.incompleteTransitive.length&&0===this.cycles.length&&0===this.spuriousEntries.length&&0===this.orphanedEntries}get totalIssues(){return this.missingSelfRef.length+this.missingParent.length+this.incompleteTransitive.length+this.cycles.length+this.spuriousEntries.length+(this.orphanedEntries>0?1:0)}get affectedTagIds(){return[...new Set([...this.missingSelfRef,...this.missingParent,...this.incompleteTransitive,...this.cycles,...this.spuriousEntries])]}};static validate(){const e=h.dbl,t=e.pluckAll({sql:(0,l.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",")")}),i=e.pluckAll({sql:(0,l.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",")")}),r=e.pluckAll({sql:(0,l.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=e.pluckAll({sql:(0,l.compressWhitespace)("SELECT DISTINCT tagId FROM TagHierarchy","WHERE tagId = descendantId AND depth > 0")}),n=e.pluckAll({sql:(0,l.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",")")}),a=e.pluckFirst({sql:(0,l.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,o=new h.ValidationResult(t,i,r,s,n,a);return o.isValid||d().warn("TagHierarchy validation found issues",{missingSelfRef:t.length,missingParent:i.length,incompleteTransitive:r.length,cycles:s.length,spuriousEntries:n.length,orphanedEntries:a}),o}static repairIfNeeded(){const e=h.validate();if(e.isValid)return{action:"none",issueCount:0};const t=e.affectedTagIds;if(t.length>20||e.orphanedEntries>0)return d().info("TagHierarchy: too many issues, performing full rebuild",{affectedTags:t.length,orphanedEntries:e.orphanedEntries}),h.rebuild(),{action:"full",issueCount:e.totalIssues};d().info("TagHierarchy: repairing individual tags",{tagIds:t});for(const e of t){const t=c.Tag.dbl.pluckFirst({sql:"SELECT parentId FROM Tag WHERE id = :tagId",bindings:{tagId:e}});h.updateForTag(e,t??null)}return{action:"partial",issueCount:e.totalIssues,repairedTagIds:t}}}t.TagHierarchy=h},41507(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaggedAssetStream=t.cmpAssetDesc=t.cmpAssetAsc=void 0,t.coalesceStreams=function(e){const t=n.Settings.minStreamCorrPct.valueOrDefault/100,i=[],s=e.filter(e=>e.length>5);for(const e of s){const s=(0,r.greatestBy)(i,i=>(0,l.gtOrElse)(i.streamCoeff(e),t));null==s?i.push(e):s.mergeWith(e)}return i};const r=i(48884),s=i(50213),n=i(28874),a=i(40958),o=i(76790),l=i(31586),u=i(34666),c=i(20214),d=i(59455);t.cmpAssetAsc=(e,t)=>(0,u.cmp)([e.capturedAtLocal,e.id],[t.capturedAtLocal,t.id]),t.cmpAssetDesc=(e,t)=>(0,u.cmp)([t.capturedAtLocal,t.id],[e.capturedAtLocal,e.id]),t.TaggedAssetStream=class{tags;before;after;limit;logger=()=>(0,s.mkLogger)("model.TaggedAssetStream("+this.toString()+")");constructor(e,t,i,r){this.tags=e,this.before=t,this.after=i,this.limit=r,this.logger().debug("new",this.toJSON())}vacuum(){(0,o.sortByInPlace)(this.before,e=>[-e.capturedAtLocal,-e.assetId]),(0,r.retainFirstN)(this.before,this.limit),(0,o.sortByInPlace)(this.after,e=>[-e.capturedAtLocal,-e.assetId]),(0,r.retainLastN)(this.after,this.limit)}toString(){return this.tags.map(e=>e.path.join("/")).join(",")}valueOf(){return this.toString()}get length(){return(0,d.toA)(this.before).length+(0,d.toA)(this.after).length}leftPad(e){return[...(0,l.times)(this.limit-e.length,e=>({assetId:-(e+1),capturedAtLocal:-1,v:0})),...e]}rightPad(e){return[...e,...(0,l.times)(this.limit-e.length,e=>({assetId:-(e+this.limit+1),capturedAtLocal:-1,v:0}))]}toJSON(){return{tags:this.tags.map(e=>e.toString()),assetIdsAfter:this.after,assetIdsBefore:this.before}}mergeWith(e){(0,a.pushUniqBy)(this.tags,e.tags,e=>e.path),(0,a.pushUniqBy)(this.before,e.before,e=>e.assetId),(0,a.pushUniqBy)(this.after,e.after,e=>e.assetId),this.logger().debug("mergeWith() complete",{tas:e.toJSON(),tags:this.tags.map(e=>e.path),beforeIds:this.before,afterIds:this.after})}async toApi(){return this.vacuum(),this.logger().tap({msg:"toApi()",result:{tags:await(0,c.thenCollect)(this.tags,e=>e.toApiTag({includeChildren:!1})),assetIdsAfter:this.leftPad(this.after),assetIdsBefore:this.rightPad(this.before)}})}streamCoeff(e){return this.logger().tap({msg:"streamCoeff",meta:{this:this.tags.map(e=>e.path),tas:e.tags.map(e=>e.path)},result:(0,r.diceCoeff)([...this.before,...this.after],[...e.before,...e.after],e=>e.assetId)})}}},72761(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimestampedModel=void 0;const r=i(97352),s=i(40958),n=i(31586),a=i(59455),o=i(55046);class l extends o.Model{static touch(e,t={}){t.updatedAt??=Date.now(),delete t.id;const i=(0,a.toA)(e).filter(n.gt0);return(0,s.isEmpty)(i)?void 0:this.dbl.runf(e=>e.whereIn("id",i).update(t))}createdAt;updatedAt;get createdAtDate(){return(0,r.mapGt0)(this.createdAt,e=>new Date(e))}get updatedAtDate(){return(0,r.mapGt0)(this.updatedAt,e=>new Date(e))}touch(e={}){e.updatedAt??=Date.now();const t=this.id;null==t?this.upsert():this.class().dbl.runf(i=>i.where({id:t}).update(e))}$beforeSave(){if(super.$beforeSave(),this.createdAt??=Date.now(),this.updatedAt=Date.now(),Object.hasOwn(this,"updateCount")){const e=this,t=e.updateCount;e.updateCount=((0,n.toGt0)(e.updateCount)??0)+1,this.logger().debug("$beforeSave(): incr updateCount",{prior:t,now:e.updateCount})}}}t.TimestampedModel=l},72965(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Volume=void 0;const s=r(i(76760)),n=i(55139),a=i(34075),o=i(9029),l=i(29882),u=i(95696),c=i(28874),d=i(5696),h=i(34238),f=i(40958),m=i(22573),p=i(45599),g=i(51926),y=i(89937),v=i(55046);class b extends v.Model{static $tableName="Volume";static $primaryKeys=["id"];static $businessKeys=["authority","mountPoint"];authority;mountPoint;label;lastSeenAt;static#w=new n.Cache({name:"model.Volume",maxSize:512});static setupLookupShim=(0,p.defer)(()=>{a.volshaToMountPointFallback.setShim(e=>b.volshaToMountPoint(e)),a.onHealthyVolumeDiscovered.setShim(e=>b.onVolumeGet(e))});static findByVolsha(e){if(null!=b.db())return this.#w.getOrMaybeSet(e,()=>b.ops().allf(t=>t.where({authority:e}).orderBy("lastSeenAt","DESC")).find(e=>e.isNativePath()))}static volshaToMountPoint(e){return(0,f.compact)([b.findByVolsha(e)?.mountPoint])}static#qs(e){return b.ops().allf(t=>t.where({authority:e}).whereNotNull("label").orderBy("lastSeenAt","DESC")).find(e=>e.isNativePath()&&(0,m.notBlank)(e.label))?.label}static onVolumeGet(e){const{volsha:t,mountPoint:i}=e;if((0,m.blank)(t))return void this.$logger().info("Skipping volume with blank volsha",{volume:e});if(null==b.db())return void this.$logger().warn("Skipping volume upsert: no database available",{volume:e});this.#w.delete(t);const r=(0,m.toNotBlank)(e.label?.trim())??this.#qs(t),s=b.ops().upsertOne({authority:t,mountPoint:i,...null==r?{}:{label:r},lastSeenAt:Date.now()});this.#w.set(t,s)}displayName(){return c.Settings.tagDisplayNameFSLabels.valueOrDefault&&(0,m.notBlank)(this.label)?this.label:"/"===this.mountPoint?c.Settings.tagDisplayNameFSRoot.valueOrDefault+(c.Settings.tagDisplayNameFSRootWithHostname.valueOrDefault?" on "+c.Settings.hostname.valueOrDefault:""):(0,m.notBlankOr)((0,g.stripPrefixSuffix)(this.mountPoint,{prefix:s.default.sep,suffix:s.default.sep}),s.default.sep)}static async upsertForScannedVolumes(){b.setupLookupShim();for await(const e of(0,a.scannedVolumes)())b.onVolumeGet(e)}static resolve_(e){const t=()=>this.$logger().throw("Volume.resolve(): cannot resolve invalid uri",{uri:e}),i=(0,h.toURI)(e);if("file"===i.scheme)return(0,m.toNotBlank)(i.fsPath)??t();if(i.scheme===y.PS_LIBRARY_SCHEME)return(0,d.pslibToNativePath_)({uri:i}).nativePath;{const e=i.path.startsWith("/")?i.path.slice(1):i.path,r=u.PosixFile.forMaybe(this.volshaToMountPoint(i.authority)[0])?.join(e)?.nativePath??t();return(0,o.canonicalizeMacPathSync)(r)??r}}isNativePath(){return(0,l.isNativePath)(this.mountPoint)}}t.Volume=b},58723(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applyDeleted=function(e){return u({unlinkAssetFiles:!0,untilTs:e.createdAt,halt:e.halt})},t.applyExcluded=function(e){return u({unlinkAssetFiles:!1,untilTs:e.createdAt,halt:e.halt})};const r=i(50213),s=i(74128),n=i(28874),a=i(43487),o=(0,r.mkLogger)("ops.ApplyRemovable"),l=Promise.resolve();async function u({unlinkAssetFiles:e,untilTs:t,halt:i}){const r=e?"Deleting":"Excluding",u=e?"deletedAt":"excludedAt";for await(const s of a.Asset.dbl.pluckBatched({pluckedColumn:"id",qb:e=>e.select("id").where("shown",0).andWhere(u,"<=",t),runLatch:()=>l,maxBatchSize:()=>n.Settings.dbBatchSelectSize.valueOrDefault})){o.throwIfAborted_(i);for(const t of s)try{await a.Asset.dao.remove({assetId:t,blocklistShas:!0,unlinkAssetFiles:e})}catch(e){o.error(r+" failed",{assetId:t,error:e})}}await(0,s.syncReport)().close()}},76386(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApiProgressPatchPath=t.tellWebProgressUpdated=t.ProgressRateMs=void 0;const r=i(19851),s=i(50213),n=i(23560),a=i(24540),o=i(28874),l=i(34238),u=i(4988),c=i(15674),d=i(42659),h=(0,i(45599).defer)(()=>(0,s.mkLogger)("progress.Progress"));t.ProgressRateMs=(0,r.lazy)(()=>d.secondMs*((0,a.isRaspberryPi)()||(0,c.maxCpus)()<=4?5:1.5)),t.tellWebProgressUpdated=(0,r.lazy)(async()=>{if((0,n.isWebService)())return;const e=l.URI.from({scheme:"http",authority:"127.0.0.1:"+o.Settings.httpPort.valueOrDefault,path:t.ApiProgressPatchPath}).toString();await(0,u.httpRequest_)({url:e,method:"PATCH",maxRedirects:0}).catch(e=>h().warn(".tellWebProgressUpdated: failed",{error:e}))},(0,t.ProgressRateMs)()),t.ApiProgressPatchPath="/api/progress"},3996(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileFinder=void 0;const r=i(50213),s=i(85527),n=i(56038),a=i(38835),o=i(74128),l=i(69589),u=i(45200),c=i(34238),d=i(28549),h=i(87001),f=i(22573),m=i(45599),p=i(89937),g=i(54017),y=i(54568);function v(e){if((0,f.blank)(e))return;const t=(0,c.toURI)(e),i=(0,d.extractUriDirectory_)(t),r=(0,d.extractUriBasename_)(t),s=y.DirUri.ops().findOneBy({uri:i});return null!=s?g.AssetFile.ops().findOneBy({dirUriId:s.id,basename:r}):void 0}t.AssetFileFinder=class{file;ctx;start=performance.now();#$;constructor(e,t=(0,l.forceContextOrSetting)()){this.file=e,this.ctx=t,this.#$=(0,r.mkLogger)("sync-file.AssetFileFinder("+e.baseWithGrandparent+")")}set abortable(e){this.#$.abortable=e}async prior(){const e=v(await this.file.uri_());if(null!=e)return e;for(const e of await(0,u.nativePathToUriStrings)(this.file.nativePath)){const t=v(e);if(null!=t)return t}}mediaInfo=(0,m.defer)(()=>s.MediaInfoFactory.for(this.file));newAssetFile_=(0,m.defer)(async()=>{const e=await this.mediaInfo().asMediaInfo_(),{uri:t,...i}=e,r=new g.AssetFile;return null!=t&&r.setUri(t),r.update(i),r});apply_=(0,n.timedLazy)({name:"sync.assetFileFinder",thunk:async()=>{const e=await this.file.uri_();if((0,f.blank)(e))throw new Error("Cannot import, file URI is blank for "+this.file);const t=await this.byUri();if(null!=t){if(!1!==await(0,h.uriIsEquivalent)(e,t.uri))return this.#$.info("Previously imported",{uri:e}),(0,p.isFileUri)(t.uri)&&!(0,p.isFileUri)(e)&&await t.upgradeUri(e),await t.upsertIfNeeded_()??t;this.#$.warn(".byUri() returned a non-equivalent URI. Ignoring"+a.InternalErrorFlag,{uri:e,prior_uri:t.uri})}this.#$.throwIfAborted_();const i=await this.newAssetFile_();return i.assetId=void 0,i.$syncState=o.AssetFileSyncStates.imported,i.upsert()}});async byUri(e=this.file){for(const t of await(0,u.nativePathToUriStrings)(e.nativePath)){const e=v(t);if(null!=e)return e}}}},34274(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileImporter=void 0,t.importFileToResult_=async function(e){const t=e.path;if(M.ProblematicPath.isProblematic(t)){const e=M.ProblematicPath.getStrikeCount(t),i=M.ProblematicPath.getLastStrike(t),r=null!=i?` (last: ${new Date(i.timestamp).toISOString()} - ${i.reason})`:"",s=`Skipped: ${(0,p.plur)(e,"strike")} from previous timeouts${r}`;return(0,a.syncReport)().onProgress({from:"AssetFileImporter",path:t,type:"file",state:a.SyncFileStates.excluded,details:s}),{path:t,state:a.SyncFileStates.excluded,details:s}}const i=g.Library.instanceRequired_();return(0,a.syncReport)().wrap_({path:t,from:"AssetFileImporter",type:"file",fn_:()=>new E(n.PosixFile.for(t),i.assetFileRepository(),e).apply_()})};const r=i(38835),s=i(50597),n=i(95696),a=i(74128),o=i(181),l=i(19851),u=i(50213),c=i(69589),d=i(28874),h=i(40958),f=i(22573),m=i(85556),p=i(12168),g=i(64526),y=i(54017),v=i(85018),b=i(2847),w=i(39604),S=i(62859),P=i(90910),M=i(33978),T=i(3996),_=i(96031);class E{file;repo;start=performance.now();#$;#$s;ctx;constructor(e,t,i){this.file=e,this.repo=t,this.ctx=(0,c.forceContextOrSetting)(i),this.#$=(0,u.mkLogger)("sync-file."+this.toString()),this.#$s=new T.AssetFileFinder(e,this.ctx),this.#$s.abortable=this.#$.abortable}toString(){return"AssetFileImporter("+this.file.nativePath+")"}newAssetFile(){return this.#$s.newAssetFile_()}whyRejected=(0,l.lazy)(async()=>{const e=[];if(null==await this.file.uriObject_())e.push("Cannot make URI"+r.DoNotSendErrorFlag+r.NonRetriableErrorFlag);else{if(!0===await this.file.isDeleted())e.push("File was deleted");else{const t=await this.prior(),i=null!=t&&v.AssetFileFlags.has(t.flags??0,"forceFilters"),r=this.ctx.forceFilters||i;if(!r){const t=await b.RejectedFile.findRejectedFile_(this.file);if(null!=t)return this.#$.info("whyRejected(): using cached rejection",{why:t.why,cachedAt:new Date(t.updatedAt).toISOString(),nativePath:this.file.nativePath}),e.push(t.why),e}if(r||null==t){const r=await(0,_.whyFileRejected)({file:this.file,forceFilters:!0});null!=r&&e.push(r),i&&null!=t.id&&(y.AssetFile.dbl.runf(e=>v.AssetFileFlags.update({qb:e.where("id",t.id),flag:"forceFilters",isSet:!1})),this.#$.debug("Cleared forceFilters flag",{assetFileId:t.id,nativePath:this.file.nativePath}))}}const t=await this.prior();if(this.#$.throwIfAborted_(),0===e.length&&(null==t||!await t.inSyncWithFile())){const t=await(0,o.whyInvalidFile)(this.file.nativePath);(0,f.blank)(t)||e.push(t)}(0,h.isNotEmpty)(e)&&null!=t&&(this.#$.info("whyRejected(): removing rejected asset file",{why:e,prior:t}),await t.remove())}return e});assetFile_=(0,l.lazy)(async()=>await this.#$s.apply_());prior=(0,l.lazy)(()=>this.#$s.prior());apply_=(0,l.lazy)(()=>this.#D());async#D(){try{return await this.#Gs()}catch(e){throw e instanceof m.TimeoutError&&await this.#Ks(),e}}async#Ks(){try{const e=await(0,s.fileSha_)(this.file.nativePath);(0,w.upsertToShaBlocklist)(e),this.#$.warn("Blocklisted SHA after timeout",{sha:e}),(0,a.syncReport)().onProgress({from:"AssetFileImporter",path:this.file.nativePath,type:"file",state:"blocklisted",details:"SHA blocklisted after timeout (files with the same SHA will not be imported)"})}catch(e){this.#$.warn("Failed to blocklist SHA after timeout",{error:e})}}async#Gs(){await(0,P.maybeDelayIfNotProd)(this.file.nativePath),this.#$.throwIfAborted_();const e=await this.#$.tapAsync_({msg:"whyRejected",result:this.whyRejected(),timeoutMs:d.Settings.taskTimeoutMs.valueOrDefault});if((0,h.isNotEmpty)(e)){const t=e.join(", "),i=d.Settings.rejectedFileCacheThresholdMs.valueOrDefault,r=performance.now()-this.start;if(!this.ctx.forceFilters&&i>0&&r>=i)try{await b.RejectedFile.addRejectedFile_(this.file,t),this.#$.info("Cached rejection for future syncs",{elapsedMs:r,thresholdMs:i})}catch(e){this.#$.warn("Failed to cache rejection",{error:e})}return{path:this.file.nativePath,state:a.SyncFileStates.excluded,details:t}}this.#$.throwIfAborted_();const t=await this.#$.tapAsync_({msg:"prior()",result:this.prior(),timeoutMs:d.Settings.taskTimeoutMs.valueOrDefault});if(null!=t&&await t.inSyncWithFile(this.ctx))return null!=this.ctx.scanGeneration&&y.AssetFile.dbl.runf(e=>e.where("id",t.id).update({lastVisitedGeneration:this.ctx.scanGeneration})),t.$syncState=a.SyncFileStates.unchanged,{path:this.file.nativePath,state:"unchanged",assetFileId:t.id,assetFile:t};this.#$.throwIfAborted_();const i=await this.#$.tapAsync_({msg:"assetFile()",result:this.assetFile_(),timeoutMs:d.Settings.taskTimeoutMs.valueOrDefault});if(null==i)return this.#$.throw("_apply(): unexpected null assetFile");const r=i.id;if(null==r)return this.#$.throw("_apply(): unexpected null assetFileId");if(null==i.uri)return this.#$.throw("_apply(): unexpected null assetFile.uri");await this.#$.tapAsync_({msg:"assetFile.upsertIfNeeded_()",result:i.upsertIfNeeded_(),timeoutMs:d.Settings.taskTimeoutMs.valueOrDefault}),null!=this.ctx.scanGeneration&&y.AssetFile.dbl.runf(e=>e.where("id",r).update({lastVisitedGeneration:this.ctx.scanGeneration})),this.#$.throwIfAborted_(),null==i.assetId?(S.AdoptAssetFileProducer.instance().onNewOrphan(r),this.#$.info("Created orphan AssetFile, notifying AdoptAssetFileProducer",{assetFileId:r})):(await S.AdoptAssetFileProducer.instance().onUpdatedAssetFile(r),this.#$.info("Updated AssetFile with existing asset, notifying AdoptAssetFileProducer",{assetFileId:r,assetId:i.assetId}));try{await b.RejectedFile.removeRejectedFile_(this.file)}catch{}return{path:this.file.nativePath,state:null!=t?"updated":"imported",assetFileId:r,assetFile:i}}}t.AssetFileImporter=E},41844(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileRepository=void 0,t.mayCopyAssetsToLibrary=async function(){return c.Settings.copyAssetsToLibrary.valueOrDefault&&await(0,o.p)()};const r=i(50213),s=i(3685),n=i(34102),a=i(74128),o=i(81674),l=i(57902),u=i(4936),c=i(28874),d=i(28544),h=i(67083),f=i(16170),m=i(54979),p=i(40538),g=i(79915),y=i(98604),v=i(40958),b=i(22573),w=i(68708),S=i(89937),P=i(59455),M=i(43487),T=i(54017),_=i(39656),E=i(94761);t.AssetFileRepository=class{originalsDir;libraryDir;logger=(0,r.mkLogger)("AssetFileRepository");constructor(e,t){this.originalsDir=e,this.libraryDir=t}async shouldCopy(e){const t=await this.whyNotCopyFile(e);return this.logger.tap({level:"info",msg:"shouldCopy()",result:null==t,meta:{file:e?.nativePath,whyNot:t}})}async whyNotCopyFile(e){if(null==e||(0,b.blank)(e.nativePath))return"blank nativePath";if(!0!==c.Settings.copyAssetsToLibrary.value)return"copyAssetsToLibrary !== true";if(await(0,o.l)())return"no active subscription";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 "+c.Settings.libraryDir.valueOrDefault;const t=await(0,m.readMimeType)(e);return null==t?"readMimeType("+e+") was null":(0,f.isMimeTypeIncluded)(t,c.Settings.copyToLibraryMimeTypes.values)?null:"mimetype "+t+" is not included in copyToLibraryMimeTypes"}async existingLibraryAssetFile(e){if(e.uri.startsWith(S.PS_LIBRARY_PROTOCOL))return e;const t=(0,v.uniqBy)((0,P.toA)(e.librarySiblings()?.filter(t=>t.sha===e.sha)).concat(T.AssetFile.dao.sameAssetFileInLibrary(e)),e=>e.id);for(const i of t)if(await i.exists_()){if(i.assetId!==e.assetId){(0,a.syncReport)().onProgress({from:"existingLibraryAssetFile()",path:i.nativePath,type:"file",state:a.SyncFileStates.warning,details:"Found a library asset file with a matching SHA that is associated to a different asset. Skipping.",meta:{nonLibraryAssetFile:(0,w.pick)(e,"id","uri","assetId"),libraryAssetFile:(0,w.pick)(i,"id","uri","assetId")}}),null!=i.assetId&&(M.Asset.dbl.runf(e=>_.AssetFlags.update({qb:e,flag:"validateSiblings",isSet:!0}).where("id",i.assetId)),(0,n.ee)().emitThrottled("notifyWorkAvailable","validateAssetSiblings"));continue}return this.logger.info("whyNotCopyAssetFile("+e.uri+"): found existing db record",{af:e,prior:i}),i}return null}async findLibraryFileWithSameContents(e,t){if(await e.matchesContent(t))return t;let i=t.parent();for(;i.isSelfOrDescendantOf(this.originalsDir);){const t=i.childWithSameContents(e);if(null!=t)return t;i=i.parent()}}async importFile_(e,t,i){const r=await this.#Js(e,t,i);return null!=r&&(await this.#Ys(e,r),await this.#Zs(e,r)),r}async#Js(e,t,i){const r=t??await(0,d.readCapturedAt)(e),s=(0,u.pathToLibraryAsset)(r?.date,e,i);if(this.logger.debug("importFile("+e+")",{capturedAt:r,assetPath:s}),null==s)throw new Error(e.nativePath+" failed to create a library path");const n=this.originalsDir.join(...s),a=await this.findLibraryFileWithSameContents(e,n);if(null!=a)return this.logger.debug("#importFile_("+e+"): found existing file",{src:e,existing:a}),a;const o=await n.ensureNew_();return this.logger.info("#importFile_("+e+"): copying...",{uniqDest:o,dest:n}),e.copyFile_(o)}async#Ys(e,t){const i=await e.existingSidecars(),r=[];for(const e of i)r.push(await this.#Xs(e,t));return(0,v.compact)(r)}async#Xs(e,t){for(const i of await t.existingSidecars())if(await(0,g.sidecarEql)(e,i))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:e,destSidecar:i,dest:t});const i=await t.parent().join(t.name+e.ext).ensureNew_({emptyIsNew:!0});return e.copyFile_(i)}async#Zs(e,t){if(null==e||null==t||e.$eql(t))return;const i=await(0,p.readTags)(e);if(null!=i)return(0,h.ensureInferredHistoryRecords)(e,await t.sidecar(),i.inferred);this.logger.warn("#handleInferred(): Failed to read tags from "+e,{dest:t})}async maybeCopyToLibrary_(e,t,i){const r=performance.now(),n=e.posixFile_();null==n&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): posixFile is null",{ignorable:!1,retriable:!1});{const e=await this.whyNotCopyFile(n);if(!(0,b.blank)(e))return this.logger.tap({level:l.LogLevels.info,msg:"maybeCopyToLibrary_(): not copying: "+e,result:void 0})}const o=e.getAsset();null==o&&this.logger.throw("maybeCopyToLibrary_("+e.uri+"): null asset");{const l=await this.existingLibraryAssetFile(e);if(null!=l){const e=l.posixFile_();if(null!=e){const u=await this.#Ys(n,e),c=null!=await this.#Zs(n,e),d=null!=await l.upsertIfNeeded_(void 0,t);return!c&&(0,v.isEmpty)(u)&&!d||((0,a.syncReport)().onProgress({path:e.nativePath,from:"maybeCopyToLibrary()",type:"file",state:a.SyncFileStates.imported,details:"Found and imported prior replica already in your library",meta:{src:n.nativePath,upsertNeeded:d,copiedSidecars:u,copiedInferredMetadata:c},elapsedMs:(0,s.roundMs)(performance.now()-r),url:(0,y.mkAssetUrl)(o.id)?.toString()}),i?i(o.id):(0,E.addLocalTask)("repairAsset",{assetId:o.id})),l}this.logger.warn("existingLibraryAssetFile() returned an assetFile that could not be resolved to a PosixFile",{prior:l})}}const u=d.CapturedAt.fromMediaInfo({mimetype:e.mimetype,capturedAtLocal:e.capturedAtLocal,capturedAtZone:e.capturedAtZone,capturedAtSrc:e.capturedAtSrc,capturedAtPrecisionMs:e.capturedAtPrecisionMs}),c=await this.importFile_(n,u,e.sha);if(null==c)return void this.logger.info("importFile() returned null",{srcAssetFile:e});if(c.nativePath===n.nativePath)return void this.logger.info("importFile() returned the same nativePath as src",{srcAssetFile:e,dest:c});const h=await o.assetFileForFile_(c,{skipUpsert:!0});await h.updateFromShaSibling_(e);const f=h.upsert();return(0,a.syncReport)().onProgress({path:c.nativePath,from:"maybeCopyToLibrary()",type:"file",state:a.SyncFileStates.copied,details:"Copied into your library from "+n.nativePath,elapsedMs:(0,s.roundMs)(performance.now()-r),url:(0,y.mkAssetUrl)(o.id)?.toString()}),f}}},96031(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whyFileRejected=async function(e){const{file:t,forceFilters:i}=e,a=await(0,s.whyRejectFile)(t,(0,n.libraryFileFiltersFor)(t));if(null!=a)return a;if(i){const e=t.parent();if(null!=e){const t=await(0,r.whyExcludedDirectoryRecursive)(e);if(null!=t)return t}}};const r=i(92423),s=i(62105),n=i(19113)},93755(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetFile=async function(e){try{return await M(e)}catch(t){return{id:e.assetFileId,...e,error:(0,s.errorToS)(t)}}},t.getAssetFile_=P,t.updateAssetFile_=M,t.handleAssetFileUriChange=T,t.updateAssetFileIfNeeded=_;const r=i(92434),s=i(98314),n=i(34102),a=i(74128),o=i(50213),l=i(3685),u=i(69589),c=i(87001),d=i(40958),h=i(75761),f=i(22573),m=i(45599),p=i(31586),g=i(68708),y=i(43487),v=i(54017),b=i(85018),w=i(39656),S=(0,m.defer)(()=>(0,o.mkLogger)("sync-file.UpdateAssetFile"));function P(e){if("af"in e)return e.af instanceof v.AssetFile?e.af:S().throw("Invalid cmd: missing af: AssetFile",{cmd:e});if("assetFileId"in e){if((0,p.gt0)(e.assetFileId)){const t=v.AssetFile.ops().findById(e.assetFileId);return null!=t?t:S().throw("Invalid cmd: db missing AssetFile",{cmd:e})}return S().throw("Invalid cmd: invalid assetFileId",{cmd:e})}return S().throw("Invalid cmd: missing af or assetFileId",{cmd:e})}async function M(e){const t=performance.now(),i=P(e),r=i.id,s=(0,o.mkLogger)(`updateAssetFile(${i.id})`),d=i.posixFile_(),h=(0,u.forceContextOrSetting)(e),m={id:r,assetFileId:r,path:d?.nativePath,uri:i?.uri};if(null==d)return(0,a.syncReport)().onProgress({path:i.uri,elapsedMs:(0,l.roundMs)(performance.now()-t),from:"updateAssetFile_()",type:"file",details:"cannot resolve URI to nativePath",state:a.SyncFileStates.unavailable}),{...m,error:"file for URI not found"};const p=await i.isUriDeleted();if(null==p)return s.info("no-op: file URI points to an unmounted volume",m),(0,a.syncReport)().onProgress({path:d.nativePath,elapsedMs:(0,l.roundMs)(performance.now()-t),from:"updateAssetFile_()",type:"file",state:a.SyncFileStates.unavailable}),{...m,skipped:!0};const g=e.whyReject??await i.whyRejected(h);if(p||!(0,f.blank)(g)){const e={...m,rejected:g,deleted:p};return s.warn("file was deleted or rejected. Deleting.",e),(0,a.syncReport)().onProgress({path:d.nativePath,elapsedMs:(0,l.roundMs)(performance.now()-t),from:"updateAssetFile_()",type:"file",details:p?"file no longer exists":"rejected: "+g,state:p?a.SyncFileStates.absent:a.SyncFileStates.deleted}),await i.remove(),!0!==h.skipAssetRepair&&null!=i.assetId&&(y.Asset.dbl.runf(e=>w.AssetFlags.update({qb:e,flag:"validateSiblings",isSet:!0}).where("id",i.assetId)),(0,n.ee)().emitThrottled("notifyWorkAvailable","validateAssetSiblings")),e}const S=await d.uri_();if(!await(0,c.uriIsEquivalent)(S,i.uri)){const e=await T(i,S,h);if(null!=e)return{...m,...e}}if(b.AssetFileFlags.has(i.flags??0,"forceUpdate")&&v.AssetFile.dbl.runf(e=>b.AssetFileFlags.update({qb:e.where("id",i.id),flag:"forceUpdate",isSet:!1})),!h.forceSync&&null==await i.whyNeedsUpsert()){s.info("no-op: file already matches db record",m);const e={updatedAt:Date.now()};return null!=h.scanGeneration&&(e.lastVisitedGeneration=h.scanGeneration),v.AssetFile.dbl.runf(t=>t.where("id",i.id).update(e)),{...m,skipped:!0}}return{...m,...await _(i,h)}}async function T(e,t,i){const s=(0,o.mkLogger)(`handleAssetFileUriChange(${e.id})`),n=(0,d.uniq)([...(0,c.uriEncodingVariants)(e.uri),...(0,c.uriEncodingVariants)(t)]);s.warn("URI is changing. Avoiding duplicate keys.",{priorUri:e.uri,variants:n});const a=v.AssetFile.ops().allf(t=>t.whereIn("uri",n).andWhereNot({id:e.id}));if((0,d.isNotEmpty)(a)){s.warn("Found other AssetFiles with equivalent URIs.",{afIds:a.map(e=>e.id)});const t=[e,...a],o=(0,r.sortAssetFilesInPlace)(t);if((0,d.isEmpty)(o))return s.warn("sortAssetFiles returned undefined",{arr:t.map(e=>(0,g.pick)(e,"id","uri")),variants:n}),{error:"sortAssetFiles returned undefined"};const l=t.map(e=>e.id);for(const e of o)if(await e.exists_()){v.AssetFile.dbl.runf(t=>t.whereIn("id",l.filter(t=>t!==e.id)).delete());const r=_(e,i);return y.Asset.dbl.runf(e=>e.update({version:0,updatedAt:Date.now()}).whereIn("id",(0,d.uniq)(t.map(e=>e.assetId)))),r}}s.info("no-op, no duplicate URIs.")}async function _(e,t){const i=performance.now();return null!=await e.upsertIfNeeded_(void 0,t)&&null!=e.assetId&&y.Asset.touch([e.assetId]),(0,a.syncReport)().onProgress({path:e.nativePath,elapsedMs:(0,l.roundMs)(performance.now()-i),from:"updateAssetFileIfNeeded()",type:"file",state:e.$syncState??a.SyncFileStates.unknown,url:(0,h.assetPath)(e.assetId)}),{assetFileId:e.id}}},68640(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateAssetPreviews_=async function(e){const t=performance.now(),i=e.assetId??e.asset?.id??(0,y.toA)(e.assetFiles).find(e=>(0,p.gt0)(e.assetId))?.assetId,u=(0,c.forceContextOrSetting)(e),f=b().child(".Asset:"+i);if(u.skipPreviews)return void f.warn("skipPreviews is true: no-op",{assetId:i});if(!(0,p.gt0)(i))return f.throw("invalid assetId",{assetId:i});const w=e.asset??v.Asset.ops().findById(i);if(null==w)return f.throw("Asset:"+i+" not found");f.throwIfAborted_(u.halt);try{const n=l.Previews.instance().ap(i),c=await n.readInfo();f.throwIfAborted_(u.halt);const p=(0,s.sortAssetFilesInPlace)(e.assetFiles??w.getAssetFiles()),y=p.map(e=>({id:e.id,assetId:e.assetId,uri:e.uri})),v=await(0,l.buildAssetPreviews_)({...u,assetId:i,assetFiles:p}),b=p.find(e=>e.id===v?.assetFileId)??await(0,r.findAsync)(p,e=>(0,d.uriIsEquivalent)(v?.uri,e.uri)),S=p.find(e=>e.id===v?.assetFileId),P=null!=S&&S.assetId!==i;(0,o.syncReport)().onProgress({path:`Asset:${i}`,type:"file",state:P?"warning":"note",from:"updateAssetPreviews_",details:P?`CROSS-ASSET: Preview selected AssetFile:${v?.assetFileId} which belongs to Asset:${S?.assetId}, not Asset:${i}`:`Preview generated from AssetFile:${v?.assetFileId}`,elapsedMs:performance.now()-t,meta:{selectedAssetFileId:v?.assetFileId,selectedUri:v?.uri,selectedFileAssetId:S?.assetId,expectedAssetId:i,inputFiles:y,wrongAsset:P},url:(0,h.assetPath)(i)}),f.info("buildAssetPreviews_()",{result:v,primaryAssetFile:b});const M=b?.posixFile_();if(null==b||null==M||!0!==await(M?.exists()))return f.throw("buildAssetPreviews_() returned invalid assetFileId"+a.InternalErrorFlag,{newInfo:v,assetFiles:p.map(e=>(0,g.pick)(e,"id","uri")),primaryAssetFile:b,primaryPosixFile:M});const T=(0,m.eql)(c,v),_=!0===v?.noop||null==v||T;return{...v,noop:_}}catch(e){throw(0,n.ending)()||(f.warn("Failed to update previews. Un-showing asset "+i,{error:e}),w.markUnshownAndUpsert()),e}};const r=i(48884),s=i(92434),n=i(99331),a=i(38835),o=i(74128),l=i(48604),u=i(50213),c=i(69589),d=i(87001),h=i(75761),f=i(45599),m=i(50357),p=i(31586),g=i(68708),y=i(59455),v=i(43487),b=(0,f.defer)(()=>(0,u.mkLogger)("sync-file.UpdateAssetPreviews"))},72914(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncRpcClient=void 0;const r=i(34102),s=i(97490),n=i(28874),a=i(45599);class o extends s.BaseJsonRpcClient{static instance=(0,a.defer)(()=>new o({port:n.Settings.syncPort.valueOrDefault}));static{(0,r.ee)().on("syncShutdown",()=>o.resetInstance())}static resetInstance(){o.instance.prior()?.close(),o.instance.reset()}constructor(e){super("sync.SyncRpcClient",e)}unwrap(e){return e.result}async status(){return this.unwrap(await this.request("status",void 0))}async enqueueTask(e){await this.request("enqueueTask",{task:e})}async getTaskListState(){return this.unwrap(await this.request("getTaskListState",void 0))}async whyDoNotRun(){return(await this.request("whyDoNotRun",void 0)).result}async isPaused(){return this.unwrap(await this.request("isPaused",void 0))}async nextRunDate(){const e=(await this.request("nextRunDate",void 0)).result;return null==e?void 0:new Date(e)}async operationalState(){return this.unwrap(await this.request("operationalState",void 0))}async getTimings(){return this.unwrap(await this.request("getTimings",void 0))}async setPaused(e){await this.request("setPaused",{paused:e})}async applyTagRenames(){return this.unwrap(await this.request("applyTagRenames",void 0))}async runMaintenance(){await this.request("runMaintenance",void 0)}async resetHealthChecks(){await this.request("resetHealthChecks",void 0)}async rerunToolChangeTracker(){await this.request("rerunToolChangeTracker",void 0)}}t.SyncRpcClient=o},19433(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adoptAssetFile=async function(e){const{assetFileId:t}=e,i=g(),r=h.AssetFile.ops().findById(t);if(null==r)return void i.warn("Orphan AssetFile not found",{assetFileId:t});if((0,c.gt0)(r.assetId))return void i.debug("AssetFile already has assetId, skipping",{assetFileId:t,assetId:r.assetId});const s=await m.AssetMatcher.findOrCreateAsset(r);if(!s.created){r.assetId=s.asset.id,r.isPrimary=!1,r.upsert();const e=(0,p.revalidateAssetSiblings)(s.asset.id,"adoptAssetFile");null!=e&&e.evicted.length>0&&i.info("Post-adoption revalidation evicted siblings",{assetId:s.asset.id,evictedCount:e.evicted.length,evictedUris:e.evicted.map(e=>e.uri)})}return i.info("Adopted orphan AssetFile",{assetFileId:r.id,assetId:s.asset.id,created:s.created,matchedBy:s.matchedBy}),(0,a.syncReport)().onProgress({path:r.nativePath,from:"adoptAssetFile",type:"file",state:"note",details:s.created?`Created new asset (matched by: ${s.matchedBy})`:`Matched to existing asset #${s.asset.id} (matched by: ${s.matchedBy})`,meta:{assetFileId:r.id,assetId:s.asset.id,created:s.created,matchedBy:s.matchedBy},url:(0,l.assetPath)(s.asset.id)}),y(s.asset.id),{assetId:s.asset.id,created:s.created,matchedBy:s.matchedBy}},t.maybeSetFinalizationFlag=async function(e){const t=g(),i=e.id;if(!0!==e.shown)return t.debug("maybeSetFinalizationFlag: asset not shown, setting flag",{assetId:i}),y(i),!0;const s=e.getAssetFiles({refresh:!0});if(0===s.length)return t.warn("maybeSetFinalizationFlag: shown asset has no files",{assetId:i}),!1;const n=(0,r.sortAssetFilesInPlace)([...s])[0],a=e.getPrimary({refresh:!1});return n?.id!==a?.id?(t.info("maybeSetFinalizationFlag: primary would change, setting flag",{assetId:i,currentPrimaryId:a?.id,bestFileId:n?.id}),y(i),!0):(t.debug("maybeSetFinalizationFlag: primary unchanged, no flag needed",{assetId:i,primaryId:a?.id}),!1)};const r=i(92434),s=i(70974),n=i(34102),a=i(74128),o=i(50213),l=i(75761),u=i(45599),c=i(31586),d=i(43487),h=i(54017),f=i(39656),m=i(61859),p=i(86368),g=(0,u.defer)(()=>(0,o.mkLogger)("sync.AdoptAssetFile"));function y(e){const t=f.AssetFlags.toBit("finalize"),i=f.AssetFlags.toBit("failedFinalize");d.Asset.dbl.runf(r=>r.where("id",e).update({flags:(0,s.knex)().raw("(COALESCE(Asset.flags, 0) | ?) & ~?",[t,i]),updatedAt:Date.now()})),(0,n.ee)().emitThrottled("notifyWorkAvailable","finalizeAsset")}},62859(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AdoptAssetFileProducer=void 0;const r=i(51040),s=i(74128),n=i(39056),a=i(30301),o=i(54017),l=i(95577),u=i(19433);class c extends l.BaseTaskProducer{static instance=(0,a.lazy)(()=>new c);constructor(){super("AdoptAssetFileProducer","adoptAssetFile")}queryIds(e,t){let i=o.AssetFile.query().join("DirUri","DirUri.id","AssetFile.dirUriId").whereNull("AssetFile.assetId").orderByRaw(`${(0,r.patternSortOrderCase)("mimetype",n.AggregationSettings.assetVariationMimetypeSortOrder.values)}, DirUri.uri, AssetFile.basename`).limit(e).select("AssetFile.id");return t.size>0&&(i=i.whereNotIn("AssetFile.id",[...t])),o.AssetFile.dbl.pluckAll(i)}async mkTask(e){return null==o.AssetFile.ops().findById(e)&&this.logger.throw("Orphan AssetFile not found",{assetFileId:e}),{method:"adoptAssetFile",args:{assetFileId:e}}}onNewOrphan(e){this.notifyWorkAvailable()}async onUpdatedAssetFile(e){const t=o.AssetFile.ops().findById(e),i=t?.getAsset();null!=i&&await(0,u.maybeSetFinalizationFlag)(i)}async recoverOrphans(){const e=c.orphanCount();e>0&&(this.logger.info(`Recovering ${e} orphan AssetFiles from interrupted sync`),(0,s.syncReport)().onProgress({from:"AdoptAssetFileProducer.recoverOrphans",state:"note",details:`Recovering ${e} orphan AssetFiles from interrupted sync`}),this.notifyWorkAvailable())}static orphanCount(){return o.AssetFile.ops().count(o.AssetFile.query().whereNull("assetId").count())}}t.AdoptAssetFileProducer=c},61859(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetMatcher=void 0,t.sortBySha=S,t.whyNotValidSibling=M;const r=i(79781),s=i(92434),n=i(89724),a=i(31302),o=i(7723),l=i(11512),u=i(50213),c=i(28874),d=i(65162),h=i(28544),f=i(14036),m=i(76790),p=i(22573),g=i(45599),y=i(31586),v=i(62324),b=i(43487),w=i(54017);function S(e){return(0,m.sortBy)(e,e=>(0,y.gt0)(e.width)&&(0,y.gt0)(e.height)&&(0,p.notBlank)(e.uri)?(0,p.toNotBlank)(e.sha):void 0)}const P=(0,g.defer)(()=>(0,u.mkLogger)("sync.AssetMatcher"));function M(e,t){for(const i of t){if(i.id===e.id)continue;const t=(0,r.whyNotSimilarMedia)(e,i);if(null!=t)return t}}t.AssetMatcher=class{static async findMatchingAsset(e,t={}){const{rejectedAssetIds:i}=t;P().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),imageDataHash:e.imageDataHash?.substring(0,8)});const r=(0,y.gt0)(e.capturedAtLocal)?h.CapturedAt.fromFields(e):void 0,s=r?.localBoundaries();if((0,p.notBlank)(e.sha)){const t=this.#Qs(e.sha,i);if(t.length>0){const i=await this.#en(e.sha,t),r=b.Asset.ops().findById(i);if(null!=r)return P().info("Matched asset by SHA",{assetFileId:e.id,assetId:r.id,sha:e.sha,collisionCount:t.length}),{asset:r,created:!1,matchedBy:"sha"}}}if((0,p.notBlank)(e.imageDataHash)){const t=this.#tn(e.imageDataHash,i);if(t.length>0){const r=await this.validateCandidates(e,t,i,"imageDataHash");if(null!=r)return P().info("Matched asset by imageDataHash",{assetFileId:e.id,assetId:r.id,imageDataHash:e.imageDataHash}),{asset:r,created:!1,matchedBy:"imageDataHash"}}}if(null!=s){const t=await this.#in(e,s,i);if(null!=t)return P().info("Matched asset by basename + similarity",{assetFileId:e.id,assetId:t.id,basename:e.basename}),{asset:t,created:!1,matchedBy:"basename"}}if(null!=s){const t=await this.#rn(e,s,i);if(null!=t)return P().info("Matched asset by capturedAt + similarity",{assetFileId:e.id,assetId:t.id,capturedAtLocal:e.capturedAtLocal}),{asset:t,created:!1,matchedBy:"capturedAt"}}if((0,o.isVec0Available)()){const t=await this.findAssetByBnameImageHashes(e,i);if(null!=t)return P().info("Matched asset by bname + image hash",{assetFileId:e.id,assetId:t.id}),{asset:t,created:!1,matchedBy:"bnameImageHash"}}if(c.Settings.allowFuzzyDateImageHashMatches.valueOrDefault&&(0,o.isVec0Available)()){const t=await this.findAssetByImageHashes(e,i,s);if(null!=t)return P().info("Matched asset by image hash",{assetFileId:e.id,assetId:t.id}),{asset:t,created:!1,matchedBy:"imageHash"}}P().debug("AssetMatcher: No match found",{assetFileId:e.id,basename:e.basename})}static async findOrCreateAsset(e,t={}){const i=await this.findMatchingAsset(e,t);if(null!=i)return i;P().info("AssetMatcher: No match found, creating NEW asset",{assetFileId:e.id,basename:e.basename,monochrome:e.monochrome,capturedAtLocal:e.capturedAtLocal});const r=b.Asset.ops().insertOne({capturedAtLocal:e.capturedAtLocal,mimetype:e.mimetype,shown:!1});return e.assetId=r.id,e.isPrimary=!0,e.upsert(),P().info("AssetMatcher: Created new asset",{assetFileId:e.id,assetId:r.id,capturedAtLocal:e.capturedAtLocal}),{asset:r,created:!0,matchedBy:"created"}}static#Qs(e,t){if((0,p.blank)(e))return[];let i=b.Asset.query().select("Asset.id").join("AssetFile","Asset.id","AssetFile.assetId").where("AssetFile.sha",e).orderBy("Asset.id").distinct();return null!=t&&t.size>0&&(i=i.whereNotIn("Asset.id",Array.from(t))),b.Asset.dbl.pluckAll(i)}static async#en(e,t){const i=t[0];if(1===t.length)return i;const r=t.slice(1);P().warn("SHA collision across multiple Assets — dissolving duplicates",{sha:e,keeperId:i,dupIds:r});for(const t of r){const r=w.AssetFile.ops().allf(e=>e.where("assetId",t)).map(e=>e.id).filter(y.gt0);r.length>0&&w.AssetFile.dao.orphan(...r),await b.Asset.dao.remove({assetId:t,blocklistShas:!1,unlinkAssetFiles:!1}),P().info("SHA-collision duplicate dissolved",{sha:e,keeperId:i,dissolvedAssetId:t,orphanedFileCount:r.length})}return i}static#tn(e,t){if((0,p.blank)(e))return[];const i=c.Settings.maxContemporaryAdoptionAssets.valueOrDefault;let r=b.Asset.query().select("Asset.id").join("AssetFile","Asset.id","AssetFile.assetId").where("AssetFile.imageDataHash",e).orderBy("Asset.id").limit(i).distinct();return null!=t&&t.size>0&&(r=r.whereNotIn("Asset.id",Array.from(t))),b.Asset.dbl.pluckAll(r)}static async#in(e,t,i){if(!c.Settings.checkBasenameMatches.valueOrDefault)return;if((0,p.blank)(e.basename))return;const r=(0,f.stripExt)(e.basename).toLowerCase();if((0,p.blank)(r))return;const s=c.Settings.maxContemporaryAdoptionAssets.valueOrDefault;let n=b.Asset.query().select("Asset.id").join("AssetFile","Asset.id","AssetFile.assetId").whereBetween("Asset.capturedAtLocal",[t.start,t.end]).whereRaw('"AssetFile"."basename" LIKE ?',[r+".%"]).whereNot("AssetFile.id",e.id).orderBy("Asset.id").limit(s).distinct();null!=i&&i.size>0&&(n=n.whereNotIn("Asset.id",Array.from(i)));const a=b.Asset.dbl.pluckAll(n);return 0!==a.length?(P().debug("Found candidates by basename",{assetFileId:e.id,basename:e.basename,basenameWithoutExt:r,candidateCount:a.length}),this.validateCandidates(e,a,i,"basename")):void 0}static async#rn(e,t,i){const r=c.Settings.maxContemporaryAdoptionAssets.valueOrDefault;let s=b.Asset.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id").join("DirUri","DirUri.id","AssetFile.dirUriId").whereBetween("Asset.capturedAtLocal",[t.start,t.end]).orderByRaw("abs(Asset.capturedAtLocal - ?), DirUri.uri, AssetFile.basename",[e.capturedAtLocal]).limit(r).distinct();null!=i&&i.size>0&&(s=s.whereNotIn("Asset.id",Array.from(i)));const n=b.Asset.dbl.pluckAll(s.select("Asset.id"));if(0!==n.length)return P().info("Strategy 4: Found candidate Assets for capturedAt matching",{assetFileId:e.id,basename:e.basename,candidateCount:n.length,candidateAssetIds:n,bounds:t}),this.validateCandidates(e,n,i,"capturedAt");P().info("Strategy 4: No candidate Assets found in capturedAt window",{assetFileId:e.id,basename:e.basename,capturedAtLocal:e.capturedAtLocal,bounds:t,limit:r})}static async findAssetByImageHashes(e,t,i){if(!(0,o.isVec0Available)())return;const r=c.Settings.imageHashMatchK.valueOrDefault,s=c.Settings.maxContemporaryAdoptionAssets.valueOrDefault;return this.#sn(e,r,s,t,i)}static async findAssetByBnameImageHashes(e,t){if(!(0,o.isVec0Available)())return;if("tags"===e.capturedAtSrc&&!(0,n.localIsFuzzy)(e.capturedAtLocal))return;const i=(0,d.shortestBname)(e.basename);if((0,p.blank)(i))return;const r=c.Settings.imageHashMatchK.valueOrDefault,s=c.Settings.maxContemporaryAdoptionAssets.valueOrDefault;return this.#sn(e,r,s,t,void 0,i,"bnameImageHash")}static async#sn(e,t,i,r,s,u,d="imageHash"){if(!(0,o.isVec0Available)())return;const h=(0,l.hashRecordToLHashHex)(e);if(null==h)return void P().debug("Missing hashes for hamming distance search",{assetFileId:e.id});const f=Math.max(c.Settings.imageHashRelaxedThresholdPct.valueOrDefault+20,60),m=Math.floor(192*(100-f)/100),g=[{hex:h,source:"HashRecord"}],y=(0,l.hashRecordToLHashHex)((0,l.hashRecord0ToHashRecord)(e));null!=y&&y!==h&&g.push({hex:y,source:"HashRecord0"});const w=!("tags"===e.capturedAtSrc)||(0,n.localIsFuzzy)(e.capturedAtLocal);for(const{hex:n,source:o}of g)try{(0,v.assertLHashHex)(n);const l=(0,p.blank)(u)?"":" AND bname = :bname",c=(0,p.blank)(u)?{}:{bname:u};let h=[];if(null==s||w){const i=`\n SELECT assetFileId, distance\n FROM AssetFileHash\n WHERE lHash MATCH vec_bit(X'${n}')\n AND k = :matchK\n AND distance <= :maxHammingDistance\n ${l}\n ORDER BY distance\n `;h=b.Asset.dbl.all({sql:i,bindings:{matchK:t,maxHammingDistance:m,...c}}),null!=s&&w&&P().debug("Phase 1 without filtering (orphan is fuzzy)",{assetFileId:e.id,rowCount:h.length,orphanIsFuzzy:w,source:o})}else{const i=`\n SELECT assetFileId, distance\n FROM AssetFileHash\n WHERE lHash MATCH vec_bit(X'${n}')\n AND k = :matchK\n AND distance <= :maxHammingDistance\n AND capturedAtLocal BETWEEN :boundsStart AND :boundsEnd\n ${l}\n ORDER BY distance\n `,r=b.Asset.dbl.all({sql:i,bindings:{matchK:t,maxHammingDistance:m,boundsStart:s.start,boundsEnd:s.end,...c}}),a=`\n SELECT assetFileId, distance\n FROM AssetFileHash\n WHERE lHash MATCH vec_bit(X'${n}')\n AND k = :matchK\n AND distance <= :maxHammingDistance\n AND capturedAtFuzzy = 1\n ${l}\n ORDER BY distance\n `,u=b.Asset.dbl.all({sql:a,bindings:{matchK:t,maxHammingDistance:m,...c}}),d=new Map;for(const e of[...r,...u]){const t=d.get(e.assetFileId);(null==t||e.distance<t)&&d.set(e.assetFileId,e.distance)}h=Array.from(d.entries()).map(([e,t])=>({assetFileId:e,distance:t})).sort((e,t)=>e.distance-t.distance).slice(0,t),P().debug("Phase 1 with metadata filtering",{assetFileId:e.id,boundedCount:r.length,fuzzyCount:u.length,combinedCount:h.length,bounds:s,orphanIsFuzzy:w,source:o})}if(0===h.length)continue;const f=h.map(e=>e.assetFileId),g={assetFileIds:JSON.stringify(f)},y=null!=r&&r.size>0?` AND af.assetId NOT IN ${(0,a.sqlWhereInJsonClauseNamed)("rejectedAssetIds")}`:"";null!=r&&r.size>0&&(g.rejectedAssetIds=JSON.stringify(Array.from(r))),g.limit=i;const S=`\n SELECT DISTINCT af.assetId\n FROM AssetFile af\n WHERE af.id IN ${(0,a.sqlWhereInJsonClauseNamed)("assetFileIds")}\n AND af.assetId IS NOT NULL\n ${y}\n LIMIT :limit\n `,M=b.Asset.dbl.all({sql:S,bindings:g}).map(e=>e.assetId);if(M.length>0){P().debug("Found candidates by hamming distance (MATCH)",{assetFileId:e.id,phase1Count:h.length,candidateCount:M.length,matchK:t,maxHammingDistance:m,bname:u,source:o});const i=await this.validateCandidates(e,M,r,d);if(null!=i)return i}}catch(t){P().debug("Hamming distance MATCH query failed",{assetFileId:e.id,source:o,error:t})}P().debug("No candidate Assets found by hamming distance (MATCH)",{assetFileId:e.id,queriedHashes:g.length})}static async validateCandidates(e,t,i,n){const a=b.Asset.ops().findByIds(t),o=a.map(e=>e.id).filter(y.gt0);if(o.length>0){const e=w.AssetFile.ops().allf(e=>e.whereIn("assetId",o).orderBy("id"));for(const t of a){const i=e.filter(e=>e.assetId===t.id);(0,s.sortAssetFilesInPlace)(i);for(const e of i)e.$asset=t;t.assetFiles=i}}for(const t of a){const s=t.id;if(null==(t.getPrimary()??t.getOrSetPrimary())){P().debug("Candidate Asset has no files, skipping",{assetId:s,strategy:n});continue}const a=t.getAssetFiles();let o=!1;for(const t of a)if(null==(0,r.whyNotSimilarMedia)(e,t)){o=!0;break}if(!o){P().debug("Doesn't match any file (single-link gate)",{assetFileId:e.id,candidateAssetId:s,fileCount:a.length,strategy:n}),i?.add(s);continue}const l=S([...a,e]),u=[l[0]];for(const e of l.slice(1))null==M(e,u)&&u.push(e);if(u.some(t=>t.id===e.id))return P().debug("Would survive revalidation",{assetFileId:e.id,matchedAssetId:s,survivorCount:u.length,totalTentative:l.length,strategy:n}),t;P().debug("Would not survive revalidation",{assetFileId:e.id,candidateAssetId:s,survivorCount:u.length,strategy:n}),i?.add(s)}}}},15399(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.finalizeAsset=async function(e){const t=performance.now(),{assetId:i}=e;if(!(0,g.gt0)(i))return I().throw("finalizeAsset(): invalid assetId",{args:e});const u=w.Asset.ops().findById(i);if(null==u)return I().throw("finalizeAsset(): Asset not found",{assetId:i,logLevel:"warn"});const{assetDeleted:m}=await(0,k.removeProblematicAssetFiles)(u,"finalizeAsset",I());if(m)return{newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:!1};if(S.AssetFlags.has(u.flags,"validateSiblings"))return w.Asset.dbl.runf(e=>S.AssetFlags.update({qb:e,flag:"finalize",isSet:!1}).where("id",i)),I().info("finalizeAsset(): skipped, validateSiblings pending",{assetId:i}),{newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:!1};const C=I().child(`.finalizeAsset(Asset:${i})`),A=(0,E.getTaskAbortable)(e);null!=A&&(C.abortable=A);const x=(0,E.getTaskReportProgress)(e);try{const e=await async function(e,t,i){const s=t.id;let a=t.getAssetFiles();const u=t.getPrimaryNativePath();null!=u&&await(0,D.maybeDelayIfNotProd)(u);for(const e of a){const t=e.nativePath;null!=t&&(0,D.maybeThrowTestFinalizeError)(t)}const c={newAssetFileUris:[],previewsUpdated:!1,transcoded:!1,tagged:!1};if(e.throwIfAborted_(),0===a.length)return await w.Asset.dao.remove({assetId:s,blocklistShas:!1,unlinkAssetFiles:!1}),e.throw(`Asset:${s} had no asset files. Deleted.`,{doNotSend:!0,retriable:!1});await(0,T.mayCopyAssetsToLibrary)()&&(await async function(e,t,i){const s=[...(0,p.groupBy)(e,e=>e.sha).entries()].sort(([e],[t])=>(e??"").localeCompare(t??""));for(const[e,n]of s){i.throwIfAborted_();const s=(0,r.sortAssetFilesInPlace)([...n]);try{for(const e of s)if(await e.exists_()){const i=await b.Library.instanceRequired_().assetFileRepository().maybeCopyToLibrary_(e,(0,d.forceContextOrSetting)({}),()=>{});if(null!=i){t.newAssetFileUris.push(i.uri);break}}}catch(t){i.warn("Failed to copy variation to library, but continuing",{sha:e,uris:s.map(e=>e.uri),error:t})}}}(a,c,e),a=t.getAssetFiles({refresh:!0})),e.throwIfAborted_();const h=await(0,_.updateAssetPreviews_)({asset:t,assetFiles:a});c.previewsUpdated=!0!==h?.noop;const{af:f,source:m}=await async function(e,t){if((0,g.gt0)(t?.assetFileId)){const i=e.getAssetFiles().find(e=>e.id===t.assetFileId)??e.getAssetFiles({refresh:!0}).find(e=>e.id===t.assetFileId);return null==i?I().throw("AssetPreviewInfo referenced unknown assetFileId",{asset:e,info:t}):{af:i,source:"previewInfo"}}const i=e.getPrimary({refresh:!1});if(null!=i)return{af:i,source:"getPrimary"};return{af:await(0,r.bestExistingAssetFile)(e.getAssetFiles()),source:"bestExisting"}}(t,h);if(null==f)return e.throw("null primaryOrShownAssetFile()",{asset:t});e.info("Selected primary file",{assetFileId:f.id,source:m,assetFileCount:a.length}),await t.setPrimary_(f,{skipAssetUpsert:!0});const P=f.posixFile_();if(t.isVideo()){if(null==P)return e.throw("null primary.posixFile()",{asset:t,assetFiles:t.getAssetFiles()});const r=null!=i?e=>i({pct:e.pct,etaMs:e.etaMs,speed:e.speed,label:"Transcoding video"}):void 0;c.transcoded=null!=await(0,l.transcode_)(P,o.Previews.instance().ap(s).mp4(),{force:!1,halt:e.abortable,onProgress:r})}e.throwIfAborted_(),await t.markShownAndUpsert_(f),await(0,v.tagAndUpsertAsset_)(t),c.tagged=!0;const M=S.AssetFlags.toBit("finalize")|S.AssetFlags.toBit("failedFinalize");return w.Asset.dbl.runf(e=>e.where("id",s).update({flags:(0,n.knex)().raw("COALESCE(flags, 0) & ~?",[M])})),e.tap({msg:"finalizeAsset() complete",result:c,meta:{asset_assetFiles:t.getAssetFiles().map(e=>(0,y.pick)(e,"id","uri")),assetFiles:a.map(e=>(0,y.pick)(e,"id","uri"))}})}(C,u,x);return(0,a.syncReport)().onProgress({path:u.getPrimaryNativePath()??`Asset:${i}`,type:"file",state:a.SyncFileStates.completed,from:"finalizeAsset",elapsedMs:performance.now()-t,details:`finalized: tags=${u.tagPaths().join(", ")}`,url:(0,f.assetPath)(i)}),e}catch(e){if(!((0,s.ending)()||(0,c.isTest)()&&null==(0,P.modelDb)())){const t=u.getPrimaryNativePath(),r=S.AssetFlags.has(u.flags,"failedFinalize"),s=u.isActive(),a=s?u.tagIds():[];C.warn("Failed to finalize asset, marking unshown",{error:e,assetId:i,primaryPath:t,alreadyFailed:r});try{const e=S.AssetFlags.toBit("finalize"),t=r?0:S.AssetFlags.toBit("failedFinalize");w.Asset.dbl.runf(r=>r.where("id",i).update({shown:0,updatedAt:Date.now(),flags:(0,n.knex)().raw("(COALESCE(flags, 0) & ~?) | ?",[e,t])})),s&&!(0,h.isEmpty)(a)&&M.Tag.dao.deltaAssetCountAndAncestors(a,-1)}catch(e){C.warn("Failed to update asset flags after finalization error",{upsertError:e,assetId:i,primaryPath:t})}}throw e}};const r=i(92434),s=i(99331),n=i(70974),a=i(74128),o=i(48604),l=i(66106),u=i(50213),c=i(7282),d=i(69589),h=i(40958),f=i(75761),m=i(45599),p=i(23838),g=i(31586),y=i(68708),v=i(88224),b=i(64526),w=i(43487),S=i(39656),P=i(94448),M=i(48723),T=i(41844),_=i(68640),E=i(23254),k=i(49896),D=i(90910),I=(0,m.defer)(()=>(0,u.mkLogger)("sync.FinalizeAsset"))},76351(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDataVolumeMountPoint=async function(e){if(!n.isMac)return!1;const t=await(0,r.getFirmlinks)();return null!=t&&e===t.mountPoint},t.macDataVolumeRoots=async function*(e){const t=await(0,r.getFirmlinks)();if(null!=t)for(const i of t.links){if(!o.has(i.visiblePath))continue;if(!await(0,s.isReadableDirectory)(i.visiblePath))continue;const t=await(0,a.toUriPath)({nativePath:i.visiblePath,volume:e});null!=t&&(yield t)}};const r=i(9029),s=i(16287),n=i(43334),a=i(16817),o=new Set(["/Users"])},94019(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isCurrentScanPath=void 0,t.pathsToSync=async function*(){return yield*(0,h.asyncUniqBy)(async function*(){if(l.Settings.argvScanPaths.isNotEmpty())return void(yield*g(l.Settings.argvScanPaths.values));const e=(0,n.originalsDir)();if(null==e)return void p().warn("pathsToSync(): originalsDir is null, nothing to scan");const t={nativePath:e,uri:c.PSLIB_ROOT_URI};l.Settings.scanLibraryFirst.valueOrDefault&&(yield t),yield*g(l.Settings.scanPaths.values),l.Settings.scanAllDrives.valueOrDefault&&(yield*async function*(){for await(const e of(0,a.scannableVolumes)()){if(await(0,f.isDataVolumeMountPoint)(e.mountPoint)){yield*(0,f.macDataVolumeRoots)(e);continue}const t=await(0,u.toUriPath)({nativePath:e.mountPoint,volume:e});null==t?p().warn("Ignoring scanPath element: failed to create URI path",e.mountPoint):yield t}}()),l.Settings.scanLibraryLast.valueOrDefault&&(yield t)}(),e=>e.nativePath)};const r=i(19851),s=i(50213),n=i(9595),a=i(34075),o=i(16287),l=i(28874),u=i(16817),c=i(5696),d=i(40958),h=i(41801),f=i(76351);var m=i(63458);Object.defineProperty(t,"isCurrentScanPath",{enumerable:!0,get:function(){return m.isCurrentScanPath}});const p=(0,r.lazy)(()=>(0,s.mkLogger)("sync.PathsToSync"));async function*g(e){for(const t of(0,d.compactBlanks)(e))if(await(0,o.isReadableDirectory)(t)){const e=await(0,u.toUriPath)({nativePath:t});null==e?p().warn("Ignoring scanPath element: failed to create URI path",t):yield e}else p().warn("Ignoring scanPath element: not readable directory",t)}},49896(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.removeProblematicAssetFiles=async function(e,t,i){const u=e.id,c=e.getAssetFiles(),d=[],h=[];for(const e of c){const n=e.posixFile_()?.nativePath;if(null!=n&&l.ProblematicPath.isProblematic(n)){h.push(e.id),d.push(n);const a=l.ProblematicPath.getStrikeCount(n);i.info("Removing problematic AssetFile",{assetId:u,assetFileId:e.id,path:n,strikeCount:a}),(0,r.syncReport)().onProgress({path:n,type:"file",state:r.SyncFileStates.excluded,from:t,details:`Removed due to ${(0,s.plur)(a,"strike")} from prior timeouts`})}}if(0===h.length)return{removedCount:0,removedPaths:[],remainingFiles:c,assetDeleted:!1};const f=o.AssetFile.db().db;for(const e of h)(0,n.deleteAssetFileHash)(f,e);o.AssetFile.dbl.runf(e=>e.whereIn("id",h).delete()),i.info("Removed problematic AssetFiles",{assetId:u,removedCount:h.length,removedPaths:d});const m=e.getAssetFiles({refresh:!0});return 0===m.length?(i.info("Asset has no files after removing problematic ones, deleting",{assetId:u}),await a.Asset.dao.remove({assetId:u,blocklistShas:!1,unlinkAssetFiles:!1}),{removedCount:h.length,removedPaths:d,remainingFiles:[],assetDeleted:!0}):{removedCount:h.length,removedPaths:d,remainingFiles:m,assetDeleted:!1}};const r=i(74128),s=i(12168),n=i(75914),a=i(43487),o=i(54017),l=i(33978)},30914(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.repairAsset=async function(e){const t=performance.now(),{assetId:i}=e,s={from:"repairAsset",path:`Asset:${i}`},o=d().child(`.repairAsset(Asset:${i})`),h=(0,c.getTaskAbortable)(e);null!=h&&(o.abortable=h);const f=l.Asset.ops().findById(i);if(null==f)return void(0,r.syncReport)().onProgress({...s,type:"file",state:r.SyncFileStates.excluded,details:"no such Asset",elapsedMs:(0,n.roundMs)(performance.now()-t)});const m=f.getAssetFiles({refresh:!0});if(0===m.length)return await l.Asset.dao.remove({assetId:i,blocklistShas:!1,unlinkAssetFiles:!1}),void(0,r.syncReport)().onProgress({...s,type:"file",state:r.SyncFileStates.deleted,details:"Asset has no files. Removed.",elapsedMs:(0,n.roundMs)(performance.now()-t)});const p=m.map(e=>(0,u.addLocalTask)("updateAssetFile",{assetFileId:e.id,forceSync:!0,skipAssetRepair:!0}));o.info("repairAsset: Scheduled repair",{assetId:i,updateCount:p.length}),async function(e,t,i){const s=d().child(`.awaitRepairCompletion(Asset:${t})`),o={from:"repairAsset",path:`Asset:${t}`,url:(0,a.assetPath)(t)};(0,r.syncReport)().onProgress({...o,type:"file",state:r.SyncFileStates.started,elapsedMs:(0,n.roundMs)(performance.now()-e)});try{const a=(await Promise.allSettled(i.map(e=>e.d.promise))).filter(e=>"rejected"===e.status).length;a>0&&s.warn("awaitRepairCompletion: some updateAssetFile tasks failed",{assetId:t,failed:a,total:i.length}),await(0,u.addLocalTask)("validateAssetSiblings",{assetId:t,skipFinalizeScheduling:!0}).d.promise,await(0,u.addLocalTask)("finalizeAsset",{assetId:t}).d.promise,(0,r.syncReport)().onProgress({...o,type:"file",state:r.SyncFileStates.completed,details:"Repair complete",elapsedMs:(0,n.roundMs)(performance.now()-e)})}catch(i){s.error("awaitRepairCompletion: failed",{assetId:t,err:i}),(0,r.syncReport)().onProgress({...o,type:"file",state:r.SyncFileStates.failed,details:`Repair failed: ${i}`,elapsedMs:(0,n.roundMs)(performance.now()-e)})}}(t,i,p)};const r=i(74128),s=i(50213),n=i(3685),a=i(75761),o=i(45599),l=i(43487),u=i(94761),c=i(23254),d=(0,o.defer)(()=>(0,s.mkLogger)("sync.RepairAsset"))},98622(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncCron=void 0,t.runTimeIsStale=function(e){return null==e||(0,l.lte)((0,t.SyncCron)().nextRun(new Date(e))?.getTime(),Date.now())};const r=i(1708),s=i(17415),n=i(28874),a=i(41400),o=i(30301),l=i(31586);t.SyncCron=(0,o.lazy)(()=>{const e=n.Settings.syncCronTZ.valueOrDefault??(0,s.toValidIanaZone)(r.env.TZ);return n.Settings.syncCron.cron(null==e?void 0:{timezone:e})}),(0,a.later)(()=>{n.Settings.syncCron.watchLater(()=>t.SyncCron.unset()),n.Settings.syncCronTZ.watchLater(()=>t.SyncCron.unset())})},92244(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathsAndTimesToSync=P,t.stalePathsToSync=async function(){const e=p.Operation.getAllPending({name:p.OperationNames.forceSyncPath}),t=[];for(const i of e)null!=i.value&&t.push(i.value),i.markCompleted();t.length>0&&w().info("stalePathsToSync(): found forceSyncPath operations",{forcedPaths:t});const i=await P(),r=_(),s=r?.createdAt,n=i.filter(e=>T(e,s)&&!t.includes(e.nativePath)),a=(0,d.sortBy)(n,e=>[null!=e.lastUpdatedAt&&Date.now()-S<e.lastUpdatedAt?0:1,e.lastStartedAt??0,e.lastCompletedAt??0]);return[...t,...a]},t.whyStale=M,t.isStale=T,t.bestStable=E,t.uptStatus=k,t.syncPathsForUI=async function(){const e=(0,c.uniqBy)(await P(),e=>e.nativePath),t=await E(e),i=(0,s.libraryOriginalsDirPosixFile)()?.nativePath,r=_(),n=r?.createdAt,a=e.map(e=>{const r=function(e){if(null==e)return;const t=(0,b.SyncCron)().nextRun(new Date(e));return t?.getTime()}(e.lastCompletedAt);let s=k(e,n);const a=e.nativePath===t?.nativePath;"syncing"!==s||a||(s="queued");const o={path:e.nativePath,library:i===e.nativePath,status:s,isNext:a,lastStartedTs:e.lastStartedAt,lastCompletedTs:e.lastCompletedAt,lastUpdatedTs:e.lastUpdatedAt,nextSyncTs:r},l=e.lastProgressId;if(null!=l){const e=function(e){const t=y.ProgressMeta.ops().allf(t=>t.where({progressId:e}).orderBy("createdAt"));if(0!==t.length)return(0,m.fromEntries)(t.map(e=>[e.name,e.value]))}(l),t=(0,f.toInt)(e?.totalFilesDiscovered)??0;if(t>0){const i=(0,f.toInt)(e?.processedImageCount)??0,r=(0,f.toInt)(e?.processedVideoCount)??0;o.totalFiles=t,o.importedCount=i+r;const s=e;o.excludedCount=((0,f.toInt)(s?.excludedByFilterCount??s?.rejectedByFilterCount)??0)+((0,f.toInt)(s?.excludedByImporterCount??s?.rejectedByImporterCount)??0),o.erroredCount=(0,f.toInt)(e?.erroredCount)??0,o.scannedDirCount=(0,f.toInt)(e?.scannedDirectoryCount)??0,o.excludedDirCount=(0,f.toInt)(e?.excludedDirCount)??0,o.newCount=((0,f.toInt)(s?.newImageCount)??0)+((0,f.toInt)(s?.newVideoCount)??0),o.changedCount=((0,f.toInt)(s?.updatedImageCount)??0)+((0,f.toInt)(s?.updatedVideoCount)??0),o.unchangedCount=((0,f.toInt)(s?.unchangedImageCount)??0)+((0,f.toInt)(s?.unchangedVideoCount)??0),o.absentCount=(0,f.toInt)(s?.absentCount)??0,o.resumed="true"===s?.resumed,s?.syncReportFilename&&(o.syncReportFilename=s.syncReportFilename)}}return o}),o=a.find(e=>e.isNext&&"syncing"!==e.status);if(null!=o&&!(0,u.isPaused)()){const t=e.find(e=>e.nativePath===o.path);w().info("syncPathsForUI(): 'Next' path is not syncing",{path:o.path,status:o.status,whyStale:t?M(t,n):void 0,forceRestartOp:r?{id:r.id,createdAt:new Date(r.createdAt).toISOString(),value:r.value}:void 0,lastStartedAt:null!=t?.lastStartedAt?new Date(t.lastStartedAt).toISOString():void 0,lastCompletedAt:null!=t?.lastCompletedAt?new Date(t.lastCompletedAt).toISOString():void 0,lastUpdatedAt:null!=t?.lastUpdatedAt?new Date(t.lastUpdatedAt).toISOString():void 0})}return a};const r=i(48884),s=i(87290),n=i(19851),a=i(50213),o=i(23560),l=i(28874),u=i(69385),c=i(40958),d=i(76790),h=i(42659),f=i(31586),m=i(68708),p=i(20958),g=i(49796),y=i(55009),v=i(94019),b=i(98622),w=(0,n.lazy)(()=>(0,a.mkLogger)("sync.SyncPaths")),S=h.minuteMs;async function P(){const e=l.Settings.forceSync.valueOrDefault?[]:g.Progress.times(),t=[];for await(const i of(0,v.pathsToSync)()){const r=i.uri.toString(),s=e.find(e=>e.uri===r);w().debug("pathsAndTimesToSync: matching",{uriString:r,nativePath:i.nativePath,matchedUri:s?.uri,lastCompletedAt:s?.lastCompletedAt,availableUris:e.map(e=>e.uri)}),t.push({...s,...i,uri:r})}return w().tap({msg:"pathsAndTimesToSync()",result:t})}function M(e,t){if(null==e.lastStartedAt)return"never started";if(null==e.lastCompletedAt)return"never completed";if(e.lastCompletedAt<e.lastStartedAt)return"started but not completed";if((0,f.lte)(e.lastStartedAt,t))return`started before forceRestartSync (${new Date(t).toISOString()})`;if((0,b.runTimeIsStale)(e.lastStartedAt)){const t=(0,b.SyncCron)().nextRun(new Date(e.lastStartedAt));return`cron schedule passed (lastStarted=${new Date(e.lastStartedAt).toISOString()}, nextRun=${t?.toISOString()})`}}function T(e,t){return null!=M(e,t)}function _(){return p.Operation.getFirstPendingOp({name:p.OperationNames.forceRestartSync})}async function E(e){const t=_(),i=t?.createdAt,s=e.map(e=>({path:e.nativePath,reason:M(e,i),lastStartedAt:e.lastStartedAt,lastCompletedAt:e.lastCompletedAt,lastUpdatedAt:e.lastUpdatedAt})),n=e.filter(e=>T(e,i));if((0,c.isEmpty)(n))return(0,o.isSyncService)()&&t?.markCompleted(),w().tap({msg:"bestStable(): No stale paths to sync!",result:void 0,meta:{arr:e,forceRestartOp:t}});w().debug("bestStable(): found stale paths",{staleCount:n.length,totalCount:e.length,forceRestartOp:t?{id:t.id,createdAt:t.createdAt}:void 0,staleInfo:s.filter(e=>null!=e.reason)});{const e=(0,r.greatestBy)(n,e=>e.lastUpdatedAt);if(null!=e&&(0,f.gt)(e.lastUpdatedAt,Date.now()-S))return w().tap({msg:"bestStable(): returning most recently updated",result:{...e,why:"recently updated"}})}const a=(0,d.leastBy)(n,e=>[e.lastStartedAt??0,e.lastCompletedAt??0]);return w().tap({msg:"bestStable(): returning least-recently-started or least-recently-completed:",result:null==a?void 0:{...a,why:"least recently started or completed"},meta:{stale:n}})}function k(e,t){return null==e.lastStartedAt?"queued":(0,f.gt)(e.lastCompletedAt,e.lastStartedAt-1)?T(e,t)?"queued":"synced":(0,f.gt)(e.lastUpdatedAt,Date.now()-S)?"syncing":"queued"}},90910(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.maybeDelayIfNotProd=async function(e){if((0,s.isProd)()||(0,n.isPacked)())return;const t=(0,r.basename)(e),i=t.match(c);if(null!=i){const e=parseInt(i[1],10);if(e>0)throw await(0,o.delay)(e*a.secondMs),new l.TimeoutError(`Test timeout triggered for ${t} after ${e}s`)}const d=t.match(u);if(null!=d){const e=parseInt(d[1],10);e>0&&await(0,o.delay)(e*a.secondMs)}},t.maybeThrowTestFinalizeError=function(e){if((0,s.isProd)()||(0,n.isPacked)())return;const t=process.env.PS_TEST_FINALIZE_ERROR;if(null!=t&&e.includes(t))throw new Error(`Test finalize error triggered for ${(0,r.basename)(e)}`)};const r=i(76760),s=i(7282),n=i(29325),a=i(42659),o=i(41400),l=i(85556),u=/delay_(\d+)\./,c=/timeout_(\d+)\./},86368(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.revalidateAssetSiblings=p,t.validateAssetSiblings=async function(e){const t=performance.now(),{assetId:i}=e,s=m().child(`.validateAssetSiblings(Asset:${i})`),a=(0,d.getTaskAbortable)(e);null!=a&&(s.abortable=a);const o=u.Asset.ops().findById(i);if(null==o)return void s.warn("Asset not found during validation",{assetId:i});const{assetDeleted:g,removedCount:y}=await(0,f.removeProblematicAssetFiles)(o,"validateAssetSiblings",s);if(g)return{assetId:i,filesOrphaned:y,totalFiles:y};const v=p(i,"validateAssetSiblings");if(null==v)return s.warn("validateAssetSiblings: no valid files after revalidation, removing asset",{assetId:i}),await u.Asset.dao.remove({assetId:i,blocklistShas:!1,unlinkAssetFiles:!0}),{assetId:i,filesOrphaned:0,totalFiles:0};const{survivors:b,evicted:w}=v,S=w.length,P=b[0];if(s.info("validateAssetSiblings: revalidation complete",{assetId:i,survivorCount:b.length,orphanedCount:S,primaryUri:P.uri}),await async function(e,t,i){const s=m(),a=e.id,o=await h.AssetMatcher.findMatchingAsset(t,{rejectedAssetIds:new Set([a])});return!(null==o||!(0,l.gt0)(o.asset.id)||(s.info("Dissolving duplicate asset",{assetId:a,matchAssetId:o.asset.id,matchedBy:o.matchedBy,fileCount:i.length}),c.AssetFile.dao.orphan(...i.map(e=>e.id)),await u.Asset.dao.remove({assetId:a,blocklistShas:!1,unlinkAssetFiles:!1}),(0,r.syncReport)().onProgress({from:"validateAssetSiblings",path:t.nativePath,type:"file",state:"note",details:`Asset ${a}: dissolved into asset ${o.asset.id} (matched by ${o.matchedBy}), ${i.length} files orphaned`,url:(0,n.assetPath)(o.asset.id)}),0))}(o,P,b))return S>0&&(0,r.syncReport)().onProgress({from:"validateAssetSiblings",path:P.nativePath,type:"file",state:"note",details:`Asset ${i}: orphaned ${S} non-similar siblings before dissolving`,url:(0,n.assetPath)(i)}),{assetId:i,filesOrphaned:S+b.length,totalFiles:b.length+w.length,dissolved:!0};u.Asset.dao.clearFlag(i,"validateSiblings"),!0!==e.skipFinalizeScheduling&&u.Asset.dao.scheduleFinalizeAsset(i);const M=b.length+w.length;return(0,r.syncReport)().onProgress({from:"validateAssetSiblings",path:P.nativePath,type:"file",state:"note",details:`Asset ${i}: validated ${M} files`,url:(0,n.assetPath)(i),elapsedMs:performance.now()-t,meta:{orphaned:S}}),{assetId:i,filesOrphaned:S,totalFiles:M}};const r=i(74128),s=i(50213),n=i(75761),a=i(22573),o=i(45599),l=i(31586),u=i(43487),c=i(54017),d=i(23254),h=i(61859),f=i(49896),m=(0,o.defer)(()=>(0,s.mkLogger)("sync.ValidateAssetSiblings"));function p(e,t){const i=m(),s=u.Asset.ops().findById(e);if(null==s)return;const n=s.getAssetFiles({refresh:!0});if(0===n.length)return;const o=(0,h.sortBySha)(n);if(0===o.length)return;const d=function(e){const t=new Map,i=[];for(const r of e)if((0,a.notBlank)(r.sha)){const e=t.get(r.sha);null==e?t.set(r.sha,[r]):e.push(r)}else i.push([r]);for(const e of t.values())e.sort((e,t)=>(e.id??0)-(t.id??0));return[...t.values(),...i]}(o),f=d.map(e=>e[0]),p=[f[0]],g=[];for(const s of f.slice(1)){const n=(0,h.whyNotValidSibling)(s,p);i.debug("revalidateAssetSiblings: similarity check",{assetId:e,candidateUri:s.uri,similar:null==n,survivorCount:p.length,reason:n,caller:t}),null==n?p.push(s):((0,r.syncReport)().onProgress({from:t,path:s.nativePath,type:"file",state:"note",details:`Evicting AssetFile:${s.id} from Asset:${e}: non-similar`,meta:{why:n,caller:t}}),g.push(s))}const y=new Set(p.map(e=>e.id)),v=[],b=[];for(const e of d)y.has(e[0].id)?v.push(...e):b.push(...e);const w=b.map(e=>e.id).filter(l.gt0);return w.length>0&&c.AssetFile.dao.orphan(...w),{evicted:b,survivors:v}}},41893(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WhoRoot=t.WhereRoot=t.WhenRoot=t.WhatRoot=t.TypeRoot=t.rootTagDef=t.Roots=t.LensRoot=t.KwRoot=t.FsRoot=t.EventRoot=t.CameraRoot=t.AlbumsRoot=void 0,t.hasTagRoot=h,t.stripTagRoot=function(e){return h(e)?e.slice(1):e};const r=i(36638),s=i(34102),n=i(70905),a=i(42231),o=i(75020),l=i(45599),u=i(41400);var c=i(74607);Object.defineProperty(t,"AlbumsRoot",{enumerable:!0,get:function(){return c.AlbumsRoot}}),Object.defineProperty(t,"CameraRoot",{enumerable:!0,get:function(){return c.CameraRoot}}),Object.defineProperty(t,"EventRoot",{enumerable:!0,get:function(){return c.EventRoot}}),Object.defineProperty(t,"FsRoot",{enumerable:!0,get:function(){return c.FsRoot}}),Object.defineProperty(t,"KwRoot",{enumerable:!0,get:function(){return c.KwRoot}}),Object.defineProperty(t,"LensRoot",{enumerable:!0,get:function(){return c.LensRoot}}),Object.defineProperty(t,"Roots",{enumerable:!0,get:function(){return c.Roots}}),Object.defineProperty(t,"rootTagDef",{enumerable:!0,get:function(){return c.rootTagDef}}),Object.defineProperty(t,"TypeRoot",{enumerable:!0,get:function(){return c.TypeRoot}}),Object.defineProperty(t,"WhatRoot",{enumerable:!0,get:function(){return c.WhatRoot}}),Object.defineProperty(t,"WhenRoot",{enumerable:!0,get:function(){return c.WhenRoot}}),Object.defineProperty(t,"WhereRoot",{enumerable:!0,get:function(){return c.WhereRoot}}),Object.defineProperty(t,"WhoRoot",{enumerable:!0,get:function(){return c.WhoRoot}});const d=(0,l.defer)(()=>new r.CaseInsensitiveSet([...o.TagRoots.values,...n.RootTagAliasConfigs.flatMap(e=>e.setting.values)]));function h(e){return d().has((0,a.tagRefToS)(e[0]))}(0,u.later)(()=>(0,s.ee)().on("clearCache",()=>d.reset()))},7656(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecursiveAssetCountForTagQuery=t.TagAssetCountQuery=void 0,t.updateTagAssetCount=m,t.updateAllTagAssetCounts=async function(e){f().info("Updating all tag asset counts");const t=e.prepare("SELECT count(*) FROM Tag").pluck().get(),i=new o.PushProgressObserver({op:"Updating tag asset counts"},t);try{const r=1e3,s=Math.ceil(t/r);for(let t=0;t<s;t++){const n=t*r;f().debug(`Processing batch ${t+1}/${s} (offset ${n})`);const a=e.prepare(`SELECT id FROM Tag ORDER BY id LIMIT ${r} OFFSET ${n}`).all();for(const t of a)m(e,t.id),await i.incrProgress();await(0,c.delay)(1)}f().info("Tag asset count update completed successfully"),i.completed()}catch(e){throw f().error("Failed to update tag asset counts",e),e}},t.rebuildTagAssetCounts=async function(e){return(0,r.time)({name:"db.rebuildTagAssetCounts",p:async()=>{const t=performance.now();f().info("Starting bulk tag asset count rebuild using TagHierarchy");const i=new o.PushProgressObserver({op:"Rebuilding tag asset counts"},100);try{const r=e.prepare("SELECT COUNT(*) FROM Tag").pluck().get();f().info(`Updating asset counts for ${r} tags`),await i.incrProgress(10);const a=performance.now(),o=e.prepare(p).run({now:Date.now()}),l=performance.now()-a;f().info(`Bulk update completed in ${(0,s.fmtMs)(l)} for ${o.changes} rows`),await i.incrProgress(80),await(0,n.ee)().emit("clearTagCache"),i.completed();const u=performance.now()-t;f().info(`Bulk tag asset count rebuild completed in ${(0,s.fmtMs)(u)}`,{totalTags:r,totalTimeMs:u,perTagMs:r>0?u/r:0,updateTimeMs:l})}catch(e){throw f().error("Failed to rebuild tag asset counts",e),e}}})},t.rebuildNullTagAssetCounts=async function(e){f().info("Starting NULL tag asset count rebuild");const t=e.prepare("SELECT count(*) FROM Tag WHERE assetCount IS NULL").pluck().get(),i=new o.PushProgressObserver({op:"Rebuilding NULL tag asset counts"},t);for(;;){const t=e.prepare("SELECT id FROM Tag WHERE assetCount IS NULL LIMIT 1000").all();if(0===t.length)break;for(const r of t)m(e,r.id),i.incrProgress(),r.id%50==0&&(f().throwIfAborted_(),await(0,c.delay)(1))}i.completed()};const r=i(56038),s=i(76596),n=i(34102),a=i(50213),o=i(38156),l=i(42231),u=i(45599),c=i(41400),d=i(31586),h=i(51926),f=(0,u.defer)(()=>(0,a.mkLogger)("tag.TagAssetCounts"));function m(e,i){if((0,d.gt0)(i))if(f().isDebugEnabled()){const r=e.prepare("SELECT _path FROM Tag WHERE id = ?").pluck().get(i),n=(0,l.splitTagPath)(r),a=performance.now(),o=e.prepare(t.TagAssetCountQuery).pluck().get({tagId:i}),u=performance.now()-a;f().debug(`Count query for tag ${n} completed in ${(0,s.fmtMs)(u)}`,{tagId:i,tagText:n,assetCount:o,queryTime:u});const c=performance.now();e.prepare("UPDATE Tag SET assetCount = ?, updatedAt = ? WHERE id = ?").run(o,Date.now(),i),f().debug(`Tag update completed in ${(0,s.fmtMs)(performance.now()-c)}`)}else{const r=e.prepare(t.TagAssetCountQuery).pluck().get({tagId:i});e.prepare("UPDATE Tag SET assetCount = ?, updatedAt = ? WHERE id = ?").run(r,Date.now(),i)}}t.TagAssetCountQuery=(0,h.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"),t.RecursiveAssetCountForTagQuery=t.TagAssetCountQuery;const p=(0,h.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")},21320(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterRootTags=function(e){const t=new r.CaseInsensitiveSet(s.Settings.hiddenRootTags.valueOrDefault);return e.filter(e=>!t.has(e.name)&&!t.hasAny((e.description??"").split(/\s+/)))};const r=i(36638),s=i(28874)},69032(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.runTagMaintenance=void 0,t.forceRunTagMaintenance=async function(e={forceSync:!0,recountAllTags:!0}){return A().info("forceRunTagMaintenance()"),await t.runTagMaintenance.force(e)},t.vacuumOrphanLeafTags=function(){const e=A().child(".vacuumOrphanLeafTags()");if(!p.Settings.vacuumOrphanTags.valueOrDefault)return e.info("Disabled via vacuumOrphanTags setting"),0;if(!I.TaskList.instance().isIdle())return e.info("Skipping: TaskList is not idle"),0;const t=new s.CaseInsensitiveSet(p.Settings.keepEmptyTags.valueOrDefault),i=new Set;for(const e of t){const t=E.Tag.dao.findByPath([e]);if(null!=t?.id){const e=E.Tag.dbl.pluckAll({sql:"SELECT descendantId FROM TagHierarchy WHERE tagId = ?",bindings:[t.id]});for(const t of e)i.add(t)}}e.info("Starting orphan tag cleanup",{keepRoots:[...t],excludedTagCount:i.size});let n=0;for(let t=1;t<=50;t++){const s=E.Tag.dbl.all({sql:(0,T.compressWhitespace)("SELECT id, _path FROM Tag","WHERE (assetCount = 0 OR assetCount IS NULL)","AND parentId IS NOT NULL","AND NOT EXISTS (SELECT 1 FROM Tag AS child WHERE child.parentId = Tag.id)")}),a=[];for(const t of s){if(i.has(t.id))continue;const r=E.Tag.dbl.pluckFirst({sql:"SELECT COUNT(*) FROM AssetTag WHERE tagId = ?",bindings:[t.id]});0===r?a.push(t.id):e.warn("Skipping tag with stale assetCount",{id:t.id,_path:t._path,assetCount:0,realAssetTagCount:r})}if(0===a.length){n>0?e.info("Orphan tag cleanup complete",{totalDeleted:n,iterations:t}):e.info("No orphan tags found");break}for(const e of(0,r.batches)(a,500))E.Tag.ops().delete(e);e.info("Iteration "+t,{deleted:a.length,totalDeleted:n+a.length}),n+=a.length}return n>0&&(E.Tag.clear(),(0,f.syncReport)().writeSystemData({from:"vacuumOrphanLeafTags",state:"note",details:`Pruned ${n} empty orphan tag(s)`})),n},t.fixFileRootTag=R,t.displayNameForVolsha=L;const r=i(48884),s=i(36638),n=i(19851),a=i(50213),o=i(7282),l=i(409),u=i(3685),c=i(99331),d=i(5916),h=i(34102),f=i(74128),m=i(69589),p=i(28874),g=i(42231),y=i(63870),v=i(22573),b=i(42659),w=i(41400),S=i(6875),P=i(31586),M=i(34666),T=i(51926),_=i(75020),E=i(48723),k=i(73716),D=i(72965),I=i(71278),C=i(7656),A=(0,n.lazy)(()=>(0,a.mkLogger)("tag.TagSql")),x=((0,o.isTest)()?5:30)*b.secondMs;t.runTagMaintenance=(0,l.rateLimited)({name:"runTagMaintenance",minCallDelayMs:x,f:async e=>{const i=(0,m.forceContextOrSetting)(e),r=A().child(".runTagMaintenance()");if(i.halt?.aborted||(0,c.ending)())return void r.info("ending(): no-op");const s=performance.now();r.info("starting",{ctx:i});try{if(r.info("validating all tags..."),E.Tag.dao.validate_(),r.throwIfAborted_(i?.halt),i.forceSync||i.recountAllTags)r.info("Rebuilding entire TagHierarchy closure table...",{ctx:i}),k.TagHierarchy.rebuild();else{const e=k.TagHierarchy.repairIfNeeded();"none"!==e.action&&r.info("TagHierarchy repaired",e)}r.throwIfAborted_(i?.halt),await F(),i.recountAllTags?(r.info("rebuilding optimized hierarchical tag asset counts..."),await(0,C.rebuildTagAssetCounts)(E.Tag.dbl.db().db)):await(0,C.rebuildNullTagAssetCounts)(E.Tag.dbl.db().db)}catch(e){const t=String(e?.message??e);if(!t.includes("Cannot read")||!t.includes("undefined"))throw e;A().warn("runTagMaintenance() failed (test-teardown race)",e)}const n=(0,u.roundMs)(performance.now()-s),a=(0,P.clamp)(x,15*b.minuteMs,20*n);t.runTagMaintenance.setMinCallDelayMs(a),A().info("runTagMaintenance(): complete.",{newMinCallDelayMs:a,elapsedMs:n})}});const F=(0,d.lazyAsync)({desc:"updateTagMountpoints",later:async()=>{A().info("updating tag mountpoints...");const e=E.Tag.dao.findByPath([_.TagRoots.fs]);if(null!=e){e.maybeUpsertDisplayName(p.Settings.tagDisplayNameFS.valueOrDefault);for(const t of e.getChildren())R(t)}else(0,a.mkLogger)("updateTagMountpoints()").info("No root filesystem tag (new db, I hope?)")}});function O(){F.clear(),t.runTagMaintenance.clear()}function R(e){if(null==e||2!==e.depth||!e._path.startsWith(_.TagRoots.fs+g.TagSep))return;const t=(0,a.mkLogger)("fixFileRootTag("+e+")");if(e.name===_.LibraryTagName)return void(1!==e.ordinal&&(t.info("fixing library ordinal",{id:e.id,path:e.path}),e.upsert({ordinal:1}),E.Tag.clear()));if(!(0,m.forceContextOrSetting)().forceSync&&(0,v.notBlank)(e.displayName)&&(0,M.gt)(e.updatedAt,Date.now()-(0,y.volumeMetadataTtlMs)()))return void t.info("no-op: tag recently updated",{id:e.id,path:e.path,updated:(0,S.fmtDuration)(Date.now()-e.updatedAt)+" ago"});const i=L(e.name);null!=i?(e.maybeUpsertDisplayName(i),t.info("updated tag",{id:e.id,path:e.path,displayName:i}),E.Tag.clear()):t.debug("cannot update tag: no Volume row for this volsha.",{id:e.id,path:e.path})}function L(e){return D.Volume.findByVolsha(e)?.displayName()}(0,w.later)(()=>{(0,h.ee)().on("clearCache",O),p.Settings.libraryDir.watchLater(O)})},94761(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addLocalTask=d,t.addLocalTasks=function(e,...t){for(const i of t)d(e,i)},t.addTask=async function(e,t){return!(0,n.isSyncService)()&&await h()?o.SyncRpcClient.instance().enqueueTask({method:e,args:t}):(c().warn("addTask(): no syncClient or isSyncService: running locally",{fn:e,args:t}),d(e,t))};const r=i(19851),s=i(50213),n=i(23560),a=i(45599),o=i(72914),l=i(23254),u=i(71278),c=(0,a.defer)(()=>(0,s.mkLogger)("library.task"));function d(e,t){const i=l.Task.for(e,t);return u.TaskList.instance().add(i),i}const h=(0,r.lazy)(async()=>{try{const e=o.SyncRpcClient.instance();return await e.isPaused(),e.isHealthy()}catch{return!1}},1e3)},7722(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AssetFileClusters=void 0;const r=i(48884),s=i(79781),n=i(78406),a=i(65594),o=i(28874),l=i(42659),u=i(30301),c=i(43487),d=i(54017),h=i(39656);class f extends n.EndableInterval{static instance=(0,u.lazy)(()=>new f);clusters=new a.Clusters(s.isSimilarMedia);#nn=0;#an=0;get stats(){return{addCount:this.#nn,totalAddMs:this.#an,avgAddMs:this.#nn>0?this.#an/this.#nn:0,clusterCount:this.clusters.clusterCount,itemCount:this.clusters.itemCount}}constructor(){super({name:"AssetFileClusters.vacuum",callback:()=>this.vacuum(),intervalMs:l.minuteMs})}add(e){const t=performance.now(),i=this.clusters.add(e);return this.#nn++,this.#an+=performance.now()-t,i}getClusterIdByAssetFileId(e){const t=this.clusters.getClusterIdByPredicate(t=>t.id===e);if(null!=t)return t;const i=d.AssetFile.ops().findById(e);return null!=i?this.add(i):void 0}vacuum(){const e=[...this.clusters.items()];if(0===e.length)return;const t=Date.now()-l.minuteMs,i=h.AssetFlags.toBit("finalize"),s=new Set,n=e.map(e=>e.id);for(const e of(0,r.batches)(n,o.Settings.dbBatchSelectSize.valueOrDefault)){const r=c.Asset.dbl.pluckAllf(r=>r.select("AssetFile.id").from("AssetFile").join("Asset","Asset.id","AssetFile.assetId").whereIn("AssetFile.id",e).andWhere("Asset.shown",1).andWhere("Asset.updatedAt","<=",t).andWhereRaw("COALESCE(Asset.flags, 0) & ? = 0",[i]));for(const e of r)s.add(e)}for(const e of this.clusters.items())s.has(e.id)&&this.clusters.remove(e)}}t.AssetFileClusters=f},95577(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseTaskProducer=void 0;const r=i(25764),s=i(38836),n=i(31562),a=i(40958),o=i(94448),l=i(71278);class u extends s.EndableWrapper{defaultTaskName;taskList;#z;#on=new Set;get state(){return this.ended?"completed":this.#z}constructor(e,t,i=r.EndableRanks.first,s=l.TaskList.instance(),n="active"){super(e,()=>this.#Es(),i),this.defaultTaskName=t,this.taskList=s,this.#z=n}#Es(){this.#z="completed"}runnable(){return(0,o.modelDb)()?.isOpen??!1}async awaitIdle(e){if(!await(0,n.untilTrue)(()=>this.isIdle(),{intervalMs:500,timeoutMs:e})&&null!=e)throw new Error(`${this.name}.awaitIdle() timed out after ${e}ms (inFlightCount: ${this.#on.size})`)}async isIdle(){return!1===this.runnable()||("idle"===this.#z||this.ended?0===this.#on.size:0===this.#on.size&&0===(await this.queryIds(1,new Set)).length)}resetForTest(e="idle"){this.#on.clear(),this.#z=e}async produceTasks(e){if(e<=0||this.ended||"active"!==this.#z||!this.runnable())return[];const t=await this.queryIds(e,this.#on);if(0===t.length)return this.#z="idle",[];for(const e of t)this.#on.add(e);this.logger.info("Producing tasks",{count:t.length,inFlightTotal:this.#on.size});const i=[];for(const e of(0,a.uniq)(t))try{const t=await this.mkTask(e);t._producerId=e,t._producerName=this.name,i.push(t)}catch(t){this.#on.delete(e),this.logger.warn("mkTask failed",{id:e,error:t})}return i}async notifyWorkAvailable(){this.#z="active",this.taskList.pullFromProducers()}get inFlightCount(){return this.#on.size}onTaskComplete(e){this.#on.delete(e)}}t.BaseTaskProducer=u},64702(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FFMPEG_SOLO_LOCK=t.GLOBAL_ASSET_LOCK=void 0,t.pathLock=d,t.assetFileLocks=h,t.adoptAssetFileLocks=function(e){const t=(0,a.toGt0)(e?.assetFileId);return h(l.AssetFile.ops().findById(t))},t.assetIdLock=f,t.assetLockNames=function(e){return m(e).locks},t.finalizeAssetLocks=function(e){const{locks:i,asset:s}=m(e);return null!=s&&0===r.Settings.ffmpegThreads.valueOrDefault&&s.isVideo()&&i.push(t.FFMPEG_SOLO_LOCK),i},t.getPathLocks=function(e){if("path"in e&&!(0,n.blank)(e.path))return d(e.path);const t=e instanceof l.AssetFile?e:(0,u.getAssetFile_)(e);return d(t?.nativePath)};const r=i(28874),s=i(40958),n=i(22573),a=i(31586),o=i(43487),l=i(54017),u=i(93755),c=i(7722);function d(e){return(0,n.blank)(e)?[]:["path:"+e]}function h(e){if(null==e)return[];const t=[...d(e.nativePath)];if((0,a.gt0)(e.id)){t.push("assetFileId:"+e.id);const i=c.AssetFileClusters.instance().getClusterIdByAssetFileId(e.id);null!=i&&t.push(`clusterId:${i}`)}return(0,s.uniq)(t)}function f(e){return(0,a.gt0)(e)?["assetId:"+e]:[]}function m(e){const t=o.Asset.ops().findById(e.assetId),i=f(e.assetId);if(null==t)return{locks:i};for(const e of t.getAssetFiles())i.push(...h(e));return{locks:(0,s.uniq)(i),asset:t}}t.GLOBAL_ASSET_LOCK=["asset"],t.FFMPEG_SOLO_LOCK="ffmpeg-solo"},33978(e,t,i){"use strict";e=i.nmd(e),Object.defineProperty(t,"__esModule",{value:!0}),t.ProblematicPath=void 0,t.isStrike=b,t.isProblematicPathEntry=w;const r=i(76760),s=i(85296),n=i(20603),a=i(34102),o=i(19851),l=i(50213),u=i(19913),c=i(28874),d=i(2858),h=i(22573),f=i(45599),m=i(98553),p=i(31586),g=i(51926),y=(0,f.defer)(()=>(0,l.mkLogger)("task.ProblematicPath")),v="problematic-files";function b(e){return"object"==typeof e&&null!=e&&"timestamp"in e&&(0,p.isNumber)(e.timestamp)&&"reason"in e&&(0,g.isString)(e.reason)}function w(e){return"object"==typeof e&&null!=e&&"path"in e&&(0,g.isString)(e.path)&&"strikes"in e&&Array.isArray(e.strikes)&&e.strikes.every(b)}class S{static#ln=(0,n.lazyLibraryStoreFile)(v);static#un=(0,o.lazy)(()=>this.#cn());static#dn=(0,o.lazy)(()=>{const e=this.#un(),t=new Map;for(const i of e.entries)t.set(i.path,i);return t});static#hn=(0,s.trailingThrottle)({fn:()=>this.#fn(),minDelayMs:2e3});static{(0,a.ee)().on("clearCache",()=>{this.clearCache()})}static clearCache(){this.#hn.reset(),this.#un.unset(),this.#dn.unset(),this.#ln.unset()}static#cn(){const e={entries:[],file:void 0},t=this.#ln.priorSync()??void 0;if(e.file=t,null==t)return e;try{const i=t.readFileSync("debug");if(null==i)return e;const r=(0,m.parseJSON)(i);if(Array.isArray(r)){const t=r.filter(w);e.entries=this.#mn(t),y().debug("Loaded problematic paths",{count:e.entries.length,pruned:t.length-e.entries.length})}else y().warn("Invalid problematic-files JSON format, starting fresh")}catch(e){y().debug("Could not load problematic-files JSON",{error:e})}return e}static async#pn(){const e=await this.#ln();if(null!=e){const t=this.#un();t.file=e,this.#gn(t)}}static#gn(e){const t=e.file;if(null!=t)try{const i=t.readFileSync("debug");if((0,h.blank)(i))return;const r=(0,m.parseJSON_)(i);if(Array.isArray(r)){const t=r.filter(w);e.entries=this.#mn(t),y().debug("Reloaded problematic paths",{count:e.entries.length,pruned:t.length-e.entries.length})}else y().warn("Invalid problematic-files JSON format during reload");this.#dn.unset()}catch(e){y().debug("Could not reload problematic-files JSON",{error:e})}}static#fn(){const e=this.#un(),t=e.file??this.#ln.priorSync()??void 0;if(null!=t)try{const i=(0,n.systemStoreDir)(v);null==i||i.existsSync()||i.mkdirpSync_(),t.writeJsonSync_(e.entries),y().debug("Saved problematic paths",{count:e.entries.length})}catch(e){y().warn("Failed to save problematic-files JSON",{nativePath:t.nativePath,error:e})}else y().warn("#save: config file not available, not persisting")}static#mn(e){const t=c.Settings.problematicDecayMs.valueOrDefault;if(0===t)return e;const i=Date.now()-t;return e.filter(e=>e.strikes.some(e=>e.timestamp>=i))}static#yn(e){const t=c.Settings.problematicDecayMs.valueOrDefault;if(0===t)return e.strikes;const i=Date.now()-t;return e.strikes.filter(e=>e.timestamp>=i)}static#vn(e){const t=this.#yn(e);return 0===t.length?0:Math.max(...t.map(e=>e.timestamp))+c.Settings.problematicCooldownMs.valueOrDefault*t.length}static add(e,t){if((0,h.blank)(e))return;const i=this.#un(),r={timestamp:Date.now(),reason:t};let s=i.entries.find(t=>t.path===e);if(null!=s){s.strikes.push(r);const i=this.#yn(s).length;y().info("Adding strike to problematic path",{path:e,reason:t,strikeCount:i})}else s={path:e,strikes:[r]},i.entries.push(s),y().info("Adding new problematic path",{path:e,reason:t});return this.#dn.priorSync()?.set(e,s),this.#hn(),s}static isProblematic(e){if((0,h.blank)(e))return!1;const t=this.#dn().get(e);if(null==t)return!1;const i=this.#yn(t);if(0===i.length)return y().tap({msg:"isProblematic: all strikes decayed",result:!1,meta:{path:e,totalStrikes:t.strikes.length}});const r=c.Settings.problematicMaxStrikes.valueOrDefault;if(r>0&&i.length>=r)return y().tap({msg:"isProblematic: too many active strikes",result:!0,meta:{path:e,activeStrikes:i.length,maxStrikes:r}});const s=this.#vn(t),n=Date.now(),a=n<s;return y().tap({msg:"isProblematic",result:a,meta:{path:e,activeStrikes:i.length,inCooldown:a,cooldownEndsIn:a?s-n:0}})}static getStrikeCount(e){if((0,h.blank)(e))return 0;const t=this.#dn().get(e);return null==t?0:this.#yn(t).length}static getAllStrikes(e){if((0,h.blank)(e))return[];const t=this.#dn().get(e);return t?.strikes??[]}static getLastStrike(e){const t=this.getAllStrikes(e);return t.length>0?t[t.length-1]:void 0}static cleanup(){if(0===c.Settings.problematicDecayMs.valueOrDefault)return 0;const e=this.#un(),t=e.entries.length,i=[];e.entries=e.entries.filter(e=>this.#yn(e).length>0||(i.push(e.path),!1));const r=t-e.entries.length;if(r>0){y().info("Cleaned up fully-decayed problematic paths",{deleted:r});const e=this.#dn.priorSync();if(null!=e)for(const t of i)e.delete(t);this.#fn()}return r}static removePath(e){if((0,h.blank)(e))return!1;const t=this.#un(),i=t.entries.findIndex(t=>t.path===e);return!(i<0||(t.entries.splice(i,1),y().info("Removed problematic path",{path:e}),this.#dn.priorSync()?.delete(e),this.#fn(),0))}static getAll(e){const t=this.#un().entries.filter(e=>this.#yn(e).length>0).sort((e,t)=>{const i=e.strikes[e.strikes.length-1]?.timestamp??0;return(t.strikes[t.strikes.length-1]?.timestamp??0)-i});return null!=e?t.slice(0,e):t}static count(){return this.#un().entries.filter(e=>this.#yn(e).length>0).length}static clear(){this.#un().entries=[],this.#dn.priorSync()?.clear(),y().info("Cleared all problematic paths"),this.#fn()}static async reload(){await this.#pn()}static flush(){this.#hn.reset(),this.#fn()}static addStrikeAt(e,t,i){if((0,h.blank)(e))return;const r=this.#un(),s={timestamp:i,reason:t};let n=r.entries.find(t=>t.path===e);return null!=n?n.strikes.push(s):(n={path:e,strikes:[s]},r.entries.push(n)),this.#dn.priorSync()?.set(e,n),this.#hn(),n}}t.ProblematicPath=S,i.c[i.s]===e&&async function(){(0,u.setServiceName)("tool"),await(0,d.readSystemSettings)(),await S.reload();for(const e of process.argv.slice(2)){const t=(0,r.resolve)(e);S.add(t,"Manual test strike")}S.flush(),console.log("Added strikes for",process.argv.slice(2).length,"path(s)")}()},39469(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StallWatcher=void 0,t.getPathForAssetTask=v;const r=i(78406),s=i(25764),n=i(56038),a=i(74128),o=i(50213),l=i(28874),u=i(75761),c=i(42659),d=i(45599),h=i(31586),f=i(43487),m=i(33978),p=i(23254),g=(0,d.defer)(()=>(0,o.mkLogger)("task.StallWatcher"));class y extends r.EndableInterval{getRunningTasks;#bn=new Set;constructor(e,t=c.minuteMs){super({name:"task.StallWatcher",intervalMs:t,rank:s.EndableRanks.service,unref:!0,callback:()=>this.check()}),this.getRunningTasks=e,g().debug("StallWatcher initialized",{checkIntervalMs:t})}check(){const e=this.getRunningTasks(),t=new Set(e.map(e=>e.d.id));for(const e of this.#bn)t.has(e)||this.#bn.delete(e);for(const t of e)this.#wn(t)}#wn(e){if(this.#bn.has(e.d.id))return;const t=e.d.timerName,i=e.d.elapsedMs,r=e.fileSize;if(null!=r&&n.PromiseTimer.instance().totalDurationEstimatorSampleCount<100)return;const s=n.PromiseTimer.instance(),o=s.estimate(t,r,"p50"),d=s.estimate(t,r,"p99"),h=l.Settings.stallWarningFloorMs.valueOrDefault;if(i<=(null!=d?Math.max(d,h):h))return;const f=this.#Sn(e);if(null==f)return void g().debug("StallWatcher: no path for task",{method:e.method,timerName:t,elapsedMs:i});const m=null==d||h>d;let y=`Stalled: ${(0,c.fmtElapsedMs)(i)} elapsed`;null!=o?(y+=` (expected ~${(0,c.fmtElapsedMs)(o)}`,y+=m?`, min warning: ${(0,c.fmtElapsedMs)(h)})`:null!=d?`, p99: ${(0,c.fmtElapsedMs)(d)})`:")"):m&&(y+=` (min warning: ${(0,c.fmtElapsedMs)(h)})`),g().warn("Task stalled",{method:e.method,timerName:t,elapsedMs:i,p50Ms:o,p99Ms:d,floorMs:h,path:f});const v=(0,p.getTaskAssetId)(e.args);(0,a.syncReport)().onProgress({path:f,from:e.method,state:a.SyncFileStates.stalled,details:y,elapsedMs:i,meta:{p50Ms:o,p99Ms:d,floorMs:m?h:void 0,fileSize:r},url:(0,u.assetPath)(v)}),this.#bn.add(e.d.id)}#Sn(e){const t=e.args;if(null!=t&&"object"==typeof t){if("path"in t)return t.path;if("assetId"in t)return v(e)}}get problematicCount(){return m.ProblematicPath.count()}get warnedCount(){return this.#bn.size}clearTracking(){this.#bn.clear()}clearProblematic(){m.ProblematicPath.clear()}}function v(e){const t=e.args;if((0,h.gt0)(t?.assetId))try{const e=f.Asset.ops().findById(t.assetId);return e?.getPrimary()?.nativePath}catch{return}}t.StallWatcher=y},23254(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Task=void 0,t.getTaskAbortable=function(e){if(null!=e&&"object"==typeof e&&"_abortable"in e)return e._abortable},t.getTaskReportProgress=function(e){if(null!=e&&"object"==typeof e&&"_reportProgress"in e)return e._reportProgress},t.getTaskPath=v,t.getTaskAssetId=b;const r=i(76740),s=i(22911),n=i(99331),a=i(56038),o=i(98314),l=i(74128),u=i(7282),c=i(40958),d=i(75761),h=i(22573),f=i(50357),m=i(98553),p=i(94448),g=i(33978),y=i(14645);function v(e){if(null!=e&&"object"==typeof e&&"path"in e)return e.path}function b(e){if(null!=e&&"object"==typeof e&&"assetId"in e)return e.assetId}class w{method;args;d;lockNames;producerName;producerId;fileSize;abortable=new r.Abortable;liveProgress;onProgressChanged;static for(e,t){const i=y.TaskImpls[e].lockNamesFn(t);return new w(e,t,i)}static fromJson(e){const t=y.TaskImpls[e.method].lockNamesFn(e.args);return new w(e.method,e.args,t,e._producerName,e._producerId)}constructor(e,t,i,r,n){this.method=e,this.args=t,this.lockNames=(0,c.uniq)(i),this.producerName=r,this.producerId=n;const o=y.TaskImpls[e],l="task."+(o.timerNameFn?.(t)??e);this.fileSize=o.fileSizeFn?.(t),this.d=new s.Deferred(e,{serialIds:i,payload:this,timer:a.PromiseTimer.instance(),timerName:l,fileSize:this.fileSize})}async run(){if(!(0,u.isTest)()||!(0,n.ending)()&&null!=(0,p.modelDb)())try{const e=e=>{const t=!(0,f.eql)(e,this.liveProgress);this.liveProgress=e,t&&this.onProgressChanged?.()},t=null!=this.args&&"object"==typeof this.args?{...this.args,_abortable:this.abortable,_reportProgress:e}:this.args;return await y.Tasks[this.method](t)}catch(e){const t=v(this.args);if(!(0,h.blank)(t)){const i=(0,l.errorToState)(e);i===l.SyncFileStates.timeout&&g.ProblematicPath.add(t,`Timed out after ${this.d.elapsedMs}ms`);const r=b(this.args);(0,l.syncReport)().onProgress({path:t,from:this.method,state:i,elapsedMs:this.d.elapsedMs,details:(0,o.errorToS)(e),url:(0,d.assetPath)(r)})}throw e}}toString(){return this.d.name+`(${(0,m.stringify)(this.args)}): ${this.d.state}`}toJSON(){return{method:this.method,args:this.args}}}t.Task=w},71278(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskList=void 0;const r=i(48884),s=i(19851),n=i(50213),a=i(7282),o=i(3685),l=i(88264),u=i(78406),c=i(25764),d=i(45608),h=i(42638),f=i(85970),m=i(73614),p=i(59958),g=i(70025),y=i(34102),v=i(61848),b=i(28874),w=i(15674),S=i(40958),P=i(42659),M=i(41400),T=i(31586),_=i(85556),E=i(33978),k=i(39469),D=i(23254),I=(0,s.lazy)(()=>(0,a.isTest)()?(0,T.toGt0)(process.env[p.PS_BAIL_AFTER_TASK_COUNT]):void 0);class C extends u.EndableInterval{#Pn=0;#Mn=0;static instance=(0,s.lazy)(()=>new C);#$=(0,n.mkLogger)("task.TaskList");ee=new v.TypedEventEmitterImpl;#Tn;p;recentlyProcessed=new l.TTLArray(P.minuteMs);#_n=new Set;#En=new Map;static get ee(){return this.instance().ee}constructor(){super({name:"task.TaskList",intervalMs:((0,a.isTest)()?1:60)*P.secondMs,rank:c.EndableRanks.first,callback:()=>this.pullFromProducers()}),this.p=h.Promises.for({name:"TaskList()",maxConcurrency:w.maxConcurrentImports,sortByDesc:e=>[e.id]}),this.p.ee.on("lowWaterMark",()=>{this.pullFromProducers()}),this.p.ee.on("drain",()=>{this.pullFromProducers(),(0,m.setUnrefTimeout)(()=>{this.#kn()},2*P.secondMs)}),(0,y.ee)().on("notifyWorkAvailable",e=>{this.#Dn();const t=this.#En.get(e);null!=t?.notifyWorkAvailable&&t.notifyWorkAvailable()}),this.#Tn=new k.StallWatcher(()=>this.currentTasks())}get timeoutCount(){return this.#Mn}nuke(){this.recentlyProcessed.clear(),this.#Pn=0,this.#Mn=0,this.#En.clear(),this.#_n.clear(),this.#Tn.clearTracking(),this.p.nuke()}registerProducer(e){this.#_n.has(e)||(this.#_n.add(e),null!=e.defaultTaskName&&this.#En.set(e.defaultTaskName,e),this.#$.info("Registered producer",{name:e.name,state:e.state,producerCount:this.#_n.size}),this.pullFromProducers())}unregisterProducer(e){this.#_n.delete(e)&&(null!=e.defaultTaskName&&this.#En.delete(e.defaultTaskName),this.#$.info("Unregistered producer",{name:e.name,producerCount:this.#_n.size}))}#In(e){return this.#_n.has(e)?e.ended?(this.#_n.delete(e),void this.#$.info("producerIfActive():Auto-unregistered ended producer",{name:e.name})):"completed"===e.state?(this.#_n.delete(e),void this.#$.info("producerIfActive(): Auto-unregistered completed producer",{name:e.name})):"active"===e.state?e:void 0:void this.#$.warn("producerIfActive(): producer not registered",{name:e.name})}pullFromProducers=(0,f.serialized)(async()=>{if(0===this.#_n.size)return;const e=this.capacity();if(e<=0)return;if(this.p.size>this.p.lowWaterMark)return void this.#$.debug("pullFromProducers(): no-op: running above low water mark",{queueSize:this.p.size,lowWaterMark:this.p.lowWaterMark});const t=(0,S.count)(this.#_n,e=>null!=this.#In(e));if(0===t)return void this.#$.trace("No active producers, waiting for notifications");const i=Math.max(1,Math.floor(e/t)),s=[];for(const e of this.#_n)if(null!=this.#In(e)){if(this.ended)return;try{const t=await e.produceTasks(i);t.length>0&&(this.#$.debug("Pulled tasks from producer",{producer:e.name,state:e.state,requested:i,produced:t.length}),s.push(t))}catch(t){this.#$.warn("Producer failed to produce tasks",{producer:e.name,error:t})}}const n=(0,S.compact)((0,r.flatZip)(...s)).map(e=>D.Task.fromJson(e));return this.add(...n),n});addJsonTasks(...e){this.add(...e.map(e=>D.Task.fromJson(e)))}add(...e){e.length>0&&this.#Dn();for(const t of e){const e=(0,D.getTaskPath)(t.args);if(null!=e&&E.ProblematicPath.isProblematic(e)){this.#$.warn("Skipping problematic task",{task:t,path:e}),t.d.reject(new Error("File is problematic (timed out recently)"));continue}const i=b.Settings.taskMaxDurationMs.valueOrDefault;i>0&&(t.d.setTimeout(i),t.onProgressChanged=()=>t.d.setTimeout(i)),t.d.promise.then(e=>{this.#Pn++,this.recentlyProcessed.push(t);const i={task:t,result:e,elapsedMs:(0,o.roundMs)(t.d.elapsedMs)};this.#$.info("Completed task",i),(0,T.gt)(this.#Pn,I())&&(0,d.exit)({reason:p.PS_BAIL_AFTER_TASK_COUNT}),this.ee.emitSync("resolved",i)},e=>{if(e instanceof _.TimeoutError){this.#Mn++,t.abortable.abort("Task timed out after "+(0,o.roundMs)(t.d.elapsedMs)+"ms"),this.#$.warn("Task timed out",{task:t,timeoutCount:this.#Mn,elapsedMs:(0,o.roundMs)(t.d.elapsedMs)});const e=b.Settings.syncMaxTimeoutsBeforeRestart.valueOrDefault;e>0&&this.#Mn>=e&&!(0,a.isTest)()&&(this.#$.warn("Proactive restart: syncMaxTimeoutsBeforeRestart exceeded",{timeoutCount:this.#Mn,maxTimeouts:e}),(0,d.exit)({reason:`proactive restart: ${this.#Mn} task timeouts (max ${e})`,status:0}))}const i=!0===(0,g.isIgnorableError)(e)||(0,g.isCorruptMediaError)(e);this.#$.log(i?"info":"warn","Rejected task",{task:t,error:e}),this.ee.emitSync("rejected",{task:t,error:e})}).finally(()=>{try{if(null!=t.producerName&&null!=t.producerId){const e=[...this.#_n].find(e=>e.name===t.producerName);e?.onTaskComplete?.(t.producerId)}}catch(e){this.#$.warn("onTaskComplete failed",{task:t,error:e})}(0,y.ee)().emitSyncRateLimited("syncStateChanged")}),this.p.enqueueDeferred(t.d,()=>t.run())}e.length>0&&(0,y.ee)().emitThrottled("syncStateChanged")}async#kn(){this.isIdle()&&await this.#Cn()&&this.hasTimer()&&(this.#$.debug("Idling down: pausing TaskList and StallWatcher intervals"),this.pauseInterval(),this.#Tn.pauseInterval())}#Dn(){this.hasTimer()||(this.#$.debug("Resuming TaskList and StallWatcher intervals"),this.resumeInterval(),this.#Tn.resumeInterval())}async#Cn(){for(const e of this.#_n)if(!await e.isIdle())return!1;return!0}async awaitQuiescent(){let e=0;for(;!this.ended;){await this.p.awaitDrain();for(const e of this.#_n)e.notifyWorkAvailable?.();const t=await this.pullFromProducers(),i=await this.#Cn();if((0,S.isEmpty)(t)&&this.p.isIdle()&&i){if(e++,this.#$.debug("awaitQuiescent: idle observation",{idleCounter:e,requiredIdleCount:2}),e>=2)return}else e=0;await(0,M.delay)(500)}}async awaitLowWaterMark(){return this.p.size<=this.p.lowWaterMark?void 0:this.p.ee.waitOnce("lowWaterMark")}taskCount(){return this.p.unsettledCount()}isIdle(){return this.p.isIdle()}pendingWorkCount(){return this.p.notStartedCount()}blockedPendingWorkCount(){const e=this.p.runningSerialIds;return(0,S.count)(this.p.deferreds,t=>t.serialIds.some(t=>e.has(t)))}capacity(e){return this.p.enqueueCapacity(e)}hasCapacity(e){return this.capacity(e)>0}currentTasks(){return this.p.runningJobs.map(e=>e.d.payload)}unsettledTasksFor(e){return this.p.deferreds.filter(t=>t.payload?.producerName===e.name).map(e=>e.payload)}state(){return{...this.p.stats(),runningJobDetails:this.#An(),isIdle:this.isIdle(),capacity:this.capacity(),taskCount:this.taskCount(),recentlyProcessedLast10:this.recentlyProcessed.slice(-10).map(e=>e.toString())}}#An(){return this.p.runningJobs.map(e=>{const t=e.d.payload;return{name:e.d.name,startedAt:e.d.startedAt,elapsedMs:e.d.elapsedMs,path:null!=t?(0,D.getTaskPath)(t.args):void 0,liveProgress:t?.liveProgress}})}}t.TaskList=C},14645(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TaskImpls=t.TaskNames=t.Tasks=void 0,t.getFileTimerName=b,t.getFileSize=w;const r=i(73024),s=i(76760),n=i(14036),a=i(40958),o=i(68708),l=i(50989),u=i(43487),c=i(58723),d=i(34274),h=i(93755),f=i(19433),m=i(15399),p=i(30914),g=i(86368),y=i(64702),v=i(31478);function b(e,t){const i=(0,s.extname)(t).slice(1).toLowerCase();return`${e}:${(0,n.getMediaCategory)(i)??"unknown"}`}function w(e){try{return(0,r.statSync)(e).size}catch{return}}function S(e){try{const t=u.Asset.ops().findById(e);if(null==t)return;const i=t.getAssetFiles(),r=t.getPrimary();return(0,a.uniqBy)([r,...i],e=>e.id)}catch{return}}function P(e,t){try{const i=S(t);if(null!=i)for(const t of i){const i=t.nativePath;if(null!=i)return b(e,i)}}catch{}return e}function M(e){try{const t=S(e);if(null==t)return;for(const e of t){const t=e.nativePath;if(null!=t){const e=w(t);if(null!=e)return e}}}catch{}}function T(e){try{return null!=e.path?e.path:(0,h.getAssetFile_)(e).nativePath}catch{return}}t.Tasks={adoptAssetFile:f.adoptAssetFile,applyDeleted:c.applyDeleted,applyExcluded:c.applyExcluded,repairAsset:p.repairAsset,updateAssetFile:h.updateAssetFile_,finalizeAsset:m.finalizeAsset,syncFile:d.importFileToResult_,testTask:v.testTask,validateAssetSiblings:g.validateAssetSiblings},t.TaskNames=(0,l.strEnum)(...(0,o.keys)(t.Tasks)),t.TaskImpls={adoptAssetFile:{fn:f.adoptAssetFile,lockNamesFn:y.adoptAssetFileLocks},applyDeleted:{fn:c.applyDeleted,lockNamesFn:()=>y.GLOBAL_ASSET_LOCK},applyExcluded:{fn:c.applyExcluded,lockNamesFn:()=>y.GLOBAL_ASSET_LOCK},repairAsset:{fn:p.repairAsset,lockNamesFn:y.assetLockNames,timerNameFn:e=>P("repairAsset",e.assetId),fileSizeFn:e=>M(e.assetId)},updateAssetFile:{fn:h.updateAssetFile_,lockNamesFn:y.getPathLocks,timerNameFn:e=>function(e,t){const i=T(t);return null!=i?b(e,i):e}("updateAssetFile",e),fileSizeFn:e=>function(e){const t=T(e);return null!=t?w(t):void 0}(e)},finalizeAsset:{fn:m.finalizeAsset,lockNamesFn:y.finalizeAssetLocks,timerNameFn:e=>P("finalizeAsset",e.assetId),fileSizeFn:e=>M(e.assetId)},syncFile:{fn:d.importFileToResult_,lockNamesFn:y.getPathLocks,timerNameFn:e=>b("syncFile",e.path),fileSizeFn:e=>w(e.path)},testTask:{fn:v.testTask,lockNamesFn:e=>["test"+e]},validateAssetSiblings:{fn:g.validateAssetSiblings,lockNamesFn:y.assetLockNames,timerNameFn:e=>P("validateAssetSiblings",e.assetId),fileSizeFn:e=>M(e.assetId)}}},31478(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.testTask=void 0;const r=i(79136),s=i(65211);t.testTask=(0,r.shim)({name:"testTask",impl:async e=>({id:(0,s.uid)(),arg:e,ts:Date.now()})})},44076(e,t){"use strict";let i;Object.defineProperty(t,"__esModule",{value:!0}),t.setServiceError=function(e){i=e},t.getServiceError=function(){return i},t.clearServiceError=function(){i=void 0}},90858(e){"use strict";e.exports=require("@iarna/toml")},16242(e){"use strict";e.exports=require("@parcel/watcher")},29365(e){"use strict";e.exports=require("@photostructure/fs-metadata")},61177(e){"use strict";e.exports=require("@photostructure/knex-sqlite")},86558(e){"use strict";e.exports=require("@photostructure/sqlite")},9227(e){"use strict";e.exports=require("@photostructure/sqlite-seeded-random")},29693(e){"use strict";e.exports=require("@photostructure/sqlite-vec")},53705(e){"use strict";e.exports=require("@photostructure/tz-lookup")},77773(e){"use strict";e.exports=require("@photostructure/windows-registry")},64770(e){"use strict";e.exports=require("assert")},58587(e){"use strict";e.exports=require("batch-cluster")},41991(e){"use strict";e.exports=require("batch-cluster/dist/BatchClusterOptions")},6858(e){"use strict";e.exports=require("commander")},36507(e){"use strict";e.exports=require("croner")},77988(e){"use strict";e.exports=require("exiftool-vendored")},85721(e){"use strict";e.exports=require("exiftool-vendored/data/TagMetadata.json")},65793(e){"use strict";e.exports=require("exiftool-vendored/dist/GeolocationTags")},66150(e){"use strict";e.exports=require("fast-xml-parser")},68817(e){"use strict";e.exports=require("file-type")},28787(e){"use strict";e.exports=require("he")},31832(e){"use strict";e.exports=require("knex")},51168(e){"use strict";e.exports=require("luxon")},83058(e){"use strict";e.exports=require("picomatch")},57160(e){"use strict";e.exports=require("punycode.js")},38064(e){"use strict";e.exports=require("semver")},9288(e){"use strict";e.exports=require("sharp")},92460(e){"use strict";e.exports=require("util")},75162(e){"use strict";e.exports=require("util/types")},76982(e){"use strict";e.exports=require("crypto")},34589(e){"use strict";e.exports=require("node:assert")},4573(e){"use strict";e.exports=require("node:buffer")},31421(e){"use strict";e.exports=require("node:child_process")},77598(e){"use strict";e.exports=require("node:crypto")},40610(e){"use strict";e.exports=require("node:dns")},78474(e){"use strict";e.exports=require("node:events")},73024(e){"use strict";e.exports=require("node:fs")},51455(e){"use strict";e.exports=require("node:fs/promises")},37067(e){"use strict";e.exports=require("node:http")},44708(e){"use strict";e.exports=require("node:https")},77030(e){"use strict";e.exports=require("node:net")},48161(e){"use strict";e.exports=require("node:os")},76760(e){"use strict";e.exports=require("node:path")},53916(e){"use strict";e.exports=require("node:path/posix")},58152(e){"use strict";e.exports=require("node:path/win32")},643(e){"use strict";e.exports=require("node:perf_hooks")},1708(e){"use strict";e.exports=require("node:process")},57075(e){"use strict";e.exports=require("node:stream")},46466(e){"use strict";e.exports=require("node:stream/promises")},87997(e){"use strict";e.exports=require("node:timers")},57975(e){"use strict";e.exports=require("node:util")},73429(e){"use strict";e.exports=require("node:util/types")},38522(e){"use strict";e.exports=require("node:zlib")},23236(e){"use strict";e.exports=require("path/posix")}},t={};function i(r){var s=t[r];if(void 0!==s)return s.exports;var n=t[r]={id:r,loaded:!1,exports:{}};return e[r].call(n.exports,n,n.exports,i),n.loaded=!0,n.exports}i.c=t,i.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var r=i(i.s=86801);module.exports=r})();
|