From 60936ed2f59719710c2a9e07b7cec57f9891e113 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A2u=20Cao?= Date: Mon, 27 Apr 2026 21:51:55 +0100 Subject: [PATCH] 1.21.1 --- package.json | 2 +- release/assets/main-48yHGHPo.css | 1 - release/assets/main-C_mgNoFX.css | 1 + release/assets/{main-B30qTale.js => main-DsygQlAh.js} | 4 ++-- .../{modules-4-12-CSVC-YcG.js => modules-4-12-Br95YYit.js} | 2 +- .../assets/{negentropy-B7CRzqXr.js => negentropy-CxcMNqMs.js} | 2 +- release/index.html | 4 ++-- 7 files changed, 8 insertions(+), 8 deletions(-) delete mode 100644 release/assets/main-48yHGHPo.css create mode 100644 release/assets/main-C_mgNoFX.css rename release/assets/{main-B30qTale.js => main-DsygQlAh.js} (66%) rename release/assets/{modules-4-12-CSVC-YcG.js => modules-4-12-Br95YYit.js} (98%) rename release/assets/{negentropy-B7CRzqXr.js => negentropy-CxcMNqMs.js} (99%) diff --git a/package.json b/package.json index ce2631a..67f552e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "marco", - "version": "1.21.0", + "version": "1.21.1", "private": true, "description": "Unhosted maps app", "repository": { diff --git a/release/assets/main-48yHGHPo.css b/release/assets/main-48yHGHPo.css deleted file mode 100644 index 269607d..0000000 --- a/release/assets/main-48yHGHPo.css +++ /dev/null @@ -1 +0,0 @@ -:root{--default-list-color: #fc3;--hover-bg: #f8f9fa;--sidebar-width: 350px;--link-color: #2a7fff;--link-color-visited: #6a4fbf;--marker-color-primary: #ea4335;--marker-color-dark: #b31412;--danger-color: var(--marker-color-primary);--danger-color-dark: var(--marker-color-dark)}html,body{height:100%;overscroll-behavior:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}button{-webkit-tap-highlight-color:transparent}body{margin:0;font-family:Noto Sans,sans-serif;font-size:16px;font-weight:400;color:#333}#root,#ember-testing{height:100%}.map-container{background:#f8f9fa;-webkit-tap-highlight-color:transparent;outline:none;position:absolute;inset:0}#rs-widget-container{position:absolute;top:60px;right:10px;z-index:4000;display:none}#rs-widget-container.visible{display:block}.rs-backdrop{position:fixed;inset:0;z-index:3999}.app-header{position:absolute;top:0;left:0;right:0;height:60px;padding:.5rem 1rem;z-index:3000;pointer-events:none;display:grid;grid-template-columns:1fr auto 1fr;grid-template-areas:"search chips user";align-items:center;gap:1rem}@media(max-width:768px){.app-header{padding:.5rem .5rem 0;height:auto;grid-template-columns:1fr auto;grid-template-areas:"search user" "chips chips";row-gap:8px}}.header-left,.header-right,.header-center{pointer-events:auto}.header-left{display:flex;align-items:center;grid-area:search;justify-self:start;width:100%}@media not (max-width:768px){.header-left{min-width:300px;max-width:400px}}@media not (max-width:768px){.header-left{min-width:300px;max-width:350px}}.header-right{grid-area:user;justify-self:end}.header-center{grid-area:chips;display:flex;justify-content:center;min-width:0}@media not (max-width:768px){.header-center .category-chips-scroll{width:auto;max-width:100%}}@media(max-width:768px){.header-center{width:100%;overflow:hidden;justify-content:start}.header-center.searching{display:none}}.btn-press{transition:transform .1s}.btn-press:active{transform:scale(.95)}.user-btn{background:none;border:none;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}.user-avatar-placeholder{width:40px;height:40px;background:#2a3743;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0}.user-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;flex-shrink:0;display:block}.photo-preview-img{max-width:100%;height:auto}.dropzone{border:2px dashed #ccc;border-radius:8px;text-align:center;transition:all .2s ease;margin:1.5rem 0 1rem;background-color:#ffffff05;cursor:pointer;aspect-ratio:4 / 3}.dropzone.is-dragging{border-color:#61afef;background-color:#61afef0d}.dropzone-label{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1rem;cursor:pointer;color:#898989;width:100%;height:100%}.dropzone-label p{margin:0}.file-input-hidden{display:none}.photo-grid{display:flex;flex-direction:column;gap:12px;margin-bottom:20px}.photo-upload-item{position:relative;aspect-ratio:4 / 3;border-radius:6px;overflow:hidden;background:#1e262e;width:100%}.photo-upload-item img{position:absolute;top:0;left:0;width:100%;height:100%;object-fit:contain;display:block;z-index:1}.photo-upload-item .overlay,.photo-upload-item .btn-remove-photo{z-index:2}.photo-upload-item .overlay{position:absolute;inset:0;background:#0009;display:flex;flex-direction:column;align-items:center;justify-content:center}.upload-status-text{color:#fff;margin-top:1rem;font-size:.9rem;text-shadow:0 1px 3px rgb(0 0 0 / 80%);text-align:center;padding:0 1rem}.photo-upload-item .error-overlay{background:#e06c75cc;cursor:pointer;border:none;padding:0;margin:0;width:100%}.photo-upload-item .btn-remove-photo{position:absolute;top:4px;right:4px;background:#000000b3;border:none;border-radius:50%;width:24px;height:24px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:#fff;padding:0}.photo-upload-item .btn-remove-photo:hover{background:var(--danger-color)}.spin-animation{animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.btn-publish{width:100%}.user-menu-container{position:relative}.user-menu-popover{position:absolute;top:100%;right:0;margin-top:10px;width:280px;background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;padding:1rem;z-index:3001}.menu-backdrop{position:fixed;inset:0;z-index:3000}.account-list{list-style:none;padding:0;margin:0}.account-item{display:flex;flex-direction:column;padding:1rem 0;border-bottom:1px solid #eee}.account-item:last-child{border-bottom:none;padding-bottom:0}.account-item:first-child{padding-top:0}.account-header{display:flex;justify-content:space-between;align-items:center}.account-status{font-size:.85rem;color:#898989;margin-top:.35rem;margin-left:calc(18px + .75rem);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.account-status strong{font-weight:600}.account-item.disabled{opacity:.5;pointer-events:none}.account-info{display:flex;align-items:center;gap:.75rem}.btn-text{background:none;border:none;padding:0;font-weight:600;cursor:pointer;font-size:.9rem}.text-primary{color:var(--link-color)}.text-danger{color:#dc3545}.btn-text:hover{text-decoration:underline}.sidebar{position:absolute;top:0;left:0;bottom:0;width:var(--sidebar-width);background:#fff;z-index:3100;box-shadow:2px 0 5px #0000001a;display:flex;flex-direction:column;overflow:hidden}.sidebar.app-menu-pane{z-index:3200}@media(max-width:768px){.sidebar.app-menu-pane{width:100%;right:0;border-radius:16px 16px 0 0;height:66vh;top:auto;bottom:0}}.sidebar-header{padding:1rem;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center}.sidebar-header.no-border{border-bottom-color:transparent}.sidebar-header h2{margin:0;font-size:1.2rem;display:flex;align-items:center;gap:.5rem}.sidebar-content{padding:1rem;overflow-y:auto;-webkit-overflow-scrolling:touch;flex:1;min-height:0;touch-action:pan-y;overscroll-behavior:contain}.app-menu-pane .sidebar-content{padding-top:.5rem}.app-menu{list-style:none;padding:0;margin:0 -1rem}.app-menu button{width:100%;display:flex;align-items:center;gap:.8rem;padding:1rem 1rem 1rem 1.4rem;background:none;border:none;color:#333;cursor:pointer;text-align:left;font-size:.95rem;font-family:inherit;transition:background-color .2s}.app-menu button:hover{background-color:var(--hover-bg)}.app-menu .icon{color:#666;width:20px;height:20px}.sidebar-content details{margin:0 -1rem}.sidebar-content details summary{list-style:none;display:flex;align-items:center;gap:.8rem;padding:1rem 1rem 1rem 1.4rem;cursor:pointer;font-size:.95rem;color:#333;transition:background-color .2s}.sidebar-content details summary::-webkit-details-marker{display:none}.sidebar-content details summary:hover{background-color:var(--hover-bg)}.sidebar-content details summary .icon{width:20px;height:20px}.sidebar-content details summary:after{content:"";width:20px;height:20px;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='9 18 15 12 9 6'/%3E%3C/svg%3E");background-size:20px 20px;background-repeat:no-repeat;background-position:center;margin-left:auto;transition:transform .2s ease}.sidebar-content details[open] summary:after{transform:rotate(90deg)}.sidebar-content details .details-content{padding:0 1.4rem 1rem;animation:details-slide-down .2s ease-out;font-size:.9rem;display:flex;flex-direction:column;gap:16px}.relay-list{list-style:none;padding:0;margin:0 0 .75rem;display:flex;flex-direction:column;gap:4px}.relay-list li{display:flex;justify-content:space-between;align-items:center;padding:.25rem 0;border-radius:4px;font-size:.9rem;word-break:break-all}.btn-remove-relay{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background-color:#fff;border:1px solid var(--danger-color);color:var(--danger-color);cursor:pointer;padding:0;transition:all .1s ease;flex-shrink:0}.btn-remove-relay svg{stroke:currentcolor}.btn-remove-relay:hover,.btn-remove-relay:active{background-color:var(--danger-color);color:#fff}.add-relay-input{display:flex;gap:.5rem}.btn-link.reset-relays{margin-top:.75rem;font-size:.85rem}@keyframes details-slide-down{0%{opacity:0;transform:translateY(-5px)}to{opacity:1;transform:translateY(0)}}.edit-form{margin:-1rem -1rem 1rem;background:var(--hover-bg);padding:1rem;border-bottom:1px solid #eee}.form-group{margin-bottom:.75rem}.form-group label{display:block;font-size:.85rem;color:#666;margin-bottom:.5rem}.form-control{width:100%;padding:.5rem;border:1px solid #ddd;border-radius:4px;font-family:inherit;font-size:1rem;box-sizing:border-box;color:#333;background-color:#fff}.form-control:focus{outline:none;border-color:var(--link-color);box-shadow:0 0 0 2px #2a7fff1a}select.form-control{appearance:none;background-color:#fff;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right .75rem center;background-size:16px 16px;padding-right:2.5rem;cursor:pointer}.edit-actions{display:flex;gap:.5rem;justify-content:flex-end}.settings-section{margin-bottom:2rem;font-size:.95rem}.settings-section .form-group{margin-top:.5rem;margin-bottom:0}.settings-section .form-group:first-of-type{margin-top:1rem}.about-section{margin-bottom:2rem}.about-section a{color:var(--link-color);text-decoration:none}.about-section a:visited{color:var(--link-color-visited)}.about-section a:hover{text-decoration:underline}.btn-full{width:100%}.btn-primary{background:var(--link-color);color:#fff;border:none;padding:.75rem;border-radius:4px;font-weight:500;cursor:pointer}.btn-primary:hover{background:#0069d9}.meta-info{font-size:.9rem}.meta-info p{margin-top:1rem;margin-bottom:1rem}.meta-info p:first-child{margin-top:1.2rem;padding-top:1.2rem;border-top:1px solid #eee}.meta-info a,.meta-info .btn-link{color:var(--link-color);text-decoration:none;background:none;border:none;padding:0;font:inherit;cursor:pointer}.meta-info a:hover,.meta-info .btn-link:hover{text-decoration:underline}.sidebar-content table{width:100%;border-collapse:collapse}.sidebar-content table th,.sidebar-content table td{padding:.5rem 0;text-align:left}.sidebar-content table th{font-size:.75rem;font-weight:700;text-transform:uppercase;color:#898989}.sidebar-content table td{border-bottom:1px solid #f9f9f9}.sidebar-content table tr:last-child td{border-bottom:none}abbr[title]{text-decoration:underline dotted}.places-list{list-style:none;padding:0;margin:-1rem -1rem 0}.place-item{width:100%;text-align:left;border:none;border-bottom:1px solid #eee;background:#fff;color:#333;padding:1rem;cursor:pointer;transition:background .2s;font-family:inherit}.place-item:hover{background:var(--hover-bg)}.place-name{font-size:1rem;font-weight:700;margin-bottom:.25rem}.place-type{color:#666;font-size:.85rem}.back-btn{background:none;border:none;cursor:pointer;padding:0 .5rem;margin-left:-.5rem;display:flex;align-items:center;justify-content:center}.close-btn{background:none;border:none;cursor:pointer;padding:0 .5rem;margin-right:-.5rem;display:flex;align-items:center;justify-content:center}.place-details{padding-bottom:2rem}.photo-carousel{position:relative}.photo-carousel.inline{margin:-1rem -1rem 1rem}.photo-carousel-track{display:flex;overflow-x:auto;scroll-behavior:smooth;scroll-snap-type:x mandatory;scrollbar-width:none;background-color:var(--hover-bg)}.photo-carousel-track::-webkit-scrollbar{display:none}.carousel-slide{cursor:pointer;position:relative;flex:0 0 100%;scroll-snap-align:start;aspect-ratio:16 / 9;display:flex;align-items:center;justify-content:center;overflow:hidden}.carousel-placeholder{display:none}.place-header-photo-blur{position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover;display:block}.place-header-photo{position:absolute;top:0;left:0;width:100%;height:100%;display:block;opacity:0;transition:opacity .3s ease-in-out;z-index:1}.place-header-photo.landscape{object-fit:cover}.place-header-photo.portrait{object-fit:contain}.place-header-photo.loaded{opacity:1}.place-header-photo.loaded-instant{opacity:1;transition:none}.carousel-nav-btn{position:absolute;top:50%;transform:translateY(-50%);background:#0000007f;color:#fff;border:none;border-radius:50%;width:36px;height:36px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:2;opacity:0;transition:opacity .2s,background-color .2s;padding:0}.photo-carousel:hover .carousel-nav-btn:not(.disabled){opacity:1}.carousel-nav-btn:not(.disabled):hover{background:#000c}.carousel-nav-btn.disabled{opacity:0;pointer-events:none}.carousel-nav-btn.prev{left:.5rem}.carousel-nav-btn.next{right:.5rem}@media(max-width:768px){.photo-carousel.inline .photo-carousel-track{scroll-snap-type:none;gap:2px;background-color:#fff}.photo-carousel.inline .carousel-slide{flex:0 0 auto;height:100px;width:auto;scroll-snap-align:none}.photo-carousel.inline .carousel-slide.landscape{aspect-ratio:var(--slide-ratio, 16 / 9)}.photo-carousel.inline .carousel-slide.portrait{aspect-ratio:1 / 1}.photo-carousel.inline .carousel-placeholder{display:block;background-color:var(--hover-bg);flex:1 1 0%;min-width:0}.photo-carousel.inline .place-header-photo.landscape,.photo-carousel.inline .place-header-photo.portrait{object-fit:cover}.photo-carousel.inline .carousel-nav-btn{display:none}}.place-details h3{font-size:1.2rem;margin-top:0;margin-bottom:.5rem}.place-details .place-type{color:#666;font-size:.9rem;margin:0 0 1rem}.place-details p.place-description{line-height:1.4}.place-details .actions{padding-bottom:.3rem;display:flex;flex-direction:row;gap:1rem;margin-top:1.5rem}.btn{padding:.6rem 1.2rem;border-radius:4px;cursor:pointer;font-size:.9rem;display:flex;align-items:center;justify-content:center;gap:.5rem}.btn:disabled{opacity:.5;cursor:not-allowed;pointer-events:none}.btn-outline{background:transparent;color:#333;border:1px solid #ccc}.btn-outline:hover{border:1px solid #898989}.btn-secondary{color:#333;border:1px solid rgb(255 204 51 / 20%);background:#ffcc334d}.btn-secondary:hover{background:#fc36}.btn-blue{background:var(--link-color);color:#fff;border:none}.btn-blue:hover{background:#0056b3}.btn-green{background:#198754;color:#fff;border:none}.btn-green:hover{background:#157347}.search-pulse{border-radius:50%;border:2px solid rgb(255 204 51 / 80%);background:#fc33;position:absolute;transform:translate3d(-50%,-50%,0);pointer-events:none;animation:pulse 1.5s infinite ease-out;box-sizing:border-box;display:none;will-change:transform,opacity;-webkit-backface-visibility:hidden;backface-visibility:hidden}.search-pulse.active{display:block}.search-pulse.blue{border-color:#39cc;background:#39c3}@keyframes pulse{0%{transform:translate3d(-50%,-50%,0) scale(.8);opacity:.8}to{transform:translate3d(-50%,-50%,0) scale(1.4);opacity:0}}.ol-control.ol-attribution{bottom:1rem}.ol-touch .ol-control.ol-attribution{bottom:.5rem}.ol-control.ol-zoom{bottom:3rem}.ol-touch .ol-control.ol-zoom{bottom:3.5rem}.ol-control.ol-locate{bottom:6.5rem}.ol-touch .ol-control.ol-locate{bottom:8.5rem}.ol-control.ol-rotate{bottom:9rem}.ol-touch .ol-control.ol-rotate{bottom:11.5rem}.ol-control.ol-attribution,.ol-control.ol-zoom,.ol-control.ol-locate,.ol-control.ol-rotate{top:auto;left:auto;right:1rem}.ol-touch .ol-control.ol-attribution,.ol-touch .ol-control.ol-zoom,.ol-touch .ol-control.ol-locate,.ol-touch .ol-control.ol-rotate{right:.5rem}.app-logo-icon{display:inline-flex;width:32px;height:32px;margin:-6px 0}.app-logo-icon svg{width:100%;height:100%}span.icon{display:inline-block}.icon{flex-shrink:0}.icon svg{width:100%;height:100%;stroke:currentcolor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.icon-filled svg{stroke:none;fill:currentcolor}.content-with-icon{display:flex;flex-direction:row;align-items:flex-start;gap:.5rem}.content-with-icon .icon{margin-top:.15rem}.selected-pin-container{position:absolute;transform:translate(-50%,-100%);pointer-events:none;display:none}.selected-pin-container.active{display:block;animation:drop-in .5s cubic-bezier(.175,.885,.32,1.275) forwards}.selected-pin{width:40px;height:40px;color:var(--marker-color-primary);filter:drop-shadow(0 4px 6px rgb(0 0 0 / 30%))}.selected-pin svg{width:100%;height:100%;fill:var(--marker-color-primary);stroke:var(--marker-color-dark);stroke-width:1}.selected-pin-shadow{width:10px;height:4px;background:#0000004d;border-radius:50%;position:absolute;bottom:0;left:50%;transform:translate(-50%);z-index:-1;opacity:0;animation:shadow-fade .5s .2s forwards}@keyframes drop-in{0%{transform:translate(-50%,-200%) scale(0);opacity:0}60%{opacity:1}to{transform:translate(-50%,-100%) scale(1);opacity:1}}@keyframes shadow-fade{to{opacity:1}}.map-crosshair{position:absolute;top:50%;left:50%;width:24px;height:24px;transform:translate(-50%,-50%);color:#333;pointer-events:none;z-index:2000;display:none;transition:top .3s ease,left .3s ease}.map-crosshair.visible{display:block}.map-container.sidebar-open .map-crosshair{left:calc(50% + var(--sidebar-width) / 2)}@media(max-width:768px){.map-container.sidebar-open .map-crosshair{left:50%;top:calc(25% + 30px)}}.helper-text{background:#eef4fc;color:#1a5c9b;padding:.75rem;border-radius:4px;font-size:.9rem;margin-top:0;margin-bottom:1rem;display:flex;align-items:center;gap:.5rem}button.create-place{width:100%;margin:1.5rem auto}@media(max-width:768px){.sidebar{width:100%;height:50vh;box-shadow:0 -2px 10px #0000001a;border-top-left-radius:16px;border-top-right-radius:16px;inset:auto 0 0}.sidebar-content{overflow-y:auto;padding-bottom:env(safe-area-inset-bottom,20px)}}.search-box{position:relative;width:100%;max-width:400px;margin-left:0;z-index:3002}@media(max-width:768px){.search-box{max-width:calc(100vw - 65px)}}.search-form{display:flex;align-items:center;background:#fff;border-radius:24px;box-shadow:0 2px 5px #00000026;padding:0 .5rem;height:48px;transition:box-shadow .2s}.search-form:focus-within{box-shadow:0 4px 12px #00000026}.menu-btn-integrated{background:transparent;border:none;padding:8px;margin-right:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;color:#5f6368}.menu-btn-integrated:hover{background:#0000000d}.search-icon{display:flex;align-items:center;justify-content:center;color:#5f6368;margin-right:.5rem;padding:8px}.search-input{border:none;background:transparent;flex:1;min-width:0;height:100%;font-size:1rem;color:#333;outline:none;width:100%;padding:0 4px;-webkit-appearance:none}.search-input::-webkit-search-cancel-button{-webkit-appearance:none}.search-submit-btn{background:transparent;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#5f6368;border-radius:50%;margin-left:4px;padding:8px}.search-submit-btn:hover{background:#0000000d;color:#333}.search-clear-btn{background:none;border:none;padding:8px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#5f6368;border-radius:50%;margin-left:2px}.search-clear-btn:hover{background:#0000000d;color:#333}.search-results-popover{position:absolute;top:100%;left:0;right:0;margin-top:8px;background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;overflow:hidden;max-height:400px;overflow-y:auto;z-index:3002}.search-results-list{list-style:none;padding:0;margin:0}.search-result-item{width:100%;display:flex;align-items:center;gap:.75rem;padding:.75rem 1rem;border:none;background:#fff;text-align:left;cursor:pointer;transition:background .1s;border-bottom:1px solid #f0f0f0}.search-result-item:last-child{border-bottom:none}.search-result-item:hover,.search-result-item:focus{background:var(--hover-bg);outline:none}.result-icon{display:flex;align-items:center;justify-content:center;width:32px;height:32px;background:#f0f0f0;border-radius:50%;flex-shrink:0;color:#666}.result-info{display:flex;flex-direction:column;overflow:hidden}.result-title{font-weight:500;color:#333;font-size:.95rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.result-desc{font-size:.8rem;color:#777;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px}.save-button-wrapper{position:relative}.place-lists-manager{position:absolute;top:100%;left:0;margin-top:.5rem;background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;width:220px;z-index:10;padding:.5rem 0}.place-lists-manager .list-item{padding:.5rem 1rem;display:flex;align-items:center}.place-lists-manager .list-item:hover{background:var(--hover-bg)}.place-lists-manager label{display:flex;align-items:center;gap:.75rem;width:100%;cursor:pointer;margin:0;font-size:.95rem;color:#333}.place-lists-manager input[type=checkbox]{accent-color:var(--link-color);width:16px;height:16px;cursor:pointer}.place-lists-manager .list-color{width:12px;height:12px;background-color:var(--default-list-color);border-radius:50%;flex-shrink:0;border:1px solid rgb(0 0 0 / 10%)}.place-lists-manager .divider{height:1px;background:#eee;margin:.5rem 0}.category-chips-scroll{width:100%;overflow-x:auto;padding:4px 0;-webkit-overflow-scrolling:touch;scrollbar-width:none;-ms-overflow-style:none;margin-top:0}.category-chips-scroll::-webkit-scrollbar{display:none}.category-chips-container{display:flex;gap:8px;padding:0 4px;width:max-content}.category-chip{display:flex;align-items:center;gap:6px;padding:6px 12px;background:#fff;border:1px solid #ddd;border-radius:16px;font-size:.9rem;color:#333;cursor:pointer;white-space:nowrap;box-shadow:0 1px 3px #0000001a;transition:background-color .2s}.category-chip:hover{background:var(--hover-bg)}.category-chip:active{background:#eee}.category-chip:disabled{opacity:.75;cursor:not-allowed;pointer-events:none}.toast-notification{position:fixed;bottom:2rem;left:50%;transform:translate(-50%);background-color:#333333d9;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);color:#fff;padding:.75rem 1.5rem;border-radius:999px;z-index:9999;box-shadow:0 4px 12px #00000026;animation:fade-in-up .3s ease-out forwards;text-align:center;max-width:90%;font-size:.9rem;font-weight:500;pointer-events:none}@keyframes fade-in-up{0%{opacity:0;transform:translate(-50%,1rem)}to{opacity:1;transform:translate(-50%)}}.nostr-connect-modal h2{margin-top:0}.nostr-connect-options{display:flex;flex-direction:column;gap:1rem;margin-top:1.5rem}.nostr-connect-status{margin-top:1.5rem;text-align:center}.qr-code-container{display:flex;justify-content:center;margin-top:1rem}.qr-code-container canvas{border-radius:8px;background:#fff}.modal-overlay{position:fixed;inset:0;background:#0000007f;z-index:9999;display:flex;align-items:center;justify-content:center}.modal-content{background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;padding:1.5rem;max-width:90vw;width:450px;position:relative}.close-modal-btn{position:absolute;top:1rem;right:1rem;cursor:pointer;color:#898989}.close-modal-btn.disabled{color:#ccc;cursor:not-allowed}.place-photo-upload h2{margin-top:0;font-size:1.2rem}.alert{padding:.5rem;margin-bottom:1rem;border-radius:.25rem}.alert-error{background:#fee;color:#c00}.preview-group{margin-bottom:1rem}.preview-group p{margin-bottom:.25rem;font-weight:700}.preview-group img{max-width:100%;border-radius:.25rem}.btn-link{background:none;border:none;padding:0;color:var(--link-color);text-decoration:none;cursor:pointer;font:inherit}.btn-link:hover{text-decoration:underline}.photo-gallery-overlay{position:fixed;inset:0;background:#000000e5;z-index:9999;display:flex;flex-direction:column}.photo-gallery-overlay .photo-gallery-content{width:100%;height:100%;display:flex;flex-direction:column;position:relative}.photo-gallery-overlay .close-btn{position:absolute;top:.5rem;right:1rem;width:48px;height:48px;z-index:10;color:#fff;background:transparent;border-radius:50%;display:flex;align-items:center;justify-content:center;transition:background-color .2s ease}@media(max-width:768px){.photo-gallery-overlay .close-btn{right:.5rem}}.photo-gallery-overlay .main-photo-container{flex:1;display:flex;align-items:center;justify-content:center;padding:2rem;overflow:hidden}@media(max-width:768px){.photo-gallery-overlay .main-photo-container{padding:2rem 0}}.photo-gallery-overlay .main-photo-container img{max-width:100%;max-height:100%;object-fit:contain}.photo-carousel.gallery-main{width:100%;height:100%;display:flex;flex-direction:column}.photo-carousel.gallery-main .photo-carousel-track{height:100%;background:transparent}.photo-carousel.gallery-main .carousel-slide{height:100%;flex:0 0 100%;aspect-ratio:auto;cursor:default}.photo-carousel.gallery-main .carousel-nav-btn{width:48px;height:48px}.photo-carousel.gallery-main .place-header-photo-blur,.photo-carousel.gallery-main .place-header-photo.landscape,.photo-carousel.gallery-main .place-header-photo.portrait{object-fit:contain}@media(max-width:768px){.photo-carousel.gallery-main .carousel-nav-btn{display:none}}.photo-carousel.gallery-thumbnails{width:100%;height:100px;background:#0000007f;padding-bottom:env(safe-area-inset-bottom,0)}.photo-carousel.gallery-thumbnails .photo-carousel-track{height:100%;background:transparent;gap:4px;scroll-snap-type:none;padding:0}.photo-carousel.gallery-thumbnails .carousel-slide{flex:0 0 auto;height:100%;width:auto;scroll-snap-align:none;opacity:.6;transition:opacity .2s}.photo-carousel.gallery-thumbnails .carousel-slide.landscape{aspect-ratio:var(--slide-ratio, 16 / 9)}.photo-carousel.gallery-thumbnails .carousel-slide.portrait{aspect-ratio:1 / 1}.photo-carousel.gallery-thumbnails .carousel-slide:hover,.photo-carousel.gallery-thumbnails .carousel-slide.active{opacity:1}.photo-carousel.gallery-thumbnails .place-header-photo.landscape,.photo-carousel.gallery-thumbnails .place-header-photo.portrait{object-fit:cover;height:100%}.photo-carousel.gallery-thumbnails .carousel-nav-btn{display:none}:root,:host{--ol-background-color: white;--ol-accent-background-color: #F5F5F5;--ol-subtle-background-color: rgba(128, 128, 128, .25);--ol-partial-background-color: rgba(255, 255, 255, .75);--ol-foreground-color: #333333;--ol-subtle-foreground-color: #666666;--ol-brand-color: #00AAFF}.ol-box{box-sizing:border-box;border-radius:2px;border:1.5px solid var(--ol-background-color);background-color:var(--ol-partial-background-color)}.ol-mouse-position{top:8px;right:8px;position:absolute}.ol-scale-line{background:var(--ol-partial-background-color);border-radius:4px;bottom:8px;left:8px;padding:2px;position:absolute}.ol-scale-line-inner{border:1px solid var(--ol-subtle-foreground-color);border-top:none;color:var(--ol-foreground-color);font-size:10px;text-align:center;margin:1px;will-change:contents,width;transition:all .25s}.ol-scale-bar{position:absolute;bottom:8px;left:8px}.ol-scale-bar-inner{display:flex}.ol-scale-step-marker{width:1px;height:15px;background-color:var(--ol-foreground-color);float:right;z-index:10}.ol-scale-step-text{position:absolute;bottom:-5px;font-size:10px;z-index:11;color:var(--ol-foreground-color);text-shadow:-1.5px 0 var(--ol-partial-background-color),0 1.5px var(--ol-partial-background-color),1.5px 0 var(--ol-partial-background-color),0 -1.5px var(--ol-partial-background-color)}.ol-scale-text{position:absolute;font-size:12px;text-align:center;bottom:25px;color:var(--ol-foreground-color);text-shadow:-1.5px 0 var(--ol-partial-background-color),0 1.5px var(--ol-partial-background-color),1.5px 0 var(--ol-partial-background-color),0 -1.5px var(--ol-partial-background-color)}.ol-scale-singlebar{position:relative;height:10px;z-index:9;box-sizing:border-box;border:1px solid var(--ol-foreground-color)}.ol-scale-singlebar-even{background-color:var(--ol-subtle-foreground-color)}.ol-scale-singlebar-odd{background-color:var(--ol-background-color)}.ol-unsupported{display:none}.ol-viewport,.ol-unselectable{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}.ol-viewport canvas{all:unset;overflow:hidden}.ol-viewport{touch-action:pan-x pan-y}.ol-selectable{-webkit-touch-callout:default;-webkit-user-select:text;-moz-user-select:text;user-select:text}.ol-grabbing{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.ol-grab{cursor:move;cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.ol-control{position:absolute;background-color:var(--ol-subtle-background-color);border-radius:4px}.ol-zoom{top:.5em;left:.5em}.ol-rotate{top:.5em;right:.5em;transition:opacity .25s linear,visibility 0s linear}.ol-rotate.ol-hidden{opacity:0;visibility:hidden;transition:opacity .25s linear,visibility 0s linear .25s}.ol-zoom-extent{top:4.643em;left:.5em}.ol-full-screen{right:.5em;top:.5em}.ol-control button{display:block;margin:1px;padding:0;color:var(--ol-subtle-foreground-color);font-weight:700;text-decoration:none;font-size:inherit;text-align:center;height:1.375em;width:1.375em;line-height:.4em;background-color:var(--ol-background-color);border:none;border-radius:2px}.ol-control button::-moz-focus-inner{border:none;padding:0}.ol-zoom-extent button{line-height:1.4em}.ol-compass{display:block;font-weight:400;will-change:transform}.ol-touch .ol-control button{font-size:1.5em}.ol-touch .ol-zoom-extent{top:5.5em}.ol-control button:hover,.ol-control button:focus{text-decoration:none;outline:1px solid var(--ol-subtle-foreground-color);color:var(--ol-foreground-color)}.ol-zoom .ol-zoom-in{border-radius:2px 2px 0 0}.ol-zoom .ol-zoom-out{border-radius:0 0 2px 2px}.ol-attribution{text-align:right;bottom:.5em;right:.5em;max-width:calc(100% - 1.3em);display:flex;flex-flow:row-reverse;align-items:center}.ol-attribution a{color:var(--ol-subtle-foreground-color);text-decoration:none}.ol-attribution ul{margin:0;padding:1px .5em;color:var(--ol-foreground-color);text-shadow:0 0 2px var(--ol-background-color);font-size:12px}.ol-attribution li{display:inline;list-style:none}.ol-attribution li:not(:last-child):after{content:" "}.ol-attribution img{max-height:2em;max-width:inherit;vertical-align:middle}.ol-attribution button{flex-shrink:0}.ol-attribution.ol-collapsed ul{display:none}.ol-attribution:not(.ol-collapsed){background:var(--ol-partial-background-color)}.ol-attribution.ol-uncollapsible{bottom:0;right:0;border-radius:4px 0 0}.ol-attribution.ol-uncollapsible img{margin-top:-.2em;max-height:1.6em}.ol-attribution.ol-uncollapsible button{display:none}.ol-zoomslider{top:4.5em;left:.5em;height:200px}.ol-zoomslider button{position:relative;height:10px}.ol-touch .ol-zoomslider{top:5.5em}.ol-overviewmap{left:.5em;bottom:.5em}.ol-overviewmap.ol-uncollapsible{bottom:0;left:0;border-radius:0 4px 0 0}.ol-overviewmap .ol-overviewmap-map,.ol-overviewmap button{display:block}.ol-overviewmap .ol-overviewmap-map{border:1px solid var(--ol-subtle-foreground-color);height:150px;width:150px}.ol-overviewmap:not(.ol-collapsed) button{bottom:0;left:0;position:absolute}.ol-overviewmap.ol-collapsed .ol-overviewmap-map,.ol-overviewmap.ol-uncollapsible button{display:none}.ol-overviewmap:not(.ol-collapsed){background:var(--ol-subtle-background-color)}.ol-overviewmap-box{border:1.5px dotted var(--ol-subtle-foreground-color)}.ol-overviewmap .ol-overviewmap-box:hover{cursor:move}.ol-overviewmap .ol-viewport:hover{cursor:pointer} diff --git a/release/assets/main-C_mgNoFX.css b/release/assets/main-C_mgNoFX.css new file mode 100644 index 0000000..c328452 --- /dev/null +++ b/release/assets/main-C_mgNoFX.css @@ -0,0 +1 @@ +:root{--default-list-color: #fc3;--hover-bg: #f8f9fa;--sidebar-width: 350px;--link-color: #2a7fff;--link-color-visited: #6a4fbf;--marker-color-primary: #ea4335;--marker-color-dark: #b31412;--danger-color: var(--marker-color-primary);--danger-color-dark: var(--marker-color-dark)}html,body{height:100%;overscroll-behavior:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}button{-webkit-tap-highlight-color:transparent}body{margin:0;font-family:Noto Sans,sans-serif;font-size:16px;font-weight:400;color:#333}#root,#ember-testing{height:100%}.map-container{background:#f8f9fa;-webkit-tap-highlight-color:transparent;outline:none;position:absolute;inset:0}#rs-widget-container{position:absolute;top:60px;right:10px;z-index:4000;display:none}#rs-widget-container.visible{display:block}.rs-backdrop{position:fixed;inset:0;z-index:3999}.app-header{position:absolute;top:0;left:0;right:0;height:60px;padding:.5rem 1rem;z-index:3000;pointer-events:none;display:grid;grid-template-columns:1fr auto 1fr;grid-template-areas:"search chips user";align-items:center;gap:1rem}@media(max-width:768px){.app-header{padding:.5rem .5rem 0;height:auto;grid-template-columns:1fr auto;grid-template-areas:"search user" "chips chips";row-gap:8px}}.header-left,.header-right,.header-center{pointer-events:auto}.header-left{display:flex;align-items:center;grid-area:search;justify-self:start;width:100%}@media not (max-width:768px){.header-left{min-width:300px;max-width:400px}}@media not (max-width:768px){.header-left{min-width:300px;max-width:350px}}.header-right{grid-area:user;justify-self:end}.header-center{grid-area:chips;display:flex;justify-content:center;min-width:0}@media not (max-width:768px){.header-center .category-chips-scroll{width:auto;max-width:100%}}@media(max-width:768px){.header-center{width:100%;overflow:hidden;justify-content:start}.header-center.searching{display:none}}.btn-press{transition:transform .1s}.btn-press:active{transform:scale(.95)}.user-btn{background:none;border:none;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}.user-avatar-placeholder{width:40px;height:40px;background:#2a3743;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0}.user-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;flex-shrink:0;display:block}.photo-preview-img{max-width:100%;height:auto}.dropzone{border:2px dashed #ccc;border-radius:8px;text-align:center;transition:all .2s ease;margin:1.5rem 0 1rem;background-color:#ffffff05;cursor:pointer;aspect-ratio:4 / 3}.dropzone.is-dragging{border-color:#61afef;background-color:#61afef0d}.dropzone-label{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1rem;cursor:pointer;color:#898989;width:100%;height:100%}.dropzone-label p{margin:0}.file-input-hidden{display:none}.photo-grid{display:flex;flex-direction:column;gap:12px;margin-bottom:20px}.photo-upload-item{position:relative;aspect-ratio:4 / 3;border-radius:6px;overflow:hidden;background:#1e262e;width:100%}.photo-upload-item img{position:absolute;top:0;left:0;width:100%;height:100%;object-fit:contain;display:block;z-index:1}.photo-upload-item .overlay,.photo-upload-item .btn-remove-photo{z-index:2}.photo-upload-item .overlay{position:absolute;inset:0;background:#0009;display:flex;flex-direction:column;align-items:center;justify-content:center}.upload-status-text{color:#fff;margin-top:1rem;font-size:.9rem;text-shadow:0 1px 3px rgb(0 0 0 / 80%);text-align:center;padding:0 1rem}.photo-upload-item .error-overlay{background:#e06c75cc;cursor:pointer;border:none;padding:0;margin:0;width:100%}.photo-upload-item .btn-remove-photo{position:absolute;top:4px;right:4px;background:#000000b3;border:none;border-radius:50%;width:24px;height:24px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:#fff;padding:0}.photo-upload-item .btn-remove-photo:hover{background:var(--danger-color)}.spin-animation{animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.btn-publish{width:100%}.user-menu-container{position:relative}.user-menu-popover{position:absolute;top:100%;right:0;margin-top:10px;width:280px;background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;padding:1rem;z-index:3001}.menu-backdrop{position:fixed;inset:0;z-index:3000}.account-list{list-style:none;padding:0;margin:0}.account-item{display:flex;flex-direction:column;padding:1rem 0;border-bottom:1px solid #eee}.account-item:last-child{border-bottom:none;padding-bottom:0}.account-item:first-child{padding-top:0}.account-header{display:flex;justify-content:space-between;align-items:center}.account-status{font-size:.85rem;color:#898989;margin-top:.35rem;margin-left:calc(18px + .75rem);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.account-status strong{font-weight:600}.account-item.disabled{opacity:.5;pointer-events:none}.account-info{display:flex;align-items:center;gap:.75rem}.btn-text{background:none;border:none;padding:0;font-weight:600;cursor:pointer;font-size:.9rem}.text-primary{color:var(--link-color)}.text-danger{color:#dc3545}.btn-text:hover{text-decoration:underline}.sidebar{position:absolute;top:0;left:0;bottom:0;width:var(--sidebar-width);background:#fff;z-index:3100;box-shadow:2px 0 5px #0000001a;display:flex;flex-direction:column;overflow:hidden}.sidebar.app-menu-pane{z-index:3200}@media(max-width:768px){.sidebar.app-menu-pane{width:100%;right:0;border-radius:16px 16px 0 0;height:66vh;top:auto;bottom:0}}.sidebar-header{padding:1rem;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center}.sidebar-header.no-border{border-bottom-color:transparent}.sidebar-header h2{margin:0;font-size:1.2rem;display:flex;align-items:center;gap:.5rem}.sidebar-content{padding:1rem;overflow-y:auto;-webkit-overflow-scrolling:touch;flex:1;min-height:0;touch-action:pan-y;overscroll-behavior:contain}.app-menu-pane .sidebar-content{padding-top:.5rem}.app-menu{list-style:none;padding:0;margin:0 -1rem}.app-menu button{width:100%;display:flex;align-items:center;gap:.8rem;padding:1rem 1rem 1rem 1.4rem;background:none;border:none;color:#333;cursor:pointer;text-align:left;font-size:.95rem;font-family:inherit;transition:background-color .2s}.app-menu button:hover{background-color:var(--hover-bg)}.app-menu .icon{color:#666;width:20px;height:20px}.sidebar-content details{margin:0 -1rem}.sidebar-content details summary{list-style:none;display:flex;align-items:center;gap:.8rem;padding:1rem 1rem 1rem 1.4rem;cursor:pointer;font-size:.95rem;color:#333;transition:background-color .2s}.sidebar-content details summary::-webkit-details-marker{display:none}.sidebar-content details summary:hover{background-color:var(--hover-bg)}.sidebar-content details summary .icon{width:20px;height:20px}.sidebar-content details summary:after{content:"";width:20px;height:20px;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='9 18 15 12 9 6'/%3E%3C/svg%3E");background-size:20px 20px;background-repeat:no-repeat;background-position:center;margin-left:auto;transition:transform .2s ease}.sidebar-content details[open] summary:after{transform:rotate(90deg)}.sidebar-content details .details-content{padding:0 1.4rem 1rem;animation:details-slide-down .2s ease-out;font-size:.9rem}.sidebar-content details .details-content.form-layout{display:flex;flex-direction:column;gap:16px}.relay-list{list-style:none;padding:0;margin:0 0 .75rem;display:flex;flex-direction:column;gap:4px}.relay-list li{display:flex;justify-content:space-between;align-items:center;padding:.25rem 0;border-radius:4px;font-size:.9rem;word-break:break-all}.btn-remove-relay{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background-color:#fff;border:1px solid var(--danger-color);color:var(--danger-color);cursor:pointer;padding:0;transition:all .1s ease;flex-shrink:0}.btn-remove-relay svg{stroke:currentcolor}.btn-remove-relay:hover,.btn-remove-relay:active{background-color:var(--danger-color);color:#fff}.add-relay-input{display:flex;gap:.5rem}.btn-link.reset-relays{margin-top:.75rem;font-size:.85rem}@keyframes details-slide-down{0%{opacity:0;transform:translateY(-5px)}to{opacity:1;transform:translateY(0)}}.edit-form{margin:-1rem -1rem 1rem;background:var(--hover-bg);padding:1rem;border-bottom:1px solid #eee}.form-group{margin-bottom:.75rem}.form-group label{display:block;font-size:.85rem;color:#666;margin-bottom:.5rem}.form-control{width:100%;padding:.5rem;border:1px solid #ddd;border-radius:4px;font-family:inherit;font-size:1rem;box-sizing:border-box;color:#333;background-color:#fff}.form-control:focus{outline:none;border-color:var(--link-color);box-shadow:0 0 0 2px #2a7fff1a}select.form-control{appearance:none;background-color:#fff;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right .75rem center;background-size:16px 16px;padding-right:2.5rem;cursor:pointer}.edit-actions{display:flex;gap:.5rem;justify-content:flex-end}.settings-section{margin-bottom:2rem;font-size:.95rem}.settings-section .form-group{margin-top:.5rem;margin-bottom:0}.settings-section .form-group:first-of-type{margin-top:1rem}.about-section{margin-bottom:2rem}.about-section a{color:var(--link-color);text-decoration:none}.about-section a:visited{color:var(--link-color-visited)}.about-section a:hover{text-decoration:underline}.btn-full{width:100%}.btn-primary{background:var(--link-color);color:#fff;border:none;padding:.75rem;border-radius:4px;font-weight:500;cursor:pointer}.btn-primary:hover{background:#0069d9}.meta-info{font-size:.9rem}.meta-info p{margin-top:1rem;margin-bottom:1rem}.meta-info p:first-child{margin-top:1.2rem;padding-top:1.2rem;border-top:1px solid #eee}.meta-info a,.meta-info .btn-link{color:var(--link-color);text-decoration:none;background:none;border:none;padding:0;font:inherit;cursor:pointer}.meta-info a:hover,.meta-info .btn-link:hover{text-decoration:underline}.sidebar-content table{width:100%;border-collapse:collapse}.sidebar-content table th,.sidebar-content table td{padding:.5rem 0;text-align:left}.sidebar-content table th{font-size:.75rem;font-weight:700;text-transform:uppercase;color:#898989}.sidebar-content table td{border-bottom:1px solid #f9f9f9}.sidebar-content table tr:last-child td{border-bottom:none}abbr[title]{text-decoration:underline dotted}.places-list{list-style:none;padding:0;margin:-1rem -1rem 0}.place-item{width:100%;text-align:left;border:none;border-bottom:1px solid #eee;background:#fff;color:#333;padding:1rem;cursor:pointer;transition:background .2s;font-family:inherit}.place-item:hover{background:var(--hover-bg)}.place-name{font-size:1rem;font-weight:700;margin-bottom:.25rem}.place-type{color:#666;font-size:.85rem}.back-btn{background:none;border:none;cursor:pointer;padding:0 .5rem;margin-left:-.5rem;display:flex;align-items:center;justify-content:center}.close-btn{background:none;border:none;cursor:pointer;padding:0 .5rem;margin-right:-.5rem;display:flex;align-items:center;justify-content:center}.place-details{padding-bottom:2rem}.photo-carousel{position:relative}.photo-carousel.inline{margin:-1rem -1rem 1rem}.photo-carousel-track{display:flex;overflow-x:auto;scroll-behavior:smooth;scroll-snap-type:x mandatory;scrollbar-width:none;background-color:var(--hover-bg)}.photo-carousel-track::-webkit-scrollbar{display:none}.carousel-slide{cursor:pointer;position:relative;flex:0 0 100%;scroll-snap-align:start;aspect-ratio:16 / 9;display:flex;align-items:center;justify-content:center;overflow:hidden}.carousel-placeholder{display:none}.place-header-photo-blur{position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover;display:block}.place-header-photo{position:absolute;top:0;left:0;width:100%;height:100%;display:block;opacity:0;transition:opacity .3s ease-in-out;z-index:1}.place-header-photo.landscape{object-fit:cover}.place-header-photo.portrait{object-fit:contain}.place-header-photo.loaded{opacity:1}.place-header-photo.loaded-instant{opacity:1;transition:none}.carousel-nav-btn{position:absolute;top:50%;transform:translateY(-50%);background:#0000007f;color:#fff;border:none;border-radius:50%;width:36px;height:36px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:2;opacity:0;transition:opacity .2s,background-color .2s;padding:0}.photo-carousel:hover .carousel-nav-btn:not(.disabled){opacity:1}.carousel-nav-btn:not(.disabled):hover{background:#000c}.carousel-nav-btn.disabled{opacity:0;pointer-events:none}.carousel-nav-btn.prev{left:.5rem}.carousel-nav-btn.next{right:.5rem}@media(max-width:768px){.photo-carousel.inline .photo-carousel-track{scroll-snap-type:none;gap:2px;background-color:#fff}.photo-carousel.inline .carousel-slide{flex:0 0 auto;height:100px;width:auto;scroll-snap-align:none}.photo-carousel.inline .carousel-slide.landscape{aspect-ratio:var(--slide-ratio, 16 / 9)}.photo-carousel.inline .carousel-slide.portrait{aspect-ratio:1 / 1}.photo-carousel.inline .carousel-placeholder{display:block;background-color:var(--hover-bg);flex:1 1 0%;min-width:0}.photo-carousel.inline .place-header-photo.landscape,.photo-carousel.inline .place-header-photo.portrait{object-fit:cover}.photo-carousel.inline .carousel-nav-btn{display:none}}.place-details h3{font-size:1.2rem;margin-top:0;margin-bottom:.5rem}.place-details .place-type{color:#666;font-size:.9rem;margin:0 0 1rem}.place-details p.place-description{line-height:1.4}.place-details .actions{padding-bottom:.3rem;display:flex;flex-direction:row;gap:1rem;margin-top:1.5rem}.btn{padding:.6rem 1.2rem;border-radius:4px;cursor:pointer;font-size:.9rem;display:flex;align-items:center;justify-content:center;gap:.5rem}.btn:disabled{opacity:.5;cursor:not-allowed;pointer-events:none}.btn-outline{background:transparent;color:#333;border:1px solid #ccc}.btn-outline:hover{border:1px solid #898989}.btn-secondary{color:#333;border:1px solid rgb(255 204 51 / 20%);background:#ffcc334d}.btn-secondary:hover{background:#fc36}.btn-blue{background:var(--link-color);color:#fff;border:none}.btn-blue:hover{background:#0056b3}.btn-green{background:#198754;color:#fff;border:none}.btn-green:hover{background:#157347}.search-pulse{border-radius:50%;border:2px solid rgb(255 204 51 / 80%);background:#fc33;position:absolute;transform:translate3d(-50%,-50%,0);pointer-events:none;animation:pulse 1.5s infinite ease-out;box-sizing:border-box;display:none;will-change:transform,opacity;-webkit-backface-visibility:hidden;backface-visibility:hidden}.search-pulse.active{display:block}.search-pulse.blue{border-color:#39cc;background:#39c3}@keyframes pulse{0%{transform:translate3d(-50%,-50%,0) scale(.8);opacity:.8}to{transform:translate3d(-50%,-50%,0) scale(1.4);opacity:0}}.ol-control.ol-attribution{bottom:1rem}.ol-touch .ol-control.ol-attribution{bottom:.5rem}.ol-control.ol-zoom{bottom:3rem}.ol-touch .ol-control.ol-zoom{bottom:3.5rem}.ol-control.ol-locate{bottom:6.5rem}.ol-touch .ol-control.ol-locate{bottom:8.5rem}.ol-control.ol-rotate{bottom:9rem}.ol-touch .ol-control.ol-rotate{bottom:11.5rem}.ol-control.ol-attribution,.ol-control.ol-zoom,.ol-control.ol-locate,.ol-control.ol-rotate{top:auto;left:auto;right:1rem}.ol-touch .ol-control.ol-attribution,.ol-touch .ol-control.ol-zoom,.ol-touch .ol-control.ol-locate,.ol-touch .ol-control.ol-rotate{right:.5rem}.app-logo-icon{display:inline-flex;width:32px;height:32px;margin:-6px 0}.app-logo-icon svg{width:100%;height:100%}span.icon{display:inline-block}.icon{flex-shrink:0}.icon svg{width:100%;height:100%;stroke:currentcolor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.icon-filled svg{stroke:none;fill:currentcolor}.content-with-icon{display:flex;flex-direction:row;align-items:flex-start;gap:.5rem}.content-with-icon .icon{margin-top:.15rem}.selected-pin-container{position:absolute;transform:translate(-50%,-100%);pointer-events:none;display:none}.selected-pin-container.active{display:block;animation:drop-in .5s cubic-bezier(.175,.885,.32,1.275) forwards}.selected-pin{width:40px;height:40px;color:var(--marker-color-primary);filter:drop-shadow(0 4px 6px rgb(0 0 0 / 30%))}.selected-pin svg{width:100%;height:100%;fill:var(--marker-color-primary);stroke:var(--marker-color-dark);stroke-width:1}.selected-pin-shadow{width:10px;height:4px;background:#0000004d;border-radius:50%;position:absolute;bottom:0;left:50%;transform:translate(-50%);z-index:-1;opacity:0;animation:shadow-fade .5s .2s forwards}@keyframes drop-in{0%{transform:translate(-50%,-200%) scale(0);opacity:0}60%{opacity:1}to{transform:translate(-50%,-100%) scale(1);opacity:1}}@keyframes shadow-fade{to{opacity:1}}.map-crosshair{position:absolute;top:50%;left:50%;width:24px;height:24px;transform:translate(-50%,-50%);color:#333;pointer-events:none;z-index:2000;display:none;transition:top .3s ease,left .3s ease}.map-crosshair.visible{display:block}.map-container.sidebar-open .map-crosshair{left:calc(50% + var(--sidebar-width) / 2)}@media(max-width:768px){.map-container.sidebar-open .map-crosshair{left:50%;top:calc(25% + 30px)}}.helper-text{background:#eef4fc;color:#1a5c9b;padding:.75rem;border-radius:4px;font-size:.9rem;margin-top:0;margin-bottom:1rem;display:flex;align-items:center;gap:.5rem}button.create-place{width:100%;margin:1.5rem auto}@media(max-width:768px){.sidebar{width:100%;height:50vh;box-shadow:0 -2px 10px #0000001a;border-top-left-radius:16px;border-top-right-radius:16px;inset:auto 0 0}.sidebar-content{overflow-y:auto;padding-bottom:env(safe-area-inset-bottom,20px)}}.search-box{position:relative;width:100%;max-width:400px;margin-left:0;z-index:3002}@media(max-width:768px){.search-box{max-width:calc(100vw - 65px)}}.search-form{display:flex;align-items:center;background:#fff;border-radius:24px;box-shadow:0 2px 5px #00000026;padding:0 .5rem;height:48px;transition:box-shadow .2s}.search-form:focus-within{box-shadow:0 4px 12px #00000026}.menu-btn-integrated{background:transparent;border:none;padding:8px;margin-right:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;color:#5f6368}.menu-btn-integrated:hover{background:#0000000d}.search-icon{display:flex;align-items:center;justify-content:center;color:#5f6368;margin-right:.5rem;padding:8px}.search-input{border:none;background:transparent;flex:1;min-width:0;height:100%;font-size:1rem;color:#333;outline:none;width:100%;padding:0 4px;-webkit-appearance:none}.search-input::-webkit-search-cancel-button{-webkit-appearance:none}.search-submit-btn{background:transparent;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#5f6368;border-radius:50%;margin-left:4px;padding:8px}.search-submit-btn:hover{background:#0000000d;color:#333}.search-clear-btn{background:none;border:none;padding:8px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#5f6368;border-radius:50%;margin-left:2px}.search-clear-btn:hover{background:#0000000d;color:#333}.search-results-popover{position:absolute;top:100%;left:0;right:0;margin-top:8px;background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;overflow:hidden;max-height:400px;overflow-y:auto;z-index:3002}.search-results-list{list-style:none;padding:0;margin:0}.search-result-item{width:100%;display:flex;align-items:center;gap:.75rem;padding:.75rem 1rem;border:none;background:#fff;text-align:left;cursor:pointer;transition:background .1s;border-bottom:1px solid #f0f0f0}.search-result-item:last-child{border-bottom:none}.search-result-item:hover,.search-result-item:focus{background:var(--hover-bg);outline:none}.result-icon{display:flex;align-items:center;justify-content:center;width:32px;height:32px;background:#f0f0f0;border-radius:50%;flex-shrink:0;color:#666}.result-info{display:flex;flex-direction:column;overflow:hidden}.result-title{font-weight:500;color:#333;font-size:.95rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.result-desc{font-size:.8rem;color:#777;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px}.save-button-wrapper{position:relative}.place-lists-manager{position:absolute;top:100%;left:0;margin-top:.5rem;background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;width:220px;z-index:10;padding:.5rem 0}.place-lists-manager .list-item{padding:.5rem 1rem;display:flex;align-items:center}.place-lists-manager .list-item:hover{background:var(--hover-bg)}.place-lists-manager label{display:flex;align-items:center;gap:.75rem;width:100%;cursor:pointer;margin:0;font-size:.95rem;color:#333}.place-lists-manager input[type=checkbox]{accent-color:var(--link-color);width:16px;height:16px;cursor:pointer}.place-lists-manager .list-color{width:12px;height:12px;background-color:var(--default-list-color);border-radius:50%;flex-shrink:0;border:1px solid rgb(0 0 0 / 10%)}.place-lists-manager .divider{height:1px;background:#eee;margin:.5rem 0}.category-chips-scroll{width:100%;overflow-x:auto;padding:4px 0;-webkit-overflow-scrolling:touch;scrollbar-width:none;-ms-overflow-style:none;margin-top:0}.category-chips-scroll::-webkit-scrollbar{display:none}.category-chips-container{display:flex;gap:8px;padding:0 4px;width:max-content}.category-chip{display:flex;align-items:center;gap:6px;padding:6px 12px;background:#fff;border:1px solid #ddd;border-radius:16px;font-size:.9rem;color:#333;cursor:pointer;white-space:nowrap;box-shadow:0 1px 3px #0000001a;transition:background-color .2s}.category-chip:hover{background:var(--hover-bg)}.category-chip:active{background:#eee}.category-chip:disabled{opacity:.75;cursor:not-allowed;pointer-events:none}.toast-notification{position:fixed;bottom:2rem;left:50%;transform:translate(-50%);background-color:#333333d9;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);color:#fff;padding:.75rem 1.5rem;border-radius:999px;z-index:9999;box-shadow:0 4px 12px #00000026;animation:fade-in-up .3s ease-out forwards;text-align:center;max-width:90%;font-size:.9rem;font-weight:500;pointer-events:none}@keyframes fade-in-up{0%{opacity:0;transform:translate(-50%,1rem)}to{opacity:1;transform:translate(-50%)}}.nostr-connect-modal h2{margin-top:0}.nostr-connect-options{display:flex;flex-direction:column;gap:1rem;margin-top:1.5rem}.nostr-connect-status{margin-top:1.5rem;text-align:center}.qr-code-container{display:flex;justify-content:center;margin-top:1rem}.qr-code-container canvas{border-radius:8px;background:#fff}.modal-overlay{position:fixed;inset:0;background:#0000007f;z-index:9999;display:flex;align-items:center;justify-content:center}.modal-content{background:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;padding:1.5rem;max-width:90vw;width:450px;position:relative}.close-modal-btn{position:absolute;top:1rem;right:1rem;cursor:pointer;color:#898989}.close-modal-btn.disabled{color:#ccc;cursor:not-allowed}.place-photo-upload h2{margin-top:0;font-size:1.2rem}.alert{padding:.5rem;margin-bottom:1rem;border-radius:.25rem}.alert-error{background:#fee;color:#c00}.preview-group{margin-bottom:1rem}.preview-group p{margin-bottom:.25rem;font-weight:700}.preview-group img{max-width:100%;border-radius:.25rem}.btn-link{background:none;border:none;padding:0;color:var(--link-color);text-decoration:none;cursor:pointer;font:inherit}.btn-link:hover{text-decoration:underline}.photo-gallery-overlay{position:fixed;inset:0;background:#000000e5;z-index:9999;display:flex;flex-direction:column}.photo-gallery-overlay .photo-gallery-content{width:100%;height:100%;display:flex;flex-direction:column;position:relative}.photo-gallery-overlay .close-btn{position:absolute;top:.5rem;right:1rem;width:48px;height:48px;z-index:10;color:#fff;background:transparent;border-radius:50%;display:flex;align-items:center;justify-content:center;transition:background-color .2s ease}@media(max-width:768px){.photo-gallery-overlay .close-btn{right:.5rem}}.photo-gallery-overlay .main-photo-container{flex:1;display:flex;align-items:center;justify-content:center;padding:2rem;overflow:hidden}@media(max-width:768px){.photo-gallery-overlay .main-photo-container{padding:2rem 0}}.photo-gallery-overlay .main-photo-container img{max-width:100%;max-height:100%;object-fit:contain}.photo-carousel.gallery-main{width:100%;height:100%;display:flex;flex-direction:column}.photo-carousel.gallery-main .photo-carousel-track{height:100%;background:transparent}.photo-carousel.gallery-main .carousel-slide{height:100%;flex:0 0 100%;aspect-ratio:auto;cursor:default}.photo-carousel.gallery-main .carousel-nav-btn{width:48px;height:48px}.photo-carousel.gallery-main .place-header-photo-blur,.photo-carousel.gallery-main .place-header-photo.landscape,.photo-carousel.gallery-main .place-header-photo.portrait{object-fit:contain}@media(max-width:768px){.photo-carousel.gallery-main .carousel-nav-btn{display:none}}.photo-carousel.gallery-thumbnails{width:100%;height:100px;background:#0000007f;padding-bottom:env(safe-area-inset-bottom,0)}.photo-carousel.gallery-thumbnails .photo-carousel-track{height:100%;background:transparent;gap:4px;scroll-snap-type:none;padding:0}.photo-carousel.gallery-thumbnails .carousel-slide{flex:0 0 auto;height:100%;width:auto;scroll-snap-align:none;opacity:.6;transition:opacity .2s}.photo-carousel.gallery-thumbnails .carousel-slide.landscape{aspect-ratio:var(--slide-ratio, 16 / 9)}.photo-carousel.gallery-thumbnails .carousel-slide.portrait{aspect-ratio:1 / 1}.photo-carousel.gallery-thumbnails .carousel-slide:hover,.photo-carousel.gallery-thumbnails .carousel-slide.active{opacity:1}.photo-carousel.gallery-thumbnails .place-header-photo.landscape,.photo-carousel.gallery-thumbnails .place-header-photo.portrait{object-fit:cover;height:100%}.photo-carousel.gallery-thumbnails .carousel-nav-btn{display:none}:root,:host{--ol-background-color: white;--ol-accent-background-color: #F5F5F5;--ol-subtle-background-color: rgba(128, 128, 128, .25);--ol-partial-background-color: rgba(255, 255, 255, .75);--ol-foreground-color: #333333;--ol-subtle-foreground-color: #666666;--ol-brand-color: #00AAFF}.ol-box{box-sizing:border-box;border-radius:2px;border:1.5px solid var(--ol-background-color);background-color:var(--ol-partial-background-color)}.ol-mouse-position{top:8px;right:8px;position:absolute}.ol-scale-line{background:var(--ol-partial-background-color);border-radius:4px;bottom:8px;left:8px;padding:2px;position:absolute}.ol-scale-line-inner{border:1px solid var(--ol-subtle-foreground-color);border-top:none;color:var(--ol-foreground-color);font-size:10px;text-align:center;margin:1px;will-change:contents,width;transition:all .25s}.ol-scale-bar{position:absolute;bottom:8px;left:8px}.ol-scale-bar-inner{display:flex}.ol-scale-step-marker{width:1px;height:15px;background-color:var(--ol-foreground-color);float:right;z-index:10}.ol-scale-step-text{position:absolute;bottom:-5px;font-size:10px;z-index:11;color:var(--ol-foreground-color);text-shadow:-1.5px 0 var(--ol-partial-background-color),0 1.5px var(--ol-partial-background-color),1.5px 0 var(--ol-partial-background-color),0 -1.5px var(--ol-partial-background-color)}.ol-scale-text{position:absolute;font-size:12px;text-align:center;bottom:25px;color:var(--ol-foreground-color);text-shadow:-1.5px 0 var(--ol-partial-background-color),0 1.5px var(--ol-partial-background-color),1.5px 0 var(--ol-partial-background-color),0 -1.5px var(--ol-partial-background-color)}.ol-scale-singlebar{position:relative;height:10px;z-index:9;box-sizing:border-box;border:1px solid var(--ol-foreground-color)}.ol-scale-singlebar-even{background-color:var(--ol-subtle-foreground-color)}.ol-scale-singlebar-odd{background-color:var(--ol-background-color)}.ol-unsupported{display:none}.ol-viewport,.ol-unselectable{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}.ol-viewport canvas{all:unset;overflow:hidden}.ol-viewport{touch-action:pan-x pan-y}.ol-selectable{-webkit-touch-callout:default;-webkit-user-select:text;-moz-user-select:text;user-select:text}.ol-grabbing{cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.ol-grab{cursor:move;cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.ol-control{position:absolute;background-color:var(--ol-subtle-background-color);border-radius:4px}.ol-zoom{top:.5em;left:.5em}.ol-rotate{top:.5em;right:.5em;transition:opacity .25s linear,visibility 0s linear}.ol-rotate.ol-hidden{opacity:0;visibility:hidden;transition:opacity .25s linear,visibility 0s linear .25s}.ol-zoom-extent{top:4.643em;left:.5em}.ol-full-screen{right:.5em;top:.5em}.ol-control button{display:block;margin:1px;padding:0;color:var(--ol-subtle-foreground-color);font-weight:700;text-decoration:none;font-size:inherit;text-align:center;height:1.375em;width:1.375em;line-height:.4em;background-color:var(--ol-background-color);border:none;border-radius:2px}.ol-control button::-moz-focus-inner{border:none;padding:0}.ol-zoom-extent button{line-height:1.4em}.ol-compass{display:block;font-weight:400;will-change:transform}.ol-touch .ol-control button{font-size:1.5em}.ol-touch .ol-zoom-extent{top:5.5em}.ol-control button:hover,.ol-control button:focus{text-decoration:none;outline:1px solid var(--ol-subtle-foreground-color);color:var(--ol-foreground-color)}.ol-zoom .ol-zoom-in{border-radius:2px 2px 0 0}.ol-zoom .ol-zoom-out{border-radius:0 0 2px 2px}.ol-attribution{text-align:right;bottom:.5em;right:.5em;max-width:calc(100% - 1.3em);display:flex;flex-flow:row-reverse;align-items:center}.ol-attribution a{color:var(--ol-subtle-foreground-color);text-decoration:none}.ol-attribution ul{margin:0;padding:1px .5em;color:var(--ol-foreground-color);text-shadow:0 0 2px var(--ol-background-color);font-size:12px}.ol-attribution li{display:inline;list-style:none}.ol-attribution li:not(:last-child):after{content:" "}.ol-attribution img{max-height:2em;max-width:inherit;vertical-align:middle}.ol-attribution button{flex-shrink:0}.ol-attribution.ol-collapsed ul{display:none}.ol-attribution:not(.ol-collapsed){background:var(--ol-partial-background-color)}.ol-attribution.ol-uncollapsible{bottom:0;right:0;border-radius:4px 0 0}.ol-attribution.ol-uncollapsible img{margin-top:-.2em;max-height:1.6em}.ol-attribution.ol-uncollapsible button{display:none}.ol-zoomslider{top:4.5em;left:.5em;height:200px}.ol-zoomslider button{position:relative;height:10px}.ol-touch .ol-zoomslider{top:5.5em}.ol-overviewmap{left:.5em;bottom:.5em}.ol-overviewmap.ol-uncollapsible{bottom:0;left:0;border-radius:0 4px 0 0}.ol-overviewmap .ol-overviewmap-map,.ol-overviewmap button{display:block}.ol-overviewmap .ol-overviewmap-map{border:1px solid var(--ol-subtle-foreground-color);height:150px;width:150px}.ol-overviewmap:not(.ol-collapsed) button{bottom:0;left:0;position:absolute}.ol-overviewmap.ol-collapsed .ol-overviewmap-map,.ol-overviewmap.ol-uncollapsible button{display:none}.ol-overviewmap:not(.ol-collapsed){background:var(--ol-subtle-background-color)}.ol-overviewmap-box{border:1.5px dotted var(--ol-subtle-foreground-color)}.ol-overviewmap .ol-overviewmap-box:hover{cursor:move}.ol-overviewmap .ol-viewport:hover{cursor:pointer} diff --git a/release/assets/main-B30qTale.js b/release/assets/main-DsygQlAh.js similarity index 66% rename from release/assets/main-B30qTale.js rename to release/assets/main-DsygQlAh.js index 6c26e46..21c3ee0 100644 --- a/release/assets/main-B30qTale.js +++ b/release/assets/main-DsygQlAh.js @@ -10,5 +10,5 @@ function getHash(e){return{hash:e,hmac:(t,...r)=>hmac$1(e,t,concatBytes$2(...r)) /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ function assertNumber(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function chain(...e){const t=(e,t)=>r=>e(t(r)),r=Array.from(e).reverse().reduce((e,r)=>e?t(e,r.encode):r.encode,void 0),n=e.reduce((e,r)=>e?t(e,r.decode):r.decode,void 0);return{encode:r,decode:n}}function alphabet(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("alphabet.encode input should be an array of numbers");return t.map(t=>{if(assertNumber(t),t<0||t>=e.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${e.length})`);return e[t]})},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map(t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const r=e.indexOf(t);if(-1===r)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return r})}}}function join(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function padding(e,t="="){if(assertNumber(e),"string"!=typeof t)throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;r.length*e%8;)r.push(t);return r},decode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=r.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function normalize(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function convertRadix(e,t,r){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let n=0;const i=[],o=Array.from(e);for(o.forEach(e=>{if(assertNumber(e),e<0||e>=t)throw new Error(`Wrong integer: ${e}`)});;){let e=0,s=!0;for(let i=n;inew SHA224);const gcd=(e,t)=>t?gcd(t,e%t):e,radix2carry=(e,t)=>e+(t-gcd(e,t));function convertRadix2(e,t,r,n){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(radix2carry(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${radix2carry(t,r)}`);let i=0,o=0;const s=2**r-1,a=[];for(const l of e){if(assertNumber(l),l>=2**t)throw new Error(`convertRadix2: invalid data word=${l} from=${t}`);if(i=i<32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${t}`);for(o+=t;o>=r;o-=r)a.push((i>>o-r&s)>>>0);i&=2**o-1}if(i=i<=t)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&a.push(i>>>0),a}function radix(e){return assertNumber(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(convertRadix(t,e,256))}}}function radix2(e,t=!1){if(assertNumber(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,e)>32||radix2carry(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(r),8,e,!t)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(convertRadix2(r,e,8,t))}}}function unsafeWrapper(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(r){}}}const base16=chain(radix2(4),alphabet("0123456789ABCDEF"),join("")),base32$1=chain(radix2(5),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),padding(5),join(""));chain(radix2(5),alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"),padding(5),join("")),chain(radix2(5),alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),join(""),normalize(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const base64=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join("")),base64url=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding(6),join("")),genBase58=e=>chain(radix(58),alphabet(e),join("")),base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const XMR_BLOCK_LEN=[0,2,3,5,6,7,9,10,11],base58xmr={encode(e){let t="";for(let r=0;r>25;let r=(33554431&e)<<5;for(let n=0;n>n&1)&&(r^=POLYMOD_GENERATORS[n]);return r}function bechChecksum(e,t,r=1){const n=e.length;let i=1;for(let o=0;o126)throw new Error(`Invalid prefix (${e})`);i=bech32Polymod(i)^t>>5}i=bech32Polymod(i);for(let o=0;or)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${r})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=(e=n).lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const o=e.slice(0,i),s=e.slice(i+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=BECH_ALPHABET.decode(s).slice(0,-6),l=bechChecksum(o,a,t);if(!s.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:o,words:a}}return{encode:function(e,r,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof r);const i=e.length+7+r.length;if(!1!==n&&i>n)throw new TypeError(`Length ${i} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${BECH_ALPHABET.encode(r)}${bechChecksum(e,r,t)}`},decode:s,decodeToBytes:function(e){const{prefix:t,words:r}=s(e,!1);return{prefix:t,words:r,bytes:n(r)}},decodeUnsafe:unsafeWrapper(s),fromWords:n,fromWordsUnsafe:o,toWords:i}}const bech32=genBech32("bech32");genBech32("bech32m");const utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},hex=chain(radix2(4),alphabet("0123456789abcdef"),join(""),normalize(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})),CODERS={utf8:utf8,hex:hex,base16:base16,base32:base32$1,base64:base64,base64url:base64url,base58:base58,base58xmr:base58xmr};function number(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function bool(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function isBytes$2(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function bytes(e,...t){if(!isBytes$2(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)} /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Object.keys(CODERS).join(", ");const u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!isLE)throw new Error("Non little-endian hardware is not supported");const hexes$1=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex$1(e){bytes(e);let t="";for(let r=0;r=asciis$1._0&&e<=asciis$1._9?e-asciis$1._0:e>=asciis$1._A&&e<=asciis$1._F?e-(asciis$1._A-10):e>=asciis$1._a&&e<=asciis$1._f?e-(asciis$1._a-10):void 0}function hexToBytes$1(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,o=0;i(Object.assign(t,e),t),BLOCK_SIZE=16,POLY=283;function mul2(e){return e<<1^POLY&-(e>>7)}function mul(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=mul2(e);return r}const sbox=(()=>{let e=new Uint8Array(256);for(let r=0,n=1;r<256;r++,n^=mul2(n))e[r]=n;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return t})(),invSbox=sbox.map((e,t)=>sbox.indexOf(t)),rotr32_8=e=>e<<24|e>>>8,rotl32_8=e=>e<<8|e>>>24;function genTtable(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map((r,n)=>t(e[n])),n=r.map(rotl32_8),i=n.map(rotl32_8),o=i.map(rotl32_8),s=new Uint32Array(65536),a=new Uint32Array(65536),l=new Uint16Array(65536);for(let c=0;c<256;c++)for(let t=0;t<256;t++){const u=256*c+t;s[u]=r[c]^n[t],a[u]=i[c]^o[t],l[u]=e[c]<<8|e[t]}return{sbox:e,sbox2:l,T0:r,T1:n,T2:i,T3:o,T01:s,T23:a}}const tableEncoding=genTtable(sbox,e=>mul(e,3)<<24|e<<16|e<<8|mul(e,2)),tableDecoding=genTtable(invSbox,e=>mul(e,11)<<24|mul(e,13)<<16|mul(e,9)<<8|mul(e,14)),xPowers=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=mul2(r))e[t]=r;return e})();function expandKeyLE(e){bytes(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:r}=tableEncoding,n=u32(e),i=n.length,o=e=>applySbox(r,e,e,e,e),s=new Uint32Array(t+28);s.set(n);for(let a=i;a6&&a%i===4&&(e=o(e)),s[a]=s[a-i]^e}return s}function expandKeyDecLE(e){const t=expandKeyLE(e),r=t.slice(),n=t.length,{sbox2:i}=tableEncoding,{T0:o,T1:s,T2:a,T3:l}=tableDecoding;for(let c=0;c>>8&255]^a[t>>>16&255]^l[t>>>24]}return r}function apply0123(e,t,r,n,i,o){return e[r<<8&65280|n>>>8&255]^t[i>>>8&65280|o>>>24&255]}function applySbox(e,t,r,n,i){return e[255&t|65280&r]|e[n>>>16&255|i>>>16&65280]<<16}function encrypt$1(e,t,r,n,i){const{sbox2:o,T01:s,T23:a}=tableEncoding;let l=0;t^=e[l++],r^=e[l++],n^=e[l++],i^=e[l++];const c=e.length/4-2;for(let u=0;u16)throw new Error(`aes/pcks5: wrong padding byte: ${n}`);const i=e.subarray(0,-n);for(let o=0;o{const o=expandKeyLE(e),{b:s,o:a,out:l}=validateBlockEncrypt(r,n,i),c=u32(t);let u=c[0],h=c[1],d=c[2],p=c[3],f=0;for(;f+4<=s.length;)u^=s[f+0],h^=s[f+1],d^=s[f+2],p^=s[f+3],({s0:u,s1:h,s2:d,s3:p}=encrypt$1(o,u,h,d,p)),a[f++]=u,a[f++]=h,a[f++]=d,a[f++]=p;if(n){const e=padPCKS(r.subarray(4*f));u^=e[0],h^=e[1],d^=e[2],p^=e[3],({s0:u,s1:h,s2:d,s3:p}=encrypt$1(o,u,h,d,p)),a[f++]=u,a[f++]=h,a[f++]=d,a[f++]=p}return o.fill(0),l},decrypt:(r,i)=>{validateBlockDecrypt(r);const o=expandKeyDecLE(e),s=u32(t),a=getDst(r.length,i),l=u32(r),c=u32(a);let u=s[0],h=s[1],d=s[2],p=s[3];for(let e=0;e+4<=l.length;){const t=u,r=h,n=d,i=p;u=l[e+0],h=l[e+1],d=l[e+2],p=l[e+3];const{s0:s,s1:a,s2:f,s3:g}=decrypt$1(o,u,h,d,p);c[e++]=s^t,c[e++]=a^r,c[e++]=f^n,c[e++]=g^i}return o.fill(0),validatePCKS(a,n)}}}),_utf8ToBytes=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),sigma16=_utf8ToBytes("expand 16-byte k"),sigma32=_utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32);function rotl(e,t){return e<>>32-t}function isAligned32(e){return e.byteOffset%4==0}sigma32_32.slice();const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(e,t,r,n,i,o,s,a){const l=i.length,c=new Uint8Array(BLOCK_LEN),u=u32(c),h=isAligned32(i)&&isAligned32(o),d=h?u32(i):U32_EMPTY,p=h?u32(o):U32_EMPTY;for(let f=0;f=MAX_COUNTER)throw new Error("arx: counter overflow");const g=Math.min(BLOCK_LEN,l-f);if(h&&g===BLOCK_LEN){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,r=0;r{bytes(t),bytes(a),bytes(l);const h=l.length;if(c||(c=new Uint8Array(h)),bytes(c),number(u),u<0||u>=MAX_COUNTER)throw new Error("arx: counter overflow");if(c.length0;)d.pop().fill(0);return c}}function chachaCore(e,t,r,n,i,o=20){let s=e[0],a=e[1],l=e[2],c=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=i,v=r[0],_=r[1],E=r[2],w=s,C=a,S=l,T=c,x=u,R=h,A=d,I=p,P=f,k=g,O=m,L=y,M=b,D=v,N=_,F=E;for(let B=0;Bn?e.create().update(r).digest():r);for(let o=0;onew HMAC(e,t).update(r).digest();function extract(e,t,r){return assert$2.hash(e),hmac(e,toBytes(r),toBytes(t))}hmac.create=(e,t)=>new HMAC(e,t);const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(e,t,r,n=32){if(assert$2.hash(e),assert$2.number(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/e.outputLen);void 0===r&&(r=EMPTY_BUFFER);const o=new Uint8Array(i*e.outputLen),s=hmac.create(e,t),a=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let c=0;c{for(var r in t)__defProp(e,r,{get:t[r],enumerable:!0})},verifiedSymbol$1=Symbol("verified"),isRecord$1=e=>e instanceof Object;function validateEvent$2(e){if(!isRecord$1(e))return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!e.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;tQueue,QueueNode:()=>QueueNode,binarySearch:()=>binarySearch$3,bytesToHex:()=>bytesToHex$2,hexToBytes:()=>hexToBytes$2,insertEventIntoAscendingList:()=>insertEventIntoAscendingList,insertEventIntoDescendingList:()=>insertEventIntoDescendingList$1,normalizeURL:()=>normalizeURL$1,utf8Decoder:()=>utf8Decoder$2,utf8Encoder:()=>utf8Encoder$2});var utf8Decoder$2=new TextDecoder("utf-8"),utf8Encoder$2=new TextEncoder;function normalizeURL$1(e){try{-1===e.indexOf("://")&&(e="wss://"+e);let t=new URL(e);return"http:"===t.protocol?t.protocol="ws:":"https:"===t.protocol&&(t.protocol="wss:"),t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),("80"===t.port&&"ws:"===t.protocol||"443"===t.port&&"wss:"===t.protocol)&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch(t){throw new Error(`Invalid URL: ${e}`)}}function insertEventIntoDescendingList$1(e,t){const[r,n]=binarySearch$3(e,e=>t.id===e.id?0:t.created_at===e.created_at?-1:e.created_at-t.created_at);return n||e.splice(r,0,t),e}function insertEventIntoAscendingList(e,t){const[r,n]=binarySearch$3(e,e=>t.id===e.id?0:t.created_at===e.created_at?-1:t.created_at-e.created_at);return n||e.splice(r,0,t),e}function binarySearch$3(e,t){let r=0,n=e.length-1;for(;r<=n;){const i=Math.floor((r+n)/2),o=t(e[i]);if(0===o)return[i,!0];o<0?n=i-1:r=i+1}return[r,!1]}var QueueNode=class{value;next=null;prev=null;constructor(e){this.value=e}},Queue=class{first;last;constructor(){this.first=null,this.last=null}enqueue(e){const t=new QueueNode(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const e=this.first;return this.first=null,this.last=null,e.value}const e=this.first;return this.first=e.next,this.first&&(this.first.prev=null),e.value}},JS$1=class{generateSecretKey(){return schnorr.utils.randomPrivateKey()}getPublicKey(e){return bytesToHex$2(schnorr.getPublicKey(e))}finalizeEvent(e,t){const r=e;return r.pubkey=bytesToHex$2(schnorr.getPublicKey(t)),r.id=getEventHash$1(r),r.sig=bytesToHex$2(schnorr.sign(getEventHash$1(r),t)),r[verifiedSymbol$1]=!0,r}verifyEvent(e){if("boolean"==typeof e[verifiedSymbol$1])return e[verifiedSymbol$1];const t=getEventHash$1(e);if(t!==e.id)return e[verifiedSymbol$1]=!1,!1;try{const r=schnorr.verify(e.sig,t,e.pubkey);return e[verifiedSymbol$1]=r,r}catch(r){return e[verifiedSymbol$1]=!1,!1}}};function serializeEvent$1(e){if(!validateEvent$2(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function getEventHash$1(e){return bytesToHex$2(sha256$1(utf8Encoder$2.encode(serializeEvent$1(e))))}var i$1=new JS$1,generateSecretKey$1=i$1.generateSecretKey,getPublicKey$1=i$1.getPublicKey,finalizeEvent$1=i$1.finalizeEvent,verifyEvent$1=i$1.verifyEvent,kinds_exports={};function isRegularKind$1(e){return e<1e4&&0!==e&&3!==e}function isReplaceableKind$2(e){return 0===e||3===e||1e4<=e&&e<2e4}function isEphemeralKind$1(e){return 2e4<=e&&e<3e4}function isAddressableKind$2(e){return 3e4<=e&&e<4e4}function classifyKind(e){return isRegularKind$1(e)?"regular":isReplaceableKind$2(e)?"replaceable":isEphemeralKind$1(e)?"ephemeral":isAddressableKind$2(e)?"parameterized":"unknown"}function isKind(e,t){const r=t instanceof Array?t:[t];return validateEvent$2(e)&&r.includes(e.kind)||!1}__export(kinds_exports,{Application:()=>Application,BadgeAward:()=>BadgeAward,BadgeDefinition:()=>BadgeDefinition,BlockedRelaysList:()=>BlockedRelaysList,BlossomServerList:()=>BlossomServerList,BookmarkList:()=>BookmarkList,Bookmarksets:()=>Bookmarksets,Calendar:()=>Calendar,CalendarEventRSVP:()=>CalendarEventRSVP,ChannelCreation:()=>ChannelCreation,ChannelHideMessage:()=>ChannelHideMessage,ChannelMessage:()=>ChannelMessage,ChannelMetadata:()=>ChannelMetadata,ChannelMuteUser:()=>ChannelMuteUser,ChatMessage:()=>ChatMessage,ClassifiedListing:()=>ClassifiedListing,ClientAuth:()=>ClientAuth$1,Comment:()=>Comment,CommunitiesList:()=>CommunitiesList,CommunityDefinition:()=>CommunityDefinition,CommunityPostApproval:()=>CommunityPostApproval,Contacts:()=>Contacts,CreateOrUpdateProduct:()=>CreateOrUpdateProduct,CreateOrUpdateStall:()=>CreateOrUpdateStall,Curationsets:()=>Curationsets,Date:()=>Date2,DirectMessageRelaysList:()=>DirectMessageRelaysList,DraftClassifiedListing:()=>DraftClassifiedListing,DraftLong:()=>DraftLong,Emojisets:()=>Emojisets,EncryptedDirectMessage:()=>EncryptedDirectMessage,EventDeletion:()=>EventDeletion,FavoriteRelays:()=>FavoriteRelays,FileMessage:()=>FileMessage,FileMetadata:()=>FileMetadata,FileServerPreference:()=>FileServerPreference,Followsets:()=>Followsets,ForumThread:()=>ForumThread,GenericRepost:()=>GenericRepost,Genericlists:()=>Genericlists,GiftWrap:()=>GiftWrap,GroupMetadata:()=>GroupMetadata,HTTPAuth:()=>HTTPAuth,Handlerinformation:()=>Handlerinformation,Handlerrecommendation:()=>Handlerrecommendation,Highlights:()=>Highlights,InterestsList:()=>InterestsList,Interestsets:()=>Interestsets,JobFeedback:()=>JobFeedback,JobRequest:()=>JobRequest,JobResult:()=>JobResult,Label:()=>Label,LightningPubRPC:()=>LightningPubRPC,LiveChatMessage:()=>LiveChatMessage,LiveEvent:()=>LiveEvent,LongFormArticle:()=>LongFormArticle,Metadata:()=>Metadata,Mutelist:()=>Mutelist,NWCWalletInfo:()=>NWCWalletInfo,NWCWalletRequest:()=>NWCWalletRequest,NWCWalletResponse:()=>NWCWalletResponse,NormalVideo:()=>NormalVideo,NostrConnect:()=>NostrConnect,OpenTimestamps:()=>OpenTimestamps,Photo:()=>Photo,Pinlist:()=>Pinlist,Poll:()=>Poll,PollResponse:()=>PollResponse,PrivateDirectMessage:()=>PrivateDirectMessage,ProblemTracker:()=>ProblemTracker,ProfileBadges:()=>ProfileBadges,PublicChatsList:()=>PublicChatsList,Reaction:()=>Reaction,RecommendRelay:()=>RecommendRelay,RelayList:()=>RelayList,RelayReview:()=>RelayReview,Relaysets:()=>Relaysets,Report:()=>Report,Reporting:()=>Reporting,Repost:()=>Repost,Seal:()=>Seal,SearchRelaysList:()=>SearchRelaysList,ShortTextNote:()=>ShortTextNote,ShortVideo:()=>ShortVideo,Time:()=>Time,UserEmojiList:()=>UserEmojiList,UserStatuses:()=>UserStatuses,Voice:()=>Voice,VoiceComment:()=>VoiceComment,Zap:()=>Zap,ZapGoal:()=>ZapGoal,ZapRequest:()=>ZapRequest,classifyKind:()=>classifyKind,isAddressableKind:()=>isAddressableKind$2,isEphemeralKind:()=>isEphemeralKind$1,isKind:()=>isKind,isRegularKind:()=>isRegularKind$1,isReplaceableKind:()=>isReplaceableKind$2});var Metadata=0,ShortTextNote=1,RecommendRelay=2,Contacts=3,EncryptedDirectMessage=4,EventDeletion=5,Repost=6,Reaction=7,BadgeAward=8,ChatMessage=9,ForumThread=11,Seal=13,PrivateDirectMessage=14,FileMessage=15,GenericRepost=16,Photo=20,NormalVideo=21,ShortVideo=22,ChannelCreation=40,ChannelMetadata=41,ChannelMessage=42,ChannelHideMessage=43,ChannelMuteUser=44,OpenTimestamps=1040,GiftWrap=1059,Poll=1068,FileMetadata=1063,Comment=1111,LiveChatMessage=1311,Voice=1222,VoiceComment=1244,ProblemTracker=1971,Report=1984,Reporting=1984,Label=1985,CommunityPostApproval=4550,JobRequest=5999,JobResult=6999,JobFeedback=7e3,ZapGoal=9041,ZapRequest=9734,Zap=9735,Highlights=9802,PollResponse=1018,Mutelist=1e4,Pinlist=10001,RelayList=10002,BookmarkList=10003,CommunitiesList=10004,PublicChatsList=10005,BlockedRelaysList=10006,SearchRelaysList=10007,FavoriteRelays=10012,InterestsList=10015,UserEmojiList=10030,DirectMessageRelaysList=10050,FileServerPreference=10096,BlossomServerList=10063,NWCWalletInfo=13194,LightningPubRPC=21e3,ClientAuth$1=22242,NWCWalletRequest=23194,NWCWalletResponse=23195,NostrConnect=24133,HTTPAuth=27235,Followsets=3e4,Genericlists=30001,Relaysets=30002,Bookmarksets=30003,Curationsets=30004,ProfileBadges=30008,BadgeDefinition=30009,Interestsets=30015,CreateOrUpdateStall=30017,CreateOrUpdateProduct=30018,LongFormArticle=30023,DraftLong=30024,Emojisets=30030,Application=30078,LiveEvent=30311,UserStatuses=30315,ClassifiedListing=30402,DraftClassifiedListing=30403,Date2=31922,Time=31923,Calendar=31924,CalendarEventRSVP=31925,RelayReview=31987,Handlerrecommendation=31989,Handlerinformation=31990,CommunityDefinition=34550,GroupMetadata=39e3,fakejson_exports={};function getHex64(e,t){let r=t.length+3,n=e.indexOf(`"${t}":`)+r,i=e.slice(n).indexOf('"')+n+1;return e.slice(i,i+64)}function getInt(e,t){let r=t.length,n=e.indexOf(`"${t}":`)+r+3,i=e.slice(n),o=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,o),10)}function getSubscriptionId(e){let t=e.slice(0,22).indexOf('"EVENT"');if(-1===t)return null;let r=e.slice(t+7+1).indexOf('"');if(-1===r)return null;let n=t+7+1+r,i=e.slice(n+1,80).indexOf('"');if(-1===i)return null;let o=n+1+i;return e.slice(n+1,o)}function matchEventId(e,t){return t===getHex64(e,"id")}function matchEventPubkey(e,t){return t===getHex64(e,"pubkey")}function matchEventKind(e,t){return t===getInt(e,"kind")}__export(fakejson_exports,{getHex64:()=>getHex64,getInt:()=>getInt,getSubscriptionId:()=>getSubscriptionId,matchEventId:()=>matchEventId,matchEventKind:()=>matchEventKind,matchEventPubkey:()=>matchEventPubkey});var nip42_exports={},_WebSocket,_WebSocket2;function makeAuthEvent$1(e,t){return{kind:ClientAuth$1,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}__export(nip42_exports,{makeAuthEvent:()=>makeAuthEvent$1});try{_WebSocket=WebSocket}catch{}try{_WebSocket2=WebSocket}catch{}var nip19_exports={};__export(nip19_exports,{BECH32_REGEX:()=>BECH32_REGEX,Bech32MaxSize:()=>Bech32MaxSize$1,NostrTypeGuard:()=>NostrTypeGuard,decode:()=>decode$1,decodeNostrURI:()=>decodeNostrURI,encodeBytes:()=>encodeBytes$1,naddrEncode:()=>naddrEncode,neventEncode:()=>neventEncode,noteEncode:()=>noteEncode,nprofileEncode:()=>nprofileEncode,npubEncode:()=>npubEncode$1,nsecEncode:()=>nsecEncode});var NostrTypeGuard={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},Bech32MaxSize$1=5e3,BECH32_REGEX=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}function decodeNostrURI(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),decode$1(e)}catch(t){return{type:"invalid",data:null}}}function decode$1(e){let{prefix:t,words:r}=bech32.decode(e,Bech32MaxSize$1),n=new Uint8Array(bech32.fromWords(r));switch(t){case"nprofile":{let e=parseTLV$1(n);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$2(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder$2.decode(e)):[]}}}case"nevent":{let e=parseTLV$1(n);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$2(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder$2.decode(e)):[],author:e[2]?.[0]?bytesToHex$2(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(bytesToHex$2(e[3][0]),16):void 0}}}case"naddr":{let e=parseTLV$1(n);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder$2.decode(e[0][0]),pubkey:bytesToHex$2(e[2][0]),kind:parseInt(bytesToHex$2(e[3][0]),16),relays:e[1]?e[1].map(e=>utf8Decoder$2.decode(e)):[]}}}case"nsec":return{type:t,data:n};case"npub":case"note":return{type:t,data:bytesToHex$2(n)};default:throw new Error(`unknown prefix ${t}`)}}function parseTLV$1(e){let t={},r=e;for(;r.length>0;){let e=r[0],n=r[1],i=r.slice(2,2+n);if(r=r.slice(2+n),i.lengthutf8Encoder$2.encode(e))}))}function neventEncode(e){let t;return void 0!==e.kind&&(t=integerToUint8Array(e.kind)),encodeBech32$1("nevent",encodeTLV({0:[hexToBytes$2(e.id)],1:(e.relays||[]).map(e=>utf8Encoder$2.encode(e)),2:e.author?[hexToBytes$2(e.author)]:[],3:t?[new Uint8Array(t)]:[]}))}function naddrEncode(e){let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e.kind,!1),encodeBech32$1("naddr",encodeTLV({0:[utf8Encoder$2.encode(e.identifier)],1:(e.relays||[]).map(e=>utf8Encoder$2.encode(e)),2:[hexToBytes$2(e.pubkey)],3:[new Uint8Array(t)]}))}function encodeTLV(e){let t=[];return Object.entries(e).reverse().forEach(([e,r])=>{r.forEach(r=>{let n=new Uint8Array(r.length+2);n.set([parseInt(e)],0),n.set([r.length],1),n.set(r,2),t.push(n)})}),concatBytes(...t)}var nip04_exports={};function encrypt(e,t,r){const n=e instanceof Uint8Array?bytesToHex$2(e):e,i=getNormalizedX(secp256k1.getSharedSecret(n,"02"+t));let o=Uint8Array.from(randomBytes(16)),s=utf8Encoder$2.encode(r),a=cbc(i,o).encrypt(s);return`${base64.encode(new Uint8Array(a))}?iv=${base64.encode(new Uint8Array(o.buffer))}`}function decrypt(e,t,r){const n=e instanceof Uint8Array?bytesToHex$2(e):e;let[i,o]=r.split("?iv="),s=getNormalizedX(secp256k1.getSharedSecret(n,"02"+t)),a=base64.decode(o),l=base64.decode(i),c=cbc(s,a).decrypt(l);return utf8Decoder$2.decode(c)}function getNormalizedX(e){return e.slice(1,33)}__export(nip04_exports,{decrypt:()=>decrypt,encrypt:()=>encrypt});var nip05_exports={};__export(nip05_exports,{NIP05_REGEX:()=>NIP05_REGEX,isNip05:()=>isNip05,isValid:()=>isValid,queryProfile:()=>queryProfile,searchDomain:()=>searchDomain,useFetchImplementation:()=>useFetchImplementation});var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,isNip05=e=>NIP05_REGEX.test(e||""),_fetch;try{_fetch=fetch}catch(_){}function useFetchImplementation(e){_fetch=e}async function searchDomain(e,t=""){try{const r=`https://${e}/.well-known/nostr.json?name=${t}`,n=await _fetch(r,{redirect:"manual"});if(200!==n.status)throw Error("Wrong response code");return(await n.json()).names}catch(_){return{}}}async function queryProfile(e){const t=e.match(NIP05_REGEX);if(!t)return null;const[,r="_",n]=t;try{const e=`https://${n}/.well-known/nostr.json?name=${r}`,t=await _fetch(e,{redirect:"manual"});if(200!==t.status)throw Error("Wrong response code");const i=await t.json(),o=i.names[r];return o?{pubkey:o,relays:i.relays?.[o]}:null}catch(i){return null}}async function isValid(e,t){const r=await queryProfile(t);return!!r&&r.pubkey===e}var nip10_exports={};function parse$1(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let r,n;for(let i=e.tags.length-1;i>=0;i--){const o=e.tags[i];if("e"===o[0]&&o[1]){const[e,i,s,a,l]=o,c={id:i,relays:s?[s]:[],author:l};if("root"===a){t.root=c;continue}if("reply"===a){t.reply=c;continue}if("mention"===a){t.mentions.push(c);continue}r?n=c:r=c,t.mentions.push(c);continue}if("q"===o[0]&&o[1]){const[e,r,n]=o;t.quotes.push({id:r,relays:n?[n]:[]})}"p"===o[0]&&o[1]&&t.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]})}return t.root||(t.root=n||r||t.reply),t.reply||(t.reply=r||t.root),[t.reply,t.root].forEach(e=>{if(!e)return;let r=t.mentions.indexOf(e);if(-1!==r&&t.mentions.splice(r,1),e.author){let r=t.profiles.find(t=>t.pubkey===e.author);r&&r.relays&&(e.relays||(e.relays=[]),r.relays.forEach(t=>{-1===e.relays?.indexOf(t)&&e.relays.push(t)}),r.relays=e.relays)}}),t.mentions.forEach(e=>{if(e.author){let r=t.profiles.find(t=>t.pubkey===e.author);r&&r.relays&&(e.relays||(e.relays=[]),r.relays.forEach(t=>{-1===e.relays.indexOf(t)&&e.relays.push(t)}),r.relays=e.relays)}}),t}__export(nip10_exports,{parse:()=>parse$1});var nip11_exports={},_fetch2;__export(nip11_exports,{fetchRelayInformation:()=>fetchRelayInformation,useFetchImplementation:()=>useFetchImplementation2});try{_fetch2=fetch}catch{}function useFetchImplementation2(e){_fetch2=e}async function fetchRelayInformation(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var nip13_exports={};function getPow(e){let t=0;for(let r=0;r<64;r+=8){const n=parseInt(e.substring(r,r+8),16);if(0!==n){t+=Math.clz32(n);break}t+=32}return t}function minePow(e,t){let r=0;const n=e,i=["nonce",r.toString(),t.toString()];for(n.tags.push(i);;){const e=Math.floor((new Date).getTime()/1e3);if(e!==n.created_at&&(r=0,n.created_at=e),i[1]=(++r).toString(),n.id=fastEventHash(n),getPow(n.id)>=t)break}return n}function fastEventHash(e){return bytesToHex$2(sha256$1(utf8Encoder$2.encode(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))))}__export(nip13_exports,{fastEventHash:()=>fastEventHash,getPow:()=>getPow,minePow:()=>minePow});var nip17_exports={};__export(nip17_exports,{unwrapEvent:()=>unwrapEvent2,unwrapManyEvents:()=>unwrapManyEvents2,wrapEvent:()=>wrapEvent2,wrapManyEvents:()=>wrapManyEvents2});var nip59_exports={};__export(nip59_exports,{createRumor:()=>createRumor,createSeal:()=>createSeal,createWrap:()=>createWrap,unwrapEvent:()=>unwrapEvent,unwrapManyEvents:()=>unwrapManyEvents,wrapEvent:()=>wrapEvent,wrapManyEvents:()=>wrapManyEvents});var nip44_exports={};__export(nip44_exports,{decrypt:()=>decrypt2,encrypt:()=>encrypt2,getConversationKey:()=>getConversationKey,v2:()=>v2});var minPlaintextSize=1,maxPlaintextSize=65535;function getConversationKey(e,t){const r=secp256k1.getSharedSecret(e,"02"+t).subarray(1,33);return extract(sha256$1,r,"nip44-v2")}function getMessageKeys(e,t){const r=expand(sha256$1,e,t,76);return{chacha_key:r.subarray(0,32),chacha_nonce:r.subarray(32,44),hmac_key:r.subarray(44,76)}}function calcPaddedLen(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function pad(e){const t=utf8Encoder$2.encode(e),r=t.length;return concatBytes(writeU16BE(r),t,new Uint8Array(calcPaddedLen(r)-r))}function unpad(e){const t=new DataView(e.buffer).getUint16(0),r=e.subarray(2,2+t);if(tmaxPlaintextSize||r.length!==t||e.length!==2+calcPaddedLen(t))throw new Error("invalid padding");return utf8Decoder$2.decode(r)}function hmacAad(e,t,r){if(32!==r.length)throw new Error("AAD associated data must be 32 bytes");const n=concatBytes(r,t);return hmac(sha256$1,e,n)}function decodePayload(e){if("string"!=typeof e)throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if("#"===e[0])throw new Error("unknown encryption version");let r;try{r=base64.decode(e)}catch(error){throw new Error("invalid base64: "+error.message)}const n=r.length;if(n<99||n>65603)throw new Error("invalid data length: "+n);const i=r[0];if(2!==i)throw new Error("unknown encryption version "+i);return{nonce:r.subarray(1,33),ciphertext:r.subarray(33,-32),mac:r.subarray(-32)}}function encrypt2(e,t,r=randomBytes(32)){const{chacha_key:n,chacha_nonce:i,hmac_key:o}=getMessageKeys(t,r),s=pad(e),a=chacha20(n,i,s),l=hmacAad(o,a,r);return base64.encode(concatBytes(new Uint8Array([2]),r,a,l))}function decrypt2(e,t){const{nonce:r,ciphertext:n,mac:i}=decodePayload(e),{chacha_key:o,chacha_nonce:s,hmac_key:a}=getMessageKeys(t,r);if(!equalBytes(hmacAad(a,n,r),i))throw new Error("invalid MAC");return unpad(chacha20(o,s,n))}var v2={utils:{getConversationKey:getConversationKey,calcPaddedLen:calcPaddedLen},encrypt:encrypt2,decrypt:decrypt2},TWO_DAYS=172800,now=()=>Math.round(Date.now()/1e3),randomNow=()=>Math.round(now()-Math.random()*TWO_DAYS),nip44ConversationKey=(e,t)=>getConversationKey(e,t),nip44Encrypt=(e,t,r)=>encrypt2(JSON.stringify(e),nip44ConversationKey(t,r)),nip44Decrypt=(e,t)=>JSON.parse(decrypt2(e.content,nip44ConversationKey(t,e.pubkey)));function createRumor(e,t){const r={created_at:now(),content:"",tags:[],...e,pubkey:getPublicKey$1(t)};return r.id=getEventHash$1(r),r}function createSeal(e,t,r){return finalizeEvent$1({kind:Seal,content:nip44Encrypt(e,t,r),created_at:randomNow(),tags:[]},t)}function createWrap(e,t){const r=generateSecretKey$1();return finalizeEvent$1({kind:GiftWrap,content:nip44Encrypt(e,r,t),created_at:randomNow(),tags:[["p",t]]},r)}function wrapEvent(e,t,r){return createWrap(createSeal(createRumor(e,t),t,r),r)}function wrapManyEvents(e,t,r){if(!r||0===r.length)throw new Error("At least one recipient is required.");const n=getPublicKey$1(t),i=[wrapEvent(e,t,n)];return r.forEach(r=>{i.push(wrapEvent(e,t,r))}),i}function unwrapEvent(e,t){const r=nip44Decrypt(e,t);return nip44Decrypt(r,t)}function unwrapManyEvents(e,t){let r=[];return e.forEach(e=>{r.push(unwrapEvent(e,t))}),r.sort((e,t)=>e.created_at-t.created_at),r}function createEvent(e,t,r,n){const i={created_at:Math.ceil(Date.now()/1e3),kind:PrivateDirectMessage,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach(({publicKey:e,relayUrl:t})=>{i.tags.push(t?["p",e,t]:["p",e])}),n&&i.tags.push(["e",n.eventId,n.relayUrl||"","reply"]),r&&i.tags.push(["subject",r]),i}function wrapEvent2(e,t,r,n,i){return wrapEvent(createEvent(t,r,n,i),e,t.publicKey)}function wrapManyEvents2(e,t,r,n,i){if(!t||0===t.length)throw new Error("At least one recipient is required.");return[{publicKey:getPublicKey$1(e)},...t].map(t=>wrapEvent2(e,t,r,n,i))}var unwrapEvent2=unwrapEvent,unwrapManyEvents2=unwrapManyEvents,nip18_exports={};function finishRepostEvent(e,t,r,n){let i;const o=[...e.tags??[],["e",t.id,r],["p",t.pubkey]];return t.kind===ShortTextNote?i=Repost:(i=GenericRepost,o.push(["k",String(t.kind)])),finalizeEvent$1({kind:i,tags:o,content:""===e.content||t.tags?.find(e=>"-"===e[0])?"":JSON.stringify(t),created_at:e.created_at},n)}function getRepostedEventPointer(e){if(![Repost,GenericRepost].includes(e.kind))return;let t,r;for(let n=e.tags.length-1;n>=0&&(void 0===t||void 0===r);n--){const i=e.tags[n];i.length>=2&&("e"===i[0]&&void 0===t?t=i:"p"===i[0]&&void 0===r&&(r=i))}return void 0!==t?{id:t[1],relays:[t[2],r?.[2]].filter(e=>"string"==typeof e),author:r?.[1]}:void 0}function getRepostedEvent(e,{skipVerification:t}={}){const r=getRepostedEventPointer(e);if(void 0===r||""===e.content)return;let n;try{n=JSON.parse(e.content)}catch(error){return}return n.id===r.id&&(t||verifyEvent$1(n))?n:void 0}__export(nip18_exports,{finishRepostEvent:()=>finishRepostEvent,getRepostedEvent:()=>getRepostedEvent,getRepostedEventPointer:()=>getRepostedEventPointer});var nip21_exports={};__export(nip21_exports,{NOSTR_URI_REGEX:()=>NOSTR_URI_REGEX,parse:()=>parse2,test:()=>test});var NOSTR_URI_REGEX=new RegExp(`nostr:(${BECH32_REGEX.source})`);function test(e){return"string"==typeof e&&new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(e)}function parse2(e){const t=e.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:decode$1(t[1])}}var nip25_exports={};function finishReactionEvent(e,t,r){const n=t.tags.filter(e=>e.length>=2&&("e"===e[0]||"p"===e[0]));return finalizeEvent$1({...e,kind:Reaction,tags:[...e.tags??[],...n,["e",t.id],["p",t.pubkey]],content:e.content??"+"},r)}function getReactedEventPointer(e){if(e.kind!==Reaction)return;let t,r;for(let n=e.tags.length-1;n>=0&&(void 0===t||void 0===r);n--){const i=e.tags[n];i.length>=2&&("e"===i[0]&&void 0===t?t=i:"p"===i[0]&&void 0===r&&(r=i))}return void 0!==t&&void 0!==r?{id:t[1],relays:[t[2],r[2]].filter(e=>void 0!==e),author:r[1]}:void 0}__export(nip25_exports,{finishReactionEvent:()=>finishReactionEvent,getReactedEventPointer:()=>getReactedEventPointer});var nip27_exports={};__export(nip27_exports,{parse:()=>parse3});var noCharacter=/\W/m,noURLCharacter=/[^\w\/] |[^\w\/]$|$|,| /m,MAX_HASHTAG_LENGTH=42;function*parse3(e){let t=[];if("string"!=typeof e){for(let r=0;r=3&&t.push({type:"emoji",shortcode:n[1],url:n[2]})}e=e.content}const r=e.length;let n=0,i=0;e:for(;i=0&&achannelCreateEvent,channelHideMessageEvent:()=>channelHideMessageEvent,channelMessageEvent:()=>channelMessageEvent,channelMetadataEvent:()=>channelMetadataEvent,channelMuteUserEvent:()=>channelMuteUserEvent});var channelCreateEvent=(e,t)=>{let r;if("object"==typeof e.content)r=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;r=e.content}return finalizeEvent$1({kind:ChannelCreation,tags:[...e.tags??[]],content:r,created_at:e.created_at},t)},channelMetadataEvent=(e,t)=>{let r;if("object"==typeof e.content)r=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;r=e.content}return finalizeEvent$1({kind:ChannelMetadata,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:r,created_at:e.created_at},t)},channelMessageEvent=(e,t)=>{const r=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&r.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),finalizeEvent$1({kind:ChannelMessage,tags:[...r,...e.tags??[]],content:e.content,created_at:e.created_at},t)},channelHideMessageEvent=(e,t)=>{let r;if("object"==typeof e.content)r=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;r=e.content}return finalizeEvent$1({kind:ChannelHideMessage,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:r,created_at:e.created_at},t)},channelMuteUserEvent=(e,t)=>{let r;if("object"==typeof e.content)r=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;r=e.content}return finalizeEvent$1({kind:ChannelMuteUser,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:r,created_at:e.created_at},t)},nip30_exports={};__export(nip30_exports,{EMOJI_SHORTCODE_REGEX:()=>EMOJI_SHORTCODE_REGEX,matchAll:()=>matchAll,regex:()=>regex$1,replaceAll:()=>replaceAll});var EMOJI_SHORTCODE_REGEX=/:(\w+):/,regex$1=()=>new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`,"g");function*matchAll(e){const t=e.matchAll(regex$1());for(const n of t)try{const[e,t]=n;yield{shortcode:e,name:t,start:n.index,end:n.index+e.length}}catch(r){}}function replaceAll(e,t){return e.replaceAll(regex$1(),(e,r)=>t({shortcode:e,name:r}))}var nip39_exports={},_fetch3;__export(nip39_exports,{useFetchImplementation:()=>useFetchImplementation3,validateGithub:()=>validateGithub});try{_fetch3=fetch}catch{}function useFetchImplementation3(e){_fetch3=e}async function validateGithub(e,t,r){try{return await(await _fetch3(`https://gist.github.com/${t}/${r}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch(_){return!1}}var nip47_exports={};function parseConnectionString(e){const{host:t,pathname:r,searchParams:n}=new URL(e),i=r||t,o=n.get("relay"),s=n.get("secret");if(!i||!o||!s)throw new Error("invalid connection string");return{pubkey:i,relay:o,secret:s}}async function makeNwcRequestEvent(e,t,r){const n={method:"pay_invoice",params:{invoice:r}},i=encrypt(t,e,JSON.stringify(n)),o={kind:NWCWalletRequest,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e]]};return finalizeEvent$1(o,t)}__export(nip47_exports,{makeNwcRequestEvent:()=>makeNwcRequestEvent,parseConnectionString:()=>parseConnectionString});var nip54_exports={};function normalizeIdentifier(e){return e=(e=e.trim().toLowerCase()).normalize("NFKC"),Array.from(e).map(e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-").join("")}__export(nip54_exports,{normalizeIdentifier:()=>normalizeIdentifier});var nip57_exports={},_fetch4;__export(nip57_exports,{getSatoshisAmountFromBolt11:()=>getSatoshisAmountFromBolt11,getZapEndpoint:()=>getZapEndpoint,makeZapReceipt:()=>makeZapReceipt,makeZapRequest:()=>makeZapRequest,useFetchImplementation:()=>useFetchImplementation4,validateZapRequest:()=>validateZapRequest});try{_fetch4=fetch}catch{}function useFetchImplementation4(e){_fetch4=e}async function getZapEndpoint(e){try{let t="",{lud06:r,lud16:n}=JSON.parse(e.content);if(n){let[e,r]=n.split("@");t=new URL(`/.well-known/lnurlp/${e}`,`https://${r}`).toString()}else{if(!r)return null;{let{words:e}=bech32.decode(r,1e3),n=bech32.fromWords(e);t=utf8Decoder$2.decode(n)}}let i=await _fetch4(t),o=await i.json();if(o.allowsNostr&&o.nostrPubkey)return o.callback}catch(t){}return null}function makeZapRequest(e){let t={kind:9734,created_at:Math.round(Date.now()/1e3),content:e.comment||"",tags:[["p","pubkey"in e?e.pubkey:e.event.pubkey],["amount",e.amount.toString()],["relays",...e.relays]]};if("event"in e){if(t.tags.push(["e",e.event.id]),isReplaceableKind$2(e.event.kind)){const r=["a",`${e.event.kind}:${e.event.pubkey}:`];t.tags.push(r)}else if(isAddressableKind$2(e.event.kind)){let r=e.event.tags.find(([e,t])=>"d"===e&&t);if(!r)throw new Error("d tag not found or is empty");const n=["a",`${e.event.kind}:${e.event.pubkey}:${r[1]}`];t.tags.push(n)}t.tags.push(["k",e.event.kind.toString()])}return t}function validateZapRequest(e){let t;try{t=JSON.parse(e)}catch(i){return"Invalid zap request JSON."}if(!validateEvent$2(t))return"Zap request is not a valid Nostr event.";if(!verifyEvent$1(t))return"Invalid signature on zap request.";let r=t.tags.find(([e,t])=>"p"===e&&t);if(!r)return"Zap request doesn't have a 'p' tag.";if(!r[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let n=t.tags.find(([e,t])=>"e"===e&&t);return n&&!n[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([e,t])=>"relays"===e&&t)?null:"Zap request doesn't have a 'relays' tag."}function makeZapReceipt({zapRequest:e,preimage:t,bolt11:r,paidAt:n}){let i=JSON.parse(e),o=i.tags.filter(([e])=>"e"===e||"p"===e||"a"===e),s={kind:9735,created_at:Math.round(n.getTime()/1e3),content:"",tags:[...o,["P",i.pubkey],["bolt11",r],["description",e]]};return t&&s.tags.push(["preimage",t]),s}function getSatoshisAmountFromBolt11(e){if(e.length<50)return 0;const t=(e=e.substring(0,50)).lastIndexOf("1");if(-1===t)return 0;const r=e.substring(0,t);if(!r.startsWith("lnbc"))return 0;const n=r.substring(4);if(n.length<1)return 0;const i=n[n.length-1],o=i.charCodeAt(0)-"0".charCodeAt(0),s=o>=0&&o<=9;let a=n.length-1;if(s&&a++,a<1)return 0;const l=parseInt(n.substring(0,a));switch(i){case"m":return 1e5*l;case"u":return 100*l;case"n":return l/10;case"p":return l/1e4;default:return 1e8*l}}var nip77_exports={};__export(nip77_exports,{Negentropy:()=>Negentropy,NegentropyStorageVector:()=>NegentropyStorageVector,NegentropySync:()=>NegentropySync});var PROTOCOL_VERSION=97,ID_SIZE=32,FINGERPRINT_SIZE=16,Mode={Skip:0,Fingerprint:1,IdList:2},WrappedBuffer=class{_raw;length;constructor(e){"number"==typeof e?(this._raw=new Uint8Array(e),this.length=0):e instanceof Uint8Array?(this._raw=new Uint8Array(e),this.length=e.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(e){if(e instanceof WrappedBuffer&&(e=e.unwrap()),"number"!=typeof e.length)throw Error("bad length");const t=e.length+this.length;if(this.capacity>>=7;t.reverse();for(let r=0;r4294967295&&(r=1),n.setUint32(e,4294967295&s,!0),t=r,r=0}}negate(){let e=new DataView(this.buf.buffer);for(let r=0;r<8;r++){let t=4*r;e.setUint32(t,~e.getUint32(t,!0))}let t=new Uint8Array(ID_SIZE);t[0]=1,this.add(t)}getFingerprint(e){let t=new WrappedBuffer;return t.extend(this.buf),t.extend(encodeVarInt(e)),sha256$1(t.unwrap()).subarray(0,FINGERPRINT_SIZE)}},NegentropyStorageVector=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(e,t){if(this.sealed)throw Error("already sealed");const r=hexToBytes$1(t);if(r.byteLength!==ID_SIZE)throw Error("bad id size for added item");this.items.push({timestamp:e,id:r})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(itemCompare);for(let e=1;e=this.items.length)throw Error("out of range");return this.items[e]}iterate(e,t,r){this._checkSealed(),this._checkBounds(e,t);for(let n=e;nitemCompare(e,r)<0)}fingerprint(e,t){let r=new Accumulator;return r.setToZero(),this.iterate(e,t,e=>(r.add(e.id),!0)),r.getFingerprint(t-e)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(e,t){if(e>t||t>this.items.length)throw Error("bad range")}_binarySearch(e,t,r,n){let i=r-t;for(;i>0;){let r=t,o=Math.floor(i/2);r+=o,n(e[r])?(t=++r,i-=o+1):i=o}return t}},Negentropy=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(e,t=6e4){if(t<4096)throw Error("frameSizeLimit too small");this.storage=e,this.frameSizeLimit=t,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(e,t){return{timestamp:e,id:t||new Uint8Array(0)}}initiate(){let e=new WrappedBuffer;return e.extend(new Uint8Array([PROTOCOL_VERSION])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),e),bytesToHex$1(e.unwrap())}reconcile(e,t,r){const n=new WrappedBuffer(hexToBytes$1(e));this.lastTimestampIn=this.lastTimestampOut=0;let i=new WrappedBuffer;i.extend(new Uint8Array([PROTOCOL_VERSION]));let o=getByte(n);if(o<96||o>111)throw Error("invalid negentropy protocol version byte");if(o!==PROTOCOL_VERSION)throw Error("unsupported negentropy protocol version requested: "+(o-96));let s=this.storage.size(),a=this._bound(0),l=0,c=!1;for(;0!==n.length;){let e=new WrappedBuffer,o=()=>{c&&(c=!1,e.extend(this.encodeBound(a)),e.extend(encodeVarInt(Mode.Skip)))},u=this.decodeBound(n),h=decodeVarInt(n),d=l,p=this.storage.findLowerBound(l,s,u);if(h===Mode.Skip)c=!0;else if(h===Mode.Fingerprint)0!==compareUint8Array(getBytes(n,FINGERPRINT_SIZE),this.storage.fingerprint(d,p))?(o(),this.splitRange(d,p,u,e)):c=!0;else{if(h!==Mode.IdList)throw Error("unexpected mode");{let e=decodeVarInt(n),i={};for(let t=0;t{let r=e.id;const n=bytesToHex$1(r);return i[n]?delete i[bytesToHex$1(r)]:t?.(n),!0}),r)for(let t of Object.values(i))r(bytesToHex$1(t))}}if(this.exceededFrameSizeLimit(i.length+e.length)){let e=this.storage.fingerprint(p,s);i.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),i.extend(encodeVarInt(Mode.Fingerprint)),i.extend(e);break}i.extend(e),l=p,a=u}return 1===i.length?null:bytesToHex$1(i.unwrap())}splitRange(e,t,r,n){let i=t-e;if(i<32)n.extend(this.encodeBound(r)),n.extend(encodeVarInt(Mode.IdList)),n.extend(encodeVarInt(i)),this.storage.iterate(e,t,e=>(n.extend(e.id),!0));else{let o=Math.floor(i/16),s=i%16,a=e;for(let e=0;e<16;e++){let i,l=o+(e(n===a-1?e=r:t=r,!0)),i=this.getMinimalBound(e,t)}n.extend(this.encodeBound(i)),n.extend(encodeVarInt(Mode.Fingerprint)),n.extend(c)}}}exceededFrameSizeLimit(e){return e>this.frameSizeLimit-200}decodeTimestampIn(e){let t=decodeVarInt(e);return t=0===t?Number.MAX_VALUE:t-1,this.lastTimestampIn===Number.MAX_VALUE||t===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(t+=this.lastTimestampIn,this.lastTimestampIn=t,t)}decodeBound(e){let t=this.decodeTimestampIn(e),r=decodeVarInt(e);if(r>ID_SIZE)throw Error("bound key too long");return{timestamp:t,id:getBytes(e,r)}}encodeTimestampOut(e){if(e===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,encodeVarInt(0);let t=e;return e-=this.lastTimestampOut,this.lastTimestampOut=t,encodeVarInt(e+1)}encodeBound(e){let t=new WrappedBuffer;return t.extend(this.encodeTimestampOut(e.timestamp)),t.extend(encodeVarInt(e.id.length)),t.extend(e.id),t}getMinimalBound(e,t){if(t.timestamp!==e.timestamp)return this._bound(t.timestamp);{let r=0,n=t.id,i=e.id;for(let e=0;et[r])return 1}return e.byteLength>t.byteLength?1:e.byteLength{switch(e[0]){case"NEG-MSG":e.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${e}`);try{const t=this.neg.reconcile(e[2],this.onhave,this.onneed);t?this.relay.send(`["NEG-MSG", "${this.subscription.id}", "${t}"]`):(this.close(),n.onclose?.())}catch(error){console.error("negentropy reconcile error:",error),n?.onclose?.(`reconcile error: ${error}`)}break;case"NEG-CLOSE":{const t=e[2];console.warn("negentropy error:",t),n.onclose?.(t);break}case"NEG-ERR":n.onclose?.()}}}async start(){const e=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${e}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},nip98_exports={};__export(nip98_exports,{getToken:()=>getToken,hashPayload:()=>hashPayload,unpackEventFromToken:()=>unpackEventFromToken,validateEvent:()=>validateEvent2,validateEventKind:()=>validateEventKind,validateEventMethodTag:()=>validateEventMethodTag,validateEventPayloadTag:()=>validateEventPayloadTag,validateEventTimestamp:()=>validateEventTimestamp,validateEventUrlTag:()=>validateEventUrlTag,validateToken:()=>validateToken});var _authorizationScheme="Nostr ";async function getToken(e,t,r,n=!1,i){const o={kind:HTTPAuth,tags:[["u",e],["method",t]],created_at:Math.round((new Date).getTime()/1e3),content:""};i&&o.tags.push(["payload",hashPayload(i)]);const s=await r(o);return(n?_authorizationScheme:"")+base64.encode(utf8Encoder$2.encode(JSON.stringify(s)))}async function validateToken(e,t,r){const n=await unpackEventFromToken(e).catch(e=>{throw e}),i=await validateEvent2(n,t,r).catch(e=>{throw e});return i}async function unpackEventFromToken(e){if(!e)throw new Error("Missing token");e=e.replace(_authorizationScheme,"");const t=utf8Decoder$2.decode(base64.decode(e));if(!t||0===t.length||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function validateEventTimestamp(e){return!!e.created_at&&Math.round((new Date).getTime()/1e3)-e.created_at<60}function validateEventKind(e){return e.kind===HTTPAuth}function validateEventUrlTag(e,t){const r=e.tags.find(e=>"u"===e[0]);return!!r&&r.length>0&&r[1]===t}function validateEventMethodTag(e,t){const r=e.tags.find(e=>"method"===e[0]);return!!r&&r.length>0&&r[1].toLowerCase()===t.toLowerCase()}function hashPayload(e){return bytesToHex$2(sha256$1(utf8Encoder$2.encode(JSON.stringify(e))))}function validateEventPayloadTag(e,t){const r=e.tags.find(e=>"payload"===e[0]);if(!r)return!1;const n=hashPayload(t);return r.length>0&&r[1]===n}async function validateEvent2(e,t,r,n){if(!verifyEvent$1(e))throw new Error("Invalid nostr event, signature invalid");if(!validateEventKind(e))throw new Error("Invalid nostr event, kind invalid");if(!validateEventTimestamp(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!validateEventUrlTag(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!validateEventMethodTag(e,r))throw new Error("Invalid nostr event, method tag invalid");if(Boolean(n)&&"object"==typeof n&&Object.keys(n).length>0&&!validateEventPayloadTag(e,n))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}function isRegularKind(e){return e<1e4&&0!==e&&3!==e}function isReplaceableKind$1(e){return 0===e||3===e||1e4<=e&&e<2e4}function isAddressableKind$1(e){return 3e4<=e&&e<4e4}var verifiedSymbol=Symbol("verified"),isRecord=e=>e instanceof Object;function validateEvent$1(e){if(!isRecord(e))return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!e.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;tt.id===e.id?0:t.created_at===e.created_at?-1:e.created_at-t.created_at);return n||e.splice(r,0,t),e}function binarySearch$2(e,t){let r=0,n=e.length-1;for(;r<=n;){const i=Math.floor((r+n)/2),o=t(e[i]);if(0===o)return[i,!0];o<0?n=i-1:r=i+1}return[r,!1]}new TextDecoder("utf-8"),new TextEncoder;const EventStoreSymbol=Symbol.for("event-store"),EventUIDSymbol$1=Symbol.for("event-uid"),ReplaceableAddressSymbol=Symbol.for("replaceable-address"),FromCacheSymbol=Symbol.for("from-cache"),ReplaceableIdentifierSymbol=Symbol.for("replaceable-identifier");function isEvent(e){return null!=e&&64===e.id?.length&&"string"==typeof e.sig&&"string"==typeof e.pubkey&&64===e.pubkey.length&&"string"==typeof e.content&&Array.isArray(e.tags)&&"number"==typeof e.created_at&&e.created_at>0}function isReplaceable(e){return isReplaceableKind$1(e)||isAddressableKind$1(e)}function getEventUID$1(e){let t=Reflect.get(e,EventUIDSymbol$1);return t||(t=isReplaceable(e.kind)?getReplaceableAddress(e)??e.id:e.id,Reflect.set(e,EventUIDSymbol$1,t)),t}function getReplaceableAddress(e){return isReplaceable(e.kind)?getOrComputeCachedValue(e,ReplaceableAddressSymbol,()=>createReplaceableAddress(e.kind,e.pubkey,getReplaceableIdentifier(e))):null}function createReplaceableAddress(e,t,r){return e+":"+t+":"+(r??"")}function isFromCache(e){return!0===Reflect.get(e,FromCacheSymbol)}function getParentEventStore(e){return Reflect.get(e,EventStoreSymbol)}function notifyEventUpdate(e){if(!isEvent(e))return;const t=getParentEventStore(e);t&&t.update(e)}function getReplaceableIdentifier(e){return getOrComputeCachedValue(e,ReplaceableIdentifierSymbol,()=>e.tags.find(e=>"d"===e[0])?.[1]??"")}function getTagValue(e,t){return e.tags.find(e=>e[0]===t)?.[1]}const EncryptedContentSymbol=Symbol.for("encrypted-content"),EventContentEncryptionMethod={[kinds_exports.EncryptedDirectMessage]:"nip04",[kinds_exports.Seal]:"nip44",[kinds_exports.GiftWrap]:"nip44"};function setEncryptedContentEncryptionMethod(e,t){return EventContentEncryptionMethod[e]=t,e}function getEncryptedContentEncryptionMethods(e,t,r){const n=r??EventContentEncryptionMethod[e];if(!n)throw new Error(`Event kind ${e} does not support encrypted content`);const i=t[n];if(!i)throw new Error(`Signer does not support ${n} encryption`);return i}function canHaveEncryptedContent(e){return void 0!==EventContentEncryptionMethod[e]}function hasEncryptedContent(e){return e.content.length>0}function getEncryptedContent(e){return Reflect.get(e,EncryptedContentSymbol)}function isEncryptedContentUnlocked(e){return!0===Reflect.has(e,EncryptedContentSymbol)}function setEncryptedContentCache(e,t){Reflect.set(e,EncryptedContentSymbol,t),notifyEventUpdate(e)}const PRESERVE_EVENT_SYMBOLS=new Set([EncryptedContentSymbol]);function identity$2(e){return e}function eventPipe(...e){return pipeFromAsyncArray(e.filter(e=>!!e),PRESERVE_EVENT_SYMBOLS)}function tagPipe(...e){return pipeFromAsyncArray(e.filter(e=>!!e))}function skip(){return e=>e}function pipeFromAsyncArray(e,t){return 0===e.length?identity$2:async function(r,n){return e.reduce(async(e,r)=>{const i=await r(await e,n);if(t&&"object"==typeof i&&null!==i&&"object"==typeof e&&null!==e){const e=Reflect.ownKeys(i).filter(e=>"symbol"==typeof e);for(const r of e)t.has(r)||Reflect.deleteProperty(i,r)}return i},r)}}function isNameValueTag(e,t){return void 0!==e[0]&&void 0!==e[1]&&(!t||e[0]===t)}function isETag(e){return isNameValueTag(e,"e")}function isPTag(e){return isNameValueTag(e,"p")}function isRTag(e){return isNameValueTag(e,"r")}function isATag(e){return isNameValueTag(e,"a")}const processTags=(e,...t)=>t.reduce((e,t)=>{const r=[];for(const n of e)try{const e=t(n);if(void 0===e)continue;r.push(e)}catch(error){}return r},e);function fillAndTrimTag(e,t=2){for(let r=(e=e.slice()).length-1;r>=0;r--)void 0!==e[r]&&null!==e[r]&&""!==e[r]||(r+1===e.length&&r>=t?e.pop():e[r]="");return e}function ensureSingletonTag(e,t,r=!0){const n=e.find(e=>e[0]===t[0]);return n?r?e.map(e=>e===n?t:e):e:[...e,t]}function unixNow(){return Math.round(Date.now()/1e3)}var utf8Decoder$1=new TextDecoder("utf-8");new TextEncoder;var Bech32MaxSize=5e3;function decode(e){let{prefix:t,words:r}=bech32.decode(e,Bech32MaxSize),n=new Uint8Array(bech32.fromWords(r));switch(t){case"nprofile":{let e=parseTLV(n);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$2(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder$1.decode(e)):[]}}}case"nevent":{let e=parseTLV(n);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$2(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder$1.decode(e)):[],author:e[2]?.[0]?bytesToHex$2(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(bytesToHex$2(e[3][0]),16):void 0}}}case"naddr":{let e=parseTLV(n);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder$1.decode(e[0][0]),pubkey:bytesToHex$2(e[2][0]),kind:parseInt(bytesToHex$2(e[3][0]),16),relays:e[1]?e[1].map(e=>utf8Decoder$1.decode(e)):[]}}}case"nsec":return{type:t,data:n};case"npub":case"note":return{type:t,data:bytesToHex$2(n)};default:throw new Error(`unknown prefix ${t}`)}}function parseTLV(e){let t={},r=e;for(;r.length>0;){let e=r[0],n=r[1],i=r.slice(2,2+n);if(r=r.slice(2+n),i.length=8&&WEBSOCKET_URL_CHECK.test(e)}function isHex(e){return!!e&&!!e.match(/^[0-9a-f]+$/i)}function isHexKey(e){return!!e&&64===e.length&&!!e.toLowerCase().match(/^[0-9a-f]{64}$/)}function safeDecode(e){try{return decode(e)}catch{return null}}function decodeProfilePointer(e){const t=safeDecode(e);if(!t)return null;const r=getPubkeyFromDecodeResult(t);return r?{pubkey:r,relays:getRelaysFromDecodeResult(t)}:null}function parseReplaceableAddress(e,t=!1){const r=e.split(":"),n=r[0]?parseInt(r[0]):void 0,i=r[1];if(void 0===n)return null;if(void 0===i||""===i||!isHexKey(i))return null;const o=r.slice(2).join(":");return t&&""===o?null:{kind:n,pubkey:i,identifier:o}}function getPubkeyFromDecodeResult(e){if(e)switch(e.type){case"naddr":case"nprofile":return e.data.pubkey;case"npub":return e.data;case"nsec":return getPublicKey(e.data);default:return}}function getRelaysFromDecodeResult(e){if(e)switch(e.type){case"naddr":case"nprofile":case"nevent":return e.data.relays}}function getEventPointerFromETag(e){const t=e[1];if(!t||!isHexKey(t))return null;const r={id:t};return e[2]&&isSafeRelayURL(e[2])&&(r.relays=[normalizeURL(e[2])]),r}function getAddressPointerFromATag(e){if(!e[1])return null;const t=parseReplaceableAddress(e[1]);return t?(e[2]&&isSafeRelayURL(e[2])&&(t.relays=[normalizeURL(e[2])]),t):null}function getProfilePointerFromPTag(e){const t=e[1];if(!t||!isHexKey(t))return null;const r={pubkey:t};return e[2]&&isSafeRelayURL(e[2])&&(r.relays=[normalizeURL(e[2])]),r}function isAddressPointer(e){return"object"==typeof e&&null!==e&&"identifier"in e&&"pubkey"in e&&"kind"in e&&"string"==typeof e.identifier&&"string"==typeof e.pubkey&&"number"==typeof e.kind}function isEventPointer(e){return"object"==typeof e&&null!==e&&"id"in e&&"string"==typeof e.id}function getReplaceableAddressFromPointer(e){return e.kind+":"+e.pubkey+":"+e.identifier}function eventMatchesPointer(e,t){return isEventPointer(t)?e.id===t.id&&(!t.author||e.pubkey===t.author):e.kind===t.kind&&e.pubkey===t.pubkey&&getReplaceableIdentifier(e)===(t.identifier??"")}const HiddenContentSymbol=EncryptedContentSymbol,getHiddenContentEncryptionMethods=getEncryptedContentEncryptionMethods,HiddenContentKinds=new Set([setEncryptedContentEncryptionMethod(kinds_exports.DraftLong,"nip04")]);function setHiddenContentEncryptionMethod(e,t){return HiddenContentKinds.add(setEncryptedContentEncryptionMethod(e,t)),e}function canHaveHiddenContent(e){return canHaveEncryptedContent(e)&&HiddenContentKinds.has(e)}function hasHiddenContent(e){return canHaveHiddenContent(e.kind)&&hasEncryptedContent(e)}function isHiddenContentUnlocked(e){return!!canHaveHiddenContent(e.kind)&&isEncryptedContentUnlocked(e)&&!0===Reflect.has(e,HiddenContentSymbol)}function getHiddenContent(e){if(canHaveHiddenContent(e.kind))return HiddenContentSymbol in e?Reflect.get(e,HiddenContentSymbol):getEncryptedContent(e)}async function unlockHiddenContent(e,t,r){if(!canHaveHiddenContent(e.kind))throw new Error("Event kind does not support hidden content");if(HiddenContentSymbol in e)return Reflect.get(e,HiddenContentSymbol);const n=getEncryptedContentEncryptionMethods(e.kind,t,r),i=await n.decrypt(e.pubkey,e.content);return setHiddenContentCache(e,i),i}function setHiddenContentCache(e,t){if(!canHaveHiddenContent(e.kind))throw new Error("Event kind does not support hidden content");setEncryptedContentCache(e,t)}const GROUPS_LIST_KIND=10009,HiddenTagsSymbol=Symbol.for("hidden-tags"),HiddenTagsKinds=new Set([setHiddenContentEncryptionMethod(kinds_exports.BookmarkList,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.InterestsList,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.Mutelist,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.CommunitiesList,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.PublicChatsList,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.SearchRelaysList,"nip04"),setHiddenContentEncryptionMethod(GROUPS_LIST_KIND,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.Bookmarksets,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.Relaysets,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.Followsets,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.Curationsets,"nip04"),setHiddenContentEncryptionMethod(kinds_exports.Interestsets,"nip04")]);function canHaveHiddenTags(e){return canHaveHiddenContent(e)&&HiddenTagsKinds.has(e)}function hasHiddenTags(e){return canHaveHiddenTags(e.kind)&&hasHiddenContent(e)}function getHiddenTagsEncryptionMethods(e,t){return getHiddenContentEncryptionMethods(e,t)}function isHiddenTagsUnlocked(e){if(!canHaveHiddenTags(e.kind))return!1;try{return HiddenTagsSymbol in e||isHiddenContentUnlocked(e)&&void 0!==getHiddenTags(e)}catch{}return!1}function getHiddenTags(e){if(!canHaveHiddenTags(e.kind))return;if(HiddenTagsSymbol in e)return e[HiddenTagsSymbol];const t=getHiddenContent(e);if(void 0===t)return;const r=JSON.parse(t);if(!Array.isArray(r))throw new Error("Content is not an array of tags");const n=r.filter(e=>Array.isArray(e)).map(e=>e.map(e=>String(e)));return Reflect.set(e,HiddenTagsSymbol,n),n}async function unlockHiddenTags(e,t,r){if(!canHaveHiddenTags(e.kind))throw new Error("Event kind does not support hidden tags");if(isHiddenTagsUnlocked(e))return e[HiddenTagsSymbol];await unlockHiddenContent(e,t,r);const n=getHiddenTags(e);if(void 0===n)throw new Error("Failed to unlock hidden tags");return setHiddenTagsCache(e,n),n}function setHiddenTagsCache(e,t){if(!canHaveHiddenTags(e.kind))throw new Error("Event kind does not support hidden tags");Reflect.set(e,HiddenTagsSymbol,t),setHiddenContentCache(e,JSON.stringify(t))}const PublicContactsSymbol=Symbol.for("public-contacts"),HiddenContactsSymbol=Symbol.for("hidden-contacts");function mergeContacts(...e){const t=new Map;for(const r of e)if(Array.isArray(r))for(const e of r)e&&t.set(e.pubkey,e);else r&&t.set(r.pubkey,r);return Array.from(t.values())}function getContacts(e){return mergeContacts(getPublicContacts(e),getHiddenContacts(e))}function getPublicContacts(e){return getOrComputeCachedValue(e,PublicContactsSymbol,()=>processTags(e.tags,e=>isPTag(e)?e:void 0,e=>getProfilePointerFromPTag(e)??void 0))}function getHiddenContacts(e){if(HiddenContactsSymbol in e)return e[HiddenContactsSymbol];const t=getHiddenTags(e);if(!t)return;const r=processTags(t,e=>isPTag(e)?e:void 0,e=>getProfilePointerFromPTag(e)??void 0);return Reflect.set(e,HiddenContactsSymbol,r),r}function getDeleteEventPointers(e){return e.tags.filter(isETag).map(getEventPointerFromETag).filter(e=>null!==e).map(t=>(t.author=e.pubkey,t))}function getDeleteAddressPointers(e){return e.tags.filter(isATag).map(getAddressPointerFromATag).filter(e=>null!==e).filter(t=>t.pubkey===e.pubkey)}var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(error){i={error:error}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}function __spreadArray(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=i[e](t)).value instanceof __await?Promise.resolve(r.value.v).then(l,c):u(o[0][2],r)}catch(n){u(o[0][3],n)}var r}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function __asyncValues(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,i){!function(e,t,r,n){Promise.resolve(n).then(function(t){e({value:t,done:r})},t)}(n,i,(t=e[r](t)).done,t.value)})}}}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e(function(e){Error.call(e),e.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var UnsubscriptionError=createErrorClass(function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}});function arrRemove(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var s=__values(o),a=s.next();!a.done;a=s.next())a.value.remove(this)}catch(p){e={error:p}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else o.remove(this);var l=this.initialTeardown;if(isFunction(l))try{l()}catch(f){i=f instanceof UnsubscriptionError?f.errors:[f]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var u=__values(c),h=u.next();!h.done;h=u.next()){var d=h.value;try{execFinalizer(d)}catch(g){i=null!=i?i:[],g instanceof UnsubscriptionError?i=__spreadArray(__spreadArray([],__read(i)),__read(g.errors)):i.push(g)}}}catch(m){r={error:m}}finally{try{h&&!h.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}if(i)throw new UnsubscriptionError(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&arrRemove(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),EMPTY_SUBSCRIPTION=Subscription.EMPTY;function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}var config={Promise:void 0},timeoutProvider={setTimeout:function(e,t){for(var r=[],n=2;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,n=r.hasError,i=r.isStopped,o=r.observers;return n||i?EMPTY_SUBSCRIPTION:(this.currentObservers=null,o.push(e),new Subscription(function(){t.currentObservers=null,arrRemove(o,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t.thrownError,i=t.isStopped;r?e.error(n):i&&e.complete()},t.prototype.asObservable=function(){var e=new Observable$1;return e.source=this,e},t.create=function(e,t){return new AnonymousSubject(e,t)},t}(Observable$1),AnonymousSubject=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return __extends(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:EMPTY_SUBSCRIPTION},t}(Subject),BehaviorSubject=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return __extends(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,n=e._value;if(t)throw r;return this._throwIfClosed(),n},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Subject),dateTimestampProvider={now:function(){return(dateTimestampProvider.delegate||Date).now()},delegate:void 0},ReplaySubject=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=dateTimestampProvider);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=r,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,r),i}return __extends(t,e),t.prototype.next=function(t){var r=this,n=r.isStopped,i=r._buffer,o=r._infiniteTimeWindow,s=r._timestampProvider,a=r._windowTime;n||(i.push(t),!o&&i.push(s.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,n=this._buffer.slice(),i=0;i0&&h(n)},void 0,void 0,function(){(null==s?void 0:s.closed)||null==s||s.unsubscribe(),l=null})),!u&&h(null!=r?"number"==typeof r?r:+r-a.now():n)})}function timeoutErrorFactory(e){throw new TimeoutError$1(e)}function map$1(e,t){return operate(function(r,n){var i=0;r.subscribe(createOperatorSubscriber(n,function(r){n.next(e.call(t,r,i++))}))})}var isArray$1=Array.isArray;function callOrApply(e,t){return isArray$1(t)?e.apply(void 0,__spreadArray([],__read(t))):e(t)}function mapOneOrManyArgs(e){return map$1(function(t){return callOrApply(e,t)})}var isArray=Array.isArray,getPrototypeOf=Object.getPrototypeOf,objectProto=Object.prototype,getKeys=Object.keys;function argsArgArrayOrObject(e){if(1===e.length){var t=e[0];if(isArray(t))return{args:t,keys:null};if(isPOJO(t)){var r=getKeys(t);return{args:r.map(function(e){return t[e]}),keys:r}}}return{args:e,keys:null}}function isPOJO(e){return e&&"object"==typeof e&&getPrototypeOf(e)===objectProto}function createObject(e,t){return e.reduce(function(e,r,n){return e[r]=t[n],e},{})}function combineLatest(){for(var e=[],t=0;t=0?executeSchedule(r,o,c,s,!0):i=!0,c();var u=createOperatorSubscriber(r,function(e){var t,r,i=n.slice();try{for(var o=__values(i),s=o.next();!s.done;s=o.next()){var c=s.value,u=c.buffer;u.push(e),a<=u.length&&l(c)}}catch(h){t={error:h}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},function(){for(;null==n?void 0:n.length;)r.next(n.shift().buffer);null==u||u.unsubscribe(),r.complete(),r.unsubscribe()},void 0,function(){return n=null});t.subscribe(u)})}function catchError(e){return operate(function(t,r){var n,i=null,o=!1;i=t.subscribe(createOperatorSubscriber(r,void 0,void 0,function(s){n=innerFrom(e(s,catchError(e)(t))),i?(i.unsubscribe(),i=null,n.subscribe(r)):o=!0})),o&&(i.unsubscribe(),i=null,n.subscribe(r))})}function scanInternals(e,t,r,n,i){return function(o,s){var a=r,l=t,c=0;o.subscribe(createOperatorSubscriber(s,function(t){var r=c++;l=a?e(l,t,r):(a=!0,t),n&&s.next(l)},i&&function(){a&&s.next(l),s.complete()}))}}function reduce(e,t){return operate(scanInternals(e,t,arguments.length>=2,!1,!0))}var arrReducer=function(e,t){return e.push(t),e};function toArray(){return operate(function(e,t){reduce(arrReducer,[])(e).subscribe(t)})}function defaultIfEmpty(e){return operate(function(t,r){var n=!1;t.subscribe(createOperatorSubscriber(r,function(e){n=!0,r.next(e)},function(){n||r.next(e),r.complete()}))})}function take(e){return e<=0?function(){return EMPTY}:operate(function(t,r){var n=0;t.subscribe(createOperatorSubscriber(r,function(t){++n<=e&&(r.next(t),e<=n&&r.complete())}))})}function ignoreElements(){return operate(function(e,t){e.subscribe(createOperatorSubscriber(t,noop))})}function distinct(e,t){return operate(function(r,n){var i=new Set;r.subscribe(createOperatorSubscriber(n,function(t){var r=e?e(t):t;i.has(r)||(i.add(r),n.next(t))})),t&&innerFrom(t).subscribe(createOperatorSubscriber(n,function(){return i.clear()},noop))})}function distinctUntilChanged(e,t){return void 0===t&&(t=identity$1),e=null!=e?e:defaultCompare$1,operate(function(r,n){var i,o=!0;r.subscribe(createOperatorSubscriber(n,function(r){var s=t(r);!o&&e(i,s)||(o=!1,i=s,n.next(r))}))})}function defaultCompare$1(e,t){return e===t}function endWith(){for(var e=[],t=0;t=2,!0))}function share(e){void 0===e&&(e={});var t=e.connector,r=void 0===t?function(){return new Subject}:t,n=e.resetOnError,i=void 0===n||n,o=e.resetOnComplete,s=void 0===o||o,a=e.resetOnRefCountZero,l=void 0===a||a;return function(e){var t,n,o,a=0,c=!1,u=!1,h=function(){null==n||n.unsubscribe(),n=void 0},d=function(){h(),t=o=void 0,c=u=!1},p=function(){var e=t;d(),null==e||e.unsubscribe()};return operate(function(e,f){a++,u||c||h();var g=o=null!=o?o:r();f.add(function(){0!==--a||u||c||(n=handleReset(p,l))}),g.subscribe(f),!t&&a>0&&(t=new SafeSubscriber({next:function(e){return g.next(e)},error:function(e){u=!0,h(),n=handleReset(d,i,e),g.error(e)},complete:function(){c=!0,h(),n=handleReset(d,s),g.complete()}}),innerFrom(e).subscribe(t))})(e)}}function handleReset(e,t){for(var r=[],n=2;n=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return ms=function(s,a){a=a||{};var l=typeof s;if("string"===l&&s.length>0)return function(o){if(!((o=String(o)).length>100)){var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(s){var a=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(s);if("number"===l&&isFinite(s))return a.long?function(i){var s=Math.abs(i);return s>=n?o(i,s,n,"day"):s>=r?o(i,s,r,"hour"):s>=t?o(i,s,t,"minute"):s>=e?o(i,s,e,"second"):i+" ms"}(s):function(i){var o=Math.abs(i);return o>=n?Math.round(i/n)+"d":o>=r?Math.round(i/r)+"h":o>=t?Math.round(i/t)+"m":o>=e?Math.round(i/e)+"s":i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))}}function requireCommon(){return hasRequiredCommon||(hasRequiredCommon=1,common=function(e){function t(e){let n,i,o,s=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),o=i-(n||i);r.diff=o,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];n=o.call(r,t),e.splice(s,1),s--}return n}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,o=0;for(;r"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const n of r)"-"===n[0]?t.skips.push(n.slice(1)):t.names.push(n)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=requireMs(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(error){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(error){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=r.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(error){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=requireCommon()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}(browser$1,browser$1.exports)),browser$1.exports}var browserExports$1=requireBrowser$1();const debug=getDefaultExportFromCjs$1(browserExports$1),logger$1=debug("applesauce"),log$4=logger$1.extend("event-cache");function persistEventsToCache(e,t,r){const n=r?.batchTime??5e3,i=e.insert$.pipe(filter$1(e=>!isFromCache(e)),r?.maxBatchSize?bufferTime(n,void 0,r?.maxBatchSize??100):bufferTime(n),filter$1(e=>e.length>0)).subscribe(e=>{t(e).then(()=>log$4(`Saved ${e.length} events to cache`)).catch(t=>log$4(`Failed to save ${e.length} events to cache`,t))});return()=>i.unsubscribe()}const ExpirationTimestampSymbol=Symbol("expiration-timestamp");function getExpirationTimestamp(e){return getOrComputeCachedValue(e,ExpirationTimestampSymbol,()=>{const t=e.tags.find(e=>"expiration"===e[0])?.[1];return t?parseInt(t):void 0})}var fastDeepEqual,hasRequiredFastDeepEqual;function requireFastDeepEqual(){return hasRequiredFastDeepEqual||(hasRequiredFastDeepEqual=1,fastDeepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(i=n;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=n;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;0!==i--;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r}),fastDeepEqual}var fastDeepEqualExports=requireFastDeepEqual();const equal=getDefaultExportFromCjs$1(fastDeepEqualExports),LETTERS$1="abcdefghijklmnopqrstuvwxyz",INDEXABLE_TAGS$1=new Set((LETTERS$1+LETTERS$1.toUpperCase()).split("")),EventIndexableTagsSymbol=Symbol.for("indexable-tags");function getIndexableTags$1(e){let t=Reflect.get(e,EventIndexableTagsSymbol);if(!t){const r=new Set;for(const t of e.tags)t.length>=2&&1===t[0].length&&INDEXABLE_TAGS$1.has(t[0])&&r.add(t[0]+":"+t[1]);t=r,Reflect.set(e,EventIndexableTagsSymbol,r)}return t}function matchFilter$1(e,t){if(e.ids&&-1===e.ids.indexOf(t.id))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey))return!1;if(e.since&&t.created_ate.until)return!1;for(let r in e)if("&"===r[0]){let n=r.slice(1),i=e[r];if(i&&i.length>0){const e=getIndexableTags$1(t);for(const t of i)if(!e.has(n+":"+t))return!1}}for(let r in e)if("#"===r[0]){let n=r.slice(1),i=e[r];if(i){const r=e[`&${n}`],o=r?i.filter(e=>!r.includes(e)):i;if(0===o.length)continue;const s=getIndexableTags$1(t);if(!1===o.some(e=>s.has(n+":"+e)))return!1}}return!0}function matchFilters$1(e,t){for(let r=0;r[e,this.get(e)])}evict(e=!1){if(e||this.size>0){const e=this.first;delete this.items[e.key],0===--this.size?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){let t;if(this.has(e)){const r=this.items[e];this.ttl>0&&r.expiry<=Date.now()?this.delete(e):(t=r.value,this.set(e,t,!0))}return t}has(e){return e in this.items}keys(){const e=[];let t=this.first;for(;null!==t;)e.push(t.key),t=t.next;return e}set(e,t,r=!1,n=this.resetTtl){let i;if(r||this.has(e)){if(i=this.items[e],i.value=t,!1===r&&n&&(i.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.last!==i){const e=this.last,t=i.next,r=i.prev;this.first===i&&(this.first=i.next),i.next=null,i.prev=this.last,e.next=i,null!==r&&(r.next=t),null!==t&&(t.prev=r)}}else this.max>0&&this.size===this.max&&this.evict(!0),i=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},1===++this.size?this.first=i:this.last.next=i;return this.last=i,this}values(e=this.keys()){return e.map(e=>this.get(e))}}const MailboxesInboxesSymbol=Symbol.for("mailboxes-inboxes"),MailboxesOutboxesSymbol=Symbol.for("mailboxes-outboxes");function getInboxes(e){return getOrComputeCachedValue(e,MailboxesInboxesSymbol,()=>{const t=[];for(const r of e.tags)if(isRTag(r))try{const[,e,n]=r;!e||!isSafeRelayURL(e)||t.includes(e)||"read"!==n&&void 0!==n||t.push(normalizeURL(e))}catch{}return t})}function getOutboxes(e){return getOrComputeCachedValue(e,MailboxesOutboxesSymbol,()=>{const t=[];for(const r of e.tags)if(isRTag(r))try{const[e,n,i]=r;"r"!==e||!isSafeRelayURL(n)||t.includes(n)||"write"!==i&&void 0!==i||t.push(normalizeURL(n))}catch{}return t})}const ProfileContentSymbol=Symbol.for("profile-content");function getProfileContent(e){return getOrComputeCachedValue(e,ProfileContentSymbol,()=>{const t=safeParse(e.content);if(t)return t.nip05&&"string"!=typeof t.nip05&&(t.nip05=String(t.nip05)),t.website&&t.website?.length>0&&!1===t.website?.startsWith("http")&&(t.website="https://"+t.website),t})}function isValidProfile(e){return!(!e||e.kind!==kinds_exports.Metadata&&e.kind!==kinds_exports.Handlerinformation||!getProfileContent(e))}function createFilterMap(e,t){return Object.fromEntries(Array.from(Object.entries(e)).map(([e,r])=>[e,{authors:r.map(e=>e.pubkey),...t}]))}function setSingletonTag(e,t=!0){return r=>ensureSingletonTag(r,e,t)}function includeSingletonTag(e,t=!0){return modifyPublicTags(setSingletonTag(e,t))}function modifyPublicTags(...e){return async(t,r)=>({...t,tags:await tagPipe(...e)(Array.from(t.tags),r)})}function modifyHiddenTags(...e){return 0===(e=e.filter(e=>!!e)).length?skip():async(t,r)=>{if(!r.signer)throw new Error("Missing signer for hidden tags");if(!canHaveHiddenTags(t.kind))throw new Error("Event kind does not support hidden tags");let n,i;if(hasHiddenTags(t)?(i=getHiddenTags(t),void 0===i&&(hasHiddenTags(t)?(n=await r.signer.getPublicKey(),i=await unlockHiddenTags({...t,pubkey:n},r.signer)):i=[])):i=[],void 0===i)throw new Error("Failed to find hidden tags");const o=await tagPipe(...e)(i,r),s=getHiddenTagsEncryptionMethods(t.kind,r.signer);n||(n=await r.signer.getPublicKey());const a=JSON.stringify(o),l=await s.encrypt(n,a);return{...t,content:l,[EncryptedContentSymbol]:a}}}function modifyTags(e){let t=[],r=[];return void 0===e?t=r=[]:Array.isArray(e)?t=e:"function"==typeof e?t=[e]:("function"==typeof e.public?t=[e.public]:e.public&&(t=e.public),"function"==typeof e.hidden?r=[e.hidden]:e.hidden&&(r=e.hidden)),eventPipe(t.length>0?modifyPublicTags(...t):void 0,r.length>0?modifyHiddenTags(...r):void 0)}function stripSignature(){return e=>{const t={...e};return Reflect.deleteProperty(t,"sig"),t}}function stripStamp(){return e=>{const t={...e};return Reflect.deleteProperty(t,"id"),Reflect.deleteProperty(t,"pubkey"),t}}function updateCreatedAt(){return e=>({...e,created_at:unixNow()})}function stripSymbols(e){return t=>{const r={...t};for(const n of Reflect.ownKeys(r))"string"==typeof n||e?.includes(n)||Reflect.deleteProperty(r,n);return r}}function includeReplaceableIdentifier(e=nanoid$1){return t=>{if(!isAddressableKind$1(t.kind))return t;if(!getTagValue(t,"d")){let r=Array.from(t.tags);return r=ensureSingletonTag(r,["d","string"==typeof e?e:e()],!0),{...t,tags:r}}return t}}function stamp(){return async(e,t)=>{if(!t.signer)throw new Error("Missing signer");Reflect.deleteProperty(e,"id"),Reflect.deleteProperty(e,"sig");const r=await t.signer.getPublicKey(),n={...e,pubkey:r};return Reflect.has(e,EncryptedContentSymbol)&&Reflect.set(n,EncryptedContentSymbol,Reflect.get(e,EncryptedContentSymbol)),n}}function sign(){return async(e,t)=>{if(!t.signer)throw new Error("Missing signer");e=await stamp()(e,t);const r=await t.signer.signEvent(e);return Reflect.has(e,EncryptedContentSymbol)&&Reflect.set(r,EncryptedContentSymbol,Reflect.get(e,EncryptedContentSymbol)),r}}const NEVER_ATTACH_CLIENT_TAG=[kinds_exports.EncryptedDirectMessage,kinds_exports.GiftWrap,kinds_exports.Seal,kinds_exports.PrivateDirectMessage];function setClient(e,t,r=!0){return(n,i)=>{if(NEVER_ATTACH_CLIENT_TAG.includes(n.kind))return n;{const o=t?getReplaceableAddressFromPointer({pubkey:t.pubkey,identifier:t.identifier,kind:kinds_exports.Handlerinformation}):void 0;return includeSingletonTag(fillAndTrimTag(["client",e,o]),r)(n,i)}}}function wrapCommon(...e){return eventPipe(stripSymbols([EncryptedContentSymbol]),includeReplaceableIdentifier(),...e,(e,t)=>t.client?setClient(t.client.name,t.client.address)(e,t):e)}async function buildEvent(e,t,...r){return await wrapCommon(stripSignature(),stripStamp(),...r)({created_at:unixNow(),tags:[],content:"",...e},t)}async function modifyEvent(e,t,...r){return"event"in e&&isEvent(e.event)&&(e=e.event),await wrapCommon(stripSignature(),stripStamp(),updateCreatedAt(),...r)(e,t)}class EventFactory{context;constructor(e={}){this.context=e}async build(e,...t){return await buildEvent(e,this.context,...t)}async create(e,...t){if(1===arguments.length)return await e(this.context);{const r=e;return await r(...t)(this.context)}}async modify(e,...t){return await modifyEvent(e,this.context,...t)}async modifyTags(e,t,r){let n=[];return void 0===r?n=[]:"function"==typeof r?n=[r]:Array.isArray(r)&&(n=r.filter(e=>!!e)),await this.modify(e,modifyTags(t),...n)}async stamp(e){return await stamp()(e,this.context)}async sign(e){return await sign()(e,this.context)}setSigner(e){this.context.signer=e}clearSigner(){this.context.signer=void 0}setClient(e){this.context.client=e}clearClient(){this.context.client=void 0}}class DeleteManager{deleted$;deletedSubject=new Subject;deletedIds=new Map;deletedIdentifiers=new Map;constructor(){this.deleted$=this.deletedSubject.asObservable()}add(e){if(e.kind!==kinds_exports.EventDeletion)return[];const t=e.pubkey,r=[],n=getDeleteEventPointers(e);if(n.length>0){let i=this.deletedIds.get(t);i||(i=new Set,this.deletedIds.set(t,i));for(const t of n){i.add(t.id);const n={pointer:t,until:e.created_at};r.push(n),this.deletedSubject.next(n)}}const i=getDeleteAddressPointers(e);if(i.length>0){let n=this.deletedIdentifiers.get(t);n||(n=new Map,this.deletedIdentifiers.set(t,n));for(const t of i){const i=t.kind+"|"+t.identifier;n.set(i,e.created_at);const o={pointer:t,until:e.created_at};r.push(o),this.deletedSubject.next(o)}}return r}check(e){const t=e.pubkey;if(isReplaceableKind$1(e.kind)||isAddressableKind$1(e.kind)){const r=this.deletedIdentifiers.get(t);if(!r)return!1;const n=getReplaceableIdentifier(e),i=e.kind+"|"+n,o=r.get(i);return void 0!==o&&o>=e.created_at}{const r=this.deletedIds.get(t);return!!r&&r.has(e.id)}}filter(e){return e.filter(e=>!1===this.check(e))}}class EventMemory{log=logger$1.extend("EventMemory");kinds=new Map;authors=new Map;tags=new LRU;created_at=[];kindAuthor=new Map;events=new LRU;replaceable=new Map;get size(){return this.events.size}hasEvent(e){return this.events.has(e)}getEvent(e){return this.events.get(e)}hasReplaceable(e,t,r){const n=this.replaceable.get(createReplaceableAddress(e,t,r));return!!n&&n.length>0}getReplaceable(e,t,r){const n=createReplaceableAddress(e,t,r),i=this.replaceable.get(n);return i?.[0]}getReplaceableHistory(e,t,r){const n=createReplaceableAddress(e,t,r);return this.replaceable.get(n)}getByFilters(e){return Array.from(this.getEventsForFilters(Array.isArray(e)?e:[e]))}getTimeline(e){const t=[],r=this.getByFilters(e);for(const n of r)insertEventIntoDescendingList(t,n);return t}add(e){const t=e.id,r=this.events.get(t);if(r)return r;this.events.set(t,e),this.getKindIndex(e.kind).add(e),this.getAuthorsIndex(e.pubkey).add(e),this.getKindAuthorIndex(e.kind,e.pubkey).add(e);for(const n of getIndexableTags$1(e))this.tags.has(n)&&this.getTagIndex(n).add(e);if(insertEventIntoDescendingList(this.created_at,e),isReplaceable(e.kind)){const t=e.tags.find(e=>"d"===e[0])?.[1],r=createReplaceableAddress(e.kind,e.pubkey,t);let n=this.replaceable.get(r);this.replaceable.has(r)||(n=[],this.replaceable.set(r,n)),insertEventIntoDescendingList(n,e)}return e}remove(e){let t="string"==typeof e?this.events.get(e):e;if(!t)return!1;const r=t.id;if(!this.events.has(r))return!1;this.getAuthorsIndex(t.pubkey).delete(t),this.getKindIndex(t.kind).delete(t);const n=`${t.kind}:${t.pubkey}`;this.kindAuthor.has(n)&&this.kindAuthor.get(n).delete(t);for(const i of getIndexableTags$1(t))this.tags.has(i)&&this.getTagIndex(i).delete(t);if(this.removeFromSortedArray(this.created_at,t),this.events.delete(r),isReplaceable(t.kind)){const e=t.tags.find(e=>"d"===e[0])?.[1],r=createReplaceableAddress(t.kind,t.pubkey,e),n=this.replaceable.get(r);n&&this.removeFromSortedArray(n,t)}return this.claims.delete(t),!0}removeByFilters(e){const t=this.getByFilters(e);let r=0;for(const n of t)this.remove(n)&&r++;return r}update(e){}claims=new WeakMap;touch(e){this.events.has(e.id)&&this.events.set(e.id,e)}claim(e){const t=this.claims.get(e)||0;this.claims.set(e,t+1),this.touch(e)}isClaimed(e){const t=this.claims.get(e);return void 0!==t&&t>0}removeClaim(e){const t=this.claims.get(e);if(void 0!==t&&t>0){const r=t-1;0===r?this.claims.delete(e):this.claims.set(e,r)}}clearClaim(e){this.claims.delete(e)}*unclaimed(){let e=this.events.first;for(;e;){const t=e.value;this.isClaimed(t)||(yield t),e=e.next}return 0}prune(e){let t=0;const r=this.unclaimed();for(const n of r)if(this.remove(n),t++,e&&t>=e)break;return t}getKindIndex(e){return this.kinds.has(e)||this.kinds.set(e,new Set),this.kinds.get(e)}getAuthorsIndex(e){return this.authors.has(e)||this.authors.set(e,new Set),this.authors.get(e)}getKindAuthorIndex(e,t){const r=`${e}:${t}`;return this.kindAuthor.has(r)||this.kindAuthor.set(r,new Set),this.kindAuthor.get(r)}getTagIndex(e){if(!this.tags.has(e)){const t=new Set,r=Date.now();for(const i of this.events.values())getIndexableTags$1(i).has(e)&&t.add(i);const n=Date.now()-r;n>100&&this.log(`Built index ${e} took ${n}ms`),this.tags.set(e,t)}return this.tags.get(e)}removeFromSortedArray(e,t){if(0===e.length)return;const r=binarySearch$2(e,e=>e.created_at-t.created_at);if(r){let n=r[0],i=!1;if(e[n]===t)return void e.splice(n,1);for(let r=n-1;r>=0&&e[r].created_at===t.created_at;r--)if(e[r]===t){e.splice(r,1),i=!0;break}if(i)return;for(let r=n+1;re.created_at-t):void 0;i&&(r=Math.max(0,Math.min(i[0],this.created_at.length-1)));const o=e?binarySearch$2(this.created_at,t=>t.created_at-e):void 0;if(o&&(n=Math.max(0,Math.min(o[0],this.created_at.length-1))),!(r>n))for(let s=r;s<=n;s++){const r=this.created_at[s];if(!(void 0!==t&&r.created_at>t)){if(void 0!==e&&r.created_at{const n=e instanceof Set?e:new Set(e);if(t)r=n,t=!1;else for(const t of r)n.has(t)||r.delete(t);return r};e.ids&&n(this.iterateIds(e.ids));let i=null;void 0!==e.since&&(i=Array.from(this.iterateTime(e.since,e.until)),n(i));for(const o of INDEXABLE_TAGS$1){const t=e[`&${o}`];if(t?.length)for(const e of t)n(this.iterateTag(o,[e]))}for(const o of INDEXABLE_TAGS$1){const t=e[`#${o}`];if(t?.length){const r=e[`&${o}`],i=r?t.filter(e=>!r.includes(e)):t;i.length>0&&n(this.iterateTag(o,i))}}if(e.authors&&e.kinds&&e.authors.length*e.kinds.length<=20){const t=new Set;for(const r of e.kinds)for(const n of e.authors){const e=`${r}:${n}`,i=this.kindAuthor.get(e);if(i)for(const r of i)t.add(r)}n(t)}else e.authors&&n(this.iterateAuthors(e.authors)),e.kinds&&n(this.iterateKinds(e.kinds));if(void 0===e.since&&void 0!==e.until&&(i=Array.from(this.iterateTime(e.since,e.until)),n(i)),t)return new Set(this.events.values());if(e.limit&&i){const t=new Set;for(const n of i){if(t.size>=e.limit)break;r.has(n)&&t.add(n)}return t}return r}getEventsForFilters(e){if(0===e.length)return new Set;let t=new Set;for(const r of e){const e=this.getEventsForFilter(r);for(const r of e)t.add(r)}return t}reset(){this.events.clear(),this.kinds.clear(),this.authors.clear(),this.kindAuthor.clear(),this.tags.clear(),this.created_at=[],this.replaceable.clear(),this.claims=new WeakMap}}var hashSum,hasRequiredHashSum;function requireHashSum(){if(hasRequiredHashSum)return hashSum;function e(e,t){var r,n;if(0===t.length)return e;for(r=0,n=t.length;r{const r=new Set;return t.pipe(tap$1(t=>{if(void 0!==t)if(Array.isArray(t))for(const n of t)r.has(n)||(r.add(n),e.claim(n));else r.has(t)||(r.add(t),e.claim(t))}),finalize(()=>{for(const t of r)e.removeClaim(t)}))}}function claimLatest(e){return t=>{let r;return t.pipe(tap$1(t=>{r!==t&&(r&&e.removeClaim(r),t&&e.claim(t),r=t)}),finalize(()=>{r&&e.removeClaim(r)}))}}function getEventFromStores(e,t){const r=e.getEvent(t.id);return r instanceof Promise?from(r):of(r)}function getReplaceableFromStores(e,t){const r=e.getReplaceable(t.kind,t.pubkey,t.identifier);return r instanceof Promise?from(r):of(r)}function getByFiltersFromStores(e,t){const r=e.getByFilters(t);return r instanceof Promise?from(r).pipe(mergeMap(e=>from(e))):from(r)}function loadEventUsingFallback(e,t){return switchMap(r=>r?of(r):e.eventLoader?from(e.eventLoader(t)).pipe(startWith(void 0)):of(r))}function EventModel(e){return"string"==typeof e&&(e={id:e}),t=>merge$1(defer(()=>getEventFromStores(t,e)).pipe(t.eventLoader?loadEventUsingFallback(t,e):identity$1),t.insert$.pipe(filter$1(t=>t.id===e.id)),t.remove$.pipe(filter$1(t=>t.id===e.id),take(1),map$1(()=>{}))).pipe(distinctUntilChanged((e,t)=>e?.id===t?.id),claimLatest(t))}function ReplaceableModel(e){return t=>{let r;return merge$1(defer(()=>getReplaceableFromStores(t,e)).pipe(t.eventLoader?loadEventUsingFallback(t,e):identity$1),t.insert$.pipe(filter$1(t=>t.pubkey==e.pubkey&&t.kind===e.kind&&(void 0===e.identifier||getReplaceableIdentifier(t)===e.identifier)))).pipe(tap$1(e=>r=e),mergeWith(t.remove$.pipe(filter$1(e=>e.id===r?.id),map$1(()=>{}))),distinctUntilChanged((e,t)=>void 0===e||void 0===t?e===t:t.created_at{const n=new Map;return defer(()=>{const t=r.getTimeline(e);return t instanceof Promise?from(t):of(t)}).pipe(claimEvents(r),mergeWith(r.insert$.pipe(filter$1(t=>matchFilters$1(e,t)),claimEvents(r))),mergeWith(r.remove$.pipe(filter$1(t=>matchFilters$1(e,t)),map$1(e=>e.id))),scan((e,r)=>{if("string"==typeof r)return e.filter(e=>e.id!==r);if(Array.isArray(r)){if(!t)for(const e of r)isReplaceable(e.kind)&&n.set(getEventUID$1(e),e);return[...r]}let i=[...e];if(!t&&isReplaceable(r.kind)){const t=getEventUID$1(r),o=n.get(t);if(o&&r.created_atn.clear()))}}function FiltersModel(e,t=!1){return e=Array.isArray(e)?e:[e],r=>merge$1(t?EMPTY:defer(()=>getByFiltersFromStores(r,e)),r.insert$.pipe(filter$1(t=>matchFilters$1(e,t))))}function watchEventUpdates(e){return t=>{let r;return merge$1(t.pipe(tap$1(e=>r=e)),e.update$.pipe(filter$1(e=>e.id===r?.id)))}}function ContactsModel(e){return"string"==typeof e&&(e={pubkey:e}),t=>t.replaceable({kind:kinds_exports.Contacts,pubkey:e.pubkey,relays:e.relays}).pipe(watchEventUpdates(t),map$1(e=>e?getContacts(e):[]))}function MailboxesModel(e){return"string"==typeof e&&(e={pubkey:e}),t=>t.replaceable({kind:kinds_exports.RelayList,pubkey:e.pubkey,relays:e.relays}).pipe(map$1(e=>e&&{inboxes:getInboxes(e),outboxes:getOutboxes(e)}))}function ProfileModel(e){return"string"==typeof e&&(e={pubkey:e}),t=>t.replaceable({kind:kinds_exports.Metadata,pubkey:e.pubkey,relays:e.relays}).pipe(filter$1(isValidProfile),map$1(e=>e&&getProfileContent(e)))}class EventModels{models=new Map;modelKeepWarm=6e4;model(e,...t){let r=this.models.get(e);r||(r=new Map,this.models.set(e,r));const n=e.getKey?e.getKey(...t):hash_sum(t);let i=r.get(n);if(!i){const o=()=>{r.get(n)===i&&r.delete(n)};i=e(...t)(this).pipe(finalize(o),share({connector:()=>new ReplaySubject(1),resetOnComplete:()=>timer(this.modelKeepWarm),resetOnRefCountZero:()=>timer(this.modelKeepWarm)})),r.set(n,i)}return i}filters(e,t=!1){return Array.isArray(e)||(e=[e]),this.model(FiltersModel,e,t)}event(e){return"string"==typeof e||isEventPointer(e)?this.model(EventModel,e):this.replaceable(e)}replaceable(...e){let t;if(1===e.length)t=e[0];else if(3===e.length||2===e.length){let[r,n,i]=e;t={kind:r,pubkey:n,identifier:i}}if(!t)throw new Error("Invalid arguments, expected address pointer or kind, pubkey, identifier");return this.model(ReplaceableModel,t)}addressable(e){return this.replaceable(e)}timeline(e,t=!1){return this.model(TimelineModel,e,t)}profile(e){return this.model(ProfileModel,e)}contacts(e){return"string"==typeof e&&(e={pubkey:e}),this.model(ContactsModel,e)}mailboxes(e){return"string"==typeof e&&(e={pubkey:e}),this.model(MailboxesModel,e)}}class ExpirationManager{expired$;expiredSubject;expirations=new Map;timer=null;nextCheck=null;constructor(){this.expiredSubject=new Subject,this.expired$=this.expiredSubject.asObservable()}track(e){const t=getExpirationTimestamp(e);if(!t||!Number.isFinite(t))return;const r=unixNow();if(t<=r)return;if(this.expirations.set(e.id,t),this.timer&&this.nextCheck&&this.nextCheck<=t)return;this.timer&&clearTimeout(this.timer);const n=t-r;n>0&&(this.timer=setTimeout(this.emitNotifications.bind(this),1e3*n+10),this.nextCheck=t)}forget(e){this.expirations.delete(e)}check(e){const t=getExpirationTimestamp(e);return!!t&&t<=unixNow()}emitNotifications(){const e=unixNow();let t=1/0;for(const[r,n]of this.expirations)n<=e?(this.expirations.delete(r),this.expiredSubject.next(r)):n0&&(this.timer=setTimeout(this.emitNotifications.bind(this),1e3*r+10),this.nextCheck=t)}}}class EventStore extends EventModels{database;memory;deletes;expiration;keepOldVersions=!1;keepExpired=!1;keepDeleted=!1;_verifyEventMethod=verifyEvent;get verifyEvent(){return this._verifyEventMethod}set verifyEvent(e){this._verifyEventMethod=e,void 0===e&&console.warn("[applesauce-core] EventStore.verifyEvent is undefined; signature checks are disabled.")}insert$=new Subject;update$=new Subject;remove$=new Subject;eventLoader;constructor(e){super(),e?.database?(this.database=e.database,this.memory=new EventMemory):this.database=this.memory=new EventMemory,void 0!==e?.keepDeleted&&(this.keepDeleted=e.keepDeleted),void 0!==e?.keepExpired&&(this.keepExpired=e.keepExpired),void 0!==e?.keepOldVersions&&(this.keepOldVersions=e.keepOldVersions),e?.verifyEvent&&(this.verifyEvent=e.verifyEvent),this.deletes=e?.deleteManager??new DeleteManager,this.deletes.deleted$.subscribe(this.handleDeleteNotification.bind(this)),this.expiration=e?.expirationManager??new ExpirationManager,this.expiration.expired$.subscribe(this.handleExpiredNotification.bind(this))}mapToMemory(e){if(void 0!==e)return this.memory?this.memory.add(e):e}handleDeleteNotification({pointer:e,until:t}){if(!this.keepDeleted)if(isEventPointer(e)){const r=this.getEvent(e.id);r&&t>=r.created_at&&eventMatchesPointer(r,e)&&this.remove(r)}else if(isAddressPointer(e)){const r=this.getReplaceableHistory(e.kind,e.pubkey,e.identifier);if(r)for(const n of r)t>=n.created_at&&eventMatchesPointer(n,e)&&this.remove(n)}}handleExpiredNotification(e){this.keepExpired||this.remove(e)}static copySymbolsToDuplicateEvent(e,t){if(e.kind!==t.kind)throw new Error("Source and destination events must have the same kind");if(isRegularKind(e.kind)&&e.id!==t.id)throw new Error("Source and destination events must have the same ID");if(isReplaceable(e.kind)&&e.pubkey!==t.pubkey&&getReplaceableIdentifier(e)!==getReplaceableIdentifier(t))throw new Error("Source and destination events must have the same pubkey and replaceable identifier");let r=!1;const n=getSeenRelays(e);if(n){for(const e of n)addSeenRelay(t,e);r=!0}const i=[FromCacheSymbol,verifiedSymbol,EncryptedContentSymbol];for(const o of i)o in e&&!(o in t)&&(Reflect.set(t,o,Reflect.get(e,o)),r=!0);return r}add(e,t){if(e.kind===kinds_exports.EventDeletion)return this.deletes.add(e),e;if(this.deletes.check(e))return e;const r=getExpirationTimestamp(e);if(!1===this.keepExpired&&r&&r<=unixNow())return null;t&&addSeenRelay(e,t);const n=isReplaceable(e.kind)?getReplaceableIdentifier(e):void 0;if(!1===this.keepOldVersions&&isReplaceable(e.kind)){const t=this.database.getReplaceableHistory(e.kind,e.pubkey,n);if(t&&t.length>0&&t[0].created_at>=e.created_at)return EventStore.copySymbolsToDuplicateEvent(e,t[0])&&this.update(t[0]),t[0]}if(this.verifyEvent&&!1===this.verifyEvent(e))return null;const i=this.memory.add(e);if(i&&i!==e)return EventStore.copySymbolsToDuplicateEvent(e,i)&&this.update(i),i;const o=this.mapToMemory(this.database.add(e));if(o===e?(Reflect.set(o,EventStoreSymbol,this),this.insert$.next(o)):EventStore.copySymbolsToDuplicateEvent(e,o)&&this.update(o),!1===this.keepOldVersions&&isReplaceable(e.kind)){const t=this.database.getReplaceableHistory(e.kind,e.pubkey,n);if(t&&t.length>0){const r=Array.from(t).filter(t=>t.created_atthis.mapToMemory(e)??e)}getByFilters(e){const t=this.database.getByFilters(e);return this.memory?t.map(e=>this.mapToMemory(e)):t}getTimeline(e){const t=this.database.getTimeline(e);return this.memory?t.map(e=>this.mapToMemory(e)):t}touch(e){return this.memory.touch(e)}claim(e){return this.memory.claim(e)}isClaimed(e){return this.memory.isClaimed(e)??!1}removeClaim(e){return this.memory.removeClaim(e)}clearClaim(e){return this.memory.clearClaim(e)}unclaimed(){return this.memory.unclaimed()||function*(){}()}prune(e){return this.memory.prune(e)??0}}function mapEventsToStore(e,t=!0){return r=>{const n=r.pipe(share());return n.pipe(mergeMap(t=>{if("string"==typeof t)return EMPTY;const r=e.add(t);return r instanceof Promise?from(r):of(r)}),catchError(()=>of(null)),filter$1(e=>null!==e),t?distinct():identity$1,mergeWith(n.pipe(filter$1(e=>"string"==typeof e))))}}function filterDuplicateEvents(e){return mapEventsToStore(e,!0)}class TimeoutError extends Error{}function simpleTimeout(e){return timeout$1({first:e,with:()=>throwError(()=>new TimeoutError("Timeout"))})}function isBytes$1(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT}function abytes$1(e,t,r=""){const n=isBytes$1(e),i=e?.length;if(!n||void 0!==t){const t=(r&&`"${r}" `)+"expected Uint8Array, got "+(n?`length=${i}`:"type="+typeof e);if(!n)throw new TypeError(t);throw new RangeError(t)}return e}function aexists(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function aoutput(e,t){abytes$1(e,void 0,"digestInto() output");const r=t.outputLen;if(e.length='+r)}function clean(...e){for(let t=0;t>>t}function createHasher(e,t={}){const r=(t,r)=>e(r).update(t).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=t=>e(t),Object.assign(r,t),Object.freeze(r)}const oidNist=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Chi(e,t,r){return e&t^~e&r}function Maj(e,t,r){return e&t^e&r^t&r}class HashMD{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this),abytes$1(e);const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let o=0;on-o&&(this.process(r,0),o=0);for(let u=o;uc.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,n=rotr(t,17)^rotr(t,19)^t>>>10;SHA256_W[u]=n+SHA256_W[u-7]+r+SHA256_W[u-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(rotr(s,6)^rotr(s,11)^rotr(s,25))+Chi(s,a,l)+SHA256_K[u]+SHA256_W[u]|0,t=(rotr(r,2)^rotr(r,13)^rotr(r,22))+Maj(r,n,i)|0;c=l,l=a,a=s,s=o+e|0,o=i,i=n,n=r,r=e+t|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(r,n,i,o,s,a,l,c)}roundClean(){clean(SHA256_W)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}class _SHA256 extends SHA2_32B{A=0|SHA256_IV[0];B=0|SHA256_IV[1];C=0|SHA256_IV[2];D=0|SHA256_IV[3];E=0|SHA256_IV[4];F=0|SHA256_IV[5];G=0|SHA256_IV[6];H=0|SHA256_IV[7];constructor(){super(32)}}const sha256=createHasher(()=>new _SHA256,oidNist(1)),deferred=new WeakMap;function deferDecorator(e,t,r){let n=deferred.get(e);n||(n=new Map,deferred.set(e,n)),n.set(t,r)}function findDeferredDecorator(e,t){var r;let n=e.prototype;for(;n;){let e=null==(r=deferred.get(n))?void 0:r.get(t);if(e)return e;n=n.prototype}}function decorateFieldV2(e,t,r,n){let i={configurable:!0,enumerable:!0,writable:!0,initializer:null};n&&(i.initializer=n);for(let o of r)i=o(e,t,i)||i;void 0===i.initializer?Object.defineProperty(e,t,i):deferDecorator(e,t,i)}function decorateMethodV2(e,t,r){let n={...Object.getOwnPropertyDescriptor(e,t)};for(let i of r)n=i(e,t,n)||n;void 0!==n.initializer&&(n.value=n.initializer?n.initializer.call(e):void 0,n.initializer=void 0),Object.defineProperty(e,t,n)}function initializeDeferredDecorator(e,t){let r=findDeferredDecorator(e.constructor,t);r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(e):void 0})}const DEFAULT_BLOSSOM_SERVER="https://blossom.nostr.build";function bufferToHex(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}function getBlossomUrl(e,t){let r=e||DEFAULT_BLOSSOM_SERVER;return r.endsWith("/")&&(r=r.slice(0,-1)),t.startsWith("/")?`${r}${t}`:`${r}/${t}`}class BlossomService extends Service{static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");get servers(){const e=this.nostrData.blossomServers,t=e.length?e:[DEFAULT_BLOSSOM_SERVER];return this.settings.nostrPhotoFallbackUploads?t:[t[0]]}async _getAuthHeader(e,t,r){const n=new EventFactory({signer:this.nostrAuth.signer}),i=Math.floor(Date.now()/1e3),o=new URL(r).hostname,s={kind:24242,created_at:i,content:"upload"===e?"Upload photo for place":"Delete photo",tags:[["t",e],["x",t],["expiration",String(i+3600)],["server",o]]},a=await n.sign(s);return`Nostr ${btoa(JSON.stringify(a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}async _uploadToServer(e,t,r,n){const i=getBlossomUrl(r,"upload");n&&n("signing");const o=await this._getAuthHeader("upload",t,r);n&&n("uploading");const s=await fetch(i,{method:"PUT",headers:{Authorization:o,"X-SHA-256":t},body:e});if(!s.ok){const e=await s.text();throw new Error(`Upload failed (${s.status}): ${e}`)}return s.json()}async upload(e,t={sequential:!1}){if(!this.nostrAuth.isConnected)throw new Error("Not connected");const r=await e.arrayBuffer();let n;n="undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest?await crypto.subtle.digest("SHA-256",r):sha256(new Uint8Array(r));const i=bufferToHex(n),o=this.servers,s=o[0],a=o.slice(1),l=[];let c;if(t.sequential){c=await this._uploadToServer(e,i,s,t.onProgress);for(const r of a)try{const n=await this._uploadToServer(e,i,r,t.onProgress);l.push(n.url)}catch(error){console.warn(`Fallback upload to ${r} failed:`,error)}}else{const r=this._uploadToServer(e,i,s,t.onProgress),n=a.map(r=>this._uploadToServer(e,i,r,t.onProgress));c=await r;const o=await Promise.allSettled(n);for(let e=0;ethis._deleteFromServer(e,t));await i;const s=await Promise.allSettled(o);for(let a=0;a{const n=new Image,i=URL.createObjectURL(e);n.onload=()=>{const e={width:n.width,height:n.height};URL.revokeObjectURL(i),t(e)},n.onerror=()=>{URL.revokeObjectURL(i),r(new Error("Could not read image dimensions"))},n.src=i})}async process(e,t,r,n=!1){if(!this._worker)throw new Error("Image processor worker is not available.");try{const{width:i,height:o}=await this._getImageDimensions(e);let s=i,a=o;return i>o?i>t&&(a=Math.round(o*(t/i)),s=t):o>t&&(s=Math.round(i*(t/o)),a=t),new Promise((t,i)=>{const o=++this._msgId;this._callbacks.set(o,{resolve:t,reject:i}),this._worker.postMessage({type:"PROCESS_IMAGE",id:o,file:e,targetWidth:s,targetHeight:a,quality:r,computeBlurhash:n})})}catch(i){throw new Error(`Failed to process image: ${i.message}`)}}willDestroy(){super.willDestroy(...arguments),this._worker&&(this._worker.terminate(),this._worker=null),this._callbacks.clear()}}const amdModule5=Object.freeze(Object.defineProperty({__proto__:null,default:ImageProcessorService},Symbol.toStringTag,{value:"Module"}));class MapUiService extends Service{static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"selectedPlace",[tracked],function(){return null})}#O=void initializeDeferredDecorator(this,"selectedPlace");static{decorateFieldV2(this.prototype,"isSearching",[tracked],function(){return!1})}#L=void initializeDeferredDecorator(this,"isSearching");static{decorateFieldV2(this.prototype,"isCreating",[tracked],function(){return!1})}#M=void initializeDeferredDecorator(this,"isCreating");static{decorateFieldV2(this.prototype,"creationCoordinates",[tracked],function(){return null})}#D=void initializeDeferredDecorator(this,"creationCoordinates");static{decorateFieldV2(this.prototype,"returnToSearch",[tracked],function(){return!1})}#N=void initializeDeferredDecorator(this,"returnToSearch");static{decorateFieldV2(this.prototype,"currentCenter",[tracked],function(){return null})}#F=void initializeDeferredDecorator(this,"currentCenter");static{decorateFieldV2(this.prototype,"currentBounds",[tracked],function(){return null})}#$=void initializeDeferredDecorator(this,"currentBounds");static{decorateFieldV2(this.prototype,"searchBoxHasFocus",[tracked],function(){return!1})}#B=void initializeDeferredDecorator(this,"searchBoxHasFocus");static{decorateFieldV2(this.prototype,"selectionOptions",[tracked],function(){return{}})}#U=void initializeDeferredDecorator(this,"selectionOptions");static{decorateFieldV2(this.prototype,"preventNextZoom",[tracked],function(){return!1})}#z=void initializeDeferredDecorator(this,"preventNextZoom");static{decorateFieldV2(this.prototype,"searchResults",[tracked],function(){return[]})}#j=void initializeDeferredDecorator(this,"searchResults");static{decorateFieldV2(this.prototype,"currentSearch",[tracked],function(){return null})}#V=void initializeDeferredDecorator(this,"currentSearch");static{decorateFieldV2(this.prototype,"loadingState",[tracked],function(){return null})}#G=void initializeDeferredDecorator(this,"loadingState");static{decorateFieldV2(this.prototype,"isSidebarVisible",[tracked],function(){return!1})}#H=void initializeDeferredDecorator(this,"isSidebarVisible");showSidebar(){this.isSidebarVisible=!0}hideSidebar(){this.isSidebarVisible=!1}selectPlace(e,t={}){this.selectedPlace=e,this.selectionOptions=t,this.nostrData.loadPhotosForPlace(e)}clearSelection(){this.selectedPlace=null,this.selectionOptions={},this.preventNextZoom=!1,this.nostrData.loadPhotosForPlace(null)}setSearchResults(e){this.searchResults=e||[]}clearSearchResults(){this.searchResults=[],this.currentSearch=null}startSearch(){this.isSearching=!0,this.isCreating=!1,this.preventNextZoom=!1}stopSearch(){this.isSearching=!1}startCreating(){this.isCreating=!0,this.isSearching=!1}stopCreating(){this.isCreating=!1,this.creationCoordinates=null}updateCreationCoordinates(e,t){this.creationCoordinates={lat:e,lon:t}}setSearchBoxFocus(e){this.searchBoxHasFocus=e}updateCenter(e,t){this.currentCenter={lat:e,lon:t}}updateBounds(e){this.currentBounds=e}startLoading(e,t){this.loadingState={type:e,value:t}}stopLoading(e=null,t=null){e||t?this.loadingState&&this.loadingState.type===e&&this.loadingState.value===t&&(this.loadingState=null):this.loadingState=null}}const amdModule6=Object.freeze(Object.defineProperty({__proto__:null,default:MapUiService},Symbol.toStringTag,{value:"Module"}));function getConnectionMethods(e,t){const r=e.subscriptionMethod||e.pool?.subscription.bind(e.pool)||t?.subscriptionMethod||t?.pool?.subscription.bind(t.pool);if(!r)throw new Error("Missing subscriptionMethod, either pass a method or set subscriptionMethod globally on the class");const n=e.publishMethod||e.pool?.publish.bind(e.pool)||t?.publishMethod||t?.pool?.publish.bind(t.pool);if(!n)throw new Error("Missing publishMethod, either pass a method or set publishMethod globally on the class");return{subscriptionMethod:r,publishMethod:n}}function createDefer(){let e,t;const r=new Promise((r,n)=>{e=r,t=n});return r.resolve=e,r.reject=t,r}class AmberClipboardSigner{static SUPPORTED="navigator"in globalThis&&navigator.userAgent.includes("Android")&&navigator.clipboard&&navigator.clipboard.readText;pendingRequest=null;pubkey;verifyEvent=verifyEvent;nip04;nip44;constructor(){document.addEventListener("visibilitychange",this.onVisibilityChange),this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)},this.nip44={encrypt:this.nip44Encrypt.bind(this),decrypt:this.nip44Decrypt.bind(this)}}onVisibilityChange=()=>{if("visible"===document.visibilityState){if(!this.pendingRequest||!navigator.clipboard)return;setTimeout(()=>{navigator.clipboard.readText().then(e=>this.pendingRequest?.resolve(e)).catch(e=>this.pendingRequest?.reject(e))},200)}};async intentRequest(e){this.rejectPending();const t=createDefer();window.open(e,"_blank"),setTimeout(()=>{this.pendingRequest=t},500);const r=await t;if(0===r.length)throw new Error("Empty clipboard");return r}rejectPending(){this.pendingRequest&&(this.pendingRequest.reject("Canceled"),this.pendingRequest=null)}destroy(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}checkSupport(){if(!AmberClipboardSigner.SUPPORTED)throw new Error("Cant use Amber on non-Android device")}async getPublicKey(){if(this.checkSupport(),this.pubkey)return this.pubkey;const e=await this.intentRequest(AmberClipboardSigner.createGetPublicKeyIntent());if(isHexKey(e))return this.pubkey=e,e;if(e.startsWith("npub")||e.startsWith("nprofile")){const t=decodeProfilePointer(e)?.pubkey;if(!t)throw new Error("Expected npub from clipboard");return this.pubkey=t,t}throw new Error("Expected clipboard to have pubkey")}async signEvent(e){this.checkSupport();const t=e.pubkey||this.pubkey;if(!t)throw new Error("Unknown signer pubkey");const r={...e,id:getEventHash({...e,pubkey:t})},n=await this.intentRequest(AmberClipboardSigner.createSignEventIntent(r));if(!isHex(n))throw new Error("Expected hex signature");const i={...r,sig:n,pubkey:t};if(!this.verifyEvent(i))throw new Error("Invalid signature");return i}async nip04Encrypt(e,t){return this.checkSupport(),await this.intentRequest(AmberClipboardSigner.createNip04EncryptIntent(e,t))}async nip04Decrypt(e,t){return this.checkSupport(),await this.intentRequest(AmberClipboardSigner.createNip04DecryptIntent(e,t))}async nip44Encrypt(e,t){return this.checkSupport(),await this.intentRequest(AmberClipboardSigner.createNip44EncryptIntent(e,t))}async nip44Decrypt(e,t){return this.checkSupport(),await this.intentRequest(AmberClipboardSigner.createNip44DecryptIntent(e,t))}static createGetPublicKeyIntent(){return"intent:#Intent;scheme=nostrsigner;S.compressionType=none;S.returnType=signature;S.type=get_public_key;end"}static createSignEventIntent(e){return`intent:${encodeURIComponent(JSON.stringify(e))}#Intent;scheme=nostrsigner;S.compressionType=none;S.returnType=signature;S.type=sign_event;end`}static createNip04EncryptIntent(e,t){return`intent:${encodeURIComponent(t)}#Intent;scheme=nostrsigner;S.pubKey=${e};S.compressionType=none;S.returnType=signature;S.type=nip04_encrypt;end`}static createNip04DecryptIntent(e,t){return`intent:${encodeURIComponent(t)}#Intent;scheme=nostrsigner;S.pubKey=${e};S.compressionType=none;S.returnType=signature;S.type=nip04_decrypt;end`}static createNip44EncryptIntent(e,t){return`intent:${encodeURIComponent(t)}#Intent;scheme=nostrsigner;S.pubKey=${e};S.compressionType=none;S.returnType=signature;S.type=nip44_encrypt;end`}static createNip44DecryptIntent(e,t){return`intent:${encodeURIComponent(t)}#Intent;scheme=nostrsigner;S.pubKey=${e};S.compressionType=none;S.returnType=signature;S.type=nip44_decrypt;end`}}class ExtensionMissingError extends Error{}class ExtensionSigner{get nip04(){return window.nostr?.nip04}get nip44(){return window.nostr?.nip44}pubkey=void 0;async getPublicKey(){if(!window.nostr)throw new ExtensionMissingError("Signer extension missing");if(this.pubkey)return this.pubkey;const e=await window.nostr.getPublicKey();if(!isHexKey(e))throw new Error("Extension returned an invalid public key");return this.pubkey=e,this.pubkey}async signEvent(e){if(!window.nostr)throw new ExtensionMissingError("Signer extension missing");const t=await window.nostr.signEvent(e);if(!verifyEvent(t))throw new Error("Extension returned an invalid event");return t}}function isNIP04Encrypted(e){const t=e.length;return!(t<28)&&"?"==e[t-28]&&"i"==e[t-27]&&"v"==e[t-26]&&"="==e[t-25]}var Permission,NostrConnectMethod;function parseBunkerURI(e){const t=new URL(e),r=t.host||t.pathname.replace("//","");if(!isHexKey(r))throw new Error("Invalid bunker URI: remote is not a valid hex key");const n=t.searchParams.getAll("relay");if(0===n.length)throw new Error("Invalid bunker URI: missing relays");return{remote:r,relays:n,secret:t.searchParams.get("secret")??void 0}}function createNostrConnectURI(e){const t=new URLSearchParams;t.set("secret",e.secret),e.metadata?.name&&t.set("name",e.metadata.name),e.metadata?.url&&t.set("url",String(e.metadata.url)),e.metadata?.image&&t.set("image",e.metadata.image),e.metadata?.permissions&&t.set("perms",e.metadata.permissions.join(","));for(const r of e.relays)t.append("relay",r);return`nostrconnect://${e.client}?`+t.toString()}function buildSigningPermissions(e){return[Permission.GetPublicKey,...e.map(e=>`${Permission.SignEvent}:${e}`)]}setHiddenContentEncryptionMethod(kinds_exports.NostrConnect,"nip44"),function(e){e.GetPublicKey="get_pubic_key",e.SignEvent="sign_event",e.Ping="ping",e.Nip04Encrypt="nip04_encrypt",e.Nip04Decrypt="nip04_decrypt",e.Nip44Encrypt="nip44_encrypt",e.Nip44Decrypt="nip44_decrypt",e.SwitchRelays="switch_relays"}(Permission||(Permission={})),function(e){e.Connect="connect",e.CreateAccount="create_account",e.GetPublicKey="get_public_key",e.SignEvent="sign_event",e.Ping="ping",e.Nip04Encrypt="nip04_encrypt",e.Nip04Decrypt="nip04_decrypt",e.Nip44Encrypt="nip44_encrypt",e.Nip44Decrypt="nip44_decrypt",e.SwitchRelays="switch_relays"}(NostrConnectMethod||(NostrConnectMethod={}));class PrivateKeySigner{key;constructor(e){this.key=e||generateSecretKey()}async getPublicKey(){return getPublicKey(this.key)}async signEvent(e){return finalizeEvent(e,this.key)}nip04={encrypt:async(e,t)=>nip04_exports.encrypt(this.key,e,t),decrypt:async(e,t)=>nip04_exports.decrypt(this.key,e,t)};nip44={encrypt:async(e,t)=>nip44_exports.v2.encrypt(t,nip44_exports.v2.utils.getConversationKey(this.key,e)),decrypt:async(e,t)=>nip44_exports.v2.decrypt(t,nip44_exports.v2.utils.getConversationKey(this.key,e))};static fromKey(e){const t=normalizeToSecretKey(e);if(!t)throw new Error("Invalid private key");return new PrivateKeySigner(t)}}async function defaultHandleAuth(e){window.open(e,"auth","width=400,height=600,resizable=no,status=no,location=no,toolbar=no,menubar=no")}class NostrConnectSigner{static subscriptionMethod=void 0;static publishMethod=void 0;static pool=void 0;publishMethod;subscriptionMethod;log=logger$1.extend("NostrConnectSigner");signer;listening=!1;isConnected=!1;pubkey;relays;remote;get clientPubkey(){return getPublicKey(this.signer.key)}onAuth=defaultHandleAuth;verifyEvent=verifyEvent;secret;nip04;nip44;constructor(e){this.relays=e.relays,this.pubkey=e.pubkey,this.remote=e.remote,this.secret=e.secret||nanoid$1(12);const{subscriptionMethod:t,publishMethod:r}=getConnectionMethods(e,NostrConnectSigner);this.subscriptionMethod=(e,r)=>t(e,r),this.publishMethod=(e,t)=>r(e,t),e.onAuth&&(this.onAuth=e.onAuth),this.signer=e?.signer||new PrivateKeySigner,this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)},this.nip44={encrypt:this.nip44Encrypt.bind(this),decrypt:this.nip44Decrypt.bind(this)}}req;async open(){if(this.listening)return;this.listening=!0;const e=await this.signer.getPublicKey();this.req=from(this.subscriptionMethod(this.relays,[{kinds:[kinds_exports.NostrConnect],"#p":[e]}])).pipe(repeat(),retry(),filter$1(e=>"string"!=typeof e)).subscribe(this.handleEvent.bind(this)),this.log("Opened",this.relays)}async close(){this.listening=!1,this.isConnected=!1,this.req&&(this.req.unsubscribe(),this.req=void 0),this.waitingPromise&&(this.waitingPromise.reject(new Error("Closed")),this.waitingPromise=null),this.log("Closed")}requests=new Map;auths=new Set;async handleEvent(e){if(this.verifyEvent(e)&&(!this.remote||e.pubkey===this.remote))try{const r=getHiddenContent(e)??(isNIP04Encrypted(e.content)?await this.signer.nip04.decrypt(e.pubkey,e.content):await this.signer.nip44.decrypt(e.pubkey,e.content));if(!r)return;const n=JSON.parse(r);if(!this.remote&&("ack"===n.result||this.secret&&n.result===this.secret))return this.log("Got ack response from",e.pubkey,n.result),this.isConnected=!0,this.remote=e.pubkey,this.waitingPromise?.resolve(),void(this.waitingPromise=null);if(n.id){const e=this.requests.get(n.id);if(!e)return;if(n.error)if(this.log("Got Error",n.id,n.result,n.error),"auth_url"===n.result){if(!this.auths.has(n.id)&&(this.auths.add(n.id),this.onAuth))try{await this.onAuth(n.error)}catch(t){e.reject(t)}}else e.reject(new Error(n.error));else n.result&&(this.log("Got Response",n.id,n.result),e.resolve(n.result))}}catch(t){}}async createRequestEvent(e,t=this.remote,r=kinds_exports.NostrConnect){if(!t)throw new Error("Missing target pubkey");return await this.signer.signEvent({kind:r,created_at:unixNow(),tags:[["p",t]],content:e})}async makeRequest(e,t,r=kinds_exports.NostrConnect){if(!this.remote)throw new Error("Missing remote signer pubkey");const n=nanoid$1(8),i={id:n,method:e,params:t},o=await this.signer.nip44.encrypt(this.remote,JSON.stringify(i)),s=await this.createRequestEvent(o,this.remote,r);this.log(`Sending ${n} (${e}) ${JSON.stringify(t)}`);const a=createDefer();this.requests.set(n,a);const l=this.publishMethod?.(this.relays,s);return l instanceof Promise?await l:"subscribe"in l&&await new Promise(e=>l.subscribe({complete:e})),this.log(`Sent ${n} (${e})`),a}async connect(e,t){if(!this.remote&&this.pubkey&&(this.remote=this.pubkey),!this.remote)throw new Error("Missing remote signer pubkey");await this.open();try{const r=await this.makeRequest(NostrConnectMethod.Connect,[this.remote,e||"",t?.join(",")??""]);return this.isConnected=!0,r}catch(r){throw this.isConnected=!1,this.close(),r}}waitingPromise=null;waitForSigner(e){return this.isConnected?Promise.resolve():(this.open(),this.waitingPromise=createDefer(),e?.addEventListener("abort",()=>{this.waitingPromise?.reject(new Error("Aborted")),this.waitingPromise=null,this.close()},!0),this.waitingPromise)}async createAccount(e,t,r,n){if(!this.remote)throw new Error("Remote pubkey must be set");await this.open();try{const i=await this.makeRequest(NostrConnectMethod.CreateAccount,[e,t,r??"",n?.join(",")??""]);return this.pubkey=i,this.isConnected=!0,i}catch(i){throw this.isConnected=!1,this.close(),i}}async requireConnection(){this.isConnected||await this.connect()}async getPublicKey(){if(this.pubkey)return this.pubkey;await this.requireConnection();const e=await this.makeRequest(NostrConnectMethod.GetPublicKey,[]);if(!isHexKey(e))throw new Error("Remote signer returned an invalid public key");return e}async signEvent(e){await this.requireConnection();const t=await this.makeRequest(NostrConnectMethod.SignEvent,[JSON.stringify(e)]),r=JSON.parse(t);if(!this.verifyEvent(r))throw new Error("Invalid event");return r}async nip04Encrypt(e,t){return await this.requireConnection(),this.makeRequest(NostrConnectMethod.Nip04Encrypt,[e,t])}async nip04Decrypt(e,t){await this.requireConnection();const r=await this.makeRequest(NostrConnectMethod.Nip04Decrypt,[e,t]);return r.startsWith('["')&&r.endsWith('"]')?JSON.parse(r)[0]:r}async nip44Encrypt(e,t){return await this.requireConnection(),this.makeRequest(NostrConnectMethod.Nip44Encrypt,[e,t])}async nip44Decrypt(e,t){await this.requireConnection();const r=await this.makeRequest(NostrConnectMethod.Nip44Decrypt,[e,t]);return r.startsWith('["')&&r.endsWith('"]')?JSON.parse(r)[0]:r}async ping(){return await this.requireConnection(),this.makeRequest(NostrConnectMethod.Ping,[])}async switchRelays(){await this.requireConnection();const e=await this.makeRequest(NostrConnectMethod.SwitchRelays,[]);return null!==e&&Array.isArray(e)&&e.length>0&&(this.log("Switching relays from",this.relays,"to",e),this.relays=e,this.listening&&(await this.close(),await this.open())),e}getNostrConnectURI(e){return createNostrConnectURI({client:getPublicKey(this.signer.key),secret:this.secret,relays:this.relays,metadata:e})}static parseBunkerURI(e){return parseBunkerURI(e)}static buildSigningPermissions(e){return buildSigningPermissions(e)}static async fromBunkerURI(e,t){const{remote:r,relays:n,secret:i}=NostrConnectSigner.parseBunkerURI(e),o=new NostrConnectSigner({relays:n,remote:r,...t});return await o.connect(i,t?.permissions),o}} -/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_8n=BigInt(8),CURVE=Object.freeze({a:_0n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),divNearest=(e,t)=>(e+t/_2n)/t,endo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=CURVE,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=divNearest(o*e,t),l=divNearest(-n*e,t);let c=mod(e-a*r-l*i,t),u=mod(-a*n-l*o,t);const h=c>s,d=u>s;if(h&&(c=t-c),d&&(u=t-u),c>s||u>s)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:c,k2neg:d,k2:u}}},fieldLen=32,groupLen=32,compressedLen=fieldLen+1,uncompressedLen=2*fieldLen+1;function weierstrass(e){const{a:t,b:r}=CURVE,n=mod(e*e),i=mod(n*e);return mod(i+t*e+r)}const USE_ENDOMORPHISM=CURVE.a===_0n;function assertJacPoint(e){if(!(e instanceof JacobianPoint))throw new TypeError("JacobianPoint expected")}class JacobianPoint{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Point$1))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Point$1.ZERO)?JacobianPoint.ZERO:new JacobianPoint(e.x,e.y,_1n)}static toAffineBatch(e){const t=invertBatch(e.map(e=>e.z));return e.map((e,r)=>e.toAffine(t[r]))}static normalizeZ(e){return JacobianPoint.toAffineBatch(e).map(JacobianPoint.fromAffine)}equals(e){assertJacPoint(e);const{x:t,y:r,z:n}=this,{x:i,y:o,z:s}=e,a=mod(n*n),l=mod(s*s),c=mod(t*l),u=mod(i*a),h=mod(mod(r*s)*l),d=mod(mod(o*n)*a);return c===u&&h===d}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=mod(e*e),i=mod(t*t),o=mod(i*i),s=e+i,a=mod(_2n*(mod(s*s)-n-o)),l=mod(_3n*n),c=mod(l*l),u=mod(c-_2n*a),h=mod(l*(a-u)-_8n*o),d=mod(_2n*t*r);return new JacobianPoint(u,h,d)}add(e){assertJacPoint(e);const{x:t,y:r,z:n}=this,{x:i,y:o,z:s}=e;if(i===_0n||o===_0n)return this;if(t===_0n||r===_0n)return e;const a=mod(n*n),l=mod(s*s),c=mod(t*l),u=mod(i*a),h=mod(mod(r*s)*l),d=mod(mod(o*n)*a),p=mod(u-c),f=mod(d-h);if(p===_0n)return f===_0n?this.double():JacobianPoint.ZERO;const g=mod(p*p),m=mod(p*g),y=mod(c*g),b=mod(f*f-m-_2n*y),v=mod(f*(y-b)-h*m),_=mod(n*s*p);return new JacobianPoint(b,v,_)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=JacobianPoint.ZERO;if("bigint"==typeof e&&e===_0n)return t;let r=normalizeScalar(e);if(r===_1n)return this;if(!USE_ENDOMORPHISM){let e=t,n=this;for(;r>_0n;)r&_1n&&(e=e.add(n)),n=n.double(),r>>=_1n;return e}let{k1neg:n,k1:i,k2neg:o,k2:s}=endo.splitScalar(r),a=t,l=t,c=this;for(;i>_0n||s>_0n;)i&_1n&&(a=a.add(c)),s&_1n&&(l=l.add(c)),c=c.double(),i>>=_1n,s>>=_1n;return n&&(a=a.negate()),o&&(l=l.negate()),l=new JacobianPoint(mod(l.x*endo.beta),l.y,l.z),a.add(l)}precomputeWindow(e){const t=USE_ENDOMORPHISM?128/e+1:256/e+1,r=[];let n=this,i=n;for(let o=0;o>=u,r>a&&(r-=c,e+=_1n);const s=t,d=t+Math.abs(r)-1,p=h%2!=0,f=r<0;0===r?o=o.add(constTimeNegate(p,n[s])):i=i.add(constTimeNegate(f,n[d]))}return{p:i,f:o}}multiply(e,t){let r,n,i=normalizeScalar(e);if(USE_ENDOMORPHISM){const{k1neg:e,k1:o,k2neg:s,k2:a}=endo.splitScalar(i);let{p:l,f:c}=this.wNAF(o,t),{p:u,f:h}=this.wNAF(a,t);l=constTimeNegate(e,l),u=constTimeNegate(s,u),u=new JacobianPoint(mod(u.x*endo.beta),u.y,u.z),r=l.add(u),n=c.add(h)}else{const{p:e,f:o}=this.wNAF(i,t);r=e,n=o}return JacobianPoint.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,i=this.equals(JacobianPoint.ZERO);null==e&&(e=i?_8n:invert(n));const o=e,s=mod(o*o),a=mod(s*o),l=mod(t*s),c=mod(r*a),u=mod(n*o);if(i)return Point$1.ZERO;if(u!==_1n)throw new Error("invZ was invalid");return new Point$1(l,c)}}function constTimeNegate(e,t){const r=t.negate();return e?r:t}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n),JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);const pointPrecomputes=new WeakMap;let Point$1=class e{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,pointPrecomputes.delete(this)}hasEvenY(){return this.y%_2n===_0n}static fromCompressedHex(t){const r=32===t.length,n=bytesToNumber(r?t:t.subarray(1));if(!isValidFieldElement(n))throw new Error("Point is not on curve");let i=sqrtMod(weierstrass(n));const o=(i&_1n)===_1n;r?o&&(i=mod(-i)):!(1&~t[0])!==o&&(i=mod(-i));const s=new e(n,i);return s.assertValidity(),s}static fromUncompressedHex(t){const r=bytesToNumber(t.subarray(1,fieldLen+1)),n=bytesToNumber(t.subarray(fieldLen+1,2*fieldLen+1)),i=new e(r,n);return i.assertValidity(),i}static fromHex(e){const t=ensureBytes(e),r=t.length,n=t[0];if(r===fieldLen)return this.fromCompressedHex(t);if(r===compressedLen&&(2===n||3===n))return this.fromCompressedHex(t);if(r===uncompressedLen&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${r}`)}static fromPrivateKey(t){return e.BASE.multiply(normalizePrivateKey(t))}static fromSignature(t,r,n){const{r:i,s:o}=normalizeSignature(r);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");const s=truncateHash(ensureBytes(t)),{n:a}=CURVE,l=2===n||3===n?i+a:i,c=invert(l,a),u=mod(-s*c,a),h=mod(o*c,a),d=1&n?"03":"02",p=e.fromHex(d+numTo32bStr(l)),f=e.BASE.multiplyAndAddUnsafe(p,u,h);if(!f)throw new Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(e=!1){return hexToBytes(this.toHex(e))}toHex(e=!1){const t=numTo32bStr(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${numTo32bStr(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!isValidFieldElement(t)||!isValidFieldElement(r))throw new Error(e);const n=mod(r*r);if(mod(n-weierstrass(t))!==_0n)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new e(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(e){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return JacobianPoint.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(t,r,n){const i=JacobianPoint.fromAffine(this),o=r===_0n||r===_1n||this!==e.BASE?i.multiplyUnsafe(r):i.multiply(r),s=JacobianPoint.fromAffine(t).multiplyUnsafe(n),a=o.add(s);return a.equals(JacobianPoint.ZERO)?void 0:a.toAffine()}};function sliceDER(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function parseDERInt(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${bytesToHex(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:bytesToNumber(r),left:e.subarray(t+2)}}function parseDERSignature(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${bytesToHex(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=parseDERInt(e.subarray(2)),{data:n,left:i}=parseDERInt(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(i)}`);return{r:t,s:n}}Point$1.BASE=new Point$1(CURVE.Gx,CURVE.Gy),Point$1.ZERO=new Point$1(_0n,_0n);class Signature{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=isBytes(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?bytesToHex(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new Signature(hexToNumber(n.slice(0,64)),hexToNumber(n.slice(64,128)))}static fromDER(e){const t=isBytes(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=parseDERSignature(t?e:hexToBytes(e));return new Signature(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!isWithinCurveOrder(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=CURVE.n>>_1n;return this.s>e}normalizeS(){return this.hasHighS()?new Signature(this.r,mod(-this.s,CURVE.n)):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){const e=sliceDER(numberToHexUnpadded(this.s)),t=sliceDER(numberToHexUnpadded(this.r)),r=e.length/2,n=t.length/2,i=numberToHexUnpadded(r),o=numberToHexUnpadded(n);return`30${numberToHexUnpadded(n+r+4)}02${o}${t}02${i}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function isBytes(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function abytes(e){if(!isBytes(e))throw new Error("Uint8Array expected")}const hexes=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex(e){abytes(e);let t="";for(let r=0;r=asciis._0&&e<=asciis._9?e-asciis._0:e>=asciis.A&&e<=asciis.F?e-(asciis.A-10):e>=asciis.a&&e<=asciis.f?e-(asciis.a-10):void 0}function hexToBytes(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,o=0;i0)return BigInt(e);if("bigint"==typeof e&&isWithinCurveOrder(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(e,t=CURVE.P){const r=e%t;return r>=_0n?r:t+r}function pow2(e,t){const{P:r}=CURVE;let n=e;for(;t-- >_0n;)n*=n,n%=r;return n}function sqrtMod(e){const{P:t}=CURVE,r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),s=BigInt(44),a=BigInt(88),l=e*e*e%t,c=l*l*e%t,u=pow2(c,_3n)*c%t,h=pow2(u,_3n)*c%t,d=pow2(h,_2n)*l%t,p=pow2(d,n)*d%t,f=pow2(p,i)*p%t,g=pow2(f,s)*f%t,m=pow2(g,a)*g%t,y=pow2(m,s)*f%t,b=pow2(y,_3n)*c%t,v=pow2(b,o)*p%t,_=pow2(v,r)*l%t,E=pow2(_,_2n);if(E*E%t!==e)throw new Error("Cannot find square root");return E}function invert(e,t=CURVE.P){if(e===_0n||t<=_0n)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=mod(e,t),n=t,i=_0n,o=_1n;for(;r!==_0n;){const e=n%r,t=i-o*(n/r);n=r,r=e,i=o,o=t}if(n!==_1n)throw new Error("invert: does not exist");return mod(i,t)}function invertBatch(e,t=CURVE.P){const r=new Array(e.length),n=e.reduce((e,n,i)=>n===_0n?e:(r[i]=e,mod(e*n,t)),_1n),i=invert(n,t);return e.reduceRight((e,n,i)=>n===_0n?e:(r[i]=mod(e*r[i],t),mod(e*n,t)),i),r}function bits2int_2(e){const t=8*e.length-8*groupLen,r=bytesToNumber(e);return t>0?r>>BigInt(t):r}function truncateHash(e,t=!1){const r=bits2int_2(e);if(t)return r;const{n:n}=CURVE;return r>=n?r-n:r}function isWithinCurveOrder(e){return _0n0)t=BigInt(e);else if("string"==typeof e){if(e.length!==2*groupLen)throw new Error("Expected 32 bytes of private key");t=hexToNumber(e)}else{if(!isBytes(e))throw new TypeError("Expected valid private key");if(e.length!==groupLen)throw new Error("Expected 32 bytes of private key");t=bytesToNumber(e)}if(!isWithinCurveOrder(t))throw new Error("Expected private key: 0 < key < n");return t}function normalizeSignature(e){if(e instanceof Signature)return e.assertValidity(),e;try{return Signature.fromDER(e)}catch(error){return Signature.fromCompact(e)}}Point$1.BASE._setWindowSize(8);const sleep=e=>new Promise(t=>setTimeout(t,e));function xOnlyToXY(e){return Point$1.fromHex(e).toHex().substring(2)}const utf8Decoder=new TextDecoder("utf-8"),utf8Encoder=new TextEncoder;function base64Encode(e){return btoa(String.fromCharCode(...e))}function base64Decode(e){return new Uint8Array(atob(e).split("").map(e=>e.charCodeAt(0)))}class SerialPortSigner{log=logger$1.extend("SerialPortSigner");writer=null;pubkey;get isConnected(){return!!this.writer}verifyEvent=verifyEvent;nip04;constructor(){this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)}}lastCommand=null;async callMethodOnDevice(e,t,r={}){if(!SerialPortSigner.SUPPORTED)throw new Error("Serial devices are not supported");if(this.writer||await this.connectToDevice(r),this.lastCommand)throw new Error("Previous command to device still pending!");const n=createDefer();return this.lastCommand=n,this.sendCommand(e,t),setTimeout(()=>{n.reject(new Error("Device timeout")),this.lastCommand===n&&(this.lastCommand=null)},6e3),this.lastCommand}async connectToDevice({onConnect:e,onDisconnect:t,onError:r,onDone:n}){let i,o=await window.navigator.serial.requestPort();await o.open({baudRate:9600}),await sleep(1e3),(async()=>{for(;o&&o.readable;){const e=new window.TextDecoderStream;o.readable.pipeTo(e.writable),i=e.readable.getReader();const t=this.readFromSerialPort(i);try{for(;;){const{value:e,done:r}=await t("\n");if(e){const{method:t,data:r}=this.parseResponse(e);if("/ping"===t&&this.log("Pong"),-1===SerialPortSigner.PUBLIC_METHODS.indexOf(t))continue;this.log("Received: ",t,r),this.lastCommand&&(this.lastCommand.resolve(r),this.lastCommand=null)}if(r)return this.lastCommand=null,this.writer=null,void(n&&n())}}catch(error){if(error instanceof Error)throw this.writer=null,r&&r(error),this.lastCommand&&(this.lastCommand.reject(error),this.lastCommand=null),error}}})();const s=new window.TextEncoderStream;s.readable.pipeTo(o.writable),this.writer=s.writable.getWriter(),await this.sendCommand(SerialPortSigner.METHOD_PING),await this.sendCommand(SerialPortSigner.METHOD_PING,[window.location.host]),e&&e(),o.addEventListener("disconnect",()=>{this.log("Disconnected"),this.lastCommand=null,this.writer=null,t&&t()})}async sendCommand(e,t=[]){if(!this.writer)return;this.log("Send command",e,t);const r=[e].concat(t).join(" ");await this.writer.write(r+"\n")}readFromSerialPort(e){let t,r=[];return async(n="\n")=>{if(r.length)return{value:r.shift().trim(),done:!1};const i=[];for(t&&(i.push(t),t=void 0);;){const{value:o,done:s}=await e.read();if(o){const e=o.split(n);if(e.length>1)return i.push(e.shift()),t=e.pop(),r=e,{value:i.join("").trim(),done:!1};i.push(o)}if(s)return{value:i.join("").trim(),done:!0}}}}parseResponse(e){const t=e.split(" ")[0];return{method:t,data:e.substring(t.length).trim()}}async nip04Encrypt(e,t){const r=hexToBytes$2(await this.callMethodOnDevice(SerialPortSigner.METHOD_SHARED_SECRET,[xOnlyToXY(e)]));let n=Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(16))),i=utf8Encoder.encode(t),o=await crypto.subtle.importKey("raw",r,{name:"AES-CBC"},!1,["encrypt"]),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:n},o,i);return`${base64Encode(new Uint8Array(s))}?iv=${base64Encode(new Uint8Array(n.buffer))}`}async nip04Decrypt(e,t){let[r,n]=t.split("?iv=");const i=hexToBytes$2(await this.callMethodOnDevice(SerialPortSigner.METHOD_SHARED_SECRET,[xOnlyToXY(e)]));let o=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["decrypt"]),s=base64Decode(r),a=base64Decode(n),l=await crypto.subtle.decrypt({name:"AES-CBC",iv:a},o,s);return utf8Decoder.decode(l)}async getPublicKey(){const e=await this.callMethodOnDevice(SerialPortSigner.METHOD_PUBLIC_KEY,[]);return this.pubkey=e,e}async restore(e){await this.callMethodOnDevice(SerialPortSigner.METHOD_RESTORE,[bytesToHex$2(e)])}async signEvent(e){const t=e.pubkey||this.pubkey;if(!t)throw new Error("Unknown signer pubkey");const r={...e,id:getEventHash({...e,pubkey:t})},n=await this.callMethodOnDevice(SerialPortSigner.METHOD_SIGN_MESSAGE,[r.id]),i={...r,sig:n,pubkey:t};if(!this.verifyEvent(i))throw new Error("Invalid signature");return i}ping(){this.sendCommand(SerialPortSigner.METHOD_PING,[window.location.host])}static SUPPORTED="navigator"in globalThis&&!!navigator.serial;static METHOD_PING="/ping";static METHOD_LOG="/log";static METHOD_SIGN_MESSAGE="/sign-message";static METHOD_SHARED_SECRET="/shared-secret";static METHOD_PUBLIC_KEY="/public-key";static METHOD_RESTORE="/restore";static PUBLIC_METHODS=[SerialPortSigner.METHOD_PUBLIC_KEY,SerialPortSigner.METHOD_SIGN_MESSAGE,SerialPortSigner.METHOD_SHARED_SECRET,SerialPortSigner.METHOD_RESTORE]}function isMobile(){return"undefined"!=typeof navigator&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)}const amdModule16=Object.freeze(Object.defineProperty({__proto__:null,isMobile:isMobile},Symbol.toStringTag,{value:"Module"})),STORAGE_KEY="marco:nostr_pubkey",STORAGE_KEY_TYPE="marco:nostr_signer_type",STORAGE_KEY_CONNECT_LOCAL_KEY="marco:nostr_connect_local_key",STORAGE_KEY_CONNECT_REMOTE_PUBKEY="marco:nostr_connect_remote_pubkey",STORAGE_KEY_CONNECT_RELAY="marco:nostr_connect_relay",DEFAULT_CONNECT_RELAY="wss://relay.nsec.app";class NostrAuthService extends Service{static{decorateFieldV2(this.prototype,"nostrRelay",[service])}#q=void initializeDeferredDecorator(this,"nostrRelay");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"pubkey",[tracked],function(){return null})}#W=void initializeDeferredDecorator(this,"pubkey");static{decorateFieldV2(this.prototype,"signerType",[tracked],function(){return null})}#K=void initializeDeferredDecorator(this,"signerType");static{decorateFieldV2(this.prototype,"connectStatus",[tracked],function(){return null})}#Y=void initializeDeferredDecorator(this,"connectStatus");static{decorateFieldV2(this.prototype,"connectUri",[tracked],function(){return null})}#Z=void initializeDeferredDecorator(this,"connectUri");_signerInstance=null;constructor(){super(...arguments),"undefined"!=typeof localStorage&&(localStorage.debug="applesauce:*");const e=localStorage.getItem(STORAGE_KEY),t=localStorage.getItem(STORAGE_KEY_TYPE);e&&(this.pubkey=e,this.signerType=t||"extension",this._verifyPubkey())}async _verifyPubkey(){if("extension"===this.signerType){if(void 0===window.nostr)return void this.disconnect();try{const e=new ExtensionSigner,t=await e.getPublicKey();t!==this.pubkey&&(this.pubkey=t,localStorage.setItem(STORAGE_KEY,this.pubkey)),this.nostrData.loadProfile(this.pubkey)}catch(e){console.warn("Failed to verify extension nostr pubkey, logging out",e),this.disconnect()}}else if("connect"===this.signerType)try{await this._initConnectSigner()}catch(e){console.warn("Failed to verify connect nostr pubkey, logging out",e),this.disconnect()}}get isMobile(){return isMobile()}get isConnected(){return!!this.pubkey&&("extension"!==this.signerType||void 0!==window.nostr)}get signer(){return this._signerInstance?this._signerInstance:"extension"===this.signerType&&void 0!==window.nostr?new ExtensionSigner:(this.signerType,null)}async connectWithExtension(){if(void 0===window.nostr)throw new Error("No NIP-07 Nostr extension found (e.g., Alby, nos2x).");try{return this._signerInstance=new ExtensionSigner,this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="extension",localStorage.setItem(STORAGE_KEY,this.pubkey),localStorage.setItem(STORAGE_KEY_TYPE,"extension"),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(error){throw console.error("Failed to get public key from extension:",error),error}}_getLocalSigner(){let e,t=localStorage.getItem(STORAGE_KEY_CONNECT_LOCAL_KEY);return t?e=PrivateKeySigner.fromKey(t):(e=new PrivateKeySigner,t=Array.from(e.key).map(e=>e.toString(16).padStart(2,"0")).join(""),localStorage.setItem(STORAGE_KEY_CONNECT_LOCAL_KEY,t)),e}async connectWithApp(){this.connectStatus="waiting";try{const t=this._getLocalSigner(),r=DEFAULT_CONNECT_RELAY;localStorage.setItem(STORAGE_KEY_CONNECT_RELAY,r),this.nostrRelay.pool.relay(r).eoseTimeout=18e4,this._signerInstance=new NostrConnectSigner({pool:this.nostrRelay.pool,relays:[r],signer:t,onAuth:async e=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${e}`)&&window.open(e,"_blank")}}),this.connectUri=this._signerInstance.getNostrConnectURI({name:"Marco",url:window.location.origin,description:"An unhosted maps application.",icons:[]}),this.isMobile&&(console.debug("Mobile detected, triggering deep link intent."),window.location.href=this.connectUri),console.debug("Opening signer connection to relay..."),await this._signerInstance.open(),console.debug("Signer connection opened successfully."),console.debug("Waiting for remote signer to ack via relay...");try{await this._signerInstance.waitForSigner(),console.debug("Remote signer ack received!")}catch(e){throw console.error("Error while waiting for remote signer ack:",e),e}return this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="connect",this.connectStatus="connected",localStorage.setItem(STORAGE_KEY,this.pubkey),localStorage.setItem(STORAGE_KEY_TYPE,"connect"),localStorage.setItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY,this._signerInstance.remote),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(error){throw this.connectStatus=null,console.error("Failed to connect via Nostr Connect:",error),error}}async _initConnectSigner(){const e=localStorage.getItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY),t=localStorage.getItem(STORAGE_KEY_CONNECT_RELAY)||DEFAULT_CONNECT_RELAY;if(!e)throw new Error("Missing Nostr Connect remote pubkey.");const r=this._getLocalSigner();if(this.nostrRelay.pool.relay(t).eoseTimeout=18e4,this._signerInstance=new NostrConnectSigner({pool:this.nostrRelay.pool,relays:[t],signer:r,remote:e,onAuth:async e=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${e}`)&&window.open(e,"_blank")}}),await this._signerInstance.open(),await this._signerInstance.getPublicKey()!==this.pubkey)throw new Error("Remote signer pubkey mismatch");this.nostrData.loadProfile(this.pubkey)}async signEvent(e){if(!this.signer)throw new Error("Not connected or extension missing. Please connect Nostr again.");return await this.signer.signEvent(e)}async disconnect(){this.pubkey=null,this.nostrData?.loadProfile(null),this.signerType=null,this.connectStatus=null,this.connectUri=null,this._signerInstance&&"function"==typeof this._signerInstance.close&&await this._signerInstance.close(),this._signerInstance=null,localStorage.removeItem(STORAGE_KEY),localStorage.removeItem(STORAGE_KEY_TYPE),localStorage.removeItem(STORAGE_KEY_CONNECT_LOCAL_KEY),localStorage.removeItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY),localStorage.removeItem(STORAGE_KEY_CONNECT_RELAY)}}const amdModule7=Object.freeze(Object.defineProperty({__proto__:null,default:NostrAuthService},Symbol.toStringTag,{value:"Module"})),instanceOfAny=(e,t)=>t.some(t=>e instanceof t);let idbProxyableTypes,cursorAdvanceMethods;function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const transactionDoneMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;function promisifyRequest(e){const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(wrap$1(e.result)),n()},o=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",o)});return reverseTransformCache.set(t,e),t}function cacheDonePromiseForTransaction(e){if(transactionDoneMap.has(e))return;const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});transactionDoneMap.set(e,t)}let idbProxyTraps={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return transactionDoneMap.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap$1(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function replaceTraps(e){idbProxyTraps=e(idbProxyTraps)}function wrapFunction(e){return getCursorAdvanceMethods().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap$1(this.request)}:function(...t){return wrap$1(e.apply(unwrap(this),t))}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&cacheDonePromiseForTransaction(e),instanceOfAny(e,getIdbProxyableTypes())?new Proxy(e,idbProxyTraps):e)}function wrap$1(e){if(e instanceof IDBRequest)return promisifyRequest(e);if(transformCache.has(e))return transformCache.get(e);const t=transformCachableValue(e);return t!==e&&(transformCache.set(e,t),reverseTransformCache.set(t,e)),t}const unwrap=e=>reverseTransformCache.get(e);function openDB$1(e,t,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=wrap$1(s);return n&&s.addEventListener("upgradeneeded",e=>{n(wrap$1(s.result),e.oldVersion,e.newVersion,wrap$1(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(cachedMethods.get(t))return cachedMethods.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=writeMethods.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!readMethods.includes(r))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return n&&(s=s.index(t.shift())),(await Promise.all([s[r](...t),i&&o.done]))[0]};return cachedMethods.set(t,o),o}replaceTraps(e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)}));const advanceMethodProps=["continue","continuePrimaryKey","advance"],methodMap={},advanceResults=new WeakMap,ittrProxiedCursorToOriginalProxy=new WeakMap,cursorIteratorTraps={get(e,t){if(!advanceMethodProps.includes(t))return e[t];let r=methodMap[t];return r||(r=methodMap[t]=function(...e){advanceResults.set(this,ittrProxiedCursorToOriginalProxy.get(this)[t](...e))}),r}};async function*iterate$1(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,cursorIteratorTraps);for(ittrProxiedCursorToOriginalProxy.set(r,t),reverseTransformCache.set(r,unwrap(t));t;)yield r,t=await(advanceResults.get(r)||t.continue()),advanceResults.delete(r)}function isIteratorProp(e,t){return t===Symbol.asyncIterator&&instanceOfAny(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&instanceOfAny(e,[IDBIndex,IDBObjectStore])}function validateEvent(e){if("object"!=typeof e||null===e)return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!/^[a-f0-9]{64}$/.test(e.pubkey))return!1;if(!Array.isArray(e.tags))return!1;for(const t of e.tags){if(!Array.isArray(t))return!1;for(const e of t)if("string"!=typeof e)return!1}return!0}function isReplaceableKind(e){return 0===e||3===e||e>=1e4&&e<2e4}function isAddressableKind(e){return e>=3e4&&e<4e4}function isEphemeralKind(e){return e>=2e4&&e<3e4}replaceTraps(e=>({...e,get:(t,r,n)=>isIteratorProp(t,r)?iterate$1:e.get(t,r,n),has:(t,r)=>isIteratorProp(t,r)||e.has(t,r)}));const IndexableTagsSymbol=Symbol.for("indexable-tags");function getIndexableTags(e){let t=Reflect.get(e,IndexableTagsSymbol);if(!t){t=new Set;for(const r of e.tags)r.length>=2&&1===r[0].length&&t.add(r[0]+":"+r[1]);Reflect.set(e,IndexableTagsSymbol,t)}return t}function matchFilter(e,t){if(e.ids&&-1===e.ids.indexOf(t.id))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey))return!1;if(e.since&&t.created_ate.until)return!1;const r=getIndexableTags(t);for(const n in e)if("&"===n[0]){const t=n.slice(1),i=e[n];if(i&&i.length>0)for(const e of i)if(!r.has(t+":"+e))return!1}for(const n in e)if("#"===n[0]){const t=n.slice(1),i=e[n];if(i){const n=e[`&${t}`],o=n?i.filter(e=>!n.includes(e)):i;if(0===o.length)continue;if(!o.some(e=>r.has(t+":"+e)))return!1}}return!0}function matchFilters(e,t){for(let r=0;re.length>=2&&1===e[0].length&&INDEXABLE_TAGS.includes(e[0])).map(e=>e[0]+e[1])}function getEventUID(e){if(Reflect.has(e,EventUIDSymbol))return Reflect.get(e,EventUIDSymbol);let t;if(isReplaceableKind(e.kind)||isAddressableKind(e.kind)){const r=e.tags.find(e=>"d"===e[0])?.[1];t=e.kind+":"+e.pubkey+":"+(r??"")}else t=e.id;return Reflect.set(e,EventUIDSymbol,t),t}const NOSTR_IDB_NAME="nostr-idb",NOSTR_IDB_VERSION=3;async function openDB(e=NOSTR_IDB_NAME,t){return await openDB$1(e,NOSTR_IDB_VERSION,{...t,async upgrade(e,t,r,n,i){if(0===t){const t=e.createObjectStore("events");t.createIndex("id","event.id",{unique:!0}),t.createIndex("pubkey","event.pubkey"),t.createIndex("kind","event.kind"),t.createIndex("created_at","event.created_at"),t.createIndex("tags","tags",{multiEntry:!0}),e.createObjectStore("used",{keyPath:"uid"}).createIndex("date","date")}1===t&&(e.deleteObjectStore("events"),e.deleteObjectStore("used"),e.deleteObjectStore("seen")),t<=2&&await migrateReplaceableEventUIDs(n)}})}async function migrateReplaceableEventUIDs(e){const t=e.objectStore("events");let r=await t.openCursor();const n=[];for(;r;){const e=r.primaryKey,t=r.value,i=t.event;if(isReplaceableKind(i.kind)||isAddressableKind(i.kind)){const r=getEventUID(i);e!==r&&n.push({oldKey:e,newKey:r,value:t})}r=await r.continue()}for(const{oldKey:i,newKey:o,value:s}of n)await t.delete(i),await t.put(s,o)}function sortByDate(e,t){return t.created_at-e.created_at}function queryForPubkeys(e,t=[],r){const n=[],i=new Set;if(r)for(const l of t){const e=r.getPubkeyIndex(l);if(e){for(const t of e)i.add(t);n.push(l)}}if(n.length===t.length)return Promise.resolve(i);const o=e.transaction("events","readonly"),s=o.objectStore("events").index("pubkey"),a=t.filter(e=>!n.includes(e)).map(e=>s.getAllKeys(e).then(t=>((e,t)=>{for(const r of t)i.add(r);r&&r.setPubkeyIndex(e,new Set(t))})(e,t)));return o.commit(),Promise.all(a).then(()=>i)}function queryForTag(e,t,r,n){const i=[],o=new Set;if(n)for(const c of r){const e=n.getTagIndex(t+c);if(e){for(const t of e)o.add(t);i.push(c)}}if(i.length===r.length)return Promise.resolve(o);const s=e.transaction("events","readonly"),a=s.objectStore("events").index("tags"),l=r.map(e=>a.getAllKeys(t+e).then(r=>((e,r)=>{for(const t of r)o.add(t);n&&n.setTagIndex(t+e,new Set(r))})(e,r)));return s.commit(),Promise.all(l).then(()=>o)}function queryForTagAnd(e,t,r,n){if(0===r.length)return Promise.resolve(new Set);if(1===r.length)return queryForTag(e,t,r,n);const i=[],o=[];if(n)for(const c of r){const e=n.getTagIndex(t+c);e&&(o.push(e),i.push(c))}if(i.length===r.length)return Promise.resolve(intersectSets(o));const s=e.transaction("events","readonly"),a=s.objectStore("events").index("tags"),l=r.filter(e=>!i.includes(e)).map(e=>a.getAllKeys(t+e).then(r=>((e,r)=>{const i=new Set(r);o.push(i),n&&n.setTagIndex(t+e,i)})(e,r)));return s.commit(),Promise.all(l).then(()=>intersectSets(o))}function intersectSets(e){if(0===e.length)return new Set;const t=e.slice().sort((e,t)=>e.size-t.size);let r=t[0];for(let n=1;n!n.includes(e)).map(e=>s.getAllKeys(e).then(t=>((e,t)=>{for(const r of t)i.add(r);r&&r.setKindIndex(e,new Set(t))})(e,t)));return o.commit(),Promise.all(a).then(()=>i)}async function queryForTime(e,t,r){let n;if(void 0!==t&&void 0!==r)n=IDBKeyRange.bound(t,r);else if(void 0!==t)n=IDBKeyRange.lowerBound(t);else{if(void 0===r)throw new Error("Missing since or until");n=IDBKeyRange.upperBound(r)}return(await e.getAllKeysFromIndex("events","created_at",n)).reverse()}async function getIdsForFilter(e,t,r){if(t.search)return new Set;if(t.ids)return new Set(t.ids);let n=null;const i=e=>{const t=e instanceof Set?e:new Set(e);if(n)for(const r of n)t.has(r)||n.delete(r);else n=t;return n};let o=null;void 0!==t.since&&(o=await queryForTime(e,t.since,t.until),i(o));for(const s of INDEXABLE_TAGS){const n=t[`&${s}`],o=t[`#${s}`];if(n?.length&&i(await queryForTagAnd(e,s,n,r)),o?.length){const t=n?.length?o.filter(e=>!n.includes(e)):o;t.length>0&&i(await queryForTag(e,s,t,r))}}if(t.authors&&i(await queryForPubkeys(e,t.authors,r)),t.kinds&&i(await queryForKinds(e,t.kinds,r)),void 0===t.since&&void 0!==t.until&&(o=await queryForTime(e,t.since,t.until),i(o)),t.limit&&o){const e=new Set;for(const r of o){if(e.size>=t.limit)break;n.has(r)&&e.add(r)}return e}if(null===n)throw new Error("Empty filter");return n}async function getIdsForFilters(e,t,r){if(0===t.length)throw new Error("No Filters");let n=new Set;for(const i of t){const t=await getIdsForFilter(e,i,r);for(const e of t)n.add(e)}return n}async function loadEventsByUID(e,t,r,n){const i=[];let o=[];if(n)for(const d of t){const e=n.get(d);e?i.push(e):o.push(d)}else o=t;const s=e.transaction("events","readonly"),a=s.objectStore("events"),l=e=>e&&i.push(e.event),c=Array.from(o).map(e=>a.get(e).then(l));s.commit();const u=await Promise.all(c).then(()=>i.sort(sortByDate));let h=1/0;for(const d of r)d.limit&&d.limith&&(u.length=h),u}async function getEventsForFilters(e,t,r,n){const i=await getIdsForFilters(e,t,r);return await loadEventsByUID(e,Array.from(i),t,n)}async function countEventsForFilters(e,t,r){return(await getIdsForFilters(e,t,r)).size}const queryFilter=Object.freeze(Object.defineProperty({__proto__:null,countEventsForFilters:countEventsForFilters,getEventsForFilters:getEventsForFilters,getIdsForFilter:getIdsForFilter,getIdsForFilters:getIdsForFilters,queryForKinds:queryForKinds,queryForPubkeys:queryForPubkeys,queryForTag:queryForTag,queryForTagAnd:queryForTagAnd,queryForTime:queryForTime},Symbol.toStringTag,{value:"Module"}));function countEvents(e){return e.transaction("events","readonly").store.count()}async function addEvents(e,t){const r=(t=t.filter(e=>validateEvent(e))).filter(e=>isReplaceableKind(e.kind)||isAddressableKind(e.kind)),n={};if(r.length>0){const t=e.transaction("events","readonly"),i=r.map(e=>{const r=getEventUID(e);return t.store.get(r).then(e=>e&&(n[r]=e.event.created_at))});t.commit(),await Promise.all(i)}const i=e.transaction("events","readwrite");for(const o of t){const e=getEventUID(o);(!n[e]||o.created_at>n[e])&&i.objectStore("events").put({event:o,tags:getEventTags(o)},e)}await i.commit()}async function updateUsed(e,t){const r=e.transaction("used","readwrite"),n=Math.floor((new Date).valueOf()/1e3);for(const i of t)r.objectStore("used").put({uid:i,date:n});await r.commit()}const logger=debug("nostr-idb"),log$3=logger.extend("prune");async function pruneLastUsed(e,t){const r=await countEvents(e);if(r<=t)return;const n=r-t;if(n<=0)return;log$3(`Pruning database to ${t}`);const i=(await e.getAll("used")).sort((e,t)=>e.date-t.date),o=[];let s=n;for(const u of i){if(s<=0)break;const e=u.uid;o.push(e),s--}if(0===o.length)return;const a=e.transaction("events","readwrite"),l=e.transaction("used","readwrite"),c=[];for(const u of o)c.push(a.store.delete(u)),c.push(l.store.delete(u));a.commit(),l.commit(),await Promise.all(c),log$3(`Removed ${o.length} old events`)}async function deleteEvent(e,t,r){const n=e.transaction("events","readwrite"),i=n.objectStore("events"),o=await i.get(t);if(!o)return await n.commit(),!1;if(await i.delete(t),await n.commit(),r){const e=o.event;r.removeEvent(e)}return!0}async function deleteReplaceable(e,t,r,n,i){if(!isReplaceableKind(r)&&!isAddressableKind(r))throw new Error(`Kind ${r} is not replaceable`);const o=`${r}:${t}:${n??""}`;return await deleteEvent(e,o,i)}async function deleteByFilters(e,t,r){const n=await getIdsForFilters(e,t,r);return await deleteEventsByIds(e,Array.from(n),r)}async function deleteEventsByIds(e,t,r){if(0===t.length)return 0;const n=e.transaction("events","readwrite"),i=n.objectStore("events");let o=0;const s=[];for(const a of t){const e=await i.get(a);e&&(s.push(e.event),await i.delete(a),o++)}if(await n.commit(),r&&s.length>0)for(const a of s)r.removeEvent(a);return o}async function deleteAllEvents(e,t){const r=e.transaction("events","readwrite");await r.objectStore("events").clear(),await r.commit(),t&&t.clear()}const log$2=logger.extend("WriteQueue");class WriteQueue{db;queuedIds=new Set;eventQueue=[];lastUsedQueue=new Set;processEvents=null;constructor(e){this.db=e}addEvent(e){this.queuedIds.has(e.id)||(this.eventQueue.push(e),this.queuedIds.add(e.id),this.touch(e))}addEvents(e){const t=e.filter(e=>!this.queuedIds.has(e.id));0!==t.length&&(this.eventQueue.push(...t),this.touch(t))}touch(e){if(Array.isArray(e))for(const t of e)this.lastUsedQueue.add(getEventUID(t));else this.lastUsedQueue.add(getEventUID(e))}matchPending(e){return this.eventQueue.filter(t=>matchFilters(e,t))}async flush(e=1e3){if(this.eventQueue.length>0){let t=[];for(let r=0;r0&&log$2(`${this.eventQueue.length} left`)}this.lastUsedQueue.size>0&&(await updateUsed(this.db,this.lastUsedQueue),this.lastUsedQueue.clear())}clear(){this.eventQueue=[]}}const log$1=logger.extend("cache:indexes");class Index extends Set{type;key;constructor(e,t,r){super(e),this.type=t,this.key=r}}class IndexCache{kinds=new Map;pubkeys=new Map;tags=new Map;get count(){return this.kinds.size+this.pubkeys.size+this.tags.size}max=1e3;lastUsed=[];useIndex(e){const t=this.lastUsed.indexOf(e);-1!==t&&this.lastUsed.splice(t,t+1),this.lastUsed.push(e)}getKindIndex(e){const t=this.kinds.get(e);return t&&this.useIndex(t),t}setKindIndex(e,t){const r=new Index(t,"kind",e);this.kinds.set(e,r),this.useIndex(r),this.pruneIndexes()}getPubkeyIndex(e){const t=this.pubkeys.get(e);return t&&this.useIndex(t),t}setPubkeyIndex(e,t){const r=new Index(t,"pubkey",e);this.pubkeys.set(e,r),this.useIndex(r),this.pruneIndexes()}getTagIndex(e){const t=this.tags.get(e);return t&&this.useIndex(t),t}setTagIndex(e,t){const r=new Index(t,"tag",e);this.tags.set(e,r),this.useIndex(r),this.pruneIndexes()}addEventToIndexes(e){this.getKindIndex(e.kind)?.add(e.id),this.getPubkeyIndex(e.pubkey)?.add(e.id);const t=getEventTags(e);for(const r of t)this.getTagIndex(r)?.add(e.id)}removeEvent(e){this.getKindIndex(e.kind)?.delete(e.id),this.getPubkeyIndex(e.pubkey)?.delete(e.id);const t=getEventTags(e);for(const r of t)this.getTagIndex(r)?.delete(e.id)}clear(){this.kinds.clear(),this.pubkeys.clear(),this.tags.clear(),this.lastUsed=[]}pruneIndexes(){for(;this.lastUsed.length>0&&this.lastUsed.length>this.max;){const e=this.lastUsed.shift();if(!e)return;switch(log$1(`Forgetting ${e.type}:${e.key}`),e.type){case"kind":this.kinds.delete(e.key);break;case"pubkey":this.pubkeys.delete(e.key);break;case"tag":this.tags.delete(e.key)}}}}const scriptRel="modulepreload",assetsURL=function(e){return"/"+e},seen={},__vitePreload=function(e,t){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const e=document.querySelector("meta[property=csp-nonce]"),i=e?.nonce||e?.getAttribute("nonce");n=t.map(e=>{if((e=assetsURL(e))in seen)return;seen[e]=!0;const t=e.endsWith(".css"),r=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${r}`))return;const n=document.createElement("link");return n.rel=t?"stylesheet":scriptRel,t||(n.as="script"),n.crossOrigin="",n.href=e,i&&n.setAttribute("nonce",i),document.head.appendChild(n),t?new Promise((t,r)=>{n.addEventListener("load",t),n.addEventListener("error",()=>r(new Error(`Unable to preload CSS for ${e}`)))}):void 0}),r=Promise.all(n.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}var n;function i(e){const t=new Event("vite:preloadError",{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(const e of t||[])"rejected"===e.status&&i(e.reason);return e().catch(i)})};let nanoid=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),"");const defaultOptions={batchWrite:1e3,writeInterval:100,cacheIndexes:1e3,pruneInterval:6e4,maxEvents:1e4},log=logger.extend("nostridb");class NostrIDB{options;running=!1;writeInterval;pruneInterval;eventMap=new Map;writeQueue=null;indexCache;db=null;baseEoseTimeout=4400;subscriptions=new Map;constructor(e,t={}){this.options={...defaultOptions,...t},e&&(this.db=e,this.writeQueue=new WriteQueue(e)),this.indexCache=new IndexCache,this.indexCache.max=this.options.cacheIndexes,this.start()}async getDb(){return this.db||(this.db=await openDB()),this.db}async getWriteQueue(){if(this.writeQueue)return this.writeQueue;const e=await this.getDb();return this.writeQueue=new WriteQueue(e),this.writeQueue}async flush(){const e=await this.getWriteQueue();await e.flush(),this.writeInterval=setTimeout(this.flush.bind(this),this.options.writeInterval)}async start(){if(this.running)return;log("Starting"),this.running=!0;const e=await this.getDb();await this.flush(),this.pruneInterval=setInterval(()=>{pruneLastUsed(e,this.options.maxEvents)},this.options.pruneInterval)}async stop(){this.running&&(this.writeInterval&&(clearTimeout(this.writeInterval),this.writeInterval=void 0),this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0),this.running=!1,log("Stopped"))}async add(e){isEphemeralKind(e.kind)||((await this.getWriteQueue()).addEvent(e),this.indexCache.addEventToIndexes(e));const t=getEventUID(e);if(!this.eventMap.has(t)){isEphemeralKind(e.kind)||this.eventMap.set(t,e);for(const[t,r]of this.subscriptions)r.event&&matchFilters(r.filters,e)&&r.event(e)}return!0}async event(e){const t=await this.getDb(),r=await t.get("events",e);return r?.event}async replaceable(e,t,r){return this.event([e,t,r??""].join(":"))}async count(e){const t=Array.isArray(e)?e:[e],r=await this.getDb();return await countEventsForFilters(r,t)}async query(e){const t=Array.isArray(e)?e:[e],r=await this.getDb(),n=(await this.getWriteQueue()).matchPending(t),i=await getEventsForFilters(r,t,this.indexCache,this.eventMap);this.addToEventMaps(i);const o=new Set(n.map(e=>e.id));return n.length>0?[...i.filter(e=>!o.has(e.id)),...n].sort(sortByDate):i}async*subscribe(e){const t=Array.isArray(e)?e:[e],r=[],n=new Set;let i=null,o=!1;const s=this.subscribeInternal(t,{event:e=>{if(!n.has(e.id)&&(n.add(e.id),r.push(e),i)){const e=i;i=null,e()}},complete:()=>{if(o=!0,i){const e=i;i=null,e()}}});try{for(;;){for(;r.length>0;)yield r.shift();if(o)break;await new Promise(e=>{i=e})}}finally{s.close()}}async supports(){return[]}async deleteEvent(e){const t=await this.getDb(),r=await deleteEvent(t,e,this.indexCache);return this.eventMap.delete(e),r}async deleteReplaceable(e,t,r){const n=await this.getDb(),i=await deleteReplaceable(n,e,t,r,this.indexCache);if(i){const n=`${t}:${e}:${r??""}`;this.eventMap.delete(n)}return i}async deleteByFilters(e){const t=Array.isArray(e)?e:[e],r=await this.getDb(),n=await this.getEventIdsForFilters(t),i=await deleteByFilters(r,t,this.indexCache);if(i>0)for(const o of n)this.eventMap.delete(o);return i}async deleteAllEvents(){const e=await this.getDb();await deleteAllEvents(e,this.indexCache),this.eventMap.clear()}async getEventIdsForFilters(e){const t=await this.getDb(),{getIdsForFilters:r}=await __vitePreload(async()=>{const{getIdsForFilters:e}=await Promise.resolve().then(()=>queryFilter);return{getIdsForFilters:e}},void 0),n=await r(t,e,this.indexCache);return Array.from(n)}addToEventMaps(e){for(const t of e)this.eventMap.set(getEventUID(t),t)}subscribeInternal(e,t){const r=nanoid(),n={id:r,filters:e,closed:!1,close:()=>this.unsubscribe(r),...t};return this.subscriptions.set(r,n),this.executeSubscription(n),n}async executeSubscription(e){const t=(new Date).valueOf();log(`Running ${e.id}`,e.filters);const r=(await this.getWriteQueue()).matchPending(e.filters);return new Promise(async n=>{const i=await this.getDb(),o=setTimeout(()=>{e.eose&&!e.closed&&e.eose(),n()},this.baseEoseTimeout);getEventsForFilters(i,e.filters,this.indexCache,this.eventMap).then(i=>{if(clearTimeout(o),this.addToEventMaps(i),e.event&&!e.closed){const n=new Set(r.map(e=>e.id)),o=r.length>0?[...i.filter(e=>!n.has(e.id)),...r].sort(sortByDate):i;for(const t of o)try{e.event(t)}catch(error){log("event handler failed with error",error)}const s=(new Date).valueOf()-t;log(`Finished ${e.id} took ${s}ms and got ${o.length} events`)}e.eose&&!e.closed&&e.eose(),n()})})}unsubscribe(e){const t=this.subscriptions.get(e);t&&(log(`Closing ${e}`),t.closed=!0,t.complete?.(),this.subscriptions.delete(e))}}function normalizeRelayUrl(e){if(!e)return"";let t=e.trim().toLowerCase();if(!t)return"";for(t.startsWith("ws://")||t.startsWith("wss://")||(t="wss://"+t);t.endsWith("/");)t=t.slice(0,-1);return t}function parsePlacePhotos(e){if(!e||0===e.length)return[];const t=[...e].sort((e,t)=>e.created_at-t.created_at),r=[];for(const i of t){const e=i.tags.filter(e=>"imeta"===e[0]);for(const t of e){let e=null,n=null,o=null,s=!1,a=16/9;for(const r of t.slice(1))if(r.startsWith("url "))e=r.substring(4);else if(r.startsWith("thumb "))n=r.substring(6);else if(r.startsWith("blurhash "))o=r.substring(9);else if(r.startsWith("dim ")){const e=r.substring(4),[t,n]=e.split("x").map(Number);t&&n&&(a=t/n,t>n&&(s=!0))}e&&r.push({eventId:i.id,pubkey:i.pubkey,createdAt:i.created_at,url:e,thumbUrl:n,blurhash:o,isLandscape:s,aspectRatio:a})}}if(0===r.length)return[];const n=r.findIndex(e=>e.isLandscape);if(n>0){const[e]=r.splice(n,1);r.unshift(e)}return r}const amdModule21=Object.freeze(Object.defineProperty({__proto__:null,normalizeRelayUrl:normalizeRelayUrl,parsePlacePhotos:parsePlacePhotos},Symbol.toStringTag,{value:"Module"})),base32="0123456789bcdefghjkmnpqrstuvwxyz";class Geohash{static encode(e,t,r){if(void 0===r){for(let r=1;r<=12;r++){const n=Geohash.encode(e,t,r),i=Geohash.decode(n);if(i.lat==e&&i.lon==t)return n}r=12}if(e=Number(e),t=Number(t),r=Number(r),isNaN(e)||isNaN(t)||isNaN(r))throw new Error("Invalid geohash");let n=0,i=0,o=!0,s="",a=-90,l=90,c=-180,u=180;for(;s.length=e?(n=2*n+1,c=e):(n*=2,u=e)}else{const t=(a+l)/2;e>=t?(n=2*n+1,a=t):(n*=2,l=t)}o=!o,5==++i&&(s+=base32.charAt(n),i=0,n=0)}return s}static decode(e){const t=Geohash.bounds(e),r=t.sw.lat,n=t.sw.lon,i=t.ne.lat,o=t.ne.lon;let s=(r+i)/2,a=(n+o)/2;return s=s.toFixed(Math.floor(2-Math.log(i-r)/Math.LN10)),a=a.toFixed(Math.floor(2-Math.log(o-n)/Math.LN10)),{lat:Number(s),lon:Number(a)}}static bounds(e){if(0==e.length)throw new Error("Invalid geohash");e=e.toLowerCase();let t=!0,r=-90,n=90,i=-180,o=180;for(let s=0;s=0;e--){const s=l>>e&1;if(t){const e=(i+o)/2;1==s?i=e:o=e}else{const e=(r+n)/2;1==s?r=e:n=e}t=!t}}return{sw:{lat:r,lon:i},ne:{lat:n,lon:o}}}static adjacent(e,t){if(e=e.toLowerCase(),t=t.toLowerCase(),0==e.length)throw new Error("Invalid geohash");if(-1=="nsew".indexOf(t))throw new Error("Invalid direction");const r=e.slice(-1);let n=e.slice(0,-1);const i=e.length%2;return-1!={n:["prxz","bcfguvyz"],s:["028b","0145hjnp"],e:["bcfguvyz","prxz"],w:["0145hjnp","028b"]}[t][i].indexOf(r)&&""!=n&&(n=Geohash.adjacent(n,t)),n+base32.charAt({n:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],s:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],e:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],w:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]}[t][i].indexOf(r))}static neighbours(e){return{n:Geohash.adjacent(e,"n"),ne:Geohash.adjacent(Geohash.adjacent(e,"n"),"e"),e:Geohash.adjacent(e,"e"),se:Geohash.adjacent(Geohash.adjacent(e,"s"),"e"),s:Geohash.adjacent(e,"s"),sw:Geohash.adjacent(Geohash.adjacent(e,"s"),"w"),w:Geohash.adjacent(e,"w"),nw:Geohash.adjacent(Geohash.adjacent(e,"n"),"w")}}}function getGeohashPrefixesInBbox(e){const{minLat:t,minLon:r,maxLat:n,maxLon:i}=e,o=new Set;if(Math.abs(n-t)>20||Math.abs(i-r)>20)return console.warn("BBox too large for 4-char geohash scanning, aborting fine scan."),[];for(let a=t;a<=n+.1;a+=.1)for(let e=r;e<=i+.1;e+=.1){const t=Math.min(a,n),r=Math.min(e,i);try{const e=Geohash.encode(t,r,4);o.add(e)}catch(s){}}try{o.add(Geohash.encode(t,r,4))}catch(s){}try{o.add(Geohash.encode(n,i,4))}catch(s){}try{o.add(Geohash.encode(t,i,4))}catch(s){}try{o.add(Geohash.encode(n,r,4))}catch(s){}return Array.from(o)}const amdModule19=Object.freeze(Object.defineProperty({__proto__:null,getGeohashPrefixesInBbox:getGeohashPrefixesInBbox},Symbol.toStringTag,{value:"Module"})),DIRECTORY_RELAYS=["wss://purplepag.es","wss://relay.damus.io","wss://nos.lol"],DEFAULT_READ_RELAYS=["wss://nostr.kosmos.org"],DEFAULT_WRITE_RELAYS=[];class NostrDataService extends Service{static{decorateFieldV2(this.prototype,"nostrRelay",[service])}#q=void initializeDeferredDecorator(this,"nostrRelay");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");store=new EventStore;static{decorateFieldV2(this.prototype,"profile",[tracked],function(){return null})}#X=void initializeDeferredDecorator(this,"profile");static{decorateFieldV2(this.prototype,"mailboxes",[tracked],function(){return null})}#J=void initializeDeferredDecorator(this,"mailboxes");static{decorateFieldV2(this.prototype,"blossomServers",[tracked],function(){return[]})}#Q=void initializeDeferredDecorator(this,"blossomServers");static{decorateFieldV2(this.prototype,"placePhotos",[tracked],function(){return[]})}#ee=void initializeDeferredDecorator(this,"placePhotos");_profileSub=null;_mailboxesSub=null;_blossomSub=null;_photosSub=null;_requestSub=null;_cachePromise=null;loadedGeohashPrefixes=new Set;constructor(){super(...arguments),this._cachePromise=openDB("applesauce-events").then(async e=>{this.cache=new NostrIDB(e,{cacheIndexes:1e3,maxEvents:1e4}),await this.cache.start(),this._stopPersisting=persistEventsToCache(this.store,async e=>{const t=e.filter(e=>0===e.kind||10002===e.kind||10063===e.kind||360===e.kind);t.length>0&&await Promise.all(t.map(e=>this.cache.add(e)))},{batchTime:1e3,maxBatchSize:100})}),this.nostrRelay.pool.relays$.subscribe(()=>{})}get defaultReadRelays(){const e=(this.mailboxes?.inboxes||[]).map(normalizeRelayUrl).filter(Boolean),t=DEFAULT_READ_RELAYS.map(normalizeRelayUrl).filter(Boolean);return Array.from(new Set([...t,...e]))}get defaultWriteRelays(){const e=(this.mailboxes?.outboxes||[]).map(normalizeRelayUrl).filter(Boolean),t=DEFAULT_WRITE_RELAYS.map(normalizeRelayUrl).filter(Boolean);return Array.from(new Set([...t,...e]))}get activeReadRelays(){return this.settings.nostrReadRelays?Array.from(new Set(this.settings.nostrReadRelays.map(normalizeRelayUrl).filter(Boolean))):this.defaultReadRelays}get activeWriteRelays(){return this.settings.nostrWriteRelays?Array.from(new Set(this.settings.nostrWriteRelays.map(normalizeRelayUrl).filter(Boolean))):this.defaultWriteRelays}async loadPlacesInBounds(e){const t=getGeohashPrefixesInBbox(e).filter(e=>!this.loadedGeohashPrefixes.has(e));if(0!==t.length){console.debug("[nostr-data] Loading place photos for prefixes:",t);try{await this._cachePromise;const e=await this.cache.query([{kinds:[360],"#g":t}]);if(e&&e.length>0)for(const t of e)this.store.add(t)}catch(r){console.warn("[nostr-data] Failed to read photos from local Nostr IDB cache",r)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#g":t}]).subscribe({next:e=>{this.store.add(e)},error:e=>{console.error("[nostr-data] Error fetching place photos by geohash:",e)}});for(const e of t)this.loadedGeohashPrefixes.add(e)}}async loadPhotosForPlace(e){if(this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null),this.placePhotos=[],!e||!e.osmId||!e.osmType)return;const t=`osm:${e.osmType}:${e.osmId}`;this._photosSub=this.store.timeline([{kinds:[360],"#i":[t]}]).subscribe(e=>{this.placePhotos=e});try{await this._cachePromise;const e=await this.cache.query([{kinds:[360],"#i":[t]}]);if(e&&e.length>0)for(const t of e)this.store.add(t)}catch(r){console.warn("[nostr-data] Failed to read photos for place from local Nostr IDB cache",r)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#i":[t]}]).subscribe({next:e=>{this.store.add(e)},error:e=>{console.error("[nostr-data] Error fetching place photos for place:",e)}})}async loadProfile(e){if(!e)return;this.profile=null,this.mailboxes=null,this.blossomServers=[],this._cleanupSubscriptions(),this._profileSub=this.store.model(ProfileModel,e).subscribe(e=>{this.profile=e}),this._mailboxesSub=this.store.model(MailboxesModel,e).subscribe(e=>{this.mailboxes=e}),this._blossomSub=this.store.replaceable(10063,e).subscribe(e=>{e&&e.tags?this.blossomServers=e.tags.filter(e=>"server"===e[0]&&e[1]).map(e=>e[1]):this.blossomServers=[]});try{await this._cachePromise;const t=await this.cache.query([{authors:[e],kinds:[0,10002,10063]}]);if(t&&t.length>0)for(const e of t)this.store.add(e)}catch(r){console.warn("Failed to read from local Nostr IDB cache",r)}const t=Array.from(new Set([...DIRECTORY_RELAYS,...this.activeWriteRelays]));this._requestSub=this.nostrRelay.pool.request(t,[{authors:[e],kinds:[0,10002,10063]}]).subscribe({next:e=>{this.store.add(e)},error:e=>{console.error("Error fetching profile events:",e)}})}get userDisplayName(){if(this.profile){if(this.profile.nip05)return this.profile.nip05;if(this.profile.displayName||this.profile.display_name)return this.profile.displayName||this.profile.display_name;if(this.profile.name)return this.profile.name}if(this.nostrAuth.pubkey)try{const e=npubEncode(this.nostrAuth.pubkey);return`${e.slice(0,9)}...${e.slice(-4)}`}catch{return this.nostrAuth.pubkey}return"Not connected"}async clearCache(){await this._cachePromise,this.cache&&await this.cache.deleteAllEvents()}_cleanupSubscriptions(){this._requestSub&&(this._requestSub.unsubscribe(),this._requestSub=null),this._profileSub&&(this._profileSub.unsubscribe(),this._profileSub=null),this._mailboxesSub&&(this._mailboxesSub.unsubscribe(),this._mailboxesSub=null),this._blossomSub&&(this._blossomSub.unsubscribe(),this._blossomSub=null),this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null)}willDestroy(){super.willDestroy(...arguments),this._cleanupSubscriptions(),this._stopPersisting&&this._stopPersisting(),this.cache&&this.cache.stop()}}const amdModule8=Object.freeze(Object.defineProperty({__proto__:null,default:NostrDataService},Symbol.toStringTag,{value:"Module"}));function completeOnEose(e){return takeWhile(e=>"EOSE"!==e,e)}function onlyEvents(){return e=>e.pipe(filter$1(e=>"EOSE"!==e))}function reverseSwitchMap(e){return operate((t,r)=>{let n=null,i=0,o=!1;const s=()=>{o&&!n&&r.complete()};t.subscribe(createOperatorSubscriber(r,t=>{const o=i++,a=n,l=n=createOperatorSubscriber(r,e=>r.next(e),()=>{n!==l&&null!==n||(n=null,s())});from(e(t,o)).subscribe(n),a?.unsubscribe()},()=>{o=!0,s()}))})}function errorToPublishResponse(e){return catchError(t=>of({ok:!1,from:e.url,message:t?.message||"Unknown error"}))}class RelayGroup{relays$=new BehaviorSubject([]);status$;get relays(){if(this.relays$ instanceof BehaviorSubject)return this.relays$.value;throw new Error("This group was created with an observable, relays are not available")}constructor(e){this.relays$=Array.isArray(e)?new BehaviorSubject(e):e,this.status$=this.relays$.pipe(switchMap(e=>0===e.length?of({}):merge$1(...e.map(e=>e.status$)).pipe(scan((e,t)=>({...e,[t.url]:t}),{}),startWith({}))),shareReplay(1))}get controlled(){return this.relays$ instanceof BehaviorSubject==0}has(e){if(this.controlled)throw new Error("This group was created with an observable, relays are not available");return"string"==typeof e?this.relays.some(t=>t.url===e):this.relays.includes(e)}add(e){this.has(e)||this.relays$.next([...this.relays,e])}remove(e){this.has(e)&&this.relays$.next(this.relays.filter(t=>t!==e))}internalSubscription(e,t=identity$1){const r=new WeakMap,n=this.relays$.pipe(reverseSwitchMap(t=>{const n=[];for(const i of t){if(r.has(i)){n.push(r.get(i));continue}const t=e(i).pipe(catchError(()=>of("EOSE")),map$1(e=>[i,e]));n.push(t),r.set(i,t)}return merge$1(...n)}),share());return merge$1(n.pipe(map$1(([e,t])=>t),onlyEvents(),t),this.relays$.pipe(switchMap(e=>n.pipe(filter$1(([e,t])=>"EOSE"===t),scan((e,[t])=>[...e,t],[]),takeWhile(t=>e.some(e=>!t.includes(e))),ignoreElements(),endWith("EOSE"))))).pipe(share())}internalPublish(e){const t=new WeakMap;return this.relays$.pipe(take(1),switchMap(r=>{const n=[];for(const i of r){if(t.has(i)){n.push(t.get(i));continue}const r=e(i).pipe(errorToPublishResponse(i));n.push(r),t.set(i,r)}return merge$1(...n)}))}req(e,t=nanoid$1(),r){return this.internalSubscription(r=>r.req(e,t),r?.eventStore?filterDuplicateEvents(r?.eventStore):identity$1)}event(e){return this.internalPublish(t=>t.event(e)).pipe(share())}async negentropy(e,t,r,n){const i=(await Promise.all(this.relays.map(async e=>[e,await e.getSupported()]))).filter(([e,t])=>t?.includes(77)).map(([e])=>e);if(0===i.length)throw new Error("No relays support NIP-77 negentropy sync");if(!n?.parallel)throw new Error("Negentropy sync must be parallel (for now)");return await Promise.allSettled(i.map(i=>i.negentropy(e,t,r,n))),!0}publish(e,t){return lastValueFrom(this.internalPublish(r=>from(r.publish(e,t))).pipe(toArray(),defaultIfEmpty([])))}request(e,t){return this.internalSubscription(r=>r.request(e,t).pipe(endWith("EOSE")),null==t?.eventStore?identity$1:filterDuplicateEvents(t?.eventStore??new EventMemory)).pipe(completeOnEose())}subscription(e,t){return this.internalSubscription(r=>r.subscription(e,t),null==t?.eventStore?identity$1:filterDuplicateEvents(t?.eventStore??new EventMemory))}count(e,t=nanoid$1()){return this.relays$.pipe(switchMap(r=>combineLatest(Object.fromEntries(r.map(r=>[r.url,r.count(e,t)])))),share())}sync(e,t,r){return defer(async()=>{const e=(await Promise.all(this.relays.map(async e=>[e,await e.getSupported()]))).filter(([e,t])=>t?.includes(77)).map(([e])=>e);if(0===e.length)throw new Error("No relays support NIP-77 negentropy sync");return e}).pipe(switchMap(n=>merge$1(...n.map(n=>n.sync(e,t,r)))),share())}}var ClientAuth=22242;function makeAuthEvent(e,t){return{kind:ClientAuth,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var DEFAULT_WEBSOCKET_CONFIG={url:"",deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT="WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }",WebSocketSubject=function(e){function t(t,r){var n=e.call(this)||this;if(n._socket=null,t instanceof Observable$1)n.destination=r,n.source=t;else{var i=n._config=__assign({},DEFAULT_WEBSOCKET_CONFIG);if(n._output=new Subject,"string"==typeof t)i.url=t;else for(var o in t)t.hasOwnProperty(o)&&(i[o]=t[o]);if(!i.WebSocketCtor&&WebSocket)i.WebSocketCtor=WebSocket;else if(!i.WebSocketCtor)throw new Error("no WebSocket constructor can be found");n.destination=new ReplaySubject}return n}return __extends(t,e),t.prototype.lift=function(e){var r=new t(this._config,this.destination);return r.operator=e,r.source=this,r},t.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new ReplaySubject),this._output=new Subject},t.prototype.multiplex=function(e,t,r){var n=this;return new Observable$1(function(i){try{n.next(e())}catch(s){i.error(s)}var o=n.subscribe({next:function(e){try{r(e)&&i.next(e)}catch(s){i.error(s)}},error:function(e){return i.error(e)},complete:function(){return i.complete()}});return function(){try{n.next(t())}catch(s){i.error(s)}o.unsubscribe()}})},t.prototype._connectSocket=function(){var e=this,t=this._config,r=t.WebSocketCtor,n=t.protocol,i=t.url,o=t.binaryType,s=this._output,a=null;try{a=n?new r(i,n):new r(i),this._socket=a,o&&(this._socket.binaryType=o)}catch(c){return void s.error(c)}var l=new Subscription(function(){e._socket=null,a&&1===a.readyState&&a.close()});a.onopen=function(t){if(!e._socket)return a.close(),void e._resetState();var r=e._config.openObserver;r&&r.next(t);var n=e.destination;e.destination=Subscriber.create(function(t){if(1===a.readyState)try{var r=e._config.serializer;a.send(r(t))}catch(c){e.destination.error(c)}},function(t){var r=e._config.closingObserver;r&&r.next(void 0),t&&t.code?a.close(t.code,t.reason):s.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT)),e._resetState()},function(){var t=e._config.closingObserver;t&&t.next(void 0),a.close(),e._resetState()}),n&&n instanceof ReplaySubject&&l.add(n.subscribe(e.destination))},a.onerror=function(t){e._resetState(),s.error(t)},a.onclose=function(t){a===e._socket&&e._resetState();var r=e._config.closeObserver;r&&r.next(t),t.wasClean?s.complete():s.error(t)},a.onmessage=function(t){try{var r=e._config.deserializer;s.next(r(t))}catch(n){s.error(n)}}},t.prototype._subscribe=function(e){var t=this,r=this.source;return r?r.subscribe(e):(this._socket||this._connectSocket(),this._output.subscribe(e),e.add(function(){var e=t._socket;0===t._output.observers.length&&(!e||1!==e.readyState&&0!==e.readyState||e.close(),t._resetState())}),e)},t.prototype.unsubscribe=function(){var t=this._socket;!t||1!==t.readyState&&0!==t.readyState||t.close(),this._resetState(),e.prototype.unsubscribe.call(this)},t}(AnonymousSubject);function webSocket(e){return new WebSocketSubject(e)}function markFromRelay(e){return t=>t.pipe(tap$1(t=>{"string"!=typeof t&&addSeenRelay(t,e)}))}const AUTH_REQUIRED_PREFIX="auth-required:",DEFAULT_RETRY_CONFIG={count:3,delay:1e3,resetOnSuccess:!0};var SyncDirection;!function(e){e[e.RECEIVE=1]="RECEIVE",e[e.SEND=2]="SEND",e[e.BOTH=3]="BOTH"}(SyncDirection||(SyncDirection={}));class ReqCloseError extends Error{}const PING_FILTER={ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0};class Relay{url;log=logger$1.extend("Relay");socket;_ready$=new BehaviorSubject(!0);ready$=this._ready$.asObservable();reconnectTimer;attempts$=new BehaviorSubject(0);connected$=new BehaviorSubject(!1);challenge$=new BehaviorSubject(null);authenticated$;authenticatedAs$;authentication$=new BehaviorSubject(null);authenticationResponse$=new BehaviorSubject(null);notices$=new BehaviorSubject([]);error$=new BehaviorSubject(null);message$;notice$;lastMessageReceivedAt=0;_lastMessageAt$=new BehaviorSubject(0);lastMessageAt$=this._lastMessageAt$.asObservable();status$;information$;_nip11=null;icon$;limitations$;supported$;open$=new Subject;close$=new Subject;closing$=new Subject;reqs$=new BehaviorSubject({});get ready(){return this._ready$.value}get connected(){return this.connected$.value}get challenge(){return this.challenge$.value}get notices(){return this.notices$.value}get authenticated(){return!0===this.authenticationResponse?.ok}get authentication(){return this.authentication$.value}get authenticatedAs(){return this.authenticated?this.authentication?.pubkey??null:null}get authenticationResponse(){return this.authenticationResponse$.value}get information(){return this._nip11}get lastMessageAt(){return this._lastMessageAt$.value}get reqs(){return this.reqs$.value}eoseTimeout=1e4;eventTimeout=1e4;publishTimeout=3e4;keepAlive=3e4;enablePing=!1;pingFrequency=29e3;pingTimeout=2e4;subscriptionReconnect;requestReconnect;publishRetry;onUnresponsive;receivedAuthRequiredForReq=new BehaviorSubject(!1);receivedAuthRequiredForEvent=new BehaviorSubject(!1);authRequiredForRead$;authRequiredForPublish$;resetState(){null!==this.challenge$.value&&this.challenge$.next(null),this.authenticationResponse$.value&&this.authenticationResponse$.next(null),null!==this.authentication$.value&&this.authentication$.next(null),this.notices$.value.length>0&&this.notices$.next([]),this.receivedAuthRequiredForReq.value&&this.receivedAuthRequiredForReq.next(!1),this.receivedAuthRequiredForEvent.value&&this.receivedAuthRequiredForEvent.next(!1)}watchTower;constructor(e,t){this.url=e,this.log=this.log.extend(e),void 0!==t?.eoseTimeout&&(this.eoseTimeout=t.eoseTimeout),void 0!==t?.eventTimeout&&(this.eventTimeout=t.eventTimeout),void 0!==t?.publishTimeout&&(this.publishTimeout=t.publishTimeout),void 0!==t?.keepAlive&&(this.keepAlive=t.keepAlive),void 0!==t?.enablePing&&(this.enablePing=t.enablePing),void 0!==t?.pingFrequency&&(this.pingFrequency=t.pingFrequency),void 0!==t?.pingTimeout&&(this.pingTimeout=t.pingTimeout),void 0!==t?.onUnresponsive&&(this.onUnresponsive=t.onUnresponsive),this.subscriptionReconnect={...DEFAULT_RETRY_CONFIG,...t?.subscriptionRetry??{}},this.requestReconnect={...DEFAULT_RETRY_CONFIG,...t?.requestRetry??{}},this.publishRetry={...DEFAULT_RETRY_CONFIG,...t?.publishRetry??{}},this.authenticated$=this.authenticationResponse$.pipe(map$1(e=>!0===e?.ok)),this.authenticatedAs$=combineLatest([this.authenticated$,this.authentication$]).pipe(map$1(([e,t])=>e&&t?t.pubkey:null)),this.reconnectTimer=Relay.createReconnectTimer(e),this.open$.subscribe(()=>{this.log("Connected"),this.connected$.next(!0),this.attempts$.next(0),this.error$.next(null),this.resetState()}),this.close$.subscribe(e=>{this.connected$.value?this.log("Disconnected"):this.log("Failed to connect"),this.connected$.value&&this.connected$.next(!1),this.attempts$.next(this.attempts$.value+1),this.resetState(),e.wasClean||this.startReconnectTimer(e)}),this.socket=webSocket({url:e,openObserver:this.open$,closeObserver:this.close$,closingObserver:this.closing$,WebSocketCtor:t?.WebSocket}),this.information$=defer(()=>(this.log("Fetching NIP-11 information document"),Relay.fetchInformationDocument(this.url))).pipe(catchError(()=>of(null)),tap$1(e=>this._nip11=e),shareReplay(1)),this.limitations$=this.information$.pipe(map$1(e=>e?e.limitation:null)),this.supported$=this.information$.pipe(map$1(e=>e&&Array.isArray(e.supported_nips)?e.supported_nips.filter(e=>"number"==typeof e):null)),this.icon$=this.information$.pipe(map$1(e=>e?.icon||new URL("/favicon.ico",ensureHttpURL(this.url)).toString())),this.authRequiredForRead$=this.receivedAuthRequiredForReq,this.authRequiredForPublish$=this.receivedAuthRequiredForEvent,this.authRequiredForRead$.pipe(filter$1(e=>!0===e),take(1)).subscribe(()=>this.log("Auth required for REQ")),this.authRequiredForPublish$.pipe(filter$1(e=>!0===e),take(1)).subscribe(()=>this.log("Auth required for EVENT")),this.status$=combineLatest({url:of(this.url),connected:this.connected$,authenticated:this.authenticated$,authenticatedAs:this.authenticatedAs$,ready:this._ready$,authRequiredForRead:this.authRequiredForRead$,authRequiredForPublish:this.authRequiredForPublish$,challenge:this.challenge$.asObservable()}).pipe(shareReplay(1));const r=this.socket.pipe(filter$1(e=>Array.isArray(e)&&"NOTICE"===e[0]),map$1(e=>e[1]),scan((e,t)=>[...e,t],[]),tap$1(e=>this.notices$.next(e))),n=this.socket.pipe(filter$1(e=>"AUTH"===e[0]),map$1(e=>e[1]),tap$1(e=>{this.log("Received AUTH challenge",e),this.challenge$.next(e)})),i=new Subject,o=this.socket.pipe(tap$1(e=>{const t=Date.now();this.lastMessageReceivedAt=t,this._lastMessageAt$.next(t),i.next(e)}));this.message$=i.asObservable(),this.notice$=this.message$.pipe(filter$1(e=>Array.isArray(e)&&"NOTICE"===e[0]),map$1(e=>e[1]));const s=this.connected$.pipe(switchMap(e=>e&&this.enablePing?timer(this.pingFrequency,this.pingFrequency).pipe(mergeMap(()=>{if(Date.now()-this.lastMessageReceivedAtArray.isArray(t)&&("EOSE"===t[0]||"CLOSED"===t[0])&&t[1]===e),take(1),timeout$1({first:this.pingTimeout,with:()=>{const e=Date.now(),t=this.onUnresponsive?.({url:this.url,lastMessageAt:this.lastMessageReceivedAt,now:e,attempts:this.attempts$.value})??"reconnect",r=new Error(`Relay ping timeout after ${this.pingTimeout}ms`);return"reconnect"===t?(this.log("Relay connection has become unresponsive, triggering reconnect"),this.startReconnectTimer(r)):"close"===t?(this.log("Relay connection has become unresponsive, closing connection"),this.error$.next(r),this.socket.complete()):this.log("Relay connection has become unresponsive (ignoring per policy)"),NEVER}}),finalize(()=>this.send(["CLOSE",e])))})):NEVER),catchError(()=>NEVER));this.watchTower=this.ready$.pipe(switchMap(e=>e?merge$1(o,r,n,this.information$,s).pipe(ignoreElements(),catchError(e=>(this.startReconnectTimer(e instanceof Error?e:new Error("Connection error")),NEVER)),share({resetOnRefCountZero:()=>timer(this.keepAlive)})):NEVER),share())}startReconnectTimer(e){this.ready&&(this.error$.next(e instanceof Error?e:new Error("Connection error")),this._ready$.next(!1),this.reconnectTimer(e,this.attempts$.value).pipe(take(1)).subscribe(()=>{this._ready$.next(!0)}))}waitForAuth(e,t){return combineLatest([e,this.authenticated$]).pipe(mergeWith(this.watchTower),filter$1(([e,t])=>!e||t),take(1),switchMap(()=>t))}waitForReady(e){return this.ready?e:this.ready$.pipe(filter$1(e=>e),take(1),switchMap(()=>e))}multiplex(e,t,r){return this.socket.multiplex(e,t,r)}send(e){this.socket.next(e)}req(e,t=nanoid$1()){let r;if("function"==typeof e){const t=e(this);r=(isObservable(t)?t:merge$1(of(t),NEVER)).pipe(map$1(e=>Array.isArray(e)?e:[e]))}else r=(isObservable(e)?e:merge$1(of(e),NEVER)).pipe(map$1(e=>Array.isArray(e)?e:[e]));const n=r.pipe(ignoreElements(),endWith(null)),i=this.socket.pipe(filter$1(e=>Array.isArray(e)&&("EVENT"===e[0]||"CLOSED"===e[0]||"EOSE"===e[0])&&e[1]===t),share()),o=r.pipe(tap$1(e=>{this.socket.next(["REQ",t,...e]),this.reqs$.next({...this.reqs$.value,[t]:e})}),finalize(()=>{this.socket.next(["CLOSE",t]);const{[t]:e,...r}=this.reqs$.value;this.reqs$.next(r)}),switchMap(()=>i)),s=merge$1(this.watchTower,o).pipe(takeUntil(i.pipe(ignoreElements(),endWith(!0))),takeUntil(n),map$1(e=>{if("EOSE"===e[0])return"EOSE";if("CLOSED"===e[0])throw new ReqCloseError(e[2]);return e[2]}),this.handleAuthRequiredForReq("REQ"),markFromRelay(this.url),timeout$1({first:this.eoseTimeout,with:()=>merge$1(of("EOSE"),NEVER)}),share());return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,s))}count(e,t=nanoid$1()){const r=this.socket.pipe(filter$1(e=>Array.isArray(e)&&("COUNT"===e[0]||"CLOSED"===e[0])&&e[1]===t)),n=defer(()=>(this.socket.next(Array.isArray(e)?["COUNT",t,...e]:["COUNT",t,e]),merge$1(this.watchTower,r))).pipe(map$1(e=>{if("COUNT"===e[0])return e[2];throw new ReqCloseError(e[2])}),this.handleAuthRequiredForReq("COUNT"),take(1),timeout$1({first:this.eoseTimeout,with:()=>throwError(()=>new Error("COUNT timeout"))}));return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,n)).pipe(share())}event(e,t="EVENT"){const r=defer(()=>(this.socket.next([t,e]),this.socket.pipe(filter$1(t=>"OK"===t[0]&&t[1]===e.id),map$1(e=>({ok:e[2],message:e[3],from:this.url}))))).pipe(share()),n=merge$1(this.watchTower,r).pipe(takeUntil(r.pipe(ignoreElements(),endWith(!0))),take(1),tap$1(({ok:e,message:t})=>{!1===e&&t?.startsWith(AUTH_REQUIRED_PREFIX)&&!this.receivedAuthRequiredForEvent.value&&(this.log("Auth required for publish"),this.receivedAuthRequiredForEvent.next(!0))}),timeout$1({first:this.eventTimeout,with:()=>of({ok:!1,from:this.url,message:"Timeout"})}));return"AUTH"===t?this.waitForReady(n).pipe(share()):this.waitForReady(this.waitForAuth(this.authRequiredForPublish$,n)).pipe(share())}auth(e){return this.authentication$.next(e),lastValueFrom(this.event(e,"AUTH").pipe(tap$1(e=>this.authenticationResponse$.next(e))))}async negentropy(e,t,r,n){if(!1===(await this.getSupported())?.includes(77))throw new Error("Relay does not support NIP-77");const{buildStorageVector:i,buildStorageFromFilter:o,negentropySync:s}=await __vitePreload(async()=>{const{buildStorageVector:e,buildStorageFromFilter:t,negentropySync:r}=await import("./negentropy-B7CRzqXr.js");return{buildStorageVector:e,buildStorageFromFilter:t,negentropySync:r}},[]);return s(Array.isArray(e)?i(e):await o(e,t),this.socket,t,r,n)}authenticate(e){if(!this.challenge)throw new Error("Have not received authentication challenge");const t=e.signEvent(makeAuthEvent(this.url,this.challenge));return lastValueFrom((t instanceof Promise?from(t):of(t)).pipe(switchMap(e=>this.auth(e))))}customRetryOperator(e,t){return!1===e?identity$1:"number"==typeof e?retry({...t,count:e}):!0===e?t?retry(t):retry():retry({...t,...e})}customRepeatOperator(e){return!1===e||void 0===e?identity$1:!0===e?repeat():repeat(e)}customTimeoutOperator(e,t){return!1===e?identity$1:simpleTimeout(!0===e?t:e??t)}handleAuthRequiredForReq(e){return catchError(t=>(t instanceof ReqCloseError&&t.message.startsWith(AUTH_REQUIRED_PREFIX)&&!this.receivedAuthRequiredForReq.value&&(this.log(`Auth required for ${e}`),this.receivedAuthRequiredForReq.next(!0)),throwError(()=>t)))}subscription(e,t){return this.req(e,t?.id).pipe(this.customRetryOperator(t?.reconnect??!0,this.subscriptionReconnect),this.customRepeatOperator(t?.resubscribe),share())}request(e,t){return this.req(e,t?.id).pipe(this.customRetryOperator(t?.reconnect??!0,this.requestReconnect),this.customRepeatOperator(t?.resubscribe),completeOnEose(),share())}publish(e,t){return lastValueFrom(this.event(e).pipe(mergeMap(e=>!1===e.ok&&e.message?.startsWith(AUTH_REQUIRED_PREFIX)?throwError(()=>new Error(e.message)):of(e)),this.customRetryOperator(t?.retries??t?.reconnect??!0,this.publishRetry),this.customTimeoutOperator(t?.timeout,this.publishTimeout)))}sync(e,t,r=SyncDirection.RECEIVE){return new Observable$1(n=>{const i=new AbortController;let o=!1;return this.negentropy(e,t,async(t,i)=>{if(r&SyncDirection.SEND&&t.length>0){const r=await(async t=>Array.isArray(e)?e.filter(e=>t.includes(e.id)):e.getByFilters({ids:t}))(t);await Promise.allSettled(r.map(e=>lastValueFrom(this.event(e))))}r&SyncDirection.RECEIVE&&i.length>0&&await lastValueFrom(this.req({ids:i}).pipe(completeOnEose(),Reflect.has(e,"add")?mapEventsToStore(e):identity$1,tap$1(e=>n.next(e))))},{signal:i.signal}).then(()=>{o||n.complete()}).catch(e=>{o||n.error(e)}),()=>{o||(o=!0,i.abort())}}).pipe(share())}close(){this.socket.unsubscribe()}async getInformation(){return firstValueFrom(this.information$)}async getLimitations(){return firstValueFrom(this.limitations$)}async getSupported(){return firstValueFrom(this.supported$)}static fetchInformationDocument(e){return from(fetch(ensureHttpURL(e),{headers:{Accept:"application/nostr+json"}}).then(e=>e.json())).pipe(catchError(()=>of(null)),simpleTimeout(1e4))}static createReconnectTimer(e){return(e,t=0)=>timer(Math.min(1e3*Math.pow(1.5,t),3e5))}}class RelayPool{options;relays$=new BehaviorSubject(new Map);get relays(){return this.relays$.value}status$;ignoreOffline=!0;add$=new Subject;remove$=new Subject;constructor(e){this.options=e,this.status$=this.relays$.pipe(map$1(e=>Array.from(e.values())),switchMap(e=>0===e.length?of({}):merge$1(...e.map(e=>e.status$)).pipe(scan((e,t)=>({...e,[t.url]:t}),{}),startWith({}))),shareReplay(1))}relay(e){e=normalizeURL(e);let t=this.relays.get(e);return t||(t=new Relay(e,this.options),this.relays.set(e,t),this.relays$.next(this.relays),t)}group(e,t=this.ignoreOffline){let r=Array.isArray(e)?e.map(e=>this.relay(e)):e.pipe(map$1(e=>e.map(e=>this.relay(e))));return t&&(r=Array.isArray(r)?r.filter(e=>e.ready):r.pipe(map$1(e=>e.filter(e=>e.ready)))),new RelayGroup(r)}remove(e,t=!0){let r;if("string"==typeof e){if(r=this.relays.get(e),!r)return}else{if(!Array.from(this.relays.values()).some(t=>t===e))return;r=e}t&&r?.close(),this.relays.delete(r.url),this.relays$.next(this.relays),this.remove$.next(r)}req(e,t,r){return this.group(e,!1).req(t,r)}event(e,t){return this.group(e,!1).event(t)}negentropy(e,t,r,n,i){return this.group(e,!1).negentropy(t,r,n,i)}publish(e,t,r){return this.group(e).publish(t,r)}request(e,t,r){return this.group(e).request(t,r)}subscription(e,t,r){return this.group(e).subscription(t,r)}subscriptionMap(e,t){const r=isObservable(e)?e:of(e);return this.group(r.pipe(map$1(e=>Object.keys(e)))).subscription(e=>r.pipe(map$1(t=>t[e.url]),distinctUntilChanged(isFilterEqual)),t)}outboxSubscription(e,t,r){const n=isObservable(e)?e.pipe(map$1(e=>createFilterMap(e,t))):createFilterMap(e,t);return this.subscriptionMap(n,r)}count(e,t,r){return this.group(e).count(t,r)}sync(e,t,r,n){return this.group(e).sync(t,r,n)}}class NostrRelayService extends Service{pool=new RelayPool({enablePing:!0});async publish(e,t){if(!e||0===e.length)throw new Error("No relays provided to publish the event.");const r=await this.pool.publish(e,t);if(!r.some(e=>e.ok))throw new Error(`Failed to publish event. Responses: ${JSON.stringify(r)}`);return r}}const amdModule9=Object.freeze(Object.defineProperty({__proto__:null,default:NostrRelayService},Symbol.toStringTag,{value:"Module"}));class ErrorOAuth2{}class ErrorUnknown extends ErrorOAuth2{constructor(e){super(),this.message=e}}class ErrorNoAccessToken extends ErrorOAuth2{}class ErrorNoAuthCode extends ErrorOAuth2{}class ErrorInvalidReturnedStateParam extends ErrorOAuth2{}class ErrorInvalidScope extends ErrorOAuth2{}class ErrorInvalidRequest extends ErrorOAuth2{}class ErrorInvalidToken extends ErrorOAuth2{}class ErrorAuthenticationGrant extends ErrorOAuth2{}class ErrorUnauthorizedClient extends ErrorAuthenticationGrant{}class ErrorAccessDenied extends ErrorAuthenticationGrant{}class ErrorUnsupportedResponseType extends ErrorAuthenticationGrant{}class ErrorServerError extends ErrorAuthenticationGrant{}class ErrorTemporarilyUnavailable extends ErrorAuthenticationGrant{}class ErrorAccessTokenResponse extends ErrorOAuth2{}class ErrorInvalidClient extends ErrorAccessTokenResponse{}class ErrorInvalidGrant extends ErrorAccessTokenResponse{}class ErrorUnsupportedGrantType extends ErrorAccessTokenResponse{}const RAW_ERROR_TO_ERROR_CLASS_MAP={invalid_request:ErrorInvalidRequest,invalid_grant:ErrorInvalidGrant,unauthorized_client:ErrorUnauthorizedClient,access_denied:ErrorAccessDenied,unsupported_response_type:ErrorUnsupportedResponseType,invalid_scope:ErrorInvalidScope,server_error:ErrorServerError,temporarily_unavailable:ErrorTemporarilyUnavailable,invalid_client:ErrorInvalidClient,unsupported_grant_type:ErrorUnsupportedGrantType,invalid_token:ErrorInvalidToken},toErrorObject=e=>{const t=RAW_ERROR_TO_ERROR_CLASS_MAP[e];return t?new t:new ErrorUnknown(e)};var __awaiter$1=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(t){o(t)}}function a(e){try{l(n.throw(e))}catch(t){o(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};const RECOMMENDED_CODE_VERIFIER_LENGTH=96,PKCE_CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",parseWwwAuthenticateHeader=e=>{const t=e.slice(7).replace(/"/g,"").split(",").map(e=>{const[t,r]=e.trim().split("=");return{[t]:r}}).reduce((e,t)=>Object.assign(Object.assign({},e),t),{});return{realm:t.realm,error:t.error,errorDescription:t.error_description,errorUri:t.error_uri}},base64urlEncode=e=>{let t=btoa(e);return t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_"),t=t.replace(/=/g,""),t},extractParamFromUrl=(e,t)=>{let r=t.split("?");if(r.length<2)return;r=r[1].split("#");const n=r[0].split("&");for(const i of n){const[t,r]=i.split("=");if(t===e)return decodeURIComponent(r)}},objectToQueryString=e=>Object.entries(e).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&"),generatePKCECodeChallengeAndVerifier=()=>__awaiter$1(void 0,void 0,void 0,function*(){const e=new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);crypto.getRandomValues(e);const t=base64urlEncode(Array.from(e).map(e=>PKCE_CHARSET[e%PKCE_CHARSET.length]).join("")),r=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t)),n=new Uint8Array(r);let i="";const o=n.byteLength;for(let s=0;s{const t=new Uint32Array(e);return crypto.getRandomValues(t),Array.from(t).map(e=>PKCE_CHARSET[e%PKCE_CHARSET.length]).join("")};var __awaiter=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(t){o(t)}}function a(e){try{l(n.throw(e))}catch(t){o(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};const HEADER_AUTHORIZATION="Authorization",HEADER_WWW_AUTHENTICATE="WWW-Authenticate",RECOMMENDED_STATE_LENGTH=32;class OAuth2AuthCodePkceClient{constructor(e,t){this.state={},this.config=e,this.storage=t||LocalStorage,this.ready=new Promise(e=>this.setReady=e),this.recoverState()}reset(){return __awaiter(this,void 0,void 0,function*(){this.state={},yield this.saveState(),this.authCodeForAccessTokenPromise=void 0,this.refreshTokenForAccessTokenPromise=void 0})}requestAuthorizationCode(e){return __awaiter(this,void 0,void 0,function*(){const{clientId:t,extraAuthorizationParams:r,redirectUrl:n,scopes:i}=this.config,{codeChallenge:o,codeVerifier:s}=yield generatePKCECodeChallengeAndVerifier(),a=generateRandomState(RECOMMENDED_STATE_LENGTH);this.state=Object.assign(Object.assign({},this.state),{codeChallenge:o,codeVerifier:s,stateQueryParam:a}),this.saveState();let l=this.config.authorizationUrl+"?response_type=code&"+`client_id=${encodeURIComponent(t)}&`+`redirect_uri=${encodeURIComponent(n)}&`+`state=${a}&`+`code_challenge=${encodeURIComponent(o)}&code_challenge_method=S256`;if(i&&(l+=`&scope=${encodeURIComponent(i.join(" "))}`),r||e){const t=Object.assign(Object.assign({},r),e);l+=`&${objectToQueryString(t)}`}location.replace(l)})}isReturningFromAuthServer(){return!!extractParamFromUrl("code",location.href)}receiveCode(){return __awaiter(this,void 0,void 0,function*(){yield this.ready;const e=extractParamFromUrl("error",location.href);if(e)throw toErrorObject(e);if(extractParamFromUrl("state",location.href)!==this.state.stateQueryParam)throw console.warn('"state" parameter doesn\'t match the one sent! Possible malicious activity.'),new ErrorInvalidReturnedStateParam;if(this.state.authorizationCode=extractParamFromUrl("code",location.href),!this.state.authorizationCode)throw new ErrorNoAuthCode;this.saveState()})}getTokens(e){return __awaiter(this,void 0,void 0,function*(){const{accessToken:t,authorizationCode:r,idToken:n,refreshToken:i,scopes:o}=this.state;if(r)return this.exchangeAuthCodeForAccessToken(e);if(!t)throw new ErrorNoAccessToken;return this.isAccessTokenExpired()&&this.config.onAccessTokenExpiry?this.config.onAccessTokenExpiry():Promise.resolve({accessToken:t,idToken:n,refreshToken:i,scopes:o})})}exchangeAuthCodeForAccessToken(e){return __awaiter(this,void 0,void 0,function*(){this.authCodeForAccessTokenPromise||(this.authCodeForAccessTokenPromise=this.fetchAccessTokenUsingCode(e));const t=yield this.authCodeForAccessTokenPromise;return this.authCodeForAccessTokenPromise=void 0,this.state.authorizationCode=void 0,this.setTokens(t)})}exchangeRefreshTokenForAccessToken(){return __awaiter(this,void 0,void 0,function*(){this.refreshTokenForAccessTokenPromise||(this.refreshTokenForAccessTokenPromise=this.fetchAccessTokenUsingRefreshToken());const e=yield this.refreshTokenForAccessTokenPromise;return this.refreshTokenForAccessTokenPromise=void 0,this.setTokens(e)})}makeRetryFetchFunction(e){return(t,...r)=>__awaiter(this,void 0,void 0,function*(){const n=yield e(t,...r);if(401===n.status){const i=n.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());if(i&&"invalid_token"===parseWwwAuthenticateHeader(i).error)return yield this.exchangeRefreshTokenForAccessToken(),t=yield this.requestInterceptor(t),e(t,...r)}return n})}decorateFetchWithInterceptors(e){return(t,...r)=>__awaiter(this,void 0,void 0,function*(){"string"==typeof t&&(t=new Request(t)),t=yield this.requestInterceptor(t);const n=yield e(t,...r);return this.responseInterceptor(n)})}requestInterceptor(e){return __awaiter(this,void 0,void 0,function*(){const t=yield this.getTokens();return e.headers.set(HEADER_AUTHORIZATION,`Bearer ${t.accessToken}`),e})}responseInterceptor(e){return __awaiter(this,void 0,void 0,function*(){if(401!==e.status)return e;const t=e.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());if(t){const e=parseWwwAuthenticateHeader(t).error;throw"invalid_grant"===e&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),"invalid_token"===e&&this.config.onInvalidToken&&(yield this.config.onInvalidToken()),toErrorObject(e)}return e})}getGrantedScopes(){return this.state.scopes}isAuthorized(){return!!this.state.accessToken}isAccessTokenExpired(){const{accessTokenExpiry:e}=this.state;return Boolean(e&&new Date>=new Date(e))}fetchAccessTokenUsingCode(e){return __awaiter(this,void 0,void 0,function*(){const{authorizationCode:t,codeVerifier:r=""}=this.state,{clientId:n,redirectUrl:i}=this.config;r?t||console.warn("No authorization grant code is being passed."):console.warn("No code verifier is being sent.");const o=this.config.tokenUrl,s=Object.assign({grant_type:"authorization_code",code:t,redirect_uri:i,client_id:n,code_verifier:r},e),a=new URLSearchParams(s).toString();return this.makeTokenRequest(o,a)})}fetchAccessTokenUsingRefreshToken(){const{extraRefreshParams:e,clientId:t,tokenUrl:r}=this.config,{refreshToken:n}=this.state;n||console.warn("No refresh token is present.");const i=r;let o=`grant_type=refresh_token&refresh_token=${n}&client_id=${t}`;return e&&(o=`${i}&${objectToQueryString(e)}`),this.makeTokenRequest(i,o)}makeTokenRequest(e,t){return __awaiter(this,void 0,void 0,function*(){const r=yield fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),n=yield r.json();if(!r.ok)throw"invalid_grant"===n.error&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),toErrorObject(n.error);const{access_token:i,expires_in:o,id_token:s,refresh_token:a,scope:l}=n;return{accessToken:i,expiresIn:o,idToken:s,refreshToken:a,scope:l}})}setTokens(e){return __awaiter(this,void 0,void 0,function*(){const{accessToken:t,expiresIn:r,idToken:n,refreshToken:i,scope:o}=e;return this.state.accessToken=t,this.state.accessTokenExpiry=new Date(Date.now()+1e3*parseInt(r,10)).toString(),n&&(this.state.idToken=n),i&&(this.state.refreshToken=i),o&&(this.state.scopes=o.split(" ")),yield this.saveState(),{accessToken:this.state.accessToken,idToken:this.state.idToken,refreshToken:this.state.refreshToken,scopes:o?this.state.scopes:[]}})}recoverState(){return __awaiter(this,void 0,void 0,function*(){this.state=JSON.parse((yield this.storage.loadState())||"{}"),this.setReady(),this.config.storeRefreshToken||(this.state.refreshToken=this.refreshToken)})}saveState(){return __awaiter(this,void 0,void 0,function*(){this.refreshToken=this.state.refreshToken;const e=Object.assign({},this.state);this.config.storeRefreshToken||delete e.refreshToken,yield this.storage.saveState(JSON.stringify(e))})}}const LOCALSTORAGE_STATE="oauth2authcodepkce-state",LocalStorage={saveState:e=>localStorage.setItem(LOCALSTORAGE_STATE,e),loadState:()=>localStorage.getItem(LOCALSTORAGE_STATE)};class MarcoOsmAuthStorage{saveState(e){localStorage.setItem("marco:osm_auth_state",e)}loadState(){const e=localStorage.getItem("marco:osm_auth_state");if(!e)return!1;try{return JSON.parse(e),e}catch(t){return console.warn("Failed to parse OSM auth state",t),!1}}}class OsmAuthService extends Service{static{decorateFieldV2(this.prototype,"isConnected",[tracked],function(){return!1})}#te=void initializeDeferredDecorator(this,"isConnected");static{decorateFieldV2(this.prototype,"userDisplayName",[tracked],function(){return null})}#re=void initializeDeferredDecorator(this,"userDisplayName");oauthClient;constructor(){super(...arguments);const e="https://www.openstreetmap.org",t=`${window.location.origin}/oauth/osm/callback`;this.oauthClient=new OAuth2AuthCodePkceClient({scopes:["read_prefs","write_api"],authorizationUrl:`${e}/oauth2/authorize`,tokenUrl:`${e}/oauth2/token`,clientId:"jIn8l5mT8FZOGYiIYXG1Yvj_2FZKB9TJ1edZwOJPsRU",redirectUrl:t,storeRefreshToken:!0},new MarcoOsmAuthStorage),this.restoreSession()}async restoreSession(){try{await this.oauthClient.ready}catch(e){console.warn("oauthClient.ready failed",e)}if(await this.oauthClient.isAuthorized()){this.isConnected=!0;const e=localStorage.getItem("marco:osm_user_display_name");e?this.userDisplayName=e:await this.fetchUserInfo()}}async login(){await this.oauthClient.requestAuthorizationCode()}async handleCallback(){await this.oauthClient.receiveCode(),await this.oauthClient.getTokens(),this.isConnected=!0,await this.fetchUserInfo()}async logout(){await this.oauthClient.reset(),this.isConnected=!1,this.userDisplayName=null,localStorage.removeItem("marco:osm_user_display_name")}async fetchUserInfo(){try{const e=await this.oauthClient.getTokens(),t=await fetch("https://api.openstreetmap.org/api/0.6/user/details.json",{headers:{Authorization:`Bearer ${e.accessToken}`}});if(t.ok){const e=await t.json();console.debug("OSM data:",e);const r=e.user.display_name;this.userDisplayName=r,localStorage.setItem("marco:osm_user_display_name",r)}else console.error("Failed to fetch OSM user info",t.status)}catch(e){console.error("Error fetching OSM user info",e)}}}const amdModule10=Object.freeze(Object.defineProperty({__proto__:null,default:OsmAuthService},Symbol.toStringTag,{value:"Module"}));function humanizeOsmTag$1(e){return"string"==typeof e&&e?e.replace(/[_-]/g," ").replace(/\w\S*/g,e=>e.replace(/^\w/,e=>e.toUpperCase())):""}const amdModule17=Object.freeze(Object.defineProperty({__proto__:null,humanizeOsmTag:humanizeOsmTag$1},Symbol.toStringTag,{value:"Module"}));function getLocalizedName(e,t="Untitled Place"){if(!e)return t;const r=navigator.languages||[navigator.language||"en"];for(const n of r){if(!n)continue;const t=`name:${n.split("-")[0]}`;if(e[t])return e[t]}return e.name?e.name:e["name:en"]?e["name:en"]:t}const PLACE_TYPE_KEYS=["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","highway","aeroway","waterway","natural","place","border_type","admin_title"];function getPlaceType(e){if(!e)return null;for(const t of PLACE_TYPE_KEYS){const r=e[t];if(r)return humanizeOsmTag$1("yes"===r?t:r)}return null}const amdModule23=Object.freeze(Object.defineProperty({__proto__:null,getLocalizedName:getLocalizedName,getPlaceType:getPlaceType},Symbol.toStringTag,{value:"Module"})),POI_CATEGORIES=[{id:"restaurants",label:"Restaurants",icon:"fork-and-knife",filter:['["amenity"~"^(restaurant|fast_food|food_court|pub|cafe)$"]["cuisine"!~"coffee"]'],types:["node","way"]},{id:"coffee",label:"Coffee",icon:"cup-and-saucer",filter:['["amenity"~"^(cafe|ice_cream)$"]','["shop"~"^(coffee|tea)$"]','["cuisine"~"coffee_shop"]'],types:["node","way"]},{id:"groceries",label:"Groceries",icon:"shopping-basket",filter:['["shop"~"^(supermarket|convenience|grocery|greengrocer|bakery|butcher|deli|farm|seafood)$"]'],types:["node","way"]},{id:"things-to-do",label:"Things to do",icon:"feather-camera",filter:['["tourism"~"^(museum|gallery|attraction|viewpoint|zoo|theme_park|aquarium|artwork)$"]','["amenity"~"^(cinema|theatre|arts_centre|planetarium)$"]','["leisure"~"^(sports_centre|stadium|water_park)$"]','["historic"]','["shop"="flea_market"]'],types:["node","way","relation"]},{id:"accommodation",label:"Hotels",icon:"person-sleeping-in-bed",filter:['["tourism"~"^(hotel|hostel|motel|chalet)$"]'],types:["node","way","relation"]}];function getCategoryById(e){return POI_CATEGORIES.find(t=>t.id===e)}const amdModule25=Object.freeze(Object.defineProperty({__proto__:null,POI_CATEGORIES:POI_CATEGORIES,getCategoryById:getCategoryById},Symbol.toStringTag,{value:"Module"}));class OsmService extends Service{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");controller=null;cachedResults=null;lastQueryKey=null;cachedPlaces=new Map;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}async getNearbyPois(e,t,r=50){const n=`${e},${t},${r}`;if(this.lastQueryKey===n&&this.cachedResults)return console.debug("Returning cached Overpass results for:",n),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,o=[`~"^(${["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","aeroway"].join("|")})$"~".*"`],s=Object.entries({public_transport:["stop_area","platform"]}).map(([e,t])=>`["${e}"!~"^(${t.join("|")})$"]`).join(""),a=`\n[out:json][timeout:25];\n(\n node(around:${r},${e},${t})\n [${o}]${s}[~"^name"~"."];\n way(around:${r},${e},${t})\n [${o}]${s}[~"^name"~"."];\n relation(around:${r},${e},${t})\n [${o}]${s}[~"^name"~"."];\n);\nout center;\n `.trim(),l=`${this.settings.overpassApi}?data=${encodeURIComponent(a)}`;try{const e=await this.fetchWithRetry(l,{signal:i});if(!e.ok)throw new Error("Overpass request failed");const t=(await e.json()).elements.map(this.normalizePoi);return this.lastQueryKey=n,this.cachedResults=t,t}catch(c){if("AbortError"===c.name)return console.debug("Overpass request aborted"),[];throw c}}async getCategoryPois(e,t,r,n){const i=getCategoryById(t);if(!i||!e)return[];const o=r&&n?`cat:${t}:${r}:${n}`:null;if(o&&this.lastQueryKey===o&&this.cachedResults)return console.debug("Returning cached category results for:",o),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const s=this.controller.signal,{minLat:a,minLon:l,maxLat:c,maxLon:u}=e,h=[],d=i.types||["node","way","relation"];i.filter.forEach(e=>{d.forEach(t=>{h.push(`${t}${e}[~"^name"~"."];`)})});const p=`\n[out:json][timeout:25][bbox:${a},${l},${c},${u}];\n(\n ${h.join("\n ")}\n);\nout center;\n `.trim(),f=`${this.settings.overpassApi}?data=${encodeURIComponent(p)}`;try{const e=await this.fetchWithRetry(f,{signal:s});if(!e.ok)throw new Error("Overpass request failed");const t=(await e.json()).elements.map(this.normalizePoi);return o&&(this.lastQueryKey=o,this.cachedResults=t),t}catch(g){if("AbortError"===g.name)return console.debug("Category search aborted"),[];throw console.error("Category search failed",g),g}}normalizePoi(e){const t=e.tags||{},r=getPlaceType(t)||"Point of Interest";return{title:getLocalizedName(t),lat:e.lat||e.center?.lat,lon:e.lon||e.center?.lon,url:t.website,osmId:String(e.id),osmType:e.type,osmTags:t,description:t.description,source:"osm",type:r}}async fetchWithRetry(e,t={},r=3){try{const n=await fetch(e,t);return!n.ok&&r>0&&[502,503,504,429].includes(n.status)?(console.warn(`Overpass request failed with ${n.status}. Retrying... (${r} left)`),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1)):n}catch(n){if(r>0&&"AbortError"!==n.name)return console.debug(`Retrying Overpass request... (${r} left)`),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1);throw n}}async getPoiById(e,t=null){let r;r="node"===t?`[out:json][timeout:25];node(${e});out center;`:"way"===t?`[out:json][timeout:25];way(${e});out center;`:`\n[out:json][timeout:25];\n(\n node(${e});\n way(${e});\n);\nout center;\n `.trim();const n=`${this.settings.overpassApi}?data=${encodeURIComponent(r)}`,i=await this.fetchWithRetry(n);if(!i.ok)throw new Error("Overpass request failed");const o=await i.json();return o.elements[0]?this.normalizePoi(o.elements[0]):null}async fetchOsmObject(e,t){if(!e||!t)return null;const r=`${t}:${e}`,n=this.cachedPlaces.get(r);if(n&&Date.now()-n.timestamp<1e4)return console.debug(`Using in-memory cached OSM object for ${r}`),n.data;let i;if("node"===t)i=`https://www.openstreetmap.org/api/0.6/node/${e}.json`;else if("way"===t)i=`https://www.openstreetmap.org/api/0.6/way/${e}/full.json`;else{if("relation"!==t)return console.error("Unknown OSM type:",t),null;i=`https://www.openstreetmap.org/api/0.6/relation/${e}/full.json`}try{const n=await this.fetchWithRetry(i);if(!n.ok){if(410===n.status)return console.warn("OSM object has been deleted"),null;throw new Error(`OSM API request failed: ${n.status}`)}const o=await n.json(),s=this.normalizeOsmApiData(o.elements,e,t);return this.cachedPlaces.set(r,{data:s,timestamp:Date.now()}),setTimeout(()=>{this.cachedPlaces.delete(r)},1e4),s}catch(o){return console.error("Failed to fetch OSM object:",o),null}}normalizeOsmApiData(e,t,r){if(!e||0===e.length)return null;let n=e.find(e=>String(e.id)===String(t)&&e.type===r);if(!n)return null;let i=n;if("relation"===r&&n.members){const t=n.members.find(e=>"label"===e.role&&"node"===e.type),r=n.members.find(e=>"admin_centre"===e.role&&"node"===e.type),o=t||r;if(o){const t=e.find(e=>String(e.id)===String(o.ref)&&"node"===e.type);t&&(i=t)}}let o=i.lat,s=i.lon,a=null,l=null;if("way"===r&&n.nodes){const t=new Map;e.forEach(e=>{"node"===e.type&&t.set(e.id,[e.lon,e.lat])});const r=n.nodes.map(e=>t.get(e)).filter(Boolean);if(r.length>0){if(i===n){const e=r.reduce((e,t)=>e+t[1],0),t=r.reduce((e,t)=>e+t[0],0);o=e/r.length,s=t/r.length}const e=r.map(e=>e[1]),t=r.map(e=>e[0]);if(a={minLat:Math.min(...e),maxLat:Math.max(...e),minLon:Math.min(...t),maxLon:Math.max(...t)},r.length>1){const e=r[0],t=r[r.length-1];l=e[0]===t[0]&&e[1]===t[1]?{type:"Polygon",coordinates:[r]}:{type:"LineString",coordinates:r}}}}else if("relation"===r&&n.members){const t=[],r=new Map;e.forEach(e=>{"node"===e.type&&r.set(e.id,e)});const c=[];if(n.members.forEach(n=>{if("node"===n.type){const e=r.get(n.ref);e&&t.push(e)}else if("way"===n.type){const i=e.find(e=>"way"===e.type&&e.id===n.ref);if(i&&i.nodes){const e=[];i.nodes.forEach(n=>{const i=r.get(n);i&&(t.push(i),e.push([i.lon,i.lat]))}),e.length>1&&c.push(e)}}}),t.length>0){if(i===n){const e=t.reduce((e,t)=>e+t.lat,0),r=t.reduce((e,t)=>e+t.lon,0);o=e/t.length,s=r/t.length}const e=t.map(e=>e.lat),r=t.map(e=>e.lon);a={minLat:Math.min(...e),maxLat:Math.max(...e),minLon:Math.min(...r),maxLon:Math.max(...r)}}c.length>0&&(l={type:"MultiLineString",coordinates:c})}const c=i.tags||{},u=getPlaceType(c)||"Point of Interest";return{title:getLocalizedName(c),lat:o,lon:s,bbox:a,geojson:l,url:c.website,osmId:String(i.id),osmType:i.type,osmTags:c,description:c.description,source:"osm",type:u}}}const amdModule11=Object.freeze(Object.defineProperty({__proto__:null,default:OsmService},Symbol.toStringTag,{value:"Module"}));class PhotonService extends Service{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");controller=null;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}get baseUrl(){return this.settings.photonApi}async search(e,t,r,n=10){if(!e||e.length<2)return[];this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,o=new URLSearchParams({q:e,limit:String(n)});t&&r&&(o.append("lat",parseFloat(t).toFixed(4)),o.append("lon",parseFloat(r).toFixed(4)));const s=`${this.baseUrl}?${o.toString()}`;try{const e=await this.fetchWithRetry(s,{signal:i});if(!e.ok)throw new Error(`Photon request failed with status ${e.status}`);const t=await e.json();return t.features?t.features.map(e=>this.normalizeFeature(e)):[]}catch(a){return"AbortError"===a.name||console.error("Photon search error:",a),[]}}normalizeFeature(e){const t=e.properties||{},r=(e.geometry||{}).coordinates||[],n=r[0],i=r[1],o=[];t.street&&o.push(t.housenumber?`${t.street} ${t.housenumber}`:t.street),t.city&&t.city!==t.name&&o.push(t.city),t.state&&t.state!==t.city&&o.push(t.state),t.country&&o.push(t.country);const s=o.join(", "),a=t.name||s||"Unknown Place",l={...t};t.osm_key&&t.osm_value&&(l[t.osm_key]=t.osm_value);const c=getPlaceType(l)||humanizeOsmTag$1(t.osm_value);return{title:a,lat:i,lon:n,osmId:t.osm_id,osmType:{N:"node",W:"way",R:"relation"}[t.osm_type]||t.osm_type,osmTags:l,description:t.name?s:o.slice(1).join(", "),source:"photon",type:c}}async fetchWithRetry(e,t={},r=3){try{const n=await fetch(e,t);return!n.ok&&r>0&&[502,503,504,429].includes(n.status)?(console.warn(`Photon request failed with ${n.status}. Retrying... (${r} left)`),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1)):n}catch(n){if(r>0&&"AbortError"!==n.name)return console.debug(`Retrying Photon request... (${r} left)`,n),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1);throw n}}}const amdModule12=Object.freeze(Object.defineProperty({__proto__:null,default:PhotonService},Symbol.toStringTag,{value:"Module"})),DEFAULT_SETTINGS={overpassApi:"https://overpass-api.de/api/interpreter",mapKinetic:!0,photonApi:"https://photon.komoot.io/api/",showQuickSearchButtons:!0,nostrPhotoFallbackUploads:!1,nostrReadRelays:null,nostrWriteRelays:null};class SettingsService extends Service{static{decorateFieldV2(this.prototype,"overpassApi",[tracked],function(){return DEFAULT_SETTINGS.overpassApi})}#ne=void initializeDeferredDecorator(this,"overpassApi");static{decorateFieldV2(this.prototype,"mapKinetic",[tracked],function(){return DEFAULT_SETTINGS.mapKinetic})}#ie=void initializeDeferredDecorator(this,"mapKinetic");static{decorateFieldV2(this.prototype,"photonApi",[tracked],function(){return DEFAULT_SETTINGS.photonApi})}#oe=void initializeDeferredDecorator(this,"photonApi");static{decorateFieldV2(this.prototype,"showQuickSearchButtons",[tracked],function(){return DEFAULT_SETTINGS.showQuickSearchButtons})}#se=void initializeDeferredDecorator(this,"showQuickSearchButtons");static{decorateFieldV2(this.prototype,"nostrPhotoFallbackUploads",[tracked],function(){return DEFAULT_SETTINGS.nostrPhotoFallbackUploads})}#ae=void initializeDeferredDecorator(this,"nostrPhotoFallbackUploads");static{decorateFieldV2(this.prototype,"nostrReadRelays",[tracked],function(){return DEFAULT_SETTINGS.nostrReadRelays})}#le=void initializeDeferredDecorator(this,"nostrReadRelays");static{decorateFieldV2(this.prototype,"nostrWriteRelays",[tracked],function(){return DEFAULT_SETTINGS.nostrWriteRelays})}#ce=void initializeDeferredDecorator(this,"nostrWriteRelays");overpassApis=[{name:"overpass-api.de (DE)",url:"https://overpass-api.de/api/interpreter"},{name:"private.coffee (AT)",url:"https://overpass.private.coffee/api/interpreter"}];photonApis=[{name:"photon.komoot.io",url:"https://photon.komoot.io/api/"}];constructor(){super(...arguments),this.loadSettings()}loadSettings(){let e={};const t=localStorage.getItem("marco:settings");if(t)try{e=JSON.parse(t)}catch(n){console.error("Failed to parse settings from localStorage",n)}else{const t=localStorage.getItem("marco:overpass-api");t&&(e.overpassApi=t);const r=localStorage.getItem("marco:map-kinetic");null!==r&&(e.mapKinetic="true"===r);const n=localStorage.getItem("marco:show-quick-search");null!==n&&(e.showQuickSearchButtons="true"===n);const i=localStorage.getItem("marco:nostr-photo-fallback-uploads");null!==i&&(e.nostrPhotoFallbackUploads="true"===i);const o=localStorage.getItem("marco:photon-api");o&&(e.photonApi=o)}const r={...DEFAULT_SETTINGS,...e};this.overpassApis.some(e=>e.url===r.overpassApi)||(r.overpassApi=DEFAULT_SETTINGS.overpassApi),this.overpassApi=r.overpassApi,this.mapKinetic=r.mapKinetic,this.photonApi=r.photonApi,this.showQuickSearchButtons=r.showQuickSearchButtons,this.nostrPhotoFallbackUploads=r.nostrPhotoFallbackUploads,this.nostrReadRelays=r.nostrReadRelays,this.nostrWriteRelays=r.nostrWriteRelays,this.saveSettings()}saveSettings(){const e={overpassApi:this.overpassApi,mapKinetic:this.mapKinetic,photonApi:this.photonApi,showQuickSearchButtons:this.showQuickSearchButtons,nostrPhotoFallbackUploads:this.nostrPhotoFallbackUploads,nostrReadRelays:this.nostrReadRelays,nostrWriteRelays:this.nostrWriteRelays};localStorage.setItem("marco:settings",JSON.stringify(e))}update(e,t){e in DEFAULT_SETTINGS&&(this[e]=t,this.saveSettings())}}const amdModule13=Object.freeze(Object.defineProperty({__proto__:null,default:SettingsService},Symbol.toStringTag,{value:"Module"}));var remotestorage$2={exports:{}},remotestorage$1=remotestorage$2.exports,hasRequiredRemotestorage; -/*! For license information please see remotestorage.js.LICENSE.txt */function requireRemotestorage(){return hasRequiredRemotestorage||(hasRequiredRemotestorage=1,function(module,exports$1){var t;t=function(){return function(){var __webpack_modules__={548:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Access=void 0;class r{constructor(e){this.rs=e,this.reset(!1)}get scopes(){return Object.keys(this.scopeModeMap).map(e=>({name:e,mode:this.scopeModeMap[e]}))}get scopeParameter(){return this.scopes.map(e=>`${this._scopeNameForParameter(e)}:${e.mode}`).join(" ")}claim(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if("string"!=typeof t||!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t,this._notifyChange()}get(e){return this.scopeModeMap[e]}remove(e){const t={};for(const r in this.scopeModeMap)t[r]=this.scopeModeMap[r];this.reset(!1),delete t[e];for(const r in t)this._adjustRootPaths(r),this.scopeModeMap[r]=t[r];this._notifyChange()}checkPermission(e,t){const r=this.get(e);return r&&("r"===t||"rw"===r)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const r=this._getModuleName(e);return!!this.checkPermission(r,t)}reset(e=!0){this.rootPaths=[],this.scopeModeMap={},e&&this._notifyChange()}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name}setStorageType(e){this.storageType=e}_notifyChange(){this.rs&&"function"==typeof this.rs._checkScopeChange&&this.rs._checkScopeChange()}static _rs_init(){}}t.Access=r,t.default=r},275:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Authorize=void 0;const o=i(r(28)),s=i(r(334)),a=r(746),l=i(r(503)),c=r(368);let u;function h(e){const t=e||d.getLocation().href,r={};for(const[o,s]of new URL(t).searchParams)r[o]=s;const n=t.indexOf("#");if(-1===n)return r;const i=t.substring(n+1);return i.includes("=")?i.split("&").reduce(function(e,t){const r=t.split("=");if("state"===r[0]&&r[1].match(/rsDiscovery/)){let t=decodeURIComponent(r[1]);const n=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(n)),t=t.replace(new RegExp("&?rsDiscovery="+n),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e},r):r}class d{static authorize(e,t){if((0,s.default)("[Authorize] authURL = ",t.authURL,"scope = ",t.scope,"redirectUri = ",t.redirectUri,"clientId = ",t.clientId,"response_type =",t.response_type),!t.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if("function"==typeof e._rememberPendingScope&&e._rememberPendingScope(t.scope),!(0,a.localStorageAvailable)()&&"remotestorage"===e.backend){t.redirectUri+=t.redirectUri.indexOf("#")>0?"&":"#";const r={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};t.redirectUri+="rsDiscovery="+(0,a.toBase64)(JSON.stringify(r))}const r=function(e){const t=new URL(e.redirectUri);e.state||(e.state=t.hash?t.hash.substring(1):""),e.response_type||(e.response_type="token");const r=new URL(e.authURL);r.searchParams.set("redirect_uri",e.redirectUri.replace(/#.*$/,"")),r.searchParams.set("scope",e.scope),r.searchParams.set("client_id",e.clientId);for(const n of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const t=e[n];t&&r.searchParams.set(n,t)}return r.href}(t);a.globalContext.cordova&&(d.getLocation().href.startsWith("file:")||"string"==typeof o.default.cordovaRedirectUri&&t.redirectUri===o.default.cordovaRedirectUri)?d.openWindow(r,t.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then(r=>{e.remote.configure({token:r.access_token}),"function"==typeof e._completeAuthorization&&e._completeAuthorization(r.scope||t.scope)}):d.setLocation(r)}static refreshAccessToken(e,t,r){return n(this,void 0,void 0,function*(){var e,n,i;yield t.configure({token:null,tokenType:null});const o=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:r}),a=yield(0,c.requestWithTimeout)("POST",t.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),responseType:"json"});if(200!==(null==a?void 0:a.status))throw yield t.configure({refreshToken:null}),new l.default("refresh token rejected:"+JSON.stringify(a.response));{(0,s.default)(`[Authorize] access token good for ${null===(e=null==a?void 0:a.response)||void 0===e?void 0:e.expires_in} seconds`);const r={token:null===(n=null==a?void 0:a.response)||void 0===n?void 0:n.access_token,tokenType:null===(i=null==a?void 0:a.response)||void 0===i?void 0:i.token_type};if(!r.token)throw new Error(`no access_token in "successful" refresh: ${a.response}`);yield t.configure(r)}})}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location.href=e.href}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",u)}}t.Authorize=d,d.IMPLIED_FAKE_TOKEN=!1,d.getLocation=function(){return document.location},d.openWindow=function(e,t,r){return new Promise((n,i)=>{const o=open(e,"_blank",r);function s(){i("Authorization was canceled")}o&&!o.closed?(o.addEventListener("loadstart",function(e){if(0!==e.url.indexOf(t))return;o.removeEventListener("exit",s),o.close();const r=h(e.url);r?n(r):i("Authorization error")}),o.addEventListener("exit",s)):i("Authorization popup was blocked")})},d._rs_init=function(e){const t=h(),r=function(e){return"string"==typeof e.access_token||"string"==typeof e.code||"string"==typeof e.error||"string"==typeof e.remotestorage||"object"==typeof e.rsDiscovery}(t);let i;r&&(i=d.getLocation(),i.hash=""),u=function(){let o=!1;if(r){if(t.error)throw"function"==typeof e._forgetPendingScope&&e._forgetPendingScope(),"access_denied"===t.error?new l.default("Authorization failed: access denied",{code:"access_denied"}):new l.default(`Authorization failed: ${t.error}`);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),"function"==typeof e._completeAuthorization&&e._completeAuthorization(t.scope),o=!0),t.remotestorage&&(e.connect(t.remotestorage),o=!0),t.state&&(i=d.getLocation(),d.setLocation(i.href.split("#")[0]+"#"+t.state)),t.code&&(function(t){n(this,void 0,void 0,function*(){var r,n,o,a,l;const u=sessionStorage.getItem("remotestorage:codeVerifier");if(!u)return void(0,s.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");i=d.getLocation();let h=i.origin;"/"!==i.pathname&&(h+=i.pathname);const p=new URLSearchParams({code:t,grant_type:"authorization_code",client_id:e.remote.clientId,redirect_uri:h,code_verifier:u}),f=yield(0,c.requestWithTimeout)("POST",e.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:p.toString(),responseType:"json"});switch(f.status){case 200:{(0,s.default)(`[Authorize] access token good for ${null===(r=null==f?void 0:f.response)||void 0===r?void 0:r.expires_in} seconds`);const t={token:null===(n=null==f?void 0:f.response)||void 0===n?void 0:n.access_token,refreshToken:null===(o=null==f?void 0:f.response)||void 0===o?void 0:o.refresh_token,tokenType:null===(a=null==f?void 0:f.response)||void 0===a?void 0:a.token_type};t.token?(e.remote.configure(t),"function"==typeof e._completeAuthorization&&e._completeAuthorization(null===(l=null==f?void 0:f.response)||void 0===l?void 0:l.scope)):e._emit("error",new Error(`no access_token in "successful" response: ${f.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier");break}default:"function"==typeof e._forgetPendingScope&&e._forgetPendingScope(),e._emit("error",new Error(`${f.statusText}: ${f.response}`))}})}(t.code),o=!0),o||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",u)},t.default=d},424:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClient=void 0;const o=i(r(439)),s=i(r(613)),a=i(r(491)),l=i(r(93)),c=i(r(28)),u=r(746);class h{constructor(e,t){if(this.schemas={configurable:!0,get(){return h.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t,this.moduleName=function(e){const t=e.split("/");return e.length>2?t[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new h(this.storage,this.makePath(e))}getListing(e,t){return n(this,void 0,void 0,function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(e=>404===e.statusCode?{}:e.body)})}getAll(e,t){return n(this,void 0,void 0,function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(r=>{if(404===r.statusCode)return{};if("object"==typeof r.body){const n=Object.keys(r.body);if(0===n.length)return{};const i=n.map(n=>this.storage.get(this.makePath(e+n),t).then(e=>{if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"==typeof e.body&&(r.body[n]=e.body)}));return Promise.all(i).then(()=>r.body)}})})}getFile(e,t){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then(e=>({data:e.body,contentType:e.contentType,revision:e.revision}))})}storeFile(e,t,r){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'contentType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))})}getObject(e,t){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then(t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))})})}storeObject(e,t,r){return n(this,void 0,void 0,function*(){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{const e=this.validate(r);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))})}remove(e){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e),this.storage.connected))})}getItemURL(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=(0,u.cleanPath)(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this}declareType(e,t,r){let n;if(r&&"string"==typeof t)n=t;else if(r||"string"==typeof t){if(!r&&"string"==typeof t)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else r=t,n=this._defaultTypeURI(e);h.Types.declare(this.moduleName,e,n,r)}validate(e){const t=h.Types.getSchema(e["@context"]);if(t)return o.default.validateResult(e,t);throw new a.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=h.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){c.default.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach(function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}}),this._emit("change",e))}static _rs_init(){}}t.BaseClient=h,h.Types=s.default,(0,u.applyMixins)(h,[l.default]),t.default=h},285:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Caching=void 0;const i=r(746),o=n(r(334));class s{constructor(e){this.pendingActivations=[],this._access=e.access,this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!(0,i.isFolder)(e))throw new Error("path should be a folder");if(!this._access.checkPathPermission(e,"r"))throw new Error('No access to path "'+e+'". You must claim access to it first.');if(void 0===t||!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))}enable(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){(0,o.default)("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t{this.emitChange(e.data)})}get(e,t,r){return n(this,void 0,void 0,function*(){return"number"==typeof t?this.getNodes((0,c.pathsFromRoot)(e)).then(n=>{const i=u(n[e]);return h(n,t)?r(e):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}}):this.getNodes([e]).then(t=>{const r=u(t[e]);if(r){if((0,c.isFolder)(e))for(const e in r.itemsMap)r.itemsMap.hasOwnProperty(e)&&!1===r.itemsMap[e]&&delete r.itemsMap[e];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}})})}put(e,t,r){return n(this,void 0,void 0,function*(){const n=(0,c.pathsFromRoot)(e);return this._updateNodes(n,function(e,n){try{for(let i=0,o=e.length;i0)break}else console.error("Cannot delete non-existing node "+i)}return r})})}flush(e){return this._getAllDescendentPaths(e).then(e=>this.getNodes(e)).then(e=>{for(const t in e){const r=e[t];r&&r.common&&r.local&&this.emitChange({path:r.path,origin:"local",oldValue:!1===r.local.body?void 0:r.local.body,newValue:!1===r.common.body?void 0:r.common.body}),e[t]=void 0}return this.setNodes(e)})}emitChange(e){a.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){a.default.changeEvents.local&&this.forAllNodes(e=>{if((0,c.isDocument)(e.path)){const t=u(e);t&&this.emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}}).then(()=>{this._emit("local-events-done")})}onDiff(e){this.diffHandler=e}_updateNodes(e,t){return new Promise((r,n)=>{this._doUpdateNodes(e,t,{resolve:r,reject:n})})}_doUpdateNodes(e,t,r){return n(this,void 0,void 0,function*(){if(this._updateNodesRunning)return void this._updateNodesQueued.push({paths:e,cb:t,promise:r});this._updateNodesRunning=!0;try{let n=yield this.getNodes(e);const i=(0,c.deepClone)(n),o=[];n=t(e,n);for(const e in n){const t=n[e];(0,c.equal)(t,i[e])?delete n[e]:(0,c.isDocument)(e)&&((0,c.equal)(t.local.body,t.local.previousBody)&&t.local.contentType===t.local.previousContentType||o.push({path:e,origin:"window",oldValue:t.local.previousBody,newValue:!1===t.local.body?void 0:t.local.body,oldContentType:t.local.previousContentType,newContentType:t.local.contentType}),void 0===t.local.body?n[e]=void 0:(delete t.local.previousBody,delete t.local.previousContentType))}yield this.setNodes(n),this._emitChangeEvents(o),r.resolve({statusCode:200})}catch(e){r.reject(e)}this._updateNodesRunning=!1;const n=this._updateNodesQueued.shift();n&&(yield this._doUpdateNodes(n.paths,n.cb,n.promise))})}_emitChangeEvents(e){for(let t=0,r=e.length;t{const r=[e],n=u(t[e]),i=Object.keys(n.itemsMap).map(t=>this._getAllDescendentPaths(e+t).then(e=>{for(let t=0,n=e.length;tr)}):Promise.resolve([e])}_getInternals(){return{getLatest:u,makeNode:d,isOutdated:h}}}(0,c.applyMixins)(f,[s.default]),e.exports=f},28:function(e){e.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},373:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(713)),o=n(r(28)),s=n(r(334)),a=r(746);let l;const c="remotestorage:discover";let u={};const h=function(e){if(e in u)return Promise.resolve(u[e]);const t=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:o.default.discoveryTimeout});let r;const n=new Promise((e,t)=>{r=setTimeout(()=>{t(new Error("timed out"))},o.default.discoveryTimeout)});return Promise.race([t.lookup(e),n]).then(t=>{if(clearTimeout(r),"object"!=typeof t.idx.links.remotestorage||"number"!=typeof t.idx.links.remotestorage.length||t.idx.links.remotestorage.length<=0)throw(0,s.default)("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(t.object)),new Error("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const n=t.idx.links.remotestorage[0],i=n.properties||{},o=i["http://tools.ietf.org/html/rfc6749#section-4.2"]||i["auth-endpoint"],a=i["http://remotestorage.io/spec/version"]||n.type;return u[e]={href:n.href,storageApi:a,authURL:o,properties:i},l&&localStorage.setItem(c,JSON.stringify({cache:u})),u[e]}).catch(e=>{throw clearTimeout(r),e})};(h.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),h.DiscoveryError.prototype.constructor=h.DiscoveryError,h._rs_init=function(){if(l=(0,a.localStorageAvailable)(),l){const e=JSON.parse(localStorage.getItem(c));e&&(u=e.cache)}},h._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},h._rs_cleanup=function(){l&&localStorage.removeItem(c)},e.exports=h},706:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(424)),a=i(r(941)),l=i(r(982)),c=i(r(503)),u=r(746),h=r(368),d=r(684),p=i(r(275));let f;const g="remotestorage:dropbox",m="https://api.dropboxapi.com/2/files/list_folder",y="https://api.dropboxapi.com/2/files/list_folder/continue",b="/remotestorage";function v(e){return(b+"/"+e).replace(/\/+$/,"").replace(/\/+/g,"/")}const _=/[\u007f-\uffff]/g;function E(e){return JSON.stringify(e).replace(_,function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)})}function w(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function C(e){return e instanceof ArrayBuffer||(0,h.isArrayBufferView)(e)}class S extends d.RemoteBase{constructor(e){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},f=(0,u.localStorageAvailable)(),f){const e=(0,u.getJSONFromLocalStorage)(g);e&&this.configure(e),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return n(this,void 0,void 0,function*(){try{if(this.rs.setBackend("dropbox"),this.token)R(this.rs);else{const{codeVerifier:e,codeChallenge:t,state:r}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",e),sessionStorage.setItem("remotestorage:state",r),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:r,code_challenge:t,code_challenge_method:"S256",token_access_type:"offline"})}}catch(e){throw this.rs._emit("error",e),this.rs.setBackend(void 0),e}})}configure(e){return n(this,void 0,void 0,function*(){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token),void 0!==e.refreshToken&&(this.refreshToken=e.refreshToken),void 0!==e.tokenType&&(this.tokenType=e.tokenType);const t=()=>{f&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),t();else try{const e=yield this.info();this.userAddress=e.email,this._emit("connected"),t()}catch(e){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),t.apply(this)}else(()=>{this.connected=!1,f&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()})}_getFolder(e){const t=this._revCache,r=r=>{let i;if(200!==r.status&&409!==r.status)return Promise.reject("Unexpected response status: "+r.status);try{i=JSON.parse(r.responseText)}catch(e){return Promise.reject(e)}if(409===r.status)return w(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const o=i.entries.reduce((r,n)=>{try{const i="folder"===n[".tag"],o=n.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)r[o]={ETag:t.get(e+o)};else{const t=new Date(n.server_modified);r[o]={ETag:n.rev,"Content-Length":n.size,"Last-Modified":t.toUTCString()},this._revCache.set(e+o,n.rev)}}catch(t){console.error(`[Dropbox] folder “${e}” has entry ${JSON.stringify(n)}:`,t)}return r},{});return i.has_more?n(i.cursor).then(function(e){return Object.assign(o,e)}):Promise.resolve(o)},n=e=>{const t={body:{cursor:e}};return this._request("POST",y,t).then(r)};return this._request("POST",m,{body:{path:v(e)}}).then(r).then(function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})})}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r=this._revCache.get(e);if(null===r)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then(()=>this.get(e,t));if(r&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.slice(-1))return this._getFolder(e);const n={headers:{"Dropbox-API-Arg":E({path:v(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(n.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",n).then(t=>{const r=t.status;let n,i,o,s;return 200!==r&&409!==r?Promise.resolve({statusCode:r}):(n=t.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(t.response,"UTF-8").then(a=>{i=a,409===r&&(n=i);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===r)return w(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(o=t.getResponseHeader("Content-Type"),s=n.rev,this._revCache.set(e,s),this._shareIfNeeded(e),(0,u.shouldBeTreatedAsBinary)(a,o))i=t.response;else try{i=JSON.parse(i),o="application/json; charset=UTF-8"}catch(e){}return{statusCode:r,body:i,contentType:o,revision:s}}))})}put(e,t,r){return n(this,arguments,void 0,function*(e,t,r,n={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const i=this._revCache.get(e);if(n&&n.ifMatch&&i&&i!==n.ifMatch)return{statusCode:412,revision:i};if(n&&"*"===n.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!r.match(/charset=/)&&C(t)&&(r+="; charset=binary"),t.length>157286400)throw new Error("Cannot upload file larger than 150MB");const o={body:t,contentType:r,path:e};if(n&&(n.ifMatch||"*"===n.ifNoneMatch)){const t=yield this._getMetadata(e);if(n&&"*"===n.ifNoneMatch&&t)return{statusCode:412,revision:t.rev};if(n&&n.ifMatch&&t&&t.rev!==n.ifMatch)return{statusCode:412,revision:t.rev}}const s=yield this._uploadSimple(o);return this._shareIfNeeded(e),s})}delete(e){return n(this,arguments,void 0,function*(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const r=this._revCache.get(e);if((null==t?void 0:t.ifMatch)&&r&&t.ifMatch!==r)return{statusCode:412,revision:r};if(null==t?void 0:t.ifMatch){const r=yield this._getMetadata(e);if((null==t?void 0:t.ifMatch)&&r&&r.rev!==t.ifMatch)return{statusCode:412,revision:r.rev}}return this._deleteSimple(e)})}_shareIfNeeded(e){if(e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e])return this.share(e)}share(e){const t={body:{path:v(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?w(r,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+r.error_summary)):Promise.resolve(r.url)}).then(t=>(this._itemRefs[e]=t,f&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t)),t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t)))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then(function(e){let t;try{const r=JSON.parse(e.responseText);t=null==r?void 0:r.email}catch(t){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+e.responseText))}return Promise.resolve({email:t})})}_request(e,t,r){return n(this,arguments,void 0,function*(e,t,r,n=1){if(this.isForbiddenRequestMethod(e,t))throw`Don't use ${e} on directories!`;if(!this.token)throw new c.default("No access token");r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!=typeof r.body||C(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)});try{const i=yield(0,h.requestWithTimeout)(e,t,r);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?n>=3?(console.error(`Abandoned after ${n} attempts: ${e} ${t}`),i):(this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)}),yield p.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),this._request(e,t,r,n+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),n>=3?(console.warn(`Abandoned after ${n} attempts: ${e} ${t}`),i):(yield new Promise(e=>setTimeout(e,(0,h.retryAfterMs)(i))),this._request(e,t,r,n+1))):i}catch(r){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!1}),r}})}fetchDelta(...e){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const t=e=>n(this,void 0,void 0,function*(){let r,n;"string"==typeof e?(r=y,n={cursor:e}):(r=m,n={path:b,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",r,{body:n});if(401===i.status)throw new c.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let o;try{o=JSON.parse(i.responseText)}catch(e){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!w(o,["path","not_found"]))throw new Error("API returned an error: "+o.error_summary);o={cursor:null,entries:[],has_more:!1}}if(e||this._revCache.deactivatePropagation(),o.entries.forEach(e=>{const t=e.path_display.slice(14);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)}),this._fetchDeltaCursor=o.cursor,o.has_more)return t(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(e){if("timeout"===e)return;throw e}});return this._fetchDeltaPromise=t(this._fetchDeltaCursor).catch(e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e=`Dropbox: fetchDelta: ${e}`,this.rs._emit("error",e),this._fetchDeltaPromise=null,Promise.reject(e))).then(()=>(this._fetchDeltaPromise=null,Promise.resolve(e))),this._fetchDeltaPromise}_getMetadata(e){const t={path:v(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?w(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)}).then(void 0,t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_uploadSimple(e){const t={path:v(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":E(t)}}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid API result: "+t.responseText))}return 409===t.status?w(r,["path","conflict"])?this._getMetadata(e.path).then(function(e){return Promise.resolve({statusCode:412,revision:e.rev})}):(this.rs._emit("error",new Error(r.error_summary)),Promise.resolve({statusCode:t.status})):(this._revCache.set(e.path,r.rev),Promise.resolve({statusCode:t.status,revision:r.rev}))})}_deleteSimple(e){const t={path:v(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}if(409===e.status){if(w(t,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(t.error_summary))}return Promise.resolve({statusCode:e.status})}).then(t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t)),t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_getSharedLink(e){return n(this,void 0,void 0,function*(){const t={body:{path:v(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+(null==t?void 0:t.error_summary)||0)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))},t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t)))})}static _rs_init(e){f=(0,u.localStorageAvailable)(),e.apiKeys.dropbox&&(e.dropbox=new S(e)),"dropbox"===e.backend&&R(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(e){(function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)})(e),function(e){e._dropboxOrigSync&&(e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}(e),function(e){e._origBaseClientGetItemURL&&(s.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),x(e)}(e),f&&localStorage.removeItem(g),e.setBackend(void 0)}}function T(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,function(t){e._emit("error",new l.default(t)),e._emit("sync-done",{completed:!1})})}.bind(e))}function x(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function R(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?T(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");T(e),e._dropboxOrigSyncCycle(e,...t),x(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=s.default.prototype.getItemURL,s.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}(0,u.applyMixins)(S,[o.default]),e.exports=S},451:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=r(746),s=n(r(334));class a{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?((0,s.default)("[Env] Going into background mode"),this.goBackground()):((0,s.default)("[Env] Going into foreground mode"),this.goForeground())}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,o.applyMixins)(a,[i.default]),e.exports=a},93:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandling=void 0;const i=n(r(334));class o{addEvents(e){e.forEach(e=>this._addEvent(e))}addEventListener(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const r=this._handlers[e].length;for(let n=0;n{e(...t)})}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,t=>{this._emit(e,t)})}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}t.EventHandling=o,t.default=o},545:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(28)),o=n(r(451)),s=n(r(334)),a=r(746),l=n(r(370)),c=n(r(548)),u=n(r(275)),h=n(r(373)),d=n(r(424)),p=n(r(801)),f=n(r(706)),g=n(r(600)),m=n(r(313)),y=n(r(285)),b=n(r(567)),v=n(r(794)),_=n(r(365)),E={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:g.default,Dropbox:f.default,GoogleDrive:p.default,Access:c.default,Discover:h.default,Authorize:u.default,BaseClient:d.default,Env:o.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:y.default,IndexedDB:b.default,LocalStorage:v.default,InMemoryStorage:_.default,Sync:m.default}),i.default.disableFeatures.forEach(e=>{this.featureModules[e]&&delete this.featureModules[e]}),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const t=this.featureModules[e],r=!t._rs_supported||t._rs_supported();(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof r?r.then(()=>{this.featureSupported(e,!0),this.initFeature(e)},()=>{this.featureSupported(e,!1)}):"boolean"==typeof r?(this.featureSupported(e,r),r&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const t=this.featureModules[e];let r;try{r=t._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof r&&"function"==typeof r.then?r.then(()=>{this.featureInitialized(e)},t=>{this.featureFailed(e,t)}):this.featureInitialized(e)},featureFailed(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some(e=>{if(this.features.some(t=>t.name===e))return this.features.local=this.featureModules[e],!0})},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){(0,s.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(l.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",()=>{this._fireReady(),this._emit("connected")}),this.remote.on("not-connected",()=>{this._fireReady(),this._emit("not-connected")}),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){(0,a.logError)(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e=r-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class b extends l.RemoteBase{constructor(e,t){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=t,this._fileIdCache=new y(300),d=(0,s.localStorageAvailable)(),d){const e=(0,s.getJSONFromLocalStorage)(u);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){d&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,delete this.token,d&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then(e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)}).catch(()=>{r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))})):r.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(e,t={}){return(0,s.isFolder)(e)?this._getFolder(m(e)):this._getFile(m(e),t)}put(e,t,r,n={}){const i=m(e);function o(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),r=this.stripQuotes(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(i).then(e=>e?n&&"*"===n.ifNoneMatch?o({status:412}):this._updateFile(e,i,t,r,n).then(o):this._createFile(i,t,r).then(o))}delete(e,t={}){const r=m(e);return this._getFileId(r).then(e=>e?this._getMeta(e).then(r=>{let n;return"object"==typeof r&&"string"==typeof r.etag&&(n=this.stripQuotes(r.etag)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:this._request("DELETE",c+"/drive/v2/files/"+e,{}).then(e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")"))}):Promise.resolve({statusCode:200}))}info(){const e=c+"/drive/v2/about?fields=user";return this._request("GET",e,{}).then(function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}})}_updateFile(e,t,r,n,i){const o={mimeType:n},s={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(s["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",c+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(o),headers:s}).then(e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r}))}_createFile(e,t,r){return this._getParentId(e).then(n=>{const i={title:p(g(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:n}]};return this._request("POST",c+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>this._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t}))})}_getFile(e,t){return this._getFileId(e).then(e=>this._getMeta(e).then(e=>{let r;if("object"==typeof e&&"string"==typeof e.etag&&(r=this.stripQuotes(e.etag)),t&&t.ifNoneMatch&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:r});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then(t=>(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then(function(n){let i=n;if(e.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(e){}else(0,s.shouldBeTreatedAsBinary)(n,e.mimeType)&&(i=t.response);return{statusCode:200,body:i,contentType:e.mimeType,revision:r}}))}))}_getFolder(e){return this._getFileId(e).then(t=>{let r,n,i;if(!t)return Promise.resolve({statusCode:404});const o="'"+t+"' in parents";return this._request("GET",c+"/drive/v2/files?q="+encodeURIComponent(o)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then(t=>{var o;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const a of r.items)(null===(o=a.labels)||void 0===o?void 0:o.trashed)||(n=this.stripQuotes(a.etag),a.mimeType===h?(this._fileIdCache.set(e+(0,s.cleanPath)(a.title)+"/",a.id),i[a.title+"/"]={ETag:n}):(this._fileIdCache.set(e+(0,s.cleanPath)(a.title),a.id),i[a.title]={ETag:n,"Content-Type":a.mimeType,"Content-Length":a.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})})})}_getParentId(e){const t=f(e);return this._getFileId(t).then(e=>e?Promise.resolve(e):this._createFolder(t))}_createFolder(e){return this._getParentId(e).then(t=>this._request("POST",c+"/drive/v2/files",{body:JSON.stringify({title:p(g(e)),mimeType:h,parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(f(e)).then(()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then(()=>this._getFileId(e)):Promise.resolve()))}_getMeta(e){return this._request("GET",c+"/drive/v2/files/"+e,{}).then(function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)})}_request(e,t,r){return this.isForbiddenRequestMethod(e,t)?Promise.reject(`Don't use ${e} on directories!`):(r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,a.requestWithTimeout)(e,t,r).then(r=>r&&401===r.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),Promise.resolve(r)),r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(r))))}static _rs_init(e){const t=e.apiKeys.googledrive;var r;t&&(e.googledrive=new b(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,s.applyMixins)(b,[o.default]),e.exports=b},567:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(496)),a=i(r(334)),l=r(746),c="remotestorage";let u;class h extends s.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(e){return n(this,void 0,void 0,function*(){const t=[],r={};for(let n=0,i=e.length;n0?this.getNodesFromDb(t).then(function(e){for(const t in r)e[t]=r[t];return e}):r})}setNodes(e){return n(this,void 0,void 0,function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;this.maybeFlush()})}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=r.g.setInterval(function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")},1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(e){return new Promise((t,r)=>{const n=this.db.transaction(["nodes"],"readonly"),i=n.objectStore("nodes"),o={};this.getsRunning++,e.map(e=>{i.get(e).onsuccess=t=>{o[e]=t.target.result}}),n.oncomplete=()=>{t(o),this.getsRunning--},n.onerror=n.onabort=()=>{r("get transaction error/abort"),this.getsRunning--}})}setNodesInDb(e){return n(this,void 0,void 0,function*(){return new Promise((t,r)=>{const n=this.db.transaction(["nodes"],"readwrite"),i=n.objectStore("nodes"),o=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting puts",e,this.putsRunning);for(const s in e){const t=e[s];if("object"==typeof t)try{i.put(t)}catch(e){throw(0,a.default)("[IndexedDB] Error while putting",t,e),e}else try{i.delete(s)}catch(e){throw(0,a.default)("[IndexedDB] Error while removing",i,t,e),e}}n.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished puts",e,this.putsRunning,(new Date).getTime()-o+"ms"),t()},n.onerror=()=>{this.putsRunning--,r("transaction error")},n.onabort=()=>{r("transaction abort"),this.putsRunning--}})})}reset(e){const t=this.db.name;this.db.close(),h.clean(t,()=>{h.open(t,(r,n)=>{r?(0,a.default)(`[IndexedDB] Error while resetting database ${t}:`,r):this.db=n,"function"==typeof e&&e(self)})})}forAllNodes(e){return n(this,void 0,void 0,function*(){return new Promise(t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=r=>{const n=r.target.result;n?(e(n.value),n.continue()):t()}})})}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const r=setTimeout(function(){t("timeout trying to open db")},1e4);try{const n=indexedDB.open(e,2);n.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){const t=n.result;(0,a.default)("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),t.objectStoreNames.contains("nodes")||((0,a.default)("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),t.objectStoreNames.contains("changes")||((0,a.default)("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"}))},n.onsuccess=function(){clearTimeout(r);const i=n.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),i.close(),void h.clean(e,function(){h.open(e,t)});t(null,n.result)}}catch(n){(0,a.default)("[IndexedDB] Failed to open database: "+n),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(r),h.clean(e,function(){h.open(e,t)})}}static clean(e,t){const r=indexedDB.deleteDatabase(e);r.onblocked=function(t){console.warn(`Deleting IndexedDB database "${e}" is blocked by another open connection`,t)},r.onsuccess=function(){(0,a.default)(`[IndexedDB] Deleted database "${e}"`),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise((t,r)=>{h.open(c,function(n,i){if(n)r(n);else{if(!i)return void r(new Error("IndexedDB opened without a database instance"));u=i,i.onerror=t=>{e._emit("error",h.eventToError(t))},t()}})})}static _rs_supported(){return new Promise((e,t)=>{const r=(0,l.getGlobalContext)();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{const r=indexedDB.open("rs-check");r.onerror=function(){t()},r.onsuccess=function(){r.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()})}static _rs_cleanup(e){return new Promise(t=>{e.local instanceof h&&e.local.closeDB(),h.clean(c,t)})}static eventToError(e){var t;const r=null==e?void 0:e.target,n=null==r?void 0:r.error;if(n)return n;if(null===(t=null==r?void 0:r.db)||void 0===t?void 0:t.name){const e=r.objectStoreNames,t=e?Array.from(e).join(", "):"";return new Error(`Error in store(s) “${t}” in database “${r.db.name}”`)}return new Error("Unknown IndexedDB error")}diffHandler(){}}(0,l.applyMixins)(h,[o.default]),e.exports=h},365:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=n(r(496)),s=r(746);class a extends o.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let r=0,n=e.length;r=2e3&&e<=36e5}var k;!function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(k||(k={}));class O{constructor(e){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=E.default.loadFeatures,this.features=E.default.features,this.loadFeature=E.default.loadFeature,this.featureSupported=E.default.featureSupported,this.featureDone=E.default.featureDone,this.featuresDone=E.default.featuresDone,this.featuresLoaded=E.default.featuresLoaded,this.featureInitialized=E.default.featureInitialized,this.featureFailed=E.default.featureFailed,this.hasFeature=E.default.hasFeature,this._setCachingModule=E.default._setCachingModule,this._collectCleanupFunctions=E.default._collectCleanupFunctions,this._fireReady=E.default._fireReady,this.initFeature=E.default.initFeature,"object"==typeof e&&(0,u.extend)(l.default,e),this.addEvents(["ready","authing","connecting","connected","disconnected","not-connected","conflict","error","features-loaded","scope-change-required","sync-interval-change","sync-started","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),S=(0,u.localStorageAvailable)(),S){this.apiKeys=(0,u.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const e=localStorage.getItem("remotestorage:backend");"dropbox"===e||"googledrive"===e?this.setBackend(e):this.setBackend("remotestorage")}this._authorizedScope=this._loadAuthorizedScope(),this._scopeChangeRequired=!1,this._scopeChangeEvent=null;const t=this.on;this.on=function(e,r){const n=t.call(this,e,r);if("scope-change-required"===e&&this._scopeChangeRequired&&this._scopeChangeEvent&&setTimeout(()=>{r(this._scopeChangeEvent)},0),this._allLoaded)switch(e){case"features-loaded":setTimeout(r,0);break;case"ready":this.remote&&setTimeout(r,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(r,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(r,0)}return n},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}get scopeChangeRequired(){return this._scopeChangeRequired}loadModules(){l.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),C.cordova&&"string"==typeof l.default.cordovaRedirectUri)e.redirectUri=l.default.cordovaRedirectUri;else{const t=d.default.getLocation();let r=t.origin;"/"!==t.pathname&&(r+=t.pathname),e.redirectUri=r}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),d.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),(0,c.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:d.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new O.DiscoveryError("Not a valid user address or URL."));else{if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e=`https://${e}`),C.cordova){if("string"!=typeof l.default.cordovaRedirectUri)return void this._emit("error",new O.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!C.cordova.InAppBrowser)return void this._emit("error",new O.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting"),O.Discover(e).then(r=>{if(this._emit("authing"),r.userAddress=e,this.remote.configure(r),!this.remote.connected)if(r.authURL)if(void 0===t)this.authorize({authURL:r.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");(0,c.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t}),this._rememberAuthorizedScope(this.access.scopeParameter)}else this.impliedauth()},()=>{this._emit("error",new O.DiscoveryError("No storage information found for this user address."))})}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}reauthorize(){this.reconnect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._forgetPendingScope(),this._rememberAuthorizedScope(null),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const e=this._cleanups.length;let t=0;const r=()=>{t++,t>=e&&(this._init(),(0,c.default)('Cleanups done, emitting "disconnected" event'),this._emit("disconnected"))};e>0?this._cleanups.forEach(e=>{const t=e(this);"object"==typeof t&&"function"==typeof t.then?t.then(r):r()}):r()}setBackend(e){if(this.backend=e,S&&(void 0!==e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend")),void 0===e)return this._authorizedScope=null,this._scopeChangeRequired=!1,void(this._scopeChangeEvent=null);this._authorizedScope=this._loadAuthorizedScope(),this._checkScopeChange()}_rememberPendingScope(e){const t=R(e);S&&(t&&this.backend?localStorage.setItem(x,JSON.stringify({backend:this.backend,scope:t})):localStorage.removeItem(x))}_forgetPendingScope(){S&&localStorage.removeItem(x)}_rememberAuthorizedScope(e){const t=R(e);return S?t&&this.backend?(localStorage.setItem(T,JSON.stringify({backend:this.backend,scope:t})),this._authorizedScope=t,void this._checkScopeChange()):(localStorage.removeItem(T),this._authorizedScope=null,void this._checkScopeChange()):(this._authorizedScope=t,void this._checkScopeChange())}_completeAuthorization(e){const t=this._loadPendingScope()||R(e);this._forgetPendingScope(),t?this._rememberAuthorizedScope(t):this._checkScopeChange()}_checkScopeChange(){const e=R(this.access.scopeParameter),t=this._authorizedScope||this._loadAuthorizedScope(),r=!(!e||!t||e===t),n=r&&(!this._scopeChangeRequired||!this._scopeChangeEvent||this._scopeChangeEvent.requestedScope!==e||this._scopeChangeEvent.authorizedScope!==t);this._scopeChangeRequired=r,r?(this._scopeChangeEvent=this._buildScopeChangeEvent(e,t),n&&this._emit("scope-change-required",this._scopeChangeEvent)):this._scopeChangeEvent=null}_loadAuthorizedScope(){if(!S||!this.backend)return null;const e=A(T);return e&&e.backend===this.backend?R(e.scope):null}_loadPendingScope(){if(!S||!this.backend)return null;const e=A(x);return e&&e.backend===this.backend?R(e.scope):null}_buildScopeChangeEvent(e=R(this.access.scopeParameter),t=this._authorizedScope){return{requestedScope:e||"",authorizedScope:t||"",reauthorize:this.reauthorize.bind(this)}}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){l.default.logging=!0}disableLog(){l.default.logging=!1}log(...e){c.default.apply(O,e)}setApiKeys(e){const t=[k.GOOGLE,k.DROPBOX];if("object"!=typeof e||!Object.keys(e).every(e=>t.includes(e)))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach(t=>{const r=e[t];if(r){switch(t){case k.DROPBOX:this.apiKeys[k.DROPBOX]={appKey:r},void 0!==this.dropbox&&this.dropbox.clientId===r||y.default._rs_init(this);break;case k.GOOGLE:this.apiKeys[k.GOOGLE]={clientId:r},void 0!==this.googledrive&&this.googledrive.clientId===r||m.default._rs_init(this)}return!0}delete this.apiKeys[t]}),S&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");l.default.cordovaRedirectUri=e}_setGPD(e,t){function r(e){return function(...r){return e.apply(t,r).then(I.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)}_pendingGPD(e){return(...t)=>{const r=Array.prototype.slice.call(t);return new Promise((t,n)=>{this._pending.push({method:e,args:r,promise:{resolve:t,reject:n}})})}}_processPending(){this._pending.forEach(e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}}),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach(r=>{const n=r.length;t.path.substr(0,n)===r&&this._pathHandlers[e][r].forEach(e=>{const n={};for(const r in t)n[r]=t[r];n.relativePath=t.path.replace(new RegExp("^"+r),"");try{e(n)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}})})}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestorage.io/rs.js/docs/api/access/classes/Access.html#claim"),new p.default(this,e)}getSyncInterval(){return l.default.syncInterval}setSyncInterval(e){if(!P(e))throw e+" is not a valid sync interval";const t=l.default.syncInterval;l.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return l.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!P(e))throw e+" is not a valid sync interval";const t=l.default.backgroundSyncInterval;l.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return l.default.isBackground?l.default.backgroundSyncInterval:l.default.syncInterval}getRequestTimeout(){return l.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";l.default.requestTimeout=e}setupSyncCycle(){this.sync&&!this.sync.stopped&&((0,c.default)("[Sync] Setting up sync cycle"),this.on("sync-done",()=>{(0,c.default)("[Sync] Sync done. Setting timer to",this.getCurrentSyncInterval()),this.sync&&!this.sync.stopped&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}),this.sync.sync())}startSync(){return l.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?((0,c.default)("[Sync] Stopping sync"),this.sync.stopped=!0):((0,c.default)("[Sync] Will instantiate sync stopped"),this.syncStopped=!0)}addModule(e){const t=e.name,r=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,r);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/\-[a-z]/g,function(e){return e[1].toUpperCase()});Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t)return t(new p.default(this,"/"+e+"/"),new p.default(this,"/public/"+e+"/")).exports;throw"Unknown module: "+e}}t.RemoteStorage=O,O.SyncError=v.default,O.Unauthorized=_.default,O.Discover=b.default,O.DiscoveryError=b.default.DiscoveryError,O.util=w,Object.defineProperty(O.prototype,"access",{configurable:!0,get:function(){const e=new h.default(this);return Object.defineProperty(this,"access",{value:e,writable:!0,configurable:!0}),e}}),Object.defineProperty(O.prototype,"caching",{configurable:!0,get:function(){const e=new f.default(this);return Object.defineProperty(this,"caching",{value:e,writable:!0,configurable:!0}),e}}),(0,u.applyMixins)(O,[g.EventHandling]),t.default=O},368:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayBufferView=void 0,t.retryAfterMs=function(e){const t=1e3*parseInt(e.getResponseHeader("Retry-After"));return t>=1e3?t:Math.max(1500,Math.min(6e4,Math.round(s.default.syncInterval/(2.9+.2*Math.random()))))},t.requestWithTimeout=function(e,r,i){return n(this,void 0,void 0,function*(){return"function"==typeof fetch?function(e,t,r){return n(this,void 0,void 0,function*(){const n="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise((e,t)=>{i=setTimeout(()=>{n&&n.abort(),t("timeout")},s.default.requestTimeout)});let l;const c={},u=fetch(t,{method:e,headers:r.headers,body:r.body,signal:n?n.signal:void 0}).then(e=>{switch((0,o.default)("[requests fetch]",e),e.headers.forEach((e,t)=>{c[t.toUpperCase()]=e}),l={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>c[e.toUpperCase()]||null,responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}}).then(e=>(l.response=e,r.responseType&&"text"!==r.responseType||(l.responseText=e),l)).finally(()=>{clearTimeout(i)});return Promise.race([u,a])})}(e,r,i):"function"==typeof XMLHttpRequest?function(e,r,i){return n(this,void 0,void 0,function*(){return new Promise((n,a)=>{(0,o.default)("[requests XHR]",e,r);let l=!1;const c=setTimeout(()=>{l=!0,a("timeout")},s.default.requestTimeout),u=new XMLHttpRequest;if(u.open(e,r,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const e in i.headers)u.setRequestHeader(e,i.headers[e]);u.onload=()=>{l||(clearTimeout(c),n(u))},u.onerror=e=>{l||(clearTimeout(c),a(e))};let h=i.body;"object"==typeof h&&!(0,t.isArrayBufferView)(h)&&h instanceof ArrayBuffer&&(h=new Uint8Array(h)),u.send(h)})})}(e,r,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")})};const o=i(r(334)),s=i(r(28));if("function"==typeof(r.g||window).ArrayBufferView)t.isArrayBufferView=function(e){return e&&e instanceof(r.g||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];t.isArrayBufferView=function(t){for(let r=0;r<8;r++)if(t instanceof e[r])return!0;return!1}}},941:function(e){e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let r=0;r0&&(r=this._generateHash(e))}return this.set(e,r),r}}},491:function(e){class t extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=t},982:function(e){class t extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=t},313:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Sync=void 0;const o=i(r(28)),s=i(r(451)),a=i(r(93)),l=i(r(334)),c=i(r(275)),u=i(r(982)),h=i(r(503)),d=r(746);let p,f;function g(e,t,r){return{action:e,path:t,promise:r}}function m(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function y(e){return!!e.common&&!!e.common.revision}class b{constructor(e){this.numThreads=10,this._tasks={},this._running={},this._timeStarted={},this._finishedTasks=[],this.rs=e,this.rs.local.onDiff(e=>{this.addTask(e),this.doTasks()}),this.rs.caching.onActivate(e=>{this.addTask(e),this.doTasks()}),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return n(this,void 0,void 0,function*(){return new Promise((t,r)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then(e=>t(e))}.bind(this)),this.doTasks()):r("cannot fulfill maxAge requirement - remote is not online"):r("cannot fulfill maxAge requirement - remote is not connected")})})}corruptServerItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e){const r=e[t];if("object"!=typeof r)return!0;if("string"!=typeof r.ETag)return!0;if((0,d.isFolder)(t)){if(-1!==t.substring(0,t.length-1).indexOf("/"))return!0}else if(-1!==t.indexOf("/"))return!0}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.keys(this._tasks).length>0}collectDiffTasks(){return n(this,void 0,void 0,function*(){let e=0;return this.rs.local.forAllNodes(t=>{e>100||(this.isCorrupt(t)?((0,l.default)("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||(0,d.isDocument)(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))}).then(()=>e)})}inConflict(e){return!(!e.local||!e.remote||void 0===e.remote.body&&!e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>o.default.syncInterval)}needsFetch(e){return!!this.inConflict(e)||!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)}needsPush(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}needsRemotePut(e){return!(!e.local||void 0===e.local.body||!1===e.local.body)}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=(0,d.pathsFromRoot)(e);for(let r=1;r{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(e){}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}}),this.deleteChildPathsFromTasks()})}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&((0,l.default)("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return n(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(t=>{const r=t[e];return void 0===r||function(e){return!(!e.remote||!e.remote.revision||e.remote.itemsMap||e.remote.body)}(r)?g("get",e,this.rs.remote.get(e)):this.needsRemotePut(r)?(r.push=(0,d.deepClone)(r.local),r.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then(()=>{let t;return t=y(r)?{ifMatch:r.common.revision}:{ifNoneMatch:"*"},g("put",e,this.rs.remote.put(e,r.push.body,r.push.contentType,t))})):this.needsRemoteDelete(r)?(r.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then(()=>y(r)?g("delete",e,this.rs.remote.delete(e,{ifMatch:r.common.revision})):g("get",e,this.rs.remote.get(e)))):y(r)?g("get",e,this.rs.remote.get(e,{ifNoneMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))})})}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);for(const t in e.local.itemsMap)e.common.itemsMap[t]||this.addTask(e.path+t);(0,d.equal)(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){var t;return function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote:void 0!==e.remote.body&&(!1===e.remote.body&&!1===(null===(t=e.local)||void 0===t?void 0:t.body)||((0,l.default)("[Sync] Emitting conflict event"),setTimeout(this.rs.local.emitChange.bind(this.rs.local),10,{origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType})),!1===e.remote.body?e.common={}:e.common=e.remote,delete e.remote,delete e.local),e}autoMerge(e){if(e.remote){if(e.local)return(0,d.isFolder)(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if((0,d.isFolder)(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if(void 0===t.oldValue&&void 0===t.newValue||this.rs.local.emitChange(t),!1===e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local.emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return n(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(r=>(r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(r))))})}markChildren(e,t,r,i){return n(this,void 0,void 0,function*(){const n=[],o={},s={};for(const r in t)n.push(e+r),o[e+r]=t[r];for(const t in i)n.push(e+t);const a=yield this.rs.local.getNodes(n);let l,c;for(const t in a)if(c=a[t],o[t])c&&c.common?m(c,o[t].ETag)&&(r[t]=(0,d.deepClone)(c),r[t].remote={revision:o[t].ETag,timestamp:this.now()},r[t]=this.autoMerge(r[t])):(l=this.rs.caching.checkPath(t),"ALL"===l&&(r[t]={path:t,common:{timestamp:this.now()},remote:{revision:o[t].ETag,timestamp:this.now()}})),r[t]&&o[t]["Content-Type"]&&(r[t].remote.contentType=o[t]["Content-Type"]),r[t]&&o[t]["Content-Length"]&&(r[t].remote.contentLength=o[t]["Content-Length"]);else if(i[t.substring(e.length)]&&c&&c.common){if(c.common.itemsMap)for(const e in c.common.itemsMap)s[t+e]=!0;if(c.local&&c.local.itemsMap)for(const e in c.local.itemsMap)s[t+e]=!0;if(c.remote||(0,d.isFolder)(t))r[t]=void 0;else if(r[t]=this.autoMerge(c),void 0===r[t]){const n=this.getParentPath(t),i=r[n],o=t.substring(e.length);i&&i.local&&(delete i.local.itemsMap[o],(0,d.equal)(i.local.itemsMap,i.common.itemsMap)&&delete i.local)}}const u=yield this.markRemoteDeletions(Object.keys(s),r);u&&(yield this.rs.local.setNodes(this.flush(u)))})}markRemoteDeletions(e,t){return n(this,void 0,void 0,function*(){if(0===e.length)return t;const r=yield this.rs.local.getNodes(e),n={};function i(e,t){if(e&&e.itemsMap)for(const r in e.itemsMap)n[t+r]=!0}for(const e in r){const n=r[e];n&&((0,d.isFolder)(e)?(i(n.common,e),i(n.local,e)):n.common&&void 0!==n.common.body&&(t[e]=(0,d.deepClone)(n),t[e].remote={body:!1,timestamp:this.now()},t[e]=this.autoMerge(t[e])))}const o=yield this.markRemoteDeletions(Object.keys(n),t);o&&(yield this.rs.local.setNodes(this.flush(o)))})}completeFetch(e,t,r,i){return n(this,void 0,void 0,function*(){let n,o;const s=(0,d.pathsFromRoot)(e);(0,d.isFolder)(e)?n=[e]:(o=s[1],n=[e,o]);const a=yield this.rs.local.getNodes(n),l=a[o],c={};let u,h=a[e];function p(e){if(e&&e.itemsMap)for(u in e.itemsMap)t[u]||(c[u]=!0)}if("object"==typeof h&&h.path===e&&"object"==typeof h.common||(h={path:e,common:{}},a[e]=h),h.remote={revision:i,timestamp:this.now()},(0,d.isFolder)(e))for(u in p(h.common),p(h.remote),h.remote.itemsMap={},t)h.remote.itemsMap[u]=!0;else h.remote.body=t,h.remote.contentType=r,l&&l.local&&l.local.itemsMap&&(u=e.substring(o.length),!1!==t?l.local.itemsMap[u]=!0:l.local.itemsMap[u]&&delete l.local.itemsMap[u],(0,d.equal)(l.local.itemsMap,l.common.itemsMap)&&delete l.local);return a[e]=this.autoMerge(h),{toBeSaved:a,missingChildren:c}})}completePush(e,t,r,i){return n(this,void 0,void 0,function*(){const n=yield this.rs.local.getNodes([e]),o=n[e];if(!o.push)throw this.stopped=!0,new Error("completePush called but no push version!");r?((0,l.default)("[Sync] We have a conflict"),o.remote&&o.remote.revision===i||(o.remote={revision:i||"conflict",timestamp:this.now()},delete o.push),n[e]=this.autoMerge(o)):(o.common={revision:i,timestamp:this.now()},"put"===t?(o.common.body=o.push.body,o.common.contentType=o.push.contentType,(0,d.equal)(o.local.body,o.push.body)&&o.local.contentType===o.push.contentType&&delete o.local,delete o.push):"delete"===t&&(!1===o.local.body?n[e]=void 0:delete o.push)),yield this.rs.local.setNodes(this.flush(n))})}dealWithFailure(e){return n(this,void 0,void 0,function*(){const t=yield this.rs.local.getNodes([e]);if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))})}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const r=Math.floor(e/100);return t.successful=2===r||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==c.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,r,i,o){return n(this,void 0,void 0,function*(){if(t.notFound&&(r=!!(0,d.isFolder)(e)&&{}),t.changed){const t=yield this.completeFetch(e,r,i,o);if((0,d.isFolder)(e)){if(this.corruptServerItemsMap(r))return(0,l.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1;yield this.markChildren(e,r,t.toBeSaved,t.missingChildren)}else yield this.rs.local.setNodes(this.flush(t.toBeSaved))}else yield this.updateCommonTimestamp(e,o);return!0})}handleResponse(e,t,r){return n(this,void 0,void 0,function*(){const n=this.interpretStatus(r.statusCode);if(n.successful){if("get"===t)return this.handleGetResponse(e,n,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,n.conflict,r.revision).then(function(){return!0});throw new Error(`cannot handle response for unknown action ${t}`)}{let t;return t=n.unAuth?new h.default:n.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+n.statusCode+" received."),this.dealWithFailure(e).then(()=>{throw this.rs._emit("error",t),t})}})}finishTask(e){return n(this,arguments,void 0,function*(e,t=!0){if(void 0===e.action)return void delete this._running[e.path];if(t&&((0,l.default)("[Sync] queue finished task:",e.path),this._finishedTasks.push(e),this._finishedTasks.length>1))return void(0,l.default)("[Sync] delaying finished task:",e.path);let r;(0,l.default)("[Sync] run task:",e.path);try{r=yield e.promise}catch(t){(0,l.default)("[Sync] wire client rejects its promise",e.path,e.action,t),r={statusCode:"offline"}}try{const t=yield this.handleResponse(e.path,e.action,r);this.finishSuccessfulTask(e,t)}catch(t){this.finishUnsuccessfulTask(e,t)}})}finishSuccessfulTask(e,t){return n(this,void 0,void 0,function*(){if(this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t0?yield this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then(()=>{!this.hasTasks()||this.stopped?(this.done||(this.done=!0),this.rs._emit("sync-done",{completed:!0})):setTimeout(()=>{this.doTasks()},10)})})}finishUnsuccessfulTask(e,t){return n(this,void 0,void 0,function*(){(0,l.default)("[Sync]",t.message),this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?yield this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))})}tasksWanted(){return this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0}doTasks(){const e=this.tasksWanted()-Object.keys(this._running).length;if(e<=0)return!0;this.hasTasks()&&!this.done&&this.rs._emit("sync-started");let t,r=0;for(t in this._tasks)if(!this._running[t]&&(this._timeStarted[t]=this.now(),this._running[t]=this.doTask(t).then(this.finishTask.bind(this)),r++,r>=e))break;return r>=e}collectTasks(){return n(this,arguments,void 0,function*(e=!0){if(!this.hasTasks()&&!this.stopped)return(yield this.collectDiffTasks())>0?void 0:e?this.collectRefreshTasks():void 0})}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return n(this,void 0,void 0,function*(){if(this.done=!1,!this.doTasks()){try{yield this.collectTasks()}catch(e){throw(0,l.default)("[Sync] Sync error",e),new Error("Local cache unavailable")}this.doTasks()}})}static _rs_init(e){p=function(){const t=new s.default;t.isBrowser()&&function(e,t){function r(e){const r=t.getCurrentSyncInterval();o.default.isBackground=!e;const n=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:r,newValue:n})}e.on("background",()=>r(!1)),e.on("foreground",()=>r(!0))}(t,e),e.sync||(e.sync=new b(e),e.syncStopped&&((0,l.default)("[Sync] Initializing with sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),e.setupSyncCycle()},f=function(){e.removeEventListener("connected",f),e.startSync()},e.on("ready",p),e.on("connected",f)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",p),e.removeEventListener("connected",f),e.caching.resetActivationHandler(),e.sync=void 0,delete e.sync}}t.Sync=b,(0,d.applyMixins)(b,[a.default]),t.default=b},370:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};const i=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(334));function o(e){return"dropbox"===this.backend&&!!e.match(/^\/public\/.*[^\/]$/)}const s={get:function(e,t){if(this.local){if(void 0===t)t="object"==typeof(r=this).remote&&r.remote.connected&&r.remote.online?2*r.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof t&&!1!==t)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e);var r},put:function(e,t,r){return o.bind(this)(e)?s._wrapBusyDone.call(this,this.remote.put(e,t,r)):this.local?this.local.put(e,t,r):s._wrapBusyDone.call(this,this.remote.put(e,t,r))},delete:function(e,t){return this.local?this.local.delete(e,t):s._wrapBusyDone.call(this,this.remote.delete(e,t))},_wrapBusyDone:function(e){return n(this,void 0,void 0,function*(){return this._emit("wire-busy"),e.then(e=>(this._emit("wire-done",{success:!0}),Promise.resolve(e)),e=>(this._emit("wire-done",{success:!1}),Promise.reject(e)))})}};e.exports=s},613:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class r{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,r,n){const i=e+"/"+t;if(n.extends){const t=n.extends.split("/"),r=1===t.length?e+"/"+t.shift():t.join("/"),o=this.uris[r];if(!o)throw"Type '"+i+"' tries to extend unknown schema '"+r+"'";n.extends=this.schemas[o]}this.uris[i]=r,this.aliases[r]=i,this.schemas[r]=n}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const t=e.length,r={};for(const n in this.uris)if(n.substr(0,t+1)===e+"/"){const e=this.uris[n];r[e]=this.schemas[e]}return r}}t.BaseClientTypes=r;const n=new r;t.default=n},503:function(e){class t extends Error{constructor(e,t={}){super(),this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack}}e.exports=t},746:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.generateCodeVerifier=function(){return n(this,arguments,void 0,function*(e=128){const t=new Uint8Array(e);crypto.getRandomValues(t);const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=Array.from(t).map(e=>r[e%66]),i=n.join(""),o=Uint8Array.from(n.map(e=>e.charCodeAt(0))),s=(a=yield crypto.subtle.digest("SHA-256",o),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(t),{codeVerifier:i,codeChallenge:s,state:Array.from(t).map(e=>r[e%66]).join("")}})},t.applyMixins=function(e,t){t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(r=>{Object.defineProperty(e.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r))})})},t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach(function(e){for(const r in e)t[r]=e[r]}),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},t.isFolder=e=>"/"===e.slice(-1),t.isDocument=e=>!(0,t.isFolder)(e),t.baseName=e=>{const r=e.split("/");return(0,t.isFolder)(e)?r[r.length-2]+"/":r[r.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,r,n=[])=>{let i;if(typeof e!=typeof r)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===r;if("function"==typeof e)return e.toString()===r.toString();if(e instanceof ArrayBuffer&&r instanceof ArrayBuffer&&(e=new Uint8Array(e),r=new Uint8Array(r)),null===e||null===r)return e===r;if(e instanceof Array){if(e.length!==r.length)return!1;for(let i=0,o=e.length;i=0)continue;o=n.slice(),o.push(r[i])}if(!(0,t.equal)(e[i],r[i],o))return!1}}return!0},t.deepClone=e=>void 0===e?void 0:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)),t.pathsFromRoot=e=>{const t=[e],r=e.replace(/\/$/,"").split("/");for(;r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},t.localStorageAvailable=()=>{const e=(0,t.getGlobalContext)();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},t.getJSONFromLocalStorage=e=>{const r=(0,t.getGlobalContext)();try{return JSON.parse(r.localStorage.getItem(e))}catch(e){}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,r)=>new Promise(n=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const t=Buffer.from(e);n(t.toString(r))}else{let i;const o=t.globalContext;if(o.BlobBuilder=o.BlobBuilder||o.WebKitBlobBuilder,void 0!==o.BlobBuilder){const t=new o.BlobBuilder;t.append(e),i=t.getBlob()}else i=new Blob([e]);const s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",function(e){n(e.target.result)}):s.onloadend=function(e){n(e.target.result)},s.readAsText(i,r)}}),t.toBase64=e=>{const r=(0,t.getGlobalContext)();return"btoa"in r?r.btoa(e):Buffer.from(e).toString("base64")}},600:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(275)),s=i(r(93)),a=i(r(503)),l=i(r(334)),c=r(746),u=r(368),h=r(684);let d;const p="remotestorage:wireclient",f={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends h.RemoteBase{constructor(e){if(super(e),this._revisionCache={},d=(0,c.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),d){const e=function(){const e=(0,c.getJSONFromLocalStorage)(p)||{},{userAddress:t,href:r,storageApi:n,token:i,properties:o}=e;return{userAddress:t,href:r,storageApi:n,token:i,properties:o}}();e&&setTimeout(()=>{this.configure(e)},0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}_request(e,t,r,i,s,h,d){return n(this,void 0,void 0,function*(){if(this.isForbiddenRequestMethod(e,t))return Promise.reject(`Don't use ${e} on directories!`);let n;return r!==o.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:(0,c.isFolder)(t)}),(0,u.requestWithTimeout)(e,t,{body:s,headers:i,responseType:"arraybuffer"}).then(r=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,c.isFolder)(t),success:!0}),i=r.status,[401,403,404,412].indexOf(i)>=0)return(0,l.default)("[WireClient] Error response status",r.status),n=h?this.stripQuotes(r.getResponseHeader("ETag")):void 0,401===r.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:r.status,revision:n});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return n=this.stripQuotes(r.getResponseHeader("ETag")),(0,l.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,revision:n});{const e=r.getResponseHeader("Content-Type");n=h?this.stripQuotes(r.getResponseHeader("ETag")):200===r.status?d:void 0;const t=function(e){let t,r="utf-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}(e);return(0,c.shouldBeTreatedAsBinary)(r.response,e)?((0,l.default)("[WireClient] Successful request with unknown or binary mime-type",n),Promise.resolve({statusCode:r.status,body:r.response,contentType:e,revision:n})):(0,c.getTextFromArrayBuffer)(r.response,t).then(t=>((0,l.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,body:t,contentType:e,revision:n})))}var i},r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,c.isFolder)(t),success:!1}),Promise.reject(r)))})}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),"string"==typeof this.storageApi){const e=f[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,d&&localStorage.setItem(p,JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r={};return this.supportsRevs&&t.ifNoneMatch&&(r["If-None-Match"]=this.addQuotes(t.ifNoneMatch)),this._request("GET",this.href+(0,c.cleanPath)(e),this.token,r,void 0,this.supportsRevs,this._revisionCache[e]).then(t=>{if(!(0,c.isFolder)(e))return Promise.resolve(t);let r={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+this.href+(0,c.cleanPath)(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(n=t.body)["@context"]&&"object"==typeof n.items){for(const r in t.body.items)this._revisionCache[e+r]=t.body.items[r].ETag;r=t.body.items}else Object.keys(t.body).forEach(n=>{this._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}});return t.body=r,Promise.resolve(t)}return Promise.resolve(t);var n})}put(e,t,r,n={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!r.match(/charset=/)&&(t instanceof ArrayBuffer||(0,u.isArrayBufferView)(t))&&(r+="; charset=binary");const i={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(i["If-Match"]=this.addQuotes(n.ifMatch)),n.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(n.ifNoneMatch))),this._request("PUT",this.href+(0,c.cleanPath)(e),this.token,i,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=this.addQuotes(t.ifMatch)),this._request("DELETE",this.href+(0,c.cleanPath)(e),this.token,r,void 0,this.supportsRevs)}static _rs_init(e){e.remote=new g(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){d&&delete localStorage[p]}}(0,c.applyMixins)(g,[s.default]),e.exports=g},439:function(e,t){var r,n;r=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var s in i)e.call(i,s)&&o.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var i=n>=0?n:Math.max(r-Math.abs(n),0);i0&&(t+=u.suffices["*"]&&r||",",u.suffices["*"]&&l&&(t+=u.name+"=")),t+=a?encodeURIComponent(h[p]).replace(/!/g,"%21"):s(h[p])}else if("object"==typeof h){l&&!u.suffices["*"]&&(t+=u.name+"=");var f=!0;for(var g in h)f||(t+=u.suffices["*"]&&r||","),f=!1,t+=a?encodeURIComponent(g).replace(/!/g,"%21"):s(g),t+=u.suffices["*"]?"=":",",t+=a?encodeURIComponent(h[g]).replace(/!/g,"%21"):s(h[g])}else l&&(t+=u.name,c&&""===h||(t+="=")),null!=u.truncate&&(h=h.substring(0,u.truncate)),t+=a?encodeURIComponent(h).replace(/!/g,"%21"):s(h)}return t};return _.varNames=u,{prefix:n,substitution:_}}function l(e){if(!(this instanceof l))return new l(e);for(var t=e.split("{"),r=[t.shift()],n=[],i=[],o=[];t.length>0;){var s=t.shift(),c=s.split("}")[0],u=s.substring(c.length+1),h=a(c);i.push(h.substitution),n.push(h.prefix),r.push(u),o=o.concat(h.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var i=g(e[n]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},c.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===g(e)+"#"&&(e=g(e)),this.schemas[e]=t,delete this.missingMap[e],m(t,e),this.searchSchemas(t,e)},c.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},c.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},c.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},c.prototype.dropSchemas=function(){this.schemas={},this.reset()},c.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},c.prototype.validateAll=function(e,t,r,n,i){var o;if(!(t=this.resolveRefs(t)))return null;if(t instanceof w)return this.errors.push(t),t;var s,a=this.errors.length,l=null,c=null;if(this.checkRecursive&&e&&"object"==typeof e){if(o=!this.scanned.length,e[this.validatedSchemasKey]){var u=e[this.validatedSchemasKey].indexOf(t);if(-1!==u)return this.errors=this.errors.concat(e[this.validationErrorsKey][u]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var h=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==h)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][h]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),l=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][l]=t,this.scannedFrozenValidationErrors[s][l]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}c=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][c]=t,e[this.validationErrorsKey][c]=[]}}var d=this.errors.length,p=this.validateBasic(e,t,i)||this.validateNumeric(e,t,i)||this.validateString(e,t,i)||this.validateArray(e,t,i)||this.validateObject(e,t,i)||this.validateCombinations(e,t,i)||this.validateHypermedia(e,t,i)||this.validateFormat(e,t,i)||this.validateDefinedKeywords(e,t,i)||null;if(o){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(p||d!==this.errors.length)for(;r&&r.length||n&&n.length;){var f=r&&r.length?""+r.pop():null,g=n&&n.length?""+n.pop():null;p&&(p=p.prefixWith(f,g)),this.prefixErrors(d,f,g)}return null!==l?this.scannedFrozenValidationErrors[s][l]=this.errors.slice(a):null!==c&&(e[this.validationErrorsKey][c]=this.errors.slice(a)),this.handleError(p)},c.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(b.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(b.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},c.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var i=this.definedKeywords[n],o=0;o=h&&nt.maximum)return this.createError(b.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(b.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},c.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(b.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},c.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},c.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(b.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},c.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,i="",o=t.pattern.match(/^\/(.+)\/([img]*)$/);o?(n=o[1],i=o[2]):n=t.pattern,r=new RegExp(n,i)}return r.test(e)?null:this.createError(b.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},c.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},c.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(b.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},c.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(b.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},c.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==b[e])throw new Error("Error already defined: "+e+" as "+b[e]);if(void 0!==v[t])throw new Error("Error code already used: "+v[t]+" as "+t);for(var n in b[e]=t,v[t]=e,E[e]=E[t]=r,C){var i=C[n];i[e]&&(i[t]=i[t]||i[e])}},reset:function(){n.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:m,resolveUrl:f,getDocumentUri:g,errorCodes:b};return i.language("en"),i}();return S.addLanguage("en-gb",E),S.tv4=S,S},void 0===(n=r.apply(t,[]))||(e.exports=n)},713:function(module){!function(e,t){{const e=t();module.exports=e,module.exports.default=e}}("undefined"!=typeof self&&self,function(){var LINK_URI_MAPS={"http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},LINK_PROPERTIES={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],camlistore:[]},URIS=["webfinger","host-meta","host-meta.json"],IPV4_OCTET="(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)",IPV4_REGEX=new RegExp(`^(?:${IPV4_OCTET}\\.){3}${IPV4_OCTET}$`),IPV4_CAPTURE_REGEX=new RegExp(`^(${IPV4_OCTET})\\.(${IPV4_OCTET})\\.(${IPV4_OCTET})\\.(${IPV4_OCTET})$`),LOCALHOST_REGEX=/^localhost(?:\.localdomain)?(?::\d+)?$/,NUMERIC_PORT_REGEX=/^\d+$/,HOSTNAME_REGEX=/^[a-zA-Z0-9.-]+$/,LOCALHOST_127_REGEX=/^127\.(?:\d{1,3}\.){2}\d{1,3}$/;class WebFingerError extends Error{status;constructor(e,t){super(e),this.name="WebFingerError",this.status=t}}class WebFinger{static default;config;constructor(e={}){this.config={tls_only:void 0===e.tls_only||e.tls_only,uri_fallback:void 0!==e.uri_fallback&&e.uri_fallback,request_timeout:void 0!==e.request_timeout?e.request_timeout:1e4,allow_private_addresses:void 0!==e.allow_private_addresses&&e.allow_private_addresses}}async fetchJRD(e,t=0){if(t>3)throw new WebFingerError("too many redirects");const r=await fetch(e,{headers:{Accept:"application/jrd+json, application/json"},redirect:"manual"});if(r.status>=300&&r.status<400){const n=r.headers.get("location");if(!n)throw new WebFingerError("redirect without location header");let i;try{i=new URL(n,e)}catch{throw new WebFingerError("invalid redirect URL")}const o=WebFinger.validateHost(i.hostname+(i.port?":"+i.port:""));if(!this.config.allow_private_addresses&&WebFinger.isPrivateAddress(o))throw new WebFingerError("redirect to private or internal address blocked");return this.fetchJRD(i.toString(),t+1)}if(404===r.status)throw new WebFingerError("resource not found",404);if(!r.ok)throw new WebFingerError("error during request",r.status);const n=r.headers.get("content-type")||"",i=n.toLowerCase().split(";")[0].trim();"application/jrd+json"===i||("application/json"===i?console.debug('WebFinger: Server uses "application/json" instead of RFC 7033 recommended "application/jrd+json".'):console.warn(`WebFinger: Server returned unexpected content-type "${n}". Expected "application/jrd+json" per RFC 7033.`));const o=await r.text();if(WebFinger.isValidJSON(o))return o;throw new WebFingerError("invalid json")}static isValidJSON(e){try{JSON.parse(e)}catch{return!1}return!0}static isLocalhost(e){return LOCALHOST_REGEX.test(e)}static isPrivateAddress(e){let t=e;if(t.startsWith("[")&&t.includes("]:"))t=t.substring(1,t.lastIndexOf("]:"));else if(t.startsWith("[")&&t.endsWith("]"))t=t.substring(1,t.length-1);else if(t.includes(":")&&1===(t.match(/:/g)||[]).length){const e=t.split(":"),r=e[0],n=e[1];if(n&&!NUMERIC_PORT_REGEX.test(n))throw new WebFingerError("invalid host format");(r.match(IPV4_REGEX)||r.match(HOSTNAME_REGEX))&&(t=r)}if("localhost"===t||"127.0.0.1"===t||t.match(LOCALHOST_127_REGEX)||"::1"===t||"localhost.localdomain"===t)return!0;const r=t.match(IPV4_CAPTURE_REGEX);if(r){const[,e,t,n,i]=r,o=Number(e),s=Number(t),a=Number(n),l=Number(i);if(isNaN(o)||isNaN(s)||isNaN(a)||isNaN(l))return!0;if(10===o)return!0;if(172===o&&s>=16&&s<=31)return!0;if(192===o&&168===s)return!0;if(169===o&&254===s)return!0;if(o>=224&&o<=239)return!0;if(o>=240)return!0}if(t.includes(":")){const e=(t.match(/:/g)||[]).length;if((e>1||1===e&&!t.match(/^[a-zA-Z0-9.-]+:\d+$/))&&(t.match(/^(fc|fd)[0-9a-f]{2}:/i)||t.match(/^fe80:/i)||t.match(/^ff[0-9a-f]{2}:/i)))return!0}return!1}static validateHost(e){const t=e.split("/")[0];if(!t||0===t.length)throw new WebFingerError("invalid host format");if(t.includes("?")||t.includes("#")||t.includes(" "))throw new WebFingerError("invalid characters in host");return t}static async processJRD(e,t){const r=JSON.parse(t);if("object"!=typeof r||"object"!=typeof r.links)throw void 0!==r.error?new WebFingerError(r.error):new WebFingerError("unknown response from server");const n={object:r,idx:{properties:{name:void 0},links:JSON.parse(JSON.stringify(LINK_PROPERTIES))}};(Array.isArray(r.links)?r.links:[]).map(function(e){if(Object.prototype.hasOwnProperty.call(LINK_URI_MAPS,String(e.rel))){const t=LINK_URI_MAPS[String(e.rel)];if(n.idx.links[t]){const r={href:String(e.href||""),rel:String(e.rel||"")};Object.keys(e).map(function(t){"object"==typeof e[t]&&null!==e[t]?r[t]=e[t]:r[t]=String(e[t])}),n.idx.links[t].push(r)}}});const i=r.properties||{};for(const o in i)Object.prototype.hasOwnProperty.call(i,o)&&"http://packetizer.com/ns/name"===o&&(n.idx.properties.name=i[o]);return n}async validateDNSResolution(hostname){if(hostname.match(IPV4_REGEX)||hostname.includes(":")||"localhost"===hostname)return;const isNodeJS="undefined"!=typeof process&&process.versions?.node;if(isNodeJS)try{const dnsImport=eval('import("dns")'),dns=await dnsImport.then(e=>e.promises).catch(()=>null);if(dns)try{const[e,t]=await Promise.allSettled([dns.resolve4(hostname).catch(()=>[]),dns.resolve6(hostname).catch(()=>[])]),r="fulfilled"===e.status?e.value:[],n="fulfilled"===t.status?t.value:[];for(const i of[...r,...n])if(WebFinger.isPrivateAddress(i))throw new WebFingerError(`hostname ${hostname} resolves to private address ${i}`)}catch(e){if(e instanceof WebFingerError)throw e}}catch(e){if(e instanceof WebFingerError)throw e}}async lookup(e){if(!e)throw new WebFingerError("address is required");let t="";if(e.indexOf("://")>-1){const r=e.replace(/ /g,"").split("/");if(r.length<3)throw new WebFingerError("invalid URI format");t=r[2]}else{const r=e.replace(/ /g,"").split("@");if(2!==r.length||!r[1])throw new WebFingerError("invalid useraddress format");t=r[1]}if(!t)throw new WebFingerError("could not determine host from address");if(t=WebFinger.validateHost(t),!this.config.allow_private_addresses&&WebFinger.isPrivateAddress(t))throw new WebFingerError("private or internal addresses are not allowed");if(!this.config.allow_private_addresses){const e=t.includes(":")?t.split(":")[0]:t;await this.validateDNSResolution(e)}let r=0,n="https";WebFinger.isLocalhost(t)&&(n="http");const i=async e=>{if(this.config.uri_fallback&&r!==URIS.length-1)return r+=1,o();if(this.config.tls_only||"https"!==n)throw e instanceof Error?e:new WebFingerError(String(e));return r=0,n="http",o()},o=async()=>{const o=(()=>{let i="";return e.split("://")[1]||(i="acct:"),n+"://"+t+"/.well-known/"+URIS[r]+"?resource="+i+e})();try{const e=await this.fetchJRD(o);return WebFinger.processJRD(o,e)}catch(e){return await i(e)}};return o()}async lookupLink(e,t){if(Object.prototype.hasOwnProperty.call(LINK_PROPERTIES,t)){const r=(await this.lookup(e)).idx.links[t];return 0===r.length?Promise.reject('no links found with rel="'+t+'"'):Promise.resolve(r[0])}return Promise.reject("unsupported rel "+t)}}return WebFinger.default=WebFinger,WebFinger})}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var __webpack_exports__=__webpack_require__(423);return __webpack_exports__=__webpack_exports__.default,__webpack_exports__}()},module.exports=t()}(remotestorage$2)),remotestorage$2.exports}var remotestorageExports=requireRemotestorage();const RemoteStorage=getDefaultExportFromCjs$1(remotestorageExports),ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=32,RANDOM_LEN=16,TIME_LEN=10,TIME_MAX=0xffffffffffff;var ULIDErrorCode;!function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID"}(ULIDErrorCode||(ULIDErrorCode={}));class ULIDError extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e}}function randomChar(e){const t=Math.floor(e()*ENCODING_LEN)%ENCODING_LEN;return ENCODING.charAt(t)}function detectPRNG(){const e=detectRoot(),t=e&&(e.crypto||e.msCrypto)||null;if("function"==typeof t?.getRandomValues)return()=>{const e=new Uint8Array(1);return t.getRandomValues(e),e[0]/256};if("function"==typeof t?.randomBytes)return()=>t.randomBytes(1).readUInt8()/256;throw new ULIDError(ULIDErrorCode.PRNGDetectFailure,"Failed to find a reliable PRNG")}function detectRoot(){return inWebWorker()?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:null}function encodeRandom(e,t){let r="";for(;e>0;e--)r=randomChar(t)+r;return r}function encodeTime(e,t=TIME_LEN){if(isNaN(e))throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed,`Time must be a number: ${e}`);if(e>TIME_MAX)throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${TIME_MAX}: ${e}`);if(e<0)throw new ULIDError(ULIDErrorCode.EncodeTimeNegative,`Time must be positive: ${e}`);if(!1===Number.isInteger(e))throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let r,n="";for(let i=t;i>0;i--)r=e%ENCODING_LEN,n=ENCODING.charAt(r)+n,e=(e-r)/ENCODING_LEN;return n}function inWebWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}function ulid(){const e=detectPRNG();return encodeTime(Date.now(),TIME_LEN)+encodeRandom(RANDOM_LEN,e)}const placeSchema={type:"object",properties:{id:{type:"string"},title:{type:"string"},lat:{type:"number"},lon:{type:"number"},geohash:{type:"string"},zoom:{type:"number"},url:{type:"string"},osmId:{type:"string"},osmType:{type:"string"},osmTags:{type:"object",additionalProperties:{type:"string"}},description:{type:"string"},tags:{type:"array",items:{type:"string"},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","lat","lon","geohash","createdAt"]},listSchema={type:"object",properties:{id:{type:"string"},title:{type:"string"},color:{type:"string"},placeRefs:{type:"array",items:{type:"object",properties:{id:{type:"string"},geohash:{type:"string"}},required:["id","geohash"]},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","placeRefs","createdAt"]},Places=function(e){function t(e,t){return`${e.substring(0,2)}/${e.substring(2,4)}/${t}`}e.declareType("place",placeSchema),e.declareType("list",listSchema);const r={async getAll(){const t=await e.getAll("_lists/");return t?Object.values(t):[]},async get(t){const r=`_lists/${t}`;return e.getObject(r)},async create(t,r,n){const i=`_lists/${t}`;let o=await e.getObject(i);const s=(new Date).toISOString();return o?(o.title=r,n&&(o.color=n),o.updatedAt=s):o={id:t,title:r,color:n,placeRefs:[],createdAt:s,updatedAt:s},await e.storeObject("list",i,o),o},async delete(t){await e.remove(`_lists/${t}`)},async addPlace(t,r,n){const i=`_lists/${t}`,o=await e.getObject(i);if(!o)throw new Error(`List not found: ${t}`);return-1===o.placeRefs.findIndex(e=>e.id===r)&&(o.placeRefs.push({id:r,geohash:n}),o.updatedAt=(new Date).toISOString(),await e.storeObject("list",i,o)),o},async removePlace(t,r){const n=`_lists/${t}`,i=await e.getObject(n);if(!i)throw new Error(`List not found: ${t}`);const o=i.placeRefs.findIndex(e=>e.id===r);return-1!==o&&(i.placeRefs.splice(o,1),i.updatedAt=(new Date).toISOString(),await e.storeObject("list",n,i)),i},async initDefaults(){const e=[{id:"to-go",title:"Want to go",color:"#2e9e4f"},{id:"to-do",title:"To do",color:"#2a7fff"}];for(const t of e)await this.get(t.id)||await this.create(t.id,t.title,t.color)}},n={lists:r,store:async function(r){const n=function(e){const t=(new Date).toISOString(),r=e.id||ulid(),n="number"==typeof e.lat?e.lat:0,i="number"==typeof e.lon?e.lon:0,o=e.title||"Untitled Place",s=e.geohash||Geohash.encode(n,i,10),a={...e,id:r,lat:n,lon:i,geohash:s,title:o,tags:e.tags||[],createdAt:e.createdAt||t,updatedAt:e.id?t:void 0};return Object.keys(a).forEach(e=>{void 0===a[e]&&delete a[e]}),a}(r),i=t(n.geohash,n.id);return await e.storeObject("place",i,n),n},remove:async function(n,i){if(!n||!i)throw new Error("Both id and geohash are required to remove a place");const o=await r.getAll();await Promise.all(o.map(async t=>{const r=t.placeRefs.findIndex(e=>e.id===n);-1!==r&&(t.placeRefs.splice(r,1),t.updatedAt=(new Date).toISOString(),await e.storeObject("list",`_lists/${t.id}`,t))}));const s=t(i,n);return e.remove(s)},get:async function(r,n){if(!r||!n)throw new Error("Both id and geohash are required to get a place");const i=t(n,r);return e.getObject(i)},listByPrefix:async function(t){let r="";return t.length>=2&&(r+=t.substring(0,2)+"/"),t.length>=4&&(r+=t.substring(2,4)+"/"),e.getAll(r)},getPlaces:async function(t){const r=[],n=async t=>{const n=await e.getAll(t,!1);n&&Object.values(n).forEach(e=>{e&&"object"==typeof e&&!e.toString().endsWith("/")&&r.push(e)})};if(t&&t.length>0){const e=t.map(async e=>{if(e.length<4)return;const t=e.substring(0,2),r=e.substring(2,4);await n(`${t}/${r}/`)});await Promise.all(e)}else{const t=e=>{if(!e||"object"!=typeof e)return[];let t=e;return e.items&&"object"==typeof e.items&&(t=e.items),Object.keys(t).filter(e=>e.endsWith("/")&&!e.startsWith("@"))},r=await e.getListing("",!1),i=t(r);await Promise.all(i.map(async r=>{const i=await e.getListing(r,!1),o=t(i);await Promise.all(o.map(async e=>{await n(r+e)}))}))}return r}};return{exports:n}},Places$1={name:"places",builder:Places};var widget={exports:{}},hasRequiredWidget;function requireWidget(){return hasRequiredWidget||(hasRequiredWidget=1,self,e=()=>(()=>{var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){var t=function(e){if("object"!=r(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=r(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==r(t)?t:t+""}e.d(t,{default:()=>i});const i=function(){return e=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.rs=t,this.leaveOpen=!!r.leaveOpen&&r.leaveOpen,this.autoCloseAfter=r.autoCloseAfter?r.autoCloseAfter:1500,this.skipInitial=!!r.skipInitial&&r.skipInitial,this.logging=!!r.logging&&r.logging,this.parentContainerEl=null,r.hasOwnProperty("modalBackdrop")){if("boolean"!=typeof r.modalBackdrop&&"onlySmallScreens"!==r.modalBackdrop)throw'options.modalBackdrop has to be true/false or "onlySmallScreens"';this.modalBackdrop=r.modalBackdrop}else this.modalBackdrop="onlySmallScreens";this.active=!1,this.online=!1,this.closed=!1,this.lastSynced=null,this.lastSyncedUpdateLoop=null},t=[{key:"log",value:function(){if(this.logging){for(var e,t=arguments.length,r=new Array(t),n=0;n

Connect your storage

To sync data with your account
';var t=document.createElement("style");return t.innerHTML='#remotestorage-widget {\n z-index: 21000000;\n}\n\n.rs-widget {\n box-sizing: border-box;\n overflow: hidden;\n max-width: 350px;\n padding: 10px;\n margin: 10px;\n border-radius: 3px;\n background-color: #fff;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n font-family: arial, sans-serif;\n font-size: 16px;\n color: #333;\n will-change: max-height, height, width, opacity, max-width, background, box-shadow;\n transition-property: width, height, opacity, max-width, max-height, background, box-shadow;\n transition-duration: 300ms;\n}\n\n.rs-widget * {\n box-sizing: border-box;\n}\n\n.rs-widget .rs-hidden {\n display: none;\n}\n\n.rs-box {\n overflow: hidden;\n will-change: height;\n transition-property: height, width, max-height;\n transition-duration: 300ms;\n transition-timing-function: ease-in;\n opacity: 0;\n max-height: 0px;\n}\n\n.rs-box.rs-selected:not([aria-hidden=true]) {\n opacity: 1;\n max-height: 420px;\n}\n\n/* Main logo */\n.rs-main-logo {\n float: left;\n height: 36px;\n width: 36px;\n margin-top: 1px;\n margin-right: 0.625em;\n transition: margin-left 300ms ease-out, transform 300ms ease-out;\n cursor: pointer;\n}\n.rs-widget .rs-backend-remotestorage svg#rs-main-logo-remotestorage {\n display: block;\n}\n.rs-widget[class*="rs-backend-"]:not(.rs-backend-remotestorage) svg#rs-main-logo-remotestorage {\n display: none;\n}\n.rs-widget.rs-backend-dropbox svg#rs-main-logo-dropbox {\n display: block;\n}\n.rs-widget:not(.rs-backend-dropbox) svg#rs-main-logo-dropbox {\n display: none;\n}\n.rs-widget.rs-backend-googledrive svg#rs-main-logo-googledrive {\n display: block;\n}\n.rs-widget:not(.rs-backend-googledrive) svg#rs-main-logo-googledrive {\n display: none;\n}\n\npolygon.rs-logo-shape {\n fill: #FF4B03;\n}\n\npolygon.rs-logo-shape,\n#rs-main-logo-dropbox path,\n#rs-main-logo-googledrive path {\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n.rs-offline polygon.rs-logo-shape,\n.rs-offline #rs-main-logo-dropbox path,\n.rs-offline #rs-main-logo-googledrive path {\n fill: #888;\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n/* Hide everything except logo when connected and clicked outside of box */\n.rs-closed {\n max-width: 56px;\n background-color: transparent;\n box-shadow: none;\n opacity: 0.5;\n\n transition: max-height 100ms ease-out 0ms, max-width 300ms ease-out 300ms, background 300ms ease-in 200ms, opacity 300ms ease 200ms;\n}\n\n.rs-closed:hover {\n cursor: pointer;\n opacity: 1;\n}\n\n.rs-box-initial {\n transition-duration: 0ms;\n}\n\n.rs-box-initial:hover {\n cursor: pointer;\n}\n\n.rs-widget a {\n color: #0093cc;\n}\n\n/* HEADLINE */\n.rs-small-headline {\n font-size: 1em;\n font-weight: bold;\n margin: 0;\n margin-bottom: 2px;\n height: 1.2em;\n word-break: break-all;\n overflow: hidden;\n line-height: 1em;\n}\n\n.rs-sub-headline {\n word-break: break-all;\n overflow: hidden;\n color: #666;\n font-size: 0.92em;\n height: 1.2em;\n}\n.rs-big-headline {\n font-size: 1.625em;\n font-weight: normal;\n text-align: center;\n margin-top: 20px;\n margin-bottom: 20px;\n}\n\n/* BUTTONS */\n.rs-button {\n font: inherit;\n color: inherit;\n background-color: transparent;\n border: 1px solid #dcdcdc;\n border-radius: 3px;\n cursor: pointer;\n}\n.rs-button-small {\n padding: 0.6em 0.7em;\n margin-left: 0.2em;\n transition: border-color 300ms ease-out;\n}\n.rs-button-small svg {\n vertical-align: top;\n}\n.rs-button-wrap {\n margin-top: 10px;\n}\n\n.rs-button-wrap img,\n.rs-button-wrap svg {\n float: left;\n margin-right: 0.6em;\n width: 40px;\n height: 40px;\n}\n\n.rs-button-big {\n padding: 15px 10px;\n margin-bottom: 10px;\n display: block;\n width: 100%;\n text-align: left;\n transition: box-shadow 200ms;\n}\n.rs-button-big > div {\n font-size: 1.125em;\n padding: 10px 0;\n}\n.rs-button-big:hover {\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:active {\n background-color: #eee;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:last-child {\n margin-bottom: 0;\n}\n\n.rs-content {\n padding: 0 10px 10px 10px;\n}\n\n\n.rs-state-choose .rs-main-logo,\n.rs-state-sign-in .rs-main-logo {\n margin-left: 45%;\n float: none;\n}\n\n.rs-sign-in-form input[type=text] {\n padding: 15px 10px;\n display: block;\n width: 100%;\n font: inherit;\n height: 52px;\n border: 1px solid #aaa;\n border-radius: 0;\n box-shadow: none;\n}\n.rs-sign-in-form button.rs-connect {\n padding: 15px 10px;\n margin-top: 20px;\n margin-bottom: 15px;\n display: block;\n width: 100%;\n border: none;\n border-radius: 3px;\n background-color: #3fb34f;\n font: inherit;\n color: #fff;\n transition: box-shadow 200ms, background-color 200ms;\n}\n\n.rs-sign-in-form button.rs-connect:hover {\n cursor: pointer;\n background-color: #4BCB5D;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n\n.rs-sign-in-form button.rs-connect:active {\n background-color: #3fb34f;\n}\n\n.rs-sign-in-form button.rs-connect:disabled,\n.rs-sign-in-form button.rs-connect:disabled:hover {\n background-color: #aaa;\n}\n\n.rs-sign-in-form button.rs-connecting svg {\n height: 1em;\n width: auto;\n vertical-align: middle;\n margin-left: 0.5em;\n animation: rs-spin 1s linear infinite;\n}\n\n.rs-sign-in-error.rs-hidden,\n.rs-box-error.rs-hidden {\n height: 0;\n}\n\n.rs-sign-in-error.rs-visible,\n.rs-box-error.rs-visible {\n height: auto;\n border-radius: 3px;\n padding: 0.5em 0.5em;\n margin-top: 0.5em;\n text-align: center;\n background-color: rgba(255,0,0,0.1);\n color: darkred;\n}\n\n.rs-box-error {\n display: flex;\n flex-direction: row;\n}\n\n.rs-box-error .rs-error-message {\n flex: auto;\n}\n\n /*Choose provider box */\n.rs-box-choose {\n text-align: center;\n overflow: hidden;\n}\n\n.rs-box-choose p {\n margin-top: 0;\n margin-bottom: 20px;\n line-height: 1.4em;\n}\n\n/*Connected box */\n.rs-box-connected {\n display: flex;\n flex-direction: row;\n height: 40px;\n transition: height 0s;\n}\n.rs-connected-text {\n flex: auto;\n min-width: 0;\n}\n.rs-box-connected .rs-user {\n font-weight: bold;\n text-overflow: ellipsis;\n overflow: hidden;\n word-break: keep-all;\n}\n.rs-connected-buttons, .rs-error-buttons {\n flex: none;\n}\n.rs-disconnect:hover {\n border-color: #FF2D2D;\n}\n.rs-disconnect:hover .rs-icon{\n fill: #FF2D2D;\n}\n.rs-sync:hover {\n border-color: #FFBB0C;\n}\n.rs-sync:hover .rs-icon {\n fill: #FFBB0C;\n}\n.rs-sync.rs-rotate {\n border-color: #FFBB0C;\n}\n.rs-sync.rs-rotate .rs-icon {\n fill: #FFBB0C;\n animation: rs-spin 1s linear infinite;\n}\n\n/* Floating widget styles (top right corner) */\n.rs-floating {\n position: fixed;\n top: 0;\n right: 0;\n}\n\n@keyframes rs-spin {\n 100% {\n transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n/* Small/mobile screens */\n@media screen and (max-width: 420px) {\n .rs-widget {\n font-size: 100%;\n transition: all 300ms ease-out;\n max-width: 400px;\n }\n .rs-floating {\n position: relative;\n top: auto;\n right: auto\n }\n .rs-closed {\n max-width: 56px;\n }\n .rs-state-choose,\n .rs-state-sign-in {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n max-width: 100%;\n }\n}\n\n/* remove dotted outline border on Firefox */\n.rs-widget a:focus,\n.rs-widget a:active,\n.rs-widget button:focus,\n.rs-widget input:focus {\n outline:none;\n}\n.rs-widget button::-moz-focus-inner,\n.rs-widget input[type="button"]::-moz-focus-inner {\n border:0;\n}\n\n/* prevent rounded buttons on mobile Safari */\n.rs-widget button,\n.rs-widget input[type="button"] {\n -webkit-appearance: none;\n}\n\n.remotestorage-widget-modal-backdrop {\n display: none;\n position: fixed;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-color: rgba(0, 0, 0, 0.5);\n opacity: 0;\n transition: opacity 0.3s linear;\n}\n\n.remotestorage-widget-modal-backdrop.visible {\n opacity: 1;\n transition: opacity 0.3s linear;\n}\n',e.appendChild(t),e}},{key:"setModalClass",value:function(){if(this.modalBackdrop){if("onlySmallScreens"===this.modalBackdrop&&!this.isSmallScreen())return;this.rsWidget.classList.add("rs-modal")}}},{key:"setupElements",value:function(){if(!this.parentContainerEl)throw new Error("Parent container element not found");this.rsWidget=this.parentContainerEl.querySelector(".rs-widget"),this.rsBackdrop=this.parentContainerEl.querySelector(".remotestorage-widget-modal-backdrop"),this.rsInitial=this.parentContainerEl.querySelector(".rs-box-initial"),this.rsChoose=this.parentContainerEl.querySelector(".rs-box-choose"),this.rsConnected=this.parentContainerEl.querySelector(".rs-box-connected"),this.rsSignIn=this.parentContainerEl.querySelector(".rs-box-sign-in"),this.rsConnectedLabel=this.parentContainerEl.querySelector(".rs-box-connected .rs-sub-headline"),this.rsChooseRemoteStorageButton=this.parentContainerEl.querySelector("button.rs-choose-rs"),this.rsChooseDropboxButton=this.parentContainerEl.querySelector("button.rs-choose-dropbox"),this.rsChooseGoogleDriveButton=this.parentContainerEl.querySelector("button.rs-choose-googledrive"),this.rsErrorBox=this.parentContainerEl.querySelector(".rs-box-error .rs-error-message"),this.rs.apiKeys.hasOwnProperty("googledrive")||this.rsChooseGoogleDriveButton.parentNode.removeChild(this.rsChooseGoogleDriveButton),this.rs.apiKeys.hasOwnProperty("dropbox")||this.rsChooseDropboxButton.parentNode.removeChild(this.rsChooseDropboxButton),this.rsSignInForm=this.parentContainerEl.querySelector(".rs-sign-in-form"),this.rsAddressInput=this.rsSignInForm.querySelector("input[name=rs-user-address]"),this.rsConnectButton=this.parentContainerEl.querySelector(".rs-connect"),this.rsDisconnectButton=this.parentContainerEl.querySelector(".rs-disconnect"),this.rsSyncButton=this.parentContainerEl.querySelector(".rs-sync"),this.rsLogo=this.parentContainerEl.querySelector(".rs-widget-icon"),this.rsErrorReconnectLink=this.parentContainerEl.querySelector(".rs-box-error a.rs-reconnect"),this.rsErrorDisconnectButton=this.parentContainerEl.querySelector(".rs-box-error button.rs-disconnect"),this.rsConnectedUser=this.parentContainerEl.querySelector(".rs-connected-text h1.rs-user")}},{key:"setupHandlers",value:function(){var e=this;this.rs.on("connected",function(){return e.eventHandler("connected")}),this.rs.on("ready",function(){return e.eventHandler("ready")}),this.rs.on("disconnected",function(){return e.eventHandler("disconnected")}),this.rs.on("network-online",function(){return e.eventHandler("network-online")}),this.rs.on("network-offline",function(){return e.eventHandler("network-offline")}),this.rs.on("error",function(t){return e.eventHandler("error",t)}),this.setEventListeners(),this.setClickHandlers()}},{key:"attach",value:function(e){var t=this.createHtmlTemplate(e);if(this.parentContainerEl,e instanceof HTMLElement)this.parentContainerEl=e;else if("string"==typeof e){if(this.parentContainerEl=document.getElementById(e),!this.parentContainerEl)throw new Error('Failed to find target DOM element with id="'+e+'"')}else{if(e)throw new Error("Unknown element type. Expected instance of HTMLElement or type of string.");this.parentContainerEl=document.body}this.parentContainerEl.appendChild(t),this.setupElements(),this.setupHandlers(),this.setInitialState(),this.setModalClass()}},{key:"setEventListeners",value:function(){var e=this;this.rsSignInForm.addEventListener("submit",function(t){t.preventDefault();var r=e.parentContainerEl.querySelector("input[name=rs-user-address]").value.trim();e.disableConnectButton(),e.rs.connect(r)})}},{key:"showChooseOrSignIn",value:function(){this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.style.display="block",this.rsBackdrop.classList.add("visible")),this.rs.apiKeys&&Object.keys(this.rs.apiKeys).length>0?this.setState("choose"):this.setState("sign-in")}},{key:"setClickHandlers",value:function(){var e=this;this.rsInitial.addEventListener("click",function(){return e.showChooseOrSignIn()}),this.rsChooseRemoteStorageButton.addEventListener("click",function(){e.setState("sign-in"),e.rsAddressInput.focus()}),this.rsChooseDropboxButton.addEventListener("click",function(){return e.rs.dropbox.connect()}),this.rsChooseGoogleDriveButton.addEventListener("click",function(){return e.rs.googledrive.connect()}),this.rsDisconnectButton.addEventListener("click",function(){return e.rs.disconnect()}),this.rsErrorReconnectLink.addEventListener("click",function(){return e.rs.reconnect()}),this.rsErrorDisconnectButton.addEventListener("click",function(){return e.rs.disconnect()}),this.rs.hasFeature("Sync")&&this.rsSyncButton.addEventListener("click",function(){e.rsSyncButton.classList.contains("rs-rotate")?(e.rs.stopSync(),e.rsSyncButton.classList.remove("rs-rotate")):(e.rsConnectedLabel.textContent="Synchronizing",e.rs.startSync(),e.rsSyncButton.classList.add("rs-rotate"))}),document.addEventListener("click",function(){return e.close()}),this.rsWidget.addEventListener("click",function(e){return e.stopPropagation()}),this.rsLogo.addEventListener("click",function(){return e.toggle()})}},{key:"toggle",value:function(){this.closed?this.open():"initial"===this.state?this.showChooseOrSignIn():this.close()}},{key:"open",value:function(){this.closed=!1,this.rsWidget.classList.remove("rs-closed"),this.shouldCloseWhenSyncDone=!1;var e=this.parentContainerEl.querySelector(".rs-box.rs-selected");e&&e.setAttribute("aria-hidden","false")}},{key:"close",value:function(){var e=this;if("error"!==this.state){if(!this.leaveOpen&&this.active){this.closed=!0,this.rsWidget.classList.add("rs-closed");var t=this.parentContainerEl.querySelector(".rs-box.rs-selected");t&&t.setAttribute("aria-hidden","true")}else this.active?this.setState("connected"):this.setInitialState();this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.classList.remove("visible"),setTimeout(function(){e.rsBackdrop.style.display="none"},300))}}},{key:"disableConnectButton",value:function(){this.rsConnectButton.disabled=!0,this.rsConnectButton.classList.add("rs-connecting"),this.rsConnectButton.innerHTML="Connecting ".concat('\n \n \n \n \n \n \n\n')}},{key:"enableConnectButton",value:function(){this.rsConnectButton.disabled=!1,this.rsConnectButton.textContent="Connect",this.rsConnectButton.classList.remove("rs-connecting")}},{key:"setOffline",value:function(){this.online&&(this.rsWidget.classList.add("rs-offline"),this.rsConnectedLabel.textContent="Offline",this.online=!1)}},{key:"setOnline",value:function(){this.online||(this.rsWidget.classList.remove("rs-offline"),this.active&&(this.rsConnectedLabel.textContent="Connected")),this.online=!0}},{key:"setBackendClass",value:function(e){this.rsWidget.classList.remove("rs-backend-remotestorage"),this.rsWidget.classList.remove("rs-backend-dropbox"),this.rsWidget.classList.remove("rs-backend-googledrive"),e&&this.rsWidget.classList.add("rs-backend-".concat(e))}},{key:"showErrorBox",value:function(e){this.rsErrorBox.innerHTML=e,this.setState("error")}},{key:"hideErrorBox",value:function(){this.rsErrorBox.innerHTML="",this.close()}},{key:"handleSyncStarted",value:function(){var e=this;this.syncInProgress=!0,this.rsSyncButton.classList.add("rs-rotate"),setTimeout(function(){e.syncInProgress&&(e.rsConnectedLabel.textContent="Synchronizing")},1e3)}},{key:"handleDiscoveryError",value:function(e){var t=this.parentContainerEl.querySelector(".rs-sign-in-error");t.innerHTML=e.message,t.classList.remove("rs-hidden"),t.classList.add("rs-visible"),this.enableConnectButton()}},{key:"handleSyncError",value:function(){this.setOffline()}},{key:"handleUnauthorized",value:function(e){e.code&&"access_denied"===e.code?this.rs.disconnect():(this.open(),this.showErrorBox(e.message+" "),this.rsErrorBox.appendChild(this.rsErrorReconnectLink),this.rsErrorReconnectLink.classList.remove("rs-hidden"))}},{key:"updateLastSyncedStatus",value:function(){var e=new Date;this.online?(this.lastSynced=e,this.rsConnectedLabel.textContent="Synced"):this.rsWidget.classList.contains("rs-state-unauthorized")||(this.rsConnectedLabel.textContent="Offline")}},{key:"isSmallScreen",value:function(){return window.innerWidth<421}}],t&&function(e,t){for(var r=0;r{r?this.updated.push(this.wrapRecord(e)):(this.added.push(this.wrapRecord(e)),r=!0)}),this.recordCaches.set(e,t)}return t}constructor(e,t,r,n,i,o){this.wrapRecord=i,this.release=o,this.recordArrayCache=createCache(()=>{let o=new Set;consumeTag(tagFor(e,"[]")),iterate(e,e=>{getValue$1(this.getCacheForItem(e)),o.add(e)}),untrack(()=>{this.recordCaches.forEach((e,t)=>{o.has(t)||(this.removed.push(i(t)),this.recordCaches.delete(t))})}),this.added.length>0&&(t(this.added),this.added=[]),this.updated.length>0&&(r(this.updated),this.updated=[]),this.removed.length>0&&(n(this.removed),this.removed=[])})}revalidate(){getValue$1(this.recordArrayCache)}}class TypeWatcher{constructor(e,t,r){this.release=r;let n=!1;this.cache=createCache(()=>{iterate(e,()=>{}),consumeTag(tagFor(e,"[]")),!0===n?next(t):n=!0}),this.release=r}revalidate(){getValue$1(this.cache)}}class DataAdapter extends EmberObject{releaseMethods=A$1();recordsWatchers=new Map;typeWatchers=new Map;flushWatchers=null;constructor(e){super(e),this.containerDebugAdapter=getOwner$2(this).lookup("container-debug-adapter:main")}attributeLimit=3;acceptsModelName=!0;getFilters(){return A$1()}watchModelTypes(e,t){let r,n=this.getModelTypes(),i=A$1();r=n.map(e=>{let r=e.klass,n=this.wrapModelType(r,e.name);return i.push(this.observeModelType(e.name,t)),n}),e(r);let o=()=>{i.forEach(e=>e()),this.releaseMethods.removeObject(o)};return this.releaseMethods.pushObject(o),o}_nameToClass(e){if("string"==typeof e){let t=getOwner$2(this).factoryFor(`model:${e}`);e=t&&t.class}return e}watchRecords(e,t,r,n){let i=this._nameToClass(e),o=this.getRecords(i,e),{recordsWatchers:s}=this,a=s.get(o);return a||(a=new RecordsWatcher(o,t,r,n,e=>this.wrapRecord(e),()=>{s.delete(o),this.updateFlushWatchers()}),s.set(o,a),this.updateFlushWatchers(),a.revalidate()),a.release}updateFlushWatchers(){null===this.flushWatchers?(this.typeWatchers.size>0||this.recordsWatchers.size>0)&&(this.flushWatchers=()=>{this.typeWatchers.forEach(e=>e.revalidate()),this.recordsWatchers.forEach(e=>e.revalidate())},_backburner.on("end",this.flushWatchers)):0===this.typeWatchers.size&&0===this.recordsWatchers.size&&(_backburner.off("end",this.flushWatchers),this.flushWatchers=null)}willDestroy(){this._super(...arguments),this.typeWatchers.forEach(e=>e.release()),this.recordsWatchers.forEach(e=>e.release()),this.releaseMethods.forEach(e=>e()),this.flushWatchers&&_backburner.off("end",this.flushWatchers)}detect(e){return!1}columnsForType(e){return A$1()}observeModelType(e,t){let r=this._nameToClass(e),n=this.getRecords(r,e),{typeWatchers:i}=this,o=i.get(n);return o||(o=new TypeWatcher(n,()=>{t([this.wrapModelType(r,e)])},()=>{i.delete(n),this.updateFlushWatchers()}),i.set(n,o),this.updateFlushWatchers(),o.revalidate()),o.release}wrapModelType(e,t){return{name:t,count:get$7(this.getRecords(e,t),"length"),columns:this.columnsForType(e),object:e}}getModelTypes(){let e=this.containerDebugAdapter,t=(e.canCatalogEntriesByType("model")?e.catalogEntriesByType("model"):this._getObjectsOnNamespaces()).map(e=>({klass:this._nameToClass(e),name:e}));return t.filter(e=>this.detect(e.klass))}_getObjectsOnNamespaces(){let e=Namespace.NAMESPACES,t=[];return e.forEach(e=>{for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!this.detect(e[r]))continue;let n=dasherize$1(r);t.push(n)}}),t}getRecords(e,t){return A$1()}wrapRecord(e){return{object:e,columnValues:this.getRecordColumnValues(e),searchKeywords:this.getRecordKeywords(e),filterValues:this.getRecordFilterValues(e),color:this.getRecordColor(e)}}getRecordColumnValues(e){return{}}getRecordKeywords(e){return A$1()}getRecordFilterValues(e){return{}}getRecordColor(e){return null}}const ARRAY_OBSERVER_MAPPING={willChange:"_arrangedContentArrayWillChange",didChange:"_arrangedContentArrayDidChange"};function customTagForArrayProxy(e,t){return"[]"===t?(e._revalidate(),e._arrTag):"length"===t?(e._revalidate(),e._lengthTag):tagFor(e,t)}class ArrayProxy extends EmberObject{_objectsDirtyIndex=0;_objects=null;_lengthDirty=!0;_length=0;_arrangedContent=null;_arrangedContentIsUpdating=!1;_arrangedContentTag=null;_arrangedContentRevision=null;_lengthTag=null;_arrTag=null;init(e){super.init(e),setCustomTagFor(this,customTagForArrayProxy)}[PROPERTY_DID_CHANGE](){this._revalidate()}willDestroy(){this._removeArrangedContentArrayObserver()}objectAtContent(e){return objectAt(get$7(this,"arrangedContent"),e)}replace(e,t,r){this.replaceContent(e,t,r)}replaceContent(e,t,r){replace(get$7(this,"content"),e,t,r)}objectAt(e){if(this._revalidate(),null===this._objects&&(this._objects=[]),-1!==this._objectsDirtyIndex&&e>=this._objectsDirtyIndex){let e=get$7(this,"arrangedContent");if(e){let t=this._objects.length=get$7(e,"length");for(let e=this._objectsDirtyIndex;ei)&&(this._objectsDirtyIndex=i),this._lengthDirty=!0,arrayContentDidChange(this,t,r,n,!1)}_invalidate(){this._objectsDirtyIndex=0,this._lengthDirty=!0}_revalidate(){if(!0!==this._arrangedContentIsUpdating&&(null===this._arrangedContentTag||!validateTag(this._arrangedContentTag,this._arrangedContentRevision))){let e=this.get("arrangedContent");null===this._arrangedContentTag?this._addArrangedContentArrayObserver(e):(this._arrangedContentIsUpdating=!0,this._updateArrangedContentArray(e),this._arrangedContentIsUpdating=!1);let t=this._arrangedContentTag=tagFor(this,"arrangedContent");this._arrangedContentRevision=valueForTag(this._arrangedContentTag),isObject(e)?(this._lengthTag=combine([t,tagForProperty(e,"length")]),this._arrTag=combine([t,tagForProperty(e,"[]")])):this._lengthTag=this._arrTag=t}}}ArrayProxy.reopen(MutableArray,{arrangedContent:alias("content")});const proxy$1=Object.freeze(Object.defineProperty({__proto__:null,default:ArrayProxy},Symbol.toStringTag,{value:"Module"}));class ObjectProxy extends FrameworkObject{}ObjectProxy.PrototypeMixin.reopen(ProxyMixin);const proxy=Object.freeze(Object.defineProperty({__proto__:null,default:ObjectProxy},Symbol.toStringTag,{value:"Module"}));function tap(e,t){return setProperties(e,{isFulfilled:!1,isRejected:!1}),t.then(t=>(e.isDestroyed||e.isDestroying||setProperties(e,{content:t,isFulfilled:!0}),t),t=>{throw e.isDestroyed||e.isDestroying||setProperties(e,{reason:t,isRejected:!0}),t},"Ember: PromiseProxy")}const PromiseProxyMixin=Mixin.create({reason:null,isPending:computed("isSettled",function(){return!get$7(this,"isSettled")}).readOnly(),isSettled:computed("isRejected","isFulfilled",function(){return get$7(this,"isRejected")||get$7(this,"isFulfilled")}).readOnly(),isRejected:!1,isFulfilled:!1,promise:computed({get(){throw new Error("PromiseProxy's promise must be set")},set(e,t){return tap(this,t)}}),then:promiseAlias("then"),catch:promiseAlias("catch"),finally:promiseAlias("finally")});function promiseAlias(e){return function(...t){return get$7(this,"promise")[e](...t)}}const promiseProxyMixin=Object.freeze(Object.defineProperty({__proto__:null,default:PromiseProxyMixin},Symbol.toStringTag,{value:"Module"}));function controllerFor(e,t,r){return e.lookup(`controller:${t}`,r)}let Ember;!function(e){function t(){}e.isNamespace=!0,e.toString=function(){return"Ember"},e.Container=Container,e.Registry=Registry,e._setComponentManager=setComponentManager,e._componentManagerCapabilities=componentCapabilities,e._modifierManagerCapabilities=modifierCapabilities,e.meta=meta$1,e._createCache=createCache,e._cacheGetValue=getValue$1,e._cacheIsConst=isConst,e._descriptor=nativeDescDecorator,e._getPath=_getPath,e._setClassicDecorator=setClassicDecorator,e._tracked=tracked,e.beginPropertyChanges=beginPropertyChanges,e.changeProperties=changeProperties,e.endPropertyChanges=endPropertyChanges,e.hasListeners=hasListeners,e.libraries=LIBRARIES,e._ContainerProxyMixin=ContainerProxyMixin,e._ProxyMixin=ProxyMixin,e._RegistryProxyMixin=RegistryProxyMixin,e.ActionHandler=ActionHandler,e.Comparable=Comparable,e.ComponentLookup=ComponentLookup,e.EventDispatcher=EventDispatcher,e._Cache=Cache$1,e.GUID_KEY=GUID_KEY,e.canInvoke=canInvoke,e.generateGuid=generateGuid,e.guidFor=guidFor,e.uuid=uuid$1,e.wrap=wrap$2,e.getOwner=getOwner,e.onLoad=onLoad,e.runLoadHooks=runLoadHooks,e.setOwner=setOwner,e.Application=Application$1,e.ApplicationInstance=ApplicationInstance,e.Namespace=Namespace,e.A=A$1,e.Array=EmberArray,e.NativeArray=NativeArray,e.isArray=isArray$4,e.makeArray=makeArray,e.MutableArray=MutableArray,e.ArrayProxy=ArrayProxy,e.FEATURES={isEnabled:isEnabled,...FEATURES},e._Input=Input,e.Component=Component,e.Helper=Helper,e.Controller=Controller,e.ControllerMixin=ControllerMixin,e._captureRenderTree=captureRenderTree,e.assert=assert$3,e.warn=warn$1,e.debug=debug$2,e.deprecate=deprecate,e.deprecateFunc=deprecateFunc,e.runInDebug=runInDebug,e.inspect=inspect,e.Debug={registerDeprecationHandler:registerHandler$1,registerWarnHandler:registerHandler,isComputed:isComputed},e.ContainerDebugAdapter=ContainerDebugAdapter,e.DataAdapter=DataAdapter,e._assertDestroyablesDestroyed=assertDestroyablesDestroyed,e._associateDestroyableChild=associateDestroyableChild,e._enableDestroyableTracking=enableDestroyableTracking,e._isDestroying=isDestroying,e._isDestroyed=isDestroyed,e._registerDestructor=registerDestructor,e._unregisterDestructor=unregisterDestructor,e.destroy=destroy,e.Engine=Engine,e.EngineInstance=EngineInstance,e.Enumerable=Enumerable,e.MutableEnumerable=MutableEnumerable,e.instrument=instrument,e.subscribe=subscribe,e.Instrumentation={instrument:instrument,subscribe:subscribe,unsubscribe:unsubscribe,reset:reset$1},e.Object=EmberObject,e._action=action,e.computed=computed,e.defineProperty=defineProperty,e.get=get$7,e.getProperties=getProperties,e.notifyPropertyChange=notifyPropertyChange,e.observer=observer,e.set=set$1,e.trySet=trySet,e.setProperties=setProperties,e.cacheFor=getCachedValueFor,e._dependentKeyCompat=dependentKeyCompat,e.ComputedProperty=ComputedProperty,e.expandProperties=expandProperties,e.CoreObject=CoreObject,e.Evented=Evented,e.on=on$3,e.addListener=addListener,e.removeListener=removeListener,e.sendEvent=sendEvent,e.Mixin=Mixin,e.mixin=mixin,e.Observable=Observable$2,e.addObserver=addObserver,e.removeObserver=removeObserver,e.PromiseProxyMixin=PromiseProxyMixin,e.ObjectProxy=ObjectProxy,e.RouterDSL=DSLImpl,e.controllerFor=controllerFor,e.generateController=generateController,e.generateControllerFactory=generateControllerFactory,e.HashLocation=HashLocation,e.HistoryLocation=HistoryLocation,e.NoneLocation=NoneLocation,e.Route=Route,e.Router=EmberRouter,e.run=run,e.Service=Service,e.compare=compare$1,e.isBlank=isBlank,e.isEmpty=isEmpty$4,e.isEqual=isEqual,e.isNone=isNone,e.isPresent=isPresent,e.typeOf=typeOf$1,e.VERSION=Version,e.ViewUtils={getChildViews:getChildViews,getElementView:getElementView,getRootViews:getRootViews,getViewBounds:getViewBounds,getViewBoundingClientRect:getViewBoundingClientRect,getViewClientRects:getViewClientRects,getViewElement:getViewElement,isSimpleClick:isSimpleClick,isSerializationFirstNode:isSerializationFirstNode},e._getComponentTemplate=getComponentTemplate,e._helperManagerCapabilities=helperCapabilities,e._setComponentTemplate=setComponentTemplate,e._setHelperManager=setHelperManager,e._setModifierManager=setModifierManager$1,e._templateOnlyComponent=templateOnlyComponent,e._invokeHelper=invokeHelper,e._hash=hash$3,e._array=array$1,e._concat=concat$1,e._get=get$6,e._on=on$1,e._fn=fn$1,e._Backburner=Backburner,e.inject=t,t.controller=inject$1,t.service=service,e.__loader={get require(){return globalThis.require},get define(){return globalThis.define},get registry(){let e=globalThis;return e.requirejs?.entries??e.require.entries}}}(Ember||(Ember={})),Reflect.set(Ember,"RSVP",RSVP$1),Object.defineProperty(Ember,"ENV",{get:getENV,enumerable:!1}),Object.defineProperty(Ember,"lookup",{get:getLookup,set:setLookup,enumerable:!1}),Object.defineProperty(Ember,"onerror",{get:getOnerror,set:setOnerror,enumerable:!1}),Object.defineProperty(Ember,"testing",{get:isTesting,set:setTesting,enumerable:!1}),Object.defineProperty(Ember,"BOOTED",{configurable:!1,enumerable:!1,get:isSearchDisabled,set:setSearchDisabled}),Object.defineProperty(Ember,"TEMPLATES",{get:getTemplates,set:setTemplates,configurable:!1,enumerable:!1}),Object.defineProperty(Ember,"TEMPLATES",{get:getTemplates,set:setTemplates,configurable:!1,enumerable:!1}),Object.defineProperty(Ember,"testing",{get:isTesting,set:setTesting,enumerable:!1}),runLoadHooks("Ember.Application",Application$1);let EmberHandlebars={template:templateFactory,Utils:{}},EmberHTMLBars={template:templateFactory};function defineEmberTemplateCompilerLazyLoad(e){Object.defineProperty(Ember,e,{configurable:!0,enumerable:!0,get:()=>"Handlebars"===e?EmberHandlebars:EmberHTMLBars})}function defineEmberTestingLazyLoad(e){Object.defineProperty(Ember,e,{configurable:!0,enumerable:!0,get(){}})}defineEmberTemplateCompilerLazyLoad("HTMLBars"),defineEmberTemplateCompilerLazyLoad("Handlebars"),defineEmberTestingLazyLoad("Test"),defineEmberTestingLazyLoad("setupForTesting"),runLoadHooks("Ember");const doNotUseThis=Ember;new Proxy(doNotUseThis,{get:(e,t,r)=>("string"==typeof t&&deprecateUntil(`importing ${t} from the 'ember' barrel file is deprecated.`,DEPRECATIONS.DEPRECATE_IMPORT_EMBER(t)),Reflect.get(e,t,r)),getOwnPropertyDescriptor:(e,t)=>("string"==typeof t&&deprecateUntil(`importing ${t} from the 'ember' barrel file is deprecated.`,DEPRECATIONS.DEPRECATE_IMPORT_EMBER(t)),Object.getOwnPropertyDescriptor(e,t))});const registeredDebounces=new WeakMap;function debounceTask(e,t,...r){if(assert$3(`Called \`destroyable.debounceTask('${t}', ...)\` where 'destroyable.${t}' is not a function.`,"function"==typeof e[t]),e.isDestroying)return;"boolean"==typeof r[r.length-1]&&r[r.length-2];let n,i=registeredDebounces.get(e);i||(i=new Map,registeredDebounces.set(e,i),registerDestructor(e,getDebouncesDisposable(i))),n=i.has(t)?i.get(t).debouncedTask:(...r)=>{i.delete(t),e[t](...r)};let o=debounce(e,n,...r);i.set(t,{debouncedTask:n,cancelId:o})}function getDebouncesDisposable(e){return function(){0!==e.size&&e.forEach(e=>cancel(e.cancelId))}}class StorageService extends Service{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");rs;widget;static{decorateFieldV2(this.prototype,"placesInView",[tracked],function(){return[]})}#de=void initializeDeferredDecorator(this,"placesInView");static{decorateFieldV2(this.prototype,"savedPlaces",[tracked],function(){return[]})}#pe=void initializeDeferredDecorator(this,"savedPlaces");static{decorateFieldV2(this.prototype,"loadedPrefixes",[tracked],function(){return[]})}#fe=void initializeDeferredDecorator(this,"loadedPrefixes");static{decorateFieldV2(this.prototype,"currentBbox",[tracked],function(){return null})}#ge=void initializeDeferredDecorator(this,"currentBbox");static{decorateFieldV2(this.prototype,"lists",[tracked],function(){return[]})}#me=void initializeDeferredDecorator(this,"lists");static{decorateFieldV2(this.prototype,"version",[tracked],function(){return 0})}#ye=void initializeDeferredDecorator(this,"version");static{decorateFieldV2(this.prototype,"initialSyncDone",[tracked],function(){return!1})}#be=void initializeDeferredDecorator(this,"initialSyncDone");static{decorateFieldV2(this.prototype,"connected",[tracked],function(){return!1})}#ve=void initializeDeferredDecorator(this,"connected");static{decorateFieldV2(this.prototype,"userAddress",[tracked],function(){return null})}#_e=void initializeDeferredDecorator(this,"userAddress");static{decorateFieldV2(this.prototype,"isWidgetOpen",[tracked],function(){return!1})}#Ee=void initializeDeferredDecorator(this,"isWidgetOpen");isNewConnection=!0;constructor(){super(...arguments),this.checkInitialConnectionState(),this.rs=new RemoteStorage({modules:[Places$1]}),this.rs.access.claim("places","rw"),this.rs.caching.enable("/places/"),window.remoteStorage=this.rs,this.widget=new Widget(this.rs,{leaveOpen:!0,skipInitial:!0}),this.rs.on("ready",()=>{}),this.rs.on("error",e=>{e&&(console.info("[rs] Error —",`${e.name}: ${e.message}`),"Unauthorized"===e.name&&this.showConnectWidget())}),this.rs.on("connected",()=>{this.connected=!0,this.userAddress=this.rs.remote.userAddress,this.isNewConnection&&(this.toast.show("Remote storage connected",3e3),this.isNewConnection=!1),this.loadLists()}),this.rs.on("not-connected",()=>{this.loadLists()}),this.rs.on("disconnected",()=>{this.connected=!1,this.userAddress=null,this.placesInView=[],this.savedPlaces=[],this.loadedPrefixes=[],this.lists=[],this.initialSyncDone=!1,this.isNewConnection=!0}),this.rs.on("sync-done",()=>{this.initialSyncDone||(this.initialSyncDone=!0,this.loadLists())}),this.rs.scope("/places/").on("change",e=>{e.relativePath.startsWith("_lists/")?this.loadLists():(this.handlePlaceChange(e),debounceTask(this,"reloadCurrentView",200))})}checkInitialConnectionState(){this.isNewConnection=!0;try{if(window.localStorage){const e=["remotestorage:wireclient","remotestorage:dropbox","remotestorage:googledrive"];for(const t of e){const e=window.localStorage.getItem(t);if(e){const t=JSON.parse(e);if(t&&t.token){this.isNewConnection=!1;break}}}}}catch(e){console.warn("Failed to check localStorage for existing connection:",e)}}handlePlaceChange(e){const{newValue:t,relativePath:r}=e,n=r.split("/"),i=n[n.length-1];if(t){const e={...t,id:i},r=this.savedPlaces.findIndex(e=>e.id===i);if(-1!==r){const t=[...this.savedPlaces];t[r]=e,this.savedPlaces=t}else this.savedPlaces=[...this.savedPlaces,e]}else this.savedPlaces=this.savedPlaces.filter(e=>e.id!==i)}get places(){return this.rs.places}notifyChange(){this.version++,debounceTask(this,"reloadCurrentView",200)}reloadCurrentView(){if(!this.currentBbox)return;const e=getGeohashPrefixesInBbox(this.currentBbox);console.debug("Reloading view due to changes, prefixes:",e),this.loadAllPlaces(e)}async loadLists(){try{if(!this.places.lists)return;await this.places.lists.initDefaults();const e=await this.places.lists.getAll();this.lists=e||[],this.lists.forEach(e=>{"to-go"===e.id?e.icon="bookmark":"to-do"===e.id&&(e.icon="check-square")}),this.refreshPlaceListAssociations()}catch(e){console.error("Failed to load lists:",e)}}refreshPlaceListAssociations(){const e=new Map;this.lists.forEach(t=>{t.placeRefs&&Array.isArray(t.placeRefs)&&t.placeRefs.forEach(r=>{r.id&&(e.has(r.id)||e.set(r.id,[]),e.get(r.id).push(t.id))})});const t=t=>{const r=e.get(t.id)||[];return t._listIds=r,t};this.savedPlaces=this.savedPlaces.map(e=>t({...e})),this.placesInView=this.placesInView.map(e=>t({...e}))}async togglePlaceList(e,t,r){if(!e)return;let n=e;if(!e.id||!e.geohash){if(!r)return;n=await this.storePlace(e)}try{return r?await this.places.lists.addPlace(t,n.id,n.geohash):await this.places.lists.removePlace(t,n.id),await this.loadLists(),this.findPlaceById(n.id)}catch(i){throw console.error("Failed to toggle place in list:",i),i}}async loadPlacesInBounds(e){const t=getGeohashPrefixesInBbox(e).filter(e=>!this.loadedPrefixes.includes(e));0!==t.length&&(console.debug("Loading new prefixes:",t),await this.loadAllPlaces(t),this.loadedPrefixes=[...this.loadedPrefixes,...t],this.currentBbox=e)}async loadAllPlaces(e=null){try{const t=await this.places.getPlaces(e);if(t&&Array.isArray(t)){if(e){const r=new Set(e),n=this.placesInView.filter(e=>{if(!e.lat||!e.lon)return!1;try{const t=Geohash.encode(e.lat,e.lon,4);return!r.has(t)}catch{return!0}});this.placesInView=[...n,...t]}else this.placesInView=t;this.refreshPlaceListAssociations()}else e||(this.placesInView=[]);console.debug("Loaded saved places:",this.placesInView.length)}catch(t){console.error("Failed to load places:",t)}}findPlaceById(e){if(!e)return;const t=String(e);let r=this.savedPlaces.find(e=>e.id&&String(e.id)===t);return r||(r=this.placesInView.find(e=>e.id&&String(e.id)===t),r||(r=this.savedPlaces.find(e=>e.osmId&&String(e.osmId)===t),r||(r=this.placesInView.find(e=>e.osmId&&String(e.osmId)===t),r)))}isPlaceSaved(e){return!!this.findPlaceById(e)}async storePlace(e){const t=await this.places.store(e);return this.savedPlaces.some(e=>e.id===t.id)?this.savedPlaces=this.savedPlaces.map(e=>e.id===t.id?t:e):this.savedPlaces=[...this.savedPlaces,t],this.placesInView.some(e=>e.id===t.id)?this.placesInView=this.placesInView.map(e=>e.id===t.id?t:e):this.placesInView=[...this.placesInView,t],t}async updatePlace(e){const t=await this.places.store(e),r=this.savedPlaces.findIndex(e=>e.id===t.id);if(-1!==r){const e=[...this.savedPlaces];e[r]=t,this.savedPlaces=e}return this.placesInView=this.placesInView.map(e=>e.id===t.id?t:e),t}async removePlace(e){await this.places.remove(e.id,e.geohash),this.savedPlaces=this.savedPlaces.filter(t=>t.id!==e.id),this.placesInView.length>0&&(this.placesInView=this.placesInView.filter(t=>t.id!==e.id))}async refreshPlace(e){if(!(e&&e.id&&e.osmId&&e.osmType))return null;try{console.debug(`Checking for updates for ${e.title} (${e.osmId})`);const t=await this.osm.fetchOsmObject(e.osmId,e.osmType);if(!t)return console.warn("Could not fetch fresh data for",e.osmId),null;let r=!1;const n={},i=Math.abs(e.lat-t.lat),o=Math.abs(e.lon-t.lon);(i>1e-5||o>1e-5)&&(r=!0,n.lat=t.lat,n.lon=t.lon);const s=e.osmTags||{},a=t.osmTags||{},l=new Set([...Object.keys(s),...Object.keys(a)]);for(const e of l)if(s[e]!==a[e]){r=!0,n.osmTags=a;break}if(!r)return console.debug("No changes detected for",e.title),null;console.debug("Changes detected:",n);const c={...e,...n},u=getLocalizedName(s),h=getLocalizedName(a);return e.title===u&&u!==h&&(c.title=h),await this.updatePlace(c)}catch(t){return console.error("Failed to refresh place:",t),null}}showConnectWidget(){this.isWidgetOpen=!0,document.querySelector(".rs-widget")||this.widget.attach("rs-widget-container")}static{decorateMethodV2(this.prototype,"showConnectWidget",[action])}closeWidget(){this.isWidgetOpen=!1}static{decorateMethodV2(this.prototype,"closeWidget",[action])}disconnect(){this.rs.disconnect(),this.isWidgetOpen=!1}static{decorateMethodV2(this.prototype,"disconnect",[action])}}const amdModule14=Object.freeze(Object.defineProperty({__proto__:null,default:StorageService},Symbol.toStringTag,{value:"Module"}));class ToastService extends Service{static{decorateFieldV2(this.prototype,"message",[tracked],function(){return null})}#we=void initializeDeferredDecorator(this,"message");static{decorateFieldV2(this.prototype,"isVisible",[tracked],function(){return!1})}#Ce=void initializeDeferredDecorator(this,"isVisible");timeoutId=null;show(e,t=3e3){this.message=e,this.isVisible=!0,this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.isVisible=!1},t)}}const amdModule15=Object.freeze(Object.defineProperty({__proto__:null,default:ToastService},Symbol.toStringTag,{value:"Module"}));function getDistance$1(e,t,r,n){const i=e*Math.PI/180,o=r*Math.PI/180,s=(r-e)*Math.PI/180,a=(n-t)*Math.PI/180,l=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(o)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3}const amdModule18=Object.freeze(Object.defineProperty({__proto__:null,getDistance:getDistance$1},Symbol.toStringTag,{value:"Module"})),activity='',arrowLeft='',bookmark='',featherCamera='',checkSquare='',chevronLeft='',chevronRight='',clock='',database='',edit='',facebook='',gift='',globe='',heart='',home='',info='',instagram='',logIn='',logOut='',mail='',map='',mapPin='',menu='',navigation='',phone='',plus='',search='',server='',settings='',target='',trash2='',uploadCloud='',user='',x$1='',check='',alertCircle='',zap='',angelfish='\n \n',barbell='\n \n',climbingWall='\n \n',banknote='\n \n',badgeShieldWithFire='\n \n',beachUmbrellaInGround='\n \n',beerMugWithFoam='\n \n',burgerAndDrinkCupWithStraw='\n \n',bridge='\n \n',bus='\n \n',camera='\n \n',boxingGloveUp='\n \n',car='\n \n',cigaretteWithSmokeCurl='\n \n',classicalBuilding='\n \n',classicalBuildingWithDomeAndFlag='\n \n',classicalBuildingWithFlag='\n \n',commercialBuilding='\n \n',clothesHanger='\n \n',cleaver='\n \n',cloth='\n \n',cocktail='\n \n',coffeeBean='\n \n',comedyMaskAndTragedyMask='\n \n',croissant='\n \n',cupAndSaucer='\n \n',donut='\n \n',eyeglasses='\n \n',fancyMirrorWithReflectionAndStars='\n \n',familyRestroomSymbol='\n \n',film='\n \n',fingernailPolished='\n \n',fish='\n \n',flagCheckered='\n \n',flowerBouquet='\n \n',fort='\n \n',forkAndKnife='\n \n',gravestone='\n \n',grecianVase='\n \n',greekCross='\n \n',iceCreamOnCone='\n \n',industrialBuilding='\n \n',jewel='\n \n',lowriseBuilding='\n \n',marketStall='\n \n',memorialStoneWithInscription='\n \n',mobilePhoneWithKeypadAndAntenna='\n \n',molarTooth='\n \n',needleAndSpoolOfThread='\n \n',openBook='\n \n',palace='\n \n',parkingP='\n \n',personCricketBattingAtCricketBall='\n \n',personBoardingTramWithDestinationDisplayAndPantographOnTramTrack='\n \n',personJockeyingRacehorse='\n \n',personPlayingTennis='\n \n',personRunning='\n \n',personSleepingInBed='\n \n',personSwimmingInWater='\n \n',personSwingingGolfClub='\n \n',plantInRaisedPlanter='\n \n',placeOfWorshipBuilding='\n \n',playStructureWithSlide='\n \n',policeOfficerWithStopArm='\n \n',planeTopRight='\n \n',roundStructureWithFlag='\n \n',sailingShipInWater='\n \n',scissorsOpen='\n \n',shipwreckInWater='\n \n',steamTrainOnRailwayTrack='\n \n',shoppingBag='\n \n',shoppingBasket='\n \n',shoppingCart='\n \n',tableTennisPaddle='\n \n',tattooMachine='\n \n',toolbox='\n \n',treeAndBenchWithBackrest='\n \n',villageBuildings='\n \n',wallHangingWithMountainsAndSun='\n \n',windingWayWide='\n \n',womensAndMensRestroomSymbol='\n \n',loadingRing='',nostrich='\n \n\n',remotestorage='\n\x3c!-- Creator: CorelDRAW X7 --\x3e\n\n \n',whatsapp='\n\n \n\n',wikipedia='\n\n\n',ICONS={activity:activity,angelfish:angelfish,"arrow-left":arrowLeft,barbell:barbell,banknote:banknote,"badge-shield-with-fire":badgeShieldWithFire,"beach-umbrella-in-ground":beachUmbrellaInGround,"beer-mug-with-foam":beerMugWithFoam,bookmark:bookmark,"boxing-glove-up":boxingGloveUp,"burger-and-drink-cup-with-straw":burgerAndDrinkCupWithStraw,bridge:bridge,bus:bus,camera:camera,"feather-camera":featherCamera,"check-square":checkSquare,"chevron-left":chevronLeft,"chevron-right":chevronRight,"cigarette-with-smoke-curl":cigaretteWithSmokeCurl,climbing_wall:climbingWall,check:check,"alert-circle":alertCircle,"classical-building":classicalBuilding,"classical-building-with-dome-and-flag":classicalBuildingWithDomeAndFlag,"classical-building-with-flag":classicalBuildingWithFlag,"commercial-building":commercialBuilding,"clothes-hanger":clothesHanger,cleaver:cleaver,cloth:cloth,cocktail:cocktail,clock:clock,"coffee-bean":coffeeBean,"comedy-mask-and-tragedy-mask":comedyMaskAndTragedyMask,croissant:croissant,"cup-and-saucer":cupAndSaucer,database:database,donut:donut,edit:edit,eyeglasses:eyeglasses,facebook:facebook,"fancy-mirror-with-reflection-and-stars":fancyMirrorWithReflectionAndStars,"family-restroom-symbol":familyRestroomSymbol,film:film,"fingernail-polished":fingernailPolished,fish:fish,"flag-checkered":flagCheckered,"flower-bouquet":flowerBouquet,"fork-and-knife":forkAndKnife,fort:fort,gift:gift,globe:globe,gravestone:gravestone,"grecian-vase":grecianVase,"greek-cross":greekCross,heart:heart,home:home,"ice-cream-on-cone":iceCreamOnCone,"industrial-building":industrialBuilding,info:info,instagram:instagram,jewel:jewel,"log-in":logIn,"log-out":logOut,"lowrise-building":lowriseBuilding,mail:mail,map:map,"map-pin":mapPin,"market-stall":marketStall,"memorial-stone-with-inscription":memorialStoneWithInscription,menu:menu,"mobile-phone-with-keypad-and-antenna":mobilePhoneWithKeypadAndAntenna,"molar-tooth":molarTooth,navigation:navigation,"needle-and-spool-of-thread":needleAndSpoolOfThread,nostrich:nostrich,"open-book":openBook,palace:palace,"person-cricket-batting-at-cricket-ball":personCricketBattingAtCricketBall,"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track":personBoardingTramWithDestinationDisplayAndPantographOnTramTrack,"person-jockeying-racehorse":personJockeyingRacehorse,"person-playing-tennis":personPlayingTennis,"person-running":personRunning,"person-sleeping-in-bed":personSleepingInBed,"person-swimming-in-water":personSwimmingInWater,"person-swinging-golf-club":personSwingingGolfClub,phone:phone,"plane-top-right":planeTopRight,"plant-in-raised-planter":plantInRaisedPlanter,"place-of-worship-building":placeOfWorshipBuilding,"play-structure-with-slide":playStructureWithSlide,"police-officer-with-stop-arm":policeOfficerWithStopArm,plus:plus,"round-structure-with-flag":roundStructureWithFlag,remotestorage:remotestorage,"sailing-ship-in-water":sailingShipInWater,"scissors-open":scissorsOpen,"shipwreck-in-water":shipwreckInWater,"steam-train-on-railway-track":steamTrainOnRailwayTrack,"shopping-bag":shoppingBag,search:search,server:server,settings:settings,"shopping-basket":shoppingBasket,"shopping-cart":shoppingCart,"table-tennis-paddle":tableTennisPaddle,"tattoo-machine":tattooMachine,toolbox:toolbox,target:target,"trash-2":trash2,"upload-cloud":uploadCloud,"tree-and-bench-with-backrest":treeAndBenchWithBackrest,user:user,"village-buildings":villageBuildings,"wall-hanging-with-mountains-and-sun":wallHangingWithMountainsAndSun,"womens-and-mens-restroom-symbol":womensAndMensRestroomSymbol,whatsapp:whatsapp,wikipedia:wikipedia,winding_way_wide:windingWayWide,parking_p:parkingP,car:car,x:x$1,zap:zap,"loading-ring":loadingRing},FILLED_ICONS=["fork-and-knife","wikipedia","whatsapp","cup-and-saucer","coffee-bean","shopping-basket","person-sleeping-in-bed","loading-ring","nostrich"];function getIcon(e){return ICONS[e]}function isIconFilled(e){return FILLED_ICONS.includes(e)}const amdModule20=Object.freeze(Object.defineProperty({__proto__:null,getIcon:getIcon,isIconFilled:isIconFilled},Symbol.toStringTag,{value:"Module"})),POI_ICON_RULES=[{tags:{cuisine:"donut"},icon:"donut"},{tags:{cuisine:"doughnut"},icon:"donut"},{tags:{cuisine:"coffee_shop"},icon:"coffee-bean"},{tags:{cuisine:"coffee"},icon:"coffee-bean"},{tags:{amenity:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{cuisine:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{shop:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{amenity:"cafe"},icon:"cup-and-saucer"},{tags:{amenity:"restaurant"},icon:"fork-and-knife"},{tags:{amenity:"fast_food"},icon:"burger-and-drink-cup-with-straw"},{tags:{amenity:"pub"},icon:"beer-mug-with-foam"},{tags:{amenity:"bar"},icon:"cocktail"},{tags:{amenity:"food_court"},icon:"fork-and-knife"},{tags:{amenity:"childcare"},icon:"family-restroom-symbol"},{tags:{amenity:"community_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_facility"},icon:"family-restroom-symbol"},{tags:{amenity:"bank"},icon:"banknote"},{tags:{amenity:"place_of_worship"},icon:"place-of-worship-building"},{tags:{amenity:"fire_station"},icon:"badge-shield-with-fire"},{tags:{amenity:"police"},icon:"police-officer-with-stop-arm"},{tags:{amenity:"toilets"},icon:"womens-and-mens-restroom-symbol"},{tags:{amenity:"school"},icon:"open-book"},{tags:{amenity:"driving_school"},icon:"car"},{tags:{shop:"coffee"},icon:"coffee-bean"},{tags:{shop:"tea"},icon:"coffee-bean"},{tags:{shop:"pastry"},icon:"donut"},{tags:{shop:"supermarket"},icon:"shopping-cart"},{tags:{shop:"convenience"},icon:"shopping-basket"},{tags:{shop:"grocery"},icon:"shopping-basket"},{tags:{shop:"greengrocer"},icon:"shopping-basket"},{tags:{shop:"bakery"},icon:"croissant"},{tags:{shop:"butcher"},icon:"cleaver"},{tags:{shop:"seafood"},icon:"fish"},{tags:{shop:"deli"},icon:"shopping-basket"},{tags:{shop:"clothes"},icon:"clothes-hanger"},{tags:{shop:"clothing"},icon:"clothes-hanger"},{tags:{shop:"hairdresser"},icon:"scissors-open"},{tags:{shop:"optician"},icon:"eyeglasses"},{tags:{shop:"fabric"},icon:"cloth"},{tags:{shop:"flea_market"},icon:"market-stall"},{tags:{shop:"kiosk"},icon:"shopping-basket"},{tags:{shop:"leather"},icon:"shopping-bag"},{tags:{shop:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{shop:"jewelry"},icon:"jewel"},{tags:{shop:"jewellery"},icon:"jewel"},{tags:{shop:"tobacco"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"cannabis"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"florist"},icon:"flower-bouquet"},{tags:{shop:"garden_centre"},icon:"plant-in-raised-planter"},{tags:{shop:"estate_agent"},icon:"village-buildings"},{tags:{shop:"mobile_phone"},icon:"mobile-phone-with-keypad-and-antenna"},{tags:{beauty:"nails"},icon:"fingernail-polished"},{tags:{shop:"tattoo"},icon:"tattoo-machine"},{tags:{shop:"beauty"},icon:"fancy-mirror-with-reflection-and-stars"},{tags:{craft:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{office:"estate_agent"},icon:"village-buildings"},{tags:{office:!0},icon:"commercial-building"},{tags:{craft:!0},icon:"toolbox"},{tags:{shop:!0},icon:"shopping-bag"},{tags:{natural:"beach"},icon:"beach-umbrella-in-ground"},{tags:{leisure:"park"},icon:"tree-and-bench-with-backrest"},{tags:{leisure:"playground"},icon:"play-structure-with-slide"},{tags:{aeroway:"aerodrome"},icon:"plane-top-right"},{tags:{aeroway:"heliport"},icon:"plane-top-right"},{tags:{aeroway:"helipad"},icon:"plane-top-right"},{tags:{highway:"bus_stop"},icon:"bus"},{tags:{bus:!0},icon:"bus"},{tags:{railway:"tram_stop"},icon:"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track"},{tags:{tourism:"museum"},icon:"classical-building"},{tags:{tourism:"gallery"},icon:"wall-hanging-with-mountains-and-sun"},{tags:{tourism:"aquarium"},icon:"angelfish"},{tags:{tourism:"theme_park"},icon:"camera"},{tags:{tourism:"attraction"},icon:"camera"},{tags:{tourism:"viewpoint"},icon:"camera"},{tags:{tourism:"zoo"},icon:"camera"},{tags:{tourism:"artwork"},icon:"camera"},{tags:{amenity:"cinema"},icon:"film"},{tags:{amenity:"theatre"},icon:"camera"},{tags:{amenity:"arts_centre"},icon:"comedy-mask-and-tragedy-mask"},{tags:{amenity:"arts_center"},icon:"comedy-mask-and-tragedy-mask"},{tags:{historic:"canal"},icon:"winding_way_wide"},{tags:{historic:"bridge"},icon:"bridge"},{tags:{historic:"bridge_site"},icon:"bridge"},{tags:{historic:"fort"},icon:"fort"},{tags:{historic:"castle"},icon:"palace"},{tags:{historic:"building"},icon:"classical-building-with-flag"},{tags:{historic:"archaeological_site"},icon:"grecian-vase"},{tags:{historic:"memorial"},icon:"memorial-stone-with-inscription"},{tags:{historic:"tomb"},icon:"gravestone"},{tags:{historic:"monument"},icon:"classical-building-with-dome-and-flag"},{tags:{historic:"folly"},icon:"classical-building"},{tags:{historic:"industrial"},icon:"industrial-building"},{tags:{historic:"railway_station"},icon:"steam-train-on-railway-track"},{tags:{historic:"ship"},icon:"sailing-ship-in-water"},{tags:{historic:"wreck"},icon:"shipwreck-in-water"},{tags:{historic:"ruins"},icon:"camera"},{tags:{historic:"ruin"},icon:"camera"},{tags:{historic:"yes"},icon:"camera"},{tags:{tourism:"hotel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"hostel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"motel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"guest_house"},icon:"person-sleeping-in-bed"},{tags:{sport:"motor"},icon:"flag-checkered"},{tags:{sport:"karting"},icon:"flag-checkered"},{tags:{sport:"motocross"},icon:"flag-checkered"},{tags:{sport:"cricket"},icon:"person-cricket-batting-at-cricket-ball"},{tags:{sport:"boxing"},icon:"boxing-glove-up"},{tags:{sport:"martial_arts"},icon:"boxing-glove-up"},{tags:{sport:"tennis"},icon:"person-playing-tennis"},{tags:{sport:"squash"},icon:"person-playing-tennis"},{tags:{sport:"padel"},icon:"person-playing-tennis"},{tags:{sport:"table_tennis"},icon:"table-tennis-paddle"},{tags:{sport:"climbing"},icon:"climbing_wall"},{tags:{leisure:"water_park"},icon:"person-swimming-in-water"},{tags:{sport:"swimming"},icon:"person-swimming-in-water"},{tags:{sport:"golf"},icon:"person-swinging-golf-club"},{tags:{leisure:"golf_course"},icon:"person-swinging-golf-club"},{tags:{sport:"horse_racing"},icon:"person-jockeying-racehorse"},{tags:{sport:"fitness"},icon:"barbell"},{tags:{sport:"fitness_centre"},icon:"barbell"},{tags:{leisure:"fitness_centre"},icon:"barbell"},{tags:{sport:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"sports_centre"},icon:"person-running"},{tags:{leisure:"pitch"},icon:"person-running"},{tags:{sport:!0},icon:"person-running"},{tags:{amenity:"dentist"},icon:"molar-tooth"},{tags:{healthcare:"dentist"},icon:"molar-tooth"},{tags:{healthcare:!0},icon:"greek-cross"},{tags:{amenity:"parking"},icon:"parking_p"},{tags:{building:"commercial"},icon:"commercial-building"},{tags:{building:"apartments"},icon:"lowrise-building"}];function getIconNameForTags(e){if(!e)return null;for(const t of POI_ICON_RULES){let r=!0;for(const[n,i]of Object.entries(t.tags)){const t=e[n];if(!t){r=!1;break}const o=t.split(";").map(e=>e.trim());if(!0!==i&&!o.includes(i)){r=!1;break}}if(r)return t.icon}return null}function getIconSvgForTags(e){const t=getIconNameForTags(e);return t?getIcon(t):null}const amdModule22=Object.freeze(Object.defineProperty({__proto__:null,POI_ICON_RULES:POI_ICON_RULES,getIconNameForTags:getIconNameForTags,getIconSvgForTags:getIconSvgForTags},Symbol.toStringTag,{value:"Module"}));function mapToStorageSchema(e){return{title:e.title||getLocalizedName(e.osmTags,"Untitled Place"),lat:e.lat,lon:e.lon,tags:[],url:e.osmTags?.website,osmId:String(e.osmId||e.id),osmType:e.osmType,osmTags:e.osmTags||{},description:e.description}}const amdModule24=Object.freeze(Object.defineProperty({__proto__:null,mapToStorageSchema:mapToStorageSchema},Symbol.toStringTag,{value:"Module"})),get$5=(e,...t)=>{for(const r of t)if(e[r])return e[r];return null};function getSocialInfo(e,t){if(!e)return null;const r=`${t}.com`,n=get$5(e,`contact:${t}`,t);if(!n)return null;if(n.startsWith("http"))try{const e=new URL(n);return"facebook"===t&&"/profile.php"===e.pathname&&e.searchParams.has("id")?{url:n,username:e.searchParams.get("id")}:{url:n,username:e.pathname.replace(/^\/|\/$/g,"")||n}}catch{return{url:n,username:n}}const i=n.replace(/^@/,"");return{url:`https://${r}/${i}`,username:i}}const amdModule26=Object.freeze(Object.defineProperty({__proto__:null,getSocialInfo:getSocialInfo},Symbol.toStringTag,{value:"Module"}));var q=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#","$","%","*","+",",","-",".",":",";","=","?","@","[","]","^","_","{","|","}","~"],x=e=>{let t=0;for(let r=0;r{var r="";for(let n=1;n<=t;n++){let i=Math.floor(e)/Math.pow(83,t-n)%83;r+=q[Math.floor(i)]}return r},f=e=>{let t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},h=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(12.92*t*255+.5):Math.trunc(255*(1.055*Math.pow(t,.4166666666666667)-.055)+.5)},F=e=>e<0?-1:1,M=(e,t)=>F(e)*Math.pow(Math.abs(e),t),d=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e}},C=e=>{if(!e||e.length<6)throw new d("The blurhash string must be at least 6 characters");let t=x(e[0]),r=Math.floor(t/9)+1,n=t%9+1;if(e.length!==4+2*n*r)throw new d(`blurhash length mismatch: length is ${e.length} but it should be ${4+2*n*r}`)},z=e=>{let t=e>>8&255,r=255&e;return[f(e>>16),f(t),f(r)]},L=(e,t)=>{let r=Math.floor(e/361),n=Math.floor(e/19)%19,i=e%19;return[M((r-9)/9,2)*t,M((n-9)/9,2)*t,M((i-9)/9,2)*t]},U=(e,t,r,n)=>{C(e),n|=1;let i=x(e[0]),o=Math.floor(i/9)+1,s=i%9+1,a=(x(e[1])+1)/166,l=new Array(s*o);for(let h=0;h{let i=0,o=0,s=0,a=t*A;for(let c=0;c(h(e[0])<<16)+(h(e[1])<<8)+h(e[2]),H=(e,t)=>19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*M(e[0]/t,.5)+9.5))))*19+19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*M(e[1]/t,.5)+9.5))))+Math.floor(Math.max(0,Math.min(18,Math.floor(9*M(e[2]/t,.5)+9.5)))),O=(e,t,r,n,i)=>{if(n<1||n>9||i<1||i>9)throw new d("BlurHash must have between 1 and 9 components");if(t*r*4!==e.length)throw new d("Width and height must match the pixels array");let o=[];for(let u=0;un*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*u*o/r));o.push(s)}let s,a=o[0],l=o.slice(1),c="";if(c+=p(n-1+9*(i-1),1),l.length>0){let e=Math.max(...l.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(166*e-.5))));s=(t+1)/166,c+=p(t,1)}else s=1,c+=p(0,1);return c+=p($(a),4),l.forEach(e=>{c+=p(H(e,s),2)}),c},S=O;self.onmessage=async e=>{if("PROCESS_IMAGE"!==e.data?.type)return;const{id:t,file:r,targetWidth:n,targetHeight:i,quality:o,computeBlurhash:s}=e.data;try{let e,c;try{const t=await createImageBitmap(r,{resizeWidth:n,resizeHeight:i,resizeQuality:"high"});if(e=new OffscreenCanvas(n,i),c=e.getContext("2d"),!c)throw new Error("Failed to get 2d context from OffscreenCanvas");c.drawImage(t,0,0,n,i),t.close()}catch(a){console.warn("Hardware resize failed, falling back to stepped software scaling:",a);const t=await r.arrayBuffer(),o=new Blob([t],{type:r.type}),s=await createImageBitmap(o);let l=s.width,u=s.height,h=new OffscreenCanvas(l,u),d=h.getContext("2d");for(d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.drawImage(s,0,0);.5*h.width>n&&.5*h.height>i;){const e=new OffscreenCanvas(Math.floor(.5*h.width),Math.floor(.5*h.height)),t=e.getContext("2d");t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.drawImage(h,0,0,e.width,e.height),h=e}e=new OffscreenCanvas(n,i),c=e.getContext("2d"),c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(h,0,0,n,i),s.close()}let u=null;if(s)try{const e=c.getImageData(0,0,n,i);u=S(e.data,n,i,4,3)}catch(l){console.warn("Could not generate blurhash (possible canvas fingerprinting protection):",l)}const h=await e.convertToBlob({type:"image/jpeg",quality:o}),d=`${n}x${i}`;self.postMessage({id:t,success:!0,blob:h,dim:d,blurhash:u})}catch(error){self.postMessage({id:t,success:!1,error:error.message})}};const amdModule27=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function _toPrimitive(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return"symbol"==typeof t?t:String(t)}function _defineProperty(e,t,r){return(t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _initializerDefineProperty(e,t,r,n){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(n):void 0})}function _applyDecoratedDescriptor(e,t,r,n){var i={};return Object.keys(n).forEach(function(e){i[e]=n[e]}),i.enumerable=!!i.enumerable,i.configurable=!!i.configurable,("value"in i||i.initializer)&&(i.writable=!0),void 0===(i=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},i)).initializer&&(Object.defineProperty(e,t,i),i=null),i}var _dec$1,_dec2,_class$1,_descriptor$1,_descriptor2;const isFastBoot="undefined"!=typeof FastBoot,RouterEvent={ROUTE_DID_CHANGE:"routeDidChange"};function hasResolveRegistration(e){return"resolveRegistration"in e}function hasPageTitleConfig(e){return"object"==typeof e&&null!==e&&"pageTitle"in e}const configKeys=["separator","prepend","replace"];let PageTitleService=(_dec$1=service("router"),_dec2=service("-document"),_class$1=class extends Service{constructor(e){if(super(e),_initializerDefineProperty(this,"router",_descriptor$1,this),_initializerDefineProperty(this,"document",_descriptor2,this),_defineProperty(this,"tokens",[]),_defineProperty(this,"_defaultConfig",{separator:" | ",prepend:!0,replace:null}),_defineProperty(this,"scheduleTitleUpdate",()=>{scheduleOnce("afterRender",this,this._updateTitle)}),this._validateExistingTitleElement(),hasResolveRegistration(e)){const t=e.resolveRegistration("config:environment");hasPageTitleConfig(t)&&configKeys.forEach(e=>{if(!isEmpty$4(t.pageTitle[e])){const r=t.pageTitle[e];this._defaultConfig[e]=r}})}this.router.on(RouterEvent.ROUTE_DID_CHANGE,this.scheduleTitleUpdate)}applyTokenDefaults(e){const t=this._defaultConfig.separator,r=this._defaultConfig.prepend,n=this._defaultConfig.replace;e.previous??=null,e.next??=null,null==e.separator&&(e.separator=t),null==e.prepend&&null!=r&&(e.prepend=r),null==e.replace&&null!=n&&(e.replace=n)}inheritFromPrevious(e){const t=e.previous;t&&(null==e.separator&&(e.separator=t.separator),null==e.prepend&&(e.prepend=t.prepend))}push(e){const t=this._findTokenById(e.id);if(t){const r=this.tokens.indexOf(t),n=[...this.tokens],i=t.previous;return e.previous=i,e.next=t.next,this.inheritFromPrevious(e),this.applyTokenDefaults(e),n.splice(r,1,e),void(this.tokens=n)}const r=this.tokens.slice(-1)[0];r&&(e.previous=r??null,r.next=e,this.inheritFromPrevious(e)),this.applyTokenDefaults(e),this.tokens=[...this.tokens,e]}remove(e){const t=this._findTokenById(e);if(!t)return;const{next:r,previous:n}=t;r&&(r.previous=n),n&&(n.next=r),t.previous=t.next=null;const i=[...this.tokens];i.splice(i.indexOf(t),1),this.tokens=i}get visibleTokens(){const e=this.tokens;let t=e?e.length:0;const r=[];for(;t--;){const n=e[t];if(n){if(n.replace){r.unshift(n);break}r.unshift(n)}}return r}get sortedTokens(){const e=this.visibleTokens;if(!e)return[];let t=!0,r=[];const n=[r],i=[];return e.forEach(e=>{e.front?i.unshift(e):e.prepend?(t&&(t=!1,r=[],n.push(r)),r.unshift(e)):(t||(t=!0,r=[],n.push(r)),r.push(e))}),i.concat(n.reduce((e,t)=>e.concat(t),[]))}toString(){const e=this.sortedTokens,t=[];for(let r=0,n=e.length;r as well.",document.head.querySelectorAll("title").length<=1)}_findTokenById(e){return this.tokens.find(t=>t.id===e)}updateFastbootTitle(e){if(!isFastBoot)return;const t=this.document.head,r=t.childNodes;for(let o=0;onew EmberGlimmerComponentManager(e),GlimmerComponent);const index=Object.freeze(Object.defineProperty({__proto__:null,default:GlimmerComponent},Symbol.toStringTag,{value:"Module"})),setModifierManager=setModifierManager$1,fn=fn$1;function truthConvert(e){return"object"==typeof e&&e&&"isTruthy"in e&&"boolean"==typeof e.isTruthy?e.isTruthy:isArray$4(e)?0!==e.length:!!e}class OrHelper extends Helper{compute(e){for(let t=0,r=e.length;t[htmlSafe],isStrictMode:!0}),this)}}class PlaceEditForm extends GlimmerComponent{static{decorateFieldV2(this.prototype,"title",[tracked],function(){return""})}#Se=void initializeDeferredDecorator(this,"title");static{decorateFieldV2(this.prototype,"description",[tracked],function(){return""})}#Te=void initializeDeferredDecorator(this,"description");constructor(){super(...arguments),this.title=this.args.place?.title||"",this.description=this.args.place?.description||""}get shouldAutofocus(){return"undefined"!=typeof window&&window.innerWidth>768}handleSubmit(e){e.preventDefault(),this.args.onSave&&this.args.onSave({title:this.title,description:this.description})}static{decorateMethodV2(this.prototype,"handleSubmit",[action])}updateTitle(e){this.title=e.target.value}static{decorateMethodV2(this.prototype,"updateTitle",[action])}updateDescription(e){this.description=e.target.value}static{decorateMethodV2(this.prototype,"updateDescription",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,"form"],[24,0,"edit-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-title"],[12],[1,"Title"],[13],[1,"\\n"],[1," "],[11,"input"],[24,1,"edit-title"],[16,2,[30,0,["title"]]],[24,0,"form-control"],[24,"placeholder","Name of the place"],[16,"autofocus",[30,0,["shouldAutofocus"]]],[24,4,"text"],[4,[32,0],["input",[30,0,["updateTitle"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-desc"],[12],[1,"Description"],[13],[1,"\\n "],[11,"textarea"],[24,1,"edit-desc"],[16,2,[30,0,["description"]]],[24,0,"form-control"],[24,"rows","3"],[24,"placeholder","Add some details..."],[4,[32,0],["input",[30,0,["updateDescription"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"edit-actions"],[12],[1,"\\n "],[10,"button"],[14,0,"btn btn-blue"],[14,4,"submit"],[12],[1,"Save"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"Cancel"],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onCancel"],[]]',moduleName:"/home/basti/src/marco/app/components/place-edit-form.gjs",scope:()=>[on],isStrictMode:!0}),this)}}function installElement$1(e,t){const r=e;return r.element=t,r}class ClassBasedModifierManager{capabilities=modifierCapabilities();constructor(e){this.owner=e}createModifier(e,t){return{instance:new e(this.owner,t),element:null}}installModifier(e,t,r){installElement$1(e,t).instance.modify(t,r.positional,r.named)}updateModifier(e,t){e.instance.modify(e.element,t.positional,t.named)}destroyModifier({instance:e}){destroy(e)}}class ClassBasedModifier{constructor(e,t){setOwner(this,e)}modify(e,t,r){}}function installElement(e,t){const r=e;return r.element=t,r}setModifierManager(e=>new ClassBasedModifierManager(e),ClassBasedModifier);class FunctionBasedModifierManager{capabilities=modifierCapabilities();createModifier(e){return{element:null,instance:e}}installModifier(e,t,r){const n=installElement(e,t),{positional:i,named:o}=r,s=e.instance(t,i,o);"function"==typeof s&&(n.teardown=s)}updateModifier(e,t){"function"==typeof e.teardown&&e.teardown();const r=e.instance(e.element,t.positional,t.named);"function"==typeof r&&(e.teardown=r)}destroyModifier(e){"function"==typeof e.teardown&&e.teardown()}getDebugName(e){return e.instance.toString()}getDebugInstance(e){return e}}const MANAGER=new FunctionBasedModifierManager;function modifier(e){return e.toString=()=>e.name,setModifierManager(()=>MANAGER,e)}const onClickOutside=modifier((e,[t])=>{const r=r=>{e&&!e.contains(r.target)&&t(r)},n=setTimeout(()=>{document.addEventListener("click",r)},0);return()=>{clearTimeout(n),document.removeEventListener("click",r)}});class PlaceListsManager extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"_forceClear",[tracked],function(){return!1})}#Ae=void initializeDeferredDecorator(this,"_forceClear");get isSaved(){return this.args.isSaved}get placeListIds(){return this._forceClear?[]:this.args.place._listIds||[]}styleFor(e){return htmlSafe(`background-color: ${e}`)}isInList(e){return!!this.placeListIds&&this.placeListIds.includes(e.id)}static{decorateMethodV2(this.prototype,"isInList",[action])}async toggleSaved(){if(this.isSaved){const{osmId:e,osmType:t}=this.args.place;if(await this.storage.removePlace(this.args.place),this.args.place&&(this.args.place.id=null,this.args.place.createdAt=null,this.args.place._listIds=[],this._forceClear=!0),e&&t){const e={...this.args.place};delete e.id,delete e.createdAt,delete e._listIds,this.router.transitionTo("place",e)}else this.router.transitionTo("index");this.args.onClose&&this.args.onClose()}else await this.storage.storePlace(this.args.place)}static{decorateMethodV2(this.prototype,"toggleSaved",[action])}async toggleList(e){const t=!this.placeListIds.includes(e.id);t&&!this.isSaved&&await this.storage.storePlace(this.args.place);try{await this.storage.togglePlaceList(this.args.place,e.id,t)}catch(r){console.error(r),alert("Failed to update list: "+r.message)}}static{decorateMethodV2(this.prototype,"toggleList",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[24,0,"place-lists-manager"],[4,[32,0],[[30,1]],null],[12],[1,"\\n "],[10,0],[14,0,"list-item master-toggle"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[30,0,["isSaved"]]],[24,4,"checkbox"],[4,[32,1],["change",[30,0,["toggleSaved"]]],null],[12],[13],[1,"\\n "],[10,1],[14,0,"list-color"],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,"Saved places"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"divider"],[12],[13],[1,"\\n\\n "],[10,0],[14,0,"lists-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["storage","lists"]]],null]],null],null,[[[1," "],[10,0],[14,0,"list-item"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[28,[30,0,["isInList"]],[[30,2]],null]],[16,"disabled",[52,[51,[30,0,["isSaved"]]],true]],[24,4,"checkbox"],[4,[32,1],["change",[28,[32,2],[[30,0,["toggleList"]],[30,2]],null]],null],[12],[13],[1,"\\n"],[1," "],[10,1],[14,0,"list-color"],[15,5,[28,[30,0,["styleFor"]],[[30,2,["color"]]],null]],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,[30,2,["title"]]],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n"],[13]],["@onClose","list"],["each","-track-array","unless"]]',moduleName:"/home/basti/src/marco/app/components/place-lists-manager.gjs",scope:()=>[onClickOutside,on,fn],isStrictMode:!0}),this)}}class Environment{assert(){}async(e){Promise.resolve().then(e)}reportUncaughtRejection(){this.async(e=>{throw e})}defer(){let e={promise:null,resolve:null,reject:null},t=new Promise((t,r)=>{e.resolve=t,e.reject=r});return e.promise=t,e}globalDebuggingEnabled(){return!1}}const DEFAULT_ENVIRONMENT=new Environment;class BoundedPolicy{constructor(e){this.maxConcurrency=e||1}}const TYPE_CANCELLED="CANCELLED",TYPE_STARTED="STARTED",TYPE_QUEUED="QUEUED",STARTED={type:TYPE_STARTED},QUEUED={type:TYPE_QUEUED},makeCancelState=e=>({type:TYPE_CANCELLED,reason:e}),CANCELLED$2=makeCancelState("it belongs to a 'drop' Task that was already running");class DropReducer{constructor(e){this.remainingSlots=e}step(){return this.remainingSlots>0?(this.remainingSlots--,STARTED):CANCELLED$2}}class DropPolicy extends BoundedPolicy{makeReducer(){return new DropReducer(this.maxConcurrency)}}class EnqueuedReducer{constructor(e){this.remainingSlots=e}step(){return this.remainingSlots>0?(this.remainingSlots--,STARTED):QUEUED}}class EnqueuedPolicy extends BoundedPolicy{makeReducer(){return new EnqueuedReducer(this.maxConcurrency)}}const CANCELLED$1=makeCancelState("it belongs to a 'keepLatest' Task that was already running");class KeepLatestReducer{constructor(e,t){this.remainingSlots=e,this.numToCancel=t}step(){return this.remainingSlots>0?(this.remainingSlots--,STARTED):this.numToCancel>0?(this.numToCancel--,CANCELLED$1):QUEUED}}class KeepLatestPolicy extends BoundedPolicy{makeReducer(e,t){let r=e+t;return new KeepLatestReducer(this.maxConcurrency,r-this.maxConcurrency-1)}}const CANCELLED=makeCancelState("it belongs to a 'restartable' Task that was .perform()ed again");class RestartableReducer{constructor(e){this.numToCancel=e}step(){return this.numToCancel>0?(this.numToCancel--,CANCELLED):STARTED}}class RestartablePolicy extends BoundedPolicy{makeReducer(e,t){return new RestartableReducer(e+t-this.maxConcurrency)}}class UnboundedReducer{step(){return STARTED}}const SINGLETON_REDUCER=new UnboundedReducer;class UnboundedPolicy{makeReducer(){return SINGLETON_REDUCER}}const LAST_APPLIED_TAGS=new Map;class Refresh{constructor(e,t,r){this.stateTracker=t,this.schedulerPolicy=e,this.initialTaskInstances=r,this.startingInstances=[]}process(){let[e,t,r]=this.filterFinishedTaskInstances(),n=this.schedulerPolicy.makeReducer(t,r),i=e.filter(e=>this.setTaskInstanceExecutionState(e,n.step()));return this.stateTracker.computeFinalStates(e=>this.applyState(e)),this.startingInstances.forEach(e=>e.start()),i}filterFinishedTaskInstances(){let e=0,t=0;return[this.initialTaskInstances.filter(r=>{let n=this.stateTracker.stateFor(r.task),i=r.executor.state;return i.isFinished?(n.onCompletion(r),!1):(i.hasStarted?e+=1:t+=1,!0)}),e,t]}setTaskInstanceExecutionState(e,t){let r=this.stateTracker.stateFor(e.task);switch(e.executor.counted||(e.executor.counted=!0,r.onPerformed(e)),t.type){case TYPE_CANCELLED:return e.cancel(t.reason),!1;case TYPE_STARTED:return e.executor.state.hasStarted||(this.startingInstances.push(e),r.onStart(e)),r.onRunning(e),!0;case TYPE_QUEUED:return r.onQueued(e),!0}}applyState(e){let{taskable:t}=e;if(!t.onState)return;const{guid:r}=t;if(LAST_APPLIED_TAGS.has(r)&&e.tage(t))}forEachState(e){this.states.forEach(t=>e(t))}}class NullState{onCompletion(){}onPerformed(){}onStart(){}onRunning(){}onQueued(){}}const NULL_STATE=new NullState;class NullStateTracker{stateFor(){return NULL_STATE}computeFinalStates(){}}class Scheduler{constructor(e,t){this.schedulerPolicy=e,this.stateTrackingEnabled=t,this.taskInstances=[]}cancelAll(e,t){let r=this.taskInstances.map(r=>{r.task.guids[e]&&r.executor.cancel(t)}).filter(e=>!!e);return Promise.all(r)}perform(e){e.onFinalize(()=>this.scheduleRefresh()),this.taskInstances.push(e),this.refresh()}scheduleRefresh(){Promise.resolve().then(()=>this.refresh())}refresh(){let e=this.stateTrackingEnabled?new StateTracker:new NullStateTracker,t=new Refresh(this.schedulerPolicy,e,this.taskInstances);this.taskInstances=t.process()}}class GeneratorStepResult{constructor(e,t,r){this.value=e,this.done=t,this.errored=r}}class GeneratorState{constructor(e){this.done=!1,this.generatorFactory=e,this.iterator=null}step(e,t){try{let r=this.getIterator(),{value:n,done:i}=r[t](e);return i?this.finalize(n,!1):new GeneratorStepResult(n,!1,!1)}catch(r){return this.finalize(r,!0)}}getIterator(){return this.iterator||this.done||(this.iterator=this.generatorFactory()),this.iterator}finalize(e,t){return this.done=!0,this.iterator=null,new GeneratorStepResult(e,!0,t)}}const cancelableSymbol="__ec_cancel__",yieldableSymbol="__ec_yieldable__",YIELDABLE_CONTINUE="next",YIELDABLE_THROW="throw",YIELDABLE_RETURN="return",YIELDABLE_CANCEL="cancel";class YieldableState{constructor(e,t){this._taskInstance=e,this._resumeIndex=t}getTaskInstance(){return this._taskInstance}cancel(){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,YIELDABLE_CANCEL)}next(e){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,YIELDABLE_CONTINUE,e)}return(e){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,YIELDABLE_RETURN,e)}throw(e){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,YIELDABLE_THROW,e)}}class Yieldable{constructor(){this[yieldableSymbol]=this[yieldableSymbol].bind(this)}onYield(){}_deferable(){let e={resolve:void 0,reject:void 0};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}_toPromise(){let e=this._deferable(),t={proceed(t,r,n){r==YIELDABLE_CONTINUE||r==YIELDABLE_RETURN?e.resolve(n):e.reject(n)}},r=this[yieldableSymbol](t,0);return e.promise[cancelableSymbol]=r,e.promise}then(...e){return this._toPromise().then(...e)}catch(...e){return this._toPromise().catch(...e)}finally(...e){return this._toPromise().finally(...e)}[yieldableSymbol](e,t){let r=new YieldableState(e,t);return this.onYield(r)}}class ForeverYieldable extends Yieldable{onYield(){}}new ForeverYieldable;const INITIAL_STATE={completionState:COMPLETION_PENDING,value:null,error:null,isSuccessful:!1,isError:!1,isCanceled:!1,hasStarted:!1,isFinished:!1},TASK_CANCELATION_NAME="TaskCancelation";function didCancel(e){return e&&e.name===TASK_CANCELATION_NAME}const CANCEL_KIND_EXPLICIT="explicit",CANCEL_KIND_YIELDABLE_CANCEL="yielded",CANCEL_KIND_LIFESPAN_END="lifespan_end",CANCEL_KIND_PARENT_CANCEL="parent_cancel";class CancelRequest{constructor(e,t){this.kind=e,this.reason=t,this.promise=new Promise(e=>{this.finalize=e})}}const PERFORM_TYPE_DEFAULT="PERFORM_TYPE_DEFAULT",PERFORM_TYPE_UNLINKED="PERFORM_TYPE_UNLINKED",PERFORM_TYPE_LINKED="PERFORM_TYPE_LINKED",CANCEL_RETURN_VALUE_SENTINEL={};let TASK_INSTANCE_STACK=[];function getRunningInstance(){return TASK_INSTANCE_STACK[TASK_INSTANCE_STACK.length-1]}class TaskInstanceExecutor{constructor({generatorFactory:e,env:t,debug:r}){this.generatorState=new GeneratorState(e),this.state=Object.assign({},INITIAL_STATE),this.index=1,this.disposers=[],this.finalizeCallbacks=[],this.env=t,this.debug=r,this.cancelRequest=null}start(){this.state.hasStarted||this.cancelRequest||(this.setState({hasStarted:!0}),this.proceedSync(YIELDABLE_CONTINUE,void 0))}cancel(e){return this.requestCancel(e)?(this.state.hasStarted?this.proceedWithCancelAsync():this.finalizeWithCancel(),this.cancelRequest.promise):(e.finalize(),e.promise)}setState(e){Object.assign(this.state,e),this.taskInstance.setState(this.state)}proceedChecked(e,t,r){this.state.isFinished||this.advanceIndex(e)&&(t===YIELDABLE_CANCEL?(this.requestCancel(new CancelRequest(CANCEL_KIND_YIELDABLE_CANCEL),r),this.proceedWithCancelAsync()):this.proceedAsync(t,r))}proceedWithCancelAsync(){this.proceedAsync(YIELDABLE_RETURN,CANCEL_RETURN_VALUE_SENTINEL)}proceedAsync(e,t){this.advanceIndex(this.index),this.env.async(()=>this.proceedSync(e,t))}proceedSync(e,t){this.state.isFinished||(this.dispose(),this.generatorState.done?this.handleResolvedReturnedValue(e,t):this.handleResolvedContinueValue(e,t))}handleResolvedContinueValue(e,t){let r=this.index,n=this.generatorStep(t,e);this.advanceIndex(r)&&(n.errored?this.finalize(n.value,COMPLETION_ERROR):this.handleYieldedValue(n))}handleResolvedReturnedValue(e,t){switch(e){case YIELDABLE_CONTINUE:case YIELDABLE_RETURN:this.finalize(t,COMPLETION_SUCCESS);break;case YIELDABLE_THROW:this.finalize(t,COMPLETION_ERROR)}}handleYieldedUnknownThenable(e){let t=this.index;e.then(e=>{this.proceedChecked(t,YIELDABLE_CONTINUE,e)},e=>{this.proceedChecked(t,YIELDABLE_THROW,e)})}advanceIndex(e){if(this.index===e)return++this.index}handleYieldedValue(e){let t=e.value;t?(this.addDisposer(t[cancelableSymbol]),t[yieldableSymbol]?this.invokeYieldable(t):"function"==typeof t.then?this.handleYieldedUnknownThenable(t):this.proceedWithSimpleValue(t)):this.proceedWithSimpleValue(t)}proceedWithSimpleValue(e){this.proceedAsync(YIELDABLE_CONTINUE,e)}addDisposer(e){"function"==typeof e&&this.disposers.push(e)}dispose(){let e=this.disposers;0!==e.length&&(this.disposers=[],e.forEach(e=>e()))}generatorStep(e,t){TASK_INSTANCE_STACK.push(this);let r=this.generatorState.step(e,t);if(TASK_INSTANCE_STACK.pop(),this._expectsLinkedYield){let e=r.value;e&&e.performType===PERFORM_TYPE_LINKED||console.warn("You performed a .linked() task without immediately yielding/returning it. This is currently unsupported (but might be supported in future version of ember-concurrency)."),this._expectsLinkedYield=!1}return r}maybeResolveDefer(){this.defer&&this.state.isFinished&&(this.state.completionState===COMPLETION_SUCCESS?this.defer.resolve(this.state.value):this.defer.reject(this.state.error))}onFinalize(e){this.finalizeCallbacks.push(e),this.state.isFinished&&this.runFinalizeCallbacks()}runFinalizeCallbacks(){this.finalizeCallbacks.forEach(e=>e()),this.finalizeCallbacks=[],this.maybeResolveDefer(),this.maybeThrowUnhandledTaskErrorLater()}promise(){return this.defer||(this.defer=this.env.defer(),this.asyncErrorsHandled=!0,this.maybeResolveDefer()),this.defer.promise}maybeThrowUnhandledTaskErrorLater(){this.asyncErrorsHandled||this.state.completionState!==COMPLETION_ERROR||didCancel(this.state.error)||this.env.async(()=>{this.asyncErrorsHandled||this.env.reportUncaughtRejection(this.state.error)})}requestCancel(e){return!this.cancelRequest&&!this.state.isFinished&&(this.cancelRequest=e,!0)}finalize(e,t){if(this.cancelRequest)return this.finalizeWithCancel();let r={completionState:t};t===COMPLETION_SUCCESS?(r.isSuccessful=!0,r.value=e):t===COMPLETION_ERROR?(r.isError=!0,r.error=e):t===COMPLETION_CANCEL&&(r.error=e),this.finalizeShared(r)}finalizeWithCancel(){let e=this.taskInstance.formatCancelReason(this.cancelRequest.reason),t=new Error(e);this.debugEnabled()&&console.log(e),t.name=TASK_CANCELATION_NAME,this.finalizeShared({isCanceled:!0,completionState:COMPLETION_CANCEL,error:t,cancelReason:e}),this.cancelRequest.finalize()}debugEnabled(){return this.debug||this.env.globalDebuggingEnabled()}finalizeShared(e){this.index++,e.isFinished=!0,this.setState(e),this.runFinalizeCallbacks()}invokeYieldable(e){try{let t=e[yieldableSymbol](this.taskInstance,this.index);this.addDisposer(t)}catch(t){this.env.reportUncaughtRejection(t)}}onYielded(e,t){this.asyncErrorsHandled=!0,this.onFinalize(()=>{let r=this.state.completionState;r===COMPLETION_SUCCESS?e.proceed(t,YIELDABLE_CONTINUE,this.state.value):r===COMPLETION_ERROR?e.proceed(t,YIELDABLE_THROW,this.state.error):r===COMPLETION_CANCEL&&e.proceed(t,YIELDABLE_CANCEL,null)});let r=this.getPerformType();if(r!==PERFORM_TYPE_UNLINKED)return()=>{this.detectSelfCancelLoop(r,e),this.cancel(new CancelRequest(CANCEL_KIND_PARENT_CANCEL))}}getPerformType(){return this.taskInstance.performType||PERFORM_TYPE_DEFAULT}detectSelfCancelLoop(e,t){if(e!==PERFORM_TYPE_DEFAULT)return;let r=t.executor&&t.executor.cancelRequest;!r||r.kind!==CANCEL_KIND_LIFESPAN_END||this.cancelRequest||this.state.isFinished||this.taskInstance.selfCancelLoopWarning(t)}}const DEFAULT_STATE={last:null,lastRunning:null,lastPerformed:null,lastSuccessful:null,lastComplete:null,lastErrored:null,lastCanceled:null,lastIncomplete:null,performCount:0};Object.freeze(DEFAULT_STATE);let guidId=0;function makeGuid(){return"ec_"+guidId++}class Taskable{constructor(e){this.context=e.context,this.debug=e.debug||!1,this.enabledModifiers=e.enabledModifiers,this.env=e.env,this.group=e.group,this.hasEnabledEvents=e.hasEnabledEvents,this.modifierOptions=e.modifierOptions,this.name=e.name,this.onStateCallback=e.onStateCallback,this.scheduler=e.scheduler,this.guid=makeGuid(),this.guids={},this.guids[this.guid]=!0,this.group&&Object.assign(this.guids,this.group.guids)}cancelAll(e){let{reason:t,cancelRequestKind:r,resetState:n}=e||{};t=t||".cancelAll() was explicitly called on the Task";let i=new CancelRequest(r||CANCEL_KIND_EXPLICIT,t);return this.scheduler.cancelAll(this.guid,i).then(()=>{n&&this._resetState()})}get _isAlive(){return!0}_resetState(){this.setState(DEFAULT_STATE)}setState(){}}Object.assign(Taskable.prototype,DEFAULT_STATE),Object.assign(Taskable.prototype,{numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"});class TaskLinkProxy{constructor(e,t,r){this.task=e,this.performType=t,this.linkedObject=r}perform(...e){return this.task._performShared(e,this.performType,this.linkedObject)}}let Task$1=class e extends Taskable{constructor(e){super(e),this.generatorFactory=e.generatorFactory,this.perform=this._perform.bind(this)}linked(){let e=getRunningInstance();if(!e)throw new Error("You can only call .linked() from within a task.");return new TaskLinkProxy(this,PERFORM_TYPE_LINKED,e)}unlinked(){return new TaskLinkProxy(this,PERFORM_TYPE_UNLINKED,null)}toString(){return``}_clone(){return new e({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}_curry(...e){let t=this._clone();return t._curryArgs=[...this._curryArgs||[],...e],t}_perform(...e){return this._performShared(e,PERFORM_TYPE_DEFAULT,null)}_performShared(e,t,r){let n=this._curryArgs?[...this._curryArgs,...e]:e,i=this._taskInstanceFactory(n,t,r);return t===PERFORM_TYPE_LINKED&&(r._expectsLinkedYield=!0),this._isAlive||i.cancel(),this.scheduler.perform(i),i}_taskInstanceOptions(e,t,r){return{args:e,executor:new TaskInstanceExecutor({generatorFactory:()=>this.generatorFactory(e),env:this.env,debug:this.debug}),performType:t,hasEnabledEvents:this.hasEnabledEvents}}};function assertUnsetBufferPolicy(e){if(e._hasSetBufferPolicy)throw new Error(`Cannot set multiple buffer policies on a task. ${e._schedulerPolicyClass} has already been set for task '${e.name}'`)}const MODIFIER_REGISTRY={enqueue:(e,t)=>t&&e.setBufferPolicy(EnqueuedPolicy),debug:(e,t)=>t&&e.setDebug(t),drop:(e,t)=>t&&e.setBufferPolicy(DropPolicy),keepLatest:(e,t)=>t&&e.setBufferPolicy(KeepLatestPolicy),maxConcurrency:(e,t)=>e.setMaxConcurrency(t),onState:(e,t)=>e.setOnState(t),restartable:(e,t)=>t&&e.setBufferPolicy(RestartablePolicy)};function hasModifier(e){return e in MODIFIER_REGISTRY}let TaskFactory$1=class{env=DEFAULT_ENVIRONMENT;_debug=null;_enabledModifiers=[];_hasSetConcurrencyConstraint=!1;_hasSetBufferPolicy=!1;_hasEnabledEvents=!1;_maxConcurrency=null;_onStateCallback=(e,t)=>t.setState(e);_schedulerPolicyClass=UnboundedPolicy;constructor(e="",t=null,r={}){this.name=e,this.taskDefinition=t,this.options=r,this._processModifierOptions(r)}createTask(e){let t=this.getTaskOptions(e);return new Task$1(Object.assign({generatorFactory:t=>this.taskDefinition.apply(e,t)},t))}getModifier(e){if(hasModifier(e))return MODIFIER_REGISTRY[e].bind(null,this)}getOptions(){return this.options}getScheduler(e,t){return new Scheduler(e,t)}getTaskOptions(e){let t,r=this._onStateCallback,n=new this._schedulerPolicyClass(this._maxConcurrency);return t=this.getScheduler(n,r&&"function"==typeof r),{context:e,debug:this._debug,env:this.env,name:this.name,group:void 0,scheduler:t,hasEnabledEvents:this._hasEnabledEvents,onStateCallback:r,enabledModifiers:this._enabledModifiers,modifierOptions:this.getOptions()}}setBufferPolicy(e){return assertUnsetBufferPolicy(this),this._hasSetBufferPolicy=!0,this._hasSetConcurrencyConstraint=!0,this._schedulerPolicyClass=e,this}setDebug(e){return this._debug=e,this}setEvented(e){return this._hasEnabledEvents=e,this}setMaxConcurrency(e){return this._hasSetConcurrencyConstraint=!0,this._maxConcurrency=e,this}setName(e){return this.name=e,this}setOnState(e){return this._onStateCallback=e,this}setTaskDefinition(e){return this.taskDefinition=e,this}_processModifierOptions(e){if(e)for(let t of Object.keys(e)){let r=e[t],n=this.getModifier(t);"function"==typeof n&&n(r)&&this._enabledModifiers.push(t)}}};class EmberEnvironment extends Environment{assert(...e){assert$3(...e)}async(e){join$1(()=>schedule("actions",e))}reportUncaughtRejection(e){next(null,function(){const t=getOnerror();if(!t)throw e;t(e)})}defer(){return defer$1()}globalDebuggingEnabled(){return!1}}const EMBER_ENVIRONMENT=new EmberEnvironment;class EmberScheduler extends Scheduler{scheduleRefresh(){once(this,this.refresh)}}const EXPLICIT_CANCEL_REASON=".cancel() was explicitly called";class BaseTaskInstance{constructor({task:e,args:t,executor:r,performType:n,hasEnabledEvents:i}){this.task=e,this.args=t,this.performType=n,this.executor=r,this.executor.taskInstance=this,this.hasEnabledEvents=i}setState(){}formatCancelReason(){}selfCancelLoopWarning(){}onFinalize(e){this.executor.onFinalize(e)}proceed(e,t,r){this.executor.proceedChecked(e,t,r)}[yieldableSymbol](e,t){return this.executor.onYielded(e,t)}cancel(e=EXPLICIT_CANCEL_REASON){this.executor.cancel(new CancelRequest(CANCEL_KIND_EXPLICIT,e))}then(...e){return this.executor.promise().then(...e)}catch(...e){return this.executor.promise().catch(...e)}finally(...e){return this.executor.promise().finally(...e)}toString(){return`${this.task} TaskInstance`}start(){return this.executor.start(),this}}function trackMixin(e,t,r){const n=Object.getOwnPropertyDescriptor(e,r);n.initializer=n.initializer||(()=>e[r]),delete n.value;const i=tracked(t,r,n);return t[r]=i,t}function applyTracked(e,t){return Object.keys(e).reduce((t,r)=>trackMixin(e,t,r),t)}let TRACKED_INITIAL_TASK_STATE,TRACKED_INITIAL_INSTANCE_STATE;Object.assign(BaseTaskInstance.prototype,INITIAL_STATE),Object.assign(BaseTaskInstance.prototype,{state:"waiting",isDropped:!1,isRunning:!0}),TRACKED_INITIAL_TASK_STATE=applyTracked(DEFAULT_STATE,{}),TRACKED_INITIAL_TASK_STATE=applyTracked({numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"},TRACKED_INITIAL_TASK_STATE),TRACKED_INITIAL_INSTANCE_STATE=applyTracked(INITIAL_STATE,{}),TRACKED_INITIAL_INSTANCE_STATE=applyTracked({state:"waiting",isDropped:!1,isRunning:!1},TRACKED_INITIAL_INSTANCE_STATE),Object.freeze(TRACKED_INITIAL_TASK_STATE),Object.freeze(TRACKED_INITIAL_INSTANCE_STATE);class TaskInstance extends BaseTaskInstance{setState(e){let t=this._recomputeState(e);Object.assign(this,{...e,isRunning:!e.isFinished,isDropped:"dropped"===t,state:t})}_recomputeState(e){return e.isDropped?"dropped":e.isCanceled?e.hasStarted?"canceled":"dropped":e.isFinished?"finished":e.hasStarted?"running":"waiting"}formatCancelReason(e){return`TaskInstance '${this.getName()}' was canceled because ${e}. For more information, see: http://ember-concurrency.com/docs/task-cancelation-help`}getName(){return this.name||(this.name=this.task&&this.task.name||""),this.name}selfCancelLoopWarning(e){let t=`\`${e.getName()}\``,r=`\`${this.getName()}\``;console.warn(`ember-concurrency detected a potentially hazardous "self-cancel loop" between parent task ${t} and child task ${r}. If you want child task ${r} to be canceled when parent task ${t} is canceled, please change \`.perform()\` to \`.linked().perform()\`. If you want child task ${r} to keep running after parent task ${t} is canceled, change it to \`.unlinked().perform()\``)}triggerEvent(...e){if(!this.hasEnabledEvents)return;let t=this.task,r=t.context,n=t&&t.name;if(r&&r.trigger&&n){let[t,...i]=e;r.trigger(`${n}:${t}`,...i)}}}TRACKED_INITIAL_INSTANCE_STATE&&Object.defineProperties(TaskInstance.prototype,TRACKED_INITIAL_INSTANCE_STATE);const TASKABLE_MIXIN={_performCount:0,setState(e){this._performCount=this._performCount+(e.numPerformedInc||0);let t=e.numRunning>0,r=e.numQueued>0,n=Object.assign({},e,{performCount:this._performCount,isRunning:t,isQueued:r,isIdle:!t&&!r,state:t?"running":"idle"});Object.assign(this,n)},onState(e,t){t.onStateCallback&&t.onStateCallback(e,t)}};class Task extends Task$1{constructor(e){super(e),isDestroying(this.context)||registerDestructor(this.context,()=>{this.cancelAll({reason:"the object it lives on was destroyed or unrendered",cancelRequestKind:CANCEL_KIND_LIFESPAN_END})})}get _isAlive(){return!isDestroying(this.context)}_taskInstanceFactory(e,t,r){let n=this._taskInstanceOptions(e,t,r);return n.task=this,new TaskInstance(n)}_clone(){return new Task({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}}TRACKED_INITIAL_TASK_STATE&&Object.defineProperties(Task.prototype,TRACKED_INITIAL_TASK_STATE),Object.assign(Task.prototype,TASKABLE_MIXIN);class TaskFactory extends TaskFactory$1{env=EMBER_ENVIRONMENT;createTask(e){assert$3("Cannot create task if a task definition is not provided as generator function",this.taskDefinition);let t=this.getTaskOptions(e);return new Task(Object.assign({generatorFactory:t=>this.taskDefinition.apply(e,t)},t))}getModifier(e){return super.getModifier(e)}getScheduler(e,t){return new EmberScheduler(e,t)}get taskFn(){return this.taskDefinition}set taskFn(e){this.setTaskDefinition(e)}}function buildTask(e,t,r){let n=t;const i=e();return new TaskFactory(r||"",i.generator,n).createTask(i.context)}class Blurhash extends GlimmerComponent{renderBlurhash=modifier((e,[t,r,n])=>{if(!t||!e)return;const i=r||32,o=n||18;e.width=i,e.height=o;const s=e.getContext("2d");if(s)try{const e=j(t,i,o),r=s.createImageData(i,o);r.data.set(e),s.putImageData(r,0,0)}catch(a){console.warn("Failed to decode blurhash:",a.message||a)}});static{setComponentTemplate(templateFactory({id:null,block:'[[[11,"canvas"],[24,0,"blurhash-canvas"],[17,1],[4,[30,0,["renderBlurhash"]],[[30,2],[30,3],[30,4]],null],[12],[13]],["&attrs","@hash","@width","@height"],[]]',moduleName:"/home/basti/src/marco/app/components/blurhash.gjs",isStrictMode:!0}),this)}}const MAX_IMAGE_DIMENSION=1920,IMAGE_QUALITY=.9,MAX_THUMBNAIL_DIMENSION=350,THUMBNAIL_QUALITY=.9;class PlacePhotoUploadItem extends GlimmerComponent{static{decorateFieldV2(this.prototype,"blossom",[service])}#Ie=void initializeDeferredDecorator(this,"blossom");static{decorateFieldV2(this.prototype,"imageProcessor",[service])}#Pe=void initializeDeferredDecorator(this,"imageProcessor");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{decorateFieldV2(this.prototype,"thumbnailUrl",[tracked],function(){return""})}#ke=void initializeDeferredDecorator(this,"thumbnailUrl");static{decorateFieldV2(this.prototype,"blurhash",[tracked],function(){return""})}#Oe=void initializeDeferredDecorator(this,"blurhash");static{decorateFieldV2(this.prototype,"error",[tracked],function(){return""})}#Le=void initializeDeferredDecorator(this,"error");static{decorateFieldV2(this.prototype,"statusText",[tracked],function(){return""})}#Me=void initializeDeferredDecorator(this,"statusText");constructor(){super(...arguments),this.args.file&&(this.thumbnailUrl=URL.createObjectURL(this.args.file),this.uploadTask.perform(this.args.file))}willDestroy(){super.willDestroy(...arguments),this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl)}showErrorToast(){this.error&&this.toast.show(this.error)}static{decorateMethodV2(this.prototype,"showErrorToast",[action])}uploadTask=buildTask(()=>({context:this,generator:function*(e){this.error="",this.statusText="Processing";try{const t=yield this.imageProcessor.process(e,MAX_IMAGE_DIMENSION,IMAGE_QUALITY,!0);this.blurhash=t.blurhash;const r=yield this.imageProcessor.process(e,MAX_THUMBNAIL_DIMENSION,THUMBNAIL_QUALITY,!1);let n,i;const o=isMobile(),s=e=>{"signing"===e&&(this.statusText="Signing photo upload"),"uploading"===e&&(this.statusText="Uploading photo")},a=e=>{"signing"===e&&(this.statusText="Signing thumbnail upload"),"uploading"===e&&(this.statusText="Uploading thumbnail")};if(o)n=yield this.blossom.upload(t.blob,{sequential:!0,onProgress:s}),i=yield this.blossom.upload(r.blob,{sequential:!0,onProgress:a});else{const e=this.blossom.upload(t.blob,{onProgress:s}),o=this.blossom.upload(r.blob,{onProgress:a});[n,i]=yield Promise.all([e,o])}this.args.onSuccess&&this.args.onSuccess({file:e,url:n.url,fallbackUrls:n.fallbackUrls,thumbUrl:i.url,blurhash:t.blurhash,type:"image/jpeg",dim:t.dim,hash:n.hash,thumbHash:i.hash})}catch(t){this.error=t.message}}}),null,"uploadTask");static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[15,0,[29,["photo-upload-item\\n ",[52,[30,0,["uploadTask","isRunning"]],"is-uploading"],"\\n ",[52,[30,0,["error"]],"has-error"]]]],[12],[1,"\\n"],[41,[30,0,["blurhash"]],[[[1," "],[8,[32,0],[[24,0,"place-header-photo-blur"]],[["@hash"],[[30,0,["blurhash"]]]],null],[1,"\\n"]],[]],null],[1," "],[10,"img"],[15,"src",[30,0,["thumbnailUrl"]]],[14,"alt","thumbnail"],[12],[13],[1,"\\n\\n"],[41,[30,0,["uploadTask","isRunning"]],[[[1," "],[10,0],[14,0,"overlay"],[12],[1,"\\n "],[8,[32,1],[[24,0,"spin-animation"]],[["@name","@size","@color"],["loading-ring",24,"white"]],null],[1,"\\n"],[41,[30,0,["statusText"]],[[[1," "],[10,1],[14,0,"upload-status-text"],[12],[1,[30,0,["statusText"]]],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["error"]],[[[1," "],[11,"button"],[24,0,"overlay error-overlay"],[16,"title",[30,0,["error"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["showErrorToast"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["alert-circle",24,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[11,"button"],[24,0,"btn-remove-photo"],[24,"title","Remove photo"],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,1],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",16,"white"]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onRemove","@file"],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload-item.gjs",scope:()=>[Blurhash,IconComponent,on,fn],isStrictMode:!0}),this)}}class AndHelper extends Helper{compute(e){for(let t=0,r=e.length;t!truthConvert(e))}class PlacePhotoUpload extends GlimmerComponent{static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrRelay",[service])}#q=void initializeDeferredDecorator(this,"nostrRelay");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"blossom",[service])}#Ie=void initializeDeferredDecorator(this,"blossom");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{decorateFieldV2(this.prototype,"file",[tracked],function(){return null})}#De=void initializeDeferredDecorator(this,"file");static{decorateFieldV2(this.prototype,"uploadedPhoto",[tracked],function(){return null})}#Ne=void initializeDeferredDecorator(this,"uploadedPhoto");static{decorateFieldV2(this.prototype,"error",[tracked],function(){return""})}#Le=void initializeDeferredDecorator(this,"error");static{decorateFieldV2(this.prototype,"isPublishing",[tracked],function(){return!1})}#Fe=void initializeDeferredDecorator(this,"isPublishing");static{decorateFieldV2(this.prototype,"isDragging",[tracked],function(){return!1})}#$e=void initializeDeferredDecorator(this,"isDragging");get place(){return this.args.place||{}}get title(){return this.place.title||"this place"}get allUploaded(){return this.file&&this.uploadedPhoto&&this.file===this.uploadedPhoto.file}handleFileSelect(e){this.addFile(e.target.files[0]),e.target.value=""}static{decorateMethodV2(this.prototype,"handleFileSelect",[action])}handleDragOver(e){e.preventDefault(),this.isDragging=!0}static{decorateMethodV2(this.prototype,"handleDragOver",[action])}handleDragLeave(e){e.preventDefault(),this.isDragging=!1}static{decorateMethodV2(this.prototype,"handleDragLeave",[action])}handleDrop(e){e.preventDefault(),this.isDragging=!1,e.dataTransfer.files.length>0&&this.addFile(e.dataTransfer.files[0])}static{decorateMethodV2(this.prototype,"handleDrop",[action])}addFile(e){e&&e.type.startsWith("image/")?(this.error="",this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=e,this.uploadedPhoto=null,this.args.onUploadStateChange&&this.args.onUploadStateChange(!0)):this.error="Please select a valid image file."}handleUploadSuccess(e){this.uploadedPhoto=e}static{decorateMethodV2(this.prototype,"handleUploadSuccess",[action])}removeFile(){this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=null,this.uploadedPhoto=null,this.args.onUploadStateChange&&this.args.onUploadStateChange(!1)}static{decorateMethodV2(this.prototype,"removeFile",[action])}deletePhotoTask=buildTask(()=>({context:this,generator:function*(e){try{e.hash&&(yield this.blossom.delete(e.hash)),e.thumbHash&&(yield this.blossom.delete(e.thumbHash))}catch(t){this.toast.show(`Failed to delete photo from server: ${t.message}`,5e3)}}}),null,"deletePhotoTask");async publish(){if(!this.nostrAuth.isConnected)return void(this.error="You must connect Nostr first.");if(!this.allUploaded)return void(this.error="Please wait for all photos to finish uploading.");const{osmId:e,lat:t,lon:r}=this.place,n=this.place.osmType||"node";if(e){this.error="",this.isPublishing=!0;try{const i=new EventFactory({signer:this.nostrAuth.signer}),o=[["i",`osm:${n}:${e}`]];t&&r&&(o.push(["g",Geohash.encode(t,r,4)]),o.push(["g",Geohash.encode(t,r,6)]),o.push(["g",Geohash.encode(t,r,7)]),o.push(["g",Geohash.encode(t,r,9)]));const s=this.uploadedPhoto,a=["imeta",`url ${s.url}`];if(a.push(`m ${s.type}`),s.dim&&a.push(`dim ${s.dim}`),a.push("alt A photo of a place"),s.fallbackUrls&&s.fallbackUrls.length>0)for(const e of s.fallbackUrls)a.push(`fallback ${e}`);s.thumbUrl&&a.push(`thumb ${s.thumbUrl}`),s.blurhash&&a.push(`blurhash ${s.blurhash}`),o.push(a);const l={kind:360,content:"",tags:o};l.created_at||(l.created_at=Math.floor(Date.now()/1e3));const c=await i.sign(l);await this.nostrRelay.publish(this.nostrData.activeWriteRelays,c),this.nostrData.store.add(c),this.toast.show("Photo published successfully"),this.file=null,this.uploadedPhoto=null,this.args.onUploadStateChange&&this.args.onUploadStateChange(!1),this.args.onClose&&this.args.onClose(c.id)}catch(i){this.error="Failed to publish: "+i.message}finally{this.isPublishing=!1}}else this.error="This place does not have a valid OSM ID."}static{decorateMethodV2(this.prototype,"publish",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"place-photo-upload"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Add Photo for "],[1,[30,0,["title"]]],[13],[1,"\\n\\n"],[41,[30,0,["error"]],[[[1," "],[10,0],[14,0,"alert alert-error"],[12],[1,"\\n "],[1,[30,0,["error"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["file"]],[[[1," "],[10,0],[14,0,"photo-grid"],[12],[1,"\\n "],[8,[32,0],null,[["@file","@onSuccess","@onRemove"],[[30,0,["file"]],[30,0,["handleUploadSuccess"]],[30,0,["removeFile"]]]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"button"],[24,0,"btn btn-primary btn-publish"],[16,"disabled",[28,[32,1],[[28,[32,2],[[30,0,["allUploaded"]]],null],[30,0,["isPublishing"]]],null]],[24,4,"button"],[4,[32,3],["click",[30,0,["publish"]]],null],[12],[1,"\\n"],[41,[30,0,["isPublishing"]],[[[1," Publishing...\\n"]],[]],[[[1," Publish Photo\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],[[[1," "],[11,0],[16,0,[29,["dropzone ",[52,[30,0,["isDragging"]],"is-dragging"]]]],[4,[32,3],["dragover",[30,0,["handleDragOver"]]],null],[4,[32,3],["dragleave",[30,0,["handleDragLeave"]]],null],[4,[32,3],["drop",[30,0,["handleDrop"]]],null],[12],[1,"\\n "],[10,"label"],[14,"for","photo-upload-input"],[14,0,"dropzone-label"],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size","@color"],["upload-cloud",48,"#ccc"]],null],[1,"\\n "],[10,2],[12],[1,"Drag and drop a photo here, or click to browse"],[13],[1,"\\n "],[13],[1,"\\n "],[11,"input"],[24,1,"photo-upload-input"],[24,"accept","image/*"],[24,0,"file-input-hidden"],[16,"disabled",[30,0,["isPublishing"]]],[24,4,"file"],[4,[32,3],["change",[30,0,["handleFileSelect"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload.gjs",scope:()=>[PlacePhotoUploadItem,OrHelper,not,on,IconComponent],isStrictMode:!0}),this)}}var browser={},canPromise,hasRequiredCanPromise;function requireCanPromise(){return hasRequiredCanPromise?canPromise:(hasRequiredCanPromise=1,canPromise=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then})}var qrcode={},utils$1={},hasRequiredUtils$1;function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;let e;hasRequiredUtils$1=1;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return utils$1.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return 4*e+17},utils$1.getSymbolTotalCodewords=function(e){return t[e]},utils$1.getBCHDigit=function(e){let t=0;for(;0!==e;)t++,e>>>=1;return t},utils$1.setToSJISFunction=function(t){if("function"!=typeof t)throw new Error('"toSJISFunc" is not a valid function.');e=t},utils$1.isKanjiModeEnabled=function(){return void 0!==e},utils$1.toSJIS=function(t){return e(t)},utils$1}var errorCorrectionLevel={},hasRequiredErrorCorrectionLevel,bitBuffer,hasRequiredBitBuffer,bitMatrix,hasRequiredBitMatrix;function requireErrorCorrectionLevel(){return hasRequiredErrorCorrectionLevel||(hasRequiredErrorCorrectionLevel=1,(e=errorCorrectionLevel).L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2},e.isValid=function(e){return e&&void 0!==e.bit&&e.bit>=0&&e.bit<4},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+t)}}(t)}catch(n){return r}}),errorCorrectionLevel;var e}function requireBitBuffer(){if(hasRequiredBitBuffer)return bitBuffer;function e(){this.buffer=[],this.length=0}return hasRequiredBitBuffer=1,e.prototype={get:function(e){const t=Math.floor(e/8);return 1==(this.buffer[t]>>>7-e%8&1)},put:function(e,t){for(let r=0;r>>t-r-1&1))},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},bitBuffer=e}function requireBitMatrix(){if(hasRequiredBitMatrix)return bitMatrix;function e(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return hasRequiredBitMatrix=1,e.prototype.set=function(e,t,r,n){const i=e*this.size+t;this.data[i]=r,n&&(this.reservedBit[i]=!0)},e.prototype.get=function(e,t){return this.data[e*this.size+t]},e.prototype.xor=function(e,t,r){this.data[e*this.size+t]^=r},e.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]},bitMatrix=e}var alignmentPattern={},hasRequiredAlignmentPattern;function requireAlignmentPattern(){return hasRequiredAlignmentPattern||(hasRequiredAlignmentPattern=1,function(e){const t=requireUtils$1().getSymbolSize;e.getRowColCoords=function(e){if(1===e)return[];const r=Math.floor(e/7)+2,n=t(e),i=145===n?26:2*Math.ceil((n-13)/(2*r-2)),o=[n-7];for(let t=1;t=0&&e<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(e){const t=e.size;let r=0,n=0,i=0,o=null,s=null;for(let a=0;a=5&&(r+=n-5+3),o=t,n=1),t=e.get(l,a),t===s?i++:(i>=5&&(r+=i-5+3),s=t,i=1)}n>=5&&(r+=n-5+3),i>=5&&(r+=i-5+3)}return r},e.getPenaltyN2=function(e){const t=e.size;let r=0;for(let n=0;n=10&&(1488===n||93===n)&&r++,i=i<<1&2047|e.get(s,o),s>=10&&(1488===i||93===i)&&r++}return 40*r},e.getPenaltyN4=function(e){let t=0;const r=e.data.length;for(let n=0;n=0;){const e=n[0];for(let o=0;o0){const e=new Uint8Array(this.degree);return e.set(n,i),e}return n},reedSolomonEncoder=t}var version={},mode={},versionCheck={},hasRequiredVersionCheck;function requireVersionCheck(){return hasRequiredVersionCheck||(hasRequiredVersionCheck=1,versionCheck.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),versionCheck}var regex={},hasRequiredRegex,hasRequiredMode,hasRequiredVersion;function requireRegex(){if(hasRequiredRegex)return regex;hasRequiredRegex=1;const e="[0-9]+";let t="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";t=t.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+t+")(?:.|[\r\n]))+";regex.KANJI=new RegExp(t,"g"),regex.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),regex.BYTE=new RegExp(r,"g"),regex.NUMERIC=new RegExp(e,"g"),regex.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");const n=new RegExp("^"+t+"$"),i=new RegExp("^"+e+"$"),o=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return regex.testKanji=function(e){return n.test(e)},regex.testNumeric=function(e){return i.test(e)},regex.testAlphanumeric=function(e){return o.test(e)},regex}function requireMode(){return hasRequiredMode||(hasRequiredMode=1,function(e){const t=requireVersionCheck(),r=requireRegex();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!t.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]},e.getBestModeForData=function(t){return r.testNumeric(t)?e.NUMERIC:r.testAlphanumeric(t)?e.ALPHANUMERIC:r.testKanji(t)?e.KANJI:e.BYTE},e.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")},e.isValid=function(e){return e&&e.bit&&e.ccBits},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+t)}}(t)}catch(n){return r}}}(mode)),mode}function requireVersion(){return hasRequiredVersion||(hasRequiredVersion=1,function(e){const t=requireUtils$1(),r=requireErrorCorrectionCode(),n=requireErrorCorrectionLevel(),i=requireMode(),o=requireVersionCheck(),s=t.getBCHDigit(7973);function a(e,t){return i.getCharCountIndicator(e,t)+4}function l(e,t){let r=0;return e.forEach(function(e){const n=a(e.mode,t);r+=n+e.getBitsLength()}),r}e.from=function(e,t){return o.isValid(e)?parseInt(e,10):t},e.getCapacity=function(e,n,s){if(!o.isValid(e))throw new Error("Invalid QR Code version");void 0===s&&(s=i.BYTE);const l=8*(t.getSymbolTotalCodewords(e)-r.getTotalCodewordsCount(e,n));if(s===i.MIXED)return l;const c=l-a(s,e);switch(s){case i.NUMERIC:return Math.floor(c/10*3);case i.ALPHANUMERIC:return Math.floor(c/11*2);case i.KANJI:return Math.floor(c/13);case i.BYTE:default:return Math.floor(c/8)}},e.getBestVersionForData=function(t,r){let o;const s=n.from(r,n.M);if(Array.isArray(t)){if(t.length>1)return function(t,r){for(let n=1;n<=40;n++)if(l(t,n)<=e.getCapacity(n,r,i.MIXED))return n}(t,s);if(0===t.length)return 1;o=t[0]}else o=t;return function(t,r,n){for(let i=1;i<=40;i++)if(r<=e.getCapacity(i,n,t))return i}(o.mode,o.getLength(),s)},e.getEncodedBits=function(e){if(!o.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;t.getBCHDigit(r)-s>=0;)r^=7973<=0;)o^=1335<0&&(r=this.data.substr(t),n=parseInt(r,10),e.put(n,3*i+1))},numericData=t}function requireAlphanumericData(){if(hasRequiredAlphanumericData)return alphanumericData;hasRequiredAlphanumericData=1;const e=requireMode(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(t){this.mode=e.ALPHANUMERIC,this.data=t}return r.getBitsLength=function(e){return 11*Math.floor(e/2)+e%2*6},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=45*t.indexOf(this.data[r]);n+=t.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(t.indexOf(this.data[r]),6)},alphanumericData=r}function requireByteData(){if(hasRequiredByteData)return byteData;hasRequiredByteData=1;const e=requireMode();function t(t){this.mode=e.BYTE,this.data="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}return t.getBitsLength=function(e){return 8*e},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(e){for(let t=0,r=this.data.length;t=33088&&n<=40956)n-=33088;else{if(!(n>=57408&&n<=60351))throw new Error("Invalid SJIS character: "+this.data[r]+"\nMake sure your charset is UTF-8");n-=49472}n=192*(n>>>8&255)+(255&n),e.put(n,13)}},kanjiData=r}var dijkstra={exports:{}},hasRequiredDijkstra,hasRequiredSegments,hasRequiredQrcode;function requireDijkstra(){return hasRequiredDijkstra||(hasRequiredDijkstra=1,function(e){var t={single_source_shortest_paths:function(e,r,n){var i={},o={};o[r]=0;var s,a,l,c,u,h,d,p=t.PriorityQueue.make();for(p.push(r,0);!p.empty();)for(l in a=(s=p.pop()).value,c=s.cost,u=e[a]||{})u.hasOwnProperty(l)&&(h=c+u[l],d=o[l],(void 0===o[l]||d>h)&&(o[l]=h,p.push(l,h),i[l]=a));if(void 0!==n&&void 0===o[n]){var f=["Could not find a path from ",r," to ",n,"."].join("");throw new Error(f)}return i},extract_shortest_path_from_predecessor_list:function(e,t){for(var r=[],n=t;n;)r.push(n),e[n],n=e[n];return r.reverse(),r},find_path:function(e,r,n){var i=t.single_source_shortest_paths(e,r,n);return t.extract_shortest_path_from_predecessor_list(i,n)},PriorityQueue:{make:function(e){var r,n=t.PriorityQueue,i={};for(r in e=e||{},n)n.hasOwnProperty(r)&&(i[r]=n[r]);return i.queue=[],i.sorter=e.sorter||n.default_sorter,i},default_sorter:function(e,t){return e.cost-t.cost},push:function(e,t){var r={value:e,cost:t};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};e.exports=t}(dijkstra)),dijkstra.exports}function requireSegments(){return hasRequiredSegments||(hasRequiredSegments=1,function(e){const t=requireMode(),r=requireNumericData(),n=requireAlphanumericData(),i=requireByteData(),o=requireKanjiData(),s=requireRegex(),a=requireUtils$1(),l=requireDijkstra();function c(e){return unescape(encodeURIComponent(e)).length}function u(e,t,r){const n=[];let i;for(;null!==(i=e.exec(r));)n.push({data:i[0],index:i.index,mode:t,length:i[0].length});return n}function h(e){const r=u(s.NUMERIC,t.NUMERIC,e),n=u(s.ALPHANUMERIC,t.ALPHANUMERIC,e);let i,o;return a.isKanjiModeEnabled()?(i=u(s.BYTE,t.BYTE,e),o=u(s.KANJI,t.KANJI,e)):(i=u(s.BYTE_KANJI,t.BYTE,e),o=[]),r.concat(n,i,o).sort(function(e,t){return e.index-t.index}).map(function(e){return{data:e.data,mode:e.mode,length:e.length}})}function d(e,s){switch(s){case t.NUMERIC:return r.getBitsLength(e);case t.ALPHANUMERIC:return n.getBitsLength(e);case t.KANJI:return o.getBitsLength(e);case t.BYTE:return i.getBitsLength(e)}}function p(e,s){let l;const c=t.getBestModeForData(e);if(l=t.from(s,c),l!==t.BYTE&&l.bit=0?e[e.length-1]:null;return r&&r.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[]))},e.rawSplit=function(t){return e.fromArray(h(t,a.isKanjiModeEnabled()))}}(segments)),segments}function requireQrcode(){if(hasRequiredQrcode)return qrcode;hasRequiredQrcode=1;const e=requireUtils$1(),t=requireErrorCorrectionLevel(),r=requireBitBuffer(),n=requireBitMatrix(),i=requireAlignmentPattern(),o=requireFinderPattern(),s=requireMaskPattern(),a=requireErrorCorrectionCode(),l=requireReedSolomonEncoder(),c=requireVersion(),u=requireFormatInfo(),h=requireMode(),d=requireSegments();function p(e,t,r){const n=e.size,i=u.getEncodedBits(t,r);let o,s;for(o=0;o<15;o++)s=1==(i>>o&1),o<6?e.set(o,8,s,!0):o<8?e.set(o+1,8,s,!0):e.set(n-15+o,8,s,!0),o<8?e.set(8,n-o-1,s,!0):o<9?e.set(8,15-o-1+1,s,!0):e.set(8,15-o-1,s,!0);e.set(n-8,8,1,!0)}return qrcode.create=function(u,f){if(void 0===u||""===u)throw new Error("No input text");let g,m,y=t.M;return void 0!==f&&(y=t.from(f.errorCorrectionLevel,t.M),g=c.from(f.version),m=s.from(f.maskPattern),f.toSJISFunc&&e.setToSJISFunction(f.toSJISFunc)),function(t,u,f,g){let m;if(Array.isArray(t))m=d.fromArray(t);else{if("string"!=typeof t)throw new Error("Invalid data");{let e=u;if(!e){const r=d.rawSplit(t);e=c.getBestVersionForData(r,f)}m=d.fromString(t,e||40)}}const y=c.getBestVersionForData(m,f);if(!y)throw new Error("The amount of data is too big to be stored in a QR Code");if(u){if(u=0&&n<=6&&(0===i||6===i)||i>=0&&i<=6&&(0===n||6===n)||n>=2&&n<=4&&i>=2&&i<=4?e.set(t+n,o+i,!0,!0):e.set(t+n,o+i,!1,!0))}}(_,u),function(e){const t=e.size;for(let r=8;r=7&&function(e,t){const r=e.size,n=c.getEncodedBits(t);let i,o,s;for(let a=0;a<18;a++)i=Math.floor(a/3),o=a%3+r-8-3,s=1==(n>>a&1),e.set(i,o,s,!0),e.set(o,i,s,!0)}(_,u),function(e,t){const r=e.size;let n=-1,i=r-1,o=7,s=0;for(let a=r-1;a>0;a-=2)for(6===a&&a--;;){for(let r=0;r<2;r++)if(!e.isReserved(i,a-r)){let n=!1;s>>o&1)),e.set(i,a-r,n),o--,-1===o&&(s++,o=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}(_,b),isNaN(g)&&(g=s.getBestMask(_,p.bind(null,_,f))),s.applyMask(g,_),p(_,f,g),{modules:_,version:u,errorCorrectionLevel:f,maskPattern:g,segments:m}}(u,g,y,m)},qrcode}var canvas={},utils={},hasRequiredUtils,hasRequiredCanvas;function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(e){function t(e){if("number"==typeof e&&(e=e.toString()),"string"!=typeof e)throw new Error("Color should be defined as hex string");let t=e.slice().replace("#","").split("");if(t.length<3||5===t.length||t.length>8)throw new Error("Invalid hex color: "+e);3!==t.length&&4!==t.length||(t=Array.prototype.concat.apply([],t.map(function(e){return[e,e]}))),6===t.length&&t.push("F","F");const r=parseInt(t.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:255&r,hex:"#"+t.slice(0,6).join("")}}e.getOptions=function(e){e||(e={}),e.color||(e.color={});const r=void 0===e.margin||null===e.margin||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:t(e.color.dark||"#000000ff"),light:t(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}},e.getScale=function(e,t){return t.width&&t.width>=e+2*t.margin?t.width/(e+2*t.margin):t.scale},e.getImageWidth=function(t,r){const n=e.getScale(t,r);return Math.floor((t+2*r.margin)*n)},e.qrToImageData=function(t,r,n){const i=r.modules.size,o=r.modules.data,s=e.getScale(i,n),a=Math.floor((i+2*n.margin)*s),l=n.margin*s,c=[n.color.light,n.color.dark];for(let e=0;e=l&&r>=l&&e':"",h="0&&c>0&&e[l-1]||(i+=s?r("M",c+n,.5+u+n):r("m",o,0),o=0,s=!1),c+1',d='viewBox="0 0 '+c+" "+c+'"',p=''+u+h+"\n";return"function"==typeof o&&o(null,p),p},svgTag}function requireBrowser(){if(hasRequiredBrowser)return browser;hasRequiredBrowser=1;const e=requireCanPromise(),t=requireQrcode(),r=requireCanvas(),n=requireSvgTag();function i(r,n,i,o,s){const a=[].slice.call(arguments,1),l=a.length,c="function"==typeof a[l-1];if(!c&&!e())throw new Error("Callback required as last argument");if(!c){if(l<1)throw new Error("Too few arguments provided");return 1===l?(i=n,n=o=void 0):2!==l||n.getContext||(o=i,i=n,n=void 0),new Promise(function(e,s){try{const s=t.create(i,o);e(r(s,n,o))}catch(a){s(a)}})}if(l<2)throw new Error("Too few arguments provided");2===l?(s=i,i=n,n=o=void 0):3===l&&(n.getContext&&void 0===s?(s=o,o=void 0):(s=o,o=i,i=n,n=void 0));try{const e=t.create(i,o);s(null,r(e,n,o))}catch(u){s(u)}}return browser.create=t.create,browser.toCanvas=i.bind(null,r.render),browser.toDataURL=i.bind(null,r.renderToDataURL),browser.toString=i.bind(null,function(e,t,r){return n.render(e,r)}),browser}var browserExports=requireBrowser();const QRCode=getDefaultExportFromCjs$1(browserExports),qrCode=modifier((e,[t])=>{t&&QRCode.toCanvas(e,t,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).catch(e=>{console.error("Failed to generate QR code",e)})});class NostrConnectComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");get hasExtension(){return"undefined"!=typeof window&&void 0!==window.nostr}async connectExtension(){try{await this.nostrAuth.connectWithExtension(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(e){console.error(e),alert(e.message)}}static{decorateMethodV2(this.prototype,"connectExtension",[action])}async connectApp(){try{await this.nostrAuth.connectWithApp(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(e){console.error(e),alert(e.message)}}static{decorateMethodV2(this.prototype,"connectApp",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"nostr-connect-modal"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Connect with Nostr"],[13],[1,"\\n\\n "],[10,0],[14,0,"nostr-connect-options"],[12],[1,"\\n"],[41,[30,0,["hasExtension"]],[[[1," "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectExtension"]]],null],[12],[1,"\\n Browser Extension (nos2x, Alby)\\n "],[13],[1,"\\n"]],[]],[[[1," "],[10,"button"],[14,0,"btn btn-outline"],[14,"disabled",""],[14,"title","No Nostr extension found in your browser."],[14,4,"button"],[12],[1,"\\n Browser Extension (Not Found)\\n "],[13],[1,"\\n"]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectApp"]]],null],[12],[1,"\\n Mobile Signer App (Amber, etc.)\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[28,[32,1],[[30,0,["nostrAuth","connectStatus"]],"waiting"],null],[[[1," "],[10,0],[14,0,"nostr-connect-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isMobile"]],[[[1," "],[10,2],[12],[1,"Waiting for you to approve the connection in your mobile signer\\n app..."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[12],[1,"Scan this QR code with a compatible Nostr signer app (like\\n Amber):"],[13],[1,"\\n "],[10,0],[14,0,"qr-code-container"],[12],[1,"\\n "],[11,"canvas"],[4,[32,2],[[30,0,["nostrAuth","connectUri"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],null],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/nostr-connect.gjs",scope:()=>[on,eq$1,qrCode],isStrictMode:!0}),this)}}class Modal extends GlimmerComponent{stopProp(e){e.stopPropagation()}static{decorateMethodV2(this.prototype,"stopProp",[action])}close(){this.args.disableClose||this.args.onClose&&this.args.onClose()}static{decorateMethodV2(this.prototype,"close",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[24,0,"modal-overlay"],[24,"role","dialog"],[24,"tabindex","-1"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[11,0],[24,0,"modal-content"],[24,"role","document"],[24,"tabindex","0"],[4,[32,0],["click",[30,0,["stopProp"]]],null],[12],[1,"\\n "],[11,"button"],[16,0,[29,["close-modal-btn btn-text ",[52,[30,1],"disabled"]]]],[16,"disabled",[30,1]],[24,4,"button"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",24,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[18,2,null],[1,"\\n "],[13],[1,"\\n"],[13]],["@disableClose","&default"],["if","yield"]]',moduleName:"/home/basti/src/marco/app/components/modal.gjs",scope:()=>[on,IconComponent],isStrictMode:!0}),this)}}const fadeInImage=modifier((e,[t])=>{if(!t)return;let r;e.classList.remove("loaded"),e.classList.remove("loaded-instant");const n=()=>{const t=e.parentElement,r=t&&"PICTURE"===t.tagName?t.parentElement:t;if(r&&r.closest(".photo-carousel.gallery-main")){const e=r.querySelector(".place-header-photo-blur");e&&(e.style.opacity="0")}},i=()=>{e.classList.contains("loaded-instant")||e.classList.add("loaded"),n()};return e.addEventListener("load",i),r=new IntersectionObserver((r,i)=>{r.forEach(r=>{if(r.isIntersecting){i.unobserve(e);const r=new Image;r.src=t,r.complete&&(e.classList.add("loaded-instant"),n());const o=e.parentElement;o&&"PICTURE"===o.tagName&&o.querySelectorAll("source").forEach(e=>{e.dataset.srcset&&(e.srcset=e.dataset.srcset)}),e.dataset.src?e.src=e.dataset.src:e.src=t}})},{root:null,rootMargin:"100px 100%",threshold:0}),r.observe(e),()=>{e.removeEventListener("load",i),r&&r.disconnect()}});class PhotoCarousel extends GlimmerComponent{static{decorateFieldV2(this.prototype,"canScrollLeft",[tracked],function(){return!1})}#Be=void initializeDeferredDecorator(this,"canScrollLeft");static{decorateFieldV2(this.prototype,"canScrollRight",[tracked],function(){return!1})}#Ue=void initializeDeferredDecorator(this,"canScrollRight");internalEventId=null;carouselElement=null;get photos(){return this.args.photos||[]}get showChevrons(){return this.photos.length>1}get cannotScrollLeft(){return!this.canScrollLeft}get cannotScrollRight(){return!this.canScrollRight}get variantClass(){return this.args.variant||"inline"}lastResetKey=null;resetScrollPosition=modifier((e,[t])=>{void 0!==t&&t!==this.lastResetKey&&(this.lastResetKey=t,e.scrollLeft=0,setTimeout(()=>this.updateScrollState(),50))});scrollToNewPhoto=modifier((e,[t])=>{if(t&&t!==this.lastEventId){const r=!this.lastEventId;if(this.lastEventId=t,this.internalEventId===t)return;const n=()=>{const n=e.querySelector(`[data-event-id="${t}"]`);if(n)if(r){const t=e.style.scrollBehavior;e.style.scrollBehavior="auto",e.scrollLeft=n.offsetLeft,setTimeout(()=>{e.style.scrollBehavior=t},50)}else e.scrollLeft=n.offsetLeft};r?n():setTimeout(n,100)}});setupCarousel=modifier(e=>{let t,r;return this.carouselElement=e,setTimeout(()=>{this.updateScrollState()},50),window.ResizeObserver&&(t=new ResizeObserver(()=>this.updateScrollState()),t.observe(e)),this.args.onVisiblePhotoChange&&window.IntersectionObserver&&(r=new IntersectionObserver(e=>{for(let t of e)if(t.isIntersecting&&t.intersectionRatio>=.5){const e=t.target.dataset.eventId;this.internalEventId=e;const r=this.photos.find(t=>t.eventId===e);r&&this.args.onVisiblePhotoChange(r)}},{root:e,threshold:.5}),e.querySelectorAll(".carousel-slide").forEach(e=>r.observe(e))),()=>{t&&t.unobserve(e),r&&r.disconnect()}});updateScrollState(){if(!this.carouselElement)return;const{scrollLeft:e,scrollWidth:t,clientWidth:r}=this.carouselElement;this.canScrollLeft=e>1,this.canScrollRight=e+r[on,AndHelper,eq$1,fn,Blurhash,fadeInImage,IconComponent],isStrictMode:!0}),this)}}class PhotoGallery extends GlimmerComponent{static{decorateFieldV2(this.prototype,"currentPhoto",[tracked],function(){return this.args.selectedPhoto||this.args.photos?.[0]})}#ze=void initializeDeferredDecorator(this,"currentPhoto");handleClose(){this.args.onClose&&this.args.onClose()}static{decorateMethodV2(this.prototype,"handleClose",[action])}handleBackgroundClick(e){e.target.closest(".thumbnail-strip-container")||e.target.closest(".carousel-nav-btn")||e.target.closest(".close-btn")||this.handleClose()}static{decorateMethodV2(this.prototype,"handleBackgroundClick",[action])}selectPhoto(e){this.currentPhoto=e}static{decorateMethodV2(this.prototype,"selectPhoto",[action])}handleVisiblePhotoChange(e){this.currentPhoto!==e&&(this.currentPhoto=e)}static{decorateMethodV2(this.prototype,"handleVisiblePhotoChange",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[24,0,"photo-gallery-overlay"],[24,"role","dialog"],[24,"tabindex","-1"],[4,[32,0],["click",[30,0,["handleBackgroundClick"]]],null],[12],[1,"\\n"],[1," "],[10,0],[14,0,"photo-gallery-content"],[12],[1,"\\n "],[11,"button"],[24,0,"close-btn btn-text"],[24,"aria-label","Close gallery"],[24,"title","Close"],[24,4,"button"],[4,[32,0],["click",[30,0,["handleClose"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",24,"white"]],null],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"main-photo-container"],[12],[1,"\\n "],[8,[32,2],null,[["@variant","@photos","@scrollToEventId","@onVisiblePhotoChange","@name"],["gallery-main",[30,1],[30,0,["currentPhoto","eventId"]],[30,0,["handleVisiblePhotoChange"]],[30,2]]],null],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"thumbnail-strip-container"],[12],[1,"\\n "],[8,[32,2],null,[["@variant","@photos","@scrollToEventId","@onPhotoClick","@name"],["gallery-thumbnails",[30,1],[30,0,["currentPhoto","eventId"]],[30,0,["selectPhoto"]],[30,2]]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@photos","@placeName"],[]]',moduleName:"/home/basti/src/marco/app/components/photo-gallery.gjs",scope:()=>[on,IconComponent,PhotoCarousel],isStrictMode:!0}),this)}}class PlaceDetails extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"isEditing",[tracked],function(){return!1})}#je=void initializeDeferredDecorator(this,"isEditing");static{decorateFieldV2(this.prototype,"showLists",[tracked],function(){return!1})}#Ve=void initializeDeferredDecorator(this,"showLists");static{decorateFieldV2(this.prototype,"isPhotoUploadActive",[tracked],function(){return!1})}#Ge=void initializeDeferredDecorator(this,"isPhotoUploadActive");static{decorateFieldV2(this.prototype,"isConnectingNostr",[tracked],function(){return!1})}#He=void initializeDeferredDecorator(this,"isConnectingNostr");static{decorateFieldV2(this.prototype,"isGalleryOpen",[tracked],function(){return!1})}#qe=void initializeDeferredDecorator(this,"isGalleryOpen");static{decorateFieldV2(this.prototype,"selectedGalleryPhoto",[tracked],function(){return null})}#We=void initializeDeferredDecorator(this,"selectedGalleryPhoto");openPhotoUploadModal(e){e&&e.preventDefault(),this.nostrAuth.isConnected?this.isPhotoUploadModalOpen=!0:this.isNostrConnectModalOpen=!0}static{decorateMethodV2(this.prototype,"openPhotoUploadModal",[action])}closePhotoUploadModal(e){this.isPhotoUploadActive||(this.isPhotoUploadModalOpen=!1,"string"==typeof e&&(this.newlyUploadedPhotoId=e,setTimeout(()=>{const e=document.querySelector(".sidebar-content");e&&(e.scrollTop=0)},50)))}static{decorateMethodV2(this.prototype,"closePhotoUploadModal",[action])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{decorateMethodV2(this.prototype,"closeNostrConnectModal",[action])}onNostrConnected(){this.isNostrConnectModalOpen=!1,this.isPhotoUploadModalOpen=!0}static{decorateMethodV2(this.prototype,"onNostrConnected",[action])}get isSaved(){return this.storage.isPlaceSaved(this.place.id||this.place.osmId)}get place(){return this.args.place||{}}get saveablePlace(){return this.place.createdAt?this.place:mapToStorageSchema(this.place)}get tags(){return this.place.osmTags||{}}get name(){return this.place.title||getLocalizedName(this.tags)||"Unnamed Place"}get photos(){return parsePlacePhotos(this.nostrData.placePhotos).map(e=>({...e,style:htmlSafe(`--slide-ratio: ${e.aspectRatio};`)}))}startEditing(){this.isSaved&&(this.isEditing=!0)}static{decorateMethodV2(this.prototype,"startEditing",[action])}cancelEditing(){this.isEditing=!1}static{decorateMethodV2(this.prototype,"cancelEditing",[action])}toggleLists(e){e&&e.stopPropagation(),this.showLists=!this.showLists}static{decorateMethodV2(this.prototype,"toggleLists",[action])}closeLists(){this.showLists=!1}static{decorateMethodV2(this.prototype,"closeLists",[action])}async saveChanges(e){this.args.onSave&&await this.args.onSave({...this.place,...e}),this.isEditing=!1}static{decorateMethodV2(this.prototype,"saveChanges",[action])}get type(){return getPlaceType(this.tags)}get address(){const e=this.tags,t=[],r=(...t)=>{for(const r of t)if(e[r])return e[r];return null};let n=r("addr:street","street");const i=r("addr:housenumber","housenumber");n&&(i&&(n=`${n} ${i}`),t.push(n));let o=r("addr:city","city");const s=r("addr:postcode","postcode");o&&(s&&(o=`${s} ${o}`),t.push(o));const a=r("addr:state","state"),l=r("addr:country","country");return a&&a!==o&&t.push(a),l&&t.push(l),0===t.length?null:t.join(", ")}formatMultiLine(e,t){if(!e)return null;const r=[...new Set(e.split(";").map(e=>e.trim()).filter(Boolean))];return 0===r.length?null:htmlSafe("phone"===t?r.map(e=>`${e}`).join("
"):"email"===t?r.map(e=>`${e}`).join("
"):"whatsapp"===t?r.map(e=>`${e}`).join("
"):"url"===t?r.map(e=>`${this.getDomain(e)}`).join("
"):r.join("
"))}get phone(){const e=[this.tags.phone,this.tags["contact:phone"],this.tags.mobile,this.tags["contact:mobile"]].filter(Boolean);return 0===e.length?null:this.formatMultiLine(e.join(";"),"phone")}get whatsapp(){const e=[this.tags.whatsapp,this.tags["contact:whatsapp"]].filter(Boolean);return 0===e.length?null:this.formatMultiLine(e.join(";"),"whatsapp")}get email(){const e=this.tags.email||this.tags["contact:email"];return this.formatMultiLine(e,"email")}get website(){const e=this.place.url||this.tags.website||this.tags["contact:website"];return this.formatMultiLine(e,"url")}getDomain(e){try{return new URL(e).hostname}catch{return e}}get openingHours(){const e=this.tags.opening_hours;return this.formatMultiLine(e)}get cuisine(){return this.tags.cuisine?this.tags.cuisine.split(";").map(e=>humanizeOsmTag$1(e)).join(", "):null}get facebook(){return getSocialInfo(this.tags,"facebook")}get instagram(){return getSocialInfo(this.tags,"instagram")}get wikipedia(){const e=this.tags.wikipedia;return e?e.split(";").map(e=>e.trim()).filter(Boolean)[0]:null}get geoLink(){const e=this.place.lat,t=this.place.lon;return e&&t?`geo:${e},${t}?q=${e},${t}(${encodeURIComponent(this.name)})`:"#"}get visibleGeoLink(){const e=this.place.lat,t=this.place.lon;return e&&t?`${Number(e).toFixed(6)}, ${Number(t).toFixed(6)}`:""}get osmUrl(){const e=this.place.osmId;return e?`https://www.openstreetmap.org/${this.place.osmType||"node"}/${e}`:null}get gmapsUrl(){return this.place.gmapsId||this.place.osmId?`https://www.google.com/maps/search/?api=1&query=${this.name}&query=${this.place.lat},${this.place.lon}`:null}get showDescription(){return"photon"!==this.place.source&&!!this.place.description}openGallery(e){this.selectedGalleryPhoto=e,this.isGalleryOpen=!0}static{decorateMethodV2(this.prototype,"openGallery",[action])}closeGallery(){this.isGalleryOpen=!1,this.selectedGalleryPhoto=null}static{decorateMethodV2(this.prototype,"closeGallery",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"place-details"],[12],[1,"\\n"],[41,[30,0,["isEditing"]],[[[1," "],[8,[32,0],null,[["@place","@onSave","@onCancel"],[[30,0,["place"]],[30,0,["saveChanges"]],[30,0,["cancelEditing"]]]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@variant","@photos","@name","@resetKey","@scrollToEventId","@onPhotoClick"],["inline",[30,0,["photos"]],[30,0,["name"]],[30,0,["place","osmId"]],[30,0,["newlyUploadedPhotoId"]],[30,0,["openGallery"]]]],null],[1,"\\n "],[10,"h3"],[12],[1,[30,0,["name"]]],[13],[1,"\\n "],[10,2],[14,0,"place-type"],[12],[1,"\\n "],[1,[30,0,["type"]]],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["showDescription"]],[[[1," "],[10,2],[14,0,"place-description"],[12],[1,"\\n "],[1,[30,0,["place","description"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[]]],[1,"\\n "],[10,0],[14,0,"actions"],[12],[1,"\\n "],[10,0],[14,0,"save-button-wrapper"],[12],[1,"\\n "],[11,"button"],[16,0,[52,[30,0,["isSaved"]],"btn btn-secondary","btn btn-outline"]],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleLists"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["bookmark",[52,[30,0,["isSaved"]],"currentColor","var(--link-color)"]]],null],[1,"\\n "],[1,[52,[30,0,["isSaved"]],"Saved","Save"]],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["showLists"]],[[[1," "],[8,[32,4],null,[["@place","@onClose","@isSaved"],[[30,0,["saveablePlace"]],[30,0,["closeLists"]],[30,0,["isSaved"]]]],null],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isSaved"]],[[[1," "],[11,"button"],[24,0,"btn btn-outline"],[24,"title","Edit"],[16,"disabled",[30,0,["isEditing"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["startEditing"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["edit","var(--link-color)"]],null],[1,"\\n Edit\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["cuisine"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["fork-and-knife","Cuisine"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["cuisine"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["openingHours"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["clock","Opening hours"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["openingHours"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["phone"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["phone","Phone"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["phone"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["whatsapp"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["whatsapp","WhatsApp"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["whatsapp"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["website"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["globe","Website"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["website"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["email"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["mail","Email"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["email"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["facebook"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["facebook","Facebook"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["facebook","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["facebook","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["instagram"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["instagram","Instagram"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["instagram","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["instagram","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["wikipedia"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["wikipedia","Wikipedia"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[29,["https://wikipedia.org/wiki/",[30,0,["wikipedia"]]]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Wikipedia\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["address"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["home","Address"]],null],[1,"\\n "],[10,1],[12],[1,[30,0,["address"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["map-pin","Geo link"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["geoLink"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["visibleGeoLink"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["osmUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n OpenStreetMap\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["gmapsUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["gmapsUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Google Maps\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,0],[14,0,"meta-info"],[12],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["feather-camera"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[11,"button"],[24,0,"btn-link"],[24,4,"button"],[4,[32,2],["click",[30,0,["openPhotoUploadModal"]]],null],[12],[1,"\\n Add a photo\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13],[1,"\\n\\n"],[41,[30,0,["isPhotoUploadModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose","@disableClose"],[[30,0,["closePhotoUploadModal"]],[30,0,["isPhotoUploadActive"]]]],[["default"],[[[[1,"\\n "],[8,[32,6],null,[["@place","@onClose","@onUploadStateChange"],[[30,0,["saveablePlace"]],[30,0,["closePhotoUploadModal"]],[30,0,["handleUploadStateChange"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,7],null,[["@onConnect"],[[30,0,["onNostrConnected"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["isGalleryOpen"]],[[[1," "],[8,[32,8],null,[["@photos","@selectedPhoto","@placeName","@onClose"],[[30,0,["photos"]],[30,0,["selectedGalleryPhoto"]],[30,0,["name"]],[30,0,["closeGallery"]]]],null],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-details.gjs",scope:()=>[PlaceEditForm,PhotoCarousel,on,IconComponent,PlaceListsManager,Modal,PlacePhotoUpload,NostrConnectComponent,PhotoGallery],isStrictMode:!0}),this)}}const humanizeOsmTag=helper$1(function([e]){return humanizeOsmTag$1(e)});class PlacesSidebar extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");createNewPlace(){const e=this.router.currentRoute.queryParams,t=e.lat,r=e.lon;t&&r?this.router.transitionTo("place.new",{queryParams:{lat:t,lon:r}}):this.router.transitionTo("place.new",{queryParams:{lat:0,lon:0}})}static{decorateMethodV2(this.prototype,"createNewPlace",[action])}selectPlace(e){this.args.onSelect&&this.args.onSelect(e)}static{decorateMethodV2(this.prototype,"selectPlace",[action])}clearSelection(){this.args.onSelect&&this.args.onSelect(null)}static{decorateMethodV2(this.prototype,"clearSelection",[action])}async toggleSave(e){if(e)if(e.createdAt)try{if(await this.storage.removePlace(e),console.debug("Place deleted:",e.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate){const t={...e,id:void 0,geohash:void 0,createdAt:void 0};this.args.onUpdate(t)}this.args.onSelect&&this.args.onSelect(null),this.args.onClose&&this.args.onClose()}catch(t){console.error("Failed to delete:",t),alert("Failed to delete: "+t.message)}else{const t={title:getLocalizedName(e.osmTags,"Untitled Place"),lat:e.lat,lon:e.lon,tags:[],url:e.osmTags.website,osmId:String(e.osmId||e.id),osmType:e.osmType,osmTags:e.osmTags};try{const e=await this.storage.storePlace(t);console.debug("Place saved:",t.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(e),this.args.onSelect&&this.args.onSelect(e)}catch(error){console.error("Failed to save place:",error),alert("Failed to save place: "+error.message)}}}static{decorateMethodV2(this.prototype,"toggleSave",[action])}async updateBookmark(e){try{const t=await this.storage.updatePlace(e);console.debug("Place updated:",t.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(t)}catch(t){console.error("Failed to update place:",t),alert("Failed to update place: "+t.message)}}static{decorateMethodV2(this.prototype,"updateBookmark",[action])}get isNearbySearch(){const e=this.router.currentRoute.queryParams;return!e.q&&!e.category&&e.lat&&e.lon}get hasHeaderPhoto(){return this.args.selectedPlace&&this.nostrData.placePhotos&&this.nostrData.placePhotos.length>0}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[15,0,[29,["sidebar-header ",[52,[30,0,["hasHeaderPhoto"]],"no-border"]]]],[12],[1,"\\n"],[41,[30,1],[[[1," "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,0,["clearSelection"]]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["target",20,"#ea4335"]],null],[1,"\\n Nearby"],[13],[1,"\\n"]],[]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#333"]],null],[1," Results"],[13],[1,"\\n"]],[]]]],[]]],[1," "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n"],[41,[30,1],[[[1," "],[8,[32,2],null,[["@place","@onToggleSave","@onSave"],[[30,1],[30,0,["toggleSave"]],[30,0,["updateBookmark"]]]],null],[1,"\\n"]],[]],[[[41,[30,3],[[[1," "],[10,"ul"],[14,0,"places-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,3]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"place-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,3],[[30,0,["selectPlace"]],[30,4]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"place-name"],[12],[1,[28,[32,4],[[30,4,["title"]],[30,4,["osmTags","name"]],[30,4,["osmTags","name:en"]],"Unnamed Place"],null]],[13],[1,"\\n "],[10,0],[14,0,"place-type"],[12],[1,"\\n"],[41,[28,[32,5],[[30,4,["source"]],"osm"],null],[[[1," "],[1,[28,[32,6],[[30,4,["type"]]],null]],[1,"\\n"]],[]],[[[41,[28,[32,5],[[30,4,["source"]],"photon"],null],[[[1," "],[1,[30,4,["description"]]],[1,"\\n"]],[]],[[[41,[30,4,["osmTags"]],[[[1," "],[1,[28,[32,6],[[28,[32,7],[[30,4,["osmTags"]]],null]],null]],[1,"\\n"]],[]],[[[41,[30,4,["description"]],[[[1," "],[1,[30,4,["description"]]],[1,"\\n "]],[]],null]],[]]],[1," "]],[]]]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[4]],null],[1," "],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No places found nearby."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No results found."],[13],[1,"\\n"]],[]]]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline create-place"],[24,4,"button"],[4,[32,0],["click",[30,0,["createNewPlace"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["plus",18,"var(--link-color)"]],null],[1,"\\n Create new place\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"],[13]],["@selectedPlace","@onClose","@places","place"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/places-sidebar.gjs",scope:()=>[on,IconComponent,PlaceDetails,fn,OrHelper,eq$1,humanizeOsmTag,getPlaceType],isStrictMode:!0}),this)}}class SearchTemplate extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");selectPlace(e){e&&(this.mapUi.returnToSearch=!0,this.mapUi.showSidebar(),this.mapUi.preventNextZoom=!0,this.router.transitionTo("place",e))}static{decorateMethodV2(this.prototype,"selectPlace",[action])}close(){this.mapUi.hideSidebar()}static{decorateMethodV2(this.prototype,"close",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["mapUi","isSidebarVisible"]],[[[1," "],[8,[32,0],null,[["@places","@onSelect","@onClose"],[[30,0,["mapUi","searchResults"]],[30,0,["selectPlace"]],[30,0,["close"]]]],null],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/templates/search.gjs",scope:()=>[PlacesSidebar],isStrictMode:!0}),this)}}const amdModule29=Object.freeze(Object.defineProperty({__proto__:null,default:SearchTemplate},Symbol.toStringTag,{value:"Module"}));class SearchController extends Controller{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"photon",[service])}#Ye=void initializeDeferredDecorator(this,"photon");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");queryParams=["lat","lon","q","selected","category"];lat=null;lon=null;q=null;selected=null;category=null;fetchResultsTask=buildTask(()=>({context:this,generator:function*(e){this.mapUi.hideSidebar(),this.mapUi.clearSearchResults();const t=e.lat?parseFloat(e.lat):null,r=e.lon?parseFloat(e.lon):null;let n=[],i=null,o=null;try{if(e.category&&t&&r){i="category",o=e.category,this.mapUi.startLoading(i,o);let s=this.mapUi.currentBounds;if(!s){const e=.01;s={minLat:t-e,maxLat:t+e,minLon:r-e,maxLon:r+e}}n=yield this.osm.getCategoryPois(s,e.category,t,r),n=n.map(e=>({...e,_distance:getDistance$1(t,r,e.lat,e.lon)})).sort((e,t)=>e._distance-t._distance)}else if(e.q){i="text",o=e.q,this.mapUi.startLoading(i,o),n=yield this.photon.search(e.q,t,r);const s=e.q.toLowerCase(),a=this.storage.savedPlaces.filter(e=>e.title?.toLowerCase().includes(s)||e.description?.toLowerCase().includes(s));a.forEach(e=>{n.find(t=>e.osmId&&t.osmId===e.osmId||t.id&&t.id===e.id)||n.push(e)})}else if(t&&r){const e=50;n=yield this.osm.getNearbyPois(t,r,e);const i=this.storage.savedPlaces.filter(n=>getDistance$1(t,r,n.lat,n.lon)<=e);i.forEach(e=>{n.find(t=>e.osmId&&t.osmId===e.osmId||t.id&&t.id===e.id)||n.push(e)}),n=n.map(e=>({...e,_distance:getDistance$1(t,r,e.lat,e.lon)})).sort((e,t)=>e._distance-t._distance)}}catch(error){return console.error("Search request failed.",error),this.toast.show("Search request failed. Please try again."),void this.mapUi.stopSearch()}finally{i&&o&&this.mapUi.stopLoading(i,o)}n=n.map(e=>this.storage.findPlaceById(e.osmId)||e);const s=e.selected||e.q;if(s&&n.length>0){let e=null;if(e=n.find(e=>e.osmTags&&(e.osmTags.name===s||e.osmTags["name:en"]===s)),!e){const t=n[0];t._distance<=10&&(e=t)}if(e)return this.router.replaceWith("place",e),void this.mapUi.stopSearch()}this.mapUi.setSearchResults(n),this.mapUi.showSidebar(),this.mapUi.stopSearch()}}),{restartable:!0},"fetchResultsTask")}const amdModule30=Object.freeze(Object.defineProperty({__proto__:null,default:SearchController},Symbol.toStringTag,{value:"Module"}));class SearchRoute extends Route{static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0},q:{refreshModel:!0},selected:{refreshModel:!0},category:{refreshModel:!0}};model(e){return e}setupController(e,t){super.setupController(e,t),e.fetchResultsTask.perform(t);const{q:r,category:n,lat:i,lon:o}=this.paramsFor("search");this.mapUi.currentSearch={q:r,category:n,lat:i,lon:o}}resetController(e,t){t&&(e.fetchResultsTask.cancelAll(),this.mapUi.stopSearch())}error(e,t){return this.mapUi.stopSearch(),this.toast.show("Search request failed. Please try again."),t&&t.abort(),!1}static{decorateMethodV2(this.prototype,"error",[action])}}const amdModule31=Object.freeze(Object.defineProperty({__proto__:null,default:SearchRoute},Symbol.toStringTag,{value:"Module"}));var _dec,_class,_descriptor;let PageTitle=(_dec=service("page-title"),_class=class extends Helper{constructor(e){super(e),_initializerDefineProperty(this,"tokens",_descriptor,this),_defineProperty(this,"tokenId",guidFor(this)),this.tokens.push({id:this.tokenId})}compute(e,t){const r={...t,id:this.tokenId,title:e.join("")};return this.tokens.push(r),this.tokens.scheduleTitleUpdate(),""}willDestroy(){super.willDestroy(),this.tokens.remove(this.tokenId),this.tokens.scheduleTitleUpdate()}},_descriptor=_applyDecoratedDescriptor(_class.prototype,"tokens",[_dec],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),_class);const CollectionEventType={ADD:"add",REMOVE:"remove"},ObjectEventType={PROPERTYCHANGE:"propertychange"},EventType$1={CHANGE:"change",ERROR:"error",CONTEXTMENU:"contextmenu",CLICK:"click",DBLCLICK:"dblclick",KEYDOWN:"keydown",KEYPRESS:"keypress",LOAD:"load",TOUCHMOVE:"touchmove",WHEEL:"wheel"};class Disposable{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}}function binarySearch$1(e,t,r){let n,i;r=r||ascending;let o=0,s=e.length,a=!1;for(;o>1),i=+r(e[n],t),i<0?o=n+1:(s=n,a=!i);return a?o:~o}function ascending(e,t){return e>t?1:et?-1:0}function linearFindNearest(e,t,r){if(e[0]<=t)return 0;const n=e.length;if(t<=e[n-1])return n-1;if("function"==typeof r){for(let i=1;i0?i-1:i}return n-1}if(r>0){for(let r=1;r0||0===i)})}function TRUE(){return!0}function FALSE(){return!1}function VOID(){}function memoizeOne(e){let t,r,n;return function(){const i=Array.prototype.slice.call(arguments);return r&&this===n&&equals$2(i,r)||(n=this,r=i,t=e.apply(this,arguments)),t}}function toPromise(e){return function(){let t;try{t=e()}catch(r){return Promise.reject(r)}return t instanceof Promise?t:Promise.resolve(t)}()}function clear(e){for(const t in e)delete e[t]}function isEmpty$1(e){let t;for(t in e)return!1;return!t}class BaseEvent{constructor(e){this.propagationStopped,this.defaultPrevented,this.type=e,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}}class Target extends Disposable{constructor(e){super(),this.eventTarget_=e,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null}addEventListener(e,t){if(!e||!t)return;const r=this.listeners_||(this.listeners_={}),n=r[e]||(r[e]=[]);n.includes(t)||n.push(t)}dispatchEvent(e){const t="string"==typeof e,r=t?e:e.type,n=this.listeners_&&this.listeners_[r];if(!n)return;const i=t?new BaseEvent(e):e;i.target||(i.target=this.eventTarget_||this);const o=this.dispatching_||(this.dispatching_={}),s=this.pendingRemovals_||(this.pendingRemovals_={});let a;r in o||(o[r]=0,s[r]=0),++o[r];for(let l=0,c=n.length;l0)}removeEventListener(e,t){if(!this.listeners_)return;const r=this.listeners_[e];if(!r)return;const n=r.indexOf(t);-1!==n&&(this.pendingRemovals_&&e in this.pendingRemovals_?(r[n]=VOID,++this.pendingRemovals_[e]):(r.splice(n,1),0===r.length&&delete this.listeners_[e]))}}function listen(e,t,r,n,i){if(i){const i=r;r=function(o){return e.removeEventListener(t,r),i.call(n??this,o)}}else n&&n!==e&&(r=r.bind(n));const o={target:e,type:t,listener:r};return e.addEventListener(t,r),o}function listenOnce(e,t,r,n){return listen(e,t,r,n,!0)}function unlistenByKey(e){e&&e.target&&(e.target.removeEventListener(e.type,e.listener),clear(e))}class Observable extends Target{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent(EventType$1.CHANGE)}getRevision(){return this.revision_}onInternal(e,t){if(Array.isArray(e)){const r=e.length,n=new Array(r);for(let i=0;i0;)this.pop()}extend(e){for(let t=0,r=e.length;tthis.getLength())throw new Error("Index out of bounds: "+e);this.unique_&&this.assertUnique_(t),this.array_.splice(e,0,t),this.updateLength_(),this.dispatchEvent(new CollectionEvent(CollectionEventType.ADD,t,e))}pop(){return this.removeAt(this.getLength()-1)}push(e){const t=this.getLength();return this.insertAt(t,e),this.getLength()}remove(e){const t=this.array_;for(let r=0,n=t.length;r=this.getLength())return;const t=this.array_[e];return this.array_.splice(e,1),this.updateLength_(),this.dispatchEvent(new CollectionEvent(CollectionEventType.REMOVE,t,e)),t}setAt(e,t){if(e>=this.getLength())return void this.insertAt(e,t);if(e<0)throw new Error("Index out of bounds: "+e);this.unique_&&this.assertUnique_(t,e);const r=this.array_[e];this.array_[e]=t,this.dispatchEvent(new CollectionEvent(CollectionEventType.REMOVE,r,e)),this.dispatchEvent(new CollectionEvent(CollectionEventType.ADD,t,e))}updateLength_(){this.set(Property$4.LENGTH,this.array_.length)}assertUnique_(e,t){const r=this.array_;for(let n=0,i=r.length;n{this.clickTimeoutId_=void 0;const t=new MapBrowserEvent(MapBrowserEventType.SINGLECLICK,this.map_,e);this.dispatchEvent(t)},250)}updateActivePointers_(e){const t=e,r=t.pointerId;if(t.type==MapBrowserEventType.POINTERUP||t.type==MapBrowserEventType.POINTERCANCEL){delete this.trackedTouches_[r];for(const e in this.trackedTouches_)if(this.trackedTouches_[e].target!==t.target){delete this.trackedTouches_[e];break}}else t.type!=MapBrowserEventType.POINTERDOWN&&t.type!=MapBrowserEventType.POINTERMOVE||(this.trackedTouches_[r]=t);this.activePointers_=Object.values(this.trackedTouches_)}handlePointerUp_(e){this.updateActivePointers_(e);const t=new MapBrowserEvent(MapBrowserEventType.POINTERUP,this.map_,e,void 0,void 0,this.activePointers_);this.dispatchEvent(t),this.emulateClicks_&&!t.defaultPrevented&&!this.dragging_&&this.isMouseActionButton_(e)&&this.emulateClick_(this.down_),0===this.activePointers_.length&&(this.dragListenerKeys_.forEach(unlistenByKey),this.dragListenerKeys_.length=0,this.dragging_=!1,this.down_=null)}isMouseActionButton_(e){return 0===e.button}handlePointerDown_(e){this.emulateClicks_=0===this.activePointers_.length,this.updateActivePointers_(e);const t=new MapBrowserEvent(MapBrowserEventType.POINTERDOWN,this.map_,e,void 0,void 0,this.activePointers_);if(this.dispatchEvent(t),this.down_=new PointerEvent(e.type,e),Object.defineProperty(this.down_,"target",{writable:!1,value:e.target}),0===this.dragListenerKeys_.length){const e=this.map_.getOwnerDocument();this.dragListenerKeys_.push(listen(e,MapBrowserEventType.POINTERMOVE,this.handlePointerMove_,this),listen(e,MapBrowserEventType.POINTERUP,this.handlePointerUp_,this),listen(this.element_,MapBrowserEventType.POINTERCANCEL,this.handlePointerUp_,this)),this.element_.getRootNode&&this.element_.getRootNode()!==e&&this.dragListenerKeys_.push(listen(this.element_.getRootNode(),MapBrowserEventType.POINTERUP,this.handlePointerUp_,this))}}handlePointerMove_(e){if(this.isMoving_(e)){this.updateActivePointers_(e),this.dragging_=!0;const t=new MapBrowserEvent(MapBrowserEventType.POINTERDRAG,this.map_,e,this.dragging_,void 0,this.activePointers_);this.dispatchEvent(t)}}relayMoveEvent_(e){this.originalPointerMoveEvent_=e;const t=!(!this.down_||!this.isMoving_(e));this.dispatchEvent(new MapBrowserEvent(MapBrowserEventType.POINTERMOVE,this.map_,e,t))}handleTouchMove_(e){const t=this.originalPointerMoveEvent_;t&&!t.defaultPrevented||"boolean"==typeof e.cancelable&&!0!==e.cancelable||e.preventDefault()}isMoving_(e){return this.dragging_||Math.abs(e.clientX-this.down_.clientX)>this.moveTolerance_||Math.abs(e.clientY-this.down_.clientY)>this.moveTolerance_}disposeInternal(){this.relayedListenerKey_&&(unlistenByKey(this.relayedListenerKey_),this.relayedListenerKey_=null),this.element_.removeEventListener(EventType$1.TOUCHMOVE,this.boundHandleTouchMove_),this.pointerdownListenerKey_&&(unlistenByKey(this.pointerdownListenerKey_),this.pointerdownListenerKey_=null),this.dragListenerKeys_.forEach(unlistenByKey),this.dragListenerKeys_.length=0,this.element_=null,super.disposeInternal()}}const MapEventType={POSTRENDER:"postrender",MOVESTART:"movestart",MOVEEND:"moveend",LOADSTART:"loadstart",LOADEND:"loadend"},MapProperty={LAYERGROUP:"layergroup",SIZE:"size",TARGET:"target",VIEW:"view"},TileState={IDLE:0,LOADING:1,LOADED:2,ERROR:3,EMPTY:4};function assert$1(e,t){if(!e)throw new Error(t)}const DROP=1/0;class PriorityQueue{constructor(e,t){this.priorityFunction_=e,this.keyFunction_=t,this.elements_=[],this.priorities_=[],this.queuedElements_={}}clear(){this.elements_.length=0,this.priorities_.length=0,clear(this.queuedElements_)}dequeue(){const e=this.elements_,t=this.priorities_,r=e[0];1==e.length?(e.length=0,t.length=0):(e[0]=e.pop(),t[0]=t.pop(),this.siftUp_(0));const n=this.keyFunction_(r);return delete this.queuedElements_[n],r}enqueue(e){assert$1(!(this.keyFunction_(e)in this.queuedElements_),"Tried to enqueue an `element` that was already added to the queue");const t=this.priorityFunction_(e);return t!=DROP&&(this.elements_.push(e),this.priorities_.push(t),this.queuedElements_[this.keyFunction_(e)]=!0,this.siftDown_(0,this.elements_.length-1),!0)}getCount(){return this.elements_.length}getLeftChildIndex_(e){return 2*e+1}getRightChildIndex_(e){return 2*e+2}getParentIndex_(e){return e-1>>1}heapify_(){let e;for(e=(this.elements_.length>>1)-1;e>=0;e--)this.siftUp_(e)}isEmpty(){return 0===this.elements_.length}isKeyQueued(e){return e in this.queuedElements_}isQueued(e){return this.isKeyQueued(this.keyFunction_(e))}siftUp_(e){const t=this.elements_,r=this.priorities_,n=t.length,i=t[e],o=r[e],s=e;for(;e>1;){const i=this.getLeftChildIndex_(e),o=this.getRightChildIndex_(e),s=oe;){const e=this.getParentIndex_(t);if(!(n[e]>o))break;r[t]=r[e],n[t]=n[e],t=e}r[t]=i,n[t]=o}reprioritize(){const e=this.priorityFunction_,t=this.elements_,r=this.priorities_;let n=0;const i=t.length;let o,s,a;for(s=0;se.apply(null,t),e=>e[0].getKey()),this.boundHandleTileChange_=this.handleTileChange.bind(this),this.tileChangeCallback_=t,this.tilesLoading_=0,this.tilesLoadingKeys_={}}enqueue(e){const t=super.enqueue(e);return t&&e[0].addEventListener(EventType$1.CHANGE,this.boundHandleTileChange_),t}getTilesLoading(){return this.tilesLoading_}handleTileChange(e){const t=e.target,r=t.getState();if(r===TileState.LOADED||r===TileState.ERROR||r===TileState.EMPTY){r!==TileState.ERROR&&t.removeEventListener(EventType$1.CHANGE,this.boundHandleTileChange_);const e=t.getKey();e in this.tilesLoadingKeys_&&(delete this.tilesLoadingKeys_[e],--this.tilesLoading_),this.tileChangeCallback_()}}loadMoreTiles(e,t){let r=0;for(;this.tilesLoading_0;){const e=this.dequeue()[0],t=e.getKey();e.getState()!==TileState.IDLE||t in this.tilesLoadingKeys_||(this.tilesLoadingKeys_[t]=!0,++this.tilesLoading_,++r,e.load())}}}function getTilePriority(e,t,r,n,i){if(!e||!(r in e.wantedTiles))return DROP;if(!e.wantedTiles[r][t.getKey()])return DROP;const o=e.viewState.center,s=n[0]-o[0],a=n[1]-o[1];return 65536*Math.log(i)+Math.sqrt(s*s+a*a)/i}const ViewHint={ANIMATING:0,INTERACTING:1},ViewProperty={CENTER:"center",RESOLUTION:"resolution",ROTATION:"rotation"};function clamp$1(e,t,r){return Math.min(Math.max(e,t),r)}function squaredSegmentDistance(e,t,r,n,i,o){const s=i-r,a=o-n;if(0!==s||0!==a){const l=((e-r)*s+(t-n)*a)/(s*s+a*a);l>1?(r=i,n=o):l>0&&(r+=s*l,n+=a*l)}return squaredDistance$1(e,t,r,n)}function squaredDistance$1(e,t,r,n){const i=r-e,o=n-t;return i*i+o*o}function solveLinearSystem(e){const t=e.length;for(let n=0;ni&&(i=t,r=s)}if(0===i)return null;const o=e[r];e[r]=e[n],e[n]=o;for(let s=n+1;s=0;n--){r[n]=e[n][t]/e[n][n];for(let i=n-1;i>=0;i--)e[i][t]-=e[i][n]*r[n]}return r}function toDegrees(e){return 180*e/Math.PI}function toRadians(e){return e*Math.PI/180}function modulo(e,t){const r=e%t;return r*t<0?r+t:r}function lerp(e,t,r){return e+r*(t-e)}function toFixed(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function floor(e,t){return Math.floor(toFixed(e,t))}function ceil(e,t){return Math.ceil(toFixed(e,t))}function wrap(e,t,r){if(e>=t&&ep&&(d=(p+d)/2,p=d),f>g&&(f=(g+f)/2,g=f);let m=clamp$1(n[0],d,p),y=clamp$1(n[1],f,g);if(s&&r&&i){const e=30*i;m+=-e*Math.log(1+Math.max(0,d-n[0])/e)+e*Math.log(1+Math.max(0,n[0]-p)/e),y+=-e*Math.log(1+Math.max(0,f-n[1])/e)+e*Math.log(1+Math.max(0,n[1]-g)/e)}return[m,y]}}function none$1(e){return e}const Relationship={UNKNOWN:0,INTERSECTING:1,ABOVE:2,RIGHT:4,BELOW:8,LEFT:16};function boundingExtent(e){const t=createEmpty();for(let r=0,n=e.length;ri&&(l|=Relationship.RIGHT),ao&&(l|=Relationship.ABOVE),l===Relationship.UNKNOWN&&(l=Relationship.INTERSECTING),l}function createEmpty(){return[1/0,1/0,-1/0,-1/0]}function createOrUpdate$2(e,t,r,n,i){return i?(i[0]=e,i[1]=t,i[2]=r,i[3]=n,i):[e,t,r,n]}function createOrUpdateEmpty(e){return createOrUpdate$2(1/0,1/0,-1/0,-1/0,e)}function createOrUpdateFromCoordinate(e,t){const r=e[0],n=e[1];return createOrUpdate$2(r,n,r,n,t)}function createOrUpdateFromFlatCoordinates(e,t,r,n,i){return extendFlatCoordinates(createOrUpdateEmpty(i),e,t,r,n)}function equals$1(e,t){return e[0]==t[0]&&e[2]==t[2]&&e[1]==t[1]&&e[3]==t[3]}function extend$1(e,t){return t[0]e[2]&&(e[2]=t[2]),t[1]e[3]&&(e[3]=t[3]),e}function extendCoordinate(e,t){t[0]e[2]&&(e[2]=t[0]),t[1]e[3]&&(e[3]=t[1])}function extendFlatCoordinates(e,t,r,n,i){for(;rt[0]?n[0]=e[0]:n[0]=t[0],e[1]>t[1]?n[1]=e[1]:n[1]=t[1],e[2]=t[0]&&e[1]<=t[3]&&e[3]>=t[1]}function isEmpty(e){return e[2]=s&&g<=l),n||!(o&Relationship.RIGHT)||i&Relationship.RIGHT||(m=p-(d-l)*f,n=m>=a&&m<=c),n||!(o&Relationship.BELOW)||i&Relationship.BELOW||(g=d-(p-a)/f,n=g>=s&&g<=l),n||!(o&Relationship.LEFT)||i&Relationship.LEFT||(m=p-(d-s)*f,n=m>=a&&m<=c)}return n}function applyTransform(e,t,r,n){if(isEmpty(e))return createOrUpdateEmpty(r);let i=[];if(n>1){const t=e[2]-e[0],r=e[3]-e[1];for(let o=0;o=r[2])){const t=getWidth(r),i=Math.floor((n[0]-r[0])/t)*t;e[0]-=i,e[2]-=i}return e}function wrapAndSliceX(e,t,r){if(t.canWrapX()){const n=t.getExtent();if(!isFinite(e[0])||!isFinite(e[2]))return[[n[0],e[1],n[2],e[3]]];wrapX$2(e,t);const i=getWidth(n);if(getWidth(e)>i&&!r)return[[n[0],e[1],n[2],e[3]]];if(e[0]n[2])return[[e[0],e[1],n[2],e[3]],[n[0],e[1],e[2]-i,e[3]]]}return[e]}function add$2(e,t){return e[0]+=+t[0],e[1]+=+t[1],e}function equals(e,t){let r=!0;for(let n=e.length-1;n>=0;--n)if(e[n]!=t[n]){r=!1;break}return r}function rotate$1(e,t){const r=Math.cos(t),n=Math.sin(t),i=e[0]*r-e[1]*n,o=e[1]*r+e[0]*n;return e[0]=i,e[1]=o,e}function scale$3(e,t){return e[0]*=t,e[1]*=t,e}function squaredDistance(e,t){const r=e[0]-t[0],n=e[1]-t[1];return r*r+n*n}function distance(e,t){return Math.sqrt(squaredDistance(e,t))}function wrapX$1(e,t){if(t.canWrapX()){const r=getWidth(t.getExtent()),n=getWorldsAway(e,t,r);n&&(e[0]-=n*r)}return e}function getWorldsAway(e,t,r){const n=t.getExtent();let i=0;return t.canWrapX()&&(e[0]n[2])&&(r=r||getWidth(n),i=Math.floor((e[0]-n[0])/r)),i}function easeIn(e){return Math.pow(e,3)}function easeOut(e){return 1-easeIn(1-e)}function inAndOut(e){return 3*e*e-2*e*e*e}function linear(e){return e}const DEFAULT_RADIUS=6371008.8;function getDistance(e,t,r){r=r||DEFAULT_RADIUS;const n=toRadians(e[1]),i=toRadians(t[1]),o=(i-n)/2,s=toRadians(t[0]-e[0])/2,a=Math.sin(o)*Math.sin(o)+Math.sin(s)*Math.sin(s)*Math.cos(n)*Math.cos(i);return 2*r*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}function offset(e,t,r,n){n=n||DEFAULT_RADIUS;const i=toRadians(e[1]),o=toRadians(e[0]),s=t/n,a=Math.asin(Math.sin(i)*Math.cos(s)+Math.cos(i)*Math.sin(s)*Math.cos(r));return[toDegrees(o+Math.atan2(Math.sin(r)*Math.sin(s)*Math.cos(i),Math.cos(s)-Math.sin(i)*Math.sin(a))),toDegrees(a)]}function warn(...e){console.warn(...e)}const METERS_PER_UNIT$1={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};class Projection{constructor(e){this.code_=e.code,this.units_=e.units,this.extent_=void 0!==e.extent?e.extent:null,this.worldExtent_=void 0!==e.worldExtent?e.worldExtent:null,this.axisOrientation_=void 0!==e.axisOrientation?e.axisOrientation:"enu",this.global_=void 0!==e.global&&e.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=e.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=e.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||METERS_PER_UNIT$1[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(e){this.global_=e,this.canWrapX_=!(!e||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(e){this.defaultTileGrid_=e}setExtent(e){this.extent_=e,this.canWrapX_=!(!this.global_||!e)}setWorldExtent(e){this.worldExtent_=e}setGetPointResolution(e){this.getPointResolutionFunc_=e}getPointResolutionFunc(){return this.getPointResolutionFunc_}}const RADIUS$1=6378137,HALF_SIZE=Math.PI*RADIUS$1,EXTENT$2=[-HALF_SIZE,-HALF_SIZE,HALF_SIZE,HALF_SIZE],WORLD_EXTENT=[-180,-85,180,85],MAX_SAFE_Y=RADIUS$1*Math.log(Math.tan(Math.PI/2));class EPSG3857Projection extends Projection{constructor(e){super({code:e,units:"m",extent:EXTENT$2,global:!0,worldExtent:WORLD_EXTENT,getPointResolution:function(e,t){return e/Math.cosh(t[1]/RADIUS$1)}})}}const PROJECTIONS$1=[new EPSG3857Projection("EPSG:3857"),new EPSG3857Projection("EPSG:102100"),new EPSG3857Projection("EPSG:102113"),new EPSG3857Projection("EPSG:900913"),new EPSG3857Projection("http://www.opengis.net/def/crs/EPSG/0/3857"),new EPSG3857Projection("http://www.opengis.net/gml/srs/epsg.xml#3857")];function fromEPSG4326(e,t,r,n){const i=e.length;r=r>1?r:2,n=n??r,void 0===t&&(t=r>2?e.slice():new Array(i));for(let o=0;oMAX_SAFE_Y?r=MAX_SAFE_Y:r<-MAX_SAFE_Y&&(r=-MAX_SAFE_Y),t[o+1]=r}return t}function toEPSG4326(e,t,r,n){const i=e.length;r=r>1?r:2,n=n??r,void 0===t&&(t=r>2?e.slice():new Array(i));for(let o=0;oMAX_LATITUDE&&(t=MAX_LATITUDE);const n=toRadians(t),i=Math.sin(n),o=Math.cos(n),s=i/o,a=s*s,l=a*a,c=toRadians(e),u=toRadians(zoneToCentralLongitude(r.number)),h=R/Math.sqrt(1-E*i**2),d=E_P2*o**2,p=o*wrap(c-u,-Math.PI,Math.PI),f=p*p,g=f*p,m=g*p,y=m*p,b=y*p,v=R*(M1*n-M2*Math.sin(2*n)+M3*Math.sin(4*n)-M4*Math.sin(6*n)),_=K0*h*(p+g/6*(1-a+d)+y/120*(5-18*a+l+72*d-58*E_P2))+5e5;let w=K0*(v+h*s*(f/2+m/24*(5-a+9*d+4*d**2)+b/720*(61-58*a+l+600*d-330*E_P2)));return r.north||(w+=1e7),[_,w]}function zoneToCentralLongitude(e){return 6*(e-1)-180+3}const epsgRegExes=[/^EPSG:(\d+)$/,/^urn:ogc:def:crs:EPSG::(\d+)$/,/^http:\/\/www\.opengis\.net\/def\/crs\/EPSG\/0\/(\d+)$/];function zoneFromCode(e){let t=0;for(const i of epsgRegExes){const r=e.match(i);if(r){t=parseInt(r[1]);break}}if(!t)return null;let r=0,n=!1;return t>32700&&t<32761?r=t-32700:t>32600&&t<32661&&(n=!0,r=t-32600),r?{number:r,north:n}:null}function makeTransformFunction(e,t){return function(r,n,i,o){const s=r.length;i=i>1?i:2,o=o??i,n||(n=i>2?r.slice():new Array(s));for(let a=0;a=a?t[s+e]:o[e]}return r}}function fromLonLat(e,t){return disableCoordinateWarning(),transform(e,"EPSG:4326",void 0!==t?t:"EPSG:3857")}function toLonLat(e){const t=transform(e,"EPSG:3857","EPSG:4326"),r=t[0];return(r<-180||r>180)&&(t[0]=modulo(r+180,360)-180),t}function equivalent$1(e,t){if(e===t)return!0;const r=e.getUnits()===t.getUnits();return(e.getCode()===t.getCode()||getTransformFromProjections(e,t)===cloneTransform)&&r}function getTransformFromProjections(e,t){const r=e.getCode(),n=t.getCode();let i=get$3(r,n);if(i)return i;let o=null,s=null;for(const l of transformFactories)o||(o=l(e)),s||(s=l(t));if(!o&&!s)return null;const a="EPSG:4326";if(s)if(o)i=composeTransformFuncs(o.inverse,s.forward);else{const e=get$3(r,a);e&&(i=composeTransformFuncs(e,s.forward))}else{const e=get$3(a,n);e&&(i=composeTransformFuncs(o.inverse,e))}return i&&(addProjection(e),addProjection(t),add(e,t,i)),i}function composeTransformFuncs(e,t){return function(r,n,i,o){return n=e(r,n,i,o),t(n,n,i,o)}}function getTransform(e,t){return getTransformFromProjections(get$2(e),get$2(t))}function transform(e,t,r){const n=getTransform(t,r);if(!n){const e=get$2(t).getCode(),n=get$2(r).getCode();throw new Error(`No transform available between ${e} and ${n}`)}return n(e,void 0,e.length)}function transformExtent(e,t,r,n){return applyTransform(e,getTransform(t,r),void 0,n)}let userProjection=null;function getUserProjection(){return userProjection}function toUserCoordinate(e){return e}function fromUserCoordinate(e){return showCoordinateWarning&&!equals(e,[0,0])&&e[0]>=-180&&e[0]<=180&&e[1]>=-90&&e[1]<=90&&(showCoordinateWarning=!1,warn("Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.")),e}function toUserExtent(e){return e}function fromUserExtent(e){return e}function addCommon(){addEquivalentProjections(PROJECTIONS$1),addEquivalentProjections(PROJECTIONS),addEquivalentTransforms(PROJECTIONS,PROJECTIONS$1,fromEPSG4326,toEPSG4326)}addCommon();const tmp_=new Array(6);function create(){return[1,0,0,1,0,0]}function reset(e){return set(e,1,0,0,1,0,0)}function multiply(e,t){const r=e[0],n=e[1],i=e[2],o=e[3],s=e[4],a=e[5],l=t[0],c=t[1],u=t[2],h=t[3],d=t[4],p=t[5];return e[0]=r*l+i*c,e[1]=n*l+o*c,e[2]=r*u+i*h,e[3]=n*u+o*h,e[4]=r*d+i*p+s,e[5]=n*d+o*p+a,e}function set(e,t,r,n,i,o,s){return e[0]=t,e[1]=r,e[2]=n,e[3]=i,e[4]=o,e[5]=s,e}function setFromArray(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e}function apply$1(e,t){const r=t[0],n=t[1];return t[0]=e[0]*r+e[2]*n+e[4],t[1]=e[1]*r+e[3]*n+e[5],t}function scale$2(e,t,r){return multiply(e,set(tmp_,t,0,0,r,0,0))}function translate$1(e,t,r){return multiply(e,set(tmp_,1,0,0,1,t,r))}function compose(e,t,r,n,i,o,s,a){const l=Math.sin(o),c=Math.cos(o);return e[0]=n*c,e[1]=i*l,e[2]=-n*l,e[3]=i*c,e[4]=s*n*c-a*n*l+t,e[5]=s*i*l+a*i*c+r,e}function makeInverse(e,t){const r=determinant(t);assert$1(0!==r,"Transformation matrix cannot be inverted");const n=t[0],i=t[1],o=t[2],s=t[3],a=t[4],l=t[5];return e[0]=s/r,e[1]=-i/r,e[2]=-o/r,e[3]=n/r,e[4]=(o*l-s*a)/r,e[5]=-(n*l-i*a)/r,e}function determinant(e){return e[0]*e[3]-e[1]*e[2]}const matrixPrecision=[1e5,1e5,1e5,1e5,2,2];function toString$1(e){return"matrix("+e.join(", ")+")"}function fromString$1(e){return e.substring(7,e.length-1).split(",").map(parseFloat)}function equivalent(e,t){const r=fromString$1(e),n=fromString$1(t);for(let i=0;i<6;++i)if(0!==Math.round((r[i]-n[i])*matrixPrecision[i]))return!1;return!0}function transform2D(e,t,r,n,i,o,s){o=o||[],s=s||2;let a=0;for(let l=t;l{if(!r)return this.getSimplifiedGeometry(t);const n=this.clone();return n.applyTransform(r),n.getSimplifiedGeometry(t)})}simplifyTransformed(e,t){return this.simplifyTransformedInternal(this.getRevision(),e,t)}clone(){return abstract()}closestPointXY(e,t,r,n){return abstract()}containsXY(e,t){return 0===this.closestPointXY(e,t,tmpPoint,Number.MIN_VALUE)}getClosestPoint(e,t){return t=t||[NaN,NaN],this.closestPointXY(e[0],e[1],t,1/0),t}intersectsCoordinate(e){return this.containsXY(e[0],e[1])}computeExtent(e){return abstract()}getExtent(e){if(this.extentRevision_!=this.getRevision()){const e=this.computeExtent(this.extent_);(isNaN(e[0])||isNaN(e[1]))&&createOrUpdateEmpty(e),this.extentRevision_=this.getRevision()}return returnOrUpdate(this.extent_,e)}rotate(e,t){abstract()}scale(e,t,r){abstract()}simplify(e){return this.getSimplifiedGeometry(e*e)}getSimplifiedGeometry(e){return abstract()}getType(){return abstract()}applyTransform(e){abstract()}intersectsExtent(e){return abstract()}translate(e,t){abstract()}transform(e,t){const r=get$2(e),n="tile-pixels"==r.getUnits()?function(e,n,i){const o=r.getExtent(),s=r.getWorldExtent(),a=getHeight(s)/getHeight(o);compose(tmpTransform$1,s[0],s[3],a,-a,0,0,0);const l=transform2D(e,0,e.length,i,tmpTransform$1,n),c=getTransform(r,t);return c?c(l,l,i):l}:getTransform(r,t);return this.applyTransform(n),this}}class SimpleGeometry extends Geometry{constructor(){super(),this.layout="XY",this.stride=2,this.flatCoordinates}computeExtent(e){return createOrUpdateFromFlatCoordinates(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,e)}getCoordinates(){return abstract()}getFirstCoordinate(){return this.flatCoordinates.slice(0,this.stride)}getFlatCoordinates(){return this.flatCoordinates}getLastCoordinate(){return this.flatCoordinates.slice(this.flatCoordinates.length-this.stride)}getLayout(){return this.layout}getSimplifiedGeometry(e){if(this.simplifiedGeometryRevision!==this.getRevision()&&(this.simplifiedGeometryMaxMinSquaredTolerance=0,this.simplifiedGeometryRevision=this.getRevision()),e<0||0!==this.simplifiedGeometryMaxMinSquaredTolerance&&e<=this.simplifiedGeometryMaxMinSquaredTolerance)return this;const t=this.getSimplifiedGeometryInternal(e);return t.getFlatCoordinates().length1)h=r;else{if(d>0){for(let i=0;ii&&(i=a),o=r,s=n}return i}function arrayMaxSquaredDelta(e,t,r,n,i){for(let o=0,s=r.length;o0;){const r=c.pop(),o=c.pop();let s=0;const a=e[o],h=e[o+1],d=e[r],p=e[r+1];for(let t=o+n;ts&&(u=t,s=r)}s>i&&(l[(u-t)/n]=1,o+n0&&f>d)&&(p<0&&g0&&g>p)?(a=r,l=h):(o[s++]=a,o[s++]=l,c=a,u=l,a=r,l=h)}return o[s++]=a,o[s++]=l,s}function quantizeArray(e,t,r,n,i,o,s,a){for(let l=0,c=r.length;lo&&(r-a)*(o-l)-(i-a)*(n-l)>0&&s++:n<=o&&(r-a)*(o-l)-(i-a)*(n-l)<0&&s--,a=r,l=n}return 0!==s}function linearRingsContainsXY(e,t,r,n,i,o){if(0===r.length)return!1;if(!linearRingContainsXY(e,t,r[0],n,i,o))return!1;for(let s=1,a=r.length;sy&&(c=(u+h)/2,linearRingsContainsXY(e,t,r,n,c,f)&&(m=c,y=i)),u=h}return isNaN(m)&&(m=i[o]),s?(s.push(m,f,y),s):[m,f,y]}function getInteriorPointsOfMultiArray(e,t,r,n,i){let o=[];for(let s=0,a=r.length;s=i[0]&&o[2]<=i[2]||o[1]>=i[1]&&o[3]<=i[3]||forEach(e,t,r,n,function(e,t){return intersectsSegment(i,e,t)}))}function intersectsLineStringArray(e,t,r,n,i){for(let o=0,s=r.length;o0}function linearRingsAreOriented(e,t,r,n,i){i=void 0!==i&&i;for(let o=0,s=r.length;ou&&d1&&"function"==typeof arguments[r-1]&&(t=arguments[r-1],--r);let n=0;for(;n0}getInteracting(){return this.hints_[ViewHint.INTERACTING]>0}cancelAnimations(){let e;this.setHint(ViewHint.ANIMATING,-this.hints_[ViewHint.ANIMATING]);for(let t=0,r=this.animations_.length;t=0;--r){const n=this.animations_[r];let i=!0;for(let r=0,o=n.length;r0?s/o.duration:1;a>=1?(o.complete=!0,a=1):i=!1;const l=o.easing(a);if(o.sourceCenter){const e=o.sourceCenter[0],t=o.sourceCenter[1],r=o.targetCenter[0],n=o.targetCenter[1];this.nextCenter_=o.targetCenter;const i=e+l*(r-e),s=t+l*(n-t);this.targetCenter_=[i,s]}if(o.sourceResolution&&o.targetResolution){const e=1===l?o.targetResolution:o.sourceResolution+l*(o.targetResolution-o.sourceResolution);if(o.anchor){const t=this.getViewportSize_(this.getRotation()),r=this.constraints_.resolution(e,0,t,!0);this.targetCenter_=this.calculateCenterZoom(r,o.anchor)}this.nextResolution_=o.targetResolution,this.targetResolution_=e,this.applyTargetState_(!0)}if(void 0!==o.sourceRotation&&void 0!==o.targetRotation){const e=1===l?modulo(o.targetRotation+Math.PI,2*Math.PI)-Math.PI:o.sourceRotation+l*(o.targetRotation-o.sourceRotation);if(o.anchor){const t=this.constraints_.rotation(e,!0);this.targetCenter_=this.calculateCenterRotate(t,o.anchor)}this.nextRotation_=o.targetRotation,this.targetRotation_=e}if(this.applyTargetState_(!0),t=!0,!o.complete)break}if(i){this.animations_[r]=null,this.setHint(ViewHint.ANIMATING,-1),this.nextCenter_=null,this.nextResolution_=NaN,this.nextRotation_=NaN;const e=n[0].callback;e&&animationCallback(e,!0)}}this.animations_=this.animations_.filter(Boolean),t&&void 0===this.updateAnimationKey_&&(this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_.bind(this)))}calculateCenterRotate(e,t){let r;const n=this.getCenterInternal();return void 0!==n&&(r=[n[0]-t[0],n[1]-t[1]],rotate$1(r,e-this.getRotation()),add$2(r,t)),r}calculateCenterZoom(e,t){let r;const n=this.getCenterInternal(),i=this.getResolution();return void 0!==n&&void 0!==i&&(r=[t[0]-e*(t[0]-n[0])/i,t[1]-e*(t[1]-n[1])/i]),r}getViewportSize_(e){const t=this.viewportSize_;if(e){const r=t[0],n=t[1];return[Math.abs(r*Math.cos(e))+Math.abs(n*Math.sin(e)),Math.abs(r*Math.sin(e))+Math.abs(n*Math.cos(e))]}return t}setViewportSize(e){this.viewportSize_=Array.isArray(e)?e.slice():[100,100],this.getAnimating()||this.resolveConstraints(0)}getCenter(){const e=this.getCenterInternal();return e?toUserCoordinate(e,this.getProjection()):e}getCenterInternal(){return this.get(ViewProperty.CENTER)}getConstraints(){return this.constraints_}getConstrainResolution(){return this.get("constrainResolution")}getHints(e){return void 0!==e?(e[0]=this.hints_[0],e[1]=this.hints_[1],e):this.hints_.slice()}calculateExtent(e){return toUserExtent(this.calculateExtentInternal(e),this.getProjection())}calculateExtentInternal(e){e=e||this.getViewportSizeMinusPadding_();const t=this.getCenterInternal();assert$1(t,"The view center is not defined");const r=this.getResolution();assert$1(void 0!==r,"The view resolution is not defined");const n=this.getRotation();return assert$1(void 0!==n,"The view rotation is not defined"),getForViewAndSize(t,r,n,e)}getMaxResolution(){return this.maxResolution_}getMinResolution(){return this.minResolution_}getMaxZoom(){return this.getZoomForResolution(this.minResolution_)}setMaxZoom(e){this.applyOptions_(this.getUpdatedOptions_({maxZoom:e}))}getMinZoom(){return this.getZoomForResolution(this.maxResolution_)}setMinZoom(e){this.applyOptions_(this.getUpdatedOptions_({minZoom:e}))}setConstrainResolution(e){this.applyOptions_(this.getUpdatedOptions_({constrainResolution:e}))}getProjection(){return this.projection_}getResolution(){return this.get(ViewProperty.RESOLUTION)}getResolutions(){return this.resolutions_}getResolutionForExtent(e,t){return this.getResolutionForExtentInternal(fromUserExtent(e,this.getProjection()),t)}getResolutionForExtentInternal(e,t){t=t||this.getViewportSizeMinusPadding_();const r=getWidth(e)/t[0],n=getHeight(e)/t[1];return Math.max(r,n)}getResolutionForValueFunction(e){e=e||2;const t=this.getConstrainedResolution(this.maxResolution_),r=this.minResolution_,n=Math.log(t/r)/Math.log(e);return function(r){return t/Math.pow(e,r*n)}}getRotation(){return this.get(ViewProperty.ROTATION)}getValueForResolutionFunction(e){const t=Math.log(e||2),r=this.getConstrainedResolution(this.maxResolution_),n=this.minResolution_,i=Math.log(r/n)/t;return function(e){return Math.log(r/e)/t/i}}getViewportSizeMinusPadding_(e){let t=this.getViewportSize_(e);const r=this.padding_;return r&&(t=[t[0]-r[1]-r[3],t[1]-r[0]-r[2]]),t}getState(){const e=this.getProjection(),t=this.getResolution(),r=this.getRotation();let n=this.getCenterInternal();const i=this.padding_;if(i){const e=this.getViewportSizeMinusPadding_();n=calculateCenterOn(n,this.getViewportSize_(),[e[0]/2+i[3],e[1]/2+i[0]],t,r)}return{center:n.slice(0),projection:void 0!==e?e:null,resolution:t,nextCenter:this.nextCenter_,nextResolution:this.nextResolution_,nextRotation:this.nextRotation_,rotation:r,zoom:this.getZoom()}}getViewStateAndExtent(){return{viewState:this.getState(),extent:this.calculateExtent()}}getZoom(){let e;const t=this.getResolution();return void 0!==t&&(e=this.getZoomForResolution(t)),e}getZoomForResolution(e){let t,r,n=this.minZoom_||0;if(this.resolutions_){const i=linearFindNearest(this.resolutions_,e,1);n=i,t=this.resolutions_[i],r=i==this.resolutions_.length-1?2:t/this.resolutions_[i+1]}else t=this.maxResolution_,r=this.zoomFactor_;return n+Math.log(t/e)/Math.log(r)}getResolutionForZoom(e){if(this.resolutions_?.length){if(1===this.resolutions_.length)return this.resolutions_[0];const t=clamp$1(Math.floor(e),0,this.resolutions_.length-2),r=this.resolutions_[t]/this.resolutions_[t+1];return this.resolutions_[t]/Math.pow(r,clamp$1(e-t,0,1))}return this.maxResolution_/Math.pow(this.zoomFactor_,e-this.minZoom_)}fit(e,t){let r;if(assert$1(Array.isArray(e)||"function"==typeof e.getSimplifiedGeometry,"Invalid extent or geometry provided as `geometry`"),Array.isArray(e))assert$1(!isEmpty(e),"Cannot fit empty extent provided as `geometry`"),r=fromExtent(fromUserExtent(e,this.getProjection()));else if("Circle"===e.getType()){const t=fromUserExtent(e.getExtent(),this.getProjection());r=fromExtent(t),r.rotate(this.getRotation(),getCenter(t))}else r=e;this.fitInternal(r,t)}rotatedExtentForGeometry(e){const t=this.getRotation(),r=Math.cos(t),n=Math.sin(-t),i=e.getFlatCoordinates(),o=e.getStride();let s=1/0,a=1/0,l=-1/0,c=-1/0;for(let u=0,h=i.length;ue.trim().replace(/^['"]|['"]$/g,"")),r};function createCanvasContext2D(e,t,r,n){let i;return i=r&&r.length?r.shift():WORKER_OFFSCREEN_CANVAS?new class extends OffscreenCanvas{style={}}(e??300,t??150):document.createElement("canvas"),e&&(i.width=e),t&&(i.height=t),i.getContext("2d",n)}let sharedCanvasContext;function getSharedCanvasContext2D(){return sharedCanvasContext||(sharedCanvasContext=createCanvasContext2D(1,1)),sharedCanvasContext}function releaseCanvas(e){const t=e.canvas;t.width=1,t.height=1,e.clearRect(0,0,1,1)}function outerWidth(e){let t=e.offsetWidth;const r=getComputedStyle(e);return t+=parseInt(r.marginLeft,10)+parseInt(r.marginRight,10),t}function outerHeight(e){let t=e.offsetHeight;const r=getComputedStyle(e);return t+=parseInt(r.marginTop,10)+parseInt(r.marginBottom,10),t}function replaceNode(e,t){const r=t.parentNode;r&&r.replaceChild(e,t)}function removeChildren(e){for(;e.lastChild;)e.lastChild.remove()}function replaceChildren(e,t){const r=e.childNodes;for(let n=0;;++n){const i=r[n],o=t[n];if(!i&&!o)break;i!==o&&(i?o?e.insertBefore(o,i):(e.removeChild(i),--n):e.appendChild(o))}}function createMockDiv(){const e=new Proxy({childNodes:[],appendChild:function(e){return this.childNodes.push(e),e},remove:function(){},removeChild:function(e){const t=this.childNodes.indexOf(e);if(-1===t)throw new Error("Node to remove was not found");return this.childNodes.splice(t,1),e},insertBefore:function(e,t){const r=this.childNodes.indexOf(t);if(-1===r)throw new Error("Reference node not found");return this.childNodes.splice(r,0,e),e},style:{}},{get:(e,t,r)=>"firstElementChild"===t?e.childNodes.length>0?e.childNodes[0]:null:Reflect.get(e,t,r)});return e}function isCanvas(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas}class Control extends BaseObject{constructor(e){super();const t=e.element;!t||e.target||t.style.pointerEvents||(t.style.pointerEvents="auto"),this.element=t||null,this.target_=null,this.map_=null,this.listenerKeys=[],e.render&&(this.render=e.render),e.target&&this.setTarget(e.target)}disposeInternal(){this.element?.remove(),super.disposeInternal()}getMap(){return this.map_}setMap(e){this.map_&&this.element?.remove();for(let t=0,r=this.listenerKeys.length;tt.getAttributions(e)));if(void 0!==this.attributions_&&(Array.isArray(this.attributions_)?this.attributions_.forEach(e=>r.add(e)):r.add(this.attributions_)),!this.overrideCollapsible_){const e=!t.some(e=>!1===e.getSource()?.getAttributionsCollapsible());this.setCollapsible(e)}return Array.from(r)}async updateElement_(e){if(!e)return void(this.renderedVisible_&&(this.element.style.display="none",this.renderedVisible_=!1));const t=await Promise.all(this.collectSourceAttributions_(e).map(e=>toPromise(()=>e))),r=t.length>0;if(this.renderedVisible_!=r&&(this.element.style.display=r?"":"none",this.renderedVisible_=r),!equals$2(t,this.renderedAttributions_)){removeChildren(this.ulElement_);for(let e=0,r=t.length;e0&&t%(2*Math.PI)!=0?e.animate({rotation:0,duration:this.duration_,easing:easeOut}):e.setRotation(0))}render(e){const t=e.frameState;if(!t)return;const r=t.viewState.rotation;if(r!=this.rotation_){const e="rotate("+r+"rad)";if(this.autoHide_){const e=this.element.classList.contains(CLASS_HIDDEN);e||0!==r?e&&0!==r&&this.element.classList.remove(CLASS_HIDDEN):this.element.classList.add(CLASS_HIDDEN)}this.label_.style.transform=e}this.rotation_=r}}class Zoom extends Control{constructor(e){e=e||{},super({element:document.createElement("div"),target:e.target});const t=void 0!==e.className?e.className:"ol-zoom",r=void 0!==e.delta?e.delta:1,n=void 0!==e.zoomInClassName?e.zoomInClassName:t+"-in",i=void 0!==e.zoomOutClassName?e.zoomOutClassName:t+"-out",o=void 0!==e.zoomInLabel?e.zoomInLabel:"+",s=void 0!==e.zoomOutLabel?e.zoomOutLabel:"–",a=void 0!==e.zoomInTipLabel?e.zoomInTipLabel:"Zoom in",l=void 0!==e.zoomOutTipLabel?e.zoomOutTipLabel:"Zoom out",c=document.createElement("button");c.className=n,c.setAttribute("type","button"),c.title=a,c.appendChild("string"==typeof o?document.createTextNode(o):o),c.addEventListener(EventType$1.CLICK,this.handleClick_.bind(this,r),!1);const u=document.createElement("button");u.className=i,u.setAttribute("type","button"),u.title=l,u.appendChild("string"==typeof s?document.createTextNode(s):s),u.addEventListener(EventType$1.CLICK,this.handleClick_.bind(this,-r),!1);const h=t+" "+CLASS_UNSELECTABLE+" "+CLASS_CONTROL,d=this.element;d.className=h,d.appendChild(c),d.appendChild(u),this.duration_=void 0!==e.duration?e.duration:250}handleClick_(e,t){t.preventDefault(),this.zoomByDelta_(e)}zoomByDelta_(e){const t=this.getMap().getView();if(!t)return;const r=t.getZoom();if(void 0!==r){const n=t.getConstrainedZoom(r+e);this.duration_>0?(t.getAnimating()&&t.cancelAnimations(),t.animate({zoom:n,duration:this.duration_,easing:easeOut})):t.setZoom(n)}}}function defaults$1(e){e=e||{};const t=new Collection;return(void 0===e.zoom||e.zoom)&&t.push(new Zoom(e.zoomOptions)),(void 0===e.rotate||e.rotate)&&t.push(new Rotate(e.rotateOptions)),(void 0===e.attribution||e.attribution)&&t.push(new Attribution(e.attributionOptions)),t}class Kinetic{constructor(e,t,r){this.decay_=e,this.minVelocity_=t,this.delay_=r,this.points_=[],this.angle_=0,this.initialVelocity_=0}begin(){this.points_.length=0,this.angle_=0,this.initialVelocity_=0}update(e,t){this.points_.push(e,t,Date.now())}end(){if(this.points_.length<6)return!1;const e=Date.now()-this.delay_,t=this.points_.length-3;if(this.points_[t+2]0&&this.points_[r+2]>e;)r-=3;const n=this.points_[t+2]-this.points_[r+2];if(n<1e3/60)return!1;const i=this.points_[t]-this.points_[r],o=this.points_[t+1]-this.points_[r+1];return this.angle_=Math.atan2(o,i),this.initialVelocity_=Math.sqrt(i*i+o*o)/n,this.initialVelocity_>this.minVelocity_}getDistance(){return(this.minVelocity_-this.initialVelocity_)/this.decay_}getAngle(){return this.angle_}}const InteractionProperty={ACTIVE:"active"};class Interaction extends BaseObject{constructor(e){super(),this.on,this.once,this.un,e&&e.handleEvent&&(this.handleEvent=e.handleEvent),this.map_=null,this.setActive(!0)}getActive(){return this.get(InteractionProperty.ACTIVE)}getMap(){return this.map_}handleEvent(e){return!0}setActive(e){this.set(InteractionProperty.ACTIVE,e)}setMap(e){this.map_=e}}function pan(e,t,r){const n=e.getCenterInternal();if(n){const i=[n[0]+t[0],n[1]+t[1]];e.animateInternal({duration:void 0!==r?r:250,easing:linear,center:e.getConstrainedCenter(i)})}}function zoomByDelta(e,t,r,n){const i=e.getZoom();if(void 0===i)return;const o=e.getConstrainedZoom(i+t),s=e.getResolutionForZoom(o);e.getAnimating()&&e.cancelAnimations(),e.animate({resolution:s,anchor:r,duration:void 0!==n?n:250,easing:easeOut})}class DoubleClickZoom extends Interaction{constructor(e){super(),e=e||{},this.delta_=e.delta?e.delta:1,this.duration_=void 0!==e.duration?e.duration:250}handleEvent(e){let t=!1;if(e.type==MapBrowserEventType.DBLCLICK){const r=e.originalEvent,n=e.map,i=e.coordinate,o=r.shiftKey?-this.delta_:this.delta_;zoomByDelta(n.getView(),o,i,this.duration_),r.preventDefault(),t=!0}return!t}}function all$1(e){const t=arguments;return function(e){let r=!0;for(let n=0,i=t.length;n0}}else if(e.type==MapBrowserEventType.POINTERDOWN){const r=this.handleDownEvent(e);this.handlingDownUpSequence=r,t=this.stopDown(r)}else e.type==MapBrowserEventType.POINTERMOVE&&this.handleMoveEvent(e);return!t}handleMoveEvent(e){}handleUpEvent(e){return!1}stopDown(e){return e}updateTrackedPointers_(e){e.activePointers&&(this.targetPointers=e.activePointers)}}function centroid(e){const t=e.length;let r=0,n=0;for(let i=0;i0&&this.condition_(e)){const t=e.map.getView();return this.lastCentroid=null,t.getAnimating()&&t.cancelAnimations(),this.kinetic_&&this.kinetic_.begin(),this.noKinetic_=this.targetPointers.length>1,!0}return!1}}class DragRotate extends PointerInteraction{constructor(e){e=e||{},super({stopDown:FALSE}),this.condition_=e.condition?e.condition:altShiftKeysOnly,this.lastAngle_=void 0,this.duration_=void 0!==e.duration?e.duration:250}handleDragEvent(e){if(!mouseOnly(e))return;const t=e.map,r=t.getView();if(r.getConstraints().rotation===disable)return;const n=t.getSize(),i=e.pixel,o=Math.atan2(n[1]/2-i[1],i[0]-n[0]/2);if(void 0!==this.lastAngle_){const e=o-this.lastAngle_;r.adjustRotationInternal(-e)}this.lastAngle_=o}handleUpEvent(e){return!mouseOnly(e)||(e.map.getView().endInteraction(this.duration_),!1)}handleDownEvent(e){return!(!mouseOnly(e)||!mouseActionButton(e)||!this.condition_(e)||(e.map.getView().beginInteraction(),this.lastAngle_=void 0,0))}}class RenderBox extends Disposable{constructor(e){super(),this.geometry_=null,this.element_=document.createElement("div"),this.element_.style.position="absolute",this.element_.style.pointerEvents="auto",this.element_.className="ol-box "+e,this.map_=null,this.startPixel_=null,this.endPixel_=null}disposeInternal(){this.setMap(null)}render_(){const e=this.startPixel_,t=this.endPixel_,r="px",n=this.element_.style;n.left=Math.min(e[0],t[0])+r,n.top=Math.min(e[1],t[1])+r,n.width=Math.abs(t[0]-e[0])+r,n.height=Math.abs(t[1]-e[1])+r}setMap(e){if(this.map_){this.map_.getOverlayContainer().removeChild(this.element_);const e=this.element_.style;e.left="inherit",e.top="inherit",e.width="inherit",e.height="inherit"}this.map_=e,this.map_&&this.map_.getOverlayContainer().appendChild(this.element_)}setPixels(e,t){this.startPixel_=e,this.endPixel_=t,this.createOrUpdateGeometry(),this.render_()}createOrUpdateGeometry(){if(!this.map_)return;const e=this.startPixel_,t=this.endPixel_,r=[e,[e[0],t[1]],t,[t[0],e[1]]].map(this.map_.getCoordinateFromPixelInternal,this.map_);r[4]=r[0].slice(),this.geometry_?this.geometry_.setCoordinates([r]):this.geometry_=new Polygon([r])}getGeometry(){return this.geometry_}}const DragBoxEventType={BOXSTART:"boxstart",BOXDRAG:"boxdrag",BOXEND:"boxend",BOXCANCEL:"boxcancel"};class DragBoxEvent extends BaseEvent{constructor(e,t,r){super(e),this.coordinate=t,this.mapBrowserEvent=r}}class DragBox extends PointerInteraction{constructor(e){super(),this.on,this.once,this.un,e=e??{},this.box_=new RenderBox(e.className||"ol-dragbox"),this.minArea_=e.minArea??64,e.onBoxEnd&&(this.onBoxEnd=e.onBoxEnd),this.startPixel_=null,this.condition_=e.condition??mouseActionButton,this.boxEndCondition_=e.boxEndCondition??this.defaultBoxEndCondition}defaultBoxEndCondition(e,t,r){const n=r[0]-t[0],i=r[1]-t[1];return n*n+i*i>=this.minArea_}getGeometry(){return this.box_.getGeometry()}handleDragEvent(e){this.startPixel_&&(this.box_.setPixels(this.startPixel_,e.pixel),this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXDRAG,e.coordinate,e)))}handleUpEvent(e){if(!this.startPixel_)return!1;const t=this.boxEndCondition_(e,this.startPixel_,e.pixel);return t&&this.onBoxEnd(e),this.dispatchEvent(new DragBoxEvent(t?DragBoxEventType.BOXEND:DragBoxEventType.BOXCANCEL,e.coordinate,e)),this.box_.setMap(null),this.startPixel_=null,!1}handleDownEvent(e){return!!this.condition_(e)&&(this.startPixel_=e.pixel,this.box_.setMap(e.map),this.box_.setPixels(this.startPixel_,this.startPixel_),this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXSTART,e.coordinate,e)),!0)}onBoxEnd(e){}setActive(e){e||(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXCANCEL,this.startPixel_,null)),this.startPixel_=null)),super.setActive(e)}setMap(e){this.getMap()&&(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXCANCEL,this.startPixel_,null)),this.startPixel_=null)),super.setMap(e)}}class DragZoom extends DragBox{constructor(e){super({condition:(e=e||{}).condition?e.condition:shiftKeyOnly,className:e.className||"ol-dragzoom",minArea:e.minArea}),this.duration_=void 0!==e.duration?e.duration:200,this.out_=void 0!==e.out&&e.out}onBoxEnd(e){const t=this.getMap().getView();let r=this.getGeometry();if(this.out_){const e=t.rotatedExtentForGeometry(r),n=t.getResolutionForExtentInternal(e),i=t.getResolution()/n;r=r.clone(),r.scale(i*i)}t.fitInternal(r,{duration:this.duration_,easing:easeOut})}}const Key={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",DOWN:"ArrowDown"};class KeyboardPan extends Interaction{constructor(e){super(),e=e||{},this.defaultCondition_=function(e){return noModifierKeys(e)&&targetNotEditable(e)},this.condition_=void 0!==e.condition?e.condition:this.defaultCondition_,this.duration_=void 0!==e.duration?e.duration:100,this.pixelDelta_=void 0!==e.pixelDelta?e.pixelDelta:128}handleEvent(e){let t=!1;if(e.type==EventType$1.KEYDOWN){const r=e.originalEvent,n=r.key;if(this.condition_(e)&&(n==Key.DOWN||n==Key.LEFT||n==Key.RIGHT||n==Key.UP)){const i=e.map.getView(),o=i.getResolution()*this.pixelDelta_;let s=0,a=0;n==Key.DOWN?a=-o:n==Key.LEFT?s=-o:n==Key.RIGHT?s=o:a=o;const l=[s,a];rotate$1(l,i.getRotation()),pan(i,l,this.duration_),r.preventDefault(),t=!0}}return!t}}class KeyboardZoom extends Interaction{constructor(e){super(),e=e||{},this.condition_=e.condition?e.condition:function(e){return!platformModifierKey(e)&&targetNotEditable(e)},this.delta_=e.delta?e.delta:1,this.duration_=void 0!==e.duration?e.duration:100}handleEvent(e){let t=!1;if(e.type==EventType$1.KEYDOWN||e.type==EventType$1.KEYPRESS){const r=e.originalEvent,n=r.key;if(this.condition_(e)&&("+"===n||"-"===n)){const i=e.map,o="+"===n?this.delta_:-this.delta_;zoomByDelta(i.getView(),o,void 0,this.duration_),r.preventDefault(),t=!0}}return!t}}const DELTA_LINE_MULTIPLIER=40,DELTA_PAGE_MULTIPLIER=300;class MouseWheelZoom extends Interaction{constructor(e){super(e=e||{}),this.totalDelta_=0,this.lastDelta_=0,this.maxDelta_=void 0!==e.maxDelta?e.maxDelta:1,this.duration_=void 0!==e.duration?e.duration:250,this.timeout_=void 0!==e.timeout?e.timeout:80,this.useAnchor_=void 0===e.useAnchor||e.useAnchor,this.constrainResolution_=void 0!==e.constrainResolution&&e.constrainResolution;const t=e.condition?e.condition:always$1;this.condition_=e.onFocusOnly?all$1(focusWithTabindex,t):t,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_,this.mode_=void 0,this.trackpadEventGap_=400,this.trackpadTimeoutId_,this.deltaPerZoom_=300}endInteraction_(){this.trackpadTimeoutId_=void 0;const e=this.getMap();e&&e.getView().endInteraction(void 0,this.lastDelta_?this.lastDelta_>0?1:-1:0,this.lastAnchor_?e.getCoordinateFromPixel(this.lastAnchor_):null)}handleEvent(e){if(!this.condition_(e))return!0;if(e.type!==EventType$1.WHEEL)return!0;const t=e.map,r=e.originalEvent;r.preventDefault(),this.useAnchor_&&(this.lastAnchor_=e.pixel);let n=r.deltaY;switch(r.deltaMode){case WheelEvent.DOM_DELTA_LINE:n*=DELTA_LINE_MULTIPLIER;break;case WheelEvent.DOM_DELTA_PAGE:n*=DELTA_PAGE_MULTIPLIER}if(0===n)return!1;this.lastDelta_=n;const i=Date.now();void 0===this.startTime_&&(this.startTime_=i),(!this.mode_||i-this.startTime_>this.trackpadEventGap_)&&(this.mode_=Math.abs(n)<4?"trackpad":"wheel");const o=t.getView();if("trackpad"===this.mode_&&!o.getConstrainResolution()&&!this.constrainResolution_)return this.trackpadTimeoutId_?clearTimeout(this.trackpadTimeoutId_):(o.getAnimating()&&o.cancelAnimations(),o.beginInteraction()),this.trackpadTimeoutId_=setTimeout(this.endInteraction_.bind(this),this.timeout_),o.adjustZoom(-n/this.deltaPerZoom_,this.lastAnchor_?t.getCoordinateFromPixel(this.lastAnchor_):null),this.startTime_=i,!1;this.totalDelta_+=n;const s=Math.max(this.timeout_-(i-this.startTime_),0);return clearTimeout(this.timeoutId_),this.timeoutId_=setTimeout(this.handleWheelZoom_.bind(this,t),s),!1}handleWheelZoom_(e){const t=e.getView();t.getAnimating()&&t.cancelAnimations();let r=-clamp$1(this.totalDelta_,-this.maxDelta_*this.deltaPerZoom_,this.maxDelta_*this.deltaPerZoom_)/this.deltaPerZoom_;(t.getConstrainResolution()||this.constrainResolution_)&&(r=r?r>0?1:-1:0),zoomByDelta(t,r,this.lastAnchor_?e.getCoordinateFromPixel(this.lastAnchor_):null,this.duration_),this.mode_=void 0,this.totalDelta_=0,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_=void 0}setMouseAnchor(e){this.useAnchor_=e,e||(this.lastAnchor_=null)}}class PinchRotate extends PointerInteraction{constructor(e){const t=e=e||{};t.stopDown||(t.stopDown=FALSE),super(t),this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.threshold_=void 0!==e.threshold?e.threshold:.3,this.duration_=void 0!==e.duration?e.duration:250}handleDragEvent(e){let t=0;const r=this.targetPointers[0],n=this.targetPointers[1],i=Math.atan2(n.clientY-r.clientY,n.clientX-r.clientX);if(void 0!==this.lastAngle_){const e=i-this.lastAngle_;this.rotationDelta_+=e,!this.rotating_&&Math.abs(this.rotationDelta_)>this.threshold_&&(this.rotating_=!0),t=e}this.lastAngle_=i;const o=e.map,s=o.getView();s.getConstraints().rotation!==disable&&(this.anchor_=o.getCoordinateFromPixelInternal(o.getEventPixel(centroid(this.targetPointers))),this.rotating_&&(o.render(),s.adjustRotationInternal(t,this.anchor_)))}handleUpEvent(e){return!(this.targetPointers.length<2&&(e.map.getView().endInteraction(this.duration_),1))}handleDownEvent(e){if(this.targetPointers.length>=2){const t=e.map;return this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.handlingDownUpSequence||t.getView().beginInteraction(),!0}return!1}}class PinchZoom extends PointerInteraction{constructor(e){const t=e=e||{};t.stopDown||(t.stopDown=FALSE),super(t),this.anchor_=null,this.duration_=void 0!==e.duration?e.duration:400,this.lastDistance_=void 0,this.lastScaleDelta_=1}handleDragEvent(e){let t=1;const r=this.targetPointers[0],n=this.targetPointers[1],i=r.clientX-n.clientX,o=r.clientY-n.clientY,s=Math.sqrt(i*i+o*o);void 0!==this.lastDistance_&&(t=this.lastDistance_/s),this.lastDistance_=s;const a=e.map,l=a.getView();1!=t&&(this.lastScaleDelta_=t),this.anchor_=a.getCoordinateFromPixelInternal(a.getEventPixel(centroid(this.targetPointers))),a.render(),l.adjustResolutionInternal(t,this.anchor_)}handleUpEvent(e){if(this.targetPointers.length<2){const t=e.map.getView(),r=this.lastScaleDelta_>1?1:-1;return t.endInteraction(this.duration_,r),!1}return!0}handleDownEvent(e){if(this.targetPointers.length>=2){const t=e.map;return this.anchor_=null,this.lastDistance_=void 0,this.lastScaleDelta_=1,this.handlingDownUpSequence||t.getView().beginInteraction(),!0}return!1}}function defaults(e){e=e||{};const t=new Collection,r=new Kinetic(-.005,.05,100);return(void 0===e.altShiftDragRotate||e.altShiftDragRotate)&&t.push(new DragRotate),(void 0===e.doubleClickZoom||e.doubleClickZoom)&&t.push(new DoubleClickZoom({delta:e.zoomDelta,duration:e.zoomDuration})),(void 0===e.dragPan||e.dragPan)&&t.push(new DragPan({onFocusOnly:e.onFocusOnly,kinetic:r})),(void 0===e.pinchRotate||e.pinchRotate)&&t.push(new PinchRotate),(void 0===e.pinchZoom||e.pinchZoom)&&t.push(new PinchZoom({duration:e.zoomDuration})),(void 0===e.keyboard||e.keyboard)&&(t.push(new KeyboardPan),t.push(new KeyboardZoom({delta:e.zoomDelta,duration:e.zoomDuration}))),(void 0===e.mouseWheelZoom||e.mouseWheelZoom)&&t.push(new MouseWheelZoom({onFocusOnly:e.onFocusOnly,duration:e.zoomDuration})),(void 0===e.shiftDragZoom||e.shiftDragZoom)&&t.push(new DragZoom({duration:e.zoomDuration})),t}const LayerProperty={OPACITY:"opacity",VISIBLE:"visible",EXTENT:"extent",Z_INDEX:"zIndex",MAX_RESOLUTION:"maxResolution",MIN_RESOLUTION:"minResolution",MAX_ZOOM:"maxZoom",MIN_ZOOM:"minZoom",SOURCE:"source",MAP:"map"};class BaseLayer extends BaseObject{constructor(e){super(),this.on,this.once,this.un,this.background_=e.background;const t=Object.assign({},e);"object"==typeof e.properties&&(delete t.properties,Object.assign(t,e.properties)),t[LayerProperty.OPACITY]=void 0!==e.opacity?e.opacity:1,assert$1("number"==typeof t[LayerProperty.OPACITY],"Layer opacity must be a number"),t[LayerProperty.VISIBLE]=void 0===e.visible||e.visible,t[LayerProperty.Z_INDEX]=e.zIndex,t[LayerProperty.MAX_RESOLUTION]=void 0!==e.maxResolution?e.maxResolution:1/0,t[LayerProperty.MIN_RESOLUTION]=void 0!==e.minResolution?e.minResolution:0,t[LayerProperty.MIN_ZOOM]=void 0!==e.minZoom?e.minZoom:-1/0,t[LayerProperty.MAX_ZOOM]=void 0!==e.maxZoom?e.maxZoom:1/0,this.className_=void 0!==t.className?t.className:"ol-layer",delete t.className,this.setProperties(t),this.state_=null}getBackground(){return this.background_}getClassName(){return this.className_}getLayerState(e){const t=this.state_||{layer:this,managed:void 0===e||e},r=this.getZIndex();return t.opacity=clamp$1(Math.round(100*this.getOpacity())/100,0,1),t.visible=this.getVisible(),t.extent=this.getExtent(),t.zIndex=void 0!==r||t.managed?r:1/0,t.maxResolution=this.getMaxResolution(),t.minResolution=Math.max(this.getMinResolution(),0),t.minZoom=this.getMinZoom(),t.maxZoom=this.getMaxZoom(),this.state_=t,t}getLayersArray(e){return abstract()}getLayerStatesArray(e){return abstract()}getExtent(){return this.get(LayerProperty.EXTENT)}getMaxResolution(){return this.get(LayerProperty.MAX_RESOLUTION)}getMinResolution(){return this.get(LayerProperty.MIN_RESOLUTION)}getMinZoom(){return this.get(LayerProperty.MIN_ZOOM)}getMaxZoom(){return this.get(LayerProperty.MAX_ZOOM)}getOpacity(){return this.get(LayerProperty.OPACITY)}getSourceState(){return abstract()}getVisible(){return this.get(LayerProperty.VISIBLE)}getZIndex(){return this.get(LayerProperty.Z_INDEX)}setBackground(e){this.background_=e,this.changed()}setExtent(e){this.set(LayerProperty.EXTENT,e)}setMaxResolution(e){this.set(LayerProperty.MAX_RESOLUTION,e)}setMinResolution(e){this.set(LayerProperty.MIN_RESOLUTION,e)}setMaxZoom(e){this.set(LayerProperty.MAX_ZOOM,e)}setMinZoom(e){this.set(LayerProperty.MIN_ZOOM,e)}setOpacity(e){assert$1("number"==typeof e,"Layer opacity must be a number"),this.set(LayerProperty.OPACITY,e)}setVisible(e){this.set(LayerProperty.VISIBLE,e)}setZIndex(e){this.set(LayerProperty.Z_INDEX,e)}disposeInternal(){this.state_&&(this.state_.layer=null,this.state_=null),super.disposeInternal()}}const GroupEventType={ADDLAYER:"addlayer",REMOVELAYER:"removelayer"};class GroupEvent extends BaseEvent{constructor(e,t){super(e),this.layer=t}}const Property$3={LAYERS:"layers"};class LayerGroup extends BaseLayer{constructor(e){e=e||{};const t=Object.assign({},e);delete t.layers;let r=e.layers;super(t),this.on,this.once,this.un,this.layersListenerKeys_=[],this.listenerKeys_={},this.addChangeListener(Property$3.LAYERS,this.handleLayersChanged_),r?Array.isArray(r)?r=new Collection(r.slice(),{unique:!0}):assert$1("function"==typeof r.getArray,"Expected `layers` to be an array or a `Collection`"):r=new Collection(void 0,{unique:!0}),this.setLayers(r)}handleLayerChange_(){this.changed()}handleLayersChanged_(){this.layersListenerKeys_.forEach(unlistenByKey),this.layersListenerKeys_.length=0;const e=this.getLayers();this.layersListenerKeys_.push(listen(e,CollectionEventType.ADD,this.handleLayersAdd_,this),listen(e,CollectionEventType.REMOVE,this.handleLayersRemove_,this));for(const r in this.listenerKeys_)this.listenerKeys_[r].forEach(unlistenByKey);clear(this.listenerKeys_);const t=e.getArray();for(let r=0,n=t.length;r{this.dispatchEvent("sourceready")},0))),this.changed()}getFeatures(e){return this.renderer_?this.renderer_.getFeatures(e):Promise.resolve([])}getData(e){return this.renderer_&&this.rendered?this.renderer_.getData(e):null}isVisible(e){let t;const r=this.getMapInternal();let n;if(!e&&r&&(e=r.getView()),t=e instanceof View?{viewState:e.getState(),extent:e.calculateExtent()}:e,!t.layerStatesArray&&r&&(t.layerStatesArray=r.getLayerGroup().getLayerStatesArray()),t.layerStatesArray){if(n=t.layerStatesArray.find(e=>e.layer===this),!n)return!1}else n=this.getLayerState();const i=this.getExtent();return inView(n,t.viewState)&&(!i||intersects$1(i,t.extent))}getAttributions(e){if(!this.isVisible(e))return[];const t=this.getSource()?.getAttributions();if(!t)return[];let r=t(e instanceof View?e.getViewStateAndExtent():e);return Array.isArray(r)||(r=[r]),r}render(e,t){const r=this.getRenderer();return r.prepareFrame(e)?(this.rendered=!0,r.renderFrame(e,t)):null}unrender(){this.rendered=!1}getDeclutter(){}renderDeclutter(e,t){}renderDeferred(e){const t=this.getRenderer();t&&t.renderDeferred(e)}setMapInternal(e){e||this.unrender(),this.set(LayerProperty.MAP,e)}getMapInternal(){return this.get(LayerProperty.MAP)}setMap(e){this.mapPrecomposeKey_&&(unlistenByKey(this.mapPrecomposeKey_),this.mapPrecomposeKey_=null),e||this.changed(),this.mapRenderKey_&&(unlistenByKey(this.mapRenderKey_),this.mapRenderKey_=null),e&&(this.mapPrecomposeKey_=listen(e,EventType.PRECOMPOSE,this.handlePrecompose_,this),this.mapRenderKey_=listen(this,EventType$1.CHANGE,e.render,e),this.changed())}handlePrecompose_(e){const t=e.frameState.layerStatesArray,r=this.getLayerState(!1);assert$1(!t.some(e=>e.layer===r.layer),"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both."),t.push(r)}setSource(e){this.set(LayerProperty.SOURCE,e)}getRenderer(){return this.renderer_||(this.renderer_=this.createRenderer()),this.renderer_}hasRenderer(){return!!this.renderer_}createRenderer(){return null}clearRenderer(){this.renderer_&&(this.renderer_.dispose(),delete this.renderer_)}disposeInternal(){this.clearRenderer(),this.setSource(null),super.disposeInternal()}}function inView(e,t){if(!e.visible)return!1;const r=t.resolution;if(r=e.maxResolution)return!1;const n=t.zoom;return n>e.minZoom&&n<=e.maxZoom}function quickselect(e,t,r=0,n=e.length-1,i=defaultCompare){for(;n>r;){if(n-r>600){const o=n-r+1,s=t-r+1,a=Math.log(o),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(o-l)/o)*(s-o/2<0?-1:1);quickselect(e,t,Math.max(r,Math.floor(t-s*l/o+c)),Math.min(n,Math.floor(t+(o-s)*l/o+c)),i)}const o=e[t];let s=r,a=n;for(swap(e,r,t),i(e[n],o)>0&&swap(e,r,n);s0;)a--}0===i(e[r],o)?swap(e,r,a):(a++,swap(e,a,n)),a<=t&&(r=a+1),t<=a&&(n=a-1)}}function swap(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function defaultCompare(e,t){return et?1:0}let RBush$1=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!intersects(e,t))return r;const n=this.toBBox,i=[];for(;t;){for(let o=0;o=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(n,i,t)}_split(e,t){const r=e[t],n=r.children.length,i=this._minEntries;this._chooseSplitAxis(r,i,n);const o=this._chooseSplitIndex(r,i,n),s=createNode(r.children.splice(o,r.children.length-o));s.height=r.height,s.leaf=r.leaf,calcBBox(r,this.toBBox),calcBBox(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(r,s)}_splitRoot(e,t){this.data=createNode([e,t]),this.data.height=e.height+1,this.data.leaf=!1,calcBBox(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let n,i=1/0,o=1/0;for(let s=t;s<=r-t;s++){const t=distBBox(e,0,s,this.toBBox),a=distBBox(e,s,r,this.toBBox),l=intersectionArea(t,a),c=bboxArea(t)+bboxArea(a);l=t;l--){const t=e.children[l];extend(s,e.leaf?i(t):t),a+=bboxMargin(s)}return a}_adjustParentBBoxes(e,t,r){for(let n=r;n>=0;n--)extend(t[n],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():calcBBox(e[r],this.toBBox)}};function findItem(e,t,r){if(!r)return t.indexOf(e);for(let n=0;n=e.minX&&t.maxY>=e.minY}function createNode(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function multiSelect(e,t,r,n,i){const o=[t,r];for(;o.length;){if((r=o.pop())-(t=o.pop())<=n)continue;const s=t+Math.ceil((r-t)/n/2)*n;quickselect(e,s,t,r,i),o.push(t,s,s,r)}}const NO_COLOR=[NaN,NaN,NaN,0];let colorParseContext;function getColorParseContext(){return colorParseContext||(colorParseContext=createCanvasContext2D(1,1,void 0,{willReadFrequently:!0,desynchronized:!0})),colorParseContext}const rgbModernRegEx=/^rgba?\(\s*(\d+%?)\s+(\d+%?)\s+(\d+%?)(?:\s*\/\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,rgbLegacyAbsoluteRegEx=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,rgbLegacyPercentageRegEx=/^rgba?\(\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(\d+%)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,hexRegEx=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i;function toColorComponent(e,t){return e.endsWith("%")?Number(e.substring(0,e.length-1))/t:Number(e)}function throwInvalidColor(e){throw new Error('failed to parse "'+e+'" as color')}function parseRgba(e){if(e.toLowerCase().startsWith("rgb")){const t=e.match(rgbLegacyAbsoluteRegEx)||e.match(rgbModernRegEx)||e.match(rgbLegacyPercentageRegEx);if(t){const e=t[4],r=100/255;return[clamp$1(toColorComponent(t[1],r)+.5|0,0,255),clamp$1(toColorComponent(t[2],r)+.5|0,0,255),clamp$1(toColorComponent(t[3],r)+.5|0,0,255),void 0!==e?clamp$1(toColorComponent(e,100),0,1):1]}throwInvalidColor(e)}if(e.startsWith("#")){if(hexRegEx.test(e)){const t=e.substring(1),r=t.length<=4?1:2,n=[0,0,0,255];for(let e=0,i=t.length;e.0031308?269.025*Math.pow(e,1/2.4)-14.025:3294.6*e}function b2(e){return e>.2068965?Math.pow(e,3):108/841*(e-4/29)}function a1(e){return e>10.314724?Math.pow((e+14.025)/269.025,2.4):e/3294.6}function a2(e){return e>.0088564?Math.pow(e,1/3):e/(108/841)+4/29}function rgbaToLcha(e){const t=a1(e[0]),r=a1(e[1]),n=a1(e[2]),i=a2(.222488403*t+.716873169*r+.06060791*n),o=500*(a2(.452247074*t+.399439023*r+.148375274*n)-i),s=200*(i-a2(.016863605*t+.117638439*r+.865350722*n)),a=Math.atan2(s,o)*(180/Math.PI);return[116*i-16,Math.sqrt(o*o+s*s),a<0?a+360:a,e[3]]}function lchaToRgba(e){const t=(e[0]+16)/116,r=e[1],n=e[2]*Math.PI/180,i=b2(t),o=b2(t+r/500*Math.cos(n)),s=b2(t-r/200*Math.sin(n)),a=b1(3.021973625*o-1.617392459*i-.404875592*s),l=b1(-.943766287*o+1.916279586*i+.027607165*s),c=b1(.069407491*o-.22898585*i+1.159737864*s);return[clamp$1(a+.5|0,0,255),clamp$1(l+.5|0,0,255),clamp$1(c+.5|0,0,255),e[3]]}function fromString(e){if("none"===e)return NO_COLOR;if(cache.hasOwnProperty(e))return cache[e];if(cacheSize>=MAX_CACHE_SIZE){let e=0;for(const t in cache)3&e++||(delete cache[t],--cacheSize)}const t=parseRgba(e);4!==t.length&&throwInvalidColor(e);for(const r of t)isNaN(r)&&throwInvalidColor(e);return cache[e]=t,++cacheSize,t}function asArray(e){return Array.isArray(e)?e:fromString(e)}function toString(e){let t=e[0];t!=(0|t)&&(t=t+.5|0);let r=e[1];r!=(0|r)&&(r=r+.5|0);let n=e[2];return n!=(0|n)&&(n=n+.5|0),"rgba("+t+","+r+","+n+","+(void 0===e[3]?1:Math.round(1e3*e[3])/1e3)+")"}function hasArea(e){return e[0]>0&&e[1]>0}function scale(e,t,r){return void 0===r&&(r=[0,0]),r[0]=e[0]*t+.5|0,r[1]=e[1]*t+.5|0,r}function toSize(e,t){return Array.isArray(e)?e:(void 0===t?t=[e,e]:(t[0]=e,t[1]=e),t)}let numTypes=0;const BooleanType$1=1<",GreaterThanOrEqualTo:">=",LessThan:"<",LessThanOrEqualTo:"<=",Multiply:"*",Divide:"/",Add:"+",Subtract:"-",Clamp:"clamp",Mod:"%",Pow:"^",Abs:"abs",Floor:"floor",Ceil:"ceil",Round:"round",Sin:"sin",Cos:"cos",Atan:"atan",Sqrt:"sqrt",Match:"match",Between:"between",Interpolate:"interpolate",Coalesce:"coalesce",Case:"case",In:"in",Number:"number",String:"string",Array:"array",Color:"color",Id:"id",Band:"band",Palette:"palette",ToString:"to-string",Has:"has"},parsers={[Ops.Get]:createCallExpressionParser(hasArgsCount(1,1/0),withGetArgs),[Ops.Var]:createCallExpressionParser(hasArgsCount(1,1),withVarArgs),[Ops.Has]:createCallExpressionParser(hasArgsCount(1,1/0),withGetArgs),[Ops.Id]:createCallExpressionParser(usesFeatureId,withNoArgs),[Ops.Concat]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(StringType$1)),[Ops.GeometryType]:createCallExpressionParser(usesGeometryType,withNoArgs),[Ops.LineMetric]:createCallExpressionParser(withNoArgs),[Ops.Resolution]:createCallExpressionParser(usesMapState,withNoArgs),[Ops.Zoom]:createCallExpressionParser(usesMapState,withNoArgs),[Ops.Time]:createCallExpressionParser(usesMapState,withNoArgs),[Ops.Any]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(BooleanType$1)),[Ops.All]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(BooleanType$1)),[Ops.Not]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(BooleanType$1)),[Ops.Equal]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(AnyType)),[Ops.NotEqual]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(AnyType)),[Ops.GreaterThan]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.GreaterThanOrEqualTo]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.LessThan]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.LessThanOrEqualTo]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Multiply]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfReturnType),[Ops.Coalesce]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfReturnType),[Ops.Divide]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Add]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(NumberType$1)),[Ops.Subtract]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Clamp]:createCallExpressionParser(hasArgsCount(3,3),withArgsOfType(NumberType$1)),[Ops.Mod]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Pow]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Abs]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Floor]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Ceil]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Round]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Sin]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Cos]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Atan]:createCallExpressionParser(hasArgsCount(1,2),withArgsOfType(NumberType$1)),[Ops.Sqrt]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Match]:createCallExpressionParser(hasArgsCount(4,1/0),hasEvenArgs,withMatchArgs),[Ops.Between]:createCallExpressionParser(hasArgsCount(3,3),withArgsOfType(NumberType$1)),[Ops.Interpolate]:createCallExpressionParser(hasArgsCount(6,1/0),hasEvenArgs,withInterpolateArgs),[Ops.Case]:createCallExpressionParser(hasArgsCount(3,1/0),hasOddArgs,withCaseArgs),[Ops.In]:createCallExpressionParser(hasArgsCount(2,2),withInArgs),[Ops.Number]:createCallExpressionParser(hasArgsCount(1,1/0),withArgsOfType(AnyType)),[Ops.String]:createCallExpressionParser(hasArgsCount(1,1/0),withArgsOfType(AnyType)),[Ops.Array]:createCallExpressionParser(hasArgsCount(1,1/0),withArgsOfType(NumberType$1)),[Ops.Color]:createCallExpressionParser(hasArgsCount(1,4),withArgsOfType(NumberType$1)),[Ops.Band]:createCallExpressionParser(hasArgsCount(1,3),withArgsOfType(NumberType$1)),[Ops.Palette]:createCallExpressionParser(hasArgsCount(2,2),withPaletteArgs),[Ops.ToString]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(BooleanType$1|NumberType$1|StringType$1|ColorType$1))};function withGetArgs(e,t,r){const n=e.length-1,i=new Array(n);for(let o=0;ot)throw new Error(`expected ${t===1/0?`${e} or more`:`${e} to ${t}`} arguments for ${n}, got ${i}`)}}function withArgsOfReturnType(e,t,r){const n=e.length-1,i=new Array(n);for(let o=0;oe.featureId;case Ops.GeometryType:return e=>e.geometryType;case Ops.Concat:{const t=e.args.map(e=>compileExpression(e));return e=>"".concat(...t.map(t=>t(e).toString()))}case Ops.Resolution:return e=>e.resolution;case Ops.Any:case Ops.All:case Ops.Between:case Ops.In:case Ops.Not:return compileLogicalExpression(e);case Ops.Equal:case Ops.NotEqual:case Ops.LessThan:case Ops.LessThanOrEqualTo:case Ops.GreaterThan:case Ops.GreaterThanOrEqualTo:return compileComparisonExpression(e);case Ops.Multiply:case Ops.Divide:case Ops.Add:case Ops.Subtract:case Ops.Clamp:case Ops.Mod:case Ops.Pow:case Ops.Abs:case Ops.Floor:case Ops.Ceil:case Ops.Round:case Ops.Sin:case Ops.Cos:case Ops.Atan:case Ops.Sqrt:return compileNumericExpression(e);case Ops.Case:return compileCaseExpression(e);case Ops.Match:return compileMatchExpression(e);case Ops.Interpolate:return compileInterpolateExpression(e);case Ops.ToString:return compileConvertExpression(e);default:throw new Error(`Unsupported operator ${t}`)}}function compileAssertionExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{for(let t=0;t{for(let i=0;i{const n=e.args;let i=r.properties[t];for(let e=1,t=n.length;ee.variables[t];case Ops.Has:return r=>{const n=e.args;if(!(t in r.properties))return!1;let i=r.properties[t];for(let e=1,t=n.length;er(e)===n(e);case Ops.NotEqual:return e=>r(e)!==n(e);case Ops.LessThan:return e=>r(e)r(e)<=n(e);case Ops.GreaterThan:return e=>r(e)>n(e);case Ops.GreaterThanOrEqualTo:return e=>r(e)>=n(e);default:throw new Error(`Unsupported comparison operator ${t}`)}}function compileLogicalExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{for(let t=0;t{for(let t=0;t{const t=n[0](e),r=n[1](e),i=n[2](e);return t>=r&&t<=i};case Ops.In:return e=>{const t=n[0](e);for(let i=1;i!n[0](e);default:throw new Error(`Unsupported logical operator ${t}`)}}function compileNumericExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{let t=1;for(let i=0;in[0](e)/n[1](e);case Ops.Add:return e=>{let t=0;for(let i=0;in[0](e)-n[1](e);case Ops.Clamp:return e=>{const t=n[0](e),r=n[1](e);if(ti?i:t};case Ops.Mod:return e=>n[0](e)%n[1](e);case Ops.Pow:return e=>Math.pow(n[0](e),n[1](e));case Ops.Abs:return e=>Math.abs(n[0](e));case Ops.Floor:return e=>Math.floor(n[0](e));case Ops.Ceil:return e=>Math.ceil(n[0](e));case Ops.Round:return e=>Math.round(n[0](e));case Ops.Sin:return e=>Math.sin(n[0](e));case Ops.Cos:return e=>Math.cos(n[0](e));case Ops.Atan:return 2===r?e=>Math.atan2(n[0](e),n[1](e)):e=>Math.atan(n[0](e));case Ops.Sqrt:return e=>Math.sqrt(n[0](e));default:throw new Error(`Unsupported numeric operator ${t}`)}}function compileCaseExpression(e){const t=e.args.length,r=new Array(t);for(let n=0;n{for(let n=0;n{const n=r[0](e);for(let i=1;i{const n=r[0](e),i=r[1](e);let o,s;for(let a=2;a=i)return 2===a?l:c?interpolateColor(n,i,o,s,t,l):interpolateNumber$1(n,i,o,s,t,l);o=t,s=l}return s}}function compileConvertExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{const r=n[0](t);return e.args[0].type===ColorType$1?toString(r):r.toString()};throw new Error(`Unsupported convert operator ${t}`)}function interpolateNumber$1(e,t,r,n,i,o){const s=i-r;if(0===s)return n;const a=t-r;return n+(1===e?a/s:(Math.pow(e,a)-1)/(Math.pow(e,s)-1))*(o-n)}function interpolateColor(e,t,r,n,i,o){if(0===i-r)return n;const s=rgbaToLcha(n),a=rgbaToLcha(o);let l=a[2]-s[2];return l>180?l-=360:l<-180&&(l+=360),lchaToRgba([interpolateNumber$1(e,t,r,s[0],i,a[0]),interpolateNumber$1(e,t,r,s[1],i,a[1]),s[2]+interpolateNumber$1(e,t,r,0,i,l),interpolateNumber$1(e,t,r,n[3],i,o[3])])}const ImageState={IDLE:0,LOADING:1,LOADED:2,ERROR:3,EMPTY:4};class ImageWrapper extends Target{constructor(e,t,r,n){super(),this.extent=e,this.pixelRatio_=r,this.resolution=t,this.state="function"==typeof n?ImageState.IDLE:n,this.image_=null,this.loader="function"==typeof n?n:null}changed(){this.dispatchEvent(EventType$1.CHANGE)}getExtent(){return this.extent}getImage(){return this.image_}getPixelRatio(){return this.pixelRatio_}getResolution(){return this.resolution}getState(){return this.state}load(){if(this.state==ImageState.IDLE&&this.loader){this.state=ImageState.LOADING,this.changed();const e=this.getResolution(),t=Array.isArray(e)?e[0]:e;toPromise(()=>this.loader(this.getExtent(),t,this.getPixelRatio())).then(e=>{"image"in e&&(this.image_=e.image),"extent"in e&&(this.extent=e.extent),"resolution"in e&&(this.resolution=e.resolution),"pixelRatio"in e&&(this.pixelRatio_=e.pixelRatio),(e instanceof HTMLImageElement||CREATE_IMAGE_BITMAP&&e instanceof ImageBitmap||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement)&&(this.image_=e),this.state=ImageState.LOADED}).catch(e=>{this.state=ImageState.ERROR,console.error(e)}).finally(()=>this.changed())}}setImage(e){this.image_=e}setResolution(e){this.resolution=e}}function listenImage(e,t,r){const n=e;let i=!0,o=!1,s=!1;const a=[listenOnce(n,EventType$1.LOAD,function(){s=!0,o||t()})];return n.src&&IMAGE_DECODE?(o=!0,n.decode().then(function(){i&&t()}).catch(function(){i&&(s?t():r())})):a.push(listenOnce(n,EventType$1.ERROR,r)),function(){i=!1,a.forEach(unlistenByKey)}}function load(e){return new Promise((t,r)=>{function n(){o(),t(e)}function i(){o(),r(new Error("Image load error"))}function o(){e.removeEventListener("load",n),e.removeEventListener("error",i)}e.addEventListener("load",n),e.addEventListener("error",i)})}function decodeFallback(e,t){return t&&(e.src=t),e.src&&IMAGE_DECODE?new Promise((t,r)=>e.decode().then(()=>t(e)).catch(n=>e.complete&&e.width?t(e):r(n))):load(e)}class IconImageCache{constructor(){this.cache_={},this.patternCache_={},this.cacheSize_=0,this.maxCacheSize_=1024}clear(){this.cache_={},this.patternCache_={},this.cacheSize_=0}canExpireCache(){return this.cacheSize_>this.maxCacheSize_}expire(){if(this.canExpireCache()){let e=0;for(const t in this.cache_){const r=this.cache_[t];3&e++||r.hasListener()||(delete this.cache_[t],delete this.patternCache_[t],--this.cacheSize_)}}}get(e,t,r){const n=getCacheKey$1(e,t,r);return n in this.cache_?this.cache_[n]:null}getPattern(e,t,r){const n=getCacheKey$1(e,t,r);return n in this.patternCache_?this.patternCache_[n]:null}set(e,t,r,n,i){const o=getCacheKey$1(e,t,r),s=o in this.cache_;this.cache_[o]=n,i&&(n.getImageState()===ImageState.IDLE&&n.load(),n.getImageState()===ImageState.LOADING?n.ready().then(()=>{this.patternCache_[o]=getSharedCanvasContext2D().createPattern(n.getImage(1),"repeat")}):this.patternCache_[o]=getSharedCanvasContext2D().createPattern(n.getImage(1),"repeat")),s||++this.cacheSize_}setSize(e){this.maxCacheSize_=e,this.expire()}}function getCacheKey$1(e,t,r){return t+":"+e+":"+(r?asArray(r):"null")}const shared=new IconImageCache;let taintedTestContext=null;class IconImage extends Target{constructor(e,t,r,n,i){super(),this.hitDetectionImage_=null,this.image_=e,this.crossOrigin_=r,this.canvas_={},this.color_=i,this.imageState_=void 0===n?ImageState.IDLE:n,this.size_=e&&e.width&&e.height?[e.width,e.height]:null,this.src_=t,this.tainted_,this.ready_=null}initializeImage_(){this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)}isTainted_(){if(void 0===this.tainted_&&this.imageState_===ImageState.LOADED){taintedTestContext||(taintedTestContext=createCanvasContext2D(1,1,void 0,{willReadFrequently:!0})),taintedTestContext.drawImage(this.image_,0,0);try{taintedTestContext.getImageData(0,0,1,1),this.tainted_=!1}catch{taintedTestContext=null,this.tainted_=!0}}return!0===this.tainted_}dispatchChangeEvent_(){this.dispatchEvent(EventType$1.CHANGE)}handleImageError_(){this.imageState_=ImageState.ERROR,this.dispatchChangeEvent_()}handleImageLoad_(){this.imageState_=ImageState.LOADED,this.size_=[this.image_.width,this.image_.height],this.dispatchChangeEvent_()}getImage(e){return this.image_||this.initializeImage_(),this.replaceColor_(e),this.canvas_[e]?this.canvas_[e]:this.image_}getPixelRatio(e){return this.replaceColor_(e),this.canvas_[e]?e:1}getImageState(){return this.imageState_}getHitDetectionImage(){if(this.image_||this.initializeImage_(),!this.hitDetectionImage_)if(this.isTainted_()){const e=this.size_[0],t=this.size_[1],r=createCanvasContext2D(e,t);r.fillRect(0,0,e,t),this.hitDetectionImage_=r.canvas}else this.hitDetectionImage_=this.image_;return this.hitDetectionImage_}getSize(){return this.size_}getSrc(){return this.src_}load(){if(this.imageState_===ImageState.IDLE){this.image_||this.initializeImage_(),this.imageState_=ImageState.LOADING;try{void 0!==this.src_&&(this.image_.src=this.src_)}catch{this.handleImageError_()}this.image_ instanceof HTMLImageElement&&decodeFallback(this.image_,this.src_).then(e=>{this.image_=e,this.handleImageLoad_()}).catch(this.handleImageError_.bind(this))}}replaceColor_(e){if(!this.color_||this.canvas_[e]||this.imageState_!==ImageState.LOADED)return;const t=this.image_,r=createCanvasContext2D(Math.ceil(t.width*e),Math.ceil(t.height*e)),n=r.canvas;r.scale(e,e),r.drawImage(t,0,0),r.globalCompositeOperation="multiply",r.fillStyle=asString(this.color_),r.fillRect(0,0,n.width/e,n.height/e),r.globalCompositeOperation="destination-in",r.drawImage(t,0,0),this.canvas_[e]=n}ready(){return this.ready_||(this.ready_=new Promise(e=>{if(this.imageState_===ImageState.LOADED||this.imageState_===ImageState.ERROR)e();else{const t=()=>{this.imageState_!==ImageState.LOADED&&this.imageState_!==ImageState.ERROR||(this.removeEventListener(EventType$1.CHANGE,t),e())};this.addEventListener(EventType$1.CHANGE,t)}})),this.ready_}}function get$1(e,t,r,n,i,o){let s=void 0===t?void 0:shared.get(t,r,i);return s||(s=new IconImage(e,e&&"src"in e?e.src||void 0:t,r,n,i),shared.set(t,r,i,s,o)),o&&s&&!shared.getPattern(t,r,i)&&shared.set(t,r,i,s,o),s}function asColorLike(e){return e?Array.isArray(e)?toString(e):"object"==typeof e&&"src"in e?asCanvasPattern(e):e:null}function asCanvasPattern(e){if(!e.offset||!e.size)return shared.getPattern(e.src,"anonymous",e.color);const t=e.src+":"+e.offset,r=shared.getPattern(t,void 0,e.color);if(r)return r;const n=shared.get(e.src,"anonymous",null);if(n.getImageState()!==ImageState.LOADED)return null;const i=createCanvasContext2D(e.size[0],e.size[1]);return i.drawImage(n.getImage(1),e.offset[0],e.offset[1],e.size[0],e.size[1],0,0,e.size[0],e.size[1]),get$1(i.canvas,t,void 0,ImageState.LOADED,e.color,!0),shared.getPattern(t,void 0,e.color)}const defaultFont="10px sans-serif",defaultFillStyle="#000",defaultLineCap="round",defaultLineDash=[],defaultLineDashOffset=0,defaultLineJoin="round",defaultMiterLimit=10,defaultStrokeStyle="#000",defaultTextAlign="center",defaultTextBaseline="middle",defaultPadding=[0,0,0,0],defaultLineWidth=1,checkedFonts=new BaseObject;let measureContext$1=null,measureFont;const textHeights={},genericFontFamilies=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"]);function getFontKey(e,t,r){return`${e} ${t} 16px "${r}"`}const registerFont=function(){const e=100;let t,r;async function n(e){await r.ready;const t=await r.load(e);if(0===t.length)return!1;const n=getFontParameters(e),i=n.families[0].toLowerCase(),o=n.weight;return t.some(e=>{const t=e.family.replace(/^['"]|['"]$/g,"").toLowerCase(),r=fontWeights$1[e.weight]||e.weight;return t===i&&e.style===n.style&&r==o})}async function i(){await r.ready;let o=!0;const s=checkedFonts.getProperties(),a=Object.keys(s).filter(t=>s[t]=0;--t){const r=a[t];let i=s[r];iMath.max(t,measureTextWidth(e,r)),0);return r[t]=n,n}function getTextDimensions(e,t){const r=[],n=[],i=[];let o=0,s=0,a=0,l=0;for(let c=0,u=t.length;c<=u;c+=2){const h=t[c];if("\n"===h||c===u){o=Math.max(o,s),i.push(s),s=0,a+=l,l=0;continue}const d=t[c+1]||e.font,p=measureTextWidth(d,h);r.push(p),s+=p;const f=measureTextHeight(d);n.push(f),l=Math.max(l,f)}return{width:o,height:a,widths:r,heights:n,lineWidths:i}}function drawImageOrLabel(e,t,r,n,i,o,s,a,l,c,u){e.save(),1!==r&&(void 0===e.globalAlpha?e.globalAlpha=e=>e.globalAlpha*=r:e.globalAlpha*=r),t&&e.transform.apply(e,t),n.contextInstructions?(e.translate(l,c),e.scale(u[0],u[1]),executeLabelInstructions(n,e)):u[0]<0||u[1]<0?(e.translate(l,c),e.scale(u[0],u[1]),e.drawImage(n,i,o,s,a,0,0,s,a)):e.drawImage(n,i,o,s,a,l,c,s*u[0],a*u[1]),e.restore()}function executeLabelInstructions(e,t){const r=e.contextInstructions;for(let n=0,i=r.length;nthis.imageState_=ImageState.LOADED),this.render()}clone(){const e=this.getScale(),t=new RegularShape({fill:this.getFill()?this.getFill().clone():void 0,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),stroke:this.getStroke()?this.getStroke().clone():void 0,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(e)?e.slice():e,displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return t.setOpacity(this.getOpacity()),t}getAnchor(){const e=this.size_,t=this.getDisplacement(),r=this.getScaleArray();return[e[0]/2-t[0]/r[0],e[1]/2+t[1]/r[1]]}getAngle(){return this.angle_}getFill(){return this.fill_}setFill(e){this.fill_=e,this.render()}getHitDetectionImage(){return this.hitDetectionCanvas_||(this.hitDetectionCanvas_=this.createHitDetectionCanvas_(this.renderOptions_)),this.hitDetectionCanvas_}getImage(e){const t=this.fill_?.getKey(),r=`${e},${this.angle_},${this.radius},${this.radius2_},${this.points_},${t}`+Object.values(this.renderOptions_).join(",");let n=shared.get(r,null,null)?.getImage(1);if(!n){const t=this.renderOptions_,i=Math.ceil(t.size*e),o=createCanvasContext2D(i,i);this.draw_(t,o,e),n=o.canvas,shared.set(r,null,null,new IconImage(n,void 0,null,ImageState.LOADED,null))}return n}getPixelRatio(e){return e}getImageSize(){return this.size_}getImageState(){return this.imageState_}getOrigin(){return this.origin_}getPoints(){return this.points_}getRadius(){return this.radius}getRadius2(){return this.radius2_}getSize(){return this.size_}getStroke(){return this.stroke_}setStroke(e){this.stroke_=e,this.render()}listenImageChange(e){}load(){}unlistenImageChange(e){}calculateLineJoinSize_(e,t,r){if(0===t||this.points_===1/0||"bevel"!==e&&"miter"!==e)return t;let n=this.radius,i=void 0===this.radius2_?n:this.radius2_;if(n{this.patternImage_=null}),t.getImageState()===ImageState.IDLE&&t.load(),t.getImageState()===ImageState.LOADING&&(this.patternImage_=t)}this.color_=e}getKey(){const e=this.getColor();return e?e instanceof CanvasPattern||e instanceof CanvasGradient?getUid(e):"object"==typeof e&&"src"in e?e.src+":"+e.offset:asArray(e).toString():""}loading(){return!!this.patternImage_}ready(){return this.patternImage_?this.patternImage_.ready():Promise.resolve()}}function calculateScale(e,t,r,n){return void 0!==r&&void 0!==n?[r/e,n/t]:void 0!==r?r/e:void 0!==n?n/t:1}class Icon extends ImageStyle{constructor(e){const t=void 0!==(e=e||{}).opacity?e.opacity:1,r=void 0!==e.rotation?e.rotation:0,n=void 0!==e.scale?e.scale:1,i=void 0!==e.rotateWithView&&e.rotateWithView;super({opacity:t,rotation:r,scale:n,displacement:void 0!==e.displacement?e.displacement:[0,0],rotateWithView:i,declutterMode:e.declutterMode}),this.anchor_=void 0!==e.anchor?e.anchor:[.5,.5],this.normalizedAnchor_=null,this.anchorOrigin_=void 0!==e.anchorOrigin?e.anchorOrigin:"top-left",this.anchorXUnits_=void 0!==e.anchorXUnits?e.anchorXUnits:"fraction",this.anchorYUnits_=void 0!==e.anchorYUnits?e.anchorYUnits:"fraction",this.crossOrigin_=void 0!==e.crossOrigin?e.crossOrigin:null;const o=void 0!==e.img?e.img:null;let s,a=e.src;if(assert$1(!(void 0!==a&&o),"`image` and `src` cannot be provided at the same time"),void 0!==a&&0!==a.length||!o||(a=o.src||getUid(o)),assert$1(void 0!==a&&a.length>0,"A defined and non-empty `src` or `image` must be provided"),assert$1(!((void 0!==e.width||void 0!==e.height)&&void 0!==e.scale),"`width` or `height` cannot be provided together with `scale`"),void 0!==e.src?s=ImageState.IDLE:void 0!==o&&(s="complete"in o?o.complete?o.src?ImageState.LOADED:ImageState.IDLE:ImageState.LOADING:ImageState.LOADED),this.color_=void 0!==e.color?asArray(e.color):null,this.iconImage_=get$1(o,a,this.crossOrigin_,s,this.color_),this.offset_=void 0!==e.offset?e.offset:[0,0],this.offsetOrigin_=void 0!==e.offsetOrigin?e.offsetOrigin:"top-left",this.origin_=null,this.size_=void 0!==e.size?e.size:null,this.initialOptions_,void 0!==e.width||void 0!==e.height){let t,r;if(e.size)[t,r]=e.size;else{const n=this.getImage(1);if(n.width&&n.height)t=n.width,r=n.height;else if(n instanceof HTMLImageElement){this.initialOptions_=e;const t=()=>{if(this.unlistenImageChange(t),!this.initialOptions_)return;const r=this.iconImage_.getSize();this.setScale(calculateScale(r[0],r[1],e.width,e.height))};return void this.listenImageChange(t)}}void 0!==t&&this.setScale(calculateScale(t,r,e.width,e.height))}}clone(){let e,t,r;return this.initialOptions_?(t=this.initialOptions_.width,r=this.initialOptions_.height):(e=this.getScale(),e=Array.isArray(e)?e.slice():e),new Icon({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||void 0,crossOrigin:this.crossOrigin_,offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,opacity:this.getOpacity(),rotateWithView:this.getRotateWithView(),rotation:this.getRotation(),scale:e,width:t,height:r,size:null!==this.size_?this.size_.slice():void 0,src:this.getSrc(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getAnchor(){let e=this.normalizedAnchor_;if(!e){e=this.anchor_;const t=this.getSize();if("fraction"==this.anchorXUnits_||"fraction"==this.anchorYUnits_){if(!t)return null;e=this.anchor_.slice(),"fraction"==this.anchorXUnits_&&(e[0]*=t[0]),"fraction"==this.anchorYUnits_&&(e[1]*=t[1])}if("top-left"!=this.anchorOrigin_){if(!t)return null;e===this.anchor_&&(e=this.anchor_.slice()),"top-right"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(e[0]=-e[0]+t[0]),"bottom-left"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(e[1]=-e[1]+t[1])}this.normalizedAnchor_=e}const t=this.getDisplacement(),r=this.getScaleArray();return[e[0]-t[0]/r[0],e[1]+t[1]/r[1]]}setAnchor(e){this.anchor_=e,this.normalizedAnchor_=null}getColor(){return this.color_}getImage(e){return this.iconImage_.getImage(e)}getPixelRatio(e){return this.iconImage_.getPixelRatio(e)}getImageSize(){return this.iconImage_.getSize()}getImageState(){return this.iconImage_.getImageState()}getHitDetectionImage(){return this.iconImage_.getHitDetectionImage()}getOrigin(){if(this.origin_)return this.origin_;let e=this.offset_;if("top-left"!=this.offsetOrigin_){const t=this.getSize(),r=this.iconImage_.getSize();if(!t||!r)return null;e=e.slice(),"top-right"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(e[0]=r[0]-t[0]-e[0]),"bottom-left"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(e[1]=r[1]-t[1]-e[1])}return this.origin_=e,this.origin_}getSrc(){return this.iconImage_.getSrc()}setSrc(e){this.iconImage_=get$1(null,e,this.crossOrigin_,ImageState.IDLE,this.color_)}getSize(){return this.size_?this.size_:this.iconImage_.getSize()}getWidth(){const e=this.getScaleArray();return this.size_?this.size_[0]*e[0]:this.iconImage_.getImageState()==ImageState.LOADED?this.iconImage_.getSize()[0]*e[0]:void 0}getHeight(){const e=this.getScaleArray();return this.size_?this.size_[1]*e[1]:this.iconImage_.getImageState()==ImageState.LOADED?this.iconImage_.getSize()[1]*e[1]:void 0}setScale(e){delete this.initialOptions_,super.setScale(e)}listenImageChange(e){this.iconImage_.addEventListener(EventType$1.CHANGE,e)}load(){this.iconImage_.load()}unlistenImageChange(e){this.iconImage_.removeEventListener(EventType$1.CHANGE,e)}ready(){return this.iconImage_.ready()}}class Stroke{constructor(e){e=e||{},this.color_=void 0!==e.color?e.color:null,this.lineCap_=e.lineCap,this.lineDash_=void 0!==e.lineDash?e.lineDash:null,this.lineDashOffset_=e.lineDashOffset,this.lineJoin_=e.lineJoin,this.miterLimit_=e.miterLimit,this.width_=e.width}clone(){const e=this.getColor();return new Stroke({color:Array.isArray(e)?e.slice():e||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(e){this.color_=e}setLineCap(e){this.lineCap_=e}setLineDash(e){this.lineDash_=e}setLineDashOffset(e){this.lineDashOffset_=e}setLineJoin(e){this.lineJoin_=e}setMiterLimit(e){this.miterLimit_=e}setWidth(e){this.width_=e}}class Style{constructor(e){e=e||{},this.geometry_=null,this.geometryFunction_=defaultGeometryFunction,void 0!==e.geometry&&this.setGeometry(e.geometry),this.fill_=void 0!==e.fill?e.fill:null,this.image_=void 0!==e.image?e.image:null,this.renderer_=void 0!==e.renderer?e.renderer:null,this.hitDetectionRenderer_=void 0!==e.hitDetectionRenderer?e.hitDetectionRenderer:null,this.stroke_=void 0!==e.stroke?e.stroke:null,this.text_=void 0!==e.text?e.text:null,this.zIndex_=e.zIndex}clone(){let e=this.getGeometry();return e&&"object"==typeof e&&(e=e.clone()),new Style({geometry:e??void 0,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer()??void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(e){this.renderer_=e}setHitDetectionRenderer(e){this.hitDetectionRenderer_=e}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(e){this.fill_=e}getImage(){return this.image_}setImage(e){this.image_=e}getStroke(){return this.stroke_}setStroke(e){this.stroke_=e}getText(){return this.text_}setText(e){this.text_=e}getZIndex(){return this.zIndex_}setGeometry(e){"function"==typeof e?this.geometryFunction_=e:"string"==typeof e?this.geometryFunction_=function(t){return t.get(e)}:e?void 0!==e&&(this.geometryFunction_=function(){return e}):this.geometryFunction_=defaultGeometryFunction,this.geometry_=e}setZIndex(e){this.zIndex_=e}}function toFunction(e){let t;if("function"==typeof e)t=e;else{let r;Array.isArray(e)?r=e:(assert$1("function"==typeof e.getZIndex,"Expected an `Style` or an array of `Style`"),r=[e]),t=function(){return r}}return t}let defaultStyles=null;function createDefaultStyle(){if(!defaultStyles){const e=new Fill({color:"rgba(255,255,255,0.4)"}),t=new Stroke({color:"#3399CC",width:1.25});defaultStyles=[new Style({image:new CircleStyle({fill:e,stroke:t,radius:5}),fill:e,stroke:t})]}return defaultStyles}function defaultGeometryFunction(e){return e.getGeometry()}const DEFAULT_FILL_COLOR="#333";let Text$1=class e{constructor(e){e=e||{},this.font_=e.font,this.rotation_=e.rotation,this.rotateWithView_=e.rotateWithView,this.keepUpright_=e.keepUpright,this.scale_=e.scale,this.scaleArray_=toSize(void 0!==e.scale?e.scale:1),this.text_=e.text,this.textAlign_=e.textAlign,this.justify_=e.justify,this.repeat_=e.repeat,this.textBaseline_=e.textBaseline,this.fill_=void 0!==e.fill?e.fill:new Fill({color:DEFAULT_FILL_COLOR}),this.maxAngle_=void 0!==e.maxAngle?e.maxAngle:Math.PI/4,this.placement_=void 0!==e.placement?e.placement:"point",this.overflow_=!!e.overflow,this.stroke_=void 0!==e.stroke?e.stroke:null,this.offsetX_=void 0!==e.offsetX?e.offsetX:0,this.offsetY_=void 0!==e.offsetY?e.offsetY:0,this.backgroundFill_=e.backgroundFill?e.backgroundFill:null,this.backgroundStroke_=e.backgroundStroke?e.backgroundStroke:null,this.padding_=void 0===e.padding?null:e.padding,this.declutterMode_=e.declutterMode}clone(){const t=this.getScale();return new e({font:this.getFont(),placement:this.getPlacement(),repeat:this.getRepeat(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),keepUpright:this.getKeepUpright(),scale:Array.isArray(t)?t.slice():t,text:this.getText(),textAlign:this.getTextAlign(),justify:this.getJustify(),textBaseline:this.getTextBaseline(),fill:this.getFill()instanceof Fill?this.getFill().clone():this.getFill(),stroke:this.getStroke()?this.getStroke().clone():void 0,offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),backgroundFill:this.getBackgroundFill()?this.getBackgroundFill().clone():void 0,backgroundStroke:this.getBackgroundStroke()?this.getBackgroundStroke().clone():void 0,padding:this.getPadding()||void 0,declutterMode:this.getDeclutterMode()})}getOverflow(){return this.overflow_}getFont(){return this.font_}getMaxAngle(){return this.maxAngle_}getPlacement(){return this.placement_}getRepeat(){return this.repeat_}getOffsetX(){return this.offsetX_}getOffsetY(){return this.offsetY_}getFill(){return this.fill_}getRotateWithView(){return this.rotateWithView_}getKeepUpright(){return this.keepUpright_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getStroke(){return this.stroke_}getText(){return this.text_}getTextAlign(){return this.textAlign_}getJustify(){return this.justify_}getTextBaseline(){return this.textBaseline_}getBackgroundFill(){return this.backgroundFill_}getBackgroundStroke(){return this.backgroundStroke_}getPadding(){return this.padding_}getDeclutterMode(){return this.declutterMode_}setOverflow(e){this.overflow_=e}setFont(e){this.font_=e}setMaxAngle(e){this.maxAngle_=e}setOffsetX(e){this.offsetX_=e}setOffsetY(e){this.offsetY_=e}setPlacement(e){this.placement_=e}setRepeat(e){this.repeat_=e}setRotateWithView(e){this.rotateWithView_=e}setKeepUpright(e){this.keepUpright_=e}setFill(e){this.fill_=e}setRotation(e){this.rotation_=e}setScale(e){this.scale_=e,this.scaleArray_=toSize(void 0!==e?e:1)}setStroke(e){this.stroke_=e}setText(e){this.text_=e}setTextAlign(e){this.textAlign_=e}setJustify(e){this.justify_=e}setTextBaseline(e){this.textBaseline_=e}setBackgroundFill(e){this.backgroundFill_=e}setBackgroundStroke(e){this.backgroundStroke_=e}setPadding(e){this.padding_=e}};function always(){return!0}function rulesToStyleFunction(e){const t=newParsingContext(),r=buildRuleSet(e,t),n=newEvaluationContext();return function(e,i){if(n.properties=e.getPropertiesInternal(),n.resolution=i,t.featureId){const t=e.getId();n.featureId=void 0!==t?t:null}return t.geometryType&&(n.geometryType=computeGeometryType(e.getGeometry())),r(n)}}function flatStylesToStyleFunction(e){const t=newParsingContext(),r=e.length,n=new Array(r);for(let s=0;snull;n=colorLikeEvaluator(e,t+"fill-color",r)}if(!n)return null;const i=new Fill;return function(e){const t=n(e);return t===NO_COLOR?null:(i.setColor(t),i)}}function buildStroke(e,t,r){const n=numberEvaluator(e,t+"stroke-width",r),i=colorLikeEvaluator(e,t+"stroke-color",r);if(!n&&!i)return null;const o=stringEvaluator(e,t+"stroke-line-cap",r),s=stringEvaluator(e,t+"stroke-line-join",r),a=numberArrayEvaluator(e,t+"stroke-line-dash",r),l=numberEvaluator(e,t+"stroke-line-dash-offset",r),c=numberEvaluator(e,t+"stroke-miter-limit",r),u=new Stroke;return function(e){if(i){const t=i(e);if(t===NO_COLOR)return null;u.setColor(t)}if(n&&u.setWidth(n(e)),o){const t=o(e);if("butt"!==t&&"round"!==t&&"square"!==t)throw new Error("Expected butt, round, or square line cap");u.setLineCap(t)}if(s){const t=s(e);if("bevel"!==t&&"round"!==t&&"miter"!==t)throw new Error("Expected bevel, round, or miter line join");u.setLineJoin(t)}return a&&u.setLineDash(a(e)),l&&u.setLineDashOffset(l(e)),c&&u.setMiterLimit(c(e)),u}}function buildText(e,t){const r="text-",n=stringEvaluator(e,r+"value",t);if(!n)return null;const i=buildFill(e,r,t),o=buildFill(e,r+"background-",t),s=buildStroke(e,r,t),a=buildStroke(e,r+"background-",t),l=stringEvaluator(e,r+"font",t),c=numberEvaluator(e,r+"max-angle",t),u=numberEvaluator(e,r+"offset-x",t),h=numberEvaluator(e,r+"offset-y",t),d=booleanEvaluator(e,r+"overflow",t),p=stringEvaluator(e,r+"placement",t),f=numberEvaluator(e,r+"repeat",t),g=sizeLikeEvaluator(e,r+"scale",t),m=booleanEvaluator(e,r+"rotate-with-view",t),y=numberEvaluator(e,r+"rotation",t),b=stringEvaluator(e,r+"align",t),v=stringEvaluator(e,r+"justify",t),_=stringEvaluator(e,r+"baseline",t),E=booleanEvaluator(e,r+"keep-upright",t),w=numberArrayEvaluator(e,r+"padding",t),C=optionalDeclutterMode(e,r+"declutter-mode"),S=new Text$1({declutterMode:C});return function(e){if(S.setText(n(e)),i&&S.setFill(i(e)),o&&S.setBackgroundFill(o(e)),s&&S.setStroke(s(e)),a&&S.setBackgroundStroke(a(e)),l&&S.setFont(l(e)),c&&S.setMaxAngle(c(e)),u&&S.setOffsetX(u(e)),h&&S.setOffsetY(h(e)),d&&S.setOverflow(d(e)),p){const t=p(e);if("point"!==t&&"line"!==t)throw new Error("Expected point or line for text-placement");S.setPlacement(t)}if(f&&S.setRepeat(f(e)),g&&S.setScale(g(e)),m&&S.setRotateWithView(m(e)),y&&S.setRotation(y(e)),b){const t=b(e);if("left"!==t&&"center"!==t&&"right"!==t&&"end"!==t&&"start"!==t)throw new Error("Expected left, right, center, start, or end for text-align");S.setTextAlign(t)}if(v){const t=v(e);if("left"!==t&&"right"!==t&&"center"!==t)throw new Error("Expected left, right, or center for text-justify");S.setJustify(t)}if(_){const t=_(e);if("bottom"!==t&&"top"!==t&&"middle"!==t&&"alphabetic"!==t&&"hanging"!==t)throw new Error("Expected bottom, top, middle, alphabetic, or hanging for text-baseline");S.setTextBaseline(t)}return w&&S.setPadding(w(e)),E&&S.setKeepUpright(E(e)),S}}function buildImage(e,t){return"icon-src"in e?buildIcon(e,t):"shape-points"in e?buildShape(e,t):"circle-radius"in e?buildCircle(e,t):null}function buildIcon(e,t){const r="icon-",n=r+"src",i=requireString(e[n],n),o=coordinateEvaluator(e,r+"anchor",t),s=sizeLikeEvaluator(e,r+"scale",t),a=numberEvaluator(e,r+"opacity",t),l=coordinateEvaluator(e,r+"displacement",t),c=numberEvaluator(e,r+"rotation",t),u=booleanEvaluator(e,r+"rotate-with-view",t),h=optionalIconOrigin(e,r+"anchor-origin"),d=optionalIconAnchorUnits(e,r+"anchor-x-units"),p=optionalIconAnchorUnits(e,r+"anchor-y-units"),f=optionalColorLike(e,r+"color"),g=optionalString(e,r+"cross-origin"),m=optionalNumberArray(e,r+"offset"),y=optionalIconOrigin(e,r+"offset-origin"),b=optionalNumber(e,r+"width"),v=optionalNumber(e,r+"height"),_=optionalSize(e,r+"size"),E=optionalDeclutterMode(e,r+"declutter-mode"),w=new Icon({src:i,anchorOrigin:h,anchorXUnits:d,anchorYUnits:p,color:f,crossOrigin:g,offset:m,offsetOrigin:y,height:v,width:b,size:_,declutterMode:E});return function(e){return a&&w.setOpacity(a(e)),l&&w.setDisplacement(l(e)),c&&w.setRotation(c(e)),u&&w.setRotateWithView(u(e)),s&&w.setScale(s(e)),o&&w.setAnchor(o(e)),w}}function buildShape(e,t){const r="shape-",n=r+"points",i=r+"radius",o=requireNumber(e[n],n),s=requireNumber(e[i],i),a=buildFill(e,r,t),l=buildStroke(e,r,t),c=sizeLikeEvaluator(e,r+"scale",t),u=coordinateEvaluator(e,r+"displacement",t),h=numberEvaluator(e,r+"rotation",t),d=booleanEvaluator(e,r+"rotate-with-view",t),p=optionalNumber(e,r+"radius2"),f=optionalNumber(e,r+"angle"),g=optionalDeclutterMode(e,r+"declutter-mode"),m=new RegularShape({points:o,radius:s,radius2:p,angle:f,declutterMode:g});return function(e){return a&&m.setFill(a(e)),l&&m.setStroke(l(e)),u&&m.setDisplacement(u(e)),h&&m.setRotation(h(e)),d&&m.setRotateWithView(d(e)),c&&m.setScale(c(e)),m}}function buildCircle(e,t){const r="circle-",n=buildFill(e,r,t),i=buildStroke(e,r,t),o=numberEvaluator(e,r+"radius",t),s=sizeLikeEvaluator(e,r+"scale",t),a=coordinateEvaluator(e,r+"displacement",t),l=numberEvaluator(e,r+"rotation",t),c=booleanEvaluator(e,r+"rotate-with-view",t),u=optionalDeclutterMode(e,r+"declutter-mode"),h=new CircleStyle({radius:5,declutterMode:u});return function(e){return o&&h.setRadius(o(e)),n&&h.setFill(n(e)),i&&h.setStroke(i(e)),a&&h.setDisplacement(a(e)),l&&h.setRotation(l(e)),c&&h.setRotateWithView(c(e)),s&&h.setScale(s(e)),h}}function numberEvaluator(e,t,r){if(!(t in e))return;const n=buildExpression(e[t],NumberType$1,r);return function(e){return requireNumber(n(e),t)}}function stringEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],StringType$1,r);return function(e){return requireString(n(e),t)}}function patternEvaluator(e,t,r){const n=stringEvaluator(e,t+"pattern-src",r),i=sizeEvaluator(e,t+"pattern-offset",r),o=sizeEvaluator(e,t+"pattern-size",r),s=colorLikeEvaluator(e,t+"color",r);return function(e){return{src:n(e),offset:i&&i(e),size:o&&o(e),color:s&&s(e)}}}function booleanEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],BooleanType$1,r);return function(e){const r=n(e);if("boolean"!=typeof r)throw new Error(`Expected a boolean for ${t}`);return r}}function colorLikeEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],ColorType$1,r);return function(e){return requireColorLike(n(e),t)}}function numberArrayEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1,r);return function(e){return requireNumberArray(n(e),t)}}function coordinateEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1,r);return function(e){const r=requireNumberArray(n(e),t);if(2!==r.length)throw new Error(`Expected two numbers for ${t}`);return r}}function sizeEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1,r);return function(e){return requireSize(n(e),t)}}function sizeLikeEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1|NumberType$1,r);return function(e){return requireSizeLike(n(e),t)}}function optionalNumber(e,t){const r=e[t];if(void 0!==r){if("number"!=typeof r)throw new Error(`Expected a number for ${t}`);return r}}function optionalSize(e,t){const r=e[t];if(void 0!==r){if("number"==typeof r)return toSize(r);if(!Array.isArray(r))throw new Error(`Expected a number or size array for ${t}`);if(2!==r.length||"number"!=typeof r[0]||"number"!=typeof r[1])throw new Error(`Expected a number or size array for ${t}`);return r}}function optionalString(e,t){const r=e[t];if(void 0!==r){if("string"!=typeof r)throw new Error(`Expected a string for ${t}`);return r}}function optionalIconOrigin(e,t){const r=e[t];if(void 0!==r){if("bottom-left"!==r&&"bottom-right"!==r&&"top-left"!==r&&"top-right"!==r)throw new Error(`Expected bottom-left, bottom-right, top-left, or top-right for ${t}`);return r}}function optionalIconAnchorUnits(e,t){const r=e[t];if(void 0!==r){if("pixels"!==r&&"fraction"!==r)throw new Error(`Expected pixels or fraction for ${t}`);return r}}function optionalNumberArray(e,t){const r=e[t];if(void 0!==r)return requireNumberArray(r,t)}function optionalDeclutterMode(e,t){const r=e[t];if(void 0!==r){if("string"!=typeof r)throw new Error(`Expected a string for ${t}`);if("declutter"!==r&&"obstacle"!==r&&"none"!==r)throw new Error(`Expected declutter, obstacle, or none for ${t}`);return r}}function optionalColorLike(e,t){const r=e[t];if(void 0!==r)return requireColorLike(r,t)}function requireNumberArray(e,t){if(!Array.isArray(e))throw new Error(`Expected an array for ${t}`);const r=e.length;for(let n=0;n4)throw new Error(`Expected a color with 3 or 4 values for ${t}`);return r}function requireSize(e,t){const r=requireNumberArray(e,t);if(2!==r.length)throw new Error(`Expected an array of two numbers for ${t}`);return r}function requireSizeLike(e,t){return"number"==typeof e?e:requireSize(e,t)}const Property$2={RENDER_ORDER:"renderOrder"};class BaseVectorLayer extends Layer{constructor(e){e=e||{};const t=Object.assign({},e);delete t.style,delete t.renderBuffer,delete t.updateWhileAnimating,delete t.updateWhileInteracting,super(t),this.declutter_=e.declutter?String(e.declutter):void 0,this.renderBuffer_=void 0!==e.renderBuffer?e.renderBuffer:100,this.style_=null,this.styleFunction_=void 0,this.setStyle(e.style),this.updateWhileAnimating_=void 0!==e.updateWhileAnimating&&e.updateWhileAnimating,this.updateWhileInteracting_=void 0!==e.updateWhileInteracting&&e.updateWhileInteracting}getDeclutter(){return this.declutter_}getFeatures(e){return super.getFeatures(e)}getRenderBuffer(){return this.renderBuffer_}getRenderOrder(){return this.get(Property$2.RENDER_ORDER)}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}getUpdateWhileAnimating(){return this.updateWhileAnimating_}getUpdateWhileInteracting(){return this.updateWhileInteracting_}renderDeclutter(e,t){const r=this.getDeclutter();r in e.declutter==0&&(e.declutter[r]=new RBush$1(9)),this.getRenderer().renderDeclutter(e,t)}setRenderOrder(e){this.set(Property$2.RENDER_ORDER,e)}setStyle(e){this.style_=void 0===e?createDefaultStyle:e;const t=toStyleLike(e);this.styleFunction_=null===e?void 0:toFunction(t),this.changed()}setDeclutter(e){this.declutter_=e?String(e):void 0,this.changed()}}function toStyleLike(e){if(void 0===e)return createDefaultStyle;if(!e)return null;if("function"==typeof e)return e;if(e instanceof Style)return e;if(!Array.isArray(e))return flatStylesToStyleFunction([e]);if(0===e.length)return[];const t=e.length,r=e[0];if(r instanceof Style){const r=new Array(t);for(let n=0;n=0;--n){const i=f[n],o=i.layer;if(o.hasRenderer()&&inView(i,c)&&s.call(a,o)){const n=o.getRenderer(),s=o.getSource();if(n&&s){const o=s.getWrapX()?d:e,a=u.bind(null,i.managed);y[0]=o[0]+p[v][0],y[1]=o[1]+p[v][1],l=n.forEachFeatureAtCoordinate(y,t,r,a,m)}if(l)return l}}if(0===m.length)return;const b=1/m.length;return m.forEach((e,t)=>e.distanceSq+=t*b),m.sort((e,t)=>e.distanceSq-t.distanceSq),m.some(e=>l=e.callback(e.feature,e.layer,e.geometry)),l}hasFeatureAtCoordinate(e,t,r,n,i,o){return void 0!==this.forEachFeatureAtCoordinate(e,t,r,n,TRUE,this,i,o)}getMap(){return this.map_}renderFrame(e){abstract()}scheduleExpireIconCache(e){shared.canExpireCache()&&e.postRenderFunctions.push(expireIconCache)}}function expireIconCache(){shared.expire()}class CompositeMapRenderer extends MapRenderer{constructor(e){super(e),this.fontChangeListenerKey_=listen(checkedFonts,ObjectEventType.PROPERTYCHANGE,e.redrawText,e),this.element_=WORKER_OFFSCREEN_CANVAS?createMockDiv():document.createElement("div");const t=this.element_.style;t.position="absolute",t.width="100%",t.height="100%",t.zIndex="0",this.element_.className=CLASS_UNSELECTABLE+" ol-layers";const r=e.getViewport();r&&r.insertBefore(this.element_,r.firstChild||null),this.children_=[],this.renderedVisible_=!0}dispatchRenderEvent(e,t){const r=this.getMap();if(r.hasListener(e)){const n=new RenderEvent(e,void 0,t);r.dispatchEvent(n)}}disposeInternal(){unlistenByKey(this.fontChangeListenerKey_),this.element_.remove(),super.disposeInternal()}renderFrame(e){if(!e)return void(this.renderedVisible_&&(this.element_.style.display="none",this.renderedVisible_=!1));this.calculateMatrices2D(e),this.dispatchRenderEvent(EventType.PRECOMPOSE,e);const t=e.layerStatesArray.sort((e,t)=>e.zIndex-t.zIndex);t.some(e=>e.layer instanceof BaseVectorLayer&&e.layer.getDeclutter())&&(e.declutter={});const r=e.viewState;this.children_.length=0;const n=[];let i=null;for(let s=0,a=t.length;s0)&&(e.fillStyle=n,e.fillRect(0,0,o.width,o.height)),isCanvas(r)&&r.width>0){const n=t.style.opacity||r.style.opacity;e.globalAlpha=""===n?1:Number(n);const i=r.style.transform;if(i)e.setTransform(...fromString$1(i));else{const t=parseFloat(r.style.width)/r.width,n=parseFloat(r.style.height)/r.height;e.setTransform(t,0,0,n,0,0)}e.drawImage(r,0,0)}}e.globalAlpha=1,e.setTransform(1,0,0,1,0,0)}this.dispatchRenderEvent(EventType.POSTCOMPOSE,e),this.renderedVisible_||(this.element_.style.display="",this.renderedVisible_=!0),this.scheduleExpireIconCache(e)}declutter(e,t){if(e.declutter){for(let r=t.length-1;r>=0;--r){const n=t[r],i=n.layer;i.getDeclutter()&&i.renderDeclutter(e,n)}t.forEach(t=>t.layer.renderDeferred(e))}}}function removeLayerMapProperty(e){e instanceof Layer?e.setMapInternal(null):e instanceof LayerGroup&&e.getLayers().forEach(removeLayerMapProperty)}function setLayerMapProperty(e,t){if(e instanceof Layer)e.setMapInternal(t);else if(e instanceof LayerGroup){const r=e.getLayers().getArray();for(let e=0,n=r.length;ethis.updateSize())),this.controls=t.controls||(WORKER_OFFSCREEN_CANVAS?new Collection:defaults$1()),this.interactions=t.interactions||(WORKER_OFFSCREEN_CANVAS?new Collection:defaults({onFocusOnly:!0})),this.overlays_=t.overlays,this.overlayIdIndex_={},this.renderer_=null,this.postRenderFunctions_=[],this.tileQueue_=new TileQueue(this.getTilePriority.bind(this),this.handleTileChange_.bind(this)),this.addChangeListener(MapProperty.LAYERGROUP,this.handleLayerGroupChanged_),this.addChangeListener(MapProperty.VIEW,this.handleViewChanged_),this.addChangeListener(MapProperty.SIZE,this.handleSizeChanged_),this.addChangeListener(MapProperty.TARGET,this.handleTargetChanged_),this.setProperties(t.values);const r=this;!e.view||e.view instanceof View||e.view.then(function(e){r.setView(new View(e))}),this.controls.addEventListener(CollectionEventType.ADD,e=>{e.element.setMap(this)}),this.controls.addEventListener(CollectionEventType.REMOVE,e=>{e.element.setMap(null)}),this.interactions.addEventListener(CollectionEventType.ADD,e=>{e.element.setMap(this)}),this.interactions.addEventListener(CollectionEventType.REMOVE,e=>{e.element.setMap(null)}),this.overlays_.addEventListener(CollectionEventType.ADD,e=>{this.addOverlayInternal_(e.element)}),this.overlays_.addEventListener(CollectionEventType.REMOVE,e=>{const t=e.element.getId();void 0!==t&&delete this.overlayIdIndex_[t.toString()],e.element.setMap(null)}),this.controls.forEach(e=>{e.setMap(this)}),this.interactions.forEach(e=>{e.setMap(this)}),this.overlays_.forEach(this.addOverlayInternal_.bind(this))}addControl(e){this.getControls().push(e)}addInteraction(e){this.getInteractions().push(e)}addLayer(e){this.getLayerGroup().getLayers().push(e)}handleLayerAdd_(e){setLayerMapProperty(e.layer,this)}addOverlay(e){this.getOverlays().push(e)}addOverlayInternal_(e){const t=e.getId();void 0!==t&&(this.overlayIdIndex_[t.toString()]=e),e.setMap(this)}disposeInternal(){this.controls.clear(),this.interactions.clear(),this.overlays_.clear(),this.resizeObserver_?.disconnect(),this.setTarget(null),super.disposeInternal()}forEachFeatureAtPixel(e,t,r){if(!this.frameState_||!this.renderer_)return;const n=this.getCoordinateFromPixelInternal(e),i=void 0!==(r=void 0!==r?r:{}).hitTolerance?r.hitTolerance:0,o=void 0!==r.layerFilter?r.layerFilter:TRUE,s=!1!==r.checkWrapped;return this.renderer_.forEachFeatureAtCoordinate(n,this.frameState_,i,s,t,null,o,null)}getFeaturesAtPixel(e,t){const r=[];return this.forEachFeatureAtPixel(e,function(e){r.push(e)},t),r}getAllLayers(){const e=[];return function t(r){r.forEach(function(r){r instanceof LayerGroup?t(r.getLayers()):e.push(r)})}(this.getLayers()),e}hasFeatureAtPixel(e,t){if(!this.frameState_||!this.renderer_)return!1;const r=this.getCoordinateFromPixelInternal(e),n=void 0!==(t=void 0!==t?t:{}).layerFilter?t.layerFilter:TRUE,i=void 0!==t.hitTolerance?t.hitTolerance:0,o=!1!==t.checkWrapped;return this.renderer_.hasFeatureAtCoordinate(r,this.frameState_,i,o,n,null)}getEventCoordinate(e){return this.getCoordinateFromPixel(this.getEventPixel(e))}getEventCoordinateInternal(e){return this.getCoordinateFromPixelInternal(this.getEventPixel(e))}getEventPixel(e){const t=this.viewport_.getBoundingClientRect(),r=this.getSize(),n=t.width/r[0],i=t.height/r[1],o="changedTouches"in e?e.changedTouches[0]:e;return[(o.clientX-t.left)/n,(o.clientY-t.top)/i]}getTarget(){return this.get(MapProperty.TARGET)}getTargetElement(){return this.targetElement_}getCoordinateFromPixel(e){return toUserCoordinate(this.getCoordinateFromPixelInternal(e),this.getView().getProjection())}getCoordinateFromPixelInternal(e){const t=this.frameState_;return t?apply$1(t.pixelToCoordinateTransform,e.slice()):null}getControls(){return this.controls}getOverlays(){return this.overlays_}getOverlayById(e){const t=this.overlayIdIndex_[e.toString()];return void 0!==t?t:null}getInteractions(){return this.interactions}getLayerGroup(){return this.get(MapProperty.LAYERGROUP)}setLayers(e){const t=this.getLayerGroup();if(e instanceof Collection)return void t.setLayers(e);const r=t.getLayers();r.clear(),r.extend(e)}getLayers(){return this.getLayerGroup().getLayers()}getLoadingOrNotReady(){const e=this.getLayerGroup().getLayerStatesArray();for(let t=0,r=e.length;t=0;r--){const n=t[r];if(n.getMap()===this&&n.getActive()&&this.getTargetElement()&&(!n.handleEvent(e)||e.propagationStopped))break}}}handlePostRender(){const e=this.frameState_,t=this.tileQueue_;if(!t.isEmpty()){let r=this.maxTilesLoading_,n=r;if(e){const t=e.viewHints;if(t[ViewHint.ANIMATING]||t[ViewHint.INTERACTING]){const t=Date.now()-e.time>8;r=t?0:8,n=t?0:2}}t.getTilesLoading(){this.postRenderTimeoutHandle_=void 0,this.handlePostRender()},0))}setLayerGroup(e){const t=this.getLayerGroup();t&&this.handleLayerRemove_(new GroupEvent("removelayer",t)),this.set(MapProperty.LAYERGROUP,e)}setSize(e){this.set(MapProperty.SIZE,e)}setTarget(e){this.set(MapProperty.TARGET,e)}setView(e){if(!e||e instanceof View)return void this.set(MapProperty.VIEW,e);this.set(MapProperty.VIEW,new View);const t=this;e.then(function(e){t.setView(new View(e))})}updateSize(){const e=this.getTargetElement();let t;if(e){let r,n;if(isCanvas(e))r=e.width,n=e.height;else{const t=getComputedStyle(e);r=e.offsetWidth-parseFloat(t.borderLeftWidth)-parseFloat(t.paddingLeft)-parseFloat(t.paddingRight)-parseFloat(t.borderRightWidth),n=e.offsetHeight-parseFloat(t.borderTopWidth)-parseFloat(t.paddingTop)-parseFloat(t.paddingBottom)-parseFloat(t.borderBottomWidth)}isNaN(r)||isNaN(n)||(t=[Math.max(0,r),Math.max(0,n)],!hasArea(t)&&(e.offsetWidth||e.offsetHeight||e.getClientRects().length)&&warn("No map visible because the map container's width or height are 0."))}const r=this.getSize();!t||r&&equals$2(t,r)||(this.setSize(t),this.updateViewportSize_(t))}updateViewportSize_(e){const t=this.getView();t&&t.setViewportSize(e)}};function createOptionsInternal(e){let t=null;void 0!==e.keyboardEventTarget&&(t="string"==typeof e.keyboardEventTarget?document.getElementById(e.keyboardEventTarget):e.keyboardEventTarget);const r={},n=e.layers&&"function"==typeof e.layers.getLayers?e.layers:new LayerGroup({layers:e.layers});let i,o,s;return r[MapProperty.LAYERGROUP]=n,r[MapProperty.TARGET]=e.target,r[MapProperty.VIEW]=e.view instanceof View?e.view:new View,void 0!==e.controls&&(Array.isArray(e.controls)?i=new Collection(e.controls.slice()):(assert$1("function"==typeof e.controls.getArray,"Expected `controls` to be an array or an `ol/Collection.js`"),i=e.controls)),void 0!==e.interactions&&(Array.isArray(e.interactions)?o=new Collection(e.interactions.slice()):(assert$1("function"==typeof e.interactions.getArray,"Expected `interactions` to be an array or an `ol/Collection.js`"),o=e.interactions)),void 0!==e.overlays?Array.isArray(e.overlays)?s=new Collection(e.overlays.slice()):(assert$1("function"==typeof e.overlays.getArray,"Expected `overlays` to be an array or an `ol/Collection.js`"),s=e.overlays):s=new Collection,{controls:i,interactions:o,keyboardEventTarget:t,overlays:s,values:r}}const Property$1={ELEMENT:"element",MAP:"map",OFFSET:"offset",POSITION:"position",POSITIONING:"positioning"};class Overlay extends BaseObject{constructor(e){super(),this.on,this.once,this.un,this.options=e,this.id=e.id,this.insertFirst=void 0===e.insertFirst||e.insertFirst,this.stopEvent=void 0===e.stopEvent||e.stopEvent,this.element=document.createElement("div"),this.element.className=void 0!==e.className?e.className:"ol-overlay-container "+CLASS_SELECTABLE,this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.autoPan=!0===e.autoPan?{}:e.autoPan||void 0,this.rendered={transform_:"",visible:!0},this.mapPostrenderListenerKey=null,this.addChangeListener(Property$1.ELEMENT,this.handleElementChanged),this.addChangeListener(Property$1.MAP,this.handleMapChanged),this.addChangeListener(Property$1.OFFSET,this.handleOffsetChanged),this.addChangeListener(Property$1.POSITION,this.handlePositionChanged),this.addChangeListener(Property$1.POSITIONING,this.handlePositioningChanged),void 0!==e.element&&this.setElement(e.element),this.setOffset(void 0!==e.offset?e.offset:[0,0]),this.setPositioning(e.positioning||"top-left"),void 0!==e.position&&this.setPosition(e.position)}getElement(){return this.get(Property$1.ELEMENT)}getId(){return this.id}getMap(){return this.get(Property$1.MAP)||null}getOffset(){return this.get(Property$1.OFFSET)}getPosition(){return this.get(Property$1.POSITION)}getPositioning(){return this.get(Property$1.POSITIONING)}handleElementChanged(){removeChildren(this.element);const e=this.getElement();e&&this.element.appendChild(e)}handleMapChanged(){this.mapPostrenderListenerKey&&(this.element?.remove(),unlistenByKey(this.mapPostrenderListenerKey),this.mapPostrenderListenerKey=null);const e=this.getMap();if(e){this.mapPostrenderListenerKey=listen(e,MapEventType.POSTRENDER,this.render,this),this.updatePixelPosition();const t=this.stopEvent?e.getOverlayContainerStopEvent():e.getOverlayContainer();this.insertFirst?t.insertBefore(this.element,t.childNodes[0]||null):t.appendChild(this.element),this.performAutoPan()}}render(){this.updatePixelPosition()}handleOffsetChanged(){this.updatePixelPosition()}handlePositionChanged(){this.updatePixelPosition(),this.performAutoPan()}handlePositioningChanged(){this.updatePixelPosition()}setElement(e){this.set(Property$1.ELEMENT,e)}setMap(e){this.set(Property$1.MAP,e)}setOffset(e){this.set(Property$1.OFFSET,e)}setPosition(e){this.set(Property$1.POSITION,e)}performAutoPan(){this.autoPan&&this.panIntoView(this.autoPan)}panIntoView(e){const t=this.getMap();if(!t||!t.getTargetElement()||!this.get(Property$1.POSITION))return;const r=this.getRect(t.getTargetElement(),t.getSize()),n=this.getElement(),i=this.getRect(n,[outerWidth(n),outerHeight(n)]),o=void 0===(e=e||{}).margin?20:e.margin;if(!containsExtent(r,i)){const n=i[0]-r[0],s=r[2]-i[2],a=i[1]-r[1],l=r[3]-i[3],c=[0,0];if(n<0?c[0]=n-o:s<0&&(c[0]=Math.abs(s)+o),a<0?c[1]=a-o:l<0&&(c[1]=Math.abs(l)+o),0!==c[0]||0!==c[1]){const r=t.getView().getCenterInternal(),n=t.getPixelFromCoordinateInternal(r);if(!n)return;const i=[n[0]+c[0],n[1]+c[1]],o=e.animation||{};t.getView().animateInternal({center:t.getCoordinateFromPixelInternal(i),duration:o.duration,easing:o.easing})}}}getRect(e,t){const r=e.getBoundingClientRect(),n=r.left+window.pageXOffset,i=r.top+window.pageYOffset;return[n,i,n+t[0],i+t[1]]}setPositioning(e){this.set(Property$1.POSITIONING,e)}setVisible(e){this.rendered.visible!==e&&(this.element.style.display=e?"":"none",this.rendered.visible=e)}updatePixelPosition(){const e=this.getMap(),t=this.getPosition();if(!e||!e.isRendered()||!t)return void this.setVisible(!1);const r=e.getPixelFromCoordinate(t),n=e.getSize();this.updateRenderedPosition(r,n)}updateRenderedPosition(e,t){const r=this.element.style,n=this.getOffset(),i=this.getPositioning();this.setVisible(!0);let o="0%",s="0%";"bottom-right"==i||"center-right"==i||"top-right"==i?o="-100%":"bottom-center"!=i&&"center-center"!=i&&"top-center"!=i||(o="-50%"),"bottom-left"==i||"bottom-center"==i||"bottom-right"==i?s="-100%":"center-left"!=i&&"center-center"!=i&&"center-right"!=i||(s="-50%");const a=`translate(${o}, ${s}) translate(${e[0]+n[0]}px, ${e[1]+n[1]}px)`;this.rendered.transform_!=a&&(this.rendered.transform_=a,r.transform=a)}getOptions(){return this.options}}class Feature extends BaseObject{constructor(e){if(super(),this.on,this.once,this.un,this.id_=void 0,this.geometryName_="geometry",this.style_=null,this.styleFunction_=void 0,this.geometryChangeKey_=null,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),e)if("function"==typeof e.getSimplifiedGeometry){const t=e;this.setGeometry(t)}else{const t=e;this.setProperties(t)}}clone(){const e=new Feature(this.hasProperties()?this.getProperties():null);e.setGeometryName(this.getGeometryName());const t=this.getGeometry();t&&e.setGeometry(t.clone());const r=this.getStyle();return r&&e.setStyle(r),e}getGeometry(){return this.get(this.geometryName_)}getId(){return this.id_}getGeometryName(){return this.geometryName_}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}handleGeometryChange_(){this.changed()}handleGeometryChanged_(){this.geometryChangeKey_&&(unlistenByKey(this.geometryChangeKey_),this.geometryChangeKey_=null);const e=this.getGeometry();e&&(this.geometryChangeKey_=listen(e,EventType$1.CHANGE,this.handleGeometryChange_,this)),this.changed()}setGeometry(e){this.set(this.geometryName_,e)}setStyle(e){this.style_=e,this.styleFunction_=e?createStyleFunction(e):void 0,this.changed()}setId(e){this.id_=e,this.changed()}setGeometryName(e){this.removeChangeListener(this.geometryName_,this.handleGeometryChanged_),this.geometryName_=e,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),this.handleGeometryChanged_()}}function createStyleFunction(e){if("function"==typeof e)return e;let t;return Array.isArray(e)?t=e:(assert$1("function"==typeof e.getZIndex,"Expected an `ol/style/Style` or an array of `ol/style/Style.js`"),t=[e]),function(){return t}}function interpolatePoint(e,t,r,n,i,o,s){let a,l;const c=(r-t)/n;if(1===c)a=t;else if(2===c)a=t,l=i;else if(0!==c){let o=e[t],s=e[t+1],c=0;const u=[0];for(let i=t+n;i1?s:2,o=o||new Array(s);for(let u=0;u>1;ia&&(this.instructions.push([Instruction.CUSTOM,a,c,e,r,inflateCoordinates,i]),this.hitDetectionInstructions.push([Instruction.CUSTOM,a,c,e,n||r,inflateCoordinates,i]));break;case"Point":l=e.getFlatCoordinates(),this.coordinates.push(l[0],l[1]),c=this.coordinates.length,this.instructions.push([Instruction.CUSTOM,a,c,e,r,void 0,i]),this.hitDetectionInstructions.push([Instruction.CUSTOM,a,c,e,n||r,void 0,i])}this.endGeometry(t)}beginGeometry(e,t,r){this.beginGeometryInstruction1_=[Instruction.BEGIN_GEOMETRY,t,0,e,r],this.instructions.push(this.beginGeometryInstruction1_),this.beginGeometryInstruction2_=[Instruction.BEGIN_GEOMETRY,t,0,e,r],this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)}finish(){return{instructions:this.instructions,hitDetectionInstructions:this.hitDetectionInstructions,coordinates:this.coordinates}}reverseHitDetectionInstructions(){const e=this.hitDetectionInstructions;let t;e.reverse();const r=e.length;let n,i,o=-1;for(t=0;tthis.maxLineWidth&&(this.maxLineWidth=t.lineWidth,this.bufferedMaxExtent_=null)}else t.strokeStyle=void 0,t.lineCap=void 0,t.lineDash=null,t.lineDashOffset=void 0,t.lineJoin=void 0,t.lineWidth=void 0,t.miterLimit=void 0;return t}setFillStrokeStyle(e,t){const r=this.state;this.fillStyleToState(e,r),this.strokeStyleToState(t,r)}createFill(e){const t=e.fillStyle,r=[Instruction.SET_FILL_STYLE,t];return"string"!=typeof t&&r.push(e.fillPatternScale),r}applyStroke(e){this.instructions.push(this.createStroke(e))}createStroke(e){return[Instruction.SET_STROKE_STYLE,e.strokeStyle,e.lineWidth*this.pixelRatio,e.lineCap,e.lineJoin,e.miterLimit,e.lineDash?this.applyPixelRatio(e.lineDash):null,e.lineDashOffset*this.pixelRatio]}updateFillStyle(e,t){const r=e.fillStyle;"string"==typeof r&&e.currentFillStyle==r||(this.instructions.push(t.call(this,e)),e.currentFillStyle=r)}updateStrokeStyle(e,t){const r=e.strokeStyle,n=e.lineCap,i=e.lineDash,o=e.lineDashOffset,s=e.lineJoin,a=e.lineWidth,l=e.miterLimit;(e.currentStrokeStyle!=r||e.currentLineCap!=n||i!=e.currentLineDash&&!equals$2(e.currentLineDash,i)||e.currentLineDashOffset!=o||e.currentLineJoin!=s||e.currentLineWidth!=a||e.currentMiterLimit!=l)&&(t.call(this,e),e.currentStrokeStyle=r,e.currentLineCap=n,e.currentLineDash=i,e.currentLineDashOffset=o,e.currentLineJoin=s,e.currentLineWidth=a,e.currentMiterLimit=l)}endGeometry(e){this.beginGeometryInstruction1_[2]=this.instructions.length,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length,this.beginGeometryInstruction2_=null;const t=[Instruction.END_GEOMETRY,e];this.instructions.push(t),this.hitDetectionInstructions.push(t)}getBufferedMaxExtent(){if(!this.bufferedMaxExtent_&&(this.bufferedMaxExtent_=clone(this.maxExtent),this.maxLineWidth>0)){const e=this.resolution*(this.maxLineWidth+1)/2;buffer(this.bufferedMaxExtent_,e,this.bufferedMaxExtent_)}return this.bufferedMaxExtent_}}class CanvasImageBuilder extends CanvasBuilder{constructor(e,t,r,n){super(e,t,r,n),this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.anchorX_=void 0,this.anchorY_=void 0,this.height_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.scale_=void 0,this.width_=void 0,this.declutterMode_=void 0,this.declutterImageWithText_=void 0}drawPoint(e,t,r){if(!this.image_||this.maxExtent&&!containsCoordinate(this.maxExtent,e.getFlatCoordinates()))return;this.beginGeometry(e,t,r);const n=e.getFlatCoordinates(),i=e.getStride(),o=this.coordinates.length,s=this.appendFlatPointCoordinates(n,i);this.instructions.push([Instruction.DRAW_IMAGE,o,s,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([Instruction.DRAW_IMAGE,o,s,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(t)}drawMultiPoint(e,t,r){if(!this.image_)return;this.beginGeometry(e,t,r);const n=e.getFlatCoordinates(),i=[];for(let a=0,l=n.length;a=e){const t=(e-a+h)/h,d=lerp(r,c,t),p=lerp(n,u,t);l.push(d,p),o.push(l),l=[d,p],a==e&&(s+=i),a=0}else if(a0&&o.push(l),o}function matchingChunk(e,t,r,n,i){let o,s,a,l,c,u,h,d,p,f,g=r,m=r,y=0,b=0,v=r;for(s=r;se&&(b>y&&(y=b,g=v,m=s),b=0,v=s-i)),a=l,h=p,d=f),c=r,u=n}return b+=l,b>y?[v,s]:[g,m]}const TEXT_ALIGN={left:0,center:.5,right:1,top:0,middle:.5,hanging:.2,alphabetic:.8,ideographic:.8,bottom:1};class CanvasTextBuilder extends CanvasBuilder{constructor(e,t,r,n){super(e,t,r,n),this.labels_=null,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=void 0,this.textKeepUpright_=void 0,this.textRotation_=0,this.textFillState_=null,this.fillStates={},this.fillStates[defaultFillStyle]={fillStyle:defaultFillStyle},this.textStrokeState_=null,this.strokeStates={},this.textState_={},this.textStates={},this.textKey_="",this.fillKey_="",this.strokeKey_="",this.declutterMode_=void 0,this.declutterImageWithText_=void 0}finish(){const e=super.finish();return e.textStates=this.textStates,e.fillStates=this.fillStates,e.strokeStates=this.strokeStates,e}drawText(e,t,r){const n=this.textFillState_,i=this.textStrokeState_,o=this.textState_;if(""===this.text_||!o||!n&&!i)return;const s=this.coordinates;let a=s.length;const l=e.getType();let c=null,u=e.getStride();if("line"!==o.placement||"LineString"!=l&&"MultiLineString"!=l&&"Polygon"!=l&&"MultiPolygon"!=l){let n=o.overflow?null:[];switch(l){case"Point":case"MultiPoint":c=e.getFlatCoordinates();break;case"LineString":c=e.getFlatMidpoint();break;case"Circle":c=e.getCenter();break;case"MultiLineString":c=e.getFlatMidpoints(),u=2;break;case"Polygon":c=e.getFlatInteriorPoint(),o.overflow||n.push(c[2]/this.resolution),u=3;break;case"MultiPolygon":const t=e.getFlatInteriorPoints();c=[];for(let e=0,r=t.length;e{const n=s[2*(e+r)]===c[r*u]&&s[2*(e+r)+1]===c[r*u+1];return n||--e,n})}this.saveTextStates_();const h=o.backgroundFill?this.createFill(this.fillStyleToState(o.backgroundFill)):null,d=o.backgroundStroke?this.createStroke(this.strokeStyleToState(o.backgroundStroke)):null;this.beginGeometry(e,t,r);let p=o.padding;if(p!=defaultPadding&&(o.scale[0]<0||o.scale[1]<0)){let e=o.padding[0],t=o.padding[1],r=o.padding[2],n=o.padding[3];o.scale[0]<0&&(t=-t,n=-n),o.scale[1]<0&&(e=-e,r=-r),p=[e,t,r,n]}const f=this.pixelRatio;this.instructions.push([Instruction.DRAW_IMAGE,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[1,1],NaN,this.declutterMode_,this.declutterImageWithText_,p==defaultPadding?defaultPadding:p.map(function(e){return e*f}),h,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_,this.textOffsetX_,this.textOffsetY_,n]);const g=1/f,m=h?h.slice(0):null;m&&(m[1]=defaultFillStyle),this.hitDetectionInstructions.push([Instruction.DRAW_IMAGE,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[g,g],NaN,this.declutterMode_,this.declutterImageWithText_,p,m,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_?defaultFillStyle:this.fillKey_,this.textOffsetX_,this.textOffsetY_,n]),this.endGeometry(t)}else{if(!intersects$1(this.maxExtent,e.getExtent()))return;let n;if(c=e.getFlatCoordinates(),"LineString"==l)n=[c.length];else if("MultiLineString"==l)n=e.getEnds();else if("Polygon"==l)n=e.getEnds().slice(0,1);else if("MultiPolygon"==l){const t=e.getEndss();n=[];for(let e=0,r=t.length;ee[2]}else A=E>x;const I=Math.PI,P=[],k=C+n===t;let O;if(y=0,b=S,p=e[t=C],f=e[t+1],k){v(),O=Math.atan2(f-m,p-g),A&&(O+=O>0?-I:I);const e=(x+E)/2,t=(R+w)/2;return P[0]=[e,t,(T-o)/2,O,i],P}for(let L=0,M=(i=i.replace(/\n/g," ")).length;L0?-I:I),void 0!==O){let t=e-O;if(t+=t>I?-2*I:t<-I?2*I:0,Math.abs(t)>s)return null}O=e;const h=L;let d=0;for(;L{if("function"==typeof getSharedCanvasContext2D()[t])return this.push_(t),this.pushMethodArgs_},set:(e,t,r)=>(this.push_(t,r),!0)})}push_(...e){const t=this.instructions_,r=this.zIndex+this.offset_;t[r]||(t[r]=[]),t[r].push(...e)}pushMethodArgs_=(...e)=>(this.push_(e),this);pushFunction(e){this.push_(e)}getContext(){return this.context_}draw(e){this.instructions_.forEach(t=>{for(let r=0,n=t.length;r0&&e.push("\n",""),e.push(t,""),e}function richTextToPlainText(e,t,r){return r%2==0&&(e+=t),e}class Executor{constructor(e,t,r,n,i){this.overlaps=r,this.pixelRatio=t,this.resolution=e,this.alignAndScaleFill_,this.instructions=n.instructions,this.coordinates=n.coordinates,this.coordinateCache_={},this.renderedTransform_=create(),this.hitDetectionInstructions=n.hitDetectionInstructions,this.pixelCoordinates_=null,this.viewRotation_=0,this.fillStates=n.fillStates||{},this.strokeStates=n.strokeStates||{},this.textStates=n.textStates||{},this.widths_={},this.labels_={},this.zIndexContext_=i?new ZIndexContext:null}getZIndexContext(){return this.zIndexContext_}createLabel(e,t,r,n){const i=e+t+r+n;if(this.labels_[i])return this.labels_[i];const o=n?this.strokeStates[n]:null,s=r?this.fillStates[r]:null,a=this.textStates[t],l=this.pixelRatio,c=[a.scale[0]*l,a.scale[1]*l],u=a.justify?TEXT_ALIGN[a.justify]:horizontalTextAlign(Array.isArray(e)?e[0]:e,a.textAlign||defaultTextAlign),h=n&&o.lineWidth?o.lineWidth:0,d=Array.isArray(e)?e:String(e).split("\n").reduce(createTextChunks,[]),{width:p,height:f,widths:g,heights:m,lineWidths:y}=getTextDimensions(a,d),b=p+h,v=[],_=(b+2)*c[0],E=(f+h)*c[1],w={width:_<0?Math.floor(_):Math.ceil(_),height:E<0?Math.floor(E):Math.ceil(E),contextInstructions:v};1==c[0]&&1==c[1]||v.push("scale",c),n&&(v.push("strokeStyle",o.strokeStyle),v.push("lineWidth",h),v.push("lineCap",o.lineCap),v.push("lineJoin",o.lineJoin),v.push("miterLimit",o.miterLimit),v.push("setLineDash",[o.lineDash]),v.push("lineDashOffset",o.lineDashOffset)),r&&v.push("fillStyle",s.fillStyle),v.push("textBaseline","middle"),v.push("textAlign","center");const C=.5-u;let S=u*b+C*h;const T=[],x=[];let R,A=0,I=0,P=0,k=0;for(let O=0,L=d.length;Oe?e-l:i,v=o+c>t?t-c:o,_=p[3]+b*h[0]+p[1],E=p[0]+v*h[1]+p[2],w=m-p[3],C=y-p[0];let S;return(f||0!==u)&&(p1[0]=w,p4[0]=w,p1[1]=C,p2[1]=C,p2[0]=w+_,p3[0]=p2[0],p3[1]=C+E,p4[1]=p3[1]),0!==u?(S=compose(create(),r,n,1,1,u,-r,-n),apply$1(S,p1),apply$1(S,p2),apply$1(S,p3),apply$1(S,p4),createOrUpdate$2(Math.min(p1[0],p2[0],p3[0],p4[0]),Math.min(p1[1],p2[1],p3[1],p4[1]),Math.max(p1[0],p2[0],p3[0],p4[0]),Math.max(p1[1],p2[1],p3[1],p4[1]),tmpExtent)):createOrUpdate$2(Math.min(w,w+_),Math.min(C,C+E),Math.max(w,w+_),Math.max(C,C+E),tmpExtent),d&&(m=Math.round(m),y=Math.round(y)),{drawImageX:m,drawImageY:y,drawImageW:b,drawImageH:v,originX:l,originY:c,declutterBox:{minX:tmpExtent[0],minY:tmpExtent[1],maxX:tmpExtent[2],maxY:tmpExtent[3],value:g},canvasTransform:S,scale:h}}replayImageOrLabel_(e,t,r,n,i,o,s){const a=!(!o&&!s),l=n.declutterBox,c=s?s[2]*n.scale[0]/2:0;return l.minX-c<=t[0]&&l.maxX+c>=0&&l.minY-c<=t[1]&&l.maxY+c>=0&&(a&&this.replayTextBackground_(e,p1,p2,p3,p4,o,s),drawImageOrLabel(e,n.canvasTransform,i,r,n.originX,n.originY,n.drawImageW,n.drawImageH,n.drawImageX,n.drawImageY,n.scale)),!0}fill_(e){const t=this.alignAndScaleFill_;if(t){const r=apply$1(this.renderedTransform_,[0,0]),n=512*this.pixelRatio;e.save(),e.translate(r[0]%n,r[1]%n),1!==t&&e.scale(t,t),e.rotate(this.viewRotation_)}e.fill(),t&&e.restore()}setStrokeStyle_(e,t){e.strokeStyle=t[1],t[1]&&(e.lineWidth=t[2],e.lineCap=t[3],e.lineJoin=t[4],e.miterLimit=t[5],e.lineDashOffset=t[7],e.setLineDash(t[6]))}drawLabelWithPointPlacement_(e,t,r,n){const i=this.textStates[t],o=this.createLabel(e,t,n,r),s=this.strokeStates[r],a=this.pixelRatio,l=horizontalTextAlign(Array.isArray(e)?e[0]:e,i.textAlign||defaultTextAlign),c=TEXT_ALIGN[i.textBaseline||defaultTextBaseline],u=s&&s.lineWidth?s.lineWidth:0;return{label:o,anchorX:l*(o.width/a-2*i.scale[0])+2*(.5-l)*u,anchorY:c*o.height/a+2*(.5-c)*u}}execute_(e,t,r,n,i,o,s,a){const l=this.zIndexContext_;let c;this.pixelCoordinates_&&equals$2(r,this.renderedTransform_)?c=this.pixelCoordinates_:(this.pixelCoordinates_||(this.pixelCoordinates_=[]),c=transform2D(this.coordinates,0,this.coordinates.length,2,r,this.pixelCoordinates_),setFromArray(this.renderedTransform_,r));let u=0;const h=n.length;let d,p,f,g,m,y,b,v,_,E,w,C,S,T=0,x=0,R=0;const A=this.coordinateCache_,I=this.viewRotation_,P=Math.round(1e12*Math.atan2(-r[1],r[0]))/1e12,k={context:e,pixelRatio:this.pixelRatio,resolution:this.resolution,rotation:I},O=this.instructions!=n||this.overlaps?0:200;let L,M,D,N;for(;uO&&(this.fill_(e),x=0),R>O&&(e.stroke(),R=0),x||R||(e.beginPath(),m=NaN,y=NaN),++u;break;case Instruction.CIRCLE:T=r[1];const n=c[T],h=c[T+1],F=c[T+2]-n,$=c[T+3]-h,B=Math.sqrt(F*F+$*$);e.moveTo(n+B,h),e.arc(n,h,B,0,2*Math.PI,!0),++u;break;case Instruction.CLOSE_PATH:e.closePath(),++u;break;case Instruction.CUSTOM:T=r[1],d=r[2];const U=r[3],z=r[4],j=r[5];k.geometry=U,k.feature=L,u in A||(A[u]=[]);const V=A[u];j?j(c,T,d,2,V):(V[0]=c[T],V[1]=c[T+1],V.length=2),l&&(l.zIndex=r[6]),z(V,k),++u;break;case Instruction.DRAW_IMAGE:T=r[1],d=r[2],_=r[3],p=r[4],f=r[5];let G=r[6];const H=r[7],q=r[8],W=r[9],K=r[10];let Y=r[11];const Z=r[12];let X=r[13];g=r[14]||"declutter";const J=r[15];if(!_&&r.length>=20){E=r[19],w=r[20],C=r[21],S=r[22];const e=this.drawLabelWithPointPlacement_(E,w,C,S);_=e.label,r[3]=_;const t=r[23];p=(e.anchorX-t)*this.pixelRatio,r[4]=p;const n=r[24];f=(e.anchorY-n)*this.pixelRatio,r[5]=f,G=_.height,r[6]=G,X=_.width,r[13]=X}let Q,ee,te,re;r.length>25&&(Q=r[25]),r.length>17?(ee=r[16],te=r[17],re=r[18]):(ee=defaultPadding,te=null,re=null),K&&P?Y+=I:K||P||(Y-=I);let ne=0;for(;T!DECLUTTER.includes(e));class ExecutorGroup{constructor(e,t,r,n,i,o,s){this.maxExtent_=e,this.overlaps_=n,this.pixelRatio_=r,this.resolution_=t,this.renderBuffer_=o,this.executorsByZIndex_={},this.hitDetectionContext_=null,this.hitDetectionTransform_=create(),this.renderedContext_=null,this.deferredZIndexContexts_={},this.createExecutors_(i,s)}clip(e,t){const r=this.getClipCoords(t);e.beginPath(),e.moveTo(r[0],r[1]),e.lineTo(r[2],r[3]),e.lineTo(r[4],r[5]),e.lineTo(r[6],r[7]),e.clip()}createExecutors_(e,t){for(const r in e){let n=this.executorsByZIndex_[r];void 0===n&&(n={},this.executorsByZIndex_[r]=n);const i=e[r];for(const e in i){const r=i[e];n[e]=new Executor(this.resolution_,this.pixelRatio_,this.overlaps_,r,t)}}}hasExecutors(e){for(const t in this.executorsByZIndex_){const r=this.executorsByZIndex_[t];for(let t=0,n=e.length;t0){if(!o||"none"===r||"Image"!==d&&"Text"!==d||o.includes(e)){const r=(h[l]-3)/4,o=n-r%s,a=n-(r/s|0),c=i(e,t,o*o+a*a);if(c)return c}c.clearRect(0,0,s,s);break}}const f=Object.keys(this.executorsByZIndex_).map(Number);let g,m,y,b,v;for(f.sort(ascending),g=f.length-1;g>=0;--g){const e=f[g].toString();for(y=this.executorsByZIndex_[e],m=ALL.length-1;m>=0;--m)if(d=ALL[m],b=y[d],void 0!==b&&(v=b.executeHitDetection(c,a,r,p,u),v))return v}}getClipCoords(e){const t=this.maxExtent_;if(!t)return null;const r=t[0],n=t[1],i=t[2],o=t[3],s=[r,n,r,o,i,o,i,n];return transform2D(s,0,8,2,e,s),s}isEmpty(){return isEmpty$1(this.executorsByZIndex_)}execute(e,t,r,n,i,o,s){const a=Object.keys(this.executorsByZIndex_).map(Number);a.sort(s?descending:ascending),o=o||ALL;const l=ALL.length;for(let c=0,u=a.length;cp.execute(e,t,r,n,i,s)):p.execute(h,t,r,n,i,s),d&&h.restore(),o){o.offset();const e=a[c]*l+ALL.indexOf(u);this.deferredZIndexContexts_[e]||(this.deferredZIndexContexts_[e]=[]),this.deferredZIndexContexts_[e].push(o)}}}}this.renderedContext_=e}getDeferredZIndexContexts(){return this.deferredZIndexContexts_}getRenderedContext(){return this.renderedContext_}renderDeferred(){const e=this.deferredZIndexContexts_,t=Object.keys(e).map(Number).sort(ascending);for(let r=0,n=t.length;r{e.draw(this.renderedContext_),e.clear()}),e[t[r]].length=0}}const circlePixelIndexArrayCache={};function getPixelIndexArray(e){if(void 0!==circlePixelIndexArrayCache[e])return circlePixelIndexArrayCache[e];const t=2*e+1,r=e*e,n=new Array(r+1);for(let o=0;o<=e;++o)for(let i=0;i<=e;++i){const s=o*o+i*i;if(s>r)break;let a=n[s];a||(a=[],n[s]=a),a.push(4*((e+o)*t+(e+i))+3),o>0&&a.push(4*((e-o)*t+(e+i))+3),i>0&&(a.push(4*((e+o)*t+(e-i))+3),o>0&&a.push(4*((e-o)*t+(e-i))+3))}const i=[];for(let o=0,s=n.length;oe*this.pixelRatio_),lineDashOffset:(i||defaultLineDashOffset)*this.pixelRatio_,lineJoin:void 0!==o?o:defaultLineJoin,lineWidth:(void 0!==s?s:defaultLineWidth)*this.pixelRatio_,miterLimit:void 0!==a?a:defaultMiterLimit,strokeStyle:asColorLike(e||defaultStrokeStyle)}}else this.strokeState_=null}setImageStyle(e){let t;if(!e||!(t=e.getSize()))return void(this.image_=null);const r=e.getPixelRatio(this.pixelRatio_),n=e.getAnchor(),i=e.getOrigin();this.image_=e.getImage(this.pixelRatio_),this.imageAnchorX_=n[0]*r,this.imageAnchorY_=n[1]*r,this.imageHeight_=t[1]*r,this.imageOpacity_=e.getOpacity(),this.imageOriginX_=i[0],this.imageOriginY_=i[1],this.imageRotateWithView_=e.getRotateWithView(),this.imageRotation_=e.getRotation();const o=e.getScaleArray();this.imageScale_=[o[0]*this.pixelRatio_/r,o[1]*this.pixelRatio_/r],this.imageWidth_=t[0]*r}setTextStyle(e){if(e){const t=e.getFill();if(t){const e=t.getColor();this.textFillState_={fillStyle:asColorLike(e||defaultFillStyle)}}else this.textFillState_=null;const r=e.getStroke();if(r){const e=r.getColor(),t=r.getLineCap(),n=r.getLineDash(),i=r.getLineDashOffset(),o=r.getLineJoin(),s=r.getWidth(),a=r.getMiterLimit();this.textStrokeState_={lineCap:void 0!==t?t:defaultLineCap,lineDash:n||defaultLineDash,lineDashOffset:i||defaultLineDashOffset,lineJoin:void 0!==o?o:defaultLineJoin,lineWidth:void 0!==s?s:defaultLineWidth,miterLimit:void 0!==a?a:defaultMiterLimit,strokeStyle:asColorLike(e||defaultStrokeStyle)}}else this.textStrokeState_=null;const n=e.getFont(),i=e.getOffsetX(),o=e.getOffsetY(),s=e.getRotateWithView(),a=e.getRotation(),l=e.getScaleArray(),c=e.getText(),u=e.getTextAlign(),h=e.getTextBaseline();this.textState_={font:void 0!==n?n:defaultFont,textAlign:void 0!==u?u:defaultTextAlign,textBaseline:void 0!==h?h:defaultTextBaseline},this.text_=void 0!==c?Array.isArray(c)?c.reduce((e,t,r)=>e+(r%2?" ":t),""):c:"",this.textOffsetX_=void 0!==i?this.pixelRatio_*i:0,this.textOffsetY_=void 0!==o?this.pixelRatio_*o:0,this.textRotateWithView_=void 0!==s&&s,this.textRotation_=void 0!==a?a:0,this.textScale_=[this.pixelRatio_*l[0],this.pixelRatio_*l[1]]}else this.text_=""}}const HIT_DETECT_RESOLUTION=.5;function createHitDetectionImageData(e,t,r,n,i,o,s,a,l){const c=l?toUserExtent(i):i,u=createCanvasContext2D(e[0]*HIT_DETECT_RESOLUTION,e[1]*HIT_DETECT_RESOLUTION);u.imageSmoothingEnabled=!1;const h=u.canvas,d=new CanvasImmediateRenderer(u,HIT_DETECT_RESOLUTION,i,null,s,a,l?getTransformFromProjections(getUserProjection(),l):null),p=r.length,f=Math.floor(16777215/p),g={};for(let y=1;y<=p;++y){const e=r[y-1],t=e.getStyleFunction()||n;if(!t)continue;let i=t(e,o);if(!i)continue;Array.isArray(i)||(i=[i]);const s=(y*f).toString(16).padStart(7,"#00000");for(let r=0,n=i.length;r0;return h&&Promise.all(l).then(()=>i(null)),renderFeatureInternal(e,t,r,n,o,s,a),h}function renderFeatureInternal(e,t,r,n,i,o,s){const a=r.getGeometryFunction()(t);if(!a)return;const l=a.simplifyTransformed(n,i);r.getRenderer()?renderGeometry(e,l,r,t,s):(0,GEOMETRY_RENDERERS[l.getType()])(e,l,r,t,s,o)}function renderGeometry(e,t,r,n,i){if("GeometryCollection"==t.getType()){const o=t.getGeometries();for(let t=0,s=o.length;tthis.maxStaleKeys&&(this.staleKeys_.length=this.maxStaleKeys)}getFeatures(e){return abstract()}getData(e){return null}prepareFrame(e){return abstract()}renderFrame(e,t){return abstract()}forEachFeatureAtCoordinate(e,t,r,n,i){}getLayer(){return this.layer_}handleFontsChanged(){}handleImageChange_(e){const t=e.target;t.getState()!==ImageState.LOADED&&t.getState()!==ImageState.ERROR||this.renderIfReadyAndVisible()}loadImage(e){let t=e.getState();return t!=ImageState.LOADED&&t!=ImageState.ERROR&&e.addEventListener(EventType$1.CHANGE,this.boundHandleImageChange_),t==ImageState.IDLE&&(e.load(),t=e.getState()),t==ImageState.LOADED}renderIfReadyAndVisible(){const e=this.getLayer();e&&e.getVisible()&&"ready"===e.getSourceState()&&e.changed()}renderDeferred(e){}disposeInternal(){delete this.layer_,super.disposeInternal()}}const canvasPool$2=[];let pixelContext=null;function createPixelContext(){pixelContext=createCanvasContext2D(1,1,void 0,{willReadFrequently:!0})}class CanvasLayerRenderer extends LayerRenderer{constructor(e){super(e),this.container=null,this.renderedResolution,this.tempTransform=create(),this.pixelTransform=create(),this.inversePixelTransform=create(),this.context=null,this.deferredContext_=null,this.containerReused=!1,this.frameState=null}getImageData(e,t,r){let n;pixelContext||createPixelContext(),pixelContext.clearRect(0,0,1,1);try{pixelContext.drawImage(e,t,r,1,1,0,0,1,1),n=pixelContext.getImageData(0,0,1,1).data}catch{return pixelContext=null,null}return n}getBackground(e){let t=this.getLayer().getBackground();return"function"==typeof t&&(t=t(e.viewState.resolution)),t||void 0}useContainer(e,t,r){const n=this.getLayer().getClassName();let i,o;if(e&&e.className===n&&(!r||e&&e.style.backgroundColor&&equals$2(asArray(e.style.backgroundColor),asArray(r)))){const t=e.firstElementChild;isCanvas(t)&&(o=t.getContext("2d"))}if(o&&equivalent(o.canvas.style.transform,t)?(this.container=e,this.context=o,this.containerReused=!0):this.containerReused?(this.container=null,this.context=null,this.containerReused=!1):this.container&&(this.container.style.backgroundColor=null),!this.container){i=WORKER_OFFSCREEN_CANVAS?createMockDiv():document.createElement("div"),i.className=n;let e=i.style;e.position="absolute",e.width="100%",e.height="100%",o=createCanvasContext2D();const t=o.canvas;i.appendChild(t),e=t.style,e.position="absolute",e.left="0",e.transformOrigin="top left",this.container=i,this.context=o}this.containerReused||!r||this.container.style.backgroundColor||(this.container.style.backgroundColor=r)}clipUnrotated(e,t,r){const n=getTopLeft(r),i=getTopRight(r),o=getBottomRight(r),s=getBottomLeft(r);apply$1(t.coordinateToPixelTransform,n),apply$1(t.coordinateToPixelTransform,i),apply$1(t.coordinateToPixelTransform,o),apply$1(t.coordinateToPixelTransform,s);const a=this.inversePixelTransform;apply$1(a,n),apply$1(a,i),apply$1(a,o),apply$1(a,s),e.save(),e.beginPath(),e.moveTo(Math.round(n[0]),Math.round(n[1])),e.lineTo(Math.round(i[0]),Math.round(i[1])),e.lineTo(Math.round(o[0]),Math.round(o[1])),e.lineTo(Math.round(s[0]),Math.round(s[1])),e.clip()}prepareContainer(e,t){const r=e.extent,n=e.viewState.resolution,i=e.viewState.rotation,o=e.pixelRatio,s=Math.round(getWidth(r)/n*o),a=Math.round(getHeight(r)/n*o);compose(this.pixelTransform,e.size[0]/2,e.size[1]/2,1/o,1/o,i,-s/2,-a/2),makeInverse(this.inversePixelTransform,this.pixelTransform);const l=toString$1(this.pixelTransform);if(this.useContainer(t,l,this.getBackground(e)),!this.containerReused){const e=this.context.canvas;e.width!=s||e.height!=a?(e.width=s,e.height=a):this.context.clearRect(0,0,s,a),l!==e.style.transform&&(e.style.transform=l)}}dispatchRenderEvent_(e,t,r){const n=this.getLayer();if(n.hasListener(e)){const i=new RenderEvent(e,this.inversePixelTransform,r,t);n.dispatchEvent(i)}}preRender(e,t){this.frameState=t,t.declutter||this.dispatchRenderEvent_(EventType.PRERENDER,e,t)}postRender(e,t){t.declutter||this.dispatchRenderEvent_(EventType.POSTRENDER,e,t)}renderDeferredInternal(e){}getRenderContext(e){return e.declutter&&!this.deferredContext_&&(this.deferredContext_=new ZIndexContext),e.declutter?this.deferredContext_.getContext():this.context}renderDeferred(e){e.declutter&&(this.dispatchRenderEvent_(EventType.PRERENDER,this.context,e),e.declutter&&this.deferredContext_&&(this.deferredContext_.draw(this.context),this.deferredContext_.clear()),this.renderDeferredInternal(e),this.dispatchRenderEvent_(EventType.POSTRENDER,this.context,e))}getRenderTransform(e,t,r,n,i,o,s){const a=i/2,l=o/2,c=n/t,u=-c,h=-e[0]+s,d=-e[1];return compose(this.tempTransform,a,l,c,u,-r,h,d)}disposeInternal(){delete this.frameState,super.disposeInternal()}}class CanvasVectorLayerRenderer extends CanvasLayerRenderer{constructor(e){super(e),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.animatingOrInteracting_,this.hitDetectionImageData_=null,this.clipped_=!1,this.renderedFeatures_=null,this.renderedRevision_=-1,this.renderedResolution_=NaN,this.renderedExtent_=createEmpty(),this.wrappedRenderedExtent_=createEmpty(),this.renderedRotation_,this.renderedCenter_=null,this.renderedProjection_=null,this.renderedPixelRatio_=1,this.renderedRenderOrder_=null,this.renderedFrameDeclutter_,this.replayGroup_=null,this.replayGroupChanged=!0,this.clipping=!0,this.targetContext_=null,this.opacity_=1}renderWorlds(e,t,r){const n=t.extent,i=t.viewState,o=i.center,s=i.resolution,a=i.projection,l=i.rotation,c=a.getExtent(),u=this.getLayer().getSource(),h=this.getLayer().getDeclutter(),d=t.pixelRatio,p=t.viewHints,f=!(p[ViewHint.ANIMATING]||p[ViewHint.INTERACTING]),g=this.context,m=Math.round(getWidth(n)/s*d),y=Math.round(getHeight(n)/s*d),b=u.getWrapX()&&a.canWrapX(),v=b?getWidth(c):null,_=b?Math.ceil((n[2]-c[2])/v)+1:1;let E=b?Math.floor((n[0]-c[0])/v):0;do{let n=this.getRenderTransform(o,s,0,d,m,y,E*v);t.declutter&&(n=n.slice(0)),e.execute(g,[g.canvas.width,g.canvas.height],n,l,f,void 0===r?ALL:r?DECLUTTER:NON_DECLUTTER,r?h&&t.declutter[h]:void 0)}while(++E<_)}setDrawContext_(){1!==this.opacity_&&(this.targetContext_=this.context,this.context=createCanvasContext2D(this.context.canvas.width,this.context.canvas.height,canvasPool$2))}resetDrawContext_(){if(1!==this.opacity_&&this.targetContext_){const e=this.targetContext_.globalAlpha;this.targetContext_.globalAlpha=this.opacity_,this.targetContext_.drawImage(this.context.canvas,0,0),this.targetContext_.globalAlpha=e,releaseCanvas(this.context),canvasPool$2.push(this.context.canvas),this.context=this.targetContext_,this.targetContext_=null}}renderDeclutter(e){this.replayGroup_&&this.getLayer().getDeclutter()&&this.renderWorlds(this.replayGroup_,e,!0)}renderDeferredInternal(e){this.replayGroup_&&(this.replayGroup_.renderDeferred(),this.clipped_&&this.context.restore(),this.resetDrawContext_())}renderFrame(e,t){const r=e.layerStatesArray[e.layerIndex];this.opacity_=r.opacity;const n=e.viewState;this.prepareContainer(e,t);const i=this.context,o=this.replayGroup_;let s=o&&!o.isEmpty();if(!s&&!this.getLayer().hasListener(EventType.PRERENDER)&&!this.getLayer().hasListener(EventType.POSTRENDER))return this.container;if(this.setDrawContext_(),this.preRender(i,e),n.projection,this.clipped_=!1,s&&r.extent&&this.clipping){const t=fromUserExtent(r.extent);s=intersects$1(t,e.extent),this.clipped_=s&&!containsExtent(t,e.extent),this.clipped_&&this.clipUnrotated(i,e,t)}return s&&this.renderWorlds(o,e,!this.getLayer().getDeclutter()&&void 0),!e.declutter&&this.clipped_&&i.restore(),this.postRender(i,e),this.renderedRotation_!==n.rotation&&(this.renderedRotation_=n.rotation,this.hitDetectionImageData_=null),e.declutter||this.resetDrawContext_(),this.container}getFeatures(e){return new Promise(t=>{if(this.frameState&&!this.hitDetectionImageData_&&!this.animatingOrInteracting_){const e=this.frameState.size.slice(),t=this.renderedCenter_,r=this.renderedResolution_,n=this.renderedRotation_,i=this.renderedProjection_,o=this.wrappedRenderedExtent_,s=this.getLayer(),a=[],l=e[0]*HIT_DETECT_RESOLUTION,c=e[1]*HIT_DETECT_RESOLUTION;a.push(this.getRenderTransform(t,r,n,HIT_DETECT_RESOLUTION,l,c,0).slice());const u=s.getSource(),h=i.getExtent();if(u.getWrapX()&&i.canWrapX()&&!containsExtent(h,o)){let e=o[0];const i=getWidth(h);let s,u=0;for(;eh[2];)++u,s=i*u,a.push(this.getRenderTransform(t,r,n,HIT_DETECT_RESOLUTION,l,c,s).slice()),e-=i}this.hitDetectionImageData_=createHitDetectionImageData(e,a,this.renderedFeatures_,s.getStyleFunction(),o,r,n,getSquaredTolerance(r,this.renderedPixelRatio_),null)}t(hitDetect(e,this.renderedFeatures_,this.hitDetectionImageData_))})}forEachFeatureAtCoordinate(e,t,r,n,i){if(!this.replayGroup_)return;const o=t.viewState.resolution,s=t.viewState.rotation,a=this.getLayer(),l={},c=this.getLayer().getDeclutter();return this.replayGroup_.forEachFeatureAtCoordinate(e,o,s,r,function(e,t,r){const o=getUid(e),s=l[o];if(s){if(!0!==s&&re.value):null)}handleFontsChanged(){const e=this.getLayer();e.getVisible()&&this.replayGroup_&&e.changed()}handleStyleImageChange_(e){this.renderIfReadyAndVisible()}prepareFrame(e){const t=this.getLayer(),r=t.getSource();if(!r)return!1;const n=e.viewHints[ViewHint.ANIMATING],i=e.viewHints[ViewHint.INTERACTING],o=t.getUpdateWhileAnimating(),s=t.getUpdateWhileInteracting();if(this.ready&&!o&&n||!s&&i)return this.animatingOrInteracting_=!0,!0;this.animatingOrInteracting_=!1;const a=e.extent,l=e.viewState,c=l.projection,u=l.resolution,h=e.pixelRatio,d=t.getRevision(),p=t.getRenderBuffer();let f=t.getRenderOrder();void 0===f&&(f=defaultOrder);const g=l.center.slice(),m=buffer(a,p*u),y=m.slice(),b=[m.slice()],v=c.getExtent();if(r.getWrapX()&&c.canWrapX()&&!containsExtent(v,e.extent)){const e=getWidth(v),t=Math.max(getWidth(m)/2,e);m[0]=v[0]-t,m[2]=v[2]+t,wrapX$1(g,c);const r=wrapX$2(b[0],c);r[0]v[0]&&r[2]>v[2]&&b.push([r[0]-e,r[1],r[2]-e,r[3]])}if(this.ready&&this.renderedResolution_==u&&this.renderedRevision_==d&&this.renderedRenderOrder_==f&&this.renderedFrameDeclutter_===!!e.declutter&&containsExtent(this.wrappedRenderedExtent_,m))return equals$2(this.renderedExtent_,y)||(this.hitDetectionImageData_=null,this.renderedExtent_=y),this.renderedCenter_=g,this.replayGroupChanged=!1,!0;this.replayGroup_=null;const _=new BuilderGroup(getTolerance(u,h),m,u,h);for(let A=0,I=b.length;A{let n;const i=e.getStyleFunction()||t.getStyleFunction();if(i&&(n=i(e,u)),n){const t=this.renderFeature(e,E,n,_,void 0,this.getLayer().getDeclutter(),r);w=w&&!t}},S=toUserExtent(m),T=r.getFeaturesInExtent(S);f&&T.sort(f);for(let A=0,I=T.length;A=200&&a.status<300){const e=t.getType();try{let n;"text"==e||"json"==e?n=a.responseText:"xml"==e?n=a.responseXML||a.responseText:"arraybuffer"==e&&(n=a.response),n?o(t.readFeatures(n,{extent:r,featureProjection:i}),t.readProjection(n)):s()}catch{s()}}else s()},a.onerror=s,a.send()}function xhr(e,t){return function(r,n,i,o,s){loadFeaturesXhr(e,t,r,n,i,e=>{this.addFeatures(e),void 0!==o&&o(e)},()=>{this.changed(),void 0!==s&&s()})}}function all(){return[[-1/0,-1/0,1/0,1/0]]}function bbox(e){return[e]}class GeometryCollection extends Geometry{constructor(e){super(),this.geometries_=e,this.changeEventsKeys_=[],this.listenGeometriesChange_()}unlistenGeometriesChange_(){this.changeEventsKeys_.forEach(unlistenByKey),this.changeEventsKeys_.length=0}listenGeometriesChange_(){const e=this.geometries_;for(let t=0,r=e.length;te.clone())}const tmpTransform=create();class RenderFeature{constructor(e,t,r,n,i,o){this.styleFunction,this.extent_,this.id_=o,this.type_=e,this.flatCoordinates_=t,this.flatInteriorPoints_=null,this.flatMidpoints_=null,this.ends_=r||null,this.properties_=i,this.squaredTolerance_,this.stride_=n,this.simplifiedGeometry_}get(e){return this.properties_[e]}getExtent(){return this.extent_||(this.extent_="Point"===this.type_?createOrUpdateFromCoordinate(this.flatCoordinates_):createOrUpdateFromFlatCoordinates(this.flatCoordinates_,0,this.flatCoordinates_.length,2)),this.extent_}getFlatInteriorPoint(){if(!this.flatInteriorPoints_){const e=getCenter(this.getExtent());this.flatInteriorPoints_=getInteriorPointOfArray(this.flatCoordinates_,0,this.ends_,2,e,0)}return this.flatInteriorPoints_}getFlatInteriorPoints(){if(!this.flatInteriorPoints_){const e=inflateEnds(this.flatCoordinates_,this.ends_),t=linearRingss(this.flatCoordinates_,0,e,2);this.flatInteriorPoints_=getInteriorPointsOfMultiArray(this.flatCoordinates_,0,e,2,t)}return this.flatInteriorPoints_}getFlatMidpoint(){return this.flatMidpoints_||(this.flatMidpoints_=interpolatePoint(this.flatCoordinates_,0,this.flatCoordinates_.length,2,.5)),this.flatMidpoints_}getFlatMidpoints(){if(!this.flatMidpoints_){this.flatMidpoints_=[];const e=this.flatCoordinates_;let t=0;const r=this.ends_;for(let n=0,i=r.length;n{if(e===this.squaredTolerance_)return this.simplifiedGeometry_;this.simplifiedGeometry_=this.clone(),t&&this.simplifiedGeometry_.applyTransform(t);const r=this.simplifiedGeometry_.getFlatCoordinates();let n;switch(this.type_){case"LineString":r.length=douglasPeucker(r,0,this.simplifiedGeometry_.flatCoordinates_.length,this.simplifiedGeometry_.stride_,e,r,0),n=[r.length];break;case"MultiLineString":n=[],r.length=douglasPeuckerArray(r,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,e,r,0,n);break;case"Polygon":n=[],r.length=quantizeArray(r,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,Math.sqrt(e),r,0,n)}return n&&(this.simplifiedGeometry_=new RenderFeature(this.type_,r,n,2,this.properties_,this.id_)),this.squaredTolerance_=e,this.simplifiedGeometry_}),this}}RenderFeature.prototype.getFlatCoordinates=RenderFeature.prototype.getOrientedFlatCoordinates;class RBush{constructor(e){this.rbush_=new RBush$1(e),this.items_={}}insert(e,t){const r={minX:e[0],minY:e[1],maxX:e[2],maxY:e[3],value:t};this.rbush_.insert(r),this.items_[getUid(t)]=r}load(e,t){const r=new Array(t.length);for(let n=0,i=t.length;ne):null}const VectorEventType={ADDFEATURE:"addfeature",CHANGEFEATURE:"changefeature",CLEAR:"clear",REMOVEFEATURE:"removefeature",FEATURESLOADSTART:"featuresloadstart",FEATURESLOADEND:"featuresloadend",FEATURESLOADERROR:"featuresloaderror"};class VectorSourceEvent extends BaseEvent{constructor(e,t,r){super(e),this.feature=t,this.features=r}}class VectorSource extends Source{constructor(e){super({attributions:(e=e||{}).attributions,interpolate:!0,projection:void 0,state:"ready",wrapX:void 0===e.wrapX||e.wrapX}),this.on,this.once,this.un,this.loader_=VOID,this.format_=e.format||null,this.overlaps_=void 0===e.overlaps||e.overlaps,this.url_=e.url,void 0!==e.loader?this.loader_=e.loader:void 0!==this.url_&&(assert$1(this.format_,"`format` must be set when `url` is set"),this.loader_=xhr(this.url_,this.format_)),this.strategy_=void 0!==e.strategy?e.strategy:all;const t=void 0===e.useSpatialIndex||e.useSpatialIndex;let r,n;this.featuresRtree_=t?new RBush:null,this.loadedExtentsRtree_=new RBush,this.loadingExtentsCount_=0,this.nullGeometryFeatures_={},this.idIndex_={},this.uidIndex_={},this.featureChangeKeys_={},this.featuresCollection_=null,Array.isArray(e.features)?n=e.features:e.features&&(r=e.features,n=r.getArray()),t||void 0!==r||(r=new Collection(n)),void 0!==n&&this.addFeaturesInternal(n),void 0!==r&&this.bindFeaturesCollection_(r)}addFeature(e){this.addFeatureInternal(e),this.changed()}addFeatureInternal(e){const t=getUid(e);if(!this.addToIndex_(t,e))return void(this.featuresCollection_&&this.featuresCollection_.remove(e));this.setupChangeEvents_(t,e);const r=e.getGeometry();if(r){const t=r.getExtent();this.featuresRtree_&&this.featuresRtree_.insert(t,e)}else this.nullGeometryFeatures_[t]=e;this.dispatchEvent(new VectorSourceEvent(VectorEventType.ADDFEATURE,e))}setupChangeEvents_(e,t){t instanceof RenderFeature||(this.featureChangeKeys_[e]=[listen(t,EventType$1.CHANGE,this.handleFeatureChange_,this),listen(t,ObjectEventType.PROPERTYCHANGE,this.handleFeatureChange_,this)])}addToIndex_(e,t){let r=!0;if(void 0!==t.getId()){const e=String(t.getId());if(e in this.idIndex_)if(t instanceof RenderFeature){const n=this.idIndex_[e];n instanceof RenderFeature?Array.isArray(n)?n.push(t):this.idIndex_[e]=[n,t]:r=!1}else r=!1;else this.idIndex_[e]=t}return r&&(assert$1(!(e in this.uidIndex_),"The passed `feature` was already added to the source"),this.uidIndex_[e]=t),r}addFeatures(e){this.addFeaturesInternal(e),this.changed()}addFeaturesInternal(e){const t=[],r=[],n=[];for(let i=0,o=e.length;i{t||(t=!0,this.addFeature(e.element),t=!1)}),e.addEventListener(CollectionEventType.REMOVE,e=>{t||(t=!0,this.removeFeature(e.element),t=!1)}),this.featuresCollection_=e}clear(e){if(e){for(const e in this.featureChangeKeys_)this.featureChangeKeys_[e].forEach(unlistenByKey);this.featuresCollection_||(this.featureChangeKeys_={},this.idIndex_={},this.uidIndex_={})}else if(this.featuresRtree_){this.featuresRtree_.forEach(e=>{this.removeFeatureInternal(e)});for(const e in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[e])}this.featuresCollection_&&this.featuresCollection_.clear(),this.featuresRtree_&&this.featuresRtree_.clear(),this.nullGeometryFeatures_={};const t=new VectorSourceEvent(VectorEventType.CLEAR);this.dispatchEvent(t),this.changed()}forEachFeature(e){if(this.featuresRtree_)return this.featuresRtree_.forEach(e);this.featuresCollection_&&this.featuresCollection_.forEach(e)}forEachFeatureAtCoordinateDirect(e,t){const r=[e[0],e[1],e[0],e[1]];return this.forEachFeatureInExtent(r,function(r){const n=r.getGeometry();if(n instanceof RenderFeature||n.intersectsCoordinate(e))return t(r)})}forEachFeatureInExtent(e,t){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(e,t);this.featuresCollection_&&this.featuresCollection_.forEach(t)}forEachFeatureIntersectingExtent(e,t){return this.forEachFeatureInExtent(e,function(r){const n=r.getGeometry();if(n instanceof RenderFeature||n.intersectsExtent(e)){const e=t(r);if(e)return e}})}getFeaturesCollection(){return this.featuresCollection_}getFeatures(){let e;return this.featuresCollection_?e=this.featuresCollection_.getArray().slice(0):this.featuresRtree_&&(e=this.featuresRtree_.getAll(),isEmpty$1(this.nullGeometryFeatures_)||extend$2(e,Object.values(this.nullGeometryFeatures_))),e}getFeaturesAtCoordinate(e){const t=[];return this.forEachFeatureAtCoordinateDirect(e,function(e){t.push(e)}),t}getFeaturesInExtent(e,t){if(this.featuresRtree_){if(!(t&&t.canWrapX()&&this.getWrapX()))return this.featuresRtree_.getInExtent(e);const r=wrapAndSliceX(e,t);return[].concat(...r.map(e=>this.featuresRtree_.getInExtent(e)))}return this.featuresCollection_?this.featuresCollection_.getArray().slice(0):[]}getClosestFeatureToCoordinate(e,t){const r=e[0],n=e[1];let i=null;const o=[NaN,NaN];let s=1/0;const a=[-1/0,-1/0,1/0,1/0];return t=t||TRUE,this.featuresRtree_.forEachInExtent(a,function(e){if(t(e)){const t=e.getGeometry(),l=s;if(s=t instanceof RenderFeature?0:t.closestPointXY(r,n,o,s),s{--this.loadingExtentsCount_,this.dispatchEvent(new VectorSourceEvent(VectorEventType.FEATURESLOADEND,void 0,e))},()=>{--this.loadingExtentsCount_,this.dispatchEvent(new VectorSourceEvent(VectorEventType.FEATURESLOADERROR))}),n.insert(e,{extent:e.slice()}))}this.loading=!(this.loader_.length<4)&&this.loadingExtentsCount_>0}refresh(){this.clear(!0),this.loadedExtentsRtree_.clear(),super.refresh()}removeLoadedExtent(e){const t=this.loadedExtentsRtree_,r=t.forEachInExtent(e,function(t){if(equals$1(t.extent,e))return t});r&&t.remove(r)}removeFeatures(e){let t=!1;for(let r=0,n=e.length;rcreateRenderFeature({...e,geometry:t})).flat();const n="MultiPolygon"===r.type?"Polygon":r.type;if("GeometryCollection"===n||"Circle"===n)throw new Error("Unsupported geometry type: "+n);const i=r.layout.length;return transformGeometryWithOptions(new RenderFeature(n,"Polygon"===n?orientFlatCoordinates(r.flatCoordinates,r.ends,i):r.flatCoordinates,r.ends?.flat(),i,e.properties||{},e.id).enableSimplifyTransformed(),!1,t)}function createGeometry(e,t){if(!e)return null;if(Array.isArray(e)){const r=e.map(e=>createGeometry(e,t));return new GeometryCollection(r)}return transformGeometryWithOptions(new(0,GeometryConstructor[e.type])(e.flatCoordinates,e.layout||"XY",e.ends),!1,t)}class JSONFeature extends FeatureFormat{constructor(){super()}getType(){return"json"}readFeature(e,t){return this.readFeatureFromObject(getObject(e),this.getReadOptions(e,t))}readFeatures(e,t){return this.readFeaturesFromObject(getObject(e),this.getReadOptions(e,t))}readFeatureFromObject(e,t){return abstract()}readFeaturesFromObject(e,t){return abstract()}readGeometry(e,t){return this.readGeometryFromObject(getObject(e),this.getReadOptions(e,t))}readGeometryFromObject(e,t){return abstract()}readProjection(e){return this.readProjectionFromObject(getObject(e))}readProjectionFromObject(e){return abstract()}writeFeature(e,t){return JSON.stringify(this.writeFeatureObject(e,t))}writeFeatureObject(e,t){return abstract()}writeFeatures(e,t){return JSON.stringify(this.writeFeaturesObject(e,t))}writeFeaturesObject(e,t){return abstract()}writeGeometry(e,t){return JSON.stringify(this.writeGeometryObject(e,t))}writeGeometryObject(e,t){return abstract()}}function getObject(e){return"string"==typeof e?JSON.parse(e)||null:null!==e?e:null}class GeoJSON extends JSONFeature{constructor(e){e=e||{},super(),this.dataProjection=get$2(e.dataProjection?e.dataProjection:"EPSG:4326"),e.featureProjection&&(this.defaultFeatureProjection=get$2(e.featureProjection)),e.featureClass&&(this.featureClass=e.featureClass),this.geometryName_=e.geometryName,this.extractGeometryName_=e.extractGeometryName,this.supportedMediaTypes=["application/geo+json","application/vnd.geo+json"]}readFeatureFromObject(e,t){let r=null;r="Feature"===e.type?e:{type:"Feature",geometry:e,properties:null};const n=readGeometryInternal(r.geometry);if(this.featureClass===RenderFeature)return createRenderFeature({geometry:n,id:r.id,properties:r.properties},t);const i=new Feature;return this.geometryName_?i.setGeometryName(this.geometryName_):this.extractGeometryName_&&r.geometry_name&&i.setGeometryName(r.geometry_name),i.setGeometry(createGeometry(n,t)),"id"in r&&i.setId(r.id),r.properties&&i.setProperties(r.properties,!0),i}readFeaturesFromObject(e,t){let r=null;if("FeatureCollection"===e.type){r=[];const n=e.features;for(let e=0,i=n.length;e":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type={type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function_stop={type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression$1={type:"array",value:"*",minimum:1},light={anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky={"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain={source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection={type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint=["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill={"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},paint_line={"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle={"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap={"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol={"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster={"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade={"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_background={"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition={duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},promoteId={"*":{type:"string"}},v8Spec={$version:$version,$root:$root,sources:sources,source:source,source_vector:source_vector,source_raster:source_raster,source_raster_dem:source_raster_dem,source_geojson:source_geojson,source_video:source_video,source_image:source_image,layer:layer,layout:layout,layout_background:layout_background,layout_fill:layout_fill,layout_circle:layout_circle,layout_heatmap:layout_heatmap,"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:layout_line,layout_symbol:layout_symbol,layout_raster:layout_raster,layout_hillshade:layout_hillshade,"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:filter,filter_operator:filter_operator,geometry_type:geometry_type,function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:function_stop,expression:expression$1,light:light,sky:sky,terrain:terrain,projection:projection,paint:paint,paint_fill:paint_fill,"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:paint_line,paint_circle:paint_circle,paint_heatmap:paint_heatmap,paint_symbol:paint_symbol,paint_raster:paint_raster,paint_hillshade:paint_hillshade,"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:paint_background,transition:transition,"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:promoteId};const refProperties=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function deref(e,t){const r={};for(const n in e)"ref"!==n&&(r[n]=e[n]);return refProperties.forEach(e=>{e in t&&(r[e]=t[e])}),r}function derefLayers(e){e=e.slice();const t=Object.create(null);for(let r=0;r`:"value"===e.itemType.kind?"array":`array<${t}>`}return e.kind}const valueMemberTypes=[NullType,NumberType,StringType,BooleanType,ColorType,ProjectionDefinitionType,FormattedType,ObjectType,array(ValueType),PaddingType,NumberArrayType,ColorArrayType,ResolvedImageType,VariableAnchorOffsetCollectionType];function checkSubtype(e,t){if("error"===t.kind)return null;if("array"===e.kind){if("array"===t.kind&&(0===t.N&&"value"===t.itemType.kind||!checkSubtype(e.itemType,t.itemType))&&("number"!=typeof e.N||e.N===t.N))return null}else{if(e.kind===t.kind)return null;if("value"===e.kind)for(const e of valueMemberTypes)if(!checkSubtype(e,t))return null}return`Expected ${typeToString(e)} but found ${typeToString(t)} instead.`}function isValidType(e,t){return t.some(t=>t.kind===e.kind)}function isValidNativeType(e,t){return t.some(t=>"null"===t?null===e:"array"===t?Array.isArray(e):"object"===t?e&&!Array.isArray(e)&&"object"==typeof e:t===typeof e)}function verifyType(e,t){return"array"===e.kind&&"array"===t.kind?e.itemType.kind===t.itemType.kind&&"number"==typeof e.N:e.kind===t.kind}const Xn=.96422,Yn=1,Zn=.82521,t0=4/29,t1=6/29,t2=3*t1*t1,t3=t1*t1*t1,deg2rad$1=Math.PI/180,rad2deg=180/Math.PI;function constrainAngle(e){return(e%=360)<0&&(e+=360),e}function rgbToLab([e,t,r,n]){let i,o;const s=xyz2lab((.2225045*(e=rgb2xyz(e))+.7168786*(t=rgb2xyz(t))+.0606169*(r=rgb2xyz(r)))/Yn);e===t&&t===r?i=o=s:(i=xyz2lab((.4360747*e+.3850649*t+.1430804*r)/Xn),o=xyz2lab((.0139322*e+.0971045*t+.7141733*r)/Zn));const a=116*s-16;return[a<0?0:a,500*(i-s),200*(s-o),n]}function rgb2xyz(e){return e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function xyz2lab(e){return e>t3?Math.pow(e,1/3):e/t2+t0}function labToRgb([e,t,r,n]){let i=(e+16)/116,o=isNaN(t)?i:i+t/500,s=isNaN(r)?i:i-r/200;return i=Yn*lab2xyz(i),o=Xn*lab2xyz(o),s=Zn*lab2xyz(s),[xyz2rgb(3.1338561*o-1.6168667*i-.4906146*s),xyz2rgb(-.9787684*o+1.9161415*i+.033454*s),xyz2rgb(.0719453*o-.2289914*i+1.4052427*s),n]}function xyz2rgb(e){return(e=e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055)<0?0:e>1?1:e}function lab2xyz(e){return e>t1?e*e*e:t2*(e-t0)}function rgbToHcl(e){const[t,r,n,i]=rgbToLab(e),o=Math.sqrt(r*r+n*n);return[Math.round(1e4*o)?constrainAngle(Math.atan2(n,r)*rad2deg):NaN,o,t,i]}function hclToRgb([e,t,r,n]){return e=isNaN(e)?0:e*deg2rad$1,labToRgb([r,Math.cos(e)*t,Math.sin(e)*t,n])}function hslToRgb([e,t,r,n]){function i(n){const i=(n+e/30)%12,o=t*Math.min(r,1-r);return r-o*Math.max(-1,Math.min(i-3,9-i,1))}return e=constrainAngle(e),t/=100,r/=100,[i(0),i(8),i(4),n]}const hasOwnProperty=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};function getOwn(e,t){return hasOwnProperty(e,t)?e[t]:void 0}function parseCssColor(e){if("transparent"===(e=e.toLowerCase().trim()))return[0,0,0,0];const t=getOwn(namedColors,e);if(t){const[e,r,n]=t;return[e/255,r/255,n/255,1]}if(e.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(e)){const t=e.length<6?1:2;let r=1;return[parseHex(e.slice(r,r+=t)),parseHex(e.slice(r,r+=t)),parseHex(e.slice(r,r+=t)),parseHex(e.slice(r,r+t)||"ff")]}if(e.startsWith("rgb")){const t=/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/,r=e.match(t);if(r){const[e,t,n,i,o,s,a,l,c,u,h,d]=r,p=[i||" ",a||" ",u].join("");if(" "===p||" /"===p||",,"===p||",,,"===p){const e=[n,s,c].join(""),r="%%%"===e?100:""===e?255:0;if(r){const e=[clamp(+t/r,0,1),clamp(+o/r,0,1),clamp(+l/r,0,1),h?parseAlpha(+h,d):1];if(validateNumbers(e))return e}}return}}const r=e.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[e,t,n,i,o,s,a,l,c]=r,u=[n||" ",o||" ",a].join("");if(" "===u||" /"===u||",,"===u||",,,"===u){const e=[+t,clamp(+i,0,100),clamp(+s,0,100),l?parseAlpha(+l,c):1];if(validateNumbers(e))return hslToRgb(e)}}}function parseHex(e){return parseInt(e.padEnd(2,e),16)/255}function parseAlpha(e,t){return clamp(t?e/100:e,0,1)}function clamp(e,t,r){return Math.min(Math.max(t,e),r)}function validateNumbers(e){return!e.some(Number.isNaN)}const namedColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function interpolateNumber(e,t,r){return e+r*(t-e)}function interpolateArray(e,t,r){return e.map((e,n)=>interpolateNumber(e,t[n],r))}class Color{constructor(e,t,r,n=1,i=!0){this.r=e,this.g=t,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[e,t,r,n]))}static parse(e){if(e instanceof Color)return e;if("string"!=typeof e)return;const t=parseCssColor(e);return t?new Color(...t,!1):void 0}get rgb(){const{r:e,g:t,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[e/i,t/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",rgbToHcl(this.rgb))}get lab(){return this.overwriteGetter("lab",rgbToLab(this.rgb))}overwriteGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}toString(){const[e,t,r,n]=this.rgb;return`rgba(${[e,t,r].map(e=>Math.round(255*e)).join(",")},${n})`}static interpolate(e,t,r,n="rgb"){switch(n){case"rgb":{const[n,i,o,s]=interpolateArray(e.rgb,t.rgb,r);return new Color(n,i,o,s,!1)}case"hcl":{const[n,i,o,s]=e.hcl,[a,l,c,u]=t.hcl;let h,d;if(isNaN(n)||isNaN(a))isNaN(n)?isNaN(a)?h=NaN:(h=a,1!==o&&0!==o||(d=l)):(h=n,1!==c&&0!==c||(d=i));else{let e=a-n;a>n&&e>180?e-=360:a180&&(e+=360),h=n+r*e}const[p,f,g,m]=hclToRgb([h,null!=d?d:interpolateNumber(i,l,r),interpolateNumber(o,c,r),interpolateNumber(s,u,r)]);return new Color(p,f,g,m,!1)}case"lab":{const[n,i,o,s]=labToRgb(interpolateArray(e.lab,t.lab,r));return new Color(n,i,o,s,!1)}}}}Color.black=new Color(0,0,0,1),Color.white=new Color(1,1,1,1),Color.transparent=new Color(0,0,0,0),Color.red=new Color(1,0,0,1);class Collator{constructor(e,t,r){this.sensitivity=e?t?"variant":"case":t?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(e,t){return this.collator.compare(e,t)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const VERTICAL_ALIGN_OPTIONS=["bottom","center","top"];class FormattedSection{constructor(e,t,r,n,i,o){this.text=e,this.image=t,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=o}}class Formatted{constructor(e){this.sections=e}static fromString(e){return new Formatted([new FormattedSection(e,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some(e=>0!==e.text.length||e.image&&0!==e.image.name.length)}static factory(e){return e instanceof Formatted?e:Formatted.fromString(e)}toString(){return 0===this.sections.length?"":this.sections.map(e=>e.text).join("")}}class Padding{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof Padding)return e;if("number"==typeof e)return new Padding([e,e,e,e]);if(Array.isArray(e)&&!(e.length<1||e.length>4)){for(const t of e)if("number"!=typeof t)return;switch(e.length){case 1:e=[e[0],e[0],e[0],e[0]];break;case 2:e=[e[0],e[1],e[0],e[1]];break;case 3:e=[e[0],e[1],e[2],e[1]]}return new Padding(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,t,r){return new Padding(interpolateArray(e.values,t.values,r))}}class NumberArray{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof NumberArray)return e;if("number"==typeof e)return new NumberArray([e]);if(Array.isArray(e)){for(const t of e)if("number"!=typeof t)return;return new NumberArray(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,t,r){return new NumberArray(interpolateArray(e.values,t.values,r))}}class ColorArray{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ColorArray)return e;if("string"==typeof e){const t=Color.parse(e);if(!t)return;return new ColorArray([t])}if(!Array.isArray(e))return;const t=[];for(const r of e){if("string"!=typeof r)return;const e=Color.parse(r);if(!e)return;t.push(e)}return new ColorArray(t)}toString(){return JSON.stringify(this.values)}static interpolate(e,t,r,n="rgb"){const i=[];if(e.values.length!=t.values.length)throw new Error(`colorArray: Arrays have mismatched length (${e.values.length} vs. ${t.values.length}), cannot interpolate.`);for(let o=0;o=0&&e<=255&&"number"==typeof t&&t>=0&&t<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[e,t,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[e,t,r,n]:[e,t,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function isValue(e){if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e||e instanceof ProjectionDefinition||e instanceof Color||e instanceof Collator||e instanceof Formatted||e instanceof Padding||e instanceof NumberArray||e instanceof ColorArray||e instanceof VariableAnchorOffsetCollection||e instanceof ResolvedImage)return!0;if(Array.isArray(e)){for(const t of e)if(!isValue(t))return!1;return!0}if("object"==typeof e){for(const t in e)if(!isValue(e[t]))return!1;return!0}return!1}function typeOf(e){if(null===e)return NullType;if("string"==typeof e)return StringType;if("boolean"==typeof e)return BooleanType;if("number"==typeof e)return NumberType;if(e instanceof Color)return ColorType;if(e instanceof ProjectionDefinition)return ProjectionDefinitionType;if(e instanceof Collator)return CollatorType;if(e instanceof Formatted)return FormattedType;if(e instanceof Padding)return PaddingType;if(e instanceof NumberArray)return NumberArrayType;if(e instanceof ColorArray)return ColorArrayType;if(e instanceof VariableAnchorOffsetCollection)return VariableAnchorOffsetCollectionType;if(e instanceof ResolvedImage)return ResolvedImageType;if(Array.isArray(e)){const t=e.length;let r;for(const n of e){const e=typeOf(n);if(r){if(r===e)continue;r=ValueType;break}r=e}return array(r||ValueType,t)}return ObjectType}function valueToString(e){const t=typeof e;return null===e?"":"string"===t||"number"===t||"boolean"===t?String(e):e instanceof Color||e instanceof ProjectionDefinition||e instanceof Formatted||e instanceof Padding||e instanceof NumberArray||e instanceof ColorArray||e instanceof VariableAnchorOffsetCollection||e instanceof ResolvedImage?e.toString():JSON.stringify(e)}class Literal{constructor(e,t){this.type=e,this.value=t}static parse(e,t){if(2!==e.length)return t.error(`'literal' expression requires exactly one argument, but found ${e.length-1} instead.`);if(!isValue(e[1]))return t.error("invalid value");const r=e[1];let n=typeOf(r);const i=t.expectedType;return"array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Literal(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}const types$1={string:StringType,number:NumberType,boolean:BooleanType,object:ObjectType};class Assertion{constructor(e,t){this.type=e,this.args=t}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");let r,n=1;const i=e[0];if("array"===i){let i,o;if(e.length>2){const r=e[1];if("string"!=typeof r||!(r in types$1)||"object"===r)return t.error('The item type argument of "array" must be one of string, number, boolean',1);i=types$1[r],n++}else i=ValueType;if(e.length>3){if(null!==e[2]&&("number"!=typeof e[2]||e[2]<0||e[2]!==Math.floor(e[2])))return t.error('The length argument to "array" must be a positive integer literal',2);o=e[2],n++}r=array(i,o)}else{if(!types$1[i])throw new Error(`Types doesn't contain name = ${i}`);r=types$1[i]}const o=[];for(;ne.outputDefined())}}const types$2={"to-boolean":BooleanType,"to-color":ColorType,"to-number":NumberType,"to-string":StringType};class Coercion{constructor(e,t){this.type=e,this.args=t}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");const r=e[0];if(!types$2[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==e.length)return t.error("Expected one argument.");const n=types$2[r],i=[];for(let o=1;o4?`Invalid rgba value ${JSON.stringify(t)}: expected an array containing either three or four numeric values.`:validateRGBA(t[0],t[1],t[2],t[3]),!r))return new Color(t[0]/255,t[1]/255,t[2]/255,t[3])}throw new RuntimeError(r||`Could not parse color from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"padding":{let t;for(const r of this.args){t=r.evaluate(e);const n=Padding.parse(t);if(n)return n}throw new RuntimeError(`Could not parse padding from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"numberArray":{let t;for(const r of this.args){t=r.evaluate(e);const n=NumberArray.parse(t);if(n)return n}throw new RuntimeError(`Could not parse numberArray from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"colorArray":{let t;for(const r of this.args){t=r.evaluate(e);const n=ColorArray.parse(t);if(n)return n}throw new RuntimeError(`Could not parse colorArray from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"variableAnchorOffsetCollection":{let t;for(const r of this.args){t=r.evaluate(e);const n=VariableAnchorOffsetCollection.parse(t);if(n)return n}throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"number":{let t=null;for(const r of this.args){if(t=r.evaluate(e),null===t)return 0;const n=Number(t);if(!isNaN(n))return n}throw new RuntimeError(`Could not convert ${JSON.stringify(t)} to number.`)}case"formatted":return Formatted.fromString(valueToString(this.args[0].evaluate(e)));case"resolvedImage":return ResolvedImage.fromString(valueToString(this.args[0].evaluate(e)));case"projectionDefinition":return this.args[0].evaluate(e);default:return valueToString(this.args[0].evaluate(e))}}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every(e=>e.outputDefined())}}const geometryTypes=["Unknown","Point","LineString","Polygon"];class EvaluationContext{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?geometryTypes[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(e){let t=this._parseColorCache.get(e);return t||(t=Color.parse(e),this._parseColorCache.set(e,t)),t}}class ParsingContext{constructor(e,t,r=[],n,i=new Scope,o=[]){this.registry=e,this.path=r,this.key=r.map(e=>`[${e}]`).join(""),this.scope=i,this.errors=o,this.expectedType=n,this._isConstant=t}parse(e,t,r,n,i={}){return t?this.concat(t,r,n)._parse(e,i):this._parse(e,i)}_parse(e,t){function r(e,t,r){return"assert"===r?new Assertion(t,[e]):"coerce"===r?new Coercion(t,[e]):e}if(null!==e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e||(e=["literal",e]),Array.isArray(e)){if(0===e.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const i=e[0];if("string"!=typeof i)return this.error(`Expression name must be a string, but found ${typeof i} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const o=this.registry[i];if(o){let i=o.parse(e,this);if(!i)return null;if(this.expectedType){const e=this.expectedType,n=i.type;if("string"!==e.kind&&"number"!==e.kind&&"boolean"!==e.kind&&"object"!==e.kind&&"array"!==e.kind||"value"!==n.kind){if("projectionDefinition"===e.kind&&["string","array"].includes(n.kind)||["color","formatted","resolvedImage"].includes(e.kind)&&["value","string"].includes(n.kind)||["padding","numberArray"].includes(e.kind)&&["value","number","array"].includes(n.kind)||"colorArray"===e.kind&&["value","string","array"].includes(n.kind)||"variableAnchorOffsetCollection"===e.kind&&["value","array"].includes(n.kind))i=r(i,e,t.typeAnnotation||"coerce");else if(this.checkSubtype(e,n))return null}else i=r(i,e,t.typeAnnotation||"assert")}if(!(i instanceof Literal)&&"resolvedImage"!==i.type.kind&&this._isConstant(i)){const e=new EvaluationContext;try{i=new Literal(i.type,i.evaluate(e))}catch(n){return this.error(n.message),null}}return i}return this.error(`Unknown expression "${i}". If you wanted a literal array, use ["literal", [...]].`,0)}return void 0===e?this.error("'undefined' value invalid. Use null instead."):"object"==typeof e?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error(`Expected an array, but found ${typeof e} instead.`)}concat(e,t,r){const n="number"==typeof e?this.path.concat(e):this.path,i=r?this.scope.concat(r):this.scope;return new ParsingContext(this.registry,this._isConstant,n,t||null,i,this.errors)}error(e,...t){const r=`${this.key}${t.map(e=>`[${e}]`).join("")}`;this.errors.push(new ExpressionParsingError(r,e))}checkSubtype(e,t){const r=checkSubtype(e,t);return r&&this.error(r),r}}class Let{constructor(e,t){this.type=t.type,this.bindings=[].concat(e),this.result=t}evaluate(e){return this.result.evaluate(e)}eachChild(e){for(const t of this.bindings)e(t[1]);e(this.result)}static parse(e,t){if(e.length<4)return t.error(`Expected at least 3 arguments, but found ${e.length-1} instead.`);const r=[];for(let i=1;i=r.length)throw new RuntimeError(`Array index out of bounds: ${t} > ${r.length-1}.`);if(t!==Math.floor(t))throw new RuntimeError(`Array index must be an integer, but found ${t} instead.`);return r[t]}eachChild(e){e(this.index),e(this.input)}outputDefined(){return!1}}class In{constructor(e,t){this.type=BooleanType,this.needle=e,this.haystack=t}static parse(e,t){if(3!==e.length)return t.error(`Expected 2 arguments, but found ${e.length-1} instead.`);const r=t.parse(e[1],1,ValueType),n=t.parse(e[2],2,ValueType);return r&&n?isValidType(r.type,[BooleanType,StringType,NumberType,NullType,ValueType])?new In(r,n):t.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(r.type)} instead`):null}evaluate(e){const t=this.needle.evaluate(e),r=this.haystack.evaluate(e);if(!r)return!1;if(!isValidNativeType(t,["boolean","string","number","null"]))throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(t))} instead.`);if(!isValidNativeType(r,["string","array"]))throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(r))} instead.`);return r.indexOf(t)>=0}eachChild(e){e(this.needle),e(this.haystack)}outputDefined(){return!0}}class IndexOf{constructor(e,t,r){this.type=NumberType,this.needle=e,this.haystack=t,this.fromIndex=r}static parse(e,t){if(e.length<=2||e.length>=5)return t.error(`Expected 3 or 4 arguments, but found ${e.length-1} instead.`);const r=t.parse(e[1],1,ValueType),n=t.parse(e[2],2,ValueType);if(!r||!n)return null;if(!isValidType(r.type,[BooleanType,StringType,NumberType,NullType,ValueType]))return t.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(r.type)} instead`);if(4===e.length){const i=t.parse(e[3],3,NumberType);return i?new IndexOf(r,n,i):null}return new IndexOf(r,n)}evaluate(e){const t=this.needle.evaluate(e),r=this.haystack.evaluate(e);if(!isValidNativeType(t,["boolean","string","number","null"]))throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(t))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(e)),isValidNativeType(r,["string"])){const e=r.indexOf(t,n);return-1===e?-1:[...r.slice(0,e)].length}if(isValidNativeType(r,["array"]))return r.indexOf(t,n);throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(r))} instead.`)}eachChild(e){e(this.needle),e(this.haystack),this.fromIndex&&e(this.fromIndex)}outputDefined(){return!1}}class Match{constructor(e,t,r,n,i,o){this.inputType=e,this.type=t,this.input=r,this.cases=n,this.outputs=i,this.otherwise=o}static parse(e,t){if(e.length<5)return t.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if(e.length%2!=1)return t.error("Expected an even number of arguments.");let r,n;t.expectedType&&"value"!==t.expectedType.kind&&(n=t.expectedType);const i={},o=[];for(let l=2;lNumber.MAX_SAFE_INTEGER)return c.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof e&&Math.floor(e)!==e)return c.error("Numeric branch labels must be integer values.");if(r){if(c.checkSubtype(r,typeOf(e)))return null}else r=typeOf(e);if(void 0!==i[String(e)])return c.error("Branch labels must be unique.");i[String(e)]=o.length}const u=t.parse(a,l,n);if(!u)return null;n=n||u.type,o.push(u)}const s=t.parse(e[1],1,ValueType);if(!s)return null;const a=t.parse(e[e.length-1],e.length-1,n);return a?"value"!==s.type.kind&&t.concat(1).checkSubtype(r,s.type)?null:new Match(r,n,s,i,o,a):null}evaluate(e){const t=this.input.evaluate(e);return(typeOf(t)===this.inputType&&this.outputs[this.cases[t]]||this.otherwise).evaluate(e)}eachChild(e){e(this.input),this.outputs.forEach(e),e(this.otherwise)}outputDefined(){return this.outputs.every(e=>e.outputDefined())&&this.otherwise.outputDefined()}}class Case{constructor(e,t,r){this.type=e,this.branches=t,this.otherwise=r}static parse(e,t){if(e.length<4)return t.error(`Expected at least 3 arguments, but found only ${e.length-1}.`);if(e.length%2!=0)return t.error("Expected an odd number of arguments.");let r;t.expectedType&&"value"!==t.expectedType.kind&&(r=t.expectedType);const n=[];for(let o=1;ot.outputDefined())&&this.otherwise.outputDefined()}}class Slice{constructor(e,t,r,n){this.type=e,this.input=t,this.beginIndex=r,this.endIndex=n}static parse(e,t){if(e.length<=2||e.length>=5)return t.error(`Expected 3 or 4 arguments, but found ${e.length-1} instead.`);const r=t.parse(e[1],1,ValueType),n=t.parse(e[2],2,NumberType);if(!r||!n)return null;if(!isValidType(r.type,[array(ValueType),StringType,ValueType]))return t.error(`Expected first argument to be of type array or string, but found ${typeToString(r.type)} instead`);if(4===e.length){const i=t.parse(e[3],3,NumberType);return i?new Slice(r.type,r,n,i):null}return new Slice(r.type,r,n)}evaluate(e){const t=this.input.evaluate(e),r=this.beginIndex.evaluate(e);let n;if(this.endIndex&&(n=this.endIndex.evaluate(e)),isValidNativeType(t,["string"]))return[...t].slice(r,n).join("");if(isValidNativeType(t,["array"]))return t.slice(r,n);throw new RuntimeError(`Expected first argument to be of type array or string, but found ${typeToString(typeOf(t))} instead.`)}eachChild(e){e(this.input),e(this.beginIndex),this.endIndex&&e(this.endIndex)}outputDefined(){return!1}}function findStopLessThanOrEqualTo(e,t){const r=e.length-1;let n,i,o=0,s=r,a=0;for(;o<=s;)if(a=Math.floor((o+s)/2),n=e[a],i=e[a+1],n<=t){if(a===r||tt))throw new RuntimeError("Input is not a number.");s=a-1}return 0}class Step{constructor(e,t,r){this.type=e,this.input=t,this.labels=[],this.outputs=[];for(const[n,i]of r)this.labels.push(n),this.outputs.push(i)}static parse(e,t){if(e.length-1<4)return t.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return t.error("Expected an even number of arguments.");const r=t.parse(e[1],1,NumberType);if(!r)return null;const n=[];let i=null;t.expectedType&&"value"!==t.expectedType.kind&&(i=t.expectedType);for(let o=1;o=r)return t.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',a);const c=t.parse(s,l,i);if(!c)return null;i=i||c.type,n.push([r,c])}return new Step(i,r,n)}evaluate(e){const t=this.labels,r=this.outputs;if(1===t.length)return r[0].evaluate(e);const n=this.input.evaluate(e);if(n<=t[0])return r[0].evaluate(e);const i=t.length;return n>=t[i-1]?r[i-1].evaluate(e):r[findStopLessThanOrEqualTo(t,n)].evaluate(e)}eachChild(e){e(this.input);for(const t of this.outputs)e(t)}outputDefined(){return this.outputs.every(e=>e.outputDefined())}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var unitbezier,hasRequiredUnitbezier;function requireUnitbezier(){if(hasRequiredUnitbezier)return unitbezier;function e(e,t,r,n){this.cx=3*e,this.bx=3*(r-e)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*t,this.by=3*(n-t)-this.cy,this.ay=1-this.cy-this.by,this.p1x=e,this.p1y=t,this.p2x=r,this.p2y=n}return hasRequiredUnitbezier=1,unitbezier=e,e.prototype={sampleCurveX:function(e){return((this.ax*e+this.bx)*e+this.cx)*e},sampleCurveY:function(e){return((this.ay*e+this.by)*e+this.cy)*e},sampleCurveDerivativeX:function(e){return(3*this.ax*e+2*this.bx)*e+this.cx},solveCurveX:function(e,t){if(void 0===t&&(t=1e-6),e<0)return 0;if(e>1)return 1;for(var r=e,n=0;n<8;n++){var i=this.sampleCurveX(r)-e;if(Math.abs(i)i?s=r:a=r,r=.5*(a-s)+s;return r},solve:function(e,t){return this.sampleCurveY(this.solveCurveX(e,t))}},unitbezier}var unitbezierExports=requireUnitbezier(),UnitBezier=getDefaultExportFromCjs(unitbezierExports);class Interpolate{constructor(e,t,r,n,i){this.type=e,this.operator=t,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[o,s]of i)this.labels.push(o),this.outputs.push(s)}static interpolationFactor(e,t,r,n){let i=0;if("exponential"===e.name)i=exponentialInterpolation(t,e.base,r,n);else if("linear"===e.name)i=exponentialInterpolation(t,1,r,n);else if("cubic-bezier"===e.name){const o=e.controlPoints;i=new UnitBezier(o[0],o[1],o[2],o[3]).solve(exponentialInterpolation(t,1,r,n))}return i}static parse(e,t){let[r,n,i,...o]=e;if(!Array.isArray(n)||0===n.length)return t.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const e=n[1];if("number"!=typeof e)return t.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:e}}else{if("cubic-bezier"!==n[0])return t.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const e=n.slice(1);if(4!==e.length||e.some(e=>"number"!=typeof e||e<0||e>1))return t.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:e}}}if(e.length-1<4)return t.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return t.error("Expected an even number of arguments.");if(i=t.parse(i,2,NumberType),!i)return null;const s=[];let a=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||t.expectedType==ColorArrayType?t.expectedType&&"value"!==t.expectedType.kind&&(a=t.expectedType):a=ColorType;for(let l=0;l=e)return t.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',n);const c=t.parse(r,i,a);if(!c)return null;a=a||c.type,s.push([e,c])}return verifyType(a,NumberType)||verifyType(a,ProjectionDefinitionType)||verifyType(a,ColorType)||verifyType(a,PaddingType)||verifyType(a,NumberArrayType)||verifyType(a,ColorArrayType)||verifyType(a,VariableAnchorOffsetCollectionType)||verifyType(a,array(NumberType))?new Interpolate(a,r,n,i,s):t.error(`Type ${typeToString(a)} is not interpolatable.`)}evaluate(e){const t=this.labels,r=this.outputs;if(1===t.length)return r[0].evaluate(e);const n=this.input.evaluate(e);if(n<=t[0])return r[0].evaluate(e);const i=t.length;if(n>=t[i-1])return r[i-1].evaluate(e);const o=findStopLessThanOrEqualTo(t,n),s=t[o],a=t[o+1],l=Interpolate.interpolationFactor(this.interpolation,n,s,a),c=r[o].evaluate(e),u=r[o+1].evaluate(e);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return interpolateNumber(c,u,l);case"color":return Color.interpolate(c,u,l);case"padding":return Padding.interpolate(c,u,l);case"colorArray":return ColorArray.interpolate(c,u,l);case"numberArray":return NumberArray.interpolate(c,u,l);case"variableAnchorOffsetCollection":return VariableAnchorOffsetCollection.interpolate(c,u,l);case"array":return interpolateArray(c,u,l);case"projectionDefinition":return ProjectionDefinition.interpolate(c,u,l)}case"interpolate-hcl":switch(this.type.kind){case"color":return Color.interpolate(c,u,l,"hcl");case"colorArray":return ColorArray.interpolate(c,u,l,"hcl")}case"interpolate-lab":switch(this.type.kind){case"color":return Color.interpolate(c,u,l,"lab");case"colorArray":return ColorArray.interpolate(c,u,l,"lab")}}}eachChild(e){e(this.input);for(const t of this.outputs)e(t)}outputDefined(){return this.outputs.every(e=>e.outputDefined())}}function exponentialInterpolation(e,t,r,n){const i=n-r,o=e-r;return 0===i?0:1===t?o/i:(Math.pow(t,o)-1)/(Math.pow(t,i)-1)}class Coalesce{constructor(e,t){this.type=e,this.args=t}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");let r=null;const n=t.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const s of e.slice(1)){const e=t.parse(s,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!e)return null;r=r||e.type,i.push(e)}if(!r)throw new Error("No output type");const o=n&&i.some(e=>checkSubtype(n,e.type));return new Coalesce(o?ValueType:r,i)}evaluate(e){let t,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(e),r&&r instanceof ResolvedImage&&!r.available&&(t||(t=r.name),r=null,n===this.args.length&&(r=t)),null!==r)break;return r}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every(e=>e.outputDefined())}}function isComparableType(e,t){return"=="===e||"!="===e?"boolean"===t.kind||"string"===t.kind||"number"===t.kind||"null"===t.kind||"value"===t.kind:"string"===t.kind||"number"===t.kind||"value"===t.kind}function eq(e,t,r){return t===r}function neq(e,t,r){return t!==r}function lt(e,t,r){return tr}function lteq(e,t,r){return t<=r}function gteq(e,t,r){return t>=r}function eqCollate(e,t,r,n){return 0===n.compare(t,r)}function neqCollate(e,t,r,n){return!eqCollate(e,t,r,n)}function ltCollate(e,t,r,n){return n.compare(t,r)<0}function gtCollate(e,t,r,n){return n.compare(t,r)>0}function lteqCollate(e,t,r,n){return n.compare(t,r)<=0}function gteqCollate(e,t,r,n){return n.compare(t,r)>=0}function makeComparison(e,t,r){const n="=="!==e&&"!="!==e;return class i{constructor(e,t,r){this.type=BooleanType,this.lhs=e,this.rhs=t,this.collator=r,this.hasUntypedArgument="value"===e.type.kind||"value"===t.type.kind}static parse(e,t){if(3!==e.length&&4!==e.length)return t.error("Expected two or three arguments.");const r=e[0];let o=t.parse(e[1],1,ValueType);if(!o)return null;if(!isComparableType(r,o.type))return t.concat(1).error(`"${r}" comparisons are not supported for type '${typeToString(o.type)}'.`);let s=t.parse(e[2],2,ValueType);if(!s)return null;if(!isComparableType(r,s.type))return t.concat(2).error(`"${r}" comparisons are not supported for type '${typeToString(s.type)}'.`);if(o.type.kind!==s.type.kind&&"value"!==o.type.kind&&"value"!==s.type.kind)return t.error(`Cannot compare types '${typeToString(o.type)}' and '${typeToString(s.type)}'.`);n&&("value"===o.type.kind&&"value"!==s.type.kind?o=new Assertion(s.type,[o]):"value"!==o.type.kind&&"value"===s.type.kind&&(s=new Assertion(o.type,[s])));let a=null;if(4===e.length){if("string"!==o.type.kind&&"string"!==s.type.kind&&"value"!==o.type.kind&&"value"!==s.type.kind)return t.error("Cannot use collator to compare non-string types.");if(a=t.parse(e[3],3,CollatorType),!a)return null}return new i(o,s,a)}evaluate(i){const o=this.lhs.evaluate(i),s=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const t=typeOf(o),r=typeOf(s);if(t.kind!==r.kind||"string"!==t.kind&&"number"!==t.kind)throw new RuntimeError(`Expected arguments for "${e}" to be (string, string) or (number, number), but found (${t.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const e=typeOf(o),r=typeOf(s);if("string"!==e.kind||"string"!==r.kind)return t(i,o,s)}return this.collator?r(i,o,s,this.collator.evaluate(i)):t(i,o,s)}eachChild(e){e(this.lhs),e(this.rhs),this.collator&&e(this.collator)}outputDefined(){return!0}}}const Equals=makeComparison("==",eq,eqCollate),NotEquals=makeComparison("!=",neq,neqCollate),LessThan=makeComparison("<",lt,ltCollate),GreaterThan=makeComparison(">",gt,gtCollate),LessThanOrEqual=makeComparison("<=",lteq,lteqCollate),GreaterThanOrEqual=makeComparison(">=",gteq,gteqCollate);class CollatorExpression{constructor(e,t,r){this.type=CollatorType,this.locale=r,this.caseSensitive=e,this.diacriticSensitive=t}static parse(e,t){if(2!==e.length)return t.error("Expected one argument.");const r=e[1];if("object"!=typeof r||Array.isArray(r))return t.error("Collator options argument must be an object.");const n=t.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,BooleanType);if(!n)return null;const i=t.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,BooleanType);if(!i)return null;let o=null;return r.locale&&(o=t.parse(r.locale,1,StringType),!o)?null:new CollatorExpression(n,i,o)}evaluate(e){return new Collator(this.caseSensitive.evaluate(e),this.diacriticSensitive.evaluate(e),this.locale?this.locale.evaluate(e):null)}eachChild(e){e(this.caseSensitive),e(this.diacriticSensitive),this.locale&&e(this.locale)}outputDefined(){return!1}}class NumberFormat{constructor(e,t,r,n,i){this.type=StringType,this.number=e,this.locale=t,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i}static parse(e,t){if(3!==e.length)return t.error("Expected two arguments.");const r=t.parse(e[1],1,NumberType);if(!r)return null;const n=e[2];if("object"!=typeof n||Array.isArray(n))return t.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=t.parse(n.locale,1,StringType),!i))return null;let o=null;if(n.currency&&(o=t.parse(n.currency,1,StringType),!o))return null;let s=null;if(n["min-fraction-digits"]&&(s=t.parse(n["min-fraction-digits"],1,NumberType),!s))return null;let a=null;return n["max-fraction-digits"]&&(a=t.parse(n["max-fraction-digits"],1,NumberType),!a)?null:new NumberFormat(r,i,o,s,a)}evaluate(e){return new Intl.NumberFormat(this.locale?this.locale.evaluate(e):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(e):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(e):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(e):void 0}).format(this.number.evaluate(e))}eachChild(e){e(this.number),this.locale&&e(this.locale),this.currency&&e(this.currency),this.minFractionDigits&&e(this.minFractionDigits),this.maxFractionDigits&&e(this.maxFractionDigits)}outputDefined(){return!1}}class FormatExpression{constructor(e){this.type=FormattedType,this.sections=e}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");const r=e[1];if(!Array.isArray(r)&&"object"==typeof r)return t.error("First argument must be an image or text section.");const n=[];let i=!1;for(let o=1;o<=e.length-1;++o){const r=e[o];if(i&&"object"==typeof r&&!Array.isArray(r)){i=!1;let e=null;if(r["font-scale"]&&(e=t.parse(r["font-scale"],1,NumberType),!e))return null;let o=null;if(r["text-font"]&&(o=t.parse(r["text-font"],1,array(StringType)),!o))return null;let s=null;if(r["text-color"]&&(s=t.parse(r["text-color"],1,ColorType),!s))return null;let a=null;if(r["vertical-align"]){if("string"==typeof r["vertical-align"]&&!VERTICAL_ALIGN_OPTIONS.includes(r["vertical-align"]))return t.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${r["vertical-align"]}' instead.`);if(a=t.parse(r["vertical-align"],1,StringType),!a)return null}const l=n[n.length-1];l.scale=e,l.font=o,l.textColor=s,l.verticalAlign=a}else{const r=t.parse(e[o],1,ValueType);if(!r)return null;const s=r.type.kind;if("string"!==s&&"value"!==s&&"null"!==s&&"resolvedImage"!==s)return t.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:r,scale:null,font:null,textColor:null,verticalAlign:null})}}return new FormatExpression(n)}evaluate(e){return new Formatted(this.sections.map(t=>{const r=t.content.evaluate(e);return typeOf(r)===ResolvedImageType?new FormattedSection("",r,null,null,null,t.verticalAlign?t.verticalAlign.evaluate(e):null):new FormattedSection(valueToString(r),null,t.scale?t.scale.evaluate(e):null,t.font?t.font.evaluate(e).join(","):null,t.textColor?t.textColor.evaluate(e):null,t.verticalAlign?t.verticalAlign.evaluate(e):null)}))}eachChild(e){for(const t of this.sections)e(t.content),t.scale&&e(t.scale),t.font&&e(t.font),t.textColor&&e(t.textColor),t.verticalAlign&&e(t.verticalAlign)}outputDefined(){return!1}}class ImageExpression{constructor(e){this.type=ResolvedImageType,this.input=e}static parse(e,t){if(2!==e.length)return t.error("Expected two arguments.");const r=t.parse(e[1],1,StringType);return r?new ImageExpression(r):t.error("No image name provided.")}evaluate(e){const t=this.input.evaluate(e),r=ResolvedImage.fromString(t);return r&&e.availableImages&&(r.available=e.availableImages.indexOf(t)>-1),r}eachChild(e){e(this.input)}outputDefined(){return!1}}class Length{constructor(e){this.type=NumberType,this.input=e}static parse(e,t){if(2!==e.length)return t.error(`Expected 1 argument, but found ${e.length-1} instead.`);const r=t.parse(e[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?t.error(`Expected argument of type string or array, but found ${typeToString(r.type)} instead.`):new Length(r):null}evaluate(e){const t=this.input.evaluate(e);if("string"==typeof t)return[...t].length;if(Array.isArray(t))return t.length;throw new RuntimeError(`Expected value to be of type string or array, but found ${typeToString(typeOf(t))} instead.`)}eachChild(e){e(this.input)}outputDefined(){return!1}}const EXTENT=8192;function getTileCoordinates(e,t){const r=mercatorXfromLng(e[0]),n=mercatorYfromLat(e[1]),i=Math.pow(2,t.z);return[Math.round(r*i*EXTENT),Math.round(n*i*EXTENT)]}function getLngLatFromTileCoord(e,t){const r=Math.pow(2,t.z),n=(e[0]/EXTENT+t.x)/r,i=(e[1]/EXTENT+t.y)/r;return[lngFromMercatorXfromLng(n),latFromMercatorY(i)]}function mercatorXfromLng(e){return(180+e)/360}function lngFromMercatorXfromLng(e){return 360*e-180}function mercatorYfromLat(e){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+e*Math.PI/360)))/360}function latFromMercatorY(e){return 360/Math.PI*Math.atan(Math.exp((180-360*e)*Math.PI/180))-90}function updateBBox(e,t){e[0]=Math.min(e[0],t[0]),e[1]=Math.min(e[1],t[1]),e[2]=Math.max(e[2],t[0]),e[3]=Math.max(e[3],t[1])}function boxWithinBox(e,t){return!(e[0]<=t[0]||e[2]>=t[2]||e[1]<=t[1]||e[3]>=t[3])}function rayIntersect(e,t,r){return t[1]>e[1]!=r[1]>e[1]&&e[0]<(r[0]-t[0])*(e[1]-t[1])/(r[1]-t[1])+t[0]}function pointOnBoundary(e,t,r){const n=e[0]-t[0],i=e[1]-t[1],o=e[0]-r[0],s=e[1]-r[1];return n*s-o*i===0&&n*o<=0&&i*s<=0}function segmentIntersectSegment(e,t,r,n){const i=[t[0]-e[0],t[1]-e[1]];return 0!==perp([n[0]-r[0],n[1]-r[1]],i)&&!(!twoSided(e,t,r,n)||!twoSided(r,n,e,t))}function lineIntersectPolygon(e,t,r){for(const n of r)for(let r=0;r0&&h<0||u<0&&h>0}function getTilePolygon(e,t,r){const n=[];for(let i=0;ir[2]){const t=.5*n;let i=e[0]-r[0]>t?-n:r[0]-e[0]>t?n:0;0===i&&(i=e[0]-r[2]>t?-n:r[2]-e[0]>t?n:0),e[0]+=i}updateBBox(t,e)}function resetBBox(e){e[0]=e[1]=1/0,e[2]=e[3]=-1/0}function getTilePoints(e,t,r,n){const i=Math.pow(2,n.z)*EXTENT,o=[n.x*EXTENT,n.y*EXTENT],s=[];for(const a of e)for(const e of a){const n=[e.x+o[0],e.y+o[1]];updatePoint(n,t,r,i),s.push(n)}return s}function getTileLines(e,t,r,n){const i=Math.pow(2,n.z)*EXTENT,o=[n.x*EXTENT,n.y*EXTENT],s=[];for(const a of e){const e=[];for(const r of a){const n=[r.x+o[0],r.y+o[1]];updateBBox(t,n),e.push(n)}s.push(e)}if(t[2]-t[0]<=i/2){resetBBox(t);for(const e of s)for(const n of e)updatePoint(n,t,r,i)}return s}function pointsWithinPolygons(e,t){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=e.canonicalID();if("Polygon"===t.type){const o=getTilePolygon(t.coordinates,n,i),s=getTilePoints(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!pointWithinPolygon(e,o))return!1}if("MultiPolygon"===t.type){const o=getTilePolygons(t.coordinates,n,i),s=getTilePoints(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!pointWithinPolygons(e,o))return!1}return!0}function linesWithinPolygons(e,t){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=e.canonicalID();if("Polygon"===t.type){const o=getTilePolygon(t.coordinates,n,i),s=getTileLines(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!lineStringWithinPolygon(e,o))return!1}if("MultiPolygon"===t.type){const o=getTilePolygons(t.coordinates,n,i),s=getTileLines(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!lineStringWithinPolygons(e,o))return!1}return!0}class Within{constructor(e,t){this.type=BooleanType,this.geojson=e,this.geometries=t}static parse(e,t){if(2!==e.length)return t.error(`'within' expression requires exactly one argument, but found ${e.length-1} instead.`);if(isValue(e[1])){const t=e[1];if("FeatureCollection"===t.type){const e=[];for(const r of t.features){const{type:t,coordinates:n}=r.geometry;"Polygon"===t&&e.push(n),"MultiPolygon"===t&&e.push(...n)}if(e.length)return new Within(t,{type:"MultiPolygon",coordinates:e})}else if("Feature"===t.type){const e=t.geometry.type;if("Polygon"===e||"MultiPolygon"===e)return new Within(t,t.geometry)}else if("Polygon"===t.type||"MultiPolygon"===t.type)return new Within(t,t)}return t.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(null!=e.geometry()&&null!=e.canonicalID()){if("Point"===e.geometryType())return pointsWithinPolygons(e,this.geometries);if("LineString"===e.geometryType())return linesWithinPolygons(e,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}class TinyQueue{constructor(e=[],t=(e,t)=>et?1:0){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,n=t[e];for(;e>0;){const i=e-1>>1,o=t[i];if(r(n,o)>=0)break;t[e]=o,e=i}t[e]=n}_down(e){const{data:t,compare:r}=this,n=this.length>>1,i=t[e];for(;e=0)break;t[e]=t[n],e=n}t[e]=i}}function classifyRings(e){if(e.length<=1)return[e];const t=[];let r,n;for(const i of e){const e=calculateSignedArea(i);0!==e&&(i.area=Math.abs(e),void 0===n&&(n=e<0),n===e<0?(r&&t.push(r),r=[i]):r.push(i))}return r&&t.push(r),t}function calculateSignedArea(e){let t=0;for(let r,n,i=0,o=e.length,s=o-1;i1?(l=e[a+1][0],c=e[a+1][1]):d>0&&(l+=u/this.kx*d,c+=h/this.ky*d)),u=this.wrap(t[0]-l)*this.kx,h=(t[1]-c)*this.ky;const p=u*u+h*h;p180;)e-=360;return e}}const MinPointsSize=100,MinLinePointsSize=50;function compareDistPair(e,t){return t[0]-e[0]}function getRangeSize(e){return e[1]-e[0]+1}function isRangeSafe(e,t){return e[1]>=e[0]&&e[1]e[1])return[null,null];const r=getRangeSize(e);if(t){if(2===r)return[e,null];const t=Math.floor(r/2);return[[e[0],e[0]+t],[e[0]+t,e[1]]]}if(1===r)return[e,null];const n=Math.floor(r/2)-1;return[[e[0],e[0]+n],[e[0]+n+1,e[1]]]}function getBBox(e,t){if(!isRangeSafe(t,e.length))return[1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=t[0];n<=t[1];++n)updateBBox(r,e[n]);return r}function getPolygonBBox(e){const t=[1/0,1/0,-1/0,-1/0];for(const r of e)for(const e of r)updateBBox(t,e);return t}function isValidBBox(e){return e[0]!==-1/0&&e[1]!==-1/0&&e[2]!==1/0&&e[3]!==1/0}function bboxToBBoxDistance(e,t,r){if(!isValidBBox(e)||!isValidBBox(t))return NaN;let n=0,i=0;return e[2]t[2]&&(n=e[0]-t[2]),e[1]>t[3]&&(i=e[1]-t[3]),e[3]=n)return n;if(boxWithinBox(i,o)){if(polygonIntersect(e,t))return 0}else if(polygonIntersect(t,e))return 0;let s=1/0;for(const a of e)for(let e=0,n=a.length,i=n-1;e0;){const i=s.pop();if(i[0]>=o)continue;const l=i[1],c=t?MinLinePointsSize:MinPointsSize;if(getRangeSize(l)<=c){if(!isRangeSafe(l,e.length))return NaN;if(t){const t=lineToPolygonDistance(e,l,r,n);if(isNaN(t)||0===t)return t;o=Math.min(o,t)}else for(let t=l[0];t<=l[1];++t){const i=pointToPolygonDistance(e[t],r,n);if(o=Math.min(o,i),0===o)return 0}}else{const r=splitRange(l,t);updateQueue(s,o,n,e,a,r[0]),updateQueue(s,o,n,e,a,r[1])}}return o}function pointSetToPointSetDistance(e,t,r,n,i,o=1/0){let s=Math.min(o,i.distance(e[0],r[0]));if(0===s)return s;const a=new TinyQueue([[0,[0,e.length-1],[0,r.length-1]]],compareDistPair);for(;a.length>0;){const o=a.pop();if(o[0]>=s)continue;const l=o[1],c=o[2],u=t?MinLinePointsSize:MinPointsSize,h=n?MinLinePointsSize:MinPointsSize;if(getRangeSize(l)<=u&&getRangeSize(c)<=h){if(!isRangeSafe(l,e.length)&&isRangeSafe(c,r.length))return NaN;let o;if(t&&n)o=lineToLineDistance(e,l,r,c,i),s=Math.min(s,o);else if(t&&!n){const t=e.slice(l[0],l[1]+1);for(let e=c[0];e<=c[1];++e)if(o=pointToLineDistance(r[e],t,i),s=Math.min(s,o),0===s)return s}else if(!t&&n){const t=r.slice(c[0],c[1]+1);for(let r=l[0];r<=l[1];++r)if(o=pointToLineDistance(e[r],t,i),s=Math.min(s,o),0===s)return s}else o=pointsToPointsDistance(e,l,r,c,i),s=Math.min(s,o)}else{const o=splitRange(l,t),u=splitRange(c,n);updateQueueTwoSets(a,s,i,e,r,o[0],u[0]),updateQueueTwoSets(a,s,i,e,r,o[0],u[1]),updateQueueTwoSets(a,s,i,e,r,o[1],u[0]),updateQueueTwoSets(a,s,i,e,r,o[1],u[1])}}return s}function pointToGeometryDistance(e,t){const r=e.geometry(),n=r.flat().map(t=>getLngLatFromTileCoord([t.x,t.y],e.canonical));if(0===r.length)return NaN;const i=new CheapRuler(n[0][1]);let o=1/0;for(const s of t){switch(s.type){case"Point":o=Math.min(o,pointSetToPointSetDistance(n,!1,[s.coordinates],!1,i,o));break;case"LineString":o=Math.min(o,pointSetToPointSetDistance(n,!1,s.coordinates,!0,i,o));break;case"Polygon":o=Math.min(o,pointsToPolygonDistance(n,!1,s.coordinates,i,o))}if(0===o)return o}return o}function lineStringToGeometryDistance(e,t){const r=e.geometry(),n=r.flat().map(t=>getLngLatFromTileCoord([t.x,t.y],e.canonical));if(0===r.length)return NaN;const i=new CheapRuler(n[0][1]);let o=1/0;for(const s of t){switch(s.type){case"Point":o=Math.min(o,pointSetToPointSetDistance(n,!0,[s.coordinates],!1,i,o));break;case"LineString":o=Math.min(o,pointSetToPointSetDistance(n,!0,s.coordinates,!0,i,o));break;case"Polygon":o=Math.min(o,pointsToPolygonDistance(n,!0,s.coordinates,i,o))}if(0===o)return o}return o}function polygonToGeometryDistance(e,t){const r=e.geometry();if(0===r.length||0===r[0].length)return NaN;const n=classifyRings(r).map(t=>t.map(t=>t.map(t=>getLngLatFromTileCoord([t.x,t.y],e.canonical)))),i=new CheapRuler(n[0][0][0][1]);let o=1/0;for(const s of t)for(const e of n){switch(s.type){case"Point":o=Math.min(o,pointsToPolygonDistance([s.coordinates],!1,e,i,o));break;case"LineString":o=Math.min(o,pointsToPolygonDistance(s.coordinates,!0,e,i,o));break;case"Polygon":o=Math.min(o,polygonToPolygonDistance(e,s.coordinates,i,o))}if(0===o)return o}return o}function toSimpleGeometry(e){return"MultiPolygon"===e.type?e.coordinates.map(e=>({type:"Polygon",coordinates:e})):"MultiLineString"===e.type?e.coordinates.map(e=>({type:"LineString",coordinates:e})):"MultiPoint"===e.type?e.coordinates.map(e=>({type:"Point",coordinates:e})):[e]}class Distance{constructor(e,t){this.type=NumberType,this.geojson=e,this.geometries=t}static parse(e,t){if(2!==e.length)return t.error(`'distance' expression requires exactly one argument, but found ${e.length-1} instead.`);if(isValue(e[1])){const t=e[1];if("FeatureCollection"===t.type)return new Distance(t,t.features.map(e=>toSimpleGeometry(e.geometry)).flat());if("Feature"===t.type)return new Distance(t,toSimpleGeometry(t.geometry));if("type"in t&&"coordinates"in t)return new Distance(t,toSimpleGeometry(t))}return t.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(null!=e.geometry()&&null!=e.canonicalID()){if("Point"===e.geometryType())return pointToGeometryDistance(e,this.geometries);if("LineString"===e.geometryType())return lineStringToGeometryDistance(e,this.geometries);if("Polygon"===e.geometryType())return polygonToGeometryDistance(e,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}class GlobalState{constructor(e){this.type=ValueType,this.key=e}static parse(e,t){if(2!==e.length)return t.error(`Expected 1 argument, but found ${e.length-1} instead.`);const r=e[1];return null==r?t.error("Global state property must be defined."):"string"!=typeof r?t.error(`Global state property must be string, but found ${typeof e[1]} instead.`):new GlobalState(r)}evaluate(e){var t;const r=null===(t=e.globals)||void 0===t?void 0:t.globalState;return r&&0!==Object.keys(r).length?getOwn(r,this.key):null}eachChild(){}outputDefined(){return!1}}const expressions$1={"==":Equals,"!=":NotEquals,">":GreaterThan,"<":LessThan,">=":GreaterThanOrEqual,"<=":LessThanOrEqual,array:Assertion,at:At,boolean:Assertion,case:Case,coalesce:Coalesce,collator:CollatorExpression,format:FormatExpression,image:ImageExpression,in:In,"index-of":IndexOf,interpolate:Interpolate,"interpolate-hcl":Interpolate,"interpolate-lab":Interpolate,length:Length,let:Let,literal:Literal,match:Match,number:Assertion,"number-format":NumberFormat,object:Assertion,slice:Slice,step:Step,string:Assertion,"to-boolean":Coercion,"to-color":Coercion,"to-number":Coercion,"to-string":Coercion,var:Var,within:Within,distance:Distance,"global-state":GlobalState};class CompoundExpression{constructor(e,t,r,n){this.name=e,this.type=t,this._evaluate=r,this.args=n}evaluate(e){return this._evaluate(e,this.args)}eachChild(e){this.args.forEach(e)}outputDefined(){return!1}static parse(e,t){const r=e[0],n=CompoundExpression.definitions[r];if(!n)return t.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,o=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,s=o.filter(([t])=>!Array.isArray(t)||t.length===e.length-1);let a=null;for(const[l,c]of s){a=new ParsingContext(t.registry,isExpressionConstant,t.path,null,t.scope);const n=[];let o=!1;for(let t=1;tstringifySignature(e)).join(" | "),n=[];for(let i=1;i>1;if(t[i]===e)return!0;t[i]>e?n=i-1:r=i+1}return!1}function varargs(e){return{type:e}}function stringifySignature(e){return Array.isArray(e)?`(${e.map(typeToString).join(", ")})`:`(${typeToString(e.type)}...)`}function isExpressionConstant(e){if(e instanceof Var)return isExpressionConstant(e.boundExpression);if(e instanceof CompoundExpression&&"error"===e.name)return!1;if(e instanceof CollatorExpression)return!1;if(e instanceof Within)return!1;if(e instanceof Distance)return!1;if(e instanceof GlobalState)return!1;const t=e instanceof Coercion||e instanceof Assertion;let r=!0;return e.eachChild(e=>{r=t?r&&isExpressionConstant(e):r&&e instanceof Literal}),!!r&&isFeatureConstant(e)&&isGlobalPropertyConstant(e,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function isFeatureConstant(e){if(e instanceof CompoundExpression){if("get"===e.name&&1===e.args.length)return!1;if("feature-state"===e.name)return!1;if("has"===e.name&&1===e.args.length)return!1;if("properties"===e.name||"geometry-type"===e.name||"id"===e.name)return!1;if(/^filter-/.test(e.name))return!1}if(e instanceof Within)return!1;if(e instanceof Distance)return!1;let t=!0;return e.eachChild(e=>{t&&!isFeatureConstant(e)&&(t=!1)}),t}function isStateConstant(e){if(e instanceof CompoundExpression&&"feature-state"===e.name)return!1;let t=!0;return e.eachChild(e=>{t&&!isStateConstant(e)&&(t=!1)}),t}function isGlobalPropertyConstant(e,t){if(e instanceof CompoundExpression&&t.indexOf(e.name)>=0)return!1;let r=!0;return e.eachChild(e=>{r&&!isGlobalPropertyConstant(e,t)&&(r=!1)}),r}function success(e){return{result:"success",value:e}}function error(e){return{result:"error",value:e}}function supportsPropertyExpression(e){return"data-driven"===e["property-type"]||"cross-faded-data-driven"===e["property-type"]}function supportsZoomExpression(e){return!!e.expression&&e.expression.parameters.indexOf("zoom")>-1}function supportsInterpolation(e){return!!e.expression&&e.expression.interpolated}function isFunction$1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&typeOf(e)===ObjectType}CompoundExpression.register(expressions$1,{error:[ErrorType,[StringType],(e,[t])=>{throw new RuntimeError(t.evaluate(e))}],typeof:[StringType,[ValueType],(e,[t])=>typeToString(typeOf(t.evaluate(e)))],"to-rgba":[array(NumberType,4),[ColorType],(e,[t])=>{const[r,n,i,o]=t.evaluate(e).rgb;return[255*r,255*n,255*i,o]}],rgb:[ColorType,[NumberType,NumberType,NumberType],rgba],rgba:[ColorType,[NumberType,NumberType,NumberType,NumberType],rgba],has:{type:BooleanType,overloads:[[[StringType],(e,[t])=>has(t.evaluate(e),e.properties())],[[StringType,ObjectType],(e,[t,r])=>has(t.evaluate(e),r.evaluate(e))]]},get:{type:ValueType,overloads:[[[StringType],(e,[t])=>get(t.evaluate(e),e.properties())],[[StringType,ObjectType],(e,[t,r])=>get(t.evaluate(e),r.evaluate(e))]]},"feature-state":[ValueType,[StringType],(e,[t])=>get(t.evaluate(e),e.featureState||{})],properties:[ObjectType,[],e=>e.properties()],"geometry-type":[StringType,[],e=>e.geometryType()],id:[ValueType,[],e=>e.id()],zoom:[NumberType,[],e=>e.globals.zoom],"heatmap-density":[NumberType,[],e=>e.globals.heatmapDensity||0],elevation:[NumberType,[],e=>e.globals.elevation||0],"line-progress":[NumberType,[],e=>e.globals.lineProgress||0],accumulated:[ValueType,[],e=>void 0===e.globals.accumulated?null:e.globals.accumulated],"+":[NumberType,varargs(NumberType),(e,t)=>{let r=0;for(const n of t)r+=n.evaluate(e);return r}],"*":[NumberType,varargs(NumberType),(e,t)=>{let r=1;for(const n of t)r*=n.evaluate(e);return r}],"-":{type:NumberType,overloads:[[[NumberType,NumberType],(e,[t,r])=>t.evaluate(e)-r.evaluate(e)],[[NumberType],(e,[t])=>-t.evaluate(e)]]},"/":[NumberType,[NumberType,NumberType],(e,[t,r])=>t.evaluate(e)/r.evaluate(e)],"%":[NumberType,[NumberType,NumberType],(e,[t,r])=>t.evaluate(e)%r.evaluate(e)],ln2:[NumberType,[],()=>Math.LN2],pi:[NumberType,[],()=>Math.PI],e:[NumberType,[],()=>Math.E],"^":[NumberType,[NumberType,NumberType],(e,[t,r])=>Math.pow(t.evaluate(e),r.evaluate(e))],sqrt:[NumberType,[NumberType],(e,[t])=>Math.sqrt(t.evaluate(e))],log10:[NumberType,[NumberType],(e,[t])=>Math.log(t.evaluate(e))/Math.LN10],ln:[NumberType,[NumberType],(e,[t])=>Math.log(t.evaluate(e))],log2:[NumberType,[NumberType],(e,[t])=>Math.log(t.evaluate(e))/Math.LN2],sin:[NumberType,[NumberType],(e,[t])=>Math.sin(t.evaluate(e))],cos:[NumberType,[NumberType],(e,[t])=>Math.cos(t.evaluate(e))],tan:[NumberType,[NumberType],(e,[t])=>Math.tan(t.evaluate(e))],asin:[NumberType,[NumberType],(e,[t])=>Math.asin(t.evaluate(e))],acos:[NumberType,[NumberType],(e,[t])=>Math.acos(t.evaluate(e))],atan:[NumberType,[NumberType],(e,[t])=>Math.atan(t.evaluate(e))],min:[NumberType,varargs(NumberType),(e,t)=>Math.min(...t.map(t=>t.evaluate(e)))],max:[NumberType,varargs(NumberType),(e,t)=>Math.max(...t.map(t=>t.evaluate(e)))],abs:[NumberType,[NumberType],(e,[t])=>Math.abs(t.evaluate(e))],round:[NumberType,[NumberType],(e,[t])=>{const r=t.evaluate(e);return r<0?-Math.round(-r):Math.round(r)}],floor:[NumberType,[NumberType],(e,[t])=>Math.floor(t.evaluate(e))],ceil:[NumberType,[NumberType],(e,[t])=>Math.ceil(t.evaluate(e))],"filter-==":[BooleanType,[StringType,ValueType],(e,[t,r])=>e.properties()[t.value]===r.value],"filter-id-==":[BooleanType,[ValueType],(e,[t])=>e.id()===t.value],"filter-type-==":[BooleanType,[StringType],(e,[t])=>e.geometryType()===t.value],"filter-<":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n{const r=e.id(),n=t.value;return typeof r==typeof n&&r":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[BooleanType,[ValueType],(e,[t])=>{const r=e.id(),n=t.value;return typeof r==typeof n&&r>n}],"filter-<=":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[BooleanType,[ValueType],(e,[t])=>{const r=e.id(),n=t.value;return typeof r==typeof n&&r<=n}],"filter->=":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[BooleanType,[ValueType],(e,[t])=>{const r=e.id(),n=t.value;return typeof r==typeof n&&r>=n}],"filter-has":[BooleanType,[ValueType],(e,[t])=>t.value in e.properties()],"filter-has-id":[BooleanType,[],e=>null!==e.id()&&void 0!==e.id()],"filter-type-in":[BooleanType,[array(StringType)],(e,[t])=>t.value.indexOf(e.geometryType())>=0],"filter-id-in":[BooleanType,[array(ValueType)],(e,[t])=>t.value.indexOf(e.id())>=0],"filter-in-small":[BooleanType,[StringType,array(ValueType)],(e,[t,r])=>r.value.indexOf(e.properties()[t.value])>=0],"filter-in-large":[BooleanType,[StringType,array(ValueType)],(e,[t,r])=>binarySearch(e.properties()[t.value],r.value,0,r.value.length-1)],all:{type:BooleanType,overloads:[[[BooleanType,BooleanType],(e,[t,r])=>t.evaluate(e)&&r.evaluate(e)],[varargs(BooleanType),(e,t)=>{for(const r of t)if(!r.evaluate(e))return!1;return!0}]]},any:{type:BooleanType,overloads:[[[BooleanType,BooleanType],(e,[t,r])=>t.evaluate(e)||r.evaluate(e)],[varargs(BooleanType),(e,t)=>{for(const r of t)if(r.evaluate(e))return!0;return!1}]]},"!":[BooleanType,[BooleanType],(e,[t])=>!t.evaluate(e)],"is-supported-script":[BooleanType,[StringType],(e,[t])=>{const r=e.globals&&e.globals.isSupportedScript;return!r||r(t.evaluate(e))}],upcase:[StringType,[StringType],(e,[t])=>t.evaluate(e).toUpperCase()],downcase:[StringType,[StringType],(e,[t])=>t.evaluate(e).toLowerCase()],concat:[StringType,varargs(ValueType),(e,t)=>t.map(t=>valueToString(t.evaluate(e))).join("")],"resolved-locale":[StringType,[CollatorType],(e,[t])=>t.evaluate(e).resolvedLocale()]});class StyleExpression{constructor(e,t){this.expression=e,this._warningHistory={},this._evaluator=new EvaluationContext,this._defaultValue=t?getDefaultValue(t):null,this._enumValues=t&&"enum"===t.type?t.values:null}evaluateWithoutErrorHandling(e,t,r,n,i,o){return this._evaluator.globals=e,this._evaluator.feature=t,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=o,this.expression.evaluate(this._evaluator)}evaluate(e,t,r,n,i,o){this._evaluator.globals=e,this._evaluator.feature=t||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=o||null;try{const e=this.expression.evaluate(this._evaluator);if(null==e||"number"==typeof e&&e!=e)return this._defaultValue;if(this._enumValues&&!(e in this._enumValues))throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(e=>JSON.stringify(e)).join(", ")}, but found ${JSON.stringify(e)} instead.`);return e}catch(s){return this._warningHistory[s.message]||(this._warningHistory[s.message]=!0,"undefined"!=typeof console&&console.warn(s.message)),this._defaultValue}}}function isExpression(e){return Array.isArray(e)&&e.length>0&&"string"==typeof e[0]&&e[0]in expressions$1}function createExpression(e,t){const r=new ParsingContext(expressions$1,isExpressionConstant,[],t?getExpectedType(t):void 0),n=r.parse(e,void 0,void 0,void 0,t&&"string"===t.type?{typeAnnotation:"coerce"}:void 0);return n?success(new StyleExpression(n,t)):error(r.errors)}class ZoomConstantExpression{constructor(e,t){this.kind=e,this._styleExpression=t,this.isStateDependent="constant"!==e&&!isStateConstant(t.expression),this.globalStateRefs=findGlobalStateRefs(t.expression)}evaluateWithoutErrorHandling(e,t,r,n,i,o){return this._styleExpression.evaluateWithoutErrorHandling(e,t,r,n,i,o)}evaluate(e,t,r,n,i,o){return this._styleExpression.evaluate(e,t,r,n,i,o)}}class ZoomDependentExpression{constructor(e,t,r,n){this.kind=e,this.zoomStops=r,this._styleExpression=t,this.isStateDependent="camera"!==e&&!isStateConstant(t.expression),this.globalStateRefs=findGlobalStateRefs(t.expression),this.interpolationType=n}evaluateWithoutErrorHandling(e,t,r,n,i,o){return this._styleExpression.evaluateWithoutErrorHandling(e,t,r,n,i,o)}evaluate(e,t,r,n,i,o){return this._styleExpression.evaluate(e,t,r,n,i,o)}interpolationFactor(e,t,r){return this.interpolationType?Interpolate.interpolationFactor(this.interpolationType,e,t,r):0}}function createPropertyExpression(e,t){const r=createExpression(e,t);if("error"===r.result)return r;const n=r.value.expression,i=isFeatureConstant(n);if(!i&&!supportsPropertyExpression(t))return error([new ExpressionParsingError("","data expressions not supported")]);const o=isGlobalPropertyConstant(n,["zoom"]);if(!o&&!supportsZoomExpression(t))return error([new ExpressionParsingError("","zoom expressions not supported")]);const s=findZoomCurve(n);if(!s&&!o)return error([new ExpressionParsingError("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);if(s instanceof ExpressionParsingError)return error([s]);if(s instanceof Interpolate&&!supportsInterpolation(t))return error([new ExpressionParsingError("",'"interpolate" expressions cannot be used with this property')]);if(!s)return success(new ZoomConstantExpression(i?"constant":"source",r.value));const a=s instanceof Interpolate?s.interpolation:void 0;return success(new ZoomDependentExpression(i?"camera":"composite",r.value,s.labels,a))}function findZoomCurve(e){let t=null;if(e instanceof Let)t=findZoomCurve(e.result);else if(e instanceof Coalesce){for(const r of e.args)if(t=findZoomCurve(r),t)break}else(e instanceof Step||e instanceof Interpolate)&&e.input instanceof CompoundExpression&&"zoom"===e.input.name&&(t=e);return t instanceof ExpressionParsingError||e.eachChild(e=>{const r=findZoomCurve(e);r instanceof ExpressionParsingError?t=r:!t&&r?t=new ExpressionParsingError("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):t&&r&&t!==r&&(t=new ExpressionParsingError("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),t}function findGlobalStateRefs(e,t=new Set){return e instanceof GlobalState&&t.add(e.key),e.eachChild(e=>{findGlobalStateRefs(e,t)}),t}function getExpectedType(e){const t={color:ColorType,string:StringType,number:NumberType,enum:StringType,boolean:BooleanType,formatted:FormattedType,padding:PaddingType,numberArray:NumberArrayType,colorArray:ColorArrayType,projectionDefinition:ProjectionDefinitionType,resolvedImage:ResolvedImageType,variableAnchorOffsetCollection:VariableAnchorOffsetCollectionType};return"array"===e.type?array(t[e.value]||ValueType,e.length):t[e.type]}function getDefaultValue(e){if("color"===e.type&&isFunction$1(e.default))return new Color(0,0,0,0);switch(e.type){case"color":return Color.parse(e.default)||null;case"padding":return Padding.parse(e.default)||null;case"numberArray":return NumberArray.parse(e.default)||null;case"colorArray":return ColorArray.parse(e.default)||null;case"variableAnchorOffsetCollection":return VariableAnchorOffsetCollection.parse(e.default)||null;case"projectionDefinition":return ProjectionDefinition.parse(e.default)||null;default:return void 0===e.default?null:e.default}}function isExpressionFilter(e){if(!0===e||!1===e)return!0;if(!Array.isArray(e)||0===e.length)return!1;switch(e[0]){case"has":return e.length>=2&&"$id"!==e[1]&&"$type"!==e[1];case"in":return e.length>=3&&("string"!=typeof e[1]||Array.isArray(e[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==e.length||Array.isArray(e[1])||Array.isArray(e[2]);case"any":case"all":for(const t of e.slice(1))if(!isExpressionFilter(t)&&"boolean"!=typeof t)return!1;return!0;default:return!0}}const filterSpec={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function featureFilter(e){if(null==e)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};isExpressionFilter(e)||(e=convertFilter$1(e));const t=createExpression(e,filterSpec);if("error"===t.result)throw new Error(t.value.map(e=>`${e.key}: ${e.message}`).join(", "));return{filter:(e,r,n)=>t.value.evaluate(e,r,{},n),needGeometry:geometryNeeded(e),getGlobalStateRefs:()=>findGlobalStateRefs(t.value.expression)}}function compare(e,t){return et?1:0}function geometryNeeded(e){if(!Array.isArray(e))return!1;if("within"===e[0]||"distance"===e[0])return!0;for(let t=1;t"===t||"<="===t||">="===t?convertComparisonOp$1(e[1],e[2],t):"any"===t?convertDisjunctionOp(e.slice(1)):"all"===t?["all"].concat(e.slice(1).map(convertFilter$1)):"none"===t?["all"].concat(e.slice(1).map(convertFilter$1).map(convertNegation)):"in"===t?convertInOp$1(e[1],e.slice(2)):"!in"===t?convertNegation(convertInOp$1(e[1],e.slice(2))):"has"===t?convertHasOp$1(e[1]):"!has"!==t||convertNegation(convertHasOp$1(e[1]))}function convertComparisonOp$1(e,t,r){switch(e){case"$type":return[`filter-type-${r}`,t];case"$id":return[`filter-id-${r}`,t];default:return[`filter-${r}`,e,t]}}function convertDisjunctionOp(e){return["any"].concat(e.map(convertFilter$1))}function convertInOp$1(e,t){if(0===t.length)return!1;switch(e){case"$type":return["filter-type-in",["literal",t]];case"$id":return["filter-id-in",["literal",t]];default:return t.length>200&&!t.some(e=>typeof e!=typeof t[0])?["filter-in-large",e,["literal",t.sort(compare)]]:["filter-in-small",e,["literal",t]]}}function convertHasOp$1(e){switch(e){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",e]}}function convertNegation(e){return["!",e]}function convertLiteral(e){return"object"==typeof e?["literal",e]:e}function convertFunction(e,t){let r=e.stops;if(!r)return convertIdentityFunction(e,t);const n=r&&"object"==typeof r[0][0],i=n||void 0!==e.property,o=n||!i;return r=r.map(e=>!i&&t.tokens&&"string"==typeof e[1]?[e[0],convertTokenString(e[1])]:[e[0],convertLiteral(e[1])]),n?convertZoomAndPropertyFunction(e,t,r):o?convertZoomFunction(e,t,r):convertPropertyFunction(e,t,r)}function convertIdentityFunction(e,t){const r=["get",e.property];if(void 0===e.default)return"string"===t.type?["string",r]:r;if("enum"===t.type)return["match",r,Object.keys(t.values),r,e.default];{const n=["color"===t.type?"to-color":t.type,r,convertLiteral(e.default)];return"array"===t.type&&n.splice(1,0,t.value,t.length||null),n}}function getInterpolateOperator(e){switch(e.colorSpace){case"hcl":return"interpolate-hcl";case"lab":return"interpolate-lab";default:return"interpolate"}}function convertZoomAndPropertyFunction(e,t,r){const n={},i={},o=[];for(let s=0;s3&&t===e[e.length-2]||(n&&2===e.length||e.push(t),e.push(r))}function getFunctionType(e,t){return e.type?e.type:t.expression.interpolated?"exponential":"interval"}function convertTokenString(e){const t=["concat"],r=/{([^{}]+)}/g;let n=0;for(let i=r.exec(e);null!==i;i=r.exec(e)){const o=e.slice(n,r.lastIndex-i[0].length);n=r.lastIndex,o.length>0&&t.push(o),t.push(["get",i[1]])}if(1===t.length)return e;if(n1?h[h.length-2].toLowerCase():"";if(d==p||d==p.replace("-","")||f+"-"+d==p){s=i?s:fontWeights[p],h.pop(),f&&p.startsWith(f)&&h.pop();break}}i||"number"!=typeof d||(s=d,i=!0);var g=h.join(sp).replace("Klokantech Noto Sans","Noto Sans").replace("DIN Pro","Barlow").replace("Arial Unicode MS","Arial");-1!==g.indexOf(sp)&&(g='"'+g+'"'),l.push(g)}n=fontCache[e]=[a,s,l]}return n[0]+sp+n[1]+sp+t+"px"+(r?"/"+r:"")+sp+n[2]}class ImageCanvas extends ImageWrapper{constructor(e,t,r,n,i){super(e,t,r,void 0!==i?ImageState.IDLE:ImageState.LOADED),this.loader_=void 0!==i?i:null,this.canvas_=n,this.error_=null}getError(){return this.error_}handleLoad_(e){e?(this.error_=e,this.state=ImageState.ERROR):this.state=ImageState.LOADED,this.changed()}load(){this.state==ImageState.IDLE&&(this.state=ImageState.LOADING,this.changed(),this.loader_(this.handleLoad_.bind(this)))}getImage(){return this.canvas_}}class Tile extends Target{constructor(e,t,r){super(),r=r||{},this.tileCoord=e,this.state=t,this.key="",this.transition_=void 0===r.transition?250:r.transition,this.transitionStarts_={},this.interpolate=!!r.interpolate}changed(){this.dispatchEvent(EventType$1.CHANGE)}release(){this.setState(TileState.EMPTY)}getKey(){return this.key+"/"+this.tileCoord}getTileCoord(){return this.tileCoord}getState(){return this.state}setState(e){if(this.state!==TileState.EMPTY){if(this.state!==TileState.ERROR&&this.state>e)throw new Error("Tile load sequence violation");this.state=e,this.changed()}}load(){abstract()}getAlpha(e,t){if(!this.transition_)return 1;let r=this.transitionStarts_[e];if(r){if(-1===r)return 1}else r=t,this.transitionStarts_[e]=r;const n=t-r+1e3/60;return n>=this.transition_?1:easeIn(n/this.transition_)}inTransition(e){return!!this.transition_&&-1!==this.transitionStarts_[e]}endTransition(e){this.transition_&&(this.transitionStarts_[e]=-1)}disposeInternal(){this.release(),super.disposeInternal()}}class ImageTile extends Tile{constructor(e,t,r,n,i,o){super(e,t,o),this.crossOrigin_=n,this.src_=r,this.key=r,this.image_,WORKER_OFFSCREEN_CANVAS?this.image_=new OffscreenCanvas(1,1):(this.image_=new Image,null!==n&&(this.image_.crossOrigin=n)),this.unlisten_=null,this.tileLoadFunction_=i}getImage(){return this.image_}setImage(e){this.image_=e,this.state=TileState.LOADED,this.unlistenImage_(),this.changed()}getCrossOrigin(){return this.crossOrigin_}handleImageError_(){this.state=TileState.ERROR,this.unlistenImage_(),this.image_=getBlankImage(),this.changed()}handleImageLoad_(){if(WORKER_OFFSCREEN_CANVAS)this.state=TileState.LOADED;else{const e=this.image_;e.naturalWidth&&e.naturalHeight?this.state=TileState.LOADED:this.state=TileState.EMPTY}this.unlistenImage_(),this.changed()}load(){this.state==TileState.ERROR&&(this.state=TileState.IDLE,this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)),this.state==TileState.IDLE&&(this.state=TileState.LOADING,this.changed(),this.tileLoadFunction_(this,this.src_),this.unlisten_=listenImage(this.image_,this.handleImageLoad_.bind(this),this.handleImageError_.bind(this)))}unlistenImage_(){this.unlisten_&&(this.unlisten_(),this.unlisten_=null)}disposeInternal(){this.unlistenImage_(),this.image_=null,super.disposeInternal()}}function getBlankImage(){const e=createCanvasContext2D(1,1);return e.fillStyle="rgba(0,0,0,0)",e.fillRect(0,0,1,1),e.canvas}class TileRange{constructor(e,t,r,n){this.minX=e,this.maxX=t,this.minY=r,this.maxY=n}contains(e){return this.containsXY(e[1],e[2])}containsTileRange(e){return this.minX<=e.minX&&e.maxX<=this.maxX&&this.minY<=e.minY&&e.maxY<=this.maxY}containsXY(e,t){return this.minX<=e&&e<=this.maxX&&this.minY<=t&&t<=this.maxY}equals(e){return this.minX==e.minX&&this.minY==e.minY&&this.maxX==e.maxX&&this.maxY==e.maxY}extend(e){e.minXthis.maxX&&(this.maxX=e.maxX),e.minYthis.maxY&&(this.maxY=e.maxY)}getHeight(){return this.maxY-this.minY+1}getSize(){return[this.getWidth(),this.getHeight()]}getWidth(){return this.maxX-this.minX+1}intersects(e){return this.minX<=e.maxX&&this.maxX>=e.minX&&this.minY<=e.maxY&&this.maxY>=e.minY}}function createOrUpdate$1(e,t,r,n,i){return void 0!==i?(i.minX=e,i.maxX=t,i.minY=r,i.maxY=n,i):new TileRange(e,t,r,n)}const canvasPool$1=[];class VectorRenderTile extends Tile{constructor(e,t,r,n,i){super(e,t,{transition:0}),this.context_=null,this.executorGroups={},this.loadingSourceTiles=0,this.hitDetectionImageData={},this.replayState_={},this.sourceTiles=[],this.errorTileKeys={},this.wantedResolution,this.getSourceTiles=n.bind(void 0,this),this.removeSourceTiles_=i,this.wrappedTileCoord=r}getContext(){return this.context_||(this.context_=createCanvasContext2D(1,1,canvasPool$1)),this.context_}hasContext(){return!!this.context_}getImage(){return this.hasContext()?this.getContext().canvas:null}getReplayState(e){const t=getUid(e);return t in this.replayState_||(this.replayState_[t]={dirty:!1,renderedRenderOrder:null,renderedResolution:NaN,renderedRevision:-1,renderedTileResolution:NaN,renderedTileRevision:-1,renderedTileZ:-1}),this.replayState_[t]}load(){this.getSourceTiles()}release(){this.context_&&(releaseCanvas(this.context_),canvasPool$1.push(this.context_.canvas),this.context_=null),this.removeSourceTiles_(this),this.sourceTiles.length=0,super.release()}}let VectorTile$1=class extends Tile{constructor(e,t,r,n,i,o){super(e,t,o),this.extent=null,this.format_=n,this.features_=null,this.loader_,this.projection=null,this.resolution,this.tileLoadFunction_=i,this.url_=r,this.key=r}getTileUrl(){return this.url_}getFormat(){return this.format_}getFeatures(){return this.features_}load(){this.state==TileState.IDLE&&(this.setState(TileState.LOADING),this.tileLoadFunction_(this,this.url_),this.loader_&&this.loader_(this.extent,this.resolution,this.projection))}onLoad(e,t){this.setFeatures(e)}onError(){this.setState(TileState.ERROR)}setFeatures(e){this.features_=e,this.setState(TileState.LOADED)}setLoader(e){this.loader_=e}};const mapboxBaseUrl="https://api.mapbox.com";function getMapboxPath(e){return 0!==e.indexOf("mapbox://")?"":e.slice(9)}function normalizeSpriteDefinition(e,t,r){if("string"==typeof e)return[{id:"default",url:normalizeSpriteUrl(e,t,r)}];for(const n of e)n.url=normalizeSpriteUrl(n.url,t,r);return e}function normalizeSpriteUrl(e,t,r){const n=getMapboxPath(e);if(!n)return decodeURI(new URL(e,r).href);if(0!==n.indexOf("sprites/"))throw new Error(`unexpected sprites url: ${e}`);const i=n.slice(8);return`${mapboxBaseUrl}/styles/v1/${i}/sprite?access_token=${t}`}function normalizeStyleUrl(e,t){const r=getMapboxPath(e);if(!r)return decodeURI(new URL(e,location.href).href);if(0!==r.indexOf("styles/"))throw new Error(`unexpected style url: ${e}`);const n=r.slice(7);return`${mapboxBaseUrl}/styles/v1/${n}?&access_token=${t}`}const mapboxSubdomains=["a","b","c","d"];function normalizeSourceUrl(e,t,r,n){const i=new URL(e,n||location.href),o=getMapboxPath(e);if(!o)return t?(i.searchParams.has(r)||i.searchParams.set(r,t),[decodeURI(i.href)]):[decodeURI(i.href)];if("mapbox.satellite"===o){const e=window.devicePixelRatio>=1.5?"@2x":"";return[`https://api.mapbox.com/v4/${o}/{z}/{x}/{y}${e}.webp?access_token=${t}`]}return mapboxSubdomains.map(e=>`https://${e}.tiles.mapbox.com/v4/${o}/{z}/{x}/{y}.vector.pbf?access_token=${t}`)}const emptyObj=Object.freeze({}),functionCacheByStyleId={},filterCacheByStyleId={};let styleId=0;function getStyleId(e){return e.id||(e.id=styleId++),e.id}function getStyleFunctionKey(e,t){return getStyleId(e)+"."+getUid(t)}function getFunctionCache(e){let t=functionCacheByStyleId[e.id];return t||(t={},functionCacheByStyleId[getStyleId(e)]=t),t}function getFilterCache(e){let t=filterCacheByStyleId[e.id];return t||(t={},filterCacheByStyleId[getStyleId(e)]=t),t}function deg2rad(e){return e*Math.PI/180}const defaultResolutions=function(){const e=[];for(let t=78271.51696402048;e.length<=24;t/=2)e.push(t);return e}();function createCanvas(e,t){if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);const r=document.createElement("canvas");return r.width=e,r.height=t,r}function getZoomForResolution(e,t){let r=0;const n=t.length;for(;ri).then(e=>e instanceof Response?(n&&(n.url=e.url),s(e)):(e instanceof Request||(e=new Request(e)),e.headers.get("Accept")||e.headers.set("Accept","application/json"),n&&(n.url=e.url),fetch(e).then(s).catch(o))).catch(o);return pendingRequests[t]=[i,a],a}function getGlStyle(e,t){if("string"!=typeof e)return Promise.resolve(e);if(!e.trim().startsWith("{"))return fetchResource("Style",e=normalizeStyleUrl(e,t.accessToken),t);try{const t=JSON.parse(e);return Promise.resolve(t)}catch(error){return Promise.reject(error)}}const tilejsonCache={};function getTileJson(e,t,r={}){const n=[t,JSON.stringify(e)].toString();let i=tilejsonCache[n];if(!i||r.transformRequest){let o;r.transformRequest&&(o=(e,t)=>{const n=r.transformRequest&&r.transformRequest(t,"Tiles")||t;if(e instanceof VectorTile$1)e.setLoader((t,r,i)=>{const o=function(r){r.arrayBuffer().then(r=>{const n=e.getFormat().readFeatures(r,{extent:t,featureProjection:i});e.setFeatures(n)})};toPromise(()=>n).then(t=>{if(t instanceof Response)return o(t);fetch(t).then(o).catch(()=>e.setState(TileState.ERROR))}).catch(()=>e.setState(TileState.ERROR))});else{const t=e.getImage();toPromise(()=>n).then(r=>{if("string"==typeof r)return void(t.src=r);const n=e=>e.blob().then(e=>{const r=URL.createObjectURL(e);t.addEventListener("load",()=>URL.revokeObjectURL(r)),t.addEventListener("error",()=>URL.revokeObjectURL(r)),t.src=r});if(r instanceof Response)return n(r);fetch(r).then(n).catch(()=>e.setState(TileState.ERROR))}).catch(()=>e.setState(TileState.ERROR))}});const s=e.url;if(s&&!e.tiles){const n=normalizeSourceUrl(s,r.accessToken,r.accessTokenParam||"access_token",t||location.href);if(s.startsWith("mapbox://"))i=Promise.resolve({tileJson:Object.assign({},e,{url:void 0,tiles:n}),tileLoadFunction:o});else{const e={};i=fetchResource("Source",n[0],r,e).then(function(t){return t.tiles=t.tiles.map(function(n){return"tms"===t.scheme&&(n=n.replace("{y}","{-y}")),normalizeSourceUrl(n,r.accessToken,r.accessTokenParam||"access_token",e.url)[0]}),Promise.resolve({tileJson:t,tileLoadFunction:o})})}}else e.tiles?(e=Object.assign({},e,{tiles:e.tiles.map(function(n){return"tms"===e.scheme&&(n=n.replace("{y}","{-y}")),normalizeSourceUrl(n,r.accessToken,r.accessTokenParam||"access_token",t||location.href)[0]})}),i=Promise.resolve({tileJson:Object.assign({},e),tileLoadFunction:o})):i=Promise.reject(new Error("source has no `tiles` nor `url`"));tilejsonCache[n]=i}return i}function drawIconHalo(e,t,r,n){const i=[2*r*t.pixelRatio+t.width,2*r*t.pixelRatio+t.height],o=createCanvas(i[0],i[1]),s=o.getContext("2d");s.drawImage(e,t.x,t.y,t.width,t.height,r*t.pixelRatio,r*t.pixelRatio,t.width,t.height);const a=s.getImageData(0,0,i[0],i[1]);s.globalCompositeOperation="destination-over",s.fillStyle=`rgba(${255*n.r},${255*n.g},${255*n.b},${n.a})`;const l=a.data;for(let c=0,u=a.width;c0&&s.arc(c,e,r*t.pixelRatio,0,2*Math.PI);return s.fill(),o}function smoothstep(e,t,r){const n=Math.max(0,Math.min(1,(r-e)/(t-e)));return n*n*(3-2*n)}function drawSDF(e,t,r){const n=createCanvas(t.width,t.height),i=n.getContext("2d");i.drawImage(e,t.x,t.y,t.width,t.height,0,0,t.width,t.height);const o=i.getImageData(0,0,t.width,t.height),s=o.data;for(let a=0,l=o.width;a0?(s[t+0]=Math.round(255*r.r*o),s[t+1]=Math.round(255*r.g*o),s[t+2]=Math.round(255*r.b*o),s[t+3]=Math.round(255*o)):s[t+3]=0}return i.putImageData(o,0,0),n}const hairSpacePool=Array(256).join(" ");function applyLetterSpacing(e,t){if(t>=.05){let r="";const n=e.split("\n"),i=hairSpacePool.slice(0,Math.round(t/.1));for(let e=0,t=n.length;e0&&(r+="\n"),r+=n[e].split("").join(i);return r}return e}let measureContext;function getMeasureContext(){return measureContext||(measureContext=createCanvas(1,1).getContext("2d")),measureContext}function measureText(e,t){return getMeasureContext().measureText(e).width+(e.length-1)*t}const measureCache={};function wrapText(e,t,r,n){if(-1!==e.indexOf("\n")){const i=e.split("\n"),o=[];for(let e=0,s=i.length;e1){const e=getMeasureContext();e.font=t;const i=e.measureText("M").width*r;let a="";const l=[];for(let t=0,r=s.length;t1;++t){const e=l[t];if(measureText(e,n)<.35*i){const i=t>0?measureText(l[t-1],n):1/0,o=t.7*i&&measureText(o,n)<.6*i){const s=e.split(" "),a=s.pop();measureText(a,n)<.2*i&&(l[t]=s.join(" "),l[t+1]=a+" "+o),r-=1}}o=l.join("\n")}else o=e;o=applyLetterSpacing(o,n),measureCache[i]=o}return o}checkedFonts.on("propertychange",()=>{for(const e in measureCache)delete measureCache[e]});const webSafeFonts=["Arial","Courier New","Times New Roman","Verdana","sans-serif","serif","monospace","cursive","fantasy"],processedFontFamilies={};function getFonts(e,t="https://cdn.jsdelivr.net/npm/@fontsource/{font-family}/{fontweight}{-fontstyle}.css"){if(WORKER_OFFSCREEN_CANVAS)return e;let r;for(let n=0,i=e.length;n{await document.fonts.ready;for(let e=0,n=r.length;ee.family.replace(/^['"]|['"]$/g,"").toLowerCase()===i.toLowerCase()&&e.weight==o&&e.style===s)){const e=t.replace("{font-family}",i.replace(/ /g,"-").toLowerCase()).replace("{Font+Family}",i.replace(/ /g,"+")).replace("{fontweight}",o).replace("{-fontstyle}",s.replace("normal","").replace(/(.+)/,"-$1")).replace("{fontstyle}",s);if(!document.querySelector('link[href="'+e+'"]')){const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)}}}})(),e):e}const types={Point:1,MultiPoint:1,LineString:2,MultiLineString:2,Polygon:3,MultiPolygon:3},anchor={center:[.5,.5],left:[0,.5],right:[1,.5],top:[.5,0],bottom:[.5,1],"top-left":[0,0],"top-right":[1,0],"bottom-left":[0,1],"bottom-right":[1,1]},expressionData=function(e,t){const r=createPropertyExpression(e,t);if("error"===r.result)throw new Error(r.value.map(e=>`${e.key}: ${e.message}`).join(", "));return r.value},cameraObj={zoom:0,distanceFromCenter:0};let renderFeatureCoordinates,renderFeature;function getValue(e,t,r,n,i,o){const s=e.id;i||(i={},console.warn("No functionCache provided to getValue()")),i[s]||(i[s]={});const a=i[s];if(!a[r]){let n=(e[t]||emptyObj)[r];const i=v8[`${t}_${e.type}`][r];void 0===n&&(n=i.default);let o=isExpression(n);if(!o&&isFunction$1(n)&&(n=convertFunction(n,i),o=!0),o){const e=expressionData(n,i);a[r]=e.evaluate.bind(e)}else{const e=i.type;"color"!==e&&"colorArray"!==e||(n=Color.parse(n)),a[r]=function(){return n}}}return a[r](cameraObj,n,o)}function getDeclutterMode(e,t,r,n){return getValue(e,"layout",`${r}-allow-overlap`,t,n)?getValue(e,"layout",`${r}-ignore-placement`,t,n)?"none":"obstacle":"declutter"}function evaluateFilter(e,t,r,n){if(n||console.warn("No filterCache provided to evaluateFilter()"),!(e in n))try{n[e]=featureFilter(t).filter}catch(i){console.warn("Filter will evaluate to false: "+i.message),n[e]=function(){return!1}}return n[e](cameraObj,r)}function colorWithOpacity(e,t){if(e){if(0===e.a||0===t)return;const r=e.a;return t=void 0===t?1:t,0===r?"transparent":"rgba("+Math.round(255*e.r/r)+","+Math.round(255*e.g/r)+","+Math.round(255*e.b/r)+","+r*t+")"}return e}CompoundExpression.register(expressions$1,{...CompoundExpression.definitions,pitch:[{kind:"number"},[],()=>cameraObj.pitch||90],"distance-from-center":[{kind:"number"},[],()=>cameraObj.distanceFromCenter||0]});const templateRegEx=/\{[^{}}]*\}/g;function fromTemplate(e,t){return e.replace(templateRegEx,function(e){return t[e.slice(1,-1)]||""})}function getSpriteImageForIcon(e,t){let r=e.split(":")[0];return r===e&&(r="default"),t[r]}const styleFunctionArgs={};function stylefunction(e,t,r,n=defaultResolutions,i,o,s,a){if("string"==typeof t&&(t=JSON.parse(t)),8!=t.version)throw new Error("glStyle version 8 required.");styleFunctionArgs[getStyleFunctionKey(t,e)]=Array.from(arguments);const l={};("string"==typeof o||o instanceof Request||o instanceof Response||o instanceof Promise)&&(o={default:o});for(const E in o){const t=o[E];toPromise(()=>t).then(async t=>{let r;if("undefined"!=typeof Image){const n=new Image;if("string"==typeof t)n.crossOrigin="anonymous",n.src=t;else{let e;t instanceof Request?e=await fetch(t):t instanceof Response&&(e=t);const i=await e.blob();r=URL.createObjectURL(i),n.src=r}n.addEventListener("load",function t(){n.removeEventListener("load",t),l[E]={image:n,size:[n.width,n.height]},e.changed(),r&&URL.revokeObjectURL(r)}),n.addEventListener("error",function e(){URL.revokeObjectURL(r),n.removeEventListener("error",e)})}else if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope){const e=self;e.postMessage({action:"loadImage",src:t}),e.addEventListener("message",function(e){"imageLoaded"===e.data.action&&e.data.src===t&&(l[E]={image:e.data.image,size:[e.data.image.width,e.data.image.height]})})}})}const c=derefLayers(t.layers),u={},h=[],d={},p={},f=getFunctionCache(t),g=getFilterCache(t);let m;for(let E=0,w=c.length;E=h.maxzoom)continue;const I=h.filter;if(!I||evaluateFilter(w,I,T,g)){let n,c,g,_,E,w;const I=u.index;if(3==C&&("fill"==h.type||"fill-extrusion"==h.type))if(c=getValue(h,"paint",h.type+"-opacity",T,f,x),h.type+"-pattern"in A){const e=getValue(h,"paint",h.type+"-pattern",T,f,x);if(e){const t="string"==typeof e?fromTemplate(e,m):e.toString(),r=getSpriteImageForIcon(t,l);if(i&&i[t]&&r){++R,w=v[R],w&&w.getFill()&&!w.getStroke()&&!w.getText()||(w=new Style({fill:new Fill}),v[R]=w),g=w.getFill(),w.setZIndex(I);const e=t+"."+c;let n=p[e];if(!n){const o=i[t],s=createCanvas(o.width,o.height),a=s.getContext("2d");a.globalAlpha=c,a.drawImage(r.image,o.x,o.y,o.width,o.height,0,0,o.width,o.height),n=a.createPattern(s,"repeat"),p[e]=n}g.setColor(n)}}}else n=colorWithOpacity(getValue(h,"paint",h.type+"-color",T,f,x),c),h.type+"-outline-color"in A&&(E=colorWithOpacity(getValue(h,"paint",h.type+"-outline-color",T,f,x),c)),E||(E=n),(n||E)&&(++R,w=v[R],(!w||n&&!w.getFill()||!n&&w.getFill()||E&&!w.getStroke()||!E&&w.getStroke()||w.getText())&&(w=new Style({fill:n?new Fill:void 0,stroke:E?new Stroke:void 0}),v[R]=w),n&&(g=w.getFill(),g.setColor(n)),E&&(_=w.getStroke(),_.setColor(E),_.setWidth(.5)),w.setZIndex(I));if(1!=C&&"line"==h.type){n="line-pattern"in A?void 0:colorWithOpacity(getValue(h,"paint","line-color",T,f,x),getValue(h,"paint","line-opacity",T,f,x));const e=getValue(h,"paint","line-width",T,f,x);n&&e>0&&(++R,w=v[R],w&&w.getStroke()&&!w.getFill()&&!w.getText()||(w=new Style({stroke:new Stroke}),v[R]=w),_=w.getStroke(),_.setLineCap(getValue(h,"layout","line-cap",T,f,x)),_.setLineJoin(getValue(h,"layout","line-join",T,f,x)),_.setMiterLimit(getValue(h,"layout","line-miter-limit",T,f,x)),_.setColor(n),_.setWidth(e),_.setLineDash(A["line-dasharray"]?getValue(h,"paint","line-dasharray",T,f,x).map(function(t){return t*e}):null),w.setZIndex(I))}let P,k,O,L,M,D,N,F,$,B=!1,U=null,z=0;if((1==C||2==C)&&"icon-image"in S){const t=getValue(h,"layout","icon-image",T,f,x);if(t){let n;P="string"==typeof t?fromTemplate(t,m):t.toString();const s=a?a(e,P):void 0,c=getSpriteImageForIcon(P,l);if(i&&i[P]&&c||s){const e=getValue(h,"layout","icon-rotation-alignment",T,f,x);if(2==C){const t=r.getGeometry();if(t.getFlatMidpoint||t.getFlatMidpoints){const r=t.getExtent();if(Math.sqrt(Math.max(Math.pow((r[2]-r[0])/o,2),Math.pow((r[3]-r[1])/o,2)))>150){const r="MultiLineString"===t.getType()?t.getFlatMidpoints():t.getFlatMidpoint();if(renderFeature||(renderFeatureCoordinates=[NaN,NaN],renderFeature=new RenderFeature("Point",renderFeatureCoordinates,[],2,{},void 0)),n=renderFeature,renderFeatureCoordinates[0]=r[0],renderFeatureCoordinates[1]=r[1],"line"===getValue(h,"layout","symbol-placement",T,f,x)&&"map"===e){const e=t.getStride(),n=t.getFlatCoordinates();for(let t=0,i=n.length-e;t=l){z=Math.atan2(o-a,s-i);break}}}}}}if(2!==C||n){const t=getValue(h,"layout","icon-size",T,f,x),r=void 0!==A["icon-color"]?getValue(h,"paint","icon-color",T,f,x):null;if(!r||0!==r.a){const n=getValue(h,"paint","icon-halo-color",T,f,x),o=getValue(h,"paint","icon-halo-width",T,f,x);let a=`${P}.${t}.${o}.${n}`;if(null!==r&&(a+=`.${r}`),k=d[a],!k){const l=getDeclutterMode(h,T,"icon",f);let u;"icon-offset"in S&&(u=getValue(h,"layout","icon-offset",T,f,x).slice(0),u[0]*=t,u[1]*=-t);let p=r?[255*r.r,255*r.g,255*r.b,r.a]:void 0;if(s){const r={color:p,rotateWithView:"map"===e,displacement:u,declutterMode:l,scale:t};"string"==typeof s?r.src=s:(r.img=s,r.imgSize=[s.width,s.height]),k=new Icon(r)}else{const s=i[P];let a,h,d;if(o)s.sdf?(a=drawIconHalo(drawSDF(c.image,s,r||[0,0,0,1]),{x:0,y:0,width:s.width,height:s.height,pixelRatio:s.pixelRatio},o,n),p=void 0):a=drawIconHalo(c.image,s,o,n);else{if(s.sdf&&!c.unSDFed){const e=drawSDF(c.image,{x:0,y:0,width:c.size[0],height:c.size[1]},{r:1,g:1,b:1});c.image=e,c.unSDFed=!0}a=c.image,h=[s.width,s.height],d=[s.x,s.y]}k=new Icon({color:p,img:a,imgSize:c.size,size:h,offset:d,rotateWithView:"map"===e,scale:t/s.pixelRatio,displacement:u,declutterMode:l})}d[a]=k}}k&&(++R,w=v[R],w&&w.getImage()&&!w.getFill()&&!w.getStroke()||(w=new Style,v[R]=w),w.setGeometry(n),k.setRotation(z+deg2rad(getValue(h,"layout","icon-rotate",T,f,x))),k.setOpacity(getValue(h,"paint","icon-opacity",T,f,x)),k.setAnchor(anchor[getValue(h,"layout","icon-anchor",T,f,x)]),w.setImage(k),U=w.getText(),w.setText(void 0),w.setZIndex(I),B=!0,O=!1)}else O=!0}}}if(1==C&&"circle"===h.type){++R,w=v[R],w&&w.getImage()&&!w.getFill()&&!w.getStroke()||(w=new Style,v[R]=w);const e="circle-radius"in A?getValue(h,"paint","circle-radius",T,f,x):5,t=colorWithOpacity(getValue(h,"paint","circle-stroke-color",T,f,x),getValue(h,"paint","circle-stroke-opacity",T,f,x)),r=getValue(h,"paint","circle-translate",T,f,x),n=colorWithOpacity(getValue(h,"paint","circle-color",T,f,x),getValue(h,"paint","circle-opacity",T,f,x)),i=getValue(h,"paint","circle-stroke-width",T,f,x),o=e+"."+t+"."+n+"."+i+"."+r[0]+"."+r[1];k=d[o],k||(k=new CircleStyle({radius:e,displacement:[r[0],-r[1]],stroke:t&&i>0?new Stroke({width:i,color:t}):void 0,fill:n?new Fill({color:n}):void 0,declutterMode:"none"}),d[o]=k),w.setImage(k),U=w.getText(),w.setText(void 0),w.setGeometry(void 0),w.setZIndex(I),B=!0}if("text-field"in S){N=Math.round(getValue(h,"layout","text-size",T,f,x));const e=getValue(h,"layout","text-font",T,f,x);D=getValue(h,"layout","text-line-height",T,f,x),M=mb2css(s?s(e,t.metadata?t.metadata["ol:webfonts"]:void 0):e,N,D),M.includes("sans-serif")||(M+=",sans-serif"),F=getValue(h,"layout","text-letter-spacing",T,f,x),$=getValue(h,"layout","text-max-width",T,f,x);const r=getValue(h,"layout","text-field",T,f,x);L="object"==typeof r&&r.sections?1===r.sections.length?r.toString():r.sections.reduce((t,r)=>{const n=r.fontStack?r.fontStack.split(","):e,i=mb2css(s?s(n):n,N*(r.scale||1),D);let o=r.text;if("\n"===o)return t.push("\n",""),t;if(2==C)return t.push(applyLetterSpacing(o,F),i),t;o=wrapText(o,i,$,F).split("\n");for(let e=0,s=o.length;e0&&t.push("\n",""),t.push(o[e],i);return t},[]):fromTemplate(r,m).trim(),c=getValue(h,"paint","text-opacity",T,f,x)}if(L&&c&&!O){B||(++R,w=v[R],w&&w.getText()&&!w.getFill()&&!w.getStroke()||(w=new Style,v[R]=w),w.setImage(void 0),w.setGeometry(void 0));const e=getDeclutterMode(h,T,"text",f);w.getText()||w.setText(U),U=w.getText(),(!U||"getDeclutterMode"in U&&U.getDeclutterMode()!==e)&&(U=new Text$1({padding:[2,2,2,2],declutterMode:e}),w.setText(U));const t=getValue(h,"layout","text-transform",T,f,x);"uppercase"==t?L=Array.isArray(L)?L.map((e,t)=>t%2?e:e.toUpperCase()):L.toUpperCase():"lowercase"==t&&(L=Array.isArray(L)?L.map((e,t)=>t%2?e:e.toLowerCase()):L.toLowerCase());const r=Array.isArray(L)?L:2==C?applyLetterSpacing(L,F):wrapText(L,M,$,F);if(U.setText(r),U.setFont(M),U.setRotation(deg2rad(getValue(h,"layout","text-rotate",T,f,x))),"function"==typeof U.setKeepUpright){const e=getValue(h,"layout","text-keep-upright",T,f,x);U.setKeepUpright(e)}const n=getValue(h,"layout","text-anchor",T,f,x),i=B||1==C?"point":getValue(h,"layout","symbol-placement",T,f,x);let o;if("line-center"===i?(U.setPlacement("line"),o="center"):U.setPlacement(i),"line"===i&&"function"==typeof U.setRepeat){const e=getValue(h,"layout","symbol-spacing",T,f,x);U.setRepeat(2*e)}U.setOverflow("point"===i);let s=getValue(h,"paint","text-halo-width",T,f,x);const a=getValue(h,"layout","text-offset",T,f,x),l=getValue(h,"paint","text-translate",T,f,x);let u=0,d=0;if("point"==i){o="center",-1!==n.indexOf("left")?(o="left",d=s):-1!==n.indexOf("right")&&(o="right",d=-s);const e=getValue(h,"layout","text-rotation-alignment",T,f,x);U.setRotateWithView("map"==e)}else U.setMaxAngle(deg2rad(getValue(h,"layout","text-max-angle",T,f,x))*L.length/r.length),U.setRotateWithView(!1);U.setTextAlign(o);let p="middle";0==n.indexOf("bottom")?(p="bottom",u=-s-.5*(D-1)*N):0==n.indexOf("top")&&(p="top",u=s+.5*(D-1)*N),U.setTextBaseline(p);const g=getValue(h,"layout","text-justify",T,f,x);U.setJustify("auto"===g?void 0:g),U.setOffsetX(a[0]*N+d+l[0]),U.setOffsetY(a[1]*N+u+l[1]),b.setColor(colorWithOpacity(getValue(h,"paint","text-color",T,f,x),c)),U.setFill(b);const m=colorWithOpacity(getValue(h,"paint","text-halo-color",T,f,x),c);if(m&&s>0){y.setColor(m),s*=2;const e=.5*N;y.setWidth(s<=e?s:e),U.setStroke(y)}else U.setStroke(void 0);const _=getValue(h,"layout","text-padding",T,f,x),E=U.getPadding();_!==E[0]&&(E[0]=_,E[1]=_,E[2]=_,E[3]=_),w.setZIndex(I)}}}return R>-1?(v.length=R+1,v):void 0};return e.setStyle(_),e.set("mapbox-layers",h),e.set("mapbox-source",m),e.set("mapbox-featurestate",e.get("mapbox-featurestate")||{}),_}const SHIFT_LEFT_32=4294967296,SHIFT_RIGHT_32=1/SHIFT_LEFT_32,TEXT_DECODER_MIN_LENGTH=12,utf8TextDecoder="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8"),PBF_VARINT=0,PBF_FIXED64=1,PBF_BYTES=2,PBF_FIXED32=5;class Pbf{constructor(e=new Uint8Array(16)){this.buf=ArrayBuffer.isView(e)?e:new Uint8Array(e),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(e,t,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,e(n,t,this),this.pos===i&&this.skip(r)}return t}readMessage(e,t){return this.readFields(e,t,this.readVarint()+this.pos)}readFixed32(){const e=this.dataView.getUint32(this.pos,!0);return this.pos+=4,e}readSFixed32(){const e=this.dataView.getInt32(this.pos,!0);return this.pos+=4,e}readFixed64(){const e=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*SHIFT_LEFT_32;return this.pos+=8,e}readSFixed64(){const e=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*SHIFT_LEFT_32;return this.pos+=8,e}readFloat(){const e=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,e}readDouble(){const e=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,e}readVarint(e){const t=this.buf;let r,n;return n=t[this.pos++],r=127&n,n<128?r:(n=t[this.pos++],r|=(127&n)<<7,n<128?r:(n=t[this.pos++],r|=(127&n)<<14,n<128?r:(n=t[this.pos++],r|=(127&n)<<21,n<128?r:(n=t[this.pos],r|=(15&n)<<28,readVarintRemainder(r,e,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const e=this.readVarint();return e%2==1?(e+1)/-2:e/2}readBoolean(){return Boolean(this.readVarint())}readString(){const e=this.readVarint()+this.pos,t=this.pos;return this.pos=e,e-t>=TEXT_DECODER_MIN_LENGTH&&utf8TextDecoder?utf8TextDecoder.decode(this.buf.subarray(t,e)):readUtf8(this.buf,t,e)}readBytes(){const e=this.readVarint()+this.pos,t=this.buf.subarray(this.pos,e);return this.pos=e,t}readPackedVarint(e=[],t){const r=this.readPackedEnd();for(;this.pos127;);else if(t===PBF_BYTES)this.pos=this.readVarint()+this.pos;else if(t===PBF_FIXED32)this.pos+=4;else{if(t!==PBF_FIXED64)throw new Error(`Unimplemented type: ${t}`);this.pos+=8}}writeTag(e,t){this.writeVarint(e<<3|t)}realloc(e){let t=this.length||16;for(;t268435455||e<0?writeBigVarint(e,this):(this.realloc(4),this.buf[this.pos++]=127&e|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=e>>>7&127))))}writeSVarint(e){this.writeVarint(e<0?2*-e-1:2*e)}writeBoolean(e){this.writeVarint(+e)}writeString(e){e=String(e),this.realloc(4*e.length),this.pos++;const t=this.pos;this.pos=writeUtf8(this.buf,e,this.pos);const r=this.pos-t;r>=128&&makeRoomForExtraLength(t,r,this),this.pos=t-1,this.writeVarint(r),this.pos+=r}writeFloat(e){this.realloc(4),this.dataView.setFloat32(this.pos,e,!0),this.pos+=4}writeDouble(e){this.realloc(8),this.dataView.setFloat64(this.pos,e,!0),this.pos+=8}writeBytes(e){const t=e.length;this.writeVarint(t),this.realloc(t);for(let r=0;r=128&&makeRoomForExtraLength(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n}writeMessage(e,t,r){this.writeTag(e,PBF_BYTES),this.writeRawMessage(t,r)}writePackedVarint(e,t){t.length&&this.writeMessage(e,writePackedVarint,t)}writePackedSVarint(e,t){t.length&&this.writeMessage(e,writePackedSVarint,t)}writePackedBoolean(e,t){t.length&&this.writeMessage(e,writePackedBoolean,t)}writePackedFloat(e,t){t.length&&this.writeMessage(e,writePackedFloat,t)}writePackedDouble(e,t){t.length&&this.writeMessage(e,writePackedDouble,t)}writePackedFixed32(e,t){t.length&&this.writeMessage(e,writePackedFixed32,t)}writePackedSFixed32(e,t){t.length&&this.writeMessage(e,writePackedSFixed32,t)}writePackedFixed64(e,t){t.length&&this.writeMessage(e,writePackedFixed64,t)}writePackedSFixed64(e,t){t.length&&this.writeMessage(e,writePackedSFixed64,t)}writeBytesField(e,t){this.writeTag(e,PBF_BYTES),this.writeBytes(t)}writeFixed32Field(e,t){this.writeTag(e,PBF_FIXED32),this.writeFixed32(t)}writeSFixed32Field(e,t){this.writeTag(e,PBF_FIXED32),this.writeSFixed32(t)}writeFixed64Field(e,t){this.writeTag(e,PBF_FIXED64),this.writeFixed64(t)}writeSFixed64Field(e,t){this.writeTag(e,PBF_FIXED64),this.writeSFixed64(t)}writeVarintField(e,t){this.writeTag(e,PBF_VARINT),this.writeVarint(t)}writeSVarintField(e,t){this.writeTag(e,PBF_VARINT),this.writeSVarint(t)}writeStringField(e,t){this.writeTag(e,PBF_BYTES),this.writeString(t)}writeFloatField(e,t){this.writeTag(e,PBF_FIXED32),this.writeFloat(t)}writeDoubleField(e,t){this.writeTag(e,PBF_FIXED64),this.writeDouble(t)}writeBooleanField(e,t){this.writeVarintField(e,+t)}}function readVarintRemainder(e,t,r){const n=r.buf;let i,o;if(o=n[r.pos++],i=(112&o)>>4,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<3,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<10,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<17,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<24,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(1&o)<<31,o<128)return toNum(e,i,t);throw new Error("Expected varint not more than 10 bytes")}function toNum(e,t,r){return r?4294967296*t+(e>>>0):4294967296*(t>>>0)+(e>>>0)}function writeBigVarint(e,t){let r,n;if(e>=0?(r=e%4294967296|0,n=e/4294967296|0):(r=~(-e%4294967296),n=~(-e/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),e>=0x10000000000000000||e<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");t.realloc(10),writeBigVarintLow(r,n,t),writeBigVarintHigh(n,t)}function writeBigVarintLow(e,t,r){r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos]=127&e}function writeBigVarintHigh(e,t){const r=(7&e)<<4;t.buf[t.pos++]|=r|((e>>>=3)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e)))))}function makeRoomForExtraLength(e,t,r){const n=t<=16383?1:t<=2097151?2:t<=268435455?3:Math.floor(Math.log(t)/(7*Math.LN2));r.realloc(n);for(let i=r.pos-1;i>=e;i--)r.buf[i+n]=r.buf[i]}function writePackedVarint(e,t){for(let r=0;r239?4:t>223?3:t>191?2:1;if(i+c>r)break;1===c?t<128&&(l=t):2===c?(o=e[i+1],128==(192&o)&&(l=(31&t)<<6|63&o,l<=127&&(l=null))):3===c?(o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(l=(15&t)<<12|(63&o)<<6|63&s,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===c&&(o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(l=(15&t)<<18|(63&o)<<12|(63&s)<<6|63&a,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,c=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=c}return n}function writeUtf8(e,t,r){for(let n,i,o=0;o55295&&n<57344){if(!i){n>56319||o+1===t.length?(e[r++]=239,e[r++]=191,e[r++]=189):i=n;continue}if(n<56320){e[r++]=239,e[r++]=191,e[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(e[r++]=239,e[r++]=191,e[r++]=189,i=null);n<128?e[r++]=n:(n<2048?e[r++]=n>>6|192:(n<65536?e[r++]=n>>12|224:(e[r++]=n>>18|240,e[r++]=n>>12&63|128),e[r++]=n>>6&63|128),e[r++]=63&n|128)}return r}class MVT extends FeatureFormat{constructor(e){super(),e=e||{},this.dataProjection=new Projection({code:"",units:"tile-pixels"}),this.featureClass=e.featureClass?e.featureClass:RenderFeature,this.geometryName_=e.geometryName,this.layerName_=e.layerName?e.layerName:"layer",this.layers_=e.layers?e.layers:null,this.idProperty_=e.idProperty,this.supportedMediaTypes=["application/vnd.mapbox-vector-tile","application/x-protobuf"]}readRawGeometry_(e,t,r,n){e.pos=t.geometry;const i=e.readVarint()+e.pos;let o=1,s=0,a=0,l=0,c=0,u=0;for(;e.pos>3}if(s--,1===o||2===o)a+=e.readSVarint(),l+=e.readSVarint(),1===o&&c>u&&(n.push(c),u=c),r.push(a,l),c+=2;else{if(7!==o)throw new Error("Invalid command found in the PBF");c>u&&(r.push(r[u],r[u+1]),c+=2)}}c>u&&(n.push(c),u=c)}createFeature_(e,t,r){const n=t.type;if(0===n)return null;let i;const o=t.properties;let s;this.idProperty_?(s=o[this.idProperty_],delete o[this.idProperty_]):s=t.id,o[this.layerName_]=t.layer.name;const a=[],l=[];this.readRawGeometry_(e,t,a,l);const c=getGeometryType(n,l.length);if(this.featureClass===RenderFeature)i=new this.featureClass(c,a,l,2,o,s),i.transform(r.dataProjection);else{let e;if("Polygon"==c){const t=inflateEnds(a,l);e=t.length>1?new MultiPolygon(a,"XY",t):new Polygon(a,"XY",l)}else e="Point"===c?new Point(a,"XY"):"LineString"===c?new LineString(a,"XY"):"MultiPoint"===c?new MultiPoint(a,"XY"):"MultiLineString"===c?new MultiLineString(a,"XY",l):null;i=new(0,this.featureClass),this.geometryName_&&i.setGeometryName(this.geometryName_);const t=transformGeometryWithOptions(e,!1,r);i.setGeometry(t),void 0!==s&&i.setId(s),i.setProperties(o,!0)}return i}getType(){return"arraybuffer"}readFeatures(e,t){const r=this.layers_,n=get$2((t=this.adaptOptions(t)).dataProjection);n.setWorldExtent(t.extent),t.dataProjection=n;const i=new Pbf(e),o=i.readFields(layersPBFReader,{}),s=[];for(const a in o){if(r&&!r.includes(a))continue;const e=o[a],l=e?[0,0,e.extent,e.extent]:null;n.setExtent(l);for(let r=0,n=e.length;r>3)?r.readString():2===e?r.readFloat():3===e?r.readDouble():4===e?r.readVarint64():5===e?r.readVarint():6===e?r.readSVarint():7===e?r.readBoolean():null;t.values.push(n)}}function featurePBFReader(e,t,r){if(1==e)t.id=r.readVarint();else if(2==e){const e=r.readVarint()+r.pos;for(;r.pos=s.width)return null;const c=getHeight(o),u=Math.floor(s.height*((o[3]-n[1])/c));return u<0||u>=s.height?null:this.getImageData(s,l,u)}renderFrame(e,t){const r=this.image,n=r.getExtent(),i=r.getResolution(),[o,s]=Array.isArray(i)?i:[i,i],a=r.getPixelRatio(),l=e.layerStatesArray[e.layerIndex],c=e.pixelRatio,u=e.viewState,h=u.center,d=u.resolution,p=c*o/(d*a),f=c*s/(d*a);this.prepareContainer(e,t);const g=this.context.canvas.width,m=this.context.canvas.height,y=this.getRenderContext(e);let b=!1,v=!0;if(l.extent){const t=fromUserExtent(l.extent,u.projection);v=intersects$1(t,e.extent),b=v&&!containsExtent(t,e.extent),b&&this.clipUnrotated(y,e,t)}const _=r.getImage(),E=compose(this.tempTransform,g/2,m/2,p,f,0,a*(n[0]-h[0])/o,a*(h[1]-n[3])/s);this.renderedResolution=s*c/a;const w=_.width*E[0],C=_.height*E[3];if(this.getLayer().getSource().getInterpolate()||(y.imageSmoothingEnabled=!1),this.preRender(y,e),v&&w>=.5&&C>=.5){const e=E[4],t=E[5],r=l.opacity;1!==r&&(y.save(),y.globalAlpha=r),y.drawImage(_,0,0,+_.width,+_.height,e,t,w,C),1!==r&&y.restore()}return this.postRender(this.context,e),b&&y.restore(),y.imageSmoothingEnabled=!0,this.container}}class BaseImageLayer extends Layer{constructor(e){super(e=e||{})}}class ImageLayer extends BaseImageLayer{constructor(e){super(e)}createRenderer(){return new CanvasImageLayerRenderer(this)}getData(e){return super.getData(e)}}function asImageLike(e){return e instanceof Image||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageBitmap?e:null}const disposedError=new Error("disposed"),defaultSize=[256,256];class DataTile extends Tile{constructor(e){const t=TileState.IDLE;super(e.tileCoord,t,{transition:e.transition,interpolate:e.interpolate}),this.loader_=e.loader,this.data_=null,this.error_=null,this.size_=e.size||null,this.controller_=e.controller||null}getSize(){if(this.size_)return this.size_;const e=asImageLike(this.data_);return e?[e.width,e.height]:defaultSize}getData(){return this.data_}getError(){return this.error_}load(){if(this.state!==TileState.IDLE&&this.state!==TileState.ERROR)return;this.state=TileState.LOADING,this.changed();const e=this;this.loader_().then(function(t){e.data_=t,e.state=TileState.LOADED,e.changed()}).catch(function(t){e.error_=t,e.state=TileState.ERROR,e.changed()})}disposeInternal(){this.controller_&&(this.controller_.abort(disposedError),this.controller_=null),super.disposeInternal()}}let brokenDiagonalRendering_;const canvasPool=[];function drawTestTriangle(e,t,r,n,i){e.beginPath(),e.moveTo(0,0),e.lineTo(t,r),e.lineTo(n,i),e.closePath(),e.save(),e.clip(),e.fillRect(0,0,Math.max(t,n)+1,Math.max(r,i)),e.restore()}function verifyBrokenDiagonalRendering(e,t){return Math.abs(e[4*t]-210)>2||Math.abs(e[4*t+3]-191.25)>2}function isBrokenDiagonalRendering(){if(void 0===brokenDiagonalRendering_){const e=createCanvasContext2D(6,6,canvasPool);e.globalCompositeOperation="lighter",e.fillStyle="rgba(210, 0, 0, 0.75)",drawTestTriangle(e,4,5,4,0),drawTestTriangle(e,4,5,0,5);const t=e.getImageData(0,0,3,3).data;brokenDiagonalRendering_=verifyBrokenDiagonalRendering(t,0)||verifyBrokenDiagonalRendering(t,4)||verifyBrokenDiagonalRendering(t,8),releaseCanvas(e),canvasPool.push(e.canvas)}return brokenDiagonalRendering_}function calculateSourceResolution(e,t,r,n){const i=transform(r,t,e);let o=getPointResolution(t,n,r);const s=t.getMetersPerUnit();void 0!==s&&(o*=s);const a=e.getMetersPerUnit();void 0!==a&&(o/=a);const l=e.getExtent();if(!l||containsCoordinate(l,i)){const t=getPointResolution(e,o,i)/o;isFinite(t)&&t>0&&(o/=t)}return o}function calculateSourceExtentResolution(e,t,r,n){const i=getCenter(r);let o=calculateSourceResolution(e,t,i,n);return(!isFinite(o)||o<=0)&&forEachCorner(r,function(r){return o=calculateSourceResolution(e,t,r,n),isFinite(o)&&o>0}),o}function render(e,t,r,n,i,o,s,a,l,c,u,h,d){const p=createCanvasContext2D(Math.round(r*e),Math.round(r*t),canvasPool);if(h||(p.imageSmoothingEnabled=!1),0===l.length)return p.canvas;function f(e){return Math.round(e*r)/r}p.scale(r,r),p.globalCompositeOperation="lighter";const g=createEmpty();let m;l.forEach(function(e){extend$1(g,e.extent)});const y=r/n,b=(h?1:1+Math.pow(2,-24))/y;d&&1===l.length&&0===c||(m=createCanvasContext2D(Math.round(getWidth(g)*y),Math.round(getHeight(g)*y),canvasPool),h||(m.imageSmoothingEnabled=!1),l.forEach(function(e){if(e.image.width>0&&e.image.height>0){if(e.clipExtent){m.save();const t=(e.clipExtent[0]-g[0])*y,r=-(e.clipExtent[3]-g[3])*y,n=getWidth(e.clipExtent)*y,i=getHeight(e.clipExtent)*y;m.rect(h?t:Math.round(t),h?r:Math.round(r),h?n:Math.round(t+n)-Math.round(t),h?i:Math.round(r+i)-Math.round(r)),m.clip()}const t=(e.extent[0]-g[0])*y,r=-(e.extent[3]-g[3])*y,n=getWidth(e.extent)*y,i=getHeight(e.extent)*y;m.drawImage(e.image,c,c,e.image.width-2*c,e.image.height-2*c,h?t:Math.round(t),h?r:Math.round(r),h?n:Math.round(t+n)-Math.round(t),h?i:Math.round(r+i)-Math.round(r)),e.clipExtent&&m.restore()}}));const v=getTopLeft(s);return a.getTriangles().forEach(function(e){const t=e.source,r=e.target;let n=t[0][0],i=t[0][1],s=t[1][0],a=t[1][1],c=t[2][0],u=t[2][1];const d=f((r[0][0]-v[0])/o),y=f(-(r[0][1]-v[1])/o),_=f((r[1][0]-v[0])/o),E=f(-(r[1][1]-v[1])/o),w=f((r[2][0]-v[0])/o),C=f(-(r[2][1]-v[1])/o),S=n,T=i;n=0,i=0,s-=S,a-=T,c-=S,u-=T;const x=solveLinearSystem([[s,a,0,0,_-d],[c,u,0,0,w-d],[0,0,s,a,E-y],[0,0,c,u,C-y]]);if(!x)return;if(p.save(),p.beginPath(),isBrokenDiagonalRendering()||!h){p.moveTo(_,E);const e=4,t=d-_,r=y-E;for(let n=0;napply$1(s,transform(e,this.targetProj_,this.sourceProj_))):getTransform(this.targetProj_,this.sourceProj_);this.transformInv_=function(e){const t=e[0]+"/"+e[1];return a[t]||(a[t]=l(e)),a[t]},this.maxSourceExtent_=n,this.errorThresholdSquared_=i*i,this.triangles_=[],this.wrapsXInSource_=!1,this.canWrapXInSource_=this.sourceProj_.canWrapX()&&!!n&&!!this.sourceProj_.getExtent()&&getWidth(n)>=getWidth(this.sourceProj_.getExtent()),this.sourceWorldWidth_=this.sourceProj_.getExtent()?getWidth(this.sourceProj_.getExtent()):null,this.targetWorldWidth_=this.targetProj_.getExtent()?getWidth(this.targetProj_.getExtent()):null;const c=getTopLeft(r),u=getTopRight(r),h=getBottomRight(r),d=getBottomLeft(r),p=this.transformInv_(c),f=this.transformInv_(u),g=this.transformInv_(h),m=this.transformInv_(d),y=MAX_SUBDIVISION+(o?Math.max(0,Math.ceil(Math.log2(getArea(r)/(o*o*256*256)))):0);if(this.addQuad_(c,u,h,d,p,f,g,m,y),this.wrapsXInSource_){let e=1/0;this.triangles_.forEach(function(t){e=Math.min(e,t.source[0][0],t.source[1][0],t.source[2][0])}),this.triangles_.forEach(t=>{if(Math.max(t.source[0][0],t.source[1][0],t.source[2][0])-e>this.sourceWorldWidth_/2){const r=[[t.source[0][0],t.source[0][1]],[t.source[1][0],t.source[1][1]],[t.source[2][0],t.source[2][1]]];r[0][0]-e>this.sourceWorldWidth_/2&&(r[0][0]-=this.sourceWorldWidth_),r[1][0]-e>this.sourceWorldWidth_/2&&(r[1][0]-=this.sourceWorldWidth_),r[2][0]-e>this.sourceWorldWidth_/2&&(r[2][0]-=this.sourceWorldWidth_);const n=Math.min(r[0][0],r[1][0],r[2][0]);Math.max(r[0][0],r[1][0],r[2][0])-n.5&&u<1;let p=!1;if(l>0&&(this.targetProj_.isGlobal()&&this.targetWorldWidth_&&(p=getWidth(boundingExtent([e,t,r,n]))/this.targetWorldWidth_>MAX_TRIANGLE_WIDTH||p),!d&&this.sourceProj_.isGlobal()&&u&&(p=u>MAX_TRIANGLE_WIDTH||p)),!p&&this.maxSourceExtent_&&isFinite(c[0])&&isFinite(c[1])&&isFinite(c[2])&&isFinite(c[3])&&!intersects$1(c,this.maxSourceExtent_))return;let f=0;if(!(p||isFinite(i[0])&&isFinite(i[1])&&isFinite(o[0])&&isFinite(o[1])&&isFinite(s[0])&&isFinite(s[1])&&isFinite(a[0])&&isFinite(a[1])))if(l>0)p=!0;else if(f=(isFinite(i[0])&&isFinite(i[1])?0:8)+(isFinite(o[0])&&isFinite(o[1])?0:4)+(isFinite(s[0])&&isFinite(s[1])?0:2)+(isFinite(a[0])&&isFinite(a[1])?0:1),1!=f&&2!=f&&4!=f&&8!=f)return;if(l>0){if(!p){const t=[(e[0]+r[0])/2,(e[1]+r[1])/2],n=this.transformInv_(t);let o;o=d?(modulo(i[0],h)+modulo(s[0],h))/2-modulo(n[0],h):(i[0]+s[0])/2-n[0];const a=(i[1]+s[1])/2-n[1];p=o*o+a*a>this.errorThresholdSquared_}if(p){if(Math.abs(e[0]-r[0])<=Math.abs(e[1]-r[1])){const c=[(t[0]+r[0])/2,(t[1]+r[1])/2],u=this.transformInv_(c),h=[(n[0]+e[0])/2,(n[1]+e[1])/2],d=this.transformInv_(h);this.addQuad_(e,t,c,h,i,o,u,d,l-1),this.addQuad_(h,c,r,n,d,u,s,a,l-1)}else{const c=[(e[0]+t[0])/2,(e[1]+t[1])/2],u=this.transformInv_(c),h=[(r[0]+n[0])/2,(r[1]+n[1])/2],d=this.transformInv_(h);this.addQuad_(e,c,h,n,i,u,d,a,l-1),this.addQuad_(c,t,r,h,u,o,s,d,l-1)}return}}if(d){if(!this.canWrapXInSource_)return;this.wrapsXInSource_=!0}11&f||this.addTriangle_(e,r,n,i,s,a),14&f||this.addTriangle_(e,r,t,i,s,o),f&&(13&f||this.addTriangle_(t,n,e,o,a,i),7&f||this.addTriangle_(t,n,r,o,a,s))}calculateSourceExtent(){const e=createEmpty();return this.triangles_.forEach(function(t){const r=t.source;extendCoordinate(e,r[0]),extendCoordinate(e,r[1]),extendCoordinate(e,r[2])}),e}getTriangles(){return this.triangles_}}const ERROR_THRESHOLD=.5;class ReprojTile extends Tile{constructor(e,t,r,n,i,o,s,a,l,c,u,h){super(i,TileState.IDLE,h),this.renderEdges_=void 0!==u&&u,this.pixelRatio_=s,this.gutter_=a,this.canvas_=null,this.sourceTileGrid_=t,this.targetTileGrid_=n,this.wrappedTileCoord_=o||i,this.sourceTiles_=[],this.sourcesListenerKeys_=null,this.sourceZ_=0,this.clipExtent_=e.canWrapX()?e.getExtent():void 0;const d=n.getTileCoordExtent(this.wrappedTileCoord_),p=this.targetTileGrid_.getExtent();let f=this.sourceTileGrid_.getExtent();const g=p?getIntersection(d,p):d;if(0===getArea(g))return void(this.state=TileState.EMPTY);const m=e.getExtent();m&&(f=f?getIntersection(f,m):m);const y=n.getResolution(this.wrappedTileCoord_[0]),b=calculateSourceExtentResolution(e,r,g,y);if(!isFinite(b)||b<=0)return void(this.state=TileState.EMPTY);const v=void 0!==c?c:ERROR_THRESHOLD;if(this.triangulation_=new Triangulation(e,r,g,f,b*v,y),0===this.triangulation_.getTriangles().length)return void(this.state=TileState.EMPTY);this.sourceZ_=t.getZForResolution(b);let _=this.triangulation_.calculateSourceExtent();if(f&&(e.canWrapX()?(_[1]=clamp$1(_[1],f[1],f[3]),_[3]=clamp$1(_[3],f[1],f[3])):_=getIntersection(_,f)),getArea(_)){let r=0,n=0;e.canWrapX()&&(r=getWidth(m),n=Math.floor((_[0]-m[0])/r)),wrapAndSliceX(_.slice(),e,!0).forEach(e=>{const i=t.getTileRangeForExtentAndZ(e,this.sourceZ_);for(let t=i.minX;t<=i.maxX;t++)for(let e=i.minY;e<=i.maxY;e++){const i=l(this.sourceZ_,t,e,s);if(i){const e=n*r;this.sourceTiles_.push({tile:i,offset:e})}}++n}),0===this.sourceTiles_.length&&(this.state=TileState.EMPTY)}else this.state=TileState.EMPTY}getImage(){return this.canvas_}reproject_(){const e=[];if(this.sourceTiles_.forEach(t=>{const r=t.tile;if(r&&r.getState()==TileState.LOADED){const n=this.sourceTileGrid_.getTileCoordExtent(r.tileCoord);n[0]+=t.offset,n[2]+=t.offset;const i=this.clipExtent_?.slice();i&&(i[0]+=t.offset,i[2]+=t.offset),e.push({extent:n,clipExtent:i,image:r.getImage()})}}),this.sourceTiles_.length=0,0===e.length)this.state=TileState.ERROR;else{const t=this.wrappedTileCoord_[0],r=this.targetTileGrid_.getTileSize(t),n="number"==typeof r?r:r[0],i="number"==typeof r?r:r[1],o=this.targetTileGrid_.getResolution(t),s=this.sourceTileGrid_.getResolution(this.sourceZ_),a=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_);this.canvas_=render(n,i,this.pixelRatio_,s,this.sourceTileGrid_.getExtent(),o,a,this.triangulation_,e,this.gutter_,this.renderEdges_,this.interpolate),this.state=TileState.LOADED}this.changed()}load(){if(this.state==TileState.IDLE){this.state=TileState.LOADING,this.changed();let e=0;this.sourcesListenerKeys_=[],this.sourceTiles_.forEach(({tile:t})=>{const r=t.getState();if(r==TileState.IDLE||r==TileState.LOADING){e++;const r=listen(t,EventType$1.CHANGE,()=>{const n=t.getState();n!=TileState.LOADED&&n!=TileState.ERROR&&n!=TileState.EMPTY||(unlistenByKey(r),e--,0===e&&(this.unlistenSources_(),this.reproject_()))});this.sourcesListenerKeys_.push(r)}}),0===e?setTimeout(this.reproject_.bind(this),0):this.sourceTiles_.forEach(function({tile:e}){e.getState()==TileState.IDLE&&e.load()})}}unlistenSources_(){this.sourcesListenerKeys_.forEach(unlistenByKey),this.sourcesListenerKeys_=null}release(){this.canvas_&&(releaseCanvas(this.canvas_.getContext("2d")),canvasPool.push(this.canvas_),this.canvas_=null),super.release()}}class LRUCache{constructor(e){this.highWaterMark=void 0!==e?e:2048,this.count_=0,this.entries_={},this.oldest_=null,this.newest_=null}deleteOldest(){const e=this.pop();e instanceof Disposable&&e.dispose()}canExpireCache(){return this.highWaterMark>0&&this.getCount()>this.highWaterMark}expireCache(e){for(;this.canExpireCache();)this.deleteOldest()}clear(){for(;this.oldest_;)this.deleteOldest()}containsKey(e){return this.entries_.hasOwnProperty(e)}forEach(e){let t=this.oldest_;for(;t;)e(t.value_,t.key_,this),t=t.newer}get(e,t){const r=this.entries_[e];return assert$1(void 0!==r,"Tried to get a value for a key that does not exist in the cache"),r===this.newest_||(r===this.oldest_?(this.oldest_=this.oldest_.newer,this.oldest_.older=null):(r.newer.older=r.older,r.older.newer=r.newer),r.newer=null,r.older=this.newest_,this.newest_.newer=r,this.newest_=r),r.value_}remove(e){const t=this.entries_[e];return assert$1(void 0!==t,"Tried to get a value for a key that does not exist in the cache"),t===this.newest_?(this.newest_=t.older,this.newest_&&(this.newest_.newer=null)):t===this.oldest_?(this.oldest_=t.newer,this.oldest_&&(this.oldest_.older=null)):(t.newer.older=t.older,t.older.newer=t.newer),delete this.entries_[e],--this.count_,t.value_}getCount(){return this.count_}getKeys(){const e=new Array(this.count_);let t,r=0;for(t=this.newest_;t;t=t.older)e[r++]=t.key_;return e}getValues(){const e=new Array(this.count_);let t,r=0;for(t=this.newest_;t;t=t.older)e[r++]=t.value_;return e}peekLast(){return this.oldest_.value_}peekLastKey(){return this.oldest_.key_}peekFirstKey(){return this.newest_.key_}peek(e){return this.entries_[e]?.value_}pop(){const e=this.oldest_;return delete this.entries_[e.key_],e.newer&&(e.newer.older=null),this.oldest_=e.newer,this.oldest_||(this.newest_=null),--this.count_,e.value_}replace(e,t){this.get(e),this.entries_[e].value_=t}set(e,t){assert$1(!(e in this.entries_),"Tried to set a value for a key that is used already");const r={key_:e,newer:null,older:this.newest_,value_:t};this.newest_?this.newest_.newer=r:this.oldest_=r,this.newest_=r,this.entries_[e]=r,++this.count_}setSize(e){this.highWaterMark=e}}function createOrUpdate(e,t,r,n){return void 0!==n?(n[0]=e,n[1]=t,n[2]=r,n):[e,t,r]}function getKeyZXY(e,t,r){return e+"/"+t+"/"+r}function getCacheKey(e,t,r,n,i){return`${getUid(e)},${t},${getKeyZXY(r,n,i)}`}function hash(e){return hashZXY(e[0],e[1],e[2])}function hashZXY(e,t,r){return(t<r||r>t.getMaxZoom())return!1;const o=t.getFullTileRange(r);return!o||o.containsXY(n,i)}function addTileToLookup(e,t,r){if(!(r in e))return e[r]=new Set([t]),!0;const n=e[r],i=n.has(t);return i||n.add(t),!i}function removeTileFromLookup(e,t,r){const n=e[r];return!!n&&n.delete(t)}function getRenderExtent(e,t){const r=e.layerStatesArray[e.layerIndex];r.extent&&(t=getIntersection(t,fromUserExtent(r.extent,e.viewState.projection)));const n=r.layer.getRenderSource();if(!n.getWrapX()){const r=n.getTileGridForProjection(e.viewState.projection).getExtent();r&&(t=getIntersection(t,r))}return t}class CanvasTileLayerRenderer extends CanvasLayerRenderer{constructor(e,t){super(e),t=t||{},this.extentChanged=!0,this.renderComplete=!1,this.renderedExtent_=null,this.renderedPixelRatio,this.renderedProjection=null,this.renderedTiles=[],this.renderedSourceKey_,this.renderedSourceRevision_,this.tempExtent=createEmpty(),this.tempTileRange_=new TileRange(0,0,0,0),this.tempTileCoord_=createOrUpdate(0,0,0);const r=void 0!==t.cacheSize?t.cacheSize:512;this.tileCache_=new LRUCache(r),this.sourceTileCache_=null,this.maxStaleKeys=.5*r}getTileCache(){return this.tileCache_}getSourceTileCache(){return this.sourceTileCache_||(this.sourceTileCache_=new LRUCache(512)),this.sourceTileCache_}getOrCreateTile(e,t,r,n){const i=this.tileCache_,o=this.getLayer().getSource(),s=getCacheKey(o,o.getKey(),e,t,r);let a;if(i.containsKey(s))a=i.get(s);else{const l=n.viewState.projection,c=o.getProjection();if(a=o.getTile(e,t,r,n.pixelRatio,l,!c||equivalent$1(c,l)?void 0:this.getSourceTileCache()),!a)return null;i.set(s,a)}return a}getTile(e,t,r,n){return this.getOrCreateTile(e,t,r,n)||null}getData(e){const t=this.frameState;if(!t)return null;const r=this.getLayer(),n=apply$1(t.pixelToCoordinateTransform,e.slice()),i=r.getExtent();if(i&&!containsCoordinate(i,n))return null;const o=t.viewState,s=r.getRenderSource(),a=s.getTileGridForProjection(o.projection),l=s.getTilePixelRatio(t.pixelRatio);for(let c=a.getZForResolution(o.resolution);c>=a.getMinZoom();--c){const e=a.getTileCoordForCoordAndZ(n,c),r=this.getTile(c,e[1],e[2],t);if(!r||r.getState()!==TileState.LOADED)continue;const i=a.getOrigin(c),u=toSize(a.getTileSize(c)),h=a.getResolution(c);let d;if(r instanceof ImageTile||r instanceof ReprojTile)d=r.getImage();else{if(!(r instanceof DataTile))continue;if(d=asImageLike(r.getData()),!d)continue}const p=Math.floor(l*((n[0]-i[0])/h-e[1]*u[0])),f=Math.floor(l*((i[1]-n[1])/h-e[2]*u[1])),g=Math.round(l*s.getGutterForProjection(o.projection));return this.getImageData(d,p+g,f+g)}return null}prepareFrame(e){this.renderedProjection?e.viewState.projection!==this.renderedProjection&&(this.tileCache_.clear(),this.renderedProjection=e.viewState.projection):this.renderedProjection=e.viewState.projection;const t=this.getLayer().getSource();if(!t)return!1;const r=t.getRevision();return this.renderedSourceRevision_?this.renderedSourceRevision_!==r&&(this.renderedSourceRevision_=r,this.renderedSourceKey_===t.getKey()&&(this.tileCache_.clear(),this.sourceTileCache_?.clear())):this.renderedSourceRevision_=r,!0}enqueueTilesForNextExtent(){return!0}enqueueTiles(e,t,r,n,i){const o=e.viewState,s=this.getLayer(),a=s.getRenderSource(),l=a.getTileGridForProjection(o.projection),c=getUid(a);c in e.wantedTiles||(e.wantedTiles[c]={});const u=e.wantedTiles[c],h=s.getMapInternal(),d=Math.max(r-i,l.getMinZoom(),l.getZForResolution(Math.min(s.getMaxResolution(),h?h.getView().getResolutionForZoom(Math.max(s.getMinZoom(),0)):l.getResolution(0)),a.zDirection)),p=o.rotation,f=p?getRotatedViewport(o.center,o.resolution,p,e.size):void 0;for(let g=r;g>=d;--g){const r=l.getTileRangeForExtentAndZ(t,g,this.tempTileRange_),i=l.getResolution(g);for(let t=r.minX;t<=r.maxX;++t)for(let o=r.minY;o<=r.maxY;++o){if(p&&!l.tileCoordIntersectsViewport([g,t,o],f))continue;const r=this.getTile(g,t,o,e);if(!r)continue;if(!addTileToLookup(n,r,g))continue;const s=r.getKey();if(u[s]=!0,r.getState()===TileState.IDLE&&!e.tileQueue.isKeyQueued(s)){const n=createOrUpdate(g,t,o,this.tempTileCoord_);e.tileQueue.enqueue([r,c,l.getTileCoordCenter(n),i])}}}}findStaleTile_(e,t){const r=this.tileCache_,n=e[0],i=e[1],o=e[2],s=this.getStaleKeys();for(let a=0;a0&&setTimeout(()=>{this.enqueueTiles(e,S,h-1,w,C-1)},0),!(h in w))return this.container;const T=getUid(this),x=e.time;for(const L of w[h]){const t=L.getState();if(t===TileState.EMPTY)continue;const r=L.tileCoord;if(t===TileState.LOADED&&1===L.getAlpha(T,x)){L.endTransition(T);continue}if(t!==TileState.ERROR&&(this.renderComplete=!1),this.findStaleTile_(r,w)){removeTileFromLookup(w,L,h),e.animate=!0;continue}if(this.findAltTiles_(u,r,h+1,w))continue;const n=u.getMinZoom();for(let e=h-1;e>=n&&!this.findAltTiles_(u,r,e,w);--e);}const R=d/o*a/g,A=this.getRenderContext(e);compose(this.tempTransform,m/2,y/2,R,R,0,-m/2,-y/2),r.extent&&this.clipUnrotated(A,e,b),c.getInterpolate()||(A.imageSmoothingEnabled=!1),this.preRender(A,e);const I=Object.keys(w).map(Number);let P;I.sort(ascending);const k=[],O=[];for(let L=I.length-1;L>=0;--L){const t=I[L],r=c.getTilePixelSize(t,a,i),n=u.getResolution(t)/d,o=r[0]*n*R,s=r[1]*n*R,l=u.getTileCoordForCoordAndZ(getTopLeft(E),t),h=u.getTileCoordExtent(l),p=apply$1(this.tempTransform,[g*(h[0]-E[0])/d,g*(E[3]-h[3])/d]),f=g*c.getGutterForProjection(i);for(const i of w[t]){if(i.getState()!==TileState.LOADED)continue;const r=i.tileCoord,n=l[1]-r[1],a=Math.round(p[0]-(n-1)*o),u=l[2]-r[2],h=Math.round(p[1]-(u-1)*s),d=Math.round(p[0]-n*o),g=Math.round(p[1]-u*s),m=a-d,y=h-g,b=1===I.length;let v=!1;P=[d,g,d+m,g,d+m,g+y,d,g+y];for(let e=0,i=k.length;e{const r=getUid(c),n=t.wantedTiles[r],i=n?Object.keys(n).length:0;this.updateCacheSize(i),this.tileCache_.expireCache(),this.sourceTileCache_?.expireCache()};e.postRenderFunctions.push(t)}return this.container}updateCacheSize(e){this.tileCache_.highWaterMark=Math.max(this.tileCache_.highWaterMark,2*e)}drawTile(e,t,r,n,i,o,s,a){let l;if(e instanceof DataTile){if(l=asImageLike(e.getData()),!l)throw new Error("Rendering array data is not yet supported")}else l=this.getTileImage(e);if(!l)return;const c=this.getRenderContext(t),u=getUid(this),h=t.layerStatesArray[t.layerIndex],d=h.opacity*(a?e.getAlpha(u,t.time):1),p=d!==c.globalAlpha;p&&(c.save(),c.globalAlpha=d),c.drawImage(l,s,s,l.width-2*s,l.height-2*s,r,n,i,o),p&&c.restore(),d!==h.opacity?t.animate=!0:a&&e.endTransition(u)}getImage(){const e=this.context;return e?e.canvas:null}getTileImage(e){return e.getImage()}updateUsedTiles(e,t,r){const n=getUid(t);n in e||(e[n]={}),e[n][r.getKey()]=!0}}const TileProperty={PRELOAD:"preload",USE_INTERIM_TILES_ON_ERROR:"useInterimTilesOnError"};class BaseTileLayer extends Layer{constructor(e){e=e||{};const t=Object.assign({},e),r=e.cacheSize;delete e.cacheSize,delete t.preload,delete t.useInterimTilesOnError,super(t),this.on,this.once,this.un,this.cacheSize_=r,this.setPreload(void 0!==e.preload?e.preload:0),this.setUseInterimTilesOnError(void 0===e.useInterimTilesOnError||e.useInterimTilesOnError)}getCacheSize(){return this.cacheSize_}getPreload(){return this.get(TileProperty.PRELOAD)}setPreload(e){this.set(TileProperty.PRELOAD,e)}getUseInterimTilesOnError(){return this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR)}setUseInterimTilesOnError(e){this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR,e)}getData(e){return super.getData(e)}}class TileLayer extends BaseTileLayer{constructor(e){super(e)}createRenderer(){return new CanvasTileLayerRenderer(this,{cacheSize:this.getCacheSize()})}}const IMAGE_REPLAYS={image:["Polygon","Circle","LineString","Image","Text"],hybrid:["Polygon","LineString"],vector:[]},VECTOR_REPLAYS={hybrid:["Image","Text","Default"],vector:["Polygon","Circle","LineString","Image","Text","Default"]};class CanvasVectorTileLayerRenderer extends CanvasTileLayerRenderer{constructor(e,t){super(e,t),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.renderedLayerRevision_,this.renderedPixelToCoordinateTransform_=null,this.renderedRotation_,this.renderedOpacity_=1,this.tmpTransform_=create(),this.tileClipContexts_=null}enqueueTilesForNextExtent(){return"vector"!==this.getLayer().getRenderMode()}drawTile(e,t,r,n,i,o,s,a){this.updateExecutorGroup_(e,t.pixelRatio,t.viewState.projection),this.tileImageNeedsRender_(e)&&this.renderTileImage_(e,t),super.drawTile(e,t,r,n,i,o,s,a)}getTile(e,t,r,n){const i=this.getOrCreateTile(e,t,r,n);if(!i)return null;const o=n.viewState,s=o.resolution,a=n.viewHints,l=this.getLayer().getSource(),c=l.getTileGridForProjection(o.projection),u=!(a[ViewHint.ANIMATING]||a[ViewHint.INTERACTING]),h=c.getZForResolution(s,l.zDirection)===e;return u&&h?i.wantedResolution=s:i.wantedResolution||(i.wantedResolution=c.getResolution(e)),i}prepareFrame(e){const t=this.getLayer().getRevision();return this.renderedLayerRevision_!==t&&(this.renderedLayerRevision_=t,this.renderedTiles.length=0),super.prepareFrame(e)}updateExecutorGroup_(e,t,r){const n=this.getLayer(),i=n.getRevision(),o=n.getRenderOrder()||null,s=e.wantedResolution,a=e.getReplayState(n);if(!a.dirty&&a.renderedResolution===s&&a.renderedRevision==i&&a.renderedRenderOrder==o)return;const l=n.getSource(),c=!!n.getDeclutter(),u=l.getTileGrid(),h=l.getTileGridForProjection(r).getTileCoordExtent(e.wrappedTileCoord),d=l.getSourceTiles(t,r,e),p=getUid(n);delete e.hitDetectionImageData[p],e.executorGroups[p]=[],a.dirty=!1;for(let f=0,g=d.length;fe.value):null;let m;e:for(let y=0,b=d.length;y{const r=this.getLayer(),n=r.getSource(),i=this.renderedProjection,o=i.getExtent(),s=this.renderedResolution,a=n.getTileGridForProjection(i),l=apply$1(this.renderedPixelToCoordinateTransform_,e.slice()),c=a.getTileCoordForCoordAndResolution(l,s).toString(),u=this.renderedTiles.find(e=>e.tileCoord.toString()===c&&e.getState()===TileState.LOADED);if(!u||u.loadingSourceTiles>0)return void t([]);n.getWrapX()&&i.canWrapX()&&!containsExtent(o,a.getTileCoordExtent(u.tileCoord))&&wrapX$1(l,i);const h=getUid(r),d=getTopLeft(a.getTileCoordExtent(u.wrappedTileCoord)),p=[(l[0]-d[0])/s,(d[1]-l[1])/s],f=u.getSourceTiles().reduce((e,t)=>e.concat(t.getFeatures()),[]);let g=u.hitDetectionImageData[h];if(!g){const e=toSize(a.getTileSize(a.getZForResolution(s,n.zDirection))),t=this.renderedRotation_;g=createHitDetectionImageData(e,[this.getRenderTransform(a.getTileCoordCenter(u.wrappedTileCoord),s,0,HIT_DETECT_RESOLUTION,e[0]*HIT_DETECT_RESOLUTION,e[1]*HIT_DETECT_RESOLUTION,0)],f,r.getStyleFunction(),a.getTileCoordExtent(u.wrappedTileCoord),u.getReplayState(r).renderedResolution,t),u.hitDetectionImageData[h]=g}t(hitDetect(p,f,g))})}getFeaturesInExtent(e){const t=[],r=this.getTileCache();if(0===r.getCount())return t;const n=this.getLayer().getSource().getTileGridForProjection(this.frameState.viewState.projection),i=n.getZForResolution(this.renderedResolution),o={};return r.forEach(r=>{if(r.tileCoord[0]!==i||r.getState()!==TileState.LOADED)return;const s=r.getSourceTiles();for(let i=0,a=s.length;i=0;--n)r[n].execute(this.context,s,this.getTileRenderTransform(t,e),e.viewState.rotation,o,DECLUTTER,l)}r.globalAlpha=n}renderDeferredInternal(e){const t=this.renderedTiles,r=getUid(this.getLayer()),n=t.reduce((e,t,n)=>(t.executorGroups[r].forEach(t=>e.push({executorGroup:t,index:n})),e),[]),i=n.map(({executorGroup:e})=>e.getDeferredZIndexContexts()),o={};for(let s=0,a=n.length;s{i.forEach((t,r)=>{t[e]&&(t[e].forEach(e=>{const{executorGroup:t,index:i}=n[r],o=t.getRenderedContext(),s=o.globalAlpha;o.globalAlpha=this.renderedOpacity_;const a=this.tileClipContexts_[i];a&&a.draw(o),e.draw(o),a&&o.restore(),o.globalAlpha=s,e.clear()}),t[e].length=0)})})}getTileRenderTransform(e,t){const r=t.pixelRatio,n=t.viewState,i=n.center,o=n.resolution,s=n.rotation,a=t.size,l=Math.round(a[0]*r),c=Math.round(a[1]*r),u=this.getLayer().getSource().getTileGridForProjection(t.viewState.projection),h=e.tileCoord,d=u.getTileCoordExtent(e.wrappedTileCoord),p=u.getTileCoordExtent(h,this.tempExtent)[0]-d[0];return multiply(scale$2(this.inversePixelTransform.slice(),1/r,1/r),this.getRenderTransform(i,o,s,r,l,c,p))}postRender(e,t){const r=t.viewHints,n=!(r[ViewHint.ANIMATING]||r[ViewHint.INTERACTING]);this.renderedPixelToCoordinateTransform_=t.pixelToCoordinateTransform.slice(),this.renderedRotation_=t.viewState.rotation,this.renderedOpacity_=t.layerStatesArray[t.layerIndex].opacity;const i=this.getLayer(),o=i.getRenderMode(),s=e.globalAlpha;e.globalAlpha=this.renderedOpacity_;const a=i.getDeclutter(),l=a?VECTOR_REPLAYS[o].filter(e=>!DECLUTTER.includes(e)):VECTOR_REPLAYS[o],c=t.viewState,u=c.rotation,h=i.getSource(),d=h.getTileGridForProjection(c.projection).getZForResolution(c.resolution,h.zDirection),p=this.renderedTiles,f=[],g=[],m=[],y=getUid(i);let b=!0;for(let v=p.length-1;v>=0;--v){const r=p[v];b=b&&!r.getReplayState(i).dirty;const o=r.executorGroups[y].filter(e=>e.hasExecutors(l));if(0===o.length)continue;const s=this.getTileRenderTransform(r,t),c=r.tileCoord[0];let h=!1;const _=o[0].getClipCoords(s);let E,w=e;if(_){E=new ZIndexContext,w=E.getContext();for(let e=0,t=f.length;e{const e=this.sourceImage_.getState();e!=ImageState.LOADED&&e!=ImageState.ERROR||(this.unlistenSource_(),this.reproject_())}),this.sourceImage_.load())}}unlistenSource_(){unlistenByKey(this.sourceListenerKey_),this.sourceListenerKey_=null}}const DECIMALS$1=4,ImageSourceEventType={IMAGELOADSTART:"imageloadstart",IMAGELOADEND:"imageloadend",IMAGELOADERROR:"imageloaderror"};class ImageSourceEvent extends BaseEvent{constructor(e,t){super(e),this.image=t}}class ImageSource extends Source{constructor(e){super({attributions:e.attributions,projection:e.projection,state:e.state,interpolate:void 0===e.interpolate||e.interpolate}),this.on,this.once,this.un,this.loader=e.loader||null,this.resolutions_=void 0!==e.resolutions?e.resolutions:null,this.reprojectedImage_=null,this.reprojectedRevision_=0,this.image=null,this.wantedExtent_,this.wantedResolution_,this.static_=!!e.loader&&0===e.loader.length,this.wantedProjection_=null}getResolutions(){return this.resolutions_}setResolutions(e){this.resolutions_=e}findNearestResolution(e){const t=this.getResolutions();return t&&(e=t[linearFindNearest(t,e,0)]),e}getImage(e,t,r,n){const i=this.getProjection();if(!i||!n||equivalent$1(i,n))return i&&(n=i),this.getImageInternal(e,t,r,n);if(this.reprojectedImage_){if(this.reprojectedRevision_==this.getRevision()&&equivalent$1(this.reprojectedImage_.getProjection(),n)&&this.reprojectedImage_.getResolution()==t&&equals$1(this.reprojectedImage_.getExtent(),e))return this.reprojectedImage_;this.reprojectedImage_.dispose(),this.reprojectedImage_=null}return this.reprojectedImage_=new ReprojImage(i,n,e,t,r,(e,t,r)=>this.getImageInternal(e,t,r,i),this.getInterpolate()),this.reprojectedRevision_=this.getRevision(),this.reprojectedImage_}getImageInternal(e,t,r,n){if(this.loader){const i=getRequestExtent(e,t,r,1),o=this.findNearestResolution(t);if(this.image&&(this.static_||this.wantedProjection_===n&&(this.wantedExtent_&&containsExtent(this.wantedExtent_,i)||containsExtent(this.image.getExtent(),i))&&(this.wantedResolution_&&fromResolutionLike(this.wantedResolution_)===o||fromResolutionLike(this.image.getResolution())===o)))return this.image;this.wantedProjection_=n,this.wantedExtent_=i,this.wantedResolution_=o,this.image=new ImageWrapper(i,o,r,this.loader),this.image.addEventListener(EventType$1.CHANGE,this.handleImageChange.bind(this))}return this.image}handleImageChange(e){const t=e.target;let r;switch(t.getState()){case ImageState.LOADING:this.loading=!0,r=ImageSourceEventType.IMAGELOADSTART;break;case ImageState.LOADED:this.loading=!1,r=ImageSourceEventType.IMAGELOADEND;break;case ImageState.ERROR:this.loading=!1,r=ImageSourceEventType.IMAGELOADERROR;break;default:return}this.hasListener(r)&&this.dispatchEvent(new ImageSourceEvent(r,t))}}function getRequestExtent(e,t,r,n){const i=t/r,o=getCenter(e),s=ceil(getWidth(e)/i,DECIMALS$1),a=ceil(getHeight(e)/i,DECIMALS$1);return getForViewAndSize(o,i,0,[s+2*ceil((n-1)*s/2,DECIMALS$1),a+2*ceil((n-1)*a/2,DECIMALS$1)])}const tmpTileCoord=[0,0,0],DECIMALS=5;class TileGrid{constructor(e){let t;if(this.minZoom=void 0!==e.minZoom?e.minZoom:0,this.resolutions_=e.resolutions,assert$1(isSorted(this.resolutions_,(e,t)=>t-e),"`resolutions` must be sorted in descending order"),!e.origins)for(let n=0,i=this.resolutions_.length-1;n{const n=new TileRange(Math.min(0,e[0]),Math.max(e[0]-1,-1),Math.min(0,e[1]),Math.max(e[1]-1,-1));if(r){const e=this.getTileRangeForExtentAndZ(r,t);n.minX=Math.max(e.minX,n.minX),n.maxX=Math.min(e.maxX,n.maxX),n.minY=Math.max(e.minY,n.minY),n.maxY=Math.min(e.maxY,n.maxY)}return n}):r&&this.calculateTileRanges_(r)}forEachTileCoord(e,t,r){const n=this.getTileRangeForExtentAndZ(e,t);for(let i=n.minX,o=n.maxX;i<=o;++i)for(let e=n.minY,s=n.maxY;e<=s;++e)r([t,i,e])}forEachTileCoordParentTileRange(e,t,r,n){let i,o,s,a=null,l=e[0]-1;for(2===this.zoomFactor_?(o=e[1],s=e[2]):a=this.getTileCoordExtent(e,n);l>=this.minZoom;){if(void 0!==o&&void 0!==s?(o=Math.floor(o/2),s=Math.floor(s/2),i=createOrUpdate$1(o,o,s,s,r)):i=this.getTileRangeForExtentAndZ(a,l,r),t(l,i))return!0;--l}return!1}getExtent(){return this.extent_}getMaxZoom(){return this.maxZoom}getMinZoom(){return this.minZoom}getOrigin(e){return this.origin_?this.origin_:this.origins_[e]}getResolution(e){return this.resolutions_[e]}getResolutions(){return this.resolutions_}getTileCoordChildTileRange(e,t,r){if(e[0]this.maxZoom||t0?n:Math.max(o/r[0],i/r[1]);const s=t+1,a=new Array(s);for(let l=0;lthis.maxQueueLength_;)this.queue_.shift().callback(null,null)}dispatch_(){if(this.running_||0===this.queue_.length)return;const e=this.queue_.shift();this.job_=e;const t=e.inputs[0].width,r=e.inputs[0].height,n=e.inputs.map(function(e){return e.data.buffer}),i=this.workers_.length;if(this.running_=i,1===i)return void this.workers_[0].postMessage({buffers:n,meta:e.meta,imageOps:this.imageOps_,width:t,height:r},n);const o=e.inputs[0].data.length,s=4*Math.ceil(o/4/i);for(let a=0;athis.getTileInternal(e,t,r,n,s,o),this.reprojectionErrorThreshold_,this.renderReprojectionEdges_,this.tileOptions);return d.key=l,d}getTileInternal(e,t,r,n,i,o){const s=this.getKey(),a=getCacheKey(this,s,e,t,r);if(o&&o.containsKey(a))return o.get(a);const l=this.createTile_(e,t,r,n,i,s);return o?.set(a,l),l}setRenderReprojectionEdges(e){this.renderReprojectionEdges_!=e&&(this.renderReprojectionEdges_=e,this.changed())}setTileGridForProjection(e,t){const r=get$2(e);if(r){const e=getUid(r);e in this.tileGridForProjection||(this.tileGridForProjection[e]=t)}}}function defaultTileLoadFunction(e,t){if(WORKER_OFFSCREEN_CANVAS){const r=e.getCrossOrigin();let n="same-origin",i="same-origin";return"anonymous"===r||""===r?(n="cors",i="omit"):"use-credentials"===r&&(n="cors",i="include"),void fetch(t,{mode:n,credentials:i}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(e=>createImageBitmap(e)).then(t=>{const r=e.getImage();r.width=t.width,r.height=t.height,r.getContext("2d").drawImage(t,0,0),t.close?.(),r.dispatchEvent(new Event("load"))}).catch(()=>{e.getImage().dispatchEvent(new Event("error"))})}e.getImage().src=t}class TileJSON extends TileImage{constructor(e){if(super({attributions:e.attributions,cacheSize:e.cacheSize,crossOrigin:e.crossOrigin,interpolate:e.interpolate,projection:get$2("EPSG:3857"),reprojectionErrorThreshold:e.reprojectionErrorThreshold,state:"loading",tileLoadFunction:e.tileLoadFunction,wrapX:void 0===e.wrapX||e.wrapX,transition:e.transition,zDirection:e.zDirection}),this.tileJSON_=null,this.tileSize_=e.tileSize,e.url)if(e.jsonp)jsonp(e.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{const t=new XMLHttpRequest;t.addEventListener("load",this.onXHRLoad_.bind(this)),t.addEventListener("error",this.onXHRError_.bind(this)),t.open("GET",e.url),t.send()}else{if(!e.tileJSON)throw new Error("Either `url` or `tileJSON` options must be provided");this.handleTileJSONResponse(e.tileJSON)}}onXHRLoad_(e){const t=e.target;if(!t.status||t.status>=200&&t.status<300){let e;try{e=JSON.parse(t.responseText)}catch{return void this.handleTileJSONError()}this.handleTileJSONResponse(e)}else this.handleTileJSONError()}onXHRError_(e){this.handleTileJSONError()}getTileJSON(){return this.tileJSON_}handleTileJSONResponse(e){const t=get$2("EPSG:4326"),r=this.getProjection();let n;if(void 0!==e.bounds){const i=getTransformFromProjections(t,r);n=applyTransform(e.bounds,i)}const i=extentFromProjection(r),o=e.minzoom||0,s=createXYZ({extent:i,maxZoom:e.maxzoom||22,minZoom:o,tileSize:this.tileSize_});if(this.tileGrid=s,this.tileUrlFunction=createFromTemplates(e.tiles,s),e.attribution&&!this.getAttributions()){const t=void 0!==n?n:i;this.setAttributions(function(r){return intersects$1(t,r.extent)?[e.attribution]:null})}this.tileJSON_=e,this.setState("ready")}handleTileJSONError(){this.setState("error")}}class VectorTile extends UrlTile{constructor(e){const t=e.projection||"EPSG:3857",r=e.extent||extentFromProjection(t),n=e.tileGrid||createXYZ({extent:r,maxResolution:e.maxResolution,maxZoom:void 0!==e.maxZoom?e.maxZoom:22,minZoom:e.minZoom,tileSize:e.tileSize||512});super({attributions:e.attributions,attributionsCollapsible:e.attributionsCollapsible,cacheSize:e.cacheSize,interpolate:!0,projection:t,state:e.state,tileGrid:n,tileLoadFunction:e.tileLoadFunction?e.tileLoadFunction:defaultLoadFunction,tileUrlFunction:e.tileUrlFunction,url:e.url,urls:e.urls,wrapX:void 0===e.wrapX||e.wrapX,transition:e.transition,zDirection:void 0===e.zDirection?1:e.zDirection}),this.format_=e.format?e.format:null,this.tileKeysBySourceTileUrl_={},this.sourceTiles_={},this.overlaps_=null==e.overlaps||e.overlaps,this.tileClass=e.tileClass?e.tileClass:VectorTile$1,this.tileGrids_={}}getOverlaps(){return this.overlaps_}getSourceTiles(e,t,r){if(r.getState()===TileState.IDLE){r.setState(TileState.LOADING);const n=r.wrappedTileCoord,i=this.getTileGridForProjection(t);let o=i.getTileCoordExtent(n);const s=n[0],a=i.getResolution(s);buffer(o,-a,o);const l=this.projection;t&&this.projection&&!equivalent$1(t,l)&&(o=transformExtent(o,t,l));const c=this.tileGrid,u=c.getExtent();u&&getIntersection(o,u,o);let h=a;t&&l&&!equivalent$1(t,l)&&(h=a/l.getMetersPerUnit()/t.getMetersPerUnit());const d=c.getZForResolution(h,this.zDirection);c.forEachTileCoord(o,d,n=>{const i=this.tileUrlFunction(n,e,t);this.sourceTiles_[i]||(this.sourceTiles_[i]=new this.tileClass(n,i?TileState.IDLE:TileState.EMPTY,i,this.format_,this.tileLoadFunction));const o=this.sourceTiles_[i];r.sourceTiles.push(o),this.tileKeysBySourceTileUrl_[i]||(this.tileKeysBySourceTileUrl_[i]=[]),this.tileKeysBySourceTileUrl_[i].push(r.getKey());const s=o.getState();if(s{this.handleTileChange(t);const n=o.getState();if(n===TileState.LOADED||n===TileState.ERROR){const t=o.getKey();t in r.errorTileKeys?o.getState()===TileState.LOADED&&delete r.errorTileKeys[t]:r.loadingSourceTiles--,n===TileState.ERROR?r.errorTileKeys[t]=!0:o.removeEventListener(EventType$1.CHANGE,e),0===r.loadingSourceTiles&&r.setState(isEmpty$1(r.errorTileKeys)?TileState.LOADED:TileState.ERROR)}};o.addEventListener(EventType$1.CHANGE,e),r.loadingSourceTiles++}s===TileState.IDLE&&(o.extent=c.getTileCoordExtent(n),o.projection=this.projection,o.resolution=c.getResolution(n[0]),o.load())}),r.loadingSourceTiles||r.setState(r.sourceTiles.some(e=>e.getState()===TileState.ERROR)?TileState.ERROR:TileState.LOADED)}return r.sourceTiles}removeSourceTiles(e){const t=e.getKey(),r=e.sourceTiles;for(let n=0,i=r.length;n{u=u&&!this.tileUrlFunction(e,n,l)})}const h=new VectorRenderTile(o,u?TileState.EMPTY:TileState.IDLE,s,this.getSourceTiles.bind(this,n,i),this.removeSourceTiles.bind(this));return h.key=this.getKey(),h}getTileGridForProjection(e){const t=e.getCode();let r=this.tileGrids_[t];if(!r){const n=this.projection;if(null!==n&&!equivalent$1(n,e))return getForProjection(e);const i=this.tileGrid,o=i.getResolutions().slice(),s=o.map(function(e,t){return i.getOrigin(t)}),a=o.map(function(e,t){return i.getTileSize(t)}),l=DEFAULT_MAX_ZOOM+1;for(let e=o.length;ed?h-L+d:d-L,O=Math.atan(Math.sqrt(P*P+k*k)),j=m*Math.cos(O)+g*Math.sin(O)*Math.cos(f-L),M=Math.cos(O),D=255*j,B=Math.min(Math.max(2*t.sunEl,0),1),U=1.875-1.75*t.opacity,z=.5!==t.opacity?d*((Math.pow(U,O)-1)/(Math.pow(U,d)-1)):O,F={r:(1-M)*v.r*B*255,g:(1-M)*v.g*B*255,b:(1-M)*v.b*B*255,a:(1-M)*v.a*B*255},N=Math.abs(((L+f)/Math.PI+.5)%2-1),$={r:(y.r*(1-N)+b.r*N)*D,g:(y.g*(1-N)+b.g*N)*D,b:(y.b*(1-N)+b.b*N)*D,a:(y.a*(1-N)+b.a*N)*D},R=4*(w*n+E),s[R]=F.r*(1-N)+$.r,s[R+1]=F.g*(1-N)+$.g,s[R+2]=F.b*(1-N)+$.b,s[R+3]=o[R+3]*t.opacity*B*Math.sin(z);return new ImageData(s,n,i)}function raster(e,t){const r=e[0],n=r.width,i=r.height,o=r.data,s=new Uint8ClampedArray(o.length),a=n-1,l=i-1,c=[0,0,0,0];let u,h,d;const p=(f=t.saturation)>0?1-1/(1.001-f):-f;var f;const g=(m=t.contrast)>0?1/(1-m):1+m;var m;const y=function(e){e*=Math.PI/180;const t=Math.sin(e),r=Math.cos(e);return[(2*r+1)/3,(-Math.sqrt(3)*t-r+1)/3,(Math.sqrt(3)*t-r+1)/3]}(t.hueRotate),b=y,v=[y[2],y[0],y[1]],_=[y[1],y[2],y[0]],E=t.brightnessLow,w=t.brightnessHigh;for(h=0;h<=l;++h)for(u=0;u<=a;++u){d=4*(h*n+u),c[0]=o[d],c[1]=o[d+1],c[2]=o[d+2],c[3]=o[d+3];const e=c[0],t=c[1],r=c[2],i=(e,t)=>{let r=0;for(let n=0;n{t.accessToken=e,t.accessTokenParam=r})),t}function applyStyle(e,t,r="",n={},i){let o,s,a,l,c=!0;return"string"==typeof r||Array.isArray(r)?l=r:(a=r,l=a.source||a.layers,n=a),"string"==typeof n?(o=n,a={}):(o=n.styleUrl,a=n),!1===a.updateSource&&(c=!1),i||(i=a.resolutions),o||"string"!=typeof t||t.trim().startsWith("{")||(o=t),o&&(o=o.startsWith("data:")?location.href:normalizeStyleUrl(o,a.accessToken),a=completeOptions(o,a)),new Promise(function(r,n){getGlStyle(t,a).then(function(t){if(8!=t.version)return n(new Error("glStyle version 8 required."));if(!(e instanceof VectorLayer||e instanceof VectorTileLayer))return n(new Error("Can only apply to VectorLayer or VectorTileLayer"));const u=e instanceof VectorTileLayer?"vector":"geojson";if(l?s=Array.isArray(l)?t.layers.find(function(e){return e.id===l[0]}).source:l:(s=t.layers.find(function(e){return e.source&&t.sources[e.source].type===u}).source,l=s),!s)return n(new Error(`No ${u} source found in the glStyle.`));function h(){if(!c)return Promise.resolve();if(e instanceof VectorTileLayer)return setupVectorSource(t.sources[s],o,a).then(function(t){const r=e.getSource();r?t!==r&&(r.setTileUrlFunction(t.getTileUrlFunction()),"function"==typeof r.setUrls&&"function"==typeof t.getUrls&&r.setUrls(t.getUrls()),r.format_||(r.format_=t.format_),r.getAttributions()||r.setAttributions(t.getAttributions()),r.getTileLoadFunction()===defaultLoadFunction&&r.setTileLoadFunction(t.getTileLoadFunction()),equivalent$1(r.getProjection(),t.getProjection())&&(r.tileGrid=t.getTileGrid())):e.setSource(t);const n=e.getSource().getTileGrid();!isFinite(e.getMaxResolution())&&!isFinite(e.getMinZoom())&&n.getMinZoom()>0&&e.setMaxResolution(getResolutionForZoom(Math.max(0,n.getMinZoom()-1e-12),n.getResolutions()))});const r=t.sources[s];let n=e.getSource();n&&n.get("mapbox-source")===r||(n=setupGeoJSONSource(r,o,a));const i=e.getSource();return i?n!==i&&(i.getAttributions()||i.setAttributions(n.getAttributions()),i.format_||(i.format_=n.getFormat()),i.url_=n.getUrl()):e.setSource(n),Promise.resolve()}let d,p;const f={},g={};function m(){if(p||t.sprite&&!f)p?(e.setStyle(p),h().then(r).catch(n)):n(new Error("Something went wrong trying to apply style."));else{if(a.projection&&!i){const e=get$2(a.projection).getUnits();"m"!==e&&(i=defaultResolutions.map(t=>t/METERS_PER_UNIT$1[e]))}let o;const c=e.getSource();c instanceof VectorTile&&c.format_ instanceof MVT&&(o=c.format_.layerName_),p=stylefunction(e,t,l,i,f,g,(e,t=a.webfonts)=>getFonts(e,t),a.getImage,o),e.getStyle()?h().then(r).catch(n):n(new Error(`Nothing to show for source [${s}]`))}}if(t.sprite){const e=normalizeSpriteDefinition(t.sprite,a.accessToken,o||location.href);d=WORKER_OFFSCREEN_CANVAS?1:window.devicePixelRatio>=1.5?.5:1;const r=.5==d?"@2x":"";Promise.all(e.map(function(e){const t=new URL(e.url);let i=t.origin+t.pathname+r+".json"+t.search;return new Promise(function(e,r){fetchResource("Sprite",i,a).then(e).catch(function(){i=t.origin+t.pathname+".json"+t.search,fetchResource("Sprite",i,a).then(e).catch(r)})}).then(function(i){let o;if(void 0===i&&n(new Error("No sprites found.")),o=t.origin+t.pathname+r+".png"+t.search,a.transformRequest){const e=a.transformRequest(o,"SpriteImage")||o;(e instanceof Request||e instanceof Promise)&&(o=e)}g[e.id]=o;for(const t in i){const r="default"==e.id?t:`${e.id}:${t}`;f[r]=i[t]}}).catch(function(e){n(new Error(`Sprites cannot be loaded: ${i}: ${e.message}`))})})).then(m).catch(n)}else m()}).catch(n)})}function getSourceIdByRef(e,t){let r;return e.some(function(e){if(e.id==t)return r=e.source,!0}),r}function extentFromTileJSON(e,t){const r=e.bounds;if(r){const e=fromLonLat([r[0],r[1]],t),n=fromLonLat([r[2],r[3]],t);return[e[0],e[1],n[0],n[1]]}return get$2(t).getExtent()}function sourceOptionsFromTileJSON(e,t,r){const n=new TileJSON({tileJSON:t,tileSize:e.tileSize||t.tileSize||512}),i=n.getTileJSON(),o=n.getTileGrid(),s=get$2(r.projection||"EPSG:3857"),a=extentFromTileJSON(i,s),l=s.getExtent(),c=i.minzoom||0,u=i.maxzoom||22,h={attributions:n.getAttributions(),projection:s,tileGrid:new TileGrid({origin:l?getTopLeft(l):o.getOrigin(0),extent:a||o.getExtent(),minZoom:c,resolutions:getTileResolutions(s,t.tileSize).slice(0,u+1),tileSize:o.getTileSize(0)})};return Array.isArray(i.tiles)?h.urls=i.tiles:h.url=i.tiles,h}function getBackgroundColor(e,t,r,n){const i={id:e.id,type:e.type},o=e.layout||{},s=e.paint||{};let a;i.paint=s,cameraObj.zoom=getZoomForResolution(t,r.resolutions||defaultResolutions),cameraObj.distanceFromCenter=0;const l=getValue(i,"paint","background-color",emptyObj,n);return void 0!==s["background-opacity"]&&(a=getValue(i,"paint","background-opacity",emptyObj,n)),"none"==o.visibility?void 0:colorWithOpacity(l,a)}function setupBackgroundLayer(e,t,r){const n=WORKER_OFFSCREEN_CANVAS?{style:{}}:document.createElement("div");return n.className="ol-mapbox-style-background",n.style.position="absolute",n.style.width="100%",n.style.height="100%",new Layer({source:new Source({}),render(i){const o=getBackgroundColor(e,i.viewState.resolution,t,r);return n.style.backgroundColor=o,n}})}function setupVectorSource(e,t,r){return new Promise(function(n,i){getTileJson(e,t,r).then(function({tileJson:t,tileLoadFunction:i}){const o=sourceOptionsFromTileJSON(e,t,r);o.tileLoadFunction=i,o.format=new MVT({layerName:"mvt:layer"});const s=new VectorTile(o);s.set("mapbox-source",e),n(s)}).catch(i)})}function setupVectorLayer(e,t,r){const n=new VectorTileLayer({declutter:!0,visible:!1});return setupVectorSource(e,t,r).then(function(e){n.setSource(e)}).catch(function(){n.setSource(void 0)}),n}function getBboxTemplate(e){return`{bbox-${(e?e.getCode():"EPSG:3857").toLowerCase().replace(/[^a-z0-9]/g,"-")}}`}function setupRasterSource(e,t,r){return new Promise(function(n,i){getTileJson(e,t,r).then(function({tileJson:t,tileLoadFunction:i}){const o=new TileJSON({interpolate:void 0===r.interpolate||r.interpolate,transition:0,crossOrigin:"anonymous",tileJSON:t});o.tileGrid=sourceOptionsFromTileJSON(e,t,r).tileGrid,r.projection&&(o.projection=get$2(r.projection));const s=o.getTileUrlFunction();i&&o.setTileLoadFunction(i),o.setTileUrlFunction(function(e,t,r){const n=getBboxTemplate(r);let i=s(e,t,r);if(-1!=i.indexOf(n)){const t=o.getTileGrid().getTileCoordExtent(e);i=i.replace(n,t.toString())}return i}),o.set("mapbox-source",e),n(o)}).catch(function(e){i(e)})})}function setupRasterLayer(e,t,r){const n=new TileLayer;return setupRasterSource(e,t,r).then(function(e){n.setSource(e)}).catch(function(){n.setSource(void 0)}),n}function setupRasterOpLayer(e,t,r){const n=setupRasterLayer(e,t,r);return new ImageLayer({source:new RasterSource({operationType:"image",operation:raster,sources:[n]})})}function setupHillshadeLayer(e,t,r){const n=setupRasterLayer(e,t,r);return new ImageLayer({source:new RasterSource({operationType:"image",operation:hillshade,sources:[n]})})}function setupGeoJSONSource(e,t,r){const n=r.projection?new GeoJSON({dataProjection:r.projection}):new GeoJSON,i=e.data,o={};if("string"==typeof i){const[o]=normalizeSourceUrl(i,r.accessToken,r.accessTokenParam||"access_token",t||location.href);if(/\{bbox-[0-9a-z-]+\}/.test(o)){const t=(e,t,r)=>{const n=getBboxTemplate(r);return o.replace(n,`${e.join(",")}`)},i=new VectorSource({attributions:e.attribution,format:n,loader:(e,n,o,s,a)=>{fetchResource("GeoJSON","function"==typeof t?t(e,n,o):t,r).then(e=>{const t=i.getFormat().readFeatures(e,{featureProjection:o});i.addFeatures(t),s(t)}).catch(()=>{i.removeLoadedExtent(e),a()})},strategy:bbox});return i.set("mapbox-source",e),i}const s=new VectorSource({attributions:e.attribution,format:n,url:o,loader:(e,t,n,i,a)=>{fetchResource("GeoJSON",o,r).then(e=>{const t=s.getFormat().readFeatures(e,{featureProjection:n});s.addFeatures(t),i(t)}).catch(()=>{s.removeLoadedExtent(e),a()})}});return s}o.features=n.readFeatures(i,{featureProjection:"EPSG:3857"});const s=new VectorSource(Object.assign({attributions:e.attribution,format:n},o));return s.set("mapbox-source",e),s}function setupGeoJSONLayer(e,t,r){return new VectorLayer({declutter:!0,source:setupGeoJSONSource(e,t,r),visible:!1})}function prerenderRasterLayer(e,t,r){let n=null;return function(i){e.paint&&"raster-opacity"in e.paint&&i.frameState.viewState.zoom!==n&&(n=i.frameState.viewState.zoom,delete r[e.id],updateRasterLayerProperties(e,t,n,r))}}function updateRasterLayerProperties(e,t,r,n){cameraObj.zoom=r,cameraObj.distanceFromCenter=0;const i=getValue(e,"paint","raster-opacity",emptyObj,n);t.setOpacity(i)}function manageVisibility(e,t){function r(){const r=t.get("mapbox-style");if(!r)return;const n=derefLayers(r.layers),i=e.get("mapbox-layers"),o=n.filter(function(e){return i.includes(e.id)}).some(function(e){return!e.layout||!e.layout.visibility||"visible"===e.layout.visibility});e.get("visible")!==o&&e.setVisible(o)}e.on("change",r),r()}function setupLayer(e,t,r,n){const i=getFunctionCache(e),o=e.layers,s=r.type,a=r.source||getSourceIdByRef(o,r.ref),l=e.sources[a];let c;if("background"==s)c=setupBackgroundLayer(r,n,i);else if("vector"==l.type)c=setupVectorLayer(l,t,n);else if("raster"==l.type){const e=["raster-saturation","raster-contrast","raster-brightness-max","raster-brightness-min","raster-hue-rotate"];Object.keys(r.paint||{}).find(t=>e.includes(t))?(c=setupRasterOpLayer(l,t,n),c.getSource().on("beforeoperations",function(e){cameraObj.zoom=getZoomForResolution(e.resolution,n.resolutions||defaultResolutions),cameraObj.distanceFromCenter=0;const t=e.data;t.saturation=getValue(r,"paint","raster-saturation",emptyObj,i),t.contrast=getValue(r,"paint","raster-contrast",emptyObj,i),t.brightnessHigh=getValue(r,"paint","raster-brightness-max",emptyObj,i),t.brightnessLow=getValue(r,"paint","raster-brightness-min",emptyObj,i),t.hueRotate=getValue(r,"paint","raster-hue-rotate",emptyObj,i)})):c=setupRasterLayer(l,t,n),c.setVisible(!r.layout||"none"!==r.layout.visibility),c.on("prerender",prerenderRasterLayer(r,c,i))}else if("geojson"==l.type)c=setupGeoJSONLayer(l,t,n);else if("raster-dem"==l.type&&"hillshade"==r.type){const e=setupHillshadeLayer(l,t,n);c=e,e.getSource().on("beforeoperations",function(e){const t=e.data;t.resolution=getPointResolution(n.projection||"EPSG:3857",e.resolution,getCenter(e.extent),"m"),cameraObj.zoom=getZoomForResolution(e.resolution,n.resolutions||defaultResolutions),cameraObj.distanceFromCenter=0,t.encoding=l.encoding,t.vert=5*getValue(r,"paint","hillshade-exaggeration",emptyObj,i),t.sunAz=getValue(r,"paint","hillshade-illumination-direction",emptyObj,i),t.sunEl=35,t.opacity=.3,t.highlightColor=getValue(r,"paint","hillshade-highlight-color",emptyObj,i),t.shadowColor=getValue(r,"paint","hillshade-shadow-color",emptyObj,i),t.accentColor=getValue(r,"paint","hillshade-accent-color",emptyObj,i)}),c.setVisible(!r.layout||"none"!==r.layout.visibility)}const u=a;return c&&c.set("mapbox-source",u),c}function processStyle(e,t,r,n){const i=[];let o=null;if(t instanceof Map$1){if(o=t.getView(),!o.isDef()&&!o.getRotation()&&!o.getResolutions()){const e=n.projection?get$2(n.projection):o.getProjection();o=new View(Object.assign(o.getProperties(),{maxResolution:defaultResolutions[0]/METERS_PER_UNIT$1[e.getUnits()],projection:n.projection||o.getProjection()})),t.setView(o)}"center"in e&&!o.getCenter()&&o.setCenter(fromLonLat(e.center,o.getProjection())),"zoom"in e&&void 0===o.getZoom()&&o.setResolution(defaultResolutions[0]/METERS_PER_UNIT$1[o.getProjection().getUnits()]/Math.pow(2,e.zoom)),o.getCenter()&&void 0!==o.getZoom()||o.fit(o.getProjection().getExtent(),{nearest:!0,size:t.getSize()})}t.set("mapbox-style",e),t.set("mapbox-metadata",{styleUrl:r,options:n});const s=e.layers;let a,l,c,u=[];for(let h=0,d=s.length;h0||r>0)&&e.setMaxResolution(Math.min(getResolutionForZoom(Math.max(0,s-1e-12),defaultResolutions),getResolutionForZoom(Math.max(0,r-1e-12),t.getResolutions()))),a<24&&e.setMinResolution(getResolutionForZoom(a,defaultResolutions))}}else s>0&&e.setMaxResolution(getResolutionForZoom(Math.max(0,s-1e-12),defaultResolutions));u instanceof VectorSource||u instanceof VectorTile?applyStyle(e,r,t,Object.assign({styleUrl:n},o)).then(function(){manageVisibility(e,i),l()}).catch(c):l()}else c(new Error("Error accessing data for source "+e.get("mapbox-source")))};e.set("mapbox-layers",t);const h=i.getLayers();-1===h.getArray().indexOf(e)&&h.push(e),e.getSource()?u():e.once("change:source",u)})}class MapComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");mapInstance;bookmarkSource;searchResultsSource;selectedShapeSource;searchOverlay;searchOverlayElement;selectedPinOverlay;selectedPinElement;crosshairElement;crosshairOverlay;ignoreNextMapClick=!1;setupMap=modifier(e=>{if(this.mapInstance)return;const t=new LayerGroup;this.selectedShapeSource=new VectorSource;const r=new VectorLayer({source:this.selectedShapeSource,style:new Style({stroke:new Stroke({color:"#3388ff",width:4}),fill:new Fill({color:"rgba(51, 136, 255, 0.1)"})}),zIndex:5});this.bookmarkSource=new VectorSource;const n=new VectorLayer({source:this.bookmarkSource,style:e=>{const t=e.get("originalPlace");let r=getComputedStyle(document.documentElement).getPropertyValue("--default-list-color").trim()||"#000000";if(t&&t._listIds&&t._listIds.length>0){const e=t._listIds[0],n=this.storage.lists.find(t=>t.id===e);n&&n.color&&(r=n.color)}return[new Style({image:new CircleStyle({radius:10,fill:new Fill({color:"rgba(0, 0, 0, 0.2)"}),displacement:[0,-2]})}),new Style({image:new CircleStyle({radius:9,fill:new Fill({color:r}),stroke:new Stroke({color:"#fff",width:2})})})]},zIndex:10});this.searchResultsSource=new VectorSource;const i=new Map,o=new VectorLayer({source:this.searchResultsSource,style:e=>{const t=e.get("originalPlace"),r=this.mapUi.selectedPlace;if(r){const e=t.osmId&&r.osmId&&t.osmId===r.osmId,n=t.id&&r.id&&t.id===r.id,i=t.lat===r.lat&&t.lon===r.lon;if(e||n||i)return new Style({})}const n=getIconNameForTags(t.osmTags||t),o=n||"default";if(!i.has(o)){const e=getComputedStyle(document.documentElement).getPropertyValue("--marker-color-primary").trim()||"#ea4335";let t=``;if(n){const r=getIcon(n);if(r){let n=r.trim();const i=n.indexOf("",i)+1,s=n.lastIndexOf("");-1!==i&&-1!==s&&(n=n.substring(o,s)),t=`\n \n \n ${n}\n \n `}}const r=`\n \n \n \n \n \n \n \n ${t}\n \n `;i.set(o,"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(r.trim()))}return new Style({image:new Icon({src:i.get(o),anchor:[.5,.65],scale:1})})},zIndex:11});let s=[14.21683569,27.060114248],a=2.661,l=!1;try{const e=localStorage.getItem("marco:map-view");if(e){const t=JSON.parse(e);t.center&&Array.isArray(t.center)&&2===t.center.length&&"number"==typeof t.zoom&&(s=t.center,a=t.zoom,l=!0)}}catch(T){console.warn("Failed to restore map view:",T)}const c=new View({center:fromLonLat(s),zoom:a,projection:"EPSG:3857"});this.mapInstance=new Map$1({target:e,layers:[t,r,o,n],view:c,controls:defaults$1({zoom:!0,rotate:!0,attribution:!0}),interactions:defaults({dragPan:!1})});const u=toLonLat(c.getCenter());this.mapUi.updateCenter(u[1],u[0]),apply(this.mapInstance,"https://tiles.openfreemap.org/styles/liberty",{webfonts:"data:text/css,"}),this.searchOverlayElement=document.createElement("div"),this.searchOverlayElement.className="search-pulse",this.searchOverlay=new Overlay({element:this.searchOverlayElement,positioning:"center-center",stopEvent:!1}),this.mapInstance.addOverlay(this.searchOverlay),this.selectedPinElement=document.createElement("div"),this.selectedPinElement.className="selected-pin-container";const h=document.createElement("div");h.className="selected-pin",h.innerHTML='';const d=document.createElement("div");d.className="selected-pin-shadow",this.selectedPinElement.appendChild(h),this.selectedPinElement.appendChild(d),this.selectedPinOverlay=new Overlay({element:this.selectedPinElement,positioning:"bottom-center",stopEvent:!1}),this.mapInstance.addOverlay(this.selectedPinOverlay),this.crosshairElement=document.createElement("div"),this.crosshairElement.className="map-crosshair",this.crosshairElement.innerHTML='\n \n \n \n \n ',e.appendChild(this.crosshairElement),this.locationOverlayElement=document.createElement("div"),this.locationOverlayElement.className="search-pulse blue",this.locationOverlay=new Overlay({element:this.locationOverlayElement,positioning:"center-center",stopEvent:!1}),this.mapInstance.addOverlay(this.locationOverlay),e.addEventListener("pointerdown",()=>{this.mapUi.searchBoxHasFocus&&(this.ignoreNextMapClick=!0)},!0);const p=new Geolocation({trackingOptions:{enableHighAccuracy:!0},projection:c.getProjection()}),f=new Feature;f.setStyle(new Style({image:new CircleStyle({radius:6,fill:new Fill({color:"#3399CC"}),stroke:new Stroke({color:"#fff",width:2})})}));const g=new VectorSource({features:[f]}),m=new VectorLayer({source:g,zIndex:15});p.on("change:position",function(){const e=p.getPosition();f.setGeometry(e?new Point(e):null)});const y=document.createElement("div");y.className="ol-control ol-locate";const b=document.createElement("button");let v,_;b.style.display="flex",b.style.alignItems="center",b.style.justifyContent="center",b.innerHTML=`${getIcon("navigation")}`,b.title="Locate Me",y.appendChild(b);const E=()=>{v&&(clearTimeout(v),v=null);try{_&&(p.un("change:position",w),_=null)}catch{}this.locationOverlayElement&&this.locationOverlayElement.classList.remove("active")},w=()=>{const e=p.getPosition(),t=p.getAccuracyGeometry(),r=p.getAccuracy();if(console.debug("Geolocation change:",{coordinates:e,accuracy:r}),!e)return;const n=this.mapInstance.getSize(),i=this.mapInstance.getView();let o=null;if(this.locationOverlayElement){const t=i.getResolution(),n=2*(r||50)/getPointResolution(i.getProjection(),t,e);this.locationOverlayElement.style.width=`${n}px`,this.locationOverlayElement.style.height=`${n}px`,this.locationOverlay.setPosition(e)}if(r&&r<=20&&E(),t){const e=t.getExtent();o=3.162*i.getResolutionForExtent(e,n)}else r&&(o=6.325*r/Math.min(n[0],n[1])/getPointResolution(i.getProjection(),1,e));let s={center:e,duration:1e3};if(o){const e=i.getResolutionForZoom(17);s.resolution=Math.max(o,e)}else s.zoom=16;this.mapInstance.getView().animate(s)},C=()=>{console.debug("Getting current geolocation..."),E(),p.setTracking(!0);const e=p.getPosition();this.locationOverlayElement&&this.locationOverlayElement.classList.add("active"),e&&w(),_=p.on("change:position",w),v=setTimeout(()=>{E()},1e4)};b.addEventListener("click",C);const S=new Control({element:y});this.mapInstance.addLayer(m),this.mapInstance.addControl(S),l||"index"!==this.router.currentRouteName||C(),this.mapInstance.on("singleclick",this.handleMapClick),this.mapInstance.on("moveend",this.handleMapMove),this.mapInstance.on("pointermove",e=>{const t=this.mapInstance.getEventPixel(e.originalEvent),r=this.mapInstance.hasFeatureAtPixel(t,{hitTolerance:10});this.mapInstance.getTarget().style.cursor=r?"pointer":""}),this.storage.rs.on("ready",()=>{this.handleMapMove()})});updateInteractions=modifier(()=>{if(!this.mapInstance)return;this.mapInstance.getInteractions().getArray().slice().forEach(e=>{e instanceof DragPan&&this.mapInstance.removeInteraction(e)});const e=!!this.settings.mapKinetic&&new Kinetic(-.005,.05,100);this.settings.mapKinetic&&window.innerWidth<=768&&(e.minVelocity_=.25),this.mapInstance.addInteraction(new DragPan({kinetic:e}))});updateSearchResults=modifier(()=>{if(!this.searchResultsSource)return;this.searchResultsSource.clear();const e=this.mapUi.searchResults;if(!e||0===e.length)return;const t=[];e.forEach(e=>{if(e.lat&&e.lon){const r=new Feature({geometry:new Point(fromLonLat([e.lon,e.lat])),name:e.title,id:e.id,isSearchResult:!0,originalPlace:e});t.push(r)}}),t.length>0&&this.searchResultsSource.addFeatures(t)});updateSelectedPin=modifier(()=>{const e=this.mapUi.selectedPlace,t=this.mapUi.selectionOptions||{};if(this.searchResultsSource&&this.searchResultsSource.changed(),this.selectedPinOverlay&&this.selectedPinElement)if(this.selectedShapeSource&&this.selectedShapeSource.clear(),e&&e.lat&&e.lon){const n=fromLonLat([e.lon,e.lat]);if(this.selectedPinOverlay.setPosition(n),this.selectedPinElement.classList.remove("active"),this.selectedPinElement.offsetWidth,this.selectedPinElement.classList.add("active"),e.geojson&&this.selectedShapeSource)try{const t=(new GeoJSON).readFeature(e.geojson,{featureProjection:"EPSG:3857"});this.selectedShapeSource.addFeature(t)}catch(r){console.warn("Failed to render selected place shape:",r)}t.preventZoom?this.handlePinVisibility(n,{maintainZoom:!0}):e.bbox?this.zoomToBbox(e.bbox):this.handlePinVisibility(n)}else this.selectedPinElement.classList.remove("active"),this.selectedPinOverlay.setPosition(void 0)});zoomToBbox(e){if(!this.mapInstance||!e)return;const t=this.mapInstance.getView(),r=this.mapInstance.getSize(),n=[...fromLonLat([e.minLon,e.minLat]),...fromLonLat([e.maxLon,e.maxLat])];let i=[.15*r[1],.15*r[0],.15*r[1],.15*r[0]];if(r[0]<=768){const e=.5*r[1],t=.15*e,n=.5*r[1]+.15*e;i[0]=t,i[2]=n}else if(this.args.isSidebarOpen){const e=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),t=parseInt(e,10)||360,n=r[0]-t;i[3]=t+.15*n,i[1]=.15*n}const o=t.getZoom();t.fit(n,{padding:i,duration:1e3,easing:e=>e*(2-e),maxZoom:Math.max(o,18)})}handlePinVisibility(e,t={}){if(!this.mapInstance)return;const r=this.mapInstance.getView().getZoom();if(!t.maintainZoom&&r<16)return void this.animateToSmartCenter(e,16);const n=this.mapInstance.getPixelFromCoordinate(e),i=this.mapInstance.getSize();if(!n||n[0]<0||n[0]>i[0]||n[1]<0||n[1]>i[1]){const r=t.maintainZoom?null:16;this.animateToSmartCenter(e,r)}else this.panIfObscured(e)}animateToSmartCenter(e,t=null){if(!this.mapInstance)return;const r=this.mapInstance.getSize(),n=this.mapInstance.getView();let i=n.getResolution();null!==t&&(i=n.getResolutionForZoom(t));let o=e;if(r[0]<=768){const t=r[1],n=document.querySelector(".app-header"),s=n?n.offsetHeight:60,a=(t/2-(s+(t/2-s)/2))*i;o=[e[0],e[1]-a]}else if(this.args.isSidebarOpen){const t=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),r=(parseInt(t,10)||360)/2*i;o=[e[0]-r,e[1]]}const s={center:o,duration:1e3,easing:e=>e*(2-e)};null!==t&&(s.zoom=t),n.animate(s)}panIfObscured(e){if(!this.mapInstance)return;const t=this.mapInstance.getSize(),r=this.mapInstance.getPixelFromCoordinate(e);if(!r)return;const n=this.mapInstance.getView(),i=n.getCenter(),o=n.getResolution();let s=r[0],a=r[1],l=!1;const c=document.querySelector(".app-header"),u=c?c.offsetHeight:60;if(t[0]<=768){const e=t[1],n=e/2;r[1]>n&&(a=u+(e/2-u)/2,l=!0)}else if(this.args.isSidebarOpen){const e=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),n=parseInt(e,10)||360;r[0]e*(2-e)})}}updateBookmarks=modifier(()=>{const e=this.storage.placesInView;this.loadBookmarks(e)});async loadBookmarks(e=[]){try{if(!this.bookmarkSource)return;e&&0!==e.length||(e=this.storage.placesInView),this.bookmarkSource.clear(),e&&Array.isArray(e)&&e.forEach(e=>{if(e.lat&&e.lon){const t=new Feature({geometry:new Point(fromLonLat([e.lon,e.lat])),name:e.title,id:e.id,isBookmark:!0,originalPlace:e});this.bookmarkSource.addFeature(t)}})}catch(t){console.error("Failed to load bookmarks:",t)}}syncPulse=modifier(()=>{this.searchOverlayElement&&(this.mapUi.isSearching?this.searchOverlayElement.classList.add("active"):this.searchOverlayElement.classList.remove("active"))});syncCreationMode=modifier(()=>{if(this.crosshairElement&&this.mapInstance)if(this.mapUi.isCreating){this.crosshairElement.classList.add("visible");const e=this.mapUi.creationCoordinates;if(e&&e.lat&&e.lon){const t=fromLonLat([e.lon,e.lat]);this.animateToCrosshair(t)}}else this.crosshairElement.classList.remove("visible")});animateToCrosshair(e){if(!this.mapInstance||!this.crosshairElement)return;const t=this.mapInstance.getTargetElement().getBoundingClientRect(),r=this.crosshairElement.getBoundingClientRect(),n=r.left+r.width/2-t.left,i=r.top+r.height/2-t.top,o=this.mapInstance.getSize(),s=n-o[0]/2,a=i-o[1]/2,l=this.mapInstance.getView(),c=l.getResolution(),u=s*c,h=-a*c,d=e[0]-u,p=e[1]-h,f=l.getCenter();Math.sqrt(Math.pow(f[0]-d,2)+Math.pow(f[1]-p,2))>5*c&&l.animate({center:[d,p],duration:800,easing:e=>e*(2-e)})}handleMapMove=async()=>{if(!this.mapInstance||this.isDestroying||this.isDestroyed)return;const e=toLonLat(this.mapInstance.getView().getCenter());if(this.mapUi.updateCenter(e[1],e[0]),this.mapUi.isCreating){const e=this.mapInstance.getTargetElement().getBoundingClientRect(),t=this.crosshairElement.getBoundingClientRect(),r=t.left+t.width/2-e.left,n=t.top+t.height/2-e.top,i=toLonLat(this.mapInstance.getCoordinateFromPixel([r,n])),o=parseFloat(i[1].toFixed(6)),s=parseFloat(i[0].toFixed(6));this.mapUi.updateCreationCoordinates(o,s),this.router.replaceWith("place.new",{queryParams:{lat:o,lon:s}})}const t=this.mapInstance.getSize(),r=this.mapInstance.getView().calculateExtent(t),[n,i]=toLonLat([r[0],r[1]]),[o,s]=toLonLat([r[2],r[3]]),a={minLat:i,minLon:n,maxLat:s,maxLon:o};this.mapUi.updateBounds(a),await this.storage.loadPlacesInBounds(a),this.nostrData.loadPlacesInBounds(a),this.loadBookmarks(this.storage.placesInView);try{const e=this.mapInstance.getView(),t={center:toLonLat(e.getCenter()),zoom:e.getZoom()};localStorage.setItem("marco:map-view",JSON.stringify(t))}catch(l){console.warn("Failed to save map view:",l)}};handleMapClick=async e=>{if(this.ignoreNextMapClick)return void(this.ignoreNextMapClick=!1);const t=this.mapInstance.getFeaturesAtPixel(e.pixel,{hitTolerance:10});let r=null,n=null,i=null;if(t&&t.length>0){console.debug(`Found ${t.length} features in map layer:`);for(const r of t)console.debug(r);const e=t.find(e=>e.get("isBookmark")),o=t.find(e=>e.get("isSearchResult"));e?r=e.get("originalPlace"):o&&(n=o.get("originalPlace"));const s=t[0].getProperties();s.name&&(i=s.name)}const o=e=>{("search"===this.router.currentRouteName||this.mapUi.currentSearch&&this.mapUi.searchResults.length>0)&&(this.mapUi.returnToSearch=!0),this.mapUi.preventNextZoom=!0,this.mapUi.selectPlace(e,{preventZoom:!0}),this.mapUi.showSidebar(),this.router.transitionTo("place",e)};if(this.args.isSidebarOpen){const e=r||n;return e?(console.debug("Clicked feature while sidebar open (switching):",e),void o(e)):void(this.args.onOutsideClick&&this.args.onOutsideClick())}if(r)return console.debug("Clicked bookmark:",r),void o(r);if(n)return console.debug("Clicked search result:",n),void o(n);if(this.mapInstance.getView().getZoom()<16)return;const s=toLonLat(e.coordinate),[a,l]=s,c=i?30:50;if(this.searchOverlayElement){const t=this.mapInstance.getView(),r=2*c/getPointResolution(t.getProjection(),t.getResolution(),e.coordinate);this.searchOverlayElement.style.width=`${r}px`,this.searchOverlayElement.style.height=`${r}px`,this.searchOverlay.setPosition(e.coordinate)}this.mapUi.startSearch();const u={lat:l.toFixed(6),lon:a.toFixed(6),q:null,category:null,selected:i||null};this.router.transitionTo("search",{queryParams:u})};static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[16,0,[29,["map-container ",[52,[30,1],"sidebar-open"]]]],[4,[30,0,["setupMap"]],null,null],[4,[30,0,["updateInteractions"]],null,null],[4,[30,0,["updateBookmarks"]],null,null],[4,[30,0,["updateSearchResults"]],null,null],[4,[30,0,["updateSelectedPin"]],null,null],[4,[30,0,["syncPulse"]],null,null],[4,[30,0,["syncCreationMode"]],null,null],[12],[13]],["@isSidebarOpen"],["if"]]',moduleName:"/home/basti/src/marco/app/components/map.gjs",isStrictMode:!0}),this)}}class UserMenuComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"osmAuth",[service])}#Ze=void initializeDeferredDecorator(this,"osmAuth");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"isNostrConnectModalOpen",[tracked],function(){return!1})}#Xe=void initializeDeferredDecorator(this,"isNostrConnectModalOpen");connectRS(){this.args.onClose(),this.args.storage.showConnectWidget()}static{decorateMethodV2(this.prototype,"connectRS",[action])}disconnectRS(){this.args.storage.disconnect()}static{decorateMethodV2(this.prototype,"disconnectRS",[action])}connectOsm(){this.args.onClose(),this.osmAuth.login()}static{decorateMethodV2(this.prototype,"connectOsm",[action])}disconnectOsm(){this.osmAuth.logout()}static{decorateMethodV2(this.prototype,"disconnectOsm",[action])}openNostrConnectModal(){this.isNostrConnectModalOpen=!0}static{decorateMethodV2(this.prototype,"openNostrConnectModal",[action])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{decorateMethodV2(this.prototype,"closeNostrConnectModal",[action])}disconnectNostr(){this.nostrAuth.disconnect()}static{decorateMethodV2(this.prototype,"disconnectNostr",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"user-menu-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"account-list"],[12],[1,"\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["remotestorage",18]],null],[1,"\\n "],[10,1],[12],[1,"RemoteStorage"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectRS"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectRS"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[10,"strong"],[12],[1,[30,1,["userAddress"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",18]],null],[1,"\\n "],[10,1],[12],[1,"OpenStreetMap"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectOsm"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectOsm"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[10,"strong"],[12],[1,[30,0,["osmAuth","userDisplayName"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",18]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectNostr"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["openNostrConnectModal"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[10,"strong"],[15,"title",[30,0,["nostrAuth","pubkey"]]],[12],[1,"\\n "],[1,[30,0,["nostrData","userDisplayName"]]],[1,"\\n "],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,2],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,3],null,[["@onConnect"],[[30,0,["closeNostrConnectModal"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null]],["@storage"],["if"]]',moduleName:"/home/basti/src/marco/app/components/user-menu.gjs",scope:()=>[IconComponent,on,Modal,NostrConnectComponent],isStrictMode:!0}),this)}}function identity(e){return e}function castForPromiseHelper(e){if(e)if(e instanceof TaskInstance)e.executor.asyncErrorsHandled=!0;else if(e instanceof Yieldable)return e._toPromise();return e}function castAwaitables(e,t){if(Array.isArray(e))return e.map(t);if("object"==typeof e&&null!==e){let r={};return Object.keys(e).forEach(n=>{r[n]=t(e[n])}),r}return e}function taskAwareVariantOf(e,t,r){return function(n){let i=castAwaitables(n,castForPromiseHelper),o=r(i),s=RSVP.defer();e[t](i).then(s.resolve,s.reject);let a=!1,l=()=>{a||(a=!0,o.forEach(e=>{e&&(e instanceof TaskInstance?e.cancel():"function"==typeof e[cancelableSymbol]&&e[cancelableSymbol]())}))},c=s.promise.finally(l);return c[cancelableSymbol]=l,c}}taskAwareVariantOf(RSVP.Promise,"all",identity);class EmberYieldable extends Yieldable{_deferable(){return EMBER_ENVIRONMENT.defer()}}class TimeoutYieldable extends EmberYieldable{constructor(e){super(),this.ms=e}onYield(e){let t=later(()=>e.next(),this.ms);return()=>cancel(t)}}function timeout(e){return new TimeoutYieldable(e)}class SearchBoxComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"photon",[service])}#Ye=void initializeDeferredDecorator(this,"photon");static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"map",[service])}#Je=void initializeDeferredDecorator(this,"map");static{decorateFieldV2(this.prototype,"_internalQuery",[tracked],function(){return""})}#Qe=void initializeDeferredDecorator(this,"_internalQuery");static{decorateFieldV2(this.prototype,"results",[tracked],function(){return[]})}#et=void initializeDeferredDecorator(this,"results");static{decorateFieldV2(this.prototype,"isFocused",[tracked],function(){return!1})}#tt=void initializeDeferredDecorator(this,"isFocused");static{decorateFieldV2(this.prototype,"isLoading",[tracked],function(){return!1})}#rt=void initializeDeferredDecorator(this,"isLoading");get query(){return this.args.query??this._internalQuery}set query(e){this._internalQuery=e}get showPopover(){return this.isFocused&&this.results.length>0}handleInput(e){const t=e.target.value;this.query=t,this.args.onQueryChange&&this.args.onQueryChange(t),t.length<2?this.results=[]:this.searchTask.perform(t)}static{decorateMethodV2(this.prototype,"handleInput",[action])}searchTask=buildTask(()=>({context:this,generator:function*(e){yield timeout(300);const t="string"==typeof e?e:this.query;if(!(t.length<2)){this.isLoading=!0;try{let e,r;this.mapUi.currentCenter&&({lat:e,lon:r}=this.mapUi.currentCenter);const n=t.toLowerCase(),i=POI_CATEGORIES.filter(e=>e.label.toLowerCase().includes(n)).map(e=>({source:"category",title:e.label,id:e.id,icon:"search"})),o=yield this.photon.search(t,e,r);this.results=[...i,...o]}catch(r){console.error("Search failed",r),this.results=[]}finally{this.isLoading=!1}}}}),{restartable:!0},"searchTask");handleFocus(){this.isFocused=!0,this.mapUi.setSearchBoxFocus(!0),this.query.length>=2&&0===this.results.length&&this.searchTask.perform()}static{decorateMethodV2(this.prototype,"handleFocus",[action])}handleBlur(){setTimeout(()=>{this.isFocused=!1,this.mapUi.setSearchBoxFocus(!1)},300)}static{decorateMethodV2(this.prototype,"handleBlur",[action])}handleSubmit(e){if(e.preventDefault(),!this.query)return;let t={q:this.query,selected:null,category:null};if(this.mapUi.currentCenter){const{lat:e,lon:r}=this.mapUi.currentCenter;t.lat=parseFloat(e).toFixed(4),t.lon=parseFloat(r).toFixed(4)}this.router.transitionTo("search",{queryParams:t}),this.isFocused=!1}static{decorateMethodV2(this.prototype,"handleSubmit",[action])}selectResult(e){if("category"===e.source){this.query=e.title,this.args.onQueryChange&&this.args.onQueryChange(e.title),this.results=[];let t=null,r=null;return this.mapUi.currentCenter&&(({lat:t,lon:r}=this.mapUi.currentCenter),t=t?.toString(),r=r?.toString()),void this.router.transitionTo("search",{queryParams:{q:e.title,category:e.id,selected:null,lat:t,lon:r}})}if(this.query=e.title,this.args.onQueryChange&&this.args.onQueryChange(e.title),this.results=[],e.osmId){const t=`osm:${e.osmType}:${e.osmId}`;this.router.transitionTo("place",t)}else this.router.transitionTo("search",{queryParams:{q:e.title,lat:e.lat,lon:e.lon,selected:null,category:null}})}static{decorateMethodV2(this.prototype,"selectResult",[action])}clear(){this.searchTask.cancelAll(),this.mapUi.stopLoading(),this.osm.cancelAll(),this.photon.cancelAll(),this.query="",this.results=[],this.args.onQueryChange&&this.args.onQueryChange(""),this.router.transitionTo("index")}static{decorateMethodV2(this.prototype,"clear",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"search-box"],[12],[1,"\\n "],[11,"form"],[24,0,"search-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[11,"button"],[24,0,"menu-btn-integrated"],[24,"aria-label","Menu"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["menu",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"input"],[24,0,"search-input"],[24,"placeholder","Search places..."],[24,"aria-label","Search places"],[16,2,[30,0,["query"]]],[24,"autocomplete","off"],[24,4,"search"],[4,[32,0],["input",[30,0,["handleInput"]]],null],[4,[32,0],["focus",[30,0,["handleFocus"]]],null],[4,[32,0],["blur",[30,0,["handleBlur"]]],null],[12],[13],[1,"\\n\\n "],[10,"button"],[14,0,"search-submit-btn"],[14,"aria-label","Search"],[14,4,"submit"],[12],[1,"\\n"],[41,[28,[32,2],[[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"text"],null],[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"category"],null]],null],[[[1," "],[8,[32,1],null,[["@name","@size"],["loading-ring",20]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#5f6368"]],null],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["query"]],[[[1," "],[11,"button"],[24,0,"search-clear-btn"],[24,"aria-label","Clear"],[24,4,"button"],[4,[32,0],["click",[30,0,["clear"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["showPopover"]],[[[1," "],[10,0],[14,0,"search-results-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"search-results-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,0,["results"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"search-result-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,4],[[30,0,["selectResult"]],[30,2]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"result-icon"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],[[52,[30,2,["icon"]],[30,2,["icon"]],"map-pin"],16,"#666"]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"result-info"],[12],[1,"\\n "],[10,1],[14,0,"result-title"],[12],[1,[30,2,["title"]]],[13],[1,"\\n"],[41,[28,[32,3],[[30,2,["source"]],"osm"],null],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[28,[32,5],[[30,2,["type"]]],null]],[13],[1,"\\n"]],[]],[[[41,[30,2,["description"]],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[30,2,["description"]]],[13],[1,"\\n"]],[]],null]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13]],["@onToggleMenu","result"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/search-box.gjs",scope:()=>[on,IconComponent,OrHelper,eq$1,fn,humanizeOsmTag],isStrictMode:!0}),this)}}class CategoryChipsComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");get categories(){return POI_CATEGORIES}searchCategory(e){this.args.onSelect&&this.args.onSelect(e);let t={category:e.id,q:null};if(this.mapUi.currentCenter){const{lat:e,lon:r}=this.mapUi.currentCenter;t.lat=parseFloat(e).toFixed(4),t.lon=parseFloat(r).toFixed(4)}this.router.transitionTo("search",{queryParams:t})}static{decorateMethodV2(this.prototype,"searchCategory",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"category-chips-scroll"],[12],[1,"\\n "],[10,0],[14,0,"category-chips-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["categories"]]],null]],null],null,[[[1," "],[11,"button"],[24,0,"category-chip"],[16,"aria-label",[30,1,["label"]]],[16,"disabled",[28,[32,0],[[28,[32,1],[[30,0,["mapUi","loadingState","type"]],"category"],null],[28,[32,1],[[30,0,["mapUi","loadingState","value"]],[30,1,["id"]]],null]],null]],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,0,["searchCategory"]],[30,1]],null]],null],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size"],[[30,1,["icon"]],16]],null],[1,"\\n "],[10,1],[12],[1,[30,1,["label"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[1]],null],[1," "],[13],[1,"\\n"],[13]],["category"],["each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/category-chips.gjs",scope:()=>[AndHelper,eq$1,on,fn,IconComponent],isStrictMode:!0}),this)}}const CACHE_NAME="nostr-image-cache-v1",cachedImage=modifier((e,[t])=>{let r=null;return async function(){if(t)try{const n=await caches.open(CACHE_NAME),i=await n.match(t);if(i){const t=await i.blob();return r=URL.createObjectURL(t),void(e.src=r)}const o=await fetch(t,{mode:"cors",credentials:"omit"});if(o.ok){const i=o.clone();await n.put(t,i);const s=await o.blob();r=URL.createObjectURL(s),e.src=r}else e.src=t}catch(error){console.warn(`Failed to cache image ${t}, falling back to standard src`,error),e.src=t}else e.src=""}(),()=>{r&&(URL.revokeObjectURL(r),r=null)}});class AppHeaderComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"isUserMenuOpen",[tracked],function(){return!1})}#nt=void initializeDeferredDecorator(this,"isUserMenuOpen");static{decorateFieldV2(this.prototype,"searchQuery",[tracked],function(){return""})}#it=void initializeDeferredDecorator(this,"searchQuery");get hasQuery(){return!!this.searchQuery}toggleUserMenu(){this.isUserMenuOpen=!this.isUserMenuOpen}static{decorateMethodV2(this.prototype,"toggleUserMenu",[action])}closeUserMenu(){this.isUserMenuOpen=!1}static{decorateMethodV2(this.prototype,"closeUserMenu",[action])}handleQueryChange(e){this.searchQuery=e}static{decorateMethodV2(this.prototype,"handleQueryChange",[action])}handleChipSelect(e){this.searchQuery=e.label}static{decorateMethodV2(this.prototype,"handleChipSelect",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"header"],[14,0,"app-header"],[12],[1,"\\n "],[10,0],[14,0,"header-left"],[12],[1,"\\n "],[8,[32,0],null,[["@query","@onToggleMenu","@onQueryChange"],[[30,0,["searchQuery"]],[30,1],[30,0,["handleQueryChange"]]]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["settings","showQuickSearchButtons"]],[[[1," "],[10,0],[15,0,[29,["header-center ",[52,[30,0,["hasQuery"]],"searching"]]]],[12],[1,"\\n "],[8,[32,1],null,[["@onSelect"],[[30,0,["handleChipSelect"]]]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,0],[14,0,"header-right"],[12],[1,"\\n "],[10,0],[14,0,"user-menu-container"],[12],[1,"\\n "],[11,"button"],[24,0,"user-btn btn-press"],[24,"aria-label","User Menu"],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleUserMenu"]]],null],[12],[1,"\\n"],[41,[28,[32,3],[[30,0,["nostrAuth","isConnected"]],[30,0,["nostrData","profile","picture"]]],null],[[[1," "],[11,"img"],[24,0,"user-avatar"],[24,"alt","User Avatar"],[4,[32,4],[[30,0,["nostrData","profile","picture"]]],null],[12],[13],[1,"\\n"]],[]],[[[1," "],[10,0],[14,0,"user-avatar-placeholder"],[12],[1,"\\n "],[8,[32,5],null,[["@name","@size","@color"],["user",20,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isUserMenuOpen"]],[[[1," "],[8,[32,6],null,[["@storage","@onClose"],[[30,0,["storage"]],[30,0,["closeUserMenu"]]]],null],[1,"\\n "],[11,0],[24,0,"menu-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["closeUserMenu"]]],null],[12],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onToggleMenu"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-header.gjs",scope:()=>[SearchBoxComponent,CategoryChipsComponent,on,AndHelper,cachedImage,IconComponent,UserMenuComponent],isStrictMode:!0}),this)}}const iconRounded='\n \x3c!-- Background --\x3e\n \n\n \x3c!-- Subtle map grid (kept well outside safe zone) --\x3e\n \n \n \n \n\n \n \n \n \n\n \x3c!-- Location pin (exact app shape, larger, centered, safe-zone compliant) --\x3e\n \x3c!-- Safe zone target: ~680px diameter --\x3e\n \n \n \n \n\n',templateOnly=templateOnlyComponent,AppMenuHome=setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[1,"\\n "],[10,1],[14,0,"app-logo-icon"],[12],[1,"\\n "],[1,[28,[32,0],[[32,1]],null]],[1,"\\n "],[13],[1,"\\n Marco\\n "],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,2],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"ul"],[14,0,"app-menu"],[12],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"settings"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["settings",20]],null],[1,"\\n "],[10,1],[12],[1,"Settings"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"about"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["info",20]],null],[1,"\\n "],[10,1],[12],[1,"About"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onClose","@onNavigate"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/home.gjs",scope:()=>[htmlSafe,iconRounded,on,IconComponent,fn],isStrictMode:!0}),templateOnly());class AppMenuSettingsMapUi extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",20]],null],[1,"\\n "],[10,1],[12],[1,"Map & UI"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","show-quick-search"],[12],[1,"Quick search buttons visible"],[13],[1,"\\n "],[11,"select"],[24,1,"show-quick-search"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"showQuickSearchButtons"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","showQuickSearchButtons"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","showQuickSearchButtons"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","map-kinetic"],[12],[1,"Map Inertia (Kinetic Panning)"],[13],[1,"\\n "],[11,"select"],[24,1,"map-kinetic"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"mapKinetic"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","mapKinetic"]],"selected"]],[12],[1,"\\n On\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","mapKinetic"]]],"selected"]],[12],[1,"\\n Off\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange"],["if","unless"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/map-ui.gjs",scope:()=>[IconComponent,on,fn],isStrictMode:!0}),this)}}class AppMenuSettingsApis extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["server",20]],null],[1,"\\n "],[10,1],[12],[1,"API Providers"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","overpass-api"],[12],[1,"Overpass API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"overpass-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"overpassApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","overpassApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,2,["url"]]],[15,"selected",[52,[28,[32,3],[[30,2,["url"]],[30,0,["settings","overpassApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,2,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","photon-api"],[12],[1,"Photon API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"photon-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"photonApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","photonApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,3,["url"]]],[15,"selected",[52,[28,[32,3],[[30,3,["url"]],[30,0,["settings","photonApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,3,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","api","api"],["each","-track-array","if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/apis.gjs",scope:()=>[IconComponent,on,fn,eq$1],isStrictMode:!0}),this)}}const stripProtocol=e=>e?e.replace(/^wss?:\/\//,""):"";class AppMenuSettingsNostr extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{decorateFieldV2(this.prototype,"newReadRelay",[tracked],function(){return""})}#ot=void initializeDeferredDecorator(this,"newReadRelay");static{decorateFieldV2(this.prototype,"newWriteRelay",[tracked],function(){return""})}#st=void initializeDeferredDecorator(this,"newWriteRelay");updateNewReadRelay(e){this.newReadRelay=e.target.value}static{decorateMethodV2(this.prototype,"updateNewReadRelay",[action])}updateNewWriteRelay(e){this.newWriteRelay=e.target.value}static{decorateMethodV2(this.prototype,"updateNewWriteRelay",[action])}addReadRelay(){const e=normalizeRelayUrl(this.newReadRelay);if(!e)return;const t=this.settings.nostrReadRelays||this.nostrData.defaultReadRelays,r=new Set([...t,e]);this.settings.update("nostrReadRelays",Array.from(r)),this.newReadRelay=""}static{decorateMethodV2(this.prototype,"addReadRelay",[action])}removeReadRelay(e){const t=(this.settings.nostrReadRelays||this.nostrData.defaultReadRelays).filter(t=>t!==e);this.settings.update("nostrReadRelays",t)}static{decorateMethodV2(this.prototype,"removeReadRelay",[action])}handleReadRelayKeydown(e){"Enter"===e.key&&this.addReadRelay()}static{decorateMethodV2(this.prototype,"handleReadRelayKeydown",[action])}handleWriteRelayKeydown(e){"Enter"===e.key&&this.addWriteRelay()}static{decorateMethodV2(this.prototype,"handleWriteRelayKeydown",[action])}resetReadRelays(){this.settings.update("nostrReadRelays",null)}static{decorateMethodV2(this.prototype,"resetReadRelays",[action])}addWriteRelay(){const e=normalizeRelayUrl(this.newWriteRelay);if(!e)return;const t=this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays,r=new Set([...t,e]);this.settings.update("nostrWriteRelays",Array.from(r)),this.newWriteRelay=""}static{decorateMethodV2(this.prototype,"addWriteRelay",[action])}removeWriteRelay(e){const t=(this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays).filter(t=>t!==e);this.settings.update("nostrWriteRelays",t)}static{decorateMethodV2(this.prototype,"removeWriteRelay",[action])}resetWriteRelays(){this.settings.update("nostrWriteRelays",null)}static{decorateMethodV2(this.prototype,"resetWriteRelays",[action])}async clearCache(){try{await this.nostrData.clearCache(),this.toast.show("Nostr cache cleared")}catch(e){this.toast.show(`Failed to clear Nostr cache: ${e.message}`)}}static{decorateMethodV2(this.prototype,"clearCache",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",20]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","nostr-photo-fallback-uploads"],[12],[1,"Upload photos to fallback\\n servers"],[13],[1,"\\n "],[11,"select"],[24,1,"nostr-photo-fallback-uploads"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"nostrPhotoFallbackUploads"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","nostrPhotoFallbackUploads"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","nostrPhotoFallbackUploads"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-read-relay"],[12],[1,"Read Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeReadRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,2]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeReadRelay"]],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-read-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newReadRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewReadRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleReadRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addReadRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrReadRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetReadRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-write-relay"],[12],[1,"Write Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeWriteRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,3]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeWriteRelay"]],[30,3]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-write-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newWriteRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewWriteRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleWriteRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addWriteRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrWriteRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetWriteRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[12],[1,"Cached data"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline btn-full"],[24,4,"button"],[4,[32,1],["click",[30,0,["clearCache"]]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["database",18,"var(--danger-color)"]],null],[1,"\\n Clear profiles, photos, and reviews\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","relay","relay"],["if","unless","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/nostr.gjs",scope:()=>[IconComponent,on,fn,stripProtocol],isStrictMode:!0}),this)}}class AppMenuSettings extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");updateSetting(e,t){let r=t.target.value;"true"===r&&(r=!0),"false"===r&&(r=!1),this.settings.update(e,r)}static{decorateMethodV2(this.prototype,"updateSetting",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"Settings"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"settings-section"],[12],[1,"\\n "],[8,[32,2],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,3],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,4],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings.gjs",scope:()=>[on,IconComponent,AppMenuSettingsMapUi,AppMenuSettingsApis,AppMenuSettingsNostr],isStrictMode:!0}),this)}}const AppMenuAbout=setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"About"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"about-section"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Marco"],[13],[1,"\\n (as in\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/Marco_Polo"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"Marco Polo"],[13],[1,") is an unhosted maps application that respects your\\n privacy and choices.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n Connect your own\\n "],[10,3],[14,6,"https://remotestorage.io/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"remote storage"],[13],[1,"\\n to sync place bookmarks across apps and devices.\\n "],[13],[1,"\\n\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size"],["gift",20]],null],[1,"\\n "],[10,1],[12],[1,"Open Source"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,"table"],[12],[1,"\\n "],[10,"thead"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"th"],[12],[1,"Source"],[13],[1,"\\n "],[10,"th"],[12],[1,"License"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tbody"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://gitea.kosmos.org/raucao/marco"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Marco App\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/GNU_Affero_General_Public_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","GNU Affero General Public License"],[12],[1,"AGPL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://openstreetmap.org/copyright"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Map Data\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://opendatacommons.org/licenses/odbl/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","Open Data Commons Open Database License"],[12],[1,"ODbL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/feathericons/feather"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Feather Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/MIT_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","MIT License"],[12],[1,"MIT"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://pinhead.ink/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Pinhead Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/waysidemapping/pinhead?tab=readme-ov-file#where-the-icons-are-from"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Various\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["heart",20,"#e5533d"]],null],[1,"\\n "],[10,1],[12],[1,"Contribute"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most impactful:"],[13],[1,"\\n Add and improve data for points of interest in\\n "],[10,3],[14,6,"https://www.openstreetmap.org"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"OpenStreetMap"],[13],[1,".\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most appreciated:"],[13],[1,"\\n Use this app as much as you can and\\n "],[10,3],[14,6,"https://community.remotestorage.io/t/marco-an-unhosted-maps-app/941"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"submit feedback"],[13],[1,"\\n about your experience, problems, feature wishes, etc.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most supportive:"],[13],[1,"\\n Tell others about this app, on social media, in blog posts,\\n educational videos, etc.\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/about.gjs",scope:()=>[on,IconComponent],isStrictMode:!0}),templateOnly());class AppMenu extends GlimmerComponent{static{decorateFieldV2(this.prototype,"currentView",[tracked],function(){return"menu"})}#at=void initializeDeferredDecorator(this,"currentView");setView(e){this.currentView=e}static{decorateMethodV2(this.prototype,"setView",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar app-menu-pane"],[12],[1,"\\n"],[41,[28,[32,0],[[30,0,["currentView"]],"menu"],null],[[[1," "],[8,[32,1],null,[["@onNavigate","@onClose"],[[30,0,["setView"]],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"settings"],null],[[[1," "],[8,[32,2],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"about"],null],[[[1," "],[8,[32,4],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n "]],[]],null]],[]]]],[]]],[13]],["@onClose"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/index.gjs",scope:()=>[eq$1,AppMenuHome,AppMenuSettings,fn,AppMenuAbout],isStrictMode:!0}),this)}}class ToastComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["toast","isVisible"]],[[[1," "],[10,0],[14,0,"toast-notification"],[12],[1,"\\n "],[1,[30,0,["toast","message"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/toast.gjs",isStrictMode:!0}),this)}}class ApplicationComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"isAppMenuOpen",[tracked],function(){return!1})}#lt=void initializeDeferredDecorator(this,"isAppMenuOpen");get isSidebarOpen(){return this.mapUi.isSidebarVisible&&("place"===this.router.currentRouteName||"place.new"===this.router.currentRouteName||"search"===this.router.currentRouteName)}constructor(){super(...arguments),console.debug("Application component constructed"),this.storage}toggleAppMenu(){this.isAppMenuOpen=!this.isAppMenuOpen}static{decorateMethodV2(this.prototype,"toggleAppMenu",[action])}closeAppMenu(){this.isAppMenuOpen=!1}static{decorateMethodV2(this.prototype,"closeAppMenu",[action])}handleOutsideClick(){this.isAppMenuOpen?this.closeAppMenu():"search"!==this.router.currentRouteName&&"place"!==this.router.currentRouteName||(this.mapUi.clearSelection(),this.mapUi.hideSidebar())}static{decorateMethodV2(this.prototype,"handleOutsideClick",[action])}refreshBookmarks(){this.storage.notifyChange()}static{decorateMethodV2(this.prototype,"refreshBookmarks",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[1,[28,[32,0],["Marco"],null]],[1,"\\n\\n"],[8,[32,1],null,[["@onToggleMenu"],[[30,0,["toggleAppMenu"]]]],null],[1,"\\n\\n"],[10,0],[14,1,"rs-widget-container"],[15,0,[52,[30,0,["storage","isWidgetOpen"]],"visible"]],[12],[13],[1,"\\n\\n"],[41,[30,0,["storage","isWidgetOpen"]],[[[1," "],[11,0],[24,0,"rs-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["storage","closeWidget"]]],null],[12],[13],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,3],null,[["@isSidebarOpen","@onOutsideClick"],[[28,[32,4],[[30,0,["isSidebarOpen"]],[30,0,["isAppMenuOpen"]]],null],[30,0,["handleOutsideClick"]]]],null],[1,"\\n\\n"],[41,[30,0,["isAppMenuOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeAppMenu"]]]],null],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,6],null,null,null],[1,"\\n\\n"],[46,[28,[31,2],null,null],null,null,null]],[],["if","component","-outlet"]]',moduleName:"/home/basti/src/marco/app/templates/application.gjs",scope:()=>[PageTitle,AppHeaderComponent,on,MapComponent,OrHelper,AppMenu,ToastComponent],isStrictMode:!0}),this)}}const amdModule32=Object.freeze(Object.defineProperty({__proto__:null,default:ApplicationComponent},Symbol.toStringTag,{value:"Module"}));class ApplicationRoute extends Route{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage")}const amdModule33=Object.freeze(Object.defineProperty({__proto__:null,default:ApplicationRoute},Symbol.toStringTag,{value:"Module"}));class IndexRoute extends Route{static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");activate(){this.mapUi.clearSearchResults()}}const amdModule34=Object.freeze(Object.defineProperty({__proto__:null,default:IndexRoute},Symbol.toStringTag,{value:"Module"}));class OauthOsmCallbackRoute extends Route{static{decorateFieldV2(this.prototype,"osmAuth",[service])}#Ze=void initializeDeferredDecorator(this,"osmAuth");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");async model(){try{await this.osmAuth.handleCallback()}catch(e){console.error("Failed to handle OSM OAuth callback",e)}finally{this.router.transitionTo("index")}}}const amdModule35=Object.freeze(Object.defineProperty({__proto__:null,default:OauthOsmCallbackRoute},Symbol.toStringTag,{value:"Module"}));class PlaceTemplate extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"localPlace",[tracked],function(){return null})}#ct=void initializeDeferredDecorator(this,"localPlace");constructor(){super(...arguments),this.localPlace=this.args.model}get place(){const e=this.args.model,t=e.osmId||e.id;return this.storage.findPlaceById(t)||(!this.localPlace||this.localPlace.osmId!==t&&this.localPlace.id!==t?e.createdAt?{...e,id:void 0,createdAt:void 0,geohash:void 0}:e:this.localPlace)}handleUpdate(e){console.debug("Updating local place state:",e),this.localPlace=e,this.storage.notifyChange()}static{decorateMethodV2(this.prototype,"handleUpdate",[action])}refreshMap(){this.storage.notifyChange()}static{decorateMethodV2(this.prototype,"refreshMap",[action])}navigateBack(e){null===e?this.mapUi.returnToSearch&&this.mapUi.currentSearch?(this.mapUi.showSidebar(),this.router.transitionTo("search",{queryParams:this.mapUi.currentSearch})):this.router.transitionTo("index"):(this.mapUi.showSidebar(),this.router.transitionTo("place",e))}static{decorateMethodV2(this.prototype,"navigateBack",[action])}close(){this.mapUi.clearSelection(),this.mapUi.hideSidebar()}static{decorateMethodV2(this.prototype,"close",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["mapUi","isSidebarVisible"]],[[[1," "],[8,[32,0],null,[["@selectedPlace","@onClose","@onSelect","@onBookmarkChange","@onUpdate"],[[30,0,["place"]],[30,0,["close"]],[30,0,["navigateBack"]],[30,0,["refreshMap"]],[30,0,["handleUpdate"]]]],null],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/templates/place.gjs",scope:()=>[PlacesSidebar],isStrictMode:!0}),this)}}const amdModule36=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceTemplate},Symbol.toStringTag,{value:"Module"}));class PlaceRoute extends Route{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");async model(e){const t=e.place_id;let r,n,i=!1;(t.startsWith("osm:node:")||t.startsWith("osm:way:")||t.startsWith("osm:relation:"))&&(i=!0,[,r,n]=t.split(":"),console.debug(`Fetching explicit OSM ${r}:`,n));let o=null;i&&(o=this.loadOsmPlace(n,r)),await this.waitForSync();let s=i?n:t,a=this.storage.findPlaceById(s);return a&&i&&a.osmType!==r&&(a=null),a?(console.debug("Found in bookmarks:",a.title),a):i?(console.debug(`Not in bookmarks, using explicitly fetched OSM ${r}:`,n),await o):(console.warn("Not in bookmarks:",t),null)}async waitForSync(){if(this.storage.initialSyncDone)return;console.debug("Waiting for initial storage sync...");const e=Date.now();for(;!this.storage.initialSyncDone;){if(Date.now()-e>5e3){console.warn("Timed out waiting for initial sync");break}await new Promise(e=>setTimeout(e,100))}}async afterModel(e){if(e&&e.osmId&&e.osmType&&"node"!==e.osmType&&!e.geojson){console.debug("Model missing geometry, fetching full OSM details...");const t=await this.loadOsmPlace(e.osmId,e.osmType);t&&(Object.assign(e,t),console.debug("Enriched model with full OSM details",e))}if(e){const t={preventZoom:this.mapUi.preventNextZoom};this.mapUi.selectPlace(e,t),this.mapUi.showSidebar(),this.mapUi.preventNextZoom=!1}this.mapUi.stopSearch()}deactivate(){this.mapUi.clearSelection(),this.mapUi.returnToSearch=!1}async loadOsmPlace(e,t=null){try{const r=await this.osm.fetchOsmObject(e,t);if(r)return console.debug("Found OSM POI:",r),r}catch(r){console.error("Failed to fetch POI",r)}return null}setupController(e,t){super.setupController(e,t),this.checkUpdates(t)}async checkUpdates(e){if(e&&e.id&&e.osmId&&e.osmType){const t=await this.storage.refreshPlace(e);t&&this.mapUi.selectPlace(t,{preventZoom:!0})}}serialize(e){return e.osmId&&e.osmType?{place_id:`osm:${e.osmType}:${e.osmId}`}:e.id?{place_id:e.id}:{place_id:e.osmId}}}const amdModule37=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceRoute},Symbol.toStringTag,{value:"Module"}));class PlaceNewTemplate extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");get initialPlace(){return{title:"",description:""}}close(){this.router.transitionTo("index")}static{decorateMethodV2(this.prototype,"close",[action])}async savePlace(e){try{const t=this.mapUi.creationCoordinates||{lat:this.args.model.lat,lon:this.args.model.lon},r=parseFloat(t.lat.toFixed(6)),n=parseFloat(t.lon.toFixed(6)),i={title:e.title||"Untitled Place",description:e.description,lat:r,lon:n,tags:[],osmTags:{}},o=await this.storage.storePlace(i);console.debug("Created private place:",o.title),this.router.replaceWith("place",o)}catch(t){console.error("Failed to create place:",t),alert("Failed to create place: "+t.message)}}static{decorateMethodV2(this.prototype,"savePlace",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["mapUi","isSidebarVisible"]],[[[1," "],[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[8,[32,0],null,[["@name","@size","@color"],["plus-circle",20,"#ea4335"]],null],[1,"\\n New Place"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,1],["click",[30,0,["close"]]],null],[12],[8,[32,0],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,2],[14,0,"helper-text"],[12],[1,"\\n Drag the map to position the crosshair.\\n "],[13],[1,"\\n\\n "],[8,[32,2],null,[["@place","@onSave","@onCancel"],[[30,0,["initialPlace"]],[30,0,["savePlace"]],[30,0,["close"]]]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/templates/place/new.gjs",scope:()=>[IconComponent,on,PlaceEditForm],isStrictMode:!0}),this)}}const amdModule38=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceNewTemplate},Symbol.toStringTag,{value:"Module"}));class PlaceNewRoute extends Route{static{decorateFieldV2(this.prototype,"mapUi",[service])}#Ke=void initializeDeferredDecorator(this,"mapUi");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0}};model(e){return{lat:parseFloat(e.lat),lon:parseFloat(e.lon)}}setupController(e,t){super.setupController(e,t),t.lat&&t.lon&&this.mapUi.updateCreationCoordinates(t.lat,t.lon),this.mapUi.startCreating(),this.mapUi.showSidebar()}deactivate(){this.mapUi.stopCreating()}}const amdModule39=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceNewRoute},Symbol.toStringTag,{value:"Module"}));let exportFastbootModules={};const compatModules=Object.assign({},defineModule0,{"marco/app":amdModule0,"marco/config/environment":amdModule1,"marco/deprecation-workflow":amdModule2,"marco/router":amdModule3,"marco/services/blossom":amdModule4,"marco/services/image-processor":amdModule5,"marco/services/map-ui":amdModule6,"marco/services/nostr-auth":amdModule7,"marco/services/nostr-data":amdModule8,"marco/services/nostr-relay":amdModule9,"marco/services/osm-auth":amdModule10,"marco/services/osm":amdModule11,"marco/services/photon":amdModule12,"marco/services/settings":amdModule13,"marco/services/storage":amdModule14,"marco/services/toast":amdModule15,"marco/utils/device":amdModule16,"marco/utils/format-text":amdModule17,"marco/utils/geo":amdModule18,"marco/utils/geohash-coverage":amdModule19,"marco/utils/icons":amdModule20,"marco/utils/nostr":amdModule21,"marco/utils/osm-icons":amdModule22,"marco/utils/osm":amdModule23,"marco/utils/place-mapping":amdModule24,"marco/utils/poi-categories":amdModule25,"marco/utils/social-links":amdModule26,"marco/workers/image-processor":amdModule27,"marco/services/page-title":amdModule28,"marco/templates/search":amdModule29,"marco/controllers/search":amdModule30,"marco/routes/search":amdModule31,"marco/templates/application":amdModule32,"marco/routes/application":amdModule33,"marco/routes/index":amdModule34,"marco/routes/oauth/osm-callback":amdModule35,"marco/templates/place":amdModule36,"marco/routes/place":amdModule37,"marco/templates/place/new":amdModule38,"marco/routes/place/new":amdModule39},exportFastbootModules);class Cache{constructor(e,t,r){this.limit=e,this.func=t,this.store=r,this.size=0,this.misses=0,this.hits=0,this.store=r||new Map}get(e){let t=this.store.get(e);return this.store.has(e)?(this.hits++,this.store.get(e)):(this.misses++,t=this.set(e,this.func(e)),t)}set(e,t){return this.limit>this.size&&(this.size++,this.store.set(e,t)),t}purge(){this.store.clear(),this.size=0,this.hits=0,this.misses=0}}const STRING_DASHERIZE_REGEXP=/[ _]/g,STRING_DASHERIZE_CACHE=new Cache(1e3,e=>decamelize(e).replace(STRING_DASHERIZE_REGEXP,"-")),STRING_CLASSIFY_REGEXP_1=/^(\-|_)+(.)?/,STRING_CLASSIFY_REGEXP_2=/(.)(\-|\_|\.|\s)+(.)?/g,STRING_CLASSIFY_REGEXP_3=/(^|\/|\.)([a-z])/g,CLASSIFY_CACHE=new Cache(1e3,e=>{const t=(e,t,r)=>r?`_${r.toUpperCase()}`:"",r=(e,t,r,n)=>t+(n?n.toUpperCase():""),n=e.split("/");for(let i=0;ie.toUpperCase())}),STRING_UNDERSCORE_REGEXP_1=/([a-z\d])([A-Z]+)/g,STRING_UNDERSCORE_REGEXP_2=/\-|\s+/g,UNDERSCORE_CACHE=new Cache(1e3,e=>e.replace(STRING_UNDERSCORE_REGEXP_1,"$1_$2").replace(STRING_UNDERSCORE_REGEXP_2,"_").toLowerCase()),STRING_DECAMELIZE_REGEXP=/([a-z\d])([A-Z])/g,DECAMELIZE_CACHE=new Cache(1e3,e=>e.replace(STRING_DECAMELIZE_REGEXP,"$1_$2").toLowerCase());function decamelize(e){return DECAMELIZE_CACHE.get(e)}function dasherize(e){return STRING_DASHERIZE_CACHE.get(e)}function classify(e){return CLASSIFY_CACHE.get(e)}function underscore(e){return UNDERSCORE_CACHE.get(e)}function classFactory(e){return{create:t=>"function"==typeof e.extend?e.extend(t):e}}class ModuleRegistry{constructor(e){this._entries=e||globalThis.requirejs.entries}moduleNames(){return Object.keys(this._entries)}has(e){return e in this._entries}get(...e){return globalThis.require(...e)}}class Resolver{static moduleBasedResolver=!0;moduleBasedResolver=!0;_deprecatedPodModulePrefix=!1;_normalizeCache=Object.create(null);static create(e){return new this(e)}moduleNameLookupPatterns=[this.podBasedModuleName,this.podBasedComponentsInSubdir,this.mainModuleName,this.defaultModuleName,this.nestedColocationComponentModuleName];static withModules(e){return class extends(this){static explicitModules=e}}constructor(e){if(Object.assign(this,e),!this._moduleRegistry){let e=this.constructor.explicitModules;e?this._moduleRegistry={moduleNames:()=>Object.keys(e),has:t=>Boolean(e[t]),get:t=>e[t],addModules(t){e=Object.assign({},e,t)}}:(void 0===globalThis.requirejs.entries&&(globalThis.requirejs.entries=globalThis.requirejs._eak_seen),this._moduleRegistry=new ModuleRegistry)}this.pluralizedTypes=this.pluralizedTypes||Object.create(null),this.pluralizedTypes.config||(this.pluralizedTypes.config="config")}makeToString(e,t){return this.namespace.modulePrefix+"@"+t+":"}shouldWrapInClassFactory(){return!1}parseName(e){if(!0===e.parsedName)return e;let t,r,n,i=e.split("@");if(3===i.length){if(0===i[0].length){t=`@${i[1]}`;let e=i[2].split(":");r=e[0],n=e[1]}else t=`@${i[1]}`,r=i[0].slice(0,-1),n=i[2];"template:components"===r&&(n=`components/${n}`,r="template")}else if(2===i.length){let e=i[0].split(":");if(2===e.length)0===e[1].length?(r=e[0],n=`@${i[1]}`):(t=e[1],r=e[0],n=i[1]);else{let e=i[1].split(":");t=i[0],r=e[0],n=e[1]}"template"===r&&0===t.lastIndexOf("components/",0)&&(n=`components/${n}`,t=t.slice(11))}else i=e.split(":"),r=i[0],n=i[1];let o=n,s=this.namespace;return{parsedName:!0,fullName:e,prefix:t||this.prefix({type:r}),type:r,fullNameWithoutType:o,name:n,root:s,resolveMethodName:"resolve"+classify(r)}}resolveOther(e){assert("`modulePrefix` must be defined",this.namespace.modulePrefix);let t=this.findModuleName(e);if(t){let r=this._extractDefaultExport(t,e);if(void 0===r)throw new Error(` Expected to find: '${e.fullName}' within '${t}' but got 'undefined'. Did you forget to 'export default' within '${t}'?`);return this.shouldWrapInClassFactory(r,e)&&(r=classFactory(r)),r}}normalize(e){return this._normalizeCache[e]||(this._normalizeCache[e]=this._normalize(e))}resolve(e){if("resolver:current"===e)return{create:()=>this};let t,r=this.parseName(e),n=r.resolveMethodName;return"function"==typeof this[n]&&(t=this[n](r)),null==t&&(t=this.resolveOther(r)),t}addModules(e){if(!this._moduleRegistry.addModules)throw new Error("addModules is only supported when your Resolver has been configured to use static modules via Resolver.withModules()");this._moduleRegistry.addModules(e)}_normalize(e){let t=e.split(":");if(t.length>1){let e=t[0];return"component"===e||"helper"===e||"modifier"===e||"template"===e&&0===t[1].indexOf("components/")?e+":"+t[1].replace(/_/g,"-"):e+":"+dasherize(t[1].replace(/\./g,"/"))}return e}pluralize(e){return this.pluralizedTypes[e]||(this.pluralizedTypes[e]=e+"s")}podBasedLookupWithPrefix(e,t){let r=t.fullNameWithoutType;return"template"===t.type&&(r=r.replace(/^components\//,"")),e+"/"+r+"/"+t.type}podBasedModuleName(e){let t=this.namespace.podModulePrefix||this.namespace.modulePrefix;return this.podBasedLookupWithPrefix(t,e)}podBasedComponentsInSubdir(e){let t=this.namespace.podModulePrefix||this.namespace.modulePrefix;if(t+="/components","component"===e.type||/^components/.test(e.fullNameWithoutType))return this.podBasedLookupWithPrefix(t,e)}resolveEngine(e){let t=e.fullNameWithoutType+"/engine";if(this._moduleRegistry.has(t))return this._extractDefaultExport(t)}resolveRouteMap(e){let t=e.fullNameWithoutType,r=t+"/routes";if(this._moduleRegistry.has(r)){let e=this._extractDefaultExport(r);return assert(`The route map for ${t} should be wrapped by 'buildRoutes' before exporting.`,e.isRouteMap),e}}resolveTemplate(e){return this.resolveOther(e)}mainModuleName(e){if("main"===e.fullNameWithoutType)return e.prefix+"/"+e.type}defaultModuleName(e){return e.prefix+"/"+this.pluralize(e.type)+"/"+e.fullNameWithoutType}nestedColocationComponentModuleName(e){if("component"===e.type)return e.prefix+"/"+this.pluralize(e.type)+"/"+e.fullNameWithoutType+"/index"}prefix(e){let t=this.namespace.modulePrefix;return this.namespace[e.type+"Prefix"]&&(t=this.namespace[e.type+"Prefix"]),t}findModuleName(e){let t,r=this.moduleNameLookupPatterns;for(let n=0,i=r.length;nn.length+i.length)return e+":"+t.slice(o+n.length,s);let a=r+"/"+this.pluralize(e)+"/";return 0===t.indexOf(a)&&t.length>a.length?e+":"+t.slice(a.length):void 0}_extractDefaultExport(e){let t=this._moduleRegistry.get(e,null,null,!0);return t&&t.default&&(t=t.default),t}}function assert(e,t){if(!t)throw new Error(e)}function setupGlobal(e,t){globalThis.emberInspectorApps||(globalThis.emberInspectorApps=[]),globalThis.emberInspectorApps.push({app:e,name:`app-${globalThis.emberInspectorApps.length}`,loadCompatInspector:t}),globalThis.dispatchEvent&&globalThis.dispatchEvent(new Event("Ember"))}function setupInspector(e){setupGlobal(e,()=>__vitePreload(()=>import("./modules-4-12-CSVC-YcG.js"),[]))}class App extends Application$1{modulePrefix=ENV.modulePrefix;podModulePrefix=ENV.podModulePrefix;Resolver=Resolver.withModules(compatModules);inspector=setupInspector(this)}App.create(ENV.APP);export{nativeDescDecorator as $,ASYNC_OBSERVERS as A,endPropertyChanges as B,ComputedDescriptor as C,DEBUG_INJECTION_FUNCTIONS as D,expandProperties as E,findNamespace as F,findNamespaces as G,flushAsyncObservers as H,getCachedValueFor as I,getProperties as J,hasListeners as K,Libraries as L,hasUnknownProperty as M,NAMESPACES as N,inject$2 as O,PROPERTY_DID_CHANGE as P,isClassicDecorator as Q,isComputed as R,SYNC_OBSERVERS as S,TrackedDescriptor as T,isConst as U,isElementDescriptor as V,isSearchDisabled as W,LIBRARIES as X,makeComputedDecorator as Y,markObjectAsDirty as Z,_getPath as _,get$7 as a,ActionHandler as a$,notifyPropertyChange as a0,objectAt as a1,on$3 as a2,processAllNamespaces as a3,processNamespace as a4,removeArrayObserver as a5,removeListener as a6,removeNamespace as a7,removeObserver as a8,replace as a9,RSVP as aA,defer$1 as aB,denodeify as aC,filter$2 as aD,hash$4 as aE,hashSettled as aF,map$3 as aG,off as aH,on$2 as aI,race as aJ,reject as aK,resolve$3 as aL,rethrow as aM,guidFor as aN,MutableArray as aO,ENV$1 as aP,context$1 as aQ,getENV as aR,getLookup as aS,global$1 as aT,setLookup as aU,Meta as aV,UNDEFINED as aW,counters as aX,meta$1 as aY,peekMeta as aZ,setMeta as a_,replaceInNativeArray as aa,revalidateObservers as ab,sendEvent as ac,setClassicDecorator as ad,setSearchDisabled as ae,setProperties as af,setUnprocessedMixins as ag,tagForObject as ah,tagForProperty as ai,tracked as aj,trySet as ak,Input as al,Textarea as am,componentCapabilities as an,Component as ao,getComponentTemplate as ap,setComponentManager as aq,setComponentTemplate as ar,EventTarget as as,Promise$1 as at,all$2 as au,allSettled as av,asap as aw,async$1 as ax,cast as ay,configure as az,ComputedProperty as b,index$1 as b$,Comparable as b0,ContainerProxyMixin as b1,MutableEnumerable as b2,RSVP$1 as b3,RegistryProxyMixin as b4,TargetActionSupport as b5,ProxyMixin as b6,contentFor as b7,onerrorDefault as b8,Cache$1 as b9,ActionSupport as bA,ComponentLookup as bB,CoreView as bC,EventDispatcher as bD,MUTABLE_CELL as bE,states as bF,addChildView as bG,clearElementView as bH,clearViewElement as bI,constructStyleDeprecationMessage as bJ,getChildViews as bK,getElementView as bL,getRootViews as bM,getViewBoundingClientRect as bN,getViewBounds as bO,getViewClientRects as bP,getViewElement as bQ,getViewId as bR,isSimpleClick as bS,setElementView as bT,setViewElement as bU,index$2 as bV,namespace as bW,index$6 as bX,proxy$1 as bY,index$5 as bZ,index$e as b_,GUID_KEY as ba,ROOT as bb,canInvoke as bc,checkHasSuper as bd,makeDictionary as be,enumerableSymbol as bf,generateGuid as bg,getDebugName$1$1 as bh,getName as bi,intern$1 as bj,isInternalSymbol as bk,isObject as bl,isProxy as bm,lookupDescriptor as bn,observerListenerMetaFor as bo,setListeners as bp,setName as bq,setObservers as br,setProxy as bs,setWithMandatorySetter as bt,setupMandatorySetter as bu,symbol as bv,teardownMandatorySetter as bw,toString$3 as bx,uuid$1 as by,wrap$2 as bz,createCache as c,index$8 as c0,mutable as c1,index$7 as c2,core as c3,evented as c4,observable$1 as c5,promiseProxyMixin as c6,proxy as c7,index$9 as c8,index$4 as c9,_importSync20 as ca,version$2 as cb,index as cc,index$a as cd,index$b as ce,index$3 as cf,index$c as cg,index$d as ch,innerFrom as ci,Observable$1 as cj,createOperatorSubscriber as ck,nanoid$1 as cl,logger$1 as cm,map$1 as cn,share as co,firstValueFrom as cp,NAMESPACES_BY_ID as d,PROXY_CONTENT as e,_getProp as f,getValue$1 as g,_setProp as h,activateObserver as i,addArrayObserver as j,addListener as k,addNamespace as l,addObserver as m,alias as n,arrayContentDidChange as o,arrayContentWillChange as p,autoComputed as q,beginPropertyChanges as r,set$1 as s,changeProperties as t,computed as u,defineDecorator as v,defineProperty as w,defineValue as x,descriptorForDecorator as y,descriptorForProperty as z}; +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_3n=BigInt(3),_8n=BigInt(8),CURVE=Object.freeze({a:_0n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),divNearest=(e,t)=>(e+t/_2n)/t,endo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=CURVE,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=divNearest(o*e,t),l=divNearest(-n*e,t);let c=mod(e-a*r-l*i,t),u=mod(-a*n-l*o,t);const h=c>s,d=u>s;if(h&&(c=t-c),d&&(u=t-u),c>s||u>s)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:c,k2neg:d,k2:u}}},fieldLen=32,groupLen=32,compressedLen=fieldLen+1,uncompressedLen=2*fieldLen+1;function weierstrass(e){const{a:t,b:r}=CURVE,n=mod(e*e),i=mod(n*e);return mod(i+t*e+r)}const USE_ENDOMORPHISM=CURVE.a===_0n;function assertJacPoint(e){if(!(e instanceof JacobianPoint))throw new TypeError("JacobianPoint expected")}class JacobianPoint{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Point$1))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Point$1.ZERO)?JacobianPoint.ZERO:new JacobianPoint(e.x,e.y,_1n)}static toAffineBatch(e){const t=invertBatch(e.map(e=>e.z));return e.map((e,r)=>e.toAffine(t[r]))}static normalizeZ(e){return JacobianPoint.toAffineBatch(e).map(JacobianPoint.fromAffine)}equals(e){assertJacPoint(e);const{x:t,y:r,z:n}=this,{x:i,y:o,z:s}=e,a=mod(n*n),l=mod(s*s),c=mod(t*l),u=mod(i*a),h=mod(mod(r*s)*l),d=mod(mod(o*n)*a);return c===u&&h===d}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=mod(e*e),i=mod(t*t),o=mod(i*i),s=e+i,a=mod(_2n*(mod(s*s)-n-o)),l=mod(_3n*n),c=mod(l*l),u=mod(c-_2n*a),h=mod(l*(a-u)-_8n*o),d=mod(_2n*t*r);return new JacobianPoint(u,h,d)}add(e){assertJacPoint(e);const{x:t,y:r,z:n}=this,{x:i,y:o,z:s}=e;if(i===_0n||o===_0n)return this;if(t===_0n||r===_0n)return e;const a=mod(n*n),l=mod(s*s),c=mod(t*l),u=mod(i*a),h=mod(mod(r*s)*l),d=mod(mod(o*n)*a),p=mod(u-c),f=mod(d-h);if(p===_0n)return f===_0n?this.double():JacobianPoint.ZERO;const g=mod(p*p),m=mod(p*g),y=mod(c*g),b=mod(f*f-m-_2n*y),v=mod(f*(y-b)-h*m),_=mod(n*s*p);return new JacobianPoint(b,v,_)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=JacobianPoint.ZERO;if("bigint"==typeof e&&e===_0n)return t;let r=normalizeScalar(e);if(r===_1n)return this;if(!USE_ENDOMORPHISM){let e=t,n=this;for(;r>_0n;)r&_1n&&(e=e.add(n)),n=n.double(),r>>=_1n;return e}let{k1neg:n,k1:i,k2neg:o,k2:s}=endo.splitScalar(r),a=t,l=t,c=this;for(;i>_0n||s>_0n;)i&_1n&&(a=a.add(c)),s&_1n&&(l=l.add(c)),c=c.double(),i>>=_1n,s>>=_1n;return n&&(a=a.negate()),o&&(l=l.negate()),l=new JacobianPoint(mod(l.x*endo.beta),l.y,l.z),a.add(l)}precomputeWindow(e){const t=USE_ENDOMORPHISM?128/e+1:256/e+1,r=[];let n=this,i=n;for(let o=0;o>=u,r>a&&(r-=c,e+=_1n);const s=t,d=t+Math.abs(r)-1,p=h%2!=0,f=r<0;0===r?o=o.add(constTimeNegate(p,n[s])):i=i.add(constTimeNegate(f,n[d]))}return{p:i,f:o}}multiply(e,t){let r,n,i=normalizeScalar(e);if(USE_ENDOMORPHISM){const{k1neg:e,k1:o,k2neg:s,k2:a}=endo.splitScalar(i);let{p:l,f:c}=this.wNAF(o,t),{p:u,f:h}=this.wNAF(a,t);l=constTimeNegate(e,l),u=constTimeNegate(s,u),u=new JacobianPoint(mod(u.x*endo.beta),u.y,u.z),r=l.add(u),n=c.add(h)}else{const{p:e,f:o}=this.wNAF(i,t);r=e,n=o}return JacobianPoint.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,i=this.equals(JacobianPoint.ZERO);null==e&&(e=i?_8n:invert(n));const o=e,s=mod(o*o),a=mod(s*o),l=mod(t*s),c=mod(r*a),u=mod(n*o);if(i)return Point$1.ZERO;if(u!==_1n)throw new Error("invZ was invalid");return new Point$1(l,c)}}function constTimeNegate(e,t){const r=t.negate();return e?r:t}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n),JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);const pointPrecomputes=new WeakMap;let Point$1=class e{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,pointPrecomputes.delete(this)}hasEvenY(){return this.y%_2n===_0n}static fromCompressedHex(t){const r=32===t.length,n=bytesToNumber(r?t:t.subarray(1));if(!isValidFieldElement(n))throw new Error("Point is not on curve");let i=sqrtMod(weierstrass(n));const o=(i&_1n)===_1n;r?o&&(i=mod(-i)):!(1&~t[0])!==o&&(i=mod(-i));const s=new e(n,i);return s.assertValidity(),s}static fromUncompressedHex(t){const r=bytesToNumber(t.subarray(1,fieldLen+1)),n=bytesToNumber(t.subarray(fieldLen+1,2*fieldLen+1)),i=new e(r,n);return i.assertValidity(),i}static fromHex(e){const t=ensureBytes(e),r=t.length,n=t[0];if(r===fieldLen)return this.fromCompressedHex(t);if(r===compressedLen&&(2===n||3===n))return this.fromCompressedHex(t);if(r===uncompressedLen&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${r}`)}static fromPrivateKey(t){return e.BASE.multiply(normalizePrivateKey(t))}static fromSignature(t,r,n){const{r:i,s:o}=normalizeSignature(r);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");const s=truncateHash(ensureBytes(t)),{n:a}=CURVE,l=2===n||3===n?i+a:i,c=invert(l,a),u=mod(-s*c,a),h=mod(o*c,a),d=1&n?"03":"02",p=e.fromHex(d+numTo32bStr(l)),f=e.BASE.multiplyAndAddUnsafe(p,u,h);if(!f)throw new Error("Cannot recover signature: point at infinify");return f.assertValidity(),f}toRawBytes(e=!1){return hexToBytes(this.toHex(e))}toHex(e=!1){const t=numTo32bStr(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${numTo32bStr(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!isValidFieldElement(t)||!isValidFieldElement(r))throw new Error(e);const n=mod(r*r);if(mod(n-weierstrass(t))!==_0n)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new e(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(e){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return JacobianPoint.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(t,r,n){const i=JacobianPoint.fromAffine(this),o=r===_0n||r===_1n||this!==e.BASE?i.multiplyUnsafe(r):i.multiply(r),s=JacobianPoint.fromAffine(t).multiplyUnsafe(n),a=o.add(s);return a.equals(JacobianPoint.ZERO)?void 0:a.toAffine()}};function sliceDER(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function parseDERInt(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${bytesToHex(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:bytesToNumber(r),left:e.subarray(t+2)}}function parseDERSignature(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${bytesToHex(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=parseDERInt(e.subarray(2)),{data:n,left:i}=parseDERInt(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(i)}`);return{r:t,s:n}}Point$1.BASE=new Point$1(CURVE.Gx,CURVE.Gy),Point$1.ZERO=new Point$1(_0n,_0n);class Signature{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=isBytes(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?bytesToHex(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new Signature(hexToNumber(n.slice(0,64)),hexToNumber(n.slice(64,128)))}static fromDER(e){const t=isBytes(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r,s:n}=parseDERSignature(t?e:hexToBytes(e));return new Signature(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!isWithinCurveOrder(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=CURVE.n>>_1n;return this.s>e}normalizeS(){return this.hasHighS()?new Signature(this.r,mod(-this.s,CURVE.n)):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){const e=sliceDER(numberToHexUnpadded(this.s)),t=sliceDER(numberToHexUnpadded(this.r)),r=e.length/2,n=t.length/2,i=numberToHexUnpadded(r),o=numberToHexUnpadded(n);return`30${numberToHexUnpadded(n+r+4)}02${o}${t}02${i}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function isBytes(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function abytes(e){if(!isBytes(e))throw new Error("Uint8Array expected")}const hexes=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex(e){abytes(e);let t="";for(let r=0;r=asciis._0&&e<=asciis._9?e-asciis._0:e>=asciis.A&&e<=asciis.F?e-(asciis.A-10):e>=asciis.a&&e<=asciis.f?e-(asciis.a-10):void 0}function hexToBytes(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,o=0;i0)return BigInt(e);if("bigint"==typeof e&&isWithinCurveOrder(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(e,t=CURVE.P){const r=e%t;return r>=_0n?r:t+r}function pow2(e,t){const{P:r}=CURVE;let n=e;for(;t-- >_0n;)n*=n,n%=r;return n}function sqrtMod(e){const{P:t}=CURVE,r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),s=BigInt(44),a=BigInt(88),l=e*e*e%t,c=l*l*e%t,u=pow2(c,_3n)*c%t,h=pow2(u,_3n)*c%t,d=pow2(h,_2n)*l%t,p=pow2(d,n)*d%t,f=pow2(p,i)*p%t,g=pow2(f,s)*f%t,m=pow2(g,a)*g%t,y=pow2(m,s)*f%t,b=pow2(y,_3n)*c%t,v=pow2(b,o)*p%t,_=pow2(v,r)*l%t,E=pow2(_,_2n);if(E*E%t!==e)throw new Error("Cannot find square root");return E}function invert(e,t=CURVE.P){if(e===_0n||t<=_0n)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=mod(e,t),n=t,i=_0n,o=_1n;for(;r!==_0n;){const e=n%r,t=i-o*(n/r);n=r,r=e,i=o,o=t}if(n!==_1n)throw new Error("invert: does not exist");return mod(i,t)}function invertBatch(e,t=CURVE.P){const r=new Array(e.length),n=e.reduce((e,n,i)=>n===_0n?e:(r[i]=e,mod(e*n,t)),_1n),i=invert(n,t);return e.reduceRight((e,n,i)=>n===_0n?e:(r[i]=mod(e*r[i],t),mod(e*n,t)),i),r}function bits2int_2(e){const t=8*e.length-8*groupLen,r=bytesToNumber(e);return t>0?r>>BigInt(t):r}function truncateHash(e,t=!1){const r=bits2int_2(e);if(t)return r;const{n:n}=CURVE;return r>=n?r-n:r}function isWithinCurveOrder(e){return _0n0)t=BigInt(e);else if("string"==typeof e){if(e.length!==2*groupLen)throw new Error("Expected 32 bytes of private key");t=hexToNumber(e)}else{if(!isBytes(e))throw new TypeError("Expected valid private key");if(e.length!==groupLen)throw new Error("Expected 32 bytes of private key");t=bytesToNumber(e)}if(!isWithinCurveOrder(t))throw new Error("Expected private key: 0 < key < n");return t}function normalizeSignature(e){if(e instanceof Signature)return e.assertValidity(),e;try{return Signature.fromDER(e)}catch(error){return Signature.fromCompact(e)}}Point$1.BASE._setWindowSize(8);const sleep=e=>new Promise(t=>setTimeout(t,e));function xOnlyToXY(e){return Point$1.fromHex(e).toHex().substring(2)}const utf8Decoder=new TextDecoder("utf-8"),utf8Encoder=new TextEncoder;function base64Encode(e){return btoa(String.fromCharCode(...e))}function base64Decode(e){return new Uint8Array(atob(e).split("").map(e=>e.charCodeAt(0)))}class SerialPortSigner{log=logger$1.extend("SerialPortSigner");writer=null;pubkey;get isConnected(){return!!this.writer}verifyEvent=verifyEvent;nip04;constructor(){this.nip04={encrypt:this.nip04Encrypt.bind(this),decrypt:this.nip04Decrypt.bind(this)}}lastCommand=null;async callMethodOnDevice(e,t,r={}){if(!SerialPortSigner.SUPPORTED)throw new Error("Serial devices are not supported");if(this.writer||await this.connectToDevice(r),this.lastCommand)throw new Error("Previous command to device still pending!");const n=createDefer();return this.lastCommand=n,this.sendCommand(e,t),setTimeout(()=>{n.reject(new Error("Device timeout")),this.lastCommand===n&&(this.lastCommand=null)},6e3),this.lastCommand}async connectToDevice({onConnect:e,onDisconnect:t,onError:r,onDone:n}){let i,o=await window.navigator.serial.requestPort();await o.open({baudRate:9600}),await sleep(1e3),(async()=>{for(;o&&o.readable;){const e=new window.TextDecoderStream;o.readable.pipeTo(e.writable),i=e.readable.getReader();const t=this.readFromSerialPort(i);try{for(;;){const{value:e,done:r}=await t("\n");if(e){const{method:t,data:r}=this.parseResponse(e);if("/ping"===t&&this.log("Pong"),-1===SerialPortSigner.PUBLIC_METHODS.indexOf(t))continue;this.log("Received: ",t,r),this.lastCommand&&(this.lastCommand.resolve(r),this.lastCommand=null)}if(r)return this.lastCommand=null,this.writer=null,void(n&&n())}}catch(error){if(error instanceof Error)throw this.writer=null,r&&r(error),this.lastCommand&&(this.lastCommand.reject(error),this.lastCommand=null),error}}})();const s=new window.TextEncoderStream;s.readable.pipeTo(o.writable),this.writer=s.writable.getWriter(),await this.sendCommand(SerialPortSigner.METHOD_PING),await this.sendCommand(SerialPortSigner.METHOD_PING,[window.location.host]),e&&e(),o.addEventListener("disconnect",()=>{this.log("Disconnected"),this.lastCommand=null,this.writer=null,t&&t()})}async sendCommand(e,t=[]){if(!this.writer)return;this.log("Send command",e,t);const r=[e].concat(t).join(" ");await this.writer.write(r+"\n")}readFromSerialPort(e){let t,r=[];return async(n="\n")=>{if(r.length)return{value:r.shift().trim(),done:!1};const i=[];for(t&&(i.push(t),t=void 0);;){const{value:o,done:s}=await e.read();if(o){const e=o.split(n);if(e.length>1)return i.push(e.shift()),t=e.pop(),r=e,{value:i.join("").trim(),done:!1};i.push(o)}if(s)return{value:i.join("").trim(),done:!0}}}}parseResponse(e){const t=e.split(" ")[0];return{method:t,data:e.substring(t.length).trim()}}async nip04Encrypt(e,t){const r=hexToBytes$2(await this.callMethodOnDevice(SerialPortSigner.METHOD_SHARED_SECRET,[xOnlyToXY(e)]));let n=Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(16))),i=utf8Encoder.encode(t),o=await crypto.subtle.importKey("raw",r,{name:"AES-CBC"},!1,["encrypt"]),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:n},o,i);return`${base64Encode(new Uint8Array(s))}?iv=${base64Encode(new Uint8Array(n.buffer))}`}async nip04Decrypt(e,t){let[r,n]=t.split("?iv=");const i=hexToBytes$2(await this.callMethodOnDevice(SerialPortSigner.METHOD_SHARED_SECRET,[xOnlyToXY(e)]));let o=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["decrypt"]),s=base64Decode(r),a=base64Decode(n),l=await crypto.subtle.decrypt({name:"AES-CBC",iv:a},o,s);return utf8Decoder.decode(l)}async getPublicKey(){const e=await this.callMethodOnDevice(SerialPortSigner.METHOD_PUBLIC_KEY,[]);return this.pubkey=e,e}async restore(e){await this.callMethodOnDevice(SerialPortSigner.METHOD_RESTORE,[bytesToHex$2(e)])}async signEvent(e){const t=e.pubkey||this.pubkey;if(!t)throw new Error("Unknown signer pubkey");const r={...e,id:getEventHash({...e,pubkey:t})},n=await this.callMethodOnDevice(SerialPortSigner.METHOD_SIGN_MESSAGE,[r.id]),i={...r,sig:n,pubkey:t};if(!this.verifyEvent(i))throw new Error("Invalid signature");return i}ping(){this.sendCommand(SerialPortSigner.METHOD_PING,[window.location.host])}static SUPPORTED="navigator"in globalThis&&!!navigator.serial;static METHOD_PING="/ping";static METHOD_LOG="/log";static METHOD_SIGN_MESSAGE="/sign-message";static METHOD_SHARED_SECRET="/shared-secret";static METHOD_PUBLIC_KEY="/public-key";static METHOD_RESTORE="/restore";static PUBLIC_METHODS=[SerialPortSigner.METHOD_PUBLIC_KEY,SerialPortSigner.METHOD_SIGN_MESSAGE,SerialPortSigner.METHOD_SHARED_SECRET,SerialPortSigner.METHOD_RESTORE]}function isMobile(){return"undefined"!=typeof navigator&&/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)}const amdModule16=Object.freeze(Object.defineProperty({__proto__:null,isMobile:isMobile},Symbol.toStringTag,{value:"Module"})),STORAGE_KEY="marco:nostr_pubkey",STORAGE_KEY_TYPE="marco:nostr_signer_type",STORAGE_KEY_CONNECT_LOCAL_KEY="marco:nostr_connect_local_key",STORAGE_KEY_CONNECT_REMOTE_PUBKEY="marco:nostr_connect_remote_pubkey",STORAGE_KEY_CONNECT_RELAY="marco:nostr_connect_relay",DEFAULT_CONNECT_RELAY="wss://relay.nsec.app";class NostrAuthService extends Service{static{decorateFieldV2(this.prototype,"nostrRelay",[service])}#q=void initializeDeferredDecorator(this,"nostrRelay");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"pubkey",[tracked],function(){return null})}#W=void initializeDeferredDecorator(this,"pubkey");static{decorateFieldV2(this.prototype,"signerType",[tracked],function(){return null})}#K=void initializeDeferredDecorator(this,"signerType");static{decorateFieldV2(this.prototype,"connectStatus",[tracked],function(){return null})}#Y=void initializeDeferredDecorator(this,"connectStatus");static{decorateFieldV2(this.prototype,"connectUri",[tracked],function(){return null})}#Z=void initializeDeferredDecorator(this,"connectUri");_signerInstance=null;constructor(){super(...arguments),"undefined"!=typeof localStorage&&(localStorage.debug="applesauce:*");const e=localStorage.getItem(STORAGE_KEY),t=localStorage.getItem(STORAGE_KEY_TYPE);e&&(this.pubkey=e,this.signerType=t||"extension",this._verifyPubkey())}async _verifyPubkey(){if("extension"===this.signerType){if(void 0===window.nostr)return void this.disconnect();try{const e=new ExtensionSigner,t=await e.getPublicKey();t!==this.pubkey&&(this.pubkey=t,localStorage.setItem(STORAGE_KEY,this.pubkey)),this.nostrData.loadProfile(this.pubkey)}catch(e){console.warn("Failed to verify extension nostr pubkey, logging out",e),this.disconnect()}}else if("connect"===this.signerType)try{await this._initConnectSigner()}catch(e){console.warn("Failed to verify connect nostr pubkey, logging out",e),this.disconnect()}}get isMobile(){return isMobile()}get isConnected(){return!!this.pubkey&&("extension"!==this.signerType||void 0!==window.nostr)}get signer(){return this._signerInstance?this._signerInstance:"extension"===this.signerType&&void 0!==window.nostr?new ExtensionSigner:(this.signerType,null)}async connectWithExtension(){if(void 0===window.nostr)throw new Error("No NIP-07 Nostr extension found (e.g., Alby, nos2x).");try{return this._signerInstance=new ExtensionSigner,this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="extension",localStorage.setItem(STORAGE_KEY,this.pubkey),localStorage.setItem(STORAGE_KEY_TYPE,"extension"),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(error){throw console.error("Failed to get public key from extension:",error),error}}_getLocalSigner(){let e,t=localStorage.getItem(STORAGE_KEY_CONNECT_LOCAL_KEY);return t?e=PrivateKeySigner.fromKey(t):(e=new PrivateKeySigner,t=Array.from(e.key).map(e=>e.toString(16).padStart(2,"0")).join(""),localStorage.setItem(STORAGE_KEY_CONNECT_LOCAL_KEY,t)),e}async connectWithApp(){this.connectStatus="waiting";try{const t=this._getLocalSigner(),r=DEFAULT_CONNECT_RELAY;localStorage.setItem(STORAGE_KEY_CONNECT_RELAY,r),this.nostrRelay.pool.relay(r).eoseTimeout=18e4,this._signerInstance=new NostrConnectSigner({pool:this.nostrRelay.pool,relays:[r],signer:t,onAuth:async e=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${e}`)&&window.open(e,"_blank")}}),this.connectUri=this._signerInstance.getNostrConnectURI({name:"Marco",url:window.location.origin,description:"An unhosted maps application.",icons:[]}),this.isMobile&&(console.debug("Mobile detected, triggering deep link intent."),window.location.href=this.connectUri),console.debug("Opening signer connection to relay..."),await this._signerInstance.open(),console.debug("Signer connection opened successfully."),console.debug("Waiting for remote signer to ack via relay...");try{await this._signerInstance.waitForSigner(),console.debug("Remote signer ack received!")}catch(e){throw console.error("Error while waiting for remote signer ack:",e),e}return this.pubkey=await this._signerInstance.getPublicKey(),this.signerType="connect",this.connectStatus="connected",localStorage.setItem(STORAGE_KEY,this.pubkey),localStorage.setItem(STORAGE_KEY_TYPE,"connect"),localStorage.setItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY,this._signerInstance.remote),this.nostrData.loadProfile(this.pubkey),this.pubkey}catch(error){throw this.connectStatus=null,console.error("Failed to connect via Nostr Connect:",error),error}}async _initConnectSigner(){const e=localStorage.getItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY),t=localStorage.getItem(STORAGE_KEY_CONNECT_RELAY)||DEFAULT_CONNECT_RELAY;if(!e)throw new Error("Missing Nostr Connect remote pubkey.");const r=this._getLocalSigner();if(this.nostrRelay.pool.relay(t).eoseTimeout=18e4,this._signerInstance=new NostrConnectSigner({pool:this.nostrRelay.pool,relays:[t],signer:r,remote:e,onAuth:async e=>{confirm(`Your signer app requests authentication via a web page. Open it now?\n\nURL: ${e}`)&&window.open(e,"_blank")}}),await this._signerInstance.open(),await this._signerInstance.getPublicKey()!==this.pubkey)throw new Error("Remote signer pubkey mismatch");this.nostrData.loadProfile(this.pubkey)}async signEvent(e){if(!this.signer)throw new Error("Not connected or extension missing. Please connect Nostr again.");return await this.signer.signEvent(e)}async disconnect(){this.pubkey=null,this.nostrData?.loadProfile(null),this.signerType=null,this.connectStatus=null,this.connectUri=null,this._signerInstance&&"function"==typeof this._signerInstance.close&&await this._signerInstance.close(),this._signerInstance=null,localStorage.removeItem(STORAGE_KEY),localStorage.removeItem(STORAGE_KEY_TYPE),localStorage.removeItem(STORAGE_KEY_CONNECT_LOCAL_KEY),localStorage.removeItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY),localStorage.removeItem(STORAGE_KEY_CONNECT_RELAY)}}const amdModule7=Object.freeze(Object.defineProperty({__proto__:null,default:NostrAuthService},Symbol.toStringTag,{value:"Module"})),instanceOfAny=(e,t)=>t.some(t=>e instanceof t);let idbProxyableTypes,cursorAdvanceMethods;function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const transactionDoneMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;function promisifyRequest(e){const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(wrap$1(e.result)),n()},o=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",o)});return reverseTransformCache.set(t,e),t}function cacheDonePromiseForTransaction(e){if(transactionDoneMap.has(e))return;const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});transactionDoneMap.set(e,t)}let idbProxyTraps={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return transactionDoneMap.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap$1(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function replaceTraps(e){idbProxyTraps=e(idbProxyTraps)}function wrapFunction(e){return getCursorAdvanceMethods().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap$1(this.request)}:function(...t){return wrap$1(e.apply(unwrap(this),t))}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&cacheDonePromiseForTransaction(e),instanceOfAny(e,getIdbProxyableTypes())?new Proxy(e,idbProxyTraps):e)}function wrap$1(e){if(e instanceof IDBRequest)return promisifyRequest(e);if(transformCache.has(e))return transformCache.get(e);const t=transformCachableValue(e);return t!==e&&(transformCache.set(e,t),reverseTransformCache.set(t,e)),t}const unwrap=e=>reverseTransformCache.get(e);function openDB$1(e,t,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=wrap$1(s);return n&&s.addEventListener("upgradeneeded",e=>{n(wrap$1(s.result),e.oldVersion,e.newVersion,wrap$1(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(cachedMethods.get(t))return cachedMethods.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=writeMethods.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!readMethods.includes(r))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return n&&(s=s.index(t.shift())),(await Promise.all([s[r](...t),i&&o.done]))[0]};return cachedMethods.set(t,o),o}replaceTraps(e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)}));const advanceMethodProps=["continue","continuePrimaryKey","advance"],methodMap={},advanceResults=new WeakMap,ittrProxiedCursorToOriginalProxy=new WeakMap,cursorIteratorTraps={get(e,t){if(!advanceMethodProps.includes(t))return e[t];let r=methodMap[t];return r||(r=methodMap[t]=function(...e){advanceResults.set(this,ittrProxiedCursorToOriginalProxy.get(this)[t](...e))}),r}};async function*iterate$1(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,cursorIteratorTraps);for(ittrProxiedCursorToOriginalProxy.set(r,t),reverseTransformCache.set(r,unwrap(t));t;)yield r,t=await(advanceResults.get(r)||t.continue()),advanceResults.delete(r)}function isIteratorProp(e,t){return t===Symbol.asyncIterator&&instanceOfAny(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&instanceOfAny(e,[IDBIndex,IDBObjectStore])}function validateEvent(e){if("object"!=typeof e||null===e)return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!/^[a-f0-9]{64}$/.test(e.pubkey))return!1;if(!Array.isArray(e.tags))return!1;for(const t of e.tags){if(!Array.isArray(t))return!1;for(const e of t)if("string"!=typeof e)return!1}return!0}function isReplaceableKind(e){return 0===e||3===e||e>=1e4&&e<2e4}function isAddressableKind(e){return e>=3e4&&e<4e4}function isEphemeralKind(e){return e>=2e4&&e<3e4}replaceTraps(e=>({...e,get:(t,r,n)=>isIteratorProp(t,r)?iterate$1:e.get(t,r,n),has:(t,r)=>isIteratorProp(t,r)||e.has(t,r)}));const IndexableTagsSymbol=Symbol.for("indexable-tags");function getIndexableTags(e){let t=Reflect.get(e,IndexableTagsSymbol);if(!t){t=new Set;for(const r of e.tags)r.length>=2&&1===r[0].length&&t.add(r[0]+":"+r[1]);Reflect.set(e,IndexableTagsSymbol,t)}return t}function matchFilter(e,t){if(e.ids&&-1===e.ids.indexOf(t.id))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey))return!1;if(e.since&&t.created_ate.until)return!1;const r=getIndexableTags(t);for(const n in e)if("&"===n[0]){const t=n.slice(1),i=e[n];if(i&&i.length>0)for(const e of i)if(!r.has(t+":"+e))return!1}for(const n in e)if("#"===n[0]){const t=n.slice(1),i=e[n];if(i){const n=e[`&${t}`],o=n?i.filter(e=>!n.includes(e)):i;if(0===o.length)continue;if(!o.some(e=>r.has(t+":"+e)))return!1}}return!0}function matchFilters(e,t){for(let r=0;re.length>=2&&1===e[0].length&&INDEXABLE_TAGS.includes(e[0])).map(e=>e[0]+e[1])}function getEventUID(e){if(Reflect.has(e,EventUIDSymbol))return Reflect.get(e,EventUIDSymbol);let t;if(isReplaceableKind(e.kind)||isAddressableKind(e.kind)){const r=e.tags.find(e=>"d"===e[0])?.[1];t=e.kind+":"+e.pubkey+":"+(r??"")}else t=e.id;return Reflect.set(e,EventUIDSymbol,t),t}const NOSTR_IDB_NAME="nostr-idb",NOSTR_IDB_VERSION=3;async function openDB(e=NOSTR_IDB_NAME,t){return await openDB$1(e,NOSTR_IDB_VERSION,{...t,async upgrade(e,t,r,n,i){if(0===t){const t=e.createObjectStore("events");t.createIndex("id","event.id",{unique:!0}),t.createIndex("pubkey","event.pubkey"),t.createIndex("kind","event.kind"),t.createIndex("created_at","event.created_at"),t.createIndex("tags","tags",{multiEntry:!0}),e.createObjectStore("used",{keyPath:"uid"}).createIndex("date","date")}1===t&&(e.deleteObjectStore("events"),e.deleteObjectStore("used"),e.deleteObjectStore("seen")),t<=2&&await migrateReplaceableEventUIDs(n)}})}async function migrateReplaceableEventUIDs(e){const t=e.objectStore("events");let r=await t.openCursor();const n=[];for(;r;){const e=r.primaryKey,t=r.value,i=t.event;if(isReplaceableKind(i.kind)||isAddressableKind(i.kind)){const r=getEventUID(i);e!==r&&n.push({oldKey:e,newKey:r,value:t})}r=await r.continue()}for(const{oldKey:i,newKey:o,value:s}of n)await t.delete(i),await t.put(s,o)}function sortByDate(e,t){return t.created_at-e.created_at}function queryForPubkeys(e,t=[],r){const n=[],i=new Set;if(r)for(const l of t){const e=r.getPubkeyIndex(l);if(e){for(const t of e)i.add(t);n.push(l)}}if(n.length===t.length)return Promise.resolve(i);const o=e.transaction("events","readonly"),s=o.objectStore("events").index("pubkey"),a=t.filter(e=>!n.includes(e)).map(e=>s.getAllKeys(e).then(t=>((e,t)=>{for(const r of t)i.add(r);r&&r.setPubkeyIndex(e,new Set(t))})(e,t)));return o.commit(),Promise.all(a).then(()=>i)}function queryForTag(e,t,r,n){const i=[],o=new Set;if(n)for(const c of r){const e=n.getTagIndex(t+c);if(e){for(const t of e)o.add(t);i.push(c)}}if(i.length===r.length)return Promise.resolve(o);const s=e.transaction("events","readonly"),a=s.objectStore("events").index("tags"),l=r.map(e=>a.getAllKeys(t+e).then(r=>((e,r)=>{for(const t of r)o.add(t);n&&n.setTagIndex(t+e,new Set(r))})(e,r)));return s.commit(),Promise.all(l).then(()=>o)}function queryForTagAnd(e,t,r,n){if(0===r.length)return Promise.resolve(new Set);if(1===r.length)return queryForTag(e,t,r,n);const i=[],o=[];if(n)for(const c of r){const e=n.getTagIndex(t+c);e&&(o.push(e),i.push(c))}if(i.length===r.length)return Promise.resolve(intersectSets(o));const s=e.transaction("events","readonly"),a=s.objectStore("events").index("tags"),l=r.filter(e=>!i.includes(e)).map(e=>a.getAllKeys(t+e).then(r=>((e,r)=>{const i=new Set(r);o.push(i),n&&n.setTagIndex(t+e,i)})(e,r)));return s.commit(),Promise.all(l).then(()=>intersectSets(o))}function intersectSets(e){if(0===e.length)return new Set;const t=e.slice().sort((e,t)=>e.size-t.size);let r=t[0];for(let n=1;n!n.includes(e)).map(e=>s.getAllKeys(e).then(t=>((e,t)=>{for(const r of t)i.add(r);r&&r.setKindIndex(e,new Set(t))})(e,t)));return o.commit(),Promise.all(a).then(()=>i)}async function queryForTime(e,t,r){let n;if(void 0!==t&&void 0!==r)n=IDBKeyRange.bound(t,r);else if(void 0!==t)n=IDBKeyRange.lowerBound(t);else{if(void 0===r)throw new Error("Missing since or until");n=IDBKeyRange.upperBound(r)}return(await e.getAllKeysFromIndex("events","created_at",n)).reverse()}async function getIdsForFilter(e,t,r){if(t.search)return new Set;if(t.ids)return new Set(t.ids);let n=null;const i=e=>{const t=e instanceof Set?e:new Set(e);if(n)for(const r of n)t.has(r)||n.delete(r);else n=t;return n};let o=null;void 0!==t.since&&(o=await queryForTime(e,t.since,t.until),i(o));for(const s of INDEXABLE_TAGS){const n=t[`&${s}`],o=t[`#${s}`];if(n?.length&&i(await queryForTagAnd(e,s,n,r)),o?.length){const t=n?.length?o.filter(e=>!n.includes(e)):o;t.length>0&&i(await queryForTag(e,s,t,r))}}if(t.authors&&i(await queryForPubkeys(e,t.authors,r)),t.kinds&&i(await queryForKinds(e,t.kinds,r)),void 0===t.since&&void 0!==t.until&&(o=await queryForTime(e,t.since,t.until),i(o)),t.limit&&o){const e=new Set;for(const r of o){if(e.size>=t.limit)break;n.has(r)&&e.add(r)}return e}if(null===n)throw new Error("Empty filter");return n}async function getIdsForFilters(e,t,r){if(0===t.length)throw new Error("No Filters");let n=new Set;for(const i of t){const t=await getIdsForFilter(e,i,r);for(const e of t)n.add(e)}return n}async function loadEventsByUID(e,t,r,n){const i=[];let o=[];if(n)for(const d of t){const e=n.get(d);e?i.push(e):o.push(d)}else o=t;const s=e.transaction("events","readonly"),a=s.objectStore("events"),l=e=>e&&i.push(e.event),c=Array.from(o).map(e=>a.get(e).then(l));s.commit();const u=await Promise.all(c).then(()=>i.sort(sortByDate));let h=1/0;for(const d of r)d.limit&&d.limith&&(u.length=h),u}async function getEventsForFilters(e,t,r,n){const i=await getIdsForFilters(e,t,r);return await loadEventsByUID(e,Array.from(i),t,n)}async function countEventsForFilters(e,t,r){return(await getIdsForFilters(e,t,r)).size}const queryFilter=Object.freeze(Object.defineProperty({__proto__:null,countEventsForFilters:countEventsForFilters,getEventsForFilters:getEventsForFilters,getIdsForFilter:getIdsForFilter,getIdsForFilters:getIdsForFilters,queryForKinds:queryForKinds,queryForPubkeys:queryForPubkeys,queryForTag:queryForTag,queryForTagAnd:queryForTagAnd,queryForTime:queryForTime},Symbol.toStringTag,{value:"Module"}));function countEvents(e){return e.transaction("events","readonly").store.count()}async function addEvents(e,t){const r=(t=t.filter(e=>validateEvent(e))).filter(e=>isReplaceableKind(e.kind)||isAddressableKind(e.kind)),n={};if(r.length>0){const t=e.transaction("events","readonly"),i=r.map(e=>{const r=getEventUID(e);return t.store.get(r).then(e=>e&&(n[r]=e.event.created_at))});t.commit(),await Promise.all(i)}const i=e.transaction("events","readwrite");for(const o of t){const e=getEventUID(o);(!n[e]||o.created_at>n[e])&&i.objectStore("events").put({event:o,tags:getEventTags(o)},e)}await i.commit()}async function updateUsed(e,t){const r=e.transaction("used","readwrite"),n=Math.floor((new Date).valueOf()/1e3);for(const i of t)r.objectStore("used").put({uid:i,date:n});await r.commit()}const logger=debug("nostr-idb"),log$3=logger.extend("prune");async function pruneLastUsed(e,t){const r=await countEvents(e);if(r<=t)return;const n=r-t;if(n<=0)return;log$3(`Pruning database to ${t}`);const i=(await e.getAll("used")).sort((e,t)=>e.date-t.date),o=[];let s=n;for(const u of i){if(s<=0)break;const e=u.uid;o.push(e),s--}if(0===o.length)return;const a=e.transaction("events","readwrite"),l=e.transaction("used","readwrite"),c=[];for(const u of o)c.push(a.store.delete(u)),c.push(l.store.delete(u));a.commit(),l.commit(),await Promise.all(c),log$3(`Removed ${o.length} old events`)}async function deleteEvent(e,t,r){const n=e.transaction("events","readwrite"),i=n.objectStore("events"),o=await i.get(t);if(!o)return await n.commit(),!1;if(await i.delete(t),await n.commit(),r){const e=o.event;r.removeEvent(e)}return!0}async function deleteReplaceable(e,t,r,n,i){if(!isReplaceableKind(r)&&!isAddressableKind(r))throw new Error(`Kind ${r} is not replaceable`);const o=`${r}:${t}:${n??""}`;return await deleteEvent(e,o,i)}async function deleteByFilters(e,t,r){const n=await getIdsForFilters(e,t,r);return await deleteEventsByIds(e,Array.from(n),r)}async function deleteEventsByIds(e,t,r){if(0===t.length)return 0;const n=e.transaction("events","readwrite"),i=n.objectStore("events");let o=0;const s=[];for(const a of t){const e=await i.get(a);e&&(s.push(e.event),await i.delete(a),o++)}if(await n.commit(),r&&s.length>0)for(const a of s)r.removeEvent(a);return o}async function deleteAllEvents(e,t){const r=e.transaction("events","readwrite");await r.objectStore("events").clear(),await r.commit(),t&&t.clear()}const log$2=logger.extend("WriteQueue");class WriteQueue{db;queuedIds=new Set;eventQueue=[];lastUsedQueue=new Set;processEvents=null;constructor(e){this.db=e}addEvent(e){this.queuedIds.has(e.id)||(this.eventQueue.push(e),this.queuedIds.add(e.id),this.touch(e))}addEvents(e){const t=e.filter(e=>!this.queuedIds.has(e.id));0!==t.length&&(this.eventQueue.push(...t),this.touch(t))}touch(e){if(Array.isArray(e))for(const t of e)this.lastUsedQueue.add(getEventUID(t));else this.lastUsedQueue.add(getEventUID(e))}matchPending(e){return this.eventQueue.filter(t=>matchFilters(e,t))}async flush(e=1e3){if(this.eventQueue.length>0){let t=[];for(let r=0;r0&&log$2(`${this.eventQueue.length} left`)}this.lastUsedQueue.size>0&&(await updateUsed(this.db,this.lastUsedQueue),this.lastUsedQueue.clear())}clear(){this.eventQueue=[]}}const log$1=logger.extend("cache:indexes");class Index extends Set{type;key;constructor(e,t,r){super(e),this.type=t,this.key=r}}class IndexCache{kinds=new Map;pubkeys=new Map;tags=new Map;get count(){return this.kinds.size+this.pubkeys.size+this.tags.size}max=1e3;lastUsed=[];useIndex(e){const t=this.lastUsed.indexOf(e);-1!==t&&this.lastUsed.splice(t,t+1),this.lastUsed.push(e)}getKindIndex(e){const t=this.kinds.get(e);return t&&this.useIndex(t),t}setKindIndex(e,t){const r=new Index(t,"kind",e);this.kinds.set(e,r),this.useIndex(r),this.pruneIndexes()}getPubkeyIndex(e){const t=this.pubkeys.get(e);return t&&this.useIndex(t),t}setPubkeyIndex(e,t){const r=new Index(t,"pubkey",e);this.pubkeys.set(e,r),this.useIndex(r),this.pruneIndexes()}getTagIndex(e){const t=this.tags.get(e);return t&&this.useIndex(t),t}setTagIndex(e,t){const r=new Index(t,"tag",e);this.tags.set(e,r),this.useIndex(r),this.pruneIndexes()}addEventToIndexes(e){this.getKindIndex(e.kind)?.add(e.id),this.getPubkeyIndex(e.pubkey)?.add(e.id);const t=getEventTags(e);for(const r of t)this.getTagIndex(r)?.add(e.id)}removeEvent(e){this.getKindIndex(e.kind)?.delete(e.id),this.getPubkeyIndex(e.pubkey)?.delete(e.id);const t=getEventTags(e);for(const r of t)this.getTagIndex(r)?.delete(e.id)}clear(){this.kinds.clear(),this.pubkeys.clear(),this.tags.clear(),this.lastUsed=[]}pruneIndexes(){for(;this.lastUsed.length>0&&this.lastUsed.length>this.max;){const e=this.lastUsed.shift();if(!e)return;switch(log$1(`Forgetting ${e.type}:${e.key}`),e.type){case"kind":this.kinds.delete(e.key);break;case"pubkey":this.pubkeys.delete(e.key);break;case"tag":this.tags.delete(e.key)}}}}const scriptRel="modulepreload",assetsURL=function(e){return"/"+e},seen={},__vitePreload=function(e,t){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const e=document.querySelector("meta[property=csp-nonce]"),i=e?.nonce||e?.getAttribute("nonce");n=t.map(e=>{if((e=assetsURL(e))in seen)return;seen[e]=!0;const t=e.endsWith(".css"),r=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${r}`))return;const n=document.createElement("link");return n.rel=t?"stylesheet":scriptRel,t||(n.as="script"),n.crossOrigin="",n.href=e,i&&n.setAttribute("nonce",i),document.head.appendChild(n),t?new Promise((t,r)=>{n.addEventListener("load",t),n.addEventListener("error",()=>r(new Error(`Unable to preload CSS for ${e}`)))}):void 0}),r=Promise.all(n.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}var n;function i(e){const t=new Event("vite:preloadError",{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(const e of t||[])"rejected"===e.status&&i(e.reason);return e().catch(i)})};let nanoid=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),"");const defaultOptions={batchWrite:1e3,writeInterval:100,cacheIndexes:1e3,pruneInterval:6e4,maxEvents:1e4},log=logger.extend("nostridb");class NostrIDB{options;running=!1;writeInterval;pruneInterval;eventMap=new Map;writeQueue=null;indexCache;db=null;baseEoseTimeout=4400;subscriptions=new Map;constructor(e,t={}){this.options={...defaultOptions,...t},e&&(this.db=e,this.writeQueue=new WriteQueue(e)),this.indexCache=new IndexCache,this.indexCache.max=this.options.cacheIndexes,this.start()}async getDb(){return this.db||(this.db=await openDB()),this.db}async getWriteQueue(){if(this.writeQueue)return this.writeQueue;const e=await this.getDb();return this.writeQueue=new WriteQueue(e),this.writeQueue}async flush(){const e=await this.getWriteQueue();await e.flush(),this.writeInterval=setTimeout(this.flush.bind(this),this.options.writeInterval)}async start(){if(this.running)return;log("Starting"),this.running=!0;const e=await this.getDb();await this.flush(),this.pruneInterval=setInterval(()=>{pruneLastUsed(e,this.options.maxEvents)},this.options.pruneInterval)}async stop(){this.running&&(this.writeInterval&&(clearTimeout(this.writeInterval),this.writeInterval=void 0),this.pruneInterval&&(clearInterval(this.pruneInterval),this.pruneInterval=void 0),this.running=!1,log("Stopped"))}async add(e){isEphemeralKind(e.kind)||((await this.getWriteQueue()).addEvent(e),this.indexCache.addEventToIndexes(e));const t=getEventUID(e);if(!this.eventMap.has(t)){isEphemeralKind(e.kind)||this.eventMap.set(t,e);for(const[t,r]of this.subscriptions)r.event&&matchFilters(r.filters,e)&&r.event(e)}return!0}async event(e){const t=await this.getDb(),r=await t.get("events",e);return r?.event}async replaceable(e,t,r){return this.event([e,t,r??""].join(":"))}async count(e){const t=Array.isArray(e)?e:[e],r=await this.getDb();return await countEventsForFilters(r,t)}async query(e){const t=Array.isArray(e)?e:[e],r=await this.getDb(),n=(await this.getWriteQueue()).matchPending(t),i=await getEventsForFilters(r,t,this.indexCache,this.eventMap);this.addToEventMaps(i);const o=new Set(n.map(e=>e.id));return n.length>0?[...i.filter(e=>!o.has(e.id)),...n].sort(sortByDate):i}async*subscribe(e){const t=Array.isArray(e)?e:[e],r=[],n=new Set;let i=null,o=!1;const s=this.subscribeInternal(t,{event:e=>{if(!n.has(e.id)&&(n.add(e.id),r.push(e),i)){const e=i;i=null,e()}},complete:()=>{if(o=!0,i){const e=i;i=null,e()}}});try{for(;;){for(;r.length>0;)yield r.shift();if(o)break;await new Promise(e=>{i=e})}}finally{s.close()}}async supports(){return[]}async deleteEvent(e){const t=await this.getDb(),r=await deleteEvent(t,e,this.indexCache);return this.eventMap.delete(e),r}async deleteReplaceable(e,t,r){const n=await this.getDb(),i=await deleteReplaceable(n,e,t,r,this.indexCache);if(i){const n=`${t}:${e}:${r??""}`;this.eventMap.delete(n)}return i}async deleteByFilters(e){const t=Array.isArray(e)?e:[e],r=await this.getDb(),n=await this.getEventIdsForFilters(t),i=await deleteByFilters(r,t,this.indexCache);if(i>0)for(const o of n)this.eventMap.delete(o);return i}async deleteAllEvents(){const e=await this.getDb();await deleteAllEvents(e,this.indexCache),this.eventMap.clear()}async getEventIdsForFilters(e){const t=await this.getDb(),{getIdsForFilters:r}=await __vitePreload(async()=>{const{getIdsForFilters:e}=await Promise.resolve().then(()=>queryFilter);return{getIdsForFilters:e}},void 0),n=await r(t,e,this.indexCache);return Array.from(n)}addToEventMaps(e){for(const t of e)this.eventMap.set(getEventUID(t),t)}subscribeInternal(e,t){const r=nanoid(),n={id:r,filters:e,closed:!1,close:()=>this.unsubscribe(r),...t};return this.subscriptions.set(r,n),this.executeSubscription(n),n}async executeSubscription(e){const t=(new Date).valueOf();log(`Running ${e.id}`,e.filters);const r=(await this.getWriteQueue()).matchPending(e.filters);return new Promise(async n=>{const i=await this.getDb(),o=setTimeout(()=>{e.eose&&!e.closed&&e.eose(),n()},this.baseEoseTimeout);getEventsForFilters(i,e.filters,this.indexCache,this.eventMap).then(i=>{if(clearTimeout(o),this.addToEventMaps(i),e.event&&!e.closed){const n=new Set(r.map(e=>e.id)),o=r.length>0?[...i.filter(e=>!n.has(e.id)),...r].sort(sortByDate):i;for(const t of o)try{e.event(t)}catch(error){log("event handler failed with error",error)}const s=(new Date).valueOf()-t;log(`Finished ${e.id} took ${s}ms and got ${o.length} events`)}e.eose&&!e.closed&&e.eose(),n()})})}unsubscribe(e){const t=this.subscriptions.get(e);t&&(log(`Closing ${e}`),t.closed=!0,t.complete?.(),this.subscriptions.delete(e))}}function normalizeRelayUrl(e){if(!e)return"";let t=e.trim().toLowerCase();if(!t)return"";for(t.startsWith("ws://")||t.startsWith("wss://")||(t="wss://"+t);t.endsWith("/");)t=t.slice(0,-1);return t}function parsePlacePhotos(e){if(!e||0===e.length)return[];const t=[...e].sort((e,t)=>e.created_at-t.created_at),r=[];for(const i of t){const e=i.tags.filter(e=>"imeta"===e[0]);for(const t of e){let e=null,n=null,o=null,s=!1,a=16/9;for(const r of t.slice(1))if(r.startsWith("url "))e=r.substring(4);else if(r.startsWith("thumb "))n=r.substring(6);else if(r.startsWith("blurhash "))o=r.substring(9);else if(r.startsWith("dim ")){const e=r.substring(4),[t,n]=e.split("x").map(Number);t&&n&&(a=t/n,t>n&&(s=!0))}e&&r.push({eventId:i.id,pubkey:i.pubkey,createdAt:i.created_at,url:e,thumbUrl:n,blurhash:o,isLandscape:s,aspectRatio:a})}}if(0===r.length)return[];const n=r.findIndex(e=>e.isLandscape);if(n>0){const[e]=r.splice(n,1);r.unshift(e)}return r}const amdModule21=Object.freeze(Object.defineProperty({__proto__:null,normalizeRelayUrl:normalizeRelayUrl,parsePlacePhotos:parsePlacePhotos},Symbol.toStringTag,{value:"Module"})),base32="0123456789bcdefghjkmnpqrstuvwxyz";class Geohash{static encode(e,t,r){if(void 0===r){for(let r=1;r<=12;r++){const n=Geohash.encode(e,t,r),i=Geohash.decode(n);if(i.lat==e&&i.lon==t)return n}r=12}if(e=Number(e),t=Number(t),r=Number(r),isNaN(e)||isNaN(t)||isNaN(r))throw new Error("Invalid geohash");let n=0,i=0,o=!0,s="",a=-90,l=90,c=-180,u=180;for(;s.length=e?(n=2*n+1,c=e):(n*=2,u=e)}else{const t=(a+l)/2;e>=t?(n=2*n+1,a=t):(n*=2,l=t)}o=!o,5==++i&&(s+=base32.charAt(n),i=0,n=0)}return s}static decode(e){const t=Geohash.bounds(e),r=t.sw.lat,n=t.sw.lon,i=t.ne.lat,o=t.ne.lon;let s=(r+i)/2,a=(n+o)/2;return s=s.toFixed(Math.floor(2-Math.log(i-r)/Math.LN10)),a=a.toFixed(Math.floor(2-Math.log(o-n)/Math.LN10)),{lat:Number(s),lon:Number(a)}}static bounds(e){if(0==e.length)throw new Error("Invalid geohash");e=e.toLowerCase();let t=!0,r=-90,n=90,i=-180,o=180;for(let s=0;s=0;e--){const s=l>>e&1;if(t){const e=(i+o)/2;1==s?i=e:o=e}else{const e=(r+n)/2;1==s?r=e:n=e}t=!t}}return{sw:{lat:r,lon:i},ne:{lat:n,lon:o}}}static adjacent(e,t){if(e=e.toLowerCase(),t=t.toLowerCase(),0==e.length)throw new Error("Invalid geohash");if(-1=="nsew".indexOf(t))throw new Error("Invalid direction");const r=e.slice(-1);let n=e.slice(0,-1);const i=e.length%2;return-1!={n:["prxz","bcfguvyz"],s:["028b","0145hjnp"],e:["bcfguvyz","prxz"],w:["0145hjnp","028b"]}[t][i].indexOf(r)&&""!=n&&(n=Geohash.adjacent(n,t)),n+base32.charAt({n:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],s:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],e:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],w:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]}[t][i].indexOf(r))}static neighbours(e){return{n:Geohash.adjacent(e,"n"),ne:Geohash.adjacent(Geohash.adjacent(e,"n"),"e"),e:Geohash.adjacent(e,"e"),se:Geohash.adjacent(Geohash.adjacent(e,"s"),"e"),s:Geohash.adjacent(e,"s"),sw:Geohash.adjacent(Geohash.adjacent(e,"s"),"w"),w:Geohash.adjacent(e,"w"),nw:Geohash.adjacent(Geohash.adjacent(e,"n"),"w")}}}function getGeohashPrefixesInBbox(e){const{minLat:t,minLon:r,maxLat:n,maxLon:i}=e,o=new Set;if(Math.abs(n-t)>20||Math.abs(i-r)>20)return console.warn("BBox too large for 4-char geohash scanning, aborting fine scan."),[];for(let a=t;a<=n+.1;a+=.1)for(let e=r;e<=i+.1;e+=.1){const t=Math.min(a,n),r=Math.min(e,i);try{const e=Geohash.encode(t,r,4);o.add(e)}catch(s){}}try{o.add(Geohash.encode(t,r,4))}catch(s){}try{o.add(Geohash.encode(n,i,4))}catch(s){}try{o.add(Geohash.encode(t,i,4))}catch(s){}try{o.add(Geohash.encode(n,r,4))}catch(s){}return Array.from(o)}const amdModule19=Object.freeze(Object.defineProperty({__proto__:null,getGeohashPrefixesInBbox:getGeohashPrefixesInBbox},Symbol.toStringTag,{value:"Module"})),DIRECTORY_RELAYS=["wss://purplepag.es","wss://relay.damus.io","wss://nos.lol"],DEFAULT_READ_RELAYS=["wss://nostr.kosmos.org"],DEFAULT_WRITE_RELAYS=[];class NostrDataService extends Service{static{decorateFieldV2(this.prototype,"nostrRelay",[service])}#q=void initializeDeferredDecorator(this,"nostrRelay");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");store=new EventStore;static{decorateFieldV2(this.prototype,"profile",[tracked],function(){return null})}#X=void initializeDeferredDecorator(this,"profile");static{decorateFieldV2(this.prototype,"mailboxes",[tracked],function(){return null})}#J=void initializeDeferredDecorator(this,"mailboxes");static{decorateFieldV2(this.prototype,"blossomServers",[tracked],function(){return[]})}#Q=void initializeDeferredDecorator(this,"blossomServers");static{decorateFieldV2(this.prototype,"placePhotos",[tracked],function(){return[]})}#ee=void initializeDeferredDecorator(this,"placePhotos");_profileSub=null;_mailboxesSub=null;_blossomSub=null;_photosSub=null;_requestSub=null;_cachePromise=null;loadedGeohashPrefixes=new Set;constructor(){super(...arguments),this._cachePromise=openDB("applesauce-events").then(async e=>{this.cache=new NostrIDB(e,{cacheIndexes:1e3,maxEvents:1e4}),await this.cache.start(),this._stopPersisting=persistEventsToCache(this.store,async e=>{const t=e.filter(e=>0===e.kind||10002===e.kind||10063===e.kind||360===e.kind);t.length>0&&await Promise.all(t.map(e=>this.cache.add(e)))},{batchTime:1e3,maxBatchSize:100})}),this.nostrRelay.pool.relays$.subscribe(()=>{})}get defaultReadRelays(){const e=(this.mailboxes?.inboxes||[]).map(normalizeRelayUrl).filter(Boolean),t=DEFAULT_READ_RELAYS.map(normalizeRelayUrl).filter(Boolean);return Array.from(new Set([...t,...e]))}get defaultWriteRelays(){const e=(this.mailboxes?.outboxes||[]).map(normalizeRelayUrl).filter(Boolean),t=DEFAULT_WRITE_RELAYS.map(normalizeRelayUrl).filter(Boolean);return Array.from(new Set([...t,...e]))}get activeReadRelays(){return this.settings.nostrReadRelays?Array.from(new Set(this.settings.nostrReadRelays.map(normalizeRelayUrl).filter(Boolean))):this.defaultReadRelays}get activeWriteRelays(){return this.settings.nostrWriteRelays?Array.from(new Set(this.settings.nostrWriteRelays.map(normalizeRelayUrl).filter(Boolean))):this.defaultWriteRelays}async loadPlacesInBounds(e){const t=getGeohashPrefixesInBbox(e).filter(e=>!this.loadedGeohashPrefixes.has(e));if(0!==t.length){console.debug("[nostr-data] Loading place photos for prefixes:",t);try{await this._cachePromise;const e=await this.cache.query([{kinds:[360],"#g":t}]);if(e&&e.length>0)for(const t of e)this.store.add(t)}catch(r){console.warn("[nostr-data] Failed to read photos from local Nostr IDB cache",r)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#g":t}]).subscribe({next:e=>{this.store.add(e)},error:e=>{console.error("[nostr-data] Error fetching place photos by geohash:",e)}});for(const e of t)this.loadedGeohashPrefixes.add(e)}}async loadPhotosForPlace(e){if(this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null),this.placePhotos=[],!e||!e.osmId||!e.osmType)return;const t=`osm:${e.osmType}:${e.osmId}`;this._photosSub=this.store.timeline([{kinds:[360],"#i":[t]}]).subscribe(e=>{this.placePhotos=e});try{await this._cachePromise;const e=await this.cache.query([{kinds:[360],"#i":[t]}]);if(e&&e.length>0)for(const t of e)this.store.add(t)}catch(r){console.warn("[nostr-data] Failed to read photos for place from local Nostr IDB cache",r)}this.nostrRelay.pool.request(this.activeReadRelays,[{kinds:[360],"#i":[t]}]).subscribe({next:e=>{this.store.add(e)},error:e=>{console.error("[nostr-data] Error fetching place photos for place:",e)}})}async loadProfile(e){if(!e)return;this.profile=null,this.mailboxes=null,this.blossomServers=[],this._cleanupSubscriptions(),this._profileSub=this.store.model(ProfileModel,e).subscribe(e=>{this.profile=e}),this._mailboxesSub=this.store.model(MailboxesModel,e).subscribe(e=>{this.mailboxes=e}),this._blossomSub=this.store.replaceable(10063,e).subscribe(e=>{e&&e.tags?this.blossomServers=e.tags.filter(e=>"server"===e[0]&&e[1]).map(e=>e[1]):this.blossomServers=[]});try{await this._cachePromise;const t=await this.cache.query([{authors:[e],kinds:[0,10002,10063]}]);if(t&&t.length>0)for(const e of t)this.store.add(e)}catch(r){console.warn("Failed to read from local Nostr IDB cache",r)}const t=Array.from(new Set([...DIRECTORY_RELAYS,...this.activeWriteRelays]));this._requestSub=this.nostrRelay.pool.request(t,[{authors:[e],kinds:[0,10002,10063]}]).subscribe({next:e=>{this.store.add(e)},error:e=>{console.error("Error fetching profile events:",e)}})}get userDisplayName(){if(this.profile){if(this.profile.nip05)return this.profile.nip05;if(this.profile.displayName||this.profile.display_name)return this.profile.displayName||this.profile.display_name;if(this.profile.name)return this.profile.name}if(this.nostrAuth.pubkey)try{const e=npubEncode(this.nostrAuth.pubkey);return`${e.slice(0,9)}...${e.slice(-4)}`}catch{return this.nostrAuth.pubkey}return"Not connected"}async clearCache(){await this._cachePromise,this.cache&&await this.cache.deleteAllEvents()}_cleanupSubscriptions(){this._requestSub&&(this._requestSub.unsubscribe(),this._requestSub=null),this._profileSub&&(this._profileSub.unsubscribe(),this._profileSub=null),this._mailboxesSub&&(this._mailboxesSub.unsubscribe(),this._mailboxesSub=null),this._blossomSub&&(this._blossomSub.unsubscribe(),this._blossomSub=null),this._photosSub&&(this._photosSub.unsubscribe(),this._photosSub=null)}willDestroy(){super.willDestroy(...arguments),this._cleanupSubscriptions(),this._stopPersisting&&this._stopPersisting(),this.cache&&this.cache.stop()}}const amdModule8=Object.freeze(Object.defineProperty({__proto__:null,default:NostrDataService},Symbol.toStringTag,{value:"Module"}));function completeOnEose(e){return takeWhile(e=>"EOSE"!==e,e)}function onlyEvents(){return e=>e.pipe(filter$1(e=>"EOSE"!==e))}function reverseSwitchMap(e){return operate((t,r)=>{let n=null,i=0,o=!1;const s=()=>{o&&!n&&r.complete()};t.subscribe(createOperatorSubscriber(r,t=>{const o=i++,a=n,l=n=createOperatorSubscriber(r,e=>r.next(e),()=>{n!==l&&null!==n||(n=null,s())});from(e(t,o)).subscribe(n),a?.unsubscribe()},()=>{o=!0,s()}))})}function errorToPublishResponse(e){return catchError(t=>of({ok:!1,from:e.url,message:t?.message||"Unknown error"}))}class RelayGroup{relays$=new BehaviorSubject([]);status$;get relays(){if(this.relays$ instanceof BehaviorSubject)return this.relays$.value;throw new Error("This group was created with an observable, relays are not available")}constructor(e){this.relays$=Array.isArray(e)?new BehaviorSubject(e):e,this.status$=this.relays$.pipe(switchMap(e=>0===e.length?of({}):merge$1(...e.map(e=>e.status$)).pipe(scan((e,t)=>({...e,[t.url]:t}),{}),startWith({}))),shareReplay(1))}get controlled(){return this.relays$ instanceof BehaviorSubject==0}has(e){if(this.controlled)throw new Error("This group was created with an observable, relays are not available");return"string"==typeof e?this.relays.some(t=>t.url===e):this.relays.includes(e)}add(e){this.has(e)||this.relays$.next([...this.relays,e])}remove(e){this.has(e)&&this.relays$.next(this.relays.filter(t=>t!==e))}internalSubscription(e,t=identity$1){const r=new WeakMap,n=this.relays$.pipe(reverseSwitchMap(t=>{const n=[];for(const i of t){if(r.has(i)){n.push(r.get(i));continue}const t=e(i).pipe(catchError(()=>of("EOSE")),map$1(e=>[i,e]));n.push(t),r.set(i,t)}return merge$1(...n)}),share());return merge$1(n.pipe(map$1(([e,t])=>t),onlyEvents(),t),this.relays$.pipe(switchMap(e=>n.pipe(filter$1(([e,t])=>"EOSE"===t),scan((e,[t])=>[...e,t],[]),takeWhile(t=>e.some(e=>!t.includes(e))),ignoreElements(),endWith("EOSE"))))).pipe(share())}internalPublish(e){const t=new WeakMap;return this.relays$.pipe(take(1),switchMap(r=>{const n=[];for(const i of r){if(t.has(i)){n.push(t.get(i));continue}const r=e(i).pipe(errorToPublishResponse(i));n.push(r),t.set(i,r)}return merge$1(...n)}))}req(e,t=nanoid$1(),r){return this.internalSubscription(r=>r.req(e,t),r?.eventStore?filterDuplicateEvents(r?.eventStore):identity$1)}event(e){return this.internalPublish(t=>t.event(e)).pipe(share())}async negentropy(e,t,r,n){const i=(await Promise.all(this.relays.map(async e=>[e,await e.getSupported()]))).filter(([e,t])=>t?.includes(77)).map(([e])=>e);if(0===i.length)throw new Error("No relays support NIP-77 negentropy sync");if(!n?.parallel)throw new Error("Negentropy sync must be parallel (for now)");return await Promise.allSettled(i.map(i=>i.negentropy(e,t,r,n))),!0}publish(e,t){return lastValueFrom(this.internalPublish(r=>from(r.publish(e,t))).pipe(toArray(),defaultIfEmpty([])))}request(e,t){return this.internalSubscription(r=>r.request(e,t).pipe(endWith("EOSE")),null==t?.eventStore?identity$1:filterDuplicateEvents(t?.eventStore??new EventMemory)).pipe(completeOnEose())}subscription(e,t){return this.internalSubscription(r=>r.subscription(e,t),null==t?.eventStore?identity$1:filterDuplicateEvents(t?.eventStore??new EventMemory))}count(e,t=nanoid$1()){return this.relays$.pipe(switchMap(r=>combineLatest(Object.fromEntries(r.map(r=>[r.url,r.count(e,t)])))),share())}sync(e,t,r){return defer(async()=>{const e=(await Promise.all(this.relays.map(async e=>[e,await e.getSupported()]))).filter(([e,t])=>t?.includes(77)).map(([e])=>e);if(0===e.length)throw new Error("No relays support NIP-77 negentropy sync");return e}).pipe(switchMap(n=>merge$1(...n.map(n=>n.sync(e,t,r)))),share())}}var ClientAuth=22242;function makeAuthEvent(e,t){return{kind:ClientAuth,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var DEFAULT_WEBSOCKET_CONFIG={url:"",deserializer:function(e){return JSON.parse(e.data)},serializer:function(e){return JSON.stringify(e)}},WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT="WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }",WebSocketSubject=function(e){function t(t,r){var n=e.call(this)||this;if(n._socket=null,t instanceof Observable$1)n.destination=r,n.source=t;else{var i=n._config=__assign({},DEFAULT_WEBSOCKET_CONFIG);if(n._output=new Subject,"string"==typeof t)i.url=t;else for(var o in t)t.hasOwnProperty(o)&&(i[o]=t[o]);if(!i.WebSocketCtor&&WebSocket)i.WebSocketCtor=WebSocket;else if(!i.WebSocketCtor)throw new Error("no WebSocket constructor can be found");n.destination=new ReplaySubject}return n}return __extends(t,e),t.prototype.lift=function(e){var r=new t(this._config,this.destination);return r.operator=e,r.source=this,r},t.prototype._resetState=function(){this._socket=null,this.source||(this.destination=new ReplaySubject),this._output=new Subject},t.prototype.multiplex=function(e,t,r){var n=this;return new Observable$1(function(i){try{n.next(e())}catch(s){i.error(s)}var o=n.subscribe({next:function(e){try{r(e)&&i.next(e)}catch(s){i.error(s)}},error:function(e){return i.error(e)},complete:function(){return i.complete()}});return function(){try{n.next(t())}catch(s){i.error(s)}o.unsubscribe()}})},t.prototype._connectSocket=function(){var e=this,t=this._config,r=t.WebSocketCtor,n=t.protocol,i=t.url,o=t.binaryType,s=this._output,a=null;try{a=n?new r(i,n):new r(i),this._socket=a,o&&(this._socket.binaryType=o)}catch(c){return void s.error(c)}var l=new Subscription(function(){e._socket=null,a&&1===a.readyState&&a.close()});a.onopen=function(t){if(!e._socket)return a.close(),void e._resetState();var r=e._config.openObserver;r&&r.next(t);var n=e.destination;e.destination=Subscriber.create(function(t){if(1===a.readyState)try{var r=e._config.serializer;a.send(r(t))}catch(c){e.destination.error(c)}},function(t){var r=e._config.closingObserver;r&&r.next(void 0),t&&t.code?a.close(t.code,t.reason):s.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT)),e._resetState()},function(){var t=e._config.closingObserver;t&&t.next(void 0),a.close(),e._resetState()}),n&&n instanceof ReplaySubject&&l.add(n.subscribe(e.destination))},a.onerror=function(t){e._resetState(),s.error(t)},a.onclose=function(t){a===e._socket&&e._resetState();var r=e._config.closeObserver;r&&r.next(t),t.wasClean?s.complete():s.error(t)},a.onmessage=function(t){try{var r=e._config.deserializer;s.next(r(t))}catch(n){s.error(n)}}},t.prototype._subscribe=function(e){var t=this,r=this.source;return r?r.subscribe(e):(this._socket||this._connectSocket(),this._output.subscribe(e),e.add(function(){var e=t._socket;0===t._output.observers.length&&(!e||1!==e.readyState&&0!==e.readyState||e.close(),t._resetState())}),e)},t.prototype.unsubscribe=function(){var t=this._socket;!t||1!==t.readyState&&0!==t.readyState||t.close(),this._resetState(),e.prototype.unsubscribe.call(this)},t}(AnonymousSubject);function webSocket(e){return new WebSocketSubject(e)}function markFromRelay(e){return t=>t.pipe(tap$1(t=>{"string"!=typeof t&&addSeenRelay(t,e)}))}const AUTH_REQUIRED_PREFIX="auth-required:",DEFAULT_RETRY_CONFIG={count:3,delay:1e3,resetOnSuccess:!0};var SyncDirection;!function(e){e[e.RECEIVE=1]="RECEIVE",e[e.SEND=2]="SEND",e[e.BOTH=3]="BOTH"}(SyncDirection||(SyncDirection={}));class ReqCloseError extends Error{}const PING_FILTER={ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0};class Relay{url;log=logger$1.extend("Relay");socket;_ready$=new BehaviorSubject(!0);ready$=this._ready$.asObservable();reconnectTimer;attempts$=new BehaviorSubject(0);connected$=new BehaviorSubject(!1);challenge$=new BehaviorSubject(null);authenticated$;authenticatedAs$;authentication$=new BehaviorSubject(null);authenticationResponse$=new BehaviorSubject(null);notices$=new BehaviorSubject([]);error$=new BehaviorSubject(null);message$;notice$;lastMessageReceivedAt=0;_lastMessageAt$=new BehaviorSubject(0);lastMessageAt$=this._lastMessageAt$.asObservable();status$;information$;_nip11=null;icon$;limitations$;supported$;open$=new Subject;close$=new Subject;closing$=new Subject;reqs$=new BehaviorSubject({});get ready(){return this._ready$.value}get connected(){return this.connected$.value}get challenge(){return this.challenge$.value}get notices(){return this.notices$.value}get authenticated(){return!0===this.authenticationResponse?.ok}get authentication(){return this.authentication$.value}get authenticatedAs(){return this.authenticated?this.authentication?.pubkey??null:null}get authenticationResponse(){return this.authenticationResponse$.value}get information(){return this._nip11}get lastMessageAt(){return this._lastMessageAt$.value}get reqs(){return this.reqs$.value}eoseTimeout=1e4;eventTimeout=1e4;publishTimeout=3e4;keepAlive=3e4;enablePing=!1;pingFrequency=29e3;pingTimeout=2e4;subscriptionReconnect;requestReconnect;publishRetry;onUnresponsive;receivedAuthRequiredForReq=new BehaviorSubject(!1);receivedAuthRequiredForEvent=new BehaviorSubject(!1);authRequiredForRead$;authRequiredForPublish$;resetState(){null!==this.challenge$.value&&this.challenge$.next(null),this.authenticationResponse$.value&&this.authenticationResponse$.next(null),null!==this.authentication$.value&&this.authentication$.next(null),this.notices$.value.length>0&&this.notices$.next([]),this.receivedAuthRequiredForReq.value&&this.receivedAuthRequiredForReq.next(!1),this.receivedAuthRequiredForEvent.value&&this.receivedAuthRequiredForEvent.next(!1)}watchTower;constructor(e,t){this.url=e,this.log=this.log.extend(e),void 0!==t?.eoseTimeout&&(this.eoseTimeout=t.eoseTimeout),void 0!==t?.eventTimeout&&(this.eventTimeout=t.eventTimeout),void 0!==t?.publishTimeout&&(this.publishTimeout=t.publishTimeout),void 0!==t?.keepAlive&&(this.keepAlive=t.keepAlive),void 0!==t?.enablePing&&(this.enablePing=t.enablePing),void 0!==t?.pingFrequency&&(this.pingFrequency=t.pingFrequency),void 0!==t?.pingTimeout&&(this.pingTimeout=t.pingTimeout),void 0!==t?.onUnresponsive&&(this.onUnresponsive=t.onUnresponsive),this.subscriptionReconnect={...DEFAULT_RETRY_CONFIG,...t?.subscriptionRetry??{}},this.requestReconnect={...DEFAULT_RETRY_CONFIG,...t?.requestRetry??{}},this.publishRetry={...DEFAULT_RETRY_CONFIG,...t?.publishRetry??{}},this.authenticated$=this.authenticationResponse$.pipe(map$1(e=>!0===e?.ok)),this.authenticatedAs$=combineLatest([this.authenticated$,this.authentication$]).pipe(map$1(([e,t])=>e&&t?t.pubkey:null)),this.reconnectTimer=Relay.createReconnectTimer(e),this.open$.subscribe(()=>{this.log("Connected"),this.connected$.next(!0),this.attempts$.next(0),this.error$.next(null),this.resetState()}),this.close$.subscribe(e=>{this.connected$.value?this.log("Disconnected"):this.log("Failed to connect"),this.connected$.value&&this.connected$.next(!1),this.attempts$.next(this.attempts$.value+1),this.resetState(),e.wasClean||this.startReconnectTimer(e)}),this.socket=webSocket({url:e,openObserver:this.open$,closeObserver:this.close$,closingObserver:this.closing$,WebSocketCtor:t?.WebSocket}),this.information$=defer(()=>(this.log("Fetching NIP-11 information document"),Relay.fetchInformationDocument(this.url))).pipe(catchError(()=>of(null)),tap$1(e=>this._nip11=e),shareReplay(1)),this.limitations$=this.information$.pipe(map$1(e=>e?e.limitation:null)),this.supported$=this.information$.pipe(map$1(e=>e&&Array.isArray(e.supported_nips)?e.supported_nips.filter(e=>"number"==typeof e):null)),this.icon$=this.information$.pipe(map$1(e=>e?.icon||new URL("/favicon.ico",ensureHttpURL(this.url)).toString())),this.authRequiredForRead$=this.receivedAuthRequiredForReq,this.authRequiredForPublish$=this.receivedAuthRequiredForEvent,this.authRequiredForRead$.pipe(filter$1(e=>!0===e),take(1)).subscribe(()=>this.log("Auth required for REQ")),this.authRequiredForPublish$.pipe(filter$1(e=>!0===e),take(1)).subscribe(()=>this.log("Auth required for EVENT")),this.status$=combineLatest({url:of(this.url),connected:this.connected$,authenticated:this.authenticated$,authenticatedAs:this.authenticatedAs$,ready:this._ready$,authRequiredForRead:this.authRequiredForRead$,authRequiredForPublish:this.authRequiredForPublish$,challenge:this.challenge$.asObservable()}).pipe(shareReplay(1));const r=this.socket.pipe(filter$1(e=>Array.isArray(e)&&"NOTICE"===e[0]),map$1(e=>e[1]),scan((e,t)=>[...e,t],[]),tap$1(e=>this.notices$.next(e))),n=this.socket.pipe(filter$1(e=>"AUTH"===e[0]),map$1(e=>e[1]),tap$1(e=>{this.log("Received AUTH challenge",e),this.challenge$.next(e)})),i=new Subject,o=this.socket.pipe(tap$1(e=>{const t=Date.now();this.lastMessageReceivedAt=t,this._lastMessageAt$.next(t),i.next(e)}));this.message$=i.asObservable(),this.notice$=this.message$.pipe(filter$1(e=>Array.isArray(e)&&"NOTICE"===e[0]),map$1(e=>e[1]));const s=this.connected$.pipe(switchMap(e=>e&&this.enablePing?timer(this.pingFrequency,this.pingFrequency).pipe(mergeMap(()=>{if(Date.now()-this.lastMessageReceivedAtArray.isArray(t)&&("EOSE"===t[0]||"CLOSED"===t[0])&&t[1]===e),take(1),timeout$1({first:this.pingTimeout,with:()=>{const e=Date.now(),t=this.onUnresponsive?.({url:this.url,lastMessageAt:this.lastMessageReceivedAt,now:e,attempts:this.attempts$.value})??"reconnect",r=new Error(`Relay ping timeout after ${this.pingTimeout}ms`);return"reconnect"===t?(this.log("Relay connection has become unresponsive, triggering reconnect"),this.startReconnectTimer(r)):"close"===t?(this.log("Relay connection has become unresponsive, closing connection"),this.error$.next(r),this.socket.complete()):this.log("Relay connection has become unresponsive (ignoring per policy)"),NEVER}}),finalize(()=>this.send(["CLOSE",e])))})):NEVER),catchError(()=>NEVER));this.watchTower=this.ready$.pipe(switchMap(e=>e?merge$1(o,r,n,this.information$,s).pipe(ignoreElements(),catchError(e=>(this.startReconnectTimer(e instanceof Error?e:new Error("Connection error")),NEVER)),share({resetOnRefCountZero:()=>timer(this.keepAlive)})):NEVER),share())}startReconnectTimer(e){this.ready&&(this.error$.next(e instanceof Error?e:new Error("Connection error")),this._ready$.next(!1),this.reconnectTimer(e,this.attempts$.value).pipe(take(1)).subscribe(()=>{this._ready$.next(!0)}))}waitForAuth(e,t){return combineLatest([e,this.authenticated$]).pipe(mergeWith(this.watchTower),filter$1(([e,t])=>!e||t),take(1),switchMap(()=>t))}waitForReady(e){return this.ready?e:this.ready$.pipe(filter$1(e=>e),take(1),switchMap(()=>e))}multiplex(e,t,r){return this.socket.multiplex(e,t,r)}send(e){this.socket.next(e)}req(e,t=nanoid$1()){let r;if("function"==typeof e){const t=e(this);r=(isObservable(t)?t:merge$1(of(t),NEVER)).pipe(map$1(e=>Array.isArray(e)?e:[e]))}else r=(isObservable(e)?e:merge$1(of(e),NEVER)).pipe(map$1(e=>Array.isArray(e)?e:[e]));const n=r.pipe(ignoreElements(),endWith(null)),i=this.socket.pipe(filter$1(e=>Array.isArray(e)&&("EVENT"===e[0]||"CLOSED"===e[0]||"EOSE"===e[0])&&e[1]===t),share()),o=r.pipe(tap$1(e=>{this.socket.next(["REQ",t,...e]),this.reqs$.next({...this.reqs$.value,[t]:e})}),finalize(()=>{this.socket.next(["CLOSE",t]);const{[t]:e,...r}=this.reqs$.value;this.reqs$.next(r)}),switchMap(()=>i)),s=merge$1(this.watchTower,o).pipe(takeUntil(i.pipe(ignoreElements(),endWith(!0))),takeUntil(n),map$1(e=>{if("EOSE"===e[0])return"EOSE";if("CLOSED"===e[0])throw new ReqCloseError(e[2]);return e[2]}),this.handleAuthRequiredForReq("REQ"),markFromRelay(this.url),timeout$1({first:this.eoseTimeout,with:()=>merge$1(of("EOSE"),NEVER)}),share());return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,s))}count(e,t=nanoid$1()){const r=this.socket.pipe(filter$1(e=>Array.isArray(e)&&("COUNT"===e[0]||"CLOSED"===e[0])&&e[1]===t)),n=defer(()=>(this.socket.next(Array.isArray(e)?["COUNT",t,...e]:["COUNT",t,e]),merge$1(this.watchTower,r))).pipe(map$1(e=>{if("COUNT"===e[0])return e[2];throw new ReqCloseError(e[2])}),this.handleAuthRequiredForReq("COUNT"),take(1),timeout$1({first:this.eoseTimeout,with:()=>throwError(()=>new Error("COUNT timeout"))}));return this.waitForReady(this.waitForAuth(this.authRequiredForRead$,n)).pipe(share())}event(e,t="EVENT"){const r=defer(()=>(this.socket.next([t,e]),this.socket.pipe(filter$1(t=>"OK"===t[0]&&t[1]===e.id),map$1(e=>({ok:e[2],message:e[3],from:this.url}))))).pipe(share()),n=merge$1(this.watchTower,r).pipe(takeUntil(r.pipe(ignoreElements(),endWith(!0))),take(1),tap$1(({ok:e,message:t})=>{!1===e&&t?.startsWith(AUTH_REQUIRED_PREFIX)&&!this.receivedAuthRequiredForEvent.value&&(this.log("Auth required for publish"),this.receivedAuthRequiredForEvent.next(!0))}),timeout$1({first:this.eventTimeout,with:()=>of({ok:!1,from:this.url,message:"Timeout"})}));return"AUTH"===t?this.waitForReady(n).pipe(share()):this.waitForReady(this.waitForAuth(this.authRequiredForPublish$,n)).pipe(share())}auth(e){return this.authentication$.next(e),lastValueFrom(this.event(e,"AUTH").pipe(tap$1(e=>this.authenticationResponse$.next(e))))}async negentropy(e,t,r,n){if(!1===(await this.getSupported())?.includes(77))throw new Error("Relay does not support NIP-77");const{buildStorageVector:i,buildStorageFromFilter:o,negentropySync:s}=await __vitePreload(async()=>{const{buildStorageVector:e,buildStorageFromFilter:t,negentropySync:r}=await import("./negentropy-CxcMNqMs.js");return{buildStorageVector:e,buildStorageFromFilter:t,negentropySync:r}},[]);return s(Array.isArray(e)?i(e):await o(e,t),this.socket,t,r,n)}authenticate(e){if(!this.challenge)throw new Error("Have not received authentication challenge");const t=e.signEvent(makeAuthEvent(this.url,this.challenge));return lastValueFrom((t instanceof Promise?from(t):of(t)).pipe(switchMap(e=>this.auth(e))))}customRetryOperator(e,t){return!1===e?identity$1:"number"==typeof e?retry({...t,count:e}):!0===e?t?retry(t):retry():retry({...t,...e})}customRepeatOperator(e){return!1===e||void 0===e?identity$1:!0===e?repeat():repeat(e)}customTimeoutOperator(e,t){return!1===e?identity$1:simpleTimeout(!0===e?t:e??t)}handleAuthRequiredForReq(e){return catchError(t=>(t instanceof ReqCloseError&&t.message.startsWith(AUTH_REQUIRED_PREFIX)&&!this.receivedAuthRequiredForReq.value&&(this.log(`Auth required for ${e}`),this.receivedAuthRequiredForReq.next(!0)),throwError(()=>t)))}subscription(e,t){return this.req(e,t?.id).pipe(this.customRetryOperator(t?.reconnect??!0,this.subscriptionReconnect),this.customRepeatOperator(t?.resubscribe),share())}request(e,t){return this.req(e,t?.id).pipe(this.customRetryOperator(t?.reconnect??!0,this.requestReconnect),this.customRepeatOperator(t?.resubscribe),completeOnEose(),share())}publish(e,t){return lastValueFrom(this.event(e).pipe(mergeMap(e=>!1===e.ok&&e.message?.startsWith(AUTH_REQUIRED_PREFIX)?throwError(()=>new Error(e.message)):of(e)),this.customRetryOperator(t?.retries??t?.reconnect??!0,this.publishRetry),this.customTimeoutOperator(t?.timeout,this.publishTimeout)))}sync(e,t,r=SyncDirection.RECEIVE){return new Observable$1(n=>{const i=new AbortController;let o=!1;return this.negentropy(e,t,async(t,i)=>{if(r&SyncDirection.SEND&&t.length>0){const r=await(async t=>Array.isArray(e)?e.filter(e=>t.includes(e.id)):e.getByFilters({ids:t}))(t);await Promise.allSettled(r.map(e=>lastValueFrom(this.event(e))))}r&SyncDirection.RECEIVE&&i.length>0&&await lastValueFrom(this.req({ids:i}).pipe(completeOnEose(),Reflect.has(e,"add")?mapEventsToStore(e):identity$1,tap$1(e=>n.next(e))))},{signal:i.signal}).then(()=>{o||n.complete()}).catch(e=>{o||n.error(e)}),()=>{o||(o=!0,i.abort())}}).pipe(share())}close(){this.socket.unsubscribe()}async getInformation(){return firstValueFrom(this.information$)}async getLimitations(){return firstValueFrom(this.limitations$)}async getSupported(){return firstValueFrom(this.supported$)}static fetchInformationDocument(e){return from(fetch(ensureHttpURL(e),{headers:{Accept:"application/nostr+json"}}).then(e=>e.json())).pipe(catchError(()=>of(null)),simpleTimeout(1e4))}static createReconnectTimer(e){return(e,t=0)=>timer(Math.min(1e3*Math.pow(1.5,t),3e5))}}class RelayPool{options;relays$=new BehaviorSubject(new Map);get relays(){return this.relays$.value}status$;ignoreOffline=!0;add$=new Subject;remove$=new Subject;constructor(e){this.options=e,this.status$=this.relays$.pipe(map$1(e=>Array.from(e.values())),switchMap(e=>0===e.length?of({}):merge$1(...e.map(e=>e.status$)).pipe(scan((e,t)=>({...e,[t.url]:t}),{}),startWith({}))),shareReplay(1))}relay(e){e=normalizeURL(e);let t=this.relays.get(e);return t||(t=new Relay(e,this.options),this.relays.set(e,t),this.relays$.next(this.relays),t)}group(e,t=this.ignoreOffline){let r=Array.isArray(e)?e.map(e=>this.relay(e)):e.pipe(map$1(e=>e.map(e=>this.relay(e))));return t&&(r=Array.isArray(r)?r.filter(e=>e.ready):r.pipe(map$1(e=>e.filter(e=>e.ready)))),new RelayGroup(r)}remove(e,t=!0){let r;if("string"==typeof e){if(r=this.relays.get(e),!r)return}else{if(!Array.from(this.relays.values()).some(t=>t===e))return;r=e}t&&r?.close(),this.relays.delete(r.url),this.relays$.next(this.relays),this.remove$.next(r)}req(e,t,r){return this.group(e,!1).req(t,r)}event(e,t){return this.group(e,!1).event(t)}negentropy(e,t,r,n,i){return this.group(e,!1).negentropy(t,r,n,i)}publish(e,t,r){return this.group(e).publish(t,r)}request(e,t,r){return this.group(e).request(t,r)}subscription(e,t,r){return this.group(e).subscription(t,r)}subscriptionMap(e,t){const r=isObservable(e)?e:of(e);return this.group(r.pipe(map$1(e=>Object.keys(e)))).subscription(e=>r.pipe(map$1(t=>t[e.url]),distinctUntilChanged(isFilterEqual)),t)}outboxSubscription(e,t,r){const n=isObservable(e)?e.pipe(map$1(e=>createFilterMap(e,t))):createFilterMap(e,t);return this.subscriptionMap(n,r)}count(e,t,r){return this.group(e).count(t,r)}sync(e,t,r,n){return this.group(e).sync(t,r,n)}}class NostrRelayService extends Service{pool=new RelayPool({enablePing:!0});async publish(e,t){if(!e||0===e.length)throw new Error("No relays provided to publish the event.");const r=await this.pool.publish(e,t);if(!r.some(e=>e.ok))throw new Error(`Failed to publish event. Responses: ${JSON.stringify(r)}`);return r}}const amdModule9=Object.freeze(Object.defineProperty({__proto__:null,default:NostrRelayService},Symbol.toStringTag,{value:"Module"}));class ErrorOAuth2{}class ErrorUnknown extends ErrorOAuth2{constructor(e){super(),this.message=e}}class ErrorNoAccessToken extends ErrorOAuth2{}class ErrorNoAuthCode extends ErrorOAuth2{}class ErrorInvalidReturnedStateParam extends ErrorOAuth2{}class ErrorInvalidScope extends ErrorOAuth2{}class ErrorInvalidRequest extends ErrorOAuth2{}class ErrorInvalidToken extends ErrorOAuth2{}class ErrorAuthenticationGrant extends ErrorOAuth2{}class ErrorUnauthorizedClient extends ErrorAuthenticationGrant{}class ErrorAccessDenied extends ErrorAuthenticationGrant{}class ErrorUnsupportedResponseType extends ErrorAuthenticationGrant{}class ErrorServerError extends ErrorAuthenticationGrant{}class ErrorTemporarilyUnavailable extends ErrorAuthenticationGrant{}class ErrorAccessTokenResponse extends ErrorOAuth2{}class ErrorInvalidClient extends ErrorAccessTokenResponse{}class ErrorInvalidGrant extends ErrorAccessTokenResponse{}class ErrorUnsupportedGrantType extends ErrorAccessTokenResponse{}const RAW_ERROR_TO_ERROR_CLASS_MAP={invalid_request:ErrorInvalidRequest,invalid_grant:ErrorInvalidGrant,unauthorized_client:ErrorUnauthorizedClient,access_denied:ErrorAccessDenied,unsupported_response_type:ErrorUnsupportedResponseType,invalid_scope:ErrorInvalidScope,server_error:ErrorServerError,temporarily_unavailable:ErrorTemporarilyUnavailable,invalid_client:ErrorInvalidClient,unsupported_grant_type:ErrorUnsupportedGrantType,invalid_token:ErrorInvalidToken},toErrorObject=e=>{const t=RAW_ERROR_TO_ERROR_CLASS_MAP[e];return t?new t:new ErrorUnknown(e)};var __awaiter$1=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(t){o(t)}}function a(e){try{l(n.throw(e))}catch(t){o(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};const RECOMMENDED_CODE_VERIFIER_LENGTH=96,PKCE_CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",parseWwwAuthenticateHeader=e=>{const t=e.slice(7).replace(/"/g,"").split(",").map(e=>{const[t,r]=e.trim().split("=");return{[t]:r}}).reduce((e,t)=>Object.assign(Object.assign({},e),t),{});return{realm:t.realm,error:t.error,errorDescription:t.error_description,errorUri:t.error_uri}},base64urlEncode=e=>{let t=btoa(e);return t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_"),t=t.replace(/=/g,""),t},extractParamFromUrl=(e,t)=>{let r=t.split("?");if(r.length<2)return;r=r[1].split("#");const n=r[0].split("&");for(const i of n){const[t,r]=i.split("=");if(t===e)return decodeURIComponent(r)}},objectToQueryString=e=>Object.entries(e).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&"),generatePKCECodeChallengeAndVerifier=()=>__awaiter$1(void 0,void 0,void 0,function*(){const e=new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);crypto.getRandomValues(e);const t=base64urlEncode(Array.from(e).map(e=>PKCE_CHARSET[e%PKCE_CHARSET.length]).join("")),r=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t)),n=new Uint8Array(r);let i="";const o=n.byteLength;for(let s=0;s{const t=new Uint32Array(e);return crypto.getRandomValues(t),Array.from(t).map(e=>PKCE_CHARSET[e%PKCE_CHARSET.length]).join("")};var __awaiter=function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(t){o(t)}}function a(e){try{l(n.throw(e))}catch(t){o(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};const HEADER_AUTHORIZATION="Authorization",HEADER_WWW_AUTHENTICATE="WWW-Authenticate",RECOMMENDED_STATE_LENGTH=32;class OAuth2AuthCodePkceClient{constructor(e,t){this.state={},this.config=e,this.storage=t||LocalStorage,this.ready=new Promise(e=>this.setReady=e),this.recoverState()}reset(){return __awaiter(this,void 0,void 0,function*(){this.state={},yield this.saveState(),this.authCodeForAccessTokenPromise=void 0,this.refreshTokenForAccessTokenPromise=void 0})}requestAuthorizationCode(e){return __awaiter(this,void 0,void 0,function*(){const{clientId:t,extraAuthorizationParams:r,redirectUrl:n,scopes:i}=this.config,{codeChallenge:o,codeVerifier:s}=yield generatePKCECodeChallengeAndVerifier(),a=generateRandomState(RECOMMENDED_STATE_LENGTH);this.state=Object.assign(Object.assign({},this.state),{codeChallenge:o,codeVerifier:s,stateQueryParam:a}),this.saveState();let l=this.config.authorizationUrl+"?response_type=code&"+`client_id=${encodeURIComponent(t)}&`+`redirect_uri=${encodeURIComponent(n)}&`+`state=${a}&`+`code_challenge=${encodeURIComponent(o)}&code_challenge_method=S256`;if(i&&(l+=`&scope=${encodeURIComponent(i.join(" "))}`),r||e){const t=Object.assign(Object.assign({},r),e);l+=`&${objectToQueryString(t)}`}location.replace(l)})}isReturningFromAuthServer(){return!!extractParamFromUrl("code",location.href)}receiveCode(){return __awaiter(this,void 0,void 0,function*(){yield this.ready;const e=extractParamFromUrl("error",location.href);if(e)throw toErrorObject(e);if(extractParamFromUrl("state",location.href)!==this.state.stateQueryParam)throw console.warn('"state" parameter doesn\'t match the one sent! Possible malicious activity.'),new ErrorInvalidReturnedStateParam;if(this.state.authorizationCode=extractParamFromUrl("code",location.href),!this.state.authorizationCode)throw new ErrorNoAuthCode;this.saveState()})}getTokens(e){return __awaiter(this,void 0,void 0,function*(){const{accessToken:t,authorizationCode:r,idToken:n,refreshToken:i,scopes:o}=this.state;if(r)return this.exchangeAuthCodeForAccessToken(e);if(!t)throw new ErrorNoAccessToken;return this.isAccessTokenExpired()&&this.config.onAccessTokenExpiry?this.config.onAccessTokenExpiry():Promise.resolve({accessToken:t,idToken:n,refreshToken:i,scopes:o})})}exchangeAuthCodeForAccessToken(e){return __awaiter(this,void 0,void 0,function*(){this.authCodeForAccessTokenPromise||(this.authCodeForAccessTokenPromise=this.fetchAccessTokenUsingCode(e));const t=yield this.authCodeForAccessTokenPromise;return this.authCodeForAccessTokenPromise=void 0,this.state.authorizationCode=void 0,this.setTokens(t)})}exchangeRefreshTokenForAccessToken(){return __awaiter(this,void 0,void 0,function*(){this.refreshTokenForAccessTokenPromise||(this.refreshTokenForAccessTokenPromise=this.fetchAccessTokenUsingRefreshToken());const e=yield this.refreshTokenForAccessTokenPromise;return this.refreshTokenForAccessTokenPromise=void 0,this.setTokens(e)})}makeRetryFetchFunction(e){return(t,...r)=>__awaiter(this,void 0,void 0,function*(){const n=yield e(t,...r);if(401===n.status){const i=n.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());if(i&&"invalid_token"===parseWwwAuthenticateHeader(i).error)return yield this.exchangeRefreshTokenForAccessToken(),t=yield this.requestInterceptor(t),e(t,...r)}return n})}decorateFetchWithInterceptors(e){return(t,...r)=>__awaiter(this,void 0,void 0,function*(){"string"==typeof t&&(t=new Request(t)),t=yield this.requestInterceptor(t);const n=yield e(t,...r);return this.responseInterceptor(n)})}requestInterceptor(e){return __awaiter(this,void 0,void 0,function*(){const t=yield this.getTokens();return e.headers.set(HEADER_AUTHORIZATION,`Bearer ${t.accessToken}`),e})}responseInterceptor(e){return __awaiter(this,void 0,void 0,function*(){if(401!==e.status)return e;const t=e.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());if(t){const e=parseWwwAuthenticateHeader(t).error;throw"invalid_grant"===e&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),"invalid_token"===e&&this.config.onInvalidToken&&(yield this.config.onInvalidToken()),toErrorObject(e)}return e})}getGrantedScopes(){return this.state.scopes}isAuthorized(){return!!this.state.accessToken}isAccessTokenExpired(){const{accessTokenExpiry:e}=this.state;return Boolean(e&&new Date>=new Date(e))}fetchAccessTokenUsingCode(e){return __awaiter(this,void 0,void 0,function*(){const{authorizationCode:t,codeVerifier:r=""}=this.state,{clientId:n,redirectUrl:i}=this.config;r?t||console.warn("No authorization grant code is being passed."):console.warn("No code verifier is being sent.");const o=this.config.tokenUrl,s=Object.assign({grant_type:"authorization_code",code:t,redirect_uri:i,client_id:n,code_verifier:r},e),a=new URLSearchParams(s).toString();return this.makeTokenRequest(o,a)})}fetchAccessTokenUsingRefreshToken(){const{extraRefreshParams:e,clientId:t,tokenUrl:r}=this.config,{refreshToken:n}=this.state;n||console.warn("No refresh token is present.");const i=r;let o=`grant_type=refresh_token&refresh_token=${n}&client_id=${t}`;return e&&(o=`${i}&${objectToQueryString(e)}`),this.makeTokenRequest(i,o)}makeTokenRequest(e,t){return __awaiter(this,void 0,void 0,function*(){const r=yield fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),n=yield r.json();if(!r.ok)throw"invalid_grant"===n.error&&this.config.onInvalidGrant&&(yield this.config.onInvalidGrant()),toErrorObject(n.error);const{access_token:i,expires_in:o,id_token:s,refresh_token:a,scope:l}=n;return{accessToken:i,expiresIn:o,idToken:s,refreshToken:a,scope:l}})}setTokens(e){return __awaiter(this,void 0,void 0,function*(){const{accessToken:t,expiresIn:r,idToken:n,refreshToken:i,scope:o}=e;return this.state.accessToken=t,this.state.accessTokenExpiry=new Date(Date.now()+1e3*parseInt(r,10)).toString(),n&&(this.state.idToken=n),i&&(this.state.refreshToken=i),o&&(this.state.scopes=o.split(" ")),yield this.saveState(),{accessToken:this.state.accessToken,idToken:this.state.idToken,refreshToken:this.state.refreshToken,scopes:o?this.state.scopes:[]}})}recoverState(){return __awaiter(this,void 0,void 0,function*(){this.state=JSON.parse((yield this.storage.loadState())||"{}"),this.setReady(),this.config.storeRefreshToken||(this.state.refreshToken=this.refreshToken)})}saveState(){return __awaiter(this,void 0,void 0,function*(){this.refreshToken=this.state.refreshToken;const e=Object.assign({},this.state);this.config.storeRefreshToken||delete e.refreshToken,yield this.storage.saveState(JSON.stringify(e))})}}const LOCALSTORAGE_STATE="oauth2authcodepkce-state",LocalStorage={saveState:e=>localStorage.setItem(LOCALSTORAGE_STATE,e),loadState:()=>localStorage.getItem(LOCALSTORAGE_STATE)};class MarcoOsmAuthStorage{saveState(e){localStorage.setItem("marco:osm_auth_state",e)}loadState(){const e=localStorage.getItem("marco:osm_auth_state");if(!e)return!1;try{return JSON.parse(e),e}catch(t){return console.warn("Failed to parse OSM auth state",t),!1}}}class OsmAuthService extends Service{static{decorateFieldV2(this.prototype,"isConnected",[tracked],function(){return!1})}#te=void initializeDeferredDecorator(this,"isConnected");static{decorateFieldV2(this.prototype,"userDisplayName",[tracked],function(){return null})}#re=void initializeDeferredDecorator(this,"userDisplayName");oauthClient;constructor(){super(...arguments);const e="https://www.openstreetmap.org",t=`${window.location.origin}/oauth/osm/callback`;this.oauthClient=new OAuth2AuthCodePkceClient({scopes:["read_prefs","write_api"],authorizationUrl:`${e}/oauth2/authorize`,tokenUrl:`${e}/oauth2/token`,clientId:"jIn8l5mT8FZOGYiIYXG1Yvj_2FZKB9TJ1edZwOJPsRU",redirectUrl:t,storeRefreshToken:!0},new MarcoOsmAuthStorage),this.restoreSession()}async restoreSession(){try{await this.oauthClient.ready}catch(e){console.warn("oauthClient.ready failed",e)}if(await this.oauthClient.isAuthorized()){this.isConnected=!0;const e=localStorage.getItem("marco:osm_user_display_name");e?this.userDisplayName=e:await this.fetchUserInfo()}}async login(){await this.oauthClient.requestAuthorizationCode()}async handleCallback(){await this.oauthClient.receiveCode(),await this.oauthClient.getTokens(),this.isConnected=!0,await this.fetchUserInfo()}async logout(){await this.oauthClient.reset(),this.isConnected=!1,this.userDisplayName=null,localStorage.removeItem("marco:osm_user_display_name")}async fetchUserInfo(){try{const e=await this.oauthClient.getTokens(),t=await fetch("https://api.openstreetmap.org/api/0.6/user/details.json",{headers:{Authorization:`Bearer ${e.accessToken}`}});if(t.ok){const e=await t.json();console.debug("OSM data:",e);const r=e.user.display_name;this.userDisplayName=r,localStorage.setItem("marco:osm_user_display_name",r)}else console.error("Failed to fetch OSM user info",t.status)}catch(e){console.error("Error fetching OSM user info",e)}}}const amdModule10=Object.freeze(Object.defineProperty({__proto__:null,default:OsmAuthService},Symbol.toStringTag,{value:"Module"}));function humanizeOsmTag$1(e){return"string"==typeof e&&e?e.replace(/[_-]/g," ").replace(/\w\S*/g,e=>e.replace(/^\w/,e=>e.toUpperCase())):""}const amdModule17=Object.freeze(Object.defineProperty({__proto__:null,humanizeOsmTag:humanizeOsmTag$1},Symbol.toStringTag,{value:"Module"}));function getLocalizedName(e,t="Untitled Place"){if(!e)return t;const r=navigator.languages||[navigator.language||"en"];for(const n of r){if(!n)continue;const t=`name:${n.split("-")[0]}`;if(e[t])return e[t]}return e.name?e.name:e["name:en"]?e["name:en"]:t}const PLACE_TYPE_KEYS=["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","highway","aeroway","waterway","natural","place","border_type","admin_title"];function getPlaceType(e){if(!e)return null;for(const t of PLACE_TYPE_KEYS){const r=e[t];if(r)return humanizeOsmTag$1("yes"===r?t:r)}return null}const amdModule23=Object.freeze(Object.defineProperty({__proto__:null,getLocalizedName:getLocalizedName,getPlaceType:getPlaceType},Symbol.toStringTag,{value:"Module"})),POI_CATEGORIES=[{id:"restaurants",label:"Restaurants",icon:"fork-and-knife",filter:['["amenity"~"^(restaurant|fast_food|food_court|pub|cafe)$"]["cuisine"!~"coffee"]'],types:["node","way"]},{id:"coffee",label:"Coffee",icon:"cup-and-saucer",filter:['["amenity"~"^(cafe|ice_cream)$"]','["shop"~"^(coffee|tea)$"]','["cuisine"~"coffee_shop"]'],types:["node","way"]},{id:"groceries",label:"Groceries",icon:"shopping-basket",filter:['["shop"~"^(supermarket|convenience|grocery|greengrocer|bakery|butcher|deli|farm|seafood)$"]'],types:["node","way"]},{id:"things-to-do",label:"Things to do",icon:"feather-camera",filter:['["tourism"~"^(museum|gallery|attraction|viewpoint|zoo|theme_park|aquarium|artwork)$"]','["amenity"~"^(cinema|theatre|arts_centre|planetarium)$"]','["leisure"~"^(sports_centre|stadium|water_park)$"]','["historic"]','["shop"="flea_market"]'],types:["node","way","relation"]},{id:"accommodation",label:"Hotels",icon:"person-sleeping-in-bed",filter:['["tourism"~"^(hotel|hostel|motel|chalet)$"]'],types:["node","way","relation"]}];function getCategoryById(e){return POI_CATEGORIES.find(t=>t.id===e)}const amdModule25=Object.freeze(Object.defineProperty({__proto__:null,POI_CATEGORIES:POI_CATEGORIES,getCategoryById:getCategoryById},Symbol.toStringTag,{value:"Module"}));class OsmService extends Service{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");controller=null;cachedResults=null;lastQueryKey=null;cachedPlaces=new Map;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}async getNearbyPois(e,t,r=50){const n=`${e},${t},${r}`;if(this.lastQueryKey===n&&this.cachedResults)return console.debug("Returning cached Overpass results for:",n),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,o=[`~"^(${["amenity","shop","tourism","historic","leisure","office","craft","building","landuse","public_transport","aeroway"].join("|")})$"~".*"`],s=Object.entries({public_transport:["stop_area","platform"]}).map(([e,t])=>`["${e}"!~"^(${t.join("|")})$"]`).join(""),a=`\n[out:json][timeout:25];\n(\n node(around:${r},${e},${t})\n [${o}]${s}[~"^name"~"."];\n way(around:${r},${e},${t})\n [${o}]${s}[~"^name"~"."];\n relation(around:${r},${e},${t})\n [${o}]${s}[~"^name"~"."];\n);\nout center;\n `.trim(),l=`${this.settings.overpassApi}?data=${encodeURIComponent(a)}`;try{const e=await this.fetchWithRetry(l,{signal:i});if(!e.ok)throw new Error("Overpass request failed");const t=(await e.json()).elements.map(this.normalizePoi);return this.lastQueryKey=n,this.cachedResults=t,t}catch(c){if("AbortError"===c.name)return console.debug("Overpass request aborted"),[];throw c}}async getCategoryPois(e,t,r,n){const i=getCategoryById(t);if(!i||!e)return[];const o=r&&n?`cat:${t}:${r}:${n}`:null;if(o&&this.lastQueryKey===o&&this.cachedResults)return console.debug("Returning cached category results for:",o),this.cachedResults;this.controller&&this.controller.abort(),this.controller=new AbortController;const s=this.controller.signal,{minLat:a,minLon:l,maxLat:c,maxLon:u}=e,h=[],d=i.types||["node","way","relation"];i.filter.forEach(e=>{d.forEach(t=>{h.push(`${t}${e}[~"^name"~"."];`)})});const p=`\n[out:json][timeout:25][bbox:${a},${l},${c},${u}];\n(\n ${h.join("\n ")}\n);\nout center;\n `.trim(),f=`${this.settings.overpassApi}?data=${encodeURIComponent(p)}`;try{const e=await this.fetchWithRetry(f,{signal:s});if(!e.ok)throw new Error("Overpass request failed");const t=(await e.json()).elements.map(this.normalizePoi);return o&&(this.lastQueryKey=o,this.cachedResults=t),t}catch(g){if("AbortError"===g.name)return console.debug("Category search aborted"),[];throw console.error("Category search failed",g),g}}normalizePoi(e){const t=e.tags||{},r=getPlaceType(t)||"Point of Interest";return{title:getLocalizedName(t),lat:e.lat||e.center?.lat,lon:e.lon||e.center?.lon,url:t.website,osmId:String(e.id),osmType:e.type,osmTags:t,description:t.description,source:"osm",type:r}}async fetchWithRetry(e,t={},r=3){try{const n=await fetch(e,t);return!n.ok&&r>0&&[502,503,504,429].includes(n.status)?(console.warn(`Overpass request failed with ${n.status}. Retrying... (${r} left)`),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1)):n}catch(n){if(r>0&&"AbortError"!==n.name)return console.debug(`Retrying Overpass request... (${r} left)`),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1);throw n}}async getPoiById(e,t=null){let r;r="node"===t?`[out:json][timeout:25];node(${e});out center;`:"way"===t?`[out:json][timeout:25];way(${e});out center;`:`\n[out:json][timeout:25];\n(\n node(${e});\n way(${e});\n);\nout center;\n `.trim();const n=`${this.settings.overpassApi}?data=${encodeURIComponent(r)}`,i=await this.fetchWithRetry(n);if(!i.ok)throw new Error("Overpass request failed");const o=await i.json();return o.elements[0]?this.normalizePoi(o.elements[0]):null}async fetchOsmObject(e,t){if(!e||!t)return null;const r=`${t}:${e}`,n=this.cachedPlaces.get(r);if(n&&Date.now()-n.timestamp<1e4)return console.debug(`Using in-memory cached OSM object for ${r}`),n.data;let i;if("node"===t)i=`https://www.openstreetmap.org/api/0.6/node/${e}.json`;else if("way"===t)i=`https://www.openstreetmap.org/api/0.6/way/${e}/full.json`;else{if("relation"!==t)return console.error("Unknown OSM type:",t),null;i=`https://www.openstreetmap.org/api/0.6/relation/${e}/full.json`}try{const n=await this.fetchWithRetry(i);if(!n.ok){if(410===n.status)return console.warn("OSM object has been deleted"),null;throw new Error(`OSM API request failed: ${n.status}`)}const o=await n.json(),s=this.normalizeOsmApiData(o.elements,e,t);return this.cachedPlaces.set(r,{data:s,timestamp:Date.now()}),setTimeout(()=>{this.cachedPlaces.delete(r)},1e4),s}catch(o){return console.error("Failed to fetch OSM object:",o),null}}normalizeOsmApiData(e,t,r){if(!e||0===e.length)return null;let n=e.find(e=>String(e.id)===String(t)&&e.type===r);if(!n)return null;let i=n;if("relation"===r&&n.members){const t=n.members.find(e=>"label"===e.role&&"node"===e.type),r=n.members.find(e=>"admin_centre"===e.role&&"node"===e.type),o=t||r;if(o){const t=e.find(e=>String(e.id)===String(o.ref)&&"node"===e.type);t&&(i=t)}}let o=i.lat,s=i.lon,a=null,l=null;if("way"===r&&n.nodes){const t=new Map;e.forEach(e=>{"node"===e.type&&t.set(e.id,[e.lon,e.lat])});const r=n.nodes.map(e=>t.get(e)).filter(Boolean);if(r.length>0){if(i===n){const e=r.reduce((e,t)=>e+t[1],0),t=r.reduce((e,t)=>e+t[0],0);o=e/r.length,s=t/r.length}const e=r.map(e=>e[1]),t=r.map(e=>e[0]);if(a={minLat:Math.min(...e),maxLat:Math.max(...e),minLon:Math.min(...t),maxLon:Math.max(...t)},r.length>1){const e=r[0],t=r[r.length-1];l=e[0]===t[0]&&e[1]===t[1]?{type:"Polygon",coordinates:[r]}:{type:"LineString",coordinates:r}}}}else if("relation"===r&&n.members){const t=[],r=new Map;e.forEach(e=>{"node"===e.type&&r.set(e.id,e)});const c=[];if(n.members.forEach(n=>{if("node"===n.type){const e=r.get(n.ref);e&&t.push(e)}else if("way"===n.type){const i=e.find(e=>"way"===e.type&&e.id===n.ref);if(i&&i.nodes){const e=[];i.nodes.forEach(n=>{const i=r.get(n);i&&(t.push(i),e.push([i.lon,i.lat]))}),e.length>1&&c.push(e)}}}),t.length>0){if(i===n){const e=t.reduce((e,t)=>e+t.lat,0),r=t.reduce((e,t)=>e+t.lon,0);o=e/t.length,s=r/t.length}const e=t.map(e=>e.lat),r=t.map(e=>e.lon);a={minLat:Math.min(...e),maxLat:Math.max(...e),minLon:Math.min(...r),maxLon:Math.max(...r)}}c.length>0&&(l={type:"MultiLineString",coordinates:c})}const c=i.tags||{},u=getPlaceType(c)||"Point of Interest";return{title:getLocalizedName(c),lat:o,lon:s,bbox:a,geojson:l,url:c.website,osmId:String(i.id),osmType:i.type,osmTags:c,description:c.description,source:"osm",type:u}}}const amdModule11=Object.freeze(Object.defineProperty({__proto__:null,default:OsmService},Symbol.toStringTag,{value:"Module"}));class PhotonService extends Service{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");controller=null;cancelAll(){this.controller&&(this.controller.abort(),this.controller=null)}get baseUrl(){return this.settings.photonApi}async search(e,t,r,n=10){if(!e||e.length<2)return[];this.controller&&this.controller.abort(),this.controller=new AbortController;const i=this.controller.signal,o=new URLSearchParams({q:e,limit:String(n)});t&&r&&(o.append("lat",parseFloat(t).toFixed(4)),o.append("lon",parseFloat(r).toFixed(4)));const s=`${this.baseUrl}?${o.toString()}`;try{const e=await this.fetchWithRetry(s,{signal:i});if(!e.ok)throw new Error(`Photon request failed with status ${e.status}`);const t=await e.json();return t.features?t.features.map(e=>this.normalizeFeature(e)):[]}catch(a){return"AbortError"===a.name||console.error("Photon search error:",a),[]}}normalizeFeature(e){const t=e.properties||{},r=(e.geometry||{}).coordinates||[],n=r[0],i=r[1],o=[];t.street&&o.push(t.housenumber?`${t.street} ${t.housenumber}`:t.street),t.city&&t.city!==t.name&&o.push(t.city),t.state&&t.state!==t.city&&o.push(t.state),t.country&&o.push(t.country);const s=o.join(", "),a=t.name||s||"Unknown Place",l={...t};t.osm_key&&t.osm_value&&(l[t.osm_key]=t.osm_value);const c=getPlaceType(l)||humanizeOsmTag$1(t.osm_value);return{title:a,lat:i,lon:n,osmId:t.osm_id,osmType:{N:"node",W:"way",R:"relation"}[t.osm_type]||t.osm_type,osmTags:l,description:t.name?s:o.slice(1).join(", "),source:"photon",type:c}}async fetchWithRetry(e,t={},r=3){try{const n=await fetch(e,t);return!n.ok&&r>0&&[502,503,504,429].includes(n.status)?(console.warn(`Photon request failed with ${n.status}. Retrying... (${r} left)`),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1)):n}catch(n){if(r>0&&"AbortError"!==n.name)return console.debug(`Retrying Photon request... (${r} left)`,n),await new Promise(e=>setTimeout(e,1e3)),this.fetchWithRetry(e,t,r-1);throw n}}}const amdModule12=Object.freeze(Object.defineProperty({__proto__:null,default:PhotonService},Symbol.toStringTag,{value:"Module"})),DEFAULT_SETTINGS={overpassApi:"https://overpass-api.de/api/interpreter",mapKinetic:!0,photonApi:"https://photon.komoot.io/api/",showQuickSearchButtons:!0,nostrPhotoFallbackUploads:!1,nostrReadRelays:null,nostrWriteRelays:null};class SettingsService extends Service{static{decorateFieldV2(this.prototype,"overpassApi",[tracked],function(){return DEFAULT_SETTINGS.overpassApi})}#ne=void initializeDeferredDecorator(this,"overpassApi");static{decorateFieldV2(this.prototype,"mapKinetic",[tracked],function(){return DEFAULT_SETTINGS.mapKinetic})}#ie=void initializeDeferredDecorator(this,"mapKinetic");static{decorateFieldV2(this.prototype,"photonApi",[tracked],function(){return DEFAULT_SETTINGS.photonApi})}#oe=void initializeDeferredDecorator(this,"photonApi");static{decorateFieldV2(this.prototype,"showQuickSearchButtons",[tracked],function(){return DEFAULT_SETTINGS.showQuickSearchButtons})}#se=void initializeDeferredDecorator(this,"showQuickSearchButtons");static{decorateFieldV2(this.prototype,"nostrPhotoFallbackUploads",[tracked],function(){return DEFAULT_SETTINGS.nostrPhotoFallbackUploads})}#ae=void initializeDeferredDecorator(this,"nostrPhotoFallbackUploads");static{decorateFieldV2(this.prototype,"nostrReadRelays",[tracked],function(){return DEFAULT_SETTINGS.nostrReadRelays})}#le=void initializeDeferredDecorator(this,"nostrReadRelays");static{decorateFieldV2(this.prototype,"nostrWriteRelays",[tracked],function(){return DEFAULT_SETTINGS.nostrWriteRelays})}#ce=void initializeDeferredDecorator(this,"nostrWriteRelays");overpassApis=[{name:"overpass-api.de (DE)",url:"https://overpass-api.de/api/interpreter"},{name:"private.coffee (AT)",url:"https://overpass.private.coffee/api/interpreter"}];photonApis=[{name:"photon.komoot.io",url:"https://photon.komoot.io/api/"}];constructor(){super(...arguments),this.loadSettings()}loadSettings(){let e={};const t=localStorage.getItem("marco:settings");if(t)try{e=JSON.parse(t)}catch(n){console.error("Failed to parse settings from localStorage",n)}else{const t=localStorage.getItem("marco:overpass-api");t&&(e.overpassApi=t);const r=localStorage.getItem("marco:map-kinetic");null!==r&&(e.mapKinetic="true"===r);const n=localStorage.getItem("marco:show-quick-search");null!==n&&(e.showQuickSearchButtons="true"===n);const i=localStorage.getItem("marco:nostr-photo-fallback-uploads");null!==i&&(e.nostrPhotoFallbackUploads="true"===i);const o=localStorage.getItem("marco:photon-api");o&&(e.photonApi=o)}const r={...DEFAULT_SETTINGS,...e};this.overpassApis.some(e=>e.url===r.overpassApi)||(r.overpassApi=DEFAULT_SETTINGS.overpassApi),this.overpassApi=r.overpassApi,this.mapKinetic=r.mapKinetic,this.photonApi=r.photonApi,this.showQuickSearchButtons=r.showQuickSearchButtons,this.nostrPhotoFallbackUploads=r.nostrPhotoFallbackUploads,this.nostrReadRelays=r.nostrReadRelays,this.nostrWriteRelays=r.nostrWriteRelays,this.saveSettings()}saveSettings(){const e={overpassApi:this.overpassApi,mapKinetic:this.mapKinetic,photonApi:this.photonApi,showQuickSearchButtons:this.showQuickSearchButtons,nostrPhotoFallbackUploads:this.nostrPhotoFallbackUploads,nostrReadRelays:this.nostrReadRelays,nostrWriteRelays:this.nostrWriteRelays};localStorage.setItem("marco:settings",JSON.stringify(e))}update(e,t){e in DEFAULT_SETTINGS&&(this[e]=t,this.saveSettings())}}const amdModule13=Object.freeze(Object.defineProperty({__proto__:null,default:SettingsService},Symbol.toStringTag,{value:"Module"}));var remotestorage$2={exports:{}},remotestorage$1=remotestorage$2.exports,hasRequiredRemotestorage; +/*! For license information please see remotestorage.js.LICENSE.txt */function requireRemotestorage(){return hasRequiredRemotestorage||(hasRequiredRemotestorage=1,function(module,exports$1){var t;t=function(){return function(){var __webpack_modules__={548:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Access=void 0;class r{constructor(e){this.rs=e,this.reset(!1)}get scopes(){return Object.keys(this.scopeModeMap).map(e=>({name:e,mode:this.scopeModeMap[e]}))}get scopeParameter(){return this.scopes.map(e=>`${this._scopeNameForParameter(e)}:${e.mode}`).join(" ")}claim(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if("string"!=typeof t||!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t,this._notifyChange()}get(e){return this.scopeModeMap[e]}remove(e){const t={};for(const r in this.scopeModeMap)t[r]=this.scopeModeMap[r];this.reset(!1),delete t[e];for(const r in t)this._adjustRootPaths(r),this.scopeModeMap[r]=t[r];this._notifyChange()}checkPermission(e,t){const r=this.get(e);return r&&("r"===t||"rw"===r)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const r=this._getModuleName(e);return!!this.checkPermission(r,t)}reset(e=!0){this.rootPaths=[],this.scopeModeMap={},e&&this._notifyChange()}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name}setStorageType(e){this.storageType=e}_notifyChange(){this.rs&&"function"==typeof this.rs._checkScopeChange&&this.rs._checkScopeChange()}static _rs_init(){}}t.Access=r,t.default=r},275:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Authorize=void 0;const o=i(r(28)),s=i(r(334)),a=r(746),l=i(r(503)),c=r(368);let u;function h(e){const t=e||d.getLocation().href,r={};for(const[o,s]of new URL(t).searchParams)r[o]=s;const n=t.indexOf("#");if(-1===n)return r;const i=t.substring(n+1);return i.includes("=")?i.split("&").reduce(function(e,t){const r=t.split("=");if("state"===r[0]&&r[1].match(/rsDiscovery/)){let t=decodeURIComponent(r[1]);const n=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(n)),t=t.replace(new RegExp("&?rsDiscovery="+n),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e},r):r}class d{static authorize(e,t){if((0,s.default)("[Authorize] authURL = ",t.authURL,"scope = ",t.scope,"redirectUri = ",t.redirectUri,"clientId = ",t.clientId,"response_type =",t.response_type),!t.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if("function"==typeof e._rememberPendingScope&&e._rememberPendingScope(t.scope),!(0,a.localStorageAvailable)()&&"remotestorage"===e.backend){t.redirectUri+=t.redirectUri.indexOf("#")>0?"&":"#";const r={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};t.redirectUri+="rsDiscovery="+(0,a.toBase64)(JSON.stringify(r))}const r=function(e){const t=new URL(e.redirectUri);e.state||(e.state=t.hash?t.hash.substring(1):""),e.response_type||(e.response_type="token");const r=new URL(e.authURL);r.searchParams.set("redirect_uri",e.redirectUri.replace(/#.*$/,"")),r.searchParams.set("scope",e.scope),r.searchParams.set("client_id",e.clientId);for(const n of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const t=e[n];t&&r.searchParams.set(n,t)}return r.href}(t);a.globalContext.cordova&&(d.getLocation().href.startsWith("file:")||"string"==typeof o.default.cordovaRedirectUri&&t.redirectUri===o.default.cordovaRedirectUri)?d.openWindow(r,t.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then(r=>{e.remote.configure({token:r.access_token}),"function"==typeof e._completeAuthorization&&e._completeAuthorization(r.scope||t.scope)}):d.setLocation(r)}static refreshAccessToken(e,t,r){return n(this,void 0,void 0,function*(){var e,n,i;yield t.configure({token:null,tokenType:null});const o=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:r}),a=yield(0,c.requestWithTimeout)("POST",t.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),responseType:"json"});if(200!==(null==a?void 0:a.status))throw yield t.configure({refreshToken:null}),new l.default("refresh token rejected:"+JSON.stringify(a.response));{(0,s.default)(`[Authorize] access token good for ${null===(e=null==a?void 0:a.response)||void 0===e?void 0:e.expires_in} seconds`);const r={token:null===(n=null==a?void 0:a.response)||void 0===n?void 0:n.access_token,tokenType:null===(i=null==a?void 0:a.response)||void 0===i?void 0:i.token_type};if(!r.token)throw new Error(`no access_token in "successful" refresh: ${a.response}`);yield t.configure(r)}})}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location.href=e.href}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",u)}}t.Authorize=d,d.IMPLIED_FAKE_TOKEN=!1,d.getLocation=function(){return document.location},d.openWindow=function(e,t,r){return new Promise((n,i)=>{const o=open(e,"_blank",r);function s(){i("Authorization was canceled")}o&&!o.closed?(o.addEventListener("loadstart",function(e){if(0!==e.url.indexOf(t))return;o.removeEventListener("exit",s),o.close();const r=h(e.url);r?n(r):i("Authorization error")}),o.addEventListener("exit",s)):i("Authorization popup was blocked")})},d._rs_init=function(e){const t=h(),r=function(e){return"string"==typeof e.access_token||"string"==typeof e.code||"string"==typeof e.error||"string"==typeof e.remotestorage||"object"==typeof e.rsDiscovery}(t);let i;r&&(i=d.getLocation(),i.hash=""),u=function(){let o=!1;if(r){if(t.error)throw"function"==typeof e._forgetPendingScope&&e._forgetPendingScope(),"access_denied"===t.error?new l.default("Authorization failed: access denied",{code:"access_denied"}):new l.default(`Authorization failed: ${t.error}`);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),"function"==typeof e._completeAuthorization&&e._completeAuthorization(t.scope),o=!0),t.remotestorage&&(e.connect(t.remotestorage),o=!0),t.state&&(i=d.getLocation(),d.setLocation(i.href.split("#")[0]+"#"+t.state)),t.code&&(function(t){n(this,void 0,void 0,function*(){var r,n,o,a,l;const u=sessionStorage.getItem("remotestorage:codeVerifier");if(!u)return void(0,s.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");i=d.getLocation();let h=i.origin;"/"!==i.pathname&&(h+=i.pathname);const p=new URLSearchParams({code:t,grant_type:"authorization_code",client_id:e.remote.clientId,redirect_uri:h,code_verifier:u}),f=yield(0,c.requestWithTimeout)("POST",e.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:p.toString(),responseType:"json"});switch(f.status){case 200:{(0,s.default)(`[Authorize] access token good for ${null===(r=null==f?void 0:f.response)||void 0===r?void 0:r.expires_in} seconds`);const t={token:null===(n=null==f?void 0:f.response)||void 0===n?void 0:n.access_token,refreshToken:null===(o=null==f?void 0:f.response)||void 0===o?void 0:o.refresh_token,tokenType:null===(a=null==f?void 0:f.response)||void 0===a?void 0:a.token_type};t.token?(e.remote.configure(t),"function"==typeof e._completeAuthorization&&e._completeAuthorization(null===(l=null==f?void 0:f.response)||void 0===l?void 0:l.scope)):e._emit("error",new Error(`no access_token in "successful" response: ${f.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier");break}default:"function"==typeof e._forgetPendingScope&&e._forgetPendingScope(),e._emit("error",new Error(`${f.statusText}: ${f.response}`))}})}(t.code),o=!0),o||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",u)},t.default=d},424:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClient=void 0;const o=i(r(439)),s=i(r(613)),a=i(r(491)),l=i(r(93)),c=i(r(28)),u=r(746);class h{constructor(e,t){if(this.schemas={configurable:!0,get(){return h.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t,this.moduleName=function(e){const t=e.split("/");return e.length>2?t[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new h(this.storage,this.makePath(e))}getListing(e,t){return n(this,void 0,void 0,function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(e=>404===e.statusCode?{}:e.body)})}getAll(e,t){return n(this,void 0,void 0,function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,u.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(r=>{if(404===r.statusCode)return{};if("object"==typeof r.body){const n=Object.keys(r.body);if(0===n.length)return{};const i=n.map(n=>this.storage.get(this.makePath(e+n),t).then(e=>{if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"==typeof e.body&&(r.body[n]=e.body)}));return Promise.all(i).then(()=>r.body)}})})}getFile(e,t){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then(e=>({data:e.body,contentType:e.contentType,revision:e.revision}))})}storeFile(e,t,r){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'contentType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))})}getObject(e,t){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then(t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))})})}storeObject(e,t,r){return n(this,void 0,void 0,function*(){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{const e=this.validate(r);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))})}remove(e){return n(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e),this.storage.connected))})}getItemURL(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=(0,u.cleanPath)(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this}declareType(e,t,r){let n;if(r&&"string"==typeof t)n=t;else if(r||"string"==typeof t){if(!r&&"string"==typeof t)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else r=t,n=this._defaultTypeURI(e);h.Types.declare(this.moduleName,e,n,r)}validate(e){const t=h.Types.getSchema(e["@context"]);if(t)return o.default.validateResult(e,t);throw new a.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=h.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){c.default.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach(function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}}),this._emit("change",e))}static _rs_init(){}}t.BaseClient=h,h.Types=s.default,(0,u.applyMixins)(h,[l.default]),t.default=h},285:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Caching=void 0;const i=r(746),o=n(r(334));class s{constructor(e){this.pendingActivations=[],this._access=e.access,this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!(0,i.isFolder)(e))throw new Error("path should be a folder");if(!this._access.checkPathPermission(e,"r"))throw new Error('No access to path "'+e+'". You must claim access to it first.');if(void 0===t||!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))}enable(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){(0,o.default)("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t{this.emitChange(e.data)})}get(e,t,r){return n(this,void 0,void 0,function*(){return"number"==typeof t?this.getNodes((0,c.pathsFromRoot)(e)).then(n=>{const i=u(n[e]);return h(n,t)?r(e):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}}):this.getNodes([e]).then(t=>{const r=u(t[e]);if(r){if((0,c.isFolder)(e))for(const e in r.itemsMap)r.itemsMap.hasOwnProperty(e)&&!1===r.itemsMap[e]&&delete r.itemsMap[e];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}})})}put(e,t,r){return n(this,void 0,void 0,function*(){const n=(0,c.pathsFromRoot)(e);return this._updateNodes(n,function(e,n){try{for(let i=0,o=e.length;i0)break}else console.error("Cannot delete non-existing node "+i)}return r})})}flush(e){return this._getAllDescendentPaths(e).then(e=>this.getNodes(e)).then(e=>{for(const t in e){const r=e[t];r&&r.common&&r.local&&this.emitChange({path:r.path,origin:"local",oldValue:!1===r.local.body?void 0:r.local.body,newValue:!1===r.common.body?void 0:r.common.body}),e[t]=void 0}return this.setNodes(e)})}emitChange(e){a.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){a.default.changeEvents.local&&this.forAllNodes(e=>{if((0,c.isDocument)(e.path)){const t=u(e);t&&this.emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}}).then(()=>{this._emit("local-events-done")})}onDiff(e){this.diffHandler=e}_updateNodes(e,t){return new Promise((r,n)=>{this._doUpdateNodes(e,t,{resolve:r,reject:n})})}_doUpdateNodes(e,t,r){return n(this,void 0,void 0,function*(){if(this._updateNodesRunning)return void this._updateNodesQueued.push({paths:e,cb:t,promise:r});this._updateNodesRunning=!0;try{let n=yield this.getNodes(e);const i=(0,c.deepClone)(n),o=[];n=t(e,n);for(const e in n){const t=n[e];(0,c.equal)(t,i[e])?delete n[e]:(0,c.isDocument)(e)&&((0,c.equal)(t.local.body,t.local.previousBody)&&t.local.contentType===t.local.previousContentType||o.push({path:e,origin:"window",oldValue:t.local.previousBody,newValue:!1===t.local.body?void 0:t.local.body,oldContentType:t.local.previousContentType,newContentType:t.local.contentType}),void 0===t.local.body?n[e]=void 0:(delete t.local.previousBody,delete t.local.previousContentType))}yield this.setNodes(n),this._emitChangeEvents(o),r.resolve({statusCode:200})}catch(e){r.reject(e)}this._updateNodesRunning=!1;const n=this._updateNodesQueued.shift();n&&(yield this._doUpdateNodes(n.paths,n.cb,n.promise))})}_emitChangeEvents(e){for(let t=0,r=e.length;t{const r=[e],n=u(t[e]),i=Object.keys(n.itemsMap).map(t=>this._getAllDescendentPaths(e+t).then(e=>{for(let t=0,n=e.length;tr)}):Promise.resolve([e])}_getInternals(){return{getLatest:u,makeNode:d,isOutdated:h}}}(0,c.applyMixins)(f,[s.default]),e.exports=f},28:function(e){e.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},373:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(713)),o=n(r(28)),s=n(r(334)),a=r(746);let l;const c="remotestorage:discover";let u={};const h=function(e){if(e in u)return Promise.resolve(u[e]);const t=new i.default({tls_only:!1,uri_fallback:!0,request_timeout:o.default.discoveryTimeout});let r;const n=new Promise((e,t)=>{r=setTimeout(()=>{t(new Error("timed out"))},o.default.discoveryTimeout)});return Promise.race([t.lookup(e),n]).then(t=>{if(clearTimeout(r),"object"!=typeof t.idx.links.remotestorage||"number"!=typeof t.idx.links.remotestorage.length||t.idx.links.remotestorage.length<=0)throw(0,s.default)("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(t.object)),new Error("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const n=t.idx.links.remotestorage[0],i=n.properties||{},o=i["http://tools.ietf.org/html/rfc6749#section-4.2"]||i["auth-endpoint"],a=i["http://remotestorage.io/spec/version"]||n.type;return u[e]={href:n.href,storageApi:a,authURL:o,properties:i},l&&localStorage.setItem(c,JSON.stringify({cache:u})),u[e]}).catch(e=>{throw clearTimeout(r),e})};(h.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),h.DiscoveryError.prototype.constructor=h.DiscoveryError,h._rs_init=function(){if(l=(0,a.localStorageAvailable)(),l){const e=JSON.parse(localStorage.getItem(c));e&&(u=e.cache)}},h._rs_supported=function(){return Object.prototype.hasOwnProperty.call(a.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(a.globalContext,"XMLHttpRequest")},h._rs_cleanup=function(){l&&localStorage.removeItem(c)},e.exports=h},706:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(424)),a=i(r(941)),l=i(r(982)),c=i(r(503)),u=r(746),h=r(368),d=r(684),p=i(r(275));let f;const g="remotestorage:dropbox",m="https://api.dropboxapi.com/2/files/list_folder",y="https://api.dropboxapi.com/2/files/list_folder/continue",b="/remotestorage";function v(e){return(b+"/"+e).replace(/\/+$/,"").replace(/\/+/g,"/")}const _=/[\u007f-\uffff]/g;function E(e){return JSON.stringify(e).replace(_,function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)})}function w(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function C(e){return e instanceof ArrayBuffer||(0,h.isArrayBufferView)(e)}class S extends d.RemoteBase{constructor(e){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new a.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},f=(0,u.localStorageAvailable)(),f){const e=(0,u.getJSONFromLocalStorage)(g);e&&this.configure(e),this._itemRefs=(0,u.getJSONFromLocalStorage)(`${g}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return n(this,void 0,void 0,function*(){try{if(this.rs.setBackend("dropbox"),this.token)R(this.rs);else{const{codeVerifier:e,codeChallenge:t,state:r}=yield(0,u.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",e),sessionStorage.setItem("remotestorage:state",r),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:r,code_challenge:t,code_challenge_method:"S256",token_access_type:"offline"})}}catch(e){throw this.rs._emit("error",e),this.rs.setBackend(void 0),e}})}configure(e){return n(this,void 0,void 0,function*(){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token),void 0!==e.refreshToken&&(this.refreshToken=e.refreshToken),void 0!==e.tokenType&&(this.tokenType=e.tokenType);const t=()=>{f&&localStorage.setItem(g,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),t();else try{const e=yield this.info();this.userAddress=e.email,this._emit("connected"),t()}catch(e){this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),t.apply(this)}else(()=>{this.connected=!1,f&&localStorage.removeItem(g),this.rs.setBackend(void 0)})()})}_getFolder(e){const t=this._revCache,r=r=>{let i;if(200!==r.status&&409!==r.status)return Promise.reject("Unexpected response status: "+r.status);try{i=JSON.parse(r.responseText)}catch(e){return Promise.reject(e)}if(409===r.status)return w(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary));const o=i.entries.reduce((r,n)=>{try{const i="folder"===n[".tag"],o=n.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)r[o]={ETag:t.get(e+o)};else{const t=new Date(n.server_modified);r[o]={ETag:n.rev,"Content-Length":n.size,"Last-Modified":t.toUTCString()},this._revCache.set(e+o,n.rev)}}catch(t){console.error(`[Dropbox] folder “${e}” has entry ${JSON.stringify(n)}:`,t)}return r},{});return i.has_more?n(i.cursor).then(function(e){return Object.assign(o,e)}):Promise.resolve(o)},n=e=>{const t={body:{cursor:e}};return this._request("POST",y,t).then(r)};return this._request("POST",m,{body:{path:v(e)}}).then(r).then(function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})})}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r=this._revCache.get(e);if(null===r)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then(()=>this.get(e,t));if(r&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.slice(-1))return this._getFolder(e);const n={headers:{"Dropbox-API-Arg":E({path:v(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(n.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",n).then(t=>{const r=t.status;let n,i,o,s;return 200!==r&&409!==r?Promise.resolve({statusCode:r}):(n=t.getResponseHeader("Dropbox-API-Result"),(0,u.getTextFromArrayBuffer)(t.response,"UTF-8").then(a=>{i=a,409===r&&(n=i);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===r)return w(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(o=t.getResponseHeader("Content-Type"),s=n.rev,this._revCache.set(e,s),this._shareIfNeeded(e),(0,u.shouldBeTreatedAsBinary)(a,o))i=t.response;else try{i=JSON.parse(i),o="application/json; charset=UTF-8"}catch(e){}return{statusCode:r,body:i,contentType:o,revision:s}}))})}put(e,t,r){return n(this,arguments,void 0,function*(e,t,r,n={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const i=this._revCache.get(e);if(n&&n.ifMatch&&i&&i!==n.ifMatch)return{statusCode:412,revision:i};if(n&&"*"===n.ifNoneMatch&&i&&"rev"!==i)return{statusCode:412,revision:i};if(!r.match(/charset=/)&&C(t)&&(r+="; charset=binary"),t.length>157286400)throw new Error("Cannot upload file larger than 150MB");const o={body:t,contentType:r,path:e};if(n&&(n.ifMatch||"*"===n.ifNoneMatch)){const t=yield this._getMetadata(e);if(n&&"*"===n.ifNoneMatch&&t)return{statusCode:412,revision:t.rev};if(n&&n.ifMatch&&t&&t.rev!==n.ifMatch)return{statusCode:412,revision:t.rev}}const s=yield this._uploadSimple(o);return this._shareIfNeeded(e),s})}delete(e){return n(this,arguments,void 0,function*(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const r=this._revCache.get(e);if((null==t?void 0:t.ifMatch)&&r&&t.ifMatch!==r)return{statusCode:412,revision:r};if(null==t?void 0:t.ifMatch){const r=yield this._getMetadata(e);if((null==t?void 0:t.ifMatch)&&r&&r.rev!==t.ifMatch)return{statusCode:412,revision:r.rev}}return this._deleteSimple(e)})}_shareIfNeeded(e){if(e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e])return this.share(e)}share(e){const t={body:{path:v(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?w(r,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+r.error_summary)):Promise.resolve(r.url)}).then(t=>(this._itemRefs[e]=t,f&&localStorage.setItem(g+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t)),t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t)))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then(function(e){let t;try{const r=JSON.parse(e.responseText);t=null==r?void 0:r.email}catch(t){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+e.responseText))}return Promise.resolve({email:t})})}_request(e,t,r){return n(this,arguments,void 0,function*(e,t,r,n=1){if(this.isForbiddenRequestMethod(e,t))throw`Don't use ${e} on directories!`;if(!this.token)throw new c.default("No access token");r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!=typeof r.body||C(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)});try{const i=yield(0,h.requestWithTimeout)(e,t,r);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),401===(null==i?void 0:i.status)&&this.refreshToken?n>=3?(console.error(`Abandoned after ${n} attempts: ${e} ${t}`),i):(this.rs._emit("wire-busy",{method:e,isFolder:(0,u.isFolder)(t)}),yield p.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!0}),this._request(e,t,r,n+1)):[503,429].includes(null==i?void 0:i.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),n>=3?(console.warn(`Abandoned after ${n} attempts: ${e} ${t}`),i):(yield new Promise(e=>setTimeout(e,(0,h.retryAfterMs)(i))),this._request(e,t,r,n+1))):i}catch(r){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,u.isFolder)(t),success:!1}),r}})}fetchDelta(...e){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const t=e=>n(this,void 0,void 0,function*(){let r,n;"string"==typeof e?(r=y,n={cursor:e}):(r=m,n={path:b,recursive:!0,include_deleted:!0});try{const i=yield this._request("POST",r,{body:n});if(401===i.status)throw new c.default;if(200!==i.status&&409!==i.status)throw new Error("Invalid response status: "+i.status);let o;try{o=JSON.parse(i.responseText)}catch(e){throw new Error("Invalid response body: "+i.responseText)}if(409===i.status){if(!w(o,["path","not_found"]))throw new Error("API returned an error: "+o.error_summary);o={cursor:null,entries:[],has_more:!1}}if(e||this._revCache.deactivatePropagation(),o.entries.forEach(e=>{const t=e.path_display.slice(14);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)}),this._fetchDeltaCursor=o.cursor,o.has_more)return t(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(e){if("timeout"===e)return;throw e}});return this._fetchDeltaPromise=t(this._fetchDeltaCursor).catch(e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e=`Dropbox: fetchDelta: ${e}`,this.rs._emit("error",e),this._fetchDeltaPromise=null,Promise.reject(e))).then(()=>(this._fetchDeltaPromise=null,Promise.resolve(e))),this._fetchDeltaPromise}_getMetadata(e){const t={path:v(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?w(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)}).then(void 0,t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_uploadSimple(e){const t={path:v(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":E(t)}}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let r;try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject(new Error("Invalid API result: "+t.responseText))}return 409===t.status?w(r,["path","conflict"])?this._getMetadata(e.path).then(function(e){return Promise.resolve({statusCode:412,revision:e.rev})}):(this.rs._emit("error",new Error(r.error_summary)),Promise.resolve({statusCode:t.status})):(this._revCache.set(e.path,r.rev),Promise.resolve({statusCode:t.status,revision:r.rev}))})}_deleteSimple(e){const t={path:v(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}if(409===e.status){if(w(t,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(t.error_summary))}return Promise.resolve({statusCode:e.status})}).then(t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t)),t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_getSharedLink(e){return n(this,void 0,void 0,function*(){const t={body:{path:v(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+(null==t?void 0:t.error_summary)||0)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))},t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t)))})}static _rs_init(e){f=(0,u.localStorageAvailable)(),e.apiKeys.dropbox&&(e.dropbox=new S(e)),"dropbox"===e.backend&&R(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(e){(function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)})(e),function(e){e._dropboxOrigSync&&(e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}(e),function(e){e._origBaseClientGetItemURL&&(s.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),x(e)}(e),f&&localStorage.removeItem(g),e.setBackend(void 0)}}function T(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,function(t){e._emit("error",new l.default(t)),e._emit("sync-done",{completed:!1})})}.bind(e))}function x(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function R(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?T(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");T(e),e._dropboxOrigSyncCycle(e,...t),x(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=s.default.prototype.getItemURL,s.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}(0,u.applyMixins)(S,[o.default]),e.exports=S},451:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=r(746),s=n(r(334));class a{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?((0,s.default)("[Env] Going into background mode"),this.goBackground()):((0,s.default)("[Env] Going into foreground mode"),this.goForeground())}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,o.applyMixins)(a,[i.default]),e.exports=a},93:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandling=void 0;const i=n(r(334));class o{addEvents(e){e.forEach(e=>this._addEvent(e))}addEventListener(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");(0,i.default)("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const r=this._handlers[e].length;for(let n=0;n{e(...t)})}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,t=>{this._emit(e,t)})}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}t.EventHandling=o,t.default=o},545:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(28)),o=n(r(451)),s=n(r(334)),a=r(746),l=n(r(370)),c=n(r(548)),u=n(r(275)),h=n(r(373)),d=n(r(424)),p=n(r(801)),f=n(r(706)),g=n(r(600)),m=n(r(313)),y=n(r(285)),b=n(r(567)),v=n(r(794)),_=n(r(365)),E={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:g.default,Dropbox:f.default,GoogleDrive:p.default,Access:c.default,Discover:h.default,Authorize:u.default,BaseClient:d.default,Env:o.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:y.default,IndexedDB:b.default,LocalStorage:v.default,InMemoryStorage:_.default,Sync:m.default}),i.default.disableFeatures.forEach(e=>{this.featureModules[e]&&delete this.featureModules[e]}),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const t=this.featureModules[e],r=!t._rs_supported||t._rs_supported();(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof r?r.then(()=>{this.featureSupported(e,!0),this.initFeature(e)},()=>{this.featureSupported(e,!1)}):"boolean"==typeof r?(this.featureSupported(e,r),r&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const t=this.featureModules[e];let r;try{r=t._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof r&&"function"==typeof r.then?r.then(()=>{this.featureInitialized(e)},t=>{this.featureFailed(e,t)}):this.featureInitialized(e)},featureFailed(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){(0,s.default)(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){(0,s.default)(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some(e=>{if(this.features.some(t=>t.name===e))return this.features.local=this.featureModules[e],!0})},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){(0,s.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(l.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",()=>{this._fireReady(),this._emit("connected")}),this.remote.on("not-connected",()=>{this._fireReady(),this._emit("not-connected")}),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){(0,a.logError)(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e=r-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class b extends l.RemoteBase{constructor(e,t){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=t,this._fileIdCache=new y(300),d=(0,s.localStorageAvailable)(),d){const e=(0,s.getJSONFromLocalStorage)(u);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){d&&localStorage.setItem(u,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,delete this.token,d&&localStorage.removeItem(u)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then(e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)}).catch(()=>{r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))})):r.apply(this)}connect(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})}get(e,t={}){return(0,s.isFolder)(e)?this._getFolder(m(e)):this._getFile(m(e),t)}put(e,t,r,n={}){const i=m(e);function o(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),r=this.stripQuotes(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(i).then(e=>e?n&&"*"===n.ifNoneMatch?o({status:412}):this._updateFile(e,i,t,r,n).then(o):this._createFile(i,t,r).then(o))}delete(e,t={}){const r=m(e);return this._getFileId(r).then(e=>e?this._getMeta(e).then(r=>{let n;return"object"==typeof r&&"string"==typeof r.etag&&(n=this.stripQuotes(r.etag)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:this._request("DELETE",c+"/drive/v2/files/"+e,{}).then(e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")"))}):Promise.resolve({statusCode:200}))}info(){const e=c+"/drive/v2/about?fields=user";return this._request("GET",e,{}).then(function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}})}_updateFile(e,t,r,n,i){const o={mimeType:n},s={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(s["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",c+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(o),headers:s}).then(e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r}))}_createFile(e,t,r){return this._getParentId(e).then(n=>{const i={title:p(g(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:n}]};return this._request("POST",c+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>this._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t}))})}_getFile(e,t){return this._getFileId(e).then(e=>this._getMeta(e).then(e=>{let r;if("object"==typeof e&&"string"==typeof e.etag&&(r=this.stripQuotes(e.etag)),t&&t.ifNoneMatch&&r===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:r});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then(t=>(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then(function(n){let i=n;if(e.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch(e){}else(0,s.shouldBeTreatedAsBinary)(n,e.mimeType)&&(i=t.response);return{statusCode:200,body:i,contentType:e.mimeType,revision:r}}))}))}_getFolder(e){return this._getFileId(e).then(t=>{let r,n,i;if(!t)return Promise.resolve({statusCode:404});const o="'"+t+"' in parents";return this._request("GET",c+"/drive/v2/files?q="+encodeURIComponent(o)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then(t=>{var o;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{r=JSON.parse(t.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}i={};for(const a of r.items)(null===(o=a.labels)||void 0===o?void 0:o.trashed)||(n=this.stripQuotes(a.etag),a.mimeType===h?(this._fileIdCache.set(e+(0,s.cleanPath)(a.title)+"/",a.id),i[a.title+"/"]={ETag:n}):(this._fileIdCache.set(e+(0,s.cleanPath)(a.title),a.id),i[a.title]={ETag:n,"Content-Type":a.mimeType,"Content-Length":a.fileSize}));return Promise.resolve({statusCode:200,body:i,contentType:"application/json; charset=UTF-8",revision:void 0})})})}_getParentId(e){const t=f(e);return this._getFileId(t).then(e=>e?Promise.resolve(e):this._createFolder(t))}_createFolder(e){return this._getParentId(e).then(t=>this._request("POST",c+"/drive/v2/files",{body:JSON.stringify({title:p(g(e)),mimeType:h,parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(f(e)).then(()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then(()=>this._getFileId(e)):Promise.resolve()))}_getMeta(e){return this._request("GET",c+"/drive/v2/files/"+e,{}).then(function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)})}_request(e,t,r){return this.isForbiddenRequestMethod(e,t)?Promise.reject(`Don't use ${e} on directories!`):(r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,a.requestWithTimeout)(e,t,r).then(r=>r&&401===r.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),Promise.resolve(r)),r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(r))))}static _rs_init(e){const t=e.apiKeys.googledrive;var r;t&&(e.googledrive=new b(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(r=e)._origBaseClientGetItemURL||(r._origBaseClientGetItemURL=i.default.prototype.getItemURL,i.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(i.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,s.applyMixins)(b,[o.default]),e.exports=b},567:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(93)),s=i(r(496)),a=i(r(334)),l=r(746),c="remotestorage";let u;class h extends s.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||u,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,a.default)("[IndexedDB] Failed to open DB")}getNodes(e){return n(this,void 0,void 0,function*(){const t=[],r={};for(let n=0,i=e.length;n0?this.getNodesFromDb(t).then(function(e){for(const t in r)e[t]=r[t];return e}):r})}setNodes(e){return n(this,void 0,void 0,function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;this.maybeFlush()})}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=r.g.setInterval(function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")},1e4))}flushChangesQueued(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))}getNodesFromDb(e){return new Promise((t,r)=>{const n=this.db.transaction(["nodes"],"readonly"),i=n.objectStore("nodes"),o={};this.getsRunning++,e.map(e=>{i.get(e).onsuccess=t=>{o[e]=t.target.result}}),n.oncomplete=()=>{t(o),this.getsRunning--},n.onerror=n.onabort=()=>{r("get transaction error/abort"),this.getsRunning--}})}setNodesInDb(e){return n(this,void 0,void 0,function*(){return new Promise((t,r)=>{const n=this.db.transaction(["nodes"],"readwrite"),i=n.objectStore("nodes"),o=(new Date).getTime();this.putsRunning++,(0,a.default)("[IndexedDB] Starting puts",e,this.putsRunning);for(const s in e){const t=e[s];if("object"==typeof t)try{i.put(t)}catch(e){throw(0,a.default)("[IndexedDB] Error while putting",t,e),e}else try{i.delete(s)}catch(e){throw(0,a.default)("[IndexedDB] Error while removing",i,t,e),e}}n.oncomplete=()=>{this.putsRunning--,(0,a.default)("[IndexedDB] Finished puts",e,this.putsRunning,(new Date).getTime()-o+"ms"),t()},n.onerror=()=>{this.putsRunning--,r("transaction error")},n.onabort=()=>{r("transaction abort"),this.putsRunning--}})})}reset(e){const t=this.db.name;this.db.close(),h.clean(t,()=>{h.open(t,(r,n)=>{r?(0,a.default)(`[IndexedDB] Error while resetting database ${t}:`,r):this.db=n,"function"==typeof e&&e(self)})})}forAllNodes(e){return n(this,void 0,void 0,function*(){return new Promise(t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=r=>{const n=r.target.result;n?(e(n.value),n.continue()):t()}})})}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const r=setTimeout(function(){t("timeout trying to open db")},1e4);try{const n=indexedDB.open(e,2);n.onerror=function(){(0,a.default)("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){const t=n.result;(0,a.default)("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),t.objectStoreNames.contains("nodes")||((0,a.default)("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),t.objectStoreNames.contains("changes")||((0,a.default)("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"}))},n.onsuccess=function(){clearTimeout(r);const i=n.result;if(!i.objectStoreNames.contains("nodes")||!i.objectStoreNames.contains("changes"))return(0,a.default)("[IndexedDB] Missing object store. Resetting the database."),i.close(),void h.clean(e,function(){h.open(e,t)});t(null,n.result)}}catch(n){(0,a.default)("[IndexedDB] Failed to open database: "+n),(0,a.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(r),h.clean(e,function(){h.open(e,t)})}}static clean(e,t){const r=indexedDB.deleteDatabase(e);r.onblocked=function(t){console.warn(`Deleting IndexedDB database "${e}" is blocked by another open connection`,t)},r.onsuccess=function(){(0,a.default)(`[IndexedDB] Deleted database "${e}"`),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise((t,r)=>{h.open(c,function(n,i){if(n)r(n);else{if(!i)return void r(new Error("IndexedDB opened without a database instance"));u=i,i.onerror=t=>{e._emit("error",h.eventToError(t))},t()}})})}static _rs_supported(){return new Promise((e,t)=>{const r=(0,l.getGlobalContext)();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{const r=indexedDB.open("rs-check");r.onerror=function(){t()},r.onsuccess=function(){r.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()})}static _rs_cleanup(e){return new Promise(t=>{e.local instanceof h&&e.local.closeDB(),h.clean(c,t)})}static eventToError(e){var t;const r=null==e?void 0:e.target,n=null==r?void 0:r.error;if(n)return n;if(null===(t=null==r?void 0:r.db)||void 0===t?void 0:t.name){const e=r.objectStoreNames,t=e?Array.from(e).join(", "):"";return new Error(`Error in store(s) “${t}” in database “${r.db.name}”`)}return new Error("Unknown IndexedDB error")}diffHandler(){}}(0,l.applyMixins)(h,[o.default]),e.exports=h},365:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=n(r(93)),o=n(r(496)),s=r(746);class a extends o.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let r=0,n=e.length;r=2e3&&e<=36e5}var k;!function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(k||(k={}));class O{constructor(e){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=E.default.loadFeatures,this.features=E.default.features,this.loadFeature=E.default.loadFeature,this.featureSupported=E.default.featureSupported,this.featureDone=E.default.featureDone,this.featuresDone=E.default.featuresDone,this.featuresLoaded=E.default.featuresLoaded,this.featureInitialized=E.default.featureInitialized,this.featureFailed=E.default.featureFailed,this.hasFeature=E.default.hasFeature,this._setCachingModule=E.default._setCachingModule,this._collectCleanupFunctions=E.default._collectCleanupFunctions,this._fireReady=E.default._fireReady,this.initFeature=E.default.initFeature,"object"==typeof e&&(0,u.extend)(l.default,e),this.addEvents(["ready","authing","connecting","connected","disconnected","not-connected","conflict","error","features-loaded","scope-change-required","sync-interval-change","sync-started","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),S=(0,u.localStorageAvailable)(),S){this.apiKeys=(0,u.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const e=localStorage.getItem("remotestorage:backend");"dropbox"===e||"googledrive"===e?this.setBackend(e):this.setBackend("remotestorage")}this._authorizedScope=this._loadAuthorizedScope(),this._scopeChangeRequired=!1,this._scopeChangeEvent=null;const t=this.on;this.on=function(e,r){const n=t.call(this,e,r);if("scope-change-required"===e&&this._scopeChangeRequired&&this._scopeChangeEvent&&setTimeout(()=>{r(this._scopeChangeEvent)},0),this._allLoaded)switch(e){case"features-loaded":setTimeout(r,0);break;case"ready":this.remote&&setTimeout(r,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(r,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(r,0)}return n},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}get scopeChangeRequired(){return this._scopeChangeRequired}loadModules(){l.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),C.cordova&&"string"==typeof l.default.cordovaRedirectUri)e.redirectUri=l.default.cordovaRedirectUri;else{const t=d.default.getLocation();let r=t.origin;"/"!==t.pathname&&(r+=t.pathname),e.redirectUri=r}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),d.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),(0,c.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:d.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s\/$\.?#]+\.[^\s]*$/))this._emit("error",new O.DiscoveryError("Not a valid user address or URL."));else{if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e=`https://${e}`),C.cordova){if("string"!=typeof l.default.cordovaRedirectUri)return void this._emit("error",new O.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!C.cordova.InAppBrowser)return void this._emit("error",new O.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting"),O.Discover(e).then(r=>{if(this._emit("authing"),r.userAddress=e,this.remote.configure(r),!this.remote.connected)if(r.authURL)if(void 0===t)this.authorize({authURL:r.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");(0,c.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t}),this._rememberAuthorizedScope(this.access.scopeParameter)}else this.impliedauth()},()=>{this._emit("error",new O.DiscoveryError("No storage information found for this user address."))})}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}reauthorize(){this.reconnect()}disconnect(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._forgetPendingScope(),this._rememberAuthorizedScope(null),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});const e=this._cleanups.length;let t=0;const r=()=>{t++,t>=e&&(this._init(),(0,c.default)('Cleanups done, emitting "disconnected" event'),this._emit("disconnected"))};e>0?this._cleanups.forEach(e=>{const t=e(this);"object"==typeof t&&"function"==typeof t.then?t.then(r):r()}):r()}setBackend(e){if(this.backend=e,S&&(void 0!==e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend")),void 0===e)return this._authorizedScope=null,this._scopeChangeRequired=!1,void(this._scopeChangeEvent=null);this._authorizedScope=this._loadAuthorizedScope(),this._checkScopeChange()}_rememberPendingScope(e){const t=R(e);S&&(t&&this.backend?localStorage.setItem(x,JSON.stringify({backend:this.backend,scope:t})):localStorage.removeItem(x))}_forgetPendingScope(){S&&localStorage.removeItem(x)}_rememberAuthorizedScope(e){const t=R(e);return S?t&&this.backend?(localStorage.setItem(T,JSON.stringify({backend:this.backend,scope:t})),this._authorizedScope=t,void this._checkScopeChange()):(localStorage.removeItem(T),this._authorizedScope=null,void this._checkScopeChange()):(this._authorizedScope=t,void this._checkScopeChange())}_completeAuthorization(e){const t=this._loadPendingScope()||R(e);this._forgetPendingScope(),t?this._rememberAuthorizedScope(t):this._checkScopeChange()}_checkScopeChange(){const e=R(this.access.scopeParameter),t=this._authorizedScope||this._loadAuthorizedScope(),r=!(!e||!t||e===t),n=r&&(!this._scopeChangeRequired||!this._scopeChangeEvent||this._scopeChangeEvent.requestedScope!==e||this._scopeChangeEvent.authorizedScope!==t);this._scopeChangeRequired=r,r?(this._scopeChangeEvent=this._buildScopeChangeEvent(e,t),n&&this._emit("scope-change-required",this._scopeChangeEvent)):this._scopeChangeEvent=null}_loadAuthorizedScope(){if(!S||!this.backend)return null;const e=A(T);return e&&e.backend===this.backend?R(e.scope):null}_loadPendingScope(){if(!S||!this.backend)return null;const e=A(x);return e&&e.backend===this.backend?R(e.scope):null}_buildScopeChangeEvent(e=R(this.access.scopeParameter),t=this._authorizedScope){return{requestedScope:e||"",authorizedScope:t||"",reauthorize:this.reauthorize.bind(this)}}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){l.default.logging=!0}disableLog(){l.default.logging=!1}log(...e){c.default.apply(O,e)}setApiKeys(e){const t=[k.GOOGLE,k.DROPBOX];if("object"!=typeof e||!Object.keys(e).every(e=>t.includes(e)))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach(t=>{const r=e[t];if(r){switch(t){case k.DROPBOX:this.apiKeys[k.DROPBOX]={appKey:r},void 0!==this.dropbox&&this.dropbox.clientId===r||y.default._rs_init(this);break;case k.GOOGLE:this.apiKeys[k.GOOGLE]={clientId:r},void 0!==this.googledrive&&this.googledrive.clientId===r||m.default._rs_init(this)}return!0}delete this.apiKeys[t]}),S&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");l.default.cordovaRedirectUri=e}_setGPD(e,t){function r(e){return function(...r){return e.apply(t,r).then(I.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)}_pendingGPD(e){return(...t)=>{const r=Array.prototype.slice.call(t);return new Promise((t,n)=>{this._pending.push({method:e,args:r,promise:{resolve:t,reject:n}})})}}_processPending(){this._pending.forEach(e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}}),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach(r=>{const n=r.length;t.path.substr(0,n)===r&&this._pathHandlers[e][r].forEach(e=>{const n={};for(const r in t)n[r]=t[r];n.relativePath=t.path.replace(new RegExp("^"+r),"");try{e(n)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}})})}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestorage.io/rs.js/docs/api/access/classes/Access.html#claim"),new p.default(this,e)}getSyncInterval(){return l.default.syncInterval}setSyncInterval(e){if(!P(e))throw e+" is not a valid sync interval";const t=l.default.syncInterval;l.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return l.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!P(e))throw e+" is not a valid sync interval";const t=l.default.backgroundSyncInterval;l.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return l.default.isBackground?l.default.backgroundSyncInterval:l.default.syncInterval}getRequestTimeout(){return l.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";l.default.requestTimeout=e}setupSyncCycle(){this.sync&&!this.sync.stopped&&((0,c.default)("[Sync] Setting up sync cycle"),this.on("sync-done",()=>{(0,c.default)("[Sync] Sync done. Setting timer to",this.getCurrentSyncInterval()),this.sync&&!this.sync.stopped&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}),this.sync.sync())}startSync(){return l.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?((0,c.default)("[Sync] Stopping sync"),this.sync.stopped=!0):((0,c.default)("[Sync] Will instantiate sync stopped"),this.syncStopped=!0)}addModule(e){const t=e.name,r=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,r);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/\-[a-z]/g,function(e){return e[1].toUpperCase()});Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t)return t(new p.default(this,"/"+e+"/"),new p.default(this,"/public/"+e+"/")).exports;throw"Unknown module: "+e}}t.RemoteStorage=O,O.SyncError=v.default,O.Unauthorized=_.default,O.Discover=b.default,O.DiscoveryError=b.default.DiscoveryError,O.util=w,Object.defineProperty(O.prototype,"access",{configurable:!0,get:function(){const e=new h.default(this);return Object.defineProperty(this,"access",{value:e,writable:!0,configurable:!0}),e}}),Object.defineProperty(O.prototype,"caching",{configurable:!0,get:function(){const e=new f.default(this);return Object.defineProperty(this,"caching",{value:e,writable:!0,configurable:!0}),e}}),(0,u.applyMixins)(O,[g.EventHandling]),t.default=O},368:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayBufferView=void 0,t.retryAfterMs=function(e){const t=1e3*parseInt(e.getResponseHeader("Retry-After"));return t>=1e3?t:Math.max(1500,Math.min(6e4,Math.round(s.default.syncInterval/(2.9+.2*Math.random()))))},t.requestWithTimeout=function(e,r,i){return n(this,void 0,void 0,function*(){return"function"==typeof fetch?function(e,t,r){return n(this,void 0,void 0,function*(){const n="function"==typeof AbortController?new AbortController:null;let i;const a=new Promise((e,t)=>{i=setTimeout(()=>{n&&n.abort(),t("timeout")},s.default.requestTimeout)});let l;const c={},u=fetch(t,{method:e,headers:r.headers,body:r.body,signal:n?n.signal:void 0}).then(e=>{switch((0,o.default)("[requests fetch]",e),e.headers.forEach((e,t)=>{c[t.toUpperCase()]=e}),l={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>c[e.toUpperCase()]||null,responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}}).then(e=>(l.response=e,r.responseType&&"text"!==r.responseType||(l.responseText=e),l)).finally(()=>{clearTimeout(i)});return Promise.race([u,a])})}(e,r,i):"function"==typeof XMLHttpRequest?function(e,r,i){return n(this,void 0,void 0,function*(){return new Promise((n,a)=>{(0,o.default)("[requests XHR]",e,r);let l=!1;const c=setTimeout(()=>{l=!0,a("timeout")},s.default.requestTimeout),u=new XMLHttpRequest;if(u.open(e,r,!0),i.responseType&&(u.responseType=i.responseType),i.headers)for(const e in i.headers)u.setRequestHeader(e,i.headers[e]);u.onload=()=>{l||(clearTimeout(c),n(u))},u.onerror=e=>{l||(clearTimeout(c),a(e))};let h=i.body;"object"==typeof h&&!(0,t.isArrayBufferView)(h)&&h instanceof ArrayBuffer&&(h=new Uint8Array(h)),u.send(h)})})}(e,r,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")})};const o=i(r(334)),s=i(r(28));if("function"==typeof(r.g||window).ArrayBufferView)t.isArrayBufferView=function(e){return e&&e instanceof(r.g||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];t.isArrayBufferView=function(t){for(let r=0;r<8;r++)if(t instanceof e[r])return!0;return!1}}},941:function(e){e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let r=0;r0&&(r=this._generateHash(e))}return this.set(e,r),r}}},491:function(e){class t extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=t},982:function(e){class t extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=t},313:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Sync=void 0;const o=i(r(28)),s=i(r(451)),a=i(r(93)),l=i(r(334)),c=i(r(275)),u=i(r(982)),h=i(r(503)),d=r(746);let p,f;function g(e,t,r){return{action:e,path:t,promise:r}}function m(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function y(e){return!!e.common&&!!e.common.revision}class b{constructor(e){this.numThreads=10,this._tasks={},this._running={},this._timeStarted={},this._finishedTasks=[],this.rs=e,this.rs.local.onDiff(e=>{this.addTask(e),this.doTasks()}),this.rs.caching.onActivate(e=>{this.addTask(e),this.doTasks()}),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return n(this,void 0,void 0,function*(){return new Promise((t,r)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then(e=>t(e))}.bind(this)),this.doTasks()):r("cannot fulfill maxAge requirement - remote is not online"):r("cannot fulfill maxAge requirement - remote is not connected")})})}corruptServerItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e){const r=e[t];if("object"!=typeof r)return!0;if("string"!=typeof r.ETag)return!0;if((0,d.isFolder)(t)){if(-1!==t.substring(0,t.length-1).indexOf("/"))return!0}else if(-1!==t.indexOf("/"))return!0}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.keys(this._tasks).length>0}collectDiffTasks(){return n(this,void 0,void 0,function*(){let e=0;return this.rs.local.forAllNodes(t=>{e>100||(this.isCorrupt(t)?((0,l.default)("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||(0,d.isDocument)(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))}).then(()=>e)})}inConflict(e){return!(!e.local||!e.remote||void 0===e.remote.body&&!e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>o.default.syncInterval)}needsFetch(e){return!!this.inConflict(e)||!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)}needsPush(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}needsRemotePut(e){return!(!e.local||void 0===e.local.body||!1===e.local.body)}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=(0,d.pathsFromRoot)(e);for(let r=1;r{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(e){}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}}),this.deleteChildPathsFromTasks()})}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&((0,l.default)("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return n(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(t=>{const r=t[e];return void 0===r||function(e){return!(!e.remote||!e.remote.revision||e.remote.itemsMap||e.remote.body)}(r)?g("get",e,this.rs.remote.get(e)):this.needsRemotePut(r)?(r.push=(0,d.deepClone)(r.local),r.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then(()=>{let t;return t=y(r)?{ifMatch:r.common.revision}:{ifNoneMatch:"*"},g("put",e,this.rs.remote.put(e,r.push.body,r.push.contentType,t))})):this.needsRemoteDelete(r)?(r.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then(()=>y(r)?g("delete",e,this.rs.remote.delete(e,{ifMatch:r.common.revision})):g("get",e,this.rs.remote.get(e)))):y(r)?g("get",e,this.rs.remote.get(e,{ifNoneMatch:r.common.revision})):g("get",e,this.rs.remote.get(e))})})}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);for(const t in e.local.itemsMap)e.common.itemsMap[t]||this.addTask(e.path+t);(0,d.equal)(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){var t;return function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote:void 0!==e.remote.body&&(!1===e.remote.body&&!1===(null===(t=e.local)||void 0===t?void 0:t.body)||((0,l.default)("[Sync] Emitting conflict event"),setTimeout(this.rs.local.emitChange.bind(this.rs.local),10,{origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType})),!1===e.remote.body?e.common={}:e.common=e.remote,delete e.remote,delete e.local),e}autoMerge(e){if(e.remote){if(e.local)return(0,d.isFolder)(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if((0,d.isFolder)(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if(void 0===t.oldValue&&void 0===t.newValue||this.rs.local.emitChange(t),!1===e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local.emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return n(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(r=>(r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(r))))})}markChildren(e,t,r,i){return n(this,void 0,void 0,function*(){const n=[],o={},s={};for(const r in t)n.push(e+r),o[e+r]=t[r];for(const t in i)n.push(e+t);const a=yield this.rs.local.getNodes(n);let l,c;for(const t in a)if(c=a[t],o[t])c&&c.common?m(c,o[t].ETag)&&(r[t]=(0,d.deepClone)(c),r[t].remote={revision:o[t].ETag,timestamp:this.now()},r[t]=this.autoMerge(r[t])):(l=this.rs.caching.checkPath(t),"ALL"===l&&(r[t]={path:t,common:{timestamp:this.now()},remote:{revision:o[t].ETag,timestamp:this.now()}})),r[t]&&o[t]["Content-Type"]&&(r[t].remote.contentType=o[t]["Content-Type"]),r[t]&&o[t]["Content-Length"]&&(r[t].remote.contentLength=o[t]["Content-Length"]);else if(i[t.substring(e.length)]&&c&&c.common){if(c.common.itemsMap)for(const e in c.common.itemsMap)s[t+e]=!0;if(c.local&&c.local.itemsMap)for(const e in c.local.itemsMap)s[t+e]=!0;if(c.remote||(0,d.isFolder)(t))r[t]=void 0;else if(r[t]=this.autoMerge(c),void 0===r[t]){const n=this.getParentPath(t),i=r[n],o=t.substring(e.length);i&&i.local&&(delete i.local.itemsMap[o],(0,d.equal)(i.local.itemsMap,i.common.itemsMap)&&delete i.local)}}const u=yield this.markRemoteDeletions(Object.keys(s),r);u&&(yield this.rs.local.setNodes(this.flush(u)))})}markRemoteDeletions(e,t){return n(this,void 0,void 0,function*(){if(0===e.length)return t;const r=yield this.rs.local.getNodes(e),n={};function i(e,t){if(e&&e.itemsMap)for(const r in e.itemsMap)n[t+r]=!0}for(const e in r){const n=r[e];n&&((0,d.isFolder)(e)?(i(n.common,e),i(n.local,e)):n.common&&void 0!==n.common.body&&(t[e]=(0,d.deepClone)(n),t[e].remote={body:!1,timestamp:this.now()},t[e]=this.autoMerge(t[e])))}const o=yield this.markRemoteDeletions(Object.keys(n),t);o&&(yield this.rs.local.setNodes(this.flush(o)))})}completeFetch(e,t,r,i){return n(this,void 0,void 0,function*(){let n,o;const s=(0,d.pathsFromRoot)(e);(0,d.isFolder)(e)?n=[e]:(o=s[1],n=[e,o]);const a=yield this.rs.local.getNodes(n),l=a[o],c={};let u,h=a[e];function p(e){if(e&&e.itemsMap)for(u in e.itemsMap)t[u]||(c[u]=!0)}if("object"==typeof h&&h.path===e&&"object"==typeof h.common||(h={path:e,common:{}},a[e]=h),h.remote={revision:i,timestamp:this.now()},(0,d.isFolder)(e))for(u in p(h.common),p(h.remote),h.remote.itemsMap={},t)h.remote.itemsMap[u]=!0;else h.remote.body=t,h.remote.contentType=r,l&&l.local&&l.local.itemsMap&&(u=e.substring(o.length),!1!==t?l.local.itemsMap[u]=!0:l.local.itemsMap[u]&&delete l.local.itemsMap[u],(0,d.equal)(l.local.itemsMap,l.common.itemsMap)&&delete l.local);return a[e]=this.autoMerge(h),{toBeSaved:a,missingChildren:c}})}completePush(e,t,r,i){return n(this,void 0,void 0,function*(){const n=yield this.rs.local.getNodes([e]),o=n[e];if(!o.push)throw this.stopped=!0,new Error("completePush called but no push version!");r?((0,l.default)("[Sync] We have a conflict"),o.remote&&o.remote.revision===i||(o.remote={revision:i||"conflict",timestamp:this.now()},delete o.push),n[e]=this.autoMerge(o)):(o.common={revision:i,timestamp:this.now()},"put"===t?(o.common.body=o.push.body,o.common.contentType=o.push.contentType,(0,d.equal)(o.local.body,o.push.body)&&o.local.contentType===o.push.contentType&&delete o.local,delete o.push):"delete"===t&&(!1===o.local.body?n[e]=void 0:delete o.push)),yield this.rs.local.setNodes(this.flush(n))})}dealWithFailure(e){return n(this,void 0,void 0,function*(){const t=yield this.rs.local.getNodes([e]);if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))})}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const r=Math.floor(e/100);return t.successful=2===r||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==c.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,r,i,o){return n(this,void 0,void 0,function*(){if(t.notFound&&(r=!!(0,d.isFolder)(e)&&{}),t.changed){const t=yield this.completeFetch(e,r,i,o);if((0,d.isFolder)(e)){if(this.corruptServerItemsMap(r))return(0,l.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1;yield this.markChildren(e,r,t.toBeSaved,t.missingChildren)}else yield this.rs.local.setNodes(this.flush(t.toBeSaved))}else yield this.updateCommonTimestamp(e,o);return!0})}handleResponse(e,t,r){return n(this,void 0,void 0,function*(){const n=this.interpretStatus(r.statusCode);if(n.successful){if("get"===t)return this.handleGetResponse(e,n,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,n.conflict,r.revision).then(function(){return!0});throw new Error(`cannot handle response for unknown action ${t}`)}{let t;return t=n.unAuth?new h.default:n.networkProblems?new u.default("Network request failed."):new Error("HTTP response code "+n.statusCode+" received."),this.dealWithFailure(e).then(()=>{throw this.rs._emit("error",t),t})}})}finishTask(e){return n(this,arguments,void 0,function*(e,t=!0){if(void 0===e.action)return void delete this._running[e.path];if(t&&((0,l.default)("[Sync] queue finished task:",e.path),this._finishedTasks.push(e),this._finishedTasks.length>1))return void(0,l.default)("[Sync] delaying finished task:",e.path);let r;(0,l.default)("[Sync] run task:",e.path);try{r=yield e.promise}catch(t){(0,l.default)("[Sync] wire client rejects its promise",e.path,e.action,t),r={statusCode:"offline"}}try{const t=yield this.handleResponse(e.path,e.action,r);this.finishSuccessfulTask(e,t)}catch(t){this.finishUnsuccessfulTask(e,t)}})}finishSuccessfulTask(e,t){return n(this,void 0,void 0,function*(){if(this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t0?yield this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then(()=>{!this.hasTasks()||this.stopped?(this.done||(this.done=!0),this.rs._emit("sync-done",{completed:!0})):setTimeout(()=>{this.doTasks()},10)})})}finishUnsuccessfulTask(e,t){return n(this,void 0,void 0,function*(){(0,l.default)("[Sync]",t.message),this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?yield this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))})}tasksWanted(){return this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0}doTasks(){const e=this.tasksWanted()-Object.keys(this._running).length;if(e<=0)return!0;this.hasTasks()&&!this.done&&this.rs._emit("sync-started");let t,r=0;for(t in this._tasks)if(!this._running[t]&&(this._timeStarted[t]=this.now(),this._running[t]=this.doTask(t).then(this.finishTask.bind(this)),r++,r>=e))break;return r>=e}collectTasks(){return n(this,arguments,void 0,function*(e=!0){if(!this.hasTasks()&&!this.stopped)return(yield this.collectDiffTasks())>0?void 0:e?this.collectRefreshTasks():void 0})}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return n(this,void 0,void 0,function*(){if(this.done=!1,!this.doTasks()){try{yield this.collectTasks()}catch(e){throw(0,l.default)("[Sync] Sync error",e),new Error("Local cache unavailable")}this.doTasks()}})}static _rs_init(e){p=function(){const t=new s.default;t.isBrowser()&&function(e,t){function r(e){const r=t.getCurrentSyncInterval();o.default.isBackground=!e;const n=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:r,newValue:n})}e.on("background",()=>r(!1)),e.on("foreground",()=>r(!0))}(t,e),e.sync||(e.sync=new b(e),e.syncStopped&&((0,l.default)("[Sync] Initializing with sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),e.setupSyncCycle()},f=function(){e.removeEventListener("connected",f),e.startSync()},e.on("ready",p),e.on("connected",f)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",p),e.removeEventListener("connected",f),e.caching.resetActivationHandler(),e.sync=void 0,delete e.sync}}t.Sync=b,(0,d.applyMixins)(b,[a.default]),t.default=b},370:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};const i=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(334));function o(e){return"dropbox"===this.backend&&!!e.match(/^\/public\/.*[^\/]$/)}const s={get:function(e,t){if(this.local){if(void 0===t)t="object"==typeof(r=this).remote&&r.remote.connected&&r.remote.online?2*r.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof t&&!1!==t)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e);var r},put:function(e,t,r){return o.bind(this)(e)?s._wrapBusyDone.call(this,this.remote.put(e,t,r)):this.local?this.local.put(e,t,r):s._wrapBusyDone.call(this,this.remote.put(e,t,r))},delete:function(e,t){return this.local?this.local.delete(e,t):s._wrapBusyDone.call(this,this.remote.delete(e,t))},_wrapBusyDone:function(e){return n(this,void 0,void 0,function*(){return this._emit("wire-busy"),e.then(e=>(this._emit("wire-done",{success:!0}),Promise.resolve(e)),e=>(this._emit("wire-done",{success:!1}),Promise.reject(e)))})}};e.exports=s},613:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class r{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,r,n){const i=e+"/"+t;if(n.extends){const t=n.extends.split("/"),r=1===t.length?e+"/"+t.shift():t.join("/"),o=this.uris[r];if(!o)throw"Type '"+i+"' tries to extend unknown schema '"+r+"'";n.extends=this.schemas[o]}this.uris[i]=r,this.aliases[r]=i,this.schemas[r]=n}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const t=e.length,r={};for(const n in this.uris)if(n.substr(0,t+1)===e+"/"){const e=this.uris[n];r[e]=this.schemas[e]}return r}}t.BaseClientTypes=r;const n=new r;t.default=n},503:function(e){class t extends Error{constructor(e,t={}){super(),this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack}}e.exports=t},746:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.generateCodeVerifier=function(){return n(this,arguments,void 0,function*(e=128){const t=new Uint8Array(e);crypto.getRandomValues(t);const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=Array.from(t).map(e=>r[e%66]),i=n.join(""),o=Uint8Array.from(n.map(e=>e.charCodeAt(0))),s=(a=yield crypto.subtle.digest("SHA-256",o),btoa(String.fromCharCode.apply(null,new Uint8Array(a))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var a;return crypto.getRandomValues(t),{codeVerifier:i,codeChallenge:s,state:Array.from(t).map(e=>r[e%66]).join("")}})},t.applyMixins=function(e,t){t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(r=>{Object.defineProperty(e.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r))})})},t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:r.g,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach(function(e){for(const r in e)t[r]=e[r]}),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},t.isFolder=e=>"/"===e.slice(-1),t.isDocument=e=>!(0,t.isFolder)(e),t.baseName=e=>{const r=e.split("/");return(0,t.isFolder)(e)?r[r.length-2]+"/":r[r.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,r,n=[])=>{let i;if(typeof e!=typeof r)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===r;if("function"==typeof e)return e.toString()===r.toString();if(e instanceof ArrayBuffer&&r instanceof ArrayBuffer&&(e=new Uint8Array(e),r=new Uint8Array(r)),null===e||null===r)return e===r;if(e instanceof Array){if(e.length!==r.length)return!1;for(let i=0,o=e.length;i=0)continue;o=n.slice(),o.push(r[i])}if(!(0,t.equal)(e[i],r[i],o))return!1}}return!0},t.deepClone=e=>void 0===e?void 0:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)),t.pathsFromRoot=e=>{const t=[e],r=e.replace(/\/$/,"").split("/");for(;r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},t.localStorageAvailable=()=>{const e=(0,t.getGlobalContext)();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},t.getJSONFromLocalStorage=e=>{const r=(0,t.getGlobalContext)();try{return JSON.parse(r.localStorage.getItem(e))}catch(e){}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,r)=>new Promise(n=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const t=Buffer.from(e);n(t.toString(r))}else{let i;const o=t.globalContext;if(o.BlobBuilder=o.BlobBuilder||o.WebKitBlobBuilder,void 0!==o.BlobBuilder){const t=new o.BlobBuilder;t.append(e),i=t.getBlob()}else i=new Blob([e]);const s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",function(e){n(e.target.result)}):s.onloadend=function(e){n(e.target.result)},s.readAsText(i,r)}}),t.toBase64=e=>{const r=(0,t.getGlobalContext)();return"btoa"in r?r.btoa(e):Buffer.from(e).toString("base64")}},600:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=i(r(275)),s=i(r(93)),a=i(r(503)),l=i(r(334)),c=r(746),u=r(368),h=r(684);let d;const p="remotestorage:wireclient",f={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};class g extends h.RemoteBase{constructor(e){if(super(e),this._revisionCache={},d=(0,c.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),d){const e=function(){const e=(0,c.getJSONFromLocalStorage)(p)||{},{userAddress:t,href:r,storageApi:n,token:i,properties:o}=e;return{userAddress:t,href:r,storageApi:n,token:i,properties:o}}();e&&setTimeout(()=>{this.configure(e)},0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}_request(e,t,r,i,s,h,d){return n(this,void 0,void 0,function*(){if(this.isForbiddenRequestMethod(e,t))return Promise.reject(`Don't use ${e} on directories!`);let n;return r!==o.default.IMPLIED_FAKE_TOKEN&&(i.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:(0,c.isFolder)(t)}),(0,u.requestWithTimeout)(e,t,{body:s,headers:i,responseType:"arraybuffer"}).then(r=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,c.isFolder)(t),success:!0}),i=r.status,[401,403,404,412].indexOf(i)>=0)return(0,l.default)("[WireClient] Error response status",r.status),n=h?this.stripQuotes(r.getResponseHeader("ETag")):void 0,401===r.status&&this.rs._emit("error",new a.default),Promise.resolve({statusCode:r.status,revision:n});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return n=this.stripQuotes(r.getResponseHeader("ETag")),(0,l.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,revision:n});{const e=r.getResponseHeader("Content-Type");n=h?this.stripQuotes(r.getResponseHeader("ETag")):200===r.status?d:void 0;const t=function(e){let t,r="utf-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}(e);return(0,c.shouldBeTreatedAsBinary)(r.response,e)?((0,l.default)("[WireClient] Successful request with unknown or binary mime-type",n),Promise.resolve({statusCode:r.status,body:r.response,contentType:e,revision:n})):(0,c.getTextFromArrayBuffer)(r.response,t).then(t=>((0,l.default)("[WireClient] Successful request",n),Promise.resolve({statusCode:r.status,body:t,contentType:e,revision:n})))}var i},r=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,c.isFolder)(t),success:!1}),Promise.reject(r)))})}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),"string"==typeof this.storageApi){const e=f[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,d&&localStorage.setItem(p,JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const r={};return this.supportsRevs&&t.ifNoneMatch&&(r["If-None-Match"]=this.addQuotes(t.ifNoneMatch)),this._request("GET",this.href+(0,c.cleanPath)(e),this.token,r,void 0,this.supportsRevs,this._revisionCache[e]).then(t=>{if(!(0,c.isFolder)(e))return Promise.resolve(t);let r={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+this.href+(0,c.cleanPath)(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(n=t.body)["@context"]&&"object"==typeof n.items){for(const r in t.body.items)this._revisionCache[e+r]=t.body.items[r].ETag;r=t.body.items}else Object.keys(t.body).forEach(n=>{this._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}});return t.body=r,Promise.resolve(t)}return Promise.resolve(t);var n})}put(e,t,r,n={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!r.match(/charset=/)&&(t instanceof ArrayBuffer||(0,u.isArrayBufferView)(t))&&(r+="; charset=binary");const i={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(i["If-Match"]=this.addQuotes(n.ifMatch)),n.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(n.ifNoneMatch))),this._request("PUT",this.href+(0,c.cleanPath)(e),this.token,i,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=this.addQuotes(t.ifMatch)),this._request("DELETE",this.href+(0,c.cleanPath)(e),this.token,r,void 0,this.supportsRevs)}static _rs_init(e){e.remote=new g(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){d&&delete localStorage[p]}}(0,c.applyMixins)(g,[s.default]),e.exports=g},439:function(e,t){var r,n;r=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("object"!=typeof i&&"function"!=typeof i||null===i)throw new TypeError("Object.keys called on non-object");var o=[];for(var s in i)e.call(i,s)&&o.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var i=n>=0?n:Math.max(r-Math.abs(n),0);i0&&(t+=u.suffices["*"]&&r||",",u.suffices["*"]&&l&&(t+=u.name+"=")),t+=a?encodeURIComponent(h[p]).replace(/!/g,"%21"):s(h[p])}else if("object"==typeof h){l&&!u.suffices["*"]&&(t+=u.name+"=");var f=!0;for(var g in h)f||(t+=u.suffices["*"]&&r||","),f=!1,t+=a?encodeURIComponent(g).replace(/!/g,"%21"):s(g),t+=u.suffices["*"]?"=":",",t+=a?encodeURIComponent(h[g]).replace(/!/g,"%21"):s(h[g])}else l&&(t+=u.name,c&&""===h||(t+="=")),null!=u.truncate&&(h=h.substring(0,u.truncate)),t+=a?encodeURIComponent(h).replace(/!/g,"%21"):s(h)}return t};return _.varNames=u,{prefix:n,substitution:_}}function l(e){if(!(this instanceof l))return new l(e);for(var t=e.split("{"),r=[t.shift()],n=[],i=[],o=[];t.length>0;){var s=t.shift(),c=s.split("}")[0],u=s.substring(c.length+1),h=a(c);i.push(h.substitution),n.push(h.prefix),r.push(u),o=o.concat(h.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var i=g(e[n]);i&&void 0===this.schemas[i]&&void 0===this.missingMap[i]&&(this.missingMap[i]=i)}},c.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===g(e)+"#"&&(e=g(e)),this.schemas[e]=t,delete this.missingMap[e],m(t,e),this.searchSchemas(t,e)},c.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},c.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},c.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},c.prototype.dropSchemas=function(){this.schemas={},this.reset()},c.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},c.prototype.validateAll=function(e,t,r,n,i){var o;if(!(t=this.resolveRefs(t)))return null;if(t instanceof w)return this.errors.push(t),t;var s,a=this.errors.length,l=null,c=null;if(this.checkRecursive&&e&&"object"==typeof e){if(o=!this.scanned.length,e[this.validatedSchemasKey]){var u=e[this.validatedSchemasKey].indexOf(t);if(-1!==u)return this.errors=this.errors.concat(e[this.validationErrorsKey][u]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var h=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==h)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][h]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),l=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][l]=t,this.scannedFrozenValidationErrors[s][l]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}c=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][c]=t,e[this.validationErrorsKey][c]=[]}}var d=this.errors.length,p=this.validateBasic(e,t,i)||this.validateNumeric(e,t,i)||this.validateString(e,t,i)||this.validateArray(e,t,i)||this.validateObject(e,t,i)||this.validateCombinations(e,t,i)||this.validateHypermedia(e,t,i)||this.validateFormat(e,t,i)||this.validateDefinedKeywords(e,t,i)||null;if(o){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(p||d!==this.errors.length)for(;r&&r.length||n&&n.length;){var f=r&&r.length?""+r.pop():null,g=n&&n.length?""+n.pop():null;p&&(p=p.prefixWith(f,g)),this.prefixErrors(d,f,g)}return null!==l?this.scannedFrozenValidationErrors[s][l]=this.errors.slice(a):null!==c&&(e[this.validationErrorsKey][c]=this.errors.slice(a)),this.handleError(p)},c.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(b.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(b.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},c.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var i=this.definedKeywords[n],o=0;o=h&&nt.maximum)return this.createError(b.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(b.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},c.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(b.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},c.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},c.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(b.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},c.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,i="",o=t.pattern.match(/^\/(.+)\/([img]*)$/);o?(n=o[1],i=o[2]):n=t.pattern,r=new RegExp(n,i)}return r.test(e)?null:this.createError(b.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},c.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},c.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(b.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},c.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(b.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},c.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==b[e])throw new Error("Error already defined: "+e+" as "+b[e]);if(void 0!==v[t])throw new Error("Error code already used: "+v[t]+" as "+t);for(var n in b[e]=t,v[t]=e,E[e]=E[t]=r,C){var i=C[n];i[e]&&(i[t]=i[t]||i[e])}},reset:function(){n.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:m,resolveUrl:f,getDocumentUri:g,errorCodes:b};return i.language("en"),i}();return S.addLanguage("en-gb",E),S.tv4=S,S},void 0===(n=r.apply(t,[]))||(e.exports=n)},713:function(module){!function(e,t){{const e=t();module.exports=e,module.exports.default=e}}("undefined"!=typeof self&&self,function(){var LINK_URI_MAPS={"http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},LINK_PROPERTIES={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],camlistore:[]},URIS=["webfinger","host-meta","host-meta.json"],IPV4_OCTET="(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)",IPV4_REGEX=new RegExp(`^(?:${IPV4_OCTET}\\.){3}${IPV4_OCTET}$`),IPV4_CAPTURE_REGEX=new RegExp(`^(${IPV4_OCTET})\\.(${IPV4_OCTET})\\.(${IPV4_OCTET})\\.(${IPV4_OCTET})$`),LOCALHOST_REGEX=/^localhost(?:\.localdomain)?(?::\d+)?$/,NUMERIC_PORT_REGEX=/^\d+$/,HOSTNAME_REGEX=/^[a-zA-Z0-9.-]+$/,LOCALHOST_127_REGEX=/^127\.(?:\d{1,3}\.){2}\d{1,3}$/;class WebFingerError extends Error{status;constructor(e,t){super(e),this.name="WebFingerError",this.status=t}}class WebFinger{static default;config;constructor(e={}){this.config={tls_only:void 0===e.tls_only||e.tls_only,uri_fallback:void 0!==e.uri_fallback&&e.uri_fallback,request_timeout:void 0!==e.request_timeout?e.request_timeout:1e4,allow_private_addresses:void 0!==e.allow_private_addresses&&e.allow_private_addresses}}async fetchJRD(e,t=0){if(t>3)throw new WebFingerError("too many redirects");const r=await fetch(e,{headers:{Accept:"application/jrd+json, application/json"},redirect:"manual"});if(r.status>=300&&r.status<400){const n=r.headers.get("location");if(!n)throw new WebFingerError("redirect without location header");let i;try{i=new URL(n,e)}catch{throw new WebFingerError("invalid redirect URL")}const o=WebFinger.validateHost(i.hostname+(i.port?":"+i.port:""));if(!this.config.allow_private_addresses&&WebFinger.isPrivateAddress(o))throw new WebFingerError("redirect to private or internal address blocked");return this.fetchJRD(i.toString(),t+1)}if(404===r.status)throw new WebFingerError("resource not found",404);if(!r.ok)throw new WebFingerError("error during request",r.status);const n=r.headers.get("content-type")||"",i=n.toLowerCase().split(";")[0].trim();"application/jrd+json"===i||("application/json"===i?console.debug('WebFinger: Server uses "application/json" instead of RFC 7033 recommended "application/jrd+json".'):console.warn(`WebFinger: Server returned unexpected content-type "${n}". Expected "application/jrd+json" per RFC 7033.`));const o=await r.text();if(WebFinger.isValidJSON(o))return o;throw new WebFingerError("invalid json")}static isValidJSON(e){try{JSON.parse(e)}catch{return!1}return!0}static isLocalhost(e){return LOCALHOST_REGEX.test(e)}static isPrivateAddress(e){let t=e;if(t.startsWith("[")&&t.includes("]:"))t=t.substring(1,t.lastIndexOf("]:"));else if(t.startsWith("[")&&t.endsWith("]"))t=t.substring(1,t.length-1);else if(t.includes(":")&&1===(t.match(/:/g)||[]).length){const e=t.split(":"),r=e[0],n=e[1];if(n&&!NUMERIC_PORT_REGEX.test(n))throw new WebFingerError("invalid host format");(r.match(IPV4_REGEX)||r.match(HOSTNAME_REGEX))&&(t=r)}if("localhost"===t||"127.0.0.1"===t||t.match(LOCALHOST_127_REGEX)||"::1"===t||"localhost.localdomain"===t)return!0;const r=t.match(IPV4_CAPTURE_REGEX);if(r){const[,e,t,n,i]=r,o=Number(e),s=Number(t),a=Number(n),l=Number(i);if(isNaN(o)||isNaN(s)||isNaN(a)||isNaN(l))return!0;if(10===o)return!0;if(172===o&&s>=16&&s<=31)return!0;if(192===o&&168===s)return!0;if(169===o&&254===s)return!0;if(o>=224&&o<=239)return!0;if(o>=240)return!0}if(t.includes(":")){const e=(t.match(/:/g)||[]).length;if((e>1||1===e&&!t.match(/^[a-zA-Z0-9.-]+:\d+$/))&&(t.match(/^(fc|fd)[0-9a-f]{2}:/i)||t.match(/^fe80:/i)||t.match(/^ff[0-9a-f]{2}:/i)))return!0}return!1}static validateHost(e){const t=e.split("/")[0];if(!t||0===t.length)throw new WebFingerError("invalid host format");if(t.includes("?")||t.includes("#")||t.includes(" "))throw new WebFingerError("invalid characters in host");return t}static async processJRD(e,t){const r=JSON.parse(t);if("object"!=typeof r||"object"!=typeof r.links)throw void 0!==r.error?new WebFingerError(r.error):new WebFingerError("unknown response from server");const n={object:r,idx:{properties:{name:void 0},links:JSON.parse(JSON.stringify(LINK_PROPERTIES))}};(Array.isArray(r.links)?r.links:[]).map(function(e){if(Object.prototype.hasOwnProperty.call(LINK_URI_MAPS,String(e.rel))){const t=LINK_URI_MAPS[String(e.rel)];if(n.idx.links[t]){const r={href:String(e.href||""),rel:String(e.rel||"")};Object.keys(e).map(function(t){"object"==typeof e[t]&&null!==e[t]?r[t]=e[t]:r[t]=String(e[t])}),n.idx.links[t].push(r)}}});const i=r.properties||{};for(const o in i)Object.prototype.hasOwnProperty.call(i,o)&&"http://packetizer.com/ns/name"===o&&(n.idx.properties.name=i[o]);return n}async validateDNSResolution(hostname){if(hostname.match(IPV4_REGEX)||hostname.includes(":")||"localhost"===hostname)return;const isNodeJS="undefined"!=typeof process&&process.versions?.node;if(isNodeJS)try{const dnsImport=eval('import("dns")'),dns=await dnsImport.then(e=>e.promises).catch(()=>null);if(dns)try{const[e,t]=await Promise.allSettled([dns.resolve4(hostname).catch(()=>[]),dns.resolve6(hostname).catch(()=>[])]),r="fulfilled"===e.status?e.value:[],n="fulfilled"===t.status?t.value:[];for(const i of[...r,...n])if(WebFinger.isPrivateAddress(i))throw new WebFingerError(`hostname ${hostname} resolves to private address ${i}`)}catch(e){if(e instanceof WebFingerError)throw e}}catch(e){if(e instanceof WebFingerError)throw e}}async lookup(e){if(!e)throw new WebFingerError("address is required");let t="";if(e.indexOf("://")>-1){const r=e.replace(/ /g,"").split("/");if(r.length<3)throw new WebFingerError("invalid URI format");t=r[2]}else{const r=e.replace(/ /g,"").split("@");if(2!==r.length||!r[1])throw new WebFingerError("invalid useraddress format");t=r[1]}if(!t)throw new WebFingerError("could not determine host from address");if(t=WebFinger.validateHost(t),!this.config.allow_private_addresses&&WebFinger.isPrivateAddress(t))throw new WebFingerError("private or internal addresses are not allowed");if(!this.config.allow_private_addresses){const e=t.includes(":")?t.split(":")[0]:t;await this.validateDNSResolution(e)}let r=0,n="https";WebFinger.isLocalhost(t)&&(n="http");const i=async e=>{if(this.config.uri_fallback&&r!==URIS.length-1)return r+=1,o();if(this.config.tls_only||"https"!==n)throw e instanceof Error?e:new WebFingerError(String(e));return r=0,n="http",o()},o=async()=>{const o=(()=>{let i="";return e.split("://")[1]||(i="acct:"),n+"://"+t+"/.well-known/"+URIS[r]+"?resource="+i+e})();try{const e=await this.fetchJRD(o);return WebFinger.processJRD(o,e)}catch(e){return await i(e)}};return o()}async lookupLink(e,t){if(Object.prototype.hasOwnProperty.call(LINK_PROPERTIES,t)){const r=(await this.lookup(e)).idx.links[t];return 0===r.length?Promise.reject('no links found with rel="'+t+'"'):Promise.resolve(r[0])}return Promise.reject("unsupported rel "+t)}}return WebFinger.default=WebFinger,WebFinger})}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var __webpack_exports__=__webpack_require__(423);return __webpack_exports__=__webpack_exports__.default,__webpack_exports__}()},module.exports=t()}(remotestorage$2)),remotestorage$2.exports}var remotestorageExports=requireRemotestorage();const RemoteStorage=getDefaultExportFromCjs$1(remotestorageExports),ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=32,RANDOM_LEN=16,TIME_LEN=10,TIME_MAX=0xffffffffffff;var ULIDErrorCode;!function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID"}(ULIDErrorCode||(ULIDErrorCode={}));class ULIDError extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e}}function randomChar(e){const t=Math.floor(e()*ENCODING_LEN)%ENCODING_LEN;return ENCODING.charAt(t)}function detectPRNG(){const e=detectRoot(),t=e&&(e.crypto||e.msCrypto)||null;if("function"==typeof t?.getRandomValues)return()=>{const e=new Uint8Array(1);return t.getRandomValues(e),e[0]/256};if("function"==typeof t?.randomBytes)return()=>t.randomBytes(1).readUInt8()/256;throw new ULIDError(ULIDErrorCode.PRNGDetectFailure,"Failed to find a reliable PRNG")}function detectRoot(){return inWebWorker()?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:null}function encodeRandom(e,t){let r="";for(;e>0;e--)r=randomChar(t)+r;return r}function encodeTime(e,t=TIME_LEN){if(isNaN(e))throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed,`Time must be a number: ${e}`);if(e>TIME_MAX)throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${TIME_MAX}: ${e}`);if(e<0)throw new ULIDError(ULIDErrorCode.EncodeTimeNegative,`Time must be positive: ${e}`);if(!1===Number.isInteger(e))throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let r,n="";for(let i=t;i>0;i--)r=e%ENCODING_LEN,n=ENCODING.charAt(r)+n,e=(e-r)/ENCODING_LEN;return n}function inWebWorker(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}function ulid(){const e=detectPRNG();return encodeTime(Date.now(),TIME_LEN)+encodeRandom(RANDOM_LEN,e)}const placeSchema={type:"object",properties:{id:{type:"string"},title:{type:"string"},lat:{type:"number"},lon:{type:"number"},geohash:{type:"string"},zoom:{type:"number"},url:{type:"string"},osmId:{type:"string"},osmType:{type:"string"},osmTags:{type:"object",additionalProperties:{type:"string"}},description:{type:"string"},tags:{type:"array",items:{type:"string"},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","lat","lon","geohash","createdAt"]},listSchema={type:"object",properties:{id:{type:"string"},title:{type:"string"},color:{type:"string"},placeRefs:{type:"array",items:{type:"object",properties:{id:{type:"string"},geohash:{type:"string"}},required:["id","geohash"]},default:[]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"}},required:["id","title","placeRefs","createdAt"]},Places=function(e){function t(e,t){return`${e.substring(0,2)}/${e.substring(2,4)}/${t}`}e.declareType("place",placeSchema),e.declareType("list",listSchema);const r={async getAll(){const t=await e.getAll("_lists/");return t?Object.values(t):[]},async get(t){const r=`_lists/${t}`;return e.getObject(r)},async create(t,r,n){const i=`_lists/${t}`;let o=await e.getObject(i);const s=(new Date).toISOString();return o?(o.title=r,n&&(o.color=n),o.updatedAt=s):o={id:t,title:r,color:n,placeRefs:[],createdAt:s,updatedAt:s},await e.storeObject("list",i,o),o},async delete(t){await e.remove(`_lists/${t}`)},async addPlace(t,r,n){const i=`_lists/${t}`,o=await e.getObject(i);if(!o)throw new Error(`List not found: ${t}`);return-1===o.placeRefs.findIndex(e=>e.id===r)&&(o.placeRefs.push({id:r,geohash:n}),o.updatedAt=(new Date).toISOString(),await e.storeObject("list",i,o)),o},async removePlace(t,r){const n=`_lists/${t}`,i=await e.getObject(n);if(!i)throw new Error(`List not found: ${t}`);const o=i.placeRefs.findIndex(e=>e.id===r);return-1!==o&&(i.placeRefs.splice(o,1),i.updatedAt=(new Date).toISOString(),await e.storeObject("list",n,i)),i},async initDefaults(){const e=[{id:"to-go",title:"Want to go",color:"#2e9e4f"},{id:"to-do",title:"To do",color:"#2a7fff"}];for(const t of e)await this.get(t.id)||await this.create(t.id,t.title,t.color)}},n={lists:r,store:async function(r){const n=function(e){const t=(new Date).toISOString(),r=e.id||ulid(),n="number"==typeof e.lat?e.lat:0,i="number"==typeof e.lon?e.lon:0,o=e.title||"Untitled Place",s=e.geohash||Geohash.encode(n,i,10),a={...e,id:r,lat:n,lon:i,geohash:s,title:o,tags:e.tags||[],createdAt:e.createdAt||t,updatedAt:e.id?t:void 0};return Object.keys(a).forEach(e=>{void 0===a[e]&&delete a[e]}),a}(r),i=t(n.geohash,n.id);return await e.storeObject("place",i,n),n},remove:async function(n,i){if(!n||!i)throw new Error("Both id and geohash are required to remove a place");const o=await r.getAll();await Promise.all(o.map(async t=>{const r=t.placeRefs.findIndex(e=>e.id===n);-1!==r&&(t.placeRefs.splice(r,1),t.updatedAt=(new Date).toISOString(),await e.storeObject("list",`_lists/${t.id}`,t))}));const s=t(i,n);return e.remove(s)},get:async function(r,n){if(!r||!n)throw new Error("Both id and geohash are required to get a place");const i=t(n,r);return e.getObject(i)},listByPrefix:async function(t){let r="";return t.length>=2&&(r+=t.substring(0,2)+"/"),t.length>=4&&(r+=t.substring(2,4)+"/"),e.getAll(r)},getPlaces:async function(t){const r=[],n=async t=>{const n=await e.getAll(t,!1);n&&Object.values(n).forEach(e=>{e&&"object"==typeof e&&!e.toString().endsWith("/")&&r.push(e)})};if(t&&t.length>0){const e=t.map(async e=>{if(e.length<4)return;const t=e.substring(0,2),r=e.substring(2,4);await n(`${t}/${r}/`)});await Promise.all(e)}else{const t=e=>{if(!e||"object"!=typeof e)return[];let t=e;return e.items&&"object"==typeof e.items&&(t=e.items),Object.keys(t).filter(e=>e.endsWith("/")&&!e.startsWith("@"))},r=await e.getListing("",!1),i=t(r);await Promise.all(i.map(async r=>{const i=await e.getListing(r,!1),o=t(i);await Promise.all(o.map(async e=>{await n(r+e)}))}))}return r}};return{exports:n}},Places$1={name:"places",builder:Places};var widget={exports:{}},hasRequiredWidget;function requireWidget(){return hasRequiredWidget||(hasRequiredWidget=1,self,e=()=>(()=>{var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){var t=function(e){if("object"!=r(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=r(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==r(t)?t:t+""}e.d(t,{default:()=>i});const i=function(){return e=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.rs=t,this.leaveOpen=!!r.leaveOpen&&r.leaveOpen,this.autoCloseAfter=r.autoCloseAfter?r.autoCloseAfter:1500,this.skipInitial=!!r.skipInitial&&r.skipInitial,this.logging=!!r.logging&&r.logging,this.parentContainerEl=null,r.hasOwnProperty("modalBackdrop")){if("boolean"!=typeof r.modalBackdrop&&"onlySmallScreens"!==r.modalBackdrop)throw'options.modalBackdrop has to be true/false or "onlySmallScreens"';this.modalBackdrop=r.modalBackdrop}else this.modalBackdrop="onlySmallScreens";this.active=!1,this.online=!1,this.closed=!1,this.lastSynced=null,this.lastSyncedUpdateLoop=null},t=[{key:"log",value:function(){if(this.logging){for(var e,t=arguments.length,r=new Array(t),n=0;n

Connect your storage

To sync data with your account
';var t=document.createElement("style");return t.innerHTML='#remotestorage-widget {\n z-index: 21000000;\n}\n\n.rs-widget {\n box-sizing: border-box;\n overflow: hidden;\n max-width: 350px;\n padding: 10px;\n margin: 10px;\n border-radius: 3px;\n background-color: #fff;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n font-family: arial, sans-serif;\n font-size: 16px;\n color: #333;\n will-change: max-height, height, width, opacity, max-width, background, box-shadow;\n transition-property: width, height, opacity, max-width, max-height, background, box-shadow;\n transition-duration: 300ms;\n}\n\n.rs-widget * {\n box-sizing: border-box;\n}\n\n.rs-widget .rs-hidden {\n display: none;\n}\n\n.rs-box {\n overflow: hidden;\n will-change: height;\n transition-property: height, width, max-height;\n transition-duration: 300ms;\n transition-timing-function: ease-in;\n opacity: 0;\n max-height: 0px;\n}\n\n.rs-box.rs-selected:not([aria-hidden=true]) {\n opacity: 1;\n max-height: 420px;\n}\n\n/* Main logo */\n.rs-main-logo {\n float: left;\n height: 36px;\n width: 36px;\n margin-top: 1px;\n margin-right: 0.625em;\n transition: margin-left 300ms ease-out, transform 300ms ease-out;\n cursor: pointer;\n}\n.rs-widget .rs-backend-remotestorage svg#rs-main-logo-remotestorage {\n display: block;\n}\n.rs-widget[class*="rs-backend-"]:not(.rs-backend-remotestorage) svg#rs-main-logo-remotestorage {\n display: none;\n}\n.rs-widget.rs-backend-dropbox svg#rs-main-logo-dropbox {\n display: block;\n}\n.rs-widget:not(.rs-backend-dropbox) svg#rs-main-logo-dropbox {\n display: none;\n}\n.rs-widget.rs-backend-googledrive svg#rs-main-logo-googledrive {\n display: block;\n}\n.rs-widget:not(.rs-backend-googledrive) svg#rs-main-logo-googledrive {\n display: none;\n}\n\npolygon.rs-logo-shape {\n fill: #FF4B03;\n}\n\npolygon.rs-logo-shape,\n#rs-main-logo-dropbox path,\n#rs-main-logo-googledrive path {\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n.rs-offline polygon.rs-logo-shape,\n.rs-offline #rs-main-logo-dropbox path,\n.rs-offline #rs-main-logo-googledrive path {\n fill: #888;\n transition-property: fill;\n transition-duration: 0.5s;\n}\n\n/* Hide everything except logo when connected and clicked outside of box */\n.rs-closed {\n max-width: 56px;\n background-color: transparent;\n box-shadow: none;\n opacity: 0.5;\n\n transition: max-height 100ms ease-out 0ms, max-width 300ms ease-out 300ms, background 300ms ease-in 200ms, opacity 300ms ease 200ms;\n}\n\n.rs-closed:hover {\n cursor: pointer;\n opacity: 1;\n}\n\n.rs-box-initial {\n transition-duration: 0ms;\n}\n\n.rs-box-initial:hover {\n cursor: pointer;\n}\n\n.rs-widget a {\n color: #0093cc;\n}\n\n/* HEADLINE */\n.rs-small-headline {\n font-size: 1em;\n font-weight: bold;\n margin: 0;\n margin-bottom: 2px;\n height: 1.2em;\n word-break: break-all;\n overflow: hidden;\n line-height: 1em;\n}\n\n.rs-sub-headline {\n word-break: break-all;\n overflow: hidden;\n color: #666;\n font-size: 0.92em;\n height: 1.2em;\n}\n.rs-big-headline {\n font-size: 1.625em;\n font-weight: normal;\n text-align: center;\n margin-top: 20px;\n margin-bottom: 20px;\n}\n\n/* BUTTONS */\n.rs-button {\n font: inherit;\n color: inherit;\n background-color: transparent;\n border: 1px solid #dcdcdc;\n border-radius: 3px;\n cursor: pointer;\n}\n.rs-button-small {\n padding: 0.6em 0.7em;\n margin-left: 0.2em;\n transition: border-color 300ms ease-out;\n}\n.rs-button-small svg {\n vertical-align: top;\n}\n.rs-button-wrap {\n margin-top: 10px;\n}\n\n.rs-button-wrap img,\n.rs-button-wrap svg {\n float: left;\n margin-right: 0.6em;\n width: 40px;\n height: 40px;\n}\n\n.rs-button-big {\n padding: 15px 10px;\n margin-bottom: 10px;\n display: block;\n width: 100%;\n text-align: left;\n transition: box-shadow 200ms;\n}\n.rs-button-big > div {\n font-size: 1.125em;\n padding: 10px 0;\n}\n.rs-button-big:hover {\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:active {\n background-color: #eee;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n.rs-button-big:last-child {\n margin-bottom: 0;\n}\n\n.rs-content {\n padding: 0 10px 10px 10px;\n}\n\n\n.rs-state-choose .rs-main-logo,\n.rs-state-sign-in .rs-main-logo {\n margin-left: 45%;\n float: none;\n}\n\n.rs-sign-in-form input[type=text] {\n padding: 15px 10px;\n display: block;\n width: 100%;\n font: inherit;\n height: 52px;\n border: 1px solid #aaa;\n border-radius: 0;\n box-shadow: none;\n}\n.rs-sign-in-form button.rs-connect {\n padding: 15px 10px;\n margin-top: 20px;\n margin-bottom: 15px;\n display: block;\n width: 100%;\n border: none;\n border-radius: 3px;\n background-color: #3fb34f;\n font: inherit;\n color: #fff;\n transition: box-shadow 200ms, background-color 200ms;\n}\n\n.rs-sign-in-form button.rs-connect:hover {\n cursor: pointer;\n background-color: #4BCB5D;\n box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2);\n}\n\n.rs-sign-in-form button.rs-connect:active {\n background-color: #3fb34f;\n}\n\n.rs-sign-in-form button.rs-connect:disabled,\n.rs-sign-in-form button.rs-connect:disabled:hover {\n background-color: #aaa;\n}\n\n.rs-sign-in-form button.rs-connecting svg {\n height: 1em;\n width: auto;\n vertical-align: middle;\n margin-left: 0.5em;\n animation: rs-spin 1s linear infinite;\n}\n\n.rs-sign-in-error.rs-hidden,\n.rs-box-error.rs-hidden {\n height: 0;\n}\n\n.rs-sign-in-error.rs-visible,\n.rs-box-error.rs-visible {\n height: auto;\n border-radius: 3px;\n padding: 0.5em 0.5em;\n margin-top: 0.5em;\n text-align: center;\n background-color: rgba(255,0,0,0.1);\n color: darkred;\n}\n\n.rs-box-error {\n display: flex;\n flex-direction: row;\n}\n\n.rs-box-error .rs-error-message {\n flex: auto;\n}\n\n /*Choose provider box */\n.rs-box-choose {\n text-align: center;\n overflow: hidden;\n}\n\n.rs-box-choose p {\n margin-top: 0;\n margin-bottom: 20px;\n line-height: 1.4em;\n}\n\n/*Connected box */\n.rs-box-connected {\n display: flex;\n flex-direction: row;\n height: 40px;\n transition: height 0s;\n}\n.rs-connected-text {\n flex: auto;\n min-width: 0;\n}\n.rs-box-connected .rs-user {\n font-weight: bold;\n text-overflow: ellipsis;\n overflow: hidden;\n word-break: keep-all;\n}\n.rs-connected-buttons, .rs-error-buttons {\n flex: none;\n}\n.rs-disconnect:hover {\n border-color: #FF2D2D;\n}\n.rs-disconnect:hover .rs-icon{\n fill: #FF2D2D;\n}\n.rs-sync:hover {\n border-color: #FFBB0C;\n}\n.rs-sync:hover .rs-icon {\n fill: #FFBB0C;\n}\n.rs-sync.rs-rotate {\n border-color: #FFBB0C;\n}\n.rs-sync.rs-rotate .rs-icon {\n fill: #FFBB0C;\n animation: rs-spin 1s linear infinite;\n}\n\n/* Floating widget styles (top right corner) */\n.rs-floating {\n position: fixed;\n top: 0;\n right: 0;\n}\n\n@keyframes rs-spin {\n 100% {\n transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n/* Small/mobile screens */\n@media screen and (max-width: 420px) {\n .rs-widget {\n font-size: 100%;\n transition: all 300ms ease-out;\n max-width: 400px;\n }\n .rs-floating {\n position: relative;\n top: auto;\n right: auto\n }\n .rs-closed {\n max-width: 56px;\n }\n .rs-state-choose,\n .rs-state-sign-in {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n max-width: 100%;\n }\n}\n\n/* remove dotted outline border on Firefox */\n.rs-widget a:focus,\n.rs-widget a:active,\n.rs-widget button:focus,\n.rs-widget input:focus {\n outline:none;\n}\n.rs-widget button::-moz-focus-inner,\n.rs-widget input[type="button"]::-moz-focus-inner {\n border:0;\n}\n\n/* prevent rounded buttons on mobile Safari */\n.rs-widget button,\n.rs-widget input[type="button"] {\n -webkit-appearance: none;\n}\n\n.remotestorage-widget-modal-backdrop {\n display: none;\n position: fixed;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-color: rgba(0, 0, 0, 0.5);\n opacity: 0;\n transition: opacity 0.3s linear;\n}\n\n.remotestorage-widget-modal-backdrop.visible {\n opacity: 1;\n transition: opacity 0.3s linear;\n}\n',e.appendChild(t),e}},{key:"setModalClass",value:function(){if(this.modalBackdrop){if("onlySmallScreens"===this.modalBackdrop&&!this.isSmallScreen())return;this.rsWidget.classList.add("rs-modal")}}},{key:"setupElements",value:function(){if(!this.parentContainerEl)throw new Error("Parent container element not found");this.rsWidget=this.parentContainerEl.querySelector(".rs-widget"),this.rsBackdrop=this.parentContainerEl.querySelector(".remotestorage-widget-modal-backdrop"),this.rsInitial=this.parentContainerEl.querySelector(".rs-box-initial"),this.rsChoose=this.parentContainerEl.querySelector(".rs-box-choose"),this.rsConnected=this.parentContainerEl.querySelector(".rs-box-connected"),this.rsSignIn=this.parentContainerEl.querySelector(".rs-box-sign-in"),this.rsConnectedLabel=this.parentContainerEl.querySelector(".rs-box-connected .rs-sub-headline"),this.rsChooseRemoteStorageButton=this.parentContainerEl.querySelector("button.rs-choose-rs"),this.rsChooseDropboxButton=this.parentContainerEl.querySelector("button.rs-choose-dropbox"),this.rsChooseGoogleDriveButton=this.parentContainerEl.querySelector("button.rs-choose-googledrive"),this.rsErrorBox=this.parentContainerEl.querySelector(".rs-box-error .rs-error-message"),this.rs.apiKeys.hasOwnProperty("googledrive")||this.rsChooseGoogleDriveButton.parentNode.removeChild(this.rsChooseGoogleDriveButton),this.rs.apiKeys.hasOwnProperty("dropbox")||this.rsChooseDropboxButton.parentNode.removeChild(this.rsChooseDropboxButton),this.rsSignInForm=this.parentContainerEl.querySelector(".rs-sign-in-form"),this.rsAddressInput=this.rsSignInForm.querySelector("input[name=rs-user-address]"),this.rsConnectButton=this.parentContainerEl.querySelector(".rs-connect"),this.rsDisconnectButton=this.parentContainerEl.querySelector(".rs-disconnect"),this.rsSyncButton=this.parentContainerEl.querySelector(".rs-sync"),this.rsLogo=this.parentContainerEl.querySelector(".rs-widget-icon"),this.rsErrorReconnectLink=this.parentContainerEl.querySelector(".rs-box-error a.rs-reconnect"),this.rsErrorDisconnectButton=this.parentContainerEl.querySelector(".rs-box-error button.rs-disconnect"),this.rsConnectedUser=this.parentContainerEl.querySelector(".rs-connected-text h1.rs-user")}},{key:"setupHandlers",value:function(){var e=this;this.rs.on("connected",function(){return e.eventHandler("connected")}),this.rs.on("ready",function(){return e.eventHandler("ready")}),this.rs.on("disconnected",function(){return e.eventHandler("disconnected")}),this.rs.on("network-online",function(){return e.eventHandler("network-online")}),this.rs.on("network-offline",function(){return e.eventHandler("network-offline")}),this.rs.on("error",function(t){return e.eventHandler("error",t)}),this.setEventListeners(),this.setClickHandlers()}},{key:"attach",value:function(e){var t=this.createHtmlTemplate(e);if(this.parentContainerEl,e instanceof HTMLElement)this.parentContainerEl=e;else if("string"==typeof e){if(this.parentContainerEl=document.getElementById(e),!this.parentContainerEl)throw new Error('Failed to find target DOM element with id="'+e+'"')}else{if(e)throw new Error("Unknown element type. Expected instance of HTMLElement or type of string.");this.parentContainerEl=document.body}this.parentContainerEl.appendChild(t),this.setupElements(),this.setupHandlers(),this.setInitialState(),this.setModalClass()}},{key:"setEventListeners",value:function(){var e=this;this.rsSignInForm.addEventListener("submit",function(t){t.preventDefault();var r=e.parentContainerEl.querySelector("input[name=rs-user-address]").value.trim();e.disableConnectButton(),e.rs.connect(r)})}},{key:"showChooseOrSignIn",value:function(){this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.style.display="block",this.rsBackdrop.classList.add("visible")),this.rs.apiKeys&&Object.keys(this.rs.apiKeys).length>0?this.setState("choose"):this.setState("sign-in")}},{key:"setClickHandlers",value:function(){var e=this;this.rsInitial.addEventListener("click",function(){return e.showChooseOrSignIn()}),this.rsChooseRemoteStorageButton.addEventListener("click",function(){e.setState("sign-in"),e.rsAddressInput.focus()}),this.rsChooseDropboxButton.addEventListener("click",function(){return e.rs.dropbox.connect()}),this.rsChooseGoogleDriveButton.addEventListener("click",function(){return e.rs.googledrive.connect()}),this.rsDisconnectButton.addEventListener("click",function(){return e.rs.disconnect()}),this.rsErrorReconnectLink.addEventListener("click",function(){return e.rs.reconnect()}),this.rsErrorDisconnectButton.addEventListener("click",function(){return e.rs.disconnect()}),this.rs.hasFeature("Sync")&&this.rsSyncButton.addEventListener("click",function(){e.rsSyncButton.classList.contains("rs-rotate")?(e.rs.stopSync(),e.rsSyncButton.classList.remove("rs-rotate")):(e.rsConnectedLabel.textContent="Synchronizing",e.rs.startSync(),e.rsSyncButton.classList.add("rs-rotate"))}),document.addEventListener("click",function(){return e.close()}),this.rsWidget.addEventListener("click",function(e){return e.stopPropagation()}),this.rsLogo.addEventListener("click",function(){return e.toggle()})}},{key:"toggle",value:function(){this.closed?this.open():"initial"===this.state?this.showChooseOrSignIn():this.close()}},{key:"open",value:function(){this.closed=!1,this.rsWidget.classList.remove("rs-closed"),this.shouldCloseWhenSyncDone=!1;var e=this.parentContainerEl.querySelector(".rs-box.rs-selected");e&&e.setAttribute("aria-hidden","false")}},{key:"close",value:function(){var e=this;if("error"!==this.state){if(!this.leaveOpen&&this.active){this.closed=!0,this.rsWidget.classList.add("rs-closed");var t=this.parentContainerEl.querySelector(".rs-box.rs-selected");t&&t.setAttribute("aria-hidden","true")}else this.active?this.setState("connected"):this.setInitialState();this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.classList.remove("visible"),setTimeout(function(){e.rsBackdrop.style.display="none"},300))}}},{key:"disableConnectButton",value:function(){this.rsConnectButton.disabled=!0,this.rsConnectButton.classList.add("rs-connecting"),this.rsConnectButton.innerHTML="Connecting ".concat('\n \n \n \n \n \n \n\n')}},{key:"enableConnectButton",value:function(){this.rsConnectButton.disabled=!1,this.rsConnectButton.textContent="Connect",this.rsConnectButton.classList.remove("rs-connecting")}},{key:"setOffline",value:function(){this.online&&(this.rsWidget.classList.add("rs-offline"),this.rsConnectedLabel.textContent="Offline",this.online=!1)}},{key:"setOnline",value:function(){this.online||(this.rsWidget.classList.remove("rs-offline"),this.active&&(this.rsConnectedLabel.textContent="Connected")),this.online=!0}},{key:"setBackendClass",value:function(e){this.rsWidget.classList.remove("rs-backend-remotestorage"),this.rsWidget.classList.remove("rs-backend-dropbox"),this.rsWidget.classList.remove("rs-backend-googledrive"),e&&this.rsWidget.classList.add("rs-backend-".concat(e))}},{key:"showErrorBox",value:function(e){this.rsErrorBox.innerHTML=e,this.setState("error")}},{key:"hideErrorBox",value:function(){this.rsErrorBox.innerHTML="",this.close()}},{key:"handleSyncStarted",value:function(){var e=this;this.syncInProgress=!0,this.rsSyncButton.classList.add("rs-rotate"),setTimeout(function(){e.syncInProgress&&(e.rsConnectedLabel.textContent="Synchronizing")},1e3)}},{key:"handleDiscoveryError",value:function(e){var t=this.parentContainerEl.querySelector(".rs-sign-in-error");t.innerHTML=e.message,t.classList.remove("rs-hidden"),t.classList.add("rs-visible"),this.enableConnectButton()}},{key:"handleSyncError",value:function(){this.setOffline()}},{key:"handleUnauthorized",value:function(e){e.code&&"access_denied"===e.code?this.rs.disconnect():(this.open(),this.showErrorBox(e.message+" "),this.rsErrorBox.appendChild(this.rsErrorReconnectLink),this.rsErrorReconnectLink.classList.remove("rs-hidden"))}},{key:"updateLastSyncedStatus",value:function(){var e=new Date;this.online?(this.lastSynced=e,this.rsConnectedLabel.textContent="Synced"):this.rsWidget.classList.contains("rs-state-unauthorized")||(this.rsConnectedLabel.textContent="Offline")}},{key:"isSmallScreen",value:function(){return window.innerWidth<421}}],t&&function(e,t){for(var r=0;r{r?this.updated.push(this.wrapRecord(e)):(this.added.push(this.wrapRecord(e)),r=!0)}),this.recordCaches.set(e,t)}return t}constructor(e,t,r,n,i,o){this.wrapRecord=i,this.release=o,this.recordArrayCache=createCache(()=>{let o=new Set;consumeTag(tagFor(e,"[]")),iterate(e,e=>{getValue$1(this.getCacheForItem(e)),o.add(e)}),untrack(()=>{this.recordCaches.forEach((e,t)=>{o.has(t)||(this.removed.push(i(t)),this.recordCaches.delete(t))})}),this.added.length>0&&(t(this.added),this.added=[]),this.updated.length>0&&(r(this.updated),this.updated=[]),this.removed.length>0&&(n(this.removed),this.removed=[])})}revalidate(){getValue$1(this.recordArrayCache)}}class TypeWatcher{constructor(e,t,r){this.release=r;let n=!1;this.cache=createCache(()=>{iterate(e,()=>{}),consumeTag(tagFor(e,"[]")),!0===n?next(t):n=!0}),this.release=r}revalidate(){getValue$1(this.cache)}}class DataAdapter extends EmberObject{releaseMethods=A$1();recordsWatchers=new Map;typeWatchers=new Map;flushWatchers=null;constructor(e){super(e),this.containerDebugAdapter=getOwner$2(this).lookup("container-debug-adapter:main")}attributeLimit=3;acceptsModelName=!0;getFilters(){return A$1()}watchModelTypes(e,t){let r,n=this.getModelTypes(),i=A$1();r=n.map(e=>{let r=e.klass,n=this.wrapModelType(r,e.name);return i.push(this.observeModelType(e.name,t)),n}),e(r);let o=()=>{i.forEach(e=>e()),this.releaseMethods.removeObject(o)};return this.releaseMethods.pushObject(o),o}_nameToClass(e){if("string"==typeof e){let t=getOwner$2(this).factoryFor(`model:${e}`);e=t&&t.class}return e}watchRecords(e,t,r,n){let i=this._nameToClass(e),o=this.getRecords(i,e),{recordsWatchers:s}=this,a=s.get(o);return a||(a=new RecordsWatcher(o,t,r,n,e=>this.wrapRecord(e),()=>{s.delete(o),this.updateFlushWatchers()}),s.set(o,a),this.updateFlushWatchers(),a.revalidate()),a.release}updateFlushWatchers(){null===this.flushWatchers?(this.typeWatchers.size>0||this.recordsWatchers.size>0)&&(this.flushWatchers=()=>{this.typeWatchers.forEach(e=>e.revalidate()),this.recordsWatchers.forEach(e=>e.revalidate())},_backburner.on("end",this.flushWatchers)):0===this.typeWatchers.size&&0===this.recordsWatchers.size&&(_backburner.off("end",this.flushWatchers),this.flushWatchers=null)}willDestroy(){this._super(...arguments),this.typeWatchers.forEach(e=>e.release()),this.recordsWatchers.forEach(e=>e.release()),this.releaseMethods.forEach(e=>e()),this.flushWatchers&&_backburner.off("end",this.flushWatchers)}detect(e){return!1}columnsForType(e){return A$1()}observeModelType(e,t){let r=this._nameToClass(e),n=this.getRecords(r,e),{typeWatchers:i}=this,o=i.get(n);return o||(o=new TypeWatcher(n,()=>{t([this.wrapModelType(r,e)])},()=>{i.delete(n),this.updateFlushWatchers()}),i.set(n,o),this.updateFlushWatchers(),o.revalidate()),o.release}wrapModelType(e,t){return{name:t,count:get$7(this.getRecords(e,t),"length"),columns:this.columnsForType(e),object:e}}getModelTypes(){let e=this.containerDebugAdapter,t=(e.canCatalogEntriesByType("model")?e.catalogEntriesByType("model"):this._getObjectsOnNamespaces()).map(e=>({klass:this._nameToClass(e),name:e}));return t.filter(e=>this.detect(e.klass))}_getObjectsOnNamespaces(){let e=Namespace.NAMESPACES,t=[];return e.forEach(e=>{for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!this.detect(e[r]))continue;let n=dasherize$1(r);t.push(n)}}),t}getRecords(e,t){return A$1()}wrapRecord(e){return{object:e,columnValues:this.getRecordColumnValues(e),searchKeywords:this.getRecordKeywords(e),filterValues:this.getRecordFilterValues(e),color:this.getRecordColor(e)}}getRecordColumnValues(e){return{}}getRecordKeywords(e){return A$1()}getRecordFilterValues(e){return{}}getRecordColor(e){return null}}const ARRAY_OBSERVER_MAPPING={willChange:"_arrangedContentArrayWillChange",didChange:"_arrangedContentArrayDidChange"};function customTagForArrayProxy(e,t){return"[]"===t?(e._revalidate(),e._arrTag):"length"===t?(e._revalidate(),e._lengthTag):tagFor(e,t)}class ArrayProxy extends EmberObject{_objectsDirtyIndex=0;_objects=null;_lengthDirty=!0;_length=0;_arrangedContent=null;_arrangedContentIsUpdating=!1;_arrangedContentTag=null;_arrangedContentRevision=null;_lengthTag=null;_arrTag=null;init(e){super.init(e),setCustomTagFor(this,customTagForArrayProxy)}[PROPERTY_DID_CHANGE](){this._revalidate()}willDestroy(){this._removeArrangedContentArrayObserver()}objectAtContent(e){return objectAt(get$7(this,"arrangedContent"),e)}replace(e,t,r){this.replaceContent(e,t,r)}replaceContent(e,t,r){replace(get$7(this,"content"),e,t,r)}objectAt(e){if(this._revalidate(),null===this._objects&&(this._objects=[]),-1!==this._objectsDirtyIndex&&e>=this._objectsDirtyIndex){let e=get$7(this,"arrangedContent");if(e){let t=this._objects.length=get$7(e,"length");for(let e=this._objectsDirtyIndex;ei)&&(this._objectsDirtyIndex=i),this._lengthDirty=!0,arrayContentDidChange(this,t,r,n,!1)}_invalidate(){this._objectsDirtyIndex=0,this._lengthDirty=!0}_revalidate(){if(!0!==this._arrangedContentIsUpdating&&(null===this._arrangedContentTag||!validateTag(this._arrangedContentTag,this._arrangedContentRevision))){let e=this.get("arrangedContent");null===this._arrangedContentTag?this._addArrangedContentArrayObserver(e):(this._arrangedContentIsUpdating=!0,this._updateArrangedContentArray(e),this._arrangedContentIsUpdating=!1);let t=this._arrangedContentTag=tagFor(this,"arrangedContent");this._arrangedContentRevision=valueForTag(this._arrangedContentTag),isObject(e)?(this._lengthTag=combine([t,tagForProperty(e,"length")]),this._arrTag=combine([t,tagForProperty(e,"[]")])):this._lengthTag=this._arrTag=t}}}ArrayProxy.reopen(MutableArray,{arrangedContent:alias("content")});const proxy$1=Object.freeze(Object.defineProperty({__proto__:null,default:ArrayProxy},Symbol.toStringTag,{value:"Module"}));class ObjectProxy extends FrameworkObject{}ObjectProxy.PrototypeMixin.reopen(ProxyMixin);const proxy=Object.freeze(Object.defineProperty({__proto__:null,default:ObjectProxy},Symbol.toStringTag,{value:"Module"}));function tap(e,t){return setProperties(e,{isFulfilled:!1,isRejected:!1}),t.then(t=>(e.isDestroyed||e.isDestroying||setProperties(e,{content:t,isFulfilled:!0}),t),t=>{throw e.isDestroyed||e.isDestroying||setProperties(e,{reason:t,isRejected:!0}),t},"Ember: PromiseProxy")}const PromiseProxyMixin=Mixin.create({reason:null,isPending:computed("isSettled",function(){return!get$7(this,"isSettled")}).readOnly(),isSettled:computed("isRejected","isFulfilled",function(){return get$7(this,"isRejected")||get$7(this,"isFulfilled")}).readOnly(),isRejected:!1,isFulfilled:!1,promise:computed({get(){throw new Error("PromiseProxy's promise must be set")},set(e,t){return tap(this,t)}}),then:promiseAlias("then"),catch:promiseAlias("catch"),finally:promiseAlias("finally")});function promiseAlias(e){return function(...t){return get$7(this,"promise")[e](...t)}}const promiseProxyMixin=Object.freeze(Object.defineProperty({__proto__:null,default:PromiseProxyMixin},Symbol.toStringTag,{value:"Module"}));function controllerFor(e,t,r){return e.lookup(`controller:${t}`,r)}let Ember;!function(e){function t(){}e.isNamespace=!0,e.toString=function(){return"Ember"},e.Container=Container,e.Registry=Registry,e._setComponentManager=setComponentManager,e._componentManagerCapabilities=componentCapabilities,e._modifierManagerCapabilities=modifierCapabilities,e.meta=meta$1,e._createCache=createCache,e._cacheGetValue=getValue$1,e._cacheIsConst=isConst,e._descriptor=nativeDescDecorator,e._getPath=_getPath,e._setClassicDecorator=setClassicDecorator,e._tracked=tracked,e.beginPropertyChanges=beginPropertyChanges,e.changeProperties=changeProperties,e.endPropertyChanges=endPropertyChanges,e.hasListeners=hasListeners,e.libraries=LIBRARIES,e._ContainerProxyMixin=ContainerProxyMixin,e._ProxyMixin=ProxyMixin,e._RegistryProxyMixin=RegistryProxyMixin,e.ActionHandler=ActionHandler,e.Comparable=Comparable,e.ComponentLookup=ComponentLookup,e.EventDispatcher=EventDispatcher,e._Cache=Cache$1,e.GUID_KEY=GUID_KEY,e.canInvoke=canInvoke,e.generateGuid=generateGuid,e.guidFor=guidFor,e.uuid=uuid$1,e.wrap=wrap$2,e.getOwner=getOwner,e.onLoad=onLoad,e.runLoadHooks=runLoadHooks,e.setOwner=setOwner,e.Application=Application$1,e.ApplicationInstance=ApplicationInstance,e.Namespace=Namespace,e.A=A$1,e.Array=EmberArray,e.NativeArray=NativeArray,e.isArray=isArray$4,e.makeArray=makeArray,e.MutableArray=MutableArray,e.ArrayProxy=ArrayProxy,e.FEATURES={isEnabled:isEnabled,...FEATURES},e._Input=Input,e.Component=Component,e.Helper=Helper,e.Controller=Controller,e.ControllerMixin=ControllerMixin,e._captureRenderTree=captureRenderTree,e.assert=assert$3,e.warn=warn$1,e.debug=debug$2,e.deprecate=deprecate,e.deprecateFunc=deprecateFunc,e.runInDebug=runInDebug,e.inspect=inspect,e.Debug={registerDeprecationHandler:registerHandler$1,registerWarnHandler:registerHandler,isComputed:isComputed},e.ContainerDebugAdapter=ContainerDebugAdapter,e.DataAdapter=DataAdapter,e._assertDestroyablesDestroyed=assertDestroyablesDestroyed,e._associateDestroyableChild=associateDestroyableChild,e._enableDestroyableTracking=enableDestroyableTracking,e._isDestroying=isDestroying,e._isDestroyed=isDestroyed,e._registerDestructor=registerDestructor,e._unregisterDestructor=unregisterDestructor,e.destroy=destroy,e.Engine=Engine,e.EngineInstance=EngineInstance,e.Enumerable=Enumerable,e.MutableEnumerable=MutableEnumerable,e.instrument=instrument,e.subscribe=subscribe,e.Instrumentation={instrument:instrument,subscribe:subscribe,unsubscribe:unsubscribe,reset:reset$1},e.Object=EmberObject,e._action=action,e.computed=computed,e.defineProperty=defineProperty,e.get=get$7,e.getProperties=getProperties,e.notifyPropertyChange=notifyPropertyChange,e.observer=observer,e.set=set$1,e.trySet=trySet,e.setProperties=setProperties,e.cacheFor=getCachedValueFor,e._dependentKeyCompat=dependentKeyCompat,e.ComputedProperty=ComputedProperty,e.expandProperties=expandProperties,e.CoreObject=CoreObject,e.Evented=Evented,e.on=on$3,e.addListener=addListener,e.removeListener=removeListener,e.sendEvent=sendEvent,e.Mixin=Mixin,e.mixin=mixin,e.Observable=Observable$2,e.addObserver=addObserver,e.removeObserver=removeObserver,e.PromiseProxyMixin=PromiseProxyMixin,e.ObjectProxy=ObjectProxy,e.RouterDSL=DSLImpl,e.controllerFor=controllerFor,e.generateController=generateController,e.generateControllerFactory=generateControllerFactory,e.HashLocation=HashLocation,e.HistoryLocation=HistoryLocation,e.NoneLocation=NoneLocation,e.Route=Route,e.Router=EmberRouter,e.run=run,e.Service=Service,e.compare=compare$1,e.isBlank=isBlank,e.isEmpty=isEmpty$4,e.isEqual=isEqual,e.isNone=isNone,e.isPresent=isPresent,e.typeOf=typeOf$1,e.VERSION=Version,e.ViewUtils={getChildViews:getChildViews,getElementView:getElementView,getRootViews:getRootViews,getViewBounds:getViewBounds,getViewBoundingClientRect:getViewBoundingClientRect,getViewClientRects:getViewClientRects,getViewElement:getViewElement,isSimpleClick:isSimpleClick,isSerializationFirstNode:isSerializationFirstNode},e._getComponentTemplate=getComponentTemplate,e._helperManagerCapabilities=helperCapabilities,e._setComponentTemplate=setComponentTemplate,e._setHelperManager=setHelperManager,e._setModifierManager=setModifierManager$1,e._templateOnlyComponent=templateOnlyComponent,e._invokeHelper=invokeHelper,e._hash=hash$3,e._array=array$1,e._concat=concat$1,e._get=get$6,e._on=on$1,e._fn=fn$1,e._Backburner=Backburner,e.inject=t,t.controller=inject$1,t.service=service,e.__loader={get require(){return globalThis.require},get define(){return globalThis.define},get registry(){let e=globalThis;return e.requirejs?.entries??e.require.entries}}}(Ember||(Ember={})),Reflect.set(Ember,"RSVP",RSVP$1),Object.defineProperty(Ember,"ENV",{get:getENV,enumerable:!1}),Object.defineProperty(Ember,"lookup",{get:getLookup,set:setLookup,enumerable:!1}),Object.defineProperty(Ember,"onerror",{get:getOnerror,set:setOnerror,enumerable:!1}),Object.defineProperty(Ember,"testing",{get:isTesting,set:setTesting,enumerable:!1}),Object.defineProperty(Ember,"BOOTED",{configurable:!1,enumerable:!1,get:isSearchDisabled,set:setSearchDisabled}),Object.defineProperty(Ember,"TEMPLATES",{get:getTemplates,set:setTemplates,configurable:!1,enumerable:!1}),Object.defineProperty(Ember,"TEMPLATES",{get:getTemplates,set:setTemplates,configurable:!1,enumerable:!1}),Object.defineProperty(Ember,"testing",{get:isTesting,set:setTesting,enumerable:!1}),runLoadHooks("Ember.Application",Application$1);let EmberHandlebars={template:templateFactory,Utils:{}},EmberHTMLBars={template:templateFactory};function defineEmberTemplateCompilerLazyLoad(e){Object.defineProperty(Ember,e,{configurable:!0,enumerable:!0,get:()=>"Handlebars"===e?EmberHandlebars:EmberHTMLBars})}function defineEmberTestingLazyLoad(e){Object.defineProperty(Ember,e,{configurable:!0,enumerable:!0,get(){}})}defineEmberTemplateCompilerLazyLoad("HTMLBars"),defineEmberTemplateCompilerLazyLoad("Handlebars"),defineEmberTestingLazyLoad("Test"),defineEmberTestingLazyLoad("setupForTesting"),runLoadHooks("Ember");const doNotUseThis=Ember;new Proxy(doNotUseThis,{get:(e,t,r)=>("string"==typeof t&&deprecateUntil(`importing ${t} from the 'ember' barrel file is deprecated.`,DEPRECATIONS.DEPRECATE_IMPORT_EMBER(t)),Reflect.get(e,t,r)),getOwnPropertyDescriptor:(e,t)=>("string"==typeof t&&deprecateUntil(`importing ${t} from the 'ember' barrel file is deprecated.`,DEPRECATIONS.DEPRECATE_IMPORT_EMBER(t)),Object.getOwnPropertyDescriptor(e,t))});const registeredDebounces=new WeakMap;function debounceTask(e,t,...r){if(assert$3(`Called \`destroyable.debounceTask('${t}', ...)\` where 'destroyable.${t}' is not a function.`,"function"==typeof e[t]),e.isDestroying)return;"boolean"==typeof r[r.length-1]&&r[r.length-2];let n,i=registeredDebounces.get(e);i||(i=new Map,registeredDebounces.set(e,i),registerDestructor(e,getDebouncesDisposable(i))),n=i.has(t)?i.get(t).debouncedTask:(...r)=>{i.delete(t),e[t](...r)};let o=debounce(e,n,...r);i.set(t,{debouncedTask:n,cancelId:o})}function getDebouncesDisposable(e){return function(){0!==e.size&&e.forEach(e=>cancel(e.cancelId))}}class StorageService extends Service{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");rs;widget;static{decorateFieldV2(this.prototype,"placesInView",[tracked],function(){return[]})}#de=void initializeDeferredDecorator(this,"placesInView");static{decorateFieldV2(this.prototype,"savedPlaces",[tracked],function(){return[]})}#pe=void initializeDeferredDecorator(this,"savedPlaces");static{decorateFieldV2(this.prototype,"loadedPrefixes",[tracked],function(){return[]})}#fe=void initializeDeferredDecorator(this,"loadedPrefixes");static{decorateFieldV2(this.prototype,"currentBbox",[tracked],function(){return null})}#ge=void initializeDeferredDecorator(this,"currentBbox");static{decorateFieldV2(this.prototype,"lists",[tracked],function(){return[]})}#me=void initializeDeferredDecorator(this,"lists");static{decorateFieldV2(this.prototype,"version",[tracked],function(){return 0})}#ye=void initializeDeferredDecorator(this,"version");static{decorateFieldV2(this.prototype,"initialSyncDone",[tracked],function(){return!1})}#be=void initializeDeferredDecorator(this,"initialSyncDone");static{decorateFieldV2(this.prototype,"connected",[tracked],function(){return!1})}#ve=void initializeDeferredDecorator(this,"connected");static{decorateFieldV2(this.prototype,"userAddress",[tracked],function(){return null})}#_e=void initializeDeferredDecorator(this,"userAddress");static{decorateFieldV2(this.prototype,"isWidgetOpen",[tracked],function(){return!1})}#Ee=void initializeDeferredDecorator(this,"isWidgetOpen");isNewConnection=!0;constructor(){super(...arguments),this.checkInitialConnectionState(),this.rs=new RemoteStorage({modules:[Places$1]}),this.rs.access.claim("places","rw"),this.rs.caching.enable("/places/"),window.remoteStorage=this.rs,this.widget=new Widget(this.rs,{leaveOpen:!0,skipInitial:!0}),this.rs.on("ready",()=>{}),this.rs.on("error",e=>{e&&(console.info("[rs] Error —",`${e.name}: ${e.message}`),"Unauthorized"===e.name&&this.showConnectWidget())}),this.rs.on("connected",()=>{this.connected=!0,this.userAddress=this.rs.remote.userAddress,this.isNewConnection&&(this.toast.show("Remote storage connected",3e3),this.isNewConnection=!1),this.loadLists()}),this.rs.on("not-connected",()=>{this.loadLists()}),this.rs.on("disconnected",()=>{this.connected=!1,this.userAddress=null,this.placesInView=[],this.savedPlaces=[],this.loadedPrefixes=[],this.lists=[],this.initialSyncDone=!1,this.isNewConnection=!0}),this.rs.on("sync-done",()=>{this.initialSyncDone||(this.initialSyncDone=!0,this.loadLists())}),this.rs.scope("/places/").on("change",e=>{e.relativePath.startsWith("_lists/")?this.loadLists():(this.handlePlaceChange(e),debounceTask(this,"reloadCurrentView",200))})}checkInitialConnectionState(){this.isNewConnection=!0;try{if(window.localStorage){const e=["remotestorage:wireclient","remotestorage:dropbox","remotestorage:googledrive"];for(const t of e){const e=window.localStorage.getItem(t);if(e){const t=JSON.parse(e);if(t&&t.token){this.isNewConnection=!1;break}}}}}catch(e){console.warn("Failed to check localStorage for existing connection:",e)}}handlePlaceChange(e){const{newValue:t,relativePath:r}=e,n=r.split("/"),i=n[n.length-1];if(t){const e={...t,id:i},r=this.savedPlaces.findIndex(e=>e.id===i);if(-1!==r){const t=[...this.savedPlaces];t[r]=e,this.savedPlaces=t}else this.savedPlaces=[...this.savedPlaces,e]}else this.savedPlaces=this.savedPlaces.filter(e=>e.id!==i)}get places(){return this.rs.places}notifyChange(){this.version++,debounceTask(this,"reloadCurrentView",200)}reloadCurrentView(){if(!this.currentBbox)return;const e=getGeohashPrefixesInBbox(this.currentBbox);console.debug("Reloading view due to changes, prefixes:",e),this.loadAllPlaces(e)}async loadLists(){try{if(!this.places.lists)return;await this.places.lists.initDefaults();const e=await this.places.lists.getAll();this.lists=e||[],this.lists.forEach(e=>{"to-go"===e.id?e.icon="bookmark":"to-do"===e.id&&(e.icon="check-square")}),this.refreshPlaceListAssociations()}catch(e){console.error("Failed to load lists:",e)}}refreshPlaceListAssociations(){const e=new Map;this.lists.forEach(t=>{t.placeRefs&&Array.isArray(t.placeRefs)&&t.placeRefs.forEach(r=>{r.id&&(e.has(r.id)||e.set(r.id,[]),e.get(r.id).push(t.id))})});const t=t=>{const r=e.get(t.id)||[];return t._listIds=r,t};this.savedPlaces=this.savedPlaces.map(e=>t({...e})),this.placesInView=this.placesInView.map(e=>t({...e}))}async togglePlaceList(e,t,r){if(!e)return;let n=e;if(!e.id||!e.geohash){if(!r)return;n=await this.storePlace(e)}try{return r?await this.places.lists.addPlace(t,n.id,n.geohash):await this.places.lists.removePlace(t,n.id),await this.loadLists(),this.findPlaceById(n.id)}catch(i){throw console.error("Failed to toggle place in list:",i),i}}async loadPlacesInBounds(e){const t=getGeohashPrefixesInBbox(e).filter(e=>!this.loadedPrefixes.includes(e));0!==t.length&&(console.debug("Loading new prefixes:",t),await this.loadAllPlaces(t),this.loadedPrefixes=[...this.loadedPrefixes,...t],this.currentBbox=e)}async loadAllPlaces(e=null){try{const t=await this.places.getPlaces(e);if(t&&Array.isArray(t)){if(e){const r=new Set(e),n=this.placesInView.filter(e=>{if(!e.lat||!e.lon)return!1;try{const t=Geohash.encode(e.lat,e.lon,4);return!r.has(t)}catch{return!0}});this.placesInView=[...n,...t]}else this.placesInView=t;this.refreshPlaceListAssociations()}else e||(this.placesInView=[]);console.debug("Loaded saved places:",this.placesInView.length)}catch(t){console.error("Failed to load places:",t)}}findPlaceById(e){if(!e)return;const t=String(e);let r=this.savedPlaces.find(e=>e.id&&String(e.id)===t);return r||(r=this.placesInView.find(e=>e.id&&String(e.id)===t),r||(r=this.savedPlaces.find(e=>e.osmId&&String(e.osmId)===t),r||(r=this.placesInView.find(e=>e.osmId&&String(e.osmId)===t),r)))}isPlaceSaved(e){return!!this.findPlaceById(e)}async storePlace(e){const t=await this.places.store(e);return this.savedPlaces.some(e=>e.id===t.id)?this.savedPlaces=this.savedPlaces.map(e=>e.id===t.id?t:e):this.savedPlaces=[...this.savedPlaces,t],this.placesInView.some(e=>e.id===t.id)?this.placesInView=this.placesInView.map(e=>e.id===t.id?t:e):this.placesInView=[...this.placesInView,t],t}async updatePlace(e){const t=await this.places.store(e),r=this.savedPlaces.findIndex(e=>e.id===t.id);if(-1!==r){const e=[...this.savedPlaces];e[r]=t,this.savedPlaces=e}return this.placesInView=this.placesInView.map(e=>e.id===t.id?t:e),t}async removePlace(e){await this.places.remove(e.id,e.geohash),this.savedPlaces=this.savedPlaces.filter(t=>t.id!==e.id),this.placesInView.length>0&&(this.placesInView=this.placesInView.filter(t=>t.id!==e.id))}async refreshPlace(e){if(!(e&&e.id&&e.osmId&&e.osmType))return null;try{console.debug(`Checking for updates for ${e.title} (${e.osmId})`);const t=await this.osm.fetchOsmObject(e.osmId,e.osmType);if(!t)return console.warn("Could not fetch fresh data for",e.osmId),null;let r=!1;const n={},i=Math.abs(e.lat-t.lat),o=Math.abs(e.lon-t.lon);(i>1e-5||o>1e-5)&&(r=!0,n.lat=t.lat,n.lon=t.lon);const s=e.osmTags||{},a=t.osmTags||{},l=new Set([...Object.keys(s),...Object.keys(a)]);for(const e of l)if(s[e]!==a[e]){r=!0,n.osmTags=a;break}if(!r)return console.debug("No changes detected for",e.title),null;console.debug("Changes detected:",n);const c={...e,...n},u=getLocalizedName(s),h=getLocalizedName(a);return e.title===u&&u!==h&&(c.title=h),await this.updatePlace(c)}catch(t){return console.error("Failed to refresh place:",t),null}}showConnectWidget(){this.isWidgetOpen=!0,document.querySelector(".rs-widget")||this.widget.attach("rs-widget-container")}static{decorateMethodV2(this.prototype,"showConnectWidget",[action])}closeWidget(){this.isWidgetOpen=!1}static{decorateMethodV2(this.prototype,"closeWidget",[action])}disconnect(){this.rs.disconnect(),this.isWidgetOpen=!1}static{decorateMethodV2(this.prototype,"disconnect",[action])}}const amdModule14=Object.freeze(Object.defineProperty({__proto__:null,default:StorageService},Symbol.toStringTag,{value:"Module"}));class ToastService extends Service{static{decorateFieldV2(this.prototype,"message",[tracked],function(){return null})}#we=void initializeDeferredDecorator(this,"message");static{decorateFieldV2(this.prototype,"isVisible",[tracked],function(){return!1})}#Ce=void initializeDeferredDecorator(this,"isVisible");timeoutId=null;show(e,t=3e3){this.message=e,this.isVisible=!0,this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.isVisible=!1},t)}}const amdModule15=Object.freeze(Object.defineProperty({__proto__:null,default:ToastService},Symbol.toStringTag,{value:"Module"}));function getDistance$1(e,t,r,n){const i=e*Math.PI/180,o=r*Math.PI/180,s=(r-e)*Math.PI/180,a=(n-t)*Math.PI/180,l=Math.sin(s/2)*Math.sin(s/2)+Math.cos(i)*Math.cos(o)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3}const amdModule18=Object.freeze(Object.defineProperty({__proto__:null,getDistance:getDistance$1},Symbol.toStringTag,{value:"Module"})),activity='',arrowLeft='',bookmark='',featherCamera='',checkSquare='',chevronLeft='',chevronRight='',clock='',database='',edit='',facebook='',gift='',globe='',heart='',home='',info='',instagram='',logIn='',logOut='',mail='',map='',mapPin='',menu='',navigation='',phone='',plus='',search='',server='',settings='',target='',trash2='',uploadCloud='',user='',x$1='',check='',alertCircle='',zap='',angelfish='\n \n',barbell='\n \n',climbingWall='\n \n',banknote='\n \n',badgeShieldWithFire='\n \n',beachUmbrellaInGround='\n \n',beerMugWithFoam='\n \n',burgerAndDrinkCupWithStraw='\n \n',bridge='\n \n',bus='\n \n',camera='\n \n',boxingGloveUp='\n \n',car='\n \n',cigaretteWithSmokeCurl='\n \n',classicalBuilding='\n \n',classicalBuildingWithDomeAndFlag='\n \n',classicalBuildingWithFlag='\n \n',commercialBuilding='\n \n',clothesHanger='\n \n',cleaver='\n \n',cloth='\n \n',cocktail='\n \n',coffeeBean='\n \n',comedyMaskAndTragedyMask='\n \n',croissant='\n \n',cupAndSaucer='\n \n',donut='\n \n',eyeglasses='\n \n',fancyMirrorWithReflectionAndStars='\n \n',familyRestroomSymbol='\n \n',film='\n \n',fingernailPolished='\n \n',fish='\n \n',flagCheckered='\n \n',flowerBouquet='\n \n',fort='\n \n',forkAndKnife='\n \n',gravestone='\n \n',grecianVase='\n \n',greekCross='\n \n',iceCreamOnCone='\n \n',industrialBuilding='\n \n',jewel='\n \n',lowriseBuilding='\n \n',marketStall='\n \n',memorialStoneWithInscription='\n \n',mobilePhoneWithKeypadAndAntenna='\n \n',molarTooth='\n \n',needleAndSpoolOfThread='\n \n',openBook='\n \n',palace='\n \n',parkingP='\n \n',personCricketBattingAtCricketBall='\n \n',personBoardingTramWithDestinationDisplayAndPantographOnTramTrack='\n \n',personJockeyingRacehorse='\n \n',personPlayingTennis='\n \n',personRunning='\n \n',personSleepingInBed='\n \n',personSwimmingInWater='\n \n',personSwingingGolfClub='\n \n',plantInRaisedPlanter='\n \n',placeOfWorshipBuilding='\n \n',playStructureWithSlide='\n \n',policeOfficerWithStopArm='\n \n',planeTopRight='\n \n',roundStructureWithFlag='\n \n',sailingShipInWater='\n \n',scissorsOpen='\n \n',shipwreckInWater='\n \n',steamTrainOnRailwayTrack='\n \n',shoppingBag='\n \n',shoppingBasket='\n \n',shoppingCart='\n \n',tableTennisPaddle='\n \n',tattooMachine='\n \n',toolbox='\n \n',treeAndBenchWithBackrest='\n \n',villageBuildings='\n \n',wallHangingWithMountainsAndSun='\n \n',windingWayWide='\n \n',womensAndMensRestroomSymbol='\n \n',loadingRing='',nostrich='\n \n\n',remotestorage='\n\x3c!-- Creator: CorelDRAW X7 --\x3e\n\n \n',whatsapp='\n\n \n\n',wikipedia='\n\n\n',ICONS={activity:activity,angelfish:angelfish,"arrow-left":arrowLeft,barbell:barbell,banknote:banknote,"badge-shield-with-fire":badgeShieldWithFire,"beach-umbrella-in-ground":beachUmbrellaInGround,"beer-mug-with-foam":beerMugWithFoam,bookmark:bookmark,"boxing-glove-up":boxingGloveUp,"burger-and-drink-cup-with-straw":burgerAndDrinkCupWithStraw,bridge:bridge,bus:bus,camera:camera,"feather-camera":featherCamera,"check-square":checkSquare,"chevron-left":chevronLeft,"chevron-right":chevronRight,"cigarette-with-smoke-curl":cigaretteWithSmokeCurl,climbing_wall:climbingWall,check:check,"alert-circle":alertCircle,"classical-building":classicalBuilding,"classical-building-with-dome-and-flag":classicalBuildingWithDomeAndFlag,"classical-building-with-flag":classicalBuildingWithFlag,"commercial-building":commercialBuilding,"clothes-hanger":clothesHanger,cleaver:cleaver,cloth:cloth,cocktail:cocktail,clock:clock,"coffee-bean":coffeeBean,"comedy-mask-and-tragedy-mask":comedyMaskAndTragedyMask,croissant:croissant,"cup-and-saucer":cupAndSaucer,database:database,donut:donut,edit:edit,eyeglasses:eyeglasses,facebook:facebook,"fancy-mirror-with-reflection-and-stars":fancyMirrorWithReflectionAndStars,"family-restroom-symbol":familyRestroomSymbol,film:film,"fingernail-polished":fingernailPolished,fish:fish,"flag-checkered":flagCheckered,"flower-bouquet":flowerBouquet,"fork-and-knife":forkAndKnife,fort:fort,gift:gift,globe:globe,gravestone:gravestone,"grecian-vase":grecianVase,"greek-cross":greekCross,heart:heart,home:home,"ice-cream-on-cone":iceCreamOnCone,"industrial-building":industrialBuilding,info:info,instagram:instagram,jewel:jewel,"log-in":logIn,"log-out":logOut,"lowrise-building":lowriseBuilding,mail:mail,map:map,"map-pin":mapPin,"market-stall":marketStall,"memorial-stone-with-inscription":memorialStoneWithInscription,menu:menu,"mobile-phone-with-keypad-and-antenna":mobilePhoneWithKeypadAndAntenna,"molar-tooth":molarTooth,navigation:navigation,"needle-and-spool-of-thread":needleAndSpoolOfThread,nostrich:nostrich,"open-book":openBook,palace:palace,"person-cricket-batting-at-cricket-ball":personCricketBattingAtCricketBall,"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track":personBoardingTramWithDestinationDisplayAndPantographOnTramTrack,"person-jockeying-racehorse":personJockeyingRacehorse,"person-playing-tennis":personPlayingTennis,"person-running":personRunning,"person-sleeping-in-bed":personSleepingInBed,"person-swimming-in-water":personSwimmingInWater,"person-swinging-golf-club":personSwingingGolfClub,phone:phone,"plane-top-right":planeTopRight,"plant-in-raised-planter":plantInRaisedPlanter,"place-of-worship-building":placeOfWorshipBuilding,"play-structure-with-slide":playStructureWithSlide,"police-officer-with-stop-arm":policeOfficerWithStopArm,plus:plus,"round-structure-with-flag":roundStructureWithFlag,remotestorage:remotestorage,"sailing-ship-in-water":sailingShipInWater,"scissors-open":scissorsOpen,"shipwreck-in-water":shipwreckInWater,"steam-train-on-railway-track":steamTrainOnRailwayTrack,"shopping-bag":shoppingBag,search:search,server:server,settings:settings,"shopping-basket":shoppingBasket,"shopping-cart":shoppingCart,"table-tennis-paddle":tableTennisPaddle,"tattoo-machine":tattooMachine,toolbox:toolbox,target:target,"trash-2":trash2,"upload-cloud":uploadCloud,"tree-and-bench-with-backrest":treeAndBenchWithBackrest,user:user,"village-buildings":villageBuildings,"wall-hanging-with-mountains-and-sun":wallHangingWithMountainsAndSun,"womens-and-mens-restroom-symbol":womensAndMensRestroomSymbol,whatsapp:whatsapp,wikipedia:wikipedia,winding_way_wide:windingWayWide,parking_p:parkingP,car:car,x:x$1,zap:zap,"loading-ring":loadingRing},FILLED_ICONS=["fork-and-knife","wikipedia","whatsapp","cup-and-saucer","coffee-bean","shopping-basket","person-sleeping-in-bed","loading-ring","nostrich"];function getIcon(e){return ICONS[e]}function isIconFilled(e){return FILLED_ICONS.includes(e)}const amdModule20=Object.freeze(Object.defineProperty({__proto__:null,getIcon:getIcon,isIconFilled:isIconFilled},Symbol.toStringTag,{value:"Module"})),POI_ICON_RULES=[{tags:{cuisine:"donut"},icon:"donut"},{tags:{cuisine:"doughnut"},icon:"donut"},{tags:{cuisine:"coffee_shop"},icon:"coffee-bean"},{tags:{cuisine:"coffee"},icon:"coffee-bean"},{tags:{amenity:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{cuisine:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{shop:"ice_cream"},icon:"ice-cream-on-cone"},{tags:{amenity:"cafe"},icon:"cup-and-saucer"},{tags:{amenity:"restaurant"},icon:"fork-and-knife"},{tags:{amenity:"fast_food"},icon:"burger-and-drink-cup-with-straw"},{tags:{amenity:"pub"},icon:"beer-mug-with-foam"},{tags:{amenity:"bar"},icon:"cocktail"},{tags:{amenity:"food_court"},icon:"fork-and-knife"},{tags:{amenity:"childcare"},icon:"family-restroom-symbol"},{tags:{amenity:"community_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_centre"},icon:"family-restroom-symbol"},{tags:{amenity:"social_facility"},icon:"family-restroom-symbol"},{tags:{amenity:"bank"},icon:"banknote"},{tags:{amenity:"place_of_worship"},icon:"place-of-worship-building"},{tags:{amenity:"fire_station"},icon:"badge-shield-with-fire"},{tags:{amenity:"police"},icon:"police-officer-with-stop-arm"},{tags:{amenity:"toilets"},icon:"womens-and-mens-restroom-symbol"},{tags:{amenity:"school"},icon:"open-book"},{tags:{amenity:"driving_school"},icon:"car"},{tags:{shop:"coffee"},icon:"coffee-bean"},{tags:{shop:"tea"},icon:"coffee-bean"},{tags:{shop:"pastry"},icon:"donut"},{tags:{shop:"supermarket"},icon:"shopping-cart"},{tags:{shop:"convenience"},icon:"shopping-basket"},{tags:{shop:"grocery"},icon:"shopping-basket"},{tags:{shop:"greengrocer"},icon:"shopping-basket"},{tags:{shop:"bakery"},icon:"croissant"},{tags:{shop:"butcher"},icon:"cleaver"},{tags:{shop:"seafood"},icon:"fish"},{tags:{shop:"deli"},icon:"shopping-basket"},{tags:{shop:"clothes"},icon:"clothes-hanger"},{tags:{shop:"clothing"},icon:"clothes-hanger"},{tags:{shop:"hairdresser"},icon:"scissors-open"},{tags:{shop:"optician"},icon:"eyeglasses"},{tags:{shop:"fabric"},icon:"cloth"},{tags:{shop:"flea_market"},icon:"market-stall"},{tags:{shop:"kiosk"},icon:"shopping-basket"},{tags:{shop:"leather"},icon:"shopping-bag"},{tags:{shop:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{shop:"jewelry"},icon:"jewel"},{tags:{shop:"jewellery"},icon:"jewel"},{tags:{shop:"tobacco"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"cannabis"},icon:"cigarette-with-smoke-curl"},{tags:{shop:"florist"},icon:"flower-bouquet"},{tags:{shop:"garden_centre"},icon:"plant-in-raised-planter"},{tags:{shop:"estate_agent"},icon:"village-buildings"},{tags:{shop:"mobile_phone"},icon:"mobile-phone-with-keypad-and-antenna"},{tags:{beauty:"nails"},icon:"fingernail-polished"},{tags:{shop:"tattoo"},icon:"tattoo-machine"},{tags:{shop:"beauty"},icon:"fancy-mirror-with-reflection-and-stars"},{tags:{craft:"tailor"},icon:"needle-and-spool-of-thread"},{tags:{office:"estate_agent"},icon:"village-buildings"},{tags:{office:!0},icon:"commercial-building"},{tags:{craft:!0},icon:"toolbox"},{tags:{shop:!0},icon:"shopping-bag"},{tags:{natural:"beach"},icon:"beach-umbrella-in-ground"},{tags:{leisure:"park"},icon:"tree-and-bench-with-backrest"},{tags:{leisure:"playground"},icon:"play-structure-with-slide"},{tags:{aeroway:"aerodrome"},icon:"plane-top-right"},{tags:{aeroway:"heliport"},icon:"plane-top-right"},{tags:{aeroway:"helipad"},icon:"plane-top-right"},{tags:{highway:"bus_stop"},icon:"bus"},{tags:{bus:!0},icon:"bus"},{tags:{railway:"tram_stop"},icon:"person-boarding-tram-with-destination-display-and-pantograph-on-tram-track"},{tags:{tourism:"museum"},icon:"classical-building"},{tags:{tourism:"gallery"},icon:"wall-hanging-with-mountains-and-sun"},{tags:{tourism:"aquarium"},icon:"angelfish"},{tags:{tourism:"theme_park"},icon:"camera"},{tags:{tourism:"attraction"},icon:"camera"},{tags:{tourism:"viewpoint"},icon:"camera"},{tags:{tourism:"zoo"},icon:"camera"},{tags:{tourism:"artwork"},icon:"camera"},{tags:{amenity:"cinema"},icon:"film"},{tags:{amenity:"theatre"},icon:"camera"},{tags:{amenity:"arts_centre"},icon:"comedy-mask-and-tragedy-mask"},{tags:{amenity:"arts_center"},icon:"comedy-mask-and-tragedy-mask"},{tags:{historic:"canal"},icon:"winding_way_wide"},{tags:{historic:"bridge"},icon:"bridge"},{tags:{historic:"bridge_site"},icon:"bridge"},{tags:{historic:"fort"},icon:"fort"},{tags:{historic:"castle"},icon:"palace"},{tags:{historic:"building"},icon:"classical-building-with-flag"},{tags:{historic:"archaeological_site"},icon:"grecian-vase"},{tags:{historic:"memorial"},icon:"memorial-stone-with-inscription"},{tags:{historic:"tomb"},icon:"gravestone"},{tags:{historic:"monument"},icon:"classical-building-with-dome-and-flag"},{tags:{historic:"folly"},icon:"classical-building"},{tags:{historic:"industrial"},icon:"industrial-building"},{tags:{historic:"railway_station"},icon:"steam-train-on-railway-track"},{tags:{historic:"ship"},icon:"sailing-ship-in-water"},{tags:{historic:"wreck"},icon:"shipwreck-in-water"},{tags:{historic:"ruins"},icon:"camera"},{tags:{historic:"ruin"},icon:"camera"},{tags:{historic:"yes"},icon:"camera"},{tags:{tourism:"hotel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"hostel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"motel"},icon:"person-sleeping-in-bed"},{tags:{tourism:"guest_house"},icon:"person-sleeping-in-bed"},{tags:{sport:"motor"},icon:"flag-checkered"},{tags:{sport:"karting"},icon:"flag-checkered"},{tags:{sport:"motocross"},icon:"flag-checkered"},{tags:{sport:"cricket"},icon:"person-cricket-batting-at-cricket-ball"},{tags:{sport:"boxing"},icon:"boxing-glove-up"},{tags:{sport:"martial_arts"},icon:"boxing-glove-up"},{tags:{sport:"tennis"},icon:"person-playing-tennis"},{tags:{sport:"squash"},icon:"person-playing-tennis"},{tags:{sport:"padel"},icon:"person-playing-tennis"},{tags:{sport:"table_tennis"},icon:"table-tennis-paddle"},{tags:{sport:"climbing"},icon:"climbing_wall"},{tags:{leisure:"water_park"},icon:"person-swimming-in-water"},{tags:{sport:"swimming"},icon:"person-swimming-in-water"},{tags:{sport:"golf"},icon:"person-swinging-golf-club"},{tags:{leisure:"golf_course"},icon:"person-swinging-golf-club"},{tags:{sport:"horse_racing"},icon:"person-jockeying-racehorse"},{tags:{sport:"fitness"},icon:"barbell"},{tags:{sport:"fitness_centre"},icon:"barbell"},{tags:{leisure:"fitness_centre"},icon:"barbell"},{tags:{sport:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"stadium"},icon:"round-structure-with-flag"},{tags:{leisure:"sports_centre"},icon:"person-running"},{tags:{leisure:"pitch"},icon:"person-running"},{tags:{sport:!0},icon:"person-running"},{tags:{amenity:"dentist"},icon:"molar-tooth"},{tags:{healthcare:"dentist"},icon:"molar-tooth"},{tags:{healthcare:!0},icon:"greek-cross"},{tags:{amenity:"parking"},icon:"parking_p"},{tags:{building:"commercial"},icon:"commercial-building"},{tags:{building:"apartments"},icon:"lowrise-building"}];function getIconNameForTags(e){if(!e)return null;for(const t of POI_ICON_RULES){let r=!0;for(const[n,i]of Object.entries(t.tags)){const t=e[n];if(!t){r=!1;break}const o=t.split(";").map(e=>e.trim());if(!0!==i&&!o.includes(i)){r=!1;break}}if(r)return t.icon}return null}function getIconSvgForTags(e){const t=getIconNameForTags(e);return t?getIcon(t):null}const amdModule22=Object.freeze(Object.defineProperty({__proto__:null,POI_ICON_RULES:POI_ICON_RULES,getIconNameForTags:getIconNameForTags,getIconSvgForTags:getIconSvgForTags},Symbol.toStringTag,{value:"Module"}));function mapToStorageSchema(e){return{title:e.title||getLocalizedName(e.osmTags,"Untitled Place"),lat:e.lat,lon:e.lon,tags:[],url:e.osmTags?.website,osmId:String(e.osmId||e.id),osmType:e.osmType,osmTags:e.osmTags||{},description:e.description}}const amdModule24=Object.freeze(Object.defineProperty({__proto__:null,mapToStorageSchema:mapToStorageSchema},Symbol.toStringTag,{value:"Module"})),get$5=(e,...t)=>{for(const r of t)if(e[r])return e[r];return null};function getSocialInfo(e,t){if(!e)return null;const r=`${t}.com`,n=get$5(e,`contact:${t}`,t);if(!n)return null;if(n.startsWith("http"))try{const e=new URL(n);return"facebook"===t&&"/profile.php"===e.pathname&&e.searchParams.has("id")?{url:n,username:e.searchParams.get("id")}:{url:n,username:e.pathname.replace(/^\/|\/$/g,"")||n}}catch{return{url:n,username:n}}const i=n.replace(/^@/,"");return{url:`https://${r}/${i}`,username:i}}const amdModule26=Object.freeze(Object.defineProperty({__proto__:null,getSocialInfo:getSocialInfo},Symbol.toStringTag,{value:"Module"}));var q=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#","$","%","*","+",",","-",".",":",";","=","?","@","[","]","^","_","{","|","}","~"],x=e=>{let t=0;for(let r=0;r{var r="";for(let n=1;n<=t;n++){let i=Math.floor(e)/Math.pow(83,t-n)%83;r+=q[Math.floor(i)]}return r},f=e=>{let t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},h=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(12.92*t*255+.5):Math.trunc(255*(1.055*Math.pow(t,.4166666666666667)-.055)+.5)},F=e=>e<0?-1:1,M=(e,t)=>F(e)*Math.pow(Math.abs(e),t),d=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e}},C=e=>{if(!e||e.length<6)throw new d("The blurhash string must be at least 6 characters");let t=x(e[0]),r=Math.floor(t/9)+1,n=t%9+1;if(e.length!==4+2*n*r)throw new d(`blurhash length mismatch: length is ${e.length} but it should be ${4+2*n*r}`)},z=e=>{let t=e>>8&255,r=255&e;return[f(e>>16),f(t),f(r)]},L=(e,t)=>{let r=Math.floor(e/361),n=Math.floor(e/19)%19,i=e%19;return[M((r-9)/9,2)*t,M((n-9)/9,2)*t,M((i-9)/9,2)*t]},U=(e,t,r,n)=>{C(e),n|=1;let i=x(e[0]),o=Math.floor(i/9)+1,s=i%9+1,a=(x(e[1])+1)/166,l=new Array(s*o);for(let h=0;h{let i=0,o=0,s=0,a=t*A;for(let c=0;c(h(e[0])<<16)+(h(e[1])<<8)+h(e[2]),H=(e,t)=>19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*M(e[0]/t,.5)+9.5))))*19+19*Math.floor(Math.max(0,Math.min(18,Math.floor(9*M(e[1]/t,.5)+9.5))))+Math.floor(Math.max(0,Math.min(18,Math.floor(9*M(e[2]/t,.5)+9.5)))),O=(e,t,r,n,i)=>{if(n<1||n>9||i<1||i>9)throw new d("BlurHash must have between 1 and 9 components");if(t*r*4!==e.length)throw new d("Width and height must match the pixels array");let o=[];for(let u=0;un*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*u*o/r));o.push(s)}let s,a=o[0],l=o.slice(1),c="";if(c+=p(n-1+9*(i-1),1),l.length>0){let e=Math.max(...l.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(166*e-.5))));s=(t+1)/166,c+=p(t,1)}else s=1,c+=p(0,1);return c+=p($(a),4),l.forEach(e=>{c+=p(H(e,s),2)}),c},S=O;self.onmessage=async e=>{if("PROCESS_IMAGE"!==e.data?.type)return;const{id:t,file:r,targetWidth:n,targetHeight:i,quality:o,computeBlurhash:s}=e.data;try{let e,c;try{const t=await createImageBitmap(r,{resizeWidth:n,resizeHeight:i,resizeQuality:"high"});if(e=new OffscreenCanvas(n,i),c=e.getContext("2d"),!c)throw new Error("Failed to get 2d context from OffscreenCanvas");c.drawImage(t,0,0,n,i),t.close()}catch(a){console.warn("Hardware resize failed, falling back to stepped software scaling:",a);const t=await r.arrayBuffer(),o=new Blob([t],{type:r.type}),s=await createImageBitmap(o);let l=s.width,u=s.height,h=new OffscreenCanvas(l,u),d=h.getContext("2d");for(d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.drawImage(s,0,0);.5*h.width>n&&.5*h.height>i;){const e=new OffscreenCanvas(Math.floor(.5*h.width),Math.floor(.5*h.height)),t=e.getContext("2d");t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.drawImage(h,0,0,e.width,e.height),h=e}e=new OffscreenCanvas(n,i),c=e.getContext("2d"),c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(h,0,0,n,i),s.close()}let u=null;if(s)try{const e=c.getImageData(0,0,n,i);u=S(e.data,n,i,4,3)}catch(l){console.warn("Could not generate blurhash (possible canvas fingerprinting protection):",l)}const h=await e.convertToBlob({type:"image/jpeg",quality:o}),d=`${n}x${i}`;self.postMessage({id:t,success:!0,blob:h,dim:d,blurhash:u})}catch(error){self.postMessage({id:t,success:!1,error:error.message})}};const amdModule27=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function _toPrimitive(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return"symbol"==typeof t?t:String(t)}function _defineProperty(e,t,r){return(t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _initializerDefineProperty(e,t,r,n){r&&Object.defineProperty(e,t,{enumerable:r.enumerable,configurable:r.configurable,writable:r.writable,value:r.initializer?r.initializer.call(n):void 0})}function _applyDecoratedDescriptor(e,t,r,n){var i={};return Object.keys(n).forEach(function(e){i[e]=n[e]}),i.enumerable=!!i.enumerable,i.configurable=!!i.configurable,("value"in i||i.initializer)&&(i.writable=!0),void 0===(i=r.slice().reverse().reduce(function(r,n){return n(e,t,r)||r},i)).initializer&&(Object.defineProperty(e,t,i),i=null),i}var _dec$1,_dec2,_class$1,_descriptor$1,_descriptor2;const isFastBoot="undefined"!=typeof FastBoot,RouterEvent={ROUTE_DID_CHANGE:"routeDidChange"};function hasResolveRegistration(e){return"resolveRegistration"in e}function hasPageTitleConfig(e){return"object"==typeof e&&null!==e&&"pageTitle"in e}const configKeys=["separator","prepend","replace"];let PageTitleService=(_dec$1=service("router"),_dec2=service("-document"),_class$1=class extends Service{constructor(e){if(super(e),_initializerDefineProperty(this,"router",_descriptor$1,this),_initializerDefineProperty(this,"document",_descriptor2,this),_defineProperty(this,"tokens",[]),_defineProperty(this,"_defaultConfig",{separator:" | ",prepend:!0,replace:null}),_defineProperty(this,"scheduleTitleUpdate",()=>{scheduleOnce("afterRender",this,this._updateTitle)}),this._validateExistingTitleElement(),hasResolveRegistration(e)){const t=e.resolveRegistration("config:environment");hasPageTitleConfig(t)&&configKeys.forEach(e=>{if(!isEmpty$4(t.pageTitle[e])){const r=t.pageTitle[e];this._defaultConfig[e]=r}})}this.router.on(RouterEvent.ROUTE_DID_CHANGE,this.scheduleTitleUpdate)}applyTokenDefaults(e){const t=this._defaultConfig.separator,r=this._defaultConfig.prepend,n=this._defaultConfig.replace;e.previous??=null,e.next??=null,null==e.separator&&(e.separator=t),null==e.prepend&&null!=r&&(e.prepend=r),null==e.replace&&null!=n&&(e.replace=n)}inheritFromPrevious(e){const t=e.previous;t&&(null==e.separator&&(e.separator=t.separator),null==e.prepend&&(e.prepend=t.prepend))}push(e){const t=this._findTokenById(e.id);if(t){const r=this.tokens.indexOf(t),n=[...this.tokens],i=t.previous;return e.previous=i,e.next=t.next,this.inheritFromPrevious(e),this.applyTokenDefaults(e),n.splice(r,1,e),void(this.tokens=n)}const r=this.tokens.slice(-1)[0];r&&(e.previous=r??null,r.next=e,this.inheritFromPrevious(e)),this.applyTokenDefaults(e),this.tokens=[...this.tokens,e]}remove(e){const t=this._findTokenById(e);if(!t)return;const{next:r,previous:n}=t;r&&(r.previous=n),n&&(n.next=r),t.previous=t.next=null;const i=[...this.tokens];i.splice(i.indexOf(t),1),this.tokens=i}get visibleTokens(){const e=this.tokens;let t=e?e.length:0;const r=[];for(;t--;){const n=e[t];if(n){if(n.replace){r.unshift(n);break}r.unshift(n)}}return r}get sortedTokens(){const e=this.visibleTokens;if(!e)return[];let t=!0,r=[];const n=[r],i=[];return e.forEach(e=>{e.front?i.unshift(e):e.prepend?(t&&(t=!1,r=[],n.push(r)),r.unshift(e)):(t||(t=!0,r=[],n.push(r)),r.push(e))}),i.concat(n.reduce((e,t)=>e.concat(t),[]))}toString(){const e=this.sortedTokens,t=[];for(let r=0,n=e.length;r as well.",document.head.querySelectorAll("title").length<=1)}_findTokenById(e){return this.tokens.find(t=>t.id===e)}updateFastbootTitle(e){if(!isFastBoot)return;const t=this.document.head,r=t.childNodes;for(let o=0;onew EmberGlimmerComponentManager(e),GlimmerComponent);const index=Object.freeze(Object.defineProperty({__proto__:null,default:GlimmerComponent},Symbol.toStringTag,{value:"Module"})),setModifierManager=setModifierManager$1,fn=fn$1;function truthConvert(e){return"object"==typeof e&&e&&"isTruthy"in e&&"boolean"==typeof e.isTruthy?e.isTruthy:isArray$4(e)?0!==e.length:!!e}class OrHelper extends Helper{compute(e){for(let t=0,r=e.length;t[htmlSafe],isStrictMode:!0}),this)}}class PlaceEditForm extends GlimmerComponent{static{decorateFieldV2(this.prototype,"title",[tracked],function(){return""})}#Se=void initializeDeferredDecorator(this,"title");static{decorateFieldV2(this.prototype,"description",[tracked],function(){return""})}#Te=void initializeDeferredDecorator(this,"description");constructor(){super(...arguments),this.title=this.args.place?.title||"",this.description=this.args.place?.description||""}get shouldAutofocus(){return"undefined"!=typeof window&&window.innerWidth>768}handleSubmit(e){e.preventDefault(),this.args.onSave&&this.args.onSave({title:this.title,description:this.description})}static{decorateMethodV2(this.prototype,"handleSubmit",[action])}updateTitle(e){this.title=e.target.value}static{decorateMethodV2(this.prototype,"updateTitle",[action])}updateDescription(e){this.description=e.target.value}static{decorateMethodV2(this.prototype,"updateDescription",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,"form"],[24,0,"edit-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-title"],[12],[1,"Title"],[13],[1,"\\n"],[1," "],[11,"input"],[24,1,"edit-title"],[16,2,[30,0,["title"]]],[24,0,"form-control"],[24,"placeholder","Name of the place"],[16,"autofocus",[30,0,["shouldAutofocus"]]],[24,4,"text"],[4,[32,0],["input",[30,0,["updateTitle"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","edit-desc"],[12],[1,"Description"],[13],[1,"\\n "],[11,"textarea"],[24,1,"edit-desc"],[16,2,[30,0,["description"]]],[24,0,"form-control"],[24,"rows","3"],[24,"placeholder","Add some details..."],[4,[32,0],["input",[30,0,["updateDescription"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"edit-actions"],[12],[1,"\\n "],[10,"button"],[14,0,"btn btn-blue"],[14,4,"submit"],[12],[1,"Save"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"Cancel"],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onCancel"],[]]',moduleName:"/home/basti/src/marco/app/components/place-edit-form.gjs",scope:()=>[on],isStrictMode:!0}),this)}}function installElement$1(e,t){const r=e;return r.element=t,r}class ClassBasedModifierManager{capabilities=modifierCapabilities();constructor(e){this.owner=e}createModifier(e,t){return{instance:new e(this.owner,t),element:null}}installModifier(e,t,r){installElement$1(e,t).instance.modify(t,r.positional,r.named)}updateModifier(e,t){e.instance.modify(e.element,t.positional,t.named)}destroyModifier({instance:e}){destroy(e)}}class ClassBasedModifier{constructor(e,t){setOwner(this,e)}modify(e,t,r){}}function installElement(e,t){const r=e;return r.element=t,r}setModifierManager(e=>new ClassBasedModifierManager(e),ClassBasedModifier);class FunctionBasedModifierManager{capabilities=modifierCapabilities();createModifier(e){return{element:null,instance:e}}installModifier(e,t,r){const n=installElement(e,t),{positional:i,named:o}=r,s=e.instance(t,i,o);"function"==typeof s&&(n.teardown=s)}updateModifier(e,t){"function"==typeof e.teardown&&e.teardown();const r=e.instance(e.element,t.positional,t.named);"function"==typeof r&&(e.teardown=r)}destroyModifier(e){"function"==typeof e.teardown&&e.teardown()}getDebugName(e){return e.instance.toString()}getDebugInstance(e){return e}}const MANAGER=new FunctionBasedModifierManager;function modifier(e){return e.toString=()=>e.name,setModifierManager(()=>MANAGER,e)}const onClickOutside=modifier((e,[t])=>{const r=r=>{e&&!e.contains(r.target)&&t(r)},n=setTimeout(()=>{document.addEventListener("click",r)},0);return()=>{clearTimeout(n),document.removeEventListener("click",r)}});class PlaceListsManager extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"_forceClear",[tracked],function(){return!1})}#Ae=void initializeDeferredDecorator(this,"_forceClear");get isSaved(){return this.args.isSaved}get placeListIds(){return this._forceClear?[]:this.args.place._listIds||[]}styleFor(e){return htmlSafe(`background-color: ${e}`)}isInList(e){return!!this.placeListIds&&this.placeListIds.includes(e.id)}static{decorateMethodV2(this.prototype,"isInList",[action])}async toggleSaved(){if(this.isSaved){const{osmId:e,osmType:t}=this.args.place;if(await this.storage.removePlace(this.args.place),this.args.place&&(this.args.place.id=null,this.args.place.createdAt=null,this.args.place._listIds=[],this._forceClear=!0),e&&t){const e={...this.args.place};delete e.id,delete e.createdAt,delete e._listIds,this.router.transitionTo("place",e)}else this.router.transitionTo("index");this.args.onClose&&this.args.onClose()}else await this.storage.storePlace(this.args.place)}static{decorateMethodV2(this.prototype,"toggleSaved",[action])}async toggleList(e){const t=!this.placeListIds.includes(e.id);t&&!this.isSaved&&await this.storage.storePlace(this.args.place);try{await this.storage.togglePlaceList(this.args.place,e.id,t)}catch(r){console.error(r),alert("Failed to update list: "+r.message)}}static{decorateMethodV2(this.prototype,"toggleList",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[24,0,"place-lists-manager"],[4,[32,0],[[30,1]],null],[12],[1,"\\n "],[10,0],[14,0,"list-item master-toggle"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[30,0,["isSaved"]]],[24,4,"checkbox"],[4,[32,1],["change",[30,0,["toggleSaved"]]],null],[12],[13],[1,"\\n "],[10,1],[14,0,"list-color"],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,"Saved places"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"divider"],[12],[13],[1,"\\n\\n "],[10,0],[14,0,"lists-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["storage","lists"]]],null]],null],null,[[[1," "],[10,0],[14,0,"list-item"],[12],[1,"\\n "],[10,"label"],[12],[1,"\\n "],[11,"input"],[16,"checked",[28,[30,0,["isInList"]],[[30,2]],null]],[16,"disabled",[52,[51,[30,0,["isSaved"]]],true]],[24,4,"checkbox"],[4,[32,1],["change",[28,[32,2],[[30,0,["toggleList"]],[30,2]],null]],null],[12],[13],[1,"\\n"],[1," "],[10,1],[14,0,"list-color"],[15,5,[28,[30,0,["styleFor"]],[[30,2,["color"]]],null]],[12],[13],[1,"\\n "],[10,1],[14,0,"list-name"],[12],[1,[30,2,["title"]]],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n"],[13]],["@onClose","list"],["each","-track-array","unless"]]',moduleName:"/home/basti/src/marco/app/components/place-lists-manager.gjs",scope:()=>[onClickOutside,on,fn],isStrictMode:!0}),this)}}class Environment{assert(){}async(e){Promise.resolve().then(e)}reportUncaughtRejection(){this.async(e=>{throw e})}defer(){let e={promise:null,resolve:null,reject:null},t=new Promise((t,r)=>{e.resolve=t,e.reject=r});return e.promise=t,e}globalDebuggingEnabled(){return!1}}const DEFAULT_ENVIRONMENT=new Environment;class BoundedPolicy{constructor(e){this.maxConcurrency=e||1}}const TYPE_CANCELLED="CANCELLED",TYPE_STARTED="STARTED",TYPE_QUEUED="QUEUED",STARTED={type:TYPE_STARTED},QUEUED={type:TYPE_QUEUED},makeCancelState=e=>({type:TYPE_CANCELLED,reason:e}),CANCELLED$2=makeCancelState("it belongs to a 'drop' Task that was already running");class DropReducer{constructor(e){this.remainingSlots=e}step(){return this.remainingSlots>0?(this.remainingSlots--,STARTED):CANCELLED$2}}class DropPolicy extends BoundedPolicy{makeReducer(){return new DropReducer(this.maxConcurrency)}}class EnqueuedReducer{constructor(e){this.remainingSlots=e}step(){return this.remainingSlots>0?(this.remainingSlots--,STARTED):QUEUED}}class EnqueuedPolicy extends BoundedPolicy{makeReducer(){return new EnqueuedReducer(this.maxConcurrency)}}const CANCELLED$1=makeCancelState("it belongs to a 'keepLatest' Task that was already running");class KeepLatestReducer{constructor(e,t){this.remainingSlots=e,this.numToCancel=t}step(){return this.remainingSlots>0?(this.remainingSlots--,STARTED):this.numToCancel>0?(this.numToCancel--,CANCELLED$1):QUEUED}}class KeepLatestPolicy extends BoundedPolicy{makeReducer(e,t){let r=e+t;return new KeepLatestReducer(this.maxConcurrency,r-this.maxConcurrency-1)}}const CANCELLED=makeCancelState("it belongs to a 'restartable' Task that was .perform()ed again");class RestartableReducer{constructor(e){this.numToCancel=e}step(){return this.numToCancel>0?(this.numToCancel--,CANCELLED):STARTED}}class RestartablePolicy extends BoundedPolicy{makeReducer(e,t){return new RestartableReducer(e+t-this.maxConcurrency)}}class UnboundedReducer{step(){return STARTED}}const SINGLETON_REDUCER=new UnboundedReducer;class UnboundedPolicy{makeReducer(){return SINGLETON_REDUCER}}const LAST_APPLIED_TAGS=new Map;class Refresh{constructor(e,t,r){this.stateTracker=t,this.schedulerPolicy=e,this.initialTaskInstances=r,this.startingInstances=[]}process(){let[e,t,r]=this.filterFinishedTaskInstances(),n=this.schedulerPolicy.makeReducer(t,r),i=e.filter(e=>this.setTaskInstanceExecutionState(e,n.step()));return this.stateTracker.computeFinalStates(e=>this.applyState(e)),this.startingInstances.forEach(e=>e.start()),i}filterFinishedTaskInstances(){let e=0,t=0;return[this.initialTaskInstances.filter(r=>{let n=this.stateTracker.stateFor(r.task),i=r.executor.state;return i.isFinished?(n.onCompletion(r),!1):(i.hasStarted?e+=1:t+=1,!0)}),e,t]}setTaskInstanceExecutionState(e,t){let r=this.stateTracker.stateFor(e.task);switch(e.executor.counted||(e.executor.counted=!0,r.onPerformed(e)),t.type){case TYPE_CANCELLED:return e.cancel(t.reason),!1;case TYPE_STARTED:return e.executor.state.hasStarted||(this.startingInstances.push(e),r.onStart(e)),r.onRunning(e),!0;case TYPE_QUEUED:return r.onQueued(e),!0}}applyState(e){let{taskable:t}=e;if(!t.onState)return;const{guid:r}=t;if(LAST_APPLIED_TAGS.has(r)&&e.tage(t))}forEachState(e){this.states.forEach(t=>e(t))}}class NullState{onCompletion(){}onPerformed(){}onStart(){}onRunning(){}onQueued(){}}const NULL_STATE=new NullState;class NullStateTracker{stateFor(){return NULL_STATE}computeFinalStates(){}}class Scheduler{constructor(e,t){this.schedulerPolicy=e,this.stateTrackingEnabled=t,this.taskInstances=[]}cancelAll(e,t){let r=this.taskInstances.map(r=>{r.task.guids[e]&&r.executor.cancel(t)}).filter(e=>!!e);return Promise.all(r)}perform(e){e.onFinalize(()=>this.scheduleRefresh()),this.taskInstances.push(e),this.refresh()}scheduleRefresh(){Promise.resolve().then(()=>this.refresh())}refresh(){let e=this.stateTrackingEnabled?new StateTracker:new NullStateTracker,t=new Refresh(this.schedulerPolicy,e,this.taskInstances);this.taskInstances=t.process()}}class GeneratorStepResult{constructor(e,t,r){this.value=e,this.done=t,this.errored=r}}class GeneratorState{constructor(e){this.done=!1,this.generatorFactory=e,this.iterator=null}step(e,t){try{let r=this.getIterator(),{value:n,done:i}=r[t](e);return i?this.finalize(n,!1):new GeneratorStepResult(n,!1,!1)}catch(r){return this.finalize(r,!0)}}getIterator(){return this.iterator||this.done||(this.iterator=this.generatorFactory()),this.iterator}finalize(e,t){return this.done=!0,this.iterator=null,new GeneratorStepResult(e,!0,t)}}const cancelableSymbol="__ec_cancel__",yieldableSymbol="__ec_yieldable__",YIELDABLE_CONTINUE="next",YIELDABLE_THROW="throw",YIELDABLE_RETURN="return",YIELDABLE_CANCEL="cancel";class YieldableState{constructor(e,t){this._taskInstance=e,this._resumeIndex=t}getTaskInstance(){return this._taskInstance}cancel(){let e=this._taskInstance;e.proceed.call(e,this._resumeIndex,YIELDABLE_CANCEL)}next(e){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,YIELDABLE_CONTINUE,e)}return(e){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,YIELDABLE_RETURN,e)}throw(e){let t=this._taskInstance;t.proceed.call(t,this._resumeIndex,YIELDABLE_THROW,e)}}class Yieldable{constructor(){this[yieldableSymbol]=this[yieldableSymbol].bind(this)}onYield(){}_deferable(){let e={resolve:void 0,reject:void 0};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}_toPromise(){let e=this._deferable(),t={proceed(t,r,n){r==YIELDABLE_CONTINUE||r==YIELDABLE_RETURN?e.resolve(n):e.reject(n)}},r=this[yieldableSymbol](t,0);return e.promise[cancelableSymbol]=r,e.promise}then(...e){return this._toPromise().then(...e)}catch(...e){return this._toPromise().catch(...e)}finally(...e){return this._toPromise().finally(...e)}[yieldableSymbol](e,t){let r=new YieldableState(e,t);return this.onYield(r)}}class ForeverYieldable extends Yieldable{onYield(){}}new ForeverYieldable;const INITIAL_STATE={completionState:COMPLETION_PENDING,value:null,error:null,isSuccessful:!1,isError:!1,isCanceled:!1,hasStarted:!1,isFinished:!1},TASK_CANCELATION_NAME="TaskCancelation";function didCancel(e){return e&&e.name===TASK_CANCELATION_NAME}const CANCEL_KIND_EXPLICIT="explicit",CANCEL_KIND_YIELDABLE_CANCEL="yielded",CANCEL_KIND_LIFESPAN_END="lifespan_end",CANCEL_KIND_PARENT_CANCEL="parent_cancel";class CancelRequest{constructor(e,t){this.kind=e,this.reason=t,this.promise=new Promise(e=>{this.finalize=e})}}const PERFORM_TYPE_DEFAULT="PERFORM_TYPE_DEFAULT",PERFORM_TYPE_UNLINKED="PERFORM_TYPE_UNLINKED",PERFORM_TYPE_LINKED="PERFORM_TYPE_LINKED",CANCEL_RETURN_VALUE_SENTINEL={};let TASK_INSTANCE_STACK=[];function getRunningInstance(){return TASK_INSTANCE_STACK[TASK_INSTANCE_STACK.length-1]}class TaskInstanceExecutor{constructor({generatorFactory:e,env:t,debug:r}){this.generatorState=new GeneratorState(e),this.state=Object.assign({},INITIAL_STATE),this.index=1,this.disposers=[],this.finalizeCallbacks=[],this.env=t,this.debug=r,this.cancelRequest=null}start(){this.state.hasStarted||this.cancelRequest||(this.setState({hasStarted:!0}),this.proceedSync(YIELDABLE_CONTINUE,void 0))}cancel(e){return this.requestCancel(e)?(this.state.hasStarted?this.proceedWithCancelAsync():this.finalizeWithCancel(),this.cancelRequest.promise):(e.finalize(),e.promise)}setState(e){Object.assign(this.state,e),this.taskInstance.setState(this.state)}proceedChecked(e,t,r){this.state.isFinished||this.advanceIndex(e)&&(t===YIELDABLE_CANCEL?(this.requestCancel(new CancelRequest(CANCEL_KIND_YIELDABLE_CANCEL),r),this.proceedWithCancelAsync()):this.proceedAsync(t,r))}proceedWithCancelAsync(){this.proceedAsync(YIELDABLE_RETURN,CANCEL_RETURN_VALUE_SENTINEL)}proceedAsync(e,t){this.advanceIndex(this.index),this.env.async(()=>this.proceedSync(e,t))}proceedSync(e,t){this.state.isFinished||(this.dispose(),this.generatorState.done?this.handleResolvedReturnedValue(e,t):this.handleResolvedContinueValue(e,t))}handleResolvedContinueValue(e,t){let r=this.index,n=this.generatorStep(t,e);this.advanceIndex(r)&&(n.errored?this.finalize(n.value,COMPLETION_ERROR):this.handleYieldedValue(n))}handleResolvedReturnedValue(e,t){switch(e){case YIELDABLE_CONTINUE:case YIELDABLE_RETURN:this.finalize(t,COMPLETION_SUCCESS);break;case YIELDABLE_THROW:this.finalize(t,COMPLETION_ERROR)}}handleYieldedUnknownThenable(e){let t=this.index;e.then(e=>{this.proceedChecked(t,YIELDABLE_CONTINUE,e)},e=>{this.proceedChecked(t,YIELDABLE_THROW,e)})}advanceIndex(e){if(this.index===e)return++this.index}handleYieldedValue(e){let t=e.value;t?(this.addDisposer(t[cancelableSymbol]),t[yieldableSymbol]?this.invokeYieldable(t):"function"==typeof t.then?this.handleYieldedUnknownThenable(t):this.proceedWithSimpleValue(t)):this.proceedWithSimpleValue(t)}proceedWithSimpleValue(e){this.proceedAsync(YIELDABLE_CONTINUE,e)}addDisposer(e){"function"==typeof e&&this.disposers.push(e)}dispose(){let e=this.disposers;0!==e.length&&(this.disposers=[],e.forEach(e=>e()))}generatorStep(e,t){TASK_INSTANCE_STACK.push(this);let r=this.generatorState.step(e,t);if(TASK_INSTANCE_STACK.pop(),this._expectsLinkedYield){let e=r.value;e&&e.performType===PERFORM_TYPE_LINKED||console.warn("You performed a .linked() task without immediately yielding/returning it. This is currently unsupported (but might be supported in future version of ember-concurrency)."),this._expectsLinkedYield=!1}return r}maybeResolveDefer(){this.defer&&this.state.isFinished&&(this.state.completionState===COMPLETION_SUCCESS?this.defer.resolve(this.state.value):this.defer.reject(this.state.error))}onFinalize(e){this.finalizeCallbacks.push(e),this.state.isFinished&&this.runFinalizeCallbacks()}runFinalizeCallbacks(){this.finalizeCallbacks.forEach(e=>e()),this.finalizeCallbacks=[],this.maybeResolveDefer(),this.maybeThrowUnhandledTaskErrorLater()}promise(){return this.defer||(this.defer=this.env.defer(),this.asyncErrorsHandled=!0,this.maybeResolveDefer()),this.defer.promise}maybeThrowUnhandledTaskErrorLater(){this.asyncErrorsHandled||this.state.completionState!==COMPLETION_ERROR||didCancel(this.state.error)||this.env.async(()=>{this.asyncErrorsHandled||this.env.reportUncaughtRejection(this.state.error)})}requestCancel(e){return!this.cancelRequest&&!this.state.isFinished&&(this.cancelRequest=e,!0)}finalize(e,t){if(this.cancelRequest)return this.finalizeWithCancel();let r={completionState:t};t===COMPLETION_SUCCESS?(r.isSuccessful=!0,r.value=e):t===COMPLETION_ERROR?(r.isError=!0,r.error=e):t===COMPLETION_CANCEL&&(r.error=e),this.finalizeShared(r)}finalizeWithCancel(){let e=this.taskInstance.formatCancelReason(this.cancelRequest.reason),t=new Error(e);this.debugEnabled()&&console.log(e),t.name=TASK_CANCELATION_NAME,this.finalizeShared({isCanceled:!0,completionState:COMPLETION_CANCEL,error:t,cancelReason:e}),this.cancelRequest.finalize()}debugEnabled(){return this.debug||this.env.globalDebuggingEnabled()}finalizeShared(e){this.index++,e.isFinished=!0,this.setState(e),this.runFinalizeCallbacks()}invokeYieldable(e){try{let t=e[yieldableSymbol](this.taskInstance,this.index);this.addDisposer(t)}catch(t){this.env.reportUncaughtRejection(t)}}onYielded(e,t){this.asyncErrorsHandled=!0,this.onFinalize(()=>{let r=this.state.completionState;r===COMPLETION_SUCCESS?e.proceed(t,YIELDABLE_CONTINUE,this.state.value):r===COMPLETION_ERROR?e.proceed(t,YIELDABLE_THROW,this.state.error):r===COMPLETION_CANCEL&&e.proceed(t,YIELDABLE_CANCEL,null)});let r=this.getPerformType();if(r!==PERFORM_TYPE_UNLINKED)return()=>{this.detectSelfCancelLoop(r,e),this.cancel(new CancelRequest(CANCEL_KIND_PARENT_CANCEL))}}getPerformType(){return this.taskInstance.performType||PERFORM_TYPE_DEFAULT}detectSelfCancelLoop(e,t){if(e!==PERFORM_TYPE_DEFAULT)return;let r=t.executor&&t.executor.cancelRequest;!r||r.kind!==CANCEL_KIND_LIFESPAN_END||this.cancelRequest||this.state.isFinished||this.taskInstance.selfCancelLoopWarning(t)}}const DEFAULT_STATE={last:null,lastRunning:null,lastPerformed:null,lastSuccessful:null,lastComplete:null,lastErrored:null,lastCanceled:null,lastIncomplete:null,performCount:0};Object.freeze(DEFAULT_STATE);let guidId=0;function makeGuid(){return"ec_"+guidId++}class Taskable{constructor(e){this.context=e.context,this.debug=e.debug||!1,this.enabledModifiers=e.enabledModifiers,this.env=e.env,this.group=e.group,this.hasEnabledEvents=e.hasEnabledEvents,this.modifierOptions=e.modifierOptions,this.name=e.name,this.onStateCallback=e.onStateCallback,this.scheduler=e.scheduler,this.guid=makeGuid(),this.guids={},this.guids[this.guid]=!0,this.group&&Object.assign(this.guids,this.group.guids)}cancelAll(e){let{reason:t,cancelRequestKind:r,resetState:n}=e||{};t=t||".cancelAll() was explicitly called on the Task";let i=new CancelRequest(r||CANCEL_KIND_EXPLICIT,t);return this.scheduler.cancelAll(this.guid,i).then(()=>{n&&this._resetState()})}get _isAlive(){return!0}_resetState(){this.setState(DEFAULT_STATE)}setState(){}}Object.assign(Taskable.prototype,DEFAULT_STATE),Object.assign(Taskable.prototype,{numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"});class TaskLinkProxy{constructor(e,t,r){this.task=e,this.performType=t,this.linkedObject=r}perform(...e){return this.task._performShared(e,this.performType,this.linkedObject)}}let Task$1=class e extends Taskable{constructor(e){super(e),this.generatorFactory=e.generatorFactory,this.perform=this._perform.bind(this)}linked(){let e=getRunningInstance();if(!e)throw new Error("You can only call .linked() from within a task.");return new TaskLinkProxy(this,PERFORM_TYPE_LINKED,e)}unlinked(){return new TaskLinkProxy(this,PERFORM_TYPE_UNLINKED,null)}toString(){return``}_clone(){return new e({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}_curry(...e){let t=this._clone();return t._curryArgs=[...this._curryArgs||[],...e],t}_perform(...e){return this._performShared(e,PERFORM_TYPE_DEFAULT,null)}_performShared(e,t,r){let n=this._curryArgs?[...this._curryArgs,...e]:e,i=this._taskInstanceFactory(n,t,r);return t===PERFORM_TYPE_LINKED&&(r._expectsLinkedYield=!0),this._isAlive||i.cancel(),this.scheduler.perform(i),i}_taskInstanceOptions(e,t,r){return{args:e,executor:new TaskInstanceExecutor({generatorFactory:()=>this.generatorFactory(e),env:this.env,debug:this.debug}),performType:t,hasEnabledEvents:this.hasEnabledEvents}}};function assertUnsetBufferPolicy(e){if(e._hasSetBufferPolicy)throw new Error(`Cannot set multiple buffer policies on a task. ${e._schedulerPolicyClass} has already been set for task '${e.name}'`)}const MODIFIER_REGISTRY={enqueue:(e,t)=>t&&e.setBufferPolicy(EnqueuedPolicy),debug:(e,t)=>t&&e.setDebug(t),drop:(e,t)=>t&&e.setBufferPolicy(DropPolicy),keepLatest:(e,t)=>t&&e.setBufferPolicy(KeepLatestPolicy),maxConcurrency:(e,t)=>e.setMaxConcurrency(t),onState:(e,t)=>e.setOnState(t),restartable:(e,t)=>t&&e.setBufferPolicy(RestartablePolicy)};function hasModifier(e){return e in MODIFIER_REGISTRY}let TaskFactory$1=class{env=DEFAULT_ENVIRONMENT;_debug=null;_enabledModifiers=[];_hasSetConcurrencyConstraint=!1;_hasSetBufferPolicy=!1;_hasEnabledEvents=!1;_maxConcurrency=null;_onStateCallback=(e,t)=>t.setState(e);_schedulerPolicyClass=UnboundedPolicy;constructor(e="",t=null,r={}){this.name=e,this.taskDefinition=t,this.options=r,this._processModifierOptions(r)}createTask(e){let t=this.getTaskOptions(e);return new Task$1(Object.assign({generatorFactory:t=>this.taskDefinition.apply(e,t)},t))}getModifier(e){if(hasModifier(e))return MODIFIER_REGISTRY[e].bind(null,this)}getOptions(){return this.options}getScheduler(e,t){return new Scheduler(e,t)}getTaskOptions(e){let t,r=this._onStateCallback,n=new this._schedulerPolicyClass(this._maxConcurrency);return t=this.getScheduler(n,r&&"function"==typeof r),{context:e,debug:this._debug,env:this.env,name:this.name,group:void 0,scheduler:t,hasEnabledEvents:this._hasEnabledEvents,onStateCallback:r,enabledModifiers:this._enabledModifiers,modifierOptions:this.getOptions()}}setBufferPolicy(e){return assertUnsetBufferPolicy(this),this._hasSetBufferPolicy=!0,this._hasSetConcurrencyConstraint=!0,this._schedulerPolicyClass=e,this}setDebug(e){return this._debug=e,this}setEvented(e){return this._hasEnabledEvents=e,this}setMaxConcurrency(e){return this._hasSetConcurrencyConstraint=!0,this._maxConcurrency=e,this}setName(e){return this.name=e,this}setOnState(e){return this._onStateCallback=e,this}setTaskDefinition(e){return this.taskDefinition=e,this}_processModifierOptions(e){if(e)for(let t of Object.keys(e)){let r=e[t],n=this.getModifier(t);"function"==typeof n&&n(r)&&this._enabledModifiers.push(t)}}};class EmberEnvironment extends Environment{assert(...e){assert$3(...e)}async(e){join$1(()=>schedule("actions",e))}reportUncaughtRejection(e){next(null,function(){const t=getOnerror();if(!t)throw e;t(e)})}defer(){return defer$1()}globalDebuggingEnabled(){return!1}}const EMBER_ENVIRONMENT=new EmberEnvironment;class EmberScheduler extends Scheduler{scheduleRefresh(){once(this,this.refresh)}}const EXPLICIT_CANCEL_REASON=".cancel() was explicitly called";class BaseTaskInstance{constructor({task:e,args:t,executor:r,performType:n,hasEnabledEvents:i}){this.task=e,this.args=t,this.performType=n,this.executor=r,this.executor.taskInstance=this,this.hasEnabledEvents=i}setState(){}formatCancelReason(){}selfCancelLoopWarning(){}onFinalize(e){this.executor.onFinalize(e)}proceed(e,t,r){this.executor.proceedChecked(e,t,r)}[yieldableSymbol](e,t){return this.executor.onYielded(e,t)}cancel(e=EXPLICIT_CANCEL_REASON){this.executor.cancel(new CancelRequest(CANCEL_KIND_EXPLICIT,e))}then(...e){return this.executor.promise().then(...e)}catch(...e){return this.executor.promise().catch(...e)}finally(...e){return this.executor.promise().finally(...e)}toString(){return`${this.task} TaskInstance`}start(){return this.executor.start(),this}}function trackMixin(e,t,r){const n=Object.getOwnPropertyDescriptor(e,r);n.initializer=n.initializer||(()=>e[r]),delete n.value;const i=tracked(t,r,n);return t[r]=i,t}function applyTracked(e,t){return Object.keys(e).reduce((t,r)=>trackMixin(e,t,r),t)}let TRACKED_INITIAL_TASK_STATE,TRACKED_INITIAL_INSTANCE_STATE;Object.assign(BaseTaskInstance.prototype,INITIAL_STATE),Object.assign(BaseTaskInstance.prototype,{state:"waiting",isDropped:!1,isRunning:!0}),TRACKED_INITIAL_TASK_STATE=applyTracked(DEFAULT_STATE,{}),TRACKED_INITIAL_TASK_STATE=applyTracked({numRunning:0,numQueued:0,isRunning:!1,isQueued:!1,isIdle:!0,state:"idle"},TRACKED_INITIAL_TASK_STATE),TRACKED_INITIAL_INSTANCE_STATE=applyTracked(INITIAL_STATE,{}),TRACKED_INITIAL_INSTANCE_STATE=applyTracked({state:"waiting",isDropped:!1,isRunning:!1},TRACKED_INITIAL_INSTANCE_STATE),Object.freeze(TRACKED_INITIAL_TASK_STATE),Object.freeze(TRACKED_INITIAL_INSTANCE_STATE);class TaskInstance extends BaseTaskInstance{setState(e){let t=this._recomputeState(e);Object.assign(this,{...e,isRunning:!e.isFinished,isDropped:"dropped"===t,state:t})}_recomputeState(e){return e.isDropped?"dropped":e.isCanceled?e.hasStarted?"canceled":"dropped":e.isFinished?"finished":e.hasStarted?"running":"waiting"}formatCancelReason(e){return`TaskInstance '${this.getName()}' was canceled because ${e}. For more information, see: http://ember-concurrency.com/docs/task-cancelation-help`}getName(){return this.name||(this.name=this.task&&this.task.name||""),this.name}selfCancelLoopWarning(e){let t=`\`${e.getName()}\``,r=`\`${this.getName()}\``;console.warn(`ember-concurrency detected a potentially hazardous "self-cancel loop" between parent task ${t} and child task ${r}. If you want child task ${r} to be canceled when parent task ${t} is canceled, please change \`.perform()\` to \`.linked().perform()\`. If you want child task ${r} to keep running after parent task ${t} is canceled, change it to \`.unlinked().perform()\``)}triggerEvent(...e){if(!this.hasEnabledEvents)return;let t=this.task,r=t.context,n=t&&t.name;if(r&&r.trigger&&n){let[t,...i]=e;r.trigger(`${n}:${t}`,...i)}}}TRACKED_INITIAL_INSTANCE_STATE&&Object.defineProperties(TaskInstance.prototype,TRACKED_INITIAL_INSTANCE_STATE);const TASKABLE_MIXIN={_performCount:0,setState(e){this._performCount=this._performCount+(e.numPerformedInc||0);let t=e.numRunning>0,r=e.numQueued>0,n=Object.assign({},e,{performCount:this._performCount,isRunning:t,isQueued:r,isIdle:!t&&!r,state:t?"running":"idle"});Object.assign(this,n)},onState(e,t){t.onStateCallback&&t.onStateCallback(e,t)}};class Task extends Task$1{constructor(e){super(e),isDestroying(this.context)||registerDestructor(this.context,()=>{this.cancelAll({reason:"the object it lives on was destroyed or unrendered",cancelRequestKind:CANCEL_KIND_LIFESPAN_END})})}get _isAlive(){return!isDestroying(this.context)}_taskInstanceFactory(e,t,r){let n=this._taskInstanceOptions(e,t,r);return n.task=this,new TaskInstance(n)}_clone(){return new Task({context:this.context,debug:this.debug,env:this.env,generatorFactory:this.generatorFactory,group:this.group,hasEnabledEvents:this.hasEnabledEvents,name:this.name,onStateCallback:this.onStateCallback,scheduler:this.scheduler})}}TRACKED_INITIAL_TASK_STATE&&Object.defineProperties(Task.prototype,TRACKED_INITIAL_TASK_STATE),Object.assign(Task.prototype,TASKABLE_MIXIN);class TaskFactory extends TaskFactory$1{env=EMBER_ENVIRONMENT;createTask(e){assert$3("Cannot create task if a task definition is not provided as generator function",this.taskDefinition);let t=this.getTaskOptions(e);return new Task(Object.assign({generatorFactory:t=>this.taskDefinition.apply(e,t)},t))}getModifier(e){return super.getModifier(e)}getScheduler(e,t){return new EmberScheduler(e,t)}get taskFn(){return this.taskDefinition}set taskFn(e){this.setTaskDefinition(e)}}function buildTask(e,t,r){let n=t;const i=e();return new TaskFactory(r||"",i.generator,n).createTask(i.context)}class Blurhash extends GlimmerComponent{renderBlurhash=modifier((e,[t,r,n])=>{if(!t||!e)return;const i=r||32,o=n||18;e.width=i,e.height=o;const s=e.getContext("2d");if(s)try{const e=j(t,i,o),r=s.createImageData(i,o);r.data.set(e),s.putImageData(r,0,0)}catch(a){console.warn("Failed to decode blurhash:",a.message||a)}});static{setComponentTemplate(templateFactory({id:null,block:'[[[11,"canvas"],[24,0,"blurhash-canvas"],[17,1],[4,[30,0,["renderBlurhash"]],[[30,2],[30,3],[30,4]],null],[12],[13]],["&attrs","@hash","@width","@height"],[]]',moduleName:"/home/basti/src/marco/app/components/blurhash.gjs",isStrictMode:!0}),this)}}const MAX_IMAGE_DIMENSION=1920,IMAGE_QUALITY=.9,MAX_THUMBNAIL_DIMENSION=350,THUMBNAIL_QUALITY=.9;class PlacePhotoUploadItem extends GlimmerComponent{static{decorateFieldV2(this.prototype,"blossom",[service])}#Ie=void initializeDeferredDecorator(this,"blossom");static{decorateFieldV2(this.prototype,"imageProcessor",[service])}#Pe=void initializeDeferredDecorator(this,"imageProcessor");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{decorateFieldV2(this.prototype,"thumbnailUrl",[tracked],function(){return""})}#ke=void initializeDeferredDecorator(this,"thumbnailUrl");static{decorateFieldV2(this.prototype,"blurhash",[tracked],function(){return""})}#Oe=void initializeDeferredDecorator(this,"blurhash");static{decorateFieldV2(this.prototype,"error",[tracked],function(){return""})}#Le=void initializeDeferredDecorator(this,"error");static{decorateFieldV2(this.prototype,"statusText",[tracked],function(){return""})}#Me=void initializeDeferredDecorator(this,"statusText");constructor(){super(...arguments),this.args.file&&(this.thumbnailUrl=URL.createObjectURL(this.args.file),this.uploadTask.perform(this.args.file))}willDestroy(){super.willDestroy(...arguments),this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl)}showErrorToast(){this.error&&this.toast.show(this.error)}static{decorateMethodV2(this.prototype,"showErrorToast",[action])}uploadTask=buildTask(()=>({context:this,generator:function*(e){this.error="",this.statusText="Processing";try{const t=yield this.imageProcessor.process(e,MAX_IMAGE_DIMENSION,IMAGE_QUALITY,!0);this.blurhash=t.blurhash;const r=yield this.imageProcessor.process(e,MAX_THUMBNAIL_DIMENSION,THUMBNAIL_QUALITY,!1);let n,i;const o=isMobile(),s=e=>{"signing"===e&&(this.statusText="Signing photo upload"),"uploading"===e&&(this.statusText="Uploading photo")},a=e=>{"signing"===e&&(this.statusText="Signing thumbnail upload"),"uploading"===e&&(this.statusText="Uploading thumbnail")};if(o)n=yield this.blossom.upload(t.blob,{sequential:!0,onProgress:s}),i=yield this.blossom.upload(r.blob,{sequential:!0,onProgress:a});else{const e=this.blossom.upload(t.blob,{onProgress:s}),o=this.blossom.upload(r.blob,{onProgress:a});[n,i]=yield Promise.all([e,o])}this.args.onSuccess&&this.args.onSuccess({file:e,url:n.url,fallbackUrls:n.fallbackUrls,thumbUrl:i.url,blurhash:t.blurhash,type:"image/jpeg",dim:t.dim,hash:n.hash,thumbHash:i.hash})}catch(t){this.error=t.message}}}),null,"uploadTask");static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[15,0,[29,["photo-upload-item\\n ",[52,[30,0,["uploadTask","isRunning"]],"is-uploading"],"\\n ",[52,[30,0,["error"]],"has-error"]]]],[12],[1,"\\n"],[41,[30,0,["blurhash"]],[[[1," "],[8,[32,0],[[24,0,"place-header-photo-blur"]],[["@hash"],[[30,0,["blurhash"]]]],null],[1,"\\n"]],[]],null],[1," "],[10,"img"],[15,"src",[30,0,["thumbnailUrl"]]],[14,"alt","thumbnail"],[12],[13],[1,"\\n\\n"],[41,[30,0,["uploadTask","isRunning"]],[[[1," "],[10,0],[14,0,"overlay"],[12],[1,"\\n "],[8,[32,1],[[24,0,"spin-animation"]],[["@name","@size","@color"],["loading-ring",24,"white"]],null],[1,"\\n"],[41,[30,0,["statusText"]],[[[1," "],[10,1],[14,0,"upload-status-text"],[12],[1,[30,0,["statusText"]]],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["error"]],[[[1," "],[11,"button"],[24,0,"overlay error-overlay"],[16,"title",[30,0,["error"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["showErrorToast"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["alert-circle",24,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[11,"button"],[24,0,"btn-remove-photo"],[24,"title","Remove photo"],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,1],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",16,"white"]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onRemove","@file"],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload-item.gjs",scope:()=>[Blurhash,IconComponent,on,fn],isStrictMode:!0}),this)}}class AndHelper extends Helper{compute(e){for(let t=0,r=e.length;t!truthConvert(e))}class PlacePhotoUpload extends GlimmerComponent{static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrRelay",[service])}#q=void initializeDeferredDecorator(this,"nostrRelay");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"blossom",[service])}#Ie=void initializeDeferredDecorator(this,"blossom");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{decorateFieldV2(this.prototype,"file",[tracked],function(){return null})}#De=void initializeDeferredDecorator(this,"file");static{decorateFieldV2(this.prototype,"uploadedPhoto",[tracked],function(){return null})}#Ne=void initializeDeferredDecorator(this,"uploadedPhoto");static{decorateFieldV2(this.prototype,"error",[tracked],function(){return""})}#Le=void initializeDeferredDecorator(this,"error");static{decorateFieldV2(this.prototype,"isPublishing",[tracked],function(){return!1})}#Fe=void initializeDeferredDecorator(this,"isPublishing");static{decorateFieldV2(this.prototype,"isDragging",[tracked],function(){return!1})}#$e=void initializeDeferredDecorator(this,"isDragging");get place(){return this.args.place||{}}get title(){return this.place.title||"this place"}get allUploaded(){return this.file&&this.uploadedPhoto&&this.file===this.uploadedPhoto.file}handleFileSelect(e){this.addFile(e.target.files[0]),e.target.value=""}static{decorateMethodV2(this.prototype,"handleFileSelect",[action])}handleDragOver(e){e.preventDefault(),this.isDragging=!0}static{decorateMethodV2(this.prototype,"handleDragOver",[action])}handleDragLeave(e){e.preventDefault(),this.isDragging=!1}static{decorateMethodV2(this.prototype,"handleDragLeave",[action])}handleDrop(e){e.preventDefault(),this.isDragging=!1,e.dataTransfer.files.length>0&&this.addFile(e.dataTransfer.files[0])}static{decorateMethodV2(this.prototype,"handleDrop",[action])}addFile(e){e&&e.type.startsWith("image/")?(this.error="",this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=e,this.uploadedPhoto=null,this.args.onUploadStateChange&&this.args.onUploadStateChange(!0)):this.error="Please select a valid image file."}handleUploadSuccess(e){this.uploadedPhoto=e}static{decorateMethodV2(this.prototype,"handleUploadSuccess",[action])}removeFile(){this.uploadedPhoto&&this.deletePhotoTask.perform(this.uploadedPhoto),this.file=null,this.uploadedPhoto=null,this.args.onUploadStateChange&&this.args.onUploadStateChange(!1)}static{decorateMethodV2(this.prototype,"removeFile",[action])}deletePhotoTask=buildTask(()=>({context:this,generator:function*(e){try{e.hash&&(yield this.blossom.delete(e.hash)),e.thumbHash&&(yield this.blossom.delete(e.thumbHash))}catch(t){this.toast.show(`Failed to delete photo from server: ${t.message}`,5e3)}}}),null,"deletePhotoTask");async publish(){if(!this.nostrAuth.isConnected)return void(this.error="You must connect Nostr first.");if(!this.allUploaded)return void(this.error="Please wait for all photos to finish uploading.");const{osmId:e,lat:t,lon:r}=this.place,n=this.place.osmType||"node";if(e){this.error="",this.isPublishing=!0;try{const i=new EventFactory({signer:this.nostrAuth.signer}),o=[["i",`osm:${n}:${e}`]];t&&r&&(o.push(["g",Geohash.encode(t,r,4)]),o.push(["g",Geohash.encode(t,r,6)]),o.push(["g",Geohash.encode(t,r,7)]),o.push(["g",Geohash.encode(t,r,9)]));const s=this.uploadedPhoto,a=["imeta",`url ${s.url}`];if(a.push(`m ${s.type}`),s.dim&&a.push(`dim ${s.dim}`),a.push("alt A photo of a place"),s.fallbackUrls&&s.fallbackUrls.length>0)for(const e of s.fallbackUrls)a.push(`fallback ${e}`);s.thumbUrl&&a.push(`thumb ${s.thumbUrl}`),s.blurhash&&a.push(`blurhash ${s.blurhash}`),o.push(a);const l={kind:360,content:"",tags:o};l.created_at||(l.created_at=Math.floor(Date.now()/1e3));const c=await i.sign(l);await this.nostrRelay.publish(this.nostrData.activeWriteRelays,c),this.nostrData.store.add(c),this.toast.show("Photo published successfully"),this.file=null,this.uploadedPhoto=null,this.args.onUploadStateChange&&this.args.onUploadStateChange(!1),this.args.onClose&&this.args.onClose(c.id)}catch(i){this.error="Failed to publish: "+i.message}finally{this.isPublishing=!1}}else this.error="This place does not have a valid OSM ID."}static{decorateMethodV2(this.prototype,"publish",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"place-photo-upload"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Add Photo for "],[1,[30,0,["title"]]],[13],[1,"\\n\\n"],[41,[30,0,["error"]],[[[1," "],[10,0],[14,0,"alert alert-error"],[12],[1,"\\n "],[1,[30,0,["error"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["file"]],[[[1," "],[10,0],[14,0,"photo-grid"],[12],[1,"\\n "],[8,[32,0],null,[["@file","@onSuccess","@onRemove"],[[30,0,["file"]],[30,0,["handleUploadSuccess"]],[30,0,["removeFile"]]]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"button"],[24,0,"btn btn-primary btn-publish"],[16,"disabled",[28,[32,1],[[28,[32,2],[[30,0,["allUploaded"]]],null],[30,0,["isPublishing"]]],null]],[24,4,"button"],[4,[32,3],["click",[30,0,["publish"]]],null],[12],[1,"\\n"],[41,[30,0,["isPublishing"]],[[[1," Publishing...\\n"]],[]],[[[1," Publish Photo\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],[[[1," "],[11,0],[16,0,[29,["dropzone ",[52,[30,0,["isDragging"]],"is-dragging"]]]],[4,[32,3],["dragover",[30,0,["handleDragOver"]]],null],[4,[32,3],["dragleave",[30,0,["handleDragLeave"]]],null],[4,[32,3],["drop",[30,0,["handleDrop"]]],null],[12],[1,"\\n "],[10,"label"],[14,"for","photo-upload-input"],[14,0,"dropzone-label"],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size","@color"],["upload-cloud",48,"#ccc"]],null],[1,"\\n "],[10,2],[12],[1,"Drag and drop a photo here, or click to browse"],[13],[1,"\\n "],[13],[1,"\\n "],[11,"input"],[24,1,"photo-upload-input"],[24,"accept","image/*"],[24,0,"file-input-hidden"],[16,"disabled",[30,0,["isPublishing"]]],[24,4,"file"],[4,[32,3],["change",[30,0,["handleFileSelect"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-photo-upload.gjs",scope:()=>[PlacePhotoUploadItem,OrHelper,not,on,IconComponent],isStrictMode:!0}),this)}}var browser={},canPromise,hasRequiredCanPromise;function requireCanPromise(){return hasRequiredCanPromise?canPromise:(hasRequiredCanPromise=1,canPromise=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then})}var qrcode={},utils$1={},hasRequiredUtils$1;function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;let e;hasRequiredUtils$1=1;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return utils$1.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return 4*e+17},utils$1.getSymbolTotalCodewords=function(e){return t[e]},utils$1.getBCHDigit=function(e){let t=0;for(;0!==e;)t++,e>>>=1;return t},utils$1.setToSJISFunction=function(t){if("function"!=typeof t)throw new Error('"toSJISFunc" is not a valid function.');e=t},utils$1.isKanjiModeEnabled=function(){return void 0!==e},utils$1.toSJIS=function(t){return e(t)},utils$1}var errorCorrectionLevel={},hasRequiredErrorCorrectionLevel,bitBuffer,hasRequiredBitBuffer,bitMatrix,hasRequiredBitMatrix;function requireErrorCorrectionLevel(){return hasRequiredErrorCorrectionLevel||(hasRequiredErrorCorrectionLevel=1,(e=errorCorrectionLevel).L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2},e.isValid=function(e){return e&&void 0!==e.bit&&e.bit>=0&&e.bit<4},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+t)}}(t)}catch(n){return r}}),errorCorrectionLevel;var e}function requireBitBuffer(){if(hasRequiredBitBuffer)return bitBuffer;function e(){this.buffer=[],this.length=0}return hasRequiredBitBuffer=1,e.prototype={get:function(e){const t=Math.floor(e/8);return 1==(this.buffer[t]>>>7-e%8&1)},put:function(e,t){for(let r=0;r>>t-r-1&1))},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},bitBuffer=e}function requireBitMatrix(){if(hasRequiredBitMatrix)return bitMatrix;function e(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return hasRequiredBitMatrix=1,e.prototype.set=function(e,t,r,n){const i=e*this.size+t;this.data[i]=r,n&&(this.reservedBit[i]=!0)},e.prototype.get=function(e,t){return this.data[e*this.size+t]},e.prototype.xor=function(e,t,r){this.data[e*this.size+t]^=r},e.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]},bitMatrix=e}var alignmentPattern={},hasRequiredAlignmentPattern;function requireAlignmentPattern(){return hasRequiredAlignmentPattern||(hasRequiredAlignmentPattern=1,function(e){const t=requireUtils$1().getSymbolSize;e.getRowColCoords=function(e){if(1===e)return[];const r=Math.floor(e/7)+2,n=t(e),i=145===n?26:2*Math.ceil((n-13)/(2*r-2)),o=[n-7];for(let t=1;t=0&&e<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(e){const t=e.size;let r=0,n=0,i=0,o=null,s=null;for(let a=0;a=5&&(r+=n-5+3),o=t,n=1),t=e.get(l,a),t===s?i++:(i>=5&&(r+=i-5+3),s=t,i=1)}n>=5&&(r+=n-5+3),i>=5&&(r+=i-5+3)}return r},e.getPenaltyN2=function(e){const t=e.size;let r=0;for(let n=0;n=10&&(1488===n||93===n)&&r++,i=i<<1&2047|e.get(s,o),s>=10&&(1488===i||93===i)&&r++}return 40*r},e.getPenaltyN4=function(e){let t=0;const r=e.data.length;for(let n=0;n=0;){const e=n[0];for(let o=0;o0){const e=new Uint8Array(this.degree);return e.set(n,i),e}return n},reedSolomonEncoder=t}var version={},mode={},versionCheck={},hasRequiredVersionCheck;function requireVersionCheck(){return hasRequiredVersionCheck||(hasRequiredVersionCheck=1,versionCheck.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),versionCheck}var regex={},hasRequiredRegex,hasRequiredMode,hasRequiredVersion;function requireRegex(){if(hasRequiredRegex)return regex;hasRequiredRegex=1;const e="[0-9]+";let t="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";t=t.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+t+")(?:.|[\r\n]))+";regex.KANJI=new RegExp(t,"g"),regex.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),regex.BYTE=new RegExp(r,"g"),regex.NUMERIC=new RegExp(e,"g"),regex.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");const n=new RegExp("^"+t+"$"),i=new RegExp("^"+e+"$"),o=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return regex.testKanji=function(e){return n.test(e)},regex.testNumeric=function(e){return i.test(e)},regex.testAlphanumeric=function(e){return o.test(e)},regex}function requireMode(){return hasRequiredMode||(hasRequiredMode=1,function(e){const t=requireVersionCheck(),r=requireRegex();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!t.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]},e.getBestModeForData=function(t){return r.testNumeric(t)?e.NUMERIC:r.testAlphanumeric(t)?e.ALPHANUMERIC:r.testKanji(t)?e.KANJI:e.BYTE},e.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")},e.isValid=function(e){return e&&e.bit&&e.ccBits},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+t)}}(t)}catch(n){return r}}}(mode)),mode}function requireVersion(){return hasRequiredVersion||(hasRequiredVersion=1,function(e){const t=requireUtils$1(),r=requireErrorCorrectionCode(),n=requireErrorCorrectionLevel(),i=requireMode(),o=requireVersionCheck(),s=t.getBCHDigit(7973);function a(e,t){return i.getCharCountIndicator(e,t)+4}function l(e,t){let r=0;return e.forEach(function(e){const n=a(e.mode,t);r+=n+e.getBitsLength()}),r}e.from=function(e,t){return o.isValid(e)?parseInt(e,10):t},e.getCapacity=function(e,n,s){if(!o.isValid(e))throw new Error("Invalid QR Code version");void 0===s&&(s=i.BYTE);const l=8*(t.getSymbolTotalCodewords(e)-r.getTotalCodewordsCount(e,n));if(s===i.MIXED)return l;const c=l-a(s,e);switch(s){case i.NUMERIC:return Math.floor(c/10*3);case i.ALPHANUMERIC:return Math.floor(c/11*2);case i.KANJI:return Math.floor(c/13);case i.BYTE:default:return Math.floor(c/8)}},e.getBestVersionForData=function(t,r){let o;const s=n.from(r,n.M);if(Array.isArray(t)){if(t.length>1)return function(t,r){for(let n=1;n<=40;n++)if(l(t,n)<=e.getCapacity(n,r,i.MIXED))return n}(t,s);if(0===t.length)return 1;o=t[0]}else o=t;return function(t,r,n){for(let i=1;i<=40;i++)if(r<=e.getCapacity(i,n,t))return i}(o.mode,o.getLength(),s)},e.getEncodedBits=function(e){if(!o.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;t.getBCHDigit(r)-s>=0;)r^=7973<=0;)o^=1335<0&&(r=this.data.substr(t),n=parseInt(r,10),e.put(n,3*i+1))},numericData=t}function requireAlphanumericData(){if(hasRequiredAlphanumericData)return alphanumericData;hasRequiredAlphanumericData=1;const e=requireMode(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(t){this.mode=e.ALPHANUMERIC,this.data=t}return r.getBitsLength=function(e){return 11*Math.floor(e/2)+e%2*6},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=45*t.indexOf(this.data[r]);n+=t.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(t.indexOf(this.data[r]),6)},alphanumericData=r}function requireByteData(){if(hasRequiredByteData)return byteData;hasRequiredByteData=1;const e=requireMode();function t(t){this.mode=e.BYTE,this.data="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}return t.getBitsLength=function(e){return 8*e},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(e){for(let t=0,r=this.data.length;t=33088&&n<=40956)n-=33088;else{if(!(n>=57408&&n<=60351))throw new Error("Invalid SJIS character: "+this.data[r]+"\nMake sure your charset is UTF-8");n-=49472}n=192*(n>>>8&255)+(255&n),e.put(n,13)}},kanjiData=r}var dijkstra={exports:{}},hasRequiredDijkstra,hasRequiredSegments,hasRequiredQrcode;function requireDijkstra(){return hasRequiredDijkstra||(hasRequiredDijkstra=1,function(e){var t={single_source_shortest_paths:function(e,r,n){var i={},o={};o[r]=0;var s,a,l,c,u,h,d,p=t.PriorityQueue.make();for(p.push(r,0);!p.empty();)for(l in a=(s=p.pop()).value,c=s.cost,u=e[a]||{})u.hasOwnProperty(l)&&(h=c+u[l],d=o[l],(void 0===o[l]||d>h)&&(o[l]=h,p.push(l,h),i[l]=a));if(void 0!==n&&void 0===o[n]){var f=["Could not find a path from ",r," to ",n,"."].join("");throw new Error(f)}return i},extract_shortest_path_from_predecessor_list:function(e,t){for(var r=[],n=t;n;)r.push(n),e[n],n=e[n];return r.reverse(),r},find_path:function(e,r,n){var i=t.single_source_shortest_paths(e,r,n);return t.extract_shortest_path_from_predecessor_list(i,n)},PriorityQueue:{make:function(e){var r,n=t.PriorityQueue,i={};for(r in e=e||{},n)n.hasOwnProperty(r)&&(i[r]=n[r]);return i.queue=[],i.sorter=e.sorter||n.default_sorter,i},default_sorter:function(e,t){return e.cost-t.cost},push:function(e,t){var r={value:e,cost:t};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};e.exports=t}(dijkstra)),dijkstra.exports}function requireSegments(){return hasRequiredSegments||(hasRequiredSegments=1,function(e){const t=requireMode(),r=requireNumericData(),n=requireAlphanumericData(),i=requireByteData(),o=requireKanjiData(),s=requireRegex(),a=requireUtils$1(),l=requireDijkstra();function c(e){return unescape(encodeURIComponent(e)).length}function u(e,t,r){const n=[];let i;for(;null!==(i=e.exec(r));)n.push({data:i[0],index:i.index,mode:t,length:i[0].length});return n}function h(e){const r=u(s.NUMERIC,t.NUMERIC,e),n=u(s.ALPHANUMERIC,t.ALPHANUMERIC,e);let i,o;return a.isKanjiModeEnabled()?(i=u(s.BYTE,t.BYTE,e),o=u(s.KANJI,t.KANJI,e)):(i=u(s.BYTE_KANJI,t.BYTE,e),o=[]),r.concat(n,i,o).sort(function(e,t){return e.index-t.index}).map(function(e){return{data:e.data,mode:e.mode,length:e.length}})}function d(e,s){switch(s){case t.NUMERIC:return r.getBitsLength(e);case t.ALPHANUMERIC:return n.getBitsLength(e);case t.KANJI:return o.getBitsLength(e);case t.BYTE:return i.getBitsLength(e)}}function p(e,s){let l;const c=t.getBestModeForData(e);if(l=t.from(s,c),l!==t.BYTE&&l.bit=0?e[e.length-1]:null;return r&&r.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[]))},e.rawSplit=function(t){return e.fromArray(h(t,a.isKanjiModeEnabled()))}}(segments)),segments}function requireQrcode(){if(hasRequiredQrcode)return qrcode;hasRequiredQrcode=1;const e=requireUtils$1(),t=requireErrorCorrectionLevel(),r=requireBitBuffer(),n=requireBitMatrix(),i=requireAlignmentPattern(),o=requireFinderPattern(),s=requireMaskPattern(),a=requireErrorCorrectionCode(),l=requireReedSolomonEncoder(),c=requireVersion(),u=requireFormatInfo(),h=requireMode(),d=requireSegments();function p(e,t,r){const n=e.size,i=u.getEncodedBits(t,r);let o,s;for(o=0;o<15;o++)s=1==(i>>o&1),o<6?e.set(o,8,s,!0):o<8?e.set(o+1,8,s,!0):e.set(n-15+o,8,s,!0),o<8?e.set(8,n-o-1,s,!0):o<9?e.set(8,15-o-1+1,s,!0):e.set(8,15-o-1,s,!0);e.set(n-8,8,1,!0)}return qrcode.create=function(u,f){if(void 0===u||""===u)throw new Error("No input text");let g,m,y=t.M;return void 0!==f&&(y=t.from(f.errorCorrectionLevel,t.M),g=c.from(f.version),m=s.from(f.maskPattern),f.toSJISFunc&&e.setToSJISFunction(f.toSJISFunc)),function(t,u,f,g){let m;if(Array.isArray(t))m=d.fromArray(t);else{if("string"!=typeof t)throw new Error("Invalid data");{let e=u;if(!e){const r=d.rawSplit(t);e=c.getBestVersionForData(r,f)}m=d.fromString(t,e||40)}}const y=c.getBestVersionForData(m,f);if(!y)throw new Error("The amount of data is too big to be stored in a QR Code");if(u){if(u=0&&n<=6&&(0===i||6===i)||i>=0&&i<=6&&(0===n||6===n)||n>=2&&n<=4&&i>=2&&i<=4?e.set(t+n,o+i,!0,!0):e.set(t+n,o+i,!1,!0))}}(_,u),function(e){const t=e.size;for(let r=8;r=7&&function(e,t){const r=e.size,n=c.getEncodedBits(t);let i,o,s;for(let a=0;a<18;a++)i=Math.floor(a/3),o=a%3+r-8-3,s=1==(n>>a&1),e.set(i,o,s,!0),e.set(o,i,s,!0)}(_,u),function(e,t){const r=e.size;let n=-1,i=r-1,o=7,s=0;for(let a=r-1;a>0;a-=2)for(6===a&&a--;;){for(let r=0;r<2;r++)if(!e.isReserved(i,a-r)){let n=!1;s>>o&1)),e.set(i,a-r,n),o--,-1===o&&(s++,o=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}(_,b),isNaN(g)&&(g=s.getBestMask(_,p.bind(null,_,f))),s.applyMask(g,_),p(_,f,g),{modules:_,version:u,errorCorrectionLevel:f,maskPattern:g,segments:m}}(u,g,y,m)},qrcode}var canvas={},utils={},hasRequiredUtils,hasRequiredCanvas;function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(e){function t(e){if("number"==typeof e&&(e=e.toString()),"string"!=typeof e)throw new Error("Color should be defined as hex string");let t=e.slice().replace("#","").split("");if(t.length<3||5===t.length||t.length>8)throw new Error("Invalid hex color: "+e);3!==t.length&&4!==t.length||(t=Array.prototype.concat.apply([],t.map(function(e){return[e,e]}))),6===t.length&&t.push("F","F");const r=parseInt(t.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:255&r,hex:"#"+t.slice(0,6).join("")}}e.getOptions=function(e){e||(e={}),e.color||(e.color={});const r=void 0===e.margin||null===e.margin||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:t(e.color.dark||"#000000ff"),light:t(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}},e.getScale=function(e,t){return t.width&&t.width>=e+2*t.margin?t.width/(e+2*t.margin):t.scale},e.getImageWidth=function(t,r){const n=e.getScale(t,r);return Math.floor((t+2*r.margin)*n)},e.qrToImageData=function(t,r,n){const i=r.modules.size,o=r.modules.data,s=e.getScale(i,n),a=Math.floor((i+2*n.margin)*s),l=n.margin*s,c=[n.color.light,n.color.dark];for(let e=0;e=l&&r>=l&&e':"",h="0&&c>0&&e[l-1]||(i+=s?r("M",c+n,.5+u+n):r("m",o,0),o=0,s=!1),c+1',d='viewBox="0 0 '+c+" "+c+'"',p=''+u+h+"\n";return"function"==typeof o&&o(null,p),p},svgTag}function requireBrowser(){if(hasRequiredBrowser)return browser;hasRequiredBrowser=1;const e=requireCanPromise(),t=requireQrcode(),r=requireCanvas(),n=requireSvgTag();function i(r,n,i,o,s){const a=[].slice.call(arguments,1),l=a.length,c="function"==typeof a[l-1];if(!c&&!e())throw new Error("Callback required as last argument");if(!c){if(l<1)throw new Error("Too few arguments provided");return 1===l?(i=n,n=o=void 0):2!==l||n.getContext||(o=i,i=n,n=void 0),new Promise(function(e,s){try{const s=t.create(i,o);e(r(s,n,o))}catch(a){s(a)}})}if(l<2)throw new Error("Too few arguments provided");2===l?(s=i,i=n,n=o=void 0):3===l&&(n.getContext&&void 0===s?(s=o,o=void 0):(s=o,o=i,i=n,n=void 0));try{const e=t.create(i,o);s(null,r(e,n,o))}catch(u){s(u)}}return browser.create=t.create,browser.toCanvas=i.bind(null,r.render),browser.toDataURL=i.bind(null,r.renderToDataURL),browser.toString=i.bind(null,function(e,t,r){return n.render(e,r)}),browser}var browserExports=requireBrowser();const QRCode=getDefaultExportFromCjs$1(browserExports),qrCode=modifier((e,[t])=>{t&&QRCode.toCanvas(e,t,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).catch(e=>{console.error("Failed to generate QR code",e)})});class NostrConnectComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");get hasExtension(){return"undefined"!=typeof window&&void 0!==window.nostr}async connectExtension(){try{await this.nostrAuth.connectWithExtension(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(e){console.error(e),alert(e.message)}}static{decorateMethodV2(this.prototype,"connectExtension",[action])}async connectApp(){try{await this.nostrAuth.connectWithApp(),this.toast.show("Nostr connected successfully"),this.args.onConnect&&this.args.onConnect()}catch(e){console.error(e),alert(e.message)}}static{decorateMethodV2(this.prototype,"connectApp",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"nostr-connect-modal"],[12],[1,"\\n "],[10,"h2"],[12],[1,"Connect with Nostr"],[13],[1,"\\n\\n "],[10,0],[14,0,"nostr-connect-options"],[12],[1,"\\n"],[41,[30,0,["hasExtension"]],[[[1," "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectExtension"]]],null],[12],[1,"\\n Browser Extension (nos2x, Alby)\\n "],[13],[1,"\\n"]],[]],[[[1," "],[10,"button"],[14,0,"btn btn-outline"],[14,"disabled",""],[14,"title","No Nostr extension found in your browser."],[14,4,"button"],[12],[1,"\\n Browser Extension (Not Found)\\n "],[13],[1,"\\n"]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-primary"],[24,4,"button"],[4,[32,0],["click",[30,0,["connectApp"]]],null],[12],[1,"\\n Mobile Signer App (Amber, etc.)\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[28,[32,1],[[30,0,["nostrAuth","connectStatus"]],"waiting"],null],[[[1," "],[10,0],[14,0,"nostr-connect-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isMobile"]],[[[1," "],[10,2],[12],[1,"Waiting for you to approve the connection in your mobile signer\\n app..."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[12],[1,"Scan this QR code with a compatible Nostr signer app (like\\n Amber):"],[13],[1,"\\n "],[10,0],[14,0,"qr-code-container"],[12],[1,"\\n "],[11,"canvas"],[4,[32,2],[[30,0,["nostrAuth","connectUri"]]],null],[12],[13],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"]],[]],null],[13]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/nostr-connect.gjs",scope:()=>[on,eq$1,qrCode],isStrictMode:!0}),this)}}class Modal extends GlimmerComponent{stopProp(e){e.stopPropagation()}static{decorateMethodV2(this.prototype,"stopProp",[action])}close(){this.args.disableClose||this.args.onClose&&this.args.onClose()}static{decorateMethodV2(this.prototype,"close",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[24,0,"modal-overlay"],[24,"role","dialog"],[24,"tabindex","-1"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[11,0],[24,0,"modal-content"],[24,"role","document"],[24,"tabindex","0"],[4,[32,0],["click",[30,0,["stopProp"]]],null],[12],[1,"\\n "],[11,"button"],[16,0,[29,["close-modal-btn btn-text ",[52,[30,1],"disabled"]]]],[16,"disabled",[30,1]],[24,4,"button"],[4,[32,0],["click",[30,0,["close"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",24,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[18,2,null],[1,"\\n "],[13],[1,"\\n"],[13]],["@disableClose","&default"],["if","yield"]]',moduleName:"/home/basti/src/marco/app/components/modal.gjs",scope:()=>[on,IconComponent],isStrictMode:!0}),this)}}const fadeInImage=modifier((e,[t])=>{if(!t)return;let r;e.classList.remove("loaded"),e.classList.remove("loaded-instant");const n=()=>{const t=e.parentElement,r=t&&"PICTURE"===t.tagName?t.parentElement:t;if(r&&r.closest(".photo-carousel.gallery-main")){const e=r.querySelector(".place-header-photo-blur");e&&(e.style.opacity="0")}},i=()=>{e.classList.contains("loaded-instant")||e.classList.add("loaded"),n()};return e.addEventListener("load",i),r=new IntersectionObserver((r,i)=>{r.forEach(r=>{if(r.isIntersecting){i.unobserve(e);const r=new Image;r.src=t,r.complete&&(e.classList.add("loaded-instant"),n());const o=e.parentElement;o&&"PICTURE"===o.tagName&&o.querySelectorAll("source").forEach(e=>{e.dataset.srcset&&(e.srcset=e.dataset.srcset)}),e.dataset.src?e.src=e.dataset.src:e.src=t}})},{root:null,rootMargin:"100px 100%",threshold:0}),r.observe(e),()=>{e.removeEventListener("load",i),r&&r.disconnect()}});class PhotoCarousel extends GlimmerComponent{static{decorateFieldV2(this.prototype,"canScrollLeft",[tracked],function(){return!1})}#Be=void initializeDeferredDecorator(this,"canScrollLeft");static{decorateFieldV2(this.prototype,"canScrollRight",[tracked],function(){return!1})}#Ue=void initializeDeferredDecorator(this,"canScrollRight");internalEventId=null;carouselElement=null;get photos(){return this.args.photos||[]}get showChevrons(){return this.photos.length>1}get cannotScrollLeft(){return!this.canScrollLeft}get cannotScrollRight(){return!this.canScrollRight}get variantClass(){return this.args.variant||"inline"}lastResetKey=null;resetScrollPosition=modifier((e,[t])=>{void 0!==t&&t!==this.lastResetKey&&(this.lastResetKey=t,e.scrollLeft=0,setTimeout(()=>this.updateScrollState(),50))});scrollToNewPhoto=modifier((e,[t])=>{if(t&&t!==this.lastEventId){const r=!this.lastEventId;if(this.lastEventId=t,this.internalEventId===t)return;const n=()=>{const n=e.querySelector(`[data-event-id="${t}"]`);if(n)if(r){const t=e.style.scrollBehavior;e.style.scrollBehavior="auto",e.scrollLeft=n.offsetLeft,setTimeout(()=>{e.style.scrollBehavior=t},50)}else e.scrollLeft=n.offsetLeft};r?n():setTimeout(n,100)}});setupCarousel=modifier(e=>{let t,r;return this.carouselElement=e,setTimeout(()=>{this.updateScrollState()},50),window.ResizeObserver&&(t=new ResizeObserver(()=>this.updateScrollState()),t.observe(e)),this.args.onVisiblePhotoChange&&window.IntersectionObserver&&(r=new IntersectionObserver(e=>{for(let t of e)if(t.isIntersecting&&t.intersectionRatio>=.5){const e=t.target.dataset.eventId;this.internalEventId=e;const r=this.photos.find(t=>t.eventId===e);r&&this.args.onVisiblePhotoChange(r)}},{root:e,threshold:.5}),e.querySelectorAll(".carousel-slide").forEach(e=>r.observe(e))),()=>{t&&t.unobserve(e),r&&r.disconnect()}});updateScrollState(){if(!this.carouselElement)return;const{scrollLeft:e,scrollWidth:t,clientWidth:r}=this.carouselElement;this.canScrollLeft=e>1,this.canScrollRight=e+r[on,AndHelper,eq$1,fn,Blurhash,fadeInImage,IconComponent],isStrictMode:!0}),this)}}class PhotoGallery extends GlimmerComponent{static{decorateFieldV2(this.prototype,"currentPhoto",[tracked],function(){return this.args.selectedPhoto||this.args.photos?.[0]})}#ze=void initializeDeferredDecorator(this,"currentPhoto");handleClose(){this.args.onClose&&this.args.onClose()}static{decorateMethodV2(this.prototype,"handleClose",[action])}handleBackgroundClick(e){e.target.closest(".thumbnail-strip-container")||e.target.closest(".carousel-nav-btn")||e.target.closest(".close-btn")||this.handleClose()}static{decorateMethodV2(this.prototype,"handleBackgroundClick",[action])}selectPhoto(e){this.currentPhoto=e}static{decorateMethodV2(this.prototype,"selectPhoto",[action])}handleVisiblePhotoChange(e){this.currentPhoto!==e&&(this.currentPhoto=e)}static{decorateMethodV2(this.prototype,"handleVisiblePhotoChange",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[24,0,"photo-gallery-overlay"],[24,"role","dialog"],[24,"tabindex","-1"],[4,[32,0],["click",[30,0,["handleBackgroundClick"]]],null],[12],[1,"\\n"],[1," "],[10,0],[14,0,"photo-gallery-content"],[12],[1,"\\n "],[11,"button"],[24,0,"close-btn btn-text"],[24,"aria-label","Close gallery"],[24,"title","Close"],[24,4,"button"],[4,[32,0],["click",[30,0,["handleClose"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",24,"white"]],null],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"main-photo-container"],[12],[1,"\\n "],[8,[32,2],null,[["@variant","@photos","@scrollToEventId","@onVisiblePhotoChange","@name"],["gallery-main",[30,1],[30,0,["currentPhoto","eventId"]],[30,0,["handleVisiblePhotoChange"]],[30,2]]],null],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"thumbnail-strip-container"],[12],[1,"\\n "],[8,[32,2],null,[["@variant","@photos","@scrollToEventId","@onPhotoClick","@name"],["gallery-thumbnails",[30,1],[30,0,["currentPhoto","eventId"]],[30,0,["selectPhoto"]],[30,2]]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@photos","@placeName"],[]]',moduleName:"/home/basti/src/marco/app/components/photo-gallery.gjs",scope:()=>[on,IconComponent,PhotoCarousel],isStrictMode:!0}),this)}}class PlaceDetails extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"isEditing",[tracked],function(){return!1})}#je=void initializeDeferredDecorator(this,"isEditing");static{decorateFieldV2(this.prototype,"showLists",[tracked],function(){return!1})}#Ve=void initializeDeferredDecorator(this,"showLists");static{decorateFieldV2(this.prototype,"isPhotoUploadActive",[tracked],function(){return!1})}#Ge=void initializeDeferredDecorator(this,"isPhotoUploadActive");static{decorateFieldV2(this.prototype,"isConnectingNostr",[tracked],function(){return!1})}#He=void initializeDeferredDecorator(this,"isConnectingNostr");static{decorateFieldV2(this.prototype,"isGalleryOpen",[tracked],function(){return!1})}#qe=void initializeDeferredDecorator(this,"isGalleryOpen");static{decorateFieldV2(this.prototype,"selectedGalleryPhoto",[tracked],function(){return null})}#We=void initializeDeferredDecorator(this,"selectedGalleryPhoto");static{decorateFieldV2(this.prototype,"isPhotoUploadModalOpen",[tracked],function(){return!1})}#Ke=void initializeDeferredDecorator(this,"isPhotoUploadModalOpen");static{decorateFieldV2(this.prototype,"isNostrConnectModalOpen",[tracked],function(){return!1})}#Ye=void initializeDeferredDecorator(this,"isNostrConnectModalOpen");static{decorateFieldV2(this.prototype,"newlyUploadedPhotoId",[tracked],function(){return null})}#Ze=void initializeDeferredDecorator(this,"newlyUploadedPhotoId");handleUploadStateChange(e){this.isPhotoUploadActive=e}static{decorateMethodV2(this.prototype,"handleUploadStateChange",[action])}openPhotoUploadModal(e){e&&e.preventDefault(),this.nostrAuth.isConnected?this.isPhotoUploadModalOpen=!0:this.isNostrConnectModalOpen=!0}static{decorateMethodV2(this.prototype,"openPhotoUploadModal",[action])}closePhotoUploadModal(e){this.isPhotoUploadActive||(this.isPhotoUploadModalOpen=!1,"string"==typeof e&&(this.newlyUploadedPhotoId=e,setTimeout(()=>{const e=document.querySelector(".sidebar-content");e&&(e.scrollTop=0)},50)))}static{decorateMethodV2(this.prototype,"closePhotoUploadModal",[action])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{decorateMethodV2(this.prototype,"closeNostrConnectModal",[action])}onNostrConnected(){this.isNostrConnectModalOpen=!1,this.isPhotoUploadModalOpen=!0}static{decorateMethodV2(this.prototype,"onNostrConnected",[action])}get isSaved(){return this.storage.isPlaceSaved(this.place.id||this.place.osmId)}get place(){return this.args.place||{}}get saveablePlace(){return this.place.createdAt?this.place:mapToStorageSchema(this.place)}get tags(){return this.place.osmTags||{}}get name(){return this.place.title||getLocalizedName(this.tags)||"Unnamed Place"}get photos(){return parsePlacePhotos(this.nostrData.placePhotos).map(e=>({...e,style:htmlSafe(`--slide-ratio: ${e.aspectRatio};`)}))}startEditing(){this.isSaved&&(this.isEditing=!0)}static{decorateMethodV2(this.prototype,"startEditing",[action])}cancelEditing(){this.isEditing=!1}static{decorateMethodV2(this.prototype,"cancelEditing",[action])}toggleLists(e){e&&e.stopPropagation(),this.showLists=!this.showLists}static{decorateMethodV2(this.prototype,"toggleLists",[action])}closeLists(){this.showLists=!1}static{decorateMethodV2(this.prototype,"closeLists",[action])}async saveChanges(e){this.args.onSave&&await this.args.onSave({...this.place,...e}),this.isEditing=!1}static{decorateMethodV2(this.prototype,"saveChanges",[action])}get type(){return getPlaceType(this.tags)}get address(){const e=this.tags,t=[],r=(...t)=>{for(const r of t)if(e[r])return e[r];return null};let n=r("addr:street","street");const i=r("addr:housenumber","housenumber");n&&(i&&(n=`${n} ${i}`),t.push(n));let o=r("addr:city","city");const s=r("addr:postcode","postcode");o&&(s&&(o=`${s} ${o}`),t.push(o));const a=r("addr:state","state"),l=r("addr:country","country");return a&&a!==o&&t.push(a),l&&t.push(l),0===t.length?null:t.join(", ")}formatMultiLine(e,t){if(!e)return null;const r=[...new Set(e.split(";").map(e=>e.trim()).filter(Boolean))];return 0===r.length?null:htmlSafe("phone"===t?r.map(e=>`${e}`).join("
"):"email"===t?r.map(e=>`${e}`).join("
"):"whatsapp"===t?r.map(e=>`${e}`).join("
"):"url"===t?r.map(e=>`${this.getDomain(e)}`).join("
"):r.join("
"))}get phone(){const e=[this.tags.phone,this.tags["contact:phone"],this.tags.mobile,this.tags["contact:mobile"]].filter(Boolean);return 0===e.length?null:this.formatMultiLine(e.join(";"),"phone")}get whatsapp(){const e=[this.tags.whatsapp,this.tags["contact:whatsapp"]].filter(Boolean);return 0===e.length?null:this.formatMultiLine(e.join(";"),"whatsapp")}get email(){const e=this.tags.email||this.tags["contact:email"];return this.formatMultiLine(e,"email")}get website(){const e=this.place.url||this.tags.website||this.tags["contact:website"];return this.formatMultiLine(e,"url")}getDomain(e){try{return new URL(e).hostname}catch{return e}}get openingHours(){const e=this.tags.opening_hours;return this.formatMultiLine(e)}get cuisine(){return this.tags.cuisine?this.tags.cuisine.split(";").map(e=>humanizeOsmTag$1(e)).join(", "):null}get facebook(){return getSocialInfo(this.tags,"facebook")}get instagram(){return getSocialInfo(this.tags,"instagram")}get wikipedia(){const e=this.tags.wikipedia;return e?e.split(";").map(e=>e.trim()).filter(Boolean)[0]:null}get geoLink(){const e=this.place.lat,t=this.place.lon;return e&&t?`geo:${e},${t}?q=${e},${t}(${encodeURIComponent(this.name)})`:"#"}get visibleGeoLink(){const e=this.place.lat,t=this.place.lon;return e&&t?`${Number(e).toFixed(6)}, ${Number(t).toFixed(6)}`:""}get osmUrl(){const e=this.place.osmId;return e?`https://www.openstreetmap.org/${this.place.osmType||"node"}/${e}`:null}get gmapsUrl(){return this.place.gmapsId||this.place.osmId?`https://www.google.com/maps/search/?api=1&query=${this.name}&query=${this.place.lat},${this.place.lon}`:null}get showDescription(){return"photon"!==this.place.source&&!!this.place.description}openGallery(e){this.selectedGalleryPhoto=e,this.isGalleryOpen=!0}static{decorateMethodV2(this.prototype,"openGallery",[action])}closeGallery(){this.isGalleryOpen=!1,this.selectedGalleryPhoto=null}static{decorateMethodV2(this.prototype,"closeGallery",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"place-details"],[12],[1,"\\n"],[41,[30,0,["isEditing"]],[[[1," "],[8,[32,0],null,[["@place","@onSave","@onCancel"],[[30,0,["place"]],[30,0,["saveChanges"]],[30,0,["cancelEditing"]]]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@variant","@photos","@name","@resetKey","@scrollToEventId","@onPhotoClick"],["inline",[30,0,["photos"]],[30,0,["name"]],[30,0,["place","osmId"]],[30,0,["newlyUploadedPhotoId"]],[30,0,["openGallery"]]]],null],[1,"\\n "],[10,"h3"],[12],[1,[30,0,["name"]]],[13],[1,"\\n "],[10,2],[14,0,"place-type"],[12],[1,"\\n "],[1,[30,0,["type"]]],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["showDescription"]],[[[1," "],[10,2],[14,0,"place-description"],[12],[1,"\\n "],[1,[30,0,["place","description"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[]]],[1,"\\n "],[10,0],[14,0,"actions"],[12],[1,"\\n "],[10,0],[14,0,"save-button-wrapper"],[12],[1,"\\n "],[11,"button"],[16,0,[52,[30,0,["isSaved"]],"btn btn-secondary","btn btn-outline"]],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleLists"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["bookmark",[52,[30,0,["isSaved"]],"currentColor","var(--link-color)"]]],null],[1,"\\n "],[1,[52,[30,0,["isSaved"]],"Saved","Save"]],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["showLists"]],[[[1," "],[8,[32,4],null,[["@place","@onClose","@isSaved"],[[30,0,["saveablePlace"]],[30,0,["closeLists"]],[30,0,["isSaved"]]]],null],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isSaved"]],[[[1," "],[11,"button"],[24,0,"btn btn-outline"],[24,"title","Edit"],[16,"disabled",[30,0,["isEditing"]]],[24,4,"button"],[4,[32,2],["click",[30,0,["startEditing"]]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@color"],["edit","var(--link-color)"]],null],[1,"\\n Edit\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["cuisine"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["fork-and-knife","Cuisine"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["cuisine"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["openingHours"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["clock","Opening hours"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["openingHours"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["phone"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["phone","Phone"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["phone"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["whatsapp"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["whatsapp","WhatsApp"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["whatsapp"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["website"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["globe","Website"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["website"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["email"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["mail","Email"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[1,[30,0,["email"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["facebook"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["facebook","Facebook"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["facebook","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["facebook","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["instagram"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["instagram","Instagram"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["instagram","url"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["instagram","username"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["wikipedia"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["wikipedia","Wikipedia"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[29,["https://wikipedia.org/wiki/",[30,0,["wikipedia"]]]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Wikipedia\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"meta-info"],[12],[1,"\\n\\n"],[41,[30,0,["address"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["home","Address"]],null],[1,"\\n "],[10,1],[12],[1,[30,0,["address"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name","@title"],["map-pin","Geo link"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["geoLink"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n "],[1,[30,0,["visibleGeoLink"]]],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["osmUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n OpenStreetMap\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["gmapsUrl"]],[[[1," "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["map"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[10,3],[15,6,[30,0,["gmapsUrl"]]],[14,"target","_blank"],[14,"rel","noopener noreferrer"],[12],[1,"\\n Google Maps\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["osmUrl"]],[[[1," "],[10,0],[14,0,"meta-info"],[12],[1,"\\n "],[10,2],[14,0,"content-with-icon"],[12],[1,"\\n "],[8,[32,3],null,[["@name"],["feather-camera"]],null],[1,"\\n "],[10,1],[12],[1,"\\n "],[11,"button"],[24,0,"btn-link"],[24,4,"button"],[4,[32,2],["click",[30,0,["openPhotoUploadModal"]]],null],[12],[1,"\\n Add a photo\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13],[1,"\\n\\n"],[41,[30,0,["isPhotoUploadModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose","@disableClose"],[[30,0,["closePhotoUploadModal"]],[30,0,["isPhotoUploadActive"]]]],[["default"],[[[[1,"\\n "],[8,[32,6],null,[["@place","@onClose","@onUploadStateChange"],[[30,0,["saveablePlace"]],[30,0,["closePhotoUploadModal"]],[30,0,["handleUploadStateChange"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,7],null,[["@onConnect"],[[30,0,["onNostrConnected"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null],[1,"\\n"],[41,[30,0,["isGalleryOpen"]],[[[1," "],[8,[32,8],null,[["@photos","@selectedPhoto","@placeName","@onClose"],[[30,0,["photos"]],[30,0,["selectedGalleryPhoto"]],[30,0,["name"]],[30,0,["closeGallery"]]]],null],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/place-details.gjs",scope:()=>[PlaceEditForm,PhotoCarousel,on,IconComponent,PlaceListsManager,Modal,PlacePhotoUpload,NostrConnectComponent,PhotoGallery],isStrictMode:!0}),this)}}const humanizeOsmTag=helper$1(function([e]){return humanizeOsmTag$1(e)});class PlacesSidebar extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");createNewPlace(){const e=this.router.currentRoute.queryParams,t=e.lat,r=e.lon;t&&r?this.router.transitionTo("place.new",{queryParams:{lat:t,lon:r}}):this.router.transitionTo("place.new",{queryParams:{lat:0,lon:0}})}static{decorateMethodV2(this.prototype,"createNewPlace",[action])}selectPlace(e){this.args.onSelect&&this.args.onSelect(e)}static{decorateMethodV2(this.prototype,"selectPlace",[action])}clearSelection(){this.args.onSelect&&this.args.onSelect(null)}static{decorateMethodV2(this.prototype,"clearSelection",[action])}async toggleSave(e){if(e)if(e.createdAt)try{if(await this.storage.removePlace(e),console.debug("Place deleted:",e.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate){const t={...e,id:void 0,geohash:void 0,createdAt:void 0};this.args.onUpdate(t)}this.args.onSelect&&this.args.onSelect(null),this.args.onClose&&this.args.onClose()}catch(t){console.error("Failed to delete:",t),alert("Failed to delete: "+t.message)}else{const t={title:getLocalizedName(e.osmTags,"Untitled Place"),lat:e.lat,lon:e.lon,tags:[],url:e.osmTags.website,osmId:String(e.osmId||e.id),osmType:e.osmType,osmTags:e.osmTags};try{const e=await this.storage.storePlace(t);console.debug("Place saved:",t.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(e),this.args.onSelect&&this.args.onSelect(e)}catch(error){console.error("Failed to save place:",error),alert("Failed to save place: "+error.message)}}}static{decorateMethodV2(this.prototype,"toggleSave",[action])}async updateBookmark(e){try{const t=await this.storage.updatePlace(e);console.debug("Place updated:",t.title),this.args.onBookmarkChange&&this.args.onBookmarkChange(),this.args.onUpdate&&this.args.onUpdate(t)}catch(t){console.error("Failed to update place:",t),alert("Failed to update place: "+t.message)}}static{decorateMethodV2(this.prototype,"updateBookmark",[action])}get isNearbySearch(){const e=this.router.currentRoute.queryParams;return!e.q&&!e.category&&e.lat&&e.lon}get hasHeaderPhoto(){return this.args.selectedPlace&&this.nostrData.placePhotos&&this.nostrData.placePhotos.length>0}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[15,0,[29,["sidebar-header ",[52,[30,0,["hasHeaderPhoto"]],"no-border"]]]],[12],[1,"\\n"],[41,[30,1],[[[1," "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,0,["clearSelection"]]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["target",20,"#ea4335"]],null],[1,"\\n Nearby"],[13],[1,"\\n"]],[]],[[[1," "],[10,"h2"],[12],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#333"]],null],[1," Results"],[13],[1,"\\n"]],[]]]],[]]],[1," "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n"],[41,[30,1],[[[1," "],[8,[32,2],null,[["@place","@onToggleSave","@onSave"],[[30,1],[30,0,["toggleSave"]],[30,0,["updateBookmark"]]]],null],[1,"\\n"]],[]],[[[41,[30,3],[[[1," "],[10,"ul"],[14,0,"places-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,3]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"place-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,3],[[30,0,["selectPlace"]],[30,4]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"place-name"],[12],[1,[28,[32,4],[[30,4,["title"]],[30,4,["osmTags","name"]],[30,4,["osmTags","name:en"]],"Unnamed Place"],null]],[13],[1,"\\n "],[10,0],[14,0,"place-type"],[12],[1,"\\n"],[41,[28,[32,5],[[30,4,["source"]],"osm"],null],[[[1," "],[1,[28,[32,6],[[30,4,["type"]]],null]],[1,"\\n"]],[]],[[[41,[28,[32,5],[[30,4,["source"]],"photon"],null],[[[1," "],[1,[30,4,["description"]]],[1,"\\n"]],[]],[[[41,[30,4,["osmTags"]],[[[1," "],[1,[28,[32,6],[[28,[32,7],[[30,4,["osmTags"]]],null]],null]],[1,"\\n"]],[]],[[[41,[30,4,["description"]],[[[1," "],[1,[30,4,["description"]]],[1,"\\n "]],[]],null]],[]]],[1," "]],[]]]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[4]],null],[1," "],[13],[1,"\\n"]],[]],[[[41,[30,0,["isNearbySearch"]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No places found nearby."],[13],[1,"\\n"]],[]],[[[1," "],[10,2],[14,0,"empty-state"],[12],[1,"No results found."],[13],[1,"\\n"]],[]]]],[]]],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline create-place"],[24,4,"button"],[4,[32,0],["click",[30,0,["createNewPlace"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["plus",18,"var(--link-color)"]],null],[1,"\\n Create new place\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n"],[13]],["@selectedPlace","@onClose","@places","place"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/places-sidebar.gjs",scope:()=>[on,IconComponent,PlaceDetails,fn,OrHelper,eq$1,humanizeOsmTag,getPlaceType],isStrictMode:!0}),this)}}class SearchTemplate extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");selectPlace(e){e&&(this.mapUi.returnToSearch=!0,this.mapUi.showSidebar(),this.mapUi.preventNextZoom=!0,this.router.transitionTo("place",e))}static{decorateMethodV2(this.prototype,"selectPlace",[action])}close(){this.mapUi.hideSidebar()}static{decorateMethodV2(this.prototype,"close",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["mapUi","isSidebarVisible"]],[[[1," "],[8,[32,0],null,[["@places","@onSelect","@onClose"],[[30,0,["mapUi","searchResults"]],[30,0,["selectPlace"]],[30,0,["close"]]]],null],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/templates/search.gjs",scope:()=>[PlacesSidebar],isStrictMode:!0}),this)}}const amdModule29=Object.freeze(Object.defineProperty({__proto__:null,default:SearchTemplate},Symbol.toStringTag,{value:"Module"}));class SearchController extends Controller{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"photon",[service])}#Je=void initializeDeferredDecorator(this,"photon");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");queryParams=["lat","lon","q","selected","category"];lat=null;lon=null;q=null;selected=null;category=null;fetchResultsTask=buildTask(()=>({context:this,generator:function*(e){this.mapUi.hideSidebar(),this.mapUi.clearSearchResults();const t=e.lat?parseFloat(e.lat):null,r=e.lon?parseFloat(e.lon):null;let n=[],i=null,o=null;try{if(e.category&&t&&r){i="category",o=e.category,this.mapUi.startLoading(i,o);let s=this.mapUi.currentBounds;if(!s){const e=.01;s={minLat:t-e,maxLat:t+e,minLon:r-e,maxLon:r+e}}n=yield this.osm.getCategoryPois(s,e.category,t,r),n=n.map(e=>({...e,_distance:getDistance$1(t,r,e.lat,e.lon)})).sort((e,t)=>e._distance-t._distance)}else if(e.q){i="text",o=e.q,this.mapUi.startLoading(i,o),n=yield this.photon.search(e.q,t,r);const s=e.q.toLowerCase(),a=this.storage.savedPlaces.filter(e=>e.title?.toLowerCase().includes(s)||e.description?.toLowerCase().includes(s));a.forEach(e=>{n.find(t=>e.osmId&&t.osmId===e.osmId||t.id&&t.id===e.id)||n.push(e)})}else if(t&&r){const e=50;n=yield this.osm.getNearbyPois(t,r,e);const i=this.storage.savedPlaces.filter(n=>getDistance$1(t,r,n.lat,n.lon)<=e);i.forEach(e=>{n.find(t=>e.osmId&&t.osmId===e.osmId||t.id&&t.id===e.id)||n.push(e)}),n=n.map(e=>({...e,_distance:getDistance$1(t,r,e.lat,e.lon)})).sort((e,t)=>e._distance-t._distance)}}catch(error){return console.error("Search request failed.",error),this.toast.show("Search request failed. Please try again."),void this.mapUi.stopSearch()}finally{i&&o&&this.mapUi.stopLoading(i,o)}n=n.map(e=>this.storage.findPlaceById(e.osmId)||e);const s=e.selected||e.q;if(s&&n.length>0){let e=null;if(e=n.find(e=>e.osmTags&&(e.osmTags.name===s||e.osmTags["name:en"]===s)),!e){const t=n[0];t._distance<=10&&(e=t)}if(e)return this.router.replaceWith("place",e),void this.mapUi.stopSearch()}this.mapUi.setSearchResults(n),this.mapUi.showSidebar(),this.mapUi.stopSearch()}}),{restartable:!0},"fetchResultsTask")}const amdModule30=Object.freeze(Object.defineProperty({__proto__:null,default:SearchController},Symbol.toStringTag,{value:"Module"}));class SearchRoute extends Route{static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0},q:{refreshModel:!0},selected:{refreshModel:!0},category:{refreshModel:!0}};model(e){return e}setupController(e,t){super.setupController(e,t),e.fetchResultsTask.perform(t);const{q:r,category:n,lat:i,lon:o}=this.paramsFor("search");this.mapUi.currentSearch={q:r,category:n,lat:i,lon:o}}resetController(e,t){t&&(e.fetchResultsTask.cancelAll(),this.mapUi.stopSearch())}error(e,t){return this.mapUi.stopSearch(),this.toast.show("Search request failed. Please try again."),t&&t.abort(),!1}static{decorateMethodV2(this.prototype,"error",[action])}}const amdModule31=Object.freeze(Object.defineProperty({__proto__:null,default:SearchRoute},Symbol.toStringTag,{value:"Module"}));var _dec,_class,_descriptor;let PageTitle=(_dec=service("page-title"),_class=class extends Helper{constructor(e){super(e),_initializerDefineProperty(this,"tokens",_descriptor,this),_defineProperty(this,"tokenId",guidFor(this)),this.tokens.push({id:this.tokenId})}compute(e,t){const r={...t,id:this.tokenId,title:e.join("")};return this.tokens.push(r),this.tokens.scheduleTitleUpdate(),""}willDestroy(){super.willDestroy(),this.tokens.remove(this.tokenId),this.tokens.scheduleTitleUpdate()}},_descriptor=_applyDecoratedDescriptor(_class.prototype,"tokens",[_dec],{configurable:!0,enumerable:!0,writable:!0,initializer:null}),_class);const CollectionEventType={ADD:"add",REMOVE:"remove"},ObjectEventType={PROPERTYCHANGE:"propertychange"},EventType$1={CHANGE:"change",ERROR:"error",CONTEXTMENU:"contextmenu",CLICK:"click",DBLCLICK:"dblclick",KEYDOWN:"keydown",KEYPRESS:"keypress",LOAD:"load",TOUCHMOVE:"touchmove",WHEEL:"wheel"};class Disposable{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}}function binarySearch$1(e,t,r){let n,i;r=r||ascending;let o=0,s=e.length,a=!1;for(;o>1),i=+r(e[n],t),i<0?o=n+1:(s=n,a=!i);return a?o:~o}function ascending(e,t){return e>t?1:et?-1:0}function linearFindNearest(e,t,r){if(e[0]<=t)return 0;const n=e.length;if(t<=e[n-1])return n-1;if("function"==typeof r){for(let i=1;i0?i-1:i}return n-1}if(r>0){for(let r=1;r0||0===i)})}function TRUE(){return!0}function FALSE(){return!1}function VOID(){}function memoizeOne(e){let t,r,n;return function(){const i=Array.prototype.slice.call(arguments);return r&&this===n&&equals$2(i,r)||(n=this,r=i,t=e.apply(this,arguments)),t}}function toPromise(e){return function(){let t;try{t=e()}catch(r){return Promise.reject(r)}return t instanceof Promise?t:Promise.resolve(t)}()}function clear(e){for(const t in e)delete e[t]}function isEmpty$1(e){let t;for(t in e)return!1;return!t}class BaseEvent{constructor(e){this.propagationStopped,this.defaultPrevented,this.type=e,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}}class Target extends Disposable{constructor(e){super(),this.eventTarget_=e,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null}addEventListener(e,t){if(!e||!t)return;const r=this.listeners_||(this.listeners_={}),n=r[e]||(r[e]=[]);n.includes(t)||n.push(t)}dispatchEvent(e){const t="string"==typeof e,r=t?e:e.type,n=this.listeners_&&this.listeners_[r];if(!n)return;const i=t?new BaseEvent(e):e;i.target||(i.target=this.eventTarget_||this);const o=this.dispatching_||(this.dispatching_={}),s=this.pendingRemovals_||(this.pendingRemovals_={});let a;r in o||(o[r]=0,s[r]=0),++o[r];for(let l=0,c=n.length;l0)}removeEventListener(e,t){if(!this.listeners_)return;const r=this.listeners_[e];if(!r)return;const n=r.indexOf(t);-1!==n&&(this.pendingRemovals_&&e in this.pendingRemovals_?(r[n]=VOID,++this.pendingRemovals_[e]):(r.splice(n,1),0===r.length&&delete this.listeners_[e]))}}function listen(e,t,r,n,i){if(i){const i=r;r=function(o){return e.removeEventListener(t,r),i.call(n??this,o)}}else n&&n!==e&&(r=r.bind(n));const o={target:e,type:t,listener:r};return e.addEventListener(t,r),o}function listenOnce(e,t,r,n){return listen(e,t,r,n,!0)}function unlistenByKey(e){e&&e.target&&(e.target.removeEventListener(e.type,e.listener),clear(e))}class Observable extends Target{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent(EventType$1.CHANGE)}getRevision(){return this.revision_}onInternal(e,t){if(Array.isArray(e)){const r=e.length,n=new Array(r);for(let i=0;i0;)this.pop()}extend(e){for(let t=0,r=e.length;tthis.getLength())throw new Error("Index out of bounds: "+e);this.unique_&&this.assertUnique_(t),this.array_.splice(e,0,t),this.updateLength_(),this.dispatchEvent(new CollectionEvent(CollectionEventType.ADD,t,e))}pop(){return this.removeAt(this.getLength()-1)}push(e){const t=this.getLength();return this.insertAt(t,e),this.getLength()}remove(e){const t=this.array_;for(let r=0,n=t.length;r=this.getLength())return;const t=this.array_[e];return this.array_.splice(e,1),this.updateLength_(),this.dispatchEvent(new CollectionEvent(CollectionEventType.REMOVE,t,e)),t}setAt(e,t){if(e>=this.getLength())return void this.insertAt(e,t);if(e<0)throw new Error("Index out of bounds: "+e);this.unique_&&this.assertUnique_(t,e);const r=this.array_[e];this.array_[e]=t,this.dispatchEvent(new CollectionEvent(CollectionEventType.REMOVE,r,e)),this.dispatchEvent(new CollectionEvent(CollectionEventType.ADD,t,e))}updateLength_(){this.set(Property$4.LENGTH,this.array_.length)}assertUnique_(e,t){const r=this.array_;for(let n=0,i=r.length;n{this.clickTimeoutId_=void 0;const t=new MapBrowserEvent(MapBrowserEventType.SINGLECLICK,this.map_,e);this.dispatchEvent(t)},250)}updateActivePointers_(e){const t=e,r=t.pointerId;if(t.type==MapBrowserEventType.POINTERUP||t.type==MapBrowserEventType.POINTERCANCEL){delete this.trackedTouches_[r];for(const e in this.trackedTouches_)if(this.trackedTouches_[e].target!==t.target){delete this.trackedTouches_[e];break}}else t.type!=MapBrowserEventType.POINTERDOWN&&t.type!=MapBrowserEventType.POINTERMOVE||(this.trackedTouches_[r]=t);this.activePointers_=Object.values(this.trackedTouches_)}handlePointerUp_(e){this.updateActivePointers_(e);const t=new MapBrowserEvent(MapBrowserEventType.POINTERUP,this.map_,e,void 0,void 0,this.activePointers_);this.dispatchEvent(t),this.emulateClicks_&&!t.defaultPrevented&&!this.dragging_&&this.isMouseActionButton_(e)&&this.emulateClick_(this.down_),0===this.activePointers_.length&&(this.dragListenerKeys_.forEach(unlistenByKey),this.dragListenerKeys_.length=0,this.dragging_=!1,this.down_=null)}isMouseActionButton_(e){return 0===e.button}handlePointerDown_(e){this.emulateClicks_=0===this.activePointers_.length,this.updateActivePointers_(e);const t=new MapBrowserEvent(MapBrowserEventType.POINTERDOWN,this.map_,e,void 0,void 0,this.activePointers_);if(this.dispatchEvent(t),this.down_=new PointerEvent(e.type,e),Object.defineProperty(this.down_,"target",{writable:!1,value:e.target}),0===this.dragListenerKeys_.length){const e=this.map_.getOwnerDocument();this.dragListenerKeys_.push(listen(e,MapBrowserEventType.POINTERMOVE,this.handlePointerMove_,this),listen(e,MapBrowserEventType.POINTERUP,this.handlePointerUp_,this),listen(this.element_,MapBrowserEventType.POINTERCANCEL,this.handlePointerUp_,this)),this.element_.getRootNode&&this.element_.getRootNode()!==e&&this.dragListenerKeys_.push(listen(this.element_.getRootNode(),MapBrowserEventType.POINTERUP,this.handlePointerUp_,this))}}handlePointerMove_(e){if(this.isMoving_(e)){this.updateActivePointers_(e),this.dragging_=!0;const t=new MapBrowserEvent(MapBrowserEventType.POINTERDRAG,this.map_,e,this.dragging_,void 0,this.activePointers_);this.dispatchEvent(t)}}relayMoveEvent_(e){this.originalPointerMoveEvent_=e;const t=!(!this.down_||!this.isMoving_(e));this.dispatchEvent(new MapBrowserEvent(MapBrowserEventType.POINTERMOVE,this.map_,e,t))}handleTouchMove_(e){const t=this.originalPointerMoveEvent_;t&&!t.defaultPrevented||"boolean"==typeof e.cancelable&&!0!==e.cancelable||e.preventDefault()}isMoving_(e){return this.dragging_||Math.abs(e.clientX-this.down_.clientX)>this.moveTolerance_||Math.abs(e.clientY-this.down_.clientY)>this.moveTolerance_}disposeInternal(){this.relayedListenerKey_&&(unlistenByKey(this.relayedListenerKey_),this.relayedListenerKey_=null),this.element_.removeEventListener(EventType$1.TOUCHMOVE,this.boundHandleTouchMove_),this.pointerdownListenerKey_&&(unlistenByKey(this.pointerdownListenerKey_),this.pointerdownListenerKey_=null),this.dragListenerKeys_.forEach(unlistenByKey),this.dragListenerKeys_.length=0,this.element_=null,super.disposeInternal()}}const MapEventType={POSTRENDER:"postrender",MOVESTART:"movestart",MOVEEND:"moveend",LOADSTART:"loadstart",LOADEND:"loadend"},MapProperty={LAYERGROUP:"layergroup",SIZE:"size",TARGET:"target",VIEW:"view"},TileState={IDLE:0,LOADING:1,LOADED:2,ERROR:3,EMPTY:4};function assert$1(e,t){if(!e)throw new Error(t)}const DROP=1/0;class PriorityQueue{constructor(e,t){this.priorityFunction_=e,this.keyFunction_=t,this.elements_=[],this.priorities_=[],this.queuedElements_={}}clear(){this.elements_.length=0,this.priorities_.length=0,clear(this.queuedElements_)}dequeue(){const e=this.elements_,t=this.priorities_,r=e[0];1==e.length?(e.length=0,t.length=0):(e[0]=e.pop(),t[0]=t.pop(),this.siftUp_(0));const n=this.keyFunction_(r);return delete this.queuedElements_[n],r}enqueue(e){assert$1(!(this.keyFunction_(e)in this.queuedElements_),"Tried to enqueue an `element` that was already added to the queue");const t=this.priorityFunction_(e);return t!=DROP&&(this.elements_.push(e),this.priorities_.push(t),this.queuedElements_[this.keyFunction_(e)]=!0,this.siftDown_(0,this.elements_.length-1),!0)}getCount(){return this.elements_.length}getLeftChildIndex_(e){return 2*e+1}getRightChildIndex_(e){return 2*e+2}getParentIndex_(e){return e-1>>1}heapify_(){let e;for(e=(this.elements_.length>>1)-1;e>=0;e--)this.siftUp_(e)}isEmpty(){return 0===this.elements_.length}isKeyQueued(e){return e in this.queuedElements_}isQueued(e){return this.isKeyQueued(this.keyFunction_(e))}siftUp_(e){const t=this.elements_,r=this.priorities_,n=t.length,i=t[e],o=r[e],s=e;for(;e>1;){const i=this.getLeftChildIndex_(e),o=this.getRightChildIndex_(e),s=oe;){const e=this.getParentIndex_(t);if(!(n[e]>o))break;r[t]=r[e],n[t]=n[e],t=e}r[t]=i,n[t]=o}reprioritize(){const e=this.priorityFunction_,t=this.elements_,r=this.priorities_;let n=0;const i=t.length;let o,s,a;for(s=0;se.apply(null,t),e=>e[0].getKey()),this.boundHandleTileChange_=this.handleTileChange.bind(this),this.tileChangeCallback_=t,this.tilesLoading_=0,this.tilesLoadingKeys_={}}enqueue(e){const t=super.enqueue(e);return t&&e[0].addEventListener(EventType$1.CHANGE,this.boundHandleTileChange_),t}getTilesLoading(){return this.tilesLoading_}handleTileChange(e){const t=e.target,r=t.getState();if(r===TileState.LOADED||r===TileState.ERROR||r===TileState.EMPTY){r!==TileState.ERROR&&t.removeEventListener(EventType$1.CHANGE,this.boundHandleTileChange_);const e=t.getKey();e in this.tilesLoadingKeys_&&(delete this.tilesLoadingKeys_[e],--this.tilesLoading_),this.tileChangeCallback_()}}loadMoreTiles(e,t){let r=0;for(;this.tilesLoading_0;){const e=this.dequeue()[0],t=e.getKey();e.getState()!==TileState.IDLE||t in this.tilesLoadingKeys_||(this.tilesLoadingKeys_[t]=!0,++this.tilesLoading_,++r,e.load())}}}function getTilePriority(e,t,r,n,i){if(!e||!(r in e.wantedTiles))return DROP;if(!e.wantedTiles[r][t.getKey()])return DROP;const o=e.viewState.center,s=n[0]-o[0],a=n[1]-o[1];return 65536*Math.log(i)+Math.sqrt(s*s+a*a)/i}const ViewHint={ANIMATING:0,INTERACTING:1},ViewProperty={CENTER:"center",RESOLUTION:"resolution",ROTATION:"rotation"};function clamp$1(e,t,r){return Math.min(Math.max(e,t),r)}function squaredSegmentDistance(e,t,r,n,i,o){const s=i-r,a=o-n;if(0!==s||0!==a){const l=((e-r)*s+(t-n)*a)/(s*s+a*a);l>1?(r=i,n=o):l>0&&(r+=s*l,n+=a*l)}return squaredDistance$1(e,t,r,n)}function squaredDistance$1(e,t,r,n){const i=r-e,o=n-t;return i*i+o*o}function solveLinearSystem(e){const t=e.length;for(let n=0;ni&&(i=t,r=s)}if(0===i)return null;const o=e[r];e[r]=e[n],e[n]=o;for(let s=n+1;s=0;n--){r[n]=e[n][t]/e[n][n];for(let i=n-1;i>=0;i--)e[i][t]-=e[i][n]*r[n]}return r}function toDegrees(e){return 180*e/Math.PI}function toRadians(e){return e*Math.PI/180}function modulo(e,t){const r=e%t;return r*t<0?r+t:r}function lerp(e,t,r){return e+r*(t-e)}function toFixed(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function floor(e,t){return Math.floor(toFixed(e,t))}function ceil(e,t){return Math.ceil(toFixed(e,t))}function wrap(e,t,r){if(e>=t&&ep&&(d=(p+d)/2,p=d),f>g&&(f=(g+f)/2,g=f);let m=clamp$1(n[0],d,p),y=clamp$1(n[1],f,g);if(s&&r&&i){const e=30*i;m+=-e*Math.log(1+Math.max(0,d-n[0])/e)+e*Math.log(1+Math.max(0,n[0]-p)/e),y+=-e*Math.log(1+Math.max(0,f-n[1])/e)+e*Math.log(1+Math.max(0,n[1]-g)/e)}return[m,y]}}function none$1(e){return e}const Relationship={UNKNOWN:0,INTERSECTING:1,ABOVE:2,RIGHT:4,BELOW:8,LEFT:16};function boundingExtent(e){const t=createEmpty();for(let r=0,n=e.length;ri&&(l|=Relationship.RIGHT),ao&&(l|=Relationship.ABOVE),l===Relationship.UNKNOWN&&(l=Relationship.INTERSECTING),l}function createEmpty(){return[1/0,1/0,-1/0,-1/0]}function createOrUpdate$2(e,t,r,n,i){return i?(i[0]=e,i[1]=t,i[2]=r,i[3]=n,i):[e,t,r,n]}function createOrUpdateEmpty(e){return createOrUpdate$2(1/0,1/0,-1/0,-1/0,e)}function createOrUpdateFromCoordinate(e,t){const r=e[0],n=e[1];return createOrUpdate$2(r,n,r,n,t)}function createOrUpdateFromFlatCoordinates(e,t,r,n,i){return extendFlatCoordinates(createOrUpdateEmpty(i),e,t,r,n)}function equals$1(e,t){return e[0]==t[0]&&e[2]==t[2]&&e[1]==t[1]&&e[3]==t[3]}function extend$1(e,t){return t[0]e[2]&&(e[2]=t[2]),t[1]e[3]&&(e[3]=t[3]),e}function extendCoordinate(e,t){t[0]e[2]&&(e[2]=t[0]),t[1]e[3]&&(e[3]=t[1])}function extendFlatCoordinates(e,t,r,n,i){for(;rt[0]?n[0]=e[0]:n[0]=t[0],e[1]>t[1]?n[1]=e[1]:n[1]=t[1],e[2]=t[0]&&e[1]<=t[3]&&e[3]>=t[1]}function isEmpty(e){return e[2]=s&&g<=l),n||!(o&Relationship.RIGHT)||i&Relationship.RIGHT||(m=p-(d-l)*f,n=m>=a&&m<=c),n||!(o&Relationship.BELOW)||i&Relationship.BELOW||(g=d-(p-a)/f,n=g>=s&&g<=l),n||!(o&Relationship.LEFT)||i&Relationship.LEFT||(m=p-(d-s)*f,n=m>=a&&m<=c)}return n}function applyTransform(e,t,r,n){if(isEmpty(e))return createOrUpdateEmpty(r);let i=[];if(n>1){const t=e[2]-e[0],r=e[3]-e[1];for(let o=0;o=r[2])){const t=getWidth(r),i=Math.floor((n[0]-r[0])/t)*t;e[0]-=i,e[2]-=i}return e}function wrapAndSliceX(e,t,r){if(t.canWrapX()){const n=t.getExtent();if(!isFinite(e[0])||!isFinite(e[2]))return[[n[0],e[1],n[2],e[3]]];wrapX$2(e,t);const i=getWidth(n);if(getWidth(e)>i&&!r)return[[n[0],e[1],n[2],e[3]]];if(e[0]n[2])return[[e[0],e[1],n[2],e[3]],[n[0],e[1],e[2]-i,e[3]]]}return[e]}function add$2(e,t){return e[0]+=+t[0],e[1]+=+t[1],e}function equals(e,t){let r=!0;for(let n=e.length-1;n>=0;--n)if(e[n]!=t[n]){r=!1;break}return r}function rotate$1(e,t){const r=Math.cos(t),n=Math.sin(t),i=e[0]*r-e[1]*n,o=e[1]*r+e[0]*n;return e[0]=i,e[1]=o,e}function scale$3(e,t){return e[0]*=t,e[1]*=t,e}function squaredDistance(e,t){const r=e[0]-t[0],n=e[1]-t[1];return r*r+n*n}function distance(e,t){return Math.sqrt(squaredDistance(e,t))}function wrapX$1(e,t){if(t.canWrapX()){const r=getWidth(t.getExtent()),n=getWorldsAway(e,t,r);n&&(e[0]-=n*r)}return e}function getWorldsAway(e,t,r){const n=t.getExtent();let i=0;return t.canWrapX()&&(e[0]n[2])&&(r=r||getWidth(n),i=Math.floor((e[0]-n[0])/r)),i}function easeIn(e){return Math.pow(e,3)}function easeOut(e){return 1-easeIn(1-e)}function inAndOut(e){return 3*e*e-2*e*e*e}function linear(e){return e}const DEFAULT_RADIUS=6371008.8;function getDistance(e,t,r){r=r||DEFAULT_RADIUS;const n=toRadians(e[1]),i=toRadians(t[1]),o=(i-n)/2,s=toRadians(t[0]-e[0])/2,a=Math.sin(o)*Math.sin(o)+Math.sin(s)*Math.sin(s)*Math.cos(n)*Math.cos(i);return 2*r*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}function offset(e,t,r,n){n=n||DEFAULT_RADIUS;const i=toRadians(e[1]),o=toRadians(e[0]),s=t/n,a=Math.asin(Math.sin(i)*Math.cos(s)+Math.cos(i)*Math.sin(s)*Math.cos(r));return[toDegrees(o+Math.atan2(Math.sin(r)*Math.sin(s)*Math.cos(i),Math.cos(s)-Math.sin(i)*Math.sin(a))),toDegrees(a)]}function warn(...e){console.warn(...e)}const METERS_PER_UNIT$1={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};class Projection{constructor(e){this.code_=e.code,this.units_=e.units,this.extent_=void 0!==e.extent?e.extent:null,this.worldExtent_=void 0!==e.worldExtent?e.worldExtent:null,this.axisOrientation_=void 0!==e.axisOrientation?e.axisOrientation:"enu",this.global_=void 0!==e.global&&e.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=e.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=e.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||METERS_PER_UNIT$1[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(e){this.global_=e,this.canWrapX_=!(!e||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(e){this.defaultTileGrid_=e}setExtent(e){this.extent_=e,this.canWrapX_=!(!this.global_||!e)}setWorldExtent(e){this.worldExtent_=e}setGetPointResolution(e){this.getPointResolutionFunc_=e}getPointResolutionFunc(){return this.getPointResolutionFunc_}}const RADIUS$1=6378137,HALF_SIZE=Math.PI*RADIUS$1,EXTENT$2=[-HALF_SIZE,-HALF_SIZE,HALF_SIZE,HALF_SIZE],WORLD_EXTENT=[-180,-85,180,85],MAX_SAFE_Y=RADIUS$1*Math.log(Math.tan(Math.PI/2));class EPSG3857Projection extends Projection{constructor(e){super({code:e,units:"m",extent:EXTENT$2,global:!0,worldExtent:WORLD_EXTENT,getPointResolution:function(e,t){return e/Math.cosh(t[1]/RADIUS$1)}})}}const PROJECTIONS$1=[new EPSG3857Projection("EPSG:3857"),new EPSG3857Projection("EPSG:102100"),new EPSG3857Projection("EPSG:102113"),new EPSG3857Projection("EPSG:900913"),new EPSG3857Projection("http://www.opengis.net/def/crs/EPSG/0/3857"),new EPSG3857Projection("http://www.opengis.net/gml/srs/epsg.xml#3857")];function fromEPSG4326(e,t,r,n){const i=e.length;r=r>1?r:2,n=n??r,void 0===t&&(t=r>2?e.slice():new Array(i));for(let o=0;oMAX_SAFE_Y?r=MAX_SAFE_Y:r<-MAX_SAFE_Y&&(r=-MAX_SAFE_Y),t[o+1]=r}return t}function toEPSG4326(e,t,r,n){const i=e.length;r=r>1?r:2,n=n??r,void 0===t&&(t=r>2?e.slice():new Array(i));for(let o=0;oMAX_LATITUDE&&(t=MAX_LATITUDE);const n=toRadians(t),i=Math.sin(n),o=Math.cos(n),s=i/o,a=s*s,l=a*a,c=toRadians(e),u=toRadians(zoneToCentralLongitude(r.number)),h=R/Math.sqrt(1-E*i**2),d=E_P2*o**2,p=o*wrap(c-u,-Math.PI,Math.PI),f=p*p,g=f*p,m=g*p,y=m*p,b=y*p,v=R*(M1*n-M2*Math.sin(2*n)+M3*Math.sin(4*n)-M4*Math.sin(6*n)),_=K0*h*(p+g/6*(1-a+d)+y/120*(5-18*a+l+72*d-58*E_P2))+5e5;let w=K0*(v+h*s*(f/2+m/24*(5-a+9*d+4*d**2)+b/720*(61-58*a+l+600*d-330*E_P2)));return r.north||(w+=1e7),[_,w]}function zoneToCentralLongitude(e){return 6*(e-1)-180+3}const epsgRegExes=[/^EPSG:(\d+)$/,/^urn:ogc:def:crs:EPSG::(\d+)$/,/^http:\/\/www\.opengis\.net\/def\/crs\/EPSG\/0\/(\d+)$/];function zoneFromCode(e){let t=0;for(const i of epsgRegExes){const r=e.match(i);if(r){t=parseInt(r[1]);break}}if(!t)return null;let r=0,n=!1;return t>32700&&t<32761?r=t-32700:t>32600&&t<32661&&(n=!0,r=t-32600),r?{number:r,north:n}:null}function makeTransformFunction(e,t){return function(r,n,i,o){const s=r.length;i=i>1?i:2,o=o??i,n||(n=i>2?r.slice():new Array(s));for(let a=0;a=a?t[s+e]:o[e]}return r}}function fromLonLat(e,t){return disableCoordinateWarning(),transform(e,"EPSG:4326",void 0!==t?t:"EPSG:3857")}function toLonLat(e){const t=transform(e,"EPSG:3857","EPSG:4326"),r=t[0];return(r<-180||r>180)&&(t[0]=modulo(r+180,360)-180),t}function equivalent$1(e,t){if(e===t)return!0;const r=e.getUnits()===t.getUnits();return(e.getCode()===t.getCode()||getTransformFromProjections(e,t)===cloneTransform)&&r}function getTransformFromProjections(e,t){const r=e.getCode(),n=t.getCode();let i=get$3(r,n);if(i)return i;let o=null,s=null;for(const l of transformFactories)o||(o=l(e)),s||(s=l(t));if(!o&&!s)return null;const a="EPSG:4326";if(s)if(o)i=composeTransformFuncs(o.inverse,s.forward);else{const e=get$3(r,a);e&&(i=composeTransformFuncs(e,s.forward))}else{const e=get$3(a,n);e&&(i=composeTransformFuncs(o.inverse,e))}return i&&(addProjection(e),addProjection(t),add(e,t,i)),i}function composeTransformFuncs(e,t){return function(r,n,i,o){return n=e(r,n,i,o),t(n,n,i,o)}}function getTransform(e,t){return getTransformFromProjections(get$2(e),get$2(t))}function transform(e,t,r){const n=getTransform(t,r);if(!n){const e=get$2(t).getCode(),n=get$2(r).getCode();throw new Error(`No transform available between ${e} and ${n}`)}return n(e,void 0,e.length)}function transformExtent(e,t,r,n){return applyTransform(e,getTransform(t,r),void 0,n)}let userProjection=null;function getUserProjection(){return userProjection}function toUserCoordinate(e){return e}function fromUserCoordinate(e){return showCoordinateWarning&&!equals(e,[0,0])&&e[0]>=-180&&e[0]<=180&&e[1]>=-90&&e[1]<=90&&(showCoordinateWarning=!1,warn("Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.")),e}function toUserExtent(e){return e}function fromUserExtent(e){return e}function addCommon(){addEquivalentProjections(PROJECTIONS$1),addEquivalentProjections(PROJECTIONS),addEquivalentTransforms(PROJECTIONS,PROJECTIONS$1,fromEPSG4326,toEPSG4326)}addCommon();const tmp_=new Array(6);function create(){return[1,0,0,1,0,0]}function reset(e){return set(e,1,0,0,1,0,0)}function multiply(e,t){const r=e[0],n=e[1],i=e[2],o=e[3],s=e[4],a=e[5],l=t[0],c=t[1],u=t[2],h=t[3],d=t[4],p=t[5];return e[0]=r*l+i*c,e[1]=n*l+o*c,e[2]=r*u+i*h,e[3]=n*u+o*h,e[4]=r*d+i*p+s,e[5]=n*d+o*p+a,e}function set(e,t,r,n,i,o,s){return e[0]=t,e[1]=r,e[2]=n,e[3]=i,e[4]=o,e[5]=s,e}function setFromArray(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e}function apply$1(e,t){const r=t[0],n=t[1];return t[0]=e[0]*r+e[2]*n+e[4],t[1]=e[1]*r+e[3]*n+e[5],t}function scale$2(e,t,r){return multiply(e,set(tmp_,t,0,0,r,0,0))}function translate$1(e,t,r){return multiply(e,set(tmp_,1,0,0,1,t,r))}function compose(e,t,r,n,i,o,s,a){const l=Math.sin(o),c=Math.cos(o);return e[0]=n*c,e[1]=i*l,e[2]=-n*l,e[3]=i*c,e[4]=s*n*c-a*n*l+t,e[5]=s*i*l+a*i*c+r,e}function makeInverse(e,t){const r=determinant(t);assert$1(0!==r,"Transformation matrix cannot be inverted");const n=t[0],i=t[1],o=t[2],s=t[3],a=t[4],l=t[5];return e[0]=s/r,e[1]=-i/r,e[2]=-o/r,e[3]=n/r,e[4]=(o*l-s*a)/r,e[5]=-(n*l-i*a)/r,e}function determinant(e){return e[0]*e[3]-e[1]*e[2]}const matrixPrecision=[1e5,1e5,1e5,1e5,2,2];function toString$1(e){return"matrix("+e.join(", ")+")"}function fromString$1(e){return e.substring(7,e.length-1).split(",").map(parseFloat)}function equivalent(e,t){const r=fromString$1(e),n=fromString$1(t);for(let i=0;i<6;++i)if(0!==Math.round((r[i]-n[i])*matrixPrecision[i]))return!1;return!0}function transform2D(e,t,r,n,i,o,s){o=o||[],s=s||2;let a=0;for(let l=t;l{if(!r)return this.getSimplifiedGeometry(t);const n=this.clone();return n.applyTransform(r),n.getSimplifiedGeometry(t)})}simplifyTransformed(e,t){return this.simplifyTransformedInternal(this.getRevision(),e,t)}clone(){return abstract()}closestPointXY(e,t,r,n){return abstract()}containsXY(e,t){return 0===this.closestPointXY(e,t,tmpPoint,Number.MIN_VALUE)}getClosestPoint(e,t){return t=t||[NaN,NaN],this.closestPointXY(e[0],e[1],t,1/0),t}intersectsCoordinate(e){return this.containsXY(e[0],e[1])}computeExtent(e){return abstract()}getExtent(e){if(this.extentRevision_!=this.getRevision()){const e=this.computeExtent(this.extent_);(isNaN(e[0])||isNaN(e[1]))&&createOrUpdateEmpty(e),this.extentRevision_=this.getRevision()}return returnOrUpdate(this.extent_,e)}rotate(e,t){abstract()}scale(e,t,r){abstract()}simplify(e){return this.getSimplifiedGeometry(e*e)}getSimplifiedGeometry(e){return abstract()}getType(){return abstract()}applyTransform(e){abstract()}intersectsExtent(e){return abstract()}translate(e,t){abstract()}transform(e,t){const r=get$2(e),n="tile-pixels"==r.getUnits()?function(e,n,i){const o=r.getExtent(),s=r.getWorldExtent(),a=getHeight(s)/getHeight(o);compose(tmpTransform$1,s[0],s[3],a,-a,0,0,0);const l=transform2D(e,0,e.length,i,tmpTransform$1,n),c=getTransform(r,t);return c?c(l,l,i):l}:getTransform(r,t);return this.applyTransform(n),this}}class SimpleGeometry extends Geometry{constructor(){super(),this.layout="XY",this.stride=2,this.flatCoordinates}computeExtent(e){return createOrUpdateFromFlatCoordinates(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,e)}getCoordinates(){return abstract()}getFirstCoordinate(){return this.flatCoordinates.slice(0,this.stride)}getFlatCoordinates(){return this.flatCoordinates}getLastCoordinate(){return this.flatCoordinates.slice(this.flatCoordinates.length-this.stride)}getLayout(){return this.layout}getSimplifiedGeometry(e){if(this.simplifiedGeometryRevision!==this.getRevision()&&(this.simplifiedGeometryMaxMinSquaredTolerance=0,this.simplifiedGeometryRevision=this.getRevision()),e<0||0!==this.simplifiedGeometryMaxMinSquaredTolerance&&e<=this.simplifiedGeometryMaxMinSquaredTolerance)return this;const t=this.getSimplifiedGeometryInternal(e);return t.getFlatCoordinates().length1)h=r;else{if(d>0){for(let i=0;ii&&(i=a),o=r,s=n}return i}function arrayMaxSquaredDelta(e,t,r,n,i){for(let o=0,s=r.length;o0;){const r=c.pop(),o=c.pop();let s=0;const a=e[o],h=e[o+1],d=e[r],p=e[r+1];for(let t=o+n;ts&&(u=t,s=r)}s>i&&(l[(u-t)/n]=1,o+n0&&f>d)&&(p<0&&g0&&g>p)?(a=r,l=h):(o[s++]=a,o[s++]=l,c=a,u=l,a=r,l=h)}return o[s++]=a,o[s++]=l,s}function quantizeArray(e,t,r,n,i,o,s,a){for(let l=0,c=r.length;lo&&(r-a)*(o-l)-(i-a)*(n-l)>0&&s++:n<=o&&(r-a)*(o-l)-(i-a)*(n-l)<0&&s--,a=r,l=n}return 0!==s}function linearRingsContainsXY(e,t,r,n,i,o){if(0===r.length)return!1;if(!linearRingContainsXY(e,t,r[0],n,i,o))return!1;for(let s=1,a=r.length;sy&&(c=(u+h)/2,linearRingsContainsXY(e,t,r,n,c,f)&&(m=c,y=i)),u=h}return isNaN(m)&&(m=i[o]),s?(s.push(m,f,y),s):[m,f,y]}function getInteriorPointsOfMultiArray(e,t,r,n,i){let o=[];for(let s=0,a=r.length;s=i[0]&&o[2]<=i[2]||o[1]>=i[1]&&o[3]<=i[3]||forEach(e,t,r,n,function(e,t){return intersectsSegment(i,e,t)}))}function intersectsLineStringArray(e,t,r,n,i){for(let o=0,s=r.length;o0}function linearRingsAreOriented(e,t,r,n,i){i=void 0!==i&&i;for(let o=0,s=r.length;ou&&d1&&"function"==typeof arguments[r-1]&&(t=arguments[r-1],--r);let n=0;for(;n0}getInteracting(){return this.hints_[ViewHint.INTERACTING]>0}cancelAnimations(){let e;this.setHint(ViewHint.ANIMATING,-this.hints_[ViewHint.ANIMATING]);for(let t=0,r=this.animations_.length;t=0;--r){const n=this.animations_[r];let i=!0;for(let r=0,o=n.length;r0?s/o.duration:1;a>=1?(o.complete=!0,a=1):i=!1;const l=o.easing(a);if(o.sourceCenter){const e=o.sourceCenter[0],t=o.sourceCenter[1],r=o.targetCenter[0],n=o.targetCenter[1];this.nextCenter_=o.targetCenter;const i=e+l*(r-e),s=t+l*(n-t);this.targetCenter_=[i,s]}if(o.sourceResolution&&o.targetResolution){const e=1===l?o.targetResolution:o.sourceResolution+l*(o.targetResolution-o.sourceResolution);if(o.anchor){const t=this.getViewportSize_(this.getRotation()),r=this.constraints_.resolution(e,0,t,!0);this.targetCenter_=this.calculateCenterZoom(r,o.anchor)}this.nextResolution_=o.targetResolution,this.targetResolution_=e,this.applyTargetState_(!0)}if(void 0!==o.sourceRotation&&void 0!==o.targetRotation){const e=1===l?modulo(o.targetRotation+Math.PI,2*Math.PI)-Math.PI:o.sourceRotation+l*(o.targetRotation-o.sourceRotation);if(o.anchor){const t=this.constraints_.rotation(e,!0);this.targetCenter_=this.calculateCenterRotate(t,o.anchor)}this.nextRotation_=o.targetRotation,this.targetRotation_=e}if(this.applyTargetState_(!0),t=!0,!o.complete)break}if(i){this.animations_[r]=null,this.setHint(ViewHint.ANIMATING,-1),this.nextCenter_=null,this.nextResolution_=NaN,this.nextRotation_=NaN;const e=n[0].callback;e&&animationCallback(e,!0)}}this.animations_=this.animations_.filter(Boolean),t&&void 0===this.updateAnimationKey_&&(this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_.bind(this)))}calculateCenterRotate(e,t){let r;const n=this.getCenterInternal();return void 0!==n&&(r=[n[0]-t[0],n[1]-t[1]],rotate$1(r,e-this.getRotation()),add$2(r,t)),r}calculateCenterZoom(e,t){let r;const n=this.getCenterInternal(),i=this.getResolution();return void 0!==n&&void 0!==i&&(r=[t[0]-e*(t[0]-n[0])/i,t[1]-e*(t[1]-n[1])/i]),r}getViewportSize_(e){const t=this.viewportSize_;if(e){const r=t[0],n=t[1];return[Math.abs(r*Math.cos(e))+Math.abs(n*Math.sin(e)),Math.abs(r*Math.sin(e))+Math.abs(n*Math.cos(e))]}return t}setViewportSize(e){this.viewportSize_=Array.isArray(e)?e.slice():[100,100],this.getAnimating()||this.resolveConstraints(0)}getCenter(){const e=this.getCenterInternal();return e?toUserCoordinate(e,this.getProjection()):e}getCenterInternal(){return this.get(ViewProperty.CENTER)}getConstraints(){return this.constraints_}getConstrainResolution(){return this.get("constrainResolution")}getHints(e){return void 0!==e?(e[0]=this.hints_[0],e[1]=this.hints_[1],e):this.hints_.slice()}calculateExtent(e){return toUserExtent(this.calculateExtentInternal(e),this.getProjection())}calculateExtentInternal(e){e=e||this.getViewportSizeMinusPadding_();const t=this.getCenterInternal();assert$1(t,"The view center is not defined");const r=this.getResolution();assert$1(void 0!==r,"The view resolution is not defined");const n=this.getRotation();return assert$1(void 0!==n,"The view rotation is not defined"),getForViewAndSize(t,r,n,e)}getMaxResolution(){return this.maxResolution_}getMinResolution(){return this.minResolution_}getMaxZoom(){return this.getZoomForResolution(this.minResolution_)}setMaxZoom(e){this.applyOptions_(this.getUpdatedOptions_({maxZoom:e}))}getMinZoom(){return this.getZoomForResolution(this.maxResolution_)}setMinZoom(e){this.applyOptions_(this.getUpdatedOptions_({minZoom:e}))}setConstrainResolution(e){this.applyOptions_(this.getUpdatedOptions_({constrainResolution:e}))}getProjection(){return this.projection_}getResolution(){return this.get(ViewProperty.RESOLUTION)}getResolutions(){return this.resolutions_}getResolutionForExtent(e,t){return this.getResolutionForExtentInternal(fromUserExtent(e,this.getProjection()),t)}getResolutionForExtentInternal(e,t){t=t||this.getViewportSizeMinusPadding_();const r=getWidth(e)/t[0],n=getHeight(e)/t[1];return Math.max(r,n)}getResolutionForValueFunction(e){e=e||2;const t=this.getConstrainedResolution(this.maxResolution_),r=this.minResolution_,n=Math.log(t/r)/Math.log(e);return function(r){return t/Math.pow(e,r*n)}}getRotation(){return this.get(ViewProperty.ROTATION)}getValueForResolutionFunction(e){const t=Math.log(e||2),r=this.getConstrainedResolution(this.maxResolution_),n=this.minResolution_,i=Math.log(r/n)/t;return function(e){return Math.log(r/e)/t/i}}getViewportSizeMinusPadding_(e){let t=this.getViewportSize_(e);const r=this.padding_;return r&&(t=[t[0]-r[1]-r[3],t[1]-r[0]-r[2]]),t}getState(){const e=this.getProjection(),t=this.getResolution(),r=this.getRotation();let n=this.getCenterInternal();const i=this.padding_;if(i){const e=this.getViewportSizeMinusPadding_();n=calculateCenterOn(n,this.getViewportSize_(),[e[0]/2+i[3],e[1]/2+i[0]],t,r)}return{center:n.slice(0),projection:void 0!==e?e:null,resolution:t,nextCenter:this.nextCenter_,nextResolution:this.nextResolution_,nextRotation:this.nextRotation_,rotation:r,zoom:this.getZoom()}}getViewStateAndExtent(){return{viewState:this.getState(),extent:this.calculateExtent()}}getZoom(){let e;const t=this.getResolution();return void 0!==t&&(e=this.getZoomForResolution(t)),e}getZoomForResolution(e){let t,r,n=this.minZoom_||0;if(this.resolutions_){const i=linearFindNearest(this.resolutions_,e,1);n=i,t=this.resolutions_[i],r=i==this.resolutions_.length-1?2:t/this.resolutions_[i+1]}else t=this.maxResolution_,r=this.zoomFactor_;return n+Math.log(t/e)/Math.log(r)}getResolutionForZoom(e){if(this.resolutions_?.length){if(1===this.resolutions_.length)return this.resolutions_[0];const t=clamp$1(Math.floor(e),0,this.resolutions_.length-2),r=this.resolutions_[t]/this.resolutions_[t+1];return this.resolutions_[t]/Math.pow(r,clamp$1(e-t,0,1))}return this.maxResolution_/Math.pow(this.zoomFactor_,e-this.minZoom_)}fit(e,t){let r;if(assert$1(Array.isArray(e)||"function"==typeof e.getSimplifiedGeometry,"Invalid extent or geometry provided as `geometry`"),Array.isArray(e))assert$1(!isEmpty(e),"Cannot fit empty extent provided as `geometry`"),r=fromExtent(fromUserExtent(e,this.getProjection()));else if("Circle"===e.getType()){const t=fromUserExtent(e.getExtent(),this.getProjection());r=fromExtent(t),r.rotate(this.getRotation(),getCenter(t))}else r=e;this.fitInternal(r,t)}rotatedExtentForGeometry(e){const t=this.getRotation(),r=Math.cos(t),n=Math.sin(-t),i=e.getFlatCoordinates(),o=e.getStride();let s=1/0,a=1/0,l=-1/0,c=-1/0;for(let u=0,h=i.length;ue.trim().replace(/^['"]|['"]$/g,"")),r};function createCanvasContext2D(e,t,r,n){let i;return i=r&&r.length?r.shift():WORKER_OFFSCREEN_CANVAS?new class extends OffscreenCanvas{style={}}(e??300,t??150):document.createElement("canvas"),e&&(i.width=e),t&&(i.height=t),i.getContext("2d",n)}let sharedCanvasContext;function getSharedCanvasContext2D(){return sharedCanvasContext||(sharedCanvasContext=createCanvasContext2D(1,1)),sharedCanvasContext}function releaseCanvas(e){const t=e.canvas;t.width=1,t.height=1,e.clearRect(0,0,1,1)}function outerWidth(e){let t=e.offsetWidth;const r=getComputedStyle(e);return t+=parseInt(r.marginLeft,10)+parseInt(r.marginRight,10),t}function outerHeight(e){let t=e.offsetHeight;const r=getComputedStyle(e);return t+=parseInt(r.marginTop,10)+parseInt(r.marginBottom,10),t}function replaceNode(e,t){const r=t.parentNode;r&&r.replaceChild(e,t)}function removeChildren(e){for(;e.lastChild;)e.lastChild.remove()}function replaceChildren(e,t){const r=e.childNodes;for(let n=0;;++n){const i=r[n],o=t[n];if(!i&&!o)break;i!==o&&(i?o?e.insertBefore(o,i):(e.removeChild(i),--n):e.appendChild(o))}}function createMockDiv(){const e=new Proxy({childNodes:[],appendChild:function(e){return this.childNodes.push(e),e},remove:function(){},removeChild:function(e){const t=this.childNodes.indexOf(e);if(-1===t)throw new Error("Node to remove was not found");return this.childNodes.splice(t,1),e},insertBefore:function(e,t){const r=this.childNodes.indexOf(t);if(-1===r)throw new Error("Reference node not found");return this.childNodes.splice(r,0,e),e},style:{}},{get:(e,t,r)=>"firstElementChild"===t?e.childNodes.length>0?e.childNodes[0]:null:Reflect.get(e,t,r)});return e}function isCanvas(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas}class Control extends BaseObject{constructor(e){super();const t=e.element;!t||e.target||t.style.pointerEvents||(t.style.pointerEvents="auto"),this.element=t||null,this.target_=null,this.map_=null,this.listenerKeys=[],e.render&&(this.render=e.render),e.target&&this.setTarget(e.target)}disposeInternal(){this.element?.remove(),super.disposeInternal()}getMap(){return this.map_}setMap(e){this.map_&&this.element?.remove();for(let t=0,r=this.listenerKeys.length;tt.getAttributions(e)));if(void 0!==this.attributions_&&(Array.isArray(this.attributions_)?this.attributions_.forEach(e=>r.add(e)):r.add(this.attributions_)),!this.overrideCollapsible_){const e=!t.some(e=>!1===e.getSource()?.getAttributionsCollapsible());this.setCollapsible(e)}return Array.from(r)}async updateElement_(e){if(!e)return void(this.renderedVisible_&&(this.element.style.display="none",this.renderedVisible_=!1));const t=await Promise.all(this.collectSourceAttributions_(e).map(e=>toPromise(()=>e))),r=t.length>0;if(this.renderedVisible_!=r&&(this.element.style.display=r?"":"none",this.renderedVisible_=r),!equals$2(t,this.renderedAttributions_)){removeChildren(this.ulElement_);for(let e=0,r=t.length;e0&&t%(2*Math.PI)!=0?e.animate({rotation:0,duration:this.duration_,easing:easeOut}):e.setRotation(0))}render(e){const t=e.frameState;if(!t)return;const r=t.viewState.rotation;if(r!=this.rotation_){const e="rotate("+r+"rad)";if(this.autoHide_){const e=this.element.classList.contains(CLASS_HIDDEN);e||0!==r?e&&0!==r&&this.element.classList.remove(CLASS_HIDDEN):this.element.classList.add(CLASS_HIDDEN)}this.label_.style.transform=e}this.rotation_=r}}class Zoom extends Control{constructor(e){e=e||{},super({element:document.createElement("div"),target:e.target});const t=void 0!==e.className?e.className:"ol-zoom",r=void 0!==e.delta?e.delta:1,n=void 0!==e.zoomInClassName?e.zoomInClassName:t+"-in",i=void 0!==e.zoomOutClassName?e.zoomOutClassName:t+"-out",o=void 0!==e.zoomInLabel?e.zoomInLabel:"+",s=void 0!==e.zoomOutLabel?e.zoomOutLabel:"–",a=void 0!==e.zoomInTipLabel?e.zoomInTipLabel:"Zoom in",l=void 0!==e.zoomOutTipLabel?e.zoomOutTipLabel:"Zoom out",c=document.createElement("button");c.className=n,c.setAttribute("type","button"),c.title=a,c.appendChild("string"==typeof o?document.createTextNode(o):o),c.addEventListener(EventType$1.CLICK,this.handleClick_.bind(this,r),!1);const u=document.createElement("button");u.className=i,u.setAttribute("type","button"),u.title=l,u.appendChild("string"==typeof s?document.createTextNode(s):s),u.addEventListener(EventType$1.CLICK,this.handleClick_.bind(this,-r),!1);const h=t+" "+CLASS_UNSELECTABLE+" "+CLASS_CONTROL,d=this.element;d.className=h,d.appendChild(c),d.appendChild(u),this.duration_=void 0!==e.duration?e.duration:250}handleClick_(e,t){t.preventDefault(),this.zoomByDelta_(e)}zoomByDelta_(e){const t=this.getMap().getView();if(!t)return;const r=t.getZoom();if(void 0!==r){const n=t.getConstrainedZoom(r+e);this.duration_>0?(t.getAnimating()&&t.cancelAnimations(),t.animate({zoom:n,duration:this.duration_,easing:easeOut})):t.setZoom(n)}}}function defaults$1(e){e=e||{};const t=new Collection;return(void 0===e.zoom||e.zoom)&&t.push(new Zoom(e.zoomOptions)),(void 0===e.rotate||e.rotate)&&t.push(new Rotate(e.rotateOptions)),(void 0===e.attribution||e.attribution)&&t.push(new Attribution(e.attributionOptions)),t}class Kinetic{constructor(e,t,r){this.decay_=e,this.minVelocity_=t,this.delay_=r,this.points_=[],this.angle_=0,this.initialVelocity_=0}begin(){this.points_.length=0,this.angle_=0,this.initialVelocity_=0}update(e,t){this.points_.push(e,t,Date.now())}end(){if(this.points_.length<6)return!1;const e=Date.now()-this.delay_,t=this.points_.length-3;if(this.points_[t+2]0&&this.points_[r+2]>e;)r-=3;const n=this.points_[t+2]-this.points_[r+2];if(n<1e3/60)return!1;const i=this.points_[t]-this.points_[r],o=this.points_[t+1]-this.points_[r+1];return this.angle_=Math.atan2(o,i),this.initialVelocity_=Math.sqrt(i*i+o*o)/n,this.initialVelocity_>this.minVelocity_}getDistance(){return(this.minVelocity_-this.initialVelocity_)/this.decay_}getAngle(){return this.angle_}}const InteractionProperty={ACTIVE:"active"};class Interaction extends BaseObject{constructor(e){super(),this.on,this.once,this.un,e&&e.handleEvent&&(this.handleEvent=e.handleEvent),this.map_=null,this.setActive(!0)}getActive(){return this.get(InteractionProperty.ACTIVE)}getMap(){return this.map_}handleEvent(e){return!0}setActive(e){this.set(InteractionProperty.ACTIVE,e)}setMap(e){this.map_=e}}function pan(e,t,r){const n=e.getCenterInternal();if(n){const i=[n[0]+t[0],n[1]+t[1]];e.animateInternal({duration:void 0!==r?r:250,easing:linear,center:e.getConstrainedCenter(i)})}}function zoomByDelta(e,t,r,n){const i=e.getZoom();if(void 0===i)return;const o=e.getConstrainedZoom(i+t),s=e.getResolutionForZoom(o);e.getAnimating()&&e.cancelAnimations(),e.animate({resolution:s,anchor:r,duration:void 0!==n?n:250,easing:easeOut})}class DoubleClickZoom extends Interaction{constructor(e){super(),e=e||{},this.delta_=e.delta?e.delta:1,this.duration_=void 0!==e.duration?e.duration:250}handleEvent(e){let t=!1;if(e.type==MapBrowserEventType.DBLCLICK){const r=e.originalEvent,n=e.map,i=e.coordinate,o=r.shiftKey?-this.delta_:this.delta_;zoomByDelta(n.getView(),o,i,this.duration_),r.preventDefault(),t=!0}return!t}}function all$1(e){const t=arguments;return function(e){let r=!0;for(let n=0,i=t.length;n0}}else if(e.type==MapBrowserEventType.POINTERDOWN){const r=this.handleDownEvent(e);this.handlingDownUpSequence=r,t=this.stopDown(r)}else e.type==MapBrowserEventType.POINTERMOVE&&this.handleMoveEvent(e);return!t}handleMoveEvent(e){}handleUpEvent(e){return!1}stopDown(e){return e}updateTrackedPointers_(e){e.activePointers&&(this.targetPointers=e.activePointers)}}function centroid(e){const t=e.length;let r=0,n=0;for(let i=0;i0&&this.condition_(e)){const t=e.map.getView();return this.lastCentroid=null,t.getAnimating()&&t.cancelAnimations(),this.kinetic_&&this.kinetic_.begin(),this.noKinetic_=this.targetPointers.length>1,!0}return!1}}class DragRotate extends PointerInteraction{constructor(e){e=e||{},super({stopDown:FALSE}),this.condition_=e.condition?e.condition:altShiftKeysOnly,this.lastAngle_=void 0,this.duration_=void 0!==e.duration?e.duration:250}handleDragEvent(e){if(!mouseOnly(e))return;const t=e.map,r=t.getView();if(r.getConstraints().rotation===disable)return;const n=t.getSize(),i=e.pixel,o=Math.atan2(n[1]/2-i[1],i[0]-n[0]/2);if(void 0!==this.lastAngle_){const e=o-this.lastAngle_;r.adjustRotationInternal(-e)}this.lastAngle_=o}handleUpEvent(e){return!mouseOnly(e)||(e.map.getView().endInteraction(this.duration_),!1)}handleDownEvent(e){return!(!mouseOnly(e)||!mouseActionButton(e)||!this.condition_(e)||(e.map.getView().beginInteraction(),this.lastAngle_=void 0,0))}}class RenderBox extends Disposable{constructor(e){super(),this.geometry_=null,this.element_=document.createElement("div"),this.element_.style.position="absolute",this.element_.style.pointerEvents="auto",this.element_.className="ol-box "+e,this.map_=null,this.startPixel_=null,this.endPixel_=null}disposeInternal(){this.setMap(null)}render_(){const e=this.startPixel_,t=this.endPixel_,r="px",n=this.element_.style;n.left=Math.min(e[0],t[0])+r,n.top=Math.min(e[1],t[1])+r,n.width=Math.abs(t[0]-e[0])+r,n.height=Math.abs(t[1]-e[1])+r}setMap(e){if(this.map_){this.map_.getOverlayContainer().removeChild(this.element_);const e=this.element_.style;e.left="inherit",e.top="inherit",e.width="inherit",e.height="inherit"}this.map_=e,this.map_&&this.map_.getOverlayContainer().appendChild(this.element_)}setPixels(e,t){this.startPixel_=e,this.endPixel_=t,this.createOrUpdateGeometry(),this.render_()}createOrUpdateGeometry(){if(!this.map_)return;const e=this.startPixel_,t=this.endPixel_,r=[e,[e[0],t[1]],t,[t[0],e[1]]].map(this.map_.getCoordinateFromPixelInternal,this.map_);r[4]=r[0].slice(),this.geometry_?this.geometry_.setCoordinates([r]):this.geometry_=new Polygon([r])}getGeometry(){return this.geometry_}}const DragBoxEventType={BOXSTART:"boxstart",BOXDRAG:"boxdrag",BOXEND:"boxend",BOXCANCEL:"boxcancel"};class DragBoxEvent extends BaseEvent{constructor(e,t,r){super(e),this.coordinate=t,this.mapBrowserEvent=r}}class DragBox extends PointerInteraction{constructor(e){super(),this.on,this.once,this.un,e=e??{},this.box_=new RenderBox(e.className||"ol-dragbox"),this.minArea_=e.minArea??64,e.onBoxEnd&&(this.onBoxEnd=e.onBoxEnd),this.startPixel_=null,this.condition_=e.condition??mouseActionButton,this.boxEndCondition_=e.boxEndCondition??this.defaultBoxEndCondition}defaultBoxEndCondition(e,t,r){const n=r[0]-t[0],i=r[1]-t[1];return n*n+i*i>=this.minArea_}getGeometry(){return this.box_.getGeometry()}handleDragEvent(e){this.startPixel_&&(this.box_.setPixels(this.startPixel_,e.pixel),this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXDRAG,e.coordinate,e)))}handleUpEvent(e){if(!this.startPixel_)return!1;const t=this.boxEndCondition_(e,this.startPixel_,e.pixel);return t&&this.onBoxEnd(e),this.dispatchEvent(new DragBoxEvent(t?DragBoxEventType.BOXEND:DragBoxEventType.BOXCANCEL,e.coordinate,e)),this.box_.setMap(null),this.startPixel_=null,!1}handleDownEvent(e){return!!this.condition_(e)&&(this.startPixel_=e.pixel,this.box_.setMap(e.map),this.box_.setPixels(this.startPixel_,this.startPixel_),this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXSTART,e.coordinate,e)),!0)}onBoxEnd(e){}setActive(e){e||(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXCANCEL,this.startPixel_,null)),this.startPixel_=null)),super.setActive(e)}setMap(e){this.getMap()&&(this.box_.setMap(null),this.startPixel_&&(this.dispatchEvent(new DragBoxEvent(DragBoxEventType.BOXCANCEL,this.startPixel_,null)),this.startPixel_=null)),super.setMap(e)}}class DragZoom extends DragBox{constructor(e){super({condition:(e=e||{}).condition?e.condition:shiftKeyOnly,className:e.className||"ol-dragzoom",minArea:e.minArea}),this.duration_=void 0!==e.duration?e.duration:200,this.out_=void 0!==e.out&&e.out}onBoxEnd(e){const t=this.getMap().getView();let r=this.getGeometry();if(this.out_){const e=t.rotatedExtentForGeometry(r),n=t.getResolutionForExtentInternal(e),i=t.getResolution()/n;r=r.clone(),r.scale(i*i)}t.fitInternal(r,{duration:this.duration_,easing:easeOut})}}const Key={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",DOWN:"ArrowDown"};class KeyboardPan extends Interaction{constructor(e){super(),e=e||{},this.defaultCondition_=function(e){return noModifierKeys(e)&&targetNotEditable(e)},this.condition_=void 0!==e.condition?e.condition:this.defaultCondition_,this.duration_=void 0!==e.duration?e.duration:100,this.pixelDelta_=void 0!==e.pixelDelta?e.pixelDelta:128}handleEvent(e){let t=!1;if(e.type==EventType$1.KEYDOWN){const r=e.originalEvent,n=r.key;if(this.condition_(e)&&(n==Key.DOWN||n==Key.LEFT||n==Key.RIGHT||n==Key.UP)){const i=e.map.getView(),o=i.getResolution()*this.pixelDelta_;let s=0,a=0;n==Key.DOWN?a=-o:n==Key.LEFT?s=-o:n==Key.RIGHT?s=o:a=o;const l=[s,a];rotate$1(l,i.getRotation()),pan(i,l,this.duration_),r.preventDefault(),t=!0}}return!t}}class KeyboardZoom extends Interaction{constructor(e){super(),e=e||{},this.condition_=e.condition?e.condition:function(e){return!platformModifierKey(e)&&targetNotEditable(e)},this.delta_=e.delta?e.delta:1,this.duration_=void 0!==e.duration?e.duration:100}handleEvent(e){let t=!1;if(e.type==EventType$1.KEYDOWN||e.type==EventType$1.KEYPRESS){const r=e.originalEvent,n=r.key;if(this.condition_(e)&&("+"===n||"-"===n)){const i=e.map,o="+"===n?this.delta_:-this.delta_;zoomByDelta(i.getView(),o,void 0,this.duration_),r.preventDefault(),t=!0}}return!t}}const DELTA_LINE_MULTIPLIER=40,DELTA_PAGE_MULTIPLIER=300;class MouseWheelZoom extends Interaction{constructor(e){super(e=e||{}),this.totalDelta_=0,this.lastDelta_=0,this.maxDelta_=void 0!==e.maxDelta?e.maxDelta:1,this.duration_=void 0!==e.duration?e.duration:250,this.timeout_=void 0!==e.timeout?e.timeout:80,this.useAnchor_=void 0===e.useAnchor||e.useAnchor,this.constrainResolution_=void 0!==e.constrainResolution&&e.constrainResolution;const t=e.condition?e.condition:always$1;this.condition_=e.onFocusOnly?all$1(focusWithTabindex,t):t,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_,this.mode_=void 0,this.trackpadEventGap_=400,this.trackpadTimeoutId_,this.deltaPerZoom_=300}endInteraction_(){this.trackpadTimeoutId_=void 0;const e=this.getMap();e&&e.getView().endInteraction(void 0,this.lastDelta_?this.lastDelta_>0?1:-1:0,this.lastAnchor_?e.getCoordinateFromPixel(this.lastAnchor_):null)}handleEvent(e){if(!this.condition_(e))return!0;if(e.type!==EventType$1.WHEEL)return!0;const t=e.map,r=e.originalEvent;r.preventDefault(),this.useAnchor_&&(this.lastAnchor_=e.pixel);let n=r.deltaY;switch(r.deltaMode){case WheelEvent.DOM_DELTA_LINE:n*=DELTA_LINE_MULTIPLIER;break;case WheelEvent.DOM_DELTA_PAGE:n*=DELTA_PAGE_MULTIPLIER}if(0===n)return!1;this.lastDelta_=n;const i=Date.now();void 0===this.startTime_&&(this.startTime_=i),(!this.mode_||i-this.startTime_>this.trackpadEventGap_)&&(this.mode_=Math.abs(n)<4?"trackpad":"wheel");const o=t.getView();if("trackpad"===this.mode_&&!o.getConstrainResolution()&&!this.constrainResolution_)return this.trackpadTimeoutId_?clearTimeout(this.trackpadTimeoutId_):(o.getAnimating()&&o.cancelAnimations(),o.beginInteraction()),this.trackpadTimeoutId_=setTimeout(this.endInteraction_.bind(this),this.timeout_),o.adjustZoom(-n/this.deltaPerZoom_,this.lastAnchor_?t.getCoordinateFromPixel(this.lastAnchor_):null),this.startTime_=i,!1;this.totalDelta_+=n;const s=Math.max(this.timeout_-(i-this.startTime_),0);return clearTimeout(this.timeoutId_),this.timeoutId_=setTimeout(this.handleWheelZoom_.bind(this,t),s),!1}handleWheelZoom_(e){const t=e.getView();t.getAnimating()&&t.cancelAnimations();let r=-clamp$1(this.totalDelta_,-this.maxDelta_*this.deltaPerZoom_,this.maxDelta_*this.deltaPerZoom_)/this.deltaPerZoom_;(t.getConstrainResolution()||this.constrainResolution_)&&(r=r?r>0?1:-1:0),zoomByDelta(t,r,this.lastAnchor_?e.getCoordinateFromPixel(this.lastAnchor_):null,this.duration_),this.mode_=void 0,this.totalDelta_=0,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_=void 0}setMouseAnchor(e){this.useAnchor_=e,e||(this.lastAnchor_=null)}}class PinchRotate extends PointerInteraction{constructor(e){const t=e=e||{};t.stopDown||(t.stopDown=FALSE),super(t),this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.threshold_=void 0!==e.threshold?e.threshold:.3,this.duration_=void 0!==e.duration?e.duration:250}handleDragEvent(e){let t=0;const r=this.targetPointers[0],n=this.targetPointers[1],i=Math.atan2(n.clientY-r.clientY,n.clientX-r.clientX);if(void 0!==this.lastAngle_){const e=i-this.lastAngle_;this.rotationDelta_+=e,!this.rotating_&&Math.abs(this.rotationDelta_)>this.threshold_&&(this.rotating_=!0),t=e}this.lastAngle_=i;const o=e.map,s=o.getView();s.getConstraints().rotation!==disable&&(this.anchor_=o.getCoordinateFromPixelInternal(o.getEventPixel(centroid(this.targetPointers))),this.rotating_&&(o.render(),s.adjustRotationInternal(t,this.anchor_)))}handleUpEvent(e){return!(this.targetPointers.length<2&&(e.map.getView().endInteraction(this.duration_),1))}handleDownEvent(e){if(this.targetPointers.length>=2){const t=e.map;return this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.handlingDownUpSequence||t.getView().beginInteraction(),!0}return!1}}class PinchZoom extends PointerInteraction{constructor(e){const t=e=e||{};t.stopDown||(t.stopDown=FALSE),super(t),this.anchor_=null,this.duration_=void 0!==e.duration?e.duration:400,this.lastDistance_=void 0,this.lastScaleDelta_=1}handleDragEvent(e){let t=1;const r=this.targetPointers[0],n=this.targetPointers[1],i=r.clientX-n.clientX,o=r.clientY-n.clientY,s=Math.sqrt(i*i+o*o);void 0!==this.lastDistance_&&(t=this.lastDistance_/s),this.lastDistance_=s;const a=e.map,l=a.getView();1!=t&&(this.lastScaleDelta_=t),this.anchor_=a.getCoordinateFromPixelInternal(a.getEventPixel(centroid(this.targetPointers))),a.render(),l.adjustResolutionInternal(t,this.anchor_)}handleUpEvent(e){if(this.targetPointers.length<2){const t=e.map.getView(),r=this.lastScaleDelta_>1?1:-1;return t.endInteraction(this.duration_,r),!1}return!0}handleDownEvent(e){if(this.targetPointers.length>=2){const t=e.map;return this.anchor_=null,this.lastDistance_=void 0,this.lastScaleDelta_=1,this.handlingDownUpSequence||t.getView().beginInteraction(),!0}return!1}}function defaults(e){e=e||{};const t=new Collection,r=new Kinetic(-.005,.05,100);return(void 0===e.altShiftDragRotate||e.altShiftDragRotate)&&t.push(new DragRotate),(void 0===e.doubleClickZoom||e.doubleClickZoom)&&t.push(new DoubleClickZoom({delta:e.zoomDelta,duration:e.zoomDuration})),(void 0===e.dragPan||e.dragPan)&&t.push(new DragPan({onFocusOnly:e.onFocusOnly,kinetic:r})),(void 0===e.pinchRotate||e.pinchRotate)&&t.push(new PinchRotate),(void 0===e.pinchZoom||e.pinchZoom)&&t.push(new PinchZoom({duration:e.zoomDuration})),(void 0===e.keyboard||e.keyboard)&&(t.push(new KeyboardPan),t.push(new KeyboardZoom({delta:e.zoomDelta,duration:e.zoomDuration}))),(void 0===e.mouseWheelZoom||e.mouseWheelZoom)&&t.push(new MouseWheelZoom({onFocusOnly:e.onFocusOnly,duration:e.zoomDuration})),(void 0===e.shiftDragZoom||e.shiftDragZoom)&&t.push(new DragZoom({duration:e.zoomDuration})),t}const LayerProperty={OPACITY:"opacity",VISIBLE:"visible",EXTENT:"extent",Z_INDEX:"zIndex",MAX_RESOLUTION:"maxResolution",MIN_RESOLUTION:"minResolution",MAX_ZOOM:"maxZoom",MIN_ZOOM:"minZoom",SOURCE:"source",MAP:"map"};class BaseLayer extends BaseObject{constructor(e){super(),this.on,this.once,this.un,this.background_=e.background;const t=Object.assign({},e);"object"==typeof e.properties&&(delete t.properties,Object.assign(t,e.properties)),t[LayerProperty.OPACITY]=void 0!==e.opacity?e.opacity:1,assert$1("number"==typeof t[LayerProperty.OPACITY],"Layer opacity must be a number"),t[LayerProperty.VISIBLE]=void 0===e.visible||e.visible,t[LayerProperty.Z_INDEX]=e.zIndex,t[LayerProperty.MAX_RESOLUTION]=void 0!==e.maxResolution?e.maxResolution:1/0,t[LayerProperty.MIN_RESOLUTION]=void 0!==e.minResolution?e.minResolution:0,t[LayerProperty.MIN_ZOOM]=void 0!==e.minZoom?e.minZoom:-1/0,t[LayerProperty.MAX_ZOOM]=void 0!==e.maxZoom?e.maxZoom:1/0,this.className_=void 0!==t.className?t.className:"ol-layer",delete t.className,this.setProperties(t),this.state_=null}getBackground(){return this.background_}getClassName(){return this.className_}getLayerState(e){const t=this.state_||{layer:this,managed:void 0===e||e},r=this.getZIndex();return t.opacity=clamp$1(Math.round(100*this.getOpacity())/100,0,1),t.visible=this.getVisible(),t.extent=this.getExtent(),t.zIndex=void 0!==r||t.managed?r:1/0,t.maxResolution=this.getMaxResolution(),t.minResolution=Math.max(this.getMinResolution(),0),t.minZoom=this.getMinZoom(),t.maxZoom=this.getMaxZoom(),this.state_=t,t}getLayersArray(e){return abstract()}getLayerStatesArray(e){return abstract()}getExtent(){return this.get(LayerProperty.EXTENT)}getMaxResolution(){return this.get(LayerProperty.MAX_RESOLUTION)}getMinResolution(){return this.get(LayerProperty.MIN_RESOLUTION)}getMinZoom(){return this.get(LayerProperty.MIN_ZOOM)}getMaxZoom(){return this.get(LayerProperty.MAX_ZOOM)}getOpacity(){return this.get(LayerProperty.OPACITY)}getSourceState(){return abstract()}getVisible(){return this.get(LayerProperty.VISIBLE)}getZIndex(){return this.get(LayerProperty.Z_INDEX)}setBackground(e){this.background_=e,this.changed()}setExtent(e){this.set(LayerProperty.EXTENT,e)}setMaxResolution(e){this.set(LayerProperty.MAX_RESOLUTION,e)}setMinResolution(e){this.set(LayerProperty.MIN_RESOLUTION,e)}setMaxZoom(e){this.set(LayerProperty.MAX_ZOOM,e)}setMinZoom(e){this.set(LayerProperty.MIN_ZOOM,e)}setOpacity(e){assert$1("number"==typeof e,"Layer opacity must be a number"),this.set(LayerProperty.OPACITY,e)}setVisible(e){this.set(LayerProperty.VISIBLE,e)}setZIndex(e){this.set(LayerProperty.Z_INDEX,e)}disposeInternal(){this.state_&&(this.state_.layer=null,this.state_=null),super.disposeInternal()}}const GroupEventType={ADDLAYER:"addlayer",REMOVELAYER:"removelayer"};class GroupEvent extends BaseEvent{constructor(e,t){super(e),this.layer=t}}const Property$3={LAYERS:"layers"};class LayerGroup extends BaseLayer{constructor(e){e=e||{};const t=Object.assign({},e);delete t.layers;let r=e.layers;super(t),this.on,this.once,this.un,this.layersListenerKeys_=[],this.listenerKeys_={},this.addChangeListener(Property$3.LAYERS,this.handleLayersChanged_),r?Array.isArray(r)?r=new Collection(r.slice(),{unique:!0}):assert$1("function"==typeof r.getArray,"Expected `layers` to be an array or a `Collection`"):r=new Collection(void 0,{unique:!0}),this.setLayers(r)}handleLayerChange_(){this.changed()}handleLayersChanged_(){this.layersListenerKeys_.forEach(unlistenByKey),this.layersListenerKeys_.length=0;const e=this.getLayers();this.layersListenerKeys_.push(listen(e,CollectionEventType.ADD,this.handleLayersAdd_,this),listen(e,CollectionEventType.REMOVE,this.handleLayersRemove_,this));for(const r in this.listenerKeys_)this.listenerKeys_[r].forEach(unlistenByKey);clear(this.listenerKeys_);const t=e.getArray();for(let r=0,n=t.length;r{this.dispatchEvent("sourceready")},0))),this.changed()}getFeatures(e){return this.renderer_?this.renderer_.getFeatures(e):Promise.resolve([])}getData(e){return this.renderer_&&this.rendered?this.renderer_.getData(e):null}isVisible(e){let t;const r=this.getMapInternal();let n;if(!e&&r&&(e=r.getView()),t=e instanceof View?{viewState:e.getState(),extent:e.calculateExtent()}:e,!t.layerStatesArray&&r&&(t.layerStatesArray=r.getLayerGroup().getLayerStatesArray()),t.layerStatesArray){if(n=t.layerStatesArray.find(e=>e.layer===this),!n)return!1}else n=this.getLayerState();const i=this.getExtent();return inView(n,t.viewState)&&(!i||intersects$1(i,t.extent))}getAttributions(e){if(!this.isVisible(e))return[];const t=this.getSource()?.getAttributions();if(!t)return[];let r=t(e instanceof View?e.getViewStateAndExtent():e);return Array.isArray(r)||(r=[r]),r}render(e,t){const r=this.getRenderer();return r.prepareFrame(e)?(this.rendered=!0,r.renderFrame(e,t)):null}unrender(){this.rendered=!1}getDeclutter(){}renderDeclutter(e,t){}renderDeferred(e){const t=this.getRenderer();t&&t.renderDeferred(e)}setMapInternal(e){e||this.unrender(),this.set(LayerProperty.MAP,e)}getMapInternal(){return this.get(LayerProperty.MAP)}setMap(e){this.mapPrecomposeKey_&&(unlistenByKey(this.mapPrecomposeKey_),this.mapPrecomposeKey_=null),e||this.changed(),this.mapRenderKey_&&(unlistenByKey(this.mapRenderKey_),this.mapRenderKey_=null),e&&(this.mapPrecomposeKey_=listen(e,EventType.PRECOMPOSE,this.handlePrecompose_,this),this.mapRenderKey_=listen(this,EventType$1.CHANGE,e.render,e),this.changed())}handlePrecompose_(e){const t=e.frameState.layerStatesArray,r=this.getLayerState(!1);assert$1(!t.some(e=>e.layer===r.layer),"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both."),t.push(r)}setSource(e){this.set(LayerProperty.SOURCE,e)}getRenderer(){return this.renderer_||(this.renderer_=this.createRenderer()),this.renderer_}hasRenderer(){return!!this.renderer_}createRenderer(){return null}clearRenderer(){this.renderer_&&(this.renderer_.dispose(),delete this.renderer_)}disposeInternal(){this.clearRenderer(),this.setSource(null),super.disposeInternal()}}function inView(e,t){if(!e.visible)return!1;const r=t.resolution;if(r=e.maxResolution)return!1;const n=t.zoom;return n>e.minZoom&&n<=e.maxZoom}function quickselect(e,t,r=0,n=e.length-1,i=defaultCompare){for(;n>r;){if(n-r>600){const o=n-r+1,s=t-r+1,a=Math.log(o),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(o-l)/o)*(s-o/2<0?-1:1);quickselect(e,t,Math.max(r,Math.floor(t-s*l/o+c)),Math.min(n,Math.floor(t+(o-s)*l/o+c)),i)}const o=e[t];let s=r,a=n;for(swap(e,r,t),i(e[n],o)>0&&swap(e,r,n);s0;)a--}0===i(e[r],o)?swap(e,r,a):(a++,swap(e,a,n)),a<=t&&(r=a+1),t<=a&&(n=a-1)}}function swap(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function defaultCompare(e,t){return et?1:0}let RBush$1=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!intersects(e,t))return r;const n=this.toBBox,i=[];for(;t;){for(let o=0;o=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(n,i,t)}_split(e,t){const r=e[t],n=r.children.length,i=this._minEntries;this._chooseSplitAxis(r,i,n);const o=this._chooseSplitIndex(r,i,n),s=createNode(r.children.splice(o,r.children.length-o));s.height=r.height,s.leaf=r.leaf,calcBBox(r,this.toBBox),calcBBox(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(r,s)}_splitRoot(e,t){this.data=createNode([e,t]),this.data.height=e.height+1,this.data.leaf=!1,calcBBox(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let n,i=1/0,o=1/0;for(let s=t;s<=r-t;s++){const t=distBBox(e,0,s,this.toBBox),a=distBBox(e,s,r,this.toBBox),l=intersectionArea(t,a),c=bboxArea(t)+bboxArea(a);l=t;l--){const t=e.children[l];extend(s,e.leaf?i(t):t),a+=bboxMargin(s)}return a}_adjustParentBBoxes(e,t,r){for(let n=r;n>=0;n--)extend(t[n],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():calcBBox(e[r],this.toBBox)}};function findItem(e,t,r){if(!r)return t.indexOf(e);for(let n=0;n=e.minX&&t.maxY>=e.minY}function createNode(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function multiSelect(e,t,r,n,i){const o=[t,r];for(;o.length;){if((r=o.pop())-(t=o.pop())<=n)continue;const s=t+Math.ceil((r-t)/n/2)*n;quickselect(e,s,t,r,i),o.push(t,s,s,r)}}const NO_COLOR=[NaN,NaN,NaN,0];let colorParseContext;function getColorParseContext(){return colorParseContext||(colorParseContext=createCanvasContext2D(1,1,void 0,{willReadFrequently:!0,desynchronized:!0})),colorParseContext}const rgbModernRegEx=/^rgba?\(\s*(\d+%?)\s+(\d+%?)\s+(\d+%?)(?:\s*\/\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,rgbLegacyAbsoluteRegEx=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,rgbLegacyPercentageRegEx=/^rgba?\(\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(\d+%)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i,hexRegEx=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i;function toColorComponent(e,t){return e.endsWith("%")?Number(e.substring(0,e.length-1))/t:Number(e)}function throwInvalidColor(e){throw new Error('failed to parse "'+e+'" as color')}function parseRgba(e){if(e.toLowerCase().startsWith("rgb")){const t=e.match(rgbLegacyAbsoluteRegEx)||e.match(rgbModernRegEx)||e.match(rgbLegacyPercentageRegEx);if(t){const e=t[4],r=100/255;return[clamp$1(toColorComponent(t[1],r)+.5|0,0,255),clamp$1(toColorComponent(t[2],r)+.5|0,0,255),clamp$1(toColorComponent(t[3],r)+.5|0,0,255),void 0!==e?clamp$1(toColorComponent(e,100),0,1):1]}throwInvalidColor(e)}if(e.startsWith("#")){if(hexRegEx.test(e)){const t=e.substring(1),r=t.length<=4?1:2,n=[0,0,0,255];for(let e=0,i=t.length;e.0031308?269.025*Math.pow(e,1/2.4)-14.025:3294.6*e}function b2(e){return e>.2068965?Math.pow(e,3):108/841*(e-4/29)}function a1(e){return e>10.314724?Math.pow((e+14.025)/269.025,2.4):e/3294.6}function a2(e){return e>.0088564?Math.pow(e,1/3):e/(108/841)+4/29}function rgbaToLcha(e){const t=a1(e[0]),r=a1(e[1]),n=a1(e[2]),i=a2(.222488403*t+.716873169*r+.06060791*n),o=500*(a2(.452247074*t+.399439023*r+.148375274*n)-i),s=200*(i-a2(.016863605*t+.117638439*r+.865350722*n)),a=Math.atan2(s,o)*(180/Math.PI);return[116*i-16,Math.sqrt(o*o+s*s),a<0?a+360:a,e[3]]}function lchaToRgba(e){const t=(e[0]+16)/116,r=e[1],n=e[2]*Math.PI/180,i=b2(t),o=b2(t+r/500*Math.cos(n)),s=b2(t-r/200*Math.sin(n)),a=b1(3.021973625*o-1.617392459*i-.404875592*s),l=b1(-.943766287*o+1.916279586*i+.027607165*s),c=b1(.069407491*o-.22898585*i+1.159737864*s);return[clamp$1(a+.5|0,0,255),clamp$1(l+.5|0,0,255),clamp$1(c+.5|0,0,255),e[3]]}function fromString(e){if("none"===e)return NO_COLOR;if(cache.hasOwnProperty(e))return cache[e];if(cacheSize>=MAX_CACHE_SIZE){let e=0;for(const t in cache)3&e++||(delete cache[t],--cacheSize)}const t=parseRgba(e);4!==t.length&&throwInvalidColor(e);for(const r of t)isNaN(r)&&throwInvalidColor(e);return cache[e]=t,++cacheSize,t}function asArray(e){return Array.isArray(e)?e:fromString(e)}function toString(e){let t=e[0];t!=(0|t)&&(t=t+.5|0);let r=e[1];r!=(0|r)&&(r=r+.5|0);let n=e[2];return n!=(0|n)&&(n=n+.5|0),"rgba("+t+","+r+","+n+","+(void 0===e[3]?1:Math.round(1e3*e[3])/1e3)+")"}function hasArea(e){return e[0]>0&&e[1]>0}function scale(e,t,r){return void 0===r&&(r=[0,0]),r[0]=e[0]*t+.5|0,r[1]=e[1]*t+.5|0,r}function toSize(e,t){return Array.isArray(e)?e:(void 0===t?t=[e,e]:(t[0]=e,t[1]=e),t)}let numTypes=0;const BooleanType$1=1<",GreaterThanOrEqualTo:">=",LessThan:"<",LessThanOrEqualTo:"<=",Multiply:"*",Divide:"/",Add:"+",Subtract:"-",Clamp:"clamp",Mod:"%",Pow:"^",Abs:"abs",Floor:"floor",Ceil:"ceil",Round:"round",Sin:"sin",Cos:"cos",Atan:"atan",Sqrt:"sqrt",Match:"match",Between:"between",Interpolate:"interpolate",Coalesce:"coalesce",Case:"case",In:"in",Number:"number",String:"string",Array:"array",Color:"color",Id:"id",Band:"band",Palette:"palette",ToString:"to-string",Has:"has"},parsers={[Ops.Get]:createCallExpressionParser(hasArgsCount(1,1/0),withGetArgs),[Ops.Var]:createCallExpressionParser(hasArgsCount(1,1),withVarArgs),[Ops.Has]:createCallExpressionParser(hasArgsCount(1,1/0),withGetArgs),[Ops.Id]:createCallExpressionParser(usesFeatureId,withNoArgs),[Ops.Concat]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(StringType$1)),[Ops.GeometryType]:createCallExpressionParser(usesGeometryType,withNoArgs),[Ops.LineMetric]:createCallExpressionParser(withNoArgs),[Ops.Resolution]:createCallExpressionParser(usesMapState,withNoArgs),[Ops.Zoom]:createCallExpressionParser(usesMapState,withNoArgs),[Ops.Time]:createCallExpressionParser(usesMapState,withNoArgs),[Ops.Any]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(BooleanType$1)),[Ops.All]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(BooleanType$1)),[Ops.Not]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(BooleanType$1)),[Ops.Equal]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(AnyType)),[Ops.NotEqual]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(AnyType)),[Ops.GreaterThan]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.GreaterThanOrEqualTo]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.LessThan]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.LessThanOrEqualTo]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Multiply]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfReturnType),[Ops.Coalesce]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfReturnType),[Ops.Divide]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Add]:createCallExpressionParser(hasArgsCount(2,1/0),withArgsOfType(NumberType$1)),[Ops.Subtract]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Clamp]:createCallExpressionParser(hasArgsCount(3,3),withArgsOfType(NumberType$1)),[Ops.Mod]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Pow]:createCallExpressionParser(hasArgsCount(2,2),withArgsOfType(NumberType$1)),[Ops.Abs]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Floor]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Ceil]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Round]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Sin]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Cos]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Atan]:createCallExpressionParser(hasArgsCount(1,2),withArgsOfType(NumberType$1)),[Ops.Sqrt]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(NumberType$1)),[Ops.Match]:createCallExpressionParser(hasArgsCount(4,1/0),hasEvenArgs,withMatchArgs),[Ops.Between]:createCallExpressionParser(hasArgsCount(3,3),withArgsOfType(NumberType$1)),[Ops.Interpolate]:createCallExpressionParser(hasArgsCount(6,1/0),hasEvenArgs,withInterpolateArgs),[Ops.Case]:createCallExpressionParser(hasArgsCount(3,1/0),hasOddArgs,withCaseArgs),[Ops.In]:createCallExpressionParser(hasArgsCount(2,2),withInArgs),[Ops.Number]:createCallExpressionParser(hasArgsCount(1,1/0),withArgsOfType(AnyType)),[Ops.String]:createCallExpressionParser(hasArgsCount(1,1/0),withArgsOfType(AnyType)),[Ops.Array]:createCallExpressionParser(hasArgsCount(1,1/0),withArgsOfType(NumberType$1)),[Ops.Color]:createCallExpressionParser(hasArgsCount(1,4),withArgsOfType(NumberType$1)),[Ops.Band]:createCallExpressionParser(hasArgsCount(1,3),withArgsOfType(NumberType$1)),[Ops.Palette]:createCallExpressionParser(hasArgsCount(2,2),withPaletteArgs),[Ops.ToString]:createCallExpressionParser(hasArgsCount(1,1),withArgsOfType(BooleanType$1|NumberType$1|StringType$1|ColorType$1))};function withGetArgs(e,t,r){const n=e.length-1,i=new Array(n);for(let o=0;ot)throw new Error(`expected ${t===1/0?`${e} or more`:`${e} to ${t}`} arguments for ${n}, got ${i}`)}}function withArgsOfReturnType(e,t,r){const n=e.length-1,i=new Array(n);for(let o=0;oe.featureId;case Ops.GeometryType:return e=>e.geometryType;case Ops.Concat:{const t=e.args.map(e=>compileExpression(e));return e=>"".concat(...t.map(t=>t(e).toString()))}case Ops.Resolution:return e=>e.resolution;case Ops.Any:case Ops.All:case Ops.Between:case Ops.In:case Ops.Not:return compileLogicalExpression(e);case Ops.Equal:case Ops.NotEqual:case Ops.LessThan:case Ops.LessThanOrEqualTo:case Ops.GreaterThan:case Ops.GreaterThanOrEqualTo:return compileComparisonExpression(e);case Ops.Multiply:case Ops.Divide:case Ops.Add:case Ops.Subtract:case Ops.Clamp:case Ops.Mod:case Ops.Pow:case Ops.Abs:case Ops.Floor:case Ops.Ceil:case Ops.Round:case Ops.Sin:case Ops.Cos:case Ops.Atan:case Ops.Sqrt:return compileNumericExpression(e);case Ops.Case:return compileCaseExpression(e);case Ops.Match:return compileMatchExpression(e);case Ops.Interpolate:return compileInterpolateExpression(e);case Ops.ToString:return compileConvertExpression(e);default:throw new Error(`Unsupported operator ${t}`)}}function compileAssertionExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{for(let t=0;t{for(let i=0;i{const n=e.args;let i=r.properties[t];for(let e=1,t=n.length;ee.variables[t];case Ops.Has:return r=>{const n=e.args;if(!(t in r.properties))return!1;let i=r.properties[t];for(let e=1,t=n.length;er(e)===n(e);case Ops.NotEqual:return e=>r(e)!==n(e);case Ops.LessThan:return e=>r(e)r(e)<=n(e);case Ops.GreaterThan:return e=>r(e)>n(e);case Ops.GreaterThanOrEqualTo:return e=>r(e)>=n(e);default:throw new Error(`Unsupported comparison operator ${t}`)}}function compileLogicalExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{for(let t=0;t{for(let t=0;t{const t=n[0](e),r=n[1](e),i=n[2](e);return t>=r&&t<=i};case Ops.In:return e=>{const t=n[0](e);for(let i=1;i!n[0](e);default:throw new Error(`Unsupported logical operator ${t}`)}}function compileNumericExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{let t=1;for(let i=0;in[0](e)/n[1](e);case Ops.Add:return e=>{let t=0;for(let i=0;in[0](e)-n[1](e);case Ops.Clamp:return e=>{const t=n[0](e),r=n[1](e);if(ti?i:t};case Ops.Mod:return e=>n[0](e)%n[1](e);case Ops.Pow:return e=>Math.pow(n[0](e),n[1](e));case Ops.Abs:return e=>Math.abs(n[0](e));case Ops.Floor:return e=>Math.floor(n[0](e));case Ops.Ceil:return e=>Math.ceil(n[0](e));case Ops.Round:return e=>Math.round(n[0](e));case Ops.Sin:return e=>Math.sin(n[0](e));case Ops.Cos:return e=>Math.cos(n[0](e));case Ops.Atan:return 2===r?e=>Math.atan2(n[0](e),n[1](e)):e=>Math.atan(n[0](e));case Ops.Sqrt:return e=>Math.sqrt(n[0](e));default:throw new Error(`Unsupported numeric operator ${t}`)}}function compileCaseExpression(e){const t=e.args.length,r=new Array(t);for(let n=0;n{for(let n=0;n{const n=r[0](e);for(let i=1;i{const n=r[0](e),i=r[1](e);let o,s;for(let a=2;a=i)return 2===a?l:c?interpolateColor(n,i,o,s,t,l):interpolateNumber$1(n,i,o,s,t,l);o=t,s=l}return s}}function compileConvertExpression(e){const t=e.operator,r=e.args.length,n=new Array(r);for(let i=0;i{const r=n[0](t);return e.args[0].type===ColorType$1?toString(r):r.toString()};throw new Error(`Unsupported convert operator ${t}`)}function interpolateNumber$1(e,t,r,n,i,o){const s=i-r;if(0===s)return n;const a=t-r;return n+(1===e?a/s:(Math.pow(e,a)-1)/(Math.pow(e,s)-1))*(o-n)}function interpolateColor(e,t,r,n,i,o){if(0===i-r)return n;const s=rgbaToLcha(n),a=rgbaToLcha(o);let l=a[2]-s[2];return l>180?l-=360:l<-180&&(l+=360),lchaToRgba([interpolateNumber$1(e,t,r,s[0],i,a[0]),interpolateNumber$1(e,t,r,s[1],i,a[1]),s[2]+interpolateNumber$1(e,t,r,0,i,l),interpolateNumber$1(e,t,r,n[3],i,o[3])])}const ImageState={IDLE:0,LOADING:1,LOADED:2,ERROR:3,EMPTY:4};class ImageWrapper extends Target{constructor(e,t,r,n){super(),this.extent=e,this.pixelRatio_=r,this.resolution=t,this.state="function"==typeof n?ImageState.IDLE:n,this.image_=null,this.loader="function"==typeof n?n:null}changed(){this.dispatchEvent(EventType$1.CHANGE)}getExtent(){return this.extent}getImage(){return this.image_}getPixelRatio(){return this.pixelRatio_}getResolution(){return this.resolution}getState(){return this.state}load(){if(this.state==ImageState.IDLE&&this.loader){this.state=ImageState.LOADING,this.changed();const e=this.getResolution(),t=Array.isArray(e)?e[0]:e;toPromise(()=>this.loader(this.getExtent(),t,this.getPixelRatio())).then(e=>{"image"in e&&(this.image_=e.image),"extent"in e&&(this.extent=e.extent),"resolution"in e&&(this.resolution=e.resolution),"pixelRatio"in e&&(this.pixelRatio_=e.pixelRatio),(e instanceof HTMLImageElement||CREATE_IMAGE_BITMAP&&e instanceof ImageBitmap||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement)&&(this.image_=e),this.state=ImageState.LOADED}).catch(e=>{this.state=ImageState.ERROR,console.error(e)}).finally(()=>this.changed())}}setImage(e){this.image_=e}setResolution(e){this.resolution=e}}function listenImage(e,t,r){const n=e;let i=!0,o=!1,s=!1;const a=[listenOnce(n,EventType$1.LOAD,function(){s=!0,o||t()})];return n.src&&IMAGE_DECODE?(o=!0,n.decode().then(function(){i&&t()}).catch(function(){i&&(s?t():r())})):a.push(listenOnce(n,EventType$1.ERROR,r)),function(){i=!1,a.forEach(unlistenByKey)}}function load(e){return new Promise((t,r)=>{function n(){o(),t(e)}function i(){o(),r(new Error("Image load error"))}function o(){e.removeEventListener("load",n),e.removeEventListener("error",i)}e.addEventListener("load",n),e.addEventListener("error",i)})}function decodeFallback(e,t){return t&&(e.src=t),e.src&&IMAGE_DECODE?new Promise((t,r)=>e.decode().then(()=>t(e)).catch(n=>e.complete&&e.width?t(e):r(n))):load(e)}class IconImageCache{constructor(){this.cache_={},this.patternCache_={},this.cacheSize_=0,this.maxCacheSize_=1024}clear(){this.cache_={},this.patternCache_={},this.cacheSize_=0}canExpireCache(){return this.cacheSize_>this.maxCacheSize_}expire(){if(this.canExpireCache()){let e=0;for(const t in this.cache_){const r=this.cache_[t];3&e++||r.hasListener()||(delete this.cache_[t],delete this.patternCache_[t],--this.cacheSize_)}}}get(e,t,r){const n=getCacheKey$1(e,t,r);return n in this.cache_?this.cache_[n]:null}getPattern(e,t,r){const n=getCacheKey$1(e,t,r);return n in this.patternCache_?this.patternCache_[n]:null}set(e,t,r,n,i){const o=getCacheKey$1(e,t,r),s=o in this.cache_;this.cache_[o]=n,i&&(n.getImageState()===ImageState.IDLE&&n.load(),n.getImageState()===ImageState.LOADING?n.ready().then(()=>{this.patternCache_[o]=getSharedCanvasContext2D().createPattern(n.getImage(1),"repeat")}):this.patternCache_[o]=getSharedCanvasContext2D().createPattern(n.getImage(1),"repeat")),s||++this.cacheSize_}setSize(e){this.maxCacheSize_=e,this.expire()}}function getCacheKey$1(e,t,r){return t+":"+e+":"+(r?asArray(r):"null")}const shared=new IconImageCache;let taintedTestContext=null;class IconImage extends Target{constructor(e,t,r,n,i){super(),this.hitDetectionImage_=null,this.image_=e,this.crossOrigin_=r,this.canvas_={},this.color_=i,this.imageState_=void 0===n?ImageState.IDLE:n,this.size_=e&&e.width&&e.height?[e.width,e.height]:null,this.src_=t,this.tainted_,this.ready_=null}initializeImage_(){this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)}isTainted_(){if(void 0===this.tainted_&&this.imageState_===ImageState.LOADED){taintedTestContext||(taintedTestContext=createCanvasContext2D(1,1,void 0,{willReadFrequently:!0})),taintedTestContext.drawImage(this.image_,0,0);try{taintedTestContext.getImageData(0,0,1,1),this.tainted_=!1}catch{taintedTestContext=null,this.tainted_=!0}}return!0===this.tainted_}dispatchChangeEvent_(){this.dispatchEvent(EventType$1.CHANGE)}handleImageError_(){this.imageState_=ImageState.ERROR,this.dispatchChangeEvent_()}handleImageLoad_(){this.imageState_=ImageState.LOADED,this.size_=[this.image_.width,this.image_.height],this.dispatchChangeEvent_()}getImage(e){return this.image_||this.initializeImage_(),this.replaceColor_(e),this.canvas_[e]?this.canvas_[e]:this.image_}getPixelRatio(e){return this.replaceColor_(e),this.canvas_[e]?e:1}getImageState(){return this.imageState_}getHitDetectionImage(){if(this.image_||this.initializeImage_(),!this.hitDetectionImage_)if(this.isTainted_()){const e=this.size_[0],t=this.size_[1],r=createCanvasContext2D(e,t);r.fillRect(0,0,e,t),this.hitDetectionImage_=r.canvas}else this.hitDetectionImage_=this.image_;return this.hitDetectionImage_}getSize(){return this.size_}getSrc(){return this.src_}load(){if(this.imageState_===ImageState.IDLE){this.image_||this.initializeImage_(),this.imageState_=ImageState.LOADING;try{void 0!==this.src_&&(this.image_.src=this.src_)}catch{this.handleImageError_()}this.image_ instanceof HTMLImageElement&&decodeFallback(this.image_,this.src_).then(e=>{this.image_=e,this.handleImageLoad_()}).catch(this.handleImageError_.bind(this))}}replaceColor_(e){if(!this.color_||this.canvas_[e]||this.imageState_!==ImageState.LOADED)return;const t=this.image_,r=createCanvasContext2D(Math.ceil(t.width*e),Math.ceil(t.height*e)),n=r.canvas;r.scale(e,e),r.drawImage(t,0,0),r.globalCompositeOperation="multiply",r.fillStyle=asString(this.color_),r.fillRect(0,0,n.width/e,n.height/e),r.globalCompositeOperation="destination-in",r.drawImage(t,0,0),this.canvas_[e]=n}ready(){return this.ready_||(this.ready_=new Promise(e=>{if(this.imageState_===ImageState.LOADED||this.imageState_===ImageState.ERROR)e();else{const t=()=>{this.imageState_!==ImageState.LOADED&&this.imageState_!==ImageState.ERROR||(this.removeEventListener(EventType$1.CHANGE,t),e())};this.addEventListener(EventType$1.CHANGE,t)}})),this.ready_}}function get$1(e,t,r,n,i,o){let s=void 0===t?void 0:shared.get(t,r,i);return s||(s=new IconImage(e,e&&"src"in e?e.src||void 0:t,r,n,i),shared.set(t,r,i,s,o)),o&&s&&!shared.getPattern(t,r,i)&&shared.set(t,r,i,s,o),s}function asColorLike(e){return e?Array.isArray(e)?toString(e):"object"==typeof e&&"src"in e?asCanvasPattern(e):e:null}function asCanvasPattern(e){if(!e.offset||!e.size)return shared.getPattern(e.src,"anonymous",e.color);const t=e.src+":"+e.offset,r=shared.getPattern(t,void 0,e.color);if(r)return r;const n=shared.get(e.src,"anonymous",null);if(n.getImageState()!==ImageState.LOADED)return null;const i=createCanvasContext2D(e.size[0],e.size[1]);return i.drawImage(n.getImage(1),e.offset[0],e.offset[1],e.size[0],e.size[1],0,0,e.size[0],e.size[1]),get$1(i.canvas,t,void 0,ImageState.LOADED,e.color,!0),shared.getPattern(t,void 0,e.color)}const defaultFont="10px sans-serif",defaultFillStyle="#000",defaultLineCap="round",defaultLineDash=[],defaultLineDashOffset=0,defaultLineJoin="round",defaultMiterLimit=10,defaultStrokeStyle="#000",defaultTextAlign="center",defaultTextBaseline="middle",defaultPadding=[0,0,0,0],defaultLineWidth=1,checkedFonts=new BaseObject;let measureContext$1=null,measureFont;const textHeights={},genericFontFamilies=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"]);function getFontKey(e,t,r){return`${e} ${t} 16px "${r}"`}const registerFont=function(){const e=100;let t,r;async function n(e){await r.ready;const t=await r.load(e);if(0===t.length)return!1;const n=getFontParameters(e),i=n.families[0].toLowerCase(),o=n.weight;return t.some(e=>{const t=e.family.replace(/^['"]|['"]$/g,"").toLowerCase(),r=fontWeights$1[e.weight]||e.weight;return t===i&&e.style===n.style&&r==o})}async function i(){await r.ready;let o=!0;const s=checkedFonts.getProperties(),a=Object.keys(s).filter(t=>s[t]=0;--t){const r=a[t];let i=s[r];iMath.max(t,measureTextWidth(e,r)),0);return r[t]=n,n}function getTextDimensions(e,t){const r=[],n=[],i=[];let o=0,s=0,a=0,l=0;for(let c=0,u=t.length;c<=u;c+=2){const h=t[c];if("\n"===h||c===u){o=Math.max(o,s),i.push(s),s=0,a+=l,l=0;continue}const d=t[c+1]||e.font,p=measureTextWidth(d,h);r.push(p),s+=p;const f=measureTextHeight(d);n.push(f),l=Math.max(l,f)}return{width:o,height:a,widths:r,heights:n,lineWidths:i}}function drawImageOrLabel(e,t,r,n,i,o,s,a,l,c,u){e.save(),1!==r&&(void 0===e.globalAlpha?e.globalAlpha=e=>e.globalAlpha*=r:e.globalAlpha*=r),t&&e.transform.apply(e,t),n.contextInstructions?(e.translate(l,c),e.scale(u[0],u[1]),executeLabelInstructions(n,e)):u[0]<0||u[1]<0?(e.translate(l,c),e.scale(u[0],u[1]),e.drawImage(n,i,o,s,a,0,0,s,a)):e.drawImage(n,i,o,s,a,l,c,s*u[0],a*u[1]),e.restore()}function executeLabelInstructions(e,t){const r=e.contextInstructions;for(let n=0,i=r.length;nthis.imageState_=ImageState.LOADED),this.render()}clone(){const e=this.getScale(),t=new RegularShape({fill:this.getFill()?this.getFill().clone():void 0,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),stroke:this.getStroke()?this.getStroke().clone():void 0,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(e)?e.slice():e,displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return t.setOpacity(this.getOpacity()),t}getAnchor(){const e=this.size_,t=this.getDisplacement(),r=this.getScaleArray();return[e[0]/2-t[0]/r[0],e[1]/2+t[1]/r[1]]}getAngle(){return this.angle_}getFill(){return this.fill_}setFill(e){this.fill_=e,this.render()}getHitDetectionImage(){return this.hitDetectionCanvas_||(this.hitDetectionCanvas_=this.createHitDetectionCanvas_(this.renderOptions_)),this.hitDetectionCanvas_}getImage(e){const t=this.fill_?.getKey(),r=`${e},${this.angle_},${this.radius},${this.radius2_},${this.points_},${t}`+Object.values(this.renderOptions_).join(",");let n=shared.get(r,null,null)?.getImage(1);if(!n){const t=this.renderOptions_,i=Math.ceil(t.size*e),o=createCanvasContext2D(i,i);this.draw_(t,o,e),n=o.canvas,shared.set(r,null,null,new IconImage(n,void 0,null,ImageState.LOADED,null))}return n}getPixelRatio(e){return e}getImageSize(){return this.size_}getImageState(){return this.imageState_}getOrigin(){return this.origin_}getPoints(){return this.points_}getRadius(){return this.radius}getRadius2(){return this.radius2_}getSize(){return this.size_}getStroke(){return this.stroke_}setStroke(e){this.stroke_=e,this.render()}listenImageChange(e){}load(){}unlistenImageChange(e){}calculateLineJoinSize_(e,t,r){if(0===t||this.points_===1/0||"bevel"!==e&&"miter"!==e)return t;let n=this.radius,i=void 0===this.radius2_?n:this.radius2_;if(n{this.patternImage_=null}),t.getImageState()===ImageState.IDLE&&t.load(),t.getImageState()===ImageState.LOADING&&(this.patternImage_=t)}this.color_=e}getKey(){const e=this.getColor();return e?e instanceof CanvasPattern||e instanceof CanvasGradient?getUid(e):"object"==typeof e&&"src"in e?e.src+":"+e.offset:asArray(e).toString():""}loading(){return!!this.patternImage_}ready(){return this.patternImage_?this.patternImage_.ready():Promise.resolve()}}function calculateScale(e,t,r,n){return void 0!==r&&void 0!==n?[r/e,n/t]:void 0!==r?r/e:void 0!==n?n/t:1}class Icon extends ImageStyle{constructor(e){const t=void 0!==(e=e||{}).opacity?e.opacity:1,r=void 0!==e.rotation?e.rotation:0,n=void 0!==e.scale?e.scale:1,i=void 0!==e.rotateWithView&&e.rotateWithView;super({opacity:t,rotation:r,scale:n,displacement:void 0!==e.displacement?e.displacement:[0,0],rotateWithView:i,declutterMode:e.declutterMode}),this.anchor_=void 0!==e.anchor?e.anchor:[.5,.5],this.normalizedAnchor_=null,this.anchorOrigin_=void 0!==e.anchorOrigin?e.anchorOrigin:"top-left",this.anchorXUnits_=void 0!==e.anchorXUnits?e.anchorXUnits:"fraction",this.anchorYUnits_=void 0!==e.anchorYUnits?e.anchorYUnits:"fraction",this.crossOrigin_=void 0!==e.crossOrigin?e.crossOrigin:null;const o=void 0!==e.img?e.img:null;let s,a=e.src;if(assert$1(!(void 0!==a&&o),"`image` and `src` cannot be provided at the same time"),void 0!==a&&0!==a.length||!o||(a=o.src||getUid(o)),assert$1(void 0!==a&&a.length>0,"A defined and non-empty `src` or `image` must be provided"),assert$1(!((void 0!==e.width||void 0!==e.height)&&void 0!==e.scale),"`width` or `height` cannot be provided together with `scale`"),void 0!==e.src?s=ImageState.IDLE:void 0!==o&&(s="complete"in o?o.complete?o.src?ImageState.LOADED:ImageState.IDLE:ImageState.LOADING:ImageState.LOADED),this.color_=void 0!==e.color?asArray(e.color):null,this.iconImage_=get$1(o,a,this.crossOrigin_,s,this.color_),this.offset_=void 0!==e.offset?e.offset:[0,0],this.offsetOrigin_=void 0!==e.offsetOrigin?e.offsetOrigin:"top-left",this.origin_=null,this.size_=void 0!==e.size?e.size:null,this.initialOptions_,void 0!==e.width||void 0!==e.height){let t,r;if(e.size)[t,r]=e.size;else{const n=this.getImage(1);if(n.width&&n.height)t=n.width,r=n.height;else if(n instanceof HTMLImageElement){this.initialOptions_=e;const t=()=>{if(this.unlistenImageChange(t),!this.initialOptions_)return;const r=this.iconImage_.getSize();this.setScale(calculateScale(r[0],r[1],e.width,e.height))};return void this.listenImageChange(t)}}void 0!==t&&this.setScale(calculateScale(t,r,e.width,e.height))}}clone(){let e,t,r;return this.initialOptions_?(t=this.initialOptions_.width,r=this.initialOptions_.height):(e=this.getScale(),e=Array.isArray(e)?e.slice():e),new Icon({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||void 0,crossOrigin:this.crossOrigin_,offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,opacity:this.getOpacity(),rotateWithView:this.getRotateWithView(),rotation:this.getRotation(),scale:e,width:t,height:r,size:null!==this.size_?this.size_.slice():void 0,src:this.getSrc(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getAnchor(){let e=this.normalizedAnchor_;if(!e){e=this.anchor_;const t=this.getSize();if("fraction"==this.anchorXUnits_||"fraction"==this.anchorYUnits_){if(!t)return null;e=this.anchor_.slice(),"fraction"==this.anchorXUnits_&&(e[0]*=t[0]),"fraction"==this.anchorYUnits_&&(e[1]*=t[1])}if("top-left"!=this.anchorOrigin_){if(!t)return null;e===this.anchor_&&(e=this.anchor_.slice()),"top-right"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(e[0]=-e[0]+t[0]),"bottom-left"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(e[1]=-e[1]+t[1])}this.normalizedAnchor_=e}const t=this.getDisplacement(),r=this.getScaleArray();return[e[0]-t[0]/r[0],e[1]+t[1]/r[1]]}setAnchor(e){this.anchor_=e,this.normalizedAnchor_=null}getColor(){return this.color_}getImage(e){return this.iconImage_.getImage(e)}getPixelRatio(e){return this.iconImage_.getPixelRatio(e)}getImageSize(){return this.iconImage_.getSize()}getImageState(){return this.iconImage_.getImageState()}getHitDetectionImage(){return this.iconImage_.getHitDetectionImage()}getOrigin(){if(this.origin_)return this.origin_;let e=this.offset_;if("top-left"!=this.offsetOrigin_){const t=this.getSize(),r=this.iconImage_.getSize();if(!t||!r)return null;e=e.slice(),"top-right"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(e[0]=r[0]-t[0]-e[0]),"bottom-left"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(e[1]=r[1]-t[1]-e[1])}return this.origin_=e,this.origin_}getSrc(){return this.iconImage_.getSrc()}setSrc(e){this.iconImage_=get$1(null,e,this.crossOrigin_,ImageState.IDLE,this.color_)}getSize(){return this.size_?this.size_:this.iconImage_.getSize()}getWidth(){const e=this.getScaleArray();return this.size_?this.size_[0]*e[0]:this.iconImage_.getImageState()==ImageState.LOADED?this.iconImage_.getSize()[0]*e[0]:void 0}getHeight(){const e=this.getScaleArray();return this.size_?this.size_[1]*e[1]:this.iconImage_.getImageState()==ImageState.LOADED?this.iconImage_.getSize()[1]*e[1]:void 0}setScale(e){delete this.initialOptions_,super.setScale(e)}listenImageChange(e){this.iconImage_.addEventListener(EventType$1.CHANGE,e)}load(){this.iconImage_.load()}unlistenImageChange(e){this.iconImage_.removeEventListener(EventType$1.CHANGE,e)}ready(){return this.iconImage_.ready()}}class Stroke{constructor(e){e=e||{},this.color_=void 0!==e.color?e.color:null,this.lineCap_=e.lineCap,this.lineDash_=void 0!==e.lineDash?e.lineDash:null,this.lineDashOffset_=e.lineDashOffset,this.lineJoin_=e.lineJoin,this.miterLimit_=e.miterLimit,this.width_=e.width}clone(){const e=this.getColor();return new Stroke({color:Array.isArray(e)?e.slice():e||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(e){this.color_=e}setLineCap(e){this.lineCap_=e}setLineDash(e){this.lineDash_=e}setLineDashOffset(e){this.lineDashOffset_=e}setLineJoin(e){this.lineJoin_=e}setMiterLimit(e){this.miterLimit_=e}setWidth(e){this.width_=e}}class Style{constructor(e){e=e||{},this.geometry_=null,this.geometryFunction_=defaultGeometryFunction,void 0!==e.geometry&&this.setGeometry(e.geometry),this.fill_=void 0!==e.fill?e.fill:null,this.image_=void 0!==e.image?e.image:null,this.renderer_=void 0!==e.renderer?e.renderer:null,this.hitDetectionRenderer_=void 0!==e.hitDetectionRenderer?e.hitDetectionRenderer:null,this.stroke_=void 0!==e.stroke?e.stroke:null,this.text_=void 0!==e.text?e.text:null,this.zIndex_=e.zIndex}clone(){let e=this.getGeometry();return e&&"object"==typeof e&&(e=e.clone()),new Style({geometry:e??void 0,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer()??void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(e){this.renderer_=e}setHitDetectionRenderer(e){this.hitDetectionRenderer_=e}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(e){this.fill_=e}getImage(){return this.image_}setImage(e){this.image_=e}getStroke(){return this.stroke_}setStroke(e){this.stroke_=e}getText(){return this.text_}setText(e){this.text_=e}getZIndex(){return this.zIndex_}setGeometry(e){"function"==typeof e?this.geometryFunction_=e:"string"==typeof e?this.geometryFunction_=function(t){return t.get(e)}:e?void 0!==e&&(this.geometryFunction_=function(){return e}):this.geometryFunction_=defaultGeometryFunction,this.geometry_=e}setZIndex(e){this.zIndex_=e}}function toFunction(e){let t;if("function"==typeof e)t=e;else{let r;Array.isArray(e)?r=e:(assert$1("function"==typeof e.getZIndex,"Expected an `Style` or an array of `Style`"),r=[e]),t=function(){return r}}return t}let defaultStyles=null;function createDefaultStyle(){if(!defaultStyles){const e=new Fill({color:"rgba(255,255,255,0.4)"}),t=new Stroke({color:"#3399CC",width:1.25});defaultStyles=[new Style({image:new CircleStyle({fill:e,stroke:t,radius:5}),fill:e,stroke:t})]}return defaultStyles}function defaultGeometryFunction(e){return e.getGeometry()}const DEFAULT_FILL_COLOR="#333";let Text$1=class e{constructor(e){e=e||{},this.font_=e.font,this.rotation_=e.rotation,this.rotateWithView_=e.rotateWithView,this.keepUpright_=e.keepUpright,this.scale_=e.scale,this.scaleArray_=toSize(void 0!==e.scale?e.scale:1),this.text_=e.text,this.textAlign_=e.textAlign,this.justify_=e.justify,this.repeat_=e.repeat,this.textBaseline_=e.textBaseline,this.fill_=void 0!==e.fill?e.fill:new Fill({color:DEFAULT_FILL_COLOR}),this.maxAngle_=void 0!==e.maxAngle?e.maxAngle:Math.PI/4,this.placement_=void 0!==e.placement?e.placement:"point",this.overflow_=!!e.overflow,this.stroke_=void 0!==e.stroke?e.stroke:null,this.offsetX_=void 0!==e.offsetX?e.offsetX:0,this.offsetY_=void 0!==e.offsetY?e.offsetY:0,this.backgroundFill_=e.backgroundFill?e.backgroundFill:null,this.backgroundStroke_=e.backgroundStroke?e.backgroundStroke:null,this.padding_=void 0===e.padding?null:e.padding,this.declutterMode_=e.declutterMode}clone(){const t=this.getScale();return new e({font:this.getFont(),placement:this.getPlacement(),repeat:this.getRepeat(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),keepUpright:this.getKeepUpright(),scale:Array.isArray(t)?t.slice():t,text:this.getText(),textAlign:this.getTextAlign(),justify:this.getJustify(),textBaseline:this.getTextBaseline(),fill:this.getFill()instanceof Fill?this.getFill().clone():this.getFill(),stroke:this.getStroke()?this.getStroke().clone():void 0,offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),backgroundFill:this.getBackgroundFill()?this.getBackgroundFill().clone():void 0,backgroundStroke:this.getBackgroundStroke()?this.getBackgroundStroke().clone():void 0,padding:this.getPadding()||void 0,declutterMode:this.getDeclutterMode()})}getOverflow(){return this.overflow_}getFont(){return this.font_}getMaxAngle(){return this.maxAngle_}getPlacement(){return this.placement_}getRepeat(){return this.repeat_}getOffsetX(){return this.offsetX_}getOffsetY(){return this.offsetY_}getFill(){return this.fill_}getRotateWithView(){return this.rotateWithView_}getKeepUpright(){return this.keepUpright_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getStroke(){return this.stroke_}getText(){return this.text_}getTextAlign(){return this.textAlign_}getJustify(){return this.justify_}getTextBaseline(){return this.textBaseline_}getBackgroundFill(){return this.backgroundFill_}getBackgroundStroke(){return this.backgroundStroke_}getPadding(){return this.padding_}getDeclutterMode(){return this.declutterMode_}setOverflow(e){this.overflow_=e}setFont(e){this.font_=e}setMaxAngle(e){this.maxAngle_=e}setOffsetX(e){this.offsetX_=e}setOffsetY(e){this.offsetY_=e}setPlacement(e){this.placement_=e}setRepeat(e){this.repeat_=e}setRotateWithView(e){this.rotateWithView_=e}setKeepUpright(e){this.keepUpright_=e}setFill(e){this.fill_=e}setRotation(e){this.rotation_=e}setScale(e){this.scale_=e,this.scaleArray_=toSize(void 0!==e?e:1)}setStroke(e){this.stroke_=e}setText(e){this.text_=e}setTextAlign(e){this.textAlign_=e}setJustify(e){this.justify_=e}setTextBaseline(e){this.textBaseline_=e}setBackgroundFill(e){this.backgroundFill_=e}setBackgroundStroke(e){this.backgroundStroke_=e}setPadding(e){this.padding_=e}};function always(){return!0}function rulesToStyleFunction(e){const t=newParsingContext(),r=buildRuleSet(e,t),n=newEvaluationContext();return function(e,i){if(n.properties=e.getPropertiesInternal(),n.resolution=i,t.featureId){const t=e.getId();n.featureId=void 0!==t?t:null}return t.geometryType&&(n.geometryType=computeGeometryType(e.getGeometry())),r(n)}}function flatStylesToStyleFunction(e){const t=newParsingContext(),r=e.length,n=new Array(r);for(let s=0;snull;n=colorLikeEvaluator(e,t+"fill-color",r)}if(!n)return null;const i=new Fill;return function(e){const t=n(e);return t===NO_COLOR?null:(i.setColor(t),i)}}function buildStroke(e,t,r){const n=numberEvaluator(e,t+"stroke-width",r),i=colorLikeEvaluator(e,t+"stroke-color",r);if(!n&&!i)return null;const o=stringEvaluator(e,t+"stroke-line-cap",r),s=stringEvaluator(e,t+"stroke-line-join",r),a=numberArrayEvaluator(e,t+"stroke-line-dash",r),l=numberEvaluator(e,t+"stroke-line-dash-offset",r),c=numberEvaluator(e,t+"stroke-miter-limit",r),u=new Stroke;return function(e){if(i){const t=i(e);if(t===NO_COLOR)return null;u.setColor(t)}if(n&&u.setWidth(n(e)),o){const t=o(e);if("butt"!==t&&"round"!==t&&"square"!==t)throw new Error("Expected butt, round, or square line cap");u.setLineCap(t)}if(s){const t=s(e);if("bevel"!==t&&"round"!==t&&"miter"!==t)throw new Error("Expected bevel, round, or miter line join");u.setLineJoin(t)}return a&&u.setLineDash(a(e)),l&&u.setLineDashOffset(l(e)),c&&u.setMiterLimit(c(e)),u}}function buildText(e,t){const r="text-",n=stringEvaluator(e,r+"value",t);if(!n)return null;const i=buildFill(e,r,t),o=buildFill(e,r+"background-",t),s=buildStroke(e,r,t),a=buildStroke(e,r+"background-",t),l=stringEvaluator(e,r+"font",t),c=numberEvaluator(e,r+"max-angle",t),u=numberEvaluator(e,r+"offset-x",t),h=numberEvaluator(e,r+"offset-y",t),d=booleanEvaluator(e,r+"overflow",t),p=stringEvaluator(e,r+"placement",t),f=numberEvaluator(e,r+"repeat",t),g=sizeLikeEvaluator(e,r+"scale",t),m=booleanEvaluator(e,r+"rotate-with-view",t),y=numberEvaluator(e,r+"rotation",t),b=stringEvaluator(e,r+"align",t),v=stringEvaluator(e,r+"justify",t),_=stringEvaluator(e,r+"baseline",t),E=booleanEvaluator(e,r+"keep-upright",t),w=numberArrayEvaluator(e,r+"padding",t),C=optionalDeclutterMode(e,r+"declutter-mode"),S=new Text$1({declutterMode:C});return function(e){if(S.setText(n(e)),i&&S.setFill(i(e)),o&&S.setBackgroundFill(o(e)),s&&S.setStroke(s(e)),a&&S.setBackgroundStroke(a(e)),l&&S.setFont(l(e)),c&&S.setMaxAngle(c(e)),u&&S.setOffsetX(u(e)),h&&S.setOffsetY(h(e)),d&&S.setOverflow(d(e)),p){const t=p(e);if("point"!==t&&"line"!==t)throw new Error("Expected point or line for text-placement");S.setPlacement(t)}if(f&&S.setRepeat(f(e)),g&&S.setScale(g(e)),m&&S.setRotateWithView(m(e)),y&&S.setRotation(y(e)),b){const t=b(e);if("left"!==t&&"center"!==t&&"right"!==t&&"end"!==t&&"start"!==t)throw new Error("Expected left, right, center, start, or end for text-align");S.setTextAlign(t)}if(v){const t=v(e);if("left"!==t&&"right"!==t&&"center"!==t)throw new Error("Expected left, right, or center for text-justify");S.setJustify(t)}if(_){const t=_(e);if("bottom"!==t&&"top"!==t&&"middle"!==t&&"alphabetic"!==t&&"hanging"!==t)throw new Error("Expected bottom, top, middle, alphabetic, or hanging for text-baseline");S.setTextBaseline(t)}return w&&S.setPadding(w(e)),E&&S.setKeepUpright(E(e)),S}}function buildImage(e,t){return"icon-src"in e?buildIcon(e,t):"shape-points"in e?buildShape(e,t):"circle-radius"in e?buildCircle(e,t):null}function buildIcon(e,t){const r="icon-",n=r+"src",i=requireString(e[n],n),o=coordinateEvaluator(e,r+"anchor",t),s=sizeLikeEvaluator(e,r+"scale",t),a=numberEvaluator(e,r+"opacity",t),l=coordinateEvaluator(e,r+"displacement",t),c=numberEvaluator(e,r+"rotation",t),u=booleanEvaluator(e,r+"rotate-with-view",t),h=optionalIconOrigin(e,r+"anchor-origin"),d=optionalIconAnchorUnits(e,r+"anchor-x-units"),p=optionalIconAnchorUnits(e,r+"anchor-y-units"),f=optionalColorLike(e,r+"color"),g=optionalString(e,r+"cross-origin"),m=optionalNumberArray(e,r+"offset"),y=optionalIconOrigin(e,r+"offset-origin"),b=optionalNumber(e,r+"width"),v=optionalNumber(e,r+"height"),_=optionalSize(e,r+"size"),E=optionalDeclutterMode(e,r+"declutter-mode"),w=new Icon({src:i,anchorOrigin:h,anchorXUnits:d,anchorYUnits:p,color:f,crossOrigin:g,offset:m,offsetOrigin:y,height:v,width:b,size:_,declutterMode:E});return function(e){return a&&w.setOpacity(a(e)),l&&w.setDisplacement(l(e)),c&&w.setRotation(c(e)),u&&w.setRotateWithView(u(e)),s&&w.setScale(s(e)),o&&w.setAnchor(o(e)),w}}function buildShape(e,t){const r="shape-",n=r+"points",i=r+"radius",o=requireNumber(e[n],n),s=requireNumber(e[i],i),a=buildFill(e,r,t),l=buildStroke(e,r,t),c=sizeLikeEvaluator(e,r+"scale",t),u=coordinateEvaluator(e,r+"displacement",t),h=numberEvaluator(e,r+"rotation",t),d=booleanEvaluator(e,r+"rotate-with-view",t),p=optionalNumber(e,r+"radius2"),f=optionalNumber(e,r+"angle"),g=optionalDeclutterMode(e,r+"declutter-mode"),m=new RegularShape({points:o,radius:s,radius2:p,angle:f,declutterMode:g});return function(e){return a&&m.setFill(a(e)),l&&m.setStroke(l(e)),u&&m.setDisplacement(u(e)),h&&m.setRotation(h(e)),d&&m.setRotateWithView(d(e)),c&&m.setScale(c(e)),m}}function buildCircle(e,t){const r="circle-",n=buildFill(e,r,t),i=buildStroke(e,r,t),o=numberEvaluator(e,r+"radius",t),s=sizeLikeEvaluator(e,r+"scale",t),a=coordinateEvaluator(e,r+"displacement",t),l=numberEvaluator(e,r+"rotation",t),c=booleanEvaluator(e,r+"rotate-with-view",t),u=optionalDeclutterMode(e,r+"declutter-mode"),h=new CircleStyle({radius:5,declutterMode:u});return function(e){return o&&h.setRadius(o(e)),n&&h.setFill(n(e)),i&&h.setStroke(i(e)),a&&h.setDisplacement(a(e)),l&&h.setRotation(l(e)),c&&h.setRotateWithView(c(e)),s&&h.setScale(s(e)),h}}function numberEvaluator(e,t,r){if(!(t in e))return;const n=buildExpression(e[t],NumberType$1,r);return function(e){return requireNumber(n(e),t)}}function stringEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],StringType$1,r);return function(e){return requireString(n(e),t)}}function patternEvaluator(e,t,r){const n=stringEvaluator(e,t+"pattern-src",r),i=sizeEvaluator(e,t+"pattern-offset",r),o=sizeEvaluator(e,t+"pattern-size",r),s=colorLikeEvaluator(e,t+"color",r);return function(e){return{src:n(e),offset:i&&i(e),size:o&&o(e),color:s&&s(e)}}}function booleanEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],BooleanType$1,r);return function(e){const r=n(e);if("boolean"!=typeof r)throw new Error(`Expected a boolean for ${t}`);return r}}function colorLikeEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],ColorType$1,r);return function(e){return requireColorLike(n(e),t)}}function numberArrayEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1,r);return function(e){return requireNumberArray(n(e),t)}}function coordinateEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1,r);return function(e){const r=requireNumberArray(n(e),t);if(2!==r.length)throw new Error(`Expected two numbers for ${t}`);return r}}function sizeEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1,r);return function(e){return requireSize(n(e),t)}}function sizeLikeEvaluator(e,t,r){if(!(t in e))return null;const n=buildExpression(e[t],NumberArrayType$1|NumberType$1,r);return function(e){return requireSizeLike(n(e),t)}}function optionalNumber(e,t){const r=e[t];if(void 0!==r){if("number"!=typeof r)throw new Error(`Expected a number for ${t}`);return r}}function optionalSize(e,t){const r=e[t];if(void 0!==r){if("number"==typeof r)return toSize(r);if(!Array.isArray(r))throw new Error(`Expected a number or size array for ${t}`);if(2!==r.length||"number"!=typeof r[0]||"number"!=typeof r[1])throw new Error(`Expected a number or size array for ${t}`);return r}}function optionalString(e,t){const r=e[t];if(void 0!==r){if("string"!=typeof r)throw new Error(`Expected a string for ${t}`);return r}}function optionalIconOrigin(e,t){const r=e[t];if(void 0!==r){if("bottom-left"!==r&&"bottom-right"!==r&&"top-left"!==r&&"top-right"!==r)throw new Error(`Expected bottom-left, bottom-right, top-left, or top-right for ${t}`);return r}}function optionalIconAnchorUnits(e,t){const r=e[t];if(void 0!==r){if("pixels"!==r&&"fraction"!==r)throw new Error(`Expected pixels or fraction for ${t}`);return r}}function optionalNumberArray(e,t){const r=e[t];if(void 0!==r)return requireNumberArray(r,t)}function optionalDeclutterMode(e,t){const r=e[t];if(void 0!==r){if("string"!=typeof r)throw new Error(`Expected a string for ${t}`);if("declutter"!==r&&"obstacle"!==r&&"none"!==r)throw new Error(`Expected declutter, obstacle, or none for ${t}`);return r}}function optionalColorLike(e,t){const r=e[t];if(void 0!==r)return requireColorLike(r,t)}function requireNumberArray(e,t){if(!Array.isArray(e))throw new Error(`Expected an array for ${t}`);const r=e.length;for(let n=0;n4)throw new Error(`Expected a color with 3 or 4 values for ${t}`);return r}function requireSize(e,t){const r=requireNumberArray(e,t);if(2!==r.length)throw new Error(`Expected an array of two numbers for ${t}`);return r}function requireSizeLike(e,t){return"number"==typeof e?e:requireSize(e,t)}const Property$2={RENDER_ORDER:"renderOrder"};class BaseVectorLayer extends Layer{constructor(e){e=e||{};const t=Object.assign({},e);delete t.style,delete t.renderBuffer,delete t.updateWhileAnimating,delete t.updateWhileInteracting,super(t),this.declutter_=e.declutter?String(e.declutter):void 0,this.renderBuffer_=void 0!==e.renderBuffer?e.renderBuffer:100,this.style_=null,this.styleFunction_=void 0,this.setStyle(e.style),this.updateWhileAnimating_=void 0!==e.updateWhileAnimating&&e.updateWhileAnimating,this.updateWhileInteracting_=void 0!==e.updateWhileInteracting&&e.updateWhileInteracting}getDeclutter(){return this.declutter_}getFeatures(e){return super.getFeatures(e)}getRenderBuffer(){return this.renderBuffer_}getRenderOrder(){return this.get(Property$2.RENDER_ORDER)}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}getUpdateWhileAnimating(){return this.updateWhileAnimating_}getUpdateWhileInteracting(){return this.updateWhileInteracting_}renderDeclutter(e,t){const r=this.getDeclutter();r in e.declutter==0&&(e.declutter[r]=new RBush$1(9)),this.getRenderer().renderDeclutter(e,t)}setRenderOrder(e){this.set(Property$2.RENDER_ORDER,e)}setStyle(e){this.style_=void 0===e?createDefaultStyle:e;const t=toStyleLike(e);this.styleFunction_=null===e?void 0:toFunction(t),this.changed()}setDeclutter(e){this.declutter_=e?String(e):void 0,this.changed()}}function toStyleLike(e){if(void 0===e)return createDefaultStyle;if(!e)return null;if("function"==typeof e)return e;if(e instanceof Style)return e;if(!Array.isArray(e))return flatStylesToStyleFunction([e]);if(0===e.length)return[];const t=e.length,r=e[0];if(r instanceof Style){const r=new Array(t);for(let n=0;n=0;--n){const i=f[n],o=i.layer;if(o.hasRenderer()&&inView(i,c)&&s.call(a,o)){const n=o.getRenderer(),s=o.getSource();if(n&&s){const o=s.getWrapX()?d:e,a=u.bind(null,i.managed);y[0]=o[0]+p[v][0],y[1]=o[1]+p[v][1],l=n.forEachFeatureAtCoordinate(y,t,r,a,m)}if(l)return l}}if(0===m.length)return;const b=1/m.length;return m.forEach((e,t)=>e.distanceSq+=t*b),m.sort((e,t)=>e.distanceSq-t.distanceSq),m.some(e=>l=e.callback(e.feature,e.layer,e.geometry)),l}hasFeatureAtCoordinate(e,t,r,n,i,o){return void 0!==this.forEachFeatureAtCoordinate(e,t,r,n,TRUE,this,i,o)}getMap(){return this.map_}renderFrame(e){abstract()}scheduleExpireIconCache(e){shared.canExpireCache()&&e.postRenderFunctions.push(expireIconCache)}}function expireIconCache(){shared.expire()}class CompositeMapRenderer extends MapRenderer{constructor(e){super(e),this.fontChangeListenerKey_=listen(checkedFonts,ObjectEventType.PROPERTYCHANGE,e.redrawText,e),this.element_=WORKER_OFFSCREEN_CANVAS?createMockDiv():document.createElement("div");const t=this.element_.style;t.position="absolute",t.width="100%",t.height="100%",t.zIndex="0",this.element_.className=CLASS_UNSELECTABLE+" ol-layers";const r=e.getViewport();r&&r.insertBefore(this.element_,r.firstChild||null),this.children_=[],this.renderedVisible_=!0}dispatchRenderEvent(e,t){const r=this.getMap();if(r.hasListener(e)){const n=new RenderEvent(e,void 0,t);r.dispatchEvent(n)}}disposeInternal(){unlistenByKey(this.fontChangeListenerKey_),this.element_.remove(),super.disposeInternal()}renderFrame(e){if(!e)return void(this.renderedVisible_&&(this.element_.style.display="none",this.renderedVisible_=!1));this.calculateMatrices2D(e),this.dispatchRenderEvent(EventType.PRECOMPOSE,e);const t=e.layerStatesArray.sort((e,t)=>e.zIndex-t.zIndex);t.some(e=>e.layer instanceof BaseVectorLayer&&e.layer.getDeclutter())&&(e.declutter={});const r=e.viewState;this.children_.length=0;const n=[];let i=null;for(let s=0,a=t.length;s0)&&(e.fillStyle=n,e.fillRect(0,0,o.width,o.height)),isCanvas(r)&&r.width>0){const n=t.style.opacity||r.style.opacity;e.globalAlpha=""===n?1:Number(n);const i=r.style.transform;if(i)e.setTransform(...fromString$1(i));else{const t=parseFloat(r.style.width)/r.width,n=parseFloat(r.style.height)/r.height;e.setTransform(t,0,0,n,0,0)}e.drawImage(r,0,0)}}e.globalAlpha=1,e.setTransform(1,0,0,1,0,0)}this.dispatchRenderEvent(EventType.POSTCOMPOSE,e),this.renderedVisible_||(this.element_.style.display="",this.renderedVisible_=!0),this.scheduleExpireIconCache(e)}declutter(e,t){if(e.declutter){for(let r=t.length-1;r>=0;--r){const n=t[r],i=n.layer;i.getDeclutter()&&i.renderDeclutter(e,n)}t.forEach(t=>t.layer.renderDeferred(e))}}}function removeLayerMapProperty(e){e instanceof Layer?e.setMapInternal(null):e instanceof LayerGroup&&e.getLayers().forEach(removeLayerMapProperty)}function setLayerMapProperty(e,t){if(e instanceof Layer)e.setMapInternal(t);else if(e instanceof LayerGroup){const r=e.getLayers().getArray();for(let e=0,n=r.length;ethis.updateSize())),this.controls=t.controls||(WORKER_OFFSCREEN_CANVAS?new Collection:defaults$1()),this.interactions=t.interactions||(WORKER_OFFSCREEN_CANVAS?new Collection:defaults({onFocusOnly:!0})),this.overlays_=t.overlays,this.overlayIdIndex_={},this.renderer_=null,this.postRenderFunctions_=[],this.tileQueue_=new TileQueue(this.getTilePriority.bind(this),this.handleTileChange_.bind(this)),this.addChangeListener(MapProperty.LAYERGROUP,this.handleLayerGroupChanged_),this.addChangeListener(MapProperty.VIEW,this.handleViewChanged_),this.addChangeListener(MapProperty.SIZE,this.handleSizeChanged_),this.addChangeListener(MapProperty.TARGET,this.handleTargetChanged_),this.setProperties(t.values);const r=this;!e.view||e.view instanceof View||e.view.then(function(e){r.setView(new View(e))}),this.controls.addEventListener(CollectionEventType.ADD,e=>{e.element.setMap(this)}),this.controls.addEventListener(CollectionEventType.REMOVE,e=>{e.element.setMap(null)}),this.interactions.addEventListener(CollectionEventType.ADD,e=>{e.element.setMap(this)}),this.interactions.addEventListener(CollectionEventType.REMOVE,e=>{e.element.setMap(null)}),this.overlays_.addEventListener(CollectionEventType.ADD,e=>{this.addOverlayInternal_(e.element)}),this.overlays_.addEventListener(CollectionEventType.REMOVE,e=>{const t=e.element.getId();void 0!==t&&delete this.overlayIdIndex_[t.toString()],e.element.setMap(null)}),this.controls.forEach(e=>{e.setMap(this)}),this.interactions.forEach(e=>{e.setMap(this)}),this.overlays_.forEach(this.addOverlayInternal_.bind(this))}addControl(e){this.getControls().push(e)}addInteraction(e){this.getInteractions().push(e)}addLayer(e){this.getLayerGroup().getLayers().push(e)}handleLayerAdd_(e){setLayerMapProperty(e.layer,this)}addOverlay(e){this.getOverlays().push(e)}addOverlayInternal_(e){const t=e.getId();void 0!==t&&(this.overlayIdIndex_[t.toString()]=e),e.setMap(this)}disposeInternal(){this.controls.clear(),this.interactions.clear(),this.overlays_.clear(),this.resizeObserver_?.disconnect(),this.setTarget(null),super.disposeInternal()}forEachFeatureAtPixel(e,t,r){if(!this.frameState_||!this.renderer_)return;const n=this.getCoordinateFromPixelInternal(e),i=void 0!==(r=void 0!==r?r:{}).hitTolerance?r.hitTolerance:0,o=void 0!==r.layerFilter?r.layerFilter:TRUE,s=!1!==r.checkWrapped;return this.renderer_.forEachFeatureAtCoordinate(n,this.frameState_,i,s,t,null,o,null)}getFeaturesAtPixel(e,t){const r=[];return this.forEachFeatureAtPixel(e,function(e){r.push(e)},t),r}getAllLayers(){const e=[];return function t(r){r.forEach(function(r){r instanceof LayerGroup?t(r.getLayers()):e.push(r)})}(this.getLayers()),e}hasFeatureAtPixel(e,t){if(!this.frameState_||!this.renderer_)return!1;const r=this.getCoordinateFromPixelInternal(e),n=void 0!==(t=void 0!==t?t:{}).layerFilter?t.layerFilter:TRUE,i=void 0!==t.hitTolerance?t.hitTolerance:0,o=!1!==t.checkWrapped;return this.renderer_.hasFeatureAtCoordinate(r,this.frameState_,i,o,n,null)}getEventCoordinate(e){return this.getCoordinateFromPixel(this.getEventPixel(e))}getEventCoordinateInternal(e){return this.getCoordinateFromPixelInternal(this.getEventPixel(e))}getEventPixel(e){const t=this.viewport_.getBoundingClientRect(),r=this.getSize(),n=t.width/r[0],i=t.height/r[1],o="changedTouches"in e?e.changedTouches[0]:e;return[(o.clientX-t.left)/n,(o.clientY-t.top)/i]}getTarget(){return this.get(MapProperty.TARGET)}getTargetElement(){return this.targetElement_}getCoordinateFromPixel(e){return toUserCoordinate(this.getCoordinateFromPixelInternal(e),this.getView().getProjection())}getCoordinateFromPixelInternal(e){const t=this.frameState_;return t?apply$1(t.pixelToCoordinateTransform,e.slice()):null}getControls(){return this.controls}getOverlays(){return this.overlays_}getOverlayById(e){const t=this.overlayIdIndex_[e.toString()];return void 0!==t?t:null}getInteractions(){return this.interactions}getLayerGroup(){return this.get(MapProperty.LAYERGROUP)}setLayers(e){const t=this.getLayerGroup();if(e instanceof Collection)return void t.setLayers(e);const r=t.getLayers();r.clear(),r.extend(e)}getLayers(){return this.getLayerGroup().getLayers()}getLoadingOrNotReady(){const e=this.getLayerGroup().getLayerStatesArray();for(let t=0,r=e.length;t=0;r--){const n=t[r];if(n.getMap()===this&&n.getActive()&&this.getTargetElement()&&(!n.handleEvent(e)||e.propagationStopped))break}}}handlePostRender(){const e=this.frameState_,t=this.tileQueue_;if(!t.isEmpty()){let r=this.maxTilesLoading_,n=r;if(e){const t=e.viewHints;if(t[ViewHint.ANIMATING]||t[ViewHint.INTERACTING]){const t=Date.now()-e.time>8;r=t?0:8,n=t?0:2}}t.getTilesLoading(){this.postRenderTimeoutHandle_=void 0,this.handlePostRender()},0))}setLayerGroup(e){const t=this.getLayerGroup();t&&this.handleLayerRemove_(new GroupEvent("removelayer",t)),this.set(MapProperty.LAYERGROUP,e)}setSize(e){this.set(MapProperty.SIZE,e)}setTarget(e){this.set(MapProperty.TARGET,e)}setView(e){if(!e||e instanceof View)return void this.set(MapProperty.VIEW,e);this.set(MapProperty.VIEW,new View);const t=this;e.then(function(e){t.setView(new View(e))})}updateSize(){const e=this.getTargetElement();let t;if(e){let r,n;if(isCanvas(e))r=e.width,n=e.height;else{const t=getComputedStyle(e);r=e.offsetWidth-parseFloat(t.borderLeftWidth)-parseFloat(t.paddingLeft)-parseFloat(t.paddingRight)-parseFloat(t.borderRightWidth),n=e.offsetHeight-parseFloat(t.borderTopWidth)-parseFloat(t.paddingTop)-parseFloat(t.paddingBottom)-parseFloat(t.borderBottomWidth)}isNaN(r)||isNaN(n)||(t=[Math.max(0,r),Math.max(0,n)],!hasArea(t)&&(e.offsetWidth||e.offsetHeight||e.getClientRects().length)&&warn("No map visible because the map container's width or height are 0."))}const r=this.getSize();!t||r&&equals$2(t,r)||(this.setSize(t),this.updateViewportSize_(t))}updateViewportSize_(e){const t=this.getView();t&&t.setViewportSize(e)}};function createOptionsInternal(e){let t=null;void 0!==e.keyboardEventTarget&&(t="string"==typeof e.keyboardEventTarget?document.getElementById(e.keyboardEventTarget):e.keyboardEventTarget);const r={},n=e.layers&&"function"==typeof e.layers.getLayers?e.layers:new LayerGroup({layers:e.layers});let i,o,s;return r[MapProperty.LAYERGROUP]=n,r[MapProperty.TARGET]=e.target,r[MapProperty.VIEW]=e.view instanceof View?e.view:new View,void 0!==e.controls&&(Array.isArray(e.controls)?i=new Collection(e.controls.slice()):(assert$1("function"==typeof e.controls.getArray,"Expected `controls` to be an array or an `ol/Collection.js`"),i=e.controls)),void 0!==e.interactions&&(Array.isArray(e.interactions)?o=new Collection(e.interactions.slice()):(assert$1("function"==typeof e.interactions.getArray,"Expected `interactions` to be an array or an `ol/Collection.js`"),o=e.interactions)),void 0!==e.overlays?Array.isArray(e.overlays)?s=new Collection(e.overlays.slice()):(assert$1("function"==typeof e.overlays.getArray,"Expected `overlays` to be an array or an `ol/Collection.js`"),s=e.overlays):s=new Collection,{controls:i,interactions:o,keyboardEventTarget:t,overlays:s,values:r}}const Property$1={ELEMENT:"element",MAP:"map",OFFSET:"offset",POSITION:"position",POSITIONING:"positioning"};class Overlay extends BaseObject{constructor(e){super(),this.on,this.once,this.un,this.options=e,this.id=e.id,this.insertFirst=void 0===e.insertFirst||e.insertFirst,this.stopEvent=void 0===e.stopEvent||e.stopEvent,this.element=document.createElement("div"),this.element.className=void 0!==e.className?e.className:"ol-overlay-container "+CLASS_SELECTABLE,this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.autoPan=!0===e.autoPan?{}:e.autoPan||void 0,this.rendered={transform_:"",visible:!0},this.mapPostrenderListenerKey=null,this.addChangeListener(Property$1.ELEMENT,this.handleElementChanged),this.addChangeListener(Property$1.MAP,this.handleMapChanged),this.addChangeListener(Property$1.OFFSET,this.handleOffsetChanged),this.addChangeListener(Property$1.POSITION,this.handlePositionChanged),this.addChangeListener(Property$1.POSITIONING,this.handlePositioningChanged),void 0!==e.element&&this.setElement(e.element),this.setOffset(void 0!==e.offset?e.offset:[0,0]),this.setPositioning(e.positioning||"top-left"),void 0!==e.position&&this.setPosition(e.position)}getElement(){return this.get(Property$1.ELEMENT)}getId(){return this.id}getMap(){return this.get(Property$1.MAP)||null}getOffset(){return this.get(Property$1.OFFSET)}getPosition(){return this.get(Property$1.POSITION)}getPositioning(){return this.get(Property$1.POSITIONING)}handleElementChanged(){removeChildren(this.element);const e=this.getElement();e&&this.element.appendChild(e)}handleMapChanged(){this.mapPostrenderListenerKey&&(this.element?.remove(),unlistenByKey(this.mapPostrenderListenerKey),this.mapPostrenderListenerKey=null);const e=this.getMap();if(e){this.mapPostrenderListenerKey=listen(e,MapEventType.POSTRENDER,this.render,this),this.updatePixelPosition();const t=this.stopEvent?e.getOverlayContainerStopEvent():e.getOverlayContainer();this.insertFirst?t.insertBefore(this.element,t.childNodes[0]||null):t.appendChild(this.element),this.performAutoPan()}}render(){this.updatePixelPosition()}handleOffsetChanged(){this.updatePixelPosition()}handlePositionChanged(){this.updatePixelPosition(),this.performAutoPan()}handlePositioningChanged(){this.updatePixelPosition()}setElement(e){this.set(Property$1.ELEMENT,e)}setMap(e){this.set(Property$1.MAP,e)}setOffset(e){this.set(Property$1.OFFSET,e)}setPosition(e){this.set(Property$1.POSITION,e)}performAutoPan(){this.autoPan&&this.panIntoView(this.autoPan)}panIntoView(e){const t=this.getMap();if(!t||!t.getTargetElement()||!this.get(Property$1.POSITION))return;const r=this.getRect(t.getTargetElement(),t.getSize()),n=this.getElement(),i=this.getRect(n,[outerWidth(n),outerHeight(n)]),o=void 0===(e=e||{}).margin?20:e.margin;if(!containsExtent(r,i)){const n=i[0]-r[0],s=r[2]-i[2],a=i[1]-r[1],l=r[3]-i[3],c=[0,0];if(n<0?c[0]=n-o:s<0&&(c[0]=Math.abs(s)+o),a<0?c[1]=a-o:l<0&&(c[1]=Math.abs(l)+o),0!==c[0]||0!==c[1]){const r=t.getView().getCenterInternal(),n=t.getPixelFromCoordinateInternal(r);if(!n)return;const i=[n[0]+c[0],n[1]+c[1]],o=e.animation||{};t.getView().animateInternal({center:t.getCoordinateFromPixelInternal(i),duration:o.duration,easing:o.easing})}}}getRect(e,t){const r=e.getBoundingClientRect(),n=r.left+window.pageXOffset,i=r.top+window.pageYOffset;return[n,i,n+t[0],i+t[1]]}setPositioning(e){this.set(Property$1.POSITIONING,e)}setVisible(e){this.rendered.visible!==e&&(this.element.style.display=e?"":"none",this.rendered.visible=e)}updatePixelPosition(){const e=this.getMap(),t=this.getPosition();if(!e||!e.isRendered()||!t)return void this.setVisible(!1);const r=e.getPixelFromCoordinate(t),n=e.getSize();this.updateRenderedPosition(r,n)}updateRenderedPosition(e,t){const r=this.element.style,n=this.getOffset(),i=this.getPositioning();this.setVisible(!0);let o="0%",s="0%";"bottom-right"==i||"center-right"==i||"top-right"==i?o="-100%":"bottom-center"!=i&&"center-center"!=i&&"top-center"!=i||(o="-50%"),"bottom-left"==i||"bottom-center"==i||"bottom-right"==i?s="-100%":"center-left"!=i&&"center-center"!=i&&"center-right"!=i||(s="-50%");const a=`translate(${o}, ${s}) translate(${e[0]+n[0]}px, ${e[1]+n[1]}px)`;this.rendered.transform_!=a&&(this.rendered.transform_=a,r.transform=a)}getOptions(){return this.options}}class Feature extends BaseObject{constructor(e){if(super(),this.on,this.once,this.un,this.id_=void 0,this.geometryName_="geometry",this.style_=null,this.styleFunction_=void 0,this.geometryChangeKey_=null,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),e)if("function"==typeof e.getSimplifiedGeometry){const t=e;this.setGeometry(t)}else{const t=e;this.setProperties(t)}}clone(){const e=new Feature(this.hasProperties()?this.getProperties():null);e.setGeometryName(this.getGeometryName());const t=this.getGeometry();t&&e.setGeometry(t.clone());const r=this.getStyle();return r&&e.setStyle(r),e}getGeometry(){return this.get(this.geometryName_)}getId(){return this.id_}getGeometryName(){return this.geometryName_}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}handleGeometryChange_(){this.changed()}handleGeometryChanged_(){this.geometryChangeKey_&&(unlistenByKey(this.geometryChangeKey_),this.geometryChangeKey_=null);const e=this.getGeometry();e&&(this.geometryChangeKey_=listen(e,EventType$1.CHANGE,this.handleGeometryChange_,this)),this.changed()}setGeometry(e){this.set(this.geometryName_,e)}setStyle(e){this.style_=e,this.styleFunction_=e?createStyleFunction(e):void 0,this.changed()}setId(e){this.id_=e,this.changed()}setGeometryName(e){this.removeChangeListener(this.geometryName_,this.handleGeometryChanged_),this.geometryName_=e,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),this.handleGeometryChanged_()}}function createStyleFunction(e){if("function"==typeof e)return e;let t;return Array.isArray(e)?t=e:(assert$1("function"==typeof e.getZIndex,"Expected an `ol/style/Style` or an array of `ol/style/Style.js`"),t=[e]),function(){return t}}function interpolatePoint(e,t,r,n,i,o,s){let a,l;const c=(r-t)/n;if(1===c)a=t;else if(2===c)a=t,l=i;else if(0!==c){let o=e[t],s=e[t+1],c=0;const u=[0];for(let i=t+n;i1?s:2,o=o||new Array(s);for(let u=0;u>1;ia&&(this.instructions.push([Instruction.CUSTOM,a,c,e,r,inflateCoordinates,i]),this.hitDetectionInstructions.push([Instruction.CUSTOM,a,c,e,n||r,inflateCoordinates,i]));break;case"Point":l=e.getFlatCoordinates(),this.coordinates.push(l[0],l[1]),c=this.coordinates.length,this.instructions.push([Instruction.CUSTOM,a,c,e,r,void 0,i]),this.hitDetectionInstructions.push([Instruction.CUSTOM,a,c,e,n||r,void 0,i])}this.endGeometry(t)}beginGeometry(e,t,r){this.beginGeometryInstruction1_=[Instruction.BEGIN_GEOMETRY,t,0,e,r],this.instructions.push(this.beginGeometryInstruction1_),this.beginGeometryInstruction2_=[Instruction.BEGIN_GEOMETRY,t,0,e,r],this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)}finish(){return{instructions:this.instructions,hitDetectionInstructions:this.hitDetectionInstructions,coordinates:this.coordinates}}reverseHitDetectionInstructions(){const e=this.hitDetectionInstructions;let t;e.reverse();const r=e.length;let n,i,o=-1;for(t=0;tthis.maxLineWidth&&(this.maxLineWidth=t.lineWidth,this.bufferedMaxExtent_=null)}else t.strokeStyle=void 0,t.lineCap=void 0,t.lineDash=null,t.lineDashOffset=void 0,t.lineJoin=void 0,t.lineWidth=void 0,t.miterLimit=void 0;return t}setFillStrokeStyle(e,t){const r=this.state;this.fillStyleToState(e,r),this.strokeStyleToState(t,r)}createFill(e){const t=e.fillStyle,r=[Instruction.SET_FILL_STYLE,t];return"string"!=typeof t&&r.push(e.fillPatternScale),r}applyStroke(e){this.instructions.push(this.createStroke(e))}createStroke(e){return[Instruction.SET_STROKE_STYLE,e.strokeStyle,e.lineWidth*this.pixelRatio,e.lineCap,e.lineJoin,e.miterLimit,e.lineDash?this.applyPixelRatio(e.lineDash):null,e.lineDashOffset*this.pixelRatio]}updateFillStyle(e,t){const r=e.fillStyle;"string"==typeof r&&e.currentFillStyle==r||(this.instructions.push(t.call(this,e)),e.currentFillStyle=r)}updateStrokeStyle(e,t){const r=e.strokeStyle,n=e.lineCap,i=e.lineDash,o=e.lineDashOffset,s=e.lineJoin,a=e.lineWidth,l=e.miterLimit;(e.currentStrokeStyle!=r||e.currentLineCap!=n||i!=e.currentLineDash&&!equals$2(e.currentLineDash,i)||e.currentLineDashOffset!=o||e.currentLineJoin!=s||e.currentLineWidth!=a||e.currentMiterLimit!=l)&&(t.call(this,e),e.currentStrokeStyle=r,e.currentLineCap=n,e.currentLineDash=i,e.currentLineDashOffset=o,e.currentLineJoin=s,e.currentLineWidth=a,e.currentMiterLimit=l)}endGeometry(e){this.beginGeometryInstruction1_[2]=this.instructions.length,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length,this.beginGeometryInstruction2_=null;const t=[Instruction.END_GEOMETRY,e];this.instructions.push(t),this.hitDetectionInstructions.push(t)}getBufferedMaxExtent(){if(!this.bufferedMaxExtent_&&(this.bufferedMaxExtent_=clone(this.maxExtent),this.maxLineWidth>0)){const e=this.resolution*(this.maxLineWidth+1)/2;buffer(this.bufferedMaxExtent_,e,this.bufferedMaxExtent_)}return this.bufferedMaxExtent_}}class CanvasImageBuilder extends CanvasBuilder{constructor(e,t,r,n){super(e,t,r,n),this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.anchorX_=void 0,this.anchorY_=void 0,this.height_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.scale_=void 0,this.width_=void 0,this.declutterMode_=void 0,this.declutterImageWithText_=void 0}drawPoint(e,t,r){if(!this.image_||this.maxExtent&&!containsCoordinate(this.maxExtent,e.getFlatCoordinates()))return;this.beginGeometry(e,t,r);const n=e.getFlatCoordinates(),i=e.getStride(),o=this.coordinates.length,s=this.appendFlatPointCoordinates(n,i);this.instructions.push([Instruction.DRAW_IMAGE,o,s,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([Instruction.DRAW_IMAGE,o,s,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(t)}drawMultiPoint(e,t,r){if(!this.image_)return;this.beginGeometry(e,t,r);const n=e.getFlatCoordinates(),i=[];for(let a=0,l=n.length;a=e){const t=(e-a+h)/h,d=lerp(r,c,t),p=lerp(n,u,t);l.push(d,p),o.push(l),l=[d,p],a==e&&(s+=i),a=0}else if(a0&&o.push(l),o}function matchingChunk(e,t,r,n,i){let o,s,a,l,c,u,h,d,p,f,g=r,m=r,y=0,b=0,v=r;for(s=r;se&&(b>y&&(y=b,g=v,m=s),b=0,v=s-i)),a=l,h=p,d=f),c=r,u=n}return b+=l,b>y?[v,s]:[g,m]}const TEXT_ALIGN={left:0,center:.5,right:1,top:0,middle:.5,hanging:.2,alphabetic:.8,ideographic:.8,bottom:1};class CanvasTextBuilder extends CanvasBuilder{constructor(e,t,r,n){super(e,t,r,n),this.labels_=null,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=void 0,this.textKeepUpright_=void 0,this.textRotation_=0,this.textFillState_=null,this.fillStates={},this.fillStates[defaultFillStyle]={fillStyle:defaultFillStyle},this.textStrokeState_=null,this.strokeStates={},this.textState_={},this.textStates={},this.textKey_="",this.fillKey_="",this.strokeKey_="",this.declutterMode_=void 0,this.declutterImageWithText_=void 0}finish(){const e=super.finish();return e.textStates=this.textStates,e.fillStates=this.fillStates,e.strokeStates=this.strokeStates,e}drawText(e,t,r){const n=this.textFillState_,i=this.textStrokeState_,o=this.textState_;if(""===this.text_||!o||!n&&!i)return;const s=this.coordinates;let a=s.length;const l=e.getType();let c=null,u=e.getStride();if("line"!==o.placement||"LineString"!=l&&"MultiLineString"!=l&&"Polygon"!=l&&"MultiPolygon"!=l){let n=o.overflow?null:[];switch(l){case"Point":case"MultiPoint":c=e.getFlatCoordinates();break;case"LineString":c=e.getFlatMidpoint();break;case"Circle":c=e.getCenter();break;case"MultiLineString":c=e.getFlatMidpoints(),u=2;break;case"Polygon":c=e.getFlatInteriorPoint(),o.overflow||n.push(c[2]/this.resolution),u=3;break;case"MultiPolygon":const t=e.getFlatInteriorPoints();c=[];for(let e=0,r=t.length;e{const n=s[2*(e+r)]===c[r*u]&&s[2*(e+r)+1]===c[r*u+1];return n||--e,n})}this.saveTextStates_();const h=o.backgroundFill?this.createFill(this.fillStyleToState(o.backgroundFill)):null,d=o.backgroundStroke?this.createStroke(this.strokeStyleToState(o.backgroundStroke)):null;this.beginGeometry(e,t,r);let p=o.padding;if(p!=defaultPadding&&(o.scale[0]<0||o.scale[1]<0)){let e=o.padding[0],t=o.padding[1],r=o.padding[2],n=o.padding[3];o.scale[0]<0&&(t=-t,n=-n),o.scale[1]<0&&(e=-e,r=-r),p=[e,t,r,n]}const f=this.pixelRatio;this.instructions.push([Instruction.DRAW_IMAGE,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[1,1],NaN,this.declutterMode_,this.declutterImageWithText_,p==defaultPadding?defaultPadding:p.map(function(e){return e*f}),h,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_,this.textOffsetX_,this.textOffsetY_,n]);const g=1/f,m=h?h.slice(0):null;m&&(m[1]=defaultFillStyle),this.hitDetectionInstructions.push([Instruction.DRAW_IMAGE,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[g,g],NaN,this.declutterMode_,this.declutterImageWithText_,p,m,d,this.text_,this.textKey_,this.strokeKey_,this.fillKey_?defaultFillStyle:this.fillKey_,this.textOffsetX_,this.textOffsetY_,n]),this.endGeometry(t)}else{if(!intersects$1(this.maxExtent,e.getExtent()))return;let n;if(c=e.getFlatCoordinates(),"LineString"==l)n=[c.length];else if("MultiLineString"==l)n=e.getEnds();else if("Polygon"==l)n=e.getEnds().slice(0,1);else if("MultiPolygon"==l){const t=e.getEndss();n=[];for(let e=0,r=t.length;ee[2]}else A=E>x;const I=Math.PI,P=[],k=C+n===t;let O;if(y=0,b=S,p=e[t=C],f=e[t+1],k){v(),O=Math.atan2(f-m,p-g),A&&(O+=O>0?-I:I);const e=(x+E)/2,t=(R+w)/2;return P[0]=[e,t,(T-o)/2,O,i],P}for(let L=0,M=(i=i.replace(/\n/g," ")).length;L0?-I:I),void 0!==O){let t=e-O;if(t+=t>I?-2*I:t<-I?2*I:0,Math.abs(t)>s)return null}O=e;const h=L;let d=0;for(;L{if("function"==typeof getSharedCanvasContext2D()[t])return this.push_(t),this.pushMethodArgs_},set:(e,t,r)=>(this.push_(t,r),!0)})}push_(...e){const t=this.instructions_,r=this.zIndex+this.offset_;t[r]||(t[r]=[]),t[r].push(...e)}pushMethodArgs_=(...e)=>(this.push_(e),this);pushFunction(e){this.push_(e)}getContext(){return this.context_}draw(e){this.instructions_.forEach(t=>{for(let r=0,n=t.length;r0&&e.push("\n",""),e.push(t,""),e}function richTextToPlainText(e,t,r){return r%2==0&&(e+=t),e}class Executor{constructor(e,t,r,n,i){this.overlaps=r,this.pixelRatio=t,this.resolution=e,this.alignAndScaleFill_,this.instructions=n.instructions,this.coordinates=n.coordinates,this.coordinateCache_={},this.renderedTransform_=create(),this.hitDetectionInstructions=n.hitDetectionInstructions,this.pixelCoordinates_=null,this.viewRotation_=0,this.fillStates=n.fillStates||{},this.strokeStates=n.strokeStates||{},this.textStates=n.textStates||{},this.widths_={},this.labels_={},this.zIndexContext_=i?new ZIndexContext:null}getZIndexContext(){return this.zIndexContext_}createLabel(e,t,r,n){const i=e+t+r+n;if(this.labels_[i])return this.labels_[i];const o=n?this.strokeStates[n]:null,s=r?this.fillStates[r]:null,a=this.textStates[t],l=this.pixelRatio,c=[a.scale[0]*l,a.scale[1]*l],u=a.justify?TEXT_ALIGN[a.justify]:horizontalTextAlign(Array.isArray(e)?e[0]:e,a.textAlign||defaultTextAlign),h=n&&o.lineWidth?o.lineWidth:0,d=Array.isArray(e)?e:String(e).split("\n").reduce(createTextChunks,[]),{width:p,height:f,widths:g,heights:m,lineWidths:y}=getTextDimensions(a,d),b=p+h,v=[],_=(b+2)*c[0],E=(f+h)*c[1],w={width:_<0?Math.floor(_):Math.ceil(_),height:E<0?Math.floor(E):Math.ceil(E),contextInstructions:v};1==c[0]&&1==c[1]||v.push("scale",c),n&&(v.push("strokeStyle",o.strokeStyle),v.push("lineWidth",h),v.push("lineCap",o.lineCap),v.push("lineJoin",o.lineJoin),v.push("miterLimit",o.miterLimit),v.push("setLineDash",[o.lineDash]),v.push("lineDashOffset",o.lineDashOffset)),r&&v.push("fillStyle",s.fillStyle),v.push("textBaseline","middle"),v.push("textAlign","center");const C=.5-u;let S=u*b+C*h;const T=[],x=[];let R,A=0,I=0,P=0,k=0;for(let O=0,L=d.length;Oe?e-l:i,v=o+c>t?t-c:o,_=p[3]+b*h[0]+p[1],E=p[0]+v*h[1]+p[2],w=m-p[3],C=y-p[0];let S;return(f||0!==u)&&(p1[0]=w,p4[0]=w,p1[1]=C,p2[1]=C,p2[0]=w+_,p3[0]=p2[0],p3[1]=C+E,p4[1]=p3[1]),0!==u?(S=compose(create(),r,n,1,1,u,-r,-n),apply$1(S,p1),apply$1(S,p2),apply$1(S,p3),apply$1(S,p4),createOrUpdate$2(Math.min(p1[0],p2[0],p3[0],p4[0]),Math.min(p1[1],p2[1],p3[1],p4[1]),Math.max(p1[0],p2[0],p3[0],p4[0]),Math.max(p1[1],p2[1],p3[1],p4[1]),tmpExtent)):createOrUpdate$2(Math.min(w,w+_),Math.min(C,C+E),Math.max(w,w+_),Math.max(C,C+E),tmpExtent),d&&(m=Math.round(m),y=Math.round(y)),{drawImageX:m,drawImageY:y,drawImageW:b,drawImageH:v,originX:l,originY:c,declutterBox:{minX:tmpExtent[0],minY:tmpExtent[1],maxX:tmpExtent[2],maxY:tmpExtent[3],value:g},canvasTransform:S,scale:h}}replayImageOrLabel_(e,t,r,n,i,o,s){const a=!(!o&&!s),l=n.declutterBox,c=s?s[2]*n.scale[0]/2:0;return l.minX-c<=t[0]&&l.maxX+c>=0&&l.minY-c<=t[1]&&l.maxY+c>=0&&(a&&this.replayTextBackground_(e,p1,p2,p3,p4,o,s),drawImageOrLabel(e,n.canvasTransform,i,r,n.originX,n.originY,n.drawImageW,n.drawImageH,n.drawImageX,n.drawImageY,n.scale)),!0}fill_(e){const t=this.alignAndScaleFill_;if(t){const r=apply$1(this.renderedTransform_,[0,0]),n=512*this.pixelRatio;e.save(),e.translate(r[0]%n,r[1]%n),1!==t&&e.scale(t,t),e.rotate(this.viewRotation_)}e.fill(),t&&e.restore()}setStrokeStyle_(e,t){e.strokeStyle=t[1],t[1]&&(e.lineWidth=t[2],e.lineCap=t[3],e.lineJoin=t[4],e.miterLimit=t[5],e.lineDashOffset=t[7],e.setLineDash(t[6]))}drawLabelWithPointPlacement_(e,t,r,n){const i=this.textStates[t],o=this.createLabel(e,t,n,r),s=this.strokeStates[r],a=this.pixelRatio,l=horizontalTextAlign(Array.isArray(e)?e[0]:e,i.textAlign||defaultTextAlign),c=TEXT_ALIGN[i.textBaseline||defaultTextBaseline],u=s&&s.lineWidth?s.lineWidth:0;return{label:o,anchorX:l*(o.width/a-2*i.scale[0])+2*(.5-l)*u,anchorY:c*o.height/a+2*(.5-c)*u}}execute_(e,t,r,n,i,o,s,a){const l=this.zIndexContext_;let c;this.pixelCoordinates_&&equals$2(r,this.renderedTransform_)?c=this.pixelCoordinates_:(this.pixelCoordinates_||(this.pixelCoordinates_=[]),c=transform2D(this.coordinates,0,this.coordinates.length,2,r,this.pixelCoordinates_),setFromArray(this.renderedTransform_,r));let u=0;const h=n.length;let d,p,f,g,m,y,b,v,_,E,w,C,S,T=0,x=0,R=0;const A=this.coordinateCache_,I=this.viewRotation_,P=Math.round(1e12*Math.atan2(-r[1],r[0]))/1e12,k={context:e,pixelRatio:this.pixelRatio,resolution:this.resolution,rotation:I},O=this.instructions!=n||this.overlaps?0:200;let L,M,D,N;for(;uO&&(this.fill_(e),x=0),R>O&&(e.stroke(),R=0),x||R||(e.beginPath(),m=NaN,y=NaN),++u;break;case Instruction.CIRCLE:T=r[1];const n=c[T],h=c[T+1],F=c[T+2]-n,$=c[T+3]-h,B=Math.sqrt(F*F+$*$);e.moveTo(n+B,h),e.arc(n,h,B,0,2*Math.PI,!0),++u;break;case Instruction.CLOSE_PATH:e.closePath(),++u;break;case Instruction.CUSTOM:T=r[1],d=r[2];const U=r[3],z=r[4],j=r[5];k.geometry=U,k.feature=L,u in A||(A[u]=[]);const V=A[u];j?j(c,T,d,2,V):(V[0]=c[T],V[1]=c[T+1],V.length=2),l&&(l.zIndex=r[6]),z(V,k),++u;break;case Instruction.DRAW_IMAGE:T=r[1],d=r[2],_=r[3],p=r[4],f=r[5];let G=r[6];const H=r[7],q=r[8],W=r[9],K=r[10];let Y=r[11];const Z=r[12];let X=r[13];g=r[14]||"declutter";const J=r[15];if(!_&&r.length>=20){E=r[19],w=r[20],C=r[21],S=r[22];const e=this.drawLabelWithPointPlacement_(E,w,C,S);_=e.label,r[3]=_;const t=r[23];p=(e.anchorX-t)*this.pixelRatio,r[4]=p;const n=r[24];f=(e.anchorY-n)*this.pixelRatio,r[5]=f,G=_.height,r[6]=G,X=_.width,r[13]=X}let Q,ee,te,re;r.length>25&&(Q=r[25]),r.length>17?(ee=r[16],te=r[17],re=r[18]):(ee=defaultPadding,te=null,re=null),K&&P?Y+=I:K||P||(Y-=I);let ne=0;for(;T!DECLUTTER.includes(e));class ExecutorGroup{constructor(e,t,r,n,i,o,s){this.maxExtent_=e,this.overlaps_=n,this.pixelRatio_=r,this.resolution_=t,this.renderBuffer_=o,this.executorsByZIndex_={},this.hitDetectionContext_=null,this.hitDetectionTransform_=create(),this.renderedContext_=null,this.deferredZIndexContexts_={},this.createExecutors_(i,s)}clip(e,t){const r=this.getClipCoords(t);e.beginPath(),e.moveTo(r[0],r[1]),e.lineTo(r[2],r[3]),e.lineTo(r[4],r[5]),e.lineTo(r[6],r[7]),e.clip()}createExecutors_(e,t){for(const r in e){let n=this.executorsByZIndex_[r];void 0===n&&(n={},this.executorsByZIndex_[r]=n);const i=e[r];for(const e in i){const r=i[e];n[e]=new Executor(this.resolution_,this.pixelRatio_,this.overlaps_,r,t)}}}hasExecutors(e){for(const t in this.executorsByZIndex_){const r=this.executorsByZIndex_[t];for(let t=0,n=e.length;t0){if(!o||"none"===r||"Image"!==d&&"Text"!==d||o.includes(e)){const r=(h[l]-3)/4,o=n-r%s,a=n-(r/s|0),c=i(e,t,o*o+a*a);if(c)return c}c.clearRect(0,0,s,s);break}}const f=Object.keys(this.executorsByZIndex_).map(Number);let g,m,y,b,v;for(f.sort(ascending),g=f.length-1;g>=0;--g){const e=f[g].toString();for(y=this.executorsByZIndex_[e],m=ALL.length-1;m>=0;--m)if(d=ALL[m],b=y[d],void 0!==b&&(v=b.executeHitDetection(c,a,r,p,u),v))return v}}getClipCoords(e){const t=this.maxExtent_;if(!t)return null;const r=t[0],n=t[1],i=t[2],o=t[3],s=[r,n,r,o,i,o,i,n];return transform2D(s,0,8,2,e,s),s}isEmpty(){return isEmpty$1(this.executorsByZIndex_)}execute(e,t,r,n,i,o,s){const a=Object.keys(this.executorsByZIndex_).map(Number);a.sort(s?descending:ascending),o=o||ALL;const l=ALL.length;for(let c=0,u=a.length;cp.execute(e,t,r,n,i,s)):p.execute(h,t,r,n,i,s),d&&h.restore(),o){o.offset();const e=a[c]*l+ALL.indexOf(u);this.deferredZIndexContexts_[e]||(this.deferredZIndexContexts_[e]=[]),this.deferredZIndexContexts_[e].push(o)}}}}this.renderedContext_=e}getDeferredZIndexContexts(){return this.deferredZIndexContexts_}getRenderedContext(){return this.renderedContext_}renderDeferred(){const e=this.deferredZIndexContexts_,t=Object.keys(e).map(Number).sort(ascending);for(let r=0,n=t.length;r{e.draw(this.renderedContext_),e.clear()}),e[t[r]].length=0}}const circlePixelIndexArrayCache={};function getPixelIndexArray(e){if(void 0!==circlePixelIndexArrayCache[e])return circlePixelIndexArrayCache[e];const t=2*e+1,r=e*e,n=new Array(r+1);for(let o=0;o<=e;++o)for(let i=0;i<=e;++i){const s=o*o+i*i;if(s>r)break;let a=n[s];a||(a=[],n[s]=a),a.push(4*((e+o)*t+(e+i))+3),o>0&&a.push(4*((e-o)*t+(e+i))+3),i>0&&(a.push(4*((e+o)*t+(e-i))+3),o>0&&a.push(4*((e-o)*t+(e-i))+3))}const i=[];for(let o=0,s=n.length;oe*this.pixelRatio_),lineDashOffset:(i||defaultLineDashOffset)*this.pixelRatio_,lineJoin:void 0!==o?o:defaultLineJoin,lineWidth:(void 0!==s?s:defaultLineWidth)*this.pixelRatio_,miterLimit:void 0!==a?a:defaultMiterLimit,strokeStyle:asColorLike(e||defaultStrokeStyle)}}else this.strokeState_=null}setImageStyle(e){let t;if(!e||!(t=e.getSize()))return void(this.image_=null);const r=e.getPixelRatio(this.pixelRatio_),n=e.getAnchor(),i=e.getOrigin();this.image_=e.getImage(this.pixelRatio_),this.imageAnchorX_=n[0]*r,this.imageAnchorY_=n[1]*r,this.imageHeight_=t[1]*r,this.imageOpacity_=e.getOpacity(),this.imageOriginX_=i[0],this.imageOriginY_=i[1],this.imageRotateWithView_=e.getRotateWithView(),this.imageRotation_=e.getRotation();const o=e.getScaleArray();this.imageScale_=[o[0]*this.pixelRatio_/r,o[1]*this.pixelRatio_/r],this.imageWidth_=t[0]*r}setTextStyle(e){if(e){const t=e.getFill();if(t){const e=t.getColor();this.textFillState_={fillStyle:asColorLike(e||defaultFillStyle)}}else this.textFillState_=null;const r=e.getStroke();if(r){const e=r.getColor(),t=r.getLineCap(),n=r.getLineDash(),i=r.getLineDashOffset(),o=r.getLineJoin(),s=r.getWidth(),a=r.getMiterLimit();this.textStrokeState_={lineCap:void 0!==t?t:defaultLineCap,lineDash:n||defaultLineDash,lineDashOffset:i||defaultLineDashOffset,lineJoin:void 0!==o?o:defaultLineJoin,lineWidth:void 0!==s?s:defaultLineWidth,miterLimit:void 0!==a?a:defaultMiterLimit,strokeStyle:asColorLike(e||defaultStrokeStyle)}}else this.textStrokeState_=null;const n=e.getFont(),i=e.getOffsetX(),o=e.getOffsetY(),s=e.getRotateWithView(),a=e.getRotation(),l=e.getScaleArray(),c=e.getText(),u=e.getTextAlign(),h=e.getTextBaseline();this.textState_={font:void 0!==n?n:defaultFont,textAlign:void 0!==u?u:defaultTextAlign,textBaseline:void 0!==h?h:defaultTextBaseline},this.text_=void 0!==c?Array.isArray(c)?c.reduce((e,t,r)=>e+(r%2?" ":t),""):c:"",this.textOffsetX_=void 0!==i?this.pixelRatio_*i:0,this.textOffsetY_=void 0!==o?this.pixelRatio_*o:0,this.textRotateWithView_=void 0!==s&&s,this.textRotation_=void 0!==a?a:0,this.textScale_=[this.pixelRatio_*l[0],this.pixelRatio_*l[1]]}else this.text_=""}}const HIT_DETECT_RESOLUTION=.5;function createHitDetectionImageData(e,t,r,n,i,o,s,a,l){const c=l?toUserExtent(i):i,u=createCanvasContext2D(e[0]*HIT_DETECT_RESOLUTION,e[1]*HIT_DETECT_RESOLUTION);u.imageSmoothingEnabled=!1;const h=u.canvas,d=new CanvasImmediateRenderer(u,HIT_DETECT_RESOLUTION,i,null,s,a,l?getTransformFromProjections(getUserProjection(),l):null),p=r.length,f=Math.floor(16777215/p),g={};for(let y=1;y<=p;++y){const e=r[y-1],t=e.getStyleFunction()||n;if(!t)continue;let i=t(e,o);if(!i)continue;Array.isArray(i)||(i=[i]);const s=(y*f).toString(16).padStart(7,"#00000");for(let r=0,n=i.length;r0;return h&&Promise.all(l).then(()=>i(null)),renderFeatureInternal(e,t,r,n,o,s,a),h}function renderFeatureInternal(e,t,r,n,i,o,s){const a=r.getGeometryFunction()(t);if(!a)return;const l=a.simplifyTransformed(n,i);r.getRenderer()?renderGeometry(e,l,r,t,s):(0,GEOMETRY_RENDERERS[l.getType()])(e,l,r,t,s,o)}function renderGeometry(e,t,r,n,i){if("GeometryCollection"==t.getType()){const o=t.getGeometries();for(let t=0,s=o.length;tthis.maxStaleKeys&&(this.staleKeys_.length=this.maxStaleKeys)}getFeatures(e){return abstract()}getData(e){return null}prepareFrame(e){return abstract()}renderFrame(e,t){return abstract()}forEachFeatureAtCoordinate(e,t,r,n,i){}getLayer(){return this.layer_}handleFontsChanged(){}handleImageChange_(e){const t=e.target;t.getState()!==ImageState.LOADED&&t.getState()!==ImageState.ERROR||this.renderIfReadyAndVisible()}loadImage(e){let t=e.getState();return t!=ImageState.LOADED&&t!=ImageState.ERROR&&e.addEventListener(EventType$1.CHANGE,this.boundHandleImageChange_),t==ImageState.IDLE&&(e.load(),t=e.getState()),t==ImageState.LOADED}renderIfReadyAndVisible(){const e=this.getLayer();e&&e.getVisible()&&"ready"===e.getSourceState()&&e.changed()}renderDeferred(e){}disposeInternal(){delete this.layer_,super.disposeInternal()}}const canvasPool$2=[];let pixelContext=null;function createPixelContext(){pixelContext=createCanvasContext2D(1,1,void 0,{willReadFrequently:!0})}class CanvasLayerRenderer extends LayerRenderer{constructor(e){super(e),this.container=null,this.renderedResolution,this.tempTransform=create(),this.pixelTransform=create(),this.inversePixelTransform=create(),this.context=null,this.deferredContext_=null,this.containerReused=!1,this.frameState=null}getImageData(e,t,r){let n;pixelContext||createPixelContext(),pixelContext.clearRect(0,0,1,1);try{pixelContext.drawImage(e,t,r,1,1,0,0,1,1),n=pixelContext.getImageData(0,0,1,1).data}catch{return pixelContext=null,null}return n}getBackground(e){let t=this.getLayer().getBackground();return"function"==typeof t&&(t=t(e.viewState.resolution)),t||void 0}useContainer(e,t,r){const n=this.getLayer().getClassName();let i,o;if(e&&e.className===n&&(!r||e&&e.style.backgroundColor&&equals$2(asArray(e.style.backgroundColor),asArray(r)))){const t=e.firstElementChild;isCanvas(t)&&(o=t.getContext("2d"))}if(o&&equivalent(o.canvas.style.transform,t)?(this.container=e,this.context=o,this.containerReused=!0):this.containerReused?(this.container=null,this.context=null,this.containerReused=!1):this.container&&(this.container.style.backgroundColor=null),!this.container){i=WORKER_OFFSCREEN_CANVAS?createMockDiv():document.createElement("div"),i.className=n;let e=i.style;e.position="absolute",e.width="100%",e.height="100%",o=createCanvasContext2D();const t=o.canvas;i.appendChild(t),e=t.style,e.position="absolute",e.left="0",e.transformOrigin="top left",this.container=i,this.context=o}this.containerReused||!r||this.container.style.backgroundColor||(this.container.style.backgroundColor=r)}clipUnrotated(e,t,r){const n=getTopLeft(r),i=getTopRight(r),o=getBottomRight(r),s=getBottomLeft(r);apply$1(t.coordinateToPixelTransform,n),apply$1(t.coordinateToPixelTransform,i),apply$1(t.coordinateToPixelTransform,o),apply$1(t.coordinateToPixelTransform,s);const a=this.inversePixelTransform;apply$1(a,n),apply$1(a,i),apply$1(a,o),apply$1(a,s),e.save(),e.beginPath(),e.moveTo(Math.round(n[0]),Math.round(n[1])),e.lineTo(Math.round(i[0]),Math.round(i[1])),e.lineTo(Math.round(o[0]),Math.round(o[1])),e.lineTo(Math.round(s[0]),Math.round(s[1])),e.clip()}prepareContainer(e,t){const r=e.extent,n=e.viewState.resolution,i=e.viewState.rotation,o=e.pixelRatio,s=Math.round(getWidth(r)/n*o),a=Math.round(getHeight(r)/n*o);compose(this.pixelTransform,e.size[0]/2,e.size[1]/2,1/o,1/o,i,-s/2,-a/2),makeInverse(this.inversePixelTransform,this.pixelTransform);const l=toString$1(this.pixelTransform);if(this.useContainer(t,l,this.getBackground(e)),!this.containerReused){const e=this.context.canvas;e.width!=s||e.height!=a?(e.width=s,e.height=a):this.context.clearRect(0,0,s,a),l!==e.style.transform&&(e.style.transform=l)}}dispatchRenderEvent_(e,t,r){const n=this.getLayer();if(n.hasListener(e)){const i=new RenderEvent(e,this.inversePixelTransform,r,t);n.dispatchEvent(i)}}preRender(e,t){this.frameState=t,t.declutter||this.dispatchRenderEvent_(EventType.PRERENDER,e,t)}postRender(e,t){t.declutter||this.dispatchRenderEvent_(EventType.POSTRENDER,e,t)}renderDeferredInternal(e){}getRenderContext(e){return e.declutter&&!this.deferredContext_&&(this.deferredContext_=new ZIndexContext),e.declutter?this.deferredContext_.getContext():this.context}renderDeferred(e){e.declutter&&(this.dispatchRenderEvent_(EventType.PRERENDER,this.context,e),e.declutter&&this.deferredContext_&&(this.deferredContext_.draw(this.context),this.deferredContext_.clear()),this.renderDeferredInternal(e),this.dispatchRenderEvent_(EventType.POSTRENDER,this.context,e))}getRenderTransform(e,t,r,n,i,o,s){const a=i/2,l=o/2,c=n/t,u=-c,h=-e[0]+s,d=-e[1];return compose(this.tempTransform,a,l,c,u,-r,h,d)}disposeInternal(){delete this.frameState,super.disposeInternal()}}class CanvasVectorLayerRenderer extends CanvasLayerRenderer{constructor(e){super(e),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.animatingOrInteracting_,this.hitDetectionImageData_=null,this.clipped_=!1,this.renderedFeatures_=null,this.renderedRevision_=-1,this.renderedResolution_=NaN,this.renderedExtent_=createEmpty(),this.wrappedRenderedExtent_=createEmpty(),this.renderedRotation_,this.renderedCenter_=null,this.renderedProjection_=null,this.renderedPixelRatio_=1,this.renderedRenderOrder_=null,this.renderedFrameDeclutter_,this.replayGroup_=null,this.replayGroupChanged=!0,this.clipping=!0,this.targetContext_=null,this.opacity_=1}renderWorlds(e,t,r){const n=t.extent,i=t.viewState,o=i.center,s=i.resolution,a=i.projection,l=i.rotation,c=a.getExtent(),u=this.getLayer().getSource(),h=this.getLayer().getDeclutter(),d=t.pixelRatio,p=t.viewHints,f=!(p[ViewHint.ANIMATING]||p[ViewHint.INTERACTING]),g=this.context,m=Math.round(getWidth(n)/s*d),y=Math.round(getHeight(n)/s*d),b=u.getWrapX()&&a.canWrapX(),v=b?getWidth(c):null,_=b?Math.ceil((n[2]-c[2])/v)+1:1;let E=b?Math.floor((n[0]-c[0])/v):0;do{let n=this.getRenderTransform(o,s,0,d,m,y,E*v);t.declutter&&(n=n.slice(0)),e.execute(g,[g.canvas.width,g.canvas.height],n,l,f,void 0===r?ALL:r?DECLUTTER:NON_DECLUTTER,r?h&&t.declutter[h]:void 0)}while(++E<_)}setDrawContext_(){1!==this.opacity_&&(this.targetContext_=this.context,this.context=createCanvasContext2D(this.context.canvas.width,this.context.canvas.height,canvasPool$2))}resetDrawContext_(){if(1!==this.opacity_&&this.targetContext_){const e=this.targetContext_.globalAlpha;this.targetContext_.globalAlpha=this.opacity_,this.targetContext_.drawImage(this.context.canvas,0,0),this.targetContext_.globalAlpha=e,releaseCanvas(this.context),canvasPool$2.push(this.context.canvas),this.context=this.targetContext_,this.targetContext_=null}}renderDeclutter(e){this.replayGroup_&&this.getLayer().getDeclutter()&&this.renderWorlds(this.replayGroup_,e,!0)}renderDeferredInternal(e){this.replayGroup_&&(this.replayGroup_.renderDeferred(),this.clipped_&&this.context.restore(),this.resetDrawContext_())}renderFrame(e,t){const r=e.layerStatesArray[e.layerIndex];this.opacity_=r.opacity;const n=e.viewState;this.prepareContainer(e,t);const i=this.context,o=this.replayGroup_;let s=o&&!o.isEmpty();if(!s&&!this.getLayer().hasListener(EventType.PRERENDER)&&!this.getLayer().hasListener(EventType.POSTRENDER))return this.container;if(this.setDrawContext_(),this.preRender(i,e),n.projection,this.clipped_=!1,s&&r.extent&&this.clipping){const t=fromUserExtent(r.extent);s=intersects$1(t,e.extent),this.clipped_=s&&!containsExtent(t,e.extent),this.clipped_&&this.clipUnrotated(i,e,t)}return s&&this.renderWorlds(o,e,!this.getLayer().getDeclutter()&&void 0),!e.declutter&&this.clipped_&&i.restore(),this.postRender(i,e),this.renderedRotation_!==n.rotation&&(this.renderedRotation_=n.rotation,this.hitDetectionImageData_=null),e.declutter||this.resetDrawContext_(),this.container}getFeatures(e){return new Promise(t=>{if(this.frameState&&!this.hitDetectionImageData_&&!this.animatingOrInteracting_){const e=this.frameState.size.slice(),t=this.renderedCenter_,r=this.renderedResolution_,n=this.renderedRotation_,i=this.renderedProjection_,o=this.wrappedRenderedExtent_,s=this.getLayer(),a=[],l=e[0]*HIT_DETECT_RESOLUTION,c=e[1]*HIT_DETECT_RESOLUTION;a.push(this.getRenderTransform(t,r,n,HIT_DETECT_RESOLUTION,l,c,0).slice());const u=s.getSource(),h=i.getExtent();if(u.getWrapX()&&i.canWrapX()&&!containsExtent(h,o)){let e=o[0];const i=getWidth(h);let s,u=0;for(;eh[2];)++u,s=i*u,a.push(this.getRenderTransform(t,r,n,HIT_DETECT_RESOLUTION,l,c,s).slice()),e-=i}this.hitDetectionImageData_=createHitDetectionImageData(e,a,this.renderedFeatures_,s.getStyleFunction(),o,r,n,getSquaredTolerance(r,this.renderedPixelRatio_),null)}t(hitDetect(e,this.renderedFeatures_,this.hitDetectionImageData_))})}forEachFeatureAtCoordinate(e,t,r,n,i){if(!this.replayGroup_)return;const o=t.viewState.resolution,s=t.viewState.rotation,a=this.getLayer(),l={},c=this.getLayer().getDeclutter();return this.replayGroup_.forEachFeatureAtCoordinate(e,o,s,r,function(e,t,r){const o=getUid(e),s=l[o];if(s){if(!0!==s&&re.value):null)}handleFontsChanged(){const e=this.getLayer();e.getVisible()&&this.replayGroup_&&e.changed()}handleStyleImageChange_(e){this.renderIfReadyAndVisible()}prepareFrame(e){const t=this.getLayer(),r=t.getSource();if(!r)return!1;const n=e.viewHints[ViewHint.ANIMATING],i=e.viewHints[ViewHint.INTERACTING],o=t.getUpdateWhileAnimating(),s=t.getUpdateWhileInteracting();if(this.ready&&!o&&n||!s&&i)return this.animatingOrInteracting_=!0,!0;this.animatingOrInteracting_=!1;const a=e.extent,l=e.viewState,c=l.projection,u=l.resolution,h=e.pixelRatio,d=t.getRevision(),p=t.getRenderBuffer();let f=t.getRenderOrder();void 0===f&&(f=defaultOrder);const g=l.center.slice(),m=buffer(a,p*u),y=m.slice(),b=[m.slice()],v=c.getExtent();if(r.getWrapX()&&c.canWrapX()&&!containsExtent(v,e.extent)){const e=getWidth(v),t=Math.max(getWidth(m)/2,e);m[0]=v[0]-t,m[2]=v[2]+t,wrapX$1(g,c);const r=wrapX$2(b[0],c);r[0]v[0]&&r[2]>v[2]&&b.push([r[0]-e,r[1],r[2]-e,r[3]])}if(this.ready&&this.renderedResolution_==u&&this.renderedRevision_==d&&this.renderedRenderOrder_==f&&this.renderedFrameDeclutter_===!!e.declutter&&containsExtent(this.wrappedRenderedExtent_,m))return equals$2(this.renderedExtent_,y)||(this.hitDetectionImageData_=null,this.renderedExtent_=y),this.renderedCenter_=g,this.replayGroupChanged=!1,!0;this.replayGroup_=null;const _=new BuilderGroup(getTolerance(u,h),m,u,h);for(let A=0,I=b.length;A{let n;const i=e.getStyleFunction()||t.getStyleFunction();if(i&&(n=i(e,u)),n){const t=this.renderFeature(e,E,n,_,void 0,this.getLayer().getDeclutter(),r);w=w&&!t}},S=toUserExtent(m),T=r.getFeaturesInExtent(S);f&&T.sort(f);for(let A=0,I=T.length;A=200&&a.status<300){const e=t.getType();try{let n;"text"==e||"json"==e?n=a.responseText:"xml"==e?n=a.responseXML||a.responseText:"arraybuffer"==e&&(n=a.response),n?o(t.readFeatures(n,{extent:r,featureProjection:i}),t.readProjection(n)):s()}catch{s()}}else s()},a.onerror=s,a.send()}function xhr(e,t){return function(r,n,i,o,s){loadFeaturesXhr(e,t,r,n,i,e=>{this.addFeatures(e),void 0!==o&&o(e)},()=>{this.changed(),void 0!==s&&s()})}}function all(){return[[-1/0,-1/0,1/0,1/0]]}function bbox(e){return[e]}class GeometryCollection extends Geometry{constructor(e){super(),this.geometries_=e,this.changeEventsKeys_=[],this.listenGeometriesChange_()}unlistenGeometriesChange_(){this.changeEventsKeys_.forEach(unlistenByKey),this.changeEventsKeys_.length=0}listenGeometriesChange_(){const e=this.geometries_;for(let t=0,r=e.length;te.clone())}const tmpTransform=create();class RenderFeature{constructor(e,t,r,n,i,o){this.styleFunction,this.extent_,this.id_=o,this.type_=e,this.flatCoordinates_=t,this.flatInteriorPoints_=null,this.flatMidpoints_=null,this.ends_=r||null,this.properties_=i,this.squaredTolerance_,this.stride_=n,this.simplifiedGeometry_}get(e){return this.properties_[e]}getExtent(){return this.extent_||(this.extent_="Point"===this.type_?createOrUpdateFromCoordinate(this.flatCoordinates_):createOrUpdateFromFlatCoordinates(this.flatCoordinates_,0,this.flatCoordinates_.length,2)),this.extent_}getFlatInteriorPoint(){if(!this.flatInteriorPoints_){const e=getCenter(this.getExtent());this.flatInteriorPoints_=getInteriorPointOfArray(this.flatCoordinates_,0,this.ends_,2,e,0)}return this.flatInteriorPoints_}getFlatInteriorPoints(){if(!this.flatInteriorPoints_){const e=inflateEnds(this.flatCoordinates_,this.ends_),t=linearRingss(this.flatCoordinates_,0,e,2);this.flatInteriorPoints_=getInteriorPointsOfMultiArray(this.flatCoordinates_,0,e,2,t)}return this.flatInteriorPoints_}getFlatMidpoint(){return this.flatMidpoints_||(this.flatMidpoints_=interpolatePoint(this.flatCoordinates_,0,this.flatCoordinates_.length,2,.5)),this.flatMidpoints_}getFlatMidpoints(){if(!this.flatMidpoints_){this.flatMidpoints_=[];const e=this.flatCoordinates_;let t=0;const r=this.ends_;for(let n=0,i=r.length;n{if(e===this.squaredTolerance_)return this.simplifiedGeometry_;this.simplifiedGeometry_=this.clone(),t&&this.simplifiedGeometry_.applyTransform(t);const r=this.simplifiedGeometry_.getFlatCoordinates();let n;switch(this.type_){case"LineString":r.length=douglasPeucker(r,0,this.simplifiedGeometry_.flatCoordinates_.length,this.simplifiedGeometry_.stride_,e,r,0),n=[r.length];break;case"MultiLineString":n=[],r.length=douglasPeuckerArray(r,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,e,r,0,n);break;case"Polygon":n=[],r.length=quantizeArray(r,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,Math.sqrt(e),r,0,n)}return n&&(this.simplifiedGeometry_=new RenderFeature(this.type_,r,n,2,this.properties_,this.id_)),this.squaredTolerance_=e,this.simplifiedGeometry_}),this}}RenderFeature.prototype.getFlatCoordinates=RenderFeature.prototype.getOrientedFlatCoordinates;class RBush{constructor(e){this.rbush_=new RBush$1(e),this.items_={}}insert(e,t){const r={minX:e[0],minY:e[1],maxX:e[2],maxY:e[3],value:t};this.rbush_.insert(r),this.items_[getUid(t)]=r}load(e,t){const r=new Array(t.length);for(let n=0,i=t.length;ne):null}const VectorEventType={ADDFEATURE:"addfeature",CHANGEFEATURE:"changefeature",CLEAR:"clear",REMOVEFEATURE:"removefeature",FEATURESLOADSTART:"featuresloadstart",FEATURESLOADEND:"featuresloadend",FEATURESLOADERROR:"featuresloaderror"};class VectorSourceEvent extends BaseEvent{constructor(e,t,r){super(e),this.feature=t,this.features=r}}class VectorSource extends Source{constructor(e){super({attributions:(e=e||{}).attributions,interpolate:!0,projection:void 0,state:"ready",wrapX:void 0===e.wrapX||e.wrapX}),this.on,this.once,this.un,this.loader_=VOID,this.format_=e.format||null,this.overlaps_=void 0===e.overlaps||e.overlaps,this.url_=e.url,void 0!==e.loader?this.loader_=e.loader:void 0!==this.url_&&(assert$1(this.format_,"`format` must be set when `url` is set"),this.loader_=xhr(this.url_,this.format_)),this.strategy_=void 0!==e.strategy?e.strategy:all;const t=void 0===e.useSpatialIndex||e.useSpatialIndex;let r,n;this.featuresRtree_=t?new RBush:null,this.loadedExtentsRtree_=new RBush,this.loadingExtentsCount_=0,this.nullGeometryFeatures_={},this.idIndex_={},this.uidIndex_={},this.featureChangeKeys_={},this.featuresCollection_=null,Array.isArray(e.features)?n=e.features:e.features&&(r=e.features,n=r.getArray()),t||void 0!==r||(r=new Collection(n)),void 0!==n&&this.addFeaturesInternal(n),void 0!==r&&this.bindFeaturesCollection_(r)}addFeature(e){this.addFeatureInternal(e),this.changed()}addFeatureInternal(e){const t=getUid(e);if(!this.addToIndex_(t,e))return void(this.featuresCollection_&&this.featuresCollection_.remove(e));this.setupChangeEvents_(t,e);const r=e.getGeometry();if(r){const t=r.getExtent();this.featuresRtree_&&this.featuresRtree_.insert(t,e)}else this.nullGeometryFeatures_[t]=e;this.dispatchEvent(new VectorSourceEvent(VectorEventType.ADDFEATURE,e))}setupChangeEvents_(e,t){t instanceof RenderFeature||(this.featureChangeKeys_[e]=[listen(t,EventType$1.CHANGE,this.handleFeatureChange_,this),listen(t,ObjectEventType.PROPERTYCHANGE,this.handleFeatureChange_,this)])}addToIndex_(e,t){let r=!0;if(void 0!==t.getId()){const e=String(t.getId());if(e in this.idIndex_)if(t instanceof RenderFeature){const n=this.idIndex_[e];n instanceof RenderFeature?Array.isArray(n)?n.push(t):this.idIndex_[e]=[n,t]:r=!1}else r=!1;else this.idIndex_[e]=t}return r&&(assert$1(!(e in this.uidIndex_),"The passed `feature` was already added to the source"),this.uidIndex_[e]=t),r}addFeatures(e){this.addFeaturesInternal(e),this.changed()}addFeaturesInternal(e){const t=[],r=[],n=[];for(let i=0,o=e.length;i{t||(t=!0,this.addFeature(e.element),t=!1)}),e.addEventListener(CollectionEventType.REMOVE,e=>{t||(t=!0,this.removeFeature(e.element),t=!1)}),this.featuresCollection_=e}clear(e){if(e){for(const e in this.featureChangeKeys_)this.featureChangeKeys_[e].forEach(unlistenByKey);this.featuresCollection_||(this.featureChangeKeys_={},this.idIndex_={},this.uidIndex_={})}else if(this.featuresRtree_){this.featuresRtree_.forEach(e=>{this.removeFeatureInternal(e)});for(const e in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[e])}this.featuresCollection_&&this.featuresCollection_.clear(),this.featuresRtree_&&this.featuresRtree_.clear(),this.nullGeometryFeatures_={};const t=new VectorSourceEvent(VectorEventType.CLEAR);this.dispatchEvent(t),this.changed()}forEachFeature(e){if(this.featuresRtree_)return this.featuresRtree_.forEach(e);this.featuresCollection_&&this.featuresCollection_.forEach(e)}forEachFeatureAtCoordinateDirect(e,t){const r=[e[0],e[1],e[0],e[1]];return this.forEachFeatureInExtent(r,function(r){const n=r.getGeometry();if(n instanceof RenderFeature||n.intersectsCoordinate(e))return t(r)})}forEachFeatureInExtent(e,t){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(e,t);this.featuresCollection_&&this.featuresCollection_.forEach(t)}forEachFeatureIntersectingExtent(e,t){return this.forEachFeatureInExtent(e,function(r){const n=r.getGeometry();if(n instanceof RenderFeature||n.intersectsExtent(e)){const e=t(r);if(e)return e}})}getFeaturesCollection(){return this.featuresCollection_}getFeatures(){let e;return this.featuresCollection_?e=this.featuresCollection_.getArray().slice(0):this.featuresRtree_&&(e=this.featuresRtree_.getAll(),isEmpty$1(this.nullGeometryFeatures_)||extend$2(e,Object.values(this.nullGeometryFeatures_))),e}getFeaturesAtCoordinate(e){const t=[];return this.forEachFeatureAtCoordinateDirect(e,function(e){t.push(e)}),t}getFeaturesInExtent(e,t){if(this.featuresRtree_){if(!(t&&t.canWrapX()&&this.getWrapX()))return this.featuresRtree_.getInExtent(e);const r=wrapAndSliceX(e,t);return[].concat(...r.map(e=>this.featuresRtree_.getInExtent(e)))}return this.featuresCollection_?this.featuresCollection_.getArray().slice(0):[]}getClosestFeatureToCoordinate(e,t){const r=e[0],n=e[1];let i=null;const o=[NaN,NaN];let s=1/0;const a=[-1/0,-1/0,1/0,1/0];return t=t||TRUE,this.featuresRtree_.forEachInExtent(a,function(e){if(t(e)){const t=e.getGeometry(),l=s;if(s=t instanceof RenderFeature?0:t.closestPointXY(r,n,o,s),s{--this.loadingExtentsCount_,this.dispatchEvent(new VectorSourceEvent(VectorEventType.FEATURESLOADEND,void 0,e))},()=>{--this.loadingExtentsCount_,this.dispatchEvent(new VectorSourceEvent(VectorEventType.FEATURESLOADERROR))}),n.insert(e,{extent:e.slice()}))}this.loading=!(this.loader_.length<4)&&this.loadingExtentsCount_>0}refresh(){this.clear(!0),this.loadedExtentsRtree_.clear(),super.refresh()}removeLoadedExtent(e){const t=this.loadedExtentsRtree_,r=t.forEachInExtent(e,function(t){if(equals$1(t.extent,e))return t});r&&t.remove(r)}removeFeatures(e){let t=!1;for(let r=0,n=e.length;rcreateRenderFeature({...e,geometry:t})).flat();const n="MultiPolygon"===r.type?"Polygon":r.type;if("GeometryCollection"===n||"Circle"===n)throw new Error("Unsupported geometry type: "+n);const i=r.layout.length;return transformGeometryWithOptions(new RenderFeature(n,"Polygon"===n?orientFlatCoordinates(r.flatCoordinates,r.ends,i):r.flatCoordinates,r.ends?.flat(),i,e.properties||{},e.id).enableSimplifyTransformed(),!1,t)}function createGeometry(e,t){if(!e)return null;if(Array.isArray(e)){const r=e.map(e=>createGeometry(e,t));return new GeometryCollection(r)}return transformGeometryWithOptions(new(0,GeometryConstructor[e.type])(e.flatCoordinates,e.layout||"XY",e.ends),!1,t)}class JSONFeature extends FeatureFormat{constructor(){super()}getType(){return"json"}readFeature(e,t){return this.readFeatureFromObject(getObject(e),this.getReadOptions(e,t))}readFeatures(e,t){return this.readFeaturesFromObject(getObject(e),this.getReadOptions(e,t))}readFeatureFromObject(e,t){return abstract()}readFeaturesFromObject(e,t){return abstract()}readGeometry(e,t){return this.readGeometryFromObject(getObject(e),this.getReadOptions(e,t))}readGeometryFromObject(e,t){return abstract()}readProjection(e){return this.readProjectionFromObject(getObject(e))}readProjectionFromObject(e){return abstract()}writeFeature(e,t){return JSON.stringify(this.writeFeatureObject(e,t))}writeFeatureObject(e,t){return abstract()}writeFeatures(e,t){return JSON.stringify(this.writeFeaturesObject(e,t))}writeFeaturesObject(e,t){return abstract()}writeGeometry(e,t){return JSON.stringify(this.writeGeometryObject(e,t))}writeGeometryObject(e,t){return abstract()}}function getObject(e){return"string"==typeof e?JSON.parse(e)||null:null!==e?e:null}class GeoJSON extends JSONFeature{constructor(e){e=e||{},super(),this.dataProjection=get$2(e.dataProjection?e.dataProjection:"EPSG:4326"),e.featureProjection&&(this.defaultFeatureProjection=get$2(e.featureProjection)),e.featureClass&&(this.featureClass=e.featureClass),this.geometryName_=e.geometryName,this.extractGeometryName_=e.extractGeometryName,this.supportedMediaTypes=["application/geo+json","application/vnd.geo+json"]}readFeatureFromObject(e,t){let r=null;r="Feature"===e.type?e:{type:"Feature",geometry:e,properties:null};const n=readGeometryInternal(r.geometry);if(this.featureClass===RenderFeature)return createRenderFeature({geometry:n,id:r.id,properties:r.properties},t);const i=new Feature;return this.geometryName_?i.setGeometryName(this.geometryName_):this.extractGeometryName_&&r.geometry_name&&i.setGeometryName(r.geometry_name),i.setGeometry(createGeometry(n,t)),"id"in r&&i.setId(r.id),r.properties&&i.setProperties(r.properties,!0),i}readFeaturesFromObject(e,t){let r=null;if("FeatureCollection"===e.type){r=[];const n=e.features;for(let e=0,i=n.length;e":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type={type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function_stop={type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression$1={type:"array",value:"*",minimum:1},light={anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky={"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain={source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection={type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint=["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill={"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},paint_line={"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle={"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap={"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol={"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster={"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade={"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_background={"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition={duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},promoteId={"*":{type:"string"}},v8Spec={$version:$version,$root:$root,sources:sources,source:source,source_vector:source_vector,source_raster:source_raster,source_raster_dem:source_raster_dem,source_geojson:source_geojson,source_video:source_video,source_image:source_image,layer:layer,layout:layout,layout_background:layout_background,layout_fill:layout_fill,layout_circle:layout_circle,layout_heatmap:layout_heatmap,"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:layout_line,layout_symbol:layout_symbol,layout_raster:layout_raster,layout_hillshade:layout_hillshade,"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:filter,filter_operator:filter_operator,geometry_type:geometry_type,function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:function_stop,expression:expression$1,light:light,sky:sky,terrain:terrain,projection:projection,paint:paint,paint_fill:paint_fill,"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:paint_line,paint_circle:paint_circle,paint_heatmap:paint_heatmap,paint_symbol:paint_symbol,paint_raster:paint_raster,paint_hillshade:paint_hillshade,"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:paint_background,transition:transition,"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:promoteId};const refProperties=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function deref(e,t){const r={};for(const n in e)"ref"!==n&&(r[n]=e[n]);return refProperties.forEach(e=>{e in t&&(r[e]=t[e])}),r}function derefLayers(e){e=e.slice();const t=Object.create(null);for(let r=0;r`:"value"===e.itemType.kind?"array":`array<${t}>`}return e.kind}const valueMemberTypes=[NullType,NumberType,StringType,BooleanType,ColorType,ProjectionDefinitionType,FormattedType,ObjectType,array(ValueType),PaddingType,NumberArrayType,ColorArrayType,ResolvedImageType,VariableAnchorOffsetCollectionType];function checkSubtype(e,t){if("error"===t.kind)return null;if("array"===e.kind){if("array"===t.kind&&(0===t.N&&"value"===t.itemType.kind||!checkSubtype(e.itemType,t.itemType))&&("number"!=typeof e.N||e.N===t.N))return null}else{if(e.kind===t.kind)return null;if("value"===e.kind)for(const e of valueMemberTypes)if(!checkSubtype(e,t))return null}return`Expected ${typeToString(e)} but found ${typeToString(t)} instead.`}function isValidType(e,t){return t.some(t=>t.kind===e.kind)}function isValidNativeType(e,t){return t.some(t=>"null"===t?null===e:"array"===t?Array.isArray(e):"object"===t?e&&!Array.isArray(e)&&"object"==typeof e:t===typeof e)}function verifyType(e,t){return"array"===e.kind&&"array"===t.kind?e.itemType.kind===t.itemType.kind&&"number"==typeof e.N:e.kind===t.kind}const Xn=.96422,Yn=1,Zn=.82521,t0=4/29,t1=6/29,t2=3*t1*t1,t3=t1*t1*t1,deg2rad$1=Math.PI/180,rad2deg=180/Math.PI;function constrainAngle(e){return(e%=360)<0&&(e+=360),e}function rgbToLab([e,t,r,n]){let i,o;const s=xyz2lab((.2225045*(e=rgb2xyz(e))+.7168786*(t=rgb2xyz(t))+.0606169*(r=rgb2xyz(r)))/Yn);e===t&&t===r?i=o=s:(i=xyz2lab((.4360747*e+.3850649*t+.1430804*r)/Xn),o=xyz2lab((.0139322*e+.0971045*t+.7141733*r)/Zn));const a=116*s-16;return[a<0?0:a,500*(i-s),200*(s-o),n]}function rgb2xyz(e){return e<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function xyz2lab(e){return e>t3?Math.pow(e,1/3):e/t2+t0}function labToRgb([e,t,r,n]){let i=(e+16)/116,o=isNaN(t)?i:i+t/500,s=isNaN(r)?i:i-r/200;return i=Yn*lab2xyz(i),o=Xn*lab2xyz(o),s=Zn*lab2xyz(s),[xyz2rgb(3.1338561*o-1.6168667*i-.4906146*s),xyz2rgb(-.9787684*o+1.9161415*i+.033454*s),xyz2rgb(.0719453*o-.2289914*i+1.4052427*s),n]}function xyz2rgb(e){return(e=e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055)<0?0:e>1?1:e}function lab2xyz(e){return e>t1?e*e*e:t2*(e-t0)}function rgbToHcl(e){const[t,r,n,i]=rgbToLab(e),o=Math.sqrt(r*r+n*n);return[Math.round(1e4*o)?constrainAngle(Math.atan2(n,r)*rad2deg):NaN,o,t,i]}function hclToRgb([e,t,r,n]){return e=isNaN(e)?0:e*deg2rad$1,labToRgb([r,Math.cos(e)*t,Math.sin(e)*t,n])}function hslToRgb([e,t,r,n]){function i(n){const i=(n+e/30)%12,o=t*Math.min(r,1-r);return r-o*Math.max(-1,Math.min(i-3,9-i,1))}return e=constrainAngle(e),t/=100,r/=100,[i(0),i(8),i(4),n]}const hasOwnProperty=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};function getOwn(e,t){return hasOwnProperty(e,t)?e[t]:void 0}function parseCssColor(e){if("transparent"===(e=e.toLowerCase().trim()))return[0,0,0,0];const t=getOwn(namedColors,e);if(t){const[e,r,n]=t;return[e/255,r/255,n/255,1]}if(e.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(e)){const t=e.length<6?1:2;let r=1;return[parseHex(e.slice(r,r+=t)),parseHex(e.slice(r,r+=t)),parseHex(e.slice(r,r+=t)),parseHex(e.slice(r,r+t)||"ff")]}if(e.startsWith("rgb")){const t=/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/,r=e.match(t);if(r){const[e,t,n,i,o,s,a,l,c,u,h,d]=r,p=[i||" ",a||" ",u].join("");if(" "===p||" /"===p||",,"===p||",,,"===p){const e=[n,s,c].join(""),r="%%%"===e?100:""===e?255:0;if(r){const e=[clamp(+t/r,0,1),clamp(+o/r,0,1),clamp(+l/r,0,1),h?parseAlpha(+h,d):1];if(validateNumbers(e))return e}}return}}const r=e.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[e,t,n,i,o,s,a,l,c]=r,u=[n||" ",o||" ",a].join("");if(" "===u||" /"===u||",,"===u||",,,"===u){const e=[+t,clamp(+i,0,100),clamp(+s,0,100),l?parseAlpha(+l,c):1];if(validateNumbers(e))return hslToRgb(e)}}}function parseHex(e){return parseInt(e.padEnd(2,e),16)/255}function parseAlpha(e,t){return clamp(t?e/100:e,0,1)}function clamp(e,t,r){return Math.min(Math.max(t,e),r)}function validateNumbers(e){return!e.some(Number.isNaN)}const namedColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function interpolateNumber(e,t,r){return e+r*(t-e)}function interpolateArray(e,t,r){return e.map((e,n)=>interpolateNumber(e,t[n],r))}class Color{constructor(e,t,r,n=1,i=!0){this.r=e,this.g=t,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[e,t,r,n]))}static parse(e){if(e instanceof Color)return e;if("string"!=typeof e)return;const t=parseCssColor(e);return t?new Color(...t,!1):void 0}get rgb(){const{r:e,g:t,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[e/i,t/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",rgbToHcl(this.rgb))}get lab(){return this.overwriteGetter("lab",rgbToLab(this.rgb))}overwriteGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}toString(){const[e,t,r,n]=this.rgb;return`rgba(${[e,t,r].map(e=>Math.round(255*e)).join(",")},${n})`}static interpolate(e,t,r,n="rgb"){switch(n){case"rgb":{const[n,i,o,s]=interpolateArray(e.rgb,t.rgb,r);return new Color(n,i,o,s,!1)}case"hcl":{const[n,i,o,s]=e.hcl,[a,l,c,u]=t.hcl;let h,d;if(isNaN(n)||isNaN(a))isNaN(n)?isNaN(a)?h=NaN:(h=a,1!==o&&0!==o||(d=l)):(h=n,1!==c&&0!==c||(d=i));else{let e=a-n;a>n&&e>180?e-=360:a180&&(e+=360),h=n+r*e}const[p,f,g,m]=hclToRgb([h,null!=d?d:interpolateNumber(i,l,r),interpolateNumber(o,c,r),interpolateNumber(s,u,r)]);return new Color(p,f,g,m,!1)}case"lab":{const[n,i,o,s]=labToRgb(interpolateArray(e.lab,t.lab,r));return new Color(n,i,o,s,!1)}}}}Color.black=new Color(0,0,0,1),Color.white=new Color(1,1,1,1),Color.transparent=new Color(0,0,0,0),Color.red=new Color(1,0,0,1);class Collator{constructor(e,t,r){this.sensitivity=e?t?"variant":"case":t?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(e,t){return this.collator.compare(e,t)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const VERTICAL_ALIGN_OPTIONS=["bottom","center","top"];class FormattedSection{constructor(e,t,r,n,i,o){this.text=e,this.image=t,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=o}}class Formatted{constructor(e){this.sections=e}static fromString(e){return new Formatted([new FormattedSection(e,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some(e=>0!==e.text.length||e.image&&0!==e.image.name.length)}static factory(e){return e instanceof Formatted?e:Formatted.fromString(e)}toString(){return 0===this.sections.length?"":this.sections.map(e=>e.text).join("")}}class Padding{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof Padding)return e;if("number"==typeof e)return new Padding([e,e,e,e]);if(Array.isArray(e)&&!(e.length<1||e.length>4)){for(const t of e)if("number"!=typeof t)return;switch(e.length){case 1:e=[e[0],e[0],e[0],e[0]];break;case 2:e=[e[0],e[1],e[0],e[1]];break;case 3:e=[e[0],e[1],e[2],e[1]]}return new Padding(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,t,r){return new Padding(interpolateArray(e.values,t.values,r))}}class NumberArray{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof NumberArray)return e;if("number"==typeof e)return new NumberArray([e]);if(Array.isArray(e)){for(const t of e)if("number"!=typeof t)return;return new NumberArray(e)}}toString(){return JSON.stringify(this.values)}static interpolate(e,t,r){return new NumberArray(interpolateArray(e.values,t.values,r))}}class ColorArray{constructor(e){this.values=e.slice()}static parse(e){if(e instanceof ColorArray)return e;if("string"==typeof e){const t=Color.parse(e);if(!t)return;return new ColorArray([t])}if(!Array.isArray(e))return;const t=[];for(const r of e){if("string"!=typeof r)return;const e=Color.parse(r);if(!e)return;t.push(e)}return new ColorArray(t)}toString(){return JSON.stringify(this.values)}static interpolate(e,t,r,n="rgb"){const i=[];if(e.values.length!=t.values.length)throw new Error(`colorArray: Arrays have mismatched length (${e.values.length} vs. ${t.values.length}), cannot interpolate.`);for(let o=0;o=0&&e<=255&&"number"==typeof t&&t>=0&&t<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[e,t,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[e,t,r,n]:[e,t,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function isValue(e){if(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e||e instanceof ProjectionDefinition||e instanceof Color||e instanceof Collator||e instanceof Formatted||e instanceof Padding||e instanceof NumberArray||e instanceof ColorArray||e instanceof VariableAnchorOffsetCollection||e instanceof ResolvedImage)return!0;if(Array.isArray(e)){for(const t of e)if(!isValue(t))return!1;return!0}if("object"==typeof e){for(const t in e)if(!isValue(e[t]))return!1;return!0}return!1}function typeOf(e){if(null===e)return NullType;if("string"==typeof e)return StringType;if("boolean"==typeof e)return BooleanType;if("number"==typeof e)return NumberType;if(e instanceof Color)return ColorType;if(e instanceof ProjectionDefinition)return ProjectionDefinitionType;if(e instanceof Collator)return CollatorType;if(e instanceof Formatted)return FormattedType;if(e instanceof Padding)return PaddingType;if(e instanceof NumberArray)return NumberArrayType;if(e instanceof ColorArray)return ColorArrayType;if(e instanceof VariableAnchorOffsetCollection)return VariableAnchorOffsetCollectionType;if(e instanceof ResolvedImage)return ResolvedImageType;if(Array.isArray(e)){const t=e.length;let r;for(const n of e){const e=typeOf(n);if(r){if(r===e)continue;r=ValueType;break}r=e}return array(r||ValueType,t)}return ObjectType}function valueToString(e){const t=typeof e;return null===e?"":"string"===t||"number"===t||"boolean"===t?String(e):e instanceof Color||e instanceof ProjectionDefinition||e instanceof Formatted||e instanceof Padding||e instanceof NumberArray||e instanceof ColorArray||e instanceof VariableAnchorOffsetCollection||e instanceof ResolvedImage?e.toString():JSON.stringify(e)}class Literal{constructor(e,t){this.type=e,this.value=t}static parse(e,t){if(2!==e.length)return t.error(`'literal' expression requires exactly one argument, but found ${e.length-1} instead.`);if(!isValue(e[1]))return t.error("invalid value");const r=e[1];let n=typeOf(r);const i=t.expectedType;return"array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Literal(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}const types$1={string:StringType,number:NumberType,boolean:BooleanType,object:ObjectType};class Assertion{constructor(e,t){this.type=e,this.args=t}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");let r,n=1;const i=e[0];if("array"===i){let i,o;if(e.length>2){const r=e[1];if("string"!=typeof r||!(r in types$1)||"object"===r)return t.error('The item type argument of "array" must be one of string, number, boolean',1);i=types$1[r],n++}else i=ValueType;if(e.length>3){if(null!==e[2]&&("number"!=typeof e[2]||e[2]<0||e[2]!==Math.floor(e[2])))return t.error('The length argument to "array" must be a positive integer literal',2);o=e[2],n++}r=array(i,o)}else{if(!types$1[i])throw new Error(`Types doesn't contain name = ${i}`);r=types$1[i]}const o=[];for(;ne.outputDefined())}}const types$2={"to-boolean":BooleanType,"to-color":ColorType,"to-number":NumberType,"to-string":StringType};class Coercion{constructor(e,t){this.type=e,this.args=t}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");const r=e[0];if(!types$2[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==e.length)return t.error("Expected one argument.");const n=types$2[r],i=[];for(let o=1;o4?`Invalid rgba value ${JSON.stringify(t)}: expected an array containing either three or four numeric values.`:validateRGBA(t[0],t[1],t[2],t[3]),!r))return new Color(t[0]/255,t[1]/255,t[2]/255,t[3])}throw new RuntimeError(r||`Could not parse color from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"padding":{let t;for(const r of this.args){t=r.evaluate(e);const n=Padding.parse(t);if(n)return n}throw new RuntimeError(`Could not parse padding from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"numberArray":{let t;for(const r of this.args){t=r.evaluate(e);const n=NumberArray.parse(t);if(n)return n}throw new RuntimeError(`Could not parse numberArray from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"colorArray":{let t;for(const r of this.args){t=r.evaluate(e);const n=ColorArray.parse(t);if(n)return n}throw new RuntimeError(`Could not parse colorArray from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"variableAnchorOffsetCollection":{let t;for(const r of this.args){t=r.evaluate(e);const n=VariableAnchorOffsetCollection.parse(t);if(n)return n}throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof t?t:JSON.stringify(t)}'`)}case"number":{let t=null;for(const r of this.args){if(t=r.evaluate(e),null===t)return 0;const n=Number(t);if(!isNaN(n))return n}throw new RuntimeError(`Could not convert ${JSON.stringify(t)} to number.`)}case"formatted":return Formatted.fromString(valueToString(this.args[0].evaluate(e)));case"resolvedImage":return ResolvedImage.fromString(valueToString(this.args[0].evaluate(e)));case"projectionDefinition":return this.args[0].evaluate(e);default:return valueToString(this.args[0].evaluate(e))}}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every(e=>e.outputDefined())}}const geometryTypes=["Unknown","Point","LineString","Polygon"];class EvaluationContext{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?geometryTypes[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(e){let t=this._parseColorCache.get(e);return t||(t=Color.parse(e),this._parseColorCache.set(e,t)),t}}class ParsingContext{constructor(e,t,r=[],n,i=new Scope,o=[]){this.registry=e,this.path=r,this.key=r.map(e=>`[${e}]`).join(""),this.scope=i,this.errors=o,this.expectedType=n,this._isConstant=t}parse(e,t,r,n,i={}){return t?this.concat(t,r,n)._parse(e,i):this._parse(e,i)}_parse(e,t){function r(e,t,r){return"assert"===r?new Assertion(t,[e]):"coerce"===r?new Coercion(t,[e]):e}if(null!==e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e||(e=["literal",e]),Array.isArray(e)){if(0===e.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const i=e[0];if("string"!=typeof i)return this.error(`Expression name must be a string, but found ${typeof i} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const o=this.registry[i];if(o){let i=o.parse(e,this);if(!i)return null;if(this.expectedType){const e=this.expectedType,n=i.type;if("string"!==e.kind&&"number"!==e.kind&&"boolean"!==e.kind&&"object"!==e.kind&&"array"!==e.kind||"value"!==n.kind){if("projectionDefinition"===e.kind&&["string","array"].includes(n.kind)||["color","formatted","resolvedImage"].includes(e.kind)&&["value","string"].includes(n.kind)||["padding","numberArray"].includes(e.kind)&&["value","number","array"].includes(n.kind)||"colorArray"===e.kind&&["value","string","array"].includes(n.kind)||"variableAnchorOffsetCollection"===e.kind&&["value","array"].includes(n.kind))i=r(i,e,t.typeAnnotation||"coerce");else if(this.checkSubtype(e,n))return null}else i=r(i,e,t.typeAnnotation||"assert")}if(!(i instanceof Literal)&&"resolvedImage"!==i.type.kind&&this._isConstant(i)){const e=new EvaluationContext;try{i=new Literal(i.type,i.evaluate(e))}catch(n){return this.error(n.message),null}}return i}return this.error(`Unknown expression "${i}". If you wanted a literal array, use ["literal", [...]].`,0)}return void 0===e?this.error("'undefined' value invalid. Use null instead."):"object"==typeof e?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error(`Expected an array, but found ${typeof e} instead.`)}concat(e,t,r){const n="number"==typeof e?this.path.concat(e):this.path,i=r?this.scope.concat(r):this.scope;return new ParsingContext(this.registry,this._isConstant,n,t||null,i,this.errors)}error(e,...t){const r=`${this.key}${t.map(e=>`[${e}]`).join("")}`;this.errors.push(new ExpressionParsingError(r,e))}checkSubtype(e,t){const r=checkSubtype(e,t);return r&&this.error(r),r}}class Let{constructor(e,t){this.type=t.type,this.bindings=[].concat(e),this.result=t}evaluate(e){return this.result.evaluate(e)}eachChild(e){for(const t of this.bindings)e(t[1]);e(this.result)}static parse(e,t){if(e.length<4)return t.error(`Expected at least 3 arguments, but found ${e.length-1} instead.`);const r=[];for(let i=1;i=r.length)throw new RuntimeError(`Array index out of bounds: ${t} > ${r.length-1}.`);if(t!==Math.floor(t))throw new RuntimeError(`Array index must be an integer, but found ${t} instead.`);return r[t]}eachChild(e){e(this.index),e(this.input)}outputDefined(){return!1}}class In{constructor(e,t){this.type=BooleanType,this.needle=e,this.haystack=t}static parse(e,t){if(3!==e.length)return t.error(`Expected 2 arguments, but found ${e.length-1} instead.`);const r=t.parse(e[1],1,ValueType),n=t.parse(e[2],2,ValueType);return r&&n?isValidType(r.type,[BooleanType,StringType,NumberType,NullType,ValueType])?new In(r,n):t.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(r.type)} instead`):null}evaluate(e){const t=this.needle.evaluate(e),r=this.haystack.evaluate(e);if(!r)return!1;if(!isValidNativeType(t,["boolean","string","number","null"]))throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(t))} instead.`);if(!isValidNativeType(r,["string","array"]))throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(r))} instead.`);return r.indexOf(t)>=0}eachChild(e){e(this.needle),e(this.haystack)}outputDefined(){return!0}}class IndexOf{constructor(e,t,r){this.type=NumberType,this.needle=e,this.haystack=t,this.fromIndex=r}static parse(e,t){if(e.length<=2||e.length>=5)return t.error(`Expected 3 or 4 arguments, but found ${e.length-1} instead.`);const r=t.parse(e[1],1,ValueType),n=t.parse(e[2],2,ValueType);if(!r||!n)return null;if(!isValidType(r.type,[BooleanType,StringType,NumberType,NullType,ValueType]))return t.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(r.type)} instead`);if(4===e.length){const i=t.parse(e[3],3,NumberType);return i?new IndexOf(r,n,i):null}return new IndexOf(r,n)}evaluate(e){const t=this.needle.evaluate(e),r=this.haystack.evaluate(e);if(!isValidNativeType(t,["boolean","string","number","null"]))throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(t))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(e)),isValidNativeType(r,["string"])){const e=r.indexOf(t,n);return-1===e?-1:[...r.slice(0,e)].length}if(isValidNativeType(r,["array"]))return r.indexOf(t,n);throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(r))} instead.`)}eachChild(e){e(this.needle),e(this.haystack),this.fromIndex&&e(this.fromIndex)}outputDefined(){return!1}}class Match{constructor(e,t,r,n,i,o){this.inputType=e,this.type=t,this.input=r,this.cases=n,this.outputs=i,this.otherwise=o}static parse(e,t){if(e.length<5)return t.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if(e.length%2!=1)return t.error("Expected an even number of arguments.");let r,n;t.expectedType&&"value"!==t.expectedType.kind&&(n=t.expectedType);const i={},o=[];for(let l=2;lNumber.MAX_SAFE_INTEGER)return c.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof e&&Math.floor(e)!==e)return c.error("Numeric branch labels must be integer values.");if(r){if(c.checkSubtype(r,typeOf(e)))return null}else r=typeOf(e);if(void 0!==i[String(e)])return c.error("Branch labels must be unique.");i[String(e)]=o.length}const u=t.parse(a,l,n);if(!u)return null;n=n||u.type,o.push(u)}const s=t.parse(e[1],1,ValueType);if(!s)return null;const a=t.parse(e[e.length-1],e.length-1,n);return a?"value"!==s.type.kind&&t.concat(1).checkSubtype(r,s.type)?null:new Match(r,n,s,i,o,a):null}evaluate(e){const t=this.input.evaluate(e);return(typeOf(t)===this.inputType&&this.outputs[this.cases[t]]||this.otherwise).evaluate(e)}eachChild(e){e(this.input),this.outputs.forEach(e),e(this.otherwise)}outputDefined(){return this.outputs.every(e=>e.outputDefined())&&this.otherwise.outputDefined()}}class Case{constructor(e,t,r){this.type=e,this.branches=t,this.otherwise=r}static parse(e,t){if(e.length<4)return t.error(`Expected at least 3 arguments, but found only ${e.length-1}.`);if(e.length%2!=0)return t.error("Expected an odd number of arguments.");let r;t.expectedType&&"value"!==t.expectedType.kind&&(r=t.expectedType);const n=[];for(let o=1;ot.outputDefined())&&this.otherwise.outputDefined()}}class Slice{constructor(e,t,r,n){this.type=e,this.input=t,this.beginIndex=r,this.endIndex=n}static parse(e,t){if(e.length<=2||e.length>=5)return t.error(`Expected 3 or 4 arguments, but found ${e.length-1} instead.`);const r=t.parse(e[1],1,ValueType),n=t.parse(e[2],2,NumberType);if(!r||!n)return null;if(!isValidType(r.type,[array(ValueType),StringType,ValueType]))return t.error(`Expected first argument to be of type array or string, but found ${typeToString(r.type)} instead`);if(4===e.length){const i=t.parse(e[3],3,NumberType);return i?new Slice(r.type,r,n,i):null}return new Slice(r.type,r,n)}evaluate(e){const t=this.input.evaluate(e),r=this.beginIndex.evaluate(e);let n;if(this.endIndex&&(n=this.endIndex.evaluate(e)),isValidNativeType(t,["string"]))return[...t].slice(r,n).join("");if(isValidNativeType(t,["array"]))return t.slice(r,n);throw new RuntimeError(`Expected first argument to be of type array or string, but found ${typeToString(typeOf(t))} instead.`)}eachChild(e){e(this.input),e(this.beginIndex),this.endIndex&&e(this.endIndex)}outputDefined(){return!1}}function findStopLessThanOrEqualTo(e,t){const r=e.length-1;let n,i,o=0,s=r,a=0;for(;o<=s;)if(a=Math.floor((o+s)/2),n=e[a],i=e[a+1],n<=t){if(a===r||tt))throw new RuntimeError("Input is not a number.");s=a-1}return 0}class Step{constructor(e,t,r){this.type=e,this.input=t,this.labels=[],this.outputs=[];for(const[n,i]of r)this.labels.push(n),this.outputs.push(i)}static parse(e,t){if(e.length-1<4)return t.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return t.error("Expected an even number of arguments.");const r=t.parse(e[1],1,NumberType);if(!r)return null;const n=[];let i=null;t.expectedType&&"value"!==t.expectedType.kind&&(i=t.expectedType);for(let o=1;o=r)return t.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',a);const c=t.parse(s,l,i);if(!c)return null;i=i||c.type,n.push([r,c])}return new Step(i,r,n)}evaluate(e){const t=this.labels,r=this.outputs;if(1===t.length)return r[0].evaluate(e);const n=this.input.evaluate(e);if(n<=t[0])return r[0].evaluate(e);const i=t.length;return n>=t[i-1]?r[i-1].evaluate(e):r[findStopLessThanOrEqualTo(t,n)].evaluate(e)}eachChild(e){e(this.input);for(const t of this.outputs)e(t)}outputDefined(){return this.outputs.every(e=>e.outputDefined())}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var unitbezier,hasRequiredUnitbezier;function requireUnitbezier(){if(hasRequiredUnitbezier)return unitbezier;function e(e,t,r,n){this.cx=3*e,this.bx=3*(r-e)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*t,this.by=3*(n-t)-this.cy,this.ay=1-this.cy-this.by,this.p1x=e,this.p1y=t,this.p2x=r,this.p2y=n}return hasRequiredUnitbezier=1,unitbezier=e,e.prototype={sampleCurveX:function(e){return((this.ax*e+this.bx)*e+this.cx)*e},sampleCurveY:function(e){return((this.ay*e+this.by)*e+this.cy)*e},sampleCurveDerivativeX:function(e){return(3*this.ax*e+2*this.bx)*e+this.cx},solveCurveX:function(e,t){if(void 0===t&&(t=1e-6),e<0)return 0;if(e>1)return 1;for(var r=e,n=0;n<8;n++){var i=this.sampleCurveX(r)-e;if(Math.abs(i)i?s=r:a=r,r=.5*(a-s)+s;return r},solve:function(e,t){return this.sampleCurveY(this.solveCurveX(e,t))}},unitbezier}var unitbezierExports=requireUnitbezier(),UnitBezier=getDefaultExportFromCjs(unitbezierExports);class Interpolate{constructor(e,t,r,n,i){this.type=e,this.operator=t,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[o,s]of i)this.labels.push(o),this.outputs.push(s)}static interpolationFactor(e,t,r,n){let i=0;if("exponential"===e.name)i=exponentialInterpolation(t,e.base,r,n);else if("linear"===e.name)i=exponentialInterpolation(t,1,r,n);else if("cubic-bezier"===e.name){const o=e.controlPoints;i=new UnitBezier(o[0],o[1],o[2],o[3]).solve(exponentialInterpolation(t,1,r,n))}return i}static parse(e,t){let[r,n,i,...o]=e;if(!Array.isArray(n)||0===n.length)return t.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const e=n[1];if("number"!=typeof e)return t.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:e}}else{if("cubic-bezier"!==n[0])return t.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const e=n.slice(1);if(4!==e.length||e.some(e=>"number"!=typeof e||e<0||e>1))return t.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:e}}}if(e.length-1<4)return t.error(`Expected at least 4 arguments, but found only ${e.length-1}.`);if((e.length-1)%2!=0)return t.error("Expected an even number of arguments.");if(i=t.parse(i,2,NumberType),!i)return null;const s=[];let a=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||t.expectedType==ColorArrayType?t.expectedType&&"value"!==t.expectedType.kind&&(a=t.expectedType):a=ColorType;for(let l=0;l=e)return t.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',n);const c=t.parse(r,i,a);if(!c)return null;a=a||c.type,s.push([e,c])}return verifyType(a,NumberType)||verifyType(a,ProjectionDefinitionType)||verifyType(a,ColorType)||verifyType(a,PaddingType)||verifyType(a,NumberArrayType)||verifyType(a,ColorArrayType)||verifyType(a,VariableAnchorOffsetCollectionType)||verifyType(a,array(NumberType))?new Interpolate(a,r,n,i,s):t.error(`Type ${typeToString(a)} is not interpolatable.`)}evaluate(e){const t=this.labels,r=this.outputs;if(1===t.length)return r[0].evaluate(e);const n=this.input.evaluate(e);if(n<=t[0])return r[0].evaluate(e);const i=t.length;if(n>=t[i-1])return r[i-1].evaluate(e);const o=findStopLessThanOrEqualTo(t,n),s=t[o],a=t[o+1],l=Interpolate.interpolationFactor(this.interpolation,n,s,a),c=r[o].evaluate(e),u=r[o+1].evaluate(e);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return interpolateNumber(c,u,l);case"color":return Color.interpolate(c,u,l);case"padding":return Padding.interpolate(c,u,l);case"colorArray":return ColorArray.interpolate(c,u,l);case"numberArray":return NumberArray.interpolate(c,u,l);case"variableAnchorOffsetCollection":return VariableAnchorOffsetCollection.interpolate(c,u,l);case"array":return interpolateArray(c,u,l);case"projectionDefinition":return ProjectionDefinition.interpolate(c,u,l)}case"interpolate-hcl":switch(this.type.kind){case"color":return Color.interpolate(c,u,l,"hcl");case"colorArray":return ColorArray.interpolate(c,u,l,"hcl")}case"interpolate-lab":switch(this.type.kind){case"color":return Color.interpolate(c,u,l,"lab");case"colorArray":return ColorArray.interpolate(c,u,l,"lab")}}}eachChild(e){e(this.input);for(const t of this.outputs)e(t)}outputDefined(){return this.outputs.every(e=>e.outputDefined())}}function exponentialInterpolation(e,t,r,n){const i=n-r,o=e-r;return 0===i?0:1===t?o/i:(Math.pow(t,o)-1)/(Math.pow(t,i)-1)}class Coalesce{constructor(e,t){this.type=e,this.args=t}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");let r=null;const n=t.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const s of e.slice(1)){const e=t.parse(s,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!e)return null;r=r||e.type,i.push(e)}if(!r)throw new Error("No output type");const o=n&&i.some(e=>checkSubtype(n,e.type));return new Coalesce(o?ValueType:r,i)}evaluate(e){let t,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(e),r&&r instanceof ResolvedImage&&!r.available&&(t||(t=r.name),r=null,n===this.args.length&&(r=t)),null!==r)break;return r}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every(e=>e.outputDefined())}}function isComparableType(e,t){return"=="===e||"!="===e?"boolean"===t.kind||"string"===t.kind||"number"===t.kind||"null"===t.kind||"value"===t.kind:"string"===t.kind||"number"===t.kind||"value"===t.kind}function eq(e,t,r){return t===r}function neq(e,t,r){return t!==r}function lt(e,t,r){return tr}function lteq(e,t,r){return t<=r}function gteq(e,t,r){return t>=r}function eqCollate(e,t,r,n){return 0===n.compare(t,r)}function neqCollate(e,t,r,n){return!eqCollate(e,t,r,n)}function ltCollate(e,t,r,n){return n.compare(t,r)<0}function gtCollate(e,t,r,n){return n.compare(t,r)>0}function lteqCollate(e,t,r,n){return n.compare(t,r)<=0}function gteqCollate(e,t,r,n){return n.compare(t,r)>=0}function makeComparison(e,t,r){const n="=="!==e&&"!="!==e;return class i{constructor(e,t,r){this.type=BooleanType,this.lhs=e,this.rhs=t,this.collator=r,this.hasUntypedArgument="value"===e.type.kind||"value"===t.type.kind}static parse(e,t){if(3!==e.length&&4!==e.length)return t.error("Expected two or three arguments.");const r=e[0];let o=t.parse(e[1],1,ValueType);if(!o)return null;if(!isComparableType(r,o.type))return t.concat(1).error(`"${r}" comparisons are not supported for type '${typeToString(o.type)}'.`);let s=t.parse(e[2],2,ValueType);if(!s)return null;if(!isComparableType(r,s.type))return t.concat(2).error(`"${r}" comparisons are not supported for type '${typeToString(s.type)}'.`);if(o.type.kind!==s.type.kind&&"value"!==o.type.kind&&"value"!==s.type.kind)return t.error(`Cannot compare types '${typeToString(o.type)}' and '${typeToString(s.type)}'.`);n&&("value"===o.type.kind&&"value"!==s.type.kind?o=new Assertion(s.type,[o]):"value"!==o.type.kind&&"value"===s.type.kind&&(s=new Assertion(o.type,[s])));let a=null;if(4===e.length){if("string"!==o.type.kind&&"string"!==s.type.kind&&"value"!==o.type.kind&&"value"!==s.type.kind)return t.error("Cannot use collator to compare non-string types.");if(a=t.parse(e[3],3,CollatorType),!a)return null}return new i(o,s,a)}evaluate(i){const o=this.lhs.evaluate(i),s=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const t=typeOf(o),r=typeOf(s);if(t.kind!==r.kind||"string"!==t.kind&&"number"!==t.kind)throw new RuntimeError(`Expected arguments for "${e}" to be (string, string) or (number, number), but found (${t.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const e=typeOf(o),r=typeOf(s);if("string"!==e.kind||"string"!==r.kind)return t(i,o,s)}return this.collator?r(i,o,s,this.collator.evaluate(i)):t(i,o,s)}eachChild(e){e(this.lhs),e(this.rhs),this.collator&&e(this.collator)}outputDefined(){return!0}}}const Equals=makeComparison("==",eq,eqCollate),NotEquals=makeComparison("!=",neq,neqCollate),LessThan=makeComparison("<",lt,ltCollate),GreaterThan=makeComparison(">",gt,gtCollate),LessThanOrEqual=makeComparison("<=",lteq,lteqCollate),GreaterThanOrEqual=makeComparison(">=",gteq,gteqCollate);class CollatorExpression{constructor(e,t,r){this.type=CollatorType,this.locale=r,this.caseSensitive=e,this.diacriticSensitive=t}static parse(e,t){if(2!==e.length)return t.error("Expected one argument.");const r=e[1];if("object"!=typeof r||Array.isArray(r))return t.error("Collator options argument must be an object.");const n=t.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,BooleanType);if(!n)return null;const i=t.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,BooleanType);if(!i)return null;let o=null;return r.locale&&(o=t.parse(r.locale,1,StringType),!o)?null:new CollatorExpression(n,i,o)}evaluate(e){return new Collator(this.caseSensitive.evaluate(e),this.diacriticSensitive.evaluate(e),this.locale?this.locale.evaluate(e):null)}eachChild(e){e(this.caseSensitive),e(this.diacriticSensitive),this.locale&&e(this.locale)}outputDefined(){return!1}}class NumberFormat{constructor(e,t,r,n,i){this.type=StringType,this.number=e,this.locale=t,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i}static parse(e,t){if(3!==e.length)return t.error("Expected two arguments.");const r=t.parse(e[1],1,NumberType);if(!r)return null;const n=e[2];if("object"!=typeof n||Array.isArray(n))return t.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=t.parse(n.locale,1,StringType),!i))return null;let o=null;if(n.currency&&(o=t.parse(n.currency,1,StringType),!o))return null;let s=null;if(n["min-fraction-digits"]&&(s=t.parse(n["min-fraction-digits"],1,NumberType),!s))return null;let a=null;return n["max-fraction-digits"]&&(a=t.parse(n["max-fraction-digits"],1,NumberType),!a)?null:new NumberFormat(r,i,o,s,a)}evaluate(e){return new Intl.NumberFormat(this.locale?this.locale.evaluate(e):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(e):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(e):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(e):void 0}).format(this.number.evaluate(e))}eachChild(e){e(this.number),this.locale&&e(this.locale),this.currency&&e(this.currency),this.minFractionDigits&&e(this.minFractionDigits),this.maxFractionDigits&&e(this.maxFractionDigits)}outputDefined(){return!1}}class FormatExpression{constructor(e){this.type=FormattedType,this.sections=e}static parse(e,t){if(e.length<2)return t.error("Expected at least one argument.");const r=e[1];if(!Array.isArray(r)&&"object"==typeof r)return t.error("First argument must be an image or text section.");const n=[];let i=!1;for(let o=1;o<=e.length-1;++o){const r=e[o];if(i&&"object"==typeof r&&!Array.isArray(r)){i=!1;let e=null;if(r["font-scale"]&&(e=t.parse(r["font-scale"],1,NumberType),!e))return null;let o=null;if(r["text-font"]&&(o=t.parse(r["text-font"],1,array(StringType)),!o))return null;let s=null;if(r["text-color"]&&(s=t.parse(r["text-color"],1,ColorType),!s))return null;let a=null;if(r["vertical-align"]){if("string"==typeof r["vertical-align"]&&!VERTICAL_ALIGN_OPTIONS.includes(r["vertical-align"]))return t.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${r["vertical-align"]}' instead.`);if(a=t.parse(r["vertical-align"],1,StringType),!a)return null}const l=n[n.length-1];l.scale=e,l.font=o,l.textColor=s,l.verticalAlign=a}else{const r=t.parse(e[o],1,ValueType);if(!r)return null;const s=r.type.kind;if("string"!==s&&"value"!==s&&"null"!==s&&"resolvedImage"!==s)return t.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:r,scale:null,font:null,textColor:null,verticalAlign:null})}}return new FormatExpression(n)}evaluate(e){return new Formatted(this.sections.map(t=>{const r=t.content.evaluate(e);return typeOf(r)===ResolvedImageType?new FormattedSection("",r,null,null,null,t.verticalAlign?t.verticalAlign.evaluate(e):null):new FormattedSection(valueToString(r),null,t.scale?t.scale.evaluate(e):null,t.font?t.font.evaluate(e).join(","):null,t.textColor?t.textColor.evaluate(e):null,t.verticalAlign?t.verticalAlign.evaluate(e):null)}))}eachChild(e){for(const t of this.sections)e(t.content),t.scale&&e(t.scale),t.font&&e(t.font),t.textColor&&e(t.textColor),t.verticalAlign&&e(t.verticalAlign)}outputDefined(){return!1}}class ImageExpression{constructor(e){this.type=ResolvedImageType,this.input=e}static parse(e,t){if(2!==e.length)return t.error("Expected two arguments.");const r=t.parse(e[1],1,StringType);return r?new ImageExpression(r):t.error("No image name provided.")}evaluate(e){const t=this.input.evaluate(e),r=ResolvedImage.fromString(t);return r&&e.availableImages&&(r.available=e.availableImages.indexOf(t)>-1),r}eachChild(e){e(this.input)}outputDefined(){return!1}}class Length{constructor(e){this.type=NumberType,this.input=e}static parse(e,t){if(2!==e.length)return t.error(`Expected 1 argument, but found ${e.length-1} instead.`);const r=t.parse(e[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?t.error(`Expected argument of type string or array, but found ${typeToString(r.type)} instead.`):new Length(r):null}evaluate(e){const t=this.input.evaluate(e);if("string"==typeof t)return[...t].length;if(Array.isArray(t))return t.length;throw new RuntimeError(`Expected value to be of type string or array, but found ${typeToString(typeOf(t))} instead.`)}eachChild(e){e(this.input)}outputDefined(){return!1}}const EXTENT=8192;function getTileCoordinates(e,t){const r=mercatorXfromLng(e[0]),n=mercatorYfromLat(e[1]),i=Math.pow(2,t.z);return[Math.round(r*i*EXTENT),Math.round(n*i*EXTENT)]}function getLngLatFromTileCoord(e,t){const r=Math.pow(2,t.z),n=(e[0]/EXTENT+t.x)/r,i=(e[1]/EXTENT+t.y)/r;return[lngFromMercatorXfromLng(n),latFromMercatorY(i)]}function mercatorXfromLng(e){return(180+e)/360}function lngFromMercatorXfromLng(e){return 360*e-180}function mercatorYfromLat(e){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+e*Math.PI/360)))/360}function latFromMercatorY(e){return 360/Math.PI*Math.atan(Math.exp((180-360*e)*Math.PI/180))-90}function updateBBox(e,t){e[0]=Math.min(e[0],t[0]),e[1]=Math.min(e[1],t[1]),e[2]=Math.max(e[2],t[0]),e[3]=Math.max(e[3],t[1])}function boxWithinBox(e,t){return!(e[0]<=t[0]||e[2]>=t[2]||e[1]<=t[1]||e[3]>=t[3])}function rayIntersect(e,t,r){return t[1]>e[1]!=r[1]>e[1]&&e[0]<(r[0]-t[0])*(e[1]-t[1])/(r[1]-t[1])+t[0]}function pointOnBoundary(e,t,r){const n=e[0]-t[0],i=e[1]-t[1],o=e[0]-r[0],s=e[1]-r[1];return n*s-o*i===0&&n*o<=0&&i*s<=0}function segmentIntersectSegment(e,t,r,n){const i=[t[0]-e[0],t[1]-e[1]];return 0!==perp([n[0]-r[0],n[1]-r[1]],i)&&!(!twoSided(e,t,r,n)||!twoSided(r,n,e,t))}function lineIntersectPolygon(e,t,r){for(const n of r)for(let r=0;r0&&h<0||u<0&&h>0}function getTilePolygon(e,t,r){const n=[];for(let i=0;ir[2]){const t=.5*n;let i=e[0]-r[0]>t?-n:r[0]-e[0]>t?n:0;0===i&&(i=e[0]-r[2]>t?-n:r[2]-e[0]>t?n:0),e[0]+=i}updateBBox(t,e)}function resetBBox(e){e[0]=e[1]=1/0,e[2]=e[3]=-1/0}function getTilePoints(e,t,r,n){const i=Math.pow(2,n.z)*EXTENT,o=[n.x*EXTENT,n.y*EXTENT],s=[];for(const a of e)for(const e of a){const n=[e.x+o[0],e.y+o[1]];updatePoint(n,t,r,i),s.push(n)}return s}function getTileLines(e,t,r,n){const i=Math.pow(2,n.z)*EXTENT,o=[n.x*EXTENT,n.y*EXTENT],s=[];for(const a of e){const e=[];for(const r of a){const n=[r.x+o[0],r.y+o[1]];updateBBox(t,n),e.push(n)}s.push(e)}if(t[2]-t[0]<=i/2){resetBBox(t);for(const e of s)for(const n of e)updatePoint(n,t,r,i)}return s}function pointsWithinPolygons(e,t){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=e.canonicalID();if("Polygon"===t.type){const o=getTilePolygon(t.coordinates,n,i),s=getTilePoints(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!pointWithinPolygon(e,o))return!1}if("MultiPolygon"===t.type){const o=getTilePolygons(t.coordinates,n,i),s=getTilePoints(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!pointWithinPolygons(e,o))return!1}return!0}function linesWithinPolygons(e,t){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=e.canonicalID();if("Polygon"===t.type){const o=getTilePolygon(t.coordinates,n,i),s=getTileLines(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!lineStringWithinPolygon(e,o))return!1}if("MultiPolygon"===t.type){const o=getTilePolygons(t.coordinates,n,i),s=getTileLines(e.geometry(),r,n,i);if(!boxWithinBox(r,n))return!1;for(const e of s)if(!lineStringWithinPolygons(e,o))return!1}return!0}class Within{constructor(e,t){this.type=BooleanType,this.geojson=e,this.geometries=t}static parse(e,t){if(2!==e.length)return t.error(`'within' expression requires exactly one argument, but found ${e.length-1} instead.`);if(isValue(e[1])){const t=e[1];if("FeatureCollection"===t.type){const e=[];for(const r of t.features){const{type:t,coordinates:n}=r.geometry;"Polygon"===t&&e.push(n),"MultiPolygon"===t&&e.push(...n)}if(e.length)return new Within(t,{type:"MultiPolygon",coordinates:e})}else if("Feature"===t.type){const e=t.geometry.type;if("Polygon"===e||"MultiPolygon"===e)return new Within(t,t.geometry)}else if("Polygon"===t.type||"MultiPolygon"===t.type)return new Within(t,t)}return t.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(null!=e.geometry()&&null!=e.canonicalID()){if("Point"===e.geometryType())return pointsWithinPolygons(e,this.geometries);if("LineString"===e.geometryType())return linesWithinPolygons(e,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}class TinyQueue{constructor(e=[],t=(e,t)=>et?1:0){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,n=t[e];for(;e>0;){const i=e-1>>1,o=t[i];if(r(n,o)>=0)break;t[e]=o,e=i}t[e]=n}_down(e){const{data:t,compare:r}=this,n=this.length>>1,i=t[e];for(;e=0)break;t[e]=t[n],e=n}t[e]=i}}function classifyRings(e){if(e.length<=1)return[e];const t=[];let r,n;for(const i of e){const e=calculateSignedArea(i);0!==e&&(i.area=Math.abs(e),void 0===n&&(n=e<0),n===e<0?(r&&t.push(r),r=[i]):r.push(i))}return r&&t.push(r),t}function calculateSignedArea(e){let t=0;for(let r,n,i=0,o=e.length,s=o-1;i1?(l=e[a+1][0],c=e[a+1][1]):d>0&&(l+=u/this.kx*d,c+=h/this.ky*d)),u=this.wrap(t[0]-l)*this.kx,h=(t[1]-c)*this.ky;const p=u*u+h*h;p180;)e-=360;return e}}const MinPointsSize=100,MinLinePointsSize=50;function compareDistPair(e,t){return t[0]-e[0]}function getRangeSize(e){return e[1]-e[0]+1}function isRangeSafe(e,t){return e[1]>=e[0]&&e[1]e[1])return[null,null];const r=getRangeSize(e);if(t){if(2===r)return[e,null];const t=Math.floor(r/2);return[[e[0],e[0]+t],[e[0]+t,e[1]]]}if(1===r)return[e,null];const n=Math.floor(r/2)-1;return[[e[0],e[0]+n],[e[0]+n+1,e[1]]]}function getBBox(e,t){if(!isRangeSafe(t,e.length))return[1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=t[0];n<=t[1];++n)updateBBox(r,e[n]);return r}function getPolygonBBox(e){const t=[1/0,1/0,-1/0,-1/0];for(const r of e)for(const e of r)updateBBox(t,e);return t}function isValidBBox(e){return e[0]!==-1/0&&e[1]!==-1/0&&e[2]!==1/0&&e[3]!==1/0}function bboxToBBoxDistance(e,t,r){if(!isValidBBox(e)||!isValidBBox(t))return NaN;let n=0,i=0;return e[2]t[2]&&(n=e[0]-t[2]),e[1]>t[3]&&(i=e[1]-t[3]),e[3]=n)return n;if(boxWithinBox(i,o)){if(polygonIntersect(e,t))return 0}else if(polygonIntersect(t,e))return 0;let s=1/0;for(const a of e)for(let e=0,n=a.length,i=n-1;e0;){const i=s.pop();if(i[0]>=o)continue;const l=i[1],c=t?MinLinePointsSize:MinPointsSize;if(getRangeSize(l)<=c){if(!isRangeSafe(l,e.length))return NaN;if(t){const t=lineToPolygonDistance(e,l,r,n);if(isNaN(t)||0===t)return t;o=Math.min(o,t)}else for(let t=l[0];t<=l[1];++t){const i=pointToPolygonDistance(e[t],r,n);if(o=Math.min(o,i),0===o)return 0}}else{const r=splitRange(l,t);updateQueue(s,o,n,e,a,r[0]),updateQueue(s,o,n,e,a,r[1])}}return o}function pointSetToPointSetDistance(e,t,r,n,i,o=1/0){let s=Math.min(o,i.distance(e[0],r[0]));if(0===s)return s;const a=new TinyQueue([[0,[0,e.length-1],[0,r.length-1]]],compareDistPair);for(;a.length>0;){const o=a.pop();if(o[0]>=s)continue;const l=o[1],c=o[2],u=t?MinLinePointsSize:MinPointsSize,h=n?MinLinePointsSize:MinPointsSize;if(getRangeSize(l)<=u&&getRangeSize(c)<=h){if(!isRangeSafe(l,e.length)&&isRangeSafe(c,r.length))return NaN;let o;if(t&&n)o=lineToLineDistance(e,l,r,c,i),s=Math.min(s,o);else if(t&&!n){const t=e.slice(l[0],l[1]+1);for(let e=c[0];e<=c[1];++e)if(o=pointToLineDistance(r[e],t,i),s=Math.min(s,o),0===s)return s}else if(!t&&n){const t=r.slice(c[0],c[1]+1);for(let r=l[0];r<=l[1];++r)if(o=pointToLineDistance(e[r],t,i),s=Math.min(s,o),0===s)return s}else o=pointsToPointsDistance(e,l,r,c,i),s=Math.min(s,o)}else{const o=splitRange(l,t),u=splitRange(c,n);updateQueueTwoSets(a,s,i,e,r,o[0],u[0]),updateQueueTwoSets(a,s,i,e,r,o[0],u[1]),updateQueueTwoSets(a,s,i,e,r,o[1],u[0]),updateQueueTwoSets(a,s,i,e,r,o[1],u[1])}}return s}function pointToGeometryDistance(e,t){const r=e.geometry(),n=r.flat().map(t=>getLngLatFromTileCoord([t.x,t.y],e.canonical));if(0===r.length)return NaN;const i=new CheapRuler(n[0][1]);let o=1/0;for(const s of t){switch(s.type){case"Point":o=Math.min(o,pointSetToPointSetDistance(n,!1,[s.coordinates],!1,i,o));break;case"LineString":o=Math.min(o,pointSetToPointSetDistance(n,!1,s.coordinates,!0,i,o));break;case"Polygon":o=Math.min(o,pointsToPolygonDistance(n,!1,s.coordinates,i,o))}if(0===o)return o}return o}function lineStringToGeometryDistance(e,t){const r=e.geometry(),n=r.flat().map(t=>getLngLatFromTileCoord([t.x,t.y],e.canonical));if(0===r.length)return NaN;const i=new CheapRuler(n[0][1]);let o=1/0;for(const s of t){switch(s.type){case"Point":o=Math.min(o,pointSetToPointSetDistance(n,!0,[s.coordinates],!1,i,o));break;case"LineString":o=Math.min(o,pointSetToPointSetDistance(n,!0,s.coordinates,!0,i,o));break;case"Polygon":o=Math.min(o,pointsToPolygonDistance(n,!0,s.coordinates,i,o))}if(0===o)return o}return o}function polygonToGeometryDistance(e,t){const r=e.geometry();if(0===r.length||0===r[0].length)return NaN;const n=classifyRings(r).map(t=>t.map(t=>t.map(t=>getLngLatFromTileCoord([t.x,t.y],e.canonical)))),i=new CheapRuler(n[0][0][0][1]);let o=1/0;for(const s of t)for(const e of n){switch(s.type){case"Point":o=Math.min(o,pointsToPolygonDistance([s.coordinates],!1,e,i,o));break;case"LineString":o=Math.min(o,pointsToPolygonDistance(s.coordinates,!0,e,i,o));break;case"Polygon":o=Math.min(o,polygonToPolygonDistance(e,s.coordinates,i,o))}if(0===o)return o}return o}function toSimpleGeometry(e){return"MultiPolygon"===e.type?e.coordinates.map(e=>({type:"Polygon",coordinates:e})):"MultiLineString"===e.type?e.coordinates.map(e=>({type:"LineString",coordinates:e})):"MultiPoint"===e.type?e.coordinates.map(e=>({type:"Point",coordinates:e})):[e]}class Distance{constructor(e,t){this.type=NumberType,this.geojson=e,this.geometries=t}static parse(e,t){if(2!==e.length)return t.error(`'distance' expression requires exactly one argument, but found ${e.length-1} instead.`);if(isValue(e[1])){const t=e[1];if("FeatureCollection"===t.type)return new Distance(t,t.features.map(e=>toSimpleGeometry(e.geometry)).flat());if("Feature"===t.type)return new Distance(t,toSimpleGeometry(t.geometry));if("type"in t&&"coordinates"in t)return new Distance(t,toSimpleGeometry(t))}return t.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(e){if(null!=e.geometry()&&null!=e.canonicalID()){if("Point"===e.geometryType())return pointToGeometryDistance(e,this.geometries);if("LineString"===e.geometryType())return lineStringToGeometryDistance(e,this.geometries);if("Polygon"===e.geometryType())return polygonToGeometryDistance(e,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}class GlobalState{constructor(e){this.type=ValueType,this.key=e}static parse(e,t){if(2!==e.length)return t.error(`Expected 1 argument, but found ${e.length-1} instead.`);const r=e[1];return null==r?t.error("Global state property must be defined."):"string"!=typeof r?t.error(`Global state property must be string, but found ${typeof e[1]} instead.`):new GlobalState(r)}evaluate(e){var t;const r=null===(t=e.globals)||void 0===t?void 0:t.globalState;return r&&0!==Object.keys(r).length?getOwn(r,this.key):null}eachChild(){}outputDefined(){return!1}}const expressions$1={"==":Equals,"!=":NotEquals,">":GreaterThan,"<":LessThan,">=":GreaterThanOrEqual,"<=":LessThanOrEqual,array:Assertion,at:At,boolean:Assertion,case:Case,coalesce:Coalesce,collator:CollatorExpression,format:FormatExpression,image:ImageExpression,in:In,"index-of":IndexOf,interpolate:Interpolate,"interpolate-hcl":Interpolate,"interpolate-lab":Interpolate,length:Length,let:Let,literal:Literal,match:Match,number:Assertion,"number-format":NumberFormat,object:Assertion,slice:Slice,step:Step,string:Assertion,"to-boolean":Coercion,"to-color":Coercion,"to-number":Coercion,"to-string":Coercion,var:Var,within:Within,distance:Distance,"global-state":GlobalState};class CompoundExpression{constructor(e,t,r,n){this.name=e,this.type=t,this._evaluate=r,this.args=n}evaluate(e){return this._evaluate(e,this.args)}eachChild(e){this.args.forEach(e)}outputDefined(){return!1}static parse(e,t){const r=e[0],n=CompoundExpression.definitions[r];if(!n)return t.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,o=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,s=o.filter(([t])=>!Array.isArray(t)||t.length===e.length-1);let a=null;for(const[l,c]of s){a=new ParsingContext(t.registry,isExpressionConstant,t.path,null,t.scope);const n=[];let o=!1;for(let t=1;tstringifySignature(e)).join(" | "),n=[];for(let i=1;i>1;if(t[i]===e)return!0;t[i]>e?n=i-1:r=i+1}return!1}function varargs(e){return{type:e}}function stringifySignature(e){return Array.isArray(e)?`(${e.map(typeToString).join(", ")})`:`(${typeToString(e.type)}...)`}function isExpressionConstant(e){if(e instanceof Var)return isExpressionConstant(e.boundExpression);if(e instanceof CompoundExpression&&"error"===e.name)return!1;if(e instanceof CollatorExpression)return!1;if(e instanceof Within)return!1;if(e instanceof Distance)return!1;if(e instanceof GlobalState)return!1;const t=e instanceof Coercion||e instanceof Assertion;let r=!0;return e.eachChild(e=>{r=t?r&&isExpressionConstant(e):r&&e instanceof Literal}),!!r&&isFeatureConstant(e)&&isGlobalPropertyConstant(e,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function isFeatureConstant(e){if(e instanceof CompoundExpression){if("get"===e.name&&1===e.args.length)return!1;if("feature-state"===e.name)return!1;if("has"===e.name&&1===e.args.length)return!1;if("properties"===e.name||"geometry-type"===e.name||"id"===e.name)return!1;if(/^filter-/.test(e.name))return!1}if(e instanceof Within)return!1;if(e instanceof Distance)return!1;let t=!0;return e.eachChild(e=>{t&&!isFeatureConstant(e)&&(t=!1)}),t}function isStateConstant(e){if(e instanceof CompoundExpression&&"feature-state"===e.name)return!1;let t=!0;return e.eachChild(e=>{t&&!isStateConstant(e)&&(t=!1)}),t}function isGlobalPropertyConstant(e,t){if(e instanceof CompoundExpression&&t.indexOf(e.name)>=0)return!1;let r=!0;return e.eachChild(e=>{r&&!isGlobalPropertyConstant(e,t)&&(r=!1)}),r}function success(e){return{result:"success",value:e}}function error(e){return{result:"error",value:e}}function supportsPropertyExpression(e){return"data-driven"===e["property-type"]||"cross-faded-data-driven"===e["property-type"]}function supportsZoomExpression(e){return!!e.expression&&e.expression.parameters.indexOf("zoom")>-1}function supportsInterpolation(e){return!!e.expression&&e.expression.interpolated}function isFunction$1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&typeOf(e)===ObjectType}CompoundExpression.register(expressions$1,{error:[ErrorType,[StringType],(e,[t])=>{throw new RuntimeError(t.evaluate(e))}],typeof:[StringType,[ValueType],(e,[t])=>typeToString(typeOf(t.evaluate(e)))],"to-rgba":[array(NumberType,4),[ColorType],(e,[t])=>{const[r,n,i,o]=t.evaluate(e).rgb;return[255*r,255*n,255*i,o]}],rgb:[ColorType,[NumberType,NumberType,NumberType],rgba],rgba:[ColorType,[NumberType,NumberType,NumberType,NumberType],rgba],has:{type:BooleanType,overloads:[[[StringType],(e,[t])=>has(t.evaluate(e),e.properties())],[[StringType,ObjectType],(e,[t,r])=>has(t.evaluate(e),r.evaluate(e))]]},get:{type:ValueType,overloads:[[[StringType],(e,[t])=>get(t.evaluate(e),e.properties())],[[StringType,ObjectType],(e,[t,r])=>get(t.evaluate(e),r.evaluate(e))]]},"feature-state":[ValueType,[StringType],(e,[t])=>get(t.evaluate(e),e.featureState||{})],properties:[ObjectType,[],e=>e.properties()],"geometry-type":[StringType,[],e=>e.geometryType()],id:[ValueType,[],e=>e.id()],zoom:[NumberType,[],e=>e.globals.zoom],"heatmap-density":[NumberType,[],e=>e.globals.heatmapDensity||0],elevation:[NumberType,[],e=>e.globals.elevation||0],"line-progress":[NumberType,[],e=>e.globals.lineProgress||0],accumulated:[ValueType,[],e=>void 0===e.globals.accumulated?null:e.globals.accumulated],"+":[NumberType,varargs(NumberType),(e,t)=>{let r=0;for(const n of t)r+=n.evaluate(e);return r}],"*":[NumberType,varargs(NumberType),(e,t)=>{let r=1;for(const n of t)r*=n.evaluate(e);return r}],"-":{type:NumberType,overloads:[[[NumberType,NumberType],(e,[t,r])=>t.evaluate(e)-r.evaluate(e)],[[NumberType],(e,[t])=>-t.evaluate(e)]]},"/":[NumberType,[NumberType,NumberType],(e,[t,r])=>t.evaluate(e)/r.evaluate(e)],"%":[NumberType,[NumberType,NumberType],(e,[t,r])=>t.evaluate(e)%r.evaluate(e)],ln2:[NumberType,[],()=>Math.LN2],pi:[NumberType,[],()=>Math.PI],e:[NumberType,[],()=>Math.E],"^":[NumberType,[NumberType,NumberType],(e,[t,r])=>Math.pow(t.evaluate(e),r.evaluate(e))],sqrt:[NumberType,[NumberType],(e,[t])=>Math.sqrt(t.evaluate(e))],log10:[NumberType,[NumberType],(e,[t])=>Math.log(t.evaluate(e))/Math.LN10],ln:[NumberType,[NumberType],(e,[t])=>Math.log(t.evaluate(e))],log2:[NumberType,[NumberType],(e,[t])=>Math.log(t.evaluate(e))/Math.LN2],sin:[NumberType,[NumberType],(e,[t])=>Math.sin(t.evaluate(e))],cos:[NumberType,[NumberType],(e,[t])=>Math.cos(t.evaluate(e))],tan:[NumberType,[NumberType],(e,[t])=>Math.tan(t.evaluate(e))],asin:[NumberType,[NumberType],(e,[t])=>Math.asin(t.evaluate(e))],acos:[NumberType,[NumberType],(e,[t])=>Math.acos(t.evaluate(e))],atan:[NumberType,[NumberType],(e,[t])=>Math.atan(t.evaluate(e))],min:[NumberType,varargs(NumberType),(e,t)=>Math.min(...t.map(t=>t.evaluate(e)))],max:[NumberType,varargs(NumberType),(e,t)=>Math.max(...t.map(t=>t.evaluate(e)))],abs:[NumberType,[NumberType],(e,[t])=>Math.abs(t.evaluate(e))],round:[NumberType,[NumberType],(e,[t])=>{const r=t.evaluate(e);return r<0?-Math.round(-r):Math.round(r)}],floor:[NumberType,[NumberType],(e,[t])=>Math.floor(t.evaluate(e))],ceil:[NumberType,[NumberType],(e,[t])=>Math.ceil(t.evaluate(e))],"filter-==":[BooleanType,[StringType,ValueType],(e,[t,r])=>e.properties()[t.value]===r.value],"filter-id-==":[BooleanType,[ValueType],(e,[t])=>e.id()===t.value],"filter-type-==":[BooleanType,[StringType],(e,[t])=>e.geometryType()===t.value],"filter-<":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n{const r=e.id(),n=t.value;return typeof r==typeof n&&r":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[BooleanType,[ValueType],(e,[t])=>{const r=e.id(),n=t.value;return typeof r==typeof n&&r>n}],"filter-<=":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[BooleanType,[ValueType],(e,[t])=>{const r=e.id(),n=t.value;return typeof r==typeof n&&r<=n}],"filter->=":[BooleanType,[StringType,ValueType],(e,[t,r])=>{const n=e.properties()[t.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[BooleanType,[ValueType],(e,[t])=>{const r=e.id(),n=t.value;return typeof r==typeof n&&r>=n}],"filter-has":[BooleanType,[ValueType],(e,[t])=>t.value in e.properties()],"filter-has-id":[BooleanType,[],e=>null!==e.id()&&void 0!==e.id()],"filter-type-in":[BooleanType,[array(StringType)],(e,[t])=>t.value.indexOf(e.geometryType())>=0],"filter-id-in":[BooleanType,[array(ValueType)],(e,[t])=>t.value.indexOf(e.id())>=0],"filter-in-small":[BooleanType,[StringType,array(ValueType)],(e,[t,r])=>r.value.indexOf(e.properties()[t.value])>=0],"filter-in-large":[BooleanType,[StringType,array(ValueType)],(e,[t,r])=>binarySearch(e.properties()[t.value],r.value,0,r.value.length-1)],all:{type:BooleanType,overloads:[[[BooleanType,BooleanType],(e,[t,r])=>t.evaluate(e)&&r.evaluate(e)],[varargs(BooleanType),(e,t)=>{for(const r of t)if(!r.evaluate(e))return!1;return!0}]]},any:{type:BooleanType,overloads:[[[BooleanType,BooleanType],(e,[t,r])=>t.evaluate(e)||r.evaluate(e)],[varargs(BooleanType),(e,t)=>{for(const r of t)if(r.evaluate(e))return!0;return!1}]]},"!":[BooleanType,[BooleanType],(e,[t])=>!t.evaluate(e)],"is-supported-script":[BooleanType,[StringType],(e,[t])=>{const r=e.globals&&e.globals.isSupportedScript;return!r||r(t.evaluate(e))}],upcase:[StringType,[StringType],(e,[t])=>t.evaluate(e).toUpperCase()],downcase:[StringType,[StringType],(e,[t])=>t.evaluate(e).toLowerCase()],concat:[StringType,varargs(ValueType),(e,t)=>t.map(t=>valueToString(t.evaluate(e))).join("")],"resolved-locale":[StringType,[CollatorType],(e,[t])=>t.evaluate(e).resolvedLocale()]});class StyleExpression{constructor(e,t){this.expression=e,this._warningHistory={},this._evaluator=new EvaluationContext,this._defaultValue=t?getDefaultValue(t):null,this._enumValues=t&&"enum"===t.type?t.values:null}evaluateWithoutErrorHandling(e,t,r,n,i,o){return this._evaluator.globals=e,this._evaluator.feature=t,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=o,this.expression.evaluate(this._evaluator)}evaluate(e,t,r,n,i,o){this._evaluator.globals=e,this._evaluator.feature=t||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=o||null;try{const e=this.expression.evaluate(this._evaluator);if(null==e||"number"==typeof e&&e!=e)return this._defaultValue;if(this._enumValues&&!(e in this._enumValues))throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(e=>JSON.stringify(e)).join(", ")}, but found ${JSON.stringify(e)} instead.`);return e}catch(s){return this._warningHistory[s.message]||(this._warningHistory[s.message]=!0,"undefined"!=typeof console&&console.warn(s.message)),this._defaultValue}}}function isExpression(e){return Array.isArray(e)&&e.length>0&&"string"==typeof e[0]&&e[0]in expressions$1}function createExpression(e,t){const r=new ParsingContext(expressions$1,isExpressionConstant,[],t?getExpectedType(t):void 0),n=r.parse(e,void 0,void 0,void 0,t&&"string"===t.type?{typeAnnotation:"coerce"}:void 0);return n?success(new StyleExpression(n,t)):error(r.errors)}class ZoomConstantExpression{constructor(e,t){this.kind=e,this._styleExpression=t,this.isStateDependent="constant"!==e&&!isStateConstant(t.expression),this.globalStateRefs=findGlobalStateRefs(t.expression)}evaluateWithoutErrorHandling(e,t,r,n,i,o){return this._styleExpression.evaluateWithoutErrorHandling(e,t,r,n,i,o)}evaluate(e,t,r,n,i,o){return this._styleExpression.evaluate(e,t,r,n,i,o)}}class ZoomDependentExpression{constructor(e,t,r,n){this.kind=e,this.zoomStops=r,this._styleExpression=t,this.isStateDependent="camera"!==e&&!isStateConstant(t.expression),this.globalStateRefs=findGlobalStateRefs(t.expression),this.interpolationType=n}evaluateWithoutErrorHandling(e,t,r,n,i,o){return this._styleExpression.evaluateWithoutErrorHandling(e,t,r,n,i,o)}evaluate(e,t,r,n,i,o){return this._styleExpression.evaluate(e,t,r,n,i,o)}interpolationFactor(e,t,r){return this.interpolationType?Interpolate.interpolationFactor(this.interpolationType,e,t,r):0}}function createPropertyExpression(e,t){const r=createExpression(e,t);if("error"===r.result)return r;const n=r.value.expression,i=isFeatureConstant(n);if(!i&&!supportsPropertyExpression(t))return error([new ExpressionParsingError("","data expressions not supported")]);const o=isGlobalPropertyConstant(n,["zoom"]);if(!o&&!supportsZoomExpression(t))return error([new ExpressionParsingError("","zoom expressions not supported")]);const s=findZoomCurve(n);if(!s&&!o)return error([new ExpressionParsingError("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);if(s instanceof ExpressionParsingError)return error([s]);if(s instanceof Interpolate&&!supportsInterpolation(t))return error([new ExpressionParsingError("",'"interpolate" expressions cannot be used with this property')]);if(!s)return success(new ZoomConstantExpression(i?"constant":"source",r.value));const a=s instanceof Interpolate?s.interpolation:void 0;return success(new ZoomDependentExpression(i?"camera":"composite",r.value,s.labels,a))}function findZoomCurve(e){let t=null;if(e instanceof Let)t=findZoomCurve(e.result);else if(e instanceof Coalesce){for(const r of e.args)if(t=findZoomCurve(r),t)break}else(e instanceof Step||e instanceof Interpolate)&&e.input instanceof CompoundExpression&&"zoom"===e.input.name&&(t=e);return t instanceof ExpressionParsingError||e.eachChild(e=>{const r=findZoomCurve(e);r instanceof ExpressionParsingError?t=r:!t&&r?t=new ExpressionParsingError("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):t&&r&&t!==r&&(t=new ExpressionParsingError("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),t}function findGlobalStateRefs(e,t=new Set){return e instanceof GlobalState&&t.add(e.key),e.eachChild(e=>{findGlobalStateRefs(e,t)}),t}function getExpectedType(e){const t={color:ColorType,string:StringType,number:NumberType,enum:StringType,boolean:BooleanType,formatted:FormattedType,padding:PaddingType,numberArray:NumberArrayType,colorArray:ColorArrayType,projectionDefinition:ProjectionDefinitionType,resolvedImage:ResolvedImageType,variableAnchorOffsetCollection:VariableAnchorOffsetCollectionType};return"array"===e.type?array(t[e.value]||ValueType,e.length):t[e.type]}function getDefaultValue(e){if("color"===e.type&&isFunction$1(e.default))return new Color(0,0,0,0);switch(e.type){case"color":return Color.parse(e.default)||null;case"padding":return Padding.parse(e.default)||null;case"numberArray":return NumberArray.parse(e.default)||null;case"colorArray":return ColorArray.parse(e.default)||null;case"variableAnchorOffsetCollection":return VariableAnchorOffsetCollection.parse(e.default)||null;case"projectionDefinition":return ProjectionDefinition.parse(e.default)||null;default:return void 0===e.default?null:e.default}}function isExpressionFilter(e){if(!0===e||!1===e)return!0;if(!Array.isArray(e)||0===e.length)return!1;switch(e[0]){case"has":return e.length>=2&&"$id"!==e[1]&&"$type"!==e[1];case"in":return e.length>=3&&("string"!=typeof e[1]||Array.isArray(e[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==e.length||Array.isArray(e[1])||Array.isArray(e[2]);case"any":case"all":for(const t of e.slice(1))if(!isExpressionFilter(t)&&"boolean"!=typeof t)return!1;return!0;default:return!0}}const filterSpec={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function featureFilter(e){if(null==e)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};isExpressionFilter(e)||(e=convertFilter$1(e));const t=createExpression(e,filterSpec);if("error"===t.result)throw new Error(t.value.map(e=>`${e.key}: ${e.message}`).join(", "));return{filter:(e,r,n)=>t.value.evaluate(e,r,{},n),needGeometry:geometryNeeded(e),getGlobalStateRefs:()=>findGlobalStateRefs(t.value.expression)}}function compare(e,t){return et?1:0}function geometryNeeded(e){if(!Array.isArray(e))return!1;if("within"===e[0]||"distance"===e[0])return!0;for(let t=1;t"===t||"<="===t||">="===t?convertComparisonOp$1(e[1],e[2],t):"any"===t?convertDisjunctionOp(e.slice(1)):"all"===t?["all"].concat(e.slice(1).map(convertFilter$1)):"none"===t?["all"].concat(e.slice(1).map(convertFilter$1).map(convertNegation)):"in"===t?convertInOp$1(e[1],e.slice(2)):"!in"===t?convertNegation(convertInOp$1(e[1],e.slice(2))):"has"===t?convertHasOp$1(e[1]):"!has"!==t||convertNegation(convertHasOp$1(e[1]))}function convertComparisonOp$1(e,t,r){switch(e){case"$type":return[`filter-type-${r}`,t];case"$id":return[`filter-id-${r}`,t];default:return[`filter-${r}`,e,t]}}function convertDisjunctionOp(e){return["any"].concat(e.map(convertFilter$1))}function convertInOp$1(e,t){if(0===t.length)return!1;switch(e){case"$type":return["filter-type-in",["literal",t]];case"$id":return["filter-id-in",["literal",t]];default:return t.length>200&&!t.some(e=>typeof e!=typeof t[0])?["filter-in-large",e,["literal",t.sort(compare)]]:["filter-in-small",e,["literal",t]]}}function convertHasOp$1(e){switch(e){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",e]}}function convertNegation(e){return["!",e]}function convertLiteral(e){return"object"==typeof e?["literal",e]:e}function convertFunction(e,t){let r=e.stops;if(!r)return convertIdentityFunction(e,t);const n=r&&"object"==typeof r[0][0],i=n||void 0!==e.property,o=n||!i;return r=r.map(e=>!i&&t.tokens&&"string"==typeof e[1]?[e[0],convertTokenString(e[1])]:[e[0],convertLiteral(e[1])]),n?convertZoomAndPropertyFunction(e,t,r):o?convertZoomFunction(e,t,r):convertPropertyFunction(e,t,r)}function convertIdentityFunction(e,t){const r=["get",e.property];if(void 0===e.default)return"string"===t.type?["string",r]:r;if("enum"===t.type)return["match",r,Object.keys(t.values),r,e.default];{const n=["color"===t.type?"to-color":t.type,r,convertLiteral(e.default)];return"array"===t.type&&n.splice(1,0,t.value,t.length||null),n}}function getInterpolateOperator(e){switch(e.colorSpace){case"hcl":return"interpolate-hcl";case"lab":return"interpolate-lab";default:return"interpolate"}}function convertZoomAndPropertyFunction(e,t,r){const n={},i={},o=[];for(let s=0;s3&&t===e[e.length-2]||(n&&2===e.length||e.push(t),e.push(r))}function getFunctionType(e,t){return e.type?e.type:t.expression.interpolated?"exponential":"interval"}function convertTokenString(e){const t=["concat"],r=/{([^{}]+)}/g;let n=0;for(let i=r.exec(e);null!==i;i=r.exec(e)){const o=e.slice(n,r.lastIndex-i[0].length);n=r.lastIndex,o.length>0&&t.push(o),t.push(["get",i[1]])}if(1===t.length)return e;if(n1?h[h.length-2].toLowerCase():"";if(d==p||d==p.replace("-","")||f+"-"+d==p){s=i?s:fontWeights[p],h.pop(),f&&p.startsWith(f)&&h.pop();break}}i||"number"!=typeof d||(s=d,i=!0);var g=h.join(sp).replace("Klokantech Noto Sans","Noto Sans").replace("DIN Pro","Barlow").replace("Arial Unicode MS","Arial");-1!==g.indexOf(sp)&&(g='"'+g+'"'),l.push(g)}n=fontCache[e]=[a,s,l]}return n[0]+sp+n[1]+sp+t+"px"+(r?"/"+r:"")+sp+n[2]}class ImageCanvas extends ImageWrapper{constructor(e,t,r,n,i){super(e,t,r,void 0!==i?ImageState.IDLE:ImageState.LOADED),this.loader_=void 0!==i?i:null,this.canvas_=n,this.error_=null}getError(){return this.error_}handleLoad_(e){e?(this.error_=e,this.state=ImageState.ERROR):this.state=ImageState.LOADED,this.changed()}load(){this.state==ImageState.IDLE&&(this.state=ImageState.LOADING,this.changed(),this.loader_(this.handleLoad_.bind(this)))}getImage(){return this.canvas_}}class Tile extends Target{constructor(e,t,r){super(),r=r||{},this.tileCoord=e,this.state=t,this.key="",this.transition_=void 0===r.transition?250:r.transition,this.transitionStarts_={},this.interpolate=!!r.interpolate}changed(){this.dispatchEvent(EventType$1.CHANGE)}release(){this.setState(TileState.EMPTY)}getKey(){return this.key+"/"+this.tileCoord}getTileCoord(){return this.tileCoord}getState(){return this.state}setState(e){if(this.state!==TileState.EMPTY){if(this.state!==TileState.ERROR&&this.state>e)throw new Error("Tile load sequence violation");this.state=e,this.changed()}}load(){abstract()}getAlpha(e,t){if(!this.transition_)return 1;let r=this.transitionStarts_[e];if(r){if(-1===r)return 1}else r=t,this.transitionStarts_[e]=r;const n=t-r+1e3/60;return n>=this.transition_?1:easeIn(n/this.transition_)}inTransition(e){return!!this.transition_&&-1!==this.transitionStarts_[e]}endTransition(e){this.transition_&&(this.transitionStarts_[e]=-1)}disposeInternal(){this.release(),super.disposeInternal()}}class ImageTile extends Tile{constructor(e,t,r,n,i,o){super(e,t,o),this.crossOrigin_=n,this.src_=r,this.key=r,this.image_,WORKER_OFFSCREEN_CANVAS?this.image_=new OffscreenCanvas(1,1):(this.image_=new Image,null!==n&&(this.image_.crossOrigin=n)),this.unlisten_=null,this.tileLoadFunction_=i}getImage(){return this.image_}setImage(e){this.image_=e,this.state=TileState.LOADED,this.unlistenImage_(),this.changed()}getCrossOrigin(){return this.crossOrigin_}handleImageError_(){this.state=TileState.ERROR,this.unlistenImage_(),this.image_=getBlankImage(),this.changed()}handleImageLoad_(){if(WORKER_OFFSCREEN_CANVAS)this.state=TileState.LOADED;else{const e=this.image_;e.naturalWidth&&e.naturalHeight?this.state=TileState.LOADED:this.state=TileState.EMPTY}this.unlistenImage_(),this.changed()}load(){this.state==TileState.ERROR&&(this.state=TileState.IDLE,this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)),this.state==TileState.IDLE&&(this.state=TileState.LOADING,this.changed(),this.tileLoadFunction_(this,this.src_),this.unlisten_=listenImage(this.image_,this.handleImageLoad_.bind(this),this.handleImageError_.bind(this)))}unlistenImage_(){this.unlisten_&&(this.unlisten_(),this.unlisten_=null)}disposeInternal(){this.unlistenImage_(),this.image_=null,super.disposeInternal()}}function getBlankImage(){const e=createCanvasContext2D(1,1);return e.fillStyle="rgba(0,0,0,0)",e.fillRect(0,0,1,1),e.canvas}class TileRange{constructor(e,t,r,n){this.minX=e,this.maxX=t,this.minY=r,this.maxY=n}contains(e){return this.containsXY(e[1],e[2])}containsTileRange(e){return this.minX<=e.minX&&e.maxX<=this.maxX&&this.minY<=e.minY&&e.maxY<=this.maxY}containsXY(e,t){return this.minX<=e&&e<=this.maxX&&this.minY<=t&&t<=this.maxY}equals(e){return this.minX==e.minX&&this.minY==e.minY&&this.maxX==e.maxX&&this.maxY==e.maxY}extend(e){e.minXthis.maxX&&(this.maxX=e.maxX),e.minYthis.maxY&&(this.maxY=e.maxY)}getHeight(){return this.maxY-this.minY+1}getSize(){return[this.getWidth(),this.getHeight()]}getWidth(){return this.maxX-this.minX+1}intersects(e){return this.minX<=e.maxX&&this.maxX>=e.minX&&this.minY<=e.maxY&&this.maxY>=e.minY}}function createOrUpdate$1(e,t,r,n,i){return void 0!==i?(i.minX=e,i.maxX=t,i.minY=r,i.maxY=n,i):new TileRange(e,t,r,n)}const canvasPool$1=[];class VectorRenderTile extends Tile{constructor(e,t,r,n,i){super(e,t,{transition:0}),this.context_=null,this.executorGroups={},this.loadingSourceTiles=0,this.hitDetectionImageData={},this.replayState_={},this.sourceTiles=[],this.errorTileKeys={},this.wantedResolution,this.getSourceTiles=n.bind(void 0,this),this.removeSourceTiles_=i,this.wrappedTileCoord=r}getContext(){return this.context_||(this.context_=createCanvasContext2D(1,1,canvasPool$1)),this.context_}hasContext(){return!!this.context_}getImage(){return this.hasContext()?this.getContext().canvas:null}getReplayState(e){const t=getUid(e);return t in this.replayState_||(this.replayState_[t]={dirty:!1,renderedRenderOrder:null,renderedResolution:NaN,renderedRevision:-1,renderedTileResolution:NaN,renderedTileRevision:-1,renderedTileZ:-1}),this.replayState_[t]}load(){this.getSourceTiles()}release(){this.context_&&(releaseCanvas(this.context_),canvasPool$1.push(this.context_.canvas),this.context_=null),this.removeSourceTiles_(this),this.sourceTiles.length=0,super.release()}}let VectorTile$1=class extends Tile{constructor(e,t,r,n,i,o){super(e,t,o),this.extent=null,this.format_=n,this.features_=null,this.loader_,this.projection=null,this.resolution,this.tileLoadFunction_=i,this.url_=r,this.key=r}getTileUrl(){return this.url_}getFormat(){return this.format_}getFeatures(){return this.features_}load(){this.state==TileState.IDLE&&(this.setState(TileState.LOADING),this.tileLoadFunction_(this,this.url_),this.loader_&&this.loader_(this.extent,this.resolution,this.projection))}onLoad(e,t){this.setFeatures(e)}onError(){this.setState(TileState.ERROR)}setFeatures(e){this.features_=e,this.setState(TileState.LOADED)}setLoader(e){this.loader_=e}};const mapboxBaseUrl="https://api.mapbox.com";function getMapboxPath(e){return 0!==e.indexOf("mapbox://")?"":e.slice(9)}function normalizeSpriteDefinition(e,t,r){if("string"==typeof e)return[{id:"default",url:normalizeSpriteUrl(e,t,r)}];for(const n of e)n.url=normalizeSpriteUrl(n.url,t,r);return e}function normalizeSpriteUrl(e,t,r){const n=getMapboxPath(e);if(!n)return decodeURI(new URL(e,r).href);if(0!==n.indexOf("sprites/"))throw new Error(`unexpected sprites url: ${e}`);const i=n.slice(8);return`${mapboxBaseUrl}/styles/v1/${i}/sprite?access_token=${t}`}function normalizeStyleUrl(e,t){const r=getMapboxPath(e);if(!r)return decodeURI(new URL(e,location.href).href);if(0!==r.indexOf("styles/"))throw new Error(`unexpected style url: ${e}`);const n=r.slice(7);return`${mapboxBaseUrl}/styles/v1/${n}?&access_token=${t}`}const mapboxSubdomains=["a","b","c","d"];function normalizeSourceUrl(e,t,r,n){const i=new URL(e,n||location.href),o=getMapboxPath(e);if(!o)return t?(i.searchParams.has(r)||i.searchParams.set(r,t),[decodeURI(i.href)]):[decodeURI(i.href)];if("mapbox.satellite"===o){const e=window.devicePixelRatio>=1.5?"@2x":"";return[`https://api.mapbox.com/v4/${o}/{z}/{x}/{y}${e}.webp?access_token=${t}`]}return mapboxSubdomains.map(e=>`https://${e}.tiles.mapbox.com/v4/${o}/{z}/{x}/{y}.vector.pbf?access_token=${t}`)}const emptyObj=Object.freeze({}),functionCacheByStyleId={},filterCacheByStyleId={};let styleId=0;function getStyleId(e){return e.id||(e.id=styleId++),e.id}function getStyleFunctionKey(e,t){return getStyleId(e)+"."+getUid(t)}function getFunctionCache(e){let t=functionCacheByStyleId[e.id];return t||(t={},functionCacheByStyleId[getStyleId(e)]=t),t}function getFilterCache(e){let t=filterCacheByStyleId[e.id];return t||(t={},filterCacheByStyleId[getStyleId(e)]=t),t}function deg2rad(e){return e*Math.PI/180}const defaultResolutions=function(){const e=[];for(let t=78271.51696402048;e.length<=24;t/=2)e.push(t);return e}();function createCanvas(e,t){if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,t);const r=document.createElement("canvas");return r.width=e,r.height=t,r}function getZoomForResolution(e,t){let r=0;const n=t.length;for(;ri).then(e=>e instanceof Response?(n&&(n.url=e.url),s(e)):(e instanceof Request||(e=new Request(e)),e.headers.get("Accept")||e.headers.set("Accept","application/json"),n&&(n.url=e.url),fetch(e).then(s).catch(o))).catch(o);return pendingRequests[t]=[i,a],a}function getGlStyle(e,t){if("string"!=typeof e)return Promise.resolve(e);if(!e.trim().startsWith("{"))return fetchResource("Style",e=normalizeStyleUrl(e,t.accessToken),t);try{const t=JSON.parse(e);return Promise.resolve(t)}catch(error){return Promise.reject(error)}}const tilejsonCache={};function getTileJson(e,t,r={}){const n=[t,JSON.stringify(e)].toString();let i=tilejsonCache[n];if(!i||r.transformRequest){let o;r.transformRequest&&(o=(e,t)=>{const n=r.transformRequest&&r.transformRequest(t,"Tiles")||t;if(e instanceof VectorTile$1)e.setLoader((t,r,i)=>{const o=function(r){r.arrayBuffer().then(r=>{const n=e.getFormat().readFeatures(r,{extent:t,featureProjection:i});e.setFeatures(n)})};toPromise(()=>n).then(t=>{if(t instanceof Response)return o(t);fetch(t).then(o).catch(()=>e.setState(TileState.ERROR))}).catch(()=>e.setState(TileState.ERROR))});else{const t=e.getImage();toPromise(()=>n).then(r=>{if("string"==typeof r)return void(t.src=r);const n=e=>e.blob().then(e=>{const r=URL.createObjectURL(e);t.addEventListener("load",()=>URL.revokeObjectURL(r)),t.addEventListener("error",()=>URL.revokeObjectURL(r)),t.src=r});if(r instanceof Response)return n(r);fetch(r).then(n).catch(()=>e.setState(TileState.ERROR))}).catch(()=>e.setState(TileState.ERROR))}});const s=e.url;if(s&&!e.tiles){const n=normalizeSourceUrl(s,r.accessToken,r.accessTokenParam||"access_token",t||location.href);if(s.startsWith("mapbox://"))i=Promise.resolve({tileJson:Object.assign({},e,{url:void 0,tiles:n}),tileLoadFunction:o});else{const e={};i=fetchResource("Source",n[0],r,e).then(function(t){return t.tiles=t.tiles.map(function(n){return"tms"===t.scheme&&(n=n.replace("{y}","{-y}")),normalizeSourceUrl(n,r.accessToken,r.accessTokenParam||"access_token",e.url)[0]}),Promise.resolve({tileJson:t,tileLoadFunction:o})})}}else e.tiles?(e=Object.assign({},e,{tiles:e.tiles.map(function(n){return"tms"===e.scheme&&(n=n.replace("{y}","{-y}")),normalizeSourceUrl(n,r.accessToken,r.accessTokenParam||"access_token",t||location.href)[0]})}),i=Promise.resolve({tileJson:Object.assign({},e),tileLoadFunction:o})):i=Promise.reject(new Error("source has no `tiles` nor `url`"));tilejsonCache[n]=i}return i}function drawIconHalo(e,t,r,n){const i=[2*r*t.pixelRatio+t.width,2*r*t.pixelRatio+t.height],o=createCanvas(i[0],i[1]),s=o.getContext("2d");s.drawImage(e,t.x,t.y,t.width,t.height,r*t.pixelRatio,r*t.pixelRatio,t.width,t.height);const a=s.getImageData(0,0,i[0],i[1]);s.globalCompositeOperation="destination-over",s.fillStyle=`rgba(${255*n.r},${255*n.g},${255*n.b},${n.a})`;const l=a.data;for(let c=0,u=a.width;c0&&s.arc(c,e,r*t.pixelRatio,0,2*Math.PI);return s.fill(),o}function smoothstep(e,t,r){const n=Math.max(0,Math.min(1,(r-e)/(t-e)));return n*n*(3-2*n)}function drawSDF(e,t,r){const n=createCanvas(t.width,t.height),i=n.getContext("2d");i.drawImage(e,t.x,t.y,t.width,t.height,0,0,t.width,t.height);const o=i.getImageData(0,0,t.width,t.height),s=o.data;for(let a=0,l=o.width;a0?(s[t+0]=Math.round(255*r.r*o),s[t+1]=Math.round(255*r.g*o),s[t+2]=Math.round(255*r.b*o),s[t+3]=Math.round(255*o)):s[t+3]=0}return i.putImageData(o,0,0),n}const hairSpacePool=Array(256).join(" ");function applyLetterSpacing(e,t){if(t>=.05){let r="";const n=e.split("\n"),i=hairSpacePool.slice(0,Math.round(t/.1));for(let e=0,t=n.length;e0&&(r+="\n"),r+=n[e].split("").join(i);return r}return e}let measureContext;function getMeasureContext(){return measureContext||(measureContext=createCanvas(1,1).getContext("2d")),measureContext}function measureText(e,t){return getMeasureContext().measureText(e).width+(e.length-1)*t}const measureCache={};function wrapText(e,t,r,n){if(-1!==e.indexOf("\n")){const i=e.split("\n"),o=[];for(let e=0,s=i.length;e1){const e=getMeasureContext();e.font=t;const i=e.measureText("M").width*r;let a="";const l=[];for(let t=0,r=s.length;t1;++t){const e=l[t];if(measureText(e,n)<.35*i){const i=t>0?measureText(l[t-1],n):1/0,o=t.7*i&&measureText(o,n)<.6*i){const s=e.split(" "),a=s.pop();measureText(a,n)<.2*i&&(l[t]=s.join(" "),l[t+1]=a+" "+o),r-=1}}o=l.join("\n")}else o=e;o=applyLetterSpacing(o,n),measureCache[i]=o}return o}checkedFonts.on("propertychange",()=>{for(const e in measureCache)delete measureCache[e]});const webSafeFonts=["Arial","Courier New","Times New Roman","Verdana","sans-serif","serif","monospace","cursive","fantasy"],processedFontFamilies={};function getFonts(e,t="https://cdn.jsdelivr.net/npm/@fontsource/{font-family}/{fontweight}{-fontstyle}.css"){if(WORKER_OFFSCREEN_CANVAS)return e;let r;for(let n=0,i=e.length;n{await document.fonts.ready;for(let e=0,n=r.length;ee.family.replace(/^['"]|['"]$/g,"").toLowerCase()===i.toLowerCase()&&e.weight==o&&e.style===s)){const e=t.replace("{font-family}",i.replace(/ /g,"-").toLowerCase()).replace("{Font+Family}",i.replace(/ /g,"+")).replace("{fontweight}",o).replace("{-fontstyle}",s.replace("normal","").replace(/(.+)/,"-$1")).replace("{fontstyle}",s);if(!document.querySelector('link[href="'+e+'"]')){const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)}}}})(),e):e}const types={Point:1,MultiPoint:1,LineString:2,MultiLineString:2,Polygon:3,MultiPolygon:3},anchor={center:[.5,.5],left:[0,.5],right:[1,.5],top:[.5,0],bottom:[.5,1],"top-left":[0,0],"top-right":[1,0],"bottom-left":[0,1],"bottom-right":[1,1]},expressionData=function(e,t){const r=createPropertyExpression(e,t);if("error"===r.result)throw new Error(r.value.map(e=>`${e.key}: ${e.message}`).join(", "));return r.value},cameraObj={zoom:0,distanceFromCenter:0};let renderFeatureCoordinates,renderFeature;function getValue(e,t,r,n,i,o){const s=e.id;i||(i={},console.warn("No functionCache provided to getValue()")),i[s]||(i[s]={});const a=i[s];if(!a[r]){let n=(e[t]||emptyObj)[r];const i=v8[`${t}_${e.type}`][r];void 0===n&&(n=i.default);let o=isExpression(n);if(!o&&isFunction$1(n)&&(n=convertFunction(n,i),o=!0),o){const e=expressionData(n,i);a[r]=e.evaluate.bind(e)}else{const e=i.type;"color"!==e&&"colorArray"!==e||(n=Color.parse(n)),a[r]=function(){return n}}}return a[r](cameraObj,n,o)}function getDeclutterMode(e,t,r,n){return getValue(e,"layout",`${r}-allow-overlap`,t,n)?getValue(e,"layout",`${r}-ignore-placement`,t,n)?"none":"obstacle":"declutter"}function evaluateFilter(e,t,r,n){if(n||console.warn("No filterCache provided to evaluateFilter()"),!(e in n))try{n[e]=featureFilter(t).filter}catch(i){console.warn("Filter will evaluate to false: "+i.message),n[e]=function(){return!1}}return n[e](cameraObj,r)}function colorWithOpacity(e,t){if(e){if(0===e.a||0===t)return;const r=e.a;return t=void 0===t?1:t,0===r?"transparent":"rgba("+Math.round(255*e.r/r)+","+Math.round(255*e.g/r)+","+Math.round(255*e.b/r)+","+r*t+")"}return e}CompoundExpression.register(expressions$1,{...CompoundExpression.definitions,pitch:[{kind:"number"},[],()=>cameraObj.pitch||90],"distance-from-center":[{kind:"number"},[],()=>cameraObj.distanceFromCenter||0]});const templateRegEx=/\{[^{}}]*\}/g;function fromTemplate(e,t){return e.replace(templateRegEx,function(e){return t[e.slice(1,-1)]||""})}function getSpriteImageForIcon(e,t){let r=e.split(":")[0];return r===e&&(r="default"),t[r]}const styleFunctionArgs={};function stylefunction(e,t,r,n=defaultResolutions,i,o,s,a){if("string"==typeof t&&(t=JSON.parse(t)),8!=t.version)throw new Error("glStyle version 8 required.");styleFunctionArgs[getStyleFunctionKey(t,e)]=Array.from(arguments);const l={};("string"==typeof o||o instanceof Request||o instanceof Response||o instanceof Promise)&&(o={default:o});for(const E in o){const t=o[E];toPromise(()=>t).then(async t=>{let r;if("undefined"!=typeof Image){const n=new Image;if("string"==typeof t)n.crossOrigin="anonymous",n.src=t;else{let e;t instanceof Request?e=await fetch(t):t instanceof Response&&(e=t);const i=await e.blob();r=URL.createObjectURL(i),n.src=r}n.addEventListener("load",function t(){n.removeEventListener("load",t),l[E]={image:n,size:[n.width,n.height]},e.changed(),r&&URL.revokeObjectURL(r)}),n.addEventListener("error",function e(){URL.revokeObjectURL(r),n.removeEventListener("error",e)})}else if("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope){const e=self;e.postMessage({action:"loadImage",src:t}),e.addEventListener("message",function(e){"imageLoaded"===e.data.action&&e.data.src===t&&(l[E]={image:e.data.image,size:[e.data.image.width,e.data.image.height]})})}})}const c=derefLayers(t.layers),u={},h=[],d={},p={},f=getFunctionCache(t),g=getFilterCache(t);let m;for(let E=0,w=c.length;E=h.maxzoom)continue;const I=h.filter;if(!I||evaluateFilter(w,I,T,g)){let n,c,g,_,E,w;const I=u.index;if(3==C&&("fill"==h.type||"fill-extrusion"==h.type))if(c=getValue(h,"paint",h.type+"-opacity",T,f,x),h.type+"-pattern"in A){const e=getValue(h,"paint",h.type+"-pattern",T,f,x);if(e){const t="string"==typeof e?fromTemplate(e,m):e.toString(),r=getSpriteImageForIcon(t,l);if(i&&i[t]&&r){++R,w=v[R],w&&w.getFill()&&!w.getStroke()&&!w.getText()||(w=new Style({fill:new Fill}),v[R]=w),g=w.getFill(),w.setZIndex(I);const e=t+"."+c;let n=p[e];if(!n){const o=i[t],s=createCanvas(o.width,o.height),a=s.getContext("2d");a.globalAlpha=c,a.drawImage(r.image,o.x,o.y,o.width,o.height,0,0,o.width,o.height),n=a.createPattern(s,"repeat"),p[e]=n}g.setColor(n)}}}else n=colorWithOpacity(getValue(h,"paint",h.type+"-color",T,f,x),c),h.type+"-outline-color"in A&&(E=colorWithOpacity(getValue(h,"paint",h.type+"-outline-color",T,f,x),c)),E||(E=n),(n||E)&&(++R,w=v[R],(!w||n&&!w.getFill()||!n&&w.getFill()||E&&!w.getStroke()||!E&&w.getStroke()||w.getText())&&(w=new Style({fill:n?new Fill:void 0,stroke:E?new Stroke:void 0}),v[R]=w),n&&(g=w.getFill(),g.setColor(n)),E&&(_=w.getStroke(),_.setColor(E),_.setWidth(.5)),w.setZIndex(I));if(1!=C&&"line"==h.type){n="line-pattern"in A?void 0:colorWithOpacity(getValue(h,"paint","line-color",T,f,x),getValue(h,"paint","line-opacity",T,f,x));const e=getValue(h,"paint","line-width",T,f,x);n&&e>0&&(++R,w=v[R],w&&w.getStroke()&&!w.getFill()&&!w.getText()||(w=new Style({stroke:new Stroke}),v[R]=w),_=w.getStroke(),_.setLineCap(getValue(h,"layout","line-cap",T,f,x)),_.setLineJoin(getValue(h,"layout","line-join",T,f,x)),_.setMiterLimit(getValue(h,"layout","line-miter-limit",T,f,x)),_.setColor(n),_.setWidth(e),_.setLineDash(A["line-dasharray"]?getValue(h,"paint","line-dasharray",T,f,x).map(function(t){return t*e}):null),w.setZIndex(I))}let P,k,O,L,M,D,N,F,$,B=!1,U=null,z=0;if((1==C||2==C)&&"icon-image"in S){const t=getValue(h,"layout","icon-image",T,f,x);if(t){let n;P="string"==typeof t?fromTemplate(t,m):t.toString();const s=a?a(e,P):void 0,c=getSpriteImageForIcon(P,l);if(i&&i[P]&&c||s){const e=getValue(h,"layout","icon-rotation-alignment",T,f,x);if(2==C){const t=r.getGeometry();if(t.getFlatMidpoint||t.getFlatMidpoints){const r=t.getExtent();if(Math.sqrt(Math.max(Math.pow((r[2]-r[0])/o,2),Math.pow((r[3]-r[1])/o,2)))>150){const r="MultiLineString"===t.getType()?t.getFlatMidpoints():t.getFlatMidpoint();if(renderFeature||(renderFeatureCoordinates=[NaN,NaN],renderFeature=new RenderFeature("Point",renderFeatureCoordinates,[],2,{},void 0)),n=renderFeature,renderFeatureCoordinates[0]=r[0],renderFeatureCoordinates[1]=r[1],"line"===getValue(h,"layout","symbol-placement",T,f,x)&&"map"===e){const e=t.getStride(),n=t.getFlatCoordinates();for(let t=0,i=n.length-e;t=l){z=Math.atan2(o-a,s-i);break}}}}}}if(2!==C||n){const t=getValue(h,"layout","icon-size",T,f,x),r=void 0!==A["icon-color"]?getValue(h,"paint","icon-color",T,f,x):null;if(!r||0!==r.a){const n=getValue(h,"paint","icon-halo-color",T,f,x),o=getValue(h,"paint","icon-halo-width",T,f,x);let a=`${P}.${t}.${o}.${n}`;if(null!==r&&(a+=`.${r}`),k=d[a],!k){const l=getDeclutterMode(h,T,"icon",f);let u;"icon-offset"in S&&(u=getValue(h,"layout","icon-offset",T,f,x).slice(0),u[0]*=t,u[1]*=-t);let p=r?[255*r.r,255*r.g,255*r.b,r.a]:void 0;if(s){const r={color:p,rotateWithView:"map"===e,displacement:u,declutterMode:l,scale:t};"string"==typeof s?r.src=s:(r.img=s,r.imgSize=[s.width,s.height]),k=new Icon(r)}else{const s=i[P];let a,h,d;if(o)s.sdf?(a=drawIconHalo(drawSDF(c.image,s,r||[0,0,0,1]),{x:0,y:0,width:s.width,height:s.height,pixelRatio:s.pixelRatio},o,n),p=void 0):a=drawIconHalo(c.image,s,o,n);else{if(s.sdf&&!c.unSDFed){const e=drawSDF(c.image,{x:0,y:0,width:c.size[0],height:c.size[1]},{r:1,g:1,b:1});c.image=e,c.unSDFed=!0}a=c.image,h=[s.width,s.height],d=[s.x,s.y]}k=new Icon({color:p,img:a,imgSize:c.size,size:h,offset:d,rotateWithView:"map"===e,scale:t/s.pixelRatio,displacement:u,declutterMode:l})}d[a]=k}}k&&(++R,w=v[R],w&&w.getImage()&&!w.getFill()&&!w.getStroke()||(w=new Style,v[R]=w),w.setGeometry(n),k.setRotation(z+deg2rad(getValue(h,"layout","icon-rotate",T,f,x))),k.setOpacity(getValue(h,"paint","icon-opacity",T,f,x)),k.setAnchor(anchor[getValue(h,"layout","icon-anchor",T,f,x)]),w.setImage(k),U=w.getText(),w.setText(void 0),w.setZIndex(I),B=!0,O=!1)}else O=!0}}}if(1==C&&"circle"===h.type){++R,w=v[R],w&&w.getImage()&&!w.getFill()&&!w.getStroke()||(w=new Style,v[R]=w);const e="circle-radius"in A?getValue(h,"paint","circle-radius",T,f,x):5,t=colorWithOpacity(getValue(h,"paint","circle-stroke-color",T,f,x),getValue(h,"paint","circle-stroke-opacity",T,f,x)),r=getValue(h,"paint","circle-translate",T,f,x),n=colorWithOpacity(getValue(h,"paint","circle-color",T,f,x),getValue(h,"paint","circle-opacity",T,f,x)),i=getValue(h,"paint","circle-stroke-width",T,f,x),o=e+"."+t+"."+n+"."+i+"."+r[0]+"."+r[1];k=d[o],k||(k=new CircleStyle({radius:e,displacement:[r[0],-r[1]],stroke:t&&i>0?new Stroke({width:i,color:t}):void 0,fill:n?new Fill({color:n}):void 0,declutterMode:"none"}),d[o]=k),w.setImage(k),U=w.getText(),w.setText(void 0),w.setGeometry(void 0),w.setZIndex(I),B=!0}if("text-field"in S){N=Math.round(getValue(h,"layout","text-size",T,f,x));const e=getValue(h,"layout","text-font",T,f,x);D=getValue(h,"layout","text-line-height",T,f,x),M=mb2css(s?s(e,t.metadata?t.metadata["ol:webfonts"]:void 0):e,N,D),M.includes("sans-serif")||(M+=",sans-serif"),F=getValue(h,"layout","text-letter-spacing",T,f,x),$=getValue(h,"layout","text-max-width",T,f,x);const r=getValue(h,"layout","text-field",T,f,x);L="object"==typeof r&&r.sections?1===r.sections.length?r.toString():r.sections.reduce((t,r)=>{const n=r.fontStack?r.fontStack.split(","):e,i=mb2css(s?s(n):n,N*(r.scale||1),D);let o=r.text;if("\n"===o)return t.push("\n",""),t;if(2==C)return t.push(applyLetterSpacing(o,F),i),t;o=wrapText(o,i,$,F).split("\n");for(let e=0,s=o.length;e0&&t.push("\n",""),t.push(o[e],i);return t},[]):fromTemplate(r,m).trim(),c=getValue(h,"paint","text-opacity",T,f,x)}if(L&&c&&!O){B||(++R,w=v[R],w&&w.getText()&&!w.getFill()&&!w.getStroke()||(w=new Style,v[R]=w),w.setImage(void 0),w.setGeometry(void 0));const e=getDeclutterMode(h,T,"text",f);w.getText()||w.setText(U),U=w.getText(),(!U||"getDeclutterMode"in U&&U.getDeclutterMode()!==e)&&(U=new Text$1({padding:[2,2,2,2],declutterMode:e}),w.setText(U));const t=getValue(h,"layout","text-transform",T,f,x);"uppercase"==t?L=Array.isArray(L)?L.map((e,t)=>t%2?e:e.toUpperCase()):L.toUpperCase():"lowercase"==t&&(L=Array.isArray(L)?L.map((e,t)=>t%2?e:e.toLowerCase()):L.toLowerCase());const r=Array.isArray(L)?L:2==C?applyLetterSpacing(L,F):wrapText(L,M,$,F);if(U.setText(r),U.setFont(M),U.setRotation(deg2rad(getValue(h,"layout","text-rotate",T,f,x))),"function"==typeof U.setKeepUpright){const e=getValue(h,"layout","text-keep-upright",T,f,x);U.setKeepUpright(e)}const n=getValue(h,"layout","text-anchor",T,f,x),i=B||1==C?"point":getValue(h,"layout","symbol-placement",T,f,x);let o;if("line-center"===i?(U.setPlacement("line"),o="center"):U.setPlacement(i),"line"===i&&"function"==typeof U.setRepeat){const e=getValue(h,"layout","symbol-spacing",T,f,x);U.setRepeat(2*e)}U.setOverflow("point"===i);let s=getValue(h,"paint","text-halo-width",T,f,x);const a=getValue(h,"layout","text-offset",T,f,x),l=getValue(h,"paint","text-translate",T,f,x);let u=0,d=0;if("point"==i){o="center",-1!==n.indexOf("left")?(o="left",d=s):-1!==n.indexOf("right")&&(o="right",d=-s);const e=getValue(h,"layout","text-rotation-alignment",T,f,x);U.setRotateWithView("map"==e)}else U.setMaxAngle(deg2rad(getValue(h,"layout","text-max-angle",T,f,x))*L.length/r.length),U.setRotateWithView(!1);U.setTextAlign(o);let p="middle";0==n.indexOf("bottom")?(p="bottom",u=-s-.5*(D-1)*N):0==n.indexOf("top")&&(p="top",u=s+.5*(D-1)*N),U.setTextBaseline(p);const g=getValue(h,"layout","text-justify",T,f,x);U.setJustify("auto"===g?void 0:g),U.setOffsetX(a[0]*N+d+l[0]),U.setOffsetY(a[1]*N+u+l[1]),b.setColor(colorWithOpacity(getValue(h,"paint","text-color",T,f,x),c)),U.setFill(b);const m=colorWithOpacity(getValue(h,"paint","text-halo-color",T,f,x),c);if(m&&s>0){y.setColor(m),s*=2;const e=.5*N;y.setWidth(s<=e?s:e),U.setStroke(y)}else U.setStroke(void 0);const _=getValue(h,"layout","text-padding",T,f,x),E=U.getPadding();_!==E[0]&&(E[0]=_,E[1]=_,E[2]=_,E[3]=_),w.setZIndex(I)}}}return R>-1?(v.length=R+1,v):void 0};return e.setStyle(_),e.set("mapbox-layers",h),e.set("mapbox-source",m),e.set("mapbox-featurestate",e.get("mapbox-featurestate")||{}),_}const SHIFT_LEFT_32=4294967296,SHIFT_RIGHT_32=1/SHIFT_LEFT_32,TEXT_DECODER_MIN_LENGTH=12,utf8TextDecoder="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8"),PBF_VARINT=0,PBF_FIXED64=1,PBF_BYTES=2,PBF_FIXED32=5;class Pbf{constructor(e=new Uint8Array(16)){this.buf=ArrayBuffer.isView(e)?e:new Uint8Array(e),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(e,t,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,e(n,t,this),this.pos===i&&this.skip(r)}return t}readMessage(e,t){return this.readFields(e,t,this.readVarint()+this.pos)}readFixed32(){const e=this.dataView.getUint32(this.pos,!0);return this.pos+=4,e}readSFixed32(){const e=this.dataView.getInt32(this.pos,!0);return this.pos+=4,e}readFixed64(){const e=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*SHIFT_LEFT_32;return this.pos+=8,e}readSFixed64(){const e=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*SHIFT_LEFT_32;return this.pos+=8,e}readFloat(){const e=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,e}readDouble(){const e=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,e}readVarint(e){const t=this.buf;let r,n;return n=t[this.pos++],r=127&n,n<128?r:(n=t[this.pos++],r|=(127&n)<<7,n<128?r:(n=t[this.pos++],r|=(127&n)<<14,n<128?r:(n=t[this.pos++],r|=(127&n)<<21,n<128?r:(n=t[this.pos],r|=(15&n)<<28,readVarintRemainder(r,e,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const e=this.readVarint();return e%2==1?(e+1)/-2:e/2}readBoolean(){return Boolean(this.readVarint())}readString(){const e=this.readVarint()+this.pos,t=this.pos;return this.pos=e,e-t>=TEXT_DECODER_MIN_LENGTH&&utf8TextDecoder?utf8TextDecoder.decode(this.buf.subarray(t,e)):readUtf8(this.buf,t,e)}readBytes(){const e=this.readVarint()+this.pos,t=this.buf.subarray(this.pos,e);return this.pos=e,t}readPackedVarint(e=[],t){const r=this.readPackedEnd();for(;this.pos127;);else if(t===PBF_BYTES)this.pos=this.readVarint()+this.pos;else if(t===PBF_FIXED32)this.pos+=4;else{if(t!==PBF_FIXED64)throw new Error(`Unimplemented type: ${t}`);this.pos+=8}}writeTag(e,t){this.writeVarint(e<<3|t)}realloc(e){let t=this.length||16;for(;t268435455||e<0?writeBigVarint(e,this):(this.realloc(4),this.buf[this.pos++]=127&e|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=127&(e>>>=7)|(e>127?128:0),e<=127||(this.buf[this.pos++]=e>>>7&127))))}writeSVarint(e){this.writeVarint(e<0?2*-e-1:2*e)}writeBoolean(e){this.writeVarint(+e)}writeString(e){e=String(e),this.realloc(4*e.length),this.pos++;const t=this.pos;this.pos=writeUtf8(this.buf,e,this.pos);const r=this.pos-t;r>=128&&makeRoomForExtraLength(t,r,this),this.pos=t-1,this.writeVarint(r),this.pos+=r}writeFloat(e){this.realloc(4),this.dataView.setFloat32(this.pos,e,!0),this.pos+=4}writeDouble(e){this.realloc(8),this.dataView.setFloat64(this.pos,e,!0),this.pos+=8}writeBytes(e){const t=e.length;this.writeVarint(t),this.realloc(t);for(let r=0;r=128&&makeRoomForExtraLength(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n}writeMessage(e,t,r){this.writeTag(e,PBF_BYTES),this.writeRawMessage(t,r)}writePackedVarint(e,t){t.length&&this.writeMessage(e,writePackedVarint,t)}writePackedSVarint(e,t){t.length&&this.writeMessage(e,writePackedSVarint,t)}writePackedBoolean(e,t){t.length&&this.writeMessage(e,writePackedBoolean,t)}writePackedFloat(e,t){t.length&&this.writeMessage(e,writePackedFloat,t)}writePackedDouble(e,t){t.length&&this.writeMessage(e,writePackedDouble,t)}writePackedFixed32(e,t){t.length&&this.writeMessage(e,writePackedFixed32,t)}writePackedSFixed32(e,t){t.length&&this.writeMessage(e,writePackedSFixed32,t)}writePackedFixed64(e,t){t.length&&this.writeMessage(e,writePackedFixed64,t)}writePackedSFixed64(e,t){t.length&&this.writeMessage(e,writePackedSFixed64,t)}writeBytesField(e,t){this.writeTag(e,PBF_BYTES),this.writeBytes(t)}writeFixed32Field(e,t){this.writeTag(e,PBF_FIXED32),this.writeFixed32(t)}writeSFixed32Field(e,t){this.writeTag(e,PBF_FIXED32),this.writeSFixed32(t)}writeFixed64Field(e,t){this.writeTag(e,PBF_FIXED64),this.writeFixed64(t)}writeSFixed64Field(e,t){this.writeTag(e,PBF_FIXED64),this.writeSFixed64(t)}writeVarintField(e,t){this.writeTag(e,PBF_VARINT),this.writeVarint(t)}writeSVarintField(e,t){this.writeTag(e,PBF_VARINT),this.writeSVarint(t)}writeStringField(e,t){this.writeTag(e,PBF_BYTES),this.writeString(t)}writeFloatField(e,t){this.writeTag(e,PBF_FIXED32),this.writeFloat(t)}writeDoubleField(e,t){this.writeTag(e,PBF_FIXED64),this.writeDouble(t)}writeBooleanField(e,t){this.writeVarintField(e,+t)}}function readVarintRemainder(e,t,r){const n=r.buf;let i,o;if(o=n[r.pos++],i=(112&o)>>4,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<3,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<10,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<17,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(127&o)<<24,o<128)return toNum(e,i,t);if(o=n[r.pos++],i|=(1&o)<<31,o<128)return toNum(e,i,t);throw new Error("Expected varint not more than 10 bytes")}function toNum(e,t,r){return r?4294967296*t+(e>>>0):4294967296*(t>>>0)+(e>>>0)}function writeBigVarint(e,t){let r,n;if(e>=0?(r=e%4294967296|0,n=e/4294967296|0):(r=~(-e%4294967296),n=~(-e/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),e>=0x10000000000000000||e<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");t.realloc(10),writeBigVarintLow(r,n,t),writeBigVarintHigh(n,t)}function writeBigVarintLow(e,t,r){r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos++]=127&e|128,e>>>=7,r.buf[r.pos]=127&e}function writeBigVarintHigh(e,t){const r=(7&e)<<4;t.buf[t.pos++]|=r|((e>>>=3)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e|((e>>>=7)?128:0),e&&(t.buf[t.pos++]=127&e)))))}function makeRoomForExtraLength(e,t,r){const n=t<=16383?1:t<=2097151?2:t<=268435455?3:Math.floor(Math.log(t)/(7*Math.LN2));r.realloc(n);for(let i=r.pos-1;i>=e;i--)r.buf[i+n]=r.buf[i]}function writePackedVarint(e,t){for(let r=0;r239?4:t>223?3:t>191?2:1;if(i+c>r)break;1===c?t<128&&(l=t):2===c?(o=e[i+1],128==(192&o)&&(l=(31&t)<<6|63&o,l<=127&&(l=null))):3===c?(o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(l=(15&t)<<12|(63&o)<<6|63&s,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===c&&(o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(l=(15&t)<<18|(63&o)<<12|(63&s)<<6|63&a,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,c=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=c}return n}function writeUtf8(e,t,r){for(let n,i,o=0;o55295&&n<57344){if(!i){n>56319||o+1===t.length?(e[r++]=239,e[r++]=191,e[r++]=189):i=n;continue}if(n<56320){e[r++]=239,e[r++]=191,e[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(e[r++]=239,e[r++]=191,e[r++]=189,i=null);n<128?e[r++]=n:(n<2048?e[r++]=n>>6|192:(n<65536?e[r++]=n>>12|224:(e[r++]=n>>18|240,e[r++]=n>>12&63|128),e[r++]=n>>6&63|128),e[r++]=63&n|128)}return r}class MVT extends FeatureFormat{constructor(e){super(),e=e||{},this.dataProjection=new Projection({code:"",units:"tile-pixels"}),this.featureClass=e.featureClass?e.featureClass:RenderFeature,this.geometryName_=e.geometryName,this.layerName_=e.layerName?e.layerName:"layer",this.layers_=e.layers?e.layers:null,this.idProperty_=e.idProperty,this.supportedMediaTypes=["application/vnd.mapbox-vector-tile","application/x-protobuf"]}readRawGeometry_(e,t,r,n){e.pos=t.geometry;const i=e.readVarint()+e.pos;let o=1,s=0,a=0,l=0,c=0,u=0;for(;e.pos>3}if(s--,1===o||2===o)a+=e.readSVarint(),l+=e.readSVarint(),1===o&&c>u&&(n.push(c),u=c),r.push(a,l),c+=2;else{if(7!==o)throw new Error("Invalid command found in the PBF");c>u&&(r.push(r[u],r[u+1]),c+=2)}}c>u&&(n.push(c),u=c)}createFeature_(e,t,r){const n=t.type;if(0===n)return null;let i;const o=t.properties;let s;this.idProperty_?(s=o[this.idProperty_],delete o[this.idProperty_]):s=t.id,o[this.layerName_]=t.layer.name;const a=[],l=[];this.readRawGeometry_(e,t,a,l);const c=getGeometryType(n,l.length);if(this.featureClass===RenderFeature)i=new this.featureClass(c,a,l,2,o,s),i.transform(r.dataProjection);else{let e;if("Polygon"==c){const t=inflateEnds(a,l);e=t.length>1?new MultiPolygon(a,"XY",t):new Polygon(a,"XY",l)}else e="Point"===c?new Point(a,"XY"):"LineString"===c?new LineString(a,"XY"):"MultiPoint"===c?new MultiPoint(a,"XY"):"MultiLineString"===c?new MultiLineString(a,"XY",l):null;i=new(0,this.featureClass),this.geometryName_&&i.setGeometryName(this.geometryName_);const t=transformGeometryWithOptions(e,!1,r);i.setGeometry(t),void 0!==s&&i.setId(s),i.setProperties(o,!0)}return i}getType(){return"arraybuffer"}readFeatures(e,t){const r=this.layers_,n=get$2((t=this.adaptOptions(t)).dataProjection);n.setWorldExtent(t.extent),t.dataProjection=n;const i=new Pbf(e),o=i.readFields(layersPBFReader,{}),s=[];for(const a in o){if(r&&!r.includes(a))continue;const e=o[a],l=e?[0,0,e.extent,e.extent]:null;n.setExtent(l);for(let r=0,n=e.length;r>3)?r.readString():2===e?r.readFloat():3===e?r.readDouble():4===e?r.readVarint64():5===e?r.readVarint():6===e?r.readSVarint():7===e?r.readBoolean():null;t.values.push(n)}}function featurePBFReader(e,t,r){if(1==e)t.id=r.readVarint();else if(2==e){const e=r.readVarint()+r.pos;for(;r.pos=s.width)return null;const c=getHeight(o),u=Math.floor(s.height*((o[3]-n[1])/c));return u<0||u>=s.height?null:this.getImageData(s,l,u)}renderFrame(e,t){const r=this.image,n=r.getExtent(),i=r.getResolution(),[o,s]=Array.isArray(i)?i:[i,i],a=r.getPixelRatio(),l=e.layerStatesArray[e.layerIndex],c=e.pixelRatio,u=e.viewState,h=u.center,d=u.resolution,p=c*o/(d*a),f=c*s/(d*a);this.prepareContainer(e,t);const g=this.context.canvas.width,m=this.context.canvas.height,y=this.getRenderContext(e);let b=!1,v=!0;if(l.extent){const t=fromUserExtent(l.extent,u.projection);v=intersects$1(t,e.extent),b=v&&!containsExtent(t,e.extent),b&&this.clipUnrotated(y,e,t)}const _=r.getImage(),E=compose(this.tempTransform,g/2,m/2,p,f,0,a*(n[0]-h[0])/o,a*(h[1]-n[3])/s);this.renderedResolution=s*c/a;const w=_.width*E[0],C=_.height*E[3];if(this.getLayer().getSource().getInterpolate()||(y.imageSmoothingEnabled=!1),this.preRender(y,e),v&&w>=.5&&C>=.5){const e=E[4],t=E[5],r=l.opacity;1!==r&&(y.save(),y.globalAlpha=r),y.drawImage(_,0,0,+_.width,+_.height,e,t,w,C),1!==r&&y.restore()}return this.postRender(this.context,e),b&&y.restore(),y.imageSmoothingEnabled=!0,this.container}}class BaseImageLayer extends Layer{constructor(e){super(e=e||{})}}class ImageLayer extends BaseImageLayer{constructor(e){super(e)}createRenderer(){return new CanvasImageLayerRenderer(this)}getData(e){return super.getData(e)}}function asImageLike(e){return e instanceof Image||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageBitmap?e:null}const disposedError=new Error("disposed"),defaultSize=[256,256];class DataTile extends Tile{constructor(e){const t=TileState.IDLE;super(e.tileCoord,t,{transition:e.transition,interpolate:e.interpolate}),this.loader_=e.loader,this.data_=null,this.error_=null,this.size_=e.size||null,this.controller_=e.controller||null}getSize(){if(this.size_)return this.size_;const e=asImageLike(this.data_);return e?[e.width,e.height]:defaultSize}getData(){return this.data_}getError(){return this.error_}load(){if(this.state!==TileState.IDLE&&this.state!==TileState.ERROR)return;this.state=TileState.LOADING,this.changed();const e=this;this.loader_().then(function(t){e.data_=t,e.state=TileState.LOADED,e.changed()}).catch(function(t){e.error_=t,e.state=TileState.ERROR,e.changed()})}disposeInternal(){this.controller_&&(this.controller_.abort(disposedError),this.controller_=null),super.disposeInternal()}}let brokenDiagonalRendering_;const canvasPool=[];function drawTestTriangle(e,t,r,n,i){e.beginPath(),e.moveTo(0,0),e.lineTo(t,r),e.lineTo(n,i),e.closePath(),e.save(),e.clip(),e.fillRect(0,0,Math.max(t,n)+1,Math.max(r,i)),e.restore()}function verifyBrokenDiagonalRendering(e,t){return Math.abs(e[4*t]-210)>2||Math.abs(e[4*t+3]-191.25)>2}function isBrokenDiagonalRendering(){if(void 0===brokenDiagonalRendering_){const e=createCanvasContext2D(6,6,canvasPool);e.globalCompositeOperation="lighter",e.fillStyle="rgba(210, 0, 0, 0.75)",drawTestTriangle(e,4,5,4,0),drawTestTriangle(e,4,5,0,5);const t=e.getImageData(0,0,3,3).data;brokenDiagonalRendering_=verifyBrokenDiagonalRendering(t,0)||verifyBrokenDiagonalRendering(t,4)||verifyBrokenDiagonalRendering(t,8),releaseCanvas(e),canvasPool.push(e.canvas)}return brokenDiagonalRendering_}function calculateSourceResolution(e,t,r,n){const i=transform(r,t,e);let o=getPointResolution(t,n,r);const s=t.getMetersPerUnit();void 0!==s&&(o*=s);const a=e.getMetersPerUnit();void 0!==a&&(o/=a);const l=e.getExtent();if(!l||containsCoordinate(l,i)){const t=getPointResolution(e,o,i)/o;isFinite(t)&&t>0&&(o/=t)}return o}function calculateSourceExtentResolution(e,t,r,n){const i=getCenter(r);let o=calculateSourceResolution(e,t,i,n);return(!isFinite(o)||o<=0)&&forEachCorner(r,function(r){return o=calculateSourceResolution(e,t,r,n),isFinite(o)&&o>0}),o}function render(e,t,r,n,i,o,s,a,l,c,u,h,d){const p=createCanvasContext2D(Math.round(r*e),Math.round(r*t),canvasPool);if(h||(p.imageSmoothingEnabled=!1),0===l.length)return p.canvas;function f(e){return Math.round(e*r)/r}p.scale(r,r),p.globalCompositeOperation="lighter";const g=createEmpty();let m;l.forEach(function(e){extend$1(g,e.extent)});const y=r/n,b=(h?1:1+Math.pow(2,-24))/y;d&&1===l.length&&0===c||(m=createCanvasContext2D(Math.round(getWidth(g)*y),Math.round(getHeight(g)*y),canvasPool),h||(m.imageSmoothingEnabled=!1),l.forEach(function(e){if(e.image.width>0&&e.image.height>0){if(e.clipExtent){m.save();const t=(e.clipExtent[0]-g[0])*y,r=-(e.clipExtent[3]-g[3])*y,n=getWidth(e.clipExtent)*y,i=getHeight(e.clipExtent)*y;m.rect(h?t:Math.round(t),h?r:Math.round(r),h?n:Math.round(t+n)-Math.round(t),h?i:Math.round(r+i)-Math.round(r)),m.clip()}const t=(e.extent[0]-g[0])*y,r=-(e.extent[3]-g[3])*y,n=getWidth(e.extent)*y,i=getHeight(e.extent)*y;m.drawImage(e.image,c,c,e.image.width-2*c,e.image.height-2*c,h?t:Math.round(t),h?r:Math.round(r),h?n:Math.round(t+n)-Math.round(t),h?i:Math.round(r+i)-Math.round(r)),e.clipExtent&&m.restore()}}));const v=getTopLeft(s);return a.getTriangles().forEach(function(e){const t=e.source,r=e.target;let n=t[0][0],i=t[0][1],s=t[1][0],a=t[1][1],c=t[2][0],u=t[2][1];const d=f((r[0][0]-v[0])/o),y=f(-(r[0][1]-v[1])/o),_=f((r[1][0]-v[0])/o),E=f(-(r[1][1]-v[1])/o),w=f((r[2][0]-v[0])/o),C=f(-(r[2][1]-v[1])/o),S=n,T=i;n=0,i=0,s-=S,a-=T,c-=S,u-=T;const x=solveLinearSystem([[s,a,0,0,_-d],[c,u,0,0,w-d],[0,0,s,a,E-y],[0,0,c,u,C-y]]);if(!x)return;if(p.save(),p.beginPath(),isBrokenDiagonalRendering()||!h){p.moveTo(_,E);const e=4,t=d-_,r=y-E;for(let n=0;napply$1(s,transform(e,this.targetProj_,this.sourceProj_))):getTransform(this.targetProj_,this.sourceProj_);this.transformInv_=function(e){const t=e[0]+"/"+e[1];return a[t]||(a[t]=l(e)),a[t]},this.maxSourceExtent_=n,this.errorThresholdSquared_=i*i,this.triangles_=[],this.wrapsXInSource_=!1,this.canWrapXInSource_=this.sourceProj_.canWrapX()&&!!n&&!!this.sourceProj_.getExtent()&&getWidth(n)>=getWidth(this.sourceProj_.getExtent()),this.sourceWorldWidth_=this.sourceProj_.getExtent()?getWidth(this.sourceProj_.getExtent()):null,this.targetWorldWidth_=this.targetProj_.getExtent()?getWidth(this.targetProj_.getExtent()):null;const c=getTopLeft(r),u=getTopRight(r),h=getBottomRight(r),d=getBottomLeft(r),p=this.transformInv_(c),f=this.transformInv_(u),g=this.transformInv_(h),m=this.transformInv_(d),y=MAX_SUBDIVISION+(o?Math.max(0,Math.ceil(Math.log2(getArea(r)/(o*o*256*256)))):0);if(this.addQuad_(c,u,h,d,p,f,g,m,y),this.wrapsXInSource_){let e=1/0;this.triangles_.forEach(function(t){e=Math.min(e,t.source[0][0],t.source[1][0],t.source[2][0])}),this.triangles_.forEach(t=>{if(Math.max(t.source[0][0],t.source[1][0],t.source[2][0])-e>this.sourceWorldWidth_/2){const r=[[t.source[0][0],t.source[0][1]],[t.source[1][0],t.source[1][1]],[t.source[2][0],t.source[2][1]]];r[0][0]-e>this.sourceWorldWidth_/2&&(r[0][0]-=this.sourceWorldWidth_),r[1][0]-e>this.sourceWorldWidth_/2&&(r[1][0]-=this.sourceWorldWidth_),r[2][0]-e>this.sourceWorldWidth_/2&&(r[2][0]-=this.sourceWorldWidth_);const n=Math.min(r[0][0],r[1][0],r[2][0]);Math.max(r[0][0],r[1][0],r[2][0])-n.5&&u<1;let p=!1;if(l>0&&(this.targetProj_.isGlobal()&&this.targetWorldWidth_&&(p=getWidth(boundingExtent([e,t,r,n]))/this.targetWorldWidth_>MAX_TRIANGLE_WIDTH||p),!d&&this.sourceProj_.isGlobal()&&u&&(p=u>MAX_TRIANGLE_WIDTH||p)),!p&&this.maxSourceExtent_&&isFinite(c[0])&&isFinite(c[1])&&isFinite(c[2])&&isFinite(c[3])&&!intersects$1(c,this.maxSourceExtent_))return;let f=0;if(!(p||isFinite(i[0])&&isFinite(i[1])&&isFinite(o[0])&&isFinite(o[1])&&isFinite(s[0])&&isFinite(s[1])&&isFinite(a[0])&&isFinite(a[1])))if(l>0)p=!0;else if(f=(isFinite(i[0])&&isFinite(i[1])?0:8)+(isFinite(o[0])&&isFinite(o[1])?0:4)+(isFinite(s[0])&&isFinite(s[1])?0:2)+(isFinite(a[0])&&isFinite(a[1])?0:1),1!=f&&2!=f&&4!=f&&8!=f)return;if(l>0){if(!p){const t=[(e[0]+r[0])/2,(e[1]+r[1])/2],n=this.transformInv_(t);let o;o=d?(modulo(i[0],h)+modulo(s[0],h))/2-modulo(n[0],h):(i[0]+s[0])/2-n[0];const a=(i[1]+s[1])/2-n[1];p=o*o+a*a>this.errorThresholdSquared_}if(p){if(Math.abs(e[0]-r[0])<=Math.abs(e[1]-r[1])){const c=[(t[0]+r[0])/2,(t[1]+r[1])/2],u=this.transformInv_(c),h=[(n[0]+e[0])/2,(n[1]+e[1])/2],d=this.transformInv_(h);this.addQuad_(e,t,c,h,i,o,u,d,l-1),this.addQuad_(h,c,r,n,d,u,s,a,l-1)}else{const c=[(e[0]+t[0])/2,(e[1]+t[1])/2],u=this.transformInv_(c),h=[(r[0]+n[0])/2,(r[1]+n[1])/2],d=this.transformInv_(h);this.addQuad_(e,c,h,n,i,u,d,a,l-1),this.addQuad_(c,t,r,h,u,o,s,d,l-1)}return}}if(d){if(!this.canWrapXInSource_)return;this.wrapsXInSource_=!0}11&f||this.addTriangle_(e,r,n,i,s,a),14&f||this.addTriangle_(e,r,t,i,s,o),f&&(13&f||this.addTriangle_(t,n,e,o,a,i),7&f||this.addTriangle_(t,n,r,o,a,s))}calculateSourceExtent(){const e=createEmpty();return this.triangles_.forEach(function(t){const r=t.source;extendCoordinate(e,r[0]),extendCoordinate(e,r[1]),extendCoordinate(e,r[2])}),e}getTriangles(){return this.triangles_}}const ERROR_THRESHOLD=.5;class ReprojTile extends Tile{constructor(e,t,r,n,i,o,s,a,l,c,u,h){super(i,TileState.IDLE,h),this.renderEdges_=void 0!==u&&u,this.pixelRatio_=s,this.gutter_=a,this.canvas_=null,this.sourceTileGrid_=t,this.targetTileGrid_=n,this.wrappedTileCoord_=o||i,this.sourceTiles_=[],this.sourcesListenerKeys_=null,this.sourceZ_=0,this.clipExtent_=e.canWrapX()?e.getExtent():void 0;const d=n.getTileCoordExtent(this.wrappedTileCoord_),p=this.targetTileGrid_.getExtent();let f=this.sourceTileGrid_.getExtent();const g=p?getIntersection(d,p):d;if(0===getArea(g))return void(this.state=TileState.EMPTY);const m=e.getExtent();m&&(f=f?getIntersection(f,m):m);const y=n.getResolution(this.wrappedTileCoord_[0]),b=calculateSourceExtentResolution(e,r,g,y);if(!isFinite(b)||b<=0)return void(this.state=TileState.EMPTY);const v=void 0!==c?c:ERROR_THRESHOLD;if(this.triangulation_=new Triangulation(e,r,g,f,b*v,y),0===this.triangulation_.getTriangles().length)return void(this.state=TileState.EMPTY);this.sourceZ_=t.getZForResolution(b);let _=this.triangulation_.calculateSourceExtent();if(f&&(e.canWrapX()?(_[1]=clamp$1(_[1],f[1],f[3]),_[3]=clamp$1(_[3],f[1],f[3])):_=getIntersection(_,f)),getArea(_)){let r=0,n=0;e.canWrapX()&&(r=getWidth(m),n=Math.floor((_[0]-m[0])/r)),wrapAndSliceX(_.slice(),e,!0).forEach(e=>{const i=t.getTileRangeForExtentAndZ(e,this.sourceZ_);for(let t=i.minX;t<=i.maxX;t++)for(let e=i.minY;e<=i.maxY;e++){const i=l(this.sourceZ_,t,e,s);if(i){const e=n*r;this.sourceTiles_.push({tile:i,offset:e})}}++n}),0===this.sourceTiles_.length&&(this.state=TileState.EMPTY)}else this.state=TileState.EMPTY}getImage(){return this.canvas_}reproject_(){const e=[];if(this.sourceTiles_.forEach(t=>{const r=t.tile;if(r&&r.getState()==TileState.LOADED){const n=this.sourceTileGrid_.getTileCoordExtent(r.tileCoord);n[0]+=t.offset,n[2]+=t.offset;const i=this.clipExtent_?.slice();i&&(i[0]+=t.offset,i[2]+=t.offset),e.push({extent:n,clipExtent:i,image:r.getImage()})}}),this.sourceTiles_.length=0,0===e.length)this.state=TileState.ERROR;else{const t=this.wrappedTileCoord_[0],r=this.targetTileGrid_.getTileSize(t),n="number"==typeof r?r:r[0],i="number"==typeof r?r:r[1],o=this.targetTileGrid_.getResolution(t),s=this.sourceTileGrid_.getResolution(this.sourceZ_),a=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_);this.canvas_=render(n,i,this.pixelRatio_,s,this.sourceTileGrid_.getExtent(),o,a,this.triangulation_,e,this.gutter_,this.renderEdges_,this.interpolate),this.state=TileState.LOADED}this.changed()}load(){if(this.state==TileState.IDLE){this.state=TileState.LOADING,this.changed();let e=0;this.sourcesListenerKeys_=[],this.sourceTiles_.forEach(({tile:t})=>{const r=t.getState();if(r==TileState.IDLE||r==TileState.LOADING){e++;const r=listen(t,EventType$1.CHANGE,()=>{const n=t.getState();n!=TileState.LOADED&&n!=TileState.ERROR&&n!=TileState.EMPTY||(unlistenByKey(r),e--,0===e&&(this.unlistenSources_(),this.reproject_()))});this.sourcesListenerKeys_.push(r)}}),0===e?setTimeout(this.reproject_.bind(this),0):this.sourceTiles_.forEach(function({tile:e}){e.getState()==TileState.IDLE&&e.load()})}}unlistenSources_(){this.sourcesListenerKeys_.forEach(unlistenByKey),this.sourcesListenerKeys_=null}release(){this.canvas_&&(releaseCanvas(this.canvas_.getContext("2d")),canvasPool.push(this.canvas_),this.canvas_=null),super.release()}}class LRUCache{constructor(e){this.highWaterMark=void 0!==e?e:2048,this.count_=0,this.entries_={},this.oldest_=null,this.newest_=null}deleteOldest(){const e=this.pop();e instanceof Disposable&&e.dispose()}canExpireCache(){return this.highWaterMark>0&&this.getCount()>this.highWaterMark}expireCache(e){for(;this.canExpireCache();)this.deleteOldest()}clear(){for(;this.oldest_;)this.deleteOldest()}containsKey(e){return this.entries_.hasOwnProperty(e)}forEach(e){let t=this.oldest_;for(;t;)e(t.value_,t.key_,this),t=t.newer}get(e,t){const r=this.entries_[e];return assert$1(void 0!==r,"Tried to get a value for a key that does not exist in the cache"),r===this.newest_||(r===this.oldest_?(this.oldest_=this.oldest_.newer,this.oldest_.older=null):(r.newer.older=r.older,r.older.newer=r.newer),r.newer=null,r.older=this.newest_,this.newest_.newer=r,this.newest_=r),r.value_}remove(e){const t=this.entries_[e];return assert$1(void 0!==t,"Tried to get a value for a key that does not exist in the cache"),t===this.newest_?(this.newest_=t.older,this.newest_&&(this.newest_.newer=null)):t===this.oldest_?(this.oldest_=t.newer,this.oldest_&&(this.oldest_.older=null)):(t.newer.older=t.older,t.older.newer=t.newer),delete this.entries_[e],--this.count_,t.value_}getCount(){return this.count_}getKeys(){const e=new Array(this.count_);let t,r=0;for(t=this.newest_;t;t=t.older)e[r++]=t.key_;return e}getValues(){const e=new Array(this.count_);let t,r=0;for(t=this.newest_;t;t=t.older)e[r++]=t.value_;return e}peekLast(){return this.oldest_.value_}peekLastKey(){return this.oldest_.key_}peekFirstKey(){return this.newest_.key_}peek(e){return this.entries_[e]?.value_}pop(){const e=this.oldest_;return delete this.entries_[e.key_],e.newer&&(e.newer.older=null),this.oldest_=e.newer,this.oldest_||(this.newest_=null),--this.count_,e.value_}replace(e,t){this.get(e),this.entries_[e].value_=t}set(e,t){assert$1(!(e in this.entries_),"Tried to set a value for a key that is used already");const r={key_:e,newer:null,older:this.newest_,value_:t};this.newest_?this.newest_.newer=r:this.oldest_=r,this.newest_=r,this.entries_[e]=r,++this.count_}setSize(e){this.highWaterMark=e}}function createOrUpdate(e,t,r,n){return void 0!==n?(n[0]=e,n[1]=t,n[2]=r,n):[e,t,r]}function getKeyZXY(e,t,r){return e+"/"+t+"/"+r}function getCacheKey(e,t,r,n,i){return`${getUid(e)},${t},${getKeyZXY(r,n,i)}`}function hash(e){return hashZXY(e[0],e[1],e[2])}function hashZXY(e,t,r){return(t<r||r>t.getMaxZoom())return!1;const o=t.getFullTileRange(r);return!o||o.containsXY(n,i)}function addTileToLookup(e,t,r){if(!(r in e))return e[r]=new Set([t]),!0;const n=e[r],i=n.has(t);return i||n.add(t),!i}function removeTileFromLookup(e,t,r){const n=e[r];return!!n&&n.delete(t)}function getRenderExtent(e,t){const r=e.layerStatesArray[e.layerIndex];r.extent&&(t=getIntersection(t,fromUserExtent(r.extent,e.viewState.projection)));const n=r.layer.getRenderSource();if(!n.getWrapX()){const r=n.getTileGridForProjection(e.viewState.projection).getExtent();r&&(t=getIntersection(t,r))}return t}class CanvasTileLayerRenderer extends CanvasLayerRenderer{constructor(e,t){super(e),t=t||{},this.extentChanged=!0,this.renderComplete=!1,this.renderedExtent_=null,this.renderedPixelRatio,this.renderedProjection=null,this.renderedTiles=[],this.renderedSourceKey_,this.renderedSourceRevision_,this.tempExtent=createEmpty(),this.tempTileRange_=new TileRange(0,0,0,0),this.tempTileCoord_=createOrUpdate(0,0,0);const r=void 0!==t.cacheSize?t.cacheSize:512;this.tileCache_=new LRUCache(r),this.sourceTileCache_=null,this.maxStaleKeys=.5*r}getTileCache(){return this.tileCache_}getSourceTileCache(){return this.sourceTileCache_||(this.sourceTileCache_=new LRUCache(512)),this.sourceTileCache_}getOrCreateTile(e,t,r,n){const i=this.tileCache_,o=this.getLayer().getSource(),s=getCacheKey(o,o.getKey(),e,t,r);let a;if(i.containsKey(s))a=i.get(s);else{const l=n.viewState.projection,c=o.getProjection();if(a=o.getTile(e,t,r,n.pixelRatio,l,!c||equivalent$1(c,l)?void 0:this.getSourceTileCache()),!a)return null;i.set(s,a)}return a}getTile(e,t,r,n){return this.getOrCreateTile(e,t,r,n)||null}getData(e){const t=this.frameState;if(!t)return null;const r=this.getLayer(),n=apply$1(t.pixelToCoordinateTransform,e.slice()),i=r.getExtent();if(i&&!containsCoordinate(i,n))return null;const o=t.viewState,s=r.getRenderSource(),a=s.getTileGridForProjection(o.projection),l=s.getTilePixelRatio(t.pixelRatio);for(let c=a.getZForResolution(o.resolution);c>=a.getMinZoom();--c){const e=a.getTileCoordForCoordAndZ(n,c),r=this.getTile(c,e[1],e[2],t);if(!r||r.getState()!==TileState.LOADED)continue;const i=a.getOrigin(c),u=toSize(a.getTileSize(c)),h=a.getResolution(c);let d;if(r instanceof ImageTile||r instanceof ReprojTile)d=r.getImage();else{if(!(r instanceof DataTile))continue;if(d=asImageLike(r.getData()),!d)continue}const p=Math.floor(l*((n[0]-i[0])/h-e[1]*u[0])),f=Math.floor(l*((i[1]-n[1])/h-e[2]*u[1])),g=Math.round(l*s.getGutterForProjection(o.projection));return this.getImageData(d,p+g,f+g)}return null}prepareFrame(e){this.renderedProjection?e.viewState.projection!==this.renderedProjection&&(this.tileCache_.clear(),this.renderedProjection=e.viewState.projection):this.renderedProjection=e.viewState.projection;const t=this.getLayer().getSource();if(!t)return!1;const r=t.getRevision();return this.renderedSourceRevision_?this.renderedSourceRevision_!==r&&(this.renderedSourceRevision_=r,this.renderedSourceKey_===t.getKey()&&(this.tileCache_.clear(),this.sourceTileCache_?.clear())):this.renderedSourceRevision_=r,!0}enqueueTilesForNextExtent(){return!0}enqueueTiles(e,t,r,n,i){const o=e.viewState,s=this.getLayer(),a=s.getRenderSource(),l=a.getTileGridForProjection(o.projection),c=getUid(a);c in e.wantedTiles||(e.wantedTiles[c]={});const u=e.wantedTiles[c],h=s.getMapInternal(),d=Math.max(r-i,l.getMinZoom(),l.getZForResolution(Math.min(s.getMaxResolution(),h?h.getView().getResolutionForZoom(Math.max(s.getMinZoom(),0)):l.getResolution(0)),a.zDirection)),p=o.rotation,f=p?getRotatedViewport(o.center,o.resolution,p,e.size):void 0;for(let g=r;g>=d;--g){const r=l.getTileRangeForExtentAndZ(t,g,this.tempTileRange_),i=l.getResolution(g);for(let t=r.minX;t<=r.maxX;++t)for(let o=r.minY;o<=r.maxY;++o){if(p&&!l.tileCoordIntersectsViewport([g,t,o],f))continue;const r=this.getTile(g,t,o,e);if(!r)continue;if(!addTileToLookup(n,r,g))continue;const s=r.getKey();if(u[s]=!0,r.getState()===TileState.IDLE&&!e.tileQueue.isKeyQueued(s)){const n=createOrUpdate(g,t,o,this.tempTileCoord_);e.tileQueue.enqueue([r,c,l.getTileCoordCenter(n),i])}}}}findStaleTile_(e,t){const r=this.tileCache_,n=e[0],i=e[1],o=e[2],s=this.getStaleKeys();for(let a=0;a0&&setTimeout(()=>{this.enqueueTiles(e,S,h-1,w,C-1)},0),!(h in w))return this.container;const T=getUid(this),x=e.time;for(const L of w[h]){const t=L.getState();if(t===TileState.EMPTY)continue;const r=L.tileCoord;if(t===TileState.LOADED&&1===L.getAlpha(T,x)){L.endTransition(T);continue}if(t!==TileState.ERROR&&(this.renderComplete=!1),this.findStaleTile_(r,w)){removeTileFromLookup(w,L,h),e.animate=!0;continue}if(this.findAltTiles_(u,r,h+1,w))continue;const n=u.getMinZoom();for(let e=h-1;e>=n&&!this.findAltTiles_(u,r,e,w);--e);}const R=d/o*a/g,A=this.getRenderContext(e);compose(this.tempTransform,m/2,y/2,R,R,0,-m/2,-y/2),r.extent&&this.clipUnrotated(A,e,b),c.getInterpolate()||(A.imageSmoothingEnabled=!1),this.preRender(A,e);const I=Object.keys(w).map(Number);let P;I.sort(ascending);const k=[],O=[];for(let L=I.length-1;L>=0;--L){const t=I[L],r=c.getTilePixelSize(t,a,i),n=u.getResolution(t)/d,o=r[0]*n*R,s=r[1]*n*R,l=u.getTileCoordForCoordAndZ(getTopLeft(E),t),h=u.getTileCoordExtent(l),p=apply$1(this.tempTransform,[g*(h[0]-E[0])/d,g*(E[3]-h[3])/d]),f=g*c.getGutterForProjection(i);for(const i of w[t]){if(i.getState()!==TileState.LOADED)continue;const r=i.tileCoord,n=l[1]-r[1],a=Math.round(p[0]-(n-1)*o),u=l[2]-r[2],h=Math.round(p[1]-(u-1)*s),d=Math.round(p[0]-n*o),g=Math.round(p[1]-u*s),m=a-d,y=h-g,b=1===I.length;let v=!1;P=[d,g,d+m,g,d+m,g+y,d,g+y];for(let e=0,i=k.length;e{const r=getUid(c),n=t.wantedTiles[r],i=n?Object.keys(n).length:0;this.updateCacheSize(i),this.tileCache_.expireCache(),this.sourceTileCache_?.expireCache()};e.postRenderFunctions.push(t)}return this.container}updateCacheSize(e){this.tileCache_.highWaterMark=Math.max(this.tileCache_.highWaterMark,2*e)}drawTile(e,t,r,n,i,o,s,a){let l;if(e instanceof DataTile){if(l=asImageLike(e.getData()),!l)throw new Error("Rendering array data is not yet supported")}else l=this.getTileImage(e);if(!l)return;const c=this.getRenderContext(t),u=getUid(this),h=t.layerStatesArray[t.layerIndex],d=h.opacity*(a?e.getAlpha(u,t.time):1),p=d!==c.globalAlpha;p&&(c.save(),c.globalAlpha=d),c.drawImage(l,s,s,l.width-2*s,l.height-2*s,r,n,i,o),p&&c.restore(),d!==h.opacity?t.animate=!0:a&&e.endTransition(u)}getImage(){const e=this.context;return e?e.canvas:null}getTileImage(e){return e.getImage()}updateUsedTiles(e,t,r){const n=getUid(t);n in e||(e[n]={}),e[n][r.getKey()]=!0}}const TileProperty={PRELOAD:"preload",USE_INTERIM_TILES_ON_ERROR:"useInterimTilesOnError"};class BaseTileLayer extends Layer{constructor(e){e=e||{};const t=Object.assign({},e),r=e.cacheSize;delete e.cacheSize,delete t.preload,delete t.useInterimTilesOnError,super(t),this.on,this.once,this.un,this.cacheSize_=r,this.setPreload(void 0!==e.preload?e.preload:0),this.setUseInterimTilesOnError(void 0===e.useInterimTilesOnError||e.useInterimTilesOnError)}getCacheSize(){return this.cacheSize_}getPreload(){return this.get(TileProperty.PRELOAD)}setPreload(e){this.set(TileProperty.PRELOAD,e)}getUseInterimTilesOnError(){return this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR)}setUseInterimTilesOnError(e){this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR,e)}getData(e){return super.getData(e)}}class TileLayer extends BaseTileLayer{constructor(e){super(e)}createRenderer(){return new CanvasTileLayerRenderer(this,{cacheSize:this.getCacheSize()})}}const IMAGE_REPLAYS={image:["Polygon","Circle","LineString","Image","Text"],hybrid:["Polygon","LineString"],vector:[]},VECTOR_REPLAYS={hybrid:["Image","Text","Default"],vector:["Polygon","Circle","LineString","Image","Text","Default"]};class CanvasVectorTileLayerRenderer extends CanvasTileLayerRenderer{constructor(e,t){super(e,t),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.renderedLayerRevision_,this.renderedPixelToCoordinateTransform_=null,this.renderedRotation_,this.renderedOpacity_=1,this.tmpTransform_=create(),this.tileClipContexts_=null}enqueueTilesForNextExtent(){return"vector"!==this.getLayer().getRenderMode()}drawTile(e,t,r,n,i,o,s,a){this.updateExecutorGroup_(e,t.pixelRatio,t.viewState.projection),this.tileImageNeedsRender_(e)&&this.renderTileImage_(e,t),super.drawTile(e,t,r,n,i,o,s,a)}getTile(e,t,r,n){const i=this.getOrCreateTile(e,t,r,n);if(!i)return null;const o=n.viewState,s=o.resolution,a=n.viewHints,l=this.getLayer().getSource(),c=l.getTileGridForProjection(o.projection),u=!(a[ViewHint.ANIMATING]||a[ViewHint.INTERACTING]),h=c.getZForResolution(s,l.zDirection)===e;return u&&h?i.wantedResolution=s:i.wantedResolution||(i.wantedResolution=c.getResolution(e)),i}prepareFrame(e){const t=this.getLayer().getRevision();return this.renderedLayerRevision_!==t&&(this.renderedLayerRevision_=t,this.renderedTiles.length=0),super.prepareFrame(e)}updateExecutorGroup_(e,t,r){const n=this.getLayer(),i=n.getRevision(),o=n.getRenderOrder()||null,s=e.wantedResolution,a=e.getReplayState(n);if(!a.dirty&&a.renderedResolution===s&&a.renderedRevision==i&&a.renderedRenderOrder==o)return;const l=n.getSource(),c=!!n.getDeclutter(),u=l.getTileGrid(),h=l.getTileGridForProjection(r).getTileCoordExtent(e.wrappedTileCoord),d=l.getSourceTiles(t,r,e),p=getUid(n);delete e.hitDetectionImageData[p],e.executorGroups[p]=[],a.dirty=!1;for(let f=0,g=d.length;fe.value):null;let m;e:for(let y=0,b=d.length;y{const r=this.getLayer(),n=r.getSource(),i=this.renderedProjection,o=i.getExtent(),s=this.renderedResolution,a=n.getTileGridForProjection(i),l=apply$1(this.renderedPixelToCoordinateTransform_,e.slice()),c=a.getTileCoordForCoordAndResolution(l,s).toString(),u=this.renderedTiles.find(e=>e.tileCoord.toString()===c&&e.getState()===TileState.LOADED);if(!u||u.loadingSourceTiles>0)return void t([]);n.getWrapX()&&i.canWrapX()&&!containsExtent(o,a.getTileCoordExtent(u.tileCoord))&&wrapX$1(l,i);const h=getUid(r),d=getTopLeft(a.getTileCoordExtent(u.wrappedTileCoord)),p=[(l[0]-d[0])/s,(d[1]-l[1])/s],f=u.getSourceTiles().reduce((e,t)=>e.concat(t.getFeatures()),[]);let g=u.hitDetectionImageData[h];if(!g){const e=toSize(a.getTileSize(a.getZForResolution(s,n.zDirection))),t=this.renderedRotation_;g=createHitDetectionImageData(e,[this.getRenderTransform(a.getTileCoordCenter(u.wrappedTileCoord),s,0,HIT_DETECT_RESOLUTION,e[0]*HIT_DETECT_RESOLUTION,e[1]*HIT_DETECT_RESOLUTION,0)],f,r.getStyleFunction(),a.getTileCoordExtent(u.wrappedTileCoord),u.getReplayState(r).renderedResolution,t),u.hitDetectionImageData[h]=g}t(hitDetect(p,f,g))})}getFeaturesInExtent(e){const t=[],r=this.getTileCache();if(0===r.getCount())return t;const n=this.getLayer().getSource().getTileGridForProjection(this.frameState.viewState.projection),i=n.getZForResolution(this.renderedResolution),o={};return r.forEach(r=>{if(r.tileCoord[0]!==i||r.getState()!==TileState.LOADED)return;const s=r.getSourceTiles();for(let i=0,a=s.length;i=0;--n)r[n].execute(this.context,s,this.getTileRenderTransform(t,e),e.viewState.rotation,o,DECLUTTER,l)}r.globalAlpha=n}renderDeferredInternal(e){const t=this.renderedTiles,r=getUid(this.getLayer()),n=t.reduce((e,t,n)=>(t.executorGroups[r].forEach(t=>e.push({executorGroup:t,index:n})),e),[]),i=n.map(({executorGroup:e})=>e.getDeferredZIndexContexts()),o={};for(let s=0,a=n.length;s{i.forEach((t,r)=>{t[e]&&(t[e].forEach(e=>{const{executorGroup:t,index:i}=n[r],o=t.getRenderedContext(),s=o.globalAlpha;o.globalAlpha=this.renderedOpacity_;const a=this.tileClipContexts_[i];a&&a.draw(o),e.draw(o),a&&o.restore(),o.globalAlpha=s,e.clear()}),t[e].length=0)})})}getTileRenderTransform(e,t){const r=t.pixelRatio,n=t.viewState,i=n.center,o=n.resolution,s=n.rotation,a=t.size,l=Math.round(a[0]*r),c=Math.round(a[1]*r),u=this.getLayer().getSource().getTileGridForProjection(t.viewState.projection),h=e.tileCoord,d=u.getTileCoordExtent(e.wrappedTileCoord),p=u.getTileCoordExtent(h,this.tempExtent)[0]-d[0];return multiply(scale$2(this.inversePixelTransform.slice(),1/r,1/r),this.getRenderTransform(i,o,s,r,l,c,p))}postRender(e,t){const r=t.viewHints,n=!(r[ViewHint.ANIMATING]||r[ViewHint.INTERACTING]);this.renderedPixelToCoordinateTransform_=t.pixelToCoordinateTransform.slice(),this.renderedRotation_=t.viewState.rotation,this.renderedOpacity_=t.layerStatesArray[t.layerIndex].opacity;const i=this.getLayer(),o=i.getRenderMode(),s=e.globalAlpha;e.globalAlpha=this.renderedOpacity_;const a=i.getDeclutter(),l=a?VECTOR_REPLAYS[o].filter(e=>!DECLUTTER.includes(e)):VECTOR_REPLAYS[o],c=t.viewState,u=c.rotation,h=i.getSource(),d=h.getTileGridForProjection(c.projection).getZForResolution(c.resolution,h.zDirection),p=this.renderedTiles,f=[],g=[],m=[],y=getUid(i);let b=!0;for(let v=p.length-1;v>=0;--v){const r=p[v];b=b&&!r.getReplayState(i).dirty;const o=r.executorGroups[y].filter(e=>e.hasExecutors(l));if(0===o.length)continue;const s=this.getTileRenderTransform(r,t),c=r.tileCoord[0];let h=!1;const _=o[0].getClipCoords(s);let E,w=e;if(_){E=new ZIndexContext,w=E.getContext();for(let e=0,t=f.length;e{const e=this.sourceImage_.getState();e!=ImageState.LOADED&&e!=ImageState.ERROR||(this.unlistenSource_(),this.reproject_())}),this.sourceImage_.load())}}unlistenSource_(){unlistenByKey(this.sourceListenerKey_),this.sourceListenerKey_=null}}const DECIMALS$1=4,ImageSourceEventType={IMAGELOADSTART:"imageloadstart",IMAGELOADEND:"imageloadend",IMAGELOADERROR:"imageloaderror"};class ImageSourceEvent extends BaseEvent{constructor(e,t){super(e),this.image=t}}class ImageSource extends Source{constructor(e){super({attributions:e.attributions,projection:e.projection,state:e.state,interpolate:void 0===e.interpolate||e.interpolate}),this.on,this.once,this.un,this.loader=e.loader||null,this.resolutions_=void 0!==e.resolutions?e.resolutions:null,this.reprojectedImage_=null,this.reprojectedRevision_=0,this.image=null,this.wantedExtent_,this.wantedResolution_,this.static_=!!e.loader&&0===e.loader.length,this.wantedProjection_=null}getResolutions(){return this.resolutions_}setResolutions(e){this.resolutions_=e}findNearestResolution(e){const t=this.getResolutions();return t&&(e=t[linearFindNearest(t,e,0)]),e}getImage(e,t,r,n){const i=this.getProjection();if(!i||!n||equivalent$1(i,n))return i&&(n=i),this.getImageInternal(e,t,r,n);if(this.reprojectedImage_){if(this.reprojectedRevision_==this.getRevision()&&equivalent$1(this.reprojectedImage_.getProjection(),n)&&this.reprojectedImage_.getResolution()==t&&equals$1(this.reprojectedImage_.getExtent(),e))return this.reprojectedImage_;this.reprojectedImage_.dispose(),this.reprojectedImage_=null}return this.reprojectedImage_=new ReprojImage(i,n,e,t,r,(e,t,r)=>this.getImageInternal(e,t,r,i),this.getInterpolate()),this.reprojectedRevision_=this.getRevision(),this.reprojectedImage_}getImageInternal(e,t,r,n){if(this.loader){const i=getRequestExtent(e,t,r,1),o=this.findNearestResolution(t);if(this.image&&(this.static_||this.wantedProjection_===n&&(this.wantedExtent_&&containsExtent(this.wantedExtent_,i)||containsExtent(this.image.getExtent(),i))&&(this.wantedResolution_&&fromResolutionLike(this.wantedResolution_)===o||fromResolutionLike(this.image.getResolution())===o)))return this.image;this.wantedProjection_=n,this.wantedExtent_=i,this.wantedResolution_=o,this.image=new ImageWrapper(i,o,r,this.loader),this.image.addEventListener(EventType$1.CHANGE,this.handleImageChange.bind(this))}return this.image}handleImageChange(e){const t=e.target;let r;switch(t.getState()){case ImageState.LOADING:this.loading=!0,r=ImageSourceEventType.IMAGELOADSTART;break;case ImageState.LOADED:this.loading=!1,r=ImageSourceEventType.IMAGELOADEND;break;case ImageState.ERROR:this.loading=!1,r=ImageSourceEventType.IMAGELOADERROR;break;default:return}this.hasListener(r)&&this.dispatchEvent(new ImageSourceEvent(r,t))}}function getRequestExtent(e,t,r,n){const i=t/r,o=getCenter(e),s=ceil(getWidth(e)/i,DECIMALS$1),a=ceil(getHeight(e)/i,DECIMALS$1);return getForViewAndSize(o,i,0,[s+2*ceil((n-1)*s/2,DECIMALS$1),a+2*ceil((n-1)*a/2,DECIMALS$1)])}const tmpTileCoord=[0,0,0],DECIMALS=5;class TileGrid{constructor(e){let t;if(this.minZoom=void 0!==e.minZoom?e.minZoom:0,this.resolutions_=e.resolutions,assert$1(isSorted(this.resolutions_,(e,t)=>t-e),"`resolutions` must be sorted in descending order"),!e.origins)for(let n=0,i=this.resolutions_.length-1;n{const n=new TileRange(Math.min(0,e[0]),Math.max(e[0]-1,-1),Math.min(0,e[1]),Math.max(e[1]-1,-1));if(r){const e=this.getTileRangeForExtentAndZ(r,t);n.minX=Math.max(e.minX,n.minX),n.maxX=Math.min(e.maxX,n.maxX),n.minY=Math.max(e.minY,n.minY),n.maxY=Math.min(e.maxY,n.maxY)}return n}):r&&this.calculateTileRanges_(r)}forEachTileCoord(e,t,r){const n=this.getTileRangeForExtentAndZ(e,t);for(let i=n.minX,o=n.maxX;i<=o;++i)for(let e=n.minY,s=n.maxY;e<=s;++e)r([t,i,e])}forEachTileCoordParentTileRange(e,t,r,n){let i,o,s,a=null,l=e[0]-1;for(2===this.zoomFactor_?(o=e[1],s=e[2]):a=this.getTileCoordExtent(e,n);l>=this.minZoom;){if(void 0!==o&&void 0!==s?(o=Math.floor(o/2),s=Math.floor(s/2),i=createOrUpdate$1(o,o,s,s,r)):i=this.getTileRangeForExtentAndZ(a,l,r),t(l,i))return!0;--l}return!1}getExtent(){return this.extent_}getMaxZoom(){return this.maxZoom}getMinZoom(){return this.minZoom}getOrigin(e){return this.origin_?this.origin_:this.origins_[e]}getResolution(e){return this.resolutions_[e]}getResolutions(){return this.resolutions_}getTileCoordChildTileRange(e,t,r){if(e[0]this.maxZoom||t0?n:Math.max(o/r[0],i/r[1]);const s=t+1,a=new Array(s);for(let l=0;lthis.maxQueueLength_;)this.queue_.shift().callback(null,null)}dispatch_(){if(this.running_||0===this.queue_.length)return;const e=this.queue_.shift();this.job_=e;const t=e.inputs[0].width,r=e.inputs[0].height,n=e.inputs.map(function(e){return e.data.buffer}),i=this.workers_.length;if(this.running_=i,1===i)return void this.workers_[0].postMessage({buffers:n,meta:e.meta,imageOps:this.imageOps_,width:t,height:r},n);const o=e.inputs[0].data.length,s=4*Math.ceil(o/4/i);for(let a=0;athis.getTileInternal(e,t,r,n,s,o),this.reprojectionErrorThreshold_,this.renderReprojectionEdges_,this.tileOptions);return d.key=l,d}getTileInternal(e,t,r,n,i,o){const s=this.getKey(),a=getCacheKey(this,s,e,t,r);if(o&&o.containsKey(a))return o.get(a);const l=this.createTile_(e,t,r,n,i,s);return o?.set(a,l),l}setRenderReprojectionEdges(e){this.renderReprojectionEdges_!=e&&(this.renderReprojectionEdges_=e,this.changed())}setTileGridForProjection(e,t){const r=get$2(e);if(r){const e=getUid(r);e in this.tileGridForProjection||(this.tileGridForProjection[e]=t)}}}function defaultTileLoadFunction(e,t){if(WORKER_OFFSCREEN_CANVAS){const r=e.getCrossOrigin();let n="same-origin",i="same-origin";return"anonymous"===r||""===r?(n="cors",i="omit"):"use-credentials"===r&&(n="cors",i="include"),void fetch(t,{mode:n,credentials:i}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(e=>createImageBitmap(e)).then(t=>{const r=e.getImage();r.width=t.width,r.height=t.height,r.getContext("2d").drawImage(t,0,0),t.close?.(),r.dispatchEvent(new Event("load"))}).catch(()=>{e.getImage().dispatchEvent(new Event("error"))})}e.getImage().src=t}class TileJSON extends TileImage{constructor(e){if(super({attributions:e.attributions,cacheSize:e.cacheSize,crossOrigin:e.crossOrigin,interpolate:e.interpolate,projection:get$2("EPSG:3857"),reprojectionErrorThreshold:e.reprojectionErrorThreshold,state:"loading",tileLoadFunction:e.tileLoadFunction,wrapX:void 0===e.wrapX||e.wrapX,transition:e.transition,zDirection:e.zDirection}),this.tileJSON_=null,this.tileSize_=e.tileSize,e.url)if(e.jsonp)jsonp(e.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{const t=new XMLHttpRequest;t.addEventListener("load",this.onXHRLoad_.bind(this)),t.addEventListener("error",this.onXHRError_.bind(this)),t.open("GET",e.url),t.send()}else{if(!e.tileJSON)throw new Error("Either `url` or `tileJSON` options must be provided");this.handleTileJSONResponse(e.tileJSON)}}onXHRLoad_(e){const t=e.target;if(!t.status||t.status>=200&&t.status<300){let e;try{e=JSON.parse(t.responseText)}catch{return void this.handleTileJSONError()}this.handleTileJSONResponse(e)}else this.handleTileJSONError()}onXHRError_(e){this.handleTileJSONError()}getTileJSON(){return this.tileJSON_}handleTileJSONResponse(e){const t=get$2("EPSG:4326"),r=this.getProjection();let n;if(void 0!==e.bounds){const i=getTransformFromProjections(t,r);n=applyTransform(e.bounds,i)}const i=extentFromProjection(r),o=e.minzoom||0,s=createXYZ({extent:i,maxZoom:e.maxzoom||22,minZoom:o,tileSize:this.tileSize_});if(this.tileGrid=s,this.tileUrlFunction=createFromTemplates(e.tiles,s),e.attribution&&!this.getAttributions()){const t=void 0!==n?n:i;this.setAttributions(function(r){return intersects$1(t,r.extent)?[e.attribution]:null})}this.tileJSON_=e,this.setState("ready")}handleTileJSONError(){this.setState("error")}}class VectorTile extends UrlTile{constructor(e){const t=e.projection||"EPSG:3857",r=e.extent||extentFromProjection(t),n=e.tileGrid||createXYZ({extent:r,maxResolution:e.maxResolution,maxZoom:void 0!==e.maxZoom?e.maxZoom:22,minZoom:e.minZoom,tileSize:e.tileSize||512});super({attributions:e.attributions,attributionsCollapsible:e.attributionsCollapsible,cacheSize:e.cacheSize,interpolate:!0,projection:t,state:e.state,tileGrid:n,tileLoadFunction:e.tileLoadFunction?e.tileLoadFunction:defaultLoadFunction,tileUrlFunction:e.tileUrlFunction,url:e.url,urls:e.urls,wrapX:void 0===e.wrapX||e.wrapX,transition:e.transition,zDirection:void 0===e.zDirection?1:e.zDirection}),this.format_=e.format?e.format:null,this.tileKeysBySourceTileUrl_={},this.sourceTiles_={},this.overlaps_=null==e.overlaps||e.overlaps,this.tileClass=e.tileClass?e.tileClass:VectorTile$1,this.tileGrids_={}}getOverlaps(){return this.overlaps_}getSourceTiles(e,t,r){if(r.getState()===TileState.IDLE){r.setState(TileState.LOADING);const n=r.wrappedTileCoord,i=this.getTileGridForProjection(t);let o=i.getTileCoordExtent(n);const s=n[0],a=i.getResolution(s);buffer(o,-a,o);const l=this.projection;t&&this.projection&&!equivalent$1(t,l)&&(o=transformExtent(o,t,l));const c=this.tileGrid,u=c.getExtent();u&&getIntersection(o,u,o);let h=a;t&&l&&!equivalent$1(t,l)&&(h=a/l.getMetersPerUnit()/t.getMetersPerUnit());const d=c.getZForResolution(h,this.zDirection);c.forEachTileCoord(o,d,n=>{const i=this.tileUrlFunction(n,e,t);this.sourceTiles_[i]||(this.sourceTiles_[i]=new this.tileClass(n,i?TileState.IDLE:TileState.EMPTY,i,this.format_,this.tileLoadFunction));const o=this.sourceTiles_[i];r.sourceTiles.push(o),this.tileKeysBySourceTileUrl_[i]||(this.tileKeysBySourceTileUrl_[i]=[]),this.tileKeysBySourceTileUrl_[i].push(r.getKey());const s=o.getState();if(s{this.handleTileChange(t);const n=o.getState();if(n===TileState.LOADED||n===TileState.ERROR){const t=o.getKey();t in r.errorTileKeys?o.getState()===TileState.LOADED&&delete r.errorTileKeys[t]:r.loadingSourceTiles--,n===TileState.ERROR?r.errorTileKeys[t]=!0:o.removeEventListener(EventType$1.CHANGE,e),0===r.loadingSourceTiles&&r.setState(isEmpty$1(r.errorTileKeys)?TileState.LOADED:TileState.ERROR)}};o.addEventListener(EventType$1.CHANGE,e),r.loadingSourceTiles++}s===TileState.IDLE&&(o.extent=c.getTileCoordExtent(n),o.projection=this.projection,o.resolution=c.getResolution(n[0]),o.load())}),r.loadingSourceTiles||r.setState(r.sourceTiles.some(e=>e.getState()===TileState.ERROR)?TileState.ERROR:TileState.LOADED)}return r.sourceTiles}removeSourceTiles(e){const t=e.getKey(),r=e.sourceTiles;for(let n=0,i=r.length;n{u=u&&!this.tileUrlFunction(e,n,l)})}const h=new VectorRenderTile(o,u?TileState.EMPTY:TileState.IDLE,s,this.getSourceTiles.bind(this,n,i),this.removeSourceTiles.bind(this));return h.key=this.getKey(),h}getTileGridForProjection(e){const t=e.getCode();let r=this.tileGrids_[t];if(!r){const n=this.projection;if(null!==n&&!equivalent$1(n,e))return getForProjection(e);const i=this.tileGrid,o=i.getResolutions().slice(),s=o.map(function(e,t){return i.getOrigin(t)}),a=o.map(function(e,t){return i.getTileSize(t)}),l=DEFAULT_MAX_ZOOM+1;for(let e=o.length;ed?h-L+d:d-L,O=Math.atan(Math.sqrt(P*P+k*k)),j=m*Math.cos(O)+g*Math.sin(O)*Math.cos(f-L),M=Math.cos(O),D=255*j,B=Math.min(Math.max(2*t.sunEl,0),1),U=1.875-1.75*t.opacity,z=.5!==t.opacity?d*((Math.pow(U,O)-1)/(Math.pow(U,d)-1)):O,F={r:(1-M)*v.r*B*255,g:(1-M)*v.g*B*255,b:(1-M)*v.b*B*255,a:(1-M)*v.a*B*255},N=Math.abs(((L+f)/Math.PI+.5)%2-1),$={r:(y.r*(1-N)+b.r*N)*D,g:(y.g*(1-N)+b.g*N)*D,b:(y.b*(1-N)+b.b*N)*D,a:(y.a*(1-N)+b.a*N)*D},R=4*(w*n+E),s[R]=F.r*(1-N)+$.r,s[R+1]=F.g*(1-N)+$.g,s[R+2]=F.b*(1-N)+$.b,s[R+3]=o[R+3]*t.opacity*B*Math.sin(z);return new ImageData(s,n,i)}function raster(e,t){const r=e[0],n=r.width,i=r.height,o=r.data,s=new Uint8ClampedArray(o.length),a=n-1,l=i-1,c=[0,0,0,0];let u,h,d;const p=(f=t.saturation)>0?1-1/(1.001-f):-f;var f;const g=(m=t.contrast)>0?1/(1-m):1+m;var m;const y=function(e){e*=Math.PI/180;const t=Math.sin(e),r=Math.cos(e);return[(2*r+1)/3,(-Math.sqrt(3)*t-r+1)/3,(Math.sqrt(3)*t-r+1)/3]}(t.hueRotate),b=y,v=[y[2],y[0],y[1]],_=[y[1],y[2],y[0]],E=t.brightnessLow,w=t.brightnessHigh;for(h=0;h<=l;++h)for(u=0;u<=a;++u){d=4*(h*n+u),c[0]=o[d],c[1]=o[d+1],c[2]=o[d+2],c[3]=o[d+3];const e=c[0],t=c[1],r=c[2],i=(e,t)=>{let r=0;for(let n=0;n{t.accessToken=e,t.accessTokenParam=r})),t}function applyStyle(e,t,r="",n={},i){let o,s,a,l,c=!0;return"string"==typeof r||Array.isArray(r)?l=r:(a=r,l=a.source||a.layers,n=a),"string"==typeof n?(o=n,a={}):(o=n.styleUrl,a=n),!1===a.updateSource&&(c=!1),i||(i=a.resolutions),o||"string"!=typeof t||t.trim().startsWith("{")||(o=t),o&&(o=o.startsWith("data:")?location.href:normalizeStyleUrl(o,a.accessToken),a=completeOptions(o,a)),new Promise(function(r,n){getGlStyle(t,a).then(function(t){if(8!=t.version)return n(new Error("glStyle version 8 required."));if(!(e instanceof VectorLayer||e instanceof VectorTileLayer))return n(new Error("Can only apply to VectorLayer or VectorTileLayer"));const u=e instanceof VectorTileLayer?"vector":"geojson";if(l?s=Array.isArray(l)?t.layers.find(function(e){return e.id===l[0]}).source:l:(s=t.layers.find(function(e){return e.source&&t.sources[e.source].type===u}).source,l=s),!s)return n(new Error(`No ${u} source found in the glStyle.`));function h(){if(!c)return Promise.resolve();if(e instanceof VectorTileLayer)return setupVectorSource(t.sources[s],o,a).then(function(t){const r=e.getSource();r?t!==r&&(r.setTileUrlFunction(t.getTileUrlFunction()),"function"==typeof r.setUrls&&"function"==typeof t.getUrls&&r.setUrls(t.getUrls()),r.format_||(r.format_=t.format_),r.getAttributions()||r.setAttributions(t.getAttributions()),r.getTileLoadFunction()===defaultLoadFunction&&r.setTileLoadFunction(t.getTileLoadFunction()),equivalent$1(r.getProjection(),t.getProjection())&&(r.tileGrid=t.getTileGrid())):e.setSource(t);const n=e.getSource().getTileGrid();!isFinite(e.getMaxResolution())&&!isFinite(e.getMinZoom())&&n.getMinZoom()>0&&e.setMaxResolution(getResolutionForZoom(Math.max(0,n.getMinZoom()-1e-12),n.getResolutions()))});const r=t.sources[s];let n=e.getSource();n&&n.get("mapbox-source")===r||(n=setupGeoJSONSource(r,o,a));const i=e.getSource();return i?n!==i&&(i.getAttributions()||i.setAttributions(n.getAttributions()),i.format_||(i.format_=n.getFormat()),i.url_=n.getUrl()):e.setSource(n),Promise.resolve()}let d,p;const f={},g={};function m(){if(p||t.sprite&&!f)p?(e.setStyle(p),h().then(r).catch(n)):n(new Error("Something went wrong trying to apply style."));else{if(a.projection&&!i){const e=get$2(a.projection).getUnits();"m"!==e&&(i=defaultResolutions.map(t=>t/METERS_PER_UNIT$1[e]))}let o;const c=e.getSource();c instanceof VectorTile&&c.format_ instanceof MVT&&(o=c.format_.layerName_),p=stylefunction(e,t,l,i,f,g,(e,t=a.webfonts)=>getFonts(e,t),a.getImage,o),e.getStyle()?h().then(r).catch(n):n(new Error(`Nothing to show for source [${s}]`))}}if(t.sprite){const e=normalizeSpriteDefinition(t.sprite,a.accessToken,o||location.href);d=WORKER_OFFSCREEN_CANVAS?1:window.devicePixelRatio>=1.5?.5:1;const r=.5==d?"@2x":"";Promise.all(e.map(function(e){const t=new URL(e.url);let i=t.origin+t.pathname+r+".json"+t.search;return new Promise(function(e,r){fetchResource("Sprite",i,a).then(e).catch(function(){i=t.origin+t.pathname+".json"+t.search,fetchResource("Sprite",i,a).then(e).catch(r)})}).then(function(i){let o;if(void 0===i&&n(new Error("No sprites found.")),o=t.origin+t.pathname+r+".png"+t.search,a.transformRequest){const e=a.transformRequest(o,"SpriteImage")||o;(e instanceof Request||e instanceof Promise)&&(o=e)}g[e.id]=o;for(const t in i){const r="default"==e.id?t:`${e.id}:${t}`;f[r]=i[t]}}).catch(function(e){n(new Error(`Sprites cannot be loaded: ${i}: ${e.message}`))})})).then(m).catch(n)}else m()}).catch(n)})}function getSourceIdByRef(e,t){let r;return e.some(function(e){if(e.id==t)return r=e.source,!0}),r}function extentFromTileJSON(e,t){const r=e.bounds;if(r){const e=fromLonLat([r[0],r[1]],t),n=fromLonLat([r[2],r[3]],t);return[e[0],e[1],n[0],n[1]]}return get$2(t).getExtent()}function sourceOptionsFromTileJSON(e,t,r){const n=new TileJSON({tileJSON:t,tileSize:e.tileSize||t.tileSize||512}),i=n.getTileJSON(),o=n.getTileGrid(),s=get$2(r.projection||"EPSG:3857"),a=extentFromTileJSON(i,s),l=s.getExtent(),c=i.minzoom||0,u=i.maxzoom||22,h={attributions:n.getAttributions(),projection:s,tileGrid:new TileGrid({origin:l?getTopLeft(l):o.getOrigin(0),extent:a||o.getExtent(),minZoom:c,resolutions:getTileResolutions(s,t.tileSize).slice(0,u+1),tileSize:o.getTileSize(0)})};return Array.isArray(i.tiles)?h.urls=i.tiles:h.url=i.tiles,h}function getBackgroundColor(e,t,r,n){const i={id:e.id,type:e.type},o=e.layout||{},s=e.paint||{};let a;i.paint=s,cameraObj.zoom=getZoomForResolution(t,r.resolutions||defaultResolutions),cameraObj.distanceFromCenter=0;const l=getValue(i,"paint","background-color",emptyObj,n);return void 0!==s["background-opacity"]&&(a=getValue(i,"paint","background-opacity",emptyObj,n)),"none"==o.visibility?void 0:colorWithOpacity(l,a)}function setupBackgroundLayer(e,t,r){const n=WORKER_OFFSCREEN_CANVAS?{style:{}}:document.createElement("div");return n.className="ol-mapbox-style-background",n.style.position="absolute",n.style.width="100%",n.style.height="100%",new Layer({source:new Source({}),render(i){const o=getBackgroundColor(e,i.viewState.resolution,t,r);return n.style.backgroundColor=o,n}})}function setupVectorSource(e,t,r){return new Promise(function(n,i){getTileJson(e,t,r).then(function({tileJson:t,tileLoadFunction:i}){const o=sourceOptionsFromTileJSON(e,t,r);o.tileLoadFunction=i,o.format=new MVT({layerName:"mvt:layer"});const s=new VectorTile(o);s.set("mapbox-source",e),n(s)}).catch(i)})}function setupVectorLayer(e,t,r){const n=new VectorTileLayer({declutter:!0,visible:!1});return setupVectorSource(e,t,r).then(function(e){n.setSource(e)}).catch(function(){n.setSource(void 0)}),n}function getBboxTemplate(e){return`{bbox-${(e?e.getCode():"EPSG:3857").toLowerCase().replace(/[^a-z0-9]/g,"-")}}`}function setupRasterSource(e,t,r){return new Promise(function(n,i){getTileJson(e,t,r).then(function({tileJson:t,tileLoadFunction:i}){const o=new TileJSON({interpolate:void 0===r.interpolate||r.interpolate,transition:0,crossOrigin:"anonymous",tileJSON:t});o.tileGrid=sourceOptionsFromTileJSON(e,t,r).tileGrid,r.projection&&(o.projection=get$2(r.projection));const s=o.getTileUrlFunction();i&&o.setTileLoadFunction(i),o.setTileUrlFunction(function(e,t,r){const n=getBboxTemplate(r);let i=s(e,t,r);if(-1!=i.indexOf(n)){const t=o.getTileGrid().getTileCoordExtent(e);i=i.replace(n,t.toString())}return i}),o.set("mapbox-source",e),n(o)}).catch(function(e){i(e)})})}function setupRasterLayer(e,t,r){const n=new TileLayer;return setupRasterSource(e,t,r).then(function(e){n.setSource(e)}).catch(function(){n.setSource(void 0)}),n}function setupRasterOpLayer(e,t,r){const n=setupRasterLayer(e,t,r);return new ImageLayer({source:new RasterSource({operationType:"image",operation:raster,sources:[n]})})}function setupHillshadeLayer(e,t,r){const n=setupRasterLayer(e,t,r);return new ImageLayer({source:new RasterSource({operationType:"image",operation:hillshade,sources:[n]})})}function setupGeoJSONSource(e,t,r){const n=r.projection?new GeoJSON({dataProjection:r.projection}):new GeoJSON,i=e.data,o={};if("string"==typeof i){const[o]=normalizeSourceUrl(i,r.accessToken,r.accessTokenParam||"access_token",t||location.href);if(/\{bbox-[0-9a-z-]+\}/.test(o)){const t=(e,t,r)=>{const n=getBboxTemplate(r);return o.replace(n,`${e.join(",")}`)},i=new VectorSource({attributions:e.attribution,format:n,loader:(e,n,o,s,a)=>{fetchResource("GeoJSON","function"==typeof t?t(e,n,o):t,r).then(e=>{const t=i.getFormat().readFeatures(e,{featureProjection:o});i.addFeatures(t),s(t)}).catch(()=>{i.removeLoadedExtent(e),a()})},strategy:bbox});return i.set("mapbox-source",e),i}const s=new VectorSource({attributions:e.attribution,format:n,url:o,loader:(e,t,n,i,a)=>{fetchResource("GeoJSON",o,r).then(e=>{const t=s.getFormat().readFeatures(e,{featureProjection:n});s.addFeatures(t),i(t)}).catch(()=>{s.removeLoadedExtent(e),a()})}});return s}o.features=n.readFeatures(i,{featureProjection:"EPSG:3857"});const s=new VectorSource(Object.assign({attributions:e.attribution,format:n},o));return s.set("mapbox-source",e),s}function setupGeoJSONLayer(e,t,r){return new VectorLayer({declutter:!0,source:setupGeoJSONSource(e,t,r),visible:!1})}function prerenderRasterLayer(e,t,r){let n=null;return function(i){e.paint&&"raster-opacity"in e.paint&&i.frameState.viewState.zoom!==n&&(n=i.frameState.viewState.zoom,delete r[e.id],updateRasterLayerProperties(e,t,n,r))}}function updateRasterLayerProperties(e,t,r,n){cameraObj.zoom=r,cameraObj.distanceFromCenter=0;const i=getValue(e,"paint","raster-opacity",emptyObj,n);t.setOpacity(i)}function manageVisibility(e,t){function r(){const r=t.get("mapbox-style");if(!r)return;const n=derefLayers(r.layers),i=e.get("mapbox-layers"),o=n.filter(function(e){return i.includes(e.id)}).some(function(e){return!e.layout||!e.layout.visibility||"visible"===e.layout.visibility});e.get("visible")!==o&&e.setVisible(o)}e.on("change",r),r()}function setupLayer(e,t,r,n){const i=getFunctionCache(e),o=e.layers,s=r.type,a=r.source||getSourceIdByRef(o,r.ref),l=e.sources[a];let c;if("background"==s)c=setupBackgroundLayer(r,n,i);else if("vector"==l.type)c=setupVectorLayer(l,t,n);else if("raster"==l.type){const e=["raster-saturation","raster-contrast","raster-brightness-max","raster-brightness-min","raster-hue-rotate"];Object.keys(r.paint||{}).find(t=>e.includes(t))?(c=setupRasterOpLayer(l,t,n),c.getSource().on("beforeoperations",function(e){cameraObj.zoom=getZoomForResolution(e.resolution,n.resolutions||defaultResolutions),cameraObj.distanceFromCenter=0;const t=e.data;t.saturation=getValue(r,"paint","raster-saturation",emptyObj,i),t.contrast=getValue(r,"paint","raster-contrast",emptyObj,i),t.brightnessHigh=getValue(r,"paint","raster-brightness-max",emptyObj,i),t.brightnessLow=getValue(r,"paint","raster-brightness-min",emptyObj,i),t.hueRotate=getValue(r,"paint","raster-hue-rotate",emptyObj,i)})):c=setupRasterLayer(l,t,n),c.setVisible(!r.layout||"none"!==r.layout.visibility),c.on("prerender",prerenderRasterLayer(r,c,i))}else if("geojson"==l.type)c=setupGeoJSONLayer(l,t,n);else if("raster-dem"==l.type&&"hillshade"==r.type){const e=setupHillshadeLayer(l,t,n);c=e,e.getSource().on("beforeoperations",function(e){const t=e.data;t.resolution=getPointResolution(n.projection||"EPSG:3857",e.resolution,getCenter(e.extent),"m"),cameraObj.zoom=getZoomForResolution(e.resolution,n.resolutions||defaultResolutions),cameraObj.distanceFromCenter=0,t.encoding=l.encoding,t.vert=5*getValue(r,"paint","hillshade-exaggeration",emptyObj,i),t.sunAz=getValue(r,"paint","hillshade-illumination-direction",emptyObj,i),t.sunEl=35,t.opacity=.3,t.highlightColor=getValue(r,"paint","hillshade-highlight-color",emptyObj,i),t.shadowColor=getValue(r,"paint","hillshade-shadow-color",emptyObj,i),t.accentColor=getValue(r,"paint","hillshade-accent-color",emptyObj,i)}),c.setVisible(!r.layout||"none"!==r.layout.visibility)}const u=a;return c&&c.set("mapbox-source",u),c}function processStyle(e,t,r,n){const i=[];let o=null;if(t instanceof Map$1){if(o=t.getView(),!o.isDef()&&!o.getRotation()&&!o.getResolutions()){const e=n.projection?get$2(n.projection):o.getProjection();o=new View(Object.assign(o.getProperties(),{maxResolution:defaultResolutions[0]/METERS_PER_UNIT$1[e.getUnits()],projection:n.projection||o.getProjection()})),t.setView(o)}"center"in e&&!o.getCenter()&&o.setCenter(fromLonLat(e.center,o.getProjection())),"zoom"in e&&void 0===o.getZoom()&&o.setResolution(defaultResolutions[0]/METERS_PER_UNIT$1[o.getProjection().getUnits()]/Math.pow(2,e.zoom)),o.getCenter()&&void 0!==o.getZoom()||o.fit(o.getProjection().getExtent(),{nearest:!0,size:t.getSize()})}t.set("mapbox-style",e),t.set("mapbox-metadata",{styleUrl:r,options:n});const s=e.layers;let a,l,c,u=[];for(let h=0,d=s.length;h0||r>0)&&e.setMaxResolution(Math.min(getResolutionForZoom(Math.max(0,s-1e-12),defaultResolutions),getResolutionForZoom(Math.max(0,r-1e-12),t.getResolutions()))),a<24&&e.setMinResolution(getResolutionForZoom(a,defaultResolutions))}}else s>0&&e.setMaxResolution(getResolutionForZoom(Math.max(0,s-1e-12),defaultResolutions));u instanceof VectorSource||u instanceof VectorTile?applyStyle(e,r,t,Object.assign({styleUrl:n},o)).then(function(){manageVisibility(e,i),l()}).catch(c):l()}else c(new Error("Error accessing data for source "+e.get("mapbox-source")))};e.set("mapbox-layers",t);const h=i.getLayers();-1===h.getArray().indexOf(e)&&h.push(e),e.getSource()?u():e.once("change:source",u)})}class MapComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");mapInstance;bookmarkSource;searchResultsSource;selectedShapeSource;searchOverlay;searchOverlayElement;selectedPinOverlay;selectedPinElement;crosshairElement;crosshairOverlay;ignoreNextMapClick=!1;setupMap=modifier(e=>{if(this.mapInstance)return;const t=new LayerGroup;this.selectedShapeSource=new VectorSource;const r=new VectorLayer({source:this.selectedShapeSource,style:new Style({stroke:new Stroke({color:"#3388ff",width:4}),fill:new Fill({color:"rgba(51, 136, 255, 0.1)"})}),zIndex:5});this.bookmarkSource=new VectorSource;const n=new VectorLayer({source:this.bookmarkSource,style:e=>{const t=e.get("originalPlace");let r=getComputedStyle(document.documentElement).getPropertyValue("--default-list-color").trim()||"#000000";if(t&&t._listIds&&t._listIds.length>0){const e=t._listIds[0],n=this.storage.lists.find(t=>t.id===e);n&&n.color&&(r=n.color)}return[new Style({image:new CircleStyle({radius:10,fill:new Fill({color:"rgba(0, 0, 0, 0.2)"}),displacement:[0,-2]})}),new Style({image:new CircleStyle({radius:9,fill:new Fill({color:r}),stroke:new Stroke({color:"#fff",width:2})})})]},zIndex:10});this.searchResultsSource=new VectorSource;const i=new Map,o=new VectorLayer({source:this.searchResultsSource,style:e=>{const t=e.get("originalPlace"),r=this.mapUi.selectedPlace;if(r){const e=t.osmId&&r.osmId&&t.osmId===r.osmId,n=t.id&&r.id&&t.id===r.id,i=t.lat===r.lat&&t.lon===r.lon;if(e||n||i)return new Style({})}const n=getIconNameForTags(t.osmTags||t),o=n||"default";if(!i.has(o)){const e=getComputedStyle(document.documentElement).getPropertyValue("--marker-color-primary").trim()||"#ea4335";let t=``;if(n){const r=getIcon(n);if(r){let n=r.trim();const i=n.indexOf("",i)+1,s=n.lastIndexOf("");-1!==i&&-1!==s&&(n=n.substring(o,s)),t=`\n \n \n ${n}\n \n `}}const r=`\n \n \n \n \n \n \n \n ${t}\n \n `;i.set(o,"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(r.trim()))}return new Style({image:new Icon({src:i.get(o),anchor:[.5,.65],scale:1})})},zIndex:11});let s=[14.21683569,27.060114248],a=2.661,l=!1;try{const e=localStorage.getItem("marco:map-view");if(e){const t=JSON.parse(e);t.center&&Array.isArray(t.center)&&2===t.center.length&&"number"==typeof t.zoom&&(s=t.center,a=t.zoom,l=!0)}}catch(T){console.warn("Failed to restore map view:",T)}const c=new View({center:fromLonLat(s),zoom:a,projection:"EPSG:3857"});this.mapInstance=new Map$1({target:e,layers:[t,r,o,n],view:c,controls:defaults$1({zoom:!0,rotate:!0,attribution:!0}),interactions:defaults({dragPan:!1})});const u=toLonLat(c.getCenter());this.mapUi.updateCenter(u[1],u[0]),apply(this.mapInstance,"https://tiles.openfreemap.org/styles/liberty",{webfonts:"data:text/css,"}),this.searchOverlayElement=document.createElement("div"),this.searchOverlayElement.className="search-pulse",this.searchOverlay=new Overlay({element:this.searchOverlayElement,positioning:"center-center",stopEvent:!1}),this.mapInstance.addOverlay(this.searchOverlay),this.selectedPinElement=document.createElement("div"),this.selectedPinElement.className="selected-pin-container";const h=document.createElement("div");h.className="selected-pin",h.innerHTML='';const d=document.createElement("div");d.className="selected-pin-shadow",this.selectedPinElement.appendChild(h),this.selectedPinElement.appendChild(d),this.selectedPinOverlay=new Overlay({element:this.selectedPinElement,positioning:"bottom-center",stopEvent:!1}),this.mapInstance.addOverlay(this.selectedPinOverlay),this.crosshairElement=document.createElement("div"),this.crosshairElement.className="map-crosshair",this.crosshairElement.innerHTML='\n \n \n \n \n ',e.appendChild(this.crosshairElement),this.locationOverlayElement=document.createElement("div"),this.locationOverlayElement.className="search-pulse blue",this.locationOverlay=new Overlay({element:this.locationOverlayElement,positioning:"center-center",stopEvent:!1}),this.mapInstance.addOverlay(this.locationOverlay),e.addEventListener("pointerdown",()=>{this.mapUi.searchBoxHasFocus&&(this.ignoreNextMapClick=!0)},!0);const p=new Geolocation({trackingOptions:{enableHighAccuracy:!0},projection:c.getProjection()}),f=new Feature;f.setStyle(new Style({image:new CircleStyle({radius:6,fill:new Fill({color:"#3399CC"}),stroke:new Stroke({color:"#fff",width:2})})}));const g=new VectorSource({features:[f]}),m=new VectorLayer({source:g,zIndex:15});p.on("change:position",function(){const e=p.getPosition();f.setGeometry(e?new Point(e):null)});const y=document.createElement("div");y.className="ol-control ol-locate";const b=document.createElement("button");let v,_;b.style.display="flex",b.style.alignItems="center",b.style.justifyContent="center",b.innerHTML=`${getIcon("navigation")}`,b.title="Locate Me",y.appendChild(b);const E=()=>{v&&(clearTimeout(v),v=null);try{_&&(p.un("change:position",w),_=null)}catch{}this.locationOverlayElement&&this.locationOverlayElement.classList.remove("active")},w=()=>{const e=p.getPosition(),t=p.getAccuracyGeometry(),r=p.getAccuracy();if(console.debug("Geolocation change:",{coordinates:e,accuracy:r}),!e)return;const n=this.mapInstance.getSize(),i=this.mapInstance.getView();let o=null;if(this.locationOverlayElement){const t=i.getResolution(),n=2*(r||50)/getPointResolution(i.getProjection(),t,e);this.locationOverlayElement.style.width=`${n}px`,this.locationOverlayElement.style.height=`${n}px`,this.locationOverlay.setPosition(e)}if(r&&r<=20&&E(),t){const e=t.getExtent();o=3.162*i.getResolutionForExtent(e,n)}else r&&(o=6.325*r/Math.min(n[0],n[1])/getPointResolution(i.getProjection(),1,e));let s={center:e,duration:1e3};if(o){const e=i.getResolutionForZoom(17);s.resolution=Math.max(o,e)}else s.zoom=16;this.mapInstance.getView().animate(s)},C=()=>{console.debug("Getting current geolocation..."),E(),p.setTracking(!0);const e=p.getPosition();this.locationOverlayElement&&this.locationOverlayElement.classList.add("active"),e&&w(),_=p.on("change:position",w),v=setTimeout(()=>{E()},1e4)};b.addEventListener("click",C);const S=new Control({element:y});this.mapInstance.addLayer(m),this.mapInstance.addControl(S),l||"index"!==this.router.currentRouteName||C(),this.mapInstance.on("singleclick",this.handleMapClick),this.mapInstance.on("moveend",this.handleMapMove),this.mapInstance.on("pointermove",e=>{const t=this.mapInstance.getEventPixel(e.originalEvent),r=this.mapInstance.hasFeatureAtPixel(t,{hitTolerance:10});this.mapInstance.getTarget().style.cursor=r?"pointer":""}),this.storage.rs.on("ready",()=>{this.handleMapMove()})});updateInteractions=modifier(()=>{if(!this.mapInstance)return;this.mapInstance.getInteractions().getArray().slice().forEach(e=>{e instanceof DragPan&&this.mapInstance.removeInteraction(e)});const e=!!this.settings.mapKinetic&&new Kinetic(-.005,.05,100);this.settings.mapKinetic&&window.innerWidth<=768&&(e.minVelocity_=.25),this.mapInstance.addInteraction(new DragPan({kinetic:e}))});updateSearchResults=modifier(()=>{if(!this.searchResultsSource)return;this.searchResultsSource.clear();const e=this.mapUi.searchResults;if(!e||0===e.length)return;const t=[];e.forEach(e=>{if(e.lat&&e.lon){const r=new Feature({geometry:new Point(fromLonLat([e.lon,e.lat])),name:e.title,id:e.id,isSearchResult:!0,originalPlace:e});t.push(r)}}),t.length>0&&this.searchResultsSource.addFeatures(t)});updateSelectedPin=modifier(()=>{const e=this.mapUi.selectedPlace,t=this.mapUi.selectionOptions||{};if(this.searchResultsSource&&this.searchResultsSource.changed(),this.selectedPinOverlay&&this.selectedPinElement)if(this.selectedShapeSource&&this.selectedShapeSource.clear(),e&&e.lat&&e.lon){const n=fromLonLat([e.lon,e.lat]);if(this.selectedPinOverlay.setPosition(n),this.selectedPinElement.classList.remove("active"),this.selectedPinElement.offsetWidth,this.selectedPinElement.classList.add("active"),e.geojson&&this.selectedShapeSource)try{const t=(new GeoJSON).readFeature(e.geojson,{featureProjection:"EPSG:3857"});this.selectedShapeSource.addFeature(t)}catch(r){console.warn("Failed to render selected place shape:",r)}t.preventZoom?this.handlePinVisibility(n,{maintainZoom:!0}):e.bbox?this.zoomToBbox(e.bbox):this.handlePinVisibility(n)}else this.selectedPinElement.classList.remove("active"),this.selectedPinOverlay.setPosition(void 0)});zoomToBbox(e){if(!this.mapInstance||!e)return;const t=this.mapInstance.getView(),r=this.mapInstance.getSize(),n=[...fromLonLat([e.minLon,e.minLat]),...fromLonLat([e.maxLon,e.maxLat])];let i=[.15*r[1],.15*r[0],.15*r[1],.15*r[0]];if(r[0]<=768){const e=.5*r[1],t=.15*e,n=.5*r[1]+.15*e;i[0]=t,i[2]=n}else if(this.args.isSidebarOpen){const e=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),t=parseInt(e,10)||360,n=r[0]-t;i[3]=t+.15*n,i[1]=.15*n}const o=t.getZoom();t.fit(n,{padding:i,duration:1e3,easing:e=>e*(2-e),maxZoom:Math.max(o,18)})}handlePinVisibility(e,t={}){if(!this.mapInstance)return;const r=this.mapInstance.getView().getZoom();if(!t.maintainZoom&&r<16)return void this.animateToSmartCenter(e,16);const n=this.mapInstance.getPixelFromCoordinate(e),i=this.mapInstance.getSize();if(!n||n[0]<0||n[0]>i[0]||n[1]<0||n[1]>i[1]){const r=t.maintainZoom?null:16;this.animateToSmartCenter(e,r)}else this.panIfObscured(e)}animateToSmartCenter(e,t=null){if(!this.mapInstance)return;const r=this.mapInstance.getSize(),n=this.mapInstance.getView();let i=n.getResolution();null!==t&&(i=n.getResolutionForZoom(t));let o=e;if(r[0]<=768){const t=r[1],n=document.querySelector(".app-header"),s=n?n.offsetHeight:60,a=(t/2-(s+(t/2-s)/2))*i;o=[e[0],e[1]-a]}else if(this.args.isSidebarOpen){const t=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),r=(parseInt(t,10)||360)/2*i;o=[e[0]-r,e[1]]}const s={center:o,duration:1e3,easing:e=>e*(2-e)};null!==t&&(s.zoom=t),n.animate(s)}panIfObscured(e){if(!this.mapInstance)return;const t=this.mapInstance.getSize(),r=this.mapInstance.getPixelFromCoordinate(e);if(!r)return;const n=this.mapInstance.getView(),i=n.getCenter(),o=n.getResolution();let s=r[0],a=r[1],l=!1;const c=document.querySelector(".app-header"),u=c?c.offsetHeight:60;if(t[0]<=768){const e=t[1],n=e/2;r[1]>n&&(a=u+(e/2-u)/2,l=!0)}else if(this.args.isSidebarOpen){const e=getComputedStyle(document.documentElement).getPropertyValue("--sidebar-width").trim(),n=parseInt(e,10)||360;r[0]e*(2-e)})}}updateBookmarks=modifier(()=>{const e=this.storage.placesInView;this.loadBookmarks(e)});async loadBookmarks(e=[]){try{if(!this.bookmarkSource)return;e&&0!==e.length||(e=this.storage.placesInView),this.bookmarkSource.clear(),e&&Array.isArray(e)&&e.forEach(e=>{if(e.lat&&e.lon){const t=new Feature({geometry:new Point(fromLonLat([e.lon,e.lat])),name:e.title,id:e.id,isBookmark:!0,originalPlace:e});this.bookmarkSource.addFeature(t)}})}catch(t){console.error("Failed to load bookmarks:",t)}}syncPulse=modifier(()=>{this.searchOverlayElement&&(this.mapUi.isSearching?this.searchOverlayElement.classList.add("active"):this.searchOverlayElement.classList.remove("active"))});syncCreationMode=modifier(()=>{if(this.crosshairElement&&this.mapInstance)if(this.mapUi.isCreating){this.crosshairElement.classList.add("visible");const e=this.mapUi.creationCoordinates;if(e&&e.lat&&e.lon){const t=fromLonLat([e.lon,e.lat]);this.animateToCrosshair(t)}}else this.crosshairElement.classList.remove("visible")});animateToCrosshair(e){if(!this.mapInstance||!this.crosshairElement)return;const t=this.mapInstance.getTargetElement().getBoundingClientRect(),r=this.crosshairElement.getBoundingClientRect(),n=r.left+r.width/2-t.left,i=r.top+r.height/2-t.top,o=this.mapInstance.getSize(),s=n-o[0]/2,a=i-o[1]/2,l=this.mapInstance.getView(),c=l.getResolution(),u=s*c,h=-a*c,d=e[0]-u,p=e[1]-h,f=l.getCenter();Math.sqrt(Math.pow(f[0]-d,2)+Math.pow(f[1]-p,2))>5*c&&l.animate({center:[d,p],duration:800,easing:e=>e*(2-e)})}handleMapMove=async()=>{if(!this.mapInstance||this.isDestroying||this.isDestroyed)return;const e=toLonLat(this.mapInstance.getView().getCenter());if(this.mapUi.updateCenter(e[1],e[0]),this.mapUi.isCreating){const e=this.mapInstance.getTargetElement().getBoundingClientRect(),t=this.crosshairElement.getBoundingClientRect(),r=t.left+t.width/2-e.left,n=t.top+t.height/2-e.top,i=toLonLat(this.mapInstance.getCoordinateFromPixel([r,n])),o=parseFloat(i[1].toFixed(6)),s=parseFloat(i[0].toFixed(6));this.mapUi.updateCreationCoordinates(o,s),this.router.replaceWith("place.new",{queryParams:{lat:o,lon:s}})}const t=this.mapInstance.getSize(),r=this.mapInstance.getView().calculateExtent(t),[n,i]=toLonLat([r[0],r[1]]),[o,s]=toLonLat([r[2],r[3]]),a={minLat:i,minLon:n,maxLat:s,maxLon:o};this.mapUi.updateBounds(a),await this.storage.loadPlacesInBounds(a),this.nostrData.loadPlacesInBounds(a),this.loadBookmarks(this.storage.placesInView);try{const e=this.mapInstance.getView(),t={center:toLonLat(e.getCenter()),zoom:e.getZoom()};localStorage.setItem("marco:map-view",JSON.stringify(t))}catch(l){console.warn("Failed to save map view:",l)}};handleMapClick=async e=>{if(this.ignoreNextMapClick)return void(this.ignoreNextMapClick=!1);const t=this.mapInstance.getFeaturesAtPixel(e.pixel,{hitTolerance:10});let r=null,n=null,i=null;if(t&&t.length>0){console.debug(`Found ${t.length} features in map layer:`);for(const r of t)console.debug(r);const e=t.find(e=>e.get("isBookmark")),o=t.find(e=>e.get("isSearchResult"));e?r=e.get("originalPlace"):o&&(n=o.get("originalPlace"));const s=t[0].getProperties();s.name&&(i=s.name)}const o=e=>{("search"===this.router.currentRouteName||this.mapUi.currentSearch&&this.mapUi.searchResults.length>0)&&(this.mapUi.returnToSearch=!0),this.mapUi.preventNextZoom=!0,this.mapUi.selectPlace(e,{preventZoom:!0}),this.mapUi.showSidebar(),this.router.transitionTo("place",e)};if(this.args.isSidebarOpen){const e=r||n;return e?(console.debug("Clicked feature while sidebar open (switching):",e),void o(e)):void(this.args.onOutsideClick&&this.args.onOutsideClick())}if(r)return console.debug("Clicked bookmark:",r),void o(r);if(n)return console.debug("Clicked search result:",n),void o(n);if(this.mapInstance.getView().getZoom()<16)return;const s=toLonLat(e.coordinate),[a,l]=s,c=i?30:50;if(this.searchOverlayElement){const t=this.mapInstance.getView(),r=2*c/getPointResolution(t.getProjection(),t.getResolution(),e.coordinate);this.searchOverlayElement.style.width=`${r}px`,this.searchOverlayElement.style.height=`${r}px`,this.searchOverlay.setPosition(e.coordinate)}this.mapUi.startSearch();const u={lat:l.toFixed(6),lon:a.toFixed(6),q:null,category:null,selected:i||null};this.router.transitionTo("search",{queryParams:u})};static{setComponentTemplate(templateFactory({id:null,block:'[[[11,0],[16,0,[29,["map-container ",[52,[30,1],"sidebar-open"]]]],[4,[30,0,["setupMap"]],null,null],[4,[30,0,["updateInteractions"]],null,null],[4,[30,0,["updateBookmarks"]],null,null],[4,[30,0,["updateSearchResults"]],null,null],[4,[30,0,["updateSelectedPin"]],null,null],[4,[30,0,["syncPulse"]],null,null],[4,[30,0,["syncCreationMode"]],null,null],[12],[13]],["@isSidebarOpen"],["if"]]',moduleName:"/home/basti/src/marco/app/components/map.gjs",isStrictMode:!0}),this)}}class UserMenuComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"osmAuth",[service])}#Qe=void initializeDeferredDecorator(this,"osmAuth");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"isNostrConnectModalOpen",[tracked],function(){return!1})}#Ye=void initializeDeferredDecorator(this,"isNostrConnectModalOpen");connectRS(){this.args.onClose(),this.args.storage.showConnectWidget()}static{decorateMethodV2(this.prototype,"connectRS",[action])}disconnectRS(){this.args.storage.disconnect()}static{decorateMethodV2(this.prototype,"disconnectRS",[action])}connectOsm(){this.args.onClose(),this.osmAuth.login()}static{decorateMethodV2(this.prototype,"connectOsm",[action])}disconnectOsm(){this.osmAuth.logout()}static{decorateMethodV2(this.prototype,"disconnectOsm",[action])}openNostrConnectModal(){this.isNostrConnectModalOpen=!0}static{decorateMethodV2(this.prototype,"openNostrConnectModal",[action])}closeNostrConnectModal(){this.isNostrConnectModalOpen=!1}static{decorateMethodV2(this.prototype,"closeNostrConnectModal",[action])}disconnectNostr(){this.nostrAuth.disconnect()}static{decorateMethodV2(this.prototype,"disconnectNostr",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"user-menu-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"account-list"],[12],[1,"\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["remotestorage",18]],null],[1,"\\n "],[10,1],[12],[1,"RemoteStorage"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectRS"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectRS"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,1,["connected"]],[[[1," "],[10,"strong"],[12],[1,[30,1,["userAddress"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",18]],null],[1,"\\n "],[10,1],[12],[1,"OpenStreetMap"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectOsm"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["connectOsm"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["osmAuth","isConnected"]],[[[1," "],[10,"strong"],[12],[1,[30,0,["osmAuth","userDisplayName"]]],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,"li"],[14,0,"account-item"],[12],[1,"\\n "],[10,0],[14,0,"account-header"],[12],[1,"\\n "],[10,0],[14,0,"account-info"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",18]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[11,"button"],[24,0,"btn-text text-danger"],[24,4,"button"],[4,[32,1],["click",[30,0,["disconnectNostr"]]],null],[12],[1,"Disconnect"],[13],[1,"\\n"]],[]],[[[1," "],[11,"button"],[24,0,"btn-text text-primary"],[24,4,"button"],[4,[32,1],["click",[30,0,["openNostrConnectModal"]]],null],[12],[1,"Connect"],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n "],[10,0],[14,0,"account-status"],[12],[1,"\\n"],[41,[30,0,["nostrAuth","isConnected"]],[[[1," "],[10,"strong"],[15,"title",[30,0,["nostrAuth","pubkey"]]],[12],[1,"\\n "],[1,[30,0,["nostrData","userDisplayName"]]],[1,"\\n "],[13],[1,"\\n"]],[]],[[[1," Not connected\\n"]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[41,[30,0,["isNostrConnectModalOpen"]],[[[1," "],[8,[32,2],null,[["@onClose"],[[30,0,["closeNostrConnectModal"]]]],[["default"],[[[[1,"\\n "],[8,[32,3],null,[["@onConnect"],[[30,0,["closeNostrConnectModal"]]]],null],[1,"\\n "]],[]]]]],[1,"\\n"]],[]],null]],["@storage"],["if"]]',moduleName:"/home/basti/src/marco/app/components/user-menu.gjs",scope:()=>[IconComponent,on,Modal,NostrConnectComponent],isStrictMode:!0}),this)}}function identity(e){return e}function castForPromiseHelper(e){if(e)if(e instanceof TaskInstance)e.executor.asyncErrorsHandled=!0;else if(e instanceof Yieldable)return e._toPromise();return e}function castAwaitables(e,t){if(Array.isArray(e))return e.map(t);if("object"==typeof e&&null!==e){let r={};return Object.keys(e).forEach(n=>{r[n]=t(e[n])}),r}return e}function taskAwareVariantOf(e,t,r){return function(n){let i=castAwaitables(n,castForPromiseHelper),o=r(i),s=RSVP.defer();e[t](i).then(s.resolve,s.reject);let a=!1,l=()=>{a||(a=!0,o.forEach(e=>{e&&(e instanceof TaskInstance?e.cancel():"function"==typeof e[cancelableSymbol]&&e[cancelableSymbol]())}))},c=s.promise.finally(l);return c[cancelableSymbol]=l,c}}taskAwareVariantOf(RSVP.Promise,"all",identity);class EmberYieldable extends Yieldable{_deferable(){return EMBER_ENVIRONMENT.defer()}}class TimeoutYieldable extends EmberYieldable{constructor(e){super(),this.ms=e}onYield(e){let t=later(()=>e.next(),this.ms);return()=>cancel(t)}}function timeout(e){return new TimeoutYieldable(e)}class SearchBoxComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"photon",[service])}#Je=void initializeDeferredDecorator(this,"photon");static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"map",[service])}#et=void initializeDeferredDecorator(this,"map");static{decorateFieldV2(this.prototype,"_internalQuery",[tracked],function(){return""})}#tt=void initializeDeferredDecorator(this,"_internalQuery");static{decorateFieldV2(this.prototype,"results",[tracked],function(){return[]})}#rt=void initializeDeferredDecorator(this,"results");static{decorateFieldV2(this.prototype,"isFocused",[tracked],function(){return!1})}#nt=void initializeDeferredDecorator(this,"isFocused");static{decorateFieldV2(this.prototype,"isLoading",[tracked],function(){return!1})}#it=void initializeDeferredDecorator(this,"isLoading");get query(){return this.args.query??this._internalQuery}set query(e){this._internalQuery=e}get showPopover(){return this.isFocused&&this.results.length>0}handleInput(e){const t=e.target.value;this.query=t,this.args.onQueryChange&&this.args.onQueryChange(t),t.length<2?this.results=[]:this.searchTask.perform(t)}static{decorateMethodV2(this.prototype,"handleInput",[action])}searchTask=buildTask(()=>({context:this,generator:function*(e){yield timeout(300);const t="string"==typeof e?e:this.query;if(!(t.length<2)){this.isLoading=!0;try{let e,r;this.mapUi.currentCenter&&({lat:e,lon:r}=this.mapUi.currentCenter);const n=t.toLowerCase(),i=POI_CATEGORIES.filter(e=>e.label.toLowerCase().includes(n)).map(e=>({source:"category",title:e.label,id:e.id,icon:"search"})),o=yield this.photon.search(t,e,r);this.results=[...i,...o]}catch(r){console.error("Search failed",r),this.results=[]}finally{this.isLoading=!1}}}}),{restartable:!0},"searchTask");handleFocus(){this.isFocused=!0,this.mapUi.setSearchBoxFocus(!0),this.query.length>=2&&0===this.results.length&&this.searchTask.perform()}static{decorateMethodV2(this.prototype,"handleFocus",[action])}handleBlur(){setTimeout(()=>{this.isFocused=!1,this.mapUi.setSearchBoxFocus(!1)},300)}static{decorateMethodV2(this.prototype,"handleBlur",[action])}handleSubmit(e){if(e.preventDefault(),!this.query)return;let t={q:this.query,selected:null,category:null};if(this.mapUi.currentCenter){const{lat:e,lon:r}=this.mapUi.currentCenter;t.lat=parseFloat(e).toFixed(4),t.lon=parseFloat(r).toFixed(4)}this.router.transitionTo("search",{queryParams:t}),this.isFocused=!1}static{decorateMethodV2(this.prototype,"handleSubmit",[action])}selectResult(e){if("category"===e.source){this.query=e.title,this.args.onQueryChange&&this.args.onQueryChange(e.title),this.results=[];let t=null,r=null;return this.mapUi.currentCenter&&(({lat:t,lon:r}=this.mapUi.currentCenter),t=t?.toString(),r=r?.toString()),void this.router.transitionTo("search",{queryParams:{q:e.title,category:e.id,selected:null,lat:t,lon:r}})}if(this.query=e.title,this.args.onQueryChange&&this.args.onQueryChange(e.title),this.results=[],e.osmId){const t=`osm:${e.osmType}:${e.osmId}`;this.router.transitionTo("place",t)}else this.router.transitionTo("search",{queryParams:{q:e.title,lat:e.lat,lon:e.lon,selected:null,category:null}})}static{decorateMethodV2(this.prototype,"selectResult",[action])}clear(){this.searchTask.cancelAll(),this.mapUi.stopLoading(),this.osm.cancelAll(),this.photon.cancelAll(),this.query="",this.results=[],this.args.onQueryChange&&this.args.onQueryChange(""),this.router.transitionTo("index")}static{decorateMethodV2(this.prototype,"clear",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"search-box"],[12],[1,"\\n "],[11,"form"],[24,0,"search-form"],[4,[32,0],["submit",[30,0,["handleSubmit"]]],null],[12],[1,"\\n "],[11,"button"],[24,0,"menu-btn-integrated"],[24,"aria-label","Menu"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["menu",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n\\n "],[11,"input"],[24,0,"search-input"],[24,"placeholder","Search places..."],[24,"aria-label","Search places"],[16,2,[30,0,["query"]]],[24,"autocomplete","off"],[24,4,"search"],[4,[32,0],["input",[30,0,["handleInput"]]],null],[4,[32,0],["focus",[30,0,["handleFocus"]]],null],[4,[32,0],["blur",[30,0,["handleBlur"]]],null],[12],[13],[1,"\\n\\n "],[10,"button"],[14,0,"search-submit-btn"],[14,"aria-label","Search"],[14,4,"submit"],[12],[1,"\\n"],[41,[28,[32,2],[[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"text"],null],[28,[32,3],[[30,0,["mapUi","loadingState","type"]],"category"],null]],null],[[[1," "],[8,[32,1],null,[["@name","@size"],["loading-ring",20]],null],[1,"\\n"]],[]],[[[1," "],[8,[32,1],null,[["@name","@size","@color"],["search",20,"#5f6368"]],null],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["query"]],[[[1," "],[11,"button"],[24,0,"search-clear-btn"],[24,"aria-label","Clear"],[24,4,"button"],[4,[32,0],["click",[30,0,["clear"]]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#5f6368"]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["showPopover"]],[[[1," "],[10,0],[14,0,"search-results-popover"],[12],[1,"\\n "],[10,"ul"],[14,0,"search-results-list"],[12],[1,"\\n"],[42,[28,[31,2],[[28,[31,2],[[30,0,["results"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,0,"search-result-item"],[24,4,"button"],[4,[32,0],["click",[28,[32,4],[[30,0,["selectResult"]],[30,2]],null]],null],[12],[1,"\\n "],[10,0],[14,0,"result-icon"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],[[52,[30,2,["icon"]],[30,2,["icon"]],"map-pin"],16,"#666"]],null],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"result-info"],[12],[1,"\\n "],[10,1],[14,0,"result-title"],[12],[1,[30,2,["title"]]],[13],[1,"\\n"],[41,[28,[32,3],[[30,2,["source"]],"osm"],null],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[28,[32,5],[[30,2,["type"]]],null]],[13],[1,"\\n"]],[]],[[[41,[30,2,["description"]],[[[1," "],[10,1],[14,0,"result-desc"],[12],[1,[30,2,["description"]]],[13],[1,"\\n"]],[]],null]],[]]],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null],[13]],["@onToggleMenu","result"],["if","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/search-box.gjs",scope:()=>[on,IconComponent,OrHelper,eq$1,fn,humanizeOsmTag],isStrictMode:!0}),this)}}class CategoryChipsComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");get categories(){return POI_CATEGORIES}searchCategory(e){this.args.onSelect&&this.args.onSelect(e);let t={category:e.id,q:null};if(this.mapUi.currentCenter){const{lat:e,lon:r}=this.mapUi.currentCenter;t.lat=parseFloat(e).toFixed(4),t.lon=parseFloat(r).toFixed(4)}this.router.transitionTo("search",{queryParams:t})}static{decorateMethodV2(this.prototype,"searchCategory",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"category-chips-scroll"],[12],[1,"\\n "],[10,0],[14,0,"category-chips-container"],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["categories"]]],null]],null],null,[[[1," "],[11,"button"],[24,0,"category-chip"],[16,"aria-label",[30,1,["label"]]],[16,"disabled",[28,[32,0],[[28,[32,1],[[30,0,["mapUi","loadingState","type"]],"category"],null],[28,[32,1],[[30,0,["mapUi","loadingState","value"]],[30,1,["id"]]],null]],null]],[24,4,"button"],[4,[32,2],["click",[28,[32,3],[[30,0,["searchCategory"]],[30,1]],null]],null],[12],[1,"\\n "],[8,[32,4],null,[["@name","@size"],[[30,1,["icon"]],16]],null],[1,"\\n "],[10,1],[12],[1,[30,1,["label"]]],[13],[1,"\\n "],[13],[1,"\\n"]],[1]],null],[1," "],[13],[1,"\\n"],[13]],["category"],["each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/category-chips.gjs",scope:()=>[AndHelper,eq$1,on,fn,IconComponent],isStrictMode:!0}),this)}}const CACHE_NAME="nostr-image-cache-v1",cachedImage=modifier((e,[t])=>{let r=null;return async function(){if(t)try{const n=await caches.open(CACHE_NAME),i=await n.match(t);if(i){const t=await i.blob();return r=URL.createObjectURL(t),void(e.src=r)}const o=await fetch(t,{mode:"cors",credentials:"omit"});if(o.ok){const i=o.clone();await n.put(t,i);const s=await o.blob();r=URL.createObjectURL(s),e.src=r}else e.src=t}catch(error){console.warn(`Failed to cache image ${t}, falling back to standard src`,error),e.src=t}else e.src=""}(),()=>{r&&(URL.revokeObjectURL(r),r=null)}});class AppHeaderComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{decorateFieldV2(this.prototype,"nostrAuth",[service])}#I=void initializeDeferredDecorator(this,"nostrAuth");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"isUserMenuOpen",[tracked],function(){return!1})}#ot=void initializeDeferredDecorator(this,"isUserMenuOpen");static{decorateFieldV2(this.prototype,"searchQuery",[tracked],function(){return""})}#st=void initializeDeferredDecorator(this,"searchQuery");get hasQuery(){return!!this.searchQuery}toggleUserMenu(){this.isUserMenuOpen=!this.isUserMenuOpen}static{decorateMethodV2(this.prototype,"toggleUserMenu",[action])}closeUserMenu(){this.isUserMenuOpen=!1}static{decorateMethodV2(this.prototype,"closeUserMenu",[action])}handleQueryChange(e){this.searchQuery=e}static{decorateMethodV2(this.prototype,"handleQueryChange",[action])}handleChipSelect(e){this.searchQuery=e.label}static{decorateMethodV2(this.prototype,"handleChipSelect",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"header"],[14,0,"app-header"],[12],[1,"\\n "],[10,0],[14,0,"header-left"],[12],[1,"\\n "],[8,[32,0],null,[["@query","@onToggleMenu","@onQueryChange"],[[30,0,["searchQuery"]],[30,1],[30,0,["handleQueryChange"]]]],null],[1,"\\n "],[13],[1,"\\n\\n"],[41,[30,0,["settings","showQuickSearchButtons"]],[[[1," "],[10,0],[15,0,[29,["header-center ",[52,[30,0,["hasQuery"]],"searching"]]]],[12],[1,"\\n "],[8,[32,1],null,[["@onSelect"],[[30,0,["handleChipSelect"]]]],null],[1,"\\n "],[13],[1,"\\n"]],[]],null],[1,"\\n "],[10,0],[14,0,"header-right"],[12],[1,"\\n "],[10,0],[14,0,"user-menu-container"],[12],[1,"\\n "],[11,"button"],[24,0,"user-btn btn-press"],[24,"aria-label","User Menu"],[24,4,"button"],[4,[32,2],["click",[30,0,["toggleUserMenu"]]],null],[12],[1,"\\n"],[41,[28,[32,3],[[30,0,["nostrAuth","isConnected"]],[30,0,["nostrData","profile","picture"]]],null],[[[1," "],[11,"img"],[24,0,"user-avatar"],[24,"alt","User Avatar"],[4,[32,4],[[30,0,["nostrData","profile","picture"]]],null],[12],[13],[1,"\\n"]],[]],[[[1," "],[10,0],[14,0,"user-avatar-placeholder"],[12],[1,"\\n "],[8,[32,5],null,[["@name","@size","@color"],["user",20,"white"]],null],[1,"\\n "],[13],[1,"\\n"]],[]]],[1," "],[13],[1,"\\n\\n"],[41,[30,0,["isUserMenuOpen"]],[[[1," "],[8,[32,6],null,[["@storage","@onClose"],[[30,0,["storage"]],[30,0,["closeUserMenu"]]]],null],[1,"\\n "],[11,0],[24,0,"menu-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["closeUserMenu"]]],null],[12],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onToggleMenu"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-header.gjs",scope:()=>[SearchBoxComponent,CategoryChipsComponent,on,AndHelper,cachedImage,IconComponent,UserMenuComponent],isStrictMode:!0}),this)}}const iconRounded='\n \x3c!-- Background --\x3e\n \n\n \x3c!-- Subtle map grid (kept well outside safe zone) --\x3e\n \n \n \n \n\n \n \n \n \n\n \x3c!-- Location pin (exact app shape, larger, centered, safe-zone compliant) --\x3e\n \x3c!-- Safe zone target: ~680px diameter --\x3e\n \n \n \n \n\n',templateOnly=templateOnlyComponent,AppMenuHome=setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[1,"\\n "],[10,1],[14,0,"app-logo-icon"],[12],[1,"\\n "],[1,[28,[32,0],[[32,1]],null]],[1,"\\n "],[13],[1,"\\n Marco\\n "],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,2],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"ul"],[14,0,"app-menu"],[12],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"settings"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["settings",20]],null],[1,"\\n "],[10,1],[12],[1,"Settings"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"li"],[12],[1,"\\n "],[11,"button"],[24,4,"button"],[4,[32,2],["click",[28,[32,4],[[30,2],"about"],null]],null],[12],[1,"\\n "],[8,[32,3],null,[["@name","@size"],["info",20]],null],[1,"\\n "],[10,1],[12],[1,"About"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onClose","@onNavigate"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/home.gjs",scope:()=>[htmlSafe,iconRounded,on,IconComponent,fn],isStrictMode:!0}),templateOnly());class AppMenuSettingsMapUi extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["map",20]],null],[1,"\\n "],[10,1],[12],[1,"Map & UI"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content form-layout"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","show-quick-search"],[12],[1,"Quick search buttons visible"],[13],[1,"\\n "],[11,"select"],[24,1,"show-quick-search"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"showQuickSearchButtons"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","showQuickSearchButtons"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","showQuickSearchButtons"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","map-kinetic"],[12],[1,"Map Inertia (Kinetic Panning)"],[13],[1,"\\n "],[11,"select"],[24,1,"map-kinetic"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"mapKinetic"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","mapKinetic"]],"selected"]],[12],[1,"\\n On\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","mapKinetic"]]],"selected"]],[12],[1,"\\n Off\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange"],["if","unless"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/map-ui.gjs",scope:()=>[IconComponent,on,fn],isStrictMode:!0}),this)}}class AppMenuSettingsApis extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["server",20]],null],[1,"\\n "],[10,1],[12],[1,"API Providers"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content form-layout"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","overpass-api"],[12],[1,"Overpass API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"overpass-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"overpassApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","overpassApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,2,["url"]]],[15,"selected",[52,[28,[32,3],[[30,2,["url"]],[30,0,["settings","overpassApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,2,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","photon-api"],[12],[1,"Photon API Provider"],[13],[1,"\\n "],[11,"select"],[24,1,"photon-api"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"photonApi"],null]],null],[12],[1,"\\n"],[42,[28,[31,1],[[28,[31,1],[[30,0,["settings","photonApis"]]],null]],null],null,[[[1," "],[10,"option"],[15,2,[30,3,["url"]]],[15,"selected",[52,[28,[32,3],[[30,3,["url"]],[30,0,["settings","photonApi"]]],null],"selected"]],[12],[1,"\\n "],[1,[30,3,["name"]]],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","api","api"],["each","-track-array","if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/apis.gjs",scope:()=>[IconComponent,on,fn,eq$1],isStrictMode:!0}),this)}}const stripProtocol=e=>e?e.replace(/^wss?:\/\//,""):"";class AppMenuSettingsNostr extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");static{decorateFieldV2(this.prototype,"nostrData",[service])}#P=void initializeDeferredDecorator(this,"nostrData");static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{decorateFieldV2(this.prototype,"newReadRelay",[tracked],function(){return""})}#at=void initializeDeferredDecorator(this,"newReadRelay");static{decorateFieldV2(this.prototype,"newWriteRelay",[tracked],function(){return""})}#lt=void initializeDeferredDecorator(this,"newWriteRelay");updateNewReadRelay(e){this.newReadRelay=e.target.value}static{decorateMethodV2(this.prototype,"updateNewReadRelay",[action])}updateNewWriteRelay(e){this.newWriteRelay=e.target.value}static{decorateMethodV2(this.prototype,"updateNewWriteRelay",[action])}addReadRelay(){const e=normalizeRelayUrl(this.newReadRelay);if(!e)return;const t=this.settings.nostrReadRelays||this.nostrData.defaultReadRelays,r=new Set([...t,e]);this.settings.update("nostrReadRelays",Array.from(r)),this.newReadRelay=""}static{decorateMethodV2(this.prototype,"addReadRelay",[action])}removeReadRelay(e){const t=(this.settings.nostrReadRelays||this.nostrData.defaultReadRelays).filter(t=>t!==e);this.settings.update("nostrReadRelays",t)}static{decorateMethodV2(this.prototype,"removeReadRelay",[action])}handleReadRelayKeydown(e){"Enter"===e.key&&this.addReadRelay()}static{decorateMethodV2(this.prototype,"handleReadRelayKeydown",[action])}handleWriteRelayKeydown(e){"Enter"===e.key&&this.addWriteRelay()}static{decorateMethodV2(this.prototype,"handleWriteRelayKeydown",[action])}resetReadRelays(){this.settings.update("nostrReadRelays",null)}static{decorateMethodV2(this.prototype,"resetReadRelays",[action])}addWriteRelay(){const e=normalizeRelayUrl(this.newWriteRelay);if(!e)return;const t=this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays,r=new Set([...t,e]);this.settings.update("nostrWriteRelays",Array.from(r)),this.newWriteRelay=""}static{decorateMethodV2(this.prototype,"addWriteRelay",[action])}removeWriteRelay(e){const t=(this.settings.nostrWriteRelays||this.nostrData.defaultWriteRelays).filter(t=>t!==e);this.settings.update("nostrWriteRelays",t)}static{decorateMethodV2(this.prototype,"removeWriteRelay",[action])}resetWriteRelays(){this.settings.update("nostrWriteRelays",null)}static{decorateMethodV2(this.prototype,"resetWriteRelays",[action])}async clearCache(){try{await this.nostrData.clearCache(),this.toast.show("Nostr cache cleared")}catch(e){this.toast.show(`Failed to clear Nostr cache: ${e.message}`)}}static{decorateMethodV2(this.prototype,"clearCache",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size"],["zap",20]],null],[1,"\\n "],[10,1],[12],[1,"Nostr"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content form-layout"],[12],[1,"\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","nostr-photo-fallback-uploads"],[12],[1,"Upload photos to fallback\\n servers"],[13],[1,"\\n "],[11,"select"],[24,1,"nostr-photo-fallback-uploads"],[24,0,"form-control"],[4,[32,1],["change",[28,[32,2],[[30,1],"nostrPhotoFallbackUploads"],null]],null],[12],[1,"\\n "],[10,"option"],[14,2,"true"],[15,"selected",[52,[30,0,["settings","nostrPhotoFallbackUploads"]],"selected"]],[12],[1,"\\n Yes\\n "],[13],[1,"\\n "],[10,"option"],[14,2,"false"],[15,"selected",[52,[51,[30,0,["settings","nostrPhotoFallbackUploads"]]],"selected"]],[12],[1,"\\n No\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-read-relay"],[12],[1,"Read Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeReadRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,2]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeReadRelay"]],[30,2]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[2]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-read-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newReadRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewReadRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleReadRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addReadRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrReadRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetReadRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[14,"for","new-write-relay"],[12],[1,"Write Relays"],[13],[1,"\\n "],[10,"ul"],[14,0,"relay-list"],[12],[1,"\\n"],[42,[28,[31,3],[[28,[31,3],[[30,0,["nostrData","activeWriteRelays"]]],null]],null],null,[[[1," "],[10,"li"],[12],[1,"\\n "],[10,1],[12],[1,[28,[32,3],[[30,3]],null]],[13],[1,"\\n "],[11,"button"],[24,0,"btn-remove-relay"],[24,"title","Remove relay"],[24,"aria-label","Remove"],[24,4,"button"],[4,[32,1],["click",[28,[32,2],[[30,0,["removeWriteRelay"]],[30,3]],null]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["x",14,"currentColor"]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[3]],null],[1," "],[13],[1,"\\n "],[10,0],[14,0,"add-relay-input"],[12],[1,"\\n "],[11,"input"],[24,1,"new-write-relay"],[24,0,"form-control"],[24,"placeholder","relay.example.com"],[16,2,[30,0,["newWriteRelay"]]],[24,4,"text"],[4,[32,1],["input",[30,0,["updateNewWriteRelay"]]],null],[4,[32,1],["keydown",[30,0,["handleWriteRelayKeydown"]]],null],[12],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-secondary"],[24,4,"button"],[4,[32,1],["click",[30,0,["addWriteRelay"]]],null],[12],[1,"Add"],[13],[1,"\\n "],[13],[1,"\\n"],[41,[30,0,["settings","nostrWriteRelays"]],[[[1," "],[11,"button"],[24,0,"btn-link reset-relays"],[24,4,"button"],[4,[32,1],["click",[30,0,["resetWriteRelays"]]],null],[12],[1,"\\n Reset to Defaults\\n "],[13],[1,"\\n"]],[]],null],[1," "],[13],[1,"\\n\\n "],[10,0],[14,0,"form-group"],[12],[1,"\\n "],[10,"label"],[12],[1,"Cached data"],[13],[1,"\\n "],[11,"button"],[24,0,"btn btn-outline btn-full"],[24,4,"button"],[4,[32,1],["click",[30,0,["clearCache"]]],null],[12],[1,"\\n "],[8,[32,0],null,[["@name","@size","@color"],["database",18,"var(--danger-color)"]],null],[1,"\\n Clear profiles, photos, and reviews\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onChange","relay","relay"],["if","unless","each","-track-array"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings/nostr.gjs",scope:()=>[IconComponent,on,fn,stripProtocol],isStrictMode:!0}),this)}}class AppMenuSettings extends GlimmerComponent{static{decorateFieldV2(this.prototype,"settings",[service])}#k=void initializeDeferredDecorator(this,"settings");updateSetting(e,t){let r=t.target.value;"true"===r&&(r=!0),"false"===r&&(r=!1),this.settings.update(e,r)}static{decorateMethodV2(this.prototype,"updateSetting",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"Settings"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"settings-section"],[12],[1,"\\n "],[8,[32,2],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,3],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[8,[32,4],null,[["@onChange"],[[30,0,["updateSetting"]]]],null],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/settings.gjs",scope:()=>[on,IconComponent,AppMenuSettingsMapUi,AppMenuSettingsApis,AppMenuSettingsNostr],isStrictMode:!0}),this)}}const AppMenuAbout=setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[11,"button"],[24,0,"back-btn"],[24,4,"button"],[4,[32,0],["click",[30,1]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["arrow-left",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n "],[10,"h2"],[12],[1,"About"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,0],["click",[30,2]],null],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["x",20,"#333"]],null],[1,"\\n "],[13],[1,"\\n"],[13],[1,"\\n\\n"],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,"section"],[14,0,"about-section"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Marco"],[13],[1,"\\n (as in\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/Marco_Polo"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"Marco Polo"],[13],[1,") is an unhosted maps application that respects your\\n privacy and choices.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n Connect your own\\n "],[10,3],[14,6,"https://remotestorage.io/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"remote storage"],[13],[1,"\\n to sync place bookmarks across apps and devices.\\n "],[13],[1,"\\n\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size"],["gift",20]],null],[1,"\\n "],[10,1],[12],[1,"Open Source"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,"table"],[12],[1,"\\n "],[10,"thead"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"th"],[12],[1,"Source"],[13],[1,"\\n "],[10,"th"],[12],[1,"License"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tbody"],[12],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://gitea.kosmos.org/raucao/marco"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Marco App\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/GNU_Affero_General_Public_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","GNU Affero General Public License"],[12],[1,"AGPL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://openstreetmap.org/copyright"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Map Data\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://opendatacommons.org/licenses/odbl/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","Open Data Commons Open Database License"],[12],[1,"ODbL"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/feathericons/feather"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Feather Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://en.wikipedia.org/wiki/MIT_License"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n "],[10,"abbr"],[14,"title","MIT License"],[12],[1,"MIT"],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"tr"],[12],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://pinhead.ink/"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Pinhead Icons\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"td"],[12],[1,"\\n "],[10,3],[14,6,"https://github.com/waysidemapping/pinhead?tab=readme-ov-file#where-the-icons-are-from"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"\\n Various\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[10,"details"],[12],[1,"\\n "],[10,"summary"],[12],[1,"\\n "],[8,[32,1],null,[["@name","@size","@color"],["heart",20,"#e5533d"]],null],[1,"\\n "],[10,1],[12],[1,"Contribute"],[13],[1,"\\n "],[13],[1,"\\n "],[10,0],[14,0,"details-content"],[12],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most impactful:"],[13],[1,"\\n Add and improve data for points of interest in\\n "],[10,3],[14,6,"https://www.openstreetmap.org"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"OpenStreetMap"],[13],[1,".\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most appreciated:"],[13],[1,"\\n Use this app as much as you can and\\n "],[10,3],[14,6,"https://community.remotestorage.io/t/marco-an-unhosted-maps-app/941"],[14,"target","_blank"],[14,"rel","noopener"],[12],[1,"submit feedback"],[13],[1,"\\n about your experience, problems, feature wishes, etc.\\n "],[13],[1,"\\n "],[10,2],[12],[1,"\\n "],[10,"strong"],[12],[1,"Most supportive:"],[13],[1,"\\n Tell others about this app, on social media, in blog posts,\\n educational videos, etc.\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"],[13]],["@onBack","@onClose"],[]]',moduleName:"/home/basti/src/marco/app/components/app-menu/about.gjs",scope:()=>[on,IconComponent],isStrictMode:!0}),templateOnly());class AppMenu extends GlimmerComponent{static{decorateFieldV2(this.prototype,"currentView",[tracked],function(){return"menu"})}#ct=void initializeDeferredDecorator(this,"currentView");setView(e){this.currentView=e}static{decorateMethodV2(this.prototype,"setView",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[10,0],[14,0,"sidebar app-menu-pane"],[12],[1,"\\n"],[41,[28,[32,0],[[30,0,["currentView"]],"menu"],null],[[[1," "],[8,[32,1],null,[["@onNavigate","@onClose"],[[30,0,["setView"]],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"settings"],null],[[[1," "],[8,[32,2],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n\\n"]],[]],[[[41,[28,[32,0],[[30,0,["currentView"]],"about"],null],[[[1," "],[8,[32,4],null,[["@onBack","@onClose"],[[28,[32,3],[[30,0,["setView"]],"menu"],null],[30,1]]],null],[1,"\\n "]],[]],null]],[]]]],[]]],[13]],["@onClose"],["if"]]',moduleName:"/home/basti/src/marco/app/components/app-menu/index.gjs",scope:()=>[eq$1,AppMenuHome,AppMenuSettings,fn,AppMenuAbout],isStrictMode:!0}),this)}}class ToastComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"toast",[service])}#he=void initializeDeferredDecorator(this,"toast");static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["toast","isVisible"]],[[[1," "],[10,0],[14,0,"toast-notification"],[12],[1,"\\n "],[1,[30,0,["toast","message"]]],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/components/toast.gjs",isStrictMode:!0}),this)}}class ApplicationComponent extends GlimmerComponent{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"isAppMenuOpen",[tracked],function(){return!1})}#ut=void initializeDeferredDecorator(this,"isAppMenuOpen");get isSidebarOpen(){return this.mapUi.isSidebarVisible&&("place"===this.router.currentRouteName||"place.new"===this.router.currentRouteName||"search"===this.router.currentRouteName)}constructor(){super(...arguments),console.debug("Application component constructed"),this.storage}toggleAppMenu(){this.isAppMenuOpen=!this.isAppMenuOpen}static{decorateMethodV2(this.prototype,"toggleAppMenu",[action])}closeAppMenu(){this.isAppMenuOpen=!1}static{decorateMethodV2(this.prototype,"closeAppMenu",[action])}handleOutsideClick(){this.isAppMenuOpen?this.closeAppMenu():"search"!==this.router.currentRouteName&&"place"!==this.router.currentRouteName||(this.mapUi.clearSelection(),this.mapUi.hideSidebar())}static{decorateMethodV2(this.prototype,"handleOutsideClick",[action])}refreshBookmarks(){this.storage.notifyChange()}static{decorateMethodV2(this.prototype,"refreshBookmarks",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[1,[28,[32,0],["Marco"],null]],[1,"\\n\\n"],[8,[32,1],null,[["@onToggleMenu"],[[30,0,["toggleAppMenu"]]]],null],[1,"\\n\\n"],[10,0],[14,1,"rs-widget-container"],[15,0,[52,[30,0,["storage","isWidgetOpen"]],"visible"]],[12],[13],[1,"\\n\\n"],[41,[30,0,["storage","isWidgetOpen"]],[[[1," "],[11,0],[24,0,"rs-backdrop"],[24,"role","button"],[4,[32,2],["click",[30,0,["storage","closeWidget"]]],null],[12],[13],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,3],null,[["@isSidebarOpen","@onOutsideClick"],[[28,[32,4],[[30,0,["isSidebarOpen"]],[30,0,["isAppMenuOpen"]]],null],[30,0,["handleOutsideClick"]]]],null],[1,"\\n\\n"],[41,[30,0,["isAppMenuOpen"]],[[[1," "],[8,[32,5],null,[["@onClose"],[[30,0,["closeAppMenu"]]]],null],[1,"\\n"]],[]],null],[1,"\\n"],[8,[32,6],null,null,null],[1,"\\n\\n"],[46,[28,[31,2],null,null],null,null,null]],[],["if","component","-outlet"]]',moduleName:"/home/basti/src/marco/app/templates/application.gjs",scope:()=>[PageTitle,AppHeaderComponent,on,MapComponent,OrHelper,AppMenu,ToastComponent],isStrictMode:!0}),this)}}const amdModule32=Object.freeze(Object.defineProperty({__proto__:null,default:ApplicationComponent},Symbol.toStringTag,{value:"Module"}));class ApplicationRoute extends Route{static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage")}const amdModule33=Object.freeze(Object.defineProperty({__proto__:null,default:ApplicationRoute},Symbol.toStringTag,{value:"Module"}));class IndexRoute extends Route{static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");activate(){this.mapUi.clearSearchResults()}}const amdModule34=Object.freeze(Object.defineProperty({__proto__:null,default:IndexRoute},Symbol.toStringTag,{value:"Module"}));class OauthOsmCallbackRoute extends Route{static{decorateFieldV2(this.prototype,"osmAuth",[service])}#Qe=void initializeDeferredDecorator(this,"osmAuth");static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");async model(){try{await this.osmAuth.handleCallback()}catch(e){console.error("Failed to handle OSM OAuth callback",e)}finally{this.router.transitionTo("index")}}}const amdModule35=Object.freeze(Object.defineProperty({__proto__:null,default:OauthOsmCallbackRoute},Symbol.toStringTag,{value:"Module"}));class PlaceTemplate extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");static{decorateFieldV2(this.prototype,"localPlace",[tracked],function(){return null})}#ht=void initializeDeferredDecorator(this,"localPlace");constructor(){super(...arguments),this.localPlace=this.args.model}get place(){const e=this.args.model,t=e.osmId||e.id;return this.storage.findPlaceById(t)||(!this.localPlace||this.localPlace.osmId!==t&&this.localPlace.id!==t?e.createdAt?{...e,id:void 0,createdAt:void 0,geohash:void 0}:e:this.localPlace)}handleUpdate(e){console.debug("Updating local place state:",e),this.localPlace=e,this.storage.notifyChange()}static{decorateMethodV2(this.prototype,"handleUpdate",[action])}refreshMap(){this.storage.notifyChange()}static{decorateMethodV2(this.prototype,"refreshMap",[action])}navigateBack(e){null===e?this.mapUi.returnToSearch&&this.mapUi.currentSearch?(this.mapUi.showSidebar(),this.router.transitionTo("search",{queryParams:this.mapUi.currentSearch})):this.router.transitionTo("index"):(this.mapUi.showSidebar(),this.router.transitionTo("place",e))}static{decorateMethodV2(this.prototype,"navigateBack",[action])}close(){this.mapUi.clearSelection(),this.mapUi.hideSidebar()}static{decorateMethodV2(this.prototype,"close",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["mapUi","isSidebarVisible"]],[[[1," "],[8,[32,0],null,[["@selectedPlace","@onClose","@onSelect","@onBookmarkChange","@onUpdate"],[[30,0,["place"]],[30,0,["close"]],[30,0,["navigateBack"]],[30,0,["refreshMap"]],[30,0,["handleUpdate"]]]],null],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/templates/place.gjs",scope:()=>[PlacesSidebar],isStrictMode:!0}),this)}}const amdModule36=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceTemplate},Symbol.toStringTag,{value:"Module"}));class PlaceRoute extends Route{static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"osm",[service])}#ue=void initializeDeferredDecorator(this,"osm");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");async model(e){const t=e.place_id;let r,n,i=!1;(t.startsWith("osm:node:")||t.startsWith("osm:way:")||t.startsWith("osm:relation:"))&&(i=!0,[,r,n]=t.split(":"),console.debug(`Fetching explicit OSM ${r}:`,n));let o=null;i&&(o=this.loadOsmPlace(n,r)),await this.waitForSync();let s=i?n:t,a=this.storage.findPlaceById(s);return a&&i&&a.osmType!==r&&(a=null),a?(console.debug("Found in bookmarks:",a.title),a):i?(console.debug(`Not in bookmarks, using explicitly fetched OSM ${r}:`,n),await o):(console.warn("Not in bookmarks:",t),null)}async waitForSync(){if(this.storage.initialSyncDone)return;console.debug("Waiting for initial storage sync...");const e=Date.now();for(;!this.storage.initialSyncDone;){if(Date.now()-e>5e3){console.warn("Timed out waiting for initial sync");break}await new Promise(e=>setTimeout(e,100))}}async afterModel(e){if(e&&e.osmId&&e.osmType&&"node"!==e.osmType&&!e.geojson){console.debug("Model missing geometry, fetching full OSM details...");const t=await this.loadOsmPlace(e.osmId,e.osmType);t&&(Object.assign(e,t),console.debug("Enriched model with full OSM details",e))}if(e){const t={preventZoom:this.mapUi.preventNextZoom};this.mapUi.selectPlace(e,t),this.mapUi.showSidebar(),this.mapUi.preventNextZoom=!1}this.mapUi.stopSearch()}deactivate(){this.mapUi.clearSelection(),this.mapUi.returnToSearch=!1}async loadOsmPlace(e,t=null){try{const r=await this.osm.fetchOsmObject(e,t);if(r)return console.debug("Found OSM POI:",r),r}catch(r){console.error("Failed to fetch POI",r)}return null}setupController(e,t){super.setupController(e,t),this.checkUpdates(t)}async checkUpdates(e){if(e&&e.id&&e.osmId&&e.osmType){const t=await this.storage.refreshPlace(e);t&&this.mapUi.selectPlace(t,{preventZoom:!0})}}serialize(e){return e.osmId&&e.osmType?{place_id:`osm:${e.osmType}:${e.osmId}`}:e.id?{place_id:e.id}:{place_id:e.osmId}}}const amdModule37=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceRoute},Symbol.toStringTag,{value:"Module"}));class PlaceNewTemplate extends GlimmerComponent{static{decorateFieldV2(this.prototype,"router",[service])}#Re=void initializeDeferredDecorator(this,"router");static{decorateFieldV2(this.prototype,"storage",[service])}#xe=void initializeDeferredDecorator(this,"storage");static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");get initialPlace(){return{title:"",description:""}}close(){this.router.transitionTo("index")}static{decorateMethodV2(this.prototype,"close",[action])}async savePlace(e){try{const t=this.mapUi.creationCoordinates||{lat:this.args.model.lat,lon:this.args.model.lon},r=parseFloat(t.lat.toFixed(6)),n=parseFloat(t.lon.toFixed(6)),i={title:e.title||"Untitled Place",description:e.description,lat:r,lon:n,tags:[],osmTags:{}},o=await this.storage.storePlace(i);console.debug("Created private place:",o.title),this.router.replaceWith("place",o)}catch(t){console.error("Failed to create place:",t),alert("Failed to create place: "+t.message)}}static{decorateMethodV2(this.prototype,"savePlace",[action])}static{setComponentTemplate(templateFactory({id:null,block:'[[[41,[30,0,["mapUi","isSidebarVisible"]],[[[1," "],[10,0],[14,0,"sidebar"],[12],[1,"\\n "],[10,0],[14,0,"sidebar-header"],[12],[1,"\\n "],[10,"h2"],[12],[8,[32,0],null,[["@name","@size","@color"],["plus-circle",20,"#ea4335"]],null],[1,"\\n New Place"],[13],[1,"\\n "],[11,"button"],[24,0,"close-btn"],[24,4,"button"],[4,[32,1],["click",[30,0,["close"]]],null],[12],[8,[32,0],null,[["@name","@size","@color"],["x",20,"#333"]],null],[13],[1,"\\n "],[13],[1,"\\n\\n "],[10,0],[14,0,"sidebar-content"],[12],[1,"\\n "],[10,2],[14,0,"helper-text"],[12],[1,"\\n Drag the map to position the crosshair.\\n "],[13],[1,"\\n\\n "],[8,[32,2],null,[["@place","@onSave","@onCancel"],[[30,0,["initialPlace"]],[30,0,["savePlace"]],[30,0,["close"]]]],null],[1,"\\n "],[13],[1,"\\n "],[13],[1,"\\n"]],[]],null]],[],["if"]]',moduleName:"/home/basti/src/marco/app/templates/place/new.gjs",scope:()=>[IconComponent,on,PlaceEditForm],isStrictMode:!0}),this)}}const amdModule38=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceNewTemplate},Symbol.toStringTag,{value:"Module"}));class PlaceNewRoute extends Route{static{decorateFieldV2(this.prototype,"mapUi",[service])}#Xe=void initializeDeferredDecorator(this,"mapUi");queryParams={lat:{refreshModel:!0},lon:{refreshModel:!0}};model(e){return{lat:parseFloat(e.lat),lon:parseFloat(e.lon)}}setupController(e,t){super.setupController(e,t),t.lat&&t.lon&&this.mapUi.updateCreationCoordinates(t.lat,t.lon),this.mapUi.startCreating(),this.mapUi.showSidebar()}deactivate(){this.mapUi.stopCreating()}}const amdModule39=Object.freeze(Object.defineProperty({__proto__:null,default:PlaceNewRoute},Symbol.toStringTag,{value:"Module"}));let exportFastbootModules={};const compatModules=Object.assign({},defineModule0,{"marco/app":amdModule0,"marco/config/environment":amdModule1,"marco/deprecation-workflow":amdModule2,"marco/router":amdModule3,"marco/services/blossom":amdModule4,"marco/services/image-processor":amdModule5,"marco/services/map-ui":amdModule6,"marco/services/nostr-auth":amdModule7,"marco/services/nostr-data":amdModule8,"marco/services/nostr-relay":amdModule9,"marco/services/osm-auth":amdModule10,"marco/services/osm":amdModule11,"marco/services/photon":amdModule12,"marco/services/settings":amdModule13,"marco/services/storage":amdModule14,"marco/services/toast":amdModule15,"marco/utils/device":amdModule16,"marco/utils/format-text":amdModule17,"marco/utils/geo":amdModule18,"marco/utils/geohash-coverage":amdModule19,"marco/utils/icons":amdModule20,"marco/utils/nostr":amdModule21,"marco/utils/osm-icons":amdModule22,"marco/utils/osm":amdModule23,"marco/utils/place-mapping":amdModule24,"marco/utils/poi-categories":amdModule25,"marco/utils/social-links":amdModule26,"marco/workers/image-processor":amdModule27,"marco/services/page-title":amdModule28,"marco/templates/search":amdModule29,"marco/controllers/search":amdModule30,"marco/routes/search":amdModule31,"marco/templates/application":amdModule32,"marco/routes/application":amdModule33,"marco/routes/index":amdModule34,"marco/routes/oauth/osm-callback":amdModule35,"marco/templates/place":amdModule36,"marco/routes/place":amdModule37,"marco/templates/place/new":amdModule38,"marco/routes/place/new":amdModule39},exportFastbootModules);class Cache{constructor(e,t,r){this.limit=e,this.func=t,this.store=r,this.size=0,this.misses=0,this.hits=0,this.store=r||new Map}get(e){let t=this.store.get(e);return this.store.has(e)?(this.hits++,this.store.get(e)):(this.misses++,t=this.set(e,this.func(e)),t)}set(e,t){return this.limit>this.size&&(this.size++,this.store.set(e,t)),t}purge(){this.store.clear(),this.size=0,this.hits=0,this.misses=0}}const STRING_DASHERIZE_REGEXP=/[ _]/g,STRING_DASHERIZE_CACHE=new Cache(1e3,e=>decamelize(e).replace(STRING_DASHERIZE_REGEXP,"-")),STRING_CLASSIFY_REGEXP_1=/^(\-|_)+(.)?/,STRING_CLASSIFY_REGEXP_2=/(.)(\-|\_|\.|\s)+(.)?/g,STRING_CLASSIFY_REGEXP_3=/(^|\/|\.)([a-z])/g,CLASSIFY_CACHE=new Cache(1e3,e=>{const t=(e,t,r)=>r?`_${r.toUpperCase()}`:"",r=(e,t,r,n)=>t+(n?n.toUpperCase():""),n=e.split("/");for(let i=0;ie.toUpperCase())}),STRING_UNDERSCORE_REGEXP_1=/([a-z\d])([A-Z]+)/g,STRING_UNDERSCORE_REGEXP_2=/\-|\s+/g,UNDERSCORE_CACHE=new Cache(1e3,e=>e.replace(STRING_UNDERSCORE_REGEXP_1,"$1_$2").replace(STRING_UNDERSCORE_REGEXP_2,"_").toLowerCase()),STRING_DECAMELIZE_REGEXP=/([a-z\d])([A-Z])/g,DECAMELIZE_CACHE=new Cache(1e3,e=>e.replace(STRING_DECAMELIZE_REGEXP,"$1_$2").toLowerCase());function decamelize(e){return DECAMELIZE_CACHE.get(e)}function dasherize(e){return STRING_DASHERIZE_CACHE.get(e)}function classify(e){return CLASSIFY_CACHE.get(e)}function underscore(e){return UNDERSCORE_CACHE.get(e)}function classFactory(e){return{create:t=>"function"==typeof e.extend?e.extend(t):e}}class ModuleRegistry{constructor(e){this._entries=e||globalThis.requirejs.entries}moduleNames(){return Object.keys(this._entries)}has(e){return e in this._entries}get(...e){return globalThis.require(...e)}}class Resolver{static moduleBasedResolver=!0;moduleBasedResolver=!0;_deprecatedPodModulePrefix=!1;_normalizeCache=Object.create(null);static create(e){return new this(e)}moduleNameLookupPatterns=[this.podBasedModuleName,this.podBasedComponentsInSubdir,this.mainModuleName,this.defaultModuleName,this.nestedColocationComponentModuleName];static withModules(e){return class extends(this){static explicitModules=e}}constructor(e){if(Object.assign(this,e),!this._moduleRegistry){let e=this.constructor.explicitModules;e?this._moduleRegistry={moduleNames:()=>Object.keys(e),has:t=>Boolean(e[t]),get:t=>e[t],addModules(t){e=Object.assign({},e,t)}}:(void 0===globalThis.requirejs.entries&&(globalThis.requirejs.entries=globalThis.requirejs._eak_seen),this._moduleRegistry=new ModuleRegistry)}this.pluralizedTypes=this.pluralizedTypes||Object.create(null),this.pluralizedTypes.config||(this.pluralizedTypes.config="config")}makeToString(e,t){return this.namespace.modulePrefix+"@"+t+":"}shouldWrapInClassFactory(){return!1}parseName(e){if(!0===e.parsedName)return e;let t,r,n,i=e.split("@");if(3===i.length){if(0===i[0].length){t=`@${i[1]}`;let e=i[2].split(":");r=e[0],n=e[1]}else t=`@${i[1]}`,r=i[0].slice(0,-1),n=i[2];"template:components"===r&&(n=`components/${n}`,r="template")}else if(2===i.length){let e=i[0].split(":");if(2===e.length)0===e[1].length?(r=e[0],n=`@${i[1]}`):(t=e[1],r=e[0],n=i[1]);else{let e=i[1].split(":");t=i[0],r=e[0],n=e[1]}"template"===r&&0===t.lastIndexOf("components/",0)&&(n=`components/${n}`,t=t.slice(11))}else i=e.split(":"),r=i[0],n=i[1];let o=n,s=this.namespace;return{parsedName:!0,fullName:e,prefix:t||this.prefix({type:r}),type:r,fullNameWithoutType:o,name:n,root:s,resolveMethodName:"resolve"+classify(r)}}resolveOther(e){assert("`modulePrefix` must be defined",this.namespace.modulePrefix);let t=this.findModuleName(e);if(t){let r=this._extractDefaultExport(t,e);if(void 0===r)throw new Error(` Expected to find: '${e.fullName}' within '${t}' but got 'undefined'. Did you forget to 'export default' within '${t}'?`);return this.shouldWrapInClassFactory(r,e)&&(r=classFactory(r)),r}}normalize(e){return this._normalizeCache[e]||(this._normalizeCache[e]=this._normalize(e))}resolve(e){if("resolver:current"===e)return{create:()=>this};let t,r=this.parseName(e),n=r.resolveMethodName;return"function"==typeof this[n]&&(t=this[n](r)),null==t&&(t=this.resolveOther(r)),t}addModules(e){if(!this._moduleRegistry.addModules)throw new Error("addModules is only supported when your Resolver has been configured to use static modules via Resolver.withModules()");this._moduleRegistry.addModules(e)}_normalize(e){let t=e.split(":");if(t.length>1){let e=t[0];return"component"===e||"helper"===e||"modifier"===e||"template"===e&&0===t[1].indexOf("components/")?e+":"+t[1].replace(/_/g,"-"):e+":"+dasherize(t[1].replace(/\./g,"/"))}return e}pluralize(e){return this.pluralizedTypes[e]||(this.pluralizedTypes[e]=e+"s")}podBasedLookupWithPrefix(e,t){let r=t.fullNameWithoutType;return"template"===t.type&&(r=r.replace(/^components\//,"")),e+"/"+r+"/"+t.type}podBasedModuleName(e){let t=this.namespace.podModulePrefix||this.namespace.modulePrefix;return this.podBasedLookupWithPrefix(t,e)}podBasedComponentsInSubdir(e){let t=this.namespace.podModulePrefix||this.namespace.modulePrefix;if(t+="/components","component"===e.type||/^components/.test(e.fullNameWithoutType))return this.podBasedLookupWithPrefix(t,e)}resolveEngine(e){let t=e.fullNameWithoutType+"/engine";if(this._moduleRegistry.has(t))return this._extractDefaultExport(t)}resolveRouteMap(e){let t=e.fullNameWithoutType,r=t+"/routes";if(this._moduleRegistry.has(r)){let e=this._extractDefaultExport(r);return assert(`The route map for ${t} should be wrapped by 'buildRoutes' before exporting.`,e.isRouteMap),e}}resolveTemplate(e){return this.resolveOther(e)}mainModuleName(e){if("main"===e.fullNameWithoutType)return e.prefix+"/"+e.type}defaultModuleName(e){return e.prefix+"/"+this.pluralize(e.type)+"/"+e.fullNameWithoutType}nestedColocationComponentModuleName(e){if("component"===e.type)return e.prefix+"/"+this.pluralize(e.type)+"/"+e.fullNameWithoutType+"/index"}prefix(e){let t=this.namespace.modulePrefix;return this.namespace[e.type+"Prefix"]&&(t=this.namespace[e.type+"Prefix"]),t}findModuleName(e){let t,r=this.moduleNameLookupPatterns;for(let n=0,i=r.length;nn.length+i.length)return e+":"+t.slice(o+n.length,s);let a=r+"/"+this.pluralize(e)+"/";return 0===t.indexOf(a)&&t.length>a.length?e+":"+t.slice(a.length):void 0}_extractDefaultExport(e){let t=this._moduleRegistry.get(e,null,null,!0);return t&&t.default&&(t=t.default),t}}function assert(e,t){if(!t)throw new Error(e)}function setupGlobal(e,t){globalThis.emberInspectorApps||(globalThis.emberInspectorApps=[]),globalThis.emberInspectorApps.push({app:e,name:`app-${globalThis.emberInspectorApps.length}`,loadCompatInspector:t}),globalThis.dispatchEvent&&globalThis.dispatchEvent(new Event("Ember"))}function setupInspector(e){setupGlobal(e,()=>__vitePreload(()=>import("./modules-4-12-Br95YYit.js"),[]))}class App extends Application$1{modulePrefix=ENV.modulePrefix;podModulePrefix=ENV.podModulePrefix;Resolver=Resolver.withModules(compatModules);inspector=setupInspector(this)}App.create(ENV.APP);export{nativeDescDecorator as $,ASYNC_OBSERVERS as A,endPropertyChanges as B,ComputedDescriptor as C,DEBUG_INJECTION_FUNCTIONS as D,expandProperties as E,findNamespace as F,findNamespaces as G,flushAsyncObservers as H,getCachedValueFor as I,getProperties as J,hasListeners as K,Libraries as L,hasUnknownProperty as M,NAMESPACES as N,inject$2 as O,PROPERTY_DID_CHANGE as P,isClassicDecorator as Q,isComputed as R,SYNC_OBSERVERS as S,TrackedDescriptor as T,isConst as U,isElementDescriptor as V,isSearchDisabled as W,LIBRARIES as X,makeComputedDecorator as Y,markObjectAsDirty as Z,_getPath as _,get$7 as a,ActionHandler as a$,notifyPropertyChange as a0,objectAt as a1,on$3 as a2,processAllNamespaces as a3,processNamespace as a4,removeArrayObserver as a5,removeListener as a6,removeNamespace as a7,removeObserver as a8,replace as a9,RSVP as aA,defer$1 as aB,denodeify as aC,filter$2 as aD,hash$4 as aE,hashSettled as aF,map$3 as aG,off as aH,on$2 as aI,race as aJ,reject as aK,resolve$3 as aL,rethrow as aM,guidFor as aN,MutableArray as aO,ENV$1 as aP,context$1 as aQ,getENV as aR,getLookup as aS,global$1 as aT,setLookup as aU,Meta as aV,UNDEFINED as aW,counters as aX,meta$1 as aY,peekMeta as aZ,setMeta as a_,replaceInNativeArray as aa,revalidateObservers as ab,sendEvent as ac,setClassicDecorator as ad,setSearchDisabled as ae,setProperties as af,setUnprocessedMixins as ag,tagForObject as ah,tagForProperty as ai,tracked as aj,trySet as ak,Input as al,Textarea as am,componentCapabilities as an,Component as ao,getComponentTemplate as ap,setComponentManager as aq,setComponentTemplate as ar,EventTarget as as,Promise$1 as at,all$2 as au,allSettled as av,asap as aw,async$1 as ax,cast as ay,configure as az,ComputedProperty as b,index$1 as b$,Comparable as b0,ContainerProxyMixin as b1,MutableEnumerable as b2,RSVP$1 as b3,RegistryProxyMixin as b4,TargetActionSupport as b5,ProxyMixin as b6,contentFor as b7,onerrorDefault as b8,Cache$1 as b9,ActionSupport as bA,ComponentLookup as bB,CoreView as bC,EventDispatcher as bD,MUTABLE_CELL as bE,states as bF,addChildView as bG,clearElementView as bH,clearViewElement as bI,constructStyleDeprecationMessage as bJ,getChildViews as bK,getElementView as bL,getRootViews as bM,getViewBoundingClientRect as bN,getViewBounds as bO,getViewClientRects as bP,getViewElement as bQ,getViewId as bR,isSimpleClick as bS,setElementView as bT,setViewElement as bU,index$2 as bV,namespace as bW,index$6 as bX,proxy$1 as bY,index$5 as bZ,index$e as b_,GUID_KEY as ba,ROOT as bb,canInvoke as bc,checkHasSuper as bd,makeDictionary as be,enumerableSymbol as bf,generateGuid as bg,getDebugName$1$1 as bh,getName as bi,intern$1 as bj,isInternalSymbol as bk,isObject as bl,isProxy as bm,lookupDescriptor as bn,observerListenerMetaFor as bo,setListeners as bp,setName as bq,setObservers as br,setProxy as bs,setWithMandatorySetter as bt,setupMandatorySetter as bu,symbol as bv,teardownMandatorySetter as bw,toString$3 as bx,uuid$1 as by,wrap$2 as bz,createCache as c,index$8 as c0,mutable as c1,index$7 as c2,core as c3,evented as c4,observable$1 as c5,promiseProxyMixin as c6,proxy as c7,index$9 as c8,index$4 as c9,_importSync20 as ca,version$2 as cb,index as cc,index$a as cd,index$b as ce,index$3 as cf,index$c as cg,index$d as ch,innerFrom as ci,Observable$1 as cj,createOperatorSubscriber as ck,nanoid$1 as cl,logger$1 as cm,map$1 as cn,share as co,firstValueFrom as cp,NAMESPACES_BY_ID as d,PROXY_CONTENT as e,_getProp as f,getValue$1 as g,_setProp as h,activateObserver as i,addArrayObserver as j,addListener as k,addNamespace as l,addObserver as m,alias as n,arrayContentDidChange as o,arrayContentWillChange as p,autoComputed as q,beginPropertyChanges as r,set$1 as s,changeProperties as t,computed as u,defineDecorator as v,defineProperty as w,defineValue as x,descriptorForDecorator as y,descriptorForProperty as z}; diff --git a/release/assets/modules-4-12-CSVC-YcG.js b/release/assets/modules-4-12-Br95YYit.js similarity index 98% rename from release/assets/modules-4-12-CSVC-YcG.js rename to release/assets/modules-4-12-Br95YYit.js index 1debe66..0c2d6d7 100644 --- a/release/assets/modules-4-12-CSVC-YcG.js +++ b/release/assets/modules-4-12-Br95YYit.js @@ -1 +1 @@ -import{c as e,g as a,a as s,s as t,A as r,C as o,b as n,D as i,L as l,N as b,d as c,P as p,e as d,S as m,T as u,_ as g,f as y,h as _,i as O,j as S,k as f,l as C,m as P,n as h,o as v,p as j,q as E,r as M,t as D,u as N,v as V,w as A,x as w,y as T,z as I,B as x,E as R,F as k,G as F,H as L,I as z,J as G,K as U,M as B,O as W,Q as Y,R as H,U as J,V as K,W as X,X as q,Y as Q,Z,$,a0 as ee,a1 as ae,a2 as se,a3 as te,a4 as re,a5 as oe,a6 as ne,a7 as ie,a8 as le,a9 as be,aa as pe,ab as de,ac as me,ad as ue,ae as ge,af as ye,ag as _e,ah as Oe,ai as Se,aj as fe,ak as Ce,al as Pe,am as he,an as ve,ao as je,ap as Ee,aq as Me,ar as De,as as Ne,at as Ve,au as Ae,av as we,aw as Te,ax as Ie,ay as xe,az as Re,aA as ke,aB as Fe,aC as Le,aD as ze,aE as Ge,aF as Ue,aG as Be,aH as We,aI as Ye,aJ as He,aK as Je,aL as Ke,aM as Xe,aN as qe,aO as Qe,aP as Ze,aQ as $e,aR as ea,aS as aa,aT as sa,aU as ta,aV as ra,aW as oa,aX as na,aY as ia,aZ as la,a_ as ba,a$ as pa,b0 as da,b1 as ma,b2 as ua,b3 as ga,b4 as ya,b5 as _a,b6 as Oa,b7 as Sa,b8 as fa,b9 as Ca,ba as Pa,bb as ha,bc as va,bd as ja,be as Ea,bf as Ma,bg as Da,bh as Na,bi as Va,bj as Aa,bk as wa,bl as Ta,bm as Ia,bn as xa,bo as Ra,bp as ka,bq as Fa,br as La,bs as za,bt as Ga,bu as Ua,bv as Ba,bw as Wa,bx as Ya,by as Ha,bz as Ja,bA as Ka,bB as Xa,bC as qa,bD as Qa,bE as Za,bF as $a,bG as es,bH as as,bI as ss,bJ as ts,bK as rs,bL as os,bM as ns,bN as is,bO as ls,bP as bs,bQ as cs,bR as ps,bS as ds,bT as ms,bU as us}from"./main-B30qTale.js";export{bV as Application,bW as ApplicationNamespace,bX as Array,bY as ArrayProxy,bZ as Controller,b_ as Debug,b$ as EmberDestroyable,c0 as EmberObject,c1 as EnumerableMutable,cc as GlimmerComponent,cd as GlimmerManager,ce as GlimmerReference,cf as GlimmerRuntime,cg as GlimmerUtil,ch as GlimmerValidator,c2 as Instrumentation,c0 as Object,c3 as ObjectCore,c4 as ObjectEvented,c5 as ObjectObservable,c6 as ObjectPromiseProxyMixin,c7 as ObjectProxy,ca as Owner,c8 as Runloop,c9 as Service,cb as VERSION}from"./main-B30qTale.js";const gs=new WeakMap,ys=Object.freeze(Object.defineProperty({__proto__:null,ASYNC_OBSERVERS:r,ComputedDescriptor:o,ComputedProperty:n,DEBUG_INJECTION_FUNCTIONS:i,Libraries:l,NAMESPACES:b,NAMESPACES_BY_ID:c,PROPERTY_DID_CHANGE:p,PROXY_CONTENT:d,SYNC_OBSERVERS:m,TrackedDescriptor:u,_getPath:g,_getProp:y,_setProp:_,activateObserver:O,addArrayObserver:S,addListener:f,addNamespace:C,addObserver:P,alias:h,arrayContentDidChange:v,arrayContentWillChange:j,autoComputed:E,beginPropertyChanges:M,cached:(...s)=>{const[t,r,o]=s,n=new WeakMap,i=o.get;o.get=function(){return n.has(this)||n.set(this,e(i.bind(this))),a(n.get(this))}},changeProperties:D,computed:N,createCache:e,defineDecorator:V,defineProperty:A,defineValue:w,deprecateProperty:function(e,a,r){Object.defineProperty(e,a,{configurable:!0,enumerable:!1,set(e){t(this,r,e)},get(){return s(this,r)}})},descriptorForDecorator:T,descriptorForProperty:I,eachProxyArrayDidChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayDidChange(e,a,s,t)},eachProxyArrayWillChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayWillChange(e,a,s,t)},endPropertyChanges:x,expandProperties:R,findNamespace:k,findNamespaces:F,flushAsyncObservers:L,get:s,getCachedValueFor:z,getProperties:G,getValue:a,hasListeners:U,hasUnknownProperty:B,inject:W,isClassicDecorator:Y,isComputed:H,isConst:J,isElementDescriptor:K,isNamespaceSearchDisabled:X,libraries:q,makeComputedDecorator:Q,markObjectAsDirty:Z,nativeDescDecorator:$,notifyPropertyChange:ee,objectAt:ae,on:se,processAllNamespaces:te,processNamespace:re,removeArrayObserver:oe,removeListener:ne,removeNamespace:ie,removeObserver:le,replace:be,replaceInNativeArray:pe,revalidateObservers:de,sendEvent:me,set:t,setClassicDecorator:ue,setNamespaceSearchDisabled:ge,setProperties:ye,setUnprocessedMixins:_e,tagForObject:Oe,tagForProperty:Se,tracked:fe,trySet:Ce},Symbol.toStringTag,{value:"Module"})),_s=Object.freeze(Object.defineProperty({__proto__:null,Input:Pe,Textarea:he,capabilities:ve,default:je,getComponentTemplate:Ee,setComponentManager:Me,setComponentTemplate:De},Symbol.toStringTag,{value:"Module"})),Os=Object.freeze(Object.defineProperty({__proto__:null,EventTarget:Ne,Promise:Ve,all:Ae,allSettled:we,asap:Te,async:Ie,cast:xe,configure:Re,default:ke,defer:Fe,denodeify:Le,filter:ze,hash:Ge,hashSettled:Ue,map:Be,off:We,on:Ye,race:He,reject:Je,resolve:Ke,rethrow:Xe},Symbol.toStringTag,{value:"Module"})),Ss=Object.freeze(Object.defineProperty({__proto__:null,cacheFor:z,guidFor:qe},Symbol.toStringTag,{value:"Module"})),fs=Object.freeze(Object.defineProperty({__proto__:null,default:Qe},Symbol.toStringTag,{value:"Module"})),Cs=Object.freeze(Object.defineProperty({__proto__:null,ENV:Ze,context:$e,getENV:ea,getLookup:aa,global:sa,setLookup:ta},Symbol.toStringTag,{value:"Module"})),Ps=Object.freeze(Object.defineProperty({__proto__:null,Meta:ra,UNDEFINED:oa,counters:na,meta:ia,peekMeta:la,setMeta:ba},Symbol.toStringTag,{value:"Module"})),hs=Object.freeze(Object.defineProperty({__proto__:null,ActionHandler:pa,Comparable:da,ContainerProxyMixin:ma,MutableEnumerable:ua,RSVP:ga,RegistryProxyMixin:ya,TargetActionSupport:_a,_ProxyMixin:Oa,_contentFor:Sa,onerrorDefault:fa},Symbol.toStringTag,{value:"Module"})),vs=Object.freeze(Object.defineProperty({__proto__:null,Cache:Ca,GUID_KEY:Pa,ROOT:ha,canInvoke:va,checkHasSuper:ja,dictionary:Ea,enumerableSymbol:Ma,generateGuid:Da,getDebugName:Na,getName:Va,guidFor:qe,intern:Aa,isInternalSymbol:wa,isObject:Ta,isProxy:Ia,lookupDescriptor:xa,observerListenerMetaFor:Ra,setListeners:ka,setName:Fa,setObservers:La,setProxy:za,setWithMandatorySetter:Ga,setupMandatorySetter:Ua,symbol:Ba,teardownMandatorySetter:Wa,toString:Ya,uuid:Ha,wrap:Ja},Symbol.toStringTag,{value:"Module"})),js=Object.freeze(Object.defineProperty({__proto__:null,ActionSupport:Ka,ComponentLookup:Xa,CoreView:qa,EventDispatcher:Qa,MUTABLE_CELL:Za,ViewStates:$a,addChildView:es,clearElementView:as,clearViewElement:ss,constructStyleDeprecationMessage:ts,getChildViews:rs,getElementView:os,getRootViews:ns,getViewBoundingClientRect:is,getViewBounds:ls,getViewClientRects:bs,getViewElement:cs,getViewId:ps,isSimpleClick:ds,setElementView:ms,setViewElement:us},Symbol.toStringTag,{value:"Module"}));export{fs as ArrayMutable,_s as Component,Cs as InternalsEnvironment,Ps as InternalsMeta,ys as InternalsMetal,hs as InternalsRuntime,vs as InternalsUtils,js as InternalsViews,Ss as ObjectInternals,Os as RSVP}; +import{c as e,g as a,a as s,s as t,A as r,C as o,b as n,D as i,L as l,N as b,d as c,P as p,e as d,S as m,T as u,_ as g,f as y,h as _,i as O,j as S,k as f,l as C,m as P,n as h,o as v,p as j,q as E,r as M,t as D,u as N,v as V,w as A,x as w,y as T,z as I,B as x,E as R,F as k,G as F,H as L,I as z,J as G,K as U,M as B,O as W,Q as Y,R as H,U as J,V as K,W as X,X as q,Y as Q,Z,$,a0 as ee,a1 as ae,a2 as se,a3 as te,a4 as re,a5 as oe,a6 as ne,a7 as ie,a8 as le,a9 as be,aa as pe,ab as de,ac as me,ad as ue,ae as ge,af as ye,ag as _e,ah as Oe,ai as Se,aj as fe,ak as Ce,al as Pe,am as he,an as ve,ao as je,ap as Ee,aq as Me,ar as De,as as Ne,at as Ve,au as Ae,av as we,aw as Te,ax as Ie,ay as xe,az as Re,aA as ke,aB as Fe,aC as Le,aD as ze,aE as Ge,aF as Ue,aG as Be,aH as We,aI as Ye,aJ as He,aK as Je,aL as Ke,aM as Xe,aN as qe,aO as Qe,aP as Ze,aQ as $e,aR as ea,aS as aa,aT as sa,aU as ta,aV as ra,aW as oa,aX as na,aY as ia,aZ as la,a_ as ba,a$ as pa,b0 as da,b1 as ma,b2 as ua,b3 as ga,b4 as ya,b5 as _a,b6 as Oa,b7 as Sa,b8 as fa,b9 as Ca,ba as Pa,bb as ha,bc as va,bd as ja,be as Ea,bf as Ma,bg as Da,bh as Na,bi as Va,bj as Aa,bk as wa,bl as Ta,bm as Ia,bn as xa,bo as Ra,bp as ka,bq as Fa,br as La,bs as za,bt as Ga,bu as Ua,bv as Ba,bw as Wa,bx as Ya,by as Ha,bz as Ja,bA as Ka,bB as Xa,bC as qa,bD as Qa,bE as Za,bF as $a,bG as es,bH as as,bI as ss,bJ as ts,bK as rs,bL as os,bM as ns,bN as is,bO as ls,bP as bs,bQ as cs,bR as ps,bS as ds,bT as ms,bU as us}from"./main-DsygQlAh.js";export{bV as Application,bW as ApplicationNamespace,bX as Array,bY as ArrayProxy,bZ as Controller,b_ as Debug,b$ as EmberDestroyable,c0 as EmberObject,c1 as EnumerableMutable,cc as GlimmerComponent,cd as GlimmerManager,ce as GlimmerReference,cf as GlimmerRuntime,cg as GlimmerUtil,ch as GlimmerValidator,c2 as Instrumentation,c0 as Object,c3 as ObjectCore,c4 as ObjectEvented,c5 as ObjectObservable,c6 as ObjectPromiseProxyMixin,c7 as ObjectProxy,ca as Owner,c8 as Runloop,c9 as Service,cb as VERSION}from"./main-DsygQlAh.js";const gs=new WeakMap,ys=Object.freeze(Object.defineProperty({__proto__:null,ASYNC_OBSERVERS:r,ComputedDescriptor:o,ComputedProperty:n,DEBUG_INJECTION_FUNCTIONS:i,Libraries:l,NAMESPACES:b,NAMESPACES_BY_ID:c,PROPERTY_DID_CHANGE:p,PROXY_CONTENT:d,SYNC_OBSERVERS:m,TrackedDescriptor:u,_getPath:g,_getProp:y,_setProp:_,activateObserver:O,addArrayObserver:S,addListener:f,addNamespace:C,addObserver:P,alias:h,arrayContentDidChange:v,arrayContentWillChange:j,autoComputed:E,beginPropertyChanges:M,cached:(...s)=>{const[t,r,o]=s,n=new WeakMap,i=o.get;o.get=function(){return n.has(this)||n.set(this,e(i.bind(this))),a(n.get(this))}},changeProperties:D,computed:N,createCache:e,defineDecorator:V,defineProperty:A,defineValue:w,deprecateProperty:function(e,a,r){Object.defineProperty(e,a,{configurable:!0,enumerable:!1,set(e){t(this,r,e)},get(){return s(this,r)}})},descriptorForDecorator:T,descriptorForProperty:I,eachProxyArrayDidChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayDidChange(e,a,s,t)},eachProxyArrayWillChange:function(e,a,s,t){let r=gs.get(e);void 0!==r&&r.arrayWillChange(e,a,s,t)},endPropertyChanges:x,expandProperties:R,findNamespace:k,findNamespaces:F,flushAsyncObservers:L,get:s,getCachedValueFor:z,getProperties:G,getValue:a,hasListeners:U,hasUnknownProperty:B,inject:W,isClassicDecorator:Y,isComputed:H,isConst:J,isElementDescriptor:K,isNamespaceSearchDisabled:X,libraries:q,makeComputedDecorator:Q,markObjectAsDirty:Z,nativeDescDecorator:$,notifyPropertyChange:ee,objectAt:ae,on:se,processAllNamespaces:te,processNamespace:re,removeArrayObserver:oe,removeListener:ne,removeNamespace:ie,removeObserver:le,replace:be,replaceInNativeArray:pe,revalidateObservers:de,sendEvent:me,set:t,setClassicDecorator:ue,setNamespaceSearchDisabled:ge,setProperties:ye,setUnprocessedMixins:_e,tagForObject:Oe,tagForProperty:Se,tracked:fe,trySet:Ce},Symbol.toStringTag,{value:"Module"})),_s=Object.freeze(Object.defineProperty({__proto__:null,Input:Pe,Textarea:he,capabilities:ve,default:je,getComponentTemplate:Ee,setComponentManager:Me,setComponentTemplate:De},Symbol.toStringTag,{value:"Module"})),Os=Object.freeze(Object.defineProperty({__proto__:null,EventTarget:Ne,Promise:Ve,all:Ae,allSettled:we,asap:Te,async:Ie,cast:xe,configure:Re,default:ke,defer:Fe,denodeify:Le,filter:ze,hash:Ge,hashSettled:Ue,map:Be,off:We,on:Ye,race:He,reject:Je,resolve:Ke,rethrow:Xe},Symbol.toStringTag,{value:"Module"})),Ss=Object.freeze(Object.defineProperty({__proto__:null,cacheFor:z,guidFor:qe},Symbol.toStringTag,{value:"Module"})),fs=Object.freeze(Object.defineProperty({__proto__:null,default:Qe},Symbol.toStringTag,{value:"Module"})),Cs=Object.freeze(Object.defineProperty({__proto__:null,ENV:Ze,context:$e,getENV:ea,getLookup:aa,global:sa,setLookup:ta},Symbol.toStringTag,{value:"Module"})),Ps=Object.freeze(Object.defineProperty({__proto__:null,Meta:ra,UNDEFINED:oa,counters:na,meta:ia,peekMeta:la,setMeta:ba},Symbol.toStringTag,{value:"Module"})),hs=Object.freeze(Object.defineProperty({__proto__:null,ActionHandler:pa,Comparable:da,ContainerProxyMixin:ma,MutableEnumerable:ua,RSVP:ga,RegistryProxyMixin:ya,TargetActionSupport:_a,_ProxyMixin:Oa,_contentFor:Sa,onerrorDefault:fa},Symbol.toStringTag,{value:"Module"})),vs=Object.freeze(Object.defineProperty({__proto__:null,Cache:Ca,GUID_KEY:Pa,ROOT:ha,canInvoke:va,checkHasSuper:ja,dictionary:Ea,enumerableSymbol:Ma,generateGuid:Da,getDebugName:Na,getName:Va,guidFor:qe,intern:Aa,isInternalSymbol:wa,isObject:Ta,isProxy:Ia,lookupDescriptor:xa,observerListenerMetaFor:Ra,setListeners:ka,setName:Fa,setObservers:La,setProxy:za,setWithMandatorySetter:Ga,setupMandatorySetter:Ua,symbol:Ba,teardownMandatorySetter:Wa,toString:Ya,uuid:Ha,wrap:Ja},Symbol.toStringTag,{value:"Module"})),js=Object.freeze(Object.defineProperty({__proto__:null,ActionSupport:Ka,ComponentLookup:Xa,CoreView:qa,EventDispatcher:Qa,MUTABLE_CELL:Za,ViewStates:$a,addChildView:es,clearElementView:as,clearViewElement:ss,constructStyleDeprecationMessage:ts,getChildViews:rs,getElementView:os,getRootViews:ns,getViewBoundingClientRect:is,getViewBounds:ls,getViewClientRects:bs,getViewElement:cs,getViewId:ps,isSimpleClick:ds,setElementView:ms,setViewElement:us},Symbol.toStringTag,{value:"Module"}));export{fs as ArrayMutable,_s as Component,Cs as InternalsEnvironment,Ps as InternalsMeta,ys as InternalsMetal,hs as InternalsRuntime,vs as InternalsUtils,js as InternalsViews,Ss as ObjectInternals,Os as RSVP}; diff --git a/release/assets/negentropy-B7CRzqXr.js b/release/assets/negentropy-CxcMNqMs.js similarity index 99% rename from release/assets/negentropy-B7CRzqXr.js rename to release/assets/negentropy-CxcMNqMs.js index 2497bbb..ed9d5bf 100644 --- a/release/assets/negentropy-B7CRzqXr.js +++ b/release/assets/negentropy-CxcMNqMs.js @@ -1,2 +1,2 @@ -import{ci as t,cj as e,ck as i,cl as r,cm as n,cn as s,co as o,cp as a}from"./main-B30qTale.js";var h=Array.isArray;function u(){for(var r,n=[],s=0;s0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function c(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function d(...t){for(let e=0;e>>e}function p(t){return"string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t)),l(t),t}class m{}function w(t){const e=e=>t().update(p(e)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function b(t,e,i){return t&e^~t&i}function y(t,e,i){return t&e^t&i^e&i}class E extends m{constructor(t,e,i,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(t),this.view=f(this.buffer)}update(t){c(this),l(t=p(t));const{view:e,buffer:i,blockLen:r}=this,n=t.length;for(let s=0;sr-s&&(this.process(i,0),s=0);for(let l=s;l>n&s),a=Number(i&s),h=r?4:0,u=r?0:4;t.setUint32(e+h,o,r),t.setUint32(e+u,a,r)}(i,r-8,BigInt(8*this.length),n),this.process(i,0);const o=f(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=a/4,u=this.get();if(h>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l>>3,r=g(e,17)^g(e,19)^e>>>10;A[l]=r+A[l-7]+i+A[l-16]|0}let{A:i,B:r,C:n,D:s,E:o,F:a,G:h,H:u}=this;for(let l=0;l<64;l++){const t=u+(g(o,6)^g(o,11)^g(o,25))+b(o,a,h)+x[l]+A[l]|0,e=(g(i,2)^g(i,13)^g(i,22))+y(i,r,n)|0;u=h,h=a,a=o,o=s+t|0,s=n,n=r,r=i,i=t+e|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,h=h+this.G|0,u=u+this.H|0,this.set(i,r,n,s,o,a,h,u)}roundClean(){d(A)}destroy(){this.set(0,0,0,0,0,0,0,0),d(this.buffer)}}const U=w(()=>new L),I=32;class B{_raw;length;constructor(t){this._raw=new Uint8Array(t||512),this.length=t?t.length:0}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(t){if(t instanceof B&&(t=t.unwrap()),"number"!=typeof t.length)throw Error("bad length");const e=t.length+this.length;if(this.capacity>>=7;e.reverse();for(let i=0;iU.create().update(t).digest()}setToZero(){this.buf=new Uint8Array(I)}add(t){let e=0,i=0,r=new DataView(this.buf.buffer),n=new DataView(t.buffer);for(let s=0;s<8;s++){let t=4*s,o=r.getUint32(t,!0);o+=e,o+=n.getUint32(t,!0),o>4294967295&&(i=1),r.setUint32(t,4294967295&o,!0),e=i,i=0}}negate(){let t=new DataView(this.buf.buffer);for(let i=0;i<8;i++){let e=4*i;t.setUint32(e,~t.getUint32(e,!0))}let e=new Uint8Array(I);e[0]=1,this.add(e)}async getFingerprint(t){let e=new B;return e.extend(this.buf),e.extend(T(t)),(await this.sha256(e.unwrap())).subarray(0,16)}}class k{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");if((e=M(e)).byteLength!==I)throw Error("bad id size for added item");this.items.push({timestamp:t,id:e})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(G);for(let t=1;t=this.items.length)throw Error("out of range");return this.items[t]}iterate(t,e,i){this._checkSealed(),this._checkBounds(t,e);for(let r=t;rG(t,i)<0)}async fingerprint(t,e){let i=new S;return i.setToZero(),this.iterate(t,e,t=>(i.add(t.id),!0)),await i.getFingerprint(e-t)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(t,e){if(t>e||e>this.items.length)throw Error("bad range")}_binarySearch(t,e,i,r){let n=i-e;for(;n>0;){let i=e,s=Math.floor(n/2);i+=s,r(t[i])?(e=++i,n-=s+1):n=s}return e}}class v{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;isInitiator;wantUint8ArrayOutput;constructor(t,e=0){if(0!==e&&e<4096)throw Error("frameSizeLimit too small");this.storage=t,this.frameSizeLimit=e,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(t,e){return{timestamp:t,id:e||new Uint8Array(0)}}async initiate(){if(this.isInitiator)throw Error("already initiated");this.isInitiator=!0;let t=new B;return t.extend([97]),await this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),this._renderOutput(t)}setInitiator(){this.isInitiator=!0}async reconcile(t){let e=[],i=[],r=new B(M(t));this.lastTimestampIn=this.lastTimestampOut=0;let n=new B;n.extend([97]);let s=N(r,1)[0];if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(97!==s){if(this.isInitiator)throw Error("unsupported negentropy protocol version requested: "+(s-96));return[this._renderOutput(n),e,i]}let o=this.storage.size(),a=this._bound(0),h=0,u=!1;for(;0!==r.length;){let t=new B,s=()=>{u&&(u=!1,t.extend(this.encodeBound(a)),t.extend(T(0)))},l=this.decodeBound(r),c=O(r),d=h,f=this.storage.findLowerBound(h,o,l);if(0===c)u=!0;else if(1===c)0!==F(N(r,16),await this.storage.fingerprint(d,f))?(s(),await this.splitRange(d,f,l,t)):u=!0;else{if(2!==c)throw Error("unexpected mode");{let o=O(r),a={};for(let t=0;t{let i=t.id;return a[i]?delete a[i]:this.isInitiator&&e.push(this.wantUint8ArrayOutput?i:z(i)),!0});for(let t of Object.values(a))i.push(this.wantUint8ArrayOutput?t:z(t))}else{s();let e=new B,i=0,r=l;this.storage.iterate(d,f,(t,s)=>this.exceededFrameSizeLimit(n.length+e.length)?(r=t,f=s,!1):(e.extend(t.id),i++,!0)),t.extend(this.encodeBound(r)),t.extend(T(2)),t.extend(T(i)),t.extend(e),n.extend(t),t=new B}}}if(this.exceededFrameSizeLimit(n.length+t.length)){let t=await this.storage.fingerprint(f,o);n.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),n.extend(T(1)),n.extend(t);break}n.extend(t),h=f,a=l}return[1===n.length&&this.isInitiator?null:this._renderOutput(n),e,i]}async splitRange(t,e,i,r){let n=e-t;if(n<32)r.extend(this.encodeBound(i)),r.extend(T(2)),r.extend(T(n)),this.storage.iterate(t,e,t=>(r.extend(t.id),!0));else{let s=Math.floor(n/16),o=n%16,a=t;for(let t=0;t<16;t++){let n,h=s+(t(r===a-1?t=i:e=i,!0)),n=this.getMinimalBound(t,e)}r.extend(this.encodeBound(n)),r.extend(T(1)),r.extend(u)}}}_renderOutput(t){let e=t.unwrap();return this.wantUint8ArrayOutput?e:z(e)}exceededFrameSizeLimit(t){return this.frameSizeLimit&&t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=O(t);return e=0===e?Number.MAX_VALUE:e-1,this.lastTimestampIn===Number.MAX_VALUE||e===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(e+=this.lastTimestampIn,this.lastTimestampIn=e,e)}decodeBound(t){let e=this.decodeTimestampIn(t),i=O(t);if(i>I)throw Error("bound key too long");return{timestamp:e,id:N(t,i)}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,T(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,T(t+1)}encodeBound(t){let e=new B;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(T(t.id.length)),e.extend(t.id),e}getMinimalBound(t,e){if(e.timestamp!==t.timestamp)return this._bound(e.timestamp);{let i=0,r=e.id,n=t.id;for(let t=0;t>>4&15]+t[15&e]}function z(t){let e="";for(let i=0,r=t.length;ie[i])return 1}return t.byteLength>e.byteLength?1:t.byteLength(C("Sending initial message",c,n,f),["NEG-OPEN",c,n,f]),()=>(C("Closing sync",c),["NEG-CLOSE",c]),t=>("NEG-MSG"===t[0]||"NEG-ERR"===t[0])&&t[1]===c).pipe(s(t=>{if("NEG-ERR"===t[0])throw new Error(t[2]);return t[2]}),o());if(l?.signal?.aborted)return!1;const m=new e(t=>{if(l?.signal?.aborted)return t.next("abort"),void t.complete();const e=()=>{t.next("abort"),t.complete()};return l?.signal?.addEventListener("abort",e),()=>l?.signal?.removeEventListener("abort",e)}),w=p.subscribe({next:t=>C(t),error:()=>{}});try{for(;g&&!0!==l?.signal?.aborted;)try{const t=await a(u(p.pipe(s(t=>({type:"message",data:t}))),m.pipe(s(()=>({type:"abort"})))));if("abort"===t.type||l?.signal?.aborted)return w.unsubscribe(),!1;const[e,i,r]=await d.reconcile(t.data);await h(i,r),g=e}catch(b){if(l?.signal?.aborted)return w.unsubscribe(),!1;throw b}}catch(b){throw w.unsubscribe(),b}finally{w.unsubscribe()}return!0}export{D as buildStorageFromFilter,X as buildStorageVector,H as negentropySync}; diff --git a/release/index.html b/release/index.html index e7b98ac..2590474 100644 --- a/release/index.html +++ b/release/index.html @@ -39,8 +39,8 @@ - - + +