diff --git a/README.md b/README.md index a085538a..caa79274 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [GitHub Star Shelf](plugins/start3208/github-star-shelf/) | Turn your GitHub stars into collections you can search and ask the AI to explain in plain language: from the README alone, or after it has read a shallow clone of the code. One session per project, your own notes, and collections the Agent can arrange | [start3208](https://github.com/start3208) | | [Plugin Listing Workbench](plugins/zhuyankarl/submission-workbench/) | Prepare a plugin submission: fill in the manifest and listing fields, check every required field and cross-file consistency, then download a reviewable listing package that names what is missing; a bundled Skill gives the Agent the same checklist | [zhuyankarl](https://github.com/zhuyankarl) | | [WeChat Article Studio](plugins/xiaobinger/wechat-mp-article-studio/) | Plan a WeChat Official Account article: cover and illustration slots rendered as real images, a duplication check against your previous piece, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing stays blocked until account authorisation, material access and a publish interface are confirmed; with no interface connected it only ever saves a draft. Requires MiniMax Code 3.1.6 or later | [xiaobinger](https://github.com/xiaobinger) | +| [Daily News Briefing](plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/) | A daily briefing page: news from overseas and independent outlets with Chinese-mainland official media filtered out, plus on-this-day history, people of the day and a picture of the day from Chinese Wikipedia; it refreshes every hour and marks what is new. Requires MiniMax Code 3.1.20 or later | [llsktsl-debug](https://github.com/llsktsl-debug) |
Preview: Weekly Planner diff --git a/README.zh-CN.md b/README.zh-CN.md index 79d64bff..68c11394 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -102,6 +102,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [GitHub 收藏夹](plugins/start3208/github-star-shelf/README.zh-CN.md) | 把 GitHub Star 分进收藏夹,按名称、README 和备注搜索;让 AI 用大白话讲清每个项目:只看 README 讲,或读一遍浅克隆的代码再讲。一个项目一个会话,可以写备注,也能让 Agent 整理收藏夹 | [start3208](https://github.com/start3208) | | [插件上架材料工作台](plugins/zhuyankarl/submission-workbench/README.zh-CN.md) | 填写插件清单与上架信息,逐项核对必填字段与内容一致性,生成可审核的上架材料包并标出缺失项;内置 Skill 让 Agent 拿到同一套检查清单 | [zhuyankarl](https://github.com/zhuyankarl) | | [公众号图文工作台](plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md) | 输入主题、正文、封面与插图需求,选一个视觉风格,产出封面与插图方案、与上一篇的查重结论、带版本和发布状态的草稿箱,以及可以直接粘贴进公众号的内联样式 HTML;发布前必须确认账号授权、素材范围与可用发布接口,没接接口时只存草稿。需要 MiniMax Code 3.1.6 或更高版本 | [xiaobinger](https://github.com/xiaobinger) | +| [每日新闻简报](plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.zh-CN.md) | 每日简报页:汇总境外与独立媒体报道并排除中国大陆官方媒体,另附中文维基百科的历史上的今天、每日人物与每日一图;每小时自动刷新并标出新条目。需要 MiniMax Code 3.1.20 或更高版本 | [llsktsl-debug](https://github.com/llsktsl-debug) |
预览:周计划 diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/.minimax-plugin/plugin.json b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/.minimax-plugin/plugin.json new file mode 100644 index 00000000..178acdd9 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "miniapp-52d26296-e0f9-462a-ab2f-e917d2508233", + "displayName": "每日新闻简报", + "version": "1.0.0", + "description": "每日新闻简报:汇总境外与独立媒体报道(排除中国大陆官方媒体),并附历史上的今天、每日人物与每日一图,内容来自中文维基百科。", + "author": "llsktsl-debug", + "icon": "icon.png", + "category": "Other", + "exampleQueries": [ + "打开每日新闻简报", + "今天有哪些境外媒体报道?", + "看看历史上的今天和每日人物" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/LICENSE b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/LICENSE new file mode 100644 index 00000000..8b1e9a83 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 llsktsl-debug + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.md b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.md new file mode 100644 index 00000000..c1295908 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.md @@ -0,0 +1,80 @@ +# Daily News Briefing (`miniapp-52d26296-e0f9-462a-ab2f-e917d2508233`) + +English | [简体中文](README.zh-CN.md) + +A daily briefing page for MiniMax Code. It collects news from overseas and independent outlets, leaves out +Chinese-mainland official media, and adds "on this day in history", "people of the day" and a "picture of the +day" from Chinese Wikipedia. The page refreshes itself every hour and marks what is new since you last looked. + +## What it shows + +- **Today's news** — headlines from six feeds: BBC 中文, 德国之声 (DW), 法广 RFI, 中央社, 纽约时报中文网 and a + Google News aggregation. Items published by Chinese-mainland official media are removed (a list of central + and local official outlets, their domains, a `XX日报` pattern and every `.gov.cn` host), duplicates are + merged, and the rest is sorted by time. The status bar shows how many items were filtered, and a details + panel names the outlets that were blocked. +- **On this day in history** — the events and holidays on today's date page of Chinese Wikipedia. +- **People of the day** — the featured article, plus the people born and the people who died on this date, + each with a short extract and a thumbnail, newest year first. +- **Picture of the day** — the image Wikipedia features for today. + +The page also has keyword search, source filters, a theme switch (system / light / dark), keyboard tab +navigation, and a button that marks new items as read. + +## Install + +Copy this directory, including the hidden `.minimax-plugin/`, into the MiniMax Code plugins directory as +`miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/` (`~/.minimax/plugins/` by default; the root README's Install +section explains where that directory is). Restart MiniMax Code and ask the Agent to "打开每日新闻简报". + +## Use + +The page opens on the 今日要闻 tab. Items that arrived since your last visit carry a 新 badge, and a banner at +the top says how many there are; 标为已读 clears them. The page refreshes every hour, and also when the day +changes or the stored data is stale; a countdown shows when the next refresh is due, and 刷新 fetches now. +If one feed fails, the page says so and keeps the rest. + +## Tested environment + +- MiniMax Code 3.1.23 on Windows 10.0.26300 x64. Installed from this directory, opened through the Agent, and + checked in the side panel: all four tabs, keyword search, source filters, the empty state, light and dark + themes, keyboard tab navigation, manual refresh, the new-item banner, read state surviving a reload, and view + state restored after reopening. +- Requires MiniMax Code 3.1.20 or later, because the manifest declares `engines.mcode`. +- Not tested: macOS, and MiniMax Code versions other than 3.1.23. + +## Data & access + +- Files: reads only its own `miniapp/` payload. Writes `briefing-state.json` (the last snapshot and the read + state) under the plugin's `context.dataDir`, replacing it atomically. Writes nothing else. +- Browser storage: `localStorage` keeps view preferences (active tab, filters, search text, theme). +- Network: GET requests only, to `feeds.bbci.co.uk`, `rss.dw.com`, `www.rfi.fr`, `feeds.feedburner.com`, + `cn.nytimes.com`, `news.google.com` and `zh.wikipedia.org`; the page loads thumbnails and the picture of + the day from `upload.wikimedia.org`. No account, no credentials, and nothing is sent anywhere else. +- Processes: none. +- Agent turns, conversations and tools: none. The Mini App declares no `permissions`. +- Microphone, camera and notifications: not used. New items are announced inside the page only. +- File extensions opened: none. It does not read which MiniMax Code page you are on; it reads the Host theme. + +## Files + +```text +.minimax-plugin/plugin.json Plugin manifest +package.json Mini App declaration +miniapp/miniapp.json Payload roots, Node entry, page route, window size +miniapp/client/index.html The page served at /briefing +miniapp/client/app.js Tabs, search, filters, refresh timer, read state +miniapp/client/styles.css Layout and the light and dark themes +miniapp/node/server.mjs Node entry: start(context) -> { dispose }, routes, hourly refresh +miniapp/node/news.mjs RSS parsing, the official-media filter, dedupe, sorting +miniapp/node/sources.mjs The six feeds and the block lists +miniapp/node/wiki.mjs Chinese Wikipedia: date page, featured feed, people +miniapp/node/store.mjs Snapshot persistence under context.dataDir +miniapp/node/http.mjs Small fetch helper with a timeout and retries +miniapp/node/miniapp-api.ts Type declarations for the runtime context; not loaded at runtime +icon.png Plugin icon +``` + +## License + +[MIT](./LICENSE) diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.zh-CN.md b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.zh-CN.md new file mode 100644 index 00000000..601c3c6c --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/README.zh-CN.md @@ -0,0 +1,69 @@ +# 每日新闻简报(`miniapp-52d26296-e0f9-462a-ab2f-e917d2508233`) + +[English](README.md) | 简体中文 + +给 MiniMax Code 用的每日简报页:汇总境外与独立媒体的报道,排除中国大陆官方媒体,并附上来自中文维基百科的 +「历史上的今天」「每日人物」和「每日一图」。页面每小时自动刷新,并标出你上次查看之后新增的条目。 + +## 页面内容 + +- **今日要闻** —— 六个新闻源的标题:BBC 中文、德国之声、法广 RFI、中央社、纽约时报中文网,以及 Google 新闻聚合。 + 中国大陆官方媒体发布的条目会被剔除(依据中央与地方官方媒体名单、其域名、`XX日报` 形式和所有 `.gov.cn` 域名), + 重复条目合并,其余按时间排序。状态栏显示被过滤的条数,展开后可以看到被屏蔽的媒体名单。 +- **历史上的今天** —— 中文维基百科当天日期页上的事件与节日。 +- **每日人物** —— 特色条目,加上当天出生和当天逝世的人物,各带一段简介和缩略图,按年份从近到远排列。 +- **每日一图** —— 维基百科当天的特色图片。 + +页面还支持关键词搜索、按来源筛选、主题切换(跟随系统 / 浅色 / 深色)、键盘切换标签页,以及把新条目标为已读。 + +## 安装 + +把本目录(含隐藏的 `.minimax-plugin/`)复制到 MiniMax Code 的插件目录,目录名为 +`miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/`(默认是 `~/.minimax/plugins/`,根 README 的安装一节说明了该目录的位置)。 +重启 MiniMax Code,然后让 Agent「打开每日新闻简报」。 + +## 使用 + +页面打开后停在「今日要闻」。上次查看之后新增的条目会带「新」标记,顶部横幅显示新增数量,点「标为已读」即可清除。 +页面每小时刷新一次,日期变化或本地数据过期时也会刷新;倒计时显示下次刷新时间,点「刷新」立即抓取。 +某个新闻源失败时,页面会提示,其余内容照常显示。 + +## Tested environment + +- MiniMax Code 3.1.23,Windows 10.0.26300 x64。从本目录安装,通过 Agent 打开,并在侧边栏中核对:四个标签页、 + 关键词搜索、来源筛选、空状态、浅色与深色主题、键盘切换标签页、手动刷新、新条目横幅、刷新后已读状态仍在、重新打开后视图状态恢复。 +- 需要 MiniMax Code 3.1.20 或更高版本,因为清单声明了 `engines.mcode`。 +- 未测试:macOS,以及 3.1.23 以外的 MiniMax Code 版本。 + +## Data & access + +- 文件:只读取自身的 `miniapp/` 载荷。向插件的 `context.dataDir` 写入 `briefing-state.json`(最近一次快照与已读状态),采用原子替换。除此之外不写任何文件。 +- 浏览器存储:`localStorage` 保存视图偏好(当前标签页、筛选条件、搜索词、主题)。 +- 网络:只发 GET 请求,目标为 `feeds.bbci.co.uk`、`rss.dw.com`、`www.rfi.fr`、`feeds.feedburner.com`、`cn.nytimes.com`、`news.google.com` 和 `zh.wikipedia.org`;页面从 `upload.wikimedia.org` 加载缩略图和每日一图。不需要账号或凭据,也不会向别处发送数据。 +- 进程:无。 +- Agent 轮次、会话与工具:无。本 Mini App 未声明任何 `permissions`。 +- 麦克风、摄像头与通知:均不使用,新条目只在页面内提示。 +- 打开的文件扩展名:无。不读取你当前所在的 MiniMax Code 页面,只读取宿主主题。 + +## 文件 + +```text +.minimax-plugin/plugin.json 插件清单 +package.json Mini App 声明 +miniapp/miniapp.json 载荷根目录、Node 入口、页面路由、窗口尺寸 +miniapp/client/index.html /briefing 路由提供的页面 +miniapp/client/app.js 标签页、搜索、筛选、刷新计时、已读状态 +miniapp/client/styles.css 布局与浅色、深色主题 +miniapp/node/server.mjs Node 入口:start(context) -> { dispose }、路由、每小时刷新 +miniapp/node/news.mjs RSS 解析、官媒过滤、去重、排序 +miniapp/node/sources.mjs 六个新闻源与屏蔽名单 +miniapp/node/wiki.mjs 中文维基百科:日期页、特色 feed、人物 +miniapp/node/store.mjs 快照持久化到 context.dataDir +miniapp/node/http.mjs 带超时与重试的抓取小工具 +miniapp/node/miniapp-api.ts 运行时上下文的类型声明;运行时不加载 +icon.png 插件图标 +``` + +## 许可 + +[MIT](./LICENSE) diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/icon.png b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/icon.png differ diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/app.js b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/app.js new file mode 100644 index 00000000..b9f42c55 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/app.js @@ -0,0 +1,867 @@ +(function () { + 'use strict'; + + var VIEW_KEY = 'daily-briefing-view'; + var TABS = ['news', 'history', 'people', 'image']; + var NEWS_STEP = 30; + var HISTORY_INITIAL = 15; + var PEOPLE_INITIAL = 8; + var THEME_LABELS = { system: '主题:跟随系统', light: '主题:浅色', dark: '主题:深色' }; + + var state = { + data: null, + loading: true, + refreshing: false, + error: null, + view: { + tab: 'news', + source: 'all', + query: '', + theme: 'system', + newsLimit: NEWS_STEP, + historyExpanded: false, + birthsExpanded: false, + deathsExpanded: false + } + }; + + var timers = { refresh: null, countdown: null, query: null }; + var hostTheme = null; + var mediaQuery = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null; + + /* ---------- 基础工具 ---------- */ + + function el(tag, attrs, children) { + var node = document.createElement(tag); + if (attrs) { + Object.keys(attrs).forEach(function (key) { + var value = attrs[key]; + if (value === null || value === undefined || value === false) return; + if (key === 'class') node.className = value; + else if (key === 'text') node.textContent = value; + else if (key === 'hidden') node.hidden = Boolean(value); + else node.setAttribute(key, value === true ? '' : String(value)); + }); + } + appendChildren(node, children); + return node; + } + + function appendChildren(node, children) { + if (children === null || children === undefined || children === false) return; + if (Array.isArray(children)) { + children.forEach(function (child) { + appendChildren(node, child); + }); + return; + } + if (children instanceof Node) { + node.appendChild(children); + return; + } + node.appendChild(document.createTextNode(String(children))); + } + + function clear(node) { + while (node.firstChild) node.removeChild(node.firstChild); + } + + function pad(value) { + return String(value).padStart(2, '0'); + } + + function formatClock(iso) { + if (!iso) return '--:--'; + var date = new Date(iso); + if (isNaN(date.getTime())) return '--:--'; + return pad(date.getHours()) + ':' + pad(date.getMinutes()); + } + + function formatDate(iso) { + var date = new Date(iso); + if (isNaN(date.getTime())) return ''; + return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()); + } + + function formatRelative(iso) { + if (!iso) return '时间未知'; + var time = Date.parse(iso); + if (!isFinite(time)) return '时间未知'; + var diff = Date.now() - time; + if (diff < 0) return '刚刚'; + if (diff < 60000) return '刚刚'; + var minutes = Math.floor(diff / 60000); + if (minutes < 60) return minutes + ' 分钟前'; + var hours = Math.floor(minutes / 60); + if (hours < 24) return hours + ' 小时前'; + var days = Math.floor(hours / 24); + if (days < 30) return days + ' 天前'; + return formatDate(iso); + } + + function externalLink(href, text, className) { + return el('a', { + href: href, + target: '_blank', + rel: 'noopener noreferrer', + class: className || null, + text: text + }); + } + + function remoteImage(src, alt, className, richClass) { + var img = el('img', { + src: src, + alt: alt, + class: className, + loading: 'lazy', + referrerpolicy: 'no-referrer' + }); + img.addEventListener('error', function () { + img.hidden = true; + if (richClass && img.parentElement) img.parentElement.classList.remove(richClass); + }); + return img; + } + + function snapshot() { + return state.data && state.data.snapshot ? state.data.snapshot : null; + } + + function request(path, options) { + return fetch(path, options).then(function (response) { + if (!response.ok) throw new Error('HTTP ' + response.status); + return response.json(); + }); + } + + /* ---------- 视图状态 ---------- */ + + function saveView() { + try { + localStorage.setItem(VIEW_KEY, JSON.stringify(state.view)); + } catch (error) { + /* 存储不可用时忽略 */ + } + } + + function restoreView() { + try { + var raw = localStorage.getItem(VIEW_KEY); + if (!raw) return; + var saved = JSON.parse(raw); + if (!saved || typeof saved !== 'object') return; + if (TABS.indexOf(saved.tab) >= 0) state.view.tab = saved.tab; + if (typeof saved.source === 'string') state.view.source = saved.source; + if (typeof saved.query === 'string') state.view.query = saved.query; + if (THEME_LABELS[saved.theme]) state.view.theme = saved.theme; + state.view.historyExpanded = Boolean(saved.historyExpanded); + state.view.birthsExpanded = Boolean(saved.birthsExpanded); + state.view.deathsExpanded = Boolean(saved.deathsExpanded); + } catch (error) { + /* 损坏的视图状态忽略 */ + } + } + + function resolvedTheme() { + if (state.view.theme === 'light' || state.view.theme === 'dark') return state.view.theme; + if (hostTheme) return hostTheme; + return mediaQuery && mediaQuery.matches ? 'dark' : 'light'; + } + + function applyTheme() { + document.documentElement.setAttribute('data-theme', resolvedTheme()); + var button = document.getElementById('theme-toggle'); + if (button) { + button.textContent = THEME_LABELS[state.view.theme]; + button.setAttribute('aria-label', '切换明暗主题,当前' + THEME_LABELS[state.view.theme].replace('主题:', '')); + } + } + + function initHostTheme() { + var host = window.miniapp; + if (!host || !host.host || !host.host.ui || typeof host.host.ui.getState !== 'function') return; + var apply = function (ui) { + if (ui && (ui.theme === 'light' || ui.theme === 'dark')) { + hostTheme = ui.theme; + applyTheme(); + } + }; + try { + host.host.ui.getState().then(apply).catch(function () {}); + if (typeof host.host.ui.subscribe === 'function') { + host.host.ui.subscribe(apply, { onError: function () {} }); + } + } catch (error) { + /* 宿主主题不可用时使用系统主题 */ + } + } + + /* ---------- 渲染:状态区 ---------- */ + + function renderStatus() { + var status = document.getElementById('update-status'); + var next = document.getElementById('next-refresh'); + var snap = snapshot(); + if (state.loading && !snap) { + status.textContent = '正在加载今日内容…'; + next.textContent = ''; + return; + } + if (state.refreshing) { + status.textContent = '正在抓取最新内容…'; + } else if (snap) { + status.textContent = + '上次更新 ' + formatClock(snap.fetchedAt) + '(' + formatDate(snap.fetchedAt) + ')· 新闻 ' + snap.news.length + ' 条'; + } else { + status.textContent = '暂无内容'; + } + if (state.data && state.data.nextRefreshAt) { + next.textContent = + '下次自动刷新 ' + formatClock(state.data.nextRefreshAt) + '(每 ' + state.data.intervalMinutes + ' 分钟)'; + } else { + next.textContent = ''; + } + } + + function renderSummary() { + var container = document.getElementById('summary'); + clear(container); + var snap = snapshot(); + if (!snap) return; + var wiki = snap.wiki; + var people = wiki ? wiki.births.length + wiki.deaths.length : 0; + var cards = [ + { + label: '今日要闻', + value: String(snap.news.length), + note: '已排除 ' + snap.filtered.count + ' 条中国大陆官方媒体报道' + }, + { + label: '历史上的今天', + value: wiki ? String(wiki.events.length) : '0', + note: wiki ? '中文维基「' + wiki.pageTitle + '」大事记' : '维基内容暂不可用' + }, + { + label: '今日人物', + value: String(people), + note: wiki ? '出生 ' + wiki.births.length + ' 位 · 逝世 ' + wiki.deaths.length + ' 位' : '维基内容暂不可用' + } + ]; + cards.forEach(function (card) { + container.appendChild( + el('article', { class: 'summary__card' }, [ + el('p', { class: 'summary__label', text: card.label }), + el('p', { class: 'summary__value', text: card.value }), + el('p', { class: 'summary__note', text: card.note }) + ]) + ); + }); + } + + function renderNotices() { + var snap = snapshot(); + var newNotice = document.getElementById('new-notice'); + var newText = document.getElementById('new-notice-text'); + var newCount = snap ? snap.news.filter(function (item) { return item.isNew; }).length : 0; + if (newCount > 0) { + newText.textContent = '本次刷新新增 ' + newCount + ' 条新闻,已在列表中标注「新」。'; + newNotice.hidden = false; + } else { + newNotice.hidden = true; + } + + var sourceNotice = document.getElementById('source-notice'); + var errors = snap && snap.errors ? snap.errors : []; + if (errors.length) { + var names = errors.map(function (entry) { return entry.source; }); + sourceNotice.textContent = '部分内容未能更新:' + names.join('、') + '。其余内容为最近一次成功抓取的结果。'; + sourceNotice.hidden = false; + } else { + sourceNotice.hidden = true; + } + + var errorNotice = document.getElementById('error-notice'); + var errorText = document.getElementById('error-text'); + if (state.error) { + errorText.textContent = state.error; + errorNotice.hidden = false; + } else { + errorNotice.hidden = true; + } + } + + function renderTabs() { + TABS.forEach(function (tab) { + var button = document.getElementById('tab-' + tab); + var panel = document.getElementById('panel-' + tab); + var selected = state.view.tab === tab; + button.setAttribute('aria-selected', selected ? 'true' : 'false'); + button.tabIndex = selected ? 0 : -1; + panel.hidden = !selected; + }); + } + + function renderSkeleton(container) { + clear(container); + var box = el('div', { class: 'skeleton', 'aria-hidden': 'true' }); + for (var index = 0; index < 4; index += 1) box.appendChild(el('div', { class: 'skeleton__row' })); + container.appendChild(box); + } + + /* ---------- 渲染:新闻 ---------- */ + + function filteredNews() { + var snap = snapshot(); + if (!snap) return []; + var query = state.view.query.trim().toLowerCase(); + return snap.news.filter(function (item) { + if (state.view.source !== 'all' && item.sourceId !== state.view.source) return false; + if (!query) return true; + return item.title.toLowerCase().indexOf(query) >= 0 || (item.summary || '').toLowerCase().indexOf(query) >= 0; + }); + } + + function renderNews() { + var snap = snapshot(); + var chips = document.getElementById('source-chips'); + var noteBox = document.getElementById('news-filter-note'); + var body = document.getElementById('news-body'); + var queryInput = document.getElementById('news-query'); + if (queryInput.value !== state.view.query) queryInput.value = state.view.query; + + clear(chips); + clear(noteBox); + if (state.loading && !snap) { + renderSkeleton(body); + return; + } + if (!snap) { + clear(body); + body.appendChild(el('p', { class: 'empty', text: '暂时没有可显示的新闻。' })); + return; + } + + var sources = state.data.sources || []; + var counts = {}; + snap.news.forEach(function (item) { + counts[item.sourceId] = (counts[item.sourceId] || 0) + 1; + }); + if (state.view.source !== 'all' && !sources.some(function (source) { return source.id === state.view.source; })) { + state.view.source = 'all'; + } + + var chipItems = [{ id: 'all', name: '全部', count: snap.news.length }].concat( + sources.map(function (source) { + return { id: source.id, name: source.name, count: counts[source.id] || 0 }; + }) + ); + chipItems.forEach(function (chip) { + chips.appendChild( + el('button', { + type: 'button', + class: 'chip', + 'aria-pressed': state.view.source === chip.id ? 'true' : 'false', + 'data-source': chip.id, + text: chip.name + ' ' + chip.count + }) + ); + }); + + if (snap.filtered && snap.filtered.count > 0) { + var list = el('ul'); + snap.filtered.sources.forEach(function (entry) { + list.appendChild(el('li', { text: entry.name + ' × ' + entry.count })); + }); + var details = el('details', { class: 'filter-note' }, [ + el('summary', { text: '已排除 ' + snap.filtered.count + ' 条中国大陆官方媒体报道' }), + list, + el('p', { + class: 'muted', + text: + '过滤依据:官方媒体名称与域名名单(' + + state.data.filter.names + + ' 个名称、' + + state.data.filter.domains + + ' 个域名),聚合源中来自这些媒体的条目不展示。' + }) + ]); + noteBox.appendChild(details); + } + + var items = filteredNews(); + clear(body); + if (!items.length) { + var empty = el('div', { class: 'empty' }, [ + el('p', { text: '没有符合当前筛选条件的新闻。' }), + el('div', { class: 'empty__action' }, [ + el('button', { + type: 'button', + class: 'btn btn--ghost btn--small', + 'data-action': 'reset-filters', + text: '清除筛选条件' + }) + ]) + ]); + body.appendChild(empty); + return; + } + + var visible = items.slice(0, state.view.newsLimit); + var listEl = el('ul', { class: 'news-list' }); + visible.forEach(function (item) { + var meta = el('div', { class: 'news-card__meta' }, [ + el('span', { class: 'badge', text: item.sourceName }), + item.publisher && item.publisher !== item.sourceName + ? el('span', { text: item.publisher }) + : null, + item.isNew ? el('span', { class: 'badge badge--new', text: '新' }) : null, + el('time', { datetime: item.publishedAt || '', title: formatDate(item.publishedAt), text: formatRelative(item.publishedAt) }) + ]); + var card = el('article', { class: 'news-card' }, [ + meta, + el('h3', { class: 'news-card__title' }, [externalLink(item.url, item.title)]), + item.summary ? el('p', { class: 'news-card__summary', text: item.summary }) : null + ]); + listEl.appendChild(el('li', null, [card])); + }); + body.appendChild(listEl); + + if (items.length > visible.length) { + body.appendChild( + el('div', { class: 'empty__action' }, [ + el('button', { + type: 'button', + class: 'btn btn--ghost btn--small', + 'data-action': 'more-news', + text: '显示更多(还有 ' + (items.length - visible.length) + ' 条)' + }) + ]) + ); + } + } + + /* ---------- 渲染:历史上的今天 ---------- */ + + function renderHistory() { + var snap = snapshot(); + var body = document.getElementById('history-body'); + if (state.loading && !snap) { + renderSkeleton(body); + return; + } + clear(body); + var wiki = snap && snap.wiki; + if (!wiki) { + body.appendChild(el('p', { class: 'empty', text: '维基内容暂时不可用。' })); + return; + } + + var head = el('div', { class: 'section-head' }, [ + el('h2', { class: 'section-title', text: '历史上的今天' }), + el('p', { class: 'section-meta' }, [ + el('span', { text: '共 ' + wiki.events.length + ' 条 · 来源:' }), + externalLink(wiki.pageUrl, '中文维基「' + wiki.pageTitle + '」') + ]) + ]); + body.appendChild(head); + + var events = state.view.historyExpanded ? wiki.events : wiki.events.slice(0, HISTORY_INITIAL); + var list = el('ul', { class: 'history-list' }); + events.forEach(function (event) { + var links = el('div', { class: 'history-item__links' }); + event.links.forEach(function (link) { + links.appendChild(externalLink(link.url, link.title)); + }); + list.appendChild( + el('li', null, [ + el('article', { class: 'history-item' }, [ + el('div', { class: 'history-item__year', text: event.year + '年' }), + el('div', null, [el('p', { class: 'history-item__text', text: event.text }), event.links.length ? links : null]) + ]) + ]) + ); + }); + body.appendChild(list); + + if (wiki.events.length > HISTORY_INITIAL) { + body.appendChild( + el('div', { class: 'empty__action' }, [ + el('button', { + type: 'button', + class: 'btn btn--ghost btn--small', + 'data-action': 'toggle-history', + text: state.view.historyExpanded ? '收起较早的条目' : '显示全部 ' + wiki.events.length + ' 条' + }) + ]) + ); + } + + if (wiki.holidays.length) { + var holidayBox = el('section', { class: 'people-group' }, [ + el('div', { class: 'section-head' }, [el('h2', { class: 'section-title', text: '节假日与习俗' })]), + el('ul', { class: 'holiday-list' }) + ]); + var holidayList = holidayBox.querySelector('ul'); + wiki.holidays.forEach(function (holiday) { + holidayList.appendChild(el('li', { text: holiday })); + }); + body.appendChild(holidayBox); + } + } + + /* ---------- 渲染:每日人物 ---------- */ + + function renderPersonList(persons, expanded, action) { + var visible = expanded ? persons : persons.slice(0, PEOPLE_INITIAL); + var list = el('ul', { class: 'person-list' }); + visible.forEach(function (person) { + var rich = Boolean(person.thumb || person.extract); + var children = [ + el('div', { class: 'person-card__head' }, [ + el('h3', { class: 'person-card__name' }, [ + person.url ? externalLink(person.url, person.name) : el('span', { text: person.name }) + ]), + el('span', { class: 'person-card__year', text: person.year + '年' }) + ]), + person.description ? el('p', { class: 'person-card__desc', text: person.description }) : null, + person.extract ? el('p', { class: 'person-card__extract', text: person.extract }) : null + ]; + var card = el('article', { class: rich ? 'person-card person-card--rich' : 'person-card' }); + if (person.thumb) { + card.appendChild(remoteImage(person.thumb, person.name + ' 的照片', 'person-card__thumb', 'person-card--rich')); + } + card.appendChild(el('div', null, children)); + list.appendChild(el('li', null, [card])); + }); + var wrapper = el('div', null, [list]); + if (persons.length > PEOPLE_INITIAL) { + wrapper.appendChild( + el('div', { class: 'empty__action' }, [ + el('button', { + type: 'button', + class: 'btn btn--ghost btn--small', + 'data-action': action, + text: expanded ? '收起' : '显示全部 ' + persons.length + ' 位' + }) + ]) + ); + } + return wrapper; + } + + function renderPeople() { + var snap = snapshot(); + var body = document.getElementById('people-body'); + if (state.loading && !snap) { + renderSkeleton(body); + return; + } + clear(body); + var wiki = snap && snap.wiki; + if (!wiki) { + body.appendChild(el('p', { class: 'empty', text: '维基内容暂时不可用。' })); + return; + } + + if (wiki.featured) { + var featured = wiki.featured; + var card = el('article', { class: featured.thumb ? 'feature-card feature-card--rich' : 'feature-card' }); + if (featured.thumb) { + card.appendChild(remoteImage(featured.thumb, featured.title + ' 的图片', 'feature-card__thumb', 'feature-card--rich')); + } + card.appendChild( + el('div', null, [ + el('h3', { class: 'feature-card__title' }, [ + featured.url ? externalLink(featured.url, featured.title) : el('span', { text: featured.title }) + ]), + el('p', { class: 'feature-card__extract', text: featured.extract || '暂无导语。' }) + ]) + ); + body.appendChild( + el('section', null, [ + el('div', { class: 'section-head' }, [ + el('h2', { class: 'section-title', text: '今日特色条目' }), + el('p', { class: 'section-meta', text: '维基百科每日推荐条目' }) + ]), + card + ]) + ); + } + + var groups = [ + { title: '当天出生', persons: wiki.births, expanded: state.view.birthsExpanded, action: 'toggle-births' }, + { title: '当天逝世', persons: wiki.deaths, expanded: state.view.deathsExpanded, action: 'toggle-deaths' } + ]; + groups.forEach(function (group) { + var section = el('section', { class: 'people-group' }, [ + el('div', { class: 'section-head' }, [ + el('h2', { class: 'section-title', text: group.title }), + el('p', { class: 'section-meta', text: '共 ' + group.persons.length + ' 位' }) + ]) + ]); + if (!group.persons.length) { + section.appendChild(el('p', { class: 'empty', text: '暂无条目。' })); + } else { + section.appendChild(renderPersonList(group.persons, group.expanded, group.action)); + } + body.appendChild(section); + }); + } + + /* ---------- 渲染:每日一图 ---------- */ + + function renderImage() { + var snap = snapshot(); + var body = document.getElementById('image-body'); + if (state.loading && !snap) { + renderSkeleton(body); + return; + } + clear(body); + var wiki = snap && snap.wiki; + var image = wiki && wiki.image; + if (!image || !image.thumb) { + body.appendChild(el('p', { class: 'empty', text: '今天的每日一图暂时不可用。' })); + return; + } + var caption = el('figcaption', null, [ + el('p', { class: 'image-figure__title', text: image.title }), + image.description ? el('p', { text: image.description }) : null, + image.artist ? el('p', { class: 'muted', text: '作者:' + image.artist }) : null, + image.page ? el('p', null, [externalLink(image.page, '在维基共享资源查看原图')]) : null + ]); + body.appendChild( + el('figure', { class: 'image-figure' }, [ + remoteImage(image.thumb, image.description || image.title, null, null), + caption + ]) + ); + } + + function renderFooter() { + var footer = document.getElementById('footer-sources'); + if (!state.data || !state.data.sources) { + footer.textContent = ''; + return; + } + footer.textContent = + '新闻来源:' + + state.data.sources + .map(function (source) { + return source.name; + }) + .join('、') + + '(已排除中国大陆官方媒体)。'; + } + + function renderAll() { + renderStatus(); + renderSummary(); + renderNotices(); + renderTabs(); + renderNews(); + renderHistory(); + renderPeople(); + renderImage(); + renderFooter(); + var refreshButton = document.getElementById('refresh-button'); + refreshButton.disabled = state.refreshing || state.loading; + refreshButton.textContent = state.refreshing ? '正在刷新…' : '立即刷新'; + } + + /* ---------- 数据流 ---------- */ + + function scheduleRefresh() { + if (timers.refresh) clearTimeout(timers.refresh); + var next = state.data && state.data.nextRefreshAt ? Date.parse(state.data.nextRefreshAt) : Date.now() + 3600000; + var delay = Math.max(15000, next - Date.now()); + timers.refresh = setTimeout(function () { + refresh(); + }, delay); + if (!timers.countdown) { + timers.countdown = setInterval(function () { + renderStatus(); + }, 30000); + } + } + + function load() { + state.loading = true; + state.error = null; + renderAll(); + return request('/api/briefing') + .then(function (data) { + state.data = data; + state.loading = false; + state.refreshing = false; + scheduleRefresh(); + renderAll(); + }) + .catch(function (error) { + state.loading = false; + state.refreshing = false; + state.error = '无法获取内容:' + (error && error.message ? error.message : '网络错误') + '。请稍后重试。'; + renderAll(); + }); + } + + function refresh() { + if (state.refreshing) return; + state.refreshing = true; + state.error = null; + renderAll(); + return request('/api/refresh', { method: 'POST' }) + .then(function (data) { + state.data = data; + state.refreshing = false; + state.view.newsLimit = NEWS_STEP; + saveView(); + scheduleRefresh(); + renderAll(); + }) + .catch(function (error) { + state.refreshing = false; + state.error = + '刷新失败:' + (error && error.message ? error.message : '网络错误') + ',页面保留上一次的内容。'; + scheduleRefresh(); + renderAll(); + }); + } + + function markSeen() { + return request('/api/seen', { method: 'POST' }) + .then(function (data) { + state.data = data; + renderAll(); + }) + .catch(function () { + /* 标为已读失败不影响浏览 */ + }); + } + + function maybeRefresh() { + if (!state.data) { + load(); + return; + } + var next = state.data.nextRefreshAt ? Date.parse(state.data.nextRefreshAt) : 0; + if (state.data.stale || (next && next <= Date.now())) refresh(); + } + + /* ---------- 事件绑定 ---------- */ + + function selectTab(tab, focus) { + if (TABS.indexOf(tab) < 0) return; + state.view.tab = tab; + saveView(); + renderTabs(); + if (focus) { + var button = document.getElementById('tab-' + tab); + if (button) button.focus(); + } + } + + function bindEvents() { + document.getElementById('refresh-button').addEventListener('click', function () { + refresh(); + }); + document.getElementById('retry-button').addEventListener('click', function () { + load(); + }); + document.getElementById('mark-seen').addEventListener('click', function () { + markSeen(); + }); + document.getElementById('theme-toggle').addEventListener('click', function () { + var order = ['system', 'light', 'dark']; + var next = order[(order.indexOf(state.view.theme) + 1) % order.length]; + state.view.theme = next; + saveView(); + applyTheme(); + }); + + var tablist = document.getElementById('tablist'); + tablist.addEventListener('click', function (event) { + var button = event.target.closest('[data-tab]'); + if (button) selectTab(button.getAttribute('data-tab'), false); + }); + tablist.addEventListener('keydown', function (event) { + var index = TABS.indexOf(state.view.tab); + var nextIndex = null; + if (event.key === 'ArrowRight') nextIndex = (index + 1) % TABS.length; + else if (event.key === 'ArrowLeft') nextIndex = (index - 1 + TABS.length) % TABS.length; + else if (event.key === 'Home') nextIndex = 0; + else if (event.key === 'End') nextIndex = TABS.length - 1; + if (nextIndex === null) return; + event.preventDefault(); + selectTab(TABS[nextIndex], true); + }); + + var queryInput = document.getElementById('news-query'); + queryInput.addEventListener('input', function () { + state.view.query = queryInput.value; + state.view.newsLimit = NEWS_STEP; + if (timers.query) clearTimeout(timers.query); + timers.query = setTimeout(function () { + saveView(); + renderNews(); + }, 200); + }); + + document.getElementById('source-chips').addEventListener('click', function (event) { + var chip = event.target.closest('[data-source]'); + if (!chip) return; + state.view.source = chip.getAttribute('data-source'); + state.view.newsLimit = NEWS_STEP; + saveView(); + renderNews(); + }); + + document.getElementById('main').addEventListener('click', function (event) { + var button = event.target.closest('[data-action]'); + if (!button) return; + var action = button.getAttribute('data-action'); + if (action === 'more-news') { + state.view.newsLimit += NEWS_STEP; + renderNews(); + } else if (action === 'reset-filters') { + state.view.source = 'all'; + state.view.query = ''; + state.view.newsLimit = NEWS_STEP; + saveView(); + renderNews(); + } else if (action === 'toggle-history') { + state.view.historyExpanded = !state.view.historyExpanded; + saveView(); + renderHistory(); + } else if (action === 'toggle-births') { + state.view.birthsExpanded = !state.view.birthsExpanded; + saveView(); + renderPeople(); + } else if (action === 'toggle-deaths') { + state.view.deathsExpanded = !state.view.deathsExpanded; + saveView(); + renderPeople(); + } + }); + + document.addEventListener('visibilitychange', function () { + if (document.visibilityState === 'hidden') { + saveView(); + return; + } + maybeRefresh(); + }); + + if (mediaQuery && typeof mediaQuery.addEventListener === 'function') { + mediaQuery.addEventListener('change', applyTheme); + } + } + + restoreView(); + applyTheme(); + initHostTheme(); + bindEvents(); + renderAll(); + load(); +})(); diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/index.html b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/index.html new file mode 100644 index 00000000..22e4b7e4 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/index.html @@ -0,0 +1,83 @@ + + + + + + 每日新闻简报 + + + +
+ + +
+

正在加载今日内容…

+

+
+ + + + + + + +
+ + + +
+
+
+ +
+
+
+
+
+ + + + + + +
+ +
+ +

历史事件、人物与图片来自中文维基百科,链接在系统浏览器中打开。新闻内容版权归各媒体所有。

+
+
+ + + diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/styles.css b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/styles.css new file mode 100644 index 00000000..b36f4b9b --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/client/styles.css @@ -0,0 +1,728 @@ +:root, +[data-theme='light'] { + --mcode-bg: #ffffff; + --mcode-bg-secondary: #f5f5f5; + --mcode-surface: #ffffff; + --mcode-surface-muted: #fafafa; + --mcode-text: #171717; + --mcode-text-muted: #666666; + --mcode-text-subtle: #adadad; + --mcode-border: #0a0a0a14; + --mcode-border-strong: #0a0a0af2; + --mcode-accent: #0094fc; + --mcode-success: #04b54b; + --mcode-warning: #f56811; + --mcode-danger: #f73646; + --mcode-primary-action-bg: #171717; + --mcode-primary-action-text: #ffffff; + --mcode-shadow: 0 0 20px rgb(10 10 10 / 8%); +} + +[data-theme='dark'] { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + --mcode-shadow: 0 0 20px rgb(0 0 0 / 40%); +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; +} + +body { + background: var(--mcode-bg); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; +} + +.page { + max-width: 1120px; + margin: 0 auto; + padding: 24px; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +.muted { + color: var(--mcode-text-muted); +} + +.page-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; +} + +.page-title { + margin: 0; + font-size: 18px; + line-height: 28px; + font-weight: 600; +} + +.page-desc { + margin: 4px 0 0; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.page-header__actions { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 36px; + padding: 0 14px; + border-radius: 8px; + border: 1px solid var(--mcode-border); + background: transparent; + color: var(--mcode-text); + font: inherit; + font-size: 14px; + cursor: pointer; + transition: background-color 150ms ease-out, opacity 150ms ease-out, border-color 150ms ease-out; +} + +.btn:hover { + background: var(--mcode-surface-muted); +} + +.btn:disabled { + opacity: 0.55; + cursor: default; +} + +.btn--primary { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); + border-color: transparent; +} + +.btn--primary:hover { + background: var(--mcode-primary-action-bg); + opacity: 0.88; +} + +.btn--ghost { + background: transparent; +} + +.btn--small { + min-height: 30px; + padding: 0 10px; + font-size: 13px; +} + +.btn:focus-visible, +.tabs__tab:focus-visible, +.chip:focus-visible, +.input:focus-visible, +a:focus-visible, +summary:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 2px; +} + +.status-bar { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + margin-top: 12px; + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-bg-secondary); + font-size: 13px; +} + +.status-bar__main { + margin: 0; +} + +.status-bar__next { + margin: 0; + color: var(--mcode-text-muted); +} + +.notice { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 12px; + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); + font-size: 13px; +} + +.notice[hidden] { + display: none; +} + +.notice--warning { + border-color: var(--mcode-warning); +} + +.notice--danger { + border-color: var(--mcode-danger); +} + +.notice__text { + min-width: 0; +} + +.summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); + gap: 12px; + margin-top: 20px; +} + +.summary__card { + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.summary__label { + margin: 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.summary__value { + margin: 4px 0 0; + font-size: 26px; + line-height: 34px; + font-weight: 600; +} + +.summary__note { + margin: 4px 0 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.tabs { + margin-top: 24px; + border-bottom: 1px solid var(--mcode-border); +} + +.tabs__list { + display: flex; + gap: 4px; + overflow-x: auto; +} + +.tabs__tab { + min-height: 38px; + padding: 0 14px; + border: 0; + border-bottom: 2px solid transparent; + background: transparent; + color: var(--mcode-text-muted); + font: inherit; + font-size: 14px; + cursor: pointer; + white-space: nowrap; + transition: color 150ms ease-out, border-color 150ms ease-out; +} + +.tabs__tab:hover { + color: var(--mcode-text); +} + +.tabs__tab[aria-selected='true'] { + color: var(--mcode-text); + border-bottom-color: var(--mcode-accent); + font-weight: 500; +} + +.main { + margin-top: 20px; +} + +.panel[hidden] { + display: none; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; +} + +.toolbar__search { + flex: 1 1 220px; + min-width: 200px; +} + +.input { + width: 100%; + height: 38px; + padding: 0 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface); + color: var(--mcode-text); + font: inherit; + font-size: 14px; +} + +.input::placeholder { + color: var(--mcode-text-subtle); +} + +.chips { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.chip { + min-height: 32px; + padding: 0 12px; + border: 1px solid var(--mcode-border); + border-radius: 999px; + background: transparent; + color: var(--mcode-text-muted); + font: inherit; + font-size: 13px; + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out; +} + +.chip:hover { + background: var(--mcode-surface-muted); + color: var(--mcode-text); +} + +.chip[aria-pressed='true'] { + background: var(--mcode-surface-muted); + border-color: var(--mcode-border-strong); + color: var(--mcode-text); + font-weight: 500; +} + +.filter-note { + margin-top: 12px; + font-size: 13px; + color: var(--mcode-text-muted); +} + +.filter-note summary { + cursor: pointer; + color: var(--mcode-text); +} + +.filter-note ul { + margin: 8px 0 0; + padding-left: 20px; +} + +.section-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin: 0 0 12px; +} + +.section-title { + margin: 0; + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.section-meta { + margin: 0; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.news-list, +.history-list, +.person-list, +.holiday-list { + list-style: none; + margin: 16px 0 0; + padding: 0; +} + +.news-list { + display: flex; + flex-direction: column; + gap: 12px; +} + +.news-card { + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.news-card__meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.badge { + display: inline-flex; + align-items: center; + padding: 1px 8px; + border: 1px solid var(--mcode-border); + border-radius: 999px; + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); + font-size: 12px; + line-height: 18px; +} + +.badge--new { + border-color: var(--mcode-accent); + color: var(--mcode-accent); +} + +.news-card__title { + margin: 8px 0 0; + font-size: 15px; + line-height: 22px; + font-weight: 500; +} + +.news-card__title a, +.history-item__links a, +.person-card__name a, +.feature-card__title a, +.section-meta a, +.image-figure figcaption a { + color: var(--mcode-text); + text-decoration: none; +} + +.news-card__title a:hover, +.history-item__links a:hover, +.person-card__name a:hover, +.feature-card__title a:hover, +.section-meta a:hover, +.image-figure figcaption a:hover { + color: var(--mcode-accent); + text-decoration: underline; +} + +.news-card__summary { + margin: 6px 0 0; + color: var(--mcode-text-muted); + font-size: 14px; + line-height: 21px; +} + +.history-list { + display: flex; + flex-direction: column; + gap: 12px; +} + +.history-item { + display: grid; + grid-template-columns: 88px minmax(0, 1fr); + gap: 16px; + padding: 14px 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.history-item__year { + font-size: 18px; + line-height: 26px; + font-weight: 600; + color: var(--mcode-text); +} + +.history-item__text { + margin: 0; +} + +.history-item__links { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; + font-size: 12px; +} + +.history-item__links a { + padding: 1px 8px; + border: 1px solid var(--mcode-border); + border-radius: 999px; + color: var(--mcode-text-muted); +} + +.holiday-list { + display: flex; + flex-direction: column; + gap: 6px; + color: var(--mcode-text-muted); +} + +.people-group { + margin-top: 28px; +} + +.person-list { + display: flex; + flex-direction: column; + gap: 12px; +} + +.person-card { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 12px; + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.person-card--rich { + grid-template-columns: 96px minmax(0, 1fr); +} + +.person-card__thumb { + width: 96px; + height: 96px; + object-fit: cover; + border-radius: 8px; + border: 1px solid var(--mcode-border); + background: var(--mcode-bg-secondary); +} + +.person-card__head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 8px; +} + +.person-card__name { + margin: 0; + font-size: 15px; + line-height: 22px; + font-weight: 500; +} + +.person-card__year { + color: var(--mcode-text-muted); + font-size: 12px; +} + +.person-card__desc { + margin: 4px 0 0; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.person-card__extract { + margin: 8px 0 0; + font-size: 14px; + line-height: 21px; +} + +.feature-card { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 16px; + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.feature-card--rich { + grid-template-columns: 200px minmax(0, 1fr); +} + +.feature-card__thumb { + width: 100%; + max-height: 240px; + object-fit: cover; + border-radius: 8px; + border: 1px solid var(--mcode-border); + background: var(--mcode-bg-secondary); +} + +.feature-card__title { + margin: 0; + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.feature-card__extract { + margin: 8px 0 0; +} + +.image-figure { + margin: 0; + padding: 16px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); +} + +.image-figure img { + display: block; + width: 100%; + max-height: 460px; + object-fit: contain; + border-radius: 8px; + background: var(--mcode-bg-secondary); +} + +.image-figure figcaption { + margin-top: 12px; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.image-figure__title { + margin: 0 0 4px; + color: var(--mcode-text); + font-size: 14px; +} + +.empty { + margin-top: 16px; + padding: 24px 16px; + border: 1px dashed var(--mcode-border); + border-radius: 12px; + color: var(--mcode-text-muted); + text-align: center; +} + +.empty__action { + margin-top: 12px; +} + +.skeleton { + margin-top: 16px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.skeleton__row { + height: 84px; + border-radius: 12px; + border: 1px solid var(--mcode-border); + background: var(--mcode-bg-secondary); + opacity: 0.7; +} + +.page-footer { + margin-top: 32px; + padding-top: 16px; + border-top: 1px solid var(--mcode-border); + color: var(--mcode-text-muted); + font-size: 12px; +} + +.page-footer p { + margin: 0 0 4px; +} + +@media (max-width: 768px) { + .page { + padding: 16px; + } + + .summary { + gap: 8px; + } + + .summary__card { + padding: 12px; + } + + .summary__value { + font-size: 20px; + line-height: 28px; + } + + .summary__note { + font-size: 11px; + } + + .history-item { + grid-template-columns: minmax(0, 1fr); + gap: 4px; + } + + .person-card--rich, + .feature-card--rich { + grid-template-columns: minmax(0, 1fr); + } + + .person-card__thumb { + width: 80px; + height: 80px; + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition: none !important; + animation: none !important; + } +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/miniapp.json b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/miniapp.json new file mode 100644 index 00000000..c35dfb37 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/miniapp.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/briefing", + "window": { + "width": 1120, + "height": 760, + "minWidth": 480, + "minHeight": 360, + "resizable": true, + "frame": true, + "transparent": false, + "alwaysOnTop": false, + "skipTaskbar": false, + "clickThrough": false + } + }, + "mcpEndpoints": [], + "engines": { + "mcode": ">=3.1.20" + } +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/http.mjs b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/http.mjs new file mode 100644 index 00000000..d678e8af --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/http.mjs @@ -0,0 +1,46 @@ +// 带超时与体积上限的 HTTP 读取工具(仅用于 Node 侧抓取公开数据源)。 + +const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) DailyBriefing/1.0 (+miniapp)'; + +/** + * @param {string} url + * @param {{ timeoutMs?: number, signal?: AbortSignal, maxChars?: number }} [options] + * @returns {Promise} + */ +export async function fetchText(url, options = {}) { + const { timeoutMs = 20000, signal, maxChars = 2_000_000 } = options; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs); + const onAbort = () => controller.abort(); + if (signal) { + if (signal.aborted) controller.abort(); + else signal.addEventListener('abort', onAbort, { once: true }); + } + try { + const response = await fetch(url, { + headers: { 'user-agent': USER_AGENT, accept: '*/*' }, + redirect: 'follow', + signal: controller.signal + }); + if (!response.ok) throw new Error('HTTP ' + response.status); + const text = await response.text(); + return text.length > maxChars ? text.slice(0, maxChars) : text; + } finally { + clearTimeout(timer); + if (signal) signal.removeEventListener('abort', onAbort); + } +} + +/** + * @param {string} url + * @param {{ timeoutMs?: number, signal?: AbortSignal }} [options] + * @returns {Promise} + */ +export async function fetchJson(url, options) { + const text = await fetchText(url, options); + try { + return JSON.parse(text); + } catch { + throw new Error('响应不是有效 JSON'); + } +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/miniapp-api.ts b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..1b68a48d --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/miniapp-api.ts @@ -0,0 +1,686 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The manifest did not declare the required grant; not dispatched. */ + | 'NOT_PERMITTED' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'PERMISSION_DENIED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Always present. Without `permissions.tool: ["call"]` (or the older `"toolAccess": ["call"]`), + * every method rejects `NOT_PERMITTED`. With `tool:call` switched off, `call()` rejects + * `PERMISSION_DENIED` while `list()` and `request()` resolve with `deny` for each tool. Every `call` + * is judged by the user's global rules: `deny` is `PERMISSION_DENIED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'PERMISSION_DENIED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Always present. `run` / `reply` / `answer` / `models` / `list` / `create` need + * `permissions.agent: ["run"]`. The deprecated `observe` / `sessions` / `session` are the + * `context.session` methods and follow its rule (see agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `list()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `list()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `list` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + list(): Promise; + /** @deprecated Use `list()`; the Host warns once and removes this name in a later version. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `list()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** @deprecated Use `context.session.observe`; the Host warns once and removes this name in a later version. */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** @deprecated Use `context.session.list`; the Host warns once and removes this name in a later version. */ + sessions(): Promise; + /** @deprecated Use `context.session.get`; the Host warns once and removes this name in a later version. */ + session(sessionId: string): Promise; +} + +/** + * Always present. Read-only access to the user's conversations (the Desktop chat list). + * Every method needs `permissions.session: ["read"]`, except that this Mini App's own sessions (those + * `agent.create` / `agent.run` made) are readable under `permissions.agent: ["run"]` alone; while the + * user has `read` switched off, calls on other sessions fail with `PERMISSION_DENIED` and running + * observers end. Check `context.capabilities?.has('session.list')` on Hosts that may predate it. + * Neither grant implies the other; `observe({ all: true })` always needs `permissions.session: ["read"]`. + */ +export interface MiniAppSessionClient { + /** The user's visible root conversations, most recently updated first (at most 50). */ + list(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session.get()`). + */ + get(sessionId: string): Promise; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `PERMISSION_DENIED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of the methods this Host offers **on the Node side**, named by API path + * (`agent.run`, `agent.list`, `session.list`, `session.get`, `session.observe`, + * `connector.call`, `connector.list`, `tool.call`, `tool.list`, `tool.request`). A + * page-only method is false here. A few Host-wide names remain until the deprecated aliases go: + * `agent.agents`, `agent.observe`, `agent.sessions`, `agent.session`, `hostConnector`, `tool`. + * The `hostConnector*` probe names stay beside `connector.*` until the alias goes. + * It says nothing about this Mini App's manifest or authorization: `has('agent.run')` is true + * even when the manifest does not grant it. Older Hosts do not + * inject `capabilities`; check `context.capabilities?.has(...)`. `has('session.list')` tells a + * `context.session` Host from one that only has the deprecated `context.agent.sessions` names. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Always present. Without `permissions.connector` (or the older `hostConnectorAccess`), every + * method rejects `NOT_PERMITTED`. A provider the user switched off is missing from `list()` + * and its calls reject with `PERMISSION_DENIED`. + */ + readonly connector: HostConnectorClient; + /** + * @deprecated `connector`. Always present. Forwards to the same client and warns once on the first method call + * (`MINIAPP-DEP-007`); it is not the same object reference, so do not compare the two or use + * both as map keys. + */ + readonly hostConnector: HostConnectorClient; + /** Always present. Calls installed MCP and Connector tools under the user's permission rules. */ + readonly tool: MiniAppToolClient; + /** + * Always present, as on the page. Its methods need `permissions.agent: ["run"]`; they reject + * with `NOT_PERMITTED` if the manifest does not declare it and `PERMISSION_DENIED` if the user + * switched it off. Session aliases follow `context.session`'s rules. + */ + readonly agent: MiniAppAgentClient; + /** + * Always present, as on the page. Reading conversations other than this Mini App's own needs + * `permissions.session: ["read"]`. Own sessions can also use `permissions.agent: ["run"]`. + */ + readonly session: MiniAppSessionClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/news.mjs b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/news.mjs new file mode 100644 index 00000000..255d0675 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/news.mjs @@ -0,0 +1,205 @@ +// 新闻 RSS 抓取与解析:统一字段、过滤中国大陆官方媒体、去重。 + +import { createHash } from 'node:crypto'; +import { fetchText } from './http.mjs'; +import { isOfficialSource } from './sources.mjs'; + +const ITEM_PATTERN = /][\s\S]*?<\/item>/g; +const MAX_ITEMS_PER_SOURCE = 30; +const MAX_TOTAL_ITEMS = 150; +const SUMMARY_LIMIT = 190; + +/** + * @param {string} value + * @returns {string} + */ +export function decodeEntities(value) { + return String(value) + .replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))) + .replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16))) + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/ /g, ' ') + .replace(/&/g, '&'); +} + +/** + * @param {string} value + * @returns {string} + */ +export function stripHtml(value) { + return decodeEntities( + String(value) + .replace(//gi, ' ') + .replace(//gi, ' ') + .replace(/<[^>]+>/g, ' ') + ) + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * @param {string} block + * @param {string} tag + * @returns {string} + */ +function pickTag(block, tag) { + const match = block.match(new RegExp('<' + tag + '(?:\\s[^>]*)?>([\\s\\S]*?)<\\/' + tag + '>', 'i')); + if (!match) return ''; + return decodeEntities(match[1].replace(//g, '')).trim(); +} + +/** + * @param {string} value + * @returns {string | null} + */ +function parseDate(value) { + if (!value) return null; + const time = Date.parse(value); + if (!Number.isFinite(time)) return null; + return new Date(time).toISOString(); +} + +/** + * @param {string} url + * @returns {string | null} + */ +function hostOf(url) { + try { + return new URL(url).hostname.toLowerCase(); + } catch { + return null; + } +} + +/** + * @param {string} value + * @returns {string} + */ +function truncate(value, limit) { + if (value.length <= limit) return value; + return value.slice(0, limit).replace(/[\s,、;:,.;:]+$/, '') + '…'; +} + +/** + * @param {string} value + * @returns {string} + */ +function titleKey(value) { + return value.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, ''); +} + +/** + * 解析一个 RSS/RDF 频道。 + * @param {string} xml + * @param {{ id: string, name: string, aggregate?: boolean }} source + * @returns {{ items: any[], blocked: { name: string, count: number }[] }} + */ +export function parseFeed(xml, source) { + const items = []; + const blocked = new Map(); + for (const match of xml.matchAll(ITEM_PATTERN)) { + const block = match[0]; + const sourceMatch = block.match(/]*)>([\s\S]*?)<\/source>/i); + // 只有聚合源才把 当作真实发布者;普通频道里的 常是图片版权署名。 + const publisherName = source.aggregate && sourceMatch ? stripHtml(sourceMatch[2]) : ''; + const publisherUrl = source.aggregate && sourceMatch ? (sourceMatch[1].match(/url="([^"]+)"/i) || [])[1] || '' : ''; + const link = pickTag(block, 'link'); + const rawTitle = stripHtml(pickTag(block, 'title')); + if (!rawTitle || !link) continue; + + const publisher = publisherName || source.name; + let title = rawTitle; + if (source.aggregate && publisherName && title.endsWith(' - ' + publisherName)) { + title = title.slice(0, title.length - publisherName.length - 3).trim(); + } + + const domain = hostOf(publisherUrl) || hostOf(link); + if (isOfficialSource({ name: publisherName, domain })) { + blocked.set(publisher, (blocked.get(publisher) || 0) + 1); + continue; + } + + let summary = stripHtml(pickTag(block, 'description')); + if (source.aggregate) summary = ''; + if (summary === title) summary = ''; + + items.push({ + id: createHash('sha1').update(link).digest('hex').slice(0, 16), + sourceId: source.id, + sourceName: source.name, + publisher, + title, + summary: truncate(summary, SUMMARY_LIMIT), + url: link, + publishedAt: parseDate(pickTag(block, 'pubDate') || pickTag(block, 'dc:date')) + }); + } + return { + items: items.slice(0, MAX_ITEMS_PER_SOURCE), + blocked: [...blocked].map(([name, count]) => ({ name, count })) + }; +} + +/** + * 抓取全部新闻源。 + * @param {Array<{ id: string, name: string, url: string, aggregate?: boolean }>} sources + * @param {{ signal?: AbortSignal }} [options] + * @returns {Promise<{ items: any[], filtered: { count: number, sources: { name: string, count: number }[] }, errors: { source: string, message: string }[] }>} + */ +export async function fetchNews(sources, options = {}) { + const settled = await Promise.allSettled( + sources.map(async (source) => { + const xml = await fetchText(source.url, { timeoutMs: 20000, signal: options.signal }); + const parsed = parseFeed(xml, source); + if (!parsed.items.length && !parsed.blocked.length) { + throw new Error('未解析到任何条目'); + } + return { source, ...parsed }; + }) + ); + + const errors = []; + const blocked = new Map(); + const merged = []; + const seenIds = new Set(); + const seenTitles = new Set(); + + for (let index = 0; index < settled.length; index += 1) { + const result = settled[index]; + const source = sources[index]; + if (result.status === 'rejected') { + errors.push({ source: source.name, message: String(result.reason?.message || result.reason) }); + continue; + } + for (const entry of result.value.blocked) { + blocked.set(entry.name, (blocked.get(entry.name) || 0) + entry.count); + } + for (const item of result.value.items) { + if (seenIds.has(item.id)) continue; + const key = titleKey(item.title); + if (key && seenTitles.has(key)) continue; + seenIds.add(item.id); + if (key) seenTitles.add(key); + merged.push(item); + } + } + + merged.sort((a, b) => { + const left = a.publishedAt ? Date.parse(a.publishedAt) : 0; + const right = b.publishedAt ? Date.parse(b.publishedAt) : 0; + return right - left; + }); + + const blockedList = [...blocked] + .map(([name, count]) => ({ name, count })) + .sort((a, b) => b.count - a.count); + + return { + items: merged.slice(0, MAX_TOTAL_ITEMS), + filtered: { count: blockedList.reduce((sum, entry) => sum + entry.count, 0), sources: blockedList.slice(0, 12) }, + errors + }; +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/server.mjs b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/server.mjs new file mode 100644 index 00000000..aa25a5cd --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/server.mjs @@ -0,0 +1,259 @@ +// @ts-check + +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { NEWS_SOURCES, OFFICIAL_DOMAINS, OFFICIAL_NAMES } from './sources.mjs'; +import { fetchNews } from './news.mjs'; +import { fetchWikiDay } from './wiki.mjs'; +import { loadState, saveState } from './store.mjs'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ + +const REFRESH_INTERVAL_MS = 60 * 60 * 1000; +const SURFACE_PATH = '/briefing'; +const MAX_BODY_BYTES = 4096; +const STATIC_FILES = [ + { route: '/assets/app.js', file: 'app.js', type: 'text/javascript; charset=utf-8' }, + { route: '/assets/styles.css', file: 'styles.css', type: 'text/css; charset=utf-8' } +]; + +/** + * @param {Date} date + * @returns {string} + */ +function dateKey(date) { + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return date.getFullYear() + '-' + month + '-' + day; +} + +/** + * @param {import('node:http').ServerResponse} response + * @param {number} status + * @param {unknown} body + */ +function sendJson(response, status, body) { + const payload = JSON.stringify(body); + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store' + }); + response.end(payload); +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise} + */ +function drainBody(request) { + return new Promise((resolve) => { + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_BODY_BYTES) request.destroy(); + }); + request.on('end', () => resolve()); + request.on('error', () => resolve()); + request.on('close', () => resolve()); + }); +} + +/** + * @param {MiniAppContext} context + */ +export async function start(context) { + const clientRoot = join(context.pluginRoot, 'miniapp/client'); + const indexHtml = await readFile(join(clientRoot, 'index.html')); + const assets = []; + for (const entry of STATIC_FILES) { + assets.push({ route: entry.route, type: entry.type, body: await readFile(join(clientRoot, entry.file)) }); + } + + let state = (await loadState(context.dataDir)) || { version: 1, snapshot: null }; + /** @type {Promise | null} */ + let inflight = null; + + /** + * @param {any} snapshot + * @returns {boolean} + */ + const isStale = (snapshot) => { + if (!snapshot || !snapshot.fetchedAt) return true; + if (snapshot.dateKey !== dateKey(new Date())) return true; + return Date.now() - Date.parse(snapshot.fetchedAt) > REFRESH_INTERVAL_MS; + }; + + const refresh = () => { + if (inflight) return inflight; + inflight = (async () => { + const now = new Date(); + const previous = state.snapshot; + const [newsResult, wikiResult] = await Promise.allSettled([ + fetchNews(NEWS_SOURCES, { signal: context.signal }), + fetchWikiDay(now, { signal: context.signal }) + ]); + + const errors = []; + const news = newsResult.status === 'fulfilled' ? newsResult.value : null; + if (newsResult.status === 'rejected') { + errors.push({ source: '新闻源', message: String(newsResult.reason?.message || newsResult.reason) }); + } else { + for (const entry of news.errors) errors.push({ source: entry.source, message: entry.message }); + } + const wiki = wikiResult.status === 'fulfilled' ? wikiResult.value : null; + if (wikiResult.status === 'rejected') { + errors.push({ source: '维基百科', message: String(wikiResult.reason?.message || wikiResult.reason) }); + } else { + for (const entry of wiki.errors) errors.push({ source: entry.source, message: entry.message }); + } + + const previousIds = new Set((previous?.news || []).map((item) => item.id)); + const snapshot = { + dateKey: dateKey(now), + fetchedAt: now.toISOString(), + news: news + ? news.items.map((item) => ({ ...item, isNew: Boolean(previous) && !previousIds.has(item.id) })) + : previous?.news || [], + filtered: news ? news.filtered : previous?.filtered || { count: 0, sources: [] }, + wiki: wiki + ? { + pageTitle: wiki.pageTitle, + pageUrl: wiki.pageUrl, + events: wiki.events, + births: wiki.births, + deaths: wiki.deaths, + holidays: wiki.holidays, + featured: wiki.featured, + image: wiki.image, + featuredDateKey: wiki.featuredDateKey + } + : previous?.wiki || null, + errors + }; + state = { version: 1, snapshot }; + await saveState(context.dataDir, state); + })().finally(() => { + inflight = null; + }); + return inflight; + }; + + const payload = () => { + const snapshot = state.snapshot; + const fetchedAt = snapshot?.fetchedAt ? Date.parse(snapshot.fetchedAt) : 0; + return { + now: new Date().toISOString(), + refreshing: Boolean(inflight), + stale: isStale(snapshot), + intervalMinutes: REFRESH_INTERVAL_MS / 60000, + nextRefreshAt: fetchedAt ? new Date(fetchedAt + REFRESH_INTERVAL_MS).toISOString() : null, + sources: NEWS_SOURCES.map((source) => ({ + id: source.id, + name: source.name, + site: source.site, + aggregate: Boolean(source.aggregate) + })), + filter: { names: OFFICIAL_NAMES.length, domains: OFFICIAL_DOMAINS.length }, + snapshot + }; + }; + + /** + * @param {import('node:http').IncomingMessage} request + * @param {import('node:http').ServerResponse} response + */ + const handle = async (request, response) => { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + + if (request.method === 'GET' && (path === SURFACE_PATH || path === '/')) { + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); + response.end(indexHtml); + return; + } + + if (request.method === 'GET') { + const asset = assets.find((entry) => entry.route === path); + if (asset) { + response.writeHead(200, { 'content-type': asset.type, 'cache-control': 'no-store' }); + response.end(asset.body); + return; + } + } + + if (request.method === 'GET' && path === '/api/briefing') { + if (isStale(state.snapshot)) { + try { + await refresh(); + } catch (error) { + context.logger.warn('miniapp.refresh.failed', { message: String(error?.message || error) }); + } + } + sendJson(response, 200, payload()); + return; + } + + if (request.method === 'POST' && path === '/api/refresh') { + await drainBody(request); + try { + await refresh(); + } catch (error) { + context.logger.warn('miniapp.refresh.failed', { message: String(error?.message || error) }); + sendJson(response, 502, { error: 'refresh_failed', message: '抓取失败,请稍后重试' }); + return; + } + sendJson(response, 200, payload()); + return; + } + + if (request.method === 'POST' && path === '/api/seen') { + await drainBody(request); + const snapshot = state.snapshot; + if (snapshot && snapshot.news.some((item) => item.isNew)) { + snapshot.news = snapshot.news.map((item) => (item.isNew ? { ...item, isNew: false } : item)); + state = { version: 1, snapshot }; + await saveState(context.dataDir, state); + } + sendJson(response, 200, payload()); + return; + } + + sendJson(response, 404, { error: 'not_found' }); + }; + + const server = createServer((request, response) => { + void handle(request, response).catch((error) => { + context.logger.warn('miniapp.request.failed', { message: String(error?.message || error) }); + if (!response.headersSent) sendJson(response, 500, { error: 'internal_error' }); + else response.end(); + }); + }); + + await new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', onError); + resolve(); + }); + }); + context.logger.info('miniapp.runtime.listening'); + + let disposal; + const dispose = () => { + if (disposal) return disposal; + context.signal.removeEventListener('abort', onAbort); + disposal = new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + return disposal; + }; + const onAbort = () => { + void dispose().catch(() => undefined); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/sources.mjs b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/sources.mjs new file mode 100644 index 00000000..ca38c046 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/sources.mjs @@ -0,0 +1,73 @@ +// 新闻源与「中国大陆官方媒体」过滤规则。 +// 口径:只排除中国大陆官方媒体,其余境外与独立媒体全部保留。 + +export const NEWS_SOURCES = [ + { id: 'bbc', name: 'BBC 中文', url: 'https://feeds.bbci.co.uk/zhongwen/simp/rss.xml', site: 'https://www.bbc.com/zhongwen/simp' }, + { id: 'dw', name: '德国之声', url: 'https://rss.dw.com/rdf/rss-chi-all', site: 'https://www.dw.com/zh/' }, + { id: 'rfi', name: '法广 RFI', url: 'https://www.rfi.fr/cn/rss', site: 'https://www.rfi.fr/cn/' }, + { id: 'cna', name: '中央社', url: 'https://feeds.feedburner.com/rsscna/intworld', site: 'https://www.cna.com.tw/list/aopl.aspx' }, + { id: 'nyt', name: '纽约时报中文网', url: 'https://cn.nytimes.com/rss.html', site: 'https://cn.nytimes.com' }, + { + id: 'gnews', + name: 'Google 新闻聚合', + url: 'https://news.google.com/rss?hl=zh-CN&gl=CN&ceid=CN:zh-Hans', + site: 'https://news.google.com/?hl=zh-CN&gl=CN&ceid=CN:zh-Hans', + aggregate: true + } +]; + +// 中央级官方媒体与机构名称。 +export const OFFICIAL_NAMES = [ + '新华社', '新华网', '新华每日电讯', '人民日报', '人民日报海外版', '人民网', '央视新闻', '央视网', '央视财经', + '中国新闻网', '中新网', '中新经纬', '中国新闻周刊', '环球时报', '环球网', '光明日报', '光明网', '经济日报', + '中国经济网', '科技日报', '中国日报', '中国日报网', '解放军报', '中国军网', '求是', '求是网', '央广网', + '中国广播网', '国际在线', '中国网', '参考消息', '人民政协报', '中国青年报', '中青在线', '农民日报', '工人日报', + '法治日报', '检察日报', '证券日报', '上海证券报', '中国证券报', '学习强国', '半月谈', '瞭望', '瞭望东方周刊', + '中国台湾网', '中国西藏网', '中国新疆网', '中国社会科学网', '党建网', '红旗文稿', '宣讲家网', '理论中国', + '中国政府网', '共产党员网', '中国气象局', '中国地震台网', '中央纪委国家监委', '最高人民检察院', '最高人民法院', + '全国人大', '全国政协', '外交部', '商务部', '财政部', '教育部', '公安部', '国防部', '国家发改委', '国家统计局', + '海关总署', '中国人民银行', '工业和信息化部', '国务院新闻办公室', '国务院国资委', '农业农村部', '交通运输部', + '国家卫健委', '国家能源局', + // 省市级党报与机关报 + '北京日报', '解放日报', '文汇报', '新民晚报', '天津日报', '河北日报', '山西日报', '内蒙古日报', '辽宁日报', + '吉林日报', '黑龙江日报', '新华日报', '浙江日报', '安徽日报', '福建日报', '江西日报', '大众日报', '河南日报', + '湖北日报', '湖南日报', '南方日报', '羊城晚报', '广西日报', '海南日报', '重庆日报', '四川日报', '贵州日报', + '云南日报', '西藏日报', '陕西日报', '甘肃日报', '青海日报', '宁夏日报', '新疆日报', '兵团日报', '长江日报', + '成都日报', '广州日报', '深圳特区报', '杭州日报', '南京日报', '济南日报', '青岛日报', '厦门日报', '福州日报', + '长沙晚报', '郑州晚报', + // 英文官方媒体 + 'Xinhua', 'People\'s Daily', 'China Daily', 'Global Times', 'CCTV', 'CGTN', 'CNR', 'CRI' +]; + +// 官方媒体域名(精确匹配或作为子域后缀)。 +export const OFFICIAL_DOMAINS = [ + 'news.cn', 'xinhuanet.com', 'xinhuanet.cn', 'people.com.cn', 'people.cn', 'cctv.com', 'cctv.cn', 'chinanews.com', + 'chinanews.com.cn', 'globaltimes.cn', 'gmw.cn', 'ce.cn', 'stdaily.com', 'chinadaily.com.cn', 'chinadaily.com', + 'qstheory.cn', '81.cn', 'cnr.cn', 'cri.cn', 'cgtn.com', 'china.com.cn', 'gov.cn', 'cankaoxiaoxi.com', + 'banyuetan.org', '12371.cn', 'xuexi.cn', 'cnjiwang.com', 'scol.com.cn', 'infomorning.com', 'cyol.com', + 'workercn.cn', 'farmer.com.cn', 'legaldaily.com.cn', 'spp.gov.cn', 'court.gov.cn', 'npc.gov.cn', 'cppcc.gov.cn', + 'mfa.gov.cn', 'mofcom.gov.cn', 'mof.gov.cn', 'moe.gov.cn', 'mps.gov.cn', 'mod.gov.cn', 'ndrc.gov.cn', + 'stats.gov.cn', 'customs.gov.cn', 'pbc.gov.cn', 'cma.gov.cn', 'weather.com.cn', 'ecns.cn' +]; + +// 「XX日报」形式的地方党报(1-3 个汉字 + 日报),如「湖北日报」「内蒙古日报」。 +const DAILY_PATTERN = /^[\u4e00-\u9fa5]{1,3}日报$/; + +/** + * 判断一个来源是否属于被排除的中国大陆官方媒体。 + * @param {{ name?: string | null, domain?: string | null }} source + * @returns {boolean} + */ +export function isOfficialSource(source) { + const name = (source?.name || '').trim(); + const domain = (source?.domain || '').trim().toLowerCase().replace(/^www\./, ''); + if (name) { + if (OFFICIAL_NAMES.some((official) => name === official || name.includes(official))) return true; + if (DAILY_PATTERN.test(name)) return true; + } + if (domain) { + if (domain === 'gov.cn' || domain.endsWith('.gov.cn')) return true; + if (OFFICIAL_DOMAINS.some((official) => domain === official || domain.endsWith('.' + official))) return true; + } + return false; +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/store.mjs b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/store.mjs new file mode 100644 index 00000000..5eb0522e --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/store.mjs @@ -0,0 +1,34 @@ +// 快照持久化:写入 dataDir,原子替换,避免被强制结束时留下半个文件。 + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +const FILE_NAME = 'briefing-state.json'; + +/** + * @param {string} dataDir + * @returns {Promise} + */ +export async function loadState(dataDir) { + try { + const raw = await readFile(join(dataDir, FILE_NAME), 'utf8'); + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== 'object' || parsed.version !== 1) return null; + return parsed; + } catch { + return null; + } +} + +/** + * @param {string} dataDir + * @param {any} state + * @returns {Promise} + */ +export async function saveState(dataDir, state) { + await mkdir(dataDir, { recursive: true }); + const target = join(dataDir, FILE_NAME); + const temporary = target + '.tmp'; + await writeFile(temporary, JSON.stringify(state), 'utf8'); + await rename(temporary, target); +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/wiki.mjs b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/wiki.mjs new file mode 100644 index 00000000..f3099ad7 --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/miniapp/node/wiki.mjs @@ -0,0 +1,365 @@ +// 中文维基百科抓取:日期页(历史上的今天 / 出生 / 逝世 / 节假日)与每日特色 feed。 +// 整页只请求一次,再按 h2 标题切片,尽量少打扰维基接口。 + +import { fetchJson } from './http.mjs'; +import { stripHtml } from './news.mjs'; + +const API = 'https://zh.wikipedia.org/w/api.php'; +const FEED = 'https://zh.wikipedia.org/api/rest_v1/feed/featured'; +const PERSON_ENRICH_LIMIT = 10; +const EXTRACT_LIMIT = 20; + +/** + * @param {string} html + * @returns {string} + */ +function cleanWiki(html) { + return tidySpacing( + stripHtml( + String(html) + .replace(//gi, ' ') + .replace(//gi, ' ') + .replace(//gi, ' ') + ) + ); +} + +/** + * 去掉中文与全角标点之间因标签剥离产生的多余空格。 + * @param {string} value + * @returns {string} + */ +function tidySpacing(value) { + const cjk = '\\u3000-\\u303f\\u4e00-\\u9fff\\uff00-\\uffef'; + return String(value) + .replace(new RegExp('([' + cjk + '])\\s+', 'g'), '$1') + .replace(new RegExp('\\s+([' + cjk + '])', 'g'), '$1') + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * @param {string} html + * @returns {string[]} + */ +function listItems(html) { + return [...html.matchAll(/]*>([\s\S]*?)<\/li>/g)].map((match) => match[1]); +} + +/** + * @param {string} html + * @returns {{ title: string, text: string, url: string }[]} + */ +function anchors(html) { + return [...html.matchAll(/]*href="\/wiki\/([^"#?]+)"[^>]*>([\s\S]*?)<\/a>/g)].map((match) => ({ + title: decodeURIComponent(match[1]).replace(/_/g, ' '), + text: cleanWiki(match[2]), + url: 'https://zh.wikipedia.org/wiki/' + match[1] + })); +} + +/** + * @param {string} value + * @param {number} limit + * @returns {string} + */ +function truncate(value, limit) { + const text = tidySpacing(String(value || '')); + if (text.length <= limit) return text; + return text.slice(0, limit).replace(/[\s,、;:,.;:]+$/, '') + '…'; +} + +/** + * @param {string} year + * @returns {number} + */ +function yearNumber(year) { + const value = Number(String(year).replace('前', '')); + return String(year).startsWith('前') ? -value : value; +} + +/** + * 按 h2 标题把整页 HTML 切成若干节。 + * @param {string} html + * @returns {{ id: string, start: number, end: number }[]} + */ +export function splitSections(html) { + const boundaries = [...html.matchAll(/]*\sid="([^"]*)"[^>]*>/g)].map((match) => ({ + id: decodeURIComponent(match[1]), + start: match.index ?? 0 + })); + return boundaries.map((boundary, index) => ({ + id: boundary.id, + start: boundary.start, + end: index + 1 < boundaries.length ? boundaries[index + 1].start : html.length + })); +} + +/** + * @param {string} html + * @returns {{ year: string, text: string, links: { title: string, url: string }[] }[]} + */ +export function parseEvents(html) { + const events = []; + for (const item of listItems(html)) { + const text = cleanWiki(item); + const yearMatch = text.match(/^(前?\d+)年/); + if (!yearMatch) continue; + const body = text.slice(yearMatch[0].length).replace(/^[::\s]+/, '').trim(); + if (body.length < 4) continue; + const links = anchors(item) + .filter((link) => link.text && !/^前?\d+年$/.test(link.text)) + .slice(0, 3) + .map((link) => ({ title: link.text, url: link.url })); + events.push({ year: yearMatch[1], text: body, links }); + } + return events; +} + +/** + * @param {string} html + * @returns {{ year: string, name: string, description: string, pageTitle: string | null, url: string | null, extract: string | null, thumb: string | null }[]} + */ +export function parsePersons(html) { + const persons = []; + for (const item of listItems(html)) { + const text = cleanWiki(item); + const match = text.match(/^(前?\d+)年[::]\s*(.+)$/); + if (!match) continue; + const rest = match[2].trim(); + const personLink = anchors(item).find((link) => link.text && !/^前?\d+年$/.test(link.text)); + const name = personLink ? personLink.text : rest.split(/[,,((]/)[0].trim(); + if (!name) continue; + const description = rest.startsWith(name) + ? rest.slice(name.length).replace(/^[,,、::\s]+/, '').trim() + : rest; + persons.push({ + year: match[1], + name, + description, + pageTitle: personLink ? personLink.title : null, + url: personLink ? personLink.url : null, + extract: null, + thumb: null + }); + } + return persons; +} + +/** + * 维基接口限流保护:串行排队 + 429/5xx 退避重试。 + * @type {number} + */ +let lastWikiRequestAt = 0; +const MIN_GAP_MS = 400; + +/** + * @param {number} ms + * @param {AbortSignal | undefined} signal + */ +function sleep(ms, signal) { + return new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + if (signal) { + signal.addEventListener( + 'abort', + () => { + clearTimeout(timer); + resolve(); + }, + { once: true } + ); + } + }); +} + +/** + * @param {string} url + * @param {{ timeoutMs?: number, signal?: AbortSignal }} [options] + * @returns {Promise} + */ +async function wikiJson(url, options = {}) { + for (let attempt = 0; attempt < 4; attempt += 1) { + const wait = lastWikiRequestAt + MIN_GAP_MS - Date.now(); + if (wait > 0) await sleep(wait, options.signal); + lastWikiRequestAt = Date.now(); + try { + return await fetchJson(url, options); + } catch (error) { + const message = String(error?.message || error); + const retryable = /HTTP (429|500|502|503|504)/.test(message) || message === 'timeout'; + if (!retryable || attempt === 3) throw error; + await sleep(1500 * (attempt + 1), options.signal); + } + } + throw new Error('维基接口重试失败'); +} + +/** + * 一次请求为出生与逝世人物补充中文维基导语与缩略图。 + * @param {any[]} groups + * @param {{ signal?: AbortSignal }} options + */ +async function enrichPersons(groups, options) { + const selected = groups.flatMap((list) => list.filter((person) => person.pageTitle).slice(-PERSON_ENRICH_LIMIT)); + const titles = [...new Set(selected.map((person) => person.pageTitle))].slice(0, EXTRACT_LIMIT); + if (!titles.length) return; + const url = + API + + '?action=query&prop=extracts|pageimages|info&exintro=1&explaintext=1&inprop=url&piprop=thumbnail&pithumbsize=240' + + '&redirects=1&format=json&formatversion=2&variant=zh-cn&titles=' + + encodeURIComponent(titles.join('|')); + const json = await wikiJson(url, { timeoutMs: 20000, signal: options.signal }); + const pages = json?.query?.pages || []; + const byTitle = new Map(pages.map((page) => [page.title, page])); + const alias = new Map(); + for (const entry of json?.query?.normalized || []) alias.set(entry.from, entry.to); + for (const entry of json?.query?.redirects || []) alias.set(entry.from, entry.to); + const resolve = (title) => { + let current = title; + for (let step = 0; step < 4; step += 1) { + const next = alias.get(current); + if (!next) break; + current = next; + } + return byTitle.get(current); + }; + for (const person of selected) { + const page = resolve(person.pageTitle); + if (!page) continue; + person.url = page.fullurl || person.url; + person.thumb = page.thumbnail?.source || null; + const extract = truncate(page.extract || '', 190); + person.extract = extract || null; + } +} + +/** + * @param {Date} date + * @param {{ signal?: AbortSignal }} options + */ +async function fetchFeatured(date, options) { + for (const offset of [0, -1]) { + const target = new Date(date.getTime() + offset * 86400000); + const year = target.getFullYear(); + const month = String(target.getMonth() + 1).padStart(2, '0'); + const day = String(target.getDate()).padStart(2, '0'); + try { + const json = await wikiJson(FEED + '/' + year + '/' + month + '/' + day + '?variant=zh-cn', { + timeoutMs: 20000, + signal: options.signal + }); + if (!json?.tfa && !json?.image) continue; + const tfa = json.tfa; + const image = json.image; + return { + dateKey: year + '-' + month + '-' + day, + featured: tfa + ? { + title: cleanWiki(tfa.normalizedtitle || tfa.title || ''), + description: tfa.description ? cleanWiki(tfa.description) : null, + extract: truncate(tfa.extract || '', 260), + url: tfa.content_urls?.desktop?.page || null, + thumb: tfa.thumbnail?.source || null + } + : null, + image: image + ? { + title: cleanWiki(image.title || '').replace(/^File:/i, '').replace(/^文件:/, ''), + description: truncate(image.description?.text || '', 200), + thumb: image.thumbnail?.source || image.image?.source || null, + page: typeof image.file_page === 'string' ? image.file_page : null, + artist: cleanWiki(image.artist?.text || '') || null + } + : null + }; + } catch { + // 尝试前一天 + } + } + return null; +} + +/** + * 抓取某一天的维基内容。 + * @param {Date} date + * @param {{ signal?: AbortSignal }} [options] + */ +export async function fetchWikiDay(date, options = {}) { + const month = date.getMonth() + 1; + const day = date.getDate(); + const pageTitle = month + '月' + day + '日'; + const errors = []; + + const pageJson = await wikiJson( + API + + '?action=parse&page=' + + encodeURIComponent(pageTitle) + + '&prop=text&format=json&formatversion=2&variant=zh-cn&redirects=1', + { timeoutMs: 25000, signal: options.signal } + ); + const html = pageJson?.parse?.text; + if (typeof html !== 'string' || !html.length) throw new Error('日期页内容不可用'); + + const sections = splitSections(html); + const findSection = (pattern) => sections.find((section) => pattern.test(section.id)); + const eventsSection = findSection(/大事[记記]/); + const birthsSection = findSection(/^出生$/); + const deathsSection = findSection(/^逝世$/); + const holidaysSection = findSection(/节假|節假|节日|節日/); + if (!eventsSection && !birthsSection && !deathsSection) throw new Error('日期页缺少大事记与人物章节'); + + const slice = (section) => (section ? html.slice(section.start, section.end) : ''); + const events = eventsSection + ? parseEvents(html.slice(eventsSection.start, birthsSection ? birthsSection.start : eventsSection.end)) + : []; + const births = parsePersons(slice(birthsSection)); + const deaths = parsePersons(slice(deathsSection)); + const holidays = []; + for (const item of listItems(slice(holidaysSection))) { + const text = cleanWiki(item); + if (text.length >= 2 && !holidays.includes(text)) holidays.push(text); + } + + const seenEvents = new Set(); + const uniqueEvents = events + .filter((event) => { + const key = event.year + '|' + event.text; + if (seenEvents.has(key)) return false; + seenEvents.add(key); + return true; + }) + .sort((a, b) => yearNumber(b.year) - yearNumber(a.year)); + + try { + await enrichPersons([births, deaths], options); + } catch (error) { + errors.push({ source: '维基·人物导语', message: String(error?.message || error) }); + } + + // 展示顺序:年份由近到远,带导语与照片的最近若干位排在最前。 + const byYearDesc = (left, right) => yearNumber(right.year) - yearNumber(left.year); + births.sort(byYearDesc); + deaths.sort(byYearDesc); + + let featuredInfo = null; + try { + featuredInfo = await fetchFeatured(date, options); + } catch (error) { + errors.push({ source: '维基·每日特色', message: String(error?.message || error) }); + } + if (!featuredInfo) errors.push({ source: '维基·每日特色', message: '未取到当日特色内容' }); + + return { + pageTitle, + pageUrl: 'https://zh.wikipedia.org/wiki/' + encodeURIComponent(pageTitle), + events: uniqueEvents, + births, + deaths, + holidays, + featured: featuredInfo?.featured || null, + image: featuredInfo?.image || null, + featuredDateKey: featuredInfo?.dateKey || null, + errors + }; +} diff --git a/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/package.json b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/llsktsl-debug/miniapp-52d26296-e0f9-462a-ab2f-e917d2508233/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}