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/app/sync.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
module.exports=function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=337)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(6),r=n(9),s=n(41),o=n(61),a=n(4),u=n(11);var l=n(6);e.defined=l.defined,e.orElse=l.orElse;var c=n(9);function d(t,e){return null!=t?e(t):void 0}function h(t,e){try{return t()}catch(t){return null!=e?e(t):void 0}}function f(t){return r.keys(t).filter(e=>o.isPrimitive(t[e])||u.isDate(t[e])).map(e=>[e,t[e]])}e.compactValues=c.compactValues,e.entries=c.entries,e.fromEntries=c.fromEntries,e.keys=c.keys,e.mapFields=c.mapFields,e.maybeCall=c.maybeCall,e.onlyReqValued=c.onlyReqValued,e.pick=c.pick,e.reqValuedOrElse=c.reqValuedOrElse,e.values=c.values,e.without=c.without,e.definedThunks=function(...t){return t.every(t=>i.defined(t()))},e.firstThunk=function(...t){for(const e of t){const t=e();if(null!=t)return t}},e.firstTrueThunk=function(t,e){for(const n of t){const t=n();if(null!=t&&(null==e||e(t)))return t}},e.firstDefined=function(...t){return t.find(i.defined)},e.firstDefinedField=function(t,...e){return d(e.find(e=>null!=t[e]),e=>t[e])},e.firstFieldLike=function(t,e){return a.first(r.keys(t),n=>e(n,t[n])?t[n]:void 0)},e.ornull=function(t){return void 0===t?null:t},e.map=d,e.mapOr=function(t,e,n){return null!=t?e(t):s.isFunction(n)?n():n},e.mapAnd=function(t,e){return null!=t&&e(t)},e.mapOrThrow=function(t,e,n){if(null!=t)return e(t);throw new Error(n)},e.Try=h,e.tryEach=function(t,e){[...t].forEach(t=>h(()=>e(t)))},e.identity=function(t){return t},e.ctor=function(t){return d(t.constructor,t=>t.name)},e.hasKeys=function(t){return Object.keys(t).some(e=>"string"==typeof e&&t.propertyIsEnumerable(e))},e.primitiveEntries=f,e.spread=function(t,...e){return Object.assign({},t,...a.compact(e))},e.assignMissingPrimitives=function(t,e){return null==e?t:(f(e).forEach(([e,n])=>{null==t[e]&&(t[e]=n)}),t)},e.pickMap=function(t,e,n){const i={};for(const r of e)i[r]=n(r,t[r]);return i},e.mapEntries=function(t,e){const n={};for(const i of r.keys(t))n[i]=e(i,t[i]);return n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(3),r=n(34),s=n(189),o=n(134),a=n(101),u=n(174),l=n(0),c=n(12);e.rootLogger=i.lazy(()=>o.ConsoleLogger.instance()),e.safeRootLogger=i.lazy(()=>a.safeLogger(e.rootLogger())),e.rootLogger.onChange(()=>e.safeRootLogger.clear()),e.alsoLogToConsole=function(){e.rootLogger.set(e.rootLogger()===o.ConsoleLogger.instance()?e.rootLogger():new s.CompoundLogger(e.rootLogger(),o.ConsoleLogger.instance()))},e.setLoggerProcessName=function(t,n){l.map(e.rootLogger.prior(),t=>t.close());const i=new u.LogWriter(r.BaseFile.for(n),t);e.rootLogger.set(c.Settings.logStdout.valueOrDefault?new s.CompoundLogger(i,o.ConsoleLogger.instance()):i)},e.mkLogger=function(t){return new a.ContextualLogger(t,e.rootLogger)},e.mkSafeLogger=function(t){return new a.ContextualLogger(t,e.safeRootLogger)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(42),s=n(15),o=n(33),a=n(4),u=n(29),l=n(11),c=n(7),d=n(0),h=n(184),f=n(37),p=n(51);var m=n(84);function g(t){return i(this,void 0,void 0,function*(){try{return yield t,!0}catch(t){return!1}})}function y(t,e,n=(()=>void 0),r=(()=>void 0)){return i(this,void 0,void 0,function*(){let i,s=!1,o=!1;return yield Promise.race([h.asPromise(t).then(t=>o?void 0:(i=t,s=!0,t)),f.unrefDelay(e).then(()=>{s||(o=!0)})]),s?yield r(i):yield n(),i})}function v(t,n,r=e.DefaultMaxConcurrent){return i(this,void 0,void 0,function*(){return(yield p.withBoundedConcurrency({name:"tuples",laters:t.map(t=>()=>i(this,void 0,void 0,function*(){return[yield n(t),t]})),maxConcurrent:r})).filter(([t,e])=>null!=t&&null!=e)})}e.thenTap=m.thenTap,e.DefaultMaxConcurrent=8,e.PromiseStates=o.strEnum("pending","resolved","rejected"),e.resolvedThen=function(t,e){return i(this,void 0,void 0,function*(){if(null==t)return Promise.resolve(void 0);try{return yield t,e()}catch(t){return}})},e.resolvedWithin=function(t,e){return Promise.race([t,f.delay(e).then(()=>void 0)])},e.resolved=g,e.rejected=function(t){return i(this,void 0,void 0,function*(){return!(yield g(t))})},e.thenDefined=function(t){return i(this,void 0,void 0,function*(){return null!=(yield t)})},e.allSerial=function(t){return i(this,void 0,void 0,function*(){const e=[];for(const n of a.compact(t))e.push(yield n());return a.compact(e)})},e.awaitAll=function(t){return i(this,void 0,void 0,function*(){yield Promise.all(a.compact(t))})},e.thenFlatten=function(t){return i(this,void 0,void 0,function*(){return null==t?[]:a.flatten(a.compact(yield Promise.all(t)))})},e.thenCompact=function(t){return i(this,void 0,void 0,function*(){const e=a.compact(t);return a.isEmpty(e)?[]:a.compact(yield Promise.all(e))})},e.asyncFind=function(t,e){return i(this,void 0,void 0,function*(){for(const n of t)if(yield e(n))return n})},e.asyncFilter=function(t,n,r=e.DefaultMaxConcurrent){return i(this,void 0,void 0,function*(){return(yield v(a.compact(t),n,r)).filter(([t])=>t).map(([,t])=>t)})},e.tryAsync=function(t){return i(this,void 0,void 0,function*(){try{return yield t()}catch(t){return}})},e.DefaultTryAllTimeoutMs=30*l.secondMs,e.tryAll=function(t,n=(t=>console.error(t)),r=e.DefaultTryAllTimeoutMs){return i(this,void 0,void 0,function*(){for(const e of t)try{yield y(e,r)}catch(t){n(t)}})},e.thenFinally=function(t,e=(()=>{}),n=(()=>{})){return i(this,void 0,void 0,function*(){let i,r=null;try{i=yield"function"==typeof t?t():t}catch(t){r=t;try{yield e(t)}catch(t){}}try{yield n(null!=r?r:i)}catch(t){}if(null!=r)throw r;return i})},e.thenNot=function(t,e=!0){return i(this,void 0,void 0,function*(){if(null==t)return e;const n=yield t;return null==n?e:!u.truthy(n)})},e.thenMap=function(t,e){return i(this,void 0,void 0,function*(){const n=yield t;return null==n?void 0:e(n)})},e.thenMapOr=function(t,e,n){return i(this,void 0,void 0,function*(){const i=yield t;if(null==i)return n();const r=yield e(i);return null==r?n():r})},e.thenAnd=function(t,e){return i(this,void 0,void 0,function*(){if(null!=t)return(yield t)?e():void 0})},e.thenOrElse=function(t,e){return i(this,void 0,void 0,function*(){return d.orElse(yield t,e)})},e.thenSome=function(t,e){return i(this,void 0,void 0,function*(){let n=0;for(const i of t)if(yield e(i,n++,t))return!0;return!1})},e.thenEvery=function(t,e){return i(this,void 0,void 0,function*(){let n=0;for(const i of t)if(!1===(yield e(i,n++,t)))return!1;return!0})},e.firstAsync=function(t,e){return i(this,void 0,void 0,function*(){if(null!=t){let n=-1;for(const i of t){n++;try{if(null==i)continue;const t=yield e(i,n);if(null!=t)return t}catch(t){}}}})},e.firstDefinedPromise=function(...t){return i(this,void 0,void 0,function*(){for(const e of t){const t=yield e();if(null!=t)return t}})},e.firstResolvedDefinedPromise=function(t,e){return i(this,void 0,void 0,function*(){for(const n of t)try{const t=yield n();if(null!=t)return t}catch(t){e(t)}})},e.firstTruePromise=function(t,...e){return i(this,void 0,void 0,function*(){for(const n of e)try{const e=yield n();if(null!=e&&!0===(yield t(e)))return e}catch(t){}})},e.until=function(t,e,n){return i(this,void 0,void 0,function*(){const i=c.mapGt0(e,t=>Date.now()+t),o=s.Opt(n).getOrElse(()=>d.orElse(e,3e4)/10),a=c.clamp(100,1e4,o);for(;null==i||Date.now()<i;){const e=yield t();if(!0===e)return!0;if(null!=e&&!1!==e)throw new Error("f must return a boolean, but returned "+r.inspect(e));yield f.delay(a)}return!1})},e.untilDefined=function(t,{timeoutMs:e,timeBetweenMs:n}){return i(this,void 0,void 0,function*(){const i=c.mapGt0(e,t=>Date.now()+t),r=s.Opt(n).getOrElse(()=>d.orElse(e,3e4)/10),o=c.clamp(50,1e4,r);for(;null==i||Date.now()<i;){const e=yield t();if(null!=e)return e;yield f.delay(o)}})},e.thenOrTimeout=y,e.tuples=v,e.thenGreatest=function(t,e){return i(this,void 0,void 0,function*(){return d.map(a.greatestBy(yield v(t,e),t=>t[0]),t=>t[1])})},e.sortByAsync=function(t,e){return i(this,void 0,void 0,function*(){return a.sortBy(yield v(t,e),t=>t[0]).map(t=>t[1])})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.lazy=function(t,e){let n,i=0;const r=[];function s(t){return i=Date.now(),n=t,r.forEach(t=>t(n)),n}function o(){return(0===i||null!=e&&i+e<=Date.now())&&s(t()),n}return o.clear=function(){const t=n;return i=0,n=void 0,r.forEach(t=>t(n)),t},o.set=function(t){return s(t)},o.prior=function(){return n},o.refresh=function(){return s(t())},o.setTTL=function(t){return e=t},o.onChange=function(t){r.push(t)},o}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(9),s=n(61),o=n(10),a=n(7),u=n(0);var l=n(5);function c(t){return u.defined(t)&&t.every(u.defined)}function d(t,e,n=1,i=u.identity){const r=[];if(t<e)for(let s=t;s<e;s+=n)r.push(i(s));else for(let s=t;s>e;s-=n)r.push(i(s));return r}function h(...t){const e=Math.max(...t.map(t=>t.length));return a.times(e,e=>t.map(t=>t[e]))}function f(t){return y(t,(t,e)=>t.valueOf()<e.valueOf())}function p(t){return g(t,t=>t.valueOf())}function m(t,e){return y(t,(t,n)=>u.map(e(t),t=>u.map(e(n),e=>t<e)))}function g(t,e){return y(t,(t,n)=>u.map(e(t),t=>u.map(e(n),e=>t>e)))}function y(t,e){let n,i=-1;for(let r=0;r<t.length;r++)u.map(t[r],t=>{null!=n&&!0!==e(t,n)||(i=r,n=t)});return i}e.clear=l.clear,e.compact=l.compact,e.count=l.count,e.includesAll=l.includesAll,e.isEmpty=l.isEmpty,e.isNotEmpty=l.isNotEmpty,e.mapNotEmpty=l.mapNotEmpty,e.filterInPlace=l.filterInPlace,e.uniq=l.uniq,e.uniqBy=l.uniqBy,e.sort=l.sort,e.sortBy=l.sortBy,e.sorted=l.sorted,e.startsWith=l.startsWith,e.toA=l.toA,e.allDefined=c,e.mapAllDefined=function(t,e){return c(t)?e(t):void 0},e.mapAll=function(t,e){return c(t)?e(t):void 0},e.allNotDefined=function(t){return null==t||t.every(t=>null==t)},e.allNotBlank=function(...t){return null!=t&&t.every(o.notBlank)},e.anyNotDefined=function(t){return null==t||t.some(t=>null==t)},e.anyDefined=function(t){return null!=t&&t.some(t=>null!=t)},e.first=function(t,e){if(null!=t)for(const n of i.compact(t)){const t=e(n);if(null!=t)return t}},e.firstNonEmptyThunk=function(...t){for(const e of t){const t=e();if(i.isNotEmpty(t))return t}},e.concat=function(...t){const e=[];for(const n of t)if(Array.isArray(n))for(const t of n)null!=t&&e.push(t);else null!=n&&e.push(n);return e},e.flatten=function t(e,n=[]){return null==e?n:(e.forEach(e=>u.map(e,e=>Array.isArray(e)?t(e,n):n.push(e))),n)},e.exclude=function(t,e){if(e.length<50)return t.filter(t=>!e.includes(t));{const n=new Set(e);return t.filter(t=>!n.has(t))}},e.remove=function(t,e){const n=t.length;return i.filterInPlace(t,t=>t!==e),n!==t.length},e.diff=function(t,e){const n=new Set(e.map(t=>t.valueOf()));return t.filter(t=>!n.has(t.valueOf()))},e.intersect=function(t,e){const n=new Set(e.map(t=>t.valueOf()));return t.filter(t=>n.has(t.valueOf()))},e.eqlContents=function(t,e){return h(i.sort(t),i.sort(e)).every(([t,e])=>t===e)},e.removeFirst=function(t,e){const n=t.findIndex(e);return n>=0?t.splice(n,1)[0]:void 0},e.uniqInPlace=function(t){i.filterInPlace(t,(e,n)=>t.indexOf(e)===n)},e.partition=function(t,e){const n=[],i=[];return t.forEach((t,r)=>(e(t,r)?n:i).push(t)),[n,i]},e.uniqCount=function(t){return function t(e){if(null==e||0===e.length)return[];const n=e[0];const i=e.lastIndexOf(n);return[{t:n,count:i+1},...t(e.slice(i+1))]}(t.sort())},e.mapCompact=function(t,e){return i.compact(i.compact(t).map(e))},e.toMapEntries=function(t,e){return new Map(t.map(e).filter(u.defined))},e.flatMap=function(t,e){return t.reduce((t,n)=>t.concat(e(n)),[])},e.range=function(t,e,n=u.identity){return d(t,e,1,n)},e.stepRange=d,e.retainLastN=function(t,e){return t.length>e&&t.splice(0,t.length-e),t},e.retainFirstN=function(t,e){return t.length=Math.min(t.length,e),t},e.contextAround=function(t,e,n,i){const r=t.findIndex(i);if(-1!==r){return{before:0===r?[]:t.slice(Math.max(0,r-e),r),after:r===t.length-1?[]:t.slice(r+1,Math.min(r+1+n,t.length))}}},e.zip=h,e.flatZip=function(...t){const e=Math.max(...t.map(t=>t.length)),n=[];return a.times(e,e=>t.map(t=>n.push(t[e]))),n},e.unzip=function(t){return[t.map(([t])=>t),t.map(([,t])=>t)]},e.ancestry=function(t){return a.times(t.length,e=>t.slice(0,e+1))},e.leastIndex=f,e.greatestIndex=p,e.min=function(t){return t[f(t)]},e.max=function(t){return t[p(t)]},e.leastIndexBy=m,e.greatestIndexBy=g,e.leastBy=function(t,e){return t[m(t,e)]},e.greatestBy=function(t,e){return t[g(t,e)]},e.combinations=function*t(e,n){if(!(null==e||e.length<n))for(let i=0;i<e.length;i++)if(1===n)yield[e[i]];else for(const r of t(e.slice(i+1),n-1))yield[e[i],...r]},e.sortByInPlace=function(t,e){return t.sort((t,n)=>s.cmp(e(t),e(n)))},e.reverse=function(t){const e=[];for(let n=t.length-1;n>=0;n--)e.push(t[n]);return e},e.batches=function(t,e){return e<=0&&(e=1),d(0,t.length,e,n=>t.slice(n,n+e))},e.sortArrArr=function(t){return i.sortBy(t.map(t=>i.sort(t)),t=>t[0].valueOf())},e.contextFilter=function(t,e){let n;return t.filter((t,i)=>r.tap(e(t,i,n),e=>{e&&(n=t)}))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(46),s=n(180),o=n(95),a=n(6),u=n(61),l=n(18);function c(t){return null==t?[]:"function"==typeof Array.from?Array.from(t):Array.isArray(t)?t:[].slice.call(t)}function d(t){return s.isList(t)&&t.length>0&&t.some(t=>null!=t)}function h(t){return!d(t)}function f(t){return u.isPrimitive(t)||u.isPrimitiveArray(t)?t:t.valueOf()}function p(t,e){if(null==t)return!1;for(const n of t)if(e===n)return!0;return!1}function m(t){if(null==t)return[];const e=c(t);return e.every(a.defined)?e:e.filter(a.defined)}e.toA=c,e.isNotEmpty=d,e.isEmpty=h,e.mapNotEmpty=function(t,e){return d(t)?e(t):void 0},e.sort=function(t){return m(t).sort((t,e)=>u.cmp(a.map(t,f),a.map(e,f)))},e.sorted=function(t){return t.every((e,n)=>0===n||e>t[n-1])},e.sortBy=function(t,e){return c(t).map(t=>[e(t),t]).filter(([t])=>null!=t).sort((t,e)=>u.cmp(t[0],e[0])).map(t=>t[1])},e.startsWith=function(t,e){return r.arrayEql(t.slice(0,e.length),e)},e.filterInPlace=function(t,e){for(let n=0;n<t.length;)e(t[n],n,t)?n++:t.splice(n,1);return t},e.includes=p,e.indexOf=function(t,e){if(null==t)return;let n=0;for(const i of t){if(e(i,n))return n;n++}},e.includesAll=function(t,e){return null!=t&&null!=e&&e.every(e=>p(t,e))},e.pushUniq=function(t,e){return p(t,e)||t.push(e),t},e.compact=m;const g=["null","undefined"];function y(t,e){if(h(t))return[];const n=new Map;return t.forEach(t=>o.getOrSet(n,e(t),()=>t)),[...n.values()]}e.compactBlankish=function(t){return c(t).filter(t=>i.notBlank(t)&&!g.includes(l.toS(t)))},e.compactBlanks=function(t){return null==t?[]:t.map(l.toS).filter(i.notBlank)},e.uniq=function(t){return y(t,t=>JSON.stringify(t))},e.uniqBy=y,e.clear=function(t){return t.length=0,t},e.count=function(t,e){return t.reduce((t,n)=>t+(e(n)?1:0),0)},e.sum=function(t,e){return t.reduce((t,n)=>t+e(n),0)},e.firstMatch=function(t,e){for(const n of m(e)){const e=t.exec(n);if(null!=e)return e}},e.commonPrefixLength=function(t,e){if(null==t||null==e)return 0;if(r.eql(t,e))return t.length;let n=0;for(;r.eql(t[n],e[n]);)n++;return n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(41);function r(t){return null!=t}e.map=function(t,e){return null==t?void 0:e(t)},e.orElse=function(t,e){return null!=t?t:i.isFunction(e)?e():e},e.mapOr=function(t,e,n){return null==t?n():e(t)},e.defined=r,e.allDefined=function(t){return null!=t&&t.every(r)},e.firstDefined=function(...t){return t.find(r)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(17),r=n(59),s=n(4),o=n(10),a=n(0);var u=n(17);e.clamp=u.clamp,e.gt0=u.gt0,e.gte0=u.gte0,e.isNumber=u.isNumber,e.id=u.id,e.mapFinite=u.mapFinite,e.mapInt=u.mapInt,e.round=u.round,e.sigFigs=u.sigFigs,e.times=u.times,e.toInt=u.toInt,e.toFloat=u.toFloat,e.toPrecision=u.toPrecision;var l=n(59);e.fmt=l.fmt,e.fmtBytes=l.fmtBytes,e.GB=l.GB,e.GiB=l.GiB,e.KB=l.KB,e.KiB=l.KiB,e.MB=l.MB,e.megapixels=l.megapixels,e.MiB=l.MiB,e.MP=l.MP;const c=t=>(e,n)=>i.isNumber(e)&&i.isNumber(n)&&t(e,n);e.lt=c((t,e)=>t<e),e.lte=c((t,e)=>t<=e),e.gt=c((t,e)=>t>e),e.gte=c((t,e)=>t>=e),e.firstGt0=function(...t){return t.find(i.gt0)},e.firstNonZero=function(...t){for(const e of s.flatten(t)){const t=i.toFloat(e);if(null!=t&&0!==t)return t}},e.mapGte0=function(t,e){return i.mapInt(t,t=>t>=0?e(t):void 0)},e.mapGt0=function(t,e){return i.mapInt(t,t=>t>0?e(t):void 0)},e.within=function(t,n,i){return null!=i&&([t,n]=[Math.min(t,n),Math.max(t,n)],e.gte(i,t)&&e.lte(i,n))};const d=/[+-]?[0-9\.]/;function h(t){if(i.isNumber(t))return t;if(o.blank(t))return;const e=String(t);return a.map(d.exec(e),t=>i.toFloat(e.substr(t.index)))}e.extractInt=function(t){return i.toInt(h(t))},e.extractFloat=h,e.closeTo=function(t,e,n){return Math.abs(t-e)<n},e.assertPositive=function(t,e){if(null==e||e<=0)throw new Error(t+" must be positive")},e.plur=function(t,e,n=e+"s"){return r.fmt(t)+" "+(1===t?e:n)},e.absdiff=function(t,e){t=null==t?0:t,e=null==e?0:e;const n=Math.min(t,e);return Math.abs(n+t-(n+e))};e.Array2D=class{constructor(t){this.columns=t,this.store=[]}get(t,e){return t<0||e<0?0:a.orElse(this.store[t*this.columns+e],()=>0)}set(t,e,n){this.store[t*this.columns+e]=n}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(18);function s(t){if(null==t)return!0;const e=r.toS(t);return 0===e.length||0===e.trim().length}function o(t){return!s(t)}e.blank=s,e.notBlank=o,e.ifNotBlank=function(t){if(null==t)return;const e=r.toS(t);return 0===e.length||0===e.trim().length?void 0:e},e.notBlankOr=function(t,e){if(null==t)return e;const n=r.toS(t).trim();return n.length>0?n:e},e.notBlankAnd=function(t,e){return!s(t)&&e(t)},e.mapNotBlank=function(t,e){if(!1===t||null==t||""===t)return;const n=r.toS(t);return o(n)?e(n):void 0},e.firstNotBlank=function(...t){return i.toA(t).find(t=>o(t))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(8),s=n(6),o=n(41);var a=n(6);function u(t){return null==t||"object"!=typeof t?[]:Object.keys(t).filter(e=>"string"==typeof e&&(null==t.propertyIsEnumerable||t.propertyIsEnumerable(e)))}function l(t){return u(t).map(e=>t[e])}function c(t){return u(t).map(e=>[e,t[e]])}function d(t,e={}){return"object"!=typeof e&&(e={}),i.compact(t).reduce((t,[e,n])=>f(t,()=>{null!=e&&null!=n&&(t[e]=n)}),e)}function h(t){return l(t).every(t=>null!=t)}function f(t,e){return null!=e?e(t):console.dir(t,{depth:3}),t}e.map=a.map,e.emptyObj=function(t){return i.isEmpty(u(t))},e.keys=u,e.values=l,e.compactValues=function(t){const e=c(t).filter(([t,e])=>null!=t&&null!=e);return i.isEmpty(e)?void 0:d(e)},e.entries=c,e.fromEntries=d,e.mapFields=function(t,e,n={}){return d(i.compact(c(t).map(([t,n])=>e(t,n))).filter(([t,e])=>null!=t&&null!=e),n)},e.pick=function(t,...e){if(null==t)return t;if(!e.every(t=>"string"==typeof t))throw new Error("bad keys: "+JSON.stringify(e));return i.isEmpty(e)?{}:e.reduce((e,n)=>f(e,()=>s.map(t[n],t=>e[n]=t)),{})},e.pickFirst=function(t,e,n=s.defined){if(null!=t)for(const i of e)if(n(t[i]))return t[i]},e.without=function(t,...e){if(null==t||e.every(e=>r.blank(t[e])))return t;const n=c(t).filter(([t])=>!e.includes(t));return i.isEmpty(n)?void 0:d(n)},e.reqValued=h,e.reqValuedOrElse=function(t){return h(t)?t:void 0},e.onlyReqValued=function(t){return t.filter(h)},e.sortedKeys=function(t){return d(i.sortBy(c(t),([t])=>t))},e.filter=function(t,e){return null==t?t:d(c(t).filter(([t,n])=>e(t,n)))},e.tap=f,e.allKeys=function(t){const e=u(t);for(;null!=(t=Reflect.getPrototypeOf(t));)e.push(...Reflect.ownKeys(t).filter(t=>"string"==typeof t));return i.uniq(e)},e.maybeCall=function(t,e,...n){return null!=t&&o.isFunction(t[e])?t[e].bind(t)(...n):void 0},e.firstValueCaseInsensitive=function(t,e){if(r.blank(e))return;if(null!=t[e])return t[e];const n=e.toLocaleLowerCase().normalize();for(const e of u(t))if(n===e.toLocaleLowerCase().normalize()&&null!=t[e])return t[e]}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8);var s=n(8);e.blank=s.blank,e.notBlank=s.notBlank,e.mapNotBlank=s.mapNotBlank,e.firstNotBlank=s.firstNotBlank;var o=n(5);e.compactBlanks=o.compactBlanks,e.firstNotBlankThunk=function(...t){for(const e of t)try{const t=e();if(r.notBlank(t))return t}catch(t){}throw new Error("No elements were defined")},e.firstNotBlankPromise=function(...t){return i(this,void 0,void 0,function*(){for(const e of t)try{const t=yield e();if(r.notBlank(t))return t}catch(t){}throw new Error("No elements were defined")})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(79),s=n(16),o=n(6),a=n(17),u=n(15),l=n(61),c=n(4),d=n(10),h=n(98),f=n(26),p=n(38),m=n(7),g=n(0),y=n(13);var v=n(16);function w(t){return t instanceof Date}function b(t,e=5*s.secondMs){return m.gt0(t)&&Math.abs(Date.now()-t)<=e}function S(t,e=2){return y.leftPad(t,e,"0")}function P(t,e,n){return t<1?void 0:m.plur(t,e,n)}function M(t,e=2){if(!m.gte0(t))return a.isNumber(t)?"-"+M(Math.abs(t),e):"";const n=[P(Math.floor(t/s.dayMs),"day","days"),P(Math.floor(t/s.hourMs)%24,"hour","hours"),P(Math.floor(t/s.minuteMs)%60,"minute","minutes"),P(Math.floor(t/s.secondMs)%60,"second","seconds")],i=n.findIndex(t=>null!=t);return c.compact(n.slice(i,i+e)).join(", ")}e.dayMs=v.dayMs,e.hourMs=v.hourMs,e.minuteMs=v.minuteMs,e.secondMs=v.secondMs,e.isDate=w,e.cmpDate=function(t,e){const n=g.mapOr(t,t=>t.getTime(),0),i=g.mapOr(e,t=>t.getTime(),0);return l.cmp(n,i)},e.unixtime=function(t){const e=w(t)?t.getTime():a.isNumber(t)?t:void 0;return o.map(e,t=>Math.floor(t/1e3))},e.ago=function(t,e){return new Date(g.orElse(e,new Date).getTime()-t)},e.closeTo=function(t,e,n){return null!=t&&null!=e&&Math.abs(t.getTime()-e.getTime())<=n},e.recent=function(t,e=5*s.secondMs){return b(o.map(t,t=>f.datedToMillis(t)),e)},e.recentMs=b,e.elapsed=function(t){const e=Date.now(),n=t();return{elapsedMs:Date.now()-e,result:n}},e.elapsedAsync=function(t){return i(this,void 0,void 0,function*(){const e=Date.now(),n=yield t();return{elapsedMs:Date.now()-e,result:n}})},e.thenElapsed=function(t){return i(this,void 0,void 0,function*(){const e=Date.now(),n=yield t;return{elapsedMs:Date.now()-e,result:n}})},e.datestamp=function(t=new Date){return t.getFullYear()+"-"+S(t.getMonth()+1)+"-"+S(t.getDate())},e.datestampUTC=function(t=new Date){return t.getUTCFullYear()+"-"+S(t.getUTCMonth()+1)+"-"+S(t.getUTCDate())},e.filestampUTC=function(t=new Date){return[t.getUTCFullYear(),S(t.getUTCMonth()+1),S(t.getUTCDate()),"-",S(t.getUTCHours()),S(t.getUTCMinutes()),S(t.getUTCSeconds())].join("")},e.fmtMs=function(t,e=2){return t<10*s.secondMs?Number(t).toLocaleString()+"ms":M(t,e)},e.fmtDuration=M;const x=new Map;e.fmtIsoDate=function(t,e,n=r.DateTime.DATETIME_MED){let i=r.DateTime.fromISO(t,{setZone:!0});if(i.isValid)return d.mapNotBlank(e,t=>i=i.setLocale(t)),i.toLocaleString(n);{const n=h.DateInterval.parse(t);return null==n?t:(i=n.middle.toDateTime(),d.mapNotBlank(e,t=>i=i.setLocale(t)),i.toLocaleString(r.DateTime.DATE_MED))}},e.isoNow=function(){return(new Date).toISOString()},e.fmtShort=function(t,e="en-US"){return p.getOrSet(x,e,()=>new Intl.DateTimeFormat(e,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"})).format(f.datedToMillis(t))};const E=/((?:19|20)\d\d)([01]\d)([0123]\d)([012]\d)([012345]\d)([012345]\d)\.(\d{6})([+-]\d{3})?/;e.wmiDate=function(t){const e=E.exec(t);if(null==e)return;const n=e.slice(1,8).map(t=>m.toInt(t));if(!c.allDefined(n))return;const[i,r,o,a,u,l,d]=n,h=m.toInt(e[8],{defaultValue:0});return new Date(Date.UTC(i,r-1,o,a,u,l,d/1e3)-h*s.minuteMs)};const _=/Date\((\d+)\)/;e.pwshJsonDate=function(t){return u.Opt(t).flatMap(t=>_.exec(t)).flatMap(t=>t[1]).flatMap(m.toInt).filter(t=>m.within(0,Date.now()+s.dayMs,t)).map(t=>new Date(t)).get()},e.MaxTzOffsetHours=14},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(45),r=n(30),s=n(22),o=n(5),a=n(8),u=n(146),l=n(9),c=n(33),d=n(18),h=n(128),f=n(129),p=n(4),m=n(3),g=n(10),y=n(29),v=n(28),w=n(7),b=n(0),S=n(23),P=n(49),M=n(138);var x;function E(t){const n=(a.blank(t)?"":t).split(r.delimiter);if(S.isWin&&a.blank(s.env.SYSTEMROOT))throw new Error("%SYSTEMROOT% is not set");return n.push(...e.DefaultPaths),o.uniq(n).filter(g.notBlank).join(r.delimiter)}function _(t){const n={};e.settingsForChildProcs().forEach(t=>t.addToEnv(n));const i=b.compactValues(Object.assign({},s.env,{ELECTRON_RUN_AS_NODE:"1",PATH:e.pathWithDefaults()},n,b.orElse(t,{})));return x.logStdout.deleteFromEnv(i),i}!function(t){t.nodeEnv=new M.StringEnumSetting({name:"nodeEnv",key:"NODE_ENV",category:M.SettingCategories.System,description:"runtime environment",defaultValue:()=>{const t=d.toS(s.env.NODE_ENV).toLowerCase();return t.startsWith("test")?"test":t.startsWith("prod")?"production":t.startsWith("dev")?"development":s.argv.some(t=>t.includes("mocha"))?"test":"production"},validValues:["development","test","production"],persisted:!1,addToChildProcs:!0}),t.electronVersion=new M.StringSetting({name:"electronVersion",key:"PS_ELECTRON_VERSION",category:M.SettingCategories.System,description:"",defaultValue:s.versions.electron,persisted:!1,addToChildProcs:!0}),t.libraryPath=new M.StringSetting({name:"libraryPath",key:"PS_LIBRARY_PATH",alternateKeys:["PS_LIBRARY"],category:M.SettingCategories.System,description:"This is the full 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.",defaultValue:"",persisted:!0,advanced:!1,addToChildProcs:!0}),t.logLevel=new M.StringSetting({name:"logLevel",key:"PS_LOG_LEVEL",alternateKeys:["PS_LOG","LOG"],category:M.SettingCategories.Logging,description:"Determines which level of log messages are emitted to log files. May be 'debug', 'info', 'warn', or 'error'.",defaultValue:"error",persisted:!0,addToChildProcs:!0}),t.logDir=new M.StringSetting({name:"logDir",key:"PS_LOG_DIR",category:M.SettingCategories.Logging,description:"Determines the directory that log files will be written to.",defaultValue:()=>"darwin"===i.platform()?v.resolve(i.homedir(),"Library","Logs",f.AppName):v.resolve(h.appData(),f.AppName,"logs"),persisted:!0,addToChildProcs:!0}),t.logColor=new M.BooleanSetting({name:"logColor",key:"PS_LOG_COLOR",category:M.SettingCategories.Logging,description:"Should log messages be colorized with ANSI escape sequences? Great for nerds, bad for everyone else.",defaultValue:!1,persisted:!0}),t.logCompression=new M.BooleanSetting({name:"logCompression",key:"PS_LOG_COMPRESS",category:M.SettingCategories.Logging,description:"Should log files be compressed as they are rotated?",defaultValue:!0,persisted:!0}),t.logWebRequests=new M.BooleanSetting({name:"logWebRequests",key:"PS_LOG_WEB_REQUESTS",category:M.SettingCategories.Logging,description:"Write an access log for all web requests?",defaultValue:!1,persisted:!0}),t.logWebDir=new M.StringSetting({name:"logWebDir",key:"PS_LOG_WEB_DIR",category:M.SettingCategories.Logging,description:"Determines the directory that log files will be written to. If unset, will use logDir.",defaultValue:"",persisted:!0,addToChildProcs:!0}),t.logSql=new M.StringSetting({name:"logSql",key:"PS_LOG_SQL",category:M.SettingCategories.Logging,description:"If non-blank, and a given db query includes the given string, the query will be logged.",defaultValue:"",persisted:!0}),t.logStdout=new M.BooleanSetting({name:"logStdout",key:"PS_LOG_STDOUT",alternateKeys:["LOG_STDOUT","PS_STDOUT"],category:M.SettingCategories.Logging,description:"Log to stdout? This should be false unless you're running a service by hand.",defaultValue:!1,persisted:!1}),t.minDiskFreeGb=new M.IntegerSetting({name:"minDiskFreeGb",key:"PS_MIN_DISK_FREE_GB",category:M.SettingCategories.System,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.",defaultValue:8,persisted:!0}),t.maxCpuPercent=new M.BoundedIntegerSetting({name:"maxCpuPercent",key:"PS_MAX_CPU_PERCENT",category:M.SettingCategories.System,description:"PhotoStructure will not schedule work if the current system utilization percent is higher than this value. This value must be between 0 and 100. Smaller values (less than 25) may mean PhotoStructure can never schedule work. A value of 100 will allow PhotoStructure to schedule work on all of your CPUs, and may make your system unusable.",defaultValue:75,min:0,max:200,persisted:!0}),t.maxMemoryMb=new M.BoundedIntegerSetting({name:"maxMemoryMb",key:"PS_MAX_MEMORY_MB",category:M.SettingCategories.System,description:"PhotoStructure will restart services if their process consumes more than this value (measured in megabytes, or 1,000,000 bytes).",defaultValue:1e3,min:512,max:8e3,persisted:!0}),t.dbCacheSizeMb=new M.IntegerSetting({name:"dbCacheSizeMb",key:"PS_DB_CACHE_SIZE_MB",category:M.SettingCategories.System,description:"PhotoStructure uses SQLite, and the cache_size pragma should ideally be set such that the whole DB can be in memory. See https://sqlite.org/pragma.html#pragma_cache_size for more information.",defaultValue:128,persisted:!0}),t.vlcPath=new M.StringSetting({name:"vlcPath",key:"PS_VLC_PATH",category:M.SettingCategories.Tools,description:'This should be the absolute, native path to the "vlc" binary on this system. If this is set to "vlc", PhotoStructure will search your $PATH.',defaultValue:"vlc",persisted:!0}),t.ffmpegPath=new M.StringSetting({name:"ffmpegPath",key:"PS_FFMPEG_PATH",category:M.SettingCategories.Tools,description:'This should be the absolute, native path to the "ffmpeg" binary on this system. If this is set to "ffmpeg", PhotoStructure will search your $PATH.',defaultValue:"ffmpeg",persisted:!0}),t.updateChannel=new M.StringEnumSetting({name:"updateChannel",key:"PS_UPDATE_CHANNEL",category:M.SettingCategories.Updates,description:'TL:DR; keep this on "latest." This controls which builds of PhotoStructure you are eligible to automatically update to. Please note that "alpha" builds may not even launch, and "beta" builds will not have been thoroughly tested. Please only consider changing this if customer support asks you to.',defaultValue:"latest",validValues:["alpha","beta","latest"],persisted:!0}),t.allowDowngrade=new M.BooleanSetting({name:"allowDowngrade",key:"PS_ALLOW_DOWNGRADE",category:M.SettingCategories.Updates,description:"If you're running an alpha or beta build, and you switch back to 'updateChannel = \"latest\"', would you like PhotoStructure to downgrade you? Note that enabling this may make your library unreadable, if the current stable version of PhotoStructure can't read new alpha or beta database schemas.",defaultValue:!1,persisted:!0}),t.updateOnLaunch=new M.BooleanSetting({name:"updateOnLaunch",key:"PS_UPDATE_ON_LAUNCH",category:M.SettingCategories.Updates,description:"If true, PhotoStructure will check for updates automatically on launch.",defaultValue:!0,persisted:!0}),t.updateCheckMinutes=new M.IntegerSetting({name:"updateCheckMinutes",key:"PS_UPDATE_CHECK_MINUTES",category:M.SettingCategories.Updates,description:"While running, PhotoStructure will check periodically for updates. The default is daily.",defaultValue:1440,persisted:!0}),t.reportErrors=new M.BooleanSetting({name:"reportErrors",key:"PS_REPORT_ERRORS",category:M.SettingCategories.ErrorReporting,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:!0,advanced:!1,persisted:!0}),t.maxErrorsPerDay=new M.IntegerSetting({name:"maxErrorsPerDay",key:"PS_MAX_ERRORS_PER_DAY",category:M.SettingCategories.ErrorReporting,description:"Set this to zero to remove all bugs in PhotoStructure.\n\nHUR HUR #DADJOKE\n\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,persisted:!0}),t.email=new M.StringSetting({name:"email",key:"PS_EMAIL",category:M.SettingCategories.ErrorReporting,description:"If set, this email will be added to error reports, so we can contact you to help debug the issue. It is not required.",defaultValue:"",advanced:!1,persisted:!0}),t.inspect=new M.BooleanSetting({name:"inspect",key:"PS_INSPECT",category:M.SettingCategories.System,description:"Should processes run with --inspect? This should only be enabled temporarily, as it impacts both performance and security.",defaultValue:!1,persisted:!0}),t.rpcPort=new M.IntegerSetting({name:"rpcPort",key:"PS_RPC_PORT",category:M.SettingCategories.Web,description:"Network port for rpc access to your PhotoStructure library. Only binds to loopback (even if exposeNetworkWithoutAuth is true).",defaultValue:1807,persisted:!0,addToChildProcs:!0}),t.httpPort=new M.IntegerSetting({name:"httpPort",key:"PS_HTTP_PORT",category:M.SettingCategories.Web,description:"Network port for HTTP access to your PhotoStructure library.",defaultValue:1787,persisted:!0,addToChildProcs:!0}),t.sessionTimeoutHours=new M.BoundedIntegerSetting({name:"sessionTimeoutHours",key:"PS_SESSION_TIMEOUT_HOURS",category:M.SettingCategories.Web,description:"How long should unused HTTP sessions exist before requiring visitors to log back in? This defaults to 180 days, just to maximize convenience.",defaultValue:4320,max:8760,min:1,persisted:!0}),t.exposeNetworkWithoutAuth=new M.BooleanSetting({name:"exposeNetworkWithoutAuth",key:"PS_EXPOSE_NETWORK_WITHOUT_AUTH",category:M.SettingCategories.Web,description:"Normally the web service is bound to loopback, so your PhotoStructure library is only accessible to this machine. Setting this to true will expose your library to all computers on your network (if they know your PhotoStructure port). 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\n** Don't enable this unless you know what you're doing. **",defaultValue:!1,persisted:!0}),t.copyAssetsToLibrary=new M.BooleanSetting({name:"copyAssetsToLibrary",key:"PS_COPY_ASSETS",category:M.SettingCategories.Sync,description:"Should PhotoStructure copy photos and videos to your PhotoStructure Library?",defaultValue:!0,advanced:!1,persisted:!0}),t.scanAllDrives=new M.BooleanSetting({name:"scanAllDrives",key:"PS_SCAN_ALL_DRIVES",category:M.SettingCategories.Sync,description:"Should PhotoStructure scan all folders on all drives available to this computer for photos and videos?",defaultValue:!0,advanced:!1,persisted:!0}),t.scanMyPictures=new M.BooleanSetting({name:"scanMyPictures",key:"PS_SCAN_MY_PICTURES",category:M.SettingCategories.Sync,description:"Should PhotoStructure only scan your system's 'Pictures' folder for photos and videos?",defaultValue:!t.scanAllDrives.defaultValue,advanced:!1,persisted:!0}),t.scanPaths=new M.StringArraySetting({name:"scanPaths",key:"PS_SCAN_PATHS",category:M.SettingCategories.Sync,description:"This holds an array of full native paths to scan for assets.",advanced:!1,persisted:!0}),t.assetSubdirectoryDatestampFormat=new M.StringSetting({name:"assetSubdirectoryDatestampFormat",key:"PS_ASSET_SUBDIR_FORMAT",category:M.SettingCategories.Sync,description:"If you chose to copy assets into your library, they will be copied into <library directory>/<result of this pattern>/<original imagename>.\nSee <https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toFormat> and <https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens>.",defaultValue:"y/y-MM-dd",persisted:!0}),t.validateJpegImages=new M.BooleanSetting({name:"validateJpegImages",key:"PS_VALIDATE_JPEG_IMAGES",category:M.SettingCategories.Sync,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,advanced:!1,persisted:!0}),t.validateRawImages=new M.BooleanSetting({name:"validateRawImages",key:"PS_VALIDATE_RAW_IMAGES",category:M.SettingCategories.Sync,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. Enabling this feature slows down imports.",defaultValue:!0,advanced:!1,persisted:!0}),t.validateVideos=new M.BooleanSetting({name:"validateVideos",key:"PS_VALIDATE_VIDEOS",category:M.SettingCategories.Sync,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 dramatically slows down imports, as videos must be "played" to be validated. Note that if you set transcodeVideos to true, this setting is effectively true for all videos that aren\'t MP4-encoded.',defaultValue:!1,advanced:!1,persisted:!0}),t.transcodeVideos=new M.BooleanSetting({name:"transcodeVideos",key:"PS_TRANSCODE_VIDEOS",category:M.SettingCategories.Sync,description:"Should videos be transcoded during import? VLC must be installed. Note that this dramatically slows down imports, and *dramatically* increases the disk space your library will need to use. If this is set to false, though, your browser will not be able to render your videos unless they are already MP4-encoded.",defaultValue:!0,persisted:!0}),t.squareThumbStrategy=new M.StringEnumSetting({name:"squareThumbStrategy",key:"PS_SQUARE_THUMB_STRATEGY",category:M.SettingCategories.Sync,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.dimens.io/en/stable/api-resize/',defaultValue:"attention",validValues:["center","entropy","attention"],persisted:!0}),t.sharpen=new M.BooleanSetting({name:"sharpen",key:"PS_SHARPEN",category:M.SettingCategories.Sync,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,persisted:!0}),t.progressive=new M.BooleanSetting({name:"progressive",key:"PS_PROGRESSIVE",category:M.SettingCategories.Sync,description:"Should preview JPEGs be progressively encoded? If set, syncs will take a bit longer, but FHD/QHD/UHD previews will be smaller.",defaultValue:!0,persisted:!0}),t.previewResolutions=new M.StringEnumsSetting({name:"previewResolutions",key:"PS_PREVIEW_RESOLUTIONS",category:M.SettingCategories.Sync,description:"This controls the resolutions that PhotoStructure creates for every asset. Note that resolutions will be skipped if there already is a preview value with 2.5x the megapixels, so even though there are a lot of sizes here, you'll only see 3-4 images on your disk per asset.",defaultValue:p.exclude(u.FitSizeValues,["uhd8k","uhd5k"]),validValues:u.FitSizeValues,persisted:!0}),t.statTimeoutSeconds=new M.BoundedIntegerSetting({name:"statTimeoutSeconds",key:"PS_STAT_TIMEOUT_SECONDS",category:M.SettingCategories.Sync,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 reading a directory entry exceeds this value. The default of 30 seconds should cover most issues with spun-down hard drives and NAS/WAN latency.',defaultValue:30,min:1,max:300,persisted:!0}),t.minFileSizeBytes=new M.IntegerSetting({name:"minFileSizeBytes",key:"PS_MIN_ASSET_SIZE",category:M.SettingCategories.Sync,description:"What's the minimum photo or video size you want imported into your library? (This can prevent small GIFs and screenshots from being imported).",defaultValue:50*w.KB,persisted:!0}),t.maxFileSizeBytes=new M.IntegerSetting({name:"maxFileSizeBytes",key:"PS_MAX_ASSET_SIZE",category:M.SettingCategories.Sync,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)",defaultValue:.5*w.GB,persisted:!0}),t.minImageDimension=new M.IntegerSetting({name:"minImageDimension",key:"PS_MIN_IMAGE_DIMENSION",category:M.SettingCategories.Sync,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.",defaultValue:480,persisted:!0}),t.minVideoDimension=new M.IntegerSetting({name:"minVideoDimension",key:"PS_MIN_VIDEO_DIMENSION",category:M.SettingCategories.Sync,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.",defaultValue:240,persisted:!0}),t.neverIgnored=new M.StringArraySetting({name:"neverIgnored",key:"PS_NEVER_IGNORED",category:M.SettingCategories.Sync,description:"Paths to files or directories that should not be ignored, even if they are hidden or have .nomedia files.",persisted:!0}),t.startPaused=new M.BooleanSetting({name:"startPaused",key:"PS_START_PAUSED",category:M.SettingCategories.Sync,description:"Should processing be paused by default when PhotoStructure starts? You'll have the manually resume processing via the system tray menu.",defaultValue:!1,persisted:!0}),t.syncIntervalHours=new M.BoundedIntegerSetting({name:"syncIntervalHours",key:"PS_SYNC_INTERVAL_HOURS",category:M.SettingCategories.Sync,description:"This value controls both how often the sync process runs, and how often new files are discovered and imported. WARNING: Setting this value to a small value (say, less than 10) will mean PhotoStructure is constantly scanning your disks, which may reduce the lifespan of your storage media. Note that setting this and fileSyncIntervalHours to 0 will disable automatic scheduling of the sync process. This defaults to every day (to balance picking up new files automatically and trying to avoid unnecessary wear and tear on your storage media).",defaultValue:24,max:504,min:0,persisted:!0}),t.fileSyncIntervalHours=new M.BoundedIntegerSetting({name:"fileSyncIntervalHours",key:"PS_FILE_SYNC_INTERVAL_HOURS",category:M.SettingCategories.Sync,description:"This value controls how often the files in your library are checked for changes. The `syncIntervalHours` setting, in contrast, controls how often *new* files are discovered. This defaults to every week (to try to balance picking up changes with wear and tear on your storage media)",defaultValue:168,max:1344,min:0,persisted:!0}),t.forceSync=new M.BooleanSetting({name:"forceSync",key:"PS_FORCE_SYNC",category:M.SettingCategories.Sync,description:"When set, all files will be visited, even if the asset seems in sync with the filesystem",defaultValue:!1,persisted:!1}),t.defaultSidecarType=new M.StringEnumSetting({name:"defaultSidecarType",key:"PS_DEFAULT_SIDECAR_TYPE",category:M.SettingCategories.Sync,description:"What type of sidecar file do you want to generate for non-destructive edits?",defaultValue:"XMP",validValues:c.strEnumValues(P.SidecarExtsEnum),persisted:!0}),t.writeMetadataToSidecars=new M.BooleanSetting({name:"writeMetadataToSidecars",key:"PS_WRITE_METADATA_TO_SIDECARS",category:M.SettingCategories.Sync,description:"Should changes made through the UI, like rotations, captions, and keywords, be written to a sidecar (which will be created if missing), or should metadata be saved to a copy of the original?",defaultValue:!0,persisted:!0})}(x=e.Settings||(e.Settings={})),e.envSuggestedPathsKey="SUGGESTED_PATHS",e.envSkipFiltersKey="PS_SKIP_FILTERS",e.envSkipFilters=y.truthy(s.env[e.envSkipFiltersKey]),e.DefaultPaths=Object.freeze(S.isWin?[s.env.SYSTEMROOT,r.join(s.env.SYSTEMROOT,"System32"),r.join(s.env.SYSTEMROOT,"System32","webm")]:["/usr/local/sbin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin"]),e.withDefaultPaths=E,e.pathWithDefaults=m.lazy(()=>E(s.env.PATH)),e.persistedSystemSettings=m.lazy(()=>l.values(x).filter(t=>t.opts.persisted&&M.SystemCategories.includes(t.category))),e.persistedLibrarySettings=m.lazy(()=>l.values(x).filter(t=>t.opts.persisted&&M.LibraryCategories.includes(t.category))),e.settingsForChildProcs=m.lazy(()=>l.values(x).filter(t=>t.addToChildProcs)),e.psenv=function(){const t=l.values(x).map(t=>t.key);return l.sortedKeys(l.filter(s.env,e=>"nodeEnv"===e||t.includes(e)))},e.childEnv=_,e.spawnOptions=function(t){const e=b.orElse(t,{});return Object.assign({},e,{env:_(e.env),detached:!1,shell:!1})};const k=x.nodeEnv.valueOrDefault;x.nodeEnv.value=k,x.nodeEnv.addToEnv(),e.isDev="development"===k,e.isTest="test"===k,e.isProd="production"===k},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(10),s=n(7),o=n(0),a=n(19),u=n(181);e.isString=function(t){return"string"==typeof t};const l={};function c(t,e){if(e<1)return"";for(null==l[t]&&(l[t]=t);e>l[t].length;)l[t]+=t;return l[t].substring(0,e)}function d(t,e){return t=a.toS(t),e=a.toS(e),t.startsWith(e)?t:e+t}function h(t){return t.sort((t,e)=>t.valueOf().localeCompare(e.valueOf()))}e.leftPad=function t(e,n,i){if("number"==typeof e&&e<0)return"-"+t(String(-e),n-1,i);const r=String(e);return c(i,n-r.length)+r},e.padding=c,e.padReplace=function(t,e,n,i){return t.substr(0,e)+c(i,n)+t.substr(e+n)},e.contains=function(t,e,n){return a.toS(t).indexOf(a.toS(e),n)>-1},e.count=function t(e,n,i=0){if(null==n||0===n.length)return 0;const r=e.indexOf(n,i);return-1===r?0:1+t(e,n,r+n.length)},e.replaceAll=function(t,e,n){return t.split(e).join(n)},e.maybeToS=function(t){return null==t?void 0:String(t)},e.mapParse=function(t,e){if(r.notBlank(t))try{return e(JSON.parse(t))}catch(t){}},e.trim=function(t){return t.map(a.toS).filter(t=>r.notBlank(t))},e.splitEvery=function(t,e,n){const i=Math.min(Math.ceil(t.length/e),o.orElse(n,()=>t.length))-1;return i<=0?[t]:[...s.times(i,n=>t.slice(n*e,(n+1)*e)),t.slice(i*e)]},e.stripPrefix=function(t,e){const n=a.toS(t),i=a.toS(e);return i.length>0&&n.startsWith(i)?n.slice(i.length):n},e.stripSuffix=function(t,e){const n=a.toS(t),i=a.toS(e);return i.length>0&&n.endsWith(i)?n.slice(0,-i.length):n},e.stripPreSuff=function(t,e,n){return(t=a.toS(t)).endsWith(n)&&t.startsWith(e)?t.slice(e.length,-n.length):t},e.ensurePrefix=d,e.ensureSuffix=function(t,e){return t=a.toS(t),e=a.toS(e),t.endsWith(e)?t:t+e},e.ellipsize=function(t,e=80){if(null==t)return"";const n=a.toS(t);return n.length<=e?n:n.slice(0,e-1)+"…"},e.gist=function(t,e=80,n=80){const i=a.toS(t),r=i.length-(e+n);return r<=0?i:i.slice(0,e).trim()+" …(+"+r+" chars)…"+i.slice(-n).trim()},e.capitalize=function(t){return r.blank(t)?t:t.charAt(0).toUpperCase()+t.slice(1)},e.equalsIgnoreCase=function(t,e){return null!=t&&null!=e&&a.toS(t).toLowerCase()===a.toS(e).toLowerCase()},e.startsWithIgnoreCase=function(t,e){return null!=t&&null!=e&&t.toLowerCase().normalize().startsWith(e.toLowerCase().normalize())},e.includesIgnoreCase=function(t,e){const n=a.toS(e).trim().toLowerCase().normalize();return!i.isEmpty(t)&&0!==n.length&&t.map(t=>a.toS(t).trim().toLowerCase().normalize()).filter(r.notBlank).some(t=>n.includes(t))},e.reverse=function(t){return null==t?t:t.split("").reverse().join("")},e.localeSort=h,e.sortChars=function(t){return h(t.split("")).join("")},e.longestPrefix=function(t,e){return i.greatestBy(e.filter(e=>t.startsWith(e)),t=>t.length)},e.stripAnsiEsc=function(t){return a.toS(t).replace(/\u001b\[[0-9;]+[a-z]/gi,"")};const f=/[\r\n]/;e.wrap=function t(e,n={maxLineLen:75,prefix:""}){if(e.includes("\n"))return i.flatten(e.split(f).map(e=>t(e,n)));if((e=d(a.toS(e).trim(),n.prefix)).length<=n.maxLineLen)return[e.trim()];const r=e.slice(0,n.maxLineLen+1).replace(/[\s-]/g," ").lastIndexOf(" "),s=r<=1?n.maxLineLen-(n.prefix.length+2):r;return[e.slice(0,s+1).trim(),...t(e.slice(s+1),n)]};const p=[[/[‘’]/g,"'"],[/[“”„«»”〃]/g,'"']];function m(t){return p.reduce((t,[e,n])=>t.replace(e,n),t).normalize()}e.dumbquote=m;const g=/^(['"]).+\1$/;e.stripQuotes=function(t){return r.blank(t)?t:(t=a.toS(t).trim(),null!=g.exec(m(t))&&(t=t.slice(1,-1).trim()),t)},e.wbrPath=function(t){return t.split(/(?<=[\\\/_,:=-]+)/).map(t=>u.escape(t.normalize())).join("<wbr>")},e.escapeRegExp=function(t){return a.toS(t).replace(/[?.()[\]{}*^+|$]/g,"\\$&")}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=new(n(182).EventEmitter);i.setMaxListeners(50),e.eventEmitter=i,e.emitBoom=function(){e.eventEmitter.emit("boom")},e.onBoom=function(t){e.eventEmitter.on("boom",t)},e.emitIdle=function(){e.eventEmitter.emit("idle")},e.onIdle=function(t){e.eventEmitter.on("idle",t)},e.emitPause=function(){e.eventEmitter.emit("pause")},e.onPause=function(t){e.eventEmitter.on("pause",t)},e.emitResume=function(){e.eventEmitter.emit("resume")},e.onResume=function(t){e.eventEmitter.on("resume",t)},e.emitBeforeExit=function(t,n){e.eventEmitter.emit("beforeExit",{reason:t,status:n})},e.onBeforeExit=function(t){e.eventEmitter.on("beforeExit",({reason:e,status:n})=>t(e,n))},e.emitClearCache=function(){e.eventEmitter.emit("clearCache")},e.onClearCache=function(t){e.eventEmitter.on("clearCache",t)},e.emitFileChanged=function(t){e.eventEmitter.emit("fileChanged",t)},e.onFileChanged=function(t){e.eventEmitter.on("fileChanged",t)},e.emitFocus=function(t,n){e.eventEmitter.emit("focus",t,n)},e.onFocus=function(t){e.eventEmitter.on("focus",t)},e.emitFatal=function(t,n){e.eventEmitter.emit("fatal",{message:t,error:n})},e.onFatal=function(t){e.eventEmitter.on("fatal",({message:e,error:n})=>t(e,n))},e.emitNonFatal=function(t,n){e.eventEmitter.emit("nonFatal",{message:t,error:n})},e.onNonFatal=function(t){e.eventEmitter.on("nonFatal",({message:e,error:n})=>t(e,n))},e.emitRpcServerChange=function(){e.eventEmitter.emit("rpcServerChange")},e.onRpcServerChange=function(t){e.eventEmitter.on("rpcServerChange",t)},e.readyToUpdate=!1,e.emitReadyToUpdate=function(){e.readyToUpdate=!0,e.eventEmitter.emit("readyToUpdate")},e.onReadyToUpdate=function(t){e.eventEmitter.on("readyToUpdate",t)},e.emitUpdateNow=function(){e.eventEmitter.emit("updateNow")},e.onUpdateNow=function(t){e.eventEmitter.on("updateNow",t)},e.emitVolumesChanged=function(){e.eventEmitter.emit("volumesChanged")},e.onVolumesChanged=function(t){e.eventEmitter.on("volumesChanged",t)}},function(t,e,n){"use strict";var i;Object.defineProperty(e,"__esModule",{value:!0}),function(t){t.isDefined=!1,t.isEmpty=!0,t.get=function(){},t.exists=()=>!1;const e=()=>t;t.map=e,t.flatMap=e,t.filter=e,t.forEach=e,t.getOrElse=function(t){return t()},t.orElse=function(t){return s(t())},t.zip1=e,t.zip2=e,t.zip3=e}(i||(i={})),e.None=i;class r{constructor(t){this.a=t,this.isDefined=!0,this.isEmpty=!1}get(){return this.a}exists(t){return t(this.a)}map(t){return new r(t(this.a))}flatMap(t){const e=t(this.a);return o(e)?e:s(e)}filter(t){return s(t(this.a)?this.a:void 0)}forEach(t){return t(this.a),this}getOrElse(t){return this.a}orElse(t){return this}zip1(t,e){return s(t).flatMap(t=>e(this.a,t))}zip2(t,e,n){return s(t).flatMap(t=>s(e).flatMap(e=>n(this.a,t,e)))}zip3(t,e,n,i){return s(t).flatMap(t=>s(e).flatMap(e=>s(n).flatMap(n=>i(this.a,t,e,n))))}}function s(t){return o(t)?t:null!=t?new r(t):e.None}function o(t){return t instanceof r||t===e.None}e.Some=r,e.Opt=s,e.isOpt=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(55),r=n(15);e.secondMs=1e3,e.minuteMs=60*e.secondMs,e.hourMs=60*e.minuteMs,e.dayMs=24*e.hourMs,e.weekMs=7*e.dayMs;const s=i.lazy(()=>new Intl.DateTimeFormat(void 0,{weekday:"short",year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric"}));e.fmtDateShort=function(t){return r.Opt(t).flatMap(t=>t instanceof Date?t.getTime():t).map(t=>s().format(t)).get()}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(6),s=n(15),o=n(18);function a(t){return"number"==typeof t&&isFinite(t)}function u(t,e){return a(t)?e(t):void 0}function l(t){return p(t,t=>{const e=Math.trunc(t);return 0===e?Math.abs(e):e})}function c(t,e){if(i.blank(t))return e.defaultValue;if(a(t))return e.nton(t);try{const n=e.ston(o.toS(t));return a(n)?e.nton(n):e.defaultValue}catch(t){return e.defaultValue}}function d(t,e){return c(t,Object.assign({defaultValue:void 0,nton:t=>l(t),ston:parseInt},e))}function h(t){return a(t)&&t>0}function f(t,e){return s.Opt(t).flatMap(t=>d(t)).flatMap(e).get()}function p(t,e){return s.Opt(t).filter(a).flatMap(e).get()}function m(t){return t<0?-Math.round(-t):Math.round(t)}function g(t,e){if(null==t)return 0;const n=Math.pow(10,e);return m(t*n)/n}e.isNumber=a,e.mapFinite=u,e.trunc=l,e.toInt=d,e.toFloat=function(t,e){return c(t,Object.assign({defaultValue:void 0,nton:t=>t,ston:parseFloat},e))},e.toGt0=function(t){const e=d(t);return null!=e&&e>0?e:void 0},e.gt0=h,e.gte0=function(t){return a(t)&&t>=0},e.mapInt=f,e.id=function(t){const e=d(t);return h(e)?String(e):void 0},e.mapIntOr=function(t,e,n){return r.orElse(f(t,e),n)},e.mapNumeric=p,e.round=m,e.toPrecisionMaybe=function(t,e){return u(t,t=>g(t,e))},e.toFixed=function(t,e){try{return p(t,t=>parseInt(t.toFixed(e)))}catch(t){return}},e.toPrecision=g,e.sigFigs=function(t,e){if(0===t||0===e)return 0;const n=Math.pow(10,e-m(Math.ceil(Math.log10(Math.abs(t)))));return m(t*n)/n},e.base2Ceil=function(t){return Math.pow(2,Math.ceil(Math.log2(t)))},e.base10Ceil=function(t){return Math.pow(10,Math.ceil(Math.log10(t)))},e.clamp=function(t,e,n){return a(n)?([t,e]=[Math.min(t,e),Math.max(t,e)],Math.max(t,Math.min(n,e))):m((t+e)/2)},e.times=function(t,e){if(!a(t))return[];const n=Math.round(t);return n<=0?[]:[...Array(n)].map((t,n)=>e(n))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.toS=function t(e){return null==e?"":"string"==typeof e?e:Array.isArray(e)?e.map(t).join(","):e.toString()}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(18);e.toS=i.toS},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(186),s=n(22),o=n(35),a=n(9),u=n(36),l=n(37),c=n(3),d=n(2),h=n(11),f=n(25),p=n(54),m=n(1),g=n(7),y=n(0),v=n(81),w=n(23),b=n(12),S=n(13),P=n(19),M=c.lazy(()=>m.mkLogger("ChildProcess"));function x(t){return a.pick(t,"pid","killed","connected","exitCode","signalCode")}function E(t,e,n){const r=new Date;let a=!1;return t.on("exit",()=>a=!0),o.setTimeout(()=>i(this,void 0,void 0,function*(){if(a)return;yield d.until(()=>g.gt0(t.pid),h.secondMs);const i=t.pid;return g.gt0(i)?v.addPid({pid:i,cmd:e,maxAgeMs:n,ppid:s.pid},r):void M().warn("newProc(): not writing pidfile, child_process has no pid",{cmd:e,cp:x(t)})}),w.isWin?500:250),t}function _(t,e,n,i){return E(r.execFile(t,e,b.spawnOptions(i)),t,n)}function k(t,e,n){return i(this,void 0,void 0,function*(){const i=y.orElse(n.quiet,!1),r=y.orElse(n.ignoreStderr,!1),s=y.orElse(n.ignoreExitCode,!1);let a="";M().debug("stdoutResult(): execFile",{cmd:t,args:e,opts:n});const l=yield _(t,e,n.timeout,y.without(n,"timeout","quiet","disconnect","ignoreStderr","ignoreExitCode"));if(!0===n.disconnect)return l.disconnect(),{result:"",pid:l.pid};const c=JSON.stringify({cmd:t,args:e}),d=new u.Deferred(c);o.setTimeout(()=>{d.pending&&M().warn("stdoutResult(): SLOW COMMAND",{cmd:t,args:e})},n.timeout/3).unref(),d.setTimeout(n.timeout);const h=(r,s)=>{f.isIgnorableError(s)||(null!=l.pid&&T(l),i||M().warn("stdoutResult(): "+r,{cmd:t,args:e,opts:n,error:s}),d.pending&&d.reject(s))};try{l.on("error",t=>h("on(error)",t)),l.on("close",n=>{const r=Date.now()-d.start,o=0!==n?"warn":r<1e3?"trace":r<3e3?"debug":"info";i||M().log(o,"stdoutResult(): on(close)",{cmd:t,code:n,args:e,elapsed:r,result:S.gist(a,160,160)}),s||0===n?d.resolve({result:a,code:n,pid:l.pid}):d.reject(new Error("non-zero exit code: "+JSON.stringify({code:n,cmd:t,args:e})))}),l.stdin.end(),l.stdout.on("data",t=>y.map(t,t=>{a+=t.toString()})),l.stderr.on("error",t=>h("stderr(error)",t)),l.stderr.on("data",t=>r?M().warn("stdoutResult(): stderr(data): "+P.toS(t)):h("stderr(data)",t))}catch(t){h("try/catch",t)}return d.promise})}function T(t,e=30*h.secondMs){return i(this,void 0,void 0,function*(){if(null==t)return!1;const n=t.pid;if(M().debug("endProcess("+n+")",{killed:t.killed,connected:t.connected}),!t.killed){if(n<=0)return M().warn("endProcess(): asked to end invalid pid",x(t)),!1;if(n===s.pid)return M().warn("endProcess(): asked to end MY pid",x(t)),!1;y.Try(()=>t.kill())}return yield l.delay(250),yield p.closeStreams(t),t.connected&&y.Try(()=>t.disconnect()),y.Try(()=>t.unref()),(yield O(n,e))?(M().debug("endProcess(): exitted",x(t)),!0):(yield v.kill(n,!0).catch(t=>{M().warn("endProcess(): kill("+n+",true) failed: "+t)}),O(n,5e3))})}function O(t,e){return d.until(()=>d.thenNot(v.pidExists(t)),e)}e.spawn=function(t,e,n,i){return M().debug("spawn()",{command:t,args:e,maxAgeMs:n,options:i}),E(r.spawn(t,e,b.spawnOptions(i)),t,n)},e.execFile=_,e.stdout=function(t,e,n){return k(t,e,n).then(t=>t.result)},e.stdoutResult=k,e.endProcess=T,e.waitForExit=O},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(9),s=n(33),o=n(4),a=n(72),u=n(11),l=n(14),c=n(1),d=n(73),h=n(7),f=n(0),p=n(12),m=n(3),g=n(2),y=n(50),v=m.lazy(()=>c.mkSafeLogger(a.red("Endable")));e.EndableWrapper=class{constructor(t,e,n){this.name=t,this._onEnd=e,this._isEnded=n,this._ended=!1}get ended(){return f.mapOr(this._isEnded,t=>t(),()=>!1)||this._ended}end(){return this._ended=!0,this._onEnd()}};const w=new d.MultiMap;y.setUnrefInterval(()=>E(),1*u.minuteMs);const b=new Map,S=5*u.secondMs;function P(t,e){return w.add(t,e),e}e.EndableRanks=s.strEnum("first","service","cleanup","db","logger"),e.addFirstEndable=function(t){return P(e.EndableRanks.first,t)},b.set(e.EndableRanks.first,5*u.secondMs),e.addServiceEndable=function(t){return P(e.EndableRanks.service,t)},e.addCleanupEndable=function(t){return P(e.EndableRanks.cleanup,t)},b.set(e.EndableRanks.cleanup,1*u.minuteMs),e.addDbEndable=function(t){return P(e.EndableRanks.db,t)},e.addLoggerEndable=function(t){return P(e.EndableRanks.logger,t)},b.set(e.EndableRanks.logger,10*u.secondMs),e.addEndable=P;let M=!1;function x(t,e=g.DefaultTryAllTimeoutMs){if(null!=t&&!t.ended)return v().debug(a.magenta(t.name+" ending...")),g.thenOrTimeout(t.end(),e,()=>v().warn(a.magenta(t.name+".end() timed out")),()=>v().debug(a.magenta(t.name+".end() completed"))).catch(e=>{v().warn(a.magenta(t.name+".end() rejected: ")+e)})}function E(){w.filterInPlace((t,e)=>!e.ended),v().debug("vacuumEndables()",w.entriesArray().map(([t,e])=>[t,e.map(t=>t.name)]))}e.ending=function(){return M},e.setEnding=function(t){if(!p.isTest)throw new Error("cannot set ending");M=t},e.end=x,l.onBeforeExit(()=>M=!0),e.endEndables=m.lazy(()=>i(this,void 0,void 0,function*(){p.isTest||(M=!0),E();for(const t of r.keys(e.EndableRanks)){const e=f.orElse(w.get(t),[]);if(o.isNotEmpty(e)){v().debug(a.magenta("endEndables(): ending "+t));const n=h.firstGt0(b.get(t),S);yield Promise.all(e.map(t=>x(t,n)))}}}))},function(t,e){t.exports=require("process")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(43),r=n(45),s=n(22),o=n(8),a=n(3),u=n(29),l=r.platform();e.inspectFlag=s.argv.includes("--inspect")||u.truthy(s.env.NODE_INSPECT),e.isWin=l.startsWith("win"),e.isWinStore=e.isWin&&u.truthy(s.windowsStore),e.isWinPortable=e.isWin&&o.notBlank(s.env.PORTABLE_EXECUTABLE_DIR),e.isMac="darwin"===l,e.isMacStore=e.isMac&&u.truthy(s.mas),e.isLinux="linux"===l,e.isLinuxAppImage=e.isLinux&&o.notBlank(s.env.APPIMAGE),e.isLinuxSnap=e.isLinux&&o.notBlank(s.env.SNAP_USER_DATA),e.isPosix=e.isMac||e.isLinux,e.isDocker=a.lazy(()=>{try{return e.isLinux&&i.readFileSync("/proc/1/cgroup").toString().includes("/docker/")}catch(t){return console.warn("isDocker: failed to read /proc/1/cgroup: "+t),!1}}),e.platformName=e.isWin?"win":e.isMac?"mac":e.isLinux?"linux":l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(16),r=n(11);e.mountpointsTtlMs=15*r.secondMs,e.dfTtlMs=5*i.minuteMs,e.cmdTimeoutMs=25*r.secondMs,e.longTtlMs=1*r.hourMs},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(8),s=n(15),o=n(21),a=n(13),u=n(19);e.asError=function(t){if(r.blank(t))throw new Error("undefined error");if(t instanceof Error)return t;if(Array.isArray(t)){const e=t[0];return e instanceof Error?(t.length>1&&(e.errors=t.slice(1)),e):new Error(t.map(t=>u.toS(t)).filter(r.notBlank).join(", "))}return new Error(u.toS(t))},e.FatalErrorFlag="¹",e.NonRetriableErrorFlag="²",e.IgnorableErrorFlag="³",e.PleaseSendErrorFlag="⁴",e.ErrorFlags=[e.FatalErrorFlag,e.NonRetriableErrorFlag,e.IgnorableErrorFlag,e.PleaseSendErrorFlag];const l=new RegExp("["+e.ErrorFlags.join("")+"]","g");function c(t){return t instanceof f?t.fatal:!h(t).includes(e.FatalErrorFlag)}function d(t){return t instanceof Error?h(t):u.toS(t)}function h(t){return null==t?h(new Error("undefined error")):r.notBlankOr(i.compactBlanks([t.name,t.message]).join(": "),u.toS(t))}e.removeErrorFlags=function(t){return t.replace(l,"")},e.hasErrorFlag=function(t){return e.ErrorFlags.some(e=>t.includes(e))},e.isFatalError=c,e.isRetriableError=function(t){return!c(t)&&!h(t).includes(e.NonRetriableErrorFlag)&&(!(t instanceof f)||t.retriable)},e.isSendableError=function(t){return h(t).includes(e.PleaseSendErrorFlag)},e.isIgnorableError=function(t){return o.ending()||!c(t)&&a.includesIgnoreCase([e.IgnorableErrorFlag,"diskutil: interrupted","net::ERR_","debugger listening on","for help","https://nodejs.org/en/docs/inspector","debugger attached"],d(t))},e.maybeErrorToS=d,e.errorToS=h,e.throws=function(t){try{return t(),!1}catch(t){return!0}},e.stack=function t(){const e={};return Error.captureStackTrace(e,t),e.stack.split(/\n(?:\s*at\s+)?/).slice(1)},e.trimErrorMessage=function(t){return u.toS(t).trim().replace(/^Error: /i,"").trim().replace(/^[0-9T\.: -]+Z? /i,"").replace(/^error /i,"").trim()},e.cleanError=function(t,e){return u.toS(t).split(/\r?\n/).map(t=>a.stripPrefix(t,e)).map(t=>t.replace(/: ?/,"")).filter(r.notBlank).join(", ")};class f extends Error{constructor({cause:t,message:n,retriable:o=!0,ignorable:l=!1,fatal:c=!1}){super(function(t,n,o,l,c){const d=[t];s.Opt(n).flatMap(t=>t.message).flatMap(t=>a.stripPrefix(t,"Error: ")).forEach(t=>d.push(t));const h=d.map(t=>u.toS(t).trim()).filter(r.notBlank).join(": "),f=[];c||o||f.push(e.NonRetriableErrorFlag);l&&!c&&f.push(e.IgnorableErrorFlag);c&&f.push(e.FatalErrorFlag);i.isNotEmpty(f)&&f.unshift(" ");return h+f.join("")}(n,t,o,l,c)),this.cause=t,this.retriable=o,this.fatal=c}}e.WrappedError=f},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(65),r=n(79),s=n(5),o=n(8),a=n(46),u=n(6),l=n(17),c=n(15),d=n(4),h=n(3),f=n(10),p=n(98),m=n(7),g=n(0),y=n(13),v=n(19);function w(t,e=2){return null==t?"":y.leftPad(t,e,"0")}function b(t){return null!=t&&("string"!=typeof t&&(!String(tt(t)).startsWith("1970-01-01T00:00:00")&&(!!S(z(t))&&(!!P(q(t))&&(t instanceof r.DateTime?t.isValid:M(z(t),q(t),W(t)))))))}function S(t){return m.within(e.minYear,e.maxYear,t)}function P(t){return m.within(1,12,t)}function M(t,e,n){return null!=n&&r.DateTime.fromObject({year:t,month:e,day:n}).isValid}function x(t,e,n){return S(t)&&(null==e||P(e)&&(null==n||M(t,e,n)))}e.validDate=b,e.minYear=1826,e.maxYear=(new Date).getFullYear()+2,e.validYear=S,e.validMonth=P,e.validDay=M,e.validYMD=x;class E{constructor(t,e,n){this.year=t,this.month=e,this.day=n}static for(t,e,n){return x(t,e,n)?new E(t,e,n):void 0}static localToday(){return it(new Date)}toString(){return s.compact([this.year,this.month,this.day]).map(t=>w(t)).join("-")}toISOString(){return this.toString()}toDateTime(){return r.DateTime.fromObject(this)}}e.FuzzyDate=E;class _{constructor(t,e,n,i,r){this.monthsToMonth=t,this.re=e,this.yearIndex=n,this.monthIndex=i,this.dayIndex=r}apply(t){const e=this.re.exec(t);if(null!=e){const t=parseInt(e[this.yearIndex],10),n=this.month(e),i=null==this.dayIndex?void 0:parseInt(e[this.dayIndex],10);return E.for(t,n,i)}}month(t){if(null==this.monthIndex)return;const e=t[this.monthIndex].toLowerCase();return this.monthsToMonth.has(e)?this.monthsToMonth.get(e):m.toInt(e)}}const k="((?:19|20)[0-9]{2})",T="(1[0-2]|0?[1-9])",O="([1-3][0-9]|0?[1-9])",D="([0-5][0-9])",F="([-\\.\\,:_/ |])?";function C(t,e){const n=e.exec(t);if(null==n)return;const i=[...n.slice(1)],[s,o,a,u,l,h]=i.splice(0,6).map(t=>m.toInt(t)),f=m.clamp(0,999,1e3*m.toFloat(i.shift(),{defaultValue:0})),p=H(function(t,e){if(d.isEmpty(t))return e;const[n,i]=t.splice(0,2),[r,s]=t.splice(0,2).map(t=>m.toInt(t));return y.equalsIgnoreCase(n,"z")?0:d.anyNotDefined([i,r,s])?e:("-"===i?-1:1)*(60*r+s)}(i));return c.Opt(r.DateTime.fromObject({year:s,month:o,day:a,hour:u,minute:l,second:h,millisecond:f,zone:p})).filter(t=>t.isValid).flatMap(t=>Y(t,p)).get()}const I=new RegExp([k,"(1[0-2]|0[1-9])","([1-3][0-9]|0[1-9])","(1[0-9]|2[0-3]|0[0-9])",D,D,"(?:(\\.[0-9]+))?"].join("[-:_ ]?")+"(?:(Z)|(?:([+-])([01][0-9]):?([0-5][0-9])))?","i");function A(t){return C(t,I)}function L(t,e=!0){return f.mapNotBlank(t,t=>g.firstTrueThunk([()=>p.DateInterval.parse(t),()=>i.ExifDateTime.fromEXIF(t),()=>e?i.ExifDate.fromEXIF(t):void 0,()=>A(t),()=>e?i.ExifDate.fromEXIF(t):void 0,()=>e?j().parseYMD(t):void 0],t=>b(t)))}e.parseFuzzyDatetime=A,e.dateTimeBetween=function(t,e){return t.until(e).divideEqually(2)[0].end},e.agoMs=function(t){return l.mapNumeric(X(t),t=>Date.now()-t)},e.parseDatedWithTime=function(t){return L(t,!1)},e.parseDated=L;class R{constructor(t){this.locale=t,this.monthsToMonth=new Map,this.ymdPatterns=[],this.ymPatterns=[],this.setup()}parseYMD(t){return d.first(this.ymdPatterns,e=>e.apply(t))}addParser(t,e,n,i){const r=new _(this.monthsToMonth,new RegExp(t+"(?:$|[^\\d])","i"),e,n,i);null!=i&&null!=n?this.ymdPatterns.push(r):null!=n&&this.ymPatterns.push(r)}setup(){["short","long"].forEach(t=>{const e=new Intl.DateTimeFormat(this.locale,{month:t});m.times(12,t=>{const n=e.format(new Date(2017,t));this.monthsToMonth.set(n.toLowerCase(),t+1)})});const t="("+d.sort([...this.monthsToMonth.keys()]).join("|")+")";this.addParser(k+F+T+"\\2"+O,1,3,4),this.addParser(k+F+t+"\\2"+O,1,3,4),this.addParser(t+F+O+",?\\2"+k,4,1,3),this.addParser(O+F+t+",?\\2"+k,4,3,1),this.addParser(t+F+k,3,1),this.addParser(k+F+t,1,3)}extractDateFromPath(t){B.forEach(e=>{d.startsWith(t,e)&&t.splice(0,e.length)}),t=t.filter(e=>o.notBlank(e)&&null==t[0].match(N));const e=[...t].reverse();return g.firstThunk(()=>d.first(e,t=>this.parseYMD(t)),()=>this.parseYMD(t.join(" ")),()=>this.parseYMD(e.join(" ")),()=>d.first(this.ymPatterns,e=>e.apply(t.join(" "))),()=>d.first(this.ymPatterns,t=>t.apply(e.join(" "))))}}e.FuzzyDateParser=R;const N=/^((DCIM)|(DSC[_0F]?|IMG_|GOPRO|MOV_|P)\d+)$/i,j=h.lazy(()=>new R(void 0)),B=[];function z(t){return g.map(t,t=>t instanceof Date?t.getFullYear():t.year)}function q(t){return g.map(t,t=>t instanceof Date?t.getMonth()+1:t.month)}function W(t){return g.map(t,t=>t instanceof Date?t.getDate():t.day)}function V(t){return st(t)?t instanceof Date?t.getHours():t.hour:void 0}function U(t){return st(t)?t instanceof Date?t.getMinutes():t.minute:void 0}function G(t){return st(t)?t instanceof Date?t.getSeconds():t.second:void 0}function $(t){return st(t)?t instanceof Date?t.getMilliseconds():t.millisecond:void 0}function J(t){return g.map(G(t),e=>{const n=g.orElse($(t),0);let i=(e+n/1e3).toString();for(e<10&&(i="0"+i),0===n&&(i+=".");i.length<6;)i+="0";return i})}function H(t){if(null==t)return;if(0===t)return"UTC";const e=t<0?"-":"+",n=15*l.round(t/15),i=Math.abs(n),r=Math.floor(i/60),s=Math.floor(Math.abs(i%60));return`UTC${e}${w(r)}:${w(s)}`}function Q(t){return!l.isNumber(t)&&(t instanceof i.ExifDateTime?null!=t.tzoffsetMinutes:t instanceof r.DateTime&&null!=t.offsetNameShort)}function K(t){return t instanceof r.DateTime?g.map(t.offsetNameShort,()=>H(t.offset)):t instanceof i.ExifDateTime?H(t.tzoffsetMinutes):void 0}function Y(t,e){const n=X(t);if(null==n||!st(t))return;const r=o.blank(e)?Q(t)?K(t):void 0:e,s=f.mapNotBlank(r,t=>ot(n,t));return null==e||null!=s?g.map(z(t),e=>g.map(q(t),n=>g.map(W(t),r=>g.map(V(t),o=>new i.ExifDateTime(e,n,r,o,g.orElse(U(t),0),g.orElse(G(t),0),$(t),s,t.rawValue))))):void 0}function Z(t){if(null==t)return;if("number"==typeof t)return new Date(t);if(t instanceof Date)return t;if(t instanceof r.DateTime)return t.toJSDate();if(t.toDate)return t.toDate();if(m.gt0(t.year)&&m.gt0(t.month)&&m.gt0(t.day))return new Date(t.year,g.orElse(t.month,1)-1,t.day,12);const e=v.toS(t);return o.notBlank(e)?g.map(et(e),Z):void 0}function X(t){if(null!=t)return l.isNumber(t)?t:t instanceof Date?t.getTime():t instanceof r.DateTime?t.toMillis():g.map(Z(t),t=>t.getTime())}function tt(t,e=!0){if(t instanceof p.DateInterval)return t.toString(e);const n=l.isNumber(t)?new Date(t):t,i=nt(n);if(!st(n))return i;const r=`${w(V(n))}:${w(U(n))}:${J(n)}`,s=g.map(e&&Q(t)?K(n):void 0,t=>"UTC"===t?"Z":y.stripPrefix(t,"UTC"));return i+"T"+r+v.toS(s)}function et(t,e){return"string"!=typeof t||o.blank(t)?void 0:c.Opt(i.ExifDateTime.fromISO(t,e)).orElse(()=>i.ExifDate.fromISO(t)).orElse(()=>i.ExifTime.fromEXIF(t)).get()}function nt(t){return s.compact([z(t),q(t),W(t)]).map(t=>w(t)).join("-")}function it(t){return g.map(t,t=>g.map(z(t),e=>new E(e,q(t),W(t))))}function rt(t,e){const[n,i]=[t,e].map(X);return null==n||null==i?void 0:n-i}function st(t){return t instanceof Date||t instanceof i.ExifDateTime||t instanceof r.DateTime}function ot(t,e){const n=r.Info.normalizeZone(e);return n.isValid?n.offset(t):void 0}e.addIgnorableSubpath=function(t){B.push(t)},e.clearIgnorableSubpaths=function(){B.length=0},e.extractDateFromPath=function(t){return j().extractDateFromPath(t)},e.parseYMD=function(t){return j().parseYMD(t)},e.isDated=function(t){return t instanceof E||t instanceof i.ExifDate||t instanceof i.ExifDateTime||t instanceof Date||t instanceof p.DateInterval||t instanceof r.DateTime},e.getYear=z,e.getMonth=q,e.getDay=W,e.getHour=V,e.getMinute=U,e.getSecond=G,e.getMillisecond=$,e.hasSeconds=function(t){return st(t)&&(m.gt0(U(t))||m.gt0(G(t))||m.gt0($(t)))},e.getSecMs=J,e.zoneOffsetToName=H,e.hasZoneOffset=Q,e.getZoneName=K,e.toDateTime=Y,e.toDate=Z,e.datedToMillis=X,e.datedToISO=tt,e.fromISO=et,e.datedToYMD=nt,e.toFuzzyDate=it,e.sameDay=function(t,e){return a.eql(it(t),it(e))},e.diffMillis=rt,e.closeTo=function(t,e,n){return u.mapOr(rt(t,e),t=>Math.abs(t)<n,()=>!1)},e.gtDate=function(t,e){const n=X(t),i=X(e);return null!=n&&null!=i&&n>i},e.nowish=function(t,e=2500){const n=X(t),i=Date.now();return m.within(i-e,i+e,n)},e.dateBetween=function(t,e,n=1,i=1){if(null==X(t)||null==X(e))return;const[s,o]=[t,e].map(t=>X(t)).sort(),a=(o-s)/(i+1),u=K(t),l=u===K(e)?u:void 0,c=r.DateTime.fromMillis(s+a*n,{zone:l});return[t,e].some(t=>!st(t))?it(c):c},e.hasTime=st,e.zoneToOffset=ot},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(9),r=n(84);var s=n(9);e.tap=s.tap,e.atap=function(t,e){return r.isPromise(t)?r.thenTap(t,e):i.tap(t,e)},e.amap=function(t,e){return r.isPromise(t)?t.then(t=>e(t)):e(t)},e.awaitAll=function(t){return t.some(t=>r.isPromise(t))?Promise.all(t):t}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(30),r=n(6),s=n(17),o=n(18),a=n(4),u=n(10),l=n(23),c=n(13),d=i.posix;function h(t){return i.sep===d.sep?t:d.sep===i.sep?t:t.split(i.sep).join(d.sep)}e.posix2native=function(t,e){if(i.sep===d.sep)return t;const n=u.notBlank(e)?i.sep+i.sep+e+i.sep:"",r=t.split(d.sep);return c.equalsIgnoreCase(r[0],e)&&r.unshift(),n+r.join(i.sep)},e.native2posix=h;const f=/^([A-Z]:)[\\\/]?(.*)$/i;e.resolve=function(...t){const e=i.join(...t);return i.resolve(l.isWin?function(t){const e=f.exec(t);return null!=e?e[1].toUpperCase()+"\\"+e[2]:t}(e):e)};const p=/(\.?.*?)(\.[a-z]{1,10}\.(?:gz|z|xz|bz2))$/i;function m(t){const e=p.exec(t);return null!=e&&u.notBlank(e[2])?e[2]:i.extname(t)}function g(t){return c.stripPrefix(t,i.sep).split(i.sep)}e.parse=function(t){const e=i.parse(t),n=m(e.base),r=c.stripSuffix(e.base,n);return Object.assign({},e,{ext:n,name:r})},e.extname2=m,e.containedBy=function(t,e){return u.notBlank(t)&&u.notBlank(e)&&(t===e||t.startsWith(c.ensureSuffix(e,d.sep)))},e.containedByNativePath=function(t,e){return u.notBlank(t)&&u.notBlank(e)&&(t===e||t.startsWith(c.ensureSuffix(e,i.sep)))},e.pathnames=g,e.posixPathFrom=function(t,e){return t.nativePath===e.nativePath?"":c.stripPrefix(h(e.nativePath),c.ensureSuffix(h(t.nativePath),"/"))},e.posixPathFromGrandparent=function(t){return g(t).slice(-3).join("/")};const y=/(.*?)(?:-(\d+)|\((\d+)\))$/;e.nameWithoutCount=function(t){return r.mapOr(o.toS(t).match(y),t=>t[1],()=>t)},e.countFromName=function(t){return r.map(o.toS(t).match(y),t=>a.first([t[2],t[3]],s.toInt))}},function(t,e,n){"use strict";function i(t){if("boolean"==typeof t)return t;if(null==t)return!1;const e=String(t).toLowerCase();return["true","1"].includes(e)}function r(t){if("boolean"==typeof t)return!t;if(null==t)return!1;const e=String(t).toLowerCase();return["false","0"].includes(e)}Object.defineProperty(e,"__esModule",{value:!0}),e.isBoolean=function(t){return"boolean"==typeof t},e.truthy=i,e.toBoolean=function(t){return!!i(t)||!r(t)&&void 0},e.boolToInt=function(t){return i(t)?1:0},e.falsy=r,e.or=function(t){return t.some(t=>i(t))},e.and=function(t){return t.every(t=>i(t))}},function(t,e){t.exports=require("path")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(65),s=n(5),o=n(16),a=n(46),u=n(9),l=n(15),c=n(39),d=n(4),h=n(21),f=n(58),p=n(3),m=n(2),g=n(132),y=n(10),v=n(63),w=n(11),b=n(14),S=n(228),P=n(32),M=n(114),x=n(163),E=n(86),_=n(1),k=n(0),T=n(23),O=n(12),D=n(19),F=n(82),C=n(76),I=n(236),A=n(237),L=n(238),R=n(239),N=n(94),j=n(240),B=n(241),z=n(115),q=n(150),W=_.mkLogger("ExifTags");let V=1;e.setMaxProcs=function(t){return i(this,void 0,void 0,function*(){V=t;const e=U.prior();null!=e&&e.options.maxProcs!==t&&(U.clear(),yield e.end())})};const U=p.lazy(()=>{return g.observeBatchCluster(new r.ExifTool({maxProcs:V,cleanupChildProcs:!1}),"exiftool",h.EndableRanks.service)});function G(){const t=U();return t.ended?U.refresh():t}e.exiftool=G,e.shutdownExiftool=function(t){return k.map(U.prior(),e=>e.end(t))},e.extractBinaryTag=function(t,e,n){return G().extractBinaryTag(t,e,n)};const $=new v.BoundedMap(3*w.minuteMs,1024,!0);function J(){$.clear(),e.rawTagsCache.clear()}e.rawTagsCache=new v.BoundedMap(3*w.minuteMs,1024,!0),e.clearTagsCache=J,b.onClearCache(J),b.onFileChanged(t=>{y.blank(t)?J():($.deleteIf(e=>e.startsWith(t)),e.rawTagsCache.deleteIf(e=>e.startsWith(t)))});const H=["Directory","FileAccessDate","FileInodeChangeDate","FileModifyDate","FileName","FilePermissions","FileSize","FileType","FileTypeExtension","MIMEType","RAFVersion","SourceFile"];function Q(t){return i(this,void 0,void 0,function*(){if(null==t)return;const e=P.PosixFile.for(t);return(yield e.isEmpty())?void 0:$.getOrSet(e.nativePath,()=>i(this,void 0,void 0,function*(){const t=yield w.thenElapsed(m.thenMap(X(e),t=>it(e,t)));return W.info("readTags("+e+") in "+t.elapsedMs+" ms"),t.result}))})}function K(t){return i(this,void 0,void 0,function*(){return $.get(String(t))})}function Y(t){return i(this,void 0,void 0,function*(){if(y.blank(t))return;const e=P.PosixFile.for(t);return m.firstDefinedPromise(()=>m.thenMap(K(e),t=>t.MIMEType),()=>m.thenMap(S.readFileType(e.nativePath),t=>t.mime),()=>m.thenMap(X(e,!1),t=>t.MIMEType))})}function Z(t,e="_original"){return i(this,void 0,void 0,function*(){return t.sibling(t.base+e).saveIfNewOrDelete(t.name+e+t.ext)})}function X(t,e=!0){return i(this,void 0,void 0,function*(){const n=yield nt(t.nativePath);if(null==n||!e)return n;const r=[],o=m.thenMap(t.jsonSidecar(),t=>i(this,void 0,void 0,function*(){const e=yield j.readJsonSidecar(t);return null!=e&&r.push(t.base),e})),a=m.thenMap(t.sidecars(),t=>m.tuples(t,t=>nt(t.nativePath)));let l=Object.assign({},n,yield o);for(const[t,e]of s.toA(yield a))r.push(e.base),l=Object.assign({},l,u.compactValues(k.without(t,...H)));return d.isNotEmpty(r)&&(l.sidecars=r),l})}e.sidecarEql=function(t,e){return i(this,void 0,void 0,function*(){const n=t=>m.thenMap(X(t,!1),t=>k.without(t,...H));return(yield a.eqlAsync(t.clear().sha(),e.clear().sha()))||(yield a.eqlAsync(n(t),n(e)))})},e.readTags=Q,e.cachedTags=K,e.capturedAt=function(t){return i(this,void 0,void 0,function*(){return m.thenMap(Q(t),t=>t.capturedAt)})},e.mimetype=Y,e.rotation=function(t){return i(this,void 0,void 0,function*(){return m.thenMap(Q(t),t=>t.rotation)})},e.isMimetype=function(t,e){return i(this,void 0,void 0,function*(){const n=yield Y(t);return null!=n&&e.has(n)})},e.exifUid=function(t){return i(this,void 0,void 0,function*(){return m.thenMap(Q(t),t=>t.exifUid)})},e.exifUid4=function(t){return i(this,void 0,void 0,function*(){return m.thenMap(Q(t),I.extractUid4)})},e.exifUid5=function(t){return i(this,void 0,void 0,function*(){return l.Opt(yield Q(t)).flatMap(t=>A.extractUidPojo5(t,t.capturedAt)).flatMap(A.serializeUidPojo5).get()})},e.exifUid6=function(t){return i(this,void 0,void 0,function*(){return l.Opt(yield Q(t)).flatMap(t=>L.extractUidPojo6(t,t.capturedAt)).flatMap(C.serializeUidPojo).get()})},e.exifUid7=function(t){return i(this,void 0,void 0,function*(){return l.Opt(yield Q(t)).flatMap(t=>R.extractUidPojo7(t,t.capturedAt)).flatMap(C.serializeUidPojo).get()})},e.exifUids=function(t){return i(this,void 0,void 0,function*(){return k.map(yield Q(t),t=>y.compactBlanks([I.extractUid4(t),k.map(A.extractUidPojo5(t,t.capturedAt),A.serializeUidPojo5),k.map(L.extractUidPojo6(t,t.capturedAt),C.serializeUidPojo),k.map(R.extractUidPojo7(t,t.capturedAt),C.serializeUidPojo)]))})},e.duration=function(t){return i(this,void 0,void 0,function*(){return m.thenMap(Q(t),t=>t.Duration)})},e.dimensions=function(t){return i(this,void 0,void 0,function*(){return m.thenMap(Q(t),t=>t.dimensions)})},e.moveOriginal=Z,e.writeTags=function(t,e){return i(this,void 0,void 0,function*(){const n=yield t.sidecar(),i=O.Settings.writeMetadataToSidecars.valueOrDefault||(yield n.exists())?n:t;yield G().write(i.nativePath,e);const r=yield Z(i);return s.uniq([t.nativePath,i.nativePath]).forEach(b.emitFileChanged),i.clearThisAndParent(),{original:r,dest:i}})},e.readRawTags=X;const tt=new f.Latch,et=new f.Latch;function nt(t){return i(this,void 0,void 0,function*(){return e.rawTagsCache.getOrSet(t,()=>i(this,void 0,void 0,function*(){W.debug("readRawTags("+t+")");const e=tt.pending;e?tt.resolve():yield et.promise;const n=yield m.thenOrTimeout(w.thenElapsed(G().read(t).catch(e=>{W.info("Failed to read "+t,e)})),30*o.secondMs);return e&&et.resolve(),k.map(n,e=>(W.debug("read("+t+") in "+e.elapsedMs+"ms"),k.map(e.result,t=>{const n=y.compactBlanks([t.Error,...k.orElse(t.errors,[]),t.Warning].map(D.toS));return d.isNotEmpty(n)&&(t.problems=n),t.exiftoolMs=e.elapsedMs,t})))}))})}function it(t,e){return i(this,void 0,void 0,function*(){if(null==e)return;const n=e.MIMEType,i=t.nativePath;if(y.blank(n))return void W.debug("No mimetype for "+t);const r=t.nativePath.startsWith(c.App.getPath("temp"))||t.pathnames.includes(".photostructure");r||(yield q.inferMakeAndModel(t,e)),e.Make=B.make(e.Make),e.Model=B.model(e.Make,D.toS(e.Model));const s=yield F.extractCapturedAt(t,e,r);if(null==s)return void W.info("No capturedAt for "+t);const o=N.extractExposureSettings(e),a=R.extractUidPojo7(e,s,o),u=k.map(a,C.serializeUidPojo),l=k.firstDefined(z.extractRotation(e),0);let d=z.extractSizeInfo(e,l);if(null==d&&E.vlcSupportedMimeType(n)){W.debug("Trying to extract video dimensions from frame...");const e=yield x.extractVideoFrame(P.PosixFile.for(t),n);null!=e&&(d=yield m.thenMap(Q(e),t=>z.extractSizeInfo(t,l)))}if(null==d)return void W.info("No size info for "+i);const h=Object.assign({mimetype:n,exposureSettings:o,rotation:l},d,{capturedAt:s,geohash:M.geohash_num(e.GPSLatitude,e.GPSLongitude),exifUidPojo:a,exifUid:u,tz:e.tz});return W.debug("parsedTags",Object.assign({nativePath:i},h,{tzSource:e.tzSource,capturedAt:k.map(s,t=>({date:t.date.toString(),src:t.src}))})),Object.assign({},e,h)})}T.isWin||(tt.resolve(),et.resolve()),e.parseTags=it},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(30),s=n(109),o=n(5),a=n(6),u=n(17),l=n(15),c=n(70),d=n(4),h=n(3),f=n(2),p=n(10),m=n(20),g=n(11),y=n(14),v=n(1),w=n(48),b=n(73),S=n(23),P=n(12),M=n(13),x=n(103),E=n(49),_=n(40),k=n(34),T=n(135),O=n(160),D=n(161),F=n(140),C=n(28),I=new k.FileCache;e.groupByMountpoint=function(t,e){return b.groupBy(t,t=>a.map(t.bestMountpoint(e),t=>t.nativePath))},e.coallesce=function(t,e){const n=b.groupBy(t,t=>a.map(t.bestMountpoint(e),t=>t.nativePath));return o.sortBy(d.flatten(o.toA(n.values()).map(t=>d.contextFilter(o.sort(t),(t,e,n)=>null==n||!t.isDescendantOf(n)))),t=>t.pathnames)};class A extends k.BaseFile{constructor(t,e){super(t,e),this.nativePath=t,this.pflog=h.lazy(()=>v.mkLogger("PosixFile("+this.nativePath+")")),this.uriObject=h.lazy(()=>T.file2voluri(this)),this.uri=h.lazy(()=>f.thenMap(this.uriObject(),t=>s.format(t))),this.fileuri=h.lazy(()=>T.file2fileuri(this)),this.mountpoint=h.lazy(()=>f.thenMap(_.mountpoints(),t=>this.bestMountpoint(t.map(t=>this.for(t))))),this.etag=h.lazy(()=>f.thenMap(this.stat(),t=>[t.size,t.mtime.getTime()].map(t=>w.Radix58.encode(t)).join("-"))),this.ignorable=h.lazy(()=>i(this,void 0,void 0,function*(){return(yield this.isDirectory())?D.ignorableDirectory(this):D.ignorableFile(this)})),this.hidden=h.lazy(()=>O.hidden(this)),this.isMountpoint=h.lazy(()=>i(this,void 0,void 0,function*(){return(yield this.isDirectory())&&(yield f.thenMapOr(_.mountpoints(),t=>t.includes(this.nativePath),()=>!1))})),this.sidecars=h.lazy(()=>i(this,void 0,void 0,function*(){if(this.isSidecar())return[];const t=yield this.dirEntSiblings(t=>t.filter(t=>E.isSidecarExt(t.ext)&&(t.name===this.name||C.nameWithoutCount(t.name)===C.nameWithoutCount(this.name))));return f.sortByAsync(o.toA(t),t=>t.mtimeMs())})),I.set(t,this)}static for(t,e){if(t instanceof A)return t;if(t instanceof k.BaseFile)return this.for(t.nativePath,e);if(T.isUri(t))throw new Error("use forUri");const n=I.get(t);if(null!=n)return n;const i=C.resolve(t);return I.getOrSet(i,()=>new A(i,e))}static forPosix(t){return this.for(t.replace(/\//g,r.sep))}static forUri(t,e){return f.thenMap(T.uri2file(t,e),t=>this.for(C.posix2native(t.posixPath,t.hostname)))}static forUriOrPath(t,e){return f.firstDefinedPromise(()=>this.forUri(t),()=>this.for(e))}for(t,e){return A.for(t,e)}clear(){return super.clear(),this.uriObject.clear(),this.uri.clear(),this.fileuri.clear(),this.mountpoint.clear(),this.etag.clear(),this.ignorable.clear(),this.hidden.clear(),this.sidecars.clear(),this}bestMountpoint(t){return d.greatestBy(t.filter(t=>this.isDescendantOf(t)),t=>l.Opt(o.commonPrefixLength(this.pathnames,t.pathnames)).filter(e=>e>=t.pathnames.length).get())}httpHeaders(){return i(this,void 0,void 0,function*(){return{ETag:yield this.etag(),"Last-Modified":yield this.lastModifiedUtc()}})}hide(){return i(this,void 0,void 0,function*(){const t=yield S.isWin?m.stdout("attrib",["+h",this.nativePath],{timeout:10*g.secondMs}).catch(t=>t):S.isMac?m.stdout("chflags",["hidden",this.nativePath],{timeout:10*g.secondMs}).catch(t=>t):"";return p.notBlank(t)?void this.pflog().warn("hide("+this.nativePath+") failed: "+t):this.clear()})}ignorableParent(){return this.trapOr("ignorableParent",()=>this.nearestDir().then(t=>t.ignorable()))}mkNoMedia(){return this.join(".NoMedia").writeTxt("See <https://support.photostructure.com/no-media/>").then(t=>t?(y.emitFileChanged(this.nativePath),this):void 0).catch(t=>{this.pflog().warn("Could not add .NoMedia file to "+this,t)})}noMediaDir(){return i(this,void 0,void 0,function*(){return F.hasNoMedia(yield this.directoryEntry())})}ignorableCheap(){return D.ignorablePath(this.nativePath)}isSidecar(){return E.isSidecarExt(this.ext)}sidecar(){return i(this,void 0,void 0,function*(){return c.thenOpt(this.sidecars()).flatMap(t=>t[t.length-1]).getOrElse(()=>this.sibling(this.name+E.asExt(P.Settings.defaultSidecarType.valueOrDefault)))})}jsonSidecar(){return i(this,void 0,void 0,function*(){const t=yield this.dirEntSiblings(t=>t.filter(t=>M.equalsIgnoreCase(t.ext,".json")&&(t.name===this.name||t.name===this.base||C.nameWithoutCount(t.name)===C.nameWithoutCount(this.name)))),e=o.sortBy(o.toA(t),t=>-x.diceCoeff(this.name,t.name))[0];return this.pflog().debug("jsonSidecar(): "+e),e})}thisOrSidecareMaxMtimeMs(){return this.trap("mtimeOrSidecarMs",()=>i(this,void 0,void 0,function*(){const t=yield this.mtimeMs(),e=yield this.sidecars(),n=[t,...yield Promise.all(o.toA(e).map(t=>t.mtimeMs()))].filter(u.gt0);return o.mapNotEmpty(n,t=>Math.floor(Math.max(...t)))}))}thisOrSidecareMaxMtimeSec(){return f.thenMap(this.thisOrSidecareMaxMtimeMs(),t=>g.unixtime(t))}}e.PosixFile=A},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(9);e.strEnum=function(...t){return Object.freeze(t.reduce((t,e)=>(t[e]=e,t),Object.create(null)))},e.strEnumValues=function(t){return i.keys(t)},e.enumHas=function(t,e){return"string"==typeof e&&t[e]===e}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(43),s=n(99),o=n(30),a=n(145),u=n(96),l=n(42),c=n(183),d=n(5),h=n(80),f=n(6),p=n(15),m=n(4),g=n(36),y=n(37),v=n(3),w=n(92),b=n(2),S=n(10),P=n(63),M=n(20),x=n(11),E=n(14),_=n(26),k=n(1),T=n(57),O=n(7),D=n(0),F=n(23),C=n(13),I=n(103),A=n(19),L=n(24),R=n(139),N=n(173),j=n(52),B=n(28),z=n(104),q=n(106),W=n(88),V=n(54),U=n(188);e.DefaultEnsureNewOptions=Object.freeze({emptyIsNew:!0,maxVersions:512,requireNumber:!1,leftPad:1,startIndex:1}),e.execDir=function(){return Q.for(process.execPath).parent()};const G=x.minuteMs,$=500;class J extends P.BoundedMap{constructor(){super(G,$,!0),E.onFileChanged(t=>this.clearFromPath(t)),E.onClearCache(()=>this.clearEntries()),this.on("expire",(t,e)=>D.map(e,t=>t.clear()))}clearEntries(){for(const t of this.values())t.clear()}clearFromPath(t){for(const e of this.values())(null==t||e.nativePath.startsWith(t))&&e.clear()}}e.FileCache=J;const H=new J;class Q{constructor(t,e){if(this.dirent=e,this.bflog=v.lazy(()=>k.mkLogger("BaseFile("+this.nativePath+")")),this.dirents=v.lazy(()=>i(this,void 0,void 0,function*(){return b.thenMap(this.directoryEntry(),t=>t.children())})),this.stat=v.lazy(()=>this.trap("stat",()=>s.stat(this.nativePath).catch(()=>void 0)),Q.attrTTL),this.statSync=v.lazy(()=>this.trapSync("statSync",()=>D.Try(()=>s.statSync(this.nativePath))),Q.attrTTL),this.executable=v.lazy(()=>this.access(s.constants.R_OK|s.constants.X_OK)),this.shaResult=v.lazy(()=>i(this,void 0,void 0,function*(){const t=yield this.size();if(0===t||null==t)return;const e=t>5*O.MiB?new z.PushProgressObserver({op:"SHA",path:this.nativePath},t):void 0;return x.elapsedAsync(()=>this.trap("sha",()=>j.fileSha(this.nativePath,{observer:e}).then(t=>t.toString("base64"))))}),Q.attrTTL),null!=e)this.nativePath=e.nativePath,this.dir=e.dir,this.base=e.base,this.name=e.name,this.ext=e.ext;else{this.nativePath=B.resolve(t),this.nativePath.startsWith("\\\\")&&(this.hostname=this.nativePath.split("\\")[2]);const e=B.parse(this.nativePath);this.dir=e.dir,this.base=e.base,this.name=e.name,this.ext=e.ext}this.posixPath=B.native2posix(this.nativePath),H.set(t,this)}[l.inspect.custom](){return{ctor:this.constructor.name,nativePath:this.nativePath}}static withFastestAccess(t){return i(this,void 0,void 0,function*(){const e=m.compact(t),n=yield Promise.all(e.map(t=>t.shaMs()));return e[m.leastIndex(n)]})}static forPosix(t){return t instanceof Q?t:this.for(C.replaceAll(t,"/",o.sep))}static forDirectoryEntry(t){return this.for(t.nativePath,t)}static for(t,e){if(t instanceof Q)return t;const n=H.get(t);if(null!=n)return n;const i=B.resolve(t);return H.getOrSet(i,()=>new Q(i,e))}static clear(t){E.emitFileChanged(t)}for(t,e){return Q.for(t,e)}clear(){return this.dirent=void 0,this.dirents.clear(),this.stat.clear(),this.statSync.clear(),this.executable.clear(),this.shaResult.clear(),this}clearThisAndParent(){return E.emitFileChanged(this.dir),this}toString(){return this.nativePath}valueOf(){return this.pathnames}eql(t){return null!=t&&this.nativePath===t.toString()}get baseWithParent(){return(this.isRoot?"":this.parent().base)+"/"+this.base}get baseWithGrandparent(){return(this.isRoot?"":this.parent().baseWithParent)+"/"+this.base}posixPathFrom(t){return B.posixPathFrom(t,this)}directoryEntry(){return i(this,void 0,void 0,function*(){if(null==this.dirent){const t=yield this.isFile(),e=yield this.isDirectory(),n=yield this.isSymbolicLink(),i={name:this.base,isFile:function(){return t},isDirectory:function(){return e},isSymbolicLink:function(){return n}};this.dirent=new N.DirectoryEntry(this.dir,i)}return this.dirent})}_child(t){return this.for(o.join(this.nativePath,t.base),t)}childNames(){return b.thenMap(this.dirents(),t=>t.map(t=>t.base))}children(t){return i(this,void 0,void 0,function*(){return b.thenMap(this.dirents(),e=>b.thenCompact(e.map(e=>i(this,void 0,void 0,function*(){return w.apply(this._child(e),t)}))))})}childFiles(t){return i(this,void 0,void 0,function*(){const e=[];for(const n of d.toA(yield this.dirents()))if(n.isFile()){const i=this._child(n);(null==t||t(i))&&e.push(i)}return e})}childDirectories(t){return i(this,void 0,void 0,function*(){return b.thenMap(this.dirents(),e=>b.thenCompact(e.filter(t=>t.isDirectory()).map(e=>i(this,void 0,void 0,function*(){return w.apply(this._child(e),t)}))))})}childrenSync(){return D.orElse(this.trapSync("childrenSync",()=>r.readdirSync(this.nativePath).map(t=>this.join(t))),[])}hasChildren(t){return i(this,void 0,void 0,function*(){const e=yield this.childNames();return m.isNotEmpty(t)?d.includesAll(e,t):m.isNotEmpty(e)})}hasNoChildren(){return i(this,void 0,void 0,function*(){return(yield this.isFile())||m.isEmpty(yield this.childNames())})}visitDescendants(t){return i(this,void 0,void 0,function*(){return b.thenMap(this.children(),e=>i(this,void 0,void 0,function*(){for(const n of e)yield n.visitDescendants(t),yield t(n)}))})}descendants(t){return i(this,void 0,void 0,function*(){const e=[];for(const n of d.toA(yield this.childFiles()))(yield t(n))&&e.push(n);const n=yield this.childDirectories();if(null!=n){for(const i of n)yield b.thenMap(i.descendants(t),t=>e.push(...t));return e}})}ancestorWithChildren(t){return i(this,void 0,void 0,function*(){return(yield this.hasChildren(t))?this:this.isRoot?void 0:this.parent().ancestorWithChildren(t)})}siblings(){return i(this,void 0,void 0,function*(){return this.selfAndSiblings().then(t=>t.filter(t=>!this.eql(t)))})}dirEntSiblings(t){return i(this,void 0,void 0,function*(){return b.thenMap(this.parent().dirents(),e=>t(e).map(t=>this.parent()._child(t)))})}selfAndSiblings(){return i(this,void 0,void 0,function*(){return this.parent().children()})}firstExistingSelfOrAncestor(){return i(this,void 0,void 0,function*(){return this.isRoot||(yield this.exists())?this:this.parent().firstExistingSelfOrAncestor()})}get pathnames(){return this.nativePath.split(o.sep).filter(t=>null!=t&&""!==t)}get pathnamesWithoutDrive(){return F.isWin?this.pathnames.slice(1):this.pathnames}get depth(){return this.pathnames.length-(F.isWin?1:0)}get isRoot(){return this.pathnames.length===(F.isWin?1:0)}root(t=0){return this.depth<=t?this:this.parent().root(t)}parent(){return this.isRoot?this:this.for(this.dir)}isAncestorOf(t){return null!=t&&m.startsWith(t.pathnames,this.pathnames)}isDescendantOf(t){return null!=t&&m.startsWith(this.pathnames,t.pathnames)}parentsAndSelf(){return[...this.parents(),this]}selfAndParents(t){return[this,...this.isRoot||t<=0?[]:this.parent().selfAndParents(t-1)]}parents(){const t=this.parent();return this.isRoot?[]:[...t.parents(),t]}sibling(t){return this.parent().join(t)}withPrefix(t){return this.sibling(t+this.base)}withNameSuffix(t){return this.sibling(this.name+t+this.ext)}siblingOf(t){return this.nativePath!==t.nativePath&&this.dir===t.dir}join(...t){return m.isEmpty(t)?this:this.for(o.join(this.nativePath,...t))}child(...t){return m.isEmpty(t)?this:this.join(...B.native2posix(o.join(...t)).split("/").filter(t=>".."!==t))}trap(t,e,n="warn"){return i(this,void 0,void 0,function*(){try{const i=yield e();return this.bflog().trace(`trap ${t}()`,Buffer.isBuffer(i)?"<Buffer>":i),i}catch(e){return void this.bflog().log(n,`trap: ${t}() failed: ${e}`)}})}trapOr(t,e,n="warn"){return i(this,void 0,void 0,function*(){try{return this.bflog().debug(`trapOr ${t}()`),yield e(),!0}catch(e){return this.bflog().log(n,`trapOr: ${t}() failed: ${e}`),!1}})}trapSync(t,e){try{return this.bflog().debug(`trapSync ${t}()`),e()}catch(e){return void this.bflog().warn(`trapSync: ${t}() failed: ${e}`)}}exists(){return i(this,void 0,void 0,function*(){return null!=this.dirent||(yield b.thenDefined(this.stat()))})}existsSync(){return null!=this.dirent||null!=this.statSync()}notExists(){return i(this,void 0,void 0,function*(){return b.thenNot(this.exists())})}mtime(){return b.thenMap(this.stat(),t=>t.mtime)}mtimeMs(){return b.thenMap(this.stat(),t=>Math.floor(t.mtimeMs))}mtimeSec(){return b.thenMap(this.stat(),t=>x.unixtime(t.mtime))}lastModifiedUtc(){return i(this,void 0,void 0,function*(){return b.thenMap(this.stat(),t=>t.mtime.toUTCString())})}statTimes(){return b.thenMap(this.stat(),t=>d.uniq([t.birthtimeMs,t.mtimeMs].filter(t=>null!=t&&0!==t)))}maxStatMs(){return b.thenMap(this.statTimes(),m.max)}maxStatDate(){return b.thenMap(this.maxStatMs(),t=>new Date(t))}minStatMs(){return b.thenMap(this.statTimes(),T.min)}minStatDate(){return b.thenMap(this.minStatMs(),t=>new Date(t))}size(){return b.thenMap(this.stat(),t=>t.size)}access(t){return this.trapOr("access("+t+")",()=>s.access(this.nativePath,t))}isReadable(){return this.access(s.constants.R_OK)}isHiddenPosix(){return this.base.startsWith(".")}isEmpty(){return i(this,void 0,void 0,function*(){if(yield this.isDirectory())return m.isNotEmpty(yield this.childNames());{const t=yield this.size();return null==t||0===t}})}isNonEmpty(t=1){return b.thenMapOr(this.stat(),e=>e.size>t,()=>!1)}modifiedGTE(t){return i(this,void 0,void 0,function*(){return b.thenMap(this.mtime(),e=>x.unixtime(e)>=x.unixtime(t))})}modifiedCloseTo(t,e){return i(this,void 0,void 0,function*(){return b.thenMap(this.mtimeMs(),n=>Math.abs(n-t)<=e)})}modifiedGT(t){return i(this,void 0,void 0,function*(){if(null!=t)return b.thenMap(this.mtime(),e=>x.unixtime(e)>x.unixtime(t))})}isDirectory(){return i(this,void 0,void 0,function*(){return null!=this.dirent?this.dirent.isDirectory():b.thenMapOr(this.stat(),t=>t.isDirectory(),()=>!1)})}isNotDirectory(){return i(this,void 0,void 0,function*(){return b.thenNot(this.isDirectory())})}isDirectorySync(){return null!=this.dirent?this.dirent.isDirectory():f.mapOr(this.statSync(),t=>t.isDirectory(),()=>!1)}isSymbolicLink(){return i(this,void 0,void 0,function*(){return null!=this.dirent?this.dirent.isSymbolicLink():b.thenMapOr(this.stat(),t=>t.isSymbolicLink(),()=>!1)})}nearestDir(){return i(this,void 0,void 0,function*(){return(yield this.isDirectory())?this:this.parent()})}isFile(){return i(this,void 0,void 0,function*(){return null!=this.dirent?this.dirent.isFile():this.stat().then(t=>p.Opt(t).map(t=>t.isFile()).getOrElse(()=>!1))})}isFileSync(){return null!=this.dirent?this.dirent.isFile():p.Opt(this.statSync()).filter(t=>t.isFile()).isDefined}rmdir(t="warn"){return this.clear(),this.trapOr("rmdir",()=>s.rmdir(this.nativePath),t)}mkdirp(){return i(this,void 0,void 0,function*(){return(yield this.clear().isDirectory())?this:this.trap("mkdirp",()=>i(this,void 0,void 0,function*(){try{return yield s.mkdirp(this.nativePath),this.clearThisAndParent()}catch(t){if("EEXIST"!==t.code)throw t}if(null==(yield this.parent().mkdirp()))throw new Error("Failed to mkdirp parent of "+this);if(yield s.mkdir(this.nativePath),!1===(yield b.until(()=>this.clear().isDirectory(),2*x.secondMs)))throw new Error("Failed to mkdirp "+this);return this.clearThisAndParent()}))})}mkdirpSync(){return this.trapSync("mkdirpSync",()=>(s.mkdirpSync(this.nativePath),this.clearThisAndParent()))}sha(){return b.thenMap(this.shaResult(),t=>t.result)}shaMs(){return b.thenMap(this.shaResult(),t=>t.elapsedMs)}writeStream(t,e){return i(this,void 0,void 0,function*(){return yield V.pipelinePromise([t,s.createWriteStream(this.nativePath,e)]),this.clearThisAndParent()})}writeJSON(t,e={}){return i(this,void 0,void 0,function*(){return this.trap("writeJSON",()=>i(this,void 0,void 0,function*(){return yield this.parent().mkdirp(),yield s.writeFile(this.nativePath,JSON.stringify(t,e.replacer,e.spaces),Object.assign({flag:"w"},e)),this.clearThisAndParent()}))})}readJSON(){return this.trap("readJSON",()=>h.retryOnReject(()=>s.readJSON(this.nativePath),{maxRetries:2,onRetryWaitUntil:()=>y.delay(25),errorIsRetriable:t=>-2!==t.errno}))}readJSONSync(){return this.trapSync("readJSONSync",()=>s.readJSONSync(this.nativePath))}readFile(){return this.trap("readFile",()=>s.readFile(this.nativePath),void 0)}readLines(){return b.thenMap(this.readFile(),t=>R.splitLines(t.toString()))}readFileSync(){return D.Try(()=>D.map(s.readFileSync(this.nativePath),A.toS))}writeTxt(t){return this.writeFile(R.crlf(t))}writeFile(t){return this.trapOr("writeFile",()=>i(this,void 0,void 0,function*(){yield this.parent().mkdirp(),yield s.outputFile(this.nativePath,t),this.clearThisAndParent()}))}appendFile(t){return this.trapOr("appendFile",()=>i(this,void 0,void 0,function*(){yield s.mkdirp(this.dir),yield s.appendFile(this.nativePath,t),this.clearThisAndParent()}))}wip(t="."){return this.sibling(t+this.base)}unwip(t="."){return i(this,void 0,void 0,function*(){const e=this.sibling(C.stripPrefix(this.base,t));return this.mv(e,{overwrite:!0})})}dest(t){return i(this,void 0,void 0,function*(){const e=t.clear();return S.notBlank(this.ext)&&S.blank(e.ext)||(yield e.isDirectory())?e.join(this.base):e})}copyFile(t,e={maxRetries:1}){return i(this,void 0,void 0,function*(){return h.retryOnReject(()=>this._copyFile(t),{maxRetries:e.maxRetries,onRetryWaitUntil:()=>y.delay(250)})})}_copyFile(t){return i(this,void 0,void 0,function*(){let e;const n=(yield this.dest(t)).clear();if(this.nativePath===n.nativePath)return this;{const t=yield this.stat(),o=D.map(t,t=>t.size);if(null==t||null==o)throw new Error("Can't copy missing files");const a=yield this.sha();if(null==a)throw new Error("Can't copy file without SHA");const u=n.wip();try{if(null==(yield n.parent().mkdirp()))throw new Error("Cannot mkdirp "+n.dir);const l=new Promise((t,e)=>r.copyFile(this.nativePath,u.nativePath,r.constants.COPYFILE_FICLONE,n=>null==n?t():e(n)));o>5*O.MiB&&(e=new z.PullProgressObserver({op:"file copy",path:this.nativePath,dest:n.nativePath},o,()=>u.clear().size())),yield l;const c=yield b.until(()=>i(this,void 0,void 0,function*(){return o===(yield u.clear().size())}),15*x.secondMs),d=yield u.clear().sha();if(!c||d!==a)throw this.bflog().warn("copyFile() failed",{sizeMatches:c,destSha:d,thisSha:a}),new Error("wipDest mismatch");const h=yield u.unwip();if(null==h)throw new Error(".unwip() failed");return yield s.chmod(h.nativePath,t.mode),yield s.utimes(h.nativePath,t.atime,t.mtime),this.bflog().debug(`copyFile(${n.nativePath}): success`),n.clearThisAndParent()}catch(t){throw this.bflog().warn(`copyFile(${u.nativePath}) failed: ${t}`),yield u.unlink(),yield n.unlink(),t}finally{D.map(e,t=>t.end())}}})}touch(t=Date.now(),e){return i(this,void 0,void 0,function*(){return this.trap("touch",()=>b.thenMap(this.ensureFile(),()=>this.utimes(t,e)))})}utimes(t,e){return i(this,void 0,void 0,function*(){const n=D.orElse(t,Date.now()),i=D.orElse(e,n);return this.trap("utimes",()=>s.utimes(this.nativePath,x.unixtime(i),x.unixtime(n)).then(()=>this.clearThisAndParent()))})}unlink(t="warn"){return i(this,void 0,void 0,function*(){return this.trap("unlink",()=>i(this,void 0,void 0,function*(){return yield s.unlink(this.nativePath),this.clearThisAndParent()}),t)})}remove(){return i(this,void 0,void 0,function*(){return this.trap("remove",()=>i(this,void 0,void 0,function*(){return this.bflog().info("remove()"),yield s.remove(this.nativePath),this.clearThisAndParent()}))})}unlock(){return i(this,void 0,void 0,function*(){return F.isMac&&(yield this.clear().exists())&&(yield M.stdout("chflags",["nouchg",this.nativePath],{timeout:L.cmdTimeoutMs})),this})}renameWithNameSuffix(t){return i(this,void 0,void 0,function*(){return b.thenMap(this.withNameSuffix(t).ensureNew({emptyIsNew:!0}),t=>t.unlink("debug").then(()=>this.mv(t)))})}mv(t,e={overwrite:!1}){return i(this,void 0,void 0,function*(){const n=yield this.dest(t);return this.nativePath===n.nativePath?(this.bflog().warn("mv(): no-op",new Error("internal error")),this):(yield n.parent().mkdirp(),yield Promise.all([this.unlock(),n.unlock()]),this.bflog().debug("mv",n),yield s.move(this.nativePath,n.nativePath,e),yield n.unlock(),this.clearThisAndParent(),n.clearThisAndParent())})}gzip(){return i(this,void 0,void 0,function*(){return this.trap("gzip",()=>i(this,void 0,void 0,function*(){const t=yield this.for(this.nativePath+".gz").ensureNew();return yield new Promise((e,n)=>u.pipeline(s.createReadStream(this.nativePath),c.createGzip(),s.createWriteStream(t.nativePath),t=>null==t?e():n(t))),yield this.unlink(),t}))})}ensureFile(){return this.trap("ensureFile",()=>s.ensureFile(this.nativePath).then(()=>this.clearThisAndParent()))}ensureFileSync(){return this.trapSync("ensureFileSync",()=>(s.ensureFileSync(this.nativePath),this.clearThisAndParent()))}get nameWithoutCount(){return B.nameWithoutCount(this.name)}get baseWithoutCount(){return this.nameWithoutCount+this.ext}get siblingWithoutCount(){return this.sibling(this.baseWithoutCount)}ensureNewNativePath(t){return i(this,void 0,void 0,function*(){const n=Object.assign({},e.DefaultEnsureNewOptions,t);if(this.clear(),!n.requireNumber&&((yield this.notExists())||n.emptyIsNew&&(yield this.isEmpty())))return this.nativePath;const i=this.parent();yield i.mkdirp();for(let t=n.startIndex;t<=n.maxVersions;t++){const e=i.join(`${this.name}-${C.leftPad(t,n.leftPad,"0")}${this.ext}`);if(e.clear(),(yield e.notExists())||n.emptyIsNew&&(yield e.isEmpty()))return e.nativePath}throw new Error("There are already more than "+n.maxVersions+" of "+this)})}ensureNew(t={}){return this.ensureNewNativePath(t).then(t=>this.for(t))}renameYMD(){return i(this,void 0,void 0,function*(){if(yield this.clear().isNonEmpty()){const t=_.datedToYMD(yield b.thenOrElse(this.mtime(),()=>new Date)),e=yield this.withNameSuffix("-"+t).ensureNew({emptyIsNew:!0});if(null!=e)return this.mv(e);this.bflog().warn("renameYMD(): failed (ensureNew returned null)")}})}saveIfNewOrDelete(t){return i(this,void 0,void 0,function*(){if(yield this.clear().isEmpty())return void(yield this.unlink());const e=yield this.siblingWithSameContents();if(null!=e)return yield this.unlink(),e;const n=yield this.sibling(t).ensureNew();return this.mv(n)})}chmod(t){return i(this,void 0,void 0,function*(){return yield s.chmod(this.nativePath,t),this.clear()})}zreadline(){return a.createInterface({input:s.createReadStream(this.nativePath).on("error",t=>{throw new Error("Failed to read from "+this+": "+t)}).pipe(c.createGunzip()).on("error",t=>{throw new Error("Failed to gunzip "+this+": "+t)})})}zcat(){return this.ext.endsWith(".gz")?this.trap("zcat",()=>i(this,void 0,void 0,function*(){const t=new U.WritableToBuffer;return yield new Promise((e,n)=>u.pipeline(s.createReadStream(this.nativePath),c.createGunzip(),t,t=>null==t?e():n(t))),b.thenMap(t.buffer,t=>t.toString())})):b.thenMap(this.readFile(),t=>t.toString())}siblingWithSameContents(){return i(this,void 0,void 0,function*(){return this.parent().childWithSameContents(this)})}childWithSameContents(t){return i(this,void 0,void 0,function*(){if((yield this.notExists())||!(yield this.isDirectory()))return;const e=yield t.size(),n=yield this.children(),i=[];for(const r of d.toA(n))(yield r.size())!==e||t.eql(r)||i.push(r);if(m.isEmpty(i))return;const r=yield t.sha();for(const t of i.sort((t,e)=>I.diceCoeff(t.base,e.base)).reverse())if((yield t.sha())===r)return t})}applyIfEmpty(t){return i(this,void 0,void 0,function*(){if(yield this.clear().isNonEmpty())return this;const e=this.wip();try{return yield e.parent().mkdirp(),yield e.unlink("debug"),yield t(e),(yield e.clear().isEmpty())?(this.bflog().warn("applyIfEmpty(): builder didn't write to dest"),void(yield e.unlink("debug"))):e.unwip()}catch(t){throw yield b.tryAll([()=>e.unlink(),()=>this.unlink()]),t}})}firstMatchingLine(t){const e=new g.Deferred("firstMatchingLine("+this+")"),n=r.createReadStream(this.nativePath,{flags:"r"});return n.on("error",t=>{-2===t.errno||"ENOENT"===t.code?(e.maybeResolve(void 0),n.close()):e.maybeReject(t)}),n.on("close",()=>e.maybeResolve(void 0)),W.onDataChunked(n,R.newlineRe,i=>{const r=t.exec(i);null!=r&&(e.maybeResolve(r),n.close())}),e.promise}}Q.attrTTL=1*x.minuteMs,Q.projectRoot=v.lazy(()=>{const t=q.ProjectPath.Root();if(null==t)throw new Error("Cannot find project path");return Q.for(t)}),e.BaseFile=Q},function(t,e){t.exports=require("timers")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(35),r=n(42),s=n(6),o=n(25),a=n(1),u=n(12),l=n(13),c=n(2),d=n(50);e.Deferred=class{constructor(t){this.name=t,this.start=Date.now(),this.state=c.PromiseStates.pending,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e}),this.logger=a.mkLogger("Deferred("+this.toString()+")")}toString(){return l.isString(this.name)?this.name:JSON.stringify(this.name)}[r.inspect.custom](){return{ctor:"Deferred",name:this.toString(),start:this.start,end:this.end,state:this.state}}observeQuietly(t){return t.then(t=>{this.resolve(t)}).catch(t=>{this.logger.log(u.isTest?"warn":"error","observeQuietly.reject()",t),this.resolve(void 0)}),this}observe(t){return t.then(t=>{this.resolve(t)}).catch(t=>{this.reject(t)}),this}setTimeout(t){return s.map(this.priorTimeout,i.clearTimeout),this.priorTimeout=d.setUnrefTimeout(()=>{if(this.pending){const t="TIMEOUT: "+this.name+" after "+(Date.now()-this.start)+"ms";this.reject(t)}},t),this}get stateStr(){return this.pending?"pending":this.resolved?"resolved":"rejected"}get pending(){return this.state===c.PromiseStates.pending}get value(){return this.resolved?this._value:void 0}get error(){return this._error}get settled(){return this.state!==c.PromiseStates.pending}get resolved(){return this.state===c.PromiseStates.resolved}get rejected(){return this.state===c.PromiseStates.rejected}get settledMs(){return null==this.end?void 0:this.end-this.start}resolve(t){return this.settle(()=>{this.state=c.PromiseStates.resolved,this._value=t,this._resolve(t)})}maybeResolve(t){return this.pending?this.resolve(t):this}reject(t){this.logger.log(u.isTest?"warn":"error",".reject()",t);const e=o.asError(t);return this.settle(()=>{this._error=e,this.state=c.PromiseStates.rejected,this._reject(e)})}maybeReject(t){return this.pending?this.reject(t):this}finally(t){return this.promise.finally(t),this}then(t){return this.promise.then(t)}settle(t){if(this.state===c.PromiseStates.pending){s.map(this.priorTimeout,i.clearTimeout),t(),this.end=Date.now();const e=this.settledMs;if(this.resolved&&e>5e3){const t=e>5e3?"info":"debug";this.logger.log(t,"Completed in "+e+"ms")}}else this.logger.warn("settled multiple times (already "+this.stateStr+")",{value:this._value});return this}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(147);e.delay=i.delay,e.delayUntil=i.delayUntil,e.later=i.later,e.unrefDelay=i.unrefDelay},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(4),o=n(0);var a=n(95);function u(t){const e=s.compact(t).filter(([t,e])=>null!=t&&null!=e);return new Map(e)}function l(t,e){return new Map([...t.entries()].filter(([t,n])=>e(t,n)))}e.getOrSet=a.getOrSet,e.hasAll=function(t,e){return e.every(e=>t.has(e))},e.getOrSetAsync=function(t,e,n){return i(this,void 0,void 0,function*(){const i=t.get(e);if(null!=i)return i;const r=Promise.resolve(n());return t.set(e,r),r.then(n=>{null==n?t.delete(e):t.set(e,n)}).catch(()=>t.delete(e)),r})},e.flatMap=function(t,e){return new Map(s.concat(...t.map(t=>e(t))))},e.compactMap=u,e.toMap=function(t,e){return u(s.compact(t).map(e))},e.toMapAsync=function(t,e){return i(this,void 0,void 0,function*(){if(null==t)return new Map;return u(yield Promise.all(s.compact(r.toA(t)).map(t=>e(t))))})},e.toObj=function(t){const e={};for(const[n,i]of t)e[n]=i;return e},e.filter=l,e.filterInPlace=function(t,e){[...t.entries()].forEach(([n,i])=>e(n,i)||t.delete(n))},e.pickKeys=function(t,e){return l(t,t=>e.indexOf(t)>=0)},e.getLike=function(t,e){return o.map([...t.entries()].find(([t])=>e(t)),([,t])=>t)},e.inverse=function(t){return new Map([...t.entries()].map(([t,e])=>[e,t]))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(43),r=n(45),s=n(22),o=n(9),a=n(33),u=n(128),l=n(129),c=n(4),d=n(3),h=n(10),f=n(28),p=n(0),m=n(12);var g;e.AppPaths=a.strEnum("exe","home","appData","userData","pictures","temp"),function(t){t.getName=function(){return l.AppName},t.exe=d.lazy(()=>s.execPath),t.home=d.lazy(()=>p.orElse(c.first(h.compactBlanks([r.homedir(),s.env.HOME,s.env.HOMEPATH,s.env.USERPROFILE]).map(t=>f.resolve(t)),t=>p.map(i.statSync(t),()=>t)),r.homedir())),t.appData=d.lazy(()=>u.appData()),t.appName=d.lazy(()=>l.AppName+(m.isProd?"":`-${m.Settings.nodeEnv.value}`)),t.userData=d.lazy(()=>f.resolve(t.appData(),t.appName())),t.pictures=d.lazy(()=>f.resolve(t.home(),"Pictures")),t.temp=d.lazy(()=>f.resolve(r.tmpdir(),l.AppName+"-"+r.userInfo().username)),t.getPath=function(e){return o.maybeCall(t,e)},t.setPath=function(e,n){t[e].set(f.resolve(n))}}(g=e.App||(e.App={})),m.Settings.nodeEnv.addListener(()=>void o.values(g).forEach(t=>o.maybeCall(t,"clear"))),g.appName.onChange(()=>g.userData.clear())},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(80),s=n(16),o=n(4),a=n(37),u=n(21),l=n(3),c=n(2),d=n(20),h=n(167),f=n(14),p=n(1),m=n(23),g=n(111),y=n(211),v=n(212),w=n(24);let b;function S(){return i(this,void 0,void 0,function*(){return null==b&&null==e.localMountpointSetup.prior()&&(yield e.localMountpointSetup()),r.retryOnReject(()=>(b||e.nonRpcMountpoints)(),{maxRetries:3,onRetryWaitUntil:t=>a.delay(1500*t)}).catch(t=>{f.emitNonFatal("mountpoints() failed",t)})})}e.nonRpcMountpoints=l.lazy(m.isWin?v.mountpointsWin:y.mountpointsPosix,w.mountpointsTtlMs),f.onClearCache(()=>e.nonRpcMountpoints.clear()),e.setRpcMountpointsImpl=function(t){b=t,e.localMountpointSetup.clear()},e.localMountpointSetup=l.lazy(()=>i(this,void 0,void 0,function*(){null==b?a.later(()=>i(this,void 0,void 0,function*(){const t=p.mkLogger("Mountpoints.localMountpointSetup()");m.isMac?(t.info("Setting up Mac diskutil activity watcher"),e.nonRpcMountpoints.setTTL(w.dfTtlMs),e.diskUtilActivity()):m.isLinux&&((yield g.isGioSupported())?(t.info("Setting up Linux gio mount monitor"),e.nonRpcMountpoints.setTTL(w.dfTtlMs),e.gioMountMonitor()):(yield P())&&(t.info("Setting up Linux findmnt mount monitor"),e.nonRpcMountpoints.setTTL(w.dfTtlMs),e.findmntPoll()))}),30*s.secondMs).unref():yield c.awaitAll([u.end(e.diskUtilActivity.clear()),u.end(e.gioMountMonitor.clear()),u.end(e.findmntPoll.clear())])})),e.mountpoints=S,e.mountsCacheKey=()=>c.thenMap(S(),t=>o.sort(t).join(":")),e.diskUtilActivity=l.lazy(()=>h.mkBasicWatchedChild("diskutil",["activity"],()=>e.nonRpcMountpoints.clear())),e.gioMountMonitor=l.lazy(()=>h.mkBasicWatchedChild(g.GioCommand,g.GioMountMonitorArgs,()=>{g.gioVolumes.clear(),g.mtabEntries.clear(),e.nonRpcMountpoints.clear()}));const P=l.lazy(()=>i(this,void 0,void 0,function*(){if(!m.isLinux)return!1;try{return 0===(yield d.stdoutResult("findmnt",["--version"],{timeout:w.cmdTimeoutMs,ignoreStderr:!0})).code}catch(t){return!1}}));e.findmntPoll=l.lazy(()=>h.mkBasicWatchedChild("findmnt",["--poll"],()=>e.nonRpcMountpoints.clear()))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(179),r=n(61);var s;function o(t){return"symbol"==typeof t}function a(t){return"function"==typeof t}function u(t){return null==t?s.Empty:o(t)?s.Symbol:r.isPrimitive(t)?s.Primitive:Array.isArray(t)?s.Array:i.isIterable(t)?s.Iterable:a(t)?s.Function:"object"==typeof t?t.constructor&&"Object"===t.constructor.name?s.Object:s.Instance:s.Unknown}!function(t){t[t.Empty=0]="Empty",t[t.Primitive=1]="Primitive",t[t.Symbol=2]="Symbol",t[t.Object=3]="Object",t[t.Array=4]="Array",t[t.Iterable=5]="Iterable",t[t.Instance=6]="Instance",t[t.Function=7]="Function",t[t.Unknown=8]="Unknown"}(s=e.ObjectType||(e.ObjectType={})),e.isSymbol=o,e.isFunction=a,e.isObject=function(t){return u(t)===s.Object},e.objectType=u},function(t,e){t.exports=require("util")},function(t,e){t.exports=require("fs")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(6);class r{constructor(t){this.value=t,this.ctime=Date.now()}touch(){this.ctime=Date.now()}}e.Entry=r;e.TTLMap=class{constructor(t,e=new Map){this.ttlMs=t,this.store=e,this.expireListeners=[]}get size(){return this.vacuum(),this.store.size}clear(){return this.store.clear(),this}delete(t){return this.store.delete(t)}deleteIf(t){this.store.forEach((e,n)=>{t(n,e.value)&&this.store.delete(n)})}entries(){const t=this;return function*(){for(const[e,n]of t.store.entries())t.expired(e,n)||(yield[e,n.value])}()}forEach(t){this.store.forEach((e,n)=>{this.expired(n,e)||t(e.value,n,this)})}get(t){return i.map(this.store.get(t),e=>this.expired(t,e)?void 0:e.value)}touch(t){i.map(this.store.get(t),t=>t.touch())}pop(t){const e=this.store.get(t);return this.store.delete(t),i.map(e,e=>this.expired(t,e)?void 0:e.value)}has(t){return!this.expired(t,this.store.get(t))}keys(){const t=this;return function*(){for(const[e,n]of t.store.entries())t.expired(e,n)||(yield e)}()}set(t,e){return i.map(this.store.get(t),e=>this.expireListeners.forEach(n=>n(t,e.value))),this.store.set(t,new r(e)),this}values(){const t=this;return function*(){for(const[e,n]of t.store.entries())t.expired(e,n)||(yield n.value)}()}[Symbol.iterator](){return this.entries()}getOrSet(t,e){const n=this.store.get(t);if(this.valid(t,n))return n.touch(),n.value;{const n=e();return this.set(t,n),n}}on(t,e){this.expireListeners.push(e)}valid(t,e){return!this.expired(t,e)}expired(t,e){return null!=e&&e.ctime+this.ttlMs<=Date.now()?(this.store.delete(t),this.expireListeners.forEach(n=>n(t,e.value)),!0):null==e}vacuum(){this.store.forEach((t,e)=>{this.expired(e,t)})}}},function(t,e){t.exports=require("os")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(9),o=n(41);function a(t,e){return i(this,void 0,void 0,function*(){const n=yield t,i=yield e;return null!=n&&null!=i&&u(n,i)})}function u(t,e){return null==l(t,e)}function l(t,e){switch(o.objectType(t)){case o.ObjectType.Empty:case o.ObjectType.Symbol:case o.ObjectType.Primitive:return t===e?void 0:`${t} !== ${e}`;case o.ObjectType.Array:return c(t,e);case o.ObjectType.Iterable:return c([...t],[...e]);default:return t instanceof Set?d(t,e):t instanceof Map?h(t,e):f(t,e)}}function c(t,e){if(!Array.isArray(t))return"a is not an Array";if(!Array.isArray(e))return"b is not an Array";if(t.length!==e.length)return`length mismatch (${t.length} != ${e.length})`;const n=r.compact(t.map((t,n)=>{const i=l(t,e[n]);return null==i?void 0:"["+n+"] not eql: "+i}));return 0===n.length?void 0:n.join(", ")}function d(t,e){if(!(t instanceof Set))return"a is not a Set";if(!(e instanceof Set))return"b is not a Set";if(t.size!==e.size)return`size mismatch (${t.size} != ${e.size})`;const n=[...t.keys()].filter(t=>!e.has(t));return 0===n.length?void 0:"Missing keys in b: "+n}function h(t,e){if(!(t instanceof Map))return"a is not a Map";if(!(e instanceof Map))return"b is not a Map";if(t.size!==e.size)return`size mismatch (${t.size} != ${e.size})`;const n=[...t.keys()].filter(t=>!e.has(t));if(n.length>0)return"Missing keys in b: "+n;const i=r.compact([...t.entries()].map(([t,n])=>l(n,e.get(t))));return 0===i.length?void 0:"Mismatched entries: "+i.join(", ")}function f(t,e){const n=s.keys(t),i=s.keys(e),o=c(n.sort(),i.sort());if(null!=o)return o;const a=r.compact(n.map(n=>{const i=l(t[n],e[n]);return null==i?void 0:"Mismatch at ["+n+"]: "+i}));return 0===a.length?void 0:a.join(", ")}e.eqlAsync=a,e.notEqlAsync=function(t,e){return i(this,void 0,void 0,function*(){return!(yield a(t,e))})},e.eql=u,e.notEql=function(t,e){return!u(t,e)},e.whyNotEql=l,e.arrayEql=function(t,e){return null==c(t,e)},e.whyNotArrayEql=c,e.setEql=function(t,e){return null==d(t,e)},e.whyNotSetEql=d,e.mapEql=function(t,e){return null==h(t,e)},e.whyNotMapEql=h,e.whyNotObjEql=f},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(87),s=n(8),o=n(16),a=n(6),u=n(21),l=n(3),c=n(2),d=n(132),h=n(20),f=n(11),p=n(14),m=n(1),g=n(12),y=n(13),v=n(24),w=10*o.minuteMs,b="{ready}",S=" | ConvertTo-Json -Compress";p.onClearCache(()=>a.map(P.instance.prior(),t=>t.clearMockResults()));class P{constructor(){this.logger=m.mkLogger("PowerShell"),this.mockResults=new Map,this.pwsh=d.observeBatchCluster(new r.BatchCluster({processFactory:()=>h.execFile("powershell",[],w),versionCommand:`function prompt {"${b}"}`,pass:b,fail:"Error",exitCommand:"exit",maxProcs:2,maxTasksPerProcess:150,taskTimeoutMillis:v.cmdTimeoutMs,cleanupChildProcs:!1}),"PowerShell",u.EndableRanks.db)}end(){return this.pwsh.end()}get ended(){return this.pwsh.ended}get spawnedProcs(){return this.pwsh.spawnedProcs}pushMockResult(t,e){this.mockResults.set(y.ensureSuffix(t,S),e)}clearMockResults(){this.mockResults.clear()}execute(t,e){return i(this,void 0,void 0,function*(){if(this.pwsh.ended||u.ending())this.logger.warn("execute() failed (ended)",{cmd:t});else{if(g.isTest&&this.mockResults.has(t)){const n=this.mockResults.get(t);return e(n.stdout,n.stderr,n.passed)}try{this.logger.debug("execute()",{cmd:t});const n=yield f.elapsedAsync(()=>this.pwsh.enqueueTask(new r.Task(t,(n,i,r)=>e(a.map(n,e=>y.stripPrefix(e,t)),i,r)))),i=n.elapsedMs<500?"trace":n.elapsedMs<1500?"debug":n.elapsedMs<3e3?"info":"warn";return this.logger.log(i,"execute()",{cmd:t,elapsedMs:n.elapsedMs}),n.result}catch(e){return void this.logger.warn("execute() failed: "+e,{cmd:t})}}})}executeJson(t){return i(this,void 0,void 0,function*(){const e=yield this.execute(y.ensureSuffix(t,S),(t,e,n)=>({stdout:t,stderr:e,passed:n}));if(null!=e)if(s.blank(e.stdout)||s.notBlank(e.stderr)||!e.passed)this.logger.warn("executeJson(): failed result",Object.assign({cmd:t},e));else try{return JSON.parse(e.stdout)}catch(t){const n=e.stdout.replace(/\\/g,"\\\\");return this.logger.info("executeJson(): parsing failed, trying dub-whack fix...",{before:y.ellipsize(e.stdout),after:y.ellipsize(n)}),JSON.parse(n)}else this.logger.warn("executeJson(): null result",{cmd:t})})}executeJsonToA(t){return i(this,void 0,void 0,function*(){return c.thenMap(this.executeJson(t),t=>Array.isArray(t)?t:[t])})}}P.instance=l.lazy(()=>new P),e.PowerShell=P},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(133),r=n(10),s=n(0),o=n(13);class a{constructor(t,e,n=s.identity){this.name=t,this.numerals=e,this.decodePreparser=n,this.base=e.length}digitsToNumerals(t){return t.map(t=>this.numerals[t]).join("")}encode(t,e=0){const n=[],i=t<0;if(i&&e--,0===(t=Math.abs(t)))n.push(0);else for(;t>0;)n.push(t%this.base),t=Math.floor(t/this.base);for(;n.length<e;)n.push(0);return(i?"-":"")+this.digitsToNumerals(n.reverse())}encodeBuffer(t){if(null==t||0===t.length)return"";const e=[0];for(let n of t)for(e.forEach((t,i)=>{n+=t<<8,e[i]=n%this.base,n=Math.floor(n/this.base)});n>0;)e.push(n%this.base),n=Math.floor(n/this.base);return this.digitsToNumerals(e.reverse())}decode(t){if(null==t||r.blank(t))return;const e="-"===(t=this.decodePreparser(t))[0];e&&(t=t.slice(1));let n=0;for(const e of t){const t=this.numerals.indexOf(e);if(t<0)return;n=n*this.base+t}return e?-1*n:n}randomChars(t){return this.encodeBuffer(i.randomBytes(t+3)).slice(1,t+1)}randomUid(t=25,e=5){return o.splitEvery(this.randomChars(t),e).join("-")}}e.Radix=a,e.Hex=new a("hex","0123456789abcdef",t=>t.toLowerCase()),e.Radix58=new a("Radix58","123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),e.RadixAlphaNum=new a("RadixAlphaNum","0123456789abcdefghijklmnopqrstuvwxyz",t=>t.toLowerCase()),e.GeoRadix=new a("GeoRadix","0123456789bcdefghjkmnpqrstuvwxyz",t=>t.toLowerCase())},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(8),s=n(6),o=n(33),a=n(18),u=n(4),l=n(0),c=n(13);e.fileExtsToDesc=[[["3G2","3GP2"],"3rd Gen. Partnership Project 2 a/v (QuickTime-based)"],[["3GP","3GPP"],"3rd Gen. Partnership Project a/v (QuickTime-based)"],[["ARQ"],"Sony Alpha Pixel-Shift RAW (TIFF-based)"],[["ARW"],"Sony Alpha RAW (TIFF-based)"],[["ASF"],"Microsoft Advanced Systems Format"],[["AVI"],"Audio Video Interleaved (RIFF-based)"],[["CR2"],"Canon RAW 2 (TIFF-based) (CR2 spec)"],[["CR3"],"Canon RAW 3 (QuickTime-based) (CR3 spec)"],[["CRM"],"Canon RAW Movie (QuickTime-based)"],[["CRW","CIFF"],"Canon RAW Camera Image File Format (CRW spec)"],[["DNG"],"Digital Negative (TIFF-based)"],[["ERF"],"Epson RAW Format (TIFF-based)"],[["EXIF"],"Exchangeable Image File Format metadata (TIFF-based)"],[["EXV"],"Exiv2 metadata file (JPEG-based)"],[["GIF"],"Compuserve Graphics Interchange Format"],[["GPR"],"GoPro RAW (DNG-based)"],[["JPEG","JPG","JPE"],"Joint Photographic Experts Group image"],[["M2TS","MTS","M2T"],"MPEG-2 Transport Stream (used for AVCHD video)"],[["M4A","M4B","M4P","M4V"],"MPEG-4 Audio/Video (QuickTime-based)"],[["MEF"],"Mamiya (RAW) Electronic Format (TIFF-based)"],[["MIE"],"Meta Information Encapsulation (MIE specification)"],[["MOV","QT"],"Apple QuickTime Movie"],[["MP4"],"Motion Picture Experts Group version 4 (QuickTime-based)"],[["MPEG","MPG","M2V"],"Motion Picture Experts Group version 1 or 2"],[["MQV"],"Sony Mobile QuickTime Video"],[["MRW"],"Minolta RAW"],[["NEF"],"Nikon (RAW) Electronic Format (TIFF-based)"],[["NRW"],"Nikon RAW (2) (TIFF-based)"],[["ORF"],"Olympus RAW Format (TIFF-based)"],[["PNG"],"Portable Network Graphics"],[["PPM","PBM","PGM"],"Portable Pixel/Bit/Gray Map"],[["RAF"],"FujiFilm RAW Format"],[["RAW"],"Panasonic RAW (TIFF-based)"],[["RW2"],"Panasonic RAW 2 (TIFF-based)"],[["RWL"],"Leica RAW (TIFF-based)"],[["SR2"],"Sony RAW 2 (TIFF-based)"],[["SRF"],"Sony RAW Format (TIFF-based)"],[["SRW"],"Samsung RAW format (TIFF-based)"],[["THM"],"Thumbnail image (JPEG)"],[["TIFF","TIF"],"Tagged Image File Format"],[["WEBM"],"Google Web Movie (Matroska-based)"],[["WEBP"],"Google Web Picture (RIFF-based)"],[["WMV"],"Windows Media Audio/Video (ASF-based)"],[["XMP"],"Extensible Metadata Platform sidecar file"]];const d=e.fileExtsToDesc.map(([t])=>t);function h(t){return u.flatten(i.compact(t.map(t=>t.toUpperCase()).map(t=>d.find(e=>e.includes(t))))).map(m)}function f(t){return r.blank(t)?void 0:c.ensurePrefix(a.toS(t),".").toLowerCase()}function p(t){const e=new Set(i.compactBlanks(t.map(f)));return t=>l.orElse(s.map(f(t),t=>e.has(t)),!1)}function m(t){return c.ensurePrefix(t,".").toUpperCase()}e.BaseSharpImageExts=["GIF","JPEG","PNG","PPM","TIFF","THM","WEBP"],e.SharpImageExts=h(e.BaseSharpImageExts),e.isSharpExt=p(e.SharpImageExts),e.sharpSupportedMimeTypes=new Set(["image/gif","image/jpeg","image/pjpeg","image/png","image/tiff","image/webp"]),e.isSharpMimetype=function(t){return e.sharpSupportedMimeTypes.has(a.toS(t).toLowerCase())},e.BaseRawImageExts=["ARQ","ARW","CR2","CR3","CRW","DNG","ERF","GPR","MEF","MRW","NEF","NRW","ORF","RAF","RAW","RW2","RWL","SR2","SRF","SRW"],e.RawImageExts=h(e.BaseRawImageExts),e.isRawImageExt=p(e.RawImageExts),e.BaseVideoExts=["3G2","3GP","ASF","AVI","CRM","M4A","MOV","MP4","MPEG","MQV","MTS","WEBM","WMV"],e.VideoExts=h(e.BaseVideoExts),e.isVideoExt=p(e.VideoExts),e.SidecarExtsEnum=o.strEnum("EXIF","EXV","MIE","XMP"),e.SidecarExts=h(o.strEnumValues(e.SidecarExtsEnum)),e.isSidecarExt=p(e.SidecarExts),e.AssetFileExts=[...e.SharpImageExts,...e.RawImageExts,...e.VideoExts].sort(),e.AllExifExts=[...e.AssetFileExts,...e.SidecarExts].sort(),e.browserImgExts=h(["JPEG","PNG"]),e.browserExts=h(["JPEG","PNG","GIF","MP4","WEBM","WEBP"]),e.asExt=m,e.ExtTypes=o.strEnum("image","raw","video"),e.extType=function(t){return e.isSharpExt(t)?e.ExtTypes.image:e.isRawImageExt(t)?e.ExtTypes.raw:e.isVideoExt(t)?e.ExtTypes.video:void 0}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(35),r=n(9),s=n(27);e.setUnrefTimeout=function(t,e,...n){return s.tap(i.setTimeout(t,Math.round(e),n),t=>t.unref())},e.setUnrefInterval=function(t,e,...n){return s.tap(i.setInterval(t,Math.round(e),n),t=>t.unref())},e.unref=function(t){return r.maybeCall(t,"unref"),t}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(41),o=n(4),a=n(67),u=n(36),l=n(58);class c{constructor(){this._pushCount=0,this._arr=[],this.nextSettledLatches=[],this.serialLatencyAvg=new a.Average}get arr(){return o.filterInPlace(this._arr,t=>t.pending),this._arr}get pushCount(){return this._pushCount}push(t,e){this._pushCount++;const n=s.isFunction(e)?e():e;return this.arr.push(new u.Deferred(t).observeQuietly(n).finally(()=>this.emitSettled())),n}emitSettled(){this.nextSettledLatches.forEach(t=>t.resolve()),this.nextSettledLatches.length=0}awaitNextSettled(){const t=new l.Latch;return this.nextSettledLatches.push(t),t}serial(t,e){const n=Date.now();return this.push(t,this.awaitAll().then(()=>(this.serialLatencyAvg.push(Date.now()-n),e())))}oneRunAtATime(t,e){return this.pending?this.awaitAll():this.serial(t,e)}maybeRun(t,e){return this.pending?void 0:this.serial(t,e)}get pendingCount(){return r.count(this._arr,t=>t.pending)}get pending(){return this.pendingCount>0}pendingNames(){return this.arr.map(t=>t.name)}get settled(){return 0===this.arr.length}awaitAll(){return 0===this.arr.length?Promise.resolve(void 0):Promise.all(this.arr.map(t=>t.promise)).then(()=>void 0)}}e.Promises=c,e.oneRunAtATime=function(t,e){const n=new c;return()=>n.oneRunAtATime(t,e)},e.maybeRun=function(t,e){const n=new c;return()=>n.maybeRun(t,e)},e.serially=function(t,e){const n=new c;return()=>n.serial(t,e)},e.withBoundedConcurrency=function({name:t,laters:e,maxConcurrent:n=4}){return i(this,void 0,void 0,function*(){const i=[],r=new c;for(const s of e){for(;r.pendingCount>=n;)yield r.awaitNextSettled();i.push(r.push(t,s))}return Promise.all(i)})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(133),r=n(43),s=n(9),o=n(15),a=n(48);function u(t,n=e.HashBits){return i.createHash("sha512").update(t).digest().slice(0,n/8)}e.HashBits=192,e.fileSha=function(t,n){const a=r.createReadStream(t,{autoClose:!0}),u=i.createHash("sha512");let l=0;const c=o.Opt(n).flatMap(t=>t.msbits).getOrElse(()=>e.HashBits)/8,d=s.map(n,t=>t.observer);return new Promise((t,e)=>{a.on("error",t=>e(t)),a.on("data",t=>{l+=t.length,s.map(d,t=>t.onProgress(l)),u.update(t)}),a.on("end",()=>t(u.digest().slice(0,c)))})},e.stringSha=u,e.shortStringSha=function(t,e=9,n=a.Radix58,i=224){return n.encodeBuffer(u(t,i)).substring(0,e)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(14),o=n(1),a=n(0),u=n(80),l=n(36),c=n(3),d=n(2);e.keyedLazy=function(t,e,n,h){const f=c.lazy(()=>o.mkLogger("KeyedLazy("+t+")")),p=[],m=()=>i(this,void 0,void 0,function*(){try{return yield e()}catch(t){return void f().warn("key() failed: "+t)}}),g=()=>i(this,void 0,void 0,function*(){const e=yield m();if(r.filterInPlace(p,t=>(null==e||t.name===e)&&t.start+h.priorResultTtlMs>Date.now()&&!t.rejected),r.sortByInPlace(p,t=>[t.resolved,t.start]),null==e||p.length>0)return a.map(p[p.length-1],t=>t.promise);const i=new l.Deferred(e).setTimeout(h.timeoutMs).observe((()=>h.maxRetries<=0?n():u.retryOnReject(n,{maxRetries:h.maxRetries}))());return i.promise.catch(n=>{f().warn("Caught error",{newKey:e,startAgoMs:Date.now()-i.start,error:n}),s.emitNonFatal(t+" failed",n)}),p.push(i),i.promise});return g.clear=()=>p.length=0,g.prior=()=>{r.greatestBy(p,t=>t.start)},g.refresh=()=>(g.clear(),g()),g.set=t=>d.thenMap(m(),e=>{p.length=0,p.push(new l.Deferred(e).resolve(t))}),g}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(96),s=n(5),o=n(37),a=n(25),u=n(0),l=n(21);e.ReadableBuffer=class extends r.Readable{constructor(t){super(),this.push(t),this.push(null)}},e.end=function(t){return i(this,void 0,void 0,function*(){null!=t&&(u.Try(()=>u.maybeCall(t,"unref")),l.ending()?t.end(null):yield new Promise(e=>t.end(null,e)),yield o.delay(50),u.Try(()=>u.maybeCall(t,"destroy")))})},e.close=function(t){return i(this,void 0,void 0,function*(){null!=t&&(u.Try(()=>u.maybeCall(t,"unref")),l.ending()?t.close(()=>{}):yield new Promise(e=>t.close(e)),yield o.delay(50),u.Try(()=>u.maybeCall(t,"destroy")))})},e.onError=function(t,e){[{name:"cp",ea:t},{name:"stdin",ea:t.stdin},{name:"stdout",ea:t.stdout},{name:"stderr",ea:t.stderr}].forEach(({name:t,ea:n})=>u.map(n,n=>n.on("error",n=>{a.isIgnorableError(n)||e(t,n)})))},e.closeStreams=function(t){null!=t&&[t.stdin,t.stdout,t.stderr].forEach(t=>u.Try(()=>u.map(t,t=>t.destroy())))},e.pipelinePromise=function(t){return new Promise((e,n)=>{const i=[];t.forEach(t=>t.on("error",t=>{i.push(t)})),r.pipeline(t,t=>o.later(()=>{null!=t?n(t):s.isNotEmpty(i)?n(a.asError(i)):e()},10))})},e.remoteDesc=function(t){return t.destroyed?"destroyed":`${t.remoteFamily}:${t.remoteAddress}:${t.remotePort}`}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.lazy=function(t){let e,n=!1;return()=>{if(!n){n=!0;try{e=t()}catch(t){}}return e}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(17),r=n(123),s=n(162),o=n(7);function a(t){return{width:t.height,height:t.width}}e.dimToS=function(t){return`${t.width}×${t.height}`},e.maybeFlip=function(t,e){return r.flippable(e)?a(t):t},e.maybeFlipInPlace=function(t,e){r.flippable(e)&&([t.width,t.height]=[t.height,t.width])},e.flip=a,e.isPortrait=function(t){return t.height/t.width>=4/3},e.dmegapixels=function(t){return o.megapixels(t.width*t.height)},e.ltBoth=function(t,e){return o.lt(t.width,e.width)&&o.lt(t.height,e.height)};const u={x:76800,y:500},l={x:2073600,y:3e3};e.roughVideoBitrateKbps=function(t){return i.clamp(300,5e3,Math.floor(s.lerp2d(u,l,t.width*t.height)))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(131),s=n(7);function o(t,e){const n=new r.CountingSet;return t.forEach(t=>s.mapFinite(t,t=>n.incr(t))),n.top(e).map(t=>t[0])}function a(t){return t.reduce((t,e)=>t+e,0)}function u(t){return i.isEmpty(t)?NaN:a(t)/t.length}function l(t){const e=u(t);return u(t.map(t=>Math.pow(t-e,2)))}function c(t){return Math.sqrt(t.reduce((t,e)=>t+e*e,0))}function d(t,e){return t.reduce((t,n,i)=>t+n*e[i],0)}e.min=function(t){return t.reduce((t,e)=>null==t?e:null==e||t<=e?t:e,void 0)},e.max=function(t){return t.reduce((t,e)=>null==t?e:null==e||t>=e?t:e,void 0)},e.deltas=function(t){return null==t||t.length<=1?[]:t.slice(1).map((e,n)=>e-t[n])},e.modes=o,e.mode=function(t){return o(t,1)[0]},e.sum=a,e.avg=u,e.variance=l,e.stdDev=function(t){return Math.sqrt(l(t))},e.weightedAvg=function(t){let e;for(const n of t)e=null==e?n:(e+n)/2;return null==e?NaN:e},e.l2norm=c,e.dot=d,e.cosineSimilarity=function(t,e){return d(t,e)/(c(t)*c(e))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.Latch=class{constructor(t){this.id=t,this._state="pending",this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(){return this.pending&&this._resolve(),this._state="resolved",this}reject(t){return this.pending&&this._reject(t),this._state="rejected",this}observe(t){return t.then(()=>this.resolve()).catch(t=>this.reject(t)),this}observeQuietly(t){return t.then(()=>this.resolve()).catch(()=>this.resolve()),this}get pending(){return"pending"===this._state}get settled(){return!this.pending}get resolved(){return"resolved"===this._state}get rejected(){return"rejected"===this._state}get state(){return this._state}then(t){return this.promise.then(t)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(17),r=new Intl.NumberFormat;e.fmt=function(t){return r.format(t)},e.KB=1e3,e.MB=1e3*e.KB,e.GB=1e3*e.MB,e.TB=1e3*e.GB,e.KiB=1024,e.MiB=1024*e.KiB,e.GiB=1024*e.MiB,e.TiB=1024*e.GiB;const s=["B","KB","MB","GB","TB","PB"],o=["B","KiB","MiB","GiB","TiB","PiB"];e.fmtBytes=function(t,e=3){const n=Math.floor(Math.log10(t)),r=Math.floor(n/3),o=Math.pow(10,3*r),a=s[r];return i.sigFigs(t/o,e)+" "+a},e.fmtMebi=function(t,e=3){const n=Math.floor(Math.log2(t)),r=Math.floor(n/10),s=Math.pow(2,10*r),a=o[r];return i.sigFigs(t/s,e)+" "+a},e.MP=1e6,e.megapixels=function(t){return i.sigFigs(t/e.MP,3)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.wmic=()=>"wmic",e.fsutil=()=>"fsutil",e.nslookupWin=()=>"nslookup",e.pingWin=()=>"ping",e.arpWin=()=>"arp"},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=["number","string","boolean"];function s(t){return-1!==r.indexOf(typeof t)}function o(t,e){return null==t&&null==e?0:null==t?-1:null==e?1:"string"==typeof t&&"string"==typeof e?t.localeCompare(e):Array.isArray(t)&&Array.isArray(e)?a(t,e):t>e?1:t<e?-1:0}function a(t,e){if(i.isEmpty(t)&&i.isEmpty(e))return 0;const n=Math.min(t.length,e.length);for(let i=0;i<n;i++){const n=o(t[i],e[i]);if(0!==n)return n}return o(t.length,e.length)}e.isPrimitive=s,e.isPrimitiveArray=function(t){return Array.isArray(t)&&t.every(s)},e.cmp=o,e.cmpArr=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(3),r=n(14),s=n(40),o=n(74),a=n(6),u=n(66);let l=!0;function c(){return l}e.dbRpc=c,e.setDbRpc=function(t){l=t,t===(null==u.dbClient.prior())&&u.dbClientEnd(),t?(s.setRpcMountpointsImpl(e.rpcMountpoints),o.setRpcVolumesImpl(e.rpcVolumes)):(s.setRpcMountpointsImpl(void 0),o.setRpcVolumesImpl(void 0))},e.rpcMountpoints=i.lazy(()=>a.mapOr(u.dbClient(),t=>t.request("mountpoints"),s.nonRpcMountpoints),1e3),e.rpcVolumes=i.lazy(()=>a.mapOr(u.dbClient(),t=>t.request("volumes"),o.nonRpcVolumes),1e3),r.onClearCache(()=>{e.rpcMountpoints.clear(),e.rpcVolumes.clear()}),e.assertLocalDb=function(){if(c())throw new Error("only supported on db-local processes")},e.assertDbRpc=function(){if(!c())throw new Error("only supported on db-remote processes")}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(44),r=n(185);e.BoundedMap=class extends i.TTLMap{constructor(t,e,n){super(t,new r.MRUMap(e,n)),this.maxSize=e,this.fifo=n}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.version="0.6.0-alpha.1",e.release="0.6.0-alpha.1+20190821062758",e.gitSha="db7c291e059bae500abafeeb1d58b7434096f821",e.gitDate=new Date(1566368878e3)},function(t,e){t.exports=require("exiftool-vendored")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(191),r=n(58),s=n(3),o=n(1),a=n(0),u=n(258),l=n(12),c=n(62),d=o.mkLogger("DbClient");e.dbClient=s.lazy(()=>{if(c.dbRpc()){const t=l.Settings.rpcPort.valueOrDefault;return d.info("Creating new dbClient to "+t),new u.Client("db@localhost:"+t,()=>(function(t){const e=new r.Latch,n=new i.Socket;return n.on("error",t=>e.reject(t)),n.connect(t,"localhost",()=>{d.info("Connected to "+t),e.resolve()}),e.then(()=>n)})(t))}}),e.dbClientReady=s.lazy(()=>a.map(e.dbClient(),t=>t.ping().then(t=>(d.debug("dbClientReady(): ping returned "+t),!0)).catch(t=>(d.warn("dbClientReady(): ping failed",t),!1))),5e3),e.dbClientEnd=function(){const t=e.dbClient.prior();return e.dbClient.clear(),a.map(t,t=>t.end())}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(130),s=n(131),o=n(7),a=n(0),u=n(57);e.Average=class{constructor(t=10,e=0,n=0){this.maxSamples=t,this._k=e,this._avg=n,this._weightedTotalAvg=n,this._samples=new r.BoundedList(t)}push(t){if(!isFinite(t))throw new Error("Average.push("+t+"): not a number");if(this._k++,this._samples.push(t),this._min=null==this._min?t:Math.min(t,this._min),this._max=null==this._max?t:Math.max(t,this._max),1===this._k)this._m=t,this._v=0,this._avg=t,this._weightedTotalAvg=t;else{const e=this._m;this._m+=(t-this._m)/this._k,this._v+=(t-e)*(t-this._m),this._avg=this._avg*(this._k-1)/this._k+t/this._k,this._weightedTotalAvg=(this._weightedTotalAvg+t)/2}return t}stats(t=2){const e={k:o.sigFigs(this.k,t)};if(!this.empty){const n=e=>a.map(e,e=>o.sigFigs(e,t));e.mean=n(this.avg),e.max=n(this.max),e.min=n(this.min)}return e}get empty(){return 0===this._k}get k(){return this._k}get avg(){return this.empty?void 0:o.sigFigs(this._avg,4)}get max(){return this._max}get min(){return this._min}get stdDev(){return this._k<2?void 0:Math.sqrt(this._v/(this._k-1))}get sampleMode(){if(this.empty)return;const t=new s.CountingSet;this._samples.forEach(e=>t.incr(e));const e=t.entriesByCountDesc(),n=e[0][1],r=e.filter(([,t])=>t===n);return i.sortBy(r,([t])=>o.absdiff(this._avg,t))[0][0]}get sampleStdDev(){return i.mapNotEmpty(this._samples,u.stdDev)}get sampleAvg(){return i.mapNotEmpty(this._samples,u.avg)}get samples(){return[...this._samples]}p(t){if(0===this._samples.length)return 0;const e=[...this._samples].sort((t,e)=>t-e);return e[Math.floor(e.length*(t/100))]}get weightedAvg(){return i.mapNotEmpty(this._samples,t=>o.sigFigs(u.weightedAvg(t),4))}get weightedTotalAvg(){return this._weightedTotalAvg}clear(){this._avg=0,this._k=0,this._weightedTotalAvg=0,this._samples.length=0}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(18),r=n(4),s=n(3),o=n(10),a=n(1),u=n(7),l=n(0),c=n(100),d=n(13);class h{constructor(t){this.h=t,this.text=l.orElse(t.text,i.toS(t)),this.greedyLeft=l.orElse(t.greedyLeft,!1)}toEntry(t){return[this.text,t.substring(this.leftIdx,this.rightIdx).trim()]}}const f=s.lazy(()=>a.mkLogger("Fixed"));e.parseFixed=function(t,e,n=!0){return new p(t,e,n).entries};class p{constructor(t,e,n=!0){this.warnIfMissingHeaders=n;const i=e.split(/[\r\n]{1,2}/);this.headerRow=i[0],this.rows=i.slice(1);const s=Math.max(...this.rows.map(t=>t.length));this.col2blanks=new Map(u.times(s,t=>[t,r.count(this.rows,e=>o.blank(e[t]))])),this.headers=this.extractHeaders(t.map(t=>new h(t))),this.entries=this.rows.map(t=>this.headers.map(e=>e.toEntry(t))).map(t=>l.fromEntries(t)).filter(t=>l.values(t).some(o.notBlank))}extractHeaders(t){let e=this.headerRow;r.sortBy(t,t=>-t.text.length),f().trace("extractHeaders()",t),t.forEach(t=>{const n=new RegExp(`\\b${t.text}\\b`,"i"),i=n.exec(e);null==i?this.warnIfMissingHeaders&&f().warn("extractHeaders(): Failed to find header!",{re:n,headerLine:e}):(t.indexOf=i.index,e=d.padReplace(e,i.index,t.text.length," "))});const n=t.filter(t=>null!=t.indexOf),i=r.sortBy(n,t=>t.indexOf);f().trace("extractHeaders()",{byAppearance:i}),i.forEach((t,e)=>{const n=t.indexOf,r=i[e-1],s=0===e?0:r.indexOf+r.text.length-1,[o,a]=t.greedyLeft?[s,n]:[n,s];t.leftIdx=l.map(this.firstBlankColumn(o,a),t=>t+1),0===e&&null==t.leftIdx&&(t.leftIdx=0),f().trace("extractHeaders(): finding leftIdx",{from:n,to:s,header:t}),null==t.leftIdx&&f().warn("no blank column for "+t.text+" between "+n+" and "+s)}),r.filterInPlace(i,t=>null!=t.leftIdx),i.slice(0,-1).forEach((t,e)=>{const n=i[e+1];t.rightIdx=n.leftIdx-1});const s=r.toA(c.diff(t.map(t=>t.text),i.map(t=>t.text)));return s.length>0&&f().warn("Missing headers",{missingHeaders:s}),i}firstBlankColumn(t,e){return r.range(t,e).find(t=>this.col2blanks.get(t)===this.rows.length)}}e.Fixed=p},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(22),r=n(9);e.getEnv=function(t){return r.firstValueCaseInsensitive(i.env,t)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(6);e.thenOpt=function(t){return o(t)?t:new s(()=>t)};class s{constructor(t){this.a=t}_map(t,e){return i(this,void 0,void 0,function*(){const n=null!=this.a?yield this.a():void 0,i=o(n)?yield n.get():n;return null!=i?t(i):e()})}isDefined(){return i(this,void 0,void 0,function*(){return this._map(()=>!0,()=>!1)})}isEmpty(){return i(this,void 0,void 0,function*(){return this._map(()=>!1,()=>!0)})}get(){return i(this,void 0,void 0,function*(){return this._map(t=>t,()=>void 0)})}getRequired(){return i(this,void 0,void 0,function*(){return this._map(t=>t,()=>{throw new Error("unexpectedly undefined")})})}exists(t){return i(this,void 0,void 0,function*(){return this._map(t,()=>!1)})}map(t){return new s(()=>i(this,void 0,void 0,function*(){return this._map(t,()=>void 0)}))}flatMap(t){return new s(()=>i(this,void 0,void 0,function*(){return this._map(t,()=>void 0)}))}filter(t){return new s(()=>i(this,void 0,void 0,function*(){return this._map(e=>i(this,void 0,void 0,function*(){return(yield t(e))?e:void 0}),()=>void 0)}))}catch(t){return new s(()=>this.get().catch(e=>i(this,void 0,void 0,function*(){return t(e)})))}forEach(t){return new s(()=>i(this,void 0,void 0,function*(){const e=yield this.get();return yield r.map(e,t),e}))}getOrElse(t){return i(this,void 0,void 0,function*(){return r.orElse(yield this.get(),t)})}orElse(t){return new s(()=>i(this,void 0,void 0,function*(){const e=yield this.get(),n=null==e?yield t():e;return o(n)?n.get():n}))}}function o(t){return t instanceof s}e.OptAsync=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(14);let r=new(n(233).PermissiveWorkPlanner);e.getWorkPlanner=function(){return r},e.setWorkPlanner=function(t){r=t},e.work=function(t,e){return r.work(t,e)},e.isPaused=function(){return r.isPaused()},e.pause=function(){r.isPaused()||(r.pause(),i.emitPause())},e.resume=function(){r.isPaused()&&(r.resume(),i.emitResume())}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(10),r=n(127);function s(t){return e=>i.blank(e)?"":t(e)}e.black=s(r.default.black),e.blue=s(r.default.blue),e.cyan=s(r.default.cyan),e.green=s(r.default.green),e.grey=s(r.default.grey),e.magenta=s(r.default.magenta),e.red=s(r.default.red),e.yellow=s(r.default.yellow)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(6),s=n(4),o=n(38),a=n(57),u=n(27);e.groupBy=function(t,e){const n=new l;return t.forEach(t=>r.map(e(t),e=>n.add(e,t))),n};class l{constructor(t=new Map){this.store=t}get(t){return this.store.get(t)}has(t){return this.store.has(t)}get keyCount(){return this.store.size}get valueCount(){return a.sum([...this.store.values()].map(t=>t.length))}add(t,e){return u.tap(o.getOrSet(this.store,t,()=>[]),t=>t.push(e))}delete(t,e){if(null==e)return this.store.delete(t);{const n=this.store.get(t);if(null==n)return!1;{const i=s.remove(n,e);return i&&0===n.length&&this.store.delete(t),i}}}clear(){return this.store.clear(),this}keys(){const t=this;return function*(){for(const[e,n]of t.store.entries())n.length>0&&(yield e)}()}values(){const t=this;return function*(){for(const[,e]of t.store.entries())e.length>0&&(yield e)}()}flatValues(){const t=this;return function*(){for(const[,e]of t.store.entries())if(e.length>0)for(const t of e)yield t}()}entriesArray(){return[...this.store.entries()].filter(([,t])=>s.isNotEmpty(t))}entries(){const t=this;return function*(){for(const[e,n]of t.store.entries())n.length>0&&(yield[e,n])}()}tuples(){const t=this;return function*(){for(const[e,n]of t.store.entries())for(const t of i.toA(n))null!=t&&(yield[e,t])}()}filterInPlace(t){let e=!1;for(const[n,i]of this.store.entries()){const r=i.length;s.filterInPlace(i,e=>t(n,e)),e=e||r!==i.length}return e}}e.MultiMap=l},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(8),o=n(16),a=n(46),u=n(15),l=n(4),c=n(53),d=n(3),h=n(2),f=n(10),p=n(29),m=n(69),g=n(14),y=n(28),v=n(1),w=n(158),b=n(23),S=n(13),P=n(216),M=n(217),x=n(219),E=n(220),_=n(222),k=n(40),T=n(223),O=n(159),D=n(24),F=d.lazy(()=>v.mkLogger("Volumes"));let C;e.nonRpcVolumes=c.keyedLazy("volumes",k.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){const t=yield b.isWin?M.dfWin():P.dfPosix();if(null==t)return void F().warn("df failed");if(t.some(t=>t.remote&&s.blank(t.remoteHost))&&(yield h.thenOrTimeout(b.isWin?O.addRemoteVolumeInfoWin(t):T.addRemoteVolumeInfoPosix(t),10*o.secondMs).catch(t=>{g.emitNonFatal("Failed to get remote volume info",t)})),null==(yield(b.isWin?_.addLocalVolumeInfoWin(t):b.isMac?x.addLocalVolumeInfoMac(t):E.addLocalVolumeInfoPosix(t)).catch(t=>{g.emitNonFatal("Failed to get local volume info",t)})))return void F().warn("addLocalVolumeInfo failed");t.forEach(t=>s.mapNotBlank(t.remoteHost,e=>t.remoteHost=e.toLowerCase().normalize().trim())),t.forEach(t=>{t.remote=!!p.truthy(t.remote),!t.remote&&s.blank(t.uuid)&&(t.uuid=JSON.stringify({size:t.size}))});const e=l.sortBy(t,t=>t.mountpoint).filter(t=>!p.truthy(t.ignorable));return F().info("_volumes(): final result",e),Object.freeze(e)})},{maxRetries:2,timeoutMs:1.5*D.cmdTimeoutMs,priorResultTtlMs:D.longTtlMs}),g.onClearCache(()=>e.nonRpcVolumes.clear()),e.setRpcVolumesImpl=function(t){C=t};let I=[];function A(){return i(this,void 0,void 0,function*(){try{return yield h.thenTap((C||e.nonRpcVolumes)(),t=>{r.mapNotEmpty(t,t=>{const e=t.map(t=>t.mountpoint).sort();a.eql(I,e)||(g.emitVolumesChanged(),I=e)})})}catch(t){return void g.emitNonFatal("volumes() failed",t)}})}function L(t){return i(this,void 0,void 0,function*(){return h.thenMap(A(),e=>R(e,t))})}function R(t,e){const n=t.filter(t=>y.containedByNativePath(e,t.mountpoint));return l.greatestBy(n,t=>r.commonPrefixLength(t.mountpoint,e))}function N(t,e,n){return i(this,void 0,void 0,function*(){const r=n.filter(t=>S.equalsIgnoreCase(e,t.remoteShare));if(l.isEmpty(r))return;const s=r.find(e=>p.truthy(e.remote)&&f.notBlank(e.remoteHost)&&S.equalsIgnoreCase(t,e.remoteHost));if(null!=s)return s;const o=yield w.friendlyname(t);return h.asyncFind(r,t=>i(this,void 0,void 0,function*(){return S.equalsIgnoreCase(o,yield w.friendlyname(t.remoteHost))}))})}e.volumes=A,e.rootPath=d.lazy(()=>b.isWin?u.Opt(m.getEnv("SystemDrive")).filter(f.notBlank).orElse(()=>"C:").map(t=>S.ensureSuffix(t,"\\")).get():"/"),e.rootVolume=function(){return L(e.rootPath())},e.volumeFor=L,e.bestVolume=R,e.remoteVolumeFor=function(t,e){return i(this,void 0,void 0,function*(){return h.thenMap(A(),n=>N(t,e,n))})},e.bestRemoteVolume=N},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(39),s=n(3),o=n(2),a=n(11),u=n(52),l=n(32),c=n(1),d=n(48),h=n(13),f=s.lazy(()=>c.mkLogger("ImgTmp"));function p(t,n,r){return i(this,void 0,void 0,function*(){const i=yield t.stat();if(null==i)return void f().warn("tmpImgFile(): src.stat() was null",{src:t,desc:n,ext:r});const s=yield e.imgtmpDir();if(null==s)return void f().warn("tmpImgFile: null imgTmpDir");const o=d.GeoRadix.encodeBuffer(u.stringSha(JSON.stringify({src:t.nativePath,size:i.size,mtime:i.mtimeMs})));r=h.ensurePrefix(r,".");const a=s.join(...h.splitEvery(o.slice(0,24),2,3),n+r);return yield a.parent().mkdirp(),f().info("tmpImgFile("+t.baseWithGrandparent+")",{desc:n,ext:r,result:a}),a})}e.imgtmpDir=s.lazy(()=>i(this,void 0,void 0,function*(){return l.PosixFile.for(r.App.temp()).mkNoMedia()}),a.minuteMs),e.tmpImgFile=p,e.readableToFile=function(t,e,n,r){return i(this,void 0,void 0,function*(){try{return yield o.thenMap(p(t,e,n),t=>t.applyIfEmpty(t=>i(this,void 0,void 0,function*(){return o.thenMap(r(),e=>t.writeStream(e))})))}catch(e){throw f().warn("readableToFile("+t+"): "+e),e}})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(8),s=n(6),o=n(17),a=n(9),u=n(3),l=n(52),c=n(114),d=n(1),h=n(0),f=n(19);e.zeroesRe=/^[\s0]*$/;const p=u.lazy(()=>d.mkLogger("ExifUid"));function m(t){return null==t||o.isNumber(t)?0===t:null!=e.zeroesRe.exec(f.toS(t))}function g(t){return null!=t&&r.notBlank(t)&&!m(t)}function y(t,e){return f.toS(t).split(e).map(t=>o.mapIntOr(t,t=>f.toS(o.sigFigs(t,2)),()=>t)).join(e)}e.zeroish=m,e.compactZeroes=function(t){return a.mapFields(t,(t,e)=>m(e)?void 0:[t,e])},e.present=g,e.sigfigish=y,e.normalizeExposureSettings=function(t){if(null==t)return;const e={focalLength:f.toS(t.focalLength).trim(),aperture:o.mapNumeric(t.aperture,t=>o.sigFigs(t,2)),shutterSpeed:y(t.shutterSpeed,"/"),iso:o.mapInt(t.iso,t=>o.sigFigs(t,2))};return p().debug("normalizeExposureSettings("+f.toS(t.FileName)+")",e),h.reqValuedOrElse(e)},e.cameraId=function(t){return a.pickFirst(t,["SerialNumber","CameraSerialNumber","BodySerialNumber","InternalSerialNumber"],t=>r.notBlank(t)&&!m(t))},e.imageId=function(t,{includeImageUniqueId:e=!0}={}){return a.pickFirst(t,i.compact(["BurstUUID","ImageNumber","ShutterCount",e?"ImageUniqueID":void 0,"RunTimeValue"]),g)},e.uidGeoHash=function(t,e){return c.geohash(o.toFixed(t,4),o.toFixed(e,4))},e.serializeUidPojo=function(t,e=28){return s.map(t,t=>l.shortStringSha(JSON.stringify(t),e)+":v"+t.version)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(9),r=n(84),s=n(63);e.memoize=function(t,e,n){let o=0;const a=new s.BoundedMap(e,n,!0),u=e=>(o++,a.getOrSet(JSON.stringify(e),()=>i.tap(t(e),t=>{r.isPromise(t)&&t.catch(()=>u.clear())})));return u.clear=t=>null==t?a.clear():a.delete(JSON.stringify(t)),u.prior=()=>new Map(a.entries()),u.size=()=>a.size,u.callCount=()=>o,u}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(30),r=n(5),s=n(9),o=n(18);e.joinQuery=function(t,e){if(null==e)return t;const n=s.entries(e).filter(([,t])=>null!=t);return r.isEmpty(n)?t:t+"?"+n.map(t=>t.map(o.toS).map(encodeURIComponent).join("=")).join("&")},e.parent=function(t){return i.posix.parse(t).dir},e.PS_LIBRARY_PROTOCOL="pslib:",e.PS_LOCAL_FILE_PROTOCOL="psfile:",e.OLD_PS_LOCAL_FILE_PROTOCOL="psvol:",e.PS_NETWORK_FILESYSTEM_PROTOCOL="psnet:"},function(t,e){t.exports=require("luxon")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(15);e.retryOnReject=function(t,e){const n=r.Opt(e.errorIsRetriable).getOrElse(()=>()=>!0),s=r.Opt(e.onRetryWaitUntil).getOrElse(()=>()=>Promise.resolve());let o=0;const a=()=>i(this,void 0,void 0,function*(){try{return yield t()}catch(t){if(n(t)&&o<e.maxRetries)return o++,yield s(o),a();throw t}});return a()}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(87),s=n(22),o=n(5),a=n(8),u=n(16),l=n(6),c=n(17),d=n(15),h=n(18),f=n(39),p=n(4),m=n(21),g=n(3),y=n(2),v=n(51),w=n(50),b=n(11),S=n(14),P=n(34),M=n(28),x=n(1),E=n(38),_=n(7),k=n(0),T=n(23),O=n(187),D=n(47),F=g.lazy(()=>x.mkLogger("Pids"));function C(t,e){return i(this,void 0,void 0,function*(){return null!=t&&null!=e&&(t.name===h.toS(e.pid)&&A(yield t.readJSON(),e))})}e.addPid=function(t,e){return L.instance().addPid(t,e)};const I=10*u.secondMs;function A(t,e){if(null==t||null==e)return!1;const n=l.map(e.start,t=>t.getTime()),i=t.startTime;return _.gt0(n)&&_.gt0(i)&&Math.abs(n-i)<I}class L{constructor(t=P.BaseFile.for(f.App.userData()).join("pids")){this.pidsDir=t,this.p=new v.Promises,this.killOldProcs=(t={})=>this.p.serial("killOldProcs()",()=>i(this,void 0,void 0,function*(){const e=k.orElse(t.everything,!1),n=k.orElse(t.force,T.isWin),i=yield this.pidfiles(),r=yield E.toMapAsync(i,t=>y.thenMap(t.readJSON(),t=>[t.pid,t])),a=o.uniq(p.flatten(o.toA(r.values()).map(t=>[t.pid,t.ppid])));if(o.isEmpty(a))return F().debug("killOldProcs(): no pidfiles"),[];const u=yield O.pidInfos(a);if(F().debug("killOldProcs()",{pids:a,allEntries:u}),null==u)return void S.emitNonFatal("Pids.killOldProcs(): failed to get process information");const c=new Set(u.map(t=>t.pid)),d=u.filter(t=>r.has(t.pid)),h=o.sortBy(o.compact(d.map(t=>l.map(r.get(t.pid),e=>A(e,t)?Object.assign({},e,t):void 0))),t=>t.pid).filter(t=>s.pid!==t.pid),f=e?h:h.filter(e=>!c.has(e.ppid)||!c.has(e.pid)||_.gt0(e.timeoutTime)&&Date.now()>=e.timeoutTime||null!=t.everythingBefore&&e.startTime<t.everythingBefore);F().debug("killOldProcs()",{trackedEntries:d,victims:f,pidfiles:o.toA(r.values())});for(const t of f)F().info("killOldProcs(): killing",{entry:t}),R(t.pid,n,!1);return yield this.vacuumPids(),o.sortBy(f,t=>t.pid)}))}addPid(t,e){return i(this,void 0,void 0,function*(){if(null==t)throw new Error("undefined info");const n=t.pid;if(!_.gt0(n))throw new Error("undefined pid");if(!_.gte0(t.maxAgeMs))throw new Error("bad maxAgeMs: "+JSON.stringify(t));const i=this.pidsDir.join(t.pid+".json"),r=d.Opt(k.Try(()=>M.parse(t.cmd).base)).filter(a.notBlank).getOrElse(()=>t.cmd),s=e.getTime(),o=_.mapGt0(t.maxAgeMs,t=>s+t),u=Object.assign({},t,{cmd:r,startTime:s,timeoutTime:o});if(null==(yield i.writeJSON(u)))throw new Error("Failed to write to "+i);return F().debug("addPid() wrote "+i,u),i})}pidfiles(){return this.pidsDir.clear().children(t=>".json"===t.ext&&null!=c.toInt(t.name))}onKill(t){return i(this,void 0,void 0,function*(){const e=this.pidsDir.join(t+".json");return y.thenMap(e.clear().readJSON(),e=>this.addPid(Object.assign({},e,{maxAgeMs:1}),b.ago(u.minuteMs)).catch(e=>{F().info("onKill(): failed to rewrite pidfile: "+e,{pid:t})}))})}vacuumPids(){return i(this,void 0,void 0,function*(){const t=yield this.pidfiles(),e=o.toA(t).map(t=>c.toInt(t.name)).filter(_.gt0);if(o.isEmpty(e))return;const n=yield O.pidInfos(e);if(null!=n){F().info("vacuumPids",{pids:e,pidfiles:o.toA(t).map(t=>t.base),entries:n});for(const e of t){const t=n.find(t=>h.toS(t.pid)===e.name);null!=t&&(yield C(e,t))||(F().info("vacuumPids(): Removing old pidfile "+e.base,{psEntry:t,pidfile:yield e.readFile().then(h.toS).catch(t=>"(failed to read file: "+t+")")}),yield e.unlink())}}else S.emitNonFatal("Failed to get pidInfo for pids "+e)})}}function R(t,e=!1,n=!0){if(t===s.pid||t===s.ppid)throw new Error("cannot self-terminate");return e&&n&&L.instance().onKill(t),T.isWin?function(t,e=!1){return i(this,void 0,void 0,function*(){if(m.ending()||D.PowerShell.instance().ended)return r.kill(t,e);try{const n=o.compact(["Stop-Process","-Id",c.toInt(t),e?"-Force":void 0]).join(" ");yield D.PowerShell.instance().execute(n,k.identity)}catch(n){F().warn("killWin(): pwsh error, using TASKKILL: "+n),r.kill(t,e)}})}(t,e):function(t,e=!1){return i(this,void 0,void 0,function*(){try{s.kill(t,e?"SIGKILL":"SIGTERM")}catch(t){if(!String(t).includes("ESRCH"))throw t}})}(t,e)}function N(t){return i(this,void 0,void 0,function*(){return null!=(yield O.pidInfo(t))})}L.instance=g.lazy(()=>new L),e.Pids=L,e.kill=R,e.pidExists=N,e.pidNotExists=function(t){return y.thenNot(N(t))},e.ProcCleaner=g.lazy(()=>{const t=[{everything:!1,force:!1,intervalMs:5*u.minuteMs},{everything:!1,force:!0,intervalMs:17*u.minuteMs}].map(t=>w.setUnrefInterval(()=>L.instance().killOldProcs(t),t.intervalMs));return m.addCleanupEndable(new m.EndableWrapper("ProcCleaner",()=>(t.map(clearInterval),L.instance().killOldProcs())))})},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(65),s=n(79),o=n(5),a=n(8),u=n(16),l=n(6),c=n(17),d=n(9),h=n(4),f=n(2),p=n(26),m=n(1),g=n(0),y=n(150),v=m.mkLogger("CapturedAt");class w{constructor(t,e,n,i){this.file=t,this.date=e,this.src=n,this.mtime=i}spread(t){const e=Object.assign({},this,t);return new w(e.file,e.date,e.src,e.mtime)}hasTz(){return p.hasZoneOffset(this.date)}hasTime(){return p.hasTime(this.date)}toISOString(){return p.datedToISO(this.date)}toString(){return JSON.stringify({file:this.file.nativePath,date:this.toISOString(),src:this.src,mtime:this.mtime})}}function b(t,e){return i(this,void 0,void 0,function*(){if(null==e||!p.validDate(e))return;if(p.hasZoneOffset(e))return e;const n=yield y.nearestSiblingTzOffset(t);if(null!=n){const t=p.toDateTime(e,n);if(p.validDate(t))return t}return e})}function S(t,e){return i(this,void 0,void 0,function*(){const n=p.datedToMillis(e),i=yield t.stat();if(null==i)return;const s=d.compactValues({bname:p.parseDatedWithTime(y.bname(t)),birthtime:0!==i.birthtimeMs?i.birthtime:void 0,mtime:i.mtime});for(const[i,o]of d.entries(s)){const s=p.diffMillis(o,n);if(null!=s){const n=r.offsetMinutesToZoneName(s/u.minuteMs);if(v.trace(t.baseWithGrandparent+" offset",{tz:n,src:i,deltaHours:c.sigFigs(s/u.hourMs,2),ea:o,ts:e}),null!=n)return{ts:p.toDateTime(e,n),src:i}}}})}function P(t){return g.map(t,t=>h.first(["SubSecDateTimeOriginal","DateTimeOriginal","SubSecCreateDate","CreateDate","SubSecMediaCreateDate","MediaCreateDate","DateTimeCreated","DateTimeUTC","GPSDateTime"],e=>{const n=t[e];if(p.validDate(n))return!p.hasZoneOffset(n)&&a.notBlank(t.tz)?l.orElse(p.toDateTime(n,t.tz),n):n}))}e.CapturedAt=w,e.bestCapturedAt=function(t){return i(this,void 0,void 0,function*(){const e=h.sortBy(t,t=>-t.mtime.getTime());return g.firstThunk(()=>e.find(t=>t.src.startsWith("tags")),()=>e.find(t=>"statname"===t.src),()=>e.find(t=>"siblings"===t.src),()=>e.find(t=>"path"===t.src),()=>t[0])})},e.capturedAtTags=function(t){return t=h.sortBy(o.toA(t),t=>-t.mtime),h.firstNonEmptyThunk(()=>t.filter(t=>t.src.startsWith("tags")),()=>t.filter(t=>"statname"===t.src),()=>t.filter(t=>"siblings"===t.src),()=>t.filter(t=>"path"===t.src),()=>t.filter(t=>"stat"===t.src).slice(1,1),()=>[])},e.hasSubSecCapturedAt=function(t){return null!=t&&h.anyDefined([t.SubSecTime,t.SubSecTimeDigitized,t.SubSecTimeOriginal,t.SubSecCreateDate,t.SubSecDateTimeOriginal])},e.addTzFromSibs=b,e.extractCapturedAt=function(t,e,n){return i(this,void 0,void 0,function*(){const r=yield t.mtime(),o=(o,a)=>f.thenMap(function(t,e,n,r){return i(this,void 0,void 0,function*(){const i=yield n;if(p.validDate(i))return p.hasZoneOffset(i)?i:null!=e&&null!=e.tz&&s.Info.isValidIANAZone(e.tz)?p.toDateTime(i,e.tz):r?i:b(t,i)})}(t,e,a,n),e=>(v.debug("extractCapturedAt()",{f:t.nativePath,src:o,at:p.datedToISO(e)}),new w(t,e,o,r))),a=yield f.firstDefinedPromise(()=>o("tags",P(e)),()=>o("statname",y.extractStatname(t)),()=>n?void 0:o("siblings",y.inferCapturedAtFromSiblings(t)),()=>n?void 0:o("name",p.parseDated(y.bname(t))),()=>n?void 0:o("path",p.extractDateFromPath(t.pathnamesWithoutDrive)),()=>o("stat",t.minStatDate()));if(null!=a&&a.hasTime()&&!a.hasTz()&&"tags"===a.src){const e=yield S(t,a.date);if(null!=e)return v.info("extractCapturedAt(): inferring timezone offset",{capturedAt:a,inferred:e}),a.spread({date:e.ts,src:a.src+" (tz from "+e.src+")"})}return a})},e.inferTzFromFile=S,e.capturedAtFromTags=P},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(11),r=n(26),s=n(7),o=n(6),a=n(18),u=n(155);e.TimestampedModel=class extends u.Model{toID(){return d(this)}get createdAtDate(){return s.mapGt0(this.createdAt,t=>new Date(t))}get updatedAtDate(){return s.mapGt0(this.updatedAt,t=>new Date(t))}$beforeUpsert(){null==this.createdAt&&(this.createdAt=Date.now()),this.updatedAt=Date.now()}$beforeInsert(){this.$beforeUpsert()}$beforeUpdate(){this.$beforeUpsert()}};const l=Math.pow(2,16);function c(t){const e=o.orElse(r.datedToMillis(t),Date.now());return a.toS(i.unixtime(e)%l)}function d(t){return o.map(t,t=>({id:t.id,ts:c(t.updatedAt)}))}e.encodeVersion=c,e.toID=d},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.thenTap=function(t,e=console.dir.bind(console)){return i(this,void 0,void 0,function*(){const n=yield t;return yield e(n),n})},e.isPromise=function(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5);function r(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t))+t}function s(t,e){return Math.random()*(e-t)+t}function o(){return e.RandomChars[r(0,e.RandomChars.length)]}function a(t){const e=Array(...t);for(let t=e.length-1;t>0;t-=1){const n=Math.floor(Math.random()*(t+1));t!==n&&([e[t],e[n]]=[e[n],e[t]])}return e}e.randomInt=r,e.randomFloat=s,e.RandomChars="0123456789abcdefghijkmnopqrstuvwxyz",e.randomChars=function(t){let e="";for(let n=0;n<t;n++)e+=o();return e},e.randomChar=o,e.pickRandom=function(...t){return t[r(0,t.length)]},e.shuffle=a,e.sample=function(t,e){if(e<t.length/10){const n=new Set;for(;n.size<e;)n.add(r(0,t.length));return[...n.keys()].map(e=>t[e])}return a([...t]).slice(0,e)},e.pickWeightedRandom=function(t){if(i.isEmpty(t))return;let e=s(0,i.sum(t,t=>t.priority));return t.find(t=>(e-=t.priority)<=0)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(30),s=n(5),o=n(8),a=n(16),u=n(6),l=n(9),c=n(15),d=n(18),h=n(3),f=n(2),p=n(10),m=n(20),g=n(69),y=n(14),v=n(32),w=n(104),b=n(1),S=n(7),P=n(0),M=n(23),x=n(47),E=n(232),_=n(12),k=n(31),T=n(24),O=n(71),D=n(93),F=h.lazy(()=>b.mkLogger("vlc"));e.vlcVersionDescription=h.lazy(()=>f.thenMapOr(e.vlcInfo().catch(()=>void 0),t=>t.version+("vlc"===t.path?" (found on $PATH)":" from "+t.path),()=>"(not found on $PATH)"));const C=/VLC version (\S+)/i,I=["--intf=dummy","--vout=dummy","--aout=dummy","--quiet"];function A(t){return i(this,void 0,void 0,function*(){return f.thenMap(m.stdoutResult(t,[...I,"--version"],{timeout:T.cmdTimeoutMs,ignoreStderr:!0,quiet:!0}),t=>c.Opt(t.result).filter(o.notBlank).map(t=>t.trim()).flatMap(t=>C.exec(t)).flatMap(t=>E.SemVer.for(t[1])).get())})}function L(t){return f.thenMap(x.PowerShell.instance().execute(`(Get-Item -path "${t}").VersionInfo.FileVersion`,t=>t).catch(e=>{F().warn("Failed to run vlcInfoWin: "+t+": "+e)}),t=>E.SemVer.for(t.trim()))}function R(t){return!p.blank(t)&&t.startsWith("video/")}e.vlcInfo=h.lazy(()=>(function(){return i(this,void 0,void 0,function*(){const t=[_.Settings.vlcPath.valueOrDefault];function e(...e){t.push(v.PosixFile.for(r.join(...e)))}const n=[];if(M.isMac){const t="/Applications/VLC.app/Contents/MacOS/VLC";o.mapNotBlank(g.getEnv("HOME"),n=>e(n+t)),e(t)}if(M.isWin){const t=["VideoLAN","VLC","vlc.exe"];o.mapNotBlank(g.getEnv("LOCALAPPDATA"),n=>{e(n,"Apps",...t)}),o.mapNotBlank(g.getEnv("HOMEPATH"),n=>{e(n,"AppData","Local","Apps",...t)}),o.mapNotBlank(g.getEnv("ProgramFiles"),n=>{e(n,...t)}),o.mapNotBlank(g.getEnv("ProgramFiles(x86)"),n=>{e(n,...t)})}for(const e of t)try{if(e instanceof v.PosixFile&&(yield e.clear().notExists()))continue;const t=e.toString(),i=yield M.isWin?L(t):A(t);if(null==i){F().info("No VLC version found for "+e);continue}if(3===i.major&&0===i.minor)return l.tap({path:t,version:i},t=>F().info("VLC version found!",t));n.push({path:t,unsupportedVersion:i})}catch(t){F().warn("vlcInfo(): err:"+t,{path:e})}return n[0]})})()),e.isVlcSupported=h.lazy(()=>f.thenMapOr(e.vlcInfo(),t=>null!=t.version,()=>!1)),e.vlcPath=h.lazy(()=>f.thenMap(e.vlcInfo(),t=>null==t.version?void 0:t.path)),e.vlcSupportedFile=function(t){return i(this,void 0,void 0,function*(){return!!(yield e.isVlcSupported())&&f.thenMapOr(k.mimetype(t),R,()=>!1)})},e.vlcSupportedMimeType=R,e.vlcFrame=function(t,n,r=1){return i(this,void 0,void 0,function*(){return O.work("vlcFrame()",()=>(function(t,n,r=1){return i(this,void 0,void 0,function*(){const i=yield k.readRawTags(t);if(null==i)throw new Error(t+" has no tags");const o=i.MIMEType;if(null==o)throw new Error(t+" has no MIMEtype");if(!o.startsWith("video/"))throw new Error(t+": unsupported mimetype, "+o);const l=_.Settings.minVideoDimension.valueOrDefault,c=i.ImageWidth;if(null!=c&&!S.gte(c,l))throw new Error(t+": invalid width: "+c);const d=i.ImageHeight;if(null!=d&&!S.gte(d,l))throw new Error(t+": invalid height: "+d);const h=yield e.vlcPath();if(p.blank(h))throw new Error(t+" is not supported (no vlc)");if(".jpg"!==n.ext)throw new Error("only .jpg is supported");if(null==(yield n.parent().mkdirp()))throw new Error("Cannot make dest dir, "+n.dir);const f=Math.min(1,r),g=s.compact([...I,"--avcodec-hw=none","--video-filter=scene","--scene-format=jpg","--scene-replace","--scene-ratio=200",u.map(c,t=>"--scene-width="+t),u.map(d,t=>"--scene-height="+t),"--scene-path="+n.parent().nativePath,"--scene-prefix="+n.name.replace(/[^a-z]/gi,""),"--start-time=0","--stop-time="+f,t.nativePath,"vlc://quit"]);F().info("_vlcFrame",{args:g});const y=yield m.stdoutResult(h,g,{timeout:30*a.secondMs,ignoreStderr:!0});if(n.clear(),S.gt0(y.code))throw new Error("vlc failed: "+JSON.stringify(y));return!0})})(t,n,r))})},e.vlcTranscode=function(t,n,r){return i(this,void 0,void 0,function*(){return O.work("vlcTranscode()",()=>(function(t,n,r=2048){return i(this,void 0,void 0,function*(){const o=yield e.vlcPath();if(p.blank(o))throw new Error("vlc.transcode(): VLC is not installed, cannot transcode "+t);const a=yield t.size();if(!S.gt0(a))throw new Error("vlcTranscode(): cannot read "+t);const l=yield D.transcodeTimeoutForFile(t);if(!S.gt0(l))throw new Error("vlcTranscode(): no timeout");const c=yield k.readRawTags(t);if(null==c)throw new Error("Cannot transcode files that exiftool can't read");if(!d.toS(c.MIMEType).startsWith("video/"))throw new Error("Cannot transcode MIMEType "+c.MIMEType);const h=yield n.parent().mkdirp();if(null==h)throw new Error("vlc.transcode(): cannot make dest dir: "+n.parent());yield n.unlink("debug");const f=u.map(c,t=>S.mapGt0(t.ImageWidth,t=>"width="+Math.floor(t))),g=u.map(c,t=>S.mapGt0(t.ImageHeight,t=>"height="+Math.floor(t))),v=u.map(r,t=>"vb="+t),b=s.compact(["vcodec=h264",v,f,g,"venc=x264{ref=2:me=hex:mixed_ref=0:chroma_qp_offset=0:b_adapt=1:direct=1:weightp=1:rc_lookahead=20}","acodec=mp4a","ab=128","channels=2","samplerate=44100","scodec=none","deinterlace"]).join(","),M=["access=file{overwrite}","mux=mp4","dst="+n.base].join(","),x=[...I,"--no-repeat","--no-loop",t.fileuri(),`--sout=#transcode{${b}}:standard{${M}}`,"vlc://quit"];F().info("transcode()",{src:t,timeout:l,duration:c.Duration,size:a,videoBitrateKbps:v,width:f,height:g,args:x});const E=u.mapOr(c.Duration,t=>t*r*300,()=>a),_=new w.PullProgressObserver({path:t.nativePath,op:"video conversion"},E,()=>i(this,void 0,void 0,function*(){return P.orElse(yield n.clear().size(),0)}));try{const t=yield _.observe(m.stdoutResult(o,x,{cwd:h.nativePath,timeout:l,ignoreStderr:!0}));if(y.emitFileChanged(n.nativePath),0!==t.code)throw new Error("vlc failed: "+JSON.stringify(t))}catch(t){throw yield n.unlink("debug"),t}return!0})})(t,n,r))})}},function(t,e){t.exports=require("batch-cluster")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8);e.onDataChunked=function(t,e,n){new r(e,n,!0).read(t)};class r{constructor(t,e,n=!0){this.sep=t,this.onData=e,this.filterBlanks=n,this.incompleteChunk=""}onChunk(t){if(null==t)return;const e=(this.incompleteChunk+t.toString()).split(this.sep);this.incompleteChunk=e.pop(),e.forEach(t=>{this.filterBlanks&&!i.notBlank(t)||this.onData(t)})}read(t){return t.on("data",t=>this.onChunk(t)),t.on("close",()=>this.onChunk("")),this}}e.Chunker=r},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(8),o=n(18),a=n(3),u=n(10),l=n(12);function c(t){const n=e.LogLevels.indexOf(t.toLowerCase());return-1===n?e.LogLevels.length-1:n}e.LogLevels=["error","warn","info","debug","trace"],e.levelIndex=c,e.silently=function(t){try{return e.logFilter().silent=!0,t()}finally{e.logFilter().silent=!1}},e.silentlyAsync=function(t){return i(this,void 0,void 0,function*(){try{return e.logFilter().silent=!0,yield t()}finally{e.logFilter().silent=!1}})},function(t){t.highlight=()=>!1,t.enabled=()=>!t.silent,t.defaultLevelIndex=c("trace"),t.silent=!1}(e.PermissiveLogFilter||(e.PermissiveLogFilter={}));const d=/^(?:(.+?):)?(error|warn|info|debug|trace)$/i;class h{constructor(t){this.silent=!1,this.contexts=[];let e=c(l.Settings.logLevel.defaultValue);const n=u.notBlank(t)?t:l.Settings.logLevel.valueOrDefault;r.compactBlanks(n.split(",")).forEach(n=>{const i=d.exec(n.trim());if(null==i)l.isTest||console.error("EnvLogFilter: Ignoring '"+n+"' from "+t);else{const t=o.toS(i[1]).toLowerCase(),n=c(i[2]);s.blank(t)?e=n:this.contexts.push({prefix:t,levelIndex:n})}}),this.defaultLevelIndex=e}contextOverride(t){if(0===this.contexts.length&&s.blank(t))return;const e=o.toS(t).toLowerCase();return this.contexts.find(t=>e.startsWith(t.prefix))}enabled(t,e){if(this.silent)return!1;const n=c(t),i=this.contextOverride(e);return n<=(null!=i?i.levelIndex:this.defaultLevelIndex)}highlight(t){const e=this.contextOverride(t);return null!=e&&e.levelIndex>=this.defaultLevelIndex}}e.LogFilterImpl=h,e.logFilter=a.lazy(()=>new h),l.Settings.logLevel.addListener(()=>e.logFilter.clear())},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(42),r=n(4),s=n(11),o=n(14),a=n(7),u=n(190),l=n(57);o.onClearCache(()=>c.clearCaches());class c{constructor(t){if(this.ttlMs=t,this._eventCount=0,this._firstEventTime=0,this._lastEventTime=0,t<=0)throw new Error("ttlMs must be positive");this.start=Date.now(),this.eventTimes=new u.TTLArray(t),c.instances.push(this),r.retainLastN(c.instances,1e3)}static clearCaches(){this.instances.forEach(t=>t.clear())}[i.inspect.custom](){return{ctor:"Rate",epm:this.eventsPerMinute,eventCount:this._eventCount,msSinceLastEvent:this.msSinceLastEvent}}onEvent(){const t=Date.now();0===this._eventCount&&(this._firstEventTime=t),this._lastEventTime=t,this.eventTimes.push(t),this._eventCount++}clear(){this._lastEventTime=0,this._eventCount=0,this.eventTimes.clear()}get firstEventTime(){return this._firstEventTime}get lastEventTime(){return this._lastEventTime}get msSinceLastEvent(){return Date.now()-this._lastEventTime}get eventCount(){return this._eventCount}get avgMsBetweenEvent(){return 0===this.eventTimes.length?0:l.weightedAvg(l.deltas([...this.eventTimes.values,Date.now()]))}get eventsPerMs(){return this.eventTimes.length/this.ttlMs}get msPerEvent(){return a.mapGt0(this.eventTimes.length,t=>this.ttlMs/t)}get eventsPerSecond(){return a.sigFigs(this.eventsPerMs*s.secondMs,3)}get eventsPerMinute(){return a.sigFigs(this.eventsPerMs*s.minuteMs,3)}}c.instances=[],e.Rate=c},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(4),o=n(3),a=n(142),u=n(1),l=n(7),c=n(12),d=n(71),h=n(8),f=n(16),p=n(59),m=n(66),g=n(62),y=n(125),v=n(197),w=n(152);function b(){const t=r.memoryUsage();return t.external+t.heapTotal}function S(){const t=c.Settings.maxMemoryMb.valueOrDefault,e=b(),n=Math.floor(e/p.MB),i=`Memory usage for ${w.lastServiceName()} (${l.fmtBytes(e,2)}, max: ${l.fmtBytes(t*p.MB,2)})`;return n>t?(u.mkLogger("HealthChecks.memoryCheck()").warn(i),{bad:[`${i} is high`]}):{ok:[`${i} is OK`]}}e.memoryUsageBytes=b,e.memoryUsageIsHigh=function(){return c.Settings.maxMemoryMb.valueOrDefault<b()/p.MB},e.memoryCheck=S,e.syncSettingsCheck=function(){return c.isTest||c.Settings.scanMyPictures.valueOrDefault||c.Settings.scanAllDrives.valueOrDefault||!s.isEmpty(c.Settings.scanPaths.values)?{}:{warn:["Nothing to scan: scanMyPictures and scanAllDrives are false and scanPaths is empty."]}},e.healthChecks=o.lazy(()=>i(this,void 0,void 0,function*(){try{return null==y.Library.instance.prior()||c.Settings.libraryPath.hasValue()?a.concatHealthChecks(yield g.dbRpc()?function(){return i(this,void 0,void 0,function*(){const t=m.dbClient();return null!=t&&!0===(yield m.dbClientReady())?t.request("healthChecks"):{fail:["RPC client is not connected"]}})}():v.libraryHealthChecks(),S()):a.fullhc({fail:["Missing Library path"]})}catch(t){return a.fullhc({fail:[h.notBlankOr(t,"healthChecks failed")]})}}),7*f.secondMs),c.Settings.libraryPath.addListener(()=>e.healthChecks.clear()),e.runvalve=function(){return i(this,void 0,void 0,function*(){if(d.isPaused())return!1;const t=yield e.healthChecks();return null!=t&&s.isNotEmpty(t.ok)&&s.isEmpty(t.fail)&&s.isEmpty(t.warn)})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(6),o=n(2);e.True=()=>!0,e.not=function(t){return e=>!t(e)},e.and=function(...t){return e=>{for(const n of t)if(!n(e))return!1;return!0}},e.or=function(...t){return e=>{for(const n of t)if(n(e))return!0;return!1}},e.all=function(t,e){for(const n of t)if(!e(n))return!1;return!0},e.some=function(t,e){for(const n of t)if(e(n))return!0;return!1},e.none=function(t,e){for(const n of t)if(e(n))return!1;return!0},e.find=function(t,e){for(const n of t)if(e(n))return n},e.filter=function(t,e){return i(this,void 0,void 0,function*(){return null==t||null==e?s.mapOr(t,r.compact,()=>[]):o.asyncFilter(t,e)})},e.apply=function(t,e){return i(this,void 0,void 0,function*(){return null==t||null==e?t:(yield e(t))?t:void 0})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(11),s=n(162),o=n(7),a=n(2),u=n(0),l=n(31),c=n(49);e.MinSyncFileTimeoutMs=30*r.secondMs,e.MaxSyncFileTimeoutMs=15*r.minuteMs,e.DurationMultiplier=15;const d={p0:{x:7*o.MB,y:30*r.secondMs},p1:{x:18*o.MB,y:90*r.secondMs}},h={p0:{x:500*o.KB,y:20*r.secondMs},p1:{x:22*o.MB,y:60*r.secondMs}},f={p0:{x:7*o.MB,y:30*r.secondMs},p1:{x:18*o.MB,y:90*r.secondMs}};function p(t){return c.isVideoExt(t.ext)?Math.max(s.lerp2d(f.p0,f.p1,t.bytes),u.orElse(o.mapGt0(t.durationMs,t=>t*e.DurationMultiplier),0)):0}function m(t){return a.thenMap(t.size(),e=>i(this,void 0,void 0,function*(){return{bytes:e,ext:t.ext,durationMs:c.isVideoExt(t.ext)?yield a.thenMap(l.readRawTags(t),t=>o.mapGt0(t.Duration,t=>t*r.secondMs)):void 0}}))}function g(t){const n=o.clamp(100*o.KB,64*o.GB,t.bytes),i=2*r.secondMs,a=20*r.secondMs,u=n*r.secondMs/(4*o.MB),l=t=>s.lerp2d(t.p0,t.p1,n),f=l(d),m="raw"===c.extType(t.ext)?l(h):0,g=p(t);return o.clamp(e.MinSyncFileTimeoutMs,e.MaxSyncFileTimeoutMs,Math.round(i+a+u+f+m+g))}e.transcodeTimeoutForFile=function(t){return c.isVideoExt(t.ext)?a.thenMap(m(t),p):void 0},e.transcodeTimeout=p,e.syncFileTimeoutForFile=function(t){return a.thenMap(m(t),g)},e.syncFileTimeout=g},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(9),r=n(10),s=n(1),o=n(7),a=s.mkLogger("ExposureSettings");e.extractExposureSettings=function(t){const e={focalLength:t.FocalLength,iso:o.firstNonZero(t.ISO,t.ISOSpeed,t.SonyISO),aperture:o.firstNonZero(t.FNumber,t.Fnumber,t.ApertureValue,t.SonyFNumber),shutterSpeed:r.firstNotBlank(t.ExposureTime,t.ShutterSpeed,t.SonyExposureTime)};return a.debug("extracted from "+t.FileName,{exposureSettings:e}),i.reqValuedOrElse(e)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getOrSet=function(t,e,n){if(t.has(e))return t.get(e);{const i=n();return t.set(e,i),i}}},function(t,e){t.exports=require("stream")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(3),o=n(2),a=n(29),u=n(11),l=n(25),c=n(14),d=n(26),h=n(38),f=n(0),p=n(82),m=n(31),g=n(27),y=n(5),v=n(170),w=n(102),b=n(203),S=n(107),P=n(66),M=n(116),x=n(62),E=n(110),_=n(144),k=n(108),T=n(83);class O{constructor(t,e){this.before=t,this.after=e,this.id=t.valueOf()+"-"+e.valueOf()}valueOf(){return this.id}}e.AssetStream=O;e.TaggedAssetStream=class extends O{constructor(t,e,n){super(e,n),this.tags=t}addTags(t){this.tags.push(...t),r.uniqInPlace(this.tags)}toApi(){return{tags:this.tags.map(t=>t.toApiTag()),assetIdsBefore:this.before.map(t=>t.toID()),assetIdsAfter:this.after.map(t=>t.toID())}}};class D extends T.TimestampedModel{constructor(){super(...arguments),this.attrs={},this.urls=s.lazy(()=>new v.AssetUrls(this.toID()))}static findFirstByFile(t,e){return this.ops().findOne(t(this.query().select("Asset.*").join("AssetFile","AssetFile.assetId","Asset.id")),e)}static addTags(t,e){const n=y.uniqBy(e,t=>S.joinTagPath(t));this.logger().debug("addTags()",{assetId:t,tagPaths:e,uniqTagPaths:n});const i=P.dbClient();if(null!=i)return i.request("assetAddTags",{assetId:t,tagPaths:n});{const e=n.map(t=>k.Tag._findOrCreate(t)).map(t=>t.id);return _.AssetTag.addTagsToAsset(t,e)}}static removeTags(t,e){if(r.isEmpty(e))return;const n=P.dbClient();if(null!=n)return n.request("assetRemoveTags",{assetId:t,tagPaths:e});{const n=r.compact(e.map(t=>k.Tag.findByPath(t)));return this.logger().info("removeTags()",{assetId:t,tags:n.map(t=>f.pick(t,"id","path")),tagPaths:e}),_.AssetTag.removeTagsFromAsset(t,r.compact(n.map(t=>t.id)))}}static unshownAssetIds(){return this.dbr(t=>t.pluckall("\n SELECT DISTINCT af1.assetId\n FROM AssetFile af1\n LEFT JOIN (SELECT DISTINCT assetId FROM AssetFile WHERE shown = 1) AS af2 \n ON af1.assetId = af2.assetId\n WHERE af2.assetId IS NULL"))}static archive(t){const e=P.dbClient();if(null!=e)return e.request("assetArchive",{assetId:t});{const e=D.opsLocal().findById(t);if(null==e)return;return e.getFiles(),e.getTags(),c.eventEmitter.emit("modelArchive",e),_.AssetTag.opsLocal().exec(_.AssetTag.query().where({assetId:t}).delete()),E.AssetFile.opsLocal().exec(E.AssetFile.query().where({assetId:t}).delete()),void D.opsLocal().delete([t])}}updateFromFile(t){return i(this,void 0,void 0,function*(){const e=yield m.readTags(t);if(null==e)throw new Error("Missing tags for file "+t.nativePath);const n=yield this.getFiles(),i=yield o.thenCompact(n.map(t=>t.toCapturedAt())),r=yield p.bestCapturedAt([e.capturedAt,...i]),s=d.datedToMillis(r.date);if(null==s)throw new Error("No capturedAt for "+t.nativePath);return this.capturedAt=s,this.geohash=f.orElse(e.geohash,this.geohash),this})}renderCaption(t){return"Taken "+u.fmtShort(this.capturedAt,t)}whenTagPath(){return o.thenMap(b.dateTag(this.capturedAt),S.tagPathToStringArray)}addTagPaths(t){return D.addTags(this.id,t)}addAssetFile(t){return null==this.files&&(this.files=[]),this.files.push(t),t.asset=this,t.assetId=this.id,t}getTags(t){if(null!=this.tags)return this.tags;const e=k.Tag.query().select("Tag.*").join("AssetTag","AssetTag.tagId","Tag.id").where("AssetTag.assetId",this.id);return g.atap(k.Tag.ops().all(e,t),t=>this.tags=t)}tagPaths(){return i(this,void 0,void 0,function*(){return(yield this.getTags()).map(t=>t.path.join("/")).sort()})}getStreams(t){if(null==this.streams){const e=this.getTags();this.logger().info("Fetched tags "+e);const n=e.map(e=>e.getAssetStream(this,t));this.streams=function(t){const e=new Map;return t.forEach(t=>{const n=t.valueOf();e.has(n)?e.get(n).addTags(t.tags):e.set(n,t)}),[...e.values()]}(r.compact(n)),this.streams.forEach(t=>t.tags.forEach(t=>t.getAncestors()))}return this.streams}get capturedAtMs(){return d.datedToMillis(this.capturedAt)}getNextPrevId(){return g.atap(D.dbr(t=>t.all(D.query().select("id","updatedAt").where("capturedAt",this.capturedAtMs).andWhere("shown",1).andWhere("hidden",0).orderBy("id"))),t=>{const e=y.indexOf(t,t=>t.id===this.id);if(null==e)throw new l.WrappedError({message:"missing asset id",retriable:!1});return this.prevId=f.map(t[e-1],T.toID),this.nextId=f.map(t[e+1],T.toID),g.awaitAll([f.orElse(this.prevId,()=>this.getPrevId()),f.orElse(this.nextId,()=>this.getNextId())])})}getPrevId(){return g.amap(D.dbr(t=>t.first(D.query().select("id","updatedAt").where("capturedAt","<",this.capturedAtMs).andWhere("shown",1).andWhere("hidden",0).orderBy("capturedAt","desc").orderBy("createdAt","desc"))),t=>this.prevId=T.toID(t))}getNextId(){return g.amap(D.dbr(t=>t.first(D.query().select("id","updatedAt").where("capturedAt",">",d.datedToMillis(this.capturedAt)).andWhere("shown",1).andWhere("hidden",0).orderBy("capturedAt","asc").orderBy("createdAt","asc"))),t=>this.nextId=T.toID(t))}getTagPaths(t){return Promise.resolve(this.getTags(t)).then(t=>t.map(t=>t.path))}getFiles(t){return null!=this.files?this.files:g.atap(E.AssetFile.ops().findBy({assetId:this.id},t),t=>this.files=r.sortBy(t,t=>[a.truthy(t.shown),t.mtime]).reverse())}setShown(t){return i(this,void 0,void 0,function*(){x.assertDbRpc();const e=new M.DbRequestRemote;return f.map(this.files,e=>e.forEach(e=>e.shown=e.id===t)),this.shown=!0,D.dbr(t=>t.run(D.query().update({shown:1,updatedAt:Date.now()}).where({id:this.id})),e),E.AssetFile.setShown(this.id,t,e),e.submit()})}getShown(t){return null!=this.files?this.files.find(t=>a.truthy(t.shown)):g.atap(E.AssetFile.ops().findOneBy({assetId:this.id,shown:1},t),t=>f.map(t,t=>t.asset=this))}getCapturedAt(){return i(this,void 0,void 0,function*(){const t=yield this.getFiles();return o.thenCompact(r.toA(t).map(t=>t.toCapturedAt()))})}link(){return"/asset/"+this.id}sqAttrs(t=!0){return Object.assign({},this.urls().sqImgAttrs(t),{title:this.renderCaption()},this.attrs)}getImgAttrs(t,e,n=!1){return i(this,void 0,void 0,function*(){return null==this.imgAttrs&&(this.imgAttrs=new Map),yield h.getOrSetAsync(this.imgAttrs,e,()=>i(this,void 0,void 0,function*(){const r=t.ap(this.toID());yield o.thenMap(r.readInfo(),t=>i(this,void 0,void 0,function*(){t.mimetype.startsWith("video/")&&(this.poster=yield r.posterLink())}));return r.imgAttrs(e,!0,n)})),this.imgAttrs})}fitAttrs(){const t=f.map(this.imgAttrs,t=>t.get(w.ReducerNames.fit));if(null==t)throw new Error("fitAttrs() called before getImgAttrs()");return Object.assign({},t,this.attrs)}isVideo(){if(null==this.files)throw new Error(".video called before getFiles()");return this.files.some(t=>t.isVideo)}videoAttrs(){return Object.assign({controls:!0,autoplay:!0,poster:this.poster},this.attrs)}videoSources(){if(null==this.existingFiles)throw new Error(".videoSources called before getExistingFiles()");const t=this.existingFiles.filter(t=>t.isVideo).map(t=>({src:this.urls().videoLink(t.id),type:t.mimetype})),e=y.uniqBy(t,t=>t.type);if(e.every(t=>"video/mp4"!==t.type)){const t=this.existingFiles[0];e.unshift({src:this.urls().videoLink(t.id)+".mp4",type:"video/mp4"})}return e}getExistingFiles(t){return i(this,void 0,void 0,function*(){if(null!=this.existingFiles)return this.existingFiles;const e=yield this.getFiles(t);return!0===(yield f.map(e[0],t=>t.exists()))?this.existingFiles=e.slice(0,1):this.existingFiles=yield o.asyncFilter(e,t=>o.thenMapOr(t.posixFile(),t=>t.exists(),()=>!1))})}findOrCreateByFile(t){return i(this,void 0,void 0,function*(){const e=yield t.uri();if(null==e)return;const n=r.toA(yield E.AssetFile.findByAsset({id:this.id},{uri:e}))[0];return f.orElse(n,()=>i(this,void 0,void 0,function*(){const e=new E.AssetFile;return e.asset=this,e.assetId=this.id,yield e.setFile(t),e}))})}clear(){return this.files=void 0,this.tags=void 0,this.existingFiles=void 0,this}}D.tableName="Asset",D.uniqueColumnName="id",D.relations=new Map([["files",E.AssetFile],["tags",k.Tag]]),D.booleanFields=["shown","hidden","favorite"],e.Asset=D},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(65),r=n(9),s=n(26),o=n(7),a=n(19),u=/^(.+?)(?:--|\/)(.+?)(?:(?:\/)(\d+)\/(\d+))?$/;class l{constructor(t,e,n,i=0,r=1){this.start=t,this.middle=e,this.end=n,this.index=i,this.splits=r,this.toISOString=this.toString.bind(this),this.year=s.getYear(this.middle),this.month=s.getMonth(this.middle),this.day=s.getDay(this.middle)}static parse(t){t=a.toS(t).trim();const e=u.exec(t);if(null==e)return;const n=i.ExifDateTime.fromISO(e[1]),r=i.ExifDateTime.fromISO(e[2]),s=o.toInt(e[3]),l=o.toInt(e[4]);return this.for(n,r,s,l)}static for(t,e,n=0,i=1){if(!s.validDate(t)||!s.validDate(e))return;const a=s.toDateTime(t),u=s.toDateTime(e);if(null==a||null==u)return;i=o.clamp(1,1e3,o.toInt(i,{defaultValue:1})),n=o.clamp(0,i-1,o.toInt(n,{defaultValue:0}));const c=r.map(a.toDateTime().until(u.toDateTime()).divideEqually(i+1)[n],t=>t.end);return null!=c?new l(a,s.toDateTime(c,a.zone),u,n,i):void 0}interval(){return this.start.toDateTime().until(this.end.toDateTime())}toDateTime(){return this.middle.toDateTime()}toDate(){return this.toDateTime().toJSDate()}get hasTimes(){return s.hasTime(this.start)&&s.hasTime(this.end)}toString(t=!0){return`${s.datedToISO(this.start,t)}/${s.datedToISO(this.end,t)}`+(0===this.index&&1===this.splits?"":`/${this.index}/${this.splits}`)}includes(t){if(null==t)return!1;const e=s.toDateTime(t);return null!=e?this.interval().contains(e.toDateTime()):this.year===s.getYear(t)&&this.month===s.getMonth(t)&&this.day===s.getDay(t)}}e.DateInterval=l},function(t,e){t.exports=require("fs-extra")},function(t,e,n){"use strict";function i(t){return t instanceof Set?t:new Set([...t])}Object.defineProperty(e,"__esModule",{value:!0}),e.asSet=i,e.union=function(t,e){return new Set([...t,...e])},e.intersection=function(t,e){const n=i(e);return new Set([...t].filter(t=>n.has(t)))},e.diff=function(t,e){const n=i(e);return new Set([...t].filter(t=>!n.has(t)))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(95),s=n(6),o=n(33),a=n(2),u=n(130),l=n(25),c=n(0),d=n(19);e.LogLevels=o.strEnum("error","warn","info","debug","trace");const h=()=>void 0;e.NoOpLogger={enabled:()=>!1,log:h,flush:()=>Promise.resolve(),close:h,error:h,warn:h,info:h,debug:h,trace:h},e.safeLogger=function(t){return{enabled:(e,n)=>c.Try(()=>t.enabled(e,n),()=>!1),log:(e,n,i,r)=>c.Try(()=>t.log(e,n,i,r)),flush:()=>a.tryAsync(()=>t.flush()),close:()=>a.tryAsync(()=>t.close())}};const f=/^[a-z]*/i;e.MaxRecentLogEntriesByLevel=20;const p=new Map;e.clearRecentLogEntries=function(){p.clear()},e.recentLogEntries=function(){const t=[];for(const e of p.values())t.push(...e.toA());return i.sortBy(t,t=>t.timestamp)};e.ContextualLogger=class{constructor(t,e){this.context=t,this.logger=e,this.error=(t,e)=>{this.log("error",t,e)},this.warn=(t,e)=>{this.log("warn",t,e)},this.info=(t,e)=>{this.log("info",t,e)},this.debug=(t,e)=>{this.log("debug",t,e)},this.trace=(t,e)=>{this.log("trace",t,e)},this.filterContext=s.mapOr(f.exec(d.toS(this.context)),t=>t[0],()=>this.context)}throw(t,e){const n=l.asError(t);throw this.log("error",l.errorToS(n),e),n}log(t,n,i){var s;"trace"!==t&&(s={timestamp:Date.now(),level:t,context:this.context,msg:n,meta:i},r.getOrSet(p,s.level,()=>new u.BoundedList(e.MaxRecentLogEntriesByLevel)).push(s)),this.enabled(t)&&c.map(this.logger(),e=>e.log(t,this.context,n,i))}enabled(t){const e=this.logger();return null!=e&&e.enabled(t,this.filterContext)}flush(){return this.logger().flush()}close(){return c.map(this.logger(),t=>t.close())}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(33);e.ReducerNames=i.strEnum("fit","sq"),e.isReducerName=function(t){return i.enumHas(e.ReducerNames,t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(4),s=n(10),o=n(63),a=n(11),u=n(48),l=n(7),c=n(0),d=n(100),h=n(19);function f(t,e){if(null==t)return e;if(null==e)return t;if((t=t.normalize())===(e=e.normalize())||e.includes(t))return t;if(t.includes(e))return e;const n=new l.Array2D(t.length);let i=0,r="";for(let s=0;s<t.length;s++)for(let o=0;o<e.length;o++)t[s]===e[o]&&(0===s||0===o?n.set(s,o,1):n.set(s,o,n.get(s-1,o-1)+1),n.get(s,o)>=i&&(i=n.get(s,o),r=t.substr(s-i+1,i)));return r}function p(t,e){if(null!=t&&null!=e)return t=t.normalize(),e=e.normalize(),t.length!==e.length?void 0:t.split("").reduce((t,n,i)=>n===e.charAt(i)?t:t+1,0)}e.commonSubstringRatio=function(t,e){return[t,e].some(s.blank)?0:f(t,e).length/Math.max(t.length,e.length)},e.lcs=f,e.hamming=p;const m=new o.BoundedMap(10*a.minuteMs,1e4,!0),g=String.fromCharCode(31);function y(t,e){return t=t.normalize(),e=e.normalize(),m.getOrSet(r.sort([t,e]).join(g),()=>{if(0===t.length)return e.length;if(0===e.length)return t.length;const n=t.charAt(t.length-1)===e.charAt(e.length-1)?0:1,i=t.slice(0,-1),r=e.slice(0,-1);return Math.min(y(i,e)+1,y(t,r)+1,y(i,r)+n)})}function v(t,e){const n=t.toUpperCase().normalize(),i=e.toUpperCase().normalize();return c.firstThunk(()=>n===i?1:void 0,()=>s.blank(t)!==s.blank(e)?0:void 0,()=>1===t.length&&1===e.length?0:void 0,()=>{const t=w(n),e=w(i);return 2*b(t,e).length/(t.length+e.length)})}function w(t){return null==t||0===t.length?[]:t.slice(0,-1).split("").map((e,n)=>e+t[n+1])}function b(t,e){const n=d.intersection(t,e),i=[];return n.forEach(n=>{const s=Math.min(r.count(t,t=>t===n),r.count(e,t=>t===n));l.times(s,()=>i.push(n))}),i}function S(t,e,n){const r=i.commonPrefixLength(t,e);return n(t.substr(r))-n(e.substr(r))}function P(t){const e=s.compactBlanks(h.toS(t).split(/[^\d]+/));return r.sortBy(e,t=>-t.length)[0]}function M(t,e){const[n,i]=[t,e].map(P).map(t=>s.blank(t)?"":t);return S(n,i,t=>l.toInt(t,{defaultValue:0}))}e.levenshtein=y,e.diceCoeff=v,e.bigrams=w,e.nonUniqIntersection=b,e.lnsDiff=M;const x=/[^0-9a-z]+/gi;function E(t,e){const[n,i]=[t,e].map(t=>h.toS(t).replace(x,"").toLowerCase());return S(n,i,t=>u.RadixAlphaNum.decode(t))}e.radixDiff=E,e.str=function(t,e){return{pref:i.commonPrefixLength(t,e),lev:y(t,e),ham:p(t,e),dice:v(t,e),lns:M(t,e),radixDiff:E(t,e)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(35),r=n(157),s=n(9),o=n(105),a=n(2),u=n(7),l=750;e.PushProgressObserver=class{constructor(t,e){this.context=t,this.total=e,this.start=Date.now(),this.emit=o.throttle(()=>{r.emitProgressEvt(Object.assign({},this.context,{pct:u.sigFigs(100*this.current/this.total,3),elapsedMs:Date.now()-this.start}))},l,!0)}onProgress(t){this.current=u.clamp(0,this.total,t),this.emit()}};e.PullProgressObserver=class{constructor(t,e,n){this.ctx=t,this.total=e,this.progress=n,this.start=Date.now(),this.onInterval=o.throttle(()=>a.thenMap(this.progress(),t=>this.emit(t)),l),this.timer=i.setInterval(()=>this.onInterval(),l)}observe(t){return t.then(()=>this.completed()).catch(()=>this.end()),t}emit(t){s.map(t,t=>r.emitProgressEvt(Object.assign({},this.ctx,{pct:100*u.clamp(0,this.total,t)/this.total,elapsedMs:Date.now()-this.start})))}completed(){Date.now()-this.start>l&&this.emit(this.total),this.end()}end(){s.map(this.timer,t=>i.clearInterval(t)),this.timer=void 0}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.throttle=function(t,e,n=!1){let i=n?Date.now()+e:0,r=0;const s=()=>{const n=Date.now();return n>=i?(i=n+e,r++,t()):void 0};return s.count=()=>r,s}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(43),r=n(30),s=n(22),o=n(3),a=n(0);function u(t){const e=[];for(;t!==r.dirname(t);)t=r.dirname(t),e.push(t);return e}function l(t){try{return i.readdirSync(t)}catch(t){return[]}}function c(t,e){const n=l(t);return e.every(t=>n.includes(t))}function d(t,e){return u(t).find(t=>c(t,e))}e.execDir=o.lazy(()=>r.dirname(process.execPath)),e.ancestors=u,e.childrenSync=l,e.hasChildren=c,e.ancestorWithChildren=d,function(t){function n(e){return o.lazy(()=>r.join(t.Root(),e))}t.Root=o.lazy(()=>{const t=["migrations","public","tools","views"];return a.firstThunk(()=>[r.join(e.execDir(),"resources"),r.join(e.execDir(),"..","Resources"),e.execDir(),process.cwd()].find(e=>c(e,t)),()=>d(s.cwd(),t),()=>{throw new Error("Failed to find project root.")})}),t.Migrations=n("migrations"),t.Public=n("public"),t.Tools=n("tools"),t.Views=n("views")}(e.ProjectPath||(e.ProjectPath={}))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(0),r=n(100),s=n(5),o=n(6),a=n(18);function u(t){return o.map(t,t=>i.orElse(t.name,a.toS(t)))}function l(t){return t.map(u)}function c(t){return l(t).join(e.sep).toLowerCase()}function d(t,e){const n=new Set(s.compact(e).map(t=>c(t)));return s.compact(t).filter(t=>!n.has(c(t)))}function h(t){return u(s.toA(t)[0])}function f(t){return new Set(s.compact(s.toA(t).map(h)))}e.sep=String.fromCharCode(31),e.When="When",e.Camera="Camera",e.Keywords="Keywords",e.Roots=[{name:e.When,ordinal:1},{name:e.Camera,ordinal:5},{name:e.Keywords,ordinal:7}],e.tagRefToS=u,e.tagPathToStringArray=l,e.joinTagPath=function(t,n=e.sep){return l(t).join(n)},e.tagPathEql=function(t,e){return null!=t&&null!=e&&c(t)===c(e)},e.tagDiff=d,e.tagDeltas=function(t,e,n=!0){const i=d(e,t),s=d(t,e),o=n?r.diff(f(s),f(i)):new Set;return{add:i,remove:s.filter(t=>!o.has(h(t)))}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(3),o=n(10),a=n(11),u=n(14),l=n(26),c=n(250),d=n(7),h=n(0),f=n(27),p=n(17),m=n(15),g=n(276),y=n(44),v=n(107),w=n(66),b=n(62),S=n(97),P=n(144),M=n(83);const x=b.dbRpc()?3*a.minuteMs:30*a.secondMs;function E(t){return _.cacheTag(t),t}u.onClearCache(()=>_.clear()),e.DefaultRelatedAssetLimit=24;class _ extends M.TimestampedModel{constructor(){super(...arguments),this.urls=s.lazy(()=>new g.TagUrls(this.id))}static clear(){this.root.clear(),this.roots.clear(),this._upsertDefaultRoots.clear(),this.recentTagsByPath.clear(),this.tagById.clear(),this._assetCountById.clear()}static onAssetTagChange(){this._assetCountById.clear()}static cacheTag(t){return i(this,void 0,void 0,function*(){const e=yield t;null!=e&&(Array.isArray(e)?e.forEach(t=>this.cacheTag(t)):e instanceof _&&null!=e.id&&o.notBlank(e._path)&&(this.recentTagsByPath.set(e._path,e),h.map(e.id,t=>this.tagById.set(t,e))))})}static newTag(t){const e=new _;e._path=v.joinTagPath(t);const n=t[t.length-1];return h.map(n.ordinal,t=>e.ordinal=t),e}static findByIdOrPath(t,e,n){return d.gt0(t)?this.findById(t,n):this.findByPath(e,n)}static findById(t,e){return 0===t?_.root():h.orElse(_.tagById.get(t),()=>E(this.ops().findById(t,e)))}static findByPath(t,e){if(r.isEmpty(t))return _.root();{const n=v.joinTagPath(t);return h.orElse(_.recentTagsByPath.get(n),()=>E(this.ops().findOneBy({_path:n},e)))}}static getPagedAssets(t,e){const n=new _;return n.id=t,n.getPagedAssets(e)}static findOrCreate(t){const e=w.dbClient();return null!=e?e.request("tagFindOrCreate",t).then(t=>_.fromJSON(t)):this._findOrCreate(t)}static _findOrCreate(t){if(b.assertLocalDb(),r.isEmpty(t))throw new Error("empty tagPath");const e=v.joinTagPath(t,"/"),n=this.findByPath(t);if(this.logger().debug("_findOrCreate("+e+")",{prior:n}),null!=n)return n;const i=this.newTag(t),s=i.isRoot?void 0:this._findOrCreate(t.slice(0,-1));h.map(s,t=>i.parentId=t.id);const o=E(this.opsLocal().upsertOne(i));return this.logger().debug("_findOrCreate("+e+") upserted",{newTag:i,result:o,parent:s}),o}set name(t){const e=null!=this.parent?this.parent.path:[];this._path=r.concat(e,[t]).join(v.sep)}get name(){const t=this.path;return t[t.length-1]}get path(){return h.orElse(o.mapNotBlank(this._path,t=>t.split(v.sep)),[])}get isRoot(){return-1===this._path.indexOf(v.sep)}get parentPath(){return this.path.slice(0,-1)}$childrenQuery(){return _.query().where({parentId:this.id}).orderByRaw("COALESCE(ordinal, _path)")}$assetsQuery(){return S.Asset.query().columns("Asset.*").join("AssetTag","AssetTag.assetId","Asset.id").where({tagId:this.id}).andWhere("Asset.shown",1).andWhere("Asset.hidden",0)}setAncestors(t){this.ancestors=t,this.parent=t[t.length-1],h.map(this.parent,e=>e.setAncestors(t.slice(0,-1)))}toApiTag(){return b.assertLocalDb(),{tagId:this.id,tagPath:this.path,assetCount:this.getAssetCount()}}toStringId(){return"Tag("+this.path.join("/")+")"}getParent(t){if(!this.isRoot)return null!=this.parentId&&null==this.parent?f.atap(_.findById(this.parentId,t),t=>this.parent=t):this.parent}getRoot(t){return this.isRoot?this:null!=this.root?this.root:f.atap(_.findByPath(this.path.slice(0,1),t),t=>this.root=t)}getPagedChildren(t,e){if(0===this.id)return this.children;let n=this.$childrenQuery();return d.mapGt0(t.offset,t=>n=n.offset(t)),d.mapGt0(t.limit,t=>n=n.limit(t)),_.ops().all(n,e)}getChildren(t){return f.atap(_.ops().all(this.$childrenQuery(),t),t=>{this.children=t,t.forEach(t=>{t.parent=this})})}link(){return"/tag/"+this.path.join("/")}get rootName(){return this.path[0]}get ancestorsAndSelf(){return[...this.ancestors,this]}getAncestors(t){const e=r.ancestry(this.parentPath).map(t=>v.joinTagPath(t)),n=e.map(t=>_.recentTagsByPath.get(t));if(n.every(t=>null!=t))return this.ancestors=n;const i=_.query().whereIn("_path",e).orderBy("_path");return f.atap(_.ops().all(i,t),t=>{E(t),this.ancestors=t,this.parent=h.orElse(this.parent,t[t.length-1])})}getPagedAssets(t,e){let n=this.$assetsQuery(),i="desc";return d.mapGte0(t.capturedAtLt,t=>{n=n.where("capturedAt","<",t)}),d.mapGte0(t.capturedAtGt,t=>{n=n.where("capturedAt",">",t),i="asc"}),d.mapGte0(t.limit,t=>n=n.limit(t)),n=n.orderBy("capturedAt",i),S.Asset.ops().all(n,e)}getAssets(t){const e=this.$assetsQuery().orderBy("capturedAt","desc");return S.Asset.ops().all(e,t)}assetCountDesc(t){const e=this.getAssetCount();return(null==t||t.length===e||0===t.length?"":d.fmt(t.length)+" of ")+d.plur(e,"asset")}getDirectAssetCount(){return this._getAssetCountWithQuery(t=>t.where({tagId:this.id}))}getAssetCount(){const t=()=>this._getAssetCountWithQuery(t=>t.join("Tag as t","t.id","AssetTag.tagId").where("t._path","like",this._path+"%"));return b.dbRpc()?t():_._assetCountById.getOrSet(this.id,t)}_getAssetCountWithQuery(t){if(null==this.id)return 0;const e=P.AssetTag.query().countDistinct("AssetTag.assetId");return o.notBlank(this._path)&&t(e),P.AssetTag.ops().count(e)}$assetStreamQuery(t,e,n){return this.$assetsQuery().orderBy("capturedAt",n?"desc":"asc").where("capturedAt",n?"<":">",l.datedToMillis(t.capturedAt)).limit(e)}getAssetStream(t,e){e=d.gt0(e)?e:8;const n=S.Asset.opsLocal().all(this.$assetStreamQuery(t,e,!0)).reverse(),i=S.Asset.opsLocal().all(this.$assetStreamQuery(t,e,!1));return new S.TaggedAssetStream([this],n,i)}getRelatedAssetIds(t,n=e.DefaultRelatedAssetLimit){const i=P.AssetTag.query().distinct("Asset.id","Asset.capturedAt","Asset.updatedAt").join("Asset","Asset.id","AssetTag.assetId").join("Tag","Tag.id","AssetTag.tagId").where("_path","like",this._path+"%").andWhere("Asset.shown",1).orderByRaw(c.prngOrderByClause(t+h.orElse(this.id,0),"Asset.id",h.orElse(k(),Math.pow(2,20)))).limit(n),s=S.Asset.opsLocal().all(i);return r.sortByInPlace(s,t=>m.Opt(t.capturedAt).map(t=>-t).getOrElse(()=>0)),this.logger().debug(this.path+": Found "+s.length+" related assets"),s.map(t=>t.toID())}get attrs(){return{href:this.link(),title:this.name}}}_.tableName="Tag",_.uniqueColumnName="_path",_.relations=new Map([["parent",_],["ancestors",_],["children",_],["assets",S.Asset]]),_.recentTagsByPath=new y.TTLMap(x),_.tagById=new y.TTLMap(x),_._assetCountById=new y.TTLMap(30*a.secondMs),_.root=s.lazy(()=>{const t=new _;return t.id=0,t.name="",t._path="",t.parentId=void 0,f.atap(_.roots(),e=>t.children=e),t.ancestors=[],t.upsert=()=>{throw new Error("upsert not supported")},t},x),_._upsertDefaultRoots=s.lazy(()=>_.ops().upsert(v.Roots.map(t=>({_path:t.name,ordinal:t.ordinal})))),_.roots=s.lazy(()=>{const t=w.dbClient();if(null!=t)return t.request("tagRoots").then(t=>t.map(t=>_.fromJSON(t)));{_._upsertDefaultRoots();const t=_.query().whereNull("parentId").orderByRaw("coalesce(ordinal, _path)");return f.atap(_.ops().all(t),t=>{_.logger().info("roots()",t),t.forEach(t=>{t.parentId=void 0,t.ancestors=[],E(t)})})}}),e.Tag=_;const k=s.lazy(()=>p.base10Ceil(S.Asset.dbLocal().pluckfirst(S.Asset.query().count("id"))),a.minuteMs)},function(t,e){t.exports=require("url")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(109),s=n(3),o=n(2),a=n(10),u=n(29),l=n(32),c=n(26),d=n(56),h=n(7),f=n(0),p=n(151),m=n(12),g=n(13),y=n(82),v=n(31),w=n(115),b=n(27),S=n(19),P=n(6),M=n(143),x=n(97),E=n(83);class _ extends E.TimestampedModel{constructor(){super(...arguments),this.posixFile=s.lazy(()=>l.PosixFile.forUri(this.uri,this.mountpoint)),this.nativePath=()=>o.thenMap(this.posixFile(),t=>t.nativePath)}static recentAssetIdsByUriRoot(t,e,n=64){const i=Date.now()-e,r=this.query().distinct("AssetFile.assetId").join("Asset","Asset.id","AssetFile.assetId").where("AssetFile.updatedAt",">",i).andWhere("AssetFile.uri","like",t+"%").andWhere("Asset.shown",1).andWhere("Asset.hidden",0);return r.orderBy("AssetFile.updatedAt","desc").limit(n),this.logger().info("recentAssetIdsByUriRoot",r.toSQL()),this.dbLocal().pluckall(r)}static assetCountByMimetype(t){const e=this.query().select(M.knex.raw("mimetype, count(*) as count"));return a.notBlank(t)&&e.andWhere("uri","like",t+"%"),e.groupBy("mimetype").orderBy("mimetype"),this.dbr(t=>t.all(e))}static children(t,e){const n=this.query().where("uri","like",t+"/%").andWhere("uri","regexp",`^${g.escapeRegExp(t)}/[^/]+$}`);return this.ops().all(f.mapOr(e,t=>t(n),n))}static setShown(t,e,n){if(this.logger().info("setShown()",{assetId:t,assetFileId:e}),!h.gt0(t)||!h.gt0(e))throw new Error("setShown(): invalid IDs: "+JSON.stringify({assetId:t,assetFileId:e}));this.dbr(e=>e.run(_.query().update("shown",0).where("assetId",t)),n);const i=["UPDATE AssetFile","SET shown = CASE id WHEN $assetFileId THEN 1 ELSE 0 END,","updatedAt = $updatedAt","WHERE assetId = $assetId"].join(" "),r={assetId:t,assetFileId:e,updatedAt:Date.now()};return this.dbr(t=>t.run({sql:i,bindings:r}),n)}static findByAsset(t,e,n){const i=this.query().select("AssetFile.*");return f.map(f.compactValues(t),t=>{i.join("Asset","Asset.id","AssetFile.assetId").where(f.mapFields(t,(t,e)=>["Asset."+t,e]))}),f.map(f.compactValues(e),t=>{i.where(f.mapFields(t,(t,e)=>["AssetFile."+t,e]))}),this.ops().all(i,n)}matchesFile(t){return i(this,void 0,void 0,function*(){return!m.Settings.forceSync.valueOrDefault&&null!=t&&null!=this.fileSize&&null!=this.mtime&&this.uri===(yield t.uri())&&this.fileSize===(yield t.size())&&this.mtime===(yield t.thisOrSidecareMaxMtimeMs())})}updateFromFile(t){return i(this,void 0,void 0,function*(){if(this.logger().debug("updateFromFile() before",this),null!=this.id&&(yield this.matchesFile(t))&&h.gt(p.LastExifVersionUpdatedAtMs,this.updatedAt))return void this.logger().info("updateFromFile() no-op, file times match and exifUID wasn't updated since last update",this);null!=t&&(yield this.setFile(t)),null==t&&(t=yield this.posixFile());const e=yield f.map(t,t=>t.stat());if(null==t||null==e||0===e.size)return void this.logger().warn("Cannot update",{file:t,stat:e,uri:this.uri});this.fileSize=e.size,this.mtime=P.orElse(yield t.thisOrSidecareMaxMtimeMs(),()=>e.mtimeMs);const n=yield v.readTags(t);if(null==n)throw new Error("missing tags for "+t.nativePath);if(a.blank(n.MIMEType))throw new Error("missing MIMEType for "+t.nativePath);this.mimetype=n.MIMEType;const i=n.dimensions;this.width=i.width,this.height=i.height,this.rotation=n.rotation,this.exifUid=n.exifUid,f.map(n.exposureSettings,t=>{this.focalLength=t.focalLength,this.aperture=t.aperture,this.shutterSpeed=t.shutterSpeed,this.iso=t.iso});const r=n.capturedAt;return this.capturedAtISO=c.datedToISO(r.date),this.capturedAtSrc=r.src,yield o.thenMap(t.sha(),t=>this.sha=t),this.logger().debug("updateFromFile() after",this),this})}getAsset(t){return null==this.assetId||null!=this.asset?this.asset:b.atap(x.Asset.ops().findById(this.assetId,t),t=>this.asset=t)}exists(){return i(this,void 0,void 0,function*(){return o.thenMapOr(this.posixFile(),t=>t.exists(),()=>!1)})}setFile(t){return i(this,void 0,void 0,function*(){const e=yield t.uriObject();if(null==e)throw this.logger().error("setFile(): cannot determine voluri",t),new Error("no URI for "+t);const n=r.format(e);if(null==n)throw new Error(t+" had no URI");if(null!=this.uri&&n!==this.uri)throw new Error("Cannot reassign URIs");return this.uri=n,this.mountpoint=f.map(e.volume,t=>t.mountpoint),this.posixFile.set(Promise.resolve(t)),n})}toCapturedAt(){return f.map(c.parseDated(this.capturedAtISO),t=>o.thenMap(this.posixFile(),e=>new y.CapturedAt(e,t,this.capturedAtSrc,new Date(this.mtime))))}toApi(){return i(this,void 0,void 0,function*(){return o.thenMap(this.posixFile(),t=>i(this,void 0,void 0,function*(){return f.reqValuedOrElse({assetId:this.assetId,assetFileId:this.id,nativePath:t.nativePath,wbrNativePath:g.wbrPath(t.nativePath),basename:t.base,exists:yield t.isNonEmpty(),mimetype:this.mimetype,shown:u.truthy(this.shown),width:this.width,height:this.height,rotation:this.rotation,fileSize:this.fileSize,mtime:this.mtime,createdAt:this.createdAt,updatedAt:this.updatedAt})}))})}get isVideo(){return S.toS(this.mimetype).startsWith("video/")}setRotation(t,e){return i(this,void 0,void 0,function*(){const n=yield this.posixFile();null==n&&this.logger().throw("setRotation(): Cannot rotate: file is missing");const i=yield f.map(w.rotationToWriteTag(t,this.mimetype),t=>v.writeTags(n,t));null==i&&this.logger().throw("setRotation(): writeTags was null");const r=yield this.getAsset();null==r&&this.logger().throw("setRotation(): asset was null");const s=[this,r];if(null==(yield this.updateFromFile(n))&&this.logger().throw("setRotation(): updateFromFile returned null"),null!=i.original&&!i.original.isSidecar()){const t=yield r.findOrCreateByFile(i.original);null==t?this.logger().throw("setRotation(): findOrCreateByFile returned null",i):s.push(t)}const o=e.ap(this.assetId);return yield o.setRotation(t),e.clearAssetId(this.assetId),d.maybeFlipInPlace(this,P.orElse(this.rotation,0)-t),this.rotation=t,s})}}_.tableName="AssetFile",_.uniqueColumnName="uri",_.booleanFields=["shown"],_.relations=new Map([["asset",x.Asset]]),e.AssetFile=_},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(6),o=n(15),a=n(3),u=n(77),l=n(2),c=n(20),d=n(34),h=n(1),f=n(23),p=n(13),m=n(112),g=n(24);e.isGioSupported=a.lazy(()=>i(this,void 0,void 0,function*(){if(!f.isLinux)return!1;try{return 0===(yield c.stdoutResult(e.GioCommand,["version"],{timeout:g.cmdTimeoutMs,ignoreStderr:!0})).code}catch(t){return!1}})),e.GioCommand="gio",e.GioMountMonitorArgs=["mount","--monitor","--anonymous"];const y=h.mkLogger("Gio.gioVolumes()");e.gioVolumes=a.lazy(()=>i(this,void 0,void 0,function*(){const t=yield function(){return i(this,void 0,void 0,function*(){return(yield e.isGioSupported())?l.thenFlatten(yield l.thenMap(e.mtabEntries(),t=>t.map(t=>d.BaseFile.for(t).clear().childDirectories()))):[]})}(),n=(yield l.thenFlatten(t.map(t=>i(this,void 0,void 0,function*(){const e=yield m.dfPosixRaw(!1,t.nativePath).catch(e=>{y.warn("Failed to df "+t+": "+e)}),n=s.map(e,t=>t[0]);return s.map(n,e=>e.mountpoint=t.nativePath),n})))).filter(t=>t.size>0);return Promise.all(n.map(t=>i(this,void 0,void 0,function*(){return l.thenMapOr(w(t.mountpoint),e=>(t.remoteHost=e.remoteHost,t.remoteShare=e.remoteShare,t.label=e.displayName,t.remote=!0,t),()=>t)})))}),g.dfTtlMs);const v=h.mkLogger("Gio.getRemoteInfo()"),w=u.memoize(t=>i(this,void 0,void 0,function*(){try{const n=(yield c.stdout(e.GioCommand,["info",t],{timeout:g.cmdTimeoutMs})).split(/[\n\r]+/),i=r.mapNotBlank(n.find(t=>t.startsWith("uri: ")),t=>new URL(p.stripPrefix(t,"uri: ")));return{displayName:s.map(n.find(t=>t.startsWith("display name: ")),t=>p.stripPrefix(t,"display name: ")),remoteHost:s.map(i,t=>t.hostname),remoteShare:o.Opt(i).flatMap(t=>t.pathname).flatMap(t=>p.stripPrefix(t,"/")).flatMap(t=>p.stripSuffix(t,"/")).flatMap(decodeURIComponent).filter(r.notBlank).get()}}catch(e){return void v.warn("gio info failed",{mountpoint:t,err:e})}}),g.dfTtlMs,1e3);e.mtabEntries=a.lazy(()=>i(this,void 0,void 0,function*(){return l.thenMap(d.BaseFile.for("/proc/mounts").readLines(),t=>t.filter(t=>t.startsWith("gvfsd-fuse ")).map(t=>t.split(" ")[1]))}),g.dfTtlMs)},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(18),o=n(20),a=n(68),u=n(7),l=n(23),c=n(210),d=n(24);function h(t){return 1024*u.toInt(t,{defaultValue:0})}const f=l.isMac?["devfs"]:["udev","tmpfs"],p=["/boot/efi"];e.dfPosixRaw=function(t,e){return i(this,void 0,void 0,function*(){const n=l.isMac?yield c.ignorableMacFilesystems():[],i=["-k","-P"];t&&i.push("-l"),r.notBlank(e)&&i.push(e);const u=yield o.stdout("df",i,{timeout:d.cmdTimeoutMs});return a.parseFixed(["Filesystem","1024-blocks","Used","Available","Capacity","Mounted on"],u).map(t=>({filesystem:t.Filesystem,size:h(t["1024-blocks"]),used:h(t.Used),available:h(t.Available),mountpoint:t["Mounted on"]})).filter(t=>{const e=s.toS(t.filesystem),i=s.toS(t.mountpoint);return r.notBlank(i)&&!p.includes(i)&&r.notBlank(e)&&!n.includes(e)&&!f.includes(e)})})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(72),o=n(0),a=n(13),u=n(92),l=n(2);class c{constructor(t){this.apply=t}static lift(t){return new c(t)}static and(...t){return new c(e=>i(this,void 0,void 0,function*(){for(const n of t){const t=yield n.apply(e);if(!t)return t}return!0}))}static or(...t){return new c(e=>i(this,void 0,void 0,function*(){for(const n of t){const t=yield n.apply(e);if(t)return t}return!1}))}static andLogged(t,...e){return this.and(...r.flatMap(e,e=>o.entries(e).map(([e,n])=>n.asAsync().logged(t,e))))}static orLogged(t,...e){return this.or(...r.flatMap(e,e=>o.entries(e).map(([e,n])=>n.asAsync().logged(t,e))))}static andExplain(t,e){return i(this,void 0,void 0,function*(){const n=[],i=[];for(const r of e)for(const[e,s]of o.entries(r))((yield s.apply(t))?n:i).push(e);return{accepted:n,rejected:i}})}asAsync(){return this}and(...t){return c.and(this,...t)}not(){return c.lift(t=>this.apply(t).then(t=>!t))}or(t){return new c(e=>i(this,void 0,void 0,function*(){return(yield this.apply(e))||(yield t.apply(e))}))}filter(t){return i(this,void 0,void 0,function*(){return u.filter(t,t=>this.apply(t))})}logged(t,e){return new c(n=>l.thenTap(this.apply(n),i=>{t.log(i?"debug":"info",[s.grey(e),i?s.green("ACCEPT"):s.red("REJECT"),a.ellipsize(n)].join(" "))}))}}e.AsyncFilter=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(230),r=n(48),s=n(7),o=n(0);function a(t,e){return s.within(-90,90,t)&&s.within(-180,180,e)&&0!==t&&0!==e}function u(t,e,n=50){return a(t,e)?i.bitZip({dims:[{min:-180,value:e,max:180},{min:-90,value:t,max:90}],bitDepth:n}):void 0}function l(t,e=52){return o.map(i.bitUnzip(t,{dims:[{min:-180,max:180},{min:-90,max:90}],bitDepth:e}),t=>t.reverse())}e.validLatLon=a,e.geohash=function(t,e,n=52){return o.map(u(t,e,n),t=>r.GeoRadix.encode(t))},e.geohash_num=u,e.ungeohash=function(t,e=52){return o.map(r.GeoRadix.decode(t),t=>l(t,e))},e.ungeohash_num=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(17),r=n(123),s=n(56),o=n(0);e.extractRotation=function(t){return o.firstThunk(()=>u(t.Orientation),()=>u(t.CameraOrientation),()=>i.toInt(t.Rotation))};const a=new Map([["Horizontal (normal)",0],["Rotate 90 CW",90],["Rotate 180",180],["Rotate 270 CW",270],[1,0],[6,90],[3,180],[8,270]]);function u(t){return o.map(t,t=>a.get(t))}e.orientationToRotation=u;const l=new Map([[0,1],[90,6],[180,3],[270,8]]);function c(t){return o.map(t,t=>l.get(t))}e.rotationToExifOrientation=c,e.extractSizeInfo=function(t,e){if(!i.gte0(t.ImageHeight)||!i.gte0(t.ImageWidth))return;const n=s.maybeFlip({width:t.ImageWidth,height:t.ImageHeight},e),r=i.sigFigs(n.width/n.height,5);return{ImageHeight:n.height,ImageWidth:n.width,aspectRatio:r,dimensions:n,fileDimensions:{width:t.ImageWidth,height:t.ImageHeight}}},e.isRotation=function(t){return i.isNumber(t)&&[0,90,180,270].includes(t)},e.rotationToWriteTag=function(t,e){return o.map(r.normalizeRotation(t),t=>e.startsWith("video/")?{Rotation:t}:o.map(c(t),t=>({"Orientation#":t})))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(36),s=n(1),o=n(0),a=n(27),u=n(66),l=n(117);e.dbr=function(t,e){return i(this,void 0,void 0,function*(){const n=o.orElse(e,new d),i=t(n);return null==e&&(yield n.submit()),i})};const c=s.mkLogger("DbRequestRemote");class d{constructor(t=u.dbClient()){this.client=t,this.d=[],this.ops=[]}op(t,e){return this.ops.push(Object.assign({},l.toSqlQuery(e),{method:t})),a.tap(new r.Deferred("DbRequestRemote."+t),t=>this.d.push(t)).promise}exec(t){return this.op("exec",t)}run(t){return this.op("run",t)}first(t){return this.op("first",t)}all(t){return this.op("all",t)}pluckfirst(t){return this.op("pluckfirst",t)}pluckall(t){return this.op("pluckall",t)}submit(){return this.client.request("batch",this.ops).then(t=>{c.debug("submit(): got response",{arr:t}),t.forEach((t,e)=>{const n=this.d[e],i=this.ops[e];c.debug("submit(): got response",{ea:t,sql:i}),n.resolve(t)})})}}e.DbRequestRemote=d},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(0),r=n(13),s=n(41),o=n(194);function a(t){return null!=t&&r.isString(t.sql)&&(null==t.bindings||o.isDbValued(t.bindings))}e.isSqlQuery=a,e.toSqlQuery=function(t){if(null==t)throw new Error("null sql");if(a(t))return t;if(r.isString(t))return{sql:t};if(s.isFunction(t.toSQL))return i.without(t.toSQL(),"__knexQueryUid");throw new Error("not queryish: "+JSON.stringify(t))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(2),s=n(1),o=n(38),a=n(204),u=n(16),l=n(85);class c{constructor(t){this.db=t,this.recentTx=new a.TTLSet(30*u.secondMs),this.logger=s.mkLogger("Transactions("+t.name+")")}static for(t){return o.getOrSet(c.instances,t.name,()=>new c(t))}tx(t,e){return i(this,void 0,void 0,function*(){try{if(this.recentTx.add(t),this.db.inTransaction&&(this.logger.warn("ALREADY IN TRANSACTION, I'll wait...",{ctx:t,recent:this.recentTx.toA()}),yield r.until(()=>!this.db.inTransaction,15e3,l.randomInt(20,100))),this.db.inTransaction)throw new Error("UNEXPECTEDLY IN A TRANSACTION YIKES");return this.db.transaction(()=>e())()}catch(e){throw this.logger.error("tx("+t+") error: "+e),e}})}}c.instances=new Map,e.Transactions=c,e.tx=function(t,e,n){return c.for(t).tx(e,n)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(3),s=n(1),o=n(38),a=n(7),u=n(0),l=n(16),c=n(9),d=n(44),h=n(156),f=n(194),p=n(117),m=n(271);e.MaxBatchSize=99;class g{constructor(t){this.model=t,this.dbr=r.lazy(()=>new h.DbRequestLocal(this.model.db)),this.columnNames=r.lazy(()=>this.db.pragma(`table_info(${this.tableName})`).map(t=>t.name)),this.stmts=new d.TTLMap(30*l.secondMs),this.logger=s.mkLogger("ModelOpsLocal("+t.$ctor+")")}static forTableName(t){return this.instances.get(t)}static forModel(t){const e=t;return o.getOrSet(this.instances,e.tableName,()=>new g(e))}get db(){return this.model.db}get dbOpen(){return null!=this.model.db&&this.model.db.open}get tableName(){return this.model.tableName}toDbValued(t){const e=this.model.fromJSON(t),n=f.toDbValued(e);return c.pick(n,...this.columnNames())}exec(t,e){return this.dbr().exec(t)}run(t){return this.dbr().run(t)}first(t,e){return u.map(this.dbr().first(t),t=>this.model.fromJSON(t))}all(t,e){return this.dbr().all(t).map(t=>this.model.fromJSON(t))}findOne(t,e){return u.map(this.dbr().first(t.first()),t=>this.model.fromJSON(t))}findOneBy(t,e){return this.findOne(this.model.query().where(t))}findById(t,e){return this.findOneBy({id:t})}findByIds(t,n){const r=i.toA(t),s=i.flatten(i.batches(r,e.MaxBatchSize).map(t=>this.all(this.model.query().where("id","in",i.toA(t)))));return i.sortBy(s,t=>r.indexOf(t.id))}findBy(t,e){return this.all(this.model.queryBy(t))}rows(){return this.count(this.model.query())}count(t,e){return u.orElse(this.dbr().pluckfirst(t),0)}insert(t){const e=this.model.fromJSON(t);if(null!=e.id)throw new Error("insert called for "+JSON.stringify(t));e.$beforeUpsert();const n=e.$toDbJSON(this.columnNames()),i=this.run(this.model.query().insert(n));return this.findById(i.lastInsertRowid)}upsertOne(t,e){return this.upsert([t])[0]}get ucn(){return this.model.uniqueColumnName}upsert(t,n){if(t.length>e.MaxBatchSize)return i.flatten(i.batches(t,e.MaxBatchSize).map(t=>this.upsert(t)));const r=(Array.isArray(t)?t:[t]).map(t=>this.model.fromJSON(t)),s=r.map(t=>t[this.ucn]);r.forEach(t=>t.$beforeUpsert());const o=this.columnNames(),a=r.map(t=>t.$toDbJSON(o)).map(t=>{const e=p.toSqlQuery(m.mkUpsertSql(this.tableName,this.ucn,t));try{return this.stmts.getOrSet(e.sql,()=>this.db.prepare(e.sql)).run(e.bindings)}catch(t){throw this.logger.warn("upsert(): bad SQL",{tableName:this.tableName,sq:e}),t}}),l=s.map((t,e)=>u.orElse(t,a[e].lastInsertRowid)),c=this.all(this.model.query().whereIn(this.ucn,l)),d=i.sortBy(c,t=>s.indexOf(t[this.ucn]));return this.logger.debug("upsert()",{result:d}),d}delete(t,e){return i.mapNotEmpty(t.filter(a.gt0),t=>this.run(this.model.query().delete().whereIn("id",t)))}}g.instances=new Map,e.ModelOpsLocal=g},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(127),r=n(42),s=n(15),o=n(10),a=n(72),u=n(12),l=n(19),c=n(89);e.OnlyMessages={formatLogEntry:t=>t.msg,format:(t,e,n,i)=>n};const d=[{re:/sync-file/,f:i.default.bgCyan},{re:/sync/,f:i.default.bgBlue},{re:/web/,f:i.default.bgGreen},{re:/db/,f:i.default.bgMagenta},{re:/main/,f:i.default.bgRed}];class h{constructor(t={}){this.chalkedLevels=new Map,this.inspectOptions=Object.assign(h.defaultInspectOptions(),t),u.Settings.logColor.valueOrDefault?(i.default.enabled=!0,i.default.level=1):(this.inspectOptions.colors=!1,i.default.enabled=!1),u.isTest&&(this.inspectOptions.breakLength=255),this.chalkedLevels.set("error",a.red("error")),this.chalkedLevels.set("warn",a.yellow("warn ")),this.chalkedLevels.set("info",a.green("info ")),this.chalkedLevels.set("debug",a.blue("debug")),this.prefix=s.Opt(t.prefix).flatMap(t=>s.Opt(d.find(e=>null!=t.match(e.re))).map(e=>e.f(a.black(t))).getOrElse(()=>t)).getOrElse(()=>"")}formatLogEntry(t){return o.compactBlanks([a.grey(new Date(t.timestamp).toISOString()),this.chalkedLevels.get(t.level),a.blue(t.context),t.msg,f(t.meta,this.inspectOptions)]).map(t=>l.toS(t)).join(" ")}format(t,e,n,i){const r=c.logFilter().highlight(e)?a.yellow:a.blue;return o.compactBlanks([a.grey((new Date).toISOString()),this.prefix,this.chalkedLevels.get(t),r(e),n,f(i,this.inspectOptions)]).map(t=>l.toS(t)).join(" ")}}function f(t,e){return null==t?t:r.inspect(t,e)}h.defaultInspectOptions=()=>({showHidden:!1,depth:4,compact:!0,colors:!0,customInspect:!0,maxArrayLength:25}),e.ColoredLogFormatter=h,e.DefaultLogFormatter=new h},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(32),o=`\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\nMoving or deleting any files here will cause problems using your library.\n\nIf you have any questions, please visit <https://support.photostructure.com/>.\n\nSincerely,\n\nYour Friendly Neighborhood PhotoStructure, v${n(64).version}`;function a(t){return r.mapNotBlank(t,t=>s.PosixFile.for(t).join(".photostructure"))}e.libraryDataDir=a,e.setupLibraryDataDir=function(t){return i(this,void 0,void 0,function*(){const e=a(t);if(null==e)throw new Error("empty dataDir");if(null==(yield e.mkdirp()))throw new Error("Could not mkdirp "+e);yield e.mkNoMedia();const n=e.join("README.txt");if((yield n.size())!==o.length&&!(yield n.writeTxt(o)))throw new Error("Could not write README to "+e);return e})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(45),s=n(55),o=n(6),a=n(2),u=n(25),l=n(23),c=n(13),d=n(34),h=n(106);function f(...t){return i(this,void 0,void 0,function*(){l.isWin&&t.push(c.ensureSuffix(t.pop(),".exe"));const e=o.map(h.ProjectPath.Tools(),t=>d.BaseFile.for(t));if(null==e||(yield e.isNotDirectory()))throw new Error("Cannot find project path for tools"+u.FatalErrorFlag);function n(n){return e.join(l.platformName+"-"+n,...t)}return a.firstTruePromise(t=>o.map(t,t=>t.exists()),()=>n(r.arch()),()=>"x64"===r.arch()?n("ia32"):void 0,()=>{throw new Error("Cannot find path to tool "+t)})})}e.toolFile=f,e.dcrawNativePath=s.lazy(()=>f("dcraw","dcraw").then(t=>t.nativePath)),e.jpegtranNativePath=s.lazy(()=>f("jpegtran","jpegtran").then(t=>t.nativePath)),e.sqliteNativePath=s.lazy(()=>f("sqlite3","sqlite3").then(t=>t.nativePath))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(6);function r(t){return i.map(t,t=>t+360*Math.ceil(-t/360))}e.normalizeRotation=r,e.flippable=function(t){const e=r(t);return 90===e||270===e}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(242),s=n(5),o=n(8),a=n(46),u=n(6),l=n(9),c=n(15),d=n(18),h=n(39),f=n(4),p=n(2),m=n(34),g=n(139),y=n(1),v=n(13),w=n(64),b=n(121),S=n(138),P=n(12),M=y.mkLogger("SettingsIO");e.systemSettingsFile=()=>m.BaseFile.for(h.App.getPath("userData")).join("settings.toml"),e.librarySettingsFile=t=>c.Opt(t).filter(o.notBlank).orElse(()=>P.Settings.libraryPath.value).filter(o.notBlank).flatMap(t=>b.libraryDataDir(t)).map(t=>t.join("settings.toml")).get(),e.libraryTxtFile=()=>m.BaseFile.for(h.App.getPath("userData")).join("library.txt"),e.readSystemSettings=function(){return i(this,void 0,void 0,function*(){const t=yield p.thenOrElse(F(e.systemSettingsFile()),()=>[]);return o.blank(P.Settings.libraryPath.value)&&o.notBlank(yield function(){return i(this,void 0,void 0,function*(){if(!P.Settings.libraryPath.hasValue()){const t=e.libraryTxtFile().clear();if(yield t.isNonEmpty()){const e=d.toS(yield t.readFile());if(o.notBlank(e))return M.info("Importing old library.txt file",{priorPath:e,libraryTxt:t}),P.Settings.libraryPath.value=e,(yield O())&&(yield t.renameWithNameSuffix("-obsolete")),e}}})}())&&s.pushUniq(t,P.Settings.libraryPath),t})},e.savedLibraryPath=function(){return p.thenMap(D(e.systemSettingsFile()),t=>t[P.Settings.libraryPath.name])},e.systemSettingsVersion=function(){return i(this,void 0,void 0,function*(){return E(e.systemSettingsFile())})},e.librarySettingsVersion=function(){return i(this,void 0,void 0,function*(){return u.map(e.librarySettingsFile(),t=>E(t))})};const x=/^# PhotoStructure v(\d+\.\d+\.\d+(?:-\S+)?)$/i;function E(t){return i(this,void 0,void 0,function*(){return p.thenMap(t.firstMatchingLine(x),t=>t[1])})}const _={maxLineLen:78,prefix:"# "};function k(t,e){return i(this,void 0,void 0,function*(){const n=yield t.clear().isNonEmpty(),r=n?yield t.wip():t;M.info("maybeWriteFile(): writing settings",{file:t});const o=yield function(t,e){return i(this,void 0,void 0,function*(){const n=f.flatten(["","Hello!","","These are settings for PhotoStructure, and are formatted using TOML. See <https://github.com/toml-lang/toml>.","","NOTE: Please shut down PhotoStructure before editing this file.","",'Most settings have reasonable defaults, which are provided after the description. Remove the "#" from the beginning of the line to override the default.',"","Visit <https://support.photostructure.com> or email <mailto:hello@photostructure.com>.","","-- ","","PhotoStructure v"+w.version,""].map(t=>v.wrap(t,_)));e.forEach(t=>{n.push("","",...v.wrap(t.opts.description,_),"# (env: "+t.key+")");const e=t.addToJSON();if(s.isNotEmpty(l.keys(e))&&n.push("# "+JSON.stringify(e)),n.push("#"),t.defaultValue!==t.value){const e={};e[t.name]=t.defaultValue,n.push(...T(e).map(t=>"# "+t))}if(t.hasValue()){const e={};e[t.name]=t.valueOrDefault,n.push(...T(e))}});try{return t.writeTxt("\n"+n.map(t=>t.trimRight()).join("\n")+"\n\n")}catch(e){return M.error("Failed to write "+t+": "+e),!1}})}(r,e);return o&&n&&((yield p.thenNot(a.eqlAsync(D(r),D(t))))&&(M.info("Archiving prior, different contents",{dest:r,file:t}),yield t.renameYMD()),yield r.unwip()),o})}function T(t){return g.splitLines(...l.entries(t).map(([t,e])=>(null==e?"# ":"")+t+" = "+JSON.stringify(e,void 0,2)))}function O(){return k(e.systemSettingsFile(),P.persistedSystemSettings())}function D(t){return i(this,void 0,void 0,function*(){return p.thenMap(t.readFile(),t=>r.parse(v.dumbquote(t.toString())))})}function F(t){return i(this,void 0,void 0,function*(){const e=y.mkLogger("FileSettings.importFileSettings("+t.baseWithGrandparent+")");try{e.debug("ENV before",P.psenv());const n=yield D(t);if(null==n){if(yield t.isNonEmpty())throw new Error("Failed to read "+t);return[]}const i=new Map(l.entries(P.Settings).filter(([,t])=>t instanceof S.Setting&&t.opts.persisted)),r=s.compact(l.keys(n).map(t=>{const r=n[t],s=i.get(t);return null==s?e.warn("Failed to import",{key:t}):s.hasValue()?e.debug("deferring to ENV",{key:t,tomlValue:r,currentValue:s.value}):s.value=r,s}));return e.info("loaded",{file:t.baseWithGrandparent,envAfter:P.psenv()}),r}catch(t){return void e.error("Cannot read",t)}})}e.stringify=T,e.writeSystemSettings=O,e.readLibrarySettings=function(t){return i(this,void 0,void 0,function*(){return u.map(e.librarySettingsFile(t),t=>F(t))})},e.writeLibrarySettings=function(t){return i(this,void 0,void 0,function*(){return yield b.setupLibraryDataDir(o.firstNotBlank(t,P.Settings.libraryPath.value)),u.map(e.librarySettingsFile(t),t=>k(t,P.persistedLibrarySettings()))})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(21),s=n(58),o=n(3),a=n(2),u=n(25),l=n(14),c=n(32),d=n(177),h=n(75),f=n(261),p=n(1),m=n(0),g=n(193),y=n(267),v=n(121),w=n(12),b=n(124),S=n(27),P=n(8),M=n(247),x=n(62),E=n(268),_=n(197),k=n(175),T=n(244),O=n(279),D=n(280),F=n(245),C=n(286),I=n(165),A=n(251),L=p.mkLogger("Library");w.Settings.libraryPath.addListener(t=>i(this,void 0,void 0,function*(){const e=m.map(R.instance.prior(),t=>t.rootDir);t!==e&&m.map(R.instance.clear(),r.end)}));class R extends r.EndableWrapper{constructor(t){super(`Library(${t})`,()=>this.onEnd()),this._ready=new s.Latch,this._lostLock=!1,this.setup=o.lazy(()=>i(this,void 0,void 0,function*(){try{if(yield v.setupLibraryDataDir(this.rootDir),yield b.readLibrarySettings(this.rootDir.nativePath),!x.dbRpc()){const t=this.lock();if(null==t)throw new u.WrappedError({message:"library lock was undefined",fatal:!0});const e=yield t.acquire();if(null==e||!e.acquired)throw new u.WrappedError({message:"Cannot acquire library lock",fatal:!0});if(null==(yield this.cacheDir()))throw new Error("Could not create cache dir"+u.FatalErrorFlag);if(null==(yield h.imgtmpDir()))throw new Error("Could not create cache dir"+u.FatalErrorFlag);if(null==(yield this.modelDbJanitor()))throw new Error("Failed to set up model DB"+u.FatalErrorFlag);L.info("Setting up db RPC..."),yield this.dbServer()}T.installLibraryUriSupport(),this._ready.resolve()}catch(t){this._ready.reject(t)}})),this.uidStore=o.lazy(()=>new d.UIDStore(this.dataDir)),this.uid=o.lazy(()=>this.uidStore().readUid()),this.cacheDir=o.lazy(()=>M.cacheDir()),this.localDbDir=o.lazy(()=>O.localDbDir()),this.previews=o.lazy(()=>new f.Previews(this.dataDir.join("previews"))),this.assetFileRepository=o.lazy(()=>new A.AssetFileRepository(this.rootDir,()=>w.Settings.copyAssetsToLibrary.valueOrDefault)),this.lock=o.lazy(()=>k.libraryLock(this.rootDir,()=>{this._lostLock=!0,r.ending()||(L.error("LOST LOCK to "+this.rootDir),_.libraryHealthChecks.clear(),l.emitFatal(k.LostLibraryLockMsg))})),this.modelDbJanitor=o.lazy(()=>i(this,void 0,void 0,function*(){return x.dbRpc()?void 0:new D.ModelDbJanitor(this.dataDir,this.localDbDir)})),this.statsDbJanitor=o.lazy(()=>i(this,void 0,void 0,function*(){return C.statsDbJanitor(yield this.cacheDir())})),this.modelDb=()=>a.thenMap(this.modelDbJanitor(),t=>t.db),this.statsDb=()=>a.thenMap(this.statsDbJanitor(),t=>t.db),this.dbServer=o.lazy(()=>i(this,void 0,void 0,function*(){const t=yield this.modelDb();F.modelJsonSetup();const e=new E.DbServiceHandlers(t);g.sid.refresh();const n=new y.Server(w.Settings.rpcPort.valueOrDefault,e);return yield n.ready,L.info("dbServer(): RPC service up on "+n.port+" serving "+this.rootDir),I.stdoutWrite(w.Settings.rpcPort.addToEnv({})),n})),this.rootDir=c.PosixFile.for(t),this.dataDir=v.libraryDataDir(this.rootDir)}get lostLock(){return this._lostLock}get ready(){return this._ready.promise}onEnd(){return i(this,void 0,void 0,function*(){return a.tryAll([()=>a.thenMap(this.dbServer.clear(),t=>t.end()),()=>a.thenMap(this.statsDbJanitor.clear(),t=>t.end(!0)),()=>a.thenMap(this.modelDbJanitor.clear(),t=>t.end()),()=>L.info("onEnd() finished.")])})}}R.instance=o.lazy(()=>P.mapNotBlank(w.Settings.libraryPath.value,t=>(L.log("info","Library.instance now points to "+t),S.tap(new R(t),t=>t.setup())))),e.Library=R},function(t,e){t.exports=require("sharp")},function(t,e){t.exports=require("chalk")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(45),r=n(30),s=n(22),o=n(8),a=n(69);e.appData=function(){const t=a.getEnv("APPDATA");if(o.notBlank(t))return r.resolve(t);switch(i.platform()){case"win32":return r.resolve(i.homedir(),"AppData","Roaming");case"darwin":return r.resolve(i.homedir(),"Library","Application Support");case"linux":return o.firstNotBlank(s.env.XDG_DATA_HOME,s.env.XDG_CONFIG_HOME,r.resolve(i.homedir(),".config"));default:throw new Error("Platform not supported")}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AppName="PhotoStructure"},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(17),r=n(7);e.BoundedList=class{constructor(t){if(this.maxLength=t,this._length=0,this._firstIndex=0,t>1e3)throw new Error("BoundedList.maxLength of "+t);this.store=new Array(...r.times(t,()=>null))}mapIndex(t,e){return t<0||t>this._length-1?void 0:e((t+this._firstIndex+this.maxLength)%this.maxLength)}get(t){return this.mapIndex(t,t=>this.store[t])}set(t,e){return this.mapIndex(t,t=>this.store[t]=e)}get length(){return this._length}set length(t){this._length=i.clamp(0,this._length,t)}[Symbol.iterator](){const t=this;return function*(){for(let e=0;e<t.length;e++)yield t.mapIndex(e,e=>t.store[e])}()}push(...t){for(const e of t)this._length<this.maxLength?this._length++:(this._firstIndex++,this._firstIndex=this._firstIndex%this.maxLength),this.mapIndex(this._length-1,t=>{this.store[t]=e});return this._length}pop(){return this.mapIndex(this._length-1,t=>(this._length--,this.store[t]))}unshift(...t){for(const e of t.reverse())this._length<this.maxLength&&this._length++,this._firstIndex--,this.mapIndex(0,t=>{this.store[t]=e,this._firstIndex=t});return this._length}shift(){return this.mapIndex(0,t=>(this._firstIndex++,this._length--,this.store[t]))}every(t){for(let e=0;e<this._length;e++)if(!t(this.get(e),e))return!1;return!0}some(t){for(let e=0;e<this._length;e++)if(t(this.get(e),e))return!0;return!1}forEach(t){for(let e=0;e<this._length;e++)t(this.get(e),e)}map(t){const e=[];for(let n=0;n<this._length;n++)e.push(t(this.get(n),n));return e}reduce(t,e){let n=e;for(let e=0;e<this._length;e++)n=t(n,this.get(e),e);return n}reverse(){for(let t=0;t<Math.floor(this._length/2);t++)this.mapIndex(t,e=>{this.mapIndex(this._length-1-t,t=>{const n=this.store[t];this.store[t]=this.store[e],this.store[e]=n})});return this}toA(){return[...this]}slice(t,e){return[...this].slice(t,e)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(67),s=n(0),o=n(27);e.CountingSet=class{constructor(){this.m=new Map}incr(t,e=1){const n=this.get(t)+e;return 0===n?this.m.delete(t):this.m.set(t,n),this}get(t){return s.orElse(this.m.get(t),()=>0)}has(t){return this.m.has(t)}get size(){return this.m.size}keys(){return this.m.keys()}entries(){return this.m.entries()}entriesByCountDesc(){return i.sortBy([...this.entries()],([,t])=>-t)}top(t=1){return this.entriesByCountDesc().slice(0,t)}get averageCounts(){return o.tap(new r.Average(this.size),t=>[...this.m.values()].forEach(e=>t.push(e)))}forEach(t){this.m.forEach(t)}clear(){this.m.clear()}get toS(){return i.sort([...this.keys()]).map(t=>t+" "+this.get(t)).join("\n")}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(87),r=n(22),s=n(16),o=n(6),a=n(18),u=n(21),l=n(14),c=n(1),d=n(81);class h{constructor(t,e){this.name=t,this.bc=e}get ended(){return this.bc.ended}end(){return this.bc.end()}}e.observeBatchCluster=function(t,e,n=u.EndableRanks.service){const f=c.mkLogger(e);return i.setLogger(f),u.addEndable(n,new h(e,t)),t.on("childStart",n=>d.addPid({pid:n.pid,ppid:r.pid,cmd:e,maxAgeMs:t.options.maxProcAgeMillis+s.minuteMs},new Date)),t.on("startError",t=>{l.emitFatal("Failed to start "+e,t)}),t.on("taskError",(t,n)=>{if(!a.toS(t).includes("end() called when not idle")&&!u.ending()){const i=o.map(n,t=>t.command);f.warn("observeBatchCluster.taskError()",{error:t,cmd:i}),l.emitNonFatal(e+" failed to run "+i,t)}}),t.on("internalError",t=>{f.warn("observeBatchCluster.internalError()",t),l.emitNonFatal("Internal error from "+e,t)}),t.on("endError",t=>{f.warn("observeBatchCluster.endError()",t),f.error("Failed to shut down: "+t)}),t}},function(t,e){t.exports=require("crypto")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(9),s=n(3),o=n(89),a=n(120),u=n(101);class l{constructor(t,e=[["error",console.error]]){this.logFilter=t,this.loggers=r.fromEntries(e)}log(t,e,n,i){(this.loggers[t]||console.log)(a.DefaultLogFormatter.format(t,e,n,i))}enabled(t,e){return this.logFilter.enabled(t,e)}flush(){return i(this,void 0,void 0,function*(){})}close(){}}l.instance=s.lazy(()=>new l(o.logFilter())),e.ConsoleLogger=l,e.mkConsoleLogger=function(t){return new u.ContextualLogger(t,()=>l.instance())}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(213),s=n(109),o=n(78),a=n(4),u=n(3),l=n(77),c=n(2),d=n(10),h=n(29),f=n(11),p=n(14),m=n(1),g=n(158),y=n(13),v=n(27),w=n(19),b=n(74),S=n(34),P=n(52),M=n(28),x=n(32),E=u.lazy(()=>m.mkLogger("FileURI")),_=["http:","https:","file:",o.PS_LOCAL_FILE_PROTOCOL,o.PS_NETWORK_FILESYSTEM_PROTOCOL,o.OLD_PS_LOCAL_FILE_PROTOCOL].map(t=>t+"//");function k(t,n){return i(this,void 0,void 0,function*(){if(h.truthy(t.remote)){if(d.notBlank(t.remoteHost)&&d.notBlank(t.remoteShare)){const e=encodeURI(n.posixPathFrom(x.PosixFile.for(t.mountpoint)));return{protocol:o.PS_NETWORK_FILESYSTEM_PROTOCOL,hostname:r.toASCII(yield g.friendlyname(t.remoteHost)),pathname:r.toASCII(t.remoteShare)+(d.blank(e)?e:"/"+e),slashes:!0,volume:t}}}else if(d.notBlank(t.uuid))return{protocol:o.PS_LOCAL_FILE_PROTOCOL,hostname:e.volsha(t.uuid),pathname:encodeURI(n.posixPathFrom(x.PosixFile.for(t.mountpoint))),slashes:!0,volume:t}})}e.isUri=function(t){const e=w.toS(t).toLowerCase();return _.some(t=>e.startsWith(t))},e.FileToFileUri=t=>{if(null==t||d.blank(t.posixPath))return;const e=w.toS(t.hostname),n={pathname:encodeURI(y.stripPrefix(t.posixPath,"//"+e)),protocol:"file:",slashes:!0};return d.notBlank(e)&&(n.hostname=r.toASCII(e)),n},e.volsha=l.memoize(t=>v.tap(d.mapNotBlank(t,P.shortStringSha),e=>E().debug("volsha",{uuid:t,ea:e})),1*f.hourMs,128),p.onClearCache(()=>e.volsha.clear()),e.volumeURI=k,e.FileToPsUri=t=>{const e=x.PosixFile.for(M.posix2native(t.posixPath));return c.thenMap(b.volumeFor(e.nativePath),t=>k(t,e))};const T=[e.FileToPsUri,e.FileToFileUri];function O(t){return i(this,void 0,void 0,function*(){if(null!=t&&!d.blank(t.posixPath))return c.firstAsync(T,e=>e(t)).catch(e=>{E().warn("file2voluri failed",{file:t,err:e})})})}e.addUriFormatter=function(t){T.unshift(t),a.uniqInPlace(T)},e.file2fileuri=function(t){return s.format(e.FileToFileUri(t))},e.nativePath2uriString=function(t){return c.thenMap(O({posixPath:M.native2posix(t)}),s.format)},e.file2voluri=O,e.uriToString=function(t){if(null==t||"string"==typeof t)return t;try{return s.format(t)}catch(e){return void E().warn("toString failed",{uri:t,err:e})}};const D=/^[a-z]+:\/\/([a-z0-9-\.]+?)(?:\/(.+)?)?$/i;e.PsfileUriToFile=(t,n)=>i(this,void 0,void 0,function*(){if(null==t||d.blank(n))return;if(!y.equalsIgnoreCase(t.protocol,o.PS_LOCAL_FILE_PROTOCOL)&&!y.equalsIgnoreCase(t.protocol,o.OLD_PS_LOCAL_FILE_PROTOCOL))return;const i=yield b.volumes();if(a.isEmpty(i))return void E().warn("PsfileUriToFile(): volumes() was empty: Can't resolve "+n);const r=n.match(D);if(null==r)return void E().warn("PsfileUriToFile(): didn't match regex",{raw:n});const s=r[1];if(d.blank(s))return void E().warn("PsfileUriToFile(): no volsha",{raw:n});const u=y.stripSuffix(decodeURI(w.toS(r[2])),"/").split("/"),l=i.find(t=>!t.remote&&d.notBlank(t.uuid)&&s===e.volsha(t.uuid));if(null!=l)return{posixPath:S.BaseFile.for(l.mountpoint).join(...u).posixPath};{const t=i.filter(t=>null!=t.uuid).map(t=>e.volsha(t.uuid));E().warn("PsfileUriToFile(): no volume had matching volsha",{raw:n,volid:s,volshas:t})}}),e.PsnetUriToFile=t=>i(this,void 0,void 0,function*(){if(null==t)return;if(!y.equalsIgnoreCase(t.protocol,o.PS_NETWORK_FILESYSTEM_PROTOCOL))return;if(d.blank(t.pathname)||d.blank(t.hostname))return;const e=r.toUnicode(w.toS(t.hostname)),n=y.stripPrefix(w.toS(t.pathname),"/").split("/"),i=r.toUnicode(n.shift());if(d.blank(i))return;const s=n.map(decodeURIComponent);return c.thenMap(b.remoteVolumeFor(e,i),t=>({posixPath:S.BaseFile.for(t.mountpoint).join(...s).posixPath}))}),e.FileUriToFile=t=>{if(null==t)return;if(!y.equalsIgnoreCase(t.protocol,"file:")||d.blank(t.pathname))return;const e=decodeURI(w.toS(t.hostname)),n=decodeURI(w.toS(t.pathname));return d.notBlank(e)?{hostname:e,posixPath:n}:{posixPath:null!=n.match(/^\/[A-Z]:\//i)?n.substring(1):n}};const F=[e.PsfileUriToFile,e.PsnetUriToFile,e.FileUriToFile];e.addUriParser=function(t){F.unshift(t),a.uniqInPlace(F)},e.uri2file=function(t,e){return i(this,void 0,void 0,function*(){if(d.blank(t))return;const n=function(t){try{return s.parse(t,!1,!0)}catch(e){return void E().warn("bad URI",{uri:t,err:e})}}(t);return null!=n?c.firstAsync(F,e=>e(n,t)).catch(i=>{if(E().warn("uri2file failed",{uri:t,err:i}),d.notBlank(e)&&null!=n.pathname){const t=n.pathname.split("/").slice(1);return{posixPath:x.PosixFile.for(e).join(...t).posixPath}}}):void 0})},e.toUrl=function(t){if(null!=t){if("string"!=typeof t&&[t.protocol,t.pathname,t.hostname].every(d.notBlank))return t;try{return s.parse(w.toS(t),!0)}catch(e){return void E().warn("toUrl failed",{uri:t,err:e})}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(42),r=n(4),s=n(3),o=n(7),a=n(12),u=n(56),l=n(231);class c{constructor(t,e,n,i,r=!0){this.name=t,this.maxWidth=e,this.maxHeight=n,this.reducer=i,this.rotational=r,this.megapixels=s.lazy(()=>o.megapixels(this.maxWidth*this.maxHeight)),this.max={width:e,height:n},c._Sizes.push(this)}static sq(){return this._Sizes.filter(t=>t.reducer===l.Square)}static largestSq(){return r.greatestBy(this.sq(),t=>t.megapixels())}static fit(){const t=a.Settings.previewResolutions.valueOrDefault;return this._Sizes.filter(e=>e.reducer===l.Fit&&t.includes(e.name))}static largestFit(){return r.greatestBy(this.fit(),t=>t.megapixels())}[i.inspect.custom](){return{ctor:"ImageSize",name:this.name+" ("+this.reducer.name+")",maxDim:this.maxWidth+"x"+this.maxHeight,maxMP:this.megapixels()}}get minDimension(){return Math.min(this.maxWidth,this.maxHeight)}outputSize(t){return this.reducer.reduce(this.rotational&&u.isPortrait(t)?u.flip(this.max):this.max,t)}resize(t,e){return e=e.resize(Object.assign({},t,{fit:this.reducer.fit,withoutEnlargement:!0}))}toJpeg({path:t,sh:e,outputSize:n}){return(u.dmegapixels(n)<2||a.Settings.sharpen.valueOrDefault)&&(e=e.sharpen()),e.jpeg({quality:85,progressive:a.Settings.progressive.valueOrDefault}).toFile(t)}toString(){return this.name}}c._Sizes=[],c.UHD8k=new c("uhd8k",7680,4320,l.Fit,!1),c.UHD5k=new c("uhd5k",5120,2880,l.Fit,!1),c.UHD=new c("uhd4k",4096,2160,l.Fit),c.QHD=new c("qhd",3120,1440,l.Fit),c.FHD=new c("fhd",1920,1080,l.Fit),c.HD=new c("hd",1280,720,l.Fit),c.WVGA=new c("wvga",720,480,l.Fit),c.QVGA=new c("qvga",320,240,l.Fit),c.QQVGA=new c("qqvga",160,120,l.Fit),c.S480=new c("s480",480,480,l.Square),c.S240=new c("s240",240,240,l.Square),c.S120=new c("s120",120,120,l.Square),c.S60=new c("s60",60,60,l.Square),e.ImageSize=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(8),s=n(15),o=n(235),a=n(13),u=n(49),l=n(28);function c(t){const e=new Set(i.compactBlanks(t.map(t=>a.ensurePrefix(t.toLowerCase().normalize(),"."))));return o.Filter.lift(t=>s.Opt(t).flatMap(t=>r.firstNotBlank(t.ext,t.base)).map(t=>e.has(t.toLowerCase().normalize())).getOrElse(()=>!1))}e.excludedPathFilter=function(t){const e=new Set(t.map(t=>t.toLowerCase()));return o.Filter.lift(t=>l.pathnames(t.nativePath).every(t=>!e.has(t.toLowerCase())))},e.extFilter=c,e.browserImgExtFilter=c(u.browserImgExts),e.browserExtFilter=c(u.browserExts),e.videoExtFilter=c(u.VideoExts)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(30),r=n(22),s=n(5),o=n(8),a=n(46),u=n(6),l=n(17),c=n(9),d=n(41),h=n(15),f=n(33),p=n(18),m=n(29),g=n(0);e.SettingCategories=f.strEnum("System","Logging","Updates","ErrorReporting","Tools","Web","Sync","Filters"),e.LibraryCategories=Object.freeze([e.SettingCategories.Web,e.SettingCategories.Sync,e.SettingCategories.Filters]),e.SystemCategories=Object.freeze(f.strEnumValues(e.SettingCategories).filter(t=>!e.LibraryCategories.includes(t)));class y{constructor(t){this.opts=t,this.listeners=[],y.instances.push(this),this.readFromEnv(),this.addToChildProcs=!0===t.addToChildProcs}static importSavedPref(t){return o.mapNotBlank(t.key,e=>u.map(this.instances.find(t=>t.key===e),e=>g.Try(()=>c.tap(e,e=>e.value=t.value))))}readFromEnv(){if(!this.hasValue())return h.Opt(r.env[this.opts.key]).filter(o.notBlank).orElse(()=>h.Opt(this.opts.alternateKeys).map(t=>t.map(t=>r.env[t])).flatMap(t=>t.find(o.notBlank))).flatMap(this.opts.fromEnv).map(t=>this.value=t).get()}addListener(t){this.listeners.push(t),this.hasValue()&&setImmediate(()=>t(this.value))}removeListener(t){s.filterInPlace(this.listeners,e=>e===t)}onChange(){const t=this.value;this.listeners.forEach(e=>e(t))}get name(){return this.opts.name}get key(){return this.opts.key}get category(){return this.opts.category}get persisted(){return this.opts.persisted}get advanced(){return g.orElse(this.opts.advanced,!0)}get value(){return this._value}set value(t){const e=this._value;this._value=this.opts.fromEnv(this.opts.toEnv(t)),a.eql(e,this._value)||this.onChange()}set valueFromFile(t){this.value!==this.defaultValue&&(this.value=t)}get defaultValue(){return d.isFunction(this.opts.defaultValue)?this.opts.defaultValue():this.opts.defaultValue}get valueOrDefault(){return g.orElse(this.value,this.defaultValue)}addToEnv(t,e){const n=g.orElse(t,r.env);return n[this.opts.key]=v(this.opts.toEnv(g.orElse(e,this.valueOrDefault))),n}deleteFromEnv(t){const e=g.orElse(t,r.env);return delete e[this.opts.key],u.map(this.opts.alternateKeys,t=>t.forEach(t=>{delete e[t]})),e}hasValue(){return null!=this.value}clear(){return this._value=void 0,this.onChange(),this}addToJSON(){return{}}toJSON(){return{key:this.opts.key,value:this.value,defaultValue:this.opts.defaultValue,description:this.opts.description}}}y.instances=[],e.Setting=y;const v=t=>o.notBlank(t)&&"undefined"!==t?p.toS(t).trim():void 0;function w(t,e){const n=p.toS(t).toLowerCase();return e.find(t=>t.toLowerCase()===n)}e.StringSetting=class extends y{constructor(t){super(Object.assign({toEnv:v,fromEnv:v},t))}hasValue(){return o.notBlank(this.value)}};e.StringEnumSetting=class extends y{constructor(t){if(super(Object.assign({toEnv:e=>w(e,t.validValues),fromEnv:e=>w(e,t.validValues)},t)),this.validValues=t.validValues,!this.validValues.includes(this.defaultValue))throw new Error(`validValues, ${this.validValues}, doesn't include defaultValue, ${t.defaultValue}`)}addToJSON(){return{validValues:this.validValues}}};e.StringArraySetting=class extends y{constructor(t){super(Object.assign({defaultValue:[],fromEnv:t=>o.mapNotBlank(t,t=>{try{return s.compactBlankish(s.toA(JSON.parse(t)))}catch(e){return s.compactBlankish(t.split(i.delimiter))}}),toEnv:t=>u.map(t,t=>JSON.stringify(s.uniq(t)))},t))}get values(){return s.uniq(s.compactBlanks(this.valueOrDefault))}push(...t){this.value=s.uniq(s.compactBlanks(this.valueOrDefault.concat(...t)))}removeValue(t){u.map(this.value,e=>this.value=e.filter(e=>e!==t))}};e.StringEnumsSetting=class extends y{constructor(t){super(Object.assign({defaultValue:t.defaultValue,fromEnv:t=>o.mapNotBlank(t,t=>{try{return this.asValidValues(JSON.parse(t))}catch(e){return this.asValidValues(t.split(i.delimiter))}}),toEnv:t=>u.map(t,t=>JSON.stringify(s.uniq(t)))},t)),this.validValues=t.validValues}asValidValues(t){return s.compactBlankish(s.toA(t).map(t=>w(p.toS(t),this.validValues)))}addToJSON(){return{validValues:this.validValues}}};e.IntegerSetting=class extends y{constructor(t){super(Object.assign({},t,{toEnv:v,fromEnv:l.toInt}))}};e.BoundedIntegerSetting=class extends y{constructor(t){super(Object.assign({},t,{toEnv:v,fromEnv:e=>h.Opt(e).flatMap(parseInt).map(e=>l.clamp(t.min,t.max,e)).get()})),this.options=t}addToJSON(){return{minValue:this.options.min,maxValue:this.options.max}}};e.BooleanSetting=class extends y{constructor(t){super(Object.assign({},t,{toEnv:v,fromEnv:m.toBoolean}))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(23);e.crlf=function(t){const n=t.trim()+"\n";return r.isWin?n.replace(e.newlineRe,"\r\n"):n},e.newlineRe=/\r?\n/gm,e.splitLines=function(...t){return i.flatten(t.map(t=>t.split(e.newlineRe)))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(30),s=n(8),o=n(16),a=n(55),u=n(17),l=n(2),c=n(29),d=n(63),h=n(11),f=n(14),p=n(1),m=n(34),g=n(148),y=n(28),v=/^\.?NoMedia$/i;function w(t){return null!=v.exec(t)}e.isNoMediaName=w,f.onClearCache(()=>S.clear()),f.onFileChanged(t=>{if(s.blank(t))S.clear();else for(const e of S.keys())e.startsWith(t)&&S.delete(e)});const b=15*o.secondMs,S=new d.BoundedMap(3*o.minuteMs,2e3,!1),P=a.lazy(()=>p.mkLogger("hasNoMedia()"));e.hasNoMedia=function t(e){return i(this,void 0,void 0,function*(){if(e instanceof m.BaseFile)return t(yield e.directoryEntry());if(g.pathIsNeverIgnored(e.nativePath))return P().debug(e+" is never ignoed"),!1;if(w(e.base))return P().debug(e+" basename is NoMedia"),!0;const n=y.pathnames(e.nativePath);if(n.some(w))return P().debug(e+" parent path is NoMedia"),!0;for(let t=n.length-1;t>0;t--){const i=n.slice(0,t).join(r.sep),s=S.get(i);if(!0===s)return P().debug(e+" ancestor is NoMedia, "+i),!0;if(!1!==s&&u.isNumber(s)&&(yield l.until(()=>c.isBoolean(S.get(i)),b))&&!0===S.get(i))return P().debug(e+" ancestor is NoMedia, "+i),!0}const i=S.get(e.nativePath);if(c.isBoolean(i))return P().debug(e+" returning cached result, "+i),i;const s=yield e.isDirectory();if(s){if(null!=i&&h.recentMs(i,b)&&(P().debug(e+" is a work-in-progress. Waiting for prior result."),yield l.until(()=>c.isBoolean(S.get(e.nativePath)),b)))return t(e);P().debug(e+" has no cached result, I'll do it.");const n=Date.now();S.set(e.nativePath,n);const r=yield e.children();if(null==r)return P().debug(e+" is a directory but has no children.",{result:!1}),S.set(e.nativePath,!1),!1;if(r.some(t=>w(t.base)))return P().debug(e+" is a directory and has a noMedia child",{result:!0}),S.set(e.nativePath,!0),!0}const o=yield e.parent();if(null==o||e.nativePath===o.nativePath)return P().debug(e+" root",{result:!1}),S.set(e.nativePath,!1),!1;{P().debug(e+" deferring to parent");const n=yield t(o);return P().debug(e+" got result from parent",{result:n}),s&&S.set(e.nativePath,n),P().debug(e+" from parent",{result:n}),n}})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(16),r=n(33),s=n(39),o=n(93);e.ServiceNames=r.strEnum("main","web","sync","sync-file","db"),e.NoDbServices=["main"],e.DbServices=["web","db"],e.RestartOnRpcChangeServices=["sync-file"],e.WelcomeServices=["main","web"],e.title=function(t){return s.App.getName()+" "+t},e.serviceMaxAgeMs=function(t){switch(t){case"main":return 0;case"sync-file":return 2*o.MaxSyncFileTimeoutMs;case"web":case"db":case"sync":default:return 6*i.hourMs}},e.serviceShutdownTimeoutMs=function(t){switch(t){case"main":case"web":case"db":return i.minuteMs;case"sync":case"sync-file":default:return 30*i.secondMs}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4);e.hasFail=function(t){return null!=t&&i.isNotEmpty(t.fail)},e.hasBad=function(t){return null!=t&&i.isNotEmpty(t.bad)},e.fullhc=function(t){return{ok:i.toA(t.ok),warn:i.toA(t.warn),bad:i.toA(t.bad),fail:i.toA(t.fail)}},e.concatHealthChecks=function(...t){function e(e){return i.uniq(i.compact(i.flatten(t.map(e))))}return t=i.compact(t),{ok:e(t=>t.ok),warn:e(t=>t.warn),bad:e(t=>t.bad),fail:e(t=>t.fail)}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(270),s=n(2),o=n(0);e.knex=r({client:"sqlite3",useNullAsDefault:!0}),e.firstMigratedAt=function(t){return i(this,void 0,void 0,function*(){return s.thenMap(t("migrations").min("migration_time").first(),t=>o.map(o.values(t)[0],t=>new Date(t)))})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(14),o=n(7),a=n(27),u=n(274),l=n(16),c=n(6),d=n(9),h=n(155),f=n(108);s.onClearCache(()=>p.clear());class p extends h.Model{static clear(){this.assetId2tagIds.clear()}$pk(){return[c.orElse(this.assetId,()=>d.map(this.asset,t=>t.id)),c.orElse(this.tagId,()=>d.map(this.tag,t=>t.id))].join(":")}static addTagsToAsset(t,e,n){return i(this,void 0,void 0,function*(){const i=o.id(t);if(null==i)return void this.logger().warn("addTagsToAsset(): got null assetId");const s=r.compact(e.map(o.id));if(r.isEmpty(s))return void this.logger().warn("addTagsToAsset(): no tagIds",{assetId:t,tagIds:e});const a="INSERT OR IGNORE INTO AssetTag(assetId,tagId) VALUES "+s.map(t=>`(${i},${t})`).join(",");return f.Tag.onAssetTagChange(),e.forEach(e=>this.assetId2tagIds.add(t,e)),this.dbr(t=>t.run(a),n)})}static removeTagsFromAsset(t,e,n){e=r.compact(e),f.Tag.onAssetTagChange();const i=this.query().whereIn("tagId",e).andWhere({assetId:t}).delete();return a.atap(this.dbr(t=>t.run(i),n),()=>e.forEach(e=>this.assetId2tagIds.delete(t,e)))}}p.tableName="AssetTag",p.assetId2tagIds=new u.TTLMultiMap(5*l.minuteMs),e.AssetTag=p},function(t,e){t.exports=require("readline")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(33);e.FitSizes=i.strEnum("uhd8k","uhd5k","uhd4k","qhd","fhd","hd","wvga","qvga","qqvga"),e.FitSizeValues=i.strEnumValues(e.FitSizes),e.SqSizes=i.strEnum("s480","s240","s120","s60"),e.SqWidths=[60,120,240,480]},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(35),r=n(17);function s(t){return o(t,!1)}function o(t,e){return new Promise(n=>{if(t<=0)n();else{const r=i.setTimeout(()=>n(),Math.round(t+1));e&&r.unref()}})}e.unrefDelay=function(t){return o(t,!0)},e.delay=s,e.delayUntil=function(t){const e=(r.gt0(t)?t:t.getTime())-Date.now();if(e<0){if(e>-500)return;throw new Error("Mr. Fusion not found, cannot time travel back "+-e+"ms")}return s(e).then(()=>e)},e.later=function(t,e=1){return i.setTimeout(t,Math.max(1,Math.round(e)))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(18),s=n(3),o=n(14),a=n(12),u=s.lazy(()=>{a.Settings.neverIgnored.addListener(()=>{l.clear(),o.emitFileChanged()}),a.Settings.scanPaths.addListener(()=>{l.clear(),o.emitFileChanged()}),o.onClearCache(()=>l.clear())}),l=s.lazy(()=>(u(),new Set(i.compactBlanks([...a.Settings.scanPaths.values,...a.Settings.neverIgnored.values]))));function c(t){return l().has(t)||l().has(t.toLowerCase().normalize())}e.pathIsNeverIgnored=c,e.neverIgnore=function(...t){a.Settings.neverIgnored.push(...i.compactBlanks(t.map(r.toS)))},e.pathIsNeverIgnoredPredicate=function(t){return c(t)?{pathIsNeverIgnored:()=>!1}:void 0}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(16),s=n(2),o=n(20),a=n(14),u=n(122),l=n(23),c=n(115),d=n(75),h=l.isWin?"NUL":"/dev/null";function f(t,e,n){return i(this,void 0,void 0,function*(){const i=yield u.jpegtranNativePath();if(!c.isRotation(n))throw new Error("refusing to rotate("+t+", "+n+")");yield o.stdout(i,["-copy","all","-trim","-rotate",n.toFixed(0),"-outfile",e.nativePath,t.nativePath],{timeout:r.minuteMs})})}e.validJpeg=function(t){return i(this,void 0,void 0,function*(){const e=yield u.jpegtranNativePath();yield o.stdoutResult(e,["-outfile",h,t.nativePath],{timeout:30*r.secondMs})})},e.rotateInPlace=function(t,e){return i(this,void 0,void 0,function*(){const n=t.wip();yield f(t,n,e),yield n.unwip(),a.emitFileChanged(t.nativePath)})},e.rotate=f,e.rotateToImgTmp=function(t,e){return i(this,void 0,void 0,function*(){return null==e||0===e?t:s.thenMap(d.tmpImgFile(t,"r"+e,t.ext),n=>n.applyIfEmpty(n=>f(t,n,e)))})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(30),s=n(8),o=n(16),a=n(15),u=n(44),l=n(4),c=n(2),d=n(10),h=n(98),f=n(137),p=n(26),m=n(1),g=n(0),y=n(103),v=n(27),w=n(19),b=n(82),S=n(31),P=n(49),M=m.mkLogger("TagInference"),x=m.mkLogger("TagInference.inferMakeAndModel()");e.inferMakeAndModel=function(t,e){return i(this,void 0,void 0,function*(){if(M.debug("inferMakeAndModel("+t+")",{Make:e.Make,Model:e.Model}),s.notBlank(e.Make)&&s.notBlank(e.Model))return;if(d.blank(e.Make)&&(w.toS(e.HandlerDescription)+w.toS(e.CompressorName)).includes("GoPro"))return void(e.Make="GoPro");const n=D(t),{younger:i,older:r}=yield A(t),o=l.compact(l.flatten(l.zip(i,r))).slice(0,50).filter(t=>y.diceCoeff(D(t),n)>.7).slice(0,10);M.info("inferMakeAndModel("+t+"): looking at nearby siblings",o.map(t=>t.base));for(const n of o){const i=yield S.readRawTags(n);if(null!=i&&l.allNotBlank(i.Make,i.Model))return x.info("Inferring Make and Model",{file:t.nativePath,sibling:n.base,Make:i.Make,Model:i.Model}),e.Make=i.Make,void(e.Model=i.Model)}})};const E=m.mkLogger("TagInference.inferCapturedAtFromSiblings()");function _(t,e=7){return i(this,void 0,void 0,function*(){return c.firstAsync(t.slice(0,e),(t,e)=>c.thenMap(S.readRawTags(t),t=>c.thenMap(b.capturedAtFromTags(t),t=>({d:t,index:e}))))})}e.inferCapturedAtFromSiblings=function(t){return i(this,void 0,void 0,function*(){return c.thenMap(function(t){return k.getOrSet(t.nativePath,()=>i(this,void 0,void 0,function*(){const{younger:e,older:n}=yield A(t),i=yield _(e),r=yield _(n);if(null!=i&&null!=r)return{before:i.d,after:r.d,index:i.index,slots:i.index+r.index+1}}))}(t),({before:e,after:n,index:r,slots:s})=>i(this,void 0,void 0,function*(){if(p.sameDay(e,n))return v.tap(h.DateInterval.for(e,n,r,s),e=>E.info("inferring date",{file:t.nativePath,result:w.toS(e)}));E.debug("rejecting, not same day",{file:t.nativePath,before:w.toS(e),after:w.toS(n)})}))})};const k=new u.TTLMap(2*o.minuteMs);const T=/^(?:(?:mvimg|img|vid|mov|gp|gf|p|gopr)(?:[-_ ]|(?=\d)))?(\S.+)$/i,O=/[\d_]{4,}$/;function D(t){return F(t.nameWithoutCount)}function F(t){return d.blank(t)?"":a.Opt(g.Try(()=>r.posix.parse(t))).flatMap(t=>t.name).flatMap(t=>a.Opt(O.exec(t.replace(/_cover$/i,""))).flatMap(t=>t[0]).orElse(()=>a.Opt(T.exec(t)).flatMap(t=>t[1]))).getOrElse(()=>t).replace(/^[\s-_]*/,"").replace(/[\s-_]*$/,"").toLowerCase().normalize()}e.bname=D,e.bnameString=F;const C=f.extFilter(P.AllExifExts),I=new u.TTLMap(2*o.minuteMs);function A(t,e=7){return i(this,void 0,void 0,function*(){return I.getOrSet(t.nativePath,()=>i(this,void 0,void 0,function*(){const n=D(t),i=(yield t.siblings()).filter(t=>C.apply(t)&&!P.isSidecarExt(t.ext)&&y.diceCoeff(D(t),n)>.7),r=l.sortBy(i,t=>D(t)),[s,o]=l.partition(r,t=>D(t)<n);return s.reverse(),{younger:s.slice(0,e),older:o.slice(0,e)}}))})}function L(t){return i(this,void 0,void 0,function*(){const{younger:e,older:n}=yield A(t),r=l.flatZip(e,n).slice(0,10),s=yield c.thenMap(function(t,e=7){return i(this,void 0,void 0,function*(){return c.firstAsync(t.slice(0,e),(t,e)=>c.thenMap(S.readRawTags(t),t=>c.thenMap(b.capturedAtFromTags(t),t=>a.Opt(t).filter(t=>p.hasZoneOffset(t)).flatMap(t=>p.getZoneName(t)).map(t=>({zoneName:t,index:e})).get())))})}(r),t=>t.zoneName);return M.info("nearestSiblingTzOffset()",{f:t.baseWithGrandparent,result:s}),s})}e.nearestSiblings=A,e.nearestSiblingTzOffset=L,e.extractStatname=function(t){return i(this,void 0,void 0,function*(){const e=p.parseDated(D(t));if(!p.hasTime(e))return;const n=yield t.stat(),i=p.datedToMillis(e);return null!=n&&null!=i&&[n.birthtimeMs,n.atimeMs,n.mtimeMs,n.ctimeMs].some(t=>Math.abs(t-i)<30*o.minuteMs)?v.tap(p.toDateTime(e,yield L(t)),e=>M.info("extractStatname()",{f:t.baseWithGrandparent,result:e})):void 0})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.LastExifVersionUpdatedAtMs=1562436664850,e.LastCuratorUpdatedAtMs=15561504e5,e.LastUpdatedAtMs=Math.max(e.LastExifVersionUpdatedAtMs,e.LastCuratorUpdatedAtMs)},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(145),o=n(39),a=n(21),u=n(58),l=n(2),c=n(10),d=n(29),h=n(227),f=n(69),p=n(25),m=n(14),g=n(1),y=n(90),v=n(7),w=n(0),b=n(141),S=n(12),P=n(124),M=n(13),x=n(19),E=n(64),_=n(202),k=n(71),T=n(16),O=n(46),D=n(6),F=n(70),C=n(62),I=n(91),A=n(125),L=n(287),R=n(288),N=n(165);e.start=Date.now();let j="";e.lastServiceName=function(){return j},e.StartupTimeoutMs=30*T.secondMs;e.Service=class{constructor(t){this.opts=t,this.errorRate=new y.Rate(2*T.minuteMs),this.exitted=!1,this._ready=new u.Latch,this.inputHandlers=new Map,this.onError=(t,e,n)=>{if(!p.isIgnorableError(n))if(p.isFatalError(n)&&(t=!0),this.errorRate.onEvent(),a.ending())this.logger.warn("onError(): We're already ending.",{fatal:t,context:e,error:n});else if(!t&&v.gt0(this.opts.maxErrorsPerMinute)&&this.errorRate.eventsPerMinute>this.opts.maxErrorsPerMinute&&(this.logger.error("Error rate is too high. Upgrading this error to fatal.",{context:e,error:n}),t=!0),this.logger.log(t?"error":"warn","propagating error",{context:e,error:n}),t){const t=e+D.mapOr(n,t=>": "+p.errorToS(t),()=>"");return this.exit(t,12)}},j=this.name=this.opts.name,S.Settings.logDir.addListener(()=>this.setupLogger()),this.logger=g.mkSafeLogger("Service("+this.name+")"),this.addDefaultInputHandlers(),l.thenOrTimeout(this.setup(),e.StartupTimeoutMs,()=>this.exit("setup timed out",13))}setupLogger(){g.setLoggerProcessName(this.name+"-"+r.pid,S.Settings.logDir.valueOrDefault)}get isDbService(){return b.DbServices.includes(this.name)}get isNoDbService(){return b.NoDbServices.includes(this.name)}get isMainService(){return this.name===b.ServiceNames.main}get isWelcomeService(){return b.WelcomeServices.includes(this.name)}get isDbRpcService(){return!this.isDbService&&!this.isNoDbService}get ready(){return this._ready.promise}setTitle(){const t=o.App.getName()+(this.name===b.ServiceNames.main?"":` ${this.name}`);w.Try(()=>r.title=t)}setup(){return i(this,void 0,void 0,function*(){try{if(yield P.readSystemSettings(),this.setTitle(),d.truthy(f.getEnv("PS_CRASH_"+this.name)))throw new Error("Requested crash by ENV."+p.FatalErrorFlag);C.setDbRpc(this.isDbRpcService),this.logger.info("setup()",Object.assign({version:E.version,argv:r.argv,arch:r.arch,platform:r.platform,versions:r.versions,settings:{logLevel:S.Settings.logLevel.valueOrDefault,httpPort:S.Settings.httpPort.valueOrDefault,rpcPort:S.Settings.rpcPort.valueOrDefault,libraryPath:S.Settings.libraryPath.valueOrDefault}},S.psenv())),_.NiceWorkPlanner.instance(),yield this.setupStdin(),this.isDbRpcService&&(yield this.setupDbRpc()),this.isDbService&&(yield F.thenOpt(A.Library.instance()).flatMap(t=>t.dbServer()),yield this.maybeWriteSystemSettings(),yield this.maybeWriteLibrarySettings(),this.logger.debug("wrote settings.")),yield this.setupErrorHandling(),this.logger.debug("set up error handling.");const t=this.exitted||a.ending();this.logger.debug("setup done.",{reject:t}),t?this._ready.reject():this._ready.resolve()}catch(t){return this._ready.reject(t),this.exit(M.ensureSuffix("Service.setup() failed: "+t,p.FatalErrorFlag),14)}})}maybeWriteSystemSettings(){return i(this,void 0,void 0,function*(){(yield O.notEqlAsync(E.version,P.systemSettingsVersion()))&&(yield P.writeSystemSettings())})}maybeWriteLibrarySettings(){return i(this,void 0,void 0,function*(){S.Settings.libraryPath.hasValue()&&(yield O.notEqlAsync(E.version,P.librarySettingsVersion()))&&(yield P.writeLibrarySettings())})}setupErrorHandling(){return i(this,void 0,void 0,function*(){R.installSentry(this),r.on("unhandledRejection",t=>this.onError(!0,"unhandledRejection",t)),r.on("uncaughtException",t=>this.onError(!0,"uncaughtException",t)),m.onFatal((t,e)=>this.onError(!0,t,e)),m.onNonFatal((t,e)=>this.onError(!1,"on(nonfatal): "+t,e)),m.eventEmitter.on("error",t=>{this.onError(!1,"on(error):",t)}),r.on("SIGINT",()=>this.exit("SIGINT",0)),r.on("SIGTERM",()=>this.exit("SIGTERM",0)),r.on("disconnect",()=>this.exit("disconnect",0)),r.stdin.on("close",()=>this.exit("stdin.close",0)),r.stdin.on("error",t=>this.logger.warn("stdin.error: "+t)),r.stdin.on("disconnect",()=>this.exit("stdin.disconnect",0)),r.stdout.on("disconnect",()=>this.exit("stdout.disconnect",0)),r.stdout.on("error",t=>this.logger.warn("stdout.error: "+t)),r.stderr.on("disconnect",()=>this.exit("stderr.disconnect",0)),r.stderr.on("error",t=>this.logger.warn("stderr.error: "+t))})}setupStdin(){s.createInterface({input:r.stdin}).on("line",t=>this.onLine(x.toS(t)))}setupDbRpc(){return i(this,void 0,void 0,function*(){if(!this.isDbRpcService)return;const t=yield L.remoteLibraryPath();if(c.blank(t))throw new Error("Could not get libraryPath from remote");t!==S.Settings.libraryPath.value&&this.logger.error("Saved library path doesn't match db. Using remote.",{local:S.Settings.libraryPath.value,remote:t}),S.Settings.libraryPath.value=t})}exit(t,e){return i(this,void 0,void 0,function*(){if(!this.exitted){if(this.exitted=!0,this.logger.info("exit()",{status:e,reason:t,ending:a.ending()}),yield this.logger.flush(),m.emitBeforeExit(t,e),0!==e){const n={exit:!0,status:e,pid:r.pid,ppid:r.ppid};n.error=t,w.Try(()=>N.stdoutWrite(n,!1))}yield a.endEndables(),r.exit(e)}})}setInputHandler(t,e){this.inputHandlers.set(t.trim().toLowerCase(),e)}addDefaultInputHandlers(){this.setInputHandler("--version",()=>i(this,void 0,void 0,function*(){return N.stdoutWrite({version:E.version})})),this.setInputHandler("--quit",()=>this.exit("--quit from stdin",0)),this.setInputHandler(h.ChildServiceExitCommand,()=>this.exit(h.ChildServiceExitCommand+" from stdin",0)),this.setInputHandler("--pause",()=>(k.pause(),N.stdoutWrite({paused:k.isPaused()}))),this.setInputHandler("--resume",()=>(k.resume(),N.stdoutWrite({paused:k.isPaused()}))),this.setInputHandler("--status",()=>i(this,void 0,void 0,function*(){return N.stdoutWrite({healthChecks:yield I.healthChecks()})})),this.setInputHandler("--boom",m.emitBoom)}onLine(t){return i(this,void 0,void 0,function*(){if(this.logger.debug("onLine",t),t.trim().startsWith("--")){const e=t.split(" ",1)[0],n=this.inputHandlers.get(e);null==n?console.warn("unknown command "+t):yield n(t.substr(e.length).trim())}else try{yield w.map(this.opts.stdinReceiver,e=>e(t))}catch(e){this.logger.error("onLine(): failed to process",{line:t,error:e})}})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(9),r=n(15),s=n(38),o=n(67),a=n(7),u=n(2);e.PromiseTimer=class{constructor(){this.times=new Map}time(t,e,n){const i=Date.now();return u.thenTap(e(),e=>{const r=Date.now()-i;this.push(t,r),null!=n&&n(e,r)}).catch(t=>{throw null!=n&&n(t,Date.now()-i),t})}push(t,e){s.getOrSet(this.times,t,()=>new o.Average).push(e)}weightedAvg(t){return r.Opt(this.times.get(t)).map(t=>t.weightedAvg).get()}callCounts(){return[...this.times.entries()].reduce((t,[e,n])=>Object.assign({},t,{[e]:n.k}),{})}weightedAvgs(){return i.compactValues([...this.times.entries()].reduce((t,[e,n])=>Object.assign({},t,{[e]:a.mapFinite(n.weightedAvg,a.round)}),{}))}report(){return[...this.times.entries()].reduce((t,[e,n])=>Object.assign({},t,{[e]:{cnt:n.k,avgMs:a.mapFinite(n.avg,a.round),minMs:n.min,maxMs:n.max}}),{})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(22),r=n(4),s=n(48);let o=0;e.geopid=s.GeoRadix.encode(i.pid),e.uid=function(t=0){return e.geopid+"-"+s.GeoRadix.encode(++o,t)},e.parseUid=function(t){const e=r.compact(t.split("-").map(t=>s.GeoRadix.decode(t)));return 2===e.length?{pid:e[0],i:e[1]}:void 0}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(42),r=n(29),s=n(1),o=n(0),a=n(12),u=n(27),l=n(19),c=n(5),d=n(8),h=n(9),f=n(156),p=n(116),m=n(62),g=n(143),y=n(118),v=n(195),w=n(119),b=n(272);class S{static get $ctor(){return this.schema+"."+this.tableName}static logger(){return null==this._logger&&(this._logger=s.mkLogger(this.tableName)),this._logger}static query(){return g.knex(this.tableName)}static queryBy(t){return this.query().where(t)}static queryOneBy(t){return this.queryBy(t)}static dbr(t,e){return m.dbRpc()?p.dbr(t,e):t(this.dbLocal())}static dbLocal(){if(null==this.db)throw new Error("only supported on db-local processes");return new f.DbRequestLocal(this.db)}static txOp(t,e){const n=this;if(null==n.db)throw new Error("only supported on db-local processes");return y.tx(n.db,n.tableName+": "+t,()=>e(n.opsLocal()))}static txDb(t,e){const n=this;if(null==n.db)throw new Error("only supported on db-local processes");return y.tx(n.db,n.tableName+": "+t,()=>e(new f.DbRequestLocal(n.db)))}static ops(){return m.dbRpc()?b.ModelOpsRemote.forModel(this):w.ModelOpsLocal.forModel(this)}static opsLocal(){if(null==this.db)throw new Error("db isn't set: only supported on db-local processes");return w.ModelOpsLocal.forModel(this)}static opsRemote(){return m.assertDbRpc(),b.ModelOpsRemote.forModel(this)}static truncate(){if(a.isProd)throw new Error("rejecting attempt to truncate in prod");return this.dbr(t=>t.exec("DELETE FROM "+this.tableName))}$ops(){return this.class().ops()}class(){return this.constructor}$pk(){return l.toS(this.id)}$ucn(){return this[this.class().uniqueColumnName]}$tableName(){return this.class().tableName}$uid(){return`${this.$tableName()}(${o.orElse(this.id,this[this.class().uniqueColumnName])})`}logger(){return s.mkLogger(l.toS(this.valueOf()))}[i.inspect.custom](){return this.$toShallowJSON()}toString(){return this.$uid()}valueOf(){return this.$uid()}static fromJSON(t){return v.fromJSON(this,t)}static toJSON(t){return this.fromJSON(t).toJSON()}static toDbJSON(t,e){return this.fromJSON(t).$toDbJSON(e)}$toShallowJSON(){return this.$_toJSON(t=>t.valueOf(),r.truthy)}$toDbJSON(t){const e=this.$_toJSON(()=>void 0,r.boolToInt);return d.notBlank(t)?h.pick(e,...t):e}toJSON(){return this.$_toJSON(t=>t.valueOf(),r.truthy)}$_toJSON(t,e){const n=this.class();return o.mapFields(this,(i,r)=>{if(null!=r&&"function"!=typeof r)return null!=n.relations&&n.relations.has(i)?[i,t(r,n.relations.get(i),i)]:c.includes(n.booleanFields,i)?[i,e(r)]:[i,r]},{$ctor:n.$ctor})}insert(){return this.$beforeUpsert(),u.atap(this.class().ops().insert(this),t=>{v.assignFromJSON(this,t)})}upsert(){return u.atap(this.class().ops().upsertOne(this),t=>{const e=this.class().uniqueColumnName;if("id"!==e&&this[e]!==t[e])throw this.logger().error("unexpected upsert result",{self:this,upserted:t}),new Error("unexpected upsert result");v.assignFromJSON(this,t)})}$beforeUpsert(){}}S.schema="models",e.Model=S},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(1),r=n(0),s=n(117),o=i.mkLogger("DbRequestLocal");e.DbRequestLocal=class{constructor(t){this.db=t}exec(t){this.db.exec(s.toSqlQuery(t).sql)}prep(t){const e=s.toSqlQuery(t),n=this.db.prepare(e.sql);return r.mapOr(e.bindings,t=>n.bind(t),n)}run(t){return this.prep(t).run()}first(t){return this.prep(t).get()}all(t){const e=Date.now(),n=s.toSqlQuery(t),i=this.prep(n).all(),r=Date.now()-e;return r>10&&o.info("all() took a while",{elapsed:r,sq:n,result:i}),i}pluckfirst(t){return this.prep(t).pluck().get()}pluckall(t){return this.prep(t).pluck().all()}},e.DbMethods=["exec","run","first","all","pluckfirst","pluckall"]},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(17),s=n(7),o=n(14);function a(t){return null!=t&&i.notBlank(t.path)&&i.notBlank(t.op)&&s.within(0,100,t.pct)}e.isProgressEvt=a;const u="progress";e.emitProgressEvt=function(t){a(t)&&o.eventEmitter.emit(u,Object.assign({},t,{pct:r.sigFigs(r.clamp(0,100,t.pct),2)}))},e.onProgressEvt=function(t){o.eventEmitter.on(u,t)},e.removeProgressEvtListener=function(t){return o.eventEmitter.removeListener(u,t)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(214),s=n(42),o=n(8),a=n(16),u=n(17),l=n(18),c=n(77),d=n(2),h=n(11),f=n(14),p=n(1),m=n(7),g=n(215),y=new RegExp("^"+g.ipv4Re.source+"$");e.friendlyname=c.memoize(t=>i(this,void 0,void 0,function*(){const n=null==y.exec(t)?t:yield e.nslookup(t);return l.toS(n).toLowerCase().normalize()}),10*h.minuteMs,128);const v=/^(?:(?:localhost(?:\.?(?:localdomain\.?)?))|(?:127(?:\.\d{1,3}){3}))$/i;function w(t){return null!=v.exec(t)}function b(t){const e=t.split(".").map(t=>u.toInt(t)).filter(t=>m.within(0,255,t));return 4===e.length?e:void 0}e.isLoopback=w,e.octets=b;const S=s.promisify(r.reverse),P=s.promisify(r.resolve4),M=p.mkLogger("nslookup");e.nslookup=c.memoize(t=>i(this,void 0,void 0,function*(){try{const e=yield d.thenOrTimeout(()=>w(t)?t.startsWith("127.")?["localhost"]:["127.0.0.1"]:null!=b(t)?S(t):P(t),10*a.secondMs);if(null==e)return M.info("nslookup("+t+"): timeout"),t;const n=e.find(o.notBlank);return null==n?(M.warn("No name found for "+t),t):n}catch(e){return M.warn("Failed to look up "+t+", using name.",e),t}}),10*h.minuteMs,256),f.onClearCache(()=>e.nslookup.clear())},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(6),o=n(15),a=n(4),u=n(53),l=n(2),c=n(20),d=n(11),h=n(14),f=n(68),p=n(60),m=n(38),g=n(0),y=n(23),v=n(47),w=n(13),b=n(19),S=n(40),P=n(24);e.addRemoteVolumeInfoWin=function(t,e){return i(this,void 0,void 0,function*(){if(!y.isWin)throw new Error("wtf");return yield l.thenMap(s.orElse(e,()=>O()),e=>{const n=m.toMap(e,t=>[t.mountpoint,t]);t.forEach(t=>{g.map(n.get(t.mountpoint),e=>{t.remote=!0,t.remoteHost=e.host,t.remoteShare=e.share,t.remoteOK=e.ok})})}),t})};const M=["LocalName","RemoteName","Status"],x=["NETUSE","get",M.join(",")],E=/^\\\\(.+?)\\(.+)$/,_=/^[a-z]:\\?$/i;function k(t){if(!r.blank(t))return o.Opt(t).flatMap(t=>E.exec(t)).map(t=>({host:t[1],share:t[2]})).orElse(()=>o.Opt(t).flatMap(t=>g.Try(()=>new URL(t))).filter(t=>r.notBlank(t.hostname)).map(t=>({host:t.hostname,share:o.Opt(t.pathname).filter(r.notBlank).getOrElse(()=>"/")}))).get()}function T(){return i(this,void 0,void 0,function*(){const t=p.wmic(),e=yield c.stdout(t,x,{timeout:15*d.secondMs}),n=f.parseFixed(M,e);return a.compact(n.map(t=>g.map(E.exec(b.toS(t.RemoteName)),e=>g.map(_.exec(b.toS(t.LocalName)),n=>({mountpoint:w.ensureSuffix(n[0],"\\"),host:e[1],share:e[2],ok:"OK"===t.Status})))))})}e.NetInfoCmd="Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status",e.parseRemoteName=k,e._netInfoWinWmic=T;const O=u.keyedLazy("netInfoWin",S.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){const t=yield v.PowerShell.instance().executeJsonToA("Get-WmiObject Win32_NetworkConnection | Select-Object -Property LocalName,RemoteName,ConnectionState,Status");return null==t?T():a.compact(t.filter(t=>r.notBlank(t.LocalName)).map(t=>g.map(k(t.RemoteName),({host:e,share:n})=>g.map(_.exec(b.toS(t.LocalName)),i=>({mountpoint:w.ensureSuffix(i[0],"\\"),host:e,share:n,ok:"OK"===t.Status&&"Connected"===t.ConnectionState})))))})},{maxRetries:2,timeoutMs:P.cmdTimeoutMs,priorResultTtlMs:P.longTtlMs});h.onClearCache(()=>O.clear())},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(16),s=n(17),o=n(15),a=n(20),u=n(23),l=n(47);e.hidden=function(t){return!!t.base.startsWith(".")||(u.isWin?function(t){return i(this,void 0,void 0,function*(){const e=yield l.PowerShell.instance().executeJsonToA(`Get-Item -Force -LiteralPath '${t.nativePath}' -ErrorAction SilentlyContinue | Select-Object -Property Name, Mode`);return o.Opt(e).flatMap(t=>t[0]).flatMap(t=>t.Mode).flatMap(t=>t.includes("h")||t.includes("s")).getOrElse(()=>!1)})}(t):!!u.isMac&&function(t){return i(this,void 0,void 0,function*(){try{const e=yield a.stdout("stat",["-f","%f",t.nativePath],{timeout:10*r.secondMs}),n=s.toInt(e);return null!=n&&(32768&n)>0}catch(t){return!1}})}(t))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(39),o=n(4),a=n(3),u=n(2),l=n(10),c=n(69),d=n(224),h=n(1),f=n(23),p=n(225),m=n(12),g=n(40),y=n(160),v=n(148),w=n(140),b=n(28),S=n(226);function P(t){const e=t.nativePath.toLowerCase().normalize();return v.pathIsNeverIgnored(t.nativePath)||v.pathIsNeverIgnored(e)?{pathIsNeverIgnored:()=>!1}:Object.assign({},x(t.nativePath),{snapDirectory:()=>i(this,void 0,void 0,function*(){return f.isLinux&&(yield S.ignorableSnapDir.apply(t))}),noMedia:()=>w.hasNoMedia(t),hidden:()=>y.hidden(t),mountpoint:()=>i(this,void 0,void 0,function*(){return u.thenMapOr(g.mountpoints(),e=>e.includes(t.nativePath),()=>!1)})})}e.ignorablePredicates=function(t){return i(this,void 0,void 0,function*(){return(yield t.isDirectory())?P(t):x(t.nativePath)})},e.ignorableFile=function(t){return E(t.nativePath)},e.ignorableDirectory=function(t){return i(this,void 0,void 0,function*(){return d.orLoggedAsync([P(t)],h.mkLogger("ignorableDirectory("+t.nativePath+")"))})},e.ignorableDirectoryPredicates=P;const M=a.lazy(()=>new _);function x(t){return M().ignorablePathPredicates(t)}function E(t){return M().ignorablePath(t)}e.ignorablePathPredicates=x,e.ignorablePath=E;class _{constructor(t=m.isTest){this.ignorableRootDirectories=new Set(["dev","etc","initrd","lib","lost+found","proc","sbin","sys","tmp","var","System","Dell","Intel","Microsoft","NVIDIA","temp","Windows.old","Windows"].map(t=>t.toLowerCase().normalize())),this.ignorableDirectories=new Set(["#recycle","@Recycle","@eaDir","@SynoResource","$Recycle.Bin","Application Data","Application Support","Applications","cache","caches","com.apple.TimeMachine.localsnapshots","cpan","cygwin","cygwin64","DefinitelyTyped","Desktop DB","Desktop DF","DisplayDriver","ehthumbs.db","lost+found","Network Trash Folder","node_modules","Program Files (x86)","Program Files","ProgramData","steamapps","spotifycache","System32","System Volume Information","Temporary Items","tmp","iTunes","iTunes Media","Thumbnails","Thumbs.db","Trash","Windows10Upgrade"].map(t=>t.toLowerCase().normalize())),this.ignorableDirectoryPatterns=[/.sparsebundle\/bands(\/|$)/i,/\/.*?\.photolibrary\/(?!Masters?\/)/i,/\/ImageMagick[\d\.-]*(\/|$)/i,/\/Install OS X .+\.app(\/|$)/i,/Smart Previews\.lrdata(\/|$)/i,/\/MinGW-.+(\/|$)/i,/\/msys[\d\.-]*(\/|$)/i,/\/Python[\d\.-]*(amd64|x64)?(\/|$)/i,/\/Ruby[\d\.-]+(amd64|x64)?(\/|$)/i],this.systemDirs=o.uniq(l.compactBlanks([s.App.appData(),c.getEnv("APPDATA"),c.getEnv("SYSTEMROOT"),c.getEnv("ProgramFiles"),c.getEnv("ProgramFiles(x86)")]).map(t=>t.toLowerCase().normalize())),this.ignorableSubdirs=new p.SetSet,f.isLinux&&(this.ignorableRootDirectories.add("run"),this.ignorableRootDirectories.add("snap")),this.addIgnorableSubdirs("nix",["store"]);const e=["bin","etc","games","include","lib","lib32","local","locale","man","sbin","share","src"];this.addIgnorableSubdirs("usr",e),this.addIgnorableSubdirs("local",e),this.addIgnorableSubdirs("lib",["firmware","modules","systemd","udev","x86_64-linux-gnu"]),this.addIgnorableSubdirs("opt",["google","x11",...e]),this.addIgnorableSubdirs("var",["cache","crash","lib","local","log","snap","spool","tmp"]),this.addIgnorableSubdirs("library",["Application Support","Audio","Bundles","Caches","ColorPickers","ColorSync","Components","Compositions","Contextual Menu Items","CoreAnalytics","CoreMediaIO","Desktop Pictures","Developer","Dictionaries","DirectoryServices","Documentation","Extensions","Filesystems","Fonts","Frameworks","GPUBundles","Graphics","Image Capture","Input Methods","Internet Plug-Ins","iTunes","Java","Keyboard Layouts","Keychains","LaunchAgents","LaunchDaemons","Logs","Messages","MessageTracer","Modem Scripts","OpenDirectory","PDF Services","Perl","PreferencePanes","Preferences","Printers","PrivilegedHelperTools","Python","QuickLook","QuickTime","Receipts","Ruby","Sandbox","Screen Savers","ScriptingAdditions","Scripts","Security","Speech","Spotlight","StagedExtensions","StartupItems","SystemProfiler","Updates","User Pictures","Video","WebServer","Widgets"]),this.addIgnorableSubdirs("go",["bin","blog","doc","lib","misc","pkg","src","test"]);const n=["bin","eg","etc","html","lib","site"];this.addIgnorableSubdirs("Perl",n),this.addIgnorableSubdirs("Perl64",n),this.addIgnorableSubdirs("sdk",["build-tools","emulator","extras","patcher","platforms","platform-tools","sources","tools"]),this.addIgnorableSubdirs("i18n",["chs","cht","deu","esn","fra","hun","ita","jpn","kor","ptb","rus","trk"]),this.addIgnorableSubdirs("test",["fixtures"]),this.addIgnorableSubdirs("data",["$of"]),this.addIgnorableSubdirs("system",["library"]),this.addIgnorableSubdirs("contents",["frameworks","plugins","resources","sharedsupport"]),this.addIgnorableSubdirs("pg",["pgsql"]),t||(this.addIgnorableSubdirs("appdata",["local","locallow","roaming"]),this.addIgnorableSubdirs(c.getEnv("APPDATA"),["local","locallow","roaming"])),t&&(this.ignorableRootDirectories.delete("tmp"),this.ignorableDirectories.delete("tmp"),this.ignorableRootDirectories.delete("temp"),this.ignorableRootDirectories.delete("var"))}addIgnorableSubdirs(t,e){if(r.blank(t))return;const n=t.toLowerCase().normalize();l.compactBlanks(e).forEach(t=>this.ignorableSubdirs.add(n,t.toLowerCase().normalize()))}ignorablePathPredicates(t){const e=v.pathIsNeverIgnoredPredicate(t);if(null!=e)return e;const n=t.toLowerCase().normalize(),i=l.compactBlanks(b.pathnames(n));return{hiddenPosix:()=>i.some(t=>t.startsWith(".")),systemDir:()=>this.systemDirs.some(t=>n.startsWith(t)),ignorableRoot:()=>this.ignorableRootDirectories.has(i[0]),ignorableDirectory:()=>i.some(t=>this.ignorableDirectories.has(t)),ignorablePath:()=>this.ignorableSubdirs.has(i),ignorablePattern:()=>{const e=b.native2posix(t);return this.ignorableDirectoryPatterns.some(t=>t.test(e))}}}ignorablePath(t){return d.orLogged([this.ignorablePathPredicates(t)],h.mkLogger("FsAttrs("+t+")"))}}e.Ignorable=_},function(t,e,n){"use strict";function i(t,e,n=.5){return(1-n)*t+n*e}Object.defineProperty(e,"__esModule",{value:!0}),e.lerp=i,e.lerp2d=function(t,e,n){const r=e.x-t.x,s=(n-t.x)/r;return i(t.y,e.y,s)},e.lerp2d_=function(t,e,n){return(t.y*(e.x-n)+e.y*(n-t.x))/(e.x-t.x)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(6),o=n(59),a=n(2),u=n(176),l=n(1),c=n(0),d=n(31),h=n(49),f=n(27),p=n(19),m=n(56),g=n(168),y=n(75),v=n(149),w=n(86),b=l.mkLogger("SharpReadable");function S(t,e,n,r){return i(this,void 0,void 0,function*(){if("image/jpeg"!==e.mimetype||0===e.rotation)return c.map(e[n],()=>a.thenMap(M(t,n),e=>a.thenMap(d.dimensions(e),i=>f.tap(m.ltBoth(r,i)?e:void 0,s=>{b.debug("imgFromExif()",{src:t.baseWithGrandparent,img:e.nativePath,tag:n,dim:i,minDim:r,result:p.toS(s)})}))));b.debug("Rotated JPEG, don't trust the thumbnail",{src:t,rotated:e.rotation})})}function P(t,e,n){return i(this,void 0,void 0,function*(){if(!(yield w.isVlcSupported())||!w.vlcSupportedMimeType(e))return;const i=yield y.tmpImgFile(t,"frame",".jpg");if(null==i)throw new Error("Cannot make tmpImgFile");const r=yield t.mtimeMs();if(null==r)return void b.warn("sharpReadable("+t+"): null mtime");const s=yield i.stat();return null!=s&&s.mtimeMs>r&&s.size>5*o.KB&&(yield a.resolved(v.validJpeg(i)))?(b.info("sharpReadable("+t+"): prior dest, "+i+" seems reasonable"),i):(yield i.unlink("debug"),a.thenAnd(w.vlcFrame(t,i,n),()=>i))})}function M(t,e){return a.thenMap(y.tmpImgFile(t,e,".jpg"),n=>n.applyIfEmpty(n=>i(this,void 0,void 0,function*(){return d.extractBinaryTag(e,t.nativePath,n.nativePath)})))}e.imgFromExif=S,e.sharpReadable=function(t,e){return i(this,void 0,void 0,function*(){const n=yield d.readTags(t.nativePath),o=c.map(n,t=>t.mimetype);if(null==n||r.blank(o))throw new Error(t+" is not supported (missing mimetype)");const l=[];null!=e&&0===n.rotation&&l.push(...["ThumbnailImage","PhotoshopThumbnail","PreviewImage","JpgFromRaw"].map(i=>()=>S(t,n,i,e))),h.isSharpMimetype(o)&&l.push(()=>i(this,void 0,void 0,function*(){return t})),u.dcrawSupportedMimeTypes.has(o)&&l.push(()=>y.readableToFile(t,"dcraw",".tiff",()=>u.dcraw(t))),l.push(()=>P(t,o)),l.push(()=>i(this,void 0,void 0,function*(){return g.ffmpegSupportedMimeType(o)&&(yield g.isFFmpegSupported())?y.readableToFile(t,"frame",".jpg",()=>g.ffmpegFrame(t)):void 0})),null!=n.JpgFromRaw&&l.push(()=>M(t,"JpgFromRaw")),null!=n.PreviewImage&&l.push(()=>M(t,"PreviewImage"));const f=[],p=yield a.firstResolvedDefinedPromise(l,e=>{b.warn("strategy failed for "+t+": "+e),f.push(e)});if(null==p)throw s.orElse(f[0],new Error("Cannot read "+t));return p})},e.extractVideoFrame=P,e.extractImageForThumbs=M},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(2);e.emitSafely=function(t,e,n,o=1e3){return i(this,void 0,void 0,function*(){const i=yield s.until(()=>r.isNotEmpty(t.listeners(e)),o);return i&&t.emit(e,n),i})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(22);e.stdoutWrite=function(t,n=!0){i.stdout.write(JSON.stringify(t)+"\n"),n&&i.stdout.write(e.readyStr+"\n")},e.readyStr=JSON.stringify({ready:!0})},,function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(8),o=n(16),a=n(208),u=n(6),l=n(15),c=n(37),d=n(21),h=n(3),f=n(2),p=n(51),m=n(25),g=n(14),y=n(88),v=n(54),w=n(1),b=n(209),S=n(90),P=n(0),M=n(81),x=n(20);e.mkBasicWatchedChild=function(t,e,n){const i=new E({name:r.compact([t,...e]).join(" "),childFactory:()=>x.spawn(t,e,30*o.minuteMs),onError:()=>!0,ignoreStopErrors:!0,onStdout:a.debounce(()=>n(),1.5*o.secondMs),onRestartError:()=>c.delay(b.randomInt(o.secondMs,15*o.secondMs)).then(()=>{i.restart()})});return i};class E{constructor(t){this.logger=h.lazy(()=>w.mkLogger("WatchedChild("+r.compact([this.name,this.pid]).join(":")+")")),this.startRate=new S.Rate(2*o.minuteMs),this.mutex=new p.Promises,this._ended=!1,this.onError=(t,e)=>{const n={src:t,errToS:m.maybeErrorToS(e)};if(this.logger().info("onError()",n),!this._ended&&!m.isIgnorableError(e)&&this.opts.onError(t,e)){const i=m.asError(e);return g.emitNonFatal(this.name+":"+t,i),this.logger().warn("onError returned true, restarting",n),this.restart(this.name+":"+t,i)}},this.name=t.name,this.opts=Object.assign({dataSep:"\n",maxErrorsPerMinute:3,endTimeoutMs:10*o.secondMs,endableRank:d.EndableRanks.first,exitCommand:"",restartOnExit:!0},t),d.addEndable(this.opts.endableRank,this),this.restart()}get ended(){return this._ended}end(){return i(this,void 0,void 0,function*(){return this._ended=!0,this.stop()})}get proc(){return this.cp}get pid(){return u.map(this.cp,t=>t.pid)}get msSinceLastStart(){return this.startRate.msSinceLastEvent}running(){return u.mapOr(this.pid,t=>M.pidExists(t),()=>i(this,void 0,void 0,function*(){return!1}))}notRunning(){return f.thenNot(this.running())}stop(){return i(this,void 0,void 0,function*(){const t=this.cp;return this.cp=void 0,null==t||(this.logger().info("stop()"),this.stopChild(t))})}stopChild(t){return i(this,void 0,void 0,function*(){return yield l.Opt(this.opts.exitCommand).filter(s.notBlank).flatMap(e=>l.Opt(t).flatMap(t=>t.stdin).filter(t=>t.writable).forEach(t=>P.Try(()=>t.write(e+"\n"))).map(v.end).get()),x.endProcess(t,this.opts.endTimeoutMs)})}restartIfStopped(){return i(this,void 0,void 0,function*(){return!(yield this.notRunning())||this.restart()})}restart(t,e){return i(this,void 0,void 0,function*(){return this.mutex.maybeRun(`WatchedChild(${this.name}).restart`,()=>i(this,void 0,void 0,function*(){if(yield this.stop(),this._ended)return!1;if(this.startRate.eventsPerMinute>this.opts.maxErrorsPerMinute)return this.logger().warn("Cannot restart, error/restart rate is too high.",{errorsPerMinute:this.startRate.eventsPerMinute,msSinceLastStart:this.startRate.msSinceLastEvent}),u.map(this.opts.onRestartError,n=>n(t,e)),!1;this.logger().info("restart()",{currentPid:this.pid,startRate:this.startRate,maxErrorsPerMinute:this.opts.maxErrorsPerMinute}),this.startRate.onEvent();const n=this.cp;if(null!=n&&!0!==(yield this.stopChild(n))&&(this.logger().info("restart(): failed to stop prior child",{prior:n}),!this.opts.ignoreStopErrors))return u.map(this.opts.onRestartError,n=>n(t,e)),!1;const i=this.cp=yield this.opts.childFactory();this.logger.clear();const r="cp("+i.pid+")";return[{o:i,desc:""},{o:i.stdin,desc:".stdin"},{o:i.stdout,desc:".stdout"},{o:i.stderr,desc:".stderr"}].forEach(({o:t,desc:e})=>{u.map(t,t=>t.on("error",t=>this.onError(r+e+".on(error)",t)))}),this.cp.stderr.on("data",t=>this.onError(r+".stderr.on(data)",t)),this.cp.on("exit",(t,e)=>{this.logger().info("onExit",{code:t,signal:e}),this.opts.restartOnExit?this.restart():(this.logger().info("onExit(): this.opts.restartOnExit is false, so we're done."),this.end())}),y.onDataChunked(this.cp.stdout,this.opts.dataSep,t=>{this.logger().debug("onDataChunked()",t),this.opts.onStdout(t)}),this.logger().info("restart(): spawned pid "+this.pid),!0}))})}}e.WatchedChild=E},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(16),o=n(6),a=n(17),u=n(15),l=n(18),c=n(44),d=n(36),h=n(3),f=n(2),p=n(20),m=n(164),g=n(1),y=n(7),v=n(0),w=n(12),b=n(31),S=n(24),P=n(75),M=n(93),x=g.mkLogger("ffmpeg"),E=/ffmpeg version (\S+)/i;function _(t){return i(this,void 0,void 0,function*(){return!!(yield e.isFFmpegSupported())&&f.thenMapOr(b.mimetype(t),k,()=>!1)})}function k(t){return l.toS(t).startsWith("video/")}function T(t,n=.3){return i(this,void 0,void 0,function*(){const i=yield b.readTags(t);return null==i?[]:u.Opt(a.toFloat(i.PosterTime)).filter(t=>0!==t).orElse(()=>u.Opt(a.toFloat(i.Duration)).filter(t=>0!==t).map(t=>Math.min(Math.round(t*n),e.MaxSS)).get()).map(t=>["-ss",t.toFixed()]).getOrElse(()=>[])})}e.ffmpegVersion=h.lazy(()=>i(this,void 0,void 0,function*(){try{const t=yield p.stdoutResult(w.Settings.ffmpegPath.valueOrDefault,["-version"],{timeout:S.cmdTimeoutMs,ignoreStderr:!0});return 0===t.code?o.map(E.exec(t.result),t=>t[1]):void 0}catch(t){return}})),e.isFFmpegSupported=h.lazy(()=>i(this,void 0,void 0,function*(){return r.notBlank(yield e.ffmpegVersion())})),e.ffmpegSupportedFile=_,e.ffmpegSupportedMimeType=k,e.MaxSS=10,e.ssFlag=T,e.ffmpegFrame=function(t){return i(this,void 0,void 0,function*(){if(!(yield _(t)))throw new Error(t+" is not supported");const e=s.minuteMs,n=yield p.execFile(yield w.Settings.ffmpegPath.valueOrDefault,["-loglevel","fatal","-i",t.nativePath,"-vframes","1",...yield T(t),"-f","singlejpeg","pipe:"],e,{timeout:e,maxBuffer:100*y.MiB}),r=e=>i(this,void 0,void 0,function*(){(yield m.emitSafely(n.stdout,"error","Problem from "+t+": "+e))||x.error("No listeners for error when reading "+t,e),n.kill("SIGINT")});return n.on("error",r),n.stderr.on("data",r),n.stdout})};const O=new c.TTLMap(10*s.minuteMs);e.transcode=function(t,e="mp4"){return O.getOrSet(t.nativePath+":"+e,()=>(function(t,e="mp4"){return i(this,void 0,void 0,function*(){const n=Date.now(),r=yield P.tmpImgFile(t,"vid",e);if(!(yield f.resolved(F(r))))return r;yield r.unlink();const s=r.wip("wip-");yield s.unlink();const o=["-loglevel","fatal","-i",t.nativePath,s.nativePath];x.info("transcode()",{args:o});const a=yield M.syncFileTimeoutForFile(t);if(null==a)throw new Error("Cannot transcode "+t+": timeout calc failed.");const u=yield p.execFile(w.Settings.ffmpegPath.valueOrDefault,o,a),l=new d.Deferred(`ffmpeg._transcode(${t})`),c=e=>i(this,void 0,void 0,function*(){x.warn("onErr("+t+"): "+e),l.reject(e),v.Try(()=>u.kill("SIGINT"))});return u.on("error",c),u.stderr.on("data",c),u.on("exit",(r,o)=>i(this,void 0,void 0,function*(){if(x.info("transcode()",{elapsedMs:Date.now()-n,code:r,signal:o,src:t,ext:e}),l.pending)if(0!==r)l.reject("ffmpeg failed with code "+r);else{const t=yield s.unwip("wip-");null==t?l.reject(new Error("null unwip for "+s)):l.resolve(t)}})),l.promise})})(t,e))};const D=[/invalid nal/i,/invalid data found/i];function F(t){return i(this,void 0,void 0,function*(){if(yield t.notExists())throw new Error(t+" doesn't exist");if(null==(yield t.size()))throw new Error("cannot read "+t);const e=yield p.execFile(w.Settings.ffmpegPath.valueOrDefault,["-v","error","-i",t.nativePath,"-f","null","-"],1*s.minuteMs),n=new d.Deferred(`ffmpegValidVideo(${t})`),r=r=>i(this,void 0,void 0,function*(){const i=l.toS(r);D.some(t=>null!=t.exec(i))?(x.warn("validVideo.onErr("+t+"): "+r),n.reject(r),v.Try(()=>e.kill("SIGINT"))):x.info("validVideo.onErr("+t+"): ignorable "+r)});return e.on("error",r),e.stdout.on("data",r),e.stderr.on("data",r),e.on("exit",t=>i(this,void 0,void 0,function*(){0===t?n.resolve():n.reject("non-zero exit code "+t)})),n.promise})}e.ffmpegValidVideo=F},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(126),s=n(44),o=n(2),a=n(11),u=n(7),l=n(31),c=n(49),d=new s.TTLMap(2*a.minuteMs);e.dimensions=function(t){return d.getOrSet(t.nativePath,()=>(function(t){return o.firstDefinedPromise(()=>o.thenMap(l.cachedTags(t),t=>t.dimensions),()=>(function(t){return i(this,void 0,void 0,function*(){return c.isSharpExt(t.ext)?o.thenMap(function(t){return r(t.nativePath).metadata()}(t),t=>{const e=[t.width,t.height];u.gt0(t.orientation)&&[5,6,7,8].includes(t.orientation)&&e.reverse();const[n,i]=e;return u.gt0(n)&&u.gt0(i)?{width:n,height:i}:void 0}):void 0})})(t),()=>l.dimensions(t.nativePath))})(t))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(102),s=n(146),o=n(6),a=n(17),u=n(9),l=n(18);class c{constructor(t){a.isNumber(t)?(this.assetId=t,this.query=""):(this.assetId=t.id,this.query="?ts="+t.ts)}static onNewPage(){this.pageImageCount=0}assetUrl(){return`/asset/${this.assetId}${this.query}`}linkAttrs(){return{href:this.assetUrl()}}imgLink(t,e){return`/img/${this.assetId}/${t}/${e}${this.query}`}imgActualLink(t){return`/img/${i.compact([this.assetId,t]).join("/")}/actual${this.query}`}videoLink(t){return`/video/${this.assetId}-${t}${this.query}`}sqImgAttrs(t){return this.imgAttrs("sq",s.SqWidths,t)}imgAttrs(t,e,n,i){const s=Math.min(...e),a={width:l.toS(s)},h=this.imgLink(t,s);c.pageImageCount++,(n=o.orElse(n,()=>c.pageImageCount>64))?(a.src="/images/clear-256.png",a["data-src"]=h):a.src=h,t===r.ReducerNames.sq&&(a.sizes="(min-width: 900px) 12.5vw, (min-width: 540px) 25vw, 50vw",a.height=l.toS(s));const f=e.map(e=>d(this.imgLink(t,e),e));u.map(i,t=>f.push(d(this.imgActualLink(),t.width)));const p=f.join(",");return n?a["data-srcSet"]=p:a.srcSet=p,a}}function d(t,e){return t+" "+e+"w"}c.pageImageCount=0,e.AssetUrls=c},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(16),o=n(6),a=n(9),u=n(70),l=n(4),c=n(3),d=n(2),h=n(10),f=n(20),p=n(23),m=n(47),g=n(13);function y(t=r.env){return o.firstDefined(t.LC_ALL,t.LC_MESSAGES,t.LANG,t.LANGUAGE)}e.defaultLocale="en",e.locale=c.lazy(()=>i(this,void 0,void 0,function*(){return w(yield d.firstDefinedPromise(()=>y(),()=>p.isWin?b():void 0,()=>p.isMac?P():void 0,()=>p.isPosix?x():void 0))}));const v=/([a-z]+)(?:(?:[_-])([a-z]+))?/i;function w(t){if(h.blank(t)||g.equalsIgnoreCase("c",t)||g.equalsIgnoreCase("posix",t))return e.defaultLocale;{const n=v.exec(t);return null==n?e.defaultLocale:l.compact([n[1],n[2]]).join("-")}}function b(){return d.thenMap(m.PowerShell.instance().executeJson("GET-WinSystemLocale | Select-Object -Property Name"),t=>t.Name)}e.lc2locale=w,e.winLocale=b;const S={timeout:10*s.secondMs};function P(){return u.thenOpt(f.stdout("defaults",["read","-globalDomain","AppleLocale"],S)).flatMap(w).get()}e.macLocale=P;const M=/^([a-z_]+)\s*=\s*"(.+)"$/i;function x(){return u.thenOpt(f.stdout("locale",[],S)).flatMap(t=>t.split("\n").map(t=>o.map(t.match(M),t=>[t[1],t[2]]))).flatMap(a.fromEntries).flatMap(y).flatMap(w).get()}e.posixLocale=x},,function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(43),s=n(99),o=n(30),a=n(5),u=n(6),l=n(2),c=n(13),d=n(28);class h{constructor(t,e){this.dir=t,this.nativePath=o.join(this.dir,e.name),this.ext=d.extname2(e.name),this.base=e.name,this.name=c.stripSuffix(this.base,this.ext),this._isFile=e.isFile(),this._isDirectory=e.isDirectory(),this._isSymbolicLink=e.isSymbolicLink()}static for(t){return i(this,void 0,void 0,function*(){const e=d.parse(t);return s.stat(t).then(t=>new h(e.dir,{name:e.base,isFile:t.isFile.bind(t),isDirectory:t.isDirectory.bind(t),isSymbolicLink:t.isSymbolicLink.bind(t)})).catch(()=>void 0)})}toString(){return this.nativePath}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}parent(){const t=d.parse(this.dir);return t.dir===this.dir?this:new h(t.dir,{name:t.base,isFile:function(){return!1},isDirectory:function(){return!0},isSymbolicLink:function(){return!1}})}children(){return this.isDirectory()?new Promise((t,e)=>{r.readdir(this.nativePath,{withFileTypes:!0},(n,i)=>{null!=n?e(n):t(u.map(i,t=>a.sortBy(t,t=>t.name.toLowerCase().normalize()).map(t=>new h(this.nativePath,t))))})}):void 0}stat(){return s.stat(this.nativePath).catch(()=>void 0)}size(){return i(this,void 0,void 0,function*(){return l.thenMap(this.stat(),t=>t.size)})}mtimeMs(){return i(this,void 0,void 0,function*(){return l.thenMap(this.stat(),t=>t.mtimeMs)})}}e.DirectoryEntry=h},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(43),s=n(35),o=n(6),a=n(21),u=n(51),l=n(50),c=n(11),d=n(54),h=n(12),f=n(134),p=n(89),m=n(120);e.CaptureLogger=class{constructor(){this.logEntries=[]}log(t,e,n,i){this.logEntries.push({timestamp:Date.now(),level:t,context:e,msg:n,meta:i})}enabled(){return!0}close(){}flush(){return i(this,void 0,void 0,function*(){})}};e.LogWriter=class{constructor(t,e,n={}){this.logdir=t,this.prefix=e,this.ended=!1,this.mutex=new u.Promises,this._linesSinceRotate=0,this.pendingWrites=[],this._startIndex=0,this.maybeFlush=()=>{this.mutex.maybeRun("maybeFlush",()=>this._flush())},this.shouldRotate=()=>null==this._stream||this._linesSinceRotate>=this.opts.maxLinesPerFile,this.flush=()=>this.mutex.serial("flush",()=>this._flush()),this.name="GzLogWriter("+t+")",this.opts=Object.assign({filter:p.logFilter(),maxLinesPerFile:25e4,logFormatter:new m.ColoredLogFormatter({prefix:e}),errorLogger:f.ConsoleLogger.instance(),flushEveryMs:500},n),this.flushInterval=l.setUnrefInterval(()=>this.maybeFlush(),this.opts.flushEveryMs),a.addLoggerEndable(this)}enabled(t,e){return this.opts.filter.enabled(t,e)}log(t,e,n,i){this.opts.filter.enabled(t,e)&&(this.ended&&p.levelIndex(t)<=1?this.opts.errorLogger.log(t,e,n,i):this.pendingWrites.push(this.opts.logFormatter.format(t,e,n,i)+"\n"))}end(){return i(this,void 0,void 0,function*(){return this.ended=!0,o.map(this.flushInterval,s.clearInterval),this.flushInterval=void 0,this.close()})}close(){return i(this,void 0,void 0,function*(){return yield this.flush(),this.mutex.serial("close",()=>this._closeCurrent())})}_flush(){return i(this,void 0,void 0,function*(){const t=[...this.pendingWrites];for(this.pendingWrites.length=0;t.length>0;){this.shouldRotate()&&(yield this._rotate());const e=this._stream;if(null==e)return void this.opts.errorLogger.log("error","LogWriter.flush()","this._rotate() returned an empty stream");const n=this.opts.maxLinesPerFile-this._linesSinceRotate,i=t.splice(0,n);this._linesSinceRotate+=i.length,e.write(i.join(""))}})}errback(t){return e=>this.opts.errorLogger.log("error","Caught error from "+t,e)}_rotate(){return i(this,void 0,void 0,function*(){yield this._closeCurrent(),this._currentFile=yield this.logdir.join(c.datestamp(),this.prefix+".log").ensureNew({emptyIsNew:!0,startIndex:++this._startIndex,requireNumber:!0,leftPad:3}),this._stream=r.createWriteStream(this._currentFile.nativePath).on("error",this.errback("file write stream"))})}_closeCurrent(){return i(this,void 0,void 0,function*(){yield o.map(this._stream,t=>d.end(t)),this._stream=void 0,this._linesSinceRotate=0,h.Settings.logCompression.valueOrDefault&&(yield o.map(this._currentFile,t=>t.gzip())),this._currentFile=void 0})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(45),r=n(25),s=n(254),o=n(121),a=n(16),u=n(6);e.libraryLock=function(t,e){return u.map(o.libraryDataDir(t),t=>new s.FsFileLock({hostname:i.hostname(),lockfileJson:t.join("opened-by.json"),staleMs:a.minuteMs,watchDepth:3,onLockLoss:e}))},e.LostLibraryLockMsg="lost library lock "+r.FatalErrorFlag},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(43),s=n(16),o=n(59),a=n(36),u=n(2),l=n(20),c=n(25),d=n(164),h=n(104),f=n(54),p=n(122),m=n(1),g=n(31),y=n(136),v=n(75);e.dcrawSupportedMimeTypes=new Set(["image/x-adobe-dng","image/x-canon-cr2","image/x-canon-crw","image/x-fuji-raf","image/x-kodak-dcr","image/x-kodak-k25","image/x-kodak-kdc","image/x-minolta-mrw","image/x-nikon-nef","image/x-nikon-nrw","image/x-olympus-orf","image/x-panasonic-raw","image/x-panasonic-rw2","image/x-pentax-pef","image/x-samsung-srw","image/x-sigma-x3f","image/x-sony-arw","image/x-sony-sr2","image/x-sony-srf"]);const w=m.mkLogger("dcraw");function b(t){return g.isMimetype(t.nativePath,e.dcrawSupportedMimeTypes)}e.rawToTiff=function(t,e,n){return i(this,void 0,void 0,function*(){try{const i=yield P(t,n);if(null==i)return;const s=yield u.firstDefinedPromise(()=>e,()=>v.tmpImgFile(t,"dcraw",".tiff")),o=new a.Deferred(`rawToTiff(${t})`),l=r.createWriteStream(s.nativePath);return l.on("finish",()=>o.resolve(s)),yield f.pipelinePromise([i,l]),o.promise}catch(e){return void w.warn("Failed to read "+t.nativePath,e)}})},e.dcrawSupported=b;const S=y.ImageSize.UHD5k.megapixels();function P(t,e=S){return i(this,void 0,void 0,function*(){if(!(yield b(t)))throw new Error(t+" is unsupported");const n=Date.now(),r=yield g.readTags(t.nativePath),a=null!=r.Megapixels&&r.Megapixels>2*e?["-h"]:["-q","2"],u=yield p.dcrawNativePath(),f=["-T","-c","-H","2","-w","-o","1",...a,t.nativePath],m=2*s.minuteMs,y={encoding:"buffer",timeout:m,maxBuffer:250*o.MB};w.debug("dcraw()",{cmd:u,args:f,opts:y});const v=yield l.execFile(u,f,m,y),S=e=>i(this,void 0,void 0,function*(){(yield d.emitSafely(v.stdout,"error","Problem from "+t+": "+c.cleanError(e,t.nativePath)))||w.error("No listeners for error when reading "+t,e),v.kill("SIGINT")});v.on("error",S),v.stderr.on("data",S);const P=new h.PullProgressObserver({path:t.nativePath,op:"raw image conversion"},30*s.secondMs,()=>Date.now()-n);return v.on("close",()=>P.end()),v.stdout})}e.dcraw=P},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(39),s=n(3),o=n(2),a=n(11),u=n(48),l=n(64),c=n(260),d=n(32);class h{constructor(t){this.rootDir=t,this.jfs=new c.JsonFileStore(t.join("uid.json"),()=>this.mkUid())}readUid(){return i(this,void 0,void 0,function*(){return this.jfs.read()})}mkUid(){return i(this,void 0,void 0,function*(){return{uid:u.GeoRadix.randomUid(),version:l.version,createdAtIso:a.isoNow()}})}}e.UIDStore=h,e.SystemUIDStore=s.lazy(()=>new h(d.PosixFile.for(r.App.userData()))),r.App.userData.onChange(()=>e.SystemUIDStore.clear()),e.systemUID=function(){return o.thenMapOr(e.SystemUIDStore().readUid(),t=>t.uid,()=>"missing!").catch(t=>"Failed to fetch System UID: "+t)}},function(t,e){("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{}).SENTRY_RELEASE={id:"0.6.0-alpha.1+20190821062758"}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isIterable=function(t){return null!=t&&"string"!=typeof t&&"function"==typeof t[Symbol.iterator]}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(41);e.isList=function(t){return null!=t&&(Array.isArray(t)||isFinite(t.length)&&i.isFunction(t[Symbol.iterator])&&i.isFunction(t.push)&&i.isFunction(t.pop)&&i.isFunction(t.forEach)&&i.isFunction(t.some))}},function(t,e){t.exports=require("he")},function(t,e){t.exports=require("events")},function(t,e){t.exports=require("zlib")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(41);e.asPromise=function(t){return i(this,void 0,void 0,function*(){return r.isFunction(t)?t():t})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(27);e.MRUMap=class{constructor(t=1e3,e=!1){if(this.maxSize=t,this.fifo=e,this.delegate=new Map,this.expireListeners=[],t<1)throw new Error("maxSize must be positive")}get size(){return this.delegate.size}clear(){return this.delegate.clear(),this}delete(t){return this.delegate.delete(t)}entries(){return this.delegate.entries()}forEach(t){this.delegate.forEach(t)}get(t){if(this.delegate.has(t)){const e=this.delegate.get(t);return this.fifo||(this.delegate.delete(t),this.delegate.set(t,e)),e}}getOrSet(t,e){return this.delegate.has(t)?this.get(t):i.tap(e(),e=>this.set(t,e))}has(t){return this.delegate.has(t)}keys(){return this.delegate.keys()}set(t,e){return this.delegate.set(t,e),this.vacuum(),this}values(){return this.delegate.values()}[Symbol.iterator](){return this.entries()}on(t,e){this.expireListeners.push(e)}vacuum(){if(this.delegate.size>this.maxSize)for(const[t,e]of this.delegate)if(this.delegate.delete(t),this.expireListeners.forEach(n=>n(t,e)),this.delegate.size<=this.maxSize)return}}},function(t,e){t.exports=require("child_process")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(5),o=n(4),a=n(21),u=n(3),l=n(2),c=n(10),d=n(20),h=n(11),f=n(68),p=n(60),m=n(1),g=n(7),y=n(0),v=n(23),w=n(47),b=n(19),S=u.lazy(()=>m.mkLogger("Ps"));function P(t){return null!=t&&g.gt0(t.pid)&&null!=t.start&&c.notBlank(t.cmd)}function M(t){return i(this,void 0,void 0,function*(){const e=s.toA(t).filter(g.gt0);if(s.isEmpty(e))throw new Error("Invalid pids: "+JSON.stringify(t));return l.thenTap(l.thenMap(v.isWin?function(t){return i(this,void 0,void 0,function*(){if(a.ending()||w.PowerShell.instance().ended)return D(t);const e=[E,"-Id",k(t),"-ErrorAction SilentlyContinue",_].join(" ");return l.thenMap(w.PowerShell.instance().executeJsonToA(e),t=>x(t))})}(e):function(t){return i(this,void 0,void 0,function*(){return F((yield d.stdoutResult("ps",["-p",k(t),"-wwwo","pid,lstart,command"],Object.assign({},T,{ignoreExitCode:!0}))).result)})}(e),t=>t.filter(t=>P(t)&&e.includes(t.pid))),t=>S().debug("pidInfo()",{pids:e,result:t}))})}function x(t){return t.map(t=>({pid:t.Id,start:h.pwshJsonDate(t.StartTime),cmd:t.ProcessName}))}e.ps=function(){return i(this,void 0,void 0,function*(){const t=yield v.isWin?function(){return i(this,void 0,void 0,function*(){if(a.ending()||w.PowerShell.instance().ended)return D();const t=yield w.PowerShell.instance().executeJsonToA([E,_].join(" "));return null==t?D():x(t)})}():function(){return i(this,void 0,void 0,function*(){return F(yield d.stdout("ps",["-ewwwo","pid,lstart,command"],T))})}();return y.orElse(o.sortBy(t.filter(P),t=>t.pid),[])})},e.pidInfo=function(t){return i(this,void 0,void 0,function*(){return l.thenMap(M([t]),e=>s.toA(e).find(e=>e.pid===t))})},e.pidInfos=M;const E="Get-Process",_="| Select-Object -Property Id,ProcessName,StartTime";function k(t){return s.uniq([...t.filter(g.gt0),r.pid]).join(",")}const T={maxBuffer:1048576,timeout:15*h.secondMs,ignoreExitCode:!0,ignoreStderr:!0},O=["CommandLine","CreationDate","ProcessId"];function D(t){return i(this,void 0,void 0,function*(){const e=["process"];if(s.isNotEmpty(t)){const n=s.uniq([...t.filter(g.gt0),r.pid]).map(t=>`ProcessId=${t}`).join(" or ");e.push("where",n)}e.push("get",O.join(","));const n=yield d.stdoutResult(p.wmic(),e,T);return y.onlyReqValued(f.parseFixed(O,n.result).map(t=>({pid:g.toInt(t.ProcessId,{defaultValue:-1}),start:h.wmiDate(t.CreationDate),cmd:b.toS(t.CommandLine)})))})}function F(t){return f.parseFixed(["PID",{greedyLeft:!0,text:"STARTED"},"COMMAND"],t).map(t=>({pid:g.toInt(t.PID,{defaultValue:-1}),start:new Date(t.STARTED),cmd:b.toS(t.COMMAND)}))}e.psWinWmic=D},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(36),r=n(96);e.WritableToBuffer=class extends r.Duplex{constructor(t){super(t),this.deferred=new i.Deferred("WritableToBuffer"),this._buf=[],this.on("finish",()=>{this.deferred.resolve(this.data)}),this.on("error",t=>{this.deferred.reject(t)})}get data(){return Buffer.concat(this._buf)}get buffer(){return this.deferred.promise}_read(){}_write(t,e,n){const i=Buffer.isBuffer(t)?t:Buffer.from(t,e);this._buf.push(i),n()}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});e.CompoundLogger=class{constructor(t,...e){if(this.primary=t,null==t)throw new Error("null primary logger");this.delegates=[t,...e]}enabled(t,e){return this.primary.enabled(t,e)}log(t,e,n,i){this.enabled(t,e)&&this.delegates.forEach(r=>r.log(t,e,n,i))}flush(){return i(this,void 0,void 0,function*(){yield Promise.all(this.delegates.map(t=>t.flush()))})}close(){this.delegates.forEach(t=>t.close())}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(7);e.TTLArray=class{constructor(t,e){this.ttlMs=t,this.maxLength=e,this.times=[],this.a=[]}push(...t){i.times(t.length,()=>this.times.push(Date.now())),this.a.push(...t),null!=this.maxLength&&this.vacuum()}pushUniq(...t){t.forEach(t=>{this.includes(t)||this.push(t)})}includes(t){return this.vacuum(),this.a.indexOf(t)>=0}shift(){return this.vacuum(),this.times.shift(),this.a.shift()}first(){return this.vacuum(),this.a[0]}shiftOrFirst(){return this.length>1?this.shift():this.first()}pop(){return this.vacuum(),this.times.pop(),this.a.pop()}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]}oldestEntryAge(){return this.vacuum(),this.times[0]}vacuum(){if(0===this.a.length)return;if(null!=this.maxLength){const t=this.a.length-this.maxLength;this.times.splice(0,t),this.a.splice(0,t)}const t=Date.now()-this.ttlMs,e=this.times.findIndex(e=>e>t);-1===e?this.clear():e>0&&(this.times.splice(0,e),this.a.splice(0,e))}}},function(t,e){t.exports=require("net")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(46),r=n(17);function s(t){return r.isNumber(t)?t:t.id}e.id2id=s,e.idEql=function(t,e){return null!=t&&null!=e&&(r.isNumber(t)?t===s(e):r.isNumber(e)?e===s(t):i.eql(t,e))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(3),r=n(48);e.sid=i.lazy(()=>r.Radix58.randomChars(12))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(26),r=n(0),s=n(5);function o(t){return s.includes(["number","string"],typeof t)}e.isDbValue=o,e.isDbValued=function(t){return null!=t&&r.entries(t).every(([,t])=>o(t))},e.toDbValued=function(t){return r.mapFields(t,(t,e)=>{if(!t.startsWith("$"))return"boolean"==typeof e?[t,e?1:0]:o(e)?[t,e]:i.isDated(e)?[t,i.datedToMillis(e)]:void 0})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(29),s=n(1),o=n(13),a=n(5),u=n(8),l=n(9),c=n(15),d=new Map;function h(t){d.set(t.$ctor,t)}e.addModelClass=h;const f=([t,e])=>null!=t&&null!=e;function p(t,e){if(null==e)throw new Error("json is null");if(null!=t&&u.notBlank(t.$ctor)&&!d.has(t.$ctor)&&h(t),e instanceof t)return e;const n=c.Opt(e.$ctor).flatMap(t=>d.get(t)).getOrElse(()=>t);if(e instanceof n)return e;const r=new n;return null==e?r:m(r,e,i.uniq([t.tableName+".",n.tableName+"."]))}function m(t,e,n=[]){const i=t.class();return l.keys(e).filter(t=>"$ctor"!=t).filter(t=>null!=e[t]).map(t=>{const s=e[t];if(n.forEach(e=>t=o.stripPrefix(t,e)),null!=i.relations&&i.relations.has(t)){const e=i.relations.get(t);return[t,Array.isArray(s)?s.map(t=>p(e,t)):p(e,s)]}return a.includes(i.booleanFields,t)?[t,r.truthy(s)]:[t,s]}).filter(f).forEach(([e,n])=>t[e]=n),t}e.fromJSON=p,e.assignFromJSON=m,e.toJSON=function t(e,n,i){if(null!=e)return Array.isArray(e)?e.map((e,r)=>t(e,n,`${i}[${r}]`)):"function"==typeof e.toJSON?e.toJSON():void s.mkLogger("ModelJSON.toJSON()").warn("Failed",{m:e,key:i,mc:n.$ctor})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(85);e.primesPerBin=6,e.SeedCount=Math.pow(e.primesPerBin,6),e.prngSeed=function(){return i.randomInt(0,e.SeedCount)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(4),o=n(3),a=n(2),u=n(142),l=n(25),c=n(26),d=n(1),h=n(7),f=n(12),p=n(74),m=n(5),g=n(8),y=n(16),v=n(59),w=n(62),b=n(91),S=n(125),P=n(175),M=d.mkLogger("LibraryHealthChecks");f.Settings.libraryPath.addListener(()=>e.libraryHealthChecks.clear()),e.libraryHealthChecks=o.lazy(function(){return i(this,void 0,void 0,function*(){const t=S.Library.instance();if(null==t)return f.Settings.libraryPath.hasValue()?{fail:["Missing library"]}:{};if(t.lostLock)return{fail:[P.LostLibraryLockMsg]};const e=[],o=[],d=[],y=[{desc:"Database directory",dir:()=>t.localDbDir()},{desc:"Library directory",dir:()=>t.rootDir}],x=[()=>i(this,void 0,void 0,function*(){if(!w.dbRpc())try{yield t.modelDb();const e=yield n(198).Example.ping();if(c.nowish(e.updatedAt))return"Model DB is OK";throw new Error("Stale upsert in Model DB")}catch(t){throw console.dir(t),new Error("Failed to validate DB: "+t)}})],E=yield p.volumes().catch(t=>(d.push("Cannot get volume information: "+t),[]));for(const t of y)try{const e=yield t.dir();if(null==e)continue;if(e.clear(),yield e.isDirectory()){if(s.isNotEmpty(E)){const n=p.bestVolume(E,e.nativePath);M.debug("checkDir()",{dir:e.nativePath,desc:t.desc,bestVolume:n,vols:E.map(t=>t.mountpoint)}),null==n?d.push(`${t.desc}, ${e}, doesn't seem to have a mountpoint (?!)`):n.available<f.Settings.minDiskFreeGb.valueOrDefault*v.GB&&o.push(`Only ${h.fmtBytes(n.available)} are available on ${n.mountpoint}.`)}}else d.push(`${t.desc}, ${e}, is missing`)}catch(e){d.push("Failed to check "+t.desc+": "+e)}m.isEmpty(d)&&m.isEmpty(o)&&e.push("Library and support directories are OK"),m.isEmpty(E)&&d.unshift("Failed to fetch current volumes"),g.notBlank(r.env.TEST_FAIL)&&d.unshift(...r.env.TEST_FAIL.split(",")),g.notBlank(r.env.TEST_WARN)&&o.unshift(...r.env.TEST_WARN.split(","));for(const t of x)try{yield a.thenMap(t(),t=>e.push(t))}catch(t){d.unshift(l.errorToS(t))}return u.concatHealthChecks({ok:e,warn:o,fail:d},b.syncSettingsCheck())})},7*y.secondMs)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(118),r=n(83);class s extends r.TimestampedModel{static ping(t="ping"){return i.tx(this.db,t,()=>this.ops().upsertOne({name:"ping"}))}}s.tableName="Example",s.uniqueColumnName="name",s.booleanFields=["isExample"],e.Example=s},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(92),s=n(20),o=n(11),a=n(122),u=n(1),l=n(18),c=u.mkLogger("SQLite");function d(t,e){return i(this,void 0,void 0,function*(){const n=yield a.sqliteNativePath(),i=yield o.elapsedAsync(()=>s.stdout(n,[t.nativePath,e],{timeout:1*o.minuteMs}));return c.debug("ops on "+t+" in "+i.elapsedMs+"ms",i.result),i.result})}e.sqliteFiles=function(t){const e=e=>t.sibling(t.base+e);return r.filter([t,e("-wal"),e("-journal")],t=>t.exists())},e.sqlite=d,e.backupDb=function(t,e){return i(this,void 0,void 0,function*(){if(null==(yield e.parent().mkdirp()))return!1;try{return yield d(t,`.backup '${e.nativePath}'`),c.info("backupDb(): copied",{srcDb:l.toS(t),destDb:l.toS(e)}),!0}catch(n){return c.warn("backupDb(): copy failed",{srcDb:l.toS(t),destDb:l.toS(e),err:n}),!1}})},e.verifyDb=function(t){return i(this,void 0,void 0,function*(){const e=yield d(t,"VACUUM ; PRAGMA integrity_check").catch(t=>t);return"ok"===e.trim()?(c.info("verifyDb("+t+"): OK"),!0):(c.warn("verifyDb("+t+"): NOT OK",e),!1)})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(283),s=n(21),o=n(34),a=n(106),u=n(7),l=n(12),c=n(284);function d(t,e){return t.join(e,"db.sqlite3")}e.pathToDb=d,e.dbSetup=function(t,e){return i(this,void 0,void 0,function*(){const n=d(t,e);if(null==(yield n.ensureFile()))throw new Error("Cannot create dbFile "+n);const i=new r(n.nativePath,{memory:!1,fileMustExist:!1,readonly:!1,timeout:2500});s.addDbEndable(new s.EndableWrapper("db("+n.baseWithGrandparent+")",()=>i.close())),function(t){t.pragma('encoding = "UTF-8"'),t.pragma("threads = 2"),t.pragma("foreign_keys = ON"),t.pragma("page_size = "+16*u.KiB),t.pragma("cache_size = -"+l.Settings.dbCacheSizeMb.valueOrDefault*u.MiB),t.pragma("locking_mode = NORMAL"),t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("case_sensitive_like = ON"),t.pragma("auto_vacuum = INCREMENTAL")}(i);const h=new c.Migration(o.BaseFile.for(a.ProjectPath.Migrations()).join(e),i);return yield h.latest(),i})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(35),s=n(37),o=n(21),a=n(0),u=["wal_checkpoint(PASSIVE)","incremental_vacuum","optimize"];e.SqliteJanitor=class{constructor(t,e){this.db=e,this.ended=!1,this.name="SqliteJanitor("+t+")",o.addFirstEndable(this)}setInterval(t){a.map(this.timer,t=>r.clearInterval(t)),this.timer=r.setInterval(()=>this.run(),t)}run(){return i(this,void 0,void 0,function*(){for(const t of u)yield s.later(()=>this.db.transaction(()=>this.db.pragma(t))())})}end(t=!1){this.ended||(this.ended=!0,a.Try(()=>this.db.exec("VACUUM")),t&&this.db.close()),a.map(this.timer,t=>r.clearInterval(t)),this.timer=void 0}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(35),s=n(5),o=n(6),a=n(17),u=n(85),l=n(105),c=n(4),d=n(37),h=n(21),f=n(3),p=n(153),m=n(11),g=n(14),y=n(1),v=n(67),w=n(90),b=n(7),S=n(0),P=n(12),M=n(256),x=n(71),E=n(257),_=f.lazy(()=>y.mkLogger("NiceWorkPlanner"));class k{constructor(t=P.Settings.maxCpuPercent.valueOrDefault,e=M.CpuUsage.instance(),n=500){this.maxCpuPercent=t,this.cpuUsage=e,this.workIntervalMs=n,this.name="NiceWorkPlanner",this.promiseTimer=new p.PromiseTimer,this.startWorkRate=new w.Rate(m.minuteMs),this.finishWorkRate=new w.Rate(m.minuteMs),this.idleEventListener=()=>this.onIdle(),this.availableCpuAvg=new v.Average,this.runningCountAvg=new v.Average,this.unstartedCountAvg=new v.Average,this.idleListeners=[],this.workCount=0,this.pendingWork=[],this._ended=!1,this.availableCpus=f.lazy(()=>a.mapFinite(this.cpuUsage.busyPct(),t=>a.mapFinite(this.cpuUsage.cpuCount,e=>this.availableCpuAvg.push(Math.ceil(e*b.clamp(0,1.5,(this.maxCpuPercent-t)/100))))),this.cpuUsage.checkIntervalMs/2),this.priorWorkCount=0,this.logState=l.throttle(()=>{this.priorWorkCount!==this.workCount&&(this.priorWorkCount=this.workCount,_().info("status",this.status))},(P.isTest?5:60)*m.secondMs),this.paused=P.Settings.startPaused.valueOrDefault,this._workInterval=r.setInterval(()=>this.maybeDoWork(),n),g.onIdle(this.idleEventListener),h.addServiceEndable(this)}static instance(){const t=x.getWorkPlanner();if(t instanceof k&&!t.ended)return t;const e=new k;return x.setWorkPlanner(e),e}isPaused(){return this.paused}pause(){_().info("pause()"),this.paused=!0}resume(){_().info("resume()"),this.paused=!1,this.maybeDoWorkLater()}end(){this._ended||(this._ended=!0,_().info("timings:",this.promiseTimer.report()),S.map(this._workInterval,r.clearInterval),g.eventEmitter.removeListener("idle",this.idleEventListener),this._workInterval=void 0,this.cpuUsage.end())}get ended(){return this._ended}work(t,e){this.workCount++;const n=new E.Work(t,e);return this.pendingWork.push(n),n.promise.then(()=>{this.finishWorkRate.onEvent(),this.maybeDoWorkLater()}),this.maybeDoWorkLater(),n.promise}addIdleListener(t){this.idleListeners.push(t),this.maybeDoWorkLater()}removeIdleListener(t){c.remove(this.idleListeners,t)}get runningCount(){return this.runningCountAvg.push(s.count(this.pendingWork,t=>t.running))}get unstartedCount(){return this.unstartedCountAvg.push(s.count(this.pendingWork,t=>!t.started))}get pausedOrShutdown(){return this.isPaused()||this._ended||h.ending()}get done(){return s.filterInPlace(this.pendingWork,t=>t.pending),c.isEmpty(this.pendingWork)}get status(){return{done:this.done,workRate:this.startWorkRate.eventsPerMinute,availProcs:this.availableCpus(),availProcsStats:this.availableCpuAvg.stats(),unstartedCount:this.unstartedCount,unstartedStats:this.unstartedCountAvg.stats(),runningCount:this.runningCount,runningStats:this.runningCountAvg.stats(),pendingWorkers:this.pendingWork.slice(0,25).map(t=>t.name)}}maybeDoWorkLater(){d.later(()=>this.maybeDoWork())}maybeDoWork(){this.pausedOrShutdown||(this.logState(),b.times(this.idleProcCount(),()=>{S.map(this.pendingWork.find(t=>!t.started),t=>{_().trace("Starting "+t.name),t.start()})}),this.onIdle())}idleProcCount(){return o.mapOr(this.availableCpus(),t=>Math.ceil(t-this.runningCount),()=>0)}onIdle(){return i(this,void 0,void 0,function*(){const t=this.idleProcCount();for(let e=0;e<t;e++){if(this.pausedOrShutdown||this.idleProcCount()<1)return;S.map(u.pickWeightedRandom(this.idleListeners),t=>{this.workCount++,t.onIdle()}),yield d.delay(1)}})}}e.NiceWorkPlanner=k},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(3),o=n(26),a=n(171),u=n(7),l=n(0),c=n(82),d=n(31),h=n(19),f=n(70),p=n(107),m=s.lazy(()=>i(this,void 0,void 0,function*(){return new Intl.DateTimeFormat(yield a.locale(),{month:"short"})})),g=s.lazy(()=>i(this,void 0,void 0,function*(){const t=yield m();return r.range(0,12,e=>t.format(new Date(2016,e)))}));function y(t){return 1e4-t}function v(t){return{name:h.toS(t),ordinal:y(t)}}function w(t){return i(this,void 0,void 0,function*(){if(u.within(1,12,t))return l.map((yield g())[t-1],e=>({name:e,ordinal:b(t)}))})}function b(t){return 13-t}function S(t){return i(this,void 0,void 0,function*(){const e=[p.When];return f.thenOpt(o.getYear(t)).forEach(t=>e.push(v(t))).flatMap(()=>w(o.getMonth(t))).forEach(t=>e.push(t)).map(()=>e).get()})}e.yearToOrdinal=y,e.yearTagRef=v,e.monthTagRef=w,e.monthToOrdinal=b,e.dateTag=S,e.dateTagFile=function(t,e=[]){return i(this,void 0,void 0,function*(){return f.thenOpt(d.readTags(t)).flatMap(t=>c.bestCapturedAt([t.capturedAt,...e])).flatMap(t=>S(t.date)).get()})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(27);e.TTLSet=class{constructor(t){this.ttlMs=t,this.expireListeners=[],this.delegate=new Map,this.keys=this.values.bind(this)}get size(){return this.vacuum(),this.delegate.size}add(t,e=this.ttlMs){return this.delegate.set(t,Date.now()+(e-this.ttlMs)),this}addIfMissing(t,e){const n=this.delegate.get(t);return null==n||n&&this.expired(t,n)?(this.add(t),e()):void 0}clear(){return this.delegate.clear(),this}delete(t){return this.delegate.delete(t)}forEach(t,e){for(const[e,n]of this.delegate)this.expired(e,n)||t(e,e,this)}has(t){return!this.expired(t,this.delegate.get(t))}values(){const t=this;return function*(){for(const[e,n]of t.delegate.entries())t.expired(e,n)||(yield e)}()}entries(){const t=this;return function*(){for(const[e,n]of t.delegate.entries())t.expired(e,n)||(yield[e,e])}()}toA(){return this.vacuum(),[...this.delegate.keys()]}[Symbol.iterator](){return this.values()}on(t,e){this.expireListeners.push(e)}expired(t,e){return i.tap(null==e||e+this.ttlMs<=Date.now(),n=>{null!=e&&n&&(this.expireListeners.forEach(e=>e(t)),this.delegate.delete(t))})}vacuum(){this.delegate.forEach((t,e)=>{this.expired(e,t)})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(10),r=n(11),s=n(0),o=n(44),a=n(83);class u extends a.TimestampedModel{toSyncState(){return{volume:this.volume,uri:this.uri,state:this.state,hed:this.hed,dek:this.dek,completePct:this.completePct,incompletePct:this.incompletePct,scanningPct:this.scanningPct}}get dek(){return s.orElse(i.mapNotBlank(this.dekJSON,()=>JSON.parse(this.dekJSON)),()=>[])}set dek(t){this.dekJSON=JSON.stringify(t)}afterUpsert(){u.recentProgressByVolume.set(this.volume,this)}static findByUri(t){return u.ops().findOne(this.query().where({uri:t}))}}u.recentProgressByVolume=new o.TTLMap(2*r.minuteMs),u.tableName="Progress",u.uniqueColumnName="uri",e.Progress=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(119),r=n(83);class s extends r.TimestampedModel{static ops(){return i.ModelOpsLocal.forModel(this)}static dbr(t,e){return t(this.dbLocal())}}s.schema="stats",e.StatsModel=s},function(t,e){t.exports=require("source-map-support")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(6);e.debounce=function(t,e){let n;const r=()=>{i.map(n,global.clearTimeout),n=global.setTimeout(()=>t(),e)};return r.reset=()=>{i.map(n,global.clearTimeout),n=void 0},r.now=()=>{r.reset(),t()},r}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(85);e.randomInt=i.randomInt,e.randomFloat=i.randomFloat,e.RandomChars=i.RandomChars,e.randomChars=i.randomChars,e.randomChar=i.randomChar,e.pickRandom=i.pickRandom,e.shuffle=i.shuffle,e.sample=i.sample},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(46),o=n(6),a=n(3),u=n(2),l=n(20),c=n(34),d=n(24),h=/^([a-z0-9\/ -_]+) on (.+?) \((.+)\)$/i;function f(){return i(this,void 0,void 0,function*(){const t=yield l.stdout("mount",[],{timeout:d.cmdTimeoutMs});return r.compact(t.split("\n").map(t=>o.map(h.exec(t),t=>{const[e,n,i]=t.slice(1);return{filesystem:e,mountpoint:n,options:i.split(",").map(t=>t.trim())}})))})}function p(t){return i(this,void 0,void 0,function*(){const e=c.BaseFile.for(t),n=yield u.thenMapOr(yield e.childNames(),t=>t.filter(t=>!t.startsWith(".")).map(t=>t.toLowerCase()).sort(),()=>[]);return s.arrayEql(n,["applications","photostructure.app"])})}e.mounts=f,e.ignorableMacFilesystems=a.lazy(()=>i(this,void 0,void 0,function*(){return u.asyncFilter(yield f(),t=>i(this,void 0,void 0,function*(){return t.options.includes("nobrowse")||t.options.includes("quarantine")||(yield p(t.mountpoint))})).then(t=>t.map(t=>t.filesystem))}),d.mountpointsTtlMs),e.isInstallDmg=p},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(2),s=n(10),o=n(0),a=n(112),u=n(111);e.mountpointsPosix=function(){return i(this,void 0,void 0,function*(){const t=yield r.thenMap(a.dfPosixRaw(!1),t=>s.compactBlanks(t.map(t=>t.mountpoint)));if(null!=t&&(yield u.isGioSupported())){const e=yield u.gioVolumes();t.push(...e.map(t=>t.mountpoint))}return o.map(t,t=>t.filter(t=>!t.startsWith("/snap/")))})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(70),o=n(3),a=n(20),u=n(11),l=n(60),c=n(47),d=n(24),h=/\s([A-Z]:\\)/g;e.mountpointsWin=o.lazy(()=>i(this,void 0,void 0,function*(){return s.thenOpt(c.PowerShell.instance().executeJsonToA("Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root")).flatMap(t=>t.map(t=>t.Root)).filter(r.isNotEmpty).orElse(()=>e.mountpointsWinFsutil()).map(t=>t.sort()).getRequired()}),d.mountpointsTtlMs),e.mountpointsWinFsutil=o.lazy(()=>i(this,void 0,void 0,function*(){const t=(yield a.stdout(yield l.fsutil(),["fsinfo","drives"],{timeout:10*u.secondMs})).trim(),e=[];let n;for(;null!==(n=h.exec(t));)e.push(n[1]);return e}),d.mountpointsTtlMs)},function(t,e){t.exports=require("punycode")},function(t,e){t.exports=require("dns")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(15),s=n(77),o=n(10),a=n(20),u=n(11),l=n(60),c=n(7),d=n(23),h=n(19);e.ping=s.memoize(t=>i(this,void 0,void 0,function*(){const e=d.isWin?yield l.pingWin():"ping";return a.stdout(e,[d.isWin?"-n":"-c","1",t],{timeout:5*u.secondMs})}),5*u.minuteMs,255),e.ipv4Re=new RegExp("\\b"+c.times(4,()=>"[0-9]{1,3}").join("\\.")+"\\b"),e.ipAddrFromPing=s.memoize(t=>i(this,void 0,void 0,function*(){return r.Opt(yield e.ping(t).catch(t=>{console.warn("failed to ping: "+t)})).filter(o.notBlank).flatMap(t=>e.ipv4Re.exec(h.toS(t))).map(t=>t[0]).get()}),5*u.minuteMs,255)},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(53),s=n(2),o=n(112),a=n(111),u=n(40),l=n(24),c=r.keyedLazy("localMountpoints",u.mountsCacheKey,()=>s.thenMap(o.dfPosixRaw(!0),t=>t.map(t=>t.mountpoint)),{maxRetries:2,timeoutMs:l.cmdTimeoutMs,priorResultTtlMs:l.longTtlMs});e.dfPosix=r.keyedLazy("dfPosix",u.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){const t=yield o.dfPosixRaw(!1);if(null!=t)return yield s.thenMap(c(),e=>{t.forEach(t=>{t.remote=!e.includes(t.mountpoint)})}),(yield a.isGioSupported())&&(yield s.thenMap(a.gioVolumes(),e=>t.push(...e))),t})},{maxRetries:2,timeoutMs:l.cmdTimeoutMs,priorResultTtlMs:l.dfTtlMs})},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(6),o=n(53),a=n(14),u=n(1),l=n(7),c=n(47),d=n(13),h=n(218),f=n(40),p=n(159),m=n(24),g=u.mkLogger("DfWin");function y(){return i(this,void 0,void 0,function*(){const t=yield c.PowerShell.instance().executeJsonToA(e.LocalAndNetCmd).catch(t=>{a.emitNonFatal("_localAndNet(): PowerShell failed, trying wmic",t)});return null==t?h._localAndNet():t.map(t=>Object.assign({mountpoint:t.Root,filesystem:"",label:t.Description,size:t.Used+t.Free,used:t.Used,available:t.Free,remote:r.notBlank(t.DisplayRoot)},s.map(p.parseRemoteName(t.DisplayRoot),t=>({remoteHost:t.host,remoteShare:t.share}))))})}function v(){return i(this,void 0,void 0,function*(){const t=yield c.PowerShell.instance().executeJsonToA(e.LocalCmd);return null==t?h._local():t.filter(t=>r.notBlank(t.DriveLetter)&&(r.notBlankAnd(t.HealthStatus,t=>d.equalsIgnoreCase(t,"Healthy"))||r.notBlankAnd(t.OperationalStatus,t=>d.equalsIgnoreCase(t,"OK")))).map(t=>({mountpoint:t.DriveLetter+":\\",filesystem:t.FileSystem,label:t.FileSystemLabel,size:t.Size,used:t.Size-t.SizeRemaining,available:t.SizeRemaining,remote:!1}))})}e.dfWin=o.keyedLazy("dfWin",f.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){return(yield y().catch(t=>(g.warn("_localAndNet timed out, using local volumes.",t),v()))).filter(t=>r.notBlank(t.mountpoint)&&l.gt0(t.size))})},{maxRetries:2,timeoutMs:m.cmdTimeoutMs,priorResultTtlMs:m.dfTtlMs}),a.onClearCache(()=>e.dfWin.clear()),e.LocalAndNetCmd="Get-PSDrive -PSProvider FileSystem | Select-Object -Property Root,DisplayRoot,Description,Used,Free",e._localAndNet=y,e.LocalCmd="Get-Volume | Select-Object -Property DriveLetter,FileSystem,FileSystemLabel,Size,SizeRemaining,HealthStatus,OperationalStatus",e._local=v},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(53),o=n(10),a=n(20),u=n(68),l=n(60),c=n(1),d=n(7),h=n(13),f=n(40),p=n(24);e.REMOVABLE_DISK=2,e.LOCAL_DISK=3,e.NETWORK_DRIVE=4;const m=c.mkLogger("DfWinWmic");e.dfWin=s.keyedLazy("dfWin",f.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){return(yield y().catch(t=>(m.warn("_localAndNet timed out, using local volumes.",t),w()))).filter(t=>r.allNotBlank([t.mountpoint,t.filesystem])&&t.size>0)})},{maxRetries:2,timeoutMs:p.cmdTimeoutMs,priorResultTtlMs:p.dfTtlMs});const g="LOGICALDISK get DeviceID,DriveType,FileSystem,FreeSpace,Size,VolumeName /format:table".split(" ");function y(){return i(this,void 0,void 0,function*(){const t=l.wmic(),n=yield a.stdout(t,g,{timeout:p.cmdTimeoutMs});return b(u.parseFixed(["DeviceID","DriveType","FileSystem","FreeSpace","Size","VolumeName"],n,!1).map(t=>{const n=o.mapNotBlank(t.DeviceID,t=>h.ensureSuffix(t,"\\")),i=t.FileSystem,r=t.VolumeName,s=d.toInt(t.Size,{defaultValue:0}),a=d.toInt(t.FreeSpace,{defaultValue:0});return{mountpoint:n,filesystem:i,label:r,size:s,used:s-a,available:a,remote:d.toInt(t.DriveType,{defaultValue:e.LOCAL_DISK})===e.NETWORK_DRIVE}}))})}e._localAndNet=y;const v="VOLUME get Capacity,DriveLetter,FileSystem,FreeSpace,Label /format:table".split(" ");function w(){return i(this,void 0,void 0,function*(){const t=l.wmic(),e=yield a.stdout(t,v,{timeout:p.cmdTimeoutMs});return b(u.parseFixed(["Capacity","DriveLetter","FileSystem","FreeSpace","Label"],e,!1).map(t=>{const e=o.mapNotBlank(t.DriveLetter,t=>h.ensureSuffix(t,"\\")),n=t.FileSystem,i=t.Label,r=d.toInt(t.Capacity,{defaultValue:0}),s=d.toInt(t.FreeSpace,{defaultValue:0});return{mountpoint:e,filesystem:n,label:i,size:r,used:r-s,available:s,remote:!1}}))})}function b(t){return t.filter(t=>r.allNotBlank(t.mountpoint,t.filesystem)&&d.gte(t.size,0))}e._local=w},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(53),s=n(10),o=n(20),a=n(38),u=n(0),l=n(13),c=n(40),d=n(24);e.addLocalVolumeInfoMac=function(t){return i(this,void 0,void 0,function*(){const n=yield e.mnt2uuidMac();if(null!=n)return t.forEach(t=>{u.map(n.get(t.mountpoint),e=>{t.uuid=e.uuid,t.label=e.label})}),t})},e.mnt2uuidMac=r.keyedLazy("mnt2uuidMac",c.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){const t=(yield o.stdout("diskutil",["info","-all"],{timeout:d.cmdTimeoutMs})).split(/^\s*\*{3,}\s*$/m);return a.toMap(t,t=>{const e=a.toMap(t.split(/\s*\n+\s*/),t=>{const[e,n]=t.split(":").map(t=>t.trim());return l.includesIgnoreCase(["not applicable","no file system"],n)?void 0:[e.toLowerCase(),n]}),n=e.get("mount point"),i=e.get("volume name"),r=e.get("volume uuid");return s.blank(n)?void 0:[n,{label:i,uuid:r}]})})},{maxRetries:2,timeoutMs:d.cmdTimeoutMs,priorResultTtlMs:d.longTtlMs})},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(53),s=n(10),o=n(20),a=n(221),u=n(0),l=n(19),c=n(40),d=n(24);e.addLocalVolumeInfoPosix=function(t){return i(this,void 0,void 0,function*(){const e=yield h();if(null!=e)return t.forEach(t=>{e.ignorablePaths.includes(t.mountpoint)?t.ignorable=!0:u.map(e.mnt2info.get(t.mountpoint),e=>{t.uuid=e.uuid,t.label=e.label})}),t})};const h=r.keyedLazy("volumeInfoLinux",c.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){const t=yield o.stdout("lsblk",["-P","--output","mountpoint,label,uuid"],{timeout:d.cmdTimeoutMs}),e=new Map,n=[];return t.split(/[\r\n]+/).forEach(t=>{u.map(a.parseEnvTokens(t),t=>{l.toS(t.mountpoint).startsWith("/")&&(s.blank(t.uuid)?n.push(t.mountpoint):e.set(t.mountpoint,t))})}),{mnt2info:e,ignorablePaths:n}})},{maxRetries:2,timeoutMs:d.cmdTimeoutMs,priorResultTtlMs:d.longTtlMs})},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseEnvTokens=function(t){const e=/([a-z]+)="(.*?)"/gi,n={};let i;for(;null!=(i=e.exec(t));){const[,t,e]=i;n[t.toLowerCase()]=e}return n}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(53),o=n(20),a=n(11),u=n(14),l=n(60),c=n(38),d=n(0),h=n(47),f=n(13),p=n(40),m=n(24);function g(){return i(this,void 0,void 0,function*(){const t=yield l.fsutil(),e=yield o.stdout(t,["volume","list"],{timeout:7*a.secondMs}),n=new Map;let i;const r=/^\\\\.+\{([a-z0-9-]+)\}\\[\r\n]+([a-z]:\\)/gim;for(;null!=(i=r.exec(e));){const t=i[1],e=i[2];n.set(e,t)}return n})}e.addLocalVolumeInfoWin=function(t){return i(this,void 0,void 0,function*(){const e=yield y();if(null!=e)return t.forEach(t=>{d.map(e.get(t.mountpoint),e=>{t.remote=!1,t.uuid=e})}),t})},e.UuidCmd="Get-Partition | Select-Object -Property DriveLetter,Guid,IsOffline",e._mnt2uuidWinFsutil=g;const y=s.keyedLazy("mnt2uuidWin",p.mountsCacheKey,function(){return i(this,void 0,void 0,function*(){const t=yield h.PowerShell.instance().executeJsonToA(e.UuidCmd);return null==t?g():c.toMap(t.filter(t=>r.notBlank(t.DriveLetter)&&!t.IsOffline&&r.notBlank(t.Guid)),t=>[t.DriveLetter+":\\",f.stripPreSuff(t.Guid,"{","}")])})},{maxRetries:2,timeoutMs:m.cmdTimeoutMs,priorResultTtlMs:m.longTtlMs});u.onClearCache(()=>y.clear())},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(0),s=n(19),o=/^\/\/(?:.+@)?(.+?)(?:\._(?:smb|afs|nfs|tcp)){0,2}(?:\.local)?\/(.+)$/i;e.addRemoteVolumeInfoPosix=function(t){return i(this,void 0,void 0,function*(){return t.filter(t=>t.remote).forEach(t=>{r.map(o.exec(s.toS(t.filesystem)),e=>{t.remoteHost=e[1],t.remoteShare=e[2]})}),t})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(18),s=n(29),o=n(72),a=n(0),u=n(27);function l({logger:t,name:e,result:n}){const i=null==n?"warn":"debug";t.enabled(i)&&t.log(i,o.grey(e)+": "+(!0===n?o.green:o.red)(r.toS(n)))}e.orLogged=function(t,e){return t.some(t=>a.keys(t).some(n=>s.truthy(u.tap(t[n](),t=>l({logger:e,name:n,result:t})))))},e.orLoggedAsync=function(t,e){return i(this,void 0,void 0,function*(){for(const n of t)for(const t of a.keys(n)){const i=yield n[t]();if(l({logger:e,name:t,result:i}),i)return i}return!1})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(4),s=n(38),o=n(0);e.SetSet=class{constructor(){this.store=new Map}add(t,...e){s.getOrSet(this.store,t,()=>new Set).add(e)}find(t){for(let e=0;e<t.length-1;e++){const n=o.map(this.store.get(t[e]),n=>{const i=t.slice(e+1),s=[...n].filter(t=>r.startsWith(i,t));return r.greatestBy(s,t=>t.length)});if(i.isNotEmpty(n))return[t[e],...n]}}has(t){return null!=this.find(t)}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(113),o=n(3),a=n(20),u=n(11),l=n(68),c=n(1),d=n(23),h=n(28),f=c.mkLogger("Snap");e.ignorableSnapDir=s.AsyncFilter.lift(t=>i(this,void 0,void 0,function*(){if(!d.isLinux||!(yield e.hasSnap()))return!1;const n=h.pathnames(t.nativePath).indexOf("snap");return!(n<0)&&r.toA(yield e.snaps()).includes(h.pathnames[n+1])})),e.hasSnap=o.lazy(()=>i(this,void 0,void 0,function*(){try{return yield a.stdout("snap",["--version"],{timeout:10*u.secondMs}),!0}catch(t){return!1}})),e.snaps=o.lazy(()=>i(this,void 0,void 0,function*(){try{return yield l.parseFixed(["Name","Version"],yield a.stdout("snap",["list"],{timeout:10*u.secondMs})).map(t=>t.Name)}catch(t){return f.warn("snap failed",t),[]}}),30*u.secondMs)},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(35),o=n(5),a=n(8),u=n(16),l=n(41),c=n(39),d=n(21),h=n(3),f=n(2),p=n(50),m=n(10),g=n(20),y=n(14),v=n(34),w=n(1),b=n(0),S=n(141),P=n(12),M=n(13),x=n(142),E=n(167);e.ChildServiceExitCommand="--exit";const _=h.lazy(()=>w.mkLogger("ChildService"));function k(t){return i(this,void 0,void 0,function*(){const e=M.ensureSuffix(t,".js"),n=yield f.firstTruePromise(t=>t.isNonEmpty(101),()=>v.BaseFile.projectRoot().join("app.asar",e),()=>v.BaseFile.for(r.cwd()).join("dist","library",e),()=>v.BaseFile.for(r.cwd()).join("dist","app",e),()=>v.BaseFile.for(r.cwd()).join("dist","js","library",e));return _().info("pathToService()",{cmdBase:t,result:n}),n})}e.pathToService=k;let T=0;function O(t){switch(t){case"main":return 9222;case"web":case"db":return 9223;case"sync":return 9224;case"sync-file":return 9225+T++%20}}function D(t){const e=[];return P.Settings.inspect.valueOrDefault&&e.push("--inspect="+O(t)),e}e.inspectPort=O,e.nodeArgs=D;class F{constructor(t,n,i){this.name=t,this.cmd=n,this.opts=i,this.logger=w.mkLogger("ChildDaemon("+t+")");const r=b.orElse(this.opts.maxAgeMs,S.serviceMaxAgeMs(t)),a=[...o.toA(i.nodeArgs),n.nativePath];o.isNotEmpty(i.args)&&a.push(...i.args);const l=b.without(this.opts,"nodeArgs","onData","onError","onStdout");this.wc=new E.WatchedChild(Object.assign({name:t,childFactory:()=>g.spawn(c.App.getPath("exe"),a,r,l),endableRank:d.EndableRanks.service,onStdout:this.onStdout.bind(this),onError:b.orElse(this.opts.onError,()=>()=>!0),ignoreStopErrors:!1,onRestartError:()=>{y.emitFatal("Can't launch "+t+": exiting")},exitCommand:e.ChildServiceExitCommand},i)),this.healthCheckTimer=p.setUnrefInterval(()=>this.healthCheck(),30*u.secondMs),d.addFirstEndable(new d.EndableWrapper("ChildService.healthCheckTimer",()=>s.clearInterval(this.healthCheckTimer)))}static mk(t,e={}){return i(this,void 0,void 0,function*(){const n=b.orElse(e.pathToService,yield k(t));if(a.blank(n))throw new Error("Failed to find path to "+t);return P.Settings.inspect.valueOrDefault&&(e.nodeArgs=[...D(t),...o.toA(e.nodeArgs)]),new F(t,n,e)})}get lastStatus(){return this._lastStatus}onStdout(t){return i(this,void 0,void 0,function*(){if(!a.blank(t))try{const e=JSON.parse(t);m.notBlank(e.fatal)?this.wc.onError("onStdout()",e.error):m.notBlank(e.healthChecks)?this._lastStatus=Object.assign({},e,{ts:Date.now()}):null!=this.opts.onData&&this.opts.onData(e)}catch(e){console.log(t)}})}get ended(){return this.wc.ended}end(){return this.wc.end()}get pid(){return this.wc.pid}get msSinceLastStart(){return this.wc.msSinceLastStart}running(){return this.wc.running()}notRunning(){return this.wc.notRunning()}restart(){return i(this,void 0,void 0,function*(){return this.wc.restart()})}restartIfStopped(){return this.wc.restartIfStopped()}stop(){return i(this,void 0,void 0,function*(){return this.wc.stop()})}write(t,e=2){return i(this,void 0,void 0,function*(){if(e<0)return this.logger.warn("write(): no more retries",{toStdin:t}),!1;try{const n=this.wc.proc;return null!=n&&null!=n.stdin&&n.stdin.writable?n.stdin.write(M.ensureSuffix(t,"\n")):(this.logger.warn("write(): childProc isn't open, ignoring",{toStdin:t}),!1)}catch(n){return this.logger.warn("write(): caught "+n),yield this.wc.onError("onStdout()",n),this.write(t,e-1)}})}healthCheck(){return i(this,void 0,void 0,function*(){if(d.ending()||this.ended)return;if(l.isFunction(this.opts.healthy)){if(!1===(yield this.opts.healthy()))return y.emitNonFatal("healthCheck for "+this.name+": !healthy(), restarting."),this.restart()}const t=Date.now();(yield this.write("--status"))||this.logger.warn("Failed to write?"),yield f.until(()=>null!=this.lastStatus&&this.lastStatus.ts>=t,20*u.secondMs);const e=this.lastStatus;if(null==e||e.ts<t)return y.emitNonFatal("healthCheck for "+this.name+": no response from --status, restarting."),this.restart();const n=e.healthChecks;return this.logger.debug("healthCheck(): ",n),x.hasBad(n)||x.hasFail(n)?(y.emitNonFatal("healthCheck for "+this.name+": unhealthy, restarting."),this.restart()):void this.logger.debug("healthCheck: all is well",n)})}}e.ChildService=F},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(229),s=n(99),o=n(7);e.readFileType=function(t){return i(this,void 0,void 0,function*(){let e=-1;try{const n=Buffer.alloc(32);e=yield s.open(t,"r");const{buffer:i}=yield s.read(e,n,0,32,0);return r(i)}catch(t){return}finally{yield o.mapGte0(e,s.close)}})}},function(t,e){t.exports=require("file-type")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(7),r=n(57);function s(t){return t.toString(2).split("").reverse().map((t,e)=>"1"===t?e:-1).filter(t=>-1!==t)}e.concatBits=function(t,e){const n=Math.pow(2,e);return t.reduce((t,e)=>t*n+i.clamp(0,n,i.toInt(e,{defaultValue:0})),0)},e.bitZip=function(t){t.dims.forEach(t=>t.value=i.clamp(t.min,t.max,t.value));let e=0;for(let n=0;n<t.bitDepth;n++){e*=2;const i=n%t.dims.length,s=t.dims[i],o=r.avg([s.min,s.max]);s.value>o?(e+=1,s.min=o):s.max=o}return e},e.bitUnzip=function(t,e){if(e.bitDepth>52||e.bitDepth<0)return;const n=s(t);for(let t=0;t<e.bitDepth;t++){const i=t%e.dims.length,s=e.dims[i],o=r.avg([s.min,s.max]);n.includes(e.bitDepth-t-1)?s.min=o:s.max=o}return e.dims.map(t=>r.avg([t.min,t.max]))},e.bitsSet=s,e.pop=function(t){return t=(t=(858993459&(t-=t>>1&1431655765))+(t>>2&858993459))+(t>>4)&252645135,t+=t>>8,63&(t+=t>>16)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(102),r=n(33),s=n(1),o=n(12),a=n(56),u=n(55);e.SharpFits=r.strEnum("cover","contain","fill","inside","outside"),function(t){t.name=i.ReducerNames.sq,t.fit="cover",t.reduce=function(t,e){const n=e.width!==e.height;if(a.ltBoth(t,e))return n?Object.assign({},t,{fit:"cover",position:o.Settings.squareThumbStrategy.valueOrDefault}):t}}(e.Square||(e.Square={})),function(t){const e=u.lazy(()=>s.mkLogger("Reducers.Fit"));t.name=i.ReducerNames.fit,t.fit="inside",t.reduce=function(t,n){if(a.ltBoth(n,t))return void e().debug("reduce(): input is too small for max",{input:n,max:t});const i=n.width/n.height;return i>=t.width/t.height?{width:t.width,height:Math.ceil(t.width/i)}:{width:Math.ceil(t.height*i),height:t.height}}}(e.Fit||(e.Fit={}))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(22),r=n(5),s=n(17),o=n(15),a=n(18),u=n(7),l=n(64);class c{constructor(t,e,n,i){this.version=t,this.major=e,this.minor=n,this.patch=i}static for(t){return o.Opt(a.toS(t).split(".",3).map(t=>s.toInt(t))).map(r.compact).filter(t=>t.length>=3).map(e=>new c(t,e[0],e[1],e[2])).get()}gte(t){return"string"==typeof t&&(t=c.for(t)),u.gte(this.major,t.major)&&u.gte(this.minor,t.minor)&&u.gte(this.patch,t.patch)}toString(){return this.version}}e.SemVer=c,e.Version=c.for(l.version),e.NodeVersion=c.for(i.versions.node)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(234),r=n(12);e.PermissiveWorkPlanner=class{constructor(){this.pausedUntil=0,this.queue=[],this.paused=r.Settings.startPaused.valueOrDefault}isPaused(){return this.paused||Date.now()<this.pausedUntil}pause(t){null==t?this.paused=!0:this.pausedUntil=Math.max(Date.now()+t,this.pausedUntil)}resume(){this.paused=!1,this.pausedUntil=0,this.queue.forEach(t=>t()),this.queue.length=0}work(t,e){if(this.isPaused()){const{promise:t,later:n}=i.laterPromise(e);return this.queue.push(n),t}return e()}addIdleListener(){}removeIdleListener(){}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(29);!function(t){t.and=function(...t){return i(this,void 0,void 0,function*(){for(const e of t)if(!r.truthy(yield e()))return!1;return!0})},t.or=function(...t){return i(this,void 0,void 0,function*(){for(const e of t)if(r.truthy(yield e()))return!0;return!1})}}(e.Later||(e.Later={})),e.laterPromise=function(t){let e,n;return{promise:new Promise((t,i)=>{e=t,n=i}),later:()=>i(this,void 0,void 0,function*(){try{const i=yield t();return e(i),i}catch(t){throw n(t),t}})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(0),r=n(113);class s{static lift(t){return new class extends s{apply(e){return t(e)}}}and(t){return s.lift(e=>this.apply(e)&&t.apply(e))}or(t){return s.lift(e=>this.apply(e)||t.apply(e))}filter(t){return t.filter(t=>this.apply(t))}asAsync(){return r.AsyncFilter.lift(t=>Promise.resolve(this.apply(t)))}}e.Filter=s,e.definedFilter=s.lift(i.defined),e.trueFilter=s.lift(()=>!0)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(6),s=n(9),o=n(52),a=n(26),u=n(114),l=n(76),c=n(55),d=n(1),h=c.lazy(()=>d.mkLogger("ExifUid4"));e.extractUid4=function(t){return r.map(function(t,e,n){if(!e.src.startsWith("tags"))return;const r=a.datedToISO(e.date),o=t.Make,c=t.Model,d=l.compactZeroes(s.pick(t,"SerialNumber","CameraSerialNumber","BodySerialNumber","InternalSerialNumber","LensSerialNumber")),f=l.compactZeroes(s.pick(t,"BurstUUID","ImageNumber","ShutterCount","ImageUniqueID","RunTimeValue")),p=u.geohash(t.GPSLatitude,t.GPSLongitude,52);if(i.blank(p)&&null==n&&s.emptyObj(f)&&s.emptyObj(d))return;const m=s.compactValues(Object.assign({exifUid:4,capturedAt:r,Make:o,Model:c},n,f,d,{geoHash:p}));return h().debug("extractUidPojo4",{tags:s.pick(t,"SourceFile","tz","tzSource"),capturedAt:e,result:m}),m}(t,t.capturedAt,t.exposureSettings),t=>o.shortStringSha(JSON.stringify(t),20)+":v4")}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(6),s=n(9),o=n(3),a=n(52),u=n(26),l=n(1),c=n(76),d=n(94),h=5,f=o.lazy(()=>l.mkLogger("ExifUid5"));e.extractUidPojo5=function(t,e,n){if(null==e||!e.src.startsWith("tags"))return void f().debug("extractUidPojo(): rejecting, captured at isn't from tags",{src:t.SourceFile,ca:e});const o=e.date,a=r.map(o,u.datedToISO);if(null==o||null==a)return void f().debug("extractUidPojo5(): rejecting, captured at doesn't have a date or ISO",{src:t.SourceFile,ca:e,capturedAtDate:o,capturedAtIso:a});const l=c.normalizeExposureSettings(r.orElse(n,()=>d.extractExposureSettings(t))),p=t.Make,m=t.Model,g=c.cameraId(t),y=c.imageId(t),v=c.uidGeoHash(t.GPSLatitude,t.GPSLongitude),w=i.notBlank(p)&&i.notBlank(m),b=u.hasTime(e.date)&&[u.getMinute(e.date),u.getSecond(e.date)].some(c.present),S=w&&c.present(g)&&c.present(y),P=w&&b&&null!=l,M=b&&i.notBlank(v)&&(w||c.present(g)||c.present(y)),x=w&&null!=c.normalizeExposureSettings&&(c.present(g)||c.present(y)),E=Object.assign({version:h,capturedAtIso:a,Make:p,Model:m},l,{imageId:y,cameraId:g,geoHash:v}),_={hasMakeModelSerial:S,hasMakeModelExp:P,hasSecsGeo:M,hasMakeModelExpSerial:x,normalizedExpSets:l,exifUid:E};return S||P||M||x?(f().debug("extractUidPojo5()",_),s.compactValues(E)):void f().debug("extractUidPojo5(): cowardly rejecting, not enough context",_)},e.serializeUidPojo5=function(t){return a.shortStringSha(JSON.stringify(t),20)+":v"+r.orElse(t.version,h)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(6),s=n(9),o=n(18),a=n(26),u=n(1),l=n(76),c=n(94),d=6;e.extractUidPojo6=function(t,e,n){const h=u.mkLogger("extractUidPojo6("+o.toS(t.FileName)+")");if(null==e||!e.src.startsWith("tags"))return void h.debug("rejecting, captured at isn't from tags",{src:t.SourceFile,ca:e});const f=e.date,p=r.map(f,t=>a.datedToISO(t,!1));if(null==f||null==p)return void h.debug("rejecting, captured at doesn't have a date or ISO",{src:t.SourceFile,ca:e,capturedAtDate:f,capturedAtIso:p});const m=l.normalizeExposureSettings(r.orElse(n,()=>c.extractExposureSettings(t))),g=t.Make,y=t.Model,v=l.cameraId(t),w=l.imageId(t),b=l.uidGeoHash(t.GPSLatitude,t.GPSLongitude),S=i.notBlank(g)&&i.notBlank(y),P=a.hasTime(e.date)&&[a.getMinute(e.date),a.getSecond(e.date),a.getMillisecond(e.date)].some(l.present),M=S&&l.present(v)&&l.present(w),x=S&&P&&null!=m,E=P&&i.notBlank(b)&&(S||l.present(v)||l.present(w)),_=S&&null!=l.normalizeExposureSettings&&(l.present(v)||l.present(w)),k=Object.assign({version:d,capturedAtIso:p,Make:g,Model:y},m,{imageId:w,cameraId:v,geoHash:b}),T={hasMakeModelSerial:M,hasMakeModelExp:x,hasSecsGeo:E,hasMakeModelExpSerial:_,normalizedExpSets:m,exifUid:k};return M||x||E||_?(h.debug("result",T),s.compactValues(k)):void h.debug("cowardly rejecting, not enough context",T)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(55),s=n(6),o=n(9),a=n(26),u=n(1),l=n(76),c=n(94),d=7,h=r.lazy(()=>u.mkLogger("ExifUid7"));e.extractUidPojo7=function(t,e,n){if(null==e||!e.src.startsWith("tags"))return void h().debug("rejecting, captured at isn't from tags",{src:t.SourceFile,ca:e});const r=s.map(e.date,t=>a.datedToMillis(t));if(null==r)return void h().debug("rejecting, captured at doesn't have a date",{src:t.SourceFile,ca:e,capturedAtMs:r});const u=l.normalizeExposureSettings(s.orElse(n,()=>c.extractExposureSettings(t))),f=t.Make,p=t.Model,m=l.cameraId(t),g=l.imageId(t,{includeImageUniqueId:!1}),y=i.notBlank(f)&&i.notBlank(p),v=a.hasSeconds(e.date),w=y&&l.present(m)&&l.present(g),b=y&&v&&null!=u,S=y&&null!=l.normalizeExposureSettings&&(l.present(m)||l.present(g)),P=Object.assign({version:d,capturedAtMs:r,Make:f,Model:p},u,{imageId:g,cameraId:m}),M={hasMakeModelSerial:w,hasMakeModelExp:b,hasMakeModelExpSerial:S,normalizedExpSets:u,exifUid:P};return w||b||S?(h().debug("result",M),o.compactValues(P)):void h().debug("cowardly rejecting, not enough context",M)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(65),s=n(79),o=n(8),a=n(17),u=n(15),l=n(1).mkLogger("JsonSidecar");function c(t,e,n){for(const i of e)if(t&&t[i]&&a.isNumber(t[i][n]))return t[i][n]}e.readJsonSidecar=function(t){return i(this,void 0,void 0,function*(){const e=yield t.readJSON(),n=null==e?void 0:{DateTimeOriginal:u.Opt(e.photoTakenTime).flatMap(t=>t.timestamp).flatMap(a.toInt).filter(a.gt0).flatMap(t=>r.ExifDateTime.fromDateTime(s.DateTime.fromMillis(1e3*t))).get(),GPSLatitude:c(e,["geoDataExif","geoData"],"latitude"),GPSLongitude:c(e,["geoDataExif","geoData"],"longitude"),GPSAltitude:c(e,["geoDataExif","geoData"],"altitude"),Title:o.ifNotBlank(e.title),Description:o.ifNotBlank(e.description)};return null!=n&&l.debug("read "+t,n),n})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(8),r=n(0),s=n(13),o=["ag","camera","co","company","computer","corp","corporation","digital","elec","electric","electronics","fototechnic","global","gmbh","group","imaging","inc","international","ltd","optical","photo","products","technologies","technology","techwin"].join("|"),a=new RegExp(`[\\s\\.,_-]*(?:${o})[\\s\\.,_-]*$`,"i");function u(t,e,n=""){const i=t.replace(e,n);return i===t?t:u(i,e,n)}function l(t){const e=t.trim();return"gopro"===e.toLowerCase()?"GoPro":"benq"===e.toLowerCase()?"BenQ":e.length<4?e:e.toLowerCase().replace(/(?:^|\s|-)\S/g,t=>t.toUpperCase())}e.companyCased=l,e.make=function(t){return i.mapNotBlank(t,t=>t=l(t=u(t=s.stripQuotes(t),a).replace("LGE","LG")))};const c=[/[0-9a-f]{24,}$/i,/\(v\d+.\d+\)\w?$/i,/digital camera$/i],d=new Map([["Samsung",[[/^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/,"Galaxy S10"],[/^SM-G975/,"Galaxy S10+"],[/^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"]]],["LG",[[/LG-D80[01235]|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[0123]|LS993|AS993|US997|VS998/,"G6"],[/^(LM-)?G71/i,"G7"]]]]);e.model=function(t,e){if(i.blank(t)||i.blank(e))return;e=s.stripQuotes(e);const n=r.map(d.get(t),t=>t.find(([t])=>null!=e.match(t)));return null!=n?n[1]:("Sony"===t&&(e=e.replace(/^(DSLR-A|SLT-A|ILCA-|ILCE-)/,"α").replace(/M2$/," II").replace(/M3$/," III").replace(/M4$/," IV")),c.forEach(t=>e=u(e,t).trim()),e=e.replace(new RegExp(`^${t}\\s+`,"i"),""),null!=t.match(/^HP|Hewlett.Packard$/i)&&null!=e.match(/^hp\b/i)&&(e=e.slice(2).trim()),e)}},function(t,e){t.exports=require("@iarna/toml")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(6),s=n(9),o=n(78),a=n(3),u=n(2),l=n(137),c=n(28),d=n(1),h=n(0),f=n(169),p=a.lazy(()=>d.mkLogger("ShownFilePicker")),m=[o.PS_NETWORK_FILESYSTEM_PROTOCOL,"file:",o.PS_LOCAL_FILE_PROTOCOL,o.PS_LIBRARY_PROTOCOL];function g(t){return h.map(t,t=>Math.ceil(Math.log2(t.width*t.height)))}function y(t){return i(this,void 0,void 0,function*(){const e=yield v(t),n=s.values(e);return n.some(t=>null==t)?void p().debug("sortShownFiles: skipping "+t,e):n})}function v(t){return i(this,void 0,void 0,function*(){const e=g(yield f.dimensions(t)),n=yield t.uriObject(),i=yield u.thenMap(t.thisOrSidecareMaxMtimeSec(),t=>Math.round(t/60)),s=h.map(n,t=>m.indexOf(t.protocol)),o=t.name.toLowerCase().includes("cover"),a=l.browserExtFilter.apply(t);return{mp:e,mtime:i,schemeIdx:s,isCover:o,count:r.orElse(c.countFromName(t.name),0),isBrowserSupported:a}})}e.dim2sort=g,e.sortShownFiles=function(t){return i(this,void 0,void 0,function*(){return u.sortByAsync(t,y)})},e.fileSortCriteria=y,e.fileSortCriteriaPojo=v},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(3),r=n(10),s=n(135),o=n(28),a=n(32),u=n(12),l=n(13),c=n(15),d=n(78);e.installLibraryUriSupport=i.lazy(()=>{s.addUriParser(p),s.addUriFormatter(f)});const h=i.lazy(()=>c.Opt(u.Settings.libraryPath.value).filter(r.notBlank).map(t=>a.PosixFile.for(t)));function f(t){const e=a.PosixFile.for(o.posix2native(t.posixPath));return h().filter(t=>e.isDescendantOf(t)).map(e=>({pathname:encodeURI(a.PosixFile.for(t.posixPath).posixPathFrom(e)),protocol:d.PS_LIBRARY_PROTOCOL,slashes:!0})).get()}function p(t){return c.Opt("").filter(()=>l.equalsIgnoreCase(t.protocol,d.PS_LIBRARY_PROTOCOL)).flatMap(()=>h()).map(e=>r.blank(t.pathname)?e:e.join(decodeURIComponent(t.pathname))).get()}u.Settings.libraryPath.addListener(()=>h.clear()),e.uriFromLibraryPath=f,e.posixPathFromUri=p},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(97),r=n(110),s=n(144),o=n(198),a=n(195),u=n(119),l=n(205),c=n(108);e.modelJsonSetup=function(){[i.Asset,r.AssetFile,s.AssetTag,o.Example,l.Progress,c.Tag].forEach(t=>{a.addModelClass(t),u.ModelOpsLocal.forModel(t)})}},function(t,e){t.exports=require("@sentry/node")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(42),s=n(39),o=n(4),a=n(3),u=n(2),l=n(52),c=n(32),d=n(86),h=n(1),f=n(48),p=n(0),m=n(151),g=n(12),y=a.lazy(()=>h.mkLogger("CacheDir"));function v(){return u.thenMapOr(c.PosixFile.for(s.App.getPath("userData")).children(),t=>t.filter(t=>t.name.startsWith(e.CacheDirPrefix)),()=>[])}function w(){return i(this,void 0,void 0,function*(){const t=[g.Settings.libraryPath,...g.persistedLibrarySettings()].map(t=>[t.key,t.valueOrDefault]);t.push(["EXIF_UID_LAST_UPDATED_AT",m.LastUpdatedAtMs]),t.push(["VLC_INSTALLED",yield d.isVlcSupported()]);const n=o.sortBy(t,([t])=>t),i=l.shortStringSha(JSON.stringify(n),9,f.GeoRadix),a=(yield c.PosixFile.for(s.App.getPath("userData")).mkNoMedia()).join(e.CacheDirPrefix+i);return yield a.join("README.txt").applyIfEmpty(t=>t.writeTxt(`\nThis folder is a library synchronization cache for\n\n${g.Settings.libraryPath.value}\n\nIf you delete or modify the contents of this directory, you will need to\nrestart PhotoStructure, and the next sync will need to rescan all your drives.\n\nIf you have any questions, please visit <https://support.photostructure.com/>.\n\nSettings used by this cache: \n\n`+r.inspect(n,{colors:!1,breakLength:80}))),y().info("Set up cache dir"+a),a})}function b(t){return i(this,void 0,void 0,function*(){const n=p.orElse(t,yield w());if(!n.name.startsWith(e.CacheDirPrefix))throw new Error("Refusing to remove directory "+n);yield n.remove()})}e.cacheDirs=v,e.CacheDirPrefix="ps-cache-",e.cacheDir=w,e.clearCacheDir=b,e.vacuumCacheDirs=function(){return i(this,void 0,void 0,function*(){const t=yield w();for(const e of yield v())e.eql(t)||(yield b(e))})},e.clearCacheDirs=function(){return i(this,void 0,void 0,function*(){for(const t of yield v())yield b(t)})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(6),r=n(37),s=n(3),o=n(11),a=n(14),u=n(1),l=n(90),c=n(19),d=3,h=new l.Rate(o.minuteMs),f=s.lazy(()=>u.mkLogger("onError")),p=["SQLITE_IOERR","SQLITE_ERROR"].map(t=>t.toLowerCase());e.onErr=function(t,e,n){const s=c.toS(e).toLowerCase(),o=p.some(t=>s.includes(t));f().log(o?"error":"warn",t+": "+i.mapOr(e,t=>t.stack,()=>c.toS(e)),n),o&&(h.onEvent(),h.eventsPerMinute>=d&&(f().error("Error rate is too high. Sending fatal event.",{source:t,err:e,context:n,errsPerMin:h.eventsPerMinute,fatalErrorRatePerMin:d}),r.later(()=>a.emitFatal(s))))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(2),s=n(16),o=n(55),a=n(6),u=n(85);let l=0;e.rpcAllowed=function(t,e){return i(this,void 0,void 0,function*(){return r.until(()=>0===l,a.orElse(t,()=>u.randomInt(5*s.secondMs,15*s.secondMs)),a.orElse(e,()=>u.randomInt(250,1e3)))})},e.pauseRpc=function(t=s.secondMs){l++;const e=o.lazy(()=>l--);return setTimeout(e,t),e}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(196),r=n(4),s=n(3),o=n(77),a=n(11),u=n(7),l=n(275);var c=n(196);function d(t){return r.zip(e.primeLists(),l.digits(t,i.primesPerBin,6).reverse()).map(([t,e])=>t[e])}e.primesPerBin=c.primesPerBin,e.SeedCount=c.SeedCount,e.prngSeed=c.prngSeed,e.prngOrderByClause=function(t,n,i){const[r,s,o,a,u]=e.primes(t),l=`(${n}%${a})`;return`ROUND(${`(${r}*${l}*${l}+${s}*${l})`}*${`(${o}*${l}+${a})`}+${`${u}+${n}`})${i?"%"+i:""}`},e.prng=function(t,n,i){const[r,s,o,a,u]=e.primes(t),l=n%a,c=(r*l*l+s*l)*(o*l+a)+u+n;return Math.round(c)%i},e.primeLists=s.lazy(()=>[[21683,39301,45853,57427,58991,65543],[262139,314569,366997,419429,471871,524309],[1048573,1258291,1468079,1677811,1887539,2097257],[10392467,22222223,32457869,42638597,58947631,68956417,84619573],[353868013,472882027,573259391,694847533,756065159,899809343],[2147483647,3743895347,4295032837,5949670231,6607882123,8753196421]]),e.primeSeeds=d,e.primes=o.memoize(t=>{const[e,n,r,s,o,a]=d(t%i.SeedCount);return[...[r/e,s/n,o/r,a/s].map(t=>u.sigFigs(t,5)),r]},1*a.minuteMs,256)},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(92),s=n(14),o=n(26),a=n(1),u=n(0),l=n(12),c=n(31),d=n(5);function h(t){return t.toDateTime().toFormat(l.Settings.assetSubdirectoryDatestampFormat.valueOrDefault).split(/[\\\/]/)}e.directoryForDate=h;e.AssetFileRepository=class{constructor(t,e){this.root=t,this.copyAssets=e,this.logger=a.mkLogger("AssetFileRepository")}directoryForDate(t){return this.root.join(...h(t))}importFile(t){return i(this,void 0,void 0,function*(){if(!this.copyAssets())return t;if(yield t.isDescendantOf(this.root))return this.logger.debug("no-op: "+t+" already contained by "+this.root),t;this.logger.debug("importing "+t);const e=yield c.readTags(t);if(null==e)throw new Error(t.nativePath+" has no tags (so, no createdAt)");const n=u.map(e.capturedAt,t=>o.toFuzzyDate(t.date));if(null==n)throw new Error(t.nativePath+" has no capturedAt");if(null==n.year||null==n.month||null==n.day)throw new Error(t.nativePath+" capturedAt has insufficient precision: "+e.capturedAt);const i=this.directoryForDate(n);if(null==(yield i.mkdirp()))throw new Error("Cannot create destination directory, "+i.nativePath+" for "+t.nativePath);const s=yield i.children(),a=yield t.size(),l=yield r.filter(s,t=>t.size().then(t=>t===a)),d=yield t.sha();if(l.length>0){const e=yield r.filter(l,t=>t.sha().then(t=>t===d));if(e.length>0){const n=e[0];return this.logger.info(t+" matches "+n),this.handleSidecars(t,n)}}const h=yield i.join(t.base).ensureNew();return this.logger.info("Copying...",{src:t.nativePath,dest:h.nativePath}),this.handleSidecars(t,yield t.copyFile(h))})}handleSidecars(t,e){return i(this,void 0,void 0,function*(){const n=u.orElse(yield t.sidecars(),[]);for(const t of n)yield this.handleSidecar(t,e);return d.isNotEmpty(n)&&s.emitFileChanged(e.nativePath),e})}handleSidecar(t,e){return i(this,void 0,void 0,function*(){for(const n of u.orElse(yield e.sidecars(),[]))if(yield c.sidecarEql(t,n))return void this.logger.info("handleSidecar(): metadata already exists.",{srcSidecar:t,destSidecar:n,dest:e});const n=yield e.parent().join(e.name+t.ext).ensureNew({emptyIsNew:!0});return t.copyFile(n)})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(45),r=n(16),s=n(4),o=n(3);e.OS=o.lazy(()=>[i.platform(),i.release(),"on",i.arch()].join(" ")),e.CPUs=o.lazy(()=>s.uniqCount(i.cpus().map(t=>t.model)).map(t=>`${t.count} × ${t.t}`).join(", "),r.minuteMs)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(3),r=n(12);e.sentryEnabled=i.lazy(()=>r.isProd&&r.Settings.reportErrors.valueOrDefault),r.Settings.reportErrors.addListener(()=>e.sentryEnabled.clear())},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(22),s=n(35),o=n(8),a=n(15),u=n(21),l=n(3),c=n(2),d=n(51),h=n(11),f=n(1),p=n(7),m=n(0),g=n(81),y=n(255);function v(t){return null!=t&&p.gt0(t.pid)&&p.gt0(t.lastTouchedTime)&&o.notBlank(t.hostname)}e.isFsLockInfo=v;e.FsFileLock=class extends u.EndableWrapper{constructor(t){super("FsFileLock("+t.lockfileJson.baseWithGrandparent+")#"+r.pid,()=>this.maybeRelease()),this.opts=t,this.currentlyAcquired=!1,this.lostLock=!1,this.p=new d.Promises,this.state=()=>this.p.serial(this.name+".state()",()=>this._state()),this.acquire=()=>this.p.serial(this.name+".acquire()",()=>this._acquire()),this.watcher=l.lazy(()=>(this.logger.debug("setting up new watcher..."),new y.FsWatcher(this.opts.lockfileJson,{depth:this.opts.watchDepth,changeListener:()=>(this.logger.debug("watcher.changeListener()"),this.reacquire())}))),this.refreshTimer=l.lazy(()=>(this.logger.debug("setting up refreshTimer..."),s.setInterval(()=>i(this,void 0,void 0,function*(){return this.logger.debug("refreshTimer().on interval..."),this.reacquire()}),this.reacquireEveryMs))),this.logger=f.mkLogger(this.name),this.reacquireEveryMs=Math.floor(t.staleMs/2),u.addCleanupEndable(this)}maybeRelease(){return this.releaseCleanup({removeJson:this.currentlyAcquired})}locked(){return i(this,void 0,void 0,function*(){const t=yield this.state();return null!=t.info&&!t.acquired})}lostParent(){return i(this,void 0,void 0,function*(){return!!(yield this.opts.lockfileJson.parent().clear().isNotDirectory())&&(this.logger.warn("lostParent(): parent dir is missing"),yield this.releaseCleanup({removeJson:!1}),!0)})}acquired(){return i(this,void 0,void 0,function*(){return(yield this.state()).acquired})}_acquire(){return i(this,void 0,void 0,function*(){if(this.currentlyAcquired&&(yield this.lostParent()))return;if(this.lostLock)return{acquired:!1};const t=this.currentlyAcquired,e=yield this._state();if(t&&!e.acquired)return this.lostLock=!0,this.logger.warn("acquire(): failed, we lost the lock",e),e;if(null!=e.info&&!e.acquired)return yield this.releaseCleanup({removeJson:!1}),this.logger.warn("acquire(): failed, someone else has the lock",e),e;if(u.ending())return;const n={hostname:this.opts.hostname,pid:r.pid,lastTouchedTime:Date.now(),lastTouchedTimeIso:h.isoNow()},i=()=>this.opts.lockfileJson.writeJSON(n,{spaces:2});return null==(yield m.mapOr(this.watcher.prior(),t=>t.withoutDetectingChange(i),i))?(yield this.releaseCleanup({removeJson:!0}),this.logger.warn("Failed to write lockfile"),{info:void 0,acquired:!1}):(this.logger.log(this.currentlyAcquired?"debug":"info","Lock "+(this.currentlyAcquired?"re":"")+"acquired",n),this.currentlyAcquired=!0,this.watcher(),this.refreshTimer(),{info:n,acquired:!0})})}_state(){return i(this,void 0,void 0,function*(){if(this.currentlyAcquired){const t=this.opts.lockfileJson;if((yield t.notExists())||(yield t.parent().clear().isNotDirectory())||(yield t.parent().parent().clear().isNotDirectory()))return yield this.releaseCleanup({removeJson:!1}),this.logger.warn("state(): parent directories are missing after acquisition"),{info:void 0,acquired:!1}}const t=yield c.thenAnd(this.opts.lockfileJson.isNonEmpty(),()=>i(this,void 0,void 0,function*(){return a.Opt(yield this.opts.lockfileJson.readJSON()).filter(v).get()})),e=this.opts.hostname===m.map(t,t=>t.hostname),n=r.pid===m.map(t,t=>t.pid),s=e&&n,o=m.map(t,t=>Date.now()-t.lastTouchedTime),u=m.map(o,t=>t-this.opts.staleMs),l=p.gt0(u),d=e&&!n&&null!=t&&(yield g.pidNotExists(t.pid));return null==t||s||l||d?null!=t&&(l||d)?(this.logger.info("state(): prior lockfile has expired, cleaning up.",{info:t,acquired:s,expiredMs:u,fileExpired:l,pidExpired:d}),yield this.releaseCleanup({removeJson:!0}),{info:void 0,acquired:!1}):(this.logger.debug("state(): lockfile is either acquired or available",{info:t,acquired:s,expiredMs:u,fileExpired:l,pidExpired:d}),{info:t,acquired:s}):(yield this.releaseCleanup({removeJson:!1}),this.logger.info("state(): acquired by someone else",{info:t,acquired:s,expiredMs:u}),{info:t,acquired:!1})})}reacquire(){return i(this,void 0,void 0,function*(){return this.p.maybeRun(this.name+".reacquire()",()=>i(this,void 0,void 0,function*(){return this.currentlyAcquired?this._acquire():void 0}))})}releaseCleanup(t){return i(this,void 0,void 0,function*(){m.map(this.refreshTimer.clear(),s.clearInterval),yield m.map(this.watcher.clear(),u.end);const e=this.currentlyAcquired;return this.currentlyAcquired=!1,e&&this.opts.onLockLoss(),!!t.removeJson&&(this.logger.info("Releasing lockfile",{acquiredPrior:e}),null!=(yield this.opts.lockfileJson.unlink()))})}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(43),s=n(147),o=n(6),a=n(4),u=n(21),l=n(51),c=n(1);e.FsWatcher=class extends u.EndableWrapper{constructor(t,e){super("FsWatcher("+t+")",()=>{this.watchers.forEach(t=>t.close())},()=>this.closed),this.file=t,this.p=new l.Promises,this.watchers=[],this.changeListeners=[],this.closed=!1,this.paused=!1,this.detectChange=()=>this.p.maybeRun(this.name+".detectChange",()=>i(this,void 0,void 0,function*(){const t=yield this.file.clear().sha();t!==this.priorSha&&(this.logger.info("detectChange(): SHA changed.",{priorSha:this.priorSha,currSha:t}),this.priorSha=t,this.changeListeners.forEach(t=>t()))})),this.logger=c.mkLogger("FsWatcher("+t+", depth:"+e.depth+")"),o.map(e.changeListener,t=>this.addChangeListener(t)),this.watchers.push(...t.selfAndParents(e.depth).map(n=>{const i=n===t&&o.orElse(e.recursive,!1);return this.logger.info("Watching "+n,{recursive:i}),r.watch(t.nativePath,{persistent:!1,recursive:i},this.listener.bind(this))})),u.addEndable(o.orElse(e.rank,"first"),this)}withoutDetectingChange(t){return i(this,void 0,void 0,function*(){try{return this.paused=!0,yield t()}finally{s.later(()=>this.paused=!1,100)}})}addChangeListener(t){this.changeListeners.push(t)}removeChangeListener(t){a.remove(this.changeListeners,t)}listener(t,e){return i(this,void 0,void 0,function*(){this.logger.trace("listener()",{event:t,_filename:e,paused:this.paused}),"close"===t?this.closed=!0:this.paused||(yield this.detectChange())})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(45),r=n(35),s=n(6),o=n(17),a=n(21),u=n(3),l=n(1),c=n(67),d=n(7),h=n(12);e.AlwaysIdle={idlePct:()=>100,cpuCount:3,busyPct:()=>0,end:()=>void 0};const f=u.lazy(()=>l.mkLogger("CpuUsage"));e.DefaultCheckIntervalMs=1e3;class p{constructor(t=e.DefaultCheckIntervalMs,n=2){this.checkIntervalMs=t,this.sampleCount=n,this._ended=!1,this.busyPctAvg=new c.Average(n),this.timer=r.setInterval(()=>this.sample(),t),this.sample(),a.addFirstEndable(new a.EndableWrapper("CpuUsage("+t+")",()=>r.clearInterval(this.timer)))}get cpuCount(){return s.map(this.last,t=>t.busyTimes.length)}end(){this._ended||(this._ended=!0,r.clearInterval(this.timer))}idlePct(){return s.map(this.busyPct(),t=>100-t)}busyPct(){return d.mapFinite(this.busyPctAvg.weightedAvg,o.round)}sample(){const t=this.last;if(null!=t&&Date.now()-t.at<this.checkIntervalMs/2)return;const e=new g;null!=t&&t.cpuCount===e.cpuCount?d.mapFinite(e.busyPct(t),t=>{this.last=e,this.busyPctAvg.push(t)}):this.last=e}}function m(t){const e=t.times;return e.user+e.nice+e.sys+e.irq}p.instance=u.lazy(()=>h.isTest?e.AlwaysIdle:new p),e.CpuUsage=p;class g{constructor(t=i.cpus()){this.at=Date.now(),this.busyTimes=t.map(m),this.idleTimes=t.map(t=>t.times.idle)}get cpuCount(){return this.busyTimes.length}busyPct(t){if(t.at>this.at)return t.busyPct(this);{let e=0,n=0;for(let i=0;i<this.cpuCount;i++)e+=this.busyTimes[i]-t.busyTimes[i],n+=this.idleTimes[i]-t.idleTimes[i];const i=e+n,r=o.round(100*e/i),s=isFinite(r)&&r>=0&&r<=100;return s||f().warn("busyPct(): invalid result",{result:r,busyMs:e,idleMs:n}),s?r:void 0}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(36);e.Work=class{constructor(t,e){this.name=t,this.f=e,this._started=!1,this.d=new i.Deferred("Work("+t+")")}get started(){return this._started}get running(){return this.d.pending&&this._started}get settled(){return this.d.settled}get pending(){return this.d.pending}get promise(){return this.d.promise}start(){if(!this._started){this._started=!0;const t=this.f();this.d.observe(t)}return this.d}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(80),s=n(44),o=n(37),a=n(21),u=n(2),l=n(51),c=n(153),d=n(10),h=n(11),f=n(25),p=n(14),m=n(88),g=n(54),y=n(1),v=n(90),w=n(0),b=n(12),S=n(19),P=n(154),M=n(259),x=h.minuteMs,E=2,_=5*h.secondMs,k={requestTTL:x,retriesPerRequest:5,delayBetweenRetries:b.isTest?100:_,maxPendingRequests:10,ee:p.eventEmitter};let T=0;e.Client=class{constructor(t,e,n={}){this.streamFactory=e,this._ended=!1,this.mkStreamRate=new v.Rate(h.minuteMs),this.times=new c.PromiseTimer,this.mkStream=l.oneRunAtATime(this.name+".mkStream",()=>i(this,void 0,void 0,function*(){const t=this.needNewStream();if(this.logger.info("mkStream()",{needNewStream:t}),t){this.mkStreamRate.onEvent(),this.logger.info("Making new stream...");try{const t=yield this.streamFactory();if(null==t)throw new Error("streamFactory() returned null");this.logger.info("Opened stream"),t.on("end",t=>this.onFinish("on(end)",t)),t.on("close",t=>this.onFinish("on(close)",t)),t.on("error",t=>this.onError("stream error",t)),m.onDataChunked(t,"\n",t=>this.onData(t)),this._stream=t}catch(t){return this._stream=void 0,this.onError("streamFactory rejection",t)}}})),this.name="rpc.Client("+t+"#"+T+++")",this.logger=y.mkLogger(this.name),this.opts=Object.assign({},k,n),this.pending=new s.TTLMap(3*this.opts.requestTTL),a.addServiceEndable(this)}get ended(){return this._ended}get eventEmitter(){return this.opts.ee}end(){return this.logger.info("end()",{ending:a.ending(),timings:this.times.report(),pendingSize:this.pending.size}),this._ended=!0,this.pending.clear(),this.close()}ping(){return this.request("ping")}ready(t=E){return i(this,void 0,void 0,function*(){if(this.ended)return this.logger.debug("ready(): false (ended)"),!1;const e=[...this.pending.values()],n=e.filter(t=>t.pending).length,i=e.filter(t=>t.rejected).length;return n>this.opts.maxPendingRequests||i>=t?(this.logger.warn("Client is not ready",{pendingReqCnt:n,recentErrCnt:i}),!1):null!=(yield this.stream())})}request(t,e){return i(this,void 0,void 0,function*(){if(this.ended)throw new f.WrappedError({message:"client is ending",fatal:a.ending()});return r.retryOnReject(()=>this.submit(t,e),{maxRetries:this.opts.retriesPerRequest,onRetryWaitUntil:t=>o.delay(this.opts.delayBetweenRetries*t).then(()=>u.until(()=>this.ready(),this.opts.requestTTL)),errorIsRetriable:t=>S.toS(t).includes("(retry)")})})}submit(t,e){return i(this,void 0,void 0,function*(){if(this.ended){if(a.ending())return;throw new Error("client is ending")}if(d.blank(t))throw new Error("method cannot be blank");const n=yield this.stream();if(null==n)throw this.logger.error("Stream is closed, cannot submit",{ended:this.ended,method:t,params:e}),new Error("closed stream");const i=P.uid(),r=new M.RequestResponse(i,t,e,this.times);return r.setTimeout(this.opts.requestTTL),this.pending.set(i,r),this.logger.debug("sending request",{id:i,method:t,params:e}),n.write(JSON.stringify({id:i,method:t,params:e})+"\n"),r.response})}close(){this.logger.info("close()",{ended:this.ended});const t=this._stream;return this._stream=void 0,g.end(t)}onData(t){if(!d.blank(t))try{const e=JSON.parse(t);if(d.blank(e.sid))throw new Error("response is missing server id");if(this.sid!==e.sid&&(null!=this.sid&&(this.logger.info("server id changed",{priorSid:this.sid,newSid:e.sid}),this.eventEmitter.emit("rpcServerChange")),this.sid=e.sid,a.ending()))return;if(null==e.id){if(d.notBlank(e.event))return this.logger.info("re-broadcasting event",e),void this.eventEmitter.emit(e.event,...w.orElse(e.args,[]));throw new Error("missing request id from response")}const n=this.pending.pop(e.id);null==n?this.logger.warn("unknown or stale request ID",{resp:e,pendingIds:[...this.pending.keys()]}):e.error?(n.reject(e.error.message||e.error),this.logger.warn("Rejected",{resp:e,rr:n})):(n.resolve(e.result),this.logger.debug("Resolved",e.result))}catch(e){this.logger.warn("invalid input: "+t,e)}}onError(t,e){return i(this,void 0,void 0,function*(){this.logger.warn(t+" onError(): "+w.map(e,t=>t.stack||t)),yield this.close(),this.ended||!1!==(yield this.restart())||this.logger.warn("Too many recent errors, we'll try reconnecting again in a bit")})}restart(){return i(this,void 0,void 0,function*(){if(this.logger.info("restart()",{ended:this.ended}),this.ended)return!1;if(this.mkStreamRate.msSinceLastEvent<5*h.secondMs||this.mkStreamRate.eventsPerMinute>10)return this.logger.warn("restart(): rate too high. Vetoing...",this.mkStreamRate),!1;if(this.close(),null!=(yield this.stream())){const t=[...this.pending.values()];return this.pending.clear(),this.logger.info("restart(): got a new socket, resubmitting "+t.length+" jobs now:"),t.forEach(t=>t.reject("restarting (retry)")),t.forEach(t=>t.d.promise.catch(()=>{})),!0}return this.logger.warn("restart(): no new stream."),!1})}needNewStream(){return!this.ended&&null==this._stream}stream(){return i(this,void 0,void 0,function*(){return this.needNewStream()&&(yield this.mkStream()),this._stream})}onFinish(t,e){if(!this.ended)return this.logger.info("onFinish",{source:t,error:e}),null==e||!1===e?this.restart():this.onError(t,e)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(42),r=n(36),s=n(0);e.RequestResponse=class{constructor(t,e,n,i){this.id=t,this.method=e,this.params=n,this.timer=i;const s="rpc.RequestResponse("+e+")#"+t;this.d=new r.Deferred(s)}[i.inspect.custom](){return{ctor:"RequestResponse",id:this.id,method:this.method,params:this.params,response:this.d}}get pending(){return this.d.pending}setTimeout(t){this.d.setTimeout(t)}resolve(t){this.d.pending&&(this.d.resolve(t),s.map(this.d.settledMs,t=>this.timer.push(this.method,t)))}reject(t){this.d.reject(t)}get rejected(){return this.d.rejected}get response(){return this.d.promise}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(3),s=n(2),o=n(0);e.JsonFileStore=class{constructor(t,e,n=o.identity,i=o.identity){this.file=t,this.onCreate=e,this.onRead=n,this.onWrite=i,this.prior=r.lazy(()=>s.thenAnd(this.file.exists(),()=>this.file.readJSON()))}read(){return i(this,void 0,void 0,function*(){const t=yield this.prior();return null!=t?this.onRead(t):s.thenMap(this.onCreate(),t=>this.write(t))})}write(t){return i(this,void 0,void 0,function*(){return yield this.file.writeJSON(yield this.onWrite(t),{spaces:2}),this.prior.set(Promise.resolve(t)),t})}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(192),s=n(17),o=n(44),a=n(11),u=n(262),l=n(265);e.Previews=class{constructor(t){this.root=t,this.id2ap=new o.TTLMap(2*a.minuteMs)}build(t,e,n=!1){return i(this,void 0,void 0,function*(){return this.apb(t,e).build(n)})}apb(t,e){return new u.AssetPreviewBuilder(this.ap(t),e)}ap(t){const e=this.id2ap.get(r.id2id(t));if(null!=e&&r.idEql(t,e.assetId))return e;{const e=new l.AssetPreviews(this.root,t);return s.isNumber(t)?e:(this.id2ap.set(r.id2id(t),e),e)}}clearAssetId(t){this.id2ap.delete(t)}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(126),s=n(42),o=n(5),a=n(6),u=n(3),l=n(2),c=n(25),d=n(32),h=n(1),f=n(31),p=n(243),m=n(56),g=n(263),y=n(136),v=n(264),w=n(163);e.AssetPreviewBuilder=class{constructor(t,e){this.ap=t,this.assetFiles=e,this.nativePath2info=u.lazy(()=>i(this,void 0,void 0,function*(){const t=yield l.thenCompact(this.assetFiles.map(t=>l.thenMap(d.PosixFile.forUri(t.uri),e=>({af:t,pf:e}))));return new Map(t.map(t=>[t.pf.nativePath,t]))})),this.posixFiles=u.lazy(()=>this.nativePath2info().then(t=>[...t.values()].map(t=>t.pf))),this.logger=h.mkLogger("AssetPreviewBuilder("+t.assetId+")")}[s.inspect.custom](){return{ctor:"AssetPreviewBuilder",assetId:this.ap.assetId,assetFiles:this.assetFiles}}build(t){return i(this,void 0,void 0,function*(){return this.ap.withLock(()=>i(this,void 0,void 0,function*(){const e=yield p.sortShownFiles(yield this.posixFiles());for(;o.isNotEmpty(e);){const n=e.pop();try{return yield this._build(n,t)}catch(t){this.logger.warn("Failed to set shown file to "+n,t)}}throw new Error("no files are available")}))})}_build(t,e){return i(this,void 0,void 0,function*(){if(null==t)throw new Error("buildOrig(): best was undefined");const n=yield l.thenMap(this.nativePath2info(),e=>e.get(t.nativePath));if(null==n)throw new Error("IE build(): missing assetFile");const i=yield t.size(),s=yield t.thisOrSidecareMaxMtimeMs(),o=yield t.sha();if(null==i||null==s||null==o)throw new Error("IE build(): missing stat info for best file "+t);const u=yield f.readTags(t);if(null==u)throw new Error("IE build(): missing tags for best file "+t);const d=u.dimensions,h=u.mimetype,p=u.rotation;if(null==d||null==h)throw new Error("IE build(): missing tags for best file "+t+": "+JSON.stringify({origDim:d,origMime:h}));const b=g.fitSizes(d,p,h),S={assetId:n.af.assetId,assetFileId:n.af.id,uri:n.af.uri,path:t.nativePath,mimetype:h,width:d.width,height:d.height,maxStatMs:s,filesize:i,sha:o,rotation:p,fitSizes:b.map(([,t])=>t.name).join(",")};if(!e){const e=yield this.ap.readInfo.refresh();if(null!=e){if(e.assetId!==S.assetId)throw new Error("IE build(): Mismatched asset IDs for "+t+": "+JSON.stringify({priorInfo:e,info:S}));if(null!=e.sha&&e.sha===S.sha&&e.rotation===S.rotation&&g.equivalentFitSizes(e.fitSizes.split(","),S.fitSizes.split(",")))return this.logger.debug("build(): no-op: SHA and rotation match.",{info:S,priorInfo:e}),yield this.ap.writeInfo(S),S}}if(this.logger.debug("Rebuilding all previews from "+n.af.uri,{assetId:n.af.assetId,best:t,info:S}),null==(yield this.ap.parent.mkdirp()))throw new Error("build(): Failed to create previews directory, "+this.ap.parent+" for "+t);const P=yield this.ap.existingFiles(),M=yield w.sharpReadable(t,y.ImageSize.largestFit().max);if(null==M)throw new Error("build(): "+t+" is not readable by sharp."+c.NonRetriableErrorFlag);const x=r(M.nativePath);0!==p&&(x.rotate(p),this.logger.debug("build(): rotating "+p+"°")),M.name.toLowerCase().includes("thumbnail")&&x.trim();const E=[];let _,k;{let t=x.clone(),e=d;for(const[n,i]of b){const r=Date.now(),s=e,o=this.ap.fileForWidth(i.reducer.name,n.width).wip();if(t=yield v.applyAndClone(i.resize(n,t)),e=n,null==k){null!=y.ImageSize.largestSq().outputSize(n)?(k=t.clone(),_=n):(k=x,_=d)}yield i.toJpeg({path:o.nativePath,sh:t.clone(),outputSize:n}),this.logger.debug("resize("+i.name+") "+m.dimToS(s)+" -> "+m.dimToS(n)+" in "+(Date.now()-r)+" ms"),E.push(o)}}null==k&&(k=x,_=d);for(const t of y.ImageSize.sq()){const e=Date.now(),n=_,i=t.outputSize(a.orElse(_,d));if(null==i)continue;const r=this.ap.fileForWidth(t.reducer.name,i.width).wip();k=yield v.applyAndClone(t.resize(i,k)),_=i,yield t.toJpeg({path:r.nativePath,sh:k.clone(),outputSize:i}),E.push(r),this.logger.debug("resize("+t.name+") "+m.dimToS(n)+" -> "+m.dimToS(i)+" in "+(Date.now()-e)+" ms")}return yield Promise.all(P.map(t=>t.unlink())),yield Promise.all(E.map(t=>t.unwip())),yield this.ap.writeInfo(S),S})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(5),r=n(17),s=n(1),o=n(56),a=n(136),u=s.mkLogger("FitSizes");function l(t){return"qhd"===t?"wvga":"uhd"===t?"uhd4k":t}e.fitSizes=function(t,e,n){const i=a.ImageSize.fit();u.debug("fitSizes()",{dim:t,rotation:e,sizes:i});const s=i.map(e=>[e.outputSize(t),e]).filter(([t])=>null!=t);let l=t;return s.filter(([t],i)=>(function(t,i){const s=o.dmegapixels(l)/o.dmegapixels(t),a=0===i&&("image/jpeg"!==n||r.gt0(e))||s>3||o.dmegapixels(t)-o.dmegapixels(l)>2.5;return a&&(l=t),a})(t,i))},e.equivalentFitSizes=function(t,e){return i.includesAll(i.compactBlanks(t).map(l),i.compactBlanks(e).map(l))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(126),s=n(9);e.applyAndClone=function(t){return i(this,void 0,void 0,function*(){const e=yield t.raw().toBuffer({resolveWithObject:!0});return r(e.data,{raw:s.pick(e.info,"width","height","channels")})})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(192),s=n(5),o=n(170),a=n(102),u=n(17),l=n(123),c=n(4),d=n(3),h=n(2),f=n(266),p=n(1),m=n(7),g=n(0),y=n(13),v=n(31),w=n(56),b=n(169),S=n(149),P=n(93);e.AssetPreviews=class{constructor(t,e){this.previewsRoot=t,this.readInfo=d.lazy(()=>this.infoJson().readJSON()),this.logger=p.mkLogger("AssetPreviews(assetId:"+r.id2id(e)+")"),this.assetId=r.id2id(e),this.urls=new o.AssetUrls(e);const n=y.leftPad(this.assetId,8,"0"),i=y.splitEvery(n,3);this.basename=i.pop()+"-",this.parent=t.join(...i)}withLock(t){return f.withLock({file:this.infoJson(),staleMs:P.MaxSyncFileTimeoutMs,timeoutMs:P.MaxSyncFileTimeoutMs},t)}existingFiles(){return h.thenOrElse(this.parent.childFiles(t=>t.base.startsWith(this.basename)),()=>[])}existingJpgs(){return h.thenOrElse(this.parent.childFiles(t=>t.base.startsWith(this.basename)&&".jpg"===t.ext),()=>[])}deleteAll(){return i(this,void 0,void 0,function*(){this.parent.clear();const t=yield this.existingFiles();if(t.length>30)throw new Error("INTERNAL ERROR (yikes, > 30 existing files?!)");return yield Promise.all(t.map(t=>t.unlink())),t})}file(t){return this.parent.join(this.basename+t)}mp4(){return this.file("video.mp4")}infoJson(){return this.file("info.json")}writeInfo(t){return this.readInfo.clear(),this.infoJson().writeJSON(t,{spaces:2})}fileForWidth(t,e){return this.file(t+"-w"+e+".jpg")}filesForReducer(t){const e=this.basename+t+"-";return this.existingFiles().then(t=>t.filter(t=>t.base.startsWith(e)))}largestFileForReducer(t){return i(this,void 0,void 0,function*(){const e=yield this.filesForReducer(t);return c.greatestBy(e,t=>g.orElse(g.map(x(this.previewsRoot,t),t=>t.width),0))})}widths(t){return i(this,void 0,void 0,function*(){const e=yield this.filesForReducer(t);return c.sort(s.compact(e.map(t=>g.map(x(this.previewsRoot,t),t=>t.width))))})}posterLink(){return i(this,void 0,void 0,function*(){const t=yield this.widths(a.ReducerNames.fit);return this.urls.imgLink(a.ReducerNames.fit,Math.max(...t))})}imgAttrs(t,e=!1,n=!0){return i(this,void 0,void 0,function*(){if(e||t!==a.ReducerNames.sq){const e=t===a.ReducerNames.fit?yield this.readInfo():void 0;return this.urls.imgAttrs(t,yield this.widths(t),n,e)}return this.urls.sqImgAttrs(n)})}setRotation(t){return i(this,void 0,void 0,function*(){return this.withLock(()=>i(this,void 0,void 0,function*(){const e=g.orElse(l.normalizeRotation(t),0),n=[],i=yield this.readInfo();if(null==i)throw new Error("IE: Missing JSON info for assetId:"+this.assetId);try{const r=g.orElse(i.rotation,0),s=l.normalizeRotation(e-r);if(0===s)return void this.logger.debug("setRotation(): no-op",{priorRotation:r,newRotation:e});const o=yield this.existingJpgs();for(const t of o){const e=x(this.previewsRoot,t),i=yield b.dimensions(t);if(null==e||null==e.reducer||null==i)this.logger.warn("setRotation(): bad thumb "+t,{pi:e,dims:i});else{const r=w.maybeFlip(i,s),o=this.fileForWidth(e.reducer,r.width).wip();yield S.rotate(t,o,s),n.push(o)}}const a=this.mp4();if(yield a.exists()){const e=a.wip();n.push(e),yield a.copyFile(e),yield v.writeTags(e,{Rotation:t})}return yield Promise.all(o.map(t=>t.unlink())),yield Promise.all(n.map(t=>t.unwip())),this.parent.clearThisAndParent(),i.rotation=e,w.maybeFlipInPlace(i,s),yield this.writeInfo(i),i}catch(t){throw yield Promise.all(n.map(t=>t.unlink())),t}}))})}};const M=p.mkLogger("extractPreviewInfo");function x(t,e){const n=e.posixPathFrom(t).replace(/\//g,"").split("-"),i=m.toInt(n[0]),r=n[1],s=a.isReducerName(r)?r:void 0,o=m.extractInt(n[2]);return u.gt0(i)?{file:e,assetId:i,reducer:s,width:o}:void M.warn("Failed to extract preview info",{file:e,previewsRoot:t,arr:n,assetId:i,reducer:s,width:o})}e.extractPreviewInfo=x},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(37),s=n(2),o=n(50),a=n(11),u=n(1),l=n(7),c=n(0),d=n(154);function h(t){return t.sibling("."+t.base+".lock")}e.lockdir=h;class f{constructor(t){this.opts=t,this.id=d.uid(),this._acquired=!1,this.refreshTimer=void 0,this.logger=u.mkLogger("FsDirLock("+t.file+")#"+this.id),this.lockdir=h(t.file),this.lockfile=this.lockdir.join(this.id)}get acquired(){return this._acquired}tryAcquire(){return i(this,void 0,void 0,function*(){const t=c.orElse(yield this.lockdir.clear().children(),[]);if(this.logger.debug("tryAcquire()",{lockfiles:t.map(t=>t.base)}),t.length>0&&t[0].base===this.id)return this.logger.info("Acquired"),this._acquired=!0,!0;const e=Date.now()-this.opts.staleMs;for(const n of t)l.lt(yield n.mtimeMs(),e)&&(this.logger.warn("Child "+n.base+" is stale. unlinking."),yield n.unlink());return!1})}acquire(){return i(this,void 0,void 0,function*(){if(this._acquired)return!0;const t=()=>this.lockfile.touch().then(()=>this.logger.debug("Touched lockfile"));yield t(),this.refreshTimer=o.setUnrefInterval(t,this.opts.staleMs/2);const e=yield s.until(()=>this.tryAcquire(),this.opts.timeoutMs);return e||(yield this.release()),e})}release(){return i(this,void 0,void 0,function*(){this.logger.debug("release()"),this._acquired=!1,c.map(this.refreshTimer,t=>clearInterval(t)),this.refreshTimer=void 0;try{return yield this.lockfile.unlink(),r.later(()=>i(this,void 0,void 0,function*(){(yield this.lockdir.rmdir("trace"))&&this.logger.debug("release() unlinking empty lockdir",{lockdir:this.lockdir.nativePath})}),1*a.secondMs),this.logger.info("Released"),!0}catch(t){return this.logger.warn("Lockfile cleanup failed, but we'll recover later."+t),!1}})}withLock(t){return i(this,void 0,void 0,function*(){if(this._acquired)return t(this);try{return(yield this.acquire())?yield t(this):void 0}finally{yield this.release()}})}}e.FsDirLock=f,e.withLock=function(t,e){return i(this,void 0,void 0,function*(){return new f(t).withLock(e)})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(191),s=n(22),o=n(8),a=n(9),u=n(105),l=n(4),c=n(21),d=n(58),h=n(3),f=n(2),p=n(153),m=n(50),g=n(10),y=n(11),v=n(14),w=n(88),b=n(54),S=n(1),P=n(0),M=n(248),x=n(12),E=n(19),_=n(193),k=n(249),T=S.mkLogger("rpc.Server");function O(){return"pong from PID "+s.pid+" at "+new Date}!function(t){t.broadcast=function(t,...e){return i(this,void 0,void 0,function*(){return T.warn("broadcast sent to no-op",{event:t,args:e}),!1})}}(e.NoOpBroadcaster||(e.NoOpBroadcaster={}));e.Server=class{constructor(t,e,n=!0){this.port=t,this.unref=n,this._ended=!1,this._ready=new d.Latch,this.openSockets=[],this.times=new p.PromiseTimer,this.onPause=()=>this.broadcast("pause"),this.onResume=()=>this.broadcast("resume"),this.handlers={},this.start=u.throttle(()=>i(this,void 0,void 0,function*(){if(!this.ended)return T.debug("start("+this.port+")"),this.server=r.createServer(this.onConnect.bind(this)),this.server.on("listening",()=>{this._ready.resolve()}),this.server.on("error",t=>i(this,void 0,void 0,function*(){yield this.onError("createServer",t),m.setUnrefTimeout(()=>this.start(),5e3)})),this.server.listen(this.port,x.Settings.exposeNetworkWithoutAuth.valueOrDefault?void 0:"127.0.0.1"),this.unref&&this.server.unref(),this._ready.promise}),5e3),this.end=h.lazy(()=>i(this,void 0,void 0,function*(){this._ended=!0,v.eventEmitter.removeListener("pause",this.onPause),v.eventEmitter.removeListener("resume",this.onResume),yield this.closeAllConnections(),yield b.close(this.server),T.info("timings:",this.times.report())})),this.name="Server:"+t,this.addHandlers(e),this.addHandler("ping",O),v.onPause(this.onPause),v.onResume(this.onResume),c.addFirstEndable(this),this.start()}serialize(t){return i(this,void 0,void 0,function*(){return JSON.stringify(Object.assign({sid:_.sid()},t))+"\n"})}addHandlers(t){const e=new Set(a.allKeys(new Object));a.allKeys(t).filter(n=>!e.has(n)&&"function"==typeof t[n]).forEach(e=>this.addHandler(e,t[e].bind(t)))}addHandler(t,e){null!=this.handlers[t]&&T.warn("addHandler(): overwriting",{name:t,priorHandler:this.handlers[t],newHandler:e}),this.handlers[t]=e}get ended(){return this._ended||c.ending()}get ready(){return this._ready.promise}closeAllConnections(){const t=this.openSockets.map(b.end);return this.openSockets.length=0,Promise.all(t)}broadcast(t,...e){return this.sendAll({event:t,args:e})}sendAll(t,e="write"){return i(this,void 0,void 0,function*(){const n=yield this.serialize(t),i=[...this.openSockets];let r=i.length;return i.forEach(t=>t[e](n,()=>r--)),f.until(()=>r<=0,1e3)})}onConnect(t){T.info("Connection from "+b.remoteDesc(t)),this.unref&&t.unref(),this.openSockets.push(t),t.on("end",()=>{T.info("Closing connection from "+b.remoteDesc(t)),l.remove(this.openSockets,t)}),t.on("error",e=>i(this,void 0,void 0,function*(){T.warn("on error from "+b.remoteDesc(t)+": "+e),yield this.onError("socket",e),t.end()}));try{w.onDataChunked(t,"\n",e=>this.onRequest(e,t))}catch(e){T.warn("Caught error from "+b.remoteDesc(t)+": "+e),t.end()}}onRequest(t,e){return i(this,void 0,void 0,function*(){if(T.debug("onRequest()",t),g.blank(t))return;let n="missing",i="missing";try{const r=JSON.parse(t);return o.mapNotBlank(r.id,t=>n=t),o.mapNotBlank(r.method,t=>i=t),yield k.rpcAllowed(),yield this.times.time(i,()=>this.handle(n,i,r.params,e))}catch(i){T.warn("invalid request",{line:t,error:i}),e.write(yield this.serialize({id:n,error:P.orElse(i.message,()=>E.toS(i))}))}})}handle(t,e,n,r){return i(this,void 0,void 0,function*(){T.debug("handle() called",{method:e,params:n});const i=this.handlers[e];if(null==i)throw T.warn("bad handler request",{method:e,params:n,supported:a.keys(this.handlers)}),new Error("No handler for "+e);const{elapsedMs:s,result:o}=yield y.elapsedAsync(()=>null==n?i():i(n)),u=s<10?"debug":s<500?"info":"warn";T.log(u,"handle()",{method:e,elapsedMs:s,id:t,params:n,result:o}),r.write(yield this.serialize({id:t,result:o}))})}onError(t,e){return i(this,void 0,void 0,function*(){this.ended||M.onErr(t,e)})}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(269),s=n(25),o=n(1),a=n(9),u=n(97),l=n(119),c=n(108),d=n(156),h=n(277),f=n(118),p=n(278);class m extends h.RpcServiceHandlers{constructor(t){super(),this.db=t,this.advisoryLocks=new r.AdvisoryLocks,this.logger=o.mkLogger("DbServiceHandlers"),this.txs=f.Transactions.for(t),this.drl=new d.DbRequestLocal(t),m._instance=this}static instance(){if(null==this._instance)throw new s.WrappedError({message:"no DbServiceHandler instance",fatal:!0});return this._instance}acquireAdvisoryLocks(t){return i(this,void 0,void 0,function*(){return this.advisoryLocks.acquireAdvisoryLocks(t.names)})}releaseAdvisoryLocks(t){return this.advisoryLocks.releaseAdvisoryLocks(t.locks)}truncate(){return this.txs.tx("truncate",()=>{p.truncateTables(this.db)})}tableInfo(t){return this.txs.tx("tableInfo",()=>this.db.pragma(`table_info(${t})`))}tagRoots(){return this.txs.tx("tagRoot",()=>c.Tag.roots())}tagFindOrCreate(t){return this.txs.tx("tagFindOrCreate",()=>c.Tag.findOrCreate(t))}assetAddTags(t){return this.txs.tx("assetAddTags",()=>u.Asset.addTags(t.assetId,t.tagPaths))}assetRemoveTags(t){return this.txs.tx("assetRemoveTags",()=>u.Asset.removeTags(t.assetId,t.tagPaths))}assetArchive(t){return this.txs.tx("assetArchive",()=>u.Asset.archive(t))}findByIds(t){return this.txs.tx("findByIds",()=>l.ModelOpsLocal.forTableName(t.tableName).findByIds(t.ids))}insert(t){return this.txs.tx("insert",()=>{return l.ModelOpsLocal.forTableName(t.tableName).insert(t.model)})}upsert(t){return this.txs.tx("upsert",()=>l.ModelOpsLocal.forTableName(t.tableName).upsert(t.models))}batch(t){if(this.logger.debug("batch()",{requests:t}),!Array.isArray(t))throw new Error("Missing batch.requests");return this.txs.tx("batch",()=>t.map(t=>{const e=t.method;if(!d.DbMethods.includes(e))throw new Error("unknown method "+e);try{const n=a.maybeCall(this.drl,e,t);return this.logger.debug("batch()."+t.method,{req:t,result:n}),n}catch(e){throw this.logger.warn("batch() failed",{req:t,err:e}),e}}))}}e.DbServiceHandlers=m},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(154),s=n(5),o=n(16),a=n(15),u=n(44),l=n(1),c=n(58),d=n(2);class h{constructor(t){this.id=t,this.released=new c.Latch}}e.AdvisoryLockRequest=h;class f{constructor(t){this.name=t,this.locks=[],this.logger=l.mkLogger("AdvisoryLocks("+this.name+")")}get idle(){return 0===this.locks.length}acquire(){const t=r.uid(0),e=new h(t),n=[...this.locks];return this.locks.push(e),n.length>0&&this.logger.info("Waiting for "+n.length+" prior locks to complete..."),d.awaitAll(n.map(t=>t.released.promise)).then(()=>(this.logger.debug("acquired for "+t),t))}release(t){const e=this.locks.find(e=>e.id===t);if(null==e)return this.logger.error("release(): unknown UID",{id:t,currentLockIds:this.locks.map(t=>t.id)}),!1;const n=e.id===this.locks[0].id;return e.released.resolve(),s.filterInPlace(this.locks,e=>e.id!==t),n?this.logger.debug("released for "+t):this.logger.error("release(): premature release by "+t),n}}e.AdvisoryLock=f;e.AdvisoryLocks=class{constructor(t=10*o.minuteMs){this.locks=new u.TTLMap(t)}get busyLocks(){return s.toA(this.locks.values()).filter(t=>!t.idle).map(t=>t.name)}lockMaybeAvailable(t){return a.Opt(this.locks.get(t)).flatMap(t=>t.idle).getOrElse(()=>!0)}advisoryLockFor(t){return this.locks.getOrSet(t,()=>new f(t))}acquireAdvisoryLocks(t){return i(this,void 0,void 0,function*(){const e=s.compactBlanks(t).map(t=>this.advisoryLockFor(t)),n=[];if(!(yield d.until(()=>e.every(t=>t.idle),2*o.minuteMs,100)))throw new Error("Cannot acquire locks");try{for(const t of e){const e=yield t.acquire();n.push({name:t.name,lockId:e})}return n}catch(t){throw this.releaseAdvisoryLocks(n),t}})}releaseAdvisoryLocks(t){return t.reverse().every(t=>this.advisoryLockFor(t.name).release(t.lockId))}withAdvisoryLocks(t,e){return i(this,void 0,void 0,function*(){const n=[];try{return n.push(...yield this.acquireAdvisoryLocks(t)),yield e(n)}finally{this.releaseAdvisoryLocks(n)}})}}},function(t,e){t.exports=require("knex")},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(1),r=n(0),s=n(8),o=n(143),a=n(117),u=i.mkLogger("mkUpsertSql");e.mkUpsertSql=function(t,e,n){if("id"===e&&null==n[e]){const e=a.toSqlQuery(o.knex(t).insert(n));return u.info("no ucn, using simple insert",e),e}if("id"!==e&&null==n[e])throw new Error("Invalid "+t+": missing UCN "+e);const i=r.keys(r.without(n,e,"id","createdAt")).map(t=>t+"=$"+t).join(","),l=r.keys(n),c=l.map(t=>"$"+t),d=["INSERT INTO `",t,"`(",l.join(","),") VALUES (",c.join(","),`) ON CONFLICT(${e}) DO `];return s.blank(i)?d.push("NOTHING "):d.push(`UPDATE SET ${i} WHERE ${e} = $${e}`),{sql:d.join(""),bindings:n}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(3),o=n(2),a=n(38),u=n(7),l=n(5),c=n(66),d=n(116),h=n(273);class f{constructor(t){this.model=t,this.columnNames=s.lazy(()=>o.thenMap(c.dbClient().request("tableInfo",this.tableName),t=>t.map(t=>t.name)))}static forModel(t){const e=t;return a.getOrSet(this.instances,e.tableName,()=>new f(e))}get tableName(){return this.model.tableName}toModel(t){return o.thenMap(t,t=>this.model.fromJSON(t))}toModels(t){return t.then(t=>l.toA(t).map(t=>this.model.fromJSON(t)))}first(t,e){return d.dbr(e=>this.toModel(e.first(t)),e)}all(t,e){return d.dbr(e=>this.toModels(e.all(t)),e)}findOne(t,e){return d.dbr(e=>this.toModel(e.first(t)),e)}findById(t,e){return this.findOne(this.model.query().where({id:t}),e)}findByIds(t){return this.toModels(c.dbClient().request("findByIds",{tableName:this.tableName,ids:t}))}findOneBy(t,e){return this.first(this.model.queryBy(t),e)}findBy(t,e){return this.all(this.model.queryBy(t),e)}rows(t){return this.count(this.model.query(),t)}count(t,e){return d.dbr(e=>e.pluckfirst(t),e)}insert(t){return this.toModel(c.dbClient().request("insert",{tableName:this.tableName,model:this.model.toDbJSON(t)}))}upsertOne(t){return this.upsert([t]).then(t=>t[0])}get ucn(){return this.model.uniqueColumnName}upsert(t){return i(this,void 0,void 0,function*(){const e=yield this.columnNames();return this.toModels(c.dbClient().request("upsert",{tableName:this.tableName,models:t.map(t=>this.model.toDbJSON(t,e))}))})}delete(t,e){return r.mapNotEmpty(t.filter(u.gt0),t=>d.dbr(e=>e.run(this.model.query().delete().whereIn("id",t)),e))}}f.instances=new Map,f.fetchTableInfo=s.lazy(()=>h.remoteTableInfo().then(t=>f.tableInfo=t)),e.ModelOpsRemote=f},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(73),r=n(116);function s(t){const e=new i.MultiMap;return t.forEach(t=>e.add(t.tableName,{name:t.columnName,type:t.columnType})),e.entriesArray().map(([t,e])=>({tableName:t,columns:e}))}e.parseTableInfo=s;const o="SELECT \nm.tbl_name as tableName,\np.name AS columnName,\np.type AS columnType,\nFROM sqlite_master AS m\nLEFT JOIN pragma_table_info(m.name) AS p\nORDER BY m.tbl_name, p.cid";e.localTableInfo=function(t){return s(t.prepare(o).all())},e.remoteTableInfo=function(){return r.dbr(t=>t.all(o)).then(s)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(44),r=n(73);e.TTLMultiMap=class extends r.MultiMap{constructor(t){super(new i.TTLMap(t)),this.ttlMs=t,this.m=this.store}add(t,e){return this.m.touch(t),super.add(t,e)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.digits=function(t,e,n){const i=[];for(;t>0;){const n=t%e;i.push(n),t=Math.floor(t/e)}for(;null!=n&&i.length<n;)i.push(0);return i.reverse()}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(9),r=n(78);e.TagUrls=class{constructor(t){this.id=t}nextAssetBatch(t){const e={};return i.map(t,t=>e.capturedAtLt=t.getTime()),r.joinQuery(`/tag-gallery/${this.id}`,e)}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(12),s=n(40),o=n(74),a=n(71),u=n(91);e.RpcServiceHandlers=class{libraryPath(){return r.Settings.libraryPath.value}healthChecks(){return i(this,void 0,void 0,function*(){return u.healthChecks()})}mountpoints(){return s.mountpoints()}volumes(){return o.volumes()}paused(){return a.isPaused()}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(4),r=n(1),s=n(12),o=n(14),a=r.mkLogger("truncateTables()");e.truncateTables=function(t,...e){if(s.isProd)throw new Error("rejecting attempt to truncate in prod");o.emitClearCache();const n=i.isNotEmpty(e)?e:["AssetFile","AssetTag","Example","Progress","Tag","Asset"];return a.warn("truncating",n),n.map(e=>t.exec("DELETE FROM "+e))}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(39),s=n(3),o=n(32);e.localDbDir=s.lazy(()=>i(this,void 0,void 0,function*(){const t=o.PosixFile.for(r.App.getPath("userData")).join("localdb");return yield t.join("README.txt").writeTxt("\nThis folder is only used when your library is on a slow remote filesystem.\n\nYou will corrupt your library if you remove this directory while PhotoStructure is\nrunning.\n\nIf you have any questions, please visit <https://support.photostructure.com/>."),t}))},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(36),s=n(2),o=n(10),a=n(14),u=n(1),l=n(0),c=n(74),d=n(281),h=n(200),f=n(199),p=n(201),m=n(155);e.ModelDbJanitor=class{constructor(t,e){this.dataDir=t,this.localDbDir=e;const n="ModelDbJanitor("+t+")";this.logger=u.mkLogger(n),this.db=new r.Deferred(n+".db"),this.backup=new r.Deferred(n+".backup"),this.src=h.pathToDb(this.dataDir,"models"),this.backupDir=this.src.parent().join("backup"),this.archiveDir=this.backupDir.sibling("archive"),a.eventEmitter.on("modelArchive",this.archive.bind(this)),this.setup()}end(){return a.eventEmitter.removeListener("modelArchive",this.archive.bind(this)),s.tryAll([()=>l.map(this.backup.value,t=>t.onEnd())])}archive(t){return i(this,void 0,void 0,function*(){try{if(o.blank(t.$pk()))return void this.logger.info("Cannot archive model, missing PK",{model:t});const e=this.archiveDir.join(t.$tableName()).join(t.$pk()+".json");yield e.writeJSON(t.toJSON()),this.logger.info("Saved model to "+e,t)}catch(e){this.logger.info("Failed to save model",{err:e,model:t})}})}setup(){return i(this,void 0,void 0,function*(){try{yield this._setup()}catch(t){throw this.logger.error("setup failed: "+t,{dataDir:this.dataDir.nativePath}),this.db.reject(t),this.backup.reject(t),t}})}_setup(){return i(this,void 0,void 0,function*(){const t=yield this.backupDir.mkdirp();if(null==t)throw new Error("Failed to create models DB backup dir for "+this.src);const e=(yield this.src.exists())&&(yield s.thenOrElse(s.thenMap(c.volumeFor(this.dataDir.nativePath),t=>t.remote),()=>!1)),n=e?yield this.src.shaMs():void 0,i=e&&null!=n&&n>500?yield this.localDbDir():void 0;if(null!=i){this.logger.info("DB is on a slow remote drive. Setting up local db cache.");const e=h.pathToDb(i,"models");if(null==(yield e.parent().mkdirp()))throw new Error("Failed to make local db cache dir for "+e);const n=yield f.sqliteFiles(e);if(yield Promise.all(n.map(t=>t.unlink())),yield e.parent().mkdirp(),!(yield f.backupDb(this.src,e)))throw new Error("Failed to copy remote db to a local drive");this.logger.info("Local models db set up at "+e);const r=m.Model.db=yield h.dbSetup(i,"models"),s=new p.SqliteJanitor("models",r);this.backup.resolve(new d.DbBackup(s,e,t,this.src.parent())),this.db.resolve(r)}else{const e=m.Model.db=yield h.dbSetup(this.dataDir,"models"),n=new p.SqliteJanitor("models",e);this.backup.resolve(new d.DbBackup(n,this.src,t)),this.db.resolve(e)}this.logger.info("Finished setup",this.db.value)})}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(35),s=n(21),o=n(50),a=n(11),u=n(282),l=n(1),c=n(0),d=n(199);e.DefaultBackupFrequencyMs=1*a.hourMs,e.DefaultRetentionCount=12,e.stamp=function(t=new Date){return"."+a.filestampUTC(t)+"-"};e.DbBackup=class{constructor(t,n,i,r,a=(()=>void 0),c=e.DefaultRetentionCount,d=e.DefaultBackupFrequencyMs){this.janitor=t,this.srcDb=n,this.backupsDir=i,this.replaceDir=r,this.onBackupFinished=a,this.retentionCount=c,this.backupFrequency=d,d>0&&(this.timer=o.setUnrefInterval(()=>this.backup().catch(t=>this.logger.warn("backup failed",t)),d)),this.hanoi=new u.Hanoi(i,c),this.logger=l.mkLogger("DbBackup("+this.srcDb.baseWithGrandparent+" -> "+this.backupsDir.baseWithGrandparent+")"),s.addCleanupEndable(new s.EndableWrapper("DbBackup",()=>this.onEnd()))}verifyDb(t=this.srcDb){return d.verifyDb(t)}onEnd(){return i(this,void 0,void 0,function*(){return c.map(this.timer,t=>r.clearInterval(t)),this.timer=void 0,this.backup()})}backup(){return i(this,void 0,void 0,function*(){try{if(yield this.srcDb.clear().isEmpty())return this.logger.warn("backup(): srcDb is missing, giving up."),!1;this.logger.info("backup(): housekeeping...",{srcDb:this.srcDb.nativePath,backupsDir:this.backupsDir.nativePath}),yield this.janitor.run(),this.logger.info("backup(): starting backup...");const t=this.backupsDir.join(this.srcDb.base);if(!(yield d.backupDb(this.srcDb,t)))return!1;if(this.logger.info("backup(): backup taken. Verifying."),!(yield this.verifyDb(t)))return!1;this.logger.info("backup(): verified. Rotating files.");const e=yield d.sqliteFiles(t);if(null!=this.replaceDir)for(const t of e)yield t.copyFile(this.replaceDir);const n=(yield this.hanoi.next("")).toFilename();for(const t of e){const e=yield t.mv(t.withPrefix(n));this.logger.debug("mv "+t+" "+e)}for(const t of yield this.hanoi.staleFiles())this.logger.info("backup(): removing stale backup "+t),yield t.unlink();return this.logger.info("backup(): finished successfully"),!0}catch(t){return this.logger.error("Failed to back up db: "+t),!1}})}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(11),o=n(57),a=n(73),u=n(7),l=n(0);class c{constructor(t,e,n,i=s.filestampUTC()){this.seq=t,this.set=e,this.name=n,this.stamp=i}valueOf(){return this.toFilename()}toFilename(){return[this.stamp,"seq"+this.seq,"set"+this.set,this.name].join("-")}toFile(t){return t.join(this.toFilename())}static fromFile(t){return this.fromBasename(t.base)}static fromBasename(t){return l.map(this.parseRe.exec(t),t=>new c(parseInt(t[2],10),parseInt(t[3],10),t[4],t[1]))}}c.parseRe=/([-\d]{8,})-seq(\d+)-set(\d+)-(.+)$/,e.HanoiFile=c;e.Hanoi=class{constructor(t,e=10){this.root=t,this.sets=e,this.seq=this.fsMaxSeq().then(t=>({max:t+1})),this.mods=u.times(e+1,t=>Math.pow(2,e-t))}set(t){return this.sets-this.mods.findIndex(e=>t%e==0)}fsMaxSeq(){return i(this,void 0,void 0,function*(){const t=yield this.hanoiFiles();return o.max([0,...t.map(t=>t.seq)])})}maxSeq(){return this.seq.then(t=>t.max)}next(t){return i(this,void 0,void 0,function*(){const e=(yield this.seq).max++;return new c(e,this.set(e),t)})}hanoiFiles(){return i(this,void 0,void 0,function*(){const t=yield this.root.clear().childNames();return r.compact(l.orElse(t,[]).map(t=>c.fromBasename(t)))})}staleHanoiFiles(){return i(this,void 0,void 0,function*(){const t=[],e=new a.MultiMap;return yield this.hanoiFiles().then(t=>t.forEach(t=>e.add(t.set,t))),[...e.keys()].forEach(n=>{const i=e.get(n),r=o.max(i.map(t=>t.seq));i.filter(t=>t.seq<r).forEach(e=>t.push(e))}),t})}staleFiles(){return i(this,void 0,void 0,function*(){return this.staleHanoiFiles().then(t=>t.map(t=>t.toFile(this.root)))})}}},function(t,e){t.exports=require("better-sqlite3")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(3),o=n(14),a=n(1),u=n(8),l=n(18),c=n(285),d="\nCREATE TABLE IF NOT EXISTS migrations (\n id integer NOT NULL PRIMARY KEY, \n name varchar(255) NOT NULL, \n migration_time integer NOT NULL \n)\n";e.Migration=class{constructor(t,e){this.migrationsDir=t,this.db=e,this.fsMigrations=s.lazy(()=>this.migrationsDir.children(t=>".sql"===t.ext)),this.logger=a.mkLogger("Migration("+t.base+")"),e.exec(d),this.addMigrationName=e.prepare("INSERT INTO migrations (name, migration_time) VALUES (?, ?)")}latest(){return i(this,void 0,void 0,function*(){const t=this.db.prepare("SELECT name from migrations").pluck().all(),e=yield this.fsMigrations();if(null==e)throw new Error("no migration files found for "+this.migrationsDir);this.logger.info("latest()",{currentNames:t,migrationFiles:e,migrationsDir:this.migrationsDir});for(const n of e)t.includes(n.name)?this.logger.info("latest(): already applied "+n.base):yield this.applyMigration(n);this.logger.info("up to latest!")})}applyMigration(t){return i(this,void 0,void 0,function*(){this.logger.info("applyMigration("+t.baseWithGrandparent+")");try{const e=Date.now(),n=c.maybeApplyMigration(t.name,this.db);return null!=n?(yield n,this.logger.info("applyMigration("+t.baseWithGrandparent+"): ran code migration",{elapsedMs:Date.now()-e})):yield this.applySqlMigration(t),this.addMigrationName.run(t.name,Date.now())}catch(e){throw this.logger.error("Failed to apply migration "+t.baseWithParent,e),o.emitFatal("Migration: failed to update "+t.baseWithParent+": "+e),e}})}applySqlMigration(t){return i(this,void 0,void 0,function*(){const e=t.base.includes("_nofk");try{const n=l.toS(yield t.readFile());if(u.blank(n))return void this.logger.error("Empty migration: "+t);e&&this.db.pragma("foreign_keys = OFF"),this.db.transaction(()=>{if(n.split(";").forEach(t=>this.db.exec(t.trim())),e){const t=this.db.pragma("foreign_key_check");if(r.isNotEmpty(t))throw this.logger.error("foreign_key_check failed",t),new Error("Foreign key checks failed")}})()}finally{e&&this.db.pragma("foreign_keys = ON")}})}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(3),s=n(1),o=n(12),a=n(124),u=n(13),l=n(9),c=n(15),d=n(78),h=n(151),f=r.lazy(()=>s.mkLogger("Migrations"));e.maybeApplyMigration=function(t,e){const n=t.replace(/^[\d_-]+/,"");return l.maybeCall(m,n,e)};const p=new RegExp(`^(${d.PS_NETWORK_FILESYSTEM_PROTOCOL}//.*?/)(.*)$`);var m;e.lowercase_psnet_function=t=>c.Opt(t).filter(u.isString).flatMap(t=>p.exec(t)).map(t=>t[1].toLowerCase()+t[2]).getOrElse(()=>t),function(t){t.lowercase_psnet_hostname=function(t){return i(this,void 0,void 0,function*(){t.function("lowercase_psnet_hostname",{deterministic:!0},e.lowercase_psnet_function),t.transaction(()=>{t.exec("DROP INDEX IF EXISTS assetfile_uri_udx"),t.exec("UPDATE AssetFile SET uri = lowercase_psnet_hostname(uri)"),t.exec("CREATE UNIQUE INDEX assetfile_uri_udx ON AssetFile(uri)")})()})},t.force_stable_channel=function(){return i(this,void 0,void 0,function*(){try{yield a.readSystemSettings();const t=o.Settings.updateChannel.value;"stable"!==t&&(o.Settings.updateChannel.value="stable",yield a.writeSystemSettings(),f().info("force_stable_channel(): reset updateChannel",{priorValue:t}))}catch(t){f().error("force_stable_channel(): failed: "+t)}})},t.on_new_exif_uid=function(t){return i(this,void 0,void 0,function*(){const e=h.LastExifVersionUpdatedAtMs;t.transaction(()=>{t.exec("UPDATE AssetFile SET updatedAt = "+e+" where updatedAt >= "+e)})})}}(m=e.Migrations||(e.Migrations={}))},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(3),s=n(11),o=n(1),a=n(200),u=n(201),l=n(206),c=r.lazy(()=>o.mkLogger("StatsDbJanitor"));e.statsDbJanitor=function(t){return i(this,void 0,void 0,function*(){c().info("Setting up "+t);const e=yield a.dbSetup(a.pathToDb(t,"stats"),"stats");l.StatsModel.db=e;const n=new u.SqliteJanitor("stats",e);return n.setInterval(5*s.minuteMs),n})}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(3),s=n(1),o=n(84),a=n(66),u=s.mkLogger("RemoteLibraryPath");e.remoteLibraryPath=r.lazy(()=>i(this,void 0,void 0,function*(){try{const t=a.dbClient()||a.dbClient.refresh();return yield o.thenTap(t.request("libraryPath"),t=>{u.info("received",{libraryPath:t})})}catch(t){return void u.error("Failed to get remote library path"+t)}}))},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(246),s=n(289),o=n(45),a=n(22),u=n(21),l=n(25),c=n(14),d=n(290),h=n(177),f=n(86),p=n(171),m=n(101),g=n(1),y=n(7),v=n(0),w=n(252),b=n(141),S=n(12),P=n(13),M=n(64),x=n(5),E=n(8),_=n(16),k=n(6),T=n(15),O=n(91),D=n(253),F=n(152),C=g.mkLogger("Sentry"),I=Math.round(3*m.MaxRecentLogEntriesByLevel);e.installSentry=function(t){return i(this,void 0,void 0,function*(){try{if(!D.sentryEnabled())return!1;const e=new A;return r.init({dsn:"https://0652cdd351054fe9853ff944b1f54e2c@sentry.io/289071",shutdownTimeout:b.serviceShutdownTimeoutMs(t.name),release:M.release,environment:S.Settings.nodeEnv.value,maxBreadcrumbs:I,beforeSend:e.beforeSend,serverName:yield h.systemUID(),onFatalError:t=>c.emitFatal("sentry.onFatalError",t)}),!0}catch(t){return C.warn("Failed to set up sentry: "+t),!1}})};class A{constructor(){this.eventStore=new d.EventStore,this.beforeSend=(t,e)=>i(this,void 0,void 0,function*(){if(!D.sentryEnabled())return C.error("Sentry.beforeSend(): not sending event",t),null;const n=S.Settings.email.value;E.notBlank(n)&&(null==t.user&&(t.user={}),t.user.email=n);const i=P.ellipsize(L(t,e),60);if(l.isIgnorableError(i))return C.info("Sentry.beforeSend(): ignorable event. vetoing",{event:t,hint:e,msg:i}),null;null==t.breadcrumbs&&(t.breadcrumbs=[]),t.breadcrumbs.push(...x.compact(m.recentLogEntries().slice(-I).map(N)));const r=v.orElse(t.extra,{});return r.msg=i,r.pid=a.pid,r.serviceName=F.lastServiceName(),r.serviceEnding=u.ending(),r.runtimeMs=Date.now()-F.start,r.version=M.version,r.os=w.OS(),r.locale=yield p.locale(),r.cpus=w.CPUs(),r.memoryUsageBytes=O.memoryUsageBytes(),r.systemMemory=y.fmtBytes(o.freemem())+" / "+y.fmtBytes(o.totalmem()),r.vlcInfo=yield f.vlcVersionDescription(),t.extra=r,this.eventStore.maybeSendEvent(i,t)});const t=(t,e)=>{null!=e?r.captureException(e):r.captureMessage(t)};c.onNonFatal(t),c.onFatal(t),c.onBoom(()=>r.captureMessage("User requested log dispatch")),u.addFirstEndable(new u.EndableWrapper("EventFilter",()=>this.end()))}end(){k.map(r.getCurrentHub().getClient(),t=>t.close(5*_.secondMs))}}function L(t,e){return T.Opt(t).flatMap(t=>t.message).filter(E.notBlank).orElse(()=>T.Opt(e).flatMap(t=>t.originalException).flatMap(l.maybeErrorToS).filter(E.notBlank)).orElse(()=>T.Opt(t.exception).flatMap(t=>t.values).flatMap(t=>t.map(R).find(E.notBlank)).filter(E.notBlank)).orElse(()=>"Unknown event").map(P.stripAnsiEsc).map(l.trimErrorMessage).get()}function R(t){return k.map(t,t=>x.compactBlanks([t.type,t.value]).join(": "))}function N(t){return k.map(j(t.level),e=>({timestamp:t.timestamp/_.secondMs,level:e,category:P.stripAnsiEsc(t.context),message:P.stripAnsiEsc(t.msg),data:"object"==typeof t.meta?t.meta:{value:P.isString(t.meta)?P.stripAnsiEsc(t.meta):t.meta}}))}function j(t){switch(t){case"error":return s.Severity.Error;case"warn":return s.Severity.Warning;case"info":return s.Severity.Info;case"debug":return s.Severity.Debug;default:return}}e.EventFilter=A,e.extractMessage=L,e.sentryExceptionToS=R,e.logEntryToBreadcrumb=N,e.logLevelToSeverity=j},function(t,e){t.exports=require("@sentry/types")},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(8),s=n(16),o=n(39),a=n(21),u=n(3),l=n(2),c=n(25),d=n(34),h=n(52),f=n(1),p=n(48),m=n(12),g=u.lazy(()=>f.mkLogger("EventStore"));e.EventStore=class{constructor(t=d.BaseFile.for(o.App.userData()).join("events")){this.root=t}vacuum(){return i(this,void 0,void 0,function*(){const t=Date.now()-s.dayMs;yield l.awaitAll(yield l.thenMap(this.root.clear().children(),e=>e.map(e=>i(this,void 0,void 0,function*(){try{if(e.isHiddenPosix()||".json"!==e.ext)return;const n=yield l.thenMapOr(e.readJSON(),t=>t.eventTime,()=>e.mtimeMs());null!=n&&n<t&&(yield e.unlink())}catch(t){g().warn("vacuum(): failed to vacuum "+e+": "+t)}})))),this.root.clear()})}maybeSendEvent(t,e){return i(this,void 0,void 0,function*(){if(a.ending())return g().error("maybeSendEvent(): REJECT: we're ending.",{msg:t,event:e}),null;r.blank(t)&&(t="UNKNOWN EVENT");try{yield l.thenOrTimeout(()=>this.vacuum(),5*s.secondMs);const n=yield l.thenMapOr(this.root.clear().children(),t=>t.length,()=>0);if(n>=m.Settings.maxErrorsPerDay.valueOrDefault+(c.isSendableError(t)?7:0))return g().error("maybeSendEvent(): REJECT: too many events sent in the last day.",{sentEventCount:n,maxErrorsPerDay:m.Settings.maxErrorsPerDay.valueOrDefault,event:e}),null;return null==(yield this.writeEvent({msg:t,event:e}))?(g().error("maybeSendEvent(): REJECT: event was already sent in the last day.",e),null):(g().error("maybeSendEvent(): ACCEPT",{sentEventCount:n,event:e}),e)}catch(t){return g().error("maybeSendEvent(): Failed to determine if we should squelch the event. Failing closed.",t),null}})}writeEvent({msg:t,eventTime:e=Date.now(),event:n}){return i(this,void 0,void 0,function*(){const i=this.msg2file(t),r={msg:t,eventTime:e,event:n},s=c.isSendableError(t)?m.Settings.maxErrorsPerDay.valueOrDefault-1:0;return l.thenMap(i.ensureNew({maxVersions:s,emptyIsNew:!1}).catch(()=>void 0),t=>t.writeJSON(r))})}msg2file(t){return this.root.join(h.shortStringSha(t,8,p.GeoRadix)+".json")}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(5),s=n(4),o=n(113),a=n(2),u=n(10),l=n(176),c=n(168),d=n(1),h=n(7),f=n(12),p=n(31),m=n(49),g=n(19),y=n(137),v=n(161);function w(t){return o.AsyncFilter.lift(e=>i(this,void 0,void 0,function*(){return a.thenMapOr(p.readTags(e.nativePath),t,()=>!1)}))}function b(t){return w(e=>s.allNotBlank(...t.map(t=>e[t])))}function S(t){return w(e=>h.gte(e.ImageWidth,t)&&h.gte(e.ImageHeight,t))}function P(t){return!u.blank(t)&&(c.ffmpegSupportedMimeType(t)||e.supportedMimeTypes.has(t.toLowerCase()))}e.onlyFiles=o.AsyncFilter.lift(t=>t.isFile()),e.onlyReadable=o.AsyncFilter.lift(t=>t.isReadable()),e.requiredTagsFilter=b,e.minDimensionFilter=S,e.hasMimeType=b(["MIMEType"]),e.hasCapturedAt=b(["capturedAt"]),e.hasMakeAndModel=b(["Make","Model"]),e.notRejected=w(t=>h.toInt(t.Rating,{defaultValue:0})>=0),e.hasBrowserImgMimetype=w(t=>r.includes(["image/jpeg","image/png"],g.toS(t.MIMEType))),e.imageFilter=w(t=>g.toS(t.MIMEType).startsWith("image/")),e.videoFilter=w(t=>g.toS(t.MIMEType).startsWith("video/")),e.imageHasMakeAndModel=e.imageFilter.and(e.hasMakeAndModel).or(e.videoFilter),e.supportedMimeTypes=new Set([...m.sharpSupportedMimeTypes,...l.dcrawSupportedMimeTypes]),e.supportedMimeTypeFilter=o.AsyncFilter.lift(t=>i(this,void 0,void 0,function*(){return a.thenMapOr(p.mimetype(t.nativePath),P,()=>!1)})),e.exifExtFilter=y.extFilter(m.AssetFileExts),e.notHiddenCheap=o.AsyncFilter.lift(t=>i(this,void 0,void 0,function*(){return!v.ignorablePath(t.nativePath)})),e.fileSizeFilter=o.AsyncFilter.lift(t=>i(this,void 0,void 0,function*(){return a.thenMapOr(t.size(),t=>h.within(f.Settings.minFileSizeBytes.valueOrDefault,f.Settings.maxFileSizeBytes.valueOrDefault,t),()=>!1)})),e.noStatFileFilter=o.AsyncFilter.andLogged(d.mkLogger("noStatFileFilter"),{exifExtFilter:e.exifExtFilter},{notHiddenCheap:e.notHiddenCheap}),e.cheapFileFilter=o.AsyncFilter.andLogged(d.mkLogger("cheapFileFilter"),{exifExtFilter:e.exifExtFilter},{notHiddenCheap:e.notHiddenCheap},{fileSizeFilter:e.fileSizeFilter},{supportedMimeTypeFilter:e.supportedMimeTypeFilter}),e.minDimensionsFilter=e.videoFilter.and(S(f.Settings.minVideoDimension.valueOrDefault)).or(e.imageFilter.and(e.hasMakeAndModel).and(S(f.Settings.minImageDimension.valueOrDefault))),e.expensiveFileFilters=[{exifExtFilter:e.exifExtFilter},{fileSizeFilter:e.fileSizeFilter},{hasMimeType:e.hasMimeType},{supportedMimeTypeFilter:e.supportedMimeTypeFilter},{imageHasMakeAndModel:e.imageHasMakeAndModel},{hasCapturedAt:e.hasCapturedAt},{notRejected:e.notRejected},{minDimensionsFilter:e.minDimensionsFilter}],e.expensiveFileFilter=o.AsyncFilter.andLogged(d.mkLogger("expensiveFileFilter"),...e.expensiveFileFilters),e.extless=o.AsyncFilter.lift(t=>i(this,void 0,void 0,function*(){return u.blank(t.ext)})),e.onlyDirectories=o.AsyncFilter.lift(t=>i(this,void 0,void 0,function*(){return t.isDirectory()})),e.fileExtFilter=function(t){return o.AsyncFilter.and(y.extFilter(t),e.onlyFiles)},e.excludeDirnameFilter=function(t){return o.AsyncFilter.and(y.excludedPathFilter(t),e.onlyDirectories)}},,,,,,,,,function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(45),r=n(16),s=n(17),o=n(59),a=n(3),u=n(12);e.maxCpus=a.lazy(()=>{const t=i.freemem()/(300*o.MB);return s.clamp(1,t,Math.ceil(u.Settings.maxCpuPercent.valueOrDefault/100*i.cpus().length))},15*r.secondMs)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(10),r=n(7);e.isErrorResult=function(t){return null!=t&&i.notBlank(t.path)&&i.notBlank(t.error)},e.isSuccessResult=function(t){return null!=t&&i.notBlank(t.path)&&r.gt0(t.assetId)&&r.gt0(t.assetFileId)}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(35),s=n(4),o=n(37),a=n(21),u=n(58),l=n(3),c=n(2),d=n(51),h=n(10),f=n(72),p=n(11),m=n(14),g=n(1),y=n(67),v=n(57),w=n(73),b=n(7),S=n(13),P=n(71),M=n(5),x=n(6),E=n(70),_=n(91),k=n(110),T=n(205),O=n(342),D=n(303),F=1e3,C=l.lazy(()=>g.mkLogger("DirectorySync"));class I{constructor(t,e,n,s,c,h){this.root=t,this.rootUri=e,this.assetProcessor=n,this.directoryCounter=s,this.runvalve=c,this.workPlanner=h,this.start=Date.now(),this.remainingMs=new y.Average(10),this._ended=!1,this.doneLatch=l.lazy(()=>new u.Latch(this.logger.context).observe((()=>i(this,void 0,void 0,function*(){yield this.directoryCounter.donePromise().catch(t=>{m.emitNonFatal("directoryCounter donePromise failed",t)}),this.logger.info("doneLatch(): directoryCounter is done"),yield this.assetProcessor.donePromise().catch(t=>{m.emitNonFatal("assetProcessor donePromise failed",t)}),this.logger.info("doneLatch(): assetProcessor is done"),this.clearProgressTimer(),o.later(()=>this.saveProgress())}))())),this.saveProgress=d.oneRunAtATime("saveProgress",()=>i(this,void 0,void 0,function*(){if(!a.ending()&&(yield this.runvalve()))try{const t=yield this.syncState();return null==t?this.logger.warn("Got null progress from this.syncState()"):this.priorProgress=yield T.Progress.ops().upsertOne(t),this.priorProgress}catch(t){return void this.logger.warn("saveProgress(): "+t)}}));const f="DirectorySync("+t+")";this.logger=g.mkLogger(f),this.progressTimer=r.setInterval(()=>this.saveProgress(),F),a.addFirstEndable(this)}static for(t,e,n=P.getWorkPlanner(),r=_.runvalve){return i(this,void 0,void 0,function*(){const i=yield t.uri(),s=yield t.directoryEntry();if(null==i||null==s)return void C().warn("Cannot make DirectorySync for "+t,{rootUri:i,rootDE:s});const o=new D.AssetFileQueue(t,n,r,e),a=new O.DirectoryCounter(s,o.fileListener.bind(o),500);return new I(t,i,o,a,r,n)})}get name(){return"DirectorySync "+JSON.stringify({done:this.done(),root:this.root.nativePath})}toString(){return this.name}status(){return i(this,void 0,void 0,function*(){return s.compact([Object.assign({},yield this.priorProgress,{dcDone:this.directoryCounter.done(),apDone:this.assetProcessor.done()})])})}get ended(){return this._ended}clearProgressTimer(){x.map(this.progressTimer,r.clearInterval),this.progressTimer=void 0}donePromise(){return this.doneLatch().promise}done(){return this.doneLatch().settled}get processedCount(){return this.assetProcessor.processedCount}syncState(){return i(this,void 0,void 0,function*(){const t=yield this.directoryCounter,e=this.assetProcessor,n=t.done(),i=e.done(),r=n&&i,s=r?"done":yield this.runvalve().then(t=>t?"processing":"paused"),o=[];r||(h.mapNotBlank(this.assetProcessor.recentProcessedFile,t=>o.push("Processing "+t)),n||o.push("Scanning "+h.firstNotBlank(this.directoryCounter.recentVisitedDirectory,this.root.nativePath)));const a=i?yield E.thenOpt(k.AssetFile.assetCountByMimetype(this.rootUri)).map(t=>w.groupBy(t,t=>t.mimetype.split("/",1)[0])).map(t=>({image:M.toA(t.get("image")).length,video:M.toA(t.get("video")).length})).getOrElse(()=>({})):{},u=["Processed",b.plur(v.max([a.image,e.processedImageCount]),"photo"),"and",b.plur(v.max([a.video,e.processedVideoCount]),"video")+"."],l=yield this.assetProcessor.pendingCount();l>0&&u.push(n?"":"At least",b.fmt(l),"remain to be processed"),o.push(h.compactBlanks(u).join(" "));const c=yield this.percents(),d=[];d.push(S.capitalize(s));const f=this.remainingMs.avg;if("processing"===s&&this.directoryCounter.done()&&this.remainingMs.k>3)if(b.isNumber(f)&&f>p.secondMs&&f<7*p.dayMs&&!0===b.mapFinite(this.remainingMs.sampleStdDev,t=>t<f/3)){const t="about "+p.fmtDuration(f,1)+" remain";d.push(t),this.logger.debug("asyncState()",{pcts:c,remaining:t,processed:this.processedCount,dirCntDone:this.directoryCounter.done(),apDone:this.assetProcessor.done()})}else this.logger.info("Skipping remaining, avgMillisRemaining is too wiggly",{avgMillisRemaining:f,stdDev:this.remainingMs.sampleStdDev,k:this.remainingMs.k});return Object.assign({volume:this.root.nativePath,uri:this.rootUri,state:s,hed:d.join(", "),dek:o},c)})}percents(){return i(this,void 0,void 0,function*(){if(yield this.done())return{completePct:100,incompletePct:0,scanningPct:0};const t=yield this.directoryCounter,e=yield c.thenMap(t.scannedPct(),b.round);if(!b.within(0,100,e))return this.logger.warn("Invalid scannedPct "+e),{completePct:0,incompletePct:0,scanningPct:100};const n=100-e,i=this.processedCount,r=yield this.assetProcessor.pendingCount(),s=0===r&&0===i?0:b.round(e*(i/(r+i))),o=100-(s+n),a={completePct:s,incompletePct:o,scanningPct:n};if(this.logger.debug("percents(): ",{scannedPct:e,processed:i,pending:r,p:a}),100!==v.sum([a.completePct,a.incompletePct,a.scanningPct])&&this.logger.warn("percents(): BUGGED",{p:a,processed:i,pending:r,scannedPct:e,scanningPct:n,incompletePct:o,completePct:s}),100===e&&i>10){const t=this.assetProcessor;let e=0;{const n=yield t.pendingImagesCount(),i=t.avgImageProcessingTime;n>0&&null!=i&&(e+=n*i)}{const n=yield t.pendingVideoCount(),i=t.avgVideoProcessingTime;n>0&&null!=i&&(e+=n*i)}e>0&&this.remainingMs.push(b.round(e))}return a})}end(){return i(this,void 0,void 0,function*(){this._ended||(this._ended=!0,this.clearProgressTimer(),a.end(this.directoryCounter),a.end(this.assetProcessor),this.logger.info(f.magenta("ended.")))})}}e.DirectorySync=I},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(37),o=n(21),a=n(3),u=n(2),l=n(51),c=n(11),d=n(25),h=n(14),f=n(157),p=n(173),m=n(135),g=n(28),y=n(32),v=n(291),w=n(1),b=n(67),S=n(7),P=n(0),M=n(12),x=n(49),E=n(190),_=n(204),k=n(300),T=n(5),O=n(6),D=n(110),F=n(343),C=n(344),I=n(301),A=C.QueueItem.fromJSON({id:-1,queueId:-1});class L{constructor(t,e,n,s,o=L.Priority){this.root=t,this.workPlanner=e,this.runvalve=n,this.importer=s,this.priority=o,this.workItems=new l.Promises,this.workMutex=new l.Promises,this._ended=!1,this._processedImages=0,this._processedVideo=0,this._imageProcessTimeMs=new b.Average(50),this._videoProcessTimeMs=new b.Average(50),this.recentProgress=new E.TTLArray(10*c.secondMs),this.recentlyProcessed=new E.TTLArray(20*c.secondMs),this.logSquelch=new _.TTLSet((M.isTest?5:30)*c.secondMs),this.recentlyRetried=new _.TTLSet(30*c.minuteMs),this.processMs=new b.Average,this._lastOpProgress=0,this.pendingCount=a.lazy(()=>C.QueueItem.dbLocal().pluckfirst(this.pathQuery.count()),1e3),this.pendingImagesCount=a.lazy(()=>C.QueueItem.dbLocal().pluckfirst(this.pathQuery.andWhere("type","!=",x.ExtTypes.video).count()),1e3),this.pendingVideoCount=a.lazy(()=>C.QueueItem.dbLocal().pluckfirst(this.pathQuery.andWhere("type","=",x.ExtTypes.video).count()),1e3),this.fileListener=t=>this.workItems.push(A,()=>i(this,void 0,void 0,function*(){this.logger.debug("fileListener()",{possibleAssetPaths:t.map(t=>t.nativePath)});const e=yield function(t,e=M.Settings.fileSyncIntervalHours.valueOrDefault){return i(this,void 0,void 0,function*(){return M.Settings.forceSync.valueOrDefault?t:u.thenFlatten(r.batches(t,50).map(t=>(function(t,e=M.Settings.fileSyncIntervalHours.valueOrDefault){return i(this,void 0,void 0,function*(){const n=new Map(yield u.tuples(t,t=>m.nativePath2uriString(t.nativePath))),r=D.AssetFile.query().select("uri","mtime","fileSize").whereIn("uri",T.toA(n.keys()));S.mapGt0(e,t=>r.andWhere("updatedAt",">=",Date.now()-Math.floor(t*c.hourMs)));const s=new Map(T.toA(n.entries()).map(([t,e])=>[e.nativePath,t])),o=yield D.AssetFile.opsRemote().all(r),a=yield u.asyncFilter(t,t=>i(this,void 0,void 0,function*(){const e=s.get(t.nativePath);if(null==e)return void N().debug("skipping, can't get uri for "+t);const n=o.find(t=>t.uri===e);if(null==n)return v.cheapFileFilter.apply(t);const i=yield t.mtimeMs(),r=yield t.size();if(null==i||null==r)return N().debug("skipping, can't stat "+t,{mtime:i,size:r}),!1;const a=n.mtime!==i||n.fileSize!==r;return N().debug((a?"including ":"removing ")+t,{changed:a,mtimeMs:i,size:r}),a}));return N().debug("result",{resultCount:a.length,fileCount:t.length,uriCount:n.size,priorsCount:o.length,priors:o,results:a.map(t=>g.posixPathFromGrandparent(t.nativePath))}),a})})(t,e)))})}(t);try{C.QueueItem.opsLocal().upsert(e.map(t=>({queueId:this.queue.id,contents:t.nativePath,type:P.orElse(x.extType(t.ext),"unknown")})))}catch(t){this.logger.error("fileListener() failed: "+t)}this.pendingCount.clear()})),this.name="AssetProcessor("+t+")",this.logger=w.mkLogger(this.name),this.queue=F.Queue.opsLocal().upsertOne({name:t.nativePath}),this.progressCallback=t=>{this.logger.debug("progressCallback()",t),this.hasPath(t.path)&&(this.recentProgress.push(`${t.op}(${t.path}): ${t.pct}%`),this._lastOpProgress=Date.now())},f.onProgressEvt(this.progressCallback),this.workPlanner.addIdleListener(this)}get pathQuery(){return C.QueueItem.query().where({queueId:this.queue.id})}get lastOpProgress(){return this._lastOpProgress}get currentQueueItems(){return this.workItems.pendingNames().filter(t=>t!==A)}get currentPaths(){return this.currentQueueItems.map(t=>t.contents)}hasPath(t){for(const e of this.currentPaths)if(t===e)return!0;return!1}get currentlyTranscoding(){return this.currentPaths.some(t=>x.isVideoExt(y.PosixFile.for(t).ext))}get processedCount(){return this._processedImages+this._processedVideo}get processedImageCount(){return this._processedImages}get processedVideoCount(){return this._processedVideo}get avgImageProcessingTime(){return this._imageProcessTimeMs.sampleAvg}get avgVideoProcessingTime(){return this._videoProcessTimeMs.sampleAvg}get recentProcessedFile(){return P.orElse(this.recentProgress.shift(),()=>this.recentlyProcessed.shiftOrFirst())}get ended(){return this._ended}end(){this._ended=!0,f.removeProgressEvtListener(this.progressCallback),this.workPlanner.removeIdleListener(this)}done(){return this.workItems.settled&&0===this.pendingCount.refresh()}donePromise(){return i(this,void 0,void 0,function*(){return u.until(()=>this.done(),void 0,1e3)})}doNotRun(){return u.thenNot(this.runvalve(),!0)}doNotEnqueueWork(){return i(this,void 0,void 0,function*(){const t={_ended:this._ended,ending:o.ending(),fullQueue:this.workItems.pendingCount>=k.maxCpus(),doNotRun:yield this.doNotRun()},e=P.values(t).some(t=>t);return this.logSquelch.addIfMissing("doNotEnqueueWork",()=>this.logger.debug("doNotEnqueueWork",{result:e,o:t,currentPathSize:this.workItems.pendingCount,pendingCount:this.pendingCount()})),e})}onIdle(){this.workMutex.maybeRun("AssetProcessor.run",()=>i(this,void 0,void 0,function*(){(yield this.doNotEnqueueWork())||O.map(this.peek(),t=>this.workItems.push(t,()=>this.processFile(t)))}))}dequeue(t){C.QueueItem.opsLocal().delete([t.id]),this.pendingCount.clear()}handleError(t,e){return i(this,void 0,void 0,function*(){this.logger.warn("Error handling file",{pq:t,err:e}),yield this.dequeue(t),d.isRetriableError(e)&&!this.recentlyRetried.has(t.contents)&&(yield u.thenMap(p.DirectoryEntry.for(t.contents),e=>(this.recentlyRetried.add(t.contents),this.logger.info("Re-enqueing "+e),this.fileListener([e]))))})}onFileDone(t,e){this.logger.debug("onFileDone("+t.contents+", "+e+" ms)");const n=R(t);x.isVideoExt(n.ext)?this._processedVideo++:this._processedImages++,e>0&&(x.isVideoExt(n.ext)?this._videoProcessTimeMs.push(e):this._imageProcessTimeMs.push(e)),this.dequeue(t),s.later(h.emitIdle)}peekQuery(){const t=this.currentQueueItems.map(t=>t.id),e=this.pathQuery.whereNotIn("id",t);return(this.currentlyTranscoding?e.andWhere("type","!=",x.ExtTypes.video):e).orderBy("id")}peek(){return C.QueueItem.opsLocal().first(this.peekQuery().limit(1))}peekN(t){return C.QueueItem.opsLocal().all(this.peekQuery().limit(t))}processFile(t){return i(this,void 0,void 0,function*(){const e="processFile("+t.contents+"): ",n=R(t),i=Date.now();if(yield n.clear().isEmpty())return this.logger.debug(e+"is empty, skipping."),this.onFileDone(t,0);try{this.logger.debug(e+"starting");const r=yield this.importer(n);I.isSuccessResult(r)?yield this.onFileDone(t,Date.now()-i):yield this.handleError(t,new Error(I.isErrorResult(r)?r.error:"undefined result"))}catch(e){return this.handleError(t,e)}finally{this.processMs.push(Date.now()-i),this.recentlyProcessed.push(n.nativePath)}})}}function R(t){return y.PosixFile.for(t.contents)}L.MaxErrors=2,L.Priority=1,e.AssetFileQueue=L;const N=a.lazy(()=>w.mkLogger("AssetProcessor.removeUnchanged()"))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(32),r=n(6),s=n(143),o=n(206);class a extends o.StatsModel{static findByUri(t){return a.opsLocal().findOneBy({uri:t})}static getAggregate(t,e){const n=this.query().select({assetCount:s.knex.raw("sum(assetCount)"),fileCount:s.knex.raw("sum(fileCount)"),dirCount:s.knex.raw("count(id)")});e(n);const i=this.dbLocal().first(n);return r.map(i,e=>e.rootUri=t),i}static getPathAggregates(t){return this.getAggregate(t,e=>e.where("uri","like",t+"%"))}static getFullAggregates(){return this.getAggregate("",()=>void 0)}static touchSubpaths(t){return a.dbLocal().run(this.query().where("uri","like",t+"%").update({updatedAt:Date.now()}))}static allForRootUri(t){return a.ops().all(this.query().where("uri","like",t+"%").orderBy("id"))}static deleteStaleForRoot(t,e){return a.dbLocal().run(this.query().where("uri","like",t+"%").where("updatedAt","<",e).delete())}get posixFile(){return i.PosixFile.forUri(this.uri)}}a.tableName="DirStat",a.uniqueColumnName="uri",e.DirStat=a},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(t,e,n){n(178),t.exports=n(338)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});try{n(207).install()}catch(t){}const i=n(22);new(n(339).SyncService)(i.argv.slice(2)),e.load=!0},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(87),s=n(4),o=n(37),a=n(21),u=n(3),l=n(2),c=n(132),d=n(29),h=n(63),f=n(20),p=n(227),m=n(11),g=n(14),y=n(157),v=n(148),w=n(32),b=n(88),S=n(340),P=n(75),M=n(93),x=n(1),E=n(7),_=n(0),k=n(141),T=n(12),O=n(24),D=n(300),F=n(202),C=n(5),I=n(80),A=n(8),L=n(18),R=n(91),N=n(125),j=n(110),B=n(245),z=n(152),q=n(165),W=n(341),V=n(302),U=n(347),G=n(348),$=n(349),J=n(350),H=x.mkLogger("SyncService");e.SyncService=class{constructor(t=[],e=g.eventEmitter,n=F.NiceWorkPlanner.instance()){this.importPaths=t,this.ee=e,this.workPlanner=n,this.logger=x.mkLogger("SyncService"),this.taskDataChunkers=new h.BoundedMap(500,10*m.minuteMs,!1),this.bc=u.lazy(()=>i(this,void 0,void 0,function*(){this.taskDataChunkers.clear();const t=yield p.pathToService("sync-file");if(null==t)return void H.error("Could not find sync-file");this.logger.info("mkbc(): sync-file found at "+t);const e=k.serviceMaxAgeMs("sync-file")-m.minuteMs,n=new r.BatchCluster({processFactory:()=>(this.logger.info("Spawning new sync-file",{execPath:process.execPath,syncFile:t.nativePath,maxProcs:D.maxCpus()}),f.spawn(process.execPath,[...p.nodeArgs("sync-file"),t.nativePath],e)),maxProcs:D.maxCpus(),maxTasksPerProcess:T.isTest?25:500,spawnTimeoutMillis:O.cmdTimeoutMs,taskTimeoutMillis:void 0,endGracefulWaitTimeMillis:30*m.secondMs,maxProcAgeMillis:e,versionCommand:"--version",pass:q.readyStr,fail:q.readyStr,exitCommand:"--exit",cleanupChildProcs:!1});return n.on("taskData",(t,e)=>{null!=t&&null!=e&&this.taskDataChunkers.getOrSet(L.toS(e),()=>new b.Chunker("\n",t=>this.onTaskData(t),!0)).onChunk(t)}),c.observeBatchCluster(n,"sync-file",a.EndableRanks.first)})),this.setupStatsDb=u.lazy(()=>{const t=N.Library.instance();if(null==t)throw new Error("cannot set up statsdb, library is undefined");return v.neverIgnore(...s.toA(this.importPaths)),t.statsDb()}),this.sync=u.lazy(()=>i(this,void 0,void 0,function*(){yield this.setupStatsDb();const t=N.Library.instance();if(null==t)throw new Error("cannot set up sync, library is undefined");const e=C.isEmpty(this.importPaths)?new $.Syncs(t,this.processFile.bind(this)):new G.CompositeSync(yield l.thenCompact(this.importPaths.map(t=>w.PosixFile.for(t)).map(t=>i(this,void 0,void 0,function*(){return(yield t.isDirectory())?V.DirectorySync.for(t,this.processFile.bind(this),F.NiceWorkPlanner.instance()):new U.FileSync(t,this.processFile(t))})))),n=T.Settings.syncIntervalHours.valueOrDefault;return this.exitWhenDone?o.delay(m.secondMs).then(()=>e.donePromise()).then(()=>o.delay(m.secondMs)).catch(t=>this.service.exit("Error: "+t,12)).then(()=>this.service.exit("Finished importing given paths",0)):E.gt0(n)&&o.delay(m.secondMs).then(()=>e.donePromise()).then(()=>e.end()).catch(t=>{g.emitNonFatal("Syncs failed, but will restart after "+n+" hours",t)}).then(()=>o.delay(n*m.hourMs)).then(()=>(this.logger.info("Restarting scanDrives after "+T.Settings.syncIntervalHours.valueOrDefault+" hours."),this.sync.refresh())),e}));const d=t.includes(J.ExitWhenDoneArg);C.filterInPlace(t,t=>t!==J.ExitWhenDoneArg&&A.notBlank(t)),this.exitWhenDone=d||s.isNotEmpty(t),this.service=new z.Service({name:"sync"}),g.onRpcServerChange(()=>this.service.exit("rpcServerChange",0)),this.setup().catch(t=>g.emitFatal("setup() failed: "+t))}done(){return i(this,void 0,void 0,function*(){const t=yield this.sync();return null==t||t.done()})}status(){return i(this,void 0,void 0,function*(){try{const t=yield this.sync.prior(),e={libraryPath:T.Settings.libraryPath.value,rpcPort:T.Settings.rpcPort.value,ending:a.ending(),done:yield this.done(),sync:_.map(t,t=>t.name),progress:yield l.thenMap(this.sync(),t=>t.status()),healthChecks:yield R.healthChecks()};q.stdoutWrite(e)}catch(t){q.stdoutWrite({error:t})}})}processFile(t){return i(this,void 0,void 0,function*(){try{if(H.info("processFile("+t+")"),null==(yield this.bc()))throw new Error("this.bc is null");const e=yield m.elapsedAsync(()=>this.workPlanner.work("processFile",()=>this._processFile(t)));if(!T.isProd){const n=yield M.syncFileTimeoutForFile(t);q.stdoutWrite(Object.assign({elapsedMs:e.elapsedMs,timeoutMs:n},e.result))}return e.result}catch(e){return H.warn("Failed to process "+t,e),{path:t.nativePath,error:e}}})}_processFile(t){return i(this,void 0,void 0,function*(){if(a.ending())return;const e=yield l.thenMap(t.uri(),e=>l.thenMap(j.AssetFile.opsRemote().findOneBy({uri:e}),e=>l.thenAnd(e.matchesFile(t),()=>e)));if(null!=e)return this.logger.info("_processFile("+t+"): no-op, AssetFile:"+e.id+" already in sync."),{path:t.nativePath,assetId:e.assetId,assetFileId:e.id,shown:d.truthy(e.shown)};{if(a.ending())return;const e=yield this.bc();return null==e?void this.logger.error("_processFile("+t+"): this.bc is null"):I.retryOnReject(()=>i(this,void 0,void 0,function*(){if(a.ending())return;const n=new W.ImportTask(t);return e.enqueueTask(n).finally(()=>this.taskDataChunkers.delete(L.toS(n)))}),{maxRetries:1})}})}setup(){return i(this,void 0,void 0,function*(){if(yield l.rejected(this.service.ready))return void this.logger.warn("setup(): service.ready was rejected, exitting.");const t=N.Library.instance();if(null==t)throw new Error("null Library");this.logger.info("setup(): library is at "+t.rootDir),B.modelJsonSetup(),yield this.bc(),yield this.sync(),this.service.setInputHandler("--status",()=>this.status()),T.isTest&&s.isNotEmpty(this.importPaths)&&y.onProgressEvt(t=>console.log(JSON.stringify(t))),new S.TmpfileCleanup(P.imgtmpDir,15*m.minuteMs)})}onTaskData(t){const e=_.orElse(_.Try(()=>JSON.parse(t)),{});y.isProgressEvt(e)&&(T.isTest&&q.stdoutWrite(e),y.emitProgressEvt(e))}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(21),s=n(11),o=n(1),a=n(140);e.TmpfileCleanup=class{constructor(t,e,n=(()=>!0),i=!0){this.root=t,this.maxAgeMs=e,this.filter=n,this.scheduleCleanup=i,this._ended=!1,this.name="TmpfileCleanup",this.logger=o.mkLogger(this.name),r.addFirstEndable(this),this._scheduleCleanup()}get ended(){return this._ended}end(){this._ended=!0}_scheduleCleanup(){!this._ended&&this.scheduleCleanup&&setTimeout(()=>this.cleanup(),Math.min(s.minuteMs,Math.floor(this.maxAgeMs/5)))}cleanup(){return i(this,void 0,void 0,function*(){if(this._ended)return[];const t=yield this.root();if(null==t)return[];const e=Date.now()-this.maxAgeMs,n=[];yield t.visitDescendants(r=>i(this,void 0,void 0,function*(){const i=yield r.stat();null!=i&&i.isFile()&&(!r.parent().eql(t)||!a.isNoMediaName(r.base))&&this.filter(r)&&i.birthtimeMs<e&&(n.push(r),yield r.unlink().catch(t=>this.logger.warn("Failed to unlink "+r,t)))}));const r=n.length;return this.logger.info("Removed "+r+" files."),yield t.visitDescendants(t=>i(this,void 0,void 0,function*(){t.clear(),(yield t.isDirectory())&&(yield t.hasNoChildren())&&(n.push(t),yield t.remove().catch(e=>this.logger.warn("Failed to rmdir "+t,e)))})),this.logger.info("Pruned "+(n.length-r)+" empty directories."),this._scheduleCleanup(),n})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(87),r=n(10),s=n(1),o=n(13),a=n(18),u=n(301);e.ImportTask=class extends i.Task{constructor(t){super(t.nativePath,t=>this.parse(t)),this.file=t,this.name=`ImportTask(${this.file})`,this.logger=s.mkLogger(this.name)}toString(){return this.name}parse(t){for(const e of r.compactBlanks(a.toS(t).split("\n")).reverse()){const t=JSON.parse(e);if(u.isErrorResult(t)||u.isSuccessResult(t)){if(o.equalsIgnoreCase(t.path,this.file.nativePath))return this.logger.debug("handleBuf(): Received result",t),t;this.logger.error("handleBuf(): Received unexpected result",t)}}return{path:this.file.nativePath,error:"INTERNAL ERROR: no result found in input"}}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(36),o=n(37),a=n(21),u=n(3),l=n(2),c=n(51),d=n(11),h=n(25),f=n(135),p=n(32),m=n(1),g=n(7),y=n(0),v=n(12),w=n(190),b=n(74),S=n(24),P=n(202),M=n(105),x=n(303),E=n(345),_=n(304);e.DirectoryCounter=class{constructor(t,e,n,h=v.Settings.syncIntervalHours.valueOrDefault*d.hourMs,y=P.NiceWorkPlanner.instance(),k=x.AssetFileQueue.Priority,T=.25*g.MB,O=50*g.KB,D=1.25*v.Settings.statTimeoutSeconds.valueOrDefault*d.secondMs){this.root=t,this.fileListener=e,this.workTimeMs=n,this.priorValidMs=h,this.workPlanner=y,this.priority=k,this.totalFileEstimateChunksize=T,this.averageFileSizeEstimate=O,this.dirIterTimeoutMs=D,this.startedAt=Date.now(),this.recentDirs=new w.TTLArray(1*d.minuteMs,200),this._skippedDirs=0,this._unchangedDirs=0,this._changedDirs=0,this._runningTotalFiles=0,this._runningTotalAssetCount=0,this._ended=!1,this.driveUsedBytes=u.lazy(()=>l.thenMap(b.volumeFor(this.root.nativePath),t=>t.used),S.longTtlMs),this.run=c.oneRunAtATime(this.name+".run",()=>this.workPlanner.work(this.name+".run()",()=>i(this,void 0,void 0,function*(){if(this._ended)return;const t=Date.now()+this.workTimeMs,e=new Map,n=yield f.nativePath2uriString(this.root.nativePath);if(null==n)return void this.onError(new Error("Cannot fetch URI for "+this.root));for(;Date.now()<t&&!this._ended;){const n=yield l.thenOrTimeout(this.dirIter.next(t).catch(t=>this.onError(t)),this.dirIterTimeoutMs,()=>{this.logger.warn("DirectoryIteratory TIMEOUT after "+this.dirIterTimeoutMs)});if(this.logger.debug("run(): got dirIter result",n),this._ended=this._ended||null==n||n.done,null==n||this.finalResult.rejected)return;const i=n.value;if(null!=i&&null!=i.result){const t=i.result;e.set(t.uri,t);const n=yield l.thenMap(p.PosixFile.forUri(t.uri),t=>t.nativePath);if(null==n)return void this.logger.error("Cannot restore path from "+t.uri);if(this.recentDirs.pushUniq(n),!0!==i.priorStillValid||v.Settings.forceSync.valueOrDefault)null!=t.completedAt&&(this.logger.info("Completed ",t),this._runningTotalAssetCount+=t.assetCount,this._runningTotalFiles+=t.fileCount,!0===i.priorMtimeMatches?this._unchangedDirs++:this._changedDirs++);else{const t=yield _.DirStat.getPathAggregates(i.result.uri);null==t?this.logger.warn("internal error: no path aggregates for "+i.result.uri):(this.logger.debug(i.result.uri+" is complete and unchanged. Adding aggregates:",{uriAgg:t,v:i}),yield _.DirStat.touchSubpaths(i.result.uri),this._runningTotalAssetCount+=t.assetCount,this._runningTotalFiles+=t.fileCount,this._unchangedDirs+=t.dirCount,this._skippedDirs+=t.dirCount)}}}this.logState();const i=[...e.values()];if(r.isNotEmpty(i)){const t=Date.now(),e=_.DirStat.opsLocal().upsert(i),n=Date.now()-t;this.logger.info("Upserted in "+n+"ms",e.map(t=>({id:t.id,uri:t.uri}))),this.dirIter.updateDirStats(e)}if(this.dirIter.done()){this.logger.info("dirIter is done, cleaning up..."),this.workPlanner.removeIdleListener(this),_.DirStat.deleteStaleForRoot(n,this.startedAt);const t={rootUri:n,assetCount:this._runningTotalAssetCount,fileCount:this._runningTotalFiles,dirCount:this.dirCount};o.later(()=>this.finalResult.resolve(t))}}))),this.logState=M.throttle(()=>this.logger.info("Visiting "+[...this.recentDirs.values],{dirIterDone:this.dirIter.done()}),(v.isTest?5:15)*d.secondMs),this.name="stats.DirectoryCounter("+t.nativePath+")",this.logger=m.mkLogger(this.name),this.finalResult=new s.Deferred(this.name).finally(()=>this.end()),this.dirIter=new E.DirectoryIterator(t,e,h),a.addFirstEndable(this),this.workPlanner.addIdleListener(this),l.thenMap(b.volumeFor(this.root.nativePath),t=>this._driveUsedBytes=t.used).catch(t=>{this.logger.warn("Failed to get used bytes for "+this.root+": "+t)})}get recentVisitedDirectory(){return this.recentDirs.shiftOrFirst()}get estimatedTotalFileCount(){const t=y.map(this._driveUsedBytes,t=>t/this.averageFileSizeEstimate),e=this.totalFileEstimateChunksize*(1+Math.ceil(this.runningTotalFiles/this.totalFileEstimateChunksize));return null!=t&&t>e?t:e}get runningTotalAssetCount(){return this._runningTotalAssetCount}get runningTotalFiles(){return this._runningTotalFiles}scannedPct(){return this.done()?100:this.runningTotalFiles/this.estimatedTotalFileCount*100}get unchangedDirs(){return this._unchangedDirs}get changedDirs(){return this._changedDirs}get skippedDirs(){return this._skippedDirs}get dirCount(){return this._unchangedDirs+this._changedDirs}get ended(){return this._ended}end(){this._ended=!0,this.workPlanner.removeIdleListener(this)}done(){return this._ended||this.finalResult.settled}donePromise(){return this.finalResult.promise}onIdle(){return this.run()}onError(t){this.logger.error("fatal: "+t),this.finalResult.reject(h.asError(t))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(206);class r extends i.StatsModel{}r.tableName="Queue",r.uniqueColumnName="name",e.Queue=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(206);class r extends i.StatsModel{}r.tableName="QueueItem",r.uniqueColumnName="contents",e.QueueItem=r},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(4),s=n(37),o=n(2),a=n(11),u=n(135),l=n(161),c=n(140),d=n(291),h=n(346),f=n(1),p=n(0),m=n(12),g=n(80),y=n(15),v=n(85),w=n(304),b={done:!0,value:void 0},S={done:!1,value:void 0};class P{constructor(t,e,n=m.Settings.syncIntervalHours.valueOrDefault*a.hourMs,r,s=3){this.dir=t,this.fileListener=e,this.priorValidMs=n,this.parent=r,this.maxRetries=s,this.skipChildFiles=!1,this.pendingChildDirs=[],this._done=!1,this.nextChain=[this.maybeTimeout,this.setupResult,this.maybeTimeout,this.fetchChildren,this.maybeTimeout,this.popChildren,this.maybeTimeout,this.maybeSetupChildDelegate,this.maybeTimeout,this.maybeDelegateToChild,this.maybeCompleteResult].map(t=>e=>i(this,void 0,void 0,function*(){const n="."+t.name+"()",i=yield t.call(this,e);return this.logger.debug(n,{result:i,thisResult:this.result}),i})),this.name="stats.DirectoryIterator("+t+")",this.logger=f.mkLogger(this.name)}get isRoot(){return null==this.parent}root(){return null==this.parent?this:this.parent.root()}updateDirStats(t){p.map(this.result,e=>{p.map(t.find(t=>t.uri===e.uri),t=>{Object.assign(e,t),this.logger.debug("updateDirStats()",this.result)})}),p.map(this.childDelegate,e=>e.updateDirStats(t))}done(){return this._done}next(t){return i(this,void 0,void 0,function*(){if(this._done)return b;const e=Date.now();if(t<e)return S;const n=yield g.retryOnReject(()=>o.firstAsync(this.nextChain,e=>e(t)),{maxRetries:this.maxRetries,onRetryWaitUntil:()=>s.delay(v.randomInt(500,10*a.secondMs))});return null==n?S:(this._done=n.done,this.logger.debug("next()",{result:n,ttr:t-e,elapsed:Date.now()-e}),n)})}maybeTimeout(t){if(Date.now()>=t)return S}setupResult(){return i(this,void 0,void 0,function*(){if(null!=this.result)return;const t=yield u.nativePath2uriString(this.dir.nativePath);if(null==t)throw new Error("Cannot create URI for "+this.dir);const e=yield o.thenMap(this.dir.mtimeMs(),a.unixtime);if(null==e)return this.logger.error("mtime was undefined"),{done:!0,value:void 0};const n=w.DirStat.findByUri(t);this.priorMtimeMatches=y.Opt(n).map(t=>t.mtime===e).getOrElse(()=>!1),this.logger.debug("setupResult()",{priorId:p.map(n,t=>t.id),priorMtimeMatches:this.priorMtimeMatches}),null!=n&&this.priorMtimeMatches?(this.result=n,this.priorValidMs<=0||a.recent(n.completedAt,this.priorValidMs)?(this.logger.debug("prior exists, mtime matches, and was completed recently enough"),this.skipChildFiles=!0):(this.result.completedAt=void 0,this.logger.debug("prior exists and mtime matches"))):(this.result=p.orElse(n,()=>w.DirStat.fromJSON({uri:t})),this.result.mtime=e,this.result.assetCount=0,this.result.fileCount=0,this.logger.info("set up result",this.result))})}fetchChildren(){return i(this,void 0,void 0,function*(){if(null==this.pendingChildren)if(yield c.hasNoMedia(this.dir))this.logger.info("skipping .nomedia dir, "+this.dir),this.pendingChildren=[];else{const t=yield o.thenMap(this.dir.children(),t=>h.sortByExt(t.filter(t=>!l.ignorableFile(t))));this.pendingChildren=r.toA(t).reverse()}})}popChildren(t){return i(this,void 0,void 0,function*(){const e=[];for(;null!=this.pendingChildren&&this.pendingChildren.length>0&&Date.now()<t;){const t=this.pendingChildren.pop();t.isDirectory()?this.pendingChildDirs.push(t):this.skipChildFiles||(this.result.fileCount++,(yield d.noStatFileFilter.apply(t))&&(e.push(t),this.result.assetCount++))}r.isNotEmpty(e)&&this.fileListener(e)})}maybeSetupChildDelegate(t){return i(this,void 0,void 0,function*(){for(;Date.now()<t&&null==this.childDelegate&&this.pendingChildDirs.length>0;){const t=this.pendingChildDirs.shift();(yield l.ignorableDirectory(t))||(this.childDelegate=new P(t,this.fileListener,this.priorValidMs,this))}})}maybeDelegateToChild(t){return i(this,void 0,void 0,function*(){const e=this.childDelegate;if(null!=e){const n=m.Settings.statTimeoutSeconds.valueOrDefault*a.secondMs,i=yield o.thenOrTimeout(e.next(t).catch(t=>{this.logger.warn("Failed to descend into "+e.dir+": "+t)}),n,()=>{this.logger.warn("Failed to descend into "+e.dir+": TIMEOUT after "+n)});return(null==i||i.done)&&(this.childDelegate=void 0),null!=i&&i.done&&(i.done=!1),p.orElse(i,S)}})}maybeCompleteResult(){return i(this,void 0,void 0,function*(){return null==this.result||null==this.pendingChildren||null!=this.childDelegate||r.isNotEmpty(this.pendingChildDirs)||r.isNotEmpty(this.pendingChildren)?(this.logger.warn("maybeCompleteResult, not done (?!)",p.pick(this,"result","pendingChildren","childDelegate","pendingChildDirs")),S):(this.result.completedAt=p.orElse(this.result.completedAt,Date.now()),{done:!0,value:{result:this.result,priorMtimeMatches:this.priorMtimeMatches}})})}}e.DirectoryIterator=P},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(30),r=n(4),s=n(10),o=n(49),a=n(19),u=[o.SharpImageExts,o.RawImageExts,o.VideoExts].map(t=>new Set(t.map(t=>t.toLowerCase().normalize())));function l(t){const e=a.toS(t.ext).toLowerCase().normalize(),n=u.findIndex(t=>t.has(e)),r=n>=0?n:u.length+1;return[t.dir+i.sep+t.name,r,e]}e.extSortCriteria=l,e.sortByExt=function(t){return r.sortBy(t,t=>[s.blank(t.ext),...l(t)])}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(36);e.FileSync=class{constructor(t,e){this.root=t,this._ended=!1,this.name="FileSync("+t+")",this.sync=new r.Deferred(this.name).observe(e)}get ended(){return this._ended}done(){return this.sync.settled}donePromise(){return this.sync}status(){return i(this,void 0,void 0,function*(){return[{volume:this.root.nativePath,state:this.sync.pending?"processing":"done"}]})}end(){this._ended=!0}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});const i=n(2);e.CompositeSync=class{constructor(t){this.syncs=t,this._ended=!1,this.name=`Syncs(${t.map(t=>t.name)})`,this._donePromise=Promise.all(this.syncs.map(t=>t.donePromise())).then(()=>void 0)}done(){return this.syncs.every(t=>t.done())}donePromise(){return this._donePromise}status(){return i.thenFlatten(this.syncs.map(t=>t.status()))}get ended(){return this._ended}end(){return this._ended=!0,i.awaitAll(this.syncs.map(t=>t.end()))}}},function(t,e,n){"use strict";var i=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,s){function o(t){try{u(i.next(t))}catch(t){s(t)}}function a(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(o,a)}u((i=i.apply(t,e||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0});const r=n(39),s=n(4),o=n(21),a=n(58),u=n(2),l=n(51),c=n(50),d=n(11),h=n(14),f=n(32),p=n(1),m=n(7),g=n(12),y=n(204),v=n(74),w=n(24),b=n(202),S=n(71),P=n(5),M=n(55),x=n(6),E=n(9),_=n(105),k=n(302),T=()=>m.clamp(1,168,g.Settings.syncIntervalHours.valueOrDefault)*d.hourMs;e.Syncs=class{constructor(t,e,n=b.NiceWorkPlanner.instance()){this.library=t,this.importer=e,this.workPlanner=n,this.logger=p.mkLogger("Syncs"),this.name="Syncs",this.scanned=new a.Latch,this._doneLatch=new a.Latch,this._ended=!1,this.nativePathsCompleted=new y.TTLSet(T()),this.urisCompleted=new y.TTLSet(T()),this.pathsToDo=[],this.onVolumesChanged=()=>this.scanDrives(),this.end=M.lazy(()=>i(this,void 0,void 0,function*(){this._ended=!0,this.logger.info("end()"),clearInterval(this.driveScanTimer),h.eventEmitter.removeListener("volumesChanged",this.onVolumesChanged),E.map(this.pathsToDo,t=>t.length=0);const t=u.thenMap(this.sync,t=>t.end());this.sync=void 0,yield t})),this.scanDrives=l.serially(this.name+".scanDrives()",()=>i(this,void 0,void 0,function*(){const t=p.mkLogger(this.name+".scanDrives()");try{return S.isPaused()||o.ending()?void t.info("paused || ending"):(yield this.validateCurrentSync(),null!=(yield this.sync)?void t.debug("sync not complete."):(yield this.buildPathsToDo(),yield this.popNextMountpoint(),this.scanned.pending&&this.scanned.resolve(),s.isEmpty(this.pathsToDo)&&null==this.sync&&(t.info("WOOT, all drives are sync'ed"),this._doneLatch.resolve()),void this.logState()))}catch(t){h.emitNonFatal("scanDrives() failed",t)}})),this.logState=_.throttle(()=>i(this,void 0,void 0,function*(){const t={mountpointsCompleted:[...this.nativePathsCompleted.keys()],urisCompleted:[...this.urisCompleted.keys()],mountpointsTodo:this.pathsToDo};yield u.thenMap(this.sync,e=>{t.sync={root:e.root.nativePath,start:d.fmtDuration(Date.now()-e.start)+" ago"}}),this.logger.info("status",t)}),30*d.secondMs),this.scanDrives(),this.driveScanTimer=c.setUnrefInterval(()=>this.scanDrives(),w.mountpointsTtlMs),g.Settings.scanAllDrives.valueOrDefault&&h.onVolumesChanged(this.onVolumesChanged)}status(){return i(this,void 0,void 0,function*(){return u.thenMap(this.sync,t=>t.status())})}done(){return this.scanned.settled&&null==this.sync&&s.isEmpty(this.pathsToDo)}doneLatch(){return this._doneLatch}donePromise(){return this._doneLatch.promise}get ended(){return this._ended}endCurrentSync(){const t=u.thenMap(this.sync,t=>(this.logger.info("endCurrentSync(): ending "+t),o.end(t)));return this.sync=void 0,t}validateCurrentSync(){return i(this,void 0,void 0,function*(){const t=p.mkLogger(this.name+".validateCurrentSync()"),e=yield this.sync;if(null==e)return void t.debug("no current sync");const n=e.root.nativePath,i=e.rootUri;return e.done()?(this.urisCompleted.add(i),this.nativePathsCompleted.add(n),this.endCurrentSync()):(yield e.root.clear().notExists())?(t.warn("sync "+n+" has disappeared. Ending."),this.endCurrentSync()):void 0})}buildPathsToDo(){return i(this,void 0,void 0,function*(){const t=p.mkLogger(this.name+".buildPathsToDo()"),e=g.Settings.scanPaths.values.map(t=>f.PosixFile.for(t));e.push(this.library.rootDir),g.Settings.scanMyPictures.valueOrDefault&&e.push(f.PosixFile.for(r.App.getPath("pictures")));const n=yield v.volumes();if(s.isEmpty(n))return void t.warn("volumes() is empty, giving up.");const o=n.map(t=>f.PosixFile.for(t.mountpoint));g.Settings.scanAllDrives.valueOrDefault&&e.push(...o);const a=f.coallesce(e,o),l=this.pathsToDo;this.pathsToDo=(yield u.asyncFilter(a,t=>i(this,void 0,void 0,function*(){return!this.nativePathsCompleted.has(t.nativePath)&&!this.urisCompleted.has(x.orElse(yield t.uri(),t.nativePath))}))).map(t=>t.nativePath),t.info("result",{allPaths:e,coallescedPaths:a,pathsToDo:this.pathsToDo,priorPathsToDo:l,pathsCompleted:P.toA(this.nativePathsCompleted.entries()),urisCompleted:P.toA(this.urisCompleted.entries())})})}popNextMountpoint(){return i(this,void 0,void 0,function*(){const t=p.mkLogger(this.name+".popNextMountpoint()");for(;!this._ended&&null==this.sync&&s.isNotEmpty(this.pathsToDo);){const e=this.pathsToDo.shift();if(null==e)continue;const n=f.PosixFile.for(e);if(!(yield n.clear().notExists()))return t.info("starting sync for "+n),this.sync=k.DirectorySync.for(n,this.importer,this.workPlanner),u.thenMap(this.sync,n=>n.donePromise().catch(n=>{t.warn("sync donePromise was rejected",{err:n,root:e}),this.sync=void 0}).then(()=>this.scanDrives())),!0;t.warn(n+" doesn't exist")}return!1})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ExitWhenDoneArg="--exitWhenDone"}]);
|
|
3
|
-
//# sourceMappingURL=sync.js.map
|