Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

18.7 KB
Raw Blame
// Generated by scripts/generate-mobile-settings-bootstrap.mjs. Edit pluginSettingsBootstrap.ts.
export const PLUGIN_SETTINGS_BOOTSTRAP = "function settingsBootstrap(config) {\n    const scope = window;\n    const nativeFetch = window.fetch.bind(window);\n    const quietConsole = Object.fromEntries([\n        \"log\",\n        \"info\",\n        \"debug\",\n        \"warn\",\n        \"error\",\n        \"assert\",\n        \"trace\",\n        \"table\",\n        \"dir\",\n        \"group\",\n        \"groupEnd\",\n        \"time\",\n        \"timeEnd\",\n        \"clear\",\n        \"count\",\n    ].map((name) => [name, () => { }]));\n    Object.defineProperty(window, \"console\", {\n        value: Object.freeze(quietConsole),\n    });\n    window.addEventListener(\"error\", (event) => event.preventDefault());\n    window.addEventListener(\"unhandledrejection\", (event) => event.preventDefault());\n    // The approved exception is transient input only. Never offer browser persistence or workers.\n    const blockedStorage = Object.freeze({\n        getItem: () => null,\n        key: () => null,\n        length: 0,\n        setItem: () => {\n            throw new DOMException(\"Settings storage disabled\", \"SecurityError\");\n        },\n        removeItem: () => { },\n        clear: () => { },\n    });\n    for (const name of [\"localStorage\", \"sessionStorage\"])\n        Object.defineProperty(window, name, { value: blockedStorage });\n    for (const name of [\n        \"indexedDB\",\n        \"caches\",\n        \"Worker\",\n        \"SharedWorker\",\n        \"RTCPeerConnection\",\n    ])\n        Object.defineProperty(window, name, { value: undefined });\n    Object.defineProperty(navigator, \"serviceWorker\", { value: undefined });\n    Object.defineProperty(navigator, \"credentials\", { value: undefined });\n    Object.defineProperty(navigator, \"clipboard\", { value: undefined });\n    navigator.sendBeacon = () => false;\n    const sensitiveValues = new Set();\n    const remember = (value) => {\n        if (typeof value !== \"string\" || !value)\n            return;\n        sensitiveValues.add(value);\n        if (sensitiveValues.size > 64)\n            sensitiveValues.delete(sensitiveValues.values().next().value);\n    };\n    const containsSensitiveInput = (data) => {\n        // Defense against accidental reuse of a credential form value in an old BC payload.\n        // Arbitrary encoded/custom BC credentials still violate the author contract and are unsupported.\n        document.querySelectorAll(\"input,textarea\").forEach((node) => {\n            const input = node;\n            if (input.type === \"password\" ||\n                /secret|token|api.?key|password/i.test(input.id + \" \" + input.name))\n                remember(input.value);\n        });\n        const json = JSON.stringify(data);\n        return [...sensitiveValues].some((value) => json.includes(JSON.stringify(value).slice(1, -1)));\n    };\n    const pending = new Map();\n    let sequence = 0, closed = false;\n    const send = (command, timeout = 30_000) => {\n        if (closed)\n            return Promise.reject(new Error(\"PLUGIN_SETTINGS_CLOSED\"));\n        return new Promise((resolve, reject) => {\n            const id = ++sequence;\n            const timer = setTimeout(() => {\n                pending.delete(id);\n                reject(new Error(\"PLUGIN_SETTINGS_RESULT_UNKNOWN\"));\n            }, timeout);\n            pending.set(id, { resolve, reject, timer });\n            try {\n                scope.ReactNativeWebView.postMessage(JSON.stringify({ settings: config.pageId, id, command }));\n            }\n            catch {\n                clearTimeout(timer);\n                pending.delete(id);\n                reject(new Error(\"PLUGIN_SETTINGS_UNAVAILABLE\"));\n            }\n        });\n    };\n    const channels = new Map();\n    let subscriptions = Promise.resolve();\n    scope.__cindySettingsReceive = (value) => {\n        if (closed)\n            return;\n        if (value.kind === \"reply\") {\n            const work = pending.get(value.id);\n            if (!work)\n                return;\n            clearTimeout(work.timer);\n            pending.delete(value.id);\n            if (value.ok)\n                work.resolve(value.value);\n            else\n                work.reject(new Error(\"PLUGIN_SETTINGS_REQUEST_FAILED\"));\n        }\n        else if (value.kind === \"events\") {\n            for (const event of value.events)\n                for (const channel of channels.get(event.channel) ?? [])\n                    channel.deliver(event.data);\n        }\n    };\n    scope.__cindySettingsTheme = (theme) => {\n        const root = document.documentElement;\n        root.classList.toggle(\"dark\", theme.dark);\n        root.dataset.theme = theme.dark ? \"dark\" : \"light\";\n        root.style.colorScheme = theme.dark ? \"dark\" : \"light\";\n        for (const [name, value] of Object.entries(theme.colors))\n            root.style.setProperty(\"--\" + name, value);\n        window.dispatchEvent(new Event(\"cindy-theme-change\"));\n    };\n    scope.__cindySettingsTheme(config.theme);\n    const urlFor = (input) => {\n        const url = new URL(input, location.href);\n        if (url.protocol === \"cindy-ghost:\" && url.hostname === config.manifestId)\n            return new URL(url.pathname + url.search + url.hash, location.origin);\n        if (url.origin !== location.origin)\n            throw new Error(\"PLUGIN_SETTINGS_NETWORK_BLOCKED\");\n        return url;\n    };\n    const api = (url) => /^\\/(kv|app-context|agent-models|media-models|secrets|oauth|connections|wake)(\\/|$)/.test(url.pathname);\n    window.fetch = async (input, init) => {\n        const request = input instanceof Request ? input : undefined;\n        const url = urlFor(request?.url ?? String(input));\n        const method = (init?.method ?? request?.method ?? \"GET\").toUpperCase();\n        if (!api(url)) {\n            if (method !== \"GET\" ||\n                !config.files.includes(decodeURIComponent(url.pathname.slice(1))))\n                throw new Error(\"PLUGIN_SETTINGS_NETWORK_BLOCKED\");\n            return nativeFetch(url.href, init);\n        }\n        const body = init?.body === undefined\n            ? request && method !== \"GET\"\n                ? await request.text()\n                : undefined\n            : init.body;\n        if (body !== undefined && body !== null && typeof body !== \"string\")\n            throw new TypeError(\"String settings body required\");\n        if (typeof body === \"string\" &&\n            /^(\\/secrets\\/|\\/connections\\/|\\/oauth\\/)/.test(url.pathname)) {\n            try {\n                const values = JSON.parse(body);\n                for (const [name, value] of Object.entries(values))\n                    if (url.pathname.startsWith(\"/secrets/\") ||\n                        /secret|token|password|api.?key/i.test(name))\n                        remember(value);\n            }\n            catch {\n                /* The original Host executor validates malformed JSON; it is never logged. */\n            }\n        }\n        const timeout = /^\\/oauth\\/[^/]+\\/connect$/.test(url.pathname)\n            ? 330_000\n            : url.pathname.startsWith(\"/connections/\") && method !== \"GET\"\n                ? 120_000\n                : 30_000;\n        const result = await send({\n            kind: \"fetch\",\n            path: url.pathname + url.search,\n            method,\n            ...(body == null ? {} : { body }),\n        }, timeout);\n        // Host settings executors return PluginPageFetchResult, including Base64 bytes.\n        const bytes = Uint8Array.from(atob(result.base64), (character) => character.charCodeAt(0));\n        return new Response([204, 205, 304].includes(result.status) ? null : bytes, {\n            status: result.status,\n            headers: { \"content-type\": result.mime },\n        });\n    };\n    class SettingsXHR extends EventTarget {\n        static UNSENT = 0;\n        static OPENED = 1;\n        static HEADERS_RECEIVED = 2;\n        static LOADING = 3;\n        static DONE = 4;\n        UNSENT = 0;\n        OPENED = 1;\n        HEADERS_RECEIVED = 2;\n        LOADING = 3;\n        DONE = 4;\n        readyState = 0;\n        status = 0;\n        statusText = \"\";\n        responseURL = \"\";\n        responseType = \"\";\n        response = null;\n        timeout = 0;\n        withCredentials = false;\n        upload = new EventTarget();\n        onreadystatechange = null;\n        onload = null;\n        onerror = null;\n        onabort = null;\n        onloadend = null;\n        onloadstart = null;\n        onprogress = null;\n        ontimeout = null;\n        text = \"\";\n        method = \"GET\";\n        url = \"\";\n        mime = \"\";\n        generation = 0;\n        sent = false;\n        get responseText() {\n            if (this.responseType && this.responseType !== \"text\")\n                throw new DOMException(\"Invalid response type\", \"InvalidStateError\");\n            return this.text;\n        }\n        get responseXML() {\n            return null;\n        }\n        emit(name) {\n            const event = new Event(name);\n            this[\"on\" + name]?.(event);\n            this.dispatchEvent(event);\n        }\n        state(value) {\n            this.readyState = value;\n            this.emit(\"readystatechange\");\n        }\n        open(method, url, async = true, username, password) {\n            if (!async || username || password)\n                throw new DOMException(\"Unsupported settings request\", \"NotSupportedError\");\n            this.generation++;\n            this.method = method.toUpperCase();\n            this.url = urlFor(String(url)).href;\n            this.status = 0;\n            this.text = \"\";\n            this.response = null;\n            this.mime = \"\";\n            this.sent = false;\n            this.state(1);\n        }\n        setRequestHeader(name, _value) {\n            if (this.readyState !== 1 ||\n                ![\"content-type\", \"accept\"].includes(name.toLowerCase()))\n                throw new DOMException(\"Unsupported settings header\", \"NotSupportedError\");\n        }\n        getResponseHeader(name) {\n            return this.readyState >= 2 && name.toLowerCase() === \"content-type\"\n                ? this.mime\n                : null;\n        }\n        getAllResponseHeaders() {\n            return this.readyState >= 2 ? \"content-type: \" + this.mime + \"\\r\\n\" : \"\";\n        }\n        overrideMimeType(mime) {\n            this.mime = mime;\n        }\n        send(body) {\n            if (this.readyState !== 1 || this.sent)\n                throw new DOMException(\"Request not opened\", \"InvalidStateError\");\n            this.sent = true;\n            const generation = this.generation;\n            const controller = new AbortController();\n            let timedOut = false;\n            const timer = this.timeout > 0\n                ? setTimeout(() => {\n                    if (generation !== this.generation)\n                        return;\n                    timedOut = true;\n                    controller.abort();\n                    this.generation++;\n                    this.status = 0;\n                    this.state(4);\n                    this.emit(\"timeout\");\n                    this.emit(\"loadend\");\n                }, this.timeout)\n                : undefined;\n            this.emit(\"loadstart\");\n            void window\n                .fetch(this.url, {\n                method: this.method,\n                ...(body == null ? {} : { body }),\n                signal: controller.signal,\n            })\n                .then(async (response) => {\n                if (generation !== this.generation)\n                    return;\n                this.status = response.status;\n                this.statusText = response.statusText;\n                this.responseURL = this.url;\n                this.mime ||= response.headers.get(\"content-type\") ?? \"\";\n                this.state(2);\n                this.state(3);\n                const bytes = await response.arrayBuffer();\n                if (generation !== this.generation)\n                    return;\n                const text = new TextDecoder().decode(bytes);\n                this.text = text;\n                this.response =\n                    this.responseType === \"json\"\n                        ? (() => {\n                            try {\n                                return JSON.parse(text);\n                            }\n                            catch {\n                                return null;\n                            }\n                        })()\n                        : this.responseType === \"arraybuffer\"\n                            ? bytes\n                            : this.responseType === \"blob\"\n                                ? new Blob([bytes], { type: this.mime })\n                                : text;\n                this.state(4);\n                this.emit(\"progress\");\n                this.emit(\"load\");\n                this.emit(\"loadend\");\n            })\n                .catch(() => {\n                if (generation !== this.generation || timedOut)\n                    return;\n                this.status = 0;\n                this.state(4);\n                this.emit(\"error\");\n                this.emit(\"loadend\");\n            })\n                .finally(() => clearTimeout(timer));\n        }\n        abort() {\n            this.generation++;\n            this.status = 0;\n            this.state(0);\n            this.emit(\"abort\");\n            this.emit(\"loadend\");\n        }\n    }\n    scope.XMLHttpRequest = SettingsXHR;\n    class RemoteChannel extends EventTarget {\n        name;\n        onmessage = null;\n        onmessageerror = null;\n        closed = false;\n        constructor(name) {\n            super();\n            this.name = String(name);\n            if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(this.name))\n                throw new TypeError(\"Invalid channel\");\n            const group = channels.get(this.name) ?? new Set();\n            group.add(this);\n            channels.set(this.name, group);\n            subscriptions = subscriptions\n                .catch(() => { })\n                .then(() => send({ kind: \"subscribe\", channels: [this.name] }));\n            void subscriptions.catch(() => this.error());\n        }\n        postMessage(data) {\n            if (this.closed)\n                throw new DOMException(\"Channel closed\", \"InvalidStateError\");\n            const copy = JSON.parse(JSON.stringify(data));\n            if (containsSensitiveInput(copy))\n                throw new DOMException(\"Credential values cannot use BroadcastChannel\", \"SecurityError\");\n            void subscriptions\n                .then(() => send({ kind: \"post\", channel: this.name, data: copy }))\n                .catch(() => this.error());\n        }\n        close() {\n            if (this.closed)\n                return;\n            this.closed = true;\n            const group = channels.get(this.name);\n            group?.delete(this);\n            if (!group?.size) {\n                channels.delete(this.name);\n                subscriptions = subscriptions\n                    .catch(() => { })\n                    .then(() => send({ kind: \"unsubscribe\", channel: this.name }));\n                void subscriptions.catch(() => { });\n            }\n        }\n        deliver(data) {\n            if (!this.closed) {\n                const event = new MessageEvent(\"message\", { data });\n                this.onmessage?.(event);\n                this.dispatchEvent(event);\n            }\n        }\n        error() {\n            if (!this.closed) {\n                const event = new MessageEvent(\"messageerror\");\n                this.onmessageerror?.(event);\n                this.dispatchEvent(event);\n            }\n        }\n    }\n    scope.BroadcastChannel = RemoteChannel;\n    let resizeObserver;\n    let controlObserver;\n    const adaptControlFonts = (root) => {\n        const adapt = (control) => {\n            if (control instanceof HTMLInputElement &&\n                ![\n                    \"text\",\n                    \"password\",\n                    \"email\",\n                    \"number\",\n                    \"search\",\n                    \"tel\",\n                    \"url\",\n                ].includes(control.type))\n                return;\n            // Small editable text triggers iOS focus zoom; preserve larger author typography.\n            if (parseFloat(window.getComputedStyle(control).fontSize) < 16)\n                control.style.fontSize = \"16px\";\n        };\n        if (root.matches(\"input,textarea,select\"))\n            adapt(root);\n        root.querySelectorAll(\"input,textarea,select\").forEach(adapt);\n    };\n    const adaptControls = () => {\n        if (closed)\n            return;\n        adaptControlFonts(document.documentElement);\n        controlObserver = new MutationObserver((records) => {\n            if (closed)\n                return;\n            for (const record of records)\n                for (const node of record.addedNodes)\n                    if (node instanceof Element)\n                        adaptControlFonts(node);\n        });\n        controlObserver.observe(document.documentElement, {\n            childList: true,\n            subtree: true,\n        });\n    };\n    if (document.readyState === \"loading\")\n        document.addEventListener(\"DOMContentLoaded\", adaptControls, {\n            once: true,\n        });\n    else\n        adaptControls();\n    window.addEventListener(\"pagehide\", () => {\n        closed = true;\n        for (const work of pending.values()) {\n            clearTimeout(work.timer);\n            work.reject(new Error(\"PLUGIN_SETTINGS_CLOSED\"));\n        }\n        pending.clear();\n        channels.clear();\n        sensitiveValues.clear();\n        resizeObserver?.disconnect();\n        controlObserver?.disconnect();\n        document.removeEventListener(\"DOMContentLoaded\", adaptControls);\n        window.name = \"\";\n        document.querySelectorAll(\"input,textarea\").forEach((input) => {\n            input.value = \"\";\n        });\n    }, { once: true });\n    const resize = () => {\n        if (!closed)\n            scope.ReactNativeWebView.postMessage(JSON.stringify({\n                settings: config.pageId,\n                height: Math.ceil(document.body?.scrollHeight ??\n                    document.documentElement.scrollHeight),\n            }));\n    };\n    window.addEventListener(\"load\", resize);\n    if (typeof ResizeObserver !== \"undefined\") {\n        resizeObserver = new ResizeObserver(resize);\n        resizeObserver.observe(document.documentElement);\n    }\n}\n";