diff --git a/bootstrap/ssr/assets/ArtworkShareModal-DEVyX6r2.js b/bootstrap/ssr/assets/ArtworkShareModal-DEVyX6r2.js new file mode 100644 index 00000000..3663af63 --- /dev/null +++ b/bootstrap/ssr/assets/ArtworkShareModal-DEVyX6r2.js @@ -0,0 +1,301 @@ +import { r as reactExports, a as reactDomExports, R as React } from "./vendor-tiptap-DSw66HfW.js"; +import { S as ShareToast } from "../ssr.js"; +import "util"; +import "stream"; +import "path"; +import "http"; +import "https"; +import "url"; +import "fs"; +import "crypto"; +import "http2"; +import "assert"; +import "tty"; +import "os"; +import "zlib"; +import "events"; +import "node:process"; +import "node:path"; +import "node:url"; +import "./vendor-tooltip-CIQaDNlG.js"; +import "./vendor-realtime-cgmg5qQY.js"; +import "buffer"; +import "child_process"; +import "net"; +import "tls"; +import "./vendor-motion-yDK3iGlC.js"; +import "process"; +import "async_hooks"; +const FeedShareArtworkModal = reactExports.lazy(() => import("../ssr.js").then((n) => n.a)); +function facebookUrl(url) { + return `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`; +} +function twitterUrl(url, title) { + return `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`; +} +function pinterestUrl(url, imageUrl, title) { + return `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(url)}&media=${encodeURIComponent(imageUrl)}&description=${encodeURIComponent(title)}`; +} +function emailUrl(url, title) { + return `mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(url)}`; +} +function CopyIcon() { + return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75" })); +} +function CheckIcon() { + return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-5 w-5 text-emerald-400" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z", clipRule: "evenodd" })); +} +function FacebookIcon() { + return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12Z" })); +} +function XTwitterIcon() { + return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77Z" })); +} +function PinterestIcon() { + return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "M12 2C6.477 2 2 6.477 2 12c0 4.236 2.636 7.855 6.356 9.312-.088-.791-.167-2.005.035-2.868.181-.78 1.172-4.97 1.172-4.97s-.299-.598-.299-1.482c0-1.388.806-2.425 1.808-2.425.853 0 1.265.64 1.265 1.408 0 .858-.546 2.14-.828 3.33-.236.995.5 1.807 1.482 1.807 1.778 0 3.144-1.874 3.144-4.58 0-2.393-1.72-4.068-4.177-4.068-2.845 0-4.515 2.135-4.515 4.34 0 .859.331 1.781.745 2.282a.3.3 0 0 1 .069.288l-.278 1.133c-.044.183-.145.222-.335.134-1.249-.581-2.03-2.407-2.03-3.874 0-3.154 2.292-6.052 6.608-6.052 3.469 0 6.165 2.472 6.165 5.776 0 3.447-2.173 6.22-5.19 6.22-1.013 0-1.965-.527-2.291-1.148l-.623 2.378c-.226.869-.835 1.958-1.244 2.621.937.29 1.931.446 2.962.446 5.523 0 10-4.477 10-10S17.523 2 12 2Z" })); +} +function EmailIcon() { + return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75" })); +} +function EmbedIcon() { + return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5" })); +} +function CloseIcon() { + return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 2, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18 18 6M6 6l12 12" })); +} +function openShareWindow(url) { + window.open(url, "_blank", "noopener,noreferrer,width=600,height=500"); +} +function trackShare(artworkId, platform) { + const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content"); + fetch(`/api/artworks/${artworkId}/share`, { + method: "POST", + headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken || "" }, + credentials: "same-origin", + body: JSON.stringify({ platform }) + }).catch(() => { + }); +} +function ArtworkShareModal({ open, onClose, artwork, shareUrl, isLoggedIn = false }) { + const backdropRef = reactExports.useRef(null); + const [linkCopied, setLinkCopied] = reactExports.useState(false); + const [embedCopied, setEmbedCopied] = reactExports.useState(false); + const [showEmbed, setShowEmbed] = reactExports.useState(false); + const [toastVisible, setToastVisible] = reactExports.useState(false); + const [toastMessage, setToastMessage] = reactExports.useState(""); + const [profileShareOpen, setProfileShareOpen] = reactExports.useState(false); + const url = shareUrl || artwork?.canonical_url || (typeof window !== "undefined" ? window.location.href : "#"); + const title = artwork?.title || "Artwork"; + const imageUrl = artwork?.thumbs?.xl?.url || artwork?.thumbs?.lg?.url || artwork?.thumbs?.md?.url || ""; + const thumbMdUrl = artwork?.thumbs?.md?.url || imageUrl; + const embedCode = ` + ${title.replace(/ +`; + reactExports.useEffect(() => { + if (open) { + document.body.style.overflow = "hidden"; + return () => { + document.body.style.overflow = ""; + }; + } + }, [open]); + reactExports.useEffect(() => { + if (!open) return; + const handler = (e) => { + if (e.key === "Escape") onClose(); + }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }, [open, onClose]); + reactExports.useEffect(() => { + if (open) { + setLinkCopied(false); + setEmbedCopied(false); + setShowEmbed(false); + } + }, [open]); + const showToast = reactExports.useCallback((msg) => { + setToastMessage(msg); + setToastVisible(true); + }, []); + const handleCopyLink = async () => { + try { + await navigator.clipboard.writeText(url); + setLinkCopied(true); + showToast("Link copied!"); + trackShare(artwork?.id, "copy"); + setTimeout(() => setLinkCopied(false), 2500); + } catch { + } + }; + const handleCopyEmbed = async () => { + try { + await navigator.clipboard.writeText(embedCode); + setEmbedCopied(true); + showToast("Embed code copied!"); + trackShare(artwork?.id, "embed"); + setTimeout(() => setEmbedCopied(false), 2500); + } catch { + } + }; + const handlePlatformShare = (platform, shareLink) => { + openShareWindow(shareLink); + trackShare(artwork?.id, platform); + onClose(); + }; + if (!open) return null; + const SHARE_OPTIONS = [ + { + label: linkCopied ? "Copied!" : "Copy Link", + icon: linkCopied ? /* @__PURE__ */ React.createElement(CheckIcon, null) : /* @__PURE__ */ React.createElement(CopyIcon, null), + onClick: handleCopyLink, + className: linkCopied ? "border-emerald-500/40 bg-emerald-500/15 text-emerald-400" : "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white" + }, + { + label: "Facebook", + icon: /* @__PURE__ */ React.createElement(FacebookIcon, null), + onClick: () => handlePlatformShare("facebook", facebookUrl(url)), + className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-[#1877F2]/40 hover:bg-[#1877F2]/15 hover:text-[#1877F2]" + }, + { + label: "X (Twitter)", + icon: /* @__PURE__ */ React.createElement(XTwitterIcon, null), + onClick: () => handlePlatformShare("twitter", twitterUrl(url, title)), + className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/30 hover:bg-white/[0.10] hover:text-white" + }, + { + label: "Pinterest", + icon: /* @__PURE__ */ React.createElement(PinterestIcon, null), + onClick: () => handlePlatformShare("pinterest", pinterestUrl(url, imageUrl, title)), + className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-[#E60023]/40 hover:bg-[#E60023]/15 hover:text-[#E60023]" + }, + { + label: "Email", + icon: /* @__PURE__ */ React.createElement(EmailIcon, null), + onClick: () => { + window.location.href = emailUrl(url, title); + trackShare(artwork?.id, "email"); + }, + className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white" + }, + ...isLoggedIn ? [{ + label: "My Profile", + icon: /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes h-5 w-5 text-[1.1rem]" }), + onClick: () => setProfileShareOpen(true), + className: "border-sky-500/30 bg-sky-500/10 text-sky-400 hover:border-sky-400/50 hover:bg-sky-500/20" + }] : [] + ]; + return reactDomExports.createPortal( + /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( + "div", + { + ref: backdropRef, + onClick: (e) => { + if (e.target === backdropRef.current) onClose(); + }, + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4", + role: "dialog", + "aria-modal": "true", + "aria-label": "Share this artwork" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-md rounded-2xl border border-nova-700/50 bg-nova-900/80 shadow-2xl backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Share this artwork"), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: onClose, + className: "rounded-lg p-1.5 text-white/40 transition hover:bg-white/[0.06] hover:text-white/70", + "aria-label": "Close share dialog" + }, + /* @__PURE__ */ React.createElement(CloseIcon, null) + )), thumbMdUrl && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 border-b border-white/[0.06] px-6 py-3" }, /* @__PURE__ */ React.createElement( + "img", + { + src: thumbMdUrl, + alt: title, + className: "h-14 w-14 rounded-lg object-cover", + loading: "lazy" + } + ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-medium text-white" }, title), artwork?.user?.username && /* @__PURE__ */ React.createElement("p", { className: "truncate text-xs text-white/50" }, "by ", artwork.user.username))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-2.5 px-6 py-5 sm:grid-cols-5" }, SHARE_OPTIONS.map((opt) => /* @__PURE__ */ React.createElement( + "button", + { + key: opt.label, + type: "button", + onClick: opt.onClick, + className: [ + "flex flex-col items-center gap-1.5 rounded-xl border px-2 py-3 text-xs font-medium transition-all duration-200", + opt.className + ].join(" ") + }, + opt.icon, + /* @__PURE__ */ React.createElement("span", { className: "truncate" }, opt.label) + ))), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: () => setShowEmbed(!showEmbed), + className: "flex items-center gap-2 text-sm font-medium text-white/60 transition hover:text-white/80" + }, + /* @__PURE__ */ React.createElement(EmbedIcon, null), + showEmbed ? "Hide Embed Code" : "Embed Code", + /* @__PURE__ */ React.createElement( + "svg", + { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 16 16", + fill: "currentColor", + className: `h-3.5 w-3.5 transition-transform duration-200 ${showEmbed ? "rotate-180" : ""}` + }, + /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z", clipRule: "evenodd" }) + ) + ), showEmbed && /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement( + "textarea", + { + readOnly: true, + value: embedCode, + rows: 3, + className: "w-full resize-none rounded-xl border border-white/[0.08] bg-white/[0.03] px-4 py-3 font-mono text-xs text-white/70 outline-none focus:border-white/[0.15]", + onClick: (e) => e.target.select() + } + ), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: handleCopyEmbed, + className: [ + "inline-flex items-center gap-1.5 rounded-full border px-4 py-1.5 text-xs font-medium transition-all duration-200", + embedCopied ? "border-emerald-500/40 bg-emerald-500/15 text-emerald-400" : "border-white/[0.08] bg-white/[0.04] text-white/60 hover:border-white/[0.15] hover:text-white/80" + ].join(" ") + }, + embedCopied ? /* @__PURE__ */ React.createElement(CheckIcon, null) : /* @__PURE__ */ React.createElement(CopyIcon, null), + embedCopied ? "Copied!" : "Copy Embed" + )))) + ), /* @__PURE__ */ React.createElement( + ShareToast, + { + message: toastMessage, + visible: toastVisible, + onHide: () => setToastVisible(false) + } + ), profileShareOpen && /* @__PURE__ */ React.createElement(reactExports.Suspense, { fallback: null }, /* @__PURE__ */ React.createElement( + FeedShareArtworkModal, + { + isOpen: profileShareOpen, + onClose: () => setProfileShareOpen(false), + preselectedArtwork: artwork?.id ? { + id: artwork.id, + title: artwork.title, + thumb_url: artwork.thumbs?.md?.url ?? artwork.thumbs?.lg?.url ?? null, + user: artwork.user ?? null + } : null, + onShared: () => { + setProfileShareOpen(false); + showToast("Shared to your profile!"); + } + } + ))), + document.body + ); +} +export { + ArtworkShareModal as default +}; diff --git a/bootstrap/ssr/assets/emoji-data-4xGXbtDn.js b/bootstrap/ssr/assets/emoji-data-4xGXbtDn.js new file mode 100644 index 00000000..e6705c33 --- /dev/null +++ b/bootstrap/ssr/assets/emoji-data-4xGXbtDn.js @@ -0,0 +1,17 @@ +const categories = /* @__PURE__ */ JSON.parse('[{"id":"people","emojis":["grinning","smiley","smile","grin","laughing","sweat_smile","rolling_on_the_floor_laughing","joy","slightly_smiling_face","upside_down_face","melting_face","wink","blush","innocent","smiling_face_with_3_hearts","heart_eyes","star-struck","kissing_heart","kissing","relaxed","kissing_closed_eyes","kissing_smiling_eyes","smiling_face_with_tear","yum","stuck_out_tongue","stuck_out_tongue_winking_eye","zany_face","stuck_out_tongue_closed_eyes","money_mouth_face","hugging_face","face_with_hand_over_mouth","face_with_open_eyes_and_hand_over_mouth","face_with_peeking_eye","shushing_face","thinking_face","saluting_face","zipper_mouth_face","face_with_raised_eyebrow","neutral_face","expressionless","no_mouth","dotted_line_face","face_in_clouds","smirk","unamused","face_with_rolling_eyes","grimacing","face_exhaling","lying_face","shaking_face","relieved","pensive","sleepy","drooling_face","sleeping","mask","face_with_thermometer","face_with_head_bandage","nauseated_face","face_vomiting","sneezing_face","hot_face","cold_face","woozy_face","dizzy_face","face_with_spiral_eyes","exploding_head","face_with_cowboy_hat","partying_face","disguised_face","sunglasses","nerd_face","face_with_monocle","confused","face_with_diagonal_mouth","worried","slightly_frowning_face","white_frowning_face","open_mouth","hushed","astonished","flushed","pleading_face","face_holding_back_tears","frowning","anguished","fearful","cold_sweat","disappointed_relieved","cry","sob","scream","confounded","persevere","disappointed","sweat","weary","tired_face","yawning_face","triumph","rage","angry","face_with_symbols_on_mouth","smiling_imp","imp","skull","skull_and_crossbones","hankey","clown_face","japanese_ogre","japanese_goblin","ghost","alien","space_invader","wave","raised_back_of_hand","raised_hand_with_fingers_splayed","hand","spock-hand","rightwards_hand","leftwards_hand","palm_down_hand","palm_up_hand","leftwards_pushing_hand","rightwards_pushing_hand","ok_hand","pinched_fingers","pinching_hand","v","crossed_fingers","hand_with_index_finger_and_thumb_crossed","i_love_you_hand_sign","the_horns","call_me_hand","point_left","point_right","point_up_2","middle_finger","point_down","point_up","index_pointing_at_the_viewer","+1","-1","fist","facepunch","left-facing_fist","right-facing_fist","clap","raised_hands","heart_hands","open_hands","palms_up_together","handshake","pray","writing_hand","nail_care","selfie","muscle","mechanical_arm","mechanical_leg","leg","foot","ear","ear_with_hearing_aid","nose","brain","anatomical_heart","lungs","tooth","bone","eyes","eye","tongue","lips","biting_lip","baby","child","boy","girl","adult","person_with_blond_hair","man","bearded_person","man_with_beard","woman_with_beard","red_haired_man","curly_haired_man","white_haired_man","bald_man","woman","red_haired_woman","red_haired_person","curly_haired_woman","curly_haired_person","white_haired_woman","white_haired_person","bald_woman","bald_person","blond-haired-woman","blond-haired-man","older_adult","older_man","older_woman","person_frowning","man-frowning","woman-frowning","person_with_pouting_face","man-pouting","woman-pouting","no_good","man-gesturing-no","woman-gesturing-no","ok_woman","man-gesturing-ok","woman-gesturing-ok","information_desk_person","man-tipping-hand","woman-tipping-hand","raising_hand","man-raising-hand","woman-raising-hand","deaf_person","deaf_man","deaf_woman","bow","man-bowing","woman-bowing","face_palm","man-facepalming","woman-facepalming","shrug","man-shrugging","woman-shrugging","health_worker","male-doctor","female-doctor","student","male-student","female-student","teacher","male-teacher","female-teacher","judge","male-judge","female-judge","farmer","male-farmer","female-farmer","cook","male-cook","female-cook","mechanic","male-mechanic","female-mechanic","factory_worker","male-factory-worker","female-factory-worker","office_worker","male-office-worker","female-office-worker","scientist","male-scientist","female-scientist","technologist","male-technologist","female-technologist","singer","male-singer","female-singer","artist","male-artist","female-artist","pilot","male-pilot","female-pilot","astronaut","male-astronaut","female-astronaut","firefighter","male-firefighter","female-firefighter","cop","male-police-officer","female-police-officer","sleuth_or_spy","male-detective","female-detective","guardsman","male-guard","female-guard","ninja","construction_worker","male-construction-worker","female-construction-worker","person_with_crown","prince","princess","man_with_turban","man-wearing-turban","woman-wearing-turban","man_with_gua_pi_mao","person_with_headscarf","person_in_tuxedo","man_in_tuxedo","woman_in_tuxedo","bride_with_veil","man_with_veil","woman_with_veil","pregnant_woman","pregnant_man","pregnant_person","breast-feeding","woman_feeding_baby","man_feeding_baby","person_feeding_baby","angel","santa","mrs_claus","mx_claus","superhero","male_superhero","female_superhero","supervillain","male_supervillain","female_supervillain","mage","male_mage","female_mage","fairy","male_fairy","female_fairy","vampire","male_vampire","female_vampire","merperson","merman","mermaid","elf","male_elf","female_elf","genie","male_genie","female_genie","zombie","male_zombie","female_zombie","troll","massage","man-getting-massage","woman-getting-massage","haircut","man-getting-haircut","woman-getting-haircut","walking","man-walking","woman-walking","standing_person","man_standing","woman_standing","kneeling_person","man_kneeling","woman_kneeling","person_with_probing_cane","man_with_probing_cane","woman_with_probing_cane","person_in_motorized_wheelchair","man_in_motorized_wheelchair","woman_in_motorized_wheelchair","person_in_manual_wheelchair","man_in_manual_wheelchair","woman_in_manual_wheelchair","runner","man-running","woman-running","dancer","man_dancing","man_in_business_suit_levitating","dancers","men-with-bunny-ears-partying","women-with-bunny-ears-partying","person_in_steamy_room","man_in_steamy_room","woman_in_steamy_room","person_climbing","man_climbing","woman_climbing","fencer","horse_racing","skier","snowboarder","golfer","man-golfing","woman-golfing","surfer","man-surfing","woman-surfing","rowboat","man-rowing-boat","woman-rowing-boat","swimmer","man-swimming","woman-swimming","person_with_ball","man-bouncing-ball","woman-bouncing-ball","weight_lifter","man-lifting-weights","woman-lifting-weights","bicyclist","man-biking","woman-biking","mountain_bicyclist","man-mountain-biking","woman-mountain-biking","person_doing_cartwheel","man-cartwheeling","woman-cartwheeling","wrestlers","man-wrestling","woman-wrestling","water_polo","man-playing-water-polo","woman-playing-water-polo","handball","man-playing-handball","woman-playing-handball","juggling","man-juggling","woman-juggling","person_in_lotus_position","man_in_lotus_position","woman_in_lotus_position","bath","sleeping_accommodation","people_holding_hands","two_women_holding_hands","man_and_woman_holding_hands","two_men_holding_hands","couplekiss","woman-kiss-man","man-kiss-man","woman-kiss-woman","couple_with_heart","woman-heart-man","man-heart-man","woman-heart-woman","family","man-woman-boy","man-woman-girl","man-woman-girl-boy","man-woman-boy-boy","man-woman-girl-girl","man-man-boy","man-man-girl","man-man-girl-boy","man-man-boy-boy","man-man-girl-girl","woman-woman-boy","woman-woman-girl","woman-woman-girl-boy","woman-woman-boy-boy","woman-woman-girl-girl","man-boy","man-boy-boy","man-girl","man-girl-boy","man-girl-girl","woman-boy","woman-boy-boy","woman-girl","woman-girl-boy","woman-girl-girl","speaking_head_in_silhouette","bust_in_silhouette","busts_in_silhouette","people_hugging","footprints","robot_face","smiley_cat","smile_cat","joy_cat","heart_eyes_cat","smirk_cat","kissing_cat","scream_cat","crying_cat_face","pouting_cat","see_no_evil","hear_no_evil","speak_no_evil","love_letter","cupid","gift_heart","sparkling_heart","heartpulse","heartbeat","revolving_hearts","two_hearts","heart_decoration","heavy_heart_exclamation_mark_ornament","broken_heart","heart_on_fire","mending_heart","heart","pink_heart","orange_heart","yellow_heart","green_heart","blue_heart","light_blue_heart","purple_heart","brown_heart","black_heart","grey_heart","white_heart","kiss","100","anger","boom","dizzy","sweat_drops","dash","hole","speech_balloon","eye-in-speech-bubble","left_speech_bubble","right_anger_bubble","thought_balloon","zzz"]},{"id":"nature","emojis":["monkey_face","monkey","gorilla","orangutan","dog","dog2","guide_dog","service_dog","poodle","wolf","fox_face","raccoon","cat","cat2","black_cat","lion_face","tiger","tiger2","leopard","horse","moose","donkey","racehorse","unicorn_face","zebra_face","deer","bison","cow","ox","water_buffalo","cow2","pig","pig2","boar","pig_nose","ram","sheep","goat","dromedary_camel","camel","llama","giraffe_face","elephant","mammoth","rhinoceros","hippopotamus","mouse","mouse2","rat","hamster","rabbit","rabbit2","chipmunk","beaver","hedgehog","bat","bear","polar_bear","koala","panda_face","sloth","otter","skunk","kangaroo","badger","feet","turkey","chicken","rooster","hatching_chick","baby_chick","hatched_chick","bird","penguin","dove_of_peace","eagle","duck","swan","owl","dodo","feather","flamingo","peacock","parrot","wing","black_bird","goose","frog","crocodile","turtle","lizard","snake","dragon_face","dragon","sauropod","t-rex","whale","whale2","dolphin","seal","fish","tropical_fish","blowfish","shark","octopus","shell","coral","jellyfish","snail","butterfly","bug","ant","bee","beetle","ladybug","cricket","cockroach","spider","spider_web","scorpion","mosquito","fly","worm","microbe","bouquet","cherry_blossom","white_flower","lotus","rosette","rose","wilted_flower","hibiscus","sunflower","blossom","tulip","hyacinth","seedling","potted_plant","evergreen_tree","deciduous_tree","palm_tree","cactus","ear_of_rice","herb","shamrock","four_leaf_clover","maple_leaf","fallen_leaf","leaves","empty_nest","nest_with_eggs","mushroom"]},{"id":"foods","emojis":["grapes","melon","watermelon","tangerine","lemon","banana","pineapple","mango","apple","green_apple","pear","peach","cherries","strawberry","blueberries","kiwifruit","tomato","olive","coconut","avocado","eggplant","potato","carrot","corn","hot_pepper","bell_pepper","cucumber","leafy_green","broccoli","garlic","onion","peanuts","beans","chestnut","ginger_root","pea_pod","bread","croissant","baguette_bread","flatbread","pretzel","bagel","pancakes","waffle","cheese_wedge","meat_on_bone","poultry_leg","cut_of_meat","bacon","hamburger","fries","pizza","hotdog","sandwich","taco","burrito","tamale","stuffed_flatbread","falafel","egg","fried_egg","shallow_pan_of_food","stew","fondue","bowl_with_spoon","green_salad","popcorn","butter","salt","canned_food","bento","rice_cracker","rice_ball","rice","curry","ramen","spaghetti","sweet_potato","oden","sushi","fried_shrimp","fish_cake","moon_cake","dango","dumpling","fortune_cookie","takeout_box","crab","lobster","shrimp","squid","oyster","icecream","shaved_ice","ice_cream","doughnut","cookie","birthday","cake","cupcake","pie","chocolate_bar","candy","lollipop","custard","honey_pot","baby_bottle","glass_of_milk","coffee","teapot","tea","sake","champagne","wine_glass","cocktail","tropical_drink","beer","beers","clinking_glasses","tumbler_glass","pouring_liquid","cup_with_straw","bubble_tea","beverage_box","mate_drink","ice_cube","chopsticks","knife_fork_plate","fork_and_knife","spoon","hocho","jar","amphora"]},{"id":"activity","emojis":["jack_o_lantern","christmas_tree","fireworks","sparkler","firecracker","sparkles","balloon","tada","confetti_ball","tanabata_tree","bamboo","dolls","flags","wind_chime","rice_scene","red_envelope","ribbon","gift","reminder_ribbon","admission_tickets","ticket","medal","trophy","sports_medal","first_place_medal","second_place_medal","third_place_medal","soccer","baseball","softball","basketball","volleyball","football","rugby_football","tennis","flying_disc","bowling","cricket_bat_and_ball","field_hockey_stick_and_ball","ice_hockey_stick_and_puck","lacrosse","table_tennis_paddle_and_ball","badminton_racquet_and_shuttlecock","boxing_glove","martial_arts_uniform","goal_net","golf","ice_skate","fishing_pole_and_fish","diving_mask","running_shirt_with_sash","ski","sled","curling_stone","dart","yo-yo","kite","gun","8ball","crystal_ball","magic_wand","video_game","joystick","slot_machine","game_die","jigsaw","teddy_bear","pinata","mirror_ball","nesting_dolls","spades","hearts","diamonds","clubs","chess_pawn","black_joker","mahjong","flower_playing_cards","performing_arts","frame_with_picture","art","thread","sewing_needle","yarn","knot"]},{"id":"places","emojis":["earth_africa","earth_americas","earth_asia","globe_with_meridians","world_map","japan","compass","snow_capped_mountain","mountain","volcano","mount_fuji","camping","beach_with_umbrella","desert","desert_island","national_park","stadium","classical_building","building_construction","bricks","rock","wood","hut","house_buildings","derelict_house_building","house","house_with_garden","office","post_office","european_post_office","hospital","bank","hotel","love_hotel","convenience_store","school","department_store","factory","japanese_castle","european_castle","wedding","tokyo_tower","statue_of_liberty","church","mosque","hindu_temple","synagogue","shinto_shrine","kaaba","fountain","tent","foggy","night_with_stars","cityscape","sunrise_over_mountains","sunrise","city_sunset","city_sunrise","bridge_at_night","hotsprings","carousel_horse","playground_slide","ferris_wheel","roller_coaster","barber","circus_tent","steam_locomotive","railway_car","bullettrain_side","bullettrain_front","train2","metro","light_rail","station","tram","monorail","mountain_railway","train","bus","oncoming_bus","trolleybus","minibus","ambulance","fire_engine","police_car","oncoming_police_car","taxi","oncoming_taxi","car","oncoming_automobile","blue_car","pickup_truck","truck","articulated_lorry","tractor","racing_car","racing_motorcycle","motor_scooter","manual_wheelchair","motorized_wheelchair","auto_rickshaw","bike","scooter","skateboard","roller_skate","busstop","motorway","railway_track","oil_drum","fuelpump","wheel","rotating_light","traffic_light","vertical_traffic_light","octagonal_sign","construction","anchor","ring_buoy","boat","canoe","speedboat","passenger_ship","ferry","motor_boat","ship","airplane","small_airplane","airplane_departure","airplane_arriving","parachute","seat","helicopter","suspension_railway","mountain_cableway","aerial_tramway","satellite","rocket","flying_saucer","bellhop_bell","luggage","hourglass","hourglass_flowing_sand","watch","alarm_clock","stopwatch","timer_clock","mantelpiece_clock","clock12","clock1230","clock1","clock130","clock2","clock230","clock3","clock330","clock4","clock430","clock5","clock530","clock6","clock630","clock7","clock730","clock8","clock830","clock9","clock930","clock10","clock1030","clock11","clock1130","new_moon","waxing_crescent_moon","first_quarter_moon","moon","full_moon","waning_gibbous_moon","last_quarter_moon","waning_crescent_moon","crescent_moon","new_moon_with_face","first_quarter_moon_with_face","last_quarter_moon_with_face","thermometer","sunny","full_moon_with_face","sun_with_face","ringed_planet","star","star2","stars","milky_way","cloud","partly_sunny","thunder_cloud_and_rain","mostly_sunny","barely_sunny","partly_sunny_rain","rain_cloud","snow_cloud","lightning","tornado","fog","wind_blowing_face","cyclone","rainbow","closed_umbrella","umbrella","umbrella_with_rain_drops","umbrella_on_ground","zap","snowflake","snowman","snowman_without_snow","comet","fire","droplet","ocean"]},{"id":"objects","emojis":["eyeglasses","dark_sunglasses","goggles","lab_coat","safety_vest","necktie","shirt","jeans","scarf","gloves","coat","socks","dress","kimono","sari","one-piece_swimsuit","briefs","shorts","bikini","womans_clothes","folding_hand_fan","purse","handbag","pouch","shopping_bags","school_satchel","thong_sandal","mans_shoe","athletic_shoe","hiking_boot","womans_flat_shoe","high_heel","sandal","ballet_shoes","boot","hair_pick","crown","womans_hat","tophat","mortar_board","billed_cap","military_helmet","helmet_with_white_cross","prayer_beads","lipstick","ring","gem","mute","speaker","sound","loud_sound","loudspeaker","mega","postal_horn","bell","no_bell","musical_score","musical_note","notes","studio_microphone","level_slider","control_knobs","microphone","headphones","radio","saxophone","accordion","guitar","musical_keyboard","trumpet","violin","banjo","drum_with_drumsticks","long_drum","maracas","flute","iphone","calling","phone","telephone_receiver","pager","fax","battery","low_battery","electric_plug","computer","desktop_computer","printer","keyboard","three_button_mouse","trackball","minidisc","floppy_disk","cd","dvd","abacus","movie_camera","film_frames","film_projector","clapper","tv","camera","camera_with_flash","video_camera","vhs","mag","mag_right","candle","bulb","flashlight","izakaya_lantern","diya_lamp","notebook_with_decorative_cover","closed_book","book","green_book","blue_book","orange_book","books","notebook","ledger","page_with_curl","scroll","page_facing_up","newspaper","rolled_up_newspaper","bookmark_tabs","bookmark","label","moneybag","coin","yen","dollar","euro","pound","money_with_wings","credit_card","receipt","chart","email","e-mail","incoming_envelope","envelope_with_arrow","outbox_tray","inbox_tray","package","mailbox","mailbox_closed","mailbox_with_mail","mailbox_with_no_mail","postbox","ballot_box_with_ballot","pencil2","black_nib","lower_left_fountain_pen","lower_left_ballpoint_pen","lower_left_paintbrush","lower_left_crayon","memo","briefcase","file_folder","open_file_folder","card_index_dividers","date","calendar","spiral_note_pad","spiral_calendar_pad","card_index","chart_with_upwards_trend","chart_with_downwards_trend","bar_chart","clipboard","pushpin","round_pushpin","paperclip","linked_paperclips","straight_ruler","triangular_ruler","scissors","card_file_box","file_cabinet","wastebasket","lock","unlock","lock_with_ink_pen","closed_lock_with_key","key","old_key","hammer","axe","pick","hammer_and_pick","hammer_and_wrench","dagger_knife","crossed_swords","bomb","boomerang","bow_and_arrow","shield","carpentry_saw","wrench","screwdriver","nut_and_bolt","gear","compression","scales","probing_cane","link","chains","hook","toolbox","magnet","ladder","alembic","test_tube","petri_dish","dna","microscope","telescope","satellite_antenna","syringe","drop_of_blood","pill","adhesive_bandage","crutch","stethoscope","x-ray","door","elevator","mirror","window","bed","couch_and_lamp","chair","toilet","plunger","shower","bathtub","mouse_trap","razor","lotion_bottle","safety_pin","broom","basket","roll_of_paper","bucket","soap","bubbles","toothbrush","sponge","fire_extinguisher","shopping_trolley","smoking","coffin","headstone","funeral_urn","nazar_amulet","hamsa","moyai","placard","identification_card"]},{"id":"symbols","emojis":["atm","put_litter_in_its_place","potable_water","wheelchair","mens","womens","restroom","baby_symbol","wc","passport_control","customs","baggage_claim","left_luggage","warning","children_crossing","no_entry","no_entry_sign","no_bicycles","no_smoking","do_not_litter","non-potable_water","no_pedestrians","no_mobile_phones","underage","radioactive_sign","biohazard_sign","arrow_up","arrow_upper_right","arrow_right","arrow_lower_right","arrow_down","arrow_lower_left","arrow_left","arrow_upper_left","arrow_up_down","left_right_arrow","leftwards_arrow_with_hook","arrow_right_hook","arrow_heading_up","arrow_heading_down","arrows_clockwise","arrows_counterclockwise","back","end","on","soon","top","place_of_worship","atom_symbol","om_symbol","star_of_david","wheel_of_dharma","yin_yang","latin_cross","orthodox_cross","star_and_crescent","peace_symbol","menorah_with_nine_branches","six_pointed_star","khanda","aries","taurus","gemini","cancer","leo","virgo","libra","scorpius","sagittarius","capricorn","aquarius","pisces","ophiuchus","twisted_rightwards_arrows","repeat","repeat_one","arrow_forward","fast_forward","black_right_pointing_double_triangle_with_vertical_bar","black_right_pointing_triangle_with_double_vertical_bar","arrow_backward","rewind","black_left_pointing_double_triangle_with_vertical_bar","arrow_up_small","arrow_double_up","arrow_down_small","arrow_double_down","double_vertical_bar","black_square_for_stop","black_circle_for_record","eject","cinema","low_brightness","high_brightness","signal_strength","wireless","vibration_mode","mobile_phone_off","female_sign","male_sign","transgender_symbol","heavy_multiplication_x","heavy_plus_sign","heavy_minus_sign","heavy_division_sign","heavy_equals_sign","infinity","bangbang","interrobang","question","grey_question","grey_exclamation","exclamation","wavy_dash","currency_exchange","heavy_dollar_sign","medical_symbol","recycle","fleur_de_lis","trident","name_badge","beginner","o","white_check_mark","ballot_box_with_check","heavy_check_mark","x","negative_squared_cross_mark","curly_loop","loop","part_alternation_mark","eight_spoked_asterisk","eight_pointed_black_star","sparkle","copyright","registered","tm","hash","keycap_star","zero","one","two","three","four","five","six","seven","eight","nine","keycap_ten","capital_abcd","abcd","1234","symbols","abc","a","ab","b","cl","cool","free","information_source","id","m","new","ng","o2","ok","parking","sos","up","vs","koko","sa","u6708","u6709","u6307","ideograph_advantage","u5272","u7121","u7981","accept","u7533","u5408","u7a7a","congratulations","secret","u55b6","u6e80","red_circle","large_orange_circle","large_yellow_circle","large_green_circle","large_blue_circle","large_purple_circle","large_brown_circle","black_circle","white_circle","large_red_square","large_orange_square","large_yellow_square","large_green_square","large_blue_square","large_purple_square","large_brown_square","black_large_square","white_large_square","black_medium_square","white_medium_square","black_medium_small_square","white_medium_small_square","black_small_square","white_small_square","large_orange_diamond","large_blue_diamond","small_orange_diamond","small_blue_diamond","small_red_triangle","small_red_triangle_down","diamond_shape_with_a_dot_inside","radio_button","white_square_button","black_square_button"]},{"id":"flags","emojis":["checkered_flag","cn","crossed_flags","de","es","flag-ac","flag-ad","flag-ae","flag-af","flag-ag","flag-ai","flag-al","flag-am","flag-ao","flag-aq","flag-ar","flag-as","flag-at","flag-au","flag-aw","flag-ax","flag-az","flag-ba","flag-bb","flag-bd","flag-be","flag-bf","flag-bg","flag-bh","flag-bi","flag-bj","flag-bl","flag-bm","flag-bn","flag-bo","flag-bq","flag-br","flag-bs","flag-bt","flag-bv","flag-bw","flag-by","flag-bz","flag-ca","flag-cc","flag-cd","flag-cf","flag-cg","flag-ch","flag-ci","flag-ck","flag-cl","flag-cm","flag-co","flag-cp","flag-cr","flag-cu","flag-cv","flag-cw","flag-cx","flag-cy","flag-cz","flag-dg","flag-dj","flag-dk","flag-dm","flag-do","flag-dz","flag-ea","flag-ec","flag-ee","flag-eg","flag-eh","flag-england","flag-er","flag-et","flag-eu","flag-fi","flag-fj","flag-fk","flag-fm","flag-fo","flag-ga","flag-gd","flag-ge","flag-gf","flag-gg","flag-gh","flag-gi","flag-gl","flag-gm","flag-gn","flag-gp","flag-gq","flag-gr","flag-gs","flag-gt","flag-gu","flag-gw","flag-gy","flag-hk","flag-hm","flag-hn","flag-hr","flag-ht","flag-hu","flag-ic","flag-id","flag-ie","flag-il","flag-im","flag-in","flag-io","flag-iq","flag-ir","flag-is","flag-je","flag-jm","flag-jo","flag-ke","flag-kg","flag-kh","flag-ki","flag-km","flag-kn","flag-kp","flag-kw","flag-ky","flag-kz","flag-la","flag-lb","flag-lc","flag-li","flag-lk","flag-lr","flag-ls","flag-lt","flag-lu","flag-lv","flag-ly","flag-ma","flag-mc","flag-md","flag-me","flag-mf","flag-mg","flag-mh","flag-mk","flag-ml","flag-mm","flag-mn","flag-mo","flag-mp","flag-mq","flag-mr","flag-ms","flag-mt","flag-mu","flag-mv","flag-mw","flag-mx","flag-my","flag-mz","flag-na","flag-nc","flag-ne","flag-nf","flag-ng","flag-ni","flag-nl","flag-no","flag-np","flag-nr","flag-nu","flag-nz","flag-om","flag-pa","flag-pe","flag-pf","flag-pg","flag-ph","flag-pk","flag-pl","flag-pm","flag-pn","flag-pr","flag-ps","flag-pt","flag-pw","flag-py","flag-qa","flag-re","flag-ro","flag-rs","flag-rw","flag-sa","flag-sb","flag-sc","flag-scotland","flag-sd","flag-se","flag-sg","flag-sh","flag-si","flag-sj","flag-sk","flag-sl","flag-sm","flag-sn","flag-so","flag-sr","flag-ss","flag-st","flag-sv","flag-sx","flag-sy","flag-sz","flag-ta","flag-tc","flag-td","flag-tf","flag-tg","flag-th","flag-tj","flag-tk","flag-tl","flag-tm","flag-tn","flag-to","flag-tr","flag-tt","flag-tv","flag-tw","flag-tz","flag-ua","flag-ug","flag-um","flag-un","flag-uy","flag-uz","flag-va","flag-vc","flag-ve","flag-vg","flag-vi","flag-vn","flag-vu","flag-wales","flag-wf","flag-ws","flag-xk","flag-ye","flag-yt","flag-za","flag-zm","flag-zw","fr","gb","it","jp","kr","pirate_flag","rainbow-flag","ru","transgender_flag","triangular_flag_on_post","us","waving_black_flag","waving_white_flag"]}]'); +const emojis = /* @__PURE__ */ JSON.parse(`{"100":{"id":"100","name":"Hundred Points","keywords":["100","score","perfect","numbers","century","exam","quiz","test","pass"],"skins":[{"unified":"1f4af","native":"💯"}],"version":1},"1234":{"id":"1234","name":"Input Numbers","keywords":["1234","blue","square","1","2","3","4"],"skins":[{"unified":"1f522","native":"🔢"}],"version":1},"grinning":{"id":"grinning","name":"Grinning Face","emoticons":[":D"],"keywords":["smile","happy","joy",":D","grin"],"skins":[{"unified":"1f600","native":"😀"}],"version":1},"smiley":{"id":"smiley","name":"Grinning Face with Big Eyes","emoticons":[":)","=)","=-)"],"keywords":["smiley","happy","joy","haha",":D",":)","smile","funny"],"skins":[{"unified":"1f603","native":"😃"}],"version":1},"smile":{"id":"smile","name":"Grinning Face with Smiling Eyes","emoticons":[":)","C:","c:",":D",":-D"],"keywords":["smile","happy","joy","funny","haha","laugh","like",":D",":)"],"skins":[{"unified":"1f604","native":"😄"}],"version":1},"grin":{"id":"grin","name":"Beaming Face with Smiling Eyes","keywords":["grin","happy","smile","joy","kawaii"],"skins":[{"unified":"1f601","native":"😁"}],"version":1},"laughing":{"id":"laughing","name":"Grinning Squinting Face","emoticons":[":>",":->"],"keywords":["laughing","satisfied","happy","joy","lol","haha","glad","XD","laugh"],"skins":[{"unified":"1f606","native":"😆"}],"version":1},"sweat_smile":{"id":"sweat_smile","name":"Grinning Face with Sweat","keywords":["smile","hot","happy","laugh","relief"],"skins":[{"unified":"1f605","native":"😅"}],"version":1},"rolling_on_the_floor_laughing":{"id":"rolling_on_the_floor_laughing","name":"Rolling on the Floor Laughing","keywords":["face","lol","haha","rofl"],"skins":[{"unified":"1f923","native":"🤣"}],"version":3},"joy":{"id":"joy","name":"Face with Tears of Joy","keywords":["cry","weep","happy","happytears","haha"],"skins":[{"unified":"1f602","native":"😂"}],"version":1},"slightly_smiling_face":{"id":"slightly_smiling_face","name":"Slightly Smiling Face","emoticons":[":)","(:",":-)"],"keywords":["smile"],"skins":[{"unified":"1f642","native":"🙂"}],"version":1},"upside_down_face":{"id":"upside_down_face","name":"Upside-Down Face","keywords":["upside","down","flipped","silly","smile"],"skins":[{"unified":"1f643","native":"🙃"}],"version":1},"melting_face":{"id":"melting_face","name":"Melting Face","keywords":["hot","heat"],"skins":[{"unified":"1fae0","native":"🫠"}],"version":14},"wink":{"id":"wink","name":"Winking Face","emoticons":[";)",";-)"],"keywords":["wink","happy","mischievous","secret",";)","smile","eye"],"skins":[{"unified":"1f609","native":"😉"}],"version":1},"blush":{"id":"blush","name":"Smiling Face with Smiling Eyes","emoticons":[":)"],"keywords":["blush","smile","happy","flushed","crush","embarrassed","shy","joy"],"skins":[{"unified":"1f60a","native":"😊"}],"version":1},"innocent":{"id":"innocent","name":"Smiling Face with Halo","keywords":["innocent","angel","heaven"],"skins":[{"unified":"1f607","native":"😇"}],"version":1},"smiling_face_with_3_hearts":{"id":"smiling_face_with_3_hearts","name":"Smiling Face with Hearts","keywords":["3","love","like","affection","valentines","infatuation","crush","adore"],"skins":[{"unified":"1f970","native":"🥰"}],"version":11},"heart_eyes":{"id":"heart_eyes","name":"Smiling Face with Heart-Eyes","keywords":["heart","eyes","love","like","affection","valentines","infatuation","crush"],"skins":[{"unified":"1f60d","native":"😍"}],"version":1},"star-struck":{"id":"star-struck","name":"Star-Struck","keywords":["star","struck","grinning","face","with","eyes","smile","starry"],"skins":[{"unified":"1f929","native":"🤩"}],"version":5},"kissing_heart":{"id":"kissing_heart","name":"Face Blowing a Kiss","emoticons":[":*",":-*"],"keywords":["kissing","heart","love","like","affection","valentines","infatuation"],"skins":[{"unified":"1f618","native":"😘"}],"version":1},"kissing":{"id":"kissing","name":"Kissing Face","keywords":["love","like","3","valentines","infatuation","kiss"],"skins":[{"unified":"1f617","native":"😗"}],"version":1},"relaxed":{"id":"relaxed","name":"Smiling Face","keywords":["relaxed","blush","massage","happiness"],"skins":[{"unified":"263a-fe0f","native":"☺️"}],"version":1},"kissing_closed_eyes":{"id":"kissing_closed_eyes","name":"Kissing Face with Closed Eyes","keywords":["love","like","affection","valentines","infatuation","kiss"],"skins":[{"unified":"1f61a","native":"😚"}],"version":1},"kissing_smiling_eyes":{"id":"kissing_smiling_eyes","name":"Kissing Face with Smiling Eyes","keywords":["affection","valentines","infatuation","kiss"],"skins":[{"unified":"1f619","native":"😙"}],"version":1},"smiling_face_with_tear":{"id":"smiling_face_with_tear","name":"Smiling Face with Tear","keywords":["sad","cry","pretend"],"skins":[{"unified":"1f972","native":"🥲"}],"version":13},"yum":{"id":"yum","name":"Face Savoring Food","keywords":["yum","happy","joy","tongue","smile","silly","yummy","nom","delicious","savouring"],"skins":[{"unified":"1f60b","native":"😋"}],"version":1},"stuck_out_tongue":{"id":"stuck_out_tongue","name":"Face with Tongue","emoticons":[":p",":-p",":P",":-P",":b",":-b"],"keywords":["stuck","out","prank","childish","playful","mischievous","smile"],"skins":[{"unified":"1f61b","native":"😛"}],"version":1},"stuck_out_tongue_winking_eye":{"id":"stuck_out_tongue_winking_eye","name":"Winking Face with Tongue","emoticons":[";p",";-p",";b",";-b",";P",";-P"],"keywords":["stuck","out","eye","prank","childish","playful","mischievous","smile","wink"],"skins":[{"unified":"1f61c","native":"😜"}],"version":1},"zany_face":{"id":"zany_face","name":"Zany Face","keywords":["grinning","with","one","large","and","small","eye","goofy","crazy"],"skins":[{"unified":"1f92a","native":"🤪"}],"version":5},"stuck_out_tongue_closed_eyes":{"id":"stuck_out_tongue_closed_eyes","name":"Squinting Face with Tongue","keywords":["stuck","out","closed","eyes","prank","playful","mischievous","smile"],"skins":[{"unified":"1f61d","native":"😝"}],"version":1},"money_mouth_face":{"id":"money_mouth_face","name":"Money-Mouth Face","keywords":["money","mouth","rich","dollar"],"skins":[{"unified":"1f911","native":"🤑"}],"version":1},"hugging_face":{"id":"hugging_face","name":"Hugging Face","keywords":["smile","hug"],"skins":[{"unified":"1f917","native":"🤗"}],"version":1},"face_with_hand_over_mouth":{"id":"face_with_hand_over_mouth","name":"Face with Hand over Mouth","keywords":["smiling","eyes","and","covering","whoops","shock","surprise"],"skins":[{"unified":"1f92d","native":"🤭"}],"version":5},"face_with_open_eyes_and_hand_over_mouth":{"id":"face_with_open_eyes_and_hand_over_mouth","name":"Face with Open Eyes and Hand over Mouth","keywords":["silence","secret","shock","surprise"],"skins":[{"unified":"1fae2","native":"🫢"}],"version":14},"face_with_peeking_eye":{"id":"face_with_peeking_eye","name":"Face with Peeking Eye","keywords":["scared","frightening","embarrassing","shy"],"skins":[{"unified":"1fae3","native":"🫣"}],"version":14},"shushing_face":{"id":"shushing_face","name":"Shushing Face","keywords":["with","finger","covering","closed","lips","quiet","shhh"],"skins":[{"unified":"1f92b","native":"🤫"}],"version":5},"thinking_face":{"id":"thinking_face","name":"Thinking Face","keywords":["hmmm","think","consider"],"skins":[{"unified":"1f914","native":"🤔"}],"version":1},"saluting_face":{"id":"saluting_face","name":"Saluting Face","keywords":["respect","salute"],"skins":[{"unified":"1fae1","native":"🫡"}],"version":14},"zipper_mouth_face":{"id":"zipper_mouth_face","name":"Zipper-Mouth Face","keywords":["zipper","mouth","sealed","secret"],"skins":[{"unified":"1f910","native":"🤐"}],"version":1},"face_with_raised_eyebrow":{"id":"face_with_raised_eyebrow","name":"Face with Raised Eyebrow","keywords":["one","distrust","scepticism","disapproval","disbelief","surprise"],"skins":[{"unified":"1f928","native":"🤨"}],"version":5},"neutral_face":{"id":"neutral_face","name":"Neutral Face","emoticons":[":|",":-|"],"keywords":["indifference","meh",":",""],"skins":[{"unified":"1f610","native":"😐"}],"version":1},"expressionless":{"id":"expressionless","name":"Expressionless Face","emoticons":["-_-"],"keywords":["indifferent","-","","meh","deadpan"],"skins":[{"unified":"1f611","native":"😑"}],"version":1},"no_mouth":{"id":"no_mouth","name":"Face Without Mouth","keywords":["no","hellokitty"],"skins":[{"unified":"1f636","native":"😶"}],"version":1},"dotted_line_face":{"id":"dotted_line_face","name":"Dotted Line Face","keywords":["invisible","lonely","isolation","depression"],"skins":[{"unified":"1fae5","native":"🫥"}],"version":14},"face_in_clouds":{"id":"face_in_clouds","name":"Face in Clouds","keywords":["shower","steam","dream"],"skins":[{"unified":"1f636-200d-1f32b-fe0f","native":"😶‍🌫️"}],"version":13.1},"smirk":{"id":"smirk","name":"Smirking Face","keywords":["smirk","smile","mean","prank","smug","sarcasm"],"skins":[{"unified":"1f60f","native":"😏"}],"version":1},"unamused":{"id":"unamused","name":"Unamused Face","emoticons":[":("],"keywords":["indifference","bored","straight","serious","sarcasm","unimpressed","skeptical","dubious","side","eye"],"skins":[{"unified":"1f612","native":"😒"}],"version":1},"face_with_rolling_eyes":{"id":"face_with_rolling_eyes","name":"Face with Rolling Eyes","keywords":["eyeroll","frustrated"],"skins":[{"unified":"1f644","native":"🙄"}],"version":1},"grimacing":{"id":"grimacing","name":"Grimacing Face","keywords":["grimace","teeth"],"skins":[{"unified":"1f62c","native":"😬"}],"version":1},"face_exhaling":{"id":"face_exhaling","name":"Face Exhaling","keywords":["relieve","relief","tired","sigh"],"skins":[{"unified":"1f62e-200d-1f4a8","native":"😮‍💨"}],"version":13.1},"lying_face":{"id":"lying_face","name":"Lying Face","keywords":["lie","pinocchio"],"skins":[{"unified":"1f925","native":"🤥"}],"version":3},"shaking_face":{"id":"shaking_face","name":"Shaking Face","keywords":["dizzy","shock","blurry","earthquake"],"skins":[{"unified":"1fae8","native":"🫨"}],"version":15},"relieved":{"id":"relieved","name":"Relieved Face","keywords":["relaxed","phew","massage","happiness"],"skins":[{"unified":"1f60c","native":"😌"}],"version":1},"pensive":{"id":"pensive","name":"Pensive Face","keywords":["sad","depressed","upset"],"skins":[{"unified":"1f614","native":"😔"}],"version":1},"sleepy":{"id":"sleepy","name":"Sleepy Face","keywords":["tired","rest","nap"],"skins":[{"unified":"1f62a","native":"😪"}],"version":1},"drooling_face":{"id":"drooling_face","name":"Drooling Face","keywords":[],"skins":[{"unified":"1f924","native":"🤤"}],"version":3},"sleeping":{"id":"sleeping","name":"Sleeping Face","keywords":["tired","sleepy","night","zzz"],"skins":[{"unified":"1f634","native":"😴"}],"version":1},"mask":{"id":"mask","name":"Face with Medical Mask","keywords":["sick","ill","disease","covid"],"skins":[{"unified":"1f637","native":"😷"}],"version":1},"face_with_thermometer":{"id":"face_with_thermometer","name":"Face with Thermometer","keywords":["sick","temperature","cold","fever","covid"],"skins":[{"unified":"1f912","native":"🤒"}],"version":1},"face_with_head_bandage":{"id":"face_with_head_bandage","name":"Face with Head-Bandage","keywords":["head","bandage","injured","clumsy","hurt"],"skins":[{"unified":"1f915","native":"🤕"}],"version":1},"nauseated_face":{"id":"nauseated_face","name":"Nauseated Face","keywords":["vomit","gross","green","sick","throw","up","ill"],"skins":[{"unified":"1f922","native":"🤢"}],"version":3},"face_vomiting":{"id":"face_vomiting","name":"Face Vomiting","keywords":["with","open","mouth","sick"],"skins":[{"unified":"1f92e","native":"🤮"}],"version":5},"sneezing_face":{"id":"sneezing_face","name":"Sneezing Face","keywords":["gesundheit","sneeze","sick","allergy"],"skins":[{"unified":"1f927","native":"🤧"}],"version":3},"hot_face":{"id":"hot_face","name":"Hot Face","keywords":["feverish","heat","red","sweating"],"skins":[{"unified":"1f975","native":"🥵"}],"version":11},"cold_face":{"id":"cold_face","name":"Cold Face","keywords":["blue","freezing","frozen","frostbite","icicles"],"skins":[{"unified":"1f976","native":"🥶"}],"version":11},"woozy_face":{"id":"woozy_face","name":"Woozy Face","keywords":["dizzy","intoxicated","tipsy","wavy"],"skins":[{"unified":"1f974","native":"🥴"}],"version":11},"dizzy_face":{"id":"dizzy_face","name":"Dizzy Face","keywords":["spent","unconscious","xox"],"skins":[{"unified":"1f635","native":"😵"}],"version":1},"face_with_spiral_eyes":{"id":"face_with_spiral_eyes","name":"Face with Spiral Eyes","keywords":["sick","ill","confused","nauseous","nausea"],"skins":[{"unified":"1f635-200d-1f4ab","native":"😵‍💫"}],"version":13.1},"exploding_head":{"id":"exploding_head","name":"Exploding Head","keywords":["shocked","face","with","mind","blown"],"skins":[{"unified":"1f92f","native":"🤯"}],"version":5},"face_with_cowboy_hat":{"id":"face_with_cowboy_hat","name":"Cowboy Hat Face","keywords":["with","cowgirl"],"skins":[{"unified":"1f920","native":"🤠"}],"version":3},"partying_face":{"id":"partying_face","name":"Partying Face","keywords":["celebration","woohoo"],"skins":[{"unified":"1f973","native":"🥳"}],"version":11},"disguised_face":{"id":"disguised_face","name":"Disguised Face","keywords":["pretent","brows","glasses","moustache"],"skins":[{"unified":"1f978","native":"🥸"}],"version":13},"sunglasses":{"id":"sunglasses","name":"Smiling Face with Sunglasses","emoticons":["8)"],"keywords":["cool","smile","summer","beach","sunglass"],"skins":[{"unified":"1f60e","native":"😎"}],"version":1},"nerd_face":{"id":"nerd_face","name":"Nerd Face","keywords":["nerdy","geek","dork"],"skins":[{"unified":"1f913","native":"🤓"}],"version":1},"face_with_monocle":{"id":"face_with_monocle","name":"Face with Monocle","keywords":["stuffy","wealthy"],"skins":[{"unified":"1f9d0","native":"🧐"}],"version":5},"confused":{"id":"confused","name":"Confused Face","emoticons":[":\\\\",":-\\\\",":/",":-/"],"keywords":["indifference","huh","weird","hmmm",":/"],"skins":[{"unified":"1f615","native":"😕"}],"version":1},"face_with_diagonal_mouth":{"id":"face_with_diagonal_mouth","name":"Face with Diagonal Mouth","keywords":["skeptic","confuse","frustrated","indifferent"],"skins":[{"unified":"1fae4","native":"🫤"}],"version":14},"worried":{"id":"worried","name":"Worried Face","keywords":["concern","nervous",":("],"skins":[{"unified":"1f61f","native":"😟"}],"version":1},"slightly_frowning_face":{"id":"slightly_frowning_face","name":"Slightly Frowning Face","keywords":["disappointed","sad","upset"],"skins":[{"unified":"1f641","native":"🙁"}],"version":1},"white_frowning_face":{"id":"white_frowning_face","name":"Frowning Face","keywords":["white","sad","upset","frown"],"skins":[{"unified":"2639-fe0f","native":"☹️"}],"version":1},"open_mouth":{"id":"open_mouth","name":"Face with Open Mouth","emoticons":[":o",":-o",":O",":-O"],"keywords":["surprise","impressed","wow","whoa",":O"],"skins":[{"unified":"1f62e","native":"😮"}],"version":1},"hushed":{"id":"hushed","name":"Hushed Face","keywords":["woo","shh"],"skins":[{"unified":"1f62f","native":"😯"}],"version":1},"astonished":{"id":"astonished","name":"Astonished Face","keywords":["xox","surprised","poisoned"],"skins":[{"unified":"1f632","native":"😲"}],"version":1},"flushed":{"id":"flushed","name":"Flushed Face","keywords":["blush","shy","flattered"],"skins":[{"unified":"1f633","native":"😳"}],"version":1},"pleading_face":{"id":"pleading_face","name":"Pleading Face","keywords":["begging","mercy","cry","tears","sad","grievance"],"skins":[{"unified":"1f97a","native":"🥺"}],"version":11},"face_holding_back_tears":{"id":"face_holding_back_tears","name":"Face Holding Back Tears","keywords":["touched","gratitude","cry"],"skins":[{"unified":"1f979","native":"🥹"}],"version":14},"frowning":{"id":"frowning","name":"Frowning Face with Open Mouth","keywords":["aw","what"],"skins":[{"unified":"1f626","native":"😦"}],"version":1},"anguished":{"id":"anguished","name":"Anguished Face","emoticons":["D:"],"keywords":["stunned","nervous"],"skins":[{"unified":"1f627","native":"😧"}],"version":1},"fearful":{"id":"fearful","name":"Fearful Face","keywords":["scared","terrified","nervous"],"skins":[{"unified":"1f628","native":"😨"}],"version":1},"cold_sweat":{"id":"cold_sweat","name":"Anxious Face with Sweat","keywords":["cold","nervous"],"skins":[{"unified":"1f630","native":"😰"}],"version":1},"disappointed_relieved":{"id":"disappointed_relieved","name":"Sad but Relieved Face","keywords":["disappointed","phew","sweat","nervous"],"skins":[{"unified":"1f625","native":"😥"}],"version":1},"cry":{"id":"cry","name":"Crying Face","emoticons":[":'("],"keywords":["cry","tears","sad","depressed","upset",":'("],"skins":[{"unified":"1f622","native":"😢"}],"version":1},"sob":{"id":"sob","name":"Loudly Crying Face","emoticons":[":'("],"keywords":["sob","cry","tears","sad","upset","depressed"],"skins":[{"unified":"1f62d","native":"😭"}],"version":1},"scream":{"id":"scream","name":"Face Screaming in Fear","keywords":["scream","munch","scared","omg"],"skins":[{"unified":"1f631","native":"😱"}],"version":1},"confounded":{"id":"confounded","name":"Confounded Face","keywords":["confused","sick","unwell","oops",":S"],"skins":[{"unified":"1f616","native":"😖"}],"version":1},"persevere":{"id":"persevere","name":"Persevering Face","keywords":["persevere","sick","no","upset","oops"],"skins":[{"unified":"1f623","native":"😣"}],"version":1},"disappointed":{"id":"disappointed","name":"Disappointed Face","emoticons":["):",":(",":-("],"keywords":["sad","upset","depressed",":("],"skins":[{"unified":"1f61e","native":"😞"}],"version":1},"sweat":{"id":"sweat","name":"Face with Cold Sweat","keywords":["downcast","hot","sad","tired","exercise"],"skins":[{"unified":"1f613","native":"😓"}],"version":1},"weary":{"id":"weary","name":"Weary Face","keywords":["tired","sleepy","sad","frustrated","upset"],"skins":[{"unified":"1f629","native":"😩"}],"version":1},"tired_face":{"id":"tired_face","name":"Tired Face","keywords":["sick","whine","upset","frustrated"],"skins":[{"unified":"1f62b","native":"😫"}],"version":1},"yawning_face":{"id":"yawning_face","name":"Yawning Face","keywords":["tired","sleepy"],"skins":[{"unified":"1f971","native":"🥱"}],"version":12},"triumph":{"id":"triumph","name":"Face with Look of Triumph","keywords":["steam","from","nose","gas","phew","proud","pride"],"skins":[{"unified":"1f624","native":"😤"}],"version":1},"rage":{"id":"rage","name":"Pouting Face","keywords":["rage","angry","mad","hate","despise"],"skins":[{"unified":"1f621","native":"😡"}],"version":1},"angry":{"id":"angry","name":"Angry Face","emoticons":[">:(",">:-("],"keywords":["mad","annoyed","frustrated"],"skins":[{"unified":"1f620","native":"😠"}],"version":1},"face_with_symbols_on_mouth":{"id":"face_with_symbols_on_mouth","name":"Face with Symbols on Mouth","keywords":["serious","covering","swearing","cursing","cussing","profanity","expletive"],"skins":[{"unified":"1f92c","native":"🤬"}],"version":5},"smiling_imp":{"id":"smiling_imp","name":"Smiling Face with Horns","keywords":["imp","devil"],"skins":[{"unified":"1f608","native":"😈"}],"version":1},"imp":{"id":"imp","name":"Imp","keywords":["angry","face","with","horns","devil"],"skins":[{"unified":"1f47f","native":"👿"}],"version":1},"skull":{"id":"skull","name":"Skull","keywords":["dead","skeleton","creepy","death"],"skins":[{"unified":"1f480","native":"💀"}],"version":1},"skull_and_crossbones":{"id":"skull_and_crossbones","name":"Skull and Crossbones","keywords":["poison","danger","deadly","scary","death","pirate","evil"],"skins":[{"unified":"2620-fe0f","native":"☠️"}],"version":1},"hankey":{"id":"hankey","name":"Pile of Poo","keywords":["hankey","poop","shit","shitface","fail","turd"],"skins":[{"unified":"1f4a9","native":"💩"}],"version":1},"clown_face":{"id":"clown_face","name":"Clown Face","keywords":[],"skins":[{"unified":"1f921","native":"🤡"}],"version":3},"japanese_ogre":{"id":"japanese_ogre","name":"Ogre","keywords":["japanese","monster","red","mask","halloween","scary","creepy","devil","demon"],"skins":[{"unified":"1f479","native":"👹"}],"version":1},"japanese_goblin":{"id":"japanese_goblin","name":"Goblin","keywords":["japanese","red","evil","mask","monster","scary","creepy"],"skins":[{"unified":"1f47a","native":"👺"}],"version":1},"ghost":{"id":"ghost","name":"Ghost","keywords":["halloween","spooky","scary"],"skins":[{"unified":"1f47b","native":"👻"}],"version":1},"alien":{"id":"alien","name":"Alien","keywords":["UFO","paul","weird","outer","space"],"skins":[{"unified":"1f47d","native":"👽"}],"version":1},"space_invader":{"id":"space_invader","name":"Alien Monster","keywords":["space","invader","game","arcade","play"],"skins":[{"unified":"1f47e","native":"👾"}],"version":1},"robot_face":{"id":"robot_face","name":"Robot","keywords":["face","computer","machine","bot"],"skins":[{"unified":"1f916","native":"🤖"}],"version":1},"smiley_cat":{"id":"smiley_cat","name":"Grinning Cat","keywords":["smiley","animal","cats","happy","smile"],"skins":[{"unified":"1f63a","native":"😺"}],"version":1},"smile_cat":{"id":"smile_cat","name":"Grinning Cat with Smiling Eyes","keywords":["smile","animal","cats"],"skins":[{"unified":"1f638","native":"😸"}],"version":1},"joy_cat":{"id":"joy_cat","name":"Cat with Tears of Joy","keywords":["animal","cats","haha","happy"],"skins":[{"unified":"1f639","native":"😹"}],"version":1},"heart_eyes_cat":{"id":"heart_eyes_cat","name":"Smiling Cat with Heart-Eyes","keywords":["heart","eyes","animal","love","like","affection","cats","valentines"],"skins":[{"unified":"1f63b","native":"😻"}],"version":1},"smirk_cat":{"id":"smirk_cat","name":"Cat with Wry Smile","keywords":["smirk","animal","cats"],"skins":[{"unified":"1f63c","native":"😼"}],"version":1},"kissing_cat":{"id":"kissing_cat","name":"Kissing Cat","keywords":["animal","cats","kiss"],"skins":[{"unified":"1f63d","native":"😽"}],"version":1},"scream_cat":{"id":"scream_cat","name":"Weary Cat","keywords":["scream","animal","cats","munch","scared"],"skins":[{"unified":"1f640","native":"🙀"}],"version":1},"crying_cat_face":{"id":"crying_cat_face","name":"Crying Cat","keywords":["face","animal","tears","weep","sad","cats","upset","cry"],"skins":[{"unified":"1f63f","native":"😿"}],"version":1},"pouting_cat":{"id":"pouting_cat","name":"Pouting Cat","keywords":["animal","cats"],"skins":[{"unified":"1f63e","native":"😾"}],"version":1},"see_no_evil":{"id":"see_no_evil","name":"See-No-Evil Monkey","keywords":["see","no","evil","animal","nature","haha"],"skins":[{"unified":"1f648","native":"🙈"}],"version":1},"hear_no_evil":{"id":"hear_no_evil","name":"Hear-No-Evil Monkey","keywords":["hear","no","evil","animal","nature"],"skins":[{"unified":"1f649","native":"🙉"}],"version":1},"speak_no_evil":{"id":"speak_no_evil","name":"Speak-No-Evil Monkey","keywords":["speak","no","evil","animal","nature","omg"],"skins":[{"unified":"1f64a","native":"🙊"}],"version":1},"love_letter":{"id":"love_letter","name":"Love Letter","keywords":["email","like","affection","envelope","valentines"],"skins":[{"unified":"1f48c","native":"💌"}],"version":1},"cupid":{"id":"cupid","name":"Heart with Arrow","keywords":["cupid","love","like","affection","valentines"],"skins":[{"unified":"1f498","native":"💘"}],"version":1},"gift_heart":{"id":"gift_heart","name":"Heart with Ribbon","keywords":["gift","love","valentines"],"skins":[{"unified":"1f49d","native":"💝"}],"version":1},"sparkling_heart":{"id":"sparkling_heart","name":"Sparkling Heart","keywords":["love","like","affection","valentines"],"skins":[{"unified":"1f496","native":"💖"}],"version":1},"heartpulse":{"id":"heartpulse","name":"Growing Heart","keywords":["heartpulse","like","love","affection","valentines","pink"],"skins":[{"unified":"1f497","native":"💗"}],"version":1},"heartbeat":{"id":"heartbeat","name":"Beating Heart","keywords":["heartbeat","love","like","affection","valentines","pink"],"skins":[{"unified":"1f493","native":"💓"}],"version":1},"revolving_hearts":{"id":"revolving_hearts","name":"Revolving Hearts","keywords":["love","like","affection","valentines"],"skins":[{"unified":"1f49e","native":"💞"}],"version":1},"two_hearts":{"id":"two_hearts","name":"Two Hearts","keywords":["love","like","affection","valentines","heart"],"skins":[{"unified":"1f495","native":"💕"}],"version":1},"heart_decoration":{"id":"heart_decoration","name":"Heart Decoration","keywords":["purple","square","love","like"],"skins":[{"unified":"1f49f","native":"💟"}],"version":1},"heavy_heart_exclamation_mark_ornament":{"id":"heavy_heart_exclamation_mark_ornament","name":"Heart Exclamation","keywords":["heavy","mark","ornament","decoration","love"],"skins":[{"unified":"2763-fe0f","native":"❣️"}],"version":1},"broken_heart":{"id":"broken_heart","name":"Broken Heart","emoticons":[" 2 && (f1.children = arguments.length > 3 ? $fb96b826c0c5f37a$var$n.call(arguments, 2) : i1), "function" == typeof l3 && null != l3.defaultProps) for (o1 in l3.defaultProps) void 0 === f1[o1] && (f1[o1] = l3.defaultProps[o1]); + return $fb96b826c0c5f37a$var$y(l3, f1, t1, r1, null); +} +function $fb96b826c0c5f37a$var$y(n3, i2, t2, r2, o2) { + var f2 = { + type: n3, + props: i2, + key: t2, + ref: r2, + __k: null, + __: null, + __b: 0, + __e: null, + __d: void 0, + __c: null, + __h: null, + constructor: void 0, + __v: null == o2 ? ++$fb96b826c0c5f37a$var$u : o2 + }; + return null == o2 && null != $fb96b826c0c5f37a$export$41c562ebe57d11e2.vnode && $fb96b826c0c5f37a$export$41c562ebe57d11e2.vnode(f2), f2; +} +function $fb96b826c0c5f37a$export$7d1e3a5e95ceca43() { + return { + current: null + }; +} +function $fb96b826c0c5f37a$export$ffb0004e005737fa(n4) { + return n4.children; +} +function $fb96b826c0c5f37a$export$16fa2f45be04daa8(n5, l4) { + this.props = n5, this.context = l4; +} +function $fb96b826c0c5f37a$var$k(n6, l5) { + if (null == l5) return n6.__ ? $fb96b826c0c5f37a$var$k(n6.__, n6.__.__k.indexOf(n6) + 1) : null; + for (var u3; l5 < n6.__k.length; l5++) if (null != (u3 = n6.__k[l5]) && null != u3.__e) return u3.__e; + return "function" == typeof n6.type ? $fb96b826c0c5f37a$var$k(n6) : null; +} +function $fb96b826c0c5f37a$var$b(n7) { + var l6, u4; + if (null != (n7 = n7.__) && null != n7.__c) { + for (n7.__e = n7.__c.base = null, l6 = 0; l6 < n7.__k.length; l6++) if (null != (u4 = n7.__k[l6]) && null != u4.__e) { + n7.__e = n7.__c.base = u4.__e; + break; + } + return $fb96b826c0c5f37a$var$b(n7); + } +} +function $fb96b826c0c5f37a$var$m(n8) { + (!n8.__d && (n8.__d = true) && $fb96b826c0c5f37a$var$t.push(n8) && !$fb96b826c0c5f37a$var$g.__r++ || $fb96b826c0c5f37a$var$o !== $fb96b826c0c5f37a$export$41c562ebe57d11e2.debounceRendering) && (($fb96b826c0c5f37a$var$o = $fb96b826c0c5f37a$export$41c562ebe57d11e2.debounceRendering) || $fb96b826c0c5f37a$var$r)($fb96b826c0c5f37a$var$g); +} +function $fb96b826c0c5f37a$var$g() { + for (var n9; $fb96b826c0c5f37a$var$g.__r = $fb96b826c0c5f37a$var$t.length; ) n9 = $fb96b826c0c5f37a$var$t.sort(function(n10, l7) { + return n10.__v.__b - l7.__v.__b; + }), $fb96b826c0c5f37a$var$t = [], n9.some(function(n11) { + var l8, u5, i3, t3, r3, o3; + n11.__d && (r3 = (t3 = (l8 = n11).__v).__e, (o3 = l8.__P) && (u5 = [], (i3 = $fb96b826c0c5f37a$var$a({}, t3)).__v = t3.__v + 1, $fb96b826c0c5f37a$var$j(o3, t3, i3, l8.__n, void 0 !== o3.ownerSVGElement, null != t3.__h ? [ + r3 + ] : null, u5, null == r3 ? $fb96b826c0c5f37a$var$k(t3) : r3, t3.__h), $fb96b826c0c5f37a$var$z(u5, t3), t3.__e != r3 && $fb96b826c0c5f37a$var$b(t3))); + }); +} +function $fb96b826c0c5f37a$var$w(n12, l9, u6, i4, t4, r4, o4, f3, s1, a1) { + var h1, v1, p1, _1, b1, m1, g1, w1 = i4 && i4.__k || $fb96b826c0c5f37a$var$c, A1 = w1.length; + for (u6.__k = [], h1 = 0; h1 < l9.length; h1++) if (null != (_1 = u6.__k[h1] = null == (_1 = l9[h1]) || "boolean" == typeof _1 ? null : "string" == typeof _1 || "number" == typeof _1 || "bigint" == typeof _1 ? $fb96b826c0c5f37a$var$y(null, _1, null, null, _1) : Array.isArray(_1) ? $fb96b826c0c5f37a$var$y($fb96b826c0c5f37a$export$ffb0004e005737fa, { + children: _1 + }, null, null, null) : _1.__b > 0 ? $fb96b826c0c5f37a$var$y(_1.type, _1.props, _1.key, null, _1.__v) : _1)) { + if (_1.__ = u6, _1.__b = u6.__b + 1, null === (p1 = w1[h1]) || p1 && _1.key == p1.key && _1.type === p1.type) w1[h1] = void 0; + else for (v1 = 0; v1 < A1; v1++) { + if ((p1 = w1[v1]) && _1.key == p1.key && _1.type === p1.type) { + w1[v1] = void 0; + break; + } + p1 = null; + } + $fb96b826c0c5f37a$var$j(n12, _1, p1 = p1 || $fb96b826c0c5f37a$var$e, t4, r4, o4, f3, s1, a1), b1 = _1.__e, (v1 = _1.ref) && p1.ref != v1 && (g1 || (g1 = []), p1.ref && g1.push(p1.ref, null, _1), g1.push(v1, _1.__c || b1, _1)), null != b1 ? (null == m1 && (m1 = b1), "function" == typeof _1.type && _1.__k === p1.__k ? _1.__d = s1 = $fb96b826c0c5f37a$var$x(_1, s1, n12) : s1 = $fb96b826c0c5f37a$var$P(n12, _1, p1, w1, b1, s1), "function" == typeof u6.type && (u6.__d = s1)) : s1 && p1.__e == s1 && s1.parentNode != n12 && (s1 = $fb96b826c0c5f37a$var$k(p1)); + } + for (u6.__e = m1, h1 = A1; h1--; ) null != w1[h1] && ("function" == typeof u6.type && null != w1[h1].__e && w1[h1].__e == u6.__d && (u6.__d = $fb96b826c0c5f37a$var$k(i4, h1 + 1)), $fb96b826c0c5f37a$var$N(w1[h1], w1[h1])); + if (g1) for (h1 = 0; h1 < g1.length; h1++) $fb96b826c0c5f37a$var$M(g1[h1], g1[++h1], g1[++h1]); +} +function $fb96b826c0c5f37a$var$x(n13, l10, u7) { + for (var i5, t5 = n13.__k, r5 = 0; t5 && r5 < t5.length; r5++) (i5 = t5[r5]) && (i5.__ = n13, l10 = "function" == typeof i5.type ? $fb96b826c0c5f37a$var$x(i5, l10, u7) : $fb96b826c0c5f37a$var$P(u7, i5, i5, t5, i5.__e, l10)); + return l10; +} +function $fb96b826c0c5f37a$export$47e4c5b300681277(n14, l11) { + return l11 = l11 || [], null == n14 || "boolean" == typeof n14 || (Array.isArray(n14) ? n14.some(function(n15) { + $fb96b826c0c5f37a$export$47e4c5b300681277(n15, l11); + }) : l11.push(n14)), l11; +} +function $fb96b826c0c5f37a$var$P(n16, l12, u8, i6, t6, r6) { + var o5, f4, e1; + if (void 0 !== l12.__d) o5 = l12.__d, l12.__d = void 0; + else if (null == u8 || t6 != r6 || null == t6.parentNode) n: if (null == r6 || r6.parentNode !== n16) n16.appendChild(t6), o5 = null; + else { + for (f4 = r6, e1 = 0; (f4 = f4.nextSibling) && e1 < i6.length; e1 += 2) if (f4 == t6) break n; + n16.insertBefore(t6, r6), o5 = r6; + } + return void 0 !== o5 ? o5 : t6.nextSibling; +} +function $fb96b826c0c5f37a$var$C(n17, l13, u9, i7, t7) { + var r7; + for (r7 in u9) "children" === r7 || "key" === r7 || r7 in l13 || $fb96b826c0c5f37a$var$H(n17, r7, null, u9[r7], i7); + for (r7 in l13) t7 && "function" != typeof l13[r7] || "children" === r7 || "key" === r7 || "value" === r7 || "checked" === r7 || u9[r7] === l13[r7] || $fb96b826c0c5f37a$var$H(n17, r7, l13[r7], u9[r7], i7); +} +function $fb96b826c0c5f37a$var$$(n18, l14, u10) { + "-" === l14[0] ? n18.setProperty(l14, u10) : n18[l14] = null == u10 ? "" : "number" != typeof u10 || $fb96b826c0c5f37a$var$s.test(l14) ? u10 : u10 + "px"; +} +function $fb96b826c0c5f37a$var$H(n19, l15, u11, i8, t8) { + var r8; + n: if ("style" === l15) { + if ("string" == typeof u11) n19.style.cssText = u11; + else { + if ("string" == typeof i8 && (n19.style.cssText = i8 = ""), i8) for (l15 in i8) u11 && l15 in u11 || $fb96b826c0c5f37a$var$$(n19.style, l15, ""); + if (u11) for (l15 in u11) i8 && u11[l15] === i8[l15] || $fb96b826c0c5f37a$var$$(n19.style, l15, u11[l15]); + } + } else if ("o" === l15[0] && "n" === l15[1]) r8 = l15 !== (l15 = l15.replace(/Capture$/, "")), l15 = l15.toLowerCase() in n19 ? l15.toLowerCase().slice(2) : l15.slice(2), n19.l || (n19.l = {}), n19.l[l15 + r8] = u11, u11 ? i8 || n19.addEventListener(l15, r8 ? $fb96b826c0c5f37a$var$T : $fb96b826c0c5f37a$var$I, r8) : n19.removeEventListener(l15, r8 ? $fb96b826c0c5f37a$var$T : $fb96b826c0c5f37a$var$I, r8); + else if ("dangerouslySetInnerHTML" !== l15) { + if (t8) l15 = l15.replace(/xlink[H:h]/, "h").replace(/sName$/, "s"); + else if ("href" !== l15 && "list" !== l15 && "form" !== l15 && "tabIndex" !== l15 && "download" !== l15 && l15 in n19) try { + n19[l15] = null == u11 ? "" : u11; + break n; + } catch (n) { + } + "function" == typeof u11 || (null != u11 && (false !== u11 || "a" === l15[0] && "r" === l15[1]) ? n19.setAttribute(l15, u11) : n19.removeAttribute(l15)); + } +} +function $fb96b826c0c5f37a$var$I(n20) { + this.l[n20.type + false]($fb96b826c0c5f37a$export$41c562ebe57d11e2.event ? $fb96b826c0c5f37a$export$41c562ebe57d11e2.event(n20) : n20); +} +function $fb96b826c0c5f37a$var$T(n21) { + this.l[n21.type + true]($fb96b826c0c5f37a$export$41c562ebe57d11e2.event ? $fb96b826c0c5f37a$export$41c562ebe57d11e2.event(n21) : n21); +} +function $fb96b826c0c5f37a$var$j(n22, u12, i9, t9, r9, o6, f5, e2, c1) { + var s2, h2, v2, y1, p2, k1, b2, m2, g2, x1, A2, P1 = u12.type; + if (void 0 !== u12.constructor) return null; + null != i9.__h && (c1 = i9.__h, e2 = u12.__e = i9.__e, u12.__h = null, o6 = [ + e2 + ]), (s2 = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__b) && s2(u12); + try { + n: if ("function" == typeof P1) { + if (m2 = u12.props, g2 = (s2 = P1.contextType) && t9[s2.__c], x1 = s2 ? g2 ? g2.props.value : s2.__ : t9, i9.__c ? b2 = (h2 = u12.__c = i9.__c).__ = h2.__E : ("prototype" in P1 && P1.prototype.render ? u12.__c = h2 = new P1(m2, x1) : (u12.__c = h2 = new $fb96b826c0c5f37a$export$16fa2f45be04daa8(m2, x1), h2.constructor = P1, h2.render = $fb96b826c0c5f37a$var$O), g2 && g2.sub(h2), h2.props = m2, h2.state || (h2.state = {}), h2.context = x1, h2.__n = t9, v2 = h2.__d = true, h2.__h = []), null == h2.__s && (h2.__s = h2.state), null != P1.getDerivedStateFromProps && (h2.__s == h2.state && (h2.__s = $fb96b826c0c5f37a$var$a({}, h2.__s)), $fb96b826c0c5f37a$var$a(h2.__s, P1.getDerivedStateFromProps(m2, h2.__s))), y1 = h2.props, p2 = h2.state, v2) null == P1.getDerivedStateFromProps && null != h2.componentWillMount && h2.componentWillMount(), null != h2.componentDidMount && h2.__h.push(h2.componentDidMount); + else { + if (null == P1.getDerivedStateFromProps && m2 !== y1 && null != h2.componentWillReceiveProps && h2.componentWillReceiveProps(m2, x1), !h2.__e && null != h2.shouldComponentUpdate && false === h2.shouldComponentUpdate(m2, h2.__s, x1) || u12.__v === i9.__v) { + h2.props = m2, h2.state = h2.__s, u12.__v !== i9.__v && (h2.__d = false), h2.__v = u12, u12.__e = i9.__e, u12.__k = i9.__k, u12.__k.forEach(function(n23) { + n23 && (n23.__ = u12); + }), h2.__h.length && f5.push(h2); + break n; + } + null != h2.componentWillUpdate && h2.componentWillUpdate(m2, h2.__s, x1), null != h2.componentDidUpdate && h2.__h.push(function() { + h2.componentDidUpdate(y1, p2, k1); + }); + } + h2.context = x1, h2.props = m2, h2.state = h2.__s, (s2 = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__r) && s2(u12), h2.__d = false, h2.__v = u12, h2.__P = n22, s2 = h2.render(h2.props, h2.state, h2.context), h2.state = h2.__s, null != h2.getChildContext && (t9 = $fb96b826c0c5f37a$var$a($fb96b826c0c5f37a$var$a({}, t9), h2.getChildContext())), v2 || null == h2.getSnapshotBeforeUpdate || (k1 = h2.getSnapshotBeforeUpdate(y1, p2)), A2 = null != s2 && s2.type === $fb96b826c0c5f37a$export$ffb0004e005737fa && null == s2.key ? s2.props.children : s2, $fb96b826c0c5f37a$var$w(n22, Array.isArray(A2) ? A2 : [ + A2 + ], u12, i9, t9, r9, o6, f5, e2, c1), h2.base = u12.__e, u12.__h = null, h2.__h.length && f5.push(h2), b2 && (h2.__E = h2.__ = null), h2.__e = false; + } else null == o6 && u12.__v === i9.__v ? (u12.__k = i9.__k, u12.__e = i9.__e) : u12.__e = $fb96b826c0c5f37a$var$L(i9.__e, u12, i9, t9, r9, o6, f5, c1); + (s2 = $fb96b826c0c5f37a$export$41c562ebe57d11e2.diffed) && s2(u12); + } catch (n24) { + u12.__v = null, (c1 || null != o6) && (u12.__e = e2, u12.__h = !!c1, o6[o6.indexOf(e2)] = null), $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(n24, u12, i9); + } +} +function $fb96b826c0c5f37a$var$z(n25, u13) { + $fb96b826c0c5f37a$export$41c562ebe57d11e2.__c && $fb96b826c0c5f37a$export$41c562ebe57d11e2.__c(u13, n25), n25.some(function(u14) { + try { + n25 = u14.__h, u14.__h = [], n25.some(function(n26) { + n26.call(u14); + }); + } catch (n27) { + $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(n27, u14.__v); + } + }); +} +function $fb96b826c0c5f37a$var$L(l16, u15, i10, t10, r10, o7, f6, c2) { + var s3, a2, v3, y2 = i10.props, p3 = u15.props, d1 = u15.type, _2 = 0; + if ("svg" === d1 && (r10 = true), null != o7) { + for (; _2 < o7.length; _2++) if ((s3 = o7[_2]) && "setAttribute" in s3 == !!d1 && (d1 ? s3.localName === d1 : 3 === s3.nodeType)) { + l16 = s3, o7[_2] = null; + break; + } + } + if (null == l16) { + if (null === d1) return document.createTextNode(p3); + l16 = r10 ? document.createElementNS("http://www.w3.org/2000/svg", d1) : document.createElement(d1, p3.is && p3), o7 = null, c2 = false; + } + if (null === d1) y2 === p3 || c2 && l16.data === p3 || (l16.data = p3); + else { + if (o7 = o7 && $fb96b826c0c5f37a$var$n.call(l16.childNodes), a2 = (y2 = i10.props || $fb96b826c0c5f37a$var$e).dangerouslySetInnerHTML, v3 = p3.dangerouslySetInnerHTML, !c2) { + if (null != o7) for (y2 = {}, _2 = 0; _2 < l16.attributes.length; _2++) y2[l16.attributes[_2].name] = l16.attributes[_2].value; + (v3 || a2) && (v3 && (a2 && v3.__html == a2.__html || v3.__html === l16.innerHTML) || (l16.innerHTML = v3 && v3.__html || "")); + } + if ($fb96b826c0c5f37a$var$C(l16, p3, y2, r10, c2), v3) u15.__k = []; + else if (_2 = u15.props.children, $fb96b826c0c5f37a$var$w(l16, Array.isArray(_2) ? _2 : [ + _2 + ], u15, i10, t10, r10 && "foreignObject" !== d1, o7, f6, o7 ? o7[0] : i10.__k && $fb96b826c0c5f37a$var$k(i10, 0), c2), null != o7) for (_2 = o7.length; _2--; ) null != o7[_2] && $fb96b826c0c5f37a$var$h(o7[_2]); + c2 || ("value" in p3 && void 0 !== (_2 = p3.value) && (_2 !== y2.value || _2 !== l16.value || "progress" === d1 && !_2) && $fb96b826c0c5f37a$var$H(l16, "value", _2, y2.value, false), "checked" in p3 && void 0 !== (_2 = p3.checked) && _2 !== l16.checked && $fb96b826c0c5f37a$var$H(l16, "checked", _2, y2.checked, false)); + } + return l16; +} +function $fb96b826c0c5f37a$var$M(n28, u16, i11) { + try { + "function" == typeof n28 ? n28(u16) : n28.current = u16; + } catch (n29) { + $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(n29, i11); + } +} +function $fb96b826c0c5f37a$var$N(n30, u17, i12) { + var t11, r11; + if ($fb96b826c0c5f37a$export$41c562ebe57d11e2.unmount && $fb96b826c0c5f37a$export$41c562ebe57d11e2.unmount(n30), (t11 = n30.ref) && (t11.current && t11.current !== n30.__e || $fb96b826c0c5f37a$var$M(t11, null, u17)), null != (t11 = n30.__c)) { + if (t11.componentWillUnmount) try { + t11.componentWillUnmount(); + } catch (n31) { + $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(n31, u17); + } + t11.base = t11.__P = null; + } + if (t11 = n30.__k) for (r11 = 0; r11 < t11.length; r11++) t11[r11] && $fb96b826c0c5f37a$var$N(t11[r11], u17, "function" != typeof n30.type); + i12 || null == n30.__e || $fb96b826c0c5f37a$var$h(n30.__e), n30.__e = n30.__d = void 0; +} +function $fb96b826c0c5f37a$var$O(n32, l, u18) { + return this.constructor(n32, u18); +} +function $fb96b826c0c5f37a$export$b3890eb0ae9dca99(u19, i13, t12) { + var r12, o8, f7; + $fb96b826c0c5f37a$export$41c562ebe57d11e2.__ && $fb96b826c0c5f37a$export$41c562ebe57d11e2.__(u19, i13), o8 = (r12 = "function" == typeof t12) ? null : t12 && t12.__k || i13.__k, f7 = [], $fb96b826c0c5f37a$var$j(i13, u19 = (!r12 && t12 || i13).__k = $fb96b826c0c5f37a$export$c8a8987d4410bf2d($fb96b826c0c5f37a$export$ffb0004e005737fa, null, [ + u19 + ]), o8 || $fb96b826c0c5f37a$var$e, $fb96b826c0c5f37a$var$e, void 0 !== i13.ownerSVGElement, !r12 && t12 ? [ + t12 + ] : o8 ? null : i13.firstChild ? $fb96b826c0c5f37a$var$n.call(i13.childNodes) : null, f7, !r12 && t12 ? t12 : o8 ? o8.__e : i13.firstChild, r12), $fb96b826c0c5f37a$var$z(f7, u19); +} +$fb96b826c0c5f37a$var$n = $fb96b826c0c5f37a$var$c.slice, $fb96b826c0c5f37a$export$41c562ebe57d11e2 = { + __e: function(n39, l22) { + for (var u23, i16, t14; l22 = l22.__; ) if ((u23 = l22.__c) && !u23.__) try { + if ((i16 = u23.constructor) && null != i16.getDerivedStateFromError && (u23.setState(i16.getDerivedStateFromError(n39)), t14 = u23.__d), null != u23.componentDidCatch && (u23.componentDidCatch(n39), t14 = u23.__d), t14) return u23.__E = u23; + } catch (l23) { + n39 = l23; + } + throw n39; + } +}, $fb96b826c0c5f37a$var$u = 0, $fb96b826c0c5f37a$export$16fa2f45be04daa8.prototype.setState = function(n41, l24) { + var u24; + u24 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = $fb96b826c0c5f37a$var$a({}, this.state), "function" == typeof n41 && (n41 = n41($fb96b826c0c5f37a$var$a({}, u24), this.props)), n41 && $fb96b826c0c5f37a$var$a(u24, n41), null != n41 && this.__v && (l24 && this.__h.push(l24), $fb96b826c0c5f37a$var$m(this)); +}, $fb96b826c0c5f37a$export$16fa2f45be04daa8.prototype.forceUpdate = function(n42) { + this.__v && (this.__e = true, n42 && this.__h.push(n42), $fb96b826c0c5f37a$var$m(this)); +}, $fb96b826c0c5f37a$export$16fa2f45be04daa8.prototype.render = $fb96b826c0c5f37a$export$ffb0004e005737fa, $fb96b826c0c5f37a$var$t = [], $fb96b826c0c5f37a$var$r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, $fb96b826c0c5f37a$var$g.__r = 0; +var $bd9dd35321b03dd4$var$o = 0; +function $bd9dd35321b03dd4$export$34b9dba7ce09269b(_1, e1, n, t, f) { + var l, s, u = {}; + for (s in e1) "ref" == s ? l = e1[s] : u[s] = e1[s]; + var a = { + type: _1, + props: u, + key: n, + ref: l, + __k: null, + __: null, + __b: 0, + __e: null, + __d: void 0, + __c: null, + __h: null, + constructor: void 0, + __v: --$bd9dd35321b03dd4$var$o, + __source: t, + __self: f + }; + if ("function" == typeof _1 && (l = _1.defaultProps)) for (s in l) void 0 === u[s] && (u[s] = l[s]); + return $fb96b826c0c5f37a$export$41c562ebe57d11e2.vnode && $fb96b826c0c5f37a$export$41c562ebe57d11e2.vnode(a), a; +} +function $f72b75cf796873c7$var$set(key, value) { + try { + window.localStorage[`emoji-mart.${key}`] = JSON.stringify(value); + } catch (error) { + } +} +function $f72b75cf796873c7$var$get(key) { + try { + const value = window.localStorage[`emoji-mart.${key}`]; + if (value) return JSON.parse(value); + } catch (error) { + } +} +var $f72b75cf796873c7$export$2e2bcd8739ae039 = { + set: $f72b75cf796873c7$var$set, + get: $f72b75cf796873c7$var$get +}; +const $c84d045dcc34faf5$var$CACHE = /* @__PURE__ */ new Map(); +const $c84d045dcc34faf5$var$VERSIONS = [ + { + v: 15, + emoji: "🫨" + }, + { + v: 14, + emoji: "🫠" + }, + { + v: 13.1, + emoji: "😶‍🌫️" + }, + { + v: 13, + emoji: "🥸" + }, + { + v: 12.1, + emoji: "🧑‍🦰" + }, + { + v: 12, + emoji: "🥱" + }, + { + v: 11, + emoji: "🥰" + }, + { + v: 5, + emoji: "🤩" + }, + { + v: 4, + emoji: "👱‍♀️" + }, + { + v: 3, + emoji: "🤣" + }, + { + v: 2, + emoji: "👋🏻" + }, + { + v: 1, + emoji: "🙃" + } +]; +function $c84d045dcc34faf5$var$latestVersion() { + for (const { v, emoji } of $c84d045dcc34faf5$var$VERSIONS) { + if ($c84d045dcc34faf5$var$isSupported(emoji)) return v; + } +} +function $c84d045dcc34faf5$var$noCountryFlags() { + if ($c84d045dcc34faf5$var$isSupported("🇨🇦")) return false; + return true; +} +function $c84d045dcc34faf5$var$isSupported(emoji) { + if ($c84d045dcc34faf5$var$CACHE.has(emoji)) return $c84d045dcc34faf5$var$CACHE.get(emoji); + const supported = $c84d045dcc34faf5$var$isEmojiSupported(emoji); + $c84d045dcc34faf5$var$CACHE.set(emoji, supported); + return supported; +} +const $c84d045dcc34faf5$var$isEmojiSupported = (() => { + let ctx = null; + try { + if (!navigator.userAgent.includes("jsdom")) ctx = document.createElement("canvas").getContext("2d", { + willReadFrequently: true + }); + } catch { + } + if (!ctx) return () => false; + const CANVAS_HEIGHT = 25; + const CANVAS_WIDTH = 20; + const textSize = Math.floor(CANVAS_HEIGHT / 2); + ctx.font = textSize + "px Arial, Sans-Serif"; + ctx.textBaseline = "top"; + ctx.canvas.width = CANVAS_WIDTH * 2; + ctx.canvas.height = CANVAS_HEIGHT; + return (unicode) => { + ctx.clearRect(0, 0, CANVAS_WIDTH * 2, CANVAS_HEIGHT); + ctx.fillStyle = "#FF0000"; + ctx.fillText(unicode, 0, 22); + ctx.fillStyle = "#0000FF"; + ctx.fillText(unicode, CANVAS_WIDTH, 22); + const a = ctx.getImageData(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT).data; + const count = a.length; + let i = 0; + for (; i < count && !a[i + 3]; i += 4) ; + if (i >= count) return false; + const x = CANVAS_WIDTH + i / 4 % CANVAS_WIDTH; + const y = Math.floor(i / 4 / CANVAS_WIDTH); + const b = ctx.getImageData(x, y, 1, 1).data; + if (a[i] !== b[0] || a[i + 2] !== b[2]) return false; + if (ctx.measureText(unicode).width >= CANVAS_WIDTH) return false; + return true; + }; +})(); +var $c84d045dcc34faf5$export$2e2bcd8739ae039 = { + latestVersion: $c84d045dcc34faf5$var$latestVersion, + noCountryFlags: $c84d045dcc34faf5$var$noCountryFlags +}; +const $b22cfd0a55410b4f$var$DEFAULTS = [ + "+1", + "grinning", + "kissing_heart", + "heart_eyes", + "laughing", + "stuck_out_tongue_winking_eye", + "sweat_smile", + "joy", + "scream", + "disappointed", + "unamused", + "weary", + "sob", + "sunglasses", + "heart" +]; +let $b22cfd0a55410b4f$var$Index = null; +function $b22cfd0a55410b4f$var$add(emoji) { + $b22cfd0a55410b4f$var$Index || ($b22cfd0a55410b4f$var$Index = $f72b75cf796873c7$export$2e2bcd8739ae039.get("frequently") || {}); + const emojiId = emoji.id || emoji; + if (!emojiId) return; + $b22cfd0a55410b4f$var$Index[emojiId] || ($b22cfd0a55410b4f$var$Index[emojiId] = 0); + $b22cfd0a55410b4f$var$Index[emojiId] += 1; + $f72b75cf796873c7$export$2e2bcd8739ae039.set("last", emojiId); + $f72b75cf796873c7$export$2e2bcd8739ae039.set("frequently", $b22cfd0a55410b4f$var$Index); +} +function $b22cfd0a55410b4f$var$get({ maxFrequentRows, perLine }) { + if (!maxFrequentRows) return []; + $b22cfd0a55410b4f$var$Index || ($b22cfd0a55410b4f$var$Index = $f72b75cf796873c7$export$2e2bcd8739ae039.get("frequently")); + let emojiIds = []; + if (!$b22cfd0a55410b4f$var$Index) { + $b22cfd0a55410b4f$var$Index = {}; + for (let i in $b22cfd0a55410b4f$var$DEFAULTS.slice(0, perLine)) { + const emojiId = $b22cfd0a55410b4f$var$DEFAULTS[i]; + $b22cfd0a55410b4f$var$Index[emojiId] = perLine - i; + emojiIds.push(emojiId); + } + return emojiIds; + } + const max = maxFrequentRows * perLine; + const last = $f72b75cf796873c7$export$2e2bcd8739ae039.get("last"); + for (let emojiId in $b22cfd0a55410b4f$var$Index) emojiIds.push(emojiId); + emojiIds.sort((a, b) => { + const aScore = $b22cfd0a55410b4f$var$Index[b]; + const bScore = $b22cfd0a55410b4f$var$Index[a]; + if (aScore == bScore) return a.localeCompare(b); + return aScore - bScore; + }); + if (emojiIds.length > max) { + const removedIds = emojiIds.slice(max); + emojiIds = emojiIds.slice(0, max); + for (let removedId of removedIds) { + if (removedId == last) continue; + delete $b22cfd0a55410b4f$var$Index[removedId]; + } + if (last && emojiIds.indexOf(last) == -1) { + delete $b22cfd0a55410b4f$var$Index[emojiIds[emojiIds.length - 1]]; + emojiIds.splice(-1, 1, last); + } + $f72b75cf796873c7$export$2e2bcd8739ae039.set("frequently", $b22cfd0a55410b4f$var$Index); + } + return emojiIds; +} +var $b22cfd0a55410b4f$export$2e2bcd8739ae039 = { + add: $b22cfd0a55410b4f$var$add, + get: $b22cfd0a55410b4f$var$get, + DEFAULTS: $b22cfd0a55410b4f$var$DEFAULTS +}; +var $8d50d93417ef682a$exports = {}; +$8d50d93417ef682a$exports = JSON.parse('{"search":"Search","search_no_results_1":"Oh no!","search_no_results_2":"That emoji couldn’t be found","pick":"Pick an emoji…","add_custom":"Add custom emoji","categories":{"activity":"Activity","custom":"Custom","flags":"Flags","foods":"Food & Drink","frequent":"Frequently used","nature":"Animals & Nature","objects":"Objects","people":"Smileys & People","places":"Travel & Places","search":"Search Results","symbols":"Symbols"},"skins":{"1":"Default","2":"Light","3":"Medium-Light","4":"Medium","5":"Medium-Dark","6":"Dark","choose":"Choose default skin tone"}}'); +var $b247ea80b67298d5$export$2e2bcd8739ae039 = { + autoFocus: { + value: false + }, + dynamicWidth: { + value: false + }, + emojiButtonColors: { + value: null + }, + emojiButtonRadius: { + value: "100%" + }, + emojiButtonSize: { + value: 36 + }, + emojiSize: { + value: 24 + }, + emojiVersion: { + value: 15, + choices: [ + 1, + 2, + 3, + 4, + 5, + 11, + 12, + 12.1, + 13, + 13.1, + 14, + 15 + ] + }, + exceptEmojis: { + value: [] + }, + icons: { + value: "auto", + choices: [ + "auto", + "outline", + "solid" + ] + }, + locale: { + value: "en", + choices: [ + "en", + "ar", + "be", + "cs", + "de", + "es", + "fa", + "fi", + "fr", + "hi", + "it", + "ja", + "ko", + "nl", + "pl", + "pt", + "ru", + "sa", + "tr", + "uk", + "vi", + "zh" + ] + }, + maxFrequentRows: { + value: 4 + }, + navPosition: { + value: "top", + choices: [ + "top", + "bottom", + "none" + ] + }, + noCountryFlags: { + value: false + }, + noResultsEmoji: { + value: null + }, + perLine: { + value: 9 + }, + previewEmoji: { + value: null + }, + previewPosition: { + value: "bottom", + choices: [ + "top", + "bottom", + "none" + ] + }, + searchPosition: { + value: "sticky", + choices: [ + "sticky", + "static", + "none" + ] + }, + set: { + value: "native", + choices: [ + "native", + "apple", + "facebook", + "google", + "twitter" + ] + }, + skin: { + value: 1, + choices: [ + 1, + 2, + 3, + 4, + 5, + 6 + ] + }, + skinTonePosition: { + value: "preview", + choices: [ + "preview", + "search", + "none" + ] + }, + theme: { + value: "auto", + choices: [ + "auto", + "light", + "dark" + ] + }, + // Data + categories: null, + categoryIcons: null, + custom: null, + data: null, + i18n: null, + // Callbacks + getImageURL: null, + getSpritesheetURL: null, + onAddCustomEmoji: null, + onClickOutside: null, + onEmojiSelect: null, + // Deprecated + stickySearch: { + deprecated: true, + value: true + } +}; +let $7adb23b0109cc36a$export$dbe3113d60765c1a = null; +let $7adb23b0109cc36a$export$2d0294657ab35f1b = null; +const $7adb23b0109cc36a$var$fetchCache = {}; +async function $7adb23b0109cc36a$var$fetchJSON(src) { + if ($7adb23b0109cc36a$var$fetchCache[src]) return $7adb23b0109cc36a$var$fetchCache[src]; + const response = await fetch(src); + const json = await response.json(); + $7adb23b0109cc36a$var$fetchCache[src] = json; + return json; +} +let $7adb23b0109cc36a$var$promise = null; +let $7adb23b0109cc36a$var$initCallback = null; +let $7adb23b0109cc36a$var$initialized = false; +function $7adb23b0109cc36a$export$2cd8252107eb640b(options, { caller } = {}) { + $7adb23b0109cc36a$var$promise || ($7adb23b0109cc36a$var$promise = new Promise((resolve) => { + $7adb23b0109cc36a$var$initCallback = resolve; + })); + if (options) $7adb23b0109cc36a$var$_init(options); + else if (caller && !$7adb23b0109cc36a$var$initialized) console.warn(`\`${caller}\` requires data to be initialized first. Promise will be pending until \`init\` is called.`); + return $7adb23b0109cc36a$var$promise; +} +async function $7adb23b0109cc36a$var$_init(props) { + $7adb23b0109cc36a$var$initialized = true; + let { emojiVersion, set, locale } = props; + emojiVersion || (emojiVersion = $b247ea80b67298d5$export$2e2bcd8739ae039.emojiVersion.value); + set || (set = $b247ea80b67298d5$export$2e2bcd8739ae039.set.value); + locale || (locale = $b247ea80b67298d5$export$2e2bcd8739ae039.locale.value); + if (!$7adb23b0109cc36a$export$2d0294657ab35f1b) { + $7adb23b0109cc36a$export$2d0294657ab35f1b = (typeof props.data === "function" ? await props.data() : props.data) || await $7adb23b0109cc36a$var$fetchJSON(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/sets/${emojiVersion}/${set}.json`); + $7adb23b0109cc36a$export$2d0294657ab35f1b.emoticons = {}; + $7adb23b0109cc36a$export$2d0294657ab35f1b.natives = {}; + $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.unshift({ + id: "frequent", + emojis: [] + }); + for (const alias in $7adb23b0109cc36a$export$2d0294657ab35f1b.aliases) { + const emojiId = $7adb23b0109cc36a$export$2d0294657ab35f1b.aliases[alias]; + const emoji = $7adb23b0109cc36a$export$2d0294657ab35f1b.emojis[emojiId]; + if (!emoji) continue; + emoji.aliases || (emoji.aliases = []); + emoji.aliases.push(alias); + } + $7adb23b0109cc36a$export$2d0294657ab35f1b.originalCategories = $7adb23b0109cc36a$export$2d0294657ab35f1b.categories; + } else $7adb23b0109cc36a$export$2d0294657ab35f1b.categories = $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.filter((c) => { + const isCustom = !!c.name; + if (!isCustom) return true; + return false; + }); + $7adb23b0109cc36a$export$dbe3113d60765c1a = (typeof props.i18n === "function" ? await props.i18n() : props.i18n) || (locale == "en" ? /* @__PURE__ */ $parcel$interopDefault($8d50d93417ef682a$exports) : await $7adb23b0109cc36a$var$fetchJSON(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/i18n/${locale}.json`)); + if (props.custom) for (let i in props.custom) { + i = parseInt(i); + const category = props.custom[i]; + const prevCategory = props.custom[i - 1]; + if (!category.emojis || !category.emojis.length) continue; + category.id || (category.id = `custom_${i + 1}`); + category.name || (category.name = $7adb23b0109cc36a$export$dbe3113d60765c1a.categories.custom); + if (prevCategory && !category.icon) category.target = prevCategory.target || prevCategory; + $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.push(category); + for (const emoji of category.emojis) $7adb23b0109cc36a$export$2d0294657ab35f1b.emojis[emoji.id] = emoji; + } + if (props.categories) $7adb23b0109cc36a$export$2d0294657ab35f1b.categories = $7adb23b0109cc36a$export$2d0294657ab35f1b.originalCategories.filter((c) => { + return props.categories.indexOf(c.id) != -1; + }).sort((c1, c2) => { + const i1 = props.categories.indexOf(c1.id); + const i2 = props.categories.indexOf(c2.id); + return i1 - i2; + }); + let latestVersionSupport = null; + let noCountryFlags = null; + if (set == "native") { + latestVersionSupport = $c84d045dcc34faf5$export$2e2bcd8739ae039.latestVersion(); + noCountryFlags = props.noCountryFlags || $c84d045dcc34faf5$export$2e2bcd8739ae039.noCountryFlags(); + } + let categoryIndex = $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.length; + let resetSearchIndex = false; + while (categoryIndex--) { + const category = $7adb23b0109cc36a$export$2d0294657ab35f1b.categories[categoryIndex]; + if (category.id == "frequent") { + let { maxFrequentRows, perLine } = props; + maxFrequentRows = maxFrequentRows >= 0 ? maxFrequentRows : $b247ea80b67298d5$export$2e2bcd8739ae039.maxFrequentRows.value; + perLine || (perLine = $b247ea80b67298d5$export$2e2bcd8739ae039.perLine.value); + category.emojis = $b22cfd0a55410b4f$export$2e2bcd8739ae039.get({ + maxFrequentRows, + perLine + }); + } + if (!category.emojis || !category.emojis.length) { + $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.splice(categoryIndex, 1); + continue; + } + const { categoryIcons } = props; + if (categoryIcons) { + const icon = categoryIcons[category.id]; + if (icon && !category.icon) category.icon = icon; + } + let emojiIndex = category.emojis.length; + while (emojiIndex--) { + const emojiId = category.emojis[emojiIndex]; + const emoji = emojiId.id ? emojiId : $7adb23b0109cc36a$export$2d0294657ab35f1b.emojis[emojiId]; + const ignore = () => { + category.emojis.splice(emojiIndex, 1); + }; + if (!emoji || props.exceptEmojis && props.exceptEmojis.includes(emoji.id)) { + ignore(); + continue; + } + if (latestVersionSupport && emoji.version > latestVersionSupport) { + ignore(); + continue; + } + if (noCountryFlags && category.id == "flags") { + if (!$e6eae5155b87f591$export$bcb25aa587e9cb13.includes(emoji.id)) { + ignore(); + continue; + } + } + if (!emoji.search) { + resetSearchIndex = true; + emoji.search = "," + [ + [ + emoji.id, + false + ], + [ + emoji.name, + true + ], + [ + emoji.keywords, + false + ], + [ + emoji.emoticons, + false + ] + ].map(([strings, split]) => { + if (!strings) return; + return (Array.isArray(strings) ? strings : [ + strings + ]).map((string) => { + return (split ? string.split(/[-|_|\s]+/) : [ + string + ]).map((s) => s.toLowerCase()); + }).flat(); + }).flat().filter((a) => a && a.trim()).join(","); + if (emoji.emoticons) for (const emoticon of emoji.emoticons) { + if ($7adb23b0109cc36a$export$2d0294657ab35f1b.emoticons[emoticon]) continue; + $7adb23b0109cc36a$export$2d0294657ab35f1b.emoticons[emoticon] = emoji.id; + } + let skinIndex = 0; + for (const skin of emoji.skins) { + if (!skin) continue; + skinIndex++; + const { native } = skin; + if (native) { + $7adb23b0109cc36a$export$2d0294657ab35f1b.natives[native] = emoji.id; + emoji.search += `,${native}`; + } + const skinShortcodes = skinIndex == 1 ? "" : `:skin-tone-${skinIndex}:`; + skin.shortcodes = `:${emoji.id}:${skinShortcodes}`; + } + } + } + } + if (resetSearchIndex) $c4d155af13ad4d4b$export$2e2bcd8739ae039.reset(); + $7adb23b0109cc36a$var$initCallback(); +} +function $7adb23b0109cc36a$export$75fe5f91d452f94b(props, defaultProps, element) { + props || (props = {}); + const _props = {}; + for (let k in defaultProps) _props[k] = $7adb23b0109cc36a$export$88c9ddb45cea7241(k, props, defaultProps, element); + return _props; +} +function $7adb23b0109cc36a$export$88c9ddb45cea7241(propName, props, defaultProps, element) { + const defaults = defaultProps[propName]; + let value = element && element.getAttribute(propName) || (props[propName] != null && props[propName] != void 0 ? props[propName] : null); + if (!defaults) return value; + if (value != null && defaults.value && typeof defaults.value != typeof value) { + if (typeof defaults.value == "boolean") value = value == "false" ? false : true; + else value = defaults.value.constructor(value); + } + if (defaults.transform && value) value = defaults.transform(value); + if (value == null || defaults.choices && defaults.choices.indexOf(value) == -1) value = defaults.value; + return value; +} +const $c4d155af13ad4d4b$var$SHORTCODES_REGEX = /^(?:\:([^\:]+)\:)(?:\:skin-tone-(\d)\:)?$/; +let $c4d155af13ad4d4b$var$Pool = null; +function $c4d155af13ad4d4b$var$get(emojiId) { + if (emojiId.id) return emojiId; + return $7adb23b0109cc36a$export$2d0294657ab35f1b.emojis[emojiId] || $7adb23b0109cc36a$export$2d0294657ab35f1b.emojis[$7adb23b0109cc36a$export$2d0294657ab35f1b.aliases[emojiId]] || $7adb23b0109cc36a$export$2d0294657ab35f1b.emojis[$7adb23b0109cc36a$export$2d0294657ab35f1b.natives[emojiId]]; +} +function $c4d155af13ad4d4b$var$reset() { + $c4d155af13ad4d4b$var$Pool = null; +} +async function $c4d155af13ad4d4b$var$search(value, { maxResults, caller } = {}) { + if (!value || !value.trim().length) return null; + maxResults || (maxResults = 90); + await $7adb23b0109cc36a$export$2cd8252107eb640b(null, { + caller: caller || "SearchIndex.search" + }); + const values = value.toLowerCase().replace(/(\w)-/, "$1 ").split(/[\s|,]+/).filter((word, i, words) => { + return word.trim() && words.indexOf(word) == i; + }); + if (!values.length) return; + let pool = $c4d155af13ad4d4b$var$Pool || ($c4d155af13ad4d4b$var$Pool = Object.values($7adb23b0109cc36a$export$2d0294657ab35f1b.emojis)); + let results, scores; + for (const value1 of values) { + if (!pool.length) break; + results = []; + scores = {}; + for (const emoji of pool) { + if (!emoji.search) continue; + const score = emoji.search.indexOf(`,${value1}`); + if (score == -1) continue; + results.push(emoji); + scores[emoji.id] || (scores[emoji.id] = 0); + scores[emoji.id] += emoji.id == value1 ? 0 : score + 1; + } + pool = results; + } + if (results.length < 2) return results; + results.sort((a, b) => { + const aScore = scores[a.id]; + const bScore = scores[b.id]; + if (aScore == bScore) return a.id.localeCompare(b.id); + return aScore - bScore; + }); + if (results.length > maxResults) results = results.slice(0, maxResults); + return results; +} +var $c4d155af13ad4d4b$export$2e2bcd8739ae039 = { + search: $c4d155af13ad4d4b$var$search, + get: $c4d155af13ad4d4b$var$get, + reset: $c4d155af13ad4d4b$var$reset, + SHORTCODES_REGEX: $c4d155af13ad4d4b$var$SHORTCODES_REGEX +}; +const $e6eae5155b87f591$export$bcb25aa587e9cb13 = [ + "checkered_flag", + "crossed_flags", + "pirate_flag", + "rainbow-flag", + "transgender_flag", + "triangular_flag_on_post", + "waving_black_flag", + "waving_white_flag" +]; +function $693b183b0a78708f$export$9cb4719e2e525b7a(a, b) { + return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((val, index) => val == b[index]); +} +async function $693b183b0a78708f$export$e772c8ff12451969(frames = 1) { + for (let _ in [ + ...Array(frames).keys() + ]) await new Promise(requestAnimationFrame); +} +function $693b183b0a78708f$export$d10ac59fbe52a745(emoji, { skinIndex = 0 } = {}) { + const skin = emoji.skins[skinIndex] || (() => { + skinIndex = 0; + return emoji.skins[skinIndex]; + })(); + const emojiData = { + id: emoji.id, + name: emoji.name, + native: skin.native, + unified: skin.unified, + keywords: emoji.keywords, + shortcodes: skin.shortcodes || emoji.shortcodes + }; + if (emoji.skins.length > 1) emojiData.skin = skinIndex + 1; + if (skin.src) emojiData.src = skin.src; + if (emoji.aliases && emoji.aliases.length) emojiData.aliases = emoji.aliases; + if (emoji.emoticons && emoji.emoticons.length) emojiData.emoticons = emoji.emoticons; + return emojiData; +} +async function $693b183b0a78708f$export$5ef5574deca44bc0(nativeString) { + const results = await $c4d155af13ad4d4b$export$2e2bcd8739ae039.search(nativeString, { + maxResults: 1, + caller: "getEmojiDataFromNative" + }); + if (!results || !results.length) return null; + const emoji = results[0]; + let skinIndex = 0; + for (let skin of emoji.skins) { + if (skin.native == nativeString) break; + skinIndex++; + } + return $693b183b0a78708f$export$d10ac59fbe52a745(emoji, { + skinIndex + }); +} +const $fcccfb36ed0cde68$var$categories = { + activity: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M12 0C5.373 0 0 5.372 0 12c0 6.627 5.373 12 12 12 6.628 0 12-5.373 12-12 0-6.628-5.372-12-12-12m9.949 11H17.05c.224-2.527 1.232-4.773 1.968-6.113A9.966 9.966 0 0 1 21.949 11M13 11V2.051a9.945 9.945 0 0 1 4.432 1.564c-.858 1.491-2.156 4.22-2.392 7.385H13zm-2 0H8.961c-.238-3.165-1.536-5.894-2.393-7.385A9.95 9.95 0 0 1 11 2.051V11zm0 2v8.949a9.937 9.937 0 0 1-4.432-1.564c.857-1.492 2.155-4.221 2.393-7.385H11zm4.04 0c.236 3.164 1.534 5.893 2.392 7.385A9.92 9.92 0 0 1 13 21.949V13h2.04zM4.982 4.887C5.718 6.227 6.726 8.473 6.951 11h-4.9a9.977 9.977 0 0 1 2.931-6.113M2.051 13h4.9c-.226 2.527-1.233 4.771-1.969 6.113A9.972 9.972 0 0 1 2.051 13m16.967 6.113c-.735-1.342-1.744-3.586-1.968-6.113h4.899a9.961 9.961 0 0 1-2.931 6.113" + }) + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M16.17 337.5c0 44.98 7.565 83.54 13.98 107.9C35.22 464.3 50.46 496 174.9 496c9.566 0 19.59-.4707 29.84-1.271L17.33 307.3C16.53 317.6 16.17 327.7 16.17 337.5zM495.8 174.5c0-44.98-7.565-83.53-13.98-107.9c-4.688-17.54-18.34-31.23-36.04-35.95C435.5 27.91 392.9 16 337 16c-9.564 0-19.59 .4707-29.84 1.271l187.5 187.5C495.5 194.4 495.8 184.3 495.8 174.5zM26.77 248.8l236.3 236.3c142-36.1 203.9-150.4 222.2-221.1L248.9 26.87C106.9 62.96 45.07 177.2 26.77 248.8zM256 335.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L164.7 283.3C161.6 280.2 160 276.1 160 271.1c0-8.529 6.865-16 16-16c4.095 0 8.189 1.562 11.31 4.688l64.01 64C254.4 327.8 256 331.9 256 335.1zM304 287.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L212.7 235.3C209.6 232.2 208 228.1 208 223.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01C302.5 279.8 304 283.9 304 287.1zM256 175.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01c3.125 3.125 4.688 7.219 4.688 11.31c0 9.133-7.468 16-16 16c-4.094 0-8.189-1.562-11.31-4.688l-64.01-64.01C257.6 184.2 256 180.1 256 175.1z" + }) + }) + }, + custom: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 448 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M417.1 368c-5.937 10.27-16.69 16-27.75 16c-5.422 0-10.92-1.375-15.97-4.281L256 311.4V448c0 17.67-14.33 32-31.1 32S192 465.7 192 448V311.4l-118.3 68.29C68.67 382.6 63.17 384 57.75 384c-11.06 0-21.81-5.734-27.75-16c-8.828-15.31-3.594-34.88 11.72-43.72L159.1 256L41.72 187.7C26.41 178.9 21.17 159.3 29.1 144C36.63 132.5 49.26 126.7 61.65 128.2C65.78 128.7 69.88 130.1 73.72 132.3L192 200.6V64c0-17.67 14.33-32 32-32S256 46.33 256 64v136.6l118.3-68.29c3.838-2.213 7.939-3.539 12.07-4.051C398.7 126.7 411.4 132.5 417.1 144c8.828 15.31 3.594 34.88-11.72 43.72L288 256l118.3 68.28C421.6 333.1 426.8 352.7 417.1 368z" + }) + }), + flags: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M0 0l6.084 24H8L1.916 0zM21 5h-4l-1-4H4l3 12h3l1 4h13L21 5zM6.563 3h7.875l2 8H8.563l-2-8zm8.832 10l-2.856 1.904L12.063 13h3.332zM19 13l-1.5-6h1.938l2 8H16l3-2z" + }) + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M64 496C64 504.8 56.75 512 48 512h-32C7.25 512 0 504.8 0 496V32c0-17.75 14.25-32 32-32s32 14.25 32 32V496zM476.3 0c-6.365 0-13.01 1.35-19.34 4.233c-45.69 20.86-79.56 27.94-107.8 27.94c-59.96 0-94.81-31.86-163.9-31.87C160.9 .3055 131.6 4.867 96 15.75v350.5c32-9.984 59.87-14.1 84.85-14.1c73.63 0 124.9 31.78 198.6 31.78c31.91 0 68.02-5.971 111.1-23.09C504.1 355.9 512 344.4 512 332.1V30.73C512 11.1 495.3 0 476.3 0z" + }) + }) + }, + foods: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M17 4.978c-1.838 0-2.876.396-3.68.934.513-1.172 1.768-2.934 4.68-2.934a1 1 0 0 0 0-2c-2.921 0-4.629 1.365-5.547 2.512-.064.078-.119.162-.18.244C11.73 1.838 10.798.023 9.207.023 8.579.022 7.85.306 7 .978 5.027 2.54 5.329 3.902 6.492 4.999 3.609 5.222 0 7.352 0 12.969c0 4.582 4.961 11.009 9 11.009 1.975 0 2.371-.486 3-1 .629.514 1.025 1 3 1 4.039 0 9-6.418 9-11 0-5.953-4.055-8-7-8M8.242 2.546c.641-.508.943-.523.965-.523.426.169.975 1.405 1.357 3.055-1.527-.629-2.741-1.352-2.98-1.846.059-.112.241-.356.658-.686M15 21.978c-1.08 0-1.21-.109-1.559-.402l-.176-.146c-.367-.302-.816-.452-1.266-.452s-.898.15-1.266.452l-.176.146c-.347.292-.477.402-1.557.402-2.813 0-7-5.389-7-9.009 0-5.823 4.488-5.991 5-5.991 1.939 0 2.484.471 3.387 1.251l.323.276a1.995 1.995 0 0 0 2.58 0l.323-.276c.902-.78 1.447-1.251 3.387-1.251.512 0 5 .168 5 6 0 3.617-4.187 9-7 9" + }) + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M481.9 270.1C490.9 279.1 496 291.3 496 304C496 316.7 490.9 328.9 481.9 337.9C472.9 346.9 460.7 352 448 352H64C51.27 352 39.06 346.9 30.06 337.9C21.06 328.9 16 316.7 16 304C16 291.3 21.06 279.1 30.06 270.1C39.06 261.1 51.27 256 64 256H448C460.7 256 472.9 261.1 481.9 270.1zM475.3 388.7C478.3 391.7 480 395.8 480 400V416C480 432.1 473.3 449.3 461.3 461.3C449.3 473.3 432.1 480 416 480H96C79.03 480 62.75 473.3 50.75 461.3C38.74 449.3 32 432.1 32 416V400C32 395.8 33.69 391.7 36.69 388.7C39.69 385.7 43.76 384 48 384H464C468.2 384 472.3 385.7 475.3 388.7zM50.39 220.8C45.93 218.6 42.03 215.5 38.97 211.6C35.91 207.7 33.79 203.2 32.75 198.4C31.71 193.5 31.8 188.5 32.99 183.7C54.98 97.02 146.5 32 256 32C365.5 32 457 97.02 479 183.7C480.2 188.5 480.3 193.5 479.2 198.4C478.2 203.2 476.1 207.7 473 211.6C469.1 215.5 466.1 218.6 461.6 220.8C457.2 222.9 452.3 224 447.3 224H64.67C59.73 224 54.84 222.9 50.39 220.8zM372.7 116.7C369.7 119.7 368 123.8 368 128C368 131.2 368.9 134.3 370.7 136.9C372.5 139.5 374.1 141.6 377.9 142.8C380.8 143.1 384 144.3 387.1 143.7C390.2 143.1 393.1 141.6 395.3 139.3C397.6 137.1 399.1 134.2 399.7 131.1C400.3 128 399.1 124.8 398.8 121.9C397.6 118.1 395.5 116.5 392.9 114.7C390.3 112.9 387.2 111.1 384 111.1C379.8 111.1 375.7 113.7 372.7 116.7V116.7zM244.7 84.69C241.7 87.69 240 91.76 240 96C240 99.16 240.9 102.3 242.7 104.9C244.5 107.5 246.1 109.6 249.9 110.8C252.8 111.1 256 112.3 259.1 111.7C262.2 111.1 265.1 109.6 267.3 107.3C269.6 105.1 271.1 102.2 271.7 99.12C272.3 96.02 271.1 92.8 270.8 89.88C269.6 86.95 267.5 84.45 264.9 82.7C262.3 80.94 259.2 79.1 256 79.1C251.8 79.1 247.7 81.69 244.7 84.69V84.69zM116.7 116.7C113.7 119.7 112 123.8 112 128C112 131.2 112.9 134.3 114.7 136.9C116.5 139.5 118.1 141.6 121.9 142.8C124.8 143.1 128 144.3 131.1 143.7C134.2 143.1 137.1 141.6 139.3 139.3C141.6 137.1 143.1 134.2 143.7 131.1C144.3 128 143.1 124.8 142.8 121.9C141.6 118.1 139.5 116.5 136.9 114.7C134.3 112.9 131.2 111.1 128 111.1C123.8 111.1 119.7 113.7 116.7 116.7L116.7 116.7z" + }) + }) + }, + frequent: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M13 4h-2l-.001 7H9v2h2v2h2v-2h4v-2h-4z" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10" + }) + ] + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512zM232 256C232 264 236 271.5 242.7 275.1L338.7 339.1C349.7 347.3 364.6 344.3 371.1 333.3C379.3 322.3 376.3 307.4 365.3 300L280 243.2V120C280 106.7 269.3 96 255.1 96C242.7 96 231.1 106.7 231.1 120L232 256z" + }) + }) + }, + nature: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M15.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 15.5 8M8.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 8.5 8" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M18.933 0h-.027c-.97 0-2.138.787-3.018 1.497-1.274-.374-2.612-.51-3.887-.51-1.285 0-2.616.133-3.874.517C7.245.79 6.069 0 5.093 0h-.027C3.352 0 .07 2.67.002 7.026c-.039 2.479.276 4.238 1.04 5.013.254.258.882.677 1.295.882.191 3.177.922 5.238 2.536 6.38.897.637 2.187.949 3.2 1.102C8.04 20.6 8 20.795 8 21c0 1.773 2.35 3 4 3 1.648 0 4-1.227 4-3 0-.201-.038-.393-.072-.586 2.573-.385 5.435-1.877 5.925-7.587.396-.22.887-.568 1.104-.788.763-.774 1.079-2.534 1.04-5.013C23.929 2.67 20.646 0 18.933 0M3.223 9.135c-.237.281-.837 1.155-.884 1.238-.15-.41-.368-1.349-.337-3.291.051-3.281 2.478-4.972 3.091-5.031.256.015.731.27 1.265.646-1.11 1.171-2.275 2.915-2.352 5.125-.133.546-.398.858-.783 1.313M12 22c-.901 0-1.954-.693-2-1 0-.654.475-1.236 1-1.602V20a1 1 0 1 0 2 0v-.602c.524.365 1 .947 1 1.602-.046.307-1.099 1-2 1m3-3.48v.02a4.752 4.752 0 0 0-1.262-1.02c1.092-.516 2.239-1.334 2.239-2.217 0-1.842-1.781-2.195-3.977-2.195-2.196 0-3.978.354-3.978 2.195 0 .883 1.148 1.701 2.238 2.217A4.8 4.8 0 0 0 9 18.539v-.025c-1-.076-2.182-.281-2.973-.842-1.301-.92-1.838-3.045-1.853-6.478l.023-.041c.496-.826 1.49-1.45 1.804-3.102 0-2.047 1.357-3.631 2.362-4.522C9.37 3.178 10.555 3 11.948 3c1.447 0 2.685.192 3.733.57 1 .9 2.316 2.465 2.316 4.48.313 1.651 1.307 2.275 1.803 3.102.035.058.068.117.102.178-.059 5.967-1.949 7.01-4.902 7.19m6.628-8.202c-.037-.065-.074-.13-.113-.195a7.587 7.587 0 0 0-.739-.987c-.385-.455-.648-.768-.782-1.313-.076-2.209-1.241-3.954-2.353-5.124.531-.376 1.004-.63 1.261-.647.636.071 3.044 1.764 3.096 5.031.027 1.81-.347 3.218-.37 3.235" + }) + ] + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 576 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M332.7 19.85C334.6 8.395 344.5 0 356.1 0C363.6 0 370.6 3.52 375.1 9.502L392 32H444.1C456.8 32 469.1 37.06 478.1 46.06L496 64H552C565.3 64 576 74.75 576 88V112C576 156.2 540.2 192 496 192H426.7L421.6 222.5L309.6 158.5L332.7 19.85zM448 64C439.2 64 432 71.16 432 80C432 88.84 439.2 96 448 96C456.8 96 464 88.84 464 80C464 71.16 456.8 64 448 64zM416 256.1V480C416 497.7 401.7 512 384 512H352C334.3 512 320 497.7 320 480V364.8C295.1 377.1 268.8 384 240 384C211.2 384 184 377.1 160 364.8V480C160 497.7 145.7 512 128 512H96C78.33 512 64 497.7 64 480V249.8C35.23 238.9 12.64 214.5 4.836 183.3L.9558 167.8C-3.331 150.6 7.094 133.2 24.24 128.1C41.38 124.7 58.76 135.1 63.05 152.2L66.93 167.8C70.49 182 83.29 191.1 97.97 191.1H303.8L416 256.1z" + }) + }) + }, + objects: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M12 0a9 9 0 0 0-5 16.482V21s2.035 3 5 3 5-3 5-3v-4.518A9 9 0 0 0 12 0zm0 2c3.86 0 7 3.141 7 7s-3.14 7-7 7-7-3.141-7-7 3.14-7 7-7zM9 17.477c.94.332 1.946.523 3 .523s2.06-.19 3-.523v.834c-.91.436-1.925.689-3 .689a6.924 6.924 0 0 1-3-.69v-.833zm.236 3.07A8.854 8.854 0 0 0 12 21c.965 0 1.888-.167 2.758-.451C14.155 21.173 13.153 22 12 22c-1.102 0-2.117-.789-2.764-1.453z" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M14.745 12.449h-.004c-.852-.024-1.188-.858-1.577-1.824-.421-1.061-.703-1.561-1.182-1.566h-.009c-.481 0-.783.497-1.235 1.537-.436.982-.801 1.811-1.636 1.791l-.276-.043c-.565-.171-.853-.691-1.284-1.794-.125-.313-.202-.632-.27-.913-.051-.213-.127-.53-.195-.634C7.067 9.004 7.039 9 6.99 9A1 1 0 0 1 7 7h.01c1.662.017 2.015 1.373 2.198 2.134.486-.981 1.304-2.058 2.797-2.075 1.531.018 2.28 1.153 2.731 2.141l.002-.008C14.944 8.424 15.327 7 16.979 7h.032A1 1 0 1 1 17 9h-.011c-.149.076-.256.474-.319.709a6.484 6.484 0 0 1-.311.951c-.429.973-.79 1.789-1.614 1.789" + }) + ] + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 384 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M112.1 454.3c0 6.297 1.816 12.44 5.284 17.69l17.14 25.69c5.25 7.875 17.17 14.28 26.64 14.28h61.67c9.438 0 21.36-6.401 26.61-14.28l17.08-25.68c2.938-4.438 5.348-12.37 5.348-17.7L272 415.1h-160L112.1 454.3zM191.4 .0132C89.44 .3257 16 82.97 16 175.1c0 44.38 16.44 84.84 43.56 115.8c16.53 18.84 42.34 58.23 52.22 91.45c.0313 .25 .0938 .5166 .125 .7823h160.2c.0313-.2656 .0938-.5166 .125-.7823c9.875-33.22 35.69-72.61 52.22-91.45C351.6 260.8 368 220.4 368 175.1C368 78.61 288.9-.2837 191.4 .0132zM192 96.01c-44.13 0-80 35.89-80 79.1C112 184.8 104.8 192 96 192S80 184.8 80 176c0-61.76 50.25-111.1 112-111.1c8.844 0 16 7.159 16 16S200.8 96.01 192 96.01z" + }) + }) + }, + people: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M8 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 8 7M16 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 16 7M15.232 15c-.693 1.195-1.87 2-3.349 2-1.477 0-2.655-.805-3.347-2H15m3-2H6a6 6 0 1 0 12 0" + }) + ] + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256zM256 432C332.1 432 396.2 382 415.2 314.1C419.1 300.4 407.8 288 393.6 288H118.4C104.2 288 92.92 300.4 96.76 314.1C115.8 382 179.9 432 256 432V432zM176.4 160C158.7 160 144.4 174.3 144.4 192C144.4 209.7 158.7 224 176.4 224C194 224 208.4 209.7 208.4 192C208.4 174.3 194 160 176.4 160zM336.4 224C354 224 368.4 209.7 368.4 192C368.4 174.3 354 160 336.4 160C318.7 160 304.4 174.3 304.4 192C304.4 209.7 318.7 224 336.4 224z" + }) + }) + }, + places: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M6.5 12C5.122 12 4 13.121 4 14.5S5.122 17 6.5 17 9 15.879 9 14.5 7.878 12 6.5 12m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5M17.5 12c-1.378 0-2.5 1.121-2.5 2.5s1.122 2.5 2.5 2.5 2.5-1.121 2.5-2.5-1.122-2.5-2.5-2.5m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M22.482 9.494l-1.039-.346L21.4 9h.6c.552 0 1-.439 1-.992 0-.006-.003-.008-.003-.008H23c0-1-.889-2-1.984-2h-.642l-.731-1.717C19.262 3.012 18.091 2 16.764 2H7.236C5.909 2 4.738 3.012 4.357 4.283L3.626 6h-.642C1.889 6 1 7 1 8h.003S1 8.002 1 8.008C1 8.561 1.448 9 2 9h.6l-.043.148-1.039.346a2.001 2.001 0 0 0-1.359 2.097l.751 7.508a1 1 0 0 0 .994.901H3v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h6v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h1.096a.999.999 0 0 0 .994-.901l.751-7.508a2.001 2.001 0 0 0-1.359-2.097M6.273 4.857C6.402 4.43 6.788 4 7.236 4h9.527c.448 0 .834.43.963.857L19.313 9H4.688l1.585-4.143zM7 21H5v-1h2v1zm12 0h-2v-1h2v1zm2.189-3H2.811l-.662-6.607L3 11h18l.852.393L21.189 18z" + }) + ] + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M39.61 196.8L74.8 96.29C88.27 57.78 124.6 32 165.4 32H346.6C387.4 32 423.7 57.78 437.2 96.29L472.4 196.8C495.6 206.4 512 229.3 512 256V448C512 465.7 497.7 480 480 480H448C430.3 480 416 465.7 416 448V400H96V448C96 465.7 81.67 480 64 480H32C14.33 480 0 465.7 0 448V256C0 229.3 16.36 206.4 39.61 196.8V196.8zM109.1 192H402.9L376.8 117.4C372.3 104.6 360.2 96 346.6 96H165.4C151.8 96 139.7 104.6 135.2 117.4L109.1 192zM96 256C78.33 256 64 270.3 64 288C64 305.7 78.33 320 96 320C113.7 320 128 305.7 128 288C128 270.3 113.7 256 96 256zM416 320C433.7 320 448 305.7 448 288C448 270.3 433.7 256 416 256C398.3 256 384 270.3 384 288C384 305.7 398.3 320 416 320z" + }) + }) + }, + symbols: { + outline: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 24 24", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M0 0h11v2H0zM4 11h3V6h4V4H0v2h4zM15.5 17c1.381 0 2.5-1.116 2.5-2.493s-1.119-2.493-2.5-2.493S13 13.13 13 14.507 14.119 17 15.5 17m0-2.986c.276 0 .5.222.5.493 0 .272-.224.493-.5.493s-.5-.221-.5-.493.224-.493.5-.493M21.5 19.014c-1.381 0-2.5 1.116-2.5 2.493S20.119 24 21.5 24s2.5-1.116 2.5-2.493-1.119-2.493-2.5-2.493m0 2.986a.497.497 0 0 1-.5-.493c0-.271.224-.493.5-.493s.5.222.5.493a.497.497 0 0 1-.5.493M22 13l-9 9 1.513 1.5 8.99-9.009zM17 11c2.209 0 4-1.119 4-2.5V2s.985-.161 1.498.949C23.01 4.055 23 6 23 6s1-1.119 1-3.135C24-.02 21 0 21 0h-2v6.347A5.853 5.853 0 0 0 17 6c-2.209 0-4 1.119-4 2.5s1.791 2.5 4 2.5M10.297 20.482l-1.475-1.585a47.54 47.54 0 0 1-1.442 1.129c-.307-.288-.989-1.016-2.045-2.183.902-.836 1.479-1.466 1.729-1.892s.376-.871.376-1.336c0-.592-.273-1.178-.818-1.759-.546-.581-1.329-.871-2.349-.871-1.008 0-1.79.293-2.344.879-.556.587-.832 1.181-.832 1.784 0 .813.419 1.748 1.256 2.805-.847.614-1.444 1.208-1.794 1.784a3.465 3.465 0 0 0-.523 1.833c0 .857.308 1.56.924 2.107.616.549 1.423.823 2.42.823 1.173 0 2.444-.379 3.813-1.137L8.235 24h2.819l-2.09-2.383 1.333-1.135zm-6.736-6.389a1.02 1.02 0 0 1 .73-.286c.31 0 .559.085.747.254a.849.849 0 0 1 .283.659c0 .518-.419 1.112-1.257 1.784-.536-.651-.805-1.231-.805-1.742a.901.901 0 0 1 .302-.669M3.74 22c-.427 0-.778-.116-1.057-.349-.279-.232-.418-.487-.418-.766 0-.594.509-1.288 1.527-2.083.968 1.134 1.717 1.946 2.248 2.438-.921.507-1.686.76-2.3.76" + }) + }), + solid: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 512 512", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M500.3 7.251C507.7 13.33 512 22.41 512 31.1V175.1C512 202.5 483.3 223.1 447.1 223.1C412.7 223.1 383.1 202.5 383.1 175.1C383.1 149.5 412.7 127.1 447.1 127.1V71.03L351.1 90.23V207.1C351.1 234.5 323.3 255.1 287.1 255.1C252.7 255.1 223.1 234.5 223.1 207.1C223.1 181.5 252.7 159.1 287.1 159.1V63.1C287.1 48.74 298.8 35.61 313.7 32.62L473.7 .6198C483.1-1.261 492.9 1.173 500.3 7.251H500.3zM74.66 303.1L86.5 286.2C92.43 277.3 102.4 271.1 113.1 271.1H174.9C185.6 271.1 195.6 277.3 201.5 286.2L213.3 303.1H239.1C266.5 303.1 287.1 325.5 287.1 351.1V463.1C287.1 490.5 266.5 511.1 239.1 511.1H47.1C21.49 511.1-.0019 490.5-.0019 463.1V351.1C-.0019 325.5 21.49 303.1 47.1 303.1H74.66zM143.1 359.1C117.5 359.1 95.1 381.5 95.1 407.1C95.1 434.5 117.5 455.1 143.1 455.1C170.5 455.1 191.1 434.5 191.1 407.1C191.1 381.5 170.5 359.1 143.1 359.1zM440.3 367.1H496C502.7 367.1 508.6 372.1 510.1 378.4C513.3 384.6 511.6 391.7 506.5 396L378.5 508C372.9 512.1 364.6 513.3 358.6 508.9C352.6 504.6 350.3 496.6 353.3 489.7L391.7 399.1H336C329.3 399.1 323.4 395.9 321 389.6C318.7 383.4 320.4 376.3 325.5 371.1L453.5 259.1C459.1 255 467.4 254.7 473.4 259.1C479.4 263.4 481.6 271.4 478.7 278.3L440.3 367.1zM116.7 219.1L19.85 119.2C-8.112 90.26-6.614 42.31 24.85 15.34C51.82-8.137 93.26-3.642 118.2 21.83L128.2 32.32L137.7 21.83C162.7-3.642 203.6-8.137 231.6 15.34C262.6 42.31 264.1 90.26 236.1 119.2L139.7 219.1C133.2 225.6 122.7 225.6 116.7 219.1H116.7z" + }) + }) + } +}; +const $fcccfb36ed0cde68$var$search = { + loupe: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 20 20", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M12.9 14.32a8 8 0 1 1 1.41-1.41l5.35 5.33-1.42 1.42-5.33-5.34zM8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z" + }) + }), + delete: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("svg", { + xmlns: "http://www.w3.org/2000/svg", + viewBox: "0 0 20 20", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("path", { + d: "M10 8.586L2.929 1.515 1.515 2.929 8.586 10l-7.071 7.071 1.414 1.414L10 11.414l7.071 7.071 1.414-1.414L11.414 10l7.071-7.071-1.414-1.414L10 8.586z" + }) + }) +}; +var $fcccfb36ed0cde68$export$2e2bcd8739ae039 = { + categories: $fcccfb36ed0cde68$var$categories, + search: $fcccfb36ed0cde68$var$search +}; +function $254755d3f438722f$export$2e2bcd8739ae039(props) { + let { id, skin, emoji } = props; + if (props.shortcodes) { + const matches = props.shortcodes.match($c4d155af13ad4d4b$export$2e2bcd8739ae039.SHORTCODES_REGEX); + if (matches) { + id = matches[1]; + if (matches[2]) skin = matches[2]; + } + } + emoji || (emoji = $c4d155af13ad4d4b$export$2e2bcd8739ae039.get(id || props.native)); + if (!emoji) return props.fallback; + const emojiSkin = emoji.skins[skin - 1] || emoji.skins[0]; + const imageSrc = emojiSkin.src || (props.set != "native" && !props.spritesheet ? typeof props.getImageURL === "function" ? props.getImageURL(props.set, emojiSkin.unified) : `https://cdn.jsdelivr.net/npm/emoji-datasource-${props.set}@15.0.1/img/${props.set}/64/${emojiSkin.unified}.png` : void 0); + const spritesheetSrc = typeof props.getSpritesheetURL === "function" ? props.getSpritesheetURL(props.set) : `https://cdn.jsdelivr.net/npm/emoji-datasource-${props.set}@15.0.1/img/${props.set}/sheets-256/64.png`; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + class: "emoji-mart-emoji", + "data-emoji-set": props.set, + children: imageSrc ? /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("img", { + style: { + maxWidth: props.size || "1em", + maxHeight: props.size || "1em", + display: "inline-block" + }, + alt: emojiSkin.native || emojiSkin.shortcodes, + src: imageSrc + }) : props.set == "native" ? /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + style: { + fontSize: props.size, + fontFamily: '"EmojiMart", "Segoe UI Emoji", "Segoe UI Symbol", "Segoe UI", "Apple Color Emoji", "Twemoji Mozilla", "Noto Color Emoji", "Android Emoji"' + }, + children: emojiSkin.native + }) : /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + style: { + display: "block", + width: props.size, + height: props.size, + backgroundImage: `url(${spritesheetSrc})`, + backgroundSize: `${100 * $7adb23b0109cc36a$export$2d0294657ab35f1b.sheet.cols}% ${100 * $7adb23b0109cc36a$export$2d0294657ab35f1b.sheet.rows}%`, + backgroundPosition: `${100 / ($7adb23b0109cc36a$export$2d0294657ab35f1b.sheet.cols - 1) * emojiSkin.x}% ${100 / ($7adb23b0109cc36a$export$2d0294657ab35f1b.sheet.rows - 1) * emojiSkin.y}%` + } + }) + }); +} +const $6f57cc9cd54c5aaa$var$WindowHTMLElement = typeof window !== "undefined" && window.HTMLElement ? window.HTMLElement : Object; +class $6f57cc9cd54c5aaa$export$2e2bcd8739ae039 extends $6f57cc9cd54c5aaa$var$WindowHTMLElement { + static get observedAttributes() { + return Object.keys(this.Props); + } + update(props = {}) { + for (let k in props) this.attributeChangedCallback(k, null, props[k]); + } + attributeChangedCallback(attr, _, newValue) { + if (!this.component) return; + const value = $7adb23b0109cc36a$export$88c9ddb45cea7241(attr, { + [attr]: newValue + }, this.constructor.Props, this); + if (this.component.componentWillReceiveProps) this.component.componentWillReceiveProps({ + [attr]: value + }); + else { + this.component.props[attr] = value; + this.component.forceUpdate(); + } + } + disconnectedCallback() { + this.disconnected = true; + if (this.component && this.component.unregister) this.component.unregister(); + } + constructor(props = {}) { + super(); + this.props = props; + if (props.parent || props.ref) { + let ref = null; + const parent = props.parent || (ref = props.ref && props.ref.current); + if (ref) ref.innerHTML = ""; + if (parent) parent.appendChild(this); + } + } +} +class $26f27c338a96b1a6$export$2e2bcd8739ae039 extends $6f57cc9cd54c5aaa$export$2e2bcd8739ae039 { + setShadow() { + this.attachShadow({ + mode: "open" + }); + } + injectStyles(styles) { + if (!styles) return; + const style = document.createElement("style"); + style.textContent = styles; + this.shadowRoot.insertBefore(style, this.shadowRoot.firstChild); + } + constructor(props, { styles } = {}) { + super(props); + this.setShadow(); + this.injectStyles(styles); + } +} +var $3d90f6e46fb2dd47$export$2e2bcd8739ae039 = { + fallback: "", + id: "", + native: "", + shortcodes: "", + size: { + value: "", + transform: (value) => { + if (!/\D/.test(value)) return `${value}px`; + return value; + } + }, + // Shared + set: $b247ea80b67298d5$export$2e2bcd8739ae039.set, + skin: $b247ea80b67298d5$export$2e2bcd8739ae039.skin +}; +class $331b4160623139bf$export$2e2bcd8739ae039 extends $6f57cc9cd54c5aaa$export$2e2bcd8739ae039 { + async connectedCallback() { + const props = $7adb23b0109cc36a$export$75fe5f91d452f94b(this.props, $3d90f6e46fb2dd47$export$2e2bcd8739ae039, this); + props.element = this; + props.ref = (component) => { + this.component = component; + }; + await $7adb23b0109cc36a$export$2cd8252107eb640b(); + if (this.disconnected) return; + $fb96b826c0c5f37a$export$b3890eb0ae9dca99(/* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b($254755d3f438722f$export$2e2bcd8739ae039, { + ...props + }), this); + } + constructor(props) { + super(props); + } +} +$c770c458706daa72$export$2e2bcd8739ae039($331b4160623139bf$export$2e2bcd8739ae039, "Props", $3d90f6e46fb2dd47$export$2e2bcd8739ae039); +if (typeof customElements !== "undefined" && !customElements.get("em-emoji")) customElements.define("em-emoji", $331b4160623139bf$export$2e2bcd8739ae039); +var $1a9a8ef576b7773d$var$r, $1a9a8ef576b7773d$var$i = [], $1a9a8ef576b7773d$var$c = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__b, $1a9a8ef576b7773d$var$f = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__r, $1a9a8ef576b7773d$var$e = $fb96b826c0c5f37a$export$41c562ebe57d11e2.diffed, $1a9a8ef576b7773d$var$a = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__c, $1a9a8ef576b7773d$var$v = $fb96b826c0c5f37a$export$41c562ebe57d11e2.unmount; +function $1a9a8ef576b7773d$var$x() { + var t6; + for ($1a9a8ef576b7773d$var$i.sort(function(n11, t7) { + return n11.__v.__b - t7.__v.__b; + }); t6 = $1a9a8ef576b7773d$var$i.pop(); ) if (t6.__P) try { + t6.__H.__h.forEach($1a9a8ef576b7773d$var$g), t6.__H.__h.forEach($1a9a8ef576b7773d$var$j), t6.__H.__h = []; + } catch (u4) { + t6.__H.__h = [], $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(u4, t6.__v); + } +} +$fb96b826c0c5f37a$export$41c562ebe57d11e2.__b = function(n12) { + $1a9a8ef576b7773d$var$c && $1a9a8ef576b7773d$var$c(n12); +}, $fb96b826c0c5f37a$export$41c562ebe57d11e2.__r = function(n13) { + $1a9a8ef576b7773d$var$f && $1a9a8ef576b7773d$var$f(n13); + var r8 = n13.__c.__H; + r8 && (r8.__h.forEach($1a9a8ef576b7773d$var$g), r8.__h.forEach($1a9a8ef576b7773d$var$j), r8.__h = []); +}, $fb96b826c0c5f37a$export$41c562ebe57d11e2.diffed = function(t8) { + $1a9a8ef576b7773d$var$e && $1a9a8ef576b7773d$var$e(t8); + var o6 = t8.__c; + o6 && o6.__H && o6.__H.__h.length && (1 !== $1a9a8ef576b7773d$var$i.push(o6) && $1a9a8ef576b7773d$var$r === $fb96b826c0c5f37a$export$41c562ebe57d11e2.requestAnimationFrame || (($1a9a8ef576b7773d$var$r = $fb96b826c0c5f37a$export$41c562ebe57d11e2.requestAnimationFrame) || function(n14) { + var t9, u5 = function() { + clearTimeout(r9), $1a9a8ef576b7773d$var$b && cancelAnimationFrame(t9), setTimeout(n14); + }, r9 = setTimeout(u5, 100); + $1a9a8ef576b7773d$var$b && (t9 = requestAnimationFrame(u5)); + })($1a9a8ef576b7773d$var$x)); +}, $fb96b826c0c5f37a$export$41c562ebe57d11e2.__c = function(t10, u6) { + u6.some(function(t11) { + try { + t11.__h.forEach($1a9a8ef576b7773d$var$g), t11.__h = t11.__h.filter(function(n15) { + return !n15.__ || $1a9a8ef576b7773d$var$j(n15); + }); + } catch (r10) { + u6.some(function(n16) { + n16.__h && (n16.__h = []); + }), u6 = [], $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(r10, t11.__v); + } + }), $1a9a8ef576b7773d$var$a && $1a9a8ef576b7773d$var$a(t10, u6); +}, $fb96b826c0c5f37a$export$41c562ebe57d11e2.unmount = function(t12) { + $1a9a8ef576b7773d$var$v && $1a9a8ef576b7773d$var$v(t12); + var u7, r11 = t12.__c; + r11 && r11.__H && (r11.__H.__.forEach(function(n17) { + try { + $1a9a8ef576b7773d$var$g(n17); + } catch (n18) { + u7 = n18; + } + }), u7 && $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e(u7, r11.__v)); +}; +var $1a9a8ef576b7773d$var$b = "function" == typeof requestAnimationFrame; +function $1a9a8ef576b7773d$var$g(n19) { + var r12 = n19.__c; + "function" == typeof r12 && (n19.__c = void 0, r12()); +} +function $1a9a8ef576b7773d$var$j(n20) { + n20.__c = n20.__(); +} +function $dc040a17866866fa$var$S(n1, t1) { + for (var e1 in t1) n1[e1] = t1[e1]; + return n1; +} +function $dc040a17866866fa$var$C(n2, t2) { + for (var e2 in n2) if ("__source" !== e2 && !(e2 in t2)) return true; + for (var r1 in t2) if ("__source" !== r1 && n2[r1] !== t2[r1]) return true; + return false; +} +function $dc040a17866866fa$export$221d75b3f55bb0bd(n3) { + this.props = n3; +} +($dc040a17866866fa$export$221d75b3f55bb0bd.prototype = new $fb96b826c0c5f37a$export$16fa2f45be04daa8()).isPureReactComponent = true, $dc040a17866866fa$export$221d75b3f55bb0bd.prototype.shouldComponentUpdate = function(n6, t5) { + return $dc040a17866866fa$var$C(this.props, n6) || $dc040a17866866fa$var$C(this.state, t5); +}; +var $dc040a17866866fa$var$w = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__b; +$fb96b826c0c5f37a$export$41c562ebe57d11e2.__b = function(n7) { + n7.type && n7.type.__f && n7.ref && (n7.props.ref = n7.ref, n7.ref = null), $dc040a17866866fa$var$w && $dc040a17866866fa$var$w(n7); +}; +var $dc040a17866866fa$var$A = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__e; +$fb96b826c0c5f37a$export$41c562ebe57d11e2.__e = function(n12, t10, e6) { + if (n12.then) { + for (var r5, u1 = t10; u1 = u1.__; ) if ((r5 = u1.__c) && r5.__c) return null == t10.__e && (t10.__e = e6.__e, t10.__k = e6.__k), r5.__c(n12, t10); + } + $dc040a17866866fa$var$A(n12, t10, e6); +}; +var $dc040a17866866fa$var$O = $fb96b826c0c5f37a$export$41c562ebe57d11e2.unmount; +function $dc040a17866866fa$export$74bf444e3cd11ea5() { + this.__u = 0, this.t = null, this.__b = null; +} +function $dc040a17866866fa$var$U(n13) { + var t11 = n13.__.__c; + return t11 && t11.__e && t11.__e(n13); +} +function $dc040a17866866fa$export$998bcd577473dd93() { + this.u = null, this.o = null; +} +$fb96b826c0c5f37a$export$41c562ebe57d11e2.unmount = function(n17) { + var t13 = n17.__c; + t13 && t13.__R && t13.__R(), t13 && true === n17.__h && (n17.type = null), $dc040a17866866fa$var$O && $dc040a17866866fa$var$O(n17); +}, ($dc040a17866866fa$export$74bf444e3cd11ea5.prototype = new $fb96b826c0c5f37a$export$16fa2f45be04daa8()).__c = function(n18, t14) { + var e8 = t14.__c, r7 = this; + null == r7.t && (r7.t = []), r7.t.push(e8); + var u4 = $dc040a17866866fa$var$U(r7.__v), o1 = false, i1 = function() { + o1 || (o1 = true, e8.__R = null, u4 ? u4(l1) : l1()); + }; + e8.__R = i1; + var l1 = function() { + if (!--r7.__u) { + if (r7.state.__e) { + var n19 = r7.state.__e; + r7.__v.__k[0] = (function n22(t17, e9, r8) { + return t17 && (t17.__v = null, t17.__k = t17.__k && t17.__k.map(function(t18) { + return n22(t18, e9, r8); + }), t17.__c && t17.__c.__P === e9 && (t17.__e && r8.insertBefore(t17.__e, t17.__d), t17.__c.__e = true, t17.__c.__P = r8)), t17; + })(n19, n19.__c.__P, n19.__c.__O); + } + var t15; + for (r7.setState({ + __e: r7.__b = null + }); t15 = r7.t.pop(); ) t15.forceUpdate(); + } + }, c1 = true === t14.__h; + r7.__u++ || c1 || r7.setState({ + __e: r7.__b = r7.__v.__k[0] + }), n18.then(i1, i1); +}, $dc040a17866866fa$export$74bf444e3cd11ea5.prototype.componentWillUnmount = function() { + this.t = []; +}, $dc040a17866866fa$export$74bf444e3cd11ea5.prototype.render = function(n23, t19) { + if (this.__b) { + if (this.__v.__k) { + var e10 = document.createElement("div"), r9 = this.__v.__k[0].__c; + this.__v.__k[0] = (function n24(t20, e13, r12) { + return t20 && (t20.__c && t20.__c.__H && (t20.__c.__H.__.forEach(function(n25) { + "function" == typeof n25.__c && n25.__c(); + }), t20.__c.__H = null), null != (t20 = $dc040a17866866fa$var$S({}, t20)).__c && (t20.__c.__P === r12 && (t20.__c.__P = e13), t20.__c = null), t20.__k = t20.__k && t20.__k.map(function(t21) { + return n24(t21, e13, r12); + })), t20; + })(this.__b, e10, r9.__O = r9.__P); + } + this.__b = null; + } + var u5 = t19.__e && $fb96b826c0c5f37a$export$c8a8987d4410bf2d($fb96b826c0c5f37a$export$ffb0004e005737fa, null, n23.fallback); + return u5 && (u5.__h = null), [ + $fb96b826c0c5f37a$export$c8a8987d4410bf2d($fb96b826c0c5f37a$export$ffb0004e005737fa, null, t19.__e ? null : n23.children), + u5 + ]; +}; +var $dc040a17866866fa$var$T = function(n26, t22, e14) { + if (++e14[1] === e14[0] && n26.o.delete(t22), n26.props.revealOrder && ("t" !== n26.props.revealOrder[0] || !n26.o.size)) for (e14 = n26.u; e14; ) { + for (; e14.length > 3; ) e14.pop()(); + if (e14[1] < e14[0]) break; + n26.u = e14 = e14[2]; + } +}; +($dc040a17866866fa$export$998bcd577473dd93.prototype = new $fb96b826c0c5f37a$export$16fa2f45be04daa8()).__e = function(n33) { + var t25 = this, e16 = $dc040a17866866fa$var$U(t25.__v), r13 = t25.o.get(n33); + return r13[0]++, function(u6) { + var o2 = function() { + t25.props.revealOrder ? (r13.push(u6), $dc040a17866866fa$var$T(t25, n33, r13)) : u6(); + }; + e16 ? e16(o2) : o2(); + }; +}, $dc040a17866866fa$export$998bcd577473dd93.prototype.render = function(n34) { + this.u = null, this.o = /* @__PURE__ */ new Map(); + var t26 = $fb96b826c0c5f37a$export$47e4c5b300681277(n34.children); + n34.revealOrder && "b" === n34.revealOrder[0] && t26.reverse(); + for (var e17 = t26.length; e17--; ) this.o.set(t26[e17], this.u = [ + 1, + 0, + this.u + ]); + return n34.children; +}, $dc040a17866866fa$export$998bcd577473dd93.prototype.componentDidUpdate = $dc040a17866866fa$export$998bcd577473dd93.prototype.componentDidMount = function() { + var n35 = this; + this.o.forEach(function(t27, e18) { + $dc040a17866866fa$var$T(n35, e18, t27); + }); +}; +var $dc040a17866866fa$var$j = "undefined" != typeof Symbol && Symbol.for && /* @__PURE__ */ Symbol.for("react.element") || 60103, $dc040a17866866fa$var$P = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|marker(?!H|W|U)|overline|paint|stop|strikethrough|stroke|text(?!L)|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/, $dc040a17866866fa$var$V = "undefined" != typeof document, $dc040a17866866fa$var$z = function(n36) { + return ("undefined" != typeof Symbol && "symbol" == typeof /* @__PURE__ */ Symbol() ? /fil|che|rad/i : /fil|che|ra/i).test(n36); +}; +$fb96b826c0c5f37a$export$16fa2f45be04daa8.prototype.isReactComponent = {}, [ + "componentWillMount", + "componentWillReceiveProps", + "componentWillUpdate" +].forEach(function(n39) { + Object.defineProperty($fb96b826c0c5f37a$export$16fa2f45be04daa8.prototype, n39, { + configurable: true, + get: function() { + return this["UNSAFE_" + n39]; + }, + set: function(t30) { + Object.defineProperty(this, n39, { + configurable: true, + writable: true, + value: t30 + }); + } + }); +}); +var $dc040a17866866fa$var$H = $fb96b826c0c5f37a$export$41c562ebe57d11e2.event; +function $dc040a17866866fa$var$Z() { +} +function $dc040a17866866fa$var$Y() { + return this.cancelBubble; +} +function $dc040a17866866fa$var$q() { + return this.defaultPrevented; +} +$fb96b826c0c5f37a$export$41c562ebe57d11e2.event = function(n40) { + return $dc040a17866866fa$var$H && (n40 = $dc040a17866866fa$var$H(n40)), n40.persist = $dc040a17866866fa$var$Z, n40.isPropagationStopped = $dc040a17866866fa$var$Y, n40.isDefaultPrevented = $dc040a17866866fa$var$q, n40.nativeEvent = n40; +}; +var $dc040a17866866fa$var$J = { + configurable: true, + get: function() { + return this.class; + } +}, $dc040a17866866fa$var$K = $fb96b826c0c5f37a$export$41c562ebe57d11e2.vnode; +$fb96b826c0c5f37a$export$41c562ebe57d11e2.vnode = function(n41) { + var t31 = n41.type, e21 = n41.props, r14 = e21; + if ("string" == typeof t31) { + var u7 = -1 === t31.indexOf("-"); + for (var o3 in r14 = {}, e21) { + var i2 = e21[o3]; + $dc040a17866866fa$var$V && "children" === o3 && "noscript" === t31 || "value" === o3 && "defaultValue" in e21 && null == i2 || ("defaultValue" === o3 && "value" in e21 && null == e21.value ? o3 = "value" : "download" === o3 && true === i2 ? i2 = "" : /ondoubleclick/i.test(o3) ? o3 = "ondblclick" : /^onchange(textarea|input)/i.test(o3 + t31) && !$dc040a17866866fa$var$z(e21.type) ? o3 = "oninput" : /^onfocus$/i.test(o3) ? o3 = "onfocusin" : /^onblur$/i.test(o3) ? o3 = "onfocusout" : /^on(Ani|Tra|Tou|BeforeInp)/.test(o3) ? o3 = o3.toLowerCase() : u7 && $dc040a17866866fa$var$P.test(o3) ? o3 = o3.replace(/[A-Z0-9]/, "-$&").toLowerCase() : null === i2 && (i2 = void 0), r14[o3] = i2); + } + "select" == t31 && r14.multiple && Array.isArray(r14.value) && (r14.value = $fb96b826c0c5f37a$export$47e4c5b300681277(e21.children).forEach(function(n42) { + n42.props.selected = -1 != r14.value.indexOf(n42.props.value); + })), "select" == t31 && null != r14.defaultValue && (r14.value = $fb96b826c0c5f37a$export$47e4c5b300681277(e21.children).forEach(function(n43) { + n43.props.selected = r14.multiple ? -1 != r14.defaultValue.indexOf(n43.props.value) : r14.defaultValue == n43.props.value; + })), n41.props = r14, e21.class != e21.className && ($dc040a17866866fa$var$J.enumerable = "className" in e21, null != e21.className && (r14.class = e21.className), Object.defineProperty(r14, "className", $dc040a17866866fa$var$J)); + } + n41.$$typeof = $dc040a17866866fa$var$j, $dc040a17866866fa$var$K && $dc040a17866866fa$var$K(n41); +}; +var $dc040a17866866fa$var$Q = $fb96b826c0c5f37a$export$41c562ebe57d11e2.__r; +$fb96b826c0c5f37a$export$41c562ebe57d11e2.__r = function(n44) { + $dc040a17866866fa$var$Q && $dc040a17866866fa$var$Q(n44), n44.__c; +}; +const $ec8c39fdad15601a$var$THEME_ICONS = { + light: "outline", + dark: "solid" +}; +class $ec8c39fdad15601a$export$2e2bcd8739ae039 extends $dc040a17866866fa$export$221d75b3f55bb0bd { + renderIcon(category) { + const { icon } = category; + if (icon) { + if (icon.svg) return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + class: "flex", + dangerouslySetInnerHTML: { + __html: icon.svg + } + }); + if (icon.src) return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("img", { + src: icon.src + }); + } + const categoryIcons = $fcccfb36ed0cde68$export$2e2bcd8739ae039.categories[category.id] || $fcccfb36ed0cde68$export$2e2bcd8739ae039.categories.custom; + const style = this.props.icons == "auto" ? $ec8c39fdad15601a$var$THEME_ICONS[this.props.theme] : this.props.icons; + return categoryIcons[style] || categoryIcons; + } + render() { + let selectedCategoryIndex = null; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("nav", { + id: "nav", + class: "padding", + "data-position": this.props.position, + dir: this.props.dir, + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "flex relative", + children: [ + this.categories.map((category, i) => { + const title = category.name || $7adb23b0109cc36a$export$dbe3113d60765c1a.categories[category.id]; + const selected = !this.props.unfocused && category.id == this.state.categoryId; + if (selected) selectedCategoryIndex = i; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("button", { + "aria-label": title, + "aria-selected": selected || void 0, + title, + type: "button", + class: "flex flex-grow flex-center", + onMouseDown: (e) => e.preventDefault(), + onClick: () => { + this.props.onClick({ + category, + i + }); + }, + children: this.renderIcon(category) + }); + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "bar", + style: { + width: `${100 / this.categories.length}%`, + opacity: selectedCategoryIndex == null ? 0 : 1, + transform: this.props.dir === "rtl" ? `scaleX(-1) translateX(${selectedCategoryIndex * 100}%)` : `translateX(${selectedCategoryIndex * 100}%)` + } + }) + ] + }) + }); + } + constructor() { + super(); + this.categories = $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.filter((category) => { + return !category.target; + }); + this.state = { + categoryId: this.categories[0].id + }; + } +} +class $e0d4dda61265ff1e$export$2e2bcd8739ae039 extends $dc040a17866866fa$export$221d75b3f55bb0bd { + shouldComponentUpdate(nextProps) { + for (let k in nextProps) { + if (k == "children") continue; + if (nextProps[k] != this.props[k]) return true; + } + return false; + } + render() { + return this.props.children; + } +} +const $89bd6bb200cc8fef$var$Performance = { + rowsPerRender: 10 +}; +class $89bd6bb200cc8fef$export$2e2bcd8739ae039 extends $fb96b826c0c5f37a$export$16fa2f45be04daa8 { + getInitialState(props = this.props) { + return { + skin: $f72b75cf796873c7$export$2e2bcd8739ae039.get("skin") || props.skin, + theme: this.initTheme(props.theme) + }; + } + componentWillMount() { + this.dir = $7adb23b0109cc36a$export$dbe3113d60765c1a.rtl ? "rtl" : "ltr"; + this.refs = { + menu: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + navigation: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + scroll: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + search: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + searchInput: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + skinToneButton: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + skinToneRadio: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43() + }; + this.initGrid(); + if (this.props.stickySearch == false && this.props.searchPosition == "sticky") { + console.warn("[EmojiMart] Deprecation warning: `stickySearch` has been renamed `searchPosition`."); + this.props.searchPosition = "static"; + } + } + componentDidMount() { + this.register(); + this.shadowRoot = this.base.parentNode; + if (this.props.autoFocus) { + const { searchInput } = this.refs; + if (searchInput.current) searchInput.current.focus(); + } + } + componentWillReceiveProps(nextProps) { + this.nextState || (this.nextState = {}); + for (const k1 in nextProps) this.nextState[k1] = nextProps[k1]; + clearTimeout(this.nextStateTimer); + this.nextStateTimer = setTimeout(() => { + let requiresGridReset = false; + for (const k in this.nextState) { + this.props[k] = this.nextState[k]; + if (k === "custom" || k === "categories") requiresGridReset = true; + } + delete this.nextState; + const nextState = this.getInitialState(); + if (requiresGridReset) return this.reset(nextState); + this.setState(nextState); + }); + } + componentWillUnmount() { + this.unregister(); + } + async reset(nextState = {}) { + await $7adb23b0109cc36a$export$2cd8252107eb640b(this.props); + this.initGrid(); + this.unobserve(); + this.setState(nextState, () => { + this.observeCategories(); + this.observeRows(); + }); + } + register() { + document.addEventListener("click", this.handleClickOutside); + this.observe(); + } + unregister() { + document.removeEventListener("click", this.handleClickOutside); + this.darkMedia?.removeEventListener("change", this.darkMediaCallback); + this.unobserve(); + } + observe() { + this.observeCategories(); + this.observeRows(); + } + unobserve({ except = [] } = {}) { + if (!Array.isArray(except)) except = [ + except + ]; + for (const observer of this.observers) { + if (except.includes(observer)) continue; + observer.disconnect(); + } + this.observers = [].concat(except); + } + initGrid() { + const { categories } = $7adb23b0109cc36a$export$2d0294657ab35f1b; + this.refs.categories = /* @__PURE__ */ new Map(); + const navKey = $7adb23b0109cc36a$export$2d0294657ab35f1b.categories.map((category) => category.id).join(","); + if (this.navKey && this.navKey != navKey) this.refs.scroll.current && (this.refs.scroll.current.scrollTop = 0); + this.navKey = navKey; + this.grid = []; + this.grid.setsize = 0; + const addRow = (rows, category) => { + const row = []; + row.__categoryId = category.id; + row.__index = rows.length; + this.grid.push(row); + const rowIndex = this.grid.length - 1; + const rowRef = rowIndex % $89bd6bb200cc8fef$var$Performance.rowsPerRender ? {} : $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(); + rowRef.index = rowIndex; + rowRef.posinset = this.grid.setsize + 1; + rows.push(rowRef); + return row; + }; + for (let category1 of categories) { + const rows = []; + let row = addRow(rows, category1); + for (let emoji of category1.emojis) { + if (row.length == this.getPerLine()) row = addRow(rows, category1); + this.grid.setsize += 1; + row.push(emoji); + } + this.refs.categories.set(category1.id, { + root: $fb96b826c0c5f37a$export$7d1e3a5e95ceca43(), + rows + }); + } + } + initTheme(theme) { + if (theme != "auto") return theme; + if (!this.darkMedia) { + this.darkMedia = matchMedia("(prefers-color-scheme: dark)"); + if (this.darkMedia.media.match(/^not/)) return "light"; + this.darkMedia.addEventListener("change", this.darkMediaCallback); + } + return this.darkMedia.matches ? "dark" : "light"; + } + initDynamicPerLine(props = this.props) { + if (!props.dynamicWidth) return; + const { element, emojiButtonSize } = props; + const calculatePerLine = () => { + const { width } = element.getBoundingClientRect(); + return Math.floor(width / emojiButtonSize); + }; + const observer = new ResizeObserver(() => { + this.unobserve({ + except: observer + }); + this.setState({ + perLine: calculatePerLine() + }, () => { + this.initGrid(); + this.forceUpdate(() => { + this.observeCategories(); + this.observeRows(); + }); + }); + }); + observer.observe(element); + this.observers.push(observer); + return calculatePerLine(); + } + getPerLine() { + return this.state.perLine || this.props.perLine; + } + getEmojiByPos([p1, p2]) { + const grid = this.state.searchResults || this.grid; + const emoji = grid[p1] && grid[p1][p2]; + if (!emoji) return; + return $c4d155af13ad4d4b$export$2e2bcd8739ae039.get(emoji); + } + observeCategories() { + const navigation = this.refs.navigation.current; + if (!navigation) return; + const visibleCategories = /* @__PURE__ */ new Map(); + const setFocusedCategory = (categoryId) => { + if (categoryId != navigation.state.categoryId) navigation.setState({ + categoryId + }); + }; + const observerOptions = { + root: this.refs.scroll.current, + threshold: [ + 0, + 1 + ] + }; + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + const id = entry.target.dataset.id; + visibleCategories.set(id, entry.intersectionRatio); + } + const ratios = [ + ...visibleCategories + ]; + for (const [id, ratio] of ratios) if (ratio) { + setFocusedCategory(id); + break; + } + }, observerOptions); + for (const { root } of this.refs.categories.values()) observer.observe(root.current); + this.observers.push(observer); + } + observeRows() { + const visibleRows = { + ...this.state.visibleRows + }; + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + const index = parseInt(entry.target.dataset.index); + if (entry.isIntersecting) visibleRows[index] = true; + else delete visibleRows[index]; + } + this.setState({ + visibleRows + }); + }, { + root: this.refs.scroll.current, + rootMargin: `${this.props.emojiButtonSize * ($89bd6bb200cc8fef$var$Performance.rowsPerRender + 5)}px 0px ${this.props.emojiButtonSize * $89bd6bb200cc8fef$var$Performance.rowsPerRender}px` + }); + for (const { rows } of this.refs.categories.values()) { + for (const row of rows) if (row.current) observer.observe(row.current); + } + this.observers.push(observer); + } + preventDefault(e) { + e.preventDefault(); + } + unfocusSearch() { + const input = this.refs.searchInput.current; + if (!input) return; + input.blur(); + } + navigate({ e, input, left, right, up, down }) { + const grid = this.state.searchResults || this.grid; + if (!grid.length) return; + let [p1, p2] = this.state.pos; + const pos = (() => { + if (p1 == 0) { + if (p2 == 0 && !e.repeat && (left || up)) return null; + } + if (p1 == -1) { + if (!e.repeat && (right || down) && input.selectionStart == input.value.length) return [ + 0, + 0 + ]; + return null; + } + if (left || right) { + let row = grid[p1]; + const increment = left ? -1 : 1; + p2 += increment; + if (!row[p2]) { + p1 += increment; + row = grid[p1]; + if (!row) { + p1 = left ? 0 : grid.length - 1; + p2 = left ? 0 : grid[p1].length - 1; + return [ + p1, + p2 + ]; + } + p2 = left ? row.length - 1 : 0; + } + return [ + p1, + p2 + ]; + } + if (up || down) { + p1 += up ? -1 : 1; + const row = grid[p1]; + if (!row) { + p1 = up ? 0 : grid.length - 1; + p2 = up ? 0 : grid[p1].length - 1; + return [ + p1, + p2 + ]; + } + if (!row[p2]) p2 = row.length - 1; + return [ + p1, + p2 + ]; + } + })(); + if (pos) e.preventDefault(); + else { + if (this.state.pos[0] > -1) this.setState({ + pos: [ + -1, + -1 + ] + }); + return; + } + this.setState({ + pos, + keyboard: true + }, () => { + this.scrollTo({ + row: pos[0] + }); + }); + } + scrollTo({ categoryId, row }) { + const grid = this.state.searchResults || this.grid; + if (!grid.length) return; + const scroll = this.refs.scroll.current; + const scrollRect = scroll.getBoundingClientRect(); + let scrollTop = 0; + if (row >= 0) categoryId = grid[row].__categoryId; + if (categoryId) { + const ref = this.refs[categoryId] || this.refs.categories.get(categoryId).root; + const categoryRect = ref.current.getBoundingClientRect(); + scrollTop = categoryRect.top - (scrollRect.top - scroll.scrollTop) + 1; + } + if (row >= 0) { + if (!row) scrollTop = 0; + else { + const rowIndex = grid[row].__index; + const rowTop = scrollTop + rowIndex * this.props.emojiButtonSize; + const rowBot = rowTop + this.props.emojiButtonSize + this.props.emojiButtonSize * 0.88; + if (rowTop < scroll.scrollTop) scrollTop = rowTop; + else if (rowBot > scroll.scrollTop + scrollRect.height) scrollTop = rowBot - scrollRect.height; + else return; + } + } + this.ignoreMouse(); + scroll.scrollTop = scrollTop; + } + ignoreMouse() { + this.mouseIsIgnored = true; + clearTimeout(this.ignoreMouseTimer); + this.ignoreMouseTimer = setTimeout(() => { + delete this.mouseIsIgnored; + }, 100); + } + handleEmojiOver(pos) { + if (this.mouseIsIgnored || this.state.showSkins) return; + this.setState({ + pos: pos || [ + -1, + -1 + ], + keyboard: false + }); + } + handleEmojiClick({ e, emoji, pos }) { + if (!this.props.onEmojiSelect) return; + if (!emoji && pos) emoji = this.getEmojiByPos(pos); + if (emoji) { + const emojiData = $693b183b0a78708f$export$d10ac59fbe52a745(emoji, { + skinIndex: this.state.skin - 1 + }); + if (this.props.maxFrequentRows) $b22cfd0a55410b4f$export$2e2bcd8739ae039.add(emojiData, this.props); + this.props.onEmojiSelect(emojiData, e); + } + } + closeSkins() { + if (!this.state.showSkins) return; + this.setState({ + showSkins: null, + tempSkin: null + }); + this.base.removeEventListener("click", this.handleBaseClick); + this.base.removeEventListener("keydown", this.handleBaseKeydown); + } + handleSkinMouseOver(tempSkin) { + this.setState({ + tempSkin + }); + } + handleSkinClick(skin) { + this.ignoreMouse(); + this.closeSkins(); + this.setState({ + skin, + tempSkin: null + }); + $f72b75cf796873c7$export$2e2bcd8739ae039.set("skin", skin); + } + renderNav() { + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b($ec8c39fdad15601a$export$2e2bcd8739ae039, { + ref: this.refs.navigation, + icons: this.props.icons, + theme: this.state.theme, + dir: this.dir, + unfocused: !!this.state.searchResults, + position: this.props.navPosition, + onClick: this.handleCategoryClick + }, this.navKey); + } + renderPreview() { + const emoji = this.getEmojiByPos(this.state.pos); + const noSearchResults = this.state.searchResults && !this.state.searchResults.length; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + id: "preview", + class: "flex flex-middle", + dir: this.dir, + "data-position": this.props.previewPosition, + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "flex flex-middle flex-grow", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "flex flex-auto flex-middle flex-center", + style: { + height: this.props.emojiButtonSize, + fontSize: this.props.emojiButtonSize + }, + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b($254755d3f438722f$export$2e2bcd8739ae039, { + emoji, + id: noSearchResults ? this.props.noResultsEmoji || "cry" : this.props.previewEmoji || (this.props.previewPosition == "top" ? "point_down" : "point_up"), + set: this.props.set, + size: this.props.emojiButtonSize, + skin: this.state.tempSkin || this.state.skin, + spritesheet: true, + getSpritesheetURL: this.props.getSpritesheetURL + }) + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: `margin-${this.dir[0]}`, + children: emoji || noSearchResults ? /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: `padding-${this.dir[2]} align-${this.dir[0]}`, + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "preview-title ellipsis", + children: emoji ? emoji.name : $7adb23b0109cc36a$export$dbe3113d60765c1a.search_no_results_1 + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "preview-subtitle ellipsis color-c", + children: emoji ? emoji.skins[0].shortcodes : $7adb23b0109cc36a$export$dbe3113d60765c1a.search_no_results_2 + }) + ] + }) : /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "preview-placeholder color-c", + children: $7adb23b0109cc36a$export$dbe3113d60765c1a.pick + }) + }) + ] + }), + !emoji && this.props.skinTonePosition == "preview" && this.renderSkinToneButton() + ] + }); + } + renderEmojiButton(emoji, { pos, posinset, grid }) { + const size = this.props.emojiButtonSize; + const skin = this.state.tempSkin || this.state.skin; + const emojiSkin = emoji.skins[skin - 1] || emoji.skins[0]; + const native = emojiSkin.native; + const selected = $693b183b0a78708f$export$9cb4719e2e525b7a(this.state.pos, pos); + const key = pos.concat(emoji.id).join(""); + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b($e0d4dda61265ff1e$export$2e2bcd8739ae039, { + selected, + skin, + size, + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("button", { + "aria-label": native, + "aria-selected": selected || void 0, + "aria-posinset": posinset, + "aria-setsize": grid.setsize, + "data-keyboard": this.state.keyboard, + title: this.props.previewPosition == "none" ? emoji.name : void 0, + type: "button", + class: "flex flex-center flex-middle", + tabindex: "-1", + onClick: (e) => this.handleEmojiClick({ + e, + emoji + }), + onMouseEnter: () => this.handleEmojiOver(pos), + onMouseLeave: () => this.handleEmojiOver(), + style: { + width: this.props.emojiButtonSize, + height: this.props.emojiButtonSize, + fontSize: this.props.emojiSize, + lineHeight: 0 + }, + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + "aria-hidden": "true", + class: "background", + style: { + borderRadius: this.props.emojiButtonRadius, + backgroundColor: this.props.emojiButtonColors ? this.props.emojiButtonColors[(posinset - 1) % this.props.emojiButtonColors.length] : void 0 + } + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b($254755d3f438722f$export$2e2bcd8739ae039, { + emoji, + set: this.props.set, + size: this.props.emojiSize, + skin, + spritesheet: true, + getSpritesheetURL: this.props.getSpritesheetURL + }) + ] + }) + }, key); + } + renderSearch() { + const renderSkinTone = this.props.previewPosition == "none" || this.props.skinTonePosition == "search"; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "spacer" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "flex flex-middle", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "search relative flex-grow", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("input", { + type: "search", + ref: this.refs.searchInput, + placeholder: $7adb23b0109cc36a$export$dbe3113d60765c1a.search, + onClick: this.handleSearchClick, + onInput: this.handleSearchInput, + onKeyDown: this.handleSearchKeyDown, + autoComplete: "off" + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + class: "icon loupe flex", + children: $fcccfb36ed0cde68$export$2e2bcd8739ae039.search.loupe + }), + this.state.searchResults && /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("button", { + title: "Clear", + "aria-label": "Clear", + type: "button", + class: "icon delete flex", + onClick: this.clearSearch, + onMouseDown: this.preventDefault, + children: $fcccfb36ed0cde68$export$2e2bcd8739ae039.search.delete + }) + ] + }), + renderSkinTone && this.renderSkinToneButton() + ] + }) + ] + }); + } + renderSearchResults() { + const { searchResults } = this.state; + if (!searchResults) return null; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "category", + ref: this.refs.search, + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: `sticky padding-small align-${this.dir[0]}`, + children: $7adb23b0109cc36a$export$dbe3113d60765c1a.categories.search + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + children: !searchResults.length ? /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: `padding-small align-${this.dir[0]}`, + children: this.props.onAddCustomEmoji && /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("a", { + onClick: this.props.onAddCustomEmoji, + children: $7adb23b0109cc36a$export$dbe3113d60765c1a.add_custom + }) + }) : searchResults.map((row, i) => { + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "flex", + children: row.map((emoji, ii) => { + return this.renderEmojiButton(emoji, { + pos: [ + i, + ii + ], + posinset: i * this.props.perLine + ii + 1, + grid: searchResults + }); + }) + }); + }) + }) + ] + }); + } + renderCategories() { + const { categories } = $7adb23b0109cc36a$export$2d0294657ab35f1b; + const hidden = !!this.state.searchResults; + const perLine = this.getPerLine(); + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + style: { + visibility: hidden ? "hidden" : void 0, + display: hidden ? "none" : void 0, + height: "100%" + }, + children: categories.map((category) => { + const { root, rows } = this.refs.categories.get(category.id); + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + "data-id": category.target ? category.target.id : category.id, + class: "category", + ref: root, + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: `sticky padding-small align-${this.dir[0]}`, + children: category.name || $7adb23b0109cc36a$export$dbe3113d60765c1a.categories[category.id] + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "relative", + style: { + height: rows.length * this.props.emojiButtonSize + }, + children: rows.map((row, i) => { + const targetRow = row.index - row.index % $89bd6bb200cc8fef$var$Performance.rowsPerRender; + const visible = this.state.visibleRows[targetRow]; + const ref = "current" in row ? row : void 0; + if (!visible && !ref) return null; + const start = i * perLine; + const end = start + perLine; + const emojiIds = category.emojis.slice(start, end); + if (emojiIds.length < perLine) emojiIds.push(...new Array(perLine - emojiIds.length)); + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + "data-index": row.index, + ref, + class: "flex row", + style: { + top: i * this.props.emojiButtonSize + }, + children: visible && emojiIds.map((emojiId, ii) => { + if (!emojiId) return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + style: { + width: this.props.emojiButtonSize, + height: this.props.emojiButtonSize + } + }); + const emoji = $c4d155af13ad4d4b$export$2e2bcd8739ae039.get(emojiId); + return this.renderEmojiButton(emoji, { + pos: [ + row.index, + ii + ], + posinset: row.posinset + ii, + grid: this.grid + }); + }) + }, row.index); + }) + }) + ] + }); + }) + }); + } + renderSkinToneButton() { + if (this.props.skinTonePosition == "none") return null; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "flex flex-auto flex-center flex-middle", + style: { + position: "relative", + width: this.props.emojiButtonSize, + height: this.props.emojiButtonSize + }, + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("button", { + type: "button", + ref: this.refs.skinToneButton, + class: "skin-tone-button flex flex-auto flex-center flex-middle", + "aria-selected": this.state.showSkins ? "" : void 0, + "aria-label": $7adb23b0109cc36a$export$dbe3113d60765c1a.skins.choose, + title: $7adb23b0109cc36a$export$dbe3113d60765c1a.skins.choose, + onClick: this.openSkins, + style: { + width: this.props.emojiSize, + height: this.props.emojiSize + }, + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + class: `skin-tone skin-tone-${this.state.skin}` + }) + }) + }); + } + renderLiveRegion() { + const emoji = this.getEmojiByPos(this.state.pos); + const contents = emoji ? emoji.name : ""; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + "aria-live": "polite", + class: "sr-only", + children: contents + }); + } + renderSkins() { + const skinToneButton = this.refs.skinToneButton.current; + const skinToneButtonRect = skinToneButton.getBoundingClientRect(); + const baseRect = this.base.getBoundingClientRect(); + const position = {}; + if (this.dir == "ltr") position.right = baseRect.right - skinToneButtonRect.right - 3; + else position.left = skinToneButtonRect.left - baseRect.left - 3; + if (this.props.previewPosition == "bottom" && this.props.skinTonePosition == "preview") position.bottom = baseRect.bottom - skinToneButtonRect.top + 6; + else { + position.top = skinToneButtonRect.bottom - baseRect.top + 3; + position.bottom = "auto"; + } + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + ref: this.refs.menu, + role: "radiogroup", + dir: this.dir, + "aria-label": $7adb23b0109cc36a$export$dbe3113d60765c1a.skins.choose, + class: "menu hidden", + "data-position": position.top ? "top" : "bottom", + style: position, + children: [ + ...Array(6).keys() + ].map((i) => { + const skin = i + 1; + const checked = this.state.skin == skin; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("input", { + type: "radio", + name: "skin-tone", + value: skin, + "aria-label": $7adb23b0109cc36a$export$dbe3113d60765c1a.skins[skin], + ref: checked ? this.refs.skinToneRadio : null, + defaultChecked: checked, + onChange: () => this.handleSkinMouseOver(skin), + onKeyDown: (e) => { + if (e.code == "Enter" || e.code == "Space" || e.code == "Tab") { + e.preventDefault(); + this.handleSkinClick(skin); + } + } + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("button", { + "aria-hidden": "true", + tabindex: "-1", + onClick: () => this.handleSkinClick(skin), + onMouseEnter: () => this.handleSkinMouseOver(skin), + onMouseLeave: () => this.handleSkinMouseOver(), + class: "option flex flex-grow flex-middle", + children: [ + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + class: `skin-tone skin-tone-${skin}` + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("span", { + class: "margin-small-lr", + children: $7adb23b0109cc36a$export$dbe3113d60765c1a.skins[skin] + }) + ] + }) + ] + }); + }) + }); + } + render() { + const lineWidth = this.props.perLine * this.props.emojiButtonSize; + return /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("section", { + id: "root", + class: "flex flex-column", + dir: this.dir, + style: { + width: this.props.dynamicWidth ? "100%" : `calc(${lineWidth}px + (var(--padding) + var(--sidebar-width)))` + }, + "data-emoji-set": this.props.set, + "data-theme": this.state.theme, + "data-menu": this.state.showSkins ? "" : void 0, + children: [ + this.props.previewPosition == "top" && this.renderPreview(), + this.props.navPosition == "top" && this.renderNav(), + this.props.searchPosition == "sticky" && /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + class: "padding-lr", + children: this.renderSearch() + }), + /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + ref: this.refs.scroll, + class: "scroll flex-grow padding-lr", + children: /* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b("div", { + style: { + width: this.props.dynamicWidth ? "100%" : lineWidth, + height: "100%" + }, + children: [ + this.props.searchPosition == "static" && this.renderSearch(), + this.renderSearchResults(), + this.renderCategories() + ] + }) + }), + this.props.navPosition == "bottom" && this.renderNav(), + this.props.previewPosition == "bottom" && this.renderPreview(), + this.state.showSkins && this.renderSkins(), + this.renderLiveRegion() + ] + }); + } + constructor(props) { + super(); + $c770c458706daa72$export$2e2bcd8739ae039(this, "darkMediaCallback", () => { + if (this.props.theme != "auto") return; + this.setState({ + theme: this.darkMedia.matches ? "dark" : "light" + }); + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleClickOutside", (e) => { + const { element } = this.props; + if (e.target != element) { + if (this.state.showSkins) this.closeSkins(); + if (this.props.onClickOutside) this.props.onClickOutside(e); + } + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleBaseClick", (e) => { + if (!this.state.showSkins) return; + if (!e.target.closest(".menu")) { + e.preventDefault(); + e.stopImmediatePropagation(); + this.closeSkins(); + } + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleBaseKeydown", (e) => { + if (!this.state.showSkins) return; + if (e.key == "Escape") { + e.preventDefault(); + e.stopImmediatePropagation(); + this.closeSkins(); + } + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleSearchClick", () => { + const emoji = this.getEmojiByPos(this.state.pos); + if (!emoji) return; + this.setState({ + pos: [ + -1, + -1 + ] + }); + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleSearchInput", async () => { + const input = this.refs.searchInput.current; + if (!input) return; + const { value } = input; + const searchResults = await $c4d155af13ad4d4b$export$2e2bcd8739ae039.search(value); + const afterRender = () => { + if (!this.refs.scroll.current) return; + this.refs.scroll.current.scrollTop = 0; + }; + if (!searchResults) return this.setState({ + searchResults, + pos: [ + -1, + -1 + ] + }, afterRender); + const pos = input.selectionStart == input.value.length ? [ + 0, + 0 + ] : [ + -1, + -1 + ]; + const grid = []; + grid.setsize = searchResults.length; + let row = null; + for (let emoji of searchResults) { + if (!grid.length || row.length == this.getPerLine()) { + row = []; + row.__categoryId = "search"; + row.__index = grid.length; + grid.push(row); + } + row.push(emoji); + } + this.ignoreMouse(); + this.setState({ + searchResults: grid, + pos + }, afterRender); + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleSearchKeyDown", (e) => { + const input = e.currentTarget; + e.stopImmediatePropagation(); + switch (e.key) { + case "ArrowLeft": + this.navigate({ + e, + input, + left: true + }); + break; + case "ArrowRight": + this.navigate({ + e, + input, + right: true + }); + break; + case "ArrowUp": + this.navigate({ + e, + input, + up: true + }); + break; + case "ArrowDown": + this.navigate({ + e, + input, + down: true + }); + break; + case "Enter": + e.preventDefault(); + this.handleEmojiClick({ + e, + pos: this.state.pos + }); + break; + case "Escape": + e.preventDefault(); + if (this.state.searchResults) this.clearSearch(); + else this.unfocusSearch(); + break; + } + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "clearSearch", () => { + const input = this.refs.searchInput.current; + if (!input) return; + input.value = ""; + input.focus(); + this.handleSearchInput(); + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "handleCategoryClick", ({ category, i }) => { + this.scrollTo(i == 0 ? { + row: -1 + } : { + categoryId: category.id + }); + }); + $c770c458706daa72$export$2e2bcd8739ae039(this, "openSkins", (e) => { + const { currentTarget } = e; + const rect = currentTarget.getBoundingClientRect(); + this.setState({ + showSkins: rect + }, async () => { + await $693b183b0a78708f$export$e772c8ff12451969(2); + const menu = this.refs.menu.current; + if (!menu) return; + menu.classList.remove("hidden"); + this.refs.skinToneRadio.current.focus(); + this.base.addEventListener("click", this.handleBaseClick, true); + this.base.addEventListener("keydown", this.handleBaseKeydown, true); + }); + }); + this.observers = []; + this.state = { + pos: [ + -1, + -1 + ], + perLine: this.initDynamicPerLine(props), + visibleRows: { + 0: true + }, + ...this.getInitialState(props) + }; + } +} +class $efa000751917694d$export$2e2bcd8739ae039 extends $26f27c338a96b1a6$export$2e2bcd8739ae039 { + async connectedCallback() { + const props = $7adb23b0109cc36a$export$75fe5f91d452f94b(this.props, $b247ea80b67298d5$export$2e2bcd8739ae039, this); + props.element = this; + props.ref = (component) => { + this.component = component; + }; + await $7adb23b0109cc36a$export$2cd8252107eb640b(props); + if (this.disconnected) return; + $fb96b826c0c5f37a$export$b3890eb0ae9dca99(/* @__PURE__ */ $bd9dd35321b03dd4$export$34b9dba7ce09269b($89bd6bb200cc8fef$export$2e2bcd8739ae039, { + ...props + }), this.shadowRoot); + } + constructor(props) { + super(props, { + styles: /* @__PURE__ */ $parcel$interopDefault($329d53ba9fd7125f$exports) + }); + } +} +$c770c458706daa72$export$2e2bcd8739ae039($efa000751917694d$export$2e2bcd8739ae039, "Props", $b247ea80b67298d5$export$2e2bcd8739ae039); +if (typeof customElements !== "undefined" && !customElements.get("em-emoji-picker")) customElements.define("em-emoji-picker", $efa000751917694d$export$2e2bcd8739ae039); +var $329d53ba9fd7125f$exports = {}; +$329d53ba9fd7125f$exports = ':host {\n width: min-content;\n height: 435px;\n min-height: 230px;\n border-radius: var(--border-radius);\n box-shadow: var(--shadow);\n --border-radius: 10px;\n --category-icon-size: 18px;\n --font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;\n --font-size: 15px;\n --preview-placeholder-size: 21px;\n --preview-title-size: 1.1em;\n --preview-subtitle-size: .9em;\n --shadow-color: 0deg 0% 0%;\n --shadow: .3px .5px 2.7px hsl(var(--shadow-color) / .14), .4px .8px 1px -3.2px hsl(var(--shadow-color) / .14), 1px 2px 2.5px -4.5px hsl(var(--shadow-color) / .14);\n display: flex;\n}\n\n[data-theme="light"] {\n --em-rgb-color: var(--rgb-color, 34, 36, 39);\n --em-rgb-accent: var(--rgb-accent, 34, 102, 237);\n --em-rgb-background: var(--rgb-background, 255, 255, 255);\n --em-rgb-input: var(--rgb-input, 255, 255, 255);\n --em-color-border: var(--color-border, rgba(0, 0, 0, .05));\n --em-color-border-over: var(--color-border-over, rgba(0, 0, 0, .1));\n}\n\n[data-theme="dark"] {\n --em-rgb-color: var(--rgb-color, 222, 222, 221);\n --em-rgb-accent: var(--rgb-accent, 58, 130, 247);\n --em-rgb-background: var(--rgb-background, 21, 22, 23);\n --em-rgb-input: var(--rgb-input, 0, 0, 0);\n --em-color-border: var(--color-border, rgba(255, 255, 255, .1));\n --em-color-border-over: var(--color-border-over, rgba(255, 255, 255, .2));\n}\n\n#root {\n --color-a: rgb(var(--em-rgb-color));\n --color-b: rgba(var(--em-rgb-color), .65);\n --color-c: rgba(var(--em-rgb-color), .45);\n --padding: 12px;\n --padding-small: calc(var(--padding) / 2);\n --sidebar-width: 16px;\n --duration: 225ms;\n --duration-fast: 125ms;\n --duration-instant: 50ms;\n --easing: cubic-bezier(.4, 0, .2, 1);\n width: 100%;\n text-align: left;\n border-radius: var(--border-radius);\n background-color: rgb(var(--em-rgb-background));\n position: relative;\n}\n\n@media (prefers-reduced-motion) {\n #root {\n --duration: 0;\n --duration-fast: 0;\n --duration-instant: 0;\n }\n}\n\n#root[data-menu] button {\n cursor: auto;\n}\n\n#root[data-menu] .menu button {\n cursor: pointer;\n}\n\n:host, #root, input, button {\n color: rgb(var(--em-rgb-color));\n font-family: var(--font-family);\n font-size: var(--font-size);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n line-height: normal;\n}\n\n*, :before, :after {\n box-sizing: border-box;\n min-width: 0;\n margin: 0;\n padding: 0;\n}\n\n.relative {\n position: relative;\n}\n\n.flex {\n display: flex;\n}\n\n.flex-auto {\n flex: none;\n}\n\n.flex-center {\n justify-content: center;\n}\n\n.flex-column {\n flex-direction: column;\n}\n\n.flex-grow {\n flex: auto;\n}\n\n.flex-middle {\n align-items: center;\n}\n\n.flex-wrap {\n flex-wrap: wrap;\n}\n\n.padding {\n padding: var(--padding);\n}\n\n.padding-t {\n padding-top: var(--padding);\n}\n\n.padding-lr {\n padding-left: var(--padding);\n padding-right: var(--padding);\n}\n\n.padding-r {\n padding-right: var(--padding);\n}\n\n.padding-small {\n padding: var(--padding-small);\n}\n\n.padding-small-b {\n padding-bottom: var(--padding-small);\n}\n\n.padding-small-lr {\n padding-left: var(--padding-small);\n padding-right: var(--padding-small);\n}\n\n.margin {\n margin: var(--padding);\n}\n\n.margin-r {\n margin-right: var(--padding);\n}\n\n.margin-l {\n margin-left: var(--padding);\n}\n\n.margin-small-l {\n margin-left: var(--padding-small);\n}\n\n.margin-small-lr {\n margin-left: var(--padding-small);\n margin-right: var(--padding-small);\n}\n\n.align-l {\n text-align: left;\n}\n\n.align-r {\n text-align: right;\n}\n\n.color-a {\n color: var(--color-a);\n}\n\n.color-b {\n color: var(--color-b);\n}\n\n.color-c {\n color: var(--color-c);\n}\n\n.ellipsis {\n white-space: nowrap;\n max-width: 100%;\n width: auto;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.sr-only {\n width: 1px;\n height: 1px;\n position: absolute;\n top: auto;\n left: -10000px;\n overflow: hidden;\n}\n\na {\n cursor: pointer;\n color: rgb(var(--em-rgb-accent));\n}\n\na:hover {\n text-decoration: underline;\n}\n\n.spacer {\n height: 10px;\n}\n\n[dir="rtl"] .scroll {\n padding-left: 0;\n padding-right: var(--padding);\n}\n\n.scroll {\n padding-right: 0;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.scroll::-webkit-scrollbar {\n width: var(--sidebar-width);\n height: var(--sidebar-width);\n}\n\n.scroll::-webkit-scrollbar-track {\n border: 0;\n}\n\n.scroll::-webkit-scrollbar-button {\n width: 0;\n height: 0;\n display: none;\n}\n\n.scroll::-webkit-scrollbar-corner {\n background-color: rgba(0, 0, 0, 0);\n}\n\n.scroll::-webkit-scrollbar-thumb {\n min-height: 20%;\n min-height: 65px;\n border: 4px solid rgb(var(--em-rgb-background));\n border-radius: 8px;\n}\n\n.scroll::-webkit-scrollbar-thumb:hover {\n background-color: var(--em-color-border-over) !important;\n}\n\n.scroll:hover::-webkit-scrollbar-thumb {\n background-color: var(--em-color-border);\n}\n\n.sticky {\n z-index: 1;\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n font-weight: 500;\n position: sticky;\n top: -1px;\n}\n\n[dir="rtl"] .search input[type="search"] {\n padding: 10px 2.2em 10px 2em;\n}\n\n[dir="rtl"] .search .loupe {\n left: auto;\n right: .7em;\n}\n\n[dir="rtl"] .search .delete {\n left: .7em;\n right: auto;\n}\n\n.search {\n z-index: 2;\n position: relative;\n}\n\n.search input, .search button {\n font-size: calc(var(--font-size) - 1px);\n}\n\n.search input[type="search"] {\n width: 100%;\n background-color: var(--em-color-border);\n transition-duration: var(--duration);\n transition-property: background-color, box-shadow;\n transition-timing-function: var(--easing);\n border: 0;\n border-radius: 10px;\n outline: 0;\n padding: 10px 2em 10px 2.2em;\n display: block;\n}\n\n.search input[type="search"]::-ms-input-placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"]::placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"], .search input[type="search"]::-webkit-search-decoration, .search input[type="search"]::-webkit-search-cancel-button, .search input[type="search"]::-webkit-search-results-button, .search input[type="search"]::-webkit-search-results-decoration {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n}\n\n.search input[type="search"]:focus {\n background-color: rgb(var(--em-rgb-input));\n box-shadow: inset 0 0 0 1px rgb(var(--em-rgb-accent)), 0 1px 3px rgba(65, 69, 73, .2);\n}\n\n.search .icon {\n z-index: 1;\n color: rgba(var(--em-rgb-color), .7);\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n\n.search .loupe {\n pointer-events: none;\n left: .7em;\n}\n\n.search .delete {\n right: .7em;\n}\n\nsvg {\n fill: currentColor;\n width: 1em;\n height: 1em;\n}\n\nbutton {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n cursor: pointer;\n color: currentColor;\n background-color: rgba(0, 0, 0, 0);\n border: 0;\n}\n\n#nav {\n z-index: 2;\n padding-top: 12px;\n padding-bottom: 12px;\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#nav button {\n color: var(--color-b);\n transition: color var(--duration) var(--easing);\n}\n\n#nav button:hover {\n color: var(--color-a);\n}\n\n#nav svg, #nav img {\n width: var(--category-icon-size);\n height: var(--category-icon-size);\n}\n\n#nav[dir="rtl"] .bar {\n left: auto;\n right: 0;\n}\n\n#nav .bar {\n width: 100%;\n height: 3px;\n background-color: rgb(var(--em-rgb-accent));\n transition: transform var(--duration) var(--easing);\n border-radius: 3px 3px 0 0;\n position: absolute;\n bottom: -12px;\n left: 0;\n}\n\n#nav button[aria-selected] {\n color: rgb(var(--em-rgb-accent));\n}\n\n#preview {\n z-index: 2;\n padding: calc(var(--padding) + 4px) var(--padding);\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#preview .preview-placeholder {\n font-size: var(--preview-placeholder-size);\n}\n\n#preview .preview-title {\n font-size: var(--preview-title-size);\n}\n\n#preview .preview-subtitle {\n font-size: var(--preview-subtitle-size);\n}\n\n#nav:before, #preview:before {\n content: "";\n height: 2px;\n position: absolute;\n left: 0;\n right: 0;\n}\n\n#nav[data-position="top"]:before, #preview[data-position="top"]:before {\n background: linear-gradient(to bottom, var(--em-color-border), transparent);\n top: 100%;\n}\n\n#nav[data-position="bottom"]:before, #preview[data-position="bottom"]:before {\n background: linear-gradient(to top, var(--em-color-border), transparent);\n bottom: 100%;\n}\n\n.category:last-child {\n min-height: calc(100% + 1px);\n}\n\n.category button {\n font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, sans-serif;\n position: relative;\n}\n\n.category button > * {\n position: relative;\n}\n\n.category button .background {\n opacity: 0;\n background-color: var(--em-color-border);\n transition: opacity var(--duration-fast) var(--easing) var(--duration-instant);\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n\n.category button:hover .background {\n transition-duration: var(--duration-instant);\n transition-delay: 0s;\n}\n\n.category button[aria-selected] .background {\n opacity: 1;\n}\n\n.category button[data-keyboard] .background {\n transition: none;\n}\n\n.row {\n width: 100%;\n position: absolute;\n top: 0;\n left: 0;\n}\n\n.skin-tone-button {\n border: 1px solid rgba(0, 0, 0, 0);\n border-radius: 100%;\n}\n\n.skin-tone-button:hover {\n border-color: var(--em-color-border);\n}\n\n.skin-tone-button:active .skin-tone {\n transform: scale(.85) !important;\n}\n\n.skin-tone-button .skin-tone {\n transition: transform var(--duration) var(--easing);\n}\n\n.skin-tone-button[aria-selected] {\n background-color: var(--em-color-border);\n border-top-color: rgba(0, 0, 0, .05);\n border-bottom-color: rgba(0, 0, 0, 0);\n border-left-width: 0;\n border-right-width: 0;\n}\n\n.skin-tone-button[aria-selected] .skin-tone {\n transform: scale(.9);\n}\n\n.menu {\n z-index: 2;\n white-space: nowrap;\n border: 1px solid var(--em-color-border);\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n transition-property: opacity, transform;\n transition-duration: var(--duration);\n transition-timing-function: var(--easing);\n border-radius: 10px;\n padding: 4px;\n position: absolute;\n box-shadow: 1px 1px 5px rgba(0, 0, 0, .05);\n}\n\n.menu.hidden {\n opacity: 0;\n}\n\n.menu[data-position="bottom"] {\n transform-origin: 100% 100%;\n}\n\n.menu[data-position="bottom"].hidden {\n transform: scale(.9)rotate(-3deg)translateY(5%);\n}\n\n.menu[data-position="top"] {\n transform-origin: 100% 0;\n}\n\n.menu[data-position="top"].hidden {\n transform: scale(.9)rotate(3deg)translateY(-5%);\n}\n\n.menu input[type="radio"] {\n clip: rect(0 0 0 0);\n width: 1px;\n height: 1px;\n border: 0;\n margin: 0;\n padding: 0;\n position: absolute;\n overflow: hidden;\n}\n\n.menu input[type="radio"]:checked + .option {\n box-shadow: 0 0 0 2px rgb(var(--em-rgb-accent));\n}\n\n.option {\n width: 100%;\n border-radius: 6px;\n padding: 4px 6px;\n}\n\n.option:hover {\n color: #fff;\n background-color: rgb(var(--em-rgb-accent));\n}\n\n.skin-tone {\n width: 16px;\n height: 16px;\n border-radius: 100%;\n display: inline-block;\n position: relative;\n overflow: hidden;\n}\n\n.skin-tone:after {\n content: "";\n mix-blend-mode: overlay;\n background: linear-gradient(rgba(255, 255, 255, .2), rgba(0, 0, 0, 0));\n border: 1px solid rgba(0, 0, 0, .8);\n border-radius: 100%;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 2px #fff;\n}\n\n.skin-tone-1 {\n background-color: #ffc93a;\n}\n\n.skin-tone-2 {\n background-color: #ffdab7;\n}\n\n.skin-tone-3 {\n background-color: #e7b98f;\n}\n\n.skin-tone-4 {\n background-color: #c88c61;\n}\n\n.skin-tone-5 {\n background-color: #a46134;\n}\n\n.skin-tone-6 {\n background-color: #5d4437;\n}\n\n[data-index] {\n justify-content: space-between;\n}\n\n[data-emoji-set="twitter"] .skin-tone:after {\n box-shadow: none;\n border-color: rgba(0, 0, 0, .5);\n}\n\n[data-emoji-set="twitter"] .skin-tone-1 {\n background-color: #fade72;\n}\n\n[data-emoji-set="twitter"] .skin-tone-2 {\n background-color: #f3dfd0;\n}\n\n[data-emoji-set="twitter"] .skin-tone-3 {\n background-color: #eed3a8;\n}\n\n[data-emoji-set="twitter"] .skin-tone-4 {\n background-color: #cfad8d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-5 {\n background-color: #a8805d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-6 {\n background-color: #765542;\n}\n\n[data-emoji-set="google"] .skin-tone:after {\n box-shadow: inset 0 0 2px 2px rgba(0, 0, 0, .4);\n}\n\n[data-emoji-set="google"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="google"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="google"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="google"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="google"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="google"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n[data-emoji-set="facebook"] .skin-tone:after {\n border-color: rgba(0, 0, 0, .4);\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 4px #fff;\n}\n\n[data-emoji-set="facebook"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="facebook"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="facebook"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="facebook"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="facebook"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="facebook"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n'; +export { + $7adb23b0109cc36a$export$2d0294657ab35f1b as Data, + $331b4160623139bf$export$2e2bcd8739ae039 as Emoji, + $b22cfd0a55410b4f$export$2e2bcd8739ae039 as FrequentlyUsed, + $7adb23b0109cc36a$export$dbe3113d60765c1a as I18n, + $efa000751917694d$export$2e2bcd8739ae039 as Picker, + $e6eae5155b87f591$export$bcb25aa587e9cb13 as SafeFlags, + $c4d155af13ad4d4b$export$2e2bcd8739ae039 as SearchIndex, + $f72b75cf796873c7$export$2e2bcd8739ae039 as Store, + $693b183b0a78708f$export$5ef5574deca44bc0 as getEmojiDataFromNative, + $7adb23b0109cc36a$export$2cd8252107eb640b as init +}; diff --git a/bootstrap/ssr/assets/vendor-motion-yDK3iGlC.js b/bootstrap/ssr/assets/vendor-motion-yDK3iGlC.js new file mode 100644 index 00000000..454450ad --- /dev/null +++ b/bootstrap/ssr/assets/vendor-motion-yDK3iGlC.js @@ -0,0 +1,8068 @@ +import { r as reactExports, j as jsxRuntimeExports } from "./vendor-tiptap-DSw66HfW.js"; +const LayoutGroupContext = reactExports.createContext({}); +function useConstant(init) { + const ref = reactExports.useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; +} +const isBrowser$1 = typeof window !== "undefined"; +const useIsomorphicLayoutEffect = isBrowser$1 ? reactExports.useLayoutEffect : reactExports.useEffect; +const PresenceContext = /* @__PURE__ */ reactExports.createContext(null); +function addUniqueItem(arr, item) { + if (arr.indexOf(item) === -1) + arr.push(item); +} +function removeItem(arr, item) { + const index = arr.indexOf(item); + if (index > -1) + arr.splice(index, 1); +} +const clamp = (min, max, v) => { + if (v > max) + return max; + if (v < min) + return min; + return v; +}; +function formatErrorMessage(message, errorCode) { + return errorCode ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}` : message; +} +let warning = () => { +}; +let invariant = () => { +}; +if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") { + warning = (check, message, errorCode) => { + if (!check && typeof console !== "undefined") { + console.warn(formatErrorMessage(message, errorCode)); + } + }; + invariant = (check, message, errorCode) => { + if (!check) { + throw new Error(formatErrorMessage(message, errorCode)); + } + }; +} +const MotionGlobalConfig = {}; +const isNumericalString = (v) => /^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(v); +function isObject(value) { + return typeof value === "object" && value !== null; +} +const isZeroValueString = (v) => /^0[^.\s]+$/u.test(v); +// @__NO_SIDE_EFFECTS__ +function memo(callback) { + let result; + return () => { + if (result === void 0) + result = callback(); + return result; + }; +} +const noop = /* @__NO_SIDE_EFFECTS__ */ (any) => any; +const combineFunctions = (a, b) => (v) => b(a(v)); +const pipe = (...transformers) => transformers.reduce(combineFunctions); +const progress = /* @__NO_SIDE_EFFECTS__ */ (from, to, value) => { + const toFromDifference = to - from; + return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; +}; +class SubscriptionManager { + constructor() { + this.subscriptions = []; + } + add(handler) { + addUniqueItem(this.subscriptions, handler); + return () => removeItem(this.subscriptions, handler); + } + notify(a, b, c) { + const numSubscriptions = this.subscriptions.length; + if (!numSubscriptions) + return; + if (numSubscriptions === 1) { + this.subscriptions[0](a, b, c); + } else { + for (let i = 0; i < numSubscriptions; i++) { + const handler = this.subscriptions[i]; + handler && handler(a, b, c); + } + } + } + getSize() { + return this.subscriptions.length; + } + clear() { + this.subscriptions.length = 0; + } +} +const secondsToMilliseconds = /* @__NO_SIDE_EFFECTS__ */ (seconds) => seconds * 1e3; +const millisecondsToSeconds = /* @__NO_SIDE_EFFECTS__ */ (milliseconds) => milliseconds / 1e3; +function velocityPerSecond(velocity, frameDuration) { + return frameDuration ? velocity * (1e3 / frameDuration) : 0; +} +const warned = /* @__PURE__ */ new Set(); +function warnOnce(condition, message, errorCode) { + if (condition || warned.has(message)) + return; + console.warn(formatErrorMessage(message, errorCode)); + warned.add(message); +} +const calcBezier = (t, a1, a2) => (((1 - 3 * a2 + 3 * a1) * t + (3 * a2 - 6 * a1)) * t + 3 * a1) * t; +const subdivisionPrecision = 1e-7; +const subdivisionMaxIterations = 12; +function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { + let currentX; + let currentT; + let i = 0; + do { + currentT = lowerBound + (upperBound - lowerBound) / 2; + currentX = calcBezier(currentT, mX1, mX2) - x; + if (currentX > 0) { + upperBound = currentT; + } else { + lowerBound = currentT; + } + } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); + return currentT; +} +function cubicBezier(mX1, mY1, mX2, mY2) { + if (mX1 === mY1 && mX2 === mY2) + return noop; + const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2); + return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); +} +const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; +const reverseEasing = (easing) => (p) => 1 - easing(1 - p); +const backOut = /* @__PURE__ */ cubicBezier(0.33, 1.53, 0.69, 0.99); +const backIn = /* @__PURE__ */ reverseEasing(backOut); +const backInOut = /* @__PURE__ */ mirrorEasing(backIn); +const anticipate = (p) => p >= 1 ? 1 : (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); +const circIn = (p) => 1 - Math.sin(Math.acos(p)); +const circOut = reverseEasing(circIn); +const circInOut = mirrorEasing(circIn); +const easeIn = /* @__PURE__ */ cubicBezier(0.42, 0, 1, 1); +const easeOut = /* @__PURE__ */ cubicBezier(0, 0, 0.58, 1); +const easeInOut = /* @__PURE__ */ cubicBezier(0.42, 0, 0.58, 1); +const isEasingArray = (ease2) => { + return Array.isArray(ease2) && typeof ease2[0] !== "number"; +}; +const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number"; +const easingLookup = { + linear: noop, + easeIn, + easeInOut, + easeOut, + circIn, + circInOut, + circOut, + backIn, + backInOut, + backOut, + anticipate +}; +const isValidEasing = (easing) => { + return typeof easing === "string"; +}; +const easingDefinitionToFunction = (definition) => { + if (isBezierDefinition(definition)) { + invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`, "cubic-bezier-length"); + const [x1, y1, x2, y2] = definition; + return cubicBezier(x1, y1, x2, y2); + } else if (isValidEasing(definition)) { + invariant(easingLookup[definition] !== void 0, `Invalid easing type '${definition}'`, "invalid-easing-type"); + return easingLookup[definition]; + } + return definition; +}; +const stepsOrder = [ + "setup", + // Compute + "read", + // Read + "resolveKeyframes", + // Write/Read/Write/Read + "preUpdate", + // Compute + "update", + // Compute + "preRender", + // Compute + "render", + // Write + "postRender" + // Compute +]; +function createRenderStep(runNextFrame, stepName) { + let thisFrame = /* @__PURE__ */ new Set(); + let nextFrame = /* @__PURE__ */ new Set(); + let isProcessing = false; + let flushNextFrame = false; + const toKeepAlive = /* @__PURE__ */ new WeakSet(); + let latestFrameData = { + delta: 0, + timestamp: 0, + isProcessing: false + }; + function triggerCallback(callback) { + if (toKeepAlive.has(callback)) { + step.schedule(callback); + runNextFrame(); + } + callback(latestFrameData); + } + const step = { + /** + * Schedule a process to run on the next frame. + */ + schedule: (callback, keepAlive = false, immediate = false) => { + const addToCurrentFrame = immediate && isProcessing; + const queue = addToCurrentFrame ? thisFrame : nextFrame; + if (keepAlive) + toKeepAlive.add(callback); + queue.add(callback); + return callback; + }, + /** + * Cancel the provided callback from running on the next frame. + */ + cancel: (callback) => { + nextFrame.delete(callback); + toKeepAlive.delete(callback); + }, + /** + * Execute all schedule callbacks. + */ + process: (frameData2) => { + latestFrameData = frameData2; + if (isProcessing) { + flushNextFrame = true; + return; + } + isProcessing = true; + const prevFrame = thisFrame; + thisFrame = nextFrame; + nextFrame = prevFrame; + thisFrame.forEach(triggerCallback); + thisFrame.clear(); + isProcessing = false; + if (flushNextFrame) { + flushNextFrame = false; + step.process(frameData2); + } + } + }; + return step; +} +const maxElapsed = 40; +function createRenderBatcher(scheduleNextBatch, allowKeepAlive) { + let runNextFrame = false; + let useDefaultElapsed = true; + const state = { + delta: 0, + timestamp: 0, + isProcessing: false + }; + const flagRunNextFrame = () => runNextFrame = true; + const steps = stepsOrder.reduce((acc, key) => { + acc[key] = createRenderStep(flagRunNextFrame); + return acc; + }, {}); + const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender } = steps; + const processBatch = () => { + const useManualTiming = MotionGlobalConfig.useManualTiming; + const timestamp = useManualTiming ? state.timestamp : performance.now(); + runNextFrame = false; + if (!useManualTiming) { + state.delta = useDefaultElapsed ? 1e3 / 60 : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1); + } + state.timestamp = timestamp; + state.isProcessing = true; + setup.process(state); + read.process(state); + resolveKeyframes.process(state); + preUpdate.process(state); + update.process(state); + preRender.process(state); + render.process(state); + postRender.process(state); + state.isProcessing = false; + if (runNextFrame && allowKeepAlive) { + useDefaultElapsed = false; + scheduleNextBatch(processBatch); + } + }; + const wake = () => { + runNextFrame = true; + useDefaultElapsed = true; + if (!state.isProcessing) { + scheduleNextBatch(processBatch); + } + }; + const schedule = stepsOrder.reduce((acc, key) => { + const step = steps[key]; + acc[key] = (process2, keepAlive = false, immediate = false) => { + if (!runNextFrame) + wake(); + return step.schedule(process2, keepAlive, immediate); + }; + return acc; + }, {}); + const cancel = (process2) => { + for (let i = 0; i < stepsOrder.length; i++) { + steps[stepsOrder[i]].cancel(process2); + } + }; + return { schedule, cancel, state, steps }; +} +const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop, true); +let now; +function clearTime() { + now = void 0; +} +const time = { + now: () => { + if (now === void 0) { + time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming ? frameData.timestamp : performance.now()); + } + return now; + }, + set: (newTime) => { + now = newTime; + queueMicrotask(clearTime); + } +}; +const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token); +const isCSSVariableName = /* @__PURE__ */ checkStringStartsWith("--"); +const startsAsVariableToken = /* @__PURE__ */ checkStringStartsWith("var(--"); +const isCSSVariableToken = (value) => { + const startsWithToken = startsAsVariableToken(value); + if (!startsWithToken) + return false; + return singleCssVariableRegex.test(value.split("/*")[0].trim()); +}; +const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu; +function containsCSSVariable(value) { + if (typeof value !== "string") + return false; + return value.split("/*")[0].includes("var(--"); +} +const number = { + test: (v) => typeof v === "number", + parse: parseFloat, + transform: (v) => v +}; +const alpha = { + ...number, + transform: (v) => clamp(0, 1, v) +}; +const scale = { + ...number, + default: 1 +}; +const sanitize = (v) => Math.round(v * 1e5) / 1e5; +const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu; +function isNullish(v) { + return v == null; +} +const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu; +const isColorString = (type, testProp) => (v) => { + return Boolean(typeof v === "string" && singleColorRegex.test(v) && v.startsWith(type) || testProp && !isNullish(v) && Object.prototype.hasOwnProperty.call(v, testProp)); +}; +const splitColor = (aName, bName, cName) => (v) => { + if (typeof v !== "string") + return v; + const [a, b, c, alpha2] = v.match(floatRegex); + return { + [aName]: parseFloat(a), + [bName]: parseFloat(b), + [cName]: parseFloat(c), + alpha: alpha2 !== void 0 ? parseFloat(alpha2) : 1 + }; +}; +const clampRgbUnit = (v) => clamp(0, 255, v); +const rgbUnit = { + ...number, + transform: (v) => Math.round(clampRgbUnit(v)) +}; +const rgba = { + test: /* @__PURE__ */ isColorString("rgb", "red"), + parse: /* @__PURE__ */ splitColor("red", "green", "blue"), + transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + rgbUnit.transform(red) + ", " + rgbUnit.transform(green) + ", " + rgbUnit.transform(blue) + ", " + sanitize(alpha.transform(alpha$1)) + ")" +}; +function parseHex(v) { + let r = ""; + let g = ""; + let b = ""; + let a = ""; + if (v.length > 5) { + r = v.substring(1, 3); + g = v.substring(3, 5); + b = v.substring(5, 7); + a = v.substring(7, 9); + } else { + r = v.substring(1, 2); + g = v.substring(2, 3); + b = v.substring(3, 4); + a = v.substring(4, 5); + r += r; + g += g; + b += b; + a += a; + } + return { + red: parseInt(r, 16), + green: parseInt(g, 16), + blue: parseInt(b, 16), + alpha: a ? parseInt(a, 16) / 255 : 1 + }; +} +const hex = { + test: /* @__PURE__ */ isColorString("#"), + parse: parseHex, + transform: rgba.transform +}; +const createUnitType = /* @__NO_SIDE_EFFECTS__ */ (unit) => ({ + test: (v) => typeof v === "string" && v.endsWith(unit) && v.split(" ").length === 1, + parse: parseFloat, + transform: (v) => `${v}${unit}` +}); +const degrees = /* @__PURE__ */ createUnitType("deg"); +const percent = /* @__PURE__ */ createUnitType("%"); +const px = /* @__PURE__ */ createUnitType("px"); +const vh = /* @__PURE__ */ createUnitType("vh"); +const vw = /* @__PURE__ */ createUnitType("vw"); +const progressPercentage = /* @__PURE__ */ (() => ({ + ...percent, + parse: (v) => percent.parse(v) / 100, + transform: (v) => percent.transform(v * 100) +}))(); +const hsla = { + test: /* @__PURE__ */ isColorString("hsl", "hue"), + parse: /* @__PURE__ */ splitColor("hue", "saturation", "lightness"), + transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => { + return "hsla(" + Math.round(hue) + ", " + percent.transform(sanitize(saturation)) + ", " + percent.transform(sanitize(lightness)) + ", " + sanitize(alpha.transform(alpha$1)) + ")"; + } +}; +const color = { + test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v), + parse: (v) => { + if (rgba.test(v)) { + return rgba.parse(v); + } else if (hsla.test(v)) { + return hsla.parse(v); + } else { + return hex.parse(v); + } + }, + transform: (v) => { + return typeof v === "string" ? v : v.hasOwnProperty("red") ? rgba.transform(v) : hsla.transform(v); + }, + getAnimatableNone: (v) => { + const parsed = color.parse(v); + parsed.alpha = 0; + return color.transform(parsed); + } +}; +const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu; +function test(v) { + return isNaN(v) && typeof v === "string" && (v.match(floatRegex)?.length || 0) + (v.match(colorRegex)?.length || 0) > 0; +} +const NUMBER_TOKEN = "number"; +const COLOR_TOKEN = "color"; +const VAR_TOKEN = "var"; +const VAR_FUNCTION_TOKEN = "var("; +const SPLIT_TOKEN = "${}"; +const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu; +function analyseComplexValue(value) { + const originalValue = value.toString(); + const values = []; + const indexes = { + color: [], + number: [], + var: [] + }; + const types = []; + let i = 0; + const tokenised = originalValue.replace(complexRegex, (parsedValue) => { + if (color.test(parsedValue)) { + indexes.color.push(i); + types.push(COLOR_TOKEN); + values.push(color.parse(parsedValue)); + } else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) { + indexes.var.push(i); + types.push(VAR_TOKEN); + values.push(parsedValue); + } else { + indexes.number.push(i); + types.push(NUMBER_TOKEN); + values.push(parseFloat(parsedValue)); + } + ++i; + return SPLIT_TOKEN; + }); + const split = tokenised.split(SPLIT_TOKEN); + return { values, split, indexes, types }; +} +function parseComplexValue(v) { + return analyseComplexValue(v).values; +} +function buildTransformer({ split, types }) { + const numSections = split.length; + return (v) => { + let output = ""; + for (let i = 0; i < numSections; i++) { + output += split[i]; + if (v[i] !== void 0) { + const type = types[i]; + if (type === NUMBER_TOKEN) { + output += sanitize(v[i]); + } else if (type === COLOR_TOKEN) { + output += color.transform(v[i]); + } else { + output += v[i]; + } + } + } + return output; + }; +} +function createTransformer(source) { + return buildTransformer(analyseComplexValue(source)); +} +const convertNumbersToZero = (v) => typeof v === "number" ? 0 : color.test(v) ? color.getAnimatableNone(v) : v; +const convertToZero = (value, splitBefore) => { + if (typeof value === "number") { + return splitBefore?.trim().endsWith("/") ? value : 0; + } + return convertNumbersToZero(value); +}; +function getAnimatableNone$1(v) { + const info = analyseComplexValue(v); + const transformer = buildTransformer(info); + return transformer(info.values.map((value, i) => convertToZero(value, info.split[i]))); +} +const complex = { + test, + parse: parseComplexValue, + createTransformer, + getAnimatableNone: getAnimatableNone$1 +}; +function hueToRgb(p, q, t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * (2 / 3 - t) * 6; + return p; +} +function hslaToRgba({ hue, saturation, lightness, alpha: alpha2 }) { + hue /= 360; + saturation /= 100; + lightness /= 100; + let red = 0; + let green = 0; + let blue = 0; + if (!saturation) { + red = green = blue = lightness; + } else { + const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; + const p = 2 * lightness - q; + red = hueToRgb(p, q, hue + 1 / 3); + green = hueToRgb(p, q, hue); + blue = hueToRgb(p, q, hue - 1 / 3); + } + return { + red: Math.round(red * 255), + green: Math.round(green * 255), + blue: Math.round(blue * 255), + alpha: alpha2 + }; +} +function mixImmediate(a, b) { + return (p) => p > 0 ? b : a; +} +const mixNumber$1 = (from, to, progress2) => { + return from + (to - from) * progress2; +}; +const mixLinearColor = (from, to, v) => { + const fromExpo = from * from; + const expo = v * (to * to - fromExpo) + fromExpo; + return expo < 0 ? 0 : Math.sqrt(expo); +}; +const colorTypes = [hex, rgba, hsla]; +const getColorType = (v) => colorTypes.find((type) => type.test(v)); +function asRGBA(color2) { + const type = getColorType(color2); + warning(Boolean(type), `'${color2}' is not an animatable color. Use the equivalent color code instead.`, "color-not-animatable"); + if (!Boolean(type)) + return false; + let model = type.parse(color2); + if (type === hsla) { + model = hslaToRgba(model); + } + return model; +} +const mixColor = (from, to) => { + const fromRGBA = asRGBA(from); + const toRGBA = asRGBA(to); + if (!fromRGBA || !toRGBA) { + return mixImmediate(from, to); + } + const blended = { ...fromRGBA }; + return (v) => { + blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v); + blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v); + blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v); + blended.alpha = mixNumber$1(fromRGBA.alpha, toRGBA.alpha, v); + return rgba.transform(blended); + }; +}; +const invisibleValues = /* @__PURE__ */ new Set(["none", "hidden"]); +function mixVisibility(origin, target) { + if (invisibleValues.has(origin)) { + return (p) => p <= 0 ? origin : target; + } else { + return (p) => p >= 1 ? target : origin; + } +} +function mixNumber(a, b) { + return (p) => mixNumber$1(a, b, p); +} +function getMixer(a) { + if (typeof a === "number") { + return mixNumber; + } else if (typeof a === "string") { + return isCSSVariableToken(a) ? mixImmediate : color.test(a) ? mixColor : mixComplex; + } else if (Array.isArray(a)) { + return mixArray; + } else if (typeof a === "object") { + return color.test(a) ? mixColor : mixObject; + } + return mixImmediate; +} +function mixArray(a, b) { + const output = [...a]; + const numValues = output.length; + const blendValue = a.map((v, i) => getMixer(v)(v, b[i])); + return (p) => { + for (let i = 0; i < numValues; i++) { + output[i] = blendValue[i](p); + } + return output; + }; +} +function mixObject(a, b) { + const output = { ...a, ...b }; + const blendValue = {}; + for (const key in output) { + if (a[key] !== void 0 && b[key] !== void 0) { + blendValue[key] = getMixer(a[key])(a[key], b[key]); + } + } + return (v) => { + for (const key in blendValue) { + output[key] = blendValue[key](v); + } + return output; + }; +} +function matchOrder(origin, target) { + const orderedOrigin = []; + const pointers = { color: 0, var: 0, number: 0 }; + for (let i = 0; i < target.values.length; i++) { + const type = target.types[i]; + const originIndex = origin.indexes[type][pointers[type]]; + const originValue = origin.values[originIndex] ?? 0; + orderedOrigin[i] = originValue; + pointers[type]++; + } + return orderedOrigin; +} +const mixComplex = (origin, target) => { + const template = complex.createTransformer(target); + const originStats = analyseComplexValue(origin); + const targetStats = analyseComplexValue(target); + const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length && originStats.indexes.color.length === targetStats.indexes.color.length && originStats.indexes.number.length >= targetStats.indexes.number.length; + if (canInterpolate) { + if (invisibleValues.has(origin) && !targetStats.values.length || invisibleValues.has(target) && !originStats.values.length) { + return mixVisibility(origin, target); + } + return pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template); + } else { + warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`, "complex-values-different"); + return mixImmediate(origin, target); + } +}; +function mix(from, to, p) { + if (typeof from === "number" && typeof to === "number" && typeof p === "number") { + return mixNumber$1(from, to, p); + } + const mixer = getMixer(from); + return mixer(from, to); +} +const frameloopDriver = (update) => { + const passTimestamp = ({ timestamp }) => update(timestamp); + return { + start: (keepAlive = true) => frame.update(passTimestamp, keepAlive), + stop: () => cancelFrame(passTimestamp), + /** + * If we're processing this frame we can use the + * framelocked timestamp to keep things in sync. + */ + now: () => frameData.isProcessing ? frameData.timestamp : time.now() + }; +}; +const generateLinearEasing = (easing, duration, resolution = 10) => { + let points = ""; + const numPoints = Math.max(Math.round(duration / resolution), 2); + for (let i = 0; i < numPoints; i++) { + points += Math.round(easing(i / (numPoints - 1)) * 1e4) / 1e4 + ", "; + } + return `linear(${points.substring(0, points.length - 2)})`; +}; +const maxGeneratorDuration = 2e4; +function calcGeneratorDuration(generator) { + let duration = 0; + const timeStep = 50; + let state = generator.next(duration); + while (!state.done && duration < maxGeneratorDuration) { + duration += timeStep; + state = generator.next(duration); + } + return duration >= maxGeneratorDuration ? Infinity : duration; +} +function createGeneratorEasing(options, scale2 = 100, createGenerator) { + const generator = createGenerator({ ...options, keyframes: [0, scale2] }); + const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration); + return { + type: "keyframes", + ease: (progress2) => { + return generator.next(duration * progress2).value / scale2; + }, + duration: /* @__PURE__ */ millisecondsToSeconds(duration) + }; +} +const springDefaults = { + // Default spring physics + stiffness: 100, + damping: 10, + mass: 1, + velocity: 0, + // Default duration/bounce-based options + duration: 800, + // in ms + bounce: 0.3, + visualDuration: 0.3, + // in seconds + // Rest thresholds + restSpeed: { + granular: 0.01, + default: 2 + }, + restDelta: { + granular: 5e-3, + default: 0.5 + }, + // Limits + minDuration: 0.01, + // in seconds + maxDuration: 10, + // in seconds + minDamping: 0.05, + maxDamping: 1 +}; +function calcAngularFreq(undampedFreq, dampingRatio) { + return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); +} +const rootIterations = 12; +function approximateRoot(envelope, derivative, initialGuess) { + let result = initialGuess; + for (let i = 1; i < rootIterations; i++) { + result = result - envelope(result) / derivative(result); + } + return result; +} +const safeMin = 1e-3; +function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass }) { + let envelope; + let derivative; + warning(duration <= /* @__PURE__ */ secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit"); + let dampingRatio = 1 - bounce; + dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio); + duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, /* @__PURE__ */ millisecondsToSeconds(duration)); + if (dampingRatio < 1) { + envelope = (undampedFreq2) => { + const exponentialDecay = undampedFreq2 * dampingRatio; + const delta = exponentialDecay * duration; + const a = exponentialDecay - velocity; + const b = calcAngularFreq(undampedFreq2, dampingRatio); + const c = Math.exp(-delta); + return safeMin - a / b * c; + }; + derivative = (undampedFreq2) => { + const exponentialDecay = undampedFreq2 * dampingRatio; + const delta = exponentialDecay * duration; + const d = delta * velocity + velocity; + const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq2, 2) * duration; + const f = Math.exp(-delta); + const g = calcAngularFreq(Math.pow(undampedFreq2, 2), dampingRatio); + const factor = -envelope(undampedFreq2) + safeMin > 0 ? -1 : 1; + return factor * ((d - e) * f) / g; + }; + } else { + envelope = (undampedFreq2) => { + const a = Math.exp(-undampedFreq2 * duration); + const b = (undampedFreq2 - velocity) * duration + 1; + return -safeMin + a * b; + }; + derivative = (undampedFreq2) => { + const a = Math.exp(-undampedFreq2 * duration); + const b = (velocity - undampedFreq2) * (duration * duration); + return a * b; + }; + } + const initialGuess = 5 / duration; + const undampedFreq = approximateRoot(envelope, derivative, initialGuess); + duration = /* @__PURE__ */ secondsToMilliseconds(duration); + if (isNaN(undampedFreq)) { + return { + stiffness: springDefaults.stiffness, + damping: springDefaults.damping, + duration + }; + } else { + const stiffness = Math.pow(undampedFreq, 2) * mass; + return { + stiffness, + damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), + duration + }; + } +} +const durationKeys = ["duration", "bounce"]; +const physicsKeys = ["stiffness", "damping", "mass"]; +function isSpringType(options, keys) { + return keys.some((key) => options[key] !== void 0); +} +function getSpringOptions(options) { + let springOptions = { + velocity: springDefaults.velocity, + stiffness: springDefaults.stiffness, + damping: springDefaults.damping, + mass: springDefaults.mass, + isResolvedFromDuration: false, + ...options + }; + if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) { + springOptions.velocity = 0; + if (options.visualDuration) { + const visualDuration = options.visualDuration; + const root = 2 * Math.PI / (visualDuration * 1.2); + const stiffness = root * root; + const damping = 2 * clamp(0.05, 1, 1 - (options.bounce || 0)) * Math.sqrt(stiffness); + springOptions = { + ...springOptions, + mass: springDefaults.mass, + stiffness, + damping + }; + } else { + const derived = findSpring({ ...options, velocity: 0 }); + springOptions = { + ...springOptions, + ...derived, + mass: springDefaults.mass + }; + springOptions.isResolvedFromDuration = true; + } + } + return springOptions; +} +function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) { + const options = typeof optionsOrVisualDuration !== "object" ? { + visualDuration: optionsOrVisualDuration, + keyframes: [0, 1], + bounce + } : optionsOrVisualDuration; + let { restSpeed, restDelta } = options; + const origin = options.keyframes[0]; + const target = options.keyframes[options.keyframes.length - 1]; + const state = { done: false, value: origin }; + const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration } = getSpringOptions({ + ...options, + velocity: -/* @__PURE__ */ millisecondsToSeconds(options.velocity || 0) + }); + const initialVelocity = velocity || 0; + const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); + const initialDelta = target - origin; + const undampedAngularFreq = /* @__PURE__ */ millisecondsToSeconds(Math.sqrt(stiffness / mass)); + const isGranularScale = Math.abs(initialDelta) < 5; + restSpeed || (restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default); + restDelta || (restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default); + let resolveSpring; + let resolveVelocity; + let angularFreq; + let A; + let sinCoeff; + let cosCoeff; + if (dampingRatio < 1) { + angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); + A = (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq; + resolveSpring = (t) => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return target - envelope * (A * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); + }; + sinCoeff = dampingRatio * undampedAngularFreq * A + initialDelta * angularFreq; + cosCoeff = dampingRatio * undampedAngularFreq * initialDelta - A * angularFreq; + resolveVelocity = (t) => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return envelope * (sinCoeff * Math.sin(angularFreq * t) + cosCoeff * Math.cos(angularFreq * t)); + }; + } else if (dampingRatio === 1) { + resolveSpring = (t) => target - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t); + const C = initialVelocity + undampedAngularFreq * initialDelta; + resolveVelocity = (t) => Math.exp(-undampedAngularFreq * t) * (undampedAngularFreq * C * t - initialVelocity); + } else { + const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); + resolveSpring = (t) => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + const freqForT = Math.min(dampedAngularFreq * t, 300); + return target - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq; + }; + const P = (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / dampedAngularFreq; + const sinhCoeff = dampingRatio * undampedAngularFreq * P - initialDelta * dampedAngularFreq; + const coshCoeff = dampingRatio * undampedAngularFreq * initialDelta - P * dampedAngularFreq; + resolveVelocity = (t) => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + const freqForT = Math.min(dampedAngularFreq * t, 300); + return envelope * (sinhCoeff * Math.sinh(freqForT) + coshCoeff * Math.cosh(freqForT)); + }; + } + const generator = { + calculatedDuration: isResolvedFromDuration ? duration || null : null, + velocity: (t) => /* @__PURE__ */ secondsToMilliseconds(resolveVelocity(t)), + next: (t) => { + if (!isResolvedFromDuration && dampingRatio < 1) { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + const sin = Math.sin(angularFreq * t); + const cos = Math.cos(angularFreq * t); + const current2 = target - envelope * (A * sin + initialDelta * cos); + const currentVelocity = /* @__PURE__ */ secondsToMilliseconds(envelope * (sinCoeff * sin + cosCoeff * cos)); + state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current2) <= restDelta; + state.value = state.done ? target : current2; + return state; + } + const current = resolveSpring(t); + if (!isResolvedFromDuration) { + const currentVelocity = /* @__PURE__ */ secondsToMilliseconds(resolveVelocity(t)); + state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current) <= restDelta; + } else { + state.done = t >= duration; + } + state.value = state.done ? target : current; + return state; + }, + toString: () => { + const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration); + const easing = generateLinearEasing((progress2) => generator.next(calculatedDuration * progress2).value, calculatedDuration, 30); + return calculatedDuration + "ms " + easing; + }, + toTransition: () => { + } + }; + return generator; +} +spring.applyToOptions = (options) => { + const generatorOptions = createGeneratorEasing(options, 100, spring); + options.ease = generatorOptions.ease; + options.duration = /* @__PURE__ */ secondsToMilliseconds(generatorOptions.duration); + options.type = "keyframes"; + return options; +}; +const velocitySampleDuration = 5; +function getGeneratorVelocity(resolveValue, t, current) { + const prevT = Math.max(t - velocitySampleDuration, 0); + return velocityPerSecond(current - resolveValue(prevT), t - prevT); +} +function inertia({ keyframes: keyframes2, velocity = 0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed }) { + const origin = keyframes2[0]; + const state = { + done: false, + value: origin + }; + const isOutOfBounds = (v) => min !== void 0 && v < min || max !== void 0 && v > max; + const nearestBoundary = (v) => { + if (min === void 0) + return max; + if (max === void 0) + return min; + return Math.abs(min - v) < Math.abs(max - v) ? min : max; + }; + let amplitude = power * velocity; + const ideal = origin + amplitude; + const target = modifyTarget === void 0 ? ideal : modifyTarget(ideal); + if (target !== ideal) + amplitude = target - origin; + const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant); + const calcLatest = (t) => target + calcDelta(t); + const applyFriction = (t) => { + const delta = calcDelta(t); + const latest = calcLatest(t); + state.done = Math.abs(delta) <= restDelta; + state.value = state.done ? target : latest; + }; + let timeReachedBoundary; + let spring$1; + const checkCatchBoundary = (t) => { + if (!isOutOfBounds(state.value)) + return; + timeReachedBoundary = t; + spring$1 = spring({ + keyframes: [state.value, nearestBoundary(state.value)], + velocity: getGeneratorVelocity(calcLatest, t, state.value), + // TODO: This should be passing * 1000 + damping: bounceDamping, + stiffness: bounceStiffness, + restDelta, + restSpeed + }); + }; + checkCatchBoundary(0); + return { + calculatedDuration: null, + next: (t) => { + let hasUpdatedFrame = false; + if (!spring$1 && timeReachedBoundary === void 0) { + hasUpdatedFrame = true; + applyFriction(t); + checkCatchBoundary(t); + } + if (timeReachedBoundary !== void 0 && t >= timeReachedBoundary) { + return spring$1.next(t - timeReachedBoundary); + } else { + !hasUpdatedFrame && applyFriction(t); + return state; + } + } + }; +} +function createMixers(output, ease2, customMixer) { + const mixers = []; + const mixerFactory = customMixer || MotionGlobalConfig.mix || mix; + const numMixers = output.length - 1; + for (let i = 0; i < numMixers; i++) { + let mixer = mixerFactory(output[i], output[i + 1]); + if (ease2) { + const easingFunction = Array.isArray(ease2) ? ease2[i] || noop : ease2; + mixer = pipe(easingFunction, mixer); + } + mixers.push(mixer); + } + return mixers; +} +function interpolate(input, output, { clamp: isClamp = true, ease: ease2, mixer } = {}) { + const inputLength = input.length; + invariant(inputLength === output.length, "Both input and output ranges must be the same length", "range-length"); + if (inputLength === 1) + return () => output[0]; + if (inputLength === 2 && output[0] === output[1]) + return () => output[1]; + const isZeroDeltaRange = input[0] === input[1]; + if (input[0] > input[inputLength - 1]) { + input = [...input].reverse(); + output = [...output].reverse(); + } + const mixers = createMixers(output, ease2, mixer); + const numMixers = mixers.length; + const interpolator = (v) => { + if (isZeroDeltaRange && v < input[0]) + return output[0]; + let i = 0; + if (numMixers > 1) { + for (; i < input.length - 2; i++) { + if (v < input[i + 1]) + break; + } + } + const progressInRange = /* @__PURE__ */ progress(input[i], input[i + 1], v); + return mixers[i](progressInRange); + }; + return isClamp ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator; +} +function fillOffset(offset, remaining) { + const min = offset[offset.length - 1]; + for (let i = 1; i <= remaining; i++) { + const offsetProgress = /* @__PURE__ */ progress(0, remaining, i); + offset.push(mixNumber$1(min, 1, offsetProgress)); + } +} +function defaultOffset(arr) { + const offset = [0]; + fillOffset(offset, arr.length - 1); + return offset; +} +function convertOffsetToTimes(offset, duration) { + return offset.map((o) => o * duration); +} +function defaultEasing(values, easing) { + return values.map(() => easing || easeInOut).splice(0, values.length - 1); +} +function keyframes({ duration = 300, keyframes: keyframeValues, times, ease: ease2 = "easeInOut" }) { + const easingFunctions = isEasingArray(ease2) ? ease2.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease2); + const state = { + done: false, + value: keyframeValues[0] + }; + const absoluteTimes = convertOffsetToTimes( + // Only use the provided offsets if they're the correct length + // TODO Maybe we should warn here if there's a length mismatch + times && times.length === keyframeValues.length ? times : defaultOffset(keyframeValues), + duration + ); + const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, { + ease: Array.isArray(easingFunctions) ? easingFunctions : defaultEasing(keyframeValues, easingFunctions) + }); + return { + calculatedDuration: duration, + next: (t) => { + state.value = mapTimeToKeyframe(t); + state.done = t >= duration; + return state; + } + }; +} +const isNotNull = (value) => value !== null; +function getFinalKeyframe(keyframes2, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) { + const resolvedKeyframes = keyframes2.filter(isNotNull); + const useFirstKeyframe = speed < 0 || repeat && repeatType !== "loop" && repeat % 2 === 1; + const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1; + return !index || finalKeyframe === void 0 ? resolvedKeyframes[index] : finalKeyframe; +} +const transitionTypeMap = { + decay: inertia, + inertia, + tween: keyframes, + keyframes, + spring +}; +function replaceTransitionType(transition) { + if (typeof transition.type === "string") { + transition.type = transitionTypeMap[transition.type]; + } +} +class WithPromise { + constructor() { + this.updateFinished(); + } + get finished() { + return this._finished; + } + updateFinished() { + this._finished = new Promise((resolve) => { + this.resolve = resolve; + }); + } + notifyFinished() { + this.resolve(); + } + /** + * Allows the animation to be awaited. + * + * @deprecated Use `finished` instead. + */ + then(onResolve, onReject) { + return this.finished.then(onResolve, onReject); + } +} +const percentToProgress = (percent2) => percent2 / 100; +class JSAnimation extends WithPromise { + constructor(options) { + super(); + this.state = "idle"; + this.startTime = null; + this.isStopped = false; + this.currentTime = 0; + this.holdTime = null; + this.playbackSpeed = 1; + this.delayState = { + done: false, + value: void 0 + }; + this.stop = () => { + const { motionValue: motionValue2 } = this.options; + if (motionValue2 && motionValue2.updatedAt !== time.now()) { + this.tick(time.now()); + } + this.isStopped = true; + if (this.state === "idle") + return; + this.teardown(); + this.options.onStop?.(); + }; + this.options = options; + this.initAnimation(); + this.play(); + if (options.autoplay === false) + this.pause(); + } + initAnimation() { + const { options } = this; + replaceTransitionType(options); + const { type = keyframes, repeat = 0, repeatDelay = 0, repeatType, velocity = 0 } = options; + let { keyframes: keyframes$1 } = options; + const generatorFactory = type || keyframes; + if (process.env.NODE_ENV !== "production" && generatorFactory !== keyframes) { + invariant(keyframes$1.length <= 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`, "spring-two-frames"); + } + if (generatorFactory !== keyframes && typeof keyframes$1[0] !== "number") { + this.mixKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1])); + keyframes$1 = [0, 100]; + } + const generator = generatorFactory({ ...options, keyframes: keyframes$1 }); + if (repeatType === "mirror") { + this.mirroredGenerator = generatorFactory({ + ...options, + keyframes: [...keyframes$1].reverse(), + velocity: -velocity + }); + } + if (generator.calculatedDuration === null) { + generator.calculatedDuration = calcGeneratorDuration(generator); + } + const { calculatedDuration } = generator; + this.calculatedDuration = calculatedDuration; + this.resolvedDuration = calculatedDuration + repeatDelay; + this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay; + this.generator = generator; + } + updateTime(timestamp) { + const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed; + if (this.holdTime !== null) { + this.currentTime = this.holdTime; + } else { + this.currentTime = animationTime; + } + } + tick(timestamp, sample = false) { + const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration } = this; + if (this.startTime === null) + return generator.next(0); + const { delay: delay2 = 0, keyframes: keyframes2, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe } = this.options; + if (this.speed > 0) { + this.startTime = Math.min(this.startTime, timestamp); + } else if (this.speed < 0) { + this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime); + } + if (sample) { + this.currentTime = timestamp; + } else { + this.updateTime(timestamp); + } + const timeWithoutDelay = this.currentTime - delay2 * (this.playbackSpeed >= 0 ? 1 : -1); + const isInDelayPhase = this.playbackSpeed >= 0 ? timeWithoutDelay < 0 : timeWithoutDelay > totalDuration; + this.currentTime = Math.max(timeWithoutDelay, 0); + if (this.state === "finished" && this.holdTime === null) { + this.currentTime = totalDuration; + } + let elapsed = this.currentTime; + let frameGenerator = generator; + if (repeat) { + const progress2 = Math.min(this.currentTime, totalDuration) / resolvedDuration; + let currentIteration = Math.floor(progress2); + let iterationProgress = progress2 % 1; + if (!iterationProgress && progress2 >= 1) { + iterationProgress = 1; + } + iterationProgress === 1 && currentIteration--; + currentIteration = Math.min(currentIteration, repeat + 1); + const isOddIteration = Boolean(currentIteration % 2); + if (isOddIteration) { + if (repeatType === "reverse") { + iterationProgress = 1 - iterationProgress; + if (repeatDelay) { + iterationProgress -= repeatDelay / resolvedDuration; + } + } else if (repeatType === "mirror") { + frameGenerator = mirroredGenerator; + } + } + elapsed = clamp(0, 1, iterationProgress) * resolvedDuration; + } + let state; + if (isInDelayPhase) { + this.delayState.value = keyframes2[0]; + state = this.delayState; + } else { + state = frameGenerator.next(elapsed); + } + if (mixKeyframes && !isInDelayPhase) { + state.value = mixKeyframes(state.value); + } + let { done } = state; + if (!isInDelayPhase && calculatedDuration !== null) { + done = this.playbackSpeed >= 0 ? this.currentTime >= totalDuration : this.currentTime <= 0; + } + const isAnimationFinished = this.holdTime === null && (this.state === "finished" || this.state === "running" && done); + if (isAnimationFinished && type !== inertia) { + state.value = getFinalKeyframe(keyframes2, this.options, finalKeyframe, this.speed); + } + if (onUpdate) { + onUpdate(state.value); + } + if (isAnimationFinished) { + this.finish(); + } + return state; + } + /** + * Allows the returned animation to be awaited or promise-chained. Currently + * resolves when the animation finishes at all but in a future update could/should + * reject if its cancels. + */ + then(resolve, reject) { + return this.finished.then(resolve, reject); + } + get duration() { + return /* @__PURE__ */ millisecondsToSeconds(this.calculatedDuration); + } + get iterationDuration() { + const { delay: delay2 = 0 } = this.options || {}; + return this.duration + /* @__PURE__ */ millisecondsToSeconds(delay2); + } + get time() { + return /* @__PURE__ */ millisecondsToSeconds(this.currentTime); + } + set time(newTime) { + newTime = /* @__PURE__ */ secondsToMilliseconds(newTime); + this.currentTime = newTime; + if (this.startTime === null || this.holdTime !== null || this.playbackSpeed === 0) { + this.holdTime = newTime; + } else if (this.driver) { + this.startTime = this.driver.now() - newTime / this.playbackSpeed; + } + if (this.driver) { + this.driver.start(false); + } else { + this.startTime = 0; + this.state = "paused"; + this.holdTime = newTime; + this.tick(newTime); + } + } + /** + * Returns the generator's velocity at the current time in units/second. + * Uses the analytical derivative when available (springs), avoiding + * the MotionValue's frame-dependent velocity estimation. + */ + getGeneratorVelocity() { + const t = this.currentTime; + if (t <= 0) + return this.options.velocity || 0; + if (this.generator.velocity) { + return this.generator.velocity(t); + } + const current = this.generator.next(t).value; + return getGeneratorVelocity((s) => this.generator.next(s).value, t, current); + } + get speed() { + return this.playbackSpeed; + } + set speed(newSpeed) { + const hasChanged = this.playbackSpeed !== newSpeed; + if (hasChanged && this.driver) { + this.updateTime(time.now()); + } + this.playbackSpeed = newSpeed; + if (hasChanged && this.driver) { + this.time = /* @__PURE__ */ millisecondsToSeconds(this.currentTime); + } + } + play() { + if (this.isStopped) + return; + const { driver = frameloopDriver, startTime } = this.options; + if (!this.driver) { + this.driver = driver((timestamp) => this.tick(timestamp)); + } + this.options.onPlay?.(); + const now2 = this.driver.now(); + if (this.state === "finished") { + this.updateFinished(); + this.startTime = now2; + } else if (this.holdTime !== null) { + this.startTime = now2 - this.holdTime; + } else if (!this.startTime) { + this.startTime = startTime ?? now2; + } + if (this.state === "finished" && this.speed < 0) { + this.startTime += this.calculatedDuration; + } + this.holdTime = null; + this.state = "running"; + this.driver.start(); + } + pause() { + this.state = "paused"; + this.updateTime(time.now()); + this.holdTime = this.currentTime; + } + complete() { + if (this.state !== "running") { + this.play(); + } + this.state = "finished"; + this.holdTime = null; + } + finish() { + this.notifyFinished(); + this.teardown(); + this.state = "finished"; + this.options.onComplete?.(); + } + cancel() { + this.holdTime = null; + this.startTime = 0; + this.tick(0); + this.teardown(); + this.options.onCancel?.(); + } + teardown() { + this.state = "idle"; + this.stopDriver(); + this.startTime = this.holdTime = null; + } + stopDriver() { + if (!this.driver) + return; + this.driver.stop(); + this.driver = void 0; + } + sample(sampleTime) { + this.startTime = 0; + return this.tick(sampleTime, true); + } + attachTimeline(timeline) { + if (this.options.allowFlatten) { + this.options.type = "keyframes"; + this.options.ease = "linear"; + this.initAnimation(); + } + this.driver?.stop(); + return timeline.observe(this); + } +} +function fillWildcards(keyframes2) { + for (let i = 1; i < keyframes2.length; i++) { + keyframes2[i] ?? (keyframes2[i] = keyframes2[i - 1]); + } +} +const radToDeg = (rad) => rad * 180 / Math.PI; +const rotate = (v) => { + const angle = radToDeg(Math.atan2(v[1], v[0])); + return rebaseAngle(angle); +}; +const matrix2dParsers = { + x: 4, + y: 5, + translateX: 4, + translateY: 5, + scaleX: 0, + scaleY: 3, + scale: (v) => (Math.abs(v[0]) + Math.abs(v[3])) / 2, + rotate, + rotateZ: rotate, + skewX: (v) => radToDeg(Math.atan(v[1])), + skewY: (v) => radToDeg(Math.atan(v[2])), + skew: (v) => (Math.abs(v[1]) + Math.abs(v[2])) / 2 +}; +const rebaseAngle = (angle) => { + angle = angle % 360; + if (angle < 0) + angle += 360; + return angle; +}; +const rotateZ = rotate; +const scaleX = (v) => Math.sqrt(v[0] * v[0] + v[1] * v[1]); +const scaleY = (v) => Math.sqrt(v[4] * v[4] + v[5] * v[5]); +const matrix3dParsers = { + x: 12, + y: 13, + z: 14, + translateX: 12, + translateY: 13, + translateZ: 14, + scaleX, + scaleY, + scale: (v) => (scaleX(v) + scaleY(v)) / 2, + rotateX: (v) => rebaseAngle(radToDeg(Math.atan2(v[6], v[5]))), + rotateY: (v) => rebaseAngle(radToDeg(Math.atan2(-v[2], v[0]))), + rotateZ, + rotate: rotateZ, + skewX: (v) => radToDeg(Math.atan(v[4])), + skewY: (v) => radToDeg(Math.atan(v[1])), + skew: (v) => (Math.abs(v[1]) + Math.abs(v[4])) / 2 +}; +function defaultTransformValue(name) { + return name.includes("scale") ? 1 : 0; +} +function parseValueFromTransform(transform, name) { + if (!transform || transform === "none") { + return defaultTransformValue(name); + } + const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u); + let parsers; + let match; + if (matrix3dMatch) { + parsers = matrix3dParsers; + match = matrix3dMatch; + } else { + const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u); + parsers = matrix2dParsers; + match = matrix2dMatch; + } + if (!match) { + return defaultTransformValue(name); + } + const valueParser = parsers[name]; + const values = match[1].split(",").map(convertTransformToNumber); + return typeof valueParser === "function" ? valueParser(values) : values[valueParser]; +} +const readTransformValue = (instance, name) => { + const { transform = "none" } = getComputedStyle(instance); + return parseValueFromTransform(transform, name); +}; +function convertTransformToNumber(value) { + return parseFloat(value.trim()); +} +const transformPropOrder = [ + "transformPerspective", + "x", + "y", + "z", + "translateX", + "translateY", + "translateZ", + "scale", + "scaleX", + "scaleY", + "rotate", + "rotateX", + "rotateY", + "rotateZ", + "skew", + "skewX", + "skewY" +]; +const transformProps = /* @__PURE__ */ (() => new Set(transformPropOrder))(); +const isNumOrPxType = (v) => v === number || v === px; +const transformKeys = /* @__PURE__ */ new Set(["x", "y", "z"]); +const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key)); +function removeNonTranslationalTransform(visualElement) { + const removedTransforms = []; + nonTranslationalTransformKeys.forEach((key) => { + const value = visualElement.getValue(key); + if (value !== void 0) { + removedTransforms.push([key, value.get()]); + value.set(key.startsWith("scale") ? 1 : 0); + } + }); + return removedTransforms; +} +const positionalValues = { + // Dimensions + width: ({ x }, { paddingLeft = "0", paddingRight = "0", boxSizing }) => { + const width = x.max - x.min; + return boxSizing === "border-box" ? width : width - parseFloat(paddingLeft) - parseFloat(paddingRight); + }, + height: ({ y }, { paddingTop = "0", paddingBottom = "0", boxSizing }) => { + const height = y.max - y.min; + return boxSizing === "border-box" ? height : height - parseFloat(paddingTop) - parseFloat(paddingBottom); + }, + top: (_bbox, { top }) => parseFloat(top), + left: (_bbox, { left }) => parseFloat(left), + bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min), + right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min), + // Transform + x: (_bbox, { transform }) => parseValueFromTransform(transform, "x"), + y: (_bbox, { transform }) => parseValueFromTransform(transform, "y") +}; +positionalValues.translateX = positionalValues.x; +positionalValues.translateY = positionalValues.y; +const toResolve = /* @__PURE__ */ new Set(); +let isScheduled = false; +let anyNeedsMeasurement = false; +let isForced = false; +function measureAllKeyframes() { + if (anyNeedsMeasurement) { + const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement); + const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element)); + const transformsToRestore = /* @__PURE__ */ new Map(); + elementsToMeasure.forEach((element) => { + const removedTransforms = removeNonTranslationalTransform(element); + if (!removedTransforms.length) + return; + transformsToRestore.set(element, removedTransforms); + element.render(); + }); + resolversToMeasure.forEach((resolver) => resolver.measureInitialState()); + elementsToMeasure.forEach((element) => { + element.render(); + const restore = transformsToRestore.get(element); + if (restore) { + restore.forEach(([key, value]) => { + element.getValue(key)?.set(value); + }); + } + }); + resolversToMeasure.forEach((resolver) => resolver.measureEndState()); + resolversToMeasure.forEach((resolver) => { + if (resolver.suspendedScrollY !== void 0) { + window.scrollTo(0, resolver.suspendedScrollY); + } + }); + } + anyNeedsMeasurement = false; + isScheduled = false; + toResolve.forEach((resolver) => resolver.complete(isForced)); + toResolve.clear(); +} +function readAllKeyframes() { + toResolve.forEach((resolver) => { + resolver.readKeyframes(); + if (resolver.needsMeasurement) { + anyNeedsMeasurement = true; + } + }); +} +function flushKeyframeResolvers() { + isForced = true; + readAllKeyframes(); + measureAllKeyframes(); + isForced = false; +} +class KeyframeResolver { + constructor(unresolvedKeyframes, onComplete, name, motionValue2, element, isAsync = false) { + this.state = "pending"; + this.isAsync = false; + this.needsMeasurement = false; + this.unresolvedKeyframes = [...unresolvedKeyframes]; + this.onComplete = onComplete; + this.name = name; + this.motionValue = motionValue2; + this.element = element; + this.isAsync = isAsync; + } + scheduleResolve() { + this.state = "scheduled"; + if (this.isAsync) { + toResolve.add(this); + if (!isScheduled) { + isScheduled = true; + frame.read(readAllKeyframes); + frame.resolveKeyframes(measureAllKeyframes); + } + } else { + this.readKeyframes(); + this.complete(); + } + } + readKeyframes() { + const { unresolvedKeyframes, name, element, motionValue: motionValue2 } = this; + if (unresolvedKeyframes[0] === null) { + const currentValue = motionValue2?.get(); + const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1]; + if (currentValue !== void 0) { + unresolvedKeyframes[0] = currentValue; + } else if (element && name) { + const valueAsRead = element.readValue(name, finalKeyframe); + if (valueAsRead !== void 0 && valueAsRead !== null) { + unresolvedKeyframes[0] = valueAsRead; + } + } + if (unresolvedKeyframes[0] === void 0) { + unresolvedKeyframes[0] = finalKeyframe; + } + if (motionValue2 && currentValue === void 0) { + motionValue2.set(unresolvedKeyframes[0]); + } + } + fillWildcards(unresolvedKeyframes); + } + setFinalKeyframe() { + } + measureInitialState() { + } + renderEndStyles() { + } + measureEndState() { + } + complete(isForcedComplete = false) { + this.state = "complete"; + this.onComplete(this.unresolvedKeyframes, this.finalKeyframe, isForcedComplete); + toResolve.delete(this); + } + cancel() { + if (this.state === "scheduled") { + toResolve.delete(this); + this.state = "pending"; + } + } + resume() { + if (this.state === "pending") + this.scheduleResolve(); + } +} +const isCSSVar = (name) => name.startsWith("--"); +function setStyle(element, name, value) { + isCSSVar(name) ? element.style.setProperty(name, value) : element.style[name] = value; +} +const supportsFlags = {}; +function memoSupports(callback, supportsFlag) { + const memoized = /* @__PURE__ */ memo(callback); + return () => supportsFlags[supportsFlag] ?? memoized(); +} +const supportsScrollTimeline = /* @__PURE__ */ memoSupports(() => window.ScrollTimeline !== void 0, "scrollTimeline"); +const supportsLinearEasing = /* @__PURE__ */ memoSupports(() => { + try { + document.createElement("div").animate({ opacity: 0 }, { easing: "linear(0, 1)" }); + } catch (e) { + return false; + } + return true; +}, "linearEasing"); +const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`; +const supportedWaapiEasing = { + linear: "linear", + ease: "ease", + easeIn: "ease-in", + easeOut: "ease-out", + easeInOut: "ease-in-out", + circIn: /* @__PURE__ */ cubicBezierAsString([0, 0.65, 0.55, 1]), + circOut: /* @__PURE__ */ cubicBezierAsString([0.55, 0, 1, 0.45]), + backIn: /* @__PURE__ */ cubicBezierAsString([0.31, 0.01, 0.66, -0.59]), + backOut: /* @__PURE__ */ cubicBezierAsString([0.33, 1.53, 0.69, 0.99]) +}; +function mapEasingToNativeEasing(easing, duration) { + if (!easing) { + return void 0; + } else if (typeof easing === "function") { + return supportsLinearEasing() ? generateLinearEasing(easing, duration) : "ease-out"; + } else if (isBezierDefinition(easing)) { + return cubicBezierAsString(easing); + } else if (Array.isArray(easing)) { + return easing.map((segmentEasing) => mapEasingToNativeEasing(segmentEasing, duration) || supportedWaapiEasing.easeOut); + } else { + return supportedWaapiEasing[easing]; + } +} +function startWaapiAnimation(element, valueName, keyframes2, { delay: delay2 = 0, duration = 300, repeat = 0, repeatType = "loop", ease: ease2 = "easeOut", times } = {}, pseudoElement = void 0) { + const keyframeOptions = { + [valueName]: keyframes2 + }; + if (times) + keyframeOptions.offset = times; + const easing = mapEasingToNativeEasing(ease2, duration); + if (Array.isArray(easing)) + keyframeOptions.easing = easing; + const options = { + delay: delay2, + duration, + easing: !Array.isArray(easing) ? easing : "linear", + fill: "both", + iterations: repeat + 1, + direction: repeatType === "reverse" ? "alternate" : "normal" + }; + if (pseudoElement) + options.pseudoElement = pseudoElement; + const animation = element.animate(keyframeOptions, options); + return animation; +} +function isGenerator(type) { + return typeof type === "function" && "applyToOptions" in type; +} +function applyGeneratorOptions({ type, ...options }) { + if (isGenerator(type) && supportsLinearEasing()) { + return type.applyToOptions(options); + } else { + options.duration ?? (options.duration = 300); + options.ease ?? (options.ease = "easeOut"); + } + return options; +} +class NativeAnimation extends WithPromise { + constructor(options) { + super(); + this.finishedTime = null; + this.isStopped = false; + this.manualStartTime = null; + if (!options) + return; + const { element, name, keyframes: keyframes2, pseudoElement, allowFlatten = false, finalKeyframe, onComplete } = options; + this.isPseudoElement = Boolean(pseudoElement); + this.allowFlatten = allowFlatten; + this.options = options; + invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring"); + const transition = applyGeneratorOptions(options); + this.animation = startWaapiAnimation(element, name, keyframes2, transition, pseudoElement); + if (transition.autoplay === false) { + this.animation.pause(); + } + this.animation.onfinish = () => { + this.finishedTime = this.time; + if (!pseudoElement) { + const keyframe = getFinalKeyframe(keyframes2, this.options, finalKeyframe, this.speed); + if (this.updateMotionValue) { + this.updateMotionValue(keyframe); + } + setStyle(element, name, keyframe); + this.animation.cancel(); + } + onComplete?.(); + this.notifyFinished(); + }; + } + play() { + if (this.isStopped) + return; + this.manualStartTime = null; + this.animation.play(); + if (this.state === "finished") { + this.updateFinished(); + } + } + pause() { + this.animation.pause(); + } + complete() { + this.animation.finish?.(); + } + cancel() { + try { + this.animation.cancel(); + } catch (e) { + } + } + stop() { + if (this.isStopped) + return; + this.isStopped = true; + const { state } = this; + if (state === "idle" || state === "finished") { + return; + } + if (this.updateMotionValue) { + this.updateMotionValue(); + } else { + this.commitStyles(); + } + if (!this.isPseudoElement) + this.cancel(); + } + /** + * WAAPI doesn't natively have any interruption capabilities. + * + * In this method, we commit styles back to the DOM before cancelling + * the animation. + * + * This is designed to be overridden by NativeAnimationExtended, which + * will create a renderless JS animation and sample it twice to calculate + * its current value, "previous" value, and therefore allow + * Motion to also correctly calculate velocity for any subsequent animation + * while deferring the commit until the next animation frame. + */ + commitStyles() { + const element = this.options?.element; + if (!this.isPseudoElement && element?.isConnected) { + this.animation.commitStyles?.(); + } + } + get duration() { + const duration = this.animation.effect?.getComputedTiming?.().duration || 0; + return /* @__PURE__ */ millisecondsToSeconds(Number(duration)); + } + get iterationDuration() { + const { delay: delay2 = 0 } = this.options || {}; + return this.duration + /* @__PURE__ */ millisecondsToSeconds(delay2); + } + get time() { + return /* @__PURE__ */ millisecondsToSeconds(Number(this.animation.currentTime) || 0); + } + set time(newTime) { + const wasFinished = this.finishedTime !== null; + this.manualStartTime = null; + this.finishedTime = null; + this.animation.currentTime = /* @__PURE__ */ secondsToMilliseconds(newTime); + if (wasFinished) { + this.animation.pause(); + } + } + /** + * The playback speed of the animation. + * 1 = normal speed, 2 = double speed, 0.5 = half speed. + */ + get speed() { + return this.animation.playbackRate; + } + set speed(newSpeed) { + if (newSpeed < 0) + this.finishedTime = null; + this.animation.playbackRate = newSpeed; + } + get state() { + return this.finishedTime !== null ? "finished" : this.animation.playState; + } + get startTime() { + return this.manualStartTime ?? Number(this.animation.startTime); + } + set startTime(newStartTime) { + this.manualStartTime = this.animation.startTime = newStartTime; + } + /** + * Attaches a timeline to the animation, for instance the `ScrollTimeline`. + */ + attachTimeline({ timeline, rangeStart, rangeEnd, observe }) { + if (this.allowFlatten) { + this.animation.effect?.updateTiming({ easing: "linear" }); + } + this.animation.onfinish = null; + if (timeline && supportsScrollTimeline()) { + this.animation.timeline = timeline; + if (rangeStart) + this.animation.rangeStart = rangeStart; + if (rangeEnd) + this.animation.rangeEnd = rangeEnd; + return noop; + } else { + return observe(this); + } + } +} +const unsupportedEasingFunctions = { + anticipate, + backInOut, + circInOut +}; +function isUnsupportedEase(key) { + return key in unsupportedEasingFunctions; +} +function replaceStringEasing(transition) { + if (typeof transition.ease === "string" && isUnsupportedEase(transition.ease)) { + transition.ease = unsupportedEasingFunctions[transition.ease]; + } +} +const sampleDelta = 10; +class NativeAnimationExtended extends NativeAnimation { + constructor(options) { + replaceStringEasing(options); + replaceTransitionType(options); + super(options); + if (options.startTime !== void 0 && options.autoplay !== false) { + this.startTime = options.startTime; + } + this.options = options; + } + /** + * WAAPI doesn't natively have any interruption capabilities. + * + * Rather than read committed styles back out of the DOM, we can + * create a renderless JS animation and sample it twice to calculate + * its current value, "previous" value, and therefore allow + * Motion to calculate velocity for any subsequent animation. + */ + updateMotionValue(value) { + const { motionValue: motionValue2, onUpdate, onComplete, element, ...options } = this.options; + if (!motionValue2) + return; + if (value !== void 0) { + motionValue2.set(value); + return; + } + const sampleAnimation = new JSAnimation({ + ...options, + autoplay: false + }); + const sampleTime = Math.max(sampleDelta, time.now() - this.startTime); + const delta = clamp(0, sampleDelta, sampleTime - sampleDelta); + const current = sampleAnimation.sample(sampleTime).value; + const { name } = this.options; + if (element && name) + setStyle(element, name, current); + motionValue2.setWithVelocity(sampleAnimation.sample(Math.max(0, sampleTime - delta)).value, current, delta); + sampleAnimation.stop(); + } +} +const isAnimatable = (value, name) => { + if (name === "zIndex") + return false; + if (typeof value === "number" || Array.isArray(value)) + return true; + if (typeof value === "string" && // It's animatable if we have a string + (complex.test(value) || value === "0") && // And it contains numbers and/or colors + !value.startsWith("url(")) { + return true; + } + return false; +}; +function hasKeyframesChanged(keyframes2) { + const current = keyframes2[0]; + if (keyframes2.length === 1) + return true; + for (let i = 0; i < keyframes2.length; i++) { + if (keyframes2[i] !== current) + return true; + } +} +function canAnimate(keyframes2, name, type, velocity) { + const originKeyframe = keyframes2[0]; + if (originKeyframe === null) { + return false; + } + if (name === "display" || name === "visibility") + return true; + const targetKeyframe = keyframes2[keyframes2.length - 1]; + const isOriginAnimatable = isAnimatable(originKeyframe, name); + const isTargetAnimatable = isAnimatable(targetKeyframe, name); + warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable"); + if (!isOriginAnimatable || !isTargetAnimatable) { + return false; + } + return hasKeyframesChanged(keyframes2) || (type === "spring" || isGenerator(type)) && velocity; +} +function makeAnimationInstant(options) { + options.duration = 0; + options.type = "keyframes"; +} +const acceleratedValues = /* @__PURE__ */ new Set([ + "opacity", + "clipPath", + "filter", + "transform" + // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved + // or until we implement support for linear() easing. + // "background-color" +]); +const browserColorFunctions = /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/; +function hasBrowserOnlyColors(keyframes2) { + for (let i = 0; i < keyframes2.length; i++) { + if (typeof keyframes2[i] === "string" && browserColorFunctions.test(keyframes2[i])) { + return true; + } + } + return false; +} +const colorProperties = /* @__PURE__ */ new Set([ + "color", + "backgroundColor", + "outlineColor", + "fill", + "stroke", + "borderColor", + "borderTopColor", + "borderRightColor", + "borderBottomColor", + "borderLeftColor" +]); +const supportsWaapi = /* @__PURE__ */ memo(() => Object.hasOwnProperty.call(Element.prototype, "animate")); +function supportsBrowserAnimation(options) { + const { motionValue: motionValue2, name, repeatDelay, repeatType, damping, type, keyframes: keyframes2 } = options; + const subject = motionValue2?.owner?.current; + if (!(subject instanceof HTMLElement)) { + return false; + } + const { onUpdate, transformTemplate } = motionValue2.owner.getProps(); + return supportsWaapi() && name && /** + * Force WAAPI for color properties with browser-only color formats + * (oklch, oklab, lab, lch, etc.) that the JS animation path can't parse. + */ + (acceleratedValues.has(name) || colorProperties.has(name) && hasBrowserOnlyColors(keyframes2)) && (name !== "transform" || !transformTemplate) && /** + * If we're outputting values to onUpdate then we can't use WAAPI as there's + * no way to read the value from WAAPI every frame. + */ + !onUpdate && !repeatDelay && repeatType !== "mirror" && damping !== 0 && type !== "inertia"; +} +const MAX_RESOLVE_DELAY = 40; +class AsyncMotionValueAnimation extends WithPromise { + constructor({ autoplay = true, delay: delay2 = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", keyframes: keyframes2, name, motionValue: motionValue2, element, ...options }) { + super(); + this.stop = () => { + if (this._animation) { + this._animation.stop(); + this.stopTimeline?.(); + } + this.keyframeResolver?.cancel(); + }; + this.createdAt = time.now(); + const optionsWithDefaults = { + autoplay, + delay: delay2, + type, + repeat, + repeatDelay, + repeatType, + name, + motionValue: motionValue2, + element, + ...options + }; + const KeyframeResolver$1 = element?.KeyframeResolver || KeyframeResolver; + this.keyframeResolver = new KeyframeResolver$1(keyframes2, (resolvedKeyframes, finalKeyframe, forced) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe, optionsWithDefaults, !forced), name, motionValue2, element); + this.keyframeResolver?.scheduleResolve(); + } + onKeyframesResolved(keyframes2, finalKeyframe, options, sync) { + this.keyframeResolver = void 0; + const { name, type, velocity, delay: delay2, isHandoff, onUpdate } = options; + this.resolvedAt = time.now(); + let canAnimateValue = true; + if (!canAnimate(keyframes2, name, type, velocity)) { + canAnimateValue = false; + if (MotionGlobalConfig.instantAnimations || !delay2) { + onUpdate?.(getFinalKeyframe(keyframes2, options, finalKeyframe)); + } + keyframes2[0] = keyframes2[keyframes2.length - 1]; + makeAnimationInstant(options); + options.repeat = 0; + } + const startTime = sync ? !this.resolvedAt ? this.createdAt : this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY ? this.resolvedAt : this.createdAt : void 0; + const resolvedOptions = { + startTime, + finalKeyframe, + ...options, + keyframes: keyframes2 + }; + const useWaapi = canAnimateValue && !isHandoff && supportsBrowserAnimation(resolvedOptions); + const element = resolvedOptions.motionValue?.owner?.current; + let animation; + if (useWaapi) { + try { + animation = new NativeAnimationExtended({ + ...resolvedOptions, + element + }); + } catch { + animation = new JSAnimation(resolvedOptions); + } + } else { + animation = new JSAnimation(resolvedOptions); + } + animation.finished.then(() => { + this.notifyFinished(); + }).catch(noop); + if (this.pendingTimeline) { + this.stopTimeline = animation.attachTimeline(this.pendingTimeline); + this.pendingTimeline = void 0; + } + this._animation = animation; + } + get finished() { + if (!this._animation) { + return this._finished; + } else { + return this.animation.finished; + } + } + then(onResolve, _onReject) { + return this.finished.finally(onResolve).then(() => { + }); + } + get animation() { + if (!this._animation) { + this.keyframeResolver?.resume(); + flushKeyframeResolvers(); + } + return this._animation; + } + get duration() { + return this.animation.duration; + } + get iterationDuration() { + return this.animation.iterationDuration; + } + get time() { + return this.animation.time; + } + set time(newTime) { + this.animation.time = newTime; + } + get speed() { + return this.animation.speed; + } + get state() { + return this.animation.state; + } + set speed(newSpeed) { + this.animation.speed = newSpeed; + } + get startTime() { + return this.animation.startTime; + } + attachTimeline(timeline) { + if (this._animation) { + this.stopTimeline = this.animation.attachTimeline(timeline); + } else { + this.pendingTimeline = timeline; + } + return () => this.stop(); + } + play() { + this.animation.play(); + } + pause() { + this.animation.pause(); + } + complete() { + this.animation.complete(); + } + cancel() { + if (this._animation) { + this.animation.cancel(); + } + this.keyframeResolver?.cancel(); + } +} +function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) { + const index = Array.from(children).sort((a, b) => a.sortNodePosition(b)).indexOf(child); + const numChildren = children.size; + const maxStaggerDuration = (numChildren - 1) * staggerChildren; + const delayIsFunction = typeof delayChildren === "function"; + return delayIsFunction ? delayChildren(index, numChildren) : staggerDirection === 1 ? index * staggerChildren : maxStaggerDuration - index * staggerChildren; +} +const splitCSSVariableRegex = ( + // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words + /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u +); +function parseCSSVariable(current) { + const match = splitCSSVariableRegex.exec(current); + if (!match) + return [,]; + const [, token1, token2, fallback] = match; + return [`--${token1 ?? token2}`, fallback]; +} +const maxDepth = 4; +function getVariableValue(current, element, depth = 1) { + invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth"); + const [token, fallback] = parseCSSVariable(current); + if (!token) + return; + const resolved = window.getComputedStyle(element).getPropertyValue(token); + if (resolved) { + const trimmed = resolved.trim(); + return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed; + } + return isCSSVariableToken(fallback) ? getVariableValue(fallback, element, depth + 1) : fallback; +} +const underDampedSpring = { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10 +}; +const criticallyDampedSpring = (target) => ({ + type: "spring", + stiffness: 550, + damping: target === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10 +}); +const keyframesTransition = { + type: "keyframes", + duration: 0.8 +}; +const ease = { + type: "keyframes", + ease: [0.25, 0.1, 0.35, 1], + duration: 0.3 +}; +const getDefaultTransition = (valueKey, { keyframes: keyframes2 }) => { + if (keyframes2.length > 2) { + return keyframesTransition; + } else if (transformProps.has(valueKey)) { + return valueKey.startsWith("scale") ? criticallyDampedSpring(keyframes2[1]) : underDampedSpring; + } + return ease; +}; +function resolveTransition(transition, parentTransition) { + if (transition?.inherit && parentTransition) { + const { inherit: _, ...rest } = transition; + return { ...parentTransition, ...rest }; + } + return transition; +} +function getValueTransition(transition, key) { + const valueTransition = transition?.[key] ?? transition?.["default"] ?? transition; + if (valueTransition !== transition) { + return resolveTransition(valueTransition, transition); + } + return valueTransition; +} +const orchestrationKeys = /* @__PURE__ */ new Set([ + "when", + "delay", + "delayChildren", + "staggerChildren", + "staggerDirection", + "repeat", + "repeatType", + "repeatDelay", + "from", + "elapsed" +]); +function isTransitionDefined(transition) { + for (const key in transition) { + if (!orchestrationKeys.has(key)) + return true; + } + return false; +} +const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => { + const valueTransition = getValueTransition(transition, name) || {}; + const delay2 = valueTransition.delay || transition.delay || 0; + let { elapsed = 0 } = transition; + elapsed = elapsed - /* @__PURE__ */ secondsToMilliseconds(delay2); + const options = { + keyframes: Array.isArray(target) ? target : [null, target], + ease: "easeOut", + velocity: value.getVelocity(), + ...valueTransition, + delay: -elapsed, + onUpdate: (v) => { + value.set(v); + valueTransition.onUpdate && valueTransition.onUpdate(v); + }, + onComplete: () => { + onComplete(); + valueTransition.onComplete && valueTransition.onComplete(); + }, + name, + motionValue: value, + element: isHandoff ? void 0 : element + }; + if (!isTransitionDefined(valueTransition)) { + Object.assign(options, getDefaultTransition(name, options)); + } + options.duration && (options.duration = /* @__PURE__ */ secondsToMilliseconds(options.duration)); + options.repeatDelay && (options.repeatDelay = /* @__PURE__ */ secondsToMilliseconds(options.repeatDelay)); + if (options.from !== void 0) { + options.keyframes[0] = options.from; + } + let shouldSkip = false; + if (options.type === false || options.duration === 0 && !options.repeatDelay) { + makeAnimationInstant(options); + if (options.delay === 0) { + shouldSkip = true; + } + } + if (MotionGlobalConfig.instantAnimations || MotionGlobalConfig.skipAnimations || element?.shouldSkipAnimations) { + shouldSkip = true; + makeAnimationInstant(options); + options.delay = 0; + } + options.allowFlatten = !valueTransition.type && !valueTransition.ease; + if (shouldSkip && !isHandoff && value.get() !== void 0) { + const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition); + if (finalKeyframe !== void 0) { + frame.update(() => { + options.onUpdate(finalKeyframe); + options.onComplete(); + }); + return; + } + } + return valueTransition.isSync ? new JSAnimation(options) : new AsyncMotionValueAnimation(options); +}; +function getValueState(visualElement) { + const state = [{}, {}]; + visualElement?.values.forEach((value, key) => { + state[0][key] = value.get(); + state[1][key] = value.getVelocity(); + }); + return state; +} +function resolveVariantFromProps(props, definition, custom, visualElement) { + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== void 0 ? custom : props.custom, current, velocity); + } + if (typeof definition === "string") { + definition = props.variants && props.variants[definition]; + } + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== void 0 ? custom : props.custom, current, velocity); + } + return definition; +} +function resolveVariant(visualElement, definition, custom) { + const props = visualElement.getProps(); + return resolveVariantFromProps(props, definition, custom !== void 0 ? custom : props.custom, visualElement); +} +const positionalKeys = /* @__PURE__ */ new Set([ + "width", + "height", + "top", + "left", + "right", + "bottom", + ...transformPropOrder +]); +const MAX_VELOCITY_DELTA = 30; +const isFloat = (value) => { + return !isNaN(parseFloat(value)); +}; +class MotionValue { + /** + * @param init - The initiating value + * @param config - Optional configuration options + * + * - `transformer`: A function to transform incoming values with. + */ + constructor(init, options = {}) { + this.canTrackVelocity = null; + this.events = {}; + this.updateAndNotify = (v) => { + const currentTime = time.now(); + if (this.updatedAt !== currentTime) { + this.setPrevFrameValue(); + } + this.prev = this.current; + this.setCurrent(v); + if (this.current !== this.prev) { + this.events.change?.notify(this.current); + if (this.dependents) { + for (const dependent of this.dependents) { + dependent.dirty(); + } + } + } + }; + this.hasAnimated = false; + this.setCurrent(init); + this.owner = options.owner; + } + setCurrent(current) { + this.current = current; + this.updatedAt = time.now(); + if (this.canTrackVelocity === null && current !== void 0) { + this.canTrackVelocity = isFloat(this.current); + } + } + setPrevFrameValue(prevFrameValue = this.current) { + this.prevFrameValue = prevFrameValue; + this.prevUpdatedAt = this.updatedAt; + } + /** + * Adds a function that will be notified when the `MotionValue` is updated. + * + * It returns a function that, when called, will cancel the subscription. + * + * When calling `onChange` inside a React component, it should be wrapped with the + * `useEffect` hook. As it returns an unsubscribe function, this should be returned + * from the `useEffect` function to ensure you don't add duplicate subscribers.. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * const y = useMotionValue(0) + * const opacity = useMotionValue(1) + * + * useEffect(() => { + * function updateOpacity() { + * const maxXY = Math.max(x.get(), y.get()) + * const newOpacity = transform(maxXY, [0, 100], [1, 0]) + * opacity.set(newOpacity) + * } + * + * const unsubscribeX = x.on("change", updateOpacity) + * const unsubscribeY = y.on("change", updateOpacity) + * + * return () => { + * unsubscribeX() + * unsubscribeY() + * } + * }, []) + * + * return + * } + * ``` + * + * @param subscriber - A function that receives the latest value. + * @returns A function that, when called, will cancel this subscription. + * + * @deprecated + */ + onChange(subscription) { + if (process.env.NODE_ENV !== "production") { + warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`); + } + return this.on("change", subscription); + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new SubscriptionManager(); + } + const unsubscribe = this.events[eventName].add(callback); + if (eventName === "change") { + return () => { + unsubscribe(); + frame.read(() => { + if (!this.events.change.getSize()) { + this.stop(); + } + }); + }; + } + return unsubscribe; + } + clearListeners() { + for (const eventManagers in this.events) { + this.events[eventManagers].clear(); + } + } + /** + * Attaches a passive effect to the `MotionValue`. + */ + attach(passiveEffect, stopPassiveEffect) { + this.passiveEffect = passiveEffect; + this.stopPassiveEffect = stopPassiveEffect; + } + /** + * Sets the state of the `MotionValue`. + * + * @remarks + * + * ```jsx + * const x = useMotionValue(0) + * x.set(10) + * ``` + * + * @param latest - Latest value to set. + * @param render - Whether to notify render subscribers. Defaults to `true` + * + * @public + */ + set(v) { + if (!this.passiveEffect) { + this.updateAndNotify(v); + } else { + this.passiveEffect(v, this.updateAndNotify); + } + } + setWithVelocity(prev, current, delta) { + this.set(current); + this.prev = void 0; + this.prevFrameValue = prev; + this.prevUpdatedAt = this.updatedAt - delta; + } + /** + * Set the state of the `MotionValue`, stopping any active animations, + * effects, and resets velocity to `0`. + */ + jump(v, endAnimation = true) { + this.updateAndNotify(v); + this.prev = v; + this.prevUpdatedAt = this.prevFrameValue = void 0; + endAnimation && this.stop(); + if (this.stopPassiveEffect) + this.stopPassiveEffect(); + } + dirty() { + this.events.change?.notify(this.current); + } + addDependent(dependent) { + if (!this.dependents) { + this.dependents = /* @__PURE__ */ new Set(); + } + this.dependents.add(dependent); + } + removeDependent(dependent) { + if (this.dependents) { + this.dependents.delete(dependent); + } + } + /** + * Returns the latest state of `MotionValue` + * + * @returns - The latest state of `MotionValue` + * + * @public + */ + get() { + return this.current; + } + /** + * @public + */ + getPrevious() { + return this.prev; + } + /** + * Returns the latest velocity of `MotionValue` + * + * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. + * + * @public + */ + getVelocity() { + const currentTime = time.now(); + if (!this.canTrackVelocity || this.prevFrameValue === void 0 || currentTime - this.updatedAt > MAX_VELOCITY_DELTA) { + return 0; + } + const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA); + return velocityPerSecond(parseFloat(this.current) - parseFloat(this.prevFrameValue), delta); + } + /** + * Registers a new animation to control this `MotionValue`. Only one + * animation can drive a `MotionValue` at one time. + * + * ```jsx + * value.start() + * ``` + * + * @param animation - A function that starts the provided animation + */ + start(startAnimation) { + this.stop(); + return new Promise((resolve) => { + this.hasAnimated = true; + this.animation = startAnimation(resolve); + if (this.events.animationStart) { + this.events.animationStart.notify(); + } + }).then(() => { + if (this.events.animationComplete) { + this.events.animationComplete.notify(); + } + this.clearAnimation(); + }); + } + /** + * Stop the currently active animation. + * + * @public + */ + stop() { + if (this.animation) { + this.animation.stop(); + if (this.events.animationCancel) { + this.events.animationCancel.notify(); + } + } + this.clearAnimation(); + } + /** + * Returns `true` if this value is currently animating. + * + * @public + */ + isAnimating() { + return !!this.animation; + } + clearAnimation() { + delete this.animation; + } + /** + * Destroy and clean up subscribers to this `MotionValue`. + * + * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically + * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually + * created a `MotionValue` via the `motionValue` function. + * + * @public + */ + destroy() { + this.dependents?.clear(); + this.events.destroy?.notify(); + this.clearListeners(); + this.stop(); + if (this.stopPassiveEffect) { + this.stopPassiveEffect(); + } + } +} +function motionValue(init, options) { + return new MotionValue(init, options); +} +const isKeyframesTarget = (v) => { + return Array.isArray(v); +}; +function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } else { + visualElement.addValue(key, motionValue(value)); + } +} +function resolveFinalValueInKeyframes(v) { + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; +} +function setTarget(visualElement, definition) { + const resolved = resolveVariant(visualElement, definition); + let { transitionEnd = {}, transition = {}, ...target } = resolved || {}; + target = { ...target, ...transitionEnd }; + for (const key in target) { + const value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } +} +const isMotionValue = (value) => Boolean(value && value.getVelocity); +function isWillChangeMotionValue(value) { + return Boolean(isMotionValue(value) && value.add); +} +function addValueToWillChange(visualElement, key) { + const willChange = visualElement.getValue("willChange"); + if (isWillChangeMotionValue(willChange)) { + return willChange.add(key); + } else if (!willChange && MotionGlobalConfig.WillChange) { + const newWillChange = new MotionGlobalConfig.WillChange("auto"); + visualElement.addValue("willChange", newWillChange); + newWillChange.add(key); + } +} +function camelToDash(str) { + return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`); +} +const optimizedAppearDataId = "framerAppearId"; +const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); +function getOptimisedAppearId(visualElement) { + return visualElement.props[optimizedAppearDataAttribute]; +} +function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) { + const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; +} +function animateTarget(visualElement, targetAndTransition, { delay: delay2 = 0, transitionOverride, type } = {}) { + let { transition, transitionEnd, ...target } = targetAndTransition; + const defaultTransition = visualElement.getDefaultTransition(); + transition = transition ? resolveTransition(transition, defaultTransition) : defaultTransition; + const reduceMotion = transition?.reduceMotion; + if (transitionOverride) + transition = transitionOverride; + const animations2 = []; + const animationTypeState = type && visualElement.animationState && visualElement.animationState.getState()[type]; + for (const key in target) { + const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null); + const valueTarget = target[key]; + if (valueTarget === void 0 || animationTypeState && shouldBlockAnimation(animationTypeState, key)) { + continue; + } + const valueTransition = { + delay: delay2, + ...getValueTransition(transition || {}, key) + }; + const currentValue = value.get(); + if (currentValue !== void 0 && !value.isAnimating() && !Array.isArray(valueTarget) && valueTarget === currentValue && !valueTransition.velocity) { + frame.update(() => value.set(valueTarget)); + continue; + } + let isHandoff = false; + if (window.MotionHandoffAnimation) { + const appearId = getOptimisedAppearId(visualElement); + if (appearId) { + const startTime = window.MotionHandoffAnimation(appearId, key, frame); + if (startTime !== null) { + valueTransition.startTime = startTime; + isHandoff = true; + } + } + } + addValueToWillChange(visualElement, key); + const shouldReduceMotion = reduceMotion ?? visualElement.shouldReduceMotion; + value.start(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key) ? { type: false } : valueTransition, visualElement, isHandoff)); + const animation = value.animation; + if (animation) { + animations2.push(animation); + } + } + if (transitionEnd) { + const applyTransitionEnd = () => frame.update(() => { + transitionEnd && setTarget(visualElement, transitionEnd); + }); + if (animations2.length) { + Promise.all(animations2).then(applyTransitionEnd); + } else { + applyTransitionEnd(); + } + } + return animations2; +} +function animateVariant(visualElement, variant, options = {}) { + const resolved = resolveVariant(visualElement, variant, options.type === "exit" ? visualElement.presenceContext?.custom : void 0); + let { transition = visualElement.getDefaultTransition() || {} } = resolved || {}; + if (options.transitionOverride) { + transition = options.transitionOverride; + } + const getAnimation = resolved ? () => Promise.all(animateTarget(visualElement, resolved, options)) : () => Promise.resolve(); + const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size ? (forwardDelay = 0) => { + const { delayChildren = 0, staggerChildren, staggerDirection } = transition; + return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options); + } : () => Promise.resolve(); + const { when } = transition; + if (when) { + const [first, last] = when === "beforeChildren" ? [getAnimation, getChildAnimations] : [getChildAnimations, getAnimation]; + return first().then(() => last()); + } else { + return Promise.all([getAnimation(), getChildAnimations(options.delay)]); + } +} +function animateChildren(visualElement, variant, delay2 = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) { + const animations2 = []; + for (const child of visualElement.variantChildren) { + child.notify("AnimationStart", variant); + animations2.push(animateVariant(child, variant, { + ...options, + delay: delay2 + (typeof delayChildren === "function" ? 0 : delayChildren) + calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection) + }).then(() => child.notify("AnimationComplete", variant))); + } + return Promise.all(animations2); +} +function animateVisualElement(visualElement, definition, options = {}) { + visualElement.notify("AnimationStart", definition); + let animation; + if (Array.isArray(definition)) { + const animations2 = definition.map((variant) => animateVariant(visualElement, variant, options)); + animation = Promise.all(animations2); + } else if (typeof definition === "string") { + animation = animateVariant(visualElement, definition, options); + } else { + const resolvedDefinition = typeof definition === "function" ? resolveVariant(visualElement, definition, options.custom) : definition; + animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options)); + } + return animation.then(() => { + visualElement.notify("AnimationComplete", definition); + }); +} +const auto = { + test: (v) => v === "auto", + parse: (v) => v +}; +const testValueType = (v) => (type) => type.test(v); +const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto]; +const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v)); +function isNone(value) { + if (typeof value === "number") { + return value === 0; + } else if (value !== null) { + return value === "none" || value === "0" || isZeroValueString(value); + } else { + return true; + } +} +const maxDefaults = /* @__PURE__ */ new Set(["brightness", "contrast", "saturate", "opacity"]); +function applyDefaultFilter(v) { + const [name, value] = v.slice(0, -1).split("("); + if (name === "drop-shadow") + return v; + const [number2] = value.match(floatRegex) || []; + if (!number2) + return v; + const unit = value.replace(number2, ""); + let defaultValue = maxDefaults.has(name) ? 1 : 0; + if (number2 !== value) + defaultValue *= 100; + return name + "(" + defaultValue + unit + ")"; +} +const functionRegex = /\b([a-z-]*)\(.*?\)/gu; +const filter = { + ...complex, + getAnimatableNone: (v) => { + const functions = v.match(functionRegex); + return functions ? functions.map(applyDefaultFilter).join(" ") : v; + } +}; +const mask = { + ...complex, + getAnimatableNone: (v) => { + const parsed = complex.parse(v); + const transformer = complex.createTransformer(v); + return transformer(parsed.map((v2) => typeof v2 === "number" ? 0 : typeof v2 === "object" ? { ...v2, alpha: 1 } : v2)); + } +}; +const int = { + ...number, + transform: Math.round +}; +const transformValueTypes = { + rotate: degrees, + rotateX: degrees, + rotateY: degrees, + rotateZ: degrees, + scale, + scaleX: scale, + scaleY: scale, + scaleZ: scale, + skew: degrees, + skewX: degrees, + skewY: degrees, + distance: px, + translateX: px, + translateY: px, + translateZ: px, + x: px, + y: px, + z: px, + perspective: px, + transformPerspective: px, + opacity: alpha, + originX: progressPercentage, + originY: progressPercentage, + originZ: px +}; +const numberValueTypes = { + // Border props + borderWidth: px, + borderTopWidth: px, + borderRightWidth: px, + borderBottomWidth: px, + borderLeftWidth: px, + borderRadius: px, + borderTopLeftRadius: px, + borderTopRightRadius: px, + borderBottomRightRadius: px, + borderBottomLeftRadius: px, + // Positioning props + width: px, + maxWidth: px, + height: px, + maxHeight: px, + top: px, + right: px, + bottom: px, + left: px, + inset: px, + insetBlock: px, + insetBlockStart: px, + insetBlockEnd: px, + insetInline: px, + insetInlineStart: px, + insetInlineEnd: px, + // Spacing props + padding: px, + paddingTop: px, + paddingRight: px, + paddingBottom: px, + paddingLeft: px, + paddingBlock: px, + paddingBlockStart: px, + paddingBlockEnd: px, + paddingInline: px, + paddingInlineStart: px, + paddingInlineEnd: px, + margin: px, + marginTop: px, + marginRight: px, + marginBottom: px, + marginLeft: px, + marginBlock: px, + marginBlockStart: px, + marginBlockEnd: px, + marginInline: px, + marginInlineStart: px, + marginInlineEnd: px, + // Typography + fontSize: px, + // Misc + backgroundPositionX: px, + backgroundPositionY: px, + ...transformValueTypes, + zIndex: int, + // SVG + fillOpacity: alpha, + strokeOpacity: alpha, + numOctaves: int +}; +const defaultValueTypes = { + ...numberValueTypes, + // Color props + color, + backgroundColor: color, + outlineColor: color, + fill: color, + stroke: color, + // Border props + borderColor: color, + borderTopColor: color, + borderRightColor: color, + borderBottomColor: color, + borderLeftColor: color, + filter, + WebkitFilter: filter, + mask, + WebkitMask: mask +}; +const getDefaultValueType = (key) => defaultValueTypes[key]; +const customTypes = /* @__PURE__ */ new Set([filter, mask]); +function getAnimatableNone(key, value) { + let defaultValueType = getDefaultValueType(key); + if (!customTypes.has(defaultValueType)) + defaultValueType = complex; + return defaultValueType.getAnimatableNone ? defaultValueType.getAnimatableNone(value) : void 0; +} +const invalidTemplates = /* @__PURE__ */ new Set(["auto", "none", "0"]); +function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) { + let i = 0; + let animatableTemplate = void 0; + while (i < unresolvedKeyframes.length && !animatableTemplate) { + const keyframe = unresolvedKeyframes[i]; + if (typeof keyframe === "string" && !invalidTemplates.has(keyframe) && analyseComplexValue(keyframe).values.length) { + animatableTemplate = unresolvedKeyframes[i]; + } + i++; + } + if (animatableTemplate && name) { + for (const noneIndex of noneKeyframeIndexes) { + unresolvedKeyframes[noneIndex] = getAnimatableNone(name, animatableTemplate); + } + } +} +class DOMKeyframesResolver extends KeyframeResolver { + constructor(unresolvedKeyframes, onComplete, name, motionValue2, element) { + super(unresolvedKeyframes, onComplete, name, motionValue2, element, true); + } + readKeyframes() { + const { unresolvedKeyframes, element, name } = this; + if (!element || !element.current) + return; + super.readKeyframes(); + for (let i = 0; i < unresolvedKeyframes.length; i++) { + let keyframe = unresolvedKeyframes[i]; + if (typeof keyframe === "string") { + keyframe = keyframe.trim(); + if (isCSSVariableToken(keyframe)) { + const resolved = getVariableValue(keyframe, element.current); + if (resolved !== void 0) { + unresolvedKeyframes[i] = resolved; + } + if (i === unresolvedKeyframes.length - 1) { + this.finalKeyframe = keyframe; + } + } + } + } + this.resolveNoneKeyframes(); + if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) { + return; + } + const [origin, target] = unresolvedKeyframes; + const originType = findDimensionValueType(origin); + const targetType = findDimensionValueType(target); + const originHasVar = containsCSSVariable(origin); + const targetHasVar = containsCSSVariable(target); + if (originHasVar !== targetHasVar && positionalValues[name]) { + this.needsMeasurement = true; + return; + } + if (originType === targetType) + return; + if (isNumOrPxType(originType) && isNumOrPxType(targetType)) { + for (let i = 0; i < unresolvedKeyframes.length; i++) { + const value = unresolvedKeyframes[i]; + if (typeof value === "string") { + unresolvedKeyframes[i] = parseFloat(value); + } + } + } else if (positionalValues[name]) { + this.needsMeasurement = true; + } + } + resolveNoneKeyframes() { + const { unresolvedKeyframes, name } = this; + const noneKeyframeIndexes = []; + for (let i = 0; i < unresolvedKeyframes.length; i++) { + if (unresolvedKeyframes[i] === null || isNone(unresolvedKeyframes[i])) { + noneKeyframeIndexes.push(i); + } + } + if (noneKeyframeIndexes.length) { + makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name); + } + } + measureInitialState() { + const { element, unresolvedKeyframes, name } = this; + if (!element || !element.current) + return; + if (name === "height") { + this.suspendedScrollY = window.pageYOffset; + } + this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current)); + unresolvedKeyframes[0] = this.measuredOrigin; + const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1]; + if (measureKeyframe !== void 0) { + element.getValue(name, measureKeyframe).jump(measureKeyframe, false); + } + } + measureEndState() { + const { element, name, unresolvedKeyframes } = this; + if (!element || !element.current) + return; + const value = element.getValue(name); + value && value.jump(this.measuredOrigin, false); + const finalKeyframeIndex = unresolvedKeyframes.length - 1; + const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex]; + unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current)); + if (finalKeyframe !== null && this.finalKeyframe === void 0) { + this.finalKeyframe = finalKeyframe; + } + if (this.removedTransforms?.length) { + this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => { + element.getValue(unsetTransformName).set(unsetTransformValue); + }); + } + this.resolveNoneKeyframes(); + } +} +function resolveElements(elementOrSelector, scope, selectorCache) { + if (elementOrSelector == null) { + return []; + } + if (elementOrSelector instanceof EventTarget) { + return [elementOrSelector]; + } else if (typeof elementOrSelector === "string") { + let root = document; + const elements = selectorCache?.[elementOrSelector] ?? root.querySelectorAll(elementOrSelector); + return elements ? Array.from(elements) : []; + } + return Array.from(elementOrSelector).filter((element) => element != null); +} +const getValueAsType = (value, type) => { + return type && typeof value === "number" ? type.transform(value) : value; +}; +function isHTMLElement(element) { + return isObject(element) && "offsetHeight" in element && !("ownerSVGElement" in element); +} +const { schedule: microtask } = /* @__PURE__ */ createRenderBatcher(queueMicrotask, false); +const isDragging = { + x: false, + y: false +}; +function isDragActive() { + return isDragging.x || isDragging.y; +} +function setDragLock(axis) { + if (axis === "x" || axis === "y") { + if (isDragging[axis]) { + return null; + } else { + isDragging[axis] = true; + return () => { + isDragging[axis] = false; + }; + } + } else { + if (isDragging.x || isDragging.y) { + return null; + } else { + isDragging.x = isDragging.y = true; + return () => { + isDragging.x = isDragging.y = false; + }; + } + } +} +function setupGesture(elementOrSelector, options) { + const elements = resolveElements(elementOrSelector); + const gestureAbortController = new AbortController(); + const eventOptions = { + passive: true, + ...options, + signal: gestureAbortController.signal + }; + const cancel = () => gestureAbortController.abort(); + return [elements, eventOptions, cancel]; +} +function isValidHover(event) { + return !(event.pointerType === "touch" || isDragActive()); +} +function hover(elementOrSelector, onHoverStart, options = {}) { + const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options); + elements.forEach((element) => { + let isPressed = false; + let deferredHoverEnd = false; + let hoverEndCallback; + const removePointerLeave = () => { + element.removeEventListener("pointerleave", onPointerLeave); + }; + const endHover = (event) => { + if (hoverEndCallback) { + hoverEndCallback(event); + hoverEndCallback = void 0; + } + removePointerLeave(); + }; + const onPointerUp = (event) => { + isPressed = false; + window.removeEventListener("pointerup", onPointerUp); + window.removeEventListener("pointercancel", onPointerUp); + if (deferredHoverEnd) { + deferredHoverEnd = false; + endHover(event); + } + }; + const onPointerDown = () => { + isPressed = true; + window.addEventListener("pointerup", onPointerUp, eventOptions); + window.addEventListener("pointercancel", onPointerUp, eventOptions); + }; + const onPointerLeave = (leaveEvent) => { + if (leaveEvent.pointerType === "touch") + return; + if (isPressed) { + deferredHoverEnd = true; + return; + } + endHover(leaveEvent); + }; + const onPointerEnter = (enterEvent) => { + if (!isValidHover(enterEvent)) + return; + deferredHoverEnd = false; + const onHoverEnd = onHoverStart(element, enterEvent); + if (typeof onHoverEnd !== "function") + return; + hoverEndCallback = onHoverEnd; + element.addEventListener("pointerleave", onPointerLeave, eventOptions); + }; + element.addEventListener("pointerenter", onPointerEnter, eventOptions); + element.addEventListener("pointerdown", onPointerDown, eventOptions); + }); + return cancel; +} +const isNodeOrChild = (parent, child) => { + if (!child) { + return false; + } else if (parent === child) { + return true; + } else { + return isNodeOrChild(parent, child.parentElement); + } +}; +const isPrimaryPointer = (event) => { + if (event.pointerType === "mouse") { + return typeof event.button !== "number" || event.button <= 0; + } else { + return event.isPrimary !== false; + } +}; +const keyboardAccessibleElements = /* @__PURE__ */ new Set([ + "BUTTON", + "INPUT", + "SELECT", + "TEXTAREA", + "A" +]); +function isElementKeyboardAccessible(element) { + return keyboardAccessibleElements.has(element.tagName) || element.isContentEditable === true; +} +const textInputElements = /* @__PURE__ */ new Set(["INPUT", "SELECT", "TEXTAREA"]); +function isElementTextInput(element) { + return textInputElements.has(element.tagName) || element.isContentEditable === true; +} +const isPressing = /* @__PURE__ */ new WeakSet(); +function filterEvents(callback) { + return (event) => { + if (event.key !== "Enter") + return; + callback(event); + }; +} +function firePointerEvent(target, type) { + target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true })); +} +const enableKeyboardPress = (focusEvent, eventOptions) => { + const element = focusEvent.currentTarget; + if (!element) + return; + const handleKeydown = filterEvents(() => { + if (isPressing.has(element)) + return; + firePointerEvent(element, "down"); + const handleKeyup = filterEvents(() => { + firePointerEvent(element, "up"); + }); + const handleBlur = () => firePointerEvent(element, "cancel"); + element.addEventListener("keyup", handleKeyup, eventOptions); + element.addEventListener("blur", handleBlur, eventOptions); + }); + element.addEventListener("keydown", handleKeydown, eventOptions); + element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions); +}; +function isValidPressEvent(event) { + return isPrimaryPointer(event) && !isDragActive(); +} +const claimedPointerDownEvents = /* @__PURE__ */ new WeakSet(); +function press(targetOrSelector, onPressStart, options = {}) { + const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options); + const startPress = (startEvent) => { + const target = startEvent.currentTarget; + if (!isValidPressEvent(startEvent)) + return; + if (claimedPointerDownEvents.has(startEvent)) + return; + isPressing.add(target); + if (options.stopPropagation) { + claimedPointerDownEvents.add(startEvent); + } + const onPressEnd = onPressStart(target, startEvent); + const onPointerEnd = (endEvent, success) => { + window.removeEventListener("pointerup", onPointerUp); + window.removeEventListener("pointercancel", onPointerCancel); + if (isPressing.has(target)) { + isPressing.delete(target); + } + if (!isValidPressEvent(endEvent)) { + return; + } + if (typeof onPressEnd === "function") { + onPressEnd(endEvent, { success }); + } + }; + const onPointerUp = (upEvent) => { + onPointerEnd(upEvent, target === window || target === document || options.useGlobalTarget || isNodeOrChild(target, upEvent.target)); + }; + const onPointerCancel = (cancelEvent) => { + onPointerEnd(cancelEvent, false); + }; + window.addEventListener("pointerup", onPointerUp, eventOptions); + window.addEventListener("pointercancel", onPointerCancel, eventOptions); + }; + targets.forEach((target) => { + const pointerDownTarget = options.useGlobalTarget ? window : target; + pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions); + if (isHTMLElement(target)) { + target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions)); + if (!isElementKeyboardAccessible(target) && !target.hasAttribute("tabindex")) { + target.tabIndex = 0; + } + } + }); + return cancelEvents; +} +function isSVGElement(element) { + return isObject(element) && "ownerSVGElement" in element; +} +const resizeHandlers = /* @__PURE__ */ new WeakMap(); +let observer; +const getSize = (borderBoxAxis, svgAxis, htmlAxis) => (target, borderBoxSize) => { + if (borderBoxSize && borderBoxSize[0]) { + return borderBoxSize[0][borderBoxAxis + "Size"]; + } else if (isSVGElement(target) && "getBBox" in target) { + return target.getBBox()[svgAxis]; + } else { + return target[htmlAxis]; + } +}; +const getWidth = /* @__PURE__ */ getSize("inline", "width", "offsetWidth"); +const getHeight = /* @__PURE__ */ getSize("block", "height", "offsetHeight"); +function notifyTarget({ target, borderBoxSize }) { + resizeHandlers.get(target)?.forEach((handler) => { + handler(target, { + get width() { + return getWidth(target, borderBoxSize); + }, + get height() { + return getHeight(target, borderBoxSize); + } + }); + }); +} +function notifyAll(entries) { + entries.forEach(notifyTarget); +} +function createResizeObserver() { + if (typeof ResizeObserver === "undefined") + return; + observer = new ResizeObserver(notifyAll); +} +function resizeElement(target, handler) { + if (!observer) + createResizeObserver(); + const elements = resolveElements(target); + elements.forEach((element) => { + let elementHandlers = resizeHandlers.get(element); + if (!elementHandlers) { + elementHandlers = /* @__PURE__ */ new Set(); + resizeHandlers.set(element, elementHandlers); + } + elementHandlers.add(handler); + observer?.observe(element); + }); + return () => { + elements.forEach((element) => { + const elementHandlers = resizeHandlers.get(element); + elementHandlers?.delete(handler); + if (!elementHandlers?.size) { + observer?.unobserve(element); + } + }); + }; +} +const windowCallbacks = /* @__PURE__ */ new Set(); +let windowResizeHandler; +function createWindowResizeHandler() { + windowResizeHandler = () => { + const info = { + get width() { + return window.innerWidth; + }, + get height() { + return window.innerHeight; + } + }; + windowCallbacks.forEach((callback) => callback(info)); + }; + window.addEventListener("resize", windowResizeHandler); +} +function resizeWindow(callback) { + windowCallbacks.add(callback); + if (!windowResizeHandler) + createWindowResizeHandler(); + return () => { + windowCallbacks.delete(callback); + if (!windowCallbacks.size && typeof windowResizeHandler === "function") { + window.removeEventListener("resize", windowResizeHandler); + windowResizeHandler = void 0; + } + }; +} +function resize(a, b) { + return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b); +} +function isSVGSVGElement(element) { + return isSVGElement(element) && element.tagName === "svg"; +} +const valueTypes = [...dimensionValueTypes, color, complex]; +const findValueType = (v) => valueTypes.find(testValueType(v)); +const createAxisDelta = () => ({ + translate: 0, + scale: 1, + origin: 0, + originPoint: 0 +}); +const createDelta = () => ({ + x: createAxisDelta(), + y: createAxisDelta() +}); +const createAxis = () => ({ min: 0, max: 0 }); +const createBox = () => ({ + x: createAxis(), + y: createAxis() +}); +const visualElementStore = /* @__PURE__ */ new WeakMap(); +function isAnimationControls(v) { + return v !== null && typeof v === "object" && typeof v.start === "function"; +} +function isVariantLabel(v) { + return typeof v === "string" || Array.isArray(v); +} +const variantPriorityOrder = [ + "animate", + "whileInView", + "whileFocus", + "whileHover", + "whileTap", + "whileDrag", + "exit" +]; +const variantProps = ["initial", ...variantPriorityOrder]; +function isControllingVariants(props) { + return isAnimationControls(props.animate) || variantProps.some((name) => isVariantLabel(props[name])); +} +function isVariantNode(props) { + return Boolean(isControllingVariants(props) || props.variants); +} +function updateMotionValuesFromProps(element, next, prev) { + for (const key in next) { + const nextValue = next[key]; + const prevValue = prev[key]; + if (isMotionValue(nextValue)) { + element.addValue(key, nextValue); + } else if (isMotionValue(prevValue)) { + element.addValue(key, motionValue(nextValue, { owner: element })); + } else if (prevValue !== nextValue) { + if (element.hasValue(key)) { + const existingValue = element.getValue(key); + if (existingValue.liveStyle === true) { + existingValue.jump(nextValue); + } else if (!existingValue.hasAnimated) { + existingValue.set(nextValue); + } + } else { + const latestValue = element.getStaticValue(key); + element.addValue(key, motionValue(latestValue !== void 0 ? latestValue : nextValue, { owner: element })); + } + } + } + for (const key in prev) { + if (next[key] === void 0) + element.removeValue(key); + } + return next; +} +const prefersReducedMotion = { current: null }; +const hasReducedMotionListener = { current: false }; +const isBrowser = typeof window !== "undefined"; +function initPrefersReducedMotion() { + hasReducedMotionListener.current = true; + if (!isBrowser) + return; + if (window.matchMedia) { + const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)"); + const setReducedMotionPreferences = () => prefersReducedMotion.current = motionMediaQuery.matches; + motionMediaQuery.addEventListener("change", setReducedMotionPreferences); + setReducedMotionPreferences(); + } else { + prefersReducedMotion.current = false; + } +} +const propEventHandlers = [ + "AnimationStart", + "AnimationComplete", + "Update", + "BeforeLayoutMeasure", + "LayoutMeasure", + "LayoutAnimationStart", + "LayoutAnimationComplete" +]; +let featureDefinitions = {}; +function setFeatureDefinitions(definitions) { + featureDefinitions = definitions; +} +function getFeatureDefinitions() { + return featureDefinitions; +} +class VisualElement { + /** + * This method takes React props and returns found MotionValues. For example, HTML + * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. + * + * This isn't an abstract method as it needs calling in the constructor, but it is + * intended to be one. + */ + scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) { + return {}; + } + constructor({ parent, props, presenceContext, reducedMotionConfig, skipAnimations, blockInitialAnimation, visualState }, options = {}) { + this.current = null; + this.children = /* @__PURE__ */ new Set(); + this.isVariantNode = false; + this.isControllingVariants = false; + this.shouldReduceMotion = null; + this.shouldSkipAnimations = false; + this.values = /* @__PURE__ */ new Map(); + this.KeyframeResolver = KeyframeResolver; + this.features = {}; + this.valueSubscriptions = /* @__PURE__ */ new Map(); + this.prevMotionValues = {}; + this.hasBeenMounted = false; + this.events = {}; + this.propEventSubscriptions = {}; + this.notifyUpdate = () => this.notify("Update", this.latestValues); + this.render = () => { + if (!this.current) + return; + this.triggerBuild(); + this.renderInstance(this.current, this.renderState, this.props.style, this.projection); + }; + this.renderScheduledAt = 0; + this.scheduleRender = () => { + const now2 = time.now(); + if (this.renderScheduledAt < now2) { + this.renderScheduledAt = now2; + frame.render(this.render, false, true); + } + }; + const { latestValues, renderState } = visualState; + this.latestValues = latestValues; + this.baseTarget = { ...latestValues }; + this.initialValues = props.initial ? { ...latestValues } : {}; + this.renderState = renderState; + this.parent = parent; + this.props = props; + this.presenceContext = presenceContext; + this.depth = parent ? parent.depth + 1 : 0; + this.reducedMotionConfig = reducedMotionConfig; + this.skipAnimationsConfig = skipAnimations; + this.options = options; + this.blockInitialAnimation = Boolean(blockInitialAnimation); + this.isControllingVariants = isControllingVariants(props); + this.isVariantNode = isVariantNode(props); + if (this.isVariantNode) { + this.variantChildren = /* @__PURE__ */ new Set(); + } + this.manuallyAnimateOnMount = Boolean(parent && parent.current); + const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this); + for (const key in initialMotionValues) { + const value = initialMotionValues[key]; + if (latestValues[key] !== void 0 && isMotionValue(value)) { + value.set(latestValues[key]); + } + } + } + mount(instance) { + if (this.hasBeenMounted) { + for (const key in this.initialValues) { + this.values.get(key)?.jump(this.initialValues[key]); + this.latestValues[key] = this.initialValues[key]; + } + } + this.current = instance; + visualElementStore.set(instance, this); + if (this.projection && !this.projection.instance) { + this.projection.mount(instance); + } + if (this.parent && this.isVariantNode && !this.isControllingVariants) { + this.removeFromVariantTree = this.parent.addVariantChild(this); + } + this.values.forEach((value, key) => this.bindToMotionValue(key, value)); + if (this.reducedMotionConfig === "never") { + this.shouldReduceMotion = false; + } else if (this.reducedMotionConfig === "always") { + this.shouldReduceMotion = true; + } else { + if (!hasReducedMotionListener.current) { + initPrefersReducedMotion(); + } + this.shouldReduceMotion = prefersReducedMotion.current; + } + if (process.env.NODE_ENV !== "production") { + warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + this.shouldSkipAnimations = this.skipAnimationsConfig ?? false; + this.parent?.addChild(this); + this.update(this.props, this.presenceContext); + this.hasBeenMounted = true; + } + unmount() { + this.projection && this.projection.unmount(); + cancelFrame(this.notifyUpdate); + cancelFrame(this.render); + this.valueSubscriptions.forEach((remove) => remove()); + this.valueSubscriptions.clear(); + this.removeFromVariantTree && this.removeFromVariantTree(); + this.parent?.removeChild(this); + for (const key in this.events) { + this.events[key].clear(); + } + for (const key in this.features) { + const feature = this.features[key]; + if (feature) { + feature.unmount(); + feature.isMounted = false; + } + } + this.current = null; + } + addChild(child) { + this.children.add(child); + this.enteringChildren ?? (this.enteringChildren = /* @__PURE__ */ new Set()); + this.enteringChildren.add(child); + } + removeChild(child) { + this.children.delete(child); + this.enteringChildren && this.enteringChildren.delete(child); + } + bindToMotionValue(key, value) { + if (this.valueSubscriptions.has(key)) { + this.valueSubscriptions.get(key)(); + } + if (value.accelerate && acceleratedValues.has(key) && this.current instanceof HTMLElement) { + const { factory, keyframes: keyframes2, times, ease: ease2, duration } = value.accelerate; + const animation = new NativeAnimation({ + element: this.current, + name: key, + keyframes: keyframes2, + times, + ease: ease2, + duration: /* @__PURE__ */ secondsToMilliseconds(duration) + }); + const cleanup = factory(animation); + this.valueSubscriptions.set(key, () => { + cleanup(); + animation.cancel(); + }); + return; + } + const valueIsTransform = transformProps.has(key); + if (valueIsTransform && this.onBindTransform) { + this.onBindTransform(); + } + const removeOnChange = value.on("change", (latestValue) => { + this.latestValues[key] = latestValue; + this.props.onUpdate && frame.preRender(this.notifyUpdate); + if (valueIsTransform && this.projection) { + this.projection.isTransformDirty = true; + } + this.scheduleRender(); + }); + let removeSyncCheck; + if (typeof window !== "undefined" && window.MotionCheckAppearSync) { + removeSyncCheck = window.MotionCheckAppearSync(this, key, value); + } + this.valueSubscriptions.set(key, () => { + removeOnChange(); + if (removeSyncCheck) + removeSyncCheck(); + if (value.owner) + value.stop(); + }); + } + sortNodePosition(other) { + if (!this.current || !this.sortInstanceNodePosition || this.type !== other.type) { + return 0; + } + return this.sortInstanceNodePosition(this.current, other.current); + } + updateFeatures() { + let key = "animation"; + for (key in featureDefinitions) { + const featureDefinition = featureDefinitions[key]; + if (!featureDefinition) + continue; + const { isEnabled, Feature: FeatureConstructor } = featureDefinition; + if (!this.features[key] && FeatureConstructor && isEnabled(this.props)) { + this.features[key] = new FeatureConstructor(this); + } + if (this.features[key]) { + const feature = this.features[key]; + if (feature.isMounted) { + feature.update(); + } else { + feature.mount(); + feature.isMounted = true; + } + } + } + } + triggerBuild() { + this.build(this.renderState, this.latestValues, this.props); + } + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox() { + return this.current ? this.measureInstanceViewportBox(this.current, this.props) : createBox(); + } + getStaticValue(key) { + return this.latestValues[key]; + } + setStaticValue(key, value) { + this.latestValues[key] = value; + } + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + update(props, presenceContext) { + if (props.transformTemplate || this.props.transformTemplate) { + this.scheduleRender(); + } + this.prevProps = this.props; + this.props = props; + this.prevPresenceContext = this.presenceContext; + this.presenceContext = presenceContext; + for (let i = 0; i < propEventHandlers.length; i++) { + const key = propEventHandlers[i]; + if (this.propEventSubscriptions[key]) { + this.propEventSubscriptions[key](); + delete this.propEventSubscriptions[key]; + } + const listenerName = "on" + key; + const listener = props[listenerName]; + if (listener) { + this.propEventSubscriptions[key] = this.on(key, listener); + } + } + this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this), this.prevMotionValues); + if (this.handleChildMotionValue) { + this.handleChildMotionValue(); + } + } + getProps() { + return this.props; + } + /** + * Returns the variant definition with a given name. + */ + getVariant(name) { + return this.props.variants ? this.props.variants[name] : void 0; + } + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition() { + return this.props.transition; + } + getTransformPagePoint() { + return this.props.transformPagePoint; + } + getClosestVariantNode() { + return this.isVariantNode ? this : this.parent ? this.parent.getClosestVariantNode() : void 0; + } + /** + * Add a child visual element to our set of children. + */ + addVariantChild(child) { + const closestVariantNode = this.getClosestVariantNode(); + if (closestVariantNode) { + closestVariantNode.variantChildren && closestVariantNode.variantChildren.add(child); + return () => closestVariantNode.variantChildren.delete(child); + } + } + /** + * Add a motion value and bind it to this visual element. + */ + addValue(key, value) { + const existingValue = this.values.get(key); + if (value !== existingValue) { + if (existingValue) + this.removeValue(key); + this.bindToMotionValue(key, value); + this.values.set(key, value); + this.latestValues[key] = value.get(); + } + } + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue(key) { + this.values.delete(key); + const unsubscribe = this.valueSubscriptions.get(key); + if (unsubscribe) { + unsubscribe(); + this.valueSubscriptions.delete(key); + } + delete this.latestValues[key]; + this.removeValueFromRenderState(key, this.renderState); + } + /** + * Check whether we have a motion value for this key + */ + hasValue(key) { + return this.values.has(key); + } + getValue(key, defaultValue) { + if (this.props.values && this.props.values[key]) { + return this.props.values[key]; + } + let value = this.values.get(key); + if (value === void 0 && defaultValue !== void 0) { + value = motionValue(defaultValue === null ? void 0 : defaultValue, { owner: this }); + this.addValue(key, value); + } + return value; + } + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue(key, target) { + let value = this.latestValues[key] !== void 0 || !this.current ? this.latestValues[key] : this.getBaseTargetFromProps(this.props, key) ?? this.readValueFromInstance(this.current, key, this.options); + if (value !== void 0 && value !== null) { + if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) { + value = parseFloat(value); + } else if (!findValueType(value) && complex.test(target)) { + value = getAnimatableNone(key, target); + } + this.setBaseTarget(key, isMotionValue(value) ? value.get() : value); + } + return isMotionValue(value) ? value.get() : value; + } + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget(key, value) { + this.baseTarget[key] = value; + } + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget(key) { + const { initial } = this.props; + let valueFromInitial; + if (typeof initial === "string" || typeof initial === "object") { + const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom); + if (variant) { + valueFromInitial = variant[key]; + } + } + if (initial && valueFromInitial !== void 0) { + return valueFromInitial; + } + const target = this.getBaseTargetFromProps(this.props, key); + if (target !== void 0 && !isMotionValue(target)) + return target; + return this.initialValues[key] !== void 0 && valueFromInitial === void 0 ? void 0 : this.baseTarget[key]; + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new SubscriptionManager(); + } + return this.events[eventName].add(callback); + } + notify(eventName, ...args) { + if (this.events[eventName]) { + this.events[eventName].notify(...args); + } + } + scheduleRenderMicrotask() { + microtask.render(this.render); + } +} +class DOMVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.KeyframeResolver = DOMKeyframesResolver; + } + sortInstanceNodePosition(a, b) { + return a.compareDocumentPosition(b) & 2 ? 1 : -1; + } + getBaseTargetFromProps(props, key) { + const style = props.style; + return style ? style[key] : void 0; + } + removeValueFromRenderState(key, { vars, style }) { + delete vars[key]; + delete style[key]; + } + handleChildMotionValue() { + if (this.childSubscription) { + this.childSubscription(); + delete this.childSubscription; + } + const { children } = this.props; + if (isMotionValue(children)) { + this.childSubscription = children.on("change", (latest) => { + if (this.current) { + this.current.textContent = `${latest}`; + } + }); + } + } +} +class Feature { + constructor(node) { + this.isMounted = false; + this.node = node; + } + update() { + } +} +function convertBoundingBoxToBox({ top, left, right, bottom }) { + return { + x: { min: left, max: right }, + y: { min: top, max: bottom } + }; +} +function convertBoxToBoundingBox({ x, y }) { + return { top: y.min, right: x.max, bottom: y.max, left: x.min }; +} +function transformBoxPoints(point, transformPoint2) { + if (!transformPoint2) + return point; + const topLeft = transformPoint2({ x: point.left, y: point.top }); + const bottomRight = transformPoint2({ x: point.right, y: point.bottom }); + return { + top: topLeft.y, + left: topLeft.x, + bottom: bottomRight.y, + right: bottomRight.x + }; +} +function isIdentityScale(scale2) { + return scale2 === void 0 || scale2 === 1; +} +function hasScale({ scale: scale2, scaleX: scaleX2, scaleY: scaleY2 }) { + return !isIdentityScale(scale2) || !isIdentityScale(scaleX2) || !isIdentityScale(scaleY2); +} +function hasTransform(values) { + return hasScale(values) || has2DTranslate(values) || values.z || values.rotate || values.rotateX || values.rotateY || values.skewX || values.skewY; +} +function has2DTranslate(values) { + return is2DTranslate(values.x) || is2DTranslate(values.y); +} +function is2DTranslate(value) { + return value && value !== "0%"; +} +function scalePoint(point, scale2, originPoint) { + const distanceFromOrigin = point - originPoint; + const scaled = scale2 * distanceFromOrigin; + return originPoint + scaled; +} +function applyPointDelta(point, translate, scale2, originPoint, boxScale) { + if (boxScale !== void 0) { + point = scalePoint(point, boxScale, originPoint); + } + return scalePoint(point, scale2, originPoint) + translate; +} +function applyAxisDelta(axis, translate = 0, scale2 = 1, originPoint, boxScale) { + axis.min = applyPointDelta(axis.min, translate, scale2, originPoint, boxScale); + axis.max = applyPointDelta(axis.max, translate, scale2, originPoint, boxScale); +} +function applyBoxDelta(box, { x, y }) { + applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); + applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); +} +const TREE_SCALE_SNAP_MIN = 0.999999999999; +const TREE_SCALE_SNAP_MAX = 1.0000000000001; +function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) { + const treeLength = treePath.length; + if (!treeLength) + return; + treeScale.x = treeScale.y = 1; + let node; + let delta; + for (let i = 0; i < treeLength; i++) { + node = treePath[i]; + delta = node.projectionDelta; + const { visualElement } = node.options; + if (visualElement && visualElement.props.style && visualElement.props.style.display === "contents") { + continue; + } + if (isSharedTransition && node.options.layoutScroll && node.scroll && node !== node.root) { + translateAxis(box.x, -node.scroll.offset.x); + translateAxis(box.y, -node.scroll.offset.y); + } + if (delta) { + treeScale.x *= delta.x.scale; + treeScale.y *= delta.y.scale; + applyBoxDelta(box, delta); + } + if (isSharedTransition && hasTransform(node.latestValues)) { + transformBox(box, node.latestValues, node.layout?.layoutBox); + } + } + if (treeScale.x < TREE_SCALE_SNAP_MAX && treeScale.x > TREE_SCALE_SNAP_MIN) { + treeScale.x = 1; + } + if (treeScale.y < TREE_SCALE_SNAP_MAX && treeScale.y > TREE_SCALE_SNAP_MIN) { + treeScale.y = 1; + } +} +function translateAxis(axis, distance2) { + axis.min += distance2; + axis.max += distance2; +} +function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) { + const originPoint = mixNumber$1(axis.min, axis.max, axisOrigin); + applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale); +} +function resolveAxisTranslate(value, axis) { + if (typeof value === "string") { + return parseFloat(value) / 100 * (axis.max - axis.min); + } + return value; +} +function transformBox(box, transform, sourceBox) { + const resolveBox = sourceBox ?? box; + transformAxis(box.x, resolveAxisTranslate(transform.x, resolveBox.x), transform.scaleX, transform.scale, transform.originX); + transformAxis(box.y, resolveAxisTranslate(transform.y, resolveBox.y), transform.scaleY, transform.scale, transform.originY); +} +function measureViewportBox(instance, transformPoint2) { + return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint2)); +} +function measurePageBox(element, rootProjectionNode2, transformPagePoint) { + const viewportBox = measureViewportBox(element, transformPagePoint); + const { scroll } = rootProjectionNode2; + if (scroll) { + translateAxis(viewportBox.x, scroll.offset.x); + translateAxis(viewportBox.y, scroll.offset.y); + } + return viewportBox; +} +const translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective" +}; +const numTransforms = transformPropOrder.length; +function buildTransform(latestValues, transform, transformTemplate) { + let transformString = ""; + let transformIsDefault = true; + for (let i = 0; i < numTransforms; i++) { + const key = transformPropOrder[i]; + const value = latestValues[key]; + if (value === void 0) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } else { + const parsed = parseFloat(value); + valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0; + } + if (!valueIsDefault || transformTemplate) { + const valueAsType = getValueAsType(value, numberValueTypes[key]); + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias[key] || key; + transformString += `${transformName}(${valueAsType}) `; + } + if (transformTemplate) { + transform[key] = valueAsType; + } + } + } + transformString = transformString.trim(); + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } else if (transformIsDefault) { + transformString = "none"; + } + return transformString; +} +function buildHTMLStyles(state, latestValues, transformTemplate) { + const { style, vars, transformOrigin } = state; + let hasTransform2 = false; + let hasTransformOrigin = false; + for (const key in latestValues) { + const value = latestValues[key]; + if (transformProps.has(key)) { + hasTransform2 = true; + continue; + } else if (isCSSVariableName(key)) { + vars[key] = value; + continue; + } else { + const valueAsType = getValueAsType(value, numberValueTypes[key]); + if (key.startsWith("origin")) { + hasTransformOrigin = true; + transformOrigin[key] = valueAsType; + } else { + style[key] = valueAsType; + } + } + } + if (!latestValues.transform) { + if (hasTransform2 || transformTemplate) { + style.transform = buildTransform(latestValues, state.transform, transformTemplate); + } else if (style.transform) { + style.transform = "none"; + } + } + if (hasTransformOrigin) { + const { originX = "50%", originY = "50%", originZ = 0 } = transformOrigin; + style.transformOrigin = `${originX} ${originY} ${originZ}`; + } +} +function renderHTML(element, { style, vars }, styleProp, projection) { + const elementStyle = element.style; + let key; + for (key in style) { + elementStyle[key] = style[key]; + } + projection?.applyProjectionStyles(elementStyle, styleProp); + for (key in vars) { + elementStyle.setProperty(key, vars[key]); + } +} +function pixelsToPercent(pixels, axis) { + if (axis.max === axis.min) + return 0; + return pixels / (axis.max - axis.min) * 100; +} +const correctBorderRadius = { + correct: (latest, node) => { + if (!node.target) + return latest; + if (typeof latest === "string") { + if (px.test(latest)) { + latest = parseFloat(latest); + } else { + return latest; + } + } + const x = pixelsToPercent(latest, node.target.x); + const y = pixelsToPercent(latest, node.target.y); + return `${x}% ${y}%`; + } +}; +const correctBoxShadow = { + correct: (latest, { treeScale, projectionDelta }) => { + const original = latest; + const shadow = complex.parse(latest); + if (shadow.length > 5) + return original; + const template = complex.createTransformer(latest); + const offset = typeof shadow[0] !== "number" ? 1 : 0; + const xScale = projectionDelta.x.scale * treeScale.x; + const yScale = projectionDelta.y.scale * treeScale.y; + shadow[0 + offset] /= xScale; + shadow[1 + offset] /= yScale; + const averageScale = mixNumber$1(xScale, yScale, 0.5); + if (typeof shadow[2 + offset] === "number") + shadow[2 + offset] /= averageScale; + if (typeof shadow[3 + offset] === "number") + shadow[3 + offset] /= averageScale; + return template(shadow); + } +}; +const scaleCorrectors = { + borderRadius: { + ...correctBorderRadius, + applyTo: [ + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomLeftRadius", + "borderBottomRightRadius" + ] + }, + borderTopLeftRadius: correctBorderRadius, + borderTopRightRadius: correctBorderRadius, + borderBottomLeftRadius: correctBorderRadius, + borderBottomRightRadius: correctBorderRadius, + boxShadow: correctBoxShadow +}; +function isForcedMotionValue(key, { layout: layout2, layoutId }) { + return transformProps.has(key) || key.startsWith("origin") || (layout2 || layoutId !== void 0) && (!!scaleCorrectors[key] || key === "opacity"); +} +function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) { + const style = props.style; + const prevStyle = prevProps?.style; + const newValues = {}; + if (!style) + return newValues; + for (const key in style) { + if (isMotionValue(style[key]) || prevStyle && isMotionValue(prevStyle[key]) || isForcedMotionValue(key, props) || visualElement?.getValue(key)?.liveStyle !== void 0) { + newValues[key] = style[key]; + } + } + return newValues; +} +function getComputedStyle$1(element) { + return window.getComputedStyle(element); +} +class HTMLVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "html"; + this.renderInstance = renderHTML; + } + readValueFromInstance(instance, key) { + if (transformProps.has(key)) { + return this.projection?.isProjecting ? defaultTransformValue(key) : readTransformValue(instance, key); + } else { + const computedStyle = getComputedStyle$1(instance); + const value = (isCSSVariableName(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0; + return typeof value === "string" ? value.trim() : value; + } + } + measureInstanceViewportBox(instance, { transformPagePoint }) { + return measureViewportBox(instance, transformPagePoint); + } + build(renderState, latestValues, props) { + buildHTMLStyles(renderState, latestValues, props.transformTemplate); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + } +} +const dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray" +}; +const camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray" +}; +function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { + attrs.pathLength = 1; + const keys = useDashCase ? dashKeys : camelKeys; + attrs[keys.offset] = `${-offset}`; + attrs[keys.array] = `${length} ${spacing}`; +} +const cssMotionPathProperties = [ + "offsetDistance", + "offsetPath", + "offsetRotate", + "offsetAnchor" +]; +function buildSVGAttrs(state, { + attrX, + attrY, + attrScale, + pathLength, + pathSpacing = 1, + pathOffset = 0, + // This is object creation, which we try to avoid per-frame. + ...latest +}, isSVGTag2, transformTemplate, styleProp) { + buildHTMLStyles(state, latest, transformTemplate); + if (isSVGTag2) { + if (state.style.viewBox) { + state.attrs.viewBox = state.style.viewBox; + } + return; + } + state.attrs = state.style; + state.style = {}; + const { attrs, style } = state; + if (attrs.transform) { + style.transform = attrs.transform; + delete attrs.transform; + } + if (style.transform || attrs.transformOrigin) { + style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; + delete attrs.transformOrigin; + } + if (style.transform) { + style.transformBox = styleProp?.transformBox ?? "fill-box"; + delete attrs.transformBox; + } + for (const key of cssMotionPathProperties) { + if (attrs[key] !== void 0) { + style[key] = attrs[key]; + delete attrs[key]; + } + } + if (attrX !== void 0) + attrs.x = attrX; + if (attrY !== void 0) + attrs.y = attrY; + if (attrScale !== void 0) + attrs.scale = attrScale; + if (pathLength !== void 0) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } +} +const camelCaseAttributes = /* @__PURE__ */ new Set([ + "baseFrequency", + "diffuseConstant", + "kernelMatrix", + "kernelUnitLength", + "keySplines", + "keyTimes", + "limitingConeAngle", + "markerHeight", + "markerWidth", + "numOctaves", + "targetX", + "targetY", + "surfaceScale", + "specularConstant", + "specularExponent", + "stdDeviation", + "tableValues", + "viewBox", + "gradientTransform", + "pathLength", + "startOffset", + "textLength", + "lengthAdjust" +]); +const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; +function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, void 0, projection); + for (const key in renderState.attrs) { + element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); + } +} +function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + for (const key in props) { + if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) { + const targetKey = transformPropOrder.indexOf(key) !== -1 ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) : key; + newValues[targetKey] = props[key]; + } + } + return newValues; +} +class SVGVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "svg"; + this.isSVGTag = false; + this.measureInstanceViewportBox = createBox; + } + getBaseTargetFromProps(props, key) { + return props[key]; + } + readValueFromInstance(instance, key) { + if (transformProps.has(key)) { + const defaultType = getDefaultValueType(key); + return defaultType ? defaultType.default || 0 : 0; + } + key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; + return instance.getAttribute(key); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps(props, prevProps, visualElement); + } + build(renderState, latestValues, props) { + buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style); + } + renderInstance(instance, renderState, styleProp, projection) { + renderSVG(instance, renderState, styleProp, projection); + } + mount(instance) { + this.isSVGTag = isSVGTag(instance.tagName); + super.mount(instance); + } +} +const numVariantProps = variantProps.length; +function getVariantContext(visualElement) { + if (!visualElement) + return void 0; + if (!visualElement.isControllingVariants) { + const context2 = visualElement.parent ? getVariantContext(visualElement.parent) || {} : {}; + if (visualElement.props.initial !== void 0) { + context2.initial = visualElement.props.initial; + } + return context2; + } + const context = {}; + for (let i = 0; i < numVariantProps; i++) { + const name = variantProps[i]; + const prop = visualElement.props[name]; + if (isVariantLabel(prop) || prop === false) { + context[name] = prop; + } + } + return context; +} +function shallowCompare(next, prev) { + if (!Array.isArray(prev)) + return false; + const prevLength = prev.length; + if (prevLength !== next.length) + return false; + for (let i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) + return false; + } + return true; +} +const reversePriorityOrder = [...variantPriorityOrder].reverse(); +const numAnimationTypes = variantPriorityOrder.length; +function createAnimateFunction(visualElement) { + return (animations2) => { + return Promise.all(animations2.map(({ animation, options }) => animateVisualElement(visualElement, animation, options))); + }; +} +function createAnimationState(visualElement) { + let animate = createAnimateFunction(visualElement); + let state = createState(); + let isInitialRender = true; + let wasReset = false; + const buildResolvedTypeValues = (type) => (acc, definition) => { + const resolved = resolveVariant(visualElement, definition, type === "exit" ? visualElement.presenceContext?.custom : void 0); + if (resolved) { + const { transition, transitionEnd, ...target } = resolved; + acc = { ...acc, ...target, ...transitionEnd }; + } + return acc; + }; + function setAnimateFunction(makeAnimator) { + animate = makeAnimator(visualElement); + } + function animateChanges(changedActiveType) { + const { props } = visualElement; + const context = getVariantContext(visualElement.parent) || {}; + const animations2 = []; + const removedKeys = /* @__PURE__ */ new Set(); + let encounteredKeys = {}; + let removedVariantIndex = Infinity; + for (let i = 0; i < numAnimationTypes; i++) { + const type = reversePriorityOrder[i]; + const typeState = state[type]; + const prop = props[type] !== void 0 ? props[type] : context[type]; + const propIsVariant = isVariantLabel(prop); + const activeDelta = type === changedActiveType ? typeState.isActive : null; + if (activeDelta === false) + removedVariantIndex = i; + let isInherited = prop === context[type] && prop !== props[type] && propIsVariant; + if (isInherited && (isInitialRender || wasReset) && visualElement.manuallyAnimateOnMount) { + isInherited = false; + } + typeState.protectedKeys = { ...encounteredKeys }; + if ( + // If it isn't active and hasn't *just* been set as inactive + !typeState.isActive && activeDelta === null || // If we didn't and don't have any defined prop for this animation type + !prop && !typeState.prevProp || // Or if the prop doesn't define an animation + isAnimationControls(prop) || typeof prop === "boolean" + ) { + continue; + } + if (type === "exit" && typeState.isActive && activeDelta !== true) { + if (typeState.prevResolvedValues) { + encounteredKeys = { + ...encounteredKeys, + ...typeState.prevResolvedValues + }; + } + continue; + } + const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); + let shouldAnimateType = variantDidChange || // If we're making this variant active, we want to always make it active + type === changedActiveType && typeState.isActive && !isInherited && propIsVariant || // If we removed a higher-priority variant (i is in reverse order) + i > removedVariantIndex && propIsVariant; + let handledRemovedValues = false; + const definitionList = Array.isArray(prop) ? prop : [prop]; + let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {}); + if (activeDelta === false) + resolvedValues = {}; + const { prevResolvedValues = {} } = typeState; + const allKeys = { + ...prevResolvedValues, + ...resolvedValues + }; + const markToAnimate = (key) => { + shouldAnimateType = true; + if (removedKeys.has(key)) { + handledRemovedValues = true; + removedKeys.delete(key); + } + typeState.needsAnimating[key] = true; + const motionValue2 = visualElement.getValue(key); + if (motionValue2) + motionValue2.liveStyle = false; + }; + for (const key in allKeys) { + const next = resolvedValues[key]; + const prev = prevResolvedValues[key]; + if (encounteredKeys.hasOwnProperty(key)) + continue; + let valueHasChanged = false; + if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { + valueHasChanged = !shallowCompare(next, prev); + } else { + valueHasChanged = next !== prev; + } + if (valueHasChanged) { + if (next !== void 0 && next !== null) { + markToAnimate(key); + } else { + removedKeys.add(key); + } + } else if (next !== void 0 && removedKeys.has(key)) { + markToAnimate(key); + } else { + typeState.protectedKeys[key] = true; + } + } + typeState.prevProp = prop; + typeState.prevResolvedValues = resolvedValues; + if (typeState.isActive) { + encounteredKeys = { ...encounteredKeys, ...resolvedValues }; + } + if ((isInitialRender || wasReset) && visualElement.blockInitialAnimation) { + shouldAnimateType = false; + } + const willAnimateViaParent = isInherited && variantDidChange; + const needsAnimating = !willAnimateViaParent || handledRemovedValues; + if (shouldAnimateType && needsAnimating) { + animations2.push(...definitionList.map((animation) => { + const options = { type }; + if (typeof animation === "string" && (isInitialRender || wasReset) && !willAnimateViaParent && visualElement.manuallyAnimateOnMount && visualElement.parent) { + const { parent } = visualElement; + const parentVariant = resolveVariant(parent, animation); + if (parent.enteringChildren && parentVariant) { + const { delayChildren } = parentVariant.transition || {}; + options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren); + } + } + return { + animation, + options + }; + })); + } + } + if (removedKeys.size) { + const fallbackAnimation = {}; + if (typeof props.initial !== "boolean") { + const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial) ? props.initial[0] : props.initial); + if (initialTransition && initialTransition.transition) { + fallbackAnimation.transition = initialTransition.transition; + } + } + removedKeys.forEach((key) => { + const fallbackTarget = visualElement.getBaseTarget(key); + const motionValue2 = visualElement.getValue(key); + if (motionValue2) + motionValue2.liveStyle = true; + fallbackAnimation[key] = fallbackTarget ?? null; + }); + animations2.push({ animation: fallbackAnimation }); + } + let shouldAnimate = Boolean(animations2.length); + if (isInitialRender && (props.initial === false || props.initial === props.animate) && !visualElement.manuallyAnimateOnMount) { + shouldAnimate = false; + } + isInitialRender = false; + wasReset = false; + return shouldAnimate ? animate(animations2) : Promise.resolve(); + } + function setActive(type, isActive) { + if (state[type].isActive === isActive) + return Promise.resolve(); + visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive)); + state[type].isActive = isActive; + const animations2 = animateChanges(type); + for (const key in state) { + state[key].protectedKeys = {}; + } + return animations2; + } + return { + animateChanges, + setActive, + setAnimateFunction, + getState: () => state, + reset: () => { + state = createState(); + wasReset = true; + } + }; +} +function checkVariantsDidChange(prev, next) { + if (typeof next === "string") { + return next !== prev; + } else if (Array.isArray(next)) { + return !shallowCompare(next, prev); + } + return false; +} +function createTypeState(isActive = false) { + return { + isActive, + protectedKeys: {}, + needsAnimating: {}, + prevResolvedValues: {} + }; +} +function createState() { + return { + animate: createTypeState(true), + whileInView: createTypeState(), + whileHover: createTypeState(), + whileTap: createTypeState(), + whileDrag: createTypeState(), + whileFocus: createTypeState(), + exit: createTypeState() + }; +} +function copyAxisInto(axis, originAxis) { + axis.min = originAxis.min; + axis.max = originAxis.max; +} +function copyBoxInto(box, originBox) { + copyAxisInto(box.x, originBox.x); + copyAxisInto(box.y, originBox.y); +} +function copyAxisDeltaInto(delta, originDelta) { + delta.translate = originDelta.translate; + delta.scale = originDelta.scale; + delta.originPoint = originDelta.originPoint; + delta.origin = originDelta.origin; +} +const SCALE_PRECISION = 1e-4; +const SCALE_MIN = 1 - SCALE_PRECISION; +const SCALE_MAX = 1 + SCALE_PRECISION; +const TRANSLATE_PRECISION = 0.01; +const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION; +const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION; +function calcLength(axis) { + return axis.max - axis.min; +} +function isNear(value, target, maxDistance) { + return Math.abs(value - target) <= maxDistance; +} +function calcAxisDelta(delta, source, target, origin = 0.5) { + delta.origin = origin; + delta.originPoint = mixNumber$1(source.min, source.max, delta.origin); + delta.scale = calcLength(target) / calcLength(source); + delta.translate = mixNumber$1(target.min, target.max, delta.origin) - delta.originPoint; + if (delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX || isNaN(delta.scale)) { + delta.scale = 1; + } + if (delta.translate >= TRANSLATE_MIN && delta.translate <= TRANSLATE_MAX || isNaN(delta.translate)) { + delta.translate = 0; + } +} +function calcBoxDelta(delta, source, target, origin) { + calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : void 0); + calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : void 0); +} +function calcRelativeAxis(target, relative, parent, anchor = 0) { + const anchorPoint = anchor ? mixNumber$1(parent.min, parent.max, anchor) : parent.min; + target.min = anchorPoint + relative.min; + target.max = target.min + calcLength(relative); +} +function calcRelativeBox(target, relative, parent, anchor) { + calcRelativeAxis(target.x, relative.x, parent.x, anchor?.x); + calcRelativeAxis(target.y, relative.y, parent.y, anchor?.y); +} +function calcRelativeAxisPosition(target, layout2, parent, anchor = 0) { + const anchorPoint = anchor ? mixNumber$1(parent.min, parent.max, anchor) : parent.min; + target.min = layout2.min - anchorPoint; + target.max = target.min + calcLength(layout2); +} +function calcRelativePosition(target, layout2, parent, anchor) { + calcRelativeAxisPosition(target.x, layout2.x, parent.x, anchor?.x); + calcRelativeAxisPosition(target.y, layout2.y, parent.y, anchor?.y); +} +function removePointDelta(point, translate, scale2, originPoint, boxScale) { + point -= translate; + point = scalePoint(point, 1 / scale2, originPoint); + if (boxScale !== void 0) { + point = scalePoint(point, 1 / boxScale, originPoint); + } + return point; +} +function removeAxisDelta(axis, translate = 0, scale2 = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) { + if (percent.test(translate)) { + translate = parseFloat(translate); + const relativeProgress = mixNumber$1(sourceAxis.min, sourceAxis.max, translate / 100); + translate = relativeProgress - sourceAxis.min; + } + if (typeof translate !== "number") + return; + let originPoint = mixNumber$1(originAxis.min, originAxis.max, origin); + if (axis === originAxis) + originPoint -= translate; + axis.min = removePointDelta(axis.min, translate, scale2, originPoint, boxScale); + axis.max = removePointDelta(axis.max, translate, scale2, originPoint, boxScale); +} +function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) { + removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); +} +const xKeys = ["x", "scaleX", "originX"]; +const yKeys = ["y", "scaleY", "originY"]; +function removeBoxTransforms(box, transforms, originBox, sourceBox) { + removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : void 0, sourceBox ? sourceBox.x : void 0); + removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : void 0, sourceBox ? sourceBox.y : void 0); +} +function isAxisDeltaZero(delta) { + return delta.translate === 0 && delta.scale === 1; +} +function isDeltaZero(delta) { + return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); +} +function axisEquals(a, b) { + return a.min === b.min && a.max === b.max; +} +function boxEquals(a, b) { + return axisEquals(a.x, b.x) && axisEquals(a.y, b.y); +} +function axisEqualsRounded(a, b) { + return Math.round(a.min) === Math.round(b.min) && Math.round(a.max) === Math.round(b.max); +} +function boxEqualsRounded(a, b) { + return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y); +} +function aspectRatio(box) { + return calcLength(box.x) / calcLength(box.y); +} +function axisDeltaEquals(a, b) { + return a.translate === b.translate && a.scale === b.scale && a.originPoint === b.originPoint; +} +function eachAxis(callback) { + return [callback("x"), callback("y")]; +} +function buildProjectionTransform(delta, treeScale, latestTransform) { + let transform = ""; + const xTranslate = delta.x.translate / treeScale.x; + const yTranslate = delta.y.translate / treeScale.y; + const zTranslate = latestTransform?.z || 0; + if (xTranslate || yTranslate || zTranslate) { + transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `; + } + if (treeScale.x !== 1 || treeScale.y !== 1) { + transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `; + } + if (latestTransform) { + const { transformPerspective, rotate: rotate2, rotateX, rotateY, skewX, skewY } = latestTransform; + if (transformPerspective) + transform = `perspective(${transformPerspective}px) ${transform}`; + if (rotate2) + transform += `rotate(${rotate2}deg) `; + if (rotateX) + transform += `rotateX(${rotateX}deg) `; + if (rotateY) + transform += `rotateY(${rotateY}deg) `; + if (skewX) + transform += `skewX(${skewX}deg) `; + if (skewY) + transform += `skewY(${skewY}deg) `; + } + const elementScaleX = delta.x.scale * treeScale.x; + const elementScaleY = delta.y.scale * treeScale.y; + if (elementScaleX !== 1 || elementScaleY !== 1) { + transform += `scale(${elementScaleX}, ${elementScaleY})`; + } + return transform || "none"; +} +const borderLabels = [ + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomLeftRadius", + "borderBottomRightRadius" +]; +const numBorders = borderLabels.length; +const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value; +const isPx = (value) => typeof value === "number" || px.test(value); +function mixValues(target, follow, lead, progress2, shouldCrossfadeOpacity, isOnlyMember) { + if (shouldCrossfadeOpacity) { + target.opacity = mixNumber$1(0, lead.opacity ?? 1, easeCrossfadeIn(progress2)); + target.opacityExit = mixNumber$1(follow.opacity ?? 1, 0, easeCrossfadeOut(progress2)); + } else if (isOnlyMember) { + target.opacity = mixNumber$1(follow.opacity ?? 1, lead.opacity ?? 1, progress2); + } + for (let i = 0; i < numBorders; i++) { + const borderLabel = borderLabels[i]; + let followRadius = getRadius(follow, borderLabel); + let leadRadius = getRadius(lead, borderLabel); + if (followRadius === void 0 && leadRadius === void 0) + continue; + followRadius || (followRadius = 0); + leadRadius || (leadRadius = 0); + const canMix = followRadius === 0 || leadRadius === 0 || isPx(followRadius) === isPx(leadRadius); + if (canMix) { + target[borderLabel] = Math.max(mixNumber$1(asNumber(followRadius), asNumber(leadRadius), progress2), 0); + if (percent.test(leadRadius) || percent.test(followRadius)) { + target[borderLabel] += "%"; + } + } else { + target[borderLabel] = leadRadius; + } + } + if (follow.rotate || lead.rotate) { + target.rotate = mixNumber$1(follow.rotate || 0, lead.rotate || 0, progress2); + } +} +function getRadius(values, radiusName) { + return values[radiusName] !== void 0 ? values[radiusName] : values.borderRadius; +} +const easeCrossfadeIn = /* @__PURE__ */ compress(0, 0.5, circOut); +const easeCrossfadeOut = /* @__PURE__ */ compress(0.5, 0.95, noop); +function compress(min, max, easing) { + return (p) => { + if (p < min) + return 0; + if (p > max) + return 1; + return easing(/* @__PURE__ */ progress(min, max, p)); + }; +} +function animateSingleValue(value, keyframes2, options) { + const motionValue$1 = isMotionValue(value) ? value : motionValue(value); + motionValue$1.start(animateMotionValue("", motionValue$1, keyframes2, options)); + return motionValue$1.animation; +} +function addDomEvent(target, eventName, handler, options = { passive: true }) { + target.addEventListener(eventName, handler, options); + return () => target.removeEventListener(eventName, handler); +} +const compareByDepth = (a, b) => a.depth - b.depth; +class FlatTree { + constructor() { + this.children = []; + this.isDirty = false; + } + add(child) { + addUniqueItem(this.children, child); + this.isDirty = true; + } + remove(child) { + removeItem(this.children, child); + this.isDirty = true; + } + forEach(callback) { + this.isDirty && this.children.sort(compareByDepth); + this.isDirty = false; + this.children.forEach(callback); + } +} +function delay(callback, timeout) { + const start = time.now(); + const checkElapsed = ({ timestamp }) => { + const elapsed = timestamp - start; + if (elapsed >= timeout) { + cancelFrame(checkElapsed); + callback(elapsed - timeout); + } + }; + frame.setup(checkElapsed, true); + return () => cancelFrame(checkElapsed); +} +function resolveMotionValue(value) { + return isMotionValue(value) ? value.get() : value; +} +class NodeStack { + constructor() { + this.members = []; + } + add(node) { + addUniqueItem(this.members, node); + for (let i = this.members.length - 1; i >= 0; i--) { + const member = this.members[i]; + if (member === node || member === this.lead || member === this.prevLead) + continue; + const inst = member.instance; + if ((!inst || inst.isConnected === false) && !member.snapshot) { + removeItem(this.members, member); + member.unmount(); + } + } + node.scheduleRender(); + } + remove(node) { + removeItem(this.members, node); + if (node === this.prevLead) + this.prevLead = void 0; + if (node === this.lead) { + const prevLead = this.members[this.members.length - 1]; + if (prevLead) + this.promote(prevLead); + } + } + relegate(node) { + for (let i = this.members.indexOf(node) - 1; i >= 0; i--) { + const member = this.members[i]; + if (member.isPresent !== false && member.instance?.isConnected !== false) { + this.promote(member); + return true; + } + } + return false; + } + promote(node, preserveFollowOpacity) { + const prevLead = this.lead; + if (node === prevLead) + return; + this.prevLead = prevLead; + this.lead = node; + node.show(); + if (prevLead) { + prevLead.updateSnapshot(); + node.scheduleRender(); + const { layoutDependency: prevDep } = prevLead.options; + const { layoutDependency: nextDep } = node.options; + if (prevDep === void 0 || prevDep !== nextDep) { + node.resumeFrom = prevLead; + if (preserveFollowOpacity) + prevLead.preserveOpacity = true; + if (prevLead.snapshot) { + node.snapshot = prevLead.snapshot; + node.snapshot.latestValues = prevLead.animationValues || prevLead.latestValues; + } + if (node.root?.isUpdating) + node.isLayoutDirty = true; + } + if (node.options.crossfade === false) + prevLead.hide(); + } + } + exitAnimationComplete() { + this.members.forEach((member) => { + member.options.onExitComplete?.(); + member.resumingFrom?.options.onExitComplete?.(); + }); + } + scheduleRender() { + this.members.forEach((member) => member.instance && member.scheduleRender(false)); + } + removeLeadSnapshot() { + if (this.lead?.snapshot) + this.lead.snapshot = void 0; + } +} +const globalProjectionState = { + /** + * Global flag as to whether the tree has animated since the last time + * we resized the window + */ + hasAnimatedSinceResize: true, + /** + * We set this to true once, on the first update. Any nodes added to the tree beyond that + * update will be given a `data-projection-id` attribute. + */ + hasEverUpdated: false +}; +const transformAxes = ["", "X", "Y", "Z"]; +const animationTarget = 1e3; +let id$1 = 0; +function resetDistortingTransform(key, visualElement, values, sharedAnimationValues) { + const { latestValues } = visualElement; + if (latestValues[key]) { + values[key] = latestValues[key]; + visualElement.setStaticValue(key, 0); + if (sharedAnimationValues) { + sharedAnimationValues[key] = 0; + } + } +} +function cancelTreeOptimisedTransformAnimations(projectionNode) { + projectionNode.hasCheckedOptimisedAppear = true; + if (projectionNode.root === projectionNode) + return; + const { visualElement } = projectionNode.options; + if (!visualElement) + return; + const appearId = getOptimisedAppearId(visualElement); + if (window.MotionHasOptimisedAnimation(appearId, "transform")) { + const { layout: layout2, layoutId } = projectionNode.options; + window.MotionCancelOptimisedAnimation(appearId, "transform", frame, !(layout2 || layoutId)); + } + const { parent } = projectionNode; + if (parent && !parent.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(parent); + } +} +function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform }) { + return class ProjectionNode { + constructor(latestValues = {}, parent = defaultParent?.()) { + this.id = id$1++; + this.animationId = 0; + this.animationCommitId = 0; + this.children = /* @__PURE__ */ new Set(); + this.options = {}; + this.isTreeAnimating = false; + this.isAnimationBlocked = false; + this.isLayoutDirty = false; + this.isProjectionDirty = false; + this.isSharedProjectionDirty = false; + this.isTransformDirty = false; + this.updateManuallyBlocked = false; + this.updateBlockedByResize = false; + this.isUpdating = false; + this.isSVG = false; + this.needsReset = false; + this.shouldResetTransform = false; + this.hasCheckedOptimisedAppear = false; + this.treeScale = { x: 1, y: 1 }; + this.eventHandlers = /* @__PURE__ */ new Map(); + this.hasTreeAnimated = false; + this.layoutVersion = 0; + this.updateScheduled = false; + this.scheduleUpdate = () => this.update(); + this.projectionUpdateScheduled = false; + this.checkUpdateFailed = () => { + if (this.isUpdating) { + this.isUpdating = false; + this.clearAllSnapshots(); + } + }; + this.updateProjection = () => { + this.projectionUpdateScheduled = false; + this.nodes.forEach(propagateDirtyNodes); + this.nodes.forEach(resolveTargetDelta); + this.nodes.forEach(calcProjection); + this.nodes.forEach(cleanDirtyNodes); + }; + this.resolvedRelativeTargetAt = 0; + this.linkedParentVersion = 0; + this.hasProjected = false; + this.isVisible = true; + this.animationProgress = 0; + this.sharedNodes = /* @__PURE__ */ new Map(); + this.latestValues = latestValues; + this.root = parent ? parent.root || parent : this; + this.path = parent ? [...parent.path, parent] : []; + this.parent = parent; + this.depth = parent ? parent.depth + 1 : 0; + for (let i = 0; i < this.path.length; i++) { + this.path[i].shouldResetTransform = true; + } + if (this.root === this) + this.nodes = new FlatTree(); + } + addEventListener(name, handler) { + if (!this.eventHandlers.has(name)) { + this.eventHandlers.set(name, new SubscriptionManager()); + } + return this.eventHandlers.get(name).add(handler); + } + notifyListeners(name, ...args) { + const subscriptionManager = this.eventHandlers.get(name); + subscriptionManager && subscriptionManager.notify(...args); + } + hasListeners(name) { + return this.eventHandlers.has(name); + } + /** + * Lifecycles + */ + mount(instance) { + if (this.instance) + return; + this.isSVG = isSVGElement(instance) && !isSVGSVGElement(instance); + this.instance = instance; + const { layoutId, layout: layout2, visualElement } = this.options; + if (visualElement && !visualElement.current) { + visualElement.mount(instance); + } + this.root.nodes.add(this); + this.parent && this.parent.children.add(this); + if (this.root.hasTreeAnimated && (layout2 || layoutId)) { + this.isLayoutDirty = true; + } + if (attachResizeListener) { + let cancelDelay; + let innerWidth = 0; + const resizeUnblockUpdate = () => this.root.updateBlockedByResize = false; + frame.read(() => { + innerWidth = window.innerWidth; + }); + attachResizeListener(instance, () => { + const newInnerWidth = window.innerWidth; + if (newInnerWidth === innerWidth) + return; + innerWidth = newInnerWidth; + this.root.updateBlockedByResize = true; + cancelDelay && cancelDelay(); + cancelDelay = delay(resizeUnblockUpdate, 250); + if (globalProjectionState.hasAnimatedSinceResize) { + globalProjectionState.hasAnimatedSinceResize = false; + this.nodes.forEach(finishAnimation); + } + }); + } + if (layoutId) { + this.root.registerSharedNode(layoutId, this); + } + if (this.options.animate !== false && visualElement && (layoutId || layout2)) { + this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout }) => { + if (this.isTreeAnimationBlocked()) { + this.target = void 0; + this.relativeTarget = void 0; + return; + } + const layoutTransition = this.options.transition || visualElement.getDefaultTransition() || defaultLayoutTransition; + const { onLayoutAnimationStart, onLayoutAnimationComplete } = visualElement.getProps(); + const hasTargetChanged = !this.targetLayout || !boxEqualsRounded(this.targetLayout, newLayout); + const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged; + if (this.options.layoutRoot || this.resumeFrom || hasOnlyRelativeTargetChanged || hasLayoutChanged && (hasTargetChanged || !this.currentAnimation)) { + if (this.resumeFrom) { + this.resumingFrom = this.resumeFrom; + this.resumingFrom.resumingFrom = void 0; + } + const animationOptions = { + ...getValueTransition(layoutTransition, "layout"), + onPlay: onLayoutAnimationStart, + onComplete: onLayoutAnimationComplete + }; + if (visualElement.shouldReduceMotion || this.options.layoutRoot) { + animationOptions.delay = 0; + animationOptions.type = false; + } + this.startAnimation(animationOptions); + this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); + } else { + if (!hasLayoutChanged) { + finishAnimation(this); + } + if (this.isLead() && this.options.onExitComplete) { + this.options.onExitComplete(); + } + } + this.targetLayout = newLayout; + }); + } + } + unmount() { + this.options.layoutId && this.willUpdate(); + this.root.nodes.remove(this); + const stack = this.getStack(); + stack && stack.remove(this); + this.parent && this.parent.children.delete(this); + this.instance = void 0; + this.eventHandlers.clear(); + cancelFrame(this.updateProjection); + } + // only on the root + blockUpdate() { + this.updateManuallyBlocked = true; + } + unblockUpdate() { + this.updateManuallyBlocked = false; + } + isUpdateBlocked() { + return this.updateManuallyBlocked || this.updateBlockedByResize; + } + isTreeAnimationBlocked() { + return this.isAnimationBlocked || this.parent && this.parent.isTreeAnimationBlocked() || false; + } + // Note: currently only running on root node + startUpdate() { + if (this.isUpdateBlocked()) + return; + this.isUpdating = true; + this.nodes && this.nodes.forEach(resetSkewAndRotation); + this.animationId++; + } + getTransformTemplate() { + const { visualElement } = this.options; + return visualElement && visualElement.getProps().transformTemplate; + } + willUpdate(shouldNotifyListeners = true) { + this.root.hasTreeAnimated = true; + if (this.root.isUpdateBlocked()) { + this.options.onExitComplete && this.options.onExitComplete(); + return; + } + if (window.MotionCancelOptimisedAnimation && !this.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(this); + } + !this.root.isUpdating && this.root.startUpdate(); + if (this.isLayoutDirty) + return; + this.isLayoutDirty = true; + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.shouldResetTransform = true; + if (typeof node.latestValues.x === "string" || typeof node.latestValues.y === "string") { + node.isLayoutDirty = true; + } + node.updateScroll("snapshot"); + if (node.options.layoutRoot) { + node.willUpdate(false); + } + } + const { layoutId, layout: layout2 } = this.options; + if (layoutId === void 0 && !layout2) + return; + const transformTemplate = this.getTransformTemplate(); + this.prevTransformTemplateValue = transformTemplate ? transformTemplate(this.latestValues, "") : void 0; + this.updateSnapshot(); + shouldNotifyListeners && this.notifyListeners("willUpdate"); + } + update() { + this.updateScheduled = false; + const updateWasBlocked = this.isUpdateBlocked(); + if (updateWasBlocked) { + const wasBlockedByResize = this.updateBlockedByResize; + this.unblockUpdate(); + this.updateBlockedByResize = false; + this.clearAllSnapshots(); + if (wasBlockedByResize) { + this.nodes.forEach(forceLayoutMeasure); + } + this.nodes.forEach(clearMeasurements); + return; + } + if (this.animationId <= this.animationCommitId) { + this.nodes.forEach(clearIsLayoutDirty); + return; + } + this.animationCommitId = this.animationId; + if (!this.isUpdating) { + this.nodes.forEach(clearIsLayoutDirty); + } else { + this.isUpdating = false; + this.nodes.forEach(ensureDraggedNodesSnapshotted); + this.nodes.forEach(resetTransformStyle); + this.nodes.forEach(updateLayout); + this.nodes.forEach(notifyLayoutUpdate); + } + this.clearAllSnapshots(); + const now2 = time.now(); + frameData.delta = clamp(0, 1e3 / 60, now2 - frameData.timestamp); + frameData.timestamp = now2; + frameData.isProcessing = true; + frameSteps.update.process(frameData); + frameSteps.preRender.process(frameData); + frameSteps.render.process(frameData); + frameData.isProcessing = false; + } + didUpdate() { + if (!this.updateScheduled) { + this.updateScheduled = true; + microtask.read(this.scheduleUpdate); + } + } + clearAllSnapshots() { + this.nodes.forEach(clearSnapshot); + this.sharedNodes.forEach(removeLeadSnapshots); + } + scheduleUpdateProjection() { + if (!this.projectionUpdateScheduled) { + this.projectionUpdateScheduled = true; + frame.preRender(this.updateProjection, false, true); + } + } + scheduleCheckAfterUnmount() { + frame.postRender(() => { + if (this.isLayoutDirty) { + this.root.didUpdate(); + } else { + this.root.checkUpdateFailed(); + } + }); + } + /** + * Update measurements + */ + updateSnapshot() { + if (this.snapshot || !this.instance) + return; + this.snapshot = this.measure(); + if (this.snapshot && !calcLength(this.snapshot.measuredBox.x) && !calcLength(this.snapshot.measuredBox.y)) { + this.snapshot = void 0; + } + } + updateLayout() { + if (!this.instance) + return; + this.updateScroll(); + if (!(this.options.alwaysMeasureLayout && this.isLead()) && !this.isLayoutDirty) { + return; + } + if (this.resumeFrom && !this.resumeFrom.instance) { + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.updateScroll(); + } + } + const prevLayout = this.layout; + this.layout = this.measure(false); + this.layoutVersion++; + if (!this.layoutCorrected) + this.layoutCorrected = createBox(); + this.isLayoutDirty = false; + this.projectionDelta = void 0; + this.notifyListeners("measure", this.layout.layoutBox); + const { visualElement } = this.options; + visualElement && visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : void 0); + } + updateScroll(phase = "measure") { + let needsMeasurement = Boolean(this.options.layoutScroll && this.instance); + if (this.scroll && this.scroll.animationId === this.root.animationId && this.scroll.phase === phase) { + needsMeasurement = false; + } + if (needsMeasurement && this.instance) { + const isRoot = checkIsScrollRoot(this.instance); + this.scroll = { + animationId: this.root.animationId, + phase, + isRoot, + offset: measureScroll(this.instance), + wasRoot: this.scroll ? this.scroll.isRoot : isRoot + }; + } + } + resetTransform() { + if (!resetTransform) + return; + const isResetRequested = this.isLayoutDirty || this.shouldResetTransform || this.options.alwaysMeasureLayout; + const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); + const transformTemplate = this.getTransformTemplate(); + const transformTemplateValue = transformTemplate ? transformTemplate(this.latestValues, "") : void 0; + const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; + if (isResetRequested && this.instance && (hasProjection || hasTransform(this.latestValues) || transformTemplateHasChanged)) { + resetTransform(this.instance, transformTemplateValue); + this.shouldResetTransform = false; + this.scheduleRender(); + } + } + measure(removeTransform = true) { + const pageBox = this.measurePageBox(); + let layoutBox = this.removeElementScroll(pageBox); + if (removeTransform) { + layoutBox = this.removeTransform(layoutBox); + } + roundBox(layoutBox); + return { + animationId: this.root.animationId, + measuredBox: pageBox, + layoutBox, + latestValues: {}, + source: this.id + }; + } + measurePageBox() { + const { visualElement } = this.options; + if (!visualElement) + return createBox(); + const box = visualElement.measureViewportBox(); + const wasInScrollRoot = this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot); + if (!wasInScrollRoot) { + const { scroll } = this.root; + if (scroll) { + translateAxis(box.x, scroll.offset.x); + translateAxis(box.y, scroll.offset.y); + } + } + return box; + } + removeElementScroll(box) { + const boxWithoutScroll = createBox(); + copyBoxInto(boxWithoutScroll, box); + if (this.scroll?.wasRoot) { + return boxWithoutScroll; + } + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + const { scroll, options } = node; + if (node !== this.root && scroll && options.layoutScroll) { + if (scroll.wasRoot) { + copyBoxInto(boxWithoutScroll, box); + } + translateAxis(boxWithoutScroll.x, scroll.offset.x); + translateAxis(boxWithoutScroll.y, scroll.offset.y); + } + } + return boxWithoutScroll; + } + applyTransform(box, transformOnly = false, output) { + const withTransforms = output || createBox(); + copyBoxInto(withTransforms, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!transformOnly && node.options.layoutScroll && node.scroll && node !== node.root) { + translateAxis(withTransforms.x, -node.scroll.offset.x); + translateAxis(withTransforms.y, -node.scroll.offset.y); + } + if (!hasTransform(node.latestValues)) + continue; + transformBox(withTransforms, node.latestValues, node.layout?.layoutBox); + } + if (hasTransform(this.latestValues)) { + transformBox(withTransforms, this.latestValues, this.layout?.layoutBox); + } + return withTransforms; + } + removeTransform(box) { + const boxWithoutTransform = createBox(); + copyBoxInto(boxWithoutTransform, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!hasTransform(node.latestValues)) + continue; + let sourceBox; + if (node.instance) { + hasScale(node.latestValues) && node.updateSnapshot(); + sourceBox = createBox(); + copyBoxInto(sourceBox, node.measurePageBox()); + } + removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot?.layoutBox, sourceBox); + } + if (hasTransform(this.latestValues)) { + removeBoxTransforms(boxWithoutTransform, this.latestValues); + } + return boxWithoutTransform; + } + setTargetDelta(delta) { + this.targetDelta = delta; + this.root.scheduleUpdateProjection(); + this.isProjectionDirty = true; + } + setOptions(options) { + this.options = { + ...this.options, + ...options, + crossfade: options.crossfade !== void 0 ? options.crossfade : true + }; + } + clearMeasurements() { + this.scroll = void 0; + this.layout = void 0; + this.snapshot = void 0; + this.prevTransformTemplateValue = void 0; + this.targetDelta = void 0; + this.target = void 0; + this.isLayoutDirty = false; + } + forceRelativeParentToResolveTarget() { + if (!this.relativeParent) + return; + if (this.relativeParent.resolvedRelativeTargetAt !== frameData.timestamp) { + this.relativeParent.resolveTargetDelta(true); + } + } + resolveTargetDelta(forceRecalculation = false) { + const lead = this.getLead(); + this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty); + this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty); + this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty); + const isShared = Boolean(this.resumingFrom) || this !== lead; + const canSkip = !(forceRecalculation || isShared && this.isSharedProjectionDirty || this.isProjectionDirty || this.parent?.isProjectionDirty || this.attemptToResolveRelativeTarget || this.root.updateBlockedByResize); + if (canSkip) + return; + const { layout: layout2, layoutId } = this.options; + if (!this.layout || !(layout2 || layoutId)) + return; + this.resolvedRelativeTargetAt = frameData.timestamp; + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && this.linkedParentVersion !== relativeParent.layoutVersion && !relativeParent.options.layoutRoot) { + this.removeRelativeTarget(); + } + if (!this.targetDelta && !this.relativeTarget) { + if (this.options.layoutAnchor !== false && relativeParent && relativeParent.layout) { + this.createRelativeTarget(relativeParent, this.layout.layoutBox, relativeParent.layout.layoutBox); + } else { + this.removeRelativeTarget(); + } + } + if (!this.relativeTarget && !this.targetDelta) + return; + if (!this.target) { + this.target = createBox(); + this.targetWithTransforms = createBox(); + } + if (this.relativeTarget && this.relativeTargetOrigin && this.relativeParent && this.relativeParent.target) { + this.forceRelativeParentToResolveTarget(); + calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target, this.options.layoutAnchor || void 0); + } else if (this.targetDelta) { + if (Boolean(this.resumingFrom)) { + this.applyTransform(this.layout.layoutBox, false, this.target); + } else { + copyBoxInto(this.target, this.layout.layoutBox); + } + applyBoxDelta(this.target, this.targetDelta); + } else { + copyBoxInto(this.target, this.layout.layoutBox); + } + if (this.attemptToResolveRelativeTarget) { + this.attemptToResolveRelativeTarget = false; + if (this.options.layoutAnchor !== false && relativeParent && Boolean(relativeParent.resumingFrom) === Boolean(this.resumingFrom) && !relativeParent.options.layoutScroll && relativeParent.target && this.animationProgress !== 1) { + this.createRelativeTarget(relativeParent, this.target, relativeParent.target); + } else { + this.relativeParent = this.relativeTarget = void 0; + } + } + } + getClosestProjectingParent() { + if (!this.parent || hasScale(this.parent.latestValues) || has2DTranslate(this.parent.latestValues)) { + return void 0; + } + if (this.parent.isProjecting()) { + return this.parent; + } else { + return this.parent.getClosestProjectingParent(); + } + } + isProjecting() { + return Boolean((this.relativeTarget || this.targetDelta || this.options.layoutRoot) && this.layout); + } + createRelativeTarget(relativeParent, layout2, parentLayout) { + this.relativeParent = relativeParent; + this.linkedParentVersion = relativeParent.layoutVersion; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, layout2, parentLayout, this.options.layoutAnchor || void 0); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + removeRelativeTarget() { + this.relativeParent = this.relativeTarget = void 0; + } + calcProjection() { + const lead = this.getLead(); + const isShared = Boolean(this.resumingFrom) || this !== lead; + let canSkip = true; + if (this.isProjectionDirty || this.parent?.isProjectionDirty) { + canSkip = false; + } + if (isShared && (this.isSharedProjectionDirty || this.isTransformDirty)) { + canSkip = false; + } + if (this.resolvedRelativeTargetAt === frameData.timestamp) { + canSkip = false; + } + if (canSkip) + return; + const { layout: layout2, layoutId } = this.options; + this.isTreeAnimating = Boolean(this.parent && this.parent.isTreeAnimating || this.currentAnimation || this.pendingAnimation); + if (!this.isTreeAnimating) { + this.targetDelta = this.relativeTarget = void 0; + } + if (!this.layout || !(layout2 || layoutId)) + return; + copyBoxInto(this.layoutCorrected, this.layout.layoutBox); + const prevTreeScaleX = this.treeScale.x; + const prevTreeScaleY = this.treeScale.y; + applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared); + if (lead.layout && !lead.target && (this.treeScale.x !== 1 || this.treeScale.y !== 1)) { + lead.target = lead.layout.layoutBox; + lead.targetWithTransforms = createBox(); + } + const { target } = lead; + if (!target) { + if (this.prevProjectionDelta) { + this.createProjectionDeltas(); + this.scheduleRender(); + } + return; + } + if (!this.projectionDelta || !this.prevProjectionDelta) { + this.createProjectionDeltas(); + } else { + copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x); + copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y); + } + calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); + if (this.treeScale.x !== prevTreeScaleX || this.treeScale.y !== prevTreeScaleY || !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) || !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) { + this.hasProjected = true; + this.scheduleRender(); + this.notifyListeners("projectionUpdate", target); + } + } + hide() { + this.isVisible = false; + } + show() { + this.isVisible = true; + } + scheduleRender(notifyAll2 = true) { + this.options.visualElement?.scheduleRender(); + if (notifyAll2) { + const stack = this.getStack(); + stack && stack.scheduleRender(); + } + if (this.resumingFrom && !this.resumingFrom.instance) { + this.resumingFrom = void 0; + } + } + createProjectionDeltas() { + this.prevProjectionDelta = createDelta(); + this.projectionDelta = createDelta(); + this.projectionDeltaWithTransform = createDelta(); + } + setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) { + const snapshot = this.snapshot; + const snapshotLatestValues = snapshot ? snapshot.latestValues : {}; + const mixedValues = { ...this.latestValues }; + const targetDelta = createDelta(); + if (!this.relativeParent || !this.relativeParent.options.layoutRoot) { + this.relativeTarget = this.relativeTargetOrigin = void 0; + } + this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; + const relativeLayout = createBox(); + const snapshotSource = snapshot ? snapshot.source : void 0; + const layoutSource = this.layout ? this.layout.source : void 0; + const isSharedLayoutAnimation = snapshotSource !== layoutSource; + const stack = this.getStack(); + const isOnlyMember = !stack || stack.members.length <= 1; + const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && !isOnlyMember && this.options.crossfade === true && !this.path.some(hasOpacityCrossfade)); + this.animationProgress = 0; + let prevRelativeTarget; + this.mixTargetDelta = (latest) => { + const progress2 = latest / 1e3; + mixAxisDelta(targetDelta.x, delta.x, progress2); + mixAxisDelta(targetDelta.y, delta.y, progress2); + this.setTargetDelta(targetDelta); + if (this.relativeTarget && this.relativeTargetOrigin && this.layout && this.relativeParent && this.relativeParent.layout) { + calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox, this.options.layoutAnchor || void 0); + mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress2); + if (prevRelativeTarget && boxEquals(this.relativeTarget, prevRelativeTarget)) { + this.isProjectionDirty = false; + } + if (!prevRelativeTarget) + prevRelativeTarget = createBox(); + copyBoxInto(prevRelativeTarget, this.relativeTarget); + } + if (isSharedLayoutAnimation) { + this.animationValues = mixedValues; + mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress2, shouldCrossfadeOpacity, isOnlyMember); + } + this.root.scheduleUpdateProjection(); + this.scheduleRender(); + this.animationProgress = progress2; + }; + this.mixTargetDelta(this.options.layoutRoot ? 1e3 : 0); + } + startAnimation(options) { + this.notifyListeners("animationStart"); + this.currentAnimation?.stop(); + this.resumingFrom?.currentAnimation?.stop(); + if (this.pendingAnimation) { + cancelFrame(this.pendingAnimation); + this.pendingAnimation = void 0; + } + this.pendingAnimation = frame.update(() => { + globalProjectionState.hasAnimatedSinceResize = true; + this.motionValue || (this.motionValue = motionValue(0)); + this.motionValue.jump(0, false); + this.currentAnimation = animateSingleValue(this.motionValue, [0, 1e3], { + ...options, + velocity: 0, + isSync: true, + onUpdate: (latest) => { + this.mixTargetDelta(latest); + options.onUpdate && options.onUpdate(latest); + }, + onStop: () => { + }, + onComplete: () => { + options.onComplete && options.onComplete(); + this.completeAnimation(); + } + }); + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = this.currentAnimation; + } + this.pendingAnimation = void 0; + }); + } + completeAnimation() { + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = void 0; + this.resumingFrom.preserveOpacity = void 0; + } + const stack = this.getStack(); + stack && stack.exitAnimationComplete(); + this.resumingFrom = this.currentAnimation = this.animationValues = void 0; + this.notifyListeners("animationComplete"); + } + finishAnimation() { + if (this.currentAnimation) { + this.mixTargetDelta && this.mixTargetDelta(animationTarget); + this.currentAnimation.stop(); + } + this.completeAnimation(); + } + applyTransformsToTarget() { + const lead = this.getLead(); + let { targetWithTransforms, target, layout: layout2, latestValues } = lead; + if (!targetWithTransforms || !target || !layout2) + return; + if (this !== lead && this.layout && layout2 && shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout2.layoutBox)) { + target = this.target || createBox(); + const xLength = calcLength(this.layout.layoutBox.x); + target.x.min = lead.target.x.min; + target.x.max = target.x.min + xLength; + const yLength = calcLength(this.layout.layoutBox.y); + target.y.min = lead.target.y.min; + target.y.max = target.y.min + yLength; + } + copyBoxInto(targetWithTransforms, target); + transformBox(targetWithTransforms, latestValues); + calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); + } + registerSharedNode(layoutId, node) { + if (!this.sharedNodes.has(layoutId)) { + this.sharedNodes.set(layoutId, new NodeStack()); + } + const stack = this.sharedNodes.get(layoutId); + stack.add(node); + const config = node.options.initialPromotionConfig; + node.promote({ + transition: config ? config.transition : void 0, + preserveFollowOpacity: config && config.shouldPreserveFollowOpacity ? config.shouldPreserveFollowOpacity(node) : void 0 + }); + } + isLead() { + const stack = this.getStack(); + return stack ? stack.lead === this : true; + } + getLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.lead || this : this; + } + getPrevLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.prevLead : void 0; + } + getStack() { + const { layoutId } = this.options; + if (layoutId) + return this.root.sharedNodes.get(layoutId); + } + promote({ needsReset, transition, preserveFollowOpacity } = {}) { + const stack = this.getStack(); + if (stack) + stack.promote(this, preserveFollowOpacity); + if (needsReset) { + this.projectionDelta = void 0; + this.needsReset = true; + } + if (transition) + this.setOptions({ transition }); + } + relegate() { + const stack = this.getStack(); + if (stack) { + return stack.relegate(this); + } else { + return false; + } + } + resetSkewAndRotation() { + const { visualElement } = this.options; + if (!visualElement) + return; + let hasDistortingTransform = false; + const { latestValues } = visualElement; + if (latestValues.z || latestValues.rotate || latestValues.rotateX || latestValues.rotateY || latestValues.rotateZ || latestValues.skewX || latestValues.skewY) { + hasDistortingTransform = true; + } + if (!hasDistortingTransform) + return; + const resetValues = {}; + if (latestValues.z) { + resetDistortingTransform("z", visualElement, resetValues, this.animationValues); + } + for (let i = 0; i < transformAxes.length; i++) { + resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + } + visualElement.render(); + for (const key in resetValues) { + visualElement.setStaticValue(key, resetValues[key]); + if (this.animationValues) { + this.animationValues[key] = resetValues[key]; + } + } + visualElement.scheduleRender(); + } + applyProjectionStyles(targetStyle, styleProp) { + if (!this.instance || this.isSVG) + return; + if (!this.isVisible) { + targetStyle.visibility = "hidden"; + return; + } + const transformTemplate = this.getTransformTemplate(); + if (this.needsReset) { + this.needsReset = false; + targetStyle.visibility = ""; + targetStyle.opacity = ""; + targetStyle.pointerEvents = resolveMotionValue(styleProp?.pointerEvents) || ""; + targetStyle.transform = transformTemplate ? transformTemplate(this.latestValues, "") : "none"; + return; + } + const lead = this.getLead(); + if (!this.projectionDelta || !this.layout || !lead.target) { + if (this.options.layoutId) { + targetStyle.opacity = this.latestValues.opacity !== void 0 ? this.latestValues.opacity : 1; + targetStyle.pointerEvents = resolveMotionValue(styleProp?.pointerEvents) || ""; + } + if (this.hasProjected && !hasTransform(this.latestValues)) { + targetStyle.transform = transformTemplate ? transformTemplate({}, "") : "none"; + this.hasProjected = false; + } + return; + } + targetStyle.visibility = ""; + const valuesToRender = lead.animationValues || lead.latestValues; + this.applyTransformsToTarget(); + let transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); + if (transformTemplate) { + transform = transformTemplate(valuesToRender, transform); + } + targetStyle.transform = transform; + const { x, y } = this.projectionDelta; + targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`; + if (lead.animationValues) { + targetStyle.opacity = lead === this ? valuesToRender.opacity ?? this.latestValues.opacity ?? 1 : this.preserveOpacity ? this.latestValues.opacity : valuesToRender.opacityExit; + } else { + targetStyle.opacity = lead === this ? valuesToRender.opacity !== void 0 ? valuesToRender.opacity : "" : valuesToRender.opacityExit !== void 0 ? valuesToRender.opacityExit : 0; + } + for (const key in scaleCorrectors) { + if (valuesToRender[key] === void 0) + continue; + const { correct, applyTo, isCSSVariable } = scaleCorrectors[key]; + const corrected = transform === "none" ? valuesToRender[key] : correct(valuesToRender[key], lead); + if (applyTo) { + const num = applyTo.length; + for (let i = 0; i < num; i++) { + targetStyle[applyTo[i]] = corrected; + } + } else { + if (isCSSVariable) { + this.options.visualElement.renderState.vars[key] = corrected; + } else { + targetStyle[key] = corrected; + } + } + } + if (this.options.layoutId) { + targetStyle.pointerEvents = lead === this ? resolveMotionValue(styleProp?.pointerEvents) || "" : "none"; + } + } + clearSnapshot() { + this.resumeFrom = this.snapshot = void 0; + } + // Only run on root + resetTree() { + this.root.nodes.forEach((node) => node.currentAnimation?.stop()); + this.root.nodes.forEach(clearMeasurements); + this.root.sharedNodes.clear(); + } + }; +} +function updateLayout(node) { + node.updateLayout(); +} +function notifyLayoutUpdate(node) { + const snapshot = node.resumeFrom?.snapshot || node.snapshot; + if (node.isLead() && node.layout && snapshot && node.hasListeners("didUpdate")) { + const { layoutBox: layout2, measuredBox: measuredLayout } = node.layout; + const { animationType } = node.options; + const isShared = snapshot.source !== node.layout.source; + if (animationType === "size") { + eachAxis((axis) => { + const axisSnapshot = isShared ? snapshot.measuredBox[axis] : snapshot.layoutBox[axis]; + const length = calcLength(axisSnapshot); + axisSnapshot.min = layout2[axis].min; + axisSnapshot.max = axisSnapshot.min + length; + }); + } else if (animationType === "x" || animationType === "y") { + const snapAxis = animationType === "x" ? "y" : "x"; + copyAxisInto(isShared ? snapshot.measuredBox[snapAxis] : snapshot.layoutBox[snapAxis], layout2[snapAxis]); + } else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout2)) { + eachAxis((axis) => { + const axisSnapshot = isShared ? snapshot.measuredBox[axis] : snapshot.layoutBox[axis]; + const length = calcLength(layout2[axis]); + axisSnapshot.max = axisSnapshot.min + length; + if (node.relativeTarget && !node.currentAnimation) { + node.isProjectionDirty = true; + node.relativeTarget[axis].max = node.relativeTarget[axis].min + length; + } + }); + } + const layoutDelta = createDelta(); + calcBoxDelta(layoutDelta, layout2, snapshot.layoutBox); + const visualDelta = createDelta(); + if (isShared) { + calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox); + } else { + calcBoxDelta(visualDelta, layout2, snapshot.layoutBox); + } + const hasLayoutChanged = !isDeltaZero(layoutDelta); + let hasRelativeLayoutChanged = false; + if (!node.resumeFrom) { + const relativeParent = node.getClosestProjectingParent(); + if (relativeParent && !relativeParent.resumeFrom) { + const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent; + if (parentSnapshot && parentLayout) { + const anchor = node.options.layoutAnchor || void 0; + const relativeSnapshot = createBox(); + calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox, anchor); + const relativeLayout = createBox(); + calcRelativePosition(relativeLayout, layout2, parentLayout.layoutBox, anchor); + if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) { + hasRelativeLayoutChanged = true; + } + if (relativeParent.options.layoutRoot) { + node.relativeTarget = relativeLayout; + node.relativeTargetOrigin = relativeSnapshot; + node.relativeParent = relativeParent; + } + } + } + } + node.notifyListeners("didUpdate", { + layout: layout2, + snapshot, + delta: visualDelta, + layoutDelta, + hasLayoutChanged, + hasRelativeLayoutChanged + }); + } else if (node.isLead()) { + const { onExitComplete } = node.options; + onExitComplete && onExitComplete(); + } + node.options.transition = void 0; +} +function propagateDirtyNodes(node) { + if (!node.parent) + return; + if (!node.isProjecting()) { + node.isProjectionDirty = node.parent.isProjectionDirty; + } + node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty || node.parent.isProjectionDirty || node.parent.isSharedProjectionDirty)); + node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty); +} +function cleanDirtyNodes(node) { + node.isProjectionDirty = node.isSharedProjectionDirty = node.isTransformDirty = false; +} +function clearSnapshot(node) { + node.clearSnapshot(); +} +function clearMeasurements(node) { + node.clearMeasurements(); +} +function forceLayoutMeasure(node) { + node.isLayoutDirty = true; + node.updateLayout(); +} +function clearIsLayoutDirty(node) { + node.isLayoutDirty = false; +} +function ensureDraggedNodesSnapshotted(node) { + if (node.isAnimationBlocked && node.layout && !node.isLayoutDirty) { + node.snapshot = node.layout; + node.isLayoutDirty = true; + } +} +function resetTransformStyle(node) { + const { visualElement } = node.options; + if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) { + visualElement.notify("BeforeLayoutMeasure"); + } + node.resetTransform(); +} +function finishAnimation(node) { + node.finishAnimation(); + node.targetDelta = node.relativeTarget = node.target = void 0; + node.isProjectionDirty = true; +} +function resolveTargetDelta(node) { + node.resolveTargetDelta(); +} +function calcProjection(node) { + node.calcProjection(); +} +function resetSkewAndRotation(node) { + node.resetSkewAndRotation(); +} +function removeLeadSnapshots(stack) { + stack.removeLeadSnapshot(); +} +function mixAxisDelta(output, delta, p) { + output.translate = mixNumber$1(delta.translate, 0, p); + output.scale = mixNumber$1(delta.scale, 1, p); + output.origin = delta.origin; + output.originPoint = delta.originPoint; +} +function mixAxis(output, from, to, p) { + output.min = mixNumber$1(from.min, to.min, p); + output.max = mixNumber$1(from.max, to.max, p); +} +function mixBox(output, from, to, p) { + mixAxis(output.x, from.x, to.x, p); + mixAxis(output.y, from.y, to.y, p); +} +function hasOpacityCrossfade(node) { + return node.animationValues && node.animationValues.opacityExit !== void 0; +} +const defaultLayoutTransition = { + duration: 0.45, + ease: [0.4, 0, 0.1, 1] +}; +const userAgentContains = (string) => typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().includes(string); +const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/") ? Math.round : noop; +function roundAxis(axis) { + axis.min = roundPoint(axis.min); + axis.max = roundPoint(axis.max); +} +function roundBox(box) { + roundAxis(box.x); + roundAxis(box.y); +} +function shouldAnimatePositionOnly(animationType, snapshot, layout2) { + return animationType === "position" || animationType === "preserve-aspect" && !isNear(aspectRatio(snapshot), aspectRatio(layout2), 0.2); +} +function checkNodeWasScrollRoot(node) { + return node !== node.root && node.scroll?.wasRoot; +} +const DocumentProjectionNode = createProjectionNode$1({ + attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify), + measureScroll: () => ({ + x: document.documentElement.scrollLeft || document.body?.scrollLeft || 0, + y: document.documentElement.scrollTop || document.body?.scrollTop || 0 + }), + checkIsScrollRoot: () => true +}); +const rootProjectionNode = { + current: void 0 +}; +const HTMLProjectionNode = createProjectionNode$1({ + measureScroll: (instance) => ({ + x: instance.scrollLeft, + y: instance.scrollTop + }), + defaultParent: () => { + if (!rootProjectionNode.current) { + const documentNode = new DocumentProjectionNode({}); + documentNode.mount(window); + documentNode.setOptions({ layoutScroll: true }); + rootProjectionNode.current = documentNode; + } + return rootProjectionNode.current; + }, + resetTransform: (instance, value) => { + instance.style.transform = value !== void 0 ? value : "none"; + }, + checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed") +}); +const MotionConfigContext = reactExports.createContext({ + transformPagePoint: (p) => p, + isStatic: false, + reducedMotion: "never" +}); +function setRef(ref, value) { + if (typeof ref === "function") { + return ref(value); + } else if (ref !== null && ref !== void 0) { + ref.current = value; + } +} +function composeRefs(...refs) { + return (node) => { + let hasCleanup = false; + const cleanups = refs.map((ref) => { + const cleanup = setRef(ref, node); + if (!hasCleanup && typeof cleanup === "function") { + hasCleanup = true; + } + return cleanup; + }); + if (hasCleanup) { + return () => { + for (let i = 0; i < cleanups.length; i++) { + const cleanup = cleanups[i]; + if (typeof cleanup === "function") { + cleanup(); + } else { + setRef(refs[i], null); + } + } + }; + } + }; +} +function useComposedRefs(...refs) { + return reactExports.useCallback(composeRefs(...refs), refs); +} +class PopChildMeasure extends reactExports.Component { + getSnapshotBeforeUpdate(prevProps) { + const element = this.props.childRef.current; + if (isHTMLElement(element) && prevProps.isPresent && !this.props.isPresent && this.props.pop !== false) { + const parent = element.offsetParent; + const parentWidth = isHTMLElement(parent) ? parent.offsetWidth || 0 : 0; + const parentHeight = isHTMLElement(parent) ? parent.offsetHeight || 0 : 0; + const computedStyle = getComputedStyle(element); + const size = this.props.sizeRef.current; + size.height = parseFloat(computedStyle.height); + size.width = parseFloat(computedStyle.width); + size.top = element.offsetTop; + size.left = element.offsetLeft; + size.right = parentWidth - size.width - size.left; + size.bottom = parentHeight - size.height - size.top; + } + return null; + } + /** + * Required with getSnapshotBeforeUpdate to stop React complaining. + */ + componentDidUpdate() { + } + render() { + return this.props.children; + } +} +function PopChild({ children, isPresent, anchorX, anchorY, root, pop }) { + const id2 = reactExports.useId(); + const ref = reactExports.useRef(null); + const size = reactExports.useRef({ + width: 0, + height: 0, + top: 0, + left: 0, + right: 0, + bottom: 0 + }); + const { nonce } = reactExports.useContext(MotionConfigContext); + const childRef = children.props?.ref ?? children?.ref; + const composedRef = useComposedRefs(ref, childRef); + reactExports.useInsertionEffect(() => { + const { width, height, top, left, right, bottom } = size.current; + if (isPresent || pop === false || !ref.current || !width || !height) + return; + const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`; + const y = anchorY === "bottom" ? `bottom: ${bottom}` : `top: ${top}`; + ref.current.dataset.motionPopId = id2; + const style = document.createElement("style"); + if (nonce) + style.nonce = nonce; + const parent = root ?? document.head; + parent.appendChild(style); + if (style.sheet) { + style.sheet.insertRule(` + [data-motion-pop-id="${id2}"] { + position: absolute !important; + width: ${width}px !important; + height: ${height}px !important; + ${x}px !important; + ${y}px !important; + } + `); + } + return () => { + ref.current?.removeAttribute("data-motion-pop-id"); + if (parent.contains(style)) { + parent.removeChild(style); + } + }; + }, [isPresent]); + return jsxRuntimeExports.jsx(PopChildMeasure, { isPresent, childRef: ref, sizeRef: size, pop, children: pop === false ? children : reactExports.cloneElement(children, { ref: composedRef }) }); +} +const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, anchorY, root }) => { + const presenceChildren = useConstant(newChildrenMap); + const id2 = reactExports.useId(); + let isReusedContext = true; + let context = reactExports.useMemo(() => { + isReusedContext = false; + return { + id: id2, + initial, + isPresent, + custom, + onExitComplete: (childId) => { + presenceChildren.set(childId, true); + for (const isComplete of presenceChildren.values()) { + if (!isComplete) + return; + } + onExitComplete && onExitComplete(); + }, + register: (childId) => { + presenceChildren.set(childId, false); + return () => presenceChildren.delete(childId); + } + }; + }, [isPresent, presenceChildren, onExitComplete]); + if (presenceAffectsLayout && isReusedContext) { + context = { ...context }; + } + reactExports.useMemo(() => { + presenceChildren.forEach((_, key) => presenceChildren.set(key, false)); + }, [isPresent]); + reactExports.useEffect(() => { + !isPresent && !presenceChildren.size && onExitComplete && onExitComplete(); + }, [isPresent]); + children = jsxRuntimeExports.jsx(PopChild, { pop: mode === "popLayout", isPresent, anchorX, anchorY, root, children }); + return jsxRuntimeExports.jsx(PresenceContext.Provider, { value: context, children }); +}; +function newChildrenMap() { + return /* @__PURE__ */ new Map(); +} +function usePresence(subscribe = true) { + const context = reactExports.useContext(PresenceContext); + if (context === null) + return [true, null]; + const { isPresent, onExitComplete, register } = context; + const id2 = reactExports.useId(); + reactExports.useEffect(() => { + if (subscribe) { + return register(id2); + } + }, [subscribe]); + const safeToRemove = reactExports.useCallback(() => subscribe && onExitComplete && onExitComplete(id2), [id2, onExitComplete, subscribe]); + return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; +} +const getChildKey = (child) => child.key || ""; +function onlyElements(children) { + const filtered = []; + reactExports.Children.forEach(children, (child) => { + if (reactExports.isValidElement(child)) + filtered.push(child); + }); + return filtered; +} +const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", anchorY = "top", root }) => { + const [isParentPresent, safeToRemove] = usePresence(propagate); + const presentChildren = reactExports.useMemo(() => onlyElements(children), [children]); + const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey); + const isInitialRender = reactExports.useRef(true); + const pendingPresentChildren = reactExports.useRef(presentChildren); + const exitComplete = useConstant(() => /* @__PURE__ */ new Map()); + const exitingComponents = reactExports.useRef(/* @__PURE__ */ new Set()); + const [diffedChildren, setDiffedChildren] = reactExports.useState(presentChildren); + const [renderedChildren, setRenderedChildren] = reactExports.useState(presentChildren); + useIsomorphicLayoutEffect(() => { + isInitialRender.current = false; + pendingPresentChildren.current = presentChildren; + for (let i = 0; i < renderedChildren.length; i++) { + const key = getChildKey(renderedChildren[i]); + if (!presentKeys.includes(key)) { + if (exitComplete.get(key) !== true) { + exitComplete.set(key, false); + } + } else { + exitComplete.delete(key); + exitingComponents.current.delete(key); + } + } + }, [renderedChildren, presentKeys.length, presentKeys.join("-")]); + const exitingChildren = []; + if (presentChildren !== diffedChildren) { + let nextChildren = [...presentChildren]; + for (let i = 0; i < renderedChildren.length; i++) { + const child = renderedChildren[i]; + const key = getChildKey(child); + if (!presentKeys.includes(key)) { + nextChildren.splice(i, 0, child); + exitingChildren.push(child); + } + } + if (mode === "wait" && exitingChildren.length) { + nextChildren = exitingChildren; + } + setRenderedChildren(onlyElements(nextChildren)); + setDiffedChildren(presentChildren); + return null; + } + if (process.env.NODE_ENV !== "production" && mode === "wait" && renderedChildren.length > 1) { + console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`); + } + const { forceRender } = reactExports.useContext(LayoutGroupContext); + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: renderedChildren.map((child) => { + const key = getChildKey(child); + const isPresent = propagate && !isParentPresent ? false : presentChildren === renderedChildren || presentKeys.includes(key); + const onExit = () => { + if (exitingComponents.current.has(key)) { + return; + } + if (exitComplete.has(key)) { + exitingComponents.current.add(key); + exitComplete.set(key, true); + } else { + return; + } + let isEveryExitComplete = true; + exitComplete.forEach((isExitComplete) => { + if (!isExitComplete) + isEveryExitComplete = false; + }); + if (isEveryExitComplete) { + forceRender?.(); + setRenderedChildren(pendingPresentChildren.current); + propagate && safeToRemove?.(); + onExitComplete && onExitComplete(); + } + }; + return jsxRuntimeExports.jsx(PresenceChild, { isPresent, initial: !isInitialRender.current || initial ? void 0 : false, custom, presenceAffectsLayout, mode, root, onExitComplete: isPresent ? void 0 : onExit, anchorX, anchorY, children: child }, key); + }) }); +}; +const LazyContext = reactExports.createContext({ strict: false }); +const featureProps = { + animation: [ + "animate", + "variants", + "whileHover", + "whileTap", + "exit", + "whileInView", + "whileFocus", + "whileDrag" + ], + exit: ["exit"], + drag: ["drag", "dragControls"], + focus: ["whileFocus"], + hover: ["whileHover", "onHoverStart", "onHoverEnd"], + tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], + pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], + inView: ["whileInView", "onViewportEnter", "onViewportLeave"], + layout: ["layout", "layoutId"] +}; +let isInitialized = false; +function initFeatureDefinitions() { + if (isInitialized) + return; + const initialFeatureDefinitions = {}; + for (const key in featureProps) { + initialFeatureDefinitions[key] = { + isEnabled: (props) => featureProps[key].some((name) => !!props[name]) + }; + } + setFeatureDefinitions(initialFeatureDefinitions); + isInitialized = true; +} +function getInitializedFeatureDefinitions() { + initFeatureDefinitions(); + return getFeatureDefinitions(); +} +function loadFeatures(features) { + const featureDefinitions2 = getInitializedFeatureDefinitions(); + for (const key in features) { + featureDefinitions2[key] = { + ...featureDefinitions2[key], + ...features[key] + }; + } + setFeatureDefinitions(featureDefinitions2); +} +const validMotionProps = /* @__PURE__ */ new Set([ + "animate", + "exit", + "variants", + "initial", + "style", + "values", + "variants", + "transition", + "transformTemplate", + "custom", + "inherit", + "onBeforeLayoutMeasure", + "onAnimationStart", + "onAnimationComplete", + "onUpdate", + "onDragStart", + "onDrag", + "onDragEnd", + "onMeasureDragConstraints", + "onDirectionLock", + "onDragTransitionEnd", + "_dragX", + "_dragY", + "onHoverStart", + "onHoverEnd", + "onViewportEnter", + "onViewportLeave", + "globalTapTarget", + "propagate", + "ignoreStrict", + "viewport" +]); +function isValidMotionProp(key) { + return key.startsWith("while") || key.startsWith("drag") && key !== "draggable" || key.startsWith("layout") || key.startsWith("onTap") || key.startsWith("onPan") || key.startsWith("onLayout") || validMotionProps.has(key); +} +let shouldForward = (key) => !isValidMotionProp(key); +function loadExternalIsValidProp(isValidProp) { + if (typeof isValidProp !== "function") + return; + shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); +} +try { + const emotionPkg = "@emotion/is-prop-valid"; + loadExternalIsValidProp(require(emotionPkg).default); +} catch { +} +function filterProps(props, isDom, forwardMotionProps) { + const filteredProps = {}; + for (const key in props) { + if (key === "values" && typeof props.values === "object") + continue; + if (isMotionValue(props[key])) + continue; + if (shouldForward(key) || forwardMotionProps === true && isValidMotionProp(key) || !isDom && !isValidMotionProp(key) || // If trying to use native HTML drag events, forward drag listeners + props["draggable"] && key.startsWith("onDrag")) { + filteredProps[key] = props[key]; + } + } + return filteredProps; +} +const MotionContext = /* @__PURE__ */ reactExports.createContext({}); +function getCurrentTreeVariants(props, context) { + if (isControllingVariants(props)) { + const { initial, animate } = props; + return { + initial: initial === false || isVariantLabel(initial) ? initial : void 0, + animate: isVariantLabel(animate) ? animate : void 0 + }; + } + return props.inherit !== false ? context : {}; +} +function useCreateMotionContext(props) { + const { initial, animate } = getCurrentTreeVariants(props, reactExports.useContext(MotionContext)); + return reactExports.useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); +} +function variantLabelsAsDependency(prop) { + return Array.isArray(prop) ? prop.join(" ") : prop; +} +const createHtmlRenderState = () => ({ + style: {}, + transform: {}, + transformOrigin: {}, + vars: {} +}); +function copyRawValuesOnly(target, source, props) { + for (const key in source) { + if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { + target[key] = source[key]; + } + } +} +function useInitialMotionValues({ transformTemplate }, visualState) { + return reactExports.useMemo(() => { + const state = createHtmlRenderState(); + buildHTMLStyles(state, visualState, transformTemplate); + return Object.assign({}, state.vars, state.style); + }, [visualState]); +} +function useStyle(props, visualState) { + const styleProp = props.style || {}; + const style = {}; + copyRawValuesOnly(style, styleProp, props); + Object.assign(style, useInitialMotionValues(props, visualState)); + return style; +} +function useHTMLProps(props, visualState) { + const htmlProps = {}; + const style = useStyle(props, visualState); + if (props.drag && props.dragListener !== false) { + htmlProps.draggable = false; + style.userSelect = style.WebkitUserSelect = style.WebkitTouchCallout = "none"; + style.touchAction = props.drag === true ? "none" : `pan-${props.drag === "x" ? "y" : "x"}`; + } + if (props.tabIndex === void 0 && (props.onTap || props.onTapStart || props.whileTap)) { + htmlProps.tabIndex = 0; + } + htmlProps.style = style; + return htmlProps; +} +const createSvgRenderState = () => ({ + ...createHtmlRenderState(), + attrs: {} +}); +function useSVGProps(props, visualState, _isStatic, Component) { + const visualProps = reactExports.useMemo(() => { + const state = createSvgRenderState(); + buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style); + return { + ...state.attrs, + style: { ...state.style } + }; + }, [visualState]); + if (props.style) { + const rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = { ...rawStyles, ...visualProps.style }; + } + return visualProps; +} +const lowercaseSVGElements = [ + "animate", + "circle", + "defs", + "desc", + "ellipse", + "g", + "image", + "line", + "filter", + "marker", + "mask", + "metadata", + "path", + "pattern", + "polygon", + "polyline", + "rect", + "stop", + "switch", + "symbol", + "svg", + "text", + "tspan", + "use", + "view" +]; +function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-") + ) { + return false; + } else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/u.test(Component) + ) { + return true; + } + return false; +} +function useRender(Component, props, ref, { latestValues }, isStatic, forwardMotionProps = false, isSVG) { + const useVisualProps = isSVG ?? isSVGComponent(Component) ? useSVGProps : useHTMLProps; + const visualProps = useVisualProps(props, latestValues, isStatic, Component); + const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); + const elementProps = Component !== reactExports.Fragment ? { ...filteredProps, ...visualProps, ref } : {}; + const { children } = props; + const renderedChildren = reactExports.useMemo(() => isMotionValue(children) ? children.get() : children, [children]); + return reactExports.createElement(Component, { + ...elementProps, + children: renderedChildren + }); +} +function makeState({ scrapeMotionValuesFromProps: scrapeMotionValuesFromProps2, createRenderState }, props, context, presenceContext) { + const state = { + latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps2), + renderState: createRenderState() + }; + return state; +} +function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { + const values = {}; + const motionValues = scrapeMotionValues(props, {}); + for (const key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + let { initial, animate } = props; + const isControllingVariants$1 = isControllingVariants(props); + const isVariantNode$1 = isVariantNode(props); + if (context && isVariantNode$1 && !isControllingVariants$1 && props.inherit !== false) { + if (initial === void 0) + initial = context.initial; + if (animate === void 0) + animate = context.animate; + } + let isInitialAnimationBlocked = presenceContext ? presenceContext.initial === false : false; + isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false; + const variantToSet = isInitialAnimationBlocked ? animate : initial; + if (variantToSet && typeof variantToSet !== "boolean" && !isAnimationControls(variantToSet)) { + const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; + for (let i = 0; i < list.length; i++) { + const resolved = resolveVariantFromProps(props, list[i]); + if (resolved) { + const { transitionEnd, transition, ...target } = resolved; + for (const key in target) { + let valueTarget = target[key]; + if (Array.isArray(valueTarget)) { + const index = isInitialAnimationBlocked ? valueTarget.length - 1 : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (const key in transitionEnd) { + values[key] = transitionEnd[key]; + } + } + } + } + return values; +} +const makeUseVisualState = (config) => (props, isStatic) => { + const context = reactExports.useContext(MotionContext); + const presenceContext = reactExports.useContext(PresenceContext); + const make = () => makeState(config, props, context, presenceContext); + return isStatic ? make() : useConstant(make); +}; +const useHTMLVisualState = /* @__PURE__ */ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + createRenderState: createHtmlRenderState +}); +const useSVGVisualState = /* @__PURE__ */ makeUseVisualState({ + scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState +}); +const motionComponentSymbol = /* @__PURE__ */ Symbol.for("motionComponentSymbol"); +function useMotionRef(visualState, visualElement, externalRef) { + const externalRefContainer = reactExports.useRef(externalRef); + reactExports.useInsertionEffect(() => { + externalRefContainer.current = externalRef; + }); + const refCleanup = reactExports.useRef(null); + return reactExports.useCallback((instance) => { + if (instance) { + visualState.onMount?.(instance); + } + const ref = externalRefContainer.current; + if (typeof ref === "function") { + if (instance) { + const cleanup = ref(instance); + if (typeof cleanup === "function") { + refCleanup.current = cleanup; + } + } else if (refCleanup.current) { + refCleanup.current(); + refCleanup.current = null; + } else { + ref(instance); + } + } else if (ref) { + ref.current = instance; + } + if (visualElement) { + instance ? visualElement.mount(instance) : visualElement.unmount(); + } + }, [visualElement]); +} +const SwitchLayoutGroupContext = reactExports.createContext({}); +function isRefObject(ref) { + return ref && typeof ref === "object" && Object.prototype.hasOwnProperty.call(ref, "current"); +} +function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor, isSVG) { + const { visualElement: parent } = reactExports.useContext(MotionContext); + const lazyContext = reactExports.useContext(LazyContext); + const presenceContext = reactExports.useContext(PresenceContext); + const motionConfig = reactExports.useContext(MotionConfigContext); + const reducedMotionConfig = motionConfig.reducedMotion; + const skipAnimations = motionConfig.skipAnimations; + const visualElementRef = reactExports.useRef(null); + const hasMountedOnce = reactExports.useRef(false); + createVisualElement = createVisualElement || lazyContext.renderer; + if (!visualElementRef.current && createVisualElement) { + visualElementRef.current = createVisualElement(Component, { + visualState, + parent, + props, + presenceContext, + blockInitialAnimation: presenceContext ? presenceContext.initial === false : false, + reducedMotionConfig, + skipAnimations, + isSVG + }); + if (hasMountedOnce.current && visualElementRef.current) { + visualElementRef.current.manuallyAnimateOnMount = true; + } + } + const visualElement = visualElementRef.current; + const initialLayoutGroupConfig = reactExports.useContext(SwitchLayoutGroupContext); + if (visualElement && !visualElement.projection && ProjectionNodeConstructor && (visualElement.type === "html" || visualElement.type === "svg")) { + createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig); + } + const isMounted = reactExports.useRef(false); + reactExports.useInsertionEffect(() => { + if (visualElement && isMounted.current) { + visualElement.update(props, presenceContext); + } + }); + const optimisedAppearId = props[optimizedAppearDataAttribute]; + const wantsHandoff = reactExports.useRef(Boolean(optimisedAppearId) && typeof window !== "undefined" && !window.MotionHandoffIsComplete?.(optimisedAppearId) && window.MotionHasOptimisedAnimation?.(optimisedAppearId)); + useIsomorphicLayoutEffect(() => { + hasMountedOnce.current = true; + if (!visualElement) + return; + isMounted.current = true; + window.MotionIsMounted = true; + visualElement.updateFeatures(); + visualElement.scheduleRenderMicrotask(); + if (wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + }); + reactExports.useEffect(() => { + if (!visualElement) + return; + if (!wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + if (wantsHandoff.current) { + queueMicrotask(() => { + window.MotionHandoffMarkAsComplete?.(optimisedAppearId); + }); + wantsHandoff.current = false; + } + visualElement.enteringChildren = void 0; + }); + return visualElement; +} +function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) { + const { layoutId, layout: layout2, drag: drag2, dragConstraints, layoutScroll, layoutRoot, layoutAnchor, layoutCrossfade } = props; + visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] ? void 0 : getClosestProjectingNode(visualElement.parent)); + visualElement.projection.setOptions({ + layoutId, + layout: layout2, + alwaysMeasureLayout: Boolean(drag2) || dragConstraints && isRefObject(dragConstraints), + visualElement, + /** + * TODO: Update options in an effect. This could be tricky as it'll be too late + * to update by the time layout animations run. + * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, + * ensuring it gets called if there's no potential layout animations. + * + */ + animationType: typeof layout2 === "string" ? layout2 : "both", + initialPromotionConfig, + crossfade: layoutCrossfade, + layoutScroll, + layoutRoot, + layoutAnchor + }); +} +function getClosestProjectingNode(visualElement) { + if (!visualElement) + return void 0; + return visualElement.options.allowProjection !== false ? visualElement.projection : getClosestProjectingNode(visualElement.parent); +} +function createMotionComponent(Component, { forwardMotionProps = false, type } = {}, preloadedFeatures, createVisualElement) { + preloadedFeatures && loadFeatures(preloadedFeatures); + const isSVG = type ? type === "svg" : isSVGComponent(Component); + const useVisualState = isSVG ? useSVGVisualState : useHTMLVisualState; + function MotionDOMComponent(props, externalRef) { + let MeasureLayout2; + const configAndProps = { + ...reactExports.useContext(MotionConfigContext), + ...props, + layoutId: useLayoutId(props) + }; + const { isStatic } = configAndProps; + const context = useCreateMotionContext(props); + const visualState = useVisualState(props, isStatic); + if (!isStatic && typeof window !== "undefined") { + useStrictMode(configAndProps, preloadedFeatures); + const layoutProjection = getProjectionFunctionality(configAndProps); + MeasureLayout2 = layoutProjection.MeasureLayout; + context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode, isSVG); + } + return jsxRuntimeExports.jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout2 && context.visualElement ? jsxRuntimeExports.jsx(MeasureLayout2, { visualElement: context.visualElement, ...configAndProps }) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps, isSVG)] }); + } + MotionDOMComponent.displayName = `motion.${typeof Component === "string" ? Component : `create(${Component.displayName ?? Component.name ?? ""})`}`; + const ForwardRefMotionComponent = reactExports.forwardRef(MotionDOMComponent); + ForwardRefMotionComponent[motionComponentSymbol] = Component; + return ForwardRefMotionComponent; +} +function useLayoutId({ layoutId }) { + const layoutGroupId = reactExports.useContext(LayoutGroupContext).id; + return layoutGroupId && layoutId !== void 0 ? layoutGroupId + "-" + layoutId : layoutId; +} +function useStrictMode(configAndProps, preloadedFeatures) { + const isStrict = reactExports.useContext(LazyContext).strict; + if (process.env.NODE_ENV !== "production" && preloadedFeatures && isStrict) { + const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."; + configAndProps.ignoreStrict ? warning(false, strictMessage, "lazy-strict-mode") : invariant(false, strictMessage, "lazy-strict-mode"); + } +} +function getProjectionFunctionality(props) { + const featureDefinitions2 = getInitializedFeatureDefinitions(); + const { drag: drag2, layout: layout2 } = featureDefinitions2; + if (!drag2 && !layout2) + return {}; + const combined = { ...drag2, ...layout2 }; + return { + MeasureLayout: drag2?.isEnabled(props) || layout2?.isEnabled(props) ? combined.MeasureLayout : void 0, + ProjectionNode: combined.ProjectionNode + }; +} +function createMotionProxy(preloadedFeatures, createVisualElement) { + if (typeof Proxy === "undefined") { + return createMotionComponent; + } + const componentCache = /* @__PURE__ */ new Map(); + const factory = (Component, options) => { + return createMotionComponent(Component, options, preloadedFeatures, createVisualElement); + }; + const deprecatedFactoryFunction = (Component, options) => { + if (process.env.NODE_ENV !== "production") { + warnOnce(false, "motion() is deprecated. Use motion.create() instead."); + } + return factory(Component, options); + }; + return new Proxy(deprecatedFactoryFunction, { + /** + * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. + * The prop name is passed through as `key` and we can use that to generate a `motion` + * DOM component with that name. + */ + get: (_target, key) => { + if (key === "create") + return factory; + if (!componentCache.has(key)) { + componentCache.set(key, createMotionComponent(key, void 0, preloadedFeatures, createVisualElement)); + } + return componentCache.get(key); + } + }); +} +const createDomVisualElement = (Component, options) => { + const isSVG = options.isSVG ?? isSVGComponent(Component); + return isSVG ? new SVGVisualElement(options) : new HTMLVisualElement(options, { + allowProjection: Component !== reactExports.Fragment + }); +}; +class AnimationFeature extends Feature { + /** + * We dynamically generate the AnimationState manager as it contains a reference + * to the underlying animation library. We only want to load that if we load this, + * so people can optionally code split it out using the `m` component. + */ + constructor(node) { + super(node); + node.animationState || (node.animationState = createAnimationState(node)); + } + updateAnimationControlsSubscription() { + const { animate } = this.node.getProps(); + if (isAnimationControls(animate)) { + this.unmountControls = animate.subscribe(this.node); + } + } + /** + * Subscribe any provided AnimationControls to the component's VisualElement + */ + mount() { + this.updateAnimationControlsSubscription(); + } + update() { + const { animate } = this.node.getProps(); + const { animate: prevAnimate } = this.node.prevProps || {}; + if (animate !== prevAnimate) { + this.updateAnimationControlsSubscription(); + } + } + unmount() { + this.node.animationState.reset(); + this.unmountControls?.(); + } +} +let id = 0; +class ExitAnimationFeature extends Feature { + constructor() { + super(...arguments); + this.id = id++; + this.isExitComplete = false; + } + update() { + if (!this.node.presenceContext) + return; + const { isPresent, onExitComplete } = this.node.presenceContext; + const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {}; + if (!this.node.animationState || isPresent === prevIsPresent) { + return; + } + if (isPresent && prevIsPresent === false) { + if (this.isExitComplete) { + const { initial, custom } = this.node.getProps(); + if (typeof initial === "string") { + const resolved = resolveVariant(this.node, initial, custom); + if (resolved) { + const { transition, transitionEnd, ...target } = resolved; + for (const key in target) { + this.node.getValue(key)?.jump(target[key]); + } + } + } + this.node.animationState.reset(); + this.node.animationState.animateChanges(); + } else { + this.node.animationState.setActive("exit", false); + } + this.isExitComplete = false; + return; + } + const exitAnimation = this.node.animationState.setActive("exit", !isPresent); + if (onExitComplete && !isPresent) { + exitAnimation.then(() => { + this.isExitComplete = true; + onExitComplete(this.id); + }); + } + } + mount() { + const { register, onExitComplete } = this.node.presenceContext || {}; + if (onExitComplete) { + onExitComplete(this.id); + } + if (register) { + this.unmount = register(this.id); + } + } + unmount() { + } +} +const animations = { + animation: { + Feature: AnimationFeature + }, + exit: { + Feature: ExitAnimationFeature + } +}; +function extractEventInfo(event) { + return { + point: { + x: event.pageX, + y: event.pageY + } + }; +} +const addPointerInfo = (handler) => (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event)); +function addPointerEvent(target, eventName, handler, options) { + return addDomEvent(target, eventName, addPointerInfo(handler), options); +} +const getContextWindow = ({ current }) => { + return current ? current.ownerDocument.defaultView : null; +}; +const distance = (a, b) => Math.abs(a - b); +function distance2D(a, b) { + const xDelta = distance(a.x, b.x); + const yDelta = distance(a.y, b.y); + return Math.sqrt(xDelta ** 2 + yDelta ** 2); +} +const overflowStyles = /* @__PURE__ */ new Set(["auto", "scroll"]); +class PanSession { + constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element } = {}) { + this.startEvent = null; + this.lastMoveEvent = null; + this.lastMoveEventInfo = null; + this.lastRawMoveEventInfo = null; + this.handlers = {}; + this.contextWindow = window; + this.scrollPositions = /* @__PURE__ */ new Map(); + this.removeScrollListeners = null; + this.onElementScroll = (event2) => { + this.handleScroll(event2.target); + }; + this.onWindowScroll = () => { + this.handleScroll(window); + }; + this.updatePoint = () => { + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + if (this.lastRawMoveEventInfo) { + this.lastMoveEventInfo = transformPoint(this.lastRawMoveEventInfo, this.transformPagePoint); + } + const info2 = getPanInfo(this.lastMoveEventInfo, this.history); + const isPanStarted = this.startEvent !== null; + const isDistancePastThreshold = distance2D(info2.offset, { x: 0, y: 0 }) >= this.distanceThreshold; + if (!isPanStarted && !isDistancePastThreshold) + return; + const { point: point2 } = info2; + const { timestamp: timestamp2 } = frameData; + this.history.push({ ...point2, timestamp: timestamp2 }); + const { onStart, onMove } = this.handlers; + if (!isPanStarted) { + onStart && onStart(this.lastMoveEvent, info2); + this.startEvent = this.lastMoveEvent; + } + onMove && onMove(this.lastMoveEvent, info2); + }; + this.handlePointerMove = (event2, info2) => { + this.lastMoveEvent = event2; + this.lastRawMoveEventInfo = info2; + this.lastMoveEventInfo = transformPoint(info2, this.transformPagePoint); + frame.update(this.updatePoint, true); + }; + this.handlePointerUp = (event2, info2) => { + this.end(); + const { onEnd, onSessionEnd, resumeAnimation } = this.handlers; + if (this.dragSnapToOrigin || !this.startEvent) { + resumeAnimation && resumeAnimation(); + } + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const panInfo = getPanInfo(event2.type === "pointercancel" ? this.lastMoveEventInfo : transformPoint(info2, this.transformPagePoint), this.history); + if (this.startEvent && onEnd) { + onEnd(event2, panInfo); + } + onSessionEnd && onSessionEnd(event2, panInfo); + }; + if (!isPrimaryPointer(event)) + return; + this.dragSnapToOrigin = dragSnapToOrigin; + this.handlers = handlers; + this.transformPagePoint = transformPagePoint; + this.distanceThreshold = distanceThreshold; + this.contextWindow = contextWindow || window; + const info = extractEventInfo(event); + const initialInfo = transformPoint(info, this.transformPagePoint); + const { point } = initialInfo; + const { timestamp } = frameData; + this.history = [{ ...point, timestamp }]; + const { onSessionStart } = handlers; + onSessionStart && onSessionStart(event, getPanInfo(initialInfo, this.history)); + this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp)); + if (element) { + this.startScrollTracking(element); + } + } + /** + * Start tracking scroll on ancestors and window. + */ + startScrollTracking(element) { + let current = element.parentElement; + while (current) { + const style = getComputedStyle(current); + if (overflowStyles.has(style.overflowX) || overflowStyles.has(style.overflowY)) { + this.scrollPositions.set(current, { + x: current.scrollLeft, + y: current.scrollTop + }); + } + current = current.parentElement; + } + this.scrollPositions.set(window, { + x: window.scrollX, + y: window.scrollY + }); + window.addEventListener("scroll", this.onElementScroll, { + capture: true + }); + window.addEventListener("scroll", this.onWindowScroll); + this.removeScrollListeners = () => { + window.removeEventListener("scroll", this.onElementScroll, { + capture: true + }); + window.removeEventListener("scroll", this.onWindowScroll); + }; + } + /** + * Handle scroll compensation during drag. + * + * For element scroll: adjusts history origin since pageX/pageY doesn't change. + * For window scroll: adjusts lastMoveEventInfo since pageX/pageY would change. + */ + handleScroll(target) { + const initial = this.scrollPositions.get(target); + if (!initial) + return; + const isWindow = target === window; + const current = isWindow ? { x: window.scrollX, y: window.scrollY } : { + x: target.scrollLeft, + y: target.scrollTop + }; + const delta = { x: current.x - initial.x, y: current.y - initial.y }; + if (delta.x === 0 && delta.y === 0) + return; + if (isWindow) { + if (this.lastMoveEventInfo) { + this.lastMoveEventInfo.point.x += delta.x; + this.lastMoveEventInfo.point.y += delta.y; + } + } else { + if (this.history.length > 0) { + this.history[0].x -= delta.x; + this.history[0].y -= delta.y; + } + } + this.scrollPositions.set(target, current); + frame.update(this.updatePoint, true); + } + updateHandlers(handlers) { + this.handlers = handlers; + } + end() { + this.removeListeners && this.removeListeners(); + this.removeScrollListeners && this.removeScrollListeners(); + this.scrollPositions.clear(); + cancelFrame(this.updatePoint); + } +} +function transformPoint(info, transformPagePoint) { + return transformPagePoint ? { point: transformPagePoint(info.point) } : info; +} +function subtractPoint(a, b) { + return { x: a.x - b.x, y: a.y - b.y }; +} +function getPanInfo({ point }, history) { + return { + point, + delta: subtractPoint(point, lastDevicePoint(history)), + offset: subtractPoint(point, startDevicePoint(history)), + velocity: getVelocity(history, 0.1) + }; +} +function startDevicePoint(history) { + return history[0]; +} +function lastDevicePoint(history) { + return history[history.length - 1]; +} +function getVelocity(history, timeDelta) { + if (history.length < 2) { + return { x: 0, y: 0 }; + } + let i = history.length - 1; + let timestampedPoint = null; + const lastPoint = lastDevicePoint(history); + while (i >= 0) { + timestampedPoint = history[i]; + if (lastPoint.timestamp - timestampedPoint.timestamp > /* @__PURE__ */ secondsToMilliseconds(timeDelta)) { + break; + } + i--; + } + if (!timestampedPoint) { + return { x: 0, y: 0 }; + } + if (timestampedPoint === history[0] && history.length > 2 && lastPoint.timestamp - timestampedPoint.timestamp > /* @__PURE__ */ secondsToMilliseconds(timeDelta) * 2) { + timestampedPoint = history[1]; + } + const time2 = /* @__PURE__ */ millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp); + if (time2 === 0) { + return { x: 0, y: 0 }; + } + const currentVelocity = { + x: (lastPoint.x - timestampedPoint.x) / time2, + y: (lastPoint.y - timestampedPoint.y) / time2 + }; + if (currentVelocity.x === Infinity) { + currentVelocity.x = 0; + } + if (currentVelocity.y === Infinity) { + currentVelocity.y = 0; + } + return currentVelocity; +} +function applyConstraints(point, { min, max }, elastic) { + if (min !== void 0 && point < min) { + point = elastic ? mixNumber$1(min, point, elastic.min) : Math.max(point, min); + } else if (max !== void 0 && point > max) { + point = elastic ? mixNumber$1(max, point, elastic.max) : Math.min(point, max); + } + return point; +} +function calcRelativeAxisConstraints(axis, min, max) { + return { + min: min !== void 0 ? axis.min + min : void 0, + max: max !== void 0 ? axis.max + max - (axis.max - axis.min) : void 0 + }; +} +function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) { + return { + x: calcRelativeAxisConstraints(layoutBox.x, left, right), + y: calcRelativeAxisConstraints(layoutBox.y, top, bottom) + }; +} +function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { + let min = constraintsAxis.min - layoutAxis.min; + let max = constraintsAxis.max - layoutAxis.max; + if (constraintsAxis.max - constraintsAxis.min < layoutAxis.max - layoutAxis.min) { + [min, max] = [max, min]; + } + return { min, max }; +} +function calcViewportConstraints(layoutBox, constraintsBox) { + return { + x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), + y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y) + }; +} +function calcOrigin(source, target) { + let origin = 0.5; + const sourceLength = calcLength(source); + const targetLength = calcLength(target); + if (targetLength > sourceLength) { + origin = /* @__PURE__ */ progress(target.min, target.max - sourceLength, source.min); + } else if (sourceLength > targetLength) { + origin = /* @__PURE__ */ progress(source.min, source.max - targetLength, target.min); + } + return clamp(0, 1, origin); +} +function rebaseAxisConstraints(layout2, constraints) { + const relativeConstraints = {}; + if (constraints.min !== void 0) { + relativeConstraints.min = constraints.min - layout2.min; + } + if (constraints.max !== void 0) { + relativeConstraints.max = constraints.max - layout2.min; + } + return relativeConstraints; +} +const defaultElastic = 0.35; +function resolveDragElastic(dragElastic = defaultElastic) { + if (dragElastic === false) { + dragElastic = 0; + } else if (dragElastic === true) { + dragElastic = defaultElastic; + } + return { + x: resolveAxisElastic(dragElastic, "left", "right"), + y: resolveAxisElastic(dragElastic, "top", "bottom") + }; +} +function resolveAxisElastic(dragElastic, minLabel, maxLabel) { + return { + min: resolvePointElastic(dragElastic, minLabel), + max: resolvePointElastic(dragElastic, maxLabel) + }; +} +function resolvePointElastic(dragElastic, label) { + return typeof dragElastic === "number" ? dragElastic : dragElastic[label] || 0; +} +const elementDragControls = /* @__PURE__ */ new WeakMap(); +class VisualElementDragControls { + constructor(visualElement) { + this.openDragLock = null; + this.isDragging = false; + this.currentDirection = null; + this.originPoint = { x: 0, y: 0 }; + this.constraints = false; + this.hasMutatedConstraints = false; + this.elastic = createBox(); + this.latestPointerEvent = null; + this.latestPanInfo = null; + this.visualElement = visualElement; + } + start(originEvent, { snapToCursor = false, distanceThreshold } = {}) { + const { presenceContext } = this.visualElement; + if (presenceContext && presenceContext.isPresent === false) + return; + const onSessionStart = (event) => { + if (snapToCursor) { + this.snapToCursor(extractEventInfo(event).point); + } + this.stopAnimation(); + }; + const onStart = (event, info) => { + const { drag: drag2, dragPropagation, onDragStart } = this.getProps(); + if (drag2 && !dragPropagation) { + if (this.openDragLock) + this.openDragLock(); + this.openDragLock = setDragLock(drag2); + if (!this.openDragLock) + return; + } + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.isDragging = true; + this.currentDirection = null; + this.resolveConstraints(); + if (this.visualElement.projection) { + this.visualElement.projection.isAnimationBlocked = true; + this.visualElement.projection.target = void 0; + } + eachAxis((axis) => { + let current = this.getAxisMotionValue(axis).get() || 0; + if (percent.test(current)) { + const { projection } = this.visualElement; + if (projection && projection.layout) { + const measuredAxis = projection.layout.layoutBox[axis]; + if (measuredAxis) { + const length = calcLength(measuredAxis); + current = length * (parseFloat(current) / 100); + } + } + } + this.originPoint[axis] = current; + }); + if (onDragStart) { + frame.update(() => onDragStart(event, info), false, true); + } + addValueToWillChange(this.visualElement, "transform"); + const { animationState } = this.visualElement; + animationState && animationState.setActive("whileDrag", true); + }; + const onMove = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag } = this.getProps(); + if (!dragPropagation && !this.openDragLock) + return; + const { offset } = info; + if (dragDirectionLock && this.currentDirection === null) { + this.currentDirection = getCurrentDirection(offset); + if (this.currentDirection !== null) { + onDirectionLock && onDirectionLock(this.currentDirection); + } + return; + } + this.updateAxis("x", info.point, offset); + this.updateAxis("y", info.point, offset); + this.visualElement.render(); + if (onDrag) { + frame.update(() => onDrag(event, info), false, true); + } + }; + const onSessionEnd = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.stop(event, info); + this.latestPointerEvent = null; + this.latestPanInfo = null; + }; + const resumeAnimation = () => { + const { dragSnapToOrigin: snap } = this.getProps(); + if (snap || this.constraints) { + this.startAnimation({ x: 0, y: 0 }); + } + }; + const { dragSnapToOrigin } = this.getProps(); + this.panSession = new PanSession(originEvent, { + onSessionStart, + onStart, + onMove, + onSessionEnd, + resumeAnimation + }, { + transformPagePoint: this.visualElement.getTransformPagePoint(), + dragSnapToOrigin, + distanceThreshold, + contextWindow: getContextWindow(this.visualElement), + element: this.visualElement.current + }); + } + /** + * @internal + */ + stop(event, panInfo) { + const finalEvent = event || this.latestPointerEvent; + const finalPanInfo = panInfo || this.latestPanInfo; + const isDragging2 = this.isDragging; + this.cancel(); + if (!isDragging2 || !finalPanInfo || !finalEvent) + return; + const { velocity } = finalPanInfo; + this.startAnimation(velocity); + const { onDragEnd } = this.getProps(); + if (onDragEnd) { + frame.postRender(() => onDragEnd(finalEvent, finalPanInfo)); + } + } + /** + * @internal + */ + cancel() { + this.isDragging = false; + const { projection, animationState } = this.visualElement; + if (projection) { + projection.isAnimationBlocked = false; + } + this.endPanSession(); + const { dragPropagation } = this.getProps(); + if (!dragPropagation && this.openDragLock) { + this.openDragLock(); + this.openDragLock = null; + } + animationState && animationState.setActive("whileDrag", false); + } + /** + * Clean up the pan session without modifying other drag state. + * This is used during unmount to ensure event listeners are removed + * without affecting projection animations or drag locks. + * @internal + */ + endPanSession() { + this.panSession && this.panSession.end(); + this.panSession = void 0; + } + updateAxis(axis, _point, offset) { + const { drag: drag2 } = this.getProps(); + if (!offset || !shouldDrag(axis, drag2, this.currentDirection)) + return; + const axisValue = this.getAxisMotionValue(axis); + let next = this.originPoint[axis] + offset[axis]; + if (this.constraints && this.constraints[axis]) { + next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); + } + axisValue.set(next); + } + resolveConstraints() { + const { dragConstraints, dragElastic } = this.getProps(); + const layout2 = this.visualElement.projection && !this.visualElement.projection.layout ? this.visualElement.projection.measure(false) : this.visualElement.projection?.layout; + const prevConstraints = this.constraints; + if (dragConstraints && isRefObject(dragConstraints)) { + if (!this.constraints) { + this.constraints = this.resolveRefConstraints(); + } + } else { + if (dragConstraints && layout2) { + this.constraints = calcRelativeConstraints(layout2.layoutBox, dragConstraints); + } else { + this.constraints = false; + } + } + this.elastic = resolveDragElastic(dragElastic); + if (prevConstraints !== this.constraints && !isRefObject(dragConstraints) && layout2 && this.constraints && !this.hasMutatedConstraints) { + eachAxis((axis) => { + if (this.constraints !== false && this.getAxisMotionValue(axis)) { + this.constraints[axis] = rebaseAxisConstraints(layout2.layoutBox[axis], this.constraints[axis]); + } + }); + } + } + resolveRefConstraints() { + const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps(); + if (!constraints || !isRefObject(constraints)) + return false; + const constraintsElement = constraints.current; + invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref"); + const { projection } = this.visualElement; + if (!projection || !projection.layout) + return false; + const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); + let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox); + if (onMeasureDragConstraints) { + const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); + this.hasMutatedConstraints = !!userConstraints; + if (userConstraints) { + measuredConstraints = convertBoundingBoxToBox(userConstraints); + } + } + return measuredConstraints; + } + startAnimation(velocity) { + const { drag: drag2, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd } = this.getProps(); + const constraints = this.constraints || {}; + const momentumAnimations = eachAxis((axis) => { + if (!shouldDrag(axis, drag2, this.currentDirection)) { + return; + } + let transition = constraints && constraints[axis] || {}; + if (dragSnapToOrigin === true || dragSnapToOrigin === axis) + transition = { min: 0, max: 0 }; + const bounceStiffness = dragElastic ? 200 : 1e6; + const bounceDamping = dragElastic ? 40 : 1e7; + const inertia2 = { + type: "inertia", + velocity: dragMomentum ? velocity[axis] : 0, + bounceStiffness, + bounceDamping, + timeConstant: 750, + restDelta: 1, + restSpeed: 10, + ...dragTransition, + ...transition + }; + return this.startAxisValueAnimation(axis, inertia2); + }); + return Promise.all(momentumAnimations).then(onDragTransitionEnd); + } + startAxisValueAnimation(axis, transition) { + const axisValue = this.getAxisMotionValue(axis); + addValueToWillChange(this.visualElement, axis); + return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false)); + } + stopAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).stop()); + } + /** + * Drag works differently depending on which props are provided. + * + * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. + * - Otherwise, we apply the delta to the x/y motion values. + */ + getAxisMotionValue(axis) { + const dragKey = `_drag${axis.toUpperCase()}`; + const props = this.visualElement.getProps(); + const externalMotionValue = props[dragKey]; + return externalMotionValue ? externalMotionValue : this.visualElement.getValue(axis, (props.initial ? props.initial[axis] : void 0) || 0); + } + snapToCursor(point) { + eachAxis((axis) => { + const { drag: drag2 } = this.getProps(); + if (!shouldDrag(axis, drag2, this.currentDirection)) + return; + const { projection } = this.visualElement; + const axisValue = this.getAxisMotionValue(axis); + if (projection && projection.layout) { + const { min, max } = projection.layout.layoutBox[axis]; + const current = axisValue.get() || 0; + axisValue.set(point[axis] - mixNumber$1(min, max, 0.5) + current); + } + }); + } + /** + * When the viewport resizes we want to check if the measured constraints + * have changed and, if so, reposition the element within those new constraints + * relative to where it was before the resize. + */ + scalePositionWithinConstraints() { + if (!this.visualElement.current) + return; + const { drag: drag2, dragConstraints } = this.getProps(); + const { projection } = this.visualElement; + if (!isRefObject(dragConstraints) || !projection || !this.constraints) + return; + this.stopAnimation(); + const boxProgress = { x: 0, y: 0 }; + eachAxis((axis) => { + const axisValue = this.getAxisMotionValue(axis); + if (axisValue && this.constraints !== false) { + const latest = axisValue.get(); + boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]); + } + }); + const { transformTemplate } = this.visualElement.getProps(); + this.visualElement.current.style.transform = transformTemplate ? transformTemplate({}, "") : "none"; + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + this.constraints = false; + this.resolveConstraints(); + eachAxis((axis) => { + if (!shouldDrag(axis, drag2, null)) + return; + const axisValue = this.getAxisMotionValue(axis); + const { min, max } = this.constraints[axis]; + axisValue.set(mixNumber$1(min, max, boxProgress[axis])); + }); + this.visualElement.render(); + } + addListeners() { + if (!this.visualElement.current) + return; + elementDragControls.set(this.visualElement, this); + const element = this.visualElement.current; + const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => { + const { drag: drag2, dragListener = true } = this.getProps(); + const target = event.target; + const isClickingTextInputChild = target !== element && isElementTextInput(target); + if (drag2 && dragListener && !isClickingTextInputChild) { + this.start(event); + } + }); + let stopResizeObservers; + const measureDragConstraints = () => { + const { dragConstraints } = this.getProps(); + if (isRefObject(dragConstraints) && dragConstraints.current) { + this.constraints = this.resolveRefConstraints(); + if (!stopResizeObservers) { + stopResizeObservers = startResizeObservers(element, dragConstraints.current, () => this.scalePositionWithinConstraints()); + } + } + }; + const { projection } = this.visualElement; + const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); + if (projection && !projection.layout) { + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + } + frame.read(measureDragConstraints); + const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints()); + const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => { + if (this.isDragging && hasLayoutChanged) { + eachAxis((axis) => { + const motionValue2 = this.getAxisMotionValue(axis); + if (!motionValue2) + return; + this.originPoint[axis] += delta[axis].translate; + motionValue2.set(motionValue2.get() + delta[axis].translate); + }); + this.visualElement.render(); + } + })); + return () => { + stopResizeListener(); + stopPointerListener(); + stopMeasureLayoutListener(); + stopLayoutUpdateListener && stopLayoutUpdateListener(); + stopResizeObservers && stopResizeObservers(); + }; + } + getProps() { + const props = this.visualElement.getProps(); + const { drag: drag2 = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true } = props; + return { + ...props, + drag: drag2, + dragDirectionLock, + dragPropagation, + dragConstraints, + dragElastic, + dragMomentum + }; + } +} +function skipFirstCall(callback) { + let isFirst = true; + return () => { + if (isFirst) { + isFirst = false; + return; + } + callback(); + }; +} +function startResizeObservers(element, constraintsElement, onResize) { + const stopElement = resize(element, skipFirstCall(onResize)); + const stopContainer = resize(constraintsElement, skipFirstCall(onResize)); + return () => { + stopElement(); + stopContainer(); + }; +} +function shouldDrag(direction, drag2, currentDirection) { + return (drag2 === true || drag2 === direction) && (currentDirection === null || currentDirection === direction); +} +function getCurrentDirection(offset, lockThreshold = 10) { + let direction = null; + if (Math.abs(offset.y) > lockThreshold) { + direction = "y"; + } else if (Math.abs(offset.x) > lockThreshold) { + direction = "x"; + } + return direction; +} +class DragGesture extends Feature { + constructor(node) { + super(node); + this.removeGroupControls = noop; + this.removeListeners = noop; + this.controls = new VisualElementDragControls(node); + } + mount() { + const { dragControls } = this.node.getProps(); + if (dragControls) { + this.removeGroupControls = dragControls.subscribe(this.controls); + } + this.removeListeners = this.controls.addListeners() || noop; + } + update() { + const { dragControls } = this.node.getProps(); + const { dragControls: prevDragControls } = this.node.prevProps || {}; + if (dragControls !== prevDragControls) { + this.removeGroupControls(); + if (dragControls) { + this.removeGroupControls = dragControls.subscribe(this.controls); + } + } + } + unmount() { + this.removeGroupControls(); + this.removeListeners(); + if (!this.controls.isDragging) { + this.controls.endPanSession(); + } + } +} +const asyncHandler = (handler) => (event, info) => { + if (handler) { + frame.update(() => handler(event, info), false, true); + } +}; +class PanGesture extends Feature { + constructor() { + super(...arguments); + this.removePointerDownListener = noop; + } + onPointerDown(pointerDownEvent) { + this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), { + transformPagePoint: this.node.getTransformPagePoint(), + contextWindow: getContextWindow(this.node) + }); + } + createPanHandlers() { + const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps(); + return { + onSessionStart: asyncHandler(onPanSessionStart), + onStart: asyncHandler(onPanStart), + onMove: asyncHandler(onPan), + onEnd: (event, info) => { + delete this.session; + if (onPanEnd) { + frame.postRender(() => onPanEnd(event, info)); + } + } + }; + } + mount() { + this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event)); + } + update() { + this.session && this.session.updateHandlers(this.createPanHandlers()); + } + unmount() { + this.removePointerDownListener(); + this.session && this.session.end(); + } +} +let hasTakenAnySnapshot = false; +class MeasureLayoutWithContext extends reactExports.Component { + /** + * This only mounts projection nodes for components that + * need measuring, we might want to do it for all components + * in order to incorporate transforms + */ + componentDidMount() { + const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props; + const { projection } = visualElement; + if (projection) { + if (layoutGroup.group) + layoutGroup.group.add(projection); + if (switchLayoutGroup && switchLayoutGroup.register && layoutId) { + switchLayoutGroup.register(projection); + } + if (hasTakenAnySnapshot) { + projection.root.didUpdate(); + } + projection.addEventListener("animationComplete", () => { + this.safeToRemove(); + }); + projection.setOptions({ + ...projection.options, + layoutDependency: this.props.layoutDependency, + onExitComplete: () => this.safeToRemove() + }); + } + globalProjectionState.hasEverUpdated = true; + } + getSnapshotBeforeUpdate(prevProps) { + const { layoutDependency, visualElement, drag: drag2, isPresent } = this.props; + const { projection } = visualElement; + if (!projection) + return null; + projection.isPresent = isPresent; + if (prevProps.layoutDependency !== layoutDependency) { + projection.setOptions({ + ...projection.options, + layoutDependency + }); + } + hasTakenAnySnapshot = true; + if (drag2 || prevProps.layoutDependency !== layoutDependency || layoutDependency === void 0 || prevProps.isPresent !== isPresent) { + projection.willUpdate(); + } else { + this.safeToRemove(); + } + if (prevProps.isPresent !== isPresent) { + if (isPresent) { + projection.promote(); + } else if (!projection.relegate()) { + frame.postRender(() => { + const stack = projection.getStack(); + if (!stack || !stack.members.length) { + this.safeToRemove(); + } + }); + } + } + return null; + } + componentDidUpdate() { + const { visualElement, layoutAnchor } = this.props; + const { projection } = visualElement; + if (projection) { + projection.options.layoutAnchor = layoutAnchor; + projection.root.didUpdate(); + microtask.postRender(() => { + if (!projection.currentAnimation && projection.isLead()) { + this.safeToRemove(); + } + }); + } + } + componentWillUnmount() { + const { visualElement, layoutGroup, switchLayoutGroup: promoteContext } = this.props; + const { projection } = visualElement; + hasTakenAnySnapshot = true; + if (projection) { + projection.scheduleCheckAfterUnmount(); + if (layoutGroup && layoutGroup.group) + layoutGroup.group.remove(projection); + if (promoteContext && promoteContext.deregister) + promoteContext.deregister(projection); + } + } + safeToRemove() { + const { safeToRemove } = this.props; + safeToRemove && safeToRemove(); + } + render() { + return null; + } +} +function MeasureLayout(props) { + const [isPresent, safeToRemove] = usePresence(); + const layoutGroup = reactExports.useContext(LayoutGroupContext); + return jsxRuntimeExports.jsx(MeasureLayoutWithContext, { ...props, layoutGroup, switchLayoutGroup: reactExports.useContext(SwitchLayoutGroupContext), isPresent, safeToRemove }); +} +const drag = { + pan: { + Feature: PanGesture + }, + drag: { + Feature: DragGesture, + ProjectionNode: HTMLProjectionNode, + MeasureLayout + } +}; +function handleHoverEvent(node, event, lifecycle) { + const { props } = node; + if (node.animationState && props.whileHover) { + node.animationState.setActive("whileHover", lifecycle === "Start"); + } + const eventName = "onHover" + lifecycle; + const callback = props[eventName]; + if (callback) { + frame.postRender(() => callback(event, extractEventInfo(event))); + } +} +class HoverGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = hover(current, (_element, startEvent) => { + handleHoverEvent(this.node, startEvent, "Start"); + return (endEvent) => handleHoverEvent(this.node, endEvent, "End"); + }); + } + unmount() { + } +} +class FocusGesture extends Feature { + constructor() { + super(...arguments); + this.isActive = false; + } + onFocus() { + let isFocusVisible = false; + try { + isFocusVisible = this.node.current.matches(":focus-visible"); + } catch (e) { + isFocusVisible = true; + } + if (!isFocusVisible || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", true); + this.isActive = true; + } + onBlur() { + if (!this.isActive || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", false); + this.isActive = false; + } + mount() { + this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur())); + } + unmount() { + } +} +function handlePressEvent(node, event, lifecycle) { + const { props } = node; + if (node.current instanceof HTMLButtonElement && node.current.disabled) { + return; + } + if (node.animationState && props.whileTap) { + node.animationState.setActive("whileTap", lifecycle === "Start"); + } + const eventName = "onTap" + (lifecycle === "End" ? "" : lifecycle); + const callback = props[eventName]; + if (callback) { + frame.postRender(() => callback(event, extractEventInfo(event))); + } +} +class PressGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + const { globalTapTarget, propagate } = this.node.props; + this.unmount = press(current, (_element, startEvent) => { + handlePressEvent(this.node, startEvent, "Start"); + return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel"); + }, { + useGlobalTarget: globalTapTarget, + stopPropagation: propagate?.tap === false + }); + } + unmount() { + } +} +const observerCallbacks = /* @__PURE__ */ new WeakMap(); +const observers = /* @__PURE__ */ new WeakMap(); +const fireObserverCallback = (entry) => { + const callback = observerCallbacks.get(entry.target); + callback && callback(entry); +}; +const fireAllObserverCallbacks = (entries) => { + entries.forEach(fireObserverCallback); +}; +function initIntersectionObserver({ root, ...options }) { + const lookupRoot = root || document; + if (!observers.has(lookupRoot)) { + observers.set(lookupRoot, {}); + } + const rootObservers = observers.get(lookupRoot); + const key = JSON.stringify(options); + if (!rootObservers[key]) { + rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options }); + } + return rootObservers[key]; +} +function observeIntersection(element, options, callback) { + const rootInteresectionObserver = initIntersectionObserver(options); + observerCallbacks.set(element, callback); + rootInteresectionObserver.observe(element); + return () => { + observerCallbacks.delete(element); + rootInteresectionObserver.unobserve(element); + }; +} +const thresholdNames = { + some: 0, + all: 1 +}; +class InViewFeature extends Feature { + constructor() { + super(...arguments); + this.hasEnteredView = false; + this.isInView = false; + } + startObserver() { + this.stopObserver?.(); + const { viewport = {} } = this.node.getProps(); + const { root, margin: rootMargin, amount = "some", once } = viewport; + const options = { + root: root ? root.current : void 0, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholdNames[amount] + }; + const onIntersectionUpdate = (entry) => { + const { isIntersecting } = entry; + if (this.isInView === isIntersecting) + return; + this.isInView = isIntersecting; + if (once && !isIntersecting && this.hasEnteredView) { + return; + } else if (isIntersecting) { + this.hasEnteredView = true; + } + if (this.node.animationState) { + this.node.animationState.setActive("whileInView", isIntersecting); + } + const { onViewportEnter, onViewportLeave } = this.node.getProps(); + const callback = isIntersecting ? onViewportEnter : onViewportLeave; + callback && callback(entry); + }; + this.stopObserver = observeIntersection(this.node.current, options, onIntersectionUpdate); + } + mount() { + this.startObserver(); + } + update() { + if (typeof IntersectionObserver === "undefined") + return; + const { props, prevProps } = this.node; + const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps)); + if (hasOptionsChanged) { + this.startObserver(); + } + } + unmount() { + this.stopObserver?.(); + this.hasEnteredView = false; + this.isInView = false; + } +} +function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) { + return (name) => viewport[name] !== prevViewport[name]; +} +const gestureAnimations = { + inView: { + Feature: InViewFeature + }, + tap: { + Feature: PressGesture + }, + focus: { + Feature: FocusGesture + }, + hover: { + Feature: HoverGesture + } +}; +const layout = { + layout: { + ProjectionNode: HTMLProjectionNode, + MeasureLayout + } +}; +const featureBundle = { + ...animations, + ...gestureAnimations, + ...drag, + ...layout +}; +const motion = /* @__PURE__ */ createMotionProxy(featureBundle, createDomVisualElement); +function useReducedMotion() { + !hasReducedMotionListener.current && initPrefersReducedMotion(); + const [shouldReduceMotion] = reactExports.useState(prefersReducedMotion.current); + if (process.env.NODE_ENV !== "production") { + warnOnce(shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + return shouldReduceMotion; +} +export { + AnimatePresence as A, + motion as m, + useReducedMotion as u +}; diff --git a/bootstrap/ssr/assets/vendor-realtime-cgmg5qQY.js b/bootstrap/ssr/assets/vendor-realtime-cgmg5qQY.js new file mode 100644 index 00000000..015a0ffe --- /dev/null +++ b/bootstrap/ssr/assets/vendor-realtime-cgmg5qQY.js @@ -0,0 +1,9704 @@ +import require$$0 from "util"; +import stream from "stream"; +import require$$4 from "https"; +import require$$5 from "url"; +import require$$6 from "fs"; +import require$$1 from "crypto"; +import require$$4$2 from "assert"; +import require$$1$1 from "buffer"; +import require$$2 from "child_process"; +import require$$4$1 from "events"; +import require$$8 from "net"; +import require$$10 from "tls"; +import { c as commonjsGlobal, g as getDefaultExportFromCjs } from "./vendor-tiptap-DSw66HfW.js"; +import require$$3 from "http"; +class u { + constructor() { + this.notificationCreatedEvent = ".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"; + } + /** + * Listen for a whisper event on the channel instance. + */ + listenForWhisper(e, t) { + return this.listen(".client-" + e, t); + } + /** + * Listen for an event on the channel instance. + */ + notification(e) { + return this.listen(this.notificationCreatedEvent, e); + } + /** + * Stop listening for notification events on the channel instance. + */ + stopListeningForNotification(e) { + return this.stopListening(this.notificationCreatedEvent, e); + } + /** + * Stop listening for a whisper event on the channel instance. + */ + stopListeningForWhisper(e, t) { + return this.stopListening(".client-" + e, t); + } +} +class d { + /** + * Create a new class instance. + */ + constructor(e) { + this.namespace = e; + } + /** + * Format the given event name. + */ + format(e) { + return [".", "\\"].includes(e.charAt(0)) ? e.substring(1) : (this.namespace && (e = this.namespace + "." + e), e.replace(/\./g, "\\")); + } + /** + * Set the event namespace. + */ + setNamespace(e) { + this.namespace = e; + } +} +function g(s) { + try { + return Reflect.construct(String, [], s), true; + } catch { + return false; + } +} +class l extends u { + /** + * Create a new class instance. + */ + constructor(e, t, n) { + super(), this.name = t, this.pusher = e, this.options = n, this.eventFormatter = new d(this.options.namespace), this.subscribe(); + } + /** + * Subscribe to a Pusher channel. + */ + subscribe() { + this.subscription = this.pusher.subscribe(this.name); + } + /** + * Unsubscribe from a Pusher channel. + */ + unsubscribe() { + this.pusher.unsubscribe(this.name); + } + /** + * Listen for an event on the channel instance. + */ + listen(e, t) { + return this.on(this.eventFormatter.format(e), t), this; + } + /** + * Listen for all events on the channel instance. + */ + listenToAll(e) { + return this.subscription.bind_global((t, n) => { + if (t.startsWith("pusher:")) + return; + let i = String(this.options.namespace ?? "").replace( + /\./g, + "\\" + ), a = t.startsWith(i) ? t.substring(i.length + 1) : "." + t; + e(a, n); + }), this; + } + /** + * Stop listening for an event on the channel instance. + */ + stopListening(e, t) { + return t ? this.subscription.unbind( + this.eventFormatter.format(e), + t + ) : this.subscription.unbind(this.eventFormatter.format(e)), this; + } + /** + * Stop listening for all events on the channel instance. + */ + stopListeningToAll(e) { + return e ? this.subscription.unbind_global(e) : this.subscription.unbind_global(), this; + } + /** + * Register a callback to be called anytime a subscription succeeds. + */ + subscribed(e) { + return this.on("pusher:subscription_succeeded", () => { + e(); + }), this; + } + /** + * Register a callback to be called anytime a subscription error occurs. + */ + error(e) { + return this.on("pusher:subscription_error", (t) => { + e(t); + }), this; + } + /** + * Bind a channel to an event. + */ + on(e, t) { + return this.subscription.bind(e, t), this; + } +} +class f extends l { + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this.pusher.channels.channels[this.name].trigger( + `client-${e}`, + t + ), this; + } +} +class w extends l { + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this.pusher.channels.channels[this.name].trigger( + `client-${e}`, + t + ), this; + } +} +class _ extends f { + /** + * Register a callback to be called anytime the member list changes. + */ + here(e) { + return this.on("pusher:subscription_succeeded", (t) => { + e(Object.keys(t.members).map((n) => t.members[n])); + }), this; + } + /** + * Listen for someone joining the channel. + */ + joining(e) { + return this.on("pusher:member_added", (t) => { + e(t.info); + }), this; + } + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this.pusher.channels.channels[this.name].trigger( + `client-${e}`, + t + ), this; + } + /** + * Listen for someone leaving the channel. + */ + leaving(e) { + return this.on("pusher:member_removed", (t) => { + e(t.info); + }), this; + } +} +class b extends u { + /** + * Create a new class instance. + */ + constructor(e, t, n) { + super(), this.events = {}, this.listeners = {}, this.name = t, this.socket = e, this.options = n, this.eventFormatter = new d(this.options.namespace), this.subscribe(); + } + /** + * Subscribe to a Socket.io channel. + */ + subscribe() { + this.socket.emit("subscribe", { + channel: this.name, + auth: this.options.auth || {} + }); + } + /** + * Unsubscribe from channel and ubind event callbacks. + */ + unsubscribe() { + this.unbind(), this.socket.emit("unsubscribe", { + channel: this.name, + auth: this.options.auth || {} + }); + } + /** + * Listen for an event on the channel instance. + */ + listen(e, t) { + return this.on(this.eventFormatter.format(e), t), this; + } + /** + * Stop listening for an event on the channel instance. + */ + stopListening(e, t) { + return this.unbindEvent(this.eventFormatter.format(e), t), this; + } + /** + * Register a callback to be called anytime a subscription succeeds. + */ + subscribed(e) { + return this.on("connect", (t) => { + e(t); + }), this; + } + /** + * Register a callback to be called anytime an error occurs. + */ + error(e) { + return this; + } + /** + * Bind the channel's socket to an event and store the callback. + */ + on(e, t) { + return this.listeners[e] = this.listeners[e] || [], this.events[e] || (this.events[e] = (n, i) => { + this.name === n && this.listeners[e] && this.listeners[e].forEach((a) => a(i)); + }, this.socket.on(e, this.events[e])), this.listeners[e].push(t), this; + } + /** + * Unbind the channel's socket from all stored event callbacks. + */ + unbind() { + Object.keys(this.events).forEach((e) => { + this.unbindEvent(e); + }); + } + /** + * Unbind the listeners for the given event. + */ + unbindEvent(e, t) { + this.listeners[e] = this.listeners[e] || [], t && (this.listeners[e] = this.listeners[e].filter( + (n) => n !== t + )), (!t || this.listeners[e].length === 0) && (this.events[e] && (this.socket.removeListener(e, this.events[e]), delete this.events[e]), delete this.listeners[e]); + } +} +class v extends b { + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this.socket.emit("client event", { + channel: this.name, + event: `client-${e}`, + data: t + }), this; + } +} +class C extends v { + /** + * Register a callback to be called anytime the member list changes. + */ + here(e) { + return this.on("presence:subscribed", (t) => { + e(t.map((n) => n.user_info)); + }), this; + } + /** + * Listen for someone joining the channel. + */ + joining(e) { + return this.on( + "presence:joining", + (t) => e(t.user_info) + ), this; + } + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this.socket.emit("client event", { + channel: this.name, + event: `client-${e}`, + data: t + }), this; + } + /** + * Listen for someone leaving the channel. + */ + leaving(e) { + return this.on( + "presence:leaving", + (t) => e(t.user_info) + ), this; + } +} +class c extends u { + /** + * Subscribe to a channel. + */ + subscribe() { + } + /** + * Unsubscribe from a channel. + */ + unsubscribe() { + } + /** + * Listen for an event on the channel instance. + */ + listen(e, t) { + return this; + } + /** + * Listen for all events on the channel instance. + */ + listenToAll(e) { + return this; + } + /** + * Stop listening for an event on the channel instance. + */ + stopListening(e, t) { + return this; + } + /** + * Register a callback to be called anytime a subscription succeeds. + */ + subscribed(e) { + return this; + } + /** + * Register a callback to be called anytime an error occurs. + */ + error(e) { + return this; + } + /** + * Bind a channel to an event. + */ + on(e, t) { + return this; + } +} +class k extends c { + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this; + } +} +class y extends c { + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this; + } +} +class m extends k { + /** + * Register a callback to be called anytime the member list changes. + */ + here(e) { + return this; + } + /** + * Listen for someone joining the channel. + */ + joining(e) { + return this; + } + /** + * Send a whisper event to other clients in the channel. + */ + whisper(e, t) { + return this; + } + /** + * Listen for someone leaving the channel. + */ + leaving(e) { + return this; + } +} +const h = class h2 { + /** + * Create a new class instance. + */ + constructor(e) { + this.setOptions(e), this.connect(); + } + /** + * Merge the custom options with the defaults. + */ + setOptions(e) { + this.options = { + ...h2._defaultOptions, + ...e, + broadcaster: e.broadcaster + }; + let t = this.csrfToken(); + t && (this.options.auth.headers["X-CSRF-TOKEN"] = t, this.options.userAuthentication.headers["X-CSRF-TOKEN"] = t), t = this.options.bearerToken, t && (this.options.auth.headers.Authorization = "Bearer " + t, this.options.userAuthentication.headers.Authorization = "Bearer " + t); + } + /** + * Extract the CSRF token from the page. + */ + csrfToken() { + var e, t; + return typeof window < "u" && ((e = window.Laravel) != null && e.csrfToken) ? window.Laravel.csrfToken : this.options.csrfToken ? this.options.csrfToken : typeof document < "u" && typeof document.querySelector == "function" ? ((t = document.querySelector('meta[name="csrf-token"]')) == null ? void 0 : t.getAttribute("content")) ?? null : null; + } +}; +h._defaultOptions = { + auth: { + headers: {} + }, + authEndpoint: "/broadcasting/auth", + userAuthentication: { + endpoint: "/broadcasting/user-auth", + headers: {} + }, + csrfToken: null, + bearerToken: null, + host: null, + key: null, + namespace: "App.Events" +}; +let r = h; +class o extends r { + constructor() { + super(...arguments), this.channels = {}; + } + /** + * Create a fresh Pusher connection. + */ + connect() { + if (typeof this.options.client < "u") + this.pusher = this.options.client; + else if (this.options.Pusher) + this.pusher = new this.options.Pusher( + this.options.key, + this.options + ); + else if (typeof window < "u" && typeof window.Pusher < "u") + this.pusher = new window.Pusher(this.options.key, this.options); + else + throw new Error( + "Pusher client not found. Should be globally available or passed via options.client" + ); + } + /** + * Sign in the user via Pusher user authentication (https://pusher.com/docs/channels/using_channels/user-authentication/). + */ + signin() { + this.pusher.signin(); + } + /** + * Listen for an event on a channel instance. + */ + listen(e, t, n) { + return this.channel(e).listen(t, n); + } + /** + * Get a channel instance by name. + */ + channel(e) { + return this.channels[e] || (this.channels[e] = new l( + this.pusher, + e, + this.options + )), this.channels[e]; + } + /** + * Get a private channel instance by name. + */ + privateChannel(e) { + return this.channels["private-" + e] || (this.channels["private-" + e] = new f( + this.pusher, + "private-" + e, + this.options + )), this.channels["private-" + e]; + } + /** + * Get a private encrypted channel instance by name. + */ + encryptedPrivateChannel(e) { + return this.channels["private-encrypted-" + e] || (this.channels["private-encrypted-" + e] = new w( + this.pusher, + "private-encrypted-" + e, + this.options + )), this.channels["private-encrypted-" + e]; + } + /** + * Get a presence channel instance by name. + */ + presenceChannel(e) { + return this.channels["presence-" + e] || (this.channels["presence-" + e] = new _( + this.pusher, + "presence-" + e, + this.options + )), this.channels["presence-" + e]; + } + /** + * Leave the given channel, as well as its private and presence variants. + */ + leave(e) { + [ + e, + "private-" + e, + "private-encrypted-" + e, + "presence-" + e + ].forEach((n) => { + this.leaveChannel(n); + }); + } + /** + * Leave the given channel. + */ + leaveChannel(e) { + this.channels[e] && (this.channels[e].unsubscribe(), delete this.channels[e]); + } + /** + * Get the socket ID for the connection. + */ + socketId() { + return this.pusher.connection.socket_id; + } + /** + * Get the current connection status. + */ + connectionStatus() { + const e = this.pusher.connection.state; + switch (e) { + case "connected": + case "connecting": + return e; + case "failed": + case "unavailable": + return "failed"; + default: + return "disconnected"; + } + } + /** + * Subscribe to connection status changes. + */ + onConnectionChange(e) { + const t = () => { + e(this.connectionStatus()); + }, n = ["state_change", "connected", "disconnected"]; + return n.forEach((i) => { + this.pusher.connection.bind(i, t); + }), () => { + n.forEach((i) => { + this.pusher.connection.unbind(i, t); + }); + }; + } + /** + * Disconnect Pusher connection. + */ + disconnect() { + this.pusher.disconnect(); + } +} +class S extends r { + constructor() { + super(...arguments), this.channels = {}; + } + /** + * Create a fresh Socket.io connection. + */ + connect() { + let e = this.getSocketIO(); + this.socket = e( + this.options.host ?? void 0, + this.options + ), this.socket.io.on("reconnect", () => { + Object.values(this.channels).forEach((t) => { + t.subscribe(); + }); + }); + } + /** + * Get socket.io module from global scope or options. + */ + getSocketIO() { + if (typeof this.options.client < "u") + return this.options.client; + if (typeof window < "u" && typeof window.io < "u") + return window.io; + throw new Error( + "Socket.io client not found. Should be globally available or passed via options.client" + ); + } + /** + * Listen for an event on a channel instance. + */ + listen(e, t, n) { + return this.channel(e).listen(t, n); + } + /** + * Get a channel instance by name. + */ + channel(e) { + return this.channels[e] || (this.channels[e] = new b( + this.socket, + e, + this.options + )), this.channels[e]; + } + /** + * Get a private channel instance by name. + */ + privateChannel(e) { + return this.channels["private-" + e] || (this.channels["private-" + e] = new v( + this.socket, + "private-" + e, + this.options + )), this.channels["private-" + e]; + } + /** + * Get a presence channel instance by name. + */ + presenceChannel(e) { + return this.channels["presence-" + e] || (this.channels["presence-" + e] = new C( + this.socket, + "presence-" + e, + this.options + )), this.channels["presence-" + e]; + } + /** + * Leave the given channel, as well as its private and presence variants. + */ + leave(e) { + [e, "private-" + e, "presence-" + e].forEach((n) => { + this.leaveChannel(n); + }); + } + /** + * Leave the given channel. + */ + leaveChannel(e) { + this.channels[e] && (this.channels[e].unsubscribe(), delete this.channels[e]); + } + /** + * Get the socket ID for the connection. + */ + socketId() { + return this.socket.id; + } + /** + * Get the current connection status. + */ + connectionStatus() { + return this.socket.connected ? "connected" : this.socket.io._reconnecting ? "reconnecting" : this.socket.id !== void 0 ? "disconnected" : "connecting"; + } + /** + * Subscribe to connection status changes. + */ + onConnectionChange(e) { + const t = () => { + e(this.connectionStatus()); + }, n = [ + "connect", + "disconnect", + "connect_error", + "reconnect_attempt", + "reconnect", + "reconnect_error", + "reconnect_failed" + ]; + return n.forEach((i) => { + this.socket.on(i, t); + }), () => { + n.forEach((i) => { + this.socket.off(i, t); + }); + }; + } + /** + * Disconnect Socketio connection. + */ + disconnect() { + this.socket.disconnect(); + } +} +class p extends r { + constructor() { + super(...arguments), this.channels = {}; + } + /** + * Create a fresh connection. + */ + connect() { + } + /** + * Listen for an event on a channel instance. + */ + listen(e, t, n) { + return new c(); + } + /** + * Get a channel instance by name. + */ + channel(e) { + return new c(); + } + /** + * Get a private channel instance by name. + */ + privateChannel(e) { + return new k(); + } + /** + * Get a private encrypted channel instance by name. + */ + encryptedPrivateChannel(e) { + return new y(); + } + /** + * Get a presence channel instance by name. + */ + presenceChannel(e) { + return new m(); + } + /** + * Leave the given channel, as well as its private and presence variants. + */ + leave(e) { + } + /** + * Leave the given channel. + */ + leaveChannel(e) { + } + /** + * Get the socket ID for the connection. + */ + socketId() { + return "fake-socket-id"; + } + /** + * Get the current connection status. + */ + connectionStatus() { + return "connected"; + } + /** + * Subscribe to connection status changes. + */ + onConnectionChange(e) { + return () => { + }; + } + /** + * Disconnect the connection. + */ + disconnect() { + } +} +class E { + /** + * Create a new class instance. + */ + constructor(e) { + this.options = e, this.connect(), this.options.withoutInterceptors || this.registerInterceptors(); + } + /** + * Get a channel instance by name. + */ + channel(e) { + return this.connector.channel(e); + } + /** + * Create a new connection. + */ + connect() { + if (this.options.broadcaster === "reverb") + this.connector = new o({ + ...this.options, + cluster: "" + }); + else if (this.options.broadcaster === "pusher") + this.connector = new o(this.options); + else if (this.options.broadcaster === "ably") + this.connector = new o({ + ...this.options, + cluster: "", + broadcaster: "pusher" + }); + else if (this.options.broadcaster === "socket.io") + this.connector = new S(this.options); + else if (this.options.broadcaster === "null") + this.connector = new p(this.options); + else if (typeof this.options.broadcaster == "function" && g(this.options.broadcaster)) + this.connector = new this.options.broadcaster(this.options); + else + throw new Error( + `Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.` + ); + } + /** + * Disconnect from the Echo server. + */ + disconnect() { + this.connector.disconnect(); + } + /** + * Get a presence channel instance by name. + */ + join(e) { + return this.connector.presenceChannel(e); + } + /** + * Leave the given channel, as well as its private and presence variants. + */ + leave(e) { + this.connector.leave(e); + } + /** + * Leave the given channel. + */ + leaveChannel(e) { + this.connector.leaveChannel(e); + } + /** + * Leave all channels. + */ + leaveAllChannels() { + for (const e in this.connector.channels) + this.leaveChannel(e); + } + /** + * Listen for an event on a channel instance. + */ + listen(e, t, n) { + return this.connector.listen(e, t, n); + } + /** + * Get a private channel instance by name. + */ + private(e) { + return this.connector.privateChannel(e); + } + /** + * Get a private encrypted channel instance by name. + */ + encryptedPrivate(e) { + if (this.connectorSupportsEncryptedPrivateChannels(this.connector)) + return this.connector.encryptedPrivateChannel(e); + throw new Error( + `Broadcaster ${typeof this.options.broadcaster} ${String( + this.options.broadcaster + )} does not support encrypted private channels.` + ); + } + connectorSupportsEncryptedPrivateChannels(e) { + return e instanceof o || e instanceof p; + } + /** + * Get the Socket ID for the connection. + */ + socketId() { + return this.connector.socketId(); + } + /** + * Get the current connection status. + */ + connectionStatus() { + return this.connector.connectionStatus(); + } + /** + * Register 3rd party request interceptors. These are used to automatically + * send a connections socket id to a Laravel app with a X-Socket-Id header. + */ + registerInterceptors() { + typeof Vue < "u" && (Vue != null && Vue.http) && this.registerVueRequestInterceptor(), typeof axios == "function" && this.registerAxiosRequestInterceptor(), typeof jQuery == "function" && this.registerjQueryAjaxSetup(), typeof Turbo == "object" && this.registerTurboRequestInterceptor(); + } + /** + * Register a Vue HTTP interceptor to add the X-Socket-ID header. + */ + registerVueRequestInterceptor() { + Vue.http.interceptors.push( + (e, t) => { + this.socketId() && e.headers.set("X-Socket-ID", this.socketId()), t(); + } + ); + } + /** + * Register an Axios HTTP interceptor to add the X-Socket-ID header. + */ + registerAxiosRequestInterceptor() { + axios.interceptors.request.use( + (e) => (this.socketId() && (e.headers["X-Socket-Id"] = this.socketId()), e) + ); + } + /** + * Register jQuery AjaxPrefilter to add the X-Socket-ID header. + */ + registerjQueryAjaxSetup() { + typeof jQuery.ajax < "u" && jQuery.ajaxPrefilter( + (e, t, n) => { + this.socketId() && n.setRequestHeader("X-Socket-Id", this.socketId()); + } + ); + } + /** + * Register the Turbo Request interceptor to add the X-Socket-ID header. + */ + registerTurboRequestInterceptor() { + document.addEventListener( + "turbo:before-fetch-request", + (e) => { + e.detail.fetchOptions.headers["X-Socket-Id"] = this.socketId(); + } + ); + } +} +var pusher = { exports: {} }; +var hasRequiredPusher; +function requirePusher() { + if (hasRequiredPusher) return pusher.exports; + hasRequiredPusher = 1; + (function(module) { + (() => { + var __webpack_modules__ = { + /***/ + 594(__unused_webpack_module, exports$1) { + var __extends = this && this.__extends || /* @__PURE__ */ (function() { + var extendStatics = function(d2, b2) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) { + d3.__proto__ = b3; + } || function(d3, b3) { + for (var p2 in b3) if (b3.hasOwnProperty(p2)) d3[p2] = b3[p2]; + }; + return extendStatics(d2, b2); + }; + return function(d2, b2) { + extendStatics(d2, b2); + function __() { + this.constructor = d2; + } + d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __()); + }; + })(); + Object.defineProperty(exports$1, "__esModule", { value: true }); + var INVALID_BYTE = 256; + var Coder = ( + /** @class */ + (function() { + function Coder2(_paddingCharacter) { + if (_paddingCharacter === void 0) { + _paddingCharacter = "="; + } + this._paddingCharacter = _paddingCharacter; + } + Coder2.prototype.encodedLength = function(length) { + if (!this._paddingCharacter) { + return (length * 8 + 5) / 6 | 0; + } + return (length + 2) / 3 * 4 | 0; + }; + Coder2.prototype.encode = function(data) { + var out = ""; + var i = 0; + for (; i < data.length - 2; i += 3) { + var c2 = data[i] << 16 | data[i + 1] << 8 | data[i + 2]; + out += this._encodeByte(c2 >>> 3 * 6 & 63); + out += this._encodeByte(c2 >>> 2 * 6 & 63); + out += this._encodeByte(c2 >>> 1 * 6 & 63); + out += this._encodeByte(c2 >>> 0 * 6 & 63); + } + var left = data.length - i; + if (left > 0) { + var c2 = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0); + out += this._encodeByte(c2 >>> 3 * 6 & 63); + out += this._encodeByte(c2 >>> 2 * 6 & 63); + if (left === 2) { + out += this._encodeByte(c2 >>> 1 * 6 & 63); + } else { + out += this._paddingCharacter || ""; + } + out += this._paddingCharacter || ""; + } + return out; + }; + Coder2.prototype.maxDecodedLength = function(length) { + if (!this._paddingCharacter) { + return (length * 6 + 7) / 8 | 0; + } + return length / 4 * 3 | 0; + }; + Coder2.prototype.decodedLength = function(s) { + return this.maxDecodedLength(s.length - this._getPaddingLength(s)); + }; + Coder2.prototype.decode = function(s) { + if (s.length === 0) { + return new Uint8Array(0); + } + var paddingLength = this._getPaddingLength(s); + var length = s.length - paddingLength; + var out = new Uint8Array(this.maxDecodedLength(length)); + var op = 0; + var i = 0; + var haveBad = 0; + var v0 = 0, v1 = 0, v2 = 0, v3 = 0; + for (; i < length - 4; i += 4) { + v0 = this._decodeChar(s.charCodeAt(i + 0)); + v1 = this._decodeChar(s.charCodeAt(i + 1)); + v2 = this._decodeChar(s.charCodeAt(i + 2)); + v3 = this._decodeChar(s.charCodeAt(i + 3)); + out[op++] = v0 << 2 | v1 >>> 4; + out[op++] = v1 << 4 | v2 >>> 2; + out[op++] = v2 << 6 | v3; + haveBad |= v0 & INVALID_BYTE; + haveBad |= v1 & INVALID_BYTE; + haveBad |= v2 & INVALID_BYTE; + haveBad |= v3 & INVALID_BYTE; + } + if (i < length - 1) { + v0 = this._decodeChar(s.charCodeAt(i)); + v1 = this._decodeChar(s.charCodeAt(i + 1)); + out[op++] = v0 << 2 | v1 >>> 4; + haveBad |= v0 & INVALID_BYTE; + haveBad |= v1 & INVALID_BYTE; + } + if (i < length - 2) { + v2 = this._decodeChar(s.charCodeAt(i + 2)); + out[op++] = v1 << 4 | v2 >>> 2; + haveBad |= v2 & INVALID_BYTE; + } + if (i < length - 3) { + v3 = this._decodeChar(s.charCodeAt(i + 3)); + out[op++] = v2 << 6 | v3; + haveBad |= v3 & INVALID_BYTE; + } + if (haveBad !== 0) { + throw new Error("Base64Coder: incorrect characters for decoding"); + } + return out; + }; + Coder2.prototype._encodeByte = function(b2) { + var result = b2; + result += 65; + result += 25 - b2 >>> 8 & 0 - 65 - 26 + 97; + result += 51 - b2 >>> 8 & 26 - 97 - 52 + 48; + result += 61 - b2 >>> 8 & 52 - 48 - 62 + 43; + result += 62 - b2 >>> 8 & 62 - 43 - 63 + 47; + return String.fromCharCode(result); + }; + Coder2.prototype._decodeChar = function(c2) { + var result = INVALID_BYTE; + result += (42 - c2 & c2 - 44) >>> 8 & -INVALID_BYTE + c2 - 43 + 62; + result += (46 - c2 & c2 - 48) >>> 8 & -INVALID_BYTE + c2 - 47 + 63; + result += (47 - c2 & c2 - 58) >>> 8 & -INVALID_BYTE + c2 - 48 + 52; + result += (64 - c2 & c2 - 91) >>> 8 & -INVALID_BYTE + c2 - 65 + 0; + result += (96 - c2 & c2 - 123) >>> 8 & -INVALID_BYTE + c2 - 97 + 26; + return result; + }; + Coder2.prototype._getPaddingLength = function(s) { + var paddingLength = 0; + if (this._paddingCharacter) { + for (var i = s.length - 1; i >= 0; i--) { + if (s[i] !== this._paddingCharacter) { + break; + } + paddingLength++; + } + if (s.length < 4 || paddingLength > 2) { + throw new Error("Base64Coder: incorrect padding"); + } + } + return paddingLength; + }; + return Coder2; + })() + ); + exports$1.Coder = Coder; + var stdCoder = new Coder(); + function encode(data) { + return stdCoder.encode(data); + } + exports$1.encode = encode; + function decode(s) { + return stdCoder.decode(s); + } + exports$1.decode = decode; + var URLSafeCoder = ( + /** @class */ + (function(_super) { + __extends(URLSafeCoder2, _super); + function URLSafeCoder2() { + return _super !== null && _super.apply(this, arguments) || this; + } + URLSafeCoder2.prototype._encodeByte = function(b2) { + var result = b2; + result += 65; + result += 25 - b2 >>> 8 & 0 - 65 - 26 + 97; + result += 51 - b2 >>> 8 & 26 - 97 - 52 + 48; + result += 61 - b2 >>> 8 & 52 - 48 - 62 + 45; + result += 62 - b2 >>> 8 & 62 - 45 - 63 + 95; + return String.fromCharCode(result); + }; + URLSafeCoder2.prototype._decodeChar = function(c2) { + var result = INVALID_BYTE; + result += (44 - c2 & c2 - 46) >>> 8 & -INVALID_BYTE + c2 - 45 + 62; + result += (94 - c2 & c2 - 96) >>> 8 & -INVALID_BYTE + c2 - 95 + 63; + result += (47 - c2 & c2 - 58) >>> 8 & -INVALID_BYTE + c2 - 48 + 52; + result += (64 - c2 & c2 - 91) >>> 8 & -INVALID_BYTE + c2 - 65 + 0; + result += (96 - c2 & c2 - 123) >>> 8 & -INVALID_BYTE + c2 - 97 + 26; + return result; + }; + return URLSafeCoder2; + })(Coder) + ); + exports$1.URLSafeCoder = URLSafeCoder; + var urlSafeCoder = new URLSafeCoder(); + function encodeURLSafe(data) { + return urlSafeCoder.encode(data); + } + exports$1.encodeURLSafe = encodeURLSafe; + function decodeURLSafe(s) { + return urlSafeCoder.decode(s); + } + exports$1.decodeURLSafe = decodeURLSafe; + exports$1.encodedLength = function(length) { + return stdCoder.encodedLength(length); + }; + exports$1.maxDecodedLength = function(length) { + return stdCoder.maxDecodedLength(length); + }; + exports$1.decodedLength = function(s) { + return stdCoder.decodedLength(s); + }; + }, + /***/ + 978(__unused_webpack_module, exports$1) { + var INVALID_UTF8 = "utf8: invalid source encoding"; + function decode(arr) { + var chars = []; + for (var i = 0; i < arr.length; i++) { + var b2 = arr[i]; + if (b2 & 128) { + var min = void 0; + if (b2 < 224) { + if (i >= arr.length) { + throw new Error(INVALID_UTF8); + } + var n1 = arr[++i]; + if ((n1 & 192) !== 128) { + throw new Error(INVALID_UTF8); + } + b2 = (b2 & 31) << 6 | n1 & 63; + min = 128; + } else if (b2 < 240) { + if (i >= arr.length - 1) { + throw new Error(INVALID_UTF8); + } + var n1 = arr[++i]; + var n2 = arr[++i]; + if ((n1 & 192) !== 128 || (n2 & 192) !== 128) { + throw new Error(INVALID_UTF8); + } + b2 = (b2 & 15) << 12 | (n1 & 63) << 6 | n2 & 63; + min = 2048; + } else if (b2 < 248) { + if (i >= arr.length - 2) { + throw new Error(INVALID_UTF8); + } + var n1 = arr[++i]; + var n2 = arr[++i]; + var n3 = arr[++i]; + if ((n1 & 192) !== 128 || (n2 & 192) !== 128 || (n3 & 192) !== 128) { + throw new Error(INVALID_UTF8); + } + b2 = (b2 & 15) << 18 | (n1 & 63) << 12 | (n2 & 63) << 6 | n3 & 63; + min = 65536; + } else { + throw new Error(INVALID_UTF8); + } + if (b2 < min || b2 >= 55296 && b2 <= 57343) { + throw new Error(INVALID_UTF8); + } + if (b2 >= 65536) { + if (b2 > 1114111) { + throw new Error(INVALID_UTF8); + } + b2 -= 65536; + chars.push(String.fromCharCode(55296 | b2 >> 10)); + b2 = 56320 | b2 & 1023; + } + } + chars.push(String.fromCharCode(b2)); + } + return chars.join(""); + } + exports$1.D4 = decode; + }, + /***/ + 945(module2, __unused_webpack_exports, __webpack_require__2) { + var Stream = __webpack_require__2(203).Stream, util = __webpack_require__2(23), driver = __webpack_require__2(41), Headers = __webpack_require__2(160), API = __webpack_require__2(720), EventTarget = __webpack_require__2(667), Event = __webpack_require__2(859); + var EventSource = function(request, response, options) { + this.writable = true; + options = options || {}; + this._stream = response.socket; + this._ping = options.ping || this.DEFAULT_PING; + this._retry = options.retry || this.DEFAULT_RETRY; + var scheme = driver.isSecureRequest(request) ? "https:" : "http:"; + this.url = scheme + "//" + request.headers.host + request.url; + this.lastEventId = request.headers["last-event-id"] || ""; + this.readyState = API.CONNECTING; + var headers = new Headers(), self2 = this; + if (options.headers) { + for (var key2 in options.headers) headers.set(key2, options.headers[key2]); + } + if (!this._stream || !this._stream.writable) return; + process.nextTick(function() { + self2._open(); + }); + this._stream.setTimeout(0); + this._stream.setNoDelay(true); + var handshake = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache, no-store\r\nConnection: close\r\n" + headers.toString() + "\r\nretry: " + Math.floor(this._retry * 1e3) + "\r\n\r\n"; + this._write(handshake); + this._stream.on("drain", function() { + self2.emit("drain"); + }); + if (this._ping) + this._pingTimer = setInterval(function() { + self2.ping(); + }, this._ping * 1e3); + ["error", "end"].forEach(function(event) { + self2._stream.on(event, function() { + self2.close(); + }); + }); + }; + util.inherits(EventSource, Stream); + EventSource.isEventSource = function(request) { + if (request.method !== "GET") return false; + var accept = (request.headers.accept || "").split(/\s*,\s*/); + return accept.indexOf("text/event-stream") >= 0; + }; + var instance = { + DEFAULT_PING: 10, + DEFAULT_RETRY: 5, + _write: function(chunk) { + if (!this.writable) return false; + try { + return this._stream.write(chunk, "utf8"); + } catch (e) { + return false; + } + }, + _open: function() { + if (this.readyState !== API.CONNECTING) return; + this.readyState = API.OPEN; + var event = new Event("open"); + event.initEvent("open", false, false); + this.dispatchEvent(event); + }, + write: function(message) { + return this.send(message); + }, + end: function(message) { + if (message !== void 0) this.write(message); + this.close(); + }, + send: function(message, options) { + if (this.readyState > API.OPEN) return false; + message = String(message).replace(/(\r\n|\r|\n)/g, "$1data: "); + options = options || {}; + var frame = ""; + if (options.event) frame += "event: " + options.event + "\r\n"; + if (options.id) frame += "id: " + options.id + "\r\n"; + frame += "data: " + message + "\r\n\r\n"; + return this._write(frame); + }, + ping: function() { + return this._write(":\r\n\r\n"); + }, + close: function() { + if (this.readyState > API.OPEN) return false; + this.readyState = API.CLOSED; + this.writable = false; + if (this._pingTimer) clearInterval(this._pingTimer); + if (this._stream) this._stream.end(); + var event = new Event("close"); + event.initEvent("close", false, false); + this.dispatchEvent(event); + return true; + } + }; + for (var method in instance) EventSource.prototype[method] = instance[method]; + for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key]; + module2.exports = EventSource; + }, + /***/ + 555(module2, __unused_webpack_exports, __webpack_require__2) { + var util = __webpack_require__2(23), driver = __webpack_require__2(41), API = __webpack_require__2(720); + var WebSocket = function(request, socket, body, protocols, options) { + options = options || {}; + this._stream = socket; + this._driver = driver.http(request, { maxLength: options.maxLength, protocols }); + var self2 = this; + if (!this._stream || !this._stream.writable) return; + if (!this._stream.readable) return this._stream.end(); + var catchup = function() { + self2._stream.removeListener("data", catchup); + }; + this._stream.on("data", catchup); + API.call(this, options); + process.nextTick(function() { + self2._driver.start(); + self2._driver.io.write(body); + }); + }; + util.inherits(WebSocket, API); + WebSocket.isWebSocket = function(request) { + return driver.isWebSocket(request); + }; + WebSocket.validateOptions = function(options, validKeys) { + driver.validateOptions(options, validKeys); + }; + WebSocket.WebSocket = WebSocket; + WebSocket.Client = __webpack_require__2(333); + WebSocket.EventSource = __webpack_require__2(945); + module2.exports = WebSocket; + }, + /***/ + 720(module2, __unused_webpack_exports, __webpack_require__2) { + var Stream = __webpack_require__2(203).Stream, util = __webpack_require__2(23), driver = __webpack_require__2(41), EventTarget = __webpack_require__2(667), Event = __webpack_require__2(859); + var API = function(options) { + options = options || {}; + driver.validateOptions(options, ["headers", "extensions", "maxLength", "ping", "proxy", "tls", "ca"]); + this.readable = this.writable = true; + var headers = options.headers; + if (headers) { + for (var name in headers) this._driver.setHeader(name, headers[name]); + } + var extensions = options.extensions; + if (extensions) { + [].concat(extensions).forEach(this._driver.addExtension, this._driver); + } + this._ping = options.ping; + this._pingId = 0; + this.readyState = API.CONNECTING; + this.bufferedAmount = 0; + this.protocol = ""; + this.url = this._driver.url; + this.version = this._driver.version; + var self2 = this; + this._driver.on("open", function(e) { + self2._open(); + }); + this._driver.on("message", function(e) { + self2._receiveMessage(e.data); + }); + this._driver.on("close", function(e) { + self2._beginClose(e.reason, e.code); + }); + this._driver.on("error", function(error) { + self2._emitError(error.message); + }); + this.on("error", function() { + }); + this._driver.messages.on("drain", function() { + self2.emit("drain"); + }); + if (this._ping) + this._pingTimer = setInterval(function() { + self2._pingId += 1; + self2.ping(self2._pingId.toString()); + }, this._ping * 1e3); + this._configureStream(); + if (!this._proxy) { + this._stream.pipe(this._driver.io); + this._driver.io.pipe(this._stream); + } + }; + util.inherits(API, Stream); + API.CONNECTING = 0; + API.OPEN = 1; + API.CLOSING = 2; + API.CLOSED = 3; + API.CLOSE_TIMEOUT = 3e4; + var instance = { + write: function(data) { + return this.send(data); + }, + end: function(data) { + if (data !== void 0) this.send(data); + this.close(); + }, + pause: function() { + return this._driver.messages.pause(); + }, + resume: function() { + return this._driver.messages.resume(); + }, + send: function(data) { + if (this.readyState > API.OPEN) return false; + if (!(data instanceof Buffer)) data = String(data); + return this._driver.messages.write(data); + }, + ping: function(message, callback) { + if (this.readyState > API.OPEN) return false; + return this._driver.ping(message, callback); + }, + close: function(code, reason) { + if (code === void 0) code = 1e3; + if (reason === void 0) reason = ""; + if (code !== 1e3 && (code < 3e3 || code > 4999)) + throw new Error("Failed to execute 'close' on WebSocket: The code must be either 1000, or between 3000 and 4999. " + code + " is neither."); + if (this.readyState !== API.CLOSED) this.readyState = API.CLOSING; + var self2 = this; + this._closeTimer = setTimeout(function() { + self2._beginClose("", 1006); + }, API.CLOSE_TIMEOUT); + this._driver.close(reason, code); + }, + _configureStream: function() { + var self2 = this; + this._stream.setTimeout(0); + this._stream.setNoDelay(true); + ["close", "end"].forEach(function(event) { + this._stream.on(event, function() { + self2._finalizeClose(); + }); + }, this); + this._stream.on("error", function(error) { + self2._emitError("Network error: " + self2.url + ": " + error.message); + self2._finalizeClose(); + }); + }, + _open: function() { + if (this.readyState !== API.CONNECTING) return; + this.readyState = API.OPEN; + this.protocol = this._driver.protocol || ""; + var event = new Event("open"); + event.initEvent("open", false, false); + this.dispatchEvent(event); + }, + _receiveMessage: function(data) { + if (this.readyState > API.OPEN) return false; + if (this.readable) this.emit("data", data); + var event = new Event("message", { data }); + event.initEvent("message", false, false); + this.dispatchEvent(event); + }, + _emitError: function(message) { + if (this.readyState >= API.CLOSING) return; + var event = new Event("error", { message }); + event.initEvent("error", false, false); + this.dispatchEvent(event); + }, + _beginClose: function(reason, code) { + if (this.readyState === API.CLOSED) return; + this.readyState = API.CLOSING; + this._closeParams = [reason, code]; + if (this._stream) { + this._stream.destroy(); + if (!this._stream.readable) this._finalizeClose(); + } + }, + _finalizeClose: function() { + if (this.readyState === API.CLOSED) return; + this.readyState = API.CLOSED; + if (this._closeTimer) clearTimeout(this._closeTimer); + if (this._pingTimer) clearInterval(this._pingTimer); + if (this._stream) this._stream.end(); + if (this.readable) this.emit("end"); + this.readable = this.writable = false; + var reason = this._closeParams ? this._closeParams[0] : "", code = this._closeParams ? this._closeParams[1] : 1006; + var event = new Event("close", { code, reason }); + event.initEvent("close", false, false); + this.dispatchEvent(event); + } + }; + for (var method in instance) API.prototype[method] = instance[method]; + for (var key in EventTarget) API.prototype[key] = EventTarget[key]; + module2.exports = API; + }, + /***/ + 859(module2) { + var Event = function(eventType, options) { + this.type = eventType; + for (var key in options) + this[key] = options[key]; + }; + Event.prototype.initEvent = function(eventType, canBubble, cancelable) { + this.type = eventType; + this.bubbles = canBubble; + this.cancelable = cancelable; + }; + Event.prototype.stopPropagation = function() { + }; + Event.prototype.preventDefault = function() { + }; + Event.CAPTURING_PHASE = 1; + Event.AT_TARGET = 2; + Event.BUBBLING_PHASE = 3; + module2.exports = Event; + }, + /***/ + 667(module2, __unused_webpack_exports, __webpack_require__2) { + var Event = __webpack_require__2(859); + var EventTarget = { + onopen: null, + onmessage: null, + onerror: null, + onclose: null, + addEventListener: function(eventType, listener, useCapture) { + this.on(eventType, listener); + }, + removeEventListener: function(eventType, listener, useCapture) { + this.removeListener(eventType, listener); + }, + dispatchEvent: function(event) { + event.target = event.currentTarget = this; + event.eventPhase = Event.AT_TARGET; + if (this["on" + event.type]) + this["on" + event.type](event); + this.emit(event.type, event); + } + }; + module2.exports = EventTarget; + }, + /***/ + 333(module2, __unused_webpack_exports, __webpack_require__2) { + var util = __webpack_require__2(23), net = __webpack_require__2(278), tls = __webpack_require__2(756), url = __webpack_require__2(16), driver = __webpack_require__2(41), API = __webpack_require__2(720); + __webpack_require__2(859); + var DEFAULT_PORTS = { "http:": 80, "https:": 443, "ws:": 80, "wss:": 443 }, SECURE_PROTOCOLS = ["https:", "wss:"]; + var Client = function(_url, protocols, options) { + options = options || {}; + this.url = _url; + this._driver = driver.client(this.url, { maxLength: options.maxLength, protocols }); + ["open", "error"].forEach(function(event) { + this._driver.on(event, function() { + self2.headers = self2._driver.headers; + self2.statusCode = self2._driver.statusCode; + }); + }, this); + var proxy = options.proxy || {}, endpoint = url.parse(proxy.origin || this.url), port = endpoint.port || DEFAULT_PORTS[endpoint.protocol], secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0, onConnect = function() { + self2._onConnect(); + }, netOptions = options.net || {}, originTLS = options.tls || {}, socketTLS = proxy.origin ? proxy.tls || {} : originTLS, self2 = this; + netOptions.host = socketTLS.host = endpoint.hostname; + netOptions.port = socketTLS.port = port; + originTLS.ca = originTLS.ca || options.ca; + socketTLS.servername = socketTLS.servername || endpoint.hostname; + this._stream = secure ? tls.connect(socketTLS, onConnect) : net.connect(netOptions, onConnect); + if (proxy.origin) this._configureProxy(proxy, originTLS); + API.call(this, options); + }; + util.inherits(Client, API); + Client.prototype._onConnect = function() { + var worker = this._proxy || this._driver; + worker.start(); + }; + Client.prototype._configureProxy = function(proxy, originTLS) { + var uri = url.parse(this.url), secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0, self2 = this, name; + this._proxy = this._driver.proxy(proxy.origin); + if (proxy.headers) { + for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]); + } + this._proxy.pipe(this._stream, { end: false }); + this._stream.pipe(this._proxy); + this._proxy.on("connect", function() { + if (secure) { + var options = { socket: self2._stream, servername: uri.hostname }; + for (name in originTLS) options[name] = originTLS[name]; + self2._stream = tls.connect(options); + self2._configureStream(); + } + self2._driver.io.pipe(self2._stream); + self2._stream.pipe(self2._driver.io); + self2._driver.start(); + }); + this._proxy.on("error", function(error) { + self2._driver.emit("error", error); + }); + }; + module2.exports = Client; + }, + /***/ + 895(__unused_webpack_module, exports$1, __webpack_require__2) { + var assert = __webpack_require__2(613); + exports$1.e = HTTPParser; + function HTTPParser(type) { + assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE || type === void 0); + if (type === void 0) ; + else { + this.initialize(type); + } + this.maxHeaderSize = HTTPParser.maxHeaderSize; + } + HTTPParser.prototype.initialize = function(type, async_resource) { + assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE); + this.type = type; + this.state = type + "_LINE"; + this.info = { + headers: [], + upgrade: false + }; + this.trailers = []; + this.line = ""; + this.isChunked = false; + this.connection = ""; + this.headerSize = 0; + this.body_bytes = null; + this.isUserCall = false; + this.hadError = false; + }; + HTTPParser.encoding = "ascii"; + HTTPParser.maxHeaderSize = 80 * 1024; + HTTPParser.REQUEST = "REQUEST"; + HTTPParser.RESPONSE = "RESPONSE"; + var kOnHeaders = HTTPParser.kOnHeaders = 1; + var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2; + var kOnBody = HTTPParser.kOnBody = 3; + var kOnMessageComplete = HTTPParser.kOnMessageComplete = 4; + HTTPParser.prototype[kOnHeaders] = HTTPParser.prototype[kOnHeadersComplete] = HTTPParser.prototype[kOnBody] = HTTPParser.prototype[kOnMessageComplete] = function() { + }; + var compatMode0_12 = true; + Object.defineProperty(HTTPParser, "kOnExecute", { + get: function() { + compatMode0_12 = false; + return 99; + } + }); + var methods = HTTPParser.methods = [ + "DELETE", + "GET", + "HEAD", + "POST", + "PUT", + "CONNECT", + "OPTIONS", + "TRACE", + "COPY", + "LOCK", + "MKCOL", + "MOVE", + "PROPFIND", + "PROPPATCH", + "SEARCH", + "UNLOCK", + "BIND", + "REBIND", + "UNBIND", + "ACL", + "REPORT", + "MKACTIVITY", + "CHECKOUT", + "MERGE", + "M-SEARCH", + "NOTIFY", + "SUBSCRIBE", + "UNSUBSCRIBE", + "PATCH", + "PURGE", + "MKCALENDAR", + "LINK", + "UNLINK", + "SOURCE" + ]; + var method_connect = methods.indexOf("CONNECT"); + HTTPParser.prototype.reinitialize = HTTPParser; + HTTPParser.prototype.close = HTTPParser.prototype.pause = HTTPParser.prototype.resume = HTTPParser.prototype.free = function() { + }; + HTTPParser.prototype._compatMode0_11 = false; + HTTPParser.prototype.getAsyncId = function() { + return 0; + }; + var headerState = { + REQUEST_LINE: true, + RESPONSE_LINE: true, + HEADER: true + }; + HTTPParser.prototype.execute = function(chunk, start, length) { + if (!(this instanceof HTTPParser)) { + throw new TypeError("not a HTTPParser"); + } + start = start || 0; + length = typeof length === "number" ? length : chunk.length; + this.chunk = chunk; + this.offset = start; + var end = this.end = start + length; + try { + while (this.offset < end) { + if (this[this.state]()) { + break; + } + } + } catch (err) { + if (this.isUserCall) { + throw err; + } + this.hadError = true; + return err; + } + this.chunk = null; + length = this.offset - start; + if (headerState[this.state]) { + this.headerSize += length; + if (this.headerSize > (this.maxHeaderSize || HTTPParser.maxHeaderSize)) { + return new Error("max header size exceeded"); + } + } + return length; + }; + var stateFinishAllowed = { + REQUEST_LINE: true, + RESPONSE_LINE: true, + BODY_RAW: true + }; + HTTPParser.prototype.finish = function() { + if (this.hadError) { + return; + } + if (!stateFinishAllowed[this.state]) { + return new Error("invalid state for EOF"); + } + if (this.state === "BODY_RAW") { + this.userCall()(this[kOnMessageComplete]()); + } + }; + HTTPParser.prototype.consume = HTTPParser.prototype.unconsume = HTTPParser.prototype.getCurrentBuffer = function() { + }; + HTTPParser.prototype.userCall = function() { + this.isUserCall = true; + var self2 = this; + return function(ret) { + self2.isUserCall = false; + return ret; + }; + }; + HTTPParser.prototype.nextRequest = function() { + this.userCall()(this[kOnMessageComplete]()); + this.reinitialize(this.type); + }; + HTTPParser.prototype.consumeLine = function() { + var end = this.end, chunk = this.chunk; + for (var i = this.offset; i < end; i++) { + if (chunk[i] === 10) { + var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i); + if (line.charAt(line.length - 1) === "\r") { + line = line.substr(0, line.length - 1); + } + this.line = ""; + this.offset = i + 1; + return line; + } + } + this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end); + this.offset = this.end; + }; + var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/; + var headerContinueExp = /^[ \t]+(.*[^ \t])/; + HTTPParser.prototype.parseHeader = function(line, headers) { + if (line.indexOf("\r") !== -1) { + throw parseErrorCode("HPE_LF_EXPECTED"); + } + var match = headerExp.exec(line); + var k2 = match && match[1]; + if (k2) { + headers.push(k2); + headers.push(match[2]); + } else { + var matchContinue = headerContinueExp.exec(line); + if (matchContinue && headers.length) { + if (headers[headers.length - 1]) { + headers[headers.length - 1] += " "; + } + headers[headers.length - 1] += matchContinue[1]; + } + } + }; + var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/; + HTTPParser.prototype.REQUEST_LINE = function() { + var line = this.consumeLine(); + if (!line) { + return; + } + var match = requestExp.exec(line); + if (match === null) { + throw parseErrorCode("HPE_INVALID_CONSTANT"); + } + this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]); + if (this.info.method === -1) { + throw new Error("invalid request method"); + } + this.info.url = match[2]; + this.info.versionMajor = +match[3]; + this.info.versionMinor = +match[4]; + this.body_bytes = 0; + this.state = "HEADER"; + }; + var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/; + HTTPParser.prototype.RESPONSE_LINE = function() { + var line = this.consumeLine(); + if (!line) { + return; + } + var match = responseExp.exec(line); + if (match === null) { + throw parseErrorCode("HPE_INVALID_CONSTANT"); + } + this.info.versionMajor = +match[1]; + this.info.versionMinor = +match[2]; + var statusCode = this.info.statusCode = +match[3]; + this.info.statusMessage = match[4]; + if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) { + this.body_bytes = 0; + } + this.state = "HEADER"; + }; + HTTPParser.prototype.shouldKeepAlive = function() { + if (this.info.versionMajor > 0 && this.info.versionMinor > 0) { + if (this.connection.indexOf("close") !== -1) { + return false; + } + } else if (this.connection.indexOf("keep-alive") === -1) { + return false; + } + if (this.body_bytes !== null || this.isChunked) { + return true; + } + return false; + }; + HTTPParser.prototype.HEADER = function() { + var line = this.consumeLine(); + if (line === void 0) { + return; + } + var info = this.info; + if (line) { + this.parseHeader(line, info.headers); + } else { + var headers = info.headers; + var hasContentLength = false; + var currentContentLengthValue; + var hasUpgradeHeader = false; + for (var i = 0; i < headers.length; i += 2) { + switch (headers[i].toLowerCase()) { + case "transfer-encoding": + this.isChunked = headers[i + 1].toLowerCase() === "chunked"; + break; + case "content-length": + currentContentLengthValue = +headers[i + 1]; + if (hasContentLength) { + if (currentContentLengthValue !== this.body_bytes) { + throw parseErrorCode("HPE_UNEXPECTED_CONTENT_LENGTH"); + } + } else { + hasContentLength = true; + this.body_bytes = currentContentLengthValue; + } + break; + case "connection": + this.connection += headers[i + 1].toLowerCase(); + break; + case "upgrade": + hasUpgradeHeader = true; + break; + } + } + if (this.isChunked && hasContentLength) { + hasContentLength = false; + this.body_bytes = null; + } + if (hasUpgradeHeader && this.connection.indexOf("upgrade") != -1) { + info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101; + } else { + info.upgrade = info.method === method_connect; + } + if (this.isChunked && info.upgrade) { + this.isChunked = false; + } + info.shouldKeepAlive = this.shouldKeepAlive(); + var skipBody; + if (compatMode0_12) { + skipBody = this.userCall()(this[kOnHeadersComplete](info)); + } else { + skipBody = this.userCall()(this[kOnHeadersComplete]( + info.versionMajor, + info.versionMinor, + info.headers, + info.method, + info.url, + info.statusCode, + info.statusMessage, + info.upgrade, + info.shouldKeepAlive + )); + } + if (skipBody === 2) { + this.nextRequest(); + return true; + } else if (this.isChunked && !skipBody) { + this.state = "BODY_CHUNKHEAD"; + } else if (skipBody || this.body_bytes === 0) { + this.nextRequest(); + return info.upgrade; + } else if (this.body_bytes === null) { + this.state = "BODY_RAW"; + } else { + this.state = "BODY_SIZED"; + } + } + }; + HTTPParser.prototype.BODY_CHUNKHEAD = function() { + var line = this.consumeLine(); + if (line === void 0) { + return; + } + this.body_bytes = parseInt(line, 16); + if (!this.body_bytes) { + this.state = "BODY_CHUNKTRAILERS"; + } else { + this.state = "BODY_CHUNK"; + } + }; + HTTPParser.prototype.BODY_CHUNK = function() { + var length = Math.min(this.end - this.offset, this.body_bytes); + this.userCall()(this[kOnBody](this.chunk, this.offset, length)); + this.offset += length; + this.body_bytes -= length; + if (!this.body_bytes) { + this.state = "BODY_CHUNKEMPTYLINE"; + } + }; + HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function() { + var line = this.consumeLine(); + if (line === void 0) { + return; + } + assert.equal(line, ""); + this.state = "BODY_CHUNKHEAD"; + }; + HTTPParser.prototype.BODY_CHUNKTRAILERS = function() { + var line = this.consumeLine(); + if (line === void 0) { + return; + } + if (line) { + this.parseHeader(line, this.trailers); + } else { + if (this.trailers.length) { + this.userCall()(this[kOnHeaders](this.trailers, "")); + } + this.nextRequest(); + } + }; + HTTPParser.prototype.BODY_RAW = function() { + var length = this.end - this.offset; + this.userCall()(this[kOnBody](this.chunk, this.offset, length)); + this.offset = this.end; + }; + HTTPParser.prototype.BODY_SIZED = function() { + var length = Math.min(this.end - this.offset, this.body_bytes); + this.userCall()(this[kOnBody](this.chunk, this.offset, length)); + this.offset += length; + this.body_bytes -= length; + if (!this.body_bytes) { + this.nextRequest(); + } + }; + ["Headers", "HeadersComplete", "Body", "MessageComplete"].forEach(function(name) { + var k2 = HTTPParser["kOn" + name]; + Object.defineProperty(HTTPParser.prototype, "on" + name, { + get: function() { + return this[k2]; + }, + set: function(to) { + this._compatMode0_11 = true; + method_connect = "CONNECT"; + return this[k2] = to; + } + }); + }); + function parseErrorCode(code) { + var err = new Error("Parse Error"); + err.code = code; + return err; + } + }, + /***/ + 891(module2, exports$1, __webpack_require__2) { + var buffer = __webpack_require__2(181); + var Buffer2 = buffer.Buffer; + function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module2.exports = buffer; + } else { + copyProps(buffer, exports$1); + exports$1.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); + } + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer.SlowBuffer(size); + }; + }, + /***/ + 601(module2, __unused_webpack_exports, __webpack_require__2) { + (function(nacl) { + var gf = function(init) { + var i, r2 = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r2[i] = init[i]; + return r2; + }; + var randombytes = function() { + throw new Error("no PRNG"); + }; + var _0 = new Uint8Array(16); + var _9 = new Uint8Array(32); + _9[0] = 9; + var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]); + function ts64(x, i, h3, l2) { + x[i] = h3 >> 24 & 255; + x[i + 1] = h3 >> 16 & 255; + x[i + 2] = h3 >> 8 & 255; + x[i + 3] = h3 & 255; + x[i + 4] = l2 >> 24 & 255; + x[i + 5] = l2 >> 16 & 255; + x[i + 6] = l2 >> 8 & 255; + x[i + 7] = l2 & 255; + } + function vn(x, xi, y2, yi, n) { + var i, d2 = 0; + for (i = 0; i < n; i++) d2 |= x[xi + i] ^ y2[yi + i]; + return (1 & d2 - 1 >>> 8) - 1; + } + function crypto_verify_16(x, xi, y2, yi) { + return vn(x, xi, y2, yi, 16); + } + function crypto_verify_32(x, xi, y2, yi) { + return vn(x, xi, y2, yi, 32); + } + function core_salsa20(o2, p2, k2, c2) { + var j0 = c2[0] & 255 | (c2[1] & 255) << 8 | (c2[2] & 255) << 16 | (c2[3] & 255) << 24, j1 = k2[0] & 255 | (k2[1] & 255) << 8 | (k2[2] & 255) << 16 | (k2[3] & 255) << 24, j2 = k2[4] & 255 | (k2[5] & 255) << 8 | (k2[6] & 255) << 16 | (k2[7] & 255) << 24, j3 = k2[8] & 255 | (k2[9] & 255) << 8 | (k2[10] & 255) << 16 | (k2[11] & 255) << 24, j4 = k2[12] & 255 | (k2[13] & 255) << 8 | (k2[14] & 255) << 16 | (k2[15] & 255) << 24, j5 = c2[4] & 255 | (c2[5] & 255) << 8 | (c2[6] & 255) << 16 | (c2[7] & 255) << 24, j6 = p2[0] & 255 | (p2[1] & 255) << 8 | (p2[2] & 255) << 16 | (p2[3] & 255) << 24, j7 = p2[4] & 255 | (p2[5] & 255) << 8 | (p2[6] & 255) << 16 | (p2[7] & 255) << 24, j8 = p2[8] & 255 | (p2[9] & 255) << 8 | (p2[10] & 255) << 16 | (p2[11] & 255) << 24, j9 = p2[12] & 255 | (p2[13] & 255) << 8 | (p2[14] & 255) << 16 | (p2[15] & 255) << 24, j10 = c2[8] & 255 | (c2[9] & 255) << 8 | (c2[10] & 255) << 16 | (c2[11] & 255) << 24, j11 = k2[16] & 255 | (k2[17] & 255) << 8 | (k2[18] & 255) << 16 | (k2[19] & 255) << 24, j12 = k2[20] & 255 | (k2[21] & 255) << 8 | (k2[22] & 255) << 16 | (k2[23] & 255) << 24, j13 = k2[24] & 255 | (k2[25] & 255) << 8 | (k2[26] & 255) << 16 | (k2[27] & 255) << 24, j14 = k2[28] & 255 | (k2[29] & 255) << 8 | (k2[30] & 255) << 16 | (k2[31] & 255) << 24, j15 = c2[12] & 255 | (c2[13] & 255) << 8 | (c2[14] & 255) << 16 | (c2[15] & 255) << 24; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u2; + for (var i = 0; i < 20; i += 2) { + u2 = x0 + x12 | 0; + x4 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x4 + x0 | 0; + x8 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x8 + x4 | 0; + x12 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x12 + x8 | 0; + x0 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x5 + x1 | 0; + x9 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x9 + x5 | 0; + x13 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x13 + x9 | 0; + x1 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x1 + x13 | 0; + x5 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x10 + x6 | 0; + x14 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x14 + x10 | 0; + x2 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x2 + x14 | 0; + x6 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x6 + x2 | 0; + x10 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x15 + x11 | 0; + x3 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x3 + x15 | 0; + x7 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x7 + x3 | 0; + x11 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x11 + x7 | 0; + x15 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x0 + x3 | 0; + x1 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x1 + x0 | 0; + x2 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x2 + x1 | 0; + x3 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x3 + x2 | 0; + x0 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x5 + x4 | 0; + x6 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x6 + x5 | 0; + x7 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x7 + x6 | 0; + x4 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x4 + x7 | 0; + x5 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x10 + x9 | 0; + x11 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x11 + x10 | 0; + x8 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x8 + x11 | 0; + x9 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x9 + x8 | 0; + x10 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x15 + x14 | 0; + x12 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x12 + x15 | 0; + x13 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x13 + x12 | 0; + x14 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x14 + x13 | 0; + x15 ^= u2 << 18 | u2 >>> 32 - 18; + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + o2[0] = x0 >>> 0 & 255; + o2[1] = x0 >>> 8 & 255; + o2[2] = x0 >>> 16 & 255; + o2[3] = x0 >>> 24 & 255; + o2[4] = x1 >>> 0 & 255; + o2[5] = x1 >>> 8 & 255; + o2[6] = x1 >>> 16 & 255; + o2[7] = x1 >>> 24 & 255; + o2[8] = x2 >>> 0 & 255; + o2[9] = x2 >>> 8 & 255; + o2[10] = x2 >>> 16 & 255; + o2[11] = x2 >>> 24 & 255; + o2[12] = x3 >>> 0 & 255; + o2[13] = x3 >>> 8 & 255; + o2[14] = x3 >>> 16 & 255; + o2[15] = x3 >>> 24 & 255; + o2[16] = x4 >>> 0 & 255; + o2[17] = x4 >>> 8 & 255; + o2[18] = x4 >>> 16 & 255; + o2[19] = x4 >>> 24 & 255; + o2[20] = x5 >>> 0 & 255; + o2[21] = x5 >>> 8 & 255; + o2[22] = x5 >>> 16 & 255; + o2[23] = x5 >>> 24 & 255; + o2[24] = x6 >>> 0 & 255; + o2[25] = x6 >>> 8 & 255; + o2[26] = x6 >>> 16 & 255; + o2[27] = x6 >>> 24 & 255; + o2[28] = x7 >>> 0 & 255; + o2[29] = x7 >>> 8 & 255; + o2[30] = x7 >>> 16 & 255; + o2[31] = x7 >>> 24 & 255; + o2[32] = x8 >>> 0 & 255; + o2[33] = x8 >>> 8 & 255; + o2[34] = x8 >>> 16 & 255; + o2[35] = x8 >>> 24 & 255; + o2[36] = x9 >>> 0 & 255; + o2[37] = x9 >>> 8 & 255; + o2[38] = x9 >>> 16 & 255; + o2[39] = x9 >>> 24 & 255; + o2[40] = x10 >>> 0 & 255; + o2[41] = x10 >>> 8 & 255; + o2[42] = x10 >>> 16 & 255; + o2[43] = x10 >>> 24 & 255; + o2[44] = x11 >>> 0 & 255; + o2[45] = x11 >>> 8 & 255; + o2[46] = x11 >>> 16 & 255; + o2[47] = x11 >>> 24 & 255; + o2[48] = x12 >>> 0 & 255; + o2[49] = x12 >>> 8 & 255; + o2[50] = x12 >>> 16 & 255; + o2[51] = x12 >>> 24 & 255; + o2[52] = x13 >>> 0 & 255; + o2[53] = x13 >>> 8 & 255; + o2[54] = x13 >>> 16 & 255; + o2[55] = x13 >>> 24 & 255; + o2[56] = x14 >>> 0 & 255; + o2[57] = x14 >>> 8 & 255; + o2[58] = x14 >>> 16 & 255; + o2[59] = x14 >>> 24 & 255; + o2[60] = x15 >>> 0 & 255; + o2[61] = x15 >>> 8 & 255; + o2[62] = x15 >>> 16 & 255; + o2[63] = x15 >>> 24 & 255; + } + function core_hsalsa20(o2, p2, k2, c2) { + var j0 = c2[0] & 255 | (c2[1] & 255) << 8 | (c2[2] & 255) << 16 | (c2[3] & 255) << 24, j1 = k2[0] & 255 | (k2[1] & 255) << 8 | (k2[2] & 255) << 16 | (k2[3] & 255) << 24, j2 = k2[4] & 255 | (k2[5] & 255) << 8 | (k2[6] & 255) << 16 | (k2[7] & 255) << 24, j3 = k2[8] & 255 | (k2[9] & 255) << 8 | (k2[10] & 255) << 16 | (k2[11] & 255) << 24, j4 = k2[12] & 255 | (k2[13] & 255) << 8 | (k2[14] & 255) << 16 | (k2[15] & 255) << 24, j5 = c2[4] & 255 | (c2[5] & 255) << 8 | (c2[6] & 255) << 16 | (c2[7] & 255) << 24, j6 = p2[0] & 255 | (p2[1] & 255) << 8 | (p2[2] & 255) << 16 | (p2[3] & 255) << 24, j7 = p2[4] & 255 | (p2[5] & 255) << 8 | (p2[6] & 255) << 16 | (p2[7] & 255) << 24, j8 = p2[8] & 255 | (p2[9] & 255) << 8 | (p2[10] & 255) << 16 | (p2[11] & 255) << 24, j9 = p2[12] & 255 | (p2[13] & 255) << 8 | (p2[14] & 255) << 16 | (p2[15] & 255) << 24, j10 = c2[8] & 255 | (c2[9] & 255) << 8 | (c2[10] & 255) << 16 | (c2[11] & 255) << 24, j11 = k2[16] & 255 | (k2[17] & 255) << 8 | (k2[18] & 255) << 16 | (k2[19] & 255) << 24, j12 = k2[20] & 255 | (k2[21] & 255) << 8 | (k2[22] & 255) << 16 | (k2[23] & 255) << 24, j13 = k2[24] & 255 | (k2[25] & 255) << 8 | (k2[26] & 255) << 16 | (k2[27] & 255) << 24, j14 = k2[28] & 255 | (k2[29] & 255) << 8 | (k2[30] & 255) << 16 | (k2[31] & 255) << 24, j15 = c2[12] & 255 | (c2[13] & 255) << 8 | (c2[14] & 255) << 16 | (c2[15] & 255) << 24; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u2; + for (var i = 0; i < 20; i += 2) { + u2 = x0 + x12 | 0; + x4 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x4 + x0 | 0; + x8 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x8 + x4 | 0; + x12 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x12 + x8 | 0; + x0 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x5 + x1 | 0; + x9 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x9 + x5 | 0; + x13 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x13 + x9 | 0; + x1 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x1 + x13 | 0; + x5 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x10 + x6 | 0; + x14 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x14 + x10 | 0; + x2 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x2 + x14 | 0; + x6 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x6 + x2 | 0; + x10 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x15 + x11 | 0; + x3 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x3 + x15 | 0; + x7 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x7 + x3 | 0; + x11 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x11 + x7 | 0; + x15 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x0 + x3 | 0; + x1 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x1 + x0 | 0; + x2 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x2 + x1 | 0; + x3 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x3 + x2 | 0; + x0 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x5 + x4 | 0; + x6 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x6 + x5 | 0; + x7 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x7 + x6 | 0; + x4 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x4 + x7 | 0; + x5 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x10 + x9 | 0; + x11 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x11 + x10 | 0; + x8 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x8 + x11 | 0; + x9 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x9 + x8 | 0; + x10 ^= u2 << 18 | u2 >>> 32 - 18; + u2 = x15 + x14 | 0; + x12 ^= u2 << 7 | u2 >>> 32 - 7; + u2 = x12 + x15 | 0; + x13 ^= u2 << 9 | u2 >>> 32 - 9; + u2 = x13 + x12 | 0; + x14 ^= u2 << 13 | u2 >>> 32 - 13; + u2 = x14 + x13 | 0; + x15 ^= u2 << 18 | u2 >>> 32 - 18; + } + o2[0] = x0 >>> 0 & 255; + o2[1] = x0 >>> 8 & 255; + o2[2] = x0 >>> 16 & 255; + o2[3] = x0 >>> 24 & 255; + o2[4] = x5 >>> 0 & 255; + o2[5] = x5 >>> 8 & 255; + o2[6] = x5 >>> 16 & 255; + o2[7] = x5 >>> 24 & 255; + o2[8] = x10 >>> 0 & 255; + o2[9] = x10 >>> 8 & 255; + o2[10] = x10 >>> 16 & 255; + o2[11] = x10 >>> 24 & 255; + o2[12] = x15 >>> 0 & 255; + o2[13] = x15 >>> 8 & 255; + o2[14] = x15 >>> 16 & 255; + o2[15] = x15 >>> 24 & 255; + o2[16] = x6 >>> 0 & 255; + o2[17] = x6 >>> 8 & 255; + o2[18] = x6 >>> 16 & 255; + o2[19] = x6 >>> 24 & 255; + o2[20] = x7 >>> 0 & 255; + o2[21] = x7 >>> 8 & 255; + o2[22] = x7 >>> 16 & 255; + o2[23] = x7 >>> 24 & 255; + o2[24] = x8 >>> 0 & 255; + o2[25] = x8 >>> 8 & 255; + o2[26] = x8 >>> 16 & 255; + o2[27] = x8 >>> 24 & 255; + o2[28] = x9 >>> 0 & 255; + o2[29] = x9 >>> 8 & 255; + o2[30] = x9 >>> 16 & 255; + o2[31] = x9 >>> 24 & 255; + } + function crypto_core_salsa20(out, inp, k2, c2) { + core_salsa20(out, inp, k2, c2); + } + function crypto_core_hsalsa20(out, inp, k2, c2) { + core_hsalsa20(out, inp, k2, c2); + } + var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + function crypto_stream_salsa20_xor(c2, cpos, m2, mpos, b2, n, k2) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u2, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b2 >= 64) { + crypto_core_salsa20(x, z, k2, sigma); + for (i = 0; i < 64; i++) c2[cpos + i] = m2[mpos + i] ^ x[i]; + u2 = 1; + for (i = 8; i < 16; i++) { + u2 = u2 + (z[i] & 255) | 0; + z[i] = u2 & 255; + u2 >>>= 8; + } + b2 -= 64; + cpos += 64; + mpos += 64; + } + if (b2 > 0) { + crypto_core_salsa20(x, z, k2, sigma); + for (i = 0; i < b2; i++) c2[cpos + i] = m2[mpos + i] ^ x[i]; + } + return 0; + } + function crypto_stream_salsa20(c2, cpos, b2, n, k2) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u2, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b2 >= 64) { + crypto_core_salsa20(x, z, k2, sigma); + for (i = 0; i < 64; i++) c2[cpos + i] = x[i]; + u2 = 1; + for (i = 8; i < 16; i++) { + u2 = u2 + (z[i] & 255) | 0; + z[i] = u2 & 255; + u2 >>>= 8; + } + b2 -= 64; + cpos += 64; + } + if (b2 > 0) { + crypto_core_salsa20(x, z, k2, sigma); + for (i = 0; i < b2; i++) c2[cpos + i] = x[i]; + } + return 0; + } + function crypto_stream(c2, cpos, d2, n, k2) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k2, sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; + return crypto_stream_salsa20(c2, cpos, d2, sn, s); + } + function crypto_stream_xor(c2, cpos, m2, mpos, d2, n, k2) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s, n, k2, sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; + return crypto_stream_salsa20_xor(c2, cpos, m2, mpos, d2, sn, s); + } + var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + var t0, t1, t2, t3, t4, t5, t6, t7; + t0 = key[0] & 255 | (key[1] & 255) << 8; + this.r[0] = t0 & 8191; + t1 = key[2] & 255 | (key[3] & 255) << 8; + this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; + t2 = key[4] & 255 | (key[5] & 255) << 8; + this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; + t3 = key[6] & 255 | (key[7] & 255) << 8; + this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; + t4 = key[8] & 255 | (key[9] & 255) << 8; + this.r[4] = (t3 >>> 4 | t4 << 12) & 255; + this.r[5] = t4 >>> 1 & 8190; + t5 = key[10] & 255 | (key[11] & 255) << 8; + this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; + t6 = key[12] & 255 | (key[13] & 255) << 8; + this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; + t7 = key[14] & 255 | (key[15] & 255) << 8; + this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this.r[9] = t7 >>> 5 & 127; + this.pad[0] = key[16] & 255 | (key[17] & 255) << 8; + this.pad[1] = key[18] & 255 | (key[19] & 255) << 8; + this.pad[2] = key[20] & 255 | (key[21] & 255) << 8; + this.pad[3] = key[22] & 255 | (key[23] & 255) << 8; + this.pad[4] = key[24] & 255 | (key[25] & 255) << 8; + this.pad[5] = key[26] & 255 | (key[27] & 255) << 8; + this.pad[6] = key[28] & 255 | (key[29] & 255) << 8; + this.pad[7] = key[30] & 255 | (key[31] & 255) << 8; + }; + poly1305.prototype.blocks = function(m2, mpos, bytes) { + var hibit = this.fin ? 0 : 1 << 11; + var t0, t1, t2, t3, t4, t5, t6, t7, c2; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + var h0 = this.h[0], h1 = this.h[1], h22 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; + var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; + while (bytes >= 16) { + t0 = m2[mpos + 0] & 255 | (m2[mpos + 1] & 255) << 8; + h0 += t0 & 8191; + t1 = m2[mpos + 2] & 255 | (m2[mpos + 3] & 255) << 8; + h1 += (t0 >>> 13 | t1 << 3) & 8191; + t2 = m2[mpos + 4] & 255 | (m2[mpos + 5] & 255) << 8; + h22 += (t1 >>> 10 | t2 << 6) & 8191; + t3 = m2[mpos + 6] & 255 | (m2[mpos + 7] & 255) << 8; + h3 += (t2 >>> 7 | t3 << 9) & 8191; + t4 = m2[mpos + 8] & 255 | (m2[mpos + 9] & 255) << 8; + h4 += (t3 >>> 4 | t4 << 12) & 8191; + h5 += t4 >>> 1 & 8191; + t5 = m2[mpos + 10] & 255 | (m2[mpos + 11] & 255) << 8; + h6 += (t4 >>> 14 | t5 << 2) & 8191; + t6 = m2[mpos + 12] & 255 | (m2[mpos + 13] & 255) << 8; + h7 += (t5 >>> 11 | t6 << 5) & 8191; + t7 = m2[mpos + 14] & 255 | (m2[mpos + 15] & 255) << 8; + h8 += (t6 >>> 8 | t7 << 8) & 8191; + h9 += t7 >>> 5 | hibit; + c2 = 0; + d0 = c2; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h22 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c2 = d0 >>> 13; + d0 &= 8191; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c2 += d0 >>> 13; + d0 &= 8191; + d1 = c2; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h22 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c2 = d1 >>> 13; + d1 &= 8191; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c2 += d1 >>> 13; + d1 &= 8191; + d2 = c2; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h22 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c2 = d2 >>> 13; + d2 &= 8191; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c2 += d2 >>> 13; + d2 &= 8191; + d3 = c2; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h22 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c2 = d3 >>> 13; + d3 &= 8191; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c2 += d3 >>> 13; + d3 &= 8191; + d4 = c2; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h22 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c2 = d4 >>> 13; + d4 &= 8191; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c2 += d4 >>> 13; + d4 &= 8191; + d5 = c2; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h22 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c2 = d5 >>> 13; + d5 &= 8191; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c2 += d5 >>> 13; + d5 &= 8191; + d6 = c2; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h22 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c2 = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c2 += d6 >>> 13; + d6 &= 8191; + d7 = c2; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h22 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c2 = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c2 += d7 >>> 13; + d7 &= 8191; + d8 = c2; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h22 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c2 = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c2 += d8 >>> 13; + d8 &= 8191; + d9 = c2; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h22 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c2 = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c2 += d9 >>> 13; + d9 &= 8191; + c2 = (c2 << 2) + c2 | 0; + c2 = c2 + d0 | 0; + d0 = c2 & 8191; + c2 = c2 >>> 13; + d1 += c2; + h0 = d0; + h1 = d1; + h22 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h22; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; + }; + poly1305.prototype.finish = function(mac, macpos) { + var g2 = new Uint16Array(10); + var c2, mask, f2, i; + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + c2 = this.h[1] >>> 13; + this.h[1] &= 8191; + for (i = 2; i < 10; i++) { + this.h[i] += c2; + c2 = this.h[i] >>> 13; + this.h[i] &= 8191; + } + this.h[0] += c2 * 5; + c2 = this.h[0] >>> 13; + this.h[0] &= 8191; + this.h[1] += c2; + c2 = this.h[1] >>> 13; + this.h[1] &= 8191; + this.h[2] += c2; + g2[0] = this.h[0] + 5; + c2 = g2[0] >>> 13; + g2[0] &= 8191; + for (i = 1; i < 10; i++) { + g2[i] = this.h[i] + c2; + c2 = g2[i] >>> 13; + g2[i] &= 8191; + } + g2[9] -= 1 << 13; + mask = (c2 ^ 1) - 1; + for (i = 0; i < 10; i++) g2[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g2[i]; + this.h[0] = (this.h[0] | this.h[1] << 13) & 65535; + this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535; + this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535; + this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535; + this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535; + this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535; + this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535; + this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535; + f2 = this.h[0] + this.pad[0]; + this.h[0] = f2 & 65535; + for (i = 1; i < 8; i++) { + f2 = (this.h[i] + this.pad[i] | 0) + (f2 >>> 16) | 0; + this.h[i] = f2 & 65535; + } + mac[macpos + 0] = this.h[0] >>> 0 & 255; + mac[macpos + 1] = this.h[0] >>> 8 & 255; + mac[macpos + 2] = this.h[1] >>> 0 & 255; + mac[macpos + 3] = this.h[1] >>> 8 & 255; + mac[macpos + 4] = this.h[2] >>> 0 & 255; + mac[macpos + 5] = this.h[2] >>> 8 & 255; + mac[macpos + 6] = this.h[3] >>> 0 & 255; + mac[macpos + 7] = this.h[3] >>> 8 & 255; + mac[macpos + 8] = this.h[4] >>> 0 & 255; + mac[macpos + 9] = this.h[4] >>> 8 & 255; + mac[macpos + 10] = this.h[5] >>> 0 & 255; + mac[macpos + 11] = this.h[5] >>> 8 & 255; + mac[macpos + 12] = this.h[6] >>> 0 & 255; + mac[macpos + 13] = this.h[6] >>> 8 & 255; + mac[macpos + 14] = this.h[7] >>> 0 & 255; + mac[macpos + 15] = this.h[7] >>> 8 & 255; + }; + poly1305.prototype.update = function(m2, mpos, bytes) { + var i, want; + if (this.leftover) { + want = 16 - this.leftover; + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m2[mpos + i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + if (bytes >= 16) { + want = bytes - bytes % 16; + this.blocks(m2, mpos, want); + mpos += want; + bytes -= want; + } + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m2[mpos + i]; + this.leftover += bytes; + } + }; + function crypto_onetimeauth(out, outpos, m2, mpos, n, k2) { + var s = new poly1305(k2); + s.update(m2, mpos, n); + s.finish(out, outpos); + return 0; + } + function crypto_onetimeauth_verify(h3, hpos, m2, mpos, n, k2) { + var x = new Uint8Array(16); + crypto_onetimeauth(x, 0, m2, mpos, n, k2); + return crypto_verify_16(h3, hpos, x, 0); + } + function crypto_secretbox(c2, m2, d2, n, k2) { + var i; + if (d2 < 32) return -1; + crypto_stream_xor(c2, 0, m2, 0, d2, n, k2); + crypto_onetimeauth(c2, 16, c2, 32, d2 - 32, c2); + for (i = 0; i < 16; i++) c2[i] = 0; + return 0; + } + function crypto_secretbox_open(m2, c2, d2, n, k2) { + var i; + var x = new Uint8Array(32); + if (d2 < 32) return -1; + crypto_stream(x, 0, 32, n, k2); + if (crypto_onetimeauth_verify(c2, 16, c2, 32, d2 - 32, x) !== 0) return -1; + crypto_stream_xor(m2, 0, c2, 0, d2, n, k2); + for (i = 0; i < 32; i++) m2[i] = 0; + return 0; + } + function set25519(r2, a) { + var i; + for (i = 0; i < 16; i++) r2[i] = a[i] | 0; + } + function car25519(o2) { + var i, v2, c2 = 1; + for (i = 0; i < 16; i++) { + v2 = o2[i] + c2 + 65535; + c2 = Math.floor(v2 / 65536); + o2[i] = v2 - c2 * 65536; + } + o2[0] += c2 - 1 + 37 * (c2 - 1); + } + function sel25519(p2, q, b2) { + var t, c2 = ~(b2 - 1); + for (var i = 0; i < 16; i++) { + t = c2 & (p2[i] ^ q[i]); + p2[i] ^= t; + q[i] ^= t; + } + } + function pack25519(o2, n) { + var i, j, b2; + var m2 = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m2[0] = t[0] - 65517; + for (i = 1; i < 15; i++) { + m2[i] = t[i] - 65535 - (m2[i - 1] >> 16 & 1); + m2[i - 1] &= 65535; + } + m2[15] = t[15] - 32767 - (m2[14] >> 16 & 1); + b2 = m2[15] >> 16 & 1; + m2[14] &= 65535; + sel25519(t, m2, 1 - b2); + } + for (i = 0; i < 16; i++) { + o2[2 * i] = t[i] & 255; + o2[2 * i + 1] = t[i] >> 8; + } + } + function neq25519(a, b2) { + var c2 = new Uint8Array(32), d2 = new Uint8Array(32); + pack25519(c2, a); + pack25519(d2, b2); + return crypto_verify_32(c2, 0, d2, 0); + } + function par25519(a) { + var d2 = new Uint8Array(32); + pack25519(d2, a); + return d2[0] & 1; + } + function unpack25519(o2, n) { + var i; + for (i = 0; i < 16; i++) o2[i] = n[2 * i] + (n[2 * i + 1] << 8); + o2[15] &= 32767; + } + function A(o2, a, b2) { + for (var i = 0; i < 16; i++) o2[i] = a[i] + b2[i]; + } + function Z(o2, a, b2) { + for (var i = 0; i < 16; i++) o2[i] = a[i] - b2[i]; + } + function M(o2, a, b2) { + var v2, c2, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b2[0], b1 = b2[1], b22 = b2[2], b3 = b2[3], b4 = b2[4], b5 = b2[5], b6 = b2[6], b7 = b2[7], b8 = b2[8], b9 = b2[9], b10 = b2[10], b11 = b2[11], b12 = b2[12], b13 = b2[13], b14 = b2[14], b15 = b2[15]; + v2 = a[0]; + t0 += v2 * b0; + t1 += v2 * b1; + t2 += v2 * b22; + t3 += v2 * b3; + t4 += v2 * b4; + t5 += v2 * b5; + t6 += v2 * b6; + t7 += v2 * b7; + t8 += v2 * b8; + t9 += v2 * b9; + t10 += v2 * b10; + t11 += v2 * b11; + t12 += v2 * b12; + t13 += v2 * b13; + t14 += v2 * b14; + t15 += v2 * b15; + v2 = a[1]; + t1 += v2 * b0; + t2 += v2 * b1; + t3 += v2 * b22; + t4 += v2 * b3; + t5 += v2 * b4; + t6 += v2 * b5; + t7 += v2 * b6; + t8 += v2 * b7; + t9 += v2 * b8; + t10 += v2 * b9; + t11 += v2 * b10; + t12 += v2 * b11; + t13 += v2 * b12; + t14 += v2 * b13; + t15 += v2 * b14; + t16 += v2 * b15; + v2 = a[2]; + t2 += v2 * b0; + t3 += v2 * b1; + t4 += v2 * b22; + t5 += v2 * b3; + t6 += v2 * b4; + t7 += v2 * b5; + t8 += v2 * b6; + t9 += v2 * b7; + t10 += v2 * b8; + t11 += v2 * b9; + t12 += v2 * b10; + t13 += v2 * b11; + t14 += v2 * b12; + t15 += v2 * b13; + t16 += v2 * b14; + t17 += v2 * b15; + v2 = a[3]; + t3 += v2 * b0; + t4 += v2 * b1; + t5 += v2 * b22; + t6 += v2 * b3; + t7 += v2 * b4; + t8 += v2 * b5; + t9 += v2 * b6; + t10 += v2 * b7; + t11 += v2 * b8; + t12 += v2 * b9; + t13 += v2 * b10; + t14 += v2 * b11; + t15 += v2 * b12; + t16 += v2 * b13; + t17 += v2 * b14; + t18 += v2 * b15; + v2 = a[4]; + t4 += v2 * b0; + t5 += v2 * b1; + t6 += v2 * b22; + t7 += v2 * b3; + t8 += v2 * b4; + t9 += v2 * b5; + t10 += v2 * b6; + t11 += v2 * b7; + t12 += v2 * b8; + t13 += v2 * b9; + t14 += v2 * b10; + t15 += v2 * b11; + t16 += v2 * b12; + t17 += v2 * b13; + t18 += v2 * b14; + t19 += v2 * b15; + v2 = a[5]; + t5 += v2 * b0; + t6 += v2 * b1; + t7 += v2 * b22; + t8 += v2 * b3; + t9 += v2 * b4; + t10 += v2 * b5; + t11 += v2 * b6; + t12 += v2 * b7; + t13 += v2 * b8; + t14 += v2 * b9; + t15 += v2 * b10; + t16 += v2 * b11; + t17 += v2 * b12; + t18 += v2 * b13; + t19 += v2 * b14; + t20 += v2 * b15; + v2 = a[6]; + t6 += v2 * b0; + t7 += v2 * b1; + t8 += v2 * b22; + t9 += v2 * b3; + t10 += v2 * b4; + t11 += v2 * b5; + t12 += v2 * b6; + t13 += v2 * b7; + t14 += v2 * b8; + t15 += v2 * b9; + t16 += v2 * b10; + t17 += v2 * b11; + t18 += v2 * b12; + t19 += v2 * b13; + t20 += v2 * b14; + t21 += v2 * b15; + v2 = a[7]; + t7 += v2 * b0; + t8 += v2 * b1; + t9 += v2 * b22; + t10 += v2 * b3; + t11 += v2 * b4; + t12 += v2 * b5; + t13 += v2 * b6; + t14 += v2 * b7; + t15 += v2 * b8; + t16 += v2 * b9; + t17 += v2 * b10; + t18 += v2 * b11; + t19 += v2 * b12; + t20 += v2 * b13; + t21 += v2 * b14; + t22 += v2 * b15; + v2 = a[8]; + t8 += v2 * b0; + t9 += v2 * b1; + t10 += v2 * b22; + t11 += v2 * b3; + t12 += v2 * b4; + t13 += v2 * b5; + t14 += v2 * b6; + t15 += v2 * b7; + t16 += v2 * b8; + t17 += v2 * b9; + t18 += v2 * b10; + t19 += v2 * b11; + t20 += v2 * b12; + t21 += v2 * b13; + t22 += v2 * b14; + t23 += v2 * b15; + v2 = a[9]; + t9 += v2 * b0; + t10 += v2 * b1; + t11 += v2 * b22; + t12 += v2 * b3; + t13 += v2 * b4; + t14 += v2 * b5; + t15 += v2 * b6; + t16 += v2 * b7; + t17 += v2 * b8; + t18 += v2 * b9; + t19 += v2 * b10; + t20 += v2 * b11; + t21 += v2 * b12; + t22 += v2 * b13; + t23 += v2 * b14; + t24 += v2 * b15; + v2 = a[10]; + t10 += v2 * b0; + t11 += v2 * b1; + t12 += v2 * b22; + t13 += v2 * b3; + t14 += v2 * b4; + t15 += v2 * b5; + t16 += v2 * b6; + t17 += v2 * b7; + t18 += v2 * b8; + t19 += v2 * b9; + t20 += v2 * b10; + t21 += v2 * b11; + t22 += v2 * b12; + t23 += v2 * b13; + t24 += v2 * b14; + t25 += v2 * b15; + v2 = a[11]; + t11 += v2 * b0; + t12 += v2 * b1; + t13 += v2 * b22; + t14 += v2 * b3; + t15 += v2 * b4; + t16 += v2 * b5; + t17 += v2 * b6; + t18 += v2 * b7; + t19 += v2 * b8; + t20 += v2 * b9; + t21 += v2 * b10; + t22 += v2 * b11; + t23 += v2 * b12; + t24 += v2 * b13; + t25 += v2 * b14; + t26 += v2 * b15; + v2 = a[12]; + t12 += v2 * b0; + t13 += v2 * b1; + t14 += v2 * b22; + t15 += v2 * b3; + t16 += v2 * b4; + t17 += v2 * b5; + t18 += v2 * b6; + t19 += v2 * b7; + t20 += v2 * b8; + t21 += v2 * b9; + t22 += v2 * b10; + t23 += v2 * b11; + t24 += v2 * b12; + t25 += v2 * b13; + t26 += v2 * b14; + t27 += v2 * b15; + v2 = a[13]; + t13 += v2 * b0; + t14 += v2 * b1; + t15 += v2 * b22; + t16 += v2 * b3; + t17 += v2 * b4; + t18 += v2 * b5; + t19 += v2 * b6; + t20 += v2 * b7; + t21 += v2 * b8; + t22 += v2 * b9; + t23 += v2 * b10; + t24 += v2 * b11; + t25 += v2 * b12; + t26 += v2 * b13; + t27 += v2 * b14; + t28 += v2 * b15; + v2 = a[14]; + t14 += v2 * b0; + t15 += v2 * b1; + t16 += v2 * b22; + t17 += v2 * b3; + t18 += v2 * b4; + t19 += v2 * b5; + t20 += v2 * b6; + t21 += v2 * b7; + t22 += v2 * b8; + t23 += v2 * b9; + t24 += v2 * b10; + t25 += v2 * b11; + t26 += v2 * b12; + t27 += v2 * b13; + t28 += v2 * b14; + t29 += v2 * b15; + v2 = a[15]; + t15 += v2 * b0; + t16 += v2 * b1; + t17 += v2 * b22; + t18 += v2 * b3; + t19 += v2 * b4; + t20 += v2 * b5; + t21 += v2 * b6; + t22 += v2 * b7; + t23 += v2 * b8; + t24 += v2 * b9; + t25 += v2 * b10; + t26 += v2 * b11; + t27 += v2 * b12; + t28 += v2 * b13; + t29 += v2 * b14; + t30 += v2 * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c2 = 1; + v2 = t0 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t0 = v2 - c2 * 65536; + v2 = t1 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t1 = v2 - c2 * 65536; + v2 = t2 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t2 = v2 - c2 * 65536; + v2 = t3 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t3 = v2 - c2 * 65536; + v2 = t4 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t4 = v2 - c2 * 65536; + v2 = t5 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t5 = v2 - c2 * 65536; + v2 = t6 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t6 = v2 - c2 * 65536; + v2 = t7 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t7 = v2 - c2 * 65536; + v2 = t8 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t8 = v2 - c2 * 65536; + v2 = t9 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t9 = v2 - c2 * 65536; + v2 = t10 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t10 = v2 - c2 * 65536; + v2 = t11 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t11 = v2 - c2 * 65536; + v2 = t12 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t12 = v2 - c2 * 65536; + v2 = t13 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t13 = v2 - c2 * 65536; + v2 = t14 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t14 = v2 - c2 * 65536; + v2 = t15 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t15 = v2 - c2 * 65536; + t0 += c2 - 1 + 37 * (c2 - 1); + c2 = 1; + v2 = t0 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t0 = v2 - c2 * 65536; + v2 = t1 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t1 = v2 - c2 * 65536; + v2 = t2 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t2 = v2 - c2 * 65536; + v2 = t3 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t3 = v2 - c2 * 65536; + v2 = t4 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t4 = v2 - c2 * 65536; + v2 = t5 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t5 = v2 - c2 * 65536; + v2 = t6 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t6 = v2 - c2 * 65536; + v2 = t7 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t7 = v2 - c2 * 65536; + v2 = t8 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t8 = v2 - c2 * 65536; + v2 = t9 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t9 = v2 - c2 * 65536; + v2 = t10 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t10 = v2 - c2 * 65536; + v2 = t11 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t11 = v2 - c2 * 65536; + v2 = t12 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t12 = v2 - c2 * 65536; + v2 = t13 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t13 = v2 - c2 * 65536; + v2 = t14 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t14 = v2 - c2 * 65536; + v2 = t15 + c2 + 65535; + c2 = Math.floor(v2 / 65536); + t15 = v2 - c2 * 65536; + t0 += c2 - 1 + 37 * (c2 - 1); + o2[0] = t0; + o2[1] = t1; + o2[2] = t2; + o2[3] = t3; + o2[4] = t4; + o2[5] = t5; + o2[6] = t6; + o2[7] = t7; + o2[8] = t8; + o2[9] = t9; + o2[10] = t10; + o2[11] = t11; + o2[12] = t12; + o2[13] = t13; + o2[14] = t14; + o2[15] = t15; + } + function S2(o2, a) { + M(o2, a, a); + } + function inv25519(o2, i) { + var c2 = gf(); + var a; + for (a = 0; a < 16; a++) c2[a] = i[a]; + for (a = 253; a >= 0; a--) { + S2(c2, c2); + if (a !== 2 && a !== 4) M(c2, c2, i); + } + for (a = 0; a < 16; a++) o2[a] = c2[a]; + } + function pow2523(o2, i) { + var c2 = gf(); + var a; + for (a = 0; a < 16; a++) c2[a] = i[a]; + for (a = 250; a >= 0; a--) { + S2(c2, c2); + if (a !== 1) M(c2, c2, i); + } + for (a = 0; a < 16; a++) o2[a] = c2[a]; + } + function crypto_scalarmult(q, n, p2) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r2, i; + var a = gf(), b2 = gf(), c2 = gf(), d2 = gf(), e = gf(), f2 = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31] = n[31] & 127 | 64; + z[0] &= 248; + unpack25519(x, p2); + for (i = 0; i < 16; i++) { + b2[i] = x[i]; + d2[i] = a[i] = c2[i] = 0; + } + a[0] = d2[0] = 1; + for (i = 254; i >= 0; --i) { + r2 = z[i >>> 3] >>> (i & 7) & 1; + sel25519(a, b2, r2); + sel25519(c2, d2, r2); + A(e, a, c2); + Z(a, a, c2); + A(c2, b2, d2); + Z(b2, b2, d2); + S2(d2, e); + S2(f2, a); + M(a, c2, a); + M(c2, b2, e); + A(e, a, c2); + Z(a, a, c2); + S2(b2, a); + Z(c2, d2, f2); + M(a, c2, _121665); + A(a, a, d2); + M(c2, c2, a); + M(a, d2, f2); + M(d2, b2, x); + S2(b2, e); + sel25519(a, b2, r2); + sel25519(c2, d2, r2); + } + for (i = 0; i < 16; i++) { + x[i + 16] = a[i]; + x[i + 32] = c2[i]; + x[i + 48] = b2[i]; + x[i + 64] = d2[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32, x32); + M(x16, x16, x32); + pack25519(q, x16); + return 0; + } + function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); + } + function crypto_box_keypair(y2, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y2, x); + } + function crypto_box_beforenm(k2, y2, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y2); + return crypto_core_hsalsa20(k2, _0, s, sigma); + } + var crypto_box_afternm = crypto_secretbox; + var crypto_box_open_afternm = crypto_secretbox_open; + function crypto_box(c2, m2, d2, n, y2, x) { + var k2 = new Uint8Array(32); + crypto_box_beforenm(k2, y2, x); + return crypto_box_afternm(c2, m2, d2, n, k2); + } + function crypto_box_open(m2, c2, d2, n, y2, x) { + var k2 = new Uint8Array(32); + crypto_box_beforenm(k2, y2, x); + return crypto_box_open_afternm(m2, c2, d2, n, k2); + } + var K = [ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 + ]; + function crypto_hashblocks_hl(hh, hl, m2, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h3, l2, a, b2, c2, d2; + var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = m2[j + 0] << 24 | m2[j + 1] << 16 | m2[j + 2] << 8 | m2[j + 3]; + wl[i] = m2[j + 4] << 24 | m2[j + 5] << 16 | m2[j + 6] << 8 | m2[j + 7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + h3 = ah7; + l2 = al7; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); + l2 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + h3 = ah4 & ah5 ^ ~ah4 & ah6; + l2 = al4 & al5 ^ ~al4 & al6; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + h3 = K[i * 2]; + l2 = K[i * 2 + 1]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + h3 = wh[i % 16]; + l2 = wl[i % 16]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + th = c2 & 65535 | d2 << 16; + tl = a & 65535 | b2 << 16; + h3 = th; + l2 = tl; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); + l2 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + h3 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; + l2 = al0 & al1 ^ al0 & al2 ^ al1 & al2; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + bh7 = c2 & 65535 | d2 << 16; + bl7 = a & 65535 | b2 << 16; + h3 = bh3; + l2 = bl3; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = th; + l2 = tl; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + bh3 = c2 & 65535 | d2 << 16; + bl3 = a & 65535 | b2 << 16; + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + if (i % 16 === 15) { + for (j = 0; j < 16; j++) { + h3 = wh[j]; + l2 = wl[j]; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = wh[(j + 9) % 16]; + l2 = wl[(j + 9) % 16]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + th = wh[(j + 1) % 16]; + tl = wl[(j + 1) % 16]; + h3 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; + l2 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + th = wh[(j + 14) % 16]; + tl = wl[(j + 14) % 16]; + h3 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; + l2 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + wh[j] = c2 & 65535 | d2 << 16; + wl[j] = a & 65535 | b2 << 16; + } + } + } + h3 = ah0; + l2 = al0; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[0]; + l2 = hl[0]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[0] = ah0 = c2 & 65535 | d2 << 16; + hl[0] = al0 = a & 65535 | b2 << 16; + h3 = ah1; + l2 = al1; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[1]; + l2 = hl[1]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[1] = ah1 = c2 & 65535 | d2 << 16; + hl[1] = al1 = a & 65535 | b2 << 16; + h3 = ah2; + l2 = al2; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[2]; + l2 = hl[2]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[2] = ah2 = c2 & 65535 | d2 << 16; + hl[2] = al2 = a & 65535 | b2 << 16; + h3 = ah3; + l2 = al3; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[3]; + l2 = hl[3]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[3] = ah3 = c2 & 65535 | d2 << 16; + hl[3] = al3 = a & 65535 | b2 << 16; + h3 = ah4; + l2 = al4; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[4]; + l2 = hl[4]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[4] = ah4 = c2 & 65535 | d2 << 16; + hl[4] = al4 = a & 65535 | b2 << 16; + h3 = ah5; + l2 = al5; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[5]; + l2 = hl[5]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[5] = ah5 = c2 & 65535 | d2 << 16; + hl[5] = al5 = a & 65535 | b2 << 16; + h3 = ah6; + l2 = al6; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[6]; + l2 = hl[6]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[6] = ah6 = c2 & 65535 | d2 << 16; + hl[6] = al6 = a & 65535 | b2 << 16; + h3 = ah7; + l2 = al7; + a = l2 & 65535; + b2 = l2 >>> 16; + c2 = h3 & 65535; + d2 = h3 >>> 16; + h3 = hh[7]; + l2 = hl[7]; + a += l2 & 65535; + b2 += l2 >>> 16; + c2 += h3 & 65535; + d2 += h3 >>> 16; + b2 += a >>> 16; + c2 += b2 >>> 16; + d2 += c2 >>> 16; + hh[7] = ah7 = c2 & 65535 | d2 << 16; + hl[7] = al7 = a & 65535 | b2 << 16; + pos += 128; + n -= 128; + } + return n; + } + function crypto_hash(out, m2, n) { + var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b2 = n; + hh[0] = 1779033703; + hh[1] = 3144134277; + hh[2] = 1013904242; + hh[3] = 2773480762; + hh[4] = 1359893119; + hh[5] = 2600822924; + hh[6] = 528734635; + hh[7] = 1541459225; + hl[0] = 4089235720; + hl[1] = 2227873595; + hl[2] = 4271175723; + hl[3] = 1595750129; + hl[4] = 2917565137; + hl[5] = 725511199; + hl[6] = 4215389547; + hl[7] = 327033209; + crypto_hashblocks_hl(hh, hl, m2, n); + n %= 128; + for (i = 0; i < n; i++) x[i] = m2[b2 - n + i]; + x[n] = 128; + n = 256 - 128 * (n < 112 ? 1 : 0); + x[n - 9] = 0; + ts64(x, n - 8, b2 / 536870912 | 0, b2 << 3); + crypto_hashblocks_hl(hh, hl, x, n); + for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]); + return 0; + } + function add(p2, q) { + var a = gf(), b2 = gf(), c2 = gf(), d2 = gf(), e = gf(), f2 = gf(), g2 = gf(), h3 = gf(), t = gf(); + Z(a, p2[1], p2[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b2, p2[0], p2[1]); + A(t, q[0], q[1]); + M(b2, b2, t); + M(c2, p2[3], q[3]); + M(c2, c2, D2); + M(d2, p2[2], q[2]); + A(d2, d2, d2); + Z(e, b2, a); + Z(f2, d2, c2); + A(g2, d2, c2); + A(h3, b2, a); + M(p2[0], e, f2); + M(p2[1], h3, g2); + M(p2[2], g2, f2); + M(p2[3], e, h3); + } + function cswap(p2, q, b2) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p2[i], q[i], b2); + } + } + function pack(r2, p2) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p2[2]); + M(tx, p2[0], zi); + M(ty, p2[1], zi); + pack25519(r2, ty); + r2[31] ^= par25519(tx) << 7; + } + function scalarmult(p2, q, s) { + var b2, i; + set25519(p2[0], gf0); + set25519(p2[1], gf1); + set25519(p2[2], gf1); + set25519(p2[3], gf0); + for (i = 255; i >= 0; --i) { + b2 = s[i / 8 | 0] >> (i & 7) & 1; + cswap(p2, q, b2); + add(q, p2); + add(p2, p2); + cswap(p2, q, b2); + } + } + function scalarbase(p2, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p2, q, s); + } + function crypto_sign_keypair(pk, sk, seeded) { + var d2 = new Uint8Array(64); + var p2 = [gf(), gf(), gf(), gf()]; + var i; + if (!seeded) randombytes(sk, 32); + crypto_hash(d2, sk, 32); + d2[0] &= 248; + d2[31] &= 127; + d2[31] |= 64; + scalarbase(p2, d2); + pack(pk, p2); + for (i = 0; i < 32; i++) sk[i + 32] = pk[i]; + return 0; + } + var L = new Float64Array([237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]); + function modL(r2, x) { + var carry, i, j, k2; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k2 = i - 12; j < k2; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i + 1] += x[i] >> 8; + r2[i] = x[i] & 255; + } + } + function reduce(r2) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r2[i]; + for (i = 0; i < 64; i++) r2[i] = 0; + modL(r2, x); + } + function crypto_sign(sm, m2, n, sk) { + var d2 = new Uint8Array(64), h3 = new Uint8Array(64), r2 = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p2 = [gf(), gf(), gf(), gf()]; + crypto_hash(d2, sk, 32); + d2[0] &= 248; + d2[31] &= 127; + d2[31] |= 64; + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m2[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d2[32 + i]; + crypto_hash(r2, sm.subarray(32), n + 32); + reduce(r2); + scalarbase(p2, r2); + pack(sm, p2); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h3, sm, n + 64); + reduce(h3); + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r2[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i + j] += h3[i] * d2[j]; + } + } + modL(sm.subarray(32), x); + return smlen; + } + function unpackneg(r2, p2) { + var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); + set25519(r2[2], gf1); + unpack25519(r2[1], p2); + S2(num, r2[1]); + M(den, num, D); + Z(num, num, r2[2]); + A(den, r2[2], den); + S2(den2, den); + S2(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r2[0], t, den); + S2(chk, r2[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r2[0], r2[0], I); + S2(chk, r2[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + if (par25519(r2[0]) === p2[31] >> 7) Z(r2[0], gf0, r2[0]); + M(r2[3], r2[0], r2[1]); + return 0; + } + function crypto_sign_open(m2, sm, n, pk) { + var i; + var t = new Uint8Array(32), h3 = new Uint8Array(64); + var p2 = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; + if (n < 64) return -1; + if (unpackneg(q, pk)) return -1; + for (i = 0; i < n; i++) m2[i] = sm[i]; + for (i = 0; i < 32; i++) m2[i + 32] = pk[i]; + crypto_hash(h3, m2, n); + reduce(h3); + scalarmult(p2, q, h3); + scalarbase(q, sm.subarray(32)); + add(p2, q); + pack(t, p2); + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m2[i] = 0; + return -1; + } + for (i = 0; i < n; i++) m2[i] = sm[i + 64]; + return n; + } + var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; + nacl.lowlevel = { + crypto_core_hsalsa20, + crypto_stream_xor, + crypto_stream, + crypto_stream_salsa20_xor, + crypto_stream_salsa20, + crypto_onetimeauth, + crypto_onetimeauth_verify, + crypto_verify_16, + crypto_verify_32, + crypto_secretbox, + crypto_secretbox_open, + crypto_scalarmult, + crypto_scalarmult_base, + crypto_box_beforenm, + crypto_box_afternm, + crypto_box, + crypto_box_open, + crypto_box_keypair, + crypto_hash, + crypto_sign, + crypto_sign_keypair, + crypto_sign_open, + crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES, + crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES, + crypto_hash_BYTES, + gf, + D, + L, + pack25519, + unpack25519, + M, + A, + S: S2, + Z, + pow2523, + add, + set25519, + modL, + scalarmult, + scalarbase + }; + function checkLengths(k2, n) { + if (k2.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size"); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size"); + } + function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size"); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size"); + } + function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError("unexpected type, use Uint8Array"); + } + } + function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; + } + nacl.randomBytes = function(n) { + var b2 = new Uint8Array(n); + randombytes(b2, n); + return b2; + }; + nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m2 = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c2 = new Uint8Array(m2.length); + for (var i = 0; i < msg.length; i++) m2[i + crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c2, m2, m2.length, nonce, key); + return c2.subarray(crypto_secretbox_BOXZEROBYTES); + }; + nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c2 = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m2 = new Uint8Array(c2.length); + for (var i = 0; i < box.length; i++) c2[i + crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c2.length < 32) return null; + if (crypto_secretbox_open(m2, c2, c2.length, nonce, key) !== 0) return null; + return m2.subarray(crypto_secretbox_ZEROBYTES); + }; + nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; + nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; + nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + nacl.scalarMult = function(n, p2) { + checkArrayTypes(n, p2); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); + if (p2.length !== crypto_scalarmult_BYTES) throw new Error("bad p size"); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p2); + return q; + }; + nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; + }; + nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; + nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + nacl.box = function(msg, nonce, publicKey, secretKey) { + var k2 = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k2); + }; + nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k2 = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k2, publicKey, secretKey); + return k2; + }; + nacl.box.after = nacl.secretbox; + nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k2 = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k2); + }; + nacl.box.open.after = nacl.secretbox.open; + nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return { publicKey: pk, secretKey: sk }; + }; + nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error("bad secret key size"); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; + }; + nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; + nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; + nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; + nacl.box.nonceLength = crypto_box_NONCEBYTES; + nacl.box.overheadLength = nacl.secretbox.overheadLength; + nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error("bad secret key size"); + var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; + }; + nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error("bad public key size"); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m2 = new Uint8Array(mlen); + for (var i = 0; i < m2.length; i++) m2[i] = tmp[i]; + return m2; + }; + nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; + }; + nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error("bad signature size"); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error("bad public key size"); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m2 = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i]; + return crypto_sign_open(m2, sm, sm.length, publicKey) >= 0; + }; + nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return { publicKey: pk, secretKey: sk }; + }; + nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error("bad secret key size"); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i]; + return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; + }; + nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error("bad seed size"); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return { publicKey: pk, secretKey: sk }; + }; + nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; + nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; + nacl.sign.seedLength = crypto_sign_SEEDBYTES; + nacl.sign.signatureLength = crypto_sign_BYTES; + nacl.hash = function(msg) { + checkArrayTypes(msg); + var h3 = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h3, msg, msg.length); + return h3; + }; + nacl.hash.hashLength = crypto_hash_BYTES; + nacl.verify = function(x, y2) { + checkArrayTypes(x, y2); + if (x.length === 0 || y2.length === 0) return false; + if (x.length !== y2.length) return false; + return vn(x, 0, y2, 0, x.length) === 0 ? true : false; + }; + nacl.setPRNG = function(fn) { + randombytes = fn; + }; + (function() { + var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; + if (crypto && crypto.getRandomValues) { + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v2 = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v2.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v2[i]; + cleanup(v2); + }); + } else { + crypto = __webpack_require__2(982); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v2 = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v2[i]; + cleanup(v2); + }); + } + } + })(); + })(module2.exports ? module2.exports : self.nacl = self.nacl || {}); + }, + /***/ + 41(module2, __unused_webpack_exports, __webpack_require__2) { + var Base = __webpack_require__2(369), Client = __webpack_require__2(483), Server = __webpack_require__2(983); + var Driver = { + client: function(url, options) { + options = options || {}; + if (options.masking === void 0) options.masking = true; + return new Client(url, options); + }, + server: function(options) { + options = options || {}; + if (options.requireMasking === void 0) options.requireMasking = true; + return new Server(options); + }, + http: function() { + return Server.http.apply(Server, arguments); + }, + isSecureRequest: function(request) { + return Server.isSecureRequest(request); + }, + isWebSocket: function(request) { + return Base.isWebSocket(request); + }, + validateOptions: function(options, validKeys) { + Base.validateOptions(options, validKeys); + } + }; + module2.exports = Driver; + }, + /***/ + 369(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer, Emitter = __webpack_require__2(434).EventEmitter, util = __webpack_require__2(23), streams = __webpack_require__2(578), Headers = __webpack_require__2(160), Reader = __webpack_require__2(212); + var Base = function(request, url, options) { + Emitter.call(this); + Base.validateOptions(options || {}, ["maxLength", "masking", "requireMasking", "protocols"]); + this._request = request; + this._reader = new Reader(); + this._options = options || {}; + this._maxLength = this._options.maxLength || this.MAX_LENGTH; + this._headers = new Headers(); + this.__queue = []; + this.readyState = 0; + this.url = url; + this.io = new streams.IO(this); + this.messages = new streams.Messages(this); + this._bindEventListeners(); + }; + util.inherits(Base, Emitter); + Base.isWebSocket = function(request) { + var connection = request.headers.connection || "", upgrade = request.headers.upgrade || ""; + return request.method === "GET" && connection.toLowerCase().split(/ *, */).indexOf("upgrade") >= 0 && upgrade.toLowerCase() === "websocket"; + }; + Base.validateOptions = function(options, validKeys) { + for (var key2 in options) { + if (validKeys.indexOf(key2) < 0) + throw new Error("Unrecognized option: " + key2); + } + }; + var instance = { + // This is 64MB, small enough for an average VPS to handle without + // crashing from process out of memory + MAX_LENGTH: 67108863, + STATES: ["connecting", "open", "closing", "closed"], + _bindEventListeners: function() { + var self2 = this; + this.messages.on("error", function() { + }); + this.on("message", function(event) { + var messages = self2.messages; + if (messages.readable) messages.emit("data", event.data); + }); + this.on("error", function(error) { + var messages = self2.messages; + if (messages.readable) messages.emit("error", error); + }); + this.on("close", function() { + var messages = self2.messages; + if (!messages.readable) return; + messages.readable = messages.writable = false; + messages.emit("end"); + }); + }, + getState: function() { + return this.STATES[this.readyState] || null; + }, + addExtension: function(extension) { + return false; + }, + setHeader: function(name, value) { + if (this.readyState > 0) return false; + this._headers.set(name, value); + return true; + }, + start: function() { + if (this.readyState !== 0) return false; + if (!Base.isWebSocket(this._request)) + return this._failHandshake(new Error("Not a WebSocket request")); + var response; + try { + response = this._handshakeResponse(); + } catch (error) { + return this._failHandshake(error); + } + this._write(response); + if (this._stage !== -1) this._open(); + return true; + }, + _failHandshake: function(error) { + var headers = new Headers(); + headers.set("Content-Type", "text/plain"); + headers.set("Content-Length", Buffer2.byteLength(error.message, "utf8")); + headers = ["HTTP/1.1 400 Bad Request", headers.toString(), error.message]; + this._write(Buffer2.from(headers.join("\r\n"), "utf8")); + this._fail("protocol_error", error.message); + return false; + }, + text: function(message) { + return this.frame(message); + }, + binary: function(message) { + return false; + }, + ping: function() { + return false; + }, + pong: function() { + return false; + }, + close: function(reason, code) { + if (this.readyState !== 1) return false; + this.readyState = 3; + this.emit("close", new Base.CloseEvent(null, null)); + return true; + }, + _open: function() { + this.readyState = 1; + this.__queue.forEach(function(args) { + this.frame.apply(this, args); + }, this); + this.__queue = []; + this.emit("open", new Base.OpenEvent()); + }, + _queue: function(message) { + this.__queue.push(message); + return true; + }, + _write: function(chunk) { + var io = this.io; + if (io.readable) io.emit("data", chunk); + }, + _fail: function(type, message) { + this.readyState = 2; + this.emit("error", new Error(message)); + this.close(); + } + }; + for (var key in instance) + Base.prototype[key] = instance[key]; + Base.ConnectEvent = function() { + }; + Base.OpenEvent = function() { + }; + Base.CloseEvent = function(code, reason) { + this.code = code; + this.reason = reason; + }; + Base.MessageEvent = function(data) { + this.data = data; + }; + Base.PingEvent = function(data) { + this.data = data; + }; + Base.PongEvent = function(data) { + this.data = data; + }; + module2.exports = Base; + }, + /***/ + 483(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer, crypto = __webpack_require__2(982), url = __webpack_require__2(16), util = __webpack_require__2(23), HttpParser = __webpack_require__2(565), Base = __webpack_require__2(369), Hybi = __webpack_require__2(518), Proxy = __webpack_require__2(662); + var Client = function(_url, options) { + this.version = "hybi-" + Hybi.VERSION; + Hybi.call(this, null, _url, options); + this.readyState = -1; + this._key = Client.generateKey(); + this._accept = Hybi.generateAccept(this._key); + this._http = new HttpParser("response"); + var uri = url.parse(this.url), auth = uri.auth && Buffer2.from(uri.auth, "utf8").toString("base64"); + if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0) + throw new Error(this.url + " is not a valid WebSocket URL"); + this._pathname = (uri.pathname || "/") + (uri.search || ""); + this._headers.set("Host", uri.host); + this._headers.set("Upgrade", "websocket"); + this._headers.set("Connection", "Upgrade"); + this._headers.set("Sec-WebSocket-Key", this._key); + this._headers.set("Sec-WebSocket-Version", Hybi.VERSION); + if (this._protocols.length > 0) + this._headers.set("Sec-WebSocket-Protocol", this._protocols.join(", ")); + if (auth) + this._headers.set("Authorization", "Basic " + auth); + }; + util.inherits(Client, Hybi); + Client.generateKey = function() { + return crypto.randomBytes(16).toString("base64"); + }; + var instance = { + VALID_PROTOCOLS: ["ws:", "wss:"], + proxy: function(origin, options) { + return new Proxy(this, origin, options); + }, + start: function() { + if (this.readyState !== -1) return false; + this._write(this._handshakeRequest()); + this.readyState = 0; + return true; + }, + parse: function(chunk) { + if (this.readyState === 3) return; + if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk); + this._http.parse(chunk); + if (!this._http.isComplete()) return; + this._validateHandshake(); + if (this.readyState === 3) return; + this._open(); + this.parse(this._http.body); + }, + _handshakeRequest: function() { + var extensions = this._extensions.generateOffer(); + if (extensions) + this._headers.set("Sec-WebSocket-Extensions", extensions); + var start = "GET " + this._pathname + " HTTP/1.1", headers = [start, this._headers.toString(), ""]; + return Buffer2.from(headers.join("\r\n"), "utf8"); + }, + _failHandshake: function(message) { + message = "Error during WebSocket handshake: " + message; + this.readyState = 3; + this.emit("error", new Error(message)); + this.emit("close", new Base.CloseEvent(this.ERRORS.protocol_error, message)); + }, + _validateHandshake: function() { + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + if (this._http.error) + return this._failHandshake(this._http.error.message); + if (this._http.statusCode !== 101) + return this._failHandshake("Unexpected response code: " + this._http.statusCode); + var headers = this._http.headers, upgrade = headers["upgrade"] || "", connection = headers["connection"] || "", accept = headers["sec-websocket-accept"] || "", protocol = headers["sec-websocket-protocol"] || ""; + if (upgrade === "") + return this._failHandshake("'Upgrade' header is missing"); + if (upgrade.toLowerCase() !== "websocket") + return this._failHandshake("'Upgrade' header value is not 'WebSocket'"); + if (connection === "") + return this._failHandshake("'Connection' header is missing"); + if (connection.toLowerCase() !== "upgrade") + return this._failHandshake("'Connection' header value is not 'Upgrade'"); + if (accept !== this._accept) + return this._failHandshake("Sec-WebSocket-Accept mismatch"); + this.protocol = null; + if (protocol !== "") { + if (this._protocols.indexOf(protocol) < 0) + return this._failHandshake("Sec-WebSocket-Protocol mismatch"); + else + this.protocol = protocol; + } + try { + this._extensions.activate(this.headers["sec-websocket-extensions"]); + } catch (e) { + return this._failHandshake(e.message); + } + } + }; + for (var key in instance) + Client.prototype[key] = instance[key]; + module2.exports = Client; + }, + /***/ + 61(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer, Base = __webpack_require__2(369), util = __webpack_require__2(23); + var Draft75 = function(request, url, options) { + Base.apply(this, arguments); + this._stage = 0; + this.version = "hixie-75"; + this._headers.set("Upgrade", "WebSocket"); + this._headers.set("Connection", "Upgrade"); + this._headers.set("WebSocket-Origin", this._request.headers.origin); + this._headers.set("WebSocket-Location", this.url); + }; + util.inherits(Draft75, Base); + var instance = { + close: function() { + if (this.readyState === 3) return false; + this.readyState = 3; + this.emit("close", new Base.CloseEvent(null, null)); + return true; + }, + parse: function(chunk) { + if (this.readyState > 1) return; + this._reader.put(chunk); + this._reader.eachByte(function(octet) { + var message; + switch (this._stage) { + case -1: + this._body.push(octet); + this._sendHandshakeBody(); + break; + case 0: + this._parseLeadingByte(octet); + break; + case 1: + this._length = (octet & 127) + 128 * this._length; + if (this._closing && this._length === 0) { + return this.close(); + } else if ((octet & 128) !== 128) { + if (this._length === 0) { + this._stage = 0; + } else { + this._skipped = 0; + this._stage = 2; + } + } + break; + case 2: + if (octet === 255) { + this._stage = 0; + message = Buffer2.from(this._buffer).toString("utf8", 0, this._buffer.length); + this.emit("message", new Base.MessageEvent(message)); + } else { + if (this._length) { + this._skipped += 1; + if (this._skipped === this._length) + this._stage = 0; + } else { + this._buffer.push(octet); + if (this._buffer.length > this._maxLength) return this.close(); + } + } + break; + } + }, this); + }, + frame: function(buffer) { + if (this.readyState === 0) return this._queue([buffer]); + if (this.readyState > 1) return false; + if (typeof buffer !== "string") buffer = buffer.toString(); + var length = Buffer2.byteLength(buffer), frame = Buffer2.allocUnsafe(length + 2); + frame[0] = 0; + frame.write(buffer, 1); + frame[frame.length - 1] = 255; + this._write(frame); + return true; + }, + _handshakeResponse: function() { + var start = "HTTP/1.1 101 Web Socket Protocol Handshake", headers = [start, this._headers.toString(), ""]; + return Buffer2.from(headers.join("\r\n"), "utf8"); + }, + _parseLeadingByte: function(octet) { + if ((octet & 128) === 128) { + this._length = 0; + this._stage = 1; + } else { + delete this._length; + delete this._skipped; + this._buffer = []; + this._stage = 2; + } + } + }; + for (var key in instance) + Draft75.prototype[key] = instance[key]; + module2.exports = Draft75; + }, + /***/ + 476(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer, Base = __webpack_require__2(369), Draft75 = __webpack_require__2(61), crypto = __webpack_require__2(982), util = __webpack_require__2(23); + var numberFromKey = function(key2) { + return parseInt((key2.match(/[0-9]/g) || []).join(""), 10); + }; + var spacesInKey = function(key2) { + return (key2.match(/ /g) || []).length; + }; + var Draft76 = function(request, url, options) { + Draft75.apply(this, arguments); + this._stage = -1; + this._body = []; + this.version = "hixie-76"; + this._headers.clear(); + this._headers.set("Upgrade", "WebSocket"); + this._headers.set("Connection", "Upgrade"); + this._headers.set("Sec-WebSocket-Origin", this._request.headers.origin); + this._headers.set("Sec-WebSocket-Location", this.url); + }; + util.inherits(Draft76, Draft75); + var instance = { + BODY_SIZE: 8, + start: function() { + if (!Draft75.prototype.start.call(this)) return false; + this._started = true; + this._sendHandshakeBody(); + return true; + }, + close: function() { + if (this.readyState === 3) return false; + if (this.readyState === 1) this._write(Buffer2.from([255, 0])); + this.readyState = 3; + this.emit("close", new Base.CloseEvent(null, null)); + return true; + }, + _handshakeResponse: function() { + var headers = this._request.headers, key1 = headers["sec-websocket-key1"], key2 = headers["sec-websocket-key2"]; + if (!key1) throw new Error("Missing required header: Sec-WebSocket-Key1"); + if (!key2) throw new Error("Missing required header: Sec-WebSocket-Key2"); + var number1 = numberFromKey(key1), spaces1 = spacesInKey(key1), number2 = numberFromKey(key2), spaces2 = spacesInKey(key2); + if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0) + throw new Error("Client sent invalid Sec-WebSocket-Key headers"); + this._keyValues = [number1 / spaces1, number2 / spaces2]; + var start = "HTTP/1.1 101 WebSocket Protocol Handshake", headers = [start, this._headers.toString(), ""]; + return Buffer2.from(headers.join("\r\n"), "binary"); + }, + _handshakeSignature: function() { + if (this._body.length < this.BODY_SIZE) return null; + var md5 = crypto.createHash("md5"), buffer = Buffer2.allocUnsafe(8 + this.BODY_SIZE); + buffer.writeUInt32BE(this._keyValues[0], 0); + buffer.writeUInt32BE(this._keyValues[1], 4); + Buffer2.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE); + md5.update(buffer); + return Buffer2.from(md5.digest("binary"), "binary"); + }, + _sendHandshakeBody: function() { + if (!this._started) return; + var signature = this._handshakeSignature(); + if (!signature) return; + this._write(signature); + this._stage = 0; + this._open(); + if (this._body.length > this.BODY_SIZE) + this.parse(this._body.slice(this.BODY_SIZE)); + }, + _parseLeadingByte: function(octet) { + if (octet !== 255) + return Draft75.prototype._parseLeadingByte.call(this, octet); + this._closing = true; + this._length = 0; + this._stage = 1; + } + }; + for (var key in instance) + Draft76.prototype[key] = instance[key]; + module2.exports = Draft76; + }, + /***/ + 160(module2) { + var Headers = function() { + this.clear(); + }; + Headers.prototype.ALLOWED_DUPLICATES = ["set-cookie", "set-cookie2", "warning", "www-authenticate"]; + Headers.prototype.clear = function() { + this._sent = {}; + this._lines = []; + }; + Headers.prototype.set = function(name, value) { + if (value === void 0) return; + name = this._strip(name); + value = this._strip(value); + var key = name.toLowerCase(); + if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) { + this._sent[key] = true; + this._lines.push(name + ": " + value + "\r\n"); + } + }; + Headers.prototype.toString = function() { + return this._lines.join(""); + }; + Headers.prototype._strip = function(string) { + return string.toString().replace(/^ */, "").replace(/ *$/, ""); + }; + module2.exports = Headers; + }, + /***/ + 518(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer, crypto = __webpack_require__2(982), util = __webpack_require__2(23), Extensions = __webpack_require__2(769), Base = __webpack_require__2(369), Frame = __webpack_require__2(68), Message = __webpack_require__2(814); + var Hybi = function(request, url, options) { + Base.apply(this, arguments); + this._extensions = new Extensions(); + this._stage = 0; + this._masking = this._options.masking; + this._protocols = this._options.protocols || []; + this._requireMasking = this._options.requireMasking; + this._pingCallbacks = {}; + if (typeof this._protocols === "string") + this._protocols = this._protocols.split(/ *, */); + if (!this._request) return; + var protos = this._request.headers["sec-websocket-protocol"], supported = this._protocols; + if (protos !== void 0) { + if (typeof protos === "string") protos = protos.split(/ *, */); + this.protocol = protos.filter(function(p2) { + return supported.indexOf(p2) >= 0; + })[0]; + } + this.version = "hybi-" + Hybi.VERSION; + }; + util.inherits(Hybi, Base); + Hybi.VERSION = "13"; + Hybi.mask = function(payload, mask, offset) { + if (!mask || mask.length === 0) return payload; + offset = offset || 0; + for (var i = 0, n = payload.length - offset; i < n; i++) { + payload[offset + i] = payload[offset + i] ^ mask[i % 4]; + } + return payload; + }; + Hybi.generateAccept = function(key2) { + var sha1 = crypto.createHash("sha1"); + sha1.update(key2 + Hybi.GUID); + return sha1.digest("base64"); + }; + Hybi.GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + var instance = { + FIN: 128, + MASK: 128, + RSV1: 64, + RSV2: 32, + RSV3: 16, + OPCODE: 15, + LENGTH: 127, + OPCODES: { + continuation: 0, + text: 1, + binary: 2, + close: 8, + ping: 9, + pong: 10 + }, + OPCODE_CODES: [0, 1, 2, 8, 9, 10], + MESSAGE_OPCODES: [0, 1, 2], + OPENING_OPCODES: [1, 2], + ERRORS: { + normal_closure: 1e3, + going_away: 1001, + protocol_error: 1002, + unacceptable: 1003, + encoding_error: 1007, + policy_violation: 1008, + too_large: 1009, + extension_error: 1010, + unexpected_condition: 1011 + }, + ERROR_CODES: [1e3, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011], + DEFAULT_ERROR_CODE: 1e3, + MIN_RESERVED_ERROR: 3e3, + MAX_RESERVED_ERROR: 4999, + // http://www.w3.org/International/questions/qa-forms-utf-8.en.php + UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/, + addExtension: function(extension) { + this._extensions.add(extension); + return true; + }, + parse: function(chunk) { + this._reader.put(chunk); + var buffer = true; + while (buffer) { + switch (this._stage) { + case 0: + buffer = this._reader.read(1); + if (buffer) this._parseOpcode(buffer[0]); + break; + case 1: + buffer = this._reader.read(1); + if (buffer) this._parseLength(buffer[0]); + break; + case 2: + buffer = this._reader.read(this._frame.lengthBytes); + if (buffer) this._parseExtendedLength(buffer); + break; + case 3: + buffer = this._reader.read(4); + if (buffer) { + this._stage = 4; + this._frame.maskingKey = buffer; + } + break; + case 4: + buffer = this._reader.read(this._frame.length); + if (buffer) { + this._stage = 0; + this._emitFrame(buffer); + } + break; + default: + buffer = null; + } + } + }, + text: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, "text"); + }, + binary: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, "binary"); + }, + ping: function(message, callback) { + if (this.readyState > 1) return false; + message = message || ""; + if (callback) this._pingCallbacks[message] = callback; + return this.frame(message, "ping"); + }, + pong: function(message) { + if (this.readyState > 1) return false; + message = message || ""; + return this.frame(message, "pong"); + }, + close: function(reason, code) { + reason = reason || ""; + code = code || this.ERRORS.normal_closure; + if (this.readyState <= 0) { + this.readyState = 3; + this.emit("close", new Base.CloseEvent(code, reason)); + return true; + } else if (this.readyState === 1) { + this.readyState = 2; + this._extensions.close(function() { + this.frame(reason, "close", code); + }, this); + return true; + } else { + return false; + } + }, + frame: function(buffer, type, code) { + if (this.readyState <= 0) return this._queue([buffer, type, code]); + if (this.readyState > 2) return false; + if (buffer instanceof Array) buffer = Buffer2.from(buffer); + if (typeof buffer === "number") buffer = buffer.toString(); + var message = new Message(), isText = typeof buffer === "string", payload, copy; + message.rsv1 = message.rsv2 = message.rsv3 = false; + message.opcode = this.OPCODES[type || (isText ? "text" : "binary")]; + payload = isText ? Buffer2.from(buffer, "utf8") : buffer; + if (code) { + copy = payload; + payload = Buffer2.allocUnsafe(2 + copy.length); + payload.writeUInt16BE(code, 0); + copy.copy(payload, 2); + } + message.data = payload; + var onMessageReady = function(message2) { + var frame = new Frame(); + frame.final = true; + frame.rsv1 = message2.rsv1; + frame.rsv2 = message2.rsv2; + frame.rsv3 = message2.rsv3; + frame.opcode = message2.opcode; + frame.masked = !!this._masking; + frame.length = message2.data.length; + frame.payload = message2.data; + if (frame.masked) frame.maskingKey = crypto.randomBytes(4); + this._sendFrame(frame); + }; + if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0) + this._extensions.processOutgoingMessage(message, function(error, message2) { + if (error) return this._fail("extension_error", error.message); + onMessageReady.call(this, message2); + }, this); + else + onMessageReady.call(this, message); + return true; + }, + _sendFrame: function(frame) { + var length = frame.length, header = length <= 125 ? 2 : length <= 65535 ? 4 : 10, offset = header + (frame.masked ? 4 : 0), buffer = Buffer2.allocUnsafe(offset + length), masked = frame.masked ? this.MASK : 0; + buffer[0] = (frame.final ? this.FIN : 0) | (frame.rsv1 ? this.RSV1 : 0) | (frame.rsv2 ? this.RSV2 : 0) | (frame.rsv3 ? this.RSV3 : 0) | frame.opcode; + if (length <= 125) { + buffer[1] = masked | length; + } else if (length <= 65535) { + buffer[1] = masked | 126; + buffer.writeUInt16BE(length, 2); + } else { + buffer[1] = masked | 127; + buffer.writeUInt32BE(Math.floor(length / 4294967296), 2); + buffer.writeUInt32BE(length % 4294967296, 6); + } + frame.payload.copy(buffer, offset); + if (frame.masked) { + frame.maskingKey.copy(buffer, header); + Hybi.mask(buffer, frame.maskingKey, offset); + } + this._write(buffer); + }, + _handshakeResponse: function() { + var secKey = this._request.headers["sec-websocket-key"], version = this._request.headers["sec-websocket-version"]; + if (version !== Hybi.VERSION) + throw new Error("Unsupported WebSocket version: " + version); + if (typeof secKey !== "string") + throw new Error("Missing handshake request header: Sec-WebSocket-Key"); + this._headers.set("Upgrade", "websocket"); + this._headers.set("Connection", "Upgrade"); + this._headers.set("Sec-WebSocket-Accept", Hybi.generateAccept(secKey)); + if (this.protocol) this._headers.set("Sec-WebSocket-Protocol", this.protocol); + var extensions = this._extensions.generateResponse(this._request.headers["sec-websocket-extensions"]); + if (extensions) this._headers.set("Sec-WebSocket-Extensions", extensions); + var start = "HTTP/1.1 101 Switching Protocols", headers = [start, this._headers.toString(), ""]; + return Buffer2.from(headers.join("\r\n"), "utf8"); + }, + _shutdown: function(code, reason, error) { + delete this._frame; + delete this._message; + this._stage = 5; + var sendCloseFrame = this.readyState === 1; + this.readyState = 2; + this._extensions.close(function() { + if (sendCloseFrame) this.frame(reason, "close", code); + this.readyState = 3; + if (error) this.emit("error", new Error(reason)); + this.emit("close", new Base.CloseEvent(code, reason)); + }, this); + }, + _fail: function(type, message) { + if (this.readyState > 1) return; + this._shutdown(this.ERRORS[type], message, true); + }, + _parseOpcode: function(octet) { + var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) { + return (octet & rsv) === rsv; + }); + var frame = this._frame = new Frame(); + frame.final = (octet & this.FIN) === this.FIN; + frame.rsv1 = rsvs[0]; + frame.rsv2 = rsvs[1]; + frame.rsv3 = rsvs[2]; + frame.opcode = octet & this.OPCODE; + this._stage = 1; + if (!this._extensions.validFrameRsv(frame)) + return this._fail( + "protocol_error", + "One or more reserved bits are on: reserved1 = " + (frame.rsv1 ? 1 : 0) + ", reserved2 = " + (frame.rsv2 ? 1 : 0) + ", reserved3 = " + (frame.rsv3 ? 1 : 0) + ); + if (this.OPCODE_CODES.indexOf(frame.opcode) < 0) + return this._fail("protocol_error", "Unrecognized frame opcode: " + frame.opcode); + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final) + return this._fail("protocol_error", "Received fragmented control frame: opcode = " + frame.opcode); + if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0) + return this._fail("protocol_error", "Received new data frame but previous continuous frame is unfinished"); + }, + _parseLength: function(octet) { + var frame = this._frame; + frame.masked = (octet & this.MASK) === this.MASK; + frame.length = octet & this.LENGTH; + if (frame.length >= 0 && frame.length <= 125) { + this._stage = frame.masked ? 3 : 4; + if (!this._checkFrameLength()) return; + } else { + this._stage = 2; + frame.lengthBytes = frame.length === 126 ? 2 : 8; + } + if (this._requireMasking && !frame.masked) + return this._fail("unacceptable", "Received unmasked frame but masking is required"); + }, + _parseExtendedLength: function(buffer) { + var frame = this._frame; + frame.length = this._readUInt(buffer); + this._stage = frame.masked ? 3 : 4; + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125) + return this._fail("protocol_error", "Received control frame having too long payload: " + frame.length); + if (!this._checkFrameLength()) return; + }, + _checkFrameLength: function() { + var length = this._message ? this._message.length : 0; + if (length + this._frame.length > this._maxLength) { + this._fail("too_large", "WebSocket frame length too large"); + return false; + } else { + return true; + } + }, + _emitFrame: function(buffer) { + var frame = this._frame, payload = frame.payload = Hybi.mask(buffer, frame.maskingKey), opcode = frame.opcode, message, code, reason, callbacks, callback; + delete this._frame; + if (opcode === this.OPCODES.continuation) { + if (!this._message) return this._fail("protocol_error", "Received unexpected continuation frame"); + this._message.pushFrame(frame); + } + if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) { + this._message = new Message(); + this._message.pushFrame(frame); + } + if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0) + return this._emitMessage(this._message); + if (opcode === this.OPCODES.close) { + code = payload.length >= 2 ? payload.readUInt16BE(0) : null; + reason = payload.length > 2 ? this._encode(payload.slice(2)) : null; + if (!(payload.length === 0) && !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) && this.ERROR_CODES.indexOf(code) < 0) + code = this.ERRORS.protocol_error; + if (payload.length > 125 || payload.length > 2 && !reason) + code = this.ERRORS.protocol_error; + this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || ""); + } + if (opcode === this.OPCODES.ping) { + this.frame(payload, "pong"); + this.emit("ping", new Base.PingEvent(payload.toString())); + } + if (opcode === this.OPCODES.pong) { + callbacks = this._pingCallbacks; + message = this._encode(payload); + callback = callbacks[message]; + delete callbacks[message]; + if (callback) callback(); + this.emit("pong", new Base.PongEvent(payload.toString())); + } + }, + _emitMessage: function(message) { + var message = this._message; + message.read(); + delete this._message; + this._extensions.processIncomingMessage(message, function(error, message2) { + if (error) return this._fail("extension_error", error.message); + var payload = message2.data; + if (message2.opcode === this.OPCODES.text) payload = this._encode(payload); + if (payload === null) + return this._fail("encoding_error", "Could not decode a text frame as UTF-8"); + else + this.emit("message", new Base.MessageEvent(payload)); + }, this); + }, + _encode: function(buffer) { + try { + var string = buffer.toString("binary", 0, buffer.length); + if (!this.UTF8_MATCH.test(string)) return null; + } catch (e) { + } + return buffer.toString("utf8", 0, buffer.length); + }, + _readUInt: function(buffer) { + if (buffer.length === 2) return buffer.readUInt16BE(0); + return buffer.readUInt32BE(0) * 4294967296 + buffer.readUInt32BE(4); + } + }; + for (var key in instance) + Hybi.prototype[key] = instance[key]; + module2.exports = Hybi; + }, + /***/ + 68(module2) { + var Frame = function() { + }; + var instance = { + final: false, + rsv1: false, + rsv2: false, + rsv3: false, + opcode: null, + masked: false, + maskingKey: null, + lengthBytes: 1, + length: 0, + payload: null + }; + for (var key in instance) + Frame.prototype[key] = instance[key]; + module2.exports = Frame; + }, + /***/ + 814(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer; + var Message = function() { + this.rsv1 = false; + this.rsv2 = false; + this.rsv3 = false; + this.opcode = null; + this.length = 0; + this._chunks = []; + }; + var instance = { + read: function() { + return this.data = this.data || Buffer2.concat(this._chunks, this.length); + }, + pushFrame: function(frame) { + this.rsv1 = this.rsv1 || frame.rsv1; + this.rsv2 = this.rsv2 || frame.rsv2; + this.rsv3 = this.rsv3 || frame.rsv3; + if (this.opcode === null) this.opcode = frame.opcode; + this._chunks.push(frame.payload); + this.length += frame.length; + } + }; + for (var key in instance) + Message.prototype[key] = instance[key]; + module2.exports = Message; + }, + /***/ + 662(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer, Stream = __webpack_require__2(203).Stream, url = __webpack_require__2(16), util = __webpack_require__2(23), Base = __webpack_require__2(369), Headers = __webpack_require__2(160), HttpParser = __webpack_require__2(565); + var PORTS = { "ws:": 80, "wss:": 443 }; + var Proxy = function(client, origin, options) { + this._client = client; + this._http = new HttpParser("response"); + this._origin = typeof client.url === "object" ? client.url : url.parse(client.url); + this._url = typeof origin === "object" ? origin : url.parse(origin); + this._options = options || {}; + this._state = 0; + this.readable = this.writable = true; + this._paused = false; + this._headers = new Headers(); + this._headers.set("Host", this._origin.host); + this._headers.set("Connection", "keep-alive"); + this._headers.set("Proxy-Connection", "keep-alive"); + var auth = this._url.auth && Buffer2.from(this._url.auth, "utf8").toString("base64"); + if (auth) this._headers.set("Proxy-Authorization", "Basic " + auth); + }; + util.inherits(Proxy, Stream); + var instance = { + setHeader: function(name, value) { + if (this._state !== 0) return false; + this._headers.set(name, value); + return true; + }, + start: function() { + if (this._state !== 0) return false; + this._state = 1; + var origin = this._origin, port = origin.port || PORTS[origin.protocol], start = "CONNECT " + origin.hostname + ":" + port + " HTTP/1.1"; + var headers = [start, this._headers.toString(), ""]; + this.emit("data", Buffer2.from(headers.join("\r\n"), "utf8")); + return true; + }, + pause: function() { + this._paused = true; + }, + resume: function() { + this._paused = false; + this.emit("drain"); + }, + write: function(chunk) { + if (!this.writable) return false; + this._http.parse(chunk); + if (!this._http.isComplete()) return !this._paused; + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + if (this.statusCode === 200) { + this.emit("connect", new Base.ConnectEvent()); + } else { + var message = "Can't establish a connection to the server at " + this._origin.href; + this.emit("error", new Error(message)); + } + this.end(); + return !this._paused; + }, + end: function(chunk) { + if (!this.writable) return; + if (chunk !== void 0) this.write(chunk); + this.readable = this.writable = false; + this.emit("close"); + this.emit("end"); + }, + destroy: function() { + this.end(); + } + }; + for (var key in instance) + Proxy.prototype[key] = instance[key]; + module2.exports = Proxy; + }, + /***/ + 983(module2, __unused_webpack_exports, __webpack_require__2) { + var util = __webpack_require__2(23), HttpParser = __webpack_require__2(565), Base = __webpack_require__2(369), Draft75 = __webpack_require__2(61), Draft76 = __webpack_require__2(476), Hybi = __webpack_require__2(518); + var Server = function(options) { + Base.call(this, null, null, options); + this._http = new HttpParser("request"); + }; + util.inherits(Server, Base); + var instance = { + EVENTS: ["open", "message", "error", "close", "ping", "pong"], + _bindEventListeners: function() { + this.messages.on("error", function() { + }); + this.on("error", function() { + }); + }, + parse: function(chunk) { + if (this._delegate) return this._delegate.parse(chunk); + this._http.parse(chunk); + if (!this._http.isComplete()) return; + this.method = this._http.method; + this.url = this._http.url; + this.headers = this._http.headers; + this.body = this._http.body; + var self2 = this; + this._delegate = Server.http(this, this._options); + this._delegate.messages = this.messages; + this._delegate.io = this.io; + this._open(); + this.EVENTS.forEach(function(event) { + this._delegate.on(event, function(e) { + self2.emit(event, e); + }); + }, this); + this.protocol = this._delegate.protocol; + this.version = this._delegate.version; + this.parse(this._http.body); + this.emit("connect", new Base.ConnectEvent()); + }, + _open: function() { + this.__queue.forEach(function(msg) { + this._delegate[msg[0]].apply(this._delegate, msg[1]); + }, this); + this.__queue = []; + } + }; + ["addExtension", "setHeader", "start", "frame", "text", "binary", "ping", "close"].forEach(function(method) { + instance[method] = function() { + if (this._delegate) { + return this._delegate[method].apply(this._delegate, arguments); + } else { + this.__queue.push([method, arguments]); + return true; + } + }; + }); + for (var key in instance) + Server.prototype[key] = instance[key]; + Server.isSecureRequest = function(request) { + if (request.connection && request.connection.authorized !== void 0) return true; + if (request.socket && request.socket.secure) return true; + var headers = request.headers; + if (!headers) return false; + if (headers["https"] === "on") return true; + if (headers["x-forwarded-ssl"] === "on") return true; + if (headers["x-forwarded-scheme"] === "https") return true; + if (headers["x-forwarded-proto"] === "https") return true; + return false; + }; + Server.determineUrl = function(request) { + var scheme = this.isSecureRequest(request) ? "wss:" : "ws:"; + return scheme + "//" + request.headers.host + request.url; + }; + Server.http = function(request, options) { + options = options || {}; + if (options.requireMasking === void 0) options.requireMasking = true; + var headers = request.headers, version = headers["sec-websocket-version"], key2 = headers["sec-websocket-key"], key1 = headers["sec-websocket-key1"], key22 = headers["sec-websocket-key2"], url = this.determineUrl(request); + if (version || key2) + return new Hybi(request, url, options); + else if (key1 || key22) + return new Draft76(request, url, options); + else + return new Draft75(request, url, options); + }; + module2.exports = Server; + }, + /***/ + 212(module2, __unused_webpack_exports, __webpack_require__2) { + var Buffer2 = __webpack_require__2(891).Buffer; + var StreamReader = function() { + this._queue = []; + this._queueSize = 0; + this._offset = 0; + }; + StreamReader.prototype.put = function(buffer) { + if (!buffer || buffer.length === 0) return; + if (!Buffer2.isBuffer(buffer)) buffer = Buffer2.from(buffer); + this._queue.push(buffer); + this._queueSize += buffer.length; + }; + StreamReader.prototype.read = function(length) { + if (length > this._queueSize) return null; + if (length === 0) return Buffer2.alloc(0); + this._queueSize -= length; + var queue = this._queue, remain = length, first = queue[0], buffers, buffer; + if (first.length >= length) { + if (first.length === length) { + return queue.shift(); + } else { + buffer = first.slice(0, length); + queue[0] = first.slice(length); + return buffer; + } + } + for (var i = 0, n = queue.length; i < n; i++) { + if (remain < queue[i].length) break; + remain -= queue[i].length; + } + buffers = queue.splice(0, i); + if (remain > 0 && queue.length > 0) { + buffers.push(queue[0].slice(0, remain)); + queue[0] = queue[0].slice(remain); + } + return Buffer2.concat(buffers, length); + }; + StreamReader.prototype.eachByte = function(callback, context) { + var buffer, n, index; + while (this._queue.length > 0) { + buffer = this._queue[0]; + n = buffer.length; + while (this._offset < n) { + index = this._offset; + this._offset += 1; + callback.call(context, buffer[index]); + } + this._offset = 0; + this._queue.shift(); + } + }; + module2.exports = StreamReader; + }, + /***/ + 565(module2, __unused_webpack_exports, __webpack_require__2) { + var NodeHTTPParser = __webpack_require__2(895).e, Buffer2 = __webpack_require__2(891).Buffer; + var TYPES = { + request: NodeHTTPParser.REQUEST || "request", + response: NodeHTTPParser.RESPONSE || "response" + }; + var HttpParser = function(type) { + this._type = type; + this._parser = new NodeHTTPParser(TYPES[type]); + this._complete = false; + this.headers = {}; + var current = null, self2 = this; + this._parser.onHeaderField = function(b2, start, length) { + current = b2.toString("utf8", start, start + length).toLowerCase(); + }; + this._parser.onHeaderValue = function(b2, start, length) { + var value = b2.toString("utf8", start, start + length); + if (self2.headers.hasOwnProperty(current)) + self2.headers[current] += ", " + value; + else + self2.headers[current] = value; + }; + this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] = function(majorVersion, minorVersion, headers, method, pathname, statusCode) { + var info = arguments[0]; + if (typeof info === "object") { + method = info.method; + pathname = info.url; + statusCode = info.statusCode; + headers = info.headers; + } + self2.method = typeof method === "number" ? HttpParser.METHODS[method] : method; + self2.statusCode = statusCode; + self2.url = pathname; + if (!headers) return; + for (var i = 0, n = headers.length, key, value; i < n; i += 2) { + key = headers[i].toLowerCase(); + value = headers[i + 1]; + if (self2.headers.hasOwnProperty(key)) + self2.headers[key] += ", " + value; + else + self2.headers[key] = value; + } + self2._complete = true; + }; + }; + HttpParser.METHODS = { + 0: "DELETE", + 1: "GET", + 2: "HEAD", + 3: "POST", + 4: "PUT", + 5: "CONNECT", + 6: "OPTIONS", + 7: "TRACE", + 8: "COPY", + 9: "LOCK", + 10: "MKCOL", + 11: "MOVE", + 12: "PROPFIND", + 13: "PROPPATCH", + 14: "SEARCH", + 15: "UNLOCK", + 16: "BIND", + 17: "REBIND", + 18: "UNBIND", + 19: "ACL", + 20: "REPORT", + 21: "MKACTIVITY", + 22: "CHECKOUT", + 23: "MERGE", + 24: "M-SEARCH", + 25: "NOTIFY", + 26: "SUBSCRIBE", + 27: "UNSUBSCRIBE", + 28: "PATCH", + 29: "PURGE", + 30: "MKCALENDAR", + 31: "LINK", + 32: "UNLINK" + }; + var VERSION = process.version ? process.version.match(/[0-9]+/g).map(function(n) { + return parseInt(n, 10); + }) : []; + if (VERSION[0] === 0 && VERSION[1] === 12) { + HttpParser.METHODS[16] = "REPORT"; + HttpParser.METHODS[17] = "MKACTIVITY"; + HttpParser.METHODS[18] = "CHECKOUT"; + HttpParser.METHODS[19] = "MERGE"; + HttpParser.METHODS[20] = "M-SEARCH"; + HttpParser.METHODS[21] = "NOTIFY"; + HttpParser.METHODS[22] = "SUBSCRIBE"; + HttpParser.METHODS[23] = "UNSUBSCRIBE"; + HttpParser.METHODS[24] = "PATCH"; + HttpParser.METHODS[25] = "PURGE"; + } + HttpParser.prototype.isComplete = function() { + return this._complete; + }; + HttpParser.prototype.parse = function(chunk) { + var consumed = this._parser.execute(chunk, 0, chunk.length); + if (typeof consumed !== "number") { + this.error = consumed; + this._complete = true; + return; + } + if (this._complete) + this.body = consumed < chunk.length ? chunk.slice(consumed) : Buffer2.alloc(0); + }; + module2.exports = HttpParser; + }, + /***/ + 578(__unused_webpack_module, exports$1, __webpack_require__2) { + var Stream = __webpack_require__2(203).Stream, util = __webpack_require__2(23); + var IO = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; + }; + util.inherits(IO, Stream); + IO.prototype.pause = function() { + this._paused = true; + this._driver.messages._paused = true; + }; + IO.prototype.resume = function() { + this._paused = false; + this.emit("drain"); + var messages = this._driver.messages; + messages._paused = false; + messages.emit("drain"); + }; + IO.prototype.write = function(chunk) { + if (!this.writable) return false; + this._driver.parse(chunk); + return !this._paused; + }; + IO.prototype.end = function(chunk) { + if (!this.writable) return; + if (chunk !== void 0) this.write(chunk); + this.writable = false; + var messages = this._driver.messages; + if (messages.readable) { + messages.readable = messages.writable = false; + messages.emit("end"); + } + }; + IO.prototype.destroy = function() { + this.end(); + }; + var Messages = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; + }; + util.inherits(Messages, Stream); + Messages.prototype.pause = function() { + this._driver.io._paused = true; + }; + Messages.prototype.resume = function() { + this._driver.io._paused = false; + this._driver.io.emit("drain"); + }; + Messages.prototype.write = function(message) { + if (!this.writable) return false; + if (typeof message === "string") this._driver.text(message); + else this._driver.binary(message); + return !this._paused; + }; + Messages.prototype.end = function(message) { + if (message !== void 0) this.write(message); + }; + Messages.prototype.destroy = function() { + }; + exports$1.IO = IO; + exports$1.Messages = Messages; + }, + /***/ + 80(module2) { + var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/, NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g, QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/, PARAM = new RegExp(TOKEN.source + "(?:=(?:" + TOKEN.source + "|" + QUOTED.source + "))?"), EXT = new RegExp(TOKEN.source + "(?: *; *" + PARAM.source + ")*", "g"), EXT_LIST = new RegExp("^" + EXT.source + "(?: *, *" + EXT.source + ")*$"), NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var Parser = { + parseHeader: function(header) { + var offers = new Offers(); + if (header === "" || header === void 0) return offers; + if (!EXT_LIST.test(header)) + throw new SyntaxError("Invalid Sec-WebSocket-Extensions header: " + header); + var values = header.match(EXT); + values.forEach(function(value) { + var params = value.match(new RegExp(PARAM.source, "g")), name = params.shift(), offer = {}; + params.forEach(function(param) { + var args = param.match(PARAM), key = args[1], data; + if (args[2] !== void 0) { + data = args[2]; + } else if (args[3] !== void 0) { + data = args[3].replace(/\\/g, ""); + } else { + data = true; + } + if (NUMBER.test(data)) data = parseFloat(data); + if (hasOwnProperty.call(offer, key)) { + offer[key] = [].concat(offer[key]); + offer[key].push(data); + } else { + offer[key] = data; + } + }, this); + offers.push(name, offer); + }, this); + return offers; + }, + serializeParams: function(name, params) { + var values = []; + var print = function(key2, value) { + if (value instanceof Array) { + value.forEach(function(v2) { + print(key2, v2); + }); + } else if (value === true) { + values.push(key2); + } else if (typeof value === "number") { + values.push(key2 + "=" + value); + } else if (NOTOKEN.test(value)) { + values.push(key2 + '="' + value.replace(/"/g, '\\"') + '"'); + } else { + values.push(key2 + "=" + value); + } + }; + for (var key in params) print(key, params[key]); + return [name].concat(values).join("; "); + } + }; + var Offers = function() { + this._byName = {}; + this._inOrder = []; + }; + Offers.prototype.push = function(name, params) { + if (!hasOwnProperty.call(this._byName, name)) + this._byName[name] = []; + this._byName[name].push(params); + this._inOrder.push({ name, params }); + }; + Offers.prototype.eachOffer = function(callback, context) { + var list = this._inOrder; + for (var i = 0, n = list.length; i < n; i++) + callback.call(context, list[i].name, list[i].params); + }; + Offers.prototype.byName = function(name) { + return this._byName[name] || []; + }; + Offers.prototype.toArray = function() { + return this._inOrder.slice(); + }; + module2.exports = Parser; + }, + /***/ + 152(module2, __unused_webpack_exports, __webpack_require__2) { + var Functor = __webpack_require__2(277), Pledge = __webpack_require__2(521); + var Cell = function(tuple) { + this._ext = tuple[0]; + this._session = tuple[1]; + this._functors = { + incoming: new Functor(this._session, "processIncomingMessage"), + outgoing: new Functor(this._session, "processOutgoingMessage") + }; + }; + Cell.prototype.pending = function(direction) { + var functor = this._functors[direction]; + if (!functor._stopped) functor.pending += 1; + }; + Cell.prototype.incoming = function(error, message, callback, context) { + this._exec("incoming", error, message, callback, context); + }; + Cell.prototype.outgoing = function(error, message, callback, context) { + this._exec("outgoing", error, message, callback, context); + }; + Cell.prototype.close = function() { + this._closed = this._closed || new Pledge(); + this._doClose(); + return this._closed; + }; + Cell.prototype._exec = function(direction, error, message, callback, context) { + this._functors[direction].call(error, message, function(err, msg) { + if (err) err.message = this._ext.name + ": " + err.message; + callback.call(context, err, msg); + this._doClose(); + }, this); + }; + Cell.prototype._doClose = function() { + var fin = this._functors.incoming, fout = this._functors.outgoing; + if (!this._closed || fin.pending + fout.pending !== 0) return; + if (this._session) this._session.close(); + this._session = null; + this._closed.done(); + }; + module2.exports = Cell; + }, + /***/ + 277(module2, __unused_webpack_exports, __webpack_require__2) { + var RingBuffer = __webpack_require__2(411); + var Functor = function(session, method) { + this._session = session; + this._method = method; + this._queue = new RingBuffer(Functor.QUEUE_SIZE); + this._stopped = false; + this.pending = 0; + }; + Functor.QUEUE_SIZE = 8; + Functor.prototype.call = function(error, message, callback, context) { + if (this._stopped) return; + var record = { error, message, callback, context, done: false }, called = false, self2 = this; + this._queue.push(record); + if (record.error) { + record.done = true; + this._stop(); + return this._flushQueue(); + } + var handler = function(err, msg) { + if (!(called ^ (called = true))) return; + if (err) { + self2._stop(); + record.error = err; + record.message = null; + } else { + record.message = msg; + } + record.done = true; + self2._flushQueue(); + }; + try { + this._session[this._method](message, handler); + } catch (err) { + handler(err); + } + }; + Functor.prototype._stop = function() { + this.pending = this._queue.length; + this._stopped = true; + }; + Functor.prototype._flushQueue = function() { + var queue = this._queue, record; + while (queue.length > 0 && queue.peek().done) { + record = queue.shift(); + if (record.error) { + this.pending = 0; + queue.clear(); + } else { + this.pending -= 1; + } + record.callback.call(record.context, record.error, record.message); + } + }; + module2.exports = Functor; + }, + /***/ + 862(module2, __unused_webpack_exports, __webpack_require__2) { + var Cell = __webpack_require__2(152), Pledge = __webpack_require__2(521); + var Pipeline = function(sessions) { + this._cells = sessions.map(function(session) { + return new Cell(session); + }); + this._stopped = { incoming: false, outgoing: false }; + }; + Pipeline.prototype.processIncomingMessage = function(message, callback, context) { + if (this._stopped.incoming) return; + this._loop("incoming", this._cells.length - 1, -1, -1, message, callback, context); + }; + Pipeline.prototype.processOutgoingMessage = function(message, callback, context) { + if (this._stopped.outgoing) return; + this._loop("outgoing", 0, this._cells.length, 1, message, callback, context); + }; + Pipeline.prototype.close = function(callback, context) { + this._stopped = { incoming: true, outgoing: true }; + var closed = this._cells.map(function(a) { + return a.close(); + }); + if (callback) + Pledge.all(closed).then(function() { + callback.call(context); + }); + }; + Pipeline.prototype._loop = function(direction, start, end, step, message, callback, context) { + var cells = this._cells, n = cells.length, self2 = this; + while (n--) cells[n].pending(direction); + var pipe = function(index, error, msg) { + if (index === end) return callback.call(context, error, msg); + cells[index][direction](error, msg, function(err, m2) { + if (err) self2._stopped[direction] = true; + pipe(index + step, err, m2); + }); + }; + pipe(start, null, message); + }; + module2.exports = Pipeline; + }, + /***/ + 521(module2, __unused_webpack_exports, __webpack_require__2) { + var RingBuffer = __webpack_require__2(411); + var Pledge = function() { + this._complete = false; + this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE); + }; + Pledge.QUEUE_SIZE = 4; + Pledge.all = function(list) { + var pledge = new Pledge(), pending = list.length, n = pending; + if (pending === 0) pledge.done(); + while (n--) list[n].then(function() { + pending -= 1; + if (pending === 0) pledge.done(); + }); + return pledge; + }; + Pledge.prototype.then = function(callback) { + if (this._complete) callback(); + else this._callbacks.push(callback); + }; + Pledge.prototype.done = function() { + this._complete = true; + var callbacks = this._callbacks, callback; + while (callback = callbacks.shift()) callback(); + }; + module2.exports = Pledge; + }, + /***/ + 411(module2) { + var RingBuffer = function(bufferSize) { + this._bufferSize = bufferSize; + this.clear(); + }; + RingBuffer.prototype.clear = function() { + this._buffer = new Array(this._bufferSize); + this._ringOffset = 0; + this._ringSize = this._bufferSize; + this._head = 0; + this._tail = 0; + this.length = 0; + }; + RingBuffer.prototype.push = function(value) { + var expandBuffer = false, expandRing = false; + if (this._ringSize < this._bufferSize) { + expandBuffer = this._tail === 0; + } else if (this._ringOffset === this._ringSize) { + expandBuffer = true; + expandRing = this._tail === 0; + } + if (expandBuffer) { + this._tail = this._bufferSize; + this._buffer = this._buffer.concat(new Array(this._bufferSize)); + this._bufferSize = this._buffer.length; + if (expandRing) + this._ringSize = this._bufferSize; + } + this._buffer[this._tail] = value; + this.length += 1; + if (this._tail < this._ringSize) this._ringOffset += 1; + this._tail = (this._tail + 1) % this._bufferSize; + }; + RingBuffer.prototype.peek = function() { + if (this.length === 0) return void 0; + return this._buffer[this._head]; + }; + RingBuffer.prototype.shift = function() { + if (this.length === 0) return void 0; + var value = this._buffer[this._head]; + this._buffer[this._head] = void 0; + this.length -= 1; + this._ringOffset -= 1; + if (this._ringOffset === 0 && this.length > 0) { + this._head = this._ringSize; + this._ringOffset = this.length; + this._ringSize = this._bufferSize; + } else { + this._head = (this._head + 1) % this._ringSize; + } + return value; + }; + module2.exports = RingBuffer; + }, + /***/ + 769(module2, __unused_webpack_exports, __webpack_require__2) { + var Parser = __webpack_require__2(80), Pipeline = __webpack_require__2(862); + var Extensions = function() { + this._rsv1 = this._rsv2 = this._rsv3 = null; + this._byName = {}; + this._inOrder = []; + this._sessions = []; + this._index = {}; + }; + Extensions.MESSAGE_OPCODES = [1, 2]; + var instance = { + add: function(ext) { + if (typeof ext.name !== "string") throw new TypeError("extension.name must be a string"); + if (ext.type !== "permessage") throw new TypeError('extension.type must be "permessage"'); + if (typeof ext.rsv1 !== "boolean") throw new TypeError("extension.rsv1 must be true or false"); + if (typeof ext.rsv2 !== "boolean") throw new TypeError("extension.rsv2 must be true or false"); + if (typeof ext.rsv3 !== "boolean") throw new TypeError("extension.rsv3 must be true or false"); + if (this._byName.hasOwnProperty(ext.name)) + throw new TypeError('An extension with name "' + ext.name + '" is already registered'); + this._byName[ext.name] = ext; + this._inOrder.push(ext); + }, + generateOffer: function() { + var sessions = [], offer = [], index = {}; + this._inOrder.forEach(function(ext) { + var session = ext.createClientSession(); + if (!session) return; + var record = [ext, session]; + sessions.push(record); + index[ext.name] = record; + var offers = session.generateOffer(); + offers = offers ? [].concat(offers) : []; + offers.forEach(function(off) { + offer.push(Parser.serializeParams(ext.name, off)); + }, this); + }, this); + this._sessions = sessions; + this._index = index; + return offer.length > 0 ? offer.join(", ") : null; + }, + activate: function(header) { + var responses = Parser.parseHeader(header), sessions = []; + responses.eachOffer(function(name, params) { + var record = this._index[name]; + if (!record) + throw new Error('Server sent an extension response for unknown extension "' + name + '"'); + var ext = record[0], session = record[1], reserved = this._reserved(ext); + if (reserved) + throw new Error("Server sent two extension responses that use the RSV" + reserved[0] + ' bit: "' + reserved[1] + '" and "' + ext.name + '"'); + if (session.activate(params) !== true) + throw new Error("Server sent unacceptable extension parameters: " + Parser.serializeParams(name, params)); + this._reserve(ext); + sessions.push(record); + }, this); + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + }, + generateResponse: function(header) { + var sessions = [], response = [], offers = Parser.parseHeader(header); + this._inOrder.forEach(function(ext) { + var offer = offers.byName(ext.name); + if (offer.length === 0 || this._reserved(ext)) return; + var session = ext.createServerSession(offer); + if (!session) return; + this._reserve(ext); + sessions.push([ext, session]); + response.push(Parser.serializeParams(ext.name, session.generateResponse())); + }, this); + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + return response.length > 0 ? response.join(", ") : null; + }, + validFrameRsv: function(frame) { + var allowed = { rsv1: false, rsv2: false, rsv3: false }, ext; + if (Extensions.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) { + for (var i = 0, n = this._sessions.length; i < n; i++) { + ext = this._sessions[i][0]; + allowed.rsv1 = allowed.rsv1 || ext.rsv1; + allowed.rsv2 = allowed.rsv2 || ext.rsv2; + allowed.rsv3 = allowed.rsv3 || ext.rsv3; + } + } + return (allowed.rsv1 || !frame.rsv1) && (allowed.rsv2 || !frame.rsv2) && (allowed.rsv3 || !frame.rsv3); + }, + processIncomingMessage: function(message, callback, context) { + this._pipeline.processIncomingMessage(message, callback, context); + }, + processOutgoingMessage: function(message, callback, context) { + this._pipeline.processOutgoingMessage(message, callback, context); + }, + close: function(callback, context) { + if (!this._pipeline) return callback.call(context); + this._pipeline.close(callback, context); + }, + _reserve: function(ext) { + this._rsv1 = this._rsv1 || ext.rsv1 && ext.name; + this._rsv2 = this._rsv2 || ext.rsv2 && ext.name; + this._rsv3 = this._rsv3 || ext.rsv3 && ext.name; + }, + _reserved: function(ext) { + if (this._rsv1 && ext.rsv1) return [1, this._rsv1]; + if (this._rsv2 && ext.rsv2) return [2, this._rsv2]; + if (this._rsv3 && ext.rsv3) return [3, this._rsv3]; + return false; + } + }; + for (var key in instance) + Extensions.prototype[key] = instance[key]; + module2.exports = Extensions; + }, + /***/ + 407(__unused_webpack_module, exports$1, __webpack_require__2) { + var Url = __webpack_require__2(16); + var spawn = __webpack_require__2(317).spawn; + var fs = __webpack_require__2(896); + exports$1.z = function() { + var self2 = this; + var http = __webpack_require__2(611); + var https = __webpack_require__2(692); + var request; + var response; + var settings = {}; + var disableHeaderCheck = false; + var defaultHeaders = { + "User-Agent": "node-XMLHttpRequest", + "Accept": "*/*" + }; + var headers = {}; + var headersCase = {}; + var forbiddenRequestHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "content-transfer-encoding", + "cookie", + "cookie2", + "date", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" + ]; + var forbiddenRequestMethods = [ + "TRACE", + "TRACK", + "CONNECT" + ]; + var sendFlag = false; + var errorFlag = false; + var listeners = {}; + this.UNSENT = 0; + this.OPENED = 1; + this.HEADERS_RECEIVED = 2; + this.LOADING = 3; + this.DONE = 4; + this.readyState = this.UNSENT; + this.onreadystatechange = null; + this.responseText = ""; + this.responseXML = ""; + this.status = null; + this.statusText = null; + this.withCredentials = false; + var isAllowedHttpHeader = function(header) { + return disableHeaderCheck || header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1; + }; + var isAllowedHttpMethod = function(method) { + return method && forbiddenRequestMethods.indexOf(method) === -1; + }; + this.open = function(method, url, async, user, password) { + this.abort(); + errorFlag = false; + if (!isAllowedHttpMethod(method)) { + throw new Error("SecurityError: Request method not allowed"); + } + settings = { + "method": method, + "url": url.toString(), + "async": typeof async !== "boolean" ? true : async, + "user": user || null, + "password": password || null + }; + setState(this.OPENED); + }; + this.setDisableHeaderCheck = function(state) { + disableHeaderCheck = state; + }; + this.setRequestHeader = function(header, value) { + if (this.readyState !== this.OPENED) { + throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN"); + } + if (!isAllowedHttpHeader(header)) { + console.warn('Refused to set unsafe header "' + header + '"'); + return; + } + if (sendFlag) { + throw new Error("INVALID_STATE_ERR: send flag is true"); + } + header = headersCase[header.toLowerCase()] || header; + headersCase[header.toLowerCase()] = header; + headers[header] = headers[header] ? headers[header] + ", " + value : value; + }; + this.getResponseHeader = function(header) { + if (typeof header === "string" && this.readyState > this.OPENED && response && response.headers && response.headers[header.toLowerCase()] && !errorFlag) { + return response.headers[header.toLowerCase()]; + } + return null; + }; + this.getAllResponseHeaders = function() { + if (this.readyState < this.HEADERS_RECEIVED || errorFlag) { + return ""; + } + var result = ""; + for (var i in response.headers) { + if (i !== "set-cookie" && i !== "set-cookie2") { + result += i + ": " + response.headers[i] + "\r\n"; + } + } + return result.substr(0, result.length - 2); + }; + this.getRequestHeader = function(name) { + if (typeof name === "string" && headersCase[name.toLowerCase()]) { + return headers[headersCase[name.toLowerCase()]]; + } + return ""; + }; + this.send = function(data) { + if (this.readyState !== this.OPENED) { + throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called"); + } + if (sendFlag) { + throw new Error("INVALID_STATE_ERR: send has already been called"); + } + var ssl = false, local = false; + var url = Url.parse(settings.url); + var host; + switch (url.protocol) { + case "https:": + ssl = true; + // SSL & non-SSL both need host, no break here. + case "http:": + host = url.hostname; + break; + case "file:": + local = true; + break; + case void 0: + case null: + case "": + host = "localhost"; + break; + default: + throw new Error("Protocol not supported."); + } + if (local) { + if (settings.method !== "GET") { + throw new Error("XMLHttpRequest: Only GET method is supported"); + } + if (settings.async) { + fs.readFile(url.pathname, "utf8", function(error, data2) { + if (error) { + self2.handleError(error); + } else { + self2.status = 200; + self2.responseText = data2; + setState(self2.DONE); + } + }); + } else { + try { + this.responseText = fs.readFileSync(url.pathname, "utf8"); + this.status = 200; + setState(self2.DONE); + } catch (e) { + this.handleError(e); + } + } + return; + } + var port = url.port || (ssl ? 443 : 80); + var uri = url.pathname + (url.search ? url.search : ""); + for (var name in defaultHeaders) { + if (!headersCase[name.toLowerCase()]) { + headers[name] = defaultHeaders[name]; + } + } + headers.Host = host; + if (!(ssl && port === 443 || port === 80)) { + headers.Host += ":" + url.port; + } + if (settings.user) { + if (typeof settings.password === "undefined") { + settings.password = ""; + } + var authBuf = new Buffer(settings.user + ":" + settings.password); + headers.Authorization = "Basic " + authBuf.toString("base64"); + } + if (settings.method === "GET" || settings.method === "HEAD") { + data = null; + } else if (data) { + headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data); + if (!headers["Content-Type"]) { + headers["Content-Type"] = "text/plain;charset=UTF-8"; + } + } else if (settings.method === "POST") { + headers["Content-Length"] = 0; + } + var options = { + host, + port, + path: uri, + method: settings.method, + headers, + agent: false, + withCredentials: self2.withCredentials + }; + errorFlag = false; + if (settings.async) { + var doRequest = ssl ? https.request : http.request; + sendFlag = true; + self2.dispatchEvent("readystatechange"); + var responseHandler = function responseHandler2(resp2) { + response = resp2; + if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) { + settings.url = response.headers.location; + var url2 = Url.parse(settings.url); + host = url2.hostname; + var newOptions = { + hostname: url2.hostname, + port: url2.port, + path: url2.path, + method: response.statusCode === 303 ? "GET" : settings.method, + headers, + withCredentials: self2.withCredentials + }; + request = doRequest(newOptions, responseHandler2).on("error", errorHandler); + request.end(); + return; + } + response.setEncoding("utf8"); + setState(self2.HEADERS_RECEIVED); + self2.status = response.statusCode; + response.on("data", function(chunk) { + if (chunk) { + self2.responseText += chunk; + } + if (sendFlag) { + setState(self2.LOADING); + } + }); + response.on("end", function() { + if (sendFlag) { + setState(self2.DONE); + sendFlag = false; + } + }); + response.on("error", function(error) { + self2.handleError(error); + }); + }; + var errorHandler = function errorHandler2(error) { + self2.handleError(error); + }; + request = doRequest(options, responseHandler).on("error", errorHandler); + if (data) { + request.write(data); + } + request.end(); + self2.dispatchEvent("loadstart"); + } else { + var contentFile = ".node-xmlhttprequest-content-" + process.pid; + var syncFile = ".node-xmlhttprequest-sync-" + process.pid; + fs.writeFileSync(syncFile, "", "utf8"); + var execString = "var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http" + (ssl ? "s" : "") + ".request;var options = " + JSON.stringify(options) + ";var responseText = '';var req = doRequest(options, function(response) {response.setEncoding('utf8');response.on('data', function(chunk) { responseText += chunk;});response.on('end', function() {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');fs.unlinkSync('" + syncFile + "');});response.on('error', function(error) {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');fs.unlinkSync('" + syncFile + "');});}).on('error', function(error) {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');fs.unlinkSync('" + syncFile + "');});" + (data ? "req.write('" + JSON.stringify(data).slice(1, -1).replace(/'/g, "\\'") + "');" : "") + "req.end();"; + var syncProc = spawn(process.argv[0], ["-e", execString]); + while (fs.existsSync(syncFile)) { + } + var resp = JSON.parse(fs.readFileSync(contentFile, "utf8")); + syncProc.stdin.end(); + fs.unlinkSync(contentFile); + if (resp.err) { + self2.handleError(resp.err); + } else { + response = resp.data; + self2.status = resp.data.statusCode; + self2.responseText = resp.data.text; + setState(self2.DONE); + } + } + }; + this.handleError = function(error) { + this.status = 0; + this.statusText = error; + this.responseText = error.stack; + errorFlag = true; + setState(this.DONE); + this.dispatchEvent("error"); + }; + this.abort = function() { + if (request) { + request.abort(); + request = null; + } + headers = defaultHeaders; + this.status = 0; + this.responseText = ""; + this.responseXML = ""; + errorFlag = true; + if (this.readyState !== this.UNSENT && (this.readyState !== this.OPENED || sendFlag) && this.readyState !== this.DONE) { + sendFlag = false; + setState(this.DONE); + } + this.readyState = this.UNSENT; + this.dispatchEvent("abort"); + }; + this.addEventListener = function(event, callback) { + if (!(event in listeners)) { + listeners[event] = []; + } + listeners[event].push(callback); + }; + this.removeEventListener = function(event, callback) { + if (event in listeners) { + listeners[event] = listeners[event].filter(function(ev) { + return ev !== callback; + }); + } + }; + this.dispatchEvent = function(event) { + if (typeof self2["on" + event] === "function") { + self2["on" + event](); + } + if (event in listeners) { + for (var i = 0, len = listeners[event].length; i < len; i++) { + listeners[event][i].call(self2); + } + } + }; + var setState = function(state) { + if (state == self2.LOADING || self2.readyState !== state) { + self2.readyState = state; + if (settings.async || self2.readyState < self2.OPENED || self2.readyState === self2.DONE) { + self2.dispatchEvent("readystatechange"); + } + if (self2.readyState === self2.DONE && !errorFlag) { + self2.dispatchEvent("load"); + self2.dispatchEvent("loadend"); + } + } + }; + }; + }, + /***/ + 42(module2, __unused_webpack_exports, __webpack_require__2) { + module2.exports = __webpack_require__2(368)["default"]; + }, + /***/ + 368(__unused_webpack_module, __webpack_exports__2, __webpack_require__2) { + __webpack_require__2.d(__webpack_exports__2, { + "default": () => ( + /* binding */ + PusherWithEncryption + ) + }); + function encode(s) { + return btoa(utob(s)); + } + var fromCharCode = String.fromCharCode; + var b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var cb_utob = function(c2) { + var cc = c2.charCodeAt(0); + return cc < 128 ? c2 : cc < 2048 ? fromCharCode(192 | cc >>> 6) + fromCharCode(128 | cc & 63) : fromCharCode(224 | cc >>> 12 & 15) + fromCharCode(128 | cc >>> 6 & 63) + fromCharCode(128 | cc & 63); + }; + var utob = function(u2) { + return u2.replace(/[^\x00-\x7F]/g, cb_utob); + }; + var cb_encode = function(ccc) { + var padlen = [0, 2, 1][ccc.length % 3]; + var ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0); + var chars = [ + b64chars.charAt(ord >>> 18), + b64chars.charAt(ord >>> 12 & 63), + padlen >= 2 ? "=" : b64chars.charAt(ord >>> 6 & 63), + padlen >= 1 ? "=" : b64chars.charAt(ord & 63) + ]; + return chars.join(""); + }; + var btoa = commonjsGlobal.btoa || function(b2) { + return b2.replace(/[\s\S]{1,3}/g, cb_encode); + }; + class Timer { + constructor(set, clear, delay, callback) { + this.clear = clear; + this.timer = set(() => { + if (this.timer) { + this.timer = callback(this.timer); + } + }, delay); + } + isRunning() { + return this.timer !== null; + } + ensureAborted() { + if (this.timer) { + this.clear(this.timer); + this.timer = null; + } + } + } + const abstract_timer = Timer; + function timers_clearTimeout(timer) { + commonjsGlobal.clearTimeout(timer); + } + function timers_clearInterval(timer) { + commonjsGlobal.clearInterval(timer); + } + class OneOffTimer extends abstract_timer { + constructor(delay, callback) { + super(setTimeout, timers_clearTimeout, delay, function(timer) { + callback(); + return null; + }); + } + } + class PeriodicTimer extends abstract_timer { + constructor(delay, callback) { + super(setInterval, timers_clearInterval, delay, function(timer) { + callback(); + return timer; + }); + } + } + var Util = { + now() { + if (Date.now) { + return Date.now(); + } else { + return (/* @__PURE__ */ new Date()).valueOf(); + } + }, + defer(callback) { + return new OneOffTimer(0, callback); + }, + method(name, ...args) { + var boundArguments = Array.prototype.slice.call(arguments, 1); + return function(object) { + return object[name].apply(object, boundArguments.concat(arguments)); + }; + } + }; + const util = Util; + function extend(target, ...sources) { + for (var i = 0; i < sources.length; i++) { + var extensions = sources[i]; + for (var property in extensions) { + if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) { + target[property] = extend(target[property] || {}, extensions[property]); + } else { + target[property] = extensions[property]; + } + } + } + return target; + } + function stringify() { + var m2 = ["Pusher"]; + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] === "string") { + m2.push(arguments[i]); + } else { + m2.push(safeJSONStringify(arguments[i])); + } + } + return m2.join(" : "); + } + function arrayIndexOf(array, item) { + var nativeIndexOf = Array.prototype.indexOf; + if (array === null) { + return -1; + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) { + return array.indexOf(item); + } + for (var i = 0, l2 = array.length; i < l2; i++) { + if (array[i] === item) { + return i; + } + } + return -1; + } + function objectApply(object, f2) { + for (var key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + f2(object[key], key, object); + } + } + } + function keys(object) { + var keys2 = []; + objectApply(object, function(_2, key) { + keys2.push(key); + }); + return keys2; + } + function values(object) { + var values2 = []; + objectApply(object, function(value) { + values2.push(value); + }); + return values2; + } + function apply(array, f2, context) { + for (var i = 0; i < array.length; i++) { + f2.call(context || commonjsGlobal, array[i], i, array); + } + } + function map(array, f2) { + var result = []; + for (var i = 0; i < array.length; i++) { + result.push(f2(array[i], i, array, result)); + } + return result; + } + function mapObject(object, f2) { + var result = {}; + objectApply(object, function(value, key) { + result[key] = f2(value); + }); + return result; + } + function filter(array, test) { + test = test || function(value) { + return !!value; + }; + var result = []; + for (var i = 0; i < array.length; i++) { + if (test(array[i], i, array, result)) { + result.push(array[i]); + } + } + return result; + } + function filterObject(object, test) { + var result = {}; + objectApply(object, function(value, key) { + if (test && test(value, key, object, result) || Boolean(value)) { + result[key] = value; + } + }); + return result; + } + function flatten(object) { + var result = []; + objectApply(object, function(value, key) { + result.push([key, value]); + }); + return result; + } + function any(array, test) { + for (var i = 0; i < array.length; i++) { + if (test(array[i], i, array)) { + return true; + } + } + return false; + } + function collections_all(array, test) { + for (var i = 0; i < array.length; i++) { + if (!test(array[i], i, array)) { + return false; + } + } + return true; + } + function encodeParamsObject(data) { + return mapObject(data, function(value) { + if (typeof value === "object") { + value = safeJSONStringify(value); + } + return encodeURIComponent(encode(value.toString())); + }); + } + function buildQueryString(data) { + var params = filterObject(data, function(value) { + return value !== void 0; + }); + var query = map(flatten(encodeParamsObject(params)), util.method("join", "=")).join("&"); + return query; + } + function decycleObject(object) { + var objects = [], paths = []; + return (function derez(value, path) { + var i, name, nu; + switch (typeof value) { + case "object": + if (!value) { + return null; + } + for (i = 0; i < objects.length; i += 1) { + if (objects[i] === value) { + return { $ref: paths[i] }; + } + } + objects.push(value); + paths.push(path); + if (Object.prototype.toString.apply(value) === "[object Array]") { + nu = []; + for (i = 0; i < value.length; i += 1) { + nu[i] = derez(value[i], path + "[" + i + "]"); + } + } else { + nu = {}; + for (name in value) { + if (Object.prototype.hasOwnProperty.call(value, name)) { + nu[name] = derez(value[name], path + "[" + JSON.stringify(name) + "]"); + } + } + } + return nu; + case "number": + case "string": + case "boolean": + return value; + } + })(object, "$"); + } + function safeJSONStringify(source) { + try { + return JSON.stringify(source); + } catch (e) { + return JSON.stringify(decycleObject(source)); + } + } + var Defaults = { + VERSION: "8.5.0", + PROTOCOL: 7, + wsPort: 80, + wssPort: 443, + wsPath: "", + httpHost: "sockjs.pusher.com", + httpPort: 80, + httpsPort: 443, + httpPath: "/pusher", + stats_host: "stats.pusher.com", + authEndpoint: "/pusher/auth", + authTransport: "ajax", + activityTimeout: 12e4, + pongTimeout: 3e4, + unavailableTimeout: 1e4, + userAuthentication: { + endpoint: "/pusher/user-auth", + transport: "ajax" + }, + channelAuthorization: { + endpoint: "/pusher/auth", + transport: "ajax" + } + }; + const defaults = Defaults; + function getGenericURL(baseScheme, params, path) { + var scheme = baseScheme + (params.useTLS ? "s" : ""); + var host = params.useTLS ? params.hostTLS : params.hostNonTLS; + return scheme + "://" + host + path; + } + function getGenericPath(key, queryString) { + var path = "/app/" + key; + var query = "?protocol=" + defaults.PROTOCOL + "&client=js&version=" + defaults.VERSION + (queryString ? "&" + queryString : ""); + return path + query; + } + var ws = { + getInitial: function(key, params) { + var path = (params.httpPath || "") + getGenericPath(key, "flash=false"); + return getGenericURL("ws", params, path); + } + }; + var http = { + getInitial: function(key, params) { + var path = (params.httpPath || "/pusher") + getGenericPath(key); + return getGenericURL("http", params, path); + } + }; + class CallbackRegistry { + constructor() { + this._callbacks = {}; + } + get(name) { + return this._callbacks[prefix(name)]; + } + add(name, callback, context) { + var prefixedEventName = prefix(name); + this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || []; + this._callbacks[prefixedEventName].push({ + fn: callback, + context + }); + } + remove(name, callback, context) { + if (!name && !callback && !context) { + this._callbacks = {}; + return; + } + var names = name ? [prefix(name)] : keys(this._callbacks); + if (callback || context) { + this.removeCallback(names, callback, context); + } else { + this.removeAllCallbacks(names); + } + } + removeCallback(names, callback, context) { + apply(names, function(name) { + this._callbacks[name] = filter(this._callbacks[name] || [], function(binding) { + return callback && callback !== binding.fn || context && context !== binding.context; + }); + if (this._callbacks[name].length === 0) { + delete this._callbacks[name]; + } + }, this); + } + removeAllCallbacks(names) { + apply(names, function(name) { + delete this._callbacks[name]; + }, this); + } + } + function prefix(name) { + return "_" + name; + } + class Dispatcher { + constructor(failThrough) { + this.callbacks = new CallbackRegistry(); + this.global_callbacks = []; + this.failThrough = failThrough; + } + bind(eventName, callback, context) { + this.callbacks.add(eventName, callback, context); + return this; + } + bind_global(callback) { + this.global_callbacks.push(callback); + return this; + } + unbind(eventName, callback, context) { + this.callbacks.remove(eventName, callback, context); + return this; + } + unbind_global(callback) { + if (!callback) { + this.global_callbacks = []; + return this; + } + this.global_callbacks = filter(this.global_callbacks || [], (c2) => c2 !== callback); + return this; + } + unbind_all() { + this.unbind(); + this.unbind_global(); + return this; + } + emit(eventName, data, metadata) { + for (var i = 0; i < this.global_callbacks.length; i++) { + this.global_callbacks[i](eventName, data); + } + var callbacks = this.callbacks.get(eventName); + var args = []; + if (metadata) { + args.push(data, metadata); + } else if (data) { + args.push(data); + } + if (callbacks && callbacks.length > 0) { + for (var i = 0; i < callbacks.length; i++) { + callbacks[i].fn.apply(callbacks[i].context || commonjsGlobal, args); + } + } else if (this.failThrough) { + this.failThrough(eventName, data); + } + return this; + } + } + class Logger { + constructor() { + this.globalLog = (message) => { + if (commonjsGlobal.console && commonjsGlobal.console.log) { + commonjsGlobal.console.log(message); + } + }; + } + debug(...args) { + this.log(this.globalLog, args); + } + warn(...args) { + this.log(this.globalLogWarn, args); + } + error(...args) { + this.log(this.globalLogError, args); + } + globalLogWarn(message) { + if (commonjsGlobal.console && commonjsGlobal.console.warn) { + commonjsGlobal.console.warn(message); + } else { + this.globalLog(message); + } + } + globalLogError(message) { + if (commonjsGlobal.console && commonjsGlobal.console.error) { + commonjsGlobal.console.error(message); + } else { + this.globalLogWarn(message); + } + } + log(defaultLoggingFunction, ...args) { + var message = stringify.apply(this, arguments); + if (pusher2.log) { + pusher2.log(message); + } else if (pusher2.logToConsole) { + const log = defaultLoggingFunction.bind(this); + log(message); + } + } + } + const logger = new Logger(); + class TransportConnection extends Dispatcher { + constructor(hooks2, name, priority, key, options) { + super(); + this.initialize = node_runtime.transportConnectionInitializer; + this.hooks = hooks2; + this.name = name; + this.priority = priority; + this.key = key; + this.options = options; + this.state = "new"; + this.timeline = options.timeline; + this.activityTimeout = options.activityTimeout; + this.id = this.timeline.generateUniqueID(); + } + handlesActivityChecks() { + return Boolean(this.hooks.handlesActivityChecks); + } + supportsPing() { + return Boolean(this.hooks.supportsPing); + } + connect() { + if (this.socket || this.state !== "initialized") { + return false; + } + var url = this.hooks.urls.getInitial(this.key, this.options); + try { + this.socket = this.hooks.getSocket(url, this.options); + } catch (e) { + util.defer(() => { + this.onError(e); + this.changeState("closed"); + }); + return false; + } + this.bindListeners(); + logger.debug("Connecting", { transport: this.name, url }); + this.changeState("connecting"); + return true; + } + close() { + if (this.socket) { + this.socket.close(); + return true; + } else { + return false; + } + } + send(data) { + if (this.state === "open") { + util.defer(() => { + if (this.socket) { + this.socket.send(data); + } + }); + return true; + } else { + return false; + } + } + ping() { + if (this.state === "open" && this.supportsPing()) { + this.socket.ping(); + } + } + onOpen() { + if (this.hooks.beforeOpen) { + this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options)); + } + this.changeState("open"); + this.socket.onopen = void 0; + } + onError(error) { + this.emit("error", { type: "WebSocketError", error }); + this.timeline.error(this.buildTimelineMessage({ error: error.toString() })); + } + onClose(closeEvent) { + if (closeEvent) { + this.changeState("closed", { + code: closeEvent.code, + reason: closeEvent.reason, + wasClean: closeEvent.wasClean + }); + } else { + this.changeState("closed"); + } + this.unbindListeners(); + this.socket = void 0; + } + onMessage(message) { + this.emit("message", message); + } + onActivity() { + this.emit("activity"); + } + bindListeners() { + this.socket.onopen = () => { + this.onOpen(); + }; + this.socket.onerror = (error) => { + this.onError(error); + }; + this.socket.onclose = (closeEvent) => { + this.onClose(closeEvent); + }; + this.socket.onmessage = (message) => { + this.onMessage(message); + }; + if (this.supportsPing()) { + this.socket.onactivity = () => { + this.onActivity(); + }; + } + } + unbindListeners() { + if (this.socket) { + this.socket.onopen = void 0; + this.socket.onerror = void 0; + this.socket.onclose = void 0; + this.socket.onmessage = void 0; + if (this.supportsPing()) { + this.socket.onactivity = void 0; + } + } + } + changeState(state2, params) { + this.state = state2; + this.timeline.info(this.buildTimelineMessage({ + state: state2, + params + })); + this.emit(state2, params); + } + buildTimelineMessage(message) { + return extend({ cid: this.id }, message); + } + } + class Transport { + constructor(hooks2) { + this.hooks = hooks2; + } + isSupported(environment) { + return this.hooks.isSupported(environment); + } + createConnection(name, priority, key, options) { + return new TransportConnection(this.hooks, name, priority, key, options); + } + } + var WSTransport = new Transport({ + urls: ws, + handlesActivityChecks: false, + supportsPing: false, + isInitialized: function() { + return Boolean(node_runtime.getWebSocketAPI()); + }, + isSupported: function() { + return Boolean(node_runtime.getWebSocketAPI()); + }, + getSocket: function(url) { + return node_runtime.createWebSocket(url); + } + }); + var httpConfiguration = { + urls: http, + handlesActivityChecks: false, + supportsPing: true, + isInitialized: function() { + return true; + } + }; + var streamingConfiguration = extend({ + getSocket: function(url) { + return node_runtime.HTTPFactory.createStreamingSocket(url); + } + }, httpConfiguration); + var pollingConfiguration = extend({ + getSocket: function(url) { + return node_runtime.HTTPFactory.createPollingSocket(url); + } + }, httpConfiguration); + var xhrConfiguration = { + isSupported: function() { + return node_runtime.isXHRSupported(); + } + }; + var XHRStreamingTransport = new Transport(extend({}, streamingConfiguration, xhrConfiguration)); + var XHRPollingTransport = new Transport(extend({}, pollingConfiguration, xhrConfiguration)); + var Transports = { + ws: WSTransport, + xhr_streaming: XHRStreamingTransport, + xhr_polling: XHRPollingTransport + }; + const transports = Transports; + class AssistantToTheTransportManager { + constructor(manager, transport, options) { + this.manager = manager; + this.transport = transport; + this.minPingDelay = options.minPingDelay; + this.maxPingDelay = options.maxPingDelay; + this.pingDelay = void 0; + } + createConnection(name, priority, key, options) { + options = extend({}, options, { + activityTimeout: this.pingDelay + }); + var connection = this.transport.createConnection(name, priority, key, options); + var openTimestamp = null; + var onOpen = function() { + connection.unbind("open", onOpen); + connection.bind("closed", onClosed); + openTimestamp = util.now(); + }; + var onClosed = (closeEvent) => { + connection.unbind("closed", onClosed); + if (closeEvent.code === 1002 || closeEvent.code === 1003) { + this.manager.reportDeath(); + } else if (!closeEvent.wasClean && openTimestamp) { + var lifespan = util.now() - openTimestamp; + if (lifespan < 2 * this.maxPingDelay) { + this.manager.reportDeath(); + this.pingDelay = Math.max(lifespan / 2, this.minPingDelay); + } + } + }; + connection.bind("open", onOpen); + return connection; + } + isSupported(environment) { + return this.manager.isAlive() && this.transport.isSupported(environment); + } + } + const Protocol = { + decodeMessage: function(messageEvent) { + try { + var messageData = JSON.parse(messageEvent.data); + var pusherEventData = messageData.data; + if (typeof pusherEventData === "string") { + try { + pusherEventData = JSON.parse(messageData.data); + } catch (e) { + } + } + var pusherEvent = { + event: messageData.event, + channel: messageData.channel, + data: pusherEventData + }; + if (messageData.user_id) { + pusherEvent.user_id = messageData.user_id; + } + return pusherEvent; + } catch (e) { + throw { type: "MessageParseError", error: e, data: messageEvent.data }; + } + }, + encodeMessage: function(event) { + return JSON.stringify(event); + }, + processHandshake: function(messageEvent) { + var message = Protocol.decodeMessage(messageEvent); + if (message.event === "pusher:connection_established") { + if (!message.data.activity_timeout) { + throw "No activity timeout specified in handshake"; + } + return { + action: "connected", + id: message.data.socket_id, + activityTimeout: message.data.activity_timeout * 1e3 + }; + } else if (message.event === "pusher:error") { + return { + action: this.getCloseAction(message.data), + error: this.getCloseError(message.data) + }; + } else { + throw "Invalid handshake"; + } + }, + getCloseAction: function(closeEvent) { + if (closeEvent.code < 4e3) { + if (closeEvent.code >= 1002 && closeEvent.code <= 1004) { + return "backoff"; + } else { + return null; + } + } else if (closeEvent.code === 4e3) { + return "tls_only"; + } else if (closeEvent.code < 4100) { + return "refused"; + } else if (closeEvent.code < 4200) { + return "backoff"; + } else if (closeEvent.code < 4300) { + return "retry"; + } else { + return "refused"; + } + }, + getCloseError: function(closeEvent) { + if (closeEvent.code !== 1e3 && closeEvent.code !== 1001) { + return { + type: "PusherError", + data: { + code: closeEvent.code, + message: closeEvent.reason || closeEvent.message + } + }; + } else { + return null; + } + } + }; + const protocol = Protocol; + class Connection extends Dispatcher { + constructor(id, transport) { + super(); + this.id = id; + this.transport = transport; + this.activityTimeout = transport.activityTimeout; + this.bindListeners(); + } + handlesActivityChecks() { + return this.transport.handlesActivityChecks(); + } + send(data) { + return this.transport.send(data); + } + send_event(name, data, channel) { + var event = { event: name, data }; + if (channel) { + event.channel = channel; + } + logger.debug("Event sent", event); + return this.send(protocol.encodeMessage(event)); + } + ping() { + if (this.transport.supportsPing()) { + this.transport.ping(); + } else { + this.send_event("pusher:ping", {}); + } + } + close() { + this.transport.close(); + } + bindListeners() { + var listeners = { + message: (messageEvent) => { + var pusherEvent; + try { + pusherEvent = protocol.decodeMessage(messageEvent); + } catch (e) { + this.emit("error", { + type: "MessageParseError", + error: e, + data: messageEvent.data + }); + } + if (pusherEvent !== void 0) { + logger.debug("Event recd", pusherEvent); + switch (pusherEvent.event) { + case "pusher:error": + this.emit("error", { + type: "PusherError", + data: pusherEvent.data + }); + break; + case "pusher:ping": + this.emit("ping"); + break; + case "pusher:pong": + this.emit("pong"); + break; + } + this.emit("message", pusherEvent); + } + }, + activity: () => { + this.emit("activity"); + }, + error: (error) => { + this.emit("error", error); + }, + closed: (closeEvent) => { + unbindListeners(); + if (closeEvent && closeEvent.code) { + this.handleCloseEvent(closeEvent); + } + this.transport = null; + this.emit("closed"); + } + }; + var unbindListeners = () => { + objectApply(listeners, (listener, event) => { + this.transport.unbind(event, listener); + }); + }; + objectApply(listeners, (listener, event) => { + this.transport.bind(event, listener); + }); + } + handleCloseEvent(closeEvent) { + var action = protocol.getCloseAction(closeEvent); + var error = protocol.getCloseError(closeEvent); + if (error) { + this.emit("error", error); + } + if (action) { + this.emit(action, { action, error }); + } + } + } + class Handshake { + constructor(transport, callback) { + this.transport = transport; + this.callback = callback; + this.bindListeners(); + } + close() { + this.unbindListeners(); + this.transport.close(); + } + bindListeners() { + this.onMessage = (m2) => { + this.unbindListeners(); + var result; + try { + result = protocol.processHandshake(m2); + } catch (e) { + this.finish("error", { error: e }); + this.transport.close(); + return; + } + if (result.action === "connected") { + this.finish("connected", { + connection: new Connection(result.id, this.transport), + activityTimeout: result.activityTimeout + }); + } else { + this.finish(result.action, { error: result.error }); + this.transport.close(); + } + }; + this.onClosed = (closeEvent) => { + this.unbindListeners(); + var action = protocol.getCloseAction(closeEvent) || "backoff"; + var error = protocol.getCloseError(closeEvent); + this.finish(action, { error }); + }; + this.transport.bind("message", this.onMessage); + this.transport.bind("closed", this.onClosed); + } + unbindListeners() { + this.transport.unbind("message", this.onMessage); + this.transport.unbind("closed", this.onClosed); + } + finish(action, params) { + this.callback(extend({ transport: this.transport, action }, params)); + } + } + class TimelineSender { + constructor(timeline, options) { + this.timeline = timeline; + this.options = options || {}; + } + send(useTLS, callback) { + if (this.timeline.isEmpty()) { + return; + } + this.timeline.send(node_runtime.TimelineTransport.getAgent(this, useTLS), callback); + } + } + class BadEventName extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class BadChannelName extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class TransportPriorityTooLow extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class TransportClosed extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class UnsupportedFeature extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class UnsupportedTransport extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class UnsupportedStrategy extends Error { + constructor(msg) { + super(msg); + Object.setPrototypeOf(this, new.target.prototype); + } + } + class HTTPAuthError extends Error { + constructor(status, msg) { + super(msg); + this.status = status; + Object.setPrototypeOf(this, new.target.prototype); + } + } + const urlStore = { + baseUrl: "https://pusher.com", + urls: { + authenticationEndpoint: { + path: "/docs/channels/server_api/authenticating_users" + }, + authorizationEndpoint: { + path: "/docs/channels/server_api/authorizing-users/" + }, + javascriptQuickStart: { + path: "/docs/javascript_quick_start" + }, + triggeringClientEvents: { + path: "/docs/client_api_guide/client_events#trigger-events" + }, + encryptedChannelSupport: { + fullUrl: "https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support" + } + } + }; + const buildLogSuffix = function(key) { + const urlPrefix = "See:"; + const urlObj = urlStore.urls[key]; + if (!urlObj) + return ""; + let url; + if (urlObj.fullUrl) { + url = urlObj.fullUrl; + } else if (urlObj.path) { + url = urlStore.baseUrl + urlObj.path; + } + if (!url) + return ""; + return `${urlPrefix} ${url}`; + }; + const url_store = { buildLogSuffix }; + class Channel extends Dispatcher { + constructor(name, pusher3) { + super(function(event, data) { + logger.debug("No callbacks on " + name + " for " + event); + }); + this.name = name; + this.pusher = pusher3; + this.subscribed = false; + this.subscriptionPending = false; + this.subscriptionCancelled = false; + } + authorize(socketId, callback) { + return callback(null, { auth: "" }); + } + trigger(event, data) { + if (event.indexOf("client-") !== 0) { + throw new BadEventName("Event '" + event + "' does not start with 'client-'"); + } + if (!this.subscribed) { + var suffix = url_store.buildLogSuffix("triggeringClientEvents"); + logger.warn(`Client event triggered before channel 'subscription_succeeded' event . ${suffix}`); + } + return this.pusher.send_event(event, data, this.name); + } + disconnect() { + this.subscribed = false; + this.subscriptionPending = false; + } + handleEvent(event) { + var eventName = event.event; + var data = event.data; + if (eventName === "pusher_internal:subscription_succeeded") { + this.handleSubscriptionSucceededEvent(event); + } else if (eventName === "pusher_internal:subscription_count") { + this.handleSubscriptionCountEvent(event); + } else if (eventName.indexOf("pusher_internal:") !== 0) { + var metadata = {}; + this.emit(eventName, data, metadata); + } + } + handleSubscriptionSucceededEvent(event) { + this.subscriptionPending = false; + this.subscribed = true; + if (this.subscriptionCancelled) { + this.pusher.unsubscribe(this.name); + } else { + this.emit("pusher:subscription_succeeded", event.data); + } + } + handleSubscriptionCountEvent(event) { + if (event.data.subscription_count) { + this.subscriptionCount = event.data.subscription_count; + } + this.emit("pusher:subscription_count", event.data); + } + subscribe() { + if (this.subscribed) { + return; + } + this.subscriptionPending = true; + this.subscriptionCancelled = false; + this.authorize(this.pusher.connection.socket_id, (error, data) => { + if (error) { + this.subscriptionPending = false; + logger.error(error.toString()); + this.emit("pusher:subscription_error", Object.assign({}, { + type: "AuthError", + error: error.message + }, error instanceof HTTPAuthError ? { status: error.status } : {})); + } else { + this.pusher.send_event("pusher:subscribe", { + auth: data.auth, + channel_data: data.channel_data, + channel: this.name + }); + } + }); + } + unsubscribe() { + this.subscribed = false; + this.pusher.send_event("pusher:unsubscribe", { + channel: this.name + }); + } + cancelSubscription() { + this.subscriptionCancelled = true; + } + reinstateSubscription() { + this.subscriptionCancelled = false; + } + } + class PrivateChannel extends Channel { + authorize(socketId, callback) { + return this.pusher.config.channelAuthorizer({ + channelName: this.name, + socketId + }, callback); + } + } + class Members { + constructor() { + this.reset(); + } + get(id) { + if (Object.prototype.hasOwnProperty.call(this.members, id)) { + return { + id, + info: this.members[id] + }; + } else { + return null; + } + } + each(callback) { + objectApply(this.members, (member, id) => { + callback(this.get(id)); + }); + } + setMyID(id) { + this.myID = id; + } + onSubscription(subscriptionData) { + this.members = subscriptionData.presence.hash; + this.count = subscriptionData.presence.count; + this.me = this.get(this.myID); + } + addMember(memberData) { + if (this.get(memberData.user_id) === null) { + this.count++; + } + this.members[memberData.user_id] = memberData.user_info; + return this.get(memberData.user_id); + } + removeMember(memberData) { + var member = this.get(memberData.user_id); + if (member) { + delete this.members[memberData.user_id]; + this.count--; + } + return member; + } + reset() { + this.members = {}; + this.count = 0; + this.myID = null; + this.me = null; + } + } + var __awaiter = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + class PresenceChannel extends PrivateChannel { + constructor(name, pusher3) { + super(name, pusher3); + this.members = new Members(); + } + authorize(socketId, callback) { + super.authorize(socketId, (error, authData) => __awaiter(this, void 0, void 0, function* () { + if (!error) { + authData = authData; + if (authData.channel_data != null) { + var channelData = JSON.parse(authData.channel_data); + this.members.setMyID(channelData.user_id); + } else { + yield this.pusher.user.signinDonePromise; + if (this.pusher.user.user_data != null) { + this.members.setMyID(this.pusher.user.user_data.id); + } else { + let suffix = url_store.buildLogSuffix("authorizationEndpoint"); + logger.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${suffix}, or the user should be signed in.`); + callback("Invalid auth response"); + return; + } + } + } + callback(error, authData); + })); + } + handleEvent(event) { + var eventName = event.event; + if (eventName.indexOf("pusher_internal:") === 0) { + this.handleInternalEvent(event); + } else { + var data = event.data; + var metadata = {}; + if (event.user_id) { + metadata.user_id = event.user_id; + } + this.emit(eventName, data, metadata); + } + } + handleInternalEvent(event) { + var eventName = event.event; + var data = event.data; + switch (eventName) { + case "pusher_internal:subscription_succeeded": + this.handleSubscriptionSucceededEvent(event); + break; + case "pusher_internal:subscription_count": + this.handleSubscriptionCountEvent(event); + break; + case "pusher_internal:member_added": + var addedMember = this.members.addMember(data); + this.emit("pusher:member_added", addedMember); + break; + case "pusher_internal:member_removed": + var removedMember = this.members.removeMember(data); + if (removedMember) { + this.emit("pusher:member_removed", removedMember); + } + break; + } + } + handleSubscriptionSucceededEvent(event) { + this.subscriptionPending = false; + this.subscribed = true; + if (this.subscriptionCancelled) { + this.pusher.unsubscribe(this.name); + } else { + this.members.onSubscription(event.data); + this.emit("pusher:subscription_succeeded", this.members); + } + } + disconnect() { + this.members.reset(); + super.disconnect(); + } + } + var utf8 = __webpack_require__2(978); + var base64 = __webpack_require__2(594); + class EncryptedChannel extends PrivateChannel { + constructor(name, pusher3, nacl) { + super(name, pusher3); + this.key = null; + this.nacl = nacl; + } + authorize(socketId, callback) { + super.authorize(socketId, (error, authData) => { + if (error) { + callback(error, authData); + return; + } + let sharedSecret = authData["shared_secret"]; + if (!sharedSecret) { + callback(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`), null); + return; + } + this.key = (0, base64.decode)(sharedSecret); + delete authData["shared_secret"]; + callback(null, authData); + }); + } + trigger(event, data) { + throw new UnsupportedFeature("Client events are not currently supported for encrypted channels"); + } + handleEvent(event) { + var eventName = event.event; + var data = event.data; + if (eventName.indexOf("pusher_internal:") === 0 || eventName.indexOf("pusher:") === 0) { + super.handleEvent(event); + return; + } + this.handleEncryptedEvent(eventName, data); + } + handleEncryptedEvent(event, data) { + if (!this.key) { + logger.debug("Received encrypted event before key has been retrieved from the authEndpoint"); + return; + } + if (!data.ciphertext || !data.nonce) { + logger.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: " + data); + return; + } + let cipherText = (0, base64.decode)(data.ciphertext); + if (cipherText.length < this.nacl.secretbox.overheadLength) { + logger.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`); + return; + } + let nonce = (0, base64.decode)(data.nonce); + if (nonce.length < this.nacl.secretbox.nonceLength) { + logger.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`); + return; + } + let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); + if (bytes === null) { + logger.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint..."); + this.authorize(this.pusher.connection.socket_id, (error, authData) => { + if (error) { + logger.error(`Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`); + return; + } + bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); + if (bytes === null) { + logger.error(`Failed to decrypt event with new key. Dropping encrypted event`); + return; + } + this.emit(event, this.getDataToEmit(bytes)); + return; + }); + return; + } + this.emit(event, this.getDataToEmit(bytes)); + } + getDataToEmit(bytes) { + let raw = (0, utf8.D4)(bytes); + try { + return JSON.parse(raw); + } catch (_a) { + return raw; + } + } + } + class ConnectionManager extends Dispatcher { + constructor(key, options) { + super(); + this.state = "initialized"; + this.connection = null; + this.key = key; + this.options = options; + this.timeline = this.options.timeline; + this.usingTLS = this.options.useTLS; + this.errorCallbacks = this.buildErrorCallbacks(); + this.connectionCallbacks = this.buildConnectionCallbacks(this.errorCallbacks); + this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks); + var Network2 = node_runtime.getNetwork(); + Network2.bind("online", () => { + this.timeline.info({ netinfo: "online" }); + if (this.state === "connecting" || this.state === "unavailable") { + this.retryIn(0); + } + }); + Network2.bind("offline", () => { + this.timeline.info({ netinfo: "offline" }); + if (this.connection) { + this.sendActivityCheck(); + } + }); + this.updateStrategy(); + } + switchCluster(key) { + this.key = key; + this.updateStrategy(); + this.retryIn(0); + } + connect() { + if (this.connection || this.runner) { + return; + } + if (!this.strategy.isSupported()) { + this.updateState("failed"); + return; + } + this.updateState("connecting"); + this.startConnecting(); + this.setUnavailableTimer(); + } + send(data) { + if (this.connection) { + return this.connection.send(data); + } else { + return false; + } + } + send_event(name, data, channel) { + if (this.connection) { + return this.connection.send_event(name, data, channel); + } else { + return false; + } + } + disconnect() { + this.disconnectInternally(); + this.updateState("disconnected"); + } + isUsingTLS() { + return this.usingTLS; + } + startConnecting() { + var callback = (error, handshake) => { + if (error) { + this.runner = this.strategy.connect(0, callback); + } else { + if (handshake.action === "error") { + this.emit("error", { + type: "HandshakeError", + error: handshake.error + }); + this.timeline.error({ handshakeError: handshake.error }); + } else { + this.abortConnecting(); + this.handshakeCallbacks[handshake.action](handshake); + } + } + }; + this.runner = this.strategy.connect(0, callback); + } + abortConnecting() { + if (this.runner) { + this.runner.abort(); + this.runner = null; + } + } + disconnectInternally() { + this.abortConnecting(); + this.clearRetryTimer(); + this.clearUnavailableTimer(); + if (this.connection) { + var connection = this.abandonConnection(); + connection.close(); + } + } + updateStrategy() { + this.strategy = this.options.getStrategy({ + key: this.key, + timeline: this.timeline, + useTLS: this.usingTLS + }); + } + retryIn(delay) { + this.timeline.info({ action: "retry", delay }); + if (delay > 0) { + this.emit("connecting_in", Math.round(delay / 1e3)); + } + this.retryTimer = new OneOffTimer(delay || 0, () => { + this.disconnectInternally(); + this.connect(); + }); + } + clearRetryTimer() { + if (this.retryTimer) { + this.retryTimer.ensureAborted(); + this.retryTimer = null; + } + } + setUnavailableTimer() { + this.unavailableTimer = new OneOffTimer(this.options.unavailableTimeout, () => { + this.updateState("unavailable"); + }); + } + clearUnavailableTimer() { + if (this.unavailableTimer) { + this.unavailableTimer.ensureAborted(); + } + } + sendActivityCheck() { + this.stopActivityCheck(); + this.connection.ping(); + this.activityTimer = new OneOffTimer(this.options.pongTimeout, () => { + this.timeline.error({ pong_timed_out: this.options.pongTimeout }); + this.retryIn(0); + }); + } + resetActivityCheck() { + this.stopActivityCheck(); + if (this.connection && !this.connection.handlesActivityChecks()) { + this.activityTimer = new OneOffTimer(this.activityTimeout, () => { + this.sendActivityCheck(); + }); + } + } + stopActivityCheck() { + if (this.activityTimer) { + this.activityTimer.ensureAborted(); + } + } + buildConnectionCallbacks(errorCallbacks) { + return extend({}, errorCallbacks, { + message: (message) => { + this.resetActivityCheck(); + this.emit("message", message); + }, + ping: () => { + this.send_event("pusher:pong", {}); + }, + activity: () => { + this.resetActivityCheck(); + }, + error: (error) => { + this.emit("error", error); + }, + closed: () => { + this.abandonConnection(); + if (this.shouldRetry()) { + this.retryIn(1e3); + } + } + }); + } + buildHandshakeCallbacks(errorCallbacks) { + return extend({}, errorCallbacks, { + connected: (handshake) => { + this.activityTimeout = Math.min(this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity); + this.clearUnavailableTimer(); + this.setConnection(handshake.connection); + this.socket_id = this.connection.id; + this.updateState("connected", { socket_id: this.socket_id }); + } + }); + } + buildErrorCallbacks() { + let withErrorEmitted = (callback) => { + return (result) => { + if (result.error) { + this.emit("error", { type: "WebSocketError", error: result.error }); + } + callback(result); + }; + }; + return { + tls_only: withErrorEmitted(() => { + this.usingTLS = true; + this.updateStrategy(); + this.retryIn(0); + }), + refused: withErrorEmitted(() => { + this.disconnect(); + }), + backoff: withErrorEmitted(() => { + this.retryIn(1e3); + }), + retry: withErrorEmitted(() => { + this.retryIn(0); + }) + }; + } + setConnection(connection) { + this.connection = connection; + for (var event in this.connectionCallbacks) { + this.connection.bind(event, this.connectionCallbacks[event]); + } + this.resetActivityCheck(); + } + abandonConnection() { + if (!this.connection) { + return; + } + this.stopActivityCheck(); + for (var event in this.connectionCallbacks) { + this.connection.unbind(event, this.connectionCallbacks[event]); + } + var connection = this.connection; + this.connection = null; + return connection; + } + updateState(newState, data) { + var previousState = this.state; + this.state = newState; + if (previousState !== newState) { + var newStateDescription = newState; + if (newStateDescription === "connected") { + newStateDescription += " with new socket ID " + data.socket_id; + } + logger.debug("State changed", previousState + " -> " + newStateDescription); + this.timeline.info({ state: newState, params: data }); + this.emit("state_change", { previous: previousState, current: newState }); + this.emit(newState, data); + } + } + shouldRetry() { + return this.state === "connecting" || this.state === "connected"; + } + } + class Channels { + constructor() { + this.channels = {}; + } + add(name, pusher3) { + if (!this.channels[name]) { + this.channels[name] = createChannel(name, pusher3); + } + return this.channels[name]; + } + all() { + return values(this.channels); + } + find(name) { + return this.channels[name]; + } + remove(name) { + var channel = this.channels[name]; + delete this.channels[name]; + return channel; + } + disconnect() { + objectApply(this.channels, function(channel) { + channel.disconnect(); + }); + } + } + function createChannel(name, pusher3) { + if (name.indexOf("private-encrypted-") === 0) { + if (pusher3.config.nacl) { + return factory.createEncryptedChannel(name, pusher3, pusher3.config.nacl); + } + let errMsg = "Tried to subscribe to a private-encrypted- channel but no nacl implementation available"; + let suffix = url_store.buildLogSuffix("encryptedChannelSupport"); + throw new UnsupportedFeature(`${errMsg}. ${suffix}`); + } else if (name.indexOf("private-") === 0) { + return factory.createPrivateChannel(name, pusher3); + } else if (name.indexOf("presence-") === 0) { + return factory.createPresenceChannel(name, pusher3); + } else if (name.indexOf("#") === 0) { + throw new BadChannelName('Cannot create a channel with name "' + name + '".'); + } else { + return factory.createChannel(name, pusher3); + } + } + var Factory = { + createChannels() { + return new Channels(); + }, + createConnectionManager(key, options) { + return new ConnectionManager(key, options); + }, + createChannel(name, pusher3) { + return new Channel(name, pusher3); + }, + createPrivateChannel(name, pusher3) { + return new PrivateChannel(name, pusher3); + }, + createPresenceChannel(name, pusher3) { + return new PresenceChannel(name, pusher3); + }, + createEncryptedChannel(name, pusher3, nacl) { + return new EncryptedChannel(name, pusher3, nacl); + }, + createTimelineSender(timeline, options) { + return new TimelineSender(timeline, options); + }, + createHandshake(transport, callback) { + return new Handshake(transport, callback); + }, + createAssistantToTheTransportManager(manager, transport, options) { + return new AssistantToTheTransportManager(manager, transport, options); + } + }; + const factory = Factory; + class TransportManager { + constructor(options) { + this.options = options || {}; + this.livesLeft = this.options.lives || Infinity; + } + getAssistant(transport) { + return factory.createAssistantToTheTransportManager(this, transport, { + minPingDelay: this.options.minPingDelay, + maxPingDelay: this.options.maxPingDelay + }); + } + isAlive() { + return this.livesLeft > 0; + } + reportDeath() { + this.livesLeft -= 1; + } + } + class SequentialStrategy { + constructor(strategies, options) { + this.strategies = strategies; + this.loop = Boolean(options.loop); + this.failFast = Boolean(options.failFast); + this.timeout = options.timeout; + this.timeoutLimit = options.timeoutLimit; + } + isSupported() { + return any(this.strategies, util.method("isSupported")); + } + connect(minPriority, callback) { + var strategies = this.strategies; + var current = 0; + var timeout = this.timeout; + var runner = null; + var tryNextStrategy = (error, handshake) => { + if (handshake) { + callback(null, handshake); + } else { + current = current + 1; + if (this.loop) { + current = current % strategies.length; + } + if (current < strategies.length) { + if (timeout) { + timeout = timeout * 2; + if (this.timeoutLimit) { + timeout = Math.min(timeout, this.timeoutLimit); + } + } + runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy); + } else { + callback(true); + } + } + }; + runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy); + return { + abort: function() { + runner.abort(); + }, + forceMinPriority: function(p2) { + minPriority = p2; + if (runner) { + runner.forceMinPriority(p2); + } + } + }; + } + tryStrategy(strategy, minPriority, options, callback) { + var timer = null; + var runner = null; + if (options.timeout > 0) { + timer = new OneOffTimer(options.timeout, function() { + runner.abort(); + callback(true); + }); + } + runner = strategy.connect(minPriority, function(error, handshake) { + if (error && timer && timer.isRunning() && !options.failFast) { + return; + } + if (timer) { + timer.ensureAborted(); + } + callback(error, handshake); + }); + return { + abort: function() { + if (timer) { + timer.ensureAborted(); + } + runner.abort(); + }, + forceMinPriority: function(p2) { + runner.forceMinPriority(p2); + } + }; + } + } + class BestConnectedEverStrategy { + constructor(strategies) { + this.strategies = strategies; + } + isSupported() { + return any(this.strategies, util.method("isSupported")); + } + connect(minPriority, callback) { + return connect(this.strategies, minPriority, function(i, runners) { + return function(error, handshake) { + runners[i].error = error; + if (error) { + if (allRunnersFailed(runners)) { + callback(true); + } + return; + } + apply(runners, function(runner) { + runner.forceMinPriority(handshake.transport.priority); + }); + callback(null, handshake); + }; + }); + } + } + function connect(strategies, minPriority, callbackBuilder) { + var runners = map(strategies, function(strategy, i, _2, rs) { + return strategy.connect(minPriority, callbackBuilder(i, rs)); + }); + return { + abort: function() { + apply(runners, abortRunner); + }, + forceMinPriority: function(p2) { + apply(runners, function(runner) { + runner.forceMinPriority(p2); + }); + } + }; + } + function allRunnersFailed(runners) { + return collections_all(runners, function(runner) { + return Boolean(runner.error); + }); + } + function abortRunner(runner) { + if (!runner.error && !runner.aborted) { + runner.abort(); + runner.aborted = true; + } + } + class WebSocketPrioritizedCachedStrategy { + constructor(strategy, transports2, options) { + this.strategy = strategy; + this.transports = transports2; + this.ttl = options.ttl || 1800 * 1e3; + this.usingTLS = options.useTLS; + this.timeline = options.timeline; + } + isSupported() { + return this.strategy.isSupported(); + } + connect(minPriority, callback) { + var usingTLS = this.usingTLS; + var info = fetchTransportCache(usingTLS); + var cacheSkipCount = info && info.cacheSkipCount ? info.cacheSkipCount : 0; + var strategies = [this.strategy]; + if (info && info.timestamp + this.ttl >= util.now()) { + var transport = this.transports[info.transport]; + if (transport) { + if (["ws", "wss"].includes(info.transport) || cacheSkipCount > 3) { + this.timeline.info({ + cached: true, + transport: info.transport, + latency: info.latency + }); + strategies.push(new SequentialStrategy([transport], { + timeout: info.latency * 2 + 1e3, + failFast: true + })); + } else { + cacheSkipCount++; + } + } + } + var startTimestamp = util.now(); + var runner = strategies.pop().connect(minPriority, function cb(error, handshake) { + if (error) { + flushTransportCache(usingTLS); + if (strategies.length > 0) { + startTimestamp = util.now(); + runner = strategies.pop().connect(minPriority, cb); + } else { + callback(error); + } + } else { + storeTransportCache(usingTLS, handshake.transport.name, util.now() - startTimestamp, cacheSkipCount); + callback(null, handshake); + } + }); + return { + abort: function() { + runner.abort(); + }, + forceMinPriority: function(p2) { + minPriority = p2; + if (runner) { + runner.forceMinPriority(p2); + } + } + }; + } + } + function getTransportCacheKey(usingTLS) { + return "pusherTransport" + (usingTLS ? "TLS" : "NonTLS"); + } + function fetchTransportCache(usingTLS) { + var storage = node_runtime.getLocalStorage(); + if (storage) { + try { + var serializedCache = storage[getTransportCacheKey(usingTLS)]; + if (serializedCache) { + return JSON.parse(serializedCache); + } + } catch (e) { + flushTransportCache(usingTLS); + } + } + return null; + } + function storeTransportCache(usingTLS, transport, latency, cacheSkipCount) { + var storage = node_runtime.getLocalStorage(); + if (storage) { + try { + storage[getTransportCacheKey(usingTLS)] = safeJSONStringify({ + timestamp: util.now(), + transport, + latency, + cacheSkipCount + }); + } catch (e) { + } + } + } + function flushTransportCache(usingTLS) { + var storage = node_runtime.getLocalStorage(); + if (storage) { + try { + delete storage[getTransportCacheKey(usingTLS)]; + } catch (e) { + } + } + } + class DelayedStrategy { + constructor(strategy, { delay: number }) { + this.strategy = strategy; + this.options = { delay: number }; + } + isSupported() { + return this.strategy.isSupported(); + } + connect(minPriority, callback) { + var strategy = this.strategy; + var runner; + var timer = new OneOffTimer(this.options.delay, function() { + runner = strategy.connect(minPriority, callback); + }); + return { + abort: function() { + timer.ensureAborted(); + if (runner) { + runner.abort(); + } + }, + forceMinPriority: function(p2) { + minPriority = p2; + if (runner) { + runner.forceMinPriority(p2); + } + } + }; + } + } + class IfStrategy { + constructor(test, trueBranch, falseBranch) { + this.test = test; + this.trueBranch = trueBranch; + this.falseBranch = falseBranch; + } + isSupported() { + var branch = this.test() ? this.trueBranch : this.falseBranch; + return branch.isSupported(); + } + connect(minPriority, callback) { + var branch = this.test() ? this.trueBranch : this.falseBranch; + return branch.connect(minPriority, callback); + } + } + class FirstConnectedStrategy { + constructor(strategy) { + this.strategy = strategy; + } + isSupported() { + return this.strategy.isSupported(); + } + connect(minPriority, callback) { + var runner = this.strategy.connect(minPriority, function(error, handshake) { + if (handshake) { + runner.abort(); + } + callback(error, handshake); + }); + return runner; + } + } + function testSupportsStrategy(strategy) { + return function() { + return strategy.isSupported(); + }; + } + var getDefaultStrategy = function(config, baseOptions, defineTransport2) { + var definedTransports = {}; + function defineTransportStrategy(name, type, priority, options, manager) { + var transport = defineTransport2(config, name, type, priority, options, manager); + definedTransports[name] = transport; + return transport; + } + var ws_options = Object.assign({}, baseOptions, { + hostNonTLS: config.wsHost + ":" + config.wsPort, + hostTLS: config.wsHost + ":" + config.wssPort, + httpPath: config.wsPath + }); + var wss_options = extend({}, ws_options, { + useTLS: true + }); + var http_options = Object.assign({}, baseOptions, { + hostNonTLS: config.httpHost + ":" + config.httpPort, + hostTLS: config.httpHost + ":" + config.httpsPort, + httpPath: config.httpPath + }); + var timeouts = { + loop: true, + timeout: 15e3, + timeoutLimit: 6e4 + }; + var ws_manager = new TransportManager({ + minPingDelay: 1e4, + maxPingDelay: config.activityTimeout + }); + var streaming_manager = new TransportManager({ + lives: 2, + minPingDelay: 1e4, + maxPingDelay: config.activityTimeout + }); + var ws_transport = defineTransportStrategy("ws", "ws", 3, ws_options, ws_manager); + var wss_transport = defineTransportStrategy("wss", "ws", 3, wss_options, ws_manager); + var xhr_streaming_transport = defineTransportStrategy("xhr_streaming", "xhr_streaming", 1, http_options, streaming_manager); + var xhr_polling_transport = defineTransportStrategy("xhr_polling", "xhr_polling", 1, http_options); + var ws_loop = new SequentialStrategy([ws_transport], timeouts); + var wss_loop = new SequentialStrategy([wss_transport], timeouts); + var streaming_loop = new SequentialStrategy([xhr_streaming_transport], timeouts); + var polling_loop = new SequentialStrategy([xhr_polling_transport], timeouts); + var http_loop = new SequentialStrategy([ + new IfStrategy(testSupportsStrategy(streaming_loop), new BestConnectedEverStrategy([ + streaming_loop, + new DelayedStrategy(polling_loop, { delay: 4e3 }) + ]), polling_loop) + ], timeouts); + var wsStrategy; + if (baseOptions.useTLS) { + wsStrategy = new BestConnectedEverStrategy([ + ws_loop, + new DelayedStrategy(http_loop, { delay: 2e3 }) + ]); + } else { + wsStrategy = new BestConnectedEverStrategy([ + ws_loop, + new DelayedStrategy(wss_loop, { delay: 2e3 }), + new DelayedStrategy(http_loop, { delay: 5e3 }) + ]); + } + return new WebSocketPrioritizedCachedStrategy(new FirstConnectedStrategy(new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop)), definedTransports, { + ttl: 18e5, + timeline: baseOptions.timeline, + useTLS: baseOptions.useTLS + }); + }; + const default_strategy = getDefaultStrategy; + function transport_connection_initializer() { + var self2 = this; + self2.timeline.info(self2.buildTimelineMessage({ + transport: self2.name + (self2.options.useTLS ? "s" : "") + })); + if (self2.hooks.isInitialized()) { + self2.changeState("initialized"); + } else { + self2.onClose(); + } + } + const MAX_BUFFER_LENGTH = 256 * 1024; + class HTTPRequest extends Dispatcher { + constructor(hooks2, method, url) { + super(); + this.hooks = hooks2; + this.method = method; + this.url = url; + } + start(payload) { + this.position = 0; + this.xhr = this.hooks.getRequest(this); + this.unloader = () => { + this.close(); + }; + node_runtime.addUnloadListener(this.unloader); + this.xhr.open(this.method, this.url, true); + if (this.xhr.setRequestHeader) { + this.xhr.setRequestHeader("Content-Type", "application/json"); + } + this.xhr.send(payload); + } + close() { + if (this.unloader) { + node_runtime.removeUnloadListener(this.unloader); + this.unloader = null; + } + if (this.xhr) { + this.hooks.abortRequest(this.xhr); + this.xhr = null; + } + } + onChunk(status, data) { + while (true) { + var chunk = this.advanceBuffer(data); + if (chunk) { + this.emit("chunk", { status, data: chunk }); + } else { + break; + } + } + if (this.isBufferTooLong(data)) { + this.emit("buffer_too_long"); + } + } + advanceBuffer(buffer) { + var unreadData = buffer.slice(this.position); + var endOfLinePosition = unreadData.indexOf("\n"); + if (endOfLinePosition !== -1) { + this.position += endOfLinePosition + 1; + return unreadData.slice(0, endOfLinePosition); + } else { + return null; + } + } + isBufferTooLong(buffer) { + return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH; + } + } + var State; + (function(State2) { + State2[State2["CONNECTING"] = 0] = "CONNECTING"; + State2[State2["OPEN"] = 1] = "OPEN"; + State2[State2["CLOSED"] = 3] = "CLOSED"; + })(State || (State = {})); + const state = State; + var autoIncrement = 1; + class HTTPSocket { + constructor(hooks2, url) { + this.hooks = hooks2; + this.session = randomNumber(1e3) + "/" + randomString(8); + this.location = getLocation(url); + this.readyState = state.CONNECTING; + this.openStream(); + } + send(payload) { + return this.sendRaw(JSON.stringify([payload])); + } + ping() { + this.hooks.sendHeartbeat(this); + } + close(code, reason) { + this.onClose(code, reason, true); + } + sendRaw(payload) { + if (this.readyState === state.OPEN) { + try { + node_runtime.createSocketRequest("POST", getUniqueURL(getSendURL(this.location, this.session))).start(payload); + return true; + } catch (e) { + return false; + } + } else { + return false; + } + } + reconnect() { + this.closeStream(); + this.openStream(); + } + onClose(code, reason, wasClean) { + this.closeStream(); + this.readyState = state.CLOSED; + if (this.onclose) { + this.onclose({ + code, + reason, + wasClean + }); + } + } + onChunk(chunk) { + if (chunk.status !== 200) { + return; + } + if (this.readyState === state.OPEN) { + this.onActivity(); + } + var payload; + var type = chunk.data.slice(0, 1); + switch (type) { + case "o": + payload = JSON.parse(chunk.data.slice(1) || "{}"); + this.onOpen(payload); + break; + case "a": + payload = JSON.parse(chunk.data.slice(1) || "[]"); + for (var i = 0; i < payload.length; i++) { + this.onEvent(payload[i]); + } + break; + case "m": + payload = JSON.parse(chunk.data.slice(1) || "null"); + this.onEvent(payload); + break; + case "h": + this.hooks.onHeartbeat(this); + break; + case "c": + payload = JSON.parse(chunk.data.slice(1) || "[]"); + this.onClose(payload[0], payload[1], true); + break; + } + } + onOpen(options) { + if (this.readyState === state.CONNECTING) { + if (options && options.hostname) { + this.location.base = replaceHost(this.location.base, options.hostname); + } + this.readyState = state.OPEN; + if (this.onopen) { + this.onopen(); + } + } else { + this.onClose(1006, "Server lost session", true); + } + } + onEvent(event) { + if (this.readyState === state.OPEN && this.onmessage) { + this.onmessage({ data: event }); + } + } + onActivity() { + if (this.onactivity) { + this.onactivity(); + } + } + onError(error) { + if (this.onerror) { + this.onerror(error); + } + } + openStream() { + this.stream = node_runtime.createSocketRequest("POST", getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))); + this.stream.bind("chunk", (chunk) => { + this.onChunk(chunk); + }); + this.stream.bind("finished", (status) => { + this.hooks.onFinished(this, status); + }); + this.stream.bind("buffer_too_long", () => { + this.reconnect(); + }); + try { + this.stream.start(); + } catch (error) { + util.defer(() => { + this.onError(error); + this.onClose(1006, "Could not start streaming", false); + }); + } + } + closeStream() { + if (this.stream) { + this.stream.unbind_all(); + this.stream.close(); + this.stream = null; + } + } + } + function getLocation(url) { + var parts = /([^\?]*)\/*(\??.*)/.exec(url); + return { + base: parts[1], + queryString: parts[2] + }; + } + function getSendURL(url, session) { + return url.base + "/" + session + "/xhr_send"; + } + function getUniqueURL(url) { + var separator = url.indexOf("?") === -1 ? "?" : "&"; + return url + separator + "t=" + +/* @__PURE__ */ new Date() + "&n=" + autoIncrement++; + } + function replaceHost(url, hostname) { + var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url); + return urlParts[1] + hostname + urlParts[3]; + } + function randomNumber(max) { + return node_runtime.randomInt(max); + } + function randomString(length) { + var result = []; + for (var i = 0; i < length; i++) { + result.push(randomNumber(32).toString(32)); + } + return result.join(""); + } + const http_socket = HTTPSocket; + var hooks = { + getReceiveURL: function(url, session) { + return url.base + "/" + session + "/xhr_streaming" + url.queryString; + }, + onHeartbeat: function(socket) { + socket.sendRaw("[]"); + }, + sendHeartbeat: function(socket) { + socket.sendRaw("[]"); + }, + onFinished: function(socket, status) { + socket.onClose(1006, "Connection interrupted (" + status + ")", false); + } + }; + const http_streaming_socket = hooks; + var http_polling_socket_hooks = { + getReceiveURL: function(url, session) { + return url.base + "/" + session + "/xhr" + url.queryString; + }, + onHeartbeat: function() { + }, + sendHeartbeat: function(socket) { + socket.sendRaw("[]"); + }, + onFinished: function(socket, status) { + if (status === 200) { + socket.reconnect(); + } else { + socket.onClose(1006, "Connection interrupted (" + status + ")", false); + } + } + }; + const http_polling_socket = http_polling_socket_hooks; + var http_xhr_request_hooks = { + getRequest: function(socket) { + var Constructor = node_runtime.getXHRAPI(); + var xhr2 = new Constructor(); + xhr2.onreadystatechange = xhr2.onprogress = function() { + switch (xhr2.readyState) { + case 3: + if (xhr2.responseText && xhr2.responseText.length > 0) { + socket.onChunk(xhr2.status, xhr2.responseText); + } + break; + case 4: + if (xhr2.responseText && xhr2.responseText.length > 0) { + socket.onChunk(xhr2.status, xhr2.responseText); + } + socket.emit("finished", xhr2.status); + socket.close(); + break; + } + }; + return xhr2; + }, + abortRequest: function(xhr2) { + xhr2.onreadystatechange = null; + xhr2.abort(); + } + }; + const http_xhr_request = http_xhr_request_hooks; + var HTTP = { + createStreamingSocket(url) { + return this.createSocket(http_streaming_socket, url); + }, + createPollingSocket(url) { + return this.createSocket(http_polling_socket, url); + }, + createSocket(hooks2, url) { + return new http_socket(hooks2, url); + }, + createXHR(method, url) { + return this.createRequest(http_xhr_request, method, url); + }, + createRequest(hooks2, method, url) { + return new HTTPRequest(hooks2, method, url); + } + }; + const http_http = HTTP; + var Isomorphic = { + getDefaultStrategy: default_strategy, + Transports: transports, + transportConnectionInitializer: transport_connection_initializer, + HTTPFactory: http_http, + setup(PusherClass) { + PusherClass.ready(); + }, + getLocalStorage() { + return void 0; + }, + getClientFeatures() { + return keys(filterObject({ ws: transports.ws }, function(t) { + return t.isSupported({}); + })); + }, + getProtocol() { + return "http:"; + }, + isXHRSupported() { + return true; + }, + createSocketRequest(method, url) { + if (this.isXHRSupported()) { + return this.HTTPFactory.createXHR(method, url); + } else { + throw "Cross-origin HTTP requests are not supported"; + } + }, + createXHR() { + var Constructor = this.getXHRAPI(); + return new Constructor(); + }, + createWebSocket(url) { + var Constructor = this.getWebSocketAPI(); + return new Constructor(url); + }, + addUnloadListener(listener) { + }, + removeUnloadListener(listener) { + } + }; + const runtime = Isomorphic; + var websocket = __webpack_require__2(555); + var XMLHttpRequest = __webpack_require__2(407); + class NetInfo extends Dispatcher { + isOnline() { + return true; + } + } + var Network = new NetInfo(); + var AuthRequestType; + (function(AuthRequestType2) { + AuthRequestType2["UserAuthentication"] = "user-authentication"; + AuthRequestType2["ChannelAuthorization"] = "channel-authorization"; + })(AuthRequestType || (AuthRequestType = {})); + const ajax = function(context, query, authOptions, authRequestType, callback) { + const xhr2 = node_runtime.createXHR(); + xhr2.open("POST", authOptions.endpoint, true); + xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + for (var headerName in authOptions.headers) { + xhr2.setRequestHeader(headerName, authOptions.headers[headerName]); + } + if (authOptions.headersProvider != null) { + let dynamicHeaders = authOptions.headersProvider(); + for (var headerName in dynamicHeaders) { + xhr2.setRequestHeader(headerName, dynamicHeaders[headerName]); + } + } + xhr2.onreadystatechange = function() { + if (xhr2.readyState === 4) { + if (xhr2.status === 200) { + let data; + let parsed = false; + try { + data = JSON.parse(xhr2.responseText); + parsed = true; + } catch (e) { + callback(new HTTPAuthError(200, `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${xhr2.responseText}`), null); + } + if (parsed) { + callback(null, data); + } + } else { + let suffix = ""; + switch (authRequestType) { + case AuthRequestType.UserAuthentication: + suffix = url_store.buildLogSuffix("authenticationEndpoint"); + break; + case AuthRequestType.ChannelAuthorization: + suffix = `Clients must be authorized to join private or presence channels. ${url_store.buildLogSuffix("authorizationEndpoint")}`; + break; + } + callback(new HTTPAuthError(xhr2.status, `Unable to retrieve auth string from ${authRequestType.toString()} endpoint - received status: ${xhr2.status} from ${authOptions.endpoint}. ${suffix}`), null); + } + } + }; + xhr2.send(query); + return xhr2; + }; + const xhr_auth = ajax; + var getAgent = function(sender, useTLS) { + return function(data, callback) { + var scheme = "http" + (useTLS ? "s" : "") + "://"; + var url = scheme + (sender.host || sender.options.host) + sender.options.path; + var query = buildQueryString(data); + url += "/2?" + query; + var xhr2 = node_runtime.createXHR(); + xhr2.open("GET", url, true); + xhr2.onreadystatechange = function() { + if (xhr2.readyState === 4) { + let { status, responseText } = xhr2; + if (status !== 200) { + logger.debug(`TimelineSender Error: received ${status} from stats.pusher.com`); + return; + } + try { + var { host } = JSON.parse(responseText); + } catch (e) { + logger.debug(`TimelineSenderError: invalid response ${responseText}`); + } + if (host) { + sender.host = host; + } + } + }; + xhr2.send(); + }; + }; + var xhr = { + name: "xhr", + getAgent + }; + const xhr_timeline = xhr; + var external_crypto_ = __webpack_require__2(982); + const { getDefaultStrategy: runtime_getDefaultStrategy, Transports: runtime_Transports, setup, getProtocol, isXHRSupported, getLocalStorage, createXHR, createWebSocket, addUnloadListener, removeUnloadListener, transportConnectionInitializer, createSocketRequest, HTTPFactory } = runtime; + const NodeJS = { + getDefaultStrategy: runtime_getDefaultStrategy, + Transports: runtime_Transports, + setup, + getProtocol, + isXHRSupported, + createSocketRequest, + getLocalStorage, + createXHR, + createWebSocket, + addUnloadListener, + removeUnloadListener, + transportConnectionInitializer, + HTTPFactory, + TimelineTransport: xhr_timeline, + getAuthorizers() { + return { ajax: xhr_auth }; + }, + getWebSocketAPI() { + return websocket.Client; + }, + getXHRAPI() { + return XMLHttpRequest.z; + }, + getNetwork() { + return Network; + }, + randomInt(max) { + return (0, external_crypto_.randomInt)(max); + } + }; + const node_runtime = NodeJS; + var TimelineLevel; + (function(TimelineLevel2) { + TimelineLevel2[TimelineLevel2["ERROR"] = 3] = "ERROR"; + TimelineLevel2[TimelineLevel2["INFO"] = 6] = "INFO"; + TimelineLevel2[TimelineLevel2["DEBUG"] = 7] = "DEBUG"; + })(TimelineLevel || (TimelineLevel = {})); + const level = TimelineLevel; + class Timeline { + constructor(key, session, options) { + this.key = key; + this.session = session; + this.events = []; + this.options = options || {}; + this.sent = 0; + this.uniqueID = 0; + } + log(level2, event) { + if (level2 <= this.options.level) { + this.events.push(extend({}, event, { timestamp: util.now() })); + if (this.options.limit && this.events.length > this.options.limit) { + this.events.shift(); + } + } + } + error(event) { + this.log(level.ERROR, event); + } + info(event) { + this.log(level.INFO, event); + } + debug(event) { + this.log(level.DEBUG, event); + } + isEmpty() { + return this.events.length === 0; + } + send(sendfn, callback) { + var data = extend({ + session: this.session, + bundle: this.sent + 1, + key: this.key, + lib: "js", + version: this.options.version, + cluster: this.options.cluster, + features: this.options.features, + timeline: this.events + }, this.options.params); + this.events = []; + sendfn(data, (error, result) => { + if (!error) { + this.sent++; + } + if (callback) { + callback(error, result); + } + }); + return true; + } + generateUniqueID() { + this.uniqueID++; + return this.uniqueID; + } + } + class TransportStrategy { + constructor(name, priority, transport, options) { + this.name = name; + this.priority = priority; + this.transport = transport; + this.options = options || {}; + } + isSupported() { + return this.transport.isSupported({ + useTLS: this.options.useTLS + }); + } + connect(minPriority, callback) { + if (!this.isSupported()) { + return failAttempt(new UnsupportedStrategy(), callback); + } else if (this.priority < minPriority) { + return failAttempt(new TransportPriorityTooLow(), callback); + } + var connected = false; + var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options); + var handshake = null; + var onInitialized = function() { + transport.unbind("initialized", onInitialized); + transport.connect(); + }; + var onOpen = function() { + handshake = factory.createHandshake(transport, function(result) { + connected = true; + unbindListeners(); + callback(null, result); + }); + }; + var onError = function(error) { + unbindListeners(); + callback(error); + }; + var onClosed = function() { + unbindListeners(); + var serializedTransport; + serializedTransport = safeJSONStringify(transport); + callback(new TransportClosed(serializedTransport)); + }; + var unbindListeners = function() { + transport.unbind("initialized", onInitialized); + transport.unbind("open", onOpen); + transport.unbind("error", onError); + transport.unbind("closed", onClosed); + }; + transport.bind("initialized", onInitialized); + transport.bind("open", onOpen); + transport.bind("error", onError); + transport.bind("closed", onClosed); + transport.initialize(); + return { + abort: () => { + if (connected) { + return; + } + unbindListeners(); + if (handshake) { + handshake.close(); + } else { + transport.close(); + } + }, + forceMinPriority: (p2) => { + if (connected) { + return; + } + if (this.priority < p2) { + if (handshake) { + handshake.close(); + } else { + transport.close(); + } + } + } + }; + } + } + function failAttempt(error, callback) { + util.defer(function() { + callback(error); + }); + return { + abort: function() { + }, + forceMinPriority: function() { + } + }; + } + const { Transports: strategy_builder_Transports } = node_runtime; + var defineTransport = function(config, name, type, priority, options, manager) { + var transportClass = strategy_builder_Transports[type]; + if (!transportClass) { + throw new UnsupportedTransport(type); + } + var enabled = (!config.enabledTransports || arrayIndexOf(config.enabledTransports, name) !== -1) && (!config.disabledTransports || arrayIndexOf(config.disabledTransports, name) === -1); + var transport; + if (enabled) { + options = Object.assign({ ignoreNullOrigin: config.ignoreNullOrigin }, options); + transport = new TransportStrategy(name, priority, manager ? manager.getAssistant(transportClass) : transportClass, options); + } else { + transport = strategy_builder_UnsupportedStrategy; + } + return transport; + }; + var strategy_builder_UnsupportedStrategy = { + isSupported: function() { + return false; + }, + connect: function(_2, callback) { + var deferred = util.defer(function() { + callback(new UnsupportedStrategy()); + }); + return { + abort: function() { + deferred.ensureAborted(); + }, + forceMinPriority: function() { + } + }; + } + }; + function validateOptions(options) { + if (options == null) { + throw "You must pass an options object"; + } + if (options.cluster == null) { + throw "Options object must provide a cluster"; + } + if ("disableStats" in options) { + logger.warn("The disableStats option is deprecated in favor of enableStats"); + } + } + const composeChannelQuery = (params, authOptions) => { + var query = "socket_id=" + encodeURIComponent(params.socketId); + for (var key in authOptions.params) { + query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(authOptions.params[key]); + } + if (authOptions.paramsProvider != null) { + let dynamicParams = authOptions.paramsProvider(); + for (var key in dynamicParams) { + query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dynamicParams[key]); + } + } + return query; + }; + const UserAuthenticator = (authOptions) => { + if (typeof node_runtime.getAuthorizers()[authOptions.transport] === "undefined") { + throw `'${authOptions.transport}' is not a recognized auth transport`; + } + return (params, callback) => { + const query = composeChannelQuery(params, authOptions); + node_runtime.getAuthorizers()[authOptions.transport](node_runtime, query, authOptions, AuthRequestType.UserAuthentication, callback); + }; + }; + const user_authenticator = UserAuthenticator; + const channel_authorizer_composeChannelQuery = (params, authOptions) => { + var query = "socket_id=" + encodeURIComponent(params.socketId); + query += "&channel_name=" + encodeURIComponent(params.channelName); + for (var key in authOptions.params) { + query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(authOptions.params[key]); + } + if (authOptions.paramsProvider != null) { + let dynamicParams = authOptions.paramsProvider(); + for (var key in dynamicParams) { + query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dynamicParams[key]); + } + } + return query; + }; + const ChannelAuthorizer = (authOptions) => { + if (typeof node_runtime.getAuthorizers()[authOptions.transport] === "undefined") { + throw `'${authOptions.transport}' is not a recognized auth transport`; + } + return (params, callback) => { + const query = channel_authorizer_composeChannelQuery(params, authOptions); + node_runtime.getAuthorizers()[authOptions.transport](node_runtime, query, authOptions, AuthRequestType.ChannelAuthorization, callback); + }; + }; + const channel_authorizer = ChannelAuthorizer; + const ChannelAuthorizerProxy = (pusher3, authOptions, channelAuthorizerGenerator) => { + const deprecatedAuthorizerOptions = { + authTransport: authOptions.transport, + authEndpoint: authOptions.endpoint, + auth: { + params: authOptions.params, + headers: authOptions.headers + } + }; + return (params, callback) => { + const channel = pusher3.channel(params.channelName); + const channelAuthorizer = channelAuthorizerGenerator(channel, deprecatedAuthorizerOptions); + channelAuthorizer.authorize(params.socketId, callback); + }; + }; + function getConfig(opts, pusher3) { + let config = { + activityTimeout: opts.activityTimeout || defaults.activityTimeout, + cluster: opts.cluster, + httpPath: opts.httpPath || defaults.httpPath, + httpPort: opts.httpPort || defaults.httpPort, + httpsPort: opts.httpsPort || defaults.httpsPort, + pongTimeout: opts.pongTimeout || defaults.pongTimeout, + statsHost: opts.statsHost || defaults.stats_host, + unavailableTimeout: opts.unavailableTimeout || defaults.unavailableTimeout, + wsPath: opts.wsPath || defaults.wsPath, + wsPort: opts.wsPort || defaults.wsPort, + wssPort: opts.wssPort || defaults.wssPort, + enableStats: getEnableStatsConfig(opts), + httpHost: getHttpHost(opts), + useTLS: shouldUseTLS(opts), + wsHost: getWebsocketHost(opts), + userAuthenticator: buildUserAuthenticator(opts), + channelAuthorizer: buildChannelAuthorizer(opts, pusher3) + }; + if ("disabledTransports" in opts) + config.disabledTransports = opts.disabledTransports; + if ("enabledTransports" in opts) + config.enabledTransports = opts.enabledTransports; + if ("ignoreNullOrigin" in opts) + config.ignoreNullOrigin = opts.ignoreNullOrigin; + if ("timelineParams" in opts) + config.timelineParams = opts.timelineParams; + if ("nacl" in opts) { + config.nacl = opts.nacl; + } + return config; + } + function getHttpHost(opts) { + if (opts.httpHost) { + return opts.httpHost; + } + if (opts.cluster) { + return `sockjs-${opts.cluster}.pusher.com`; + } + return defaults.httpHost; + } + function getWebsocketHost(opts) { + if (opts.wsHost) { + return opts.wsHost; + } + return getWebsocketHostFromCluster(opts.cluster); + } + function getWebsocketHostFromCluster(cluster) { + return `ws-${cluster}.pusher.com`; + } + function shouldUseTLS(opts) { + if (node_runtime.getProtocol() === "https:") { + return true; + } else if (opts.forceTLS === false) { + return false; + } + return true; + } + function getEnableStatsConfig(opts) { + if ("enableStats" in opts) { + return opts.enableStats; + } + if ("disableStats" in opts) { + return !opts.disableStats; + } + return false; + } + const hasCustomHandler = (auth) => { + return "customHandler" in auth && auth["customHandler"] != null; + }; + function buildUserAuthenticator(opts) { + const userAuthentication = Object.assign(Object.assign({}, defaults.userAuthentication), opts.userAuthentication); + if (hasCustomHandler(userAuthentication)) { + return userAuthentication["customHandler"]; + } + return user_authenticator(userAuthentication); + } + function buildChannelAuth(opts, pusher3) { + let channelAuthorization; + if ("channelAuthorization" in opts) { + channelAuthorization = Object.assign(Object.assign({}, defaults.channelAuthorization), opts.channelAuthorization); + } else { + channelAuthorization = { + transport: opts.authTransport || defaults.authTransport, + endpoint: opts.authEndpoint || defaults.authEndpoint + }; + if ("auth" in opts) { + if ("params" in opts.auth) + channelAuthorization.params = opts.auth.params; + if ("headers" in opts.auth) + channelAuthorization.headers = opts.auth.headers; + } + if ("authorizer" in opts) { + return { + customHandler: ChannelAuthorizerProxy(pusher3, channelAuthorization, opts.authorizer) + }; + } + } + return channelAuthorization; + } + function buildChannelAuthorizer(opts, pusher3) { + const channelAuthorization = buildChannelAuth(opts, pusher3); + if (hasCustomHandler(channelAuthorization)) { + return channelAuthorization["customHandler"]; + } + return channel_authorizer(channelAuthorization); + } + class WatchlistFacade extends Dispatcher { + constructor(pusher3) { + super(function(eventName, data) { + logger.debug(`No callbacks on watchlist events for ${eventName}`); + }); + this.pusher = pusher3; + this.bindWatchlistInternalEvent(); + } + handleEvent(pusherEvent) { + pusherEvent.data.events.forEach((watchlistEvent) => { + this.emit(watchlistEvent.name, watchlistEvent); + }); + } + bindWatchlistInternalEvent() { + this.pusher.connection.bind("message", (pusherEvent) => { + var eventName = pusherEvent.event; + if (eventName === "pusher_internal:watchlist_events") { + this.handleEvent(pusherEvent); + } + }); + } + } + function flatPromise() { + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; + } + const flat_promise = flatPromise; + class UserFacade extends Dispatcher { + constructor(pusher3) { + super(function(eventName, data) { + logger.debug("No callbacks on user for " + eventName); + }); + this.signin_requested = false; + this.user_data = null; + this.serverToUserChannel = null; + this.signinDonePromise = null; + this._signinDoneResolve = null; + this._onAuthorize = (err, authData) => { + if (err) { + logger.warn(`Error during signin: ${err}`); + this._cleanup(); + return; + } + this.pusher.send_event("pusher:signin", { + auth: authData.auth, + user_data: authData.user_data + }); + }; + this.pusher = pusher3; + this.pusher.connection.bind("state_change", ({ previous, current }) => { + if (previous !== "connected" && current === "connected") { + this._signin(); + } + if (previous === "connected" && current !== "connected") { + this._cleanup(); + this._newSigninPromiseIfNeeded(); + } + }); + this.watchlist = new WatchlistFacade(pusher3); + this.pusher.connection.bind("message", (event) => { + var eventName = event.event; + if (eventName === "pusher:signin_success") { + this._onSigninSuccess(event.data); + } + if (this.serverToUserChannel && this.serverToUserChannel.name === event.channel) { + this.serverToUserChannel.handleEvent(event); + } + }); + } + signin() { + if (this.signin_requested) { + return; + } + this.signin_requested = true; + this._signin(); + } + _signin() { + if (!this.signin_requested) { + return; + } + this._newSigninPromiseIfNeeded(); + if (this.pusher.connection.state !== "connected") { + return; + } + this.pusher.config.userAuthenticator({ + socketId: this.pusher.connection.socket_id + }, this._onAuthorize); + } + _onSigninSuccess(data) { + try { + this.user_data = JSON.parse(data.user_data); + } catch (e) { + logger.error(`Failed parsing user data after signin: ${data.user_data}`); + this._cleanup(); + return; + } + if (typeof this.user_data.id !== "string" || this.user_data.id === "") { + logger.error(`user_data doesn't contain an id. user_data: ${this.user_data}`); + this._cleanup(); + return; + } + this._signinDoneResolve(); + this._subscribeChannels(); + } + _subscribeChannels() { + const ensure_subscribed = (channel) => { + if (channel.subscriptionPending && channel.subscriptionCancelled) { + channel.reinstateSubscription(); + } else if (!channel.subscriptionPending && this.pusher.connection.state === "connected") { + channel.subscribe(); + } + }; + this.serverToUserChannel = new Channel(`#server-to-user-${this.user_data.id}`, this.pusher); + this.serverToUserChannel.bind_global((eventName, data) => { + if (eventName.indexOf("pusher_internal:") === 0 || eventName.indexOf("pusher:") === 0) { + return; + } + this.emit(eventName, data); + }); + ensure_subscribed(this.serverToUserChannel); + } + _cleanup() { + this.user_data = null; + if (this.serverToUserChannel) { + this.serverToUserChannel.unbind_all(); + this.serverToUserChannel.disconnect(); + this.serverToUserChannel = null; + } + if (this.signin_requested) { + this._signinDoneResolve(); + } + } + _newSigninPromiseIfNeeded() { + if (!this.signin_requested) { + return; + } + if (this.signinDonePromise && !this.signinDonePromise.done) { + return; + } + const { promise, resolve } = flat_promise(); + promise.done = false; + const setDone = () => { + promise.done = true; + }; + promise.then(setDone).catch(setDone); + this.signinDonePromise = promise; + this._signinDoneResolve = resolve; + } + } + class Pusher2 { + static ready() { + Pusher2.isReady = true; + for (var i = 0, l2 = Pusher2.instances.length; i < l2; i++) { + Pusher2.instances[i].connect(); + } + } + static getClientFeatures() { + return keys(filterObject({ ws: node_runtime.Transports.ws }, function(t) { + return t.isSupported({}); + })); + } + constructor(app_key, options) { + checkAppKey(app_key); + validateOptions(options); + this.key = app_key; + this.options = options; + this.config = getConfig(this.options, this); + this.channels = factory.createChannels(); + this.global_emitter = new Dispatcher(); + this.sessionID = node_runtime.randomInt(1e9); + this.timeline = new Timeline(this.key, this.sessionID, { + cluster: this.config.cluster, + features: Pusher2.getClientFeatures(), + params: this.config.timelineParams || {}, + limit: 50, + level: level.INFO, + version: defaults.VERSION + }); + if (this.config.enableStats) { + this.timelineSender = factory.createTimelineSender(this.timeline, { + host: this.config.statsHost, + path: "/timeline/v2/" + node_runtime.TimelineTransport.name + }); + } + var getStrategy = (options2) => { + return node_runtime.getDefaultStrategy(this.config, options2, defineTransport); + }; + this.connection = factory.createConnectionManager(this.key, { + getStrategy, + timeline: this.timeline, + activityTimeout: this.config.activityTimeout, + pongTimeout: this.config.pongTimeout, + unavailableTimeout: this.config.unavailableTimeout, + useTLS: Boolean(this.config.useTLS) + }); + this.connection.bind("connected", () => { + this.subscribeAll(); + if (this.timelineSender) { + this.timelineSender.send(this.connection.isUsingTLS()); + } + }); + this.connection.bind("message", (event) => { + var eventName = event.event; + var internal = eventName.indexOf("pusher_internal:") === 0; + if (event.channel) { + var channel = this.channel(event.channel); + if (channel) { + channel.handleEvent(event); + } + } + if (!internal) { + this.global_emitter.emit(event.event, event.data); + } + }); + this.connection.bind("connecting", () => { + this.channels.disconnect(); + }); + this.connection.bind("disconnected", () => { + this.channels.disconnect(); + }); + this.connection.bind("error", (err) => { + logger.warn(err); + }); + Pusher2.instances.push(this); + this.timeline.info({ instances: Pusher2.instances.length }); + this.user = new UserFacade(this); + if (Pusher2.isReady) { + this.connect(); + } + } + switchCluster(options) { + const { appKey, cluster } = options; + this.key = appKey; + this.options = Object.assign(Object.assign({}, this.options), { cluster }); + this.config = getConfig(this.options, this); + this.connection.switchCluster(this.key); + } + channel(name) { + return this.channels.find(name); + } + allChannels() { + return this.channels.all(); + } + connect() { + this.connection.connect(); + if (this.timelineSender) { + if (!this.timelineSenderTimer) { + var usingTLS = this.connection.isUsingTLS(); + var timelineSender = this.timelineSender; + this.timelineSenderTimer = new PeriodicTimer(6e4, function() { + timelineSender.send(usingTLS); + }); + } + } + } + disconnect() { + this.connection.disconnect(); + if (this.timelineSenderTimer) { + this.timelineSenderTimer.ensureAborted(); + this.timelineSenderTimer = null; + } + } + bind(event_name, callback, context) { + this.global_emitter.bind(event_name, callback, context); + return this; + } + unbind(event_name, callback, context) { + this.global_emitter.unbind(event_name, callback, context); + return this; + } + bind_global(callback) { + this.global_emitter.bind_global(callback); + return this; + } + unbind_global(callback) { + this.global_emitter.unbind_global(callback); + return this; + } + unbind_all(callback) { + this.global_emitter.unbind_all(); + return this; + } + subscribeAll() { + var channelName; + for (channelName in this.channels.channels) { + if (this.channels.channels.hasOwnProperty(channelName)) { + this.subscribe(channelName); + } + } + } + subscribe(channel_name) { + var channel = this.channels.add(channel_name, this); + if (channel.subscriptionPending && channel.subscriptionCancelled) { + channel.reinstateSubscription(); + } else if (!channel.subscriptionPending && this.connection.state === "connected") { + channel.subscribe(); + } + return channel; + } + unsubscribe(channel_name) { + var channel = this.channels.find(channel_name); + if (channel && channel.subscriptionPending) { + channel.cancelSubscription(); + } else { + channel = this.channels.remove(channel_name); + if (channel && channel.subscribed) { + channel.unsubscribe(); + } + } + } + send_event(event_name, data, channel) { + return this.connection.send_event(event_name, data, channel); + } + shouldUseTLS() { + return this.config.useTLS; + } + signin() { + this.user.signin(); + } + } + Pusher2.instances = []; + Pusher2.isReady = false; + Pusher2.logToConsole = false; + Pusher2.Runtime = node_runtime; + Pusher2.ScriptReceivers = node_runtime.ScriptReceivers; + Pusher2.DependenciesReceivers = node_runtime.DependenciesReceivers; + Pusher2.auth_callbacks = node_runtime.auth_callbacks; + const pusher2 = Pusher2; + function checkAppKey(key) { + if (key === null || key === void 0) { + throw "You must pass your app key when you instantiate Pusher."; + } + } + node_runtime.setup(Pusher2); + var nacl_fast = __webpack_require__2(601); + class PusherWithEncryption extends pusher2 { + constructor(app_key, options) { + pusher2.logToConsole = PusherWithEncryption.logToConsole; + pusher2.log = PusherWithEncryption.log; + validateOptions(options); + options.nacl = nacl_fast; + super(app_key, options); + } + } + }, + /***/ + 613(module2) { + module2.exports = require$$4$2; + }, + /***/ + 181(module2) { + module2.exports = require$$1$1; + }, + /***/ + 317(module2) { + module2.exports = require$$2; + }, + /***/ + 982(module2) { + module2.exports = require$$1; + }, + /***/ + 434(module2) { + module2.exports = require$$4$1; + }, + /***/ + 896(module2) { + module2.exports = require$$6; + }, + /***/ + 611(module2) { + module2.exports = require$$3; + }, + /***/ + 692(module2) { + module2.exports = require$$4; + }, + /***/ + 278(module2) { + module2.exports = require$$8; + }, + /***/ + 203(module2) { + module2.exports = stream; + }, + /***/ + 756(module2) { + module2.exports = require$$10; + }, + /***/ + 16(module2) { + module2.exports = require$$5; + }, + /***/ + 23(module2) { + module2.exports = require$$0; + } + /******/ + }; + var __webpack_module_cache__ = {}; + function __webpack_require__(moduleId) { + var cachedModule = __webpack_module_cache__[moduleId]; + if (cachedModule !== void 0) { + return cachedModule.exports; + } + var module2 = __webpack_module_cache__[moduleId] = { + /******/ + // no module.id needed + /******/ + // no module.loaded needed + /******/ + exports: {} + /******/ + }; + __webpack_modules__[moduleId].call(module2.exports, module2, module2.exports, __webpack_require__); + return module2.exports; + } + (() => { + __webpack_require__.d = (exports$1, definition) => { + for (var key in definition) { + if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports$1, key)) { + Object.defineProperty(exports$1, key, { enumerable: true, get: definition[key] }); + } + } + }; + })(); + (() => { + __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop); + })(); + var __webpack_exports__ = __webpack_require__(42); + module.exports.Pusher = __webpack_exports__; + })(); + })(pusher); + return pusher.exports; +} +var pusherExports = requirePusher(); +const Pusher = /* @__PURE__ */ getDefaultExportFromCjs(pusherExports); +export { + E, + Pusher as P +}; diff --git a/bootstrap/ssr/assets/vendor-tiptap-DSw66HfW.js b/bootstrap/ssr/assets/vendor-tiptap-DSw66HfW.js new file mode 100644 index 00000000..b953fda0 --- /dev/null +++ b/bootstrap/ssr/assets/vendor-tiptap-DSw66HfW.js @@ -0,0 +1,27177 @@ +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} +var react = { exports: {} }; +var react_production = {}; +var hasRequiredReact_production; +function requireReact_production() { + if (hasRequiredReact_production) return react_production; + hasRequiredReact_production = 1; + var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) return null; + maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + var ReactNoopUpdateQueue = { + isMounted: function() { + return false; + }, + enqueueForceUpdate: function() { + }, + enqueueReplaceState: function() { + }, + enqueueSetState: function() { + } + }, assign = Object.assign, emptyObject = {}; + function Component(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + Component.prototype.isReactComponent = {}; + Component.prototype.setState = function(partialState, callback) { + if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState) + throw Error( + "takes an object of state variables to update or a function which returns an object of state variables." + ); + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + function ComponentDummy() { + } + ComponentDummy.prototype = Component.prototype; + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; + assign(pureComponentPrototype, Component.prototype); + pureComponentPrototype.isPureReactComponent = true; + var isArrayImpl = Array.isArray; + function noop2() { + } + var ReactSharedInternals = { H: null, A: null, T: null, S: null }, hasOwnProperty2 = Object.prototype.hasOwnProperty; + function ReactElement(type, key, props) { + var refProp = props.ref; + return { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + ref: void 0 !== refProp ? refProp : null, + props + }; + } + function cloneAndReplaceKey(oldElement, newKey) { + return ReactElement(oldElement.type, newKey, oldElement.props); + } + function isValidElement(object) { + return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; + } + function escape(key) { + var escaperLookup = { "=": "=0", ":": "=2" }; + return "$" + key.replace(/[=:]/g, function(match) { + return escaperLookup[match]; + }); + } + var userProvidedKeyEscapeRegex = /\/+/g; + function getElementKey(element, index) { + return "object" === typeof element && null !== element && null != element.key ? escape("" + element.key) : index.toString(36); + } + function resolveThenable(thenable) { + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + default: + switch ("string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenable.status = "pending", thenable.then( + function(fulfilledValue) { + "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue); + }, + function(error) { + "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error); + } + )), thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + } + throw thenable; + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if ("undefined" === type || "boolean" === type) children = null; + var invokeCallback = false; + if (null === children) invokeCallback = true; + else + switch (type) { + case "bigint": + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + break; + case REACT_LAZY_TYPE: + return invokeCallback = children._init, mapIntoArray( + invokeCallback(children._payload), + array, + escapedPrefix, + nameSoFar, + callback + ); + } + } + if (invokeCallback) + return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) { + return c; + })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey( + callback, + escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace( + userProvidedKeyEscapeRegex, + "$&/" + ) + "/") + invokeCallback + )), array.push(callback)), 1; + invokeCallback = 0; + var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":"; + if (isArrayImpl(children)) + for (var i = 0; i < children.length; i++) + nameSoFar = children[i], type = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + ); + else if (i = getIteratorFn(children), "function" === typeof i) + for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; ) + nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + ); + else if ("object" === type) { + if ("function" === typeof children.then) + return mapIntoArray( + resolveThenable(children), + array, + escapedPrefix, + nameSoFar, + callback + ); + array = String(children); + throw Error( + "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead." + ); + } + return invokeCallback; + } + function mapChildren2(children, func, context) { + if (null == children) return children; + var result = [], count = 0; + mapIntoArray(children, result, "", "", function(child) { + return func.call(context, child, count++); + }); + return result; + } + function lazyInitializer(payload) { + if (-1 === payload._status) { + var ctor = payload._result; + ctor = ctor(); + ctor.then( + function(moduleObject) { + if (0 === payload._status || -1 === payload._status) + payload._status = 1, payload._result = moduleObject; + }, + function(error) { + if (0 === payload._status || -1 === payload._status) + payload._status = 2, payload._result = error; + } + ); + -1 === payload._status && (payload._status = 0, payload._result = ctor); + } + if (1 === payload._status) return payload._result.default; + throw payload._result; + } + var reportGlobalError = "function" === typeof reportError ? reportError : function(error) { + if ("object" === typeof window && "function" === typeof window.ErrorEvent) { + var event = new window.ErrorEvent("error", { + bubbles: true, + cancelable: true, + message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error), + error + }); + if (!window.dispatchEvent(event)) return; + } else if ("object" === typeof process && "function" === typeof process.emit) { + process.emit("uncaughtException", error); + return; + } + console.error(error); + }, Children = { + map: mapChildren2, + forEach: function(children, forEachFunc, forEachContext) { + mapChildren2( + children, + function() { + forEachFunc.apply(this, arguments); + }, + forEachContext + ); + }, + count: function(children) { + var n = 0; + mapChildren2(children, function() { + n++; + }); + return n; + }, + toArray: function(children) { + return mapChildren2(children, function(child) { + return child; + }) || []; + }, + only: function(children) { + if (!isValidElement(children)) + throw Error( + "React.Children.only expected to receive a single React element child." + ); + return children; + } + }; + react_production.Activity = REACT_ACTIVITY_TYPE; + react_production.Children = Children; + react_production.Component = Component; + react_production.Fragment = REACT_FRAGMENT_TYPE; + react_production.Profiler = REACT_PROFILER_TYPE; + react_production.PureComponent = PureComponent; + react_production.StrictMode = REACT_STRICT_MODE_TYPE; + react_production.Suspense = REACT_SUSPENSE_TYPE; + react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals; + react_production.__COMPILER_RUNTIME = { + __proto__: null, + c: function(size) { + return ReactSharedInternals.H.useMemoCache(size); + } + }; + react_production.cache = function(fn) { + return function() { + return fn.apply(null, arguments); + }; + }; + react_production.cacheSignal = function() { + return null; + }; + react_production.cloneElement = function(element, config, children) { + if (null === element || void 0 === element) + throw Error( + "The argument must be a React element, but you passed " + element + "." + ); + var props = assign({}, element.props), key = element.key; + if (null != config) + for (propName in void 0 !== config.key && (key = "" + config.key), config) + !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]); + var propName = arguments.length - 2; + if (1 === propName) props.children = children; + else if (1 < propName) { + for (var childArray = Array(propName), i = 0; i < propName; i++) + childArray[i] = arguments[i + 2]; + props.children = childArray; + } + return ReactElement(element.type, key, props); + }; + react_production.createContext = function(defaultValue) { + defaultValue = { + $$typeof: REACT_CONTEXT_TYPE, + _currentValue: defaultValue, + _currentValue2: defaultValue, + _threadCount: 0, + Provider: null, + Consumer: null + }; + defaultValue.Provider = defaultValue; + defaultValue.Consumer = { + $$typeof: REACT_CONSUMER_TYPE, + _context: defaultValue + }; + return defaultValue; + }; + react_production.createElement = function(type, config, children) { + var propName, props = {}, key = null; + if (null != config) + for (propName in void 0 !== config.key && (key = "" + config.key), config) + hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config[propName]); + var childrenLength = arguments.length - 2; + if (1 === childrenLength) props.children = children; + else if (1 < childrenLength) { + for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++) + childArray[i] = arguments[i + 2]; + props.children = childArray; + } + if (type && type.defaultProps) + for (propName in childrenLength = type.defaultProps, childrenLength) + void 0 === props[propName] && (props[propName] = childrenLength[propName]); + return ReactElement(type, key, props); + }; + react_production.createRef = function() { + return { current: null }; + }; + react_production.forwardRef = function(render) { + return { $$typeof: REACT_FORWARD_REF_TYPE, render }; + }; + react_production.isValidElement = isValidElement; + react_production.lazy = function(ctor) { + return { + $$typeof: REACT_LAZY_TYPE, + _payload: { _status: -1, _result: ctor }, + _init: lazyInitializer + }; + }; + react_production.memo = function(type, compare) { + return { + $$typeof: REACT_MEMO_TYPE, + type, + compare: void 0 === compare ? null : compare + }; + }; + react_production.startTransition = function(scope) { + var prevTransition = ReactSharedInternals.T, currentTransition = {}; + ReactSharedInternals.T = currentTransition; + try { + var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S; + null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue); + "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop2, reportGlobalError); + } catch (error) { + reportGlobalError(error); + } finally { + null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition; + } + }; + react_production.unstable_useCacheRefresh = function() { + return ReactSharedInternals.H.useCacheRefresh(); + }; + react_production.use = function(usable) { + return ReactSharedInternals.H.use(usable); + }; + react_production.useActionState = function(action, initialState, permalink) { + return ReactSharedInternals.H.useActionState(action, initialState, permalink); + }; + react_production.useCallback = function(callback, deps) { + return ReactSharedInternals.H.useCallback(callback, deps); + }; + react_production.useContext = function(Context) { + return ReactSharedInternals.H.useContext(Context); + }; + react_production.useDebugValue = function() { + }; + react_production.useDeferredValue = function(value, initialValue) { + return ReactSharedInternals.H.useDeferredValue(value, initialValue); + }; + react_production.useEffect = function(create, deps) { + return ReactSharedInternals.H.useEffect(create, deps); + }; + react_production.useEffectEvent = function(callback) { + return ReactSharedInternals.H.useEffectEvent(callback); + }; + react_production.useId = function() { + return ReactSharedInternals.H.useId(); + }; + react_production.useImperativeHandle = function(ref, create, deps) { + return ReactSharedInternals.H.useImperativeHandle(ref, create, deps); + }; + react_production.useInsertionEffect = function(create, deps) { + return ReactSharedInternals.H.useInsertionEffect(create, deps); + }; + react_production.useLayoutEffect = function(create, deps) { + return ReactSharedInternals.H.useLayoutEffect(create, deps); + }; + react_production.useMemo = function(create, deps) { + return ReactSharedInternals.H.useMemo(create, deps); + }; + react_production.useOptimistic = function(passthrough, reducer) { + return ReactSharedInternals.H.useOptimistic(passthrough, reducer); + }; + react_production.useReducer = function(reducer, initialArg, init2) { + return ReactSharedInternals.H.useReducer(reducer, initialArg, init2); + }; + react_production.useRef = function(initialValue) { + return ReactSharedInternals.H.useRef(initialValue); + }; + react_production.useState = function(initialState) { + return ReactSharedInternals.H.useState(initialState); + }; + react_production.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) { + return ReactSharedInternals.H.useSyncExternalStore( + subscribe, + getSnapshot, + getServerSnapshot + ); + }; + react_production.useTransition = function() { + return ReactSharedInternals.H.useTransition(); + }; + react_production.version = "19.2.4"; + return react_production; +} +var react_development = { exports: {} }; +react_development.exports; +var hasRequiredReact_development; +function requireReact_development() { + if (hasRequiredReact_development) return react_development.exports; + hasRequiredReact_development = 1; + (function(module, exports$1) { + "production" !== process.env.NODE_ENV && (function() { + function defineDeprecationWarning(methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function() { + console.warn( + "%s(...) is deprecated in plain JavaScript React classes. %s", + info[0], + info[1] + ); + } + }); + } + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) + return null; + maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + function warnNoop(publicInstance, callerName) { + publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass"; + var warningKey = publicInstance + "." + callerName; + didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error( + "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", + callerName, + publicInstance + ), didWarnStateUpdateForUnmountedComponent[warningKey] = true); + } + function Component(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + function ComponentDummy() { + } + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + function noop2() { + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + try { + testStringCoercion(value); + var JSCompiler_inline_result = false; + } catch (e) { + JSCompiler_inline_result = true; + } + if (JSCompiler_inline_result) { + JSCompiler_inline_result = console; + var JSCompiler_temp_const = JSCompiler_inline_result.error; + var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + JSCompiler_temp_const.call( + JSCompiler_inline_result, + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + JSCompiler_inline_result$jscomp$0 + ); + return testStringCoercion(value); + } + } + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + } + if ("object" === typeof type) + switch ("number" === typeof type.tag && console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), type.$$typeof) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef"); + return type; + case REACT_MEMO_TYPE: + return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) { + } + } + return null; + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE) + return "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function getOwner() { + var dispatcher = ReactSharedInternals.A; + return null === dispatcher ? null : dispatcher.getOwner(); + } + function UnknownOwner() { + return Error("react-stack-top-frame"); + } + function hasValidKey(config) { + if (hasOwnProperty2.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) return false; + } + return void 0 !== config.key; + } + function defineKeyPropWarningGetter(props, displayName) { + function warnAboutAccessingKey() { + specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error( + "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", + displayName + )); + } + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + function elementRefGetterWithDeprecationWarning() { + var componentName = getComponentNameFromType(this.type); + didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error( + "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." + )); + componentName = this.props.ref; + return void 0 !== componentName ? componentName : null; + } + function ReactElement(type, key, props, owner, debugStack, debugTask) { + var refProp = props.ref; + type = { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + props, + _owner: owner + }; + null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", { + enumerable: false, + get: elementRefGetterWithDeprecationWarning + }) : Object.defineProperty(type, "ref", { enumerable: false, value: null }); + type._store = {}; + Object.defineProperty(type._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: 0 + }); + Object.defineProperty(type, "_debugInfo", { + configurable: false, + enumerable: false, + writable: true, + value: null + }); + Object.defineProperty(type, "_debugStack", { + configurable: false, + enumerable: false, + writable: true, + value: debugStack + }); + Object.defineProperty(type, "_debugTask", { + configurable: false, + enumerable: false, + writable: true, + value: debugTask + }); + Object.freeze && (Object.freeze(type.props), Object.freeze(type)); + return type; + } + function cloneAndReplaceKey(oldElement, newKey) { + newKey = ReactElement( + oldElement.type, + newKey, + oldElement.props, + oldElement._owner, + oldElement._debugStack, + oldElement._debugTask + ); + oldElement._store && (newKey._store.validated = oldElement._store.validated); + return newKey; + } + function validateChildKeys(node) { + isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1)); + } + function isValidElement(object) { + return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; + } + function escape(key) { + var escaperLookup = { "=": "=0", ":": "=2" }; + return "$" + key.replace(/[=:]/g, function(match) { + return escaperLookup[match]; + }); + } + function getElementKey(element, index) { + return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36); + } + function resolveThenable(thenable) { + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + default: + switch ("string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenable.status = "pending", thenable.then( + function(fulfilledValue) { + "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue); + }, + function(error) { + "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error); + } + )), thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + } + throw thenable; + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if ("undefined" === type || "boolean" === type) children = null; + var invokeCallback = false; + if (null === children) invokeCallback = true; + else + switch (type) { + case "bigint": + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + break; + case REACT_LAZY_TYPE: + return invokeCallback = children._init, mapIntoArray( + invokeCallback(children._payload), + array, + escapedPrefix, + nameSoFar, + callback + ); + } + } + if (invokeCallback) { + invokeCallback = children; + callback = callback(invokeCallback); + var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar; + isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) { + return c; + })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey( + callback, + escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace( + userProvidedKeyEscapeRegex, + "$&/" + ) + "/") + childKey + ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback)); + return 1; + } + invokeCallback = 0; + childKey = "" === nameSoFar ? "." : nameSoFar + ":"; + if (isArrayImpl(children)) + for (var i = 0; i < children.length; i++) + nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + ); + else if (i = getIteratorFn(children), "function" === typeof i) + for (i === children.entries && (didWarnAboutMaps || console.warn( + "Using Maps as children is not supported. Use an array of keyed ReactElements instead." + ), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; ) + nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + ); + else if ("object" === type) { + if ("function" === typeof children.then) + return mapIntoArray( + resolveThenable(children), + array, + escapedPrefix, + nameSoFar, + callback + ); + array = String(children); + throw Error( + "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead." + ); + } + return invokeCallback; + } + function mapChildren2(children, func, context) { + if (null == children) return children; + var result = [], count = 0; + mapIntoArray(children, result, "", "", function(child) { + return func.call(context, child, count++); + }); + return result; + } + function lazyInitializer(payload) { + if (-1 === payload._status) { + var ioInfo = payload._ioInfo; + null != ioInfo && (ioInfo.start = ioInfo.end = performance.now()); + ioInfo = payload._result; + var thenable = ioInfo(); + thenable.then( + function(moduleObject) { + if (0 === payload._status || -1 === payload._status) { + payload._status = 1; + payload._result = moduleObject; + var _ioInfo = payload._ioInfo; + null != _ioInfo && (_ioInfo.end = performance.now()); + void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject); + } + }, + function(error) { + if (0 === payload._status || -1 === payload._status) { + payload._status = 2; + payload._result = error; + var _ioInfo2 = payload._ioInfo; + null != _ioInfo2 && (_ioInfo2.end = performance.now()); + void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error); + } + } + ); + ioInfo = payload._ioInfo; + if (null != ioInfo) { + ioInfo.value = thenable; + var displayName = thenable.displayName; + "string" === typeof displayName && (ioInfo.name = displayName); + } + -1 === payload._status && (payload._status = 0, payload._result = thenable); + } + if (1 === payload._status) + return ioInfo = payload._result, void 0 === ioInfo && console.error( + "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", + ioInfo + ), "default" in ioInfo || console.error( + "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", + ioInfo + ), ioInfo.default; + throw payload._result; + } + function resolveDispatcher() { + var dispatcher = ReactSharedInternals.H; + null === dispatcher && console.error( + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + return dispatcher; + } + function releaseAsyncTransition() { + ReactSharedInternals.asyncTransitions--; + } + function enqueueTask(task) { + if (null === enqueueTaskImpl) + try { + var requireString = ("require" + Math.random()).slice(0, 7); + enqueueTaskImpl = (module && module[requireString]).call( + module, + "timers" + ).setImmediate; + } catch (_err) { + enqueueTaskImpl = function(callback) { + false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error( + "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning." + )); + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(void 0); + }; + } + return enqueueTaskImpl(task); + } + function aggregateErrors(errors) { + return 1 < errors.length && "function" === typeof AggregateError ? new AggregateError(errors) : errors[0]; + } + function popActScope(prevActQueue, prevActScopeDepth) { + prevActScopeDepth !== actScopeDepth - 1 && console.error( + "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. " + ); + actScopeDepth = prevActScopeDepth; + } + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + var queue = ReactSharedInternals.actQueue; + if (null !== queue) + if (0 !== queue.length) + try { + flushActQueue(queue); + enqueueTask(function() { + return recursivelyFlushAsyncActWork(returnValue, resolve, reject); + }); + return; + } catch (error) { + ReactSharedInternals.thrownErrors.push(error); + } + else ReactSharedInternals.actQueue = null; + 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue); + } + function flushActQueue(queue) { + if (!isFlushing) { + isFlushing = true; + var i = 0; + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + do { + ReactSharedInternals.didUsePromise = false; + var continuation = callback(false); + if (null !== continuation) { + if (ReactSharedInternals.didUsePromise) { + queue[i] = callback; + queue.splice(0, i); + return; + } + callback = continuation; + } else break; + } while (1); + } + queue.length = 0; + } catch (error) { + queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error); + } finally { + isFlushing = false; + } + } + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = { + isMounted: function() { + return false; + }, + enqueueForceUpdate: function(publicInstance) { + warnNoop(publicInstance, "forceUpdate"); + }, + enqueueReplaceState: function(publicInstance) { + warnNoop(publicInstance, "replaceState"); + }, + enqueueSetState: function(publicInstance) { + warnNoop(publicInstance, "setState"); + } + }, assign = Object.assign, emptyObject = {}; + Object.freeze(emptyObject); + Component.prototype.isReactComponent = {}; + Component.prototype.setState = function(partialState, callback) { + if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState) + throw Error( + "takes an object of state variables to update or a function which returns an object of state variables." + ); + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + var deprecatedAPIs = { + isMounted: [ + "isMounted", + "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks." + ], + replaceState: [ + "replaceState", + "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)." + ] + }; + for (fnName in deprecatedAPIs) + deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + ComponentDummy.prototype = Component.prototype; + deprecatedAPIs = PureComponent.prototype = new ComponentDummy(); + deprecatedAPIs.constructor = PureComponent; + assign(deprecatedAPIs, Component.prototype); + deprecatedAPIs.isPureReactComponent = true; + var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = { + H: null, + A: null, + T: null, + S: null, + actQueue: null, + asyncTransitions: 0, + isBatchingLegacy: false, + didScheduleLegacyUpdate: false, + didUsePromise: false, + thrownErrors: [], + getCurrentStack: null, + recentlyCreatedOwnerStacks: 0 + }, hasOwnProperty2 = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() { + return null; + }; + deprecatedAPIs = { + react_stack_bottom_frame: function(callStackForError) { + return callStackForError(); + } + }; + var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime; + var didWarnAboutElementRef = {}; + var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind( + deprecatedAPIs, + UnknownOwner + )(); + var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); + var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error) { + if ("object" === typeof window && "function" === typeof window.ErrorEvent) { + var event = new window.ErrorEvent("error", { + bubbles: true, + cancelable: true, + message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error), + error + }); + if (!window.dispatchEvent(event)) return; + } else if ("object" === typeof process && "function" === typeof process.emit) { + process.emit("uncaughtException", error); + return; + } + console.error(error); + }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) { + queueMicrotask(function() { + return queueMicrotask(callback); + }); + } : enqueueTask; + deprecatedAPIs = Object.freeze({ + __proto__: null, + c: function(size) { + return resolveDispatcher().useMemoCache(size); + } + }); + var fnName = { + map: mapChildren2, + forEach: function(children, forEachFunc, forEachContext) { + mapChildren2( + children, + function() { + forEachFunc.apply(this, arguments); + }, + forEachContext + ); + }, + count: function(children) { + var n = 0; + mapChildren2(children, function() { + n++; + }); + return n; + }, + toArray: function(children) { + return mapChildren2(children, function(child) { + return child; + }) || []; + }, + only: function(children) { + if (!isValidElement(children)) + throw Error( + "React.Children.only expected to receive a single React element child." + ); + return children; + } + }; + exports$1.Activity = REACT_ACTIVITY_TYPE; + exports$1.Children = fnName; + exports$1.Component = Component; + exports$1.Fragment = REACT_FRAGMENT_TYPE; + exports$1.Profiler = REACT_PROFILER_TYPE; + exports$1.PureComponent = PureComponent; + exports$1.StrictMode = REACT_STRICT_MODE_TYPE; + exports$1.Suspense = REACT_SUSPENSE_TYPE; + exports$1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals; + exports$1.__COMPILER_RUNTIME = deprecatedAPIs; + exports$1.act = function(callback) { + var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth; + actScopeDepth++; + var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false; + try { + var result = callback(); + } catch (error) { + ReactSharedInternals.thrownErrors.push(error); + } + if (0 < ReactSharedInternals.thrownErrors.length) + throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback; + if (null !== result && "object" === typeof result && "function" === typeof result.then) { + var thenable = result; + queueSeveralMicrotasks(function() { + didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error( + "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);" + )); + }); + return { + then: function(resolve, reject) { + didAwaitActCall = true; + thenable.then( + function(returnValue) { + popActScope(prevActQueue, prevActScopeDepth); + if (0 === prevActScopeDepth) { + try { + flushActQueue(queue), enqueueTask(function() { + return recursivelyFlushAsyncActWork( + returnValue, + resolve, + reject + ); + }); + } catch (error$0) { + ReactSharedInternals.thrownErrors.push(error$0); + } + if (0 < ReactSharedInternals.thrownErrors.length) { + var _thrownError = aggregateErrors( + ReactSharedInternals.thrownErrors + ); + ReactSharedInternals.thrownErrors.length = 0; + reject(_thrownError); + } + } else resolve(returnValue); + }, + function(error) { + popActScope(prevActQueue, prevActScopeDepth); + 0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors( + ReactSharedInternals.thrownErrors + ), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error); + } + ); + } + }; + } + var returnValue$jscomp$0 = result; + popActScope(prevActQueue, prevActScopeDepth); + 0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() { + didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error( + "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)" + )); + }), ReactSharedInternals.actQueue = null); + if (0 < ReactSharedInternals.thrownErrors.length) + throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback; + return { + then: function(resolve, reject) { + didAwaitActCall = true; + 0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() { + return recursivelyFlushAsyncActWork( + returnValue$jscomp$0, + resolve, + reject + ); + })) : resolve(returnValue$jscomp$0); + } + }; + }; + exports$1.cache = function(fn) { + return function() { + return fn.apply(null, arguments); + }; + }; + exports$1.cacheSignal = function() { + return null; + }; + exports$1.captureOwnerStack = function() { + var getCurrentStack = ReactSharedInternals.getCurrentStack; + return null === getCurrentStack ? null : getCurrentStack(); + }; + exports$1.cloneElement = function(element, config, children) { + if (null === element || void 0 === element) + throw Error( + "The argument must be a React element, but you passed " + element + "." + ); + var props = assign({}, element.props), key = element.key, owner = element._owner; + if (null != config) { + var JSCompiler_inline_result; + a: { + if (hasOwnProperty2.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor( + config, + "ref" + ).get) && JSCompiler_inline_result.isReactWarning) { + JSCompiler_inline_result = false; + break a; + } + JSCompiler_inline_result = void 0 !== config.ref; + } + JSCompiler_inline_result && (owner = getOwner()); + hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key); + for (propName in config) + !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]); + } + var propName = arguments.length - 2; + if (1 === propName) props.children = children; + else if (1 < propName) { + JSCompiler_inline_result = Array(propName); + for (var i = 0; i < propName; i++) + JSCompiler_inline_result[i] = arguments[i + 2]; + props.children = JSCompiler_inline_result; + } + props = ReactElement( + element.type, + key, + props, + owner, + element._debugStack, + element._debugTask + ); + for (key = 2; key < arguments.length; key++) + validateChildKeys(arguments[key]); + return props; + }; + exports$1.createContext = function(defaultValue) { + defaultValue = { + $$typeof: REACT_CONTEXT_TYPE, + _currentValue: defaultValue, + _currentValue2: defaultValue, + _threadCount: 0, + Provider: null, + Consumer: null + }; + defaultValue.Provider = defaultValue; + defaultValue.Consumer = { + $$typeof: REACT_CONSUMER_TYPE, + _context: defaultValue + }; + defaultValue._currentRenderer = null; + defaultValue._currentRenderer2 = null; + return defaultValue; + }; + exports$1.createElement = function(type, config, children) { + for (var i = 2; i < arguments.length; i++) + validateChildKeys(arguments[i]); + i = {}; + var key = null; + if (null != config) + for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn( + "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform" + )), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config) + hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]); + var childrenLength = arguments.length - 2; + if (1 === childrenLength) i.children = children; + else if (1 < childrenLength) { + for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++) + childArray[_i] = arguments[_i + 2]; + Object.freeze && Object.freeze(childArray); + i.children = childArray; + } + if (type && type.defaultProps) + for (propName in childrenLength = type.defaultProps, childrenLength) + void 0 === i[propName] && (i[propName] = childrenLength[propName]); + key && defineKeyPropWarningGetter( + i, + "function" === typeof type ? type.displayName || type.name || "Unknown" : type + ); + var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; + return ReactElement( + type, + key, + i, + getOwner(), + propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack, + propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + exports$1.createRef = function() { + var refObject = { current: null }; + Object.seal(refObject); + return refObject; + }; + exports$1.forwardRef = function(render) { + null != render && render.$$typeof === REACT_MEMO_TYPE ? console.error( + "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))." + ) : "function" !== typeof render ? console.error( + "forwardRef requires a render function but was given %s.", + null === render ? "null" : typeof render + ) : 0 !== render.length && 2 !== render.length && console.error( + "forwardRef render functions accept exactly two parameters: props and ref. %s", + 1 === render.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined." + ); + null != render && null != render.defaultProps && console.error( + "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?" + ); + var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name); + } + }); + return elementType; + }; + exports$1.isValidElement = isValidElement; + exports$1.lazy = function(ctor) { + ctor = { _status: -1, _result: ctor }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: ctor, + _init: lazyInitializer + }, ioInfo = { + name: "lazy", + start: -1, + end: -1, + value: null, + owner: null, + debugStack: Error("react-stack-top-frame"), + debugTask: console.createTask ? console.createTask("lazy()") : null + }; + ctor._ioInfo = ioInfo; + lazyType._debugInfo = [{ awaited: ioInfo }]; + return lazyType; + }; + exports$1.memo = function(type, compare) { + null == type && console.error( + "memo: The first argument must be a component. Instead received: %s", + null === type ? "null" : typeof type + ); + compare = { + $$typeof: REACT_MEMO_TYPE, + type, + compare: void 0 === compare ? null : compare + }; + var ownName; + Object.defineProperty(compare, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name); + } + }); + return compare; + }; + exports$1.startTransition = function(scope) { + var prevTransition = ReactSharedInternals.T, currentTransition = {}; + currentTransition._updatedFibers = /* @__PURE__ */ new Set(); + ReactSharedInternals.T = currentTransition; + try { + var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S; + null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue); + "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop2, reportGlobalError)); + } catch (error) { + reportGlobalError(error); + } finally { + null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn( + "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table." + )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error( + "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React." + ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition; + } + }; + exports$1.unstable_useCacheRefresh = function() { + return resolveDispatcher().useCacheRefresh(); + }; + exports$1.use = function(usable) { + return resolveDispatcher().use(usable); + }; + exports$1.useActionState = function(action, initialState, permalink) { + return resolveDispatcher().useActionState( + action, + initialState, + permalink + ); + }; + exports$1.useCallback = function(callback, deps) { + return resolveDispatcher().useCallback(callback, deps); + }; + exports$1.useContext = function(Context) { + var dispatcher = resolveDispatcher(); + Context.$$typeof === REACT_CONSUMER_TYPE && console.error( + "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?" + ); + return dispatcher.useContext(Context); + }; + exports$1.useDebugValue = function(value, formatterFn) { + return resolveDispatcher().useDebugValue(value, formatterFn); + }; + exports$1.useDeferredValue = function(value, initialValue) { + return resolveDispatcher().useDeferredValue(value, initialValue); + }; + exports$1.useEffect = function(create, deps) { + null == create && console.warn( + "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?" + ); + return resolveDispatcher().useEffect(create, deps); + }; + exports$1.useEffectEvent = function(callback) { + return resolveDispatcher().useEffectEvent(callback); + }; + exports$1.useId = function() { + return resolveDispatcher().useId(); + }; + exports$1.useImperativeHandle = function(ref, create, deps) { + return resolveDispatcher().useImperativeHandle(ref, create, deps); + }; + exports$1.useInsertionEffect = function(create, deps) { + null == create && console.warn( + "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?" + ); + return resolveDispatcher().useInsertionEffect(create, deps); + }; + exports$1.useLayoutEffect = function(create, deps) { + null == create && console.warn( + "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?" + ); + return resolveDispatcher().useLayoutEffect(create, deps); + }; + exports$1.useMemo = function(create, deps) { + return resolveDispatcher().useMemo(create, deps); + }; + exports$1.useOptimistic = function(passthrough, reducer) { + return resolveDispatcher().useOptimistic(passthrough, reducer); + }; + exports$1.useReducer = function(reducer, initialArg, init2) { + return resolveDispatcher().useReducer(reducer, initialArg, init2); + }; + exports$1.useRef = function(initialValue) { + return resolveDispatcher().useRef(initialValue); + }; + exports$1.useState = function(initialState) { + return resolveDispatcher().useState(initialState); + }; + exports$1.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) { + return resolveDispatcher().useSyncExternalStore( + subscribe, + getSnapshot, + getServerSnapshot + ); + }; + exports$1.useTransition = function() { + return resolveDispatcher().useTransition(); + }; + exports$1.version = "19.2.4"; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + })(react_development, react_development.exports); + return react_development.exports; +} +var hasRequiredReact; +function requireReact() { + if (hasRequiredReact) return react.exports; + hasRequiredReact = 1; + if (process.env.NODE_ENV === "production") { + react.exports = requireReact_production(); + } else { + react.exports = requireReact_development(); + } + return react.exports; +} +var reactExports = requireReact(); +const React = /* @__PURE__ */ getDefaultExportFromCjs(reactExports); +var reactDom = { exports: {} }; +var reactDom_production = {}; +var hasRequiredReactDom_production; +function requireReactDom_production() { + if (hasRequiredReactDom_production) return reactDom_production; + hasRequiredReactDom_production = 1; + var React2 = requireReact(); + function formatProdErrorMessage(code) { + var url = "https://react.dev/errors/" + code; + if (1 < arguments.length) { + url += "?args[]=" + encodeURIComponent(arguments[1]); + for (var i = 2; i < arguments.length; i++) + url += "&args[]=" + encodeURIComponent(arguments[i]); + } + return "Minified React error #" + code + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; + } + function noop2() { + } + var Internals = { + d: { + f: noop2, + r: function() { + throw Error(formatProdErrorMessage(522)); + }, + D: noop2, + C: noop2, + L: noop2, + m: noop2, + X: noop2, + S: noop2, + M: noop2 + }, + p: 0, + findDOMNode: null + }, REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"); + function createPortal$1(children, containerInfo, implementation) { + var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null; + return { + $$typeof: REACT_PORTAL_TYPE, + key: null == key ? null : "" + key, + children, + containerInfo, + implementation + }; + } + var ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + function getCrossOriginStringAs(as, input) { + if ("font" === as) return ""; + if ("string" === typeof input) + return "use-credentials" === input ? input : ""; + } + reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals; + reactDom_production.createPortal = function(children, container) { + var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null; + if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType) + throw Error(formatProdErrorMessage(299)); + return createPortal$1(children, container, null, key); + }; + reactDom_production.flushSync = function(fn) { + var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p; + try { + if (ReactSharedInternals.T = null, Internals.p = 2, fn) return fn(); + } finally { + ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f(); + } + }; + reactDom_production.preconnect = function(href, options) { + "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options)); + }; + reactDom_production.prefetchDNS = function(href) { + "string" === typeof href && Internals.d.D(href); + }; + reactDom_production.preinit = function(href, options) { + if ("string" === typeof href && options && "string" === typeof options.as) { + var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0; + "style" === as ? Internals.d.S( + href, + "string" === typeof options.precedence ? options.precedence : void 0, + { + crossOrigin, + integrity, + fetchPriority + } + ) : "script" === as && Internals.d.X(href, { + crossOrigin, + integrity, + fetchPriority, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } + }; + reactDom_production.preinitModule = function(href, options) { + if ("string" === typeof href) + if ("object" === typeof options && null !== options) { + if (null == options.as || "script" === options.as) { + var crossOrigin = getCrossOriginStringAs( + options.as, + options.crossOrigin + ); + Internals.d.M(href, { + crossOrigin, + integrity: "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } + } else null == options && Internals.d.M(href); + }; + reactDom_production.preload = function(href, options) { + if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) { + var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); + Internals.d.L(href, as, { + crossOrigin, + integrity: "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + type: "string" === typeof options.type ? options.type : void 0, + fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0, + referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0, + imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, + imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0, + media: "string" === typeof options.media ? options.media : void 0 + }); + } + }; + reactDom_production.preloadModule = function(href, options) { + if ("string" === typeof href) + if (options) { + var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin); + Internals.d.m(href, { + as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0, + crossOrigin, + integrity: "string" === typeof options.integrity ? options.integrity : void 0 + }); + } else Internals.d.m(href); + }; + reactDom_production.requestFormReset = function(form) { + Internals.d.r(form); + }; + reactDom_production.unstable_batchedUpdates = function(fn, a) { + return fn(a); + }; + reactDom_production.useFormState = function(action, initialState, permalink) { + return ReactSharedInternals.H.useFormState(action, initialState, permalink); + }; + reactDom_production.useFormStatus = function() { + return ReactSharedInternals.H.useHostTransitionStatus(); + }; + reactDom_production.version = "19.2.4"; + return reactDom_production; +} +var reactDom_development = {}; +var hasRequiredReactDom_development; +function requireReactDom_development() { + if (hasRequiredReactDom_development) return reactDom_development; + hasRequiredReactDom_development = 1; + "production" !== process.env.NODE_ENV && (function() { + function noop2() { + } + function testStringCoercion(value) { + return "" + value; + } + function createPortal$1(children, containerInfo, implementation) { + var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null; + try { + testStringCoercion(key); + var JSCompiler_inline_result = false; + } catch (e) { + JSCompiler_inline_result = true; + } + JSCompiler_inline_result && (console.error( + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + "function" === typeof Symbol && Symbol.toStringTag && key[Symbol.toStringTag] || key.constructor.name || "Object" + ), testStringCoercion(key)); + return { + $$typeof: REACT_PORTAL_TYPE, + key: null == key ? null : "" + key, + children, + containerInfo, + implementation + }; + } + function getCrossOriginStringAs(as, input) { + if ("font" === as) return ""; + if ("string" === typeof input) + return "use-credentials" === input ? input : ""; + } + function getValueDescriptorExpectingObjectForWarning(thing) { + return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : 'something with type "' + typeof thing + '"'; + } + function getValueDescriptorExpectingEnumForWarning(thing) { + return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : "string" === typeof thing ? JSON.stringify(thing) : "number" === typeof thing ? "`" + thing + "`" : 'something with type "' + typeof thing + '"'; + } + function resolveDispatcher() { + var dispatcher = ReactSharedInternals.H; + null === dispatcher && console.error( + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + return dispatcher; + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var React2 = requireReact(), Internals = { + d: { + f: noop2, + r: function() { + throw Error( + "Invalid form element. requestFormReset must be passed a form that was rendered by React." + ); + }, + D: noop2, + C: noop2, + L: noop2, + m: noop2, + X: noop2, + S: noop2, + M: noop2 + }, + p: 0, + findDOMNode: null + }, REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error( + "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills" + ); + reactDom_development.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals; + reactDom_development.createPortal = function(children, container) { + var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null; + if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType) + throw Error("Target container is not a DOM element."); + return createPortal$1(children, container, null, key); + }; + reactDom_development.flushSync = function(fn) { + var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p; + try { + if (ReactSharedInternals.T = null, Internals.p = 2, fn) + return fn(); + } finally { + ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f() && console.error( + "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task." + ); + } + }; + reactDom_development.preconnect = function(href, options) { + "string" === typeof href && href ? null != options && "object" !== typeof options ? console.error( + "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.", + getValueDescriptorExpectingEnumForWarning(options) + ) : null != options && "string" !== typeof options.crossOrigin && console.error( + "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.", + getValueDescriptorExpectingObjectForWarning(options.crossOrigin) + ) : console.error( + "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options)); + }; + reactDom_development.prefetchDNS = function(href) { + if ("string" !== typeof href || !href) + console.error( + "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + else if (1 < arguments.length) { + var options = arguments[1]; + "object" === typeof options && options.hasOwnProperty("crossOrigin") ? console.error( + "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", + getValueDescriptorExpectingEnumForWarning(options) + ) : console.error( + "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", + getValueDescriptorExpectingEnumForWarning(options) + ); + } + "string" === typeof href && Internals.d.D(href); + }; + reactDom_development.preinit = function(href, options) { + "string" === typeof href && href ? null == options || "object" !== typeof options ? console.error( + "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.", + getValueDescriptorExpectingEnumForWarning(options) + ) : "style" !== options.as && "script" !== options.as && console.error( + 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".', + getValueDescriptorExpectingEnumForWarning(options.as) + ) : console.error( + "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + if ("string" === typeof href && options && "string" === typeof options.as) { + var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0; + "style" === as ? Internals.d.S( + href, + "string" === typeof options.precedence ? options.precedence : void 0, + { + crossOrigin, + integrity, + fetchPriority + } + ) : "script" === as && Internals.d.X(href, { + crossOrigin, + integrity, + fetchPriority, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } + }; + reactDom_development.preinitModule = function(href, options) { + var encountered = ""; + "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + "."); + void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "script" !== options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingEnumForWarning(options.as) + "."); + if (encountered) + console.error( + "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s", + encountered + ); + else + switch (encountered = options && "string" === typeof options.as ? options.as : "script", encountered) { + case "script": + break; + default: + encountered = getValueDescriptorExpectingEnumForWarning(encountered), console.error( + 'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)', + encountered, + href + ); + } + if ("string" === typeof href) + if ("object" === typeof options && null !== options) { + if (null == options.as || "script" === options.as) + encountered = getCrossOriginStringAs( + options.as, + options.crossOrigin + ), Internals.d.M(href, { + crossOrigin: encountered, + integrity: "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } else null == options && Internals.d.M(href); + }; + reactDom_development.preload = function(href, options) { + var encountered = ""; + "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + "."); + null == options || "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : "string" === typeof options.as && options.as || (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + "."); + encountered && console.error( + 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `` tag.%s', + encountered + ); + if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) { + encountered = options.as; + var crossOrigin = getCrossOriginStringAs( + encountered, + options.crossOrigin + ); + Internals.d.L(href, encountered, { + crossOrigin, + integrity: "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + type: "string" === typeof options.type ? options.type : void 0, + fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0, + referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0, + imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, + imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0, + media: "string" === typeof options.media ? options.media : void 0 + }); + } + }; + reactDom_development.preloadModule = function(href, options) { + var encountered = ""; + "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + "."); + void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "string" !== typeof options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + "."); + encountered && console.error( + 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `` tag.%s', + encountered + ); + "string" === typeof href && (options ? (encountered = getCrossOriginStringAs( + options.as, + options.crossOrigin + ), Internals.d.m(href, { + as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0, + crossOrigin: encountered, + integrity: "string" === typeof options.integrity ? options.integrity : void 0 + })) : Internals.d.m(href)); + }; + reactDom_development.requestFormReset = function(form) { + Internals.d.r(form); + }; + reactDom_development.unstable_batchedUpdates = function(fn, a) { + return fn(a); + }; + reactDom_development.useFormState = function(action, initialState, permalink) { + return resolveDispatcher().useFormState(action, initialState, permalink); + }; + reactDom_development.useFormStatus = function() { + return resolveDispatcher().useHostTransitionStatus(); + }; + reactDom_development.version = "19.2.4"; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + return reactDom_development; +} +var hasRequiredReactDom; +function requireReactDom() { + if (hasRequiredReactDom) return reactDom.exports; + hasRequiredReactDom = 1; + function checkDCE() { + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") { + return; + } + if (process.env.NODE_ENV !== "production") { + throw new Error("^_^"); + } + try { + __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); + } catch (err) { + console.error(err); + } + } + if (process.env.NODE_ENV === "production") { + checkDCE(); + reactDom.exports = requireReactDom_production(); + } else { + reactDom.exports = requireReactDom_development(); + } + return reactDom.exports; +} +var reactDomExports = requireReactDom(); +const ReactDOM = /* @__PURE__ */ getDefaultExportFromCjs(reactDomExports); +var shim = { exports: {} }; +var useSyncExternalStoreShim_production = {}; +var hasRequiredUseSyncExternalStoreShim_production; +function requireUseSyncExternalStoreShim_production() { + if (hasRequiredUseSyncExternalStoreShim_production) return useSyncExternalStoreShim_production; + hasRequiredUseSyncExternalStoreShim_production = 1; + var React2 = requireReact(); + function is(x, y) { + return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; + } + var objectIs = "function" === typeof Object.is ? Object.is : is, useState = React2.useState, useEffect = React2.useEffect, useLayoutEffect = React2.useLayoutEffect, useDebugValue = React2.useDebugValue; + function useSyncExternalStore$2(subscribe, getSnapshot) { + var value = getSnapshot(), _useState = useState({ inst: { value, getSnapshot } }), inst = _useState[0].inst, forceUpdate = _useState[1]; + useLayoutEffect( + function() { + inst.value = value; + inst.getSnapshot = getSnapshot; + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + }, + [subscribe, value, getSnapshot] + ); + useEffect( + function() { + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + return subscribe(function() { + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + }); + }, + [subscribe] + ); + useDebugValue(value); + return value; + } + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + inst = inst.value; + try { + var nextValue = latestGetSnapshot(); + return !objectIs(inst, nextValue); + } catch (error) { + return true; + } + } + function useSyncExternalStore$1(subscribe, getSnapshot) { + return getSnapshot(); + } + var shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; + useSyncExternalStoreShim_production.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim2; + return useSyncExternalStoreShim_production; +} +var useSyncExternalStoreShim_development = {}; +var hasRequiredUseSyncExternalStoreShim_development; +function requireUseSyncExternalStoreShim_development() { + if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development; + hasRequiredUseSyncExternalStoreShim_development = 1; + "production" !== process.env.NODE_ENV && (function() { + function is(x, y) { + return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; + } + function useSyncExternalStore$2(subscribe, getSnapshot) { + didWarnOld18Alpha || void 0 === React2.startTransition || (didWarnOld18Alpha = true, console.error( + "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." + )); + var value = getSnapshot(); + if (!didWarnUncachedGetSnapshot) { + var cachedValue = getSnapshot(); + objectIs(value, cachedValue) || (console.error( + "The result of getSnapshot should be cached to avoid an infinite loop" + ), didWarnUncachedGetSnapshot = true); + } + cachedValue = useState({ + inst: { value, getSnapshot } + }); + var inst = cachedValue[0].inst, forceUpdate = cachedValue[1]; + useLayoutEffect( + function() { + inst.value = value; + inst.getSnapshot = getSnapshot; + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + }, + [subscribe, value, getSnapshot] + ); + useEffect( + function() { + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + return subscribe(function() { + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + }); + }, + [subscribe] + ); + useDebugValue(value); + return value; + } + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + inst = inst.value; + try { + var nextValue = latestGetSnapshot(); + return !objectIs(inst, nextValue); + } catch (error) { + return true; + } + } + function useSyncExternalStore$1(subscribe, getSnapshot) { + return getSnapshot(); + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var React2 = requireReact(), objectIs = "function" === typeof Object.is ? Object.is : is, useState = React2.useState, useEffect = React2.useEffect, useLayoutEffect = React2.useLayoutEffect, useDebugValue = React2.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; + useSyncExternalStoreShim_development.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim2; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + return useSyncExternalStoreShim_development; +} +var hasRequiredShim; +function requireShim() { + if (hasRequiredShim) return shim.exports; + hasRequiredShim = 1; + if (process.env.NODE_ENV === "production") { + shim.exports = requireUseSyncExternalStoreShim_production(); + } else { + shim.exports = requireUseSyncExternalStoreShim_development(); + } + return shim.exports; +} +var shimExports = requireShim(); +var jsxRuntime = { exports: {} }; +var reactJsxRuntime_production = {}; +var hasRequiredReactJsxRuntime_production; +function requireReactJsxRuntime_production() { + if (hasRequiredReactJsxRuntime_production) return reactJsxRuntime_production; + hasRequiredReactJsxRuntime_production = 1; + var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"); + function jsxProd(type, config, maybeKey) { + var key = null; + void 0 !== maybeKey && (key = "" + maybeKey); + void 0 !== config.key && (key = "" + config.key); + if ("key" in config) { + maybeKey = {}; + for (var propName in config) + "key" !== propName && (maybeKey[propName] = config[propName]); + } else maybeKey = config; + config = maybeKey.ref; + return { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + ref: void 0 !== config ? config : null, + props: maybeKey + }; + } + reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE; + reactJsxRuntime_production.jsx = jsxProd; + reactJsxRuntime_production.jsxs = jsxProd; + return reactJsxRuntime_production; +} +var reactJsxRuntime_development = {}; +var hasRequiredReactJsxRuntime_development; +function requireReactJsxRuntime_development() { + if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development; + hasRequiredReactJsxRuntime_development = 1; + "production" !== process.env.NODE_ENV && (function() { + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + } + if ("object" === typeof type) + switch ("number" === typeof type.tag && console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), type.$$typeof) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef"); + return type; + case REACT_MEMO_TYPE: + return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) { + } + } + return null; + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + try { + testStringCoercion(value); + var JSCompiler_inline_result = false; + } catch (e) { + JSCompiler_inline_result = true; + } + if (JSCompiler_inline_result) { + JSCompiler_inline_result = console; + var JSCompiler_temp_const = JSCompiler_inline_result.error; + var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + JSCompiler_temp_const.call( + JSCompiler_inline_result, + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + JSCompiler_inline_result$jscomp$0 + ); + return testStringCoercion(value); + } + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE) + return "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function getOwner() { + var dispatcher = ReactSharedInternals.A; + return null === dispatcher ? null : dispatcher.getOwner(); + } + function UnknownOwner() { + return Error("react-stack-top-frame"); + } + function hasValidKey(config) { + if (hasOwnProperty2.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) return false; + } + return void 0 !== config.key; + } + function defineKeyPropWarningGetter(props, displayName) { + function warnAboutAccessingKey() { + specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error( + "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", + displayName + )); + } + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + function elementRefGetterWithDeprecationWarning() { + var componentName = getComponentNameFromType(this.type); + didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error( + "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." + )); + componentName = this.props.ref; + return void 0 !== componentName ? componentName : null; + } + function ReactElement(type, key, props, owner, debugStack, debugTask) { + var refProp = props.ref; + type = { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + props, + _owner: owner + }; + null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", { + enumerable: false, + get: elementRefGetterWithDeprecationWarning + }) : Object.defineProperty(type, "ref", { enumerable: false, value: null }); + type._store = {}; + Object.defineProperty(type._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: 0 + }); + Object.defineProperty(type, "_debugInfo", { + configurable: false, + enumerable: false, + writable: true, + value: null + }); + Object.defineProperty(type, "_debugStack", { + configurable: false, + enumerable: false, + writable: true, + value: debugStack + }); + Object.defineProperty(type, "_debugTask", { + configurable: false, + enumerable: false, + writable: true, + value: debugTask + }); + Object.freeze && (Object.freeze(type.props), Object.freeze(type)); + return type; + } + function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) { + var children = config.children; + if (void 0 !== children) + if (isStaticChildren) + if (isArrayImpl(children)) { + for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++) + validateChildKeys(children[isStaticChildren]); + Object.freeze && Object.freeze(children); + } else + console.error( + "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." + ); + else validateChildKeys(children); + if (hasOwnProperty2.call(config, "key")) { + children = getComponentNameFromType(type); + var keys2 = Object.keys(config).filter(function(k) { + return "key" !== k; + }); + isStaticChildren = 0 < keys2.length ? "{key: someKey, " + keys2.join(": ..., ") + ": ...}" : "{key: someKey}"; + didWarnAboutKeySpread[children + isStaticChildren] || (keys2 = 0 < keys2.length ? "{" + keys2.join(": ..., ") + ": ...}" : "{}", console.error( + 'A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', + isStaticChildren, + children, + keys2, + children + ), didWarnAboutKeySpread[children + isStaticChildren] = true); + } + children = null; + void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey); + hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key); + if ("key" in config) { + maybeKey = {}; + for (var propName in config) + "key" !== propName && (maybeKey[propName] = config[propName]); + } else maybeKey = config; + children && defineKeyPropWarningGetter( + maybeKey, + "function" === typeof type ? type.displayName || type.name || "Unknown" : type + ); + return ReactElement( + type, + children, + maybeKey, + getOwner(), + debugStack, + debugTask + ); + } + function validateChildKeys(node) { + isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1)); + } + function isValidElement(object) { + return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; + } + var React2 = requireReact(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty2 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() { + return null; + }; + React2 = { + react_stack_bottom_frame: function(callStackForError) { + return callStackForError(); + } + }; + var specialPropKeyWarningShown; + var didWarnAboutElementRef = {}; + var unknownOwnerDebugStack = React2.react_stack_bottom_frame.bind( + React2, + UnknownOwner + )(); + var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); + var didWarnAboutKeySpread = {}; + reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE; + reactJsxRuntime_development.jsx = function(type, config, maybeKey) { + var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; + return jsxDEVImpl( + type, + config, + maybeKey, + false, + trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + reactJsxRuntime_development.jsxs = function(type, config, maybeKey) { + var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; + return jsxDEVImpl( + type, + config, + maybeKey, + true, + trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + })(); + return reactJsxRuntime_development; +} +var hasRequiredJsxRuntime; +function requireJsxRuntime() { + if (hasRequiredJsxRuntime) return jsxRuntime.exports; + hasRequiredJsxRuntime = 1; + if (process.env.NODE_ENV === "production") { + jsxRuntime.exports = requireReactJsxRuntime_production(); + } else { + jsxRuntime.exports = requireReactJsxRuntime_development(); + } + return jsxRuntime.exports; +} +var jsxRuntimeExports = requireJsxRuntime(); +function OrderedMap(content) { + this.content = content; +} +OrderedMap.prototype = { + constructor: OrderedMap, + find: function(key) { + for (var i = 0; i < this.content.length; i += 2) + if (this.content[i] === key) return i; + return -1; + }, + // :: (string) → ?any + // Retrieve the value stored under `key`, or return undefined when + // no such key exists. + get: function(key) { + var found2 = this.find(key); + return found2 == -1 ? void 0 : this.content[found2 + 1]; + }, + // :: (string, any, ?string) → OrderedMap + // Create a new map by replacing the value of `key` with a new + // value, or adding a binding to the end of the map. If `newKey` is + // given, the key of the binding will be replaced with that key. + update: function(key, value, newKey) { + var self2 = newKey && newKey != key ? this.remove(newKey) : this; + var found2 = self2.find(key), content = self2.content.slice(); + if (found2 == -1) { + content.push(newKey || key, value); + } else { + content[found2 + 1] = value; + if (newKey) content[found2] = newKey; + } + return new OrderedMap(content); + }, + // :: (string) → OrderedMap + // Return a map with the given key removed, if it existed. + remove: function(key) { + var found2 = this.find(key); + if (found2 == -1) return this; + var content = this.content.slice(); + content.splice(found2, 2); + return new OrderedMap(content); + }, + // :: (string, any) → OrderedMap + // Add a new key to the start of the map. + addToStart: function(key, value) { + return new OrderedMap([key, value].concat(this.remove(key).content)); + }, + // :: (string, any) → OrderedMap + // Add a new key to the end of the map. + addToEnd: function(key, value) { + var content = this.remove(key).content.slice(); + content.push(key, value); + return new OrderedMap(content); + }, + // :: (string, string, any) → OrderedMap + // Add a key after the given key. If `place` is not found, the new + // key is added to the end. + addBefore: function(place, key, value) { + var without = this.remove(key), content = without.content.slice(); + var found2 = without.find(place); + content.splice(found2 == -1 ? content.length : found2, 0, key, value); + return new OrderedMap(content); + }, + // :: ((key: string, value: any)) + // Call the given function for each key/value pair in the map, in + // order. + forEach: function(f) { + for (var i = 0; i < this.content.length; i += 2) + f(this.content[i], this.content[i + 1]); + }, + // :: (union) → OrderedMap + // Create a new map by prepending the keys in this map that don't + // appear in `map` before the keys in `map`. + prepend: function(map2) { + map2 = OrderedMap.from(map2); + if (!map2.size) return this; + return new OrderedMap(map2.content.concat(this.subtract(map2).content)); + }, + // :: (union) → OrderedMap + // Create a new map by appending the keys in this map that don't + // appear in `map` after the keys in `map`. + append: function(map2) { + map2 = OrderedMap.from(map2); + if (!map2.size) return this; + return new OrderedMap(this.subtract(map2).content.concat(map2.content)); + }, + // :: (union) → OrderedMap + // Create a map containing all the keys in this map that don't + // appear in `map`. + subtract: function(map2) { + var result = this; + map2 = OrderedMap.from(map2); + for (var i = 0; i < map2.content.length; i += 2) + result = result.remove(map2.content[i]); + return result; + }, + // :: () → Object + // Turn ordered map into a plain object. + toObject: function() { + var result = {}; + this.forEach(function(key, value) { + result[key] = value; + }); + return result; + }, + // :: number + // The amount of keys in this map. + get size() { + return this.content.length >> 1; + } +}; +OrderedMap.from = function(value) { + if (value instanceof OrderedMap) return value; + var content = []; + if (value) for (var prop in value) content.push(prop, value[prop]); + return new OrderedMap(content); +}; +function findDiffStart(a, b, pos) { + for (let i = 0; ; i++) { + if (i == a.childCount || i == b.childCount) + return a.childCount == b.childCount ? null : pos; + let childA = a.child(i), childB = b.child(i); + if (childA == childB) { + pos += childA.nodeSize; + continue; + } + if (!childA.sameMarkup(childB)) + return pos; + if (childA.isText && childA.text != childB.text) { + for (let j = 0; childA.text[j] == childB.text[j]; j++) + pos++; + return pos; + } + if (childA.content.size || childB.content.size) { + let inner = findDiffStart(childA.content, childB.content, pos + 1); + if (inner != null) + return inner; + } + pos += childA.nodeSize; + } +} +function findDiffEnd(a, b, posA, posB) { + for (let iA = a.childCount, iB = b.childCount; ; ) { + if (iA == 0 || iB == 0) + return iA == iB ? null : { a: posA, b: posB }; + let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; + if (childA == childB) { + posA -= size; + posB -= size; + continue; + } + if (!childA.sameMarkup(childB)) + return { a: posA, b: posB }; + if (childA.isText && childA.text != childB.text) { + let same = 0, minSize = Math.min(childA.text.length, childB.text.length); + while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { + same++; + posA--; + posB--; + } + return { a: posA, b: posB }; + } + if (childA.content.size || childB.content.size) { + let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); + if (inner) + return inner; + } + posA -= size; + posB -= size; + } +} +class Fragment { + /** + @internal + */ + constructor(content, size) { + this.content = content; + this.size = size || 0; + if (size == null) + for (let i = 0; i < content.length; i++) + this.size += content[i].nodeSize; + } + /** + Invoke a callback for all descendant nodes between the given two + positions (relative to start of this fragment). Doesn't descend + into a node when the callback returns `false`. + */ + nodesBetween(from2, to, f, nodeStart = 0, parent) { + for (let i = 0, pos = 0; pos < to; i++) { + let child = this.content[i], end = pos + child.nodeSize; + if (end > from2 && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) { + let start = pos + 1; + child.nodesBetween(Math.max(0, from2 - start), Math.min(child.content.size, to - start), f, nodeStart + start); + } + pos = end; + } + } + /** + Call the given callback for every descendant node. `pos` will be + relative to the start of the fragment. The callback may return + `false` to prevent traversal of a given node's children. + */ + descendants(f) { + this.nodesBetween(0, this.size, f); + } + /** + Extract the text between `from` and `to`. See the same method on + [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween). + */ + textBetween(from2, to, blockSeparator, leafText) { + let text = "", first2 = true; + this.nodesBetween(from2, to, (node, pos) => { + let nodeText = node.isText ? node.text.slice(Math.max(from2, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : ""; + if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) { + if (first2) + first2 = false; + else + text += blockSeparator; + } + text += nodeText; + }, 0); + return text; + } + /** + Create a new fragment containing the combined content of this + fragment and the other. + */ + append(other) { + if (!other.size) + return this; + if (!this.size) + return other; + let last = this.lastChild, first2 = other.firstChild, content = this.content.slice(), i = 0; + if (last.isText && last.sameMarkup(first2)) { + content[content.length - 1] = last.withText(last.text + first2.text); + i = 1; + } + for (; i < other.content.length; i++) + content.push(other.content[i]); + return new Fragment(content, this.size + other.size); + } + /** + Cut out the sub-fragment between the two given positions. + */ + cut(from2, to = this.size) { + if (from2 == 0 && to == this.size) + return this; + let result = [], size = 0; + if (to > from2) + for (let i = 0, pos = 0; pos < to; i++) { + let child = this.content[i], end = pos + child.nodeSize; + if (end > from2) { + if (pos < from2 || end > to) { + if (child.isText) + child = child.cut(Math.max(0, from2 - pos), Math.min(child.text.length, to - pos)); + else + child = child.cut(Math.max(0, from2 - pos - 1), Math.min(child.content.size, to - pos - 1)); + } + result.push(child); + size += child.nodeSize; + } + pos = end; + } + return new Fragment(result, size); + } + /** + @internal + */ + cutByIndex(from2, to) { + if (from2 == to) + return Fragment.empty; + if (from2 == 0 && to == this.content.length) + return this; + return new Fragment(this.content.slice(from2, to)); + } + /** + Create a new fragment in which the node at the given index is + replaced by the given node. + */ + replaceChild(index, node) { + let current = this.content[index]; + if (current == node) + return this; + let copy2 = this.content.slice(); + let size = this.size + node.nodeSize - current.nodeSize; + copy2[index] = node; + return new Fragment(copy2, size); + } + /** + Create a new fragment by prepending the given node to this + fragment. + */ + addToStart(node) { + return new Fragment([node].concat(this.content), this.size + node.nodeSize); + } + /** + Create a new fragment by appending the given node to this + fragment. + */ + addToEnd(node) { + return new Fragment(this.content.concat(node), this.size + node.nodeSize); + } + /** + Compare this fragment to another one. + */ + eq(other) { + if (this.content.length != other.content.length) + return false; + for (let i = 0; i < this.content.length; i++) + if (!this.content[i].eq(other.content[i])) + return false; + return true; + } + /** + The first child of the fragment, or `null` if it is empty. + */ + get firstChild() { + return this.content.length ? this.content[0] : null; + } + /** + The last child of the fragment, or `null` if it is empty. + */ + get lastChild() { + return this.content.length ? this.content[this.content.length - 1] : null; + } + /** + The number of child nodes in this fragment. + */ + get childCount() { + return this.content.length; + } + /** + Get the child node at the given index. Raise an error when the + index is out of range. + */ + child(index) { + let found2 = this.content[index]; + if (!found2) + throw new RangeError("Index " + index + " out of range for " + this); + return found2; + } + /** + Get the child node at the given index, if it exists. + */ + maybeChild(index) { + return this.content[index] || null; + } + /** + Call `f` for every child node, passing the node, its offset + into this parent node, and its index. + */ + forEach(f) { + for (let i = 0, p = 0; i < this.content.length; i++) { + let child = this.content[i]; + f(child, p, i); + p += child.nodeSize; + } + } + /** + Find the first position at which this fragment and another + fragment differ, or `null` if they are the same. + */ + findDiffStart(other, pos = 0) { + return findDiffStart(this, other, pos); + } + /** + Find the first position, searching from the end, at which this + fragment and the given fragment differ, or `null` if they are + the same. Since this position will not be the same in both + nodes, an object with two separate positions is returned. + */ + findDiffEnd(other, pos = this.size, otherPos = other.size) { + return findDiffEnd(this, other, pos, otherPos); + } + /** + Find the index and inner offset corresponding to a given relative + position in this fragment. The result object will be reused + (overwritten) the next time the function is called. @internal + */ + findIndex(pos) { + if (pos == 0) + return retIndex(0, pos); + if (pos == this.size) + return retIndex(this.content.length, pos); + if (pos > this.size || pos < 0) + throw new RangeError(`Position ${pos} outside of fragment (${this})`); + for (let i = 0, curPos = 0; ; i++) { + let cur = this.child(i), end = curPos + cur.nodeSize; + if (end >= pos) { + if (end == pos) + return retIndex(i + 1, end); + return retIndex(i, curPos); + } + curPos = end; + } + } + /** + Return a debugging string that describes this fragment. + */ + toString() { + return "<" + this.toStringInner() + ">"; + } + /** + @internal + */ + toStringInner() { + return this.content.join(", "); + } + /** + Create a JSON-serializeable representation of this fragment. + */ + toJSON() { + return this.content.length ? this.content.map((n) => n.toJSON()) : null; + } + /** + Deserialize a fragment from its JSON representation. + */ + static fromJSON(schema, value) { + if (!value) + return Fragment.empty; + if (!Array.isArray(value)) + throw new RangeError("Invalid input for Fragment.fromJSON"); + return new Fragment(value.map(schema.nodeFromJSON)); + } + /** + Build a fragment from an array of nodes. Ensures that adjacent + text nodes with the same marks are joined together. + */ + static fromArray(array) { + if (!array.length) + return Fragment.empty; + let joined, size = 0; + for (let i = 0; i < array.length; i++) { + let node = array[i]; + size += node.nodeSize; + if (i && node.isText && array[i - 1].sameMarkup(node)) { + if (!joined) + joined = array.slice(0, i); + joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); + } else if (joined) { + joined.push(node); + } + } + return new Fragment(joined || array, size); + } + /** + Create a fragment from something that can be interpreted as a + set of nodes. For `null`, it returns the empty fragment. For a + fragment, the fragment itself. For a node or array of nodes, a + fragment containing those nodes. + */ + static from(nodes) { + if (!nodes) + return Fragment.empty; + if (nodes instanceof Fragment) + return nodes; + if (Array.isArray(nodes)) + return this.fromArray(nodes); + if (nodes.attrs) + return new Fragment([nodes], nodes.nodeSize); + throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")); + } +} +Fragment.empty = new Fragment([], 0); +const found = { index: 0, offset: 0 }; +function retIndex(index, offset) { + found.index = index; + found.offset = offset; + return found; +} +function compareDeep(a, b) { + if (a === b) + return true; + if (!(a && typeof a == "object") || !(b && typeof b == "object")) + return false; + let array = Array.isArray(a); + if (Array.isArray(b) != array) + return false; + if (array) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!compareDeep(a[i], b[i])) + return false; + } else { + for (let p in a) + if (!(p in b) || !compareDeep(a[p], b[p])) + return false; + for (let p in b) + if (!(p in a)) + return false; + } + return true; +} +let Mark$1 = class Mark { + /** + @internal + */ + constructor(type, attrs) { + this.type = type; + this.attrs = attrs; + } + /** + Given a set of marks, create a new set which contains this one as + well, in the right position. If this mark is already in the set, + the set itself is returned. If any marks that are set to be + [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present, + those are replaced by this one. + */ + addToSet(set) { + let copy2, placed = false; + for (let i = 0; i < set.length; i++) { + let other = set[i]; + if (this.eq(other)) + return set; + if (this.type.excludes(other.type)) { + if (!copy2) + copy2 = set.slice(0, i); + } else if (other.type.excludes(this.type)) { + return set; + } else { + if (!placed && other.type.rank > this.type.rank) { + if (!copy2) + copy2 = set.slice(0, i); + copy2.push(this); + placed = true; + } + if (copy2) + copy2.push(other); + } + } + if (!copy2) + copy2 = set.slice(); + if (!placed) + copy2.push(this); + return copy2; + } + /** + Remove this mark from the given set, returning a new set. If this + mark is not in the set, the set itself is returned. + */ + removeFromSet(set) { + for (let i = 0; i < set.length; i++) + if (this.eq(set[i])) + return set.slice(0, i).concat(set.slice(i + 1)); + return set; + } + /** + Test whether this mark is in the given set of marks. + */ + isInSet(set) { + for (let i = 0; i < set.length; i++) + if (this.eq(set[i])) + return true; + return false; + } + /** + Test whether this mark has the same type and attributes as + another mark. + */ + eq(other) { + return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs); + } + /** + Convert this mark to a JSON-serializeable representation. + */ + toJSON() { + let obj = { type: this.type.name }; + for (let _ in this.attrs) { + obj.attrs = this.attrs; + break; + } + return obj; + } + /** + Deserialize a mark from JSON. + */ + static fromJSON(schema, json) { + if (!json) + throw new RangeError("Invalid input for Mark.fromJSON"); + let type = schema.marks[json.type]; + if (!type) + throw new RangeError(`There is no mark type ${json.type} in this schema`); + let mark = type.create(json.attrs); + type.checkAttrs(mark.attrs); + return mark; + } + /** + Test whether two sets of marks are identical. + */ + static sameSet(a, b) { + if (a == b) + return true; + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].eq(b[i])) + return false; + return true; + } + /** + Create a properly sorted mark set from null, a single mark, or an + unsorted array of marks. + */ + static setFrom(marks) { + if (!marks || Array.isArray(marks) && marks.length == 0) + return Mark.none; + if (marks instanceof Mark) + return [marks]; + let copy2 = marks.slice(); + copy2.sort((a, b) => a.type.rank - b.type.rank); + return copy2; + } +}; +Mark$1.none = []; +class ReplaceError extends Error { +} +class Slice { + /** + Create a slice. When specifying a non-zero open depth, you must + make sure that there are nodes of at least that depth at the + appropriate side of the fragment—i.e. if the fragment is an + empty paragraph node, `openStart` and `openEnd` can't be greater + than 1. + + It is not necessary for the content of open nodes to conform to + the schema's content constraints, though it should be a valid + start/end/middle for such a node, depending on which sides are + open. + */ + constructor(content, openStart, openEnd) { + this.content = content; + this.openStart = openStart; + this.openEnd = openEnd; + } + /** + The size this slice would add when inserted into a document. + */ + get size() { + return this.content.size - this.openStart - this.openEnd; + } + /** + @internal + */ + insertAt(pos, fragment) { + let content = insertInto(this.content, pos + this.openStart, fragment); + return content && new Slice(content, this.openStart, this.openEnd); + } + /** + @internal + */ + removeBetween(from2, to) { + return new Slice(removeRange(this.content, from2 + this.openStart, to + this.openStart), this.openStart, this.openEnd); + } + /** + Tests whether this slice is equal to another slice. + */ + eq(other) { + return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd; + } + /** + @internal + */ + toString() { + return this.content + "(" + this.openStart + "," + this.openEnd + ")"; + } + /** + Convert a slice to a JSON-serializable representation. + */ + toJSON() { + if (!this.content.size) + return null; + let json = { content: this.content.toJSON() }; + if (this.openStart > 0) + json.openStart = this.openStart; + if (this.openEnd > 0) + json.openEnd = this.openEnd; + return json; + } + /** + Deserialize a slice from its JSON representation. + */ + static fromJSON(schema, json) { + if (!json) + return Slice.empty; + let openStart = json.openStart || 0, openEnd = json.openEnd || 0; + if (typeof openStart != "number" || typeof openEnd != "number") + throw new RangeError("Invalid input for Slice.fromJSON"); + return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd); + } + /** + Create a slice from a fragment by taking the maximum possible + open value on both side of the fragment. + */ + static maxOpen(fragment, openIsolating = true) { + let openStart = 0, openEnd = 0; + for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) + openStart++; + for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) + openEnd++; + return new Slice(fragment, openStart, openEnd); + } +} +Slice.empty = new Slice(Fragment.empty, 0, 0); +function removeRange(content, from2, to) { + let { index, offset } = content.findIndex(from2), child = content.maybeChild(index); + let { index: indexTo, offset: offsetTo } = content.findIndex(to); + if (offset == from2 || child.isText) { + if (offsetTo != to && !content.child(indexTo).isText) + throw new RangeError("Removing non-flat range"); + return content.cut(0, from2).append(content.cut(to)); + } + if (index != indexTo) + throw new RangeError("Removing non-flat range"); + return content.replaceChild(index, child.copy(removeRange(child.content, from2 - offset - 1, to - offset - 1))); +} +function insertInto(content, dist, insert, parent) { + let { index, offset } = content.findIndex(dist), child = content.maybeChild(index); + if (offset == dist || child.isText) { + if (parent && !parent.canReplace(index, index, insert)) + return null; + return content.cut(0, dist).append(insert).append(content.cut(dist)); + } + let inner = insertInto(child.content, dist - offset - 1, insert, child); + return inner && content.replaceChild(index, child.copy(inner)); +} +function replace($from, $to, slice2) { + if (slice2.openStart > $from.depth) + throw new ReplaceError("Inserted content deeper than insertion position"); + if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd) + throw new ReplaceError("Inconsistent open depths"); + return replaceOuter($from, $to, slice2, 0); +} +function replaceOuter($from, $to, slice2, depth) { + let index = $from.index(depth), node = $from.node(depth); + if (index == $to.index(depth) && depth < $from.depth - slice2.openStart) { + let inner = replaceOuter($from, $to, slice2, depth + 1); + return node.copy(node.content.replaceChild(index, inner)); + } else if (!slice2.content.size) { + return close(node, replaceTwoWay($from, $to, depth)); + } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) { + let parent = $from.parent, content = parent.content; + return close(parent, content.cut(0, $from.parentOffset).append(slice2.content).append(content.cut($to.parentOffset))); + } else { + let { start, end } = prepareSliceForReplace(slice2, $from); + return close(node, replaceThreeWay($from, start, end, $to, depth)); + } +} +function checkJoin(main, sub) { + if (!sub.type.compatibleContent(main.type)) + throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name); +} +function joinable$1($before, $after, depth) { + let node = $before.node(depth); + checkJoin(node, $after.node(depth)); + return node; +} +function addNode(child, target) { + let last = target.length - 1; + if (last >= 0 && child.isText && child.sameMarkup(target[last])) + target[last] = child.withText(target[last].text + child.text); + else + target.push(child); +} +function addRange($start, $end, depth, target) { + let node = ($end || $start).node(depth); + let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; + if ($start) { + startIndex = $start.index(depth); + if ($start.depth > depth) { + startIndex++; + } else if ($start.textOffset) { + addNode($start.nodeAfter, target); + startIndex++; + } + } + for (let i = startIndex; i < endIndex; i++) + addNode(node.child(i), target); + if ($end && $end.depth == depth && $end.textOffset) + addNode($end.nodeBefore, target); +} +function close(node, content) { + node.type.checkContent(content); + return node.copy(content); +} +function replaceThreeWay($from, $start, $end, $to, depth) { + let openStart = $from.depth > depth && joinable$1($from, $start, depth + 1); + let openEnd = $to.depth > depth && joinable$1($end, $to, depth + 1); + let content = []; + addRange(null, $from, depth, content); + if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { + checkJoin(openStart, openEnd); + addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); + } else { + if (openStart) + addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); + addRange($start, $end, depth, content); + if (openEnd) + addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); + } + addRange($to, null, depth, content); + return new Fragment(content); +} +function replaceTwoWay($from, $to, depth) { + let content = []; + addRange(null, $from, depth, content); + if ($from.depth > depth) { + let type = joinable$1($from, $to, depth + 1); + addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content); + } + addRange($to, null, depth, content); + return new Fragment(content); +} +function prepareSliceForReplace(slice2, $along) { + let extra = $along.depth - slice2.openStart, parent = $along.node(extra); + let node = parent.copy(slice2.content); + for (let i = extra - 1; i >= 0; i--) + node = $along.node(i).copy(Fragment.from(node)); + return { + start: node.resolveNoCache(slice2.openStart + extra), + end: node.resolveNoCache(node.content.size - slice2.openEnd - extra) + }; +} +class ResolvedPos { + /** + @internal + */ + constructor(pos, path, parentOffset) { + this.pos = pos; + this.path = path; + this.parentOffset = parentOffset; + this.depth = path.length / 3 - 1; + } + /** + @internal + */ + resolveDepth(val) { + if (val == null) + return this.depth; + if (val < 0) + return this.depth + val; + return val; + } + /** + The parent node that the position points into. Note that even if + a position points into a text node, that node is not considered + the parent—text nodes are ‘flat’ in this model, and have no content. + */ + get parent() { + return this.node(this.depth); + } + /** + The root node in which the position was resolved. + */ + get doc() { + return this.node(0); + } + /** + The ancestor node at the given level. `p.node(p.depth)` is the + same as `p.parent`. + */ + node(depth) { + return this.path[this.resolveDepth(depth) * 3]; + } + /** + The index into the ancestor at the given level. If this points + at the 3rd node in the 2nd paragraph on the top level, for + example, `p.index(0)` is 1 and `p.index(1)` is 2. + */ + index(depth) { + return this.path[this.resolveDepth(depth) * 3 + 1]; + } + /** + The index pointing after this position into the ancestor at the + given level. + */ + indexAfter(depth) { + depth = this.resolveDepth(depth); + return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1); + } + /** + The (absolute) position at the start of the node at the given + level. + */ + start(depth) { + depth = this.resolveDepth(depth); + return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; + } + /** + The (absolute) position at the end of the node at the given + level. + */ + end(depth) { + depth = this.resolveDepth(depth); + return this.start(depth) + this.node(depth).content.size; + } + /** + The (absolute) position directly before the wrapping node at the + given level, or, when `depth` is `this.depth + 1`, the original + position. + */ + before(depth) { + depth = this.resolveDepth(depth); + if (!depth) + throw new RangeError("There is no position before the top-level node"); + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]; + } + /** + The (absolute) position directly after the wrapping node at the + given level, or the original position when `depth` is `this.depth + 1`. + */ + after(depth) { + depth = this.resolveDepth(depth); + if (!depth) + throw new RangeError("There is no position after the top-level node"); + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize; + } + /** + When this position points into a text node, this returns the + distance between the position and the start of the text node. + Will be zero for positions that point between nodes. + */ + get textOffset() { + return this.pos - this.path[this.path.length - 1]; + } + /** + Get the node directly after the position, if any. If the position + points into a text node, only the part of that node after the + position is returned. + */ + get nodeAfter() { + let parent = this.parent, index = this.index(this.depth); + if (index == parent.childCount) + return null; + let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); + return dOff ? parent.child(index).cut(dOff) : child; + } + /** + Get the node directly before the position, if any. If the + position points into a text node, only the part of that node + before the position is returned. + */ + get nodeBefore() { + let index = this.index(this.depth); + let dOff = this.pos - this.path[this.path.length - 1]; + if (dOff) + return this.parent.child(index).cut(0, dOff); + return index == 0 ? null : this.parent.child(index - 1); + } + /** + Get the position at the given index in the parent node at the + given depth (which defaults to `this.depth`). + */ + posAtIndex(index, depth) { + depth = this.resolveDepth(depth); + let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; + for (let i = 0; i < index; i++) + pos += node.child(i).nodeSize; + return pos; + } + /** + Get the marks at this position, factoring in the surrounding + marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the + position is at the start of a non-empty node, the marks of the + node after it (if any) are returned. + */ + marks() { + let parent = this.parent, index = this.index(); + if (parent.content.size == 0) + return Mark$1.none; + if (this.textOffset) + return parent.child(index).marks; + let main = parent.maybeChild(index - 1), other = parent.maybeChild(index); + if (!main) { + let tmp = main; + main = other; + other = tmp; + } + let marks = main.marks; + for (var i = 0; i < marks.length; i++) + if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) + marks = marks[i--].removeFromSet(marks); + return marks; + } + /** + Get the marks after the current position, if any, except those + that are non-inclusive and not present at position `$end`. This + is mostly useful for getting the set of marks to preserve after a + deletion. Will return `null` if this position is at the end of + its parent node or its parent node isn't a textblock (in which + case no marks should be preserved). + */ + marksAcross($end) { + let after = this.parent.maybeChild(this.index()); + if (!after || !after.isInline) + return null; + let marks = after.marks, next = $end.parent.maybeChild($end.index()); + for (var i = 0; i < marks.length; i++) + if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) + marks = marks[i--].removeFromSet(marks); + return marks; + } + /** + The depth up to which this position and the given (non-resolved) + position share the same parent nodes. + */ + sharedDepth(pos) { + for (let depth = this.depth; depth > 0; depth--) + if (this.start(depth) <= pos && this.end(depth) >= pos) + return depth; + return 0; + } + /** + Returns a range based on the place where this position and the + given position diverge around block content. If both point into + the same textblock, for example, a range around that textblock + will be returned. If they point into different blocks, the range + around those blocks in their shared ancestor is returned. You can + pass in an optional predicate that will be called with a parent + node to see if a range into that parent is acceptable. + */ + blockRange(other = this, pred) { + if (other.pos < this.pos) + return other.blockRange(this); + for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) + if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) + return new NodeRange(this, other, d); + return null; + } + /** + Query whether the given position shares the same parent node. + */ + sameParent(other) { + return this.pos - this.parentOffset == other.pos - other.parentOffset; + } + /** + Return the greater of this and the given position. + */ + max(other) { + return other.pos > this.pos ? other : this; + } + /** + Return the smaller of this and the given position. + */ + min(other) { + return other.pos < this.pos ? other : this; + } + /** + @internal + */ + toString() { + let str = ""; + for (let i = 1; i <= this.depth; i++) + str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1); + return str + ":" + this.parentOffset; + } + /** + @internal + */ + static resolve(doc2, pos) { + if (!(pos >= 0 && pos <= doc2.content.size)) + throw new RangeError("Position " + pos + " out of range"); + let path = []; + let start = 0, parentOffset = pos; + for (let node = doc2; ; ) { + let { index, offset } = node.content.findIndex(parentOffset); + let rem = parentOffset - offset; + path.push(node, index, start + offset); + if (!rem) + break; + node = node.child(index); + if (node.isText) + break; + parentOffset = rem - 1; + start += offset + 1; + } + return new ResolvedPos(pos, path, parentOffset); + } + /** + @internal + */ + static resolveCached(doc2, pos) { + let cache = resolveCache.get(doc2); + if (cache) { + for (let i = 0; i < cache.elts.length; i++) { + let elt = cache.elts[i]; + if (elt.pos == pos) + return elt; + } + } else { + resolveCache.set(doc2, cache = new ResolveCache()); + } + let result = cache.elts[cache.i] = ResolvedPos.resolve(doc2, pos); + cache.i = (cache.i + 1) % resolveCacheSize; + return result; + } +} +class ResolveCache { + constructor() { + this.elts = []; + this.i = 0; + } +} +const resolveCacheSize = 12, resolveCache = /* @__PURE__ */ new WeakMap(); +class NodeRange { + /** + Construct a node range. `$from` and `$to` should point into the + same node until at least the given `depth`, since a node range + denotes an adjacent set of nodes in a single parent node. + */ + constructor($from, $to, depth) { + this.$from = $from; + this.$to = $to; + this.depth = depth; + } + /** + The position at the start of the range. + */ + get start() { + return this.$from.before(this.depth + 1); + } + /** + The position at the end of the range. + */ + get end() { + return this.$to.after(this.depth + 1); + } + /** + The parent node that the range points into. + */ + get parent() { + return this.$from.node(this.depth); + } + /** + The start index of the range in the parent node. + */ + get startIndex() { + return this.$from.index(this.depth); + } + /** + The end index of the range in the parent node. + */ + get endIndex() { + return this.$to.indexAfter(this.depth); + } +} +const emptyAttrs = /* @__PURE__ */ Object.create(null); +class Node { + /** + @internal + */ + constructor(type, attrs, content, marks = Mark$1.none) { + this.type = type; + this.attrs = attrs; + this.marks = marks; + this.content = content || Fragment.empty; + } + /** + The array of this node's child nodes. + */ + get children() { + return this.content.content; + } + /** + The size of this node, as defined by the integer-based [indexing + scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the + amount of characters. For other leaf nodes, it is one. For + non-leaf nodes, it is the size of the content plus two (the + start and end token). + */ + get nodeSize() { + return this.isLeaf ? 1 : 2 + this.content.size; + } + /** + The number of children that the node has. + */ + get childCount() { + return this.content.childCount; + } + /** + Get the child node at the given index. Raises an error when the + index is out of range. + */ + child(index) { + return this.content.child(index); + } + /** + Get the child node at the given index, if it exists. + */ + maybeChild(index) { + return this.content.maybeChild(index); + } + /** + Call `f` for every child node, passing the node, its offset + into this parent node, and its index. + */ + forEach(f) { + this.content.forEach(f); + } + /** + Invoke a callback for all descendant nodes recursively between + the given two positions that are relative to start of this + node's content. The callback is invoked with the node, its + position relative to the original node (method receiver), + its parent node, and its child index. When the callback returns + false for a given node, that node's children will not be + recursed over. The last parameter can be used to specify a + starting position to count from. + */ + nodesBetween(from2, to, f, startPos = 0) { + this.content.nodesBetween(from2, to, f, startPos, this); + } + /** + Call the given callback for every descendant node. Doesn't + descend into a node when the callback returns `false`. + */ + descendants(f) { + this.nodesBetween(0, this.content.size, f); + } + /** + Concatenates all the text nodes found in this fragment and its + children. + */ + get textContent() { + return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, ""); + } + /** + Get all text between positions `from` and `to`. When + `blockSeparator` is given, it will be inserted to separate text + from different block nodes. If `leafText` is given, it'll be + inserted for every non-text leaf node encountered, otherwise + [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used. + */ + textBetween(from2, to, blockSeparator, leafText) { + return this.content.textBetween(from2, to, blockSeparator, leafText); + } + /** + Returns this node's first child, or `null` if there are no + children. + */ + get firstChild() { + return this.content.firstChild; + } + /** + Returns this node's last child, or `null` if there are no + children. + */ + get lastChild() { + return this.content.lastChild; + } + /** + Test whether two nodes represent the same piece of document. + */ + eq(other) { + return this == other || this.sameMarkup(other) && this.content.eq(other.content); + } + /** + Compare the markup (type, attributes, and marks) of this node to + those of another. Returns `true` if both have the same markup. + */ + sameMarkup(other) { + return this.hasMarkup(other.type, other.attrs, other.marks); + } + /** + Check whether this node's markup correspond to the given type, + attributes, and marks. + */ + hasMarkup(type, attrs, marks) { + return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark$1.sameSet(this.marks, marks || Mark$1.none); + } + /** + Create a new node with the same markup as this node, containing + the given content (or empty, if no content is given). + */ + copy(content = null) { + if (content == this.content) + return this; + return new Node(this.type, this.attrs, content, this.marks); + } + /** + Create a copy of this node, with the given set of marks instead + of the node's own marks. + */ + mark(marks) { + return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks); + } + /** + Create a copy of this node with only the content between the + given positions. If `to` is not given, it defaults to the end of + the node. + */ + cut(from2, to = this.content.size) { + if (from2 == 0 && to == this.content.size) + return this; + return this.copy(this.content.cut(from2, to)); + } + /** + Cut out the part of the document between the given positions, and + return it as a `Slice` object. + */ + slice(from2, to = this.content.size, includeParents = false) { + if (from2 == to) + return Slice.empty; + let $from = this.resolve(from2), $to = this.resolve(to); + let depth = includeParents ? 0 : $from.sharedDepth(to); + let start = $from.start(depth), node = $from.node(depth); + let content = node.content.cut($from.pos - start, $to.pos - start); + return new Slice(content, $from.depth - depth, $to.depth - depth); + } + /** + Replace the part of the document between the given positions with + the given slice. The slice must 'fit', meaning its open sides + must be able to connect to the surrounding content, and its + content nodes must be valid children for the node they are placed + into. If any of this is violated, an error of type + [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown. + */ + replace(from2, to, slice2) { + return replace(this.resolve(from2), this.resolve(to), slice2); + } + /** + Find the node directly after the given position. + */ + nodeAt(pos) { + for (let node = this; ; ) { + let { index, offset } = node.content.findIndex(pos); + node = node.maybeChild(index); + if (!node) + return null; + if (offset == pos || node.isText) + return node; + pos -= offset + 1; + } + } + /** + Find the (direct) child node after the given offset, if any, + and return it along with its index and offset relative to this + node. + */ + childAfter(pos) { + let { index, offset } = this.content.findIndex(pos); + return { node: this.content.maybeChild(index), index, offset }; + } + /** + Find the (direct) child node before the given offset, if any, + and return it along with its index and offset relative to this + node. + */ + childBefore(pos) { + if (pos == 0) + return { node: null, index: 0, offset: 0 }; + let { index, offset } = this.content.findIndex(pos); + if (offset < pos) + return { node: this.content.child(index), index, offset }; + let node = this.content.child(index - 1); + return { node, index: index - 1, offset: offset - node.nodeSize }; + } + /** + Resolve the given position in the document, returning an + [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context. + */ + resolve(pos) { + return ResolvedPos.resolveCached(this, pos); + } + /** + @internal + */ + resolveNoCache(pos) { + return ResolvedPos.resolve(this, pos); + } + /** + Test whether a given mark or mark type occurs in this document + between the two given positions. + */ + rangeHasMark(from2, to, type) { + let found2 = false; + if (to > from2) + this.nodesBetween(from2, to, (node) => { + if (type.isInSet(node.marks)) + found2 = true; + return !found2; + }); + return found2; + } + /** + True when this is a block (non-inline node) + */ + get isBlock() { + return this.type.isBlock; + } + /** + True when this is a textblock node, a block node with inline + content. + */ + get isTextblock() { + return this.type.isTextblock; + } + /** + True when this node allows inline content. + */ + get inlineContent() { + return this.type.inlineContent; + } + /** + True when this is an inline node (a text node or a node that can + appear among text). + */ + get isInline() { + return this.type.isInline; + } + /** + True when this is a text node. + */ + get isText() { + return this.type.isText; + } + /** + True when this is a leaf node. + */ + get isLeaf() { + return this.type.isLeaf; + } + /** + True when this is an atom, i.e. when it does not have directly + editable content. This is usually the same as `isLeaf`, but can + be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom) + on a node's spec (typically used when the node is displayed as + an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)). + */ + get isAtom() { + return this.type.isAtom; + } + /** + Return a string representation of this node for debugging + purposes. + */ + toString() { + if (this.type.spec.toDebugString) + return this.type.spec.toDebugString(this); + let name = this.type.name; + if (this.content.size) + name += "(" + this.content.toStringInner() + ")"; + return wrapMarks(this.marks, name); + } + /** + Get the content match in this node at the given index. + */ + contentMatchAt(index) { + let match = this.type.contentMatch.matchFragment(this.content, 0, index); + if (!match) + throw new Error("Called contentMatchAt on a node with invalid content"); + return match; + } + /** + Test whether replacing the range between `from` and `to` (by + child index) with the given replacement fragment (which defaults + to the empty fragment) would leave the node's content valid. You + can optionally pass `start` and `end` indices into the + replacement fragment. + */ + canReplace(from2, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) { + let one = this.contentMatchAt(from2).matchFragment(replacement, start, end); + let two = one && one.matchFragment(this.content, to); + if (!two || !two.validEnd) + return false; + for (let i = start; i < end; i++) + if (!this.type.allowsMarks(replacement.child(i).marks)) + return false; + return true; + } + /** + Test whether replacing the range `from` to `to` (by index) with + a node of the given type would leave the node's content valid. + */ + canReplaceWith(from2, to, type, marks) { + if (marks && !this.type.allowsMarks(marks)) + return false; + let start = this.contentMatchAt(from2).matchType(type); + let end = start && start.matchFragment(this.content, to); + return end ? end.validEnd : false; + } + /** + Test whether the given node's content could be appended to this + node. If that node is empty, this will only return true if there + is at least one node type that can appear in both nodes (to avoid + merging completely incompatible nodes). + */ + canAppend(other) { + if (other.content.size) + return this.canReplace(this.childCount, this.childCount, other.content); + else + return this.type.compatibleContent(other.type); + } + /** + Check whether this node and its descendants conform to the + schema, and raise an exception when they do not. + */ + check() { + this.type.checkContent(this.content); + this.type.checkAttrs(this.attrs); + let copy2 = Mark$1.none; + for (let i = 0; i < this.marks.length; i++) { + let mark = this.marks[i]; + mark.type.checkAttrs(mark.attrs); + copy2 = mark.addToSet(copy2); + } + if (!Mark$1.sameSet(copy2, this.marks)) + throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`); + this.content.forEach((node) => node.check()); + } + /** + Return a JSON-serializeable representation of this node. + */ + toJSON() { + let obj = { type: this.type.name }; + for (let _ in this.attrs) { + obj.attrs = this.attrs; + break; + } + if (this.content.size) + obj.content = this.content.toJSON(); + if (this.marks.length) + obj.marks = this.marks.map((n) => n.toJSON()); + return obj; + } + /** + Deserialize a node from its JSON representation. + */ + static fromJSON(schema, json) { + if (!json) + throw new RangeError("Invalid input for Node.fromJSON"); + let marks = void 0; + if (json.marks) { + if (!Array.isArray(json.marks)) + throw new RangeError("Invalid mark data for Node.fromJSON"); + marks = json.marks.map(schema.markFromJSON); + } + if (json.type == "text") { + if (typeof json.text != "string") + throw new RangeError("Invalid text node in JSON"); + return schema.text(json.text, marks); + } + let content = Fragment.fromJSON(schema, json.content); + let node = schema.nodeType(json.type).create(json.attrs, content, marks); + node.type.checkAttrs(node.attrs); + return node; + } +} +Node.prototype.text = void 0; +class TextNode extends Node { + /** + @internal + */ + constructor(type, attrs, content, marks) { + super(type, attrs, null, marks); + if (!content) + throw new RangeError("Empty text nodes are not allowed"); + this.text = content; + } + toString() { + if (this.type.spec.toDebugString) + return this.type.spec.toDebugString(this); + return wrapMarks(this.marks, JSON.stringify(this.text)); + } + get textContent() { + return this.text; + } + textBetween(from2, to) { + return this.text.slice(from2, to); + } + get nodeSize() { + return this.text.length; + } + mark(marks) { + return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks); + } + withText(text) { + if (text == this.text) + return this; + return new TextNode(this.type, this.attrs, text, this.marks); + } + cut(from2 = 0, to = this.text.length) { + if (from2 == 0 && to == this.text.length) + return this; + return this.withText(this.text.slice(from2, to)); + } + eq(other) { + return this.sameMarkup(other) && this.text == other.text; + } + toJSON() { + let base2 = super.toJSON(); + base2.text = this.text; + return base2; + } +} +function wrapMarks(marks, str) { + for (let i = marks.length - 1; i >= 0; i--) + str = marks[i].type.name + "(" + str + ")"; + return str; +} +class ContentMatch { + /** + @internal + */ + constructor(validEnd) { + this.validEnd = validEnd; + this.next = []; + this.wrapCache = []; + } + /** + @internal + */ + static parse(string, nodeTypes) { + let stream = new TokenStream(string, nodeTypes); + if (stream.next == null) + return ContentMatch.empty; + let expr = parseExpr(stream); + if (stream.next) + stream.err("Unexpected trailing text"); + let match = dfa(nfa(expr)); + checkForDeadEnds(match, stream); + return match; + } + /** + Match a node type, returning a match after that node if + successful. + */ + matchType(type) { + for (let i = 0; i < this.next.length; i++) + if (this.next[i].type == type) + return this.next[i].next; + return null; + } + /** + Try to match a fragment. Returns the resulting match when + successful. + */ + matchFragment(frag, start = 0, end = frag.childCount) { + let cur = this; + for (let i = start; cur && i < end; i++) + cur = cur.matchType(frag.child(i).type); + return cur; + } + /** + @internal + */ + get inlineContent() { + return this.next.length != 0 && this.next[0].type.isInline; + } + /** + Get the first matching node type at this match position that can + be generated. + */ + get defaultType() { + for (let i = 0; i < this.next.length; i++) { + let { type } = this.next[i]; + if (!(type.isText || type.hasRequiredAttrs())) + return type; + } + return null; + } + /** + @internal + */ + compatible(other) { + for (let i = 0; i < this.next.length; i++) + for (let j = 0; j < other.next.length; j++) + if (this.next[i].type == other.next[j].type) + return true; + return false; + } + /** + Try to match the given fragment, and if that fails, see if it can + be made to match by inserting nodes in front of it. When + successful, return a fragment of inserted nodes (which may be + empty if nothing had to be inserted). When `toEnd` is true, only + return a fragment if the resulting match goes to the end of the + content expression. + */ + fillBefore(after, toEnd = false, startIndex = 0) { + let seen = [this]; + function search(match, types) { + let finished = match.matchFragment(after, startIndex); + if (finished && (!toEnd || finished.validEnd)) + return Fragment.from(types.map((tp) => tp.createAndFill())); + for (let i = 0; i < match.next.length; i++) { + let { type, next } = match.next[i]; + if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { + seen.push(next); + let found2 = search(next, types.concat(type)); + if (found2) + return found2; + } + } + return null; + } + return search(this, []); + } + /** + Find a set of wrapping node types that would allow a node of the + given type to appear at this position. The result may be empty + (when it fits directly) and will be null when no such wrapping + exists. + */ + findWrapping(target) { + for (let i = 0; i < this.wrapCache.length; i += 2) + if (this.wrapCache[i] == target) + return this.wrapCache[i + 1]; + let computed = this.computeWrapping(target); + this.wrapCache.push(target, computed); + return computed; + } + /** + @internal + */ + computeWrapping(target) { + let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }]; + while (active.length) { + let current = active.shift(), match = current.match; + if (match.matchType(target)) { + let result = []; + for (let obj = current; obj.type; obj = obj.via) + result.push(obj.type); + return result.reverse(); + } + for (let i = 0; i < match.next.length; i++) { + let { type, next } = match.next[i]; + if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) { + active.push({ match: type.contentMatch, type, via: current }); + seen[type.name] = true; + } + } + } + return null; + } + /** + The number of outgoing edges this node has in the finite + automaton that describes the content expression. + */ + get edgeCount() { + return this.next.length; + } + /** + Get the _n_​th outgoing edge from this node in the finite + automaton that describes the content expression. + */ + edge(n) { + if (n >= this.next.length) + throw new RangeError(`There's no ${n}th edge in this content match`); + return this.next[n]; + } + /** + @internal + */ + toString() { + let seen = []; + function scan(m) { + seen.push(m); + for (let i = 0; i < m.next.length; i++) + if (seen.indexOf(m.next[i].next) == -1) + scan(m.next[i].next); + } + scan(this); + return seen.map((m, i) => { + let out = i + (m.validEnd ? "*" : " ") + " "; + for (let i2 = 0; i2 < m.next.length; i2++) + out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next); + return out; + }).join("\n"); + } +} +ContentMatch.empty = new ContentMatch(true); +class TokenStream { + constructor(string, nodeTypes) { + this.string = string; + this.nodeTypes = nodeTypes; + this.inline = null; + this.pos = 0; + this.tokens = string.split(/\s*(?=\b|\W|$)/); + if (this.tokens[this.tokens.length - 1] == "") + this.tokens.pop(); + if (this.tokens[0] == "") + this.tokens.shift(); + } + get next() { + return this.tokens[this.pos]; + } + eat(tok) { + return this.next == tok && (this.pos++ || true); + } + err(str) { + throw new SyntaxError(str + " (in content expression '" + this.string + "')"); + } +} +function parseExpr(stream) { + let exprs = []; + do { + exprs.push(parseExprSeq(stream)); + } while (stream.eat("|")); + return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; +} +function parseExprSeq(stream) { + let exprs = []; + do { + exprs.push(parseExprSubscript(stream)); + } while (stream.next && stream.next != ")" && stream.next != "|"); + return exprs.length == 1 ? exprs[0] : { type: "seq", exprs }; +} +function parseExprSubscript(stream) { + let expr = parseExprAtom(stream); + for (; ; ) { + if (stream.eat("+")) + expr = { type: "plus", expr }; + else if (stream.eat("*")) + expr = { type: "star", expr }; + else if (stream.eat("?")) + expr = { type: "opt", expr }; + else if (stream.eat("{")) + expr = parseExprRange(stream, expr); + else + break; + } + return expr; +} +function parseNum(stream) { + if (/\D/.test(stream.next)) + stream.err("Expected number, got '" + stream.next + "'"); + let result = Number(stream.next); + stream.pos++; + return result; +} +function parseExprRange(stream, expr) { + let min = parseNum(stream), max = min; + if (stream.eat(",")) { + if (stream.next != "}") + max = parseNum(stream); + else + max = -1; + } + if (!stream.eat("}")) + stream.err("Unclosed braced range"); + return { type: "range", min, max, expr }; +} +function resolveName(stream, name) { + let types = stream.nodeTypes, type = types[name]; + if (type) + return [type]; + let result = []; + for (let typeName in types) { + let type2 = types[typeName]; + if (type2.isInGroup(name)) + result.push(type2); + } + if (result.length == 0) + stream.err("No node type or group '" + name + "' found"); + return result; +} +function parseExprAtom(stream) { + if (stream.eat("(")) { + let expr = parseExpr(stream); + if (!stream.eat(")")) + stream.err("Missing closing paren"); + return expr; + } else if (!/\W/.test(stream.next)) { + let exprs = resolveName(stream, stream.next).map((type) => { + if (stream.inline == null) + stream.inline = type.isInline; + else if (stream.inline != type.isInline) + stream.err("Mixing inline and block content"); + return { type: "name", value: type }; + }); + stream.pos++; + return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; + } else { + stream.err("Unexpected token '" + stream.next + "'"); + } +} +function nfa(expr) { + let nfa2 = [[]]; + connect(compile(expr, 0), node()); + return nfa2; + function node() { + return nfa2.push([]) - 1; + } + function edge(from2, to, term) { + let edge2 = { term, to }; + nfa2[from2].push(edge2); + return edge2; + } + function connect(edges, to) { + edges.forEach((edge2) => edge2.to = to); + } + function compile(expr2, from2) { + if (expr2.type == "choice") { + return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from2)), []); + } else if (expr2.type == "seq") { + for (let i = 0; ; i++) { + let next = compile(expr2.exprs[i], from2); + if (i == expr2.exprs.length - 1) + return next; + connect(next, from2 = node()); + } + } else if (expr2.type == "star") { + let loop = node(); + edge(from2, loop); + connect(compile(expr2.expr, loop), loop); + return [edge(loop)]; + } else if (expr2.type == "plus") { + let loop = node(); + connect(compile(expr2.expr, from2), loop); + connect(compile(expr2.expr, loop), loop); + return [edge(loop)]; + } else if (expr2.type == "opt") { + return [edge(from2)].concat(compile(expr2.expr, from2)); + } else if (expr2.type == "range") { + let cur = from2; + for (let i = 0; i < expr2.min; i++) { + let next = node(); + connect(compile(expr2.expr, cur), next); + cur = next; + } + if (expr2.max == -1) { + connect(compile(expr2.expr, cur), cur); + } else { + for (let i = expr2.min; i < expr2.max; i++) { + let next = node(); + edge(cur, next); + connect(compile(expr2.expr, cur), next); + cur = next; + } + } + return [edge(cur)]; + } else if (expr2.type == "name") { + return [edge(from2, void 0, expr2.value)]; + } else { + throw new Error("Unknown expr type"); + } + } +} +function cmp(a, b) { + return b - a; +} +function nullFrom(nfa2, node) { + let result = []; + scan(node); + return result.sort(cmp); + function scan(node2) { + let edges = nfa2[node2]; + if (edges.length == 1 && !edges[0].term) + return scan(edges[0].to); + result.push(node2); + for (let i = 0; i < edges.length; i++) { + let { term, to } = edges[i]; + if (!term && result.indexOf(to) == -1) + scan(to); + } + } +} +function dfa(nfa2) { + let labeled = /* @__PURE__ */ Object.create(null); + return explore(nullFrom(nfa2, 0)); + function explore(states) { + let out = []; + states.forEach((node) => { + nfa2[node].forEach(({ term, to }) => { + if (!term) + return; + let set; + for (let i = 0; i < out.length; i++) + if (out[i][0] == term) + set = out[i][1]; + nullFrom(nfa2, to).forEach((node2) => { + if (!set) + out.push([term, set = []]); + if (set.indexOf(node2) == -1) + set.push(node2); + }); + }); + }); + let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1); + for (let i = 0; i < out.length; i++) { + let states2 = out[i][1].sort(cmp); + state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) }); + } + return state; + } +} +function checkForDeadEnds(match, stream) { + for (let i = 0, work = [match]; i < work.length; i++) { + let state = work[i], dead = !state.validEnd, nodes = []; + for (let j = 0; j < state.next.length; j++) { + let { type, next } = state.next[j]; + nodes.push(type.name); + if (dead && !(type.isText || type.hasRequiredAttrs())) + dead = false; + if (work.indexOf(next) == -1) + work.push(next); + } + if (dead) + stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); + } +} +function defaultAttrs(attrs) { + let defaults2 = /* @__PURE__ */ Object.create(null); + for (let attrName in attrs) { + let attr = attrs[attrName]; + if (!attr.hasDefault) + return null; + defaults2[attrName] = attr.default; + } + return defaults2; +} +function computeAttrs(attrs, value) { + let built = /* @__PURE__ */ Object.create(null); + for (let name in attrs) { + let given = value && value[name]; + if (given === void 0) { + let attr = attrs[name]; + if (attr.hasDefault) + given = attr.default; + else + throw new RangeError("No value supplied for attribute " + name); + } + built[name] = given; + } + return built; +} +function checkAttrs(attrs, values, type, name) { + for (let name2 in values) + if (!(name2 in attrs)) + throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`); + for (let name2 in attrs) { + let attr = attrs[name2]; + if (attr.validate) + attr.validate(values[name2]); + } +} +function initAttrs(typeName, attrs) { + let result = /* @__PURE__ */ Object.create(null); + if (attrs) + for (let name in attrs) + result[name] = new Attribute(typeName, name, attrs[name]); + return result; +} +let NodeType$1 = class NodeType { + /** + @internal + */ + constructor(name, schema, spec) { + this.name = name; + this.schema = schema; + this.spec = spec; + this.markSet = null; + this.groups = spec.group ? spec.group.split(" ") : []; + this.attrs = initAttrs(name, spec.attrs); + this.defaultAttrs = defaultAttrs(this.attrs); + this.contentMatch = null; + this.inlineContent = null; + this.isBlock = !(spec.inline || name == "text"); + this.isText = name == "text"; + } + /** + True if this is an inline type. + */ + get isInline() { + return !this.isBlock; + } + /** + True if this is a textblock type, a block that contains inline + content. + */ + get isTextblock() { + return this.isBlock && this.inlineContent; + } + /** + True for node types that allow no content. + */ + get isLeaf() { + return this.contentMatch == ContentMatch.empty; + } + /** + True when this node is an atom, i.e. when it does not have + directly editable content. + */ + get isAtom() { + return this.isLeaf || !!this.spec.atom; + } + /** + Return true when this node type is part of the given + [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group). + */ + isInGroup(group) { + return this.groups.indexOf(group) > -1; + } + /** + The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option. + */ + get whitespace() { + return this.spec.whitespace || (this.spec.code ? "pre" : "normal"); + } + /** + Tells you whether this node type has any required attributes. + */ + hasRequiredAttrs() { + for (let n in this.attrs) + if (this.attrs[n].isRequired) + return true; + return false; + } + /** + Indicates whether this node allows some of the same content as + the given node type. + */ + compatibleContent(other) { + return this == other || this.contentMatch.compatible(other.contentMatch); + } + /** + @internal + */ + computeAttrs(attrs) { + if (!attrs && this.defaultAttrs) + return this.defaultAttrs; + else + return computeAttrs(this.attrs, attrs); + } + /** + Create a `Node` of this type. The given attributes are + checked and defaulted (you can pass `null` to use the type's + defaults entirely, if no required attributes exist). `content` + may be a `Fragment`, a node, an array of nodes, or + `null`. Similarly `marks` may be `null` to default to the empty + set of marks. + */ + create(attrs = null, content, marks) { + if (this.isText) + throw new Error("NodeType.create can't construct text nodes"); + return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark$1.setFrom(marks)); + } + /** + Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content + against the node type's content restrictions, and throw an error + if it doesn't match. + */ + createChecked(attrs = null, content, marks) { + content = Fragment.from(content); + this.checkContent(content); + return new Node(this, this.computeAttrs(attrs), content, Mark$1.setFrom(marks)); + } + /** + Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is + necessary to add nodes to the start or end of the given fragment + to make it fit the node. If no fitting wrapping can be found, + return null. Note that, due to the fact that required nodes can + always be created, this will always succeed if you pass null or + `Fragment.empty` as content. + */ + createAndFill(attrs = null, content, marks) { + attrs = this.computeAttrs(attrs); + content = Fragment.from(content); + if (content.size) { + let before = this.contentMatch.fillBefore(content); + if (!before) + return null; + content = before.append(content); + } + let matched = this.contentMatch.matchFragment(content); + let after = matched && matched.fillBefore(Fragment.empty, true); + if (!after) + return null; + return new Node(this, attrs, content.append(after), Mark$1.setFrom(marks)); + } + /** + Returns true if the given fragment is valid content for this node + type. + */ + validContent(content) { + let result = this.contentMatch.matchFragment(content); + if (!result || !result.validEnd) + return false; + for (let i = 0; i < content.childCount; i++) + if (!this.allowsMarks(content.child(i).marks)) + return false; + return true; + } + /** + Throws a RangeError if the given fragment is not valid content for this + node type. + @internal + */ + checkContent(content) { + if (!this.validContent(content)) + throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`); + } + /** + @internal + */ + checkAttrs(attrs) { + checkAttrs(this.attrs, attrs, "node", this.name); + } + /** + Check whether the given mark type is allowed in this node. + */ + allowsMarkType(markType) { + return this.markSet == null || this.markSet.indexOf(markType) > -1; + } + /** + Test whether the given set of marks are allowed in this node. + */ + allowsMarks(marks) { + if (this.markSet == null) + return true; + for (let i = 0; i < marks.length; i++) + if (!this.allowsMarkType(marks[i].type)) + return false; + return true; + } + /** + Removes the marks that are not allowed in this node from the given set. + */ + allowedMarks(marks) { + if (this.markSet == null) + return marks; + let copy2; + for (let i = 0; i < marks.length; i++) { + if (!this.allowsMarkType(marks[i].type)) { + if (!copy2) + copy2 = marks.slice(0, i); + } else if (copy2) { + copy2.push(marks[i]); + } + } + return !copy2 ? marks : copy2.length ? copy2 : Mark$1.none; + } + /** + @internal + */ + static compile(nodes, schema) { + let result = /* @__PURE__ */ Object.create(null); + nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec)); + let topType = schema.spec.topNode || "doc"; + if (!result[topType]) + throw new RangeError("Schema is missing its top node type ('" + topType + "')"); + if (!result.text) + throw new RangeError("Every schema needs a 'text' type"); + for (let _ in result.text.attrs) + throw new RangeError("The text node type should not have attributes"); + return result; + } +}; +function validateType(typeName, attrName, type) { + let types = type.split("|"); + return (value) => { + let name = value === null ? "null" : typeof value; + if (types.indexOf(name) < 0) + throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`); + }; +} +class Attribute { + constructor(typeName, attrName, options) { + this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); + this.default = options.default; + this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate; + } + get isRequired() { + return !this.hasDefault; + } +} +class MarkType { + /** + @internal + */ + constructor(name, rank, schema, spec) { + this.name = name; + this.rank = rank; + this.schema = schema; + this.spec = spec; + this.attrs = initAttrs(name, spec.attrs); + this.excluded = null; + let defaults2 = defaultAttrs(this.attrs); + this.instance = defaults2 ? new Mark$1(this, defaults2) : null; + } + /** + Create a mark of this type. `attrs` may be `null` or an object + containing only some of the mark's attributes. The others, if + they have defaults, will be added. + */ + create(attrs = null) { + if (!attrs && this.instance) + return this.instance; + return new Mark$1(this, computeAttrs(this.attrs, attrs)); + } + /** + @internal + */ + static compile(marks, schema) { + let result = /* @__PURE__ */ Object.create(null), rank = 0; + marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec)); + return result; + } + /** + When there is a mark of this type in the given set, a new set + without it is returned. Otherwise, the input set is returned. + */ + removeFromSet(set) { + for (var i = 0; i < set.length; i++) + if (set[i].type == this) { + set = set.slice(0, i).concat(set.slice(i + 1)); + i--; + } + return set; + } + /** + Tests whether there is a mark of this type in the given set. + */ + isInSet(set) { + for (let i = 0; i < set.length; i++) + if (set[i].type == this) + return set[i]; + } + /** + @internal + */ + checkAttrs(attrs) { + checkAttrs(this.attrs, attrs, "mark", this.name); + } + /** + Queries whether a given mark type is + [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one. + */ + excludes(other) { + return this.excluded.indexOf(other) > -1; + } +} +class Schema { + /** + Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec). + */ + constructor(spec) { + this.linebreakReplacement = null; + this.cached = /* @__PURE__ */ Object.create(null); + let instanceSpec = this.spec = {}; + for (let prop in spec) + instanceSpec[prop] = spec[prop]; + instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType$1.compile(this.spec.nodes, this); + this.marks = MarkType.compile(this.spec.marks, this); + let contentExprCache = /* @__PURE__ */ Object.create(null); + for (let prop in this.nodes) { + if (prop in this.marks) + throw new RangeError(prop + " can not be both a node and a mark"); + let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks; + type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); + type.inlineContent = type.contentMatch.inlineContent; + if (type.spec.linebreakReplacement) { + if (this.linebreakReplacement) + throw new RangeError("Multiple linebreak nodes defined"); + if (!type.isInline || !type.isLeaf) + throw new RangeError("Linebreak replacement nodes must be inline leaf nodes"); + this.linebreakReplacement = type; + } + type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null; + } + for (let prop in this.marks) { + let type = this.marks[prop], excl = type.spec.excludes; + type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); + } + this.nodeFromJSON = (json) => Node.fromJSON(this, json); + this.markFromJSON = (json) => Mark$1.fromJSON(this, json); + this.topNodeType = this.nodes[this.spec.topNode || "doc"]; + this.cached.wrappings = /* @__PURE__ */ Object.create(null); + } + /** + Create a node in this schema. The `type` may be a string or a + `NodeType` instance. Attributes will be extended with defaults, + `content` may be a `Fragment`, `null`, a `Node`, or an array of + nodes. + */ + node(type, attrs = null, content, marks) { + if (typeof type == "string") + type = this.nodeType(type); + else if (!(type instanceof NodeType$1)) + throw new RangeError("Invalid node type: " + type); + else if (type.schema != this) + throw new RangeError("Node type from different schema used (" + type.name + ")"); + return type.createChecked(attrs, content, marks); + } + /** + Create a text node in the schema. Empty text nodes are not + allowed. + */ + text(text, marks) { + let type = this.nodes.text; + return new TextNode(type, type.defaultAttrs, text, Mark$1.setFrom(marks)); + } + /** + Create a mark with the given type and attributes. + */ + mark(type, attrs) { + if (typeof type == "string") + type = this.marks[type]; + return type.create(attrs); + } + /** + @internal + */ + nodeType(name) { + let found2 = this.nodes[name]; + if (!found2) + throw new RangeError("Unknown node type: " + name); + return found2; + } +} +function gatherMarks(schema, marks) { + let found2 = []; + for (let i = 0; i < marks.length; i++) { + let name = marks[i], mark = schema.marks[name], ok = mark; + if (mark) { + found2.push(mark); + } else { + for (let prop in schema.marks) { + let mark2 = schema.marks[prop]; + if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1) + found2.push(ok = mark2); + } + } + if (!ok) + throw new SyntaxError("Unknown mark type: '" + marks[i] + "'"); + } + return found2; +} +function isTagRule(rule) { + return rule.tag != null; +} +function isStyleRule(rule) { + return rule.style != null; +} +class DOMParser { + /** + Create a parser that targets the given schema, using the given + parsing rules. + */ + constructor(schema, rules) { + this.schema = schema; + this.rules = rules; + this.tags = []; + this.styles = []; + let matchedStyles = this.matchedStyles = []; + rules.forEach((rule) => { + if (isTagRule(rule)) { + this.tags.push(rule); + } else if (isStyleRule(rule)) { + let prop = /[^=]*/.exec(rule.style)[0]; + if (matchedStyles.indexOf(prop) < 0) + matchedStyles.push(prop); + this.styles.push(rule); + } + }); + this.normalizeLists = !this.tags.some((r) => { + if (!/^(ul|ol)\b/.test(r.tag) || !r.node) + return false; + let node = schema.nodes[r.node]; + return node.contentMatch.matchType(node); + }); + } + /** + Parse a document from the content of a DOM node. + */ + parse(dom, options = {}) { + let context = new ParseContext(this, options, false); + context.addAll(dom, Mark$1.none, options.from, options.to); + return context.finish(); + } + /** + Parses the content of the given DOM node, like + [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of + options. But unlike that method, which produces a whole node, + this one returns a slice that is open at the sides, meaning that + the schema constraints aren't applied to the start of nodes to + the left of the input and the end of nodes at the end. + */ + parseSlice(dom, options = {}) { + let context = new ParseContext(this, options, true); + context.addAll(dom, Mark$1.none, options.from, options.to); + return Slice.maxOpen(context.finish()); + } + /** + @internal + */ + matchTag(dom, context, after) { + for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) { + let rule = this.tags[i]; + if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) { + if (rule.getAttrs) { + let result = rule.getAttrs(dom); + if (result === false) + continue; + rule.attrs = result || void 0; + } + return rule; + } + } + } + /** + @internal + */ + matchStyle(prop, value, context, after) { + for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) { + let rule = this.styles[i], style2 = rule.style; + if (style2.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop, + // or has an '=' sign after the prop, followed by the given + // value. + style2.length > prop.length && (style2.charCodeAt(prop.length) != 61 || style2.slice(prop.length + 1) != value)) + continue; + if (rule.getAttrs) { + let result = rule.getAttrs(value); + if (result === false) + continue; + rule.attrs = result || void 0; + } + return rule; + } + } + /** + @internal + */ + static schemaRules(schema) { + let result = []; + function insert(rule) { + let priority = rule.priority == null ? 50 : rule.priority, i = 0; + for (; i < result.length; i++) { + let next = result[i], nextPriority = next.priority == null ? 50 : next.priority; + if (nextPriority < priority) + break; + } + result.splice(i, 0, rule); + } + for (let name in schema.marks) { + let rules = schema.marks[name].spec.parseDOM; + if (rules) + rules.forEach((rule) => { + insert(rule = copy(rule)); + if (!(rule.mark || rule.ignore || rule.clearMark)) + rule.mark = name; + }); + } + for (let name in schema.nodes) { + let rules = schema.nodes[name].spec.parseDOM; + if (rules) + rules.forEach((rule) => { + insert(rule = copy(rule)); + if (!(rule.node || rule.ignore || rule.mark)) + rule.node = name; + }); + } + return result; + } + /** + Construct a DOM parser using the parsing rules listed in a + schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by + [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority). + */ + static fromSchema(schema) { + return schema.cached.domParser || (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema))); + } +} +const blockTags = { + address: true, + article: true, + aside: true, + blockquote: true, + canvas: true, + dd: true, + div: true, + dl: true, + fieldset: true, + figcaption: true, + figure: true, + footer: true, + form: true, + h1: true, + h2: true, + h3: true, + h4: true, + h5: true, + h6: true, + header: true, + hgroup: true, + hr: true, + li: true, + noscript: true, + ol: true, + output: true, + p: true, + pre: true, + section: true, + table: true, + tfoot: true, + ul: true +}; +const ignoreTags = { + head: true, + noscript: true, + object: true, + script: true, + style: true, + title: true +}; +const listTags = { ol: true, ul: true }; +const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4; +function wsOptionsFor(type, preserveWhitespace, base2) { + if (preserveWhitespace != null) + return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0); + return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT; +} +class NodeContext { + constructor(type, attrs, marks, solid, match, options) { + this.type = type; + this.attrs = attrs; + this.marks = marks; + this.solid = solid; + this.options = options; + this.content = []; + this.activeMarks = Mark$1.none; + this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); + } + findWrapping(node) { + if (!this.match) { + if (!this.type) + return []; + let fill = this.type.contentMatch.fillBefore(Fragment.from(node)); + if (fill) { + this.match = this.type.contentMatch.matchFragment(fill); + } else { + let start = this.type.contentMatch, wrap2; + if (wrap2 = start.findWrapping(node.type)) { + this.match = start; + return wrap2; + } else { + return null; + } + } + } + return this.match.findWrapping(node.type); + } + finish(openEnd) { + if (!(this.options & OPT_PRESERVE_WS)) { + let last = this.content[this.content.length - 1], m; + if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { + let text = last; + if (last.text.length == m[0].length) + this.content.pop(); + else + this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length)); + } + } + let content = Fragment.from(this.content); + if (!openEnd && this.match) + content = content.append(this.match.fillBefore(Fragment.empty, true)); + return this.type ? this.type.create(this.attrs, content, this.marks) : content; + } + inlineContext(node) { + if (this.type) + return this.type.inlineContent; + if (this.content.length) + return this.content[0].isInline; + return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase()); + } +} +class ParseContext { + constructor(parser, options, isOpen) { + this.parser = parser; + this.options = options; + this.isOpen = isOpen; + this.open = 0; + this.localPreserveWS = false; + let topNode = options.topNode, topContext; + let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0); + if (topNode) + topContext = new NodeContext(topNode.type, topNode.attrs, Mark$1.none, true, options.topMatch || topNode.type.contentMatch, topOptions); + else if (isOpen) + topContext = new NodeContext(null, null, Mark$1.none, true, null, topOptions); + else + topContext = new NodeContext(parser.schema.topNodeType, null, Mark$1.none, true, null, topOptions); + this.nodes = [topContext]; + this.find = options.findPositions; + this.needsBlock = false; + } + get top() { + return this.nodes[this.open]; + } + // Add a DOM node to the content. Text is inserted as text node, + // otherwise, the node is passed to `addElement` or, if it has a + // `style` attribute, `addElementWithStyles`. + addDOM(dom, marks) { + if (dom.nodeType == 3) + this.addTextNode(dom, marks); + else if (dom.nodeType == 1) + this.addElement(dom, marks); + } + addTextNode(dom, marks) { + let value = dom.nodeValue; + let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0; + let { schema } = this.parser; + if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) { + if (!preserveWS) { + value = value.replace(/[ \t\r\n\u000c]+/g, " "); + if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { + let nodeBefore = top.content[top.content.length - 1]; + let domNodeBefore = dom.previousSibling; + if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)) + value = value.slice(1); + } + } else if (preserveWS === "full") { + value = value.replace(/\r\n?/g, "\n"); + } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) { + let lines = value.split(/\r?\n|\r/); + for (let i = 0; i < lines.length; i++) { + if (i) + this.insertNode(schema.linebreakReplacement.create(), marks, true); + if (lines[i]) + this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i])); + } + value = ""; + } else { + value = value.replace(/\r?\n|\r/g, " "); + } + if (value) + this.insertNode(schema.text(value), marks, !/\S/.test(value)); + this.findInText(dom); + } else { + this.findInside(dom); + } + } + // Try to find a handler for the given tag and use that to parse. If + // none is found, the element's content nodes are added directly. + addElement(dom, marks, matchAfter) { + let outerWS = this.localPreserveWS, top = this.top; + if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace)) + this.localPreserveWS = true; + let name = dom.nodeName.toLowerCase(), ruleID; + if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) + normalizeList(dom); + let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter)); + out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { + this.findInside(dom); + this.ignoreFallback(dom, marks); + } else if (!rule || rule.skip || rule.closeParent) { + if (rule && rule.closeParent) + this.open = Math.max(0, this.open - 1); + else if (rule && rule.skip.nodeType) + dom = rule.skip; + let sync, oldNeedsBlock = this.needsBlock; + if (blockTags.hasOwnProperty(name)) { + if (top.content.length && top.content[0].isInline && this.open) { + this.open--; + top = this.top; + } + sync = true; + if (!top.type) + this.needsBlock = true; + } else if (!dom.firstChild) { + this.leafFallback(dom, marks); + break out; + } + let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks); + if (innerMarks) + this.addAll(dom, innerMarks); + if (sync) + this.sync(top); + this.needsBlock = oldNeedsBlock; + } else { + let innerMarks = this.readStyles(dom, marks); + if (innerMarks) + this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0); + } + this.localPreserveWS = outerWS; + } + // Called for leaf DOM nodes that would otherwise be ignored + leafFallback(dom, marks) { + if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) + this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks); + } + // Called for ignored nodes + ignoreFallback(dom, marks) { + if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent)) + this.findPlace(this.parser.schema.text("-"), marks, true); + } + // Run any style parser associated with the node's styles. Either + // return an updated array of marks, or null to indicate some of the + // styles had a rule with `ignore` set. + readStyles(dom, marks) { + let styles = dom.style; + if (styles && styles.length) + for (let i = 0; i < this.parser.matchedStyles.length; i++) { + let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name); + if (value) + for (let after = void 0; ; ) { + let rule = this.parser.matchStyle(name, value, this, after); + if (!rule) + break; + if (rule.ignore) + return null; + if (rule.clearMark) + marks = marks.filter((m) => !rule.clearMark(m)); + else + marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs)); + if (rule.consuming === false) + after = rule; + else + break; + } + } + return marks; + } + // Look up a handler for the given node. If none are found, return + // false. Otherwise, apply it, use its return value to drive the way + // the node's content is wrapped, and return true. + addElementByRule(dom, rule, marks, continueAfter) { + let sync, nodeType; + if (rule.node) { + nodeType = this.parser.schema.nodes[rule.node]; + if (!nodeType.isLeaf) { + let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace); + if (inner) { + sync = true; + marks = inner; + } + } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) { + this.leafFallback(dom, marks); + } + } else { + let markType = this.parser.schema.marks[rule.mark]; + marks = marks.concat(markType.create(rule.attrs)); + } + let startIn = this.top; + if (nodeType && nodeType.isLeaf) { + this.findInside(dom); + } else if (continueAfter) { + this.addElement(dom, marks, continueAfter); + } else if (rule.getContent) { + this.findInside(dom); + rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false)); + } else { + let contentDOM = dom; + if (typeof rule.contentElement == "string") + contentDOM = dom.querySelector(rule.contentElement); + else if (typeof rule.contentElement == "function") + contentDOM = rule.contentElement(dom); + else if (rule.contentElement) + contentDOM = rule.contentElement; + this.findAround(dom, contentDOM, true); + this.addAll(contentDOM, marks); + this.findAround(dom, contentDOM, false); + } + if (sync && this.sync(startIn)) + this.open--; + } + // Add all child nodes between `startIndex` and `endIndex` (or the + // whole node, if not given). If `sync` is passed, use it to + // synchronize after every block element. + addAll(parent, marks, startIndex, endIndex) { + let index = startIndex || 0; + for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { + this.findAtPoint(parent, index); + this.addDOM(dom, marks); + } + this.findAtPoint(parent, index); + } + // Try to find a way to fit the given node type into the current + // context. May add intermediate wrappers and/or leave non-solid + // nodes that we're in. + findPlace(node, marks, cautious) { + let route, sync; + for (let depth = this.open, penalty = 0; depth >= 0; depth--) { + let cx = this.nodes[depth]; + let found2 = cx.findWrapping(node); + if (found2 && (!route || route.length > found2.length + penalty)) { + route = found2; + sync = cx; + if (!found2.length) + break; + } + if (cx.solid) { + if (cautious) + break; + penalty += 2; + } + } + if (!route) + return null; + this.sync(sync); + for (let i = 0; i < route.length; i++) + marks = this.enterInner(route[i], null, marks, false); + return marks; + } + // Try to insert the given node, adjusting the context when needed. + insertNode(node, marks, cautious) { + if (node.isInline && this.needsBlock && !this.top.type) { + let block = this.textblockFromContext(); + if (block) + marks = this.enterInner(block, null, marks); + } + let innerMarks = this.findPlace(node, marks, cautious); + if (innerMarks) { + this.closeExtra(); + let top = this.top; + if (top.match) + top.match = top.match.matchType(node.type); + let nodeMarks = Mark$1.none; + for (let m of innerMarks.concat(node.marks)) + if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type)) + nodeMarks = m.addToSet(nodeMarks); + top.content.push(node.mark(nodeMarks)); + return true; + } + return false; + } + // Try to start a node of the given type, adjusting the context when + // necessary. + enter(type, attrs, marks, preserveWS) { + let innerMarks = this.findPlace(type.create(attrs), marks, false); + if (innerMarks) + innerMarks = this.enterInner(type, attrs, marks, true, preserveWS); + return innerMarks; + } + // Open a node of the given type + enterInner(type, attrs, marks, solid = false, preserveWS) { + this.closeExtra(); + let top = this.top; + top.match = top.match && top.match.matchType(type); + let options = wsOptionsFor(type, preserveWS, top.options); + if (top.options & OPT_OPEN_LEFT && top.content.length == 0) + options |= OPT_OPEN_LEFT; + let applyMarks = Mark$1.none; + marks = marks.filter((m) => { + if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) { + applyMarks = m.addToSet(applyMarks); + return false; + } + return true; + }); + this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options)); + this.open++; + return marks; + } + // Make sure all nodes above this.open are finished and added to + // their parents + closeExtra(openEnd = false) { + let i = this.nodes.length - 1; + if (i > this.open) { + for (; i > this.open; i--) + this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); + this.nodes.length = this.open + 1; + } + } + finish() { + this.open = 0; + this.closeExtra(this.isOpen); + return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen)); + } + sync(to) { + for (let i = this.open; i >= 0; i--) { + if (this.nodes[i] == to) { + this.open = i; + return true; + } else if (this.localPreserveWS) { + this.nodes[i].options |= OPT_PRESERVE_WS; + } + } + return false; + } + get currentPos() { + this.closeExtra(); + let pos = 0; + for (let i = this.open; i >= 0; i--) { + let content = this.nodes[i].content; + for (let j = content.length - 1; j >= 0; j--) + pos += content[j].nodeSize; + if (i) + pos++; + } + return pos; + } + findAtPoint(parent, offset) { + if (this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].node == parent && this.find[i].offset == offset) + this.find[i].pos = this.currentPos; + } + } + findInside(parent) { + if (this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) + this.find[i].pos = this.currentPos; + } + } + findAround(parent, content, before) { + if (parent != content && this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { + let pos = content.compareDocumentPosition(this.find[i].node); + if (pos & (before ? 2 : 4)) + this.find[i].pos = this.currentPos; + } + } + } + findInText(textNode) { + if (this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].node == textNode) + this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); + } + } + // Determines whether the given context string matches this context. + matchesContext(context) { + if (context.indexOf("|") > -1) + return context.split(/\s*\|\s*/).some(this.matchesContext, this); + let parts = context.split("/"); + let option = this.options.context; + let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); + let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); + let match = (i, depth) => { + for (; i >= 0; i--) { + let part = parts[i]; + if (part == "") { + if (i == parts.length - 1 || i == 0) + continue; + for (; depth >= minDepth; depth--) + if (match(i - 1, depth)) + return true; + return false; + } else { + let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null; + if (!next || next.name != part && !next.isInGroup(part)) + return false; + depth--; + } + } + return true; + }; + return match(parts.length - 1, this.open); + } + textblockFromContext() { + let $context = this.options.context; + if ($context) + for (let d = $context.depth; d >= 0; d--) { + let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; + if (deflt && deflt.isTextblock && deflt.defaultAttrs) + return deflt; + } + for (let name in this.parser.schema.nodes) { + let type = this.parser.schema.nodes[name]; + if (type.isTextblock && type.defaultAttrs) + return type; + } + } +} +function normalizeList(dom) { + for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { + let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; + if (name && listTags.hasOwnProperty(name) && prevItem) { + prevItem.appendChild(child); + child = prevItem; + } else if (name == "li") { + prevItem = child; + } else if (name) { + prevItem = null; + } + } +} +function matches(dom, selector) { + return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector); +} +function copy(obj) { + let copy2 = {}; + for (let prop in obj) + copy2[prop] = obj[prop]; + return copy2; +} +function markMayApply(markType, nodeType) { + let nodes = nodeType.schema.nodes; + for (let name in nodes) { + let parent = nodes[name]; + if (!parent.allowsMarkType(markType)) + continue; + let seen = [], scan = (match) => { + seen.push(match); + for (let i = 0; i < match.edgeCount; i++) { + let { type, next } = match.edge(i); + if (type == nodeType) + return true; + if (seen.indexOf(next) < 0 && scan(next)) + return true; + } + }; + if (scan(parent.contentMatch)) + return true; + } +} +class DOMSerializer { + /** + Create a serializer. `nodes` should map node names to functions + that take a node and return a description of the corresponding + DOM. `marks` does the same for mark names, but also gets an + argument that tells it whether the mark's content is block or + inline content (for typical use, it'll always be inline). A mark + serializer may be `null` to indicate that marks of that type + should not be serialized. + */ + constructor(nodes, marks) { + this.nodes = nodes; + this.marks = marks; + } + /** + Serialize the content of this fragment to a DOM fragment. When + not in the browser, the `document` option, containing a DOM + document, should be passed so that the serializer can create + nodes. + */ + serializeFragment(fragment, options = {}, target) { + if (!target) + target = doc$1(options).createDocumentFragment(); + let top = target, active = []; + fragment.forEach((node) => { + if (active.length || node.marks.length) { + let keep = 0, rendered = 0; + while (keep < active.length && rendered < node.marks.length) { + let next = node.marks[rendered]; + if (!this.marks[next.type.name]) { + rendered++; + continue; + } + if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) + break; + keep++; + rendered++; + } + while (keep < active.length) + top = active.pop()[1]; + while (rendered < node.marks.length) { + let add = node.marks[rendered++]; + let markDOM = this.serializeMark(add, node.isInline, options); + if (markDOM) { + active.push([add, top]); + top.appendChild(markDOM.dom); + top = markDOM.contentDOM || markDOM.dom; + } + } + } + top.appendChild(this.serializeNodeInner(node, options)); + }); + return target; + } + /** + @internal + */ + serializeNodeInner(node, options) { + let { dom, contentDOM } = renderSpec(doc$1(options), this.nodes[node.type.name](node), null, node.attrs); + if (contentDOM) { + if (node.isLeaf) + throw new RangeError("Content hole not allowed in a leaf node spec"); + this.serializeFragment(node.content, options, contentDOM); + } + return dom; + } + /** + Serialize this node to a DOM node. This can be useful when you + need to serialize a part of a document, as opposed to the whole + document. To serialize a whole document, use + [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on + its [content](https://prosemirror.net/docs/ref/#model.Node.content). + */ + serializeNode(node, options = {}) { + let dom = this.serializeNodeInner(node, options); + for (let i = node.marks.length - 1; i >= 0; i--) { + let wrap2 = this.serializeMark(node.marks[i], node.isInline, options); + if (wrap2) { + (wrap2.contentDOM || wrap2.dom).appendChild(dom); + dom = wrap2.dom; + } + } + return dom; + } + /** + @internal + */ + serializeMark(mark, inline, options = {}) { + let toDOM = this.marks[mark.type.name]; + return toDOM && renderSpec(doc$1(options), toDOM(mark, inline), null, mark.attrs); + } + static renderSpec(doc2, structure, xmlNS = null, blockArraysIn) { + return renderSpec(doc2, structure, xmlNS, blockArraysIn); + } + /** + Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM) + properties in a schema's node and mark specs. + */ + static fromSchema(schema) { + return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))); + } + /** + Gather the serializers in a schema's node specs into an object. + This can be useful as a base to build a custom serializer from. + */ + static nodesFromSchema(schema) { + let result = gatherToDOM(schema.nodes); + if (!result.text) + result.text = (node) => node.text; + return result; + } + /** + Gather the serializers in a schema's mark specs into an object. + */ + static marksFromSchema(schema) { + return gatherToDOM(schema.marks); + } +} +function gatherToDOM(obj) { + let result = {}; + for (let name in obj) { + let toDOM = obj[name].spec.toDOM; + if (toDOM) + result[name] = toDOM; + } + return result; +} +function doc$1(options) { + return options.document || window.document; +} +const suspiciousAttributeCache = /* @__PURE__ */ new WeakMap(); +function suspiciousAttributes(attrs) { + let value = suspiciousAttributeCache.get(attrs); + if (value === void 0) + suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs)); + return value; +} +function suspiciousAttributesInner(attrs) { + let result = null; + function scan(value) { + if (value && typeof value == "object") { + if (Array.isArray(value)) { + if (typeof value[0] == "string") { + if (!result) + result = []; + result.push(value); + } else { + for (let i = 0; i < value.length; i++) + scan(value[i]); + } + } else { + for (let prop in value) + scan(value[prop]); + } + } + } + scan(attrs); + return result; +} +function renderSpec(doc2, structure, xmlNS, blockArraysIn) { + if (typeof structure == "string") + return { dom: doc2.createTextNode(structure) }; + if (structure.nodeType != null) + return { dom: structure }; + if (structure.dom && structure.dom.nodeType != null) + return structure; + let tagName = structure[0], suspicious; + if (typeof tagName != "string") + throw new RangeError("Invalid array passed to renderSpec"); + if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1) + throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack."); + let space = tagName.indexOf(" "); + if (space > 0) { + xmlNS = tagName.slice(0, space); + tagName = tagName.slice(space + 1); + } + let contentDOM; + let dom = xmlNS ? doc2.createElementNS(xmlNS, tagName) : doc2.createElement(tagName); + let attrs = structure[1], start = 1; + if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { + start = 2; + for (let name in attrs) + if (attrs[name] != null) { + let space2 = name.indexOf(" "); + if (space2 > 0) + dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs[name]); + else if (name == "style" && dom.style) + dom.style.cssText = attrs[name]; + else + dom.setAttribute(name, attrs[name]); + } + } + for (let i = start; i < structure.length; i++) { + let child = structure[i]; + if (child === 0) { + if (i < structure.length - 1 || i > start) + throw new RangeError("Content hole must be the only child of its parent node"); + return { dom, contentDOM: dom }; + } else { + let { dom: inner, contentDOM: innerContent } = renderSpec(doc2, child, xmlNS, blockArraysIn); + dom.appendChild(inner); + if (innerContent) { + if (contentDOM) + throw new RangeError("Multiple content holes"); + contentDOM = innerContent; + } + } + } + return { dom, contentDOM }; +} +const lower16 = 65535; +const factor16 = Math.pow(2, 16); +function makeRecover(index, offset) { + return index + offset * factor16; +} +function recoverIndex(value) { + return value & lower16; +} +function recoverOffset(value) { + return (value - (value & lower16)) / factor16; +} +const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8; +class MapResult { + /** + @internal + */ + constructor(pos, delInfo, recover) { + this.pos = pos; + this.delInfo = delInfo; + this.recover = recover; + } + /** + Tells you whether the position was deleted, that is, whether the + step removed the token on the side queried (via the `assoc`) + argument from the document. + */ + get deleted() { + return (this.delInfo & DEL_SIDE) > 0; + } + /** + Tells you whether the token before the mapped position was deleted. + */ + get deletedBefore() { + return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; + } + /** + True when the token after the mapped position was deleted. + */ + get deletedAfter() { + return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; + } + /** + Tells whether any of the steps mapped through deletes across the + position (including both the token before and after the + position). + */ + get deletedAcross() { + return (this.delInfo & DEL_ACROSS) > 0; + } +} +class StepMap { + /** + Create a position map. The modifications to the document are + represented as an array of numbers, in which each group of three + represents a modified chunk as `[start, oldSize, newSize]`. + */ + constructor(ranges, inverted = false) { + this.ranges = ranges; + this.inverted = inverted; + if (!ranges.length && StepMap.empty) + return StepMap.empty; + } + /** + @internal + */ + recover(value) { + let diff = 0, index = recoverIndex(value); + if (!this.inverted) + for (let i = 0; i < index; i++) + diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; + return this.ranges[index * 3] + diff + recoverOffset(value); + } + mapResult(pos, assoc = 1) { + return this._map(pos, assoc, false); + } + map(pos, assoc = 1) { + return this._map(pos, assoc, true); + } + /** + @internal + */ + _map(pos, assoc, simple) { + let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (let i = 0; i < this.ranges.length; i += 3) { + let start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) + break; + let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize; + if (pos <= end) { + let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; + let result = start + diff + (side < 0 ? 0 : newSize); + if (simple) + return result; + let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start); + let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS; + if (assoc < 0 ? pos != start : pos != end) + del |= DEL_SIDE; + return new MapResult(result, del, recover); + } + diff += newSize - oldSize; + } + return simple ? pos + diff : new MapResult(pos + diff, 0, null); + } + /** + @internal + */ + touches(pos, recover) { + let diff = 0, index = recoverIndex(recover); + let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (let i = 0; i < this.ranges.length; i += 3) { + let start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) + break; + let oldSize = this.ranges[i + oldIndex], end = start + oldSize; + if (pos <= end && i == index * 3) + return true; + diff += this.ranges[i + newIndex] - oldSize; + } + return false; + } + /** + Calls the given function on each of the changed ranges included in + this map. + */ + forEach(f) { + let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (let i = 0, diff = 0; i < this.ranges.length; i += 3) { + let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); + let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex]; + f(oldStart, oldStart + oldSize, newStart, newStart + newSize); + diff += newSize - oldSize; + } + } + /** + Create an inverted version of this map. The result can be used to + map positions in the post-step document to the pre-step document. + */ + invert() { + return new StepMap(this.ranges, !this.inverted); + } + /** + @internal + */ + toString() { + return (this.inverted ? "-" : "") + JSON.stringify(this.ranges); + } + /** + Create a map that moves all positions by offset `n` (which may be + negative). This can be useful when applying steps meant for a + sub-document to a larger document, or vice-versa. + */ + static offset(n) { + return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]); + } +} +StepMap.empty = new StepMap([]); +class Mapping { + /** + Create a new mapping with the given position maps. + */ + constructor(maps, mirror, from2 = 0, to = maps ? maps.length : 0) { + this.mirror = mirror; + this.from = from2; + this.to = to; + this._maps = maps || []; + this.ownData = !(maps || mirror); + } + /** + The step maps in this mapping. + */ + get maps() { + return this._maps; + } + /** + Create a mapping that maps only through a part of this one. + */ + slice(from2 = 0, to = this.maps.length) { + return new Mapping(this._maps, this.mirror, from2, to); + } + /** + Add a step map to the end of this mapping. If `mirrors` is + given, it should be the index of the step map that is the mirror + image of this one. + */ + appendMap(map2, mirrors) { + if (!this.ownData) { + this._maps = this._maps.slice(); + this.mirror = this.mirror && this.mirror.slice(); + this.ownData = true; + } + this.to = this._maps.push(map2); + if (mirrors != null) + this.setMirror(this._maps.length - 1, mirrors); + } + /** + Add all the step maps in a given mapping to this one (preserving + mirroring information). + */ + appendMapping(mapping) { + for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) { + let mirr = mapping.getMirror(i); + this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : void 0); + } + } + /** + Finds the offset of the step map that mirrors the map at the + given offset, in this mapping (as per the second argument to + `appendMap`). + */ + getMirror(n) { + if (this.mirror) { + for (let i = 0; i < this.mirror.length; i++) + if (this.mirror[i] == n) + return this.mirror[i + (i % 2 ? -1 : 1)]; + } + } + /** + @internal + */ + setMirror(n, m) { + if (!this.mirror) + this.mirror = []; + this.mirror.push(n, m); + } + /** + Append the inverse of the given mapping to this one. + */ + appendMappingInverted(mapping) { + for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) { + let mirr = mapping.getMirror(i); + this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0); + } + } + /** + Create an inverted version of this mapping. + */ + invert() { + let inverse = new Mapping(); + inverse.appendMappingInverted(this); + return inverse; + } + /** + Map a position through this mapping. + */ + map(pos, assoc = 1) { + if (this.mirror) + return this._map(pos, assoc, true); + for (let i = this.from; i < this.to; i++) + pos = this._maps[i].map(pos, assoc); + return pos; + } + /** + Map a position through this mapping, returning a mapping + result. + */ + mapResult(pos, assoc = 1) { + return this._map(pos, assoc, false); + } + /** + @internal + */ + _map(pos, assoc, simple) { + let delInfo = 0; + for (let i = this.from; i < this.to; i++) { + let map2 = this._maps[i], result = map2.mapResult(pos, assoc); + if (result.recover != null) { + let corr = this.getMirror(i); + if (corr != null && corr > i && corr < this.to) { + i = corr; + pos = this._maps[corr].recover(result.recover); + continue; + } + } + delInfo |= result.delInfo; + pos = result.pos; + } + return simple ? pos : new MapResult(pos, delInfo, null); + } +} +const stepsByID = /* @__PURE__ */ Object.create(null); +class Step { + /** + Get the step map that represents the changes made by this step, + and which can be used to transform between positions in the old + and the new document. + */ + getMap() { + return StepMap.empty; + } + /** + Try to merge this step with another one, to be applied directly + after it. Returns the merged step when possible, null if the + steps can't be merged. + */ + merge(other) { + return null; + } + /** + Deserialize a step from its JSON representation. Will call + through to the step class' own implementation of this method. + */ + static fromJSON(schema, json) { + if (!json || !json.stepType) + throw new RangeError("Invalid input for Step.fromJSON"); + let type = stepsByID[json.stepType]; + if (!type) + throw new RangeError(`No step type ${json.stepType} defined`); + return type.fromJSON(schema, json); + } + /** + To be able to serialize steps to JSON, each step needs a string + ID to attach to its JSON representation. Use this method to + register an ID for your step classes. Try to pick something + that's unlikely to clash with steps from other modules. + */ + static jsonID(id, stepClass) { + if (id in stepsByID) + throw new RangeError("Duplicate use of step JSON ID " + id); + stepsByID[id] = stepClass; + stepClass.prototype.jsonID = id; + return stepClass; + } +} +class StepResult { + /** + @internal + */ + constructor(doc2, failed) { + this.doc = doc2; + this.failed = failed; + } + /** + Create a successful step result. + */ + static ok(doc2) { + return new StepResult(doc2, null); + } + /** + Create a failed step result. + */ + static fail(message) { + return new StepResult(null, message); + } + /** + Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given + arguments. Create a successful result if it succeeds, and a + failed one if it throws a `ReplaceError`. + */ + static fromReplace(doc2, from2, to, slice2) { + try { + return StepResult.ok(doc2.replace(from2, to, slice2)); + } catch (e) { + if (e instanceof ReplaceError) + return StepResult.fail(e.message); + throw e; + } + } +} +function mapFragment(fragment, f, parent) { + let mapped = []; + for (let i = 0; i < fragment.childCount; i++) { + let child = fragment.child(i); + if (child.content.size) + child = child.copy(mapFragment(child.content, f, child)); + if (child.isInline) + child = f(child, parent, i); + mapped.push(child); + } + return Fragment.fromArray(mapped); +} +class AddMarkStep extends Step { + /** + Create a mark step. + */ + constructor(from2, to, mark) { + super(); + this.from = from2; + this.to = to; + this.mark = mark; + } + apply(doc2) { + let oldSlice = doc2.slice(this.from, this.to), $from = doc2.resolve(this.from); + let parent = $from.node($from.sharedDepth(this.to)); + let slice2 = new Slice(mapFragment(oldSlice.content, (node, parent2) => { + if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type)) + return node; + return node.mark(this.mark.addToSet(node.marks)); + }, parent), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc2, this.from, this.to, slice2); + } + invert() { + return new RemoveMarkStep(this.from, this.to, this.mark); + } + map(mapping) { + let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from2.deleted && to.deleted || from2.pos >= to.pos) + return null; + return new AddMarkStep(from2.pos, to.pos, this.mark); + } + merge(other) { + if (other instanceof AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) + return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); + return null; + } + toJSON() { + return { + stepType: "addMark", + mark: this.mark.toJSON(), + from: this.from, + to: this.to + }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + throw new RangeError("Invalid input for AddMarkStep.fromJSON"); + return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); + } +} +Step.jsonID("addMark", AddMarkStep); +class RemoveMarkStep extends Step { + /** + Create a mark-removing step. + */ + constructor(from2, to, mark) { + super(); + this.from = from2; + this.to = to; + this.mark = mark; + } + apply(doc2) { + let oldSlice = doc2.slice(this.from, this.to); + let slice2 = new Slice(mapFragment(oldSlice.content, (node) => { + return node.mark(this.mark.removeFromSet(node.marks)); + }, doc2), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc2, this.from, this.to, slice2); + } + invert() { + return new AddMarkStep(this.from, this.to, this.mark); + } + map(mapping) { + let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from2.deleted && to.deleted || from2.pos >= to.pos) + return null; + return new RemoveMarkStep(from2.pos, to.pos, this.mark); + } + merge(other) { + if (other instanceof RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) + return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); + return null; + } + toJSON() { + return { + stepType: "removeMark", + mark: this.mark.toJSON(), + from: this.from, + to: this.to + }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + throw new RangeError("Invalid input for RemoveMarkStep.fromJSON"); + return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); + } +} +Step.jsonID("removeMark", RemoveMarkStep); +class AddNodeMarkStep extends Step { + /** + Create a node mark step. + */ + constructor(pos, mark) { + super(); + this.pos = pos; + this.mark = mark; + } + apply(doc2) { + let node = doc2.nodeAt(this.pos); + if (!node) + return StepResult.fail("No node at mark step's position"); + let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks)); + return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); + } + invert(doc2) { + let node = doc2.nodeAt(this.pos); + if (node) { + let newSet = this.mark.addToSet(node.marks); + if (newSet.length == node.marks.length) { + for (let i = 0; i < node.marks.length; i++) + if (!node.marks[i].isInSet(newSet)) + return new AddNodeMarkStep(this.pos, node.marks[i]); + return new AddNodeMarkStep(this.pos, this.mark); + } + } + return new RemoveNodeMarkStep(this.pos, this.mark); + } + map(mapping) { + let pos = mapping.mapResult(this.pos, 1); + return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark); + } + toJSON() { + return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.pos != "number") + throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON"); + return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); + } +} +Step.jsonID("addNodeMark", AddNodeMarkStep); +class RemoveNodeMarkStep extends Step { + /** + Create a mark-removing step. + */ + constructor(pos, mark) { + super(); + this.pos = pos; + this.mark = mark; + } + apply(doc2) { + let node = doc2.nodeAt(this.pos); + if (!node) + return StepResult.fail("No node at mark step's position"); + let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks)); + return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); + } + invert(doc2) { + let node = doc2.nodeAt(this.pos); + if (!node || !this.mark.isInSet(node.marks)) + return this; + return new AddNodeMarkStep(this.pos, this.mark); + } + map(mapping) { + let pos = mapping.mapResult(this.pos, 1); + return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark); + } + toJSON() { + return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.pos != "number") + throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON"); + return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); + } +} +Step.jsonID("removeNodeMark", RemoveNodeMarkStep); +class ReplaceStep extends Step { + /** + The given `slice` should fit the 'gap' between `from` and + `to`—the depths must line up, and the surrounding nodes must be + able to be joined with the open sides of the slice. When + `structure` is true, the step will fail if the content between + from and to is not just a sequence of closing and then opening + tokens (this is to guard against rebased replace steps + overwriting something they weren't supposed to). + */ + constructor(from2, to, slice2, structure = false) { + super(); + this.from = from2; + this.to = to; + this.slice = slice2; + this.structure = structure; + } + apply(doc2) { + if (this.structure && contentBetween(doc2, this.from, this.to)) + return StepResult.fail("Structure replace would overwrite content"); + return StepResult.fromReplace(doc2, this.from, this.to, this.slice); + } + getMap() { + return new StepMap([this.from, this.to - this.from, this.slice.size]); + } + invert(doc2) { + return new ReplaceStep(this.from, this.from + this.slice.size, doc2.slice(this.from, this.to)); + } + map(mapping) { + let to = mapping.mapResult(this.to, -1); + let from2 = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1); + if (from2.deletedAcross && to.deletedAcross) + return null; + return new ReplaceStep(from2.pos, Math.max(from2.pos, to.pos), this.slice, this.structure); + } + merge(other) { + if (!(other instanceof ReplaceStep) || other.structure || this.structure) + return null; + if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { + let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd); + return new ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure); + } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { + let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd); + return new ReplaceStep(other.from, this.to, slice2, this.structure); + } else { + return null; + } + } + toJSON() { + let json = { stepType: "replace", from: this.from, to: this.to }; + if (this.slice.size) + json.slice = this.slice.toJSON(); + if (this.structure) + json.structure = true; + return json; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + throw new RangeError("Invalid input for ReplaceStep.fromJSON"); + return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure); + } +} +ReplaceStep.MAP_BIAS = 1; +Step.jsonID("replace", ReplaceStep); +class ReplaceAroundStep extends Step { + /** + Create a replace-around step with the given range and gap. + `insert` should be the point in the slice into which the content + of the gap should be moved. `structure` has the same meaning as + it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class. + */ + constructor(from2, to, gapFrom, gapTo, slice2, insert, structure = false) { + super(); + this.from = from2; + this.to = to; + this.gapFrom = gapFrom; + this.gapTo = gapTo; + this.slice = slice2; + this.insert = insert; + this.structure = structure; + } + apply(doc2) { + if (this.structure && (contentBetween(doc2, this.from, this.gapFrom) || contentBetween(doc2, this.gapTo, this.to))) + return StepResult.fail("Structure gap-replace would overwrite content"); + let gap = doc2.slice(this.gapFrom, this.gapTo); + if (gap.openStart || gap.openEnd) + return StepResult.fail("Gap is not a flat range"); + let inserted = this.slice.insertAt(this.insert, gap.content); + if (!inserted) + return StepResult.fail("Content does not fit in gap"); + return StepResult.fromReplace(doc2, this.from, this.to, inserted); + } + getMap() { + return new StepMap([ + this.from, + this.gapFrom - this.from, + this.insert, + this.gapTo, + this.to - this.gapTo, + this.slice.size - this.insert + ]); + } + invert(doc2) { + let gap = this.gapTo - this.gapFrom; + return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure); + } + map(mapping) { + let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + let gapFrom = this.from == this.gapFrom ? from2.pos : mapping.map(this.gapFrom, -1); + let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1); + if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos) + return null; + return new ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure); + } + toJSON() { + let json = { + stepType: "replaceAround", + from: this.from, + to: this.to, + gapFrom: this.gapFrom, + gapTo: this.gapTo, + insert: this.insert + }; + if (this.slice.size) + json.slice = this.slice.toJSON(); + if (this.structure) + json.structure = true; + return json; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") + throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON"); + return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure); + } +} +Step.jsonID("replaceAround", ReplaceAroundStep); +function contentBetween(doc2, from2, to) { + let $from = doc2.resolve(from2), dist = to - from2, depth = $from.depth; + while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { + depth--; + dist--; + } + if (dist > 0) { + let next = $from.node(depth).maybeChild($from.indexAfter(depth)); + while (dist > 0) { + if (!next || next.isLeaf) + return true; + next = next.firstChild; + dist--; + } + } + return false; +} +function addMark(tr2, from2, to, mark) { + let removed = [], added = []; + let removing, adding; + tr2.doc.nodesBetween(from2, to, (node, pos, parent) => { + if (!node.isInline) + return; + let marks = node.marks; + if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { + let start = Math.max(pos, from2), end = Math.min(pos + node.nodeSize, to); + let newSet = mark.addToSet(marks); + for (let i = 0; i < marks.length; i++) { + if (!marks[i].isInSet(newSet)) { + if (removing && removing.to == start && removing.mark.eq(marks[i])) + removing.to = end; + else + removed.push(removing = new RemoveMarkStep(start, end, marks[i])); + } + } + if (adding && adding.to == start) + adding.to = end; + else + added.push(adding = new AddMarkStep(start, end, mark)); + } + }); + removed.forEach((s) => tr2.step(s)); + added.forEach((s) => tr2.step(s)); +} +function removeMark(tr2, from2, to, mark) { + let matched = [], step = 0; + tr2.doc.nodesBetween(from2, to, (node, pos) => { + if (!node.isInline) + return; + step++; + let toRemove = null; + if (mark instanceof MarkType) { + let set = node.marks, found2; + while (found2 = mark.isInSet(set)) { + (toRemove || (toRemove = [])).push(found2); + set = found2.removeFromSet(set); + } + } else if (mark) { + if (mark.isInSet(node.marks)) + toRemove = [mark]; + } else { + toRemove = node.marks; + } + if (toRemove && toRemove.length) { + let end = Math.min(pos + node.nodeSize, to); + for (let i = 0; i < toRemove.length; i++) { + let style2 = toRemove[i], found2; + for (let j = 0; j < matched.length; j++) { + let m = matched[j]; + if (m.step == step - 1 && style2.eq(matched[j].style)) + found2 = m; + } + if (found2) { + found2.to = end; + found2.step = step; + } else { + matched.push({ style: style2, from: Math.max(pos, from2), to: end, step }); + } + } + } + }); + matched.forEach((m) => tr2.step(new RemoveMarkStep(m.from, m.to, m.style))); +} +function clearIncompatible(tr2, pos, parentType, match = parentType.contentMatch, clearNewlines = true) { + let node = tr2.doc.nodeAt(pos); + let replSteps = [], cur = pos + 1; + for (let i = 0; i < node.childCount; i++) { + let child = node.child(i), end = cur + child.nodeSize; + let allowed = match.matchType(child.type); + if (!allowed) { + replSteps.push(new ReplaceStep(cur, end, Slice.empty)); + } else { + match = allowed; + for (let j = 0; j < child.marks.length; j++) + if (!parentType.allowsMarkType(child.marks[j].type)) + tr2.step(new RemoveMarkStep(cur, end, child.marks[j])); + if (clearNewlines && child.isText && parentType.whitespace != "pre") { + let m, newline = /\r?\n|\r/g, slice2; + while (m = newline.exec(child.text)) { + if (!slice2) + slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0); + replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice2)); + } + } + } + cur = end; + } + if (!match.validEnd) { + let fill = match.fillBefore(Fragment.empty, true); + tr2.replace(cur, cur, new Slice(fill, 0, 0)); + } + for (let i = replSteps.length - 1; i >= 0; i--) + tr2.step(replSteps[i]); +} +function canCut(node, start, end) { + return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end)); +} +function liftTarget(range) { + let parent = range.parent; + let content = parent.content.cutByIndex(range.startIndex, range.endIndex); + for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) { + let node = range.$from.node(depth); + let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter; + if (depth < range.depth && node.canReplace(index, endIndex, content)) + return depth; + if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) + break; + if (index) + contentBefore = 1; + if (endIndex < node.childCount) + contentAfter = 1; + } + return null; +} +function lift$2(tr2, range, target) { + let { $from, $to, depth } = range; + let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); + let start = gapStart, end = gapEnd; + let before = Fragment.empty, openStart = 0; + for (let d = depth, splitting = false; d > target; d--) + if (splitting || $from.index(d) > 0) { + splitting = true; + before = Fragment.from($from.node(d).copy(before)); + openStart++; + } else { + start--; + } + let after = Fragment.empty, openEnd = 0; + for (let d = depth, splitting = false; d > target; d--) + if (splitting || $to.after(d + 1) < $to.end(d)) { + splitting = true; + after = Fragment.from($to.node(d).copy(after)); + openEnd++; + } else { + end++; + } + tr2.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true)); +} +function findWrapping(range, nodeType, attrs = null, innerRange = range) { + let around = findWrappingOutside(range, nodeType); + let inner = around && findWrappingInside(innerRange, nodeType); + if (!inner) + return null; + return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner.map(withAttrs)); +} +function withAttrs(type) { + return { type, attrs: null }; +} +function findWrappingOutside(range, type) { + let { parent, startIndex, endIndex } = range; + let around = parent.contentMatchAt(startIndex).findWrapping(type); + if (!around) + return null; + let outer = around.length ? around[0] : type; + return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null; +} +function findWrappingInside(range, type) { + let { parent, startIndex, endIndex } = range; + let inner = parent.child(startIndex); + let inside = type.contentMatch.findWrapping(inner.type); + if (!inside) + return null; + let lastType = inside.length ? inside[inside.length - 1] : type; + let innerMatch = lastType.contentMatch; + for (let i = startIndex; innerMatch && i < endIndex; i++) + innerMatch = innerMatch.matchType(parent.child(i).type); + if (!innerMatch || !innerMatch.validEnd) + return null; + return inside; +} +function wrap(tr2, range, wrappers) { + let content = Fragment.empty; + for (let i = wrappers.length - 1; i >= 0; i--) { + if (content.size) { + let match = wrappers[i].type.contentMatch.matchFragment(content); + if (!match || !match.validEnd) + throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper"); + } + content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); + } + let start = range.start, end = range.end; + tr2.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)); +} +function setBlockType$1(tr2, from2, to, type, attrs) { + if (!type.isTextblock) + throw new RangeError("Type given to setBlockType should be a textblock"); + let mapFrom = tr2.steps.length; + tr2.doc.nodesBetween(from2, to, (node, pos) => { + let attrsHere = typeof attrs == "function" ? attrs(node) : attrs; + if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr2.doc, tr2.mapping.slice(mapFrom).map(pos), type)) { + let convertNewlines = null; + if (type.schema.linebreakReplacement) { + let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement); + if (pre && !supportLinebreak) + convertNewlines = false; + else if (!pre && supportLinebreak) + convertNewlines = true; + } + if (convertNewlines === false) + replaceLinebreaks(tr2, node, pos, mapFrom); + clearIncompatible(tr2, tr2.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null); + let mapping = tr2.mapping.slice(mapFrom); + let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); + tr2.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true)); + if (convertNewlines === true) + replaceNewlines(tr2, node, pos, mapFrom); + return false; + } + }); +} +function replaceNewlines(tr2, node, pos, mapFrom) { + node.forEach((child, offset) => { + if (child.isText) { + let m, newline = /\r?\n|\r/g; + while (m = newline.exec(child.text)) { + let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset + m.index); + tr2.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create()); + } + } + }); +} +function replaceLinebreaks(tr2, node, pos, mapFrom) { + node.forEach((child, offset) => { + if (child.type == child.type.schema.linebreakReplacement) { + let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset); + tr2.replaceWith(start, start + 1, node.type.schema.text("\n")); + } + }); +} +function canChangeType(doc2, pos, type) { + let $pos = doc2.resolve(pos), index = $pos.index(); + return $pos.parent.canReplaceWith(index, index + 1, type); +} +function setNodeMarkup(tr2, pos, type, attrs, marks) { + let node = tr2.doc.nodeAt(pos); + if (!node) + throw new RangeError("No node at given position"); + if (!type) + type = node.type; + let newNode = type.create(attrs, null, marks || node.marks); + if (node.isLeaf) + return tr2.replaceWith(pos, pos + node.nodeSize, newNode); + if (!type.validContent(node.content)) + throw new RangeError("Invalid content for node type " + type.name); + tr2.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true)); +} +function canSplit(doc2, pos, depth = 1, typesAfter) { + let $pos = doc2.resolve(pos), base2 = $pos.depth - depth; + let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent; + if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) + return false; + for (let d = $pos.depth - 1, i = depth - 2; d > base2; d--, i--) { + let node = $pos.node(d), index2 = $pos.index(d); + if (node.type.spec.isolating) + return false; + let rest = node.content.cutByIndex(index2, node.childCount); + let overrideChild = typesAfter && typesAfter[i + 1]; + if (overrideChild) + rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs)); + let after = typesAfter && typesAfter[i] || node; + if (!node.canReplace(index2 + 1, node.childCount) || !after.type.validContent(rest)) + return false; + } + let index = $pos.indexAfter(base2); + let baseType = typesAfter && typesAfter[0]; + return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type); +} +function split(tr2, pos, depth = 1, typesAfter) { + let $pos = tr2.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; + for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) { + before = Fragment.from($pos.node(d).copy(before)); + let typeAfter = typesAfter && typesAfter[i]; + after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); + } + tr2.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)); +} +function canJoin(doc2, pos) { + let $pos = doc2.resolve(pos), index = $pos.index(); + return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1); +} +function canAppendWithSubstitutedLinebreaks(a, b) { + if (!b.content.size) + a.type.compatibleContent(b.type); + let match = a.contentMatchAt(a.childCount); + let { linebreakReplacement } = a.type.schema; + for (let i = 0; i < b.childCount; i++) { + let child = b.child(i); + let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type; + match = match.matchType(type); + if (!match) + return false; + if (!a.type.allowsMarks(child.marks)) + return false; + } + return match.validEnd; +} +function joinable(a, b) { + return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b)); +} +function joinPoint(doc2, pos, dir = -1) { + let $pos = doc2.resolve(pos); + for (let d = $pos.depth; ; d--) { + let before, after, index = $pos.index(d); + if (d == $pos.depth) { + before = $pos.nodeBefore; + after = $pos.nodeAfter; + } else if (dir > 0) { + before = $pos.node(d + 1); + index++; + after = $pos.node(d).maybeChild(index); + } else { + before = $pos.node(d).maybeChild(index - 1); + after = $pos.node(d + 1); + } + if (before && !before.isTextblock && joinable(before, after) && $pos.node(d).canReplace(index, index + 1)) + return pos; + if (d == 0) + break; + pos = dir < 0 ? $pos.before(d) : $pos.after(d); + } +} +function join(tr2, pos, depth) { + let convertNewlines = null; + let { linebreakReplacement } = tr2.doc.type.schema; + let $before = tr2.doc.resolve(pos - depth), beforeType = $before.node().type; + if (linebreakReplacement && beforeType.inlineContent) { + let pre = beforeType.whitespace == "pre"; + let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement); + if (pre && !supportLinebreak) + convertNewlines = false; + else if (!pre && supportLinebreak) + convertNewlines = true; + } + let mapFrom = tr2.steps.length; + if (convertNewlines === false) { + let $after = tr2.doc.resolve(pos + depth); + replaceLinebreaks(tr2, $after.node(), $after.before(), mapFrom); + } + if (beforeType.inlineContent) + clearIncompatible(tr2, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null); + let mapping = tr2.mapping.slice(mapFrom), start = mapping.map(pos - depth); + tr2.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true)); + if (convertNewlines === true) { + let $full = tr2.doc.resolve(start); + replaceNewlines(tr2, $full.node(), $full.before(), tr2.steps.length); + } + return tr2; +} +function insertPoint(doc2, pos, nodeType) { + let $pos = doc2.resolve(pos); + if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) + return pos; + if ($pos.parentOffset == 0) + for (let d = $pos.depth - 1; d >= 0; d--) { + let index = $pos.index(d); + if ($pos.node(d).canReplaceWith(index, index, nodeType)) + return $pos.before(d + 1); + if (index > 0) + return null; + } + if ($pos.parentOffset == $pos.parent.content.size) + for (let d = $pos.depth - 1; d >= 0; d--) { + let index = $pos.indexAfter(d); + if ($pos.node(d).canReplaceWith(index, index, nodeType)) + return $pos.after(d + 1); + if (index < $pos.node(d).childCount) + return null; + } + return null; +} +function dropPoint(doc2, pos, slice2) { + let $pos = doc2.resolve(pos); + if (!slice2.content.size) + return pos; + let content = slice2.content; + for (let i = 0; i < slice2.openStart; i++) + content = content.firstChild.content; + for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) { + for (let d = $pos.depth; d >= 0; d--) { + let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; + let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); + let parent = $pos.node(d), fits = false; + if (pass == 1) { + fits = parent.canReplace(insertPos, insertPos, content); + } else { + let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type); + fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]); + } + if (fits) + return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1); + } + } + return null; +} +function replaceStep(doc2, from2, to = from2, slice2 = Slice.empty) { + if (from2 == to && !slice2.size) + return null; + let $from = doc2.resolve(from2), $to = doc2.resolve(to); + if (fitsTrivially($from, $to, slice2)) + return new ReplaceStep(from2, to, slice2); + return new Fitter($from, $to, slice2).fit(); +} +function fitsTrivially($from, $to, slice2) { + return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content); +} +class Fitter { + constructor($from, $to, unplaced) { + this.$from = $from; + this.$to = $to; + this.unplaced = unplaced; + this.frontier = []; + this.placed = Fragment.empty; + for (let i = 0; i <= $from.depth; i++) { + let node = $from.node(i); + this.frontier.push({ + type: node.type, + match: node.contentMatchAt($from.indexAfter(i)) + }); + } + for (let i = $from.depth; i > 0; i--) + this.placed = Fragment.from($from.node(i).copy(this.placed)); + } + get depth() { + return this.frontier.length - 1; + } + fit() { + while (this.unplaced.size) { + let fit = this.findFittable(); + if (fit) + this.placeNodes(fit); + else + this.openMore() || this.dropNode(); + } + let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; + let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); + if (!$to) + return null; + let content = this.placed, openStart = $from.depth, openEnd = $to.depth; + while (openStart && openEnd && content.childCount == 1) { + content = content.firstChild.content; + openStart--; + openEnd--; + } + let slice2 = new Slice(content, openStart, openEnd); + if (moveInline > -1) + return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize); + if (slice2.size || $from.pos != this.$to.pos) + return new ReplaceStep($from.pos, $to.pos, slice2); + return null; + } + // Find a position on the start spine of `this.unplaced` that has + // content that can be moved somewhere on the frontier. Returns two + // depths, one for the slice and one for the frontier. + findFittable() { + let startDepth = this.unplaced.openStart; + for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) { + let node = cur.firstChild; + if (cur.childCount > 1) + openEnd = 0; + if (node.type.spec.isolating && openEnd <= d) { + startDepth = d; + break; + } + cur = node.content; + } + for (let pass = 1; pass <= 2; pass++) { + for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { + let fragment, parent = null; + if (sliceDepth) { + parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; + fragment = parent.content; + } else { + fragment = this.unplaced.content; + } + let first2 = fragment.firstChild; + for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { + let { type, match } = this.frontier[frontierDepth], wrap2, inject = null; + if (pass == 1 && (first2 ? match.matchType(first2.type) || (inject = match.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type))) + return { sliceDepth, frontierDepth, parent, inject }; + else if (pass == 2 && first2 && (wrap2 = match.findWrapping(first2.type))) + return { sliceDepth, frontierDepth, parent, wrap: wrap2 }; + if (parent && match.matchType(parent.type)) + break; + } + } + } + } + openMore() { + let { content, openStart, openEnd } = this.unplaced; + let inner = contentAt(content, openStart); + if (!inner.childCount || inner.firstChild.isLeaf) + return false; + this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0)); + return true; + } + dropNode() { + let { content, openStart, openEnd } = this.unplaced; + let inner = contentAt(content, openStart); + if (inner.childCount <= 1 && openStart > 0) { + let openAtEnd = content.size - openStart <= openStart + inner.size; + this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd); + } else { + this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); + } + } + // Move content from the unplaced slice at `sliceDepth` to the + // frontier node at `frontierDepth`. Close that frontier node when + // applicable. + placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) { + while (this.depth > frontierDepth) + this.closeFrontierNode(); + if (wrap2) + for (let i = 0; i < wrap2.length; i++) + this.openFrontierNode(wrap2[i]); + let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content; + let openStart = slice2.openStart - sliceDepth; + let taken = 0, add = []; + let { match, type } = this.frontier[frontierDepth]; + if (inject) { + for (let i = 0; i < inject.childCount; i++) + add.push(inject.child(i)); + match = match.matchFragment(inject); + } + let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd); + while (taken < fragment.childCount) { + let next = fragment.child(taken), matches2 = match.matchType(next.type); + if (!matches2) + break; + taken++; + if (taken > 1 || openStart == 0 || next.content.size) { + match = matches2; + add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1)); + } + } + let toEnd = taken == fragment.childCount; + if (!toEnd) + openEndCount = -1; + this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); + this.frontier[frontierDepth].match = match; + if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) + this.closeFrontierNode(); + for (let i = 0, cur = fragment; i < openEndCount; i++) { + let node = cur.lastChild; + this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) }); + cur = node.content; + } + this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1); + } + mustMoveInline() { + if (!this.$to.parent.isTextblock) + return -1; + let top = this.frontier[this.depth], level; + if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) + return -1; + let { depth } = this.$to, after = this.$to.after(depth); + while (depth > 1 && after == this.$to.end(--depth)) + ++after; + return after; + } + findCloseLevel($to) { + scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) { + let { match, type } = this.frontier[i]; + let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1)); + let fit = contentAfterFits($to, i, type, match, dropInner); + if (!fit) + continue; + for (let d = i - 1; d >= 0; d--) { + let { match: match2, type: type2 } = this.frontier[d]; + let matches2 = contentAfterFits($to, d, type2, match2, true); + if (!matches2 || matches2.childCount) + continue scan; + } + return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to }; + } + } + close($to) { + let close2 = this.findCloseLevel($to); + if (!close2) + return null; + while (this.depth > close2.depth) + this.closeFrontierNode(); + if (close2.fit.childCount) + this.placed = addToFragment(this.placed, close2.depth, close2.fit); + $to = close2.move; + for (let d = close2.depth + 1; d <= $to.depth; d++) { + let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); + this.openFrontierNode(node.type, node.attrs, add); + } + return $to; + } + openFrontierNode(type, attrs = null, content) { + let top = this.frontier[this.depth]; + top.match = top.match.matchType(type); + this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); + this.frontier.push({ type, match: type.contentMatch }); + } + closeFrontierNode() { + let open = this.frontier.pop(); + let add = open.match.fillBefore(Fragment.empty, true); + if (add.childCount) + this.placed = addToFragment(this.placed, this.frontier.length, add); + } +} +function dropFromFragment(fragment, depth, count) { + if (depth == 0) + return fragment.cutByIndex(count, fragment.childCount); + return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))); +} +function addToFragment(fragment, depth, content) { + if (depth == 0) + return fragment.append(content); + return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))); +} +function contentAt(fragment, depth) { + for (let i = 0; i < depth; i++) + fragment = fragment.firstChild.content; + return fragment; +} +function closeNodeStart(node, openStart, openEnd) { + if (openStart <= 0) + return node; + let frag = node.content; + if (openStart > 1) + frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); + if (openStart > 0) { + frag = node.type.contentMatch.fillBefore(frag).append(frag); + if (openEnd <= 0) + frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); + } + return node.copy(frag); +} +function contentAfterFits($to, depth, type, match, open) { + let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); + if (index == node.childCount && !type.compatibleContent(node.type)) + return null; + let fit = match.fillBefore(node.content, true, index); + return fit && !invalidMarks(type, node.content, index) ? fit : null; +} +function invalidMarks(type, fragment, start) { + for (let i = start; i < fragment.childCount; i++) + if (!type.allowsMarks(fragment.child(i).marks)) + return true; + return false; +} +function definesContent(type) { + return type.spec.defining || type.spec.definingForContent; +} +function replaceRange(tr2, from2, to, slice2) { + if (!slice2.size) + return tr2.deleteRange(from2, to); + let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to); + if (fitsTrivially($from, $to, slice2)) + return tr2.step(new ReplaceStep(from2, to, slice2)); + let targetDepths = coveredDepths($from, $to); + if (targetDepths[targetDepths.length - 1] == 0) + targetDepths.pop(); + let preferredTarget = -($from.depth + 1); + targetDepths.unshift(preferredTarget); + for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { + let spec = $from.node(d).type.spec; + if (spec.defining || spec.definingAsContext || spec.isolating) + break; + if (targetDepths.indexOf(d) > -1) + preferredTarget = d; + else if ($from.before(d) == pos) + targetDepths.splice(1, 0, -d); + } + let preferredTargetIndex = targetDepths.indexOf(preferredTarget); + let leftNodes = [], preferredDepth = slice2.openStart; + for (let content = slice2.content, i = 0; ; i++) { + let node = content.firstChild; + leftNodes.push(node); + if (i == slice2.openStart) + break; + content = node.content; + } + for (let d = preferredDepth - 1; d >= 0; d--) { + let leftNode = leftNodes[d], def = definesContent(leftNode.type); + if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) + preferredDepth = d; + else if (def || !leftNode.type.isTextblock) + break; + } + for (let j = slice2.openStart; j >= 0; j--) { + let openDepth = (j + preferredDepth + 1) % (slice2.openStart + 1); + let insert = leftNodes[openDepth]; + if (!insert) + continue; + for (let i = 0; i < targetDepths.length; i++) { + let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true; + if (targetDepth < 0) { + expand = false; + targetDepth = -targetDepth; + } + let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); + if (parent.canReplaceWith(index, index, insert.type, insert.marks)) + return tr2.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd)); + } + } + let startSteps = tr2.steps.length; + for (let i = targetDepths.length - 1; i >= 0; i--) { + tr2.replace(from2, to, slice2); + if (tr2.steps.length > startSteps) + break; + let depth = targetDepths[i]; + if (depth < 0) + continue; + from2 = $from.before(depth); + to = $to.after(depth); + } +} +function closeFragment(fragment, depth, oldOpen, newOpen, parent) { + if (depth < oldOpen) { + let first2 = fragment.firstChild; + fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2))); + } + if (depth > newOpen) { + let match = parent.contentMatchAt(0); + let start = match.fillBefore(fragment).append(fragment); + fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); + } + return fragment; +} +function replaceRangeWith(tr2, from2, to, node) { + if (!node.isInline && from2 == to && tr2.doc.resolve(from2).parent.content.size) { + let point = insertPoint(tr2.doc, from2, node.type); + if (point != null) + from2 = to = point; + } + tr2.replaceRange(from2, to, new Slice(Fragment.from(node), 0, 0)); +} +function deleteRange$1(tr2, from2, to) { + let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to); + if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() && $from.parentOffset == 0 && $to.parentOffset == 0) { + let shared = $from.sharedDepth(to), isolated = false; + for (let d = $from.depth; d > shared; d--) + if ($from.node(d).type.spec.isolating) + isolated = true; + for (let d = $to.depth; d > shared; d--) + if ($to.node(d).type.spec.isolating) + isolated = true; + if (!isolated) { + for (let d = $from.depth; d > 0 && from2 == $from.start(d); d--) + from2 = $from.before(d); + for (let d = $to.depth; d > 0 && to == $to.start(d); d--) + to = $to.before(d); + $from = tr2.doc.resolve(from2); + $to = tr2.doc.resolve(to); + } + } + let covered = coveredDepths($from, $to); + for (let i = 0; i < covered.length; i++) { + let depth = covered[i], last = i == covered.length - 1; + if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) + return tr2.delete($from.start(depth), $to.end(depth)); + if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) + return tr2.delete($from.before(depth), $to.after(depth)); + } + for (let d = 1; d <= $from.depth && d <= $to.depth; d++) { + if (from2 - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1))) + return tr2.delete($from.before(d), to); + } + tr2.delete(from2, to); +} +function coveredDepths($from, $to) { + let result = [], minDepth = Math.min($from.depth, $to.depth); + for (let d = minDepth; d >= 0; d--) { + let start = $from.start(d); + if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) + break; + if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1) + result.push(d); + } + return result; +} +class AttrStep extends Step { + /** + Construct an attribute step. + */ + constructor(pos, attr, value) { + super(); + this.pos = pos; + this.attr = attr; + this.value = value; + } + apply(doc2) { + let node = doc2.nodeAt(this.pos); + if (!node) + return StepResult.fail("No node at attribute step's position"); + let attrs = /* @__PURE__ */ Object.create(null); + for (let name in node.attrs) + attrs[name] = node.attrs[name]; + attrs[this.attr] = this.value; + let updated = node.type.create(attrs, null, node.marks); + return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); + } + getMap() { + return StepMap.empty; + } + invert(doc2) { + return new AttrStep(this.pos, this.attr, doc2.nodeAt(this.pos).attrs[this.attr]); + } + map(mapping) { + let pos = mapping.mapResult(this.pos, 1); + return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value); + } + toJSON() { + return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value }; + } + static fromJSON(schema, json) { + if (typeof json.pos != "number" || typeof json.attr != "string") + throw new RangeError("Invalid input for AttrStep.fromJSON"); + return new AttrStep(json.pos, json.attr, json.value); + } +} +Step.jsonID("attr", AttrStep); +class DocAttrStep extends Step { + /** + Construct an attribute step. + */ + constructor(attr, value) { + super(); + this.attr = attr; + this.value = value; + } + apply(doc2) { + let attrs = /* @__PURE__ */ Object.create(null); + for (let name in doc2.attrs) + attrs[name] = doc2.attrs[name]; + attrs[this.attr] = this.value; + let updated = doc2.type.create(attrs, doc2.content, doc2.marks); + return StepResult.ok(updated); + } + getMap() { + return StepMap.empty; + } + invert(doc2) { + return new DocAttrStep(this.attr, doc2.attrs[this.attr]); + } + map(mapping) { + return this; + } + toJSON() { + return { stepType: "docAttr", attr: this.attr, value: this.value }; + } + static fromJSON(schema, json) { + if (typeof json.attr != "string") + throw new RangeError("Invalid input for DocAttrStep.fromJSON"); + return new DocAttrStep(json.attr, json.value); + } +} +Step.jsonID("docAttr", DocAttrStep); +let TransformError = class extends Error { +}; +TransformError = function TransformError2(message) { + let err = Error.call(this, message); + err.__proto__ = TransformError2.prototype; + return err; +}; +TransformError.prototype = Object.create(Error.prototype); +TransformError.prototype.constructor = TransformError; +TransformError.prototype.name = "TransformError"; +class Transform { + /** + Create a transform that starts with the given document. + */ + constructor(doc2) { + this.doc = doc2; + this.steps = []; + this.docs = []; + this.mapping = new Mapping(); + } + /** + The starting document. + */ + get before() { + return this.docs.length ? this.docs[0] : this.doc; + } + /** + Apply a new step in this transform, saving the result. Throws an + error when the step fails. + */ + step(step) { + let result = this.maybeStep(step); + if (result.failed) + throw new TransformError(result.failed); + return this; + } + /** + Try to apply a step in this transformation, ignoring it if it + fails. Returns the step result. + */ + maybeStep(step) { + let result = step.apply(this.doc); + if (!result.failed) + this.addStep(step, result.doc); + return result; + } + /** + True when the document has been changed (when there are any + steps). + */ + get docChanged() { + return this.steps.length > 0; + } + /** + Return a single range, in post-transform document positions, + that covers all content changed by this transform. Returns null + if no replacements are made. Note that this will ignore changes + that add/remove marks without replacing the underlying content. + */ + changedRange() { + let from2 = 1e9, to = -1e9; + for (let i = 0; i < this.mapping.maps.length; i++) { + let map2 = this.mapping.maps[i]; + if (i) { + from2 = map2.map(from2, 1); + to = map2.map(to, -1); + } + map2.forEach((_f, _t, fromB, toB) => { + from2 = Math.min(from2, fromB); + to = Math.max(to, toB); + }); + } + return from2 == 1e9 ? null : { from: from2, to }; + } + /** + @internal + */ + addStep(step, doc2) { + this.docs.push(this.doc); + this.steps.push(step); + this.mapping.appendMap(step.getMap()); + this.doc = doc2; + } + /** + Replace the part of the document between `from` and `to` with the + given `slice`. + */ + replace(from2, to = from2, slice2 = Slice.empty) { + let step = replaceStep(this.doc, from2, to, slice2); + if (step) + this.step(step); + return this; + } + /** + Replace the given range with the given content, which may be a + fragment, node, or array of nodes. + */ + replaceWith(from2, to, content) { + return this.replace(from2, to, new Slice(Fragment.from(content), 0, 0)); + } + /** + Delete the content between the given positions. + */ + delete(from2, to) { + return this.replace(from2, to, Slice.empty); + } + /** + Insert the given content at the given position. + */ + insert(pos, content) { + return this.replaceWith(pos, pos, content); + } + /** + Replace a range of the document with a given slice, using + `from`, `to`, and the slice's + [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather + than fixed start and end points. This method may grow the + replaced area or close open nodes in the slice in order to get a + fit that is more in line with WYSIWYG expectations, by dropping + fully covered parent nodes of the replaced region when they are + marked [non-defining as + context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an + open parent node from the slice that _is_ marked as [defining + its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent). + + This is the method, for example, to handle paste. The similar + [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more + primitive tool which will _not_ move the start and end of its given + range, and is useful in situations where you need more precise + control over what happens. + */ + replaceRange(from2, to, slice2) { + replaceRange(this, from2, to, slice2); + return this; + } + /** + Replace the given range with a node, but use `from` and `to` as + hints, rather than precise positions. When from and to are the same + and are at the start or end of a parent node in which the given + node doesn't fit, this method may _move_ them out towards a parent + that does allow the given node to be placed. When the given range + completely covers a parent node, this method may completely replace + that parent node. + */ + replaceRangeWith(from2, to, node) { + replaceRangeWith(this, from2, to, node); + return this; + } + /** + Delete the given range, expanding it to cover fully covered + parent nodes until a valid replace is found. + */ + deleteRange(from2, to) { + deleteRange$1(this, from2, to); + return this; + } + /** + Split the content in the given range off from its parent, if there + is sibling content before or after it, and move it up the tree to + the depth specified by `target`. You'll probably want to use + [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make + sure the lift is valid. + */ + lift(range, target) { + lift$2(this, range, target); + return this; + } + /** + Join the blocks around the given position. If depth is 2, their + last and first siblings are also joined, and so on. + */ + join(pos, depth = 1) { + join(this, pos, depth); + return this; + } + /** + Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers. + The wrappers are assumed to be valid in this position, and should + probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping). + */ + wrap(range, wrappers) { + wrap(this, range, wrappers); + return this; + } + /** + Set the type of all textblocks (partly) between `from` and `to` to + the given node type with the given attributes. + */ + setBlockType(from2, to = from2, type, attrs = null) { + setBlockType$1(this, from2, to, type, attrs); + return this; + } + /** + Change the type, attributes, and/or marks of the node at `pos`. + When `type` isn't given, the existing node type is preserved, + */ + setNodeMarkup(pos, type, attrs = null, marks) { + setNodeMarkup(this, pos, type, attrs, marks); + return this; + } + /** + Set a single attribute on a given node to a new value. + The `pos` addresses the document content. Use `setDocAttribute` + to set attributes on the document itself. + */ + setNodeAttribute(pos, attr, value) { + this.step(new AttrStep(pos, attr, value)); + return this; + } + /** + Set a single attribute on the document to a new value. + */ + setDocAttribute(attr, value) { + this.step(new DocAttrStep(attr, value)); + return this; + } + /** + Add a mark to the node at position `pos`. + */ + addNodeMark(pos, mark) { + this.step(new AddNodeMarkStep(pos, mark)); + return this; + } + /** + Remove a mark (or all marks of the given type) from the node at + position `pos`. + */ + removeNodeMark(pos, mark) { + let node = this.doc.nodeAt(pos); + if (!node) + throw new RangeError("No node at position " + pos); + if (mark instanceof Mark$1) { + if (mark.isInSet(node.marks)) + this.step(new RemoveNodeMarkStep(pos, mark)); + } else { + let set = node.marks, found2, steps = []; + while (found2 = mark.isInSet(set)) { + steps.push(new RemoveNodeMarkStep(pos, found2)); + set = found2.removeFromSet(set); + } + for (let i = steps.length - 1; i >= 0; i--) + this.step(steps[i]); + } + return this; + } + /** + Split the node at the given position, and optionally, if `depth` is + greater than one, any number of nodes above that. By default, the + parts split off will inherit the node type of the original node. + This can be changed by passing an array of types and attributes to + use after the split (with the outermost nodes coming first). + */ + split(pos, depth = 1, typesAfter) { + split(this, pos, depth, typesAfter); + return this; + } + /** + Add the given mark to the inline content between `from` and `to`. + */ + addMark(from2, to, mark) { + addMark(this, from2, to, mark); + return this; + } + /** + Remove marks from inline nodes between `from` and `to`. When + `mark` is a single mark, remove precisely that mark. When it is + a mark type, remove all marks of that type. When it is null, + remove all marks of any type. + */ + removeMark(from2, to, mark) { + removeMark(this, from2, to, mark); + return this; + } + /** + Removes all marks and nodes from the content of the node at + `pos` that don't match the given new parent node type. Accepts + an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as + third argument. + */ + clearIncompatible(pos, parentType, match) { + clearIncompatible(this, pos, parentType, match); + return this; + } +} +const classesById = /* @__PURE__ */ Object.create(null); +class Selection { + /** + Initialize a selection with the head and anchor and ranges. If no + ranges are given, constructs a single range across `$anchor` and + `$head`. + */ + constructor($anchor, $head, ranges) { + this.$anchor = $anchor; + this.$head = $head; + this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; + } + /** + The selection's anchor, as an unresolved position. + */ + get anchor() { + return this.$anchor.pos; + } + /** + The selection's head. + */ + get head() { + return this.$head.pos; + } + /** + The lower bound of the selection's main range. + */ + get from() { + return this.$from.pos; + } + /** + The upper bound of the selection's main range. + */ + get to() { + return this.$to.pos; + } + /** + The resolved lower bound of the selection's main range. + */ + get $from() { + return this.ranges[0].$from; + } + /** + The resolved upper bound of the selection's main range. + */ + get $to() { + return this.ranges[0].$to; + } + /** + Indicates whether the selection contains any content. + */ + get empty() { + let ranges = this.ranges; + for (let i = 0; i < ranges.length; i++) + if (ranges[i].$from.pos != ranges[i].$to.pos) + return false; + return true; + } + /** + Get the content of this selection as a slice. + */ + content() { + return this.$from.doc.slice(this.from, this.to, true); + } + /** + Replace the selection with a slice or, if no slice is given, + delete the selection. Will append to the given transaction. + */ + replace(tr2, content = Slice.empty) { + let lastNode = content.content.lastChild, lastParent = null; + for (let i = 0; i < content.openEnd; i++) { + lastParent = lastNode; + lastNode = lastNode.lastChild; + } + let mapFrom = tr2.steps.length, ranges = this.ranges; + for (let i = 0; i < ranges.length; i++) { + let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); + tr2.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content); + if (i == 0) + selectionToInsertionEnd$1(tr2, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); + } + } + /** + Replace the selection with the given node, appending the changes + to the given transaction. + */ + replaceWith(tr2, node) { + let mapFrom = tr2.steps.length, ranges = this.ranges; + for (let i = 0; i < ranges.length; i++) { + let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); + let from2 = mapping.map($from.pos), to = mapping.map($to.pos); + if (i) { + tr2.deleteRange(from2, to); + } else { + tr2.replaceRangeWith(from2, to, node); + selectionToInsertionEnd$1(tr2, mapFrom, node.isInline ? -1 : 1); + } + } + } + /** + Find a valid cursor or leaf node selection starting at the given + position and searching back if `dir` is negative, and forward if + positive. When `textOnly` is true, only consider cursor + selections. Will return null when no valid selection position is + found. + */ + static findFrom($pos, dir, textOnly = false) { + let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); + if (inner) + return inner; + for (let depth = $pos.depth - 1; depth >= 0; depth--) { + let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly); + if (found2) + return found2; + } + return null; + } + /** + Find a valid cursor or leaf node selection near the given + position. Searches forward first by default, but if `bias` is + negative, it will search backwards first. + */ + static near($pos, bias = 1) { + return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)); + } + /** + Find the cursor or leaf node selection closest to the start of + the given document. Will return an + [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position + exists. + */ + static atStart(doc2) { + return findSelectionIn(doc2, doc2, 0, 0, 1) || new AllSelection(doc2); + } + /** + Find the cursor or leaf node selection closest to the end of the + given document. + */ + static atEnd(doc2) { + return findSelectionIn(doc2, doc2, doc2.content.size, doc2.childCount, -1) || new AllSelection(doc2); + } + /** + Deserialize the JSON representation of a selection. Must be + implemented for custom classes (as a static class method). + */ + static fromJSON(doc2, json) { + if (!json || !json.type) + throw new RangeError("Invalid input for Selection.fromJSON"); + let cls = classesById[json.type]; + if (!cls) + throw new RangeError(`No selection type ${json.type} defined`); + return cls.fromJSON(doc2, json); + } + /** + To be able to deserialize selections from JSON, custom selection + classes must register themselves with an ID string, so that they + can be disambiguated. Try to pick something that's unlikely to + clash with classes from other modules. + */ + static jsonID(id, selectionClass) { + if (id in classesById) + throw new RangeError("Duplicate use of selection JSON ID " + id); + classesById[id] = selectionClass; + selectionClass.prototype.jsonID = id; + return selectionClass; + } + /** + Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection, + which is a value that can be mapped without having access to a + current document, and later resolved to a real selection for a + given document again. (This is used mostly by the history to + track and restore old selections.) The default implementation of + this method just converts the selection to a text selection and + returns the bookmark for that. + */ + getBookmark() { + return TextSelection.between(this.$anchor, this.$head).getBookmark(); + } +} +Selection.prototype.visible = true; +class SelectionRange { + /** + Create a range. + */ + constructor($from, $to) { + this.$from = $from; + this.$to = $to; + } +} +let warnedAboutTextSelection = false; +function checkTextSelection($pos) { + if (!warnedAboutTextSelection && !$pos.parent.inlineContent) { + warnedAboutTextSelection = true; + console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")"); + } +} +class TextSelection extends Selection { + /** + Construct a text selection between the given points. + */ + constructor($anchor, $head = $anchor) { + checkTextSelection($anchor); + checkTextSelection($head); + super($anchor, $head); + } + /** + Returns a resolved position if this is a cursor selection (an + empty text selection), and null otherwise. + */ + get $cursor() { + return this.$anchor.pos == this.$head.pos ? this.$head : null; + } + map(doc2, mapping) { + let $head = doc2.resolve(mapping.map(this.head)); + if (!$head.parent.inlineContent) + return Selection.near($head); + let $anchor = doc2.resolve(mapping.map(this.anchor)); + return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head); + } + replace(tr2, content = Slice.empty) { + super.replace(tr2, content); + if (content == Slice.empty) { + let marks = this.$from.marksAcross(this.$to); + if (marks) + tr2.ensureMarks(marks); + } + } + eq(other) { + return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head; + } + getBookmark() { + return new TextBookmark(this.anchor, this.head); + } + toJSON() { + return { type: "text", anchor: this.anchor, head: this.head }; + } + /** + @internal + */ + static fromJSON(doc2, json) { + if (typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid input for TextSelection.fromJSON"); + return new TextSelection(doc2.resolve(json.anchor), doc2.resolve(json.head)); + } + /** + Create a text selection from non-resolved positions. + */ + static create(doc2, anchor, head = anchor) { + let $anchor = doc2.resolve(anchor); + return new this($anchor, head == anchor ? $anchor : doc2.resolve(head)); + } + /** + Return a text selection that spans the given positions or, if + they aren't text positions, find a text selection near them. + `bias` determines whether the method searches forward (default) + or backwards (negative number) first. Will fall back to calling + [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document + doesn't contain a valid text position. + */ + static between($anchor, $head, bias) { + let dPos = $anchor.pos - $head.pos; + if (!bias || dPos) + bias = dPos >= 0 ? 1 : -1; + if (!$head.parent.inlineContent) { + let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true); + if (found2) + $head = found2.$head; + else + return Selection.near($head, bias); + } + if (!$anchor.parent.inlineContent) { + if (dPos == 0) { + $anchor = $head; + } else { + $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor; + if ($anchor.pos < $head.pos != dPos < 0) + $anchor = $head; + } + } + return new TextSelection($anchor, $head); + } +} +Selection.jsonID("text", TextSelection); +class TextBookmark { + constructor(anchor, head) { + this.anchor = anchor; + this.head = head; + } + map(mapping) { + return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head)); + } + resolve(doc2) { + return TextSelection.between(doc2.resolve(this.anchor), doc2.resolve(this.head)); + } +} +class NodeSelection extends Selection { + /** + Create a node selection. Does not verify the validity of its + argument. + */ + constructor($pos) { + let node = $pos.nodeAfter; + let $end = $pos.node(0).resolve($pos.pos + node.nodeSize); + super($pos, $end); + this.node = node; + } + map(doc2, mapping) { + let { deleted, pos } = mapping.mapResult(this.anchor); + let $pos = doc2.resolve(pos); + if (deleted) + return Selection.near($pos); + return new NodeSelection($pos); + } + content() { + return new Slice(Fragment.from(this.node), 0, 0); + } + eq(other) { + return other instanceof NodeSelection && other.anchor == this.anchor; + } + toJSON() { + return { type: "node", anchor: this.anchor }; + } + getBookmark() { + return new NodeBookmark(this.anchor); + } + /** + @internal + */ + static fromJSON(doc2, json) { + if (typeof json.anchor != "number") + throw new RangeError("Invalid input for NodeSelection.fromJSON"); + return new NodeSelection(doc2.resolve(json.anchor)); + } + /** + Create a node selection from non-resolved positions. + */ + static create(doc2, from2) { + return new NodeSelection(doc2.resolve(from2)); + } + /** + Determines whether the given node may be selected as a node + selection. + */ + static isSelectable(node) { + return !node.isText && node.type.spec.selectable !== false; + } +} +NodeSelection.prototype.visible = false; +Selection.jsonID("node", NodeSelection); +class NodeBookmark { + constructor(anchor) { + this.anchor = anchor; + } + map(mapping) { + let { deleted, pos } = mapping.mapResult(this.anchor); + return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos); + } + resolve(doc2) { + let $pos = doc2.resolve(this.anchor), node = $pos.nodeAfter; + if (node && NodeSelection.isSelectable(node)) + return new NodeSelection($pos); + return Selection.near($pos); + } +} +class AllSelection extends Selection { + /** + Create an all-selection over the given document. + */ + constructor(doc2) { + super(doc2.resolve(0), doc2.resolve(doc2.content.size)); + } + replace(tr2, content = Slice.empty) { + if (content == Slice.empty) { + tr2.delete(0, tr2.doc.content.size); + let sel = Selection.atStart(tr2.doc); + if (!sel.eq(tr2.selection)) + tr2.setSelection(sel); + } else { + super.replace(tr2, content); + } + } + toJSON() { + return { type: "all" }; + } + /** + @internal + */ + static fromJSON(doc2) { + return new AllSelection(doc2); + } + map(doc2) { + return new AllSelection(doc2); + } + eq(other) { + return other instanceof AllSelection; + } + getBookmark() { + return AllBookmark; + } +} +Selection.jsonID("all", AllSelection); +const AllBookmark = { + map() { + return this; + }, + resolve(doc2) { + return new AllSelection(doc2); + } +}; +function findSelectionIn(doc2, node, pos, index, dir, text = false) { + if (node.inlineContent) + return TextSelection.create(doc2, pos); + for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) { + let child = node.child(i); + if (!child.isAtom) { + let inner = findSelectionIn(doc2, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text); + if (inner) + return inner; + } else if (!text && NodeSelection.isSelectable(child)) { + return NodeSelection.create(doc2, pos - (dir < 0 ? child.nodeSize : 0)); + } + pos += child.nodeSize * dir; + } + return null; +} +function selectionToInsertionEnd$1(tr2, startLen, bias) { + let last = tr2.steps.length - 1; + if (last < startLen) + return; + let step = tr2.steps[last]; + if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) + return; + let map2 = tr2.mapping.maps[last], end; + map2.forEach((_from, _to, _newFrom, newTo) => { + if (end == null) + end = newTo; + }); + tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias)); +} +const UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4; +class Transaction extends Transform { + /** + @internal + */ + constructor(state) { + super(state.doc); + this.curSelectionFor = 0; + this.updated = 0; + this.meta = /* @__PURE__ */ Object.create(null); + this.time = Date.now(); + this.curSelection = state.selection; + this.storedMarks = state.storedMarks; + } + /** + The transaction's current selection. This defaults to the editor + selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the + transaction, but can be overwritten with + [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection). + */ + get selection() { + if (this.curSelectionFor < this.steps.length) { + this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); + this.curSelectionFor = this.steps.length; + } + return this.curSelection; + } + /** + Update the transaction's current selection. Will determine the + selection that the editor gets when the transaction is applied. + */ + setSelection(selection) { + if (selection.$from.doc != this.doc) + throw new RangeError("Selection passed to setSelection must point at the current document"); + this.curSelection = selection; + this.curSelectionFor = this.steps.length; + this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; + this.storedMarks = null; + return this; + } + /** + Whether the selection was explicitly updated by this transaction. + */ + get selectionSet() { + return (this.updated & UPDATED_SEL) > 0; + } + /** + Set the current stored marks. + */ + setStoredMarks(marks) { + this.storedMarks = marks; + this.updated |= UPDATED_MARKS; + return this; + } + /** + Make sure the current stored marks or, if that is null, the marks + at the selection, match the given set of marks. Does nothing if + this is already the case. + */ + ensureMarks(marks) { + if (!Mark$1.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) + this.setStoredMarks(marks); + return this; + } + /** + Add a mark to the set of stored marks. + */ + addStoredMark(mark) { + return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks())); + } + /** + Remove a mark or mark type from the set of stored marks. + */ + removeStoredMark(mark) { + return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks())); + } + /** + Whether the stored marks were explicitly set for this transaction. + */ + get storedMarksSet() { + return (this.updated & UPDATED_MARKS) > 0; + } + /** + @internal + */ + addStep(step, doc2) { + super.addStep(step, doc2); + this.updated = this.updated & ~UPDATED_MARKS; + this.storedMarks = null; + } + /** + Update the timestamp for the transaction. + */ + setTime(time) { + this.time = time; + return this; + } + /** + Replace the current selection with the given slice. + */ + replaceSelection(slice2) { + this.selection.replace(this, slice2); + return this; + } + /** + Replace the selection with the given node. When `inheritMarks` is + true and the content is inline, it inherits the marks from the + place where it is inserted. + */ + replaceSelectionWith(node, inheritMarks = true) { + let selection = this.selection; + if (inheritMarks) + node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark$1.none)); + selection.replaceWith(this, node); + return this; + } + /** + Delete the selection. + */ + deleteSelection() { + this.selection.replace(this); + return this; + } + /** + Replace the given range, or the selection if no range is given, + with a text node containing the given string. + */ + insertText(text, from2, to) { + let schema = this.doc.type.schema; + if (from2 == null) { + if (!text) + return this.deleteSelection(); + return this.replaceSelectionWith(schema.text(text), true); + } else { + if (to == null) + to = from2; + if (!text) + return this.deleteRange(from2, to); + let marks = this.storedMarks; + if (!marks) { + let $from = this.doc.resolve(from2); + marks = to == from2 ? $from.marks() : $from.marksAcross(this.doc.resolve(to)); + } + this.replaceRangeWith(from2, to, schema.text(text, marks)); + if (!this.selection.empty && this.selection.to == from2 + text.length) + this.setSelection(Selection.near(this.selection.$to)); + return this; + } + } + /** + Store a metadata property in this transaction, keyed either by + name or by plugin. + */ + setMeta(key, value) { + this.meta[typeof key == "string" ? key : key.key] = value; + return this; + } + /** + Retrieve a metadata property for a given name or plugin. + */ + getMeta(key) { + return this.meta[typeof key == "string" ? key : key.key]; + } + /** + Returns true if this transaction doesn't contain any metadata, + and can thus safely be extended. + */ + get isGeneric() { + for (let _ in this.meta) + return false; + return true; + } + /** + Indicate that the editor should scroll the selection into view + when updated to the state produced by this transaction. + */ + scrollIntoView() { + this.updated |= UPDATED_SCROLL; + return this; + } + /** + True when this transaction has had `scrollIntoView` called on it. + */ + get scrolledIntoView() { + return (this.updated & UPDATED_SCROLL) > 0; + } +} +function bind(f, self2) { + return !self2 || !f ? f : f.bind(self2); +} +class FieldDesc { + constructor(name, desc, self2) { + this.name = name; + this.init = bind(desc.init, self2); + this.apply = bind(desc.apply, self2); + } +} +const baseFields = [ + new FieldDesc("doc", { + init(config) { + return config.doc || config.schema.topNodeType.createAndFill(); + }, + apply(tr2) { + return tr2.doc; + } + }), + new FieldDesc("selection", { + init(config, instance) { + return config.selection || Selection.atStart(instance.doc); + }, + apply(tr2) { + return tr2.selection; + } + }), + new FieldDesc("storedMarks", { + init(config) { + return config.storedMarks || null; + }, + apply(tr2, _marks, _old, state) { + return state.selection.$cursor ? tr2.storedMarks : null; + } + }), + new FieldDesc("scrollToSelection", { + init() { + return 0; + }, + apply(tr2, prev) { + return tr2.scrolledIntoView ? prev + 1 : prev; + } + }) +]; +class Configuration { + constructor(schema, plugins) { + this.schema = schema; + this.plugins = []; + this.pluginsByKey = /* @__PURE__ */ Object.create(null); + this.fields = baseFields.slice(); + if (plugins) + plugins.forEach((plugin) => { + if (this.pluginsByKey[plugin.key]) + throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")"); + this.plugins.push(plugin); + this.pluginsByKey[plugin.key] = plugin; + if (plugin.spec.state) + this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); + }); + } +} +class EditorState { + /** + @internal + */ + constructor(config) { + this.config = config; + } + /** + The schema of the state's document. + */ + get schema() { + return this.config.schema; + } + /** + The plugins that are active in this state. + */ + get plugins() { + return this.config.plugins; + } + /** + Apply the given transaction to produce a new state. + */ + apply(tr2) { + return this.applyTransaction(tr2).state; + } + /** + @internal + */ + filterTransaction(tr2, ignore = -1) { + for (let i = 0; i < this.config.plugins.length; i++) + if (i != ignore) { + let plugin = this.config.plugins[i]; + if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr2, this)) + return false; + } + return true; + } + /** + Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that + returns the precise transactions that were applied (which might + be influenced by the [transaction + hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of + plugins) along with the new state. + */ + applyTransaction(rootTr) { + if (!this.filterTransaction(rootTr)) + return { state: this, transactions: [] }; + let trs = [rootTr], newState = this.applyInner(rootTr), seen = null; + for (; ; ) { + let haveNew = false; + for (let i = 0; i < this.config.plugins.length; i++) { + let plugin = this.config.plugins[i]; + if (plugin.spec.appendTransaction) { + let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this; + let tr2 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); + if (tr2 && newState.filterTransaction(tr2, i)) { + tr2.setMeta("appendedTransaction", rootTr); + if (!seen) { + seen = []; + for (let j = 0; j < this.config.plugins.length; j++) + seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 }); + } + trs.push(tr2); + newState = newState.applyInner(tr2); + haveNew = true; + } + if (seen) + seen[i] = { state: newState, n: trs.length }; + } + } + if (!haveNew) + return { state: newState, transactions: trs }; + } + } + /** + @internal + */ + applyInner(tr2) { + if (!tr2.before.eq(this.doc)) + throw new RangeError("Applying a mismatched transaction"); + let newInstance = new EditorState(this.config), fields = this.config.fields; + for (let i = 0; i < fields.length; i++) { + let field = fields[i]; + newInstance[field.name] = field.apply(tr2, this[field.name], this, newInstance); + } + return newInstance; + } + /** + Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state. + */ + get tr() { + return new Transaction(this); + } + /** + Create a new state. + */ + static create(config) { + let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins); + let instance = new EditorState($config); + for (let i = 0; i < $config.fields.length; i++) + instance[$config.fields[i].name] = $config.fields[i].init(config, instance); + return instance; + } + /** + Create a new state based on this one, but with an adjusted set + of active plugins. State fields that exist in both sets of + plugins are kept unchanged. Those that no longer exist are + dropped, and those that are new are initialized using their + [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new + configuration object.. + */ + reconfigure(config) { + let $config = new Configuration(this.schema, config.plugins); + let fields = $config.fields, instance = new EditorState($config); + for (let i = 0; i < fields.length; i++) { + let name = fields[i].name; + instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance); + } + return instance; + } + /** + Serialize this state to JSON. If you want to serialize the state + of plugins, pass an object mapping property names to use in the + resulting JSON object to plugin objects. The argument may also be + a string or number, in which case it is ignored, to support the + way `JSON.stringify` calls `toString` methods. + */ + toJSON(pluginFields) { + let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() }; + if (this.storedMarks) + result.storedMarks = this.storedMarks.map((m) => m.toJSON()); + if (pluginFields && typeof pluginFields == "object") + for (let prop in pluginFields) { + if (prop == "doc" || prop == "selection") + throw new RangeError("The JSON fields `doc` and `selection` are reserved"); + let plugin = pluginFields[prop], state = plugin.spec.state; + if (state && state.toJSON) + result[prop] = state.toJSON.call(plugin, this[plugin.key]); + } + return result; + } + /** + Deserialize a JSON representation of a state. `config` should + have at least a `schema` field, and should contain array of + plugins to initialize the state with. `pluginFields` can be used + to deserialize the state of plugins, by associating plugin + instances with the property names they use in the JSON object. + */ + static fromJSON(config, json, pluginFields) { + if (!json) + throw new RangeError("Invalid input for EditorState.fromJSON"); + if (!config.schema) + throw new RangeError("Required config field 'schema' missing"); + let $config = new Configuration(config.schema, config.plugins); + let instance = new EditorState($config); + $config.fields.forEach((field) => { + if (field.name == "doc") { + instance.doc = Node.fromJSON(config.schema, json.doc); + } else if (field.name == "selection") { + instance.selection = Selection.fromJSON(instance.doc, json.selection); + } else if (field.name == "storedMarks") { + if (json.storedMarks) + instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); + } else { + if (pluginFields) + for (let prop in pluginFields) { + let plugin = pluginFields[prop], state = plugin.spec.state; + if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) { + instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); + return; + } + } + instance[field.name] = field.init(config, instance); + } + }); + return instance; + } +} +function bindProps(obj, self2, target) { + for (let prop in obj) { + let val = obj[prop]; + if (val instanceof Function) + val = val.bind(self2); + else if (prop == "handleDOMEvents") + val = bindProps(val, self2, {}); + target[prop] = val; + } + return target; +} +class Plugin { + /** + Create a plugin. + */ + constructor(spec) { + this.spec = spec; + this.props = {}; + if (spec.props) + bindProps(spec.props, this, this.props); + this.key = spec.key ? spec.key.key : createKey("plugin"); + } + /** + Extract the plugin's state field from an editor state. + */ + getState(state) { + return state[this.key]; + } +} +const keys$1 = /* @__PURE__ */ Object.create(null); +function createKey(name) { + if (name in keys$1) + return name + "$" + ++keys$1[name]; + keys$1[name] = 0; + return name + "$"; +} +class PluginKey { + /** + Create a plugin key. + */ + constructor(name = "key") { + this.key = createKey(name); + } + /** + Get the active plugin with this key, if any, from an editor + state. + */ + get(state) { + return state.config.pluginsByKey[this.key]; + } + /** + Get the plugin's state from an editor state. + */ + getState(state) { + return state[this.key]; + } +} +const deleteSelection$1 = (state, dispatch) => { + if (state.selection.empty) + return false; + if (dispatch) + dispatch(state.tr.deleteSelection().scrollIntoView()); + return true; +}; +function atBlockStart(state, view) { + let { $cursor } = state.selection; + if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) + return null; + return $cursor; +} +const joinBackward$1 = (state, dispatch, view) => { + let $cursor = atBlockStart(state, view); + if (!$cursor) + return false; + let $cut = findCutBefore($cursor); + if (!$cut) { + let range = $cursor.blockRange(), target = range && liftTarget(range); + if (target == null) + return false; + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; + } + let before = $cut.nodeBefore; + if (deleteBarrier(state, $cut, dispatch, -1)) + return true; + if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) { + for (let depth = $cursor.depth; ; depth--) { + let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty); + if (delStep && delStep.slice.size < delStep.to - delStep.from) { + if (dispatch) { + let tr2 = state.tr.step(delStep); + tr2.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before.nodeSize)); + dispatch(tr2.scrollIntoView()); + } + return true; + } + if (depth == 1 || $cursor.node(depth - 1).childCount > 1) + break; + } + } + if (before.isAtom && $cut.depth == $cursor.depth - 1) { + if (dispatch) + dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); + return true; + } + return false; +}; +const joinTextblockBackward$1 = (state, dispatch, view) => { + let $cursor = atBlockStart(state, view); + if (!$cursor) + return false; + let $cut = findCutBefore($cursor); + return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; +}; +const joinTextblockForward$1 = (state, dispatch, view) => { + let $cursor = atBlockEnd(state, view); + if (!$cursor) + return false; + let $cut = findCutAfter($cursor); + return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; +}; +function joinTextblocksAround(state, $cut, dispatch) { + let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1; + for (; !beforeText.isTextblock; beforePos--) { + if (beforeText.type.spec.isolating) + return false; + let child = beforeText.lastChild; + if (!child) + return false; + beforeText = child; + } + let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1; + for (; !afterText.isTextblock; afterPos++) { + if (afterText.type.spec.isolating) + return false; + let child = afterText.firstChild; + if (!child) + return false; + afterText = child; + } + let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty); + if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos) + return false; + if (dispatch) { + let tr2 = state.tr.step(step); + tr2.setSelection(TextSelection.create(tr2.doc, beforePos)); + dispatch(tr2.scrollIntoView()); + } + return true; +} +function textblockAt(node, side, only = false) { + for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) { + if (scan.isTextblock) + return true; + if (only && scan.childCount != 1) + return false; + } + return false; +} +const selectNodeBackward$1 = (state, dispatch, view) => { + let { $head, empty: empty2 } = state.selection, $cut = $head; + if (!empty2) + return false; + if ($head.parent.isTextblock) { + if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) + return false; + $cut = findCutBefore($head); + } + let node = $cut && $cut.nodeBefore; + if (!node || !NodeSelection.isSelectable(node)) + return false; + if (dispatch) + dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); + return true; +}; +function findCutBefore($pos) { + if (!$pos.parent.type.spec.isolating) + for (let i = $pos.depth - 1; i >= 0; i--) { + if ($pos.index(i) > 0) + return $pos.doc.resolve($pos.before(i + 1)); + if ($pos.node(i).type.spec.isolating) + break; + } + return null; +} +function atBlockEnd(state, view) { + let { $cursor } = state.selection; + if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) + return null; + return $cursor; +} +const joinForward$1 = (state, dispatch, view) => { + let $cursor = atBlockEnd(state, view); + if (!$cursor) + return false; + let $cut = findCutAfter($cursor); + if (!$cut) + return false; + let after = $cut.nodeAfter; + if (deleteBarrier(state, $cut, dispatch, 1)) + return true; + if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) { + let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty); + if (delStep && delStep.slice.size < delStep.to - delStep.from) { + if (dispatch) { + let tr2 = state.tr.step(delStep); + tr2.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos))); + dispatch(tr2.scrollIntoView()); + } + return true; + } + } + if (after.isAtom && $cut.depth == $cursor.depth - 1) { + if (dispatch) + dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); + return true; + } + return false; +}; +const selectNodeForward$1 = (state, dispatch, view) => { + let { $head, empty: empty2 } = state.selection, $cut = $head; + if (!empty2) + return false; + if ($head.parent.isTextblock) { + if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) + return false; + $cut = findCutAfter($head); + } + let node = $cut && $cut.nodeAfter; + if (!node || !NodeSelection.isSelectable(node)) + return false; + if (dispatch) + dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); + return true; +}; +function findCutAfter($pos) { + if (!$pos.parent.type.spec.isolating) + for (let i = $pos.depth - 1; i >= 0; i--) { + let parent = $pos.node(i); + if ($pos.index(i) + 1 < parent.childCount) + return $pos.doc.resolve($pos.after(i + 1)); + if (parent.type.spec.isolating) + break; + } + return null; +} +const joinUp$1 = (state, dispatch) => { + let sel = state.selection, nodeSel = sel instanceof NodeSelection, point; + if (nodeSel) { + if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) + return false; + point = sel.from; + } else { + point = joinPoint(state.doc, sel.from, -1); + if (point == null) + return false; + } + if (dispatch) { + let tr2 = state.tr.join(point); + if (nodeSel) + tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); + dispatch(tr2.scrollIntoView()); + } + return true; +}; +const joinDown$1 = (state, dispatch) => { + let sel = state.selection, point; + if (sel instanceof NodeSelection) { + if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) + return false; + point = sel.to; + } else { + point = joinPoint(state.doc, sel.to, 1); + if (point == null) + return false; + } + if (dispatch) + dispatch(state.tr.join(point).scrollIntoView()); + return true; +}; +const lift$1 = (state, dispatch) => { + let { $from, $to } = state.selection; + let range = $from.blockRange($to), target = range && liftTarget(range); + if (target == null) + return false; + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; +}; +const newlineInCode$1 = (state, dispatch) => { + let { $head, $anchor } = state.selection; + if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) + return false; + if (dispatch) + dispatch(state.tr.insertText("\n").scrollIntoView()); + return true; +}; +function defaultBlockAt$1(match) { + for (let i = 0; i < match.edgeCount; i++) { + let { type } = match.edge(i); + if (type.isTextblock && !type.hasRequiredAttrs()) + return type; + } + return null; +} +const exitCode$1 = (state, dispatch) => { + let { $head, $anchor } = state.selection; + if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) + return false; + let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt$1(above.contentMatchAt(after)); + if (!type || !above.canReplaceWith(after, after, type)) + return false; + if (dispatch) { + let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill()); + tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1)); + dispatch(tr2.scrollIntoView()); + } + return true; +}; +const createParagraphNear$1 = (state, dispatch) => { + let sel = state.selection, { $from, $to } = sel; + if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) + return false; + let type = defaultBlockAt$1($to.parent.contentMatchAt($to.indexAfter())); + if (!type || !type.isTextblock) + return false; + if (dispatch) { + let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos; + let tr2 = state.tr.insert(side, type.createAndFill()); + tr2.setSelection(TextSelection.create(tr2.doc, side + 1)); + dispatch(tr2.scrollIntoView()); + } + return true; +}; +const liftEmptyBlock$1 = (state, dispatch) => { + let { $cursor } = state.selection; + if (!$cursor || $cursor.parent.content.size) + return false; + if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) { + let before = $cursor.before(); + if (canSplit(state.doc, before)) { + if (dispatch) + dispatch(state.tr.split(before).scrollIntoView()); + return true; + } + } + let range = $cursor.blockRange(), target = range && liftTarget(range); + if (target == null) + return false; + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; +}; +function splitBlockAs(splitNode) { + return (state, dispatch) => { + let { $from, $to } = state.selection; + if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { + if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) + return false; + if (dispatch) + dispatch(state.tr.split($from.pos).scrollIntoView()); + return true; + } + if (!$from.depth) + return false; + let types = []; + let splitDepth, deflt, atEnd = false, atStart = false; + for (let d = $from.depth; ; d--) { + let node = $from.node(d); + if (node.isBlock) { + atEnd = $from.end(d) == $from.pos + ($from.depth - d); + atStart = $from.start(d) == $from.pos - ($from.depth - d); + deflt = defaultBlockAt$1($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1))); + types.unshift(atEnd && deflt ? { type: deflt } : null); + splitDepth = d; + break; + } else { + if (d == 1) + return false; + types.unshift(null); + } + } + let tr2 = state.tr; + if (state.selection instanceof TextSelection || state.selection instanceof AllSelection) + tr2.deleteSelection(); + let splitPos = tr2.mapping.map($from.pos); + let can = canSplit(tr2.doc, splitPos, types.length, types); + if (!can) { + types[0] = deflt ? { type: deflt } : null; + can = canSplit(tr2.doc, splitPos, types.length, types); + } + if (!can) + return false; + tr2.split(splitPos, types.length, types); + if (!atEnd && atStart && $from.node(splitDepth).type != deflt) { + let first2 = tr2.mapping.map($from.before(splitDepth)), $first = tr2.doc.resolve(first2); + if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) + tr2.setNodeMarkup(tr2.mapping.map($from.before(splitDepth)), deflt); + } + if (dispatch) + dispatch(tr2.scrollIntoView()); + return true; + }; +} +const splitBlock$1 = splitBlockAs(); +const selectParentNode$1 = (state, dispatch) => { + let { $from, to } = state.selection, pos; + let same = $from.sharedDepth(to); + if (same == 0) + return false; + pos = $from.before(same); + if (dispatch) + dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); + return true; +}; +function joinMaybeClear(state, $pos, dispatch) { + let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index(); + if (!before || !after || !before.type.compatibleContent(after.type)) + return false; + if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { + if (dispatch) + dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); + return true; + } + if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) + return false; + if (dispatch) + dispatch(state.tr.join($pos.pos).scrollIntoView()); + return true; +} +function deleteBarrier(state, $cut, dispatch, dir) { + let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match; + let isolated = before.type.spec.isolating || after.type.spec.isolating; + if (!isolated && joinMaybeClear(state, $cut, dispatch)) + return true; + let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1); + if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) { + if (dispatch) { + let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty; + for (let i = conn.length - 1; i >= 0; i--) + wrap2 = Fragment.from(conn[i].create(null, wrap2)); + wrap2 = Fragment.from(before.copy(wrap2)); + let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true)); + let $joinAt = tr2.doc.resolve(end + 2 * conn.length); + if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr2.doc, $joinAt.pos)) + tr2.join($joinAt.pos); + dispatch(tr2.scrollIntoView()); + } + return true; + } + let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1); + let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range); + if (target != null && target >= $cut.depth) { + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; + } + if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) { + let at = before, wrap2 = []; + for (; ; ) { + wrap2.push(at); + if (at.isTextblock) + break; + at = at.lastChild; + } + let afterText = after, afterDepth = 1; + for (; !afterText.isTextblock; afterText = afterText.firstChild) + afterDepth++; + if (at.canReplace(at.childCount, at.childCount, afterText.content)) { + if (dispatch) { + let end = Fragment.empty; + for (let i = wrap2.length - 1; i >= 0; i--) + end = Fragment.from(wrap2[i].copy(end)); + let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true)); + dispatch(tr2.scrollIntoView()); + } + return true; + } + } + return false; +} +function selectTextblockSide(side) { + return function(state, dispatch) { + let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to; + let depth = $pos.depth; + while ($pos.node(depth).isInline) { + if (!depth) + return false; + depth--; + } + if (!$pos.node(depth).isTextblock) + return false; + if (dispatch) + dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth)))); + return true; + }; +} +const selectTextblockStart$1 = selectTextblockSide(-1); +const selectTextblockEnd$1 = selectTextblockSide(1); +function wrapIn$1(nodeType, attrs = null) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs); + if (!wrapping) + return false; + if (dispatch) + dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); + return true; + }; +} +function setBlockType(nodeType, attrs = null) { + return function(state, dispatch) { + let applicable = false; + for (let i = 0; i < state.selection.ranges.length && !applicable; i++) { + let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i]; + state.doc.nodesBetween(from2, to, (node, pos) => { + if (applicable) + return false; + if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) + return; + if (node.type == nodeType) { + applicable = true; + } else { + let $pos = state.doc.resolve(pos), index = $pos.index(); + applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType); + } + }); + } + if (!applicable) + return false; + if (dispatch) { + let tr2 = state.tr; + for (let i = 0; i < state.selection.ranges.length; i++) { + let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i]; + tr2.setBlockType(from2, to, nodeType, attrs); + } + dispatch(tr2.scrollIntoView()); + } + return true; + }; +} +function chainCommands(...commands) { + return function(state, dispatch, view) { + for (let i = 0; i < commands.length; i++) + if (commands[i](state, dispatch, view)) + return true; + return false; + }; +} +chainCommands(deleteSelection$1, joinBackward$1, selectNodeBackward$1); +chainCommands(deleteSelection$1, joinForward$1, selectNodeForward$1); +({ + "Enter": chainCommands(newlineInCode$1, createParagraphNear$1, liftEmptyBlock$1, splitBlock$1) +}); +typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false; +function wrapInList$1(listType, attrs = null) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to); + if (!range) + return false; + let tr2 = dispatch ? state.tr : null; + if (!wrapRangeInList(tr2, range, listType, attrs)) + return false; + if (dispatch) + dispatch(tr2.scrollIntoView()); + return true; + }; +} +function wrapRangeInList(tr2, range, listType, attrs = null) { + let doJoin = false, outerRange = range, doc2 = range.$from.doc; + if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) { + if (range.$from.index(range.depth - 1) == 0) + return false; + let $insert = doc2.resolve(range.start - 2); + outerRange = new NodeRange($insert, $insert, range.depth); + if (range.endIndex < range.parent.childCount) + range = new NodeRange(range.$from, doc2.resolve(range.$to.end(range.depth)), range.depth); + doJoin = true; + } + let wrap2 = findWrapping(outerRange, listType, attrs, range); + if (!wrap2) + return false; + if (tr2) + doWrapInList(tr2, range, wrap2, doJoin, listType); + return true; +} +function doWrapInList(tr2, range, wrappers, joinBefore, listType) { + let content = Fragment.empty; + for (let i = wrappers.length - 1; i >= 0; i--) + content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); + tr2.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true)); + let found2 = 0; + for (let i = 0; i < wrappers.length; i++) + if (wrappers[i].type == listType) + found2 = i + 1; + let splitDepth = wrappers.length - found2; + let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; + for (let i = range.startIndex, e = range.endIndex, first2 = true; i < e; i++, first2 = false) { + if (!first2 && canSplit(tr2.doc, splitPos, splitDepth)) { + tr2.split(splitPos, splitDepth); + splitPos += 2 * splitDepth; + } + splitPos += parent.child(i).nodeSize; + } + return tr2; +} +function liftListItem$1(itemType) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); + if (!range) + return false; + if (!dispatch) + return true; + if ($from.node(range.depth - 1).type == itemType) + return liftToOuterList(state, dispatch, itemType, range); + else + return liftOutOfList(state, dispatch, range); + }; +} +function liftToOuterList(state, dispatch, itemType, range) { + let tr2 = state.tr, end = range.end, endOfList = range.$to.end(range.depth); + if (end < endOfList) { + tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true)); + range = new NodeRange(tr2.doc.resolve(range.$from.pos), tr2.doc.resolve(endOfList), range.depth); + } + const target = liftTarget(range); + if (target == null) + return false; + tr2.lift(range, target); + let $after = tr2.doc.resolve(tr2.mapping.map(end, -1) - 1); + if (canJoin(tr2.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) + tr2.join($after.pos); + dispatch(tr2.scrollIntoView()); + return true; +} +function liftOutOfList(state, dispatch, range) { + let tr2 = state.tr, list = range.parent; + for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) { + pos -= list.child(i).nodeSize; + tr2.delete(pos - 1, pos + 1); + } + let $start = tr2.doc.resolve(range.start), item = $start.nodeAfter; + if (tr2.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) + return false; + let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount; + let parent = $start.node(-1), indexBefore = $start.index(-1); + if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) + return false; + let start = $start.pos, end = start + item.nodeSize; + tr2.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1)); + dispatch(tr2.scrollIntoView()); + return true; +} +function sinkListItem$1(itemType) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); + if (!range) + return false; + let startIndex = range.startIndex; + if (startIndex == 0) + return false; + let parent = range.parent, nodeBefore = parent.child(startIndex - 1); + if (nodeBefore.type != itemType) + return false; + if (dispatch) { + let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type; + let inner = Fragment.from(nestedBefore ? itemType.create() : null); + let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0); + let before = range.start, after = range.end; + dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView()); + } + return true; + }; +} +const domIndex = function(node) { + for (var index = 0; ; index++) { + node = node.previousSibling; + if (!node) + return index; + } +}; +const parentNode = function(node) { + let parent = node.assignedSlot || node.parentNode; + return parent && parent.nodeType == 11 ? parent.host : parent; +}; +let reusedRange = null; +const textRange = function(node, from2, to) { + let range = reusedRange || (reusedRange = document.createRange()); + range.setEnd(node, to == null ? node.nodeValue.length : to); + range.setStart(node, from2 || 0); + return range; +}; +const clearReusedRange = function() { + reusedRange = null; +}; +const isEquivalentPosition = function(node, off, targetNode, targetOff) { + return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1)); +}; +const atomElements = /^(img|br|input|textarea|hr)$/i; +function scanFor(node, off, targetNode, targetOff, dir) { + var _a; + for (; ; ) { + if (node == targetNode && off == targetOff) + return true; + if (off == (dir < 0 ? 0 : nodeSize(node))) { + let parent = node.parentNode; + if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") + return false; + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } else if (node.nodeType == 1) { + let child = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (child.nodeType == 1 && child.contentEditable == "false") { + if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection) + off += dir; + else + return false; + } else { + node = child; + off = dir < 0 ? nodeSize(node) : 0; + } + } else { + return false; + } + } +} +function nodeSize(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; +} +function textNodeBefore$1(node, offset) { + for (; ; ) { + if (node.nodeType == 3 && offset) + return node; + if (node.nodeType == 1 && offset > 0) { + if (node.contentEditable == "false") + return null; + node = node.childNodes[offset - 1]; + offset = nodeSize(node); + } else if (node.parentNode && !hasBlockDesc(node)) { + offset = domIndex(node); + node = node.parentNode; + } else { + return null; + } + } +} +function textNodeAfter$1(node, offset) { + for (; ; ) { + if (node.nodeType == 3 && offset < node.nodeValue.length) + return node; + if (node.nodeType == 1 && offset < node.childNodes.length) { + if (node.contentEditable == "false") + return null; + node = node.childNodes[offset]; + offset = 0; + } else if (node.parentNode && !hasBlockDesc(node)) { + offset = domIndex(node) + 1; + node = node.parentNode; + } else { + return null; + } + } +} +function isOnEdge(node, offset, parent) { + for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) { + if (node == parent) + return true; + let index = domIndex(node); + node = node.parentNode; + if (!node) + return false; + atStart = atStart && index == 0; + atEnd = atEnd && index == nodeSize(node); + } +} +function hasBlockDesc(dom) { + let desc; + for (let cur = dom; cur; cur = cur.parentNode) + if (desc = cur.pmViewDesc) + break; + return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom); +} +const selectionCollapsed = function(domSel) { + return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset); +}; +function keyEvent(keyCode, key) { + let event = document.createEvent("Event"); + event.initEvent("keydown", true, true); + event.keyCode = keyCode; + event.key = event.code = key; + return event; +} +function deepActiveElement(doc2) { + let elt = doc2.activeElement; + while (elt && elt.shadowRoot) + elt = elt.shadowRoot.activeElement; + return elt; +} +function caretFromPoint(doc2, x, y) { + if (doc2.caretPositionFromPoint) { + try { + let pos = doc2.caretPositionFromPoint(x, y); + if (pos) + return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) }; + } catch (_) { + } + } + if (doc2.caretRangeFromPoint) { + let range = doc2.caretRangeFromPoint(x, y); + if (range) + return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) }; + } +} +const nav = typeof navigator != "undefined" ? navigator : null; +const doc = typeof document != "undefined" ? document : null; +const agent = nav && nav.userAgent || ""; +const ie_edge = /Edge\/(\d+)/.exec(agent); +const ie_upto10 = /MSIE \d/.exec(agent); +const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent); +const ie$1 = !!(ie_upto10 || ie_11up || ie_edge); +const ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0; +const gecko = !ie$1 && /gecko\/(\d+)/i.test(agent); +gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1]; +const _chrome = !ie$1 && /Chrome\/(\d+)/.exec(agent); +const chrome = !!_chrome; +const chrome_version = _chrome ? +_chrome[1] : 0; +const safari = !ie$1 && !!nav && /Apple Computer/.test(nav.vendor); +const ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2); +const mac$2 = ios || (nav ? /Mac/.test(nav.platform) : false); +const windows$1 = nav ? /Win/.test(nav.platform) : false; +const android = /Android \d/.test(agent); +const webkit = !!doc && "webkitFontSmoothing" in doc.documentElement.style; +const webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0; +function windowRect(doc2) { + let vp = doc2.defaultView && doc2.defaultView.visualViewport; + if (vp) + return { + left: 0, + right: vp.width, + top: 0, + bottom: vp.height + }; + return { + left: 0, + right: doc2.documentElement.clientWidth, + top: 0, + bottom: doc2.documentElement.clientHeight + }; +} +function getSide(value, side) { + return typeof value == "number" ? value : value[side]; +} +function clientRect(node) { + let rect = node.getBoundingClientRect(); + let scaleX = rect.width / node.offsetWidth || 1; + let scaleY = rect.height / node.offsetHeight || 1; + return { + left: rect.left, + right: rect.left + node.clientWidth * scaleX, + top: rect.top, + bottom: rect.top + node.clientHeight * scaleY + }; +} +function scrollRectIntoView(view, rect, startDOM) { + let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; + let doc2 = view.dom.ownerDocument; + for (let parent = startDOM || view.dom; ; ) { + if (!parent) + break; + if (parent.nodeType != 1) { + parent = parentNode(parent); + continue; + } + let elt = parent; + let atTop = elt == doc2.body; + let bounding = atTop ? windowRect(doc2) : clientRect(elt); + let moveX = 0, moveY = 0; + if (rect.top < bounding.top + getSide(scrollThreshold, "top")) + moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); + else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) + moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); + if (rect.left < bounding.left + getSide(scrollThreshold, "left")) + moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); + else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) + moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); + if (moveX || moveY) { + if (atTop) { + doc2.defaultView.scrollBy(moveX, moveY); + } else { + let startX = elt.scrollLeft, startY = elt.scrollTop; + if (moveY) + elt.scrollTop += moveY; + if (moveX) + elt.scrollLeft += moveX; + let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY; + rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY }; + } + } + let pos = atTop ? "fixed" : getComputedStyle(parent).position; + if (/^(fixed|sticky)$/.test(pos)) + break; + parent = pos == "absolute" ? parent.offsetParent : parentNode(parent); + } +} +function storeScrollPos(view) { + let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); + let refDOM, refTop; + for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) { + let dom = view.root.elementFromPoint(x, y); + if (!dom || dom == view.dom || !view.dom.contains(dom)) + continue; + let localRect = dom.getBoundingClientRect(); + if (localRect.top >= startY - 20) { + refDOM = dom; + refTop = localRect.top; + break; + } + } + return { refDOM, refTop, stack: scrollStack(view.dom) }; +} +function scrollStack(dom) { + let stack = [], doc2 = dom.ownerDocument; + for (let cur = dom; cur; cur = parentNode(cur)) { + stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft }); + if (dom == doc2) + break; + } + return stack; +} +function resetScrollPos({ refDOM, refTop, stack }) { + let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; + restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); +} +function restoreScrollStack(stack, dTop) { + for (let i = 0; i < stack.length; i++) { + let { dom, top, left } = stack[i]; + if (dom.scrollTop != top + dTop) + dom.scrollTop = top + dTop; + if (dom.scrollLeft != left) + dom.scrollLeft = left; + } +} +let preventScrollSupported = null; +function focusPreventScroll(dom) { + if (dom.setActive) + return dom.setActive(); + if (preventScrollSupported) + return dom.focus(preventScrollSupported); + let stored = scrollStack(dom); + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = { preventScroll: true }; + return true; + } + } : void 0); + if (!preventScrollSupported) { + preventScrollSupported = false; + restoreScrollStack(stored, 0); + } +} +function findOffsetInNode(node, coords) { + let closest, dxClosest = 2e8, coordsClosest, offset = 0; + let rowBot = coords.top, rowTop = coords.top; + let firstBelow, coordsBelow; + for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { + let rects; + if (child.nodeType == 1) + rects = child.getClientRects(); + else if (child.nodeType == 3) + rects = textRange(child).getClientRects(); + else + continue; + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (rect.top <= rowBot && rect.bottom >= rowTop) { + rowBot = Math.max(rect.bottom, rowBot); + rowTop = Math.min(rect.top, rowTop); + let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0; + if (dx < dxClosest) { + closest = child; + dxClosest = dx; + coordsClosest = dx && closest.nodeType == 3 ? { + left: rect.right < coords.left ? rect.right : rect.left, + top: coords.top + } : coords; + if (child.nodeType == 1 && dx) + offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); + continue; + } + } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) { + firstBelow = child; + coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top }; + } + if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom)) + offset = childIndex + 1; + } + } + if (!closest && firstBelow) { + closest = firstBelow; + coordsClosest = coordsBelow; + dxClosest = 0; + } + if (closest && closest.nodeType == 3) + return findOffsetInText(closest, coordsClosest); + if (!closest || dxClosest && closest.nodeType == 1) + return { node, offset }; + return findOffsetInNode(closest, coordsClosest); +} +function findOffsetInText(node, coords) { + let len = node.nodeValue.length; + let range = document.createRange(), result; + for (let i = 0; i < len; i++) { + range.setEnd(node, i + 1); + range.setStart(node, i); + let rect = singleRect(range, 1); + if (rect.top == rect.bottom) + continue; + if (inRect(coords, rect)) { + result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) }; + break; + } + } + range.detach(); + return result || { node, offset: 0 }; +} +function inRect(coords, rect) { + return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1; +} +function targetKludge(dom, coords) { + let parent = dom.parentNode; + if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) + return parent; + return dom; +} +function posFromElement(view, elt, coords) { + let { node, offset } = findOffsetInNode(elt, coords), bias = -1; + if (node.nodeType == 1 && !node.firstChild) { + let rect = node.getBoundingClientRect(); + bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; + } + return view.docView.posFromDOM(node, offset, bias); +} +function posFromCaret(view, node, offset, coords) { + let outsideBlock = -1; + for (let cur = node, sawBlock = false; ; ) { + if (cur == view.dom) + break; + let desc = view.docView.nearestDesc(cur, true), rect; + if (!desc) + return null; + if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles + ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) { + if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) { + if (!sawBlock && rect.left > coords.left || rect.top > coords.top) + outsideBlock = desc.posBefore; + else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top) + outsideBlock = desc.posAfter; + sawBlock = true; + } + if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) { + let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2; + return before ? desc.posBefore : desc.posAfter; + } + } + cur = desc.dom.parentNode; + } + return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1); +} +function elementFromPoint(element, coords, box) { + let len = element.childNodes.length; + if (len && box.top < box.bottom) { + for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI; ; ) { + let child = element.childNodes[i]; + if (child.nodeType == 1) { + let rects = child.getClientRects(); + for (let j = 0; j < rects.length; j++) { + let rect = rects[j]; + if (inRect(coords, rect)) + return elementFromPoint(child, coords, rect); + } + } + if ((i = (i + 1) % len) == startI) + break; + } + } + return element; +} +function posAtCoords(view, coords) { + let doc2 = view.dom.ownerDocument, node, offset = 0; + let caret = caretFromPoint(doc2, coords.left, coords.top); + if (caret) + ({ node, offset } = caret); + let elt = (view.root.elementFromPoint ? view.root : doc2).elementFromPoint(coords.left, coords.top); + let pos; + if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { + let box = view.dom.getBoundingClientRect(); + if (!inRect(coords, box)) + return null; + elt = elementFromPoint(view.dom, coords, box); + if (!elt) + return null; + } + if (safari) { + for (let p = elt; node && p; p = parentNode(p)) + if (p.draggable) + node = void 0; + } + elt = targetKludge(elt, coords); + if (node) { + if (gecko && node.nodeType == 1) { + offset = Math.min(offset, node.childNodes.length); + if (offset < node.childNodes.length) { + let next = node.childNodes[offset], box; + if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top) + offset++; + } + } + let prev; + if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top) + offset--; + if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom) + pos = view.state.doc.content.size; + else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") + pos = posFromCaret(view, node, offset, coords); + } + if (pos == null) + pos = posFromElement(view, elt, coords); + let desc = view.docView.nearestDesc(elt, true); + return { pos, inside: desc ? desc.posAtStart - desc.border : -1 }; +} +function nonZero(rect) { + return rect.top < rect.bottom || rect.left < rect.right; +} +function singleRect(target, bias) { + let rects = target.getClientRects(); + if (rects.length) { + let first2 = rects[bias < 0 ? 0 : rects.length - 1]; + if (nonZero(first2)) + return first2; + } + return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect(); +} +const BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; +function coordsAtPos(view, pos, side) { + let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1); + let supportEmptyRange = webkit || gecko; + if (node.nodeType == 3) { + if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) { + let rect = singleRect(textRange(node, offset, offset), side); + if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) { + let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1); + if (rectBefore.top == rect.top) { + let rectAfter = singleRect(textRange(node, offset, offset + 1), -1); + if (rectAfter.top != rect.top) + return flattenV(rectAfter, rectAfter.left < rectBefore.left); + } + } + return rect; + } else { + let from2 = offset, to = offset, takeSide = side < 0 ? 1 : -1; + if (side < 0 && !offset) { + to++; + takeSide = -1; + } else if (side >= 0 && offset == node.nodeValue.length) { + from2--; + takeSide = 1; + } else if (side < 0) { + from2--; + } else { + to++; + } + return flattenV(singleRect(textRange(node, from2, to), takeSide), takeSide < 0); + } + } + let $dom = view.state.doc.resolve(pos - (atom || 0)); + if (!$dom.parent.inlineContent) { + if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { + let before = node.childNodes[offset - 1]; + if (before.nodeType == 1) + return flattenH(before.getBoundingClientRect(), false); + } + if (atom == null && offset < nodeSize(node)) { + let after = node.childNodes[offset]; + if (after.nodeType == 1) + return flattenH(after.getBoundingClientRect(), true); + } + return flattenH(node.getBoundingClientRect(), side >= 0); + } + if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { + let before = node.childNodes[offset - 1]; + let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null; + if (target) + return flattenV(singleRect(target, 1), false); + } + if (atom == null && offset < nodeSize(node)) { + let after = node.childNodes[offset]; + while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords) + after = after.nextSibling; + let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null; + if (target) + return flattenV(singleRect(target, -1), true); + } + return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0); +} +function flattenV(rect, left) { + if (rect.width == 0) + return rect; + let x = left ? rect.left : rect.right; + return { top: rect.top, bottom: rect.bottom, left: x, right: x }; +} +function flattenH(rect, top) { + if (rect.height == 0) + return rect; + let y = top ? rect.top : rect.bottom; + return { top: y, bottom: y, left: rect.left, right: rect.right }; +} +function withFlushedState(view, state, f) { + let viewState = view.state, active = view.root.activeElement; + if (viewState != state) + view.updateState(state); + if (active != view.dom) + view.focus(); + try { + return f(); + } finally { + if (viewState != state) + view.updateState(viewState); + if (active != view.dom && active) + active.focus(); + } +} +function endOfTextblockVertical(view, state, dir) { + let sel = state.selection; + let $pos = dir == "up" ? sel.$from : sel.$to; + return withFlushedState(view, state, () => { + let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1); + for (; ; ) { + let nearest = view.docView.nearestDesc(dom, true); + if (!nearest) + break; + if (nearest.node.isBlock) { + dom = nearest.contentDOM || nearest.dom; + break; + } + dom = nearest.dom.parentNode; + } + let coords = coordsAtPos(view, $pos.pos, 1); + for (let child = dom.firstChild; child; child = child.nextSibling) { + let boxes; + if (child.nodeType == 1) + boxes = child.getClientRects(); + else if (child.nodeType == 3) + boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); + else + continue; + for (let i = 0; i < boxes.length; i++) { + let box = boxes[i]; + if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2)) + return false; + } + } + return true; + }); +} +const maybeRTL = /[\u0590-\u08ac]/; +function endOfTextblockHorizontal(view, state, dir) { + let { $head } = state.selection; + if (!$head.parent.isTextblock) + return false; + let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size; + let sel = view.domSelection(); + if (!sel) + return $head.pos == $head.start() || $head.pos == $head.end(); + if (!maybeRTL.test($head.parent.textContent) || !sel.modify) + return dir == "left" || dir == "backward" ? atStart : atEnd; + return withFlushedState(view, state, () => { + let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange(); + let oldBidiLevel = sel.caretBidiLevel; + sel.modify("move", dir, "character"); + let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; + let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange(); + let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff; + try { + sel.collapse(anchorNode, anchorOffset); + if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend) + sel.extend(oldNode, oldOff); + } catch (_) { + } + if (oldBidiLevel != null) + sel.caretBidiLevel = oldBidiLevel; + return result; + }); +} +let cachedState = null; +let cachedDir = null; +let cachedResult = false; +function endOfTextblock(view, state, dir) { + if (cachedState == state && cachedDir == dir) + return cachedResult; + cachedState = state; + cachedDir = dir; + return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir); +} +const NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3; +class ViewDesc { + constructor(parent, children, dom, contentDOM) { + this.parent = parent; + this.children = children; + this.dom = dom; + this.contentDOM = contentDOM; + this.dirty = NOT_DIRTY; + dom.pmViewDesc = this; + } + // Used to check whether a given description corresponds to a + // widget/mark/node. + matchesWidget(widget) { + return false; + } + matchesMark(mark) { + return false; + } + matchesNode(node, outerDeco, innerDeco) { + return false; + } + matchesHack(nodeName) { + return false; + } + // When parsing in-editor content (in domchange.js), we allow + // descriptions to determine the parse rules that should be used to + // parse them. + parseRule() { + return null; + } + // Used by the editor's event handler to ignore events that come + // from certain descs. + stopEvent(event) { + return false; + } + // The size of the content represented by this desc. + get size() { + let size = 0; + for (let i = 0; i < this.children.length; i++) + size += this.children[i].size; + return size; + } + // For block nodes, this represents the space taken up by their + // start/end tokens. + get border() { + return 0; + } + destroy() { + this.parent = void 0; + if (this.dom.pmViewDesc == this) + this.dom.pmViewDesc = void 0; + for (let i = 0; i < this.children.length; i++) + this.children[i].destroy(); + } + posBeforeChild(child) { + for (let i = 0, pos = this.posAtStart; ; i++) { + let cur = this.children[i]; + if (cur == child) + return pos; + pos += cur.size; + } + } + get posBefore() { + return this.parent.posBeforeChild(this); + } + get posAtStart() { + return this.parent ? this.parent.posBeforeChild(this) + this.border : 0; + } + get posAfter() { + return this.posBefore + this.size; + } + get posAtEnd() { + return this.posAtStart + this.size - 2 * this.border; + } + localPosFromDOM(dom, offset, bias) { + if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) { + if (bias < 0) { + let domBefore, desc; + if (dom == this.contentDOM) { + domBefore = dom.childNodes[offset - 1]; + } else { + while (dom.parentNode != this.contentDOM) + dom = dom.parentNode; + domBefore = dom.previousSibling; + } + while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) + domBefore = domBefore.previousSibling; + return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart; + } else { + let domAfter, desc; + if (dom == this.contentDOM) { + domAfter = dom.childNodes[offset]; + } else { + while (dom.parentNode != this.contentDOM) + dom = dom.parentNode; + domAfter = dom.nextSibling; + } + while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) + domAfter = domAfter.nextSibling; + return domAfter ? this.posBeforeChild(desc) : this.posAtEnd; + } + } + let atEnd; + if (dom == this.dom && this.contentDOM) { + atEnd = offset > domIndex(this.contentDOM); + } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) { + atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; + } else if (this.dom.firstChild) { + if (offset == 0) + for (let search = dom; ; search = search.parentNode) { + if (search == this.dom) { + atEnd = false; + break; + } + if (search.previousSibling) + break; + } + if (atEnd == null && offset == dom.childNodes.length) + for (let search = dom; ; search = search.parentNode) { + if (search == this.dom) { + atEnd = true; + break; + } + if (search.nextSibling) + break; + } + } + return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart; + } + nearestDesc(dom, onlyNodes = false) { + for (let first2 = true, cur = dom; cur; cur = cur.parentNode) { + let desc = this.getDesc(cur), nodeDOM; + if (desc && (!onlyNodes || desc.node)) { + if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom)) + first2 = false; + else + return desc; + } + } + } + getDesc(dom) { + let desc = dom.pmViewDesc; + for (let cur = desc; cur; cur = cur.parent) + if (cur == this) + return desc; + } + posFromDOM(dom, offset, bias) { + for (let scan = dom; scan; scan = scan.parentNode) { + let desc = this.getDesc(scan); + if (desc) + return desc.localPosFromDOM(dom, offset, bias); + } + return -1; + } + // Find the desc for the node after the given pos, if any. (When a + // parent node overrode rendering, there might not be one.) + descAt(pos) { + for (let i = 0, offset = 0; i < this.children.length; i++) { + let child = this.children[i], end = offset + child.size; + if (offset == pos && end != offset) { + while (!child.border && child.children.length) { + for (let i2 = 0; i2 < child.children.length; i2++) { + let inner = child.children[i2]; + if (inner.size) { + child = inner; + break; + } + } + } + return child; + } + if (pos < end) + return child.descAt(pos - offset - child.border); + offset = end; + } + } + domFromPos(pos, side) { + if (!this.contentDOM) + return { node: this.dom, offset: 0, atom: pos + 1 }; + let i = 0, offset = 0; + for (let curPos = 0; i < this.children.length; i++) { + let child = this.children[i], end = curPos + child.size; + if (end > pos || child instanceof TrailingHackViewDesc) { + offset = pos - curPos; + break; + } + curPos = end; + } + if (offset) + return this.children[i].domFromPos(offset - this.children[i].border, side); + for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { + } + if (side <= 0) { + let prev, enter2 = true; + for (; ; i--, enter2 = false) { + prev = i ? this.children[i - 1] : null; + if (!prev || prev.dom.parentNode == this.contentDOM) + break; + } + if (prev && side && enter2 && !prev.border && !prev.domAtom) + return prev.domFromPos(prev.size, side); + return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 }; + } else { + let next, enter2 = true; + for (; ; i++, enter2 = false) { + next = i < this.children.length ? this.children[i] : null; + if (!next || next.dom.parentNode == this.contentDOM) + break; + } + if (next && enter2 && !next.border && !next.domAtom) + return next.domFromPos(0, side); + return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length }; + } + } + // Used to find a DOM range in a single parent for a given changed + // range. + parseRange(from2, to, base2 = 0) { + if (this.children.length == 0) + return { node: this.contentDOM, from: from2, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length }; + let fromOffset = -1, toOffset = -1; + for (let offset = base2, i = 0; ; i++) { + let child = this.children[i], end = offset + child.size; + if (fromOffset == -1 && from2 <= end) { + let childBase = offset + child.border; + if (from2 >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM)) + return child.parseRange(from2, to, childBase); + from2 = offset; + for (let j = i; j > 0; j--) { + let prev = this.children[j - 1]; + if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { + fromOffset = domIndex(prev.dom) + 1; + break; + } + from2 -= prev.size; + } + if (fromOffset == -1) + fromOffset = 0; + } + if (fromOffset > -1 && (end > to || i == this.children.length - 1)) { + to = end; + for (let j = i + 1; j < this.children.length; j++) { + let next = this.children[j]; + if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) { + toOffset = domIndex(next.dom); + break; + } + to += next.size; + } + if (toOffset == -1) + toOffset = this.contentDOM.childNodes.length; + break; + } + offset = end; + } + return { node: this.contentDOM, from: from2, to, fromOffset, toOffset }; + } + emptyChildAt(side) { + if (this.border || !this.contentDOM || !this.children.length) + return false; + let child = this.children[side < 0 ? 0 : this.children.length - 1]; + return child.size == 0 || child.emptyChildAt(side); + } + domAfterPos(pos) { + let { node, offset } = this.domFromPos(pos, 0); + if (node.nodeType != 1 || offset == node.childNodes.length) + throw new RangeError("No node after pos " + pos); + return node.childNodes[offset]; + } + // View descs are responsible for setting any selection that falls + // entirely inside of them, so that custom implementations can do + // custom things with the selection. Note that this falls apart when + // a selection starts in such a node and ends in another, in which + // case we just use whatever domFromPos produces as a best effort. + setSelection(anchor, head, view, force = false) { + let from2 = Math.min(anchor, head), to = Math.max(anchor, head); + for (let i = 0, offset = 0; i < this.children.length; i++) { + let child = this.children[i], end = offset + child.size; + if (from2 > offset && to < end) + return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force); + offset = end; + } + let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1); + let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1); + let domSel = view.root.getSelection(); + let selRange = view.domSelectionRange(); + let brKludge = false; + if ((gecko || safari) && anchor == head) { + let { node, offset } = anchorDOM; + if (node.nodeType == 3) { + brKludge = !!(offset && node.nodeValue[offset - 1] == "\n"); + if (brKludge && offset == node.nodeValue.length) { + for (let scan = node, after; scan; scan = scan.parentNode) { + if (after = scan.nextSibling) { + if (after.nodeName == "BR") + anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 }; + break; + } + let desc = scan.pmViewDesc; + if (desc && desc.node && desc.node.isBlock) + break; + } + } + } else { + let prev = node.childNodes[offset - 1]; + brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); + } + } + if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) { + let after = selRange.focusNode.childNodes[selRange.focusOffset]; + if (after && after.contentEditable == "false") + force = true; + } + if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset)) + return; + let domSelExtended = false; + if ((domSel.extend || anchor == head) && !(brKludge && gecko)) { + domSel.collapse(anchorDOM.node, anchorDOM.offset); + try { + if (anchor != head) + domSel.extend(headDOM.node, headDOM.offset); + domSelExtended = true; + } catch (_) { + } + } + if (!domSelExtended) { + if (anchor > head) { + let tmp = anchorDOM; + anchorDOM = headDOM; + headDOM = tmp; + } + let range = document.createRange(); + range.setEnd(headDOM.node, headDOM.offset); + range.setStart(anchorDOM.node, anchorDOM.offset); + domSel.removeAllRanges(); + domSel.addRange(range); + } + } + ignoreMutation(mutation) { + return !this.contentDOM && mutation.type != "selection"; + } + get contentLost() { + return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM); + } + // Remove a subtree of the element tree that has been touched + // by a DOM change, so that the next update will redraw it. + markDirty(from2, to) { + for (let offset = 0, i = 0; i < this.children.length; i++) { + let child = this.children[i], end = offset + child.size; + if (offset == end ? from2 <= end && to >= offset : from2 < end && to > offset) { + let startInside = offset + child.border, endInside = end - child.border; + if (from2 >= startInside && to <= endInside) { + this.dirty = from2 == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY; + if (from2 == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) + child.dirty = NODE_DIRTY; + else + child.markDirty(from2 - startInside, to - startInside); + return; + } else { + child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY; + } + } + offset = end; + } + this.dirty = CONTENT_DIRTY; + } + markParentsDirty() { + let level = 1; + for (let node = this.parent; node; node = node.parent, level++) { + let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; + if (node.dirty < dirty) + node.dirty = dirty; + } + } + get domAtom() { + return false; + } + get ignoreForCoords() { + return false; + } + get ignoreForSelection() { + return false; + } + isText(text) { + return false; + } +} +class WidgetViewDesc extends ViewDesc { + constructor(parent, widget, view, pos) { + let self2, dom = widget.type.toDOM; + if (typeof dom == "function") + dom = dom(view, () => { + if (!self2) + return pos; + if (self2.parent) + return self2.parent.posBeforeChild(self2); + }); + if (!widget.type.spec.raw) { + if (dom.nodeType != 1) { + let wrap2 = document.createElement("span"); + wrap2.appendChild(dom); + dom = wrap2; + } + dom.contentEditable = "false"; + dom.classList.add("ProseMirror-widget"); + } + super(parent, [], dom, null); + this.widget = widget; + this.widget = widget; + self2 = this; + } + matchesWidget(widget) { + return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type); + } + parseRule() { + return { ignore: true }; + } + stopEvent(event) { + let stop = this.widget.spec.stopEvent; + return stop ? stop(event) : false; + } + ignoreMutation(mutation) { + return mutation.type != "selection" || this.widget.spec.ignoreSelection; + } + destroy() { + this.widget.type.destroy(this.dom); + super.destroy(); + } + get domAtom() { + return true; + } + get ignoreForSelection() { + return !!this.widget.type.spec.relaxedSide; + } + get side() { + return this.widget.type.side; + } +} +class CompositionViewDesc extends ViewDesc { + constructor(parent, dom, textDOM, text) { + super(parent, [], dom, null); + this.textDOM = textDOM; + this.text = text; + } + get size() { + return this.text.length; + } + localPosFromDOM(dom, offset) { + if (dom != this.textDOM) + return this.posAtStart + (offset ? this.size : 0); + return this.posAtStart + offset; + } + domFromPos(pos) { + return { node: this.textDOM, offset: pos }; + } + ignoreMutation(mut) { + return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue; + } +} +class MarkViewDesc extends ViewDesc { + constructor(parent, mark, dom, contentDOM, spec) { + super(parent, [], dom, contentDOM); + this.mark = mark; + this.spec = spec; + } + static create(parent, mark, inline, view) { + let custom = view.nodeViews[mark.type.name]; + let spec = custom && custom(mark, view, inline); + if (!spec || !spec.dom) + spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs); + return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec); + } + parseRule() { + if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView) + return null; + return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM }; + } + matchesMark(mark) { + return this.dirty != NODE_DIRTY && this.mark.eq(mark); + } + markDirty(from2, to) { + super.markDirty(from2, to); + if (this.dirty != NOT_DIRTY) { + let parent = this.parent; + while (!parent.node) + parent = parent.parent; + if (parent.dirty < this.dirty) + parent.dirty = this.dirty; + this.dirty = NOT_DIRTY; + } + } + slice(from2, to, view) { + let copy2 = MarkViewDesc.create(this.parent, this.mark, true, view); + let nodes = this.children, size = this.size; + if (to < size) + nodes = replaceNodes(nodes, to, size, view); + if (from2 > 0) + nodes = replaceNodes(nodes, 0, from2, view); + for (let i = 0; i < nodes.length; i++) + nodes[i].parent = copy2; + copy2.children = nodes; + return copy2; + } + ignoreMutation(mutation) { + return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); + } + destroy() { + if (this.spec.destroy) + this.spec.destroy(); + super.destroy(); + } +} +class NodeViewDesc extends ViewDesc { + constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) { + super(parent, [], dom, contentDOM); + this.node = node; + this.outerDeco = outerDeco; + this.innerDeco = innerDeco; + this.nodeDOM = nodeDOM; + } + // By default, a node is rendered using the `toDOM` method from the + // node type spec. But client code can use the `nodeViews` spec to + // supply a custom node view, which can influence various aspects of + // the way the node works. + // + // (Using subclassing for this was intentionally decided against, + // since it'd require exposing a whole slew of finicky + // implementation details to the user code that they probably will + // never need.) + static create(parent, node, outerDeco, innerDeco, view, pos) { + let custom = view.nodeViews[node.type.name], descObj; + let spec = custom && custom(node, view, () => { + if (!descObj) + return pos; + if (descObj.parent) + return descObj.parent.posBeforeChild(descObj); + }, outerDeco, innerDeco); + let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; + if (node.isText) { + if (!dom) + dom = document.createTextNode(node.text); + else if (dom.nodeType != 3) + throw new RangeError("Text must be rendered as a DOM text node"); + } else if (!dom) { + let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs); + ({ dom, contentDOM } = spec2); + } + if (!contentDOM && !node.isText && dom.nodeName != "BR") { + if (!dom.hasAttribute("contenteditable")) + dom.contentEditable = "false"; + if (node.type.spec.draggable) + dom.draggable = true; + } + let nodeDOM = dom; + dom = applyOuterDeco(dom, outerDeco, node); + if (spec) + return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1); + else if (node.isText) + return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view); + else + return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1); + } + parseRule() { + if (this.node.type.spec.reparseInView) + return null; + let rule = { node: this.node.type.name, attrs: this.node.attrs }; + if (this.node.type.whitespace == "pre") + rule.preserveWhitespace = "full"; + if (!this.contentDOM) { + rule.getContent = () => this.node.content; + } else if (!this.contentLost) { + rule.contentElement = this.contentDOM; + } else { + for (let i = this.children.length - 1; i >= 0; i--) { + let child = this.children[i]; + if (this.dom.contains(child.dom.parentNode)) { + rule.contentElement = child.dom.parentNode; + break; + } + } + if (!rule.contentElement) + rule.getContent = () => Fragment.empty; + } + return rule; + } + matchesNode(node, outerDeco, innerDeco) { + return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco); + } + get size() { + return this.node.nodeSize; + } + get border() { + return this.node.isLeaf ? 0 : 1; + } + // Syncs `this.children` to match `this.node.content` and the local + // decorations, possibly introducing nesting for marks. Then, in a + // separate step, syncs the DOM inside `this.contentDOM` to + // `this.children`. + updateChildren(view, pos) { + let inline = this.node.inlineContent, off = pos; + let composition = view.composing ? this.localCompositionInfo(view, pos) : null; + let localComposition = composition && composition.pos > -1 ? composition : null; + let compositionInChild = composition && composition.pos < 0; + let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view); + iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => { + if (widget.spec.marks) + updater.syncToMarks(widget.spec.marks, inline, view, i); + else if (widget.type.side >= 0 && !insideNode) + updater.syncToMarks(i == this.node.childCount ? Mark$1.none : this.node.child(i).marks, inline, view, i); + updater.placeWidget(widget, view, off); + }, (child, outerDeco, innerDeco, i) => { + updater.syncToMarks(child.marks, inline, view, i); + let compIndex; + if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ; + else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ; + else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ; + else { + updater.addNode(child, outerDeco, innerDeco, view, off); + } + off += child.nodeSize; + }); + updater.syncToMarks([], inline, view, 0); + if (this.node.isTextblock) + updater.addTextblockHacks(); + updater.destroyRest(); + if (updater.changed || this.dirty == CONTENT_DIRTY) { + if (localComposition) + this.protectLocalComposition(view, localComposition); + renderDescs(this.contentDOM, this.children, view); + if (ios) + iosHacks(this.dom); + } + } + localCompositionInfo(view, pos) { + let { from: from2, to } = view.state.selection; + if (!(view.state.selection instanceof TextSelection) || from2 < pos || to > pos + this.node.content.size) + return null; + let textNode = view.input.compositionNode; + if (!textNode || !this.dom.contains(textNode.parentNode)) + return null; + if (this.node.inlineContent) { + let text = textNode.nodeValue; + let textPos = findTextInFragment(this.node.content, text, from2 - pos, to - pos); + return textPos < 0 ? null : { node: textNode, pos: textPos, text }; + } else { + return { node: textNode, pos: -1, text: "" }; + } + } + protectLocalComposition(view, { node, pos, text }) { + if (this.getDesc(node)) + return; + let topNode = node; + for (; ; topNode = topNode.parentNode) { + if (topNode.parentNode == this.contentDOM) + break; + while (topNode.previousSibling) + topNode.parentNode.removeChild(topNode.previousSibling); + while (topNode.nextSibling) + topNode.parentNode.removeChild(topNode.nextSibling); + if (topNode.pmViewDesc) + topNode.pmViewDesc = void 0; + } + let desc = new CompositionViewDesc(this, topNode, node, text); + view.input.compositionNodes.push(desc); + this.children = replaceNodes(this.children, pos, pos + text.length, view, desc); + } + // If this desc must be updated to match the given node decoration, + // do so and return true. + update(node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node)) + return false; + this.updateInner(node, outerDeco, innerDeco, view); + return true; + } + updateInner(node, outerDeco, innerDeco, view) { + this.updateOuterDeco(outerDeco); + this.node = node; + this.innerDeco = innerDeco; + if (this.contentDOM) + this.updateChildren(view, this.posAtStart); + this.dirty = NOT_DIRTY; + } + updateOuterDeco(outerDeco) { + if (sameOuterDeco(outerDeco, this.outerDeco)) + return; + let needsWrap = this.nodeDOM.nodeType != 1; + let oldDOM = this.dom; + this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap)); + if (this.dom != oldDOM) { + oldDOM.pmViewDesc = void 0; + this.dom.pmViewDesc = this; + } + this.outerDeco = outerDeco; + } + // Mark this node as being the selected node. + selectNode() { + if (this.nodeDOM.nodeType == 1) { + this.nodeDOM.classList.add("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) + this.nodeDOM.draggable = true; + } + } + // Remove selected node marking from this node. + deselectNode() { + if (this.nodeDOM.nodeType == 1) { + this.nodeDOM.classList.remove("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) + this.nodeDOM.removeAttribute("draggable"); + } + } + get domAtom() { + return this.node.isAtom; + } +} +function docViewDesc(doc2, outerDeco, innerDeco, dom, view) { + applyOuterDeco(dom, outerDeco, doc2); + let docView = new NodeViewDesc(void 0, doc2, outerDeco, innerDeco, dom, dom, dom, view, 0); + if (docView.contentDOM) + docView.updateChildren(view, 0); + return docView; +} +class TextViewDesc extends NodeViewDesc { + constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) { + super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0); + } + parseRule() { + let skip = this.nodeDOM.parentNode; + while (skip && skip != this.dom && !skip.pmIsDeco) + skip = skip.parentNode; + return { skip: skip || true }; + } + update(node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node)) + return false; + this.updateOuterDeco(outerDeco); + if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) { + this.nodeDOM.nodeValue = node.text; + if (view.trackWrites == this.nodeDOM) + view.trackWrites = null; + } + this.node = node; + this.dirty = NOT_DIRTY; + return true; + } + inParent() { + let parentDOM = this.parent.contentDOM; + for (let n = this.nodeDOM; n; n = n.parentNode) + if (n == parentDOM) + return true; + return false; + } + domFromPos(pos) { + return { node: this.nodeDOM, offset: pos }; + } + localPosFromDOM(dom, offset, bias) { + if (dom == this.nodeDOM) + return this.posAtStart + Math.min(offset, this.node.text.length); + return super.localPosFromDOM(dom, offset, bias); + } + ignoreMutation(mutation) { + return mutation.type != "characterData" && mutation.type != "selection"; + } + slice(from2, to, view) { + let node = this.node.cut(from2, to), dom = document.createTextNode(node.text); + return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view); + } + markDirty(from2, to) { + super.markDirty(from2, to); + if (this.dom != this.nodeDOM && (from2 == 0 || to == this.nodeDOM.nodeValue.length)) + this.dirty = NODE_DIRTY; + } + get domAtom() { + return false; + } + isText(text) { + return this.node.text == text; + } +} +class TrailingHackViewDesc extends ViewDesc { + parseRule() { + return { ignore: true }; + } + matchesHack(nodeName) { + return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; + } + get domAtom() { + return true; + } + get ignoreForCoords() { + return this.dom.nodeName == "IMG"; + } +} +class CustomNodeViewDesc extends NodeViewDesc { + constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) { + super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos); + this.spec = spec; + } + // A custom `update` method gets to decide whether the update goes + // through. If it does, and there's a `contentDOM` node, our logic + // updates the children. + update(node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY) + return false; + if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) { + let result = this.spec.update(node, outerDeco, innerDeco); + if (result) + this.updateInner(node, outerDeco, innerDeco, view); + return result; + } else if (!this.contentDOM && !node.isLeaf) { + return false; + } else { + return super.update(node, outerDeco, innerDeco, view); + } + } + selectNode() { + this.spec.selectNode ? this.spec.selectNode() : super.selectNode(); + } + deselectNode() { + this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode(); + } + setSelection(anchor, head, view, force) { + this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force); + } + destroy() { + if (this.spec.destroy) + this.spec.destroy(); + super.destroy(); + } + stopEvent(event) { + return this.spec.stopEvent ? this.spec.stopEvent(event) : false; + } + ignoreMutation(mutation) { + return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); + } +} +function renderDescs(parentDOM, descs, view) { + let dom = parentDOM.firstChild, written = false; + for (let i = 0; i < descs.length; i++) { + let desc = descs[i], childDOM = desc.dom; + if (childDOM.parentNode == parentDOM) { + while (childDOM != dom) { + dom = rm(dom); + written = true; + } + dom = dom.nextSibling; + } else { + written = true; + parentDOM.insertBefore(childDOM, dom); + } + if (desc instanceof MarkViewDesc) { + let pos = dom ? dom.previousSibling : parentDOM.lastChild; + renderDescs(desc.contentDOM, desc.children, view); + dom = pos ? pos.nextSibling : parentDOM.firstChild; + } + } + while (dom) { + dom = rm(dom); + written = true; + } + if (written && view.trackWrites == parentDOM) + view.trackWrites = null; +} +const OuterDecoLevel = function(nodeName) { + if (nodeName) + this.nodeName = nodeName; +}; +OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null); +const noDeco = [new OuterDecoLevel()]; +function computeOuterDeco(outerDeco, node, needsWrap) { + if (outerDeco.length == 0) + return noDeco; + let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top]; + for (let i = 0; i < outerDeco.length; i++) { + let attrs = outerDeco[i].type.attrs; + if (!attrs) + continue; + if (attrs.nodeName) + result.push(top = new OuterDecoLevel(attrs.nodeName)); + for (let name in attrs) { + let val = attrs[name]; + if (val == null) + continue; + if (needsWrap && result.length == 1) + result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div")); + if (name == "class") + top.class = (top.class ? top.class + " " : "") + val; + else if (name == "style") + top.style = (top.style ? top.style + ";" : "") + val; + else if (name != "nodeName") + top[name] = val; + } + } + return result; +} +function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { + if (prevComputed == noDeco && curComputed == noDeco) + return nodeDOM; + let curDOM = nodeDOM; + for (let i = 0; i < curComputed.length; i++) { + let deco = curComputed[i], prev = prevComputed[i]; + if (i) { + let parent; + if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) { + curDOM = parent; + } else { + parent = document.createElement(deco.nodeName); + parent.pmIsDeco = true; + parent.appendChild(curDOM); + prev = noDeco[0]; + curDOM = parent; + } + } + patchAttributes(curDOM, prev || noDeco[0], deco); + } + return curDOM; +} +function patchAttributes(dom, prev, cur) { + for (let name in prev) + if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) + dom.removeAttribute(name); + for (let name in cur) + if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name]) + dom.setAttribute(name, cur[name]); + if (prev.class != cur.class) { + let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : []; + let curList = cur.class ? cur.class.split(" ").filter(Boolean) : []; + for (let i = 0; i < prevList.length; i++) + if (curList.indexOf(prevList[i]) == -1) + dom.classList.remove(prevList[i]); + for (let i = 0; i < curList.length; i++) + if (prevList.indexOf(curList[i]) == -1) + dom.classList.add(curList[i]); + if (dom.classList.length == 0) + dom.removeAttribute("class"); + } + if (prev.style != cur.style) { + if (prev.style) { + let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m; + while (m = prop.exec(prev.style)) + dom.style.removeProperty(m[1]); + } + if (cur.style) + dom.style.cssText += cur.style; + } +} +function applyOuterDeco(dom, deco, node) { + return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1)); +} +function sameOuterDeco(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].type.eq(b[i].type)) + return false; + return true; +} +function rm(dom) { + let next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next; +} +class ViewTreeUpdater { + constructor(top, lock, view) { + this.lock = lock; + this.view = view; + this.index = 0; + this.stack = []; + this.changed = false; + this.top = top; + this.preMatch = preMatch(top.node.content, top); + } + // Destroy and remove the children between the given indices in + // `this.top`. + destroyBetween(start, end) { + if (start == end) + return; + for (let i = start; i < end; i++) + this.top.children[i].destroy(); + this.top.children.splice(start, end - start); + this.changed = true; + } + // Destroy all remaining children in `this.top`. + destroyRest() { + this.destroyBetween(this.index, this.top.children.length); + } + // Sync the current stack of mark descs with the given array of + // marks, reusing existing mark descs when possible. + syncToMarks(marks, inline, view, parentIndex) { + let keep = 0, depth = this.stack.length >> 1; + let maxKeep = Math.min(depth, marks.length); + while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) + keep++; + while (keep < depth) { + this.destroyRest(); + this.top.dirty = NOT_DIRTY; + this.index = this.stack.pop(); + this.top = this.stack.pop(); + depth--; + } + while (depth < marks.length) { + this.stack.push(this.top, this.index + 1); + let found2 = -1, scanTo = this.top.children.length; + if (parentIndex < this.preMatch.index) + scanTo = Math.min(this.index + 3, scanTo); + for (let i = this.index; i < scanTo; i++) { + let next = this.top.children[i]; + if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) { + found2 = i; + break; + } + } + if (found2 > -1) { + if (found2 > this.index) { + this.changed = true; + this.destroyBetween(this.index, found2); + } + this.top = this.top.children[this.index]; + } else { + let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view); + this.top.children.splice(this.index, 0, markDesc); + this.top = markDesc; + this.changed = true; + } + this.index = 0; + depth++; + } + } + // Try to find a node desc matching the given data. Skip over it and + // return true when successful. + findNodeMatch(node, outerDeco, innerDeco, index) { + let found2 = -1, targetDesc; + if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) { + found2 = this.top.children.indexOf(targetDesc, this.index); + } else { + for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) { + let child = this.top.children[i]; + if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) { + found2 = i; + break; + } + } + } + if (found2 < 0) + return false; + this.destroyBetween(this.index, found2); + this.index++; + return true; + } + updateNodeAt(node, outerDeco, innerDeco, index, view) { + let child = this.top.children[index]; + if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM) + child.dirty = CONTENT_DIRTY; + if (!child.update(node, outerDeco, innerDeco, view)) + return false; + this.destroyBetween(this.index, index); + this.index++; + return true; + } + findIndexWithChild(domNode) { + for (; ; ) { + let parent = domNode.parentNode; + if (!parent) + return -1; + if (parent == this.top.contentDOM) { + let desc = domNode.pmViewDesc; + if (desc) + for (let i = this.index; i < this.top.children.length; i++) { + if (this.top.children[i] == desc) + return i; + } + return -1; + } + domNode = parent; + } + } + // Try to update the next node, if any, to the given data. Checks + // pre-matches to avoid overwriting nodes that could still be used. + updateNextNode(node, outerDeco, innerDeco, view, index, pos) { + for (let i = this.index; i < this.top.children.length; i++) { + let next = this.top.children[i]; + if (next instanceof NodeViewDesc) { + let preMatch2 = this.preMatch.matched.get(next); + if (preMatch2 != null && preMatch2 != index) + return false; + let nextDOM = next.dom, updated; + let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco)); + if (!locked && next.update(node, outerDeco, innerDeco, view)) { + this.destroyBetween(this.index, i); + if (next.dom != nextDOM) + this.changed = true; + this.index++; + return true; + } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) { + this.destroyBetween(this.index, i); + this.top.children[this.index] = updated; + if (updated.contentDOM) { + updated.dirty = CONTENT_DIRTY; + updated.updateChildren(view, pos + 1); + updated.dirty = NOT_DIRTY; + } + this.changed = true; + this.index++; + return true; + } + break; + } + } + return false; + } + // When a node with content is replaced by a different node with + // identical content, move over its children. + recreateWrapper(next, node, outerDeco, innerDeco, view, pos) { + if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco)) + return null; + let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); + if (wrapper.contentDOM) { + wrapper.children = next.children; + next.children = []; + for (let ch of wrapper.children) + ch.parent = wrapper; + } + next.destroy(); + return wrapper; + } + // Insert the node as a newly created node desc. + addNode(node, outerDeco, innerDeco, view, pos) { + let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); + if (desc.contentDOM) + desc.updateChildren(view, pos + 1); + this.top.children.splice(this.index++, 0, desc); + this.changed = true; + } + placeWidget(widget, view, pos) { + let next = this.index < this.top.children.length ? this.top.children[this.index] : null; + if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) { + this.index++; + } else { + let desc = new WidgetViewDesc(this.top, widget, view, pos); + this.top.children.splice(this.index++, 0, desc); + this.changed = true; + } + } + // Make sure a textblock looks and behaves correctly in + // contentEditable. + addTextblockHacks() { + let lastChild = this.top.children[this.index - 1], parent = this.top; + while (lastChild instanceof MarkViewDesc) { + parent = lastChild; + lastChild = parent.children[parent.children.length - 1]; + } + if (!lastChild || // Empty textblock + !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) { + if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false") + this.addHackNode("IMG", parent); + this.addHackNode("BR", this.top); + } + } + addHackNode(nodeName, parent) { + if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) { + this.index++; + } else { + let dom = document.createElement(nodeName); + if (nodeName == "IMG") { + dom.className = "ProseMirror-separator"; + dom.alt = ""; + } + if (nodeName == "BR") + dom.className = "ProseMirror-trailingBreak"; + let hack = new TrailingHackViewDesc(this.top, [], dom, null); + if (parent != this.top) + parent.children.push(hack); + else + parent.children.splice(this.index++, 0, hack); + this.changed = true; + } + } + isLocked(node) { + return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode)); + } +} +function preMatch(frag, parentDesc) { + let curDesc = parentDesc, descI = curDesc.children.length; + let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = []; + outer: while (fI > 0) { + let desc; + for (; ; ) { + if (descI) { + let next = curDesc.children[descI - 1]; + if (next instanceof MarkViewDesc) { + curDesc = next; + descI = next.children.length; + } else { + desc = next; + descI--; + break; + } + } else if (curDesc == parentDesc) { + break outer; + } else { + descI = curDesc.parent.children.indexOf(curDesc); + curDesc = curDesc.parent; + } + } + let node = desc.node; + if (!node) + continue; + if (node != frag.child(fI - 1)) + break; + --fI; + matched.set(desc, fI); + matches2.push(desc); + } + return { index: fI, matched, matches: matches2.reverse() }; +} +function compareSide(a, b) { + return a.type.side - b.type.side; +} +function iterDeco(parent, deco, onWidget, onNode) { + let locals = deco.locals(parent), offset = 0; + if (locals.length == 0) { + for (let i = 0; i < parent.childCount; i++) { + let child = parent.child(i); + onNode(child, locals, deco.forChild(offset, child), i); + offset += child.nodeSize; + } + return; + } + let decoIndex = 0, active = [], restNode = null; + for (let parentIndex = 0; ; ) { + let widget, widgets; + while (decoIndex < locals.length && locals[decoIndex].to == offset) { + let next = locals[decoIndex++]; + if (next.widget) { + if (!widget) + widget = next; + else + (widgets || (widgets = [widget])).push(next); + } + } + if (widget) { + if (widgets) { + widgets.sort(compareSide); + for (let i = 0; i < widgets.length; i++) + onWidget(widgets[i], parentIndex, !!restNode); + } else { + onWidget(widget, parentIndex, !!restNode); + } + } + let child, index; + if (restNode) { + index = -1; + child = restNode; + restNode = null; + } else if (parentIndex < parent.childCount) { + index = parentIndex; + child = parent.child(parentIndex++); + } else { + break; + } + for (let i = 0; i < active.length; i++) + if (active[i].to <= offset) + active.splice(i--, 1); + while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset) + active.push(locals[decoIndex++]); + let end = offset + child.nodeSize; + if (child.isText) { + let cutAt = end; + if (decoIndex < locals.length && locals[decoIndex].from < cutAt) + cutAt = locals[decoIndex].from; + for (let i = 0; i < active.length; i++) + if (active[i].to < cutAt) + cutAt = active[i].to; + if (cutAt < end) { + restNode = child.cut(cutAt - offset); + child = child.cut(0, cutAt - offset); + end = cutAt; + index = -1; + } + } else { + while (decoIndex < locals.length && locals[decoIndex].to < end) + decoIndex++; + } + let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice(); + onNode(child, outerDeco, deco.forChild(offset, child), index); + offset = end; + } +} +function iosHacks(dom) { + if (dom.nodeName == "UL" || dom.nodeName == "OL") { + let oldCSS = dom.style.cssText; + dom.style.cssText = oldCSS + "; list-style: square !important"; + window.getComputedStyle(dom).listStyle; + dom.style.cssText = oldCSS; + } +} +function findTextInFragment(frag, text, from2, to) { + for (let i = 0, pos = 0; i < frag.childCount && pos <= to; ) { + let child = frag.child(i++), childStart = pos; + pos += child.nodeSize; + if (!child.isText) + continue; + let str = child.text; + while (i < frag.childCount) { + let next = frag.child(i++); + pos += next.nodeSize; + if (!next.isText) + break; + str += next.text; + } + if (pos >= from2) { + if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text) + return to - text.length; + let found2 = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1; + if (found2 >= 0 && found2 + text.length + childStart >= from2) + return childStart + found2; + if (from2 == to && str.length >= to + text.length - childStart && str.slice(to - childStart, to - childStart + text.length) == text) + return to; + } + } + return -1; +} +function replaceNodes(nodes, from2, to, view, replacement) { + let result = []; + for (let i = 0, off = 0; i < nodes.length; i++) { + let child = nodes[i], start = off, end = off += child.size; + if (start >= to || end <= from2) { + result.push(child); + } else { + if (start < from2) + result.push(child.slice(0, from2 - start, view)); + if (replacement) { + result.push(replacement); + replacement = void 0; + } + if (end > to) + result.push(child.slice(to - start, child.size, view)); + } + } + return result; +} +function selectionFromDOM(view, origin = null) { + let domSel = view.domSelectionRange(), doc2 = view.state.doc; + if (!domSel.focusNode) + return null; + let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; + let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1); + if (head < 0) + return null; + let $head = doc2.resolve(head), anchor, selection; + if (selectionCollapsed(domSel)) { + anchor = head; + while (nearestDesc && !nearestDesc.node) + nearestDesc = nearestDesc.parent; + let nearestDescNode = nearestDesc.node; + if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { + let pos = nearestDesc.posBefore; + selection = new NodeSelection(head == pos ? $head : doc2.resolve(pos)); + } + } else { + if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) { + let min = head, max = head; + for (let i = 0; i < domSel.rangeCount; i++) { + let range = domSel.getRangeAt(i); + min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1)); + max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1)); + } + if (min < 0) + return null; + [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max]; + $head = doc2.resolve(head); + } else { + anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1); + } + if (anchor < 0) + return null; + } + let $anchor = doc2.resolve(anchor); + if (!selection) { + let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1; + selection = selectionBetween(view, $anchor, $head, bias); + } + return selection; +} +function editorOwnsSelection(view) { + return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom); +} +function selectionToDOM(view, force = false) { + let sel = view.state.selection; + syncNodeSelection(view, sel); + if (!editorOwnsSelection(view)) + return; + if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) { + let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection; + if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) { + view.input.mouseDown.delayedSelectionSync = true; + view.domObserver.setCurSelection(); + return; + } + } + view.domObserver.disconnectSelection(); + if (view.cursorWrapper) { + selectCursorWrapper(view); + } else { + let { anchor, head } = sel, resetEditableFrom, resetEditableTo; + if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { + if (!sel.$from.parent.inlineContent) + resetEditableFrom = temporarilyEditableNear(view, sel.from); + if (!sel.empty && !sel.$from.parent.inlineContent) + resetEditableTo = temporarilyEditableNear(view, sel.to); + } + view.docView.setSelection(anchor, head, view, force); + if (brokenSelectBetweenUneditable) { + if (resetEditableFrom) + resetEditable(resetEditableFrom); + if (resetEditableTo) + resetEditable(resetEditableTo); + } + if (sel.visible) { + view.dom.classList.remove("ProseMirror-hideselection"); + } else { + view.dom.classList.add("ProseMirror-hideselection"); + if ("onselectionchange" in document) + removeClassOnSelectionChange(view); + } + } + view.domObserver.setCurSelection(); + view.domObserver.connectSelection(); +} +const brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63; +function temporarilyEditableNear(view, pos) { + let { node, offset } = view.docView.domFromPos(pos, 0); + let after = offset < node.childNodes.length ? node.childNodes[offset] : null; + let before = offset ? node.childNodes[offset - 1] : null; + if (safari && after && after.contentEditable == "false") + return setEditable(after); + if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { + if (after) + return setEditable(after); + else if (before) + return setEditable(before); + } +} +function setEditable(element) { + element.contentEditable = "true"; + if (safari && element.draggable) { + element.draggable = false; + element.wasDraggable = true; + } + return element; +} +function resetEditable(element) { + element.contentEditable = "false"; + if (element.wasDraggable) { + element.draggable = true; + element.wasDraggable = null; + } +} +function removeClassOnSelectionChange(view) { + let doc2 = view.dom.ownerDocument; + doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard); + let domSel = view.domSelectionRange(); + let node = domSel.anchorNode, offset = domSel.anchorOffset; + doc2.addEventListener("selectionchange", view.input.hideSelectionGuard = () => { + if (domSel.anchorNode != node || domSel.anchorOffset != offset) { + doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard); + setTimeout(() => { + if (!editorOwnsSelection(view) || view.state.selection.visible) + view.dom.classList.remove("ProseMirror-hideselection"); + }, 20); + } + }); +} +function selectCursorWrapper(view) { + let domSel = view.domSelection(); + if (!domSel) + return; + let node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; + if (img) + domSel.collapse(node.parentNode, domIndex(node) + 1); + else + domSel.collapse(node, 0); + if (!img && !view.state.selection.visible && ie$1 && ie_version <= 11) { + node.disabled = true; + node.disabled = false; + } +} +function syncNodeSelection(view, sel) { + if (sel instanceof NodeSelection) { + let desc = view.docView.descAt(sel.from); + if (desc != view.lastSelectedViewDesc) { + clearNodeSelection(view); + if (desc) + desc.selectNode(); + view.lastSelectedViewDesc = desc; + } + } else { + clearNodeSelection(view); + } +} +function clearNodeSelection(view) { + if (view.lastSelectedViewDesc) { + if (view.lastSelectedViewDesc.parent) + view.lastSelectedViewDesc.deselectNode(); + view.lastSelectedViewDesc = void 0; + } +} +function selectionBetween(view, $anchor, $head, bias) { + return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias); +} +function hasFocusAndSelection(view) { + if (view.editable && !view.hasFocus()) + return false; + return hasSelection(view); +} +function hasSelection(view) { + let sel = view.domSelectionRange(); + if (!sel.anchorNode) + return false; + try { + return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)); + } catch (_) { + return false; + } +} +function anchorInRightPlace(view) { + let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0); + let domSel = view.domSelectionRange(); + return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset); +} +function moveSelectionBlock(state, dir) { + let { $anchor, $head } = state.selection; + let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); + let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; + return $start && Selection.findFrom($start, dir); +} +function apply(view, sel) { + view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); + return true; +} +function selectHorizontally(view, dir, mods) { + let sel = view.state.selection; + if (sel instanceof TextSelection) { + if (mods.indexOf("s") > -1) { + let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter; + if (!node || node.isText || !node.isLeaf) + return false; + let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1)); + return apply(view, new TextSelection(sel.$anchor, $newHead)); + } else if (!sel.empty) { + return false; + } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { + let next = moveSelectionBlock(view.state, dir); + if (next && next instanceof NodeSelection) + return apply(view, next); + return false; + } else if (!(mac$2 && mods.indexOf("m") > -1)) { + let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; + if (!node || node.isText) + return false; + let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; + if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) + return false; + if (NodeSelection.isSelectable(node)) { + return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)); + } else if (webkit) { + return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))); + } else { + return false; + } + } + } else if (sel instanceof NodeSelection && sel.node.isInline) { + return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)); + } else { + let next = moveSelectionBlock(view.state, dir); + if (next) + return apply(view, next); + return false; + } +} +function nodeLen(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; +} +function isIgnorable(dom, dir) { + let desc = dom.pmViewDesc; + return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR"); +} +function skipIgnoredNodes(view, dir) { + return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view); +} +function skipIgnoredNodesBefore(view) { + let sel = view.domSelectionRange(); + let node = sel.focusNode, offset = sel.focusOffset; + if (!node) + return; + let moveNode, moveOffset, force = false; + if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1)) + force = true; + for (; ; ) { + if (offset > 0) { + if (node.nodeType != 1) { + break; + } else { + let before = node.childNodes[offset - 1]; + if (isIgnorable(before, -1)) { + moveNode = node; + moveOffset = --offset; + } else if (before.nodeType == 3) { + node = before; + offset = node.nodeValue.length; + } else + break; + } + } else if (isBlockNode(node)) { + break; + } else { + let prev = node.previousSibling; + while (prev && isIgnorable(prev, -1)) { + moveNode = node.parentNode; + moveOffset = domIndex(prev); + prev = prev.previousSibling; + } + if (!prev) { + node = node.parentNode; + if (node == view.dom) + break; + offset = 0; + } else { + node = prev; + offset = nodeLen(node); + } + } + } + if (force) + setSelFocus(view, node, offset); + else if (moveNode) + setSelFocus(view, moveNode, moveOffset); +} +function skipIgnoredNodesAfter(view) { + let sel = view.domSelectionRange(); + let node = sel.focusNode, offset = sel.focusOffset; + if (!node) + return; + let len = nodeLen(node); + let moveNode, moveOffset; + for (; ; ) { + if (offset < len) { + if (node.nodeType != 1) + break; + let after = node.childNodes[offset]; + if (isIgnorable(after, 1)) { + moveNode = node; + moveOffset = ++offset; + } else + break; + } else if (isBlockNode(node)) { + break; + } else { + let next = node.nextSibling; + while (next && isIgnorable(next, 1)) { + moveNode = next.parentNode; + moveOffset = domIndex(next) + 1; + next = next.nextSibling; + } + if (!next) { + node = node.parentNode; + if (node == view.dom) + break; + offset = len = 0; + } else { + node = next; + offset = 0; + len = nodeLen(node); + } + } + } + if (moveNode) + setSelFocus(view, moveNode, moveOffset); +} +function isBlockNode(dom) { + let desc = dom.pmViewDesc; + return desc && desc.node && desc.node.isBlock; +} +function textNodeAfter(node, offset) { + while (node && offset == node.childNodes.length && !hasBlockDesc(node)) { + offset = domIndex(node) + 1; + node = node.parentNode; + } + while (node && offset < node.childNodes.length) { + let next = node.childNodes[offset]; + if (next.nodeType == 3) + return next; + if (next.nodeType == 1 && next.contentEditable == "false") + break; + node = next; + offset = 0; + } +} +function textNodeBefore(node, offset) { + while (node && !offset && !hasBlockDesc(node)) { + offset = domIndex(node); + node = node.parentNode; + } + while (node && offset) { + let next = node.childNodes[offset - 1]; + if (next.nodeType == 3) + return next; + if (next.nodeType == 1 && next.contentEditable == "false") + break; + node = next; + offset = node.childNodes.length; + } +} +function setSelFocus(view, node, offset) { + if (node.nodeType != 3) { + let before, after; + if (after = textNodeAfter(node, offset)) { + node = after; + offset = 0; + } else if (before = textNodeBefore(node, offset)) { + node = before; + offset = before.nodeValue.length; + } + } + let sel = view.domSelection(); + if (!sel) + return; + if (selectionCollapsed(sel)) { + let range = document.createRange(); + range.setEnd(node, offset); + range.setStart(node, offset); + sel.removeAllRanges(); + sel.addRange(range); + } else if (sel.extend) { + sel.extend(node, offset); + } + view.domObserver.setCurSelection(); + let { state } = view; + setTimeout(() => { + if (view.state == state) + selectionToDOM(view); + }, 50); +} +function findDirection(view, pos) { + let $pos = view.state.doc.resolve(pos); + if (!(chrome || windows$1) && $pos.parent.inlineContent) { + let coords = view.coordsAtPos(pos); + if (pos > $pos.start()) { + let before = view.coordsAtPos(pos - 1); + let mid = (before.top + before.bottom) / 2; + if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1) + return before.left < coords.left ? "ltr" : "rtl"; + } + if (pos < $pos.end()) { + let after = view.coordsAtPos(pos + 1); + let mid = (after.top + after.bottom) / 2; + if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1) + return after.left > coords.left ? "ltr" : "rtl"; + } + } + let computed = getComputedStyle(view.dom).direction; + return computed == "rtl" ? "rtl" : "ltr"; +} +function selectVertically(view, dir, mods) { + let sel = view.state.selection; + if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) + return false; + if (mac$2 && mods.indexOf("m") > -1) + return false; + let { $from, $to } = sel; + if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { + let next = moveSelectionBlock(view.state, dir); + if (next && next instanceof NodeSelection) + return apply(view, next); + } + if (!$from.parent.inlineContent) { + let side = dir < 0 ? $from : $to; + let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir); + return beyond ? apply(view, beyond) : false; + } + return false; +} +function stopNativeHorizontalDelete(view, dir) { + if (!(view.state.selection instanceof TextSelection)) + return true; + let { $head, $anchor, empty: empty2 } = view.state.selection; + if (!$head.sameParent($anchor)) + return true; + if (!empty2) + return false; + if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) + return true; + let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); + if (nextNode && !nextNode.isText) { + let tr2 = view.state.tr; + if (dir < 0) + tr2.delete($head.pos - nextNode.nodeSize, $head.pos); + else + tr2.delete($head.pos, $head.pos + nextNode.nodeSize); + view.dispatch(tr2); + return true; + } + return false; +} +function switchEditable(view, node, state) { + view.domObserver.stop(); + node.contentEditable = state; + view.domObserver.start(); +} +function safariDownArrowBug(view) { + if (!safari || view.state.selection.$head.parentOffset > 0) + return false; + let { focusNode, focusOffset } = view.domSelectionRange(); + if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { + let child = focusNode.firstChild; + switchEditable(view, child, "true"); + setTimeout(() => switchEditable(view, child, "false"), 20); + } + return false; +} +function getMods(event) { + let result = ""; + if (event.ctrlKey) + result += "c"; + if (event.metaKey) + result += "m"; + if (event.altKey) + result += "a"; + if (event.shiftKey) + result += "s"; + return result; +} +function captureKeyDown(view, event) { + let code = event.keyCode, mods = getMods(event); + if (code == 8 || mac$2 && code == 72 && mods == "c") { + return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1); + } else if (code == 46 && !event.shiftKey || mac$2 && code == 68 && mods == "c") { + return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1); + } else if (code == 13 || code == 27) { + return true; + } else if (code == 37 || mac$2 && code == 66 && mods == "c") { + let dir = code == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1; + return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); + } else if (code == 39 || mac$2 && code == 70 && mods == "c") { + let dir = code == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1; + return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); + } else if (code == 38 || mac$2 && code == 80 && mods == "c") { + return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1); + } else if (code == 40 || mac$2 && code == 78 && mods == "c") { + return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1); + } else if (mods == (mac$2 ? "m" : "c") && (code == 66 || code == 73 || code == 89 || code == 90)) { + return true; + } + return false; +} +function serializeForClipboard(view, slice2) { + view.someProp("transformCopied", (f) => { + slice2 = f(slice2, view); + }); + let context = [], { content, openStart, openEnd } = slice2; + while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { + openStart--; + openEnd--; + let node = content.firstChild; + context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); + content = node.content; + } + let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); + let doc2 = detachedDoc(), wrap2 = doc2.createElement("div"); + wrap2.appendChild(serializer.serializeFragment(content, { document: doc2 })); + let firstChild = wrap2.firstChild, needsWrap, wrappers = 0; + while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { + for (let i = needsWrap.length - 1; i >= 0; i--) { + let wrapper = doc2.createElement(needsWrap[i]); + while (wrap2.firstChild) + wrapper.appendChild(wrap2.firstChild); + wrap2.appendChild(wrapper); + wrappers++; + } + firstChild = wrap2.firstChild; + } + if (firstChild && firstChild.nodeType == 1) + firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`); + let text = view.someProp("clipboardTextSerializer", (f) => f(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n"); + return { dom: wrap2, text, slice: slice2 }; +} +function parseFromClipboard(view, text, html, plainText, $context) { + let inCode = $context.parent.type.spec.code; + let dom, slice2; + if (!html && !text) + return null; + let asText = !!text && (plainText || inCode || !html); + if (asText) { + view.someProp("transformPastedText", (f) => { + text = f(text, inCode || plainText, view); + }); + if (inCode) { + slice2 = new Slice(Fragment.from(view.state.schema.text(text.replace(/\r\n?/g, "\n"))), 0, 0); + view.someProp("transformPasted", (f) => { + slice2 = f(slice2, view, true); + }); + return slice2; + } + let parsed = view.someProp("clipboardTextParser", (f) => f(text, $context, plainText, view)); + if (parsed) { + slice2 = parsed; + } else { + let marks = $context.marks(); + let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema); + dom = document.createElement("div"); + text.split(/(?:\r\n?|\n)+/).forEach((block) => { + let p = dom.appendChild(document.createElement("p")); + if (block) + p.appendChild(serializer.serializeNode(schema.text(block, marks))); + }); + } + } else { + view.someProp("transformPastedHTML", (f) => { + html = f(html, view); + }); + dom = readHTML(html); + if (webkit) + restoreReplacedSpaces(dom); + } + let contextNode = dom && dom.querySelector("[data-pm-slice]"); + let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || ""); + if (sliceData && sliceData[3]) + for (let i = +sliceData[3]; i > 0; i--) { + let child = dom.firstChild; + while (child && child.nodeType != 1) + child = child.nextSibling; + if (!child) + break; + dom = child; + } + if (!slice2) { + let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); + slice2 = parser.parseSlice(dom, { + preserveWhitespace: !!(asText || sliceData), + context: $context, + ruleFromNode(dom2) { + if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName)) + return { ignore: true }; + return null; + } + }); + } + if (sliceData) { + slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]); + } else { + slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true); + if (slice2.openStart || slice2.openEnd) { + let openStart = 0, openEnd = 0; + for (let node = slice2.content.firstChild; openStart < slice2.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { + } + for (let node = slice2.content.lastChild; openEnd < slice2.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { + } + slice2 = closeSlice(slice2, openStart, openEnd); + } + } + view.someProp("transformPasted", (f) => { + slice2 = f(slice2, view, asText); + }); + return slice2; +} +const inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i; +function normalizeSiblings(fragment, $context) { + if (fragment.childCount < 2) + return fragment; + for (let d = $context.depth; d >= 0; d--) { + let parent = $context.node(d); + let match = parent.contentMatchAt($context.index(d)); + let lastWrap, result = []; + fragment.forEach((node) => { + if (!result) + return; + let wrap2 = match.findWrapping(node.type), inLast; + if (!wrap2) + return result = null; + if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) { + result[result.length - 1] = inLast; + } else { + if (result.length) + result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); + let wrapped = withWrappers(node, wrap2); + result.push(wrapped); + match = match.matchType(wrapped.type); + lastWrap = wrap2; + } + }); + if (result) + return Fragment.from(result); + } + return fragment; +} +function withWrappers(node, wrap2, from2 = 0) { + for (let i = wrap2.length - 1; i >= from2; i--) + node = wrap2[i].create(null, Fragment.from(node)); + return node; +} +function addToSibling(wrap2, lastWrap, node, sibling, depth) { + if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) { + let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1); + if (inner) + return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)); + let match = sibling.contentMatchAt(sibling.childCount); + if (match.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1])) + return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1)))); + } +} +function closeRight(node, depth) { + if (depth == 0) + return node; + let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); + let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); + return node.copy(fragment.append(fill)); +} +function closeRange(fragment, side, from2, to, depth, openEnd) { + let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; + if (fragment.childCount > 1) + openEnd = 0; + if (depth < to - 1) + inner = closeRange(inner, side, from2, to, depth + 1, openEnd); + if (depth >= from2) + inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); + return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)); +} +function closeSlice(slice2, openStart, openEnd) { + if (openStart < slice2.openStart) + slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd); + if (openEnd < slice2.openEnd) + slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd); + return slice2; +} +const wrapMap = { + thead: ["table"], + tbody: ["table"], + tfoot: ["table"], + caption: ["table"], + colgroup: ["table"], + col: ["table", "colgroup"], + tr: ["table", "tbody"], + td: ["table", "tbody", "tr"], + th: ["table", "tbody", "tr"] +}; +let _detachedDoc = null; +function detachedDoc() { + return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title")); +} +let _policy = null; +function maybeWrapTrusted(html) { + let trustedTypes = window.trustedTypes; + if (!trustedTypes) + return html; + if (!_policy) + _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s }); + return _policy.createHTML(html); +} +function readHTML(html) { + let metas = /^(\s*]*>)*/.exec(html); + if (metas) + html = html.slice(metas[0].length); + let elt = detachedDoc().createElement("div"); + let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap2; + if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()]) + html = wrap2.map((n) => "<" + n + ">").join("") + html + wrap2.map((n) => "").reverse().join(""); + elt.innerHTML = maybeWrapTrusted(html); + if (wrap2) + for (let i = 0; i < wrap2.length; i++) + elt = elt.querySelector(wrap2[i]) || elt; + return elt; +} +function restoreReplacedSpaces(dom) { + let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space"); + for (let i = 0; i < nodes.length; i++) { + let node = nodes[i]; + if (node.childNodes.length == 1 && node.textContent == " " && node.parentNode) + node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node); + } +} +function addContext(slice2, context) { + if (!slice2.size) + return slice2; + let schema = slice2.content.firstChild.type.schema, array; + try { + array = JSON.parse(context); + } catch (e) { + return slice2; + } + let { content, openStart, openEnd } = slice2; + for (let i = array.length - 2; i >= 0; i -= 2) { + let type = schema.nodes[array[i]]; + if (!type || type.hasRequiredAttrs()) + break; + content = Fragment.from(type.create(array[i + 1], content)); + openStart++; + openEnd++; + } + return new Slice(content, openStart, openEnd); +} +const handlers = {}; +const editHandlers = {}; +const passiveHandlers = { touchstart: true, touchmove: true }; +class InputState { + constructor() { + this.shiftKey = false; + this.mouseDown = null; + this.lastKeyCode = null; + this.lastKeyCodeTime = 0; + this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 }; + this.lastSelectionOrigin = null; + this.lastSelectionTime = 0; + this.lastIOSEnter = 0; + this.lastIOSEnterFallbackTimeout = -1; + this.lastFocus = 0; + this.lastTouch = 0; + this.lastChromeDelete = 0; + this.composing = false; + this.compositionNode = null; + this.composingTimeout = -1; + this.compositionNodes = []; + this.compositionEndedAt = -2e8; + this.compositionID = 1; + this.badSafariComposition = false; + this.compositionPendingChanges = 0; + this.domChangeCount = 0; + this.eventHandlers = /* @__PURE__ */ Object.create(null); + this.hideSelectionGuard = null; + } +} +function initInput(view) { + for (let event in handlers) { + let handler = handlers[event]; + view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => { + if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers))) + handler(view, event2); + }, passiveHandlers[event] ? { passive: true } : void 0); + } + if (safari) + view.dom.addEventListener("input", () => null); + ensureListeners(view); +} +function setSelectionOrigin(view, origin) { + view.input.lastSelectionOrigin = origin; + view.input.lastSelectionTime = Date.now(); +} +function destroyInput(view) { + view.domObserver.stop(); + for (let type in view.input.eventHandlers) + view.dom.removeEventListener(type, view.input.eventHandlers[type]); + clearTimeout(view.input.composingTimeout); + clearTimeout(view.input.lastIOSEnterFallbackTimeout); +} +function ensureListeners(view) { + view.someProp("handleDOMEvents", (currentHandlers) => { + for (let type in currentHandlers) + if (!view.input.eventHandlers[type]) + view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event)); + }); +} +function runCustomHandler(view, event) { + return view.someProp("handleDOMEvents", (handlers2) => { + let handler = handlers2[event.type]; + return handler ? handler(view, event) || event.defaultPrevented : false; + }); +} +function eventBelongsToView(view, event) { + if (!event.bubbles) + return true; + if (event.defaultPrevented) + return false; + for (let node = event.target; node != view.dom; node = node.parentNode) + if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event)) + return false; + return true; +} +function dispatchEvent(view, event) { + if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers))) + handlers[event.type](view, event); +} +editHandlers.keydown = (view, _event) => { + let event = _event; + view.input.shiftKey = event.keyCode == 16 || event.shiftKey; + if (inOrNearComposition(view, event)) + return; + view.input.lastKeyCode = event.keyCode; + view.input.lastKeyCodeTime = Date.now(); + if (android && chrome && event.keyCode == 13) + return; + if (event.keyCode != 229) + view.domObserver.forceFlush(); + if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { + let now = Date.now(); + view.input.lastIOSEnter = now; + view.input.lastIOSEnterFallbackTimeout = setTimeout(() => { + if (view.input.lastIOSEnter == now) { + view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))); + view.input.lastIOSEnter = 0; + } + }, 200); + } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) { + event.preventDefault(); + } else { + setSelectionOrigin(view, "key"); + } +}; +editHandlers.keyup = (view, event) => { + if (event.keyCode == 16) + view.input.shiftKey = false; +}; +editHandlers.keypress = (view, _event) => { + let event = _event; + if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac$2 && event.metaKey) + return; + if (view.someProp("handleKeyPress", (f) => f(view, event))) { + event.preventDefault(); + return; + } + let sel = view.state.selection; + if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { + let text = String.fromCharCode(event.charCode); + let deflt = () => view.state.tr.insertText(text).scrollIntoView(); + if (!/[\r\n]/.test(text) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text, deflt))) + view.dispatch(deflt()); + event.preventDefault(); + } +}; +function eventCoords(event) { + return { left: event.clientX, top: event.clientY }; +} +function isNear(event, click) { + let dx = click.x - event.clientX, dy = click.y - event.clientY; + return dx * dx + dy * dy < 100; +} +function runHandlerOnContext(view, propName, pos, inside, event) { + if (inside == -1) + return false; + let $pos = view.state.doc.resolve(inside); + for (let i = $pos.depth + 1; i > 0; i--) { + if (view.someProp(propName, (f) => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false))) + return true; + } + return false; +} +function updateSelection(view, selection, origin) { + if (!view.focused) + view.focus(); + if (view.state.selection.eq(selection)) + return; + let tr2 = view.state.tr.setSelection(selection); + tr2.setMeta("pointer", true); + view.dispatch(tr2); +} +function selectClickedLeaf(view, inside) { + if (inside == -1) + return false; + let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; + if (node && node.isAtom && NodeSelection.isSelectable(node)) { + updateSelection(view, new NodeSelection($pos)); + return true; + } + return false; +} +function selectClickedNode(view, inside) { + if (inside == -1) + return false; + let sel = view.state.selection, selectedNode, selectAt; + if (sel instanceof NodeSelection) + selectedNode = sel.node; + let $pos = view.state.doc.resolve(inside); + for (let i = $pos.depth + 1; i > 0; i--) { + let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + if (NodeSelection.isSelectable(node)) { + if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) + selectAt = $pos.before(sel.$from.depth); + else + selectAt = $pos.before(i); + break; + } + } + if (selectAt != null) { + updateSelection(view, NodeSelection.create(view.state.doc, selectAt)); + return true; + } else { + return false; + } +} +function handleSingleClick(view, pos, inside, event, selectNode) { + return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)); +} +function handleDoubleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event)); +} +function handleTripleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event); +} +function defaultTripleClick(view, inside, event) { + if (event.button != 0) + return false; + let doc2 = view.state.doc; + if (inside == -1) { + if (doc2.inlineContent) { + updateSelection(view, TextSelection.create(doc2, 0, doc2.content.size)); + return true; + } + return false; + } + let $pos = doc2.resolve(inside); + for (let i = $pos.depth + 1; i > 0; i--) { + let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + let nodePos = $pos.before(i); + if (node.inlineContent) + updateSelection(view, TextSelection.create(doc2, nodePos + 1, nodePos + 1 + node.content.size)); + else if (NodeSelection.isSelectable(node)) + updateSelection(view, NodeSelection.create(doc2, nodePos)); + else + continue; + return true; + } +} +function forceDOMFlush(view) { + return endComposition(view); +} +const selectNodeModifier = mac$2 ? "metaKey" : "ctrlKey"; +handlers.mousedown = (view, _event) => { + let event = _event; + view.input.shiftKey = event.shiftKey; + let flushed = forceDOMFlush(view); + let now = Date.now(), type = "singleClick"; + if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) { + if (view.input.lastClick.type == "singleClick") + type = "doubleClick"; + else if (view.input.lastClick.type == "doubleClick") + type = "tripleClick"; + } + view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button }; + let pos = view.posAtCoords(eventCoords(event)); + if (!pos) + return; + if (type == "singleClick") { + if (view.input.mouseDown) + view.input.mouseDown.done(); + view.input.mouseDown = new MouseDown(view, pos, event, !!flushed); + } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) { + event.preventDefault(); + } else { + setSelectionOrigin(view, "pointer"); + } +}; +class MouseDown { + constructor(view, pos, event, flushed) { + this.view = view; + this.pos = pos; + this.event = event; + this.flushed = flushed; + this.delayedSelectionSync = false; + this.mightDrag = null; + this.startDoc = view.state.doc; + this.selectNode = !!event[selectNodeModifier]; + this.allowDefault = event.shiftKey; + let targetNode, targetPos; + if (pos.inside > -1) { + targetNode = view.state.doc.nodeAt(pos.inside); + targetPos = pos.inside; + } else { + let $pos = view.state.doc.resolve(pos.pos); + targetNode = $pos.parent; + targetPos = $pos.depth ? $pos.before() : 0; + } + const target = flushed ? null : event.target; + const targetDesc = target ? view.docView.nearestDesc(target, true) : null; + this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null; + let { selection } = view.state; + if (event.button == 0 && (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)) + this.mightDrag = { + node: targetNode, + pos: targetPos, + addAttr: !!(this.target && !this.target.draggable), + setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable")) + }; + if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) + this.target.draggable = true; + if (this.mightDrag.setUneditable) + setTimeout(() => { + if (this.view.input.mouseDown == this) + this.target.setAttribute("contentEditable", "false"); + }, 20); + this.view.domObserver.start(); + } + view.root.addEventListener("mouseup", this.up = this.up.bind(this)); + view.root.addEventListener("mousemove", this.move = this.move.bind(this)); + setSelectionOrigin(view, "pointer"); + } + done() { + this.view.root.removeEventListener("mouseup", this.up); + this.view.root.removeEventListener("mousemove", this.move); + if (this.mightDrag && this.target) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) + this.target.removeAttribute("draggable"); + if (this.mightDrag.setUneditable) + this.target.removeAttribute("contentEditable"); + this.view.domObserver.start(); + } + if (this.delayedSelectionSync) + setTimeout(() => selectionToDOM(this.view)); + this.view.input.mouseDown = null; + } + up(event) { + this.done(); + if (!this.view.dom.contains(event.target)) + return; + let pos = this.pos; + if (this.view.state.doc != this.startDoc) + pos = this.view.posAtCoords(eventCoords(event)); + this.updateAllowDefault(event); + if (this.allowDefault || !pos) { + setSelectionOrigin(this.view, "pointer"); + } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) { + event.preventDefault(); + } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements + safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a + // cursor, but still report that the node is selected + // when asked through getSelection. You'll then get a + // situation where clicking at the point where that + // (hidden) cursor is doesn't change the selection, and + // thus doesn't get a reaction from ProseMirror. This + // works around that. + chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) { + updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos))); + event.preventDefault(); + } else { + setSelectionOrigin(this.view, "pointer"); + } + } + move(event) { + this.updateAllowDefault(event); + setSelectionOrigin(this.view, "pointer"); + if (event.buttons == 0) + this.done(); + } + updateAllowDefault(event) { + if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) + this.allowDefault = true; + } +} +handlers.touchstart = (view) => { + view.input.lastTouch = Date.now(); + forceDOMFlush(view); + setSelectionOrigin(view, "pointer"); +}; +handlers.touchmove = (view) => { + view.input.lastTouch = Date.now(); + setSelectionOrigin(view, "pointer"); +}; +handlers.contextmenu = (view) => forceDOMFlush(view); +function inOrNearComposition(view, event) { + if (view.composing) + return true; + if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) { + view.input.compositionEndedAt = -2e8; + return true; + } + return false; +} +const timeoutComposition = android ? 5e3 : -1; +editHandlers.compositionstart = editHandlers.compositionupdate = (view) => { + if (!view.composing) { + view.domObserver.flush(); + let { state } = view, $pos = state.selection.$to; + if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows$1 && selectionBeforeUneditable(view))) { + view.markCursor = view.state.storedMarks || $pos.marks(); + endComposition(view, true); + view.markCursor = null; + } else { + endComposition(view, !state.selection.empty); + if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { + let sel = view.domSelectionRange(); + for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) { + let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; + if (!before) + break; + if (before.nodeType == 3) { + let sel2 = view.domSelection(); + if (sel2) + sel2.collapse(before, before.nodeValue.length); + break; + } else { + node = before; + offset = -1; + } + } + } + } + view.input.composing = true; + } + scheduleComposeEnd(view, timeoutComposition); +}; +function selectionBeforeUneditable(view) { + let { focusNode, focusOffset } = view.domSelectionRange(); + if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length) + return false; + let next = focusNode.childNodes[focusOffset]; + return next.nodeType == 1 && next.contentEditable == "false"; +} +editHandlers.compositionend = (view, event) => { + if (view.composing) { + view.input.composing = false; + view.input.compositionEndedAt = event.timeStamp; + view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0; + view.input.compositionNode = null; + if (view.input.badSafariComposition) + view.domObserver.forceFlush(); + else if (view.input.compositionPendingChanges) + Promise.resolve().then(() => view.domObserver.flush()); + view.input.compositionID++; + scheduleComposeEnd(view, 20); + } +}; +function scheduleComposeEnd(view, delay) { + clearTimeout(view.input.composingTimeout); + if (delay > -1) + view.input.composingTimeout = setTimeout(() => endComposition(view), delay); +} +function clearComposition(view) { + if (view.composing) { + view.input.composing = false; + view.input.compositionEndedAt = timestampFromCustomEvent(); + } + while (view.input.compositionNodes.length > 0) + view.input.compositionNodes.pop().markParentsDirty(); +} +function findCompositionNode(view) { + let sel = view.domSelectionRange(); + if (!sel.focusNode) + return null; + let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset); + let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset); + if (textBefore && textAfter && textBefore != textAfter) { + let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode; + if (textBefore == lastChanged || textAfter == lastChanged) + return lastChanged; + if (!descAfter || !descAfter.isText(textAfter.nodeValue)) { + return textAfter; + } else if (view.input.compositionNode == textAfter) { + let descBefore = textBefore.pmViewDesc; + if (!(!descBefore || !descBefore.isText(textBefore.nodeValue))) + return textAfter; + } + } + return textBefore || textAfter; +} +function timestampFromCustomEvent() { + let event = document.createEvent("Event"); + event.initEvent("event", true, true); + return event.timeStamp; +} +function endComposition(view, restarting = false) { + if (android && view.domObserver.flushingSoon >= 0) + return; + view.domObserver.forceFlush(); + clearComposition(view); + if (restarting || view.docView && view.docView.dirty) { + let sel = selectionFromDOM(view), cur = view.state.selection; + if (sel && !sel.eq(cur)) + view.dispatch(view.state.tr.setSelection(sel)); + else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent) + view.dispatch(view.state.tr.deleteSelection()); + else + view.updateState(view.state); + return true; + } + return false; +} +function captureCopy(view, dom) { + if (!view.dom.parentNode) + return; + let wrap2 = view.dom.parentNode.appendChild(document.createElement("div")); + wrap2.appendChild(dom); + wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px"; + let sel = getSelection(), range = document.createRange(); + range.selectNodeContents(dom); + view.dom.blur(); + sel.removeAllRanges(); + sel.addRange(range); + setTimeout(() => { + if (wrap2.parentNode) + wrap2.parentNode.removeChild(wrap2); + view.focus(); + }, 50); +} +const brokenClipboardAPI = ie$1 && ie_version < 15 || ios && webkit_version < 604; +handlers.copy = editHandlers.cut = (view, _event) => { + let event = _event; + let sel = view.state.selection, cut2 = event.type == "cut"; + if (sel.empty) + return; + let data = brokenClipboardAPI ? null : event.clipboardData; + let slice2 = sel.content(), { dom, text } = serializeForClipboard(view, slice2); + if (data) { + event.preventDefault(); + data.clearData(); + data.setData("text/html", dom.innerHTML); + data.setData("text/plain", text); + } else { + captureCopy(view, dom); + } + if (cut2) + view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); +}; +function sliceSingleNode(slice2) { + return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null; +} +function capturePaste(view, event) { + if (!view.dom.parentNode) + return; + let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code; + let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); + if (!plainText) + target.contentEditable = "true"; + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + let plain = view.input.shiftKey && view.input.lastKeyCode != 45; + setTimeout(() => { + view.focus(); + if (target.parentNode) + target.parentNode.removeChild(target); + if (plainText) + doPaste(view, target.value, null, plain, event); + else + doPaste(view, target.textContent, target.innerHTML, plain, event); + }, 50); +} +function doPaste(view, text, html, preferPlain, event) { + let slice2 = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from); + if (view.someProp("handlePaste", (f) => f(view, event, slice2 || Slice.empty))) + return true; + if (!slice2) + return false; + let singleNode = sliceSingleNode(slice2); + let tr2 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2); + view.dispatch(tr2.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); + return true; +} +function getText$1(clipboardData) { + let text = clipboardData.getData("text/plain") || clipboardData.getData("Text"); + if (text) + return text; + let uris = clipboardData.getData("text/uri-list"); + return uris ? uris.replace(/\r?\n/g, " ") : ""; +} +editHandlers.paste = (view, _event) => { + let event = _event; + if (view.composing && !android) + return; + let data = brokenClipboardAPI ? null : event.clipboardData; + let plain = view.input.shiftKey && view.input.lastKeyCode != 45; + if (data && doPaste(view, getText$1(data), data.getData("text/html"), plain, event)) + event.preventDefault(); + else + capturePaste(view, event); +}; +class Dragging { + constructor(slice2, move, node) { + this.slice = slice2; + this.move = move; + this.node = node; + } +} +const dragCopyModifier = mac$2 ? "altKey" : "ctrlKey"; +function dragMoves(view, event) { + let copy2; + view.someProp("dragCopies", (test) => { + copy2 = copy2 || test(event); + }); + return copy2 != null ? !copy2 : !event[dragCopyModifier]; +} +handlers.dragstart = (view, _event) => { + let event = _event; + let mouseDown = view.input.mouseDown; + if (mouseDown) + mouseDown.done(); + if (!event.dataTransfer) + return; + let sel = view.state.selection; + let pos = sel.empty ? null : view.posAtCoords(eventCoords(event)); + let node; + if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ; + else if (mouseDown && mouseDown.mightDrag) { + node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos); + } else if (event.target && event.target.nodeType == 1) { + let desc = view.docView.nearestDesc(event.target, true); + if (desc && desc.node.type.spec.draggable && desc != view.docView) + node = NodeSelection.create(view.state.doc, desc.posBefore); + } + let draggedSlice = (node || view.state.selection).content(); + let { dom, text, slice: slice2 } = serializeForClipboard(view, draggedSlice); + if (!event.dataTransfer.files.length || !chrome || chrome_version > 120) + event.dataTransfer.clearData(); + event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); + event.dataTransfer.effectAllowed = "copyMove"; + if (!brokenClipboardAPI) + event.dataTransfer.setData("text/plain", text); + view.dragging = new Dragging(slice2, dragMoves(view, event), node); +}; +handlers.dragend = (view) => { + let dragging = view.dragging; + window.setTimeout(() => { + if (view.dragging == dragging) + view.dragging = null; + }, 50); +}; +editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault(); +editHandlers.drop = (view, event) => { + try { + handleDrop(view, event, view.dragging); + } finally { + view.dragging = null; + } +}; +function handleDrop(view, event, dragging) { + if (!event.dataTransfer) + return; + let eventPos = view.posAtCoords(eventCoords(event)); + if (!eventPos) + return; + let $mouse = view.state.doc.resolve(eventPos.pos); + let slice2 = dragging && dragging.slice; + if (slice2) { + view.someProp("transformPasted", (f) => { + slice2 = f(slice2, view, false); + }); + } else { + slice2 = parseFromClipboard(view, getText$1(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse); + } + let move = !!(dragging && dragMoves(view, event)); + if (view.someProp("handleDrop", (f) => f(view, event, slice2 || Slice.empty, move))) { + event.preventDefault(); + return; + } + if (!slice2) + return; + event.preventDefault(); + let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos; + if (insertPos == null) + insertPos = $mouse.pos; + let tr2 = view.state.tr; + if (move) { + let { node } = dragging; + if (node) + node.replace(tr2); + else + tr2.deleteSelection(); + } + let pos = tr2.mapping.map(insertPos); + let isNode = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1; + let beforeInsert = tr2.doc; + if (isNode) + tr2.replaceRangeWith(pos, pos, slice2.content.firstChild); + else + tr2.replaceRange(pos, pos, slice2); + if (tr2.doc.eq(beforeInsert)) + return; + let $pos = tr2.doc.resolve(pos); + if (isNode && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) { + tr2.setSelection(new NodeSelection($pos)); + } else { + let end = tr2.mapping.map(insertPos); + tr2.mapping.maps[tr2.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo); + tr2.setSelection(selectionBetween(view, $pos, tr2.doc.resolve(end))); + } + view.focus(); + view.dispatch(tr2.setMeta("uiEvent", "drop")); +} +handlers.focus = (view) => { + view.input.lastFocus = Date.now(); + if (!view.focused) { + view.domObserver.stop(); + view.dom.classList.add("ProseMirror-focused"); + view.domObserver.start(); + view.focused = true; + setTimeout(() => { + if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange())) + selectionToDOM(view); + }, 20); + } +}; +handlers.blur = (view, _event) => { + let event = _event; + if (view.focused) { + view.domObserver.stop(); + view.dom.classList.remove("ProseMirror-focused"); + view.domObserver.start(); + if (event.relatedTarget && view.dom.contains(event.relatedTarget)) + view.domObserver.currentSelection.clear(); + view.focused = false; + } +}; +handlers.beforeinput = (view, _event) => { + let event = _event; + if (chrome && android && event.inputType == "deleteContentBackward") { + view.domObserver.flushSoon(); + let { domChangeCount } = view.input; + setTimeout(() => { + if (view.input.domChangeCount != domChangeCount) + return; + view.dom.blur(); + view.focus(); + if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) + return; + let { $cursor } = view.state.selection; + if ($cursor && $cursor.pos > 0) + view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); + }, 50); + } +}; +for (let prop in editHandlers) + handlers[prop] = editHandlers[prop]; +function compareObjs(a, b) { + if (a == b) + return true; + for (let p in a) + if (a[p] !== b[p]) + return false; + for (let p in b) + if (!(p in a)) + return false; + return true; +} +class WidgetType { + constructor(toDOM, spec) { + this.toDOM = toDOM; + this.spec = spec || noSpec; + this.side = this.spec.side || 0; + } + map(mapping, span, offset, oldOffset) { + let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); + return deleted ? null : new Decoration(pos - offset, pos - offset, this); + } + valid() { + return true; + } + eq(other) { + return this == other || other instanceof WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)); + } + destroy(node) { + if (this.spec.destroy) + this.spec.destroy(node); + } +} +class InlineType { + constructor(attrs, spec) { + this.attrs = attrs; + this.spec = spec || noSpec; + } + map(mapping, span, offset, oldOffset) { + let from2 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; + let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; + return from2 >= to ? null : new Decoration(from2, to, this); + } + valid(_, span) { + return span.from < span.to; + } + eq(other) { + return this == other || other instanceof InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); + } + static is(span) { + return span.type instanceof InlineType; + } + destroy() { + } +} +class NodeType2 { + constructor(attrs, spec) { + this.attrs = attrs; + this.spec = spec || noSpec; + } + map(mapping, span, offset, oldOffset) { + let from2 = mapping.mapResult(span.from + oldOffset, 1); + if (from2.deleted) + return null; + let to = mapping.mapResult(span.to + oldOffset, -1); + if (to.deleted || to.pos <= from2.pos) + return null; + return new Decoration(from2.pos - offset, to.pos - offset, this); + } + valid(node, span) { + let { index, offset } = node.content.findIndex(span.from), child; + return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to; + } + eq(other) { + return this == other || other instanceof NodeType2 && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); + } + destroy() { + } +} +class Decoration { + /** + @internal + */ + constructor(from2, to, type) { + this.from = from2; + this.to = to; + this.type = type; + } + /** + @internal + */ + copy(from2, to) { + return new Decoration(from2, to, this.type); + } + /** + @internal + */ + eq(other, offset = 0) { + return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to; + } + /** + @internal + */ + map(mapping, offset, oldOffset) { + return this.type.map(mapping, this, offset, oldOffset); + } + /** + Creates a widget decoration, which is a DOM node that's shown in + the document at the given position. It is recommended that you + delay rendering the widget by passing a function that will be + called when the widget is actually drawn in a view, but you can + also directly pass a DOM node. `getPos` can be used to find the + widget's current document position. + */ + static widget(pos, toDOM, spec) { + return new Decoration(pos, pos, new WidgetType(toDOM, spec)); + } + /** + Creates an inline decoration, which adds the given attributes to + each inline node between `from` and `to`. + */ + static inline(from2, to, attrs, spec) { + return new Decoration(from2, to, new InlineType(attrs, spec)); + } + /** + Creates a node decoration. `from` and `to` should point precisely + before and after a node in the document. That node, and only that + node, will receive the given attributes. + */ + static node(from2, to, attrs, spec) { + return new Decoration(from2, to, new NodeType2(attrs, spec)); + } + /** + The spec provided when creating this decoration. Can be useful + if you've stored extra information in that object. + */ + get spec() { + return this.type.spec; + } + /** + @internal + */ + get inline() { + return this.type instanceof InlineType; + } + /** + @internal + */ + get widget() { + return this.type instanceof WidgetType; + } +} +const none = [], noSpec = {}; +class DecorationSet { + /** + @internal + */ + constructor(local, children) { + this.local = local.length ? local : none; + this.children = children.length ? children : none; + } + /** + Create a set of decorations, using the structure of the given + document. This will consume (modify) the `decorations` array, so + you must make a copy if you want need to preserve that. + */ + static create(doc2, decorations) { + return decorations.length ? buildTree(decorations, doc2, 0, noSpec) : empty; + } + /** + Find all decorations in this set which touch the given range + (including decorations that start or end directly at the + boundaries) and match the given predicate on their spec. When + `start` and `end` are omitted, all decorations in the set are + considered. When `predicate` isn't given, all decorations are + assumed to match. + */ + find(start, end, predicate) { + let result = []; + this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); + return result; + } + findInner(start, end, result, offset, predicate) { + for (let i = 0; i < this.local.length; i++) { + let span = this.local[i]; + if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) + result.push(span.copy(span.from + offset, span.to + offset)); + } + for (let i = 0; i < this.children.length; i += 3) { + if (this.children[i] < end && this.children[i + 1] > start) { + let childOff = this.children[i] + 1; + this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); + } + } + } + /** + Map the set of decorations in response to a change in the + document. + */ + map(mapping, doc2, options) { + if (this == empty || mapping.maps.length == 0) + return this; + return this.mapInner(mapping, doc2, 0, 0, options || noSpec); + } + /** + @internal + */ + mapInner(mapping, node, offset, oldOffset, options) { + let newLocal; + for (let i = 0; i < this.local.length; i++) { + let mapped = this.local[i].map(mapping, offset, oldOffset); + if (mapped && mapped.type.valid(node, mapped)) + (newLocal || (newLocal = [])).push(mapped); + else if (options.onRemove) + options.onRemove(this.local[i].spec); + } + if (this.children.length) + return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options); + else + return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty; + } + /** + Add the given array of decorations to the ones in the set, + producing a new set. Consumes the `decorations` array. Needs + access to the current document to create the appropriate tree + structure. + */ + add(doc2, decorations) { + if (!decorations.length) + return this; + if (this == empty) + return DecorationSet.create(doc2, decorations); + return this.addInner(doc2, decorations, 0); + } + addInner(doc2, decorations, offset) { + let children, childIndex = 0; + doc2.forEach((childNode, childOffset) => { + let baseOffset = childOffset + offset, found2; + if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset))) + return; + if (!children) + children = this.children.slice(); + while (childIndex < children.length && children[childIndex] < childOffset) + childIndex += 3; + if (children[childIndex] == childOffset) + children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1); + else + children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec)); + childIndex += 3; + }); + let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); + for (let i = 0; i < local.length; i++) + if (!local[i].type.valid(doc2, local[i])) + local.splice(i--, 1); + return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children); + } + /** + Create a new set that contains the decorations in this set, minus + the ones in the given array. + */ + remove(decorations) { + if (decorations.length == 0 || this == empty) + return this; + return this.removeInner(decorations, 0); + } + removeInner(decorations, offset) { + let children = this.children, local = this.local; + for (let i = 0; i < children.length; i += 3) { + let found2; + let from2 = children[i] + offset, to = children[i + 1] + offset; + for (let j = 0, span; j < decorations.length; j++) + if (span = decorations[j]) { + if (span.from > from2 && span.to < to) { + decorations[j] = null; + (found2 || (found2 = [])).push(span); + } + } + if (!found2) + continue; + if (children == this.children) + children = this.children.slice(); + let removed = children[i + 2].removeInner(found2, from2 + 1); + if (removed != empty) { + children[i + 2] = removed; + } else { + children.splice(i, 3); + i -= 3; + } + } + if (local.length) { + for (let i = 0, span; i < decorations.length; i++) + if (span = decorations[i]) { + for (let j = 0; j < local.length; j++) + if (local[j].eq(span, offset)) { + if (local == this.local) + local = this.local.slice(); + local.splice(j--, 1); + } + } + } + if (children == this.children && local == this.local) + return this; + return local.length || children.length ? new DecorationSet(local, children) : empty; + } + forChild(offset, node) { + if (this == empty) + return this; + if (node.isLeaf) + return DecorationSet.empty; + let child, local; + for (let i = 0; i < this.children.length; i += 3) + if (this.children[i] >= offset) { + if (this.children[i] == offset) + child = this.children[i + 2]; + break; + } + let start = offset + 1, end = start + node.content.size; + for (let i = 0; i < this.local.length; i++) { + let dec = this.local[i]; + if (dec.from < end && dec.to > start && dec.type instanceof InlineType) { + let from2 = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; + if (from2 < to) + (local || (local = [])).push(dec.copy(from2, to)); + } + } + if (local) { + let localSet = new DecorationSet(local.sort(byPos), none); + return child ? new DecorationGroup([localSet, child]) : localSet; + } + return child || empty; + } + /** + @internal + */ + eq(other) { + if (this == other) + return true; + if (!(other instanceof DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) + return false; + for (let i = 0; i < this.local.length; i++) + if (!this.local[i].eq(other.local[i])) + return false; + for (let i = 0; i < this.children.length; i += 3) + if (this.children[i] != other.children[i] || this.children[i + 1] != other.children[i + 1] || !this.children[i + 2].eq(other.children[i + 2])) + return false; + return true; + } + /** + @internal + */ + locals(node) { + return removeOverlap(this.localsInner(node)); + } + /** + @internal + */ + localsInner(node) { + if (this == empty) + return none; + if (node.inlineContent || !this.local.some(InlineType.is)) + return this.local; + let result = []; + for (let i = 0; i < this.local.length; i++) { + if (!(this.local[i].type instanceof InlineType)) + result.push(this.local[i]); + } + return result; + } + forEachSet(f) { + f(this); + } +} +DecorationSet.empty = new DecorationSet([], []); +DecorationSet.removeOverlap = removeOverlap; +const empty = DecorationSet.empty; +class DecorationGroup { + constructor(members) { + this.members = members; + } + map(mapping, doc2) { + const mappedDecos = this.members.map((member) => member.map(mapping, doc2, noSpec)); + return DecorationGroup.from(mappedDecos); + } + forChild(offset, child) { + if (child.isLeaf) + return DecorationSet.empty; + let found2 = []; + for (let i = 0; i < this.members.length; i++) { + let result = this.members[i].forChild(offset, child); + if (result == empty) + continue; + if (result instanceof DecorationGroup) + found2 = found2.concat(result.members); + else + found2.push(result); + } + return DecorationGroup.from(found2); + } + eq(other) { + if (!(other instanceof DecorationGroup) || other.members.length != this.members.length) + return false; + for (let i = 0; i < this.members.length; i++) + if (!this.members[i].eq(other.members[i])) + return false; + return true; + } + locals(node) { + let result, sorted = true; + for (let i = 0; i < this.members.length; i++) { + let locals = this.members[i].localsInner(node); + if (!locals.length) + continue; + if (!result) { + result = locals; + } else { + if (sorted) { + result = result.slice(); + sorted = false; + } + for (let j = 0; j < locals.length; j++) + result.push(locals[j]); + } + } + return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none; + } + // Create a group for the given array of decoration sets, or return + // a single set when possible. + static from(members) { + switch (members.length) { + case 0: + return empty; + case 1: + return members[0]; + default: + return new DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), [])); + } + } + forEachSet(f) { + for (let i = 0; i < this.members.length; i++) + this.members[i].forEachSet(f); + } +} +function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { + let children = oldChildren.slice(); + for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) { + let moved = 0; + mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => { + let dSize = newEnd - newStart - (oldEnd - oldStart); + for (let i2 = 0; i2 < children.length; i2 += 3) { + let end = children[i2 + 1]; + if (end < 0 || oldStart > end + baseOffset - moved) + continue; + let start = children[i2] + baseOffset - moved; + if (oldEnd >= start) { + children[i2 + 1] = oldStart <= start ? -2 : -1; + } else if (oldStart >= baseOffset && dSize) { + children[i2] += dSize; + children[i2 + 1] += dSize; + } + } + moved += dSize; + }); + baseOffset = mapping.maps[i].map(baseOffset, -1); + } + let mustRebuild = false; + for (let i = 0; i < children.length; i += 3) + if (children[i + 1] < 0) { + if (children[i + 1] == -2) { + mustRebuild = true; + children[i + 1] = -1; + continue; + } + let from2 = mapping.map(oldChildren[i] + oldOffset), fromLocal = from2 - offset; + if (fromLocal < 0 || fromLocal >= node.content.size) { + mustRebuild = true; + continue; + } + let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset; + let { index, offset: childOffset } = node.content.findIndex(fromLocal); + let childNode = node.maybeChild(index); + if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { + let mapped = children[i + 2].mapInner(mapping, childNode, from2 + 1, oldChildren[i] + oldOffset + 1, options); + if (mapped != empty) { + children[i] = fromLocal; + children[i + 1] = toLocal; + children[i + 2] = mapped; + } else { + children[i + 1] = -2; + mustRebuild = true; + } + } else { + mustRebuild = true; + } + } + if (mustRebuild) { + let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options); + let built = buildTree(decorations, node, 0, options); + newLocal = built.local; + for (let i = 0; i < children.length; i += 3) + if (children[i + 1] < 0) { + children.splice(i, 3); + i -= 3; + } + for (let i = 0, j = 0; i < built.children.length; i += 3) { + let from2 = built.children[i]; + while (j < children.length && children[j] < from2) + j += 3; + children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]); + } + } + return new DecorationSet(newLocal.sort(byPos), children); +} +function moveSpans(spans, offset) { + if (!offset || !spans.length) + return spans; + let result = []; + for (let i = 0; i < spans.length; i++) { + let span = spans[i]; + result.push(new Decoration(span.from + offset, span.to + offset, span.type)); + } + return result; +} +function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { + function gather(set, oldOffset2) { + for (let i = 0; i < set.local.length; i++) { + let mapped = set.local[i].map(mapping, offset, oldOffset2); + if (mapped) + decorations.push(mapped); + else if (options.onRemove) + options.onRemove(set.local[i].spec); + } + for (let i = 0; i < set.children.length; i += 3) + gather(set.children[i + 2], set.children[i] + oldOffset2 + 1); + } + for (let i = 0; i < children.length; i += 3) + if (children[i + 1] == -1) + gather(children[i + 2], oldChildren[i] + oldOffset + 1); + return decorations; +} +function takeSpansForNode(spans, node, offset) { + if (node.isLeaf) + return null; + let end = offset + node.nodeSize, found2 = null; + for (let i = 0, span; i < spans.length; i++) { + if ((span = spans[i]) && span.from > offset && span.to < end) { + (found2 || (found2 = [])).push(span); + spans[i] = null; + } + } + return found2; +} +function withoutNulls(array) { + let result = []; + for (let i = 0; i < array.length; i++) + if (array[i] != null) + result.push(array[i]); + return result; +} +function buildTree(spans, node, offset, options) { + let children = [], hasNulls = false; + node.forEach((childNode, localStart) => { + let found2 = takeSpansForNode(spans, childNode, localStart + offset); + if (found2) { + hasNulls = true; + let subtree = buildTree(found2, childNode, offset + localStart + 1, options); + if (subtree != empty) + children.push(localStart, localStart + childNode.nodeSize, subtree); + } + }); + let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); + for (let i = 0; i < locals.length; i++) + if (!locals[i].type.valid(node, locals[i])) { + if (options.onRemove) + options.onRemove(locals[i].spec); + locals.splice(i--, 1); + } + return locals.length || children.length ? new DecorationSet(locals, children) : empty; +} +function byPos(a, b) { + return a.from - b.from || a.to - b.to; +} +function removeOverlap(spans) { + let working = spans; + for (let i = 0; i < working.length - 1; i++) { + let span = working[i]; + if (span.from != span.to) + for (let j = i + 1; j < working.length; j++) { + let next = working[j]; + if (next.from == span.from) { + if (next.to != span.to) { + if (working == spans) + working = spans.slice(); + working[j] = next.copy(next.from, span.to); + insertAhead(working, j + 1, next.copy(span.to, next.to)); + } + continue; + } else { + if (next.from < span.to) { + if (working == spans) + working = spans.slice(); + working[i] = span.copy(span.from, next.from); + insertAhead(working, j, span.copy(next.from, span.to)); + } + break; + } + } + } + return working; +} +function insertAhead(array, i, deco) { + while (i < array.length && byPos(deco, array[i]) > 0) + i++; + array.splice(i, 0, deco); +} +function viewDecorations(view) { + let found2 = []; + view.someProp("decorations", (f) => { + let result = f(view.state); + if (result && result != empty) + found2.push(result); + }); + if (view.cursorWrapper) + found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); + return DecorationGroup.from(found2); +} +const observeOptions = { + childList: true, + characterData: true, + characterDataOldValue: true, + attributes: true, + attributeOldValue: true, + subtree: true +}; +const useCharData = ie$1 && ie_version <= 11; +class SelectionState { + constructor() { + this.anchorNode = null; + this.anchorOffset = 0; + this.focusNode = null; + this.focusOffset = 0; + } + set(sel) { + this.anchorNode = sel.anchorNode; + this.anchorOffset = sel.anchorOffset; + this.focusNode = sel.focusNode; + this.focusOffset = sel.focusOffset; + } + clear() { + this.anchorNode = this.focusNode = null; + } + eq(sel) { + return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset; + } +} +class DOMObserver { + constructor(view, handleDOMChange) { + this.view = view; + this.handleDOMChange = handleDOMChange; + this.queue = []; + this.flushingSoon = -1; + this.observer = null; + this.currentSelection = new SelectionState(); + this.onCharData = null; + this.suppressingSelectionUpdates = false; + this.lastChangedTextNode = null; + this.observer = window.MutationObserver && new window.MutationObserver((mutations) => { + for (let i = 0; i < mutations.length; i++) + this.queue.push(mutations[i]); + if (ie$1 && ie_version <= 11 && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) { + this.flushSoon(); + } else if (safari && view.composing && mutations.some((m) => m.type == "childList" && m.target.nodeName == "TR")) { + view.input.badSafariComposition = true; + this.flushSoon(); + } else { + this.flush(); + } + }); + if (useCharData) { + this.onCharData = (e) => { + this.queue.push({ target: e.target, type: "characterData", oldValue: e.prevValue }); + this.flushSoon(); + }; + } + this.onSelectionChange = this.onSelectionChange.bind(this); + } + flushSoon() { + if (this.flushingSoon < 0) + this.flushingSoon = window.setTimeout(() => { + this.flushingSoon = -1; + this.flush(); + }, 20); + } + forceFlush() { + if (this.flushingSoon > -1) { + window.clearTimeout(this.flushingSoon); + this.flushingSoon = -1; + this.flush(); + } + } + start() { + if (this.observer) { + this.observer.takeRecords(); + this.observer.observe(this.view.dom, observeOptions); + } + if (this.onCharData) + this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); + this.connectSelection(); + } + stop() { + if (this.observer) { + let take = this.observer.takeRecords(); + if (take.length) { + for (let i = 0; i < take.length; i++) + this.queue.push(take[i]); + window.setTimeout(() => this.flush(), 20); + } + this.observer.disconnect(); + } + if (this.onCharData) + this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); + this.disconnectSelection(); + } + connectSelection() { + this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); + } + disconnectSelection() { + this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); + } + suppressSelectionUpdates() { + this.suppressingSelectionUpdates = true; + setTimeout(() => this.suppressingSelectionUpdates = false, 50); + } + onSelectionChange() { + if (!hasFocusAndSelection(this.view)) + return; + if (this.suppressingSelectionUpdates) + return selectionToDOM(this.view); + if (ie$1 && ie_version <= 11 && !this.view.state.selection.empty) { + let sel = this.view.domSelectionRange(); + if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + return this.flushSoon(); + } + this.flush(); + } + setCurSelection() { + this.currentSelection.set(this.view.domSelectionRange()); + } + ignoreSelectionChange(sel) { + if (!sel.focusNode) + return true; + let ancestors = /* @__PURE__ */ new Set(), container; + for (let scan = sel.focusNode; scan; scan = parentNode(scan)) + ancestors.add(scan); + for (let scan = sel.anchorNode; scan; scan = parentNode(scan)) + if (ancestors.has(scan)) { + container = scan; + break; + } + let desc = container && this.view.docView.nearestDesc(container); + if (desc && desc.ignoreMutation({ + type: "selection", + target: container.nodeType == 3 ? container.parentNode : container + })) { + this.setCurSelection(); + return true; + } + } + pendingRecords() { + if (this.observer) + for (let mut of this.observer.takeRecords()) + this.queue.push(mut); + return this.queue; + } + flush() { + let { view } = this; + if (!view.docView || this.flushingSoon > -1) + return; + let mutations = this.pendingRecords(); + if (mutations.length) + this.queue = []; + let sel = view.domSelectionRange(); + let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel); + let from2 = -1, to = -1, typeOver = false, added = []; + if (view.editable) { + for (let i = 0; i < mutations.length; i++) { + let result = this.registerMutation(mutations[i], added); + if (result) { + from2 = from2 < 0 ? result.from : Math.min(result.from, from2); + to = to < 0 ? result.to : Math.max(result.to, to); + if (result.typeOver) + typeOver = true; + } + } + } + if (added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) { + for (let node of added) + if (node.nodeName == "BR" && node.parentNode) { + let after = node.nextSibling; + while (after && after.nodeType == 1) { + if (after.contentEditable == "false") { + node.parentNode.removeChild(node); + break; + } + after = after.firstChild; + } + } + } else if (gecko && added.length) { + let brs = added.filter((n) => n.nodeName == "BR"); + if (brs.length == 2) { + let [a, b] = brs; + if (a.parentNode && a.parentNode.parentNode == b.parentNode) + b.remove(); + else + a.remove(); + } else { + let { focusNode } = this.currentSelection; + for (let br of brs) { + let parent = br.parentNode; + if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent)) + br.remove(); + } + } + } + let readSel = null; + if (from2 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) { + view.input.lastFocus = 0; + selectionToDOM(view); + this.currentSelection.set(sel); + view.scrollToSelection(); + } else if (from2 > -1 || newSel) { + if (from2 > -1) { + view.docView.markDirty(from2, to); + checkCSS(view); + } + if (view.input.badSafariComposition) { + view.input.badSafariComposition = false; + fixUpBadSafariComposition(view, added); + } + this.handleDOMChange(from2, to, typeOver, added); + if (view.docView && view.docView.dirty) + view.updateState(view.state); + else if (!this.currentSelection.eq(sel)) + selectionToDOM(view); + this.currentSelection.set(sel); + } + } + registerMutation(mut, added) { + if (added.indexOf(mut.target) > -1) + return null; + let desc = this.view.docView.nearestDesc(mut.target); + if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles + mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style"))) + return null; + if (!desc || desc.ignoreMutation(mut)) + return null; + if (mut.type == "childList") { + for (let i = 0; i < mut.addedNodes.length; i++) { + let node = mut.addedNodes[i]; + added.push(node); + if (node.nodeType == 3) + this.lastChangedTextNode = node; + } + if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target)) + return { from: desc.posBefore, to: desc.posAfter }; + let prev = mut.previousSibling, next = mut.nextSibling; + if (ie$1 && ie_version <= 11 && mut.addedNodes.length) { + for (let i = 0; i < mut.addedNodes.length; i++) { + let { previousSibling, nextSibling } = mut.addedNodes[i]; + if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) + prev = previousSibling; + if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) + next = nextSibling; + } + } + let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0; + let from2 = desc.localPosFromDOM(mut.target, fromOffset, -1); + let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length; + let to = desc.localPosFromDOM(mut.target, toOffset, 1); + return { from: from2, to }; + } else if (mut.type == "attributes") { + return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border }; + } else { + this.lastChangedTextNode = mut.target; + return { + from: desc.posAtStart, + to: desc.posAtEnd, + // An event was generated for a text change that didn't change + // any text. Mark the dom change to fall back to assuming the + // selection was typed over with an identical value if it can't + // find another change. + typeOver: mut.target.nodeValue == mut.oldValue + }; + } + } +} +let cssChecked = /* @__PURE__ */ new WeakMap(); +let cssCheckWarned = false; +function checkCSS(view) { + if (cssChecked.has(view)) + return; + cssChecked.set(view, null); + if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) { + view.requiresGeckoHackNode = gecko; + if (cssCheckWarned) + return; + console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); + cssCheckWarned = true; + } +} +function rangeToSelectionRange(view, range) { + let anchorNode = range.startContainer, anchorOffset = range.startOffset; + let focusNode = range.endContainer, focusOffset = range.endOffset; + let currentAnchor = view.domAtPos(view.state.selection.anchor); + if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset)) + [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; + return { anchorNode, anchorOffset, focusNode, focusOffset }; +} +function safariShadowSelectionRange(view, selection) { + if (selection.getComposedRanges) { + let range = selection.getComposedRanges(view.root)[0]; + if (range) + return rangeToSelectionRange(view, range); + } + let found2; + function read(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + found2 = event.getTargetRanges()[0]; + } + view.dom.addEventListener("beforeinput", read, true); + document.execCommand("indent"); + view.dom.removeEventListener("beforeinput", read, true); + return found2 ? rangeToSelectionRange(view, found2) : null; +} +function blockParent(view, node) { + for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) { + let desc = view.docView.nearestDesc(p, true); + if (desc && desc.node.isBlock) + return p; + } + return null; +} +function fixUpBadSafariComposition(view, addedNodes) { + var _a; + let { focusNode, focusOffset } = view.domSelectionRange(); + for (let node of addedNodes) { + if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == "TR") { + let nextCell = node.nextSibling; + while (nextCell && (nextCell.nodeName != "TD" && nextCell.nodeName != "TH")) + nextCell = nextCell.nextSibling; + if (nextCell) { + let parent = nextCell; + for (; ; ) { + let first2 = parent.firstChild; + if (!first2 || first2.nodeType != 1 || first2.contentEditable == "false" || /^(BR|IMG)$/.test(first2.nodeName)) + break; + parent = first2; + } + parent.insertBefore(node, parent.firstChild); + if (focusNode == node) + view.domSelection().collapse(node, focusOffset); + } else { + node.parentNode.removeChild(node); + } + } + } +} +function parseBetween(view, from_, to_) { + let { node: parent, fromOffset, toOffset, from: from2, to } = view.docView.parseRange(from_, to_); + let domSel = view.domSelectionRange(); + let find2; + let anchor = domSel.anchorNode; + if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { + find2 = [{ node: anchor, offset: domSel.anchorOffset }]; + if (!selectionCollapsed(domSel)) + find2.push({ node: domSel.focusNode, offset: domSel.focusOffset }); + } + if (chrome && view.input.lastKeyCode === 8) { + for (let off = toOffset; off > fromOffset; off--) { + let node = parent.childNodes[off - 1], desc = node.pmViewDesc; + if (node.nodeName == "BR" && !desc) { + toOffset = off; + break; + } + if (!desc || desc.size) + break; + } + } + let startDoc = view.state.doc; + let parser = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); + let $from = startDoc.resolve(from2); + let sel = null, doc2 = parser.parse(parent, { + topNode: $from.parent, + topMatch: $from.parent.contentMatchAt($from.index()), + topOpen: true, + from: fromOffset, + to: toOffset, + preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true, + findPositions: find2, + ruleFromNode, + context: $from + }); + if (find2 && find2[0].pos != null) { + let anchor2 = find2[0].pos, head = find2[1] && find2[1].pos; + if (head == null) + head = anchor2; + sel = { anchor: anchor2 + from2, head: head + from2 }; + } + return { doc: doc2, sel, from: from2, to }; +} +function ruleFromNode(dom) { + let desc = dom.pmViewDesc; + if (desc) { + return desc.parseRule(); + } else if (dom.nodeName == "BR" && dom.parentNode) { + if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { + let skip = document.createElement("div"); + skip.appendChild(document.createElement("li")); + return { skip }; + } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) { + return { ignore: true }; + } + } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) { + return { ignore: true }; + } + return null; +} +const isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i; +function readDOMChange(view, from2, to, typeOver, addedNodes) { + let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0); + view.input.compositionPendingChanges = 0; + if (from2 < 0) { + let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null; + let newSel = selectionFromDOM(view, origin); + if (newSel && !view.state.selection.eq(newSel)) { + if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) + return; + let tr2 = view.state.tr.setSelection(newSel); + if (origin == "pointer") + tr2.setMeta("pointer", true); + else if (origin == "key") + tr2.scrollIntoView(); + if (compositionID) + tr2.setMeta("composition", compositionID); + view.dispatch(tr2); + } + return; + } + let $before = view.state.doc.resolve(from2); + let shared = $before.sharedDepth(to); + from2 = $before.before(shared + 1); + to = view.state.doc.resolve(to).after(shared + 1); + let sel = view.state.selection; + let parse = parseBetween(view, from2, to); + let doc2 = view.state.doc, compare = doc2.slice(parse.from, parse.to); + let preferredPos, preferredSide; + if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) { + preferredPos = view.state.selection.to; + preferredSide = "end"; + } else { + preferredPos = view.state.selection.from; + preferredSide = "start"; + } + view.input.lastKeyCode = null; + let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide); + if (change) + view.input.domChangeCount++; + if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { + view.input.lastIOSEnter = 0; + return; + } + if (!change) { + if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) { + change = { start: sel.from, endA: sel.to, endB: sel.to }; + } else { + if (parse.sel) { + let sel2 = resolveSelection(view, view.state.doc, parse.sel); + if (sel2 && !sel2.eq(view.state.selection)) { + let tr2 = view.state.tr.setSelection(sel2); + if (compositionID) + tr2.setMeta("composition", compositionID); + view.dispatch(tr2); + } + } + return; + } + } + if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) { + if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse.from) { + change.start = view.state.selection.from; + } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse.to) { + change.endB += view.state.selection.to - change.endA; + change.endA = view.state.selection.to; + } + } + if (ie$1 && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == "  ") { + change.start--; + change.endA--; + change.endB--; + } + let $from = parse.doc.resolveNoCache(change.start - parse.from); + let $to = parse.doc.resolveNoCache(change.endB - parse.from); + let $fromA = doc2.resolve(change.start); + let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA; + if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { + view.input.lastIOSEnter = 0; + return; + } + if (view.state.selection.anchor > change.start && looksLikeBackspace(doc2, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) { + if (android && chrome) + view.domObserver.suppressSelectionUpdates(); + return; + } + if (chrome && change.endB == change.start) + view.input.lastChromeDelete = Date.now(); + if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) { + change.endB -= 2; + $to = parse.doc.resolveNoCache(change.endB - parse.from); + setTimeout(() => { + view.someProp("handleKeyDown", function(f) { + return f(view, keyEvent(13, "Enter")); + }); + }, 20); + } + let chFrom = change.start, chTo = change.endA; + let mkTr = (base2) => { + let tr2 = base2 || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); + if (parse.sel) { + let sel2 = resolveSelection(view, tr2.doc, parse.sel); + if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr2.mapping.map(chTo) - 1) || ie$1 && sel2.empty && sel2.head == chFrom)) + tr2.setSelection(sel2); + } + if (compositionID) + tr2.setMeta("composition", compositionID); + return tr2.scrollIntoView(); + }; + let markChange; + if (inlineChange) { + if ($from.pos == $to.pos) { + if (ie$1 && ie_version <= 11 && $from.parentOffset == 0) { + view.domObserver.suppressSelectionUpdates(); + setTimeout(() => selectionToDOM(view), 20); + } + let tr2 = mkTr(view.state.tr.delete(chFrom, chTo)); + let marks = doc2.resolve(change.start).marksAcross(doc2.resolve(change.endA)); + if (marks) + tr2.ensureMarks(marks); + view.dispatch(tr2); + } else if ( + // Adding or removing a mark + change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start()))) + ) { + let tr2 = mkTr(view.state.tr); + if (markChange.type == "add") + tr2.addMark(chFrom, chTo, markChange.mark); + else + tr2.removeMark(chFrom, chTo, markChange.mark); + view.dispatch(tr2); + } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { + let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset); + let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo)); + if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text, deflt))) + view.dispatch(deflt()); + } else { + view.dispatch(mkTr()); + } + } else { + view.dispatch(mkTr()); + } +} +function resolveSelection(view, doc2, parsedSel) { + if (Math.max(parsedSel.anchor, parsedSel.head) > doc2.content.size) + return null; + return selectionBetween(view, doc2.resolve(parsedSel.anchor), doc2.resolve(parsedSel.head)); +} +function isMarkChange(cur, prev) { + let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; + let added = curMarks, removed = prevMarks, type, mark, update; + for (let i = 0; i < prevMarks.length; i++) + added = prevMarks[i].removeFromSet(added); + for (let i = 0; i < curMarks.length; i++) + removed = curMarks[i].removeFromSet(removed); + if (added.length == 1 && removed.length == 0) { + mark = added[0]; + type = "add"; + update = (node) => node.mark(mark.addToSet(node.marks)); + } else if (added.length == 0 && removed.length == 1) { + mark = removed[0]; + type = "remove"; + update = (node) => node.mark(mark.removeFromSet(node.marks)); + } else { + return null; + } + let updated = []; + for (let i = 0; i < prev.childCount; i++) + updated.push(update(prev.child(i))); + if (Fragment.from(updated).eq(cur)) + return { mark, type }; +} +function looksLikeBackspace(old, start, end, $newStart, $newEnd) { + if ( + // The content must have shrunk + end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into + skipClosingAndOpening($newStart, true, false) < $newEnd.pos + ) + return false; + let $start = old.resolve(start); + if (!$newStart.parent.isTextblock) { + let after = $start.nodeAfter; + return after != null && end == start + after.nodeSize; + } + if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) + return false; + let $next = old.resolve(skipClosingAndOpening($start, true, true)); + if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end) + return false; + return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content); +} +function skipClosingAndOpening($pos, fromEnd, mayOpen) { + let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; + while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { + depth--; + end++; + fromEnd = false; + } + if (mayOpen) { + let next = $pos.node(depth).maybeChild($pos.indexAfter(depth)); + while (next && !next.isLeaf) { + next = next.firstChild; + end++; + } + } + return end; +} +function findDiff(a, b, pos, preferredPos, preferredSide) { + let start = a.findDiffStart(b, pos); + if (start == null) + return null; + let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size); + if (preferredSide == "end") { + let adjust = Math.max(0, start - Math.min(endA, endB)); + preferredPos -= endA + adjust - start; + } + if (endA < start && a.size < b.size) { + let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; + start -= move; + if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1))) + start += move ? 1 : -1; + endB = start + (endB - endA); + endA = start; + } else if (endB < start) { + let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; + start -= move; + if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1))) + start += move ? 1 : -1; + endA = start + (endA - endB); + endB = start; + } + return { start, endA, endB }; +} +function isSurrogatePair(str) { + if (str.length != 2) + return false; + let a = str.charCodeAt(0), b = str.charCodeAt(1); + return a >= 56320 && a <= 57343 && b >= 55296 && b <= 56319; +} +class EditorView { + /** + Create a view. `place` may be a DOM node that the editor should + be appended to, a function that will place it into the document, + or an object whose `mount` property holds the node to use as the + document container. If it is `null`, the editor will not be + added to the document. + */ + constructor(place, props) { + this._root = null; + this.focused = false; + this.trackWrites = null; + this.mounted = false; + this.markCursor = null; + this.cursorWrapper = null; + this.lastSelectedViewDesc = void 0; + this.input = new InputState(); + this.prevDirectPlugins = []; + this.pluginViews = []; + this.requiresGeckoHackNode = false; + this.dragging = null; + this._props = props; + this.state = props.state; + this.directPlugins = props.plugins || []; + this.directPlugins.forEach(checkStateComponent); + this.dispatch = this.dispatch.bind(this); + this.dom = place && place.mount || document.createElement("div"); + if (place) { + if (place.appendChild) + place.appendChild(this.dom); + else if (typeof place == "function") + place(this.dom); + else if (place.mount) + this.mounted = true; + } + this.editable = getEditable(this); + updateCursorWrapper(this); + this.nodeViews = buildNodeViews(this); + this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); + this.domObserver = new DOMObserver(this, (from2, to, typeOver, added) => readDOMChange(this, from2, to, typeOver, added)); + this.domObserver.start(); + initInput(this); + this.updatePluginViews(); + } + /** + Holds `true` when a + [composition](https://w3c.github.io/uievents/#events-compositionevents) + is active. + */ + get composing() { + return this.input.composing; + } + /** + The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps). + */ + get props() { + if (this._props.state != this.state) { + let prev = this._props; + this._props = {}; + for (let name in prev) + this._props[name] = prev[name]; + this._props.state = this.state; + } + return this._props; + } + /** + Update the view's props. Will immediately cause an update to + the DOM. + */ + update(props) { + if (props.handleDOMEvents != this._props.handleDOMEvents) + ensureListeners(this); + let prevProps = this._props; + this._props = props; + if (props.plugins) { + props.plugins.forEach(checkStateComponent); + this.directPlugins = props.plugins; + } + this.updateStateInner(props.state, prevProps); + } + /** + Update the view by updating existing props object with the object + given as argument. Equivalent to `view.update(Object.assign({}, + view.props, props))`. + */ + setProps(props) { + let updated = {}; + for (let name in this._props) + updated[name] = this._props[name]; + updated.state = this.state; + for (let name in props) + updated[name] = props[name]; + this.update(updated); + } + /** + Update the editor's `state` prop, without touching any of the + other props. + */ + updateState(state) { + this.updateStateInner(state, this._props); + } + updateStateInner(state, prevProps) { + var _a; + let prev = this.state, redraw = false, updateSel = false; + if (state.storedMarks && this.composing) { + clearComposition(this); + updateSel = true; + } + this.state = state; + let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins; + if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) { + let nodeViews = buildNodeViews(this); + if (changedNodeViews(nodeViews, this.nodeViews)) { + this.nodeViews = nodeViews; + redraw = true; + } + } + if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) { + ensureListeners(this); + } + this.editable = getEditable(this); + updateCursorWrapper(this); + let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); + let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; + let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); + if (updateDoc || !state.selection.eq(prev.selection)) + updateSel = true; + let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); + if (updateSel) { + this.domObserver.stop(); + let forceSelUpdate = updateDoc && (ie$1 || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); + if (updateDoc) { + let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null; + if (this.composing) + this.input.compositionNode = findCompositionNode(this); + if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { + this.docView.updateOuterDeco(outerDeco); + this.docView.destroy(); + this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); + } + if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites))) + forceSelUpdate = true; + } + if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) { + selectionToDOM(this, forceSelUpdate); + } else { + syncNodeSelection(this, state.selection); + this.domObserver.setCurSelection(); + } + this.domObserver.start(); + } + this.updatePluginViews(prev); + if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc)) + this.updateDraggedNode(this.dragging, prev); + if (scroll == "reset") { + this.dom.scrollTop = 0; + } else if (scroll == "to selection") { + this.scrollToSelection(); + } else if (oldScrollPos) { + resetScrollPos(oldScrollPos); + } + } + /** + @internal + */ + scrollToSelection() { + let startDOM = this.domSelectionRange().focusNode; + if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ; + else if (this.someProp("handleScrollToSelection", (f) => f(this))) ; + else if (this.state.selection instanceof NodeSelection) { + let target = this.docView.domAfterPos(this.state.selection.from); + if (target.nodeType == 1) + scrollRectIntoView(this, target.getBoundingClientRect(), startDOM); + } else { + scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM); + } + } + destroyPluginViews() { + let view; + while (view = this.pluginViews.pop()) + if (view.destroy) + view.destroy(); + } + updatePluginViews(prevState) { + if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) { + this.prevDirectPlugins = this.directPlugins; + this.destroyPluginViews(); + for (let i = 0; i < this.directPlugins.length; i++) { + let plugin = this.directPlugins[i]; + if (plugin.spec.view) + this.pluginViews.push(plugin.spec.view(this)); + } + for (let i = 0; i < this.state.plugins.length; i++) { + let plugin = this.state.plugins[i]; + if (plugin.spec.view) + this.pluginViews.push(plugin.spec.view(this)); + } + } else { + for (let i = 0; i < this.pluginViews.length; i++) { + let pluginView = this.pluginViews[i]; + if (pluginView.update) + pluginView.update(this, prevState); + } + } + } + updateDraggedNode(dragging, prev) { + let sel = dragging.node, found2 = -1; + if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) { + found2 = sel.from; + } else { + let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size); + let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos); + if (moved == sel.node) + found2 = movedPos; + } + this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2)); + } + someProp(propName, f) { + let prop = this._props && this._props[propName], value; + if (prop != null && (value = f ? f(prop) : prop)) + return value; + for (let i = 0; i < this.directPlugins.length; i++) { + let prop2 = this.directPlugins[i].props[propName]; + if (prop2 != null && (value = f ? f(prop2) : prop2)) + return value; + } + let plugins = this.state.plugins; + if (plugins) + for (let i = 0; i < plugins.length; i++) { + let prop2 = plugins[i].props[propName]; + if (prop2 != null && (value = f ? f(prop2) : prop2)) + return value; + } + } + /** + Query whether the view has focus. + */ + hasFocus() { + if (ie$1) { + let node = this.root.activeElement; + if (node == this.dom) + return true; + if (!node || !this.dom.contains(node)) + return false; + while (node && this.dom != node && this.dom.contains(node)) { + if (node.contentEditable == "false") + return false; + node = node.parentElement; + } + return true; + } + return this.root.activeElement == this.dom; + } + /** + Focus the editor. + */ + focus() { + this.domObserver.stop(); + if (this.editable) + focusPreventScroll(this.dom); + selectionToDOM(this); + this.domObserver.start(); + } + /** + Get the document root in which the editor exists. This will + usually be the top-level `document`, but might be a [shadow + DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) + root if the editor is inside one. + */ + get root() { + let cached = this._root; + if (cached == null) + for (let search = this.dom.parentNode; search; search = search.parentNode) { + if (search.nodeType == 9 || search.nodeType == 11 && search.host) { + if (!search.getSelection) + Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection(); + return this._root = search; + } + } + return cached || document; + } + /** + When an existing editor view is moved to a new document or + shadow tree, call this to make it recompute its root. + */ + updateRoot() { + this._root = null; + } + /** + Given a pair of viewport coordinates, return the document + position that corresponds to them. May return null if the given + coordinates aren't inside of the editor. When an object is + returned, its `pos` property is the position nearest to the + coordinates, and its `inside` property holds the position of the + inner node that the position falls inside of, or -1 if it is at + the top level, not in any node. + */ + posAtCoords(coords) { + return posAtCoords(this, coords); + } + /** + Returns the viewport rectangle at a given document position. + `left` and `right` will be the same number, as this returns a + flat cursor-ish rectangle. If the position is between two things + that aren't directly adjacent, `side` determines which element + is used. When < 0, the element before the position is used, + otherwise the element after. + */ + coordsAtPos(pos, side = 1) { + return coordsAtPos(this, pos, side); + } + /** + Find the DOM position that corresponds to the given document + position. When `side` is negative, find the position as close as + possible to the content before the position. When positive, + prefer positions close to the content after the position. When + zero, prefer as shallow a position as possible. + + Note that you should **not** mutate the editor's internal DOM, + only inspect it (and even that is usually not necessary). + */ + domAtPos(pos, side = 0) { + return this.docView.domFromPos(pos, side); + } + /** + Find the DOM node that represents the document node after the + given position. May return `null` when the position doesn't point + in front of a node or if the node is inside an opaque node view. + + This is intended to be able to call things like + `getBoundingClientRect` on that DOM node. Do **not** mutate the + editor DOM directly, or add styling this way, since that will be + immediately overriden by the editor as it redraws the node. + */ + nodeDOM(pos) { + let desc = this.docView.descAt(pos); + return desc ? desc.nodeDOM : null; + } + /** + Find the document position that corresponds to a given DOM + position. (Whenever possible, it is preferable to inspect the + document structure directly, rather than poking around in the + DOM, but sometimes—for example when interpreting an event + target—you don't have a choice.) + + The `bias` parameter can be used to influence which side of a DOM + node to use when the position is inside a leaf node. + */ + posAtDOM(node, offset, bias = -1) { + let pos = this.docView.posFromDOM(node, offset, bias); + if (pos == null) + throw new RangeError("DOM position not inside the editor"); + return pos; + } + /** + Find out whether the selection is at the end of a textblock when + moving in a given direction. When, for example, given `"left"`, + it will return true if moving left from the current cursor + position would leave that position's parent textblock. Will apply + to the view's current state by default, but it is possible to + pass a different state. + */ + endOfTextblock(dir, state) { + return endOfTextblock(this, state || this.state, dir); + } + /** + Run the editor's paste logic with the given HTML string. The + `event`, if given, will be passed to the + [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook. + */ + pasteHTML(html, event) { + return doPaste(this, "", html, false, event || new ClipboardEvent("paste")); + } + /** + Run the editor's paste logic with the given plain-text input. + */ + pasteText(text, event) { + return doPaste(this, text, null, true, event || new ClipboardEvent("paste")); + } + /** + Serialize the given slice as it would be if it was copied from + this editor. Returns a DOM element that contains a + representation of the slice as its children, a textual + representation, and the transformed slice (which can be + different from the given input due to hooks like + [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)). + */ + serializeForClipboard(slice2) { + return serializeForClipboard(this, slice2); + } + /** + Removes the editor from the DOM and destroys all [node + views](https://prosemirror.net/docs/ref/#view.NodeView). + */ + destroy() { + if (!this.docView) + return; + destroyInput(this); + this.destroyPluginViews(); + if (this.mounted) { + this.docView.update(this.state.doc, [], viewDecorations(this), this); + this.dom.textContent = ""; + } else if (this.dom.parentNode) { + this.dom.parentNode.removeChild(this.dom); + } + this.docView.destroy(); + this.docView = null; + clearReusedRange(); + } + /** + This is true when the view has been + [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be + used anymore). + */ + get isDestroyed() { + return this.docView == null; + } + /** + Used for testing. + */ + dispatchEvent(event) { + return dispatchEvent(this, event); + } + /** + @internal + */ + domSelectionRange() { + let sel = this.domSelection(); + if (!sel) + return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 }; + return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel; + } + /** + @internal + */ + domSelection() { + return this.root.getSelection(); + } +} +EditorView.prototype.dispatch = function(tr2) { + let dispatchTransaction = this._props.dispatchTransaction; + if (dispatchTransaction) + dispatchTransaction.call(this, tr2); + else + this.updateState(this.state.apply(tr2)); +}; +function computeDocDeco(view) { + let attrs = /* @__PURE__ */ Object.create(null); + attrs.class = "ProseMirror"; + attrs.contenteditable = String(view.editable); + view.someProp("attributes", (value) => { + if (typeof value == "function") + value = value(view.state); + if (value) + for (let attr in value) { + if (attr == "class") + attrs.class += " " + value[attr]; + else if (attr == "style") + attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr]; + else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") + attrs[attr] = String(value[attr]); + } + }); + if (!attrs.translate) + attrs.translate = "no"; + return [Decoration.node(0, view.state.doc.content.size, attrs)]; +} +function updateCursorWrapper(view) { + if (view.markCursor) { + let dom = document.createElement("img"); + dom.className = "ProseMirror-separator"; + dom.setAttribute("mark-placeholder", "true"); + dom.setAttribute("alt", ""); + view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) }; + } else { + view.cursorWrapper = null; + } +} +function getEditable(view) { + return !view.someProp("editable", (value) => value(view.state) === false); +} +function selectionContextChanged(sel1, sel2) { + let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); + return sel1.$anchor.start(depth) != sel2.$anchor.start(depth); +} +function buildNodeViews(view) { + let result = /* @__PURE__ */ Object.create(null); + function add(obj) { + for (let prop in obj) + if (!Object.prototype.hasOwnProperty.call(result, prop)) + result[prop] = obj[prop]; + } + view.someProp("nodeViews", add); + view.someProp("markViews", add); + return result; +} +function changedNodeViews(a, b) { + let nA = 0, nB = 0; + for (let prop in a) { + if (a[prop] != b[prop]) + return true; + nA++; + } + for (let _ in b) + nB++; + return nA != nB; +} +function checkStateComponent(plugin) { + if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction) + throw new RangeError("Plugins passed directly to the view must not have a state component"); +} +var base = { + 8: "Backspace", + 9: "Tab", + 10: "Enter", + 12: "NumLock", + 13: "Enter", + 16: "Shift", + 17: "Control", + 18: "Alt", + 20: "CapsLock", + 27: "Escape", + 32: " ", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "ArrowLeft", + 38: "ArrowUp", + 39: "ArrowRight", + 40: "ArrowDown", + 44: "PrintScreen", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Meta", + 92: "Meta", + 106: "*", + 107: "+", + 108: ",", + 109: "-", + 110: ".", + 111: "/", + 144: "NumLock", + 145: "ScrollLock", + 160: "Shift", + 161: "Shift", + 162: "Control", + 163: "Control", + 164: "Alt", + 165: "Alt", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'" +}; +var shift = { + 48: ")", + 49: "!", + 50: "@", + 51: "#", + 52: "$", + 53: "%", + 54: "^", + 55: "&", + 56: "*", + 57: "(", + 59: ":", + 61: "+", + 173: "_", + 186: ":", + 187: "+", + 188: "<", + 189: "_", + 190: ">", + 191: "?", + 192: "~", + 219: "{", + 220: "|", + 221: "}", + 222: '"' +}; +var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform); +var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); +for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); +for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; +for (var i = 65; i <= 90; i++) { + base[i] = String.fromCharCode(i + 32); + shift[i] = String.fromCharCode(i); +} +for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; +function keyName(event) { + var ignoreKey = mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified"; + var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; + if (name == "Esc") name = "Escape"; + if (name == "Del") name = "Delete"; + if (name == "Left") name = "ArrowLeft"; + if (name == "Up") name = "ArrowUp"; + if (name == "Right") name = "ArrowRight"; + if (name == "Down") name = "ArrowDown"; + return name; +} +const mac = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform); +const windows = typeof navigator != "undefined" && /Win/.test(navigator.platform); +function normalizeKeyName$1(name) { + let parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; + if (result == "Space") + result = " "; + let alt, ctrl, shift2, meta; + for (let i = 0; i < parts.length - 1; i++) { + let mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) + meta = true; + else if (/^a(lt)?$/i.test(mod)) + alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) + ctrl = true; + else if (/^s(hift)?$/i.test(mod)) + shift2 = true; + else if (/^mod$/i.test(mod)) { + if (mac) + meta = true; + else + ctrl = true; + } else + throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) + result = "Alt-" + result; + if (ctrl) + result = "Ctrl-" + result; + if (meta) + result = "Meta-" + result; + if (shift2) + result = "Shift-" + result; + return result; +} +function normalize(map2) { + let copy2 = /* @__PURE__ */ Object.create(null); + for (let prop in map2) + copy2[normalizeKeyName$1(prop)] = map2[prop]; + return copy2; +} +function modifiers(name, event, shift2 = true) { + if (event.altKey) + name = "Alt-" + name; + if (event.ctrlKey) + name = "Ctrl-" + name; + if (event.metaKey) + name = "Meta-" + name; + if (shift2 && event.shiftKey) + name = "Shift-" + name; + return name; +} +function keymap(bindings) { + return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } }); +} +function keydownHandler(bindings) { + let map2 = normalize(bindings); + return function(view, event) { + let name = keyName(event), baseName, direct = map2[modifiers(name, event)]; + if (direct && direct(view.state, view.dispatch, view)) + return true; + if (name.length == 1 && name != " ") { + if (event.shiftKey) { + let noShift = map2[modifiers(name, event, false)]; + if (noShift && noShift(view.state, view.dispatch, view)) + return true; + } + if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows + !(windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) { + let fromCode = map2[modifiers(baseName, event)]; + if (fromCode && fromCode(view.state, view.dispatch, view)) + return true; + } + } + return false; + }; +} +var __defProp$1 = Object.defineProperty; +var __export$1 = (target, all) => { + for (var name in all) + __defProp$1(target, name, { get: all[name], enumerable: true }); +}; +function createChainableState(config) { + const { state, transaction } = config; + let { selection } = transaction; + let { doc: doc2 } = transaction; + let { storedMarks } = transaction; + return { + ...state, + apply: state.apply.bind(state), + applyTransaction: state.applyTransaction.bind(state), + plugins: state.plugins, + schema: state.schema, + reconfigure: state.reconfigure.bind(state), + toJSON: state.toJSON.bind(state), + get storedMarks() { + return storedMarks; + }, + get selection() { + return selection; + }, + get doc() { + return doc2; + }, + get tr() { + selection = transaction.selection; + doc2 = transaction.doc; + storedMarks = transaction.storedMarks; + return transaction; + } + }; +} +var CommandManager = class { + constructor(props) { + this.editor = props.editor; + this.rawCommands = this.editor.extensionManager.commands; + this.customState = props.state; + } + get hasCustomState() { + return !!this.customState; + } + get state() { + return this.customState || this.editor.state; + } + get commands() { + const { rawCommands, editor, state } = this; + const { view } = editor; + const { tr: tr2 } = state; + const props = this.buildProps(tr2); + return Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + const method = (...args) => { + const callback = command2(...args)(props); + if (!tr2.getMeta("preventDispatch") && !this.hasCustomState) { + view.dispatch(tr2); + } + return callback; + }; + return [name, method]; + }) + ); + } + get chain() { + return () => this.createChain(); + } + get can() { + return () => this.createCan(); + } + createChain(startTr, shouldDispatch = true) { + const { rawCommands, editor, state } = this; + const { view } = editor; + const callbacks = []; + const hasStartTransaction = !!startTr; + const tr2 = startTr || state.tr; + const run3 = () => { + if (!hasStartTransaction && shouldDispatch && !tr2.getMeta("preventDispatch") && !this.hasCustomState) { + view.dispatch(tr2); + } + return callbacks.every((callback) => callback === true); + }; + const chain = { + ...Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + const chainedCommand = (...args) => { + const props = this.buildProps(tr2, shouldDispatch); + const callback = command2(...args)(props); + callbacks.push(callback); + return chain; + }; + return [name, chainedCommand]; + }) + ), + run: run3 + }; + return chain; + } + createCan(startTr) { + const { rawCommands, state } = this; + const dispatch = false; + const tr2 = startTr || state.tr; + const props = this.buildProps(tr2, dispatch); + const formattedCommands = Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })]; + }) + ); + return { + ...formattedCommands, + chain: () => this.createChain(tr2, dispatch) + }; + } + buildProps(tr2, shouldDispatch = true) { + const { rawCommands, editor, state } = this; + const { view } = editor; + const props = { + tr: tr2, + editor, + view, + state: createChainableState({ + state, + transaction: tr2 + }), + dispatch: shouldDispatch ? () => void 0 : void 0, + chain: () => this.createChain(tr2, shouldDispatch), + can: () => this.createCan(tr2), + get commands() { + return Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + return [name, (...args) => command2(...args)(props)]; + }) + ); + } + }; + return props; + } +}; +var commands_exports = {}; +__export$1(commands_exports, { + blur: () => blur, + clearContent: () => clearContent, + clearNodes: () => clearNodes, + command: () => command, + createParagraphNear: () => createParagraphNear, + cut: () => cut, + deleteCurrentNode: () => deleteCurrentNode, + deleteNode: () => deleteNode, + deleteRange: () => deleteRange, + deleteSelection: () => deleteSelection, + enter: () => enter, + exitCode: () => exitCode, + extendMarkRange: () => extendMarkRange, + first: () => first, + focus: () => focus, + forEach: () => forEach, + insertContent: () => insertContent, + insertContentAt: () => insertContentAt, + joinBackward: () => joinBackward, + joinDown: () => joinDown, + joinForward: () => joinForward, + joinItemBackward: () => joinItemBackward, + joinItemForward: () => joinItemForward, + joinTextblockBackward: () => joinTextblockBackward, + joinTextblockForward: () => joinTextblockForward, + joinUp: () => joinUp, + keyboardShortcut: () => keyboardShortcut, + lift: () => lift, + liftEmptyBlock: () => liftEmptyBlock, + liftListItem: () => liftListItem, + newlineInCode: () => newlineInCode, + resetAttributes: () => resetAttributes, + scrollIntoView: () => scrollIntoView, + selectAll: () => selectAll, + selectNodeBackward: () => selectNodeBackward, + selectNodeForward: () => selectNodeForward, + selectParentNode: () => selectParentNode, + selectTextblockEnd: () => selectTextblockEnd, + selectTextblockStart: () => selectTextblockStart, + setContent: () => setContent, + setMark: () => setMark, + setMeta: () => setMeta, + setNode: () => setNode, + setNodeSelection: () => setNodeSelection, + setTextDirection: () => setTextDirection, + setTextSelection: () => setTextSelection, + sinkListItem: () => sinkListItem, + splitBlock: () => splitBlock, + splitListItem: () => splitListItem, + toggleList: () => toggleList, + toggleMark: () => toggleMark, + toggleNode: () => toggleNode, + toggleWrap: () => toggleWrap, + undoInputRule: () => undoInputRule, + unsetAllMarks: () => unsetAllMarks, + unsetMark: () => unsetMark, + unsetTextDirection: () => unsetTextDirection, + updateAttributes: () => updateAttributes, + wrapIn: () => wrapIn, + wrapInList: () => wrapInList +}); +var blur = () => ({ editor, view }) => { + requestAnimationFrame(() => { + var _a; + if (!editor.isDestroyed) { + view.dom.blur(); + (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges(); + } + }); + return true; +}; +var clearContent = (emitUpdate = true) => ({ commands }) => { + return commands.setContent("", { emitUpdate }); +}; +var clearNodes = () => ({ state, tr: tr2, dispatch }) => { + const { selection } = tr2; + const { ranges } = selection; + if (!dispatch) { + return true; + } + ranges.forEach(({ $from, $to }) => { + state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => { + if (node.type.isText) { + return; + } + const { doc: doc2, mapping } = tr2; + const $mappedFrom = doc2.resolve(mapping.map(pos)); + const $mappedTo = doc2.resolve(mapping.map(pos + node.nodeSize)); + const nodeRange = $mappedFrom.blockRange($mappedTo); + if (!nodeRange) { + return; + } + const targetLiftDepth = liftTarget(nodeRange); + if (node.type.isTextblock) { + const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index()); + tr2.setNodeMarkup(nodeRange.start, defaultType); + } + if (targetLiftDepth || targetLiftDepth === 0) { + tr2.lift(nodeRange, targetLiftDepth); + } + }); + }); + return true; +}; +var command = (fn) => (props) => { + return fn(props); +}; +var createParagraphNear = () => ({ state, dispatch }) => { + return createParagraphNear$1(state, dispatch); +}; +var cut = (originRange, targetPos) => ({ editor, tr: tr2 }) => { + const { state } = editor; + const contentSlice = state.doc.slice(originRange.from, originRange.to); + tr2.deleteRange(originRange.from, originRange.to); + const newPos = tr2.mapping.map(targetPos); + tr2.insert(newPos, contentSlice.content); + tr2.setSelection(new TextSelection(tr2.doc.resolve(Math.max(newPos - 1, 0)))); + return true; +}; +var deleteCurrentNode = () => ({ tr: tr2, dispatch }) => { + const { selection } = tr2; + const currentNode = selection.$anchor.node(); + if (currentNode.content.size > 0) { + return false; + } + const $pos = tr2.selection.$anchor; + for (let depth = $pos.depth; depth > 0; depth -= 1) { + const node = $pos.node(depth); + if (node.type === currentNode.type) { + if (dispatch) { + const from2 = $pos.before(depth); + const to = $pos.after(depth); + tr2.delete(from2, to).scrollIntoView(); + } + return true; + } + } + return false; +}; +function getNodeType(nameOrType, schema) { + if (typeof nameOrType === "string") { + if (!schema.nodes[nameOrType]) { + throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`); + } + return schema.nodes[nameOrType]; + } + return nameOrType; +} +var deleteNode = (typeOrName) => ({ tr: tr2, state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + const $pos = tr2.selection.$anchor; + for (let depth = $pos.depth; depth > 0; depth -= 1) { + const node = $pos.node(depth); + if (node.type === type) { + if (dispatch) { + const from2 = $pos.before(depth); + const to = $pos.after(depth); + tr2.delete(from2, to).scrollIntoView(); + } + return true; + } + } + return false; +}; +var deleteRange = (range) => ({ tr: tr2, dispatch }) => { + const { from: from2, to } = range; + if (dispatch) { + tr2.delete(from2, to); + } + return true; +}; +var deleteSelection = () => ({ state, dispatch }) => { + return deleteSelection$1(state, dispatch); +}; +var enter = () => ({ commands }) => { + return commands.keyboardShortcut("Enter"); +}; +var exitCode = () => ({ state, dispatch }) => { + return exitCode$1(state, dispatch); +}; +function isRegExp(value) { + return Object.prototype.toString.call(value) === "[object RegExp]"; +} +function objectIncludes(object1, object2, options = { strict: true }) { + const keys2 = Object.keys(object2); + if (!keys2.length) { + return true; + } + return keys2.every((key) => { + if (options.strict) { + return object2[key] === object1[key]; + } + if (isRegExp(object2[key])) { + return object2[key].test(object1[key]); + } + return object2[key] === object1[key]; + }); +} +function findMarkInSet(marks, type, attributes = {}) { + return marks.find((item) => { + return item.type === type && objectIncludes( + // Only check equality for the attributes that are provided + Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])), + attributes + ); + }); +} +function isMarkInSet(marks, type, attributes = {}) { + return !!findMarkInSet(marks, type, attributes); +} +function getMarkRange($pos, type, attributes) { + if (!$pos || !type) { + return; + } + let start = $pos.parent.childAfter($pos.parentOffset); + if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) { + start = $pos.parent.childBefore($pos.parentOffset); + } + if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) { + return; + } + if (!attributes) { + const firstMark = start.node.marks.find((mark2) => mark2.type === type); + if (firstMark) { + attributes = firstMark.attrs; + } + } + const mark = findMarkInSet([...start.node.marks], type, attributes); + if (!mark) { + return; + } + let startIndex = start.index; + let startPos = $pos.start() + start.offset; + let endIndex = startIndex + 1; + let endPos = startPos + start.node.nodeSize; + while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) { + startIndex -= 1; + startPos -= $pos.parent.child(startIndex).nodeSize; + } + while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) { + endPos += $pos.parent.child(endIndex).nodeSize; + endIndex += 1; + } + return { + from: startPos, + to: endPos + }; +} +function getMarkType(nameOrType, schema) { + if (typeof nameOrType === "string") { + if (!schema.marks[nameOrType]) { + throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`); + } + return schema.marks[nameOrType]; + } + return nameOrType; +} +var extendMarkRange = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => { + const type = getMarkType(typeOrName, state.schema); + const { doc: doc2, selection } = tr2; + const { $from, from: from2, to } = selection; + if (dispatch) { + const range = getMarkRange($from, type, attributes); + if (range && range.from <= from2 && range.to >= to) { + const newSelection = TextSelection.create(doc2, range.from, range.to); + tr2.setSelection(newSelection); + } + } + return true; +}; +var first = (commands) => (props) => { + const items = typeof commands === "function" ? commands(props) : commands; + for (let i = 0; i < items.length; i += 1) { + if (items[i](props)) { + return true; + } + } + return false; +}; +function isTextSelection(value) { + return value instanceof TextSelection; +} +function minMax(value = 0, min = 0, max = 0) { + return Math.min(Math.max(value, min), max); +} +function resolveFocusPosition(doc2, position = null) { + if (!position) { + return null; + } + const selectionAtStart = Selection.atStart(doc2); + const selectionAtEnd = Selection.atEnd(doc2); + if (position === "start" || position === true) { + return selectionAtStart; + } + if (position === "end") { + return selectionAtEnd; + } + const minPos = selectionAtStart.from; + const maxPos = selectionAtEnd.to; + if (position === "all") { + return TextSelection.create(doc2, minMax(0, minPos, maxPos), minMax(doc2.content.size, minPos, maxPos)); + } + return TextSelection.create(doc2, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos)); +} +function isAndroid() { + return navigator.platform === "Android" || /android/i.test(navigator.userAgent); +} +function isiOS() { + return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection + navigator.userAgent.includes("Mac") && "ontouchend" in document; +} +function isSafari() { + return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false; +} +var focus = (position = null, options = {}) => ({ editor, view, tr: tr2, dispatch }) => { + options = { + scrollIntoView: true, + ...options + }; + const delayedFocus = () => { + if (isiOS() || isAndroid()) { + view.dom.focus(); + } + if (isSafari() && !isiOS() && !isAndroid()) { + view.dom.focus({ preventScroll: true }); + } + requestAnimationFrame(() => { + if (!editor.isDestroyed) { + view.focus(); + if (options == null ? void 0 : options.scrollIntoView) { + editor.commands.scrollIntoView(); + } + } + }); + }; + try { + if (view.hasFocus() && position === null || position === false) { + return true; + } + } catch { + return false; + } + if (dispatch && position === null && !isTextSelection(editor.state.selection)) { + delayedFocus(); + return true; + } + const selection = resolveFocusPosition(tr2.doc, position) || editor.state.selection; + const isSameSelection = editor.state.selection.eq(selection); + if (dispatch) { + if (!isSameSelection) { + tr2.setSelection(selection); + } + if (isSameSelection && tr2.storedMarks) { + tr2.setStoredMarks(tr2.storedMarks); + } + delayedFocus(); + } + return true; +}; +var forEach = (items, fn) => (props) => { + return items.every((item, index) => fn(item, { ...props, index })); +}; +var insertContent = (value, options) => ({ tr: tr2, commands }) => { + return commands.insertContentAt({ from: tr2.selection.from, to: tr2.selection.to }, value, options); +}; +var removeWhitespaces = (node) => { + const children = node.childNodes; + for (let i = children.length - 1; i >= 0; i -= 1) { + const child = children[i]; + if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) { + node.removeChild(child); + } else if (child.nodeType === 1) { + removeWhitespaces(child); + } + } + return node; +}; +function elementFromString(value) { + if (typeof window === "undefined") { + throw new Error("[tiptap error]: there is no window object available, so this function cannot be used"); + } + const wrappedValue = `${value}`; + const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body; + return removeWhitespaces(html); +} +function createNodeFromContent(content, schema, options) { + if (content instanceof Node || content instanceof Fragment) { + return content; + } + options = { + slice: true, + parseOptions: {}, + ...options + }; + const isJSONContent = typeof content === "object" && content !== null; + const isTextContent = typeof content === "string"; + if (isJSONContent) { + try { + const isArrayContent = Array.isArray(content) && content.length > 0; + if (isArrayContent) { + return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item))); + } + const node = schema.nodeFromJSON(content); + if (options.errorOnInvalidContent) { + node.check(); + } + return node; + } catch (error) { + if (options.errorOnInvalidContent) { + throw new Error("[tiptap error]: Invalid JSON content", { cause: error }); + } + console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error); + return createNodeFromContent("", schema, options); + } + } + if (isTextContent) { + if (options.errorOnInvalidContent) { + let hasInvalidContent = false; + let invalidContent = ""; + const contentCheckSchema = new Schema({ + topNode: schema.spec.topNode, + marks: schema.spec.marks, + // Prosemirror's schemas are executed such that: the last to execute, matches last + // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle + nodes: schema.spec.nodes.append({ + __tiptap__private__unknown__catch__all__node: { + content: "inline*", + group: "block", + parseDOM: [ + { + tag: "*", + getAttrs: (e) => { + hasInvalidContent = true; + invalidContent = typeof e === "string" ? e : e.outerHTML; + return null; + } + } + ] + } + }) + }); + if (options.slice) { + DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions); + } else { + DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions); + } + if (options.errorOnInvalidContent && hasInvalidContent) { + throw new Error("[tiptap error]: Invalid HTML content", { + cause: new Error(`Invalid element found: ${invalidContent}`) + }); + } + } + const parser = DOMParser.fromSchema(schema); + if (options.slice) { + return parser.parseSlice(elementFromString(content), options.parseOptions).content; + } + return parser.parse(elementFromString(content), options.parseOptions); + } + return createNodeFromContent("", schema, options); +} +function selectionToInsertionEnd(tr2, startLen, bias) { + const last = tr2.steps.length - 1; + if (last < startLen) { + return; + } + const step = tr2.steps[last]; + if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { + return; + } + const map2 = tr2.mapping.maps[last]; + let end = 0; + map2.forEach((_from, _to, _newFrom, newTo) => { + if (end === 0) { + end = newTo; + } + }); + tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias)); +} +var isFragment = (nodeOrFragment) => { + return !("type" in nodeOrFragment); +}; +var insertContentAt = (position, value, options) => ({ tr: tr2, dispatch, editor }) => { + var _a; + if (dispatch) { + options = { + parseOptions: editor.options.parseOptions, + updateSelection: true, + applyInputRules: false, + applyPasteRules: false, + ...options + }; + let content; + const emitContentError = (error) => { + editor.emit("contentError", { + editor, + error, + disableCollaboration: () => { + if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) { + editor.storage.collaboration.isDisabled = true; + } + } + }); + }; + const parseOptions = { + preserveWhitespace: "full", + ...options.parseOptions + }; + if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) { + try { + createNodeFromContent(value, editor.schema, { + parseOptions, + errorOnInvalidContent: true + }); + } catch (e) { + emitContentError(e); + } + } + try { + content = createNodeFromContent(value, editor.schema, { + parseOptions, + errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck + }); + } catch (e) { + emitContentError(e); + return false; + } + let { from: from2, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to }; + let isOnlyTextContent = true; + let isOnlyBlockContent = true; + const nodes = isFragment(content) ? content : [content]; + nodes.forEach((node) => { + node.check(); + isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false; + isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false; + }); + if (from2 === to && isOnlyBlockContent) { + const { parent } = tr2.doc.resolve(from2); + const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount; + if (isEmptyTextBlock) { + from2 -= 1; + to += 1; + } + } + let newContent; + if (isOnlyTextContent) { + if (Array.isArray(value)) { + newContent = value.map((v) => v.text || "").join(""); + } else if (value instanceof Fragment) { + let text = ""; + value.forEach((node) => { + if (node.text) { + text += node.text; + } + }); + newContent = text; + } else if (typeof value === "object" && !!value && !!value.text) { + newContent = value.text; + } else { + newContent = value; + } + tr2.insertText(newContent, from2, to); + } else { + newContent = content; + const $from = tr2.doc.resolve(from2); + const $fromNode = $from.node(); + const fromSelectionAtStart = $from.parentOffset === 0; + const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock; + const hasContent = $fromNode.content.size > 0; + if (fromSelectionAtStart && isTextSelection2 && hasContent) { + from2 = Math.max(0, from2 - 1); + } + tr2.replaceWith(from2, to, newContent); + } + if (options.updateSelection) { + selectionToInsertionEnd(tr2, tr2.steps.length - 1, -1); + } + if (options.applyInputRules) { + tr2.setMeta("applyInputRules", { from: from2, text: newContent }); + } + if (options.applyPasteRules) { + tr2.setMeta("applyPasteRules", { from: from2, text: newContent }); + } + } + return true; +}; +var joinUp = () => ({ state, dispatch }) => { + return joinUp$1(state, dispatch); +}; +var joinDown = () => ({ state, dispatch }) => { + return joinDown$1(state, dispatch); +}; +var joinBackward = () => ({ state, dispatch }) => { + return joinBackward$1(state, dispatch); +}; +var joinForward = () => ({ state, dispatch }) => { + return joinForward$1(state, dispatch); +}; +var joinItemBackward = () => ({ state, dispatch, tr: tr2 }) => { + try { + const point = joinPoint(state.doc, state.selection.$from.pos, -1); + if (point === null || point === void 0) { + return false; + } + tr2.join(point, 2); + if (dispatch) { + dispatch(tr2); + } + return true; + } catch { + return false; + } +}; +var joinItemForward = () => ({ state, dispatch, tr: tr2 }) => { + try { + const point = joinPoint(state.doc, state.selection.$from.pos, 1); + if (point === null || point === void 0) { + return false; + } + tr2.join(point, 2); + if (dispatch) { + dispatch(tr2); + } + return true; + } catch { + return false; + } +}; +var joinTextblockBackward = () => ({ state, dispatch }) => { + return joinTextblockBackward$1(state, dispatch); +}; +var joinTextblockForward = () => ({ state, dispatch }) => { + return joinTextblockForward$1(state, dispatch); +}; +function isMacOS() { + return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; +} +function normalizeKeyName(name) { + const parts = name.split(/-(?!$)/); + let result = parts[parts.length - 1]; + if (result === "Space") { + result = " "; + } + let alt; + let ctrl; + let shift2; + let meta; + for (let i = 0; i < parts.length - 1; i += 1) { + const mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) { + meta = true; + } else if (/^a(lt)?$/i.test(mod)) { + alt = true; + } else if (/^(c|ctrl|control)$/i.test(mod)) { + ctrl = true; + } else if (/^s(hift)?$/i.test(mod)) { + shift2 = true; + } else if (/^mod$/i.test(mod)) { + if (isiOS() || isMacOS()) { + meta = true; + } else { + ctrl = true; + } + } else { + throw new Error(`Unrecognized modifier name: ${mod}`); + } + } + if (alt) { + result = `Alt-${result}`; + } + if (ctrl) { + result = `Ctrl-${result}`; + } + if (meta) { + result = `Meta-${result}`; + } + if (shift2) { + result = `Shift-${result}`; + } + return result; +} +var keyboardShortcut = (name) => ({ editor, view, tr: tr2, dispatch }) => { + const keys2 = normalizeKeyName(name).split(/-(?!$)/); + const key = keys2.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item)); + const event = new KeyboardEvent("keydown", { + key: key === "Space" ? " " : key, + altKey: keys2.includes("Alt"), + ctrlKey: keys2.includes("Ctrl"), + metaKey: keys2.includes("Meta"), + shiftKey: keys2.includes("Shift"), + bubbles: true, + cancelable: true + }); + const capturedTransaction = editor.captureTransaction(() => { + view.someProp("handleKeyDown", (f) => f(view, event)); + }); + capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => { + const newStep = step.map(tr2.mapping); + if (newStep && dispatch) { + tr2.maybeStep(newStep); + } + }); + return true; +}; +function isNodeActive(state, typeOrName, attributes = {}) { + const { from: from2, to, empty: empty2 } = state.selection; + const type = typeOrName ? getNodeType(typeOrName, state.schema) : null; + const nodeRanges = []; + state.doc.nodesBetween(from2, to, (node, pos) => { + if (node.isText) { + return; + } + const relativeFrom = Math.max(from2, pos); + const relativeTo = Math.min(to, pos + node.nodeSize); + nodeRanges.push({ + node, + from: relativeFrom, + to: relativeTo + }); + }); + const selectionRange = to - from2; + const matchedNodeRanges = nodeRanges.filter((nodeRange) => { + if (!type) { + return true; + } + return type.name === nodeRange.node.type.name; + }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false })); + if (empty2) { + return !!matchedNodeRanges.length; + } + const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0); + return range >= selectionRange; +} +var lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + const isActive2 = isNodeActive(state, type, attributes); + if (!isActive2) { + return false; + } + return lift$1(state, dispatch); +}; +var liftEmptyBlock = () => ({ state, dispatch }) => { + return liftEmptyBlock$1(state, dispatch); +}; +var liftListItem = (typeOrName) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return liftListItem$1(type)(state, dispatch); +}; +var newlineInCode = () => ({ state, dispatch }) => { + return newlineInCode$1(state, dispatch); +}; +function getSchemaTypeNameByName(name, schema) { + if (schema.nodes[name]) { + return "node"; + } + if (schema.marks[name]) { + return "mark"; + } + return null; +} +function deleteProps(obj, propOrProps) { + const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps; + return Object.keys(obj).reduce((newObj, prop) => { + if (!props.includes(prop)) { + newObj[prop] = obj[prop]; + } + return newObj; + }, {}); +} +var resetAttributes = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => { + let nodeType = null; + let markType = null; + const schemaType = getSchemaTypeNameByName( + typeof typeOrName === "string" ? typeOrName : typeOrName.name, + state.schema + ); + if (!schemaType) { + return false; + } + if (schemaType === "node") { + nodeType = getNodeType(typeOrName, state.schema); + } + if (schemaType === "mark") { + markType = getMarkType(typeOrName, state.schema); + } + let canReset = false; + tr2.selection.ranges.forEach((range) => { + state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => { + if (nodeType && nodeType === node.type) { + canReset = true; + if (dispatch) { + tr2.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes)); + } + } + if (markType && node.marks.length) { + node.marks.forEach((mark) => { + if (markType === mark.type) { + canReset = true; + if (dispatch) { + tr2.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes))); + } + } + }); + } + }); + }); + return canReset; +}; +var scrollIntoView = () => ({ tr: tr2, dispatch }) => { + if (dispatch) { + tr2.scrollIntoView(); + } + return true; +}; +var selectAll = () => ({ tr: tr2, dispatch }) => { + if (dispatch) { + const selection = new AllSelection(tr2.doc); + tr2.setSelection(selection); + } + return true; +}; +var selectNodeBackward = () => ({ state, dispatch }) => { + return selectNodeBackward$1(state, dispatch); +}; +var selectNodeForward = () => ({ state, dispatch }) => { + return selectNodeForward$1(state, dispatch); +}; +var selectParentNode = () => ({ state, dispatch }) => { + return selectParentNode$1(state, dispatch); +}; +var selectTextblockEnd = () => ({ state, dispatch }) => { + return selectTextblockEnd$1(state, dispatch); +}; +var selectTextblockStart = () => ({ state, dispatch }) => { + return selectTextblockStart$1(state, dispatch); +}; +function createDocument(content, schema, parseOptions = {}, options = {}) { + return createNodeFromContent(content, schema, { + slice: false, + parseOptions, + errorOnInvalidContent: options.errorOnInvalidContent + }); +} +var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr2, dispatch, commands }) => { + const { doc: doc2 } = tr2; + if (parseOptions.preserveWhitespace !== "full") { + const document2 = createDocument(content, editor.schema, parseOptions, { + errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck + }); + if (dispatch) { + tr2.replaceWith(0, doc2.content.size, document2).setMeta("preventUpdate", !emitUpdate); + } + return true; + } + if (dispatch) { + tr2.setMeta("preventUpdate", !emitUpdate); + } + return commands.insertContentAt({ from: 0, to: doc2.content.size }, content, { + parseOptions, + errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck + }); +}; +function getMarkAttributes(state, typeOrName) { + const type = getMarkType(typeOrName, state.schema); + const { from: from2, to, empty: empty2 } = state.selection; + const marks = []; + if (empty2) { + if (state.storedMarks) { + marks.push(...state.storedMarks); + } + marks.push(...state.selection.$head.marks()); + } else { + state.doc.nodesBetween(from2, to, (node) => { + marks.push(...node.marks); + }); + } + const mark = marks.find((markItem) => markItem.type.name === type.name); + if (!mark) { + return {}; + } + return { ...mark.attrs }; +} +function combineTransactionSteps(oldDoc, transactions) { + const transform = new Transform(oldDoc); + transactions.forEach((transaction) => { + transaction.steps.forEach((step) => { + transform.step(step); + }); + }); + return transform; +} +function defaultBlockAt(match) { + for (let i = 0; i < match.edgeCount; i += 1) { + const { type } = match.edge(i); + if (type.isTextblock && !type.hasRequiredAttrs()) { + return type; + } + } + return null; +} +function findChildrenInRange(node, range, predicate) { + const nodesWithPos = []; + node.nodesBetween(range.from, range.to, (child, pos) => { + if (predicate(child)) { + nodesWithPos.push({ + node: child, + pos + }); + } + }); + return nodesWithPos; +} +function findParentNodeClosestToPos($pos, predicate) { + for (let i = $pos.depth; i > 0; i -= 1) { + const node = $pos.node(i); + if (predicate(node)) { + return { + pos: i > 0 ? $pos.before(i) : 0, + start: $pos.start(i), + depth: i, + node + }; + } + } +} +function findParentNode(predicate) { + return (selection) => findParentNodeClosestToPos(selection.$from, predicate); +} +function getExtensionField(extension, field, context) { + if (extension.config[field] === void 0 && extension.parent) { + return getExtensionField(extension.parent, field, context); + } + if (typeof extension.config[field] === "function") { + const value = extension.config[field].bind({ + ...context, + parent: extension.parent ? getExtensionField(extension.parent, field, context) : null + }); + return value; + } + return extension.config[field]; +} +function flattenExtensions(extensions) { + return extensions.map((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + const addExtensions = getExtensionField(extension, "addExtensions", context); + if (addExtensions) { + return [extension, ...flattenExtensions(addExtensions())]; + } + return extension; + }).flat(10); +} +function getHTMLFromFragment(fragment, schema) { + const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment); + const temporaryDocument = document.implementation.createHTMLDocument(); + const container = temporaryDocument.createElement("div"); + container.appendChild(documentFragment); + return container.innerHTML; +} +function isFunction(value) { + return typeof value === "function"; +} +function callOrReturn(value, context = void 0, ...props) { + if (isFunction(value)) { + if (context) { + return value.bind(context)(...props); + } + return value(...props); + } + return value; +} +function isEmptyObject(value = {}) { + return Object.keys(value).length === 0 && value.constructor === Object; +} +function splitExtensions(extensions) { + const baseExtensions = extensions.filter((extension) => extension.type === "extension"); + const nodeExtensions = extensions.filter((extension) => extension.type === "node"); + const markExtensions = extensions.filter((extension) => extension.type === "mark"); + return { + baseExtensions, + nodeExtensions, + markExtensions + }; +} +function getAttributesFromExtensions(extensions) { + const extensionAttributes = []; + const { nodeExtensions, markExtensions } = splitExtensions(extensions); + const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]; + const defaultAttribute = { + default: null, + validate: void 0, + rendered: true, + renderHTML: null, + parseHTML: null, + keepOnSplit: true, + isRequired: false + }; + const nodeExtensionTypes = nodeExtensions.filter((ext) => ext.name !== "text").map((ext) => ext.name); + const markExtensionTypes = markExtensions.map((ext) => ext.name); + const allExtensionTypes = [...nodeExtensionTypes, ...markExtensionTypes]; + extensions.forEach((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage, + extensions: nodeAndMarkExtensions + }; + const addGlobalAttributes = getExtensionField( + extension, + "addGlobalAttributes", + context + ); + if (!addGlobalAttributes) { + return; + } + const globalAttributes = addGlobalAttributes(); + globalAttributes.forEach((globalAttribute) => { + let resolvedTypes; + if (Array.isArray(globalAttribute.types)) { + resolvedTypes = globalAttribute.types; + } else if (globalAttribute.types === "*") { + resolvedTypes = allExtensionTypes; + } else if (globalAttribute.types === "nodes") { + resolvedTypes = nodeExtensionTypes; + } else if (globalAttribute.types === "marks") { + resolvedTypes = markExtensionTypes; + } else { + resolvedTypes = []; + } + resolvedTypes.forEach((type) => { + Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => { + extensionAttributes.push({ + type, + name, + attribute: { + ...defaultAttribute, + ...attribute + } + }); + }); + }); + }); + }); + nodeAndMarkExtensions.forEach((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + const addAttributes = getExtensionField( + extension, + "addAttributes", + context + ); + if (!addAttributes) { + return; + } + const attributes = addAttributes(); + Object.entries(attributes).forEach(([name, attribute]) => { + const mergedAttr = { + ...defaultAttribute, + ...attribute + }; + if (typeof (mergedAttr == null ? void 0 : mergedAttr.default) === "function") { + mergedAttr.default = mergedAttr.default(); + } + if ((mergedAttr == null ? void 0 : mergedAttr.isRequired) && (mergedAttr == null ? void 0 : mergedAttr.default) === void 0) { + delete mergedAttr.default; + } + extensionAttributes.push({ + type: extension.name, + name, + attribute: mergedAttr + }); + }); + }); + return extensionAttributes; +} +function splitStyleDeclarations(styles) { + const result = []; + let current = ""; + let inSingleQuote = false; + let inDoubleQuote = false; + let parenDepth = 0; + const length = styles.length; + for (let i = 0; i < length; i += 1) { + const char = styles[i]; + if (char === "'" && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + current += char; + continue; + } + if (char === '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + current += char; + continue; + } + if (!inSingleQuote && !inDoubleQuote) { + if (char === "(") { + parenDepth += 1; + current += char; + continue; + } + if (char === ")" && parenDepth > 0) { + parenDepth -= 1; + current += char; + continue; + } + if (char === ";" && parenDepth === 0) { + result.push(current); + current = ""; + continue; + } + } + current += char; + } + if (current) { + result.push(current); + } + return result; +} +function parseStyleEntries(styles) { + const pairs = []; + const declarations = splitStyleDeclarations(styles || ""); + const numDeclarations = declarations.length; + for (let i = 0; i < numDeclarations; i += 1) { + const declaration = declarations[i]; + const firstColonIndex = declaration.indexOf(":"); + if (firstColonIndex === -1) { + continue; + } + const property = declaration.slice(0, firstColonIndex).trim(); + const value = declaration.slice(firstColonIndex + 1).trim(); + if (property && value) { + pairs.push([property, value]); + } + } + return pairs; +} +function mergeAttributes(...objects) { + return objects.filter((item) => !!item).reduce((items, item) => { + const mergedAttributes = { ...items }; + Object.entries(item).forEach(([key, value]) => { + const exists = mergedAttributes[key]; + if (!exists) { + mergedAttributes[key] = value; + return; + } + if (key === "class") { + const valueClasses = value ? String(value).split(" ") : []; + const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : []; + const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass)); + mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" "); + } else if (key === "style") { + const styleMap = new Map([...parseStyleEntries(mergedAttributes[key]), ...parseStyleEntries(value)]); + mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; "); + } else { + mergedAttributes[key] = value; + } + }); + return mergedAttributes; + }, {}); +} +function getRenderedAttributes(nodeOrMark, extensionAttributes) { + return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => { + if (!item.attribute.renderHTML) { + return { + [item.name]: nodeOrMark.attrs[item.name] + }; + } + return item.attribute.renderHTML(nodeOrMark.attrs) || {}; + }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {}); +} +function fromString(value) { + if (typeof value !== "string") { + return value; + } + if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) { + return Number(value); + } + if (value === "true") { + return true; + } + if (value === "false") { + return false; + } + return value; +} +function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) { + if ("style" in parseRule) { + return parseRule; + } + return { + ...parseRule, + getAttrs: (node) => { + const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs; + if (oldAttributes === false) { + return false; + } + const newAttributes = extensionAttributes.reduce((items, item) => { + const value = item.attribute.parseHTML ? item.attribute.parseHTML(node) : fromString(node.getAttribute(item.name)); + if (value === null || value === void 0) { + return items; + } + return { + ...items, + [item.name]: value + }; + }, {}); + return { ...oldAttributes, ...newAttributes }; + } + }; +} +function cleanUpSchemaItem(data) { + return Object.fromEntries( + // @ts-ignore + Object.entries(data).filter(([key, value]) => { + if (key === "attrs" && isEmptyObject(value)) { + return false; + } + return value !== null && value !== void 0; + }) + ); +} +function buildAttributeSpec(extensionAttribute) { + var _a, _b; + const spec = {}; + if (!((_a = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _a.isRequired) && "default" in ((extensionAttribute == null ? void 0 : extensionAttribute.attribute) || {})) { + spec.default = extensionAttribute.attribute.default; + } + if (((_b = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _b.validate) !== void 0) { + spec.validate = extensionAttribute.attribute.validate; + } + return [extensionAttribute.name, spec]; +} +function getSchemaByResolvedExtensions(extensions, editor) { + var _a; + const allAttributes = getAttributesFromExtensions(extensions); + const { nodeExtensions, markExtensions } = splitExtensions(extensions); + const topNode = (_a = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) == null ? void 0 : _a.name; + const nodes = Object.fromEntries( + nodeExtensions.map((extension) => { + const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage, + editor + }; + const extraNodeFields = extensions.reduce((fields, e) => { + const extendNodeSchema = getExtensionField(e, "extendNodeSchema", context); + return { + ...fields, + ...extendNodeSchema ? extendNodeSchema(extension) : {} + }; + }, {}); + const schema = cleanUpSchemaItem({ + ...extraNodeFields, + content: callOrReturn(getExtensionField(extension, "content", context)), + marks: callOrReturn(getExtensionField(extension, "marks", context)), + group: callOrReturn(getExtensionField(extension, "group", context)), + inline: callOrReturn(getExtensionField(extension, "inline", context)), + atom: callOrReturn(getExtensionField(extension, "atom", context)), + selectable: callOrReturn(getExtensionField(extension, "selectable", context)), + draggable: callOrReturn(getExtensionField(extension, "draggable", context)), + code: callOrReturn(getExtensionField(extension, "code", context)), + whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)), + linebreakReplacement: callOrReturn( + getExtensionField(extension, "linebreakReplacement", context) + ), + defining: callOrReturn(getExtensionField(extension, "defining", context)), + isolating: callOrReturn(getExtensionField(extension, "isolating", context)), + attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) + }); + const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); + if (parseHTML) { + schema.parseDOM = parseHTML.map( + (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) + ); + } + const renderHTML = getExtensionField(extension, "renderHTML", context); + if (renderHTML) { + schema.toDOM = (node) => renderHTML({ + node, + HTMLAttributes: getRenderedAttributes(node, extensionAttributes) + }); + } + const renderText = getExtensionField(extension, "renderText", context); + if (renderText) { + schema.toText = renderText; + } + return [extension.name, schema]; + }) + ); + const marks = Object.fromEntries( + markExtensions.map((extension) => { + const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage, + editor + }; + const extraMarkFields = extensions.reduce((fields, e) => { + const extendMarkSchema = getExtensionField(e, "extendMarkSchema", context); + return { + ...fields, + ...extendMarkSchema ? extendMarkSchema(extension) : {} + }; + }, {}); + const schema = cleanUpSchemaItem({ + ...extraMarkFields, + inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)), + excludes: callOrReturn(getExtensionField(extension, "excludes", context)), + group: callOrReturn(getExtensionField(extension, "group", context)), + spanning: callOrReturn(getExtensionField(extension, "spanning", context)), + code: callOrReturn(getExtensionField(extension, "code", context)), + attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) + }); + const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); + if (parseHTML) { + schema.parseDOM = parseHTML.map( + (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) + ); + } + const renderHTML = getExtensionField(extension, "renderHTML", context); + if (renderHTML) { + schema.toDOM = (mark) => renderHTML({ + mark, + HTMLAttributes: getRenderedAttributes(mark, extensionAttributes) + }); + } + return [extension.name, schema]; + }) + ); + return new Schema({ + topNode, + nodes, + marks + }); +} +function findDuplicates(items) { + const filtered = items.filter((el, index) => items.indexOf(el) !== index); + return Array.from(new Set(filtered)); +} +function sortExtensions(extensions) { + const defaultPriority = 100; + return extensions.sort((a, b) => { + const priorityA = getExtensionField(a, "priority") || defaultPriority; + const priorityB = getExtensionField(b, "priority") || defaultPriority; + if (priorityA > priorityB) { + return -1; + } + if (priorityA < priorityB) { + return 1; + } + return 0; + }); +} +function resolveExtensions(extensions) { + const resolvedExtensions = sortExtensions(flattenExtensions(extensions)); + const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name)); + if (duplicatedNames.length) { + console.warn( + `[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.` + ); + } + return resolvedExtensions; +} +function getTextBetween(startNode, range, options) { + const { from: from2, to } = range; + const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; + let text = ""; + startNode.nodesBetween(from2, to, (node, pos, parent, index) => { + var _a; + if (node.isBlock && pos > from2) { + text += blockSeparator; + } + const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name]; + if (textSerializer) { + if (parent) { + text += textSerializer({ + node, + pos, + parent, + index, + range + }); + } + return false; + } + if (node.isText) { + text += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from2, pos) - pos, to - pos); + } + }); + return text; +} +function getText(node, options) { + const range = { + from: 0, + to: node.content.size + }; + return getTextBetween(node, range, options); +} +function getTextSerializersFromSchema(schema) { + return Object.fromEntries( + Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText]) + ); +} +function getNodeAttributes(state, typeOrName) { + const type = getNodeType(typeOrName, state.schema); + const { from: from2, to } = state.selection; + const nodes = []; + state.doc.nodesBetween(from2, to, (node2) => { + nodes.push(node2); + }); + const node = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name); + if (!node) { + return {}; + } + return { ...node.attrs }; +} +function getAttributes(state, typeOrName) { + const schemaType = getSchemaTypeNameByName( + typeof typeOrName === "string" ? typeOrName : typeOrName.name, + state.schema + ); + if (schemaType === "node") { + return getNodeAttributes(state, typeOrName); + } + if (schemaType === "mark") { + return getMarkAttributes(state, typeOrName); + } + return {}; +} +function removeDuplicates(array, by = JSON.stringify) { + const seen = {}; + return array.filter((item) => { + const key = by(item); + return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true; + }); +} +function simplifyChangedRanges(changes) { + const uniqueChanges = removeDuplicates(changes); + return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => { + const rest = uniqueChanges.filter((_, i) => i !== index); + return !rest.some((otherChange) => { + return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to; + }); + }); +} +function getChangedRanges(transform) { + const { mapping, steps } = transform; + const changes = []; + mapping.maps.forEach((stepMap, index) => { + const ranges = []; + if (!stepMap.ranges.length) { + const { from: from2, to } = steps[index]; + if (from2 === void 0 || to === void 0) { + return; + } + ranges.push({ from: from2, to }); + } else { + stepMap.forEach((from2, to) => { + ranges.push({ from: from2, to }); + }); + } + ranges.forEach(({ from: from2, to }) => { + const newStart = mapping.slice(index).map(from2, -1); + const newEnd = mapping.slice(index).map(to); + const oldStart = mapping.invert().map(newStart, -1); + const oldEnd = mapping.invert().map(newEnd); + changes.push({ + oldRange: { + from: oldStart, + to: oldEnd + }, + newRange: { + from: newStart, + to: newEnd + } + }); + }); + }); + return simplifyChangedRanges(changes); +} +function getMarksBetween(from2, to, doc2) { + const marks = []; + if (from2 === to) { + doc2.resolve(from2).marks().forEach((mark) => { + const $pos = doc2.resolve(from2); + const range = getMarkRange($pos, mark.type); + if (!range) { + return; + } + marks.push({ + mark, + ...range + }); + }); + } else { + doc2.nodesBetween(from2, to, (node, pos) => { + if (!node || (node == null ? void 0 : node.nodeSize) === void 0) { + return; + } + marks.push( + ...node.marks.map((mark) => ({ + from: pos, + to: pos + node.nodeSize, + mark + })) + ); + }); + } + return marks; +} +var getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => { + const $pos = state.doc.resolve(pos); + let currentDepth = maxDepth; + let node = null; + while (currentDepth > 0 && node === null) { + const currentNode = $pos.node(currentDepth); + if ((currentNode == null ? void 0 : currentNode.type.name) === typeOrName) { + node = currentNode; + } else { + currentDepth -= 1; + } + } + return [node, currentDepth]; +}; +function getSchemaTypeByName(name, schema) { + return schema.nodes[name] || schema.marks[name] || null; +} +function getSplittedAttributes(extensionAttributes, typeName, attributes) { + return Object.fromEntries( + Object.entries(attributes).filter(([name]) => { + const extensionAttribute = extensionAttributes.find((item) => { + return item.type === typeName && item.name === name; + }); + if (!extensionAttribute) { + return false; + } + return extensionAttribute.attribute.keepOnSplit; + }) + ); +} +var getTextContentFromNodes = ($from, maxMatch = 500) => { + let textBefore = ""; + const sliceEndPos = $from.parentOffset; + $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => { + var _a, _b; + const chunk = ((_b = (_a = node.type.spec).toText) == null ? void 0 : _b.call(_a, { + node, + pos, + parent, + index + })) || node.textContent || "%leaf%"; + textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos)); + }); + return textBefore; +}; +function isMarkActive(state, typeOrName, attributes = {}) { + const { empty: empty2, ranges } = state.selection; + const type = typeOrName ? getMarkType(typeOrName, state.schema) : null; + if (empty2) { + return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => { + if (!type) { + return true; + } + return type.name === mark.type.name; + }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false })); + } + let selectionRange = 0; + const markRanges = []; + ranges.forEach(({ $from, $to }) => { + const from2 = $from.pos; + const to = $to.pos; + state.doc.nodesBetween(from2, to, (node, pos) => { + if (type && node.inlineContent && !node.type.allowsMarkType(type)) { + return false; + } + if (!node.isText && !node.marks.length) { + return; + } + const relativeFrom = Math.max(from2, pos); + const relativeTo = Math.min(to, pos + node.nodeSize); + const range2 = relativeTo - relativeFrom; + selectionRange += range2; + markRanges.push( + ...node.marks.map((mark) => ({ + mark, + from: relativeFrom, + to: relativeTo + })) + ); + }); + }); + if (selectionRange === 0) { + return false; + } + const matchedRange = markRanges.filter((markRange) => { + if (!type) { + return true; + } + return type.name === markRange.mark.type.name; + }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); + const excludedRange = markRanges.filter((markRange) => { + if (!type) { + return true; + } + return markRange.mark.type !== type && markRange.mark.type.excludes(type); + }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); + const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange; + return range >= selectionRange; +} +function isActive(state, name, attributes = {}) { + if (!name) { + return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes); + } + const schemaType = getSchemaTypeNameByName(name, state.schema); + if (schemaType === "node") { + return isNodeActive(state, name, attributes); + } + if (schemaType === "mark") { + return isMarkActive(state, name, attributes); + } + return false; +} +var isAtEndOfNode = (state, nodeType) => { + const { $from, $to, $anchor } = state.selection; + if (nodeType) { + const parentNode2 = findParentNode((node) => node.type.name === nodeType)(state.selection); + if (!parentNode2) { + return false; + } + const $parentPos = state.doc.resolve(parentNode2.pos + 1); + if ($anchor.pos + 1 === $parentPos.end()) { + return true; + } + return false; + } + if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) { + return false; + } + return true; +}; +var isAtStartOfNode = (state) => { + const { $from, $to } = state.selection; + if ($from.parentOffset > 0 || $from.pos !== $to.pos) { + return false; + } + return true; +}; +function isExtensionRulesEnabled(extension, enabled) { + if (Array.isArray(enabled)) { + return enabled.some((enabledExtension) => { + const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name; + return name === extension.name; + }); + } + return enabled; +} +function isList(name, extensions) { + const { nodeExtensions } = splitExtensions(extensions); + const extension = nodeExtensions.find((item) => item.name === name); + if (!extension) { + return false; + } + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + const group = callOrReturn(getExtensionField(extension, "group", context)); + if (typeof group !== "string") { + return false; + } + return group.split(" ").includes("list"); +} +function isNodeEmpty(node, { + checkChildren = true, + ignoreWhitespace = false +} = {}) { + var _a; + if (ignoreWhitespace) { + if (node.type.name === "hardBreak") { + return true; + } + if (node.isText) { + return !/\S/.test((_a = node.text) != null ? _a : ""); + } + } + if (node.isText) { + return !node.text; + } + if (node.isAtom || node.isLeaf) { + return false; + } + if (node.content.childCount === 0) { + return true; + } + if (checkChildren) { + let isContentEmpty = true; + node.content.forEach((childNode) => { + if (isContentEmpty === false) { + return; + } + if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) { + isContentEmpty = false; + } + }); + return isContentEmpty; + } + return false; +} +function isNodeSelection(value) { + return value instanceof NodeSelection; +} +var MappablePosition = class _MappablePosition { + constructor(position) { + this.position = position; + } + /** + * Creates a MappablePosition from a JSON object. + */ + static fromJSON(json) { + return new _MappablePosition(json.position); + } + /** + * Converts the MappablePosition to a JSON object. + */ + toJSON() { + return { + position: this.position + }; + } +}; +function getUpdatedPosition(position, transaction) { + const mapResult = transaction.mapping.mapResult(position.position); + return { + position: new MappablePosition(mapResult.pos), + mapResult + }; +} +function createMappablePosition(position) { + return new MappablePosition(position); +} +function canSetMark(state, tr2, newMarkType) { + var _a; + const { selection } = tr2; + let cursor = null; + if (isTextSelection(selection)) { + cursor = selection.$cursor; + } + if (cursor) { + const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks(); + const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType); + return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType))); + } + const { ranges } = selection; + return ranges.some(({ $from, $to }) => { + let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false; + state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => { + if (someNodeSupportsMark) { + return false; + } + if (node.isInline) { + const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType); + const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType)); + someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType; + } + return !someNodeSupportsMark; + }); + return someNodeSupportsMark; + }); +} +var setMark = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => { + const { selection } = tr2; + const { empty: empty2, ranges } = selection; + const type = getMarkType(typeOrName, state.schema); + if (dispatch) { + if (empty2) { + const oldAttributes = getMarkAttributes(state, type); + tr2.addStoredMark( + type.create({ + ...oldAttributes, + ...attributes + }) + ); + } else { + ranges.forEach((range) => { + const from2 = range.$from.pos; + const to = range.$to.pos; + state.doc.nodesBetween(from2, to, (node, pos) => { + const trimmedFrom = Math.max(pos, from2); + const trimmedTo = Math.min(pos + node.nodeSize, to); + const someHasMark = node.marks.find((mark) => mark.type === type); + if (someHasMark) { + node.marks.forEach((mark) => { + if (type === mark.type) { + tr2.addMark( + trimmedFrom, + trimmedTo, + type.create({ + ...mark.attrs, + ...attributes + }) + ); + } + }); + } else { + tr2.addMark(trimmedFrom, trimmedTo, type.create(attributes)); + } + }); + }); + } + } + return canSetMark(state, tr2, type); +}; +var setMeta = (key, value) => ({ tr: tr2 }) => { + tr2.setMeta(key, value); + return true; +}; +var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => { + const type = getNodeType(typeOrName, state.schema); + let attributesToCopy; + if (state.selection.$anchor.sameParent(state.selection.$head)) { + attributesToCopy = state.selection.$anchor.parent.attrs; + } + if (!type.isTextblock) { + console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'); + return false; + } + return chain().command(({ commands }) => { + const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state); + if (canSetBlock) { + return true; + } + return commands.clearNodes(); + }).command(({ state: updatedState }) => { + return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch); + }).run(); +}; +var setNodeSelection = (position) => ({ tr: tr2, dispatch }) => { + if (dispatch) { + const { doc: doc2 } = tr2; + const from2 = minMax(position, 0, doc2.content.size); + const selection = NodeSelection.create(doc2, from2); + tr2.setSelection(selection); + } + return true; +}; +var setTextDirection = (direction, position) => ({ tr: tr2, state, dispatch }) => { + const { selection } = state; + let from2; + let to; + if (typeof position === "number") { + from2 = position; + to = position; + } else if (position && "from" in position && "to" in position) { + from2 = position.from; + to = position.to; + } else { + from2 = selection.from; + to = selection.to; + } + if (dispatch) { + tr2.doc.nodesBetween(from2, to, (node, pos) => { + if (node.isText) { + return; + } + tr2.setNodeMarkup(pos, void 0, { + ...node.attrs, + dir: direction + }); + }); + } + return true; +}; +var setTextSelection = (position) => ({ tr: tr2, dispatch }) => { + if (dispatch) { + const { doc: doc2 } = tr2; + const { from: from2, to } = typeof position === "number" ? { from: position, to: position } : position; + const minPos = TextSelection.atStart(doc2).from; + const maxPos = TextSelection.atEnd(doc2).to; + const resolvedFrom = minMax(from2, minPos, maxPos); + const resolvedEnd = minMax(to, minPos, maxPos); + const selection = TextSelection.create(doc2, resolvedFrom, resolvedEnd); + tr2.setSelection(selection); + } + return true; +}; +var sinkListItem = (typeOrName) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return sinkListItem$1(type)(state, dispatch); +}; +function ensureMarks(state, splittableMarks) { + const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks(); + if (marks) { + const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name)); + state.tr.ensureMarks(filteredMarks); + } +} +var splitBlock = ({ keepMarks = true } = {}) => ({ tr: tr2, state, dispatch, editor }) => { + const { selection, doc: doc2 } = tr2; + const { $from, $to } = selection; + const extensionAttributes = editor.extensionManager.attributes; + const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs); + if (selection instanceof NodeSelection && selection.node.isBlock) { + if (!$from.parentOffset || !canSplit(doc2, $from.pos)) { + return false; + } + if (dispatch) { + if (keepMarks) { + ensureMarks(state, editor.extensionManager.splittableMarks); + } + tr2.split($from.pos).scrollIntoView(); + } + return true; + } + if (!$from.parent.isBlock) { + return false; + } + const atEnd = $to.parentOffset === $to.parent.content.size; + const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1))); + let types = atEnd && deflt ? [ + { + type: deflt, + attrs: newAttributes + } + ] : void 0; + let can = canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, types); + if (!types && !can && canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) { + can = true; + types = deflt ? [ + { + type: deflt, + attrs: newAttributes + } + ] : void 0; + } + if (dispatch) { + if (can) { + if (selection instanceof TextSelection) { + tr2.deleteSelection(); + } + tr2.split(tr2.mapping.map($from.pos), 1, types); + if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) { + const first2 = tr2.mapping.map($from.before()); + const $first = tr2.doc.resolve(first2); + if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) { + tr2.setNodeMarkup(tr2.mapping.map($from.before()), deflt); + } + } + } + if (keepMarks) { + ensureMarks(state, editor.extensionManager.splittableMarks); + } + tr2.scrollIntoView(); + } + return can; +}; +var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr2, state, dispatch, editor }) => { + var _a; + const type = getNodeType(typeOrName, state.schema); + const { $from, $to } = state.selection; + const node = state.selection.node; + if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) { + return false; + } + const grandParent = $from.node(-1); + if (grandParent.type !== type) { + return false; + } + const extensionAttributes = editor.extensionManager.attributes; + if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) { + if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) { + return false; + } + if (dispatch) { + let wrap2 = Fragment.empty; + const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3; + for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) { + wrap2 = Fragment.from($from.node(d).copy(wrap2)); + } + const depthAfter = ( + // eslint-disable-next-line no-nested-ternary + $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3 + ); + const newNextTypeAttributes2 = { + ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), + ...overrideAttrs + }; + const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0; + wrap2 = wrap2.append(Fragment.from(type.createAndFill(null, nextType2) || void 0)); + const start = $from.before($from.depth - (depthBefore - 1)); + tr2.replace(start, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0)); + let sel = -1; + tr2.doc.nodesBetween(start, tr2.doc.content.size, (n, pos) => { + if (sel > -1) { + return false; + } + if (n.isTextblock && n.content.size === 0) { + sel = pos + 1; + } + }); + if (sel > -1) { + tr2.setSelection(TextSelection.near(tr2.doc.resolve(sel))); + } + tr2.scrollIntoView(); + } + return true; + } + const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null; + const newTypeAttributes = { + ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs), + ...overrideAttrs + }; + const newNextTypeAttributes = { + ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), + ...overrideAttrs + }; + tr2.delete($from.pos, $to.pos); + const types = nextType ? [ + { type, attrs: newTypeAttributes }, + { type: nextType, attrs: newNextTypeAttributes } + ] : [{ type, attrs: newTypeAttributes }]; + if (!canSplit(tr2.doc, $from.pos, 2)) { + return false; + } + if (dispatch) { + const { selection, storedMarks } = state; + const { splittableMarks } = editor.extensionManager; + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + tr2.split($from.pos, 2, types).scrollIntoView(); + if (!marks || !dispatch) { + return true; + } + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr2.ensureMarks(filteredMarks); + } + return true; +}; +var joinListBackwards = (tr2, listType) => { + const list = findParentNode((node) => node.type === listType)(tr2.selection); + if (!list) { + return true; + } + const before = tr2.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth); + if (before === void 0) { + return true; + } + const nodeBefore = tr2.doc.nodeAt(before); + const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr2.doc, list.pos); + if (!canJoinBackwards) { + return true; + } + tr2.join(list.pos); + return true; +}; +var joinListForwards = (tr2, listType) => { + const list = findParentNode((node) => node.type === listType)(tr2.selection); + if (!list) { + return true; + } + const after = tr2.doc.resolve(list.start).after(list.depth); + if (after === void 0) { + return true; + } + const nodeAfter = tr2.doc.nodeAt(after); + const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr2.doc, after); + if (!canJoinForwards) { + return true; + } + tr2.join(after); + return true; +}; +var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr2, state, dispatch, chain, commands, can }) => { + const { extensions, splittableMarks } = editor.extensionManager; + const listType = getNodeType(listTypeOrName, state.schema); + const itemType = getNodeType(itemTypeOrName, state.schema); + const { selection, storedMarks } = state; + const { $from, $to } = selection; + const range = $from.blockRange($to); + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + if (!range) { + return false; + } + const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection); + if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) { + if (parentList.node.type === listType) { + return commands.liftListItem(itemType); + } + if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) { + return chain().command(() => { + tr2.setNodeMarkup(parentList.pos, listType); + return true; + }).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); + } + } + if (!keepMarks || !marks || !dispatch) { + return chain().command(() => { + const canWrapInList = can().wrapInList(listType, attributes); + if (canWrapInList) { + return true; + } + return commands.clearNodes(); + }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); + } + return chain().command(() => { + const canWrapInList = can().wrapInList(listType, attributes); + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr2.ensureMarks(filteredMarks); + if (canWrapInList) { + return true; + } + return commands.clearNodes(); + }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); +}; +var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => { + const { extendEmptyMarkRange = false } = options; + const type = getMarkType(typeOrName, state.schema); + const isActive2 = isMarkActive(state, type, attributes); + if (isActive2) { + return commands.unsetMark(type, { extendEmptyMarkRange }); + } + return commands.setMark(type, attributes); +}; +var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => { + const type = getNodeType(typeOrName, state.schema); + const toggleType = getNodeType(toggleTypeOrName, state.schema); + const isActive2 = isNodeActive(state, type, attributes); + let attributesToCopy; + if (state.selection.$anchor.sameParent(state.selection.$head)) { + attributesToCopy = state.selection.$anchor.parent.attrs; + } + if (isActive2) { + return commands.setNode(toggleType, attributesToCopy); + } + return commands.setNode(type, { ...attributesToCopy, ...attributes }); +}; +var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => { + const type = getNodeType(typeOrName, state.schema); + const isActive2 = isNodeActive(state, type, attributes); + if (isActive2) { + return commands.lift(type); + } + return commands.wrapIn(type, attributes); +}; +var undoInputRule = () => ({ state, dispatch }) => { + const plugins = state.plugins; + for (let i = 0; i < plugins.length; i += 1) { + const plugin = plugins[i]; + let undoable; + if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { + if (dispatch) { + const tr2 = state.tr; + const toUndo = undoable.transform; + for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) { + tr2.step(toUndo.steps[j].invert(toUndo.docs[j])); + } + if (undoable.text) { + const marks = tr2.doc.resolve(undoable.from).marks(); + tr2.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)); + } else { + tr2.delete(undoable.from, undoable.to); + } + } + return true; + } + } + return false; +}; +var unsetAllMarks = () => ({ tr: tr2, dispatch }) => { + const { selection } = tr2; + const { empty: empty2, ranges } = selection; + if (empty2) { + return true; + } + if (dispatch) { + ranges.forEach((range) => { + tr2.removeMark(range.$from.pos, range.$to.pos); + }); + } + return true; +}; +var unsetMark = (typeOrName, options = {}) => ({ tr: tr2, state, dispatch }) => { + var _a; + const { extendEmptyMarkRange = false } = options; + const { selection } = tr2; + const type = getMarkType(typeOrName, state.schema); + const { $from, empty: empty2, ranges } = selection; + if (!dispatch) { + return true; + } + if (empty2 && extendEmptyMarkRange) { + let { from: from2, to } = selection; + const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs; + const range = getMarkRange($from, type, attrs); + if (range) { + from2 = range.from; + to = range.to; + } + tr2.removeMark(from2, to, type); + } else { + ranges.forEach((range) => { + tr2.removeMark(range.$from.pos, range.$to.pos, type); + }); + } + tr2.removeStoredMark(type); + return true; +}; +var unsetTextDirection = (position) => ({ tr: tr2, state, dispatch }) => { + const { selection } = state; + let from2; + let to; + if (typeof position === "number") { + from2 = position; + to = position; + } else if (position && "from" in position && "to" in position) { + from2 = position.from; + to = position.to; + } else { + from2 = selection.from; + to = selection.to; + } + if (dispatch) { + tr2.doc.nodesBetween(from2, to, (node, pos) => { + if (node.isText) { + return; + } + const newAttrs = { ...node.attrs }; + delete newAttrs.dir; + tr2.setNodeMarkup(pos, void 0, newAttrs); + }); + } + return true; +}; +var updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => { + let nodeType = null; + let markType = null; + const schemaType = getSchemaTypeNameByName( + typeof typeOrName === "string" ? typeOrName : typeOrName.name, + state.schema + ); + if (!schemaType) { + return false; + } + if (schemaType === "node") { + nodeType = getNodeType(typeOrName, state.schema); + } + if (schemaType === "mark") { + markType = getMarkType(typeOrName, state.schema); + } + let canUpdate = false; + tr2.selection.ranges.forEach((range) => { + const from2 = range.$from.pos; + const to = range.$to.pos; + let lastPos; + let lastNode; + let trimmedFrom; + let trimmedTo; + if (tr2.selection.empty) { + state.doc.nodesBetween(from2, to, (node, pos) => { + if (nodeType && nodeType === node.type) { + canUpdate = true; + trimmedFrom = Math.max(pos, from2); + trimmedTo = Math.min(pos + node.nodeSize, to); + lastPos = pos; + lastNode = node; + } + }); + } else { + state.doc.nodesBetween(from2, to, (node, pos) => { + if (pos < from2 && nodeType && nodeType === node.type) { + canUpdate = true; + trimmedFrom = Math.max(pos, from2); + trimmedTo = Math.min(pos + node.nodeSize, to); + lastPos = pos; + lastNode = node; + } + if (pos >= from2 && pos <= to) { + if (nodeType && nodeType === node.type) { + canUpdate = true; + if (dispatch) { + tr2.setNodeMarkup(pos, void 0, { + ...node.attrs, + ...attributes + }); + } + } + if (markType && node.marks.length) { + node.marks.forEach((mark) => { + if (markType === mark.type) { + canUpdate = true; + if (dispatch) { + const trimmedFrom2 = Math.max(pos, from2); + const trimmedTo2 = Math.min(pos + node.nodeSize, to); + tr2.addMark( + trimmedFrom2, + trimmedTo2, + markType.create({ + ...mark.attrs, + ...attributes + }) + ); + } + } + }); + } + } + }); + } + if (lastNode) { + if (lastPos !== void 0 && dispatch) { + tr2.setNodeMarkup(lastPos, void 0, { + ...lastNode.attrs, + ...attributes + }); + } + if (markType && lastNode.marks.length) { + lastNode.marks.forEach((mark) => { + if (markType === mark.type && dispatch) { + tr2.addMark( + trimmedFrom, + trimmedTo, + markType.create({ + ...mark.attrs, + ...attributes + }) + ); + } + }); + } + } + }); + return canUpdate; +}; +var wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return wrapIn$1(type, attributes)(state, dispatch); +}; +var wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return wrapInList$1(type, attributes)(state, dispatch); +}; +var EventEmitter = class { + constructor() { + this.callbacks = {}; + } + on(event, fn) { + if (!this.callbacks[event]) { + this.callbacks[event] = []; + } + this.callbacks[event].push(fn); + return this; + } + emit(event, ...args) { + const callbacks = this.callbacks[event]; + if (callbacks) { + callbacks.forEach((callback) => callback.apply(this, args)); + } + return this; + } + off(event, fn) { + const callbacks = this.callbacks[event]; + if (callbacks) { + if (fn) { + this.callbacks[event] = callbacks.filter((callback) => callback !== fn); + } else { + delete this.callbacks[event]; + } + } + return this; + } + once(event, fn) { + const onceFn = (...args) => { + this.off(event, onceFn); + fn.apply(this, args); + }; + return this.on(event, onceFn); + } + removeAllListeners() { + this.callbacks = {}; + } +}; +var InputRule = class { + constructor(config) { + var _a; + this.find = config.find; + this.handler = config.handler; + this.undoable = (_a = config.undoable) != null ? _a : true; + } +}; +var inputRuleMatcherHandler = (text, find2) => { + if (isRegExp(find2)) { + return find2.exec(text); + } + const inputRuleMatch = find2(text); + if (!inputRuleMatch) { + return null; + } + const result = [inputRuleMatch.text]; + result.index = inputRuleMatch.index; + result.input = text; + result.data = inputRuleMatch.data; + if (inputRuleMatch.replaceWith) { + if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) { + console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'); + } + result.push(inputRuleMatch.replaceWith); + } + return result; +}; +function run$2(config) { + var _a; + const { editor, from: from2, to, text, rules, plugin } = config; + const { view } = editor; + if (view.composing) { + return false; + } + const $from = view.state.doc.resolve(from2); + if ( + // check for code node + $from.parent.type.spec.code || // check for code mark + !!((_a = $from.nodeBefore || $from.nodeAfter) == null ? void 0 : _a.marks.find((mark) => mark.type.spec.code)) + ) { + return false; + } + let matched = false; + const textBefore = getTextContentFromNodes($from) + text; + rules.forEach((rule) => { + if (matched) { + return; + } + const match = inputRuleMatcherHandler(textBefore, rule.find); + if (!match) { + return; + } + const tr2 = view.state.tr; + const state = createChainableState({ + state: view.state, + transaction: tr2 + }); + const range = { + from: from2 - (match[0].length - text.length), + to + }; + const { commands, chain, can } = new CommandManager({ + editor, + state + }); + const handler = rule.handler({ + state, + range, + match, + commands, + chain, + can + }); + if (handler === null || !tr2.steps.length) { + return; + } + if (rule.undoable) { + tr2.setMeta(plugin, { + transform: tr2, + from: from2, + to, + text + }); + } + view.dispatch(tr2); + matched = true; + }); + return matched; +} +function inputRulesPlugin(props) { + const { editor, rules } = props; + const plugin = new Plugin({ + state: { + init() { + return null; + }, + apply(tr2, prev, state) { + const stored = tr2.getMeta(plugin); + if (stored) { + return stored; + } + const simulatedInputMeta = tr2.getMeta("applyInputRules"); + const isSimulatedInput = !!simulatedInputMeta; + if (isSimulatedInput) { + setTimeout(() => { + let { text } = simulatedInputMeta; + if (typeof text === "string") { + text = text; + } else { + text = getHTMLFromFragment(Fragment.from(text), state.schema); + } + const { from: from2 } = simulatedInputMeta; + const to = from2 + text.length; + run$2({ + editor, + from: from2, + to, + text, + rules, + plugin + }); + }); + } + return tr2.selectionSet || tr2.docChanged ? null : prev; + } + }, + props: { + handleTextInput(view, from2, to, text) { + return run$2({ + editor, + from: from2, + to, + text, + rules, + plugin + }); + }, + handleDOMEvents: { + compositionend: (view) => { + setTimeout(() => { + const { $cursor } = view.state.selection; + if ($cursor) { + run$2({ + editor, + from: $cursor.pos, + to: $cursor.pos, + text: "", + rules, + plugin + }); + } + }); + return false; + } + }, + // add support for input rules to trigger on enter + // this is useful for example for code blocks + handleKeyDown(view, event) { + if (event.key !== "Enter") { + return false; + } + const { $cursor } = view.state.selection; + if ($cursor) { + return run$2({ + editor, + from: $cursor.pos, + to: $cursor.pos, + text: "\n", + rules, + plugin + }); + } + return false; + } + }, + // @ts-ignore + isInputRules: true + }); + return plugin; +} +function getType(value) { + return Object.prototype.toString.call(value).slice(8, -1); +} +function isPlainObject(value) { + if (getType(value) !== "Object") { + return false; + } + return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype; +} +function mergeDeep(target, source) { + const output = { ...target }; + if (isPlainObject(target) && isPlainObject(source)) { + Object.keys(source).forEach((key) => { + if (isPlainObject(source[key]) && isPlainObject(target[key])) { + output[key] = mergeDeep(target[key], source[key]); + } else { + output[key] = source[key]; + } + }); + } + return output; +} +var Extendable = class { + constructor(config = {}) { + this.type = "extendable"; + this.parent = null; + this.child = null; + this.name = ""; + this.config = { + name: this.name + }; + this.config = { + ...this.config, + ...config + }; + this.name = this.config.name; + } + get options() { + return { + ...callOrReturn( + getExtensionField(this, "addOptions", { + name: this.name + }) + ) || {} + }; + } + get storage() { + return { + ...callOrReturn( + getExtensionField(this, "addStorage", { + name: this.name, + options: this.options + }) + ) || {} + }; + } + configure(options = {}) { + const extension = this.extend({ + ...this.config, + addOptions: () => { + return mergeDeep(this.options, options); + } + }); + extension.name = this.name; + extension.parent = this.parent; + return extension; + } + extend(extendedConfig = {}) { + const extension = new this.constructor({ ...this.config, ...extendedConfig }); + extension.parent = this; + this.child = extension; + extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name; + return extension; + } +}; +var Mark2 = class _Mark extends Extendable { + constructor() { + super(...arguments); + this.type = "mark"; + } + /** + * Create a new Mark instance + * @param config - Mark configuration object or a function that returns a configuration object + */ + static create(config = {}) { + const resolvedConfig = typeof config === "function" ? config() : config; + return new _Mark(resolvedConfig); + } + static handleExit({ editor, mark }) { + const { tr: tr2 } = editor.state; + const currentPos = editor.state.selection.$from; + const isAtEnd = currentPos.pos === currentPos.end(); + if (isAtEnd) { + const currentMarks = currentPos.marks(); + const isInMark = !!currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name); + if (!isInMark) { + return false; + } + const removeMark2 = currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name); + if (removeMark2) { + tr2.removeStoredMark(removeMark2); + } + tr2.insertText(" ", currentPos.pos); + editor.view.dispatch(tr2); + return true; + } + return false; + } + configure(options) { + return super.configure(options); + } + extend(extendedConfig) { + const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; + return super.extend(resolvedConfig); + } +}; +function isNumber(value) { + return typeof value === "number"; +} +var PasteRule = class { + constructor(config) { + this.find = config.find; + this.handler = config.handler; + } +}; +var pasteRuleMatcherHandler = (text, find2, event) => { + if (isRegExp(find2)) { + return [...text.matchAll(find2)]; + } + const matches2 = find2(text, event); + if (!matches2) { + return []; + } + return matches2.map((pasteRuleMatch) => { + const result = [pasteRuleMatch.text]; + result.index = pasteRuleMatch.index; + result.input = text; + result.data = pasteRuleMatch.data; + if (pasteRuleMatch.replaceWith) { + if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) { + console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'); + } + result.push(pasteRuleMatch.replaceWith); + } + return result; + }); +}; +function run2(config) { + const { editor, state, from: from2, to, rule, pasteEvent, dropEvent } = config; + const { commands, chain, can } = new CommandManager({ + editor, + state + }); + const handlers2 = []; + state.doc.nodesBetween(from2, to, (node, pos) => { + var _a, _b, _c, _d, _e; + if (((_b = (_a = node.type) == null ? void 0 : _a.spec) == null ? void 0 : _b.code) || !(node.isText || node.isTextblock || node.isInline)) { + return; + } + const contentSize = (_e = (_d = (_c = node.content) == null ? void 0 : _c.size) != null ? _d : node.nodeSize) != null ? _e : 0; + const resolvedFrom = Math.max(from2, pos); + const resolvedTo = Math.min(to, pos + contentSize); + if (resolvedFrom >= resolvedTo) { + return; + } + const textToMatch = node.isText ? node.text || "" : node.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, ""); + const matches2 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent); + matches2.forEach((match) => { + if (match.index === void 0) { + return; + } + const start = resolvedFrom + match.index + 1; + const end = start + match[0].length; + const range = { + from: state.tr.mapping.map(start), + to: state.tr.mapping.map(end) + }; + const handler = rule.handler({ + state, + range, + match, + commands, + chain, + can, + pasteEvent, + dropEvent + }); + handlers2.push(handler); + }); + }); + const success = handlers2.every((handler) => handler !== null); + return success; +} +var tiptapDragFromOtherEditor = null; +var createClipboardPasteEvent = (text) => { + var _a; + const event = new ClipboardEvent("paste", { + clipboardData: new DataTransfer() + }); + (_a = event.clipboardData) == null ? void 0 : _a.setData("text/html", text); + return event; +}; +function pasteRulesPlugin(props) { + const { editor, rules } = props; + let dragSourceElement = null; + let isPastedFromProseMirror = false; + let isDroppedFromProseMirror = false; + let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; + let dropEvent; + try { + dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; + } catch { + dropEvent = null; + } + const processEvent = ({ + state, + from: from2, + to, + rule, + pasteEvt + }) => { + const tr2 = state.tr; + const chainableState = createChainableState({ + state, + transaction: tr2 + }); + const handler = run2({ + editor, + state: chainableState, + from: Math.max(from2 - 1, 0), + to: to.b - 1, + rule, + pasteEvent: pasteEvt, + dropEvent + }); + if (!handler || !tr2.steps.length) { + return; + } + try { + dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; + } catch { + dropEvent = null; + } + pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; + return tr2; + }; + const plugins = rules.map((rule) => { + return new Plugin({ + // we register a global drag handler to track the current drag source element + view(view) { + const handleDragstart = (event) => { + var _a; + dragSourceElement = ((_a = view.dom.parentElement) == null ? void 0 : _a.contains(event.target)) ? view.dom.parentElement : null; + if (dragSourceElement) { + tiptapDragFromOtherEditor = editor; + } + }; + const handleDragend = () => { + if (tiptapDragFromOtherEditor) { + tiptapDragFromOtherEditor = null; + } + }; + window.addEventListener("dragstart", handleDragstart); + window.addEventListener("dragend", handleDragend); + return { + destroy() { + window.removeEventListener("dragstart", handleDragstart); + window.removeEventListener("dragend", handleDragend); + } + }; + }, + props: { + handleDOMEvents: { + drop: (view, event) => { + isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement; + dropEvent = event; + if (!isDroppedFromProseMirror) { + const dragFromOtherEditor = tiptapDragFromOtherEditor; + if (dragFromOtherEditor == null ? void 0 : dragFromOtherEditor.isEditable) { + setTimeout(() => { + const selection = dragFromOtherEditor.state.selection; + if (selection) { + dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to }); + } + }, 10); + } + } + return false; + }, + paste: (_view, event) => { + var _a; + const html = (_a = event.clipboardData) == null ? void 0 : _a.getData("text/html"); + pasteEvent = event; + isPastedFromProseMirror = !!(html == null ? void 0 : html.includes("data-pm-slice")); + return false; + } + } + }, + appendTransaction: (transactions, oldState, state) => { + const transaction = transactions[0]; + const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror; + const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror; + const simulatedPasteMeta = transaction.getMeta("applyPasteRules"); + const isSimulatedPaste = !!simulatedPasteMeta; + if (!isPaste && !isDrop && !isSimulatedPaste) { + return; + } + if (isSimulatedPaste) { + let { text } = simulatedPasteMeta; + if (typeof text === "string") { + text = text; + } else { + text = getHTMLFromFragment(Fragment.from(text), state.schema); + } + const { from: from22 } = simulatedPasteMeta; + const to2 = from22 + text.length; + const pasteEvt = createClipboardPasteEvent(text); + return processEvent({ + rule, + state, + from: from22, + to: { b: to2 }, + pasteEvt + }); + } + const from2 = oldState.doc.content.findDiffStart(state.doc.content); + const to = oldState.doc.content.findDiffEnd(state.doc.content); + if (!isNumber(from2) || !to || from2 === to.b) { + return; + } + return processEvent({ + rule, + state, + from: from2, + to, + pasteEvt: pasteEvent + }); + } + }); + }); + return plugins; +} +var ExtensionManager = class { + constructor(extensions, editor) { + this.splittableMarks = []; + this.editor = editor; + this.baseExtensions = extensions; + this.extensions = resolveExtensions(extensions); + this.schema = getSchemaByResolvedExtensions(this.extensions, editor); + this.setupExtensions(); + } + /** + * Get all commands from the extensions. + * @returns An object with all commands where the key is the command name and the value is the command function + */ + get commands() { + return this.extensions.reduce((commands, extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor: this.editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const addCommands = getExtensionField(extension, "addCommands", context); + if (!addCommands) { + return commands; + } + return { + ...commands, + ...addCommands() + }; + }, {}); + } + /** + * Get all registered Prosemirror plugins from the extensions. + * @returns An array of Prosemirror plugins + */ + get plugins() { + const { editor } = this; + const extensions = sortExtensions([...this.extensions].reverse()); + const allPlugins = extensions.flatMap((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const plugins = []; + const addKeyboardShortcuts = getExtensionField( + extension, + "addKeyboardShortcuts", + context + ); + let defaultBindings = {}; + if (extension.type === "mark" && getExtensionField(extension, "exitable", context)) { + defaultBindings.ArrowRight = () => Mark2.handleExit({ editor, mark: extension }); + } + if (addKeyboardShortcuts) { + const bindings = Object.fromEntries( + Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => { + return [shortcut, () => method({ editor })]; + }) + ); + defaultBindings = { ...defaultBindings, ...bindings }; + } + const keyMapPlugin = keymap(defaultBindings); + plugins.push(keyMapPlugin); + const addInputRules = getExtensionField(extension, "addInputRules", context); + if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) { + const rules = addInputRules(); + if (rules && rules.length) { + const inputResult = inputRulesPlugin({ + editor, + rules + }); + const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]; + plugins.push(...inputPlugins); + } + } + const addPasteRules = getExtensionField(extension, "addPasteRules", context); + if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) { + const rules = addPasteRules(); + if (rules && rules.length) { + const pasteRules = pasteRulesPlugin({ editor, rules }); + plugins.push(...pasteRules); + } + } + const addProseMirrorPlugins = getExtensionField( + extension, + "addProseMirrorPlugins", + context + ); + if (addProseMirrorPlugins) { + const proseMirrorPlugins = addProseMirrorPlugins(); + plugins.push(...proseMirrorPlugins); + } + return plugins; + }); + return allPlugins; + } + /** + * Get all attributes from the extensions. + * @returns An array of attributes + */ + get attributes() { + return getAttributesFromExtensions(this.extensions); + } + /** + * Get all node views from the extensions. + * @returns An object with all node views where the key is the node name and the value is the node view function + */ + get nodeViews() { + const { editor } = this; + const { nodeExtensions } = splitExtensions(this.extensions); + return Object.fromEntries( + nodeExtensions.filter((extension) => !!getExtensionField(extension, "addNodeView")).map((extension) => { + const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getNodeType(extension.name, this.schema) + }; + const addNodeView = getExtensionField(extension, "addNodeView", context); + if (!addNodeView) { + return []; + } + const nodeViewResult = addNodeView(); + if (!nodeViewResult) { + return []; + } + const nodeview = (node, view, getPos, decorations, innerDecorations) => { + const HTMLAttributes = getRenderedAttributes(node, extensionAttributes); + return nodeViewResult({ + // pass-through + node, + view, + getPos, + decorations, + innerDecorations, + // tiptap-specific + editor, + extension, + HTMLAttributes + }); + }; + return [extension.name, nodeview]; + }) + ); + } + /** + * Get the composed dispatchTransaction function from all extensions. + * @param baseDispatch The base dispatch function (e.g. from the editor or user props) + * @returns A composed dispatch function + */ + dispatchTransaction(baseDispatch) { + const { editor } = this; + const extensions = sortExtensions([...this.extensions].reverse()); + return extensions.reduceRight((next, extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const dispatchTransaction = getExtensionField( + extension, + "dispatchTransaction", + context + ); + if (!dispatchTransaction) { + return next; + } + return (transaction) => { + dispatchTransaction.call(context, { transaction, next }); + }; + }, baseDispatch); + } + /** + * Get the composed transformPastedHTML function from all extensions. + * @param baseTransform The base transform function (e.g. from the editor props) + * @returns A composed transform function that chains all extension transforms + */ + transformPastedHTML(baseTransform) { + const { editor } = this; + const extensions = sortExtensions([...this.extensions]); + return extensions.reduce( + (transform, extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const extensionTransform = getExtensionField( + extension, + "transformPastedHTML", + context + ); + if (!extensionTransform) { + return transform; + } + return (html, view) => { + const transformedHtml = transform(html, view); + return extensionTransform.call(context, transformedHtml); + }; + }, + baseTransform || ((html) => html) + ); + } + get markViews() { + const { editor } = this; + const { markExtensions } = splitExtensions(this.extensions); + return Object.fromEntries( + markExtensions.filter((extension) => !!getExtensionField(extension, "addMarkView")).map((extension) => { + const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getMarkType(extension.name, this.schema) + }; + const addMarkView = getExtensionField(extension, "addMarkView", context); + if (!addMarkView) { + return []; + } + const markView = (mark, view, inline) => { + const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes); + return addMarkView()({ + // pass-through + mark, + view, + inline, + // tiptap-specific + editor, + extension, + HTMLAttributes, + updateAttributes: (attrs) => { + updateMarkViewAttributes(mark, editor, attrs); + } + }); + }; + return [extension.name, markView]; + }) + ); + } + /** + * Go through all extensions, create extension storages & setup marks + * & bind editor event listener. + */ + setupExtensions() { + const extensions = this.extensions; + this.editor.extensionStorage = Object.fromEntries( + extensions.map((extension) => [extension.name, extension.storage]) + ); + extensions.forEach((extension) => { + var _a; + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor: this.editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + if (extension.type === "mark") { + const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, "keepOnSplit", context))) != null ? _a : true; + if (keepOnSplit) { + this.splittableMarks.push(extension.name); + } + } + const onBeforeCreate = getExtensionField(extension, "onBeforeCreate", context); + const onCreate = getExtensionField(extension, "onCreate", context); + const onUpdate = getExtensionField(extension, "onUpdate", context); + const onSelectionUpdate = getExtensionField( + extension, + "onSelectionUpdate", + context + ); + const onTransaction = getExtensionField(extension, "onTransaction", context); + const onFocus = getExtensionField(extension, "onFocus", context); + const onBlur = getExtensionField(extension, "onBlur", context); + const onDestroy = getExtensionField(extension, "onDestroy", context); + if (onBeforeCreate) { + this.editor.on("beforeCreate", onBeforeCreate); + } + if (onCreate) { + this.editor.on("create", onCreate); + } + if (onUpdate) { + this.editor.on("update", onUpdate); + } + if (onSelectionUpdate) { + this.editor.on("selectionUpdate", onSelectionUpdate); + } + if (onTransaction) { + this.editor.on("transaction", onTransaction); + } + if (onFocus) { + this.editor.on("focus", onFocus); + } + if (onBlur) { + this.editor.on("blur", onBlur); + } + if (onDestroy) { + this.editor.on("destroy", onDestroy); + } + }); + } +}; +ExtensionManager.resolve = resolveExtensions; +ExtensionManager.sort = sortExtensions; +ExtensionManager.flatten = flattenExtensions; +var extensions_exports = {}; +__export$1(extensions_exports, { + ClipboardTextSerializer: () => ClipboardTextSerializer, + Commands: () => Commands, + Delete: () => Delete, + Drop: () => Drop, + Editable: () => Editable, + FocusEvents: () => FocusEvents, + Keymap: () => Keymap, + Paste: () => Paste, + Tabindex: () => Tabindex, + TextDirection: () => TextDirection, + focusEventsPluginKey: () => focusEventsPluginKey +}); +var Extension = class _Extension extends Extendable { + constructor() { + super(...arguments); + this.type = "extension"; + } + /** + * Create a new Extension instance + * @param config - Extension configuration object or a function that returns a configuration object + */ + static create(config = {}) { + const resolvedConfig = typeof config === "function" ? config() : config; + return new _Extension(resolvedConfig); + } + configure(options) { + return super.configure(options); + } + extend(extendedConfig) { + const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; + return super.extend(resolvedConfig); + } +}; +var ClipboardTextSerializer = Extension.create({ + name: "clipboardTextSerializer", + addOptions() { + return { + blockSeparator: void 0 + }; + }, + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("clipboardTextSerializer"), + props: { + clipboardTextSerializer: () => { + const { editor } = this; + const { state, schema } = editor; + const { doc: doc2, selection } = state; + const { ranges } = selection; + const from2 = Math.min(...ranges.map((range2) => range2.$from.pos)); + const to = Math.max(...ranges.map((range2) => range2.$to.pos)); + const textSerializers = getTextSerializersFromSchema(schema); + const range = { from: from2, to }; + return getTextBetween(doc2, range, { + ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {}, + textSerializers + }); + } + } + }) + ]; + } +}); +var Commands = Extension.create({ + name: "commands", + addCommands() { + return { + ...commands_exports + }; + } +}); +var Delete = Extension.create({ + name: "delete", + onUpdate({ transaction, appendedTransactions }) { + var _a, _b, _c; + const callback = () => { + var _a2, _b2, _c2, _d; + if ((_d = (_c2 = (_b2 = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) { + return; + } + const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]); + const changes = getChangedRanges(nextTransaction); + changes.forEach((change) => { + if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) { + nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from2) => { + const to = from2 + node.nodeSize - 2; + const isFullyWithinRange = change.oldRange.from <= from2 && to <= change.oldRange.to; + this.editor.emit("delete", { + type: "node", + node, + from: from2, + to, + newFrom: nextTransaction.mapping.map(from2), + newTo: nextTransaction.mapping.map(to), + deletedRange: change.oldRange, + newRange: change.newRange, + partial: !isFullyWithinRange, + editor: this.editor, + transaction, + combinedTransform: nextTransaction + }); + }); + } + }); + const mapping = nextTransaction.mapping; + nextTransaction.steps.forEach((step, index) => { + var _a3, _b3; + if (step instanceof RemoveMarkStep) { + const newStart = mapping.slice(index).map(step.from, -1); + const newEnd = mapping.slice(index).map(step.to); + const oldStart = mapping.invert().map(newStart, -1); + const oldEnd = mapping.invert().map(newEnd); + const foundBeforeMark = newStart > 0 ? (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark)) : false; + const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark)); + this.editor.emit("delete", { + type: "mark", + mark: step.mark, + from: step.from, + to: step.to, + deletedRange: { + from: oldStart, + to: oldEnd + }, + newRange: { + from: newStart, + to: newEnd + }, + partial: Boolean(foundAfterMark || foundBeforeMark), + editor: this.editor, + transaction, + combinedTransform: nextTransaction + }); + } + }); + }; + if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) { + setTimeout(callback, 0); + } else { + callback(); + } + } +}); +var Drop = Extension.create({ + name: "drop", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("tiptapDrop"), + props: { + handleDrop: (_, e, slice2, moved) => { + this.editor.emit("drop", { + editor: this.editor, + event: e, + slice: slice2, + moved + }); + } + } + }) + ]; + } +}); +var Editable = Extension.create({ + name: "editable", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("editable"), + props: { + editable: () => this.editor.options.editable + } + }) + ]; + } +}); +var focusEventsPluginKey = new PluginKey("focusEvents"); +var FocusEvents = Extension.create({ + name: "focusEvents", + addProseMirrorPlugins() { + const { editor } = this; + return [ + new Plugin({ + key: focusEventsPluginKey, + props: { + handleDOMEvents: { + focus: (view, event) => { + editor.isFocused = true; + const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false); + view.dispatch(transaction); + return false; + }, + blur: (view, event) => { + editor.isFocused = false; + const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false); + view.dispatch(transaction); + return false; + } + } + } + }) + ]; + } +}); +var Keymap = Extension.create({ + name: "keymap", + addKeyboardShortcuts() { + const handleBackspace2 = () => this.editor.commands.first(({ commands }) => [ + () => commands.undoInputRule(), + // maybe convert first text block node to default node + () => commands.command(({ tr: tr2 }) => { + const { selection, doc: doc2 } = tr2; + const { empty: empty2, $anchor } = selection; + const { pos, parent } = $anchor; + const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr2.doc.resolve(pos - 1) : $anchor; + const parentIsIsolating = $parentPos.parent.type.spec.isolating; + const parentPos = $anchor.pos - $anchor.parentOffset; + const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc2).from === pos; + if (!empty2 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") { + return false; + } + return commands.clearNodes(); + }), + () => commands.deleteSelection(), + () => commands.joinBackward(), + () => commands.selectNodeBackward() + ]); + const handleDelete2 = () => this.editor.commands.first(({ commands }) => [ + () => commands.deleteSelection(), + () => commands.deleteCurrentNode(), + () => commands.joinForward(), + () => commands.selectNodeForward() + ]); + const handleEnter = () => this.editor.commands.first(({ commands }) => [ + () => commands.newlineInCode(), + () => commands.createParagraphNear(), + () => commands.liftEmptyBlock(), + () => commands.splitBlock() + ]); + const baseKeymap = { + Enter: handleEnter, + "Mod-Enter": () => this.editor.commands.exitCode(), + Backspace: handleBackspace2, + "Mod-Backspace": handleBackspace2, + "Shift-Backspace": handleBackspace2, + Delete: handleDelete2, + "Mod-Delete": handleDelete2, + "Mod-a": () => this.editor.commands.selectAll() + }; + const pcKeymap = { + ...baseKeymap + }; + const macKeymap = { + ...baseKeymap, + "Ctrl-h": handleBackspace2, + "Alt-Backspace": handleBackspace2, + "Ctrl-d": handleDelete2, + "Ctrl-Alt-Backspace": handleDelete2, + "Alt-Delete": handleDelete2, + "Alt-d": handleDelete2, + "Ctrl-a": () => this.editor.commands.selectTextblockStart(), + "Ctrl-e": () => this.editor.commands.selectTextblockEnd() + }; + if (isiOS() || isMacOS()) { + return macKeymap; + } + return pcKeymap; + }, + addProseMirrorPlugins() { + return [ + // With this plugin we check if the whole document was selected and deleted. + // In this case we will additionally call `clearNodes()` to convert e.g. a heading + // to a paragraph if necessary. + // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well + // with many other commands. + new Plugin({ + key: new PluginKey("clearDocument"), + appendTransaction: (transactions, oldState, newState) => { + if (transactions.some((tr22) => tr22.getMeta("composition"))) { + return; + } + const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); + const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument")); + if (!docChanges || ignoreTr) { + return; + } + const { empty: empty2, from: from2, to } = oldState.selection; + const allFrom = Selection.atStart(oldState.doc).from; + const allEnd = Selection.atEnd(oldState.doc).to; + const allWasSelected = from2 === allFrom && to === allEnd; + if (empty2 || !allWasSelected) { + return; + } + const isEmpty = isNodeEmpty(newState.doc); + if (!isEmpty) { + return; + } + const tr2 = newState.tr; + const state = createChainableState({ + state: newState, + transaction: tr2 + }); + const { commands } = new CommandManager({ + editor: this.editor, + state + }); + commands.clearNodes(); + if (!tr2.steps.length) { + return; + } + return tr2; + } + }) + ]; + } +}); +var Paste = Extension.create({ + name: "paste", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("tiptapPaste"), + props: { + handlePaste: (_view, e, slice2) => { + this.editor.emit("paste", { + editor: this.editor, + event: e, + slice: slice2 + }); + } + } + }) + ]; + } +}); +var Tabindex = Extension.create({ + name: "tabindex", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("tabindex"), + props: { + attributes: () => this.editor.isEditable ? { tabindex: "0" } : {} + } + }) + ]; + } +}); +var TextDirection = Extension.create({ + name: "textDirection", + addOptions() { + return { + direction: void 0 + }; + }, + addGlobalAttributes() { + if (!this.options.direction) { + return []; + } + const { nodeExtensions } = splitExtensions(this.extensions); + return [ + { + types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name), + attributes: { + dir: { + default: this.options.direction, + parseHTML: (element) => { + const dir = element.getAttribute("dir"); + if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) { + return dir; + } + return this.options.direction; + }, + renderHTML: (attributes) => { + if (!attributes.dir) { + return {}; + } + return { + dir: attributes.dir + }; + } + } + } + } + ]; + }, + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("textDirection"), + props: { + attributes: () => { + const direction = this.options.direction; + if (!direction) { + return {}; + } + return { + dir: direction + }; + } + } + }) + ]; + } +}); +var NodePos = class _NodePos { + constructor(pos, editor, isBlock = false, node = null) { + this.currentNode = null; + this.actualDepth = null; + this.isBlock = isBlock; + this.resolvedPos = pos; + this.editor = editor; + this.currentNode = node; + } + get name() { + return this.node.type.name; + } + get node() { + return this.currentNode || this.resolvedPos.node(); + } + get element() { + return this.editor.view.domAtPos(this.pos).node; + } + get depth() { + var _a; + return (_a = this.actualDepth) != null ? _a : this.resolvedPos.depth; + } + get pos() { + return this.resolvedPos.pos; + } + get content() { + return this.node.content; + } + set content(content) { + let from2 = this.from; + let to = this.to; + if (this.isBlock) { + if (this.content.size === 0) { + console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`); + return; + } + from2 = this.from + 1; + to = this.to - 1; + } + this.editor.commands.insertContentAt({ from: from2, to }, content); + } + get attributes() { + return this.node.attrs; + } + get textContent() { + return this.node.textContent; + } + get size() { + return this.node.nodeSize; + } + get from() { + if (this.isBlock) { + return this.pos; + } + return this.resolvedPos.start(this.resolvedPos.depth); + } + get range() { + return { + from: this.from, + to: this.to + }; + } + get to() { + if (this.isBlock) { + return this.pos + this.size; + } + return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1); + } + get parent() { + if (this.depth === 0) { + return null; + } + const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1); + const $pos = this.resolvedPos.doc.resolve(parentPos); + return new _NodePos($pos, this.editor); + } + get before() { + let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2)); + if ($pos.depth !== this.depth) { + $pos = this.resolvedPos.doc.resolve(this.from - 3); + } + return new _NodePos($pos, this.editor); + } + get after() { + let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1)); + if ($pos.depth !== this.depth) { + $pos = this.resolvedPos.doc.resolve(this.to + 3); + } + return new _NodePos($pos, this.editor); + } + get children() { + const children = []; + this.node.content.forEach((node, offset) => { + const isBlock = node.isBlock && !node.isTextblock; + const isNonTextAtom = node.isAtom && !node.isText; + const isInline2 = node.isInline; + const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1); + if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) { + return; + } + const $pos = this.resolvedPos.doc.resolve(targetPos); + if (!isBlock && !isInline2 && $pos.depth <= this.depth) { + return; + } + const childNodePos = new _NodePos($pos, this.editor, isBlock, isBlock || isInline2 ? node : null); + if (isBlock) { + childNodePos.actualDepth = this.depth + 1; + } + children.push(childNodePos); + }); + return children; + } + get firstChild() { + return this.children[0] || null; + } + get lastChild() { + const children = this.children; + return children[children.length - 1] || null; + } + closest(selector, attributes = {}) { + let node = null; + let currentNode = this.parent; + while (currentNode && !node) { + if (currentNode.node.type.name === selector) { + if (Object.keys(attributes).length > 0) { + const nodeAttributes = currentNode.node.attrs; + const attrKeys = Object.keys(attributes); + for (let index = 0; index < attrKeys.length; index += 1) { + const key = attrKeys[index]; + if (nodeAttributes[key] !== attributes[key]) { + break; + } + } + } else { + node = currentNode; + } + } + currentNode = currentNode.parent; + } + return node; + } + querySelector(selector, attributes = {}) { + return this.querySelectorAll(selector, attributes, true)[0] || null; + } + querySelectorAll(selector, attributes = {}, firstItemOnly = false) { + let nodes = []; + if (!this.children || this.children.length === 0) { + return nodes; + } + const attrKeys = Object.keys(attributes); + this.children.forEach((childPos) => { + if (firstItemOnly && nodes.length > 0) { + return; + } + if (childPos.node.type.name === selector) { + const doesAllAttributesMatch = attrKeys.every((key) => attributes[key] === childPos.node.attrs[key]); + if (doesAllAttributesMatch) { + nodes.push(childPos); + } + } + if (firstItemOnly && nodes.length > 0) { + return; + } + nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly)); + }); + return nodes; + } + setAttribute(attributes) { + const { tr: tr2 } = this.editor.state; + tr2.setNodeMarkup(this.from, void 0, { + ...this.node.attrs, + ...attributes + }); + this.editor.view.dispatch(tr2); + } +}; +var style = `.ProseMirror { + position: relative; +} + +.ProseMirror { + word-wrap: break-word; + white-space: pre-wrap; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ +} + +.ProseMirror [contenteditable="false"] { + white-space: normal; +} + +.ProseMirror [contenteditable="false"] [contenteditable="true"] { + white-space: pre-wrap; +} + +.ProseMirror pre { + white-space: pre-wrap; +} + +img.ProseMirror-separator { + display: inline !important; + border: none !important; + margin: 0 !important; + width: 0 !important; + height: 0 !important; +} + +.ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; + margin: 0; +} + +.ProseMirror-gapcursor:after { + content: ""; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; +} + +@keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } +} + +.ProseMirror-hideselection *::selection { + background: transparent; +} + +.ProseMirror-hideselection *::-moz-selection { + background: transparent; +} + +.ProseMirror-hideselection * { + caret-color: transparent; +} + +.ProseMirror-focused .ProseMirror-gapcursor { + display: block; +}`; +function createStyleTag(style2, nonce, suffix) { + const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${""}]`); + if (tiptapStyleTag !== null) { + return tiptapStyleTag; + } + const styleNode = document.createElement("style"); + if (nonce) { + styleNode.setAttribute("nonce", nonce); + } + styleNode.setAttribute(`data-tiptap-style${""}`, ""); + styleNode.innerHTML = style2; + document.getElementsByTagName("head")[0].appendChild(styleNode); + return styleNode; +} +var Editor = class extends EventEmitter { + constructor(options = {}) { + super(); + this.css = null; + this.className = "tiptap"; + this.editorView = null; + this.isFocused = false; + this.isInitialized = false; + this.extensionStorage = {}; + this.instanceId = Math.random().toString(36).slice(2, 9); + this.options = { + element: typeof document !== "undefined" ? document.createElement("div") : null, + content: "", + injectCSS: true, + injectNonce: void 0, + extensions: [], + autofocus: false, + editable: true, + textDirection: void 0, + editorProps: {}, + parseOptions: {}, + coreExtensionOptions: {}, + enableInputRules: true, + enablePasteRules: true, + enableCoreExtensions: true, + enableContentCheck: false, + emitContentError: false, + onBeforeCreate: () => null, + onCreate: () => null, + onMount: () => null, + onUnmount: () => null, + onUpdate: () => null, + onSelectionUpdate: () => null, + onTransaction: () => null, + onFocus: () => null, + onBlur: () => null, + onDestroy: () => null, + onContentError: ({ error }) => { + throw error; + }, + onPaste: () => null, + onDrop: () => null, + onDelete: () => null, + enableExtensionDispatchTransaction: true + }; + this.isCapturingTransaction = false; + this.capturedTransaction = null; + this.utils = { + getUpdatedPosition, + createMappablePosition + }; + this.setOptions(options); + this.createExtensionManager(); + this.createCommandManager(); + this.createSchema(); + this.on("beforeCreate", this.options.onBeforeCreate); + this.emit("beforeCreate", { editor: this }); + this.on("mount", this.options.onMount); + this.on("unmount", this.options.onUnmount); + this.on("contentError", this.options.onContentError); + this.on("create", this.options.onCreate); + this.on("update", this.options.onUpdate); + this.on("selectionUpdate", this.options.onSelectionUpdate); + this.on("transaction", this.options.onTransaction); + this.on("focus", this.options.onFocus); + this.on("blur", this.options.onBlur); + this.on("destroy", this.options.onDestroy); + this.on("drop", ({ event, slice: slice2, moved }) => this.options.onDrop(event, slice2, moved)); + this.on("paste", ({ event, slice: slice2 }) => this.options.onPaste(event, slice2)); + this.on("delete", this.options.onDelete); + const initialDoc = this.createDoc(); + const selection = resolveFocusPosition(initialDoc, this.options.autofocus); + this.editorState = EditorState.create({ + doc: initialDoc, + schema: this.schema, + selection: selection || void 0 + }); + if (this.options.element) { + this.mount(this.options.element); + } + } + /** + * Attach the editor to the DOM, creating a new editor view. + */ + mount(el) { + if (typeof document === "undefined") { + throw new Error( + `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.` + ); + } + this.createView(el); + this.emit("mount", { editor: this }); + if (this.css && !document.head.contains(this.css)) { + document.head.appendChild(this.css); + } + window.setTimeout(() => { + if (this.isDestroyed) { + return; + } + if (this.options.autofocus !== false && this.options.autofocus !== null) { + this.commands.focus(this.options.autofocus); + } + this.emit("create", { editor: this }); + this.isInitialized = true; + }, 0); + } + /** + * Remove the editor from the DOM, but still allow remounting at a different point in time + */ + unmount() { + if (this.editorView) { + const dom = this.editorView.dom; + if (dom == null ? void 0 : dom.editor) { + delete dom.editor; + } + this.editorView.destroy(); + } + this.editorView = null; + this.isInitialized = false; + if (this.css && !document.querySelectorAll(`.${this.className}`).length) { + try { + if (typeof this.css.remove === "function") { + this.css.remove(); + } else if (this.css.parentNode) { + this.css.parentNode.removeChild(this.css); + } + } catch (error) { + console.warn("Failed to remove CSS element:", error); + } + } + this.css = null; + this.emit("unmount", { editor: this }); + } + /** + * Returns the editor storage. + */ + get storage() { + return this.extensionStorage; + } + /** + * An object of all registered commands. + */ + get commands() { + return this.commandManager.commands; + } + /** + * Create a command chain to call multiple commands at once. + */ + chain() { + return this.commandManager.chain(); + } + /** + * Check if a command or a command chain can be executed. Without executing it. + */ + can() { + return this.commandManager.can(); + } + /** + * Inject CSS styles. + */ + injectCSS() { + if (this.options.injectCSS && typeof document !== "undefined") { + this.css = createStyleTag(style, this.options.injectNonce); + } + } + /** + * Update editor options. + * + * @param options A list of options + */ + setOptions(options = {}) { + this.options = { + ...this.options, + ...options + }; + if (!this.editorView || !this.state || this.isDestroyed) { + return; + } + if (this.options.editorProps) { + this.view.setProps(this.options.editorProps); + } + this.view.updateState(this.state); + } + /** + * Update editable state of the editor. + */ + setEditable(editable, emitUpdate = true) { + this.setOptions({ editable }); + if (emitUpdate) { + this.emit("update", { editor: this, transaction: this.state.tr, appendedTransactions: [] }); + } + } + /** + * Returns whether the editor is editable. + */ + get isEditable() { + return this.options.editable && this.view && this.view.editable; + } + /** + * Returns the editor view. + */ + get view() { + if (this.editorView) { + return this.editorView; + } + return new Proxy( + { + state: this.editorState, + updateState: (state) => { + this.editorState = state; + }, + dispatch: (tr2) => { + this.dispatchTransaction(tr2); + }, + // Stub some commonly accessed properties to prevent errors + composing: false, + dragging: null, + editable: true, + isDestroyed: false + }, + { + get: (obj, key) => { + if (this.editorView) { + return this.editorView[key]; + } + if (key === "state") { + return this.editorState; + } + if (key in obj) { + return Reflect.get(obj, key); + } + throw new Error( + `[tiptap error]: The editor view is not available. Cannot access view['${key}']. The editor may not be mounted yet.` + ); + } + } + ); + } + /** + * Returns the editor state. + */ + get state() { + if (this.editorView) { + this.editorState = this.view.state; + } + return this.editorState; + } + /** + * Register a ProseMirror plugin. + * + * @param plugin A ProseMirror plugin + * @param handlePlugins Control how to merge the plugin into the existing plugins. + * @returns The new editor state + */ + registerPlugin(plugin, handlePlugins) { + const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin]; + const state = this.state.reconfigure({ plugins }); + this.view.updateState(state); + return state; + } + /** + * Unregister a ProseMirror plugin. + * + * @param nameOrPluginKeyToRemove The plugins name + * @returns The new editor state or undefined if the editor is destroyed + */ + unregisterPlugin(nameOrPluginKeyToRemove) { + if (this.isDestroyed) { + return void 0; + } + const prevPlugins = this.state.plugins; + let plugins = prevPlugins; + [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => { + const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key; + plugins = plugins.filter((plugin) => !plugin.key.startsWith(name)); + }); + if (prevPlugins.length === plugins.length) { + return void 0; + } + const state = this.state.reconfigure({ + plugins + }); + this.view.updateState(state); + return state; + } + /** + * Creates an extension manager. + */ + createExtensionManager() { + var _a, _b; + const coreExtensions = this.options.enableCoreExtensions ? [ + Editable, + ClipboardTextSerializer.configure({ + blockSeparator: (_b = (_a = this.options.coreExtensionOptions) == null ? void 0 : _a.clipboardTextSerializer) == null ? void 0 : _b.blockSeparator + }), + Commands, + FocusEvents, + Keymap, + Tabindex, + Drop, + Paste, + Delete, + TextDirection.configure({ + direction: this.options.textDirection + }) + ].filter((ext) => { + if (typeof this.options.enableCoreExtensions === "object") { + return this.options.enableCoreExtensions[ext.name] !== false; + } + return true; + }) : []; + const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension) => { + return ["extension", "node", "mark"].includes(extension == null ? void 0 : extension.type); + }); + this.extensionManager = new ExtensionManager(allExtensions, this); + } + /** + * Creates an command manager. + */ + createCommandManager() { + this.commandManager = new CommandManager({ + editor: this + }); + } + /** + * Creates a ProseMirror schema. + */ + createSchema() { + this.schema = this.extensionManager.schema; + } + /** + * Creates the initial document. + */ + createDoc() { + let doc2; + try { + doc2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { + errorOnInvalidContent: this.options.enableContentCheck + }); + } catch (e) { + if (!(e instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e.message)) { + throw e; + } + this.emit("contentError", { + editor: this, + error: e, + disableCollaboration: () => { + if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) { + this.storage.collaboration.isDisabled = true; + } + this.options.extensions = this.options.extensions.filter((extension) => extension.name !== "collaboration"); + this.createExtensionManager(); + } + }); + doc2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { + errorOnInvalidContent: false + }); + } + return doc2; + } + /** + * Creates a ProseMirror view. + */ + createView(element) { + const { editorProps, enableExtensionDispatchTransaction } = this.options; + const baseDispatch = editorProps.dispatchTransaction || this.dispatchTransaction.bind(this); + const dispatch = enableExtensionDispatchTransaction ? this.extensionManager.dispatchTransaction(baseDispatch) : baseDispatch; + const baseTransformPastedHTML = editorProps.transformPastedHTML; + const transformPastedHTML = this.extensionManager.transformPastedHTML(baseTransformPastedHTML); + this.editorView = new EditorView(element, { + ...editorProps, + attributes: { + // add `role="textbox"` to the editor element + role: "textbox", + ...editorProps == null ? void 0 : editorProps.attributes + }, + dispatchTransaction: dispatch, + transformPastedHTML, + state: this.editorState, + markViews: this.extensionManager.markViews, + nodeViews: this.extensionManager.nodeViews + }); + const newState = this.state.reconfigure({ + plugins: this.extensionManager.plugins + }); + this.view.updateState(newState); + this.prependClass(); + this.injectCSS(); + const dom = this.view.dom; + dom.editor = this; + } + /** + * Creates all node and mark views. + */ + createNodeViews() { + if (this.view.isDestroyed) { + return; + } + this.view.setProps({ + markViews: this.extensionManager.markViews, + nodeViews: this.extensionManager.nodeViews + }); + } + /** + * Prepend class name to element. + */ + prependClass() { + this.view.dom.className = `${this.className} ${this.view.dom.className}`; + } + captureTransaction(fn) { + this.isCapturingTransaction = true; + fn(); + this.isCapturingTransaction = false; + const tr2 = this.capturedTransaction; + this.capturedTransaction = null; + return tr2; + } + /** + * The callback over which to send transactions (state updates) produced by the view. + * + * @param transaction An editor state transaction + */ + dispatchTransaction(transaction) { + if (this.view.isDestroyed) { + return; + } + if (this.isCapturingTransaction) { + if (!this.capturedTransaction) { + this.capturedTransaction = transaction; + return; + } + transaction.steps.forEach((step) => { + var _a; + return (_a = this.capturedTransaction) == null ? void 0 : _a.step(step); + }); + return; + } + const { state, transactions } = this.state.applyTransaction(transaction); + const selectionHasChanged = !this.state.selection.eq(state.selection); + const rootTrWasApplied = transactions.includes(transaction); + const prevState = this.state; + this.emit("beforeTransaction", { + editor: this, + transaction, + nextState: state + }); + if (!rootTrWasApplied) { + return; + } + this.view.updateState(state); + this.emit("transaction", { + editor: this, + transaction, + appendedTransactions: transactions.slice(1) + }); + if (selectionHasChanged) { + this.emit("selectionUpdate", { + editor: this, + transaction + }); + } + const mostRecentFocusTr = transactions.findLast((tr2) => tr2.getMeta("focus") || tr2.getMeta("blur")); + const focus2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("focus"); + const blur2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("blur"); + if (focus2) { + this.emit("focus", { + editor: this, + event: focus2.event, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + transaction: mostRecentFocusTr + }); + } + if (blur2) { + this.emit("blur", { + editor: this, + event: blur2.event, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + transaction: mostRecentFocusTr + }); + } + if (transaction.getMeta("preventUpdate") || !transactions.some((tr2) => tr2.docChanged) || prevState.doc.eq(state.doc)) { + return; + } + this.emit("update", { + editor: this, + transaction, + appendedTransactions: transactions.slice(1) + }); + } + /** + * Get attributes of the currently selected node or mark. + */ + getAttributes(nameOrType) { + return getAttributes(this.state, nameOrType); + } + isActive(nameOrAttributes, attributesOrUndefined) { + const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null; + const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes; + return isActive(this.state, name, attributes); + } + /** + * Get the document as JSON. + */ + getJSON() { + return this.state.doc.toJSON(); + } + /** + * Get the document as HTML. + */ + getHTML() { + return getHTMLFromFragment(this.state.doc.content, this.schema); + } + /** + * Get the document as text. + */ + getText(options) { + const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; + return getText(this.state.doc, { + blockSeparator, + textSerializers: { + ...getTextSerializersFromSchema(this.schema), + ...textSerializers + } + }); + } + /** + * Check if there is no content. + */ + get isEmpty() { + return isNodeEmpty(this.state.doc); + } + /** + * Destroy the editor. + */ + destroy() { + this.emit("destroy"); + this.unmount(); + this.removeAllListeners(); + } + /** + * Check if the editor is already destroyed. + */ + get isDestroyed() { + var _a, _b; + return (_b = (_a = this.editorView) == null ? void 0 : _a.isDestroyed) != null ? _b : true; + } + $node(selector, attributes) { + var _a; + return ((_a = this.$doc) == null ? void 0 : _a.querySelector(selector, attributes)) || null; + } + $nodes(selector, attributes) { + var _a; + return ((_a = this.$doc) == null ? void 0 : _a.querySelectorAll(selector, attributes)) || null; + } + $pos(pos) { + const $pos = this.state.doc.resolve(pos); + return new NodePos($pos, this); + } + get $doc() { + return this.$pos(0); + } +}; +function markInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match); + if (attributes === false || attributes === null) { + return null; + } + const { tr: tr2 } = state; + const captureGroup = match[match.length - 1]; + const fullMatch = match[0]; + if (captureGroup) { + const startSpaces = fullMatch.search(/\S/); + const textStart = range.from + fullMatch.indexOf(captureGroup); + const textEnd = textStart + captureGroup.length; + const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { + const excluded = item.mark.type.excluded; + return excluded.find((type) => type === config.type && type !== item.mark.type); + }).filter((item) => item.to > textStart); + if (excludedMarks.length) { + return null; + } + if (textEnd < range.to) { + tr2.delete(textEnd, range.to); + } + if (textStart > range.from) { + tr2.delete(range.from + startSpaces, textStart); + } + const markEnd = range.from + startSpaces + captureGroup.length; + tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); + tr2.removeStoredMark(config.type); + } + }, + undoable: config.undoable + }); +} +function nodeInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; + const { tr: tr2 } = state; + const start = range.from; + let end = range.to; + const newNode = config.type.create(attributes); + if (match[1]) { + const offset = match[0].lastIndexOf(match[1]); + let matchStart = start + offset; + if (matchStart > end) { + matchStart = end; + } else { + end = matchStart + match[1].length; + } + const lastChar = match[0][match[0].length - 1]; + tr2.insertText(lastChar, start + match[0].length - 1); + tr2.replaceWith(matchStart, end, newNode); + } else if (match[0]) { + const insertionStart = config.type.isInline ? start : start - 1; + tr2.insert(insertionStart, config.type.create(attributes)).delete(tr2.mapping.map(start), tr2.mapping.map(end)); + } + tr2.scrollIntoView(); + }, + undoable: config.undoable + }); +} +function textblockTypeInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + const $start = state.doc.resolve(range.from); + const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; + if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) { + return null; + } + state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes); + }, + undoable: config.undoable + }); +} +function wrappingInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match, chain }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; + const tr2 = state.tr.delete(range.from, range.to); + const $start = tr2.doc.resolve(range.from); + const blockRange = $start.blockRange(); + const wrapping = blockRange && findWrapping(blockRange, config.type, attributes); + if (!wrapping) { + return null; + } + tr2.wrap(blockRange, wrapping); + if (config.keepMarks && config.editor) { + const { selection, storedMarks } = state; + const { splittableMarks } = config.editor.extensionManager; + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + if (marks) { + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr2.ensureMarks(filteredMarks); + } + } + if (config.keepAttributes) { + const nodeType = config.type.name === "bulletList" || config.type.name === "orderedList" ? "listItem" : "taskList"; + chain().updateAttributes(nodeType, attributes).run(); + } + const before = tr2.doc.resolve(range.from - 1).nodeBefore; + if (before && before.type === config.type && canJoin(tr2.doc, range.from - 1) && (!config.joinPredicate || config.joinPredicate(match, before))) { + tr2.join(range.from - 1); + } + }, + undoable: config.undoable + }); +} +var isTouchEvent = (e) => { + return "touches" in e; +}; +var ResizableNodeView = class { + /** + * Creates a new ResizableNodeView instance. + * + * The constructor sets up the resize handles, applies initial sizing from + * node attributes, and configures all resize behavior options. + * + * @param options - Configuration options for the resizable node view + */ + constructor(options) { + this.directions = ["bottom-left", "bottom-right", "top-left", "top-right"]; + this.minSize = { + height: 8, + width: 8 + }; + this.preserveAspectRatio = false; + this.classNames = { + container: "", + wrapper: "", + handle: "", + resizing: "" + }; + this.initialWidth = 0; + this.initialHeight = 0; + this.aspectRatio = 1; + this.isResizing = false; + this.activeHandle = null; + this.startX = 0; + this.startY = 0; + this.startWidth = 0; + this.startHeight = 0; + this.isShiftKeyPressed = false; + this.lastEditableState = void 0; + this.handleMap = /* @__PURE__ */ new Map(); + this.handleMouseMove = (event) => { + if (!this.isResizing || !this.activeHandle) { + return; + } + const deltaX = event.clientX - this.startX; + const deltaY = event.clientY - this.startY; + this.handleResize(deltaX, deltaY); + }; + this.handleTouchMove = (event) => { + if (!this.isResizing || !this.activeHandle) { + return; + } + const touch = event.touches[0]; + if (!touch) { + return; + } + const deltaX = touch.clientX - this.startX; + const deltaY = touch.clientY - this.startY; + this.handleResize(deltaX, deltaY); + }; + this.handleMouseUp = () => { + if (!this.isResizing) { + return; + } + const finalWidth = this.element.offsetWidth; + const finalHeight = this.element.offsetHeight; + this.onCommit(finalWidth, finalHeight); + this.isResizing = false; + this.activeHandle = null; + this.container.dataset.resizeState = "false"; + if (this.classNames.resizing) { + this.container.classList.remove(this.classNames.resizing); + } + document.removeEventListener("mousemove", this.handleMouseMove); + document.removeEventListener("mouseup", this.handleMouseUp); + document.removeEventListener("keydown", this.handleKeyDown); + document.removeEventListener("keyup", this.handleKeyUp); + }; + this.handleKeyDown = (event) => { + if (event.key === "Shift") { + this.isShiftKeyPressed = true; + } + }; + this.handleKeyUp = (event) => { + if (event.key === "Shift") { + this.isShiftKeyPressed = false; + } + }; + var _a, _b, _c, _d, _e, _f; + this.node = options.node; + this.editor = options.editor; + this.element = options.element; + this.contentElement = options.contentElement; + this.getPos = options.getPos; + this.onResize = options.onResize; + this.onCommit = options.onCommit; + this.onUpdate = options.onUpdate; + if ((_a = options.options) == null ? void 0 : _a.min) { + this.minSize = { + ...this.minSize, + ...options.options.min + }; + } + if ((_b = options.options) == null ? void 0 : _b.max) { + this.maxSize = options.options.max; + } + if ((_c = options == null ? void 0 : options.options) == null ? void 0 : _c.directions) { + this.directions = options.options.directions; + } + if ((_d = options.options) == null ? void 0 : _d.preserveAspectRatio) { + this.preserveAspectRatio = options.options.preserveAspectRatio; + } + if ((_e = options.options) == null ? void 0 : _e.className) { + this.classNames = { + container: options.options.className.container || "", + wrapper: options.options.className.wrapper || "", + handle: options.options.className.handle || "", + resizing: options.options.className.resizing || "" + }; + } + if ((_f = options.options) == null ? void 0 : _f.createCustomHandle) { + this.createCustomHandle = options.options.createCustomHandle; + } + this.wrapper = this.createWrapper(); + this.container = this.createContainer(); + this.applyInitialSize(); + this.attachHandles(); + this.editor.on("update", this.handleEditorUpdate.bind(this)); + } + /** + * Returns the top-level DOM node that should be placed in the editor. + * + * This is required by the ProseMirror NodeView interface. The container + * includes the wrapper, handles, and the actual content element. + * + * @returns The container element to be inserted into the editor + */ + get dom() { + return this.container; + } + get contentDOM() { + var _a; + return (_a = this.contentElement) != null ? _a : null; + } + handleEditorUpdate() { + const isEditable = this.editor.isEditable; + if (isEditable === this.lastEditableState) { + return; + } + this.lastEditableState = isEditable; + if (!isEditable) { + this.removeHandles(); + } else if (isEditable && this.handleMap.size === 0) { + this.attachHandles(); + } + } + /** + * Called when the node's content or attributes change. + * + * Updates the internal node reference. If a custom `onUpdate` callback + * was provided, it will be called to handle additional update logic. + * + * @param node - The new/updated node + * @param decorations - Node decorations + * @param innerDecorations - Inner decorations + * @returns `false` if the node type has changed (requires full rebuild), otherwise the result of `onUpdate` or `true` + */ + update(node, decorations, innerDecorations) { + if (node.type !== this.node.type) { + return false; + } + this.node = node; + if (this.onUpdate) { + return this.onUpdate(node, decorations, innerDecorations); + } + return true; + } + /** + * Cleanup method called when the node view is being removed. + * + * Removes all event listeners to prevent memory leaks. This is required + * by the ProseMirror NodeView interface. If a resize is active when + * destroy is called, it will be properly cancelled. + */ + destroy() { + if (this.isResizing) { + this.container.dataset.resizeState = "false"; + if (this.classNames.resizing) { + this.container.classList.remove(this.classNames.resizing); + } + document.removeEventListener("mousemove", this.handleMouseMove); + document.removeEventListener("mouseup", this.handleMouseUp); + document.removeEventListener("keydown", this.handleKeyDown); + document.removeEventListener("keyup", this.handleKeyUp); + this.isResizing = false; + this.activeHandle = null; + } + this.editor.off("update", this.handleEditorUpdate.bind(this)); + this.container.remove(); + } + /** + * Creates the outer container element. + * + * The container is the top-level element returned by the NodeView and + * wraps the entire resizable node. It's set up with flexbox to handle + * alignment and includes data attributes for styling and identification. + * + * @returns The container element + */ + createContainer() { + const element = document.createElement("div"); + element.dataset.resizeContainer = ""; + element.dataset.node = this.node.type.name; + element.style.display = this.node.type.isInline ? "inline-flex" : "flex"; + if (this.classNames.container) { + element.className = this.classNames.container; + } + element.appendChild(this.wrapper); + return element; + } + /** + * Creates the wrapper element that contains the content and handles. + * + * The wrapper uses relative positioning so that resize handles can be + * positioned absolutely within it. This is the direct parent of the + * content element being made resizable. + * + * @returns The wrapper element + */ + createWrapper() { + const element = document.createElement("div"); + element.style.position = "relative"; + element.style.display = "block"; + element.dataset.resizeWrapper = ""; + if (this.classNames.wrapper) { + element.className = this.classNames.wrapper; + } + element.appendChild(this.element); + return element; + } + /** + * Creates a resize handle element for a specific direction. + * + * Each handle is absolutely positioned and includes a data attribute + * identifying its direction for styling purposes. + * + * @param direction - The resize direction for this handle + * @returns The handle element + */ + createHandle(direction) { + const handle = document.createElement("div"); + handle.dataset.resizeHandle = direction; + handle.style.position = "absolute"; + if (this.classNames.handle) { + handle.className = this.classNames.handle; + } + return handle; + } + /** + * Positions a handle element according to its direction. + * + * Corner handles (e.g., 'top-left') are positioned at the intersection + * of two edges. Edge handles (e.g., 'top') span the full width or height. + * + * @param handle - The handle element to position + * @param direction - The direction determining the position + */ + positionHandle(handle, direction) { + const isTop = direction.includes("top"); + const isBottom = direction.includes("bottom"); + const isLeft = direction.includes("left"); + const isRight = direction.includes("right"); + if (isTop) { + handle.style.top = "0"; + } + if (isBottom) { + handle.style.bottom = "0"; + } + if (isLeft) { + handle.style.left = "0"; + } + if (isRight) { + handle.style.right = "0"; + } + if (direction === "top" || direction === "bottom") { + handle.style.left = "0"; + handle.style.right = "0"; + } + if (direction === "left" || direction === "right") { + handle.style.top = "0"; + handle.style.bottom = "0"; + } + } + /** + * Creates and attaches all resize handles to the wrapper. + * + * Iterates through the configured directions, creates a handle for each, + * positions it, attaches the mousedown listener, and appends it to the DOM. + */ + attachHandles() { + this.directions.forEach((direction) => { + let handle; + if (this.createCustomHandle) { + handle = this.createCustomHandle(direction); + } else { + handle = this.createHandle(direction); + } + if (!(handle instanceof HTMLElement)) { + console.warn( + `[ResizableNodeView] createCustomHandle("${direction}") did not return an HTMLElement. Falling back to default handle.` + ); + handle = this.createHandle(direction); + } + if (!this.createCustomHandle) { + this.positionHandle(handle, direction); + } + handle.addEventListener("mousedown", (event) => this.handleResizeStart(event, direction)); + handle.addEventListener("touchstart", (event) => this.handleResizeStart(event, direction)); + this.handleMap.set(direction, handle); + this.wrapper.appendChild(handle); + }); + } + /** + * Removes all resize handles from the wrapper. + * + * Cleans up the handle map and removes each handle element from the DOM. + */ + removeHandles() { + this.handleMap.forEach((el) => el.remove()); + this.handleMap.clear(); + } + /** + * Applies initial sizing from node attributes to the element. + * + * If width/height attributes exist on the node, they're applied to the element. + * Otherwise, the element's natural/current dimensions are measured. The aspect + * ratio is calculated for later use in aspect-ratio-preserving resizes. + */ + applyInitialSize() { + const width = this.node.attrs.width; + const height = this.node.attrs.height; + if (width) { + this.element.style.width = `${width}px`; + this.initialWidth = width; + } else { + this.initialWidth = this.element.offsetWidth; + } + if (height) { + this.element.style.height = `${height}px`; + this.initialHeight = height; + } else { + this.initialHeight = this.element.offsetHeight; + } + if (this.initialWidth > 0 && this.initialHeight > 0) { + this.aspectRatio = this.initialWidth / this.initialHeight; + } + } + /** + * Initiates a resize operation when a handle is clicked. + * + * Captures the starting mouse position and element dimensions, sets up + * the resize state, adds the resizing class and state attribute, and + * attaches document-level listeners for mouse movement and keyboard input. + * + * @param event - The mouse down event + * @param direction - The direction of the handle being dragged + */ + handleResizeStart(event, direction) { + event.preventDefault(); + event.stopPropagation(); + this.isResizing = true; + this.activeHandle = direction; + if (isTouchEvent(event)) { + this.startX = event.touches[0].clientX; + this.startY = event.touches[0].clientY; + } else { + this.startX = event.clientX; + this.startY = event.clientY; + } + this.startWidth = this.element.offsetWidth; + this.startHeight = this.element.offsetHeight; + if (this.startWidth > 0 && this.startHeight > 0) { + this.aspectRatio = this.startWidth / this.startHeight; + } + this.getPos(); + this.container.dataset.resizeState = "true"; + if (this.classNames.resizing) { + this.container.classList.add(this.classNames.resizing); + } + document.addEventListener("mousemove", this.handleMouseMove); + document.addEventListener("touchmove", this.handleTouchMove); + document.addEventListener("mouseup", this.handleMouseUp); + document.addEventListener("keydown", this.handleKeyDown); + document.addEventListener("keyup", this.handleKeyUp); + } + handleResize(deltaX, deltaY) { + if (!this.activeHandle) { + return; + } + const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; + const { width, height } = this.calculateNewDimensions(this.activeHandle, deltaX, deltaY); + const constrained = this.applyConstraints(width, height, shouldPreserveAspectRatio); + this.element.style.width = `${constrained.width}px`; + this.element.style.height = `${constrained.height}px`; + if (this.onResize) { + this.onResize(constrained.width, constrained.height); + } + } + /** + * Calculates new dimensions based on mouse delta and resize direction. + * + * Takes the starting dimensions and applies the mouse movement delta + * according to the handle direction. For corner handles, both dimensions + * are affected. For edge handles, only one dimension changes. If aspect + * ratio should be preserved, delegates to applyAspectRatio. + * + * @param direction - The active resize handle direction + * @param deltaX - Horizontal mouse movement since resize start + * @param deltaY - Vertical mouse movement since resize start + * @returns The calculated width and height + */ + calculateNewDimensions(direction, deltaX, deltaY) { + let newWidth = this.startWidth; + let newHeight = this.startHeight; + const isRight = direction.includes("right"); + const isLeft = direction.includes("left"); + const isBottom = direction.includes("bottom"); + const isTop = direction.includes("top"); + if (isRight) { + newWidth = this.startWidth + deltaX; + } else if (isLeft) { + newWidth = this.startWidth - deltaX; + } + if (isBottom) { + newHeight = this.startHeight + deltaY; + } else if (isTop) { + newHeight = this.startHeight - deltaY; + } + if (direction === "right" || direction === "left") { + newWidth = this.startWidth + (isRight ? deltaX : -deltaX); + } + if (direction === "top" || direction === "bottom") { + newHeight = this.startHeight + (isBottom ? deltaY : -deltaY); + } + const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; + if (shouldPreserveAspectRatio) { + return this.applyAspectRatio(newWidth, newHeight, direction); + } + return { width: newWidth, height: newHeight }; + } + /** + * Applies min/max constraints to dimensions. + * + * When aspect ratio is NOT preserved, constraints are applied independently + * to width and height. When aspect ratio IS preserved, constraints are + * applied while maintaining the aspect ratio—if one dimension hits a limit, + * the other is recalculated proportionally. + * + * This ensures that aspect ratio is never broken when constrained. + * + * @param width - The unconstrained width + * @param height - The unconstrained height + * @param preserveAspectRatio - Whether to maintain aspect ratio while constraining + * @returns The constrained dimensions + */ + applyConstraints(width, height, preserveAspectRatio) { + var _a, _b, _c, _d; + if (!preserveAspectRatio) { + let constrainedWidth2 = Math.max(this.minSize.width, width); + let constrainedHeight2 = Math.max(this.minSize.height, height); + if ((_a = this.maxSize) == null ? void 0 : _a.width) { + constrainedWidth2 = Math.min(this.maxSize.width, constrainedWidth2); + } + if ((_b = this.maxSize) == null ? void 0 : _b.height) { + constrainedHeight2 = Math.min(this.maxSize.height, constrainedHeight2); + } + return { width: constrainedWidth2, height: constrainedHeight2 }; + } + let constrainedWidth = width; + let constrainedHeight = height; + if (constrainedWidth < this.minSize.width) { + constrainedWidth = this.minSize.width; + constrainedHeight = constrainedWidth / this.aspectRatio; + } + if (constrainedHeight < this.minSize.height) { + constrainedHeight = this.minSize.height; + constrainedWidth = constrainedHeight * this.aspectRatio; + } + if (((_c = this.maxSize) == null ? void 0 : _c.width) && constrainedWidth > this.maxSize.width) { + constrainedWidth = this.maxSize.width; + constrainedHeight = constrainedWidth / this.aspectRatio; + } + if (((_d = this.maxSize) == null ? void 0 : _d.height) && constrainedHeight > this.maxSize.height) { + constrainedHeight = this.maxSize.height; + constrainedWidth = constrainedHeight * this.aspectRatio; + } + return { width: constrainedWidth, height: constrainedHeight }; + } + /** + * Adjusts dimensions to maintain the original aspect ratio. + * + * For horizontal handles (left/right), uses width as the primary dimension + * and calculates height from it. For vertical handles (top/bottom), uses + * height as primary and calculates width. For corner handles, uses width + * as the primary dimension. + * + * @param width - The new width + * @param height - The new height + * @param direction - The active resize direction + * @returns Dimensions adjusted to preserve aspect ratio + */ + applyAspectRatio(width, height, direction) { + const isHorizontal = direction === "left" || direction === "right"; + const isVertical = direction === "top" || direction === "bottom"; + if (isHorizontal) { + return { + width, + height: width / this.aspectRatio + }; + } + if (isVertical) { + return { + width: height * this.aspectRatio, + height + }; + } + return { + width, + height: width / this.aspectRatio + }; + } +}; +function canInsertNode(state, nodeType) { + const { selection } = state; + const { $from } = selection; + if (selection instanceof NodeSelection) { + const index = $from.index(); + const parent = $from.parent; + return parent.canReplaceWith(index, index + 1, nodeType); + } + let depth = $from.depth; + while (depth >= 0) { + const index = $from.index(depth); + const parent = $from.node(depth); + const match = parent.contentMatchAt(index); + if (match.matchType(nodeType)) { + return true; + } + depth -= 1; + } + return false; +} +function escapeForRegEx(string) { + return string.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var markdown_exports = {}; +__export$1(markdown_exports, { + createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec, + createBlockMarkdownSpec: () => createBlockMarkdownSpec, + createInlineMarkdownSpec: () => createInlineMarkdownSpec, + parseAttributes: () => parseAttributes, + parseIndentedBlocks: () => parseIndentedBlocks, + renderNestedMarkdownContent: () => renderNestedMarkdownContent, + serializeAttributes: () => serializeAttributes +}); +function parseAttributes(attrString) { + if (!(attrString == null ? void 0 : attrString.trim())) { + return {}; + } + const attributes = {}; + const quotedStrings = []; + const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => { + quotedStrings.push(match); + return `__QUOTED_${quotedStrings.length - 1}__`; + }); + const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g); + if (classMatches) { + const classes = classMatches.map((match) => match.trim().slice(1)); + attributes.class = classes.join(" "); + } + const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/); + if (idMatch) { + attributes.id = idMatch[1]; + } + const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g; + const kvMatches = Array.from(tempString.matchAll(kvRegex)); + kvMatches.forEach(([, key, quotedRef]) => { + var _a; + const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10); + const quotedValue = quotedStrings[quotedIndex]; + if (quotedValue) { + attributes[key] = quotedValue.slice(1, -1); + } + }); + const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim(); + if (cleanString) { + const booleanAttrs = cleanString.split(/\s+/).filter(Boolean); + booleanAttrs.forEach((attr) => { + if (attr.match(/^[a-zA-Z][\w-]*$/)) { + attributes[attr] = true; + } + }); + } + return attributes; +} +function serializeAttributes(attributes) { + if (!attributes || Object.keys(attributes).length === 0) { + return ""; + } + const parts = []; + if (attributes.class) { + const classes = String(attributes.class).split(/\s+/).filter(Boolean); + classes.forEach((cls) => parts.push(`.${cls}`)); + } + if (attributes.id) { + parts.push(`#${attributes.id}`); + } + Object.entries(attributes).forEach(([key, value]) => { + if (key === "class" || key === "id") { + return; + } + if (value === true) { + parts.push(key); + } else if (value !== false && value != null) { + parts.push(`${key}="${String(value)}"`); + } + }); + return parts.join(" "); +} +function createAtomBlockMarkdownSpec(options) { + const { + nodeName, + name: markdownName, + parseAttributes: parseAttributes2 = parseAttributes, + serializeAttributes: serializeAttributes2 = serializeAttributes, + defaultAttributes = {}, + requiredAttributes = [], + allowedAttributes + } = options; + const blockName = markdownName || nodeName; + const filterAttributes = (attrs) => { + if (!allowedAttributes) { + return attrs; + } + const filtered = {}; + allowedAttributes.forEach((key) => { + if (key in attrs) { + filtered[key] = attrs[key]; + } + }); + return filtered; + }; + return { + parseMarkdown: (token, h2) => { + const attrs = { ...defaultAttributes, ...token.attributes }; + return h2.createNode(nodeName, attrs, []); + }, + markdownTokenizer: { + name: nodeName, + level: "block", + start(src) { + var _a; + const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m"); + const index = (_a = src.match(regex)) == null ? void 0 : _a.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, _tokens, _lexer) { + const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`); + const match = src.match(regex); + if (!match) { + return void 0; + } + const attrString = match[1] || ""; + const attributes = parseAttributes2(attrString); + const missingRequired = requiredAttributes.find((required) => !(required in attributes)); + if (missingRequired) { + return void 0; + } + return { + type: nodeName, + raw: match[0], + attributes + }; + } + }, + renderMarkdown: (node) => { + const filteredAttrs = filterAttributes(node.attrs || {}); + const attrs = serializeAttributes2(filteredAttrs); + const attrString = attrs ? ` {${attrs}}` : ""; + return `:::${blockName}${attrString} :::`; + } + }; +} +function createBlockMarkdownSpec(options) { + const { + nodeName, + name: markdownName, + getContent, + parseAttributes: parseAttributes2 = parseAttributes, + serializeAttributes: serializeAttributes2 = serializeAttributes, + defaultAttributes = {}, + content = "block", + allowedAttributes + } = options; + const blockName = markdownName || nodeName; + const filterAttributes = (attrs) => { + if (!allowedAttributes) { + return attrs; + } + const filtered = {}; + allowedAttributes.forEach((key) => { + if (key in attrs) { + filtered[key] = attrs[key]; + } + }); + return filtered; + }; + return { + parseMarkdown: (token, h2) => { + let nodeContent; + if (getContent) { + const contentResult = getContent(token); + nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult; + } else if (content === "block") { + nodeContent = h2.parseChildren(token.tokens || []); + } else { + nodeContent = h2.parseInline(token.tokens || []); + } + const attrs = { ...defaultAttributes, ...token.attributes }; + return h2.createNode(nodeName, attrs, nodeContent); + }, + markdownTokenizer: { + name: nodeName, + level: "block", + start(src) { + var _a; + const regex = new RegExp(`^:::${blockName}`, "m"); + const index = (_a = src.match(regex)) == null ? void 0 : _a.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, _tokens, lexer) { + var _a; + const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`); + const openingMatch = src.match(openingRegex); + if (!openingMatch) { + return void 0; + } + const [openingTag, attrString = ""] = openingMatch; + const attributes = parseAttributes2(attrString); + let level = 1; + const position = openingTag.length; + let matchedContent = ""; + const blockPattern = /^:::([\w-]*)(\s.*)?/gm; + const remaining = src.slice(position); + blockPattern.lastIndex = 0; + for (; ; ) { + const match = blockPattern.exec(remaining); + if (match === null) { + break; + } + const matchPos = match.index; + const blockType = match[1]; + if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) { + continue; + } + if (blockType) { + level += 1; + } else { + level -= 1; + if (level === 0) { + const rawContent = remaining.slice(0, matchPos); + matchedContent = rawContent.trim(); + const fullMatch = src.slice(0, position + matchPos + match[0].length); + let contentTokens = []; + if (matchedContent) { + if (content === "block") { + contentTokens = lexer.blockTokens(rawContent); + contentTokens.forEach((token) => { + if (token.text && (!token.tokens || token.tokens.length === 0)) { + token.tokens = lexer.inlineTokens(token.text); + } + }); + while (contentTokens.length > 0) { + const lastToken = contentTokens[contentTokens.length - 1]; + if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) { + contentTokens.pop(); + } else { + break; + } + } + } else { + contentTokens = lexer.inlineTokens(matchedContent); + } + } + return { + type: nodeName, + raw: fullMatch, + attributes, + content: matchedContent, + tokens: contentTokens + }; + } + } + } + return void 0; + } + }, + renderMarkdown: (node, h2) => { + const filteredAttrs = filterAttributes(node.attrs || {}); + const attrs = serializeAttributes2(filteredAttrs); + const attrString = attrs ? ` {${attrs}}` : ""; + const renderedContent = h2.renderChildren(node.content || [], "\n\n"); + return `:::${blockName}${attrString} + +${renderedContent} + +:::`; + } + }; +} +function parseShortcodeAttributes(attrString) { + if (!attrString.trim()) { + return {}; + } + const attributes = {}; + const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g; + let match = regex.exec(attrString); + while (match !== null) { + const [, key, doubleQuoted, singleQuoted] = match; + attributes[key] = doubleQuoted || singleQuoted; + match = regex.exec(attrString); + } + return attributes; +} +function serializeShortcodeAttributes(attrs) { + return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" "); +} +function createInlineMarkdownSpec(options) { + const { + nodeName, + name: shortcodeName, + getContent, + parseAttributes: parseAttributes2 = parseShortcodeAttributes, + serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes, + defaultAttributes = {}, + selfClosing = false, + allowedAttributes + } = options; + const shortcode = shortcodeName || nodeName; + const filterAttributes = (attrs) => { + if (!allowedAttributes) { + return attrs; + } + const filtered = {}; + allowedAttributes.forEach((attr) => { + const attrName = typeof attr === "string" ? attr : attr.name; + const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault; + if (attrName in attrs) { + const value = attrs[attrName]; + if (skipIfDefault !== void 0 && value === skipIfDefault) { + return; + } + filtered[attrName] = value; + } + }); + return filtered; + }; + const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return { + parseMarkdown: (token, h2) => { + const attrs = { ...defaultAttributes, ...token.attributes }; + if (selfClosing) { + return h2.createNode(nodeName, attrs); + } + const content = getContent ? getContent(token) : token.content || ""; + if (content) { + return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]); + } + return h2.createNode(nodeName, attrs, []); + }, + markdownTokenizer: { + name: nodeName, + level: "inline", + start(src) { + const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`); + const match = src.match(startPattern); + const index = match == null ? void 0 : match.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, _tokens, _lexer) { + const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`); + const match = src.match(tokenPattern); + if (!match) { + return void 0; + } + let content = ""; + let attrString = ""; + if (selfClosing) { + const [, attrs] = match; + attrString = attrs; + } else { + const [, attrs, contentMatch] = match; + attrString = attrs; + content = contentMatch || ""; + } + const attributes = parseAttributes2(attrString.trim()); + return { + type: nodeName, + raw: match[0], + content: content.trim(), + attributes + }; + } + }, + renderMarkdown: (node) => { + let content = ""; + if (getContent) { + content = getContent(node); + } else if (node.content && node.content.length > 0) { + content = node.content.filter((child) => child.type === "text").map((child) => child.text).join(""); + } + const filteredAttrs = filterAttributes(node.attrs || {}); + const attrs = serializeAttributes2(filteredAttrs); + const attrString = attrs ? ` ${attrs}` : ""; + if (selfClosing) { + return `[${shortcode}${attrString}]`; + } + return `[${shortcode}${attrString}]${content}[/${shortcode}]`; + } + }; +} +function parseIndentedBlocks(src, config, lexer) { + var _a, _b, _c, _d; + const lines = src.split("\n"); + const items = []; + let totalRaw = ""; + let i = 0; + const baseIndentSize = config.baseIndentSize || 2; + while (i < lines.length) { + const currentLine = lines[i]; + const itemMatch = currentLine.match(config.itemPattern); + if (!itemMatch) { + if (items.length > 0) { + break; + } else if (currentLine.trim() === "") { + i += 1; + totalRaw = `${totalRaw}${currentLine} +`; + continue; + } else { + return void 0; + } + } + const itemData = config.extractItemData(itemMatch); + const { indentLevel, mainContent } = itemData; + totalRaw = `${totalRaw}${currentLine} +`; + const itemContent = [mainContent]; + i += 1; + while (i < lines.length) { + const nextLine = lines[i]; + if (nextLine.trim() === "") { + const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== ""); + if (nextNonEmptyIndex === -1) { + break; + } + const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex]; + const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0; + if (nextIndent2 > indentLevel) { + itemContent.push(nextLine); + totalRaw = `${totalRaw}${nextLine} +`; + i += 1; + continue; + } else { + break; + } + } + const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0; + if (nextIndent > indentLevel) { + itemContent.push(nextLine); + totalRaw = `${totalRaw}${nextLine} +`; + i += 1; + } else { + break; + } + } + let nestedTokens; + const nestedContent = itemContent.slice(1); + if (nestedContent.length > 0) { + const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n"); + if (dedentedNested.trim()) { + if (config.customNestedParser) { + nestedTokens = config.customNestedParser(dedentedNested); + } else { + nestedTokens = lexer.blockTokens(dedentedNested); + } + } + } + const token = config.createToken(itemData, nestedTokens); + items.push(token); + } + if (items.length === 0) { + return void 0; + } + return { + items, + raw: totalRaw + }; +} +function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) { + if (!node || !Array.isArray(node.content)) { + return ""; + } + const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator; + const [content, ...children] = node.content; + const mainContent = h2.renderChildren([content]); + let output = `${prefix}${mainContent}`; + if (children && children.length > 0) { + children.forEach((child, index) => { + var _a, _b; + const childContent = (_b = (_a = h2.renderChild) == null ? void 0 : _a.call(h2, child, index + 1)) != null ? _b : h2.renderChildren([child]); + if (childContent !== void 0 && childContent !== null) { + const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : h2.indent("")).join("\n"); + output += child.type === "paragraph" ? ` + +${indentedChild}` : ` +${indentedChild}`; + } + }); + } + return output; +} +function updateMarkViewAttributes(checkMark, editor, attrs = {}) { + const { state } = editor; + const { doc: doc2, tr: tr2 } = state; + const thisMark = checkMark; + doc2.descendants((node, pos) => { + const from2 = tr2.mapping.map(pos); + const to = tr2.mapping.map(pos) + node.nodeSize; + let foundMark = null; + node.marks.forEach((mark) => { + if (mark !== thisMark) { + return false; + } + foundMark = mark; + }); + if (!foundMark) { + return; + } + let needsUpdate = false; + Object.keys(attrs).forEach((k) => { + if (attrs[k] !== foundMark.attrs[k]) { + needsUpdate = true; + } + }); + if (needsUpdate) { + const updatedMark = checkMark.type.create({ + ...checkMark.attrs, + ...attrs + }); + tr2.removeMark(from2, to, checkMark.type); + tr2.addMark(from2, to, updatedMark); + } + }); + if (tr2.docChanged) { + editor.view.dispatch(tr2); + } +} +var Node3 = class _Node extends Extendable { + constructor() { + super(...arguments); + this.type = "node"; + } + /** + * Create a new Node instance + * @param config - Node configuration object or a function that returns a configuration object + */ + static create(config = {}) { + const resolvedConfig = typeof config === "function" ? config() : config; + return new _Node(resolvedConfig); + } + configure(options) { + return super.configure(options); + } + extend(extendedConfig) { + const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; + return super.extend(resolvedConfig); + } +}; +function markPasteRule(config) { + return new PasteRule({ + find: config.find, + handler: ({ state, range, match, pasteEvent }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent); + if (attributes === false || attributes === null) { + return null; + } + const { tr: tr2 } = state; + const captureGroup = match[match.length - 1]; + const fullMatch = match[0]; + let markEnd = range.to; + if (captureGroup) { + const startSpaces = fullMatch.search(/\S/); + const textStart = range.from + fullMatch.indexOf(captureGroup); + const textEnd = textStart + captureGroup.length; + const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { + const excluded = item.mark.type.excluded; + return excluded.find((type) => type === config.type && type !== item.mark.type); + }).filter((item) => item.to > textStart); + if (excludedMarks.length) { + return null; + } + if (textEnd < range.to) { + tr2.delete(textEnd, range.to); + } + if (textStart > range.from) { + tr2.delete(range.from + startSpaces, textStart); + } + markEnd = range.from + startSpaces + captureGroup.length; + tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); + tr2.removeStoredMark(config.type); + } + } + }); +} +const { getOwnPropertyNames, getOwnPropertySymbols } = Object; +const { hasOwnProperty } = Object.prototype; +function combineComparators(comparatorA, comparatorB) { + return function isEqual(a, b, state) { + return comparatorA(a, b, state) && comparatorB(a, b, state); + }; +} +function createIsCircular(areItemsEqual) { + return function isCircular(a, b, state) { + if (!a || !b || typeof a !== "object" || typeof b !== "object") { + return areItemsEqual(a, b, state); + } + const { cache } = state; + const cachedA = cache.get(a); + const cachedB = cache.get(b); + if (cachedA && cachedB) { + return cachedA === b && cachedB === a; + } + cache.set(a, b); + cache.set(b, a); + const result = areItemsEqual(a, b, state); + cache.delete(a); + cache.delete(b); + return result; + }; +} +function getShortTag(value) { + return value != null ? value[Symbol.toStringTag] : void 0; +} +function getStrictProperties(object) { + return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object)); +} +const hasOwn = ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + Object.hasOwn || ((object, property) => hasOwnProperty.call(object, property)) +); +function sameValueZeroEqual(a, b) { + return a === b || !a && !b && a !== a && b !== b; +} +const PREACT_VNODE = "__v"; +const PREACT_OWNER = "__o"; +const REACT_OWNER = "_owner"; +const { getOwnPropertyDescriptor, keys } = Object; +function areArrayBuffersEqual(a, b) { + return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b)); +} +function areArraysEqual(a, b, state) { + let index = a.length; + if (b.length !== index) { + return false; + } + while (index-- > 0) { + if (!state.equals(a[index], b[index], index, index, a, b, state)) { + return false; + } + } + return true; +} +function areDataViewsEqual(a, b) { + return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)); +} +function areDatesEqual(a, b) { + return sameValueZeroEqual(a.getTime(), b.getTime()); +} +function areErrorsEqual(a, b) { + return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack; +} +function areFunctionsEqual(a, b) { + return a === b; +} +function areMapsEqual(a, b, state) { + const size = a.size; + if (size !== b.size) { + return false; + } + if (!size) { + return true; + } + const matchedIndices = new Array(size); + const aIterable = a.entries(); + let aResult; + let bResult; + let index = 0; + while (aResult = aIterable.next()) { + if (aResult.done) { + break; + } + const bIterable = b.entries(); + let hasMatch = false; + let matchIndex = 0; + while (bResult = bIterable.next()) { + if (bResult.done) { + break; + } + if (matchedIndices[matchIndex]) { + matchIndex++; + continue; + } + const aEntry = aResult.value; + const bEntry = bResult.value; + if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) { + hasMatch = matchedIndices[matchIndex] = true; + break; + } + matchIndex++; + } + if (!hasMatch) { + return false; + } + index++; + } + return true; +} +const areNumbersEqual = sameValueZeroEqual; +function areObjectsEqual(a, b, state) { + const properties = keys(a); + let index = properties.length; + if (keys(b).length !== index) { + return false; + } + while (index-- > 0) { + if (!isPropertyEqual(a, b, state, properties[index])) { + return false; + } + } + return true; +} +function areObjectsEqualStrict(a, b, state) { + const properties = getStrictProperties(a); + let index = properties.length; + if (getStrictProperties(b).length !== index) { + return false; + } + let property; + let descriptorA; + let descriptorB; + while (index-- > 0) { + property = properties[index]; + if (!isPropertyEqual(a, b, state, property)) { + return false; + } + descriptorA = getOwnPropertyDescriptor(a, property); + descriptorB = getOwnPropertyDescriptor(b, property); + if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) { + return false; + } + } + return true; +} +function arePrimitiveWrappersEqual(a, b) { + return sameValueZeroEqual(a.valueOf(), b.valueOf()); +} +function areRegExpsEqual(a, b) { + return a.source === b.source && a.flags === b.flags; +} +function areSetsEqual(a, b, state) { + const size = a.size; + if (size !== b.size) { + return false; + } + if (!size) { + return true; + } + const matchedIndices = new Array(size); + const aIterable = a.values(); + let aResult; + let bResult; + while (aResult = aIterable.next()) { + if (aResult.done) { + break; + } + const bIterable = b.values(); + let hasMatch = false; + let matchIndex = 0; + while (bResult = bIterable.next()) { + if (bResult.done) { + break; + } + if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) { + hasMatch = matchedIndices[matchIndex] = true; + break; + } + matchIndex++; + } + if (!hasMatch) { + return false; + } + } + return true; +} +function areTypedArraysEqual(a, b) { + let index = a.byteLength; + if (b.byteLength !== index || a.byteOffset !== b.byteOffset) { + return false; + } + while (index-- > 0) { + if (a[index] !== b[index]) { + return false; + } + } + return true; +} +function areUrlsEqual(a, b) { + return a.hostname === b.hostname && a.pathname === b.pathname && a.protocol === b.protocol && a.port === b.port && a.hash === b.hash && a.username === b.username && a.password === b.password; +} +function isPropertyEqual(a, b, state, property) { + if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE) && (a.$$typeof || b.$$typeof)) { + return true; + } + return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state); +} +const ARRAY_BUFFER_TAG = "[object ArrayBuffer]"; +const ARGUMENTS_TAG = "[object Arguments]"; +const BOOLEAN_TAG = "[object Boolean]"; +const DATA_VIEW_TAG = "[object DataView]"; +const DATE_TAG = "[object Date]"; +const ERROR_TAG = "[object Error]"; +const MAP_TAG = "[object Map]"; +const NUMBER_TAG = "[object Number]"; +const OBJECT_TAG = "[object Object]"; +const REG_EXP_TAG = "[object RegExp]"; +const SET_TAG = "[object Set]"; +const STRING_TAG = "[object String]"; +const TYPED_ARRAY_TAGS = { + "[object Int8Array]": true, + "[object Uint8Array]": true, + "[object Uint8ClampedArray]": true, + "[object Int16Array]": true, + "[object Uint16Array]": true, + "[object Int32Array]": true, + "[object Uint32Array]": true, + "[object Float16Array]": true, + "[object Float32Array]": true, + "[object Float64Array]": true, + "[object BigInt64Array]": true, + "[object BigUint64Array]": true +}; +const URL_TAG = "[object URL]"; +const toString = Object.prototype.toString; +function createEqualityComparator({ areArrayBuffersEqual: areArrayBuffersEqual2, areArraysEqual: areArraysEqual2, areDataViewsEqual: areDataViewsEqual2, areDatesEqual: areDatesEqual2, areErrorsEqual: areErrorsEqual2, areFunctionsEqual: areFunctionsEqual2, areMapsEqual: areMapsEqual2, areNumbersEqual: areNumbersEqual2, areObjectsEqual: areObjectsEqual2, arePrimitiveWrappersEqual: arePrimitiveWrappersEqual2, areRegExpsEqual: areRegExpsEqual2, areSetsEqual: areSetsEqual2, areTypedArraysEqual: areTypedArraysEqual2, areUrlsEqual: areUrlsEqual2, unknownTagComparators }) { + return function comparator(a, b, state) { + if (a === b) { + return true; + } + if (a == null || b == null) { + return false; + } + const type = typeof a; + if (type !== typeof b) { + return false; + } + if (type !== "object") { + if (type === "number") { + return areNumbersEqual2(a, b, state); + } + if (type === "function") { + return areFunctionsEqual2(a, b, state); + } + return false; + } + const constructor = a.constructor; + if (constructor !== b.constructor) { + return false; + } + if (constructor === Object) { + return areObjectsEqual2(a, b, state); + } + if (Array.isArray(a)) { + return areArraysEqual2(a, b, state); + } + if (constructor === Date) { + return areDatesEqual2(a, b, state); + } + if (constructor === RegExp) { + return areRegExpsEqual2(a, b, state); + } + if (constructor === Map) { + return areMapsEqual2(a, b, state); + } + if (constructor === Set) { + return areSetsEqual2(a, b, state); + } + const tag = toString.call(a); + if (tag === DATE_TAG) { + return areDatesEqual2(a, b, state); + } + if (tag === REG_EXP_TAG) { + return areRegExpsEqual2(a, b, state); + } + if (tag === MAP_TAG) { + return areMapsEqual2(a, b, state); + } + if (tag === SET_TAG) { + return areSetsEqual2(a, b, state); + } + if (tag === OBJECT_TAG) { + return typeof a.then !== "function" && typeof b.then !== "function" && areObjectsEqual2(a, b, state); + } + if (tag === URL_TAG) { + return areUrlsEqual2(a, b, state); + } + if (tag === ERROR_TAG) { + return areErrorsEqual2(a, b, state); + } + if (tag === ARGUMENTS_TAG) { + return areObjectsEqual2(a, b, state); + } + if (TYPED_ARRAY_TAGS[tag]) { + return areTypedArraysEqual2(a, b, state); + } + if (tag === ARRAY_BUFFER_TAG) { + return areArrayBuffersEqual2(a, b, state); + } + if (tag === DATA_VIEW_TAG) { + return areDataViewsEqual2(a, b, state); + } + if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) { + return arePrimitiveWrappersEqual2(a, b, state); + } + if (unknownTagComparators) { + let unknownTagComparator = unknownTagComparators[tag]; + if (!unknownTagComparator) { + const shortTag = getShortTag(a); + if (shortTag) { + unknownTagComparator = unknownTagComparators[shortTag]; + } + } + if (unknownTagComparator) { + return unknownTagComparator(a, b, state); + } + } + return false; + }; +} +function createEqualityComparatorConfig({ circular, createCustomConfig, strict }) { + let config = { + areArrayBuffersEqual, + areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual, + areDataViewsEqual, + areDatesEqual, + areErrorsEqual, + areFunctionsEqual, + areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual, + areNumbersEqual, + areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual, + arePrimitiveWrappersEqual, + areRegExpsEqual, + areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual, + areTypedArraysEqual: strict ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict) : areTypedArraysEqual, + areUrlsEqual, + unknownTagComparators: void 0 + }; + if (createCustomConfig) { + config = Object.assign({}, config, createCustomConfig(config)); + } + if (circular) { + const areArraysEqual2 = createIsCircular(config.areArraysEqual); + const areMapsEqual2 = createIsCircular(config.areMapsEqual); + const areObjectsEqual2 = createIsCircular(config.areObjectsEqual); + const areSetsEqual2 = createIsCircular(config.areSetsEqual); + config = Object.assign({}, config, { + areArraysEqual: areArraysEqual2, + areMapsEqual: areMapsEqual2, + areObjectsEqual: areObjectsEqual2, + areSetsEqual: areSetsEqual2 + }); + } + return config; +} +function createInternalEqualityComparator(compare) { + return function(a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) { + return compare(a, b, state); + }; +} +function createIsEqual({ circular, comparator, createState, equals, strict }) { + if (createState) { + return function isEqual(a, b) { + const { cache = circular ? /* @__PURE__ */ new WeakMap() : void 0, meta } = createState(); + return comparator(a, b, { + cache, + equals, + meta, + strict + }); + }; + } + if (circular) { + return function isEqual(a, b) { + return comparator(a, b, { + cache: /* @__PURE__ */ new WeakMap(), + equals, + meta: void 0, + strict + }); + }; + } + const state = { + cache: void 0, + equals, + meta: void 0, + strict + }; + return function isEqual(a, b) { + return comparator(a, b, state); + }; +} +const deepEqual = createCustomEqual(); +createCustomEqual({ strict: true }); +createCustomEqual({ circular: true }); +createCustomEqual({ + circular: true, + strict: true +}); +createCustomEqual({ + createInternalComparator: () => sameValueZeroEqual +}); +createCustomEqual({ + strict: true, + createInternalComparator: () => sameValueZeroEqual +}); +createCustomEqual({ + circular: true, + createInternalComparator: () => sameValueZeroEqual +}); +createCustomEqual({ + circular: true, + createInternalComparator: () => sameValueZeroEqual, + strict: true +}); +function createCustomEqual(options = {}) { + const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false } = options; + const config = createEqualityComparatorConfig(options); + const comparator = createEqualityComparator(config); + const equals = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator); + return createIsEqual({ circular, comparator, createState, equals, strict }); +} +var withSelector = { exports: {} }; +var withSelector_production = {}; +var hasRequiredWithSelector_production; +function requireWithSelector_production() { + if (hasRequiredWithSelector_production) return withSelector_production; + hasRequiredWithSelector_production = 1; + var React2 = requireReact(), shim2 = requireShim(); + function is(x, y) { + return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; + } + var objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef = React2.useRef, useEffect = React2.useEffect, useMemo = React2.useMemo, useDebugValue = React2.useDebugValue; + withSelector_production.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { + var instRef = useRef(null); + if (null === instRef.current) { + var inst = { hasValue: false, value: null }; + instRef.current = inst; + } else inst = instRef.current; + instRef = useMemo( + function() { + function memoizedSelector(nextSnapshot) { + if (!hasMemo) { + hasMemo = true; + memoizedSnapshot = nextSnapshot; + nextSnapshot = selector(nextSnapshot); + if (void 0 !== isEqual && inst.hasValue) { + var currentSelection = inst.value; + if (isEqual(currentSelection, nextSnapshot)) + return memoizedSelection = currentSelection; + } + return memoizedSelection = nextSnapshot; + } + currentSelection = memoizedSelection; + if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection; + var nextSelection = selector(nextSnapshot); + if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) + return memoizedSnapshot = nextSnapshot, currentSelection; + memoizedSnapshot = nextSnapshot; + return memoizedSelection = nextSelection; + } + var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; + return [ + function() { + return memoizedSelector(getSnapshot()); + }, + null === maybeGetServerSnapshot ? void 0 : function() { + return memoizedSelector(maybeGetServerSnapshot()); + } + ]; + }, + [getSnapshot, getServerSnapshot, selector, isEqual] + ); + var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]); + useEffect( + function() { + inst.hasValue = true; + inst.value = value; + }, + [value] + ); + useDebugValue(value); + return value; + }; + return withSelector_production; +} +var withSelector_development = {}; +var hasRequiredWithSelector_development; +function requireWithSelector_development() { + if (hasRequiredWithSelector_development) return withSelector_development; + hasRequiredWithSelector_development = 1; + "production" !== process.env.NODE_ENV && (function() { + function is(x, y) { + return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var React2 = requireReact(), shim2 = requireShim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef = React2.useRef, useEffect = React2.useEffect, useMemo = React2.useMemo, useDebugValue = React2.useDebugValue; + withSelector_development.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { + var instRef = useRef(null); + if (null === instRef.current) { + var inst = { hasValue: false, value: null }; + instRef.current = inst; + } else inst = instRef.current; + instRef = useMemo( + function() { + function memoizedSelector(nextSnapshot) { + if (!hasMemo) { + hasMemo = true; + memoizedSnapshot = nextSnapshot; + nextSnapshot = selector(nextSnapshot); + if (void 0 !== isEqual && inst.hasValue) { + var currentSelection = inst.value; + if (isEqual(currentSelection, nextSnapshot)) + return memoizedSelection = currentSelection; + } + return memoizedSelection = nextSnapshot; + } + currentSelection = memoizedSelection; + if (objectIs(memoizedSnapshot, nextSnapshot)) + return currentSelection; + var nextSelection = selector(nextSnapshot); + if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) + return memoizedSnapshot = nextSnapshot, currentSelection; + memoizedSnapshot = nextSnapshot; + return memoizedSelection = nextSelection; + } + var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; + return [ + function() { + return memoizedSelector(getSnapshot()); + }, + null === maybeGetServerSnapshot ? void 0 : function() { + return memoizedSelector(maybeGetServerSnapshot()); + } + ]; + }, + [getSnapshot, getServerSnapshot, selector, isEqual] + ); + var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]); + useEffect( + function() { + inst.hasValue = true; + inst.value = value; + }, + [value] + ); + useDebugValue(value); + return value; + }; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + return withSelector_development; +} +var hasRequiredWithSelector; +function requireWithSelector() { + if (hasRequiredWithSelector) return withSelector.exports; + hasRequiredWithSelector = 1; + if (process.env.NODE_ENV === "production") { + withSelector.exports = requireWithSelector_production(); + } else { + withSelector.exports = requireWithSelector_development(); + } + return withSelector.exports; +} +var withSelectorExports = requireWithSelector(); +var mergeRefs = (...refs) => { + return (node) => { + refs.forEach((ref) => { + if (typeof ref === "function") { + ref(node); + } else if (ref) { + ref.current = node; + } + }); + }; +}; +var Portals = ({ contentComponent }) => { + const renderers = shimExports.useSyncExternalStore( + contentComponent.subscribe, + contentComponent.getSnapshot, + contentComponent.getServerSnapshot + ); + return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: Object.values(renderers) }); +}; +function getInstance() { + const subscribers = /* @__PURE__ */ new Set(); + let renderers = {}; + return { + /** + * Subscribe to the editor instance's changes. + */ + subscribe(callback) { + subscribers.add(callback); + return () => { + subscribers.delete(callback); + }; + }, + getSnapshot() { + return renderers; + }, + getServerSnapshot() { + return renderers; + }, + /** + * Adds a new NodeView Renderer to the editor. + */ + setRenderer(id, renderer) { + renderers = { + ...renderers, + [id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id) + }; + subscribers.forEach((subscriber) => subscriber()); + }, + /** + * Removes a NodeView Renderer from the editor. + */ + removeRenderer(id) { + const nextRenderers = { ...renderers }; + delete nextRenderers[id]; + renderers = nextRenderers; + subscribers.forEach((subscriber) => subscriber()); + } + }; +} +var PureEditorContent = class extends React.Component { + constructor(props) { + var _a; + super(props); + this.editorContentRef = React.createRef(); + this.initialized = false; + this.state = { + hasContentComponentInitialized: Boolean((_a = props.editor) == null ? void 0 : _a.contentComponent) + }; + } + componentDidMount() { + this.init(); + } + componentDidUpdate() { + this.init(); + } + init() { + var _a; + const editor = this.props.editor; + if (editor && !editor.isDestroyed && ((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) { + if (editor.contentComponent) { + return; + } + const element = this.editorContentRef.current; + element.append(...editor.view.dom.parentNode.childNodes); + editor.setOptions({ + element + }); + editor.contentComponent = getInstance(); + if (!this.state.hasContentComponentInitialized) { + this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => { + this.setState((prevState) => { + if (!prevState.hasContentComponentInitialized) { + return { + hasContentComponentInitialized: true + }; + } + return prevState; + }); + if (this.unsubscribeToContentComponent) { + this.unsubscribeToContentComponent(); + } + }); + } + editor.createNodeViews(); + this.initialized = true; + } + } + componentWillUnmount() { + var _a; + const editor = this.props.editor; + if (!editor) { + return; + } + this.initialized = false; + if (!editor.isDestroyed) { + editor.view.setProps({ + nodeViews: {} + }); + } + if (this.unsubscribeToContentComponent) { + this.unsubscribeToContentComponent(); + } + editor.contentComponent = null; + try { + if (!((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) { + return; + } + const newElement = document.createElement("div"); + newElement.append(...editor.view.dom.parentNode.childNodes); + editor.setOptions({ + element: newElement + }); + } catch { + } + } + render() { + const { editor, innerRef, ...rest } = this.props; + return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }), + (editor == null ? void 0 : editor.contentComponent) && /* @__PURE__ */ jsxRuntimeExports.jsx(Portals, { contentComponent: editor.contentComponent }) + ] }); + } +}; +var EditorContentWithKey = reactExports.forwardRef( + (props, ref) => { + const key = React.useMemo(() => { + return Math.floor(Math.random() * 4294967295).toString(); + }, [props.editor]); + return React.createElement(PureEditorContent, { + key, + innerRef: ref, + ...props + }); + } +); +var EditorContent = React.memo(EditorContentWithKey); +var useIsomorphicLayoutEffect = typeof window !== "undefined" ? reactExports.useLayoutEffect : reactExports.useEffect; +var EditorStateManager = class { + constructor(initialEditor) { + this.transactionNumber = 0; + this.lastTransactionNumber = 0; + this.subscribers = /* @__PURE__ */ new Set(); + this.editor = initialEditor; + this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }; + this.getSnapshot = this.getSnapshot.bind(this); + this.getServerSnapshot = this.getServerSnapshot.bind(this); + this.watch = this.watch.bind(this); + this.subscribe = this.subscribe.bind(this); + } + /** + * Get the current editor instance. + */ + getSnapshot() { + if (this.transactionNumber === this.lastTransactionNumber) { + return this.lastSnapshot; + } + this.lastTransactionNumber = this.transactionNumber; + this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }; + return this.lastSnapshot; + } + /** + * Always disable the editor on the server-side. + */ + getServerSnapshot() { + return { editor: null, transactionNumber: 0 }; + } + /** + * Subscribe to the editor instance's changes. + */ + subscribe(callback) { + this.subscribers.add(callback); + return () => { + this.subscribers.delete(callback); + }; + } + /** + * Watch the editor instance for changes. + */ + watch(nextEditor) { + this.editor = nextEditor; + if (this.editor) { + const fn = () => { + this.transactionNumber += 1; + this.subscribers.forEach((callback) => callback()); + }; + const currentEditor = this.editor; + currentEditor.on("transaction", fn); + return () => { + currentEditor.off("transaction", fn); + }; + } + return void 0; + } +}; +function useEditorState(options) { + var _a; + const [editorStateManager] = reactExports.useState(() => new EditorStateManager(options.editor)); + const selectedState = withSelectorExports.useSyncExternalStoreWithSelector( + editorStateManager.subscribe, + editorStateManager.getSnapshot, + editorStateManager.getServerSnapshot, + options.selector, + (_a = options.equalityFn) != null ? _a : deepEqual + ); + useIsomorphicLayoutEffect(() => { + return editorStateManager.watch(options.editor); + }, [options.editor, editorStateManager]); + reactExports.useDebugValue(selectedState); + return selectedState; +} +var isDev = process.env.NODE_ENV !== "production"; +var isSSR = typeof window === "undefined"; +var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next); +var EditorInstanceManager = class _EditorInstanceManager { + constructor(options) { + this.editor = null; + this.subscriptions = /* @__PURE__ */ new Set(); + this.isComponentMounted = false; + this.previousDeps = null; + this.instanceId = ""; + this.options = options; + this.subscriptions = /* @__PURE__ */ new Set(); + this.setEditor(this.getInitialEditor()); + this.scheduleDestroy(); + this.getEditor = this.getEditor.bind(this); + this.getServerSnapshot = this.getServerSnapshot.bind(this); + this.subscribe = this.subscribe.bind(this); + this.refreshEditorInstance = this.refreshEditorInstance.bind(this); + this.scheduleDestroy = this.scheduleDestroy.bind(this); + this.onRender = this.onRender.bind(this); + this.createEditor = this.createEditor.bind(this); + } + setEditor(editor) { + this.editor = editor; + this.instanceId = Math.random().toString(36).slice(2, 9); + this.subscriptions.forEach((cb) => cb()); + } + getInitialEditor() { + if (this.options.current.immediatelyRender === void 0) { + if (isSSR || isNext) { + if (isDev) { + throw new Error( + "Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches." + ); + } + return null; + } + return this.createEditor(); + } + if (this.options.current.immediatelyRender && isSSR && isDev) { + throw new Error( + "Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches." + ); + } + if (this.options.current.immediatelyRender) { + return this.createEditor(); + } + return null; + } + /** + * Create a new editor instance. And attach event listeners. + */ + createEditor() { + const optionsToApply = { + ...this.options.current, + // Always call the most recent version of the callback function by default + onBeforeCreate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onBeforeCreate) == null ? void 0 : _b.call(_a, ...args); + }, + onBlur: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onBlur) == null ? void 0 : _b.call(_a, ...args); + }, + onCreate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onCreate) == null ? void 0 : _b.call(_a, ...args); + }, + onDestroy: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onDestroy) == null ? void 0 : _b.call(_a, ...args); + }, + onFocus: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onFocus) == null ? void 0 : _b.call(_a, ...args); + }, + onSelectionUpdate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onSelectionUpdate) == null ? void 0 : _b.call(_a, ...args); + }, + onTransaction: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onTransaction) == null ? void 0 : _b.call(_a, ...args); + }, + onUpdate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onUpdate) == null ? void 0 : _b.call(_a, ...args); + }, + onContentError: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onContentError) == null ? void 0 : _b.call(_a, ...args); + }, + onDrop: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onDrop) == null ? void 0 : _b.call(_a, ...args); + }, + onPaste: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onPaste) == null ? void 0 : _b.call(_a, ...args); + }, + onDelete: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onDelete) == null ? void 0 : _b.call(_a, ...args); + } + }; + const editor = new Editor(optionsToApply); + return editor; + } + /** + * Get the current editor instance. + */ + getEditor() { + return this.editor; + } + /** + * Always disable the editor on the server-side. + */ + getServerSnapshot() { + return null; + } + /** + * Subscribe to the editor instance's changes. + */ + subscribe(onStoreChange) { + this.subscriptions.add(onStoreChange); + return () => { + this.subscriptions.delete(onStoreChange); + }; + } + static compareOptions(a, b) { + return Object.keys(a).every((key) => { + if ([ + "onCreate", + "onBeforeCreate", + "onDestroy", + "onUpdate", + "onTransaction", + "onFocus", + "onBlur", + "onSelectionUpdate", + "onContentError", + "onDrop", + "onPaste" + ].includes(key)) { + return true; + } + if (key === "extensions" && a.extensions && b.extensions) { + if (a.extensions.length !== b.extensions.length) { + return false; + } + return a.extensions.every((extension, index) => { + var _a; + if (extension !== ((_a = b.extensions) == null ? void 0 : _a[index])) { + return false; + } + return true; + }); + } + if (a[key] !== b[key]) { + return false; + } + return true; + }); + } + /** + * On each render, we will create, update, or destroy the editor instance. + * @param deps The dependencies to watch for changes + * @returns A cleanup function + */ + onRender(deps) { + return () => { + this.isComponentMounted = true; + clearTimeout(this.scheduledDestructionTimeout); + if (this.editor && !this.editor.isDestroyed && deps.length === 0) { + if (!_EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) { + this.editor.setOptions({ + ...this.options.current, + editable: this.editor.isEditable + }); + } + } else { + this.refreshEditorInstance(deps); + } + return () => { + this.isComponentMounted = false; + this.scheduleDestroy(); + }; + }; + } + /** + * Recreate the editor instance if the dependencies have changed. + */ + refreshEditorInstance(deps) { + if (this.editor && !this.editor.isDestroyed) { + if (this.previousDeps === null) { + this.previousDeps = deps; + return; + } + const depsAreEqual = this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index]); + if (depsAreEqual) { + return; + } + } + if (this.editor && !this.editor.isDestroyed) { + this.editor.destroy(); + } + this.setEditor(this.createEditor()); + this.previousDeps = deps; + } + /** + * Schedule the destruction of the editor instance. + * This will only destroy the editor if it was not mounted on the next tick. + * This is to avoid destroying the editor instance when it's actually still mounted. + */ + scheduleDestroy() { + const currentInstanceId = this.instanceId; + const currentEditor = this.editor; + this.scheduledDestructionTimeout = setTimeout(() => { + if (this.isComponentMounted && this.instanceId === currentInstanceId) { + if (currentEditor) { + currentEditor.setOptions(this.options.current); + } + return; + } + if (currentEditor && !currentEditor.isDestroyed) { + currentEditor.destroy(); + if (this.instanceId === currentInstanceId) { + this.setEditor(null); + } + } + }, 1); + } +}; +function useEditor(options = {}, deps = []) { + const mostRecentOptions = reactExports.useRef(options); + mostRecentOptions.current = options; + const [instanceManager] = reactExports.useState(() => new EditorInstanceManager(mostRecentOptions)); + const editor = shimExports.useSyncExternalStore( + instanceManager.subscribe, + instanceManager.getEditor, + instanceManager.getServerSnapshot + ); + reactExports.useDebugValue(editor); + reactExports.useEffect(instanceManager.onRender(deps)); + useEditorState({ + editor, + selector: ({ transactionNumber }) => { + if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === void 0) { + return null; + } + if (options.immediatelyRender && transactionNumber === 0) { + return 0; + } + return transactionNumber + 1; + } + }); + return editor; +} +var EditorContext = reactExports.createContext({ + editor: null +}); +EditorContext.Consumer; +var ReactNodeViewContext = reactExports.createContext({ + onDragStart: () => { + }, + nodeViewContentChildren: void 0, + nodeViewContentRef: () => { + } +}); +var useReactNodeView = () => reactExports.useContext(ReactNodeViewContext); +React.forwardRef((props, ref) => { + const { onDragStart } = useReactNodeView(); + const Tag = props.as || "div"; + return ( + // @ts-ignore + /* @__PURE__ */ jsxRuntimeExports.jsx( + Tag, + { + ...props, + ref, + "data-node-view-wrapper": "", + onDragStart, + style: { + whiteSpace: "normal", + ...props.style + } + } + ) + ); +}); +function isClassComponent(Component) { + return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent); +} +function isForwardRefComponent(Component) { + return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.forward_ref)" || Component.$$typeof.description === "react.forward_ref")); +} +function isMemoComponent(Component) { + return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.memo)" || Component.$$typeof.description === "react.memo")); +} +function canReceiveRef(Component) { + if (isClassComponent(Component)) { + return true; + } + if (isForwardRefComponent(Component)) { + return true; + } + if (isMemoComponent(Component)) { + const wrappedComponent = Component.type; + if (wrappedComponent) { + return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent); + } + } + return false; +} +function isReact19Plus() { + try { + if (reactExports.version) { + const majorVersion = parseInt(reactExports.version.split(".")[0], 10); + return majorVersion >= 19; + } + } catch { + } + return false; +} +var ReactRenderer = class { + /** + * Immediately creates element and renders the provided React component. + */ + constructor(component, { editor, props = {}, as = "div", className = "" }) { + this.ref = null; + this.destroyed = false; + this.id = Math.floor(Math.random() * 4294967295).toString(); + this.component = component; + this.editor = editor; + this.props = props; + this.element = document.createElement(as); + this.element.classList.add("react-renderer"); + if (className) { + this.element.classList.add(...className.split(" ")); + } + if (this.editor.isInitialized) { + reactDomExports.flushSync(() => { + this.render(); + }); + } else { + queueMicrotask(() => { + if (this.destroyed) { + return; + } + this.render(); + }); + } + } + /** + * Render the React component. + */ + render() { + var _a; + if (this.destroyed) { + return; + } + const Component = this.component; + const props = this.props; + const editor = this.editor; + const isReact19 = isReact19Plus(); + const componentCanReceiveRef = canReceiveRef(Component); + const elementProps = { ...props }; + if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) { + delete elementProps.ref; + } + if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) { + elementProps.ref = (ref) => { + this.ref = ref; + }; + } + this.reactElement = /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...elementProps }); + (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.setRenderer(this.id, this); + } + /** + * Re-renders the React component with new props. + */ + updateProps(props = {}) { + if (this.destroyed) { + return; + } + this.props = { + ...this.props, + ...props + }; + this.render(); + } + /** + * Destroy the React component. + */ + destroy() { + var _a; + this.destroyed = true; + const editor = this.editor; + (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.removeRenderer(this.id); + try { + if (this.element && this.element.parentNode) { + this.element.parentNode.removeChild(this.element); + } + } catch { + } + } + /** + * Update the attributes of the element that holds the React component. + */ + updateAttributes(attributes) { + Object.keys(attributes).forEach((key) => { + this.element.setAttribute(key, attributes[key]); + }); + } +}; +React.createContext({ + markViewContentRef: () => { + } +}); +var TiptapContext = reactExports.createContext({ + get editor() { + throw new Error("useTiptap must be used within a provider"); + } +}); +TiptapContext.displayName = "TiptapContext"; +var useTiptap = () => reactExports.useContext(TiptapContext); +function TiptapWrapper({ editor, instance, children }) { + const resolvedEditor = editor != null ? editor : instance; + if (!resolvedEditor) { + throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop."); + } + const tiptapContextValue = reactExports.useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor]); + const legacyContextValue = reactExports.useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor]); + return /* @__PURE__ */ jsxRuntimeExports.jsx(EditorContext.Provider, { value: legacyContextValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(TiptapContext.Provider, { value: tiptapContextValue, children }) }); +} +TiptapWrapper.displayName = "Tiptap"; +function TiptapContent({ ...rest }) { + const { editor } = useTiptap(); + return /* @__PURE__ */ jsxRuntimeExports.jsx(EditorContent, { editor, ...rest }); +} +TiptapContent.displayName = "Tiptap.Content"; +Object.assign(TiptapWrapper, { + /** + * The Tiptap Content component that renders the EditorContent with the editor instance from the context. + * @see TiptapContent + */ + Content: TiptapContent +}); +var h = (tag, attributes) => { + if (tag === "slot") { + return 0; + } + if (tag instanceof Function) { + return tag(attributes); + } + const { children, ...rest } = attributes != null ? attributes : {}; + if (tag === "svg") { + throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead"); + } + return [tag, rest, children]; +}; +var inputRegex$4 = /^\s*>\s$/; +var Blockquote = Node3.create({ + name: "blockquote", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + content: "block+", + group: "block", + defining: true, + parseHTML() { + return [{ tag: "blockquote" }]; + }, + renderHTML({ HTMLAttributes }) { + return /* @__PURE__ */ h("blockquote", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: /* @__PURE__ */ h("slot", {}) }); + }, + parseMarkdown: (token, helpers) => { + var _a; + const parseBlockChildren = (_a = helpers.parseBlockChildren) != null ? _a : helpers.parseChildren; + return helpers.createNode("blockquote", void 0, parseBlockChildren(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + const prefix = ">"; + const result = []; + node.content.forEach((child, index) => { + var _a, _b; + const childContent = (_b = (_a = h2.renderChild) == null ? void 0 : _a.call(h2, child, index)) != null ? _b : h2.renderChildren([child]); + const lines = childContent.split("\n"); + const linesWithPrefix = lines.map((line) => { + if (line.trim() === "") { + return prefix; + } + return `${prefix} ${line}`; + }); + result.push(linesWithPrefix.join("\n")); + }); + return result.join(` +${prefix} +`); + }, + addCommands() { + return { + setBlockquote: () => ({ commands }) => { + return commands.wrapIn(this.name); + }, + toggleBlockquote: () => ({ commands }) => { + return commands.toggleWrap(this.name); + }, + unsetBlockquote: () => ({ commands }) => { + return commands.lift(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-b": () => this.editor.commands.toggleBlockquote() + }; + }, + addInputRules() { + return [ + wrappingInputRule({ + find: inputRegex$4, + type: this.type + }) + ]; + } +}); +var starInputRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/; +var starPasteRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g; +var underscoreInputRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/; +var underscorePasteRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g; +var Bold = Mark2.create({ + name: "bold", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "strong" + }, + { + tag: "b", + getAttrs: (node) => node.style.fontWeight !== "normal" && null + }, + { + style: "font-weight=400", + clearMark: (mark) => mark.type.name === this.name + }, + { + style: "font-weight", + getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return /* @__PURE__ */ h("strong", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: /* @__PURE__ */ h("slot", {}) }); + }, + markdownTokenName: "strong", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("bold", helpers.parseInline(token.tokens || [])); + }, + markdownOptions: { + htmlReopen: { + open: "", + close: "" + } + }, + renderMarkdown: (node, h2) => { + return `**${h2.renderChildren(node)}**`; + }, + addCommands() { + return { + setBold: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleBold: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetBold: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-b": () => this.editor.commands.toggleBold(), + "Mod-B": () => this.editor.commands.toggleBold() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: starInputRegex$1, + type: this.type + }), + markInputRule({ + find: underscoreInputRegex$1, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: starPasteRegex$1, + type: this.type + }), + markPasteRule({ + find: underscorePasteRegex$1, + type: this.type + }) + ]; + } +}); +var inputRegex$3 = /(^|[^`])`([^`]+)`(?!`)$/; +var pasteRegex$1 = /(^|[^`])`([^`]+)`(?!`)/g; +var Code = Mark2.create({ + name: "code", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + excludes: "_", + code: true, + exitable: true, + parseHTML() { + return [{ tag: "code" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "codespan", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("code", [{ type: "text", text: token.text || "" }]); + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return `\`${h2.renderChildren(node.content)}\``; + }, + addCommands() { + return { + setCode: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleCode: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetCode: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-e": () => this.editor.commands.toggleCode() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: inputRegex$3, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: pasteRegex$1, + type: this.type + }) + ]; + } +}); +var DEFAULT_TAB_SIZE = 4; +var backtickInputRegex = /^```([a-z]+)?[\s\n]$/; +var tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/; +var CodeBlock = Node3.create({ + name: "codeBlock", + addOptions() { + return { + languageClassPrefix: "language-", + exitOnTripleEnter: true, + exitOnArrowDown: true, + defaultLanguage: null, + enableTabIndentation: false, + tabSize: DEFAULT_TAB_SIZE, + HTMLAttributes: {} + }; + }, + content: "text*", + marks: "", + group: "block", + code: true, + defining: true, + addAttributes() { + return { + language: { + default: this.options.defaultLanguage, + parseHTML: (element) => { + var _a; + const { languageClassPrefix } = this.options; + if (!languageClassPrefix) { + return null; + } + const classNames = [...((_a = element.firstElementChild) == null ? void 0 : _a.classList) || []]; + const languages = classNames.filter((className) => className.startsWith(languageClassPrefix)).map((className) => className.replace(languageClassPrefix, "")); + const language = languages[0]; + if (!language) { + return null; + } + return language; + }, + rendered: false + } + }; + }, + parseHTML() { + return [ + { + tag: "pre", + preserveWhitespace: "full" + } + ]; + }, + renderHTML({ node, HTMLAttributes }) { + return [ + "pre", + mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), + [ + "code", + { + class: node.attrs.language ? this.options.languageClassPrefix + node.attrs.language : null + }, + 0 + ] + ]; + }, + markdownTokenName: "code", + parseMarkdown: (token, helpers) => { + var _a, _b; + if (((_a = token.raw) == null ? void 0 : _a.startsWith("```")) === false && ((_b = token.raw) == null ? void 0 : _b.startsWith("~~~")) === false && token.codeBlockStyle !== "indented") { + return []; + } + return helpers.createNode( + "codeBlock", + { language: token.lang || null }, + token.text ? [helpers.createTextNode(token.text)] : [] + ); + }, + renderMarkdown: (node, h2) => { + var _a; + let output = ""; + const language = ((_a = node.attrs) == null ? void 0 : _a.language) || ""; + if (!node.content) { + output = `\`\`\`${language} + +\`\`\``; + } else { + const lines = [`\`\`\`${language}`, h2.renderChildren(node.content), "```"]; + output = lines.join("\n"); + } + return output; + }, + addCommands() { + return { + setCodeBlock: (attributes) => ({ commands }) => { + return commands.setNode(this.name, attributes); + }, + toggleCodeBlock: (attributes) => ({ commands }) => { + return commands.toggleNode(this.name, "paragraph", attributes); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Alt-c": () => this.editor.commands.toggleCodeBlock(), + // remove code block when at start of document or code block is empty + Backspace: () => { + const { empty: empty2, $anchor } = this.editor.state.selection; + const isAtStart = $anchor.pos === 1; + if (!empty2 || $anchor.parent.type.name !== this.name) { + return false; + } + if (isAtStart || !$anchor.parent.textContent.length) { + return this.editor.commands.clearNodes(); + } + return false; + }, + // handle tab indentation + Tab: ({ editor }) => { + var _a; + if (!this.options.enableTabIndentation) { + return false; + } + const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE; + const { state } = editor; + const { selection } = state; + const { $from, empty: empty2 } = selection; + if ($from.parent.type !== this.type) { + return false; + } + const indent = " ".repeat(tabSize); + if (empty2) { + return editor.commands.insertContent(indent); + } + return editor.commands.command(({ tr: tr2 }) => { + const { from: from2, to } = selection; + const text = state.doc.textBetween(from2, to, "\n", "\n"); + const lines = text.split("\n"); + const indentedText = lines.map((line) => indent + line).join("\n"); + tr2.replaceWith(from2, to, state.schema.text(indentedText)); + return true; + }); + }, + // handle shift+tab reverse indentation + "Shift-Tab": ({ editor }) => { + var _a; + if (!this.options.enableTabIndentation) { + return false; + } + const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE; + const { state } = editor; + const { selection } = state; + const { $from, empty: empty2 } = selection; + if ($from.parent.type !== this.type) { + return false; + } + if (empty2) { + return editor.commands.command(({ tr: tr2 }) => { + var _a2; + const { pos } = $from; + const codeBlockStart = $from.start(); + const codeBlockEnd = $from.end(); + const allText = state.doc.textBetween(codeBlockStart, codeBlockEnd, "\n", "\n"); + const lines = allText.split("\n"); + let currentLineIndex = 0; + let charCount = 0; + const relativeCursorPos = pos - codeBlockStart; + for (let i = 0; i < lines.length; i += 1) { + if (charCount + lines[i].length >= relativeCursorPos) { + currentLineIndex = i; + break; + } + charCount += lines[i].length + 1; + } + const currentLine = lines[currentLineIndex]; + const leadingSpaces = ((_a2 = currentLine.match(/^ */)) == null ? void 0 : _a2[0]) || ""; + const spacesToRemove = Math.min(leadingSpaces.length, tabSize); + if (spacesToRemove === 0) { + return true; + } + let lineStartPos = codeBlockStart; + for (let i = 0; i < currentLineIndex; i += 1) { + lineStartPos += lines[i].length + 1; + } + tr2.delete(lineStartPos, lineStartPos + spacesToRemove); + const cursorPosInLine = pos - lineStartPos; + if (cursorPosInLine <= spacesToRemove) { + tr2.setSelection(TextSelection.create(tr2.doc, lineStartPos)); + } + return true; + }); + } + return editor.commands.command(({ tr: tr2 }) => { + const { from: from2, to } = selection; + const text = state.doc.textBetween(from2, to, "\n", "\n"); + const lines = text.split("\n"); + const reverseIndentText = lines.map((line) => { + var _a2; + const leadingSpaces = ((_a2 = line.match(/^ */)) == null ? void 0 : _a2[0]) || ""; + const spacesToRemove = Math.min(leadingSpaces.length, tabSize); + return line.slice(spacesToRemove); + }).join("\n"); + tr2.replaceWith(from2, to, state.schema.text(reverseIndentText)); + return true; + }); + }, + // exit node on triple enter + Enter: ({ editor }) => { + if (!this.options.exitOnTripleEnter) { + return false; + } + const { state } = editor; + const { selection } = state; + const { $from, empty: empty2 } = selection; + if (!empty2 || $from.parent.type !== this.type) { + return false; + } + const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; + const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n"); + if (!isAtEnd || !endsWithDoubleNewline) { + return false; + } + return editor.chain().command(({ tr: tr2 }) => { + tr2.delete($from.pos - 2, $from.pos); + return true; + }).exitCode().run(); + }, + // exit node on arrow down + ArrowDown: ({ editor }) => { + if (!this.options.exitOnArrowDown) { + return false; + } + const { state } = editor; + const { selection, doc: doc2 } = state; + const { $from, empty: empty2 } = selection; + if (!empty2 || $from.parent.type !== this.type) { + return false; + } + const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; + if (!isAtEnd) { + return false; + } + const after = $from.after(); + if (after === void 0) { + return false; + } + const nodeAfter = doc2.nodeAt(after); + if (nodeAfter) { + return editor.commands.command(({ tr: tr2 }) => { + tr2.setSelection(Selection.near(doc2.resolve(after))); + return true; + }); + } + return editor.commands.exitCode(); + } + }; + }, + addInputRules() { + return [ + textblockTypeInputRule({ + find: backtickInputRegex, + type: this.type, + getAttributes: (match) => ({ + language: match[1] + }) + }), + textblockTypeInputRule({ + find: tildeInputRegex, + type: this.type, + getAttributes: (match) => ({ + language: match[1] + }) + }) + ]; + }, + addProseMirrorPlugins() { + return [ + // this plugin creates a code block for pasted content from VS Code + // we can also detect the copied code language + new Plugin({ + key: new PluginKey("codeBlockVSCodeHandler"), + props: { + handlePaste: (view, event) => { + if (!event.clipboardData) { + return false; + } + if (this.editor.isActive(this.type.name)) { + return false; + } + const text = event.clipboardData.getData("text/plain"); + const vscode = event.clipboardData.getData("vscode-editor-data"); + const vscodeData = vscode ? JSON.parse(vscode) : void 0; + const language = vscodeData == null ? void 0 : vscodeData.mode; + if (!text || !language) { + return false; + } + const { tr: tr2, schema } = view.state; + const textNode = schema.text(text.replace(/\r\n?/g, "\n")); + tr2.replaceSelectionWith(this.type.create({ language }, textNode)); + if (tr2.selection.$from.parent.type !== this.type) { + tr2.setSelection(TextSelection.near(tr2.doc.resolve(Math.max(0, tr2.selection.from - 2)))); + } + tr2.setMeta("paste", true); + view.dispatch(tr2); + return true; + } + } + }) + ]; + } +}); +var Document = Node3.create({ + name: "doc", + topNode: true, + content: "block+", + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n\n"); + } +}); +var HardBreak = Node3.create({ + name: "hardBreak", + markdownTokenName: "br", + addOptions() { + return { + keepMarks: true, + HTMLAttributes: {} + }; + }, + inline: true, + group: "inline", + selectable: false, + linebreakReplacement: true, + parseHTML() { + return [{ tag: "br" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["br", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; + }, + renderText() { + return "\n"; + }, + renderMarkdown: () => ` +`, + parseMarkdown: () => { + return { + type: "hardBreak" + }; + }, + addCommands() { + return { + setHardBreak: () => ({ commands, chain, state, editor }) => { + return commands.first([ + () => commands.exitCode(), + () => commands.command(() => { + const { selection, storedMarks } = state; + if (selection.$from.parent.type.spec.isolating) { + return false; + } + const { keepMarks } = this.options; + const { splittableMarks } = editor.extensionManager; + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + return chain().insertContent({ type: this.name }).command(({ tr: tr2, dispatch }) => { + if (dispatch && marks && keepMarks) { + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr2.ensureMarks(filteredMarks); + } + return true; + }).run(); + }) + ]); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Enter": () => this.editor.commands.setHardBreak(), + "Shift-Enter": () => this.editor.commands.setHardBreak() + }; + } +}); +var Heading = Node3.create({ + name: "heading", + addOptions() { + return { + levels: [1, 2, 3, 4, 5, 6], + HTMLAttributes: {} + }; + }, + content: "inline*", + group: "block", + defining: true, + addAttributes() { + return { + level: { + default: 1, + rendered: false + } + }; + }, + parseHTML() { + return this.options.levels.map((level) => ({ + tag: `h${level}`, + attrs: { level } + })); + }, + renderHTML({ node, HTMLAttributes }) { + const hasLevel = this.options.levels.includes(node.attrs.level); + const level = hasLevel ? node.attrs.level : this.options.levels[0]; + return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + parseMarkdown: (token, helpers) => { + return helpers.createNode("heading", { level: token.depth || 1 }, helpers.parseInline(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + var _a; + const level = ((_a = node.attrs) == null ? void 0 : _a.level) ? parseInt(node.attrs.level, 10) : 1; + const headingChars = "#".repeat(level); + if (!node.content) { + return ""; + } + return `${headingChars} ${h2.renderChildren(node.content)}`; + }, + addCommands() { + return { + setHeading: (attributes) => ({ commands }) => { + if (!this.options.levels.includes(attributes.level)) { + return false; + } + return commands.setNode(this.name, attributes); + }, + toggleHeading: (attributes) => ({ commands }) => { + if (!this.options.levels.includes(attributes.level)) { + return false; + } + return commands.toggleNode(this.name, "paragraph", attributes); + } + }; + }, + addKeyboardShortcuts() { + return this.options.levels.reduce( + (items, level) => ({ + ...items, + ...{ + [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }) + } + }), + {} + ); + }, + addInputRules() { + return this.options.levels.map((level) => { + return textblockTypeInputRule({ + find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\s$`), + type: this.type, + getAttributes: { + level + } + }); + }); + } +}); +var HorizontalRule = Node3.create({ + name: "horizontalRule", + addOptions() { + return { + HTMLAttributes: {}, + nextNodeType: "paragraph" + }; + }, + group: "block", + parseHTML() { + return [{ tag: "hr" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["hr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; + }, + markdownTokenName: "hr", + parseMarkdown: (token, helpers) => { + return helpers.createNode("horizontalRule"); + }, + renderMarkdown: () => { + return "---"; + }, + addCommands() { + return { + setHorizontalRule: () => ({ chain, state }) => { + if (!canInsertNode(state, state.schema.nodes[this.name])) { + return false; + } + const { selection } = state; + const { $to: $originTo } = selection; + const currentChain = chain(); + if (isNodeSelection(selection)) { + currentChain.insertContentAt($originTo.pos, { + type: this.name + }); + } else { + currentChain.insertContent({ type: this.name }); + } + return currentChain.command(({ state: chainState, tr: tr2, dispatch }) => { + if (dispatch) { + const { $to } = tr2.selection; + const posAfter = $to.end(); + if ($to.nodeAfter) { + if ($to.nodeAfter.isTextblock) { + tr2.setSelection(TextSelection.create(tr2.doc, $to.pos + 1)); + } else if ($to.nodeAfter.isBlock) { + tr2.setSelection(NodeSelection.create(tr2.doc, $to.pos)); + } else { + tr2.setSelection(TextSelection.create(tr2.doc, $to.pos)); + } + } else { + const nodeType = chainState.schema.nodes[this.options.nextNodeType] || $to.parent.type.contentMatch.defaultType; + const node = nodeType == null ? void 0 : nodeType.create(); + if (node) { + tr2.insert(posAfter, node); + tr2.setSelection(TextSelection.create(tr2.doc, posAfter + 1)); + } + } + tr2.scrollIntoView(); + } + return true; + }).run(); + } + }; + }, + addInputRules() { + return [ + nodeInputRule({ + find: /^(?:---|—-|___\s|\*\*\*\s)$/, + type: this.type + }) + ]; + } +}); +var starInputRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/; +var starPasteRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g; +var underscoreInputRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/; +var underscorePasteRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g; +var Italic = Mark2.create({ + name: "italic", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "em" + }, + { + tag: "i", + getAttrs: (node) => node.style.fontStyle !== "normal" && null + }, + { + style: "font-style=normal", + clearMark: (mark) => mark.type.name === this.name + }, + { + style: "font-style=italic" + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + addCommands() { + return { + setItalic: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleItalic: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetItalic: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + markdownTokenName: "em", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("italic", helpers.parseInline(token.tokens || [])); + }, + markdownOptions: { + htmlReopen: { + open: "", + close: "" + } + }, + renderMarkdown: (node, h2) => { + return `*${h2.renderChildren(node)}*`; + }, + addKeyboardShortcuts() { + return { + "Mod-i": () => this.editor.commands.toggleItalic(), + "Mod-I": () => this.editor.commands.toggleItalic() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: starInputRegex, + type: this.type + }), + markInputRule({ + find: underscoreInputRegex, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: starPasteRegex, + type: this.type + }), + markPasteRule({ + find: underscorePasteRegex, + type: this.type + }) + ]; + } +}); +const encodedTlds = "aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2"; +const encodedUtlds = "ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2"; +const numeric = "numeric"; +const ascii = "ascii"; +const alpha = "alpha"; +const asciinumeric = "asciinumeric"; +const alphanumeric = "alphanumeric"; +const domain = "domain"; +const emoji = "emoji"; +const scheme = "scheme"; +const slashscheme = "slashscheme"; +const whitespace = "whitespace"; +function registerGroup(name, groups) { + if (!(name in groups)) { + groups[name] = []; + } + return groups[name]; +} +function addToGroups(t, flags, groups) { + if (flags[numeric]) { + flags[asciinumeric] = true; + flags[alphanumeric] = true; + } + if (flags[ascii]) { + flags[asciinumeric] = true; + flags[alpha] = true; + } + if (flags[asciinumeric]) { + flags[alphanumeric] = true; + } + if (flags[alpha]) { + flags[alphanumeric] = true; + } + if (flags[alphanumeric]) { + flags[domain] = true; + } + if (flags[emoji]) { + flags[domain] = true; + } + for (const k in flags) { + const group = registerGroup(k, groups); + if (group.indexOf(t) < 0) { + group.push(t); + } + } +} +function flagsForToken(t, groups) { + const result = {}; + for (const c in groups) { + if (groups[c].indexOf(t) >= 0) { + result[c] = true; + } + } + return result; +} +function State(token = null) { + this.j = {}; + this.jr = []; + this.jd = null; + this.t = token; +} +State.groups = {}; +State.prototype = { + accepts() { + return !!this.t; + }, + /** + * Follow an existing transition from the given input to the next state. + * Does not mutate. + * @param {string} input character or token type to transition on + * @returns {?State} the next state, if any + */ + go(input) { + const state = this; + const nextState = state.j[input]; + if (nextState) { + return nextState; + } + for (let i = 0; i < state.jr.length; i++) { + const regex = state.jr[i][0]; + const nextState2 = state.jr[i][1]; + if (nextState2 && regex.test(input)) { + return nextState2; + } + } + return state.jd; + }, + /** + * Whether the state has a transition for the given input. Set the second + * argument to true to only look for an exact match (and not a default or + * regular-expression-based transition) + * @param {string} input + * @param {boolean} exactOnly + */ + has(input, exactOnly = false) { + return exactOnly ? input in this.j : !!this.go(input); + }, + /** + * Short for "transition all"; create a transition from the array of items + * in the given list to the same final resulting state. + * @param {string | string[]} inputs Group of inputs to transition on + * @param {Transition | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of token groups + */ + ta(inputs, next, flags, groups) { + for (let i = 0; i < inputs.length; i++) { + this.tt(inputs[i], next, flags, groups); + } + }, + /** + * Short for "take regexp transition"; defines a transition for this state + * when it encounters a token which matches the given regular expression + * @param {RegExp} regexp Regular expression transition (populate first) + * @param {T | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of token groups + * @returns {State} taken after the given input + */ + tr(regexp, next, flags, groups) { + groups = groups || State.groups; + let nextState; + if (next && next.j) { + nextState = next; + } else { + nextState = new State(next); + if (flags && groups) { + addToGroups(next, flags, groups); + } + } + this.jr.push([regexp, nextState]); + return nextState; + }, + /** + * Short for "take transitions", will take as many sequential transitions as + * the length of the given input and returns the + * resulting final state. + * @param {string | string[]} input + * @param {T | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of token groups + * @returns {State} taken after the given input + */ + ts(input, next, flags, groups) { + let state = this; + const len = input.length; + if (!len) { + return state; + } + for (let i = 0; i < len - 1; i++) { + state = state.tt(input[i]); + } + return state.tt(input[len - 1], next, flags, groups); + }, + /** + * Short for "take transition", this is a method for building/working with + * state machines. + * + * If a state already exists for the given input, returns it. + * + * If a token is specified, that state will emit that token when reached by + * the linkify engine. + * + * If no state exists, it will be initialized with some default transitions + * that resemble existing default transitions. + * + * If a state is given for the second argument, that state will be + * transitioned to on the given input regardless of what that input + * previously did. + * + * Specify a token group flags to define groups that this token belongs to. + * The token will be added to corresponding entires in the given groups + * object. + * + * @param {string} input character, token type to transition on + * @param {T | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of groups + * @returns {State} taken after the given input + */ + tt(input, next, flags, groups) { + groups = groups || State.groups; + const state = this; + if (next && next.j) { + state.j[input] = next; + return next; + } + const t = next; + let nextState, templateState = state.go(input); + if (templateState) { + nextState = new State(); + Object.assign(nextState.j, templateState.j); + nextState.jr.push.apply(nextState.jr, templateState.jr); + nextState.jd = templateState.jd; + nextState.t = templateState.t; + } else { + nextState = new State(); + } + if (t) { + if (groups) { + if (nextState.t && typeof nextState.t === "string") { + const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags); + addToGroups(t, allFlags, groups); + } else if (flags) { + addToGroups(t, flags, groups); + } + } + nextState.t = t; + } + state.j[input] = nextState; + return nextState; + } +}; +const ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups); +const tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups); +const ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups); +const tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups); +const WORD = "WORD"; +const UWORD = "UWORD"; +const ASCIINUMERICAL = "ASCIINUMERICAL"; +const ALPHANUMERICAL = "ALPHANUMERICAL"; +const LOCALHOST = "LOCALHOST"; +const TLD = "TLD"; +const UTLD = "UTLD"; +const SCHEME = "SCHEME"; +const SLASH_SCHEME = "SLASH_SCHEME"; +const NUM = "NUM"; +const WS = "WS"; +const NL = "NL"; +const OPENBRACE = "OPENBRACE"; +const CLOSEBRACE = "CLOSEBRACE"; +const OPENBRACKET = "OPENBRACKET"; +const CLOSEBRACKET = "CLOSEBRACKET"; +const OPENPAREN = "OPENPAREN"; +const CLOSEPAREN = "CLOSEPAREN"; +const OPENANGLEBRACKET = "OPENANGLEBRACKET"; +const CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET"; +const FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN"; +const FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN"; +const LEFTCORNERBRACKET = "LEFTCORNERBRACKET"; +const RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET"; +const LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET"; +const RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET"; +const FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN"; +const FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN"; +const AMPERSAND = "AMPERSAND"; +const APOSTROPHE = "APOSTROPHE"; +const ASTERISK = "ASTERISK"; +const AT = "AT"; +const BACKSLASH = "BACKSLASH"; +const BACKTICK = "BACKTICK"; +const CARET = "CARET"; +const COLON = "COLON"; +const COMMA = "COMMA"; +const DOLLAR = "DOLLAR"; +const DOT = "DOT"; +const EQUALS = "EQUALS"; +const EXCLAMATION = "EXCLAMATION"; +const HYPHEN = "HYPHEN"; +const PERCENT = "PERCENT"; +const PIPE = "PIPE"; +const PLUS = "PLUS"; +const POUND = "POUND"; +const QUERY = "QUERY"; +const QUOTE = "QUOTE"; +const FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT"; +const SEMI = "SEMI"; +const SLASH = "SLASH"; +const TILDE = "TILDE"; +const UNDERSCORE = "UNDERSCORE"; +const EMOJI$1 = "EMOJI"; +const SYM = "SYM"; +var tk = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ALPHANUMERICAL, + AMPERSAND, + APOSTROPHE, + ASCIINUMERICAL, + ASTERISK, + AT, + BACKSLASH, + BACKTICK, + CARET, + CLOSEANGLEBRACKET, + CLOSEBRACE, + CLOSEBRACKET, + CLOSEPAREN, + COLON, + COMMA, + DOLLAR, + DOT, + EMOJI: EMOJI$1, + EQUALS, + EXCLAMATION, + FULLWIDTHGREATERTHAN, + FULLWIDTHLEFTPAREN, + FULLWIDTHLESSTHAN, + FULLWIDTHMIDDLEDOT, + FULLWIDTHRIGHTPAREN, + HYPHEN, + LEFTCORNERBRACKET, + LEFTWHITECORNERBRACKET, + LOCALHOST, + NL, + NUM, + OPENANGLEBRACKET, + OPENBRACE, + OPENBRACKET, + OPENPAREN, + PERCENT, + PIPE, + PLUS, + POUND, + QUERY, + QUOTE, + RIGHTCORNERBRACKET, + RIGHTWHITECORNERBRACKET, + SCHEME, + SEMI, + SLASH, + SLASH_SCHEME, + SYM, + TILDE, + TLD, + UNDERSCORE, + UTLD, + UWORD, + WORD, + WS +}); +const ASCII_LETTER = /[a-z]/; +const LETTER = new RegExp("\\p{L}", "u"); +const EMOJI = new RegExp("\\p{Emoji}", "u"); +const DIGIT = /\d/; +const SPACE = /\s/; +const CR = "\r"; +const LF = "\n"; +const EMOJI_VARIATION = "️"; +const EMOJI_JOINER = "‍"; +const OBJECT_REPLACEMENT = ""; +let tlds = null, utlds = null; +function init$2(customSchemes = []) { + const groups = {}; + State.groups = groups; + const Start = new State(); + if (tlds == null) { + tlds = decodeTlds(encodedTlds); + } + if (utlds == null) { + utlds = decodeTlds(encodedUtlds); + } + tt(Start, "'", APOSTROPHE); + tt(Start, "{", OPENBRACE); + tt(Start, "}", CLOSEBRACE); + tt(Start, "[", OPENBRACKET); + tt(Start, "]", CLOSEBRACKET); + tt(Start, "(", OPENPAREN); + tt(Start, ")", CLOSEPAREN); + tt(Start, "<", OPENANGLEBRACKET); + tt(Start, ">", CLOSEANGLEBRACKET); + tt(Start, "(", FULLWIDTHLEFTPAREN); + tt(Start, ")", FULLWIDTHRIGHTPAREN); + tt(Start, "「", LEFTCORNERBRACKET); + tt(Start, "」", RIGHTCORNERBRACKET); + tt(Start, "『", LEFTWHITECORNERBRACKET); + tt(Start, "』", RIGHTWHITECORNERBRACKET); + tt(Start, "<", FULLWIDTHLESSTHAN); + tt(Start, ">", FULLWIDTHGREATERTHAN); + tt(Start, "&", AMPERSAND); + tt(Start, "*", ASTERISK); + tt(Start, "@", AT); + tt(Start, "`", BACKTICK); + tt(Start, "^", CARET); + tt(Start, ":", COLON); + tt(Start, ",", COMMA); + tt(Start, "$", DOLLAR); + tt(Start, ".", DOT); + tt(Start, "=", EQUALS); + tt(Start, "!", EXCLAMATION); + tt(Start, "-", HYPHEN); + tt(Start, "%", PERCENT); + tt(Start, "|", PIPE); + tt(Start, "+", PLUS); + tt(Start, "#", POUND); + tt(Start, "?", QUERY); + tt(Start, '"', QUOTE); + tt(Start, "/", SLASH); + tt(Start, ";", SEMI); + tt(Start, "~", TILDE); + tt(Start, "_", UNDERSCORE); + tt(Start, "\\", BACKSLASH); + tt(Start, "・", FULLWIDTHMIDDLEDOT); + const Num = tr(Start, DIGIT, NUM, { + [numeric]: true + }); + tr(Num, DIGIT, Num); + const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, { + [asciinumeric]: true + }); + const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, { + [alphanumeric]: true + }); + const Word = tr(Start, ASCII_LETTER, WORD, { + [ascii]: true + }); + tr(Word, DIGIT, Asciinumeric); + tr(Word, ASCII_LETTER, Word); + tr(Asciinumeric, DIGIT, Asciinumeric); + tr(Asciinumeric, ASCII_LETTER, Asciinumeric); + const UWord = tr(Start, LETTER, UWORD, { + [alpha]: true + }); + tr(UWord, ASCII_LETTER); + tr(UWord, DIGIT, Alphanumeric); + tr(UWord, LETTER, UWord); + tr(Alphanumeric, DIGIT, Alphanumeric); + tr(Alphanumeric, ASCII_LETTER); + tr(Alphanumeric, LETTER, Alphanumeric); + const Nl2 = tt(Start, LF, NL, { + [whitespace]: true + }); + const Cr = tt(Start, CR, WS, { + [whitespace]: true + }); + const Ws = tr(Start, SPACE, WS, { + [whitespace]: true + }); + tt(Start, OBJECT_REPLACEMENT, Ws); + tt(Cr, LF, Nl2); + tt(Cr, OBJECT_REPLACEMENT, Ws); + tr(Cr, SPACE, Ws); + tt(Ws, CR); + tt(Ws, LF); + tr(Ws, SPACE, Ws); + tt(Ws, OBJECT_REPLACEMENT, Ws); + const Emoji = tr(Start, EMOJI, EMOJI$1, { + [emoji]: true + }); + tt(Emoji, "#"); + tr(Emoji, EMOJI, Emoji); + tt(Emoji, EMOJI_VARIATION, Emoji); + const EmojiJoiner = tt(Emoji, EMOJI_JOINER); + tt(EmojiJoiner, "#"); + tr(EmojiJoiner, EMOJI, Emoji); + const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]]; + const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]]; + for (let i = 0; i < tlds.length; i++) { + fastts(Start, tlds[i], TLD, WORD, wordjr); + } + for (let i = 0; i < utlds.length; i++) { + fastts(Start, utlds[i], UTLD, UWORD, uwordjr); + } + addToGroups(TLD, { + tld: true, + ascii: true + }, groups); + addToGroups(UTLD, { + utld: true, + alpha: true + }, groups); + fastts(Start, "file", SCHEME, WORD, wordjr); + fastts(Start, "mailto", SCHEME, WORD, wordjr); + fastts(Start, "http", SLASH_SCHEME, WORD, wordjr); + fastts(Start, "https", SLASH_SCHEME, WORD, wordjr); + fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr); + fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr); + addToGroups(SCHEME, { + scheme: true, + ascii: true + }, groups); + addToGroups(SLASH_SCHEME, { + slashscheme: true, + ascii: true + }, groups); + customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1); + for (let i = 0; i < customSchemes.length; i++) { + const sch = customSchemes[i][0]; + const optionalSlashSlash = customSchemes[i][1]; + const flags = optionalSlashSlash ? { + [scheme]: true + } : { + [slashscheme]: true + }; + if (sch.indexOf("-") >= 0) { + flags[domain] = true; + } else if (!ASCII_LETTER.test(sch)) { + flags[numeric] = true; + } else if (DIGIT.test(sch)) { + flags[asciinumeric] = true; + } else { + flags[ascii] = true; + } + ts(Start, sch, sch, flags); + } + ts(Start, "localhost", LOCALHOST, { + ascii: true + }); + Start.jd = new State(SYM); + return { + start: Start, + tokens: Object.assign({ + groups + }, tk) + }; +} +function run$1(start, str) { + const iterable = stringToArray(str.replace(/[A-Z]/g, (c) => c.toLowerCase())); + const charCount = iterable.length; + const tokens = []; + let cursor = 0; + let charCursor = 0; + while (charCursor < charCount) { + let state = start; + let nextState = null; + let tokenLength = 0; + let latestAccepting = null; + let sinceAccepts = -1; + let charsSinceAccepts = -1; + while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) { + state = nextState; + if (state.accepts()) { + sinceAccepts = 0; + charsSinceAccepts = 0; + latestAccepting = state; + } else if (sinceAccepts >= 0) { + sinceAccepts += iterable[charCursor].length; + charsSinceAccepts++; + } + tokenLength += iterable[charCursor].length; + cursor += iterable[charCursor].length; + charCursor++; + } + cursor -= sinceAccepts; + charCursor -= charsSinceAccepts; + tokenLength -= sinceAccepts; + tokens.push({ + t: latestAccepting.t, + // token type/name + v: str.slice(cursor - tokenLength, cursor), + // string value + s: cursor - tokenLength, + // start index + e: cursor + // end index (excluding) + }); + } + return tokens; +} +function stringToArray(str) { + const result = []; + const len = str.length; + let index = 0; + while (index < len) { + let first2 = str.charCodeAt(index); + let second; + let char = first2 < 55296 || first2 > 56319 || index + 1 === len || (second = str.charCodeAt(index + 1)) < 56320 || second > 57343 ? str[index] : str.slice(index, index + 2); + result.push(char); + index += char.length; + } + return result; +} +function fastts(state, input, t, defaultt, jr) { + let next; + const len = input.length; + for (let i = 0; i < len - 1; i++) { + const char = input[i]; + if (state.j[char]) { + next = state.j[char]; + } else { + next = new State(defaultt); + next.jr = jr.slice(); + state.j[char] = next; + } + state = next; + } + next = new State(t); + next.jr = jr.slice(); + state.j[input[len - 1]] = next; + return next; +} +function decodeTlds(encoded) { + const words = []; + const stack = []; + let i = 0; + let digits = "0123456789"; + while (i < encoded.length) { + let popDigitCount = 0; + while (digits.indexOf(encoded[i + popDigitCount]) >= 0) { + popDigitCount++; + } + if (popDigitCount > 0) { + words.push(stack.join("")); + for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) { + stack.pop(); + } + i += popDigitCount; + } else { + stack.push(encoded[i]); + i++; + } + } + return words; +} +const defaults = { + defaultProtocol: "http", + events: null, + format: noop, + formatHref: noop, + nl2br: false, + tagName: "a", + target: null, + rel: null, + validate: true, + truncate: Infinity, + className: null, + attributes: null, + ignoreTags: [], + render: null +}; +function Options(opts, defaultRender = null) { + let o = Object.assign({}, defaults); + if (opts) { + o = Object.assign(o, opts instanceof Options ? opts.o : opts); + } + const ignoredTags = o.ignoreTags; + const uppercaseIgnoredTags = []; + for (let i = 0; i < ignoredTags.length; i++) { + uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase()); + } + this.o = o; + if (defaultRender) { + this.defaultRender = defaultRender; + } + this.ignoreTags = uppercaseIgnoredTags; +} +Options.prototype = { + o: defaults, + /** + * @type string[] + */ + ignoreTags: [], + /** + * @param {IntermediateRepresentation} ir + * @returns {any} + */ + defaultRender(ir) { + return ir; + }, + /** + * Returns true or false based on whether a token should be displayed as a + * link based on the user options. + * @param {MultiToken} token + * @returns {boolean} + */ + check(token) { + return this.get("validate", token.toString(), token); + }, + // Private methods + /** + * Resolve an option's value based on the value of the option and the given + * params. If operator and token are specified and the target option is + * callable, automatically calls the function with the given argument. + * @template {keyof Opts} K + * @param {K} key Name of option to use + * @param {string} [operator] will be passed to the target option if it's a + * function. If not specified, RAW function value gets returned + * @param {MultiToken} [token] The token from linkify.tokenize + * @returns {Opts[K] | any} + */ + get(key, operator, token) { + const isCallable = operator != null; + let option = this.o[key]; + if (!option) { + return option; + } + if (typeof option === "object") { + option = token.t in option ? option[token.t] : defaults[key]; + if (typeof option === "function" && isCallable) { + option = option(operator, token); + } + } else if (typeof option === "function" && isCallable) { + option = option(operator, token.t, token); + } + return option; + }, + /** + * @template {keyof Opts} L + * @param {L} key Name of options object to use + * @param {string} [operator] + * @param {MultiToken} [token] + * @returns {Opts[L] | any} + */ + getObj(key, operator, token) { + let obj = this.o[key]; + if (typeof obj === "function" && operator != null) { + obj = obj(operator, token.t, token); + } + return obj; + }, + /** + * Convert the given token to a rendered element that may be added to the + * calling-interface's DOM + * @param {MultiToken} token Token to render to an HTML element + * @returns {any} Render result; e.g., HTML string, DOM element, React + * Component, etc. + */ + render(token) { + const ir = token.render(this); + const renderFn = this.get("render", null, token) || this.defaultRender; + return renderFn(ir, token.t, token); + } +}; +function noop(val) { + return val; +} +function MultiToken(value, tokens) { + this.t = "token"; + this.v = value; + this.tk = tokens; +} +MultiToken.prototype = { + isLink: false, + /** + * Return the string this token represents. + * @return {string} + */ + toString() { + return this.v; + }, + /** + * What should the value for this token be in the `href` HTML attribute? + * Returns the `.toString` value by default. + * @param {string} [scheme] + * @return {string} + */ + toHref(scheme2) { + return this.toString(); + }, + /** + * @param {Options} options Formatting options + * @returns {string} + */ + toFormattedString(options) { + const val = this.toString(); + const truncate = options.get("truncate", val, this); + const formatted = options.get("format", val, this); + return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + "…" : formatted; + }, + /** + * + * @param {Options} options + * @returns {string} + */ + toFormattedHref(options) { + return options.get("formatHref", this.toHref(options.get("defaultProtocol")), this); + }, + /** + * The start index of this token in the original input string + * @returns {number} + */ + startIndex() { + return this.tk[0].s; + }, + /** + * The end index of this token in the original input string (up to this + * index but not including it) + * @returns {number} + */ + endIndex() { + return this.tk[this.tk.length - 1].e; + }, + /** + Returns an object of relevant values for this token, which includes keys + * type - Kind of token ('url', 'email', etc.) + * value - Original text + * href - The value that should be added to the anchor tag's href + attribute + @method toObject + @param {string} [protocol] `'http'` by default + */ + toObject(protocol = defaults.defaultProtocol) { + return { + type: this.t, + value: this.toString(), + isLink: this.isLink, + href: this.toHref(protocol), + start: this.startIndex(), + end: this.endIndex() + }; + }, + /** + * + * @param {Options} options Formatting option + */ + toFormattedObject(options) { + return { + type: this.t, + value: this.toFormattedString(options), + isLink: this.isLink, + href: this.toFormattedHref(options), + start: this.startIndex(), + end: this.endIndex() + }; + }, + /** + * Whether this token should be rendered as a link according to the given options + * @param {Options} options + * @returns {boolean} + */ + validate(options) { + return options.get("validate", this.toString(), this); + }, + /** + * Return an object that represents how this link should be rendered. + * @param {Options} options Formattinng options + */ + render(options) { + const token = this; + const href = this.toHref(options.get("defaultProtocol")); + const formattedHref = options.get("formatHref", href, this); + const tagName = options.get("tagName", href, token); + const content = this.toFormattedString(options); + const attributes = {}; + const className = options.get("className", href, token); + const target = options.get("target", href, token); + const rel = options.get("rel", href, token); + const attrs = options.getObj("attributes", href, token); + const eventListeners = options.getObj("events", href, token); + attributes.href = formattedHref; + if (className) { + attributes.class = className; + } + if (target) { + attributes.target = target; + } + if (rel) { + attributes.rel = rel; + } + if (attrs) { + Object.assign(attributes, attrs); + } + return { + tagName, + attributes, + content, + eventListeners + }; + } +}; +function createTokenClass(type, props) { + class Token extends MultiToken { + constructor(value, tokens) { + super(value, tokens); + this.t = type; + } + } + for (const p in props) { + Token.prototype[p] = props[p]; + } + Token.t = type; + return Token; +} +const Email = createTokenClass("email", { + isLink: true, + toHref() { + return "mailto:" + this.toString(); + } +}); +const Text$1 = createTokenClass("text"); +const Nl = createTokenClass("nl"); +const Url = createTokenClass("url", { + isLink: true, + /** + Lowercases relevant parts of the domain and adds the protocol if + required. Note that this will not escape unsafe HTML characters in the + URL. + @param {string} [scheme] default scheme (e.g., 'https') + @return {string} the full href + */ + toHref(scheme2 = defaults.defaultProtocol) { + return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`; + }, + /** + * Check whether this URL token has a protocol + * @return {boolean} + */ + hasProtocol() { + const tokens = this.tk; + return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON; + } +}); +const makeState = (arg) => new State(arg); +function init$1({ + groups +}) { + const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]); + const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]; + const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE]; + const Start = makeState(); + const Localpart = tt(Start, TILDE); + ta(Localpart, localpartAccepting, Localpart); + ta(Localpart, groups.domain, Localpart); + const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState(); + ta(Start, groups.domain, Domain); + ta(Start, groups.scheme, Scheme); + ta(Start, groups.slashscheme, SlashScheme); + ta(Domain, localpartAccepting, Localpart); + ta(Domain, groups.domain, Domain); + const LocalpartAt = tt(Domain, AT); + tt(Localpart, AT, LocalpartAt); + tt(Scheme, AT, LocalpartAt); + tt(SlashScheme, AT, LocalpartAt); + const LocalpartDot = tt(Localpart, DOT); + ta(LocalpartDot, localpartAccepting, Localpart); + ta(LocalpartDot, groups.domain, Localpart); + const EmailDomain = makeState(); + ta(LocalpartAt, groups.domain, EmailDomain); + ta(EmailDomain, groups.domain, EmailDomain); + const EmailDomainDot = tt(EmailDomain, DOT); + ta(EmailDomainDot, groups.domain, EmailDomain); + const Email$1 = makeState(Email); + ta(EmailDomainDot, groups.tld, Email$1); + ta(EmailDomainDot, groups.utld, Email$1); + tt(LocalpartAt, LOCALHOST, Email$1); + const EmailDomainHyphen = tt(EmailDomain, HYPHEN); + tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen); + ta(EmailDomainHyphen, groups.domain, EmailDomain); + ta(Email$1, groups.domain, EmailDomain); + tt(Email$1, DOT, EmailDomainDot); + tt(Email$1, HYPHEN, EmailDomainHyphen); + const EmailColon = tt(Email$1, COLON); + ta(EmailColon, groups.numeric, Email); + const DomainHyphen = tt(Domain, HYPHEN); + const DomainDot = tt(Domain, DOT); + tt(DomainHyphen, HYPHEN, DomainHyphen); + ta(DomainHyphen, groups.domain, Domain); + ta(DomainDot, localpartAccepting, Localpart); + ta(DomainDot, groups.domain, Domain); + const DomainDotTld = makeState(Url); + ta(DomainDot, groups.tld, DomainDotTld); + ta(DomainDot, groups.utld, DomainDotTld); + ta(DomainDotTld, groups.domain, Domain); + ta(DomainDotTld, localpartAccepting, Localpart); + tt(DomainDotTld, DOT, DomainDot); + tt(DomainDotTld, HYPHEN, DomainHyphen); + tt(DomainDotTld, AT, LocalpartAt); + const DomainDotTldColon = tt(DomainDotTld, COLON); + const DomainDotTldColonPort = makeState(Url); + ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort); + const Url$1 = makeState(Url); + const UrlNonaccept = makeState(); + ta(Url$1, qsAccepting, Url$1); + ta(Url$1, qsNonAccepting, UrlNonaccept); + ta(UrlNonaccept, qsAccepting, Url$1); + ta(UrlNonaccept, qsNonAccepting, UrlNonaccept); + tt(DomainDotTld, SLASH, Url$1); + tt(DomainDotTldColonPort, SLASH, Url$1); + const SchemeColon = tt(Scheme, COLON); + const SlashSchemeColon = tt(SlashScheme, COLON); + const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); + const UriPrefix = tt(SlashSchemeColonSlash, SLASH); + ta(Scheme, groups.domain, Domain); + tt(Scheme, DOT, DomainDot); + tt(Scheme, HYPHEN, DomainHyphen); + ta(SlashScheme, groups.domain, Domain); + tt(SlashScheme, DOT, DomainDot); + tt(SlashScheme, HYPHEN, DomainHyphen); + ta(SchemeColon, groups.domain, Url$1); + tt(SchemeColon, SLASH, Url$1); + tt(SchemeColon, QUERY, Url$1); + ta(UriPrefix, groups.domain, Url$1); + ta(UriPrefix, qsAccepting, Url$1); + tt(UriPrefix, SLASH, Url$1); + const bracketPairs = [ + [OPENBRACE, CLOSEBRACE], + // {} + [OPENBRACKET, CLOSEBRACKET], + // [] + [OPENPAREN, CLOSEPAREN], + // () + [OPENANGLEBRACKET, CLOSEANGLEBRACKET], + // <> + [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN], + // () + [LEFTCORNERBRACKET, RIGHTCORNERBRACKET], + // 「」 + [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET], + // 『』 + [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] + // <> + ]; + for (let i = 0; i < bracketPairs.length; i++) { + const [OPEN, CLOSE] = bracketPairs[i]; + const UrlOpen = tt(Url$1, OPEN); + tt(UrlNonaccept, OPEN, UrlOpen); + tt(UrlOpen, CLOSE, Url$1); + const UrlOpenQ = makeState(Url); + ta(UrlOpen, qsAccepting, UrlOpenQ); + const UrlOpenSyms = makeState(); + ta(UrlOpen, qsNonAccepting); + ta(UrlOpenQ, qsAccepting, UrlOpenQ); + ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms); + ta(UrlOpenSyms, qsAccepting, UrlOpenQ); + ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms); + tt(UrlOpenQ, CLOSE, Url$1); + tt(UrlOpenSyms, CLOSE, Url$1); + } + tt(Start, LOCALHOST, DomainDotTld); + tt(Start, NL, Nl); + return { + start: Start, + tokens: tk + }; +} +function run(start, input, tokens) { + let len = tokens.length; + let cursor = 0; + let multis = []; + let textTokens = []; + while (cursor < len) { + let state = start; + let secondState = null; + let nextState = null; + let multiLength = 0; + let latestAccepting = null; + let sinceAccepts = -1; + while (cursor < len && !(secondState = state.go(tokens[cursor].t))) { + textTokens.push(tokens[cursor++]); + } + while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) { + secondState = null; + state = nextState; + if (state.accepts()) { + sinceAccepts = 0; + latestAccepting = state; + } else if (sinceAccepts >= 0) { + sinceAccepts++; + } + cursor++; + multiLength++; + } + if (sinceAccepts < 0) { + cursor -= multiLength; + if (cursor < len) { + textTokens.push(tokens[cursor]); + cursor++; + } + } else { + if (textTokens.length > 0) { + multis.push(initMultiToken(Text$1, input, textTokens)); + textTokens = []; + } + cursor -= sinceAccepts; + multiLength -= sinceAccepts; + const Multi = latestAccepting.t; + const subtokens = tokens.slice(cursor - multiLength, cursor); + multis.push(initMultiToken(Multi, input, subtokens)); + } + } + if (textTokens.length > 0) { + multis.push(initMultiToken(Text$1, input, textTokens)); + } + return multis; +} +function initMultiToken(Multi, input, tokens) { + const startIdx = tokens[0].s; + const endIdx = tokens[tokens.length - 1].e; + const value = input.slice(startIdx, endIdx); + return new Multi(value, tokens); +} +const warn = typeof console !== "undefined" && console && console.warn || (() => { +}); +const warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time."; +const INIT = { + scanner: null, + parser: null, + tokenQueue: [], + pluginQueue: [], + customSchemes: [], + initialized: false +}; +function reset() { + State.groups = {}; + INIT.scanner = null; + INIT.parser = null; + INIT.tokenQueue = []; + INIT.pluginQueue = []; + INIT.customSchemes = []; + INIT.initialized = false; + return INIT; +} +function registerCustomProtocol(scheme2, optionalSlashSlash = false) { + if (INIT.initialized) { + warn(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`); + } + if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) { + throw new Error(`linkifyjs: incorrect scheme format. +1. Must only contain digits, lowercase ASCII letters or "-" +2. Cannot start or end with "-" +3. "-" cannot repeat`); + } + INIT.customSchemes.push([scheme2, optionalSlashSlash]); +} +function init() { + INIT.scanner = init$2(INIT.customSchemes); + for (let i = 0; i < INIT.tokenQueue.length; i++) { + INIT.tokenQueue[i][1]({ + scanner: INIT.scanner + }); + } + INIT.parser = init$1(INIT.scanner.tokens); + for (let i = 0; i < INIT.pluginQueue.length; i++) { + INIT.pluginQueue[i][1]({ + scanner: INIT.scanner, + parser: INIT.parser + }); + } + INIT.initialized = true; + return INIT; +} +function tokenize(str) { + if (!INIT.initialized) { + init(); + } + return run(INIT.parser.start, str, run$1(INIT.scanner.start, str)); +} +tokenize.scan = run$1; +function find(str, type = null, opts = null) { + if (type && typeof type === "object") { + if (opts) { + throw Error(`linkifyjs: Invalid link type ${type}; must be a string`); + } + opts = type; + type = null; + } + const options = new Options(opts); + const tokens = tokenize(str); + const filtered = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.isLink && (!type || token.t === type) && options.check(token)) { + filtered.push(token.toFormattedObject(options)); + } + } + return filtered; +} +var UNICODE_WHITESPACE_PATTERN = "[\0-   ᠎ -\u2029  ]"; +var UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN); +var UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`); +var UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, "g"); +function isValidLinkStructure(tokens) { + if (tokens.length === 1) { + return tokens[0].isLink; + } + if (tokens.length === 3 && tokens[1].isLink) { + return ["()", "[]"].includes(tokens[0].value + tokens[2].value); + } + return false; +} +function autolink(options) { + return new Plugin({ + key: new PluginKey("autolink"), + appendTransaction: (transactions, oldState, newState) => { + const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); + const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink")); + if (!docChanges || preventAutolink) { + return; + } + const { tr: tr2 } = newState; + const transform = combineTransactionSteps(oldState.doc, [...transactions]); + const changes = getChangedRanges(transform); + changes.forEach(({ newRange }) => { + const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock); + let textBlock; + let textBeforeWhitespace; + if (nodesInChangedRanges.length > 1) { + textBlock = nodesInChangedRanges[0]; + textBeforeWhitespace = newState.doc.textBetween( + textBlock.pos, + textBlock.pos + textBlock.node.nodeSize, + void 0, + " " + ); + } else if (nodesInChangedRanges.length) { + const endText = newState.doc.textBetween(newRange.from, newRange.to, " ", " "); + if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) { + return; + } + textBlock = nodesInChangedRanges[0]; + textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " "); + } + if (textBlock && textBeforeWhitespace) { + const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean); + if (wordsBeforeWhitespace.length <= 0) { + return false; + } + const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]; + const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace); + if (!lastWordBeforeSpace) { + return false; + } + const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t) => t.toObject(options.defaultProtocol)); + if (!isValidLinkStructure(linksBeforeSpace)) { + return false; + } + linksBeforeSpace.filter((link) => link.isLink).map((link) => ({ + ...link, + from: lastWordAndBlockOffset + link.start + 1, + to: lastWordAndBlockOffset + link.end + 1 + })).filter((link) => { + if (!newState.schema.marks.code) { + return true; + } + return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code); + }).filter((link) => options.validate(link.value)).filter((link) => options.shouldAutoLink(link.value)).forEach((link) => { + if (getMarksBetween(link.from, link.to, newState.doc).some((item) => item.mark.type === options.type)) { + return; + } + tr2.addMark( + link.from, + link.to, + options.type.create({ + href: link.href + }) + ); + }); + } + }); + if (!tr2.steps.length) { + return; + } + return tr2; + } + }); +} +function clickHandler(options) { + return new Plugin({ + key: new PluginKey("handleClickLink"), + props: { + handleClick: (view, pos, event) => { + var _a, _b; + if (event.button !== 0) { + return false; + } + if (!view.editable) { + return false; + } + let link = null; + if (event.target instanceof HTMLAnchorElement) { + link = event.target; + } else { + const target = event.target; + if (!target) { + return false; + } + const root = options.editor.view.dom; + link = target.closest("a"); + if (link && !root.contains(link)) { + link = null; + } + } + if (!link) { + return false; + } + let handled = false; + if (options.enableClickSelection) { + const commandResult = options.editor.commands.extendMarkRange(options.type.name); + handled = commandResult; + } + if (options.openOnClick) { + const attrs = getAttributes(view.state, options.type.name); + const href = (_a = link.href) != null ? _a : attrs.href; + const target = (_b = link.target) != null ? _b : attrs.target; + if (href) { + window.open(href, target); + handled = true; + } + } + return handled; + } + } + }); +} +function pasteHandler(options) { + return new Plugin({ + key: new PluginKey("handlePasteLink"), + props: { + handlePaste: (view, _event, slice2) => { + const { shouldAutoLink } = options; + const { state } = view; + const { selection } = state; + const { empty: empty2 } = selection; + if (empty2) { + return false; + } + let textContent = ""; + slice2.content.forEach((node) => { + textContent += node.textContent; + }); + const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find( + (item) => item.isLink && item.value === textContent + ); + if (!textContent || !link || shouldAutoLink !== void 0 && !shouldAutoLink(link.value)) { + return false; + } + return options.editor.commands.setMark(options.type, { + href: link.href + }); + } + } + }); +} +function isAllowedUri(uri, protocols) { + const allowedProtocols = ["http", "https", "ftp", "ftps", "mailto", "tel", "callto", "sms", "cid", "xmpp"]; + if (protocols) { + protocols.forEach((protocol) => { + const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme; + if (nextProtocol) { + allowedProtocols.push(nextProtocol); + } + }); + } + return !uri || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, "").match( + new RegExp( + // eslint-disable-next-line no-useless-escape + `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`, + "i" + ) + ); +} +var Link = Mark2.create({ + name: "link", + priority: 1e3, + keepOnSplit: false, + exitable: true, + onCreate() { + if (this.options.validate && !this.options.shouldAutoLink) { + this.options.shouldAutoLink = this.options.validate; + console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead."); + } + this.options.protocols.forEach((protocol) => { + if (typeof protocol === "string") { + registerCustomProtocol(protocol); + return; + } + registerCustomProtocol(protocol.scheme, protocol.optionalSlashes); + }); + }, + onDestroy() { + reset(); + }, + inclusive() { + return this.options.autolink; + }, + addOptions() { + return { + openOnClick: true, + enableClickSelection: false, + linkOnPaste: true, + autolink: true, + protocols: [], + defaultProtocol: "http", + HTMLAttributes: { + target: "_blank", + rel: "noopener noreferrer nofollow", + class: null + }, + isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols), + validate: (url) => !!url, + shouldAutoLink: (url) => { + const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(url); + const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url); + if (hasProtocol || hasMaybeProtocol && !url.includes("@")) { + return true; + } + const urlWithoutUserinfo = url.includes("@") ? url.split("@").pop() : url; + const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0]; + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) { + return false; + } + if (!/\./.test(hostname)) { + return false; + } + return true; + } + }; + }, + addAttributes() { + return { + href: { + default: null, + parseHTML(element) { + return element.getAttribute("href"); + } + }, + target: { + default: this.options.HTMLAttributes.target + }, + rel: { + default: this.options.HTMLAttributes.rel + }, + class: { + default: this.options.HTMLAttributes.class + }, + title: { + default: null + } + }; + }, + parseHTML() { + return [ + { + tag: "a[href]", + getAttrs: (dom) => { + const href = dom.getAttribute("href"); + if (!href || !this.options.isAllowedUri(href, { + defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return false; + } + return null; + } + } + ]; + }, + renderHTML({ HTMLAttributes }) { + if (!this.options.isAllowedUri(HTMLAttributes.href, { + defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return ["a", mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }), 0]; + } + return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "link", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("link", helpers.parseInline(token.tokens || []), { + href: token.href, + title: token.title || null + }); + }, + renderMarkdown: (node, h2) => { + var _a, _b, _c, _d; + const href = (_b = (_a = node.attrs) == null ? void 0 : _a.href) != null ? _b : ""; + const title = (_d = (_c = node.attrs) == null ? void 0 : _c.title) != null ? _d : ""; + const text = h2.renderChildren(node); + return title ? `[${text}](${href} "${title}")` : `[${text}](${href})`; + }, + addCommands() { + return { + setLink: (attributes) => ({ chain }) => { + const { href } = attributes; + if (!this.options.isAllowedUri(href, { + defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return false; + } + return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run(); + }, + toggleLink: (attributes) => ({ chain }) => { + const { href } = attributes || {}; + if (href && !this.options.isAllowedUri(href, { + defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return false; + } + return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); + }, + unsetLink: () => ({ chain }) => { + return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); + } + }; + }, + addPasteRules() { + return [ + markPasteRule({ + find: (text) => { + const foundLinks = []; + if (text) { + const { protocols, defaultProtocol } = this.options; + const links = find(text).filter( + (item) => item.isLink && this.options.isAllowedUri(item.value, { + defaultValidate: (href) => !!isAllowedUri(href, protocols), + protocols, + defaultProtocol + }) + ); + if (links.length) { + links.forEach((link) => { + if (!this.options.shouldAutoLink(link.value)) { + return; + } + foundLinks.push({ + text: link.value, + data: { + href: link.href + }, + index: link.start + }); + }); + } + } + return foundLinks; + }, + type: this.type, + getAttributes: (match) => { + var _a; + return { + href: (_a = match.data) == null ? void 0 : _a.href + }; + } + }) + ]; + }, + addProseMirrorPlugins() { + const plugins = []; + const { protocols, defaultProtocol } = this.options; + if (this.options.autolink) { + plugins.push( + autolink({ + type: this.type, + defaultProtocol: this.options.defaultProtocol, + validate: (url) => this.options.isAllowedUri(url, { + defaultValidate: (href) => !!isAllowedUri(href, protocols), + protocols, + defaultProtocol + }), + shouldAutoLink: this.options.shouldAutoLink + }) + ); + } + plugins.push( + clickHandler({ + type: this.type, + editor: this.editor, + openOnClick: this.options.openOnClick === "whenNotEditable" ? true : this.options.openOnClick, + enableClickSelection: this.options.enableClickSelection + }) + ); + if (this.options.linkOnPaste) { + plugins.push( + pasteHandler({ + editor: this.editor, + defaultProtocol: this.options.defaultProtocol, + type: this.type, + shouldAutoLink: this.options.shouldAutoLink + }) + ); + } + return plugins; + } +}); +var index_default$5 = Link; +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var ListItemName = "listItem"; +var TextStyleName = "textStyle"; +var bulletListInputRegex = /^\s*([-+*])\s$/; +var BulletList = Node3.create({ + name: "bulletList", + addOptions() { + return { + itemTypeName: "listItem", + HTMLAttributes: {}, + keepMarks: false, + keepAttributes: false + }; + }, + group: "block list", + content() { + return `${this.options.itemTypeName}+`; + }, + parseHTML() { + return [{ tag: "ul" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "list", + parseMarkdown: (token, helpers) => { + if (token.type !== "list" || token.ordered) { + return []; + } + return { + type: "bulletList", + content: token.items ? helpers.parseChildren(token.items) : [] + }; + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n"); + }, + markdownOptions: { + indentsContent: true + }, + addCommands() { + return { + toggleBulletList: () => ({ commands, chain }) => { + if (this.options.keepAttributes) { + return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run(); + } + return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-8": () => this.editor.commands.toggleBulletList() + }; + }, + addInputRules() { + let inputRule = wrappingInputRule({ + find: bulletListInputRegex, + type: this.type + }); + if (this.options.keepMarks || this.options.keepAttributes) { + inputRule = wrappingInputRule({ + find: bulletListInputRegex, + type: this.type, + keepMarks: this.options.keepMarks, + keepAttributes: this.options.keepAttributes, + getAttributes: () => { + return this.editor.getAttributes(TextStyleName); + }, + editor: this.editor + }); + } + return [inputRule]; + } +}); +var ListItem = Node3.create({ + name: "listItem", + addOptions() { + return { + HTMLAttributes: {}, + bulletListTypeName: "bulletList", + orderedListTypeName: "orderedList" + }; + }, + content: "paragraph block*", + defining: true, + parseHTML() { + return [ + { + tag: "li" + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["li", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "list_item", + parseMarkdown: (token, helpers) => { + var _a; + if (token.type !== "list_item") { + return []; + } + const parseBlockChildren = (_a = helpers.parseBlockChildren) != null ? _a : helpers.parseChildren; + let content = []; + if (token.tokens && token.tokens.length > 0) { + const hasParagraphTokens = token.tokens.some((t) => t.type === "paragraph"); + if (hasParagraphTokens) { + content = parseBlockChildren(token.tokens); + } else { + const firstToken = token.tokens[0]; + if (firstToken && firstToken.type === "text" && firstToken.tokens && firstToken.tokens.length > 0) { + const inlineContent = helpers.parseInline(firstToken.tokens); + content = [ + { + type: "paragraph", + content: inlineContent + } + ]; + if (token.tokens.length > 1) { + const remainingTokens = token.tokens.slice(1); + const additionalContent = parseBlockChildren(remainingTokens); + content.push(...additionalContent); + } + } else { + content = parseBlockChildren(token.tokens); + } + } + } + if (content.length === 0) { + content = [ + { + type: "paragraph", + content: [] + } + ]; + } + return { + type: "listItem", + content + }; + }, + renderMarkdown: (node, h2, ctx) => { + return renderNestedMarkdownContent( + node, + h2, + (context) => { + var _a, _b; + if (context.parentType === "bulletList") { + return "- "; + } + if (context.parentType === "orderedList") { + const start = ((_b = (_a = context.meta) == null ? void 0 : _a.parentAttrs) == null ? void 0 : _b.start) || 1; + return `${start + context.index}. `; + } + return "- "; + }, + ctx + ); + }, + addKeyboardShortcuts() { + return { + Enter: () => this.editor.commands.splitListItem(this.name), + Tab: () => this.editor.commands.sinkListItem(this.name), + "Shift-Tab": () => this.editor.commands.liftListItem(this.name) + }; + } +}); +var listHelpers_exports = {}; +__export(listHelpers_exports, { + findListItemPos: () => findListItemPos, + getNextListDepth: () => getNextListDepth, + handleBackspace: () => handleBackspace, + handleDelete: () => handleDelete, + hasListBefore: () => hasListBefore, + hasListItemAfter: () => hasListItemAfter, + hasListItemBefore: () => hasListItemBefore, + listItemHasSubList: () => listItemHasSubList, + nextListIsDeeper: () => nextListIsDeeper, + nextListIsHigher: () => nextListIsHigher +}); +var findListItemPos = (typeOrName, state) => { + const { $from } = state.selection; + const nodeType = getNodeType(typeOrName, state.schema); + let currentNode = null; + let currentDepth = $from.depth; + let currentPos = $from.pos; + let targetDepth = null; + while (currentDepth > 0 && targetDepth === null) { + currentNode = $from.node(currentDepth); + if (currentNode.type === nodeType) { + targetDepth = currentDepth; + } else { + currentDepth -= 1; + currentPos -= 1; + } + } + if (targetDepth === null) { + return null; + } + return { $pos: state.doc.resolve(currentPos), depth: targetDepth }; +}; +var getNextListDepth = (typeOrName, state) => { + const listItemPos = findListItemPos(typeOrName, state); + if (!listItemPos) { + return false; + } + const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4); + return depth; +}; +var hasListBefore = (editorState, name, parentListTypes) => { + const { $anchor } = editorState.selection; + const previousNodePos = Math.max(0, $anchor.pos - 2); + const previousNode = editorState.doc.resolve(previousNodePos).node(); + if (!previousNode || !parentListTypes.includes(previousNode.type.name)) { + return false; + } + return true; +}; +var hasListItemBefore = (typeOrName, state) => { + var _a; + const { $anchor } = state.selection; + const $targetPos = state.doc.resolve($anchor.pos - 2); + if ($targetPos.index() === 0) { + return false; + } + if (((_a = $targetPos.nodeBefore) == null ? void 0 : _a.type.name) !== typeOrName) { + return false; + } + return true; +}; +var listItemHasSubList = (typeOrName, state, node) => { + if (!node) { + return false; + } + const nodeType = getNodeType(typeOrName, state.schema); + let hasSubList = false; + node.descendants((child) => { + if (child.type === nodeType) { + hasSubList = true; + } + }); + return hasSubList; +}; +var handleBackspace = (editor, name, parentListTypes) => { + if (editor.commands.undoInputRule()) { + return true; + } + if (editor.state.selection.from !== editor.state.selection.to) { + return false; + } + if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) { + const { $anchor } = editor.state.selection; + const $listPos = editor.state.doc.resolve($anchor.before() - 1); + const listDescendants = []; + $listPos.node().descendants((node, pos) => { + if (node.type.name === name) { + listDescendants.push({ node, pos }); + } + }); + const lastItem = listDescendants.at(-1); + if (!lastItem) { + return false; + } + const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1); + return editor.chain().cut({ from: $anchor.start() - 1, to: $anchor.end() + 1 }, $lastItemPos.end()).joinForward().run(); + } + if (!isNodeActive(editor.state, name)) { + return false; + } + if (!isAtStartOfNode(editor.state)) { + return false; + } + const listItemPos = findListItemPos(name, editor.state); + if (!listItemPos) { + return false; + } + const $prev = editor.state.doc.resolve(listItemPos.$pos.pos - 2); + const prevNode = $prev.node(listItemPos.depth); + const previousListItemHasSubList = listItemHasSubList(name, editor.state, prevNode); + if (hasListItemBefore(name, editor.state) && !previousListItemHasSubList) { + return editor.commands.joinItemBackward(); + } + return editor.chain().liftListItem(name).run(); +}; +var nextListIsDeeper = (typeOrName, state) => { + const listDepth = getNextListDepth(typeOrName, state); + const listItemPos = findListItemPos(typeOrName, state); + if (!listItemPos || !listDepth) { + return false; + } + if (listDepth > listItemPos.depth) { + return true; + } + return false; +}; +var nextListIsHigher = (typeOrName, state) => { + const listDepth = getNextListDepth(typeOrName, state); + const listItemPos = findListItemPos(typeOrName, state); + if (!listItemPos || !listDepth) { + return false; + } + if (listDepth < listItemPos.depth) { + return true; + } + return false; +}; +var handleDelete = (editor, name) => { + if (!isNodeActive(editor.state, name)) { + return false; + } + if (!isAtEndOfNode(editor.state, name)) { + return false; + } + const { selection } = editor.state; + const { $from, $to } = selection; + if (!selection.empty && $from.sameParent($to)) { + return false; + } + if (nextListIsDeeper(name, editor.state)) { + return editor.chain().focus(editor.state.selection.from + 4).lift(name).joinBackward().run(); + } + if (nextListIsHigher(name, editor.state)) { + return editor.chain().joinForward().joinBackward().run(); + } + return editor.commands.joinItemForward(); +}; +var hasListItemAfter = (typeOrName, state) => { + var _a; + const { $anchor } = state.selection; + const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2); + if ($targetPos.index() === $targetPos.parent.childCount - 1) { + return false; + } + if (((_a = $targetPos.nodeAfter) == null ? void 0 : _a.type.name) !== typeOrName) { + return false; + } + return true; +}; +var ListKeymap = Extension.create({ + name: "listKeymap", + addOptions() { + return { + listTypes: [ + { + itemName: "listItem", + wrapperNames: ["bulletList", "orderedList"] + }, + { + itemName: "taskItem", + wrapperNames: ["taskList"] + } + ] + }; + }, + addKeyboardShortcuts() { + return { + Delete: ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleDelete(editor, itemName)) { + handled = true; + } + }); + return handled; + }, + "Mod-Delete": ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleDelete(editor, itemName)) { + handled = true; + } + }); + return handled; + }, + Backspace: ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName, wrapperNames }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleBackspace(editor, itemName, wrapperNames)) { + handled = true; + } + }); + return handled; + }, + "Mod-Backspace": ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName, wrapperNames }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleBackspace(editor, itemName, wrapperNames)) { + handled = true; + } + }); + return handled; + } + }; + } +}); +var ORDERED_LIST_ITEM_REGEX = /^(\s*)(\d+)\.\s+(.*)$/; +var INDENTED_LINE_REGEX = /^\s/; +function collectOrderedListItems(lines) { + const listItems = []; + let currentLineIndex = 0; + let consumed = 0; + while (currentLineIndex < lines.length) { + const line = lines[currentLineIndex]; + const match = line.match(ORDERED_LIST_ITEM_REGEX); + if (!match) { + break; + } + const [, indent, number, content] = match; + const indentLevel = indent.length; + let itemContent = content; + let nextLineIndex = currentLineIndex + 1; + const itemLines = [line]; + while (nextLineIndex < lines.length) { + const nextLine = lines[nextLineIndex]; + const nextMatch = nextLine.match(ORDERED_LIST_ITEM_REGEX); + if (nextMatch) { + break; + } + if (nextLine.trim() === "") { + itemLines.push(nextLine); + itemContent += "\n"; + nextLineIndex += 1; + } else if (nextLine.match(INDENTED_LINE_REGEX)) { + itemLines.push(nextLine); + itemContent += ` +${nextLine.slice(indentLevel + 2)}`; + nextLineIndex += 1; + } else { + break; + } + } + listItems.push({ + indent: indentLevel, + number: parseInt(number, 10), + content: itemContent.trim(), + raw: itemLines.join("\n") + }); + consumed = nextLineIndex; + currentLineIndex = nextLineIndex; + } + return [listItems, consumed]; +} +function buildNestedStructure(items, baseIndent, lexer) { + var _a; + const result = []; + let currentIndex = 0; + while (currentIndex < items.length) { + const item = items[currentIndex]; + if (item.indent === baseIndent) { + const contentLines = item.content.split("\n"); + const mainText = ((_a = contentLines[0]) == null ? void 0 : _a.trim()) || ""; + const tokens = []; + if (mainText) { + tokens.push({ + type: "paragraph", + raw: mainText, + tokens: lexer.inlineTokens(mainText) + }); + } + const additionalContent = contentLines.slice(1).join("\n").trim(); + if (additionalContent) { + const blockTokens = lexer.blockTokens(additionalContent); + tokens.push(...blockTokens); + } + let lookAheadIndex = currentIndex + 1; + const nestedItems = []; + while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) { + nestedItems.push(items[lookAheadIndex]); + lookAheadIndex += 1; + } + if (nestedItems.length > 0) { + const nextIndent = Math.min(...nestedItems.map((nestedItem) => nestedItem.indent)); + const nestedListItems = buildNestedStructure(nestedItems, nextIndent, lexer); + tokens.push({ + type: "list", + ordered: true, + start: nestedItems[0].number, + items: nestedListItems, + raw: nestedItems.map((nestedItem) => nestedItem.raw).join("\n") + }); + } + result.push({ + type: "list_item", + raw: item.raw, + tokens + }); + currentIndex = lookAheadIndex; + } else { + currentIndex += 1; + } + } + return result; +} +function parseListItems(items, helpers) { + return items.map((item) => { + if (item.type !== "list_item") { + return helpers.parseChildren([item])[0]; + } + const content = []; + if (item.tokens && item.tokens.length > 0) { + item.tokens.forEach((itemToken) => { + if (itemToken.type === "paragraph" || itemToken.type === "list" || itemToken.type === "blockquote" || itemToken.type === "code") { + content.push(...helpers.parseChildren([itemToken])); + } else if (itemToken.type === "text" && itemToken.tokens) { + const inlineContent = helpers.parseChildren([itemToken]); + content.push({ + type: "paragraph", + content: inlineContent + }); + } else { + const parsed = helpers.parseChildren([itemToken]); + if (parsed.length > 0) { + content.push(...parsed); + } + } + }); + } + return { + type: "listItem", + content + }; + }); +} +var ListItemName2 = "listItem"; +var TextStyleName2 = "textStyle"; +var orderedListInputRegex = /^(\d+)\.\s$/; +var OrderedList = Node3.create({ + name: "orderedList", + addOptions() { + return { + itemTypeName: "listItem", + HTMLAttributes: {}, + keepMarks: false, + keepAttributes: false + }; + }, + group: "block list", + content() { + return `${this.options.itemTypeName}+`; + }, + addAttributes() { + return { + start: { + default: 1, + parseHTML: (element) => { + return element.hasAttribute("start") ? parseInt(element.getAttribute("start") || "", 10) : 1; + } + }, + type: { + default: null, + parseHTML: (element) => element.getAttribute("type") + } + }; + }, + parseHTML() { + return [ + { + tag: "ol" + } + ]; + }, + renderHTML({ HTMLAttributes }) { + const { start, ...attributesWithoutStart } = HTMLAttributes; + return start === 1 ? ["ol", mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0] : ["ol", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "list", + parseMarkdown: (token, helpers) => { + if (token.type !== "list" || !token.ordered) { + return []; + } + const startValue = token.start || 1; + const content = token.items ? parseListItems(token.items, helpers) : []; + if (startValue !== 1) { + return { + type: "orderedList", + attrs: { start: startValue }, + content + }; + } + return { + type: "orderedList", + content + }; + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n"); + }, + markdownTokenizer: { + name: "orderedList", + level: "block", + start: (src) => { + const match = src.match(/^(\s*)(\d+)\.\s+/); + const index = match == null ? void 0 : match.index; + return index !== void 0 ? index : -1; + }, + tokenize: (src, _tokens, lexer) => { + var _a; + const lines = src.split("\n"); + const [listItems, consumed] = collectOrderedListItems(lines); + if (listItems.length === 0) { + return void 0; + } + const items = buildNestedStructure(listItems, 0, lexer); + if (items.length === 0) { + return void 0; + } + const startValue = ((_a = listItems[0]) == null ? void 0 : _a.number) || 1; + return { + type: "list", + ordered: true, + start: startValue, + items, + raw: lines.slice(0, consumed).join("\n") + }; + } + }, + markdownOptions: { + indentsContent: true + }, + addCommands() { + return { + toggleOrderedList: () => ({ commands, chain }) => { + if (this.options.keepAttributes) { + return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName2, this.editor.getAttributes(TextStyleName2)).run(); + } + return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-7": () => this.editor.commands.toggleOrderedList() + }; + }, + addInputRules() { + let inputRule = wrappingInputRule({ + find: orderedListInputRegex, + type: this.type, + getAttributes: (match) => ({ start: +match[1] }), + joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1] + }); + if (this.options.keepMarks || this.options.keepAttributes) { + inputRule = wrappingInputRule({ + find: orderedListInputRegex, + type: this.type, + keepMarks: this.options.keepMarks, + keepAttributes: this.options.keepAttributes, + getAttributes: (match) => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName2) }), + joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1], + editor: this.editor + }); + } + return [inputRule]; + } +}); +var inputRegex$2 = /^\s*(\[([( |x])?\])\s$/; +var TaskItem = Node3.create({ + name: "taskItem", + addOptions() { + return { + nested: false, + HTMLAttributes: {}, + taskListTypeName: "taskList", + a11y: void 0 + }; + }, + content() { + return this.options.nested ? "paragraph block*" : "paragraph+"; + }, + defining: true, + addAttributes() { + return { + checked: { + default: false, + keepOnSplit: false, + parseHTML: (element) => { + const dataChecked = element.getAttribute("data-checked"); + return dataChecked === "" || dataChecked === "true"; + }, + renderHTML: (attributes) => ({ + "data-checked": attributes.checked + }) + } + }; + }, + parseHTML() { + return [ + { + tag: `li[data-type="${this.name}"]`, + priority: 51 + } + ]; + }, + renderHTML({ node, HTMLAttributes }) { + return [ + "li", + mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { + "data-type": this.name + }), + [ + "label", + [ + "input", + { + type: "checkbox", + checked: node.attrs.checked ? "checked" : null + } + ], + ["span"] + ], + ["div", 0] + ]; + }, + parseMarkdown: (token, h2) => { + const content = []; + if (token.tokens && token.tokens.length > 0) { + content.push(h2.createNode("paragraph", {}, h2.parseInline(token.tokens))); + } else if (token.text) { + content.push(h2.createNode("paragraph", {}, [h2.createNode("text", { text: token.text })])); + } else { + content.push(h2.createNode("paragraph", {}, [])); + } + if (token.nestedTokens && token.nestedTokens.length > 0) { + const nestedContent = h2.parseChildren(token.nestedTokens); + content.push(...nestedContent); + } + return h2.createNode("taskItem", { checked: token.checked || false }, content); + }, + renderMarkdown: (node, h2) => { + var _a; + const checkedChar = ((_a = node.attrs) == null ? void 0 : _a.checked) ? "x" : " "; + const prefix = `- [${checkedChar}] `; + return renderNestedMarkdownContent(node, h2, prefix); + }, + addKeyboardShortcuts() { + const shortcuts = { + Enter: () => this.editor.commands.splitListItem(this.name), + "Shift-Tab": () => this.editor.commands.liftListItem(this.name) + }; + if (!this.options.nested) { + return shortcuts; + } + return { + ...shortcuts, + Tab: () => this.editor.commands.sinkListItem(this.name) + }; + }, + addNodeView() { + return ({ node, HTMLAttributes, getPos, editor }) => { + const listItem = document.createElement("li"); + const checkboxWrapper = document.createElement("label"); + const checkboxStyler = document.createElement("span"); + const checkbox = document.createElement("input"); + const content = document.createElement("div"); + const updateA11Y = (currentNode) => { + var _a, _b; + checkbox.ariaLabel = ((_b = (_a = this.options.a11y) == null ? void 0 : _a.checkboxLabel) == null ? void 0 : _b.call(_a, currentNode, checkbox.checked)) || `Task item checkbox for ${currentNode.textContent || "empty task item"}`; + }; + updateA11Y(node); + checkboxWrapper.contentEditable = "false"; + checkbox.type = "checkbox"; + checkbox.addEventListener("mousedown", (event) => event.preventDefault()); + checkbox.addEventListener("change", (event) => { + if (!editor.isEditable && !this.options.onReadOnlyChecked) { + checkbox.checked = !checkbox.checked; + return; + } + const { checked } = event.target; + if (editor.isEditable && typeof getPos === "function") { + editor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr: tr2 }) => { + const position = getPos(); + if (typeof position !== "number") { + return false; + } + const currentNode = tr2.doc.nodeAt(position); + tr2.setNodeMarkup(position, void 0, { + ...currentNode == null ? void 0 : currentNode.attrs, + checked + }); + return true; + }).run(); + } + if (!editor.isEditable && this.options.onReadOnlyChecked) { + if (!this.options.onReadOnlyChecked(node, checked)) { + checkbox.checked = !checkbox.checked; + } + } + }); + Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => { + listItem.setAttribute(key, value); + }); + listItem.dataset.checked = node.attrs.checked; + checkbox.checked = node.attrs.checked; + checkboxWrapper.append(checkbox, checkboxStyler); + listItem.append(checkboxWrapper, content); + Object.entries(HTMLAttributes).forEach(([key, value]) => { + listItem.setAttribute(key, value); + }); + let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes)); + return { + dom: listItem, + contentDOM: content, + update: (updatedNode) => { + if (updatedNode.type !== this.type) { + return false; + } + listItem.dataset.checked = updatedNode.attrs.checked; + checkbox.checked = updatedNode.attrs.checked; + updateA11Y(updatedNode); + const extensionAttributes = editor.extensionManager.attributes; + const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes); + const newKeys = new Set(Object.keys(newHTMLAttributes)); + const staticAttrs = this.options.HTMLAttributes; + prevRenderedAttributeKeys.forEach((key) => { + if (!newKeys.has(key)) { + if (key in staticAttrs) { + listItem.setAttribute(key, staticAttrs[key]); + } else { + listItem.removeAttribute(key); + } + } + }); + Object.entries(newHTMLAttributes).forEach(([key, value]) => { + if (value === null || value === void 0) { + if (key in staticAttrs) { + listItem.setAttribute(key, staticAttrs[key]); + } else { + listItem.removeAttribute(key); + } + } else { + listItem.setAttribute(key, value); + } + }); + prevRenderedAttributeKeys = newKeys; + return true; + } + }; + }; + }, + addInputRules() { + return [ + wrappingInputRule({ + find: inputRegex$2, + type: this.type, + getAttributes: (match) => ({ + checked: match[match.length - 1] === "x" + }) + }) + ]; + } +}); +var TaskList = Node3.create({ + name: "taskList", + addOptions() { + return { + itemTypeName: "taskItem", + HTMLAttributes: {} + }; + }, + group: "block list", + content() { + return `${this.options.itemTypeName}+`; + }, + parseHTML() { + return [ + { + tag: `ul[data-type="${this.name}"]`, + priority: 51 + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { "data-type": this.name }), 0]; + }, + parseMarkdown: (token, h2) => { + return h2.createNode("taskList", {}, h2.parseChildren(token.items || [])); + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n"); + }, + markdownTokenizer: { + name: "taskList", + level: "block", + start(src) { + var _a; + const index = (_a = src.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)) == null ? void 0 : _a.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, tokens, lexer) { + const parseTaskListContent = (content) => { + const nestedResult = parseIndentedBlocks( + content, + { + itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, + extractItemData: (match) => ({ + indentLevel: match[1].length, + mainContent: match[4], + checked: match[3].toLowerCase() === "x" + }), + createToken: (data, nestedTokens) => ({ + type: "taskItem", + raw: "", + mainContent: data.mainContent, + indentLevel: data.indentLevel, + checked: data.checked, + text: data.mainContent, + tokens: lexer.inlineTokens(data.mainContent), + nestedTokens + }), + // Allow recursive nesting + customNestedParser: parseTaskListContent + }, + lexer + ); + if (nestedResult) { + return [ + { + type: "taskList", + raw: nestedResult.raw, + items: nestedResult.items + } + ]; + } + return lexer.blockTokens(content); + }; + const result = parseIndentedBlocks( + src, + { + itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, + extractItemData: (match) => ({ + indentLevel: match[1].length, + mainContent: match[4], + checked: match[3].toLowerCase() === "x" + }), + createToken: (data, nestedTokens) => ({ + type: "taskItem", + raw: "", + mainContent: data.mainContent, + indentLevel: data.indentLevel, + checked: data.checked, + text: data.mainContent, + tokens: lexer.inlineTokens(data.mainContent), + nestedTokens + }), + // Use the recursive parser for nested content + customNestedParser: parseTaskListContent + }, + lexer + ); + if (!result) { + return void 0; + } + return { + type: "taskList", + raw: result.raw, + items: result.items + }; + } + }, + markdownOptions: { + indentsContent: true + }, + addCommands() { + return { + toggleTaskList: () => ({ commands }) => { + return commands.toggleList(this.name, this.options.itemTypeName); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-9": () => this.editor.commands.toggleTaskList() + }; + } +}); +Extension.create({ + name: "listKit", + addExtensions() { + const extensions = []; + if (this.options.bulletList !== false) { + extensions.push(BulletList.configure(this.options.bulletList)); + } + if (this.options.listItem !== false) { + extensions.push(ListItem.configure(this.options.listItem)); + } + if (this.options.listKeymap !== false) { + extensions.push(ListKeymap.configure(this.options.listKeymap)); + } + if (this.options.orderedList !== false) { + extensions.push(OrderedList.configure(this.options.orderedList)); + } + if (this.options.taskItem !== false) { + extensions.push(TaskItem.configure(this.options.taskItem)); + } + if (this.options.taskList !== false) { + extensions.push(TaskList.configure(this.options.taskList)); + } + return extensions; + } +}); +var EMPTY_PARAGRAPH_MARKDOWN = " "; +var NBSP_CHAR = " "; +var Paragraph = Node3.create({ + name: "paragraph", + priority: 1e3, + addOptions() { + return { + HTMLAttributes: {} + }; + }, + group: "block", + content: "inline*", + parseHTML() { + return [{ tag: "p" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["p", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + parseMarkdown: (token, helpers) => { + const tokens = token.tokens || []; + if (tokens.length === 1 && tokens[0].type === "image") { + return helpers.parseChildren([tokens[0]]); + } + const content = helpers.parseInline(tokens); + const hasExplicitEmptyParagraphMarker = tokens.length === 1 && tokens[0].type === "text" && (tokens[0].raw === EMPTY_PARAGRAPH_MARKDOWN || tokens[0].text === EMPTY_PARAGRAPH_MARKDOWN || tokens[0].raw === NBSP_CHAR || tokens[0].text === NBSP_CHAR); + if (hasExplicitEmptyParagraphMarker && content.length === 1 && content[0].type === "text" && (content[0].text === EMPTY_PARAGRAPH_MARKDOWN || content[0].text === NBSP_CHAR)) { + return helpers.createNode("paragraph", void 0, []); + } + return helpers.createNode("paragraph", void 0, content); + }, + renderMarkdown: (node, h2, ctx) => { + var _a, _b; + if (!node) { + return ""; + } + const content = Array.isArray(node.content) ? node.content : []; + if (content.length === 0) { + const previousContent = Array.isArray((_a = ctx == null ? void 0 : ctx.previousNode) == null ? void 0 : _a.content) ? ctx.previousNode.content : []; + const previousNodeIsEmptyParagraph = ((_b = ctx == null ? void 0 : ctx.previousNode) == null ? void 0 : _b.type) === "paragraph" && previousContent.length === 0; + return previousNodeIsEmptyParagraph ? EMPTY_PARAGRAPH_MARKDOWN : ""; + } + return h2.renderChildren(content); + }, + addCommands() { + return { + setParagraph: () => ({ commands }) => { + return commands.setNode(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Alt-0": () => this.editor.commands.setParagraph() + }; + } +}); +var inputRegex$1 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/; +var pasteRegex = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g; +var Strike = Mark2.create({ + name: "strike", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "s" + }, + { + tag: "del" + }, + { + tag: "strike" + }, + { + style: "text-decoration", + consuming: false, + getAttrs: (style2) => style2.includes("line-through") ? {} : false + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "del", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("strike", helpers.parseInline(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + return `~~${h2.renderChildren(node)}~~`; + }, + addCommands() { + return { + setStrike: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleStrike: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetStrike: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-s": () => this.editor.commands.toggleStrike() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: inputRegex$1, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: pasteRegex, + type: this.type + }) + ]; + } +}); +var Text = Node3.create({ + name: "text", + group: "inline", + parseMarkdown: (token) => { + return { + type: "text", + text: token.text || "" + }; + }, + renderMarkdown: (node) => node.text || "" +}); +var Underline = Mark2.create({ + name: "underline", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "u" + }, + { + style: "text-decoration", + consuming: false, + getAttrs: (style2) => style2.includes("underline") ? {} : false + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["u", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + parseMarkdown(token, helpers) { + return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || [])); + }, + renderMarkdown(node, helpers) { + return `++${helpers.renderChildren(node)}++`; + }, + markdownTokenizer: { + name: "underline", + level: "inline", + start(src) { + return src.indexOf("++"); + }, + tokenize(src, _tokens, lexer) { + const rule = /^(\+\+)([\s\S]+?)(\+\+)/; + const match = rule.exec(src); + if (!match) { + return void 0; + } + const innerContent = match[2].trim(); + return { + type: "underline", + raw: match[0], + text: innerContent, + tokens: lexer.inlineTokens(innerContent) + }; + } + }, + addCommands() { + return { + setUnderline: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleUnderline: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetUnderline: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-u": () => this.editor.commands.toggleUnderline(), + "Mod-U": () => this.editor.commands.toggleUnderline() + }; + } +}); +var index_default$4 = Underline; +function dropCursor(options = {}) { + return new Plugin({ + view(editorView) { + return new DropCursorView(editorView, options); + } + }); +} +class DropCursorView { + constructor(editorView, options) { + var _a; + this.editorView = editorView; + this.cursorPos = null; + this.element = null; + this.timeout = -1; + this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1; + this.color = options.color === false ? void 0 : options.color || "black"; + this.class = options.class; + this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => { + let handler = (e) => { + this[name](e); + }; + editorView.dom.addEventListener(name, handler); + return { name, handler }; + }); + } + destroy() { + this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler)); + } + update(editorView, prevState) { + if (this.cursorPos != null && prevState.doc != editorView.state.doc) { + if (this.cursorPos > editorView.state.doc.content.size) + this.setCursor(null); + else + this.updateOverlay(); + } + } + setCursor(pos) { + if (pos == this.cursorPos) + return; + this.cursorPos = pos; + if (pos == null) { + this.element.parentNode.removeChild(this.element); + this.element = null; + } else { + this.updateOverlay(); + } + } + updateOverlay() { + let $pos = this.editorView.state.doc.resolve(this.cursorPos); + let isBlock = !$pos.parent.inlineContent, rect; + let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect(); + let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight; + if (isBlock) { + let before = $pos.nodeBefore, after = $pos.nodeAfter; + if (before || after) { + let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0)); + if (node) { + let nodeRect = node.getBoundingClientRect(); + let top = before ? nodeRect.bottom : nodeRect.top; + if (before && after) + top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; + let halfWidth = this.width / 2 * scaleY; + rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth }; + } + } + } + if (!rect) { + let coords = this.editorView.coordsAtPos(this.cursorPos); + let halfWidth = this.width / 2 * scaleX; + rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom }; + } + let parent = this.editorView.dom.offsetParent; + if (!this.element) { + this.element = parent.appendChild(document.createElement("div")); + if (this.class) + this.element.className = this.class; + this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;"; + if (this.color) { + this.element.style.backgroundColor = this.color; + } + } + this.element.classList.toggle("prosemirror-dropcursor-block", isBlock); + this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock); + let parentLeft, parentTop; + if (!parent || parent == document.body && getComputedStyle(parent).position == "static") { + parentLeft = -pageXOffset; + parentTop = -pageYOffset; + } else { + let rect2 = parent.getBoundingClientRect(); + let parentScaleX = rect2.width / parent.offsetWidth, parentScaleY = rect2.height / parent.offsetHeight; + parentLeft = rect2.left - parent.scrollLeft * parentScaleX; + parentTop = rect2.top - parent.scrollTop * parentScaleY; + } + this.element.style.left = (rect.left - parentLeft) / scaleX + "px"; + this.element.style.top = (rect.top - parentTop) / scaleY + "px"; + this.element.style.width = (rect.right - rect.left) / scaleX + "px"; + this.element.style.height = (rect.bottom - rect.top) / scaleY + "px"; + } + scheduleRemoval(timeout) { + clearTimeout(this.timeout); + this.timeout = setTimeout(() => this.setCursor(null), timeout); + } + dragover(event) { + if (!this.editorView.editable) + return; + let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY }); + let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside); + let disableDropCursor = node && node.type.spec.disableDropCursor; + let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor; + if (pos && !disabled) { + let target = pos.pos; + if (this.editorView.dragging && this.editorView.dragging.slice) { + let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice); + if (point != null) + target = point; + } + this.setCursor(target); + this.scheduleRemoval(5e3); + } + } + dragend() { + this.scheduleRemoval(20); + } + drop() { + this.scheduleRemoval(20); + } + dragleave(event) { + if (!this.editorView.dom.contains(event.relatedTarget)) + this.setCursor(null); + } +} +class GapCursor extends Selection { + /** + Create a gap cursor. + */ + constructor($pos) { + super($pos, $pos); + } + map(doc2, mapping) { + let $pos = doc2.resolve(mapping.map(this.head)); + return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos); + } + content() { + return Slice.empty; + } + eq(other) { + return other instanceof GapCursor && other.head == this.head; + } + toJSON() { + return { type: "gapcursor", pos: this.head }; + } + /** + @internal + */ + static fromJSON(doc2, json) { + if (typeof json.pos != "number") + throw new RangeError("Invalid input for GapCursor.fromJSON"); + return new GapCursor(doc2.resolve(json.pos)); + } + /** + @internal + */ + getBookmark() { + return new GapBookmark(this.anchor); + } + /** + @internal + */ + static valid($pos) { + let parent = $pos.parent; + if (parent.inlineContent || !closedBefore($pos) || !closedAfter($pos)) + return false; + let override = parent.type.spec.allowGapCursor; + if (override != null) + return override; + let deflt = parent.contentMatchAt($pos.index()).defaultType; + return deflt && deflt.isTextblock; + } + /** + @internal + */ + static findGapCursorFrom($pos, dir, mustMove = false) { + search: for (; ; ) { + if (!mustMove && GapCursor.valid($pos)) + return $pos; + let pos = $pos.pos, next = null; + for (let d = $pos.depth; ; d--) { + let parent = $pos.node(d); + if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) { + next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1); + break; + } else if (d == 0) { + return null; + } + pos += dir; + let $cur = $pos.doc.resolve(pos); + if (GapCursor.valid($cur)) + return $cur; + } + for (; ; ) { + let inside = dir > 0 ? next.firstChild : next.lastChild; + if (!inside) { + if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) { + $pos = $pos.doc.resolve(pos + next.nodeSize * dir); + mustMove = false; + continue search; + } + break; + } + next = inside; + pos += dir; + let $cur = $pos.doc.resolve(pos); + if (GapCursor.valid($cur)) + return $cur; + } + return null; + } + } +} +GapCursor.prototype.visible = false; +GapCursor.findFrom = GapCursor.findGapCursorFrom; +Selection.jsonID("gapcursor", GapCursor); +class GapBookmark { + constructor(pos) { + this.pos = pos; + } + map(mapping) { + return new GapBookmark(mapping.map(this.pos)); + } + resolve(doc2) { + let $pos = doc2.resolve(this.pos); + return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos); + } +} +function needsGap(type) { + return type.isAtom || type.spec.isolating || type.spec.createGapCursor; +} +function closedBefore($pos) { + for (let d = $pos.depth; d >= 0; d--) { + let index = $pos.index(d), parent = $pos.node(d); + if (index == 0) { + if (parent.type.spec.isolating) + return true; + continue; + } + for (let before = parent.child(index - 1); ; before = before.lastChild) { + if (before.childCount == 0 && !before.inlineContent || needsGap(before.type)) + return true; + if (before.inlineContent) + return false; + } + } + return true; +} +function closedAfter($pos) { + for (let d = $pos.depth; d >= 0; d--) { + let index = $pos.indexAfter(d), parent = $pos.node(d); + if (index == parent.childCount) { + if (parent.type.spec.isolating) + return true; + continue; + } + for (let after = parent.child(index); ; after = after.firstChild) { + if (after.childCount == 0 && !after.inlineContent || needsGap(after.type)) + return true; + if (after.inlineContent) + return false; + } + } + return true; +} +function gapCursor() { + return new Plugin({ + props: { + decorations: drawGapCursor, + createSelectionBetween(_view, $anchor, $head) { + return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null; + }, + handleClick, + handleKeyDown, + handleDOMEvents: { beforeinput } + } + }); +} +const handleKeyDown = keydownHandler({ + "ArrowLeft": arrow("horiz", -1), + "ArrowRight": arrow("horiz", 1), + "ArrowUp": arrow("vert", -1), + "ArrowDown": arrow("vert", 1) +}); +function arrow(axis, dir) { + const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left"; + return function(state, dispatch, view) { + let sel = state.selection; + let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty; + if (sel instanceof TextSelection) { + if (!view.endOfTextblock(dirStr) || $start.depth == 0) + return false; + mustMove = false; + $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before()); + } + let $found = GapCursor.findGapCursorFrom($start, dir, mustMove); + if (!$found) + return false; + if (dispatch) + dispatch(state.tr.setSelection(new GapCursor($found))); + return true; + }; +} +function handleClick(view, pos, event) { + if (!view || !view.editable) + return false; + let $pos = view.state.doc.resolve(pos); + if (!GapCursor.valid($pos)) + return false; + let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY }); + if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside))) + return false; + view.dispatch(view.state.tr.setSelection(new GapCursor($pos))); + return true; +} +function beforeinput(view, event) { + if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor)) + return false; + let { $from } = view.state.selection; + let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text); + if (!insert) + return false; + let frag = Fragment.empty; + for (let i = insert.length - 1; i >= 0; i--) + frag = Fragment.from(insert[i].createAndFill(null, frag)); + let tr2 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0)); + tr2.setSelection(TextSelection.near(tr2.doc.resolve($from.pos + 1))); + view.dispatch(tr2); + return false; +} +function drawGapCursor(state) { + if (!(state.selection instanceof GapCursor)) + return null; + let node = document.createElement("div"); + node.className = "ProseMirror-gapcursor"; + return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: "gapcursor" })]); +} +var GOOD_LEAF_SIZE = 200; +var RopeSequence = function RopeSequence2() { +}; +RopeSequence.prototype.append = function append(other) { + if (!other.length) { + return this; + } + other = RopeSequence.from(other); + return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other); +}; +RopeSequence.prototype.prepend = function prepend(other) { + if (!other.length) { + return this; + } + return RopeSequence.from(other).append(this); +}; +RopeSequence.prototype.appendInner = function appendInner(other) { + return new Append(this, other); +}; +RopeSequence.prototype.slice = function slice(from2, to) { + if (from2 === void 0) from2 = 0; + if (to === void 0) to = this.length; + if (from2 >= to) { + return RopeSequence.empty; + } + return this.sliceInner(Math.max(0, from2), Math.min(this.length, to)); +}; +RopeSequence.prototype.get = function get(i) { + if (i < 0 || i >= this.length) { + return void 0; + } + return this.getInner(i); +}; +RopeSequence.prototype.forEach = function forEach2(f, from2, to) { + if (from2 === void 0) from2 = 0; + if (to === void 0) to = this.length; + if (from2 <= to) { + this.forEachInner(f, from2, to, 0); + } else { + this.forEachInvertedInner(f, from2, to, 0); + } +}; +RopeSequence.prototype.map = function map(f, from2, to) { + if (from2 === void 0) from2 = 0; + if (to === void 0) to = this.length; + var result = []; + this.forEach(function(elt, i) { + return result.push(f(elt, i)); + }, from2, to); + return result; +}; +RopeSequence.from = function from(values) { + if (values instanceof RopeSequence) { + return values; + } + return values && values.length ? new Leaf(values) : RopeSequence.empty; +}; +var Leaf = /* @__PURE__ */ (function(RopeSequence3) { + function Leaf2(values) { + RopeSequence3.call(this); + this.values = values; + } + if (RopeSequence3) Leaf2.__proto__ = RopeSequence3; + Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); + Leaf2.prototype.constructor = Leaf2; + var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } }; + Leaf2.prototype.flatten = function flatten() { + return this.values; + }; + Leaf2.prototype.sliceInner = function sliceInner(from2, to) { + if (from2 == 0 && to == this.length) { + return this; + } + return new Leaf2(this.values.slice(from2, to)); + }; + Leaf2.prototype.getInner = function getInner(i) { + return this.values[i]; + }; + Leaf2.prototype.forEachInner = function forEachInner(f, from2, to, start) { + for (var i = from2; i < to; i++) { + if (f(this.values[i], start + i) === false) { + return false; + } + } + }; + Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) { + for (var i = from2 - 1; i >= to; i--) { + if (f(this.values[i], start + i) === false) { + return false; + } + } + }; + Leaf2.prototype.leafAppend = function leafAppend(other) { + if (this.length + other.length <= GOOD_LEAF_SIZE) { + return new Leaf2(this.values.concat(other.flatten())); + } + }; + Leaf2.prototype.leafPrepend = function leafPrepend(other) { + if (this.length + other.length <= GOOD_LEAF_SIZE) { + return new Leaf2(other.flatten().concat(this.values)); + } + }; + prototypeAccessors.length.get = function() { + return this.values.length; + }; + prototypeAccessors.depth.get = function() { + return 0; + }; + Object.defineProperties(Leaf2.prototype, prototypeAccessors); + return Leaf2; +})(RopeSequence); +RopeSequence.empty = new Leaf([]); +var Append = /* @__PURE__ */ (function(RopeSequence3) { + function Append2(left, right) { + RopeSequence3.call(this); + this.left = left; + this.right = right; + this.length = left.length + right.length; + this.depth = Math.max(left.depth, right.depth) + 1; + } + if (RopeSequence3) Append2.__proto__ = RopeSequence3; + Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); + Append2.prototype.constructor = Append2; + Append2.prototype.flatten = function flatten() { + return this.left.flatten().concat(this.right.flatten()); + }; + Append2.prototype.getInner = function getInner(i) { + return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length); + }; + Append2.prototype.forEachInner = function forEachInner(f, from2, to, start) { + var leftLen = this.left.length; + if (from2 < leftLen && this.left.forEachInner(f, from2, Math.min(to, leftLen), start) === false) { + return false; + } + if (to > leftLen && this.right.forEachInner(f, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) { + return false; + } + }; + Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) { + var leftLen = this.left.length; + if (from2 > leftLen && this.right.forEachInvertedInner(f, from2 - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) { + return false; + } + if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from2, leftLen), to, start) === false) { + return false; + } + }; + Append2.prototype.sliceInner = function sliceInner(from2, to) { + if (from2 == 0 && to == this.length) { + return this; + } + var leftLen = this.left.length; + if (to <= leftLen) { + return this.left.slice(from2, to); + } + if (from2 >= leftLen) { + return this.right.slice(from2 - leftLen, to - leftLen); + } + return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen)); + }; + Append2.prototype.leafAppend = function leafAppend(other) { + var inner = this.right.leafAppend(other); + if (inner) { + return new Append2(this.left, inner); + } + }; + Append2.prototype.leafPrepend = function leafPrepend(other) { + var inner = this.left.leafPrepend(other); + if (inner) { + return new Append2(inner, this.right); + } + }; + Append2.prototype.appendInner = function appendInner2(other) { + if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) { + return new Append2(this.left, new Append2(this.right, other)); + } + return new Append2(this, other); + }; + return Append2; +})(RopeSequence); +const max_empty_items = 500; +class Branch { + constructor(items, eventCount) { + this.items = items; + this.eventCount = eventCount; + } + // Pop the latest event off the branch's history and apply it + // to a document transform. + popEvent(state, preserveItems) { + if (this.eventCount == 0) + return null; + let end = this.items.length; + for (; ; end--) { + let next = this.items.get(end - 1); + if (next.selection) { + --end; + break; + } + } + let remap, mapFrom; + if (preserveItems) { + remap = this.remapping(end, this.items.length); + mapFrom = remap.maps.length; + } + let transform = state.tr; + let selection, remaining; + let addAfter = [], addBefore = []; + this.items.forEach((item, i) => { + if (!item.step) { + if (!remap) { + remap = this.remapping(end, i + 1); + mapFrom = remap.maps.length; + } + mapFrom--; + addBefore.push(item); + return; + } + if (remap) { + addBefore.push(new Item(item.map)); + let step = item.step.map(remap.slice(mapFrom)), map2; + if (step && transform.maybeStep(step).doc) { + map2 = transform.mapping.maps[transform.mapping.maps.length - 1]; + addAfter.push(new Item(map2, void 0, void 0, addAfter.length + addBefore.length)); + } + mapFrom--; + if (map2) + remap.appendMap(map2, mapFrom); + } else { + transform.maybeStep(item.step); + } + if (item.selection) { + selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection; + remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1); + return false; + } + }, this.items.length, 0); + return { remaining, transform, selection }; + } + // Create a new branch with the given transform added. + addTransform(transform, selection, histOptions, preserveItems) { + let newItems = [], eventCount = this.eventCount; + let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null; + for (let i = 0; i < transform.steps.length; i++) { + let step = transform.steps[i].invert(transform.docs[i]); + let item = new Item(transform.mapping.maps[i], step, selection), merged; + if (merged = lastItem && lastItem.merge(item)) { + item = merged; + if (i) + newItems.pop(); + else + oldItems = oldItems.slice(0, oldItems.length - 1); + } + newItems.push(item); + if (selection) { + eventCount++; + selection = void 0; + } + if (!preserveItems) + lastItem = item; + } + let overflow = eventCount - histOptions.depth; + if (overflow > DEPTH_OVERFLOW) { + oldItems = cutOffEvents(oldItems, overflow); + eventCount -= overflow; + } + return new Branch(oldItems.append(newItems), eventCount); + } + remapping(from2, to) { + let maps = new Mapping(); + this.items.forEach((item, i) => { + let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from2 ? maps.maps.length - item.mirrorOffset : void 0; + maps.appendMap(item.map, mirrorPos); + }, from2, to); + return maps; + } + addMaps(array) { + if (this.eventCount == 0) + return this; + return new Branch(this.items.append(array.map((map2) => new Item(map2))), this.eventCount); + } + // When the collab module receives remote changes, the history has + // to know about those, so that it can adjust the steps that were + // rebased on top of the remote changes, and include the position + // maps for the remote changes in its array of items. + rebased(rebasedTransform, rebasedCount) { + if (!this.eventCount) + return this; + let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount); + let mapping = rebasedTransform.mapping; + let newUntil = rebasedTransform.steps.length; + let eventCount = this.eventCount; + this.items.forEach((item) => { + if (item.selection) + eventCount--; + }, start); + let iRebased = rebasedCount; + this.items.forEach((item) => { + let pos = mapping.getMirror(--iRebased); + if (pos == null) + return; + newUntil = Math.min(newUntil, pos); + let map2 = mapping.maps[pos]; + if (item.step) { + let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]); + let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)); + if (selection) + eventCount++; + rebasedItems.push(new Item(map2, step, selection)); + } else { + rebasedItems.push(new Item(map2)); + } + }, start); + let newMaps = []; + for (let i = rebasedCount; i < newUntil; i++) + newMaps.push(new Item(mapping.maps[i])); + let items = this.items.slice(0, start).append(newMaps).append(rebasedItems); + let branch = new Branch(items, eventCount); + if (branch.emptyItemCount() > max_empty_items) + branch = branch.compress(this.items.length - rebasedItems.length); + return branch; + } + emptyItemCount() { + let count = 0; + this.items.forEach((item) => { + if (!item.step) + count++; + }); + return count; + } + // Compressing a branch means rewriting it to push the air (map-only + // items) out. During collaboration, these naturally accumulate + // because each remote change adds one. The `upto` argument is used + // to ensure that only the items below a given level are compressed, + // because `rebased` relies on a clean, untouched set of items in + // order to associate old items with rebased steps. + compress(upto = this.items.length) { + let remap = this.remapping(0, upto), mapFrom = remap.maps.length; + let items = [], events = 0; + this.items.forEach((item, i) => { + if (i >= upto) { + items.push(item); + if (item.selection) + events++; + } else if (item.step) { + let step = item.step.map(remap.slice(mapFrom)), map2 = step && step.getMap(); + mapFrom--; + if (map2) + remap.appendMap(map2, mapFrom); + if (step) { + let selection = item.selection && item.selection.map(remap.slice(mapFrom)); + if (selection) + events++; + let newItem = new Item(map2.invert(), step, selection), merged, last = items.length - 1; + if (merged = items.length && items[last].merge(newItem)) + items[last] = merged; + else + items.push(newItem); + } + } else if (item.map) { + mapFrom--; + } + }, this.items.length, 0); + return new Branch(RopeSequence.from(items.reverse()), events); + } +} +Branch.empty = new Branch(RopeSequence.empty, 0); +function cutOffEvents(items, n) { + let cutPoint; + items.forEach((item, i) => { + if (item.selection && n-- == 0) { + cutPoint = i; + return false; + } + }); + return items.slice(cutPoint); +} +class Item { + constructor(map2, step, selection, mirrorOffset) { + this.map = map2; + this.step = step; + this.selection = selection; + this.mirrorOffset = mirrorOffset; + } + merge(other) { + if (this.step && other.step && !other.selection) { + let step = other.step.merge(this.step); + if (step) + return new Item(step.getMap().invert(), step, this.selection); + } + } +} +class HistoryState { + constructor(done, undone, prevRanges, prevTime, prevComposition) { + this.done = done; + this.undone = undone; + this.prevRanges = prevRanges; + this.prevTime = prevTime; + this.prevComposition = prevComposition; + } +} +const DEPTH_OVERFLOW = 20; +function applyTransaction(history2, state, tr2, options) { + let historyTr = tr2.getMeta(historyKey), rebased; + if (historyTr) + return historyTr.historyState; + if (tr2.getMeta(closeHistoryKey)) + history2 = new HistoryState(history2.done, history2.undone, null, 0, -1); + let appended = tr2.getMeta("appendedTransaction"); + if (tr2.steps.length == 0) { + return history2; + } else if (appended && appended.getMeta(historyKey)) { + if (appended.getMeta(historyKey).redo) + return new HistoryState(history2.done.addTransform(tr2, void 0, options, mustPreserveItems(state)), history2.undone, rangesFor(tr2.mapping.maps), history2.prevTime, history2.prevComposition); + else + return new HistoryState(history2.done, history2.undone.addTransform(tr2, void 0, options, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition); + } else if (tr2.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { + let composition = tr2.getMeta("composition"); + let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr2.time || 0) - options.newGroupDelay || !isAdjacentTo(tr2, history2.prevRanges)); + let prevRanges = appended ? mapRanges(history2.prevRanges, tr2.mapping) : rangesFor(tr2.mapping.maps); + return new HistoryState(history2.done.addTransform(tr2, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr2.time, composition == null ? history2.prevComposition : composition); + } else if (rebased = tr2.getMeta("rebased")) { + return new HistoryState(history2.done.rebased(tr2, rebased), history2.undone.rebased(tr2, rebased), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition); + } else { + return new HistoryState(history2.done.addMaps(tr2.mapping.maps), history2.undone.addMaps(tr2.mapping.maps), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition); + } +} +function isAdjacentTo(transform, prevRanges) { + if (!prevRanges) + return false; + if (!transform.docChanged) + return true; + let adjacent = false; + transform.mapping.maps[0].forEach((start, end) => { + for (let i = 0; i < prevRanges.length; i += 2) + if (start <= prevRanges[i + 1] && end >= prevRanges[i]) + adjacent = true; + }); + return adjacent; +} +function rangesFor(maps) { + let result = []; + for (let i = maps.length - 1; i >= 0 && result.length == 0; i--) + maps[i].forEach((_from, _to, from2, to) => result.push(from2, to)); + return result; +} +function mapRanges(ranges, mapping) { + if (!ranges) + return null; + let result = []; + for (let i = 0; i < ranges.length; i += 2) { + let from2 = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1); + if (from2 <= to) + result.push(from2, to); + } + return result; +} +function histTransaction(history2, state, redo2) { + let preserveItems = mustPreserveItems(state); + let histOptions = historyKey.get(state).spec.config; + let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems); + if (!pop) + return null; + let selection = pop.selection.resolve(pop.transform.doc); + let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems); + let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1); + return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist }); +} +let cachedPreserveItems = false, cachedPreserveItemsPlugins = null; +function mustPreserveItems(state) { + let plugins = state.plugins; + if (cachedPreserveItemsPlugins != plugins) { + cachedPreserveItems = false; + cachedPreserveItemsPlugins = plugins; + for (let i = 0; i < plugins.length; i++) + if (plugins[i].spec.historyPreserveItems) { + cachedPreserveItems = true; + break; + } + } + return cachedPreserveItems; +} +const historyKey = new PluginKey("history"); +const closeHistoryKey = new PluginKey("closeHistory"); +function history(config = {}) { + config = { + depth: config.depth || 100, + newGroupDelay: config.newGroupDelay || 500 + }; + return new Plugin({ + key: historyKey, + state: { + init() { + return new HistoryState(Branch.empty, Branch.empty, null, 0, -1); + }, + apply(tr2, hist, state) { + return applyTransaction(hist, state, tr2, config); + } + }, + config, + props: { + handleDOMEvents: { + beforeinput(view, e) { + let inputType = e.inputType; + let command2 = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null; + if (!command2 || !view.editable) + return false; + e.preventDefault(); + return command2(view.state, view.dispatch); + } + } + } + }); +} +function buildCommand(redo2, scroll) { + return (state, dispatch) => { + let hist = historyKey.getState(state); + if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0) + return false; + if (dispatch) { + let tr2 = histTransaction(hist, state, redo2); + if (tr2) + dispatch(scroll ? tr2.scrollIntoView() : tr2); + } + return true; + }; +} +const undo = buildCommand(false, true); +const redo = buildCommand(true, true); +Extension.create({ + name: "characterCount", + addOptions() { + return { + limit: null, + mode: "textSize", + textCounter: (text) => text.length, + wordCounter: (text) => text.split(" ").filter((word) => word !== "").length + }; + }, + addStorage() { + return { + characters: () => 0, + words: () => 0 + }; + }, + onBeforeCreate() { + this.storage.characters = (options) => { + const node = (options == null ? void 0 : options.node) || this.editor.state.doc; + const mode = (options == null ? void 0 : options.mode) || this.options.mode; + if (mode === "textSize") { + const text = node.textBetween(0, node.content.size, void 0, " "); + return this.options.textCounter(text); + } + return node.nodeSize; + }; + this.storage.words = (options) => { + const node = (options == null ? void 0 : options.node) || this.editor.state.doc; + const text = node.textBetween(0, node.content.size, " ", " "); + return this.options.wordCounter(text); + }; + }, + addProseMirrorPlugins() { + let initialEvaluationDone = false; + return [ + new Plugin({ + key: new PluginKey("characterCount"), + appendTransaction: (transactions, oldState, newState) => { + if (initialEvaluationDone) { + return; + } + const limit = this.options.limit; + if (limit === null || limit === void 0 || limit === 0) { + initialEvaluationDone = true; + return; + } + const initialContentSize = this.storage.characters({ node: newState.doc }); + if (initialContentSize > limit) { + const over = initialContentSize - limit; + const from2 = 0; + const to = over; + console.warn( + `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.` + ); + const tr2 = newState.tr.deleteRange(from2, to); + initialEvaluationDone = true; + return tr2; + } + initialEvaluationDone = true; + }, + filterTransaction: (transaction, state) => { + const limit = this.options.limit; + if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) { + return true; + } + const oldSize = this.storage.characters({ node: state.doc }); + const newSize = this.storage.characters({ node: transaction.doc }); + if (newSize <= limit) { + return true; + } + if (oldSize > limit && newSize > limit && newSize <= oldSize) { + return true; + } + if (oldSize > limit && newSize > limit && newSize > oldSize) { + return false; + } + const isPaste = transaction.getMeta("paste"); + if (!isPaste) { + return false; + } + const pos = transaction.selection.$head.pos; + const over = newSize - limit; + const from2 = pos - over; + const to = pos; + transaction.deleteRange(from2, to); + const updatedSize = this.storage.characters({ node: transaction.doc }); + if (updatedSize > limit) { + return false; + } + return true; + } + }) + ]; + } +}); +var Dropcursor = Extension.create({ + name: "dropCursor", + addOptions() { + return { + color: "currentColor", + width: 1, + class: void 0 + }; + }, + addProseMirrorPlugins() { + return [dropCursor(this.options)]; + } +}); +Extension.create({ + name: "focus", + addOptions() { + return { + className: "has-focus", + mode: "all" + }; + }, + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("focus"), + props: { + decorations: ({ doc: doc2, selection }) => { + const { isEditable, isFocused } = this.editor; + const { anchor } = selection; + const decorations = []; + if (!isEditable || !isFocused) { + return DecorationSet.create(doc2, []); + } + let maxLevels = 0; + if (this.options.mode === "deepest") { + doc2.descendants((node, pos) => { + if (node.isText) { + return; + } + const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1; + if (!isCurrent) { + return false; + } + maxLevels += 1; + }); + } + let currentLevel = 0; + doc2.descendants((node, pos) => { + if (node.isText) { + return false; + } + const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1; + if (!isCurrent) { + return false; + } + currentLevel += 1; + const outOfScope = this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1; + if (outOfScope) { + return this.options.mode === "deepest"; + } + decorations.push( + Decoration.node(pos, pos + node.nodeSize, { + class: this.options.className + }) + ); + }); + return DecorationSet.create(doc2, decorations); + } + } + }) + ]; + } +}); +var Gapcursor = Extension.create({ + name: "gapCursor", + addProseMirrorPlugins() { + return [gapCursor()]; + }, + extendNodeSchema(extension) { + var _a; + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + return { + allowGapCursor: (_a = callOrReturn(getExtensionField(extension, "allowGapCursor", context))) != null ? _a : null + }; + } +}); +var DEFAULT_DATA_ATTRIBUTE = "placeholder"; +function preparePlaceholderAttribute(attr) { + return attr.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9-]/g, "").replace(/^[0-9-]+/, "").replace(/^-+/, "").toLowerCase(); +} +var Placeholder = Extension.create({ + name: "placeholder", + addOptions() { + return { + emptyEditorClass: "is-editor-empty", + emptyNodeClass: "is-empty", + dataAttribute: DEFAULT_DATA_ATTRIBUTE, + placeholder: "Write something …", + showOnlyWhenEditable: true, + showOnlyCurrent: true, + includeChildren: false + }; + }, + addProseMirrorPlugins() { + const dataAttribute = this.options.dataAttribute ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}` : `data-${DEFAULT_DATA_ATTRIBUTE}`; + return [ + new Plugin({ + key: new PluginKey("placeholder"), + props: { + decorations: ({ doc: doc2, selection }) => { + const active = this.editor.isEditable || !this.options.showOnlyWhenEditable; + const { anchor } = selection; + const decorations = []; + if (!active) { + return null; + } + const isEmptyDoc = this.editor.isEmpty; + doc2.descendants((node, pos) => { + const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize; + const isEmpty = !node.isLeaf && isNodeEmpty(node); + if (!node.type.isTextblock) { + return this.options.includeChildren; + } + if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) { + const classes = [this.options.emptyNodeClass]; + if (isEmptyDoc) { + classes.push(this.options.emptyEditorClass); + } + const decoration = Decoration.node(pos, pos + node.nodeSize, { + class: classes.join(" "), + [dataAttribute]: typeof this.options.placeholder === "function" ? this.options.placeholder({ + editor: this.editor, + node, + pos, + hasAnchor + }) : this.options.placeholder + }); + decorations.push(decoration); + } + return this.options.includeChildren; + }); + return DecorationSet.create(doc2, decorations); + } + } + }) + ]; + } +}); +Extension.create({ + name: "selection", + addOptions() { + return { + className: "selection" + }; + }, + addProseMirrorPlugins() { + const { editor, options } = this; + return [ + new Plugin({ + key: new PluginKey("selection"), + props: { + decorations(state) { + if (state.selection.empty || editor.isFocused || !editor.isEditable || isNodeSelection(state.selection) || editor.view.dragging) { + return null; + } + return DecorationSet.create(state.doc, [ + Decoration.inline(state.selection.from, state.selection.to, { + class: options.className + }) + ]); + } + } + }) + ]; + } +}); +var skipTrailingNodeMeta = "skipTrailingNode"; +function nodeEqualsType({ types, node }) { + return node && Array.isArray(types) && types.includes(node.type) || (node == null ? void 0 : node.type) === types; +} +var TrailingNode = Extension.create({ + name: "trailingNode", + addOptions() { + return { + node: void 0, + notAfter: [] + }; + }, + addProseMirrorPlugins() { + var _a; + const plugin = new PluginKey(this.name); + const defaultNode = this.options.node || ((_a = this.editor.schema.topNodeType.contentMatch.defaultType) == null ? void 0 : _a.name) || "paragraph"; + const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node) => (this.options.notAfter || []).concat(defaultNode).includes(node.name)); + return [ + new Plugin({ + key: plugin, + appendTransaction: (transactions, __, state) => { + const { doc: doc2, tr: tr2, schema } = state; + const shouldInsertNodeAtEnd = plugin.getState(state); + const endPosition = doc2.content.size; + const type = schema.nodes[defaultNode]; + if (transactions.some((transaction) => transaction.getMeta(skipTrailingNodeMeta))) { + return; + } + if (!shouldInsertNodeAtEnd) { + return; + } + return tr2.insert(endPosition, type.create()); + }, + state: { + init: (_, state) => { + const lastNode = state.tr.doc.lastChild; + return !nodeEqualsType({ node: lastNode, types: disabledNodes }); + }, + apply: (tr2, value) => { + if (!tr2.docChanged) { + return value; + } + if (tr2.getMeta("__uniqueIDTransaction")) { + return value; + } + const lastNode = tr2.doc.lastChild; + return !nodeEqualsType({ node: lastNode, types: disabledNodes }); + } + } + }) + ]; + } +}); +var UndoRedo = Extension.create({ + name: "undoRedo", + addOptions() { + return { + depth: 100, + newGroupDelay: 500 + }; + }, + addCommands() { + return { + undo: () => ({ state, dispatch }) => { + return undo(state, dispatch); + }, + redo: () => ({ state, dispatch }) => { + return redo(state, dispatch); + } + }; + }, + addProseMirrorPlugins() { + return [history(this.options)]; + }, + addKeyboardShortcuts() { + return { + "Mod-z": () => this.editor.commands.undo(), + "Shift-Mod-z": () => this.editor.commands.redo(), + "Mod-y": () => this.editor.commands.redo(), + // Russian keyboard layouts + "Mod-я": () => this.editor.commands.undo(), + "Shift-Mod-я": () => this.editor.commands.redo() + }; + } +}); +var StarterKit = Extension.create({ + name: "starterKit", + addExtensions() { + var _a, _b, _c, _d; + const extensions = []; + if (this.options.bold !== false) { + extensions.push(Bold.configure(this.options.bold)); + } + if (this.options.blockquote !== false) { + extensions.push(Blockquote.configure(this.options.blockquote)); + } + if (this.options.bulletList !== false) { + extensions.push(BulletList.configure(this.options.bulletList)); + } + if (this.options.code !== false) { + extensions.push(Code.configure(this.options.code)); + } + if (this.options.codeBlock !== false) { + extensions.push(CodeBlock.configure(this.options.codeBlock)); + } + if (this.options.document !== false) { + extensions.push(Document.configure(this.options.document)); + } + if (this.options.dropcursor !== false) { + extensions.push(Dropcursor.configure(this.options.dropcursor)); + } + if (this.options.gapcursor !== false) { + extensions.push(Gapcursor.configure(this.options.gapcursor)); + } + if (this.options.hardBreak !== false) { + extensions.push(HardBreak.configure(this.options.hardBreak)); + } + if (this.options.heading !== false) { + extensions.push(Heading.configure(this.options.heading)); + } + if (this.options.undoRedo !== false) { + extensions.push(UndoRedo.configure(this.options.undoRedo)); + } + if (this.options.horizontalRule !== false) { + extensions.push(HorizontalRule.configure(this.options.horizontalRule)); + } + if (this.options.italic !== false) { + extensions.push(Italic.configure(this.options.italic)); + } + if (this.options.listItem !== false) { + extensions.push(ListItem.configure(this.options.listItem)); + } + if (this.options.listKeymap !== false) { + extensions.push(ListKeymap.configure((_a = this.options) == null ? void 0 : _a.listKeymap)); + } + if (this.options.link !== false) { + extensions.push(Link.configure((_b = this.options) == null ? void 0 : _b.link)); + } + if (this.options.orderedList !== false) { + extensions.push(OrderedList.configure(this.options.orderedList)); + } + if (this.options.paragraph !== false) { + extensions.push(Paragraph.configure(this.options.paragraph)); + } + if (this.options.strike !== false) { + extensions.push(Strike.configure(this.options.strike)); + } + if (this.options.text !== false) { + extensions.push(Text.configure(this.options.text)); + } + if (this.options.underline !== false) { + extensions.push(Underline.configure((_c = this.options) == null ? void 0 : _c.underline)); + } + if (this.options.trailingNode !== false) { + extensions.push(TrailingNode.configure((_d = this.options) == null ? void 0 : _d.trailingNode)); + } + return extensions; + } +}); +var index_default$3 = StarterKit; +var index_default$2 = Placeholder; +var inputRegex = /(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/; +var Image = Node3.create({ + name: "image", + addOptions() { + return { + inline: false, + allowBase64: false, + HTMLAttributes: {}, + resize: false + }; + }, + inline() { + return this.options.inline; + }, + group() { + return this.options.inline ? "inline" : "block"; + }, + draggable: true, + addAttributes() { + return { + src: { + default: null + }, + alt: { + default: null + }, + title: { + default: null + }, + width: { + default: null + }, + height: { + default: null + } + }; + }, + parseHTML() { + return [ + { + tag: this.options.allowBase64 ? "img[src]" : 'img[src]:not([src^="data:"])' + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["img", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; + }, + parseMarkdown: (token, helpers) => { + return helpers.createNode("image", { + src: token.href, + title: token.title, + alt: token.text + }); + }, + renderMarkdown: (node) => { + var _a, _b, _c, _d, _e, _f; + const src = (_b = (_a = node.attrs) == null ? void 0 : _a.src) != null ? _b : ""; + const alt = (_d = (_c = node.attrs) == null ? void 0 : _c.alt) != null ? _d : ""; + const title = (_f = (_e = node.attrs) == null ? void 0 : _e.title) != null ? _f : ""; + return title ? `![${alt}](${src} "${title}")` : `![${alt}](${src})`; + }, + addNodeView() { + if (!this.options.resize || !this.options.resize.enabled || typeof document === "undefined") { + return null; + } + const { directions, minWidth, minHeight, alwaysPreserveAspectRatio } = this.options.resize; + return ({ node, getPos, HTMLAttributes, editor }) => { + const el = document.createElement("img"); + Object.entries(HTMLAttributes).forEach(([key, value]) => { + if (value != null) { + switch (key) { + case "width": + case "height": + break; + default: + el.setAttribute(key, value); + break; + } + } + }); + el.src = HTMLAttributes.src; + const nodeView = new ResizableNodeView({ + element: el, + editor, + node, + getPos, + onResize: (width, height) => { + el.style.width = `${width}px`; + el.style.height = `${height}px`; + }, + onCommit: (width, height) => { + const pos = getPos(); + if (pos === void 0) { + return; + } + this.editor.chain().setNodeSelection(pos).updateAttributes(this.name, { + width, + height + }).run(); + }, + onUpdate: (updatedNode, _decorations, _innerDecorations) => { + if (updatedNode.type !== node.type) { + return false; + } + return true; + }, + options: { + directions, + min: { + width: minWidth, + height: minHeight + }, + preserveAspectRatio: alwaysPreserveAspectRatio === true + } + }); + const dom = nodeView.dom; + dom.style.visibility = "hidden"; + dom.style.pointerEvents = "none"; + el.onload = () => { + dom.style.visibility = ""; + dom.style.pointerEvents = ""; + }; + return nodeView; + }; + }, + addCommands() { + return { + setImage: (options) => ({ commands }) => { + return commands.insertContent({ + type: this.name, + attrs: options + }); + } + }; + }, + addInputRules() { + return [ + nodeInputRule({ + find: inputRegex, + type: this.type, + getAttributes: (match) => { + const [, , alt, src, title] = match; + return { src, alt, title }; + } + }) + ]; + } +}); +var index_default$1 = Image; +function findSuggestionMatch(config) { + var _a; + const { char, allowSpaces: allowSpacesOption, allowToIncludeChar, allowedPrefixes, startOfLine, $position } = config; + const allowSpaces = allowSpacesOption && !allowToIncludeChar; + const escapedChar = escapeForRegEx(char); + const suffix = new RegExp(`\\s${escapedChar}$`); + const prefix = startOfLine ? "^" : ""; + const finalEscapedChar = allowToIncludeChar ? "" : escapedChar; + const regexp = allowSpaces ? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${finalEscapedChar}|$)`, "gm") : new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${finalEscapedChar}]*`, "gm"); + const text = ((_a = $position.nodeBefore) == null ? void 0 : _a.isText) && $position.nodeBefore.text; + if (!text) { + return null; + } + const textFrom = $position.pos - text.length; + const match = Array.from(text.matchAll(regexp)).pop(); + if (!match || match.input === void 0 || match.index === void 0) { + return null; + } + const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index); + const matchPrefixIsAllowed = new RegExp(`^[${allowedPrefixes == null ? void 0 : allowedPrefixes.join("")}\0]?$`).test(matchPrefix); + if (allowedPrefixes !== null && !matchPrefixIsAllowed) { + return null; + } + const from2 = textFrom + match.index; + let to = from2 + match[0].length; + if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) { + match[0] += " "; + to += 1; + } + if (from2 < $position.pos && to >= $position.pos) { + return { + range: { + from: from2, + to + }, + query: match[0].slice(char.length), + text: match[0] + }; + } + return null; +} +function hasInsertedWhitespace(transaction) { + if (!transaction.docChanged) { + return false; + } + return transaction.steps.some((step) => { + const slice2 = step.slice; + if (!(slice2 == null ? void 0 : slice2.content)) { + return false; + } + const inserted = slice2.content.textBetween(0, slice2.content.size, "\n"); + return /\s/.test(inserted); + }); +} +var SuggestionPluginKey = new PluginKey("suggestion"); +function Suggestion({ + pluginKey = SuggestionPluginKey, + editor, + char = "@", + allowSpaces = false, + allowToIncludeChar = false, + allowedPrefixes = [" "], + startOfLine = false, + decorationTag = "span", + decorationClass = "suggestion", + decorationContent = "", + decorationEmptyClass = "is-empty", + command: command2 = () => null, + items = () => [], + render = () => ({}), + allow = () => true, + findSuggestionMatch: findSuggestionMatch2 = findSuggestionMatch, + shouldShow, + shouldResetDismissed +}) { + let props; + const renderer = render == null ? void 0 : render(); + const effectiveAllowSpaces = allowSpaces && !allowToIncludeChar; + const getAnchorClientRect = () => { + const pos = editor.state.selection.$anchor.pos; + const coords = editor.view.coordsAtPos(pos); + const { top, right, bottom, left } = coords; + try { + return new DOMRect(left, top, right - left, bottom - top); + } catch { + return null; + } + }; + const clientRectFor = (view, decorationNode) => { + if (!decorationNode) { + return getAnchorClientRect; + } + return () => { + const state = pluginKey.getState(editor.state); + const decorationId = state == null ? void 0 : state.decorationId; + const currentDecorationNode = view.dom.querySelector(`[data-decoration-id="${decorationId}"]`); + return (currentDecorationNode == null ? void 0 : currentDecorationNode.getBoundingClientRect()) || null; + }; + }; + const shouldKeepDismissed = ({ + match, + dismissedRange, + state, + transaction + }) => { + if (shouldResetDismissed == null ? void 0 : shouldResetDismissed({ + editor, + state, + range: dismissedRange, + match, + transaction, + allowSpaces: effectiveAllowSpaces + })) { + return false; + } + if (effectiveAllowSpaces) { + return match.range.from === dismissedRange.from; + } + return match.range.from === dismissedRange.from && !hasInsertedWhitespace(transaction); + }; + function dispatchExit(view, pluginKeyRef) { + var _a; + try { + const state = pluginKey.getState(view.state); + const decorationNode = (state == null ? void 0 : state.decorationId) ? view.dom.querySelector(`[data-decoration-id="${state.decorationId}"]`) : null; + const exitProps = { + // @ts-ignore editor is available in closure + editor, + range: (state == null ? void 0 : state.range) || { from: 0, to: 0 }, + query: (state == null ? void 0 : state.query) || null, + text: (state == null ? void 0 : state.text) || null, + items: [], + command: (commandProps) => { + return command2({ editor, range: (state == null ? void 0 : state.range) || { from: 0, to: 0 }, props: commandProps }); + }, + decorationNode, + clientRect: clientRectFor(view, decorationNode) + }; + (_a = renderer == null ? void 0 : renderer.onExit) == null ? void 0 : _a.call(renderer, exitProps); + } catch { + } + const tr2 = view.state.tr.setMeta(pluginKeyRef, { exit: true }); + view.dispatch(tr2); + } + const plugin = new Plugin({ + key: pluginKey, + view() { + return { + update: async (view, prevState) => { + var _a, _b, _c, _d, _e, _f, _g; + const prev = (_a = this.key) == null ? void 0 : _a.getState(prevState); + const next = (_b = this.key) == null ? void 0 : _b.getState(view.state); + const moved = prev.active && next.active && prev.range.from !== next.range.from; + const started = !prev.active && next.active; + const stopped = prev.active && !next.active; + const changed = !started && !stopped && prev.query !== next.query; + const handleStart = started || moved && changed; + const handleChange = changed || moved; + const handleExit = stopped || moved && changed; + if (!handleStart && !handleChange && !handleExit) { + return; + } + const state = handleExit && !handleStart ? prev : next; + const decorationNode = view.dom.querySelector(`[data-decoration-id="${state.decorationId}"]`); + props = { + editor, + range: state.range, + query: state.query, + text: state.text, + items: [], + command: (commandProps) => { + return command2({ + editor, + range: state.range, + props: commandProps + }); + }, + decorationNode, + clientRect: clientRectFor(view, decorationNode) + }; + if (handleStart) { + (_c = renderer == null ? void 0 : renderer.onBeforeStart) == null ? void 0 : _c.call(renderer, props); + } + if (handleChange) { + (_d = renderer == null ? void 0 : renderer.onBeforeUpdate) == null ? void 0 : _d.call(renderer, props); + } + if (handleChange || handleStart) { + props.items = await items({ + editor, + query: state.query + }); + } + if (handleExit) { + (_e = renderer == null ? void 0 : renderer.onExit) == null ? void 0 : _e.call(renderer, props); + } + if (handleChange) { + (_f = renderer == null ? void 0 : renderer.onUpdate) == null ? void 0 : _f.call(renderer, props); + } + if (handleStart) { + (_g = renderer == null ? void 0 : renderer.onStart) == null ? void 0 : _g.call(renderer, props); + } + }, + destroy: () => { + var _a; + if (!props) { + return; + } + (_a = renderer == null ? void 0 : renderer.onExit) == null ? void 0 : _a.call(renderer, props); + } + }; + }, + state: { + // Initialize the plugin's internal state. + init() { + const state = { + active: false, + range: { + from: 0, + to: 0 + }, + query: null, + text: null, + composing: false, + dismissedRange: null + }; + return state; + }, + // Apply changes to the plugin state from a view transaction. + apply(transaction, prev, _oldState, state) { + const { isEditable } = editor; + const { composing } = editor.view; + const { selection } = transaction; + const { empty: empty2, from: from2 } = selection; + const next = { ...prev }; + const meta = transaction.getMeta(pluginKey); + if (meta && meta.exit) { + next.active = false; + next.decorationId = null; + next.range = { from: 0, to: 0 }; + next.query = null; + next.text = null; + next.dismissedRange = prev.active ? { ...prev.range } : prev.dismissedRange; + return next; + } + next.composing = composing; + if (transaction.docChanged && next.dismissedRange !== null) { + next.dismissedRange = { + from: transaction.mapping.map(next.dismissedRange.from), + to: transaction.mapping.map(next.dismissedRange.to) + }; + } + if (isEditable && (empty2 || editor.view.composing)) { + if ((from2 < prev.range.from || from2 > prev.range.to) && !composing && !prev.composing) { + next.active = false; + } + const match = findSuggestionMatch2({ + char, + allowSpaces, + allowToIncludeChar, + allowedPrefixes, + startOfLine, + $position: selection.$from + }); + const decorationId = `id_${Math.floor(Math.random() * 4294967295)}`; + if (match && allow({ + editor, + state, + range: match.range, + isActive: prev.active + }) && (!shouldShow || shouldShow({ + editor, + range: match.range, + query: match.query, + text: match.text, + transaction + }))) { + if (next.dismissedRange !== null && !shouldKeepDismissed({ + match, + dismissedRange: next.dismissedRange, + state, + transaction + })) { + next.dismissedRange = null; + } + if (next.dismissedRange === null) { + next.active = true; + next.decorationId = prev.decorationId ? prev.decorationId : decorationId; + next.range = match.range; + next.query = match.query; + next.text = match.text; + } else { + next.active = false; + } + } else { + if (!match) { + next.dismissedRange = null; + } + next.active = false; + } + } else { + next.active = false; + } + if (!next.active) { + next.decorationId = null; + next.range = { from: 0, to: 0 }; + next.query = null; + next.text = null; + } + return next; + } + }, + props: { + // Call the keydown hook if suggestion is active. + handleKeyDown(view, event) { + var _a, _b; + const { active, range } = plugin.getState(view.state); + if (!active) { + return false; + } + if (event.key === "Escape" || event.key === "Esc") { + const state = plugin.getState(view.state); + (_a = renderer == null ? void 0 : renderer.onKeyDown) == null ? void 0 : _a.call(renderer, { view, event, range: state.range }); + dispatchExit(view, pluginKey); + return true; + } + const handled = ((_b = renderer == null ? void 0 : renderer.onKeyDown) == null ? void 0 : _b.call(renderer, { view, event, range })) || false; + return handled; + }, + // Setup decorator on the currently active suggestion. + decorations(state) { + const { active, range, decorationId, query } = plugin.getState(state); + if (!active) { + return null; + } + const isEmpty = !(query == null ? void 0 : query.length); + const classNames = [decorationClass]; + if (isEmpty) { + classNames.push(decorationEmptyClass); + } + return DecorationSet.create(state.doc, [ + Decoration.inline(range.from, range.to, { + nodeName: decorationTag, + class: classNames.join(" "), + "data-decoration-id": decorationId, + "data-decoration-content": decorationContent + }) + ]); + } + } + }); + return plugin; +} +function getSuggestionOptions({ + editor: tiptapEditor, + overrideSuggestionOptions, + extensionName, + char = "@" +}) { + const pluginKey = new PluginKey(); + return { + editor: tiptapEditor, + char, + pluginKey, + command: ({ editor, range, props }) => { + var _a, _b, _c; + const nodeAfter = editor.view.state.selection.$to.nodeAfter; + const overrideSpace = (_a = nodeAfter == null ? void 0 : nodeAfter.text) == null ? void 0 : _a.startsWith(" "); + if (overrideSpace) { + range.to += 1; + } + editor.chain().focus().insertContentAt(range, [ + { + type: extensionName, + attrs: { ...props, mentionSuggestionChar: char } + }, + { + type: "text", + text: " " + } + ]).run(); + (_c = (_b = editor.view.dom.ownerDocument.defaultView) == null ? void 0 : _b.getSelection()) == null ? void 0 : _c.collapseToEnd(); + }, + allow: ({ state, range }) => { + const $from = state.doc.resolve(range.from); + const type = state.schema.nodes[extensionName]; + const allow = !!$from.parent.type.contentMatch.matchType(type); + return allow; + }, + ...overrideSuggestionOptions + }; +} +function getSuggestions(options) { + return (options.options.suggestions.length ? options.options.suggestions : [options.options.suggestion]).map( + (suggestion) => getSuggestionOptions({ + // @ts-ignore `editor` can be `undefined` when converting the document to HTML with the HTML utility + editor: options.editor, + overrideSuggestionOptions: suggestion, + extensionName: options.name, + char: suggestion.char + }) + ); +} +function getSuggestionFromChar(options, char) { + const suggestions = getSuggestions(options); + const suggestion = suggestions.find((s) => s.char === char); + if (suggestion) { + return suggestion; + } + if (suggestions.length) { + return suggestions[0]; + } + return null; +} +var Mention = Node3.create({ + name: "mention", + priority: 101, + addOptions() { + return { + HTMLAttributes: {}, + renderText({ node, suggestion }) { + var _a, _b; + return `${(_a = suggestion == null ? void 0 : suggestion.char) != null ? _a : "@"}${(_b = node.attrs.label) != null ? _b : node.attrs.id}`; + }, + deleteTriggerWithBackspace: false, + renderHTML({ options, node, suggestion }) { + var _a, _b; + return [ + "span", + mergeAttributes(this.HTMLAttributes, options.HTMLAttributes), + `${(_a = suggestion == null ? void 0 : suggestion.char) != null ? _a : "@"}${(_b = node.attrs.label) != null ? _b : node.attrs.id}` + ]; + }, + suggestions: [], + suggestion: {} + }; + }, + group: "inline", + inline: true, + selectable: false, + atom: true, + addAttributes() { + return { + id: { + default: null, + parseHTML: (element) => element.getAttribute("data-id"), + renderHTML: (attributes) => { + if (!attributes.id) { + return {}; + } + return { + "data-id": attributes.id + }; + } + }, + label: { + default: null, + parseHTML: (element) => element.getAttribute("data-label"), + renderHTML: (attributes) => { + if (!attributes.label) { + return {}; + } + return { + "data-label": attributes.label + }; + } + }, + // When there are multiple types of mentions, this attribute helps distinguish them + mentionSuggestionChar: { + default: "@", + parseHTML: (element) => element.getAttribute("data-mention-suggestion-char"), + renderHTML: (attributes) => { + return { + "data-mention-suggestion-char": attributes.mentionSuggestionChar + }; + } + } + }; + }, + parseHTML() { + return [ + { + tag: `span[data-type="${this.name}"]` + } + ]; + }, + renderHTML({ node, HTMLAttributes }) { + const suggestion = getSuggestionFromChar(this, node.attrs.mentionSuggestionChar); + if (this.options.renderLabel !== void 0) { + console.warn("renderLabel is deprecated use renderText and renderHTML instead"); + return [ + "span", + mergeAttributes({ "data-type": this.name }, this.options.HTMLAttributes, HTMLAttributes), + this.options.renderLabel({ + options: this.options, + node, + suggestion + }) + ]; + } + const mergedOptions = { ...this.options }; + mergedOptions.HTMLAttributes = mergeAttributes( + { "data-type": this.name }, + this.options.HTMLAttributes, + HTMLAttributes + ); + const html = this.options.renderHTML({ + options: mergedOptions, + node, + suggestion + }); + if (typeof html === "string") { + return ["span", mergeAttributes({ "data-type": this.name }, this.options.HTMLAttributes, HTMLAttributes), html]; + } + return html; + }, + ...createInlineMarkdownSpec({ + nodeName: "mention", + name: "@", + selfClosing: true, + allowedAttributes: ["id", "label", { name: "mentionSuggestionChar", skipIfDefault: "@" }], + parseAttributes: (attrString) => { + const attrs = {}; + const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g; + let match = regex.exec(attrString); + while (match !== null) { + const [, key, doubleQuoted, singleQuoted] = match; + const value = doubleQuoted != null ? doubleQuoted : singleQuoted; + attrs[key === "char" ? "mentionSuggestionChar" : key] = value; + match = regex.exec(attrString); + } + return attrs; + }, + serializeAttributes: (attrs) => { + return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => { + const serializedKey = key === "mentionSuggestionChar" ? "char" : key; + return `${serializedKey}="${value}"`; + }).join(" "); + } + }), + renderText({ node }) { + const args = { + options: this.options, + node, + suggestion: getSuggestionFromChar(this, node.attrs.mentionSuggestionChar) + }; + if (this.options.renderLabel !== void 0) { + console.warn("renderLabel is deprecated use renderText and renderHTML instead"); + return this.options.renderLabel(args); + } + return this.options.renderText(args); + }, + addKeyboardShortcuts() { + return { + Backspace: () => this.editor.commands.command(({ tr: tr2, state }) => { + let isMention = false; + const { selection } = state; + const { empty: empty2, anchor } = selection; + if (!empty2) { + return false; + } + let mentionNode = new Node(); + let mentionPos = 0; + state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => { + if (node.type.name === this.name) { + isMention = true; + mentionNode = node; + mentionPos = pos; + return false; + } + }); + if (isMention) { + tr2.insertText( + this.options.deleteTriggerWithBackspace ? "" : mentionNode.attrs.mentionSuggestionChar, + mentionPos, + mentionPos + mentionNode.nodeSize + ); + } + return isMention; + }) + }; + }, + addProseMirrorPlugins() { + return getSuggestions(this).map(Suggestion); + } +}); +var index_default = Mention; +export { + EditorContent as E, + React as R, + reactDomExports as a, + index_default$5 as b, + commonjsGlobal as c, + index_default$2 as d, + requireReact as e, + requireReactDom as f, + getDefaultExportFromCjs as g, + ReactRenderer as h, + index_default$3 as i, + jsxRuntimeExports as j, + index_default$4 as k, + index_default$1 as l, + index_default as m, + reactExports as r, + useEditor as u +}; diff --git a/bootstrap/ssr/assets/vendor-tooltip-CIQaDNlG.js b/bootstrap/ssr/assets/vendor-tooltip-CIQaDNlG.js new file mode 100644 index 00000000..a405ce9a --- /dev/null +++ b/bootstrap/ssr/assets/vendor-tooltip-CIQaDNlG.js @@ -0,0 +1,2627 @@ +var top = "top"; +var bottom = "bottom"; +var right = "right"; +var left = "left"; +var auto = "auto"; +var basePlacements = [top, bottom, right, left]; +var start = "start"; +var end = "end"; +var clippingParents = "clippingParents"; +var viewport = "viewport"; +var popper = "popper"; +var reference = "reference"; +var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) { + return acc.concat([placement + "-" + start, placement + "-" + end]); +}, []); +var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) { + return acc.concat([placement, placement + "-" + start, placement + "-" + end]); +}, []); +var beforeRead = "beforeRead"; +var read = "read"; +var afterRead = "afterRead"; +var beforeMain = "beforeMain"; +var main = "main"; +var afterMain = "afterMain"; +var beforeWrite = "beforeWrite"; +var write = "write"; +var afterWrite = "afterWrite"; +var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; +function getNodeName(element) { + return element ? (element.nodeName || "").toLowerCase() : null; +} +function getWindow(node) { + if (node == null) { + return window; + } + if (node.toString() !== "[object Window]") { + var ownerDocument = node.ownerDocument; + return ownerDocument ? ownerDocument.defaultView || window : window; + } + return node; +} +function isElement$1(node) { + var OwnElement = getWindow(node).Element; + return node instanceof OwnElement || node instanceof Element; +} +function isHTMLElement(node) { + var OwnElement = getWindow(node).HTMLElement; + return node instanceof OwnElement || node instanceof HTMLElement; +} +function isShadowRoot(node) { + if (typeof ShadowRoot === "undefined") { + return false; + } + var OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; +} +function applyStyles(_ref) { + var state = _ref.state; + Object.keys(state.elements).forEach(function(name) { + var style = state.styles[name] || {}; + var attributes = state.attributes[name] || {}; + var element = state.elements[name]; + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + Object.assign(element.style, style); + Object.keys(attributes).forEach(function(name2) { + var value = attributes[name2]; + if (value === false) { + element.removeAttribute(name2); + } else { + element.setAttribute(name2, value === true ? "" : value); + } + }); + }); +} +function effect$2(_ref2) { + var state = _ref2.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: "0", + top: "0", + margin: "0" + }, + arrow: { + position: "absolute" + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); + } + return function() { + Object.keys(state.elements).forEach(function(name) { + var element = state.elements[name]; + var attributes = state.attributes[name] || {}; + var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); + var style = styleProperties.reduce(function(style2, property) { + style2[property] = ""; + return style2; + }, {}); + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + Object.assign(element.style, style); + Object.keys(attributes).forEach(function(attribute) { + element.removeAttribute(attribute); + }); + }); + }; +} +const applyStyles$1 = { + name: "applyStyles", + enabled: true, + phase: "write", + fn: applyStyles, + effect: effect$2, + requires: ["computeStyles"] +}; +function getBasePlacement$1(placement) { + return placement.split("-")[0]; +} +var max = Math.max; +var min = Math.min; +var round = Math.round; +function getUAString() { + var uaData = navigator.userAgentData; + if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { + return uaData.brands.map(function(item) { + return item.brand + "/" + item.version; + }).join(" "); + } + return navigator.userAgent; +} +function isLayoutViewport() { + return !/^((?!chrome|android).)*safari/i.test(getUAString()); +} +function getBoundingClientRect(element, includeScale, isFixedStrategy) { + if (includeScale === void 0) { + includeScale = false; + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + var clientRect = element.getBoundingClientRect(); + var scaleX = 1; + var scaleY = 1; + if (includeScale && isHTMLElement(element)) { + scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; + scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; + } + var _ref = isElement$1(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport; + var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; + var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; + var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; + var width = clientRect.width / scaleX; + var height = clientRect.height / scaleY; + return { + width, + height, + top: y, + right: x + width, + bottom: y + height, + left: x, + x, + y + }; +} +function getLayoutRect(element) { + var clientRect = getBoundingClientRect(element); + var width = element.offsetWidth; + var height = element.offsetHeight; + if (Math.abs(clientRect.width - width) <= 1) { + width = clientRect.width; + } + if (Math.abs(clientRect.height - height) <= 1) { + height = clientRect.height; + } + return { + x: element.offsetLeft, + y: element.offsetTop, + width, + height + }; +} +function contains(parent, child) { + var rootNode = child.getRootNode && child.getRootNode(); + if (parent.contains(child)) { + return true; + } else if (rootNode && isShadowRoot(rootNode)) { + var next = child; + do { + if (next && parent.isSameNode(next)) { + return true; + } + next = next.parentNode || next.host; + } while (next); + } + return false; +} +function getComputedStyle(element) { + return getWindow(element).getComputedStyle(element); +} +function isTableElement(element) { + return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0; +} +function getDocumentElement(element) { + return ((isElement$1(element) ? element.ownerDocument : ( + // $FlowFixMe[prop-missing] + element.document + )) || window.document).documentElement; +} +function getParentNode(element) { + if (getNodeName(element) === "html") { + return element; + } + return ( + // this is a quicker (but less type safe) way to save quite some bytes from the bundle + // $FlowFixMe[incompatible-return] + // $FlowFixMe[prop-missing] + element.assignedSlot || // step into the shadow DOM of the parent of a slotted node + element.parentNode || // DOM Element detected + (isShadowRoot(element) ? element.host : null) || // ShadowRoot detected + // $FlowFixMe[incompatible-call]: HTMLElement is a Node + getDocumentElement(element) + ); +} +function getTrueOffsetParent(element) { + if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 + getComputedStyle(element).position === "fixed") { + return null; + } + return element.offsetParent; +} +function getContainingBlock(element) { + var isFirefox = /firefox/i.test(getUAString()); + var isIE = /Trident/i.test(getUAString()); + if (isIE && isHTMLElement(element)) { + var elementCss = getComputedStyle(element); + if (elementCss.position === "fixed") { + return null; + } + } + var currentNode = getParentNode(element); + if (isShadowRoot(currentNode)) { + currentNode = currentNode.host; + } + while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) { + var css = getComputedStyle(currentNode); + if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") { + return currentNode; + } else { + currentNode = currentNode.parentNode; + } + } + return null; +} +function getOffsetParent(element) { + var window2 = getWindow(element); + var offsetParent = getTrueOffsetParent(element); + while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") { + offsetParent = getTrueOffsetParent(offsetParent); + } + if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) { + return window2; + } + return offsetParent || getContainingBlock(element) || window2; +} +function getMainAxisFromPlacement(placement) { + return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y"; +} +function within(min$1, value, max$1) { + return max(min$1, min(value, max$1)); +} +function withinMaxClamp(min2, value, max2) { + var v = within(min2, value, max2); + return v > max2 ? max2 : v; +} +function getFreshSideObject() { + return { + top: 0, + right: 0, + bottom: 0, + left: 0 + }; +} +function mergePaddingObject(paddingObject) { + return Object.assign({}, getFreshSideObject(), paddingObject); +} +function expandToHashMap(value, keys) { + return keys.reduce(function(hashMap, key) { + hashMap[key] = value; + return hashMap; + }, {}); +} +var toPaddingObject = function toPaddingObject2(padding, state) { + padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, { + placement: state.placement + })) : padding; + return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); +}; +function arrow(_ref) { + var _state$modifiersData$; + var state = _ref.state, name = _ref.name, options = _ref.options; + var arrowElement = state.elements.arrow; + var popperOffsets2 = state.modifiersData.popperOffsets; + var basePlacement = getBasePlacement$1(state.placement); + var axis = getMainAxisFromPlacement(basePlacement); + var isVertical = [left, right].indexOf(basePlacement) >= 0; + var len = isVertical ? "height" : "width"; + if (!arrowElement || !popperOffsets2) { + return; + } + var paddingObject = toPaddingObject(options.padding, state); + var arrowRect = getLayoutRect(arrowElement); + var minProp = axis === "y" ? top : left; + var maxProp = axis === "y" ? bottom : right; + var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len]; + var startDiff = popperOffsets2[axis] - state.rects.reference[axis]; + var arrowOffsetParent = getOffsetParent(arrowElement); + var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; + var centerToReference = endDiff / 2 - startDiff / 2; + var min2 = paddingObject[minProp]; + var max2 = clientSize - arrowRect[len] - paddingObject[maxProp]; + var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; + var offset2 = within(min2, center, max2); + var axisProp = axis; + state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$); +} +function effect$1(_ref2) { + var state = _ref2.state, options = _ref2.options; + var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element; + if (arrowElement == null) { + return; + } + if (typeof arrowElement === "string") { + arrowElement = state.elements.popper.querySelector(arrowElement); + if (!arrowElement) { + return; + } + } + if (!contains(state.elements.popper, arrowElement)) { + return; + } + state.elements.arrow = arrowElement; +} +const arrow$1 = { + name: "arrow", + enabled: true, + phase: "main", + fn: arrow, + effect: effect$1, + requires: ["popperOffsets"], + requiresIfExists: ["preventOverflow"] +}; +function getVariation(placement) { + return placement.split("-")[1]; +} +var unsetSides = { + top: "auto", + right: "auto", + bottom: "auto", + left: "auto" +}; +function roundOffsetsByDPR(_ref, win) { + var x = _ref.x, y = _ref.y; + var dpr = win.devicePixelRatio || 1; + return { + x: round(x * dpr) / dpr || 0, + y: round(y * dpr) / dpr || 0 + }; +} +function mapToStyles(_ref2) { + var _Object$assign2; + var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed; + var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y; + var _ref3 = typeof roundOffsets === "function" ? roundOffsets({ + x, + y + }) : { + x, + y + }; + x = _ref3.x; + y = _ref3.y; + var hasX = offsets.hasOwnProperty("x"); + var hasY = offsets.hasOwnProperty("y"); + var sideX = left; + var sideY = top; + var win = window; + if (adaptive) { + var offsetParent = getOffsetParent(popper2); + var heightProp = "clientHeight"; + var widthProp = "clientWidth"; + if (offsetParent === getWindow(popper2)) { + offsetParent = getDocumentElement(popper2); + if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") { + heightProp = "scrollHeight"; + widthProp = "scrollWidth"; + } + } + offsetParent = offsetParent; + if (placement === top || (placement === left || placement === right) && variation === end) { + sideY = bottom; + var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : ( + // $FlowFixMe[prop-missing] + offsetParent[heightProp] + ); + y -= offsetY - popperRect.height; + y *= gpuAcceleration ? 1 : -1; + } + if (placement === left || (placement === top || placement === bottom) && variation === end) { + sideX = right; + var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : ( + // $FlowFixMe[prop-missing] + offsetParent[widthProp] + ); + x -= offsetX - popperRect.width; + x *= gpuAcceleration ? 1 : -1; + } + } + var commonStyles = Object.assign({ + position + }, adaptive && unsetSides); + var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ + x, + y + }, getWindow(popper2)) : { + x, + y + }; + x = _ref4.x; + y = _ref4.y; + if (gpuAcceleration) { + var _Object$assign; + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + } + return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2)); +} +function computeStyles(_ref5) { + var state = _ref5.state, options = _ref5.options; + var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; + var commonStyles = { + placement: getBasePlacement$1(state.placement), + variation: getVariation(state.placement), + popper: state.elements.popper, + popperRect: state.rects.popper, + gpuAcceleration, + isFixed: state.options.strategy === "fixed" + }; + if (state.modifiersData.popperOffsets != null) { + state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.popperOffsets, + position: state.options.strategy, + adaptive, + roundOffsets + }))); + } + if (state.modifiersData.arrow != null) { + state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.arrow, + position: "absolute", + adaptive: false, + roundOffsets + }))); + } + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-placement": state.placement + }); +} +const computeStyles$1 = { + name: "computeStyles", + enabled: true, + phase: "beforeWrite", + fn: computeStyles, + data: {} +}; +var passive = { + passive: true +}; +function effect(_ref) { + var state = _ref.state, instance = _ref.instance, options = _ref.options; + var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize; + var window2 = getWindow(state.elements.popper); + var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.addEventListener("scroll", instance.update, passive); + }); + } + if (resize) { + window2.addEventListener("resize", instance.update, passive); + } + return function() { + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.removeEventListener("scroll", instance.update, passive); + }); + } + if (resize) { + window2.removeEventListener("resize", instance.update, passive); + } + }; +} +const eventListeners = { + name: "eventListeners", + enabled: true, + phase: "write", + fn: function fn() { + }, + effect, + data: {} +}; +var hash$1 = { + left: "right", + right: "left", + bottom: "top", + top: "bottom" +}; +function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, function(matched) { + return hash$1[matched]; + }); +} +var hash = { + start: "end", + end: "start" +}; +function getOppositeVariationPlacement(placement) { + return placement.replace(/start|end/g, function(matched) { + return hash[matched]; + }); +} +function getWindowScroll(node) { + var win = getWindow(node); + var scrollLeft = win.pageXOffset; + var scrollTop = win.pageYOffset; + return { + scrollLeft, + scrollTop + }; +} +function getWindowScrollBarX(element) { + return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; +} +function getViewportRect(element, strategy) { + var win = getWindow(element); + var html = getDocumentElement(element); + var visualViewport = win.visualViewport; + var width = html.clientWidth; + var height = html.clientHeight; + var x = 0; + var y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + var layoutViewport = isLayoutViewport(); + if (layoutViewport || !layoutViewport && strategy === "fixed") { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + return { + width, + height, + x: x + getWindowScrollBarX(element), + y + }; +} +function getDocumentRect(element) { + var _element$ownerDocumen; + var html = getDocumentElement(element); + var winScroll = getWindowScroll(element); + var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; + var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); + var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); + var x = -winScroll.scrollLeft + getWindowScrollBarX(element); + var y = -winScroll.scrollTop; + if (getComputedStyle(body || html).direction === "rtl") { + x += max(html.clientWidth, body ? body.clientWidth : 0) - width; + } + return { + width, + height, + x, + y + }; +} +function isScrollParent(element) { + var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; + return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); +} +function getScrollParent(node) { + if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) { + return node.ownerDocument.body; + } + if (isHTMLElement(node) && isScrollParent(node)) { + return node; + } + return getScrollParent(getParentNode(node)); +} +function listScrollParents(element, list) { + var _element$ownerDocumen; + if (list === void 0) { + list = []; + } + var scrollParent = getScrollParent(element); + var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); + var win = getWindow(scrollParent); + var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; + var updatedList = list.concat(target); + return isBody ? updatedList : ( + // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here + updatedList.concat(listScrollParents(getParentNode(target))) + ); +} +function rectToClientRect(rect) { + return Object.assign({}, rect, { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }); +} +function getInnerBoundingClientRect(element, strategy) { + var rect = getBoundingClientRect(element, false, strategy === "fixed"); + rect.top = rect.top + element.clientTop; + rect.left = rect.left + element.clientLeft; + rect.bottom = rect.top + element.clientHeight; + rect.right = rect.left + element.clientWidth; + rect.width = element.clientWidth; + rect.height = element.clientHeight; + rect.x = rect.left; + rect.y = rect.top; + return rect; +} +function getClientRectFromMixedType(element, clippingParent, strategy) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement$1(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); +} +function getClippingParents(element) { + var clippingParents2 = listScrollParents(getParentNode(element)); + var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0; + var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; + if (!isElement$1(clipperElement)) { + return []; + } + return clippingParents2.filter(function(clippingParent) { + return isElement$1(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body"; + }); +} +function getClippingRect(element, boundary, rootBoundary, strategy) { + var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary); + var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]); + var firstClippingParent = clippingParents2[0]; + var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) { + var rect = getClientRectFromMixedType(element, clippingParent, strategy); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromMixedType(element, firstClippingParent, strategy)); + clippingRect.width = clippingRect.right - clippingRect.left; + clippingRect.height = clippingRect.bottom - clippingRect.top; + clippingRect.x = clippingRect.left; + clippingRect.y = clippingRect.top; + return clippingRect; +} +function computeOffsets(_ref) { + var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement; + var basePlacement = placement ? getBasePlacement$1(placement) : null; + var variation = placement ? getVariation(placement) : null; + var commonX = reference2.x + reference2.width / 2 - element.width / 2; + var commonY = reference2.y + reference2.height / 2 - element.height / 2; + var offsets; + switch (basePlacement) { + case top: + offsets = { + x: commonX, + y: reference2.y - element.height + }; + break; + case bottom: + offsets = { + x: commonX, + y: reference2.y + reference2.height + }; + break; + case right: + offsets = { + x: reference2.x + reference2.width, + y: commonY + }; + break; + case left: + offsets = { + x: reference2.x - element.width, + y: commonY + }; + break; + default: + offsets = { + x: reference2.x, + y: reference2.y + }; + } + var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; + if (mainAxis != null) { + var len = mainAxis === "y" ? "height" : "width"; + switch (variation) { + case start: + offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2); + break; + case end: + offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2); + break; + } + } + return offsets; +} +function detectOverflow(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; + var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); + var altContext = elementContext === popper ? reference : popper; + var popperRect = state.rects.popper; + var element = state.elements[altBoundary ? altContext : elementContext]; + var clippingClientRect = getClippingRect(isElement$1(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); + var referenceClientRect = getBoundingClientRect(state.elements.reference); + var popperOffsets2 = computeOffsets({ + reference: referenceClientRect, + element: popperRect, + placement + }); + var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2)); + var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; + var overflowOffsets = { + top: clippingClientRect.top - elementClientRect.top + paddingObject.top, + bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, + left: clippingClientRect.left - elementClientRect.left + paddingObject.left, + right: elementClientRect.right - clippingClientRect.right + paddingObject.right + }; + var offsetData = state.modifiersData.offset; + if (elementContext === popper && offsetData) { + var offset2 = offsetData[placement]; + Object.keys(overflowOffsets).forEach(function(key) { + var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; + var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x"; + overflowOffsets[key] += offset2[axis] * multiply; + }); + } + return overflowOffsets; +} +function computeAutoPlacement(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; + var variation = getVariation(placement); + var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) { + return getVariation(placement2) === variation; + }) : basePlacements; + var allowedPlacements = placements$1.filter(function(placement2) { + return allowedAutoPlacements.indexOf(placement2) >= 0; + }); + if (allowedPlacements.length === 0) { + allowedPlacements = placements$1; + } + var overflows = allowedPlacements.reduce(function(acc, placement2) { + acc[placement2] = detectOverflow(state, { + placement: placement2, + boundary, + rootBoundary, + padding + })[getBasePlacement$1(placement2)]; + return acc; + }, {}); + return Object.keys(overflows).sort(function(a, b) { + return overflows[a] - overflows[b]; + }); +} +function getExpandedFallbackPlacements(placement) { + if (getBasePlacement$1(placement) === auto) { + return []; + } + var oppositePlacement = getOppositePlacement(placement); + return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; +} +function flip(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + if (state.modifiersData[name]._skip) { + return; + } + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements; + var preferredPlacement = state.options.placement; + var basePlacement = getBasePlacement$1(preferredPlacement); + var isBasePlacement = basePlacement === preferredPlacement; + var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); + var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) { + return acc.concat(getBasePlacement$1(placement2) === auto ? computeAutoPlacement(state, { + placement: placement2, + boundary, + rootBoundary, + padding, + flipVariations, + allowedAutoPlacements + }) : placement2); + }, []); + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var checksMap = /* @__PURE__ */ new Map(); + var makeFallbackChecks = true; + var firstFittingPlacement = placements2[0]; + for (var i = 0; i < placements2.length; i++) { + var placement = placements2[i]; + var _basePlacement = getBasePlacement$1(placement); + var isStartVariation = getVariation(placement) === start; + var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; + var len = isVertical ? "width" : "height"; + var overflow = detectOverflow(state, { + placement, + boundary, + rootBoundary, + altBoundary, + padding + }); + var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; + if (referenceRect[len] > popperRect[len]) { + mainVariationSide = getOppositePlacement(mainVariationSide); + } + var altVariationSide = getOppositePlacement(mainVariationSide); + var checks = []; + if (checkMainAxis) { + checks.push(overflow[_basePlacement] <= 0); + } + if (checkAltAxis) { + checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); + } + if (checks.every(function(check) { + return check; + })) { + firstFittingPlacement = placement; + makeFallbackChecks = false; + break; + } + checksMap.set(placement, checks); + } + if (makeFallbackChecks) { + var numberOfChecks = flipVariations ? 3 : 1; + var _loop = function _loop2(_i2) { + var fittingPlacement = placements2.find(function(placement2) { + var checks2 = checksMap.get(placement2); + if (checks2) { + return checks2.slice(0, _i2).every(function(check) { + return check; + }); + } + }); + if (fittingPlacement) { + firstFittingPlacement = fittingPlacement; + return "break"; + } + }; + for (var _i = numberOfChecks; _i > 0; _i--) { + var _ret = _loop(_i); + if (_ret === "break") break; + } + } + if (state.placement !== firstFittingPlacement) { + state.modifiersData[name]._skip = true; + state.placement = firstFittingPlacement; + state.reset = true; + } +} +const flip$1 = { + name: "flip", + enabled: true, + phase: "main", + fn: flip, + requiresIfExists: ["offset"], + data: { + _skip: false + } +}; +function getSideOffsets(overflow, rect, preventedOffsets) { + if (preventedOffsets === void 0) { + preventedOffsets = { + x: 0, + y: 0 + }; + } + return { + top: overflow.top - rect.height - preventedOffsets.y, + right: overflow.right - rect.width + preventedOffsets.x, + bottom: overflow.bottom - rect.height + preventedOffsets.y, + left: overflow.left - rect.width - preventedOffsets.x + }; +} +function isAnySideFullyClipped(overflow) { + return [top, right, bottom, left].some(function(side) { + return overflow[side] >= 0; + }); +} +function hide(_ref) { + var state = _ref.state, name = _ref.name; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var preventedOffsets = state.modifiersData.preventOverflow; + var referenceOverflow = detectOverflow(state, { + elementContext: "reference" + }); + var popperAltOverflow = detectOverflow(state, { + altBoundary: true + }); + var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); + var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); + var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); + var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); + state.modifiersData[name] = { + referenceClippingOffsets, + popperEscapeOffsets, + isReferenceHidden, + hasPopperEscaped + }; + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-reference-hidden": isReferenceHidden, + "data-popper-escaped": hasPopperEscaped + }); +} +const hide$1 = { + name: "hide", + enabled: true, + phase: "main", + requiresIfExists: ["preventOverflow"], + fn: hide +}; +function distanceAndSkiddingToXY(placement, rects, offset2) { + var basePlacement = getBasePlacement$1(placement); + var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; + var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, { + placement + })) : offset2, skidding = _ref[0], distance = _ref[1]; + skidding = skidding || 0; + distance = (distance || 0) * invertDistance; + return [left, right].indexOf(basePlacement) >= 0 ? { + x: distance, + y: skidding + } : { + x: skidding, + y: distance + }; +} +function offset(_ref2) { + var state = _ref2.state, options = _ref2.options, name = _ref2.name; + var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset; + var data = placements.reduce(function(acc, placement) { + acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2); + return acc; + }, {}); + var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y; + if (state.modifiersData.popperOffsets != null) { + state.modifiersData.popperOffsets.x += x; + state.modifiersData.popperOffsets.y += y; + } + state.modifiersData[name] = data; +} +const offset$1 = { + name: "offset", + enabled: true, + phase: "main", + requires: ["popperOffsets"], + fn: offset +}; +function popperOffsets(_ref) { + var state = _ref.state, name = _ref.name; + state.modifiersData[name] = computeOffsets({ + reference: state.rects.reference, + element: state.rects.popper, + placement: state.placement + }); +} +const popperOffsets$1 = { + name: "popperOffsets", + enabled: true, + phase: "read", + fn: popperOffsets, + data: {} +}; +function getAltAxis(axis) { + return axis === "x" ? "y" : "x"; +} +function preventOverflow(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; + var overflow = detectOverflow(state, { + boundary, + rootBoundary, + padding, + altBoundary + }); + var basePlacement = getBasePlacement$1(state.placement); + var variation = getVariation(state.placement); + var isBasePlacement = !variation; + var mainAxis = getMainAxisFromPlacement(basePlacement); + var altAxis = getAltAxis(mainAxis); + var popperOffsets2 = state.modifiersData.popperOffsets; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, { + placement: state.placement + })) : tetherOffset; + var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? { + mainAxis: tetherOffsetValue, + altAxis: tetherOffsetValue + } : Object.assign({ + mainAxis: 0, + altAxis: 0 + }, tetherOffsetValue); + var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; + var data = { + x: 0, + y: 0 + }; + if (!popperOffsets2) { + return; + } + if (checkMainAxis) { + var _offsetModifierState$; + var mainSide = mainAxis === "y" ? top : left; + var altSide = mainAxis === "y" ? bottom : right; + var len = mainAxis === "y" ? "height" : "width"; + var offset2 = popperOffsets2[mainAxis]; + var min$1 = offset2 + overflow[mainSide]; + var max$1 = offset2 - overflow[altSide]; + var additive = tether ? -popperRect[len] / 2 : 0; + var minLen = variation === start ? referenceRect[len] : popperRect[len]; + var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; + var arrowElement = state.elements.arrow; + var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { + width: 0, + height: 0 + }; + var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject(); + var arrowPaddingMin = arrowPaddingObject[mainSide]; + var arrowPaddingMax = arrowPaddingObject[altSide]; + var arrowLen = within(0, referenceRect[len], arrowRect[len]); + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; + var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); + var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; + var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; + var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset; + var tetherMax = offset2 + maxOffset - offsetModifierValue; + var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset2, tether ? max(max$1, tetherMax) : max$1); + popperOffsets2[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset2; + } + if (checkAltAxis) { + var _offsetModifierState$2; + var _mainSide = mainAxis === "x" ? top : left; + var _altSide = mainAxis === "x" ? bottom : right; + var _offset = popperOffsets2[altAxis]; + var _len = altAxis === "y" ? "height" : "width"; + var _min = _offset + overflow[_mainSide]; + var _max = _offset - overflow[_altSide]; + var isOriginSide = [top, left].indexOf(basePlacement) !== -1; + var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; + var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; + var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; + var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); + popperOffsets2[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; + } + state.modifiersData[name] = data; +} +const preventOverflow$1 = { + name: "preventOverflow", + enabled: true, + phase: "main", + fn: preventOverflow, + requiresIfExists: ["offset"] +}; +function getHTMLElementScroll(element) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop + }; +} +function getNodeScroll(node) { + if (node === getWindow(node) || !isHTMLElement(node)) { + return getWindowScroll(node); + } else { + return getHTMLElementScroll(node); + } +} +function isElementScaled(element) { + var rect = element.getBoundingClientRect(); + var scaleX = round(rect.width) / element.offsetWidth || 1; + var scaleY = round(rect.height) / element.offsetHeight || 1; + return scaleX !== 1 || scaleY !== 1; +} +function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { + if (isFixed === void 0) { + isFixed = false; + } + var isOffsetParentAnElement = isHTMLElement(offsetParent); + var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); + var documentElement = getDocumentElement(offsetParent); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); + var scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + var offsets = { + x: 0, + y: 0 + }; + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== "body" || // https://github.com/popperjs/popper-core/issues/1078 + isScrollParent(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + offsets = getBoundingClientRect(offsetParent, true); + offsets.x += offsetParent.clientLeft; + offsets.y += offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; +} +function order(modifiers) { + var map = /* @__PURE__ */ new Map(); + var visited = /* @__PURE__ */ new Set(); + var result = []; + modifiers.forEach(function(modifier) { + map.set(modifier.name, modifier); + }); + function sort(modifier) { + visited.add(modifier.name); + var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); + requires.forEach(function(dep) { + if (!visited.has(dep)) { + var depModifier = map.get(dep); + if (depModifier) { + sort(depModifier); + } + } + }); + result.push(modifier); + } + modifiers.forEach(function(modifier) { + if (!visited.has(modifier.name)) { + sort(modifier); + } + }); + return result; +} +function orderModifiers(modifiers) { + var orderedModifiers = order(modifiers); + return modifierPhases.reduce(function(acc, phase) { + return acc.concat(orderedModifiers.filter(function(modifier) { + return modifier.phase === phase; + })); + }, []); +} +function debounce$1(fn2) { + var pending; + return function() { + if (!pending) { + pending = new Promise(function(resolve) { + Promise.resolve().then(function() { + pending = void 0; + resolve(fn2()); + }); + }); + } + return pending; + }; +} +function mergeByName(modifiers) { + var merged = modifiers.reduce(function(merged2, current) { + var existing = merged2[current.name]; + merged2[current.name] = existing ? Object.assign({}, existing, current, { + options: Object.assign({}, existing.options, current.options), + data: Object.assign({}, existing.data, current.data) + }) : current; + return merged2; + }, {}); + return Object.keys(merged).map(function(key) { + return merged[key]; + }); +} +var DEFAULT_OPTIONS = { + placement: "bottom", + modifiers: [], + strategy: "absolute" +}; +function areValidElements() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return !args.some(function(element) { + return !(element && typeof element.getBoundingClientRect === "function"); + }); +} +function popperGenerator(generatorOptions) { + if (generatorOptions === void 0) { + generatorOptions = {}; + } + var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; + return function createPopper2(reference2, popper2, options) { + if (options === void 0) { + options = defaultOptions; + } + var state = { + placement: "bottom", + orderedModifiers: [], + options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), + modifiersData: {}, + elements: { + reference: reference2, + popper: popper2 + }, + attributes: {}, + styles: {} + }; + var effectCleanupFns = []; + var isDestroyed = false; + var instance = { + state, + setOptions: function setOptions(setOptionsAction) { + var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction; + cleanupModifierEffects(); + state.options = Object.assign({}, defaultOptions, state.options, options2); + state.scrollParents = { + reference: isElement$1(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [], + popper: listScrollParents(popper2) + }; + var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers))); + state.orderedModifiers = orderedModifiers.filter(function(m) { + return m.enabled; + }); + runModifierEffects(); + return instance.update(); + }, + // Sync update – it will always be executed, even if not necessary. This + // is useful for low frequency updates where sync behavior simplifies the + // logic. + // For high frequency updates (e.g. `resize` and `scroll` events), always + // prefer the async Popper#update method + forceUpdate: function forceUpdate() { + if (isDestroyed) { + return; + } + var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper; + if (!areValidElements(reference3, popper3)) { + return; + } + state.rects = { + reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"), + popper: getLayoutRect(popper3) + }; + state.reset = false; + state.placement = state.options.placement; + state.orderedModifiers.forEach(function(modifier) { + return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); + }); + for (var index = 0; index < state.orderedModifiers.length; index++) { + if (state.reset === true) { + state.reset = false; + index = -1; + continue; + } + var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; + if (typeof fn2 === "function") { + state = fn2({ + state, + options: _options, + name, + instance + }) || state; + } + } + }, + // Async and optimistically optimized update – it will not be executed if + // not necessary (debounced to run at most once-per-tick) + update: debounce$1(function() { + return new Promise(function(resolve) { + instance.forceUpdate(); + resolve(state); + }); + }), + destroy: function destroy() { + cleanupModifierEffects(); + isDestroyed = true; + } + }; + if (!areValidElements(reference2, popper2)) { + return instance; + } + instance.setOptions(options).then(function(state2) { + if (!isDestroyed && options.onFirstUpdate) { + options.onFirstUpdate(state2); + } + }); + function runModifierEffects() { + state.orderedModifiers.forEach(function(_ref) { + var name = _ref.name, _ref$options = _ref.options, options2 = _ref$options === void 0 ? {} : _ref$options, effect3 = _ref.effect; + if (typeof effect3 === "function") { + var cleanupFn = effect3({ + state, + name, + instance, + options: options2 + }); + var noopFn = function noopFn2() { + }; + effectCleanupFns.push(cleanupFn || noopFn); + } + }); + } + function cleanupModifierEffects() { + effectCleanupFns.forEach(function(fn2) { + return fn2(); + }); + effectCleanupFns = []; + } + return instance; + }; +} +var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1]; +var createPopper = /* @__PURE__ */ popperGenerator({ + defaultModifiers +}); +var BOX_CLASS = "tippy-box"; +var CONTENT_CLASS = "tippy-content"; +var BACKDROP_CLASS = "tippy-backdrop"; +var ARROW_CLASS = "tippy-arrow"; +var SVG_ARROW_CLASS = "tippy-svg-arrow"; +var TOUCH_OPTIONS = { + passive: true, + capture: true +}; +var TIPPY_DEFAULT_APPEND_TO = function TIPPY_DEFAULT_APPEND_TO2() { + return document.body; +}; +function hasOwnProperty(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} +function getValueAtIndexOrReturn(value, index, defaultValue) { + if (Array.isArray(value)) { + var v = value[index]; + return v == null ? Array.isArray(defaultValue) ? defaultValue[index] : defaultValue : v; + } + return value; +} +function isType(value, type) { + var str = {}.toString.call(value); + return str.indexOf("[object") === 0 && str.indexOf(type + "]") > -1; +} +function invokeWithArgsOrReturn(value, args) { + return typeof value === "function" ? value.apply(void 0, args) : value; +} +function debounce(fn2, ms) { + if (ms === 0) { + return fn2; + } + var timeout; + return function(arg) { + clearTimeout(timeout); + timeout = setTimeout(function() { + fn2(arg); + }, ms); + }; +} +function removeProperties(obj, keys) { + var clone = Object.assign({}, obj); + keys.forEach(function(key) { + delete clone[key]; + }); + return clone; +} +function splitBySpaces(value) { + return value.split(/\s+/).filter(Boolean); +} +function normalizeToArray(value) { + return [].concat(value); +} +function pushIfUnique(arr, value) { + if (arr.indexOf(value) === -1) { + arr.push(value); + } +} +function unique(arr) { + return arr.filter(function(item, index) { + return arr.indexOf(item) === index; + }); +} +function getBasePlacement(placement) { + return placement.split("-")[0]; +} +function arrayFrom(value) { + return [].slice.call(value); +} +function removeUndefinedProps(obj) { + return Object.keys(obj).reduce(function(acc, key) { + if (obj[key] !== void 0) { + acc[key] = obj[key]; + } + return acc; + }, {}); +} +function div() { + return document.createElement("div"); +} +function isElement(value) { + return ["Element", "Fragment"].some(function(type) { + return isType(value, type); + }); +} +function isNodeList(value) { + return isType(value, "NodeList"); +} +function isMouseEvent(value) { + return isType(value, "MouseEvent"); +} +function isReferenceElement(value) { + return !!(value && value._tippy && value._tippy.reference === value); +} +function getArrayOfElements(value) { + if (isElement(value)) { + return [value]; + } + if (isNodeList(value)) { + return arrayFrom(value); + } + if (Array.isArray(value)) { + return value; + } + return arrayFrom(document.querySelectorAll(value)); +} +function setTransitionDuration(els, value) { + els.forEach(function(el) { + if (el) { + el.style.transitionDuration = value + "ms"; + } + }); +} +function setVisibilityState(els, state) { + els.forEach(function(el) { + if (el) { + el.setAttribute("data-state", state); + } + }); +} +function getOwnerDocument(elementOrElements) { + var _element$ownerDocumen; + var _normalizeToArray = normalizeToArray(elementOrElements), element = _normalizeToArray[0]; + return element != null && (_element$ownerDocumen = element.ownerDocument) != null && _element$ownerDocumen.body ? element.ownerDocument : document; +} +function isCursorOutsideInteractiveBorder(popperTreeData, event) { + var clientX = event.clientX, clientY = event.clientY; + return popperTreeData.every(function(_ref) { + var popperRect = _ref.popperRect, popperState = _ref.popperState, props = _ref.props; + var interactiveBorder = props.interactiveBorder; + var basePlacement = getBasePlacement(popperState.placement); + var offsetData = popperState.modifiersData.offset; + if (!offsetData) { + return true; + } + var topDistance = basePlacement === "bottom" ? offsetData.top.y : 0; + var bottomDistance = basePlacement === "top" ? offsetData.bottom.y : 0; + var leftDistance = basePlacement === "right" ? offsetData.left.x : 0; + var rightDistance = basePlacement === "left" ? offsetData.right.x : 0; + var exceedsTop = popperRect.top - clientY + topDistance > interactiveBorder; + var exceedsBottom = clientY - popperRect.bottom - bottomDistance > interactiveBorder; + var exceedsLeft = popperRect.left - clientX + leftDistance > interactiveBorder; + var exceedsRight = clientX - popperRect.right - rightDistance > interactiveBorder; + return exceedsTop || exceedsBottom || exceedsLeft || exceedsRight; + }); +} +function updateTransitionEndListener(box, action, listener) { + var method = action + "EventListener"; + ["transitionend", "webkitTransitionEnd"].forEach(function(event) { + box[method](event, listener); + }); +} +function actualContains(parent, child) { + var target = child; + while (target) { + var _target$getRootNode; + if (parent.contains(target)) { + return true; + } + target = target.getRootNode == null ? void 0 : (_target$getRootNode = target.getRootNode()) == null ? void 0 : _target$getRootNode.host; + } + return false; +} +var currentInput = { + isTouch: false +}; +var lastMouseMoveTime = 0; +function onDocumentTouchStart() { + if (currentInput.isTouch) { + return; + } + currentInput.isTouch = true; + if (window.performance) { + document.addEventListener("mousemove", onDocumentMouseMove); + } +} +function onDocumentMouseMove() { + var now = performance.now(); + if (now - lastMouseMoveTime < 20) { + currentInput.isTouch = false; + document.removeEventListener("mousemove", onDocumentMouseMove); + } + lastMouseMoveTime = now; +} +function onWindowBlur() { + var activeElement = document.activeElement; + if (isReferenceElement(activeElement)) { + var instance = activeElement._tippy; + if (activeElement.blur && !instance.state.isVisible) { + activeElement.blur(); + } + } +} +function bindGlobalEventListeners() { + document.addEventListener("touchstart", onDocumentTouchStart, TOUCH_OPTIONS); + window.addEventListener("blur", onWindowBlur); +} +var isBrowser = typeof window !== "undefined" && typeof document !== "undefined"; +var isIE11 = isBrowser ? ( + // @ts-ignore + !!window.msCrypto +) : false; +function createMemoryLeakWarning(method) { + var txt = method === "destroy" ? "n already-" : " "; + return [method + "() was called on a" + txt + "destroyed instance. This is a no-op but", "indicates a potential memory leak."].join(" "); +} +function clean(value) { + var spacesAndTabs = /[ \t]{2,}/g; + var lineStartWithSpaces = /^[ \t]*/gm; + return value.replace(spacesAndTabs, " ").replace(lineStartWithSpaces, "").trim(); +} +function getDevMessage(message) { + return clean("\n %ctippy.js\n\n %c" + clean(message) + "\n\n %c👷‍ This is a development-only message. It will be removed in production.\n "); +} +function getFormattedMessage(message) { + return [ + getDevMessage(message), + // title + "color: #00C584; font-size: 1.3em; font-weight: bold;", + // message + "line-height: 1.5", + // footer + "color: #a6a095;" + ]; +} +var visitedMessages; +if (process.env.NODE_ENV !== "production") { + resetVisitedMessages(); +} +function resetVisitedMessages() { + visitedMessages = /* @__PURE__ */ new Set(); +} +function warnWhen(condition, message) { + if (condition && !visitedMessages.has(message)) { + var _console; + visitedMessages.add(message); + (_console = console).warn.apply(_console, getFormattedMessage(message)); + } +} +function errorWhen(condition, message) { + if (condition && !visitedMessages.has(message)) { + var _console2; + visitedMessages.add(message); + (_console2 = console).error.apply(_console2, getFormattedMessage(message)); + } +} +function validateTargets(targets) { + var didPassFalsyValue = !targets; + var didPassPlainObject = Object.prototype.toString.call(targets) === "[object Object]" && !targets.addEventListener; + errorWhen(didPassFalsyValue, ["tippy() was passed", "`" + String(targets) + "`", "as its targets (first) argument. Valid types are: String, Element,", "Element[], or NodeList."].join(" ")); + errorWhen(didPassPlainObject, ["tippy() was passed a plain object which is not supported as an argument", "for virtual positioning. Use props.getReferenceClientRect instead."].join(" ")); +} +var pluginProps = { + animateFill: false, + followCursor: false, + inlinePositioning: false, + sticky: false +}; +var renderProps = { + allowHTML: false, + animation: "fade", + arrow: true, + content: "", + inertia: false, + maxWidth: 350, + role: "tooltip", + theme: "", + zIndex: 9999 +}; +var defaultProps = Object.assign({ + appendTo: TIPPY_DEFAULT_APPEND_TO, + aria: { + content: "auto", + expanded: "auto" + }, + delay: 0, + duration: [300, 250], + getReferenceClientRect: null, + hideOnClick: true, + ignoreAttributes: false, + interactive: false, + interactiveBorder: 2, + interactiveDebounce: 0, + moveTransition: "", + offset: [0, 10], + onAfterUpdate: function onAfterUpdate() { + }, + onBeforeUpdate: function onBeforeUpdate() { + }, + onCreate: function onCreate() { + }, + onDestroy: function onDestroy() { + }, + onHidden: function onHidden() { + }, + onHide: function onHide() { + }, + onMount: function onMount() { + }, + onShow: function onShow() { + }, + onShown: function onShown() { + }, + onTrigger: function onTrigger() { + }, + onUntrigger: function onUntrigger() { + }, + onClickOutside: function onClickOutside() { + }, + placement: "top", + plugins: [], + popperOptions: {}, + render: null, + showOnCreate: false, + touch: true, + trigger: "mouseenter focus", + triggerTarget: null +}, pluginProps, renderProps); +var defaultKeys = Object.keys(defaultProps); +var setDefaultProps = function setDefaultProps2(partialProps) { + if (process.env.NODE_ENV !== "production") { + validateProps(partialProps, []); + } + var keys = Object.keys(partialProps); + keys.forEach(function(key) { + defaultProps[key] = partialProps[key]; + }); +}; +function getExtendedPassedProps(passedProps) { + var plugins = passedProps.plugins || []; + var pluginProps2 = plugins.reduce(function(acc, plugin) { + var name = plugin.name, defaultValue = plugin.defaultValue; + if (name) { + var _name; + acc[name] = passedProps[name] !== void 0 ? passedProps[name] : (_name = defaultProps[name]) != null ? _name : defaultValue; + } + return acc; + }, {}); + return Object.assign({}, passedProps, pluginProps2); +} +function getDataAttributeProps(reference2, plugins) { + var propKeys = plugins ? Object.keys(getExtendedPassedProps(Object.assign({}, defaultProps, { + plugins + }))) : defaultKeys; + var props = propKeys.reduce(function(acc, key) { + var valueAsString = (reference2.getAttribute("data-tippy-" + key) || "").trim(); + if (!valueAsString) { + return acc; + } + if (key === "content") { + acc[key] = valueAsString; + } else { + try { + acc[key] = JSON.parse(valueAsString); + } catch (e) { + acc[key] = valueAsString; + } + } + return acc; + }, {}); + return props; +} +function evaluateProps(reference2, props) { + var out = Object.assign({}, props, { + content: invokeWithArgsOrReturn(props.content, [reference2]) + }, props.ignoreAttributes ? {} : getDataAttributeProps(reference2, props.plugins)); + out.aria = Object.assign({}, defaultProps.aria, out.aria); + out.aria = { + expanded: out.aria.expanded === "auto" ? props.interactive : out.aria.expanded, + content: out.aria.content === "auto" ? props.interactive ? null : "describedby" : out.aria.content + }; + return out; +} +function validateProps(partialProps, plugins) { + if (partialProps === void 0) { + partialProps = {}; + } + if (plugins === void 0) { + plugins = []; + } + var keys = Object.keys(partialProps); + keys.forEach(function(prop) { + var nonPluginProps = removeProperties(defaultProps, Object.keys(pluginProps)); + var didPassUnknownProp = !hasOwnProperty(nonPluginProps, prop); + if (didPassUnknownProp) { + didPassUnknownProp = plugins.filter(function(plugin) { + return plugin.name === prop; + }).length === 0; + } + warnWhen(didPassUnknownProp, ["`" + prop + "`", "is not a valid prop. You may have spelled it incorrectly, or if it's", "a plugin, forgot to pass it in an array as props.plugins.", "\n\n", "All props: https://atomiks.github.io/tippyjs/v6/all-props/\n", "Plugins: https://atomiks.github.io/tippyjs/v6/plugins/"].join(" ")); + }); +} +var innerHTML = function innerHTML2() { + return "innerHTML"; +}; +function dangerouslySetInnerHTML(element, html) { + element[innerHTML()] = html; +} +function createArrowElement(value) { + var arrow2 = div(); + if (value === true) { + arrow2.className = ARROW_CLASS; + } else { + arrow2.className = SVG_ARROW_CLASS; + if (isElement(value)) { + arrow2.appendChild(value); + } else { + dangerouslySetInnerHTML(arrow2, value); + } + } + return arrow2; +} +function setContent(content, props) { + if (isElement(props.content)) { + dangerouslySetInnerHTML(content, ""); + content.appendChild(props.content); + } else if (typeof props.content !== "function") { + if (props.allowHTML) { + dangerouslySetInnerHTML(content, props.content); + } else { + content.textContent = props.content; + } + } +} +function getChildren(popper2) { + var box = popper2.firstElementChild; + var boxChildren = arrayFrom(box.children); + return { + box, + content: boxChildren.find(function(node) { + return node.classList.contains(CONTENT_CLASS); + }), + arrow: boxChildren.find(function(node) { + return node.classList.contains(ARROW_CLASS) || node.classList.contains(SVG_ARROW_CLASS); + }), + backdrop: boxChildren.find(function(node) { + return node.classList.contains(BACKDROP_CLASS); + }) + }; +} +function render(instance) { + var popper2 = div(); + var box = div(); + box.className = BOX_CLASS; + box.setAttribute("data-state", "hidden"); + box.setAttribute("tabindex", "-1"); + var content = div(); + content.className = CONTENT_CLASS; + content.setAttribute("data-state", "hidden"); + setContent(content, instance.props); + popper2.appendChild(box); + box.appendChild(content); + onUpdate(instance.props, instance.props); + function onUpdate(prevProps, nextProps) { + var _getChildren = getChildren(popper2), box2 = _getChildren.box, content2 = _getChildren.content, arrow2 = _getChildren.arrow; + if (nextProps.theme) { + box2.setAttribute("data-theme", nextProps.theme); + } else { + box2.removeAttribute("data-theme"); + } + if (typeof nextProps.animation === "string") { + box2.setAttribute("data-animation", nextProps.animation); + } else { + box2.removeAttribute("data-animation"); + } + if (nextProps.inertia) { + box2.setAttribute("data-inertia", ""); + } else { + box2.removeAttribute("data-inertia"); + } + box2.style.maxWidth = typeof nextProps.maxWidth === "number" ? nextProps.maxWidth + "px" : nextProps.maxWidth; + if (nextProps.role) { + box2.setAttribute("role", nextProps.role); + } else { + box2.removeAttribute("role"); + } + if (prevProps.content !== nextProps.content || prevProps.allowHTML !== nextProps.allowHTML) { + setContent(content2, instance.props); + } + if (nextProps.arrow) { + if (!arrow2) { + box2.appendChild(createArrowElement(nextProps.arrow)); + } else if (prevProps.arrow !== nextProps.arrow) { + box2.removeChild(arrow2); + box2.appendChild(createArrowElement(nextProps.arrow)); + } + } else if (arrow2) { + box2.removeChild(arrow2); + } + } + return { + popper: popper2, + onUpdate + }; +} +render.$$tippy = true; +var idCounter = 1; +var mouseMoveListeners = []; +var mountedInstances = []; +function createTippy(reference2, passedProps) { + var props = evaluateProps(reference2, Object.assign({}, defaultProps, getExtendedPassedProps(removeUndefinedProps(passedProps)))); + var showTimeout; + var hideTimeout; + var scheduleHideAnimationFrame; + var isVisibleFromClick = false; + var didHideDueToDocumentMouseDown = false; + var didTouchMove = false; + var ignoreOnFirstUpdate = false; + var lastTriggerEvent; + var currentTransitionEndListener; + var onFirstUpdate; + var listeners = []; + var debouncedOnMouseMove = debounce(onMouseMove, props.interactiveDebounce); + var currentTarget; + var id = idCounter++; + var popperInstance = null; + var plugins = unique(props.plugins); + var state = { + // Is the instance currently enabled? + isEnabled: true, + // Is the tippy currently showing and not transitioning out? + isVisible: false, + // Has the instance been destroyed? + isDestroyed: false, + // Is the tippy currently mounted to the DOM? + isMounted: false, + // Has the tippy finished transitioning in? + isShown: false + }; + var instance = { + // properties + id, + reference: reference2, + popper: div(), + popperInstance, + props, + state, + plugins, + // methods + clearDelayTimeouts, + setProps, + setContent: setContent2, + show, + hide: hide2, + hideWithInteractivity, + enable, + disable, + unmount, + destroy + }; + if (!props.render) { + if (process.env.NODE_ENV !== "production") { + errorWhen(true, "render() function has not been supplied."); + } + return instance; + } + var _props$render = props.render(instance), popper2 = _props$render.popper, onUpdate = _props$render.onUpdate; + popper2.setAttribute("data-tippy-root", ""); + popper2.id = "tippy-" + instance.id; + instance.popper = popper2; + reference2._tippy = instance; + popper2._tippy = instance; + var pluginsHooks = plugins.map(function(plugin) { + return plugin.fn(instance); + }); + var hasAriaExpanded = reference2.hasAttribute("aria-expanded"); + addListeners(); + handleAriaExpandedAttribute(); + handleStyles(); + invokeHook("onCreate", [instance]); + if (props.showOnCreate) { + scheduleShow(); + } + popper2.addEventListener("mouseenter", function() { + if (instance.props.interactive && instance.state.isVisible) { + instance.clearDelayTimeouts(); + } + }); + popper2.addEventListener("mouseleave", function() { + if (instance.props.interactive && instance.props.trigger.indexOf("mouseenter") >= 0) { + getDocument().addEventListener("mousemove", debouncedOnMouseMove); + } + }); + return instance; + function getNormalizedTouchSettings() { + var touch = instance.props.touch; + return Array.isArray(touch) ? touch : [touch, 0]; + } + function getIsCustomTouchBehavior() { + return getNormalizedTouchSettings()[0] === "hold"; + } + function getIsDefaultRenderFn() { + var _instance$props$rende; + return !!((_instance$props$rende = instance.props.render) != null && _instance$props$rende.$$tippy); + } + function getCurrentTarget() { + return currentTarget || reference2; + } + function getDocument() { + var parent = getCurrentTarget().parentNode; + return parent ? getOwnerDocument(parent) : document; + } + function getDefaultTemplateChildren() { + return getChildren(popper2); + } + function getDelay(isShow) { + if (instance.state.isMounted && !instance.state.isVisible || currentInput.isTouch || lastTriggerEvent && lastTriggerEvent.type === "focus") { + return 0; + } + return getValueAtIndexOrReturn(instance.props.delay, isShow ? 0 : 1, defaultProps.delay); + } + function handleStyles(fromHide) { + if (fromHide === void 0) { + fromHide = false; + } + popper2.style.pointerEvents = instance.props.interactive && !fromHide ? "" : "none"; + popper2.style.zIndex = "" + instance.props.zIndex; + } + function invokeHook(hook, args, shouldInvokePropsHook) { + if (shouldInvokePropsHook === void 0) { + shouldInvokePropsHook = true; + } + pluginsHooks.forEach(function(pluginHooks) { + if (pluginHooks[hook]) { + pluginHooks[hook].apply(pluginHooks, args); + } + }); + if (shouldInvokePropsHook) { + var _instance$props; + (_instance$props = instance.props)[hook].apply(_instance$props, args); + } + } + function handleAriaContentAttribute() { + var aria = instance.props.aria; + if (!aria.content) { + return; + } + var attr = "aria-" + aria.content; + var id2 = popper2.id; + var nodes = normalizeToArray(instance.props.triggerTarget || reference2); + nodes.forEach(function(node) { + var currentValue = node.getAttribute(attr); + if (instance.state.isVisible) { + node.setAttribute(attr, currentValue ? currentValue + " " + id2 : id2); + } else { + var nextValue = currentValue && currentValue.replace(id2, "").trim(); + if (nextValue) { + node.setAttribute(attr, nextValue); + } else { + node.removeAttribute(attr); + } + } + }); + } + function handleAriaExpandedAttribute() { + if (hasAriaExpanded || !instance.props.aria.expanded) { + return; + } + var nodes = normalizeToArray(instance.props.triggerTarget || reference2); + nodes.forEach(function(node) { + if (instance.props.interactive) { + node.setAttribute("aria-expanded", instance.state.isVisible && node === getCurrentTarget() ? "true" : "false"); + } else { + node.removeAttribute("aria-expanded"); + } + }); + } + function cleanupInteractiveMouseListeners() { + getDocument().removeEventListener("mousemove", debouncedOnMouseMove); + mouseMoveListeners = mouseMoveListeners.filter(function(listener) { + return listener !== debouncedOnMouseMove; + }); + } + function onDocumentPress(event) { + if (currentInput.isTouch) { + if (didTouchMove || event.type === "mousedown") { + return; + } + } + var actualTarget = event.composedPath && event.composedPath()[0] || event.target; + if (instance.props.interactive && actualContains(popper2, actualTarget)) { + return; + } + if (normalizeToArray(instance.props.triggerTarget || reference2).some(function(el) { + return actualContains(el, actualTarget); + })) { + if (currentInput.isTouch) { + return; + } + if (instance.state.isVisible && instance.props.trigger.indexOf("click") >= 0) { + return; + } + } else { + invokeHook("onClickOutside", [instance, event]); + } + if (instance.props.hideOnClick === true) { + instance.clearDelayTimeouts(); + instance.hide(); + didHideDueToDocumentMouseDown = true; + setTimeout(function() { + didHideDueToDocumentMouseDown = false; + }); + if (!instance.state.isMounted) { + removeDocumentPress(); + } + } + } + function onTouchMove() { + didTouchMove = true; + } + function onTouchStart() { + didTouchMove = false; + } + function addDocumentPress() { + var doc = getDocument(); + doc.addEventListener("mousedown", onDocumentPress, true); + doc.addEventListener("touchend", onDocumentPress, TOUCH_OPTIONS); + doc.addEventListener("touchstart", onTouchStart, TOUCH_OPTIONS); + doc.addEventListener("touchmove", onTouchMove, TOUCH_OPTIONS); + } + function removeDocumentPress() { + var doc = getDocument(); + doc.removeEventListener("mousedown", onDocumentPress, true); + doc.removeEventListener("touchend", onDocumentPress, TOUCH_OPTIONS); + doc.removeEventListener("touchstart", onTouchStart, TOUCH_OPTIONS); + doc.removeEventListener("touchmove", onTouchMove, TOUCH_OPTIONS); + } + function onTransitionedOut(duration, callback) { + onTransitionEnd(duration, function() { + if (!instance.state.isVisible && popper2.parentNode && popper2.parentNode.contains(popper2)) { + callback(); + } + }); + } + function onTransitionedIn(duration, callback) { + onTransitionEnd(duration, callback); + } + function onTransitionEnd(duration, callback) { + var box = getDefaultTemplateChildren().box; + function listener(event) { + if (event.target === box) { + updateTransitionEndListener(box, "remove", listener); + callback(); + } + } + if (duration === 0) { + return callback(); + } + updateTransitionEndListener(box, "remove", currentTransitionEndListener); + updateTransitionEndListener(box, "add", listener); + currentTransitionEndListener = listener; + } + function on(eventType, handler, options) { + if (options === void 0) { + options = false; + } + var nodes = normalizeToArray(instance.props.triggerTarget || reference2); + nodes.forEach(function(node) { + node.addEventListener(eventType, handler, options); + listeners.push({ + node, + eventType, + handler, + options + }); + }); + } + function addListeners() { + if (getIsCustomTouchBehavior()) { + on("touchstart", onTrigger2, { + passive: true + }); + on("touchend", onMouseLeave, { + passive: true + }); + } + splitBySpaces(instance.props.trigger).forEach(function(eventType) { + if (eventType === "manual") { + return; + } + on(eventType, onTrigger2); + switch (eventType) { + case "mouseenter": + on("mouseleave", onMouseLeave); + break; + case "focus": + on(isIE11 ? "focusout" : "blur", onBlurOrFocusOut); + break; + case "focusin": + on("focusout", onBlurOrFocusOut); + break; + } + }); + } + function removeListeners() { + listeners.forEach(function(_ref) { + var node = _ref.node, eventType = _ref.eventType, handler = _ref.handler, options = _ref.options; + node.removeEventListener(eventType, handler, options); + }); + listeners = []; + } + function onTrigger2(event) { + var _lastTriggerEvent; + var shouldScheduleClickHide = false; + if (!instance.state.isEnabled || isEventListenerStopped(event) || didHideDueToDocumentMouseDown) { + return; + } + var wasFocused = ((_lastTriggerEvent = lastTriggerEvent) == null ? void 0 : _lastTriggerEvent.type) === "focus"; + lastTriggerEvent = event; + currentTarget = event.currentTarget; + handleAriaExpandedAttribute(); + if (!instance.state.isVisible && isMouseEvent(event)) { + mouseMoveListeners.forEach(function(listener) { + return listener(event); + }); + } + if (event.type === "click" && (instance.props.trigger.indexOf("mouseenter") < 0 || isVisibleFromClick) && instance.props.hideOnClick !== false && instance.state.isVisible) { + shouldScheduleClickHide = true; + } else { + scheduleShow(event); + } + if (event.type === "click") { + isVisibleFromClick = !shouldScheduleClickHide; + } + if (shouldScheduleClickHide && !wasFocused) { + scheduleHide(event); + } + } + function onMouseMove(event) { + var target = event.target; + var isCursorOverReferenceOrPopper = getCurrentTarget().contains(target) || popper2.contains(target); + if (event.type === "mousemove" && isCursorOverReferenceOrPopper) { + return; + } + var popperTreeData = getNestedPopperTree().concat(popper2).map(function(popper3) { + var _instance$popperInsta; + var instance2 = popper3._tippy; + var state2 = (_instance$popperInsta = instance2.popperInstance) == null ? void 0 : _instance$popperInsta.state; + if (state2) { + return { + popperRect: popper3.getBoundingClientRect(), + popperState: state2, + props + }; + } + return null; + }).filter(Boolean); + if (isCursorOutsideInteractiveBorder(popperTreeData, event)) { + cleanupInteractiveMouseListeners(); + scheduleHide(event); + } + } + function onMouseLeave(event) { + var shouldBail = isEventListenerStopped(event) || instance.props.trigger.indexOf("click") >= 0 && isVisibleFromClick; + if (shouldBail) { + return; + } + if (instance.props.interactive) { + instance.hideWithInteractivity(event); + return; + } + scheduleHide(event); + } + function onBlurOrFocusOut(event) { + if (instance.props.trigger.indexOf("focusin") < 0 && event.target !== getCurrentTarget()) { + return; + } + if (instance.props.interactive && event.relatedTarget && popper2.contains(event.relatedTarget)) { + return; + } + scheduleHide(event); + } + function isEventListenerStopped(event) { + return currentInput.isTouch ? getIsCustomTouchBehavior() !== event.type.indexOf("touch") >= 0 : false; + } + function createPopperInstance() { + destroyPopperInstance(); + var _instance$props2 = instance.props, popperOptions = _instance$props2.popperOptions, placement = _instance$props2.placement, offset2 = _instance$props2.offset, getReferenceClientRect = _instance$props2.getReferenceClientRect, moveTransition = _instance$props2.moveTransition; + var arrow2 = getIsDefaultRenderFn() ? getChildren(popper2).arrow : null; + var computedReference = getReferenceClientRect ? { + getBoundingClientRect: getReferenceClientRect, + contextElement: getReferenceClientRect.contextElement || getCurrentTarget() + } : reference2; + var tippyModifier = { + name: "$$tippy", + enabled: true, + phase: "beforeWrite", + requires: ["computeStyles"], + fn: function fn2(_ref2) { + var state2 = _ref2.state; + if (getIsDefaultRenderFn()) { + var _getDefaultTemplateCh = getDefaultTemplateChildren(), box = _getDefaultTemplateCh.box; + ["placement", "reference-hidden", "escaped"].forEach(function(attr) { + if (attr === "placement") { + box.setAttribute("data-placement", state2.placement); + } else { + if (state2.attributes.popper["data-popper-" + attr]) { + box.setAttribute("data-" + attr, ""); + } else { + box.removeAttribute("data-" + attr); + } + } + }); + state2.attributes.popper = {}; + } + } + }; + var modifiers = [{ + name: "offset", + options: { + offset: offset2 + } + }, { + name: "preventOverflow", + options: { + padding: { + top: 2, + bottom: 2, + left: 5, + right: 5 + } + } + }, { + name: "flip", + options: { + padding: 5 + } + }, { + name: "computeStyles", + options: { + adaptive: !moveTransition + } + }, tippyModifier]; + if (getIsDefaultRenderFn() && arrow2) { + modifiers.push({ + name: "arrow", + options: { + element: arrow2, + padding: 3 + } + }); + } + modifiers.push.apply(modifiers, (popperOptions == null ? void 0 : popperOptions.modifiers) || []); + instance.popperInstance = createPopper(computedReference, popper2, Object.assign({}, popperOptions, { + placement, + onFirstUpdate, + modifiers + })); + } + function destroyPopperInstance() { + if (instance.popperInstance) { + instance.popperInstance.destroy(); + instance.popperInstance = null; + } + } + function mount() { + var appendTo = instance.props.appendTo; + var parentNode; + var node = getCurrentTarget(); + if (instance.props.interactive && appendTo === TIPPY_DEFAULT_APPEND_TO || appendTo === "parent") { + parentNode = node.parentNode; + } else { + parentNode = invokeWithArgsOrReturn(appendTo, [node]); + } + if (!parentNode.contains(popper2)) { + parentNode.appendChild(popper2); + } + instance.state.isMounted = true; + createPopperInstance(); + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.props.interactive && appendTo === defaultProps.appendTo && node.nextElementSibling !== popper2, ["Interactive tippy element may not be accessible via keyboard", "navigation because it is not directly after the reference element", "in the DOM source order.", "\n\n", "Using a wrapper
or tag around the reference element", "solves this by creating a new parentNode context.", "\n\n", "Specifying `appendTo: document.body` silences this warning, but it", "assumes you are using a focus management solution to handle", "keyboard navigation.", "\n\n", "See: https://atomiks.github.io/tippyjs/v6/accessibility/#interactivity"].join(" ")); + } + } + function getNestedPopperTree() { + return arrayFrom(popper2.querySelectorAll("[data-tippy-root]")); + } + function scheduleShow(event) { + instance.clearDelayTimeouts(); + if (event) { + invokeHook("onTrigger", [instance, event]); + } + addDocumentPress(); + var delay = getDelay(true); + var _getNormalizedTouchSe = getNormalizedTouchSettings(), touchValue = _getNormalizedTouchSe[0], touchDelay = _getNormalizedTouchSe[1]; + if (currentInput.isTouch && touchValue === "hold" && touchDelay) { + delay = touchDelay; + } + if (delay) { + showTimeout = setTimeout(function() { + instance.show(); + }, delay); + } else { + instance.show(); + } + } + function scheduleHide(event) { + instance.clearDelayTimeouts(); + invokeHook("onUntrigger", [instance, event]); + if (!instance.state.isVisible) { + removeDocumentPress(); + return; + } + if (instance.props.trigger.indexOf("mouseenter") >= 0 && instance.props.trigger.indexOf("click") >= 0 && ["mouseleave", "mousemove"].indexOf(event.type) >= 0 && isVisibleFromClick) { + return; + } + var delay = getDelay(false); + if (delay) { + hideTimeout = setTimeout(function() { + if (instance.state.isVisible) { + instance.hide(); + } + }, delay); + } else { + scheduleHideAnimationFrame = requestAnimationFrame(function() { + instance.hide(); + }); + } + } + function enable() { + instance.state.isEnabled = true; + } + function disable() { + instance.hide(); + instance.state.isEnabled = false; + } + function clearDelayTimeouts() { + clearTimeout(showTimeout); + clearTimeout(hideTimeout); + cancelAnimationFrame(scheduleHideAnimationFrame); + } + function setProps(partialProps) { + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.state.isDestroyed, createMemoryLeakWarning("setProps")); + } + if (instance.state.isDestroyed) { + return; + } + invokeHook("onBeforeUpdate", [instance, partialProps]); + removeListeners(); + var prevProps = instance.props; + var nextProps = evaluateProps(reference2, Object.assign({}, prevProps, removeUndefinedProps(partialProps), { + ignoreAttributes: true + })); + instance.props = nextProps; + addListeners(); + if (prevProps.interactiveDebounce !== nextProps.interactiveDebounce) { + cleanupInteractiveMouseListeners(); + debouncedOnMouseMove = debounce(onMouseMove, nextProps.interactiveDebounce); + } + if (prevProps.triggerTarget && !nextProps.triggerTarget) { + normalizeToArray(prevProps.triggerTarget).forEach(function(node) { + node.removeAttribute("aria-expanded"); + }); + } else if (nextProps.triggerTarget) { + reference2.removeAttribute("aria-expanded"); + } + handleAriaExpandedAttribute(); + handleStyles(); + if (onUpdate) { + onUpdate(prevProps, nextProps); + } + if (instance.popperInstance) { + createPopperInstance(); + getNestedPopperTree().forEach(function(nestedPopper) { + requestAnimationFrame(nestedPopper._tippy.popperInstance.forceUpdate); + }); + } + invokeHook("onAfterUpdate", [instance, partialProps]); + } + function setContent2(content) { + instance.setProps({ + content + }); + } + function show() { + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.state.isDestroyed, createMemoryLeakWarning("show")); + } + var isAlreadyVisible = instance.state.isVisible; + var isDestroyed = instance.state.isDestroyed; + var isDisabled = !instance.state.isEnabled; + var isTouchAndTouchDisabled = currentInput.isTouch && !instance.props.touch; + var duration = getValueAtIndexOrReturn(instance.props.duration, 0, defaultProps.duration); + if (isAlreadyVisible || isDestroyed || isDisabled || isTouchAndTouchDisabled) { + return; + } + if (getCurrentTarget().hasAttribute("disabled")) { + return; + } + invokeHook("onShow", [instance], false); + if (instance.props.onShow(instance) === false) { + return; + } + instance.state.isVisible = true; + if (getIsDefaultRenderFn()) { + popper2.style.visibility = "visible"; + } + handleStyles(); + addDocumentPress(); + if (!instance.state.isMounted) { + popper2.style.transition = "none"; + } + if (getIsDefaultRenderFn()) { + var _getDefaultTemplateCh2 = getDefaultTemplateChildren(), box = _getDefaultTemplateCh2.box, content = _getDefaultTemplateCh2.content; + setTransitionDuration([box, content], 0); + } + onFirstUpdate = function onFirstUpdate2() { + var _instance$popperInsta2; + if (!instance.state.isVisible || ignoreOnFirstUpdate) { + return; + } + ignoreOnFirstUpdate = true; + void popper2.offsetHeight; + popper2.style.transition = instance.props.moveTransition; + if (getIsDefaultRenderFn() && instance.props.animation) { + var _getDefaultTemplateCh3 = getDefaultTemplateChildren(), _box = _getDefaultTemplateCh3.box, _content = _getDefaultTemplateCh3.content; + setTransitionDuration([_box, _content], duration); + setVisibilityState([_box, _content], "visible"); + } + handleAriaContentAttribute(); + handleAriaExpandedAttribute(); + pushIfUnique(mountedInstances, instance); + (_instance$popperInsta2 = instance.popperInstance) == null ? void 0 : _instance$popperInsta2.forceUpdate(); + invokeHook("onMount", [instance]); + if (instance.props.animation && getIsDefaultRenderFn()) { + onTransitionedIn(duration, function() { + instance.state.isShown = true; + invokeHook("onShown", [instance]); + }); + } + }; + mount(); + } + function hide2() { + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.state.isDestroyed, createMemoryLeakWarning("hide")); + } + var isAlreadyHidden = !instance.state.isVisible; + var isDestroyed = instance.state.isDestroyed; + var isDisabled = !instance.state.isEnabled; + var duration = getValueAtIndexOrReturn(instance.props.duration, 1, defaultProps.duration); + if (isAlreadyHidden || isDestroyed || isDisabled) { + return; + } + invokeHook("onHide", [instance], false); + if (instance.props.onHide(instance) === false) { + return; + } + instance.state.isVisible = false; + instance.state.isShown = false; + ignoreOnFirstUpdate = false; + isVisibleFromClick = false; + if (getIsDefaultRenderFn()) { + popper2.style.visibility = "hidden"; + } + cleanupInteractiveMouseListeners(); + removeDocumentPress(); + handleStyles(true); + if (getIsDefaultRenderFn()) { + var _getDefaultTemplateCh4 = getDefaultTemplateChildren(), box = _getDefaultTemplateCh4.box, content = _getDefaultTemplateCh4.content; + if (instance.props.animation) { + setTransitionDuration([box, content], duration); + setVisibilityState([box, content], "hidden"); + } + } + handleAriaContentAttribute(); + handleAriaExpandedAttribute(); + if (instance.props.animation) { + if (getIsDefaultRenderFn()) { + onTransitionedOut(duration, instance.unmount); + } + } else { + instance.unmount(); + } + } + function hideWithInteractivity(event) { + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.state.isDestroyed, createMemoryLeakWarning("hideWithInteractivity")); + } + getDocument().addEventListener("mousemove", debouncedOnMouseMove); + pushIfUnique(mouseMoveListeners, debouncedOnMouseMove); + debouncedOnMouseMove(event); + } + function unmount() { + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.state.isDestroyed, createMemoryLeakWarning("unmount")); + } + if (instance.state.isVisible) { + instance.hide(); + } + if (!instance.state.isMounted) { + return; + } + destroyPopperInstance(); + getNestedPopperTree().forEach(function(nestedPopper) { + nestedPopper._tippy.unmount(); + }); + if (popper2.parentNode) { + popper2.parentNode.removeChild(popper2); + } + mountedInstances = mountedInstances.filter(function(i) { + return i !== instance; + }); + instance.state.isMounted = false; + invokeHook("onHidden", [instance]); + } + function destroy() { + if (process.env.NODE_ENV !== "production") { + warnWhen(instance.state.isDestroyed, createMemoryLeakWarning("destroy")); + } + if (instance.state.isDestroyed) { + return; + } + instance.clearDelayTimeouts(); + instance.unmount(); + removeListeners(); + delete reference2._tippy; + instance.state.isDestroyed = true; + invokeHook("onDestroy", [instance]); + } +} +function tippy(targets, optionalProps) { + if (optionalProps === void 0) { + optionalProps = {}; + } + var plugins = defaultProps.plugins.concat(optionalProps.plugins || []); + if (process.env.NODE_ENV !== "production") { + validateTargets(targets); + validateProps(optionalProps, plugins); + } + bindGlobalEventListeners(); + var passedProps = Object.assign({}, optionalProps, { + plugins + }); + var elements = getArrayOfElements(targets); + if (process.env.NODE_ENV !== "production") { + var isSingleContentElement = isElement(passedProps.content); + var isMoreThanOneReferenceElement = elements.length > 1; + warnWhen(isSingleContentElement && isMoreThanOneReferenceElement, ["tippy() was passed an Element as the `content` prop, but more than", "one tippy instance was created by this invocation. This means the", "content element will only be appended to the last tippy instance.", "\n\n", "Instead, pass the .innerHTML of the element, or use a function that", "returns a cloned version of the element instead.", "\n\n", "1) content: element.innerHTML\n", "2) content: () => element.cloneNode(true)"].join(" ")); + } + var instances = elements.reduce(function(acc, reference2) { + var instance = reference2 && createTippy(reference2, passedProps); + if (instance) { + acc.push(instance); + } + return acc; + }, []); + return isElement(targets) ? instances[0] : instances; +} +tippy.defaultProps = defaultProps; +tippy.setDefaultProps = setDefaultProps; +tippy.currentInput = currentInput; +Object.assign({}, applyStyles$1, { + effect: function effect2(_ref) { + var state = _ref.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: "0", + top: "0", + margin: "0" + }, + arrow: { + position: "absolute" + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); + } + } +}); +tippy.setDefaultProps({ + render +}); +export { + tippy as t +}; diff --git a/bootstrap/ssr/ssr-manifest.json b/bootstrap/ssr/ssr-manifest.json new file mode 100644 index 00000000..e670a6a4 --- /dev/null +++ b/bootstrap/ssr/ssr-manifest.json @@ -0,0 +1,2407 @@ +{ + "\u0000D:/Sites/Skinbase26/node_modules/asynckit/serialOrdered.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/debug/src/browser.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/debug/src/index.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/debug/src/node.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/deepmerge/dist/cjs.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/extend/index.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/follow-redirects/index.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/follow-redirects/index.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/form-data/lib/form_data.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/lodash.isequal/index.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/lodash.isequal/index.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/mime-types/index.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/nprogress/nprogress.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/nprogress/nprogress.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/pusher-js/dist/node/pusher.js?commonjs-es-import": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/pusher-js/dist/node/pusher.js?commonjs-module": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/qs/lib/index.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-client.development.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-client.production.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-server-legacy.node.production.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-server.node.development.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-server.node.production.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom.development.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom.production.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/client.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/client.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/index.js?commonjs-es-import": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/index.js?commonjs-module": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/server.node.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/react-dom/server.node.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react-jsx-runtime.development.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react-jsx-runtime.production.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react.development.js?commonjs-module": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react.production.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/index.js?commonjs-es-import": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/index.js?commonjs-module": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/jsx-runtime.js?commonjs-es-import": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/react/jsx-runtime.js?commonjs-module": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/scheduler/cjs/scheduler.development.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/scheduler/cjs/scheduler.production.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/scheduler/index.js?commonjs-module": [], + "\u0000D:/Sites/Skinbase26/node_modules/style-to-js/cjs/index.js?commonjs-es-import": [], + "\u0000D:/Sites/Skinbase26/node_modules/style-to-js/cjs/utilities.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/style-to-object/cjs/index.js?commonjs-exports": [], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.js?commonjs-exports": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/index.js?commonjs-es-import": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/index.js?commonjs-module": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/with-selector.js?commonjs-es-import": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/with-selector.js?commonjs-module": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000assert?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000buffer?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000child_process?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000commonjsHelpers.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "\u0000crypto?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000events?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000fs?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000http?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000https?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000net?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000stream?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000tls?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000url?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "\u0000util?commonjs-external": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "node_modules/@emoji-mart/data/sets/15/native.json": [ + "/build/assets/emoji-data-4xGXbtDn.js" + ], + "node_modules/@inertiajs/core/dist/index.esm.js": [], + "node_modules/@inertiajs/core/dist/server.esm.js": [], + "node_modules/@inertiajs/react/dist/index.esm.js": [], + "node_modules/@popperjs/core/lib/createPopper.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/contains.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getNodeName.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getParentNode.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getWindow.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/instanceOf.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/isTableElement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/enums.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/index.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/applyStyles.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/arrow.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/computeStyles.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/eventListeners.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/flip.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/hide.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/index.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/offset.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/popperOffsets.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/modifiers/preventOverflow.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/popper-lite.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/popper.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/computeOffsets.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/debounce.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/detectOverflow.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/expandToHashMap.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getAltAxis.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getBasePlacement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getFreshSideObject.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getOppositePlacement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/getVariation.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/math.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/mergeByName.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/mergePaddingObject.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/orderModifiers.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/rectToClientRect.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/userAgent.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@popperjs/core/lib/utils/within.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/@tiptap/core/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/core/dist/jsx-runtime/jsx-runtime.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/core/jsx-runtime/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-blockquote/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-bold/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-code-block/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-code/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-document/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-hard-break/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-heading/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-horizontal-rule/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-image/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-italic/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-link/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-list/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-mention/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-paragraph/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-placeholder/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-strike/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-text/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extension-underline/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/extensions/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/commands/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/dropcursor/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/gapcursor/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/history/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/keymap/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/model/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/schema-list/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/state/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/transform/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/pm/dist/view/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/react/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/starter-kit/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@tiptap/suggestion/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/@ungap/structured-clone/esm/deserialize.js": [], + "node_modules/@ungap/structured-clone/esm/index.js": [], + "node_modules/@ungap/structured-clone/esm/serialize.js": [], + "node_modules/@ungap/structured-clone/esm/types.js": [], + "node_modules/asynckit/index.js": [], + "node_modules/asynckit/lib/abort.js": [], + "node_modules/asynckit/lib/async.js": [], + "node_modules/asynckit/lib/defer.js": [], + "node_modules/asynckit/lib/iterate.js": [], + "node_modules/asynckit/lib/state.js": [], + "node_modules/asynckit/lib/terminator.js": [], + "node_modules/asynckit/parallel.js": [], + "node_modules/asynckit/serial.js": [], + "node_modules/asynckit/serialOrdered.js": [], + "node_modules/axios/index.js": [], + "node_modules/axios/lib/adapters/adapters.js": [], + "node_modules/axios/lib/adapters/fetch.js": [], + "node_modules/axios/lib/adapters/http.js": [], + "node_modules/axios/lib/adapters/xhr.js": [], + "node_modules/axios/lib/axios.js": [], + "node_modules/axios/lib/cancel/CancelToken.js": [], + "node_modules/axios/lib/cancel/CanceledError.js": [], + "node_modules/axios/lib/cancel/isCancel.js": [], + "node_modules/axios/lib/core/Axios.js": [], + "node_modules/axios/lib/core/AxiosError.js": [], + "node_modules/axios/lib/core/AxiosHeaders.js": [], + "node_modules/axios/lib/core/InterceptorManager.js": [], + "node_modules/axios/lib/core/buildFullPath.js": [], + "node_modules/axios/lib/core/dispatchRequest.js": [], + "node_modules/axios/lib/core/mergeConfig.js": [], + "node_modules/axios/lib/core/settle.js": [], + "node_modules/axios/lib/core/transformData.js": [], + "node_modules/axios/lib/defaults/index.js": [], + "node_modules/axios/lib/defaults/transitional.js": [], + "node_modules/axios/lib/env/data.js": [], + "node_modules/axios/lib/helpers/AxiosTransformStream.js": [], + "node_modules/axios/lib/helpers/AxiosURLSearchParams.js": [], + "node_modules/axios/lib/helpers/HttpStatusCode.js": [], + "node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js": [], + "node_modules/axios/lib/helpers/bind.js": [], + "node_modules/axios/lib/helpers/buildURL.js": [], + "node_modules/axios/lib/helpers/callbackify.js": [], + "node_modules/axios/lib/helpers/combineURLs.js": [], + "node_modules/axios/lib/helpers/composeSignals.js": [], + "node_modules/axios/lib/helpers/cookies.js": [], + "node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js": [], + "node_modules/axios/lib/helpers/formDataToJSON.js": [], + "node_modules/axios/lib/helpers/formDataToStream.js": [], + "node_modules/axios/lib/helpers/fromDataURI.js": [], + "node_modules/axios/lib/helpers/isAbsoluteURL.js": [], + "node_modules/axios/lib/helpers/isAxiosError.js": [], + "node_modules/axios/lib/helpers/isURLSameOrigin.js": [], + "node_modules/axios/lib/helpers/parseHeaders.js": [], + "node_modules/axios/lib/helpers/parseProtocol.js": [], + "node_modules/axios/lib/helpers/progressEventReducer.js": [], + "node_modules/axios/lib/helpers/readBlob.js": [], + "node_modules/axios/lib/helpers/resolveConfig.js": [], + "node_modules/axios/lib/helpers/speedometer.js": [], + "node_modules/axios/lib/helpers/spread.js": [], + "node_modules/axios/lib/helpers/throttle.js": [], + "node_modules/axios/lib/helpers/toFormData.js": [], + "node_modules/axios/lib/helpers/toURLEncodedForm.js": [], + "node_modules/axios/lib/helpers/trackStream.js": [], + "node_modules/axios/lib/helpers/validator.js": [], + "node_modules/axios/lib/platform/common/utils.js": [], + "node_modules/axios/lib/platform/index.js": [], + "node_modules/axios/lib/platform/node/classes/URLSearchParams.js": [], + "node_modules/axios/lib/platform/node/index.js": [], + "node_modules/axios/lib/utils.js": [], + "node_modules/bail/index.js": [], + "node_modules/call-bind-apply-helpers/actualApply.js": [], + "node_modules/call-bind-apply-helpers/functionApply.js": [], + "node_modules/call-bind-apply-helpers/functionCall.js": [], + "node_modules/call-bind-apply-helpers/index.js": [], + "node_modules/call-bind-apply-helpers/reflectApply.js": [], + "node_modules/call-bound/index.js": [], + "node_modules/character-entities/index.js": [], + "node_modules/combined-stream/lib/combined_stream.js": [], + "node_modules/comma-separated-tokens/index.js": [], + "node_modules/debug/src/browser.js": [], + "node_modules/debug/src/common.js": [], + "node_modules/debug/src/index.js": [], + "node_modules/debug/src/node.js": [], + "node_modules/decode-named-character-reference/index.js": [], + "node_modules/deepmerge/dist/cjs.js": [], + "node_modules/delayed-stream/lib/delayed_stream.js": [], + "node_modules/devlop/lib/default.js": [], + "node_modules/dunder-proto/get.js": [], + "node_modules/emoji-mart/dist/module.js": [ + "/build/assets/emoji-ui-C_DZUNyP.js" + ], + "node_modules/es-define-property/index.js": [], + "node_modules/es-errors/eval.js": [], + "node_modules/es-errors/index.js": [], + "node_modules/es-errors/range.js": [], + "node_modules/es-errors/ref.js": [], + "node_modules/es-errors/syntax.js": [], + "node_modules/es-errors/type.js": [], + "node_modules/es-errors/uri.js": [], + "node_modules/es-object-atoms/index.js": [], + "node_modules/es-set-tostringtag/index.js": [], + "node_modules/estree-util-is-identifier-name/lib/index.js": [], + "node_modules/extend/index.js": [], + "node_modules/fast-equals/dist/es/index.mjs": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/follow-redirects/debug.js": [], + "node_modules/follow-redirects/index.js": [], + "node_modules/form-data/lib/form_data.js": [], + "node_modules/form-data/lib/populate.js": [], + "node_modules/framer-motion/dist/es/animation/animate/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/animate/resolve-subjects.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/animate/sequence.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/animate/subject.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/animators/waapi/animate-elements.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/animators/waapi/animate-style.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/hooks/animation-controls.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/hooks/use-animate-style.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/hooks/use-animate.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/hooks/use-animated-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/hooks/use-animation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/optimized-appear/handoff.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/optimized-appear/start.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/optimized-appear/store-id.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/optimized-appear/store.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/sequence/create.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/sequence/utils/calc-repeat-duration.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/sequence/utils/calc-time.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/sequence/utils/edit.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/sequence/utils/normalize-times.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/sequence/utils/sort.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/utils/create-visual-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/animation/utils/is-dom-keyframes.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence-data.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimatePresence/utils.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/AnimateSharedLayout.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/LayoutGroup/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/LazyMotion/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/MotionConfig/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/Reorder/Group.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/Reorder/Item.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/Reorder/namespace.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/Reorder/utils/auto-scroll.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/components/Reorder/utils/check-reorder.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/DeprecatedLayoutGroupContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/LazyContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/MotionContext/create.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/MotionContext/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/PresenceContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/ReorderContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/events/add-pointer-event.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/events/event-info.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/events/use-dom-event.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/drag/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/drag/use-drag-controls.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/focus.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/hover.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/pan/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/gestures/press.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/animation/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/animations.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/definitions.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/drag.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/gestures.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/layout.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/load-features.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/is-motion-component.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/symbol.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/unwrap-motion-component.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/projection/use-instant-layout-transition.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/projection/use-reset-projection.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/components/create-proxy.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/components/m/proxy.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/components/motion/feature-bundle.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/components/motion/proxy.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/features-animation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/features-max.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/features-min.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/attach-animation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/attach-function.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/info.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/edge.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/inset.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/offset.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/presets.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/on-scroll-handler.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/track.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/utils/can-use-native-timeline.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/utils/get-timeline.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/scroll/utils/offset-to-range.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/use-render.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/dom/viewport/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/html/use-html-visual-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/html/use-props.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/svg/use-props.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/svg/use-svg-visual-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/distance.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/get-context-window.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/is-browser.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/is-ref-object.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion-config.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/transform-rotated-parent.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/transform-viewbox-point.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-animation-frame.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-composed-ref.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-constant.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-cycle.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-force-update.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-in-view.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-instant-transition.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-motion-value-event.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-page-in-view.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/scroll/use-element-scroll.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/scroll/use-viewport-scroll.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-combine-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-computed.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-follow-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-inverted-scale.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-motion-template.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-motion-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-scroll.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-spring.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-time.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-velocity.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-will-change/WillChangeMotionValue.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/framer-motion/dist/es/value/use-will-change/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/function-bind/implementation.js": [], + "node_modules/function-bind/index.js": [], + "node_modules/get-intrinsic/index.js": [], + "node_modules/get-proto/Object.getPrototypeOf.js": [], + "node_modules/get-proto/Reflect.getPrototypeOf.js": [], + "node_modules/get-proto/index.js": [], + "node_modules/gopd/gOPD.js": [], + "node_modules/gopd/index.js": [], + "node_modules/has-flag/index.js": [], + "node_modules/has-symbols/index.js": [], + "node_modules/has-symbols/shams.js": [], + "node_modules/has-tostringtag/shams.js": [], + "node_modules/hasown/index.js": [], + "node_modules/hast-util-to-jsx-runtime/lib/index.js": [], + "node_modules/hast-util-whitespace/lib/index.js": [], + "node_modules/html-url-attributes/lib/index.js": [], + "node_modules/inline-style-parser/cjs/index.js": [], + "node_modules/is-plain-obj/index.js": [], + "node_modules/laravel-echo/dist/echo.js": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "node_modules/linkifyjs/dist/linkify.mjs": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/lodash.isequal/index.js": [], + "node_modules/math-intrinsics/abs.js": [], + "node_modules/math-intrinsics/floor.js": [], + "node_modules/math-intrinsics/isNaN.js": [], + "node_modules/math-intrinsics/max.js": [], + "node_modules/math-intrinsics/min.js": [], + "node_modules/math-intrinsics/pow.js": [], + "node_modules/math-intrinsics/round.js": [], + "node_modules/math-intrinsics/sign.js": [], + "node_modules/mdast-util-from-markdown/lib/index.js": [], + "node_modules/mdast-util-to-hast/lib/footer.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/blockquote.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/break.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/code.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/delete.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/emphasis.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/footnote-reference.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/heading.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/html.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/image-reference.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/image.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/index.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/inline-code.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/link-reference.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/link.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/list-item.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/list.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/paragraph.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/root.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/strong.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/table-cell.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/table-row.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/table.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/text.js": [], + "node_modules/mdast-util-to-hast/lib/handlers/thematic-break.js": [], + "node_modules/mdast-util-to-hast/lib/index.js": [], + "node_modules/mdast-util-to-hast/lib/revert.js": [], + "node_modules/mdast-util-to-hast/lib/state.js": [], + "node_modules/mdast-util-to-string/lib/index.js": [], + "node_modules/micromark-core-commonmark/lib/attention.js": [], + "node_modules/micromark-core-commonmark/lib/autolink.js": [], + "node_modules/micromark-core-commonmark/lib/blank-line.js": [], + "node_modules/micromark-core-commonmark/lib/block-quote.js": [], + "node_modules/micromark-core-commonmark/lib/character-escape.js": [], + "node_modules/micromark-core-commonmark/lib/character-reference.js": [], + "node_modules/micromark-core-commonmark/lib/code-fenced.js": [], + "node_modules/micromark-core-commonmark/lib/code-indented.js": [], + "node_modules/micromark-core-commonmark/lib/code-text.js": [], + "node_modules/micromark-core-commonmark/lib/content.js": [], + "node_modules/micromark-core-commonmark/lib/definition.js": [], + "node_modules/micromark-core-commonmark/lib/hard-break-escape.js": [], + "node_modules/micromark-core-commonmark/lib/heading-atx.js": [], + "node_modules/micromark-core-commonmark/lib/html-flow.js": [], + "node_modules/micromark-core-commonmark/lib/html-text.js": [], + "node_modules/micromark-core-commonmark/lib/label-end.js": [], + "node_modules/micromark-core-commonmark/lib/label-start-image.js": [], + "node_modules/micromark-core-commonmark/lib/label-start-link.js": [], + "node_modules/micromark-core-commonmark/lib/line-ending.js": [], + "node_modules/micromark-core-commonmark/lib/list.js": [], + "node_modules/micromark-core-commonmark/lib/setext-underline.js": [], + "node_modules/micromark-core-commonmark/lib/thematic-break.js": [], + "node_modules/micromark-factory-destination/index.js": [], + "node_modules/micromark-factory-label/index.js": [], + "node_modules/micromark-factory-space/index.js": [], + "node_modules/micromark-factory-title/index.js": [], + "node_modules/micromark-factory-whitespace/index.js": [], + "node_modules/micromark-util-character/index.js": [], + "node_modules/micromark-util-chunked/index.js": [], + "node_modules/micromark-util-classify-character/index.js": [], + "node_modules/micromark-util-combine-extensions/index.js": [], + "node_modules/micromark-util-decode-numeric-character-reference/index.js": [], + "node_modules/micromark-util-decode-string/index.js": [], + "node_modules/micromark-util-html-tag-name/index.js": [], + "node_modules/micromark-util-normalize-identifier/index.js": [], + "node_modules/micromark-util-resolve-all/index.js": [], + "node_modules/micromark-util-sanitize-uri/index.js": [], + "node_modules/micromark-util-subtokenize/index.js": [], + "node_modules/micromark-util-subtokenize/lib/splice-buffer.js": [], + "node_modules/micromark/lib/constructs.js": [], + "node_modules/micromark/lib/create-tokenizer.js": [], + "node_modules/micromark/lib/initialize/content.js": [], + "node_modules/micromark/lib/initialize/document.js": [], + "node_modules/micromark/lib/initialize/flow.js": [], + "node_modules/micromark/lib/initialize/text.js": [], + "node_modules/micromark/lib/parse.js": [], + "node_modules/micromark/lib/postprocess.js": [], + "node_modules/micromark/lib/preprocess.js": [], + "node_modules/mime-db/db.json": [], + "node_modules/mime-db/index.js": [], + "node_modules/mime-types/index.js": [], + "node_modules/motion-dom/dist/es/animation/AsyncMotionValueAnimation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/GroupAnimation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/GroupAnimationWithThen.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/JSAnimation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/NativeAnimation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/NativeAnimationExtended.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/NativeAnimationWrapper.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/animate/single-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/drivers/frame.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/inertia.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/keyframes.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/spring.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/utils/calc-duration.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/utils/create-generator-easing.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/utils/is-generator.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/generators/utils/velocity.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/interfaces/motion-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/interfaces/visual-element-target.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/interfaces/visual-element-variant.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/interfaces/visual-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/DOMKeyframesResolver.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/KeyframesResolver.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/get-final.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/offsets/default.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/offsets/fill.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/offsets/time.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/utils/apply-px-defaults.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/utils/fill-wildcards.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/utils/is-none.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/utils/make-none-animatable.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/keyframes/utils/unit-conversion.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/optimized-appear/data-id.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/optimized-appear/get-appear-id.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/WithPromise.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/active-animations.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/calc-child-stagger.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/can-animate.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/css-variables-conversion.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/default-transitions.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/get-value-transition.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/is-animatable.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/is-css-variable.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/is-transition-defined.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/make-animation-instant.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/replace-transition-type.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/utils/resolve-transition.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/easing/cubic-bezier.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/easing/is-supported.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/easing/map-easing.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/easing/supported.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/start-waapi-animation.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/supports/partial-keyframes.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/supports/waapi.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/utils/accelerated-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/utils/apply-generator.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/utils/is-browser-color.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/utils/linear.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/utils/px-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/animation/waapi/utils/unsupported-easing.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/MotionValueState.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/attr/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/prop/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/style/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/style/transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/svg/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/utils/create-dom-effect.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/effects/utils/create-effect.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/events/add-dom-event.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/batcher.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/frame.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/index-legacy.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/microtask.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/order.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/render-step.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/frameloop/sync-time.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/drag/state/is-active.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/drag/state/set-active.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/hover.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/press/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/press/utils/is-keyboard-accessible.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/press/utils/keyboard.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/press/utils/state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/utils/is-node-or-child.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/utils/is-primary-pointer.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/gestures/utils/setup.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/layout/LayoutAnimationBuilder.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/animation/mix-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/conversion.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/copy.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/delta-apply.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/delta-calc.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/delta-remove.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/models.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/geometry/utils.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/node/DocumentProjectionNode.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/node/HTMLProjectionNode.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/node/create-projection-node.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/node/group.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/node/state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/shared/stack.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/styles/scale-border-radius.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/styles/scale-box-shadow.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/styles/scale-correction.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/styles/transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/utils/compare-by-depth.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/utils/each-axis.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/utils/flat-tree.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/utils/has-transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/projection/utils/measure.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/Feature.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/VisualElement.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/dom/DOMVisualElement.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/dom/is-css-var.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/dom/parse-transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/dom/style-computed.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/dom/style-set.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/dom/utils/camel-to-dash.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/html/HTMLVisualElement.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/html/utils/build-styles.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/html/utils/build-transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/html/utils/render.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/html/utils/scrape-motion-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/object/ObjectVisualElement.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/store.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/SVGVisualElement.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/utils/build-attrs.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/utils/camel-case-attrs.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/utils/is-svg-tag.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/utils/path.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/utils/render.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/svg/utils/scrape-motion-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/animation-state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/get-variant-context.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/is-animation-controls.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/is-controlling-variants.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/is-forced-motion-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/is-keyframes-target.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/is-variant-label.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/keys-position.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/keys-transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/motion-values.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/reduced-motion/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/reduced-motion/state.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/resolve-dynamic-variants.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/resolve-variants.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/setters.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/shallow-compare.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/render/utils/variant-props.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/resize/handle-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/resize/handle-window.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/resize/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/scroll/observe.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/stats/animation-count.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/stats/buffer.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/stats/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/delay.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/interpolate.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/is-html-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/is-svg-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/is-svg-svg-element.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/mix/color.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/mix/complex.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/mix/immediate.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/mix/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/mix/number.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/mix/visibility.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/resolve-elements.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/stagger.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/supports/flags.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/supports/linear-easing.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/supports/memo.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/supports/scroll-timeline.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/utils/transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/follow-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/map-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/spring-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/subscribe-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/transform-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/auto.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/color/hex.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/color/hsla-to-rgba.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/color/hsla.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/color/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/color/rgba.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/color/utils.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/complex/filter.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/complex/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/complex/mask.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/dimensions.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/int.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/maps/defaults.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/maps/number.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/maps/transform.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/numbers/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/numbers/units.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/test.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/animatable-none.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/color-regex.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/find.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/float-regex.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/get-as-type.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/is-nullish.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/sanitize.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/types/utils/single-color-regex.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/utils/is-motion-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/utils/resolve-motion-value.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/will-change/add-will-change.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/value/will-change/is.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/queue.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/start.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/utils/choose-layer-type.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/utils/css.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/utils/get-layer-info.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/utils/get-view-animations.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-dom/dist/es/view/utils/has-target.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/array.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/clamp.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/anticipate.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/back.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/circ.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/cubic-bezier.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/ease.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/modifiers/mirror.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/modifiers/reverse.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/steps.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/utils/get-easing-for-segment.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/utils/is-bezier-definition.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/utils/is-easing-array.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/easing/utils/map.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/errors.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/format-error-message.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/global-config.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/index.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/is-numerical-string.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/is-object.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/is-zero-value-string.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/memo.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/noop.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/pipe.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/progress.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/subscription-manager.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/time-conversion.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/velocity-per-second.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/warn-once.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/motion-utils/dist/es/wrap.mjs": [ + "/build/assets/vendor-motion-yDK3iGlC.js" + ], + "node_modules/ms/index.js": [], + "node_modules/nprogress/nprogress.js": [], + "node_modules/object-inspect/index.js": [], + "node_modules/object-inspect/util.inspect.js": [], + "node_modules/orderedmap/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/property-information/index.js": [], + "node_modules/property-information/lib/aria.js": [], + "node_modules/property-information/lib/find.js": [], + "node_modules/property-information/lib/hast-to-react.js": [], + "node_modules/property-information/lib/html.js": [], + "node_modules/property-information/lib/normalize.js": [], + "node_modules/property-information/lib/svg.js": [], + "node_modules/property-information/lib/util/case-insensitive-transform.js": [], + "node_modules/property-information/lib/util/case-sensitive-transform.js": [], + "node_modules/property-information/lib/util/create.js": [], + "node_modules/property-information/lib/util/defined-info.js": [], + "node_modules/property-information/lib/util/info.js": [], + "node_modules/property-information/lib/util/merge.js": [], + "node_modules/property-information/lib/util/schema.js": [], + "node_modules/property-information/lib/util/types.js": [], + "node_modules/property-information/lib/xlink.js": [], + "node_modules/property-information/lib/xml.js": [], + "node_modules/property-information/lib/xmlns.js": [], + "node_modules/prosemirror-commands/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-dropcursor/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-gapcursor/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-history/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-keymap/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-model/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-schema-list/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-state/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-transform/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/prosemirror-view/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/proxy-from-env/index.js": [], + "node_modules/pusher-js/dist/node/pusher.js": [ + "/build/assets/vendor-realtime-cgmg5qQY.js" + ], + "node_modules/qs/lib/formats.js": [], + "node_modules/qs/lib/index.js": [], + "node_modules/qs/lib/parse.js": [], + "node_modules/qs/lib/stringify.js": [], + "node_modules/qs/lib/utils.js": [], + "node_modules/react-dom/cjs/react-dom-client.development.js": [], + "node_modules/react-dom/cjs/react-dom-client.production.js": [], + "node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js": [], + "node_modules/react-dom/cjs/react-dom-server-legacy.node.production.js": [], + "node_modules/react-dom/cjs/react-dom-server.node.development.js": [], + "node_modules/react-dom/cjs/react-dom-server.node.production.js": [], + "node_modules/react-dom/cjs/react-dom.development.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react-dom/cjs/react-dom.production.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react-dom/client.js": [], + "node_modules/react-dom/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react-dom/server.node.js": [], + "node_modules/react-markdown/lib/index.js": [], + "node_modules/react/cjs/react-jsx-runtime.development.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react/cjs/react-jsx-runtime.production.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react/cjs/react.development.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react/cjs/react.production.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/react/jsx-runtime.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/remark-parse/lib/index.js": [], + "node_modules/remark-rehype/lib/index.js": [], + "node_modules/rope-sequence/dist/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/scheduler/cjs/scheduler.development.js": [], + "node_modules/scheduler/cjs/scheduler.production.js": [], + "node_modules/scheduler/index.js": [], + "node_modules/side-channel-list/index.js": [], + "node_modules/side-channel-map/index.js": [], + "node_modules/side-channel-weakmap/index.js": [], + "node_modules/side-channel/index.js": [], + "node_modules/space-separated-tokens/index.js": [], + "node_modules/style-to-js/cjs/index.js": [], + "node_modules/style-to-js/cjs/utilities.js": [], + "node_modules/style-to-object/cjs/index.js": [], + "node_modules/supports-color/index.js": [], + "node_modules/tippy.js/dist/tippy.esm.js": [ + "/build/assets/vendor-tooltip-CIQaDNlG.js" + ], + "node_modules/trim-lines/index.js": [], + "node_modules/trough/lib/index.js": [], + "node_modules/unified/lib/callable-instance.js": [], + "node_modules/unified/lib/index.js": [], + "node_modules/unist-util-is/lib/index.js": [], + "node_modules/unist-util-position/lib/index.js": [], + "node_modules/unist-util-stringify-position/lib/index.js": [], + "node_modules/unist-util-visit-parents/lib/color.node.js": [], + "node_modules/unist-util-visit-parents/lib/index.js": [], + "node_modules/unist-util-visit/lib/index.js": [], + "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/use-sync-external-store/shim/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/use-sync-external-store/shim/with-selector.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "node_modules/vfile-message/lib/index.js": [], + "node_modules/vfile/lib/index.js": [], + "node_modules/vfile/lib/minurl.shared.js": [], + "node_modules/w3c-keyname/index.js": [ + "/build/assets/vendor-tiptap-DSw66HfW.js" + ], + "resources/js/Layouts/AdminLayout.jsx": [], + "resources/js/Layouts/SettingsLayout.jsx": [], + "resources/js/Layouts/StudioLayout.jsx": [], + "resources/js/Pages/Admin/AiBiography.jsx": [], + "resources/js/Pages/Admin/Artworks.jsx": [], + "resources/js/Pages/Admin/AuthAudit.jsx": [], + "resources/js/Pages/Admin/Dashboard.jsx": [], + "resources/js/Pages/Admin/FeaturedArtworks.jsx": [], + "resources/js/Pages/Admin/HomepageAnnouncements/Form.jsx": [], + "resources/js/Pages/Admin/HomepageAnnouncements/Index.jsx": [], + "resources/js/Pages/Admin/Settings.jsx": [], + "resources/js/Pages/Admin/Stories.jsx": [], + "resources/js/Pages/Admin/UploadQueue.jsx": [], + "resources/js/Pages/Admin/UsernameQueue.jsx": [], + "resources/js/Pages/Admin/Users/Index.jsx": [], + "resources/js/Pages/Artwork/SimilarArtworksHeader.jsx": [], + "resources/js/Pages/ArtworkPage.jsx": [], + "resources/js/Pages/CategoriesPage.jsx": [], + "resources/js/Pages/Collection/CollectionAnalytics.jsx": [], + "resources/js/Pages/Collection/CollectionDashboard.jsx": [], + "resources/js/Pages/Collection/CollectionFeaturedIndex.jsx": [], + "resources/js/Pages/Collection/CollectionHistory.jsx": [], + "resources/js/Pages/Collection/CollectionManage.jsx": [], + "resources/js/Pages/Collection/CollectionSeriesShow.jsx": [], + "resources/js/Pages/Collection/CollectionShow.jsx": [], + "resources/js/Pages/Collection/CollectionStaffProgramming.jsx": [], + "resources/js/Pages/Collection/CollectionStaffSurfaces.jsx": [], + "resources/js/Pages/Collection/FeaturedArtworksAdmin.jsx": [], + "resources/js/Pages/Collection/NovaCardsAdminIndex.jsx": [], + "resources/js/Pages/Collection/NovaCardsAssetPackAdmin.jsx": [], + "resources/js/Pages/Collection/NovaCardsChallengeAdmin.jsx": [], + "resources/js/Pages/Collection/NovaCardsCollectionAdmin.jsx": [], + "resources/js/Pages/Collection/NovaCardsTemplateAdmin.jsx": [], + "resources/js/Pages/Collection/SavedCollections.jsx": [], + "resources/js/Pages/Community/CommunityActivityPage.jsx": [], + "resources/js/Pages/Community/LatestCommentsPage.jsx": [], + "resources/js/Pages/Feed/FollowingFeed.jsx": [], + "resources/js/Pages/Feed/HashtagFeed.jsx": [], + "resources/js/Pages/Feed/SavedFeed.jsx": [], + "resources/js/Pages/Feed/SearchFeed.jsx": [], + "resources/js/Pages/Feed/TrendingFeed.jsx": [], + "resources/js/Pages/Forum/ForumCategory.jsx": [], + "resources/js/Pages/Forum/ForumEditPost.jsx": [], + "resources/js/Pages/Forum/ForumIndex.jsx": [], + "resources/js/Pages/Forum/ForumNewThread.jsx": [], + "resources/js/Pages/Forum/ForumSection.jsx": [], + "resources/js/Pages/Forum/ForumThread.jsx": [], + "resources/js/Pages/Group/GroupChallengeShow.jsx": [], + "resources/js/Pages/Group/GroupEventShow.jsx": [], + "resources/js/Pages/Group/GroupFaqPage.jsx": [], + "resources/js/Pages/Group/GroupHelpPage.jsx": [], + "resources/js/Pages/Group/GroupIndex.jsx": [], + "resources/js/Pages/Group/GroupPostShow.jsx": [], + "resources/js/Pages/Group/GroupProjectShow.jsx": [], + "resources/js/Pages/Group/GroupQuickstartPage.jsx": [], + "resources/js/Pages/Group/GroupReleaseShow.jsx": [], + "resources/js/Pages/Group/GroupShow.jsx": [], + "resources/js/Pages/Group/groupFaqContent.js": [], + "resources/js/Pages/Group/groupHelpContent.js": [], + "resources/js/Pages/Group/groupQuickstartContent.js": [], + "resources/js/Pages/Help/AccountHelpPage.jsx": [], + "resources/js/Pages/Help/AuthHelpPage.jsx": [], + "resources/js/Pages/Help/CardsHelpPage.jsx": [], + "resources/js/Pages/Help/HelpCenterPage.jsx": [], + "resources/js/Pages/Help/ProfileHelpPage.jsx": [], + "resources/js/Pages/Help/StudioHelpPage.jsx": [], + "resources/js/Pages/Help/TroubleshootingHelpPage.jsx": [], + "resources/js/Pages/Help/UploadHelpPage.jsx": [], + "resources/js/Pages/Help/WorldsHelpPage.jsx": [], + "resources/js/Pages/Help/accountHelpContent.js": [], + "resources/js/Pages/Help/authHelpContent.js": [], + "resources/js/Pages/Help/cardsHelpContent.js": [], + "resources/js/Pages/Help/helpCenterContent.js": [], + "resources/js/Pages/Help/profileHelpContent.js": [], + "resources/js/Pages/Help/studioHelpContent.js": [], + "resources/js/Pages/Help/troubleshootingHelpContent.js": [], + "resources/js/Pages/Help/uploadHelpContent.js": [], + "resources/js/Pages/Help/worldsHelpContent.js": [], + "resources/js/Pages/Home/HomeBecauseYouLike.jsx": [], + "resources/js/Pages/Home/HomeCTA.jsx": [], + "resources/js/Pages/Home/HomeCategories.jsx": [], + "resources/js/Pages/Home/HomeCollections.jsx": [], + "resources/js/Pages/Home/HomeCreators.jsx": [], + "resources/js/Pages/Home/HomeFresh.jsx": [], + "resources/js/Pages/Home/HomeFromFollowing.jsx": [], + "resources/js/Pages/Home/HomeGroups.jsx": [], + "resources/js/Pages/Home/HomeHero.jsx": [], + "resources/js/Pages/Home/HomeMedalHighlights.jsx": [], + "resources/js/Pages/Home/HomeNews.jsx": [], + "resources/js/Pages/Home/HomePage.jsx": [], + "resources/js/Pages/Home/HomeRising.jsx": [], + "resources/js/Pages/Home/HomeSuggestedCreators.jsx": [], + "resources/js/Pages/Home/HomeTags.jsx": [], + "resources/js/Pages/Home/HomeTrending.jsx": [], + "resources/js/Pages/Home/HomeTrendingForYou.jsx": [], + "resources/js/Pages/Home/HomeWelcomeRow.jsx": [], + "resources/js/Pages/Home/HomeWorldSpotlight.jsx": [], + "resources/js/Pages/Leaderboard/LeaderboardPage.jsx": [], + "resources/js/Pages/Messages/Index.jsx": [], + "resources/js/Pages/Moderation/AiBiographyAdmin.jsx": [], + "resources/js/Pages/Moderation/ArtworkMaturityQueue.jsx": [], + "resources/js/Pages/News/NewsComments.jsx": [], + "resources/js/Pages/Profile/ProfileGallery.jsx": [], + "resources/js/Pages/Profile/ProfileShow.jsx": [], + "resources/js/Pages/Settings/ProfileEdit.jsx": [], + "resources/js/Pages/Studio/StudioActivity.jsx": [], + "resources/js/Pages/Studio/StudioAnalytics.jsx": [], + "resources/js/Pages/Studio/StudioArchived.jsx": [], + "resources/js/Pages/Studio/StudioArtworkAnalytics.jsx": [], + "resources/js/Pages/Studio/StudioArtworkEdit.jsx": [], + "resources/js/Pages/Studio/StudioArtworks.jsx": [], + "resources/js/Pages/Studio/StudioAssets.jsx": [], + "resources/js/Pages/Studio/StudioCalendar.jsx": [], + "resources/js/Pages/Studio/StudioCardAnalytics.jsx": [], + "resources/js/Pages/Studio/StudioCardEditor.jsx": [], + "resources/js/Pages/Studio/StudioCardsIndex.jsx": [], + "resources/js/Pages/Studio/StudioChallenges.jsx": [], + "resources/js/Pages/Studio/StudioCollections.jsx": [], + "resources/js/Pages/Studio/StudioComments.jsx": [], + "resources/js/Pages/Studio/StudioContentIndex.jsx": [], + "resources/js/Pages/Studio/StudioDashboard.jsx": [], + "resources/js/Pages/Studio/StudioDrafts.jsx": [], + "resources/js/Pages/Studio/StudioFeatured.jsx": [], + "resources/js/Pages/Studio/StudioFollowers.jsx": [], + "resources/js/Pages/Studio/StudioGroupActivity.jsx": [], + "resources/js/Pages/Studio/StudioGroupArtworks.jsx": [], + "resources/js/Pages/Studio/StudioGroupAssets.jsx": [], + "resources/js/Pages/Studio/StudioGroupChallengeEditor.jsx": [], + "resources/js/Pages/Studio/StudioGroupChallenges.jsx": [], + "resources/js/Pages/Studio/StudioGroupCollections.jsx": [], + "resources/js/Pages/Studio/StudioGroupCreate.jsx": [], + "resources/js/Pages/Studio/StudioGroupDashboard.jsx": [], + "resources/js/Pages/Studio/StudioGroupEventEditor.jsx": [], + "resources/js/Pages/Studio/StudioGroupEvents.jsx": [], + "resources/js/Pages/Studio/StudioGroupInvitations.jsx": [], + "resources/js/Pages/Studio/StudioGroupJoinRequests.jsx": [], + "resources/js/Pages/Studio/StudioGroupMembers.jsx": [], + "resources/js/Pages/Studio/StudioGroupPostEditor.jsx": [], + "resources/js/Pages/Studio/StudioGroupPosts.jsx": [], + "resources/js/Pages/Studio/StudioGroupProjectEditor.jsx": [], + "resources/js/Pages/Studio/StudioGroupProjects.jsx": [], + "resources/js/Pages/Studio/StudioGroupRecruitment.jsx": [], + "resources/js/Pages/Studio/StudioGroupReleaseEditor.jsx": [], + "resources/js/Pages/Studio/StudioGroupReleases.jsx": [], + "resources/js/Pages/Studio/StudioGroupReputation.jsx": [], + "resources/js/Pages/Studio/StudioGroupReviewQueue.jsx": [], + "resources/js/Pages/Studio/StudioGroupSettings.jsx": [], + "resources/js/Pages/Studio/StudioGroupsIndex.jsx": [], + "resources/js/Pages/Studio/StudioGrowth.jsx": [], + "resources/js/Pages/Studio/StudioInbox.jsx": [], + "resources/js/Pages/Studio/StudioNewsEditor.jsx": [], + "resources/js/Pages/Studio/StudioNewsIndex.jsx": [], + "resources/js/Pages/Studio/StudioNewsTaxonomies.jsx": [], + "resources/js/Pages/Studio/StudioPreferences.jsx": [], + "resources/js/Pages/Studio/StudioProfile.jsx": [], + "resources/js/Pages/Studio/StudioScheduled.jsx": [], + "resources/js/Pages/Studio/StudioSearch.jsx": [], + "resources/js/Pages/Studio/StudioSettings.jsx": [], + "resources/js/Pages/Studio/StudioStories.jsx": [], + "resources/js/Pages/Studio/StudioUploadQueue.jsx": [], + "resources/js/Pages/Studio/StudioWorldEditor.jsx": [], + "resources/js/Pages/Studio/StudioWorldsIndex.jsx": [], + "resources/js/Pages/Upload/Index.jsx": [], + "resources/js/Pages/World/WorldIndex.jsx": [], + "resources/js/Pages/World/WorldShow.jsx": [], + "resources/js/bootstrap.js": [], + "resources/js/components/Feed/FeedSidebar.jsx": [], + "resources/js/components/Feed/LinkPreviewCard.jsx": [], + "resources/js/components/Feed/PostActions.jsx": [], + "resources/js/components/Feed/PostCard.jsx": [], + "resources/js/components/Feed/PostCardSkeleton.jsx": [], + "resources/js/components/Feed/PostComments.jsx": [], + "resources/js/components/Feed/PostComposer.jsx": [], + "resources/js/components/Feed/ShareArtworkModal.jsx": [], + "resources/js/components/Feed/TagPeopleModal.jsx": [], + "resources/js/components/Feed/VisibilityPill.jsx": [], + "resources/js/components/Studio/ConfirmDangerModal.jsx": [], + "resources/js/components/Studio/StudioContentBrowser.jsx": [], + "resources/js/components/achievements/AchievementBadge.jsx": [], + "resources/js/components/achievements/AchievementCard.jsx": [], + "resources/js/components/achievements/AchievementsList.jsx": [], + "resources/js/components/admin/AdminUploadQueue.jsx": [], + "resources/js/components/admin/AdminUsernameQueue.jsx": [], + "resources/js/components/artwork/ArtworkActionBar.jsx": [], + "resources/js/components/artwork/ArtworkAwards.jsx": [], + "resources/js/components/artwork/ArtworkBreadcrumbs.jsx": [], + "resources/js/components/artwork/ArtworkCard.jsx": [], + "resources/js/components/artwork/ArtworkComments.jsx": [], + "resources/js/components/artwork/ArtworkDescription.jsx": [], + "resources/js/components/artwork/ArtworkDetailsPanel.jsx": [], + "resources/js/components/artwork/ArtworkEvolutionPanel.jsx": [], + "resources/js/components/artwork/ArtworkEvolutionSearchPicker.jsx": [], + "resources/js/components/artwork/ArtworkFormatBadges.jsx": [], + "resources/js/components/artwork/ArtworkGallery.jsx": [], + "resources/js/components/artwork/ArtworkGalleryGrid.jsx": [], + "resources/js/components/artwork/ArtworkHero.jsx": [], + "resources/js/components/artwork/ArtworkMediaStrip.jsx": [], + "resources/js/components/artwork/ArtworkMeta.jsx": [], + "resources/js/components/artwork/ArtworkRecommendationsRails.jsx": [], + "resources/js/components/artwork/ArtworkShareButton.jsx": [], + "resources/js/components/artwork/ArtworkShareModal.jsx": [ + "/build/assets/ArtworkShareModal-DEVyX6r2.js" + ], + "resources/js/components/artwork/ArtworkTags.jsx": [], + "resources/js/components/artwork/AuthorBioPopover.jsx": [], + "resources/js/components/artwork/CreatorSpotlight.jsx": [], + "resources/js/components/artwork/WorldParticipationBadge.jsx": [], + "resources/js/components/category/CategoryCard.jsx": [], + "resources/js/components/comments/CommentForm.jsx": [], + "resources/js/components/comments/CommentsFeed.jsx": [], + "resources/js/components/comments/EmojiPickerButton.jsx": [], + "resources/js/components/comments/ReactionBar.jsx": [], + "resources/js/components/common/EmojiMartPicker.jsx": [], + "resources/js/components/common/extractNativeEmoji.js": [], + "resources/js/components/common/isEventWithinNode.js": [], + "resources/js/components/common/loadEmojiMartData.js": [], + "resources/js/components/community/ActivityArtworkPreview.jsx": [], + "resources/js/components/community/ActivityAvatar.jsx": [], + "resources/js/components/community/ActivityCard.jsx": [], + "resources/js/components/community/ActivityFeed.jsx": [], + "resources/js/components/community/ActivityReactions.jsx": [], + "resources/js/components/docs/DocsCallout.jsx": [], + "resources/js/components/docs/DocsComparisonTable.jsx": [], + "resources/js/components/docs/DocsFaqAccordion.jsx": [], + "resources/js/components/docs/DocsSection.jsx": [], + "resources/js/components/docs/DocsSidebarNav.jsx": [], + "resources/js/components/docs/DocsStepList.jsx": [], + "resources/js/components/docs/FaqSearchInput.jsx": [], + "resources/js/components/docs/QuickstartChecklist.jsx": [], + "resources/js/components/docs/QuickstartNextSteps.jsx": [], + "resources/js/components/forum/AuthorBadge.jsx": [], + "resources/js/components/forum/Breadcrumbs.jsx": [], + "resources/js/components/forum/CategoryCard.jsx": [], + "resources/js/components/forum/EmojiPicker.jsx": [], + "resources/js/components/forum/MentionList.jsx": [], + "resources/js/components/forum/Pagination.jsx": [], + "resources/js/components/forum/PostCard.jsx": [], + "resources/js/components/forum/ReplyForm.jsx": [], + "resources/js/components/forum/RichTextEditor.jsx": [], + "resources/js/components/forum/ThreadRow.jsx": [], + "resources/js/components/forum/mentionSuggestion.js": [], + "resources/js/components/gallery/MasonryGallery.css": [], + "resources/js/components/gallery/MasonryGallery.jsx": [], + "resources/js/components/groups/GroupBadgePill.jsx": [], + "resources/js/components/groups/GroupBrowseFilters.jsx": [], + "resources/js/components/groups/GroupDiscoveryCard.jsx": [], + "resources/js/components/groups/GroupLeaderboardCard.jsx": [], + "resources/js/components/groups/GroupProfileSummary.jsx": [], + "resources/js/components/groups/GroupPromoCard.jsx": [], + "resources/js/components/groups/GroupStudioPromoCard.jsx": [], + "resources/js/components/groups/GroupSummaryPanel.jsx": [], + "resources/js/components/groups/GroupTrendingSection.jsx": [], + "resources/js/components/groups/groupStyles.js": [], + "resources/js/components/help/HelpGuideCard.jsx": [], + "resources/js/components/help/HelpSearchBar.jsx": [], + "resources/js/components/help/HelpSupportCta.jsx": [], + "resources/js/components/help/HelpTopicCard.jsx": [], + "resources/js/components/homepage/HomepageAnnouncement.jsx": [], + "resources/js/components/homepage/HomepageAnnouncementEditor.jsx": [], + "resources/js/components/leaderboard/LeaderboardItem.jsx": [], + "resources/js/components/leaderboard/LeaderboardList.jsx": [], + "resources/js/components/leaderboard/LeaderboardTabs.jsx": [], + "resources/js/components/messaging/ConversationList.jsx": [], + "resources/js/components/messaging/ConversationThread.jsx": [], + "resources/js/components/messaging/MessageBubble.jsx": [], + "resources/js/components/messaging/NewConversationModal.jsx": [], + "resources/js/components/nova-cards/NovaCardAutosaveIndicator.jsx": [], + "resources/js/components/nova-cards/NovaCardCanvasPreview.jsx": [], + "resources/js/components/nova-cards/NovaCardFontPicker.jsx": [], + "resources/js/components/nova-cards/NovaCardGradientPicker.jsx": [], + "resources/js/components/nova-cards/NovaCardPresetPicker.jsx": [], + "resources/js/components/nova-cards/NovaCardTemplatePicker.jsx": [], + "resources/js/components/profile/CreatorJourneySection.jsx": [], + "resources/js/components/profile/ProfileCoverEditor.jsx": [], + "resources/js/components/profile/ProfileGalleryPanel.jsx": [], + "resources/js/components/profile/ProfileHero.jsx": [], + "resources/js/components/profile/ProfileTabs.jsx": [], + "resources/js/components/profile/activity/ActivityCard.jsx": [], + "resources/js/components/profile/activity/ActivityFeed.jsx": [], + "resources/js/components/profile/activity/ActivityFilters.jsx": [], + "resources/js/components/profile/activity/ActivityTab.jsx": [], + "resources/js/components/profile/collections/CollectionCard.jsx": [], + "resources/js/components/profile/collections/CollectionEmptyState.jsx": [], + "resources/js/components/profile/collections/CollectionVisibilityBadge.jsx": [], + "resources/js/components/profile/tabs/TabAbout.jsx": [], + "resources/js/components/profile/tabs/TabAchievements.jsx": [], + "resources/js/components/profile/tabs/TabActivity.jsx": [], + "resources/js/components/profile/tabs/TabArtworks.jsx": [], + "resources/js/components/profile/tabs/TabCollections.jsx": [], + "resources/js/components/profile/tabs/TabFavourites.jsx": [], + "resources/js/components/profile/tabs/TabPosts.jsx": [], + "resources/js/components/profile/tabs/TabStats.jsx": [], + "resources/js/components/profile/tabs/TabStories.jsx": [], + "resources/js/components/profile/tabs/TabWorlds.jsx": [], + "resources/js/components/profile/worlds/ProfileWorldHistoryCard.jsx": [], + "resources/js/components/profile/worlds/ProfileWorldHistorySection.jsx": [], + "resources/js/components/profile/worlds/ProfileWorldHistorySummary.jsx": [], + "resources/js/components/profile/worlds/ProfileWorldRecognitionBadge.jsx": [], + "resources/js/components/profile/worlds/ProfileWorldStatsRow.jsx": [], + "resources/js/components/profile/worlds/ProfileWorldTimelineList.jsx": [], + "resources/js/components/security/TurnstileField.jsx": [], + "resources/js/components/seo/SeoHead.jsx": [], + "resources/js/components/social/CommentForm.jsx": [], + "resources/js/components/social/CommentList.jsx": [], + "resources/js/components/social/FollowButton.jsx": [], + "resources/js/components/social/FollowersPreview.jsx": [], + "resources/js/components/social/MutualFollowersBadge.jsx": [], + "resources/js/components/social/SuggestedUsersWidget.jsx": [], + "resources/js/components/tags/TagInput.jsx": [], + "resources/js/components/tags/TagPicker.jsx": [], + "resources/js/components/ui/Button.jsx": [], + "resources/js/components/ui/Checkbox.jsx": [], + "resources/js/components/ui/DateTimePicker.jsx": [], + "resources/js/components/ui/FormField.jsx": [], + "resources/js/components/ui/Modal.jsx": [], + "resources/js/components/ui/NovaConfirmDialog.jsx": [], + "resources/js/components/ui/NovaSelect.jsx": [], + "resources/js/components/ui/Radio.jsx": [], + "resources/js/components/ui/ShareToast.jsx": [], + "resources/js/components/ui/TextInput.jsx": [], + "resources/js/components/ui/Textarea.jsx": [], + "resources/js/components/ui/Toggle.jsx": [], + "resources/js/components/upload/ArchiveScreenshotPicker.jsx": [], + "resources/js/components/upload/PublishPanel.jsx": [], + "resources/js/components/upload/ReadinessChecklist.jsx": [], + "resources/js/components/upload/SchedulePublishPicker.jsx": [], + "resources/js/components/upload/ScreenshotUploader.jsx": [], + "resources/js/components/upload/StudioStatusBar.jsx": [], + "resources/js/components/upload/UploadActions.jsx": [], + "resources/js/components/upload/UploadDropzone.jsx": [], + "resources/js/components/upload/UploadOverlay.jsx": [], + "resources/js/components/upload/UploadSidebar.jsx": [], + "resources/js/components/upload/UploadWizard.jsx": [], + "resources/js/components/upload/steps/Step1FileUpload.jsx": [], + "resources/js/components/upload/steps/Step2Details.jsx": [], + "resources/js/components/upload/steps/Step3Publish.jsx": [], + "resources/js/components/viewer/ArtworkNavigator.jsx": [], + "resources/js/components/viewer/ArtworkViewer.jsx": [], + "resources/js/components/worlds/ActiveWorldSpotlight.jsx": [], + "resources/js/components/worlds/ChallengeWorldLinkBadge.jsx": [], + "resources/js/components/worlds/UploadWorldHighlightCard.jsx": [], + "resources/js/components/worlds/WorldArchiveNotice.jsx": [], + "resources/js/components/worlds/WorldCampaignMeta.jsx": [], + "resources/js/components/worlds/WorldCard.jsx": [], + "resources/js/components/worlds/WorldChallengeArtworkCard.jsx": [], + "resources/js/components/worlds/WorldChallengeEntriesRail.jsx": [], + "resources/js/components/worlds/WorldChallengeFinalistsGrid.jsx": [], + "resources/js/components/worlds/WorldChallengeMeta.jsx": [], + "resources/js/components/worlds/WorldChallengePanel.jsx": [], + "resources/js/components/worlds/WorldChallengeStatusBadge.jsx": [], + "resources/js/components/worlds/WorldChallengeWinnersPanel.jsx": [], + "resources/js/components/worlds/WorldCommunitySubmissionsSection.jsx": [], + "resources/js/components/worlds/WorldEndedBadge.jsx": [], + "resources/js/components/worlds/WorldFamilyCard.jsx": [], + "resources/js/components/worlds/WorldHero.jsx": [], + "resources/js/components/worlds/WorldRecapArticleCard.jsx": [], + "resources/js/components/worlds/WorldRecapCommunityHighlights.jsx": [], + "resources/js/components/worlds/WorldRecapCreatorsPanel.jsx": [], + "resources/js/components/worlds/WorldRecapFeaturedArtworks.jsx": [], + "resources/js/components/worlds/WorldRecapHero.jsx": [], + "resources/js/components/worlds/WorldRecapStatsGrid.jsx": [], + "resources/js/components/worlds/WorldRecapSummaryCard.jsx": [], + "resources/js/components/worlds/WorldSection.jsx": [], + "resources/js/components/worlds/WorldStatusBadge.jsx": [], + "resources/js/components/worlds/WorldSubmissionSelector.jsx": [], + "resources/js/components/worlds/WorldsIndexSection.jsx": [], + "resources/js/components/worlds/editor/WorldDuplicateActionMenu.jsx": [], + "resources/js/components/worlds/editor/WorldLinkedChallengePickerModal.jsx": [], + "resources/js/components/worlds/editor/WorldMediaUploadField.jsx": [], + "resources/js/components/worlds/editor/WorldMiniPreviewPanel.jsx": [], + "resources/js/components/worlds/editor/WorldPreviewButton.jsx": [], + "resources/js/components/worlds/editor/WorldRecapArticlePickerModal.jsx": [], + "resources/js/components/worlds/editor/WorldRecurrenceHelper.jsx": [], + "resources/js/components/worlds/editor/WorldRelationCard.jsx": [], + "resources/js/components/worlds/editor/WorldRelationPickerModal.jsx": [], + "resources/js/components/worlds/editor/WorldSectionToggleList.jsx": [], + "resources/js/components/worlds/editor/WorldSummaryCard.jsx": [], + "resources/js/components/worlds/editor/WorldThemePresetHelper.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsChallengePanel.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsEditionComparisonCard.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsMetricGrid.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsPanel.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsParticipationPanel.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsPortfolioPanel.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsSectionPerformance.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsSourceBreakdown.jsx": [], + "resources/js/components/worlds/editor/analytics/WorldAnalyticsSummaryCard.jsx": [], + "resources/js/components/worlds/editor/suggestions/WorldChallengeSuggestionPanel.jsx": [], + "resources/js/components/worlds/editor/suggestions/WorldSuggestionActions.jsx": [], + "resources/js/components/worlds/editor/suggestions/WorldSuggestionCard.jsx": [], + "resources/js/components/worlds/editor/suggestions/WorldSuggestionFilters.jsx": [], + "resources/js/components/worlds/editor/suggestions/WorldSuggestionReasonPills.jsx": [], + "resources/js/components/worlds/editor/suggestions/WorldSuggestionsPanel.jsx": [], + "resources/js/components/xp/LevelBadge.jsx": [], + "resources/js/components/xp/XPProgressBar.jsx": [], + "resources/js/config/tags.js": [], + "resources/js/hooks/upload/useFileValidation.js": [], + "resources/js/hooks/upload/useUploadMachine.js": [], + "resources/js/hooks/upload/useVisionTags.js": [], + "resources/js/hooks/useWebShare.js": [], + "resources/js/lib/security/botFingerprint.js": [], + "resources/js/lib/uploadAnalytics.js": [], + "resources/js/lib/uploadEndpoints.js": [], + "resources/js/lib/uploadNotices.js": [], + "resources/js/lib/uploadUtils.js": [], + "resources/js/lib/useNavContext.js": [], + "resources/js/lib/worldAnalytics.js": [], + "resources/js/ssr.jsx": [], + "resources/js/utils/emojiFlood.js": [], + "resources/js/utils/flagUrl.js": [], + "resources/js/utils/scheduleCountdown.js": [], + "resources/js/utils/studioEvents.js": [] +} \ No newline at end of file diff --git a/bootstrap/ssr/ssr.js b/bootstrap/ssr/ssr.js new file mode 100644 index 00000000..2616fd91 --- /dev/null +++ b/bootstrap/ssr/ssr.js @@ -0,0 +1,128661 @@ +import { g as getDefaultExportFromCjs, c as commonjsGlobal, r as reactExports, R as React, a as reactDomExports, u as useEditor, i as index_default, b as index_default$1, d as index_default$2, E as EditorContent, j as jsxRuntimeExports, e as requireReact, f as requireReactDom, h as ReactRenderer, k as index_default$3, l as index_default$4, m as index_default$5 } from "./assets/vendor-tiptap-DSw66HfW.js"; +import require$$0$1 from "util"; +import stream, { Readable } from "stream"; +import require$$1 from "path"; +import require$$3, { createServer } from "http"; +import require$$4 from "https"; +import require$$5 from "url"; +import require$$6 from "fs"; +import require$$1$1 from "crypto"; +import http2 from "http2"; +import require$$4$1 from "assert"; +import require$$1$2 from "tty"; +import require$$0$2 from "os"; +import zlib from "zlib"; +import { EventEmitter } from "events"; +import minproc from "node:process"; +import minpath from "node:path"; +import { fileURLToPath } from "node:url"; +import { t as tippy } from "./assets/vendor-tooltip-CIQaDNlG.js"; +import { P as Pusher, E as E$1 } from "./assets/vendor-realtime-cgmg5qQY.js"; +import { u as useReducedMotion, m as motion, A as AnimatePresence } from "./assets/vendor-motion-yDK3iGlC.js"; +import * as s from "process"; +import require$$2 from "async_hooks"; +import "buffer"; +import "child_process"; +import "net"; +import "tls"; +function bind(fn, thisArg) { + return function wrap2() { + return fn.apply(thisArg, arguments); + }; +} +const { toString: toString$2 } = Object.prototype; +const { getPrototypeOf } = Object; +const { iterator, toStringTag } = Symbol; +const kindOf = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString$2.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(/* @__PURE__ */ Object.create(null)); +const kindOfTest = (type2) => { + type2 = type2.toLowerCase(); + return (thing) => kindOf(thing) === type2; +}; +const typeOfTest = (type2) => (thing) => typeof thing === type2; +const { isArray } = Array; +const isUndefined = typeOfTest("undefined"); +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} +const isArrayBuffer = kindOfTest("ArrayBuffer"); +function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; +} +const isString = typeOfTest("string"); +const isFunction$1 = typeOfTest("function"); +const isNumber = typeOfTest("number"); +const isObject = (thing) => thing !== null && typeof thing === "object"; +const isBoolean = (thing) => thing === true || thing === false; +const isPlainObject$1 = (val) => { + if (kindOf(val) !== "object") { + return false; + } + const prototype2 = getPrototypeOf(val); + return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val); +}; +const isEmptyObject = (val) => { + if (!isObject(val) || isBuffer(val)) { + return false; + } + try { + return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; + } catch (e) { + return false; + } +}; +const isDate = kindOfTest("Date"); +const isFile = kindOfTest("File"); +const isReactNativeBlob = (value) => { + return !!(value && typeof value.uri !== "undefined"); +}; +const isReactNative = (formData) => formData && typeof formData.getParts !== "undefined"; +const isBlob = kindOfTest("Blob"); +const isFileList = kindOfTest("FileList"); +const isStream = (val) => isObject(val) && isFunction$1(val.pipe); +function getGlobal() { + if (typeof globalThis !== "undefined") return globalThis; + if (typeof self !== "undefined") return self; + if (typeof window !== "undefined") return window; + if (typeof global !== "undefined") return global; + return {}; +} +const G$1 = getGlobal(); +const FormDataCtor = typeof G$1.FormData !== "undefined" ? G$1.FormData : void 0; +const isFormData = (thing) => { + let kind; + return thing && (FormDataCtor && thing instanceof FormDataCtor || isFunction$1(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]")); +}; +const isURLSearchParams = kindOfTest("URLSearchParams"); +const [isReadableStream, isRequest, isResponse, isHeaders] = [ + "ReadableStream", + "Request", + "Response", + "Headers" +].map(kindOfTest); +const trim = (str) => { + return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); +}; +function forEach(obj, fn, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i; + let l; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray(obj)) { + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + if (isBuffer(obj)) { + return; + } + const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys2.length; + let key; + for (i = 0; i < len; i++) { + key = keys2[i]; + fn.call(null, obj[key], key, obj); + } + } +} +function findKey(obj, key) { + if (isBuffer(obj)) { + return null; + } + key = key.toLowerCase(); + const keys2 = Object.keys(obj); + let i = keys2.length; + let _key; + while (i-- > 0) { + _key = keys2[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} +const _global = (() => { + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; +})(); +const isContextDefined = (context) => !isUndefined(context) && context !== _global; +function merge$1() { + const { caseless, skipUndefined } = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + if (key === "__proto__" || key === "constructor" || key === "prototype") { + return; + } + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject$1(result[targetKey]) && isPlainObject$1(val)) { + result[targetKey] = merge$1(result[targetKey], val); + } else if (isPlainObject$1(val)) { + result[targetKey] = merge$1({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else if (!skipUndefined || !isUndefined(val)) { + result[targetKey] = val; + } + }; + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} +const extend$2 = (a, b2, thisArg, { allOwnKeys } = {}) => { + forEach( + b2, + (val, key) => { + if (thisArg && isFunction$1(val)) { + Object.defineProperty(a, key, { + value: bind(val, thisArg), + writable: true, + enumerable: true, + configurable: true + }); + } else { + Object.defineProperty(a, key, { + value: val, + writable: true, + enumerable: true, + configurable: true + }); + } + }, + { allOwnKeys } + ); + return a; +}; +const stripBOM = (content2) => { + if (content2.charCodeAt(0) === 65279) { + content2 = content2.slice(1); + } + return content2; +}; +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + Object.defineProperty(constructor.prototype, "constructor", { + value: constructor, + writable: true, + enumerable: false, + configurable: true + }); + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; +const toFlatObject = (sourceObj, destObj, filter2, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter2 !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; +}; +const endsWith = (str, searchString, position2) => { + str = String(str); + if (position2 === void 0 || position2 > str.length) { + position2 = str.length; + } + position2 -= searchString.length; + const lastIndex = str.indexOf(searchString, position2); + return lastIndex !== -1 && lastIndex === position2; +}; +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; +const isTypedArray = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); +const forEachEntry = (obj, fn) => { + const generator = obj && obj[iterator]; + const _iterator = generator.call(obj); + let result; + while ((result = _iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; +const matchAll = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; +}; +const isHTMLForm = kindOfTest("HTMLFormElement"); +const toCamelCase = (str) => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + }); +}; +const hasOwnProperty$1 = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); +const isRegExp = kindOfTest("RegExp"); +const reduceDescriptors = (obj, reducer2) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach(descriptors, (descriptor, name2) => { + let ret; + if ((ret = reducer2(descriptor, name2, obj)) !== false) { + reducedDescriptors[name2] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); +}; +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name2) => { + if (isFunction$1(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) { + return false; + } + const value = obj[name2]; + if (!isFunction$1(value)) return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name2 + "'"); + }; + } + }); +}; +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + const define = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + return obj; +}; +const noop = () => { +}; +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +}; +function isSpecCompliantForm(thing) { + return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]); +} +const toJSONObject = (obj) => { + const stack = new Array(10); + const visit2 = (source, i) => { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (isBuffer(source)) { + return source; + } + if (!("toJSON" in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + forEach(source, (value, key) => { + const reducedValue = visit2(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = void 0; + return target; + } + } + return source; + }; + return visit2(obj, 0); +}; +const isAsyncFn = kindOfTest("AsyncFunction"); +const isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch); +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener( + "message", + ({ source, data }) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, + false + ); + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + }; + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})(typeof setImmediate === "function", isFunction$1(_global.postMessage)); +const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate; +const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]); +const utils$2 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject: isPlainObject$1, + isEmptyObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isReactNativeBlob, + isReactNative, + isBlob, + isRegExp, + isFunction: isFunction$1, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge: merge$1, + extend: extend$2, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty: hasOwnProperty$1, + hasOwnProp: hasOwnProperty$1, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap, + isIterable +}; +let AxiosError$1 = class AxiosError extends Error { + static from(error, code2, config, request, response, customProps) { + const axiosError = new AxiosError(error.message, code2 || error.code, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + if (error.status != null && axiosError.status == null) { + axiosError.status = error.status; + } + customProps && Object.assign(axiosError, customProps); + return axiosError; + } + /** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ + constructor(message, code2, config, request, response) { + super(message); + Object.defineProperty(this, "message", { + value: message, + enumerable: true, + writable: true, + configurable: true + }); + this.name = "AxiosError"; + this.isAxiosError = true; + code2 && (this.code = code2); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status; + } + } + toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$2.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}; +AxiosError$1.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; +AxiosError$1.ERR_BAD_OPTION = "ERR_BAD_OPTION"; +AxiosError$1.ECONNABORTED = "ECONNABORTED"; +AxiosError$1.ETIMEDOUT = "ETIMEDOUT"; +AxiosError$1.ERR_NETWORK = "ERR_NETWORK"; +AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; +AxiosError$1.ERR_DEPRECATED = "ERR_DEPRECATED"; +AxiosError$1.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; +AxiosError$1.ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; +AxiosError$1.ERR_CANCELED = "ERR_CANCELED"; +AxiosError$1.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; +AxiosError$1.ERR_INVALID_URL = "ERR_INVALID_URL"; +var delayed_stream; +var hasRequiredDelayed_stream; +function requireDelayed_stream() { + if (hasRequiredDelayed_stream) return delayed_stream; + hasRequiredDelayed_stream = 1; + var Stream = stream.Stream; + var util = require$$0$1; + delayed_stream = DelayedStream; + function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; + } + util.inherits(DelayedStream, Stream); + DelayedStream.create = function(source, options) { + var delayedStream = new this(); + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + delayedStream.source = source; + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + source.on("error", function() { + }); + if (delayedStream.pauseStream) { + source.pause(); + } + return delayedStream; + }; + Object.defineProperty(DelayedStream.prototype, "readable", { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } + }); + DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); + }; + DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + this.source.resume(); + }; + DelayedStream.prototype.pause = function() { + this.source.pause(); + }; + DelayedStream.prototype.release = function() { + this._released = true; + this._bufferedEvents.forEach((function(args) { + this.emit.apply(this, args); + }).bind(this)); + this._bufferedEvents = []; + }; + DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; + }; + DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + if (args[0] === "data") { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + this._bufferedEvents.push(args); + }; + DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + if (this.dataSize <= this.maxDataSize) { + return; + } + this._maxDataSizeExceeded = true; + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this.emit("error", new Error(message)); + }; + return delayed_stream; +} +var combined_stream; +var hasRequiredCombined_stream; +function requireCombined_stream() { + if (hasRequiredCombined_stream) return combined_stream; + hasRequiredCombined_stream = 1; + var util = require$$0$1; + var Stream = stream.Stream; + var DelayedStream = requireDelayed_stream(); + combined_stream = CombinedStream; + function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; + } + util.inherits(CombinedStream, Stream); + CombinedStream.create = function(options) { + var combinedStream = new this(); + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + return combinedStream; + }; + CombinedStream.isStreamLike = function(stream2) { + return typeof stream2 !== "function" && typeof stream2 !== "string" && typeof stream2 !== "boolean" && typeof stream2 !== "number" && !Buffer.isBuffer(stream2); + }; + CombinedStream.prototype.append = function(stream2) { + var isStreamLike = CombinedStream.isStreamLike(stream2); + if (isStreamLike) { + if (!(stream2 instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream2, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams + }); + stream2.on("data", this._checkDataSize.bind(this)); + stream2 = newStream; + } + this._handleErrors(stream2); + if (this.pauseStreams) { + stream2.pause(); + } + } + this._streams.push(stream2); + return this; + }; + CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; + }; + CombinedStream.prototype._getNext = function() { + this._currentStream = null; + if (this._insideLoop) { + this._pendingNext = true; + return; + } + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } + }; + CombinedStream.prototype._realGetNext = function() { + var stream2 = this._streams.shift(); + if (typeof stream2 == "undefined") { + this.end(); + return; + } + if (typeof stream2 !== "function") { + this._pipeNext(stream2); + return; + } + var getStream = stream2; + getStream((function(stream3) { + var isStreamLike = CombinedStream.isStreamLike(stream3); + if (isStreamLike) { + stream3.on("data", this._checkDataSize.bind(this)); + this._handleErrors(stream3); + } + this._pipeNext(stream3); + }).bind(this)); + }; + CombinedStream.prototype._pipeNext = function(stream2) { + this._currentStream = stream2; + var isStreamLike = CombinedStream.isStreamLike(stream2); + if (isStreamLike) { + stream2.on("end", this._getNext.bind(this)); + stream2.pipe(this, { end: false }); + return; + } + var value = stream2; + this.write(value); + this._getNext(); + }; + CombinedStream.prototype._handleErrors = function(stream2) { + var self2 = this; + stream2.on("error", function(err) { + self2._emitError(err); + }); + }; + CombinedStream.prototype.write = function(data) { + this.emit("data", data); + }; + CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause(); + this.emit("pause"); + }; + CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume(); + this.emit("resume"); + }; + CombinedStream.prototype.end = function() { + this._reset(); + this.emit("end"); + }; + CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit("close"); + }; + CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; + }; + CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this._emitError(new Error(message)); + }; + CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + var self2 = this; + this._streams.forEach(function(stream2) { + if (!stream2.dataSize) { + return; + } + self2.dataSize += stream2.dataSize; + }); + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } + }; + CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit("error", err); + }; + return combined_stream; +} +var mimeTypes = {}; +const require$$0 = { + "application/1d-interleaved-parityfec": { "source": "iana" }, + "application/3gpdash-qoe-report+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/3gpp-ims+xml": { "source": "iana", "compressible": true }, + "application/3gpphal+json": { "source": "iana", "compressible": true }, + "application/3gpphalforms+json": { "source": "iana", "compressible": true }, + "application/a2l": { "source": "iana" }, + "application/ace+cbor": { "source": "iana" }, + "application/activemessage": { "source": "iana" }, + "application/activity+json": { "source": "iana", "compressible": true }, + "application/alto-costmap+json": { "source": "iana", "compressible": true }, + "application/alto-costmapfilter+json": { "source": "iana", "compressible": true }, + "application/alto-directory+json": { "source": "iana", "compressible": true }, + "application/alto-endpointcost+json": { "source": "iana", "compressible": true }, + "application/alto-endpointcostparams+json": { "source": "iana", "compressible": true }, + "application/alto-endpointprop+json": { "source": "iana", "compressible": true }, + "application/alto-endpointpropparams+json": { "source": "iana", "compressible": true }, + "application/alto-error+json": { "source": "iana", "compressible": true }, + "application/alto-networkmap+json": { "source": "iana", "compressible": true }, + "application/alto-networkmapfilter+json": { "source": "iana", "compressible": true }, + "application/alto-updatestreamcontrol+json": { "source": "iana", "compressible": true }, + "application/alto-updatestreamparams+json": { "source": "iana", "compressible": true }, + "application/aml": { "source": "iana" }, + "application/andrew-inset": { "source": "iana", "extensions": ["ez"] }, + "application/applefile": { "source": "iana" }, + "application/applixware": { "source": "apache", "extensions": ["aw"] }, + "application/at+jwt": { "source": "iana" }, + "application/atf": { "source": "iana" }, + "application/atfx": { "source": "iana" }, + "application/atom+xml": { "source": "iana", "compressible": true, "extensions": ["atom"] }, + "application/atomcat+xml": { "source": "iana", "compressible": true, "extensions": ["atomcat"] }, + "application/atomdeleted+xml": { "source": "iana", "compressible": true, "extensions": ["atomdeleted"] }, + "application/atomicmail": { "source": "iana" }, + "application/atomsvc+xml": { "source": "iana", "compressible": true, "extensions": ["atomsvc"] }, + "application/atsc-dwd+xml": { "source": "iana", "compressible": true, "extensions": ["dwd"] }, + "application/atsc-dynamic-event-message": { "source": "iana" }, + "application/atsc-held+xml": { "source": "iana", "compressible": true, "extensions": ["held"] }, + "application/atsc-rdt+json": { "source": "iana", "compressible": true }, + "application/atsc-rsat+xml": { "source": "iana", "compressible": true, "extensions": ["rsat"] }, + "application/atxml": { "source": "iana" }, + "application/auth-policy+xml": { "source": "iana", "compressible": true }, + "application/bacnet-xdd+zip": { "source": "iana", "compressible": false }, + "application/batch-smtp": { "source": "iana" }, + "application/bdoc": { "compressible": false, "extensions": ["bdoc"] }, + "application/beep+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/calendar+json": { "source": "iana", "compressible": true }, + "application/calendar+xml": { "source": "iana", "compressible": true, "extensions": ["xcs"] }, + "application/call-completion": { "source": "iana" }, + "application/cals-1840": { "source": "iana" }, + "application/captive+json": { "source": "iana", "compressible": true }, + "application/cbor": { "source": "iana" }, + "application/cbor-seq": { "source": "iana" }, + "application/cccex": { "source": "iana" }, + "application/ccmp+xml": { "source": "iana", "compressible": true }, + "application/ccxml+xml": { "source": "iana", "compressible": true, "extensions": ["ccxml"] }, + "application/cdfx+xml": { "source": "iana", "compressible": true, "extensions": ["cdfx"] }, + "application/cdmi-capability": { "source": "iana", "extensions": ["cdmia"] }, + "application/cdmi-container": { "source": "iana", "extensions": ["cdmic"] }, + "application/cdmi-domain": { "source": "iana", "extensions": ["cdmid"] }, + "application/cdmi-object": { "source": "iana", "extensions": ["cdmio"] }, + "application/cdmi-queue": { "source": "iana", "extensions": ["cdmiq"] }, + "application/cdni": { "source": "iana" }, + "application/cea": { "source": "iana" }, + "application/cea-2018+xml": { "source": "iana", "compressible": true }, + "application/cellml+xml": { "source": "iana", "compressible": true }, + "application/cfw": { "source": "iana" }, + "application/city+json": { "source": "iana", "compressible": true }, + "application/clr": { "source": "iana" }, + "application/clue+xml": { "source": "iana", "compressible": true }, + "application/clue_info+xml": { "source": "iana", "compressible": true }, + "application/cms": { "source": "iana" }, + "application/cnrp+xml": { "source": "iana", "compressible": true }, + "application/coap-group+json": { "source": "iana", "compressible": true }, + "application/coap-payload": { "source": "iana" }, + "application/commonground": { "source": "iana" }, + "application/conference-info+xml": { "source": "iana", "compressible": true }, + "application/cose": { "source": "iana" }, + "application/cose-key": { "source": "iana" }, + "application/cose-key-set": { "source": "iana" }, + "application/cpl+xml": { "source": "iana", "compressible": true, "extensions": ["cpl"] }, + "application/csrattrs": { "source": "iana" }, + "application/csta+xml": { "source": "iana", "compressible": true }, + "application/cstadata+xml": { "source": "iana", "compressible": true }, + "application/csvm+json": { "source": "iana", "compressible": true }, + "application/cu-seeme": { "source": "apache", "extensions": ["cu"] }, + "application/cwt": { "source": "iana" }, + "application/cybercash": { "source": "iana" }, + "application/dart": { "compressible": true }, + "application/dash+xml": { "source": "iana", "compressible": true, "extensions": ["mpd"] }, + "application/dash-patch+xml": { "source": "iana", "compressible": true, "extensions": ["mpp"] }, + "application/dashdelta": { "source": "iana" }, + "application/davmount+xml": { "source": "iana", "compressible": true, "extensions": ["davmount"] }, + "application/dca-rft": { "source": "iana" }, + "application/dcd": { "source": "iana" }, + "application/dec-dx": { "source": "iana" }, + "application/dialog-info+xml": { "source": "iana", "compressible": true }, + "application/dicom": { "source": "iana" }, + "application/dicom+json": { "source": "iana", "compressible": true }, + "application/dicom+xml": { "source": "iana", "compressible": true }, + "application/dii": { "source": "iana" }, + "application/dit": { "source": "iana" }, + "application/dns": { "source": "iana" }, + "application/dns+json": { "source": "iana", "compressible": true }, + "application/dns-message": { "source": "iana" }, + "application/docbook+xml": { "source": "apache", "compressible": true, "extensions": ["dbk"] }, + "application/dots+cbor": { "source": "iana" }, + "application/dskpp+xml": { "source": "iana", "compressible": true }, + "application/dssc+der": { "source": "iana", "extensions": ["dssc"] }, + "application/dssc+xml": { "source": "iana", "compressible": true, "extensions": ["xdssc"] }, + "application/dvcs": { "source": "iana" }, + "application/ecmascript": { "source": "iana", "compressible": true, "extensions": ["es", "ecma"] }, + "application/edi-consent": { "source": "iana" }, + "application/edi-x12": { "source": "iana", "compressible": false }, + "application/edifact": { "source": "iana", "compressible": false }, + "application/efi": { "source": "iana" }, + "application/elm+json": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/elm+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.cap+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/emergencycalldata.comment+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.control+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.deviceinfo+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.ecall.msd": { "source": "iana" }, + "application/emergencycalldata.providerinfo+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.serviceinfo+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.subscriberinfo+xml": { "source": "iana", "compressible": true }, + "application/emergencycalldata.veds+xml": { "source": "iana", "compressible": true }, + "application/emma+xml": { "source": "iana", "compressible": true, "extensions": ["emma"] }, + "application/emotionml+xml": { "source": "iana", "compressible": true, "extensions": ["emotionml"] }, + "application/encaprtp": { "source": "iana" }, + "application/epp+xml": { "source": "iana", "compressible": true }, + "application/epub+zip": { "source": "iana", "compressible": false, "extensions": ["epub"] }, + "application/eshop": { "source": "iana" }, + "application/exi": { "source": "iana", "extensions": ["exi"] }, + "application/expect-ct-report+json": { "source": "iana", "compressible": true }, + "application/express": { "source": "iana", "extensions": ["exp"] }, + "application/fastinfoset": { "source": "iana" }, + "application/fastsoap": { "source": "iana" }, + "application/fdt+xml": { "source": "iana", "compressible": true, "extensions": ["fdt"] }, + "application/fhir+json": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/fhir+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/fido.trusted-apps+json": { "compressible": true }, + "application/fits": { "source": "iana" }, + "application/flexfec": { "source": "iana" }, + "application/font-sfnt": { "source": "iana" }, + "application/font-tdpfr": { "source": "iana", "extensions": ["pfr"] }, + "application/font-woff": { "source": "iana", "compressible": false }, + "application/framework-attributes+xml": { "source": "iana", "compressible": true }, + "application/geo+json": { "source": "iana", "compressible": true, "extensions": ["geojson"] }, + "application/geo+json-seq": { "source": "iana" }, + "application/geopackage+sqlite3": { "source": "iana" }, + "application/geoxacml+xml": { "source": "iana", "compressible": true }, + "application/gltf-buffer": { "source": "iana" }, + "application/gml+xml": { "source": "iana", "compressible": true, "extensions": ["gml"] }, + "application/gpx+xml": { "source": "apache", "compressible": true, "extensions": ["gpx"] }, + "application/gxf": { "source": "apache", "extensions": ["gxf"] }, + "application/gzip": { "source": "iana", "compressible": false, "extensions": ["gz"] }, + "application/h224": { "source": "iana" }, + "application/held+xml": { "source": "iana", "compressible": true }, + "application/hjson": { "extensions": ["hjson"] }, + "application/http": { "source": "iana" }, + "application/hyperstudio": { "source": "iana", "extensions": ["stk"] }, + "application/ibe-key-request+xml": { "source": "iana", "compressible": true }, + "application/ibe-pkg-reply+xml": { "source": "iana", "compressible": true }, + "application/ibe-pp-data": { "source": "iana" }, + "application/iges": { "source": "iana" }, + "application/im-iscomposing+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/index": { "source": "iana" }, + "application/index.cmd": { "source": "iana" }, + "application/index.obj": { "source": "iana" }, + "application/index.response": { "source": "iana" }, + "application/index.vnd": { "source": "iana" }, + "application/inkml+xml": { "source": "iana", "compressible": true, "extensions": ["ink", "inkml"] }, + "application/iotp": { "source": "iana" }, + "application/ipfix": { "source": "iana", "extensions": ["ipfix"] }, + "application/ipp": { "source": "iana" }, + "application/isup": { "source": "iana" }, + "application/its+xml": { "source": "iana", "compressible": true, "extensions": ["its"] }, + "application/java-archive": { "source": "apache", "compressible": false, "extensions": ["jar", "war", "ear"] }, + "application/java-serialized-object": { "source": "apache", "compressible": false, "extensions": ["ser"] }, + "application/java-vm": { "source": "apache", "compressible": false, "extensions": ["class"] }, + "application/javascript": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["js", "mjs"] }, + "application/jf2feed+json": { "source": "iana", "compressible": true }, + "application/jose": { "source": "iana" }, + "application/jose+json": { "source": "iana", "compressible": true }, + "application/jrd+json": { "source": "iana", "compressible": true }, + "application/jscalendar+json": { "source": "iana", "compressible": true }, + "application/json": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["json", "map"] }, + "application/json-patch+json": { "source": "iana", "compressible": true }, + "application/json-seq": { "source": "iana" }, + "application/json5": { "extensions": ["json5"] }, + "application/jsonml+json": { "source": "apache", "compressible": true, "extensions": ["jsonml"] }, + "application/jwk+json": { "source": "iana", "compressible": true }, + "application/jwk-set+json": { "source": "iana", "compressible": true }, + "application/jwt": { "source": "iana" }, + "application/kpml-request+xml": { "source": "iana", "compressible": true }, + "application/kpml-response+xml": { "source": "iana", "compressible": true }, + "application/ld+json": { "source": "iana", "compressible": true, "extensions": ["jsonld"] }, + "application/lgr+xml": { "source": "iana", "compressible": true, "extensions": ["lgr"] }, + "application/link-format": { "source": "iana" }, + "application/load-control+xml": { "source": "iana", "compressible": true }, + "application/lost+xml": { "source": "iana", "compressible": true, "extensions": ["lostxml"] }, + "application/lostsync+xml": { "source": "iana", "compressible": true }, + "application/lpf+zip": { "source": "iana", "compressible": false }, + "application/lxf": { "source": "iana" }, + "application/mac-binhex40": { "source": "iana", "extensions": ["hqx"] }, + "application/mac-compactpro": { "source": "apache", "extensions": ["cpt"] }, + "application/macwriteii": { "source": "iana" }, + "application/mads+xml": { "source": "iana", "compressible": true, "extensions": ["mads"] }, + "application/manifest+json": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["webmanifest"] }, + "application/marc": { "source": "iana", "extensions": ["mrc"] }, + "application/marcxml+xml": { "source": "iana", "compressible": true, "extensions": ["mrcx"] }, + "application/mathematica": { "source": "iana", "extensions": ["ma", "nb", "mb"] }, + "application/mathml+xml": { "source": "iana", "compressible": true, "extensions": ["mathml"] }, + "application/mathml-content+xml": { "source": "iana", "compressible": true }, + "application/mathml-presentation+xml": { "source": "iana", "compressible": true }, + "application/mbms-associated-procedure-description+xml": { "source": "iana", "compressible": true }, + "application/mbms-deregister+xml": { "source": "iana", "compressible": true }, + "application/mbms-envelope+xml": { "source": "iana", "compressible": true }, + "application/mbms-msk+xml": { "source": "iana", "compressible": true }, + "application/mbms-msk-response+xml": { "source": "iana", "compressible": true }, + "application/mbms-protection-description+xml": { "source": "iana", "compressible": true }, + "application/mbms-reception-report+xml": { "source": "iana", "compressible": true }, + "application/mbms-register+xml": { "source": "iana", "compressible": true }, + "application/mbms-register-response+xml": { "source": "iana", "compressible": true }, + "application/mbms-schedule+xml": { "source": "iana", "compressible": true }, + "application/mbms-user-service-description+xml": { "source": "iana", "compressible": true }, + "application/mbox": { "source": "iana", "extensions": ["mbox"] }, + "application/media-policy-dataset+xml": { "source": "iana", "compressible": true, "extensions": ["mpf"] }, + "application/media_control+xml": { "source": "iana", "compressible": true }, + "application/mediaservercontrol+xml": { "source": "iana", "compressible": true, "extensions": ["mscml"] }, + "application/merge-patch+json": { "source": "iana", "compressible": true }, + "application/metalink+xml": { "source": "apache", "compressible": true, "extensions": ["metalink"] }, + "application/metalink4+xml": { "source": "iana", "compressible": true, "extensions": ["meta4"] }, + "application/mets+xml": { "source": "iana", "compressible": true, "extensions": ["mets"] }, + "application/mf4": { "source": "iana" }, + "application/mikey": { "source": "iana" }, + "application/mipc": { "source": "iana" }, + "application/missing-blocks+cbor-seq": { "source": "iana" }, + "application/mmt-aei+xml": { "source": "iana", "compressible": true, "extensions": ["maei"] }, + "application/mmt-usd+xml": { "source": "iana", "compressible": true, "extensions": ["musd"] }, + "application/mods+xml": { "source": "iana", "compressible": true, "extensions": ["mods"] }, + "application/moss-keys": { "source": "iana" }, + "application/moss-signature": { "source": "iana" }, + "application/mosskey-data": { "source": "iana" }, + "application/mosskey-request": { "source": "iana" }, + "application/mp21": { "source": "iana", "extensions": ["m21", "mp21"] }, + "application/mp4": { "source": "iana", "extensions": ["mp4s", "m4p"] }, + "application/mpeg4-generic": { "source": "iana" }, + "application/mpeg4-iod": { "source": "iana" }, + "application/mpeg4-iod-xmt": { "source": "iana" }, + "application/mrb-consumer+xml": { "source": "iana", "compressible": true }, + "application/mrb-publish+xml": { "source": "iana", "compressible": true }, + "application/msc-ivr+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/msc-mixer+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/msword": { "source": "iana", "compressible": false, "extensions": ["doc", "dot"] }, + "application/mud+json": { "source": "iana", "compressible": true }, + "application/multipart-core": { "source": "iana" }, + "application/mxf": { "source": "iana", "extensions": ["mxf"] }, + "application/n-quads": { "source": "iana", "extensions": ["nq"] }, + "application/n-triples": { "source": "iana", "extensions": ["nt"] }, + "application/nasdata": { "source": "iana" }, + "application/news-checkgroups": { "source": "iana", "charset": "US-ASCII" }, + "application/news-groupinfo": { "source": "iana", "charset": "US-ASCII" }, + "application/news-transmission": { "source": "iana" }, + "application/nlsml+xml": { "source": "iana", "compressible": true }, + "application/node": { "source": "iana", "extensions": ["cjs"] }, + "application/nss": { "source": "iana" }, + "application/oauth-authz-req+jwt": { "source": "iana" }, + "application/oblivious-dns-message": { "source": "iana" }, + "application/ocsp-request": { "source": "iana" }, + "application/ocsp-response": { "source": "iana" }, + "application/octet-stream": { "source": "iana", "compressible": false, "extensions": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] }, + "application/oda": { "source": "iana", "extensions": ["oda"] }, + "application/odm+xml": { "source": "iana", "compressible": true }, + "application/odx": { "source": "iana" }, + "application/oebps-package+xml": { "source": "iana", "compressible": true, "extensions": ["opf"] }, + "application/ogg": { "source": "iana", "compressible": false, "extensions": ["ogx"] }, + "application/omdoc+xml": { "source": "apache", "compressible": true, "extensions": ["omdoc"] }, + "application/onenote": { "source": "apache", "extensions": ["onetoc", "onetoc2", "onetmp", "onepkg"] }, + "application/opc-nodeset+xml": { "source": "iana", "compressible": true }, + "application/oscore": { "source": "iana" }, + "application/oxps": { "source": "iana", "extensions": ["oxps"] }, + "application/p21": { "source": "iana" }, + "application/p21+zip": { "source": "iana", "compressible": false }, + "application/p2p-overlay+xml": { "source": "iana", "compressible": true, "extensions": ["relo"] }, + "application/parityfec": { "source": "iana" }, + "application/passport": { "source": "iana" }, + "application/patch-ops-error+xml": { "source": "iana", "compressible": true, "extensions": ["xer"] }, + "application/pdf": { "source": "iana", "compressible": false, "extensions": ["pdf"] }, + "application/pdx": { "source": "iana" }, + "application/pem-certificate-chain": { "source": "iana" }, + "application/pgp-encrypted": { "source": "iana", "compressible": false, "extensions": ["pgp"] }, + "application/pgp-keys": { "source": "iana", "extensions": ["asc"] }, + "application/pgp-signature": { "source": "iana", "extensions": ["asc", "sig"] }, + "application/pics-rules": { "source": "apache", "extensions": ["prf"] }, + "application/pidf+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/pidf-diff+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/pkcs10": { "source": "iana", "extensions": ["p10"] }, + "application/pkcs12": { "source": "iana" }, + "application/pkcs7-mime": { "source": "iana", "extensions": ["p7m", "p7c"] }, + "application/pkcs7-signature": { "source": "iana", "extensions": ["p7s"] }, + "application/pkcs8": { "source": "iana", "extensions": ["p8"] }, + "application/pkcs8-encrypted": { "source": "iana" }, + "application/pkix-attr-cert": { "source": "iana", "extensions": ["ac"] }, + "application/pkix-cert": { "source": "iana", "extensions": ["cer"] }, + "application/pkix-crl": { "source": "iana", "extensions": ["crl"] }, + "application/pkix-pkipath": { "source": "iana", "extensions": ["pkipath"] }, + "application/pkixcmp": { "source": "iana", "extensions": ["pki"] }, + "application/pls+xml": { "source": "iana", "compressible": true, "extensions": ["pls"] }, + "application/poc-settings+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/postscript": { "source": "iana", "compressible": true, "extensions": ["ai", "eps", "ps"] }, + "application/ppsp-tracker+json": { "source": "iana", "compressible": true }, + "application/problem+json": { "source": "iana", "compressible": true }, + "application/problem+xml": { "source": "iana", "compressible": true }, + "application/provenance+xml": { "source": "iana", "compressible": true, "extensions": ["provx"] }, + "application/prs.alvestrand.titrax-sheet": { "source": "iana" }, + "application/prs.cww": { "source": "iana", "extensions": ["cww"] }, + "application/prs.cyn": { "source": "iana", "charset": "7-BIT" }, + "application/prs.hpub+zip": { "source": "iana", "compressible": false }, + "application/prs.nprend": { "source": "iana" }, + "application/prs.plucker": { "source": "iana" }, + "application/prs.rdf-xml-crypt": { "source": "iana" }, + "application/prs.xsf+xml": { "source": "iana", "compressible": true }, + "application/pskc+xml": { "source": "iana", "compressible": true, "extensions": ["pskcxml"] }, + "application/pvd+json": { "source": "iana", "compressible": true }, + "application/qsig": { "source": "iana" }, + "application/raml+yaml": { "compressible": true, "extensions": ["raml"] }, + "application/raptorfec": { "source": "iana" }, + "application/rdap+json": { "source": "iana", "compressible": true }, + "application/rdf+xml": { "source": "iana", "compressible": true, "extensions": ["rdf", "owl"] }, + "application/reginfo+xml": { "source": "iana", "compressible": true, "extensions": ["rif"] }, + "application/relax-ng-compact-syntax": { "source": "iana", "extensions": ["rnc"] }, + "application/remote-printing": { "source": "iana" }, + "application/reputon+json": { "source": "iana", "compressible": true }, + "application/resource-lists+xml": { "source": "iana", "compressible": true, "extensions": ["rl"] }, + "application/resource-lists-diff+xml": { "source": "iana", "compressible": true, "extensions": ["rld"] }, + "application/rfc+xml": { "source": "iana", "compressible": true }, + "application/riscos": { "source": "iana" }, + "application/rlmi+xml": { "source": "iana", "compressible": true }, + "application/rls-services+xml": { "source": "iana", "compressible": true, "extensions": ["rs"] }, + "application/route-apd+xml": { "source": "iana", "compressible": true, "extensions": ["rapd"] }, + "application/route-s-tsid+xml": { "source": "iana", "compressible": true, "extensions": ["sls"] }, + "application/route-usd+xml": { "source": "iana", "compressible": true, "extensions": ["rusd"] }, + "application/rpki-ghostbusters": { "source": "iana", "extensions": ["gbr"] }, + "application/rpki-manifest": { "source": "iana", "extensions": ["mft"] }, + "application/rpki-publication": { "source": "iana" }, + "application/rpki-roa": { "source": "iana", "extensions": ["roa"] }, + "application/rpki-updown": { "source": "iana" }, + "application/rsd+xml": { "source": "apache", "compressible": true, "extensions": ["rsd"] }, + "application/rss+xml": { "source": "apache", "compressible": true, "extensions": ["rss"] }, + "application/rtf": { "source": "iana", "compressible": true, "extensions": ["rtf"] }, + "application/rtploopback": { "source": "iana" }, + "application/rtx": { "source": "iana" }, + "application/samlassertion+xml": { "source": "iana", "compressible": true }, + "application/samlmetadata+xml": { "source": "iana", "compressible": true }, + "application/sarif+json": { "source": "iana", "compressible": true }, + "application/sarif-external-properties+json": { "source": "iana", "compressible": true }, + "application/sbe": { "source": "iana" }, + "application/sbml+xml": { "source": "iana", "compressible": true, "extensions": ["sbml"] }, + "application/scaip+xml": { "source": "iana", "compressible": true }, + "application/scim+json": { "source": "iana", "compressible": true }, + "application/scvp-cv-request": { "source": "iana", "extensions": ["scq"] }, + "application/scvp-cv-response": { "source": "iana", "extensions": ["scs"] }, + "application/scvp-vp-request": { "source": "iana", "extensions": ["spq"] }, + "application/scvp-vp-response": { "source": "iana", "extensions": ["spp"] }, + "application/sdp": { "source": "iana", "extensions": ["sdp"] }, + "application/secevent+jwt": { "source": "iana" }, + "application/senml+cbor": { "source": "iana" }, + "application/senml+json": { "source": "iana", "compressible": true }, + "application/senml+xml": { "source": "iana", "compressible": true, "extensions": ["senmlx"] }, + "application/senml-etch+cbor": { "source": "iana" }, + "application/senml-etch+json": { "source": "iana", "compressible": true }, + "application/senml-exi": { "source": "iana" }, + "application/sensml+cbor": { "source": "iana" }, + "application/sensml+json": { "source": "iana", "compressible": true }, + "application/sensml+xml": { "source": "iana", "compressible": true, "extensions": ["sensmlx"] }, + "application/sensml-exi": { "source": "iana" }, + "application/sep+xml": { "source": "iana", "compressible": true }, + "application/sep-exi": { "source": "iana" }, + "application/session-info": { "source": "iana" }, + "application/set-payment": { "source": "iana" }, + "application/set-payment-initiation": { "source": "iana", "extensions": ["setpay"] }, + "application/set-registration": { "source": "iana" }, + "application/set-registration-initiation": { "source": "iana", "extensions": ["setreg"] }, + "application/sgml": { "source": "iana" }, + "application/sgml-open-catalog": { "source": "iana" }, + "application/shf+xml": { "source": "iana", "compressible": true, "extensions": ["shf"] }, + "application/sieve": { "source": "iana", "extensions": ["siv", "sieve"] }, + "application/simple-filter+xml": { "source": "iana", "compressible": true }, + "application/simple-message-summary": { "source": "iana" }, + "application/simplesymbolcontainer": { "source": "iana" }, + "application/sipc": { "source": "iana" }, + "application/slate": { "source": "iana" }, + "application/smil": { "source": "iana" }, + "application/smil+xml": { "source": "iana", "compressible": true, "extensions": ["smi", "smil"] }, + "application/smpte336m": { "source": "iana" }, + "application/soap+fastinfoset": { "source": "iana" }, + "application/soap+xml": { "source": "iana", "compressible": true }, + "application/sparql-query": { "source": "iana", "extensions": ["rq"] }, + "application/sparql-results+xml": { "source": "iana", "compressible": true, "extensions": ["srx"] }, + "application/spdx+json": { "source": "iana", "compressible": true }, + "application/spirits-event+xml": { "source": "iana", "compressible": true }, + "application/sql": { "source": "iana" }, + "application/srgs": { "source": "iana", "extensions": ["gram"] }, + "application/srgs+xml": { "source": "iana", "compressible": true, "extensions": ["grxml"] }, + "application/sru+xml": { "source": "iana", "compressible": true, "extensions": ["sru"] }, + "application/ssdl+xml": { "source": "apache", "compressible": true, "extensions": ["ssdl"] }, + "application/ssml+xml": { "source": "iana", "compressible": true, "extensions": ["ssml"] }, + "application/stix+json": { "source": "iana", "compressible": true }, + "application/swid+xml": { "source": "iana", "compressible": true, "extensions": ["swidtag"] }, + "application/tamp-apex-update": { "source": "iana" }, + "application/tamp-apex-update-confirm": { "source": "iana" }, + "application/tamp-community-update": { "source": "iana" }, + "application/tamp-community-update-confirm": { "source": "iana" }, + "application/tamp-error": { "source": "iana" }, + "application/tamp-sequence-adjust": { "source": "iana" }, + "application/tamp-sequence-adjust-confirm": { "source": "iana" }, + "application/tamp-status-query": { "source": "iana" }, + "application/tamp-status-response": { "source": "iana" }, + "application/tamp-update": { "source": "iana" }, + "application/tamp-update-confirm": { "source": "iana" }, + "application/tar": { "compressible": true }, + "application/taxii+json": { "source": "iana", "compressible": true }, + "application/td+json": { "source": "iana", "compressible": true }, + "application/tei+xml": { "source": "iana", "compressible": true, "extensions": ["tei", "teicorpus"] }, + "application/tetra_isi": { "source": "iana" }, + "application/thraud+xml": { "source": "iana", "compressible": true, "extensions": ["tfi"] }, + "application/timestamp-query": { "source": "iana" }, + "application/timestamp-reply": { "source": "iana" }, + "application/timestamped-data": { "source": "iana", "extensions": ["tsd"] }, + "application/tlsrpt+gzip": { "source": "iana" }, + "application/tlsrpt+json": { "source": "iana", "compressible": true }, + "application/tnauthlist": { "source": "iana" }, + "application/token-introspection+jwt": { "source": "iana" }, + "application/toml": { "compressible": true, "extensions": ["toml"] }, + "application/trickle-ice-sdpfrag": { "source": "iana" }, + "application/trig": { "source": "iana", "extensions": ["trig"] }, + "application/ttml+xml": { "source": "iana", "compressible": true, "extensions": ["ttml"] }, + "application/tve-trigger": { "source": "iana" }, + "application/tzif": { "source": "iana" }, + "application/tzif-leap": { "source": "iana" }, + "application/ubjson": { "compressible": false, "extensions": ["ubj"] }, + "application/ulpfec": { "source": "iana" }, + "application/urc-grpsheet+xml": { "source": "iana", "compressible": true }, + "application/urc-ressheet+xml": { "source": "iana", "compressible": true, "extensions": ["rsheet"] }, + "application/urc-targetdesc+xml": { "source": "iana", "compressible": true, "extensions": ["td"] }, + "application/urc-uisocketdesc+xml": { "source": "iana", "compressible": true }, + "application/vcard+json": { "source": "iana", "compressible": true }, + "application/vcard+xml": { "source": "iana", "compressible": true }, + "application/vemmi": { "source": "iana" }, + "application/vividence.scriptfile": { "source": "apache" }, + "application/vnd.1000minds.decision-model+xml": { "source": "iana", "compressible": true, "extensions": ["1km"] }, + "application/vnd.3gpp-prose+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp-prose-pc3ch+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp-v2x-local-service-information": { "source": "iana" }, + "application/vnd.3gpp.5gnas": { "source": "iana" }, + "application/vnd.3gpp.access-transfer-events+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.bsf+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.gmop+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.gtpc": { "source": "iana" }, + "application/vnd.3gpp.interworking-data": { "source": "iana" }, + "application/vnd.3gpp.lpp": { "source": "iana" }, + "application/vnd.3gpp.mc-signalling-ear": { "source": "iana" }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcdata-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcdata-payload": { "source": "iana" }, + "application/vnd.3gpp.mcdata-service-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcdata-signalling": { "source": "iana" }, + "application/vnd.3gpp.mcdata-ue-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcdata-user-profile+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-floor-request+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-location-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-service-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-signed+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-ue-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcptt-user-profile+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-location-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-service-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.mid-call+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.ngap": { "source": "iana" }, + "application/vnd.3gpp.pfcp": { "source": "iana" }, + "application/vnd.3gpp.pic-bw-large": { "source": "iana", "extensions": ["plb"] }, + "application/vnd.3gpp.pic-bw-small": { "source": "iana", "extensions": ["psb"] }, + "application/vnd.3gpp.pic-bw-var": { "source": "iana", "extensions": ["pvb"] }, + "application/vnd.3gpp.s1ap": { "source": "iana" }, + "application/vnd.3gpp.sms": { "source": "iana" }, + "application/vnd.3gpp.sms+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.srvcc-ext+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.srvcc-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.state-and-event-info+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp.ussd+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp2.bcmcsinfo+xml": { "source": "iana", "compressible": true }, + "application/vnd.3gpp2.sms": { "source": "iana" }, + "application/vnd.3gpp2.tcap": { "source": "iana", "extensions": ["tcap"] }, + "application/vnd.3lightssoftware.imagescal": { "source": "iana" }, + "application/vnd.3m.post-it-notes": { "source": "iana", "extensions": ["pwn"] }, + "application/vnd.accpac.simply.aso": { "source": "iana", "extensions": ["aso"] }, + "application/vnd.accpac.simply.imp": { "source": "iana", "extensions": ["imp"] }, + "application/vnd.acucobol": { "source": "iana", "extensions": ["acu"] }, + "application/vnd.acucorp": { "source": "iana", "extensions": ["atc", "acutc"] }, + "application/vnd.adobe.air-application-installer-package+zip": { "source": "apache", "compressible": false, "extensions": ["air"] }, + "application/vnd.adobe.flash.movie": { "source": "iana" }, + "application/vnd.adobe.formscentral.fcdt": { "source": "iana", "extensions": ["fcdt"] }, + "application/vnd.adobe.fxp": { "source": "iana", "extensions": ["fxp", "fxpl"] }, + "application/vnd.adobe.partial-upload": { "source": "iana" }, + "application/vnd.adobe.xdp+xml": { "source": "iana", "compressible": true, "extensions": ["xdp"] }, + "application/vnd.adobe.xfdf": { "source": "iana", "extensions": ["xfdf"] }, + "application/vnd.aether.imp": { "source": "iana" }, + "application/vnd.afpc.afplinedata": { "source": "iana" }, + "application/vnd.afpc.afplinedata-pagedef": { "source": "iana" }, + "application/vnd.afpc.cmoca-cmresource": { "source": "iana" }, + "application/vnd.afpc.foca-charset": { "source": "iana" }, + "application/vnd.afpc.foca-codedfont": { "source": "iana" }, + "application/vnd.afpc.foca-codepage": { "source": "iana" }, + "application/vnd.afpc.modca": { "source": "iana" }, + "application/vnd.afpc.modca-cmtable": { "source": "iana" }, + "application/vnd.afpc.modca-formdef": { "source": "iana" }, + "application/vnd.afpc.modca-mediummap": { "source": "iana" }, + "application/vnd.afpc.modca-objectcontainer": { "source": "iana" }, + "application/vnd.afpc.modca-overlay": { "source": "iana" }, + "application/vnd.afpc.modca-pagesegment": { "source": "iana" }, + "application/vnd.age": { "source": "iana", "extensions": ["age"] }, + "application/vnd.ah-barcode": { "source": "iana" }, + "application/vnd.ahead.space": { "source": "iana", "extensions": ["ahead"] }, + "application/vnd.airzip.filesecure.azf": { "source": "iana", "extensions": ["azf"] }, + "application/vnd.airzip.filesecure.azs": { "source": "iana", "extensions": ["azs"] }, + "application/vnd.amadeus+json": { "source": "iana", "compressible": true }, + "application/vnd.amazon.ebook": { "source": "apache", "extensions": ["azw"] }, + "application/vnd.amazon.mobi8-ebook": { "source": "iana" }, + "application/vnd.americandynamics.acc": { "source": "iana", "extensions": ["acc"] }, + "application/vnd.amiga.ami": { "source": "iana", "extensions": ["ami"] }, + "application/vnd.amundsen.maze+xml": { "source": "iana", "compressible": true }, + "application/vnd.android.ota": { "source": "iana" }, + "application/vnd.android.package-archive": { "source": "apache", "compressible": false, "extensions": ["apk"] }, + "application/vnd.anki": { "source": "iana" }, + "application/vnd.anser-web-certificate-issue-initiation": { "source": "iana", "extensions": ["cii"] }, + "application/vnd.anser-web-funds-transfer-initiation": { "source": "apache", "extensions": ["fti"] }, + "application/vnd.antix.game-component": { "source": "iana", "extensions": ["atx"] }, + "application/vnd.apache.arrow.file": { "source": "iana" }, + "application/vnd.apache.arrow.stream": { "source": "iana" }, + "application/vnd.apache.thrift.binary": { "source": "iana" }, + "application/vnd.apache.thrift.compact": { "source": "iana" }, + "application/vnd.apache.thrift.json": { "source": "iana" }, + "application/vnd.api+json": { "source": "iana", "compressible": true }, + "application/vnd.aplextor.warrp+json": { "source": "iana", "compressible": true }, + "application/vnd.apothekende.reservation+json": { "source": "iana", "compressible": true }, + "application/vnd.apple.installer+xml": { "source": "iana", "compressible": true, "extensions": ["mpkg"] }, + "application/vnd.apple.keynote": { "source": "iana", "extensions": ["key"] }, + "application/vnd.apple.mpegurl": { "source": "iana", "extensions": ["m3u8"] }, + "application/vnd.apple.numbers": { "source": "iana", "extensions": ["numbers"] }, + "application/vnd.apple.pages": { "source": "iana", "extensions": ["pages"] }, + "application/vnd.apple.pkpass": { "compressible": false, "extensions": ["pkpass"] }, + "application/vnd.arastra.swi": { "source": "iana" }, + "application/vnd.aristanetworks.swi": { "source": "iana", "extensions": ["swi"] }, + "application/vnd.artisan+json": { "source": "iana", "compressible": true }, + "application/vnd.artsquare": { "source": "iana" }, + "application/vnd.astraea-software.iota": { "source": "iana", "extensions": ["iota"] }, + "application/vnd.audiograph": { "source": "iana", "extensions": ["aep"] }, + "application/vnd.autopackage": { "source": "iana" }, + "application/vnd.avalon+json": { "source": "iana", "compressible": true }, + "application/vnd.avistar+xml": { "source": "iana", "compressible": true }, + "application/vnd.balsamiq.bmml+xml": { "source": "iana", "compressible": true, "extensions": ["bmml"] }, + "application/vnd.balsamiq.bmpr": { "source": "iana" }, + "application/vnd.banana-accounting": { "source": "iana" }, + "application/vnd.bbf.usp.error": { "source": "iana" }, + "application/vnd.bbf.usp.msg": { "source": "iana" }, + "application/vnd.bbf.usp.msg+json": { "source": "iana", "compressible": true }, + "application/vnd.bekitzur-stech+json": { "source": "iana", "compressible": true }, + "application/vnd.bint.med-content": { "source": "iana" }, + "application/vnd.biopax.rdf+xml": { "source": "iana", "compressible": true }, + "application/vnd.blink-idb-value-wrapper": { "source": "iana" }, + "application/vnd.blueice.multipass": { "source": "iana", "extensions": ["mpm"] }, + "application/vnd.bluetooth.ep.oob": { "source": "iana" }, + "application/vnd.bluetooth.le.oob": { "source": "iana" }, + "application/vnd.bmi": { "source": "iana", "extensions": ["bmi"] }, + "application/vnd.bpf": { "source": "iana" }, + "application/vnd.bpf3": { "source": "iana" }, + "application/vnd.businessobjects": { "source": "iana", "extensions": ["rep"] }, + "application/vnd.byu.uapi+json": { "source": "iana", "compressible": true }, + "application/vnd.cab-jscript": { "source": "iana" }, + "application/vnd.canon-cpdl": { "source": "iana" }, + "application/vnd.canon-lips": { "source": "iana" }, + "application/vnd.capasystems-pg+json": { "source": "iana", "compressible": true }, + "application/vnd.cendio.thinlinc.clientconf": { "source": "iana" }, + "application/vnd.century-systems.tcp_stream": { "source": "iana" }, + "application/vnd.chemdraw+xml": { "source": "iana", "compressible": true, "extensions": ["cdxml"] }, + "application/vnd.chess-pgn": { "source": "iana" }, + "application/vnd.chipnuts.karaoke-mmd": { "source": "iana", "extensions": ["mmd"] }, + "application/vnd.ciedi": { "source": "iana" }, + "application/vnd.cinderella": { "source": "iana", "extensions": ["cdy"] }, + "application/vnd.cirpack.isdn-ext": { "source": "iana" }, + "application/vnd.citationstyles.style+xml": { "source": "iana", "compressible": true, "extensions": ["csl"] }, + "application/vnd.claymore": { "source": "iana", "extensions": ["cla"] }, + "application/vnd.cloanto.rp9": { "source": "iana", "extensions": ["rp9"] }, + "application/vnd.clonk.c4group": { "source": "iana", "extensions": ["c4g", "c4d", "c4f", "c4p", "c4u"] }, + "application/vnd.cluetrust.cartomobile-config": { "source": "iana", "extensions": ["c11amc"] }, + "application/vnd.cluetrust.cartomobile-config-pkg": { "source": "iana", "extensions": ["c11amz"] }, + "application/vnd.coffeescript": { "source": "iana" }, + "application/vnd.collabio.xodocuments.document": { "source": "iana" }, + "application/vnd.collabio.xodocuments.document-template": { "source": "iana" }, + "application/vnd.collabio.xodocuments.presentation": { "source": "iana" }, + "application/vnd.collabio.xodocuments.presentation-template": { "source": "iana" }, + "application/vnd.collabio.xodocuments.spreadsheet": { "source": "iana" }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { "source": "iana" }, + "application/vnd.collection+json": { "source": "iana", "compressible": true }, + "application/vnd.collection.doc+json": { "source": "iana", "compressible": true }, + "application/vnd.collection.next+json": { "source": "iana", "compressible": true }, + "application/vnd.comicbook+zip": { "source": "iana", "compressible": false }, + "application/vnd.comicbook-rar": { "source": "iana" }, + "application/vnd.commerce-battelle": { "source": "iana" }, + "application/vnd.commonspace": { "source": "iana", "extensions": ["csp"] }, + "application/vnd.contact.cmsg": { "source": "iana", "extensions": ["cdbcmsg"] }, + "application/vnd.coreos.ignition+json": { "source": "iana", "compressible": true }, + "application/vnd.cosmocaller": { "source": "iana", "extensions": ["cmc"] }, + "application/vnd.crick.clicker": { "source": "iana", "extensions": ["clkx"] }, + "application/vnd.crick.clicker.keyboard": { "source": "iana", "extensions": ["clkk"] }, + "application/vnd.crick.clicker.palette": { "source": "iana", "extensions": ["clkp"] }, + "application/vnd.crick.clicker.template": { "source": "iana", "extensions": ["clkt"] }, + "application/vnd.crick.clicker.wordbank": { "source": "iana", "extensions": ["clkw"] }, + "application/vnd.criticaltools.wbs+xml": { "source": "iana", "compressible": true, "extensions": ["wbs"] }, + "application/vnd.cryptii.pipe+json": { "source": "iana", "compressible": true }, + "application/vnd.crypto-shade-file": { "source": "iana" }, + "application/vnd.cryptomator.encrypted": { "source": "iana" }, + "application/vnd.cryptomator.vault": { "source": "iana" }, + "application/vnd.ctc-posml": { "source": "iana", "extensions": ["pml"] }, + "application/vnd.ctct.ws+xml": { "source": "iana", "compressible": true }, + "application/vnd.cups-pdf": { "source": "iana" }, + "application/vnd.cups-postscript": { "source": "iana" }, + "application/vnd.cups-ppd": { "source": "iana", "extensions": ["ppd"] }, + "application/vnd.cups-raster": { "source": "iana" }, + "application/vnd.cups-raw": { "source": "iana" }, + "application/vnd.curl": { "source": "iana" }, + "application/vnd.curl.car": { "source": "apache", "extensions": ["car"] }, + "application/vnd.curl.pcurl": { "source": "apache", "extensions": ["pcurl"] }, + "application/vnd.cyan.dean.root+xml": { "source": "iana", "compressible": true }, + "application/vnd.cybank": { "source": "iana" }, + "application/vnd.cyclonedx+json": { "source": "iana", "compressible": true }, + "application/vnd.cyclonedx+xml": { "source": "iana", "compressible": true }, + "application/vnd.d2l.coursepackage1p0+zip": { "source": "iana", "compressible": false }, + "application/vnd.d3m-dataset": { "source": "iana" }, + "application/vnd.d3m-problem": { "source": "iana" }, + "application/vnd.dart": { "source": "iana", "compressible": true, "extensions": ["dart"] }, + "application/vnd.data-vision.rdz": { "source": "iana", "extensions": ["rdz"] }, + "application/vnd.datapackage+json": { "source": "iana", "compressible": true }, + "application/vnd.dataresource+json": { "source": "iana", "compressible": true }, + "application/vnd.dbf": { "source": "iana", "extensions": ["dbf"] }, + "application/vnd.debian.binary-package": { "source": "iana" }, + "application/vnd.dece.data": { "source": "iana", "extensions": ["uvf", "uvvf", "uvd", "uvvd"] }, + "application/vnd.dece.ttml+xml": { "source": "iana", "compressible": true, "extensions": ["uvt", "uvvt"] }, + "application/vnd.dece.unspecified": { "source": "iana", "extensions": ["uvx", "uvvx"] }, + "application/vnd.dece.zip": { "source": "iana", "extensions": ["uvz", "uvvz"] }, + "application/vnd.denovo.fcselayout-link": { "source": "iana", "extensions": ["fe_launch"] }, + "application/vnd.desmume.movie": { "source": "iana" }, + "application/vnd.dir-bi.plate-dl-nosuffix": { "source": "iana" }, + "application/vnd.dm.delegation+xml": { "source": "iana", "compressible": true }, + "application/vnd.dna": { "source": "iana", "extensions": ["dna"] }, + "application/vnd.document+json": { "source": "iana", "compressible": true }, + "application/vnd.dolby.mlp": { "source": "apache", "extensions": ["mlp"] }, + "application/vnd.dolby.mobile.1": { "source": "iana" }, + "application/vnd.dolby.mobile.2": { "source": "iana" }, + "application/vnd.doremir.scorecloud-binary-document": { "source": "iana" }, + "application/vnd.dpgraph": { "source": "iana", "extensions": ["dpg"] }, + "application/vnd.dreamfactory": { "source": "iana", "extensions": ["dfac"] }, + "application/vnd.drive+json": { "source": "iana", "compressible": true }, + "application/vnd.ds-keypoint": { "source": "apache", "extensions": ["kpxx"] }, + "application/vnd.dtg.local": { "source": "iana" }, + "application/vnd.dtg.local.flash": { "source": "iana" }, + "application/vnd.dtg.local.html": { "source": "iana" }, + "application/vnd.dvb.ait": { "source": "iana", "extensions": ["ait"] }, + "application/vnd.dvb.dvbisl+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.dvbj": { "source": "iana" }, + "application/vnd.dvb.esgcontainer": { "source": "iana" }, + "application/vnd.dvb.ipdcdftnotifaccess": { "source": "iana" }, + "application/vnd.dvb.ipdcesgaccess": { "source": "iana" }, + "application/vnd.dvb.ipdcesgaccess2": { "source": "iana" }, + "application/vnd.dvb.ipdcesgpdd": { "source": "iana" }, + "application/vnd.dvb.ipdcroaming": { "source": "iana" }, + "application/vnd.dvb.iptv.alfec-base": { "source": "iana" }, + "application/vnd.dvb.iptv.alfec-enhancement": { "source": "iana" }, + "application/vnd.dvb.notif-aggregate-root+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.notif-container+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.notif-generic+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.notif-ia-msglist+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.notif-ia-registration-request+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.notif-ia-registration-response+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.notif-init+xml": { "source": "iana", "compressible": true }, + "application/vnd.dvb.pfr": { "source": "iana" }, + "application/vnd.dvb.service": { "source": "iana", "extensions": ["svc"] }, + "application/vnd.dxr": { "source": "iana" }, + "application/vnd.dynageo": { "source": "iana", "extensions": ["geo"] }, + "application/vnd.dzr": { "source": "iana" }, + "application/vnd.easykaraoke.cdgdownload": { "source": "iana" }, + "application/vnd.ecdis-update": { "source": "iana" }, + "application/vnd.ecip.rlp": { "source": "iana" }, + "application/vnd.eclipse.ditto+json": { "source": "iana", "compressible": true }, + "application/vnd.ecowin.chart": { "source": "iana", "extensions": ["mag"] }, + "application/vnd.ecowin.filerequest": { "source": "iana" }, + "application/vnd.ecowin.fileupdate": { "source": "iana" }, + "application/vnd.ecowin.series": { "source": "iana" }, + "application/vnd.ecowin.seriesrequest": { "source": "iana" }, + "application/vnd.ecowin.seriesupdate": { "source": "iana" }, + "application/vnd.efi.img": { "source": "iana" }, + "application/vnd.efi.iso": { "source": "iana" }, + "application/vnd.emclient.accessrequest+xml": { "source": "iana", "compressible": true }, + "application/vnd.enliven": { "source": "iana", "extensions": ["nml"] }, + "application/vnd.enphase.envoy": { "source": "iana" }, + "application/vnd.eprints.data+xml": { "source": "iana", "compressible": true }, + "application/vnd.epson.esf": { "source": "iana", "extensions": ["esf"] }, + "application/vnd.epson.msf": { "source": "iana", "extensions": ["msf"] }, + "application/vnd.epson.quickanime": { "source": "iana", "extensions": ["qam"] }, + "application/vnd.epson.salt": { "source": "iana", "extensions": ["slt"] }, + "application/vnd.epson.ssf": { "source": "iana", "extensions": ["ssf"] }, + "application/vnd.ericsson.quickcall": { "source": "iana" }, + "application/vnd.espass-espass+zip": { "source": "iana", "compressible": false }, + "application/vnd.eszigno3+xml": { "source": "iana", "compressible": true, "extensions": ["es3", "et3"] }, + "application/vnd.etsi.aoc+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.asic-e+zip": { "source": "iana", "compressible": false }, + "application/vnd.etsi.asic-s+zip": { "source": "iana", "compressible": false }, + "application/vnd.etsi.cug+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvcommand+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvdiscovery+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvprofile+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvsad-bc+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvsad-cod+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvsad-npvr+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvservice+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvsync+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.iptvueprofile+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.mcid+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.mheg5": { "source": "iana" }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.pstn+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.sci+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.simservs+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.timestamp-token": { "source": "iana" }, + "application/vnd.etsi.tsl+xml": { "source": "iana", "compressible": true }, + "application/vnd.etsi.tsl.der": { "source": "iana" }, + "application/vnd.eu.kasparian.car+json": { "source": "iana", "compressible": true }, + "application/vnd.eudora.data": { "source": "iana" }, + "application/vnd.evolv.ecig.profile": { "source": "iana" }, + "application/vnd.evolv.ecig.settings": { "source": "iana" }, + "application/vnd.evolv.ecig.theme": { "source": "iana" }, + "application/vnd.exstream-empower+zip": { "source": "iana", "compressible": false }, + "application/vnd.exstream-package": { "source": "iana" }, + "application/vnd.ezpix-album": { "source": "iana", "extensions": ["ez2"] }, + "application/vnd.ezpix-package": { "source": "iana", "extensions": ["ez3"] }, + "application/vnd.f-secure.mobile": { "source": "iana" }, + "application/vnd.familysearch.gedcom+zip": { "source": "iana", "compressible": false }, + "application/vnd.fastcopy-disk-image": { "source": "iana" }, + "application/vnd.fdf": { "source": "iana", "extensions": ["fdf"] }, + "application/vnd.fdsn.mseed": { "source": "iana", "extensions": ["mseed"] }, + "application/vnd.fdsn.seed": { "source": "iana", "extensions": ["seed", "dataless"] }, + "application/vnd.ffsns": { "source": "iana" }, + "application/vnd.ficlab.flb+zip": { "source": "iana", "compressible": false }, + "application/vnd.filmit.zfc": { "source": "iana" }, + "application/vnd.fints": { "source": "iana" }, + "application/vnd.firemonkeys.cloudcell": { "source": "iana" }, + "application/vnd.flographit": { "source": "iana", "extensions": ["gph"] }, + "application/vnd.fluxtime.clip": { "source": "iana", "extensions": ["ftc"] }, + "application/vnd.font-fontforge-sfd": { "source": "iana" }, + "application/vnd.framemaker": { "source": "iana", "extensions": ["fm", "frame", "maker", "book"] }, + "application/vnd.frogans.fnc": { "source": "iana", "extensions": ["fnc"] }, + "application/vnd.frogans.ltf": { "source": "iana", "extensions": ["ltf"] }, + "application/vnd.fsc.weblaunch": { "source": "iana", "extensions": ["fsc"] }, + "application/vnd.fujifilm.fb.docuworks": { "source": "iana" }, + "application/vnd.fujifilm.fb.docuworks.binder": { "source": "iana" }, + "application/vnd.fujifilm.fb.docuworks.container": { "source": "iana" }, + "application/vnd.fujifilm.fb.jfi+xml": { "source": "iana", "compressible": true }, + "application/vnd.fujitsu.oasys": { "source": "iana", "extensions": ["oas"] }, + "application/vnd.fujitsu.oasys2": { "source": "iana", "extensions": ["oa2"] }, + "application/vnd.fujitsu.oasys3": { "source": "iana", "extensions": ["oa3"] }, + "application/vnd.fujitsu.oasysgp": { "source": "iana", "extensions": ["fg5"] }, + "application/vnd.fujitsu.oasysprs": { "source": "iana", "extensions": ["bh2"] }, + "application/vnd.fujixerox.art-ex": { "source": "iana" }, + "application/vnd.fujixerox.art4": { "source": "iana" }, + "application/vnd.fujixerox.ddd": { "source": "iana", "extensions": ["ddd"] }, + "application/vnd.fujixerox.docuworks": { "source": "iana", "extensions": ["xdw"] }, + "application/vnd.fujixerox.docuworks.binder": { "source": "iana", "extensions": ["xbd"] }, + "application/vnd.fujixerox.docuworks.container": { "source": "iana" }, + "application/vnd.fujixerox.hbpl": { "source": "iana" }, + "application/vnd.fut-misnet": { "source": "iana" }, + "application/vnd.futoin+cbor": { "source": "iana" }, + "application/vnd.futoin+json": { "source": "iana", "compressible": true }, + "application/vnd.fuzzysheet": { "source": "iana", "extensions": ["fzs"] }, + "application/vnd.genomatix.tuxedo": { "source": "iana", "extensions": ["txd"] }, + "application/vnd.gentics.grd+json": { "source": "iana", "compressible": true }, + "application/vnd.geo+json": { "source": "iana", "compressible": true }, + "application/vnd.geocube+xml": { "source": "iana", "compressible": true }, + "application/vnd.geogebra.file": { "source": "iana", "extensions": ["ggb"] }, + "application/vnd.geogebra.slides": { "source": "iana" }, + "application/vnd.geogebra.tool": { "source": "iana", "extensions": ["ggt"] }, + "application/vnd.geometry-explorer": { "source": "iana", "extensions": ["gex", "gre"] }, + "application/vnd.geonext": { "source": "iana", "extensions": ["gxt"] }, + "application/vnd.geoplan": { "source": "iana", "extensions": ["g2w"] }, + "application/vnd.geospace": { "source": "iana", "extensions": ["g3w"] }, + "application/vnd.gerber": { "source": "iana" }, + "application/vnd.globalplatform.card-content-mgt": { "source": "iana" }, + "application/vnd.globalplatform.card-content-mgt-response": { "source": "iana" }, + "application/vnd.gmx": { "source": "iana", "extensions": ["gmx"] }, + "application/vnd.google-apps.document": { "compressible": false, "extensions": ["gdoc"] }, + "application/vnd.google-apps.presentation": { "compressible": false, "extensions": ["gslides"] }, + "application/vnd.google-apps.spreadsheet": { "compressible": false, "extensions": ["gsheet"] }, + "application/vnd.google-earth.kml+xml": { "source": "iana", "compressible": true, "extensions": ["kml"] }, + "application/vnd.google-earth.kmz": { "source": "iana", "compressible": false, "extensions": ["kmz"] }, + "application/vnd.gov.sk.e-form+xml": { "source": "iana", "compressible": true }, + "application/vnd.gov.sk.e-form+zip": { "source": "iana", "compressible": false }, + "application/vnd.gov.sk.xmldatacontainer+xml": { "source": "iana", "compressible": true }, + "application/vnd.grafeq": { "source": "iana", "extensions": ["gqf", "gqs"] }, + "application/vnd.gridmp": { "source": "iana" }, + "application/vnd.groove-account": { "source": "iana", "extensions": ["gac"] }, + "application/vnd.groove-help": { "source": "iana", "extensions": ["ghf"] }, + "application/vnd.groove-identity-message": { "source": "iana", "extensions": ["gim"] }, + "application/vnd.groove-injector": { "source": "iana", "extensions": ["grv"] }, + "application/vnd.groove-tool-message": { "source": "iana", "extensions": ["gtm"] }, + "application/vnd.groove-tool-template": { "source": "iana", "extensions": ["tpl"] }, + "application/vnd.groove-vcard": { "source": "iana", "extensions": ["vcg"] }, + "application/vnd.hal+json": { "source": "iana", "compressible": true }, + "application/vnd.hal+xml": { "source": "iana", "compressible": true, "extensions": ["hal"] }, + "application/vnd.handheld-entertainment+xml": { "source": "iana", "compressible": true, "extensions": ["zmm"] }, + "application/vnd.hbci": { "source": "iana", "extensions": ["hbci"] }, + "application/vnd.hc+json": { "source": "iana", "compressible": true }, + "application/vnd.hcl-bireports": { "source": "iana" }, + "application/vnd.hdt": { "source": "iana" }, + "application/vnd.heroku+json": { "source": "iana", "compressible": true }, + "application/vnd.hhe.lesson-player": { "source": "iana", "extensions": ["les"] }, + "application/vnd.hl7cda+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/vnd.hl7v2+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/vnd.hp-hpgl": { "source": "iana", "extensions": ["hpgl"] }, + "application/vnd.hp-hpid": { "source": "iana", "extensions": ["hpid"] }, + "application/vnd.hp-hps": { "source": "iana", "extensions": ["hps"] }, + "application/vnd.hp-jlyt": { "source": "iana", "extensions": ["jlt"] }, + "application/vnd.hp-pcl": { "source": "iana", "extensions": ["pcl"] }, + "application/vnd.hp-pclxl": { "source": "iana", "extensions": ["pclxl"] }, + "application/vnd.httphone": { "source": "iana" }, + "application/vnd.hydrostatix.sof-data": { "source": "iana", "extensions": ["sfd-hdstx"] }, + "application/vnd.hyper+json": { "source": "iana", "compressible": true }, + "application/vnd.hyper-item+json": { "source": "iana", "compressible": true }, + "application/vnd.hyperdrive+json": { "source": "iana", "compressible": true }, + "application/vnd.hzn-3d-crossword": { "source": "iana" }, + "application/vnd.ibm.afplinedata": { "source": "iana" }, + "application/vnd.ibm.electronic-media": { "source": "iana" }, + "application/vnd.ibm.minipay": { "source": "iana", "extensions": ["mpy"] }, + "application/vnd.ibm.modcap": { "source": "iana", "extensions": ["afp", "listafp", "list3820"] }, + "application/vnd.ibm.rights-management": { "source": "iana", "extensions": ["irm"] }, + "application/vnd.ibm.secure-container": { "source": "iana", "extensions": ["sc"] }, + "application/vnd.iccprofile": { "source": "iana", "extensions": ["icc", "icm"] }, + "application/vnd.ieee.1905": { "source": "iana" }, + "application/vnd.igloader": { "source": "iana", "extensions": ["igl"] }, + "application/vnd.imagemeter.folder+zip": { "source": "iana", "compressible": false }, + "application/vnd.imagemeter.image+zip": { "source": "iana", "compressible": false }, + "application/vnd.immervision-ivp": { "source": "iana", "extensions": ["ivp"] }, + "application/vnd.immervision-ivu": { "source": "iana", "extensions": ["ivu"] }, + "application/vnd.ims.imsccv1p1": { "source": "iana" }, + "application/vnd.ims.imsccv1p2": { "source": "iana" }, + "application/vnd.ims.imsccv1p3": { "source": "iana" }, + "application/vnd.ims.lis.v2.result+json": { "source": "iana", "compressible": true }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { "source": "iana", "compressible": true }, + "application/vnd.ims.lti.v2.toolproxy+json": { "source": "iana", "compressible": true }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { "source": "iana", "compressible": true }, + "application/vnd.ims.lti.v2.toolsettings+json": { "source": "iana", "compressible": true }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { "source": "iana", "compressible": true }, + "application/vnd.informedcontrol.rms+xml": { "source": "iana", "compressible": true }, + "application/vnd.informix-visionary": { "source": "iana" }, + "application/vnd.infotech.project": { "source": "iana" }, + "application/vnd.infotech.project+xml": { "source": "iana", "compressible": true }, + "application/vnd.innopath.wamp.notification": { "source": "iana" }, + "application/vnd.insors.igm": { "source": "iana", "extensions": ["igm"] }, + "application/vnd.intercon.formnet": { "source": "iana", "extensions": ["xpw", "xpx"] }, + "application/vnd.intergeo": { "source": "iana", "extensions": ["i2g"] }, + "application/vnd.intertrust.digibox": { "source": "iana" }, + "application/vnd.intertrust.nncp": { "source": "iana" }, + "application/vnd.intu.qbo": { "source": "iana", "extensions": ["qbo"] }, + "application/vnd.intu.qfx": { "source": "iana", "extensions": ["qfx"] }, + "application/vnd.iptc.g2.catalogitem+xml": { "source": "iana", "compressible": true }, + "application/vnd.iptc.g2.conceptitem+xml": { "source": "iana", "compressible": true }, + "application/vnd.iptc.g2.knowledgeitem+xml": { "source": "iana", "compressible": true }, + "application/vnd.iptc.g2.newsitem+xml": { "source": "iana", "compressible": true }, + "application/vnd.iptc.g2.newsmessage+xml": { "source": "iana", "compressible": true }, + "application/vnd.iptc.g2.packageitem+xml": { "source": "iana", "compressible": true }, + "application/vnd.iptc.g2.planningitem+xml": { "source": "iana", "compressible": true }, + "application/vnd.ipunplugged.rcprofile": { "source": "iana", "extensions": ["rcprofile"] }, + "application/vnd.irepository.package+xml": { "source": "iana", "compressible": true, "extensions": ["irp"] }, + "application/vnd.is-xpr": { "source": "iana", "extensions": ["xpr"] }, + "application/vnd.isac.fcs": { "source": "iana", "extensions": ["fcs"] }, + "application/vnd.iso11783-10+zip": { "source": "iana", "compressible": false }, + "application/vnd.jam": { "source": "iana", "extensions": ["jam"] }, + "application/vnd.japannet-directory-service": { "source": "iana" }, + "application/vnd.japannet-jpnstore-wakeup": { "source": "iana" }, + "application/vnd.japannet-payment-wakeup": { "source": "iana" }, + "application/vnd.japannet-registration": { "source": "iana" }, + "application/vnd.japannet-registration-wakeup": { "source": "iana" }, + "application/vnd.japannet-setstore-wakeup": { "source": "iana" }, + "application/vnd.japannet-verification": { "source": "iana" }, + "application/vnd.japannet-verification-wakeup": { "source": "iana" }, + "application/vnd.jcp.javame.midlet-rms": { "source": "iana", "extensions": ["rms"] }, + "application/vnd.jisp": { "source": "iana", "extensions": ["jisp"] }, + "application/vnd.joost.joda-archive": { "source": "iana", "extensions": ["joda"] }, + "application/vnd.jsk.isdn-ngn": { "source": "iana" }, + "application/vnd.kahootz": { "source": "iana", "extensions": ["ktz", "ktr"] }, + "application/vnd.kde.karbon": { "source": "iana", "extensions": ["karbon"] }, + "application/vnd.kde.kchart": { "source": "iana", "extensions": ["chrt"] }, + "application/vnd.kde.kformula": { "source": "iana", "extensions": ["kfo"] }, + "application/vnd.kde.kivio": { "source": "iana", "extensions": ["flw"] }, + "application/vnd.kde.kontour": { "source": "iana", "extensions": ["kon"] }, + "application/vnd.kde.kpresenter": { "source": "iana", "extensions": ["kpr", "kpt"] }, + "application/vnd.kde.kspread": { "source": "iana", "extensions": ["ksp"] }, + "application/vnd.kde.kword": { "source": "iana", "extensions": ["kwd", "kwt"] }, + "application/vnd.kenameaapp": { "source": "iana", "extensions": ["htke"] }, + "application/vnd.kidspiration": { "source": "iana", "extensions": ["kia"] }, + "application/vnd.kinar": { "source": "iana", "extensions": ["kne", "knp"] }, + "application/vnd.koan": { "source": "iana", "extensions": ["skp", "skd", "skt", "skm"] }, + "application/vnd.kodak-descriptor": { "source": "iana", "extensions": ["sse"] }, + "application/vnd.las": { "source": "iana" }, + "application/vnd.las.las+json": { "source": "iana", "compressible": true }, + "application/vnd.las.las+xml": { "source": "iana", "compressible": true, "extensions": ["lasxml"] }, + "application/vnd.laszip": { "source": "iana" }, + "application/vnd.leap+json": { "source": "iana", "compressible": true }, + "application/vnd.liberty-request+xml": { "source": "iana", "compressible": true }, + "application/vnd.llamagraphics.life-balance.desktop": { "source": "iana", "extensions": ["lbd"] }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { "source": "iana", "compressible": true, "extensions": ["lbe"] }, + "application/vnd.logipipe.circuit+zip": { "source": "iana", "compressible": false }, + "application/vnd.loom": { "source": "iana" }, + "application/vnd.lotus-1-2-3": { "source": "iana", "extensions": ["123"] }, + "application/vnd.lotus-approach": { "source": "iana", "extensions": ["apr"] }, + "application/vnd.lotus-freelance": { "source": "iana", "extensions": ["pre"] }, + "application/vnd.lotus-notes": { "source": "iana", "extensions": ["nsf"] }, + "application/vnd.lotus-organizer": { "source": "iana", "extensions": ["org"] }, + "application/vnd.lotus-screencam": { "source": "iana", "extensions": ["scm"] }, + "application/vnd.lotus-wordpro": { "source": "iana", "extensions": ["lwp"] }, + "application/vnd.macports.portpkg": { "source": "iana", "extensions": ["portpkg"] }, + "application/vnd.mapbox-vector-tile": { "source": "iana", "extensions": ["mvt"] }, + "application/vnd.marlin.drm.actiontoken+xml": { "source": "iana", "compressible": true }, + "application/vnd.marlin.drm.conftoken+xml": { "source": "iana", "compressible": true }, + "application/vnd.marlin.drm.license+xml": { "source": "iana", "compressible": true }, + "application/vnd.marlin.drm.mdcf": { "source": "iana" }, + "application/vnd.mason+json": { "source": "iana", "compressible": true }, + "application/vnd.maxar.archive.3tz+zip": { "source": "iana", "compressible": false }, + "application/vnd.maxmind.maxmind-db": { "source": "iana" }, + "application/vnd.mcd": { "source": "iana", "extensions": ["mcd"] }, + "application/vnd.medcalcdata": { "source": "iana", "extensions": ["mc1"] }, + "application/vnd.mediastation.cdkey": { "source": "iana", "extensions": ["cdkey"] }, + "application/vnd.meridian-slingshot": { "source": "iana" }, + "application/vnd.mfer": { "source": "iana", "extensions": ["mwf"] }, + "application/vnd.mfmp": { "source": "iana", "extensions": ["mfm"] }, + "application/vnd.micro+json": { "source": "iana", "compressible": true }, + "application/vnd.micrografx.flo": { "source": "iana", "extensions": ["flo"] }, + "application/vnd.micrografx.igx": { "source": "iana", "extensions": ["igx"] }, + "application/vnd.microsoft.portable-executable": { "source": "iana" }, + "application/vnd.microsoft.windows.thumbnail-cache": { "source": "iana" }, + "application/vnd.miele+json": { "source": "iana", "compressible": true }, + "application/vnd.mif": { "source": "iana", "extensions": ["mif"] }, + "application/vnd.minisoft-hp3000-save": { "source": "iana" }, + "application/vnd.mitsubishi.misty-guard.trustweb": { "source": "iana" }, + "application/vnd.mobius.daf": { "source": "iana", "extensions": ["daf"] }, + "application/vnd.mobius.dis": { "source": "iana", "extensions": ["dis"] }, + "application/vnd.mobius.mbk": { "source": "iana", "extensions": ["mbk"] }, + "application/vnd.mobius.mqy": { "source": "iana", "extensions": ["mqy"] }, + "application/vnd.mobius.msl": { "source": "iana", "extensions": ["msl"] }, + "application/vnd.mobius.plc": { "source": "iana", "extensions": ["plc"] }, + "application/vnd.mobius.txf": { "source": "iana", "extensions": ["txf"] }, + "application/vnd.mophun.application": { "source": "iana", "extensions": ["mpn"] }, + "application/vnd.mophun.certificate": { "source": "iana", "extensions": ["mpc"] }, + "application/vnd.motorola.flexsuite": { "source": "iana" }, + "application/vnd.motorola.flexsuite.adsi": { "source": "iana" }, + "application/vnd.motorola.flexsuite.fis": { "source": "iana" }, + "application/vnd.motorola.flexsuite.gotap": { "source": "iana" }, + "application/vnd.motorola.flexsuite.kmr": { "source": "iana" }, + "application/vnd.motorola.flexsuite.ttc": { "source": "iana" }, + "application/vnd.motorola.flexsuite.wem": { "source": "iana" }, + "application/vnd.motorola.iprm": { "source": "iana" }, + "application/vnd.mozilla.xul+xml": { "source": "iana", "compressible": true, "extensions": ["xul"] }, + "application/vnd.ms-3mfdocument": { "source": "iana" }, + "application/vnd.ms-artgalry": { "source": "iana", "extensions": ["cil"] }, + "application/vnd.ms-asf": { "source": "iana" }, + "application/vnd.ms-cab-compressed": { "source": "iana", "extensions": ["cab"] }, + "application/vnd.ms-color.iccprofile": { "source": "apache" }, + "application/vnd.ms-excel": { "source": "iana", "compressible": false, "extensions": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] }, + "application/vnd.ms-excel.addin.macroenabled.12": { "source": "iana", "extensions": ["xlam"] }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { "source": "iana", "extensions": ["xlsb"] }, + "application/vnd.ms-excel.sheet.macroenabled.12": { "source": "iana", "extensions": ["xlsm"] }, + "application/vnd.ms-excel.template.macroenabled.12": { "source": "iana", "extensions": ["xltm"] }, + "application/vnd.ms-fontobject": { "source": "iana", "compressible": true, "extensions": ["eot"] }, + "application/vnd.ms-htmlhelp": { "source": "iana", "extensions": ["chm"] }, + "application/vnd.ms-ims": { "source": "iana", "extensions": ["ims"] }, + "application/vnd.ms-lrm": { "source": "iana", "extensions": ["lrm"] }, + "application/vnd.ms-office.activex+xml": { "source": "iana", "compressible": true }, + "application/vnd.ms-officetheme": { "source": "iana", "extensions": ["thmx"] }, + "application/vnd.ms-opentype": { "source": "apache", "compressible": true }, + "application/vnd.ms-outlook": { "compressible": false, "extensions": ["msg"] }, + "application/vnd.ms-package.obfuscated-opentype": { "source": "apache" }, + "application/vnd.ms-pki.seccat": { "source": "apache", "extensions": ["cat"] }, + "application/vnd.ms-pki.stl": { "source": "apache", "extensions": ["stl"] }, + "application/vnd.ms-playready.initiator+xml": { "source": "iana", "compressible": true }, + "application/vnd.ms-powerpoint": { "source": "iana", "compressible": false, "extensions": ["ppt", "pps", "pot"] }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { "source": "iana", "extensions": ["ppam"] }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { "source": "iana", "extensions": ["pptm"] }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { "source": "iana", "extensions": ["sldm"] }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { "source": "iana", "extensions": ["ppsm"] }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { "source": "iana", "extensions": ["potm"] }, + "application/vnd.ms-printdevicecapabilities+xml": { "source": "iana", "compressible": true }, + "application/vnd.ms-printing.printticket+xml": { "source": "apache", "compressible": true }, + "application/vnd.ms-printschematicket+xml": { "source": "iana", "compressible": true }, + "application/vnd.ms-project": { "source": "iana", "extensions": ["mpp", "mpt"] }, + "application/vnd.ms-tnef": { "source": "iana" }, + "application/vnd.ms-windows.devicepairing": { "source": "iana" }, + "application/vnd.ms-windows.nwprinting.oob": { "source": "iana" }, + "application/vnd.ms-windows.printerpairing": { "source": "iana" }, + "application/vnd.ms-windows.wsd.oob": { "source": "iana" }, + "application/vnd.ms-wmdrm.lic-chlg-req": { "source": "iana" }, + "application/vnd.ms-wmdrm.lic-resp": { "source": "iana" }, + "application/vnd.ms-wmdrm.meter-chlg-req": { "source": "iana" }, + "application/vnd.ms-wmdrm.meter-resp": { "source": "iana" }, + "application/vnd.ms-word.document.macroenabled.12": { "source": "iana", "extensions": ["docm"] }, + "application/vnd.ms-word.template.macroenabled.12": { "source": "iana", "extensions": ["dotm"] }, + "application/vnd.ms-works": { "source": "iana", "extensions": ["wps", "wks", "wcm", "wdb"] }, + "application/vnd.ms-wpl": { "source": "iana", "extensions": ["wpl"] }, + "application/vnd.ms-xpsdocument": { "source": "iana", "compressible": false, "extensions": ["xps"] }, + "application/vnd.msa-disk-image": { "source": "iana" }, + "application/vnd.mseq": { "source": "iana", "extensions": ["mseq"] }, + "application/vnd.msign": { "source": "iana" }, + "application/vnd.multiad.creator": { "source": "iana" }, + "application/vnd.multiad.creator.cif": { "source": "iana" }, + "application/vnd.music-niff": { "source": "iana" }, + "application/vnd.musician": { "source": "iana", "extensions": ["mus"] }, + "application/vnd.muvee.style": { "source": "iana", "extensions": ["msty"] }, + "application/vnd.mynfc": { "source": "iana", "extensions": ["taglet"] }, + "application/vnd.nacamar.ybrid+json": { "source": "iana", "compressible": true }, + "application/vnd.ncd.control": { "source": "iana" }, + "application/vnd.ncd.reference": { "source": "iana" }, + "application/vnd.nearst.inv+json": { "source": "iana", "compressible": true }, + "application/vnd.nebumind.line": { "source": "iana" }, + "application/vnd.nervana": { "source": "iana" }, + "application/vnd.netfpx": { "source": "iana" }, + "application/vnd.neurolanguage.nlu": { "source": "iana", "extensions": ["nlu"] }, + "application/vnd.nimn": { "source": "iana" }, + "application/vnd.nintendo.nitro.rom": { "source": "iana" }, + "application/vnd.nintendo.snes.rom": { "source": "iana" }, + "application/vnd.nitf": { "source": "iana", "extensions": ["ntf", "nitf"] }, + "application/vnd.noblenet-directory": { "source": "iana", "extensions": ["nnd"] }, + "application/vnd.noblenet-sealer": { "source": "iana", "extensions": ["nns"] }, + "application/vnd.noblenet-web": { "source": "iana", "extensions": ["nnw"] }, + "application/vnd.nokia.catalogs": { "source": "iana" }, + "application/vnd.nokia.conml+wbxml": { "source": "iana" }, + "application/vnd.nokia.conml+xml": { "source": "iana", "compressible": true }, + "application/vnd.nokia.iptv.config+xml": { "source": "iana", "compressible": true }, + "application/vnd.nokia.isds-radio-presets": { "source": "iana" }, + "application/vnd.nokia.landmark+wbxml": { "source": "iana" }, + "application/vnd.nokia.landmark+xml": { "source": "iana", "compressible": true }, + "application/vnd.nokia.landmarkcollection+xml": { "source": "iana", "compressible": true }, + "application/vnd.nokia.n-gage.ac+xml": { "source": "iana", "compressible": true, "extensions": ["ac"] }, + "application/vnd.nokia.n-gage.data": { "source": "iana", "extensions": ["ngdat"] }, + "application/vnd.nokia.n-gage.symbian.install": { "source": "iana", "extensions": ["n-gage"] }, + "application/vnd.nokia.ncd": { "source": "iana" }, + "application/vnd.nokia.pcd+wbxml": { "source": "iana" }, + "application/vnd.nokia.pcd+xml": { "source": "iana", "compressible": true }, + "application/vnd.nokia.radio-preset": { "source": "iana", "extensions": ["rpst"] }, + "application/vnd.nokia.radio-presets": { "source": "iana", "extensions": ["rpss"] }, + "application/vnd.novadigm.edm": { "source": "iana", "extensions": ["edm"] }, + "application/vnd.novadigm.edx": { "source": "iana", "extensions": ["edx"] }, + "application/vnd.novadigm.ext": { "source": "iana", "extensions": ["ext"] }, + "application/vnd.ntt-local.content-share": { "source": "iana" }, + "application/vnd.ntt-local.file-transfer": { "source": "iana" }, + "application/vnd.ntt-local.ogw_remote-access": { "source": "iana" }, + "application/vnd.ntt-local.sip-ta_remote": { "source": "iana" }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { "source": "iana" }, + "application/vnd.oasis.opendocument.chart": { "source": "iana", "extensions": ["odc"] }, + "application/vnd.oasis.opendocument.chart-template": { "source": "iana", "extensions": ["otc"] }, + "application/vnd.oasis.opendocument.database": { "source": "iana", "extensions": ["odb"] }, + "application/vnd.oasis.opendocument.formula": { "source": "iana", "extensions": ["odf"] }, + "application/vnd.oasis.opendocument.formula-template": { "source": "iana", "extensions": ["odft"] }, + "application/vnd.oasis.opendocument.graphics": { "source": "iana", "compressible": false, "extensions": ["odg"] }, + "application/vnd.oasis.opendocument.graphics-template": { "source": "iana", "extensions": ["otg"] }, + "application/vnd.oasis.opendocument.image": { "source": "iana", "extensions": ["odi"] }, + "application/vnd.oasis.opendocument.image-template": { "source": "iana", "extensions": ["oti"] }, + "application/vnd.oasis.opendocument.presentation": { "source": "iana", "compressible": false, "extensions": ["odp"] }, + "application/vnd.oasis.opendocument.presentation-template": { "source": "iana", "extensions": ["otp"] }, + "application/vnd.oasis.opendocument.spreadsheet": { "source": "iana", "compressible": false, "extensions": ["ods"] }, + "application/vnd.oasis.opendocument.spreadsheet-template": { "source": "iana", "extensions": ["ots"] }, + "application/vnd.oasis.opendocument.text": { "source": "iana", "compressible": false, "extensions": ["odt"] }, + "application/vnd.oasis.opendocument.text-master": { "source": "iana", "extensions": ["odm"] }, + "application/vnd.oasis.opendocument.text-template": { "source": "iana", "extensions": ["ott"] }, + "application/vnd.oasis.opendocument.text-web": { "source": "iana", "extensions": ["oth"] }, + "application/vnd.obn": { "source": "iana" }, + "application/vnd.ocf+cbor": { "source": "iana" }, + "application/vnd.oci.image.manifest.v1+json": { "source": "iana", "compressible": true }, + "application/vnd.oftn.l10n+json": { "source": "iana", "compressible": true }, + "application/vnd.oipf.contentaccessdownload+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.contentaccessstreaming+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.cspg-hexbinary": { "source": "iana" }, + "application/vnd.oipf.dae.svg+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.dae.xhtml+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.mippvcontrolmessage+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.pae.gem": { "source": "iana" }, + "application/vnd.oipf.spdiscovery+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.spdlist+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.ueprofile+xml": { "source": "iana", "compressible": true }, + "application/vnd.oipf.userprofile+xml": { "source": "iana", "compressible": true }, + "application/vnd.olpc-sugar": { "source": "iana", "extensions": ["xo"] }, + "application/vnd.oma-scws-config": { "source": "iana" }, + "application/vnd.oma-scws-http-request": { "source": "iana" }, + "application/vnd.oma-scws-http-response": { "source": "iana" }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.drm-trigger+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.imd+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.ltkm": { "source": "iana" }, + "application/vnd.oma.bcast.notification+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.provisioningtrigger": { "source": "iana" }, + "application/vnd.oma.bcast.sgboot": { "source": "iana" }, + "application/vnd.oma.bcast.sgdd+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.sgdu": { "source": "iana" }, + "application/vnd.oma.bcast.simple-symbol-container": { "source": "iana" }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.sprov+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.bcast.stkm": { "source": "iana" }, + "application/vnd.oma.cab-address-book+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.cab-feature-handler+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.cab-pcc+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.cab-subs-invite+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.cab-user-prefs+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.dcd": { "source": "iana" }, + "application/vnd.oma.dcdc": { "source": "iana" }, + "application/vnd.oma.dd2+xml": { "source": "iana", "compressible": true, "extensions": ["dd2"] }, + "application/vnd.oma.drm.risd+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.group-usage-list+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.lwm2m+cbor": { "source": "iana" }, + "application/vnd.oma.lwm2m+json": { "source": "iana", "compressible": true }, + "application/vnd.oma.lwm2m+tlv": { "source": "iana" }, + "application/vnd.oma.pal+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.poc.detailed-progress-report+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.poc.final-report+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.poc.groups+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.poc.invocation-descriptor+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.poc.optimized-progress-report+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.push": { "source": "iana" }, + "application/vnd.oma.scidm.messages+xml": { "source": "iana", "compressible": true }, + "application/vnd.oma.xcap-directory+xml": { "source": "iana", "compressible": true }, + "application/vnd.omads-email+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/vnd.omads-file+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/vnd.omads-folder+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/vnd.omaloc-supl-init": { "source": "iana" }, + "application/vnd.onepager": { "source": "iana" }, + "application/vnd.onepagertamp": { "source": "iana" }, + "application/vnd.onepagertamx": { "source": "iana" }, + "application/vnd.onepagertat": { "source": "iana" }, + "application/vnd.onepagertatp": { "source": "iana" }, + "application/vnd.onepagertatx": { "source": "iana" }, + "application/vnd.openblox.game+xml": { "source": "iana", "compressible": true, "extensions": ["obgx"] }, + "application/vnd.openblox.game-binary": { "source": "iana" }, + "application/vnd.openeye.oeb": { "source": "iana" }, + "application/vnd.openofficeorg.extension": { "source": "apache", "extensions": ["oxt"] }, + "application/vnd.openstreetmap.data+xml": { "source": "iana", "compressible": true, "extensions": ["osm"] }, + "application/vnd.opentimestamps.ots": { "source": "iana" }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { "source": "iana", "compressible": false, "extensions": ["pptx"] }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { "source": "iana", "extensions": ["sldx"] }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { "source": "iana", "extensions": ["ppsx"] }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { "source": "iana", "extensions": ["potx"] }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { "source": "iana", "compressible": false, "extensions": ["xlsx"] }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { "source": "iana", "extensions": ["xltx"] }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.theme+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { "source": "iana" }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { "source": "iana", "compressible": false, "extensions": ["docx"] }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { "source": "iana", "extensions": ["dotx"] }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-package.core-properties+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { "source": "iana", "compressible": true }, + "application/vnd.openxmlformats-package.relationships+xml": { "source": "iana", "compressible": true }, + "application/vnd.oracle.resource+json": { "source": "iana", "compressible": true }, + "application/vnd.orange.indata": { "source": "iana" }, + "application/vnd.osa.netdeploy": { "source": "iana" }, + "application/vnd.osgeo.mapguide.package": { "source": "iana", "extensions": ["mgp"] }, + "application/vnd.osgi.bundle": { "source": "iana" }, + "application/vnd.osgi.dp": { "source": "iana", "extensions": ["dp"] }, + "application/vnd.osgi.subsystem": { "source": "iana", "extensions": ["esa"] }, + "application/vnd.otps.ct-kip+xml": { "source": "iana", "compressible": true }, + "application/vnd.oxli.countgraph": { "source": "iana" }, + "application/vnd.pagerduty+json": { "source": "iana", "compressible": true }, + "application/vnd.palm": { "source": "iana", "extensions": ["pdb", "pqa", "oprc"] }, + "application/vnd.panoply": { "source": "iana" }, + "application/vnd.paos.xml": { "source": "iana" }, + "application/vnd.patentdive": { "source": "iana" }, + "application/vnd.patientecommsdoc": { "source": "iana" }, + "application/vnd.pawaafile": { "source": "iana", "extensions": ["paw"] }, + "application/vnd.pcos": { "source": "iana" }, + "application/vnd.pg.format": { "source": "iana", "extensions": ["str"] }, + "application/vnd.pg.osasli": { "source": "iana", "extensions": ["ei6"] }, + "application/vnd.piaccess.application-licence": { "source": "iana" }, + "application/vnd.picsel": { "source": "iana", "extensions": ["efif"] }, + "application/vnd.pmi.widget": { "source": "iana", "extensions": ["wg"] }, + "application/vnd.poc.group-advertisement+xml": { "source": "iana", "compressible": true }, + "application/vnd.pocketlearn": { "source": "iana", "extensions": ["plf"] }, + "application/vnd.powerbuilder6": { "source": "iana", "extensions": ["pbd"] }, + "application/vnd.powerbuilder6-s": { "source": "iana" }, + "application/vnd.powerbuilder7": { "source": "iana" }, + "application/vnd.powerbuilder7-s": { "source": "iana" }, + "application/vnd.powerbuilder75": { "source": "iana" }, + "application/vnd.powerbuilder75-s": { "source": "iana" }, + "application/vnd.preminet": { "source": "iana" }, + "application/vnd.previewsystems.box": { "source": "iana", "extensions": ["box"] }, + "application/vnd.proteus.magazine": { "source": "iana", "extensions": ["mgz"] }, + "application/vnd.psfs": { "source": "iana" }, + "application/vnd.publishare-delta-tree": { "source": "iana", "extensions": ["qps"] }, + "application/vnd.pvi.ptid1": { "source": "iana", "extensions": ["ptid"] }, + "application/vnd.pwg-multiplexed": { "source": "iana" }, + "application/vnd.pwg-xhtml-print+xml": { "source": "iana", "compressible": true }, + "application/vnd.qualcomm.brew-app-res": { "source": "iana" }, + "application/vnd.quarantainenet": { "source": "iana" }, + "application/vnd.quark.quarkxpress": { "source": "iana", "extensions": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] }, + "application/vnd.quobject-quoxdocument": { "source": "iana" }, + "application/vnd.radisys.moml+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-audit+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-audit-conf+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-audit-conn+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-audit-dialog+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-audit-stream+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-conf+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog-base+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog-group+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog-speech+xml": { "source": "iana", "compressible": true }, + "application/vnd.radisys.msml-dialog-transform+xml": { "source": "iana", "compressible": true }, + "application/vnd.rainstor.data": { "source": "iana" }, + "application/vnd.rapid": { "source": "iana" }, + "application/vnd.rar": { "source": "iana", "extensions": ["rar"] }, + "application/vnd.realvnc.bed": { "source": "iana", "extensions": ["bed"] }, + "application/vnd.recordare.musicxml": { "source": "iana", "extensions": ["mxl"] }, + "application/vnd.recordare.musicxml+xml": { "source": "iana", "compressible": true, "extensions": ["musicxml"] }, + "application/vnd.renlearn.rlprint": { "source": "iana" }, + "application/vnd.resilient.logic": { "source": "iana" }, + "application/vnd.restful+json": { "source": "iana", "compressible": true }, + "application/vnd.rig.cryptonote": { "source": "iana", "extensions": ["cryptonote"] }, + "application/vnd.rim.cod": { "source": "apache", "extensions": ["cod"] }, + "application/vnd.rn-realmedia": { "source": "apache", "extensions": ["rm"] }, + "application/vnd.rn-realmedia-vbr": { "source": "apache", "extensions": ["rmvb"] }, + "application/vnd.route66.link66+xml": { "source": "iana", "compressible": true, "extensions": ["link66"] }, + "application/vnd.rs-274x": { "source": "iana" }, + "application/vnd.ruckus.download": { "source": "iana" }, + "application/vnd.s3sms": { "source": "iana" }, + "application/vnd.sailingtracker.track": { "source": "iana", "extensions": ["st"] }, + "application/vnd.sar": { "source": "iana" }, + "application/vnd.sbm.cid": { "source": "iana" }, + "application/vnd.sbm.mid2": { "source": "iana" }, + "application/vnd.scribus": { "source": "iana" }, + "application/vnd.sealed.3df": { "source": "iana" }, + "application/vnd.sealed.csf": { "source": "iana" }, + "application/vnd.sealed.doc": { "source": "iana" }, + "application/vnd.sealed.eml": { "source": "iana" }, + "application/vnd.sealed.mht": { "source": "iana" }, + "application/vnd.sealed.net": { "source": "iana" }, + "application/vnd.sealed.ppt": { "source": "iana" }, + "application/vnd.sealed.tiff": { "source": "iana" }, + "application/vnd.sealed.xls": { "source": "iana" }, + "application/vnd.sealedmedia.softseal.html": { "source": "iana" }, + "application/vnd.sealedmedia.softseal.pdf": { "source": "iana" }, + "application/vnd.seemail": { "source": "iana", "extensions": ["see"] }, + "application/vnd.seis+json": { "source": "iana", "compressible": true }, + "application/vnd.sema": { "source": "iana", "extensions": ["sema"] }, + "application/vnd.semd": { "source": "iana", "extensions": ["semd"] }, + "application/vnd.semf": { "source": "iana", "extensions": ["semf"] }, + "application/vnd.shade-save-file": { "source": "iana" }, + "application/vnd.shana.informed.formdata": { "source": "iana", "extensions": ["ifm"] }, + "application/vnd.shana.informed.formtemplate": { "source": "iana", "extensions": ["itp"] }, + "application/vnd.shana.informed.interchange": { "source": "iana", "extensions": ["iif"] }, + "application/vnd.shana.informed.package": { "source": "iana", "extensions": ["ipk"] }, + "application/vnd.shootproof+json": { "source": "iana", "compressible": true }, + "application/vnd.shopkick+json": { "source": "iana", "compressible": true }, + "application/vnd.shp": { "source": "iana" }, + "application/vnd.shx": { "source": "iana" }, + "application/vnd.sigrok.session": { "source": "iana" }, + "application/vnd.simtech-mindmapper": { "source": "iana", "extensions": ["twd", "twds"] }, + "application/vnd.siren+json": { "source": "iana", "compressible": true }, + "application/vnd.smaf": { "source": "iana", "extensions": ["mmf"] }, + "application/vnd.smart.notebook": { "source": "iana" }, + "application/vnd.smart.teacher": { "source": "iana", "extensions": ["teacher"] }, + "application/vnd.snesdev-page-table": { "source": "iana" }, + "application/vnd.software602.filler.form+xml": { "source": "iana", "compressible": true, "extensions": ["fo"] }, + "application/vnd.software602.filler.form-xml-zip": { "source": "iana" }, + "application/vnd.solent.sdkm+xml": { "source": "iana", "compressible": true, "extensions": ["sdkm", "sdkd"] }, + "application/vnd.spotfire.dxp": { "source": "iana", "extensions": ["dxp"] }, + "application/vnd.spotfire.sfs": { "source": "iana", "extensions": ["sfs"] }, + "application/vnd.sqlite3": { "source": "iana" }, + "application/vnd.sss-cod": { "source": "iana" }, + "application/vnd.sss-dtf": { "source": "iana" }, + "application/vnd.sss-ntf": { "source": "iana" }, + "application/vnd.stardivision.calc": { "source": "apache", "extensions": ["sdc"] }, + "application/vnd.stardivision.draw": { "source": "apache", "extensions": ["sda"] }, + "application/vnd.stardivision.impress": { "source": "apache", "extensions": ["sdd"] }, + "application/vnd.stardivision.math": { "source": "apache", "extensions": ["smf"] }, + "application/vnd.stardivision.writer": { "source": "apache", "extensions": ["sdw", "vor"] }, + "application/vnd.stardivision.writer-global": { "source": "apache", "extensions": ["sgl"] }, + "application/vnd.stepmania.package": { "source": "iana", "extensions": ["smzip"] }, + "application/vnd.stepmania.stepchart": { "source": "iana", "extensions": ["sm"] }, + "application/vnd.street-stream": { "source": "iana" }, + "application/vnd.sun.wadl+xml": { "source": "iana", "compressible": true, "extensions": ["wadl"] }, + "application/vnd.sun.xml.calc": { "source": "apache", "extensions": ["sxc"] }, + "application/vnd.sun.xml.calc.template": { "source": "apache", "extensions": ["stc"] }, + "application/vnd.sun.xml.draw": { "source": "apache", "extensions": ["sxd"] }, + "application/vnd.sun.xml.draw.template": { "source": "apache", "extensions": ["std"] }, + "application/vnd.sun.xml.impress": { "source": "apache", "extensions": ["sxi"] }, + "application/vnd.sun.xml.impress.template": { "source": "apache", "extensions": ["sti"] }, + "application/vnd.sun.xml.math": { "source": "apache", "extensions": ["sxm"] }, + "application/vnd.sun.xml.writer": { "source": "apache", "extensions": ["sxw"] }, + "application/vnd.sun.xml.writer.global": { "source": "apache", "extensions": ["sxg"] }, + "application/vnd.sun.xml.writer.template": { "source": "apache", "extensions": ["stw"] }, + "application/vnd.sus-calendar": { "source": "iana", "extensions": ["sus", "susp"] }, + "application/vnd.svd": { "source": "iana", "extensions": ["svd"] }, + "application/vnd.swiftview-ics": { "source": "iana" }, + "application/vnd.sycle+xml": { "source": "iana", "compressible": true }, + "application/vnd.syft+json": { "source": "iana", "compressible": true }, + "application/vnd.symbian.install": { "source": "apache", "extensions": ["sis", "sisx"] }, + "application/vnd.syncml+xml": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["xsm"] }, + "application/vnd.syncml.dm+wbxml": { "source": "iana", "charset": "UTF-8", "extensions": ["bdm"] }, + "application/vnd.syncml.dm+xml": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["xdm"] }, + "application/vnd.syncml.dm.notification": { "source": "iana" }, + "application/vnd.syncml.dmddf+wbxml": { "source": "iana" }, + "application/vnd.syncml.dmddf+xml": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["ddf"] }, + "application/vnd.syncml.dmtnds+wbxml": { "source": "iana" }, + "application/vnd.syncml.dmtnds+xml": { "source": "iana", "charset": "UTF-8", "compressible": true }, + "application/vnd.syncml.ds.notification": { "source": "iana" }, + "application/vnd.tableschema+json": { "source": "iana", "compressible": true }, + "application/vnd.tao.intent-module-archive": { "source": "iana", "extensions": ["tao"] }, + "application/vnd.tcpdump.pcap": { "source": "iana", "extensions": ["pcap", "cap", "dmp"] }, + "application/vnd.think-cell.ppttc+json": { "source": "iana", "compressible": true }, + "application/vnd.tmd.mediaflex.api+xml": { "source": "iana", "compressible": true }, + "application/vnd.tml": { "source": "iana" }, + "application/vnd.tmobile-livetv": { "source": "iana", "extensions": ["tmo"] }, + "application/vnd.tri.onesource": { "source": "iana" }, + "application/vnd.trid.tpt": { "source": "iana", "extensions": ["tpt"] }, + "application/vnd.triscape.mxs": { "source": "iana", "extensions": ["mxs"] }, + "application/vnd.trueapp": { "source": "iana", "extensions": ["tra"] }, + "application/vnd.truedoc": { "source": "iana" }, + "application/vnd.ubisoft.webplayer": { "source": "iana" }, + "application/vnd.ufdl": { "source": "iana", "extensions": ["ufd", "ufdl"] }, + "application/vnd.uiq.theme": { "source": "iana", "extensions": ["utz"] }, + "application/vnd.umajin": { "source": "iana", "extensions": ["umj"] }, + "application/vnd.unity": { "source": "iana", "extensions": ["unityweb"] }, + "application/vnd.uoml+xml": { "source": "iana", "compressible": true, "extensions": ["uoml"] }, + "application/vnd.uplanet.alert": { "source": "iana" }, + "application/vnd.uplanet.alert-wbxml": { "source": "iana" }, + "application/vnd.uplanet.bearer-choice": { "source": "iana" }, + "application/vnd.uplanet.bearer-choice-wbxml": { "source": "iana" }, + "application/vnd.uplanet.cacheop": { "source": "iana" }, + "application/vnd.uplanet.cacheop-wbxml": { "source": "iana" }, + "application/vnd.uplanet.channel": { "source": "iana" }, + "application/vnd.uplanet.channel-wbxml": { "source": "iana" }, + "application/vnd.uplanet.list": { "source": "iana" }, + "application/vnd.uplanet.list-wbxml": { "source": "iana" }, + "application/vnd.uplanet.listcmd": { "source": "iana" }, + "application/vnd.uplanet.listcmd-wbxml": { "source": "iana" }, + "application/vnd.uplanet.signal": { "source": "iana" }, + "application/vnd.uri-map": { "source": "iana" }, + "application/vnd.valve.source.material": { "source": "iana" }, + "application/vnd.vcx": { "source": "iana", "extensions": ["vcx"] }, + "application/vnd.vd-study": { "source": "iana" }, + "application/vnd.vectorworks": { "source": "iana" }, + "application/vnd.vel+json": { "source": "iana", "compressible": true }, + "application/vnd.verimatrix.vcas": { "source": "iana" }, + "application/vnd.veritone.aion+json": { "source": "iana", "compressible": true }, + "application/vnd.veryant.thin": { "source": "iana" }, + "application/vnd.ves.encrypted": { "source": "iana" }, + "application/vnd.vidsoft.vidconference": { "source": "iana" }, + "application/vnd.visio": { "source": "iana", "extensions": ["vsd", "vst", "vss", "vsw"] }, + "application/vnd.visionary": { "source": "iana", "extensions": ["vis"] }, + "application/vnd.vividence.scriptfile": { "source": "iana" }, + "application/vnd.vsf": { "source": "iana", "extensions": ["vsf"] }, + "application/vnd.wap.sic": { "source": "iana" }, + "application/vnd.wap.slc": { "source": "iana" }, + "application/vnd.wap.wbxml": { "source": "iana", "charset": "UTF-8", "extensions": ["wbxml"] }, + "application/vnd.wap.wmlc": { "source": "iana", "extensions": ["wmlc"] }, + "application/vnd.wap.wmlscriptc": { "source": "iana", "extensions": ["wmlsc"] }, + "application/vnd.webturbo": { "source": "iana", "extensions": ["wtb"] }, + "application/vnd.wfa.dpp": { "source": "iana" }, + "application/vnd.wfa.p2p": { "source": "iana" }, + "application/vnd.wfa.wsc": { "source": "iana" }, + "application/vnd.windows.devicepairing": { "source": "iana" }, + "application/vnd.wmc": { "source": "iana" }, + "application/vnd.wmf.bootstrap": { "source": "iana" }, + "application/vnd.wolfram.mathematica": { "source": "iana" }, + "application/vnd.wolfram.mathematica.package": { "source": "iana" }, + "application/vnd.wolfram.player": { "source": "iana", "extensions": ["nbp"] }, + "application/vnd.wordperfect": { "source": "iana", "extensions": ["wpd"] }, + "application/vnd.wqd": { "source": "iana", "extensions": ["wqd"] }, + "application/vnd.wrq-hp3000-labelled": { "source": "iana" }, + "application/vnd.wt.stf": { "source": "iana", "extensions": ["stf"] }, + "application/vnd.wv.csp+wbxml": { "source": "iana" }, + "application/vnd.wv.csp+xml": { "source": "iana", "compressible": true }, + "application/vnd.wv.ssp+xml": { "source": "iana", "compressible": true }, + "application/vnd.xacml+json": { "source": "iana", "compressible": true }, + "application/vnd.xara": { "source": "iana", "extensions": ["xar"] }, + "application/vnd.xfdl": { "source": "iana", "extensions": ["xfdl"] }, + "application/vnd.xfdl.webform": { "source": "iana" }, + "application/vnd.xmi+xml": { "source": "iana", "compressible": true }, + "application/vnd.xmpie.cpkg": { "source": "iana" }, + "application/vnd.xmpie.dpkg": { "source": "iana" }, + "application/vnd.xmpie.plan": { "source": "iana" }, + "application/vnd.xmpie.ppkg": { "source": "iana" }, + "application/vnd.xmpie.xlim": { "source": "iana" }, + "application/vnd.yamaha.hv-dic": { "source": "iana", "extensions": ["hvd"] }, + "application/vnd.yamaha.hv-script": { "source": "iana", "extensions": ["hvs"] }, + "application/vnd.yamaha.hv-voice": { "source": "iana", "extensions": ["hvp"] }, + "application/vnd.yamaha.openscoreformat": { "source": "iana", "extensions": ["osf"] }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { "source": "iana", "compressible": true, "extensions": ["osfpvg"] }, + "application/vnd.yamaha.remote-setup": { "source": "iana" }, + "application/vnd.yamaha.smaf-audio": { "source": "iana", "extensions": ["saf"] }, + "application/vnd.yamaha.smaf-phrase": { "source": "iana", "extensions": ["spf"] }, + "application/vnd.yamaha.through-ngn": { "source": "iana" }, + "application/vnd.yamaha.tunnel-udpencap": { "source": "iana" }, + "application/vnd.yaoweme": { "source": "iana" }, + "application/vnd.yellowriver-custom-menu": { "source": "iana", "extensions": ["cmp"] }, + "application/vnd.youtube.yt": { "source": "iana" }, + "application/vnd.zul": { "source": "iana", "extensions": ["zir", "zirz"] }, + "application/vnd.zzazz.deck+xml": { "source": "iana", "compressible": true, "extensions": ["zaz"] }, + "application/voicexml+xml": { "source": "iana", "compressible": true, "extensions": ["vxml"] }, + "application/voucher-cms+json": { "source": "iana", "compressible": true }, + "application/vq-rtcpxr": { "source": "iana" }, + "application/wasm": { "source": "iana", "compressible": true, "extensions": ["wasm"] }, + "application/watcherinfo+xml": { "source": "iana", "compressible": true, "extensions": ["wif"] }, + "application/webpush-options+json": { "source": "iana", "compressible": true }, + "application/whoispp-query": { "source": "iana" }, + "application/whoispp-response": { "source": "iana" }, + "application/widget": { "source": "iana", "extensions": ["wgt"] }, + "application/winhlp": { "source": "apache", "extensions": ["hlp"] }, + "application/wita": { "source": "iana" }, + "application/wordperfect5.1": { "source": "iana" }, + "application/wsdl+xml": { "source": "iana", "compressible": true, "extensions": ["wsdl"] }, + "application/wspolicy+xml": { "source": "iana", "compressible": true, "extensions": ["wspolicy"] }, + "application/x-7z-compressed": { "source": "apache", "compressible": false, "extensions": ["7z"] }, + "application/x-abiword": { "source": "apache", "extensions": ["abw"] }, + "application/x-ace-compressed": { "source": "apache", "extensions": ["ace"] }, + "application/x-amf": { "source": "apache" }, + "application/x-apple-diskimage": { "source": "apache", "extensions": ["dmg"] }, + "application/x-arj": { "compressible": false, "extensions": ["arj"] }, + "application/x-authorware-bin": { "source": "apache", "extensions": ["aab", "x32", "u32", "vox"] }, + "application/x-authorware-map": { "source": "apache", "extensions": ["aam"] }, + "application/x-authorware-seg": { "source": "apache", "extensions": ["aas"] }, + "application/x-bcpio": { "source": "apache", "extensions": ["bcpio"] }, + "application/x-bdoc": { "compressible": false, "extensions": ["bdoc"] }, + "application/x-bittorrent": { "source": "apache", "extensions": ["torrent"] }, + "application/x-blorb": { "source": "apache", "extensions": ["blb", "blorb"] }, + "application/x-bzip": { "source": "apache", "compressible": false, "extensions": ["bz"] }, + "application/x-bzip2": { "source": "apache", "compressible": false, "extensions": ["bz2", "boz"] }, + "application/x-cbr": { "source": "apache", "extensions": ["cbr", "cba", "cbt", "cbz", "cb7"] }, + "application/x-cdlink": { "source": "apache", "extensions": ["vcd"] }, + "application/x-cfs-compressed": { "source": "apache", "extensions": ["cfs"] }, + "application/x-chat": { "source": "apache", "extensions": ["chat"] }, + "application/x-chess-pgn": { "source": "apache", "extensions": ["pgn"] }, + "application/x-chrome-extension": { "extensions": ["crx"] }, + "application/x-cocoa": { "source": "nginx", "extensions": ["cco"] }, + "application/x-compress": { "source": "apache" }, + "application/x-conference": { "source": "apache", "extensions": ["nsc"] }, + "application/x-cpio": { "source": "apache", "extensions": ["cpio"] }, + "application/x-csh": { "source": "apache", "extensions": ["csh"] }, + "application/x-deb": { "compressible": false }, + "application/x-debian-package": { "source": "apache", "extensions": ["deb", "udeb"] }, + "application/x-dgc-compressed": { "source": "apache", "extensions": ["dgc"] }, + "application/x-director": { "source": "apache", "extensions": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] }, + "application/x-doom": { "source": "apache", "extensions": ["wad"] }, + "application/x-dtbncx+xml": { "source": "apache", "compressible": true, "extensions": ["ncx"] }, + "application/x-dtbook+xml": { "source": "apache", "compressible": true, "extensions": ["dtb"] }, + "application/x-dtbresource+xml": { "source": "apache", "compressible": true, "extensions": ["res"] }, + "application/x-dvi": { "source": "apache", "compressible": false, "extensions": ["dvi"] }, + "application/x-envoy": { "source": "apache", "extensions": ["evy"] }, + "application/x-eva": { "source": "apache", "extensions": ["eva"] }, + "application/x-font-bdf": { "source": "apache", "extensions": ["bdf"] }, + "application/x-font-dos": { "source": "apache" }, + "application/x-font-framemaker": { "source": "apache" }, + "application/x-font-ghostscript": { "source": "apache", "extensions": ["gsf"] }, + "application/x-font-libgrx": { "source": "apache" }, + "application/x-font-linux-psf": { "source": "apache", "extensions": ["psf"] }, + "application/x-font-pcf": { "source": "apache", "extensions": ["pcf"] }, + "application/x-font-snf": { "source": "apache", "extensions": ["snf"] }, + "application/x-font-speedo": { "source": "apache" }, + "application/x-font-sunos-news": { "source": "apache" }, + "application/x-font-type1": { "source": "apache", "extensions": ["pfa", "pfb", "pfm", "afm"] }, + "application/x-font-vfont": { "source": "apache" }, + "application/x-freearc": { "source": "apache", "extensions": ["arc"] }, + "application/x-futuresplash": { "source": "apache", "extensions": ["spl"] }, + "application/x-gca-compressed": { "source": "apache", "extensions": ["gca"] }, + "application/x-glulx": { "source": "apache", "extensions": ["ulx"] }, + "application/x-gnumeric": { "source": "apache", "extensions": ["gnumeric"] }, + "application/x-gramps-xml": { "source": "apache", "extensions": ["gramps"] }, + "application/x-gtar": { "source": "apache", "extensions": ["gtar"] }, + "application/x-gzip": { "source": "apache" }, + "application/x-hdf": { "source": "apache", "extensions": ["hdf"] }, + "application/x-httpd-php": { "compressible": true, "extensions": ["php"] }, + "application/x-install-instructions": { "source": "apache", "extensions": ["install"] }, + "application/x-iso9660-image": { "source": "apache", "extensions": ["iso"] }, + "application/x-iwork-keynote-sffkey": { "extensions": ["key"] }, + "application/x-iwork-numbers-sffnumbers": { "extensions": ["numbers"] }, + "application/x-iwork-pages-sffpages": { "extensions": ["pages"] }, + "application/x-java-archive-diff": { "source": "nginx", "extensions": ["jardiff"] }, + "application/x-java-jnlp-file": { "source": "apache", "compressible": false, "extensions": ["jnlp"] }, + "application/x-javascript": { "compressible": true }, + "application/x-keepass2": { "extensions": ["kdbx"] }, + "application/x-latex": { "source": "apache", "compressible": false, "extensions": ["latex"] }, + "application/x-lua-bytecode": { "extensions": ["luac"] }, + "application/x-lzh-compressed": { "source": "apache", "extensions": ["lzh", "lha"] }, + "application/x-makeself": { "source": "nginx", "extensions": ["run"] }, + "application/x-mie": { "source": "apache", "extensions": ["mie"] }, + "application/x-mobipocket-ebook": { "source": "apache", "extensions": ["prc", "mobi"] }, + "application/x-mpegurl": { "compressible": false }, + "application/x-ms-application": { "source": "apache", "extensions": ["application"] }, + "application/x-ms-shortcut": { "source": "apache", "extensions": ["lnk"] }, + "application/x-ms-wmd": { "source": "apache", "extensions": ["wmd"] }, + "application/x-ms-wmz": { "source": "apache", "extensions": ["wmz"] }, + "application/x-ms-xbap": { "source": "apache", "extensions": ["xbap"] }, + "application/x-msaccess": { "source": "apache", "extensions": ["mdb"] }, + "application/x-msbinder": { "source": "apache", "extensions": ["obd"] }, + "application/x-mscardfile": { "source": "apache", "extensions": ["crd"] }, + "application/x-msclip": { "source": "apache", "extensions": ["clp"] }, + "application/x-msdos-program": { "extensions": ["exe"] }, + "application/x-msdownload": { "source": "apache", "extensions": ["exe", "dll", "com", "bat", "msi"] }, + "application/x-msmediaview": { "source": "apache", "extensions": ["mvb", "m13", "m14"] }, + "application/x-msmetafile": { "source": "apache", "extensions": ["wmf", "wmz", "emf", "emz"] }, + "application/x-msmoney": { "source": "apache", "extensions": ["mny"] }, + "application/x-mspublisher": { "source": "apache", "extensions": ["pub"] }, + "application/x-msschedule": { "source": "apache", "extensions": ["scd"] }, + "application/x-msterminal": { "source": "apache", "extensions": ["trm"] }, + "application/x-mswrite": { "source": "apache", "extensions": ["wri"] }, + "application/x-netcdf": { "source": "apache", "extensions": ["nc", "cdf"] }, + "application/x-ns-proxy-autoconfig": { "compressible": true, "extensions": ["pac"] }, + "application/x-nzb": { "source": "apache", "extensions": ["nzb"] }, + "application/x-perl": { "source": "nginx", "extensions": ["pl", "pm"] }, + "application/x-pilot": { "source": "nginx", "extensions": ["prc", "pdb"] }, + "application/x-pkcs12": { "source": "apache", "compressible": false, "extensions": ["p12", "pfx"] }, + "application/x-pkcs7-certificates": { "source": "apache", "extensions": ["p7b", "spc"] }, + "application/x-pkcs7-certreqresp": { "source": "apache", "extensions": ["p7r"] }, + "application/x-pki-message": { "source": "iana" }, + "application/x-rar-compressed": { "source": "apache", "compressible": false, "extensions": ["rar"] }, + "application/x-redhat-package-manager": { "source": "nginx", "extensions": ["rpm"] }, + "application/x-research-info-systems": { "source": "apache", "extensions": ["ris"] }, + "application/x-sea": { "source": "nginx", "extensions": ["sea"] }, + "application/x-sh": { "source": "apache", "compressible": true, "extensions": ["sh"] }, + "application/x-shar": { "source": "apache", "extensions": ["shar"] }, + "application/x-shockwave-flash": { "source": "apache", "compressible": false, "extensions": ["swf"] }, + "application/x-silverlight-app": { "source": "apache", "extensions": ["xap"] }, + "application/x-sql": { "source": "apache", "extensions": ["sql"] }, + "application/x-stuffit": { "source": "apache", "compressible": false, "extensions": ["sit"] }, + "application/x-stuffitx": { "source": "apache", "extensions": ["sitx"] }, + "application/x-subrip": { "source": "apache", "extensions": ["srt"] }, + "application/x-sv4cpio": { "source": "apache", "extensions": ["sv4cpio"] }, + "application/x-sv4crc": { "source": "apache", "extensions": ["sv4crc"] }, + "application/x-t3vm-image": { "source": "apache", "extensions": ["t3"] }, + "application/x-tads": { "source": "apache", "extensions": ["gam"] }, + "application/x-tar": { "source": "apache", "compressible": true, "extensions": ["tar"] }, + "application/x-tcl": { "source": "apache", "extensions": ["tcl", "tk"] }, + "application/x-tex": { "source": "apache", "extensions": ["tex"] }, + "application/x-tex-tfm": { "source": "apache", "extensions": ["tfm"] }, + "application/x-texinfo": { "source": "apache", "extensions": ["texinfo", "texi"] }, + "application/x-tgif": { "source": "apache", "extensions": ["obj"] }, + "application/x-ustar": { "source": "apache", "extensions": ["ustar"] }, + "application/x-virtualbox-hdd": { "compressible": true, "extensions": ["hdd"] }, + "application/x-virtualbox-ova": { "compressible": true, "extensions": ["ova"] }, + "application/x-virtualbox-ovf": { "compressible": true, "extensions": ["ovf"] }, + "application/x-virtualbox-vbox": { "compressible": true, "extensions": ["vbox"] }, + "application/x-virtualbox-vbox-extpack": { "compressible": false, "extensions": ["vbox-extpack"] }, + "application/x-virtualbox-vdi": { "compressible": true, "extensions": ["vdi"] }, + "application/x-virtualbox-vhd": { "compressible": true, "extensions": ["vhd"] }, + "application/x-virtualbox-vmdk": { "compressible": true, "extensions": ["vmdk"] }, + "application/x-wais-source": { "source": "apache", "extensions": ["src"] }, + "application/x-web-app-manifest+json": { "compressible": true, "extensions": ["webapp"] }, + "application/x-www-form-urlencoded": { "source": "iana", "compressible": true }, + "application/x-x509-ca-cert": { "source": "iana", "extensions": ["der", "crt", "pem"] }, + "application/x-x509-ca-ra-cert": { "source": "iana" }, + "application/x-x509-next-ca-cert": { "source": "iana" }, + "application/x-xfig": { "source": "apache", "extensions": ["fig"] }, + "application/x-xliff+xml": { "source": "apache", "compressible": true, "extensions": ["xlf"] }, + "application/x-xpinstall": { "source": "apache", "compressible": false, "extensions": ["xpi"] }, + "application/x-xz": { "source": "apache", "extensions": ["xz"] }, + "application/x-zmachine": { "source": "apache", "extensions": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] }, + "application/x400-bp": { "source": "iana" }, + "application/xacml+xml": { "source": "iana", "compressible": true }, + "application/xaml+xml": { "source": "apache", "compressible": true, "extensions": ["xaml"] }, + "application/xcap-att+xml": { "source": "iana", "compressible": true, "extensions": ["xav"] }, + "application/xcap-caps+xml": { "source": "iana", "compressible": true, "extensions": ["xca"] }, + "application/xcap-diff+xml": { "source": "iana", "compressible": true, "extensions": ["xdf"] }, + "application/xcap-el+xml": { "source": "iana", "compressible": true, "extensions": ["xel"] }, + "application/xcap-error+xml": { "source": "iana", "compressible": true }, + "application/xcap-ns+xml": { "source": "iana", "compressible": true, "extensions": ["xns"] }, + "application/xcon-conference-info+xml": { "source": "iana", "compressible": true }, + "application/xcon-conference-info-diff+xml": { "source": "iana", "compressible": true }, + "application/xenc+xml": { "source": "iana", "compressible": true, "extensions": ["xenc"] }, + "application/xhtml+xml": { "source": "iana", "compressible": true, "extensions": ["xhtml", "xht"] }, + "application/xhtml-voice+xml": { "source": "apache", "compressible": true }, + "application/xliff+xml": { "source": "iana", "compressible": true, "extensions": ["xlf"] }, + "application/xml": { "source": "iana", "compressible": true, "extensions": ["xml", "xsl", "xsd", "rng"] }, + "application/xml-dtd": { "source": "iana", "compressible": true, "extensions": ["dtd"] }, + "application/xml-external-parsed-entity": { "source": "iana" }, + "application/xml-patch+xml": { "source": "iana", "compressible": true }, + "application/xmpp+xml": { "source": "iana", "compressible": true }, + "application/xop+xml": { "source": "iana", "compressible": true, "extensions": ["xop"] }, + "application/xproc+xml": { "source": "apache", "compressible": true, "extensions": ["xpl"] }, + "application/xslt+xml": { "source": "iana", "compressible": true, "extensions": ["xsl", "xslt"] }, + "application/xspf+xml": { "source": "apache", "compressible": true, "extensions": ["xspf"] }, + "application/xv+xml": { "source": "iana", "compressible": true, "extensions": ["mxml", "xhvml", "xvml", "xvm"] }, + "application/yang": { "source": "iana", "extensions": ["yang"] }, + "application/yang-data+json": { "source": "iana", "compressible": true }, + "application/yang-data+xml": { "source": "iana", "compressible": true }, + "application/yang-patch+json": { "source": "iana", "compressible": true }, + "application/yang-patch+xml": { "source": "iana", "compressible": true }, + "application/yin+xml": { "source": "iana", "compressible": true, "extensions": ["yin"] }, + "application/zip": { "source": "iana", "compressible": false, "extensions": ["zip"] }, + "application/zlib": { "source": "iana" }, + "application/zstd": { "source": "iana" }, + "audio/1d-interleaved-parityfec": { "source": "iana" }, + "audio/32kadpcm": { "source": "iana" }, + "audio/3gpp": { "source": "iana", "compressible": false, "extensions": ["3gpp"] }, + "audio/3gpp2": { "source": "iana" }, + "audio/aac": { "source": "iana" }, + "audio/ac3": { "source": "iana" }, + "audio/adpcm": { "source": "apache", "extensions": ["adp"] }, + "audio/amr": { "source": "iana", "extensions": ["amr"] }, + "audio/amr-wb": { "source": "iana" }, + "audio/amr-wb+": { "source": "iana" }, + "audio/aptx": { "source": "iana" }, + "audio/asc": { "source": "iana" }, + "audio/atrac-advanced-lossless": { "source": "iana" }, + "audio/atrac-x": { "source": "iana" }, + "audio/atrac3": { "source": "iana" }, + "audio/basic": { "source": "iana", "compressible": false, "extensions": ["au", "snd"] }, + "audio/bv16": { "source": "iana" }, + "audio/bv32": { "source": "iana" }, + "audio/clearmode": { "source": "iana" }, + "audio/cn": { "source": "iana" }, + "audio/dat12": { "source": "iana" }, + "audio/dls": { "source": "iana" }, + "audio/dsr-es201108": { "source": "iana" }, + "audio/dsr-es202050": { "source": "iana" }, + "audio/dsr-es202211": { "source": "iana" }, + "audio/dsr-es202212": { "source": "iana" }, + "audio/dv": { "source": "iana" }, + "audio/dvi4": { "source": "iana" }, + "audio/eac3": { "source": "iana" }, + "audio/encaprtp": { "source": "iana" }, + "audio/evrc": { "source": "iana" }, + "audio/evrc-qcp": { "source": "iana" }, + "audio/evrc0": { "source": "iana" }, + "audio/evrc1": { "source": "iana" }, + "audio/evrcb": { "source": "iana" }, + "audio/evrcb0": { "source": "iana" }, + "audio/evrcb1": { "source": "iana" }, + "audio/evrcnw": { "source": "iana" }, + "audio/evrcnw0": { "source": "iana" }, + "audio/evrcnw1": { "source": "iana" }, + "audio/evrcwb": { "source": "iana" }, + "audio/evrcwb0": { "source": "iana" }, + "audio/evrcwb1": { "source": "iana" }, + "audio/evs": { "source": "iana" }, + "audio/flexfec": { "source": "iana" }, + "audio/fwdred": { "source": "iana" }, + "audio/g711-0": { "source": "iana" }, + "audio/g719": { "source": "iana" }, + "audio/g722": { "source": "iana" }, + "audio/g7221": { "source": "iana" }, + "audio/g723": { "source": "iana" }, + "audio/g726-16": { "source": "iana" }, + "audio/g726-24": { "source": "iana" }, + "audio/g726-32": { "source": "iana" }, + "audio/g726-40": { "source": "iana" }, + "audio/g728": { "source": "iana" }, + "audio/g729": { "source": "iana" }, + "audio/g7291": { "source": "iana" }, + "audio/g729d": { "source": "iana" }, + "audio/g729e": { "source": "iana" }, + "audio/gsm": { "source": "iana" }, + "audio/gsm-efr": { "source": "iana" }, + "audio/gsm-hr-08": { "source": "iana" }, + "audio/ilbc": { "source": "iana" }, + "audio/ip-mr_v2.5": { "source": "iana" }, + "audio/isac": { "source": "apache" }, + "audio/l16": { "source": "iana" }, + "audio/l20": { "source": "iana" }, + "audio/l24": { "source": "iana", "compressible": false }, + "audio/l8": { "source": "iana" }, + "audio/lpc": { "source": "iana" }, + "audio/melp": { "source": "iana" }, + "audio/melp1200": { "source": "iana" }, + "audio/melp2400": { "source": "iana" }, + "audio/melp600": { "source": "iana" }, + "audio/mhas": { "source": "iana" }, + "audio/midi": { "source": "apache", "extensions": ["mid", "midi", "kar", "rmi"] }, + "audio/mobile-xmf": { "source": "iana", "extensions": ["mxmf"] }, + "audio/mp3": { "compressible": false, "extensions": ["mp3"] }, + "audio/mp4": { "source": "iana", "compressible": false, "extensions": ["m4a", "mp4a"] }, + "audio/mp4a-latm": { "source": "iana" }, + "audio/mpa": { "source": "iana" }, + "audio/mpa-robust": { "source": "iana" }, + "audio/mpeg": { "source": "iana", "compressible": false, "extensions": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] }, + "audio/mpeg4-generic": { "source": "iana" }, + "audio/musepack": { "source": "apache" }, + "audio/ogg": { "source": "iana", "compressible": false, "extensions": ["oga", "ogg", "spx", "opus"] }, + "audio/opus": { "source": "iana" }, + "audio/parityfec": { "source": "iana" }, + "audio/pcma": { "source": "iana" }, + "audio/pcma-wb": { "source": "iana" }, + "audio/pcmu": { "source": "iana" }, + "audio/pcmu-wb": { "source": "iana" }, + "audio/prs.sid": { "source": "iana" }, + "audio/qcelp": { "source": "iana" }, + "audio/raptorfec": { "source": "iana" }, + "audio/red": { "source": "iana" }, + "audio/rtp-enc-aescm128": { "source": "iana" }, + "audio/rtp-midi": { "source": "iana" }, + "audio/rtploopback": { "source": "iana" }, + "audio/rtx": { "source": "iana" }, + "audio/s3m": { "source": "apache", "extensions": ["s3m"] }, + "audio/scip": { "source": "iana" }, + "audio/silk": { "source": "apache", "extensions": ["sil"] }, + "audio/smv": { "source": "iana" }, + "audio/smv-qcp": { "source": "iana" }, + "audio/smv0": { "source": "iana" }, + "audio/sofa": { "source": "iana" }, + "audio/sp-midi": { "source": "iana" }, + "audio/speex": { "source": "iana" }, + "audio/t140c": { "source": "iana" }, + "audio/t38": { "source": "iana" }, + "audio/telephone-event": { "source": "iana" }, + "audio/tetra_acelp": { "source": "iana" }, + "audio/tetra_acelp_bb": { "source": "iana" }, + "audio/tone": { "source": "iana" }, + "audio/tsvcis": { "source": "iana" }, + "audio/uemclip": { "source": "iana" }, + "audio/ulpfec": { "source": "iana" }, + "audio/usac": { "source": "iana" }, + "audio/vdvi": { "source": "iana" }, + "audio/vmr-wb": { "source": "iana" }, + "audio/vnd.3gpp.iufp": { "source": "iana" }, + "audio/vnd.4sb": { "source": "iana" }, + "audio/vnd.audiokoz": { "source": "iana" }, + "audio/vnd.celp": { "source": "iana" }, + "audio/vnd.cisco.nse": { "source": "iana" }, + "audio/vnd.cmles.radio-events": { "source": "iana" }, + "audio/vnd.cns.anp1": { "source": "iana" }, + "audio/vnd.cns.inf1": { "source": "iana" }, + "audio/vnd.dece.audio": { "source": "iana", "extensions": ["uva", "uvva"] }, + "audio/vnd.digital-winds": { "source": "iana", "extensions": ["eol"] }, + "audio/vnd.dlna.adts": { "source": "iana" }, + "audio/vnd.dolby.heaac.1": { "source": "iana" }, + "audio/vnd.dolby.heaac.2": { "source": "iana" }, + "audio/vnd.dolby.mlp": { "source": "iana" }, + "audio/vnd.dolby.mps": { "source": "iana" }, + "audio/vnd.dolby.pl2": { "source": "iana" }, + "audio/vnd.dolby.pl2x": { "source": "iana" }, + "audio/vnd.dolby.pl2z": { "source": "iana" }, + "audio/vnd.dolby.pulse.1": { "source": "iana" }, + "audio/vnd.dra": { "source": "iana", "extensions": ["dra"] }, + "audio/vnd.dts": { "source": "iana", "extensions": ["dts"] }, + "audio/vnd.dts.hd": { "source": "iana", "extensions": ["dtshd"] }, + "audio/vnd.dts.uhd": { "source": "iana" }, + "audio/vnd.dvb.file": { "source": "iana" }, + "audio/vnd.everad.plj": { "source": "iana" }, + "audio/vnd.hns.audio": { "source": "iana" }, + "audio/vnd.lucent.voice": { "source": "iana", "extensions": ["lvp"] }, + "audio/vnd.ms-playready.media.pya": { "source": "iana", "extensions": ["pya"] }, + "audio/vnd.nokia.mobile-xmf": { "source": "iana" }, + "audio/vnd.nortel.vbk": { "source": "iana" }, + "audio/vnd.nuera.ecelp4800": { "source": "iana", "extensions": ["ecelp4800"] }, + "audio/vnd.nuera.ecelp7470": { "source": "iana", "extensions": ["ecelp7470"] }, + "audio/vnd.nuera.ecelp9600": { "source": "iana", "extensions": ["ecelp9600"] }, + "audio/vnd.octel.sbc": { "source": "iana" }, + "audio/vnd.presonus.multitrack": { "source": "iana" }, + "audio/vnd.qcelp": { "source": "iana" }, + "audio/vnd.rhetorex.32kadpcm": { "source": "iana" }, + "audio/vnd.rip": { "source": "iana", "extensions": ["rip"] }, + "audio/vnd.rn-realaudio": { "compressible": false }, + "audio/vnd.sealedmedia.softseal.mpeg": { "source": "iana" }, + "audio/vnd.vmx.cvsd": { "source": "iana" }, + "audio/vnd.wave": { "compressible": false }, + "audio/vorbis": { "source": "iana", "compressible": false }, + "audio/vorbis-config": { "source": "iana" }, + "audio/wav": { "compressible": false, "extensions": ["wav"] }, + "audio/wave": { "compressible": false, "extensions": ["wav"] }, + "audio/webm": { "source": "apache", "compressible": false, "extensions": ["weba"] }, + "audio/x-aac": { "source": "apache", "compressible": false, "extensions": ["aac"] }, + "audio/x-aiff": { "source": "apache", "extensions": ["aif", "aiff", "aifc"] }, + "audio/x-caf": { "source": "apache", "compressible": false, "extensions": ["caf"] }, + "audio/x-flac": { "source": "apache", "extensions": ["flac"] }, + "audio/x-m4a": { "source": "nginx", "extensions": ["m4a"] }, + "audio/x-matroska": { "source": "apache", "extensions": ["mka"] }, + "audio/x-mpegurl": { "source": "apache", "extensions": ["m3u"] }, + "audio/x-ms-wax": { "source": "apache", "extensions": ["wax"] }, + "audio/x-ms-wma": { "source": "apache", "extensions": ["wma"] }, + "audio/x-pn-realaudio": { "source": "apache", "extensions": ["ram", "ra"] }, + "audio/x-pn-realaudio-plugin": { "source": "apache", "extensions": ["rmp"] }, + "audio/x-realaudio": { "source": "nginx", "extensions": ["ra"] }, + "audio/x-tta": { "source": "apache" }, + "audio/x-wav": { "source": "apache", "extensions": ["wav"] }, + "audio/xm": { "source": "apache", "extensions": ["xm"] }, + "chemical/x-cdx": { "source": "apache", "extensions": ["cdx"] }, + "chemical/x-cif": { "source": "apache", "extensions": ["cif"] }, + "chemical/x-cmdf": { "source": "apache", "extensions": ["cmdf"] }, + "chemical/x-cml": { "source": "apache", "extensions": ["cml"] }, + "chemical/x-csml": { "source": "apache", "extensions": ["csml"] }, + "chemical/x-pdb": { "source": "apache" }, + "chemical/x-xyz": { "source": "apache", "extensions": ["xyz"] }, + "font/collection": { "source": "iana", "extensions": ["ttc"] }, + "font/otf": { "source": "iana", "compressible": true, "extensions": ["otf"] }, + "font/sfnt": { "source": "iana" }, + "font/ttf": { "source": "iana", "compressible": true, "extensions": ["ttf"] }, + "font/woff": { "source": "iana", "extensions": ["woff"] }, + "font/woff2": { "source": "iana", "extensions": ["woff2"] }, + "image/aces": { "source": "iana", "extensions": ["exr"] }, + "image/apng": { "compressible": false, "extensions": ["apng"] }, + "image/avci": { "source": "iana", "extensions": ["avci"] }, + "image/avcs": { "source": "iana", "extensions": ["avcs"] }, + "image/avif": { "source": "iana", "compressible": false, "extensions": ["avif"] }, + "image/bmp": { "source": "iana", "compressible": true, "extensions": ["bmp"] }, + "image/cgm": { "source": "iana", "extensions": ["cgm"] }, + "image/dicom-rle": { "source": "iana", "extensions": ["drle"] }, + "image/emf": { "source": "iana", "extensions": ["emf"] }, + "image/fits": { "source": "iana", "extensions": ["fits"] }, + "image/g3fax": { "source": "iana", "extensions": ["g3"] }, + "image/gif": { "source": "iana", "compressible": false, "extensions": ["gif"] }, + "image/heic": { "source": "iana", "extensions": ["heic"] }, + "image/heic-sequence": { "source": "iana", "extensions": ["heics"] }, + "image/heif": { "source": "iana", "extensions": ["heif"] }, + "image/heif-sequence": { "source": "iana", "extensions": ["heifs"] }, + "image/hej2k": { "source": "iana", "extensions": ["hej2"] }, + "image/hsj2": { "source": "iana", "extensions": ["hsj2"] }, + "image/ief": { "source": "iana", "extensions": ["ief"] }, + "image/jls": { "source": "iana", "extensions": ["jls"] }, + "image/jp2": { "source": "iana", "compressible": false, "extensions": ["jp2", "jpg2"] }, + "image/jpeg": { "source": "iana", "compressible": false, "extensions": ["jpeg", "jpg", "jpe"] }, + "image/jph": { "source": "iana", "extensions": ["jph"] }, + "image/jphc": { "source": "iana", "extensions": ["jhc"] }, + "image/jpm": { "source": "iana", "compressible": false, "extensions": ["jpm"] }, + "image/jpx": { "source": "iana", "compressible": false, "extensions": ["jpx", "jpf"] }, + "image/jxr": { "source": "iana", "extensions": ["jxr"] }, + "image/jxra": { "source": "iana", "extensions": ["jxra"] }, + "image/jxrs": { "source": "iana", "extensions": ["jxrs"] }, + "image/jxs": { "source": "iana", "extensions": ["jxs"] }, + "image/jxsc": { "source": "iana", "extensions": ["jxsc"] }, + "image/jxsi": { "source": "iana", "extensions": ["jxsi"] }, + "image/jxss": { "source": "iana", "extensions": ["jxss"] }, + "image/ktx": { "source": "iana", "extensions": ["ktx"] }, + "image/ktx2": { "source": "iana", "extensions": ["ktx2"] }, + "image/naplps": { "source": "iana" }, + "image/pjpeg": { "compressible": false }, + "image/png": { "source": "iana", "compressible": false, "extensions": ["png"] }, + "image/prs.btif": { "source": "iana", "extensions": ["btif"] }, + "image/prs.pti": { "source": "iana", "extensions": ["pti"] }, + "image/pwg-raster": { "source": "iana" }, + "image/sgi": { "source": "apache", "extensions": ["sgi"] }, + "image/svg+xml": { "source": "iana", "compressible": true, "extensions": ["svg", "svgz"] }, + "image/t38": { "source": "iana", "extensions": ["t38"] }, + "image/tiff": { "source": "iana", "compressible": false, "extensions": ["tif", "tiff"] }, + "image/tiff-fx": { "source": "iana", "extensions": ["tfx"] }, + "image/vnd.adobe.photoshop": { "source": "iana", "compressible": true, "extensions": ["psd"] }, + "image/vnd.airzip.accelerator.azv": { "source": "iana", "extensions": ["azv"] }, + "image/vnd.cns.inf2": { "source": "iana" }, + "image/vnd.dece.graphic": { "source": "iana", "extensions": ["uvi", "uvvi", "uvg", "uvvg"] }, + "image/vnd.djvu": { "source": "iana", "extensions": ["djvu", "djv"] }, + "image/vnd.dvb.subtitle": { "source": "iana", "extensions": ["sub"] }, + "image/vnd.dwg": { "source": "iana", "extensions": ["dwg"] }, + "image/vnd.dxf": { "source": "iana", "extensions": ["dxf"] }, + "image/vnd.fastbidsheet": { "source": "iana", "extensions": ["fbs"] }, + "image/vnd.fpx": { "source": "iana", "extensions": ["fpx"] }, + "image/vnd.fst": { "source": "iana", "extensions": ["fst"] }, + "image/vnd.fujixerox.edmics-mmr": { "source": "iana", "extensions": ["mmr"] }, + "image/vnd.fujixerox.edmics-rlc": { "source": "iana", "extensions": ["rlc"] }, + "image/vnd.globalgraphics.pgb": { "source": "iana" }, + "image/vnd.microsoft.icon": { "source": "iana", "compressible": true, "extensions": ["ico"] }, + "image/vnd.mix": { "source": "iana" }, + "image/vnd.mozilla.apng": { "source": "iana" }, + "image/vnd.ms-dds": { "compressible": true, "extensions": ["dds"] }, + "image/vnd.ms-modi": { "source": "iana", "extensions": ["mdi"] }, + "image/vnd.ms-photo": { "source": "apache", "extensions": ["wdp"] }, + "image/vnd.net-fpx": { "source": "iana", "extensions": ["npx"] }, + "image/vnd.pco.b16": { "source": "iana", "extensions": ["b16"] }, + "image/vnd.radiance": { "source": "iana" }, + "image/vnd.sealed.png": { "source": "iana" }, + "image/vnd.sealedmedia.softseal.gif": { "source": "iana" }, + "image/vnd.sealedmedia.softseal.jpg": { "source": "iana" }, + "image/vnd.svf": { "source": "iana" }, + "image/vnd.tencent.tap": { "source": "iana", "extensions": ["tap"] }, + "image/vnd.valve.source.texture": { "source": "iana", "extensions": ["vtf"] }, + "image/vnd.wap.wbmp": { "source": "iana", "extensions": ["wbmp"] }, + "image/vnd.xiff": { "source": "iana", "extensions": ["xif"] }, + "image/vnd.zbrush.pcx": { "source": "iana", "extensions": ["pcx"] }, + "image/webp": { "source": "apache", "extensions": ["webp"] }, + "image/wmf": { "source": "iana", "extensions": ["wmf"] }, + "image/x-3ds": { "source": "apache", "extensions": ["3ds"] }, + "image/x-cmu-raster": { "source": "apache", "extensions": ["ras"] }, + "image/x-cmx": { "source": "apache", "extensions": ["cmx"] }, + "image/x-freehand": { "source": "apache", "extensions": ["fh", "fhc", "fh4", "fh5", "fh7"] }, + "image/x-icon": { "source": "apache", "compressible": true, "extensions": ["ico"] }, + "image/x-jng": { "source": "nginx", "extensions": ["jng"] }, + "image/x-mrsid-image": { "source": "apache", "extensions": ["sid"] }, + "image/x-ms-bmp": { "source": "nginx", "compressible": true, "extensions": ["bmp"] }, + "image/x-pcx": { "source": "apache", "extensions": ["pcx"] }, + "image/x-pict": { "source": "apache", "extensions": ["pic", "pct"] }, + "image/x-portable-anymap": { "source": "apache", "extensions": ["pnm"] }, + "image/x-portable-bitmap": { "source": "apache", "extensions": ["pbm"] }, + "image/x-portable-graymap": { "source": "apache", "extensions": ["pgm"] }, + "image/x-portable-pixmap": { "source": "apache", "extensions": ["ppm"] }, + "image/x-rgb": { "source": "apache", "extensions": ["rgb"] }, + "image/x-tga": { "source": "apache", "extensions": ["tga"] }, + "image/x-xbitmap": { "source": "apache", "extensions": ["xbm"] }, + "image/x-xcf": { "compressible": false }, + "image/x-xpixmap": { "source": "apache", "extensions": ["xpm"] }, + "image/x-xwindowdump": { "source": "apache", "extensions": ["xwd"] }, + "message/cpim": { "source": "iana" }, + "message/delivery-status": { "source": "iana" }, + "message/disposition-notification": { "source": "iana", "extensions": ["disposition-notification"] }, + "message/external-body": { "source": "iana" }, + "message/feedback-report": { "source": "iana" }, + "message/global": { "source": "iana", "extensions": ["u8msg"] }, + "message/global-delivery-status": { "source": "iana", "extensions": ["u8dsn"] }, + "message/global-disposition-notification": { "source": "iana", "extensions": ["u8mdn"] }, + "message/global-headers": { "source": "iana", "extensions": ["u8hdr"] }, + "message/http": { "source": "iana", "compressible": false }, + "message/imdn+xml": { "source": "iana", "compressible": true }, + "message/news": { "source": "iana" }, + "message/partial": { "source": "iana", "compressible": false }, + "message/rfc822": { "source": "iana", "compressible": true, "extensions": ["eml", "mime"] }, + "message/s-http": { "source": "iana" }, + "message/sip": { "source": "iana" }, + "message/sipfrag": { "source": "iana" }, + "message/tracking-status": { "source": "iana" }, + "message/vnd.si.simp": { "source": "iana" }, + "message/vnd.wfa.wsc": { "source": "iana", "extensions": ["wsc"] }, + "model/3mf": { "source": "iana", "extensions": ["3mf"] }, + "model/e57": { "source": "iana" }, + "model/gltf+json": { "source": "iana", "compressible": true, "extensions": ["gltf"] }, + "model/gltf-binary": { "source": "iana", "compressible": true, "extensions": ["glb"] }, + "model/iges": { "source": "iana", "compressible": false, "extensions": ["igs", "iges"] }, + "model/mesh": { "source": "iana", "compressible": false, "extensions": ["msh", "mesh", "silo"] }, + "model/mtl": { "source": "iana", "extensions": ["mtl"] }, + "model/obj": { "source": "iana", "extensions": ["obj"] }, + "model/step": { "source": "iana" }, + "model/step+xml": { "source": "iana", "compressible": true, "extensions": ["stpx"] }, + "model/step+zip": { "source": "iana", "compressible": false, "extensions": ["stpz"] }, + "model/step-xml+zip": { "source": "iana", "compressible": false, "extensions": ["stpxz"] }, + "model/stl": { "source": "iana", "extensions": ["stl"] }, + "model/vnd.collada+xml": { "source": "iana", "compressible": true, "extensions": ["dae"] }, + "model/vnd.dwf": { "source": "iana", "extensions": ["dwf"] }, + "model/vnd.flatland.3dml": { "source": "iana" }, + "model/vnd.gdl": { "source": "iana", "extensions": ["gdl"] }, + "model/vnd.gs-gdl": { "source": "apache" }, + "model/vnd.gs.gdl": { "source": "iana" }, + "model/vnd.gtw": { "source": "iana", "extensions": ["gtw"] }, + "model/vnd.moml+xml": { "source": "iana", "compressible": true }, + "model/vnd.mts": { "source": "iana", "extensions": ["mts"] }, + "model/vnd.opengex": { "source": "iana", "extensions": ["ogex"] }, + "model/vnd.parasolid.transmit.binary": { "source": "iana", "extensions": ["x_b"] }, + "model/vnd.parasolid.transmit.text": { "source": "iana", "extensions": ["x_t"] }, + "model/vnd.pytha.pyox": { "source": "iana" }, + "model/vnd.rosette.annotated-data-model": { "source": "iana" }, + "model/vnd.sap.vds": { "source": "iana", "extensions": ["vds"] }, + "model/vnd.usdz+zip": { "source": "iana", "compressible": false, "extensions": ["usdz"] }, + "model/vnd.valve.source.compiled-map": { "source": "iana", "extensions": ["bsp"] }, + "model/vnd.vtu": { "source": "iana", "extensions": ["vtu"] }, + "model/vrml": { "source": "iana", "compressible": false, "extensions": ["wrl", "vrml"] }, + "model/x3d+binary": { "source": "apache", "compressible": false, "extensions": ["x3db", "x3dbz"] }, + "model/x3d+fastinfoset": { "source": "iana", "extensions": ["x3db"] }, + "model/x3d+vrml": { "source": "apache", "compressible": false, "extensions": ["x3dv", "x3dvz"] }, + "model/x3d+xml": { "source": "iana", "compressible": true, "extensions": ["x3d", "x3dz"] }, + "model/x3d-vrml": { "source": "iana", "extensions": ["x3dv"] }, + "multipart/alternative": { "source": "iana", "compressible": false }, + "multipart/appledouble": { "source": "iana" }, + "multipart/byteranges": { "source": "iana" }, + "multipart/digest": { "source": "iana" }, + "multipart/encrypted": { "source": "iana", "compressible": false }, + "multipart/form-data": { "source": "iana", "compressible": false }, + "multipart/header-set": { "source": "iana" }, + "multipart/mixed": { "source": "iana" }, + "multipart/multilingual": { "source": "iana" }, + "multipart/parallel": { "source": "iana" }, + "multipart/related": { "source": "iana", "compressible": false }, + "multipart/report": { "source": "iana" }, + "multipart/signed": { "source": "iana", "compressible": false }, + "multipart/vnd.bint.med-plus": { "source": "iana" }, + "multipart/voice-message": { "source": "iana" }, + "multipart/x-mixed-replace": { "source": "iana" }, + "text/1d-interleaved-parityfec": { "source": "iana" }, + "text/cache-manifest": { "source": "iana", "compressible": true, "extensions": ["appcache", "manifest"] }, + "text/calendar": { "source": "iana", "extensions": ["ics", "ifb"] }, + "text/calender": { "compressible": true }, + "text/cmd": { "compressible": true }, + "text/coffeescript": { "extensions": ["coffee", "litcoffee"] }, + "text/cql": { "source": "iana" }, + "text/cql-expression": { "source": "iana" }, + "text/cql-identifier": { "source": "iana" }, + "text/css": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["css"] }, + "text/csv": { "source": "iana", "compressible": true, "extensions": ["csv"] }, + "text/csv-schema": { "source": "iana" }, + "text/directory": { "source": "iana" }, + "text/dns": { "source": "iana" }, + "text/ecmascript": { "source": "iana" }, + "text/encaprtp": { "source": "iana" }, + "text/enriched": { "source": "iana" }, + "text/fhirpath": { "source": "iana" }, + "text/flexfec": { "source": "iana" }, + "text/fwdred": { "source": "iana" }, + "text/gff3": { "source": "iana" }, + "text/grammar-ref-list": { "source": "iana" }, + "text/html": { "source": "iana", "compressible": true, "extensions": ["html", "htm", "shtml"] }, + "text/jade": { "extensions": ["jade"] }, + "text/javascript": { "source": "iana", "compressible": true }, + "text/jcr-cnd": { "source": "iana" }, + "text/jsx": { "compressible": true, "extensions": ["jsx"] }, + "text/less": { "compressible": true, "extensions": ["less"] }, + "text/markdown": { "source": "iana", "compressible": true, "extensions": ["markdown", "md"] }, + "text/mathml": { "source": "nginx", "extensions": ["mml"] }, + "text/mdx": { "compressible": true, "extensions": ["mdx"] }, + "text/mizar": { "source": "iana" }, + "text/n3": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["n3"] }, + "text/parameters": { "source": "iana", "charset": "UTF-8" }, + "text/parityfec": { "source": "iana" }, + "text/plain": { "source": "iana", "compressible": true, "extensions": ["txt", "text", "conf", "def", "list", "log", "in", "ini"] }, + "text/provenance-notation": { "source": "iana", "charset": "UTF-8" }, + "text/prs.fallenstein.rst": { "source": "iana" }, + "text/prs.lines.tag": { "source": "iana", "extensions": ["dsc"] }, + "text/prs.prop.logic": { "source": "iana" }, + "text/raptorfec": { "source": "iana" }, + "text/red": { "source": "iana" }, + "text/rfc822-headers": { "source": "iana" }, + "text/richtext": { "source": "iana", "compressible": true, "extensions": ["rtx"] }, + "text/rtf": { "source": "iana", "compressible": true, "extensions": ["rtf"] }, + "text/rtp-enc-aescm128": { "source": "iana" }, + "text/rtploopback": { "source": "iana" }, + "text/rtx": { "source": "iana" }, + "text/sgml": { "source": "iana", "extensions": ["sgml", "sgm"] }, + "text/shaclc": { "source": "iana" }, + "text/shex": { "source": "iana", "extensions": ["shex"] }, + "text/slim": { "extensions": ["slim", "slm"] }, + "text/spdx": { "source": "iana", "extensions": ["spdx"] }, + "text/strings": { "source": "iana" }, + "text/stylus": { "extensions": ["stylus", "styl"] }, + "text/t140": { "source": "iana" }, + "text/tab-separated-values": { "source": "iana", "compressible": true, "extensions": ["tsv"] }, + "text/troff": { "source": "iana", "extensions": ["t", "tr", "roff", "man", "me", "ms"] }, + "text/turtle": { "source": "iana", "charset": "UTF-8", "extensions": ["ttl"] }, + "text/ulpfec": { "source": "iana" }, + "text/uri-list": { "source": "iana", "compressible": true, "extensions": ["uri", "uris", "urls"] }, + "text/vcard": { "source": "iana", "compressible": true, "extensions": ["vcard"] }, + "text/vnd.a": { "source": "iana" }, + "text/vnd.abc": { "source": "iana" }, + "text/vnd.ascii-art": { "source": "iana" }, + "text/vnd.curl": { "source": "iana", "extensions": ["curl"] }, + "text/vnd.curl.dcurl": { "source": "apache", "extensions": ["dcurl"] }, + "text/vnd.curl.mcurl": { "source": "apache", "extensions": ["mcurl"] }, + "text/vnd.curl.scurl": { "source": "apache", "extensions": ["scurl"] }, + "text/vnd.debian.copyright": { "source": "iana", "charset": "UTF-8" }, + "text/vnd.dmclientscript": { "source": "iana" }, + "text/vnd.dvb.subtitle": { "source": "iana", "extensions": ["sub"] }, + "text/vnd.esmertec.theme-descriptor": { "source": "iana", "charset": "UTF-8" }, + "text/vnd.familysearch.gedcom": { "source": "iana", "extensions": ["ged"] }, + "text/vnd.ficlab.flt": { "source": "iana" }, + "text/vnd.fly": { "source": "iana", "extensions": ["fly"] }, + "text/vnd.fmi.flexstor": { "source": "iana", "extensions": ["flx"] }, + "text/vnd.gml": { "source": "iana" }, + "text/vnd.graphviz": { "source": "iana", "extensions": ["gv"] }, + "text/vnd.hans": { "source": "iana" }, + "text/vnd.hgl": { "source": "iana" }, + "text/vnd.in3d.3dml": { "source": "iana", "extensions": ["3dml"] }, + "text/vnd.in3d.spot": { "source": "iana", "extensions": ["spot"] }, + "text/vnd.iptc.newsml": { "source": "iana" }, + "text/vnd.iptc.nitf": { "source": "iana" }, + "text/vnd.latex-z": { "source": "iana" }, + "text/vnd.motorola.reflex": { "source": "iana" }, + "text/vnd.ms-mediapackage": { "source": "iana" }, + "text/vnd.net2phone.commcenter.command": { "source": "iana" }, + "text/vnd.radisys.msml-basic-layout": { "source": "iana" }, + "text/vnd.senx.warpscript": { "source": "iana" }, + "text/vnd.si.uricatalogue": { "source": "iana" }, + "text/vnd.sosi": { "source": "iana" }, + "text/vnd.sun.j2me.app-descriptor": { "source": "iana", "charset": "UTF-8", "extensions": ["jad"] }, + "text/vnd.trolltech.linguist": { "source": "iana", "charset": "UTF-8" }, + "text/vnd.wap.si": { "source": "iana" }, + "text/vnd.wap.sl": { "source": "iana" }, + "text/vnd.wap.wml": { "source": "iana", "extensions": ["wml"] }, + "text/vnd.wap.wmlscript": { "source": "iana", "extensions": ["wmls"] }, + "text/vtt": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["vtt"] }, + "text/x-asm": { "source": "apache", "extensions": ["s", "asm"] }, + "text/x-c": { "source": "apache", "extensions": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] }, + "text/x-component": { "source": "nginx", "extensions": ["htc"] }, + "text/x-fortran": { "source": "apache", "extensions": ["f", "for", "f77", "f90"] }, + "text/x-gwt-rpc": { "compressible": true }, + "text/x-handlebars-template": { "extensions": ["hbs"] }, + "text/x-java-source": { "source": "apache", "extensions": ["java"] }, + "text/x-jquery-tmpl": { "compressible": true }, + "text/x-lua": { "extensions": ["lua"] }, + "text/x-markdown": { "compressible": true, "extensions": ["mkd"] }, + "text/x-nfo": { "source": "apache", "extensions": ["nfo"] }, + "text/x-opml": { "source": "apache", "extensions": ["opml"] }, + "text/x-org": { "compressible": true, "extensions": ["org"] }, + "text/x-pascal": { "source": "apache", "extensions": ["p", "pas"] }, + "text/x-processing": { "compressible": true, "extensions": ["pde"] }, + "text/x-sass": { "extensions": ["sass"] }, + "text/x-scss": { "extensions": ["scss"] }, + "text/x-setext": { "source": "apache", "extensions": ["etx"] }, + "text/x-sfv": { "source": "apache", "extensions": ["sfv"] }, + "text/x-suse-ymp": { "compressible": true, "extensions": ["ymp"] }, + "text/x-uuencode": { "source": "apache", "extensions": ["uu"] }, + "text/x-vcalendar": { "source": "apache", "extensions": ["vcs"] }, + "text/x-vcard": { "source": "apache", "extensions": ["vcf"] }, + "text/xml": { "source": "iana", "compressible": true, "extensions": ["xml"] }, + "text/xml-external-parsed-entity": { "source": "iana" }, + "text/yaml": { "compressible": true, "extensions": ["yaml", "yml"] }, + "video/1d-interleaved-parityfec": { "source": "iana" }, + "video/3gpp": { "source": "iana", "extensions": ["3gp", "3gpp"] }, + "video/3gpp-tt": { "source": "iana" }, + "video/3gpp2": { "source": "iana", "extensions": ["3g2"] }, + "video/av1": { "source": "iana" }, + "video/bmpeg": { "source": "iana" }, + "video/bt656": { "source": "iana" }, + "video/celb": { "source": "iana" }, + "video/dv": { "source": "iana" }, + "video/encaprtp": { "source": "iana" }, + "video/ffv1": { "source": "iana" }, + "video/flexfec": { "source": "iana" }, + "video/h261": { "source": "iana", "extensions": ["h261"] }, + "video/h263": { "source": "iana", "extensions": ["h263"] }, + "video/h263-1998": { "source": "iana" }, + "video/h263-2000": { "source": "iana" }, + "video/h264": { "source": "iana", "extensions": ["h264"] }, + "video/h264-rcdo": { "source": "iana" }, + "video/h264-svc": { "source": "iana" }, + "video/h265": { "source": "iana" }, + "video/iso.segment": { "source": "iana", "extensions": ["m4s"] }, + "video/jpeg": { "source": "iana", "extensions": ["jpgv"] }, + "video/jpeg2000": { "source": "iana" }, + "video/jpm": { "source": "apache", "extensions": ["jpm", "jpgm"] }, + "video/jxsv": { "source": "iana" }, + "video/mj2": { "source": "iana", "extensions": ["mj2", "mjp2"] }, + "video/mp1s": { "source": "iana" }, + "video/mp2p": { "source": "iana" }, + "video/mp2t": { "source": "iana", "extensions": ["ts"] }, + "video/mp4": { "source": "iana", "compressible": false, "extensions": ["mp4", "mp4v", "mpg4"] }, + "video/mp4v-es": { "source": "iana" }, + "video/mpeg": { "source": "iana", "compressible": false, "extensions": ["mpeg", "mpg", "mpe", "m1v", "m2v"] }, + "video/mpeg4-generic": { "source": "iana" }, + "video/mpv": { "source": "iana" }, + "video/nv": { "source": "iana" }, + "video/ogg": { "source": "iana", "compressible": false, "extensions": ["ogv"] }, + "video/parityfec": { "source": "iana" }, + "video/pointer": { "source": "iana" }, + "video/quicktime": { "source": "iana", "compressible": false, "extensions": ["qt", "mov"] }, + "video/raptorfec": { "source": "iana" }, + "video/raw": { "source": "iana" }, + "video/rtp-enc-aescm128": { "source": "iana" }, + "video/rtploopback": { "source": "iana" }, + "video/rtx": { "source": "iana" }, + "video/scip": { "source": "iana" }, + "video/smpte291": { "source": "iana" }, + "video/smpte292m": { "source": "iana" }, + "video/ulpfec": { "source": "iana" }, + "video/vc1": { "source": "iana" }, + "video/vc2": { "source": "iana" }, + "video/vnd.cctv": { "source": "iana" }, + "video/vnd.dece.hd": { "source": "iana", "extensions": ["uvh", "uvvh"] }, + "video/vnd.dece.mobile": { "source": "iana", "extensions": ["uvm", "uvvm"] }, + "video/vnd.dece.mp4": { "source": "iana" }, + "video/vnd.dece.pd": { "source": "iana", "extensions": ["uvp", "uvvp"] }, + "video/vnd.dece.sd": { "source": "iana", "extensions": ["uvs", "uvvs"] }, + "video/vnd.dece.video": { "source": "iana", "extensions": ["uvv", "uvvv"] }, + "video/vnd.directv.mpeg": { "source": "iana" }, + "video/vnd.directv.mpeg-tts": { "source": "iana" }, + "video/vnd.dlna.mpeg-tts": { "source": "iana" }, + "video/vnd.dvb.file": { "source": "iana", "extensions": ["dvb"] }, + "video/vnd.fvt": { "source": "iana", "extensions": ["fvt"] }, + "video/vnd.hns.video": { "source": "iana" }, + "video/vnd.iptvforum.1dparityfec-1010": { "source": "iana" }, + "video/vnd.iptvforum.1dparityfec-2005": { "source": "iana" }, + "video/vnd.iptvforum.2dparityfec-1010": { "source": "iana" }, + "video/vnd.iptvforum.2dparityfec-2005": { "source": "iana" }, + "video/vnd.iptvforum.ttsavc": { "source": "iana" }, + "video/vnd.iptvforum.ttsmpeg2": { "source": "iana" }, + "video/vnd.motorola.video": { "source": "iana" }, + "video/vnd.motorola.videop": { "source": "iana" }, + "video/vnd.mpegurl": { "source": "iana", "extensions": ["mxu", "m4u"] }, + "video/vnd.ms-playready.media.pyv": { "source": "iana", "extensions": ["pyv"] }, + "video/vnd.nokia.interleaved-multimedia": { "source": "iana" }, + "video/vnd.nokia.mp4vr": { "source": "iana" }, + "video/vnd.nokia.videovoip": { "source": "iana" }, + "video/vnd.objectvideo": { "source": "iana" }, + "video/vnd.radgamettools.bink": { "source": "iana" }, + "video/vnd.radgamettools.smacker": { "source": "iana" }, + "video/vnd.sealed.mpeg1": { "source": "iana" }, + "video/vnd.sealed.mpeg4": { "source": "iana" }, + "video/vnd.sealed.swf": { "source": "iana" }, + "video/vnd.sealedmedia.softseal.mov": { "source": "iana" }, + "video/vnd.uvvu.mp4": { "source": "iana", "extensions": ["uvu", "uvvu"] }, + "video/vnd.vivo": { "source": "iana", "extensions": ["viv"] }, + "video/vnd.youtube.yt": { "source": "iana" }, + "video/vp8": { "source": "iana" }, + "video/vp9": { "source": "iana" }, + "video/webm": { "source": "apache", "compressible": false, "extensions": ["webm"] }, + "video/x-f4v": { "source": "apache", "extensions": ["f4v"] }, + "video/x-fli": { "source": "apache", "extensions": ["fli"] }, + "video/x-flv": { "source": "apache", "compressible": false, "extensions": ["flv"] }, + "video/x-m4v": { "source": "apache", "extensions": ["m4v"] }, + "video/x-matroska": { "source": "apache", "compressible": false, "extensions": ["mkv", "mk3d", "mks"] }, + "video/x-mng": { "source": "apache", "extensions": ["mng"] }, + "video/x-ms-asf": { "source": "apache", "extensions": ["asf", "asx"] }, + "video/x-ms-vob": { "source": "apache", "extensions": ["vob"] }, + "video/x-ms-wm": { "source": "apache", "extensions": ["wm"] }, + "video/x-ms-wmv": { "source": "apache", "compressible": false, "extensions": ["wmv"] }, + "video/x-ms-wmx": { "source": "apache", "extensions": ["wmx"] }, + "video/x-ms-wvx": { "source": "apache", "extensions": ["wvx"] }, + "video/x-msvideo": { "source": "apache", "extensions": ["avi"] }, + "video/x-sgi-movie": { "source": "apache", "extensions": ["movie"] }, + "video/x-smv": { "source": "apache", "extensions": ["smv"] }, + "x-conference/x-cooltalk": { "source": "apache", "extensions": ["ice"] }, + "x-shader/x-fragment": { "compressible": true }, + "x-shader/x-vertex": { "compressible": true } +}; +var mimeDb; +var hasRequiredMimeDb; +function requireMimeDb() { + if (hasRequiredMimeDb) return mimeDb; + hasRequiredMimeDb = 1; + mimeDb = require$$0; + return mimeDb; +} +var hasRequiredMimeTypes; +function requireMimeTypes() { + if (hasRequiredMimeTypes) return mimeTypes; + hasRequiredMimeTypes = 1; + (function(exports$1) { + var db = requireMimeDb(); + var extname = require$$1.extname; + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + exports$1.charset = charset; + exports$1.charsets = { lookup: charset }; + exports$1.contentType = contentType; + exports$1.extension = extension2; + exports$1.extensions = /* @__PURE__ */ Object.create(null); + exports$1.lookup = lookup; + exports$1.types = /* @__PURE__ */ Object.create(null); + populateMaps(exports$1.extensions, exports$1.types); + function charset(type2) { + if (!type2 || typeof type2 !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type2); + var mime = match && db[match[1].toLowerCase()]; + if (mime && mime.charset) { + return mime.charset; + } + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return "UTF-8"; + } + return false; + } + function contentType(str) { + if (!str || typeof str !== "string") { + return false; + } + var mime = str.indexOf("/") === -1 ? exports$1.lookup(str) : str; + if (!mime) { + return false; + } + if (mime.indexOf("charset") === -1) { + var charset2 = exports$1.charset(mime); + if (charset2) mime += "; charset=" + charset2.toLowerCase(); + } + return mime; + } + function extension2(type2) { + if (!type2 || typeof type2 !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type2); + var exts = match && exports$1.extensions[match[1].toLowerCase()]; + if (!exts || !exts.length) { + return false; + } + return exts[0]; + } + function lookup(path) { + if (!path || typeof path !== "string") { + return false; + } + var extension3 = extname("x." + path).toLowerCase().substr(1); + if (!extension3) { + return false; + } + return exports$1.types[extension3] || false; + } + function populateMaps(extensions, types2) { + var preference = ["nginx", "apache", void 0, "iana"]; + Object.keys(db).forEach(function forEachMimeType(type2) { + var mime = db[type2]; + var exts = mime.extensions; + if (!exts || !exts.length) { + return; + } + extensions[type2] = exts; + for (var i = 0; i < exts.length; i++) { + var extension3 = exts[i]; + if (types2[extension3]) { + var from = preference.indexOf(db[types2[extension3]].source); + var to = preference.indexOf(mime.source); + if (types2[extension3] !== "application/octet-stream" && (from > to || from === to && types2[extension3].substr(0, 12) === "application/")) { + continue; + } + } + types2[extension3] = type2; + } + }); + } + })(mimeTypes); + return mimeTypes; +} +var defer_1; +var hasRequiredDefer; +function requireDefer() { + if (hasRequiredDefer) return defer_1; + hasRequiredDefer = 1; + defer_1 = defer; + function defer(fn) { + var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null; + if (nextTick) { + nextTick(fn); + } else { + setTimeout(fn, 0); + } + } + return defer_1; +} +var async_1; +var hasRequiredAsync; +function requireAsync() { + if (hasRequiredAsync) return async_1; + hasRequiredAsync = 1; + var defer = requireDefer(); + async_1 = async; + function async(callback) { + var isAsync = false; + defer(function() { + isAsync = true; + }); + return function async_callback(err, result) { + if (isAsync) { + callback(err, result); + } else { + defer(function nextTick_callback() { + callback(err, result); + }); + } + }; + } + return async_1; +} +var abort_1; +var hasRequiredAbort; +function requireAbort() { + if (hasRequiredAbort) return abort_1; + hasRequiredAbort = 1; + abort_1 = abort; + function abort(state) { + Object.keys(state.jobs).forEach(clean.bind(state)); + state.jobs = {}; + } + function clean(key) { + if (typeof this.jobs[key] == "function") { + this.jobs[key](); + } + } + return abort_1; +} +var iterate_1; +var hasRequiredIterate; +function requireIterate() { + if (hasRequiredIterate) return iterate_1; + hasRequiredIterate = 1; + var async = requireAsync(), abort = requireAbort(); + iterate_1 = iterate; + function iterate(list2, iterator2, state, callback) { + var key = state["keyedList"] ? state["keyedList"][state.index] : state.index; + state.jobs[key] = runJob(iterator2, key, list2[key], function(error, output) { + if (!(key in state.jobs)) { + return; + } + delete state.jobs[key]; + if (error) { + abort(state); + } else { + state.results[key] = output; + } + callback(error, state.results); + }); + } + function runJob(iterator2, key, item, callback) { + var aborter; + if (iterator2.length == 2) { + aborter = iterator2(item, async(callback)); + } else { + aborter = iterator2(item, key, async(callback)); + } + return aborter; + } + return iterate_1; +} +var state_1; +var hasRequiredState; +function requireState() { + if (hasRequiredState) return state_1; + hasRequiredState = 1; + state_1 = state; + function state(list2, sortMethod) { + var isNamedList = !Array.isArray(list2), initState = { + index: 0, + keyedList: isNamedList || sortMethod ? Object.keys(list2) : null, + jobs: {}, + results: isNamedList ? {} : [], + size: isNamedList ? Object.keys(list2).length : list2.length + }; + if (sortMethod) { + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b2) { + return sortMethod(list2[a], list2[b2]); + }); + } + return initState; + } + return state_1; +} +var terminator_1; +var hasRequiredTerminator; +function requireTerminator() { + if (hasRequiredTerminator) return terminator_1; + hasRequiredTerminator = 1; + var abort = requireAbort(), async = requireAsync(); + terminator_1 = terminator; + function terminator(callback) { + if (!Object.keys(this.jobs).length) { + return; + } + this.index = this.size; + abort(this); + async(callback)(null, this.results); + } + return terminator_1; +} +var parallel_1; +var hasRequiredParallel; +function requireParallel() { + if (hasRequiredParallel) return parallel_1; + hasRequiredParallel = 1; + var iterate = requireIterate(), initState = requireState(), terminator = requireTerminator(); + parallel_1 = parallel; + function parallel(list2, iterator2, callback) { + var state = initState(list2); + while (state.index < (state["keyedList"] || list2).length) { + iterate(list2, iterator2, state, function(error, result) { + if (error) { + callback(error, result); + return; + } + if (Object.keys(state.jobs).length === 0) { + callback(null, state.results); + return; + } + }); + state.index++; + } + return terminator.bind(state, callback); + } + return parallel_1; +} +var serialOrdered = { exports: {} }; +var hasRequiredSerialOrdered; +function requireSerialOrdered() { + if (hasRequiredSerialOrdered) return serialOrdered.exports; + hasRequiredSerialOrdered = 1; + var iterate = requireIterate(), initState = requireState(), terminator = requireTerminator(); + serialOrdered.exports = serialOrdered$1; + serialOrdered.exports.ascending = ascending; + serialOrdered.exports.descending = descending; + function serialOrdered$1(list2, iterator2, sortMethod, callback) { + var state = initState(list2, sortMethod); + iterate(list2, iterator2, state, function iteratorHandler(error, result) { + if (error) { + callback(error, result); + return; + } + state.index++; + if (state.index < (state["keyedList"] || list2).length) { + iterate(list2, iterator2, state, iteratorHandler); + return; + } + callback(null, state.results); + }); + return terminator.bind(state, callback); + } + function ascending(a, b2) { + return a < b2 ? -1 : a > b2 ? 1 : 0; + } + function descending(a, b2) { + return -1 * ascending(a, b2); + } + return serialOrdered.exports; +} +var serial_1; +var hasRequiredSerial; +function requireSerial() { + if (hasRequiredSerial) return serial_1; + hasRequiredSerial = 1; + var serialOrdered2 = requireSerialOrdered(); + serial_1 = serial; + function serial(list2, iterator2, callback) { + return serialOrdered2(list2, iterator2, null, callback); + } + return serial_1; +} +var asynckit; +var hasRequiredAsynckit; +function requireAsynckit() { + if (hasRequiredAsynckit) return asynckit; + hasRequiredAsynckit = 1; + asynckit = { + parallel: requireParallel(), + serial: requireSerial(), + serialOrdered: requireSerialOrdered() + }; + return asynckit; +} +var esObjectAtoms; +var hasRequiredEsObjectAtoms; +function requireEsObjectAtoms() { + if (hasRequiredEsObjectAtoms) return esObjectAtoms; + hasRequiredEsObjectAtoms = 1; + esObjectAtoms = Object; + return esObjectAtoms; +} +var esErrors; +var hasRequiredEsErrors; +function requireEsErrors() { + if (hasRequiredEsErrors) return esErrors; + hasRequiredEsErrors = 1; + esErrors = Error; + return esErrors; +} +var _eval; +var hasRequired_eval; +function require_eval() { + if (hasRequired_eval) return _eval; + hasRequired_eval = 1; + _eval = EvalError; + return _eval; +} +var range; +var hasRequiredRange; +function requireRange() { + if (hasRequiredRange) return range; + hasRequiredRange = 1; + range = RangeError; + return range; +} +var ref; +var hasRequiredRef; +function requireRef() { + if (hasRequiredRef) return ref; + hasRequiredRef = 1; + ref = ReferenceError; + return ref; +} +var syntax; +var hasRequiredSyntax; +function requireSyntax() { + if (hasRequiredSyntax) return syntax; + hasRequiredSyntax = 1; + syntax = SyntaxError; + return syntax; +} +var type; +var hasRequiredType; +function requireType() { + if (hasRequiredType) return type; + hasRequiredType = 1; + type = TypeError; + return type; +} +var uri; +var hasRequiredUri; +function requireUri() { + if (hasRequiredUri) return uri; + hasRequiredUri = 1; + uri = URIError; + return uri; +} +var abs; +var hasRequiredAbs; +function requireAbs() { + if (hasRequiredAbs) return abs; + hasRequiredAbs = 1; + abs = Math.abs; + return abs; +} +var floor; +var hasRequiredFloor; +function requireFloor() { + if (hasRequiredFloor) return floor; + hasRequiredFloor = 1; + floor = Math.floor; + return floor; +} +var max; +var hasRequiredMax; +function requireMax() { + if (hasRequiredMax) return max; + hasRequiredMax = 1; + max = Math.max; + return max; +} +var min; +var hasRequiredMin; +function requireMin() { + if (hasRequiredMin) return min; + hasRequiredMin = 1; + min = Math.min; + return min; +} +var pow; +var hasRequiredPow; +function requirePow() { + if (hasRequiredPow) return pow; + hasRequiredPow = 1; + pow = Math.pow; + return pow; +} +var round; +var hasRequiredRound; +function requireRound() { + if (hasRequiredRound) return round; + hasRequiredRound = 1; + round = Math.round; + return round; +} +var _isNaN; +var hasRequired_isNaN; +function require_isNaN() { + if (hasRequired_isNaN) return _isNaN; + hasRequired_isNaN = 1; + _isNaN = Number.isNaN || function isNaN2(a) { + return a !== a; + }; + return _isNaN; +} +var sign; +var hasRequiredSign; +function requireSign() { + if (hasRequiredSign) return sign; + hasRequiredSign = 1; + var $isNaN = /* @__PURE__ */ require_isNaN(); + sign = function sign2(number2) { + if ($isNaN(number2) || number2 === 0) { + return number2; + } + return number2 < 0 ? -1 : 1; + }; + return sign; +} +var gOPD; +var hasRequiredGOPD; +function requireGOPD() { + if (hasRequiredGOPD) return gOPD; + hasRequiredGOPD = 1; + gOPD = Object.getOwnPropertyDescriptor; + return gOPD; +} +var gopd; +var hasRequiredGopd; +function requireGopd() { + if (hasRequiredGopd) return gopd; + hasRequiredGopd = 1; + var $gOPD = /* @__PURE__ */ requireGOPD(); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e) { + $gOPD = null; + } + } + gopd = $gOPD; + return gopd; +} +var esDefineProperty; +var hasRequiredEsDefineProperty; +function requireEsDefineProperty() { + if (hasRequiredEsDefineProperty) return esDefineProperty; + hasRequiredEsDefineProperty = 1; + var $defineProperty = Object.defineProperty || false; + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e) { + $defineProperty = false; + } + } + esDefineProperty = $defineProperty; + return esDefineProperty; +} +var shams$1; +var hasRequiredShams$1; +function requireShams$1() { + if (hasRequiredShams$1) return shams$1; + hasRequiredShams$1 = 1; + shams$1 = function hasSymbols2() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = /* @__PURE__ */ Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (var _2 in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = ( + /** @type {PropertyDescriptor} */ + Object.getOwnPropertyDescriptor(obj, sym) + ); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + return shams$1; +} +var hasSymbols; +var hasRequiredHasSymbols; +function requireHasSymbols() { + if (hasRequiredHasSymbols) return hasSymbols; + hasRequiredHasSymbols = 1; + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = requireShams$1(); + hasSymbols = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + return hasSymbols; +} +var Reflect_getPrototypeOf; +var hasRequiredReflect_getPrototypeOf; +function requireReflect_getPrototypeOf() { + if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf; + hasRequiredReflect_getPrototypeOf = 1; + Reflect_getPrototypeOf = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; + return Reflect_getPrototypeOf; +} +var Object_getPrototypeOf; +var hasRequiredObject_getPrototypeOf; +function requireObject_getPrototypeOf() { + if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf; + hasRequiredObject_getPrototypeOf = 1; + var $Object = /* @__PURE__ */ requireEsObjectAtoms(); + Object_getPrototypeOf = $Object.getPrototypeOf || null; + return Object_getPrototypeOf; +} +var implementation; +var hasRequiredImplementation; +function requireImplementation() { + if (hasRequiredImplementation) return implementation; + hasRequiredImplementation = 1; + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max2 = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a, b2) { + var arr = []; + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b2.length; j += 1) { + arr[j + a.length] = b2[j]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + implementation = function bind2(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max2(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = "$" + i; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + return implementation; +} +var functionBind; +var hasRequiredFunctionBind; +function requireFunctionBind() { + if (hasRequiredFunctionBind) return functionBind; + hasRequiredFunctionBind = 1; + var implementation2 = requireImplementation(); + functionBind = Function.prototype.bind || implementation2; + return functionBind; +} +var functionCall; +var hasRequiredFunctionCall; +function requireFunctionCall() { + if (hasRequiredFunctionCall) return functionCall; + hasRequiredFunctionCall = 1; + functionCall = Function.prototype.call; + return functionCall; +} +var functionApply; +var hasRequiredFunctionApply; +function requireFunctionApply() { + if (hasRequiredFunctionApply) return functionApply; + hasRequiredFunctionApply = 1; + functionApply = Function.prototype.apply; + return functionApply; +} +var reflectApply; +var hasRequiredReflectApply; +function requireReflectApply() { + if (hasRequiredReflectApply) return reflectApply; + hasRequiredReflectApply = 1; + reflectApply = typeof Reflect !== "undefined" && Reflect && Reflect.apply; + return reflectApply; +} +var actualApply; +var hasRequiredActualApply; +function requireActualApply() { + if (hasRequiredActualApply) return actualApply; + hasRequiredActualApply = 1; + var bind2 = requireFunctionBind(); + var $apply = requireFunctionApply(); + var $call = requireFunctionCall(); + var $reflectApply = requireReflectApply(); + actualApply = $reflectApply || bind2.call($call, $apply); + return actualApply; +} +var callBindApplyHelpers; +var hasRequiredCallBindApplyHelpers; +function requireCallBindApplyHelpers() { + if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers; + hasRequiredCallBindApplyHelpers = 1; + var bind2 = requireFunctionBind(); + var $TypeError = /* @__PURE__ */ requireType(); + var $call = requireFunctionCall(); + var $actualApply = requireActualApply(); + callBindApplyHelpers = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== "function") { + throw new $TypeError("a function is required"); + } + return $actualApply(bind2, $call, args); + }; + return callBindApplyHelpers; +} +var get; +var hasRequiredGet; +function requireGet() { + if (hasRequiredGet) return get; + hasRequiredGet = 1; + var callBind = requireCallBindApplyHelpers(); + var gOPD2 = /* @__PURE__ */ requireGopd(); + var hasProtoAccessor; + try { + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ + [].__proto__ === Array.prototype; + } catch (e) { + if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") { + throw e; + } + } + var desc = !!hasProtoAccessor && gOPD2 && gOPD2( + Object.prototype, + /** @type {keyof typeof Object.prototype} */ + "__proto__" + ); + var $Object = Object; + var $getPrototypeOf = $Object.getPrototypeOf; + get = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? ( + /** @type {import('./get')} */ + function getDunder(value) { + return $getPrototypeOf(value == null ? value : $Object(value)); + } + ) : false; + return get; +} +var getProto; +var hasRequiredGetProto; +function requireGetProto() { + if (hasRequiredGetProto) return getProto; + hasRequiredGetProto = 1; + var reflectGetProto = requireReflect_getPrototypeOf(); + var originalGetProto = requireObject_getPrototypeOf(); + var getDunderProto = /* @__PURE__ */ requireGet(); + getProto = reflectGetProto ? function getProto2(O) { + return reflectGetProto(O); + } : originalGetProto ? function getProto2(O) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new TypeError("getProto: not an object"); + } + return originalGetProto(O); + } : getDunderProto ? function getProto2(O) { + return getDunderProto(O); + } : null; + return getProto; +} +var hasown; +var hasRequiredHasown; +function requireHasown() { + if (hasRequiredHasown) return hasown; + hasRequiredHasown = 1; + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind2 = requireFunctionBind(); + hasown = bind2.call(call, $hasOwn); + return hasown; +} +var getIntrinsic; +var hasRequiredGetIntrinsic; +function requireGetIntrinsic() { + if (hasRequiredGetIntrinsic) return getIntrinsic; + hasRequiredGetIntrinsic = 1; + var undefined$1; + var $Object = /* @__PURE__ */ requireEsObjectAtoms(); + var $Error = /* @__PURE__ */ requireEsErrors(); + var $EvalError = /* @__PURE__ */ require_eval(); + var $RangeError = /* @__PURE__ */ requireRange(); + var $ReferenceError = /* @__PURE__ */ requireRef(); + var $SyntaxError = /* @__PURE__ */ requireSyntax(); + var $TypeError = /* @__PURE__ */ requireType(); + var $URIError = /* @__PURE__ */ requireUri(); + var abs2 = /* @__PURE__ */ requireAbs(); + var floor2 = /* @__PURE__ */ requireFloor(); + var max2 = /* @__PURE__ */ requireMax(); + var min2 = /* @__PURE__ */ requireMin(); + var pow2 = /* @__PURE__ */ requirePow(); + var round2 = /* @__PURE__ */ requireRound(); + var sign2 = /* @__PURE__ */ requireSign(); + var $Function = Function; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e) { + } + }; + var $gOPD = /* @__PURE__ */ requireGopd(); + var $defineProperty = /* @__PURE__ */ requireEsDefineProperty(); + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? (function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + })() : throwTypeError; + var hasSymbols2 = requireHasSymbols()(); + var getProto2 = requireGetProto(); + var $ObjectGPO = requireObject_getPrototypeOf(); + var $ReflectGPO = requireReflect_getPrototypeOf(); + var $apply = requireFunctionApply(); + var $call = requireFunctionCall(); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto2 ? undefined$1 : getProto2(Uint8Array); + var INTRINSICS = { + __proto__: null, + "%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2([][Symbol.iterator]()) : undefined$1, + "%AsyncFromSyncIteratorPrototype%": undefined$1, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": $Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": $EvalError, + "%Float16Array%": typeof Float16Array === "undefined" ? undefined$1 : Float16Array, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(getProto2([][Symbol.iterator]())) : undefined$1, + "%JSON%": typeof JSON === "object" ? JSON : undefined$1, + "%Map%": typeof Map === "undefined" ? undefined$1 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": $Object, + "%Object.getOwnPropertyDescriptor%": $gOPD, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy, + "%RangeError%": $RangeError, + "%ReferenceError%": $ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined$1 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(""[Symbol.iterator]()) : undefined$1, + "%Symbol%": hasSymbols2 ? Symbol : undefined$1, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array, + "%URIError%": $URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet, + "%Function.prototype.call%": $call, + "%Function.prototype.apply%": $apply, + "%Object.defineProperty%": $defineProperty, + "%Object.getPrototypeOf%": $ObjectGPO, + "%Math.abs%": abs2, + "%Math.floor%": floor2, + "%Math.max%": max2, + "%Math.min%": min2, + "%Math.pow%": pow2, + "%Math.round%": round2, + "%Math.sign%": sign2, + "%Reflect.getPrototypeOf%": $ReflectGPO + }; + if (getProto2) { + try { + null.error; + } catch (e) { + var errorProto = getProto2(getProto2(e)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var doEval = function doEval2(name2) { + var value; + if (name2 === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name2 === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name2 === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name2 === "%AsyncGenerator%") { + var fn = doEval2("%AsyncGeneratorFunction%"); + if (fn) { + value = fn.prototype; + } + } else if (name2 === "%AsyncIteratorPrototype%") { + var gen = doEval2("%AsyncGenerator%"); + if (gen && getProto2) { + value = getProto2(gen.prototype); + } + } + INTRINSICS[name2] = value; + return value; + }; + var LEGACY_ALIASES = { + __proto__: null, + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind2 = requireFunctionBind(); + var hasOwn = /* @__PURE__ */ requireHasown(); + var $concat = bind2.call($call, Array.prototype.concat); + var $spliceApply = bind2.call($apply, Array.prototype.splice); + var $replace = bind2.call($call, String.prototype.replace); + var $strSlice = bind2.call($call, String.prototype.slice); + var $exec = bind2.call($call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string2) { + var first = $strSlice(string2, 0, 1); + var last = $strSlice(string2, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string2, rePropName, function(match, number2, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number2 || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) { + var intrinsicName = name2; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name2 + " does not exist!"); + }; + getIntrinsic = function GetIntrinsic(name2, allowMissing) { + if (typeof name2 !== "string" || name2.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name2) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name2); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available."); + } + return void undefined$1; + } + if ($gOPD && i + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + return getIntrinsic; +} +var shams; +var hasRequiredShams; +function requireShams() { + if (hasRequiredShams) return shams; + hasRequiredShams = 1; + var hasSymbols2 = requireShams$1(); + shams = function hasToStringTagShams() { + return hasSymbols2() && !!Symbol.toStringTag; + }; + return shams; +} +var esSetTostringtag; +var hasRequiredEsSetTostringtag; +function requireEsSetTostringtag() { + if (hasRequiredEsSetTostringtag) return esSetTostringtag; + hasRequiredEsSetTostringtag = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasToStringTag = requireShams()(); + var hasOwn = /* @__PURE__ */ requireHasown(); + var $TypeError = /* @__PURE__ */ requireType(); + var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null; + esSetTostringtag = function setToStringTag(object, value) { + var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; + var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; + if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") { + throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans"); + } + if (toStringTag2 && (overrideIfSet || !hasOwn(object, toStringTag2))) { + if ($defineProperty) { + $defineProperty(object, toStringTag2, { + configurable: !nonConfigurable, + enumerable: false, + value, + writable: false + }); + } else { + object[toStringTag2] = value; + } + } + }; + return esSetTostringtag; +} +var populate; +var hasRequiredPopulate; +function requirePopulate() { + if (hasRequiredPopulate) return populate; + hasRequiredPopulate = 1; + populate = function(dst, src2) { + Object.keys(src2).forEach(function(prop) { + dst[prop] = dst[prop] || src2[prop]; + }); + return dst; + }; + return populate; +} +var form_data; +var hasRequiredForm_data; +function requireForm_data() { + if (hasRequiredForm_data) return form_data; + hasRequiredForm_data = 1; + var CombinedStream = requireCombined_stream(); + var util = require$$0$1; + var path = require$$1; + var http = require$$3; + var https = require$$4; + var parseUrl2 = require$$5.parse; + var fs = require$$6; + var Stream = stream.Stream; + var crypto2 = require$$1$1; + var mime = requireMimeTypes(); + var asynckit2 = requireAsynckit(); + var setToStringTag = /* @__PURE__ */ requireEsSetTostringtag(); + var hasOwn = /* @__PURE__ */ requireHasown(); + var populate2 = requirePopulate(); + function FormData2(options) { + if (!(this instanceof FormData2)) { + return new FormData2(options); + } + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + CombinedStream.call(this); + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } + } + util.inherits(FormData2, CombinedStream); + FormData2.LINE_BREAK = "\r\n"; + FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream"; + FormData2.prototype.append = function(field, value, options) { + options = options || {}; + if (typeof options === "string") { + options = { filename: options }; + } + var append2 = CombinedStream.prototype.append.bind(this); + if (typeof value === "number" || value == null) { + value = String(value); + } + if (Array.isArray(value)) { + this._error(new Error("Arrays are not supported.")); + return; + } + var header = this._multiPartHeader(field, value, options); + var footer2 = this._multiPartFooter(); + append2(header); + append2(value); + append2(footer2); + this._trackLength(header, value, options); + }; + FormData2.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + if (options.knownLength != null) { + valueLength += Number(options.knownLength); + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === "string") { + valueLength = Buffer.byteLength(value); + } + this._valueLength += valueLength; + this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length; + if (!value || !value.path && !(value.readable && hasOwn(value, "httpVersion")) && !(value instanceof Stream)) { + return; + } + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } + }; + FormData2.prototype._lengthRetriever = function(value, callback) { + if (hasOwn(value, "fd")) { + if (value.end != void 0 && value.end != Infinity && value.start != void 0) { + callback(null, value.end + 1 - (value.start ? value.start : 0)); + } else { + fs.stat(value.path, function(err, stat) { + if (err) { + callback(err); + return; + } + var fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + } else if (hasOwn(value, "httpVersion")) { + callback(null, Number(value.headers["content-length"])); + } else if (hasOwn(value, "httpModule")) { + value.on("response", function(response) { + value.pause(); + callback(null, Number(response.headers["content-length"])); + }); + value.resume(); + } else { + callback("Unknown stream"); + } + }; + FormData2.prototype._multiPartHeader = function(field, value, options) { + if (typeof options.header === "string") { + return options.header; + } + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + var contents = ""; + var headers = { + // add custom disposition as third element or keep it two elements if not + "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + "Content-Type": [].concat(contentType || []) + }; + if (typeof options.header === "object") { + populate2(headers, options.header); + } + var header; + for (var prop in headers) { + if (hasOwn(headers, prop)) { + header = headers[prop]; + if (header == null) { + continue; + } + if (!Array.isArray(header)) { + header = [header]; + } + if (header.length) { + contents += prop + ": " + header.join("; ") + FormData2.LINE_BREAK; + } + } + } + return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK; + }; + FormData2.prototype._getContentDisposition = function(value, options) { + var filename; + if (typeof options.filepath === "string") { + filename = path.normalize(options.filepath).replace(/\\/g, "/"); + } else if (options.filename || value && (value.name || value.path)) { + filename = path.basename(options.filename || value && (value.name || value.path)); + } else if (value && value.readable && hasOwn(value, "httpVersion")) { + filename = path.basename(value.client._httpMessage.path || ""); + } + if (filename) { + return 'filename="' + filename + '"'; + } + }; + FormData2.prototype._getContentType = function(value, options) { + var contentType = options.contentType; + if (!contentType && value && value.name) { + contentType = mime.lookup(value.name); + } + if (!contentType && value && value.path) { + contentType = mime.lookup(value.path); + } + if (!contentType && value && value.readable && hasOwn(value, "httpVersion")) { + contentType = value.headers["content-type"]; + } + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + if (!contentType && value && typeof value === "object") { + contentType = FormData2.DEFAULT_CONTENT_TYPE; + } + return contentType; + }; + FormData2.prototype._multiPartFooter = function() { + return (function(next) { + var footer2 = FormData2.LINE_BREAK; + var lastPart = this._streams.length === 0; + if (lastPart) { + footer2 += this._lastBoundary(); + } + next(footer2); + }).bind(this); + }; + FormData2.prototype._lastBoundary = function() { + return "--" + this.getBoundary() + "--" + FormData2.LINE_BREAK; + }; + FormData2.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + "content-type": "multipart/form-data; boundary=" + this.getBoundary() + }; + for (header in userHeaders) { + if (hasOwn(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + return formHeaders; + }; + FormData2.prototype.setBoundary = function(boundary) { + if (typeof boundary !== "string") { + throw new TypeError("FormData boundary must be a string"); + } + this._boundary = boundary; + }; + FormData2.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + return this._boundary; + }; + FormData2.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc(0); + var boundary = this.getBoundary(); + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== "function") { + if (Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); + } + if (typeof this._streams[i] !== "string" || this._streams[i].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData2.LINE_BREAK)]); + } + } + } + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); + }; + FormData2.prototype._generateBoundary = function() { + this._boundary = "--------------------------" + crypto2.randomBytes(12).toString("hex"); + }; + FormData2.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + if (!this.hasKnownLength()) { + this._error(new Error("Cannot calculate proper length in synchronous way.")); + } + return knownLength; + }; + FormData2.prototype.hasKnownLength = function() { + var hasKnownLength = true; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + return hasKnownLength; + }; + FormData2.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + asynckit2.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + values.forEach(function(length) { + knownLength += length; + }); + cb(null, knownLength); + }); + }; + FormData2.prototype.submit = function(params, cb) { + var request; + var options; + var defaults2 = { method: "post" }; + if (typeof params === "string") { + params = parseUrl2(params); + options = populate2({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults2); + } else { + options = populate2(params, defaults2); + if (!options.port) { + options.port = options.protocol === "https:" ? 443 : 80; + } + } + options.headers = this.getHeaders(params.headers); + if (options.protocol === "https:") { + request = https.request(options); + } else { + request = http.request(options); + } + this.getLength((function(err, length) { + if (err && err !== "Unknown stream") { + this._error(err); + return; + } + if (length) { + request.setHeader("Content-Length", length); + } + this.pipe(request); + if (cb) { + var onResponse; + var callback = function(error, responce) { + request.removeListener("error", callback); + request.removeListener("response", onResponse); + return cb.call(this, error, responce); + }; + onResponse = callback.bind(this, null); + request.on("error", callback); + request.on("response", onResponse); + } + }).bind(this)); + return request; + }; + FormData2.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit("error", err); + } + }; + FormData2.prototype.toString = function() { + return "[object FormData]"; + }; + setToStringTag(FormData2.prototype, "FormData"); + form_data = FormData2; + return form_data; +} +var form_dataExports = requireForm_data(); +const FormData$1 = /* @__PURE__ */ getDefaultExportFromCjs(form_dataExports); +function isVisitable(thing) { + return utils$2.isPlainObject(thing) || utils$2.isArray(thing); +} +function removeBrackets(key) { + return utils$2.endsWith(key, "[]") ? key.slice(0, -2) : key; +} +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + token = removeBrackets(token); + return !dots && i ? "[" + token + "]" : token; + }).join(dots ? "." : ""); +} +function isFlatArray(arr) { + return utils$2.isArray(arr) && !arr.some(isVisitable); +} +const predicates = utils$2.toFlatObject(utils$2, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); +function toFormData$1(obj, formData, options) { + if (!utils$2.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new (FormData$1 || FormData)(); + options = utils$2.toFlatObject( + options, + { + metaTokens: true, + dots: false, + indexes: false + }, + false, + function defined(option, source) { + return !utils$2.isUndefined(source[option]); + } + ); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils$2.isSpecCompliantForm(formData); + if (!utils$2.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) return ""; + if (utils$2.isDate(value)) { + return value.toISOString(); + } + if (utils$2.isBoolean(value)) { + return value.toString(); + } + if (!useBlob && utils$2.isBlob(value)) { + throw new AxiosError$1("Blob is not supported. Use a Buffer instead."); + } + if (utils$2.isArrayBuffer(value) || utils$2.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (utils$2.isReactNative(formData) && utils$2.isReactNativeBlob(value)) { + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + if (value && !path && typeof value === "object") { + if (utils$2.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils$2.isArray(value) && isFlatArray(value) || (utils$2.isFileList(value) || utils$2.endsWith(key, "[]")) && (arr = utils$2.toArray(value))) { + key = removeBrackets(key); + arr.forEach(function each(el, index2) { + !(utils$2.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", + convertValue(el) + ); + }); + return false; + } + } + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils$2.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils$2.forEach(value, function each(el, key) { + const result = !(utils$2.isUndefined(el) || el === null) && visitor.call(formData, el, utils$2.isString(key) ? key.trim() : key, path, exposedHelpers); + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils$2.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; +} +function encode$1(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} +function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData$1(params, this, options); +} +const prototype = AxiosURLSearchParams.prototype; +prototype.append = function append(name2, value) { + this._pairs.push([name2, value]); +}; +prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); +}; +function encode(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+"); +} +function buildURL(url, params, options) { + if (!params) { + return url; + } + const _encode = options && options.encode || encode; + const _options = utils$2.isFunction(options) ? { + serialize: options + } : options; + const serializeFn = _options && _options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, _options); + } else { + serializedParams = utils$2.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url; +} +class InterceptorManager { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * @param {Object} options The options for the interceptor, synchronous and runWhen + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {void} + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils$2.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} +const transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false, + legacyInterceptorReqResOrdering: true +}; +const URLSearchParams$1 = require$$5.URLSearchParams; +const ALPHA = "abcdefghijklmnopqrstuvwxyz"; +const DIGIT = "0123456789"; +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ""; + const { length } = alphabet; + const randomValues = new Uint32Array(size); + require$$1$1.randomFillSync(randomValues); + for (let i = 0; i < size; i++) { + str += alphabet[randomValues[i] % length]; + } + return str; +}; +const platform$1 = { + isNode: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: typeof Blob !== "undefined" && Blob || null + }, + ALPHABET, + generateString, + protocols: ["http", "https", "file", "data"] +}; +const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; +const _navigator = typeof navigator === "object" && navigator || void 0; +const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0); +const hasStandardBrowserWebWorkerEnv = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; +})(); +const origin = hasBrowserEnv && window.location.href || "http://localhost"; +const utils$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + hasBrowserEnv, + hasStandardBrowserEnv, + hasStandardBrowserWebWorkerEnv, + navigator: _navigator, + origin +}, Symbol.toStringTag, { value: "Module" })); +const platform = { + ...utils$1, + ...platform$1 +}; +function toURLEncodedForm(data, options) { + return toFormData$1(data, new platform.classes.URLSearchParams(), { + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$2.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + }, + ...options + }); +} +function parsePropPath(name2) { + return utils$2.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); +} +function arrayToObject(arr) { + const obj = {}; + const keys2 = Object.keys(arr); + let i; + const len = keys2.length; + let key; + for (i = 0; i < len; i++) { + key = keys2[i]; + obj[key] = arr[key]; + } + return obj; +} +function formDataToJSON(formData) { + function buildPath(path, value, target, index2) { + let name2 = path[index2++]; + if (name2 === "__proto__") return true; + const isNumericKey = Number.isFinite(+name2); + const isLast = index2 >= path.length; + name2 = !name2 && utils$2.isArray(target) ? target.length : name2; + if (isLast) { + if (utils$2.hasOwnProp(target, name2)) { + target[name2] = [target[name2], value]; + } else { + target[name2] = value; + } + return !isNumericKey; + } + if (!target[name2] || !utils$2.isObject(target[name2])) { + target[name2] = []; + } + const result = buildPath(path, value, target[name2], index2); + if (result && utils$2.isArray(target[name2])) { + target[name2] = arrayToObject(target[name2]); + } + return !isNumericKey; + } + if (utils$2.isFormData(formData) && utils$2.isFunction(formData.entries)) { + const obj = {}; + utils$2.forEachEntry(formData, (name2, value) => { + buildPath(parsePropPath(name2), value, obj, 0); + }); + return obj; + } + return null; +} +function stringifySafely(rawValue, parser, encoder) { + if (utils$2.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$2.trim(rawValue); + } catch (e) { + if (e.name !== "SyntaxError") { + throw e; + } + } + } + return (encoder || JSON.stringify)(rawValue); +} +const defaults = { + transitional: transitionalDefaults, + adapter: ["xhr", "http", "fetch"], + transformRequest: [ + function transformRequest(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils$2.isObject(data); + if (isObjectPayload && utils$2.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData2 = utils$2.isFormData(data); + if (isFormData2) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + if (utils$2.isArrayBuffer(data) || utils$2.isBuffer(data) || utils$2.isStream(data) || utils$2.isFile(data) || utils$2.isBlob(data) || utils$2.isReadableStream(data)) { + return data; + } + if (utils$2.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$2.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList2; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + if ((isFileList2 = utils$2.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData$1( + isFileList2 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely(data); + } + return data; + } + ], + transformResponse: [ + function transformResponse(data) { + const transitional2 = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (utils$2.isResponse(data) || utils$2.isReadableStream(data)) { + return data; + } + if (data && utils$2.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data, this.parseReviver); + } catch (e) { + if (strictJSONParsing) { + if (e.name === "SyntaxError") { + throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + return data; + } + ], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + validateStatus: function validateStatus(status2) { + return status2 >= 200 && status2 < 300; + }, + headers: { + common: { + Accept: "application/json, text/plain, */*", + "Content-Type": void 0 + } + } +}; +utils$2.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults.headers[method] = {}; +}); +const ignoreDuplicateOf = utils$2.toObjectSet([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "user-agent" +]); +const parseHeaders = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i = line.indexOf(":"); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; +}; +const $internals = /* @__PURE__ */ Symbol("internals"); +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils$2.isArray(value) ? value.map(normalizeValue) : String(value).replace(/[\r\n]+$/, ""); +} +function parseTokens(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; +} +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); +function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { + if (utils$2.isFunction(filter2)) { + return filter2.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils$2.isString(value)) return; + if (utils$2.isString(filter2)) { + return value.indexOf(filter2) !== -1; + } + if (utils$2.isRegExp(filter2)) { + return filter2.test(value); + } +} +function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { + return char.toUpperCase() + str; + }); +} +function buildAccessors(obj, header) { + const accessorName = utils$2.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} +let AxiosHeaders$1 = class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils$2.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue(_value); + } + } + const setHeaders = (headers, _rewrite) => utils$2.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils$2.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils$2.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$2.isObject(header) && utils$2.isIterable(header)) { + let obj = {}, dest, key; + for (const entry of header) { + if (!utils$2.isArray(entry)) { + throw TypeError("Object iterator must return a key-value pair"); + } + obj[key = entry[0]] = (dest = obj[key]) ? utils$2.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; + } + setHeaders(obj, valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader(header); + if (header) { + const key = utils$2.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils$2.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils$2.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); + } + } + } + has(header, matcher) { + header = normalizeHeader(header); + if (header) { + const key = utils$2.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + const key = utils$2.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils$2.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys2 = Object.keys(this); + let i = keys2.length; + let deleted = false; + while (i--) { + const key = keys2[i]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils$2.forEach(this, (value, header) => { + const key = utils$2.findKey(headers, header); + if (key) { + self2[key] = normalizeValue(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils$2.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$2.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + getSetCookie() { + return this.get("set-cookie") || []; + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals] = this[$internals] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype2 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype2, _header); + accessors[lHeader] = true; + } + } + utils$2.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } +}; +AxiosHeaders$1.accessor([ + "Content-Type", + "Content-Length", + "Accept", + "Accept-Encoding", + "User-Agent", + "Authorization" +]); +utils$2.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; +}); +utils$2.freezeMethods(AxiosHeaders$1); +function transformData(fns, response) { + const config = this || defaults; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + utils$2.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; +} +function isCancel$1(value) { + return !!(value && value.__CANCEL__); +} +let CanceledError$1 = class CanceledError extends AxiosError$1 { + /** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ + constructor(message, config, request) { + super(message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config, request); + this.name = "CanceledError"; + this.__CANCEL__ = true; + } +}; +function settle(resolve, reject, response) { + const validateStatus2 = response.config.validateStatus; + if (!response.status || !validateStatus2 || validateStatus2(response.status)) { + resolve(response); + } else { + reject( + new AxiosError$1( + "Request failed with status code " + response.status, + [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + ) + ); + } +} +function isAbsoluteURL(url) { + if (typeof url !== "string") { + return false; + } + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} +function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; +} +function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { + let isRelativeUrl = !isAbsoluteURL(requestedURL); + if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} +var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; +function parseUrl(urlString) { + try { + return new URL(urlString); + } catch { + return null; + } +} +function getProxyForUrl(url) { + var parsedUrl = (typeof url === "string" ? parseUrl(url) : url) || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== "string" || !hostname || typeof proto !== "string") { + return ""; + } + proto = proto.split(":", 1)[0]; + hostname = hostname.replace(/:\d*$/, ""); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ""; + } + var proxy = getEnv(proto + "_proxy") || getEnv("all_proxy"); + if (proxy && proxy.indexOf("://") === -1) { + proxy = proto + "://" + proxy; + } + return proxy; +} +function shouldProxy(hostname, port) { + var NO_PROXY = getEnv("no_proxy").toLowerCase(); + if (!NO_PROXY) { + return true; + } + if (NO_PROXY === "*") { + return false; + } + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; + } + if (!/^[.*]/.test(parsedProxyHostname)) { + return hostname !== parsedProxyHostname; + } + if (parsedProxyHostname.charAt(0) === "*") { + parsedProxyHostname = parsedProxyHostname.slice(1); + } + return !hostname.endsWith(parsedProxyHostname); + }); +} +function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ""; +} +var followRedirects$1 = { exports: {} }; +var src = { exports: {} }; +var browser = { exports: {} }; +var ms; +var hasRequiredMs; +function requireMs() { + if (hasRequiredMs) return ms; + hasRequiredMs = 1; + var s2 = 1e3; + var m = s2 * 60; + var h = m * 60; + var d2 = h * 24; + var w2 = d2 * 7; + var y = d2 * 365.25; + ms = function(val, options) { + options = options || {}; + var type2 = typeof val; + if (type2 === "string" && val.length > 0) { + return parse2(val); + } else if (type2 === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse2(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w2; + case "days": + case "day": + case "d": + return n * d2; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s2; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms2) { + var msAbs = Math.abs(ms2); + if (msAbs >= d2) { + return Math.round(ms2 / d2) + "d"; + } + if (msAbs >= h) { + return Math.round(ms2 / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms2 / m) + "m"; + } + if (msAbs >= s2) { + return Math.round(ms2 / s2) + "s"; + } + return ms2 + "ms"; + } + function fmtLong(ms2) { + var msAbs = Math.abs(ms2); + if (msAbs >= d2) { + return plural(ms2, msAbs, d2, "day"); + } + if (msAbs >= h) { + return plural(ms2, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms2, msAbs, m, "minute"); + } + if (msAbs >= s2) { + return plural(ms2, msAbs, s2, "second"); + } + return ms2 + " ms"; + } + function plural(ms2, msAbs, n, name2) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms2 / n) + " " + name2 + (isPlural ? "s" : ""); + } + return ms; +} +var common; +var hasRequiredCommon; +function requireCommon() { + if (hasRequiredCommon) return common; + hasRequiredCommon = 1; + function setup(env2) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable2; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs(); + createDebug.destroy = destroy; + Object.keys(env2).forEach((key) => { + createDebug[key] = env2[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(/* @__PURE__ */ new Date()); + const ms2 = curr - (prevTime || curr); + self2.diff = ms2; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index2++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index2]; + match = formatter.call(self2, val); + args.splice(index2, 1); + index2--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend2; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); + } + return debug; + } + function extend2(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + function matchesTemplate(search2, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search2.length) { + if (templateIndex < template.length && (template[templateIndex] === search2[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable2() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name2) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name2, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name2, ns)) { + return true; + } + } + return false; + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + common = setup; + return common; +} +var hasRequiredBrowser; +function requireBrowser() { + if (hasRequiredBrowser) return browser.exports; + hasRequiredBrowser = 1; + (function(module, exports$1) { + exports$1.formatArgs = formatArgs; + exports$1.save = save; + exports$1.load = load; + exports$1.useColors = useColors; + exports$1.storage = localstorage(); + exports$1.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports$1.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" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index2++; + if (match === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c); + } + exports$1.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports$1.storage.setItem("debug", namespaces); + } else { + exports$1.storage.removeItem("debug"); + } + } catch (error) { + } + } + function load() { + let r; + try { + r = exports$1.storage.getItem("debug") || exports$1.storage.getItem("DEBUG"); + } catch (error) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + module.exports = requireCommon()(exports$1); + const { formatters } = module.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; + })(browser, browser.exports); + return browser.exports; +} +var node$1 = { exports: {} }; +var hasFlag; +var hasRequiredHasFlag; +function requireHasFlag() { + if (hasRequiredHasFlag) return hasFlag; + hasRequiredHasFlag = 1; + hasFlag = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position2 = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position2 !== -1 && (terminatorPosition === -1 || position2 < terminatorPosition); + }; + return hasFlag; +} +var supportsColor_1; +var hasRequiredSupportsColor; +function requireSupportsColor() { + if (hasRequiredSupportsColor) return supportsColor_1; + hasRequiredSupportsColor = 1; + const os = require$$0$2; + const tty = require$$1$2; + const hasFlag2 = requireHasFlag(); + const { env: env2 } = process; + let flagForceColor; + if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) { + flagForceColor = 0; + } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) { + flagForceColor = 1; + } + function envForceColor() { + if ("FORCE_COLOR" in env2) { + if (env2.FORCE_COLOR === "true") { + return 1; + } + if (env2.FORCE_COLOR === "false") { + return 0; + } + return env2.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env2.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== void 0) { + flagForceColor = noFlagForceColor; + } + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + if (forceColor === 0) { + return 0; + } + if (sniffFlags) { + if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) { + return 3; + } + if (hasFlag2("color=256")) { + return 2; + } + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min2 = forceColor || 0; + if (env2.TERM === "dumb") { + return min2; + } + if (process.platform === "win32") { + const osRelease = os.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env2) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign2) => sign2 in env2) || env2.CI_NAME === "codeship") { + return 1; + } + return min2; + } + if ("TEAMCITY_VERSION" in env2) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0; + } + if (env2.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env2) { + const version = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env2.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env2.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) { + return 1; + } + if ("COLORTERM" in env2) { + return 1; + } + return min2; + } + function getSupportLevel(stream2, options = {}) { + const level = supportsColor(stream2, { + streamIsTTY: stream2 && stream2.isTTY, + ...options + }); + return translateLevel(level); + } + supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel({ isTTY: tty.isatty(1) }), + stderr: getSupportLevel({ isTTY: tty.isatty(2) }) + }; + return supportsColor_1; +} +var hasRequiredNode; +function requireNode() { + if (hasRequiredNode) return node$1.exports; + hasRequiredNode = 1; + (function(module, exports$1) { + const tty = require$$1$2; + const util = require$$0$1; + exports$1.init = init2; + exports$1.log = log; + exports$1.formatArgs = formatArgs; + exports$1.save = save; + exports$1.load = load; + exports$1.useColors = useColors; + exports$1.destroy = util.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports$1.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = requireSupportsColor(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports$1.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + } + exports$1.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k2) => { + return k2.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports$1.inspectOpts ? Boolean(exports$1.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name2, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name2} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name2 + " " + args[0]; + } + } + function getDate() { + if (exports$1.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports$1.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load() { + return process.env.DEBUG; + } + function init2(debug) { + debug.inspectOpts = {}; + const keys2 = Object.keys(exports$1.inspectOpts); + for (let i = 0; i < keys2.length; i++) { + debug.inspectOpts[keys2[i]] = exports$1.inspectOpts[keys2[i]]; + } + } + module.exports = requireCommon()(exports$1); + const { formatters } = module.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + })(node$1, node$1.exports); + return node$1.exports; +} +var hasRequiredSrc; +function requireSrc() { + if (hasRequiredSrc) return src.exports; + hasRequiredSrc = 1; + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + src.exports = requireBrowser(); + } else { + src.exports = requireNode(); + } + return src.exports; +} +var debug_1; +var hasRequiredDebug; +function requireDebug() { + if (hasRequiredDebug) return debug_1; + hasRequiredDebug = 1; + var debug; + debug_1 = function() { + if (!debug) { + try { + debug = requireSrc()("follow-redirects"); + } catch (error) { + } + if (typeof debug !== "function") { + debug = function() { + }; + } + } + debug.apply(null, arguments); + }; + return debug_1; +} +var hasRequiredFollowRedirects; +function requireFollowRedirects() { + if (hasRequiredFollowRedirects) return followRedirects$1.exports; + hasRequiredFollowRedirects = 1; + var url = require$$5; + var URL2 = url.URL; + var http = require$$3; + var https = require$$4; + var Writable = stream.Writable; + var assert = require$$4$1; + var debug = requireDebug(); + (function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction2(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); + } + })(); + var useNativeURL = false; + try { + assert(new URL2("")); + } catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; + } + var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash" + ]; + var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; + var eventHandlers = /* @__PURE__ */ Object.create(null); + events.forEach(function(event) { + eventHandlers[event] = function(arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; + }); + var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError + ); + var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" + ); + var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError + ); + var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" + ); + var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" + ); + var destroy = Writable.prototype.destroy || noop2; + function RedirectableRequest(options, responseCallback) { + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + if (responseCallback) { + this.on("response", responseCallback); + } + var self2 = this; + this._onNativeResponse = function(response) { + try { + self2._processResponse(response); + } catch (cause) { + self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause })); + } + }; + this._performRequest(); + } + RedirectableRequest.prototype = Object.create(Writable.prototype); + RedirectableRequest.prototype.abort = function() { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); + }; + RedirectableRequest.prototype.destroy = function(error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; + }; + RedirectableRequest.prototype.write = function(data, encoding, callback) { + if (this._ending) { + throw new WriteAfterEndError(); + } + if (!isString2(data) && !isBuffer2(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data, encoding }); + this._currentRequest.write(data, encoding, callback); + } else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } + }; + RedirectableRequest.prototype.end = function(data, encoding, callback) { + if (isFunction2(data)) { + callback = data; + data = encoding = null; + } else if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } else { + var self2 = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function() { + self2._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } + }; + RedirectableRequest.prototype.setHeader = function(name2, value) { + this._options.headers[name2] = value; + this._currentRequest.setHeader(name2, value); + }; + RedirectableRequest.prototype.removeHeader = function(name2) { + delete this._options.headers[name2]; + this._currentRequest.removeHeader(name2); + }; + RedirectableRequest.prototype.setTimeout = function(msecs, callback) { + var self2 = this; + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + function startTimer(socket) { + if (self2._timeout) { + clearTimeout(self2._timeout); + } + self2._timeout = setTimeout(function() { + self2.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + function clearTimer() { + if (self2._timeout) { + clearTimeout(self2._timeout); + self2._timeout = null; + } + self2.removeListener("abort", clearTimer); + self2.removeListener("error", clearTimer); + self2.removeListener("response", clearTimer); + self2.removeListener("close", clearTimer); + if (callback) { + self2.removeListener("timeout", callback); + } + if (!self2.socket) { + self2._currentRequest.removeListener("socket", startTimer); + } + } + if (callback) { + this.on("timeout", callback); + } + if (this.socket) { + startTimer(this.socket); + } else { + this._currentRequest.once("socket", startTimer); + } + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); + return this; + }; + [ + "flushHeaders", + "getHeader", + "setNoDelay", + "setSocketKeepAlive" + ].forEach(function(method) { + RedirectableRequest.prototype[method] = function(a, b2) { + return this._currentRequest[method](a, b2); + }; + }); + ["aborted", "connection", "socket"].forEach(function(property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function() { + return this._currentRequest[property]; + } + }); + }); + RedirectableRequest.prototype._sanitizeOptions = function(options) { + if (!options.headers) { + options.headers = {}; + } + if (options.host) { + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } + }; + RedirectableRequest.prototype._performRequest = function() { + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } + this._currentUrl = /^\//.test(this._options.path) ? url.format(this._options) : ( + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path + ); + if (this._isRedirect) { + var i = 0; + var self2 = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + if (request === self2._currentRequest) { + if (error) { + self2.emit("error", error); + } else if (i < buffers.length) { + var buffer = buffers[i++]; + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } else if (self2._ended) { + request.end(); + } + } + })(); + } + }; + RedirectableRequest.prototype._processResponse = function(response) { + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode + }); + } + var location = response.headers.location; + if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + this._requestBodyBuffers = []; + return; + } + destroyRequest(this._currentRequest); + response.destroy(); + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host") + }, this._options.headers); + } + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + var currentUrlParts = parseUrl2(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost })); + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); + if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + } + if (isFunction2(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode + }; + var requestDetails = { + url: currentUrl, + method, + headers: requestHeaders + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } + this._performRequest(); + }; + function wrap2(protocols) { + var exports$1 = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024 + }; + var nativeProtocols = {}; + Object.keys(protocols).forEach(function(scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports$1[scheme] = Object.create(nativeProtocol); + function request(input, options, callback) { + if (isURL(input)) { + input = spreadUrlObject(input); + } else if (isString2(input)) { + input = spreadUrlObject(parseUrl2(input)); + } else { + callback = options; + options = validateUrl(input); + input = { protocol }; + } + if (isFunction2(options)) { + callback = options; + options = null; + } + options = Object.assign({ + maxRedirects: exports$1.maxRedirects, + maxBodyLength: exports$1.maxBodyLength + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString2(options.host) && !isString2(options.hostname)) { + options.hostname = "::1"; + } + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + function get2(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get2, configurable: true, enumerable: true, writable: true } + }); + }); + return exports$1; + } + function noop2() { + } + function parseUrl2(input) { + var parsed; + if (useNativeURL) { + parsed = new URL2(input); + } else { + parsed = validateUrl(url.parse(input)); + if (!isString2(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + } + return parsed; + } + function resolveUrl(relative, base) { + return useNativeURL ? new URL2(relative, base) : parseUrl2(url.resolve(base, relative)); + } + function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; + } + function spreadUrlObject(urlObject, target) { + var spread2 = target || {}; + for (var key of preservedUrlFields) { + spread2[key] = urlObject[key]; + } + if (spread2.hostname.startsWith("[")) { + spread2.hostname = spread2.hostname.slice(1, -1); + } + if (spread2.port !== "") { + spread2.port = Number(spread2.port); + } + spread2.path = spread2.search ? spread2.pathname + spread2.search : spread2.pathname; + return spread2; + } + function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim(); + } + function createErrorType(code2, message, baseClass) { + function CustomError(properties) { + if (isFunction2(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code2; + this.message = this.cause ? message + ": " + this.cause.message : message; + } + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false + }, + name: { + value: "Error [" + code2 + "]", + enumerable: false + } + }); + return CustomError; + } + function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop2); + request.destroy(error); + } + function isSubdomain(subdomain, domain) { + assert(isString2(subdomain) && isString2(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); + } + function isString2(value) { + return typeof value === "string" || value instanceof String; + } + function isFunction2(value) { + return typeof value === "function"; + } + function isBuffer2(value) { + return typeof value === "object" && "length" in value; + } + function isURL(value) { + return URL2 && value instanceof URL2; + } + followRedirects$1.exports = wrap2({ http, https }); + followRedirects$1.exports.wrap = wrap2; + return followRedirects$1.exports; +} +var followRedirectsExports = requireFollowRedirects(); +const followRedirects = /* @__PURE__ */ getDefaultExportFromCjs(followRedirectsExports); +const VERSION$1 = "1.14.0"; +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ""; +} +const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; +function fromDataURI(uri2, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol(uri2); + if (asBlob === void 0 && _Blob) { + asBlob = true; + } + if (protocol === "data") { + uri2 = protocol.length ? uri2.slice(protocol.length + 1) : uri2; + const match = DATA_URL_PATTERN.exec(uri2); + if (!match) { + throw new AxiosError$1("Invalid URL", AxiosError$1.ERR_INVALID_URL); + } + const mime = match[1]; + const isBase64 = match[2]; + const body2 = match[3]; + const buffer = Buffer.from(decodeURIComponent(body2), isBase64 ? "base64" : "utf8"); + if (asBlob) { + if (!_Blob) { + throw new AxiosError$1("Blob is not supported", AxiosError$1.ERR_NOT_SUPPORT); + } + return new _Blob([buffer], { type: mime }); + } + return buffer; + } + throw new AxiosError$1("Unsupported protocol " + protocol, AxiosError$1.ERR_NOT_SUPPORT); +} +const kInternals = /* @__PURE__ */ Symbol("internals"); +class AxiosTransformStream extends stream.Transform { + constructor(options) { + options = utils$2.toFlatObject( + options, + { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, + null, + (prop, source) => { + return !utils$2.isUndefined(source[prop]); + } + ); + super({ + readableHighWaterMark: options.chunkSize + }); + const internals = this[kInternals] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + this.on("newListener", (event) => { + if (event === "progress") { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + _read(size) { + const internals = this[kInternals]; + if (internals.onReadCallback) { + internals.onReadCallback(); + } + return super._read(size); + } + _transform(chunk2, encoding, callback) { + const internals = this[kInternals]; + const maxRate = internals.maxRate; + const readableHighWaterMark = this.readableHighWaterMark; + const timeWindow = internals.timeWindow; + const divider = 1e3 / timeWindow; + const bytesThreshold = maxRate / divider; + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + internals.isCaptured && this.emit("progress", internals.bytesSeen); + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + }; + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + if (maxRate) { + const now = Date.now(); + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + bytesLeft = bytesThreshold - internals.bytes; + } + if (maxRate) { + if (bytesLeft <= 0) { + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + pushChunk( + _chunk, + chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback + ); + }; + transformChunk(chunk2, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } +} +const { asyncIterator } = Symbol; +const readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; + } +}; +const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + "-_"; +const textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new require$$0$1.TextEncoder(); +const CRLF = "\r\n"; +const CRLF_BYTES = textEncoder.encode(CRLF); +const CRLF_BYTES_COUNT = 2; +class FormDataPart { + constructor(name2, value) { + const { escapeName } = this.constructor; + const isStringValue = utils$2.isString(value); + let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`; + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; + } + this.headers = textEncoder.encode(headers + CRLF); + this.contentLength = isStringValue ? value.byteLength : value.size; + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + this.name = name2; + this.value = value; + } + async *encode() { + yield this.headers; + const { value } = this; + if (utils$2.isTypedArray(value)) { + yield value; + } else { + yield* readBlob(value); + } + yield CRLF_BYTES; + } + static escapeName(name2) { + return String(name2).replace( + /[\r\n"]/g, + (match) => ({ + "\r": "%0D", + "\n": "%0A", + '"': "%22" + })[match] + ); + } +} +const formDataToStream = (form, headersHandler, options) => { + const { + tag = "form-data-boundary", + size = 25, + boundary = tag + "-" + platform.generateString(size, BOUNDARY_ALPHABET) + } = options || {}; + if (!utils$2.isFormData(form)) { + throw TypeError("FormData instance required"); + } + if (boundary.length < 1 || boundary.length > 70) { + throw Error("boundary must be 10-70 characters long"); + } + const boundaryBytes = textEncoder.encode("--" + boundary + CRLF); + const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF); + let contentLength = footerBytes.byteLength; + const parts = Array.from(form.entries()).map(([name2, value]) => { + const part = new FormDataPart(name2, value); + contentLength += part.size; + return part; + }); + contentLength += boundaryBytes.byteLength * parts.length; + contentLength = utils$2.toFiniteNumber(contentLength); + const computedHeaders = { + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (Number.isFinite(contentLength)) { + computedHeaders["Content-Length"] = contentLength; + } + headersHandler && headersHandler(computedHeaders); + return Readable.from( + (async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + yield footerBytes; + })() + ); +}; +class ZlibHeaderTransformStream extends stream.Transform { + __transform(chunk2, encoding, callback) { + this.push(chunk2); + callback(); + } + _transform(chunk2, encoding, callback) { + if (chunk2.length !== 0) { + this._transform = this.__transform; + if (chunk2[0] !== 120) { + const header = Buffer.alloc(2); + header[0] = 120; + header[1] = 156; + this.push(header, encoding); + } + } + this.__transform(chunk2, encoding, callback); + } +} +const callbackify = (fn, reducer2) => { + return utils$2.isAsyncFn(fn) ? function(...args) { + const cb = args.pop(); + fn.apply(this, args).then((value) => { + try { + reducer2 ? cb(null, ...reducer2(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn; +}; +function speedometer(samplesCount, min2) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min2 = min2 !== void 0 ? min2 : 1e3; + return function push2(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min2) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; +} +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1e3 / freq; + let lastArgs; + let timer; + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn(...args); + }; + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + const flush = () => lastArgs && invoke(lastArgs); + return [throttled, flush]; +} +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + return throttle((e) => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange ? (total - loaded) / rate : void 0, + event: e, + lengthComputable: total != null, + [isDownloadStream ? "download" : "upload"]: true + }; + listener(data); + }, freq); +}; +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + return [ + (loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), + throttled[1] + ]; +}; +const asyncDecorator = (fn) => (...args) => utils$2.asap(() => fn(...args)); +function estimateDataURLDecodedBytes(url) { + if (!url || typeof url !== "string") return 0; + if (!url.startsWith("data:")) return 0; + const comma = url.indexOf(","); + if (comma < 0) return 0; + const meta = url.slice(5, comma); + const body2 = url.slice(comma + 1); + const isBase64 = /;base64/i.test(meta); + if (isBase64) { + let effectiveLen = body2.length; + const len = body2.length; + for (let i = 0; i < len; i++) { + if (body2.charCodeAt(i) === 37 && i + 2 < len) { + const a = body2.charCodeAt(i + 1); + const b2 = body2.charCodeAt(i + 2); + const isHex = (a >= 48 && a <= 57 || a >= 65 && a <= 70 || a >= 97 && a <= 102) && (b2 >= 48 && b2 <= 57 || b2 >= 65 && b2 <= 70 || b2 >= 97 && b2 <= 102); + if (isHex) { + effectiveLen -= 2; + i += 2; + } + } + } + let pad2 = 0; + let idx = len - 1; + const tailIsPct3D = (j) => j >= 2 && body2.charCodeAt(j - 2) === 37 && // '%' + body2.charCodeAt(j - 1) === 51 && // '3' + (body2.charCodeAt(j) === 68 || body2.charCodeAt(j) === 100); + if (idx >= 0) { + if (body2.charCodeAt(idx) === 61) { + pad2++; + idx--; + } else if (tailIsPct3D(idx)) { + pad2++; + idx -= 3; + } + } + if (pad2 === 1 && idx >= 0) { + if (body2.charCodeAt(idx) === 61) { + pad2++; + } else if (tailIsPct3D(idx)) { + pad2++; + } + } + const groups = Math.floor(effectiveLen / 4); + const bytes = groups * 3 - (pad2 || 0); + return bytes > 0 ? bytes : 0; + } + return Buffer.byteLength(body2, "utf8"); +} +const zlibOptions = { + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH +}; +const brotliOptions = { + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH +}; +const isBrotliSupported = utils$2.isFunction(zlib.createBrotliDecompress); +const { http: httpFollow, https: httpsFollow } = followRedirects; +const isHttps = /https:?/; +const supportedProtocols = platform.protocols.map((protocol) => { + return protocol + ":"; +}); +const flushOnFinish = (stream2, [throttled, flush]) => { + stream2.on("end", flush).on("error", flush); + return throttled; +}; +class Http2Sessions { + constructor() { + this.sessions = /* @__PURE__ */ Object.create(null); + } + getSession(authority, options) { + options = Object.assign( + { + sessionTimeout: 1e3 + }, + options + ); + let authoritySessions = this.sessions[authority]; + if (authoritySessions) { + let len = authoritySessions.length; + for (let i = 0; i < len; i++) { + const [sessionHandle, sessionOptions] = authoritySessions[i]; + if (!sessionHandle.destroyed && !sessionHandle.closed && require$$0$1.isDeepStrictEqual(sessionOptions, options)) { + return sessionHandle; + } + } + } + const session = http2.connect(authority, options); + let removed; + const removeSession = () => { + if (removed) { + return; + } + removed = true; + let entries = authoritySessions, len = entries.length, i = len; + while (i--) { + if (entries[i][0] === session) { + if (len === 1) { + delete this.sessions[authority]; + } else { + entries.splice(i, 1); + } + if (!session.closed) { + session.close(); + } + return; + } + } + }; + const originalRequestFn = session.request; + const { sessionTimeout } = options; + if (sessionTimeout != null) { + let timer; + let streamsCount = 0; + session.request = function() { + const stream2 = originalRequestFn.apply(this, arguments); + streamsCount++; + if (timer) { + clearTimeout(timer); + timer = null; + } + stream2.once("close", () => { + if (!--streamsCount) { + timer = setTimeout(() => { + timer = null; + removeSession(); + }, sessionTimeout); + } + }); + return stream2; + }; + } + session.once("close", removeSession); + let entry = [session, options]; + authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry]; + return session; + } +} +const http2Sessions = new Http2Sessions(); +function dispatchBeforeRedirect(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } +} +function setProxy(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); + } + } + if (proxy) { + if (proxy.username) { + proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); + } + if (proxy.auth) { + const validProxyAuth = Boolean(proxy.auth.username || proxy.auth.password); + if (validProxyAuth) { + proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); + } else if (typeof proxy.auth === "object") { + throw new AxiosError$1("Invalid proxy authorization", AxiosError$1.ERR_BAD_OPTION, { proxy }); + } + const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); + options.headers["Proxy-Authorization"] = "Basic " + base64; + } + options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; + } + } + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + setProxy(redirectOptions, configProxy, redirectOptions.href); + }; +} +const isHttpAdapterSupported = typeof process !== "undefined" && utils$2.kindOf(process) === "process"; +const wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + const _resolve = (value) => { + done(value); + resolve(value); + }; + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); + }); +}; +const resolveFamily = ({ address, family }) => { + if (!utils$2.isString(address)) { + throw TypeError("address must be a string"); + } + return { + address, + family: family || (address.indexOf(".") < 0 ? 6 : 4) + }; +}; +const buildAddressEntry = (address, family) => resolveFamily(utils$2.isObject(address) ? address : { address, family }); +const http2Transport = { + request(options, cb) { + const authority = options.protocol + "//" + options.hostname + ":" + (options.port || (options.protocol === "https:" ? 443 : 80)); + const { http2Options, headers } = options; + const session = http2Sessions.getSession(authority, http2Options); + const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants; + const http2Headers = { + [HTTP2_HEADER_SCHEME]: options.protocol.replace(":", ""), + [HTTP2_HEADER_METHOD]: options.method, + [HTTP2_HEADER_PATH]: options.path + }; + utils$2.forEach(headers, (header, name2) => { + name2.charAt(0) !== ":" && (http2Headers[name2] = header); + }); + const req = session.request(http2Headers); + req.once("response", (responseHeaders) => { + const response = req; + responseHeaders = Object.assign({}, responseHeaders); + const status2 = responseHeaders[HTTP2_HEADER_STATUS]; + delete responseHeaders[HTTP2_HEADER_STATUS]; + response.headers = responseHeaders; + response.statusCode = +status2; + cb(response); + }); + return req; + } +}; +const httpAdapter = isHttpAdapterSupported && function httpAdapter2(config) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let { data, lookup, family, httpVersion = 1, http2Options } = config; + const { responseType, responseEncoding } = config; + const method = config.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + httpVersion = +httpVersion; + if (Number.isNaN(httpVersion)) { + throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); + } + if (httpVersion !== 1 && httpVersion !== 2) { + throw TypeError(`Unsupported protocol version '${httpVersion}'`); + } + const isHttp2 = httpVersion === 2; + if (lookup) { + const _lookup = callbackify(lookup, (value) => utils$2.isArray(value) ? value : [value]); + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + const addresses = utils$2.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + const abortEmitter = new EventEmitter(); + function abort(reason) { + try { + abortEmitter.emit( + "abort", + !reason || reason.type ? new CanceledError$1(null, config, req) : reason + ); + } catch (err) { + console.warn("emit error", err); + } + } + abortEmitter.once("abort", reject); + const onFinished = () => { + if (config.cancelToken) { + config.cancelToken.unsubscribe(abort); + } + if (config.signal) { + config.signal.removeEventListener("abort", abort); + } + abortEmitter.removeAllListeners(); + }; + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener("abort", abort); + } + } + onDone((response, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + return; + } + const { data: data2 } = response; + if (data2 instanceof stream.Readable || data2 instanceof stream.Duplex) { + const offListeners = stream.finished(data2, () => { + offListeners(); + onFinished(); + }); + } else { + onFinished(); + } + }); + const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : void 0); + const protocol = parsed.protocol || supportedProtocols[0]; + if (protocol === "data:") { + if (config.maxContentLength > -1) { + const dataUrl = String(config.url || fullPath || ""); + const estimated = estimateDataURLDecodedBytes(dataUrl); + if (estimated > config.maxContentLength) { + return reject( + new AxiosError$1( + "maxContentLength size of " + config.maxContentLength + " exceeded", + AxiosError$1.ERR_BAD_RESPONSE, + config + ) + ); + } + } + let convertedData; + if (method !== "GET") { + return settle(resolve, reject, { + status: 405, + statusText: "method not allowed", + headers: {}, + config + }); + } + try { + convertedData = fromDataURI(config.url, responseType === "blob", { + Blob: config.env && config.env.Blob + }); + } catch (err) { + throw AxiosError$1.from(err, AxiosError$1.ERR_BAD_REQUEST, config); + } + if (responseType === "text") { + convertedData = convertedData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + convertedData = utils$2.stripBOM(convertedData); + } + } else if (responseType === "stream") { + convertedData = stream.Readable.from(convertedData); + } + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: "OK", + headers: new AxiosHeaders$1(), + config + }); + } + if (supportedProtocols.indexOf(protocol) === -1) { + return reject( + new AxiosError$1("Unsupported protocol " + protocol, AxiosError$1.ERR_BAD_REQUEST, config) + ); + } + const headers = AxiosHeaders$1.from(config.headers).normalize(); + headers.set("User-Agent", "axios/" + VERSION$1, false); + const { onUploadProgress, onDownloadProgress } = config; + const maxRate = config.maxRate; + let maxUploadRate = void 0; + let maxDownloadRate = void 0; + if (utils$2.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + data = formDataToStream( + data, + (formHeaders) => { + headers.set(formHeaders); + }, + { + tag: `axios-${VERSION$1}-boundary`, + boundary: userBoundary && userBoundary[1] || void 0 + } + ); + } else if (utils$2.isFormData(data) && utils$2.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + if (!headers.hasContentLength()) { + try { + const knownLength = await require$$0$1.promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + } catch (e) { + } + } + } else if (utils$2.isBlob(data) || utils$2.isFile(data)) { + data.size && headers.setContentType(data.type || "application/octet-stream"); + headers.setContentLength(data.size || 0); + data = stream.Readable.from(readBlob(data)); + } else if (data && !utils$2.isStream(data)) { + if (Buffer.isBuffer(data)) ; + else if (utils$2.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils$2.isString(data)) { + data = Buffer.from(data, "utf-8"); + } else { + return reject( + new AxiosError$1( + "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", + AxiosError$1.ERR_BAD_REQUEST, + config + ) + ); + } + headers.setContentLength(data.length, false); + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject( + new AxiosError$1( + "Request body larger than maxBodyLength limit", + AxiosError$1.ERR_BAD_REQUEST, + config + ) + ); + } + } + const contentLength = utils$2.toFiniteNumber(headers.getContentLength()); + if (utils$2.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils$2.isStream(data)) { + data = stream.Readable.from(data, { objectMode: false }); + } + data = stream.pipeline( + [ + data, + new AxiosTransformStream({ + maxRate: utils$2.toFiniteNumber(maxUploadRate) + }) + ], + utils$2.noop + ); + onUploadProgress && data.on( + "progress", + flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + ) + ); + } + let auth = void 0; + if (config.auth) { + const username = config.auth.username || ""; + const password = config.auth.password || ""; + auth = username + ":" + password; + } + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ":" + urlPassword; + } + auth && headers.delete("authorization"); + let path; + try { + path = buildURL( + parsed.pathname + parsed.search, + config.params, + config.paramsSerializer + ).replace(/^\?/, ""); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + return reject(customErr); + } + headers.set( + "Accept-Encoding", + "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""), + false + ); + const options = { + path, + method, + headers: headers.toJSON(), + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {}, + http2Options + }; + !utils$2.isUndefined(lookup) && (options.lookup = lookup); + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy( + options, + config.proxy, + protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path + ); + } + let transport; + const isHttpsRequest = isHttps.test(options.protocol); + options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + if (isHttp2) { + transport = http2Transport; + } else { + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsRequest ? require$$4 : require$$3; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirects.config = config.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + } + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } else { + options.maxBodyLength = Infinity; + } + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + const streams = [res]; + const responseLength = utils$2.toFiniteNumber(res.headers["content-length"]); + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream({ + maxRate: utils$2.toFiniteNumber(maxDownloadRate) + }); + onDownloadProgress && transformStream.on( + "progress", + flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + ) + ); + streams.push(transformStream); + } + let responseStream = res; + const lastRequest = res.req || req; + if (config.decompress !== false && res.headers["content-encoding"]) { + if (method === "HEAD" || res.statusCode === 204) { + delete res.headers["content-encoding"]; + } + switch ((res.headers["content-encoding"] || "").toLowerCase()) { + /*eslint default-case:0*/ + case "gzip": + case "x-gzip": + case "compress": + case "x-compress": + streams.push(zlib.createUnzip(zlibOptions)); + delete res.headers["content-encoding"]; + break; + case "deflate": + streams.push(new ZlibHeaderTransformStream()); + streams.push(zlib.createUnzip(zlibOptions)); + delete res.headers["content-encoding"]; + break; + case "br": + if (isBrotliSupported) { + streams.push(zlib.createBrotliDecompress(brotliOptions)); + delete res.headers["content-encoding"]; + } + } + } + responseStream = streams.length > 1 ? stream.pipeline(streams, utils$2.noop) : streams[0]; + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders$1(res.headers), + config, + request: lastRequest + }; + if (responseType === "stream") { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + responseStream.on("data", function handleStreamData(chunk2) { + responseBuffer.push(chunk2); + totalResponseBytes += chunk2.length; + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + rejected = true; + responseStream.destroy(); + abort( + new AxiosError$1( + "maxContentLength size of " + config.maxContentLength + " exceeded", + AxiosError$1.ERR_BAD_RESPONSE, + config, + lastRequest + ) + ); + } + }); + responseStream.on("aborted", function handlerStreamAborted() { + if (rejected) { + return; + } + const err = new AxiosError$1( + "stream has been aborted", + AxiosError$1.ERR_BAD_RESPONSE, + config, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + responseStream.on("error", function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError$1.from(err, null, config, lastRequest)); + }); + responseStream.on("end", function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== "arraybuffer") { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + responseData = utils$2.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError$1.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + abortEmitter.once("abort", (err) => { + if (!responseStream.destroyed) { + responseStream.emit("error", err); + responseStream.destroy(); + } + }); + }); + abortEmitter.once("abort", (err) => { + if (req.close) { + req.close(); + } else { + req.destroy(err); + } + }); + req.on("error", function handleRequestError(err) { + reject(AxiosError$1.from(err, null, config, req)); + }); + req.on("socket", function handleRequestSocket(socket) { + socket.setKeepAlive(true, 1e3 * 60); + }); + if (config.timeout) { + const timeout = parseInt(config.timeout, 10); + if (Number.isNaN(timeout)) { + abort( + new AxiosError$1( + "error trying to parse `config.timeout` to int", + AxiosError$1.ERR_BAD_OPTION_VALUE, + config, + req + ) + ); + return; + } + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + abort( + new AxiosError$1( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, + config, + req + ) + ); + }); + } else { + req.setTimeout(0); + } + if (utils$2.isStream(data)) { + let ended = false; + let errored = false; + data.on("end", () => { + ended = true; + }); + data.once("error", (err) => { + errored = true; + req.destroy(err); + }); + data.on("close", () => { + if (!ended && !errored) { + abort(new CanceledError$1("Request stream has been aborted", config, req)); + } + }); + data.pipe(req); + } else { + data && req.write(data); + req.end(); + } + }); +}; +const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => { + url = new URL(url, platform.origin); + return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true; +const cookies = platform.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name2, value, expires, path, domain, secure, sameSite) { + if (typeof document === "undefined") return; + const cookie = [`${name2}=${encodeURIComponent(value)}`]; + if (utils$2.isNumber(expires)) { + cookie.push(`expires=${new Date(expires).toUTCString()}`); + } + if (utils$2.isString(path)) { + cookie.push(`path=${path}`); + } + if (utils$2.isString(domain)) { + cookie.push(`domain=${domain}`); + } + if (secure === true) { + cookie.push("secure"); + } + if (utils$2.isString(sameSite)) { + cookie.push(`SameSite=${sameSite}`); + } + document.cookie = cookie.join("; "); + }, + read(name2) { + if (typeof document === "undefined") return null; + const match = document.cookie.match(new RegExp("(?:^|; )" + name2 + "=([^;]*)")); + return match ? decodeURIComponent(match[1]) : null; + }, + remove(name2) { + this.write(name2, "", Date.now() - 864e5, "/"); + } + } +) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } +); +const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; +function mergeConfig$1(config1, config2) { + config2 = config2 || {}; + const config = {}; + function getMergedValue(target, source, prop, caseless) { + if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) { + return utils$2.merge.call({ caseless }, target, source); + } else if (utils$2.isPlainObject(source)) { + return utils$2.merge({}, source); + } else if (utils$2.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a, b2, prop, caseless) { + if (!utils$2.isUndefined(b2)) { + return getMergedValue(a, b2, prop, caseless); + } else if (!utils$2.isUndefined(a)) { + return getMergedValue(void 0, a, prop, caseless); + } + } + function valueFromConfig2(a, b2) { + if (!utils$2.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } + } + function defaultToConfig2(a, b2) { + if (!utils$2.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } else if (!utils$2.isUndefined(a)) { + return getMergedValue(void 0, a); + } + } + function mergeDirectKeys(a, b2, prop) { + if (prop in config2) { + return getMergedValue(a, b2); + } else if (prop in config1) { + return getMergedValue(void 0, a); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b2, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b2), prop, true) + }; + utils$2.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) { + if (prop === "__proto__" || prop === "constructor" || prop === "prototype") return; + const merge2 = utils$2.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties; + const configValue = merge2(config1[prop], config2[prop], prop); + utils$2.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); + }); + return config; +} +const resolveConfig = (config) => { + const newConfig = mergeConfig$1({}, config); + let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; + newConfig.headers = headers = AxiosHeaders$1.from(headers); + newConfig.url = buildURL( + buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), + config.params, + config.paramsSerializer + ); + if (auth) { + headers.set( + "Authorization", + "Basic " + btoa( + (auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "") + ) + ); + } + if (utils$2.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(void 0); + } else if (utils$2.isFunction(data.getHeaders)) { + const formHeaders = data.getHeaders(); + const allowedHeaders = ["content-type", "content-length"]; + Object.entries(formHeaders).forEach(([key, val]) => { + if (allowedHeaders.includes(key.toLowerCase())) { + headers.set(key, val); + } + }); + } + } + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$2.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) { + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + return newConfig; +}; +const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; +const xhrAdapter = isXHRAdapterSupported && function(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + function done() { + flushUpload && flushUpload(); + flushDownload && flushDownload(); + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.signal && _config.signal.removeEventListener("abort", onCanceled); + } + let request = new XMLHttpRequest(); + request.open(_config.method.toUpperCase(), _config.url, true); + request.timeout = _config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders$1.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + settle( + function _resolve(value) { + resolve(value); + done(); + }, + function _reject(err) { + reject(err); + done(); + }, + response + ); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config, request)); + request = null; + }; + request.onerror = function handleError(event) { + const msg = event && event.message ? event.message : "Network Error"; + const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request); + err.event = event || null; + reject(err); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject( + new AxiosError$1( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, + config, + request + ) + ); + request = null; + }; + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils$2.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils$2.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = _config.responseType; + } + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); + request.addEventListener("progress", downloadThrottled); + } + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); + request.upload.addEventListener("progress", uploadThrottled); + request.upload.addEventListener("loadend", flushUpload); + } + if (_config.cancelToken || _config.signal) { + onCanceled = (cancel2) => { + if (!request) { + return; + } + reject(!cancel2 || cancel2.type ? new CanceledError$1(null, config, request) : cancel2); + request.abort(); + request = null; + }; + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol(_config.url); + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject( + new AxiosError$1( + "Unsupported protocol " + protocol + ":", + AxiosError$1.ERR_BAD_REQUEST, + config + ) + ); + return; + } + request.send(requestData || null); + }); +}; +const composeSignals = (signals, timeout) => { + const { length } = signals = signals ? signals.filter(Boolean) : []; + if (timeout || length) { + let controller = new AbortController(); + let aborted; + const onabort = function(reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort( + err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err) + ); + } + }; + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT)); + }, timeout); + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach((signal2) => { + signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); + }); + signals = null; + } + }; + signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); + const { signal } = controller; + signal.unsubscribe = () => utils$2.asap(unsubscribe); + return signal; + } +}; +const streamChunk = function* (chunk2, chunkSize) { + let len = chunk2.byteLength; + if (len < chunkSize) { + yield chunk2; + return; + } + let pos = 0; + let end; + while (pos < len) { + end = pos + chunkSize; + yield chunk2.slice(pos, end); + pos = end; + } +}; +const readBytes = async function* (iterable, chunkSize) { + for await (const chunk2 of readStream(iterable)) { + yield* streamChunk(chunk2, chunkSize); + } +}; +const readStream = async function* (stream2) { + if (stream2[Symbol.asyncIterator]) { + yield* stream2; + return; + } + const reader = stream2.getReader(); + try { + for (; ; ) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; +const trackStream = (stream2, chunkSize, onProgress, onFinish) => { + const iterator2 = readBytes(stream2, chunkSize); + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + return new ReadableStream( + { + async pull(controller) { + try { + const { done: done2, value } = await iterator2.next(); + if (done2) { + _onFinish(); + controller.close(); + return; + } + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator2.return(); + } + }, + { + highWaterMark: 2 + } + ); +}; +const DEFAULT_CHUNK_SIZE = 64 * 1024; +const { isFunction } = utils$2; +const globalFetchAPI = (({ Request, Response }) => ({ + Request, + Response +}))(utils$2.global); +const { ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1 } = utils$2.global; +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false; + } +}; +const factory = (env2) => { + env2 = utils$2.merge.call( + { + skipUndefined: true + }, + globalFetchAPI, + env2 + ); + const { fetch: envFetch, Request, Response } = env2; + const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function"; + const isRequestSupported = isFunction(Request); + const isResponseSupported = isFunction(Response); + if (!isFetchSupported) { + return false; + } + const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1); + const encodeText = isFetchSupported && (typeof TextEncoder$1 === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer())); + const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { + let duplexAccessed = false; + const body2 = new ReadableStream$1(); + const hasContentType = new Request(platform.origin, { + body: body2, + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + } + }).headers.has("Content-Type"); + body2.cancel(); + return duplexAccessed && !hasContentType; + }); + const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$2.isReadableStream(new Response("").body)); + const resolvers = { + stream: supportsResponseStream && ((res) => res.body) + }; + isFetchSupported && (() => { + ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type2) => { + !resolvers[type2] && (resolvers[type2] = (res, config) => { + let method = res && res[type2]; + if (method) { + return method.call(res); + } + throw new AxiosError$1( + `Response type '${type2}' is not supported`, + AxiosError$1.ERR_NOT_SUPPORT, + config + ); + }); + }); + })(); + const getBodyLength = async (body2) => { + if (body2 == null) { + return 0; + } + if (utils$2.isBlob(body2)) { + return body2.size; + } + if (utils$2.isSpecCompliantForm(body2)) { + const _request = new Request(platform.origin, { + method: "POST", + body: body2 + }); + return (await _request.arrayBuffer()).byteLength; + } + if (utils$2.isArrayBufferView(body2) || utils$2.isArrayBuffer(body2)) { + return body2.byteLength; + } + if (utils$2.isURLSearchParams(body2)) { + body2 = body2 + ""; + } + if (utils$2.isString(body2)) { + return (await encodeText(body2)).byteLength; + } + }; + const resolveBodyLength = async (headers, body2) => { + const length = utils$2.toFiniteNumber(headers.getContentLength()); + return length == null ? getBodyLength(body2) : length; + }; + return async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = "same-origin", + fetchOptions + } = resolveConfig(config); + let _fetch = envFetch || fetch; + responseType = responseType ? (responseType + "").toLowerCase() : "text"; + let composedSignal = composeSignals( + [signal, cancelToken && cancelToken.toAbortSignal()], + timeout + ); + let request = null; + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + let requestContentLength; + try { + if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) { + let _request = new Request(url, { + method: "POST", + body: data, + duplex: "half" + }); + let contentTypeHeader; + if (utils$2.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { + headers.setContentType(contentTypeHeader); + } + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + if (!utils$2.isString(withCredentials)) { + withCredentials = withCredentials ? "include" : "omit"; + } + const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype; + const resolvedOptions = { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : void 0 + }; + request = isRequestSupported && new Request(url, resolvedOptions); + let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions)); + const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response"); + if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) { + const options = {}; + ["status", "statusText", "headers"].forEach((prop) => { + options[prop] = response[prop]; + }); + const responseContentLength = utils$2.toFiniteNumber(response.headers.get("content-length")); + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + responseType = responseType || "text"; + let responseData = await resolvers[utils$2.findKey(resolvers, responseType) || "text"]( + response, + config + ); + !isStreamResponse && unsubscribe && unsubscribe(); + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }); + }); + } catch (err) { + unsubscribe && unsubscribe(); + if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError$1( + "Network Error", + AxiosError$1.ERR_NETWORK, + config, + request, + err && err.response + ), + { + cause: err.cause || err + } + ); + } + throw AxiosError$1.from(err, err && err.code, config, request, err && err.response); + } + }; +}; +const seedCache = /* @__PURE__ */ new Map(); +const getFetch = (config) => { + let env2 = config && config.env || {}; + const { fetch: fetch2, Request, Response } = env2; + const seeds = [Request, Response, fetch2]; + let len = seeds.length, i = len, seed, target, map = seedCache; + while (i--) { + seed = seeds[i]; + target = map.get(seed); + target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env2)); + map = target; + } + return target; +}; +getFetch(); +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: { + get: getFetch + } +}; +utils$2.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, "name", { value }); + } catch (e) { + } + Object.defineProperty(fn, "adapterName", { value }); + } +}); +const renderReason = (reason) => `- ${reason}`; +const isResolvedHandle = (adapter) => utils$2.isFunction(adapter) || adapter === null || adapter === false; +function getAdapter$1(adapters2, config) { + adapters2 = utils$2.isArray(adapters2) ? adapters2 : [adapters2]; + const { length } = adapters2; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters2[i]; + let id; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError$1(`Unknown adapter '${id}'`); + } + } + if (adapter && (utils$2.isFunction(adapter) || (adapter = adapter.get(config)))) { + break; + } + rejectedReasons[id || "#" + i] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s2 = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; + throw new AxiosError$1( + `There is no suitable adapter to dispatch the request ` + s2, + "ERR_NOT_SUPPORT" + ); + } + return adapter; +} +const adapters = { + /** + * Resolve an adapter from a list of adapter names or functions. + * @type {Function} + */ + getAdapter: getAdapter$1, + /** + * Exposes all known adapters + * @type {Object} + */ + adapters: knownAdapters +}; +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + if (config.signal && config.signal.aborted) { + throw new CanceledError$1(null, config); + } +} +function dispatchRequest(config) { + throwIfCancellationRequested(config); + config.headers = AxiosHeaders$1.from(config.headers); + config.data = transformData.call(config, config.transformRequest); + if (["post", "put", "patch"].indexOf(config.method) !== -1) { + config.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config); + return adapter(config).then( + function onAdapterResolution(response) { + throwIfCancellationRequested(config); + response.data = transformData.call(config, config.transformResponse, response); + response.headers = AxiosHeaders$1.from(response.headers); + return response; + }, + function onAdapterRejection(reason) { + if (!isCancel$1(reason)) { + throwIfCancellationRequested(config); + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + return Promise.reject(reason); + } + ); +} +const validators$1 = {}; +["object", "boolean", "number", "function", "string", "symbol"].forEach((type2, i) => { + validators$1[type2] = function validator2(thing) { + return typeof thing === type2 || "a" + (i < 1 ? "n " : " ") + type2; + }; +}); +const deprecatedWarnings = {}; +validators$1.transitional = function transitional(validator2, version, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION$1 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator2 === false) { + throw new AxiosError$1( + formatMessage(opt, " has been removed" + (version ? " in " + version : "")), + AxiosError$1.ERR_DEPRECATED + ); + } + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version + " and will be removed in the near future" + ) + ); + } + return validator2 ? validator2(value, opt, opts) : true; + }; +}; +validators$1.spelling = function spelling(correctSpelling) { + return (value, opt) => { + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + }; +}; +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE); + } + const keys2 = Object.keys(options); + let i = keys2.length; + while (i-- > 0) { + const opt = keys2[i]; + const validator2 = schema[opt]; + if (validator2) { + const value = options[opt]; + const result = value === void 0 || validator2(value, opt, options); + if (result !== true) { + throw new AxiosError$1( + "option " + opt + " must be " + result, + AxiosError$1.ERR_BAD_OPTION_VALUE + ); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError$1("Unknown option " + opt, AxiosError$1.ERR_BAD_OPTION); + } + } +} +const validator = { + assertOptions, + validators: validators$1 +}; +const validators = validator.validators; +let Axios$1 = class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig || {}; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; + } + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + try { + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } catch (e) { + } + } + throw err; + } + } + _request(configOrUrl, config) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + config = mergeConfig$1(this.defaults, config); + const { transitional: transitional2, paramsSerializer, headers } = config; + if (transitional2 !== void 0) { + validator.assertOptions( + transitional2, + { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean), + legacyInterceptorReqResOrdering: validators.transitional(validators.boolean) + }, + false + ); + } + if (paramsSerializer != null) { + if (utils$2.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions( + paramsSerializer, + { + encode: validators.function, + serialize: validators.function + }, + true + ); + } + } + if (config.allowAbsoluteUrls !== void 0) ; + else if (this.defaults.allowAbsoluteUrls !== void 0) { + config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; + } else { + config.allowAbsoluteUrls = true; + } + validator.assertOptions( + config, + { + baseUrl: validators.spelling("baseURL"), + withXsrfToken: validators.spelling("withXSRFToken") + }, + true + ); + config.method = (config.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils$2.merge(headers.common, headers[config.method]); + headers && utils$2.forEach(["delete", "get", "head", "post", "put", "patch", "common"], (method) => { + delete headers[method]; + }); + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + const transitional3 = config.transitional || transitionalDefaults; + const legacyInterceptorReqResOrdering = transitional3 && transitional3.legacyInterceptorReqResOrdering; + if (legacyInterceptorReqResOrdering) { + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + } else { + requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + } + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), void 0]; + chain.unshift(...requestInterceptorChain); + chain.push(...responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config; + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; + } + getUri(config) { + config = mergeConfig$1(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +}; +utils$2.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { + Axios$1.prototype[method] = function(url, config) { + return this.request( + mergeConfig$1(config || {}, { + method, + url, + data: (config || {}).data + }) + ); + }; +}); +utils$2.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request( + mergeConfig$1(config || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url, + data + }) + ); + }; + } + Axios$1.prototype[method] = generateHTTPMethod(); + Axios$1.prototype[method + "Form"] = generateHTTPMethod(true); +}); +let CancelToken$1 = class CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + const token = this; + this.promise.then((cancel2) => { + if (!token._listeners) return; + let i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel2); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel2(message, config, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError$1(message, config, request); + resolvePromise(token.reason); + }); + } + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + /** + * Subscribe to the cancel signal + */ + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + /** + * Unsubscribe from the cancel signal + */ + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index2 = this._listeners.indexOf(listener); + if (index2 !== -1) { + this._listeners.splice(index2, 1); + } + } + toAbortSignal() { + const controller = new AbortController(); + const abort = (err) => { + controller.abort(err); + }; + this.subscribe(abort); + controller.signal.unsubscribe = () => this.unsubscribe(abort); + return controller.signal; + } + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel2; + const token = new CancelToken(function executor(c) { + cancel2 = c; + }); + return { + token, + cancel: cancel2 + }; + } +}; +function spread$1(callback) { + return function wrap2(arr) { + return callback.apply(null, arr); + }; +} +function isAxiosError$1(payload) { + return utils$2.isObject(payload) && payload.isAxiosError === true; +} +const HttpStatusCode$1 = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, + WebServerIsDown: 521, + ConnectionTimedOut: 522, + OriginIsUnreachable: 523, + TimeoutOccurred: 524, + SslHandshakeFailed: 525, + InvalidSslCertificate: 526 +}; +Object.entries(HttpStatusCode$1).forEach(([key, value]) => { + HttpStatusCode$1[value] = key; +}); +function createInstance(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); + utils$2.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); + utils$2.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create2(instanceConfig) { + return createInstance(mergeConfig$1(defaultConfig, instanceConfig)); + }; + return instance; +} +const axios = createInstance(defaults); +axios.Axios = Axios$1; +axios.CanceledError = CanceledError$1; +axios.CancelToken = CancelToken$1; +axios.isCancel = isCancel$1; +axios.VERSION = VERSION$1; +axios.toFormData = toFormData$1; +axios.AxiosError = AxiosError$1; +axios.Cancel = axios.CanceledError; +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = spread$1; +axios.isAxiosError = isAxiosError$1; +axios.mergeConfig = mergeConfig$1; +axios.AxiosHeaders = AxiosHeaders$1; +axios.formToJSON = (thing) => formDataToJSON(utils$2.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.getAdapter = adapters.getAdapter; +axios.HttpStatusCode = HttpStatusCode$1; +axios.default = axios; +const { + Axios: Axios2, + AxiosError: AxiosError2, + CanceledError: CanceledError2, + isCancel, + CancelToken: CancelToken2, + VERSION, + all: all$1, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders: AxiosHeaders2, + HttpStatusCode, + formToJSON, + getAdapter, + mergeConfig +} = axios; +const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Axios: Axios2, + AxiosError: AxiosError2, + AxiosHeaders: AxiosHeaders2, + Cancel, + CancelToken: CancelToken2, + CanceledError: CanceledError2, + HttpStatusCode, + VERSION, + all: all$1, + default: axios, + formToJSON, + getAdapter, + isAxiosError, + isCancel, + mergeConfig, + spread, + toFormData +}, Symbol.toStringTag, { value: "Module" })); +var cjs$3; +var hasRequiredCjs$3; +function requireCjs$3() { + if (hasRequiredCjs$3) return cjs$3; + hasRequiredCjs$3 = 1; + var isMergeableObject = function isMergeableObject2(value) { + return isNonNullObject(value) && !isSpecial(value); + }; + function isNonNullObject(value) { + return !!value && typeof value === "object"; + } + function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); + return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value); + } + var canUseSymbol = typeof Symbol === "function" && Symbol.for; + var REACT_ELEMENT_TYPE = canUseSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103; + function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE; + } + function emptyTarget(val) { + return Array.isArray(val) ? [] : {}; + } + function cloneUnlessOtherwiseSpecified(value, options) { + return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value; + } + function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element2) { + return cloneUnlessOtherwiseSpecified(element2, options); + }); + } + function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge; + } + var customMerge = options.customMerge(key); + return typeof customMerge === "function" ? customMerge : deepmerge; + } + function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return Object.propertyIsEnumerable.call(target, symbol); + }) : []; + } + function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)); + } + function propertyIsOnObject(object, property) { + try { + return property in object; + } catch (_2) { + return false; + } + } + function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key)); + } + function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return; + } + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination; + } + function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options); + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options); + } else { + return mergeObject(target, source, options); + } + } + deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error("first argument should be an array"); + } + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options); + }, {}); + }; + var deepmerge_1 = deepmerge; + cjs$3 = deepmerge_1; + return cjs$3; +} +var cjsExports$1 = requireCjs$3(); +const oe = /* @__PURE__ */ getDefaultExportFromCjs(cjsExports$1); +var util_inspect; +var hasRequiredUtil_inspect; +function requireUtil_inspect() { + if (hasRequiredUtil_inspect) return util_inspect; + hasRequiredUtil_inspect = 1; + util_inspect = require$$0$1.inspect; + return util_inspect; +} +var objectInspect; +var hasRequiredObjectInspect; +function requireObjectInspect() { + if (hasRequiredObjectInspect) return objectInspect; + hasRequiredObjectInspect = 1; + var hasMap = typeof Map === "function" && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === "function" && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; + var toStringTag2 = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) { + return O.__proto__; + } : null); + function addNumericSeparator(num, str) { + if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === "number") { + var int = num < 0 ? -$floor(-num) : $floor(num); + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); + } + } + return $replace.call(str, sepRegex, "$&_"); + } + var utilInspect = /* @__PURE__ */ requireUtil_inspect(); + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + var quotes = { + __proto__: null, + "double": '"', + single: "'" + }; + var quoteREs = { + __proto__: null, + "double": /(["\\])/g, + single: /(['\\])/g + }; + objectInspect = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, "customInspect") ? opts.customInspect : true; + if (typeof customInspect !== "boolean" && customInspect !== "symbol") { + throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); + } + if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + if (typeof obj === "boolean") { + return obj ? "true" : "false"; + } + if (typeof obj === "string") { + return inspectString(obj, opts); + } + if (typeof obj === "number") { + if (obj === 0) { + return Infinity / obj > 0 ? "0" : "-0"; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === "bigint") { + var bigIntStr = String(obj) + "n"; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; + if (typeof depth === "undefined") { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { + return isArray2(obj) ? "[Array]" : "[Object]"; + } + var indent = getIndent(opts, depth); + if (typeof seen === "undefined") { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return "[Circular]"; + } + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, "quoteStyle")) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === "function" && !isRegExp2(obj)) { + var name2 = nameOf(obj); + var keys2 = arrObjKeys(obj, inspect); + return "[Function" + (name2 ? ": " + name2 : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : ""); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); + return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s2 = "<" + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s2 += " " + attrs[i].name + "=" + wrapQuotes(quote(attrs[i].value), "double", opts); + } + s2 += ">"; + if (obj.childNodes && obj.childNodes.length) { + s2 += "..."; + } + s2 += ""; + return s2; + } + if (isArray2(obj)) { + if (obj.length === 0) { + return "[]"; + } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return "[" + indentedJoin(xs, indent) + "]"; + } + return "[ " + $join.call(xs, ", ") + " ]"; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { + return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; + } + if (parts.length === 0) { + return "[" + String(obj) + "]"; + } + return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; + } + if (typeof obj === "object" && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function(value, key) { + mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); + }); + } + return collectionOf("Map", mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function(value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf("Set", setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf("WeakMap"); + } + if (isWeakSet(obj)) { + return weakCollectionOf("WeakSet"); + } + if (isWeakRef(obj)) { + return weakCollectionOf("WeakRef"); + } + if (isNumber2(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean2(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString2(obj)) { + return markBoxed(inspect(String(obj))); + } + if (typeof window !== "undefined" && obj === window) { + return "{ [object Window] }"; + } + if (typeof globalThis !== "undefined" && obj === globalThis || typeof commonjsGlobal !== "undefined" && obj === commonjsGlobal) { + return "{ [object globalThis] }"; + } + if (!isDate2(obj) && !isRegExp2(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject2 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? "" : "null prototype"; + var stringTag = !isPlainObject2 && toStringTag2 && Object(obj) === obj && toStringTag2 in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; + var constructorTag = isPlainObject2 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; + var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); + if (ys.length === 0) { + return tag + "{}"; + } + if (indent) { + return tag + "{" + indentedJoin(ys, indent) + "}"; + } + return tag + "{ " + $join.call(ys, ", ") + " }"; + } + return String(obj); + }; + function wrapQuotes(s2, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s2 + quoteChar; + } + function quote(s2) { + return $replace.call(String(s2), /"/g, """); + } + function canTrustToString(obj) { + return !toStringTag2 || !(typeof obj === "object" && (toStringTag2 in obj || typeof obj[toStringTag2] !== "undefined")); + } + function isArray2(obj) { + return toStr(obj) === "[object Array]" && canTrustToString(obj); + } + function isDate2(obj) { + return toStr(obj) === "[object Date]" && canTrustToString(obj); + } + function isRegExp2(obj) { + return toStr(obj) === "[object RegExp]" && canTrustToString(obj); + } + function isError(obj) { + return toStr(obj) === "[object Error]" && canTrustToString(obj); + } + function isString2(obj) { + return toStr(obj) === "[object String]" && canTrustToString(obj); + } + function isNumber2(obj) { + return toStr(obj) === "[object Number]" && canTrustToString(obj); + } + function isBoolean2(obj) { + return toStr(obj) === "[object Boolean]" && canTrustToString(obj); + } + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === "object" && obj instanceof Symbol; + } + if (typeof obj === "symbol") { + return true; + } + if (!obj || typeof obj !== "object" || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) { + } + return false; + } + function isBigInt(obj) { + if (!obj || typeof obj !== "object" || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) { + } + return false; + } + var hasOwn = Object.prototype.hasOwnProperty || function(key) { + return key in this; + }; + function has(obj, key) { + return hasOwn.call(obj, key); + } + function toStr(obj) { + return objectToString.call(obj); + } + function nameOf(f2) { + if (f2.name) { + return f2.name; + } + var m = $match.call(functionToString.call(f2), /^function\s*([\w$]+)/); + if (m) { + return m[1]; + } + return null; + } + function indexOf(xs, x) { + if (xs.indexOf) { + return xs.indexOf(x); + } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { + return i; + } + } + return -1; + } + function isMap(x) { + if (!mapSize || !x || typeof x !== "object") { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s2) { + return true; + } + return x instanceof Map; + } catch (e) { + } + return false; + } + function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== "object") { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s2) { + return true; + } + return x instanceof WeakMap; + } catch (e) { + } + return false; + } + function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== "object") { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) { + } + return false; + } + function isSet(x) { + if (!setSize || !x || typeof x !== "object") { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; + } catch (e) { + } + return false; + } + function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== "object") { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s2) { + return true; + } + return x instanceof WeakSet; + } catch (e) { + } + return false; + } + function isElement(x) { + if (!x || typeof x !== "object") { + return false; + } + if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === "string" && typeof x.getAttribute === "function"; + } + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || "single"]; + quoteRE.lastIndex = 0; + var s2 = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s2, "single", opts); + } + function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: "b", + 9: "t", + 10: "n", + 12: "f", + 13: "r" + }[n]; + if (x) { + return "\\" + x; + } + return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16)); + } + function markBoxed(str) { + return "Object(" + str + ")"; + } + function weakCollectionOf(type2) { + return type2 + " { ? }"; + } + function collectionOf(type2, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); + return type2 + " (" + size + ") {" + joinedEntries + "}"; + } + function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], "\n") >= 0) { + return false; + } + } + return true; + } + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === " ") { + baseIndent = " "; + } else if (typeof opts.indent === "number" && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), " "); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + function indentedJoin(xs, indent) { + if (xs.length === 0) { + return ""; + } + var lineJoiner = "\n" + indent.prev + indent.base; + return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; + } + function arrObjKeys(obj, inspect) { + var isArr = isArray2(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ""; + } + } + var syms = typeof gOPS === "function" ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k2 = 0; k2 < syms.length; k2++) { + symMap["$" + syms[k2]] = syms[k2]; + } + } + for (var key in obj) { + if (!has(obj, key)) { + continue; + } + if (isArr && String(Number(key)) === key && key < obj.length) { + continue; + } + if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { + continue; + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); + } else { + xs.push(key + ": " + inspect(obj[key], obj)); + } + } + if (typeof gOPS === "function") { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj)); + } + } + } + return xs; + } + return objectInspect; +} +var sideChannelList; +var hasRequiredSideChannelList; +function requireSideChannelList() { + if (hasRequiredSideChannelList) return sideChannelList; + hasRequiredSideChannelList = 1; + var inspect = /* @__PURE__ */ requireObjectInspect(); + var $TypeError = /* @__PURE__ */ requireType(); + var listGetNode = function(list2, key, isDelete) { + var prev = list2; + var curr; + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + curr.next = /** @type {NonNullable} */ + list2.next; + list2.next = curr; + } + return curr; + } + } + }; + var listGet = function(objects, key) { + if (!objects) { + return void 0; + } + var node2 = listGetNode(objects, key); + return node2 && node2.value; + }; + var listSet = function(objects, key, value) { + var node2 = listGetNode(objects, key); + if (node2) { + node2.value = value; + } else { + objects.next = /** @type {import('./list.d.ts').ListNode} */ + { + // eslint-disable-line no-param-reassign, no-extra-parens + key, + next: objects.next, + value + }; + } + }; + var listHas = function(objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); + }; + var listDelete = function(objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } + }; + sideChannelList = function getSideChannelList() { + var $o; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + var root2 = $o && $o.next; + var deletedNode = listDelete($o, key); + if (deletedNode && root2 && root2 === deletedNode) { + $o = void 0; + } + return !!deletedNode; + }, + get: function(key) { + return listGet($o, key); + }, + has: function(key) { + return listHas($o, key); + }, + set: function(key, value) { + if (!$o) { + $o = { + next: void 0 + }; + } + listSet( + /** @type {NonNullable} */ + $o, + key, + value + ); + } + }; + return channel; + }; + return sideChannelList; +} +var callBound; +var hasRequiredCallBound; +function requireCallBound() { + if (hasRequiredCallBound) return callBound; + hasRequiredCallBound = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBindBasic = requireCallBindApplyHelpers(); + var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]); + callBound = function callBoundIntrinsic(name2, allowMissing) { + var intrinsic = ( + /** @type {(this: unknown, ...args: unknown[]) => unknown} */ + GetIntrinsic(name2, !!allowMissing) + ); + if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) { + return callBindBasic( + /** @type {const} */ + [intrinsic] + ); + } + return intrinsic; + }; + return callBound; +} +var sideChannelMap; +var hasRequiredSideChannelMap; +function requireSideChannelMap() { + if (hasRequiredSideChannelMap) return sideChannelMap; + hasRequiredSideChannelMap = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBound2 = /* @__PURE__ */ requireCallBound(); + var inspect = /* @__PURE__ */ requireObjectInspect(); + var $TypeError = /* @__PURE__ */ requireType(); + var $Map = GetIntrinsic("%Map%", true); + var $mapGet = callBound2("Map.prototype.get", true); + var $mapSet = callBound2("Map.prototype.set", true); + var $mapHas = callBound2("Map.prototype.has", true); + var $mapDelete = callBound2("Map.prototype.delete", true); + var $mapSize = callBound2("Map.prototype.size", true); + sideChannelMap = !!$Map && /** @type {Exclude} */ + function getSideChannelMap() { + var $m; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void 0; + } + return result; + } + return false; + }, + get: function(key) { + if ($m) { + return $mapGet($m, key); + } + }, + has: function(key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function(key, value) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + return channel; + }; + return sideChannelMap; +} +var sideChannelWeakmap; +var hasRequiredSideChannelWeakmap; +function requireSideChannelWeakmap() { + if (hasRequiredSideChannelWeakmap) return sideChannelWeakmap; + hasRequiredSideChannelWeakmap = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBound2 = /* @__PURE__ */ requireCallBound(); + var inspect = /* @__PURE__ */ requireObjectInspect(); + var getSideChannelMap = requireSideChannelMap(); + var $TypeError = /* @__PURE__ */ requireType(); + var $WeakMap = GetIntrinsic("%WeakMap%", true); + var $weakMapGet = callBound2("WeakMap.prototype.get", true); + var $weakMapSet = callBound2("WeakMap.prototype.set", true); + var $weakMapHas = callBound2("WeakMap.prototype.has", true); + var $weakMapDelete = callBound2("WeakMap.prototype.delete", true); + sideChannelWeakmap = $WeakMap ? ( + /** @type {Exclude} */ + function getSideChannelWeakMap() { + var $wm; + var $m; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m["delete"](key); + } + } + return false; + }, + get: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function(key, value) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + $m.set(key, value); + } + } + }; + return channel; + } + ) : getSideChannelMap; + return sideChannelWeakmap; +} +var sideChannel; +var hasRequiredSideChannel; +function requireSideChannel() { + if (hasRequiredSideChannel) return sideChannel; + hasRequiredSideChannel = 1; + var $TypeError = /* @__PURE__ */ requireType(); + var inspect = /* @__PURE__ */ requireObjectInspect(); + var getSideChannelList = requireSideChannelList(); + var getSideChannelMap = requireSideChannelMap(); + var getSideChannelWeakMap = requireSideChannelWeakmap(); + var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + sideChannel = function getSideChannel() { + var $channelData; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + return !!$channelData && $channelData["delete"](key); + }, + get: function(key) { + return $channelData && $channelData.get(key); + }, + has: function(key) { + return !!$channelData && $channelData.has(key); + }, + set: function(key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + $channelData.set(key, value); + } + }; + return channel; + }; + return sideChannel; +} +var formats; +var hasRequiredFormats; +function requireFormats() { + if (hasRequiredFormats) return formats; + hasRequiredFormats = 1; + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + var Format = { + RFC1738: "RFC1738", + RFC3986: "RFC3986" + }; + formats = { + "default": Format.RFC3986, + formatters: { + RFC1738: function(value) { + return replace.call(value, percentTwenties, "+"); + }, + RFC3986: function(value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + return formats; +} +var utils; +var hasRequiredUtils; +function requireUtils() { + if (hasRequiredUtils) return utils; + hasRequiredUtils = 1; + var formats2 = /* @__PURE__ */ requireFormats(); + var getSideChannel = requireSideChannel(); + var has = Object.prototype.hasOwnProperty; + var isArray2 = Array.isArray; + var overflowChannel = getSideChannel(); + var markOverflow = function markOverflow2(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + return obj; + }; + var isOverflow = function isOverflow2(obj) { + return overflowChannel.has(obj); + }; + var getMaxIndex = function getMaxIndex2(obj) { + return overflowChannel.get(obj); + }; + var setMaxIndex = function setMaxIndex2(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + }; + var hexTable = (function() { + var array = []; + for (var i = 0; i < 256; ++i) { + array[array.length] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(); + } + return array; + })(); + var compactQueue = function compactQueue2(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + if (isArray2(obj)) { + var compacted = []; + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== "undefined") { + compacted[compacted.length] = obj[j]; + } + } + item.obj[item.prop] = compacted; + } + } + }; + var arrayToObject2 = function arrayToObject3(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== "undefined") { + obj[i] = source[i]; + } + } + return obj; + }; + var merge2 = function merge3(target, source, options) { + if (!source) { + return target; + } + if (typeof source !== "object" && typeof source !== "function") { + if (isArray2(target)) { + var nextIndex = target.length; + if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) { + return markOverflow(arrayToObject2(target.concat(source), options), nextIndex); + } + target[nextIndex] = source; + } else if (target && typeof target === "object") { + if (isOverflow(target)) { + var newIndex = getMaxIndex(target) + 1; + target[newIndex] = source; + setMaxIndex(target, newIndex); + } else if (options && options.strictMerge) { + return [target, source]; + } else if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + return target; + } + if (!target || typeof target !== "object") { + if (isOverflow(source)) { + var sourceKeys = Object.keys(source); + var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target }; + for (var m = 0; m < sourceKeys.length; m++) { + var oldKey = parseInt(sourceKeys[m], 10); + result[oldKey + 1] = source[sourceKeys[m]]; + } + return markOverflow(result, getMaxIndex(source) + 1); + } + var combined = [target].concat(source); + if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) { + return markOverflow(arrayToObject2(combined, options), combined.length - 1); + } + return combined; + } + var mergeTarget = target; + if (isArray2(target) && !isArray2(source)) { + mergeTarget = arrayToObject2(target, options); + } + if (isArray2(target) && isArray2(source)) { + source.forEach(function(item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { + target[i] = merge3(targetItem, item, options); + } else { + target[target.length] = item; + } + } else { + target[i] = item; + } + }); + return target; + } + return Object.keys(source).reduce(function(acc, key) { + var value = source[key]; + if (has.call(acc, key)) { + acc[key] = merge3(acc[key], value, options); + } else { + acc[key] = value; + } + if (isOverflow(source) && !isOverflow(acc)) { + markOverflow(acc, getMaxIndex(source)); + } + if (isOverflow(acc)) { + var keyNum = parseInt(key, 10); + if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) { + setMaxIndex(acc, keyNum); + } + } + return acc; + }, mergeTarget); + }; + var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function(acc, key) { + acc[key] = source[key]; + return acc; + }, target); + }; + var decode2 = function(str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, " "); + if (charset === "iso-8859-1") { + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } + }; + var limit = 1024; + var encode2 = function encode3(str, defaultEncoder, charset, kind, format) { + if (str.length === 0) { + return str; + } + var string2 = str; + if (typeof str === "symbol") { + string2 = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string2 = String(str); + } + if (charset === "iso-8859-1") { + return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + var out = ""; + for (var j = 0; j < string2.length; j += limit) { + var segment = string2.length >= limit ? string2.slice(j, j + limit) : string2; + var arr = []; + for (var i = 0; i < segment.length; ++i) { + var c = segment.charCodeAt(i); + if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === formats2.RFC1738 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hexTable[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hexTable[192 | c >> 6] + hexTable[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; + } + out += arr.join(""); + } + return out; + }; + var compact = function compact2(value) { + var queue = [{ obj: { o: value }, prop: "o" }]; + var refs = []; + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + var keys2 = Object.keys(obj); + for (var j = 0; j < keys2.length; ++j) { + var key = keys2[j]; + var val = obj[key]; + if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { + queue[queue.length] = { obj, prop: key }; + refs[refs.length] = val; + } + } + } + compactQueue(queue); + return value; + }; + var isRegExp2 = function isRegExp3(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; + }; + var isBuffer2 = function isBuffer3(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + }; + var combine = function combine2(a, b2, arrayLimit, plainObjects) { + if (isOverflow(a)) { + var newIndex = getMaxIndex(a) + 1; + a[newIndex] = b2; + setMaxIndex(a, newIndex); + return a; + } + var result = [].concat(a, b2); + if (result.length > arrayLimit) { + return markOverflow(arrayToObject2(result, { plainObjects }), result.length - 1); + } + return result; + }; + var maybeMap = function maybeMap2(val, fn) { + if (isArray2(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped[mapped.length] = fn(val[i]); + } + return mapped; + } + return fn(val); + }; + utils = { + arrayToObject: arrayToObject2, + assign, + combine, + compact, + decode: decode2, + encode: encode2, + isBuffer: isBuffer2, + isOverflow, + isRegExp: isRegExp2, + markOverflow, + maybeMap, + merge: merge2 + }; + return utils; +} +var stringify_1; +var hasRequiredStringify; +function requireStringify() { + if (hasRequiredStringify) return stringify_1; + hasRequiredStringify = 1; + var getSideChannel = requireSideChannel(); + var utils2 = /* @__PURE__ */ requireUtils(); + var formats2 = /* @__PURE__ */ requireFormats(); + var has = Object.prototype.hasOwnProperty; + var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + "[]"; + }, + comma: "comma", + indices: function indices(prefix, key) { + return prefix + "[" + key + "]"; + }, + repeat: function repeat(prefix) { + return prefix; + } + }; + var isArray2 = Array.isArray; + var push2 = Array.prototype.push; + var pushToArray = function(arr, valueOrArray) { + push2.apply(arr, isArray2(valueOrArray) ? valueOrArray : [valueOrArray]); + }; + var toISO = Date.prototype.toISOString; + var defaultFormat = formats2["default"]; + var defaults2 = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + commaRoundTrip: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: utils2.encode, + encodeValuesOnly: false, + filter: void 0, + format: defaultFormat, + formatter: formats2.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false + }; + var isNonNullishPrimitive = function isNonNullishPrimitive2(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; + }; + var sentinel = {}; + var stringify2 = function stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel2) { + var obj = object; + var tmpSc = sideChannel2; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + findFlag = true; + } + } + if (typeof tmpSc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter2 === "function") { + obj = filter2(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === "comma" && isArray2(obj)) { + obj = utils2.maybeMap(obj, function(value2) { + if (value2 instanceof Date) { + return serializeDate(value2); + } + return value2; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults2.encoder, charset, "key", format) : prefix; + } + obj = ""; + } + if (isNonNullishPrimitive(obj) || utils2.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format); + return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults2.encoder, charset, "value", format))]; + } + return [formatter(prefix) + "=" + formatter(String(obj))]; + } + var values = []; + if (typeof obj === "undefined") { + return values; + } + var objKeys; + if (generateArrayPrefix === "comma" && isArray2(obj)) { + if (encodeValuesOnly && encoder) { + obj = utils2.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray2(filter2)) { + objKeys = filter2; + } else { + var keys2 = Object.keys(obj); + objKeys = sort ? keys2.sort(sort) : keys2; + } + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + var adjustedPrefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix; + if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { + return adjustedPrefix + "[]"; + } + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === "object" && key && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; + } + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, "%2E") : String(key); + var keyPrefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]"); + sideChannel2.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel2); + pushToArray(values, stringify3( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, + filter2, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; + }; + var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { + if (!opts) { + return defaults2; + } + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + var charset = opts.charset || defaults2.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var format = formats2["default"]; + if (typeof opts.format !== "undefined") { + if (!has.call(formats2.formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + var formatter = formats2.formatters[format]; + var filter2 = defaults2.filter; + if (typeof opts.filter === "function" || isArray2(opts.filter)) { + filter2 = opts.filter; + } + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults2.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix, + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly, + filter: filter2, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling + }; + }; + stringify_1 = function(object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + var objKeys; + var filter2; + if (typeof options.filter === "function") { + filter2 = options.filter; + obj = filter2("", obj); + } else if (isArray2(options.filter)) { + filter2 = options.filter; + objKeys = filter2; + } + var keys2 = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!objKeys) { + objKeys = Object.keys(obj); + } + if (options.sort) { + objKeys.sort(options.sort); + } + var sideChannel2 = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + var value = obj[key]; + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys2, stringify2( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel2 + )); + } + var joined = keys2.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; + }; + return stringify_1; +} +var parse$1; +var hasRequiredParse; +function requireParse() { + if (hasRequiredParse) return parse$1; + hasRequiredParse = 1; + var utils2 = /* @__PURE__ */ requireUtils(); + var has = Object.prototype.hasOwnProperty; + var isArray2 = Array.isArray; + var defaults2 = { + allowDots: false, + allowEmptyArrays: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: "utf-8", + charsetSentinel: false, + comma: false, + decodeDotInKeys: false, + decoder: utils2.decode, + delimiter: "&", + depth: 5, + duplicates: "combine", + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1e3, + parseArrays: true, + plainObjects: false, + strictDepth: false, + strictMerge: true, + strictNullHandling: false, + throwOnLimitExceeded: false + }; + var interpretNumericEntities = function(str) { + return str.replace(/&#(\d+);/g, function($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); + }; + var parseArrayValue = function(val, options, currentArrayLength) { + if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { + return val.split(","); + } + if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { + throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); + } + return val; + }; + var isoSentinel = "utf8=%26%2310003%3B"; + var charsetSentinel = "utf8=%E2%9C%93"; + var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; + cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; + var parts = cleanStr.split( + options.delimiter, + options.throwOnLimitExceeded ? limit + 1 : limit + ); + if (options.throwOnLimitExceeded && parts.length > limit) { + throw new RangeError("Parameter limit exceeded. Only " + limit + " parameter" + (limit === 1 ? "" : "s") + " allowed."); + } + var skipIndex = -1; + var i; + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf("utf8=") === 0) { + if (parts[i] === charsetSentinel) { + charset = "utf-8"; + } else if (parts[i] === isoSentinel) { + charset = "iso-8859-1"; + } + skipIndex = i; + i = parts.length; + } + } + } + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + var bracketEqualsPos = part.indexOf("]="); + var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults2.decoder, charset, "key"); + val = options.strictNullHandling ? null : ""; + } else { + key = options.decoder(part.slice(0, pos), defaults2.decoder, charset, "key"); + if (key !== null) { + val = utils2.maybeMap( + parseArrayValue( + part.slice(pos + 1), + options, + isArray2(obj[key]) ? obj[key].length : 0 + ), + function(encodedVal) { + return options.decoder(encodedVal, defaults2.decoder, charset, "value"); + } + ); + } + } + if (val && options.interpretNumericEntities && charset === "iso-8859-1") { + val = interpretNumericEntities(String(val)); + } + if (part.indexOf("[]=") > -1) { + val = isArray2(val) ? [val] : val; + } + if (options.comma && isArray2(val) && val.length > options.arrayLimit) { + if (options.throwOnLimitExceeded) { + throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); + } + val = utils2.combine([], val, options.arrayLimit, options.plainObjects); + } + if (key !== null) { + var existing = has.call(obj, key); + if (existing && (options.duplicates === "combine" || part.indexOf("[]=") > -1)) { + obj[key] = utils2.combine( + obj[key], + val, + options.arrayLimit, + options.plainObjects + ); + } else if (!existing || options.duplicates === "last") { + obj[key] = val; + } + } + } + return obj; + }; + var parseObject = function(chain, val, options, valuesParsed) { + var currentArrayLength = 0; + if (chain.length > 0 && chain[chain.length - 1] === "[]") { + var parentKey = chain.slice(0, -1).join(""); + currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; + } + var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root2 = chain[i]; + if (root2 === "[]" && options.parseArrays) { + if (utils2.isOverflow(leaf)) { + obj = leaf; + } else { + obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : utils2.combine( + [], + leaf, + options.arrayLimit, + options.plainObjects + ); + } + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root2.charAt(0) === "[" && root2.charAt(root2.length - 1) === "]" ? root2.slice(1, -1) : root2; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot; + var index2 = parseInt(decodedRoot, 10); + var isValidArrayIndex = !isNaN(index2) && root2 !== decodedRoot && String(index2) === decodedRoot && index2 >= 0 && options.parseArrays; + if (!options.parseArrays && decodedRoot === "") { + obj = { 0: leaf }; + } else if (isValidArrayIndex && index2 < options.arrayLimit) { + obj = []; + obj[index2] = leaf; + } else if (isValidArrayIndex && options.throwOnLimitExceeded) { + throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); + } else if (isValidArrayIndex) { + obj[index2] = leaf; + utils2.markOverflow(obj, index2); + } else if (decodedRoot !== "__proto__") { + obj[decodedRoot] = leaf; + } + } + leaf = obj; + } + return leaf; + }; + var splitKeyIntoSegments = function splitKeyIntoSegments2(givenKey, options) { + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; + if (options.depth <= 0) { + if (!options.plainObjects && has.call(Object.prototype, key)) { + if (!options.allowPrototypes) { + return; + } + } + return [key]; + } + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + var keys2 = []; + if (parent) { + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + keys2[keys2.length] = parent; + } + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + var segmentContent = segment[1].slice(1, -1); + if (!options.plainObjects && has.call(Object.prototype, segmentContent)) { + if (!options.allowPrototypes) { + return; + } + } + keys2[keys2.length] = segment[1]; + } + if (segment) { + if (options.strictDepth === true) { + throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true"); + } + keys2[keys2.length] = "[" + key.slice(segment.index) + "]"; + } + return keys2; + }; + var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + var keys2 = splitKeyIntoSegments(givenKey, options); + if (!keys2) { + return; + } + return parseObject(keys2, val, options, valuesParsed); + }; + var normalizeParseOptions = function normalizeParseOptions2(opts) { + if (!opts) { + return defaults2; + } + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") { + throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") { + throw new TypeError("Decoder has to be a function."); + } + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + if (typeof opts.throwOnLimitExceeded !== "undefined" && typeof opts.throwOnLimitExceeded !== "boolean") { + throw new TypeError("`throwOnLimitExceeded` option must be a boolean"); + } + var charset = typeof opts.charset === "undefined" ? defaults2.charset : opts.charset; + var duplicates = typeof opts.duplicates === "undefined" ? defaults2.duplicates : opts.duplicates; + if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") { + throw new TypeError("The duplicates option must be either combine, first, or last"); + } + var allowDots = typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots; + return { + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults2.allowPrototypes, + allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults2.allowSparse, + arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults2.arrayLimit, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel, + comma: typeof opts.comma === "boolean" ? opts.comma : defaults2.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults2.decodeDotInKeys, + decoder: typeof opts.decoder === "function" ? opts.decoder : defaults2.decoder, + delimiter: typeof opts.delimiter === "string" || utils2.isRegExp(opts.delimiter) ? opts.delimiter : defaults2.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults2.depth, + duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults2.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults2.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults2.plainObjects, + strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults2.strictDepth, + strictMerge: typeof opts.strictMerge === "boolean" ? !!opts.strictMerge : defaults2.strictMerge, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling, + throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === "boolean" ? opts.throwOnLimitExceeded : false + }; + }; + parse$1 = function(str, opts) { + var options = normalizeParseOptions(opts); + if (str === "" || str === null || typeof str === "undefined") { + return options.plainObjects ? { __proto__: null } : {}; + } + var tempObj = typeof str === "string" ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + var keys2 = Object.keys(tempObj); + for (var i = 0; i < keys2.length; ++i) { + var key = keys2[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); + obj = utils2.merge(obj, newObj, options); + } + if (options.allowSparse === true) { + return obj; + } + return utils2.compact(obj); + }; + return parse$1; +} +var lib; +var hasRequiredLib; +function requireLib() { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + var stringify2 = /* @__PURE__ */ requireStringify(); + var parse2 = /* @__PURE__ */ requireParse(); + var formats2 = /* @__PURE__ */ requireFormats(); + lib = { + formats: formats2, + parse: parse2, + stringify: stringify2 + }; + return lib; +} +var libExports = /* @__PURE__ */ requireLib(); +var nprogress$1 = { exports: {} }; +var nprogress = nprogress$1.exports; +var hasRequiredNprogress; +function requireNprogress() { + if (hasRequiredNprogress) return nprogress$1.exports; + hasRequiredNprogress = 1; + (function(module, exports$1) { + (function(root2, factory2) { + { + module.exports = factory2(); + } + })(nprogress, function() { + var NProgress = {}; + NProgress.version = "0.2.0"; + var Settings = NProgress.settings = { + minimum: 0.08, + easing: "ease", + positionUsing: "", + speed: 200, + trickle: true, + trickleRate: 0.02, + trickleSpeed: 800, + showSpinner: true, + barSelector: '[role="bar"]', + spinnerSelector: '[role="spinner"]', + parent: "body", + template: '
' + }; + NProgress.configure = function(options) { + var key, value; + for (key in options) { + value = options[key]; + if (value !== void 0 && options.hasOwnProperty(key)) Settings[key] = value; + } + return this; + }; + NProgress.status = null; + NProgress.set = function(n) { + var started = NProgress.isStarted(); + n = clamp2(n, Settings.minimum, 1); + NProgress.status = n === 1 ? null : n; + var progress = NProgress.render(!started), bar = progress.querySelector(Settings.barSelector), speed = Settings.speed, ease = Settings.easing; + progress.offsetWidth; + queue(function(next) { + if (Settings.positionUsing === "") Settings.positionUsing = NProgress.getPositioningCSS(); + css(bar, barPositionCSS(n, speed, ease)); + if (n === 1) { + css(progress, { + transition: "none", + opacity: 1 + }); + progress.offsetWidth; + setTimeout(function() { + css(progress, { + transition: "all " + speed + "ms linear", + opacity: 0 + }); + setTimeout(function() { + NProgress.remove(); + next(); + }, speed); + }, speed); + } else { + setTimeout(next, speed); + } + }); + return this; + }; + NProgress.isStarted = function() { + return typeof NProgress.status === "number"; + }; + NProgress.start = function() { + if (!NProgress.status) NProgress.set(0); + var work = function() { + setTimeout(function() { + if (!NProgress.status) return; + NProgress.trickle(); + work(); + }, Settings.trickleSpeed); + }; + if (Settings.trickle) work(); + return this; + }; + NProgress.done = function(force) { + if (!force && !NProgress.status) return this; + return NProgress.inc(0.3 + 0.5 * Math.random()).set(1); + }; + NProgress.inc = function(amount) { + var n = NProgress.status; + if (!n) { + return NProgress.start(); + } else { + if (typeof amount !== "number") { + amount = (1 - n) * clamp2(Math.random() * n, 0.1, 0.95); + } + n = clamp2(n + amount, 0, 0.994); + return NProgress.set(n); + } + }; + NProgress.trickle = function() { + return NProgress.inc(Math.random() * Settings.trickleRate); + }; + (function() { + var initial = 0, current = 0; + NProgress.promise = function($promise) { + if (!$promise || $promise.state() === "resolved") { + return this; + } + if (current === 0) { + NProgress.start(); + } + initial++; + current++; + $promise.always(function() { + current--; + if (current === 0) { + initial = 0; + NProgress.done(); + } else { + NProgress.set((initial - current) / initial); + } + }); + return this; + }; + })(); + NProgress.render = function(fromStart) { + if (NProgress.isRendered()) return document.getElementById("nprogress"); + addClass(document.documentElement, "nprogress-busy"); + var progress = document.createElement("div"); + progress.id = "nprogress"; + progress.innerHTML = Settings.template; + var bar = progress.querySelector(Settings.barSelector), perc = fromStart ? "-100" : toBarPerc(NProgress.status || 0), parent = document.querySelector(Settings.parent), spinner; + css(bar, { + transition: "all 0 linear", + transform: "translate3d(" + perc + "%,0,0)" + }); + if (!Settings.showSpinner) { + spinner = progress.querySelector(Settings.spinnerSelector); + spinner && removeElement(spinner); + } + if (parent != document.body) { + addClass(parent, "nprogress-custom-parent"); + } + parent.appendChild(progress); + return progress; + }; + NProgress.remove = function() { + removeClass(document.documentElement, "nprogress-busy"); + removeClass(document.querySelector(Settings.parent), "nprogress-custom-parent"); + var progress = document.getElementById("nprogress"); + progress && removeElement(progress); + }; + NProgress.isRendered = function() { + return !!document.getElementById("nprogress"); + }; + NProgress.getPositioningCSS = function() { + var bodyStyle = document.body.style; + var vendorPrefix = "WebkitTransform" in bodyStyle ? "Webkit" : "MozTransform" in bodyStyle ? "Moz" : "msTransform" in bodyStyle ? "ms" : "OTransform" in bodyStyle ? "O" : ""; + if (vendorPrefix + "Perspective" in bodyStyle) { + return "translate3d"; + } else if (vendorPrefix + "Transform" in bodyStyle) { + return "translate"; + } else { + return "margin"; + } + }; + function clamp2(n, min2, max2) { + if (n < min2) return min2; + if (n > max2) return max2; + return n; + } + function toBarPerc(n) { + return (-1 + n) * 100; + } + function barPositionCSS(n, speed, ease) { + var barCSS; + if (Settings.positionUsing === "translate3d") { + barCSS = { transform: "translate3d(" + toBarPerc(n) + "%,0,0)" }; + } else if (Settings.positionUsing === "translate") { + barCSS = { transform: "translate(" + toBarPerc(n) + "%,0)" }; + } else { + barCSS = { "margin-left": toBarPerc(n) + "%" }; + } + barCSS.transition = "all " + speed + "ms " + ease; + return barCSS; + } + var queue = /* @__PURE__ */ (function() { + var pending = []; + function next() { + var fn = pending.shift(); + if (fn) { + fn(next); + } + } + return function(fn) { + pending.push(fn); + if (pending.length == 1) next(); + }; + })(); + var css = /* @__PURE__ */ (function() { + var cssPrefixes = ["Webkit", "O", "Moz", "ms"], cssProps = {}; + function camelCase(string2) { + return string2.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function(match, letter) { + return letter.toUpperCase(); + }); + } + function getVendorProp(name2) { + var style = document.body.style; + if (name2 in style) return name2; + var i = cssPrefixes.length, capName = name2.charAt(0).toUpperCase() + name2.slice(1), vendorName; + while (i--) { + vendorName = cssPrefixes[i] + capName; + if (vendorName in style) return vendorName; + } + return name2; + } + function getStyleProp(name2) { + name2 = camelCase(name2); + return cssProps[name2] || (cssProps[name2] = getVendorProp(name2)); + } + function applyCss(element2, prop, value) { + prop = getStyleProp(prop); + element2.style[prop] = value; + } + return function(element2, properties) { + var args = arguments, prop, value; + if (args.length == 2) { + for (prop in properties) { + value = properties[prop]; + if (value !== void 0 && properties.hasOwnProperty(prop)) applyCss(element2, prop, value); + } + } else { + applyCss(element2, args[1], args[2]); + } + }; + })(); + function hasClass(element2, name2) { + var list2 = typeof element2 == "string" ? element2 : classList(element2); + return list2.indexOf(" " + name2 + " ") >= 0; + } + function addClass(element2, name2) { + var oldList = classList(element2), newList = oldList + name2; + if (hasClass(oldList, name2)) return; + element2.className = newList.substring(1); + } + function removeClass(element2, name2) { + var oldList = classList(element2), newList; + if (!hasClass(element2, name2)) return; + newList = oldList.replace(" " + name2 + " ", " "); + element2.className = newList.substring(1, newList.length - 1); + } + function classList(element2) { + return (" " + (element2.className || "") + " ").replace(/\s+/gi, " "); + } + function removeElement(element2) { + element2 && element2.parentNode && element2.parentNode.removeChild(element2); + } + return NProgress; + }); + })(nprogress$1); + return nprogress$1.exports; +} +var nprogressExports = requireNprogress(); +const u = /* @__PURE__ */ getDefaultExportFromCjs(nprogressExports); +function T(t, e) { + let i; + return function(...r) { + clearTimeout(i), i = setTimeout(() => t.apply(this, r), e); + }; +} +function f(t, e) { + return document.dispatchEvent(new CustomEvent(`inertia:${t}`, e)); +} +var H$1 = (t) => f("before", { cancelable: true, detail: { visit: t } }), q = (t) => f("error", { detail: { errors: t } }), $ = (t) => f("exception", { cancelable: true, detail: { exception: t } }), N$1 = (t) => f("finish", { detail: { visit: t } }), W$1 = (t) => f("invalid", { cancelable: true, detail: { response: t } }), P = (t) => f("navigate", { detail: { page: t } }), K$1 = (t) => f("progress", { detail: { progress: t } }), X$1 = (t) => f("start", { detail: { visit: t } }), B = (t) => f("success", { detail: { page: t } }); +function I(t) { + return t instanceof File || t instanceof Blob || t instanceof FileList && t.length > 0 || t instanceof FormData && Array.from(t.values()).some((e) => I(e)) || typeof t == "object" && t !== null && Object.values(t).some((e) => I(e)); +} +function k(t, e = new FormData(), i = null) { + t = t || {}; + for (let r in t) Object.prototype.hasOwnProperty.call(t, r) && z(e, J$1(i, r), t[r]); + return e; +} +function J$1(t, e) { + return t ? t + "[" + e + "]" : e; +} +function z(t, e, i) { + if (Array.isArray(i)) return Array.from(i.keys()).forEach((r) => z(t, J$1(e, r.toString()), i[r])); + if (i instanceof Date) return t.append(e, i.toISOString()); + if (i instanceof File) return t.append(e, i, i.name); + if (i instanceof Blob) return t.append(e, i); + if (typeof i == "boolean") return t.append(e, i ? "1" : "0"); + if (typeof i == "string") return t.append(e, i); + if (typeof i == "number") return t.append(e, `${i}`); + if (i == null) return t.append(e, ""); + k(i, t, e); +} +var _ = { modal: null, listener: null, show(t) { + typeof t == "object" && (t = `All Inertia requests must receive a valid Inertia response, however a plain JSON response was received.
${JSON.stringify(t)}`); + let e = document.createElement("html"); + e.innerHTML = t, e.querySelectorAll("a").forEach((r) => r.setAttribute("target", "_top")), this.modal = document.createElement("div"), this.modal.style.position = "fixed", this.modal.style.width = "100vw", this.modal.style.height = "100vh", this.modal.style.padding = "50px", this.modal.style.boxSizing = "border-box", this.modal.style.backgroundColor = "rgba(0, 0, 0, .6)", this.modal.style.zIndex = 2e5, this.modal.addEventListener("click", () => this.hide()); + let i = document.createElement("iframe"); + if (i.style.backgroundColor = "white", i.style.borderRadius = "5px", i.style.width = "100%", i.style.height = "100%", this.modal.appendChild(i), document.body.prepend(this.modal), document.body.style.overflow = "hidden", !i.contentWindow) throw new Error("iframe not yet ready."); + i.contentWindow.document.open(), i.contentWindow.document.write(e.outerHTML), i.contentWindow.document.close(), this.listener = this.hideOnEscape.bind(this), document.addEventListener("keydown", this.listener); +}, hide() { + this.modal.outerHTML = "", this.modal = null, document.body.style.overflow = "visible", document.removeEventListener("keydown", this.listener); +}, hideOnEscape(t) { + t.keyCode === 27 && this.hide(); +} }; +function b(t) { + return new URL(t.toString(), window.location.toString()); +} +function D(t, e, i, r = "brackets") { + let s2 = /^https?:\/\//.test(e.toString()), l = s2 || e.toString().startsWith("/"), h = !l && !e.toString().startsWith("#") && !e.toString().startsWith("?"), g2 = e.toString().includes("?") || t === "get" && Object.keys(i).length, m = e.toString().includes("#"), c = new URL(e.toString(), "http://localhost"); + return t === "get" && Object.keys(i).length && (c.search = libExports.stringify(oe(libExports.parse(c.search, { ignoreQueryPrefix: true }), i), { encodeValuesOnly: true, arrayFormat: r }), i = {}), [[s2 ? `${c.protocol}//${c.host}` : "", l ? c.pathname : "", h ? c.pathname.substring(1) : "", g2 ? c.search : "", m ? c.hash : ""].join(""), i]; +} +function E(t) { + return t = new URL(t.href), t.hash = "", t; +} +var C$1 = typeof window > "u", Y = !C$1 && /CriOS/.test(window.navigator.userAgent), Z = (t) => { + requestAnimationFrame(() => { + requestAnimationFrame(t); + }); +}, F = class { + constructor() { + this.visitId = null; + } + init({ initialPage: e, resolveComponent: i, swapComponent: r }) { + this.page = e, this.resolveComponent = i, this.swapComponent = r, this.setNavigationType(), this.clearRememberedStateOnReload(), this.isBackForwardVisit() ? this.handleBackForwardVisit(this.page) : this.isLocationVisit() ? this.handleLocationVisit(this.page) : this.handleInitialPageVisit(this.page), this.setupEventListeners(); + } + setNavigationType() { + this.navigationType = window.performance && window.performance.getEntriesByType && window.performance.getEntriesByType("navigation").length > 0 ? window.performance.getEntriesByType("navigation")[0].type : "navigate"; + } + clearRememberedStateOnReload() { + this.navigationType === "reload" && window.history.state?.rememberedState && delete window.history.state.rememberedState; + } + handleInitialPageVisit(e) { + let i = window.location.hash; + this.page.url.includes(i) || (this.page.url += i), this.setPage(e, { preserveScroll: true, preserveState: true }).then(() => P(e)); + } + setupEventListeners() { + window.addEventListener("popstate", this.handlePopstateEvent.bind(this)), document.addEventListener("scroll", T(this.handleScrollEvent.bind(this), 100), true); + } + scrollRegions() { + return document.querySelectorAll("[scroll-region]"); + } + handleScrollEvent(e) { + typeof e.target.hasAttribute == "function" && e.target.hasAttribute("scroll-region") && this.saveScrollPositions(); + } + saveScrollPositions() { + this.replaceState({ ...this.page, scrollRegions: Array.from(this.scrollRegions()).map((e) => ({ top: e.scrollTop, left: e.scrollLeft })) }); + } + resetScrollPositions() { + Z(() => { + window.scrollTo(0, 0), this.scrollRegions().forEach((e) => { + typeof e.scrollTo == "function" ? e.scrollTo(0, 0) : (e.scrollTop = 0, e.scrollLeft = 0); + }), this.saveScrollPositions(), window.location.hash && document.getElementById(window.location.hash.slice(1))?.scrollIntoView(); + }); + } + restoreScrollPositions() { + Z(() => { + this.page.scrollRegions && this.scrollRegions().forEach((e, i) => { + let r = this.page.scrollRegions[i]; + if (r) typeof e.scrollTo == "function" ? e.scrollTo(r.left, r.top) : (e.scrollTop = r.top, e.scrollLeft = r.left); + else return; + }); + }); + } + isBackForwardVisit() { + return window.history.state && this.navigationType === "back_forward"; + } + handleBackForwardVisit(e) { + window.history.state.version = e.version, this.setPage(window.history.state, { preserveScroll: true, preserveState: true }).then(() => { + this.restoreScrollPositions(), P(e); + }); + } + locationVisit(e, i) { + try { + let r = { preserveScroll: i }; + window.sessionStorage.setItem("inertiaLocationVisit", JSON.stringify(r)), window.location.href = e.href, E(window.location).href === E(e).href && window.location.reload(); + } catch { + return false; + } + } + isLocationVisit() { + try { + return window.sessionStorage.getItem("inertiaLocationVisit") !== null; + } catch { + return false; + } + } + handleLocationVisit(e) { + let i = JSON.parse(window.sessionStorage.getItem("inertiaLocationVisit") || ""); + window.sessionStorage.removeItem("inertiaLocationVisit"), e.url += window.location.hash, e.rememberedState = window.history.state?.rememberedState ?? {}, e.scrollRegions = window.history.state?.scrollRegions ?? [], this.setPage(e, { preserveScroll: i.preserveScroll, preserveState: true }).then(() => { + i.preserveScroll && this.restoreScrollPositions(), P(e); + }); + } + isLocationVisitResponse(e) { + return !!(e && e.status === 409 && e.headers["x-inertia-location"]); + } + isInertiaResponse(e) { + return !!e?.headers["x-inertia"]; + } + createVisitId() { + return this.visitId = {}, this.visitId; + } + cancelVisit(e, { cancelled: i = false, interrupted: r = false }) { + e && !e.completed && !e.cancelled && !e.interrupted && (e.cancelToken.abort(), e.onCancel(), e.completed = false, e.cancelled = i, e.interrupted = r, N$1(e), e.onFinish(e)); + } + finishVisit(e) { + !e.cancelled && !e.interrupted && (e.completed = true, e.cancelled = false, e.interrupted = false, N$1(e), e.onFinish(e)); + } + resolvePreserveOption(e, i) { + return typeof e == "function" ? e(i) : e === "errors" ? Object.keys(i.props.errors || {}).length > 0 : e; + } + cancel() { + this.activeVisit && this.cancelVisit(this.activeVisit, { cancelled: true }); + } + visit(e, { method: i = "get", data: r = {}, replace: s2 = false, preserveScroll: l = false, preserveState: h = false, only: g2 = [], except: m = [], headers: c = {}, errorBag: o = "", forceFormData: v = false, onCancelToken: L = () => { + }, onBefore: d2 = () => { + }, onStart: p = () => { + }, onProgress: x = () => { + }, onFinish: y = () => { + }, onCancel: ne = () => { + }, onSuccess: U = () => { + }, onError: G2 = () => { + }, queryStringArrayFormat: A = "brackets" } = {}) { + let S = typeof e == "string" ? b(e) : e; + if ((I(r) || v) && !(r instanceof FormData) && (r = k(r)), !(r instanceof FormData)) { + let [n, a] = D(i, S, r, A); + S = b(n), r = a; + } + let R = { url: S, method: i, data: r, replace: s2, preserveScroll: l, preserveState: h, only: g2, except: m, headers: c, errorBag: o, forceFormData: v, queryStringArrayFormat: A, cancelled: false, completed: false, interrupted: false }; + if (d2(R) === false || !H$1(R)) return; + this.activeVisit && this.cancelVisit(this.activeVisit, { interrupted: true }), this.saveScrollPositions(); + let M2 = this.createVisitId(); + this.activeVisit = { ...R, onCancelToken: L, onBefore: d2, onStart: p, onProgress: x, onFinish: y, onCancel: ne, onSuccess: U, onError: G2, queryStringArrayFormat: A, cancelToken: new AbortController() }, L({ cancel: () => { + this.activeVisit && this.cancelVisit(this.activeVisit, { cancelled: true }); + } }), X$1(R), p(R); + let j = !!(g2.length || m.length); + axios({ method: i, url: E(S).href, data: i === "get" ? {} : r, params: i === "get" ? r : {}, signal: this.activeVisit.cancelToken.signal, headers: { ...c, Accept: "text/html, application/xhtml+xml", "X-Requested-With": "XMLHttpRequest", "X-Inertia": true, ...j ? { "X-Inertia-Partial-Component": this.page.component } : {}, ...g2.length ? { "X-Inertia-Partial-Data": g2.join(",") } : {}, ...m.length ? { "X-Inertia-Partial-Except": m.join(",") } : {}, ...o && o.length ? { "X-Inertia-Error-Bag": o } : {}, ...this.page.version ? { "X-Inertia-Version": this.page.version } : {} }, onUploadProgress: (n) => { + r instanceof FormData && (n.percentage = n.progress ? Math.round(n.progress * 100) : 0, K$1(n), x(n)); + } }).then((n) => { + if (!this.isInertiaResponse(n)) return Promise.reject({ response: n }); + let a = n.data; + j && a.component === this.page.component && (a.props = { ...this.page.props, ...a.props }), l = this.resolvePreserveOption(l, a), h = this.resolvePreserveOption(h, a), h && window.history.state?.rememberedState && a.component === this.page.component && (a.rememberedState = window.history.state.rememberedState); + let w2 = S, V2 = b(a.url); + return w2.hash && !V2.hash && E(w2).href === V2.href && (V2.hash = w2.hash, a.url = V2.href), this.setPage(a, { visitId: M2, replace: s2, preserveScroll: l, preserveState: h }); + }).then(() => { + let n = this.page.props.errors || {}; + if (Object.keys(n).length > 0) { + let a = o ? n[o] ? n[o] : {} : n; + return q(a), G2(a); + } + return B(this.page), U(this.page); + }).catch((n) => { + if (this.isInertiaResponse(n.response)) return this.setPage(n.response.data, { visitId: M2 }); + if (this.isLocationVisitResponse(n.response)) { + let a = b(n.response.headers["x-inertia-location"]), w2 = S; + w2.hash && !a.hash && E(w2).href === a.href && (a.hash = w2.hash), this.locationVisit(a, l === true); + } else if (n.response) W$1(n.response) && _.show(n.response.data); + else return Promise.reject(n); + }).then(() => { + this.activeVisit && this.finishVisit(this.activeVisit); + }).catch((n) => { + if (!axios.isCancel(n)) { + let a = $(n); + if (this.activeVisit && this.finishVisit(this.activeVisit), a) return Promise.reject(n); + } + }); + } + setPage(e, { visitId: i = this.createVisitId(), replace: r = false, preserveScroll: s2 = false, preserveState: l = false } = {}) { + return Promise.resolve(this.resolveComponent(e.component)).then((h) => { + i === this.visitId && (e.scrollRegions = this.page.scrollRegions || [], e.rememberedState = e.rememberedState || {}, r = r || b(e.url).href === window.location.href, r ? this.replaceState(e) : this.pushState(e), this.swapComponent({ component: h, page: e, preserveState: l }).then(() => { + s2 ? this.restoreScrollPositions() : this.resetScrollPositions(), r || P(e); + })); + }); + } + pushState(e) { + this.page = e, Y ? setTimeout(() => window.history.pushState(e, "", e.url)) : window.history.pushState(e, "", e.url); + } + replaceState(e) { + this.page = e, Y ? setTimeout(() => window.history.replaceState(e, "", e.url)) : window.history.replaceState(e, "", e.url); + } + handlePopstateEvent(e) { + if (e.state !== null) { + let i = e.state, r = this.createVisitId(); + Promise.resolve(this.resolveComponent(i.component)).then((s2) => { + r === this.visitId && (this.page = i, this.swapComponent({ component: s2, page: i, preserveState: false }).then(() => { + this.restoreScrollPositions(), P(i); + })); + }); + } else { + let i = b(this.page.url); + i.hash = window.location.hash, this.replaceState({ ...this.page, url: i.href }), this.resetScrollPositions(); + } + } + get(e, i = {}, r = {}) { + return this.visit(e, { ...r, method: "get", data: i }); + } + reload(e = {}) { + return this.visit(window.location.href, { ...e, preserveScroll: true, preserveState: true }); + } + replace(e, i = {}) { + return console.warn(`Inertia.replace() has been deprecated and will be removed in a future release. Please use Inertia.${i.method ?? "get"}() instead.`), this.visit(e, { preserveState: true, ...i, replace: true }); + } + post(e, i = {}, r = {}) { + return this.visit(e, { preserveState: true, ...r, method: "post", data: i }); + } + put(e, i = {}, r = {}) { + return this.visit(e, { preserveState: true, ...r, method: "put", data: i }); + } + patch(e, i = {}, r = {}) { + return this.visit(e, { preserveState: true, ...r, method: "patch", data: i }); + } + delete(e, i = {}) { + return this.visit(e, { preserveState: true, ...i, method: "delete" }); + } + remember(e, i = "default") { + C$1 || this.replaceState({ ...this.page, rememberedState: { ...this.page?.rememberedState, [i]: e } }); + } + restore(e = "default") { + if (!C$1) return window.history.state?.rememberedState?.[e]; + } + on(e, i) { + if (C$1) return () => { + }; + let r = (s2) => { + let l = i(s2); + s2.cancelable && !s2.defaultPrevented && l === false && s2.preventDefault(); + }; + return document.addEventListener(`inertia:${e}`, r), () => document.removeEventListener(`inertia:${e}`, r); + } +}; +var se = { buildDOMElement(t) { + let e = document.createElement("template"); + e.innerHTML = t; + let i = e.content.firstChild; + if (!t.startsWith("