From a1d87bcd741436a1f6ee15cc419a06769788ae56 Mon Sep 17 00:00:00 2001 From: reya Date: Sun, 22 Dec 2024 07:35:25 +0700 Subject: [PATCH] wip: update --- .eslintrc.json | 148 - .prettierrc.yaml | 9 - biome.json | 28 + extension/background.js | 384 +- extension/build/style.css | 1137 + extension/chrome/manifest.json | 68 +- extension/common.js | 180 +- extension/content-script.js | 59 +- extension/firefox/manifest.json | 66 +- extension/icons.jsx | 151 +- extension/nostr-provider.js | 186 +- extension/options.jsx | 1268 +- extension/output/background.build.js | 13247 +++--- extension/output/common.js | 180 +- extension/output/content-script.build.js | 2220 +- extension/output/manifest.json | 67 +- extension/output/nostr-provider.js | 186 +- extension/output/prompt.build.js | 49958 ++++++++++++--------- extension/output/style.css | 730 +- extension/popup.jsx | 348 +- extension/prompt.jsx | 263 +- extension/style.css | 4 +- package.json | 60 +- pnpm-lock.yaml | 1847 +- 24 files changed, 39476 insertions(+), 33318 deletions(-) delete mode 100644 .eslintrc.json delete mode 100644 .prettierrc.yaml create mode 100644 biome.json create mode 100644 extension/build/style.css diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 79ea442..0000000 --- a/.eslintrc.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "root": true, - "parserOptions": { - "ecmaVersion": 2020, - "ecmaFeatures": { - "jsx": true - }, - "sourceType": "module", - "allowImportExportEverywhere": false - }, - - "env": { - "es6": true, - "node": true - }, - - "plugins": [ - "react", - "babel" - ], - - "globals": { - "document": false, - "navigator": false, - "window": false, - "location": false, - "URL": false, - "URLSearchParams": false, - "fetch": false, - "EventSource": false, - "localStorage": false, - "sessionStorage": false - }, - - "rules": { - "react/jsx-uses-vars": 2, - "react/jsx-no-undef": 2, - "react/jsx-uses-react": 2, - "accessor-pairs": 2, - "arrow-spacing": [2, { "before": true, "after": true }], - "block-spacing": [2, "always"], - "brace-style": [2, "1tbs", { "allowSingleLine": true }], - "comma-dangle": 0, - "comma-spacing": [2, { "before": false, "after": true }], - "comma-style": [2, "last"], - "constructor-super": 2, - "curly": [0, "multi-line"], - "dot-location": [2, "property"], - "eol-last": 2, - "eqeqeq": [2, "allow-null"], - "generator-star-spacing": [2, { "before": true, "after": true }], - "handle-callback-err": [2, "^(err|error)$" ], - "indent": 0, - "jsx-quotes": [2, "prefer-double"], - "key-spacing": [2, { "beforeColon": false, "afterColon": true }], - "keyword-spacing": [2, { "before": true, "after": true }], - "new-cap": 0, - "new-parens": 0, - "no-array-constructor": 2, - "no-caller": 2, - "no-class-assign": 2, - "no-cond-assign": 2, - "no-const-assign": 2, - "no-control-regex": 0, - "no-debugger": 0, - "no-delete-var": 2, - "no-dupe-args": 2, - "no-dupe-class-members": 2, - "no-dupe-keys": 2, - "no-duplicate-case": 2, - "no-empty-character-class": 2, - "no-empty-pattern": 2, - "no-eval": 0, - "no-ex-assign": 2, - "no-extend-native": 2, - "no-extra-bind": 2, - "no-extra-boolean-cast": 2, - "no-extra-parens": [2, "functions"], - "no-fallthrough": 2, - "no-floating-decimal": 2, - "no-func-assign": 2, - "no-implied-eval": 2, - "no-inner-declarations": [0, "functions"], - "no-invalid-regexp": 2, - "no-irregular-whitespace": 2, - "no-iterator": 2, - "no-label-var": 2, - "no-labels": [2, { "allowLoop": false, "allowSwitch": false }], - "no-lone-blocks": 2, - "no-mixed-spaces-and-tabs": 2, - "no-multi-spaces": 2, - "no-multi-str": 2, - "no-multiple-empty-lines": [2, { "max": 2 }], - "no-native-reassign": 2, - "no-negated-in-lhs": 2, - "no-new": 0, - "no-new-func": 2, - "no-new-object": 2, - "no-new-require": 2, - "no-new-symbol": 2, - "no-new-wrappers": 2, - "no-obj-calls": 2, - "no-octal": 2, - "no-octal-escape": 2, - "no-path-concat": 0, - "no-proto": 2, - "no-redeclare": 2, - "no-regex-spaces": 2, - "no-return-assign": 0, - "no-self-assign": 2, - "no-self-compare": 2, - "no-sequences": 2, - "no-shadow-restricted-names": 2, - "no-spaced-func": 2, - "no-sparse-arrays": 2, - "no-this-before-super": 2, - "no-throw-literal": 2, - "no-trailing-spaces": 2, - "no-undef": 2, - "no-undef-init": 2, - "no-unexpected-multiline": 2, - "no-unneeded-ternary": [2, { "defaultAssignment": false }], - "no-unreachable": 2, - "no-unused-vars": [2, { "vars": "local", "args": "none", "varsIgnorePattern": "^_"}], - "no-useless-call": 2, - "no-useless-constructor": 2, - "no-with": 2, - "one-var": [0, { "initialized": "never" }], - "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }], - "padded-blocks": [2, "never"], - "quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }], - "semi": [2, "never"], - "semi-spacing": [2, { "before": false, "after": true }], - "space-before-blocks": [2, "always"], - "space-before-function-paren": 0, - "space-in-parens": [2, "never"], - "space-infix-ops": 2, - "space-unary-ops": [2, { "words": true, "nonwords": false }], - "spaced-comment": 0, - "template-curly-spacing": [2, "never"], - "use-isnan": 2, - "valid-typeof": 2, - "wrap-iife": [2, "any"], - "yield-star-spacing": [2, "both"], - "yoda": 0, - "no-unsafe-optional-chaning": 0 - } -} diff --git a/.prettierrc.yaml b/.prettierrc.yaml deleted file mode 100644 index e31d792..0000000 --- a/.prettierrc.yaml +++ /dev/null @@ -1,9 +0,0 @@ -arrowParens: avoid -bracketSpacing: false -jsxBracketSameLine: false -printWidth: 80 -proseWrap: preserve -semi: false -singleQuote: true -trailingComma: none -useTabs: false diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..2fd46ba --- /dev/null +++ b/biome.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://biomejs.dev/schemas/1.4.1/schema.json", + "organizeImports": { + "enabled": true + }, + "files": { + "ignore": [] + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "style": { + "noNonNullAssertion": "warn", + "noUselessElse": "off" + }, + "correctness": { + "useExhaustiveDependencies": "off" + }, + "a11y": { + "noSvgWithoutTitle": "off" + }, + "complexity": { + "noStaticOnlyClass": "off" + } + } + } +} diff --git a/extension/background.js b/extension/background.js index 5f67b3e..ca49c18 100644 --- a/extension/background.js +++ b/extension/background.js @@ -1,225 +1,227 @@ -import browser from 'webextension-polyfill' +import { Mutex } from "async-mutex"; import { - validateEvent, - getSignature, - getEventHash, - getPublicKey, - nip19 -} from 'nostr-tools' -import {nip04} from 'nostr-tools' -import {Mutex} from 'async-mutex' + getEventHash, + getPublicKey, + getSignature, + nip19, + validateEvent, +} from "nostr-tools"; +import { nip04 } from "nostr-tools"; +import browser from "webextension-polyfill"; import { - NO_PERMISSIONS_REQUIRED, - getPermissionStatus, - updatePermission, - showNotification -} from './common' + NO_PERMISSIONS_REQUIRED, + getPermissionStatus, + showNotification, + updatePermission, +} from "./common"; -const {encrypt, decrypt} = nip04 +const { encrypt, decrypt } = nip04; -let openPrompt = null -let promptMutex = new Mutex() -let releasePromptMutex = () => {} +let openPrompt = null; +const promptMutex = new Mutex(); +let releasePromptMutex = () => {}; browser.runtime.onInstalled.addListener((_, __, reason) => { - if (reason === 'install') browser.runtime.openOptionsPage() -}) + if (reason === "install") browser.runtime.openOptionsPage(); +}); browser.runtime.onMessage.addListener(async (req, sender) => { - let {prompt} = req + const { prompt } = req; - if (prompt) { - handlePromptMessage(req, sender) - } else { - return handleContentScriptMessage(req) - } -}) + if (prompt) { + handlePromptMessage(req, sender); + } else { + return handleContentScriptMessage(req); + } +}); browser.runtime.onMessageExternal.addListener( - async ({type, params}, sender) => { - let extensionId = new URL(sender.url).host - return handleContentScriptMessage({type, params, host: extensionId}) - } -) + async ({ type, params }, sender) => { + const extensionId = new URL(sender.url).host; + return handleContentScriptMessage({ type, params, host: extensionId }); + }, +); -browser.windows.onRemoved.addListener(windowId => { - if (openPrompt) { - // calling this with a simple "no" response will not store anything, so it's fine - // it will just return a failure - handlePromptMessage({accept: false}, null) - } -}) +browser.windows.onRemoved.addListener((windowId) => { + if (openPrompt) { + // calling this with a simple "no" response will not store anything, so it's fine + // it will just return a failure + handlePromptMessage({ accept: false }, null); + } +}); -async function handleContentScriptMessage({type, params, host}) { - if (NO_PERMISSIONS_REQUIRED[type]) { - // authorized, and we won't do anything with private key here, so do a separate handler - switch (type) { - case 'replaceURL': { - let {protocol_handler: ph} = await browser.storage.local.get([ - 'protocol_handler' - ]) - if (!ph) return false +async function handleContentScriptMessage({ type, params, host }) { + if (NO_PERMISSIONS_REQUIRED[type]) { + // authorized, and we won't do anything with private key here, so do a separate handler + switch (type) { + case "replaceURL": { + const { protocol_handler: ph } = await browser.storage.local.get([ + "protocol_handler", + ]); + if (!ph) return false; - let {url} = params - let raw = url.split('nostr:')[1] - let {type, data} = nip19.decode(raw) - let replacements = { - raw, - hrp: type, - hex: - type === 'npub' || type === 'note' - ? data - : type === 'nprofile' - ? data.pubkey - : type === 'nevent' - ? data.id - : null, - p_or_e: {npub: 'p', note: 'e', nprofile: 'p', nevent: 'e'}[type], - u_or_n: {npub: 'u', note: 'n', nprofile: 'u', nevent: 'n'}[type], - relay0: type === 'nprofile' ? data.relays[0] : null, - relay1: type === 'nprofile' ? data.relays[1] : null, - relay2: type === 'nprofile' ? data.relays[2] : null - } - let result = ph - Object.entries(replacements).forEach(([pattern, value]) => { - result = result.replace(new RegExp(`{ *${pattern} *}`, 'g'), value) - }) + const { url } = params; + const raw = url.split("nostr:")[1]; + const { type, data } = nip19.decode(raw); + const replacements = { + raw, + hrp: type, + hex: + type === "npub" || type === "note" + ? data + : type === "nprofile" + ? data.pubkey + : type === "nevent" + ? data.id + : null, + p_or_e: { npub: "p", note: "e", nprofile: "p", nevent: "e" }[type], + u_or_n: { npub: "u", note: "n", nprofile: "u", nevent: "n" }[type], + relay0: type === "nprofile" ? data.relays[0] : null, + relay1: type === "nprofile" ? data.relays[1] : null, + relay2: type === "nprofile" ? data.relays[2] : null, + }; + let result = ph; + // biome-ignore lint/complexity/noForEach: TODO: fix this + Object.entries(replacements).forEach(([pattern, value]) => { + result = result.replace(new RegExp(`{ *${pattern} *}`, "g"), value); + }); - return result - } - } + return result; + } + } - return - } else { - // acquire mutex here before reading policies - releasePromptMutex = await promptMutex.acquire() + return; + } else { + // acquire mutex here before reading policies + releasePromptMutex = await promptMutex.acquire(); - let allowed = await getPermissionStatus( - host, - type, - type === 'signEvent' ? params.event : undefined - ) + const allowed = await getPermissionStatus( + host, + type, + type === "signEvent" ? params.event : undefined, + ); - if (allowed === true) { - // authorized, proceed - releasePromptMutex() - showNotification(host, allowed, type, params) - } else if (allowed === false) { - // denied, just refuse immediately - releasePromptMutex() - showNotification(host, allowed, type, params) - return { - error: 'denied' - } - } else { - // ask for authorization - try { - let id = Math.random().toString().slice(4) - let qs = new URLSearchParams({ - host, - id, - params: JSON.stringify(params), - type - }) + if (allowed === true) { + // authorized, proceed + releasePromptMutex(); + showNotification(host, allowed, type, params); + } else if (allowed === false) { + // denied, just refuse immediately + releasePromptMutex(); + showNotification(host, allowed, type, params); + return { + error: "denied", + }; + } else { + // ask for authorization + try { + const id = Math.random().toString().slice(4); + const qs = new URLSearchParams({ + host, + id, + params: JSON.stringify(params), + type, + }); - // prompt will be resolved with true or false - let accept = await new Promise((resolve, reject) => { - openPrompt = {resolve, reject} - const url = `${browser.runtime.getURL( - 'prompt.html' - )}?${qs.toString()}` + // prompt will be resolved with true or false + const accept = await new Promise((resolve, reject) => { + openPrompt = { resolve, reject }; + const url = `${browser.runtime.getURL( + "prompt.html", + )}?${qs.toString()}`; - if (browser.windows) { - browser.windows.create({ - url, - type: 'popup', - width: 600, - height: 600 - }) - } else { - browser.tabs.create({ - url, - active: true - }) - } - }) + if (browser.windows) { + browser.windows.create({ + url, + type: "popup", + width: 600, + height: 600, + }); + } else { + browser.tabs.create({ + url, + active: true, + }); + } + }); - // denied, stop here - if (!accept) return {error: 'denied'} - } catch (err) { - // errored, stop here - releasePromptMutex() - return { - error: `error: ${err}` - } - } - } - } + // denied, stop here + if (!accept) return { error: "denied" }; + } catch (err) { + // errored, stop here + releasePromptMutex(); + return { + error: `error: ${err}`, + }; + } + } + } - // if we're here this means it was accepted - let results = await browser.storage.local.get('private_key') - if (!results || !results.private_key) { - return {error: 'no private key found'} - } + // if we're here this means it was accepted + const results = await browser.storage.local.get("private_key"); + if (!results || !results.private_key) { + return { error: "no private key found" }; + } - let sk = results.private_key + const sk = results.private_key; - try { - switch (type) { - case 'getPublicKey': { - return getPublicKey(sk) - } - case 'getRelays': { - let results = await browser.storage.local.get('relays') - return results.relays || {} - } - case 'signEvent': { - let {event} = params + try { + switch (type) { + case "getPublicKey": { + return getPublicKey(sk); + } + case "getRelays": { + const results = await browser.storage.local.get("relays"); + return results.relays || {}; + } + case "signEvent": { + const { event } = params; - if (!event.pubkey) event.pubkey = getPublicKey(sk) - if (!event.id) event.id = getEventHash(event) - if (!validateEvent(event)) return {error: {message: 'invalid event'}} + if (!event.pubkey) event.pubkey = getPublicKey(sk); + if (!event.id) event.id = getEventHash(event); + if (!validateEvent(event)) + return { error: { message: "invalid event" } }; - event.sig = await getSignature(event, sk) - return event - } - case 'nip04.encrypt': { - let {peer, plaintext} = params - return encrypt(sk, peer, plaintext) - } - case 'nip04.decrypt': { - let {peer, ciphertext} = params - return decrypt(sk, peer, ciphertext) - } - } - } catch (error) { - return {error: {message: error.message, stack: error.stack}} - } + event.sig = await getSignature(event, sk); + return event; + } + case "nip04.encrypt": { + const { peer, plaintext } = params; + return encrypt(sk, peer, plaintext); + } + case "nip04.decrypt": { + const { peer, ciphertext } = params; + return decrypt(sk, peer, ciphertext); + } + } + } catch (error) { + return { error: { message: error.message, stack: error.stack } }; + } } -async function handlePromptMessage({host, type, accept, conditions}, sender) { - // return response - openPrompt?.resolve?.(accept) +async function handlePromptMessage({ host, type, accept, conditions }, sender) { + // return response + openPrompt?.resolve?.(accept); - // update policies - if (conditions) { - await updatePermission(host, type, accept, conditions) - } + // update policies + if (conditions) { + await updatePermission(host, type, accept, conditions); + } - // cleanup this - openPrompt = null + // cleanup this + openPrompt = null; - // release mutex here after updating policies - releasePromptMutex() + // release mutex here after updating policies + releasePromptMutex(); - // close prompt - if (sender) { - if (browser.windows) { - browser.windows.remove(sender.tab.windowId) - } else { - // Android Firefox - browser.tabs.remove(sender.tab.id) - } - } + // close prompt + if (sender) { + if (browser.windows) { + browser.windows.remove(sender.tab.windowId); + } else { + // Android Firefox + browser.tabs.remove(sender.tab.id); + } + } } diff --git a/extension/build/style.css b/extension/build/style.css new file mode 100644 index 0000000..c67c18c --- /dev/null +++ b/extension/build/style.css @@ -0,0 +1,1137 @@ +*, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgb(59 130 246 / 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + --tw-contain-size: ; + --tw-contain-layout: ; + --tw-contain-paint: ; + --tw-contain-style: ; +} + +::backdrop { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgb(59 130 246 / 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + --tw-contain-size: ; + --tw-contain-layout: ; + --tw-contain-paint: ; + --tw-contain-style: ; +} + +/* +! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com +*/ + +/* +1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) +2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) +*/ + +*, +::before, +::after { + box-sizing: border-box; + /* 1 */ + border-width: 0; + /* 2 */ + border-style: solid; + /* 2 */ + border-color: #e5e7eb; + /* 2 */ +} + +::before, +::after { + --tw-content: ''; +} + +/* +1. Use a consistent sensible line-height in all browsers. +2. Prevent adjustments of font size after orientation changes in iOS. +3. Use a more readable tab size. +4. Use the user's configured `sans` font-family by default. +5. Use the user's configured `sans` font-feature-settings by default. +6. Use the user's configured `sans` font-variation-settings by default. +7. Disable tap highlights on iOS +*/ + +html, +:host { + line-height: 1.5; + /* 1 */ + -webkit-text-size-adjust: 100%; + /* 2 */ + -moz-tab-size: 4; + /* 3 */ + -o-tab-size: 4; + tab-size: 4; + /* 3 */ + font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + /* 4 */ + font-feature-settings: normal; + /* 5 */ + font-variation-settings: normal; + /* 6 */ + -webkit-tap-highlight-color: transparent; + /* 7 */ +} + +/* +1. Remove the margin in all browsers. +2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. +*/ + +body { + margin: 0; + /* 1 */ + line-height: inherit; + /* 2 */ +} + +/* +1. Add the correct height in Firefox. +2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) +3. Ensure horizontal rules are visible by default. +*/ + +hr { + height: 0; + /* 1 */ + color: inherit; + /* 2 */ + border-top-width: 1px; + /* 3 */ +} + +/* +Add the correct text decoration in Chrome, Edge, and Safari. +*/ + +abbr:where([title]) { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} + +/* +Remove the default font size and weight for headings. +*/ + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: inherit; + font-weight: inherit; +} + +/* +Reset links to optimize for opt-in styling instead of opt-out. +*/ + +a { + color: inherit; + text-decoration: inherit; +} + +/* +Add the correct font weight in Edge and Safari. +*/ + +b, +strong { + font-weight: bolder; +} + +/* +1. Use the user's configured `mono` font-family by default. +2. Use the user's configured `mono` font-feature-settings by default. +3. Use the user's configured `mono` font-variation-settings by default. +4. Correct the odd `em` font sizing in all browsers. +*/ + +code, +kbd, +samp, +pre { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + /* 1 */ + font-feature-settings: normal; + /* 2 */ + font-variation-settings: normal; + /* 3 */ + font-size: 1em; + /* 4 */ +} + +/* +Add the correct font size in all browsers. +*/ + +small { + font-size: 80%; +} + +/* +Prevent `sub` and `sup` elements from affecting the line height in all browsers. +*/ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* +1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) +2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) +3. Remove gaps between table borders by default. +*/ + +table { + text-indent: 0; + /* 1 */ + border-color: inherit; + /* 2 */ + border-collapse: collapse; + /* 3 */ +} + +/* +1. Change the font styles in all browsers. +2. Remove the margin in Firefox and Safari. +3. Remove default padding in all browsers. +*/ + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; + /* 1 */ + font-feature-settings: inherit; + /* 1 */ + font-variation-settings: inherit; + /* 1 */ + font-size: 100%; + /* 1 */ + font-weight: inherit; + /* 1 */ + line-height: inherit; + /* 1 */ + letter-spacing: inherit; + /* 1 */ + color: inherit; + /* 1 */ + margin: 0; + /* 2 */ + padding: 0; + /* 3 */ +} + +/* +Remove the inheritance of text transform in Edge and Firefox. +*/ + +button, +select { + text-transform: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Remove default button styles. +*/ + +button, +input:where([type='button']), +input:where([type='reset']), +input:where([type='submit']) { + -webkit-appearance: button; + /* 1 */ + background-color: transparent; + /* 2 */ + background-image: none; + /* 2 */ +} + +/* +Use the modern Firefox focus style for all focusable elements. +*/ + +:-moz-focusring { + outline: auto; +} + +/* +Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) +*/ + +:-moz-ui-invalid { + box-shadow: none; +} + +/* +Add the correct vertical alignment in Chrome and Firefox. +*/ + +progress { + vertical-align: baseline; +} + +/* +Correct the cursor style of increment and decrement buttons in Safari. +*/ + +::-webkit-inner-spin-button, +::-webkit-outer-spin-button { + height: auto; +} + +/* +1. Correct the odd appearance in Chrome and Safari. +2. Correct the outline style in Safari. +*/ + +[type='search'] { + -webkit-appearance: textfield; + /* 1 */ + outline-offset: -2px; + /* 2 */ +} + +/* +Remove the inner padding in Chrome and Safari on macOS. +*/ + +::-webkit-search-decoration { + -webkit-appearance: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Change font properties to `inherit` in Safari. +*/ + +::-webkit-file-upload-button { + -webkit-appearance: button; + /* 1 */ + font: inherit; + /* 2 */ +} + +/* +Add the correct display in Chrome and Safari. +*/ + +summary { + display: list-item; +} + +/* +Removes the default spacing and border for appropriate elements. +*/ + +blockquote, +dl, +dd, +h1, +h2, +h3, +h4, +h5, +h6, +hr, +figure, +p, +pre { + margin: 0; +} + +fieldset { + margin: 0; + padding: 0; +} + +legend { + padding: 0; +} + +ol, +ul, +menu { + list-style: none; + margin: 0; + padding: 0; +} + +/* +Reset default styling for dialogs. +*/ + +dialog { + padding: 0; +} + +/* +Prevent resizing textareas horizontally by default. +*/ + +textarea { + resize: vertical; +} + +/* +1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) +2. Set the default placeholder color to the user's configured gray 400 color. +*/ + +input::-moz-placeholder, textarea::-moz-placeholder { + opacity: 1; + /* 1 */ + color: #9ca3af; + /* 2 */ +} + +input::placeholder, +textarea::placeholder { + opacity: 1; + /* 1 */ + color: #9ca3af; + /* 2 */ +} + +/* +Set the default cursor for buttons. +*/ + +button, +[role="button"] { + cursor: pointer; +} + +/* +Make sure disabled buttons don't get the pointer cursor. +*/ + +:disabled { + cursor: default; +} + +/* +1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) +2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) + This can trigger a poorly considered lint error in some tools but is included by design. +*/ + +img, +svg, +video, +canvas, +audio, +iframe, +embed, +object { + display: block; + /* 1 */ + vertical-align: middle; + /* 2 */ +} + +/* +Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) +*/ + +img, +video { + max-width: 100%; + height: auto; +} + +/* Make elements with the HTML hidden attribute stay hidden by default */ + +[hidden]:where(:not([hidden="until-found"])) { + display: none; +} + +.\!container { + width: 100% !important; +} + +.container { + width: 100%; +} + +@media (min-width: 640px) { + .\!container { + max-width: 640px !important; + } + + .container { + max-width: 640px; + } +} + +@media (min-width: 768px) { + .\!container { + max-width: 768px !important; + } + + .container { + max-width: 768px; + } +} + +@media (min-width: 1024px) { + .\!container { + max-width: 1024px !important; + } + + .container { + max-width: 1024px; + } +} + +@media (min-width: 1280px) { + .\!container { + max-width: 1280px !important; + } + + .container { + max-width: 1280px; + } +} + +@media (min-width: 1536px) { + .\!container { + max-width: 1536px !important; + } + + .container { + max-width: 1536px; + } +} + +.visible { + visibility: visible; +} + +.static { + position: static; +} + +.fixed { + position: fixed; +} + +.absolute { + position: absolute; +} + +.isolate { + isolation: isolate; +} + +.mx-auto { + margin-left: auto; + margin-right: auto; +} + +.my-4 { + margin-top: 1rem; + margin-bottom: 1rem; +} + +.mb-2 { + margin-bottom: 0.5rem; +} + +.mb-3 { + margin-bottom: 0.75rem; +} + +.mb-4 { + margin-bottom: 1rem; +} + +.mt-1 { + margin-top: 0.25rem; +} + +.mt-3 { + margin-top: 0.75rem; +} + +.mt-5 { + margin-top: 1.25rem; +} + +.block { + display: block; +} + +.flex { + display: flex; +} + +.inline-flex { + display: inline-flex; +} + +.table { + display: table; +} + +.grid { + display: grid; +} + +.hidden { + display: none; +} + +.h-10 { + height: 2.5rem; +} + +.h-11 { + height: 2.75rem; +} + +.h-20 { + height: 5rem; +} + +.h-4 { + height: 1rem; +} + +.h-5 { + height: 1.25rem; +} + +.h-6 { + height: 1.5rem; +} + +.h-9 { + height: 2.25rem; +} + +.h-screen { + height: 100vh; +} + +.w-24 { + width: 6rem; +} + +.w-4 { + width: 1rem; +} + +.w-5 { + width: 1.25rem; +} + +.w-6 { + width: 1.5rem; +} + +.w-9 { + width: 2.25rem; +} + +.w-\[320px\] { + width: 320px; +} + +.w-full { + width: 100%; +} + +.w-screen { + width: 100vw; +} + +.max-w-full { + max-width: 100%; +} + +.max-w-xl { + max-width: 36rem; +} + +.flex-1 { + flex: 1 1 0%; +} + +.shrink-0 { + flex-shrink: 0; +} + +.grow { + flex-grow: 1; +} + +.table-auto { + table-layout: auto; +} + +.transform { + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} + +.resize-none { + resize: none; +} + +.appearance-none { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; +} + +.flex-col { + flex-direction: column; +} + +.items-center { + align-items: center; +} + +.justify-center { + justify-content: center; +} + +.justify-between { + justify-content: space-between; +} + +.gap-1 { + gap: 0.25rem; +} + +.gap-2 { + gap: 0.5rem; +} + +.gap-3 { + gap: 0.75rem; +} + +.gap-4 { + gap: 1rem; +} + +.gap-5 { + gap: 1.25rem; +} + +.gap-6 { + gap: 1.5rem; +} + +.overflow-scroll { + overflow: scroll; +} + +.rounded-2xl { + border-radius: 1rem; +} + +.rounded-full { + border-radius: 9999px; +} + +.rounded-lg { + border-radius: 0.5rem; +} + +.rounded-xl { + border-radius: 0.75rem; +} + +.border { + border-width: 1px; +} + +.border-b { + border-bottom-width: 1px; +} + +.border-b-8 { + border-bottom-width: 8px; +} + +.border-primary { + --tw-border-opacity: 1; + border-color: rgb(225 227 234 / var(--tw-border-opacity, 1)); +} + +.border-secondary { + border-color: rgba(90, 65, 244, 1); +} + +.border-transparent { + border-color: transparent; +} + +.bg-background { + --tw-bg-opacity: 1; + background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); +} + +.bg-muted { + background-color: rgba(240, 240, 246, 1); +} + +.bg-primary { + background-color: rgba(90, 65, 244, 1); +} + +.bg-transparent { + background-color: transparent; +} + +.bg-white { + --tw-bg-opacity: 1; + background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); +} + +.p-3 { + padding: 0.75rem; +} + +.p-4 { + padding: 1rem; +} + +.p-6 { + padding: 1.5rem; +} + +.p-8 { + padding: 2rem; +} + +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} + +.px-3 { + padding-left: 0.75rem; + padding-right: 0.75rem; +} + +.py-1 { + padding-top: 0.25rem; + padding-bottom: 0.25rem; +} + +.text-left { + text-align: left; +} + +.text-center { + text-align: center; +} + +.font-sans { + font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; +} + +.text-base { + font-size: 1rem; + line-height: 1.5rem; +} + +.text-lg { + font-size: 1.125rem; + line-height: 1.75rem; +} + +.text-sm { + font-size: 0.875rem; + line-height: 1.25rem; +} + +.font-bold { + font-weight: 700; +} + +.font-medium { + font-weight: 500; +} + +.font-semibold { + font-weight: 600; +} + +.uppercase { + text-transform: uppercase; +} + +.lowercase { + text-transform: lowercase; +} + +.capitalize { + text-transform: capitalize; +} + +.text-foreground { + --tw-text-opacity: 1; + color: rgb(54 54 74 / var(--tw-text-opacity, 1)); +} + +.text-gray-500 { + --tw-text-opacity: 1; + color: rgb(107 114 128 / var(--tw-text-opacity, 1)); +} + +.text-muted { + --tw-text-opacity: 1; + color: rgb(129 132 152 / var(--tw-text-opacity, 1)); +} + +.text-primary { + color: rgba(90, 65, 244, 1); +} + +.text-red-500 { + --tw-text-opacity: 1; + color: rgb(239 68 68 / var(--tw-text-opacity, 1)); +} + +.text-white { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity, 1)); +} + +.antialiased { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.shadow { + --tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); + --tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); +} + +.shadow-primary { + --tw-shadow: 0px 10px 36px 0px rgba(64, 47, 132, 0.04); + --tw-shadow-colored: 0px 10px 36px 0px var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); +} + +.shadow-sm { + --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); + --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); +} + +.outline-none { + outline: 2px solid transparent; + outline-offset: 2px; +} + +.outline { + outline-style: solid; +} + +.ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); +} + +.blur { + --tw-blur: blur(8px); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); +} + +.invert { + --tw-invert: invert(100%); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); +} + +.filter { + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); +} + +.transition { + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} + +.transition-transform { + transition-property: transform; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} + +.duration-75 { + transition-duration: 75ms; +} + +.ease-in-out { + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); +} + +.data-\[state\=active\]\:text-primary[data-state="active"] > .bg-muted { + background-color: rgba(90, 65, 244, 0.1); +} + +.placeholder\:text-muted::-moz-placeholder { + --tw-text-opacity: 1; + color: rgb(129 132 152 / var(--tw-text-opacity, 1)); +} + +.placeholder\:text-muted::placeholder { + --tw-text-opacity: 1; + color: rgb(129 132 152 / var(--tw-text-opacity, 1)); +} + +.active\:translate-y-1:active { + --tw-translate-y: 0.25rem; + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} + +.disabled\:cursor-not-allowed:disabled { + cursor: not-allowed; +} + +.disabled\:text-muted:disabled { + --tw-text-opacity: 1; + color: rgb(129 132 152 / var(--tw-text-opacity, 1)); +} + +.disabled\:opacity-70:disabled { + opacity: 0.7; +} + +.data-\[state\=active\]\:border-b[data-state="active"] { + border-bottom-width: 1px; +} + +.data-\[state\=active\]\:border-secondary[data-state="active"] { + border-color: rgba(90, 65, 244, 1); +} + +.data-\[state\=checked\]\:border-secondary[data-state="checked"] { + border-color: rgba(90, 65, 244, 1); +} + +.data-\[state\=checked\]\:bg-primary[data-state="checked"] { + background-color: rgba(90, 65, 244, 1); +} + +.data-\[state\=active\]\:text-primary[data-state="active"] { + color: rgba(90, 65, 244, 1); +} diff --git a/extension/chrome/manifest.json b/extension/chrome/manifest.json index f831a64..3e8973e 100644 --- a/extension/chrome/manifest.json +++ b/extension/chrome/manifest.json @@ -1,36 +1,36 @@ { - "name": "Nostr Connect", - "description": "Nostr Signer Extension", - "version": "0.1.2", - "homepage_url": "https://github.com/reyamir/nostr-connect", - "manifest_version": 3, - "icons": { - "16": "icons/icon16.png", - "32": "icons/icon32.png", - "48": "icons/icon48.png", - "128": "icons/icon128.png" - }, - "options_page": "options.html", - "background": { - "service_worker": "background.build.js" - }, - "action": { - "default_title": "Nostr Connect", - "default_popup": "popup.html" - }, - "content_scripts": [ - { - "matches": [""], - "js": ["content-script.build.js"], - "all_frames": true - } - ], - "permissions": ["storage"], - "optional_permissions": ["notifications"], - "web_accessible_resources": [ - { - "resources": ["nostr-provider.js"], - "matches": ["https://*/*", "http://localhost:*/*"] - } - ] + "name": "Nostr Connect", + "description": "Nostr Signer Extension", + "version": "0.1.2", + "homepage_url": "https://github.com/reyamir/nostr-connect", + "manifest_version": 3, + "icons": { + "16": "icons/icon16.png", + "32": "icons/icon32.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + }, + "options_page": "options.html", + "background": { + "service_worker": "background.build.js" + }, + "action": { + "default_title": "Nostr Connect", + "default_popup": "popup.html" + }, + "content_scripts": [ + { + "matches": [""], + "js": ["content-script.build.js"], + "all_frames": true + } + ], + "permissions": ["storage"], + "optional_permissions": ["notifications"], + "web_accessible_resources": [ + { + "resources": ["nostr-provider.js"], + "matches": ["https://*/*", "http://localhost:*/*"] + } + ] } diff --git a/extension/common.js b/extension/common.js index 9b9185b..7f711fe 100644 --- a/extension/common.js +++ b/extension/common.js @@ -1,116 +1,118 @@ -import browser from 'webextension-polyfill' +import browser from "webextension-polyfill"; export const NO_PERMISSIONS_REQUIRED = { - replaceURL: true -} + replaceURL: true, +}; export const PERMISSION_NAMES = Object.fromEntries([ - ['getPublicKey', 'read your public key'], - ['getRelays', 'read your list of preferred relays'], - ['signEvent', 'sign events using your private key'], - ['nip04.encrypt', 'encrypt messages to peers'], - ['nip04.decrypt', 'decrypt messages from peers'] -]) + ["getPublicKey", "read your public key"], + ["getRelays", "read your list of preferred relays"], + ["signEvent", "sign events using your private key"], + ["nip04.encrypt", "encrypt messages to peers"], + ["nip04.decrypt", "decrypt messages from peers"], +]); function matchConditions(conditions, event) { - if (conditions?.kinds) { - if (event.kind in conditions.kinds) return true - else return false - } + if (conditions?.kinds) { + if (event.kind in conditions.kinds) return true; + else return false; + } - return true + return true; } export async function getPermissionStatus(host, type, event) { - let {policies} = await browser.storage.local.get('policies') + const { policies } = await browser.storage.local.get("policies"); - let answers = [true, false] - for (let i = 0; i < answers.length; i++) { - let accept = answers[i] - let {conditions} = policies?.[host]?.[accept]?.[type] || {} + const answers = [true, false]; + for (let i = 0; i < answers.length; i++) { + const accept = answers[i]; + const { conditions } = policies?.[host]?.[accept]?.[type] || {}; - if (conditions) { - if (type === 'signEvent') { - if (matchConditions(conditions, event)) { - return accept // may be true or false - } else { - // if this doesn't match we just continue so it will either match for the opposite answer (reject) - // or it will end up returning undefined at the end - continue - } - } else { - return accept // may be true or false - } - } - } + if (conditions) { + if (type === "signEvent") { + if (matchConditions(conditions, event)) { + return accept; // may be true or false + } else { + // if this doesn't match we just continue so it will either match for the opposite answer (reject) + // or it will end up returning undefined at the end + // biome-ignore lint/correctness/noUnnecessaryContinue: + continue; + } + } else { + return accept; // may be true or false + } + } + } - return undefined + return undefined; } export async function updatePermission(host, type, accept, conditions) { - let {policies = {}} = await browser.storage.local.get('policies') + const { policies = {} } = await browser.storage.local.get("policies"); - // if the new conditions is "match everything", override the previous - if (Object.keys(conditions).length === 0) { - conditions = {} - } else { - // if we already had a policy for this, merge the conditions - let existingConditions = policies[host]?.[accept]?.[type]?.conditions - if (existingConditions) { - if (existingConditions.kinds && conditions.kinds) { - Object.keys(existingConditions.kinds).forEach(kind => { - conditions.kinds[kind] = true - }) - } - } - } + // if the new conditions is "match everything", override the previous + if (Object.keys(conditions).length === 0) { + conditions = {}; + } else { + // if we already had a policy for this, merge the conditions + const existingConditions = policies[host]?.[accept]?.[type]?.conditions; - // if we have a reverse policy (accept / reject) that is exactly equal to this, remove it - let other = !accept - let reverse = policies?.[host]?.[other]?.[type] - if ( - reverse && - JSON.stringify(reverse.conditions) === JSON.stringify(conditions) - ) { - delete policies[host][other][type] - } + if (existingConditions) { + if (existingConditions.kinds && conditions.kinds) { + Object.keys(existingConditions.kinds).forEach((kind) => { + conditions.kinds[kind] = true; + }); + } + } + } - // insert our new policy - policies[host] = policies[host] || {} - policies[host][accept] = policies[host][accept] || {} - policies[host][accept][type] = { - conditions, // filter that must match the event (in case of signEvent) - created_at: Math.round(Date.now() / 1000) - } + // if we have a reverse policy (accept / reject) that is exactly equal to this, remove it + const other = !accept; + const reverse = policies?.[host]?.[other]?.[type]; + if ( + reverse && + JSON.stringify(reverse.conditions) === JSON.stringify(conditions) + ) { + delete policies[host][other][type]; + } - browser.storage.local.set({policies}) + // insert our new policy + policies[host] = policies[host] || {}; + policies[host][accept] = policies[host][accept] || {}; + policies[host][accept][type] = { + conditions, // filter that must match the event (in case of signEvent) + created_at: Math.round(Date.now() / 1000), + }; + + browser.storage.local.set({ policies }); } export async function removePermissions(host, accept, type) { - let {policies = {}} = await browser.storage.local.get('policies') - delete policies[host]?.[accept]?.[type] - browser.storage.local.set({policies}) + const { policies = {} } = await browser.storage.local.get("policies"); + delete policies[host]?.[accept]?.[type]; + browser.storage.local.set({ policies }); } export async function showNotification(host, answer, type, params) { - let ok = await browser.storage.local.get('notifications') - if (ok) { - let action = answer ? 'allowed' : 'denied' - browser.notifications.create(undefined, { - type: 'basic', - title: `${type} ${action} for ${host}`, - message: JSON.stringify( - params?.event - ? { - kind: params.event.kind, - content: params.event.content, - tags: params.event.tags - } - : params, - null, - 2 - ), - iconUrl: 'icons/48x48.png' - }) - } + const ok = await browser.storage.local.get("notifications"); + if (ok) { + const action = answer ? "allowed" : "denied"; + browser.notifications.create(undefined, { + type: "basic", + title: `${type} ${action} for ${host}`, + message: JSON.stringify( + params?.event + ? { + kind: params.event.kind, + content: params.event.content, + tags: params.event.tags, + } + : params, + null, + 2, + ), + iconUrl: "icons/48x48.png", + }); + } } diff --git a/extension/content-script.js b/extension/content-script.js index c67cd4c..d8f7d96 100644 --- a/extension/content-script.js +++ b/extension/content-script.js @@ -1,36 +1,37 @@ -import browser from 'webextension-polyfill' +import browser from "webextension-polyfill"; -const EXTENSION = 'nostrconnect' +const EXTENSION = "nostrconnect"; // inject the script that will provide window.nostr -let script = document.createElement('script') -script.setAttribute('async', 'false') -script.setAttribute('type', 'text/javascript') -script.setAttribute('src', browser.runtime.getURL('nostr-provider.js')) -document.head.appendChild(script) +const script = document.createElement("script"); +script.setAttribute("async", "false"); +script.setAttribute("type", "text/javascript"); +script.setAttribute("src", browser.runtime.getURL("nostr-provider.js")); +document.head.appendChild(script); // listen for messages from that script -window.addEventListener('message', async message => { - if (message.source !== window) return - if (!message.data) return - if (!message.data.params) return - if (message.data.ext !== EXTENSION) return +window.addEventListener("message", async (message) => { + if (message.source !== window) return; + if (!message.data) return; + if (!message.data.params) return; + if (message.data.ext !== EXTENSION) return; - // pass on to background - var response - try { - response = await browser.runtime.sendMessage({ - type: message.data.type, - params: message.data.params, - host: location.host - }) - } catch (error) { - response = {error} - } + // pass on to background + let response; - // return response - window.postMessage( - {id: message.data.id, ext: EXTENSION, response}, - message.origin - ) -}) + try { + response = await browser.runtime.sendMessage({ + type: message.data.type, + params: message.data.params, + host: location.host, + }); + } catch (error) { + response = { error }; + } + + // return response + window.postMessage( + { id: message.data.id, ext: EXTENSION, response }, + message.origin, + ); +}); diff --git a/extension/firefox/manifest.json b/extension/firefox/manifest.json index b786aca..a595cbc 100644 --- a/extension/firefox/manifest.json +++ b/extension/firefox/manifest.json @@ -1,35 +1,35 @@ { - "name": "Nostr Connect", - "description": "Nostr Signer Extension", - "version": "0.1.2", - "homepage_url": "https://github.com/reyamir/nostr-connect", - "manifest_version": 2, - "browser_specific_settings": { - "gecko": { - "id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}" - } - }, - "icons": { - "16": "icons/icon16.png", - "32": "icons/icon32.png", - "48": "icons/icon48.png", - "128": "icons/icon128.png" - }, - "options_page": "options.html", - "background": { - "scripts": ["background.build.js"] - }, - "browser_action": { - "default_title": "Nostr Connect", - "default_popup": "popup.html" - }, - "content_scripts": [ - { - "matches": [""], - "js": ["content-script.build.js"] - } - ], - "permissions": ["storage"], - "optional_permissions": ["notifications"], - "web_accessible_resources": ["nostr-provider.js"] + "name": "Nostr Connect", + "description": "Nostr Signer Extension", + "version": "0.1.2", + "homepage_url": "https://github.com/reyamir/nostr-connect", + "manifest_version": 2, + "browser_specific_settings": { + "gecko": { + "id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}" + } + }, + "icons": { + "16": "icons/icon16.png", + "32": "icons/icon32.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + }, + "options_page": "options.html", + "background": { + "scripts": ["background.build.js"] + }, + "browser_action": { + "default_title": "Nostr Connect", + "default_popup": "popup.html" + }, + "content_scripts": [ + { + "matches": [""], + "js": ["content-script.build.js"] + } + ], + "permissions": ["storage"], + "optional_permissions": ["notifications"], + "web_accessible_resources": ["nostr-provider.js"] } diff --git a/extension/icons.jsx b/extension/icons.jsx index 9e81a4f..58da6d8 100644 --- a/extension/icons.jsx +++ b/extension/icons.jsx @@ -1,87 +1,76 @@ -import React from 'react' +import React from "react"; export function LogoIcon() { - return ( - - - - - - - - - - - - - - - - - - - ) + return ( + + + + + + + + + + + + + + + + + + + ); } export function SettingsIcon(props) { - return ( - - - - - ) + return ( + + + + + ); } diff --git a/extension/nostr-provider.js b/extension/nostr-provider.js index 945b471..de31cd2 100644 --- a/extension/nostr-provider.js +++ b/extension/nostr-provider.js @@ -1,114 +1,108 @@ -const EXTENSION = 'nostrconnect' +const EXTENSION = "nostrconnect"; window.nostr = { - _requests: {}, - _pubkey: null, + _requests: {}, + _pubkey: null, - async getPublicKey() { - if (this._pubkey) return this._pubkey - this._pubkey = await this._call('getPublicKey', {}) - return this._pubkey - }, + async getPublicKey() { + if (this._pubkey) return this._pubkey; + this._pubkey = await this._call("getPublicKey", {}); + return this._pubkey; + }, - async signEvent(event) { - return this._call('signEvent', {event}) - }, + async signEvent(event) { + return this._call("signEvent", { event }); + }, - async getRelays() { - return this._call('getRelays', {}) - }, + async getRelays() { + return this._call("getRelays", {}); + }, - nip04: { - async encrypt(peer, plaintext) { - return window.nostr._call('nip04.encrypt', {peer, plaintext}) - }, + nip04: { + async encrypt(peer, plaintext) { + return window.nostr._call("nip04.encrypt", { peer, plaintext }); + }, - async decrypt(peer, ciphertext) { - return window.nostr._call('nip04.decrypt', {peer, ciphertext}) - } - }, + async decrypt(peer, ciphertext) { + return window.nostr._call("nip04.decrypt", { peer, ciphertext }); + }, + }, - _call(type, params) { - let id = Math.random().toString().slice(-4) - console.log( - '%c[nostrconnect:%c' + - id + - '%c]%c calling %c' + - type + - '%c with %c' + - JSON.stringify(params || {}), - 'background-color:#f1b912;font-weight:bold;color:white', - 'background-color:#f1b912;font-weight:bold;color:#a92727', - 'background-color:#f1b912;color:white;font-weight:bold', - 'color:auto', - 'font-weight:bold;color:#08589d;font-family:monospace', - 'color:auto', - 'font-weight:bold;color:#90b12d;font-family:monospace' - ) - return new Promise((resolve, reject) => { - this._requests[id] = {resolve, reject} - window.postMessage( - { - id, - ext: EXTENSION, - type, - params - }, - '*' - ) - }) - } -} + _call(type, params) { + const id = Math.random().toString().slice(-4); + console.log( + `%c[nostrconnect:%c${id}%c]%c calling %c${type}%c with %c${JSON.stringify(params || {})}`, + "background-color:#f1b912;font-weight:bold;color:white", + "background-color:#f1b912;font-weight:bold;color:#a92727", + "background-color:#f1b912;color:white;font-weight:bold", + "color:auto", + "font-weight:bold;color:#08589d;font-family:monospace", + "color:auto", + "font-weight:bold;color:#90b12d;font-family:monospace", + ); + return new Promise((resolve, reject) => { + this._requests[id] = { resolve, reject }; + window.postMessage( + { + id, + ext: EXTENSION, + type, + params, + }, + "*", + ); + }); + }, +}; -window.addEventListener('message', message => { - if ( - !message.data || - message.data.response === null || - message.data.response === undefined || - message.data.ext !== EXTENSION || - !window.nostr._requests[message.data.id] - ) - return +window.addEventListener("message", (message) => { + if ( + !message.data || + message.data.response === null || + message.data.response === undefined || + message.data.ext !== EXTENSION || + !window.nostr._requests[message.data.id] + ) + return; - if (message.data.response.error) { - let error = new Error( - `${EXTENSION}: ` + message.data.response.error.message - ) - error.stack = message.data.response.error.stack - window.nostr._requests[message.data.id].reject(error) - } else { - window.nostr._requests[message.data.id].resolve(message.data.response) - } + if (message.data.response.error) { + const error = new Error( + `${EXTENSION}: ${message.data.response.error.message}`, + ); + error.stack = message.data.response.error.stack; + window.nostr._requests[message.data.id].reject(error); + } else { + window.nostr._requests[message.data.id].resolve(message.data.response); + } - console.log( - '%c[nostrconnect:%c' + - message.data.id + - '%c]%c result: %c' + - JSON.stringify( - message?.data?.response || message?.data?.response?.error?.message || {} - ), - 'background-color:#f1b912;font-weight:bold;color:white', - 'background-color:#f1b912;font-weight:bold;color:#a92727', - 'background-color:#f1b912;color:white;font-weight:bold', - 'color:auto', - 'font-weight:bold;color:#08589d' - ) + console.log( + `%c[nostrconnect:%c${message.data.id}%c]%c result: %c${JSON.stringify( + message?.data?.response || message?.data?.response?.error?.message || {}, + )}`, + "background-color:#f1b912;font-weight:bold;color:white", + "background-color:#f1b912;font-weight:bold;color:#a92727", + "background-color:#f1b912;color:white;font-weight:bold", + "color:auto", + "font-weight:bold;color:#08589d", + ); - delete window.nostr._requests[message.data.id] -}) + delete window.nostr._requests[message.data.id]; +}); // hack to replace nostr:nprofile.../etc links with something else -let replacing = null -document.addEventListener('mousedown', replaceNostrSchemeLink) +let replacing = null; +document.addEventListener("mousedown", replaceNostrSchemeLink); async function replaceNostrSchemeLink(e) { - if (e.target.tagName !== 'A' || !e.target.href.startsWith('nostr:')) return - if (replacing === false) return + if (e.target.tagName !== "A" || !e.target.href.startsWith("nostr:")) return; + if (replacing === false) return; - let response = await window.nostr._call('replaceURL', {url: e.target.href}) - if (response === false) { - replacing = false - return - } + const response = await window.nostr._call("replaceURL", { + url: e.target.href, + }); + if (response === false) { + replacing = false; + return; + } - e.target.href = response + e.target.href = response; } diff --git a/extension/options.jsx b/extension/options.jsx index 96e489d..775e6a5 100644 --- a/extension/options.jsx +++ b/extension/options.jsx @@ -1,470 +1,480 @@ -import browser from 'webextension-polyfill' -import React, {useState, useCallback, useEffect} from 'react' -import {render} from 'react-dom' -import {generatePrivateKey, nip19} from 'nostr-tools' -import QRCode from 'react-qr-code' -import * as Tabs from '@radix-ui/react-tabs' -import {LogoIcon} from './icons' -import {removePermissions} from './common' -import * as Checkbox from '@radix-ui/react-checkbox' +import * as Checkbox from "@radix-ui/react-checkbox"; +import * as Tabs from "@radix-ui/react-tabs"; +import { generatePrivateKey, nip19 } from "nostr-tools"; +import React, { useState, useCallback, useEffect } from "react"; +import QRCode from "react-qr-code"; +import browser from "webextension-polyfill"; +import { removePermissions } from "./common"; +import { LogoIcon } from "./icons"; function Options() { - let [privKey, setPrivKey] = useState('') - let [relays, setRelays] = useState([]) - let [newRelayURL, setNewRelayURL] = useState('') - let [policies, setPermissions] = useState([]) - let [protocolHandler, setProtocolHandler] = useState('https://njump.me/{raw}') - let [hidingPrivateKey, hidePrivateKey] = useState(true) - let [showNotifications, setNotifications] = useState(false) - let [messages, setMessages] = useState([]) - let [handleNostrLinks, setHandleNostrLinks] = useState(false) - let [showProtocolHandlerHelp, setShowProtocolHandlerHelp] = useState(false) - let [unsavedChanges, setUnsavedChanges] = useState([]) + const [privKey, setPrivKey] = useState(""); + const [relays, setRelays] = useState([]); + const [newRelayURL, setNewRelayURL] = useState(""); + const [policies, setPermissions] = useState([]); + const [protocolHandler, setProtocolHandler] = useState( + "https://njump.me/{raw}", + ); + const [hidingPrivateKey, hidePrivateKey] = useState(true); + const [showNotifications, setNotifications] = useState(false); + const [messages, setMessages] = useState([]); + const [handleNostrLinks, setHandleNostrLinks] = useState(false); + const [showProtocolHandlerHelp, setShowProtocolHandlerHelp] = useState(false); + const [unsavedChanges, setUnsavedChanges] = useState([]); - const showMessage = useCallback(msg => { - messages.push(msg) - setMessages(messages) - setTimeout(() => setMessages([]), 3000) - }) + const showMessage = useCallback((msg) => { + messages.push(msg); + setMessages(messages); + setTimeout(() => setMessages([]), 3000); + }); - useEffect(() => { - browser.storage.local - .get(['private_key', 'relays', 'protocol_handler', 'notifications']) - .then(results => { - if (results.private_key) { - setPrivKey(nip19.nsecEncode(results.private_key)) - } - if (results.relays) { - let relaysList = [] - for (let url in results.relays) { - relaysList.push({ - url, - policy: results.relays[url] - }) - } - setRelays(relaysList) - } - if (results.protocol_handler) { - setProtocolHandler(results.protocol_handler) - setHandleNostrLinks(true) - setShowProtocolHandlerHelp(false) - } - if (results.notifications) { - setNotifications(true) - } - }) - }, []) + useEffect(() => { + browser.storage.local + .get(["private_key", "relays", "protocol_handler", "notifications"]) + .then((results) => { + if (results.private_key) { + setPrivKey(nip19.nsecEncode(results.private_key)); + } + if (results.relays) { + const relaysList = []; + for (const url in results.relays) { + relaysList.push({ + url, + policy: results.relays[url], + }); + } + setRelays(relaysList); + } + if (results.protocol_handler) { + setProtocolHandler(results.protocol_handler); + setHandleNostrLinks(true); + setShowProtocolHandlerHelp(false); + } + if (results.notifications) { + setNotifications(true); + } + }); + }, []); - useEffect(() => { - loadPermissions() - }, []) + useEffect(() => { + loadPermissions(); + }, []); - async function loadPermissions() { - let {policies = {}} = await browser.storage.local.get('policies') - let list = [] + async function loadPermissions() { + const { policies = {} } = await browser.storage.local.get("policies"); + const list = []; - Object.entries(policies).forEach(([host, accepts]) => { - Object.entries(accepts).forEach(([accept, types]) => { - Object.entries(types).forEach(([type, {conditions, created_at}]) => { - list.push({ - host, - type, - accept, - conditions, - created_at - }) - }) - }) - }) + // biome-ignore lint/complexity/noForEach: TODO: fix this + Object.entries(policies).forEach(([host, accepts]) => { + // biome-ignore lint/complexity/noForEach: TODO: fix this + Object.entries(accepts).forEach(([accept, types]) => { + // biome-ignore lint/complexity/noForEach: TODO: fix this + Object.entries(types).forEach(([type, { conditions, created_at }]) => { + list.push({ + host, + type, + accept, + conditions, + created_at, + }); + }); + }); + }); - setPermissions(list) - } + setPermissions(list); + } - return ( -
-
-
- -
-

Nostr Connect

-

Nostr signer

-
-
-
-
-
Private key:
-
-
- -
- {!privKey && ( - - )} - {privKey && hidingPrivateKey && ( - - )} - {privKey && !hidingPrivateKey && ( - - )} -
-
-
- {privKey && !isKeyValid() ? ( -

Private key is invalid!

- ) : ( -

- Your key is stored locally. The developer has no way of - seeing your keys. -

- )} -
- {!hidingPrivateKey && isKeyValid() && ( -
- -
- )} -
-
- - - - Relays - - {relays.length} - - - - Permissions - - {policies.length} - - - - -
-
Preferred Relays:
-
- {relays.map(({url, policy}, i) => ( -
- -
-
- - - - - - - - -
-
- - - - - - - - -
-
- -
- ))} -
- setNewRelayURL(e.target.value)} - onKeyDown={e => { - if (e.key === 'Enter') addNewRelay() - }} - placeholder="wss://" - className="flex-1 h-9 bg-transparent border px-3 py-1 border-primary rounded-lg placeholder:text-muted" - /> - -
-
-
-
- -
-
Permissions:
- {!policies.length ? ( -
- You haven't granted any permissions to any apps yet -
- ) : ( - - - - - - - - - - - - - {policies.map( - ({host, type, accept, conditions, created_at}) => ( - - - - - - - - - ) - )} - {!policies.length && ( - - {Array(5) - .fill('N/A') - .map((v, i) => ( - - ))} - - )} - -
- Domain - - Permission - - Answer - - Conditions - - Since -
{host}{type} - {accept === 'true' ? 'allow' : 'deny'} - - {conditions.kinds - ? `kinds: ${Object.keys(conditions.kinds).join( - ', ' - )}` - : 'always'} - - {new Date(created_at * 1000) - .toISOString() - .split('.')[0] - .split('T') - .join(' ')} - - -
{v}
- )} -
-
-
-
-
- - - - - - - - -
-
-
-
- -
Advanced
-
- - - -
-
-
-
- - - - - - - - -
- {handleNostrLinks && ( -
-
- - {!showProtocolHandlerHelp && ( - - )} -
- {showProtocolHandlerHelp && ( -
{`
+	return (
+		
+
+
+ +
+

Nostr Connect

+

Nostr signer

+
+
+
+
+
Private key:
+
+
+ +
+ {!privKey && ( + + )} + {privKey && hidingPrivateKey && ( + + )} + {privKey && !hidingPrivateKey && ( + + )} +
+
+
+ {privKey && !isKeyValid() ? ( +

Private key is invalid!

+ ) : ( +

+ Your key is stored locally. The developer has no way of + seeing your keys. +

+ )} +
+ {!hidingPrivateKey && isKeyValid() && ( +
+ +
+ )} +
+
+ + + + Relays + + {relays.length} + + + + Permissions + + {policies.length} + + + + +
+
Preferred Relays:
+
+ {relays.map(({ url, policy }, i) => ( +
+ +
+
+ + + + + + + + +
+
+ + + + + + + + +
+
+ +
+ ))} +
+ setNewRelayURL(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") addNewRelay(); + }} + placeholder="wss://" + className="flex-1 h-9 bg-transparent border px-3 py-1 border-primary rounded-lg placeholder:text-muted" + /> + +
+
+
+
+ +
+
Permissions:
+ {!policies.length ? ( +
+ You haven't granted any permissions to any apps yet +
+ ) : ( + + + + + + + + + + + + {policies.map( + ({ host, type, accept, conditions, created_at }) => ( + + + + + + + + + ), + )} + {!policies.length && ( + + {Array(5) + .fill("N/A") + .map((v) => ( + + ))} + + )} + +
+ Domain + + Permission + + Answer + + Conditions + + Since + +
{host}{type} + {accept === "true" ? "allow" : "deny"} + + {conditions.kinds + ? `kinds: ${Object.keys(conditions.kinds).join( + ", ", + )}` + : "always"} + + {new Date(created_at * 1000) + .toISOString() + .split(".")[0] + .split("T") + .join(" ")} + + +
{v}
+ )} +
+
+
+
+
+ + + + + + + + +
+
+
+
+ +
Advanced
+
+ + + +
+
+
+
+ + + + + + + + +
+ {handleNostrLinks && ( +
+
+ + {!showProtocolHandlerHelp && ( + + )} +
+ {showProtocolHandlerHelp && ( +
{`
 {raw} = anything after the colon, i.e. the full nip19 bech32 string
 {hex} = hex pubkey for npub or nprofile, hex event id for note or nevent
 {p_or_e} = "p" for npub or nprofile, "e" for note or nevent
@@ -479,198 +489,202 @@ examples:
   - https://snort.social/{raw}
   - https://nostr.band/{raw}
                 `}
- )} -
- )} -
-
-
-
- -
-
- ) + )} +
+ )} +
+
+
+
+ +
+
+ ); - async function handleKeyChange(e) { - let key = e.target.value.toLowerCase().trim() - setPrivKey(key) - addUnsavedChanges('private_key') - } + async function handleKeyChange(e) { + const key = e.target.value.toLowerCase().trim(); + setPrivKey(key); + addUnsavedChanges("private_key"); + } - async function generate() { - setPrivKey(nip19.nsecEncode(generatePrivateKey())) - addUnsavedChanges('private_key') - } + async function generate() { + setPrivKey(nip19.nsecEncode(generatePrivateKey())); + addUnsavedChanges("private_key"); + } - async function saveKey() { - if (!isKeyValid()) { - showMessage('PRIVATE KEY IS INVALID! did not save private key.') - return - } + async function saveKey() { + if (!isKeyValid()) { + showMessage("PRIVATE KEY IS INVALID! did not save private key."); + return; + } - let hexOrEmptyKey = privKey + let hexOrEmptyKey = privKey; - try { - let {type, data} = nip19.decode(privKey) - if (type === 'nsec') hexOrEmptyKey = data - } catch (_) {} + try { + const { type, data } = nip19.decode(privKey); + if (type === "nsec") hexOrEmptyKey = data; + } catch (_) {} - await browser.storage.local.set({ - private_key: hexOrEmptyKey - }) + await browser.storage.local.set({ + private_key: hexOrEmptyKey, + }); - if (hexOrEmptyKey !== '') { - setPrivKey(nip19.nsecEncode(hexOrEmptyKey)) - } + if (hexOrEmptyKey !== "") { + setPrivKey(nip19.nsecEncode(hexOrEmptyKey)); + } - showMessage('saved private key!') - } + showMessage("saved private key!"); + } - function isKeyValid() { - if (privKey === '') return true - if (privKey.match(/^[a-f0-9]{64}$/)) return true - try { - if (nip19.decode(privKey).type === 'nsec') return true - } catch (_) {} - return false - } + function isKeyValid() { + if (privKey === "") return true; + if (privKey.match(/^[a-f0-9]{64}$/)) return true; + try { + if (nip19.decode(privKey).type === "nsec") return true; + } catch (_) {} + return false; + } - function changeRelayURL(i, ev) { - setRelays([ - ...relays.slice(0, i), - {url: ev.target.value, policy: relays[i].policy}, - ...relays.slice(i + 1) - ]) - addUnsavedChanges('relays') - } + function changeRelayURL(i, ev) { + setRelays([ + ...relays.slice(0, i), + { url: ev.target.value, policy: relays[i].policy }, + ...relays.slice(i + 1), + ]); + addUnsavedChanges("relays"); + } - function toggleRelayPolicy(i, cat) { - setRelays([ - ...relays.slice(0, i), - { - url: relays[i].url, - policy: {...relays[i].policy, [cat]: !relays[i].policy[cat]} - }, - ...relays.slice(i + 1) - ]) - addUnsavedChanges('relays') - } + function toggleRelayPolicy(i, cat) { + setRelays([ + ...relays.slice(0, i), + { + url: relays[i].url, + policy: { ...relays[i].policy, [cat]: !relays[i].policy[cat] }, + }, + ...relays.slice(i + 1), + ]); + addUnsavedChanges("relays"); + } - function removeRelay(i) { - setRelays([...relays.slice(0, i), ...relays.slice(i + 1)]) - addUnsavedChanges('relays') - } + function removeRelay(i) { + setRelays([...relays.slice(0, i), ...relays.slice(i + 1)]); + addUnsavedChanges("relays"); + } - function addNewRelay() { - if (newRelayURL.trim() === '') return - if (!newRelayURL.startsWith('wss://')) return - relays.push({ - url: newRelayURL, - policy: {read: true, write: true} - }) - setRelays(relays) - addUnsavedChanges('relays') - setNewRelayURL('') - } + function addNewRelay() { + if (newRelayURL.trim() === "") return; + if (!newRelayURL.startsWith("wss://")) return; + relays.push({ + url: newRelayURL, + policy: { read: true, write: true }, + }); + setRelays(relays); + addUnsavedChanges("relays"); + setNewRelayURL(""); + } - async function handleRevoke(e) { - let {host, accept, type} = e.target.dataset - if ( - window.confirm( - `revoke all ${ - accept === 'true' ? 'accept' : 'deny' - } ${type} policies from ${host}?` - ) - ) { - await removePermissions(host, accept, type) - showMessage('removed policies') - loadPermissions() - } - } + async function handleRevoke(e) { + const { host, accept, type } = e.target.dataset; + if ( + window.confirm( + `revoke all ${ + accept === "true" ? "accept" : "deny" + } ${type} policies from ${host}?`, + ) + ) { + await removePermissions(host, accept, type); + showMessage("removed policies"); + loadPermissions(); + } + } - function handleNotifications() { - setNotifications(!showNotifications) - addUnsavedChanges('notifications') - if (!showNotifications) requestBrowserNotificationPermissions() - } + function handleNotifications() { + setNotifications(!showNotifications); + addUnsavedChanges("notifications"); + if (!showNotifications) requestBrowserNotificationPermissions(); + } - async function requestBrowserNotificationPermissions() { - let granted = await browser.permissions.request({ - permissions: ['notifications'] - }) - if (!granted) setNotifications(false) - } + async function requestBrowserNotificationPermissions() { + const granted = await browser.permissions.request({ + permissions: ["notifications"], + }); + if (!granted) setNotifications(false); + } - async function saveNotifications() { - await browser.storage.local.set({notifications: showNotifications}) - showMessage('saved notifications!') - } + async function saveNotifications() { + await browser.storage.local.set({ notifications: showNotifications }); + showMessage("saved notifications!"); + } - async function saveRelays() { - await browser.storage.local.set({ - relays: Object.fromEntries( - relays - .filter(({url}) => url.trim() !== '') - .map(({url, policy}) => [url.trim(), policy]) - ) - }) - showMessage('saved relays!') - } + async function saveRelays() { + await browser.storage.local.set({ + relays: Object.fromEntries( + relays + .filter(({ url }) => url.trim() !== "") + .map(({ url, policy }) => [url.trim(), policy]), + ), + }); + showMessage("saved relays!"); + } - function changeShowProtocolHandlerHelp() { - setShowProtocolHandlerHelp(true) - } + function changeShowProtocolHandlerHelp() { + setShowProtocolHandlerHelp(true); + } - function changeHandleNostrLinks() { - if (handleNostrLinks) { - setProtocolHandler('') - addUnsavedChanges('protocol_handler') - } else setShowProtocolHandlerHelp(true) - setHandleNostrLinks(!handleNostrLinks) - } + function changeHandleNostrLinks() { + if (handleNostrLinks) { + setProtocolHandler(""); + addUnsavedChanges("protocol_handler"); + } else setShowProtocolHandlerHelp(true); + setHandleNostrLinks(!handleNostrLinks); + } - function handleChangeProtocolHandler(e) { - setProtocolHandler(e.target.value) - addUnsavedChanges('protocol_handler') - } + function handleChangeProtocolHandler(e) { + setProtocolHandler(e.target.value); + addUnsavedChanges("protocol_handler"); + } - async function saveNostrProtocolHandlerSettings() { - await browser.storage.local.set({protocol_handler: protocolHandler}) - showMessage('saved protocol handler!') - } + async function saveNostrProtocolHandlerSettings() { + await browser.storage.local.set({ protocol_handler: protocolHandler }); + showMessage("saved protocol handler!"); + } - function addUnsavedChanges(section) { - if (!unsavedChanges.find(s => s === section)) { - unsavedChanges.push(section) - setUnsavedChanges(unsavedChanges) - } - } + function addUnsavedChanges(section) { + if (!unsavedChanges.find((s) => s === section)) { + unsavedChanges.push(section); + setUnsavedChanges(unsavedChanges); + } + } - async function saveChanges() { - for (let section of unsavedChanges) { - switch (section) { - case 'private_key': - await saveKey() - break - case 'relays': - await saveRelays() - break - case 'protocol_handler': - await saveNostrProtocolHandlerSettings() - break - case 'notifications': - await saveNotifications() - break - } - } - setUnsavedChanges([]) - } + async function saveChanges() { + for (const section of unsavedChanges) { + switch (section) { + case "private_key": + await saveKey(); + break; + case "relays": + await saveRelays(); + break; + case "protocol_handler": + await saveNostrProtocolHandlerSettings(); + break; + case "notifications": + await saveNotifications(); + break; + } + } + setUnsavedChanges([]); + } } -render(, document.getElementById('main')) +const container = document.getElementById("main"); +const root = createRoot(container); + +root.render(); diff --git a/extension/output/background.build.js b/extension/output/background.build.js index a4c3a97..3e13cbb 100644 --- a/extension/output/background.build.js +++ b/extension/output/background.build.js @@ -1,3341 +1,3533 @@ (() => { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __commonJS = (cb, mod2) => function __require() { - return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; - }; - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( - isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, - mod2 - )); + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __commonJS = (cb, mod2) => + function __require() { + return ( + mod2 || + (0, cb[__getOwnPropNames(cb)[0]])( + (mod2 = { exports: {} }).exports, + mod2, + ), + mod2.exports + ); + }; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if ((from && typeof from === "object") || typeof from === "function") { + for (const key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { + get: () => from[key], + enumerable: + !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, + }); + } + return to; + }; + var __toESM = (mod2, isNodeMode, target) => ( + (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}), + __copyProps( + isNodeMode || !mod2 || !mod2.__esModule + ? __defProp(target, "default", { value: mod2, enumerable: true }) + : target, + mod2, + ) + ); - // node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js - var require_browser_polyfill = __commonJS({ - "node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) { - (function(global, factory) { - if (typeof define === "function" && define.amd) { - define("webextension-polyfill", ["module"], factory); - } else if (typeof exports !== "undefined") { - factory(module); - } else { - var mod2 = { - exports: {} - }; - factory(mod2); - global.browser = mod2.exports; - } - })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports, function(module2) { - "use strict"; - if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) { - const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received."; - const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; - const wrapAPIs = (extensionAPIs) => { - const apiMetadata = { - "alarms": { - "clear": { - "minArgs": 0, - "maxArgs": 1 - }, - "clearAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "bookmarks": { - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getChildren": { - "minArgs": 1, - "maxArgs": 1 - }, - "getRecent": { - "minArgs": 1, - "maxArgs": 1 - }, - "getSubTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTree": { - "minArgs": 0, - "maxArgs": 0 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "browserAction": { - "disable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "enable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "getBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1 - }, - "getBadgeText": { - "minArgs": 1, - "maxArgs": 1 - }, - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "openPopup": { - "minArgs": 0, - "maxArgs": 0 - }, - "setBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setBadgeText": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "browsingData": { - "remove": { - "minArgs": 2, - "maxArgs": 2 - }, - "removeCache": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCookies": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeDownloads": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFormData": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeHistory": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeLocalStorage": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePasswords": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePluginData": { - "minArgs": 1, - "maxArgs": 1 - }, - "settings": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "commands": { - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "contextMenus": { - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "cookies": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAllCookieStores": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "devtools": { - "inspectedWindow": { - "eval": { - "minArgs": 1, - "maxArgs": 2, - "singleCallbackArg": false - } - }, - "panels": { - "create": { - "minArgs": 3, - "maxArgs": 3, - "singleCallbackArg": true - }, - "elements": { - "createSidebarPane": { - "minArgs": 1, - "maxArgs": 1 - } - } - } - }, - "downloads": { - "cancel": { - "minArgs": 1, - "maxArgs": 1 - }, - "download": { - "minArgs": 1, - "maxArgs": 1 - }, - "erase": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFileIcon": { - "minArgs": 1, - "maxArgs": 2 - }, - "open": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "pause": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFile": { - "minArgs": 1, - "maxArgs": 1 - }, - "resume": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "extension": { - "isAllowedFileSchemeAccess": { - "minArgs": 0, - "maxArgs": 0 - }, - "isAllowedIncognitoAccess": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "history": { - "addUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "deleteRange": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "getVisits": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "i18n": { - "detectLanguage": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAcceptLanguages": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "identity": { - "launchWebAuthFlow": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "idle": { - "queryState": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "management": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getSelf": { - "minArgs": 0, - "maxArgs": 0 - }, - "setEnabled": { - "minArgs": 2, - "maxArgs": 2 - }, - "uninstallSelf": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "notifications": { - "clear": { - "minArgs": 1, - "maxArgs": 1 - }, - "create": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPermissionLevel": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "pageAction": { - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "hide": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "permissions": { - "contains": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "request": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "runtime": { - "getBackgroundPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPlatformInfo": { - "minArgs": 0, - "maxArgs": 0 - }, - "openOptionsPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "requestUpdateCheck": { - "minArgs": 0, - "maxArgs": 0 - }, - "sendMessage": { - "minArgs": 1, - "maxArgs": 3 - }, - "sendNativeMessage": { - "minArgs": 2, - "maxArgs": 2 - }, - "setUninstallURL": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "sessions": { - "getDevices": { - "minArgs": 0, - "maxArgs": 1 - }, - "getRecentlyClosed": { - "minArgs": 0, - "maxArgs": 1 - }, - "restore": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "storage": { - "local": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "managed": { - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "sync": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - } - }, - "tabs": { - "captureVisibleTab": { - "minArgs": 0, - "maxArgs": 2 - }, - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "detectLanguage": { - "minArgs": 0, - "maxArgs": 1 - }, - "discard": { - "minArgs": 0, - "maxArgs": 1 - }, - "duplicate": { - "minArgs": 1, - "maxArgs": 1 - }, - "executeScript": { - "minArgs": 1, - "maxArgs": 2 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 0 - }, - "getZoom": { - "minArgs": 0, - "maxArgs": 1 - }, - "getZoomSettings": { - "minArgs": 0, - "maxArgs": 1 - }, - "goBack": { - "minArgs": 0, - "maxArgs": 1 - }, - "goForward": { - "minArgs": 0, - "maxArgs": 1 - }, - "highlight": { - "minArgs": 1, - "maxArgs": 1 - }, - "insertCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "query": { - "minArgs": 1, - "maxArgs": 1 - }, - "reload": { - "minArgs": 0, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "sendMessage": { - "minArgs": 2, - "maxArgs": 3 - }, - "setZoom": { - "minArgs": 1, - "maxArgs": 2 - }, - "setZoomSettings": { - "minArgs": 1, - "maxArgs": 2 - }, - "update": { - "minArgs": 1, - "maxArgs": 2 - } - }, - "topSites": { - "get": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "webNavigation": { - "getAllFrames": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFrame": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "webRequest": { - "handlerBehaviorChanged": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "windows": { - "create": { - "minArgs": 0, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 1 - }, - "getLastFocused": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - } - }; - if (Object.keys(apiMetadata).length === 0) { - throw new Error("api-metadata.json has not been included in browser-polyfill"); - } - class DefaultWeakMap extends WeakMap { - constructor(createItem, items = void 0) { - super(items); - this.createItem = createItem; - } - get(key) { - if (!this.has(key)) { - this.set(key, this.createItem(key)); - } - return super.get(key); - } - } - const isThenable = (value) => { - return value && typeof value === "object" && typeof value.then === "function"; - }; - const makeCallback = (promise, metadata) => { - return (...callbackArgs) => { - if (extensionAPIs.runtime.lastError) { - promise.reject(new Error(extensionAPIs.runtime.lastError.message)); - } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) { - promise.resolve(callbackArgs[0]); - } else { - promise.resolve(callbackArgs); - } - }; - }; - const pluralizeArguments = (numArgs) => numArgs == 1 ? "argument" : "arguments"; - const wrapAsyncFunction = (name, metadata) => { - return function asyncFunctionWrapper(target, ...args) { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - return new Promise((resolve, reject) => { - if (metadata.fallbackToNoCallback) { - try { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } catch (cbError) { - console.warn(`${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, cbError); - target[name](...args); - metadata.fallbackToNoCallback = false; - metadata.noCallback = true; - resolve(); - } - } else if (metadata.noCallback) { - target[name](...args); - resolve(); - } else { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } - }); - }; - }; - const wrapMethod = (target, method, wrapper) => { - return new Proxy(method, { - apply(targetMethod, thisObj, args) { - return wrapper.call(thisObj, target, ...args); - } - }); - }; - let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); - const wrapObject = (target, wrappers = {}, metadata = {}) => { - let cache = /* @__PURE__ */ Object.create(null); - let handlers = { - has(proxyTarget2, prop) { - return prop in target || prop in cache; - }, - get(proxyTarget2, prop, receiver) { - if (prop in cache) { - return cache[prop]; - } - if (!(prop in target)) { - return void 0; - } - let value = target[prop]; - if (typeof value === "function") { - if (typeof wrappers[prop] === "function") { - value = wrapMethod(target, target[prop], wrappers[prop]); - } else if (hasOwnProperty(metadata, prop)) { - let wrapper = wrapAsyncFunction(prop, metadata[prop]); - value = wrapMethod(target, target[prop], wrapper); - } else { - value = value.bind(target); - } - } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) { - value = wrapObject(value, wrappers[prop], metadata[prop]); - } else if (hasOwnProperty(metadata, "*")) { - value = wrapObject(value, wrappers[prop], metadata["*"]); - } else { - Object.defineProperty(cache, prop, { - configurable: true, - enumerable: true, - get() { - return target[prop]; - }, - set(value2) { - target[prop] = value2; - } - }); - return value; - } - cache[prop] = value; - return value; - }, - set(proxyTarget2, prop, value, receiver) { - if (prop in cache) { - cache[prop] = value; - } else { - target[prop] = value; - } - return true; - }, - defineProperty(proxyTarget2, prop, desc) { - return Reflect.defineProperty(cache, prop, desc); - }, - deleteProperty(proxyTarget2, prop) { - return Reflect.deleteProperty(cache, prop); - } - }; - let proxyTarget = Object.create(target); - return new Proxy(proxyTarget, handlers); - }; - const wrapEvent = (wrapperMap) => ({ - addListener(target, listener, ...args) { - target.addListener(wrapperMap.get(listener), ...args); - }, - hasListener(target, listener) { - return target.hasListener(wrapperMap.get(listener)); - }, - removeListener(target, listener) { - target.removeListener(wrapperMap.get(listener)); - } - }); - const onRequestFinishedWrappers = new DefaultWeakMap((listener) => { - if (typeof listener !== "function") { - return listener; - } - return function onRequestFinished(req) { - const wrappedReq = wrapObject( - req, - {}, - { - getContent: { - minArgs: 0, - maxArgs: 0 - } - } - ); - listener(wrappedReq); - }; - }); - let loggedSendResponseDeprecationWarning = false; - const onMessageWrappers = new DefaultWeakMap((listener) => { - if (typeof listener !== "function") { - return listener; - } - return function onMessage(message, sender, sendResponse) { - let didCallSendResponse = false; - let wrappedSendResponse; - let sendResponsePromise = new Promise((resolve) => { - wrappedSendResponse = function(response) { - if (!loggedSendResponseDeprecationWarning) { - console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack); - loggedSendResponseDeprecationWarning = true; - } - didCallSendResponse = true; - resolve(response); - }; - }); - let result; - try { - result = listener(message, sender, wrappedSendResponse); - } catch (err) { - result = Promise.reject(err); - } - const isResultThenable = result !== true && isThenable(result); - if (result !== true && !isResultThenable && !didCallSendResponse) { - return false; - } - const sendPromisedResult = (promise) => { - promise.then((msg) => { - sendResponse(msg); - }, (error) => { - let message2; - if (error && (error instanceof Error || typeof error.message === "string")) { - message2 = error.message; - } else { - message2 = "An unexpected error occurred"; - } - sendResponse({ - __mozWebExtensionPolyfillReject__: true, - message: message2 - }); - }).catch((err) => { - console.error("Failed to send onMessage rejected reply", err); - }); - }; - if (isResultThenable) { - sendPromisedResult(result); - } else { - sendPromisedResult(sendResponsePromise); - } - return true; - }; - }); - const wrappedSendMessageCallback = ({ - reject, - resolve - }, reply) => { - if (extensionAPIs.runtime.lastError) { - if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) { - resolve(); - } else { - reject(new Error(extensionAPIs.runtime.lastError.message)); - } - } else if (reply && reply.__mozWebExtensionPolyfillReject__) { - reject(new Error(reply.message)); - } else { - resolve(reply); - } - }; - const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - return new Promise((resolve, reject) => { - const wrappedCb = wrappedSendMessageCallback.bind(null, { - resolve, - reject - }); - args.push(wrappedCb); - apiNamespaceObj.sendMessage(...args); - }); - }; - const staticWrappers = { - devtools: { - network: { - onRequestFinished: wrapEvent(onRequestFinishedWrappers) - } - }, - runtime: { - onMessage: wrapEvent(onMessageWrappers), - onMessageExternal: wrapEvent(onMessageWrappers), - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 1, - maxArgs: 3 - }) - }, - tabs: { - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 2, - maxArgs: 3 - }) - } - }; - const settingMetadata = { - clear: { - minArgs: 1, - maxArgs: 1 - }, - get: { - minArgs: 1, - maxArgs: 1 - }, - set: { - minArgs: 1, - maxArgs: 1 - } - }; - apiMetadata.privacy = { - network: { - "*": settingMetadata - }, - services: { - "*": settingMetadata - }, - websites: { - "*": settingMetadata - } - }; - return wrapObject(extensionAPIs, staticWrappers, apiMetadata); - }; - if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) { - throw new Error("This script should only be loaded in a browser extension."); - } - module2.exports = wrapAPIs(chrome); - } else { - module2.exports = browser; - } - }); - } - }); + // node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js + var require_browser_polyfill = __commonJS({ + "node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"( + exports, + module, + ) { + ((global, factory) => { + if (typeof define === "function" && define.amd) { + define("webextension-polyfill", ["module"], factory); + } else if (typeof exports !== "undefined") { + factory(module); + } else { + var mod2 = { + exports: {}, + }; + factory(mod2); + global.browser = mod2.exports; + } + })( + typeof globalThis !== "undefined" + ? globalThis + : typeof self !== "undefined" + ? self + : exports, + (module2) => { + if ( + typeof browser === "undefined" || + Object.getPrototypeOf(browser) !== Object.prototype + ) { + const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = + "The message port closed before a response was received."; + const SEND_RESPONSE_DEPRECATION_WARNING = + "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; + const wrapAPIs = (extensionAPIs) => { + const apiMetadata = { + alarms: { + clear: { + minArgs: 0, + maxArgs: 1, + }, + clearAll: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + }, + bookmarks: { + create: { + minArgs: 1, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + getChildren: { + minArgs: 1, + maxArgs: 1, + }, + getRecent: { + minArgs: 1, + maxArgs: 1, + }, + getSubTree: { + minArgs: 1, + maxArgs: 1, + }, + getTree: { + minArgs: 0, + maxArgs: 0, + }, + move: { + minArgs: 2, + maxArgs: 2, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeTree: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + browserAction: { + disable: { + minArgs: 0, + maxArgs: 1, + fallbackToNoCallback: true, + }, + enable: { + minArgs: 0, + maxArgs: 1, + fallbackToNoCallback: true, + }, + getBadgeBackgroundColor: { + minArgs: 1, + maxArgs: 1, + }, + getBadgeText: { + minArgs: 1, + maxArgs: 1, + }, + getPopup: { + minArgs: 1, + maxArgs: 1, + }, + getTitle: { + minArgs: 1, + maxArgs: 1, + }, + openPopup: { + minArgs: 0, + maxArgs: 0, + }, + setBadgeBackgroundColor: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setBadgeText: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setIcon: { + minArgs: 1, + maxArgs: 1, + }, + setPopup: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setTitle: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + browsingData: { + remove: { + minArgs: 2, + maxArgs: 2, + }, + removeCache: { + minArgs: 1, + maxArgs: 1, + }, + removeCookies: { + minArgs: 1, + maxArgs: 1, + }, + removeDownloads: { + minArgs: 1, + maxArgs: 1, + }, + removeFormData: { + minArgs: 1, + maxArgs: 1, + }, + removeHistory: { + minArgs: 1, + maxArgs: 1, + }, + removeLocalStorage: { + minArgs: 1, + maxArgs: 1, + }, + removePasswords: { + minArgs: 1, + maxArgs: 1, + }, + removePluginData: { + minArgs: 1, + maxArgs: 1, + }, + settings: { + minArgs: 0, + maxArgs: 0, + }, + }, + commands: { + getAll: { + minArgs: 0, + maxArgs: 0, + }, + }, + contextMenus: { + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeAll: { + minArgs: 0, + maxArgs: 0, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + cookies: { + get: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 1, + maxArgs: 1, + }, + getAllCookieStores: { + minArgs: 0, + maxArgs: 0, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + devtools: { + inspectedWindow: { + eval: { + minArgs: 1, + maxArgs: 2, + singleCallbackArg: false, + }, + }, + panels: { + create: { + minArgs: 3, + maxArgs: 3, + singleCallbackArg: true, + }, + elements: { + createSidebarPane: { + minArgs: 1, + maxArgs: 1, + }, + }, + }, + }, + downloads: { + cancel: { + minArgs: 1, + maxArgs: 1, + }, + download: { + minArgs: 1, + maxArgs: 1, + }, + erase: { + minArgs: 1, + maxArgs: 1, + }, + getFileIcon: { + minArgs: 1, + maxArgs: 2, + }, + open: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + pause: { + minArgs: 1, + maxArgs: 1, + }, + removeFile: { + minArgs: 1, + maxArgs: 1, + }, + resume: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + show: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + extension: { + isAllowedFileSchemeAccess: { + minArgs: 0, + maxArgs: 0, + }, + isAllowedIncognitoAccess: { + minArgs: 0, + maxArgs: 0, + }, + }, + history: { + addUrl: { + minArgs: 1, + maxArgs: 1, + }, + deleteAll: { + minArgs: 0, + maxArgs: 0, + }, + deleteRange: { + minArgs: 1, + maxArgs: 1, + }, + deleteUrl: { + minArgs: 1, + maxArgs: 1, + }, + getVisits: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + }, + i18n: { + detectLanguage: { + minArgs: 1, + maxArgs: 1, + }, + getAcceptLanguages: { + minArgs: 0, + maxArgs: 0, + }, + }, + identity: { + launchWebAuthFlow: { + minArgs: 1, + maxArgs: 1, + }, + }, + idle: { + queryState: { + minArgs: 1, + maxArgs: 1, + }, + }, + management: { + get: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + getSelf: { + minArgs: 0, + maxArgs: 0, + }, + setEnabled: { + minArgs: 2, + maxArgs: 2, + }, + uninstallSelf: { + minArgs: 0, + maxArgs: 1, + }, + }, + notifications: { + clear: { + minArgs: 1, + maxArgs: 1, + }, + create: { + minArgs: 1, + maxArgs: 2, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + getPermissionLevel: { + minArgs: 0, + maxArgs: 0, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + pageAction: { + getPopup: { + minArgs: 1, + maxArgs: 1, + }, + getTitle: { + minArgs: 1, + maxArgs: 1, + }, + hide: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setIcon: { + minArgs: 1, + maxArgs: 1, + }, + setPopup: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setTitle: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + show: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + permissions: { + contains: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + request: { + minArgs: 1, + maxArgs: 1, + }, + }, + runtime: { + getBackgroundPage: { + minArgs: 0, + maxArgs: 0, + }, + getPlatformInfo: { + minArgs: 0, + maxArgs: 0, + }, + openOptionsPage: { + minArgs: 0, + maxArgs: 0, + }, + requestUpdateCheck: { + minArgs: 0, + maxArgs: 0, + }, + sendMessage: { + minArgs: 1, + maxArgs: 3, + }, + sendNativeMessage: { + minArgs: 2, + maxArgs: 2, + }, + setUninstallURL: { + minArgs: 1, + maxArgs: 1, + }, + }, + sessions: { + getDevices: { + minArgs: 0, + maxArgs: 1, + }, + getRecentlyClosed: { + minArgs: 0, + maxArgs: 1, + }, + restore: { + minArgs: 0, + maxArgs: 1, + }, + }, + storage: { + local: { + clear: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + managed: { + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + }, + sync: { + clear: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + }, + tabs: { + captureVisibleTab: { + minArgs: 0, + maxArgs: 2, + }, + create: { + minArgs: 1, + maxArgs: 1, + }, + detectLanguage: { + minArgs: 0, + maxArgs: 1, + }, + discard: { + minArgs: 0, + maxArgs: 1, + }, + duplicate: { + minArgs: 1, + maxArgs: 1, + }, + executeScript: { + minArgs: 1, + maxArgs: 2, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + getCurrent: { + minArgs: 0, + maxArgs: 0, + }, + getZoom: { + minArgs: 0, + maxArgs: 1, + }, + getZoomSettings: { + minArgs: 0, + maxArgs: 1, + }, + goBack: { + minArgs: 0, + maxArgs: 1, + }, + goForward: { + minArgs: 0, + maxArgs: 1, + }, + highlight: { + minArgs: 1, + maxArgs: 1, + }, + insertCSS: { + minArgs: 1, + maxArgs: 2, + }, + move: { + minArgs: 2, + maxArgs: 2, + }, + query: { + minArgs: 1, + maxArgs: 1, + }, + reload: { + minArgs: 0, + maxArgs: 2, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeCSS: { + minArgs: 1, + maxArgs: 2, + }, + sendMessage: { + minArgs: 2, + maxArgs: 3, + }, + setZoom: { + minArgs: 1, + maxArgs: 2, + }, + setZoomSettings: { + minArgs: 1, + maxArgs: 2, + }, + update: { + minArgs: 1, + maxArgs: 2, + }, + }, + topSites: { + get: { + minArgs: 0, + maxArgs: 0, + }, + }, + webNavigation: { + getAllFrames: { + minArgs: 1, + maxArgs: 1, + }, + getFrame: { + minArgs: 1, + maxArgs: 1, + }, + }, + webRequest: { + handlerBehaviorChanged: { + minArgs: 0, + maxArgs: 0, + }, + }, + windows: { + create: { + minArgs: 0, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 2, + }, + getAll: { + minArgs: 0, + maxArgs: 1, + }, + getCurrent: { + minArgs: 0, + maxArgs: 1, + }, + getLastFocused: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + }; + if (Object.keys(apiMetadata).length === 0) { + throw new Error( + "api-metadata.json has not been included in browser-polyfill", + ); + } + class DefaultWeakMap extends WeakMap { + constructor(createItem, items = void 0) { + super(items); + this.createItem = createItem; + } + get(key) { + if (!this.has(key)) { + this.set(key, this.createItem(key)); + } + return super.get(key); + } + } + const isThenable = (value) => { + return ( + value && + typeof value === "object" && + typeof value.then === "function" + ); + }; + const makeCallback = (promise, metadata) => { + return (...callbackArgs) => { + if (extensionAPIs.runtime.lastError) { + promise.reject( + new Error(extensionAPIs.runtime.lastError.message), + ); + } else if ( + metadata.singleCallbackArg || + (callbackArgs.length <= 1 && + metadata.singleCallbackArg !== false) + ) { + promise.resolve(callbackArgs[0]); + } else { + promise.resolve(callbackArgs); + } + }; + }; + const pluralizeArguments = (numArgs) => + numArgs == 1 ? "argument" : "arguments"; + const wrapAsyncFunction = (name, metadata) => { + return function asyncFunctionWrapper(target, ...args) { + if (args.length < metadata.minArgs) { + throw new Error( + `Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`, + ); + } + if (args.length > metadata.maxArgs) { + throw new Error( + `Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`, + ); + } + return new Promise((resolve, reject) => { + if (metadata.fallbackToNoCallback) { + try { + target[name]( + ...args, + makeCallback( + { + resolve, + reject, + }, + metadata, + ), + ); + } catch (cbError) { + console.warn( + `${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, + cbError, + ); + target[name](...args); + metadata.fallbackToNoCallback = false; + metadata.noCallback = true; + resolve(); + } + } else if (metadata.noCallback) { + target[name](...args); + resolve(); + } else { + target[name]( + ...args, + makeCallback( + { + resolve, + reject, + }, + metadata, + ), + ); + } + }); + }; + }; + const wrapMethod = (target, method, wrapper) => { + return new Proxy(method, { + apply(targetMethod, thisObj, args) { + return wrapper.call(thisObj, target, ...args); + }, + }); + }; + const hasOwnProperty = Function.call.bind( + Object.prototype.hasOwnProperty, + ); + const wrapObject = (target, wrappers = {}, metadata = {}) => { + const cache = /* @__PURE__ */ Object.create(null); + const handlers = { + has(proxyTarget2, prop) { + return prop in target || prop in cache; + }, + get(proxyTarget2, prop, receiver) { + if (prop in cache) { + return cache[prop]; + } + if (!(prop in target)) { + return void 0; + } + let value = target[prop]; + if (typeof value === "function") { + if (typeof wrappers[prop] === "function") { + value = wrapMethod( + target, + target[prop], + wrappers[prop], + ); + } else if (hasOwnProperty(metadata, prop)) { + const wrapper = wrapAsyncFunction(prop, metadata[prop]); + value = wrapMethod(target, target[prop], wrapper); + } else { + value = value.bind(target); + } + } else if ( + typeof value === "object" && + value !== null && + (hasOwnProperty(wrappers, prop) || + hasOwnProperty(metadata, prop)) + ) { + value = wrapObject(value, wrappers[prop], metadata[prop]); + } else if (hasOwnProperty(metadata, "*")) { + value = wrapObject(value, wrappers[prop], metadata["*"]); + } else { + Object.defineProperty(cache, prop, { + configurable: true, + enumerable: true, + get() { + return target[prop]; + }, + set(value2) { + target[prop] = value2; + }, + }); + return value; + } + cache[prop] = value; + return value; + }, + set(proxyTarget2, prop, value, receiver) { + if (prop in cache) { + cache[prop] = value; + } else { + target[prop] = value; + } + return true; + }, + defineProperty(proxyTarget2, prop, desc) { + return Reflect.defineProperty(cache, prop, desc); + }, + deleteProperty(proxyTarget2, prop) { + return Reflect.deleteProperty(cache, prop); + }, + }; + const proxyTarget = Object.create(target); + return new Proxy(proxyTarget, handlers); + }; + const wrapEvent = (wrapperMap) => ({ + addListener(target, listener, ...args) { + target.addListener(wrapperMap.get(listener), ...args); + }, + hasListener(target, listener) { + return target.hasListener(wrapperMap.get(listener)); + }, + removeListener(target, listener) { + target.removeListener(wrapperMap.get(listener)); + }, + }); + const onRequestFinishedWrappers = new DefaultWeakMap( + (listener) => { + if (typeof listener !== "function") { + return listener; + } + return function onRequestFinished(req) { + const wrappedReq = wrapObject( + req, + {}, + { + getContent: { + minArgs: 0, + maxArgs: 0, + }, + }, + ); + listener(wrappedReq); + }; + }, + ); + let loggedSendResponseDeprecationWarning = false; + const onMessageWrappers = new DefaultWeakMap((listener) => { + if (typeof listener !== "function") { + return listener; + } + return function onMessage(message, sender, sendResponse) { + let didCallSendResponse = false; + let wrappedSendResponse; + const sendResponsePromise = new Promise((resolve) => { + wrappedSendResponse = (response) => { + if (!loggedSendResponseDeprecationWarning) { + console.warn( + SEND_RESPONSE_DEPRECATION_WARNING, + new Error().stack, + ); + loggedSendResponseDeprecationWarning = true; + } + didCallSendResponse = true; + resolve(response); + }; + }); + let result; + try { + result = listener(message, sender, wrappedSendResponse); + } catch (err) { + result = Promise.reject(err); + } + const isResultThenable = + result !== true && isThenable(result); + if ( + result !== true && + !isResultThenable && + !didCallSendResponse + ) { + return false; + } + const sendPromisedResult = (promise) => { + promise + .then( + (msg) => { + sendResponse(msg); + }, + (error) => { + let message2; + if ( + error && + (error instanceof Error || + typeof error.message === "string") + ) { + message2 = error.message; + } else { + message2 = "An unexpected error occurred"; + } + sendResponse({ + __mozWebExtensionPolyfillReject__: true, + message: message2, + }); + }, + ) + .catch((err) => { + console.error( + "Failed to send onMessage rejected reply", + err, + ); + }); + }; + if (isResultThenable) { + sendPromisedResult(result); + } else { + sendPromisedResult(sendResponsePromise); + } + return true; + }; + }); + const wrappedSendMessageCallback = ( + { reject, resolve }, + reply, + ) => { + if (extensionAPIs.runtime.lastError) { + if ( + extensionAPIs.runtime.lastError.message === + CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE + ) { + resolve(); + } else { + reject(new Error(extensionAPIs.runtime.lastError.message)); + } + } else if (reply && reply.__mozWebExtensionPolyfillReject__) { + reject(new Error(reply.message)); + } else { + resolve(reply); + } + }; + const wrappedSendMessage = ( + name, + metadata, + apiNamespaceObj, + ...args + ) => { + if (args.length < metadata.minArgs) { + throw new Error( + `Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`, + ); + } + if (args.length > metadata.maxArgs) { + throw new Error( + `Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`, + ); + } + return new Promise((resolve, reject) => { + const wrappedCb = wrappedSendMessageCallback.bind(null, { + resolve, + reject, + }); + args.push(wrappedCb); + apiNamespaceObj.sendMessage(...args); + }); + }; + const staticWrappers = { + devtools: { + network: { + onRequestFinished: wrapEvent(onRequestFinishedWrappers), + }, + }, + runtime: { + onMessage: wrapEvent(onMessageWrappers), + onMessageExternal: wrapEvent(onMessageWrappers), + sendMessage: wrappedSendMessage.bind(null, "sendMessage", { + minArgs: 1, + maxArgs: 3, + }), + }, + tabs: { + sendMessage: wrappedSendMessage.bind(null, "sendMessage", { + minArgs: 2, + maxArgs: 3, + }), + }, + }; + const settingMetadata = { + clear: { + minArgs: 1, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }; + apiMetadata.privacy = { + network: { + "*": settingMetadata, + }, + services: { + "*": settingMetadata, + }, + websites: { + "*": settingMetadata, + }, + }; + return wrapObject(extensionAPIs, staticWrappers, apiMetadata); + }; + if ( + typeof chrome != "object" || + !chrome || + !chrome.runtime || + !chrome.runtime.id + ) { + throw new Error( + "This script should only be loaded in a browser extension.", + ); + } + module2.exports = wrapAPIs(chrome); + } else { + module2.exports = browser; + } + }, + ); + }, + }); - // extension/background.js - var import_webextension_polyfill2 = __toESM(require_browser_polyfill()); + // extension/background.js + var import_webextension_polyfill2 = __toESM(require_browser_polyfill()); - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/_assert.js - function number(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bool(b) { - if (typeof b !== "boolean") - throw new Error(`Expected boolean, not ${b}`); - } - function bytes(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number(hash3.outputLen); - number(hash3.blockLen); - } - function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); - } - function output(out, instance) { - bytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - var assert = { - number, - bool, - bytes, - hash, - exists, - output - }; - var assert_default = assert; + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/_assert.js + function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); + } + function bool(b) { + if (typeof b !== "boolean") throw new Error(`Expected boolean, not ${b}`); + } + function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error( + `Expected Uint8Array of length ${lengths}, not of length=${b.length}`, + ); + } + function hash(hash3) { + if (typeof hash3 !== "function" || typeof hash3.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number(hash3.outputLen); + number(hash3.blockLen); + } + function exists(instance, checkFinished = true) { + if (instance.destroyed) throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); + } + function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error( + `digestInto() expects output buffer of length at least ${min}`, + ); + } + } + var assert = { + number, + bool, + bytes, + hash, + exists, + output, + }; + var assert_default = assert; - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/crypto.js - var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/crypto.js + var crypto2 = + typeof globalThis === "object" && "crypto" in globalThis + ? globalThis.crypto + : void 0; - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/utils.js - var u8a = (a) => a instanceof Uint8Array; - var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - var rotr = (word, shift) => word << 32 - shift | word >>> shift; - var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE) - throw new Error("Non little-endian hardware is not supported"); - var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); - function bytesToHex(bytes3) { - if (!u8a(bytes3)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i = 0; i < bytes3.length; i++) { - hex2 += hexes[bytes3[i]]; - } - return hex2; - } - function hexToBytes(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i = 0; i < array.length; i++) { - const j = i * 2; - const hexByte = hex2.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i] = byte; - } - return array; - } - function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function toBytes(data) { - if (typeof data === "string") - data = utf8ToBytes(data); - if (!u8a(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - function concatBytes(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; - arrays.forEach((a) => { - if (!u8a(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad); - pad += a.length; - }); - return r; - } - var Hash = class { - clone() { - return this._cloneInto(); - } - }; - var isPlainObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]" && obj.constructor === Object; - function checkOpts(defaults, opts) { - if (opts !== void 0 && (typeof opts !== "object" || !isPlainObject(opts))) - throw new Error("Options should be object or undefined"); - const merged = Object.assign(defaults, opts); - return merged; - } - function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; - } - function randomBytes(bytesLength = 32) { - if (crypto2 && typeof crypto2.getRandomValues === "function") { - return crypto2.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); - } + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/utils.js + var u8a = (a) => a instanceof Uint8Array; + var createView = (arr) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + var rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); + var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; + if (!isLE) throw new Error("Non little-endian hardware is not supported"); + var hexes = Array.from({ length: 256 }, (v, i) => + i.toString(16).padStart(2, "0"), + ); + function bytesToHex(bytes3) { + if (!u8a(bytes3)) throw new Error("Uint8Array expected"); + let hex2 = ""; + for (let i = 0; i < bytes3.length; i++) { + hex2 += hexes[bytes3[i]]; + } + return hex2; + } + function hexToBytes(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + const len = hex2.length; + if (len % 2) + throw new Error( + "padded hex string expected, got unpadded hex of length " + len, + ); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex2.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error("Invalid byte sequence"); + array[i] = byte; + } + return array; + } + function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function toBytes(data) { + if (typeof data === "string") data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; + } + function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; + arrays.forEach((a) => { + if (!u8a(a)) throw new Error("Uint8Array expected"); + r.set(a, pad); + pad += a.length; + }); + return r; + } + var Hash = class { + clone() { + return this._cloneInto(); + } + }; + var isPlainObject = (obj) => + Object.prototype.toString.call(obj) === "[object Object]" && + obj.constructor === Object; + function checkOpts(defaults, opts) { + if (opts !== void 0 && (typeof opts !== "object" || !isPlainObject(opts))) + throw new Error("Options should be object or undefined"); + const merged = Object.assign(defaults, opts); + return merged; + } + function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; + } + function randomBytes(bytesLength = 32) { + if (crypto2 && typeof crypto2.getRandomValues === "function") { + return crypto2.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); + } - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/_sha2.js - function setBigUint64(view, byteOffset, value, isLE3) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE3); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE3 ? 4 : 0; - const l = isLE3 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE3); - view.setUint32(byteOffset + l, wl, isLE3); - } - var SHA2 = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE3) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - assert_default.exists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - assert_default.exists(this); - assert_default.output(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE3); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - }; + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/_sha2.js + function setBigUint64(view, byteOffset, value, isLE3) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE3); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number((value >> _32n2) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE3 ? 4 : 0; + const l = isLE3 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE3); + view.setUint32(byteOffset + l, wl, isLE3); + } + var SHA2 = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE3) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE3; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + assert_default.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + assert_default.exists(this); + assert_default.output(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE: isLE3 } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE3); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } + }; - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/sha256.js - var Chi = (a, b, c) => a & b ^ ~a & c; - var Maj = (a, b, c) => a & b ^ a & c ^ b & c; - var SHA256_K = new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]); - var IV = new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - var SHA256_W = new Uint32Array(64); - var SHA256 = class extends SHA2 { - constructor() { - super(64, 32, 8, false); - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } - }; - var SHA224 = class extends SHA256 { - constructor() { - super(); - this.A = 3238371032 | 0; - this.B = 914150663 | 0; - this.C = 812702999 | 0; - this.D = 4144912697 | 0; - this.E = 4290775857 | 0; - this.F = 1750603025 | 0; - this.G = 1694076839 | 0; - this.H = 3204075428 | 0; - this.outputLen = 28; - } - }; - var sha256 = wrapConstructor(() => new SHA256()); - var sha224 = wrapConstructor(() => new SHA224()); + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/sha256.js + var Chi = (a, b, c) => (a & b) ^ (~a & c); + var Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); + var SHA256_K = new Uint32Array([ + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, + 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, + 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, + 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, + 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, + 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, + 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, + 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, + 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, + 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, + 2428436474, 2756734187, 3204031479, 3329325298, + ]); + var IV = new Uint32Array([ + 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, + 528734635, 1541459225, + ]); + var SHA256_W = new Uint32Array(64); + var SHA256 = class extends SHA2 { + constructor() { + super(64, 32, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } + }; + var SHA224 = class extends SHA256 { + constructor() { + super(); + this.A = 3238371032 | 0; + this.B = 914150663 | 0; + this.C = 812702999 | 0; + this.D = 4144912697 | 0; + this.E = 4290775857 | 0; + this.F = 1750603025 | 0; + this.G = 1694076839 | 0; + this.H = 3204075428 | 0; + this.outputLen = 28; + } + }; + var sha256 = wrapConstructor(() => new SHA256()); + var sha224 = wrapConstructor(() => new SHA224()); - // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/utils.js - var utils_exports = {}; - __export(utils_exports, { - bitGet: () => bitGet, - bitLen: () => bitLen, - bitMask: () => bitMask, - bitSet: () => bitSet, - bytesToHex: () => bytesToHex2, - bytesToNumberBE: () => bytesToNumberBE, - bytesToNumberLE: () => bytesToNumberLE, - concatBytes: () => concatBytes2, - createHmacDrbg: () => createHmacDrbg, - ensureBytes: () => ensureBytes, - equalBytes: () => equalBytes, - hexToBytes: () => hexToBytes2, - hexToNumber: () => hexToNumber, - numberToBytesBE: () => numberToBytesBE, - numberToBytesLE: () => numberToBytesLE, - numberToHexUnpadded: () => numberToHexUnpadded, - numberToVarBytesBE: () => numberToVarBytesBE, - utf8ToBytes: () => utf8ToBytes2, - validateObject: () => validateObject - }); - var _0n = BigInt(0); - var _1n = BigInt(1); - var _2n = BigInt(2); - var u8a2 = (a) => a instanceof Uint8Array; - var hexes2 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); - function bytesToHex2(bytes3) { - if (!u8a2(bytes3)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i = 0; i < bytes3.length; i++) { - hex2 += hexes2[bytes3[i]]; - } - return hex2; - } - function numberToHexUnpadded(num) { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - } - function hexToNumber(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - return BigInt(hex2 === "" ? "0" : `0x${hex2}`); - } - function hexToBytes2(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i = 0; i < array.length; i++) { - const j = i * 2; - const hexByte = hex2.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i] = byte; - } - return array; - } - function bytesToNumberBE(bytes3) { - return hexToNumber(bytesToHex2(bytes3)); - } - function bytesToNumberLE(bytes3) { - if (!u8a2(bytes3)) - throw new Error("Uint8Array expected"); - return hexToNumber(bytesToHex2(Uint8Array.from(bytes3).reverse())); - } - function numberToBytesBE(n, len) { - return hexToBytes2(n.toString(16).padStart(len * 2, "0")); - } - function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); - } - function numberToVarBytesBE(n) { - return hexToBytes2(numberToHexUnpadded(n)); - } - function ensureBytes(title, hex2, expectedLength) { - let res; - if (typeof hex2 === "string") { - try { - res = hexToBytes2(hex2); - } catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`); - } - } else if (u8a2(hex2)) { - res = Uint8Array.from(hex2); - } else { - throw new Error(`${title} must be hex string or Uint8Array`); - } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; - } - function concatBytes2(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; - arrays.forEach((a) => { - if (!u8a2(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad); - pad += a.length; - }); - return r; - } - function equalBytes(b1, b2) { - if (b1.length !== b2.length) - return false; - for (let i = 0; i < b1.length; i++) - if (b1[i] !== b2[i]) - return false; - return true; - } - function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function bitLen(n) { - let len; - for (len = 0; n > _0n; n >>= _1n, len += 1) - ; - return len; - } - function bitGet(n, pos) { - return n >> BigInt(pos) & _1n; - } - var bitSet = (n, pos, value) => { - return n | (value ? _1n : _0n) << BigInt(pos); - }; - var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; - var u8n = (data) => new Uint8Array(data); - var u8fr = (arr) => Uint8Array.from(arr); - function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v = u8n(hashLen); - let k = u8n(hashLen); - let i = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); - const reseed = (seed = u8n()) => { - k = h(u8fr([0]), seed); - v = h(); - if (seed.length === 0) - return; - k = h(u8fr([1]), seed); - v = h(); - }; - const gen = () => { - if (i++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes2(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen()))) - reseed(); - reset(); - return res; - }; - return genUntil; - } - var validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) - }; - function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error(`Invalid validator "${type}", expected function`); - const val = object[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; - } + // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/utils.js + var utils_exports = {}; + __export(utils_exports, { + bitGet: () => bitGet, + bitLen: () => bitLen, + bitMask: () => bitMask, + bitSet: () => bitSet, + bytesToHex: () => bytesToHex2, + bytesToNumberBE: () => bytesToNumberBE, + bytesToNumberLE: () => bytesToNumberLE, + concatBytes: () => concatBytes2, + createHmacDrbg: () => createHmacDrbg, + ensureBytes: () => ensureBytes, + equalBytes: () => equalBytes, + hexToBytes: () => hexToBytes2, + hexToNumber: () => hexToNumber, + numberToBytesBE: () => numberToBytesBE, + numberToBytesLE: () => numberToBytesLE, + numberToHexUnpadded: () => numberToHexUnpadded, + numberToVarBytesBE: () => numberToVarBytesBE, + utf8ToBytes: () => utf8ToBytes2, + validateObject: () => validateObject, + }); + var _0n = BigInt(0); + var _1n = BigInt(1); + var _2n = BigInt(2); + var u8a2 = (a) => a instanceof Uint8Array; + var hexes2 = Array.from({ length: 256 }, (v, i) => + i.toString(16).padStart(2, "0"), + ); + function bytesToHex2(bytes3) { + if (!u8a2(bytes3)) throw new Error("Uint8Array expected"); + let hex2 = ""; + for (let i = 0; i < bytes3.length; i++) { + hex2 += hexes2[bytes3[i]]; + } + return hex2; + } + function numberToHexUnpadded(num) { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; + } + function hexToNumber(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + return BigInt(hex2 === "" ? "0" : `0x${hex2}`); + } + function hexToBytes2(hex2) { + if (typeof hex2 !== "string") + throw new Error("hex string expected, got " + typeof hex2); + const len = hex2.length; + if (len % 2) + throw new Error( + "padded hex string expected, got unpadded hex of length " + len, + ); + const array = new Uint8Array(len / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex2.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error("Invalid byte sequence"); + array[i] = byte; + } + return array; + } + function bytesToNumberBE(bytes3) { + return hexToNumber(bytesToHex2(bytes3)); + } + function bytesToNumberLE(bytes3) { + if (!u8a2(bytes3)) throw new Error("Uint8Array expected"); + return hexToNumber(bytesToHex2(Uint8Array.from(bytes3).reverse())); + } + function numberToBytesBE(n, len) { + return hexToBytes2(n.toString(16).padStart(len * 2, "0")); + } + function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); + } + function numberToVarBytesBE(n) { + return hexToBytes2(numberToHexUnpadded(n)); + } + function ensureBytes(title, hex2, expectedLength) { + let res; + if (typeof hex2 === "string") { + try { + res = hexToBytes2(hex2); + } catch (e) { + throw new Error( + `${title} must be valid hex string, got "${hex2}". Cause: ${e}`, + ); + } + } else if (u8a2(hex2)) { + res = Uint8Array.from(hex2); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; + } + function concatBytes2(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; + arrays.forEach((a) => { + if (!u8a2(a)) throw new Error("Uint8Array expected"); + r.set(a, pad); + pad += a.length; + }); + return r; + } + function equalBytes(b1, b2) { + if (b1.length !== b2.length) return false; + for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false; + return true; + } + function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function bitLen(n) { + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1); + return len; + } + function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; + } + var bitSet = (n, pos, value) => { + return n | ((value ? _1n : _0n) << BigInt(pos)); + }; + var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; + var u8n = (data) => new Uint8Array(data); + var u8fr = (arr) => Uint8Array.from(arr); + function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); + const reseed = (seed = u8n()) => { + k = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) return; + k = h(u8fr([1]), seed); + v = h(); + }; + const gen = () => { + if (i++ >= 1e3) throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes2(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen()))) reseed(); + reset(); + return res; + }; + return genUntil; + } + var validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => + typeof val === "function" && Number.isSafeInteger(val.outputLen), + }; + function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === void 0) return; + if (!checkVal(val, object)) { + throw new Error( + `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`, + ); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; + } - // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/modular.js - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - var _2n2 = BigInt(2); - var _3n = BigInt(3); - var _4n = BigInt(4); - var _5n = BigInt(5); - var _8n = BigInt(8); - var _9n = BigInt(9); - var _16n = BigInt(16); - function mod(a, b) { - const result = a % b; - return result >= _0n2 ? result : b + result; - } - function pow(num, power, modulo) { - if (modulo <= _0n2 || power < _0n2) - throw new Error("Expected power/modulo > 0"); - if (modulo === _1n2) - return _0n2; - let res = _1n2; - while (power > _0n2) { - if (power & _1n2) - res = res * num % modulo; - num = num * num % modulo; - power >>= _1n2; - } - return res; - } - function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; - } - function invert(number3, modulo) { - if (number3 === _0n2 || modulo <= _0n2) { - throw new Error(`invert: expected positive integers, got n=${number3} mod=${modulo}`); - } - let a = mod(number3, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd2 = b; - if (gcd2 !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); - } - function tonelliShanks(P) { - const legendreC = (P - _1n2) / _2n2; - let Q, S, Z; - for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) - ; - for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) - ; - if (S === 1) { - const p1div4 = (P + _1n2) / _4n; - return function tonelliFast(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - const Q1div2 = (Q + _1n2) / _2n2; - return function tonelliSlow(Fp2, n) { - if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r = S; - let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); - let x = Fp2.pow(n, Q1div2); - let b = Fp2.pow(n, Q); - while (!Fp2.eql(b, Fp2.ONE)) { - if (Fp2.eql(b, Fp2.ZERO)) - return Fp2.ZERO; - let m = 1; - for (let t2 = Fp2.sqr(b); m < r; m++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); - g = Fp2.sqr(ge2); - x = Fp2.mul(x, ge2); - b = Fp2.mul(b, g); - r = m; - } - return x; - }; - } - function FpSqrt(P) { - if (P % _4n === _3n) { - const p1div4 = (P + _1n2) / _4n; - return function sqrt3mod4(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _8n === _5n) { - const c1 = (P - _5n) / _8n; - return function sqrt5mod8(Fp2, n) { - const n2 = Fp2.mul(n, _2n2); - const v = Fp2.pow(n2, c1); - const nv = Fp2.mul(n, v); - const i = Fp2.mul(Fp2.mul(nv, _2n2), v); - const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _16n === _9n) { - } - return tonelliShanks(P); - } - var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" - ]; - function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); - } - function FpPow(f2, num, power) { - if (power < _0n2) - throw new Error("Expected power > 0"); - if (power === _0n2) - return f2.ONE; - if (power === _1n2) - return num; - let p = f2.ONE; - let d = num; - while (power > _0n2) { - if (power & _1n2) - p = f2.mul(p, d); - d = f2.sqr(d); - power >>= _1n2; - } - return p; - } - function FpInvertBatch(f2, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num, i) => { - if (f2.is0(num)) - return acc; - tmp[i] = acc; - return f2.mul(acc, num); - }, f2.ONE); - const inverted = f2.inv(lastMultiplied); - nums.reduceRight((acc, num, i) => { - if (f2.is0(num)) - return acc; - tmp[i] = f2.mul(acc, tmp[i]); - return f2.mul(acc, num); - }, inverted); - return tmp; - } - function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; - } - function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { - if (ORDER <= _0n2) - throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("Field lengths over 2048 bytes are not supported"); - const sqrtP = FpSqrt(ORDER); - const f2 = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n2, - ONE: _1n2, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n2 <= num && num < ORDER; - }, - is0: (num) => num === _0n2, - isOdd: (num) => (num & _1n2) === _1n2, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f2, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => sqrtP(f2, n)), - invertBatch: (lst) => FpInvertBatch(f2, lst), - cmov: (a, b, c) => c ? b : a, - toBytes: (num) => isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), - fromBytes: (bytes3) => { - if (bytes3.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes3.length}`); - return isLE3 ? bytesToNumberLE(bytes3) : bytesToNumberBE(bytes3); - } - }); - return Object.freeze(f2); - } - function hashToPrivateScalar(hash3, groupOrder, isLE3 = false) { - hash3 = ensureBytes("privateHash", hash3); - const hashLen = hash3.length; - const minLen = nLength(groupOrder).nByteLength + 8; - if (minLen < 24 || hashLen < minLen || hashLen > 1024) - throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); - const num = isLE3 ? bytesToNumberLE(hash3) : bytesToNumberBE(hash3); - return mod(num, groupOrder - _1n2) + _1n2; - } + // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/modular.js + var _0n2 = BigInt(0); + var _1n2 = BigInt(1); + var _2n2 = BigInt(2); + var _3n = BigInt(3); + var _4n = BigInt(4); + var _5n = BigInt(5); + var _8n = BigInt(8); + var _9n = BigInt(9); + var _16n = BigInt(16); + function mod(a, b) { + const result = a % b; + return result >= _0n2 ? result : b + result; + } + function pow(num, power, modulo) { + if (modulo <= _0n2 || power < _0n2) + throw new Error("Expected power/modulo > 0"); + if (modulo === _1n2) return _0n2; + let res = _1n2; + while (power > _0n2) { + if (power & _1n2) res = (res * num) % modulo; + num = (num * num) % modulo; + power >>= _1n2; + } + return res; + } + function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n2) { + res *= res; + res %= modulo; + } + return res; + } + function invert(number3, modulo) { + if (number3 === _0n2 || modulo <= _0n2) { + throw new Error( + `invert: expected positive integers, got n=${number3} mod=${modulo}`, + ); + } + let a = mod(number3, modulo); + let b = modulo; + let x = _0n2, + y = _1n2, + u = _1n2, + v = _0n2; + while (a !== _0n2) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + (b = a), (a = r), (x = u), (y = v), (u = m), (v = n); + } + const gcd2 = b; + if (gcd2 !== _1n2) throw new Error("invert: does not exist"); + return mod(x, modulo); + } + function tonelliShanks(P) { + const legendreC = (P - _1n2) / _2n2; + let Q, S, Z; + for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++); + for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++); + if (S === 1) { + const p1div4 = (P + _1n2) / _4n; + return function tonelliFast(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + const Q1div2 = (Q + _1n2) / _2n2; + return function tonelliSlow(Fp2, n) { + if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r = S; + let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); + let x = Fp2.pow(n, Q1div2); + let b = Fp2.pow(n, Q); + while (!Fp2.eql(b, Fp2.ONE)) { + if (Fp2.eql(b, Fp2.ZERO)) return Fp2.ZERO; + let m = 1; + for (let t2 = Fp2.sqr(b); m < r; m++) { + if (Fp2.eql(t2, Fp2.ONE)) break; + t2 = Fp2.sqr(t2); + } + const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); + g = Fp2.sqr(ge2); + x = Fp2.mul(x, ge2); + b = Fp2.mul(b, g); + r = m; + } + return x; + }; + } + function FpSqrt(P) { + if (P % _4n === _3n) { + const p1div4 = (P + _1n2) / _4n; + return function sqrt3mod4(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp2, n) { + const n2 = Fp2.mul(n, _2n2); + const v = Fp2.pow(n2, c1); + const nv = Fp2.mul(n, v); + const i = Fp2.mul(Fp2.mul(nv, _2n2), v); + const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P % _16n === _9n) { + } + return tonelliShanks(P); + } + var FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN", + ]; + function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger", + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); + } + function FpPow(f2, num, power) { + if (power < _0n2) throw new Error("Expected power > 0"); + if (power === _0n2) return f2.ONE; + if (power === _1n2) return num; + let p = f2.ONE; + let d = num; + while (power > _0n2) { + if (power & _1n2) p = f2.mul(p, d); + d = f2.sqr(d); + power >>= _1n2; + } + return p; + } + function FpInvertBatch(f2, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i) => { + if (f2.is0(num)) return acc; + tmp[i] = acc; + return f2.mul(acc, num); + }, f2.ONE); + const inverted = f2.inv(lastMultiplied); + nums.reduceRight((acc, num, i) => { + if (f2.is0(num)) return acc; + tmp[i] = f2.mul(acc, tmp[i]); + return f2.mul(acc, num); + }, inverted); + return tmp; + } + function nLength(n, nBitLength) { + const _nBitLength = + nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; + } + function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { + if (ORDER <= _0n2) throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("Field lengths over 2048 bytes are not supported"); + const sqrtP = FpSqrt(ORDER); + const f2 = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n2, + ONE: _1n2, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== "bigint") + throw new Error( + `Invalid field element: expected bigint, got ${typeof num}`, + ); + return _0n2 <= num && num < ORDER; + }, + is0: (num) => num === _0n2, + isOdd: (num) => (num & _1n2) === _1n2, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f2, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f2, n)), + invertBatch: (lst) => FpInvertBatch(f2, lst), + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => + isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), + fromBytes: (bytes3) => { + if (bytes3.length !== BYTES) + throw new Error( + `Fp.fromBytes: expected ${BYTES}, got ${bytes3.length}`, + ); + return isLE3 ? bytesToNumberLE(bytes3) : bytesToNumberBE(bytes3); + }, + }); + return Object.freeze(f2); + } + function hashToPrivateScalar(hash3, groupOrder, isLE3 = false) { + hash3 = ensureBytes("privateHash", hash3); + const hashLen = hash3.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error( + `hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`, + ); + const num = isLE3 ? bytesToNumberLE(hash3) : bytesToNumberBE(hash3); + return mod(num, groupOrder - _1n2) + _1n2; + } - // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/curve.js - var _0n3 = BigInt(0); - var _1n3 = BigInt(1); - function wNAF(c, bits) { - const constTimeNegate = (condition, item) => { - const neg = item.negate(); - return condition ? neg : item; - }; - const opts = (W) => { - const windows = Math.ceil(bits / W) + 1; - const windowSize = 2 ** (W - 1); - return { windows, windowSize }; - }; - return { - constTimeNegate, - unsafeLadder(elm, n) { - let p = c.ZERO; - let d = elm; - while (n > _0n3) { - if (n & _1n3) - p = p.add(d); - d = d.double(); - n >>= _1n3; - } - return p; - }, - precomputeWindow(elm, W) { - const { windows, windowSize } = opts(W); - const points = []; - let p = elm; - let base = p; - for (let window = 0; window < windows; window++) { - base = p; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - wNAF(W, precomputes, n) { - const { windows, windowSize } = opts(W); - let p = c.ZERO; - let f2 = c.BASE; - const mask = BigInt(2 ** W - 1); - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window = 0; window < windows; window++) { - const offset = window * windowSize; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n3; - } - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; - const cond1 = window % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - return { p, f: f2 }; - }, - wNAFCached(P, precomputesMap, n, transform) { - const W = P._WINDOW_SIZE || 1; - let comp = precomputesMap.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) { - precomputesMap.set(P, transform(comp)); - } - } - return this.wNAF(W, comp, n); - } - }; - } - function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); - } + // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/curve.js + var _0n3 = BigInt(0); + var _1n3 = BigInt(1); + function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; + const windowSize = 2 ** (W - 1); + return { windows, windowSize }; + }; + return { + constTimeNegate, + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n3) { + if (n & _1n3) p = p.add(d); + d = d.double(); + n >>= _1n3; + } + return p; + }, + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + wNAF(W, precomputes, n) { + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f2 = c.BASE; + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n3; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { p, f: f2 }; + }, + wNAFCached(P, precomputesMap, n, transform) { + const W = P._WINDOW_SIZE || 1; + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + }, + }; + } + function validateBasic(curve) { + validateField(curve.Fp); + validateObject( + curve, + { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field", + }, + { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger", + }, + ); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER }, + }); + } - // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/weierstrass.js - function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a } = opts; - if (endo) { - if (!Fp2.eql(a, Fp2.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); - } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); - } - } - return Object.freeze({ ...opts }); - } - var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; - var DER = { - Err: class DERErr extends Error { - constructor(m = "") { - super(m); - } - }, - _parseInt(data) { - const { Err: E } = DER; - if (data.length < 2 || data[0] !== 2) - throw new E("Invalid signature integer tag"); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E("Invalid signature integer: negative"); - if (res[0] === 0 && !(res[1] & 128)) - throw new E("Invalid signature integer: unnecessary leading zero"); - return { d: b2n(res), l: data.subarray(len + 2) }; - }, - toSig(hex2) { - const { Err: E } = DER; - const data = typeof hex2 === "string" ? h2b(hex2) : hex2; - if (!(data instanceof Uint8Array)) - throw new Error("ui8a expected"); - let l = data.length; - if (l < 2 || data[0] != 48) - throw new E("Invalid signature tag"); - if (data[1] !== l - 2) - throw new E("Invalid signature: incorrect length"); - const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E("Invalid signature: left bytes after parsing"); - return { r, s }; - }, - hexFromSig(sig) { - const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; - const h = (num) => { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - }; - const s = slice(h(sig.s)); - const r = slice(h(sig.r)); - const shl = s.length / 2; - const rhl = r.length / 2; - const sl = h(shl); - const rl = h(rhl); - return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - } - }; - var _0n4 = BigInt(0); - var _1n4 = BigInt(1); - var _2n3 = BigInt(2); - var _3n2 = BigInt(3); - var _4n2 = BigInt(4); - function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp: Fp2 } = CURVE; - const toBytes3 = CURVE.toBytes || ((c, point, isCompressed) => { - const a = point.toAffine(); - return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes3) => { - const tail = bytes3.subarray(1); - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - }); - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp2.sqr(x); - const x3 = Fp2.mul(x2, x); - return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); - } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num) { - return typeof num === "bigint" && _0n4 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error("Expected valid bigint: 0 < bigint < curve.n"); - } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; - if (lengths && typeof key !== "bigint") { - if (key instanceof Uint8Array) - key = bytesToHex2(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("Invalid key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; - try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); - } - if (wrapPrivateKey) - num = mod(num, n); - assertGE(num); - return num; - } - const pointPrecomputes = /* @__PURE__ */ new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point3)) - throw new Error("ProjectivePoint expected"); - } - class Point3 { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp2.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - } - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point3) - throw new Error("projective point not allowed"); - const is0 = (i) => Fp2.eql(i, Fp2.ZERO); - if (is0(x) && is0(y)) - return Point3.ZERO; - return new Point3(x, y, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine); - } - static fromHex(hex2) { - const P = Point3.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); - P.assertValidity(); - return P; - } - static fromPrivateKey(privateKey) { - return Point3.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - assertValidity() { - if (this.is0()) { - if (CURVE.allowInfinityPoint) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = this.toAffine(); - if (!Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y); - const right = weierstrassEquation(x); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!this.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U1 && U2; - } - negate() { - return new Point3(this.px, Fp2.neg(this.py), this.pz); - } - double() { - const { a, b } = CURVE; - const b3 = Fp2.mul(b, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point3(X3, Y3, Z3); - } - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n2); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point3(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point3.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { - const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine); - }); - } - multiplyUnsafe(n) { - const I = Point3.ZERO; - if (n === _0n4) - return I; - assertGE(n); - if (n === _1n4) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n4 || k2 > _0n4) { - if (k1 & _1n4) - k1p = k1p.add(d); - if (k2 & _1n4) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n4; - k2 >>= _1n4; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - multiply(scalar) { - assertGE(scalar); - let n = scalar; - let point, fake; - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f: f2 } = this.wNAF(n); - point = p; - fake = f2; - } - return Point3.normalizeZ([point, fake])[0]; - } - multiplyAndAddUnsafe(Q, a, b) { - const G = Point3.BASE; - const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? void 0 : sum; - } - toAffine(iz) { - const { px: x, py: y, pz: z } = this; - const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z); - const ax = Fp2.mul(x, iz); - const ay = Fp2.mul(y, iz); - const zz = Fp2.mul(z, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(Point3, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(Point3, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes3(Point3, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex2(this.toRawBytes(isCompressed)); - } - } - Point3.BASE = new Point3(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point3.ZERO = new Point3(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point3, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point3, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; - } - function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); - return Object.freeze({ lowS: true, ...opts }); - } - function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function isValidFieldElement(num) { - return _0n4 < num && num < Fp2.ORDER; - } - function modN2(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point3, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp2.toBytes(a.x); - const cat = concatBytes2; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); - } else { - return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); - } - }, - fromBytes(bytes3) { - const len = bytes3.length; - const head = bytes3[0]; - const tail = bytes3.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x); - let y = Fp2.sqrt(y2); - const isYOdd = (y & _1n4) === _1n4; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp2.neg(y); - return { x, y }; - } else if (len === uncompressedLen && head === 4) { - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); - } - } - }); - const numToNByteStr = (num) => bytesToHex2(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number3) { - const HALF = CURVE_ORDER >> _1n4; - return number3 > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN2(-s) : s; - } - const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - static fromCompact(hex2) { - const l = CURVE.nByteLength; - hex2 = ensureBytes("compactSignature", hex2, l * 2); - return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l)); - } - static fromDER(hex2) { - const { r, s } = DER.toSig(ensureBytes("DER", hex2)); - return new Signature(r, s); - } - assertValidity() { - if (!isWithinCurveOrder(this.r)) - throw new Error("r must be 0 < r < CURVE.n"); - if (!isWithinCurveOrder(this.s)) - throw new Error("s must be 0 < s < CURVE.n"); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R = Point3.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN2(-h * ir); - const u2 = modN2(s * ir); - const Q = Point3.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; - } - toDERRawBytes() { - return hexToBytes2(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - toCompactRawBytes() { - return hexToBytes2(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils3 = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - randomPrivateKey: () => { - const rand = CURVE.randomBytes(Fp2.BYTES + 8); - const num = hashToPrivateScalar(rand, CURVE_ORDER); - return numberToBytesBE(num, CURVE.nByteLength); - }, - precompute(windowSize = 8, point = Point3.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey2(privateKey, isCompressed = true) { - return Point3.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - const arr = item instanceof Uint8Array; - const str = typeof item === "string"; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point3) - return true; - return false; - } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b = Point3.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes3) { - const num = bytesToNumberBE(bytes3); - const delta = bytes3.length * 8 - CURVE.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes3) { - return modN2(bits2int(bytes3)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - if (!(_0n4 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - return numberToBytesBE(num, CURVE.nByteLength); - } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k) => k in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash3, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash3(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null) { - const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e, Fp2.BYTES)); - } - const seed = concatBytes2(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; - const ik = invN(k); - const q = Point3.BASE.multiply(k).toAffine(); - const r = modN2(q.x); - if (r === _0n4) - return; - const s = modN2(ik * modN2(m + r * d)); - if (s === _0n4) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; - } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); - } - Point3.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const { lowS, prehash } = opts; - let _sig = void 0; - let P; - try { - if (typeof sg === "string" || sg instanceof Uint8Array) { - try { - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig = Signature.fromCompact(sg); - } - } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { - const { r: r2, s: s2 } = sg; - _sig = new Signature(r2, s2); - } else { - throw new Error("PARSE"); - } - P = Point3.fromHex(publicKey); - } catch (error) { - if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; - } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is = invN(s); - const u1 = modN2(h * is); - const u2 = modN2(r * is); - const R = Point3.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); - if (!R) - return false; - const v = modN2(R.x); - return v === r; - } - return { - CURVE, - getPublicKey: getPublicKey2, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point3, - Signature, - utils: utils3 - }; - } + // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/weierstrass.js + function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject( + opts, + { + a: "field", + b: "field", + }, + { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function", + }, + ); + const { endo, Fp: Fp2, a } = opts; + if (endo) { + if (!Fp2.eql(a, Fp2.ZERO)) { + throw new Error( + "Endomorphism can only be defined for Koblitz curves that have a=0", + ); + } + if ( + typeof endo !== "object" || + typeof endo.beta !== "bigint" || + typeof endo.splitScalar !== "function" + ) { + throw new Error( + "Expected endomorphism with beta: bigint and splitScalar: function", + ); + } + } + return Object.freeze({ ...opts }); + } + var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; + var DER = { + Err: class DERErr extends Error { + constructor(m = "") { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 2) + throw new E("Invalid signature integer tag"); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E("Invalid signature integer: wrong length"); + if (res[0] & 128) throw new E("Invalid signature integer: negative"); + if (res[0] === 0 && !(res[1] & 128)) + throw new E("Invalid signature integer: unnecessary leading zero"); + return { d: b2n(res), l: data.subarray(len + 2) }; + }, + toSig(hex2) { + const { Err: E } = DER; + const data = typeof hex2 === "string" ? h2b(hex2) : hex2; + if (!(data instanceof Uint8Array)) throw new Error("ui8a expected"); + const l = data.length; + if (l < 2 || data[0] != 48) throw new E("Invalid signature tag"); + if (data[1] !== l - 2) throw new E("Invalid signature: incorrect length"); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E("Invalid signature: left bytes after parsing"); + return { r, s }; + }, + hexFromSig(sig) { + const slice = (s2) => (Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2); + const h = (num) => { + const hex2 = num.toString(16); + return hex2.length & 1 ? `0${hex2}` : hex2; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + }, + }; + var _0n4 = BigInt(0); + var _1n4 = BigInt(1); + var _2n3 = BigInt(2); + var _3n2 = BigInt(3); + var _4n2 = BigInt(4); + function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp: Fp2 } = CURVE; + const toBytes3 = + CURVE.toBytes || + ((c, point, isCompressed) => { + const a = point.toAffine(); + return concatBytes2( + Uint8Array.from([4]), + Fp2.toBytes(a.x), + Fp2.toBytes(a.y), + ); + }); + const fromBytes = + CURVE.fromBytes || + ((bytes3) => { + const tail = bytes3.subarray(1); + const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x, y }; + }); + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp2.sqr(x); + const x3 = Fp2.mul(x2, x); + return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); + } + if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num) { + return typeof num === "bigint" && _0n4 < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) + throw new Error("Expected valid bigint: 0 < bigint < curve.n"); + } + function normPrivateKeyToScalar(key) { + const { + allowedPrivateKeyLengths: lengths, + nByteLength, + wrapPrivateKey, + n, + } = CURVE; + if (lengths && typeof key !== "bigint") { + if (key instanceof Uint8Array) key = bytesToHex2(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("Invalid key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num; + try { + num = + typeof key === "bigint" + ? key + : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error( + `private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`, + ); + } + if (wrapPrivateKey) num = mod(num, n); + assertGE(num); + return num; + } + const pointPrecomputes = /* @__PURE__ */ new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point3)) + throw new Error("ProjectivePoint expected"); + } + class Point3 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp2.isValid(px)) throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) throw new Error("z required"); + } + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof Point3) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp2.eql(i, Fp2.ZERO); + if (is0(x) && is0(y)) return Point3.ZERO; + return new Point3(x, y, Fp2.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p) => p.pz)); + return points + .map((p, i) => p.toAffine(toInv[i])) + .map(Point3.fromAffine); + } + static fromHex(hex2) { + const P = Point3.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); + P.assertValidity(); + return P; + } + static fromPrivateKey(privateKey) { + return Point3.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + assertValidity() { + if (this.is0()) { + if (CURVE.allowInfinityPoint) return; + throw new Error("bad point: ZERO"); + } + const { x, y } = this.toAffine(); + if (!Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y); + const right = weierstrassEquation(x); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!this.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp2.isOdd) return !Fp2.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U1 && U2; + } + negate() { + return new Point3(this.px, Fp2.neg(this.py), this.pz); + } + double() { + const { a, b } = CURVE; + const b3 = Fp2.mul(b, _3n2); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, + Y3 = Fp2.ZERO, + Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + const t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point3(X3, Y3, Z3); + } + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, + Y3 = Fp2.ZERO, + Z3 = Fp2.ZERO; + const a = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n2); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point3(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point3.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { + const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); + return comp + .map((p, i) => p.toAffine(toInv[i])) + .map(Point3.fromAffine); + }); + } + multiplyUnsafe(n) { + const I = Point3.ZERO; + if (n === _0n4) return I; + assertGE(n); + if (n === _1n4) return this; + const { endo } = CURVE; + if (!endo) return wnaf.unsafeLadder(this, n); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n4 || k2 > _0n4) { + if (k1 & _1n4) k1p = k1p.add(d); + if (k2 & _1n4) k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n4; + k2 >>= _1n4; + } + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + multiply(scalar) { + assertGE(scalar); + const n = scalar; + let point, fake; + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f: f2 } = this.wNAF(n); + point = p; + fake = f2; + } + return Point3.normalizeZ([point, fake])[0]; + } + multiplyAndAddUnsafe(Q, a, b) { + const G = Point3.BASE; + const mul = (P, a2) => + a2 === _0n4 || a2 === _1n4 || !P.equals(G) + ? P.multiplyUnsafe(a2) + : P.multiply(a2); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? void 0 : sum; + } + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + if (iz == null) iz = is0 ? Fp2.ONE : Fp2.inv(z); + const ax = Fp2.mul(x, iz); + const ay = Fp2.mul(y, iz); + const zz = Fp2.mul(z, iz); + if (is0) return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) throw new Error("invZ was invalid"); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n4) return true; + if (isTorsionFree) return isTorsionFree(Point3, this); + throw new Error( + "isTorsionFree() has not been declared for the elliptic curve", + ); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n4) return this; + if (clearCofactor) return clearCofactor(Point3, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes3(Point3, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex2(this.toRawBytes(isCompressed)); + } + } + Point3.BASE = new Point3(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point3.ZERO = new Point3(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point3, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point3, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + }; + } + function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject( + opts, + { + hash: "hash", + hmac: "function", + randomBytes: "function", + }, + { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean", + }, + ); + return Object.freeze({ lowS: true, ...opts }); + } + function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp: Fp2, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function isValidFieldElement(num) { + return _0n4 < num && num < Fp2.ORDER; + } + function modN2(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { + ProjectivePoint: Point3, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp2.toBytes(a.x); + const cat = concatBytes2; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); + } else { + return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); + } + }, + fromBytes(bytes3) { + const len = bytes3.length; + const head = bytes3[0]; + const tail = bytes3.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x = bytesToNumberBE(tail); + if (!isValidFieldElement(x)) throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x); + let y = Fp2.sqrt(y2); + const isYOdd = (y & _1n4) === _1n4; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) y = Fp2.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 4) { + const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x, y }; + } else { + throw new Error( + `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`, + ); + } + }, + }); + const numToNByteStr = (num) => + bytesToHex2(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number3) { + const HALF = CURVE_ORDER >> _1n4; + return number3 > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + } + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + static fromCompact(hex2) { + const l = CURVE.nByteLength; + hex2 = ensureBytes("compactSignature", hex2, l * 2); + return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l)); + } + static fromDER(hex2) { + const { r, s } = DER.toSig(ensureBytes("DER", hex2)); + return new Signature(r, s); + } + assertValidity() { + if (!isWithinCurveOrder(this.r)) + throw new Error("r must be 0 < r < CURVE.n"); + if (!isWithinCurveOrder(this.s)) + throw new Error("s must be 0 < s < CURVE.n"); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp2.ORDER) throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R = Point3.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN2(-h * ir); + const u2 = modN2(s * ir); + const Q = Point3.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() + ? new Signature(this.r, modN2(-this.s), this.recovery) + : this; + } + toDERRawBytes() { + return hexToBytes2(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + toCompactRawBytes() { + return hexToBytes2(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils3 = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar, + randomPrivateKey: () => { + const rand = CURVE.randomBytes(Fp2.BYTES + 8); + const num = hashToPrivateScalar(rand, CURVE_ORDER); + return numberToBytesBE(num, CURVE.nByteLength); + }, + precompute(windowSize = 8, point = Point3.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + }, + }; + function getPublicKey2(privateKey, isCompressed = true) { + return Point3.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point3) return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) throw new Error("second arg must be public key"); + const b = Point3.fromHex(publicB); + return b + .multiply(normPrivateKeyToScalar(privateA)) + .toRawBytes(isCompressed); + } + const bits2int = + CURVE.bits2int || + ((bytes3) => { + const num = bytesToNumberBE(bytes3); + const delta = bytes3.length * 8 - CURVE.nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; + }); + const bits2int_modN = + CURVE.bits2int_modN || ((bytes3) => modN2(bits2int(bytes3))); + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num) { + if (typeof num !== "bigint") throw new Error("bigint expected"); + if (!(_0n4 <= num && num < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + return numberToBytesBE(num, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k) => k in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash3, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + if (prehash) msgHash = ensureBytes("prehashed msgHash", hash3(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null) { + const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e, Fp2.BYTES)); + } + const seed = concatBytes2(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!isWithinCurveOrder(k)) return; + const ik = invN(k); + const q = Point3.BASE.multiply(k).toAffine(); + const r = modN2(q.x); + if (r === _0n4) return; + const s = modN2(ik * modN2(m + r * d)); + if (s === _0n4) return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point3.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + const { lowS, prehash } = opts; + let _sig = void 0; + let P; + try { + if (typeof sg === "string" || sg instanceof Uint8Array) { + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) throw derError; + _sig = Signature.fromCompact(sg); + } + } else if ( + typeof sg === "object" && + typeof sg.r === "bigint" && + typeof sg.s === "bigint" + ) { + const { r: r2, s: s2 } = sg; + _sig = new Signature(r2, s2); + } else { + throw new Error("PARSE"); + } + P = Point3.fromHex(publicKey); + } catch (error) { + if (error.message === "PARSE") + throw new Error( + `signature must be Signature instance, Uint8Array or hex string`, + ); + return false; + } + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is = invN(s); + const u1 = modN2(h * is); + const u2 = modN2(r * is); + const R = Point3.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); + if (!R) return false; + const v = modN2(R.x); + return v === r; + } + return { + CURVE, + getPublicKey: getPublicKey2, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point3, + Signature, + utils: utils3, + }; + } - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/hmac.js - var HMAC = class extends Hash { - constructor(hash3, _key) { - super(); - this.finished = false; - this.destroyed = false; - assert_default.hash(hash3); - const key = toBytes(_key); - this.iHash = hash3.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash3.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54; - this.iHash.update(pad); - this.oHash = hash3.create(); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54 ^ 92; - this.oHash.update(pad); - pad.fill(0); - } - update(buf) { - assert_default.exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - assert_default.exists(this); - assert_default.bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }; - var hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest(); - hmac.create = (hash3, key) => new HMAC(hash3, key); + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/hmac.js + var HMAC = class extends Hash { + constructor(hash3, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert_default.hash(hash3); + const key = toBytes(_key); + this.iHash = hash3.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set( + key.length > blockLen ? hash3.create().update(key).digest() : key, + ); + for (let i = 0; i < pad.length; i++) pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash3.create(); + for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assert_default.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert_default.exists(this); + assert_default.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + var hmac = (hash3, key, message) => + new HMAC(hash3, key).update(message).digest(); + hmac.create = (hash3, key) => new HMAC(hash3, key); - // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/_shortw_utils.js - function getHash(hash3) { - return { - hash: hash3, - hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)), - randomBytes - }; - } - function createCurve(curveDef, defHash) { - const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) }); - return Object.freeze({ ...create(defHash), create }); - } + // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/_shortw_utils.js + function getHash(hash3) { + return { + hash: hash3, + hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)), + randomBytes, + }; + } + function createCurve(curveDef, defHash) { + const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) }); + return Object.freeze({ ...create(defHash), create }); + } - // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/secp256k1.js - var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); - var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); - var _1n5 = BigInt(1); - var _2n4 = BigInt(2); - var divNearest = (a, b) => (a + b / _2n4) / b; - function sqrtMod(y) { - const P = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n4, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n4, P); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; - } - var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); - var secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - } - }, sha256); - var _0n5 = BigInt(0); - var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; - var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; - var TAGGED_HASH_PREFIXES = {}; - function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes2(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256(concatBytes2(tagP, ...messages)); - } - var pointToBytes = (point) => point.toRawBytes(true).slice(1); - var numTo32b = (n) => numberToBytesBE(n, 32); - var modP = (x) => mod(x, secp256k1P); - var modN = (x) => mod(x, secp256k1N); - var Point = secp256k1.ProjectivePoint; - var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); - function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; - } - function lift_x(x) { - if (!fe(x)) - throw new Error("bad x: need 0 < x < p"); - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); - let y = sqrtMod(c); - if (y % _2n4 !== _0n5) - y = modP(-y); - const p = new Point(x, y, _1n5); - p.assertValidity(); - return p; - } - function challenge(...args) { - return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); - } - function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; - } - function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const k_ = modN(bytesToNumberBE(rand)); - if (k_ === _0n5) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; - } - function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); - try { - const P = lift_x(bytesToNumberBE(pub)); - const r = bytesToNumberBE(sig.subarray(0, 32)); - if (!fe(r)) - return false; - const s = bytesToNumberBE(sig.subarray(32, 64)); - if (!ge(s)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); - const R = GmulAdd(P, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; - } - } - var schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } - }))(); + // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/secp256k1.js + var secp256k1P = BigInt( + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", + ); + var secp256k1N = BigInt( + "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", + ); + var _1n5 = BigInt(1); + var _2n4 = BigInt(2); + var divNearest = (a, b) => (a + b / _2n4) / b; + function sqrtMod(y) { + const P = secp256k1P; + const _3n3 = BigInt(3), + _6n = BigInt(6), + _11n = BigInt(11), + _22n = BigInt(22); + const _23n = BigInt(23), + _44n = BigInt(44), + _88n = BigInt(88); + const b2 = (y * y * y) % P; + const b3 = (b2 * b2 * y) % P; + const b6 = (pow2(b3, _3n3, P) * b3) % P; + const b9 = (pow2(b6, _3n3, P) * b3) % P; + const b11 = (pow2(b9, _2n4, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n3, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n4, P); + if (!Fp.eql(Fp.sqr(root), y)) throw new Error("Cannot find square root"); + return root; + } + var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); + var secp256k1 = createCurve( + { + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + Gx: BigInt( + "55066263022277343669578718895168534326250603453777594175500187360389116729240", + ), + Gy: BigInt( + "32670510020758816978083085130507043184471273380659243275938904335757337482424", + ), + h: BigInt(1), + lowS: true, + endo: { + beta: BigInt( + "0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", + ), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, + sha256, + ); + var _0n5 = BigInt(0); + var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; + var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; + var TAGGED_HASH_PREFIXES = {}; + function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === void 0) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes2(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes2(tagP, ...messages)); + } + var pointToBytes = (point) => point.toRawBytes(true).slice(1); + var numTo32b = (n) => numberToBytesBE(n, 32); + var modP = (x) => mod(x, secp256k1P); + var modN = (x) => mod(x, secp256k1N); + var Point = secp256k1.ProjectivePoint; + var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); + function schnorrGetExtPubKey(priv) { + const d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + const p = Point.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar, bytes: pointToBytes(p) }; + } + function lift_x(x) { + if (!fe(x)) throw new Error("bad x: need 0 < x < p"); + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); + let y = sqrtMod(c); + if (y % _2n4 !== _0n5) y = modP(-y); + const p = new Point(x, y, _1n5); + p.assertValidity(); + return p; + } + function challenge(...args) { + return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); + } + function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; + } + function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m); + const k_ = modN(bytesToNumberBE(rand)); + if (k_ === _0n5) throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + if (!schnorrVerify(sig, m, px)) + throw new Error("sign: Invalid signature produced"); + return sig; + } + function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P = lift_x(bytesToNumberBE(pub)); + const r = bytesToNumberBE(sig.subarray(0, 32)); + if (!fe(r)) return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); + if (!ge(s)) return false; + const e = challenge(numTo32b(r), pointToBytes(P), m); + const R = GmulAdd(P, s, modN(-e)); + if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; + return true; + } catch (error) { + return false; + } + } + var schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod, + }, + }))(); - // node_modules/.pnpm/@scure+base@1.1.1/node_modules/@scure/base/lib/esm/index.js - function assertNumber(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`Wrong integer: ${n}`); - } - function chain(...args) { - const wrap = (a, b) => (c) => a(b(c)); - const encode = Array.from(args).reverse().reduce((acc, i) => acc ? wrap(acc, i.encode) : i.encode, void 0); - const decode2 = args.reduce((acc, i) => acc ? wrap(acc, i.decode) : i.decode, void 0); - return { encode, decode: decode2 }; - } - function alphabet(alphabet2) { - return { - encode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("alphabet.encode input should be an array of numbers"); - return digits.map((i) => { - assertNumber(i); - if (i < 0 || i >= alphabet2.length) - throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet2.length})`); - return alphabet2[i]; - }); - }, - decode: (input) => { - if (!Array.isArray(input) || input.length && typeof input[0] !== "string") - throw new Error("alphabet.decode input should be array of strings"); - return input.map((letter) => { - if (typeof letter !== "string") - throw new Error(`alphabet.decode: not string element=${letter}`); - const index = alphabet2.indexOf(letter); - if (index === -1) - throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`); - return index; - }); - } - }; - } - function join(separator = "") { - if (typeof separator !== "string") - throw new Error("join separator should be string"); - return { - encode: (from) => { - if (!Array.isArray(from) || from.length && typeof from[0] !== "string") - throw new Error("join.encode input should be array of strings"); - for (let i of from) - if (typeof i !== "string") - throw new Error(`join.encode: non-string input=${i}`); - return from.join(separator); - }, - decode: (to) => { - if (typeof to !== "string") - throw new Error("join.decode input should be string"); - return to.split(separator); - } - }; - } - function padding(bits, chr = "=") { - assertNumber(bits); - if (typeof chr !== "string") - throw new Error("padding chr should be string"); - return { - encode(data) { - if (!Array.isArray(data) || data.length && typeof data[0] !== "string") - throw new Error("padding.encode input should be array of strings"); - for (let i of data) - if (typeof i !== "string") - throw new Error(`padding.encode: non-string input=${i}`); - while (data.length * bits % 8) - data.push(chr); - return data; - }, - decode(input) { - if (!Array.isArray(input) || input.length && typeof input[0] !== "string") - throw new Error("padding.encode input should be array of strings"); - for (let i of input) - if (typeof i !== "string") - throw new Error(`padding.decode: non-string input=${i}`); - let end = input.length; - if (end * bits % 8) - throw new Error("Invalid padding: string should have whole number of bytes"); - for (; end > 0 && input[end - 1] === chr; end--) { - if (!((end - 1) * bits % 8)) - throw new Error("Invalid padding: string has too much padding"); - } - return input.slice(0, end); - } - }; - } - function normalize(fn) { - if (typeof fn !== "function") - throw new Error("normalize fn should be function"); - return { encode: (from) => from, decode: (to) => fn(to) }; - } - function convertRadix(data, from, to) { - if (from < 2) - throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); - if (to < 2) - throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); - if (!Array.isArray(data)) - throw new Error("convertRadix: data should be array"); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data); - digits.forEach((d) => { - assertNumber(d); - if (d < 0 || d >= from) - throw new Error(`Wrong integer: ${d}`); - }); - while (true) { - let carry = 0; - let done = true; - for (let i = pos; i < digits.length; i++) { - const digit = digits[i]; - const digitBase = from * carry + digit; - if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) { - throw new Error("convertRadix: carry overflow"); - } - carry = digitBase % to; - digits[i] = Math.floor(digitBase / to); - if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!digits[i]) - pos = i; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i = 0; i < data.length - 1 && data[i] === 0; i++) - res.push(0); - return res.reverse(); - } - var gcd = (a, b) => !b ? a : gcd(b, a % b); - var radix2carry = (from, to) => from + (to - gcd(from, to)); - function convertRadix2(data, from, to, padding2) { - if (!Array.isArray(data)) - throw new Error("convertRadix2: data should be array"); - if (from <= 0 || from > 32) - throw new Error(`convertRadix2: wrong from=${from}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry(from, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); - } - let carry = 0; - let pos = 0; - const mask = 2 ** to - 1; - const res = []; - for (const n of data) { - assertNumber(n); - if (n >= 2 ** from) - throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); - carry = carry << from | n; - if (pos + from > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); - pos += from; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - carry &= 2 ** pos - 1; - } - carry = carry << to - pos & mask; - if (!padding2 && pos >= from) - throw new Error("Excess padding"); - if (!padding2 && carry) - throw new Error(`Non-zero padding: ${carry}`); - if (padding2 && pos > 0) - res.push(carry >>> 0); - return res; - } - function radix(num) { - assertNumber(num); - return { - encode: (bytes3) => { - if (!(bytes3 instanceof Uint8Array)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix(Array.from(bytes3), 2 ** 8, num); - }, - decode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("radix.decode input should be array of strings"); - return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); - } - }; - } - function radix2(bits, revPadding = false) { - assertNumber(bits); - if (bits <= 0 || bits > 32) - throw new Error("radix2: bits should be in (0..32]"); - if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) - throw new Error("radix2: carry overflow"); - return { - encode: (bytes3) => { - if (!(bytes3 instanceof Uint8Array)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix2(Array.from(bytes3), 8, bits, !revPadding); - }, - decode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("radix2.decode input should be array of strings"); - return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); - } - }; - } - function unsafeWrapper(fn) { - if (typeof fn !== "function") - throw new Error("unsafeWrapper fn should be function"); - return function(...args) { - try { - return fn.apply(null, args); - } catch (e) { - } - }; - } - function checksum(len, fn) { - assertNumber(len); - if (typeof fn !== "function") - throw new Error("checksum fn should be function"); - return { - encode(data) { - if (!(data instanceof Uint8Array)) - throw new Error("checksum.encode: input should be Uint8Array"); - const checksum2 = fn(data).slice(0, len); - const res = new Uint8Array(data.length + len); - res.set(data); - res.set(checksum2, data.length); - return res; - }, - decode(data) { - if (!(data instanceof Uint8Array)) - throw new Error("checksum.decode: input should be Uint8Array"); - const payload = data.slice(0, -len); - const newChecksum = fn(payload).slice(0, len); - const oldChecksum = data.slice(-len); - for (let i = 0; i < len; i++) - if (newChecksum[i] !== oldChecksum[i]) - throw new Error("Invalid checksum"); - return payload; - } - }; - } - var utils = { alphabet, chain, checksum, radix, radix2, join, padding }; - var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join("")); - var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join("")); - var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join("")); - var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); - var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join("")); - var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join("")); - var genBase58 = (abc) => chain(radix(58), alphabet(abc), join("")); - var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); - var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; - var base58xmr = { - encode(data) { - let res = ""; - for (let i = 0; i < data.length; i += 8) { - const block = data.subarray(i, i + 8); - res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); - } - return res; - }, - decode(str) { - let res = []; - for (let i = 0; i < str.length; i += 11) { - const slice = str.slice(i, i + 11); - const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); - const block = base58.decode(slice); - for (let j = 0; j < block.length - blockLen; j++) { - if (block[j] !== 0) - throw new Error("base58xmr: wrong padding"); - } - res = res.concat(Array.from(block.slice(block.length - blockLen))); - } - return Uint8Array.from(res); - } - }; - var base58check = (sha2562) => chain(checksum(4, (data) => sha2562(sha2562(data))), base58); - var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join("")); - var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; - function bech32Polymod(pre) { - const b = pre >> 25; - let chk = (pre & 33554431) << 5; - for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { - if ((b >> i & 1) === 1) - chk ^= POLYMOD_GENERATORS[i]; - } - return chk; - } - function bechChecksum(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i = 0; i < len; i++) { - const c = prefix.charCodeAt(i); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod(chk) ^ c >> 5; - } - chk = bech32Polymod(chk); - for (let i = 0; i < len; i++) - chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31; - for (let v of words) - chk = bech32Polymod(chk) ^ v; - for (let i = 0; i < 6; i++) - chk = bech32Polymod(chk); - chk ^= encodingConst; - return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); - } - function genBech32(encoding) { - const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; - const _words = radix2(5); - const fromWords = _words.decode; - const toWords = _words.encode; - const fromWordsUnsafe = unsafeWrapper(fromWords); - function encode(prefix, words, limit = 90) { - if (typeof prefix !== "string") - throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); - if (!Array.isArray(words) || words.length && typeof words[0] !== "number") - throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); - const actualLength = prefix.length + 7 + words.length; - if (limit !== false && actualLength > limit) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); - prefix = prefix.toLowerCase(); - return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; - } - function decode2(str, limit = 90) { - if (typeof str !== "string") - throw new Error(`bech32.decode input should be string, not ${typeof str}`); - if (str.length < 8 || limit !== false && str.length > limit) - throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); - const lowered = str.toLowerCase(); - if (str !== lowered && str !== str.toUpperCase()) - throw new Error(`String must be lowercase or uppercase`); - str = lowered; - const sepIndex = str.lastIndexOf("1"); - if (sepIndex === 0 || sepIndex === -1) - throw new Error(`Letter "1" must be present between prefix and data only`); - const prefix = str.slice(0, sepIndex); - const _words2 = str.slice(sepIndex + 1); - if (_words2.length < 6) - throw new Error("Data must be at least 6 characters long"); - const words = BECH_ALPHABET.decode(_words2).slice(0, -6); - const sum = bechChecksum(prefix, words, ENCODING_CONST); - if (!_words2.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper(decode2); - function decodeToBytes(str) { - const { prefix, words } = decode2(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - return { encode, decode: decode2, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; - } - var bech32 = genBech32("bech32"); - var bech32m = genBech32("bech32m"); - var utf8 = { - encode: (data) => new TextDecoder().decode(data), - decode: (str) => new TextEncoder().encode(str) - }; - var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => { - if (typeof s !== "string" || s.length % 2) - throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); - return s.toLowerCase(); - })); - var CODERS = { - utf8, - hex, - base16, - base32, - base64, - base64url, - base58, - base58xmr - }; - var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`; + // node_modules/.pnpm/@scure+base@1.1.1/node_modules/@scure/base/lib/esm/index.js + function assertNumber(n) { + if (!Number.isSafeInteger(n)) throw new Error(`Wrong integer: ${n}`); + } + function chain(...args) { + const wrap = (a, b) => (c) => a(b(c)); + const encode = Array.from(args) + .reverse() + .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), void 0); + const decode2 = args.reduce( + (acc, i) => (acc ? wrap(acc, i.decode) : i.decode), + void 0, + ); + return { encode, decode: decode2 }; + } + function alphabet(alphabet2) { + return { + encode: (digits) => { + if ( + !Array.isArray(digits) || + (digits.length && typeof digits[0] !== "number") + ) + throw new Error( + "alphabet.encode input should be an array of numbers", + ); + return digits.map((i) => { + assertNumber(i); + if (i < 0 || i >= alphabet2.length) + throw new Error( + `Digit index outside alphabet: ${i} (alphabet: ${alphabet2.length})`, + ); + return alphabet2[i]; + }); + }, + decode: (input) => { + if ( + !Array.isArray(input) || + (input.length && typeof input[0] !== "string") + ) + throw new Error("alphabet.decode input should be array of strings"); + return input.map((letter) => { + if (typeof letter !== "string") + throw new Error(`alphabet.decode: not string element=${letter}`); + const index = alphabet2.indexOf(letter); + if (index === -1) + throw new Error( + `Unknown letter: "${letter}". Allowed: ${alphabet2}`, + ); + return index; + }); + }, + }; + } + function join(separator = "") { + if (typeof separator !== "string") + throw new Error("join separator should be string"); + return { + encode: (from) => { + if ( + !Array.isArray(from) || + (from.length && typeof from[0] !== "string") + ) + throw new Error("join.encode input should be array of strings"); + for (const i of from) + if (typeof i !== "string") + throw new Error(`join.encode: non-string input=${i}`); + return from.join(separator); + }, + decode: (to) => { + if (typeof to !== "string") + throw new Error("join.decode input should be string"); + return to.split(separator); + }, + }; + } + function padding(bits, chr = "=") { + assertNumber(bits); + if (typeof chr !== "string") + throw new Error("padding chr should be string"); + return { + encode(data) { + if ( + !Array.isArray(data) || + (data.length && typeof data[0] !== "string") + ) + throw new Error("padding.encode input should be array of strings"); + for (const i of data) + if (typeof i !== "string") + throw new Error(`padding.encode: non-string input=${i}`); + while ((data.length * bits) % 8) data.push(chr); + return data; + }, + decode(input) { + if ( + !Array.isArray(input) || + (input.length && typeof input[0] !== "string") + ) + throw new Error("padding.encode input should be array of strings"); + for (const i of input) + if (typeof i !== "string") + throw new Error(`padding.decode: non-string input=${i}`); + let end = input.length; + if ((end * bits) % 8) + throw new Error( + "Invalid padding: string should have whole number of bytes", + ); + for (; end > 0 && input[end - 1] === chr; end--) { + if (!(((end - 1) * bits) % 8)) + throw new Error("Invalid padding: string has too much padding"); + } + return input.slice(0, end); + }, + }; + } + function normalize(fn) { + if (typeof fn !== "function") + throw new Error("normalize fn should be function"); + return { encode: (from) => from, decode: (to) => fn(to) }; + } + function convertRadix(data, from, to) { + if (from < 2) + throw new Error( + `convertRadix: wrong from=${from}, base cannot be less than 2`, + ); + if (to < 2) + throw new Error( + `convertRadix: wrong to=${to}, base cannot be less than 2`, + ); + if (!Array.isArray(data)) + throw new Error("convertRadix: data should be array"); + if (!data.length) return []; + let pos = 0; + const res = []; + const digits = Array.from(data); + digits.forEach((d) => { + assertNumber(d); + if (d < 0 || d >= from) throw new Error(`Wrong integer: ${d}`); + }); + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < digits.length; i++) { + const digit = digits[i]; + const digitBase = from * carry + digit; + if ( + !Number.isSafeInteger(digitBase) || + (from * carry) / from !== carry || + digitBase - digit !== from * carry + ) { + throw new Error("convertRadix: carry overflow"); + } + carry = digitBase % to; + digits[i] = Math.floor(digitBase / to); + if ( + !Number.isSafeInteger(digits[i]) || + digits[i] * to + carry !== digitBase + ) + throw new Error("convertRadix: carry overflow"); + if (!done) continue; + else if (!digits[i]) pos = i; + else done = false; + } + res.push(carry); + if (done) break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0); + return res.reverse(); + } + var gcd = (a, b) => (!b ? a : gcd(b, a % b)); + var radix2carry = (from, to) => from + (to - gcd(from, to)); + function convertRadix2(data, from, to, padding2) { + if (!Array.isArray(data)) + throw new Error("convertRadix2: data should be array"); + if (from <= 0 || from > 32) + throw new Error(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error( + `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`, + ); + } + let carry = 0; + let pos = 0; + const mask = 2 ** to - 1; + const res = []; + for (const n of data) { + assertNumber(n); + if (n >= 2 ** from) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error( + `convertRadix2: carry overflow pos=${pos} from=${from}`, + ); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + carry &= 2 ** pos - 1; + } + carry = (carry << (to - pos)) & mask; + if (!padding2 && pos >= from) throw new Error("Excess padding"); + if (!padding2 && carry) throw new Error(`Non-zero padding: ${carry}`); + if (padding2 && pos > 0) res.push(carry >>> 0); + return res; + } + function radix(num) { + assertNumber(num); + return { + encode: (bytes3) => { + if (!(bytes3 instanceof Uint8Array)) + throw new Error("radix.encode input should be Uint8Array"); + return convertRadix(Array.from(bytes3), 2 ** 8, num); + }, + decode: (digits) => { + if ( + !Array.isArray(digits) || + (digits.length && typeof digits[0] !== "number") + ) + throw new Error("radix.decode input should be array of strings"); + return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); + }, + }; + } + function radix2(bits, revPadding = false) { + assertNumber(bits); + if (bits <= 0 || bits > 32) + throw new Error("radix2: bits should be in (0..32]"); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new Error("radix2: carry overflow"); + return { + encode: (bytes3) => { + if (!(bytes3 instanceof Uint8Array)) + throw new Error("radix2.encode input should be Uint8Array"); + return convertRadix2(Array.from(bytes3), 8, bits, !revPadding); + }, + decode: (digits) => { + if ( + !Array.isArray(digits) || + (digits.length && typeof digits[0] !== "number") + ) + throw new Error("radix2.decode input should be array of strings"); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; + } + function unsafeWrapper(fn) { + if (typeof fn !== "function") + throw new Error("unsafeWrapper fn should be function"); + return (...args) => { + try { + return fn.apply(null, args); + } catch (e) {} + }; + } + function checksum(len, fn) { + assertNumber(len); + if (typeof fn !== "function") + throw new Error("checksum fn should be function"); + return { + encode(data) { + if (!(data instanceof Uint8Array)) + throw new Error("checksum.encode: input should be Uint8Array"); + const checksum2 = fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(checksum2, data.length); + return res; + }, + decode(data) { + if (!(data instanceof Uint8Array)) + throw new Error("checksum.decode: input should be Uint8Array"); + const payload = data.slice(0, -len); + const newChecksum = fn(payload).slice(0, len); + const oldChecksum = data.slice(-len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error("Invalid checksum"); + return payload; + }, + }; + } + var utils = { alphabet, chain, checksum, radix, radix2, join, padding }; + var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join("")); + var base32 = chain( + radix2(5), + alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), + padding(5), + join(""), + ); + var base32hex = chain( + radix2(5), + alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), + padding(5), + join(""), + ); + var base32crockford = chain( + radix2(5), + alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), + join(""), + normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")), + ); + var base64 = chain( + radix2(6), + alphabet( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", + ), + padding(6), + join(""), + ); + var base64url = chain( + radix2(6), + alphabet( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + ), + padding(6), + join(""), + ); + var genBase58 = (abc) => chain(radix(58), alphabet(abc), join("")); + var base58 = genBase58( + "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", + ); + var base58flickr = genBase58( + "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", + ); + var base58xrp = genBase58( + "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz", + ); + var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; + var base58xmr = { + encode(data) { + let res = ""; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); + } + return res; + }, + decode(str) { + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) throw new Error("base58xmr: wrong padding"); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, + }; + var base58check = (sha2562) => + chain( + checksum(4, (data) => sha2562(sha2562(data))), + base58, + ); + var BECH_ALPHABET = chain( + alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), + join(""), + ); + var POLYMOD_GENERATORS = [ + 996825010, 642813549, 513874426, 1027748829, 705979059, + ]; + function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 33554431) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]; + } + return chk; + } + function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 31); + for (const v of words) chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) chk = bech32Polymod(chk); + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); + } + function genBech32(encoding) { + const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + if (typeof prefix !== "string") + throw new Error( + `bech32.encode prefix should be string, not ${typeof prefix}`, + ); + if ( + !Array.isArray(words) || + (words.length && typeof words[0] !== "number") + ) + throw new Error( + `bech32.encode words should be array of numbers, not ${typeof words}`, + ); + const actualLength = prefix.length + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + prefix = prefix.toLowerCase(); + return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; + } + function decode2(str, limit = 90) { + if (typeof str !== "string") + throw new Error( + `bech32.decode input should be string, not ${typeof str}`, + ); + if (str.length < 8 || (limit !== false && str.length > limit)) + throw new TypeError( + `Wrong string length: ${str.length} (${str}). Expected (8..${limit})`, + ); + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + str = lowered; + const sepIndex = str.lastIndexOf("1"); + if (sepIndex === 0 || sepIndex === -1) + throw new Error( + `Letter "1" must be present between prefix and data only`, + ); + const prefix = str.slice(0, sepIndex); + const _words2 = str.slice(sepIndex + 1); + if (_words2.length < 6) + throw new Error("Data must be at least 6 characters long"); + const words = BECH_ALPHABET.decode(_words2).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!_words2.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode2); + function decodeToBytes(str) { + const { prefix, words } = decode2(str, false); + return { prefix, words, bytes: fromWords(words) }; + } + return { + encode, + decode: decode2, + decodeToBytes, + decodeUnsafe, + fromWords, + fromWordsUnsafe, + toWords, + }; + } + var bech32 = genBech32("bech32"); + var bech32m = genBech32("bech32m"); + var utf8 = { + encode: (data) => new TextDecoder().decode(data), + decode: (str) => new TextEncoder().encode(str), + }; + var hex = chain( + radix2(4), + alphabet("0123456789abcdef"), + join(""), + normalize((s) => { + if (typeof s !== "string" || s.length % 2) + throw new TypeError( + `hex.decode: expected string, got ${typeof s} with length ${s.length}`, + ); + return s.toLowerCase(); + }), + ); + var CODERS = { + utf8, + hex, + base16, + base32, + base64, + base64url, + base58, + base58xmr, + }; + var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`; - // node_modules/.pnpm/@scure+bip39@1.2.1/node_modules/@scure/bip39/esm/wordlists/english.js - var wordlist = `abandon + // node_modules/.pnpm/@scure+bip39@1.2.1/node_modules/@scure/bip39/esm/wordlists/english.js + var wordlist = `abandon ability able about @@ -5384,3052 +5576,3403 @@ zero zone zoo`.split("\n"); - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/pbkdf2.js - function pbkdf2Init(hash3, _password, _salt, _opts) { - assert_default.hash(hash3); - const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); - const { c, dkLen, asyncTick } = opts; - assert_default.number(c); - assert_default.number(dkLen); - assert_default.number(asyncTick); - if (c < 1) - throw new Error("PBKDF2: iterations (c) should be >= 1"); - const password = toBytes(_password); - const salt2 = toBytes(_salt); - const DK = new Uint8Array(dkLen); - const PRF = hmac.create(hash3, password); - const PRFSalt = PRF._cloneInto().update(salt2); - return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; - } - function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - u.fill(0); - return DK; - } - function pbkdf2(hash3, password, salt2, opts) { - const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash3, password, salt2, opts); - let prfW; - const arr = new Uint8Array(4); - const view = createView(arr); - const u = new Uint8Array(PRF.outputLen); - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); - Ti.set(u.subarray(0, Ti.length)); - for (let ui = 1; ui < c; ui++) { - PRF._cloneInto(prfW).update(u).digestInto(u); - for (let i = 0; i < Ti.length; i++) - Ti[i] ^= u[i]; - } - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); - } + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/pbkdf2.js + function pbkdf2Init(hash3, _password, _salt, _opts) { + assert_default.hash(hash3); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assert_default.number(c); + assert_default.number(dkLen); + assert_default.number(asyncTick); + if (c < 1) throw new Error("PBKDF2: iterations (c) should be >= 1"); + const password = toBytes(_password); + const salt2 = toBytes(_salt); + const DK = new Uint8Array(dkLen); + const PRF = hmac.create(hash3, password); + const PRFSalt = PRF._cloneInto().update(salt2); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; + } + function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; + } + function pbkdf2(hash3, password, salt2, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init( + hash3, + password, + salt2, + opts, + ); + let prfW; + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); + } - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/_u64.js - var U32_MASK64 = BigInt(2 ** 32 - 1); - var _32n = BigInt(32); - function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; - } - function split(lst, le = false) { - let Ah = new Uint32Array(lst.length); - let Al = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h, l } = fromBig(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; - } - var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0); - var shrSH = (h, l, s) => h >>> s; - var shrSL = (h, l, s) => h << 32 - s | l >>> s; - var rotrSH = (h, l, s) => h >>> s | l << 32 - s; - var rotrSL = (h, l, s) => h << 32 - s | l >>> s; - var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; - var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; - var rotr32H = (h, l) => l; - var rotr32L = (h, l) => h; - var rotlSH = (h, l, s) => h << s | l >>> 32 - s; - var rotlSL = (h, l, s) => l << s | h >>> 32 - s; - var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; - var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; - function add(Ah, Al, Bh, Bl) { - const l = (Al >>> 0) + (Bl >>> 0); - return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; - } - var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); - var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; - var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); - var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; - var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); - var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; - var u64 = { - fromBig, - split, - toBig, - shrSH, - shrSL, - rotrSH, - rotrSL, - rotrBH, - rotrBL, - rotr32H, - rotr32L, - rotlSH, - rotlSL, - rotlBH, - rotlBL, - add, - add3L, - add3H, - add4L, - add4H, - add5H, - add5L - }; - var u64_default = u64; + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/_u64.js + var U32_MASK64 = BigInt(2 ** 32 - 1); + var _32n = BigInt(32); + function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { + h: Number((n >> _32n) & U32_MASK64) | 0, + l: Number(n & U32_MASK64) | 0, + }; + } + function split(lst, le = false) { + const Ah = new Uint32Array(lst.length); + const Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; + } + var toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); + var shrSH = (h, l, s) => h >>> s; + var shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + var rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); + var rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + var rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); + var rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); + var rotr32H = (h, l) => l; + var rotr32L = (h, l) => h; + var rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); + var rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); + var rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); + var rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); + function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; + } + var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); + var add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; + var add4L = (Al, Bl, Cl, Dl) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); + var add4H = (low, Ah, Bh, Ch, Dh) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; + var add5L = (Al, Bl, Cl, Dl, El) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); + var add5H = (low, Ah, Bh, Ch, Dh, Eh) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + var u64 = { + fromBig, + split, + toBig, + shrSH, + shrSL, + rotrSH, + rotrSL, + rotrBH, + rotrBL, + rotr32H, + rotr32L, + rotlSH, + rotlSL, + rotlBH, + rotlBL, + add, + add3L, + add3H, + add4L, + add4H, + add5H, + add5L, + }; + var u64_default = u64; - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/sha512.js - var [SHA512_Kh, SHA512_Kl] = u64_default.split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" - ].map((n) => BigInt(n))); - var SHA512_W_H = new Uint32Array(80); - var SHA512_W_L = new Uint32Array(80); - var SHA512 = class extends SHA2 { - constructor() { - super(128, 64, 16, false); - this.Ah = 1779033703 | 0; - this.Al = 4089235720 | 0; - this.Bh = 3144134277 | 0; - this.Bl = 2227873595 | 0; - this.Ch = 1013904242 | 0; - this.Cl = 4271175723 | 0; - this.Dh = 2773480762 | 0; - this.Dl = 1595750129 | 0; - this.Eh = 1359893119 | 0; - this.El = 2917565137 | 0; - this.Fh = 2600822924 | 0; - this.Fl = 725511199 | 0; - this.Gh = 528734635 | 0; - this.Gl = 4215389547 | 0; - this.Hh = 1541459225 | 0; - this.Hl = 327033209 | 0; - } - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); - } - for (let i = 16; i < 80; i++) { - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7); - const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7); - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6); - const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6); - const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - for (let i = 0; i < 80; i++) { - const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41); - const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41); - const CHIh = Eh & Fh ^ ~Eh & Gh; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39); - const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39); - const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = u64_default.add3L(T1l, sigma0l, MAJl); - Ah = u64_default.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - ({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - SHA512_W_H.fill(0); - SHA512_W_L.fill(0); - } - destroy() { - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - }; - var SHA512_224 = class extends SHA512 { - constructor() { - super(); - this.Ah = 2352822216 | 0; - this.Al = 424955298 | 0; - this.Bh = 1944164710 | 0; - this.Bl = 2312950998 | 0; - this.Ch = 502970286 | 0; - this.Cl = 855612546 | 0; - this.Dh = 1738396948 | 0; - this.Dl = 1479516111 | 0; - this.Eh = 258812777 | 0; - this.El = 2077511080 | 0; - this.Fh = 2011393907 | 0; - this.Fl = 79989058 | 0; - this.Gh = 1067287976 | 0; - this.Gl = 1780299464 | 0; - this.Hh = 286451373 | 0; - this.Hl = 2446758561 | 0; - this.outputLen = 28; - } - }; - var SHA512_256 = class extends SHA512 { - constructor() { - super(); - this.Ah = 573645204 | 0; - this.Al = 4230739756 | 0; - this.Bh = 2673172387 | 0; - this.Bl = 3360449730 | 0; - this.Ch = 596883563 | 0; - this.Cl = 1867755857 | 0; - this.Dh = 2520282905 | 0; - this.Dl = 1497426621 | 0; - this.Eh = 2519219938 | 0; - this.El = 2827943907 | 0; - this.Fh = 3193839141 | 0; - this.Fl = 1401305490 | 0; - this.Gh = 721525244 | 0; - this.Gl = 746961066 | 0; - this.Hh = 246885852 | 0; - this.Hl = 2177182882 | 0; - this.outputLen = 32; - } - }; - var SHA384 = class extends SHA512 { - constructor() { - super(); - this.Ah = 3418070365 | 0; - this.Al = 3238371032 | 0; - this.Bh = 1654270250 | 0; - this.Bl = 914150663 | 0; - this.Ch = 2438529370 | 0; - this.Cl = 812702999 | 0; - this.Dh = 355462360 | 0; - this.Dl = 4144912697 | 0; - this.Eh = 1731405415 | 0; - this.El = 4290775857 | 0; - this.Fh = 2394180231 | 0; - this.Fl = 1750603025 | 0; - this.Gh = 3675008525 | 0; - this.Gl = 1694076839 | 0; - this.Hh = 1203062813 | 0; - this.Hl = 3204075428 | 0; - this.outputLen = 48; - } - }; - var sha512 = wrapConstructor(() => new SHA512()); - var sha512_224 = wrapConstructor(() => new SHA512_224()); - var sha512_256 = wrapConstructor(() => new SHA512_256()); - var sha384 = wrapConstructor(() => new SHA384()); + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/sha512.js + var [SHA512_Kh, SHA512_Kl] = u64_default.split( + [ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817", + ].map((n) => BigInt(n)), + ); + var SHA512_W_H = new Uint32Array(80); + var SHA512_W_L = new Uint32Array(80); + var SHA512 = class extends SHA2 { + constructor() { + super(128, 64, 16, false); + this.Ah = 1779033703 | 0; + this.Al = 4089235720 | 0; + this.Bh = 3144134277 | 0; + this.Bl = 2227873595 | 0; + this.Ch = 1013904242 | 0; + this.Cl = 4271175723 | 0; + this.Dh = 2773480762 | 0; + this.Dl = 1595750129 | 0; + this.Eh = 1359893119 | 0; + this.El = 2917565137 | 0; + this.Fh = 2600822924 | 0; + this.Fl = 725511199 | 0; + this.Gh = 528734635 | 0; + this.Gl = 4215389547 | 0; + this.Hh = 1541459225 | 0; + this.Hl = 327033209 | 0; + } + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = + this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = + u64_default.rotrSH(W15h, W15l, 1) ^ + u64_default.rotrSH(W15h, W15l, 8) ^ + u64_default.shrSH(W15h, W15l, 7); + const s0l = + u64_default.rotrSL(W15h, W15l, 1) ^ + u64_default.rotrSL(W15h, W15l, 8) ^ + u64_default.shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = + u64_default.rotrSH(W2h, W2l, 19) ^ + u64_default.rotrBH(W2h, W2l, 61) ^ + u64_default.shrSH(W2h, W2l, 6); + const s1l = + u64_default.rotrSL(W2h, W2l, 19) ^ + u64_default.rotrBL(W2h, W2l, 61) ^ + u64_default.shrSL(W2h, W2l, 6); + const SUMl = u64_default.add4L( + s0l, + s1l, + SHA512_W_L[i - 7], + SHA512_W_L[i - 16], + ); + const SUMh = u64_default.add4H( + SUMl, + s0h, + s1h, + SHA512_W_H[i - 7], + SHA512_W_H[i - 16], + ); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = + this; + for (let i = 0; i < 80; i++) { + const sigma1h = + u64_default.rotrSH(Eh, El, 14) ^ + u64_default.rotrSH(Eh, El, 18) ^ + u64_default.rotrBH(Eh, El, 41); + const sigma1l = + u64_default.rotrSL(Eh, El, 14) ^ + u64_default.rotrSL(Eh, El, 18) ^ + u64_default.rotrBL(Eh, El, 41); + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + const T1ll = u64_default.add5L( + Hl, + sigma1l, + CHIl, + SHA512_Kl[i], + SHA512_W_L[i], + ); + const T1h = u64_default.add5H( + T1ll, + Hh, + sigma1h, + CHIh, + SHA512_Kh[i], + SHA512_W_H[i], + ); + const T1l = T1ll | 0; + const sigma0h = + u64_default.rotrSH(Ah, Al, 28) ^ + u64_default.rotrBH(Ah, Al, 34) ^ + u64_default.rotrBH(Ah, Al, 39); + const sigma0l = + u64_default.rotrSL(Ah, Al, 28) ^ + u64_default.rotrBL(Ah, Al, 34) ^ + u64_default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64_default.add3L(T1l, sigma0l, MAJl); + Ah = u64_default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + ({ h: Ah, l: Al } = u64_default.add( + this.Ah | 0, + this.Al | 0, + Ah | 0, + Al | 0, + )); + ({ h: Bh, l: Bl } = u64_default.add( + this.Bh | 0, + this.Bl | 0, + Bh | 0, + Bl | 0, + )); + ({ h: Ch, l: Cl } = u64_default.add( + this.Ch | 0, + this.Cl | 0, + Ch | 0, + Cl | 0, + )); + ({ h: Dh, l: Dl } = u64_default.add( + this.Dh | 0, + this.Dl | 0, + Dh | 0, + Dl | 0, + )); + ({ h: Eh, l: El } = u64_default.add( + this.Eh | 0, + this.El | 0, + Eh | 0, + El | 0, + )); + ({ h: Fh, l: Fl } = u64_default.add( + this.Fh | 0, + this.Fl | 0, + Fh | 0, + Fl | 0, + )); + ({ h: Gh, l: Gl } = u64_default.add( + this.Gh | 0, + this.Gl | 0, + Gh | 0, + Gl | 0, + )); + ({ h: Hh, l: Hl } = u64_default.add( + this.Hh | 0, + this.Hl | 0, + Hh | 0, + Hl | 0, + )); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + }; + var SHA512_224 = class extends SHA512 { + constructor() { + super(); + this.Ah = 2352822216 | 0; + this.Al = 424955298 | 0; + this.Bh = 1944164710 | 0; + this.Bl = 2312950998 | 0; + this.Ch = 502970286 | 0; + this.Cl = 855612546 | 0; + this.Dh = 1738396948 | 0; + this.Dl = 1479516111 | 0; + this.Eh = 258812777 | 0; + this.El = 2077511080 | 0; + this.Fh = 2011393907 | 0; + this.Fl = 79989058 | 0; + this.Gh = 1067287976 | 0; + this.Gl = 1780299464 | 0; + this.Hh = 286451373 | 0; + this.Hl = 2446758561 | 0; + this.outputLen = 28; + } + }; + var SHA512_256 = class extends SHA512 { + constructor() { + super(); + this.Ah = 573645204 | 0; + this.Al = 4230739756 | 0; + this.Bh = 2673172387 | 0; + this.Bl = 3360449730 | 0; + this.Ch = 596883563 | 0; + this.Cl = 1867755857 | 0; + this.Dh = 2520282905 | 0; + this.Dl = 1497426621 | 0; + this.Eh = 2519219938 | 0; + this.El = 2827943907 | 0; + this.Fh = 3193839141 | 0; + this.Fl = 1401305490 | 0; + this.Gh = 721525244 | 0; + this.Gl = 746961066 | 0; + this.Hh = 246885852 | 0; + this.Hl = 2177182882 | 0; + this.outputLen = 32; + } + }; + var SHA384 = class extends SHA512 { + constructor() { + super(); + this.Ah = 3418070365 | 0; + this.Al = 3238371032 | 0; + this.Bh = 1654270250 | 0; + this.Bl = 914150663 | 0; + this.Ch = 2438529370 | 0; + this.Cl = 812702999 | 0; + this.Dh = 355462360 | 0; + this.Dl = 4144912697 | 0; + this.Eh = 1731405415 | 0; + this.El = 4290775857 | 0; + this.Fh = 2394180231 | 0; + this.Fl = 1750603025 | 0; + this.Gh = 3675008525 | 0; + this.Gl = 1694076839 | 0; + this.Hh = 1203062813 | 0; + this.Hl = 3204075428 | 0; + this.outputLen = 48; + } + }; + var sha512 = wrapConstructor(() => new SHA512()); + var sha512_224 = wrapConstructor(() => new SHA512_224()); + var sha512_256 = wrapConstructor(() => new SHA512_256()); + var sha384 = wrapConstructor(() => new SHA384()); - // node_modules/.pnpm/@scure+bip39@1.2.1/node_modules/@scure/bip39/esm/index.js - var isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093"; - function nfkd(str) { - if (typeof str !== "string") - throw new TypeError(`Invalid mnemonic type: ${typeof str}`); - return str.normalize("NFKD"); - } - function normalize2(str) { - const norm = nfkd(str); - const words = norm.split(" "); - if (![12, 15, 18, 21, 24].includes(words.length)) - throw new Error("Invalid mnemonic"); - return { nfkd: norm, words }; - } - function assertEntropy(entropy) { - assert_default.bytes(entropy, 16, 20, 24, 28, 32); - } - function generateMnemonic(wordlist2, strength = 128) { - assert_default.number(strength); - if (strength % 32 !== 0 || strength > 256) - throw new TypeError("Invalid entropy"); - return entropyToMnemonic(randomBytes(strength / 8), wordlist2); - } - var calcChecksum = (entropy) => { - const bitsLeft = 8 - entropy.length / 4; - return new Uint8Array([sha256(entropy)[0] >> bitsLeft << bitsLeft]); - }; - function getCoder(wordlist2) { - if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string") - throw new Error("Worlist: expected array of 2048 strings"); - wordlist2.forEach((i) => { - if (typeof i !== "string") - throw new Error(`Wordlist: non-string element: ${i}`); - }); - return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2)); - } - function mnemonicToEntropy(mnemonic, wordlist2) { - const { words } = normalize2(mnemonic); - const entropy = getCoder(wordlist2).decode(words); - assertEntropy(entropy); - return entropy; - } - function entropyToMnemonic(entropy, wordlist2) { - assertEntropy(entropy); - const words = getCoder(wordlist2).encode(entropy); - return words.join(isJapanese(wordlist2) ? "\u3000" : " "); - } - function validateMnemonic(mnemonic, wordlist2) { - try { - mnemonicToEntropy(mnemonic, wordlist2); - } catch (e) { - return false; - } - return true; - } - var salt = (passphrase) => nfkd(`mnemonic${passphrase}`); - function mnemonicToSeedSync(mnemonic, passphrase = "") { - return pbkdf2(sha512, normalize2(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 }); - } + // node_modules/.pnpm/@scure+bip39@1.2.1/node_modules/@scure/bip39/esm/index.js + var isJapanese = (wordlist2) => + wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093"; + function nfkd(str) { + if (typeof str !== "string") + throw new TypeError(`Invalid mnemonic type: ${typeof str}`); + return str.normalize("NFKD"); + } + function normalize2(str) { + const norm = nfkd(str); + const words = norm.split(" "); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error("Invalid mnemonic"); + return { nfkd: norm, words }; + } + function assertEntropy(entropy) { + assert_default.bytes(entropy, 16, 20, 24, 28, 32); + } + function generateMnemonic(wordlist2, strength = 128) { + assert_default.number(strength); + if (strength % 32 !== 0 || strength > 256) + throw new TypeError("Invalid entropy"); + return entropyToMnemonic(randomBytes(strength / 8), wordlist2); + } + var calcChecksum = (entropy) => { + const bitsLeft = 8 - entropy.length / 4; + return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]); + }; + function getCoder(wordlist2) { + if ( + !Array.isArray(wordlist2) || + wordlist2.length !== 2048 || + typeof wordlist2[0] !== "string" + ) + throw new Error("Worlist: expected array of 2048 strings"); + wordlist2.forEach((i) => { + if (typeof i !== "string") + throw new Error(`Wordlist: non-string element: ${i}`); + }); + return utils.chain( + utils.checksum(1, calcChecksum), + utils.radix2(11, true), + utils.alphabet(wordlist2), + ); + } + function mnemonicToEntropy(mnemonic, wordlist2) { + const { words } = normalize2(mnemonic); + const entropy = getCoder(wordlist2).decode(words); + assertEntropy(entropy); + return entropy; + } + function entropyToMnemonic(entropy, wordlist2) { + assertEntropy(entropy); + const words = getCoder(wordlist2).encode(entropy); + return words.join(isJapanese(wordlist2) ? "\u3000" : " "); + } + function validateMnemonic(mnemonic, wordlist2) { + try { + mnemonicToEntropy(mnemonic, wordlist2); + } catch (e) { + return false; + } + return true; + } + var salt = (passphrase) => nfkd(`mnemonic${passphrase}`); + function mnemonicToSeedSync(mnemonic, passphrase = "") { + return pbkdf2(sha512, normalize2(mnemonic).nfkd, salt(passphrase), { + c: 2048, + dkLen: 64, + }); + } - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/ripemd160.js - var Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); - var Id = Uint8Array.from({ length: 16 }, (_, i) => i); - var Pi = Id.map((i) => (9 * i + 5) % 16); - var idxL = [Id]; - var idxR = [Pi]; - for (let i = 0; i < 4; i++) - for (let j of [idxL, idxR]) - j.push(j[i].map((k) => Rho[k])); - var shifts = [ - [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], - [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], - [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], - [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], - [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] - ].map((i) => new Uint8Array(i)); - var shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); - var shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); - var Kl = new Uint32Array([0, 1518500249, 1859775393, 2400959708, 2840853838]); - var Kr = new Uint32Array([1352829926, 1548603684, 1836072691, 2053994217, 0]); - var rotl = (word, shift) => word << shift | word >>> 32 - shift; - function f(group, x, y, z) { - if (group === 0) - return x ^ y ^ z; - else if (group === 1) - return x & y | ~x & z; - else if (group === 2) - return (x | ~y) ^ z; - else if (group === 3) - return x & z | y & ~z; - else - return x ^ (y | ~z); - } - var BUF = new Uint32Array(16); - var RIPEMD160 = class extends SHA2 { - constructor() { - super(64, 20, 8, true); - this.h0 = 1732584193 | 0; - this.h1 = 4023233417 | 0; - this.h2 = 2562383102 | 0; - this.h3 = 271733878 | 0; - this.h4 = 3285377520 | 0; - } - get() { - const { h0, h1, h2, h3, h4 } = this; - return [h0, h1, h2, h3, h4]; - } - set(h0, h1, h2, h3, h4) { - this.h0 = h0 | 0; - this.h1 = h1 | 0; - this.h2 = h2 | 0; - this.h3 = h3 | 0; - this.h4 = h4 | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - BUF[i] = view.getUint32(offset, true); - let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; - for (let group = 0; group < 5; group++) { - const rGroup = 4 - group; - const hbl = Kl[group], hbr = Kr[group]; - const rl = idxL[group], rr = idxR[group]; - const sl = shiftsL[group], sr = shiftsR[group]; - for (let i = 0; i < 16; i++) { - const tl = rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el | 0; - al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; - } - for (let i = 0; i < 16; i++) { - const tr = rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er | 0; - ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; - } - } - this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0); - } - roundClean() { - BUF.fill(0); - } - destroy() { - this.destroyed = true; - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0); - } - }; - var ripemd160 = wrapConstructor(() => new RIPEMD160()); + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/ripemd160.js + var Rho = new Uint8Array([ + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + ]); + var Id = Uint8Array.from({ length: 16 }, (_, i) => i); + var Pi = Id.map((i) => (9 * i + 5) % 16); + var idxL = [Id]; + var idxR = [Pi]; + for (let i = 0; i < 4; i++) + for (const j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + var shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], + ].map((i) => new Uint8Array(i)); + var shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); + var shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); + var Kl = new Uint32Array([0, 1518500249, 1859775393, 2400959708, 2840853838]); + var Kr = new Uint32Array([1352829926, 1548603684, 1836072691, 2053994217, 0]); + var rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); + function f(group, x, y, z) { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); + } + var BUF = new Uint32Array(16); + var RIPEMD160 = class extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 1732584193 | 0; + this.h1 = 4023233417 | 0; + this.h2 = 2562383102 | 0; + this.h3 = 271733878 | 0; + this.h4 = 3285377520 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + let al = this.h0 | 0, + ar = al, + bl = this.h1 | 0, + br = bl, + cl = this.h2 | 0, + cr = cl, + dl = this.h3 | 0, + dr = dl, + el = this.h4 | 0, + er = el; + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], + hbr = Kr[group]; + const rl = idxL[group], + rr = idxR[group]; + const sl = shiftsL[group], + sr = shiftsR[group]; + for (let i = 0; i < 16; i++) { + const tl = + (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | + 0; + (al = el), (el = dl), (dl = rotl(cl, 10) | 0), (cl = bl), (bl = tl); + } + for (let i = 0; i < 16; i++) { + const tr = + (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | + 0; + (ar = er), (er = dr), (dr = rotl(cr, 10) | 0), (cr = br), (br = tr); + } + } + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0, + ); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } + }; + var ripemd160 = wrapConstructor(() => new RIPEMD160()); - // node_modules/.pnpm/@scure+bip32@1.3.1/node_modules/@scure/bip32/lib/esm/index.js - var Point2 = secp256k1.ProjectivePoint; - var base58check2 = base58check(sha256); - function bytesToNumber(bytes3) { - return BigInt(`0x${bytesToHex(bytes3)}`); - } - function numberToBytes(num) { - return hexToBytes(num.toString(16).padStart(64, "0")); - } - var MASTER_SECRET = utf8ToBytes("Bitcoin seed"); - var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 }; - var HARDENED_OFFSET = 2147483648; - var hash160 = (data) => ripemd160(sha256(data)); - var fromU32 = (data) => createView(data).getUint32(0, false); - var toU32 = (n) => { - if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { - throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); - } - const buf = new Uint8Array(4); - createView(buf).setUint32(0, n, false); - return buf; - }; - var HDKey = class { - get fingerprint() { - if (!this.pubHash) { - throw new Error("No publicKey set!"); - } - return fromU32(this.pubHash); - } - get identifier() { - return this.pubHash; - } - get pubKeyHash() { - return this.pubHash; - } - get privateKey() { - return this.privKeyBytes || null; - } - get publicKey() { - return this.pubKey || null; - } - get privateExtendedKey() { - const priv = this.privateKey; - if (!priv) { - throw new Error("No private key"); - } - return base58check2.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv))); - } - get publicExtendedKey() { - if (!this.pubKey) { - throw new Error("No public key"); - } - return base58check2.encode(this.serialize(this.versions.public, this.pubKey)); - } - static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { - bytes(seed); - if (8 * seed.length < 128 || 8 * seed.length > 512) { - throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`); - } - const I = hmac(sha512, MASTER_SECRET, seed); - return new HDKey({ - versions, - chainCode: I.slice(32), - privateKey: I.slice(0, 32) - }); - } - static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { - const keyBuffer = base58check2.decode(base58key); - const keyView = createView(keyBuffer); - const version = keyView.getUint32(0, false); - const opt = { - versions, - depth: keyBuffer[4], - parentFingerprint: keyView.getUint32(5, false), - index: keyView.getUint32(9, false), - chainCode: keyBuffer.slice(13, 45) - }; - const key = keyBuffer.slice(45); - const isPriv = key[0] === 0; - if (version !== versions[isPriv ? "private" : "public"]) { - throw new Error("Version mismatch"); - } - if (isPriv) { - return new HDKey({ ...opt, privateKey: key.slice(1) }); - } else { - return new HDKey({ ...opt, publicKey: key }); - } - } - static fromJSON(json) { - return HDKey.fromExtendedKey(json.xpriv); - } - constructor(opt) { - this.depth = 0; - this.index = 0; - this.chainCode = null; - this.parentFingerprint = 0; - if (!opt || typeof opt !== "object") { - throw new Error("HDKey.constructor must not be called directly"); - } - this.versions = opt.versions || BITCOIN_VERSIONS; - this.depth = opt.depth || 0; - this.chainCode = opt.chainCode; - this.index = opt.index || 0; - this.parentFingerprint = opt.parentFingerprint || 0; - if (!this.depth) { - if (this.parentFingerprint || this.index) { - throw new Error("HDKey: zero depth with non-zero index/parent fingerprint"); - } - } - if (opt.publicKey && opt.privateKey) { - throw new Error("HDKey: publicKey and privateKey at same time."); - } - if (opt.privateKey) { - if (!secp256k1.utils.isValidPrivateKey(opt.privateKey)) { - throw new Error("Invalid private key"); - } - this.privKey = typeof opt.privateKey === "bigint" ? opt.privateKey : bytesToNumber(opt.privateKey); - this.privKeyBytes = numberToBytes(this.privKey); - this.pubKey = secp256k1.getPublicKey(opt.privateKey, true); - } else if (opt.publicKey) { - this.pubKey = Point2.fromHex(opt.publicKey).toRawBytes(true); - } else { - throw new Error("HDKey: no public or private key provided"); - } - this.pubHash = hash160(this.pubKey); - } - derive(path) { - if (!/^[mM]'?/.test(path)) { - throw new Error('Path must start with "m" or "M"'); - } - if (/^[mM]'?$/.test(path)) { - return this; - } - const parts = path.replace(/^[mM]'?\//, "").split("/"); - let child = this; - for (const c of parts) { - const m = /^(\d+)('?)$/.exec(c); - if (!m || m.length !== 3) { - throw new Error(`Invalid child index: ${c}`); - } - let idx = +m[1]; - if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { - throw new Error("Invalid index"); - } - if (m[2] === "'") { - idx += HARDENED_OFFSET; - } - child = child.deriveChild(idx); - } - return child; - } - deriveChild(index) { - if (!this.pubKey || !this.chainCode) { - throw new Error("No publicKey or chainCode set"); - } - let data = toU32(index); - if (index >= HARDENED_OFFSET) { - const priv = this.privateKey; - if (!priv) { - throw new Error("Could not derive hardened child key"); - } - data = concatBytes(new Uint8Array([0]), priv, data); - } else { - data = concatBytes(this.pubKey, data); - } - const I = hmac(sha512, this.chainCode, data); - const childTweak = bytesToNumber(I.slice(0, 32)); - const chainCode = I.slice(32); - if (!secp256k1.utils.isValidPrivateKey(childTweak)) { - throw new Error("Tweak bigger than curve order"); - } - const opt = { - versions: this.versions, - chainCode, - depth: this.depth + 1, - parentFingerprint: this.fingerprint, - index - }; - try { - if (this.privateKey) { - const added = mod(this.privKey + childTweak, secp256k1.CURVE.n); - if (!secp256k1.utils.isValidPrivateKey(added)) { - throw new Error("The tweak was out of range or the resulted private key is invalid"); - } - opt.privateKey = added; - } else { - const added = Point2.fromHex(this.pubKey).add(Point2.fromPrivateKey(childTweak)); - if (added.equals(Point2.ZERO)) { - throw new Error("The tweak was equal to negative P, which made the result key invalid"); - } - opt.publicKey = added.toRawBytes(true); - } - return new HDKey(opt); - } catch (err) { - return this.deriveChild(index + 1); - } - } - sign(hash3) { - if (!this.privateKey) { - throw new Error("No privateKey set!"); - } - bytes(hash3, 32); - return secp256k1.sign(hash3, this.privKey).toCompactRawBytes(); - } - verify(hash3, signature) { - bytes(hash3, 32); - bytes(signature, 64); - if (!this.publicKey) { - throw new Error("No publicKey set!"); - } - let sig; - try { - sig = secp256k1.Signature.fromCompact(signature); - } catch (error) { - return false; - } - return secp256k1.verify(sig, hash3, this.publicKey); - } - wipePrivateData() { - this.privKey = void 0; - if (this.privKeyBytes) { - this.privKeyBytes.fill(0); - this.privKeyBytes = void 0; - } - return this; - } - toJSON() { - return { - xpriv: this.privateExtendedKey, - xpub: this.publicExtendedKey - }; - } - serialize(version, key) { - if (!this.chainCode) { - throw new Error("No chainCode set"); - } - bytes(key, 33); - return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); - } - }; + // node_modules/.pnpm/@scure+bip32@1.3.1/node_modules/@scure/bip32/lib/esm/index.js + var Point2 = secp256k1.ProjectivePoint; + var base58check2 = base58check(sha256); + function bytesToNumber(bytes3) { + return BigInt(`0x${bytesToHex(bytes3)}`); + } + function numberToBytes(num) { + return hexToBytes(num.toString(16).padStart(64, "0")); + } + var MASTER_SECRET = utf8ToBytes("Bitcoin seed"); + var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 }; + var HARDENED_OFFSET = 2147483648; + var hash160 = (data) => ripemd160(sha256(data)); + var fromU32 = (data) => createView(data).getUint32(0, false); + var toU32 = (n) => { + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { + throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`); + } + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; + }; + var HDKey = class { + get fingerprint() { + if (!this.pubHash) { + throw new Error("No publicKey set!"); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + get privateKey() { + return this.privKeyBytes || null; + } + get publicKey() { + return this.pubKey || null; + } + get privateExtendedKey() { + const priv = this.privateKey; + if (!priv) { + throw new Error("No private key"); + } + return base58check2.encode( + this.serialize( + this.versions.private, + concatBytes(new Uint8Array([0]), priv), + ), + ); + } + get publicExtendedKey() { + if (!this.pubKey) { + throw new Error("No public key"); + } + return base58check2.encode( + this.serialize(this.versions.public, this.pubKey), + ); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + bytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new Error( + `HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`, + ); + } + const I = hmac(sha512, MASTER_SECRET, seed); + return new HDKey({ + versions, + chainCode: I.slice(32), + privateKey: I.slice(0, 32), + }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + const keyBuffer = base58check2.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? "private" : "public"]) { + throw new Error("Version mismatch"); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } else { + return new HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return HDKey.fromExtendedKey(json.xpriv); + } + constructor(opt) { + this.depth = 0; + this.index = 0; + this.chainCode = null; + this.parentFingerprint = 0; + if (!opt || typeof opt !== "object") { + throw new Error("HDKey.constructor must not be called directly"); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error( + "HDKey: zero depth with non-zero index/parent fingerprint", + ); + } + } + if (opt.publicKey && opt.privateKey) { + throw new Error("HDKey: publicKey and privateKey at same time."); + } + if (opt.privateKey) { + if (!secp256k1.utils.isValidPrivateKey(opt.privateKey)) { + throw new Error("Invalid private key"); + } + this.privKey = + typeof opt.privateKey === "bigint" + ? opt.privateKey + : bytesToNumber(opt.privateKey); + this.privKeyBytes = numberToBytes(this.privKey); + this.pubKey = secp256k1.getPublicKey(opt.privateKey, true); + } else if (opt.publicKey) { + this.pubKey = Point2.fromHex(opt.publicKey).toRawBytes(true); + } else { + throw new Error("HDKey: no public or private key provided"); + } + this.pubHash = hash160(this.pubKey); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, "").split("/"); + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + if (!m || m.length !== 3) { + throw new Error(`Invalid child index: ${c}`); + } + let idx = +m[1]; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error("Invalid index"); + } + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + deriveChild(index) { + if (!this.pubKey || !this.chainCode) { + throw new Error("No publicKey or chainCode set"); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + const priv = this.privateKey; + if (!priv) { + throw new Error("Could not derive hardened child key"); + } + data = concatBytes(new Uint8Array([0]), priv, data); + } else { + data = concatBytes(this.pubKey, data); + } + const I = hmac(sha512, this.chainCode, data); + const childTweak = bytesToNumber(I.slice(0, 32)); + const chainCode = I.slice(32); + if (!secp256k1.utils.isValidPrivateKey(childTweak)) { + throw new Error("Tweak bigger than curve order"); + } + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + try { + if (this.privateKey) { + const added = mod(this.privKey + childTweak, secp256k1.CURVE.n); + if (!secp256k1.utils.isValidPrivateKey(added)) { + throw new Error( + "The tweak was out of range or the resulted private key is invalid", + ); + } + opt.privateKey = added; + } else { + const added = Point2.fromHex(this.pubKey).add( + Point2.fromPrivateKey(childTweak), + ); + if (added.equals(Point2.ZERO)) { + throw new Error( + "The tweak was equal to negative P, which made the result key invalid", + ); + } + opt.publicKey = added.toRawBytes(true); + } + return new HDKey(opt); + } catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash3) { + if (!this.privateKey) { + throw new Error("No privateKey set!"); + } + bytes(hash3, 32); + return secp256k1.sign(hash3, this.privKey).toCompactRawBytes(); + } + verify(hash3, signature) { + bytes(hash3, 32); + bytes(signature, 64); + if (!this.publicKey) { + throw new Error("No publicKey set!"); + } + let sig; + try { + sig = secp256k1.Signature.fromCompact(signature); + } catch (error) { + return false; + } + return secp256k1.verify(sig, hash3, this.publicKey); + } + wipePrivateData() { + this.privKey = void 0; + if (this.privKeyBytes) { + this.privKeyBytes.fill(0); + this.privKeyBytes = void 0; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error("No chainCode set"); + } + bytes(key, 33); + return concatBytes( + toU32(version), + new Uint8Array([this.depth]), + toU32(this.parentFingerprint), + toU32(this.index), + this.chainCode, + key, + ); + } + }; - // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/utils.js - var u8a3 = (a) => a instanceof Uint8Array; - var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE2) - throw new Error("Non little-endian hardware is not supported"); - function utf8ToBytes3(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function toBytes2(data) { - if (typeof data === "string") - data = utf8ToBytes3(data); - if (!u8a3(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - var isPlainObject2 = (obj) => Object.prototype.toString.call(obj) === "[object Object]" && obj.constructor === Object; - function checkOpts2(defaults, opts) { - if (opts !== void 0 && (typeof opts !== "object" || !isPlainObject2(opts))) - throw new Error("options must be object or undefined"); - const merged = Object.assign(defaults, opts); - return merged; - } - function ensureBytes2(b, len) { - if (!(b instanceof Uint8Array)) - throw new Error("Uint8Array expected"); - if (typeof len === "number") { - if (b.length !== len) - throw new Error(`Uint8Array length ${len} expected`); - } - } - function equalBytes2(a, b) { - if (a.length !== b.length) - throw new Error("equalBytes: Different size of Uint8Arrays"); - let isSame = true; - for (let i = 0; i < a.length; i++) - isSame && (isSame = a[i] === b[i]); - return isSame; - } + // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/utils.js + var u8a3 = (a) => a instanceof Uint8Array; + var u32 = (arr) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; + if (!isLE2) throw new Error("Non little-endian hardware is not supported"); + function utf8ToBytes3(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function toBytes2(data) { + if (typeof data === "string") data = utf8ToBytes3(data); + if (!u8a3(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; + } + var isPlainObject2 = (obj) => + Object.prototype.toString.call(obj) === "[object Object]" && + obj.constructor === Object; + function checkOpts2(defaults, opts) { + if (opts !== void 0 && (typeof opts !== "object" || !isPlainObject2(opts))) + throw new Error("options must be object or undefined"); + const merged = Object.assign(defaults, opts); + return merged; + } + function ensureBytes2(b, len) { + if (!(b instanceof Uint8Array)) throw new Error("Uint8Array expected"); + if (typeof len === "number") { + if (b.length !== len) + throw new Error(`Uint8Array length ${len} expected`); + } + } + function equalBytes2(a, b) { + if (a.length !== b.length) + throw new Error("equalBytes: Different size of Uint8Arrays"); + let isSame = true; + for (let i = 0; i < a.length; i++) isSame && (isSame = a[i] === b[i]); + return isSame; + } - // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/_assert.js - function number2(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bool2(b) { - if (typeof b !== "boolean") - throw new Error(`Expected boolean, not ${b}`); - } - function bytes2(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash2(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("hash must be wrapped by utils.wrapConstructor"); - number2(hash3.outputLen); - number2(hash3.blockLen); - } - function exists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); - } - function output2(out, instance) { - bytes2(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - var assert2 = { number: number2, bool: bool2, bytes: bytes2, hash: hash2, exists: exists2, output: output2 }; - var assert_default2 = assert2; + // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/_assert.js + function number2(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); + } + function bool2(b) { + if (typeof b !== "boolean") throw new Error(`Expected boolean, not ${b}`); + } + function bytes2(b, ...lengths) { + if (!(b instanceof Uint8Array)) throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error( + `Expected Uint8Array of length ${lengths}, not of length=${b.length}`, + ); + } + function hash2(hash3) { + if (typeof hash3 !== "function" || typeof hash3.create !== "function") + throw new Error("hash must be wrapped by utils.wrapConstructor"); + number2(hash3.outputLen); + number2(hash3.blockLen); + } + function exists2(instance, checkFinished = true) { + if (instance.destroyed) throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); + } + function output2(out, instance) { + bytes2(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error( + `digestInto() expects output buffer of length at least ${min}`, + ); + } + } + var assert2 = { + number: number2, + bool: bool2, + bytes: bytes2, + hash: hash2, + exists: exists2, + output: output2, + }; + var assert_default2 = assert2; - // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/_poly1305.js - var u8to16 = (a, i) => a[i++] & 255 | (a[i++] & 255) << 8; - var Poly1305 = class { - constructor(key) { - this.blockLen = 16; - this.outputLen = 16; - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.pos = 0; - this.finished = false; - key = toBytes2(key); - ensureBytes2(key, 32); - const t0 = u8to16(key, 0); - const t1 = u8to16(key, 2); - const t2 = u8to16(key, 4); - const t3 = u8to16(key, 6); - const t4 = u8to16(key, 8); - const t5 = u8to16(key, 10); - const t6 = u8to16(key, 12); - const t7 = u8to16(key, 14); - this.r[0] = t0 & 8191; - this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; - this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; - this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; - this.r[4] = (t3 >>> 4 | t4 << 12) & 255; - this.r[5] = t4 >>> 1 & 8190; - this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; - this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; - this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this.r[9] = t7 >>> 5 & 127; - for (let i = 0; i < 8; i++) - this.pad[i] = u8to16(key, 16 + 2 * i); - } - process(data, offset, isLast = false) { - const hibit = isLast ? 0 : 1 << 11; - const { h, r } = this; - const r0 = r[0]; - const r1 = r[1]; - const r2 = r[2]; - const r3 = r[3]; - const r4 = r[4]; - const r5 = r[5]; - const r6 = r[6]; - const r7 = r[7]; - const r8 = r[8]; - const r9 = r[9]; - const t0 = u8to16(data, offset + 0); - const t1 = u8to16(data, offset + 2); - const t2 = u8to16(data, offset + 4); - const t3 = u8to16(data, offset + 6); - const t4 = u8to16(data, offset + 8); - const t5 = u8to16(data, offset + 10); - const t6 = u8to16(data, offset + 12); - const t7 = u8to16(data, offset + 14); - let h0 = h[0] + (t0 & 8191); - let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191); - let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191); - let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191); - let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191); - let h5 = h[5] + (t4 >>> 1 & 8191); - let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191); - let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191); - let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191); - let h9 = h[9] + (t7 >>> 5 | hibit); - let c = 0; - let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); - c = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); - c += d0 >>> 13; - d0 &= 8191; - let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); - c = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); - c += d1 >>> 13; - d1 &= 8191; - let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); - c = d2 >>> 13; - d2 &= 8191; - d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); - c += d2 >>> 13; - d2 &= 8191; - let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); - c = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); - c += d3 >>> 13; - d3 &= 8191; - let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; - c = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); - c += d4 >>> 13; - d4 &= 8191; - let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; - c = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); - c += d5 >>> 13; - d5 &= 8191; - let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; - c = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); - c += d6 >>> 13; - d6 &= 8191; - let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; - c = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); - c += d7 >>> 13; - d7 &= 8191; - let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; - c = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); - c += d8 >>> 13; - d8 &= 8191; - let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; - c = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; - c += d9 >>> 13; - d9 &= 8191; - c = (c << 2) + c | 0; - c = c + d0 | 0; - d0 = c & 8191; - c = c >>> 13; - d1 += c; - h[0] = d0; - h[1] = d1; - h[2] = d2; - h[3] = d3; - h[4] = d4; - h[5] = d5; - h[6] = d6; - h[7] = d7; - h[8] = d8; - h[9] = d9; - } - finalize() { - const { h, pad } = this; - const g = new Uint16Array(10); - let c = h[1] >>> 13; - h[1] &= 8191; - for (let i = 2; i < 10; i++) { - h[i] += c; - c = h[i] >>> 13; - h[i] &= 8191; - } - h[0] += c * 5; - c = h[0] >>> 13; - h[0] &= 8191; - h[1] += c; - c = h[1] >>> 13; - h[1] &= 8191; - h[2] += c; - g[0] = h[0] + 5; - c = g[0] >>> 13; - g[0] &= 8191; - for (let i = 1; i < 10; i++) { - g[i] = h[i] + c; - c = g[i] >>> 13; - g[i] &= 8191; - } - g[9] -= 1 << 13; - let mask = (c ^ 1) - 1; - for (let i = 0; i < 10; i++) - g[i] &= mask; - mask = ~mask; - for (let i = 0; i < 10; i++) - h[i] = h[i] & mask | g[i]; - h[0] = (h[0] | h[1] << 13) & 65535; - h[1] = (h[1] >>> 3 | h[2] << 10) & 65535; - h[2] = (h[2] >>> 6 | h[3] << 7) & 65535; - h[3] = (h[3] >>> 9 | h[4] << 4) & 65535; - h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535; - h[5] = (h[6] >>> 2 | h[7] << 11) & 65535; - h[6] = (h[7] >>> 5 | h[8] << 8) & 65535; - h[7] = (h[8] >>> 8 | h[9] << 5) & 65535; - let f2 = h[0] + pad[0]; - h[0] = f2 & 65535; - for (let i = 1; i < 8; i++) { - f2 = (h[i] + pad[i] | 0) + (f2 >>> 16) | 0; - h[i] = f2 & 65535; - } - } - update(data) { - assert_default2.exists(this); - const { buffer, blockLen } = this; - data = toBytes2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - for (; blockLen <= len - pos; pos += blockLen) - this.process(data, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(buffer, 0, false); - this.pos = 0; - } - } - return this; - } - destroy() { - this.h.fill(0); - this.r.fill(0); - this.buffer.fill(0); - this.pad.fill(0); - } - digestInto(out) { - assert_default2.exists(this); - assert_default2.output(out, this); - this.finished = true; - const { buffer, h } = this; - let { pos } = this; - if (pos) { - buffer[pos++] = 1; - for (; pos < 16; pos++) - buffer[pos] = 0; - this.process(buffer, 0, true); - } - this.finalize(); - let opos = 0; - for (let i = 0; i < 8; i++) { - out[opos++] = h[i] >>> 0; - out[opos++] = h[i] >>> 8; - } - return out; - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - }; - function wrapConstructorWithKey(hashCons) { - const hashC = (msg, key) => hashCons(key).update(toBytes2(msg)).digest(); - const tmp = hashCons(new Uint8Array(32)); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (key) => hashCons(key); - return hashC; - } - var poly1305 = wrapConstructorWithKey((key) => new Poly1305(key)); + // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/_poly1305.js + var u8to16 = (a, i) => (a[i++] & 255) | ((a[i++] & 255) << 8); + var Poly1305 = class { + constructor(key) { + this.blockLen = 16; + this.outputLen = 16; + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.pos = 0; + this.finished = false; + key = toBytes2(key); + ensureBytes2(key, 32); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + this.r[0] = t0 & 8191; + this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 8191; + this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 7939; + this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 8191; + this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 255; + this.r[5] = (t4 >>> 1) & 8190; + this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 8191; + this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 8065; + this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 8191; + this.r[9] = (t7 >>> 5) & 127; + for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i); + } + process(data, offset, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + const h0 = h[0] + (t0 & 8191); + const h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 8191); + const h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 8191); + const h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 8191); + const h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 8191); + const h5 = h[5] + ((t4 >>> 1) & 8191); + const h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 8191); + const h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 8191); + const h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 8191); + const h9 = h[9] + ((t7 >>> 5) | hibit); + let c = 0; + let d0 = + c + + h0 * r0 + + h1 * (5 * r9) + + h2 * (5 * r8) + + h3 * (5 * r7) + + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 8191; + d0 += + h5 * (5 * r5) + + h6 * (5 * r4) + + h7 * (5 * r3) + + h8 * (5 * r2) + + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 8191; + let d1 = + c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 8191; + d1 += + h5 * (5 * r6) + + h6 * (5 * r5) + + h7 * (5 * r4) + + h8 * (5 * r3) + + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 8191; + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 8191; + d2 += + h5 * (5 * r7) + + h6 * (5 * r6) + + h7 * (5 * r5) + + h8 * (5 * r4) + + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 8191; + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 8191; + d3 += + h5 * (5 * r8) + + h6 * (5 * r7) + + h7 * (5 * r6) + + h8 * (5 * r5) + + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 8191; + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 8191; + d4 += + h5 * (5 * r9) + + h6 * (5 * r8) + + h7 * (5 * r7) + + h8 * (5 * r6) + + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 8191; + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 8191; + d5 += + h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 8191; + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 8191; + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 8191; + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 8191; + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 8191; + c = ((c << 2) + c) | 0; + c = (c + d0) | 0; + d0 = c & 8191; + c = c >>> 13; + d1 += c; + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 8191; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 8191; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 8191; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 8191; + h[2] += c; + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 8191; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 8191; + } + g[9] -= 1 << 13; + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i]; + h[0] = (h[0] | (h[1] << 13)) & 65535; + h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 65535; + h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 65535; + h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 65535; + h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 65535; + h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 65535; + h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 65535; + h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 65535; + let f2 = h[0] + pad[0]; + h[0] = f2 & 65535; + for (let i = 1; i < 8; i++) { + f2 = (((h[i] + pad[i]) | 0) + (f2 >>> 16)) | 0; + h[i] = f2 & 65535; + } + } + update(data) { + assert_default2.exists(this); + const { buffer, blockLen } = this; + data = toBytes2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.h.fill(0); + this.r.fill(0); + this.buffer.fill(0); + this.pad.fill(0); + } + digestInto(out) { + assert_default2.exists(this); + assert_default2.output(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + buffer[pos++] = 1; + for (; pos < 16; pos++) buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + return out; + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + }; + function wrapConstructorWithKey(hashCons) { + const hashC = (msg, key) => hashCons(key).update(toBytes2(msg)).digest(); + const tmp = hashCons(new Uint8Array(32)); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (key) => hashCons(key); + return hashC; + } + var poly1305 = wrapConstructorWithKey((key) => new Poly1305(key)); - // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/_salsa.js - var sigma16 = utf8ToBytes3("expand 16-byte k"); - var sigma32 = utf8ToBytes3("expand 32-byte k"); - var sigma16_32 = u32(sigma16); - var sigma32_32 = u32(sigma32); - var isAligned32 = (b) => !(b.byteOffset % 4); - var salsaBasic = (opts) => { - const { core, rounds, counterRight, counterLen, allow128bitKeys, extendNonceFn, blockLen } = checkOpts2({ rounds: 20, counterRight: false, counterLen: 8, allow128bitKeys: true, blockLen: 64 }, opts); - assert_default2.number(counterLen); - assert_default2.number(rounds); - assert_default2.number(blockLen); - assert_default2.bool(counterRight); - assert_default2.bool(allow128bitKeys); - const blockLen32 = blockLen / 4; - if (blockLen % 4 !== 0) - throw new Error("Salsa/ChaCha: blockLen must be aligned to 4 bytes"); - return (key, nonce, data, output3, counter = 0) => { - assert_default2.bytes(key); - assert_default2.bytes(nonce); - assert_default2.bytes(data); - if (!output3) - output3 = new Uint8Array(data.length); - assert_default2.bytes(output3); - assert_default2.number(counter); - if (counter < 0 || counter >= 2 ** 32 - 1) - throw new Error("Salsa/ChaCha: counter overflow"); - if (output3.length < data.length) { - throw new Error(`Salsa/ChaCha: output (${output3.length}) is shorter than data (${data.length})`); - } - const toClean = []; - let k, sigma; - if (key.length === 32) { - k = key; - sigma = sigma32_32; - } else if (key.length === 16 && allow128bitKeys) { - k = new Uint8Array(32); - k.set(key); - k.set(key, 16); - sigma = sigma16_32; - toClean.push(k); - } else - throw new Error(`Salsa/ChaCha: invalid 32-byte key, got length=${key.length}`); - if (extendNonceFn) { - if (nonce.length <= 16) - throw new Error(`Salsa/ChaCha: extended nonce must be bigger than 16 bytes`); - k = extendNonceFn(sigma, k, nonce.subarray(0, 16), new Uint8Array(32)); - toClean.push(k); - nonce = nonce.subarray(16); - } - const nonceLen = 16 - counterLen; - if (nonce.length !== nonceLen) - throw new Error(`Salsa/ChaCha: nonce must be ${nonceLen} or 16 bytes`); - if (nonceLen !== 12) { - const nc = new Uint8Array(12); - nc.set(nonce, counterRight ? 0 : 12 - nonce.length); - toClean.push(nonce = nc); - } - const block = new Uint8Array(blockLen); - const b32 = u32(block); - const k32 = u32(k); - const n32 = u32(nonce); - const d32 = isAligned32(data) && u32(data); - const o32 = isAligned32(output3) && u32(output3); - toClean.push(b32); - const len = data.length; - for (let pos = 0, ctr = counter; pos < len; ctr++) { - core(sigma, k32, n32, b32, ctr, rounds); - if (ctr >= 2 ** 32 - 1) - throw new Error("Salsa/ChaCha: counter overflow"); - const take = Math.min(blockLen, len - pos); - if (take === blockLen && o32 && d32) { - const pos32 = pos / 4; - if (pos % 4 !== 0) - throw new Error("Salsa/ChaCha: invalid block position"); - for (let j = 0; j < blockLen32; j++) - o32[pos32 + j] = d32[pos32 + j] ^ b32[j]; - pos += blockLen; - continue; - } - for (let j = 0; j < take; j++) - output3[pos + j] = data[pos + j] ^ block[j]; - pos += take; - } - for (let i = 0; i < toClean.length; i++) - toClean[i].fill(0); - return output3; - }; - }; + // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/_salsa.js + var sigma16 = utf8ToBytes3("expand 16-byte k"); + var sigma32 = utf8ToBytes3("expand 32-byte k"); + var sigma16_32 = u32(sigma16); + var sigma32_32 = u32(sigma32); + var isAligned32 = (b) => !(b.byteOffset % 4); + var salsaBasic = (opts) => { + const { + core, + rounds, + counterRight, + counterLen, + allow128bitKeys, + extendNonceFn, + blockLen, + } = checkOpts2( + { + rounds: 20, + counterRight: false, + counterLen: 8, + allow128bitKeys: true, + blockLen: 64, + }, + opts, + ); + assert_default2.number(counterLen); + assert_default2.number(rounds); + assert_default2.number(blockLen); + assert_default2.bool(counterRight); + assert_default2.bool(allow128bitKeys); + const blockLen32 = blockLen / 4; + if (blockLen % 4 !== 0) + throw new Error("Salsa/ChaCha: blockLen must be aligned to 4 bytes"); + return (key, nonce, data, output3, counter = 0) => { + assert_default2.bytes(key); + assert_default2.bytes(nonce); + assert_default2.bytes(data); + if (!output3) output3 = new Uint8Array(data.length); + assert_default2.bytes(output3); + assert_default2.number(counter); + if (counter < 0 || counter >= 2 ** 32 - 1) + throw new Error("Salsa/ChaCha: counter overflow"); + if (output3.length < data.length) { + throw new Error( + `Salsa/ChaCha: output (${output3.length}) is shorter than data (${data.length})`, + ); + } + const toClean = []; + let k, sigma; + if (key.length === 32) { + k = key; + sigma = sigma32_32; + } else if (key.length === 16 && allow128bitKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } else + throw new Error( + `Salsa/ChaCha: invalid 32-byte key, got length=${key.length}`, + ); + if (extendNonceFn) { + if (nonce.length <= 16) + throw new Error( + `Salsa/ChaCha: extended nonce must be bigger than 16 bytes`, + ); + k = extendNonceFn(sigma, k, nonce.subarray(0, 16), new Uint8Array(32)); + toClean.push(k); + nonce = nonce.subarray(16); + } + const nonceLen = 16 - counterLen; + if (nonce.length !== nonceLen) + throw new Error(`Salsa/ChaCha: nonce must be ${nonceLen} or 16 bytes`); + if (nonceLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + toClean.push((nonce = nc)); + } + const block = new Uint8Array(blockLen); + const b32 = u32(block); + const k32 = u32(k); + const n32 = u32(nonce); + const d32 = isAligned32(data) && u32(data); + const o32 = isAligned32(output3) && u32(output3); + toClean.push(b32); + const len = data.length; + for (let pos = 0, ctr = counter; pos < len; ctr++) { + core(sigma, k32, n32, b32, ctr, rounds); + if (ctr >= 2 ** 32 - 1) + throw new Error("Salsa/ChaCha: counter overflow"); + const take = Math.min(blockLen, len - pos); + if (take === blockLen && o32 && d32) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error("Salsa/ChaCha: invalid block position"); + for (let j = 0; j < blockLen32; j++) + o32[pos32 + j] = d32[pos32 + j] ^ b32[j]; + pos += blockLen; + continue; + } + for (let j = 0; j < take; j++) + output3[pos + j] = data[pos + j] ^ block[j]; + pos += take; + } + for (let i = 0; i < toClean.length; i++) toClean[i].fill(0); + return output3; + }; + }; - // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/chacha.js - var rotl2 = (a, b) => a << b | a >>> 32 - b; - function chachaCore(c, k, n, out, cnt, rounds = 20) { - let y00 = c[0], y01 = c[1], y02 = c[2], y03 = c[3]; - let y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3]; - let y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7]; - let y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - for (let i = 0; i < rounds; i += 2) { - x00 = x00 + x04 | 0; - x12 = rotl2(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl2(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl2(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl2(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl2(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl2(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl2(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl2(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl2(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl2(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl2(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl2(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl2(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl2(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl2(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl2(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl2(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl2(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl2(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl2(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl2(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl2(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl2(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl2(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl2(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl2(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl2(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl2(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl2(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl2(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl2(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl2(x04 ^ x09, 7); - } - let oi = 0; - out[oi++] = y00 + x00 | 0; - out[oi++] = y01 + x01 | 0; - out[oi++] = y02 + x02 | 0; - out[oi++] = y03 + x03 | 0; - out[oi++] = y04 + x04 | 0; - out[oi++] = y05 + x05 | 0; - out[oi++] = y06 + x06 | 0; - out[oi++] = y07 + x07 | 0; - out[oi++] = y08 + x08 | 0; - out[oi++] = y09 + x09 | 0; - out[oi++] = y10 + x10 | 0; - out[oi++] = y11 + x11 | 0; - out[oi++] = y12 + x12 | 0; - out[oi++] = y13 + x13 | 0; - out[oi++] = y14 + x14 | 0; - out[oi++] = y15 + x15 | 0; - } - var chacha20 = /* @__PURE__ */ salsaBasic({ - core: chachaCore, - counterRight: false, - counterLen: 4, - allow128bitKeys: false - }); + // node_modules/.pnpm/@noble+ciphers@0.2.0/node_modules/@noble/ciphers/esm/chacha.js + var rotl2 = (a, b) => (a << b) | (a >>> (32 - b)); + function chachaCore(c, k, n, out, cnt, rounds = 20) { + const y00 = c[0], + y01 = c[1], + y02 = c[2], + y03 = c[3]; + const y04 = k[0], + y05 = k[1], + y06 = k[2], + y07 = k[3]; + const y08 = k[4], + y09 = k[5], + y10 = k[6], + y11 = k[7]; + const y12 = cnt, + y13 = n[0], + y14 = n[1], + y15 = n[2]; + let x00 = y00, + x01 = y01, + x02 = y02, + x03 = y03, + x04 = y04, + x05 = y05, + x06 = y06, + x07 = y07, + x08 = y08, + x09 = y09, + x10 = y10, + x11 = y11, + x12 = y12, + x13 = y13, + x14 = y14, + x15 = y15; + for (let i = 0; i < rounds; i += 2) { + x00 = (x00 + x04) | 0; + x12 = rotl2(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = rotl2(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = rotl2(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = rotl2(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = rotl2(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = rotl2(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = rotl2(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = rotl2(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = rotl2(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = rotl2(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = rotl2(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = rotl2(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = rotl2(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = rotl2(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = rotl2(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = rotl2(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = rotl2(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = rotl2(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = rotl2(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = rotl2(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = rotl2(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = rotl2(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = rotl2(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = rotl2(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = rotl2(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = rotl2(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = rotl2(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = rotl2(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = rotl2(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = rotl2(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = rotl2(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = rotl2(x04 ^ x09, 7); + } + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; + } + var chacha20 = /* @__PURE__ */ salsaBasic({ + core: chachaCore, + counterRight: false, + counterLen: 4, + allow128bitKeys: false, + }); - // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/hkdf.js - function extract(hash3, ikm, salt2) { - assert_default.hash(hash3); - if (salt2 === void 0) - salt2 = new Uint8Array(hash3.outputLen); - return hmac(hash3, toBytes(salt2), toBytes(ikm)); - } - var HKDF_COUNTER = new Uint8Array([0]); - var EMPTY_BUFFER = new Uint8Array(); - function expand(hash3, prk, info, length = 32) { - assert_default.hash(hash3); - assert_default.number(length); - if (length > 255 * hash3.outputLen) - throw new Error("Length should be <= 255*HashLen"); - const blocks = Math.ceil(length / hash3.outputLen); - if (info === void 0) - info = EMPTY_BUFFER; - const okm = new Uint8Array(blocks * hash3.outputLen); - const HMAC2 = hmac.create(hash3, prk); - const HMACTmp = HMAC2._cloneInto(); - const T = new Uint8Array(HMAC2.outputLen); - for (let counter = 0; counter < blocks; counter++) { - HKDF_COUNTER[0] = counter + 1; - HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T); - okm.set(T, hash3.outputLen * counter); - HMAC2._cloneInto(HMACTmp); - } - HMAC2.destroy(); - HMACTmp.destroy(); - T.fill(0); - HKDF_COUNTER.fill(0); - return okm.slice(0, length); - } - var hkdf = (hash3, ikm, salt2, info, length) => expand(hash3, extract(hash3, ikm, salt2), info, length); + // node_modules/.pnpm/@noble+hashes@1.3.1/node_modules/@noble/hashes/esm/hkdf.js + function extract(hash3, ikm, salt2) { + assert_default.hash(hash3); + if (salt2 === void 0) salt2 = new Uint8Array(hash3.outputLen); + return hmac(hash3, toBytes(salt2), toBytes(ikm)); + } + var HKDF_COUNTER = new Uint8Array([0]); + var EMPTY_BUFFER = new Uint8Array(); + function expand(hash3, prk, info, length = 32) { + assert_default.hash(hash3); + assert_default.number(length); + if (length > 255 * hash3.outputLen) + throw new Error("Length should be <= 255*HashLen"); + const blocks = Math.ceil(length / hash3.outputLen); + if (info === void 0) info = EMPTY_BUFFER; + const okm = new Uint8Array(blocks * hash3.outputLen); + const HMAC2 = hmac.create(hash3, prk); + const HMACTmp = HMAC2._cloneInto(); + const T = new Uint8Array(HMAC2.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash3.outputLen * counter); + HMAC2._cloneInto(HMACTmp); + } + HMAC2.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); + } + var hkdf = (hash3, ikm, salt2, info, length) => + expand(hash3, extract(hash3, ikm, salt2), info, length); - // node_modules/.pnpm/nostr-tools@1.17.0/node_modules/nostr-tools/lib/esm/index.js - var __defProp2 = Object.defineProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - function getPublicKey(privateKey) { - return bytesToHex(schnorr.getPublicKey(privateKey)); - } - var utils_exports2 = {}; - __export2(utils_exports2, { - MessageNode: () => MessageNode, - MessageQueue: () => MessageQueue, - insertEventIntoAscendingList: () => insertEventIntoAscendingList, - insertEventIntoDescendingList: () => insertEventIntoDescendingList, - normalizeURL: () => normalizeURL, - utf8Decoder: () => utf8Decoder, - utf8Encoder: () => utf8Encoder - }); - var utf8Decoder = new TextDecoder("utf-8"); - var utf8Encoder = new TextEncoder(); - function normalizeURL(url) { - let p = new URL(url); - p.pathname = p.pathname.replace(/\/+/g, "/"); - if (p.pathname.endsWith("/")) - p.pathname = p.pathname.slice(0, -1); - if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") - p.port = ""; - p.searchParams.sort(); - p.hash = ""; - return p.toString(); - } - function insertEventIntoDescendingList(sortedArray, event) { - let start = 0; - let end = sortedArray.length - 1; - let midPoint; - let position = start; - if (end < 0) { - position = 0; - } else if (event.created_at < sortedArray[end].created_at) { - position = end + 1; - } else if (event.created_at >= sortedArray[start].created_at) { - position = start; - } else - while (true) { - if (end <= start + 1) { - position = end; - break; - } - midPoint = Math.floor(start + (end - start) / 2); - if (sortedArray[midPoint].created_at > event.created_at) { - start = midPoint; - } else if (sortedArray[midPoint].created_at < event.created_at) { - end = midPoint; - } else { - position = midPoint; - break; - } - } - if (sortedArray[position]?.id !== event.id) { - return [...sortedArray.slice(0, position), event, ...sortedArray.slice(position)]; - } - return sortedArray; - } - function insertEventIntoAscendingList(sortedArray, event) { - let start = 0; - let end = sortedArray.length - 1; - let midPoint; - let position = start; - if (end < 0) { - position = 0; - } else if (event.created_at > sortedArray[end].created_at) { - position = end + 1; - } else if (event.created_at <= sortedArray[start].created_at) { - position = start; - } else - while (true) { - if (end <= start + 1) { - position = end; - break; - } - midPoint = Math.floor(start + (end - start) / 2); - if (sortedArray[midPoint].created_at < event.created_at) { - start = midPoint; - } else if (sortedArray[midPoint].created_at > event.created_at) { - end = midPoint; - } else { - position = midPoint; - break; - } - } - if (sortedArray[position]?.id !== event.id) { - return [...sortedArray.slice(0, position), event, ...sortedArray.slice(position)]; - } - return sortedArray; - } - var MessageNode = class { - _value; - _next; - get value() { - return this._value; - } - set value(message) { - this._value = message; - } - get next() { - return this._next; - } - set next(node) { - this._next = node; - } - constructor(message) { - this._value = message; - this._next = null; - } - }; - var MessageQueue = class { - _first; - _last; - get first() { - return this._first; - } - set first(messageNode) { - this._first = messageNode; - } - get last() { - return this._last; - } - set last(messageNode) { - this._last = messageNode; - } - _size; - get size() { - return this._size; - } - set size(v) { - this._size = v; - } - constructor() { - this._first = null; - this._last = null; - this._size = 0; - } - enqueue(message) { - const newNode = new MessageNode(message); - if (this._size === 0 || !this._last) { - this._first = newNode; - this._last = newNode; - } else { - this._last.next = newNode; - this._last = newNode; - } - this._size++; - return true; - } - dequeue() { - if (this._size === 0 || !this._first) - return null; - let prev = this._first; - this._first = prev.next; - prev.next = null; - this._size--; - return prev.value; - } - }; - var verifiedSymbol = Symbol("verified"); - function getBlankEvent(kind = 255) { - return { - kind, - content: "", - tags: [], - created_at: 0 - }; - } - function finishEvent(t, privateKey) { - const event = t; - event.pubkey = getPublicKey(privateKey); - event.id = getEventHash(event); - event.sig = getSignature(event, privateKey); - event[verifiedSymbol] = true; - return event; - } - function serializeEvent(evt) { - if (!validateEvent(evt)) - throw new Error("can't serialize event with wrong or missing properties"); - return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); - } - function getEventHash(event) { - let eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); - return bytesToHex(eventHash); - } - var isRecord = (obj) => obj instanceof Object; - function validateEvent(event) { - if (!isRecord(event)) - return false; - if (typeof event.kind !== "number") - return false; - if (typeof event.content !== "string") - return false; - if (typeof event.created_at !== "number") - return false; - if (typeof event.pubkey !== "string") - return false; - if (!event.pubkey.match(/^[a-f0-9]{64}$/)) - return false; - if (!Array.isArray(event.tags)) - return false; - for (let i = 0; i < event.tags.length; i++) { - let tag = event.tags[i]; - if (!Array.isArray(tag)) - return false; - for (let j = 0; j < tag.length; j++) { - if (typeof tag[j] === "object") - return false; - } - } - return true; - } - function verifySignature(event) { - if (typeof event[verifiedSymbol] === "boolean") - return event[verifiedSymbol]; - const hash3 = getEventHash(event); - if (hash3 !== event.id) { - return event[verifiedSymbol] = false; - } - try { - return event[verifiedSymbol] = schnorr.verify(event.sig, hash3, event.pubkey); - } catch (err) { - return event[verifiedSymbol] = false; - } - } - function getSignature(event, key) { - return bytesToHex(schnorr.sign(getEventHash(event), key)); - } - var fakejson_exports = {}; - __export2(fakejson_exports, { - getHex64: () => getHex64, - getInt: () => getInt, - getSubscriptionId: () => getSubscriptionId, - matchEventId: () => matchEventId, - matchEventKind: () => matchEventKind, - matchEventPubkey: () => matchEventPubkey - }); - function getHex64(json, field) { - let len = field.length + 3; - let idx = json.indexOf(`"${field}":`) + len; - let s = json.slice(idx).indexOf(`"`) + idx + 1; - return json.slice(s, s + 64); - } - function getInt(json, field) { - let len = field.length; - let idx = json.indexOf(`"${field}":`) + len + 3; - let sliced = json.slice(idx); - let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); - return parseInt(sliced.slice(0, end), 10); - } - function getSubscriptionId(json) { - let idx = json.slice(0, 22).indexOf(`"EVENT"`); - if (idx === -1) - return null; - let pstart = json.slice(idx + 7 + 1).indexOf(`"`); - if (pstart === -1) - return null; - let start = idx + 7 + 1 + pstart; - let pend = json.slice(start + 1, 80).indexOf(`"`); - if (pend === -1) - return null; - let end = start + 1 + pend; - return json.slice(start + 1, end); - } - function matchEventId(json, id) { - return id === getHex64(json, "id"); - } - function matchEventPubkey(json, pubkey) { - return pubkey === getHex64(json, "pubkey"); - } - function matchEventKind(json, kind) { - return kind === getInt(json, "kind"); - } - var nip19_exports = {}; - __export2(nip19_exports, { - BECH32_REGEX: () => BECH32_REGEX, - decode: () => decode, - naddrEncode: () => naddrEncode, - neventEncode: () => neventEncode, - noteEncode: () => noteEncode, - nprofileEncode: () => nprofileEncode, - npubEncode: () => npubEncode, - nrelayEncode: () => nrelayEncode, - nsecEncode: () => nsecEncode - }); - var Bech32MaxSize = 5e3; - var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; - function integerToUint8Array(number3) { - const uint8Array = new Uint8Array(4); - uint8Array[0] = number3 >> 24 & 255; - uint8Array[1] = number3 >> 16 & 255; - uint8Array[2] = number3 >> 8 & 255; - uint8Array[3] = number3 & 255; - return uint8Array; - } - function decode(nip19) { - let { prefix, words } = bech32.decode(nip19, Bech32MaxSize); - let data = new Uint8Array(bech32.fromWords(words)); - switch (prefix) { - case "nprofile": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nprofile"); - if (tlv[0][0].length !== 32) - throw new Error("TLV 0 should be 32 bytes"); - return { - type: "nprofile", - data: { - pubkey: bytesToHex(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] - } - }; - } - case "nevent": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nevent"); - if (tlv[0][0].length !== 32) - throw new Error("TLV 0 should be 32 bytes"); - if (tlv[2] && tlv[2][0].length !== 32) - throw new Error("TLV 2 should be 32 bytes"); - if (tlv[3] && tlv[3][0].length !== 4) - throw new Error("TLV 3 should be 4 bytes"); - return { - type: "nevent", - data: { - id: bytesToHex(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], - author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : void 0, - kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : void 0 - } - }; - } - case "naddr": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for naddr"); - if (!tlv[2]?.[0]) - throw new Error("missing TLV 2 for naddr"); - if (tlv[2][0].length !== 32) - throw new Error("TLV 2 should be 32 bytes"); - if (!tlv[3]?.[0]) - throw new Error("missing TLV 3 for naddr"); - if (tlv[3][0].length !== 4) - throw new Error("TLV 3 should be 4 bytes"); - return { - type: "naddr", - data: { - identifier: utf8Decoder.decode(tlv[0][0]), - pubkey: bytesToHex(tlv[2][0]), - kind: parseInt(bytesToHex(tlv[3][0]), 16), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] - } - }; - } - case "nrelay": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nrelay"); - return { - type: "nrelay", - data: utf8Decoder.decode(tlv[0][0]) - }; - } - case "nsec": - case "npub": - case "note": - return { type: prefix, data: bytesToHex(data) }; - default: - throw new Error(`unknown prefix ${prefix}`); - } - } - function parseTLV(data) { - let result = {}; - let rest = data; - while (rest.length > 0) { - let t = rest[0]; - let l = rest[1]; - if (!l) - throw new Error(`malformed TLV ${t}`); - let v = rest.slice(2, 2 + l); - rest = rest.slice(2 + l); - if (v.length < l) - throw new Error(`not enough data to read on TLV ${t}`); - result[t] = result[t] || []; - result[t].push(v); - } - return result; - } - function nsecEncode(hex2) { - return encodeBytes("nsec", hex2); - } - function npubEncode(hex2) { - return encodeBytes("npub", hex2); - } - function noteEncode(hex2) { - return encodeBytes("note", hex2); - } - function encodeBech32(prefix, data) { - let words = bech32.toWords(data); - return bech32.encode(prefix, words, Bech32MaxSize); - } - function encodeBytes(prefix, hex2) { - let data = hexToBytes(hex2); - return encodeBech32(prefix, data); - } - function nprofileEncode(profile) { - let data = encodeTLV({ - 0: [hexToBytes(profile.pubkey)], - 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) - }); - return encodeBech32("nprofile", data); - } - function neventEncode(event) { - let kindArray; - if (event.kind != void 0) { - kindArray = integerToUint8Array(event.kind); - } - let data = encodeTLV({ - 0: [hexToBytes(event.id)], - 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), - 2: event.author ? [hexToBytes(event.author)] : [], - 3: kindArray ? [new Uint8Array(kindArray)] : [] - }); - return encodeBech32("nevent", data); - } - function naddrEncode(addr) { - let kind = new ArrayBuffer(4); - new DataView(kind).setUint32(0, addr.kind, false); - let data = encodeTLV({ - 0: [utf8Encoder.encode(addr.identifier)], - 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), - 2: [hexToBytes(addr.pubkey)], - 3: [new Uint8Array(kind)] - }); - return encodeBech32("naddr", data); - } - function nrelayEncode(url) { - let data = encodeTLV({ - 0: [utf8Encoder.encode(url)] - }); - return encodeBech32("nrelay", data); - } - function encodeTLV(tlv) { - let entries = []; - Object.entries(tlv).forEach(([t, vs]) => { - vs.forEach((v) => { - let entry = new Uint8Array(v.length + 2); - entry.set([parseInt(t)], 0); - entry.set([v.length], 1); - entry.set(v, 2); - entries.push(entry); - }); - }); - return concatBytes(...entries); - } - var nip04_exports = {}; - __export2(nip04_exports, { - decrypt: () => decrypt, - encrypt: () => encrypt - }); - if (typeof crypto !== "undefined" && !crypto.subtle && crypto.webcrypto) { - crypto.subtle = crypto.webcrypto.subtle; - } - async function encrypt(privkey, pubkey, text) { - const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); - const normalizedKey = getNormalizedX(key); - let iv = Uint8Array.from(randomBytes(16)); - let plaintext = utf8Encoder.encode(text); - let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, { name: "AES-CBC" }, false, ["encrypt"]); - let ciphertext = await crypto.subtle.encrypt({ name: "AES-CBC", iv }, cryptoKey, plaintext); - let ctb64 = base64.encode(new Uint8Array(ciphertext)); - let ivb64 = base64.encode(new Uint8Array(iv.buffer)); - return `${ctb64}?iv=${ivb64}`; - } - async function decrypt(privkey, pubkey, data) { - let [ctb64, ivb64] = data.split("?iv="); - let key = secp256k1.getSharedSecret(privkey, "02" + pubkey); - let normalizedKey = getNormalizedX(key); - let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, { name: "AES-CBC" }, false, ["decrypt"]); - let ciphertext = base64.decode(ctb64); - let iv = base64.decode(ivb64); - let plaintext = await crypto.subtle.decrypt({ name: "AES-CBC", iv }, cryptoKey, ciphertext); - let text = utf8Decoder.decode(plaintext); - return text; - } - function getNormalizedX(key) { - return key.slice(1, 33); - } - var nip05_exports = {}; - __export2(nip05_exports, { - NIP05_REGEX: () => NIP05_REGEX, - queryProfile: () => queryProfile, - searchDomain: () => searchDomain, - useFetchImplementation: () => useFetchImplementation - }); - var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w.-]+)$/; - var _fetch; - try { - _fetch = fetch; - } catch { - } - function useFetchImplementation(fetchImplementation) { - _fetch = fetchImplementation; - } - async function searchDomain(domain, query = "") { - try { - let res = await (await _fetch(`https://${domain}/.well-known/nostr.json?name=${query}`)).json(); - return res.names; - } catch (_) { - return {}; - } - } - async function queryProfile(fullname) { - const match = fullname.match(NIP05_REGEX); - if (!match) - return null; - const [_, name = "_", domain] = match; - try { - const res = await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`); - const { names, relays } = parseNIP05Result(await res.json()); - const pubkey = names[name]; - return pubkey ? { pubkey, relays: relays?.[pubkey] } : null; - } catch (_e) { - return null; - } - } - function parseNIP05Result(json) { - const result = { - names: {} - }; - for (const [name, pubkey] of Object.entries(json.names)) { - if (typeof name === "string" && typeof pubkey === "string") { - result.names[name] = pubkey; - } - } - if (json.relays) { - result.relays = {}; - for (const [pubkey, relays] of Object.entries(json.relays)) { - if (typeof pubkey === "string" && Array.isArray(relays)) { - result.relays[pubkey] = relays.filter((relay) => typeof relay === "string"); - } - } - } - return result; - } - var nip06_exports = {}; - __export2(nip06_exports, { - generateSeedWords: () => generateSeedWords, - privateKeyFromSeedWords: () => privateKeyFromSeedWords, - validateWords: () => validateWords - }); - function privateKeyFromSeedWords(mnemonic, passphrase) { - let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)); - let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey; - if (!privateKey) - throw new Error("could not derive private key"); - return bytesToHex(privateKey); - } - function generateSeedWords() { - return generateMnemonic(wordlist); - } - function validateWords(words) { - return validateMnemonic(words, wordlist); - } - var nip10_exports = {}; - __export2(nip10_exports, { - parse: () => parse - }); - function parse(event) { - const result = { - reply: void 0, - root: void 0, - mentions: [], - profiles: [] - }; - const eTags = []; - for (const tag of event.tags) { - if (tag[0] === "e" && tag[1]) { - eTags.push(tag); - } - if (tag[0] === "p" && tag[1]) { - result.profiles.push({ - pubkey: tag[1], - relays: tag[2] ? [tag[2]] : [] - }); - } - } - for (let eTagIndex = 0; eTagIndex < eTags.length; eTagIndex++) { - const eTag = eTags[eTagIndex]; - const [_, eTagEventId, eTagRelayUrl, eTagMarker] = eTag; - const eventPointer = { - id: eTagEventId, - relays: eTagRelayUrl ? [eTagRelayUrl] : [] - }; - const isFirstETag = eTagIndex === 0; - const isLastETag = eTagIndex === eTags.length - 1; - if (eTagMarker === "root") { - result.root = eventPointer; - continue; - } - if (eTagMarker === "reply") { - result.reply = eventPointer; - continue; - } - if (eTagMarker === "mention") { - result.mentions.push(eventPointer); - continue; - } - if (isFirstETag) { - result.root = eventPointer; - continue; - } - if (isLastETag) { - result.reply = eventPointer; - continue; - } - result.mentions.push(eventPointer); - } - return result; - } - var nip13_exports = {}; - __export2(nip13_exports, { - getPow: () => getPow, - minePow: () => minePow - }); - function getPow(hex2) { - let count = 0; - for (let i = 0; i < hex2.length; i++) { - const nibble = parseInt(hex2[i], 16); - if (nibble === 0) { - count += 4; - } else { - count += Math.clz32(nibble) - 28; - break; - } - } - return count; - } - function minePow(unsigned, difficulty) { - let count = 0; - const event = unsigned; - const tag = ["nonce", count.toString(), difficulty.toString()]; - event.tags.push(tag); - while (true) { - const now = Math.floor(new Date().getTime() / 1e3); - if (now !== event.created_at) { - count = 0; - event.created_at = now; - } - tag[1] = (++count).toString(); - event.id = getEventHash(event); - if (getPow(event.id) >= difficulty) { - break; - } - } - return event; - } - var nip18_exports = {}; - __export2(nip18_exports, { - finishRepostEvent: () => finishRepostEvent, - getRepostedEvent: () => getRepostedEvent, - getRepostedEventPointer: () => getRepostedEventPointer - }); - function finishRepostEvent(t, reposted, relayUrl, privateKey) { - return finishEvent( - { - kind: 6, - tags: [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]], - content: t.content === "" ? "" : JSON.stringify(reposted), - created_at: t.created_at - }, - privateKey - ); - } - function getRepostedEventPointer(event) { - if (event.kind !== 6) { - return void 0; - } - let lastETag; - let lastPTag; - for (let i = event.tags.length - 1; i >= 0 && (lastETag === void 0 || lastPTag === void 0); i--) { - const tag = event.tags[i]; - if (tag.length >= 2) { - if (tag[0] === "e" && lastETag === void 0) { - lastETag = tag; - } else if (tag[0] === "p" && lastPTag === void 0) { - lastPTag = tag; - } - } - } - if (lastETag === void 0) { - return void 0; - } - return { - id: lastETag[1], - relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), - author: lastPTag?.[1] - }; - } - function getRepostedEvent(event, { skipVerification } = {}) { - const pointer = getRepostedEventPointer(event); - if (pointer === void 0 || event.content === "") { - return void 0; - } - let repostedEvent; - try { - repostedEvent = JSON.parse(event.content); - } catch (error) { - return void 0; - } - if (repostedEvent.id !== pointer.id) { - return void 0; - } - if (!skipVerification && !verifySignature(repostedEvent)) { - return void 0; - } - return repostedEvent; - } - var nip21_exports = {}; - __export2(nip21_exports, { - NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, - parse: () => parse2, - test: () => test - }); - var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); - function test(value) { - return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); - } - function parse2(uri) { - const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); - if (!match) - throw new Error(`Invalid Nostr URI: ${uri}`); - return { - uri: match[0], - value: match[1], - decoded: decode(match[1]) - }; - } - var nip25_exports = {}; - __export2(nip25_exports, { - finishReactionEvent: () => finishReactionEvent, - getReactedEventPointer: () => getReactedEventPointer - }); - function finishReactionEvent(t, reacted, privateKey) { - const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); - return finishEvent( - { - ...t, - kind: 7, - tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], - content: t.content ?? "+" - }, - privateKey - ); - } - function getReactedEventPointer(event) { - if (event.kind !== 7) { - return void 0; - } - let lastETag; - let lastPTag; - for (let i = event.tags.length - 1; i >= 0 && (lastETag === void 0 || lastPTag === void 0); i--) { - const tag = event.tags[i]; - if (tag.length >= 2) { - if (tag[0] === "e" && lastETag === void 0) { - lastETag = tag; - } else if (tag[0] === "p" && lastPTag === void 0) { - lastPTag = tag; - } - } - } - if (lastETag === void 0 || lastPTag === void 0) { - return void 0; - } - return { - id: lastETag[1], - relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), - author: lastPTag[1] - }; - } - var nip26_exports = {}; - __export2(nip26_exports, { - createDelegation: () => createDelegation, - getDelegator: () => getDelegator - }); - function createDelegation(privateKey, parameters) { - let conditions = []; - if ((parameters.kind || -1) >= 0) - conditions.push(`kind=${parameters.kind}`); - if (parameters.until) - conditions.push(`created_at<${parameters.until}`); - if (parameters.since) - conditions.push(`created_at>${parameters.since}`); - let cond = conditions.join("&"); - if (cond === "") - throw new Error("refusing to create a delegation without any conditions"); - let sighash = sha256(utf8Encoder.encode(`nostr:delegation:${parameters.pubkey}:${cond}`)); - let sig = bytesToHex(schnorr.sign(sighash, privateKey)); - return { - from: getPublicKey(privateKey), - to: parameters.pubkey, - cond, - sig - }; - } - function getDelegator(event) { - let tag = event.tags.find((tag2) => tag2[0] === "delegation" && tag2.length >= 4); - if (!tag) - return null; - let pubkey = tag[1]; - let cond = tag[2]; - let sig = tag[3]; - let conditions = cond.split("&"); - for (let i = 0; i < conditions.length; i++) { - let [key, operator, value] = conditions[i].split(/\b/); - if (key === "kind" && operator === "=" && event.kind === parseInt(value)) - continue; - else if (key === "created_at" && operator === "<" && event.created_at < parseInt(value)) - continue; - else if (key === "created_at" && operator === ">" && event.created_at > parseInt(value)) - continue; - else - return null; - } - let sighash = sha256(utf8Encoder.encode(`nostr:delegation:${event.pubkey}:${cond}`)); - if (!schnorr.verify(sig, sighash, pubkey)) - return null; - return pubkey; - } - var nip27_exports = {}; - __export2(nip27_exports, { - matchAll: () => matchAll, - regex: () => regex, - replaceAll: () => replaceAll - }); - var regex = () => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, "g"); - function* matchAll(content) { - const matches = content.matchAll(regex()); - for (const match of matches) { - try { - const [uri, value] = match; - yield { - uri, - value, - decoded: decode(value), - start: match.index, - end: match.index + uri.length - }; - } catch (_e) { - } - } - } - function replaceAll(content, replacer) { - return content.replaceAll(regex(), (uri, value) => { - return replacer({ - uri, - value, - decoded: decode(value) - }); - }); - } - var nip28_exports = {}; - __export2(nip28_exports, { - channelCreateEvent: () => channelCreateEvent, - channelHideMessageEvent: () => channelHideMessageEvent, - channelMessageEvent: () => channelMessageEvent, - channelMetadataEvent: () => channelMetadataEvent, - channelMuteUserEvent: () => channelMuteUserEvent - }); - var channelCreateEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finishEvent( - { - kind: 40, - tags: [...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); - }; - var channelMetadataEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finishEvent( - { - kind: 41, - tags: [["e", t.channel_create_event_id], ...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); - }; - var channelMessageEvent = (t, privateKey) => { - const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; - if (t.reply_to_channel_message_event_id) { - tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); - } - return finishEvent( - { - kind: 42, - tags: [...tags, ...t.tags ?? []], - content: t.content, - created_at: t.created_at - }, - privateKey - ); - }; - var channelHideMessageEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finishEvent( - { - kind: 43, - tags: [["e", t.channel_message_event_id], ...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); - }; - var channelMuteUserEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finishEvent( - { - kind: 44, - tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); - }; - var nip39_exports = {}; - __export2(nip39_exports, { - useFetchImplementation: () => useFetchImplementation2, - validateGithub: () => validateGithub - }); - var _fetch2; - try { - _fetch2 = fetch; - } catch { - } - function useFetchImplementation2(fetchImplementation) { - _fetch2 = fetchImplementation; - } - async function validateGithub(pubkey, username, proof) { - try { - let res = await (await _fetch2(`https://gist.github.com/${username}/${proof}/raw`)).text(); - return res === `Verifying that I control the following Nostr public key: ${pubkey}`; - } catch (_) { - return false; - } - } - var nip42_exports = {}; - __export2(nip42_exports, { - authenticate: () => authenticate - }); - var authenticate = async ({ - challenge: challenge2, - relay, - sign - }) => { - const e = { - kind: 22242, - created_at: Math.floor(Date.now() / 1e3), - tags: [ - ["relay", relay.url], - ["challenge", challenge2] - ], - content: "" - }; - return relay.auth(await sign(e)); - }; - var nip44_exports = {}; - __export2(nip44_exports, { - decrypt: () => decrypt2, - encrypt: () => encrypt2, - utils: () => utils2 - }); - var utils2 = { - v2: { - maxPlaintextSize: 65536 - 128, - minCiphertextSize: 100, - maxCiphertextSize: 102400, - getConversationKey(privkeyA, pubkeyB) { - const key = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB); - return key.subarray(1, 33); - }, - getMessageKeys(conversationKey, salt2) { - const keys = hkdf(sha256, conversationKey, salt2, "nip44-v2", 76); - return { - encryption: keys.subarray(0, 32), - nonce: keys.subarray(32, 44), - auth: keys.subarray(44, 76) - }; - }, - calcPadding(len) { - if (!Number.isSafeInteger(len) || len < 0) - throw new Error("expected positive integer"); - if (len <= 32) - return 32; - const nextpower = 1 << Math.floor(Math.log2(len - 1)) + 1; - const chunk = nextpower <= 256 ? 32 : nextpower / 8; - return chunk * (Math.floor((len - 1) / chunk) + 1); - }, - pad(unpadded) { - const unpaddedB = utf8Encoder.encode(unpadded); - const len = unpaddedB.length; - if (len < 1 || len >= utils2.v2.maxPlaintextSize) - throw new Error("invalid plaintext length: must be between 1b and 64KB"); - const paddedLen = utils2.v2.calcPadding(len); - const zeros = new Uint8Array(paddedLen - len); - const lenBuf = new Uint8Array(2); - new DataView(lenBuf.buffer).setUint16(0, len); - return concatBytes(lenBuf, unpaddedB, zeros); - }, - unpad(padded) { - const unpaddedLen = new DataView(padded.buffer).getUint16(0); - const unpadded = padded.subarray(2, 2 + unpaddedLen); - if (unpaddedLen === 0 || unpadded.length !== unpaddedLen || padded.length !== 2 + utils2.v2.calcPadding(unpaddedLen)) - throw new Error("invalid padding"); - return utf8Decoder.decode(unpadded); - } - } - }; - function encrypt2(key, plaintext, options = {}) { - const version = options.version ?? 2; - if (version !== 2) - throw new Error("unknown encryption version " + version); - const salt2 = options.salt ?? randomBytes(32); - ensureBytes2(salt2, 32); - const keys = utils2.v2.getMessageKeys(key, salt2); - const padded = utils2.v2.pad(plaintext); - const ciphertext = chacha20(keys.encryption, keys.nonce, padded); - const mac = hmac(sha256, keys.auth, ciphertext); - return base64.encode(concatBytes(new Uint8Array([version]), salt2, ciphertext, mac)); - } - function decrypt2(key, ciphertext) { - const u = utils2.v2; - ensureBytes2(key, 32); - const clen = ciphertext.length; - if (clen < u.minCiphertextSize || clen >= u.maxCiphertextSize) - throw new Error("invalid ciphertext length: " + clen); - if (ciphertext[0] === "#") - throw new Error("unknown encryption version"); - let data; - try { - data = base64.decode(ciphertext); - } catch (error) { - throw new Error("invalid base64: " + error.message); - } - const vers = data.subarray(0, 1)[0]; - if (vers !== 2) - throw new Error("unknown encryption version " + vers); - const salt2 = data.subarray(1, 33); - const ciphertext_ = data.subarray(33, -32); - const mac = data.subarray(-32); - const keys = u.getMessageKeys(key, salt2); - const calculatedMac = hmac(sha256, keys.auth, ciphertext_); - if (!equalBytes2(calculatedMac, mac)) - throw new Error("invalid MAC"); - const padded = chacha20(keys.encryption, keys.nonce, ciphertext_); - return u.unpad(padded); - } - var nip47_exports = {}; - __export2(nip47_exports, { - makeNwcRequestEvent: () => makeNwcRequestEvent, - parseConnectionString: () => parseConnectionString - }); - function parseConnectionString(connectionString) { - const { pathname, searchParams } = new URL(connectionString); - const pubkey = pathname; - const relay = searchParams.get("relay"); - const secret = searchParams.get("secret"); - if (!pubkey || !relay || !secret) { - throw new Error("invalid connection string"); - } - return { pubkey, relay, secret }; - } - async function makeNwcRequestEvent({ - pubkey, - secret, - invoice - }) { - const content = { - method: "pay_invoice", - params: { - invoice - } - }; - const encryptedContent = await encrypt(secret, pubkey, JSON.stringify(content)); - const eventTemplate = { - kind: 23194, - created_at: Math.round(Date.now() / 1e3), - content: encryptedContent, - tags: [["p", pubkey]] - }; - return finishEvent(eventTemplate, secret); - } - var nip57_exports = {}; - __export2(nip57_exports, { - getZapEndpoint: () => getZapEndpoint, - makeZapReceipt: () => makeZapReceipt, - makeZapRequest: () => makeZapRequest, - useFetchImplementation: () => useFetchImplementation3, - validateZapRequest: () => validateZapRequest - }); - var _fetch3; - try { - _fetch3 = fetch; - } catch { - } - function useFetchImplementation3(fetchImplementation) { - _fetch3 = fetchImplementation; - } - async function getZapEndpoint(metadata) { - try { - let lnurl = ""; - let { lud06, lud16 } = JSON.parse(metadata.content); - if (lud06) { - let { words } = bech32.decode(lud06, 1e3); - let data = bech32.fromWords(words); - lnurl = utf8Decoder.decode(data); - } else if (lud16) { - let [name, domain] = lud16.split("@"); - lnurl = `https://${domain}/.well-known/lnurlp/${name}`; - } else { - return null; - } - let res = await _fetch3(lnurl); - let body = await res.json(); - if (body.allowsNostr && body.nostrPubkey) { - return body.callback; - } - } catch (err) { - } - return null; - } - function makeZapRequest({ - profile, - event, - amount, - relays, - comment = "" - }) { - if (!amount) - throw new Error("amount not given"); - if (!profile) - throw new Error("profile not given"); - let zr = { - kind: 9734, - created_at: Math.round(Date.now() / 1e3), - content: comment, - tags: [ - ["p", profile], - ["amount", amount.toString()], - ["relays", ...relays] - ] - }; - if (event) { - zr.tags.push(["e", event]); - } - return zr; - } - function validateZapRequest(zapRequestString) { - let zapRequest; - try { - zapRequest = JSON.parse(zapRequestString); - } catch (err) { - return "Invalid zap request JSON."; - } - if (!validateEvent(zapRequest)) - return "Zap request is not a valid Nostr event."; - if (!verifySignature(zapRequest)) - return "Invalid signature on zap request."; - let p = zapRequest.tags.find(([t, v]) => t === "p" && v); - if (!p) - return "Zap request doesn't have a 'p' tag."; - if (!p[1].match(/^[a-f0-9]{64}$/)) - return "Zap request 'p' tag is not valid hex."; - let e = zapRequest.tags.find(([t, v]) => t === "e" && v); - if (e && !e[1].match(/^[a-f0-9]{64}$/)) - return "Zap request 'e' tag is not valid hex."; - let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); - if (!relays) - return "Zap request doesn't have a 'relays' tag."; - return null; - } - function makeZapReceipt({ - zapRequest, - preimage, - bolt11, - paidAt - }) { - let zr = JSON.parse(zapRequest); - let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); - let zap = { - kind: 9735, - created_at: Math.round(paidAt.getTime() / 1e3), - content: "", - tags: [...tagsFromZapRequest, ["bolt11", bolt11], ["description", zapRequest]] - }; - if (preimage) { - zap.tags.push(["preimage", preimage]); - } - return zap; - } - var nip98_exports = {}; - __export2(nip98_exports, { - getToken: () => getToken, - unpackEventFromToken: () => unpackEventFromToken, - validateEvent: () => validateEvent2, - validateToken: () => validateToken - }); - var _authorizationScheme = "Nostr "; - async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false) { - if (!loginUrl || !httpMethod) - throw new Error("Missing loginUrl or httpMethod"); - const event = getBlankEvent(27235); - event.tags = [ - ["u", loginUrl], - ["method", httpMethod] - ]; - event.created_at = Math.round(new Date().getTime() / 1e3); - const signedEvent = await sign(event); - const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; - return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); - } - async function validateToken(token, url, method) { - const event = await unpackEventFromToken(token).catch((error) => { - throw error; - }); - const valid = await validateEvent2(event, url, method).catch((error) => { - throw error; - }); - return valid; - } - async function unpackEventFromToken(token) { - if (!token) { - throw new Error("Missing token"); - } - token = token.replace(_authorizationScheme, ""); - const eventB64 = utf8Decoder.decode(base64.decode(token)); - if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { - throw new Error("Invalid token"); - } - const event = JSON.parse(eventB64); - return event; - } - async function validateEvent2(event, url, method) { - if (!event) { - throw new Error("Invalid nostr event"); - } - if (!verifySignature(event)) { - throw new Error("Invalid nostr event, signature invalid"); - } - if (event.kind !== 27235) { - throw new Error("Invalid nostr event, kind invalid"); - } - if (!event.created_at) { - throw new Error("Invalid nostr event, created_at invalid"); - } - if (Math.round(new Date().getTime() / 1e3) - event.created_at > 60) { - throw new Error("Invalid nostr event, expired"); - } - const urlTag = event.tags.find((t) => t[0] === "u"); - if (urlTag?.length !== 1 && urlTag?.[1] !== url) { - throw new Error("Invalid nostr event, url tag invalid"); - } - const methodTag = event.tags.find((t) => t[0] === "method"); - if (methodTag?.length !== 1 && methodTag?.[1].toLowerCase() !== method.toLowerCase()) { - throw new Error("Invalid nostr event, method tag invalid"); - } - return true; - } + // node_modules/.pnpm/nostr-tools@1.17.0/node_modules/nostr-tools/lib/esm/index.js + var __defProp2 = Object.defineProperty; + var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + function getPublicKey(privateKey) { + return bytesToHex(schnorr.getPublicKey(privateKey)); + } + var utils_exports2 = {}; + __export2(utils_exports2, { + MessageNode: () => MessageNode, + MessageQueue: () => MessageQueue, + insertEventIntoAscendingList: () => insertEventIntoAscendingList, + insertEventIntoDescendingList: () => insertEventIntoDescendingList, + normalizeURL: () => normalizeURL, + utf8Decoder: () => utf8Decoder, + utf8Encoder: () => utf8Encoder, + }); + var utf8Decoder = new TextDecoder("utf-8"); + var utf8Encoder = new TextEncoder(); + function normalizeURL(url) { + const p = new URL(url); + p.pathname = p.pathname.replace(/\/+/g, "/"); + if (p.pathname.endsWith("/")) p.pathname = p.pathname.slice(0, -1); + if ( + (p.port === "80" && p.protocol === "ws:") || + (p.port === "443" && p.protocol === "wss:") + ) + p.port = ""; + p.searchParams.sort(); + p.hash = ""; + return p.toString(); + } + function insertEventIntoDescendingList(sortedArray, event) { + let start = 0; + let end = sortedArray.length - 1; + let midPoint; + let position = start; + if (end < 0) { + position = 0; + } else if (event.created_at < sortedArray[end].created_at) { + position = end + 1; + } else if (event.created_at >= sortedArray[start].created_at) { + position = start; + } else + while (true) { + if (end <= start + 1) { + position = end; + break; + } + midPoint = Math.floor(start + (end - start) / 2); + if (sortedArray[midPoint].created_at > event.created_at) { + start = midPoint; + } else if (sortedArray[midPoint].created_at < event.created_at) { + end = midPoint; + } else { + position = midPoint; + break; + } + } + if (sortedArray[position]?.id !== event.id) { + return [ + ...sortedArray.slice(0, position), + event, + ...sortedArray.slice(position), + ]; + } + return sortedArray; + } + function insertEventIntoAscendingList(sortedArray, event) { + let start = 0; + let end = sortedArray.length - 1; + let midPoint; + let position = start; + if (end < 0) { + position = 0; + } else if (event.created_at > sortedArray[end].created_at) { + position = end + 1; + } else if (event.created_at <= sortedArray[start].created_at) { + position = start; + } else + while (true) { + if (end <= start + 1) { + position = end; + break; + } + midPoint = Math.floor(start + (end - start) / 2); + if (sortedArray[midPoint].created_at < event.created_at) { + start = midPoint; + } else if (sortedArray[midPoint].created_at > event.created_at) { + end = midPoint; + } else { + position = midPoint; + break; + } + } + if (sortedArray[position]?.id !== event.id) { + return [ + ...sortedArray.slice(0, position), + event, + ...sortedArray.slice(position), + ]; + } + return sortedArray; + } + var MessageNode = class { + _value; + _next; + get value() { + return this._value; + } + set value(message) { + this._value = message; + } + get next() { + return this._next; + } + set next(node) { + this._next = node; + } + constructor(message) { + this._value = message; + this._next = null; + } + }; + var MessageQueue = class { + _first; + _last; + get first() { + return this._first; + } + set first(messageNode) { + this._first = messageNode; + } + get last() { + return this._last; + } + set last(messageNode) { + this._last = messageNode; + } + _size; + get size() { + return this._size; + } + set size(v) { + this._size = v; + } + constructor() { + this._first = null; + this._last = null; + this._size = 0; + } + enqueue(message) { + const newNode = new MessageNode(message); + if (this._size === 0 || !this._last) { + this._first = newNode; + this._last = newNode; + } else { + this._last.next = newNode; + this._last = newNode; + } + this._size++; + return true; + } + dequeue() { + if (this._size === 0 || !this._first) return null; + const prev = this._first; + this._first = prev.next; + prev.next = null; + this._size--; + return prev.value; + } + }; + var verifiedSymbol = Symbol("verified"); + function getBlankEvent(kind = 255) { + return { + kind, + content: "", + tags: [], + created_at: 0, + }; + } + function finishEvent(t, privateKey) { + const event = t; + event.pubkey = getPublicKey(privateKey); + event.id = getEventHash(event); + event.sig = getSignature(event, privateKey); + event[verifiedSymbol] = true; + return event; + } + function serializeEvent(evt) { + if (!validateEvent(evt)) + throw new Error("can't serialize event with wrong or missing properties"); + return JSON.stringify([ + 0, + evt.pubkey, + evt.created_at, + evt.kind, + evt.tags, + evt.content, + ]); + } + function getEventHash(event) { + const eventHash = sha256(utf8Encoder.encode(serializeEvent(event))); + return bytesToHex(eventHash); + } + var isRecord = (obj) => obj instanceof Object; + function validateEvent(event) { + if (!isRecord(event)) return false; + if (typeof event.kind !== "number") return false; + if (typeof event.content !== "string") return false; + if (typeof event.created_at !== "number") return false; + if (typeof event.pubkey !== "string") return false; + if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false; + if (!Array.isArray(event.tags)) return false; + for (let i = 0; i < event.tags.length; i++) { + const tag = event.tags[i]; + if (!Array.isArray(tag)) return false; + for (let j = 0; j < tag.length; j++) { + if (typeof tag[j] === "object") return false; + } + } + return true; + } + function verifySignature(event) { + if (typeof event[verifiedSymbol] === "boolean") + return event[verifiedSymbol]; + const hash3 = getEventHash(event); + if (hash3 !== event.id) { + return (event[verifiedSymbol] = false); + } + try { + return (event[verifiedSymbol] = schnorr.verify( + event.sig, + hash3, + event.pubkey, + )); + } catch (err) { + return (event[verifiedSymbol] = false); + } + } + function getSignature(event, key) { + return bytesToHex(schnorr.sign(getEventHash(event), key)); + } + var fakejson_exports = {}; + __export2(fakejson_exports, { + getHex64: () => getHex64, + getInt: () => getInt, + getSubscriptionId: () => getSubscriptionId, + matchEventId: () => matchEventId, + matchEventKind: () => matchEventKind, + matchEventPubkey: () => matchEventPubkey, + }); + function getHex64(json, field) { + const len = field.length + 3; + const idx = json.indexOf(`"${field}":`) + len; + const s = json.slice(idx).indexOf(`"`) + idx + 1; + return json.slice(s, s + 64); + } + function getInt(json, field) { + const len = field.length; + const idx = json.indexOf(`"${field}":`) + len + 3; + const sliced = json.slice(idx); + const end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); + return Number.parseInt(sliced.slice(0, end), 10); + } + function getSubscriptionId(json) { + const idx = json.slice(0, 22).indexOf(`"EVENT"`); + if (idx === -1) return null; + const pstart = json.slice(idx + 7 + 1).indexOf(`"`); + if (pstart === -1) return null; + const start = idx + 7 + 1 + pstart; + const pend = json.slice(start + 1, 80).indexOf(`"`); + if (pend === -1) return null; + const end = start + 1 + pend; + return json.slice(start + 1, end); + } + function matchEventId(json, id) { + return id === getHex64(json, "id"); + } + function matchEventPubkey(json, pubkey) { + return pubkey === getHex64(json, "pubkey"); + } + function matchEventKind(json, kind) { + return kind === getInt(json, "kind"); + } + var nip19_exports = {}; + __export2(nip19_exports, { + BECH32_REGEX: () => BECH32_REGEX, + decode: () => decode, + naddrEncode: () => naddrEncode, + neventEncode: () => neventEncode, + noteEncode: () => noteEncode, + nprofileEncode: () => nprofileEncode, + npubEncode: () => npubEncode, + nrelayEncode: () => nrelayEncode, + nsecEncode: () => nsecEncode, + }); + var Bech32MaxSize = 5e3; + var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; + function integerToUint8Array(number3) { + const uint8Array = new Uint8Array(4); + uint8Array[0] = (number3 >> 24) & 255; + uint8Array[1] = (number3 >> 16) & 255; + uint8Array[2] = (number3 >> 8) & 255; + uint8Array[3] = number3 & 255; + return uint8Array; + } + function decode(nip19) { + const { prefix, words } = bech32.decode(nip19, Bech32MaxSize); + const data = new Uint8Array(bech32.fromWords(words)); + switch (prefix) { + case "nprofile": { + const tlv = parseTLV(data); + if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for nprofile"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + return { + type: "nprofile", + data: { + pubkey: bytesToHex(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + }, + }; + } + case "nevent": { + const tlv = parseTLV(data); + if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for nevent"); + if (tlv[0][0].length !== 32) + throw new Error("TLV 0 should be 32 bytes"); + if (tlv[2] && tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (tlv[3] && tlv[3][0].length !== 4) + throw new Error("TLV 3 should be 4 bytes"); + return { + type: "nevent", + data: { + id: bytesToHex(tlv[0][0]), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : void 0, + kind: tlv[3]?.[0] + ? Number.parseInt(bytesToHex(tlv[3][0]), 16) + : void 0, + }, + }; + } + case "naddr": { + const tlv = parseTLV(data); + if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for naddr"); + if (!tlv[2]?.[0]) throw new Error("missing TLV 2 for naddr"); + if (tlv[2][0].length !== 32) + throw new Error("TLV 2 should be 32 bytes"); + if (!tlv[3]?.[0]) throw new Error("missing TLV 3 for naddr"); + if (tlv[3][0].length !== 4) throw new Error("TLV 3 should be 4 bytes"); + return { + type: "naddr", + data: { + identifier: utf8Decoder.decode(tlv[0][0]), + pubkey: bytesToHex(tlv[2][0]), + kind: Number.parseInt(bytesToHex(tlv[3][0]), 16), + relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], + }, + }; + } + case "nrelay": { + const tlv = parseTLV(data); + if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for nrelay"); + return { + type: "nrelay", + data: utf8Decoder.decode(tlv[0][0]), + }; + } + case "nsec": + case "npub": + case "note": + return { type: prefix, data: bytesToHex(data) }; + default: + throw new Error(`unknown prefix ${prefix}`); + } + } + function parseTLV(data) { + const result = {}; + let rest = data; + while (rest.length > 0) { + const t = rest[0]; + const l = rest[1]; + if (!l) throw new Error(`malformed TLV ${t}`); + const v = rest.slice(2, 2 + l); + rest = rest.slice(2 + l); + if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`); + result[t] = result[t] || []; + result[t].push(v); + } + return result; + } + function nsecEncode(hex2) { + return encodeBytes("nsec", hex2); + } + function npubEncode(hex2) { + return encodeBytes("npub", hex2); + } + function noteEncode(hex2) { + return encodeBytes("note", hex2); + } + function encodeBech32(prefix, data) { + const words = bech32.toWords(data); + return bech32.encode(prefix, words, Bech32MaxSize); + } + function encodeBytes(prefix, hex2) { + const data = hexToBytes(hex2); + return encodeBech32(prefix, data); + } + function nprofileEncode(profile) { + const data = encodeTLV({ + 0: [hexToBytes(profile.pubkey)], + 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)), + }); + return encodeBech32("nprofile", data); + } + function neventEncode(event) { + let kindArray; + if (event.kind != void 0) { + kindArray = integerToUint8Array(event.kind); + } + const data = encodeTLV({ + 0: [hexToBytes(event.id)], + 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), + 2: event.author ? [hexToBytes(event.author)] : [], + 3: kindArray ? [new Uint8Array(kindArray)] : [], + }); + return encodeBech32("nevent", data); + } + function naddrEncode(addr) { + const kind = new ArrayBuffer(4); + new DataView(kind).setUint32(0, addr.kind, false); + const data = encodeTLV({ + 0: [utf8Encoder.encode(addr.identifier)], + 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), + 2: [hexToBytes(addr.pubkey)], + 3: [new Uint8Array(kind)], + }); + return encodeBech32("naddr", data); + } + function nrelayEncode(url) { + const data = encodeTLV({ + 0: [utf8Encoder.encode(url)], + }); + return encodeBech32("nrelay", data); + } + function encodeTLV(tlv) { + const entries = []; + Object.entries(tlv).forEach(([t, vs]) => { + vs.forEach((v) => { + const entry = new Uint8Array(v.length + 2); + entry.set([Number.parseInt(t)], 0); + entry.set([v.length], 1); + entry.set(v, 2); + entries.push(entry); + }); + }); + return concatBytes(...entries); + } + var nip04_exports = {}; + __export2(nip04_exports, { + decrypt: () => decrypt, + encrypt: () => encrypt, + }); + if (typeof crypto !== "undefined" && !crypto.subtle && crypto.webcrypto) { + crypto.subtle = crypto.webcrypto.subtle; + } + async function encrypt(privkey, pubkey, text) { + const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + const iv = Uint8Array.from(randomBytes(16)); + const plaintext = utf8Encoder.encode(text); + const cryptoKey = await crypto.subtle.importKey( + "raw", + normalizedKey, + { name: "AES-CBC" }, + false, + ["encrypt"], + ); + const ciphertext = await crypto.subtle.encrypt( + { name: "AES-CBC", iv }, + cryptoKey, + plaintext, + ); + const ctb64 = base64.encode(new Uint8Array(ciphertext)); + const ivb64 = base64.encode(new Uint8Array(iv.buffer)); + return `${ctb64}?iv=${ivb64}`; + } + async function decrypt(privkey, pubkey, data) { + const [ctb64, ivb64] = data.split("?iv="); + const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); + const normalizedKey = getNormalizedX(key); + const cryptoKey = await crypto.subtle.importKey( + "raw", + normalizedKey, + { name: "AES-CBC" }, + false, + ["decrypt"], + ); + const ciphertext = base64.decode(ctb64); + const iv = base64.decode(ivb64); + const plaintext = await crypto.subtle.decrypt( + { name: "AES-CBC", iv }, + cryptoKey, + ciphertext, + ); + const text = utf8Decoder.decode(plaintext); + return text; + } + function getNormalizedX(key) { + return key.slice(1, 33); + } + var nip05_exports = {}; + __export2(nip05_exports, { + NIP05_REGEX: () => NIP05_REGEX, + queryProfile: () => queryProfile, + searchDomain: () => searchDomain, + useFetchImplementation: () => useFetchImplementation, + }); + var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w.-]+)$/; + var _fetch; + try { + _fetch = fetch; + } catch {} + function useFetchImplementation(fetchImplementation) { + _fetch = fetchImplementation; + } + async function searchDomain(domain, query = "") { + try { + const res = await ( + await _fetch(`https://${domain}/.well-known/nostr.json?name=${query}`) + ).json(); + return res.names; + } catch (_) { + return {}; + } + } + async function queryProfile(fullname) { + const match = fullname.match(NIP05_REGEX); + if (!match) return null; + const [_, name = "_", domain] = match; + try { + const res = await _fetch( + `https://${domain}/.well-known/nostr.json?name=${name}`, + ); + const { names, relays } = parseNIP05Result(await res.json()); + const pubkey = names[name]; + return pubkey ? { pubkey, relays: relays?.[pubkey] } : null; + } catch (_e) { + return null; + } + } + function parseNIP05Result(json) { + const result = { + names: {}, + }; + for (const [name, pubkey] of Object.entries(json.names)) { + if (typeof name === "string" && typeof pubkey === "string") { + result.names[name] = pubkey; + } + } + if (json.relays) { + result.relays = {}; + for (const [pubkey, relays] of Object.entries(json.relays)) { + if (typeof pubkey === "string" && Array.isArray(relays)) { + result.relays[pubkey] = relays.filter( + (relay) => typeof relay === "string", + ); + } + } + } + return result; + } + var nip06_exports = {}; + __export2(nip06_exports, { + generateSeedWords: () => generateSeedWords, + privateKeyFromSeedWords: () => privateKeyFromSeedWords, + validateWords: () => validateWords, + }); + function privateKeyFromSeedWords(mnemonic, passphrase) { + const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)); + const privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey; + if (!privateKey) throw new Error("could not derive private key"); + return bytesToHex(privateKey); + } + function generateSeedWords() { + return generateMnemonic(wordlist); + } + function validateWords(words) { + return validateMnemonic(words, wordlist); + } + var nip10_exports = {}; + __export2(nip10_exports, { + parse: () => parse, + }); + function parse(event) { + const result = { + reply: void 0, + root: void 0, + mentions: [], + profiles: [], + }; + const eTags = []; + for (const tag of event.tags) { + if (tag[0] === "e" && tag[1]) { + eTags.push(tag); + } + if (tag[0] === "p" && tag[1]) { + result.profiles.push({ + pubkey: tag[1], + relays: tag[2] ? [tag[2]] : [], + }); + } + } + for (let eTagIndex = 0; eTagIndex < eTags.length; eTagIndex++) { + const eTag = eTags[eTagIndex]; + const [_, eTagEventId, eTagRelayUrl, eTagMarker] = eTag; + const eventPointer = { + id: eTagEventId, + relays: eTagRelayUrl ? [eTagRelayUrl] : [], + }; + const isFirstETag = eTagIndex === 0; + const isLastETag = eTagIndex === eTags.length - 1; + if (eTagMarker === "root") { + result.root = eventPointer; + continue; + } + if (eTagMarker === "reply") { + result.reply = eventPointer; + continue; + } + if (eTagMarker === "mention") { + result.mentions.push(eventPointer); + continue; + } + if (isFirstETag) { + result.root = eventPointer; + continue; + } + if (isLastETag) { + result.reply = eventPointer; + continue; + } + result.mentions.push(eventPointer); + } + return result; + } + var nip13_exports = {}; + __export2(nip13_exports, { + getPow: () => getPow, + minePow: () => minePow, + }); + function getPow(hex2) { + let count = 0; + for (let i = 0; i < hex2.length; i++) { + const nibble = Number.parseInt(hex2[i], 16); + if (nibble === 0) { + count += 4; + } else { + count += Math.clz32(nibble) - 28; + break; + } + } + return count; + } + function minePow(unsigned, difficulty) { + let count = 0; + const event = unsigned; + const tag = ["nonce", count.toString(), difficulty.toString()]; + event.tags.push(tag); + while (true) { + const now = Math.floor(new Date().getTime() / 1e3); + if (now !== event.created_at) { + count = 0; + event.created_at = now; + } + tag[1] = (++count).toString(); + event.id = getEventHash(event); + if (getPow(event.id) >= difficulty) { + break; + } + } + return event; + } + var nip18_exports = {}; + __export2(nip18_exports, { + finishRepostEvent: () => finishRepostEvent, + getRepostedEvent: () => getRepostedEvent, + getRepostedEventPointer: () => getRepostedEventPointer, + }); + function finishRepostEvent(t, reposted, relayUrl, privateKey) { + return finishEvent( + { + kind: 6, + tags: [ + ...(t.tags ?? []), + ["e", reposted.id, relayUrl], + ["p", reposted.pubkey], + ], + content: t.content === "" ? "" : JSON.stringify(reposted), + created_at: t.created_at, + }, + privateKey, + ); + } + function getRepostedEventPointer(event) { + if (event.kind !== 6) { + return void 0; + } + let lastETag; + let lastPTag; + for ( + let i = event.tags.length - 1; + i >= 0 && (lastETag === void 0 || lastPTag === void 0); + i-- + ) { + const tag = event.tags[i]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === "string"), + author: lastPTag?.[1], + }; + } + function getRepostedEvent(event, { skipVerification } = {}) { + const pointer = getRepostedEventPointer(event); + if (pointer === void 0 || event.content === "") { + return void 0; + } + let repostedEvent; + try { + repostedEvent = JSON.parse(event.content); + } catch (error) { + return void 0; + } + if (repostedEvent.id !== pointer.id) { + return void 0; + } + if (!skipVerification && !verifySignature(repostedEvent)) { + return void 0; + } + return repostedEvent; + } + var nip21_exports = {}; + __export2(nip21_exports, { + NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, + parse: () => parse2, + test: () => test, + }); + var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); + function test(value) { + return ( + typeof value === "string" && + new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value) + ); + } + function parse2(uri) { + const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); + if (!match) throw new Error(`Invalid Nostr URI: ${uri}`); + return { + uri: match[0], + value: match[1], + decoded: decode(match[1]), + }; + } + var nip25_exports = {}; + __export2(nip25_exports, { + finishReactionEvent: () => finishReactionEvent, + getReactedEventPointer: () => getReactedEventPointer, + }); + function finishReactionEvent(t, reacted, privateKey) { + const inheritedTags = reacted.tags.filter( + (tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p"), + ); + return finishEvent( + { + ...t, + kind: 7, + tags: [ + ...(t.tags ?? []), + ...inheritedTags, + ["e", reacted.id], + ["p", reacted.pubkey], + ], + content: t.content ?? "+", + }, + privateKey, + ); + } + function getReactedEventPointer(event) { + if (event.kind !== 7) { + return void 0; + } + let lastETag; + let lastPTag; + for ( + let i = event.tags.length - 1; + i >= 0 && (lastETag === void 0 || lastPTag === void 0); + i-- + ) { + const tag = event.tags[i]; + if (tag.length >= 2) { + if (tag[0] === "e" && lastETag === void 0) { + lastETag = tag; + } else if (tag[0] === "p" && lastPTag === void 0) { + lastPTag = tag; + } + } + } + if (lastETag === void 0 || lastPTag === void 0) { + return void 0; + } + return { + id: lastETag[1], + relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), + author: lastPTag[1], + }; + } + var nip26_exports = {}; + __export2(nip26_exports, { + createDelegation: () => createDelegation, + getDelegator: () => getDelegator, + }); + function createDelegation(privateKey, parameters) { + const conditions = []; + if ((parameters.kind || -1) >= 0) + conditions.push(`kind=${parameters.kind}`); + if (parameters.until) conditions.push(`created_at<${parameters.until}`); + if (parameters.since) conditions.push(`created_at>${parameters.since}`); + const cond = conditions.join("&"); + if (cond === "") + throw new Error("refusing to create a delegation without any conditions"); + const sighash = sha256( + utf8Encoder.encode(`nostr:delegation:${parameters.pubkey}:${cond}`), + ); + const sig = bytesToHex(schnorr.sign(sighash, privateKey)); + return { + from: getPublicKey(privateKey), + to: parameters.pubkey, + cond, + sig, + }; + } + function getDelegator(event) { + const tag = event.tags.find( + (tag2) => tag2[0] === "delegation" && tag2.length >= 4, + ); + if (!tag) return null; + const pubkey = tag[1]; + const cond = tag[2]; + const sig = tag[3]; + const conditions = cond.split("&"); + for (let i = 0; i < conditions.length; i++) { + const [key, operator, value] = conditions[i].split(/\b/); + if ( + key === "kind" && + operator === "=" && + event.kind === Number.parseInt(value) + ) + continue; + else if ( + key === "created_at" && + operator === "<" && + event.created_at < Number.parseInt(value) + ) + continue; + else if ( + key === "created_at" && + operator === ">" && + event.created_at > Number.parseInt(value) + ) + continue; + else return null; + } + const sighash = sha256( + utf8Encoder.encode(`nostr:delegation:${event.pubkey}:${cond}`), + ); + if (!schnorr.verify(sig, sighash, pubkey)) return null; + return pubkey; + } + var nip27_exports = {}; + __export2(nip27_exports, { + matchAll: () => matchAll, + regex: () => regex, + replaceAll: () => replaceAll, + }); + var regex = () => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, "g"); + function* matchAll(content) { + const matches = content.matchAll(regex()); + for (const match of matches) { + try { + const [uri, value] = match; + yield { + uri, + value, + decoded: decode(value), + start: match.index, + end: match.index + uri.length, + }; + } catch (_e) {} + } + } + function replaceAll(content, replacer) { + return content.replaceAll(regex(), (uri, value) => { + return replacer({ + uri, + value, + decoded: decode(value), + }); + }); + } + var nip28_exports = {}; + __export2(nip28_exports, { + channelCreateEvent: () => channelCreateEvent, + channelHideMessageEvent: () => channelHideMessageEvent, + channelMessageEvent: () => channelMessageEvent, + channelMetadataEvent: () => channelMetadataEvent, + channelMuteUserEvent: () => channelMuteUserEvent, + }); + var channelCreateEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finishEvent( + { + kind: 40, + tags: [...(t.tags ?? [])], + content, + created_at: t.created_at, + }, + privateKey, + ); + }; + var channelMetadataEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finishEvent( + { + kind: 41, + tags: [["e", t.channel_create_event_id], ...(t.tags ?? [])], + content, + created_at: t.created_at, + }, + privateKey, + ); + }; + var channelMessageEvent = (t, privateKey) => { + const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; + if (t.reply_to_channel_message_event_id) { + tags.push([ + "e", + t.reply_to_channel_message_event_id, + t.relay_url, + "reply", + ]); + } + return finishEvent( + { + kind: 42, + tags: [...tags, ...(t.tags ?? [])], + content: t.content, + created_at: t.created_at, + }, + privateKey, + ); + }; + var channelHideMessageEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finishEvent( + { + kind: 43, + tags: [["e", t.channel_message_event_id], ...(t.tags ?? [])], + content, + created_at: t.created_at, + }, + privateKey, + ); + }; + var channelMuteUserEvent = (t, privateKey) => { + let content; + if (typeof t.content === "object") { + content = JSON.stringify(t.content); + } else if (typeof t.content === "string") { + content = t.content; + } else { + return void 0; + } + return finishEvent( + { + kind: 44, + tags: [["p", t.pubkey_to_mute], ...(t.tags ?? [])], + content, + created_at: t.created_at, + }, + privateKey, + ); + }; + var nip39_exports = {}; + __export2(nip39_exports, { + useFetchImplementation: () => useFetchImplementation2, + validateGithub: () => validateGithub, + }); + var _fetch2; + try { + _fetch2 = fetch; + } catch {} + function useFetchImplementation2(fetchImplementation) { + _fetch2 = fetchImplementation; + } + async function validateGithub(pubkey, username, proof) { + try { + const res = await ( + await _fetch2(`https://gist.github.com/${username}/${proof}/raw`) + ).text(); + return ( + res === + `Verifying that I control the following Nostr public key: ${pubkey}` + ); + } catch (_) { + return false; + } + } + var nip42_exports = {}; + __export2(nip42_exports, { + authenticate: () => authenticate, + }); + var authenticate = async ({ challenge: challenge2, relay, sign }) => { + const e = { + kind: 22242, + created_at: Math.floor(Date.now() / 1e3), + tags: [ + ["relay", relay.url], + ["challenge", challenge2], + ], + content: "", + }; + return relay.auth(await sign(e)); + }; + var nip44_exports = {}; + __export2(nip44_exports, { + decrypt: () => decrypt2, + encrypt: () => encrypt2, + utils: () => utils2, + }); + var utils2 = { + v2: { + maxPlaintextSize: 65536 - 128, + minCiphertextSize: 100, + maxCiphertextSize: 102400, + getConversationKey(privkeyA, pubkeyB) { + const key = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB); + return key.subarray(1, 33); + }, + getMessageKeys(conversationKey, salt2) { + const keys = hkdf(sha256, conversationKey, salt2, "nip44-v2", 76); + return { + encryption: keys.subarray(0, 32), + nonce: keys.subarray(32, 44), + auth: keys.subarray(44, 76), + }; + }, + calcPadding(len) { + if (!Number.isSafeInteger(len) || len < 0) + throw new Error("expected positive integer"); + if (len <= 32) return 32; + const nextpower = 1 << (Math.floor(Math.log2(len - 1)) + 1); + const chunk = nextpower <= 256 ? 32 : nextpower / 8; + return chunk * (Math.floor((len - 1) / chunk) + 1); + }, + pad(unpadded) { + const unpaddedB = utf8Encoder.encode(unpadded); + const len = unpaddedB.length; + if (len < 1 || len >= utils2.v2.maxPlaintextSize) + throw new Error( + "invalid plaintext length: must be between 1b and 64KB", + ); + const paddedLen = utils2.v2.calcPadding(len); + const zeros = new Uint8Array(paddedLen - len); + const lenBuf = new Uint8Array(2); + new DataView(lenBuf.buffer).setUint16(0, len); + return concatBytes(lenBuf, unpaddedB, zeros); + }, + unpad(padded) { + const unpaddedLen = new DataView(padded.buffer).getUint16(0); + const unpadded = padded.subarray(2, 2 + unpaddedLen); + if ( + unpaddedLen === 0 || + unpadded.length !== unpaddedLen || + padded.length !== 2 + utils2.v2.calcPadding(unpaddedLen) + ) + throw new Error("invalid padding"); + return utf8Decoder.decode(unpadded); + }, + }, + }; + function encrypt2(key, plaintext, options = {}) { + const version = options.version ?? 2; + if (version !== 2) throw new Error("unknown encryption version " + version); + const salt2 = options.salt ?? randomBytes(32); + ensureBytes2(salt2, 32); + const keys = utils2.v2.getMessageKeys(key, salt2); + const padded = utils2.v2.pad(plaintext); + const ciphertext = chacha20(keys.encryption, keys.nonce, padded); + const mac = hmac(sha256, keys.auth, ciphertext); + return base64.encode( + concatBytes(new Uint8Array([version]), salt2, ciphertext, mac), + ); + } + function decrypt2(key, ciphertext) { + const u = utils2.v2; + ensureBytes2(key, 32); + const clen = ciphertext.length; + if (clen < u.minCiphertextSize || clen >= u.maxCiphertextSize) + throw new Error("invalid ciphertext length: " + clen); + if (ciphertext[0] === "#") throw new Error("unknown encryption version"); + let data; + try { + data = base64.decode(ciphertext); + } catch (error) { + throw new Error("invalid base64: " + error.message); + } + const vers = data.subarray(0, 1)[0]; + if (vers !== 2) throw new Error("unknown encryption version " + vers); + const salt2 = data.subarray(1, 33); + const ciphertext_ = data.subarray(33, -32); + const mac = data.subarray(-32); + const keys = u.getMessageKeys(key, salt2); + const calculatedMac = hmac(sha256, keys.auth, ciphertext_); + if (!equalBytes2(calculatedMac, mac)) throw new Error("invalid MAC"); + const padded = chacha20(keys.encryption, keys.nonce, ciphertext_); + return u.unpad(padded); + } + var nip47_exports = {}; + __export2(nip47_exports, { + makeNwcRequestEvent: () => makeNwcRequestEvent, + parseConnectionString: () => parseConnectionString, + }); + function parseConnectionString(connectionString) { + const { pathname, searchParams } = new URL(connectionString); + const pubkey = pathname; + const relay = searchParams.get("relay"); + const secret = searchParams.get("secret"); + if (!pubkey || !relay || !secret) { + throw new Error("invalid connection string"); + } + return { pubkey, relay, secret }; + } + async function makeNwcRequestEvent({ pubkey, secret, invoice }) { + const content = { + method: "pay_invoice", + params: { + invoice, + }, + }; + const encryptedContent = await encrypt( + secret, + pubkey, + JSON.stringify(content), + ); + const eventTemplate = { + kind: 23194, + created_at: Math.round(Date.now() / 1e3), + content: encryptedContent, + tags: [["p", pubkey]], + }; + return finishEvent(eventTemplate, secret); + } + var nip57_exports = {}; + __export2(nip57_exports, { + getZapEndpoint: () => getZapEndpoint, + makeZapReceipt: () => makeZapReceipt, + makeZapRequest: () => makeZapRequest, + useFetchImplementation: () => useFetchImplementation3, + validateZapRequest: () => validateZapRequest, + }); + var _fetch3; + try { + _fetch3 = fetch; + } catch {} + function useFetchImplementation3(fetchImplementation) { + _fetch3 = fetchImplementation; + } + async function getZapEndpoint(metadata) { + try { + let lnurl = ""; + const { lud06, lud16 } = JSON.parse(metadata.content); + if (lud06) { + const { words } = bech32.decode(lud06, 1e3); + const data = bech32.fromWords(words); + lnurl = utf8Decoder.decode(data); + } else if (lud16) { + const [name, domain] = lud16.split("@"); + lnurl = `https://${domain}/.well-known/lnurlp/${name}`; + } else { + return null; + } + const res = await _fetch3(lnurl); + const body = await res.json(); + if (body.allowsNostr && body.nostrPubkey) { + return body.callback; + } + } catch (err) {} + return null; + } + function makeZapRequest({ profile, event, amount, relays, comment = "" }) { + if (!amount) throw new Error("amount not given"); + if (!profile) throw new Error("profile not given"); + const zr = { + kind: 9734, + created_at: Math.round(Date.now() / 1e3), + content: comment, + tags: [ + ["p", profile], + ["amount", amount.toString()], + ["relays", ...relays], + ], + }; + if (event) { + zr.tags.push(["e", event]); + } + return zr; + } + function validateZapRequest(zapRequestString) { + let zapRequest; + try { + zapRequest = JSON.parse(zapRequestString); + } catch (err) { + return "Invalid zap request JSON."; + } + if (!validateEvent(zapRequest)) + return "Zap request is not a valid Nostr event."; + if (!verifySignature(zapRequest)) + return "Invalid signature on zap request."; + const p = zapRequest.tags.find(([t, v]) => t === "p" && v); + if (!p) return "Zap request doesn't have a 'p' tag."; + if (!p[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'p' tag is not valid hex."; + const e = zapRequest.tags.find(([t, v]) => t === "e" && v); + if (e && !e[1].match(/^[a-f0-9]{64}$/)) + return "Zap request 'e' tag is not valid hex."; + const relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); + if (!relays) return "Zap request doesn't have a 'relays' tag."; + return null; + } + function makeZapReceipt({ zapRequest, preimage, bolt11, paidAt }) { + const zr = JSON.parse(zapRequest); + const tagsFromZapRequest = zr.tags.filter( + ([t]) => t === "e" || t === "p" || t === "a", + ); + const zap = { + kind: 9735, + created_at: Math.round(paidAt.getTime() / 1e3), + content: "", + tags: [ + ...tagsFromZapRequest, + ["bolt11", bolt11], + ["description", zapRequest], + ], + }; + if (preimage) { + zap.tags.push(["preimage", preimage]); + } + return zap; + } + var nip98_exports = {}; + __export2(nip98_exports, { + getToken: () => getToken, + unpackEventFromToken: () => unpackEventFromToken, + validateEvent: () => validateEvent2, + validateToken: () => validateToken, + }); + var _authorizationScheme = "Nostr "; + async function getToken( + loginUrl, + httpMethod, + sign, + includeAuthorizationScheme = false, + ) { + if (!loginUrl || !httpMethod) + throw new Error("Missing loginUrl or httpMethod"); + const event = getBlankEvent(27235); + event.tags = [ + ["u", loginUrl], + ["method", httpMethod], + ]; + event.created_at = Math.round(new Date().getTime() / 1e3); + const signedEvent = await sign(event); + const authorizationScheme = includeAuthorizationScheme + ? _authorizationScheme + : ""; + return ( + authorizationScheme + + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))) + ); + } + async function validateToken(token, url, method) { + const event = await unpackEventFromToken(token).catch((error) => { + throw error; + }); + const valid = await validateEvent2(event, url, method).catch((error) => { + throw error; + }); + return valid; + } + async function unpackEventFromToken(token) { + if (!token) { + throw new Error("Missing token"); + } + token = token.replace(_authorizationScheme, ""); + const eventB64 = utf8Decoder.decode(base64.decode(token)); + if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { + throw new Error("Invalid token"); + } + const event = JSON.parse(eventB64); + return event; + } + async function validateEvent2(event, url, method) { + if (!event) { + throw new Error("Invalid nostr event"); + } + if (!verifySignature(event)) { + throw new Error("Invalid nostr event, signature invalid"); + } + if (event.kind !== 27235) { + throw new Error("Invalid nostr event, kind invalid"); + } + if (!event.created_at) { + throw new Error("Invalid nostr event, created_at invalid"); + } + if (Math.round(new Date().getTime() / 1e3) - event.created_at > 60) { + throw new Error("Invalid nostr event, expired"); + } + const urlTag = event.tags.find((t) => t[0] === "u"); + if (urlTag?.length !== 1 && urlTag?.[1] !== url) { + throw new Error("Invalid nostr event, url tag invalid"); + } + const methodTag = event.tags.find((t) => t[0] === "method"); + if ( + methodTag?.length !== 1 && + methodTag?.[1].toLowerCase() !== method.toLowerCase() + ) { + throw new Error("Invalid nostr event, method tag invalid"); + } + return true; + } - // node_modules/.pnpm/async-mutex@0.3.2/node_modules/async-mutex/index.mjs - var E_TIMEOUT = new Error("timeout while waiting for mutex to become available"); - var E_ALREADY_LOCKED = new Error("mutex already locked"); - var E_CANCELED = new Error("request for lock canceled"); - var __awaiter$2 = 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()); - }); - }; - var Semaphore = class { - constructor(_maxConcurrency, _cancelError = E_CANCELED) { - this._maxConcurrency = _maxConcurrency; - this._cancelError = _cancelError; - this._queue = []; - this._waiters = []; - if (_maxConcurrency <= 0) { - throw new Error("semaphore must be initialized to a positive value"); - } - this._value = _maxConcurrency; - } - acquire() { - const locked = this.isLocked(); - const ticketPromise = new Promise((resolve, reject) => this._queue.push({ resolve, reject })); - if (!locked) - this._dispatch(); - return ticketPromise; - } - runExclusive(callback) { - return __awaiter$2(this, void 0, void 0, function* () { - const [value, release] = yield this.acquire(); - try { - return yield callback(value); - } finally { - release(); - } - }); - } - waitForUnlock() { - return __awaiter$2(this, void 0, void 0, function* () { - if (!this.isLocked()) { - return Promise.resolve(); - } - const waitPromise = new Promise((resolve) => this._waiters.push({ resolve })); - return waitPromise; - }); - } - isLocked() { - return this._value <= 0; - } - release() { - if (this._maxConcurrency > 1) { - throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead"); - } - if (this._currentReleaser) { - const releaser = this._currentReleaser; - this._currentReleaser = void 0; - releaser(); - } - } - cancel() { - this._queue.forEach((ticket) => ticket.reject(this._cancelError)); - this._queue = []; - } - _dispatch() { - const nextTicket = this._queue.shift(); - if (!nextTicket) - return; - let released = false; - this._currentReleaser = () => { - if (released) - return; - released = true; - this._value++; - this._resolveWaiters(); - this._dispatch(); - }; - nextTicket.resolve([this._value--, this._currentReleaser]); - } - _resolveWaiters() { - this._waiters.forEach((waiter) => waiter.resolve()); - this._waiters = []; - } - }; - var __awaiter$1 = 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()); - }); - }; - var Mutex = class { - constructor(cancelError) { - this._semaphore = new Semaphore(1, cancelError); - } - acquire() { - return __awaiter$1(this, void 0, void 0, function* () { - const [, releaser] = yield this._semaphore.acquire(); - return releaser; - }); - } - runExclusive(callback) { - return this._semaphore.runExclusive(() => callback()); - } - isLocked() { - return this._semaphore.isLocked(); - } - waitForUnlock() { - return this._semaphore.waitForUnlock(); - } - release() { - this._semaphore.release(); - } - cancel() { - return this._semaphore.cancel(); - } - }; + // node_modules/.pnpm/async-mutex@0.3.2/node_modules/async-mutex/index.mjs + var E_TIMEOUT = new Error( + "timeout while waiting for mutex to become available", + ); + var E_ALREADY_LOCKED = new Error("mutex already locked"); + var E_CANCELED = new Error("request for lock canceled"); + var __awaiter$2 = (thisArg, _arguments, P, generator) => { + function adopt(value) { + return value instanceof P + ? value + : new P((resolve) => { + resolve(value); + }); + } + return new (P || (P = Promise))((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()); + }); + }; + var Semaphore = class { + constructor(_maxConcurrency, _cancelError = E_CANCELED) { + this._maxConcurrency = _maxConcurrency; + this._cancelError = _cancelError; + this._queue = []; + this._waiters = []; + if (_maxConcurrency <= 0) { + throw new Error("semaphore must be initialized to a positive value"); + } + this._value = _maxConcurrency; + } + acquire() { + const locked = this.isLocked(); + const ticketPromise = new Promise((resolve, reject) => + this._queue.push({ resolve, reject }), + ); + if (!locked) this._dispatch(); + return ticketPromise; + } + runExclusive(callback) { + return __awaiter$2(this, void 0, void 0, function* () { + const [value, release] = yield this.acquire(); + try { + return yield callback(value); + } finally { + release(); + } + }); + } + waitForUnlock() { + return __awaiter$2(this, void 0, void 0, function* () { + if (!this.isLocked()) { + return Promise.resolve(); + } + const waitPromise = new Promise((resolve) => + this._waiters.push({ resolve }), + ); + return waitPromise; + }); + } + isLocked() { + return this._value <= 0; + } + release() { + if (this._maxConcurrency > 1) { + throw new Error( + "this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead", + ); + } + if (this._currentReleaser) { + const releaser = this._currentReleaser; + this._currentReleaser = void 0; + releaser(); + } + } + cancel() { + this._queue.forEach((ticket) => ticket.reject(this._cancelError)); + this._queue = []; + } + _dispatch() { + const nextTicket = this._queue.shift(); + if (!nextTicket) return; + let released = false; + this._currentReleaser = () => { + if (released) return; + released = true; + this._value++; + this._resolveWaiters(); + this._dispatch(); + }; + nextTicket.resolve([this._value--, this._currentReleaser]); + } + _resolveWaiters() { + this._waiters.forEach((waiter) => waiter.resolve()); + this._waiters = []; + } + }; + var __awaiter$1 = (thisArg, _arguments, P, generator) => { + function adopt(value) { + return value instanceof P + ? value + : new P((resolve) => { + resolve(value); + }); + } + return new (P || (P = Promise))((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()); + }); + }; + var Mutex = class { + constructor(cancelError) { + this._semaphore = new Semaphore(1, cancelError); + } + acquire() { + return __awaiter$1(this, void 0, void 0, function* () { + const [, releaser] = yield this._semaphore.acquire(); + return releaser; + }); + } + runExclusive(callback) { + return this._semaphore.runExclusive(() => callback()); + } + isLocked() { + return this._semaphore.isLocked(); + } + waitForUnlock() { + return this._semaphore.waitForUnlock(); + } + release() { + this._semaphore.release(); + } + cancel() { + return this._semaphore.cancel(); + } + }; - // extension/common.js - var import_webextension_polyfill = __toESM(require_browser_polyfill()); - var NO_PERMISSIONS_REQUIRED = { - replaceURL: true - }; - var PERMISSION_NAMES = Object.fromEntries([ - ["getPublicKey", "read your public key"], - ["getRelays", "read your list of preferred relays"], - ["signEvent", "sign events using your private key"], - ["nip04.encrypt", "encrypt messages to peers"], - ["nip04.decrypt", "decrypt messages from peers"] - ]); - function matchConditions(conditions, event) { - if (conditions?.kinds) { - if (event.kind in conditions.kinds) - return true; - else - return false; - } - return true; - } - async function getPermissionStatus(host, type, event) { - let { policies } = await import_webextension_polyfill.default.storage.local.get("policies"); - let answers = [true, false]; - for (let i = 0; i < answers.length; i++) { - let accept = answers[i]; - let { conditions } = policies?.[host]?.[accept]?.[type] || {}; - if (conditions) { - if (type === "signEvent") { - if (matchConditions(conditions, event)) { - return accept; - } else { - continue; - } - } else { - return accept; - } - } - } - return void 0; - } - async function updatePermission(host, type, accept, conditions) { - let { policies = {} } = await import_webextension_polyfill.default.storage.local.get("policies"); - if (Object.keys(conditions).length === 0) { - conditions = {}; - } else { - let existingConditions = policies[host]?.[accept]?.[type]?.conditions; - if (existingConditions) { - if (existingConditions.kinds && conditions.kinds) { - Object.keys(existingConditions.kinds).forEach((kind) => { - conditions.kinds[kind] = true; - }); - } - } - } - let other = !accept; - let reverse = policies?.[host]?.[other]?.[type]; - if (reverse && JSON.stringify(reverse.conditions) === JSON.stringify(conditions)) { - delete policies[host][other][type]; - } - policies[host] = policies[host] || {}; - policies[host][accept] = policies[host][accept] || {}; - policies[host][accept][type] = { - conditions, - created_at: Math.round(Date.now() / 1e3) - }; - import_webextension_polyfill.default.storage.local.set({ policies }); - } - async function showNotification(host, answer, type, params) { - let ok = await import_webextension_polyfill.default.storage.local.get("notifications"); - if (ok) { - let action = answer ? "allowed" : "denied"; - import_webextension_polyfill.default.notifications.create(void 0, { - type: "basic", - title: `${type} ${action} for ${host}`, - message: JSON.stringify( - params?.event ? { - kind: params.event.kind, - content: params.event.content, - tags: params.event.tags - } : params, - null, - 2 - ), - iconUrl: "icons/48x48.png" - }); - } - } + // extension/common.js + var import_webextension_polyfill = __toESM(require_browser_polyfill()); + var NO_PERMISSIONS_REQUIRED = { + replaceURL: true, + }; + var PERMISSION_NAMES = Object.fromEntries([ + ["getPublicKey", "read your public key"], + ["getRelays", "read your list of preferred relays"], + ["signEvent", "sign events using your private key"], + ["nip04.encrypt", "encrypt messages to peers"], + ["nip04.decrypt", "decrypt messages from peers"], + ]); + function matchConditions(conditions, event) { + if (conditions?.kinds) { + if (event.kind in conditions.kinds) return true; + else return false; + } + return true; + } + async function getPermissionStatus(host, type, event) { + const { policies } = + await import_webextension_polyfill.default.storage.local.get("policies"); + const answers = [true, false]; + for (let i = 0; i < answers.length; i++) { + const accept = answers[i]; + const { conditions } = policies?.[host]?.[accept]?.[type] || {}; + if (conditions) { + if (type === "signEvent") { + if (matchConditions(conditions, event)) { + return accept; + } else { + continue; + } + } else { + return accept; + } + } + } + return void 0; + } + async function updatePermission(host, type, accept, conditions) { + const { policies = {} } = + await import_webextension_polyfill.default.storage.local.get("policies"); + if (Object.keys(conditions).length === 0) { + conditions = {}; + } else { + const existingConditions = policies[host]?.[accept]?.[type]?.conditions; + if (existingConditions) { + if (existingConditions.kinds && conditions.kinds) { + Object.keys(existingConditions.kinds).forEach((kind) => { + conditions.kinds[kind] = true; + }); + } + } + } + const other = !accept; + const reverse = policies?.[host]?.[other]?.[type]; + if ( + reverse && + JSON.stringify(reverse.conditions) === JSON.stringify(conditions) + ) { + delete policies[host][other][type]; + } + policies[host] = policies[host] || {}; + policies[host][accept] = policies[host][accept] || {}; + policies[host][accept][type] = { + conditions, + created_at: Math.round(Date.now() / 1e3), + }; + import_webextension_polyfill.default.storage.local.set({ policies }); + } + async function showNotification(host, answer, type, params) { + const ok = + await import_webextension_polyfill.default.storage.local.get( + "notifications", + ); + if (ok) { + const action = answer ? "allowed" : "denied"; + import_webextension_polyfill.default.notifications.create(void 0, { + type: "basic", + title: `${type} ${action} for ${host}`, + message: JSON.stringify( + params?.event + ? { + kind: params.event.kind, + content: params.event.content, + tags: params.event.tags, + } + : params, + null, + 2, + ), + iconUrl: "icons/48x48.png", + }); + } + } - // extension/background.js - var { encrypt: encrypt3, decrypt: decrypt3 } = nip04_exports; - var openPrompt = null; - var promptMutex = new Mutex(); - var releasePromptMutex = () => { - }; - import_webextension_polyfill2.default.runtime.onInstalled.addListener((_, __, reason) => { - if (reason === "install") - import_webextension_polyfill2.default.runtime.openOptionsPage(); - }); - import_webextension_polyfill2.default.runtime.onMessage.addListener(async (req, sender) => { - let { prompt } = req; - if (prompt) { - handlePromptMessage(req, sender); - } else { - return handleContentScriptMessage(req); - } - }); - import_webextension_polyfill2.default.runtime.onMessageExternal.addListener( - async ({ type, params }, sender) => { - let extensionId = new URL(sender.url).host; - return handleContentScriptMessage({ type, params, host: extensionId }); - } - ); - import_webextension_polyfill2.default.windows.onRemoved.addListener((windowId) => { - if (openPrompt) { - handlePromptMessage({ accept: false }, null); - } - }); - async function handleContentScriptMessage({ type, params, host }) { - if (NO_PERMISSIONS_REQUIRED[type]) { - switch (type) { - case "replaceURL": { - let { protocol_handler: ph } = await import_webextension_polyfill2.default.storage.local.get([ - "protocol_handler" - ]); - if (!ph) - return false; - let { url } = params; - let raw = url.split("nostr:")[1]; - let { type: type2, data } = nip19_exports.decode(raw); - let replacements = { - raw, - hrp: type2, - hex: type2 === "npub" || type2 === "note" ? data : type2 === "nprofile" ? data.pubkey : type2 === "nevent" ? data.id : null, - p_or_e: { npub: "p", note: "e", nprofile: "p", nevent: "e" }[type2], - u_or_n: { npub: "u", note: "n", nprofile: "u", nevent: "n" }[type2], - relay0: type2 === "nprofile" ? data.relays[0] : null, - relay1: type2 === "nprofile" ? data.relays[1] : null, - relay2: type2 === "nprofile" ? data.relays[2] : null - }; - let result = ph; - Object.entries(replacements).forEach(([pattern, value]) => { - result = result.replace(new RegExp(`{ *${pattern} *}`, "g"), value); - }); - return result; - } - } - return; - } else { - releasePromptMutex = await promptMutex.acquire(); - let allowed = await getPermissionStatus( - host, - type, - type === "signEvent" ? params.event : void 0 - ); - if (allowed === true) { - releasePromptMutex(); - showNotification(host, allowed, type, params); - } else if (allowed === false) { - releasePromptMutex(); - showNotification(host, allowed, type, params); - return { - error: "denied" - }; - } else { - try { - let id = Math.random().toString().slice(4); - let qs = new URLSearchParams({ - host, - id, - params: JSON.stringify(params), - type - }); - let accept = await new Promise((resolve, reject) => { - openPrompt = { resolve, reject }; - const url = `${import_webextension_polyfill2.default.runtime.getURL( - "prompt.html" - )}?${qs.toString()}`; - if (import_webextension_polyfill2.default.windows) { - import_webextension_polyfill2.default.windows.create({ - url, - type: "popup", - width: 600, - height: 600 - }); - } else { - import_webextension_polyfill2.default.tabs.create({ - url, - active: true - }); - } - }); - if (!accept) - return { error: "denied" }; - } catch (err) { - releasePromptMutex(); - return { - error: `error: ${err}` - }; - } - } - } - let results = await import_webextension_polyfill2.default.storage.local.get("private_key"); - if (!results || !results.private_key) { - return { error: "no private key found" }; - } - let sk = results.private_key; - try { - switch (type) { - case "getPublicKey": { - return getPublicKey(sk); - } - case "getRelays": { - let results2 = await import_webextension_polyfill2.default.storage.local.get("relays"); - return results2.relays || {}; - } - case "signEvent": { - let { event } = params; - if (!event.pubkey) - event.pubkey = getPublicKey(sk); - if (!event.id) - event.id = getEventHash(event); - if (!validateEvent(event)) - return { error: { message: "invalid event" } }; - event.sig = await getSignature(event, sk); - return event; - } - case "nip04.encrypt": { - let { peer, plaintext } = params; - return encrypt3(sk, peer, plaintext); - } - case "nip04.decrypt": { - let { peer, ciphertext } = params; - return decrypt3(sk, peer, ciphertext); - } - } - } catch (error) { - return { error: { message: error.message, stack: error.stack } }; - } - } - async function handlePromptMessage({ host, type, accept, conditions }, sender) { - openPrompt?.resolve?.(accept); - if (conditions) { - await updatePermission(host, type, accept, conditions); - } - openPrompt = null; - releasePromptMutex(); - if (sender) { - if (import_webextension_polyfill2.default.windows) { - import_webextension_polyfill2.default.windows.remove(sender.tab.windowId); - } else { - import_webextension_polyfill2.default.tabs.remove(sender.tab.id); - } - } - } + // extension/background.js + var { encrypt: encrypt3, decrypt: decrypt3 } = nip04_exports; + var openPrompt = null; + var promptMutex = new Mutex(); + var releasePromptMutex = () => {}; + import_webextension_polyfill2.default.runtime.onInstalled.addListener( + (_, __, reason) => { + if (reason === "install") + import_webextension_polyfill2.default.runtime.openOptionsPage(); + }, + ); + import_webextension_polyfill2.default.runtime.onMessage.addListener( + async (req, sender) => { + const { prompt } = req; + if (prompt) { + handlePromptMessage(req, sender); + } else { + return handleContentScriptMessage(req); + } + }, + ); + import_webextension_polyfill2.default.runtime.onMessageExternal.addListener( + async ({ type, params }, sender) => { + const extensionId = new URL(sender.url).host; + return handleContentScriptMessage({ type, params, host: extensionId }); + }, + ); + import_webextension_polyfill2.default.windows.onRemoved.addListener( + (windowId) => { + if (openPrompt) { + handlePromptMessage({ accept: false }, null); + } + }, + ); + async function handleContentScriptMessage({ type, params, host }) { + if (NO_PERMISSIONS_REQUIRED[type]) { + switch (type) { + case "replaceURL": { + const { protocol_handler: ph } = + await import_webextension_polyfill2.default.storage.local.get([ + "protocol_handler", + ]); + if (!ph) return false; + const { url } = params; + const raw = url.split("nostr:")[1]; + const { type: type2, data } = nip19_exports.decode(raw); + const replacements = { + raw, + hrp: type2, + hex: + type2 === "npub" || type2 === "note" + ? data + : type2 === "nprofile" + ? data.pubkey + : type2 === "nevent" + ? data.id + : null, + p_or_e: { npub: "p", note: "e", nprofile: "p", nevent: "e" }[type2], + u_or_n: { npub: "u", note: "n", nprofile: "u", nevent: "n" }[type2], + relay0: type2 === "nprofile" ? data.relays[0] : null, + relay1: type2 === "nprofile" ? data.relays[1] : null, + relay2: type2 === "nprofile" ? data.relays[2] : null, + }; + let result = ph; + Object.entries(replacements).forEach(([pattern, value]) => { + result = result.replace(new RegExp(`{ *${pattern} *}`, "g"), value); + }); + return result; + } + } + return; + } else { + releasePromptMutex = await promptMutex.acquire(); + const allowed = await getPermissionStatus( + host, + type, + type === "signEvent" ? params.event : void 0, + ); + if (allowed === true) { + releasePromptMutex(); + showNotification(host, allowed, type, params); + } else if (allowed === false) { + releasePromptMutex(); + showNotification(host, allowed, type, params); + return { + error: "denied", + }; + } else { + try { + const id = Math.random().toString().slice(4); + const qs = new URLSearchParams({ + host, + id, + params: JSON.stringify(params), + type, + }); + const accept = await new Promise((resolve, reject) => { + openPrompt = { resolve, reject }; + const url = `${import_webextension_polyfill2.default.runtime.getURL( + "prompt.html", + )}?${qs.toString()}`; + if (import_webextension_polyfill2.default.windows) { + import_webextension_polyfill2.default.windows.create({ + url, + type: "popup", + width: 600, + height: 600, + }); + } else { + import_webextension_polyfill2.default.tabs.create({ + url, + active: true, + }); + } + }); + if (!accept) return { error: "denied" }; + } catch (err) { + releasePromptMutex(); + return { + error: `error: ${err}`, + }; + } + } + } + const results = + await import_webextension_polyfill2.default.storage.local.get( + "private_key", + ); + if (!results || !results.private_key) { + return { error: "no private key found" }; + } + const sk = results.private_key; + try { + switch (type) { + case "getPublicKey": { + return getPublicKey(sk); + } + case "getRelays": { + const results2 = + await import_webextension_polyfill2.default.storage.local.get( + "relays", + ); + return results2.relays || {}; + } + case "signEvent": { + const { event } = params; + if (!event.pubkey) event.pubkey = getPublicKey(sk); + if (!event.id) event.id = getEventHash(event); + if (!validateEvent(event)) + return { error: { message: "invalid event" } }; + event.sig = await getSignature(event, sk); + return event; + } + case "nip04.encrypt": { + const { peer, plaintext } = params; + return encrypt3(sk, peer, plaintext); + } + case "nip04.decrypt": { + const { peer, ciphertext } = params; + return decrypt3(sk, peer, ciphertext); + } + } + } catch (error) { + return { error: { message: error.message, stack: error.stack } }; + } + } + async function handlePromptMessage( + { host, type, accept, conditions }, + sender, + ) { + openPrompt?.resolve?.(accept); + if (conditions) { + await updatePermission(host, type, accept, conditions); + } + openPrompt = null; + releasePromptMutex(); + if (sender) { + if (import_webextension_polyfill2.default.windows) { + import_webextension_polyfill2.default.windows.remove( + sender.tab.windowId, + ); + } else { + import_webextension_polyfill2.default.tabs.remove(sender.tab.id); + } + } + } })(); /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ diff --git a/extension/output/common.js b/extension/output/common.js index 9b9185b..7f711fe 100644 --- a/extension/output/common.js +++ b/extension/output/common.js @@ -1,116 +1,118 @@ -import browser from 'webextension-polyfill' +import browser from "webextension-polyfill"; export const NO_PERMISSIONS_REQUIRED = { - replaceURL: true -} + replaceURL: true, +}; export const PERMISSION_NAMES = Object.fromEntries([ - ['getPublicKey', 'read your public key'], - ['getRelays', 'read your list of preferred relays'], - ['signEvent', 'sign events using your private key'], - ['nip04.encrypt', 'encrypt messages to peers'], - ['nip04.decrypt', 'decrypt messages from peers'] -]) + ["getPublicKey", "read your public key"], + ["getRelays", "read your list of preferred relays"], + ["signEvent", "sign events using your private key"], + ["nip04.encrypt", "encrypt messages to peers"], + ["nip04.decrypt", "decrypt messages from peers"], +]); function matchConditions(conditions, event) { - if (conditions?.kinds) { - if (event.kind in conditions.kinds) return true - else return false - } + if (conditions?.kinds) { + if (event.kind in conditions.kinds) return true; + else return false; + } - return true + return true; } export async function getPermissionStatus(host, type, event) { - let {policies} = await browser.storage.local.get('policies') + const { policies } = await browser.storage.local.get("policies"); - let answers = [true, false] - for (let i = 0; i < answers.length; i++) { - let accept = answers[i] - let {conditions} = policies?.[host]?.[accept]?.[type] || {} + const answers = [true, false]; + for (let i = 0; i < answers.length; i++) { + const accept = answers[i]; + const { conditions } = policies?.[host]?.[accept]?.[type] || {}; - if (conditions) { - if (type === 'signEvent') { - if (matchConditions(conditions, event)) { - return accept // may be true or false - } else { - // if this doesn't match we just continue so it will either match for the opposite answer (reject) - // or it will end up returning undefined at the end - continue - } - } else { - return accept // may be true or false - } - } - } + if (conditions) { + if (type === "signEvent") { + if (matchConditions(conditions, event)) { + return accept; // may be true or false + } else { + // if this doesn't match we just continue so it will either match for the opposite answer (reject) + // or it will end up returning undefined at the end + // biome-ignore lint/correctness/noUnnecessaryContinue: + continue; + } + } else { + return accept; // may be true or false + } + } + } - return undefined + return undefined; } export async function updatePermission(host, type, accept, conditions) { - let {policies = {}} = await browser.storage.local.get('policies') + const { policies = {} } = await browser.storage.local.get("policies"); - // if the new conditions is "match everything", override the previous - if (Object.keys(conditions).length === 0) { - conditions = {} - } else { - // if we already had a policy for this, merge the conditions - let existingConditions = policies[host]?.[accept]?.[type]?.conditions - if (existingConditions) { - if (existingConditions.kinds && conditions.kinds) { - Object.keys(existingConditions.kinds).forEach(kind => { - conditions.kinds[kind] = true - }) - } - } - } + // if the new conditions is "match everything", override the previous + if (Object.keys(conditions).length === 0) { + conditions = {}; + } else { + // if we already had a policy for this, merge the conditions + const existingConditions = policies[host]?.[accept]?.[type]?.conditions; - // if we have a reverse policy (accept / reject) that is exactly equal to this, remove it - let other = !accept - let reverse = policies?.[host]?.[other]?.[type] - if ( - reverse && - JSON.stringify(reverse.conditions) === JSON.stringify(conditions) - ) { - delete policies[host][other][type] - } + if (existingConditions) { + if (existingConditions.kinds && conditions.kinds) { + Object.keys(existingConditions.kinds).forEach((kind) => { + conditions.kinds[kind] = true; + }); + } + } + } - // insert our new policy - policies[host] = policies[host] || {} - policies[host][accept] = policies[host][accept] || {} - policies[host][accept][type] = { - conditions, // filter that must match the event (in case of signEvent) - created_at: Math.round(Date.now() / 1000) - } + // if we have a reverse policy (accept / reject) that is exactly equal to this, remove it + const other = !accept; + const reverse = policies?.[host]?.[other]?.[type]; + if ( + reverse && + JSON.stringify(reverse.conditions) === JSON.stringify(conditions) + ) { + delete policies[host][other][type]; + } - browser.storage.local.set({policies}) + // insert our new policy + policies[host] = policies[host] || {}; + policies[host][accept] = policies[host][accept] || {}; + policies[host][accept][type] = { + conditions, // filter that must match the event (in case of signEvent) + created_at: Math.round(Date.now() / 1000), + }; + + browser.storage.local.set({ policies }); } export async function removePermissions(host, accept, type) { - let {policies = {}} = await browser.storage.local.get('policies') - delete policies[host]?.[accept]?.[type] - browser.storage.local.set({policies}) + const { policies = {} } = await browser.storage.local.get("policies"); + delete policies[host]?.[accept]?.[type]; + browser.storage.local.set({ policies }); } export async function showNotification(host, answer, type, params) { - let ok = await browser.storage.local.get('notifications') - if (ok) { - let action = answer ? 'allowed' : 'denied' - browser.notifications.create(undefined, { - type: 'basic', - title: `${type} ${action} for ${host}`, - message: JSON.stringify( - params?.event - ? { - kind: params.event.kind, - content: params.event.content, - tags: params.event.tags - } - : params, - null, - 2 - ), - iconUrl: 'icons/48x48.png' - }) - } + const ok = await browser.storage.local.get("notifications"); + if (ok) { + const action = answer ? "allowed" : "denied"; + browser.notifications.create(undefined, { + type: "basic", + title: `${type} ${action} for ${host}`, + message: JSON.stringify( + params?.event + ? { + kind: params.event.kind, + content: params.event.content, + tags: params.event.tags, + } + : params, + null, + 2, + ), + iconUrl: "icons/48x48.png", + }); + } } diff --git a/extension/output/content-script.build.js b/extension/output/content-script.build.js index 6ccd4d5..e257efe 100644 --- a/extension/output/content-script.build.js +++ b/extension/output/content-script.build.js @@ -1,1056 +1,1172 @@ (() => { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod - )); + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __commonJS = (cb, mod) => + function __require() { + return ( + mod || + (0, cb[__getOwnPropNames(cb)[0]])( + (mod = { exports: {} }).exports, + mod, + ), + mod.exports + ); + }; + var __copyProps = (to, from, except, desc) => { + if ((from && typeof from === "object") || typeof from === "function") { + for (const key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { + get: () => from[key], + enumerable: + !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => ( + (target = mod != null ? __create(__getProtoOf(mod)) : {}), + __copyProps( + isNodeMode || !mod || !mod.__esModule + ? __defProp(target, "default", { value: mod, enumerable: true }) + : target, + mod, + ) + ); - // node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js - var require_browser_polyfill = __commonJS({ - "node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) { - (function(global, factory) { - if (typeof define === "function" && define.amd) { - define("webextension-polyfill", ["module"], factory); - } else if (typeof exports !== "undefined") { - factory(module); - } else { - var mod = { - exports: {} - }; - factory(mod); - global.browser = mod.exports; - } - })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports, function(module2) { - "use strict"; - if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) { - const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received."; - const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; - const wrapAPIs = (extensionAPIs) => { - const apiMetadata = { - "alarms": { - "clear": { - "minArgs": 0, - "maxArgs": 1 - }, - "clearAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "bookmarks": { - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getChildren": { - "minArgs": 1, - "maxArgs": 1 - }, - "getRecent": { - "minArgs": 1, - "maxArgs": 1 - }, - "getSubTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTree": { - "minArgs": 0, - "maxArgs": 0 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "browserAction": { - "disable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "enable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "getBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1 - }, - "getBadgeText": { - "minArgs": 1, - "maxArgs": 1 - }, - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "openPopup": { - "minArgs": 0, - "maxArgs": 0 - }, - "setBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setBadgeText": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "browsingData": { - "remove": { - "minArgs": 2, - "maxArgs": 2 - }, - "removeCache": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCookies": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeDownloads": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFormData": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeHistory": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeLocalStorage": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePasswords": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePluginData": { - "minArgs": 1, - "maxArgs": 1 - }, - "settings": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "commands": { - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "contextMenus": { - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "cookies": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAllCookieStores": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "devtools": { - "inspectedWindow": { - "eval": { - "minArgs": 1, - "maxArgs": 2, - "singleCallbackArg": false - } - }, - "panels": { - "create": { - "minArgs": 3, - "maxArgs": 3, - "singleCallbackArg": true - }, - "elements": { - "createSidebarPane": { - "minArgs": 1, - "maxArgs": 1 - } - } - } - }, - "downloads": { - "cancel": { - "minArgs": 1, - "maxArgs": 1 - }, - "download": { - "minArgs": 1, - "maxArgs": 1 - }, - "erase": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFileIcon": { - "minArgs": 1, - "maxArgs": 2 - }, - "open": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "pause": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFile": { - "minArgs": 1, - "maxArgs": 1 - }, - "resume": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "extension": { - "isAllowedFileSchemeAccess": { - "minArgs": 0, - "maxArgs": 0 - }, - "isAllowedIncognitoAccess": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "history": { - "addUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "deleteRange": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "getVisits": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "i18n": { - "detectLanguage": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAcceptLanguages": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "identity": { - "launchWebAuthFlow": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "idle": { - "queryState": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "management": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getSelf": { - "minArgs": 0, - "maxArgs": 0 - }, - "setEnabled": { - "minArgs": 2, - "maxArgs": 2 - }, - "uninstallSelf": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "notifications": { - "clear": { - "minArgs": 1, - "maxArgs": 1 - }, - "create": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPermissionLevel": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "pageAction": { - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "hide": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "permissions": { - "contains": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "request": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "runtime": { - "getBackgroundPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPlatformInfo": { - "minArgs": 0, - "maxArgs": 0 - }, - "openOptionsPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "requestUpdateCheck": { - "minArgs": 0, - "maxArgs": 0 - }, - "sendMessage": { - "minArgs": 1, - "maxArgs": 3 - }, - "sendNativeMessage": { - "minArgs": 2, - "maxArgs": 2 - }, - "setUninstallURL": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "sessions": { - "getDevices": { - "minArgs": 0, - "maxArgs": 1 - }, - "getRecentlyClosed": { - "minArgs": 0, - "maxArgs": 1 - }, - "restore": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "storage": { - "local": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "managed": { - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "sync": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - } - }, - "tabs": { - "captureVisibleTab": { - "minArgs": 0, - "maxArgs": 2 - }, - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "detectLanguage": { - "minArgs": 0, - "maxArgs": 1 - }, - "discard": { - "minArgs": 0, - "maxArgs": 1 - }, - "duplicate": { - "minArgs": 1, - "maxArgs": 1 - }, - "executeScript": { - "minArgs": 1, - "maxArgs": 2 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 0 - }, - "getZoom": { - "minArgs": 0, - "maxArgs": 1 - }, - "getZoomSettings": { - "minArgs": 0, - "maxArgs": 1 - }, - "goBack": { - "minArgs": 0, - "maxArgs": 1 - }, - "goForward": { - "minArgs": 0, - "maxArgs": 1 - }, - "highlight": { - "minArgs": 1, - "maxArgs": 1 - }, - "insertCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "query": { - "minArgs": 1, - "maxArgs": 1 - }, - "reload": { - "minArgs": 0, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "sendMessage": { - "minArgs": 2, - "maxArgs": 3 - }, - "setZoom": { - "minArgs": 1, - "maxArgs": 2 - }, - "setZoomSettings": { - "minArgs": 1, - "maxArgs": 2 - }, - "update": { - "minArgs": 1, - "maxArgs": 2 - } - }, - "topSites": { - "get": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "webNavigation": { - "getAllFrames": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFrame": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "webRequest": { - "handlerBehaviorChanged": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "windows": { - "create": { - "minArgs": 0, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 1 - }, - "getLastFocused": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - } - }; - if (Object.keys(apiMetadata).length === 0) { - throw new Error("api-metadata.json has not been included in browser-polyfill"); - } - class DefaultWeakMap extends WeakMap { - constructor(createItem, items = void 0) { - super(items); - this.createItem = createItem; - } - get(key) { - if (!this.has(key)) { - this.set(key, this.createItem(key)); - } - return super.get(key); - } - } - const isThenable = (value) => { - return value && typeof value === "object" && typeof value.then === "function"; - }; - const makeCallback = (promise, metadata) => { - return (...callbackArgs) => { - if (extensionAPIs.runtime.lastError) { - promise.reject(new Error(extensionAPIs.runtime.lastError.message)); - } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) { - promise.resolve(callbackArgs[0]); - } else { - promise.resolve(callbackArgs); - } - }; - }; - const pluralizeArguments = (numArgs) => numArgs == 1 ? "argument" : "arguments"; - const wrapAsyncFunction = (name, metadata) => { - return function asyncFunctionWrapper(target, ...args) { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - return new Promise((resolve, reject) => { - if (metadata.fallbackToNoCallback) { - try { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } catch (cbError) { - console.warn(`${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, cbError); - target[name](...args); - metadata.fallbackToNoCallback = false; - metadata.noCallback = true; - resolve(); - } - } else if (metadata.noCallback) { - target[name](...args); - resolve(); - } else { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } - }); - }; - }; - const wrapMethod = (target, method, wrapper) => { - return new Proxy(method, { - apply(targetMethod, thisObj, args) { - return wrapper.call(thisObj, target, ...args); - } - }); - }; - let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); - const wrapObject = (target, wrappers = {}, metadata = {}) => { - let cache = /* @__PURE__ */ Object.create(null); - let handlers = { - has(proxyTarget2, prop) { - return prop in target || prop in cache; - }, - get(proxyTarget2, prop, receiver) { - if (prop in cache) { - return cache[prop]; - } - if (!(prop in target)) { - return void 0; - } - let value = target[prop]; - if (typeof value === "function") { - if (typeof wrappers[prop] === "function") { - value = wrapMethod(target, target[prop], wrappers[prop]); - } else if (hasOwnProperty(metadata, prop)) { - let wrapper = wrapAsyncFunction(prop, metadata[prop]); - value = wrapMethod(target, target[prop], wrapper); - } else { - value = value.bind(target); - } - } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) { - value = wrapObject(value, wrappers[prop], metadata[prop]); - } else if (hasOwnProperty(metadata, "*")) { - value = wrapObject(value, wrappers[prop], metadata["*"]); - } else { - Object.defineProperty(cache, prop, { - configurable: true, - enumerable: true, - get() { - return target[prop]; - }, - set(value2) { - target[prop] = value2; - } - }); - return value; - } - cache[prop] = value; - return value; - }, - set(proxyTarget2, prop, value, receiver) { - if (prop in cache) { - cache[prop] = value; - } else { - target[prop] = value; - } - return true; - }, - defineProperty(proxyTarget2, prop, desc) { - return Reflect.defineProperty(cache, prop, desc); - }, - deleteProperty(proxyTarget2, prop) { - return Reflect.deleteProperty(cache, prop); - } - }; - let proxyTarget = Object.create(target); - return new Proxy(proxyTarget, handlers); - }; - const wrapEvent = (wrapperMap) => ({ - addListener(target, listener, ...args) { - target.addListener(wrapperMap.get(listener), ...args); - }, - hasListener(target, listener) { - return target.hasListener(wrapperMap.get(listener)); - }, - removeListener(target, listener) { - target.removeListener(wrapperMap.get(listener)); - } - }); - const onRequestFinishedWrappers = new DefaultWeakMap((listener) => { - if (typeof listener !== "function") { - return listener; - } - return function onRequestFinished(req) { - const wrappedReq = wrapObject( - req, - {}, - { - getContent: { - minArgs: 0, - maxArgs: 0 - } - } - ); - listener(wrappedReq); - }; - }); - let loggedSendResponseDeprecationWarning = false; - const onMessageWrappers = new DefaultWeakMap((listener) => { - if (typeof listener !== "function") { - return listener; - } - return function onMessage(message, sender, sendResponse) { - let didCallSendResponse = false; - let wrappedSendResponse; - let sendResponsePromise = new Promise((resolve) => { - wrappedSendResponse = function(response) { - if (!loggedSendResponseDeprecationWarning) { - console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack); - loggedSendResponseDeprecationWarning = true; - } - didCallSendResponse = true; - resolve(response); - }; - }); - let result; - try { - result = listener(message, sender, wrappedSendResponse); - } catch (err) { - result = Promise.reject(err); - } - const isResultThenable = result !== true && isThenable(result); - if (result !== true && !isResultThenable && !didCallSendResponse) { - return false; - } - const sendPromisedResult = (promise) => { - promise.then((msg) => { - sendResponse(msg); - }, (error) => { - let message2; - if (error && (error instanceof Error || typeof error.message === "string")) { - message2 = error.message; - } else { - message2 = "An unexpected error occurred"; - } - sendResponse({ - __mozWebExtensionPolyfillReject__: true, - message: message2 - }); - }).catch((err) => { - console.error("Failed to send onMessage rejected reply", err); - }); - }; - if (isResultThenable) { - sendPromisedResult(result); - } else { - sendPromisedResult(sendResponsePromise); - } - return true; - }; - }); - const wrappedSendMessageCallback = ({ - reject, - resolve - }, reply) => { - if (extensionAPIs.runtime.lastError) { - if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) { - resolve(); - } else { - reject(new Error(extensionAPIs.runtime.lastError.message)); - } - } else if (reply && reply.__mozWebExtensionPolyfillReject__) { - reject(new Error(reply.message)); - } else { - resolve(reply); - } - }; - const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - return new Promise((resolve, reject) => { - const wrappedCb = wrappedSendMessageCallback.bind(null, { - resolve, - reject - }); - args.push(wrappedCb); - apiNamespaceObj.sendMessage(...args); - }); - }; - const staticWrappers = { - devtools: { - network: { - onRequestFinished: wrapEvent(onRequestFinishedWrappers) - } - }, - runtime: { - onMessage: wrapEvent(onMessageWrappers), - onMessageExternal: wrapEvent(onMessageWrappers), - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 1, - maxArgs: 3 - }) - }, - tabs: { - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 2, - maxArgs: 3 - }) - } - }; - const settingMetadata = { - clear: { - minArgs: 1, - maxArgs: 1 - }, - get: { - minArgs: 1, - maxArgs: 1 - }, - set: { - minArgs: 1, - maxArgs: 1 - } - }; - apiMetadata.privacy = { - network: { - "*": settingMetadata - }, - services: { - "*": settingMetadata - }, - websites: { - "*": settingMetadata - } - }; - return wrapObject(extensionAPIs, staticWrappers, apiMetadata); - }; - if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) { - throw new Error("This script should only be loaded in a browser extension."); - } - module2.exports = wrapAPIs(chrome); - } else { - module2.exports = browser; - } - }); - } - }); + // node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js + var require_browser_polyfill = __commonJS({ + "node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"( + exports, + module, + ) { + ((global, factory) => { + if (typeof define === "function" && define.amd) { + define("webextension-polyfill", ["module"], factory); + } else if (typeof exports !== "undefined") { + factory(module); + } else { + var mod = { + exports: {}, + }; + factory(mod); + global.browser = mod.exports; + } + })( + typeof globalThis !== "undefined" + ? globalThis + : typeof self !== "undefined" + ? self + : exports, + (module2) => { + if ( + typeof browser === "undefined" || + Object.getPrototypeOf(browser) !== Object.prototype + ) { + const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = + "The message port closed before a response was received."; + const SEND_RESPONSE_DEPRECATION_WARNING = + "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; + const wrapAPIs = (extensionAPIs) => { + const apiMetadata = { + alarms: { + clear: { + minArgs: 0, + maxArgs: 1, + }, + clearAll: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + }, + bookmarks: { + create: { + minArgs: 1, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + getChildren: { + minArgs: 1, + maxArgs: 1, + }, + getRecent: { + minArgs: 1, + maxArgs: 1, + }, + getSubTree: { + minArgs: 1, + maxArgs: 1, + }, + getTree: { + minArgs: 0, + maxArgs: 0, + }, + move: { + minArgs: 2, + maxArgs: 2, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeTree: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + browserAction: { + disable: { + minArgs: 0, + maxArgs: 1, + fallbackToNoCallback: true, + }, + enable: { + minArgs: 0, + maxArgs: 1, + fallbackToNoCallback: true, + }, + getBadgeBackgroundColor: { + minArgs: 1, + maxArgs: 1, + }, + getBadgeText: { + minArgs: 1, + maxArgs: 1, + }, + getPopup: { + minArgs: 1, + maxArgs: 1, + }, + getTitle: { + minArgs: 1, + maxArgs: 1, + }, + openPopup: { + minArgs: 0, + maxArgs: 0, + }, + setBadgeBackgroundColor: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setBadgeText: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setIcon: { + minArgs: 1, + maxArgs: 1, + }, + setPopup: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setTitle: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + browsingData: { + remove: { + minArgs: 2, + maxArgs: 2, + }, + removeCache: { + minArgs: 1, + maxArgs: 1, + }, + removeCookies: { + minArgs: 1, + maxArgs: 1, + }, + removeDownloads: { + minArgs: 1, + maxArgs: 1, + }, + removeFormData: { + minArgs: 1, + maxArgs: 1, + }, + removeHistory: { + minArgs: 1, + maxArgs: 1, + }, + removeLocalStorage: { + minArgs: 1, + maxArgs: 1, + }, + removePasswords: { + minArgs: 1, + maxArgs: 1, + }, + removePluginData: { + minArgs: 1, + maxArgs: 1, + }, + settings: { + minArgs: 0, + maxArgs: 0, + }, + }, + commands: { + getAll: { + minArgs: 0, + maxArgs: 0, + }, + }, + contextMenus: { + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeAll: { + minArgs: 0, + maxArgs: 0, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + cookies: { + get: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 1, + maxArgs: 1, + }, + getAllCookieStores: { + minArgs: 0, + maxArgs: 0, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + devtools: { + inspectedWindow: { + eval: { + minArgs: 1, + maxArgs: 2, + singleCallbackArg: false, + }, + }, + panels: { + create: { + minArgs: 3, + maxArgs: 3, + singleCallbackArg: true, + }, + elements: { + createSidebarPane: { + minArgs: 1, + maxArgs: 1, + }, + }, + }, + }, + downloads: { + cancel: { + minArgs: 1, + maxArgs: 1, + }, + download: { + minArgs: 1, + maxArgs: 1, + }, + erase: { + minArgs: 1, + maxArgs: 1, + }, + getFileIcon: { + minArgs: 1, + maxArgs: 2, + }, + open: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + pause: { + minArgs: 1, + maxArgs: 1, + }, + removeFile: { + minArgs: 1, + maxArgs: 1, + }, + resume: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + show: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + extension: { + isAllowedFileSchemeAccess: { + minArgs: 0, + maxArgs: 0, + }, + isAllowedIncognitoAccess: { + minArgs: 0, + maxArgs: 0, + }, + }, + history: { + addUrl: { + minArgs: 1, + maxArgs: 1, + }, + deleteAll: { + minArgs: 0, + maxArgs: 0, + }, + deleteRange: { + minArgs: 1, + maxArgs: 1, + }, + deleteUrl: { + minArgs: 1, + maxArgs: 1, + }, + getVisits: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + }, + i18n: { + detectLanguage: { + minArgs: 1, + maxArgs: 1, + }, + getAcceptLanguages: { + minArgs: 0, + maxArgs: 0, + }, + }, + identity: { + launchWebAuthFlow: { + minArgs: 1, + maxArgs: 1, + }, + }, + idle: { + queryState: { + minArgs: 1, + maxArgs: 1, + }, + }, + management: { + get: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + getSelf: { + minArgs: 0, + maxArgs: 0, + }, + setEnabled: { + minArgs: 2, + maxArgs: 2, + }, + uninstallSelf: { + minArgs: 0, + maxArgs: 1, + }, + }, + notifications: { + clear: { + minArgs: 1, + maxArgs: 1, + }, + create: { + minArgs: 1, + maxArgs: 2, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + getPermissionLevel: { + minArgs: 0, + maxArgs: 0, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + pageAction: { + getPopup: { + minArgs: 1, + maxArgs: 1, + }, + getTitle: { + minArgs: 1, + maxArgs: 1, + }, + hide: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setIcon: { + minArgs: 1, + maxArgs: 1, + }, + setPopup: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setTitle: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + show: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + permissions: { + contains: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + request: { + minArgs: 1, + maxArgs: 1, + }, + }, + runtime: { + getBackgroundPage: { + minArgs: 0, + maxArgs: 0, + }, + getPlatformInfo: { + minArgs: 0, + maxArgs: 0, + }, + openOptionsPage: { + minArgs: 0, + maxArgs: 0, + }, + requestUpdateCheck: { + minArgs: 0, + maxArgs: 0, + }, + sendMessage: { + minArgs: 1, + maxArgs: 3, + }, + sendNativeMessage: { + minArgs: 2, + maxArgs: 2, + }, + setUninstallURL: { + minArgs: 1, + maxArgs: 1, + }, + }, + sessions: { + getDevices: { + minArgs: 0, + maxArgs: 1, + }, + getRecentlyClosed: { + minArgs: 0, + maxArgs: 1, + }, + restore: { + minArgs: 0, + maxArgs: 1, + }, + }, + storage: { + local: { + clear: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + managed: { + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + }, + sync: { + clear: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + }, + tabs: { + captureVisibleTab: { + minArgs: 0, + maxArgs: 2, + }, + create: { + minArgs: 1, + maxArgs: 1, + }, + detectLanguage: { + minArgs: 0, + maxArgs: 1, + }, + discard: { + minArgs: 0, + maxArgs: 1, + }, + duplicate: { + minArgs: 1, + maxArgs: 1, + }, + executeScript: { + minArgs: 1, + maxArgs: 2, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + getCurrent: { + minArgs: 0, + maxArgs: 0, + }, + getZoom: { + minArgs: 0, + maxArgs: 1, + }, + getZoomSettings: { + minArgs: 0, + maxArgs: 1, + }, + goBack: { + minArgs: 0, + maxArgs: 1, + }, + goForward: { + minArgs: 0, + maxArgs: 1, + }, + highlight: { + minArgs: 1, + maxArgs: 1, + }, + insertCSS: { + minArgs: 1, + maxArgs: 2, + }, + move: { + minArgs: 2, + maxArgs: 2, + }, + query: { + minArgs: 1, + maxArgs: 1, + }, + reload: { + minArgs: 0, + maxArgs: 2, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeCSS: { + minArgs: 1, + maxArgs: 2, + }, + sendMessage: { + minArgs: 2, + maxArgs: 3, + }, + setZoom: { + minArgs: 1, + maxArgs: 2, + }, + setZoomSettings: { + minArgs: 1, + maxArgs: 2, + }, + update: { + minArgs: 1, + maxArgs: 2, + }, + }, + topSites: { + get: { + minArgs: 0, + maxArgs: 0, + }, + }, + webNavigation: { + getAllFrames: { + minArgs: 1, + maxArgs: 1, + }, + getFrame: { + minArgs: 1, + maxArgs: 1, + }, + }, + webRequest: { + handlerBehaviorChanged: { + minArgs: 0, + maxArgs: 0, + }, + }, + windows: { + create: { + minArgs: 0, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 2, + }, + getAll: { + minArgs: 0, + maxArgs: 1, + }, + getCurrent: { + minArgs: 0, + maxArgs: 1, + }, + getLastFocused: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + }; + if (Object.keys(apiMetadata).length === 0) { + throw new Error( + "api-metadata.json has not been included in browser-polyfill", + ); + } + class DefaultWeakMap extends WeakMap { + constructor(createItem, items = void 0) { + super(items); + this.createItem = createItem; + } + get(key) { + if (!this.has(key)) { + this.set(key, this.createItem(key)); + } + return super.get(key); + } + } + const isThenable = (value) => { + return ( + value && + typeof value === "object" && + typeof value.then === "function" + ); + }; + const makeCallback = (promise, metadata) => { + return (...callbackArgs) => { + if (extensionAPIs.runtime.lastError) { + promise.reject( + new Error(extensionAPIs.runtime.lastError.message), + ); + } else if ( + metadata.singleCallbackArg || + (callbackArgs.length <= 1 && + metadata.singleCallbackArg !== false) + ) { + promise.resolve(callbackArgs[0]); + } else { + promise.resolve(callbackArgs); + } + }; + }; + const pluralizeArguments = (numArgs) => + numArgs == 1 ? "argument" : "arguments"; + const wrapAsyncFunction = (name, metadata) => { + return function asyncFunctionWrapper(target, ...args) { + if (args.length < metadata.minArgs) { + throw new Error( + `Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`, + ); + } + if (args.length > metadata.maxArgs) { + throw new Error( + `Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`, + ); + } + return new Promise((resolve, reject) => { + if (metadata.fallbackToNoCallback) { + try { + target[name]( + ...args, + makeCallback( + { + resolve, + reject, + }, + metadata, + ), + ); + } catch (cbError) { + console.warn( + `${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, + cbError, + ); + target[name](...args); + metadata.fallbackToNoCallback = false; + metadata.noCallback = true; + resolve(); + } + } else if (metadata.noCallback) { + target[name](...args); + resolve(); + } else { + target[name]( + ...args, + makeCallback( + { + resolve, + reject, + }, + metadata, + ), + ); + } + }); + }; + }; + const wrapMethod = (target, method, wrapper) => { + return new Proxy(method, { + apply(targetMethod, thisObj, args) { + return wrapper.call(thisObj, target, ...args); + }, + }); + }; + const hasOwnProperty = Function.call.bind( + Object.prototype.hasOwnProperty, + ); + const wrapObject = (target, wrappers = {}, metadata = {}) => { + const cache = /* @__PURE__ */ Object.create(null); + const handlers = { + has(proxyTarget2, prop) { + return prop in target || prop in cache; + }, + get(proxyTarget2, prop, receiver) { + if (prop in cache) { + return cache[prop]; + } + if (!(prop in target)) { + return void 0; + } + let value = target[prop]; + if (typeof value === "function") { + if (typeof wrappers[prop] === "function") { + value = wrapMethod( + target, + target[prop], + wrappers[prop], + ); + } else if (hasOwnProperty(metadata, prop)) { + const wrapper = wrapAsyncFunction(prop, metadata[prop]); + value = wrapMethod(target, target[prop], wrapper); + } else { + value = value.bind(target); + } + } else if ( + typeof value === "object" && + value !== null && + (hasOwnProperty(wrappers, prop) || + hasOwnProperty(metadata, prop)) + ) { + value = wrapObject(value, wrappers[prop], metadata[prop]); + } else if (hasOwnProperty(metadata, "*")) { + value = wrapObject(value, wrappers[prop], metadata["*"]); + } else { + Object.defineProperty(cache, prop, { + configurable: true, + enumerable: true, + get() { + return target[prop]; + }, + set(value2) { + target[prop] = value2; + }, + }); + return value; + } + cache[prop] = value; + return value; + }, + set(proxyTarget2, prop, value, receiver) { + if (prop in cache) { + cache[prop] = value; + } else { + target[prop] = value; + } + return true; + }, + defineProperty(proxyTarget2, prop, desc) { + return Reflect.defineProperty(cache, prop, desc); + }, + deleteProperty(proxyTarget2, prop) { + return Reflect.deleteProperty(cache, prop); + }, + }; + const proxyTarget = Object.create(target); + return new Proxy(proxyTarget, handlers); + }; + const wrapEvent = (wrapperMap) => ({ + addListener(target, listener, ...args) { + target.addListener(wrapperMap.get(listener), ...args); + }, + hasListener(target, listener) { + return target.hasListener(wrapperMap.get(listener)); + }, + removeListener(target, listener) { + target.removeListener(wrapperMap.get(listener)); + }, + }); + const onRequestFinishedWrappers = new DefaultWeakMap( + (listener) => { + if (typeof listener !== "function") { + return listener; + } + return function onRequestFinished(req) { + const wrappedReq = wrapObject( + req, + {}, + { + getContent: { + minArgs: 0, + maxArgs: 0, + }, + }, + ); + listener(wrappedReq); + }; + }, + ); + let loggedSendResponseDeprecationWarning = false; + const onMessageWrappers = new DefaultWeakMap((listener) => { + if (typeof listener !== "function") { + return listener; + } + return function onMessage(message, sender, sendResponse) { + let didCallSendResponse = false; + let wrappedSendResponse; + const sendResponsePromise = new Promise((resolve) => { + wrappedSendResponse = (response) => { + if (!loggedSendResponseDeprecationWarning) { + console.warn( + SEND_RESPONSE_DEPRECATION_WARNING, + new Error().stack, + ); + loggedSendResponseDeprecationWarning = true; + } + didCallSendResponse = true; + resolve(response); + }; + }); + let result; + try { + result = listener(message, sender, wrappedSendResponse); + } catch (err) { + result = Promise.reject(err); + } + const isResultThenable = + result !== true && isThenable(result); + if ( + result !== true && + !isResultThenable && + !didCallSendResponse + ) { + return false; + } + const sendPromisedResult = (promise) => { + promise + .then( + (msg) => { + sendResponse(msg); + }, + (error) => { + let message2; + if ( + error && + (error instanceof Error || + typeof error.message === "string") + ) { + message2 = error.message; + } else { + message2 = "An unexpected error occurred"; + } + sendResponse({ + __mozWebExtensionPolyfillReject__: true, + message: message2, + }); + }, + ) + .catch((err) => { + console.error( + "Failed to send onMessage rejected reply", + err, + ); + }); + }; + if (isResultThenable) { + sendPromisedResult(result); + } else { + sendPromisedResult(sendResponsePromise); + } + return true; + }; + }); + const wrappedSendMessageCallback = ( + { reject, resolve }, + reply, + ) => { + if (extensionAPIs.runtime.lastError) { + if ( + extensionAPIs.runtime.lastError.message === + CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE + ) { + resolve(); + } else { + reject(new Error(extensionAPIs.runtime.lastError.message)); + } + } else if (reply && reply.__mozWebExtensionPolyfillReject__) { + reject(new Error(reply.message)); + } else { + resolve(reply); + } + }; + const wrappedSendMessage = ( + name, + metadata, + apiNamespaceObj, + ...args + ) => { + if (args.length < metadata.minArgs) { + throw new Error( + `Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`, + ); + } + if (args.length > metadata.maxArgs) { + throw new Error( + `Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`, + ); + } + return new Promise((resolve, reject) => { + const wrappedCb = wrappedSendMessageCallback.bind(null, { + resolve, + reject, + }); + args.push(wrappedCb); + apiNamespaceObj.sendMessage(...args); + }); + }; + const staticWrappers = { + devtools: { + network: { + onRequestFinished: wrapEvent(onRequestFinishedWrappers), + }, + }, + runtime: { + onMessage: wrapEvent(onMessageWrappers), + onMessageExternal: wrapEvent(onMessageWrappers), + sendMessage: wrappedSendMessage.bind(null, "sendMessage", { + minArgs: 1, + maxArgs: 3, + }), + }, + tabs: { + sendMessage: wrappedSendMessage.bind(null, "sendMessage", { + minArgs: 2, + maxArgs: 3, + }), + }, + }; + const settingMetadata = { + clear: { + minArgs: 1, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }; + apiMetadata.privacy = { + network: { + "*": settingMetadata, + }, + services: { + "*": settingMetadata, + }, + websites: { + "*": settingMetadata, + }, + }; + return wrapObject(extensionAPIs, staticWrappers, apiMetadata); + }; + if ( + typeof chrome != "object" || + !chrome || + !chrome.runtime || + !chrome.runtime.id + ) { + throw new Error( + "This script should only be loaded in a browser extension.", + ); + } + module2.exports = wrapAPIs(chrome); + } else { + module2.exports = browser; + } + }, + ); + }, + }); - // extension/content-script.js - var import_webextension_polyfill = __toESM(require_browser_polyfill()); - var EXTENSION = "nostrconnect"; - var script = document.createElement("script"); - script.setAttribute("async", "false"); - script.setAttribute("type", "text/javascript"); - script.setAttribute("src", import_webextension_polyfill.default.runtime.getURL("nostr-provider.js")); - document.head.appendChild(script); - self.addEventListener("message", async (message) => { - if (message.source !== self) - return; - if (!message.data) - return; - if (!message.data.params) - return; - if (message.data.ext !== EXTENSION) - return; - var response; - try { - response = await import_webextension_polyfill.default.runtime.sendMessage({ - type: message.data.type, - params: message.data.params, - host: location.host - }); - } catch (error) { - response = { error }; - } - self.postMessage( - { id: message.data.id, ext: EXTENSION, response }, - message.origin - ); - }); + // extension/content-script.js + var import_webextension_polyfill = __toESM(require_browser_polyfill()); + var EXTENSION = "nostrconnect"; + var script = document.createElement("script"); + script.setAttribute("async", "false"); + script.setAttribute("type", "text/javascript"); + script.setAttribute( + "src", + import_webextension_polyfill.default.runtime.getURL("nostr-provider.js"), + ); + document.head.appendChild(script); + self.addEventListener("message", async (message) => { + if (message.source !== self) return; + if (!message.data) return; + if (!message.data.params) return; + if (message.data.ext !== EXTENSION) return; + var response; + try { + response = await import_webextension_polyfill.default.runtime.sendMessage( + { + type: message.data.type, + params: message.data.params, + host: location.host, + }, + ); + } catch (error) { + response = { error }; + } + self.postMessage( + { id: message.data.id, ext: EXTENSION, response }, + message.origin, + ); + }); })(); diff --git a/extension/output/manifest.json b/extension/output/manifest.json index b786aca..3e8973e 100644 --- a/extension/output/manifest.json +++ b/extension/output/manifest.json @@ -1,35 +1,36 @@ { - "name": "Nostr Connect", - "description": "Nostr Signer Extension", - "version": "0.1.2", - "homepage_url": "https://github.com/reyamir/nostr-connect", - "manifest_version": 2, - "browser_specific_settings": { - "gecko": { - "id": "{e665d138-0e5b-4b7a-ab91-7af834eda7a2}" - } - }, - "icons": { - "16": "icons/icon16.png", - "32": "icons/icon32.png", - "48": "icons/icon48.png", - "128": "icons/icon128.png" - }, - "options_page": "options.html", - "background": { - "scripts": ["background.build.js"] - }, - "browser_action": { - "default_title": "Nostr Connect", - "default_popup": "popup.html" - }, - "content_scripts": [ - { - "matches": [""], - "js": ["content-script.build.js"] - } - ], - "permissions": ["storage"], - "optional_permissions": ["notifications"], - "web_accessible_resources": ["nostr-provider.js"] + "name": "Nostr Connect", + "description": "Nostr Signer Extension", + "version": "0.1.2", + "homepage_url": "https://github.com/reyamir/nostr-connect", + "manifest_version": 3, + "icons": { + "16": "icons/icon16.png", + "32": "icons/icon32.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + }, + "options_page": "options.html", + "background": { + "service_worker": "background.build.js" + }, + "action": { + "default_title": "Nostr Connect", + "default_popup": "popup.html" + }, + "content_scripts": [ + { + "matches": [""], + "js": ["content-script.build.js"], + "all_frames": true + } + ], + "permissions": ["storage"], + "optional_permissions": ["notifications"], + "web_accessible_resources": [ + { + "resources": ["nostr-provider.js"], + "matches": ["https://*/*", "http://localhost:*/*"] + } + ] } diff --git a/extension/output/nostr-provider.js b/extension/output/nostr-provider.js index 945b471..de31cd2 100644 --- a/extension/output/nostr-provider.js +++ b/extension/output/nostr-provider.js @@ -1,114 +1,108 @@ -const EXTENSION = 'nostrconnect' +const EXTENSION = "nostrconnect"; window.nostr = { - _requests: {}, - _pubkey: null, + _requests: {}, + _pubkey: null, - async getPublicKey() { - if (this._pubkey) return this._pubkey - this._pubkey = await this._call('getPublicKey', {}) - return this._pubkey - }, + async getPublicKey() { + if (this._pubkey) return this._pubkey; + this._pubkey = await this._call("getPublicKey", {}); + return this._pubkey; + }, - async signEvent(event) { - return this._call('signEvent', {event}) - }, + async signEvent(event) { + return this._call("signEvent", { event }); + }, - async getRelays() { - return this._call('getRelays', {}) - }, + async getRelays() { + return this._call("getRelays", {}); + }, - nip04: { - async encrypt(peer, plaintext) { - return window.nostr._call('nip04.encrypt', {peer, plaintext}) - }, + nip04: { + async encrypt(peer, plaintext) { + return window.nostr._call("nip04.encrypt", { peer, plaintext }); + }, - async decrypt(peer, ciphertext) { - return window.nostr._call('nip04.decrypt', {peer, ciphertext}) - } - }, + async decrypt(peer, ciphertext) { + return window.nostr._call("nip04.decrypt", { peer, ciphertext }); + }, + }, - _call(type, params) { - let id = Math.random().toString().slice(-4) - console.log( - '%c[nostrconnect:%c' + - id + - '%c]%c calling %c' + - type + - '%c with %c' + - JSON.stringify(params || {}), - 'background-color:#f1b912;font-weight:bold;color:white', - 'background-color:#f1b912;font-weight:bold;color:#a92727', - 'background-color:#f1b912;color:white;font-weight:bold', - 'color:auto', - 'font-weight:bold;color:#08589d;font-family:monospace', - 'color:auto', - 'font-weight:bold;color:#90b12d;font-family:monospace' - ) - return new Promise((resolve, reject) => { - this._requests[id] = {resolve, reject} - window.postMessage( - { - id, - ext: EXTENSION, - type, - params - }, - '*' - ) - }) - } -} + _call(type, params) { + const id = Math.random().toString().slice(-4); + console.log( + `%c[nostrconnect:%c${id}%c]%c calling %c${type}%c with %c${JSON.stringify(params || {})}`, + "background-color:#f1b912;font-weight:bold;color:white", + "background-color:#f1b912;font-weight:bold;color:#a92727", + "background-color:#f1b912;color:white;font-weight:bold", + "color:auto", + "font-weight:bold;color:#08589d;font-family:monospace", + "color:auto", + "font-weight:bold;color:#90b12d;font-family:monospace", + ); + return new Promise((resolve, reject) => { + this._requests[id] = { resolve, reject }; + window.postMessage( + { + id, + ext: EXTENSION, + type, + params, + }, + "*", + ); + }); + }, +}; -window.addEventListener('message', message => { - if ( - !message.data || - message.data.response === null || - message.data.response === undefined || - message.data.ext !== EXTENSION || - !window.nostr._requests[message.data.id] - ) - return +window.addEventListener("message", (message) => { + if ( + !message.data || + message.data.response === null || + message.data.response === undefined || + message.data.ext !== EXTENSION || + !window.nostr._requests[message.data.id] + ) + return; - if (message.data.response.error) { - let error = new Error( - `${EXTENSION}: ` + message.data.response.error.message - ) - error.stack = message.data.response.error.stack - window.nostr._requests[message.data.id].reject(error) - } else { - window.nostr._requests[message.data.id].resolve(message.data.response) - } + if (message.data.response.error) { + const error = new Error( + `${EXTENSION}: ${message.data.response.error.message}`, + ); + error.stack = message.data.response.error.stack; + window.nostr._requests[message.data.id].reject(error); + } else { + window.nostr._requests[message.data.id].resolve(message.data.response); + } - console.log( - '%c[nostrconnect:%c' + - message.data.id + - '%c]%c result: %c' + - JSON.stringify( - message?.data?.response || message?.data?.response?.error?.message || {} - ), - 'background-color:#f1b912;font-weight:bold;color:white', - 'background-color:#f1b912;font-weight:bold;color:#a92727', - 'background-color:#f1b912;color:white;font-weight:bold', - 'color:auto', - 'font-weight:bold;color:#08589d' - ) + console.log( + `%c[nostrconnect:%c${message.data.id}%c]%c result: %c${JSON.stringify( + message?.data?.response || message?.data?.response?.error?.message || {}, + )}`, + "background-color:#f1b912;font-weight:bold;color:white", + "background-color:#f1b912;font-weight:bold;color:#a92727", + "background-color:#f1b912;color:white;font-weight:bold", + "color:auto", + "font-weight:bold;color:#08589d", + ); - delete window.nostr._requests[message.data.id] -}) + delete window.nostr._requests[message.data.id]; +}); // hack to replace nostr:nprofile.../etc links with something else -let replacing = null -document.addEventListener('mousedown', replaceNostrSchemeLink) +let replacing = null; +document.addEventListener("mousedown", replaceNostrSchemeLink); async function replaceNostrSchemeLink(e) { - if (e.target.tagName !== 'A' || !e.target.href.startsWith('nostr:')) return - if (replacing === false) return + if (e.target.tagName !== "A" || !e.target.href.startsWith("nostr:")) return; + if (replacing === false) return; - let response = await window.nostr._call('replaceURL', {url: e.target.href}) - if (response === false) { - replacing = false - return - } + const response = await window.nostr._call("replaceURL", { + url: e.target.href, + }); + if (response === false) { + replacing = false; + return; + } - e.target.href = response + e.target.href = response; } diff --git a/extension/output/prompt.build.js b/extension/output/prompt.build.js index 6a7b848..5563e69 100644 --- a/extension/output/prompt.build.js +++ b/extension/output/prompt.build.js @@ -1,22433 +1,27601 @@ (() => { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod - )); + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __commonJS = (cb, mod) => + function __require() { + return ( + mod || + (0, cb[__getOwnPropNames(cb)[0]])( + (mod = { exports: {} }).exports, + mod, + ), + mod.exports + ); + }; + var __copyProps = (to, from, except, desc) => { + if ((from && typeof from === "object") || typeof from === "function") { + for (const key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { + get: () => from[key], + enumerable: + !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => ( + (target = mod != null ? __create(__getProtoOf(mod)) : {}), + __copyProps( + isNodeMode || !mod || !mod.__esModule + ? __defProp(target, "default", { value: mod, enumerable: true }) + : target, + mod, + ) + ); - // node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js - var require_browser_polyfill = __commonJS({ - "node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module) { - (function(global, factory) { - if (typeof define === "function" && define.amd) { - define("webextension-polyfill", ["module"], factory); - } else if (typeof exports !== "undefined") { - factory(module); - } else { - var mod = { - exports: {} - }; - factory(mod); - global.browser = mod.exports; - } - })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports, function(module2) { - "use strict"; - if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) { - const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received."; - const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; - const wrapAPIs = (extensionAPIs) => { - const apiMetadata = { - "alarms": { - "clear": { - "minArgs": 0, - "maxArgs": 1 - }, - "clearAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "bookmarks": { - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getChildren": { - "minArgs": 1, - "maxArgs": 1 - }, - "getRecent": { - "minArgs": 1, - "maxArgs": 1 - }, - "getSubTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTree": { - "minArgs": 0, - "maxArgs": 0 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "browserAction": { - "disable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "enable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "getBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1 - }, - "getBadgeText": { - "minArgs": 1, - "maxArgs": 1 - }, - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "openPopup": { - "minArgs": 0, - "maxArgs": 0 - }, - "setBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setBadgeText": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "browsingData": { - "remove": { - "minArgs": 2, - "maxArgs": 2 - }, - "removeCache": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCookies": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeDownloads": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFormData": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeHistory": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeLocalStorage": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePasswords": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePluginData": { - "minArgs": 1, - "maxArgs": 1 - }, - "settings": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "commands": { - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "contextMenus": { - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "cookies": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAllCookieStores": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "devtools": { - "inspectedWindow": { - "eval": { - "minArgs": 1, - "maxArgs": 2, - "singleCallbackArg": false - } - }, - "panels": { - "create": { - "minArgs": 3, - "maxArgs": 3, - "singleCallbackArg": true - }, - "elements": { - "createSidebarPane": { - "minArgs": 1, - "maxArgs": 1 - } - } - } - }, - "downloads": { - "cancel": { - "minArgs": 1, - "maxArgs": 1 - }, - "download": { - "minArgs": 1, - "maxArgs": 1 - }, - "erase": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFileIcon": { - "minArgs": 1, - "maxArgs": 2 - }, - "open": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "pause": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFile": { - "minArgs": 1, - "maxArgs": 1 - }, - "resume": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "extension": { - "isAllowedFileSchemeAccess": { - "minArgs": 0, - "maxArgs": 0 - }, - "isAllowedIncognitoAccess": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "history": { - "addUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "deleteRange": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "getVisits": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "i18n": { - "detectLanguage": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAcceptLanguages": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "identity": { - "launchWebAuthFlow": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "idle": { - "queryState": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "management": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getSelf": { - "minArgs": 0, - "maxArgs": 0 - }, - "setEnabled": { - "minArgs": 2, - "maxArgs": 2 - }, - "uninstallSelf": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "notifications": { - "clear": { - "minArgs": 1, - "maxArgs": 1 - }, - "create": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPermissionLevel": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "pageAction": { - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "hide": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "permissions": { - "contains": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "request": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "runtime": { - "getBackgroundPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPlatformInfo": { - "minArgs": 0, - "maxArgs": 0 - }, - "openOptionsPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "requestUpdateCheck": { - "minArgs": 0, - "maxArgs": 0 - }, - "sendMessage": { - "minArgs": 1, - "maxArgs": 3 - }, - "sendNativeMessage": { - "minArgs": 2, - "maxArgs": 2 - }, - "setUninstallURL": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "sessions": { - "getDevices": { - "minArgs": 0, - "maxArgs": 1 - }, - "getRecentlyClosed": { - "minArgs": 0, - "maxArgs": 1 - }, - "restore": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "storage": { - "local": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "managed": { - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "sync": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - } - }, - "tabs": { - "captureVisibleTab": { - "minArgs": 0, - "maxArgs": 2 - }, - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "detectLanguage": { - "minArgs": 0, - "maxArgs": 1 - }, - "discard": { - "minArgs": 0, - "maxArgs": 1 - }, - "duplicate": { - "minArgs": 1, - "maxArgs": 1 - }, - "executeScript": { - "minArgs": 1, - "maxArgs": 2 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 0 - }, - "getZoom": { - "minArgs": 0, - "maxArgs": 1 - }, - "getZoomSettings": { - "minArgs": 0, - "maxArgs": 1 - }, - "goBack": { - "minArgs": 0, - "maxArgs": 1 - }, - "goForward": { - "minArgs": 0, - "maxArgs": 1 - }, - "highlight": { - "minArgs": 1, - "maxArgs": 1 - }, - "insertCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "query": { - "minArgs": 1, - "maxArgs": 1 - }, - "reload": { - "minArgs": 0, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "sendMessage": { - "minArgs": 2, - "maxArgs": 3 - }, - "setZoom": { - "minArgs": 1, - "maxArgs": 2 - }, - "setZoomSettings": { - "minArgs": 1, - "maxArgs": 2 - }, - "update": { - "minArgs": 1, - "maxArgs": 2 - } - }, - "topSites": { - "get": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "webNavigation": { - "getAllFrames": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFrame": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "webRequest": { - "handlerBehaviorChanged": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "windows": { - "create": { - "minArgs": 0, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 1 - }, - "getLastFocused": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - } - }; - if (Object.keys(apiMetadata).length === 0) { - throw new Error("api-metadata.json has not been included in browser-polyfill"); - } - class DefaultWeakMap extends WeakMap { - constructor(createItem, items = void 0) { - super(items); - this.createItem = createItem; - } - get(key) { - if (!this.has(key)) { - this.set(key, this.createItem(key)); - } - return super.get(key); - } - } - const isThenable = (value) => { - return value && typeof value === "object" && typeof value.then === "function"; - }; - const makeCallback = (promise, metadata) => { - return (...callbackArgs) => { - if (extensionAPIs.runtime.lastError) { - promise.reject(new Error(extensionAPIs.runtime.lastError.message)); - } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) { - promise.resolve(callbackArgs[0]); - } else { - promise.resolve(callbackArgs); - } - }; - }; - const pluralizeArguments = (numArgs) => numArgs == 1 ? "argument" : "arguments"; - const wrapAsyncFunction = (name, metadata) => { - return function asyncFunctionWrapper(target, ...args) { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - return new Promise((resolve, reject) => { - if (metadata.fallbackToNoCallback) { - try { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } catch (cbError) { - console.warn(`${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, cbError); - target[name](...args); - metadata.fallbackToNoCallback = false; - metadata.noCallback = true; - resolve(); - } - } else if (metadata.noCallback) { - target[name](...args); - resolve(); - } else { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } - }); - }; - }; - const wrapMethod = (target, method, wrapper) => { - return new Proxy(method, { - apply(targetMethod, thisObj, args) { - return wrapper.call(thisObj, target, ...args); - } - }); - }; - let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); - const wrapObject = (target, wrappers = {}, metadata = {}) => { - let cache = /* @__PURE__ */ Object.create(null); - let handlers = { - has(proxyTarget2, prop) { - return prop in target || prop in cache; - }, - get(proxyTarget2, prop, receiver) { - if (prop in cache) { - return cache[prop]; - } - if (!(prop in target)) { - return void 0; - } - let value = target[prop]; - if (typeof value === "function") { - if (typeof wrappers[prop] === "function") { - value = wrapMethod(target, target[prop], wrappers[prop]); - } else if (hasOwnProperty(metadata, prop)) { - let wrapper = wrapAsyncFunction(prop, metadata[prop]); - value = wrapMethod(target, target[prop], wrapper); - } else { - value = value.bind(target); - } - } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) { - value = wrapObject(value, wrappers[prop], metadata[prop]); - } else if (hasOwnProperty(metadata, "*")) { - value = wrapObject(value, wrappers[prop], metadata["*"]); - } else { - Object.defineProperty(cache, prop, { - configurable: true, - enumerable: true, - get() { - return target[prop]; - }, - set(value2) { - target[prop] = value2; - } - }); - return value; - } - cache[prop] = value; - return value; - }, - set(proxyTarget2, prop, value, receiver) { - if (prop in cache) { - cache[prop] = value; - } else { - target[prop] = value; - } - return true; - }, - defineProperty(proxyTarget2, prop, desc) { - return Reflect.defineProperty(cache, prop, desc); - }, - deleteProperty(proxyTarget2, prop) { - return Reflect.deleteProperty(cache, prop); - } - }; - let proxyTarget = Object.create(target); - return new Proxy(proxyTarget, handlers); - }; - const wrapEvent = (wrapperMap) => ({ - addListener(target, listener, ...args) { - target.addListener(wrapperMap.get(listener), ...args); - }, - hasListener(target, listener) { - return target.hasListener(wrapperMap.get(listener)); - }, - removeListener(target, listener) { - target.removeListener(wrapperMap.get(listener)); - } - }); - const onRequestFinishedWrappers = new DefaultWeakMap((listener) => { - if (typeof listener !== "function") { - return listener; - } - return function onRequestFinished(req) { - const wrappedReq = wrapObject( - req, - {}, - { - getContent: { - minArgs: 0, - maxArgs: 0 - } - } - ); - listener(wrappedReq); - }; - }); - let loggedSendResponseDeprecationWarning = false; - const onMessageWrappers = new DefaultWeakMap((listener) => { - if (typeof listener !== "function") { - return listener; - } - return function onMessage(message, sender, sendResponse) { - let didCallSendResponse = false; - let wrappedSendResponse; - let sendResponsePromise = new Promise((resolve) => { - wrappedSendResponse = function(response) { - if (!loggedSendResponseDeprecationWarning) { - console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack); - loggedSendResponseDeprecationWarning = true; - } - didCallSendResponse = true; - resolve(response); - }; - }); - let result; - try { - result = listener(message, sender, wrappedSendResponse); - } catch (err) { - result = Promise.reject(err); - } - const isResultThenable = result !== true && isThenable(result); - if (result !== true && !isResultThenable && !didCallSendResponse) { - return false; - } - const sendPromisedResult = (promise) => { - promise.then((msg) => { - sendResponse(msg); - }, (error) => { - let message2; - if (error && (error instanceof Error || typeof error.message === "string")) { - message2 = error.message; - } else { - message2 = "An unexpected error occurred"; - } - sendResponse({ - __mozWebExtensionPolyfillReject__: true, - message: message2 - }); - }).catch((err) => { - console.error("Failed to send onMessage rejected reply", err); - }); - }; - if (isResultThenable) { - sendPromisedResult(result); - } else { - sendPromisedResult(sendResponsePromise); - } - return true; - }; - }); - const wrappedSendMessageCallback = ({ - reject, - resolve - }, reply) => { - if (extensionAPIs.runtime.lastError) { - if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) { - resolve(); - } else { - reject(new Error(extensionAPIs.runtime.lastError.message)); - } - } else if (reply && reply.__mozWebExtensionPolyfillReject__) { - reject(new Error(reply.message)); - } else { - resolve(reply); - } - }; - const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - return new Promise((resolve, reject) => { - const wrappedCb = wrappedSendMessageCallback.bind(null, { - resolve, - reject - }); - args.push(wrappedCb); - apiNamespaceObj.sendMessage(...args); - }); - }; - const staticWrappers = { - devtools: { - network: { - onRequestFinished: wrapEvent(onRequestFinishedWrappers) - } - }, - runtime: { - onMessage: wrapEvent(onMessageWrappers), - onMessageExternal: wrapEvent(onMessageWrappers), - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 1, - maxArgs: 3 - }) - }, - tabs: { - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 2, - maxArgs: 3 - }) - } - }; - const settingMetadata = { - clear: { - minArgs: 1, - maxArgs: 1 - }, - get: { - minArgs: 1, - maxArgs: 1 - }, - set: { - minArgs: 1, - maxArgs: 1 - } - }; - apiMetadata.privacy = { - network: { - "*": settingMetadata - }, - services: { - "*": settingMetadata - }, - websites: { - "*": settingMetadata - } - }; - return wrapObject(extensionAPIs, staticWrappers, apiMetadata); - }; - if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) { - throw new Error("This script should only be loaded in a browser extension."); - } - module2.exports = wrapAPIs(chrome); - } else { - module2.exports = browser; - } - }); - } - }); + // node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js + var require_browser_polyfill = __commonJS({ + "node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"( + exports, + module, + ) { + ((global, factory) => { + if (typeof define === "function" && define.amd) { + define("webextension-polyfill", ["module"], factory); + } else if (typeof exports !== "undefined") { + factory(module); + } else { + var mod = { + exports: {}, + }; + factory(mod); + global.browser = mod.exports; + } + })( + typeof globalThis !== "undefined" + ? globalThis + : typeof self !== "undefined" + ? self + : exports, + (module2) => { + if ( + typeof browser === "undefined" || + Object.getPrototypeOf(browser) !== Object.prototype + ) { + const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = + "The message port closed before a response was received."; + const SEND_RESPONSE_DEPRECATION_WARNING = + "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; + const wrapAPIs = (extensionAPIs) => { + const apiMetadata = { + alarms: { + clear: { + minArgs: 0, + maxArgs: 1, + }, + clearAll: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + }, + bookmarks: { + create: { + minArgs: 1, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + getChildren: { + minArgs: 1, + maxArgs: 1, + }, + getRecent: { + minArgs: 1, + maxArgs: 1, + }, + getSubTree: { + minArgs: 1, + maxArgs: 1, + }, + getTree: { + minArgs: 0, + maxArgs: 0, + }, + move: { + minArgs: 2, + maxArgs: 2, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeTree: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + browserAction: { + disable: { + minArgs: 0, + maxArgs: 1, + fallbackToNoCallback: true, + }, + enable: { + minArgs: 0, + maxArgs: 1, + fallbackToNoCallback: true, + }, + getBadgeBackgroundColor: { + minArgs: 1, + maxArgs: 1, + }, + getBadgeText: { + minArgs: 1, + maxArgs: 1, + }, + getPopup: { + minArgs: 1, + maxArgs: 1, + }, + getTitle: { + minArgs: 1, + maxArgs: 1, + }, + openPopup: { + minArgs: 0, + maxArgs: 0, + }, + setBadgeBackgroundColor: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setBadgeText: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setIcon: { + minArgs: 1, + maxArgs: 1, + }, + setPopup: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setTitle: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + browsingData: { + remove: { + minArgs: 2, + maxArgs: 2, + }, + removeCache: { + minArgs: 1, + maxArgs: 1, + }, + removeCookies: { + minArgs: 1, + maxArgs: 1, + }, + removeDownloads: { + minArgs: 1, + maxArgs: 1, + }, + removeFormData: { + minArgs: 1, + maxArgs: 1, + }, + removeHistory: { + minArgs: 1, + maxArgs: 1, + }, + removeLocalStorage: { + minArgs: 1, + maxArgs: 1, + }, + removePasswords: { + minArgs: 1, + maxArgs: 1, + }, + removePluginData: { + minArgs: 1, + maxArgs: 1, + }, + settings: { + minArgs: 0, + maxArgs: 0, + }, + }, + commands: { + getAll: { + minArgs: 0, + maxArgs: 0, + }, + }, + contextMenus: { + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeAll: { + minArgs: 0, + maxArgs: 0, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + cookies: { + get: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 1, + maxArgs: 1, + }, + getAllCookieStores: { + minArgs: 0, + maxArgs: 0, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + devtools: { + inspectedWindow: { + eval: { + minArgs: 1, + maxArgs: 2, + singleCallbackArg: false, + }, + }, + panels: { + create: { + minArgs: 3, + maxArgs: 3, + singleCallbackArg: true, + }, + elements: { + createSidebarPane: { + minArgs: 1, + maxArgs: 1, + }, + }, + }, + }, + downloads: { + cancel: { + minArgs: 1, + maxArgs: 1, + }, + download: { + minArgs: 1, + maxArgs: 1, + }, + erase: { + minArgs: 1, + maxArgs: 1, + }, + getFileIcon: { + minArgs: 1, + maxArgs: 2, + }, + open: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + pause: { + minArgs: 1, + maxArgs: 1, + }, + removeFile: { + minArgs: 1, + maxArgs: 1, + }, + resume: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + show: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + extension: { + isAllowedFileSchemeAccess: { + minArgs: 0, + maxArgs: 0, + }, + isAllowedIncognitoAccess: { + minArgs: 0, + maxArgs: 0, + }, + }, + history: { + addUrl: { + minArgs: 1, + maxArgs: 1, + }, + deleteAll: { + minArgs: 0, + maxArgs: 0, + }, + deleteRange: { + minArgs: 1, + maxArgs: 1, + }, + deleteUrl: { + minArgs: 1, + maxArgs: 1, + }, + getVisits: { + minArgs: 1, + maxArgs: 1, + }, + search: { + minArgs: 1, + maxArgs: 1, + }, + }, + i18n: { + detectLanguage: { + minArgs: 1, + maxArgs: 1, + }, + getAcceptLanguages: { + minArgs: 0, + maxArgs: 0, + }, + }, + identity: { + launchWebAuthFlow: { + minArgs: 1, + maxArgs: 1, + }, + }, + idle: { + queryState: { + minArgs: 1, + maxArgs: 1, + }, + }, + management: { + get: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + getSelf: { + minArgs: 0, + maxArgs: 0, + }, + setEnabled: { + minArgs: 2, + maxArgs: 2, + }, + uninstallSelf: { + minArgs: 0, + maxArgs: 1, + }, + }, + notifications: { + clear: { + minArgs: 1, + maxArgs: 1, + }, + create: { + minArgs: 1, + maxArgs: 2, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + getPermissionLevel: { + minArgs: 0, + maxArgs: 0, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + pageAction: { + getPopup: { + minArgs: 1, + maxArgs: 1, + }, + getTitle: { + minArgs: 1, + maxArgs: 1, + }, + hide: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setIcon: { + minArgs: 1, + maxArgs: 1, + }, + setPopup: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + setTitle: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + show: { + minArgs: 1, + maxArgs: 1, + fallbackToNoCallback: true, + }, + }, + permissions: { + contains: { + minArgs: 1, + maxArgs: 1, + }, + getAll: { + minArgs: 0, + maxArgs: 0, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + request: { + minArgs: 1, + maxArgs: 1, + }, + }, + runtime: { + getBackgroundPage: { + minArgs: 0, + maxArgs: 0, + }, + getPlatformInfo: { + minArgs: 0, + maxArgs: 0, + }, + openOptionsPage: { + minArgs: 0, + maxArgs: 0, + }, + requestUpdateCheck: { + minArgs: 0, + maxArgs: 0, + }, + sendMessage: { + minArgs: 1, + maxArgs: 3, + }, + sendNativeMessage: { + minArgs: 2, + maxArgs: 2, + }, + setUninstallURL: { + minArgs: 1, + maxArgs: 1, + }, + }, + sessions: { + getDevices: { + minArgs: 0, + maxArgs: 1, + }, + getRecentlyClosed: { + minArgs: 0, + maxArgs: 1, + }, + restore: { + minArgs: 0, + maxArgs: 1, + }, + }, + storage: { + local: { + clear: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + managed: { + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + }, + sync: { + clear: { + minArgs: 0, + maxArgs: 0, + }, + get: { + minArgs: 0, + maxArgs: 1, + }, + getBytesInUse: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }, + }, + tabs: { + captureVisibleTab: { + minArgs: 0, + maxArgs: 2, + }, + create: { + minArgs: 1, + maxArgs: 1, + }, + detectLanguage: { + minArgs: 0, + maxArgs: 1, + }, + discard: { + minArgs: 0, + maxArgs: 1, + }, + duplicate: { + minArgs: 1, + maxArgs: 1, + }, + executeScript: { + minArgs: 1, + maxArgs: 2, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + getCurrent: { + minArgs: 0, + maxArgs: 0, + }, + getZoom: { + minArgs: 0, + maxArgs: 1, + }, + getZoomSettings: { + minArgs: 0, + maxArgs: 1, + }, + goBack: { + minArgs: 0, + maxArgs: 1, + }, + goForward: { + minArgs: 0, + maxArgs: 1, + }, + highlight: { + minArgs: 1, + maxArgs: 1, + }, + insertCSS: { + minArgs: 1, + maxArgs: 2, + }, + move: { + minArgs: 2, + maxArgs: 2, + }, + query: { + minArgs: 1, + maxArgs: 1, + }, + reload: { + minArgs: 0, + maxArgs: 2, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + removeCSS: { + minArgs: 1, + maxArgs: 2, + }, + sendMessage: { + minArgs: 2, + maxArgs: 3, + }, + setZoom: { + minArgs: 1, + maxArgs: 2, + }, + setZoomSettings: { + minArgs: 1, + maxArgs: 2, + }, + update: { + minArgs: 1, + maxArgs: 2, + }, + }, + topSites: { + get: { + minArgs: 0, + maxArgs: 0, + }, + }, + webNavigation: { + getAllFrames: { + minArgs: 1, + maxArgs: 1, + }, + getFrame: { + minArgs: 1, + maxArgs: 1, + }, + }, + webRequest: { + handlerBehaviorChanged: { + minArgs: 0, + maxArgs: 0, + }, + }, + windows: { + create: { + minArgs: 0, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 2, + }, + getAll: { + minArgs: 0, + maxArgs: 1, + }, + getCurrent: { + minArgs: 0, + maxArgs: 1, + }, + getLastFocused: { + minArgs: 0, + maxArgs: 1, + }, + remove: { + minArgs: 1, + maxArgs: 1, + }, + update: { + minArgs: 2, + maxArgs: 2, + }, + }, + }; + if (Object.keys(apiMetadata).length === 0) { + throw new Error( + "api-metadata.json has not been included in browser-polyfill", + ); + } + class DefaultWeakMap extends WeakMap { + constructor(createItem, items = void 0) { + super(items); + this.createItem = createItem; + } + get(key) { + if (!this.has(key)) { + this.set(key, this.createItem(key)); + } + return super.get(key); + } + } + const isThenable = (value) => { + return ( + value && + typeof value === "object" && + typeof value.then === "function" + ); + }; + const makeCallback = (promise, metadata) => { + return (...callbackArgs) => { + if (extensionAPIs.runtime.lastError) { + promise.reject( + new Error(extensionAPIs.runtime.lastError.message), + ); + } else if ( + metadata.singleCallbackArg || + (callbackArgs.length <= 1 && + metadata.singleCallbackArg !== false) + ) { + promise.resolve(callbackArgs[0]); + } else { + promise.resolve(callbackArgs); + } + }; + }; + const pluralizeArguments = (numArgs) => + numArgs == 1 ? "argument" : "arguments"; + const wrapAsyncFunction = (name, metadata) => { + return function asyncFunctionWrapper(target, ...args) { + if (args.length < metadata.minArgs) { + throw new Error( + `Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`, + ); + } + if (args.length > metadata.maxArgs) { + throw new Error( + `Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`, + ); + } + return new Promise((resolve, reject) => { + if (metadata.fallbackToNoCallback) { + try { + target[name]( + ...args, + makeCallback( + { + resolve, + reject, + }, + metadata, + ), + ); + } catch (cbError) { + console.warn( + `${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, + cbError, + ); + target[name](...args); + metadata.fallbackToNoCallback = false; + metadata.noCallback = true; + resolve(); + } + } else if (metadata.noCallback) { + target[name](...args); + resolve(); + } else { + target[name]( + ...args, + makeCallback( + { + resolve, + reject, + }, + metadata, + ), + ); + } + }); + }; + }; + const wrapMethod = (target, method, wrapper) => { + return new Proxy(method, { + apply(targetMethod, thisObj, args) { + return wrapper.call(thisObj, target, ...args); + }, + }); + }; + const hasOwnProperty = Function.call.bind( + Object.prototype.hasOwnProperty, + ); + const wrapObject = (target, wrappers = {}, metadata = {}) => { + const cache = /* @__PURE__ */ Object.create(null); + const handlers = { + has(proxyTarget2, prop) { + return prop in target || prop in cache; + }, + get(proxyTarget2, prop, receiver) { + if (prop in cache) { + return cache[prop]; + } + if (!(prop in target)) { + return void 0; + } + let value = target[prop]; + if (typeof value === "function") { + if (typeof wrappers[prop] === "function") { + value = wrapMethod( + target, + target[prop], + wrappers[prop], + ); + } else if (hasOwnProperty(metadata, prop)) { + const wrapper = wrapAsyncFunction(prop, metadata[prop]); + value = wrapMethod(target, target[prop], wrapper); + } else { + value = value.bind(target); + } + } else if ( + typeof value === "object" && + value !== null && + (hasOwnProperty(wrappers, prop) || + hasOwnProperty(metadata, prop)) + ) { + value = wrapObject(value, wrappers[prop], metadata[prop]); + } else if (hasOwnProperty(metadata, "*")) { + value = wrapObject(value, wrappers[prop], metadata["*"]); + } else { + Object.defineProperty(cache, prop, { + configurable: true, + enumerable: true, + get() { + return target[prop]; + }, + set(value2) { + target[prop] = value2; + }, + }); + return value; + } + cache[prop] = value; + return value; + }, + set(proxyTarget2, prop, value, receiver) { + if (prop in cache) { + cache[prop] = value; + } else { + target[prop] = value; + } + return true; + }, + defineProperty(proxyTarget2, prop, desc) { + return Reflect.defineProperty(cache, prop, desc); + }, + deleteProperty(proxyTarget2, prop) { + return Reflect.deleteProperty(cache, prop); + }, + }; + const proxyTarget = Object.create(target); + return new Proxy(proxyTarget, handlers); + }; + const wrapEvent = (wrapperMap) => ({ + addListener(target, listener, ...args) { + target.addListener(wrapperMap.get(listener), ...args); + }, + hasListener(target, listener) { + return target.hasListener(wrapperMap.get(listener)); + }, + removeListener(target, listener) { + target.removeListener(wrapperMap.get(listener)); + }, + }); + const onRequestFinishedWrappers = new DefaultWeakMap( + (listener) => { + if (typeof listener !== "function") { + return listener; + } + return function onRequestFinished(req) { + const wrappedReq = wrapObject( + req, + {}, + { + getContent: { + minArgs: 0, + maxArgs: 0, + }, + }, + ); + listener(wrappedReq); + }; + }, + ); + let loggedSendResponseDeprecationWarning = false; + const onMessageWrappers = new DefaultWeakMap((listener) => { + if (typeof listener !== "function") { + return listener; + } + return function onMessage(message, sender, sendResponse) { + let didCallSendResponse = false; + let wrappedSendResponse; + const sendResponsePromise = new Promise((resolve) => { + wrappedSendResponse = (response) => { + if (!loggedSendResponseDeprecationWarning) { + console.warn( + SEND_RESPONSE_DEPRECATION_WARNING, + new Error().stack, + ); + loggedSendResponseDeprecationWarning = true; + } + didCallSendResponse = true; + resolve(response); + }; + }); + let result; + try { + result = listener(message, sender, wrappedSendResponse); + } catch (err) { + result = Promise.reject(err); + } + const isResultThenable = + result !== true && isThenable(result); + if ( + result !== true && + !isResultThenable && + !didCallSendResponse + ) { + return false; + } + const sendPromisedResult = (promise) => { + promise + .then( + (msg) => { + sendResponse(msg); + }, + (error) => { + let message2; + if ( + error && + (error instanceof Error || + typeof error.message === "string") + ) { + message2 = error.message; + } else { + message2 = "An unexpected error occurred"; + } + sendResponse({ + __mozWebExtensionPolyfillReject__: true, + message: message2, + }); + }, + ) + .catch((err) => { + console.error( + "Failed to send onMessage rejected reply", + err, + ); + }); + }; + if (isResultThenable) { + sendPromisedResult(result); + } else { + sendPromisedResult(sendResponsePromise); + } + return true; + }; + }); + const wrappedSendMessageCallback = ( + { reject, resolve }, + reply, + ) => { + if (extensionAPIs.runtime.lastError) { + if ( + extensionAPIs.runtime.lastError.message === + CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE + ) { + resolve(); + } else { + reject(new Error(extensionAPIs.runtime.lastError.message)); + } + } else if (reply && reply.__mozWebExtensionPolyfillReject__) { + reject(new Error(reply.message)); + } else { + resolve(reply); + } + }; + const wrappedSendMessage = ( + name, + metadata, + apiNamespaceObj, + ...args + ) => { + if (args.length < metadata.minArgs) { + throw new Error( + `Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`, + ); + } + if (args.length > metadata.maxArgs) { + throw new Error( + `Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`, + ); + } + return new Promise((resolve, reject) => { + const wrappedCb = wrappedSendMessageCallback.bind(null, { + resolve, + reject, + }); + args.push(wrappedCb); + apiNamespaceObj.sendMessage(...args); + }); + }; + const staticWrappers = { + devtools: { + network: { + onRequestFinished: wrapEvent(onRequestFinishedWrappers), + }, + }, + runtime: { + onMessage: wrapEvent(onMessageWrappers), + onMessageExternal: wrapEvent(onMessageWrappers), + sendMessage: wrappedSendMessage.bind(null, "sendMessage", { + minArgs: 1, + maxArgs: 3, + }), + }, + tabs: { + sendMessage: wrappedSendMessage.bind(null, "sendMessage", { + minArgs: 2, + maxArgs: 3, + }), + }, + }; + const settingMetadata = { + clear: { + minArgs: 1, + maxArgs: 1, + }, + get: { + minArgs: 1, + maxArgs: 1, + }, + set: { + minArgs: 1, + maxArgs: 1, + }, + }; + apiMetadata.privacy = { + network: { + "*": settingMetadata, + }, + services: { + "*": settingMetadata, + }, + websites: { + "*": settingMetadata, + }, + }; + return wrapObject(extensionAPIs, staticWrappers, apiMetadata); + }; + if ( + typeof chrome != "object" || + !chrome || + !chrome.runtime || + !chrome.runtime.id + ) { + throw new Error( + "This script should only be loaded in a browser extension.", + ); + } + module2.exports = wrapAPIs(chrome); + } else { + module2.exports = browser; + } + }, + ); + }, + }); - // node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js - var require_object_assign = __commonJS({ - "node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js"(exports, module) { - "use strict"; - var getOwnPropertySymbols = Object.getOwnPropertySymbols; - var hasOwnProperty = Object.prototype.hasOwnProperty; - var propIsEnumerable = Object.prototype.propertyIsEnumerable; - function toObject(val) { - if (val === null || val === void 0) { - throw new TypeError("Object.assign cannot be called with null or undefined"); - } - return Object(val); - } - function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - var test1 = new String("abc"); - test1[5] = "de"; - if (Object.getOwnPropertyNames(test1)[0] === "5") { - return false; - } - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2["_" + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function(n) { - return test2[n]; - }); - if (order2.join("") !== "0123456789") { - return false; - } - var test3 = {}; - "abcdefghijklmnopqrst".split("").forEach(function(letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { - return false; - } - return true; - } catch (err) { - return false; - } - } - module.exports = shouldUseNative() ? Object.assign : function(target, source) { - var from; - var to = toObject(target); - var symbols; - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - return to; - }; - } - }); + // node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js + var require_object_assign = __commonJS({ + "node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js"( + exports, + module, + ) { + var getOwnPropertySymbols = Object.getOwnPropertySymbols; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var propIsEnumerable = Object.prototype.propertyIsEnumerable; + function toObject(val) { + if (val === null || val === void 0) { + throw new TypeError( + "Object.assign cannot be called with null or undefined", + ); + } + return Object(val); + } + function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + var test1 = new String("abc"); + test1[5] = "de"; + if (Object.getOwnPropertyNames(test1)[0] === "5") { + return false; + } + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2["_" + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map((n) => test2[n]); + if (order2.join("") !== "0123456789") { + return false; + } + var test3 = {}; + "abcdefghijklmnopqrst".split("").forEach((letter) => { + test3[letter] = letter; + }); + if ( + Object.keys(Object.assign({}, test3)).join("") !== + "abcdefghijklmnopqrst" + ) { + return false; + } + return true; + } catch (err) { + return false; + } + } + module.exports = shouldUseNative() + ? Object.assign + : (target, source) => { + var from; + var to = toObject(target); + var symbols; + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + return to; + }; + }, + }); - // node_modules/.pnpm/react@17.0.2/node_modules/react/cjs/react.development.js - var require_react_development = __commonJS({ - "node_modules/.pnpm/react@17.0.2/node_modules/react/cjs/react.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var _assign = require_object_assign(); - var ReactVersion = "17.0.2"; - var REACT_ELEMENT_TYPE = 60103; - var REACT_PORTAL_TYPE = 60106; - exports.Fragment = 60107; - exports.StrictMode = 60108; - exports.Profiler = 60114; - var REACT_PROVIDER_TYPE = 60109; - var REACT_CONTEXT_TYPE = 60110; - var REACT_FORWARD_REF_TYPE = 60112; - exports.Suspense = 60113; - var REACT_SUSPENSE_LIST_TYPE = 60120; - var REACT_MEMO_TYPE = 60115; - var REACT_LAZY_TYPE = 60116; - var REACT_BLOCK_TYPE = 60121; - var REACT_SERVER_BLOCK_TYPE = 60122; - var REACT_FUNDAMENTAL_TYPE = 60117; - var REACT_SCOPE_TYPE = 60119; - var REACT_OPAQUE_ID_TYPE = 60128; - var REACT_DEBUG_TRACING_MODE_TYPE = 60129; - var REACT_OFFSCREEN_TYPE = 60130; - var REACT_LEGACY_HIDDEN_TYPE = 60131; - if (typeof Symbol === "function" && Symbol.for) { - var symbolFor = Symbol.for; - REACT_ELEMENT_TYPE = symbolFor("react.element"); - REACT_PORTAL_TYPE = symbolFor("react.portal"); - exports.Fragment = symbolFor("react.fragment"); - exports.StrictMode = symbolFor("react.strict_mode"); - exports.Profiler = symbolFor("react.profiler"); - REACT_PROVIDER_TYPE = symbolFor("react.provider"); - REACT_CONTEXT_TYPE = symbolFor("react.context"); - REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref"); - exports.Suspense = symbolFor("react.suspense"); - REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list"); - REACT_MEMO_TYPE = symbolFor("react.memo"); - REACT_LAZY_TYPE = symbolFor("react.lazy"); - REACT_BLOCK_TYPE = symbolFor("react.block"); - REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block"); - REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental"); - REACT_SCOPE_TYPE = symbolFor("react.scope"); - REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id"); - REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode"); - REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen"); - REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden"); - } - var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var ReactCurrentDispatcher = { - current: null - }; - var ReactCurrentBatchConfig = { - transition: 0 - }; - var ReactCurrentOwner = { - current: null - }; - var ReactDebugCurrentFrame = {}; - var currentExtraStackFrame = null; - function setExtraStackFrame(stack) { - { - currentExtraStackFrame = stack; - } - } - { - ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { - { - currentExtraStackFrame = stack; - } - }; - ReactDebugCurrentFrame.getCurrentStack = null; - ReactDebugCurrentFrame.getStackAddendum = function() { - var stack = ""; - if (currentExtraStackFrame) { - stack += currentExtraStackFrame; - } - var impl = ReactDebugCurrentFrame.getCurrentStack; - if (impl) { - stack += impl() || ""; - } - return stack; - }; - } - var IsSomeRendererActing = { - current: false - }; - var ReactSharedInternals = { - ReactCurrentDispatcher, - ReactCurrentBatchConfig, - ReactCurrentOwner, - IsSomeRendererActing, - assign: _assign - }; - { - ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; - } - function warn(format) { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - function error(format) { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return "" + item; - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var didWarnStateUpdateForUnmountedComponent = {}; - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; - var warningKey = componentName + "." + callerName; - if (didWarnStateUpdateForUnmountedComponent[warningKey]) { - return; - } - 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, componentName); - didWarnStateUpdateForUnmountedComponent[warningKey] = true; - } - } - var ReactNoopUpdateQueue = { - isMounted: function(publicInstance) { - return false; - }, - enqueueForceUpdate: function(publicInstance, callback, callerName) { - warnNoop(publicInstance, "forceUpdate"); - }, - enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { - warnNoop(publicInstance, "replaceState"); - }, - enqueueSetState: function(publicInstance, partialState, callback, callerName) { - warnNoop(publicInstance, "setState"); - } - }; - var emptyObject = {}; - { - Object.freeze(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 (!(typeof partialState === "object" || typeof partialState === "function" || partialState == null)) { - { - throw Error("setState(...): 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)."] - }; - var defineDeprecationWarning = function(methodName, info) { - Object.defineProperty(Component.prototype, methodName, { - get: function() { - warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); - return void 0; - } - }); - }; - for (var fnName in deprecatedAPIs) { - if (deprecatedAPIs.hasOwnProperty(fnName)) { - defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); - } - } - } - 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; - function createRef() { - var refObject = { - current: null - }; - { - Object.seal(refObject); - } - return refObject; - } - function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentName(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case exports.Fragment: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case exports.Profiler: - return "Profiler"; - case exports.StrictMode: - return "StrictMode"; - case exports.Suspense: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - return getComponentName(type.type); - case REACT_BLOCK_TYPE: - return getComponentName(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentName(init(payload)); - } catch (x) { - return null; - } - } - } - } - return null; - } - var hasOwnProperty = Object.prototype.hasOwnProperty; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config) { - { - if (hasOwnProperty.call(config, "ref")) { - var getter = Object.getOwnPropertyDescriptor(config, "ref").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.ref !== void 0; - } - function hasValidKey(config) { - { - if (hasOwnProperty.call(config, "key")) { - var getter = Object.getOwnPropertyDescriptor(config, "key").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.key !== void 0; - } - function defineKeyPropWarningGetter(props, displayName) { - var warnAboutAccessingKey = function() { - { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - 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://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function defineRefPropWarningGetter(props, displayName) { - var warnAboutAccessingRef = function() { - { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error("%s: `ref` 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://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, "ref", { - get: warnAboutAccessingRef, - configurable: true - }); - } - function warnIfStringRefCannotBeAutoConverted(config) { - { - if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { - var componentName = getComponentName(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - var ReactElement = function(type, key, ref, self2, source, owner, props) { - var element = { - $$typeof: REACT_ELEMENT_TYPE, - type, - key, - ref, - props, - _owner: owner - }; - { - element._store = {}; - Object.defineProperty(element._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: false - }); - Object.defineProperty(element, "_self", { - configurable: false, - enumerable: false, - writable: false, - value: self2 - }); - Object.defineProperty(element, "_source", { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - function createElement(type, config, children) { - var propName; - var props = {}; - var key = null; - var ref = null; - var self2 = null; - var source = null; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - { - warnIfStringRefCannotBeAutoConverted(config); - } - } - if (hasValidKey(config)) { - key = "" + config.key; - } - self2 = config.__self === void 0 ? null : config.__self; - source = config.__source === void 0 ? null : config.__source; - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config[propName]; - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2]; - } - { - if (Object.freeze) { - Object.freeze(childArray); - } - } - props.children = childArray; - } - if (type && type.defaultProps) { - var defaultProps = type.defaultProps; - for (propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } - { - if (key || ref) { - var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - } - return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); - } - function cloneAndReplaceKey(oldElement, newKey) { - var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); - return newElement; - } - function cloneElement(element, config, children) { - if (!!(element === null || element === void 0)) { - { - throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); - } - } - var propName; - var props = _assign({}, element.props); - var key = element.key; - var ref = element.ref; - var self2 = element._self; - var source = element._source; - var owner = element._owner; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - owner = ReactCurrentOwner.current; - } - if (hasValidKey(config)) { - key = "" + config.key; - } - var defaultProps; - if (element.type && element.type.defaultProps) { - defaultProps = element.type.defaultProps; - } - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - if (config[propName] === void 0 && defaultProps !== void 0) { - props[propName] = defaultProps[propName]; - } else { - props[propName] = config[propName]; - } - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2]; - } - props.children = childArray; - } - return ReactElement(element.type, key, ref, self2, source, owner, props); - } - function isValidElement(object) { - return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - var SEPARATOR = "."; - var SUBSEPARATOR = ":"; - function escape(key) { - var escapeRegex = /[=:]/g; - var escaperLookup = { - "=": "=0", - ":": "=2" - }; - var escapedString = key.replace(escapeRegex, function(match) { - return escaperLookup[match]; - }); - return "$" + escapedString; - } - var didWarnAboutMaps = false; - var userProvidedKeyEscapeRegex = /\/+/g; - function escapeUserProvidedKey(text) { - return text.replace(userProvidedKeyEscapeRegex, "$&/"); - } - function getElementKey(element, index) { - if (typeof element === "object" && element !== null && element.key != null) { - return escape("" + element.key); - } - return index.toString(36); - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if (type === "undefined" || type === "boolean") { - children = null; - } - var invokeCallback = false; - if (children === null) { - invokeCallback = true; - } else { - switch (type) { - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - } - } - } - if (invokeCallback) { - var _child = children; - var mappedChild = callback(_child); - var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; - if (Array.isArray(mappedChild)) { - var escapedChildKey = ""; - if (childKey != null) { - escapedChildKey = escapeUserProvidedKey(childKey) + "/"; - } - mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { - return c; - }); - } else if (mappedChild != null) { - if (isValidElement(mappedChild)) { - mappedChild = cloneAndReplaceKey( - mappedChild, - escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey - ); - } - array.push(mappedChild); - } - return 1; - } - var child; - var nextName; - var subtreeCount = 0; - var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; - if (Array.isArray(children)) { - for (var i = 0; i < children.length; i++) { - child = children[i]; - nextName = nextNamePrefix + getElementKey(child, i); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else { - var iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === "function") { - var iterableChildren = children; - { - if (iteratorFn === iterableChildren.entries) { - if (!didWarnAboutMaps) { - warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); - } - didWarnAboutMaps = true; - } - } - var iterator = iteratorFn.call(iterableChildren); - var step; - var ii = 0; - while (!(step = iterator.next()).done) { - child = step.value; - nextName = nextNamePrefix + getElementKey(child, ii++); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else if (type === "object") { - var childrenString = "" + children; - { - { - throw Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); - } - } - } - } - return subtreeCount; - } - function mapChildren(children, func, context) { - if (children == null) { - return children; - } - var result = []; - var count = 0; - mapIntoArray(children, result, "", "", function(child) { - return func.call(context, child, count++); - }); - return result; - } - function countChildren(children) { - var n = 0; - mapChildren(children, function() { - n++; - }); - return n; - } - function forEachChildren(children, forEachFunc, forEachContext) { - mapChildren(children, function() { - forEachFunc.apply(this, arguments); - }, forEachContext); - } - function toArray(children) { - return mapChildren(children, function(child) { - return child; - }) || []; - } - function onlyChild(children) { - if (!isValidElement(children)) { - { - throw Error("React.Children.only expected to receive a single React element child."); - } - } - return children; - } - function createContext(defaultValue, calculateChangedBits) { - if (calculateChangedBits === void 0) { - calculateChangedBits = null; - } else { - { - if (calculateChangedBits !== null && typeof calculateChangedBits !== "function") { - error("createContext: Expected the optional second argument to be a function. Instead received: %s", calculateChangedBits); - } - } - } - var context = { - $$typeof: REACT_CONTEXT_TYPE, - _calculateChangedBits: calculateChangedBits, - _currentValue: defaultValue, - _currentValue2: defaultValue, - _threadCount: 0, - Provider: null, - Consumer: null - }; - context.Provider = { - $$typeof: REACT_PROVIDER_TYPE, - _context: context - }; - var hasWarnedAboutUsingNestedContextConsumers = false; - var hasWarnedAboutUsingConsumerProvider = false; - var hasWarnedAboutDisplayNameOnConsumer = false; - { - var Consumer = { - $$typeof: REACT_CONTEXT_TYPE, - _context: context, - _calculateChangedBits: context._calculateChangedBits - }; - Object.defineProperties(Consumer, { - Provider: { - get: function() { - if (!hasWarnedAboutUsingConsumerProvider) { - hasWarnedAboutUsingConsumerProvider = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Provider; - }, - set: function(_Provider) { - context.Provider = _Provider; - } - }, - _currentValue: { - get: function() { - return context._currentValue; - }, - set: function(_currentValue) { - context._currentValue = _currentValue; - } - }, - _currentValue2: { - get: function() { - return context._currentValue2; - }, - set: function(_currentValue2) { - context._currentValue2 = _currentValue2; - } - }, - _threadCount: { - get: function() { - return context._threadCount; - }, - set: function(_threadCount) { - context._threadCount = _threadCount; - } - }, - Consumer: { - get: function() { - if (!hasWarnedAboutUsingNestedContextConsumers) { - hasWarnedAboutUsingNestedContextConsumers = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Consumer; - } - }, - displayName: { - get: function() { - return context.displayName; - }, - set: function(displayName) { - if (!hasWarnedAboutDisplayNameOnConsumer) { - warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); - hasWarnedAboutDisplayNameOnConsumer = true; - } - } - } - }); - context.Consumer = Consumer; - } - { - context._currentRenderer = null; - context._currentRenderer2 = null; - } - return context; - } - var Uninitialized = -1; - var Pending = 0; - var Resolved = 1; - var Rejected = 2; - function lazyInitializer(payload) { - if (payload._status === Uninitialized) { - var ctor = payload._result; - var thenable = ctor(); - var pending = payload; - pending._status = Pending; - pending._result = thenable; - thenable.then(function(moduleObject) { - if (payload._status === Pending) { - var defaultExport = moduleObject.default; - { - if (defaultExport === void 0) { - 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'))", moduleObject); - } - } - var resolved = payload; - resolved._status = Resolved; - resolved._result = defaultExport; - } - }, function(error2) { - if (payload._status === Pending) { - var rejected = payload; - rejected._status = Rejected; - rejected._result = error2; - } - }); - } - if (payload._status === Resolved) { - return payload._result; - } else { - throw payload._result; - } - } - function lazy(ctor) { - var payload = { - _status: -1, - _result: ctor - }; - var lazyType = { - $$typeof: REACT_LAZY_TYPE, - _payload: payload, - _init: lazyInitializer - }; - { - var defaultProps; - var propTypes; - Object.defineProperties(lazyType, { - defaultProps: { - configurable: true, - get: function() { - return defaultProps; - }, - set: function(newDefaultProps) { - error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - defaultProps = newDefaultProps; - Object.defineProperty(lazyType, "defaultProps", { - enumerable: true - }); - } - }, - propTypes: { - configurable: true, - get: function() { - return propTypes; - }, - set: function(newPropTypes) { - error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - propTypes = newPropTypes; - Object.defineProperty(lazyType, "propTypes", { - enumerable: true - }); - } - } - }); - } - return lazyType; - } - function forwardRef(render2) { - { - if (render2 != null && render2.$$typeof === REACT_MEMO_TYPE) { - error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); - } else if (typeof render2 !== "function") { - error("forwardRef requires a render function but was given %s.", render2 === null ? "null" : typeof render2); - } else { - if (render2.length !== 0 && render2.length !== 2) { - error("forwardRef render functions accept exactly two parameters: props and ref. %s", render2.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); - } - } - if (render2 != null) { - if (render2.defaultProps != null || render2.propTypes != null) { - error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); - } - } - } - var elementType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: render2 - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (render2.displayName == null) { - render2.displayName = name; - } - } - }); - } - return elementType; - } - var enableScopeAPI = false; - function isValidElementType(type) { - if (typeof type === "string" || typeof type === "function") { - return true; - } - if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) { - return true; - } - if (typeof type === "object" && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { - return true; - } - } - return false; - } - function memo(type, compare) { - { - if (!isValidElementType(type)) { - error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); - } - } - var elementType = { - $$typeof: REACT_MEMO_TYPE, - type, - compare: compare === void 0 ? null : compare - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (type.displayName == null) { - type.displayName = name; - } - } - }); - } - return elementType; - } - function resolveDispatcher() { - var dispatcher = ReactCurrentDispatcher.current; - if (!(dispatcher !== null)) { - { - throw 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://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); - } - } - return dispatcher; - } - function useContext(Context, unstable_observedBits) { - var dispatcher = resolveDispatcher(); - { - if (unstable_observedBits !== void 0) { - error("useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", unstable_observedBits, typeof unstable_observedBits === "number" && Array.isArray(arguments[2]) ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" : ""); - } - if (Context._context !== void 0) { - var realContext = Context._context; - if (realContext.Consumer === Context) { - error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); - } else if (realContext.Provider === Context) { - error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); - } - } - } - return dispatcher.useContext(Context, unstable_observedBits); - } - function useState2(initialState) { - var dispatcher = resolveDispatcher(); - return dispatcher.useState(initialState); - } - function useReducer(reducer, initialArg, init) { - var dispatcher = resolveDispatcher(); - return dispatcher.useReducer(reducer, initialArg, init); - } - function useRef(initialValue) { - var dispatcher = resolveDispatcher(); - return dispatcher.useRef(initialValue); - } - function useEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useEffect(create, deps); - } - function useLayoutEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useLayoutEffect(create, deps); - } - function useCallback(callback, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useCallback(callback, deps); - } - function useMemo(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useMemo(create, deps); - } - function useImperativeHandle(ref, create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useImperativeHandle(ref, create, deps); - } - function useDebugValue(value, formatterFn) { - { - var dispatcher = resolveDispatcher(); - return dispatcher.useDebugValue(value, formatterFn); - } - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: _assign({}, props, { - value: prevLog - }), - info: _assign({}, props, { - value: prevInfo - }), - warn: _assign({}, props, { - value: prevWarn - }), - error: _assign({}, props, { - value: prevError - }), - group: _assign({}, props, { - value: prevGroup - }), - groupCollapsed: _assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: _assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - c--; - } - for (; s >= 1 && c >= 0; s--, c--) { - if (sampleLines[s] !== controlLines[c]) { - if (s !== 1 || c !== 1) { - do { - s--; - c--; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component2) { - var prototype = Component2.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case exports.Suspense: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_BLOCK_TYPE: - return describeFunctionComponentFrame(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) { - } - } - } - } - return ""; - } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location2, componentName, element) { - { - var has = Function.call.bind(Object.prototype.hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; - try { - if (typeof typeSpecs[typeSpecName] !== "function") { - var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); - err.name = "Invariant Violation"; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location2, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error("Failed %s type: %s", location2, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - setExtraStackFrame(stack); - } else { - setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - function getDeclarationErrorAddendum() { - if (ReactCurrentOwner.current) { - var name = getComponentName(ReactCurrentOwner.current.type); - if (name) { - return "\n\nCheck the render method of `" + name + "`."; - } - } - return ""; - } - function getSourceInfoErrorAddendum(source) { - if (source !== void 0) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ""); - var lineNumber = source.lineNumber; - return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; - } - return ""; - } - function getSourceInfoErrorAddendumForProps(elementProps) { - if (elementProps !== null && elementProps !== void 0) { - return getSourceInfoErrorAddendum(elementProps.__source); - } - return ""; - } - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } - } - return info; - } - function validateExplicitKey(element, parentType) { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - var childOwner = ""; - if (element && element._owner && element._owner !== ReactCurrentOwner.current) { - childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; - } - { - setCurrentlyValidatingElement$1(element); - error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - function validateChildKeys(node, parentType) { - if (typeof node !== "object") { - return; - } - if (Array.isArray(node)) { - for (var i = 0; i < node.length; i++) { - var child = node[i]; - if (isValidElement(child)) { - validateExplicitKey(child, parentType); - } - } - } else if (isValidElement(node)) { - if (node._store) { - node._store.validated = true; - } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === "function") { - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType); - } - } - } - } - } - } - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === void 0 || typeof type === "string") { - return; - } - var propTypes; - if (typeof type === "function") { - propTypes = type.propTypes; - } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - var name = getComponentName(type); - checkPropTypes(propTypes, element.props, "prop", name, element); - } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; - var _name = getComponentName(type); - error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); - } - if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { - error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); - } - } - } - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key !== "children" && key !== "key") { - setCurrentlyValidatingElement$1(fragment); - error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error("Invalid attribute `ref` supplied to `React.Fragment`."); - setCurrentlyValidatingElement$1(null); - } - } - } - function createElementWithValidation(type, props, children) { - var validType = isValidElementType(type); - if (!validType) { - var info = ""; - if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { - info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendumForProps(props); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = "null"; - } else if (Array.isArray(type)) { - typeString = "array"; - } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentName(type.type) || "Unknown") + " />"; - info = " Did you accidentally export a JSX literal instead of a component?"; - } else { - typeString = typeof type; - } - { - error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); - } - } - var element = createElement.apply(this, arguments); - if (element == null) { - return element; - } - if (validType) { - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], type); - } - } - if (type === exports.Fragment) { - validateFragmentProps(element); - } else { - validatePropTypes(element); - } - return element; - } - var didWarnAboutDeprecatedCreateFactory = false; - function createFactoryWithValidation(type) { - var validatedFactory = createElementWithValidation.bind(null, type); - validatedFactory.type = type; - { - if (!didWarnAboutDeprecatedCreateFactory) { - didWarnAboutDeprecatedCreateFactory = true; - warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); - } - Object.defineProperty(validatedFactory, "type", { - enumerable: false, - get: function() { - warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); - Object.defineProperty(this, "type", { - value: type - }); - return type; - } - }); - } - return validatedFactory; - } - function cloneElementWithValidation(element, props, children) { - var newElement = cloneElement.apply(this, arguments); - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], newElement.type); - } - validatePropTypes(newElement); - return newElement; - } - { - try { - var frozenObject = Object.freeze({}); - /* @__PURE__ */ new Map([[frozenObject, null]]); - /* @__PURE__ */ new Set([frozenObject]); - } catch (e) { - } - } - var createElement$1 = createElementWithValidation; - var cloneElement$1 = cloneElementWithValidation; - var createFactory = createFactoryWithValidation; - var Children = { - map: mapChildren, - forEach: forEachChildren, - count: countChildren, - toArray, - only: onlyChild - }; - exports.Children = Children; - exports.Component = Component; - exports.PureComponent = PureComponent; - exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; - exports.cloneElement = cloneElement$1; - exports.createContext = createContext; - exports.createElement = createElement$1; - exports.createFactory = createFactory; - exports.createRef = createRef; - exports.forwardRef = forwardRef; - exports.isValidElement = isValidElement; - exports.lazy = lazy; - exports.memo = memo; - exports.useCallback = useCallback; - exports.useContext = useContext; - exports.useDebugValue = useDebugValue; - exports.useEffect = useEffect; - exports.useImperativeHandle = useImperativeHandle; - exports.useLayoutEffect = useLayoutEffect; - exports.useMemo = useMemo; - exports.useReducer = useReducer; - exports.useRef = useRef; - exports.useState = useState2; - exports.version = ReactVersion; - })(); - } - } - }); + // node_modules/.pnpm/react@17.0.2/node_modules/react/cjs/react.development.js + var require_react_development = __commonJS({ + "node_modules/.pnpm/react@17.0.2/node_modules/react/cjs/react.development.js"( + exports, + ) { + if (true) { + (() => { + var _assign = require_object_assign(); + var ReactVersion = "17.0.2"; + var REACT_ELEMENT_TYPE = 60103; + var REACT_PORTAL_TYPE = 60106; + exports.Fragment = 60107; + exports.StrictMode = 60108; + exports.Profiler = 60114; + var REACT_PROVIDER_TYPE = 60109; + var REACT_CONTEXT_TYPE = 60110; + var REACT_FORWARD_REF_TYPE = 60112; + exports.Suspense = 60113; + var REACT_SUSPENSE_LIST_TYPE = 60120; + var REACT_MEMO_TYPE = 60115; + var REACT_LAZY_TYPE = 60116; + var REACT_BLOCK_TYPE = 60121; + var REACT_SERVER_BLOCK_TYPE = 60122; + var REACT_FUNDAMENTAL_TYPE = 60117; + var REACT_SCOPE_TYPE = 60119; + var REACT_OPAQUE_ID_TYPE = 60128; + var REACT_DEBUG_TRACING_MODE_TYPE = 60129; + var REACT_OFFSCREEN_TYPE = 60130; + var REACT_LEGACY_HIDDEN_TYPE = 60131; + if (typeof Symbol === "function" && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor("react.element"); + REACT_PORTAL_TYPE = symbolFor("react.portal"); + exports.Fragment = symbolFor("react.fragment"); + exports.StrictMode = symbolFor("react.strict_mode"); + exports.Profiler = symbolFor("react.profiler"); + REACT_PROVIDER_TYPE = symbolFor("react.provider"); + REACT_CONTEXT_TYPE = symbolFor("react.context"); + REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref"); + exports.Suspense = symbolFor("react.suspense"); + REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list"); + REACT_MEMO_TYPE = symbolFor("react.memo"); + REACT_LAZY_TYPE = symbolFor("react.lazy"); + REACT_BLOCK_TYPE = symbolFor("react.block"); + REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block"); + REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental"); + REACT_SCOPE_TYPE = symbolFor("react.scope"); + REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id"); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode"); + REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen"); + REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden"); + } + var MAYBE_ITERATOR_SYMBOL = + typeof Symbol === "function" && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var ReactCurrentDispatcher = { + current: null, + }; + var ReactCurrentBatchConfig = { + transition: 0, + }; + var ReactCurrentOwner = { + current: null, + }; + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + currentExtraStackFrame = stack; + } + ReactDebugCurrentFrame.setExtraStackFrame = (stack) => { + currentExtraStackFrame = stack; + }; + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFrame.getStackAddendum = () => { + var stack = ""; + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } + var impl = ReactDebugCurrentFrame.getCurrentStack; + if (impl) { + stack += impl() || ""; + } + return stack; + }; + var IsSomeRendererActing = { + current: false, + }; + var ReactSharedInternals = { + ReactCurrentDispatcher, + ReactCurrentBatchConfig, + ReactCurrentOwner, + IsSomeRendererActing, + assign: _assign, + }; + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + function warn(format) { + for ( + var _len = arguments.length, + args = new Array(_len > 1 ? _len - 1 : 0), + _key = 1; + _key < _len; + _key++ + ) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + function error(format) { + for ( + var _len2 = arguments.length, + args = new Array(_len2 > 1 ? _len2 - 1 : 0), + _key2 = 1; + _key2 < _len2; + _key2++ + ) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + function printWarning(level, format, args) { + var ReactDebugCurrentFrame2 = + ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map((item) => "" + item); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call( + console[level], + console, + argsWithFormat, + ); + } + var didWarnStateUpdateForUnmountedComponent = {}; + function warnNoop(publicInstance, callerName) { + var _constructor = publicInstance.constructor; + var componentName = + (_constructor && + (_constructor.displayName || _constructor.name)) || + "ReactClass"; + var warningKey = componentName + "." + callerName; + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + 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, + componentName, + ); + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + var ReactNoopUpdateQueue = { + isMounted: (publicInstance) => false, + enqueueForceUpdate: (publicInstance, callback, callerName) => { + warnNoop(publicInstance, "forceUpdate"); + }, + enqueueReplaceState: ( + publicInstance, + completeState, + callback, + callerName, + ) => { + warnNoop(publicInstance, "replaceState"); + }, + enqueueSetState: ( + publicInstance, + partialState, + callback, + callerName, + ) => { + warnNoop(publicInstance, "setState"); + }, + }; + var emptyObject = {}; + Object.freeze(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 ( + !( + typeof partialState === "object" || + typeof partialState === "function" || + partialState == null + ) + ) { + throw Error( + "setState(...): 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).", + ], + }; + var defineDeprecationWarning = (methodName, info) => { + Object.defineProperty(Component.prototype, methodName, { + get: () => { + warn( + "%s(...) is deprecated in plain JavaScript React classes. %s", + info[0], + info[1], + ); + return void 0; + }, + }); + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + 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; + function createRef() { + var refObject = { + current: null, + }; + Object.seal(refObject); + return refObject; + } + function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ""; + return ( + outerType.displayName || + (functionName !== "" + ? wrapperName + "(" + functionName + ")" + : wrapperName) + ); + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentName(type) { + if (type == null) { + return null; + } + if (typeof type.tag === "number") { + error( + "Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue.", + ); + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case exports.Fragment: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case exports.Profiler: + return "Profiler"; + case exports.StrictMode: + return "StrictMode"; + case exports.Suspense: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + return getComponentName(type.type); + case REACT_BLOCK_TYPE: + return getComponentName(type._render); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentName(init(payload)); + } catch (x) { + return null; + } + } + } + } + return null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true, + }; + var specialPropKeyWarningShown, + specialPropRefWarningShown, + didWarnAboutStringRefs; + didWarnAboutStringRefs = {}; + function hasValidRef(config) { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + return config.ref !== void 0; + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + return config.key !== void 0; + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = () => { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + 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://reactjs.org/link/special-props)", + displayName, + ); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true, + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = () => { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error( + "%s: `ref` 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://reactjs.org/link/special-props)", + displayName, + ); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true, + }); + } + function warnIfStringRefCannotBeAutoConverted(config) { + if ( + typeof config.ref === "string" && + ReactCurrentOwner.current && + config.__self && + ReactCurrentOwner.current.stateNode !== config.__self + ) { + var componentName = getComponentName( + ReactCurrentOwner.current.type, + ); + if (!didWarnAboutStringRefs[componentName]) { + error( + 'Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', + componentName, + config.ref, + ); + didWarnAboutStringRefs[componentName] = true; + } + } + } + var ReactElement = (type, key, ref, self2, source, owner, props) => { + var element = { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + ref, + props, + _owner: owner, + }; + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false, + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self2, + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source, + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + return element; + }; + function createElement(type, config, children) { + var propName; + var props = {}; + var key = null; + var ref = null; + var self2 = null; + var source = null; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config); + } + if (hasValidKey(config)) { + key = "" + config.key; + } + self2 = config.__self === void 0 ? null : config.__self; + source = config.__source === void 0 ? null : config.__source; + for (propName in config) { + if ( + hasOwnProperty.call(config, propName) && + !RESERVED_PROPS.hasOwnProperty(propName) + ) { + props[propName] = config[propName]; + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + if (Object.freeze) { + Object.freeze(childArray); + } + props.children = childArray; + } + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } + if (key || ref) { + var displayName = + typeof type === "function" + ? type.displayName || type.name || "Unknown" + : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + return ReactElement( + type, + key, + ref, + self2, + source, + ReactCurrentOwner.current, + props, + ); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement( + oldElement.type, + newKey, + oldElement.ref, + oldElement._self, + oldElement._source, + oldElement._owner, + oldElement.props, + ); + return newElement; + } + function cloneElement(element, config, children) { + if (!!(element === null || element === void 0)) { + throw Error( + "React.cloneElement(...): The argument must be a React element, but you passed " + + element + + ".", + ); + } + var propName; + var props = _assign({}, element.props); + var key = element.key; + var ref = element.ref; + var self2 = element._self; + var source = element._source; + var owner = element._owner; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (hasValidKey(config)) { + key = "" + config.key; + } + var defaultProps; + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + for (propName in config) { + if ( + hasOwnProperty.call(config, propName) && + !RESERVED_PROPS.hasOwnProperty(propName) + ) { + if (config[propName] === void 0 && defaultProps !== void 0) { + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + return ReactElement( + element.type, + key, + ref, + self2, + source, + owner, + props, + ); + } + function isValidElement(object) { + return ( + typeof object === "object" && + object !== null && + object.$$typeof === REACT_ELEMENT_TYPE + ); + } + var SEPARATOR = "."; + var SUBSEPARATOR = ":"; + function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + "=": "=0", + ":": "=2", + }; + var escapedString = key.replace( + escapeRegex, + (match) => escaperLookup[match], + ); + return "$" + escapedString; + } + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, "$&/"); + } + function getElementKey(element, index) { + if ( + typeof element === "object" && + element !== null && + element.key != null + ) { + return escape("" + element.key); + } + return index.toString(36); + } + function mapIntoArray( + children, + array, + escapedPrefix, + nameSoFar, + callback, + ) { + var type = typeof children; + if (type === "undefined" || type === "boolean") { + children = null; + } + var invokeCallback = false; + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + } + } + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); + var childKey = + nameSoFar === "" + ? SEPARATOR + getElementKey(_child, 0) + : nameSoFar; + if (Array.isArray(mappedChild)) { + var escapedChildKey = ""; + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + "/"; + } + mapIntoArray(mappedChild, array, escapedChildKey, "", (c) => c); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + mappedChild = cloneAndReplaceKey( + mappedChild, + escapedPrefix + + (mappedChild.key && + (!_child || _child.key !== mappedChild.key) + ? escapeUserProvidedKey("" + mappedChild.key) + "/" + : "") + + childKey, + ); + } + array.push(mappedChild); + } + return 1; + } + var child; + var nextName; + var subtreeCount = 0; + var nextNamePrefix = + nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (Array.isArray(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray( + child, + array, + escapedPrefix, + nextName, + callback, + ); + } + } else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { + var iterableChildren = children; + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn( + "Using Maps as children is not supported. Use an array of keyed ReactElements instead.", + ); + } + didWarnAboutMaps = true; + } + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray( + child, + array, + escapedPrefix, + nextName, + callback, + ); + } + } else if (type === "object") { + var childrenString = "" + children; + throw Error( + "Objects are not valid as a React child (found: " + + (childrenString === "[object Object]" + ? "object with keys {" + + Object.keys(children).join(", ") + + "}" + : childrenString) + + "). If you meant to render a collection of children, use an array instead.", + ); + } + } + return subtreeCount; + } + function mapChildren(children, func, context) { + if (children == null) { + return children; + } + var result = []; + var count = 0; + mapIntoArray(children, result, "", "", (child) => + func.call(context, child, count++), + ); + return result; + } + function countChildren(children) { + var n = 0; + mapChildren(children, () => { + n++; + }); + return n; + } + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren( + children, + function () { + forEachFunc.apply(this, arguments); + }, + forEachContext, + ); + } + function toArray(children) { + return mapChildren(children, (child) => child) || []; + } + function onlyChild(children) { + if (!isValidElement(children)) { + throw Error( + "React.Children.only expected to receive a single React element child.", + ); + } + return children; + } + function createContext(defaultValue, calculateChangedBits) { + if (calculateChangedBits === void 0) { + calculateChangedBits = null; + } else { + if ( + calculateChangedBits !== null && + typeof calculateChangedBits !== "function" + ) { + error( + "createContext: Expected the optional second argument to be a function. Instead received: %s", + calculateChangedBits, + ); + } + } + var context = { + $$typeof: REACT_CONTEXT_TYPE, + _calculateChangedBits: calculateChangedBits, + _currentValue: defaultValue, + _currentValue2: defaultValue, + _threadCount: 0, + Provider: null, + Consumer: null, + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context, + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context, + _calculateChangedBits: context._calculateChangedBits, + }; + Object.defineProperties(Consumer, { + Provider: { + get: () => { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + error( + "Rendering is not supported and will be removed in a future major release. Did you mean to render instead?", + ); + } + return context.Provider; + }, + set: (_Provider) => { + context.Provider = _Provider; + }, + }, + _currentValue: { + get: () => context._currentValue, + set: (_currentValue) => { + context._currentValue = _currentValue; + }, + }, + _currentValue2: { + get: () => context._currentValue2, + set: (_currentValue2) => { + context._currentValue2 = _currentValue2; + }, + }, + _threadCount: { + get: () => context._threadCount, + set: (_threadCount) => { + context._threadCount = _threadCount; + }, + }, + Consumer: { + get: () => { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + error( + "Rendering is not supported and will be removed in a future major release. Did you mean to render instead?", + ); + } + return context.Consumer; + }, + }, + displayName: { + get: () => context.displayName, + set: (displayName) => { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn( + "Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", + displayName, + ); + hasWarnedAboutDisplayNameOnConsumer = true; + } + }, + }, + }); + context.Consumer = Consumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + return context; + } + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); + var pending = payload; + pending._status = Pending; + pending._result = thenable; + thenable.then( + (moduleObject) => { + if (payload._status === Pending) { + var defaultExport = moduleObject.default; + if (defaultExport === void 0) { + 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'))", + moduleObject, + ); + } + var resolved = payload; + resolved._status = Resolved; + resolved._result = defaultExport; + } + }, + (error2) => { + if (payload._status === Pending) { + var rejected = payload; + rejected._status = Rejected; + rejected._result = error2; + } + }, + ); + } + if (payload._status === Resolved) { + return payload._result; + } else { + throw payload._result; + } + } + function lazy(ctor) { + var payload = { + _status: -1, + _result: ctor, + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer, + }; + var defaultProps; + var propTypes; + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: () => defaultProps, + set: (newDefaultProps) => { + error( + "React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.", + ); + defaultProps = newDefaultProps; + Object.defineProperty(lazyType, "defaultProps", { + enumerable: true, + }); + }, + }, + propTypes: { + configurable: true, + get: () => propTypes, + set: (newPropTypes) => { + error( + "React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.", + ); + propTypes = newPropTypes; + Object.defineProperty(lazyType, "propTypes", { + enumerable: true, + }); + }, + }, + }); + return lazyType; + } + function forwardRef(render2) { + if (render2 != null && render2.$$typeof === REACT_MEMO_TYPE) { + error( + "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).", + ); + } else if (typeof render2 !== "function") { + error( + "forwardRef requires a render function but was given %s.", + render2 === null ? "null" : typeof render2, + ); + } else { + if (render2.length !== 0 && render2.length !== 2) { + error( + "forwardRef render functions accept exactly two parameters: props and ref. %s", + render2.length === 1 + ? "Did you forget to use the ref parameter?" + : "Any additional parameter will be undefined.", + ); + } + } + if (render2 != null) { + if (render2.defaultProps != null || render2.propTypes != null) { + error( + "forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?", + ); + } + } + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render: render2, + }; + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: () => ownName, + set: (name) => { + ownName = name; + if (render2.displayName == null) { + render2.displayName = name; + } + }, + }); + return elementType; + } + var enableScopeAPI = false; + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if ( + type === exports.Fragment || + type === exports.Profiler || + type === REACT_DEBUG_TRACING_MODE_TYPE || + type === exports.StrictMode || + type === exports.Suspense || + type === REACT_SUSPENSE_LIST_TYPE || + type === REACT_LEGACY_HIDDEN_TYPE || + enableScopeAPI + ) { + return true; + } + if (typeof type === "object" && type !== null) { + if ( + type.$$typeof === REACT_LAZY_TYPE || + type.$$typeof === REACT_MEMO_TYPE || + type.$$typeof === REACT_PROVIDER_TYPE || + type.$$typeof === REACT_CONTEXT_TYPE || + type.$$typeof === REACT_FORWARD_REF_TYPE || + type.$$typeof === REACT_FUNDAMENTAL_TYPE || + type.$$typeof === REACT_BLOCK_TYPE || + type[0] === REACT_SERVER_BLOCK_TYPE + ) { + return true; + } + } + return false; + } + function memo(type, compare) { + if (!isValidElementType(type)) { + error( + "memo: The first argument must be a component. Instead received: %s", + type === null ? "null" : typeof type, + ); + } + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type, + compare: compare === void 0 ? null : compare, + }; + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: () => ownName, + set: (name) => { + ownName = name; + if (type.displayName == null) { + type.displayName = name; + } + }, + }); + return elementType; + } + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + if (!(dispatcher !== null)) { + throw 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://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.", + ); + } + return dispatcher; + } + function useContext(Context, unstable_observedBits) { + var dispatcher = resolveDispatcher(); + if (unstable_observedBits !== void 0) { + error( + "useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", + unstable_observedBits, + typeof unstable_observedBits === "number" && + Array.isArray(arguments[2]) + ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" + : "", + ); + } + if (Context._context !== void 0) { + var realContext = Context._context; + if (realContext.Consumer === Context) { + error( + "Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?", + ); + } else if (realContext.Provider === Context) { + error( + "Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?", + ); + } + } + return dispatcher.useContext(Context, unstable_observedBits); + } + function useState2(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() {} + disabledLog.__reactDisabledLog = true; + function disableLogs() { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true, + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props, + }); + } + disabledDepth++; + } + function reenableLogs() { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true, + }; + Object.defineProperties(console, { + log: _assign({}, props, { + value: prevLog, + }), + info: _assign({}, props, { + value: prevInfo, + }), + warn: _assign({}, props, { + value: prevWarn, + }), + error: _assign({}, props, { + value: prevError, + }), + group: _assign({}, props, { + value: prevGroup, + }), + groupCollapsed: _assign({}, props, { + value: prevGroupCollapsed, + }), + groupEnd: _assign({}, props, { + value: prevGroupEnd, + }), + }); + } + if (disabledDepth < 0) { + error( + "disabledDepth fell below zero. This is a bug in React. Please file an issue.", + ); + } + } + var ReactCurrentDispatcher$1 = + ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + if (prefix === void 0) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + } + return "\n" + prefix + name; + } + var reentry = false; + var componentFrameCache; + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + previousDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = null; + disableLogs(); + try { + if (construct) { + var Fake = () => { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: () => { + throw Error(); + }, + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = + "\n" + sampleLines[s].replace(" at new ", " at "); + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name + ? describeBuiltInComponentFrame(name) + : ""; + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + return describeNativeComponentFrame(fn, false); + } + function shouldConstruct(Component2) { + var prototype = Component2.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case exports.Suspense: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV( + type.type, + source, + ownerFn, + ); + case REACT_BLOCK_TYPE: + return describeFunctionComponentFrame(type._render); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV( + init(payload), + source, + ownerFn, + ); + } catch (x) {} + } + } + } + return ""; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = + ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV( + element.type, + element._source, + owner ? owner.type : null, + ); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + function checkPropTypes( + typeSpecs, + values, + location2, + componentName, + element, + ) { + var has = Function.call.bind(Object.prototype.hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error( + (componentName || "React class") + + ": " + + location2 + + " type `" + + typeSpecName + + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + + typeof typeSpecs[typeSpecName] + + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.", + ); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName]( + values, + typeSpecName, + componentName, + location2, + null, + "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED", + ); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error( + "%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", + componentName || "React class", + location2, + typeSpecName, + typeof error$1, + ); + setCurrentlyValidatingElement(null); + } + if ( + error$1 instanceof Error && + !(error$1.message in loggedTypeFailures) + ) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location2, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + function setCurrentlyValidatingElement$1(element) { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV( + element.type, + element._source, + owner ? owner.type : null, + ); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + var propTypesMisspellWarningShown; + propTypesMisspellWarningShown = false; + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentName(ReactCurrentOwner.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + function getSourceInfoErrorAddendum(source) { + if (source !== void 0) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return ( + "\n\nCheck your code at " + fileName + ":" + lineNumber + "." + ); + } + return ""; + } + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== void 0) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + return ""; + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = + typeof parentType === "string" + ? parentType + : parentType.displayName || parentType.name; + if (parentName) { + info = + "\n\nCheck the top-level render call using <" + + parentName + + ">."; + } + } + return info; + } + function validateExplicitKey(element, parentType) { + if ( + !element._store || + element._store.validated || + element.key != null + ) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = + getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if ( + element && + element._owner && + element._owner !== ReactCurrentOwner.current + ) { + childOwner = + " It was passed a child from " + + getComponentName(element._owner.type) + + "."; + } + setCurrentlyValidatingElement$1(element); + error( + 'Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', + currentComponentErrorInfo, + childOwner, + ); + setCurrentlyValidatingElement$1(null); + } + function validateChildKeys(node, parentType) { + if (typeof node !== "object") { + return; + } + if (Array.isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + function validatePropTypes(element) { + var type = element.type; + if (type === null || type === void 0 || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if ( + typeof type === "object" && + (type.$$typeof === REACT_FORWARD_REF_TYPE || + type.$$typeof === REACT_MEMO_TYPE) + ) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentName(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if ( + type.PropTypes !== void 0 && + !propTypesMisspellWarningShown + ) { + propTypesMisspellWarningShown = true; + var _name = getComponentName(type); + error( + "Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", + _name || "Unknown", + ); + } + if ( + typeof type.getDefaultProps === "function" && + !type.getDefaultProps.isReactClassApproved + ) { + error( + "getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.", + ); + } + } + function validateFragmentProps(fragment) { + var keys = Object.keys(fragment.props); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error( + "Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", + key, + ); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); + if (!validType) { + var info = ""; + if ( + type === void 0 || + (typeof type === "object" && + type !== null && + Object.keys(type).length === 0) + ) { + info += + " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (Array.isArray(type)) { + typeString = "array"; + } else if ( + type !== void 0 && + type.$$typeof === REACT_ELEMENT_TYPE + ) { + typeString = + "<" + (getComponentName(type.type) || "Unknown") + " />"; + info = + " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + error( + "React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", + typeString, + info, + ); + } + var element = createElement.apply(this, arguments); + if (element == null) { + return element; + } + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + if (type === exports.Fragment) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + warn( + "React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.", + ); + } + Object.defineProperty(validatedFactory, "type", { + enumerable: false, + get: function () { + warn( + "Factory.type is deprecated. Access the class directly before passing it to createFactory.", + ); + Object.defineProperty(this, "type", { + value: type, + }); + return type; + }, + }); + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + try { + var frozenObject = Object.freeze({}); + /* @__PURE__ */ new Map([[frozenObject, null]]); + /* @__PURE__ */ new Set([frozenObject]); + } catch (e) {} + var createElement$1 = createElementWithValidation; + var cloneElement$1 = cloneElementWithValidation; + var createFactory = createFactoryWithValidation; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray, + only: onlyChild, + }; + exports.Children = Children; + exports.Component = Component; + exports.PureComponent = PureComponent; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = + ReactSharedInternals; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext; + exports.createElement = createElement$1; + exports.createFactory = createFactory; + exports.createRef = createRef; + exports.forwardRef = forwardRef; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.useCallback = useCallback; + exports.useContext = useContext; + exports.useDebugValue = useDebugValue; + exports.useEffect = useEffect; + exports.useImperativeHandle = useImperativeHandle; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo; + exports.useReducer = useReducer; + exports.useRef = useRef; + exports.useState = useState2; + exports.version = ReactVersion; + })(); + } + }, + }); - // node_modules/.pnpm/react@17.0.2/node_modules/react/index.js - var require_react = __commonJS({ - "node_modules/.pnpm/react@17.0.2/node_modules/react/index.js"(exports, module) { - "use strict"; - if (false) { - module.exports = null; - } else { - module.exports = require_react_development(); - } - } - }); + // node_modules/.pnpm/react@17.0.2/node_modules/react/index.js + var require_react = __commonJS({ + "node_modules/.pnpm/react@17.0.2/node_modules/react/index.js"( + exports, + module, + ) { + if (false) { + module.exports = null; + } else { + module.exports = require_react_development(); + } + }, + }); - // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler.development.js - var require_scheduler_development = __commonJS({ - "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var enableSchedulerDebugging = false; - var enableProfiling = false; - var requestHostCallback; - var requestHostTimeout; - var cancelHostTimeout; - var requestPaint; - var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; - if (hasPerformanceNow) { - var localPerformance = performance; - exports.unstable_now = function() { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - exports.unstable_now = function() { - return localDate.now() - initialTime; - }; - } - if (typeof self === "undefined" || typeof MessageChannel !== "function") { - var _callback = null; - var _timeoutID = null; - var _flushCallback = function() { - if (_callback !== null) { - try { - var currentTime = exports.unstable_now(); - var hasRemainingTime = true; - _callback(hasRemainingTime, currentTime); - _callback = null; - } catch (e) { - setTimeout(_flushCallback, 0); - throw e; - } - } - }; - requestHostCallback = function(cb) { - if (_callback !== null) { - setTimeout(requestHostCallback, 0, cb); - } else { - _callback = cb; - setTimeout(_flushCallback, 0); - } - }; - requestHostTimeout = function(cb, ms) { - _timeoutID = setTimeout(cb, ms); - }; - cancelHostTimeout = function() { - clearTimeout(_timeoutID); - }; - exports.unstable_shouldYield = function() { - return false; - }; - requestPaint = exports.unstable_forceFrameRate = function() { - }; - } else { - var _setTimeout = self.setTimeout; - var _clearTimeout = self.clearTimeout; - if (typeof console !== "undefined") { - var requestAnimationFrame = self.requestAnimationFrame; - var cancelAnimationFrame = self.cancelAnimationFrame; - if (typeof requestAnimationFrame !== "function") { - console["error"]("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"); - } - if (typeof cancelAnimationFrame !== "function") { - console["error"]("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"); - } - } - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; - var yieldInterval = 5; - var deadline = 0; - { - exports.unstable_shouldYield = function() { - return exports.unstable_now() >= deadline; - }; - requestPaint = function() { - }; - } - exports.unstable_forceFrameRate = function(fps) { - if (fps < 0 || fps > 125) { - console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); - return; - } - if (fps > 0) { - yieldInterval = Math.floor(1e3 / fps); - } else { - yieldInterval = 5; - } - }; - var performWorkUntilDeadline = function() { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); - deadline = currentTime + yieldInterval; - var hasTimeRemaining = true; - try { - var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - if (!hasMoreWork) { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } else { - port.postMessage(null); - } - } catch (error) { - port.postMessage(null); - throw error; - } - } else { - isMessageLoopRunning = false; - } - }; - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - requestHostCallback = function(callback) { - scheduledHostCallback = callback; - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - port.postMessage(null); - } - }; - requestHostTimeout = function(callback, ms) { - taskTimeoutID = _setTimeout(function() { - callback(exports.unstable_now()); - }, ms); - }; - cancelHostTimeout = function() { - _clearTimeout(taskTimeoutID); - taskTimeoutID = -1; - }; - } - function push(heap, node) { - var index = heap.length; - heap.push(node); - siftUp(heap, node, index); - } - function peek(heap) { - var first = heap[0]; - return first === void 0 ? null : first; - } - function pop(heap) { - var first = heap[0]; - if (first !== void 0) { - var last = heap.pop(); - if (last !== first) { - heap[0] = last; - siftDown(heap, last, 0); - } - return first; - } else { - return null; - } - } - function siftUp(heap, node, i) { - var index = i; - while (true) { - var parentIndex = index - 1 >>> 1; - var parent = heap[parentIndex]; - if (parent !== void 0 && compare(parent, node) > 0) { - heap[parentIndex] = node; - heap[index] = parent; - index = parentIndex; - } else { - return; - } - } - } - function siftDown(heap, node, i) { - var index = i; - var length = heap.length; - while (index < length) { - var leftIndex = (index + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; - if (left !== void 0 && compare(left, node) < 0) { - if (right !== void 0 && compare(right, left) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - heap[index] = left; - heap[leftIndex] = node; - index = leftIndex; - } - } else if (right !== void 0 && compare(right, node) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - return; - } - } - } - function compare(a, b) { - var diff = a.sortIndex - b.sortIndex; - return diff !== 0 ? diff : a.id - b.id; - } - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - function markTaskErrored(task, ms) { - } - var maxSigned31BitInt = 1073741823; - var IMMEDIATE_PRIORITY_TIMEOUT = -1; - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5e3; - var LOW_PRIORITY_TIMEOUT = 1e4; - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; - var taskQueue = []; - var timerQueue = []; - var taskIdCounter = 1; - var currentTask = null; - var currentPriorityLevel = NormalPriority; - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; - function advanceTimers(currentTime) { - var timer = peek(timerQueue); - while (timer !== null) { - if (timer.callback === null) { - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push(taskQueue, timer); - } else { - return; - } - timer = peek(timerQueue); - } - } - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - function flushWork(hasTimeRemaining, initialTime2) { - isHostCallbackScheduled = false; - if (isHostTimeoutScheduled) { - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - try { - if (enableProfiling) { - try { - return workLoop(hasTimeRemaining, initialTime2); - } catch (error) { - if (currentTask !== null) { - var currentTime = exports.unstable_now(); - markTaskErrored(currentTask, currentTime); - currentTask.isQueued = false; - } - throw error; - } - } else { - return workLoop(hasTimeRemaining, initialTime2); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - function workLoop(hasTimeRemaining, initialTime2) { - var currentTime = initialTime2; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - while (currentTask !== null && !enableSchedulerDebugging) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || exports.unstable_shouldYield())) { - break; - } - var callback = currentTask.callback; - if (typeof callback === "function") { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - if (typeof continuationCallback === "function") { - currentTask.callback = continuationCallback; - } else { - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - currentTask = peek(taskQueue); - } - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - return false; - } - } - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - default: - priorityLevel = NormalPriority; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_next(eventHandler) { - var priorityLevel; - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - priorityLevel = NormalPriority; - break; - default: - priorityLevel = currentPriorityLevel; - break; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function() { - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime; - if (typeof options === "object" && options !== null) { - var delay = options.delay; - if (typeof delay === "number" && delay > 0) { - startTime = currentTime + delay; - } else { - startTime = currentTime; - } - } else { - startTime = currentTime; - } - var timeout; - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - var expirationTime = startTime + timeout; - var newTask = { - id: taskIdCounter++, - callback, - priorityLevel, - startTime, - expirationTime, - sortIndex: -1 - }; - if (startTime > currentTime) { - newTask.sortIndex = startTime; - push(timerQueue, newTask); - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - if (isHostTimeoutScheduled) { - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } - requestHostTimeout(handleTimeout, startTime - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push(taskQueue, newTask); - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - return newTask; - } - function unstable_pauseExecution() { - } - function unstable_continueExecution() { - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - function unstable_cancelCallback(task) { - task.callback = null; - } - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_wrapCallback = unstable_wrapCallback; - })(); - } - } - }); + // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler.development.js + var require_scheduler_development = __commonJS({ + "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler.development.js"( + exports, + ) { + if (true) { + (() => { + var enableSchedulerDebugging = false; + var enableProfiling = false; + var requestHostCallback; + var requestHostTimeout; + var cancelHostTimeout; + var requestPaint; + var hasPerformanceNow = + typeof performance === "object" && + typeof performance.now === "function"; + if (hasPerformanceNow) { + var localPerformance = performance; + exports.unstable_now = () => localPerformance.now(); + } else { + var localDate = Date; + var initialTime = localDate.now(); + exports.unstable_now = () => localDate.now() - initialTime; + } + if ( + typeof self === "undefined" || + typeof MessageChannel !== "function" + ) { + var _callback = null; + var _timeoutID = null; + var _flushCallback = () => { + if (_callback !== null) { + try { + var currentTime = exports.unstable_now(); + var hasRemainingTime = true; + _callback(hasRemainingTime, currentTime); + _callback = null; + } catch (e) { + setTimeout(_flushCallback, 0); + throw e; + } + } + }; + requestHostCallback = (cb) => { + if (_callback !== null) { + setTimeout(requestHostCallback, 0, cb); + } else { + _callback = cb; + setTimeout(_flushCallback, 0); + } + }; + requestHostTimeout = (cb, ms) => { + _timeoutID = setTimeout(cb, ms); + }; + cancelHostTimeout = () => { + clearTimeout(_timeoutID); + }; + exports.unstable_shouldYield = () => false; + requestPaint = exports.unstable_forceFrameRate = () => {}; + } else { + var _setTimeout = self.setTimeout; + var _clearTimeout = self.clearTimeout; + if (typeof console !== "undefined") { + var requestAnimationFrame = self.requestAnimationFrame; + var cancelAnimationFrame = self.cancelAnimationFrame; + if (typeof requestAnimationFrame !== "function") { + console["error"]( + "This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills", + ); + } + if (typeof cancelAnimationFrame !== "function") { + console["error"]( + "This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills", + ); + } + } + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; + var yieldInterval = 5; + var deadline = 0; + exports.unstable_shouldYield = () => + exports.unstable_now() >= deadline; + requestPaint = () => {}; + exports.unstable_forceFrameRate = (fps) => { + if (fps < 0 || fps > 125) { + console["error"]( + "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported", + ); + return; + } + if (fps > 0) { + yieldInterval = Math.floor(1e3 / fps); + } else { + yieldInterval = 5; + } + }; + var performWorkUntilDeadline = () => { + if (scheduledHostCallback !== null) { + var currentTime = exports.unstable_now(); + deadline = currentTime + yieldInterval; + var hasTimeRemaining = true; + try { + var hasMoreWork = scheduledHostCallback( + hasTimeRemaining, + currentTime, + ); + if (!hasMoreWork) { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } else { + port.postMessage(null); + } + } catch (error) { + port.postMessage(null); + throw error; + } + } else { + isMessageLoopRunning = false; + } + }; + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; + requestHostCallback = (callback) => { + scheduledHostCallback = callback; + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + port.postMessage(null); + } + }; + requestHostTimeout = (callback, ms) => { + taskTimeoutID = _setTimeout(() => { + callback(exports.unstable_now()); + }, ms); + }; + cancelHostTimeout = () => { + _clearTimeout(taskTimeoutID); + taskTimeoutID = -1; + }; + } + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + var first = heap[0]; + return first === void 0 ? null : first; + } + function pop(heap) { + var first = heap[0]; + if (first !== void 0) { + var last = heap.pop(); + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } + return first; + } else { + return null; + } + } + function siftUp(heap, node, i) { + var index = i; + while (true) { + var parentIndex = (index - 1) >>> 1; + var parent = heap[parentIndex]; + if (parent !== void 0 && compare(parent, node) > 0) { + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + return; + } + } + } + function siftDown(heap, node, i) { + var index = i; + var length = heap.length; + while (index < length) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; + if (left !== void 0 && compare(left, node) < 0) { + if (right !== void 0 && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (right !== void 0 && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + return; + } + } + } + function compare(a, b) { + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; + function markTaskErrored(task, ms) {} + var maxSigned31BitInt = 1073741823; + var IMMEDIATE_PRIORITY_TIMEOUT = -1; + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5e3; + var LOW_PRIORITY_TIMEOUT = 1e4; + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; + var taskQueue = []; + var timerQueue = []; + var taskIdCounter = 1; + var currentTask = null; + var currentPriorityLevel = NormalPriority; + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; + function advanceTimers(currentTime) { + var timer = peek(timerQueue); + while (timer !== null) { + if (timer.callback === null) { + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + return; + } + timer = peek(timerQueue); + } + } + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); + if (firstTimer !== null) { + requestHostTimeout( + handleTimeout, + firstTimer.startTime - currentTime, + ); + } + } + } + } + function flushWork(hasTimeRemaining, initialTime2) { + isHostCallbackScheduled = false; + if (isHostTimeoutScheduled) { + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; + try { + if (enableProfiling) { + try { + return workLoop(hasTimeRemaining, initialTime2); + } catch (error) { + if (currentTask !== null) { + var currentTime = exports.unstable_now(); + markTaskErrored(currentTask, currentTime); + currentTask.isQueued = false; + } + throw error; + } + } else { + return workLoop(hasTimeRemaining, initialTime2); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } + function workLoop(hasTimeRemaining, initialTime2) { + var currentTime = initialTime2; + advanceTimers(currentTime); + currentTask = peek(taskQueue); + while (currentTask !== null && !enableSchedulerDebugging) { + if ( + currentTask.expirationTime > currentTime && + (!hasTimeRemaining || exports.unstable_shouldYield()) + ) { + break; + } + var callback = currentTask.callback; + if (typeof callback === "function") { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = + currentTask.expirationTime <= currentTime; + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = exports.unstable_now(); + if (typeof continuationCallback === "function") { + currentTask.callback = continuationCallback; + } else { + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } + advanceTimers(currentTime); + } else { + pop(taskQueue); + } + currentTask = peek(taskQueue); + } + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); + if (firstTimer !== null) { + requestHostTimeout( + handleTimeout, + firstTimer.startTime - currentTime, + ); + } + return false; + } + } + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; + default: + priorityLevel = NormalPriority; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_next(eventHandler) { + var priorityLevel; + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + priorityLevel = NormalPriority; + break; + default: + priorityLevel = currentPriorityLevel; + break; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function () { + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = exports.unstable_now(); + var startTime; + if (typeof options === "object" && options !== null) { + var delay = options.delay; + if (typeof delay === "number" && delay > 0) { + startTime = currentTime + delay; + } else { + startTime = currentTime; + } + } else { + startTime = currentTime; + } + var timeout; + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } + var expirationTime = startTime + timeout; + var newTask = { + id: taskIdCounter++, + callback, + priorityLevel, + startTime, + expirationTime, + sortIndex: -1, + }; + if (startTime > currentTime) { + newTask.sortIndex = startTime; + push(timerQueue, newTask); + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + if (isHostTimeoutScheduled) { + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } + requestHostTimeout(handleTimeout, startTime - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + return newTask; + } + function unstable_pauseExecution() {} + function unstable_continueExecution() { + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } + function unstable_cancelCallback(task) { + task.callback = null; + } + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; + exports.unstable_IdlePriority = IdlePriority; + exports.unstable_ImmediatePriority = ImmediatePriority; + exports.unstable_LowPriority = LowPriority; + exports.unstable_NormalPriority = NormalPriority; + exports.unstable_Profiling = unstable_Profiling; + exports.unstable_UserBlockingPriority = UserBlockingPriority; + exports.unstable_cancelCallback = unstable_cancelCallback; + exports.unstable_continueExecution = unstable_continueExecution; + exports.unstable_getCurrentPriorityLevel = + unstable_getCurrentPriorityLevel; + exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; + exports.unstable_next = unstable_next; + exports.unstable_pauseExecution = unstable_pauseExecution; + exports.unstable_requestPaint = unstable_requestPaint; + exports.unstable_runWithPriority = unstable_runWithPriority; + exports.unstable_scheduleCallback = unstable_scheduleCallback; + exports.unstable_wrapCallback = unstable_wrapCallback; + })(); + } + }, + }); - // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/index.js - var require_scheduler = __commonJS({ - "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/index.js"(exports, module) { - "use strict"; - if (false) { - module.exports = null; - } else { - module.exports = require_scheduler_development(); - } - } - }); + // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/index.js + var require_scheduler = __commonJS({ + "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/index.js"( + exports, + module, + ) { + if (false) { + module.exports = null; + } else { + module.exports = require_scheduler_development(); + } + }, + }); - // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler-tracing.development.js - var require_scheduler_tracing_development = __commonJS({ - "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler-tracing.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var DEFAULT_THREAD_ID = 0; - var interactionIDCounter = 0; - var threadIDCounter = 0; - exports.__interactionsRef = null; - exports.__subscriberRef = null; - { - exports.__interactionsRef = { - current: /* @__PURE__ */ new Set() - }; - exports.__subscriberRef = { - current: null - }; - } - function unstable_clear(callback) { - var prevInteractions = exports.__interactionsRef.current; - exports.__interactionsRef.current = /* @__PURE__ */ new Set(); - try { - return callback(); - } finally { - exports.__interactionsRef.current = prevInteractions; - } - } - function unstable_getCurrent() { - { - return exports.__interactionsRef.current; - } - } - function unstable_getThreadID() { - return ++threadIDCounter; - } - function unstable_trace(name, timestamp, callback) { - var threadID = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : DEFAULT_THREAD_ID; - var interaction = { - __count: 1, - id: interactionIDCounter++, - name, - timestamp - }; - var prevInteractions = exports.__interactionsRef.current; - var interactions = new Set(prevInteractions); - interactions.add(interaction); - exports.__interactionsRef.current = interactions; - var subscriber = exports.__subscriberRef.current; - var returnValue; - try { - if (subscriber !== null) { - subscriber.onInteractionTraced(interaction); - } - } finally { - try { - if (subscriber !== null) { - subscriber.onWorkStarted(interactions, threadID); - } - } finally { - try { - returnValue = callback(); - } finally { - exports.__interactionsRef.current = prevInteractions; - try { - if (subscriber !== null) { - subscriber.onWorkStopped(interactions, threadID); - } - } finally { - interaction.__count--; - if (subscriber !== null && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } - } - } - } - } - return returnValue; - } - function unstable_wrap(callback) { - var threadID = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_THREAD_ID; - var wrappedInteractions = exports.__interactionsRef.current; - var subscriber = exports.__subscriberRef.current; - if (subscriber !== null) { - subscriber.onWorkScheduled(wrappedInteractions, threadID); - } - wrappedInteractions.forEach(function(interaction) { - interaction.__count++; - }); - var hasRun = false; - function wrapped() { - var prevInteractions = exports.__interactionsRef.current; - exports.__interactionsRef.current = wrappedInteractions; - subscriber = exports.__subscriberRef.current; - try { - var returnValue; - try { - if (subscriber !== null) { - subscriber.onWorkStarted(wrappedInteractions, threadID); - } - } finally { - try { - returnValue = callback.apply(void 0, arguments); - } finally { - exports.__interactionsRef.current = prevInteractions; - if (subscriber !== null) { - subscriber.onWorkStopped(wrappedInteractions, threadID); - } - } - } - return returnValue; - } finally { - if (!hasRun) { - hasRun = true; - wrappedInteractions.forEach(function(interaction) { - interaction.__count--; - if (subscriber !== null && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } - }); - } - } - } - wrapped.cancel = function cancel() { - subscriber = exports.__subscriberRef.current; - try { - if (subscriber !== null) { - subscriber.onWorkCanceled(wrappedInteractions, threadID); - } - } finally { - wrappedInteractions.forEach(function(interaction) { - interaction.__count--; - if (subscriber && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } - }); - } - }; - return wrapped; - } - var subscribers = null; - { - subscribers = /* @__PURE__ */ new Set(); - } - function unstable_subscribe(subscriber) { - { - subscribers.add(subscriber); - if (subscribers.size === 1) { - exports.__subscriberRef.current = { - onInteractionScheduledWorkCompleted, - onInteractionTraced, - onWorkCanceled, - onWorkScheduled, - onWorkStarted, - onWorkStopped - }; - } - } - } - function unstable_unsubscribe(subscriber) { - { - subscribers.delete(subscriber); - if (subscribers.size === 0) { - exports.__subscriberRef.current = null; - } - } - } - function onInteractionTraced(interaction) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onInteractionTraced(interaction); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onInteractionScheduledWorkCompleted(interaction) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkScheduled(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkScheduled(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkStarted(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkStarted(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkStopped(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkStopped(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkCanceled(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkCanceled(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - exports.unstable_clear = unstable_clear; - exports.unstable_getCurrent = unstable_getCurrent; - exports.unstable_getThreadID = unstable_getThreadID; - exports.unstable_subscribe = unstable_subscribe; - exports.unstable_trace = unstable_trace; - exports.unstable_unsubscribe = unstable_unsubscribe; - exports.unstable_wrap = unstable_wrap; - })(); - } - } - }); + // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler-tracing.development.js + var require_scheduler_tracing_development = __commonJS({ + "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/cjs/scheduler-tracing.development.js"( + exports, + ) { + if (true) { + (() => { + var DEFAULT_THREAD_ID = 0; + var interactionIDCounter = 0; + var threadIDCounter = 0; + exports.__interactionsRef = null; + exports.__subscriberRef = null; + exports.__interactionsRef = { + current: /* @__PURE__ */ new Set(), + }; + exports.__subscriberRef = { + current: null, + }; + function unstable_clear(callback) { + var prevInteractions = exports.__interactionsRef.current; + exports.__interactionsRef.current = /* @__PURE__ */ new Set(); + try { + return callback(); + } finally { + exports.__interactionsRef.current = prevInteractions; + } + } + function unstable_getCurrent() { + return exports.__interactionsRef.current; + } + function unstable_getThreadID() { + return ++threadIDCounter; + } + function unstable_trace(name, timestamp, callback) { + var threadID = + arguments.length > 3 && arguments[3] !== void 0 + ? arguments[3] + : DEFAULT_THREAD_ID; + var interaction = { + __count: 1, + id: interactionIDCounter++, + name, + timestamp, + }; + var prevInteractions = exports.__interactionsRef.current; + var interactions = new Set(prevInteractions); + interactions.add(interaction); + exports.__interactionsRef.current = interactions; + var subscriber = exports.__subscriberRef.current; + var returnValue; + try { + if (subscriber !== null) { + subscriber.onInteractionTraced(interaction); + } + } finally { + try { + if (subscriber !== null) { + subscriber.onWorkStarted(interactions, threadID); + } + } finally { + try { + returnValue = callback(); + } finally { + exports.__interactionsRef.current = prevInteractions; + try { + if (subscriber !== null) { + subscriber.onWorkStopped(interactions, threadID); + } + } finally { + interaction.__count--; + if (subscriber !== null && interaction.__count === 0) { + subscriber.onInteractionScheduledWorkCompleted( + interaction, + ); + } + } + } + } + } + return returnValue; + } + function unstable_wrap(callback) { + var threadID = + arguments.length > 1 && arguments[1] !== void 0 + ? arguments[1] + : DEFAULT_THREAD_ID; + var wrappedInteractions = exports.__interactionsRef.current; + var subscriber = exports.__subscriberRef.current; + if (subscriber !== null) { + subscriber.onWorkScheduled(wrappedInteractions, threadID); + } + wrappedInteractions.forEach((interaction) => { + interaction.__count++; + }); + var hasRun = false; + function wrapped() { + var prevInteractions = exports.__interactionsRef.current; + exports.__interactionsRef.current = wrappedInteractions; + subscriber = exports.__subscriberRef.current; + try { + var returnValue; + try { + if (subscriber !== null) { + subscriber.onWorkStarted(wrappedInteractions, threadID); + } + } finally { + try { + returnValue = callback.apply(void 0, arguments); + } finally { + exports.__interactionsRef.current = prevInteractions; + if (subscriber !== null) { + subscriber.onWorkStopped(wrappedInteractions, threadID); + } + } + } + return returnValue; + } finally { + if (!hasRun) { + hasRun = true; + wrappedInteractions.forEach((interaction) => { + interaction.__count--; + if (subscriber !== null && interaction.__count === 0) { + subscriber.onInteractionScheduledWorkCompleted( + interaction, + ); + } + }); + } + } + } + wrapped.cancel = function cancel() { + subscriber = exports.__subscriberRef.current; + try { + if (subscriber !== null) { + subscriber.onWorkCanceled(wrappedInteractions, threadID); + } + } finally { + wrappedInteractions.forEach((interaction) => { + interaction.__count--; + if (subscriber && interaction.__count === 0) { + subscriber.onInteractionScheduledWorkCompleted(interaction); + } + }); + } + }; + return wrapped; + } + var subscribers = null; + subscribers = /* @__PURE__ */ new Set(); + function unstable_subscribe(subscriber) { + subscribers.add(subscriber); + if (subscribers.size === 1) { + exports.__subscriberRef.current = { + onInteractionScheduledWorkCompleted, + onInteractionTraced, + onWorkCanceled, + onWorkScheduled, + onWorkStarted, + onWorkStopped, + }; + } + } + function unstable_unsubscribe(subscriber) { + subscribers.delete(subscriber); + if (subscribers.size === 0) { + exports.__subscriberRef.current = null; + } + } + function onInteractionTraced(interaction) { + var didCatchError = false; + var caughtError = null; + subscribers.forEach((subscriber) => { + try { + subscriber.onInteractionTraced(interaction); + } catch (error) { + if (!didCatchError) { + didCatchError = true; + caughtError = error; + } + } + }); + if (didCatchError) { + throw caughtError; + } + } + function onInteractionScheduledWorkCompleted(interaction) { + var didCatchError = false; + var caughtError = null; + subscribers.forEach((subscriber) => { + try { + subscriber.onInteractionScheduledWorkCompleted(interaction); + } catch (error) { + if (!didCatchError) { + didCatchError = true; + caughtError = error; + } + } + }); + if (didCatchError) { + throw caughtError; + } + } + function onWorkScheduled(interactions, threadID) { + var didCatchError = false; + var caughtError = null; + subscribers.forEach((subscriber) => { + try { + subscriber.onWorkScheduled(interactions, threadID); + } catch (error) { + if (!didCatchError) { + didCatchError = true; + caughtError = error; + } + } + }); + if (didCatchError) { + throw caughtError; + } + } + function onWorkStarted(interactions, threadID) { + var didCatchError = false; + var caughtError = null; + subscribers.forEach((subscriber) => { + try { + subscriber.onWorkStarted(interactions, threadID); + } catch (error) { + if (!didCatchError) { + didCatchError = true; + caughtError = error; + } + } + }); + if (didCatchError) { + throw caughtError; + } + } + function onWorkStopped(interactions, threadID) { + var didCatchError = false; + var caughtError = null; + subscribers.forEach((subscriber) => { + try { + subscriber.onWorkStopped(interactions, threadID); + } catch (error) { + if (!didCatchError) { + didCatchError = true; + caughtError = error; + } + } + }); + if (didCatchError) { + throw caughtError; + } + } + function onWorkCanceled(interactions, threadID) { + var didCatchError = false; + var caughtError = null; + subscribers.forEach((subscriber) => { + try { + subscriber.onWorkCanceled(interactions, threadID); + } catch (error) { + if (!didCatchError) { + didCatchError = true; + caughtError = error; + } + } + }); + if (didCatchError) { + throw caughtError; + } + } + exports.unstable_clear = unstable_clear; + exports.unstable_getCurrent = unstable_getCurrent; + exports.unstable_getThreadID = unstable_getThreadID; + exports.unstable_subscribe = unstable_subscribe; + exports.unstable_trace = unstable_trace; + exports.unstable_unsubscribe = unstable_unsubscribe; + exports.unstable_wrap = unstable_wrap; + })(); + } + }, + }); - // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/tracing.js - var require_tracing = __commonJS({ - "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/tracing.js"(exports, module) { - "use strict"; - if (false) { - module.exports = null; - } else { - module.exports = require_scheduler_tracing_development(); - } - } - }); + // node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/tracing.js + var require_tracing = __commonJS({ + "node_modules/.pnpm/scheduler@0.20.2/node_modules/scheduler/tracing.js"( + exports, + module, + ) { + if (false) { + module.exports = null; + } else { + module.exports = require_scheduler_tracing_development(); + } + }, + }); - // node_modules/.pnpm/react-dom@17.0.2_react@17.0.2/node_modules/react-dom/cjs/react-dom.development.js - var require_react_dom_development = __commonJS({ - "node_modules/.pnpm/react-dom@17.0.2_react@17.0.2/node_modules/react-dom/cjs/react-dom.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var React3 = require_react(); - var _assign = require_object_assign(); - var Scheduler = require_scheduler(); - var tracing = require_tracing(); - var ReactSharedInternals = React3.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - function warn(format) { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - function error(format) { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return "" + item; - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - if (!React3) { - { - throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM."); - } - } - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; - var HostRoot = 3; - var HostPortal = 4; - var HostComponent = 5; - var HostText = 6; - var Fragment = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var FundamentalComponent = 20; - var ScopeComponent = 21; - var Block = 22; - var OffscreenComponent = 23; - var LegacyHiddenComponent = 24; - var enableProfilerTimer = true; - var enableFundamentalAPI = false; - var enableNewReconciler = false; - var warnAboutStringRefs = false; - var allNativeEvents = /* @__PURE__ */ new Set(); - var registrationNameDependencies = {}; - var possibleRegistrationNames = {}; - function registerTwoPhaseEvent(registrationName, dependencies) { - registerDirectEvent(registrationName, dependencies); - registerDirectEvent(registrationName + "Capture", dependencies); - } - function registerDirectEvent(registrationName, dependencies) { - { - if (registrationNameDependencies[registrationName]) { - error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); - } - } - registrationNameDependencies[registrationName] = dependencies; - { - var lowerCasedName = registrationName.toLowerCase(); - possibleRegistrationNames[lowerCasedName] = registrationName; - if (registrationName === "onDoubleClick") { - possibleRegistrationNames.ondblclick = registrationName; - } - } - for (var i = 0; i < dependencies.length; i++) { - allNativeEvents.add(dependencies[i]); - } - } - var canUseDOM = !!(typeof self !== "undefined" && typeof self.document !== "undefined" && typeof self.document.createElement !== "undefined"); - var RESERVED = 0; - var STRING = 1; - var BOOLEANISH_STRING = 2; - var BOOLEAN = 3; - var OVERLOADED_BOOLEAN = 4; - var NUMERIC = 5; - var POSITIVE_NUMERIC = 6; - var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; - var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; - var ROOT_ATTRIBUTE_NAME = "data-reactroot"; - var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); - var hasOwnProperty = Object.prototype.hasOwnProperty; - var illegalAttributeNameCache = {}; - var validatedAttributeNameCache = {}; - function isAttributeNameSafe(attributeName) { - if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { - return true; - } - if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { - return false; - } - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true; - return true; - } - illegalAttributeNameCache[attributeName] = true; - { - error("Invalid attribute name: `%s`", attributeName); - } - return false; - } - function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null) { - return propertyInfo.type === RESERVED; - } - if (isCustomComponentTag) { - return false; - } - if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { - return true; - } - return false; - } - function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false; - } - switch (typeof value) { - case "function": - case "symbol": - return true; - case "boolean": { - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans; - } else { - var prefix2 = name.toLowerCase().slice(0, 5); - return prefix2 !== "data-" && prefix2 !== "aria-"; - } - } - default: - return false; - } - } - function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { - if (value === null || typeof value === "undefined") { - return true; - } - if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { - return true; - } - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - switch (propertyInfo.type) { - case BOOLEAN: - return !value; - case OVERLOADED_BOOLEAN: - return value === false; - case NUMERIC: - return isNaN(value); - case POSITIVE_NUMERIC: - return isNaN(value) || value < 1; - } - } - return false; - } - function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null; - } - function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { - this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; - this.attributeName = attributeName; - this.attributeNamespace = attributeNamespace; - this.mustUseProperty = mustUseProperty; - this.propertyName = name; - this.type = type; - this.sanitizeURL = sanitizeURL2; - this.removeEmptyString = removeEmptyString; - } - var properties = {}; - var reservedProps = [ - "children", - "dangerouslySetInnerHTML", - "defaultValue", - "defaultChecked", - "innerHTML", - "suppressContentEditableWarning", - "suppressHydrationWarning", - "style" - ]; - reservedProps.forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - RESERVED, - false, - name, - null, - false, - false - ); - }); - [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { - var name = _ref[0], attributeName = _ref[1]; - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - attributeName, - null, - false, - false - ); - }); - ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEANISH_STRING, - false, - name.toLowerCase(), - null, - false, - false - ); - }); - ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEANISH_STRING, - false, - name, - null, - false, - false - ); - }); - [ - "allowFullScreen", - "async", - "autoFocus", - "autoPlay", - "controls", - "default", - "defer", - "disabled", - "disablePictureInPicture", - "disableRemotePlayback", - "formNoValidate", - "hidden", - "loop", - "noModule", - "noValidate", - "open", - "playsInline", - "readOnly", - "required", - "reversed", - "scoped", - "seamless", - "itemScope" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEAN, - false, - name.toLowerCase(), - null, - false, - false - ); - }); - [ - "checked", - "multiple", - "muted", - "selected" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEAN, - true, - name, - null, - false, - false - ); - }); - [ - "capture", - "download" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - OVERLOADED_BOOLEAN, - false, - name, - null, - false, - false - ); - }); - [ - "cols", - "rows", - "size", - "span" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - POSITIVE_NUMERIC, - false, - name, - null, - false, - false - ); - }); - ["rowSpan", "start"].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - NUMERIC, - false, - name.toLowerCase(), - null, - false, - false - ); - }); - var CAMELIZE = /[\-\:]([a-z])/g; - var capitalize = function(token) { - return token[1].toUpperCase(); - }; - [ - "accent-height", - "alignment-baseline", - "arabic-form", - "baseline-shift", - "cap-height", - "clip-path", - "clip-rule", - "color-interpolation", - "color-interpolation-filters", - "color-profile", - "color-rendering", - "dominant-baseline", - "enable-background", - "fill-opacity", - "fill-rule", - "flood-color", - "flood-opacity", - "font-family", - "font-size", - "font-size-adjust", - "font-stretch", - "font-style", - "font-variant", - "font-weight", - "glyph-name", - "glyph-orientation-horizontal", - "glyph-orientation-vertical", - "horiz-adv-x", - "horiz-origin-x", - "image-rendering", - "letter-spacing", - "lighting-color", - "marker-end", - "marker-mid", - "marker-start", - "overline-position", - "overline-thickness", - "paint-order", - "panose-1", - "pointer-events", - "rendering-intent", - "shape-rendering", - "stop-color", - "stop-opacity", - "strikethrough-position", - "strikethrough-thickness", - "stroke-dasharray", - "stroke-dashoffset", - "stroke-linecap", - "stroke-linejoin", - "stroke-miterlimit", - "stroke-opacity", - "stroke-width", - "text-anchor", - "text-decoration", - "text-rendering", - "underline-position", - "underline-thickness", - "unicode-bidi", - "unicode-range", - "units-per-em", - "v-alphabetic", - "v-hanging", - "v-ideographic", - "v-mathematical", - "vector-effect", - "vert-adv-y", - "vert-origin-x", - "vert-origin-y", - "word-spacing", - "writing-mode", - "xmlns:xlink", - "x-height" - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - attributeName, - null, - false, - false - ); - }); - [ - "xlink:actuate", - "xlink:arcrole", - "xlink:role", - "xlink:show", - "xlink:title", - "xlink:type" - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - attributeName, - "http://www.w3.org/1999/xlink", - false, - false - ); - }); - [ - "xml:base", - "xml:lang", - "xml:space" - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - attributeName, - "http://www.w3.org/XML/1998/namespace", - false, - false - ); - }); - ["tabIndex", "crossOrigin"].forEach(function(attributeName) { - properties[attributeName] = new PropertyInfoRecord( - attributeName, - STRING, - false, - attributeName.toLowerCase(), - null, - false, - false - ); - }); - var xlinkHref = "xlinkHref"; - properties[xlinkHref] = new PropertyInfoRecord( - "xlinkHref", - STRING, - false, - "xlink:href", - "http://www.w3.org/1999/xlink", - true, - false - ); - ["src", "href", "action", "formAction"].forEach(function(attributeName) { - properties[attributeName] = new PropertyInfoRecord( - attributeName, - STRING, - false, - attributeName.toLowerCase(), - null, - true, - true - ); - }); - var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; - var didWarn = false; - function sanitizeURL(url) { - { - if (!didWarn && isJavaScriptProtocol.test(url)) { - didWarn = true; - error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); - } - } - } - function getValueForProperty(node, name, expected, propertyInfo) { - { - if (propertyInfo.mustUseProperty) { - var propertyName = propertyInfo.propertyName; - return node[propertyName]; - } else { - if (propertyInfo.sanitizeURL) { - sanitizeURL("" + expected); - } - var attributeName = propertyInfo.attributeName; - var stringValue = null; - if (propertyInfo.type === OVERLOADED_BOOLEAN) { - if (node.hasAttribute(attributeName)) { - var value = node.getAttribute(attributeName); - if (value === "") { - return true; - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return value; - } - if (value === "" + expected) { - return expected; - } - return value; - } - } else if (node.hasAttribute(attributeName)) { - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return node.getAttribute(attributeName); - } - if (propertyInfo.type === BOOLEAN) { - return expected; - } - stringValue = node.getAttribute(attributeName); - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return stringValue === null ? expected : stringValue; - } else if (stringValue === "" + expected) { - return expected; - } else { - return stringValue; - } - } - } - } - function getValueForAttribute(node, name, expected) { - { - if (!isAttributeNameSafe(name)) { - return; - } - if (isOpaqueHydratingObject(expected)) { - return expected; - } - if (!node.hasAttribute(name)) { - return expected === void 0 ? void 0 : null; - } - var value = node.getAttribute(name); - if (value === "" + expected) { - return expected; - } - return value; - } - } - function setValueForProperty(node, name, value, isCustomComponentTag) { - var propertyInfo = getPropertyInfo(name); - if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { - return; - } - if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { - value = null; - } - if (isCustomComponentTag || propertyInfo === null) { - if (isAttributeNameSafe(name)) { - var _attributeName = name; - if (value === null) { - node.removeAttribute(_attributeName); - } else { - node.setAttribute(_attributeName, "" + value); - } - } - return; - } - var mustUseProperty = propertyInfo.mustUseProperty; - if (mustUseProperty) { - var propertyName = propertyInfo.propertyName; - if (value === null) { - var type = propertyInfo.type; - node[propertyName] = type === BOOLEAN ? false : ""; - } else { - node[propertyName] = value; - } - return; - } - var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; - if (value === null) { - node.removeAttribute(attributeName); - } else { - var _type = propertyInfo.type; - var attributeValue; - if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { - attributeValue = ""; - } else { - { - attributeValue = "" + value; - } - if (propertyInfo.sanitizeURL) { - sanitizeURL(attributeValue.toString()); - } - } - if (attributeNamespace) { - node.setAttributeNS(attributeNamespace, attributeName, attributeValue); - } else { - node.setAttribute(attributeName, attributeValue); - } - } - } - var REACT_ELEMENT_TYPE = 60103; - var REACT_PORTAL_TYPE = 60106; - var REACT_FRAGMENT_TYPE = 60107; - var REACT_STRICT_MODE_TYPE = 60108; - var REACT_PROFILER_TYPE = 60114; - var REACT_PROVIDER_TYPE = 60109; - var REACT_CONTEXT_TYPE = 60110; - var REACT_FORWARD_REF_TYPE = 60112; - var REACT_SUSPENSE_TYPE = 60113; - var REACT_SUSPENSE_LIST_TYPE = 60120; - var REACT_MEMO_TYPE = 60115; - var REACT_LAZY_TYPE = 60116; - var REACT_BLOCK_TYPE = 60121; - var REACT_SERVER_BLOCK_TYPE = 60122; - var REACT_FUNDAMENTAL_TYPE = 60117; - var REACT_SCOPE_TYPE = 60119; - var REACT_OPAQUE_ID_TYPE = 60128; - var REACT_DEBUG_TRACING_MODE_TYPE = 60129; - var REACT_OFFSCREEN_TYPE = 60130; - var REACT_LEGACY_HIDDEN_TYPE = 60131; - if (typeof Symbol === "function" && Symbol.for) { - var symbolFor = Symbol.for; - REACT_ELEMENT_TYPE = symbolFor("react.element"); - REACT_PORTAL_TYPE = symbolFor("react.portal"); - REACT_FRAGMENT_TYPE = symbolFor("react.fragment"); - REACT_STRICT_MODE_TYPE = symbolFor("react.strict_mode"); - REACT_PROFILER_TYPE = symbolFor("react.profiler"); - REACT_PROVIDER_TYPE = symbolFor("react.provider"); - REACT_CONTEXT_TYPE = symbolFor("react.context"); - REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref"); - REACT_SUSPENSE_TYPE = symbolFor("react.suspense"); - REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list"); - REACT_MEMO_TYPE = symbolFor("react.memo"); - REACT_LAZY_TYPE = symbolFor("react.lazy"); - REACT_BLOCK_TYPE = symbolFor("react.block"); - REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block"); - REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental"); - REACT_SCOPE_TYPE = symbolFor("react.scope"); - REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id"); - REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode"); - REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen"); - REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden"); - } - var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: _assign({}, props, { - value: prevLog - }), - info: _assign({}, props, { - value: prevInfo - }), - warn: _assign({}, props, { - value: prevWarn - }), - error: _assign({}, props, { - value: prevError - }), - group: _assign({}, props, { - value: prevGroup - }), - groupCollapsed: _assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: _assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - c--; - } - for (; s >= 1 && c >= 0; s--, c--) { - if (sampleLines[s] !== controlLines[c]) { - if (s !== 1 || c !== 1) { - do { - s--; - c--; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_BLOCK_TYPE: - return describeFunctionComponentFrame(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) { - } - } - } - } - return ""; - } - function describeFiber(fiber) { - var owner = fiber._debugOwner ? fiber._debugOwner.type : null; - var source = fiber._debugSource; - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - case LazyComponent: - return describeBuiltInComponentFrame("Lazy"); - case SuspenseComponent: - return describeBuiltInComponentFrame("Suspense"); - case SuspenseListComponent: - return describeBuiltInComponentFrame("SuspenseList"); - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - case Block: - return describeFunctionComponentFrame(fiber.type._render); - case ClassComponent: - return describeClassComponentFrame(fiber.type); - default: - return ""; - } - } - function getStackByFiberInDevAndProd(workInProgress2) { - try { - var info = ""; - var node = workInProgress2; - do { - info += describeFiber(node); - node = node.return; - } while (node); - return info; - } catch (x) { - return "\nError generating stack: " + x.message + "\n" + x.stack; - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentName(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - 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"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - return getComponentName(type.type); - case REACT_BLOCK_TYPE: - return getComponentName(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentName(init(payload)); - } catch (x) { - return null; - } - } - } - } - return null; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - var owner = current._debugOwner; - if (owner !== null && typeof owner !== "undefined") { - return getComponentName(owner.type); - } - } - return null; - } - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ""; - } - return getStackByFiberInDevAndProd(current); - } - } - function resetCurrentFiber() { - { - ReactDebugCurrentFrame.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - function getIsRendering() { - { - return isRendering; - } - } - function toString(value) { - return "" + value; - } - function getToStringValue(value) { - switch (typeof value) { - case "boolean": - case "number": - case "object": - case "string": - case "undefined": - return value; - default: - return ""; - } - } - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true - }; - function checkControlledValueProps(tagName, props) { - { - if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { - error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); - } - if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { - error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); - } - } - } - function isCheckable(elem) { - var type = elem.type; - var nodeName = elem.nodeName; - return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio"); - } - function getTracker(node) { - return node._valueTracker; - } - function detachTracker(node) { - node._valueTracker = null; - } - function getValueFromNode(node) { - var value = ""; - if (!node) { - return value; - } - if (isCheckable(node)) { - value = node.checked ? "true" : "false"; - } else { - value = node.value; - } - return value; - } - function trackValueOnNode(node) { - var valueField = isCheckable(node) ? "checked" : "value"; - var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); - var currentValue = "" + node[valueField]; - if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { - return; - } - var get2 = descriptor.get, set2 = descriptor.set; - Object.defineProperty(node, valueField, { - configurable: true, - get: function() { - return get2.call(this); - }, - set: function(value) { - currentValue = "" + value; - set2.call(this, value); - } - }); - Object.defineProperty(node, valueField, { - enumerable: descriptor.enumerable - }); - var tracker = { - getValue: function() { - return currentValue; - }, - setValue: function(value) { - currentValue = "" + value; - }, - stopTracking: function() { - detachTracker(node); - delete node[valueField]; - } - }; - return tracker; - } - function track(node) { - if (getTracker(node)) { - return; - } - node._valueTracker = trackValueOnNode(node); - } - function updateValueIfChanged(node) { - if (!node) { - return false; - } - var tracker = getTracker(node); - if (!tracker) { - return true; - } - var lastValue = tracker.getValue(); - var nextValue = getValueFromNode(node); - if (nextValue !== lastValue) { - tracker.setValue(nextValue); - return true; - } - return false; - } - function getActiveElement(doc) { - doc = doc || (typeof document !== "undefined" ? document : void 0); - if (typeof doc === "undefined") { - return null; - } - try { - return doc.activeElement || doc.body; - } catch (e) { - return doc.body; - } - } - var didWarnValueDefaultValue = false; - var didWarnCheckedDefaultChecked = false; - var didWarnControlledToUncontrolled = false; - var didWarnUncontrolledToControlled = false; - function isControlled(props) { - var usesChecked = props.type === "checkbox" || props.type === "radio"; - return usesChecked ? props.checked != null : props.value != null; - } - function getHostProps(element, props) { - var node = element; - var checked = props.checked; - var hostProps = _assign({}, props, { - defaultChecked: void 0, - defaultValue: void 0, - value: void 0, - checked: checked != null ? checked : node._wrapperState.initialChecked - }); - return hostProps; - } - function initWrapperState(element, props) { - { - checkControlledValueProps("input", props); - if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) { - error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnCheckedDefaultChecked = true; - } - if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) { - error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnValueDefaultValue = true; - } - } - var node = element; - var defaultValue = props.defaultValue == null ? "" : props.defaultValue; - node._wrapperState = { - initialChecked: props.checked != null ? props.checked : props.defaultChecked, - initialValue: getToStringValue(props.value != null ? props.value : defaultValue), - controlled: isControlled(props) - }; - } - function updateChecked(element, props) { - var node = element; - var checked = props.checked; - if (checked != null) { - setValueForProperty(node, "checked", checked, false); - } - } - function updateWrapper(element, props) { - var node = element; - { - var controlled = isControlled(props); - if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { - error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnUncontrolledToControlled = true; - } - if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { - error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnControlledToUncontrolled = true; - } - } - updateChecked(element, props); - var value = getToStringValue(props.value); - var type = props.type; - if (value != null) { - if (type === "number") { - if (value === 0 && node.value === "" || node.value != value) { - node.value = toString(value); - } - } else if (node.value !== toString(value)) { - node.value = toString(value); - } - } else if (type === "submit" || type === "reset") { - node.removeAttribute("value"); - return; - } - { - if (props.hasOwnProperty("value")) { - setDefaultValue(node, props.type, value); - } else if (props.hasOwnProperty("defaultValue")) { - setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); - } - } - { - if (props.checked == null && props.defaultChecked != null) { - node.defaultChecked = !!props.defaultChecked; - } - } - } - function postMountWrapper(element, props, isHydrating2) { - var node = element; - if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { - var type = props.type; - var isButton = type === "submit" || type === "reset"; - if (isButton && (props.value === void 0 || props.value === null)) { - return; - } - var initialValue = toString(node._wrapperState.initialValue); - if (!isHydrating2) { - { - if (initialValue !== node.value) { - node.value = initialValue; - } - } - } - { - node.defaultValue = initialValue; - } - } - var name = node.name; - if (name !== "") { - node.name = ""; - } - { - node.defaultChecked = !node.defaultChecked; - node.defaultChecked = !!node._wrapperState.initialChecked; - } - if (name !== "") { - node.name = name; - } - } - function restoreControlledState(element, props) { - var node = element; - updateWrapper(node, props); - updateNamedCousins(node, props); - } - function updateNamedCousins(rootNode, props) { - var name = props.name; - if (props.type === "radio" && name != null) { - var queryRoot = rootNode; - while (queryRoot.parentNode) { - queryRoot = queryRoot.parentNode; - } - var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'); - for (var i = 0; i < group.length; i++) { - var otherNode = group[i]; - if (otherNode === rootNode || otherNode.form !== rootNode.form) { - continue; - } - var otherProps = getFiberCurrentPropsFromNode(otherNode); - if (!otherProps) { - { - throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); - } - } - updateValueIfChanged(otherNode); - updateWrapper(otherNode, otherProps); - } - } - } - function setDefaultValue(node, type, value) { - if (type !== "number" || getActiveElement(node.ownerDocument) !== node) { - if (value == null) { - node.defaultValue = toString(node._wrapperState.initialValue); - } else if (node.defaultValue !== toString(value)) { - node.defaultValue = toString(value); - } - } - } - var didWarnSelectedSetOnOption = false; - var didWarnInvalidChild = false; - function flattenChildren(children) { - var content = ""; - React3.Children.forEach(children, function(child) { - if (child == null) { - return; - } - content += child; - }); - return content; - } - function validateProps(element, props) { - { - if (typeof props.children === "object" && props.children !== null) { - React3.Children.forEach(props.children, function(child) { - if (child == null) { - return; - } - if (typeof child === "string" || typeof child === "number") { - return; - } - if (typeof child.type !== "string") { - return; - } - if (!didWarnInvalidChild) { - didWarnInvalidChild = true; - error("Only strings and numbers are supported as