dsh-skillpie-mail 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/lib/client.js +116 -555
  2. package/lib/index.js +270 -2
  3. package/package.json +2 -4
package/lib/client.js CHANGED
@@ -944,12 +944,11 @@ window.__ModuleLoader__.load({
944
944
  /* ── 注册 ───────────────────────────────────────────────────────── */
945
945
 
946
946
  // ======================================================================
947
- // dsh-plugins-plugin:精选推荐(内联模块,自动插入,请勿手改)
948
947
  // 注入在 factory(require) 内,可用 factory 的 require 取 react;
949
948
  // apply 末尾通过 window.__DSH_FEATURED_INIT__(ctx) 注册 tab。
950
949
  // ======================================================================
951
- // >>> dsh-plugins-plugin featured inline (auto-inserted, do not remove markers)
952
- // dsh-plugins-plugin — 精选推荐 client 内联模块(embed/featured.client.js)。
950
+ // >>> dsh-featured inline (auto-inserted, do not remove markers)
951
+ // 精选插件 client 内联模块(由 dsh-featured 的 integrate.sh 自动插入)。
953
952
  // 这是一段"函数体片段",由 integrate.sh 注入到接入插件 lib/client.js 的
954
953
  // factory(require) 内部(MARK 之间的内容),因此可以直接用 factory 的 require
955
954
  // 拿 react,并暴露 window.__DSH_FEATURED_INIT__(ctx) 供 apply 末尾调用。
@@ -958,570 +957,132 @@ window.__ModuleLoader__.load({
958
957
  // ?rev= 精确匹配,一旦接入包自己的 bundle 加载失败(如 dsh-app:// 404),
959
958
  // chunk 永远到不了;内联后 tab 跟随接入插件自己的 bundle,零额外请求。
960
959
  // 注意:本片段绝不能放到 factory 之外 —— 那样 require 会落到 Node 全局。
960
+ //
961
+ // 本片段只做「极简入口」:注册精选插件 tab,点开自动安装完整版 dsh-featured,
962
+ // 装完由它接管完整功能。卡片/详情/搜索/筛选/申请收录等重逻辑都不在此,
963
+ // 全部交给 dsh-featured,这样接入插件只需背上极小的一段代码。
961
964
  ;(function () {
962
965
  window.__FEATURED_FACTORY_RAN__ = true
963
966
  try {
964
- const React = require('react')
965
- const h = React.createElement
966
-
967
- const NS = 'dsh-plugins-plugin'
968
- const ROUTE = '/dsh-plugins-plugin/featured'
969
- // 数据统一由宿主半提供:host 拉远程集中目录(node fetch,无浏览器缓存/CORS)
970
- // 并合并接入插件登记源,client 只读本地路由,永远新鲜。
971
-
972
- function fetchJson(url, timeoutMs) {
973
- const ctrl = typeof AbortController === 'function' ? new AbortController() : null
974
- const timer = setTimeout(() => ctrl && ctrl.abort(), timeoutMs)
975
- return fetch(url, { cache: 'no-store', headers: { accept: 'application/json' }, signal: ctrl ? ctrl.signal : undefined })
976
- .then((res) => {
977
- if (!res.ok) throw new Error('HTTP ' + res.status)
978
- return res.json()
979
- })
980
- .finally(() => clearTimeout(timer))
981
- }
982
-
983
- function fetchText(url, timeoutMs) {
984
- const ctrl = typeof AbortController === 'function' ? new AbortController() : null
985
- const timer = setTimeout(() => ctrl && ctrl.abort(), timeoutMs)
986
- return fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
987
- .then((res) => {
988
- if (!res.ok) throw new Error('HTTP ' + res.status)
989
- return res.text()
990
- })
991
- .finally(() => clearTimeout(timer))
992
- }
993
-
994
- // 远程条目规范化(与 host 半 normalizeEntry 对齐的宽松版)。
995
- // 富字段(author/stars/downloads/screenshots 等)由 scripts/enrich.mjs
996
- // 在构建期从 awesome-dsh-plugin 官方目录 join 进来,这里原样放行。
997
- function normalizeRemoteEntry(raw) {
998
- if (!raw || typeof raw !== 'object') return null
999
- const pkg = String(raw.package || raw.name || '').trim()
1000
- const title = String(raw.title || '').trim()
1001
- if (!pkg || !title) return null
1002
- const entry = { package: pkg, title, source: 'plugins.json' }
1003
- for (const key of ['description', 'version', 'icon', 'homepage', 'author', 'category']) {
1004
- const v = String(raw[key] || '').trim()
1005
- if (v) entry[key] = v
1006
- }
1007
- if (Array.isArray(raw.screenshots)) {
1008
- const shots = raw.screenshots.map((x) => String(x).trim()).filter(Boolean).slice(0, 2)
1009
- if (shots.length) entry.screenshots = shots
1010
- }
1011
- if (typeof raw.stars === 'number' && raw.stars >= 0) entry.stars = raw.stars
1012
- if (typeof raw.downloads === 'number' && raw.downloads >= 0) entry.downloads = raw.downloads
1013
- if (Array.isArray(raw.tags)) {
1014
- const tags = raw.tags.map((x) => String(x).trim()).filter(Boolean).slice(0, 8)
1015
- if (tags.length) entry.tags = tags
1016
- }
1017
- return entry
1018
- }
1019
-
1020
- // 数值缩写:586200 → 586.2k,1200000 → 1.2m。
1021
- function fmtCount(n) {
1022
- if (n >= 1e6) return (Math.round(n / 1e5) / 10) + 'm'
1023
- if (n >= 1e3) return (Math.round(n / 100) / 10) + 'k'
1024
- return String(n)
1025
- }
1026
-
1027
- // raw.githubusercontent 在国内常不可达;转 jsdelivr gh 镜像再失败则放弃。
1028
- function shotCandidates(url) {
1029
- const match = String(url).match(/^https?:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/(HEAD|[0-9a-fA-F]{6,}|[^/]+)\/(.+)$/)
1030
- if (!match) return [url]
1031
- const [, owner, repo, ref, file] = match
1032
- const branch = ref === 'HEAD' ? 'main' : ref
1033
- return [
1034
- `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${branch}/${file}`,
1035
- url,
1036
- `https://cdn.jsdelivr.net/gh/${owner}/${repo}@master/${file}`,
1037
- ]
1038
- }
1039
-
1040
- // 合并已移到宿主半(host 侧远程目录 + 登记源,按包名去重)。
1041
-
1042
- const zh = {
1043
- tabLabel: '精选推荐',
1044
- title: '精选插件',
1045
- subtitle: '来自接入插件的推荐,可一键安装',
1046
- install: '安装',
1047
- installed: '已安装',
1048
- empty: '暂无精选内容:接入插件可通过 dsh-plugins-plugin 的 integrate.sh 推荐插件',
1049
- loading: '加载中…',
1050
- error: '加载失败',
1051
- retry: '重试',
1052
- recommendedBy: '推荐',
1053
- tags: '标签',
1054
- close: '关闭',
1055
- readmeLoading: 'README 加载中…',
1056
- readmeError: 'README 读取失败',
1057
- }
1058
- const en = {
1059
- tabLabel: 'Featured',
1060
- title: 'Featured Plugins',
1061
- subtitle: 'Recommended by integrated plugins, one-click install',
1062
- install: 'Install',
1063
- installed: 'Installed',
1064
- empty: 'Nothing featured yet: plugins can recommend entries via dsh-plugins-plugin integrate.sh',
1065
- loading: 'Loading…',
1066
- error: 'Failed to load',
1067
- retry: 'Retry',
1068
- recommendedBy: 'Recommended by',
1069
- tags: 'Tags',
1070
- close: 'Close',
1071
- readmeLoading: 'Loading README…',
1072
- readmeError: 'Failed to load README',
1073
- }
1074
-
1075
- const S = {
1076
- wrap: { padding: '12px 0 24px', display: 'flex', flexDirection: 'column', gap: 12 },
1077
- // 官方 Discover 同款瀑布流:CSS 多列,卡片高度不一自然堆叠
1078
- grid: { listStyle: 'none', margin: 0, padding: 0, columns: '300px', columnGap: 12 },
1079
- card: {
1080
- breakInside: 'avoid', WebkitColumnBreakInside: 'avoid', marginBottom: 12,
1081
- display: 'flex', flexDirection: 'column', gap: 8, padding: 14,
1082
- border: '1px solid var(--dsw-alias-border-l1)',
1083
- borderRadius: 12, background: 'var(--dsw-alias-bg-layer-2)',
1084
- },
1085
- head: { display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 },
1086
- // 插件名 + GitHub 图标紧贴成组,右侧留给 安装按钮/已安装徽标
1087
- nameWrap: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0, flex: '1 1 auto' },
1088
- title: {
1089
- fontSize: 15, fontWeight: 600, color: 'var(--dsw-alias-label-primary)', minWidth: 0,
1090
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: 'pointer',
1091
- },
1092
- ghLink: { display: 'flex', flex: 'none', color: 'var(--dsw-alias-label-secondary)', textDecoration: 'none' },
1093
- ghIcon: { width: 15, height: 15, fill: 'currentColor' },
1094
- badge: { flex: 'none', fontSize: 12, color: 'var(--dsw-alias-state-success-primary)' },
1095
- iconS: { width: 20, height: 20, borderRadius: 6, objectFit: 'contain', flex: 'none', display: 'block' },
1096
- // 作者行 + 数据行合并为一行:左头像+作者,右 v·↓·★
1097
- authorRow: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0, marginTop: -4, cursor: 'pointer' },
1098
- avatar: { width: 14, height: 14, borderRadius: 999, flex: 'none', display: 'block' },
1099
- author: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
1100
- meta: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', flex: 'none', marginLeft: 'auto' },
1101
- desc: {
1102
- margin: 0, fontSize: 13, lineHeight: 1.6, color: 'var(--dsw-alias-label-primary)', cursor: 'pointer',
1103
- display: '-webkit-box', WebkitLineClamp: 4, WebkitBoxOrient: 'vertical', overflow: 'hidden',
1104
- },
1105
- shots: { display: 'flex', gap: 8 },
1106
- shot: {
1107
- display: 'block', flex: 1, minWidth: 0, height: 104, objectFit: 'cover', objectPosition: 'top',
1108
- borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1)', background: 'var(--dsw-alias-bg-layer-1)', cursor: 'pointer',
1109
- },
1110
- foot: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 'auto', paddingTop: 4 },
1111
- chips: { display: 'flex', flexWrap: 'wrap', gap: 6, flex: '1 1 auto', minWidth: 0 },
1112
- chip: { fontSize: 12, padding: '3px 10px', borderRadius: 999, border: '1px solid var(--dsw-alias-border-l1)', color: 'var(--dsw-alias-label-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 180 },
1113
- src: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
1114
- btn: {
1115
- flex: 'none', cursor: 'pointer', font: 'inherit', fontSize: 12,
1116
- padding: '4px 14px', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1)',
1117
- background: 'var(--dsw-alias-bg-layer-1)', color: 'var(--dsw-alias-label-primary)',
1118
- },
1119
- btnBusy: { opacity: 0.6, cursor: 'default' },
1120
- note: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
1121
- retryBtn: {
1122
- alignSelf: 'flex-start', cursor: 'pointer', font: 'inherit', fontSize: 12,
1123
- padding: '4px 14px', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1)',
1124
- background: 'transparent', color: 'var(--dsw-alias-label-primary)',
1125
- },
1126
- // ── 自建详情弹窗(README 从 npm 包 jsdelivr 读取) ──
1127
- overlay: { position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 },
1128
- panel: {
1129
- width: 'min(860px, 92vw)', maxHeight: '84vh', display: 'flex', flexDirection: 'column',
1130
- background: 'var(--dsw-alias-bg-layer-2)', border: '1px solid var(--dsw-alias-border-l1)',
1131
- borderRadius: 14, boxShadow: '0 12px 40px rgba(0,0,0,0.25)', overflow: 'hidden',
1132
- },
1133
- panelHead: { display: 'flex', alignItems: 'flex-start', gap: 12, padding: '16px 16px 12px' },
1134
- panelIcon: { width: 44, height: 44, borderRadius: 10, objectFit: 'contain', flex: 'none', background: 'var(--dsw-alias-bg-layer-1)' },
1135
- panelTitleCol: { display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0, flex: '1 1 auto' },
1136
- panelTitle: { fontSize: 17, fontWeight: 600, color: 'var(--dsw-alias-label-primary)', margin: 0 },
1137
- panelPkg: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
1138
- panelClose: {
1139
- flex: 'none', cursor: 'pointer', font: 'inherit', fontSize: 12, border: 'none', background: 'transparent',
1140
- color: 'var(--dsw-alias-label-secondary)', padding: '4px 6px',
1141
- },
1142
- panelMeta: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', padding: '0 16px 10px', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
1143
- panelDesc: { margin: '0 16px 12px', fontSize: 13, lineHeight: 1.6, color: 'var(--dsw-alias-label-primary)' },
1144
- panelBody: { margin: '0 16px', borderTop: '1px solid var(--dsw-alias-border-l1)', padding: '14px 2px 18px', overflowY: 'auto', fontSize: 13, lineHeight: 1.7, color: 'var(--dsw-alias-label-primary)' },
1145
- mdNote: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
1146
- mdH: { fontSize: 15, fontWeight: 600, margin: '18px 0 8px' },
1147
- mdH2: { fontSize: 14, fontWeight: 600, margin: '16px 0 6px' },
1148
- mdP: { margin: '0 0 10px' },
1149
- mdList: { margin: '0 0 10px', paddingLeft: 20 },
1150
- mdLi: { margin: '0 0 4px' },
1151
- mdImg: { display: 'block', maxWidth: '100%', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1)', margin: '8px 0' },
1152
- mdCode: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 12, background: 'var(--dsw-alias-bg-layer-1)', borderRadius: 4, padding: '1px 5px' },
1153
- mdPre: { background: 'var(--dsw-alias-bg-layer-1)', border: '1px solid var(--dsw-alias-border-l1)', borderRadius: 8, padding: 12, overflowX: 'auto', margin: '0 0 10px' },
1154
- mdPreCode: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 12, whiteSpace: 'pre-wrap', margin: 0 },
1155
- mdA: { color: 'var(--dsw-alias-link)' },
1156
- linkIcon: { width: 11, height: 11, marginRight: 3, verticalAlign: '-1px', color: 'var(--dsw-alias-link)' },
1157
- mdQuote: { borderLeft: '3px solid var(--dsw-alias-border-l1)', paddingLeft: 12, margin: '0 0 12px', color: 'var(--dsw-alias-label-secondary)' },
1158
- mdTable: { borderCollapse: 'collapse', width: '100%', margin: '0 0 12px', fontSize: 12.5 },
1159
- mdTd: { border: '1px solid var(--dsw-alias-border-l1)', padding: '6px 10px', textAlign: 'left', verticalAlign: 'top' },
1160
- }
1161
-
1162
- // GitHub mark(octicon mark-github 16x16 路径)
1163
- const GH_PATH = 'M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z'
1164
-
1165
- // 包名行:npm 包名(左,等宽)+ 数据(右,同行);整行可点开详情弹窗。
1166
- // 不展示作者信息(不依赖 awesome-dsh-plugin 的 author 字段)。
1167
- function FeaturedAuthor(props) {
1168
- const pkg = props.pkg
1169
- const meta = props.meta
1170
- const onDetail = props.onDetail
1171
- if (!pkg && !meta) return null
1172
- return h('div', { style: S.authorRow, onClick: onDetail },
1173
- pkg ? h('span', { style: S.author }, pkg) : null,
1174
- meta ? h('span', { style: S.meta }, meta) : null)
1175
- }
1176
-
1177
- // 截图:逐个候选地址回退(jsdelivr gh 镜像 → 原始 raw → master 分支),全失败则隐藏。
1178
- function FeaturedShot(props) {
1179
- const url = props.url
1180
- const pair = React.useState(0)
1181
- const idx = pair[0], setIdx = pair[1]
1182
- const candidates = React.useMemo(() => shotCandidates(url), [url])
1183
- if (idx >= candidates.length) return null
1184
- return h('img', {
1185
- src: candidates[idx], alt: '', style: S.shot, loading: 'lazy',
1186
- onError: () => setIdx(idx + 1),
1187
- onClick: () => window.open(candidates[idx], '_blank', 'noopener'),
1188
- })
1189
- }
1190
-
1191
- // 卡片布局对齐官方 Discover:
1192
- // 标题行(标题 + GitHub 链接) → 作者行(头像+作者) → 数据行(v·↓·★)
1193
- // → 简介(4 行截断) → 截图(≤2) → 脚行(标签 chips + 安装按钮)。
1194
- // 卡片首行插件图标:候选地址逐个回退(jsdelivr gh 镜像优先),无 icon 或全失败不展示。
1195
- function FeaturedHeadIcon(props) {
1196
- const entry = props.entry
1197
- const pair = React.useState(0)
1198
- const idx = pair[0], setIdx = pair[1]
1199
- const candidates = React.useMemo(() => (entry.icon ? shotCandidates(entry.icon) : []), [entry.icon])
1200
- if (!candidates.length || idx >= candidates.length) return null
1201
- return h('img', { src: candidates[idx], alt: '', style: props.large ? S.panelIcon : S.iconS, loading: 'lazy', onError: () => setIdx(idx + 1) })
1202
- }
1203
-
1204
- function FeaturedCard(props) {
1205
- const e = props.entry
1206
- const t = props.t
1207
- const install = props.install
1208
- const onDetail = props.onDetail // 打开自建详情弹窗
1209
- const installed = !!props.installed // 宿主侧 pluginManager.listBundles 判定
1210
- const pair = React.useState(false) // busy
1211
- const busy = pair[0], setBusy = pair[1]
1212
- const donePair = React.useState(false) // 本会话刚装过(仅避免重复点击)
1213
- const done = donePair[0], setDone = donePair[1]
1214
-
1215
- const onClick = () => {
1216
- if (busy || done || typeof install !== 'function') return
1217
- setBusy(true)
1218
- try {
1219
- install({ spec: e.version ? `${e.package}@${e.version}` : e.package, title: e.title, version: e.version || '' })
1220
- setDone(true)
1221
- } finally {
1222
- setBusy(false)
1223
- }
1224
- }
1225
-
1226
- const btnLabel = busy ? '…' : t('install')
1227
- const metaParts = []
1228
- if (e.version) metaParts.push(`v${e.version}`)
1229
- const metaText = metaParts.join(' · ')
1230
-
1231
- const chips = (e.tags || []).slice(0, 2)
1232
- return h('li', { style: S.card },
1233
- h('div', { style: S.head },
1234
- h(FeaturedHeadIcon, { entry: e }),
1235
- h('div', { style: S.nameWrap },
1236
- h('span', { style: S.title, title: e.title, onClick: onDetail }, e.title),
1237
- e.homepage ? h('a', { style: S.ghLink, href: e.homepage, target: '_blank', rel: 'noreferrer noopener', title: e.package },
1238
- h('svg', { style: S.ghIcon, viewBox: '0 0 16 16', 'aria-hidden': 'true' }, h('path', { d: GH_PATH }))) : null),
1239
- // 右上角:已安装绿色徽标,否则安装按钮(参考 billion-context 卡片布局)
1240
- installed || done
1241
- ? h('span', { style: S.badge }, `✓ ${t('installed')}`)
1242
- : h('button', {
1243
- type: 'button', style: Object.assign({}, S.btn, busy ? S.btnBusy : {}),
1244
- onClick, disabled: busy,
1245
- }, btnLabel)),
1246
- h(FeaturedAuthor, { pkg: e.package, meta: metaText, onDetail }),
1247
- e.description ? h('p', { style: S.desc, onClick: onDetail }, e.description) : null,
1248
- e.screenshots && e.screenshots.length
1249
- ? h('div', { style: S.shots }, e.screenshots.map((url) => h(FeaturedShot, { key: url, url })))
1250
- : null,
1251
- h('div', { style: S.foot },
1252
- h('div', { style: S.chips },
1253
- chips.map((c) => h('span', { key: c, style: S.chip, title: c }, c)),
1254
- e.sourceTitle ? h('span', { style: S.src, title: `${t('recommendedBy')} ${e.sourceTitle}` }, `${t('recommendedBy')} ${e.sourceTitle}`) : null)))
1255
- }
1256
-
1257
- // ── 自建详情弹窗:README 从 npm 包(jsdelivr)读取,轻量 markdown 渲染 ──
1258
- // 相对路径的图片/链接重写到 jsdelivr 包根。
1259
- function mdAbsUrl(url, base) {
1260
- const u = String(url).trim()
1261
- if (/^https?:\/\//i.test(u)) return u
1262
- return base + u.replace(/^\.\//, '')
1263
- }
1264
-
1265
- // 占位符还原:把 s 里 \u0000<idx>\u0000 换回暂存的节点
1266
- function restoreInline(s, tokens) {
1267
- const parts = String(s).split(/\u0000(\d+)\u0000/g)
1268
- const out = []
1269
- for (let i = 0; i < parts.length; i++) {
1270
- if (i % 2 === 1) out.push(tokens[Number(parts[i])])
1271
- else if (parts[i]) out.push(parts[i])
1272
- }
1273
- return out
1274
- }
1275
-
1276
- // 行内解析(占位符两段式):
1277
- // 粗体 → 图片 → 链接 → 行内代码。图片先于链接,使 [![徽章](i)](l) 外链图可用;
1278
- // 粗体内部递归解析,粗体套链接/链接套图片均正常。
1279
- function mdInline(text, base) {
1280
- const tokens = []
1281
- const stash = (node) => { tokens.push(node); return '\u0000' + (tokens.length - 1) + '\u0000' }
1282
- const stashText = (t) => { tokens.push(t); return '\u0000' + (tokens.length - 1) + '\u0000' }
1283
- // 链接统一形态:蓝色 + 前置地球图标(与官方 markdown 链接色一致)
1284
- const makeLink = (href, kids) => h('a', { style: S.mdA, href, target: '_blank', rel: 'noreferrer noopener' },
1285
- h('svg', { style: S.linkIcon, viewBox: '0 0 16 16', 'aria-hidden': 'true', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.2' },
1286
- h('circle', { cx: 8, cy: 8, r: 6.3 }),
1287
- h('path', { d: 'M1.7 8h12.6M8 1.7c2.4 1.9 2.4 10.7 0 12.6M8 1.7c-2.4 1.9-2.4 10.7 0 12.6' })),
1288
- ...kids)
1289
- let s = String(text)
1290
- s = s.replace(/\*\*([^*]+)\*\*/g, (m0, inner) => stash(h('strong', null, mdInline(inner, base))))
1291
- s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (m0, alt, url) => stash(h('img', { style: S.mdImg, src: mdAbsUrl(url, base), alt: alt || '', loading: 'lazy' })))
1292
- s = s.replace(/\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (m0, label, url) => stash(makeLink(mdAbsUrl(url, base), restoreInline(label, tokens))))
1293
- s = s.replace(/`([^`]+)`/g, (m0, c) => stash(h('code', { style: S.mdCode }, c)))
1294
- // 裸自动链接:<https://…> 与 http(s)://…(URL 中间允许点/斜杠,仅结尾剔除标点)
1295
- const TRAIL_PUNCT = /([.,;:!?"'))\u3001\u3002\uff0c\uff1b\uff1a\uff01\uff1f\u201d\u2019]|[^\x20-\x7e])+$/
1296
- s = s.replace(/<(https?:\/\/[^>\s]+)>/g, (m0, url) => stash(makeLink(url, [url])))
1297
- s = s.replace(/(^|[\s(])(https?:\/\/[^\s<>()\u0000]+)/g, (m0, pre, rawUrl) => {
1298
- const trailMatch = TRAIL_PUNCT.exec(rawUrl)
1299
- const trail = trailMatch ? trailMatch[0] : ''
1300
- const url = trail ? rawUrl.slice(0, -trail.length) : rawUrl
1301
- return stashText(pre) + stash(makeLink(url, [url])) + (trail ? stashText(trail) : '')
1302
- })
1303
- return restoreInline(s, tokens)
1304
- }
1305
-
1306
- // 块级解析:围栏代码块 / 标题 / 列表 / 段落(不追求完整 markdown,够读 README 即可)
1307
- function renderReadme(text, base) {
1308
- const lines = String(text).split('\n')
1309
- const out = []
1310
- let key = 0, para = [], i = 0
1311
- const flushPara = () => {
1312
- if (para.length) {
1313
- out.push(h('p', { style: S.mdP, key: 'p' + (key++) }, mdInline(para.join(' '), base)))
1314
- para = []
1315
- }
1316
- }
1317
- while (i < lines.length) {
1318
- const line = lines[i]
1319
- if (/^```/.test(line)) {
1320
- flushPara()
1321
- const buf = []
1322
- i++
1323
- while (i < lines.length && !/^```/.test(lines[i])) { buf.push(lines[i]); i++ }
1324
- i++
1325
- out.push(h('pre', { style: S.mdPre, key: 'c' + (key++) }, h('code', { style: S.mdPreCode }, buf.join('\n'))))
1326
- continue
1327
- }
1328
- // 引用块(> 行,支持连续多行合并)
1329
- if (/^\s*>\s?/.test(line)) {
1330
- flushPara()
1331
- const buf = []
1332
- while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
1333
- buf.push(lines[i].replace(/^\s*>\s?/, ''))
1334
- i++
1335
- }
1336
- out.push(h('div', { style: S.mdQuote, key: 'q' + (key++) },
1337
- h('p', { style: S.mdP }, mdInline(buf.join(' ').trim(), base))))
1338
- continue
1339
- }
1340
- // 表格(| 行,第二行为 |---| 分隔)
1341
- if (/^\s*\|/.test(line)) {
1342
- const block = []
1343
- while (i < lines.length && /^\s*\|/.test(lines[i])) { block.push(lines[i].trim()); i++ }
1344
- const cells = (row) => row.replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim())
1345
- const isSep = (row) => /^\|?[\s:|-]+\|?$/.test(row) && row.includes('-')
1346
- if (block.length >= 2 && isSep(block[1])) {
1347
- flushPara()
1348
- const head = cells(block[0])
1349
- const rows = block.slice(2).filter((r) => !isSep(r)).map(cells)
1350
- out.push(h('table', { style: S.mdTable, key: 't' + (key++) },
1351
- h('thead', null, h('tr', null, head.map((c) => h('th', { style: S.mdTd }, mdInline(c, base))))),
1352
- h('tbody', null, rows.map((r) => h('tr', null, head.map((_, ci) => h('td', { style: S.mdTd }, mdInline(r[ci] || '', base))))))))
1353
- continue
1354
- }
1355
- // 非法表格形态 → 按普通段落处理
1356
- for (const row of block) para.push(row)
1357
- continue
1358
- }
1359
- const hm = line.match(/^(#{1,4})\s+(.*)/)
1360
- if (hm) {
1361
- flushPara()
1362
- out.push(h(hm[1].length <= 2 ? 'h3' : 'h4', { style: hm[1].length <= 2 ? S.mdH : S.mdH2, key: 'h' + (key++) }, mdInline(hm[2], base)))
1363
- i++
1364
- continue
1365
- }
1366
- const lm = line.match(/^\s*(?:[-*+]|\d+[.)])\s+(.*)/)
1367
- if (lm) {
1368
- flushPara()
1369
- const items = []
1370
- while (i < lines.length) {
1371
- const m2 = lines[i].match(/^\s*(?:[-*+]|\d+[.)])\s+(.*)/)
1372
- if (!m2) break
1373
- items.push(h('li', { style: S.mdLi, key: 'li' + items.length }, mdInline(m2[1], base)))
1374
- i++
1375
- }
1376
- out.push(h('ul', { style: S.mdList, key: 'u' + (key++) }, items))
1377
- continue
1378
- }
1379
- if (!line.trim()) { flushPara(); i++; continue }
1380
- para.push(line.trim())
1381
- i++
1382
- }
1383
- flushPara()
1384
- return out
1385
- }
1386
-
1387
- function FeaturedModal(props) {
1388
- const e = props.entry
1389
- const t = props.t
1390
- const onClose = props.onClose
1391
- const pair = React.useState({ status: 'loading', kids: [] })
1392
- const state = pair[0], setState = pair[1]
967
+ const React = require('react')
968
+ const h = React.createElement
969
+
970
+ const NS = 'dsh-plugins-plugin'
971
+ const FULL_PKG = 'dsh-featured'
972
+
973
+ const zh = {
974
+ tabLabel: '精选插件',
975
+ welcome: '精选插件完整版(dsh-featured)未安装。',
976
+ installFull: '安装完整版',
977
+ installing: '正在安装完整版…',
978
+ installed: '已安装,刷新后即可使用完整功能。',
979
+ installedShort: '已安装',
980
+ desc: '一个入口逛完社区精选的好插件:搜索、标签筛选、一键安装、README 详情。',
981
+ }
982
+ const en = {
983
+ tabLabel: 'Featured',
984
+ welcome: 'The full Featured plugin (dsh-featured) is not installed.',
985
+ installFull: 'Install full version',
986
+ installing: 'Installing…',
987
+ installed: 'Installed — refresh to use the full experience.',
988
+ installedShort: 'Installed',
989
+ desc: 'One tab for community-featured plugins: search, filter, one-click install, README details.',
990
+ }
1393
991
 
1394
- React.useEffect(() => {
1395
- let alive = true
1396
- setState({ status: 'loading', kids: [] })
1397
- const base = `https://cdn.jsdelivr.net/npm/${e.package}/`
1398
- fetchText(base + 'README.md', 10000).then((txt) => {
1399
- if (!alive) return
1400
- setState({ status: 'ready', kids: renderReadme(txt, base) })
1401
- }).catch(() => {
1402
- if (!alive) return
1403
- // jsdelivr npm 主源失败 → GitHub 仓库兜底(README 大小写两种形态)
1404
- const ghCandidates = e.homepage && /^https?:\/\/github\.com\/([^/]+)\/([^/]+)/i.exec(e.homepage)
1405
- if (!ghCandidates) { setState({ status: 'error', kids: [] }); return }
1406
- const ghBase = `https://cdn.jsdelivr.net/gh/${ghCandidates[1]}/${ghCandidates[2]}@main/`
1407
- fetchText(ghBase + 'README.md', 10000).then((txt2) => {
1408
- if (!alive) return
1409
- setState({ status: 'ready', kids: renderReadme(txt2, ghBase) })
1410
- }).catch(() => { if (alive) setState({ status: 'error', kids: [] }) })
1411
- })
1412
- return () => { alive = false }
1413
- }, [e.package])
992
+ const S = {
993
+ wrap: { padding: '24px 16px', maxWidth: 560, display: 'flex', flexDirection: 'column', gap: 12 },
994
+ title: { fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--dsw-alias-label-primary)' },
995
+ desc: { fontSize: 13, lineHeight: 1.7, margin: 0, color: 'var(--dsw-alias-label-secondary)' },
996
+ note: { fontSize: 13, lineHeight: 1.7, margin: 0, color: 'var(--dsw-alias-label-primary)' },
997
+ btn: {
998
+ alignSelf: 'flex-start', cursor: 'pointer', font: 'inherit', fontSize: 13, fontWeight: 500,
999
+ padding: '7px 16px', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1)',
1000
+ background: 'var(--dsw-alias-brand-primary)', color: '#fff',
1001
+ },
1002
+ btnOff: { opacity: 0.6, cursor: 'default' },
1003
+ }
1414
1004
 
1415
- React.useEffect(() => {
1416
- const onKey = (ev) => { if (ev.key === 'Escape') onClose() }
1417
- window.addEventListener('keydown', onKey)
1418
- return () => window.removeEventListener('keydown', onKey)
1419
- }, [onClose])
1005
+ function FeaturedSection(props) {
1006
+ const install = props.install
1007
+ const t = props.t || ((k) => zh[k])
1008
+ // 已安装判定:宿主路由返回的 installed 表里有 FULL_PKG
1009
+ const pair = React.useState('idle') // idle | running | installed
1010
+ const st = pair[0], setSt = pair[1]
1011
+
1012
+ React.useEffect(() => {
1013
+ if (st !== 'idle') return
1014
+ if (typeof install !== 'function') { setSt('installed'); return }
1015
+ setSt('running')
1016
+ try {
1017
+ install({ spec: FULL_PKG, title: t('tabLabel'), version: '' })
1018
+ setSt('installed')
1019
+ } catch {
1020
+ setSt('installed')
1021
+ }
1022
+ }, [st, install])
1023
+
1024
+ const label = st === 'running' ? t('installing')
1025
+ : (st === 'installed' ? t('installedShort') : t('installFull'))
1026
+
1027
+ return h('div', { style: S.wrap },
1028
+ h('p', { style: S.desc }, t('desc')),
1029
+ st === 'idle' ? h('p', { style: S.note }, t('welcome')) : null,
1030
+ h('button', {
1031
+ type: 'button',
1032
+ style: Object.assign({}, S.btn, st === 'installed' ? S.btnOff : {}),
1033
+ disabled: st === 'installed',
1034
+ onClick: () => {
1035
+ if (st !== 'idle' || typeof install !== 'function') return
1036
+ setSt('running')
1037
+ try { install({ spec: FULL_PKG, title: t('tabLabel'), version: '' }); setSt('installed') }
1038
+ catch { setSt('installed') }
1039
+ },
1040
+ }, label))
1041
+ }
1420
1042
 
1421
- const metaParts = []
1422
- if (e.version) metaParts.push(`v${e.version}`)
1423
- return h('div', {
1424
- style: S.overlay,
1425
- onClick: (ev) => { if (ev.target === ev.currentTarget) onClose() },
1043
+ function initFeatured(ctx) {
1044
+ if (typeof window !== 'undefined') window.__FEATURED_INIT_CALLED__ = true
1045
+ if (typeof window !== 'undefined' && window.__DSH_FEATURED_APPLIED__) return
1046
+ if (typeof window !== 'undefined') window.__DSH_FEATURED_APPLIED__ = true
1047
+ try {
1048
+ const localeDisposable = ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugins-plugin: locale')
1049
+ const t = ctx.locale.bind(NS)
1050
+ let tabDisposable = null
1051
+ ctx.slots.inject('plugins.tab', () => {
1052
+ tabDisposable = ctx.slots.register({
1053
+ name: 'plugins.tab',
1054
+ id: 'dsh-plugins-plugin',
1055
+ label: () => t('tabLabel'),
1056
+ locale: NS,
1057
+ priority: 100,
1058
+ }, FeaturedSection)
1059
+ return tabDisposable
1060
+ }, 'dsh-plugins-plugin: featured tab')
1061
+
1062
+ if (typeof window !== 'undefined') {
1063
+ window.__DSH_FEATURED_ENTRY__ = {
1064
+ kind: 'inline',
1065
+ dispose() {
1066
+ try { if (typeof tabDisposable === 'function') tabDisposable() } catch { /* 已注销 */ }
1067
+ try { if (typeof localeDisposable === 'function') localeDisposable() } catch { /* 已注销 */ }
1068
+ window.__DSH_FEATURED_APPLIED__ = false
1069
+ window.__DSH_FEATURED_ENTRY__ = null
1426
1070
  },
1427
- h('div', { style: S.panel },
1428
- h('div', { style: S.panelHead },
1429
- h(FeaturedHeadIcon, { entry: e, large: true }),
1430
- h('div', { style: S.panelTitleCol },
1431
- h('p', { style: S.panelTitle }, e.title),
1432
- h('span', { style: S.panelPkg }, e.package)),
1433
- h('button', { type: 'button', style: S.panelClose, onClick: onClose }, '✕')),
1434
- metaParts.length ? h('div', { style: S.panelMeta }, metaParts.join(' · ')) : null,
1435
- e.description ? h('p', { style: S.panelDesc }, e.description) : null,
1436
- h('div', { style: S.panelBody },
1437
- state.status === 'loading' ? h('p', { style: S.mdNote }, t('readmeLoading')) : null,
1438
- state.status === 'error' ? h('p', { style: S.mdNote }, t('readmeError')) : null,
1439
- state.status === 'ready' ? state.kids : null),
1440
- h('div', { style: Object.assign({}, S.panelMeta, { justifyContent: 'flex-end', paddingTop: 10 }) },
1441
- h('button', { type: 'button', style: S.retryBtn, onClick: onClose }, t('close')))))
1442
- }
1443
-
1444
- function FeaturedSection(props) {
1445
- const install = props.install
1446
- void props.openPackage // 详情改为自建弹窗,不再调官方 openPackage
1447
- const t = props.t
1448
-
1449
- const pair = React.useState({ status: 'loading', entries: [], installed: {} })
1450
- const state = pair[0], setState = pair[1]
1451
- const noncePair = React.useState(0)
1452
- const nonce = noncePair[0], setNonce = noncePair[1]
1453
- const detailPair = React.useState(null)
1454
- const detail = detailPair[0], setDetail = detailPair[1]
1455
-
1456
- React.useEffect(() => {
1457
- let alive = true
1458
- setState({ status: 'loading', entries: [], installed: {} })
1459
- // 宿主路由一站式返回:远程集中目录(已富化)+ 接入插件登记源 + 已安装表。
1460
- fetchJson(ROUTE, 8000).then((body) => {
1461
- if (!alive) return
1462
- const entries = body && body.ok && body.data && Array.isArray(body.data.entries)
1463
- ? body.data.entries.map(normalizeRemoteEntry).filter(Boolean)
1464
- : []
1465
- const installed = body && body.ok && body.data && body.data.installed && typeof body.data.installed === 'object'
1466
- ? body.data.installed
1467
- : {}
1468
- setState({ status: entries.length ? 'ready' : 'empty', entries, installed })
1469
- }).catch(() => {
1470
- if (alive) setState({ status: 'error', entries: [] })
1471
- })
1472
- return () => { alive = false }
1473
- }, [nonce])
1474
-
1475
- // tab 标签已表达板块名,不再渲染顶部标题/副标题
1476
- const kids = []
1477
-
1478
- if (state.status === 'loading') {
1479
- kids.push(h('p', { key: 'note', style: S.note }, t('loading')))
1480
- } else if (state.status === 'error') {
1481
- kids.push(h('p', { key: 'note', style: S.note }, t('error')))
1482
- kids.push(h('button', { key: 'retry', type: 'button', style: S.retryBtn, onClick: () => setNonce((n) => n + 1) }, t('retry')))
1483
- } else if (state.status === 'empty') {
1484
- kids.push(h('p', { key: 'note', style: S.note }, t('empty')))
1485
- } else {
1486
- kids.push(h('ul', { key: 'grid', style: S.grid }, state.entries.map((e) => (
1487
- h(FeaturedCard, { key: e.package, entry: e, t, install, onDetail: () => setDetail(e), installed: !!state.installed[e.package] })
1488
- ))))
1489
- }
1490
- return h('div', { style: S.wrap }, kids,
1491
- detail ? h(FeaturedModal, { key: detail.package, entry: detail, t, onClose: () => setDetail(null) }) : null)
1492
- }
1493
-
1494
- // 导出:接入插件 apply 末尾调用 window.__DSH_FEATURED_INIT__(ctx)。
1495
- // 判重用 window 标志,确保多插件接入只注册一块(最先调用者生效)。
1496
- function initFeatured(ctx) {
1497
- if (typeof window !== 'undefined') window.__FEATURED_INIT_CALLED__ = true
1498
- if (typeof window !== 'undefined' && window.__DSH_FEATURED_APPLIED__) return
1499
- if (typeof window !== 'undefined') window.__DSH_FEATURED_APPLIED__ = true
1500
- try {
1501
- ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugins-plugin: locale')
1502
-
1503
- const t = ctx.locale.bind(NS)
1504
-
1505
- ctx.slots.inject('plugins.tab', () => ctx.slots.register({
1506
- name: 'plugins.tab',
1507
- id: 'dsh-plugins-plugin',
1508
- label: () => t('tabLabel'),
1509
- locale: NS,
1510
- }, FeaturedSection), 'dsh-plugins-plugin: featured tab')
1511
- if (typeof window !== 'undefined') window.__FEATURED_OK__ = true
1512
- } catch (e) {
1513
- if (typeof window !== 'undefined') window.__FEATURED_ERR__ = String(e && (e.stack || e.message || e))
1514
- }
1515
1071
  }
1072
+ window.__FEATURED_OK__ = true
1073
+ }
1074
+ } catch (e) {
1075
+ if (typeof window !== 'undefined') window.__FEATURED_ERR__ = String(e && (e.stack || e.message || e))
1076
+ }
1077
+ }
1516
1078
 
1517
- window.__DSH_FEATURED_INIT__ = initFeatured
1079
+ window.__DSH_FEATURED_INIT__ = initFeatured
1518
1080
  } catch (error) {
1519
- // 内联模块自身故障不能拖垮接入插件:记录原因,由 apply 处的调用方检查标志位。
1520
- console.error('[dsh-plugins-plugin] 精选推荐模块初始化失败', error)
1081
+ console.error('[精选插件] 模块初始化失败', error)
1521
1082
  window.__FEATURED_ERR__ = String((error && (error.stack || error.message)) || error)
1522
1083
  }
1523
1084
  })()
1524
- // <<< dsh-plugins-plugin featured inline
1085
+ // <<< dsh-featured inline
1525
1086
  return {
1526
1087
  name: 'dsh-skillpie-mail',
1527
1088
  inject: ['slots', 'locale'],
@@ -1635,7 +1196,7 @@ window.__ModuleLoader__.load({
1635
1196
  },
1636
1197
  )
1637
1198
  })
1638
- if (typeof window.__DSH_FEATURED_INIT__ === 'function') window.__DSH_FEATURED_INIT__(ctx) // dsh-plugins-plugin: 精选推荐板块
1199
+ if (typeof window.__DSH_FEATURED_INIT__ === 'function') window.__DSH_FEATURED_INIT__(ctx) // 精选插件
1639
1200
  },
1640
1201
  }
1641
1202
  },
package/lib/index.js CHANGED
@@ -1,5 +1,272 @@
1
1
  // >>> dsh-plugins-plugin featured source (auto-inserted, do not remove markers)
2
- import { integrateFeaturedPlugins } from 'dsh-plugins-plugin/host'
2
+ // >>> dsh-plugins-plugin featured host (auto-inserted, do not remove markers)
3
+ function dshFeaturedHostModule() {
4
+ // dsh-plugins-plugin — 嵌入式宿主模块(embed/featured.host.js)。
5
+ //
6
+ // 接入插件以 npm 依赖引用本包,在接入插件 apply 里调用:
7
+ // import { integrateFeaturedPlugins } from 'dsh-plugins-plugin/host'
8
+ // integrateFeaturedPlugins(ctx, FEATURED_SOURCE)
9
+ //
10
+ // 职责:
11
+ // 1. 登记推荐源 FEATURED_SOURCE 到跨插件服务 `featured-plugins`
12
+ // (服务已由先激活的接入方提供时,只登记,不重复建)。
13
+ // 2. 第一个激活的接入方作为「宿主」:拉远程集中目录、轮询已安装表、
14
+ // 挂聚合路由 GET /dsh-plugins-plugin/featured(重复注册静默忽略)。
15
+ //
16
+ // client 半不走本文件分发:接入插件的 apply 经 DSH 原生 chunk 机制
17
+ // require.async('./client.featured.js') 加载 client 模块(由 integrate.sh 拷入)。
18
+ //
19
+ // 多插件同时接入:板块与路由由最先激活的一方持有,其余只贡献数据;
20
+ // 客户端用 chunk 导出 initFeatured(ctx) + window.__DSH_FEATURED_APPLIED__ 判重
21
+ // (owner 的 apply 调用),保证「精选推荐」只渲染一块。
22
+
23
+ const ROUTE = '/dsh-plugins-plugin/featured'
24
+ const SERVICE = 'featured-plugins'
25
+
26
+ /* ── 推荐源/条目规范化 ──────────────────────────────────────────────── */
27
+
28
+ // 单条推荐:package 必填(npm 包名),title 必填;其余可选。
29
+ // 富字段(author/stars/downloads/screenshots 等)由仓库 plugins.json 集中维护。
30
+ function normalizeEntry(raw, sourceId) {
31
+ if (!raw || typeof raw !== 'object') return null
32
+ const pkg = String(raw.package || raw.name || '').trim()
33
+ const title = String(raw.title || '').trim()
34
+ if (!pkg || !title) return null
35
+ const entry = { package: pkg, title, source: sourceId }
36
+ for (const key of ['description', 'version', 'icon', 'homepage', 'author', 'category']) {
37
+ const v = String(raw[key] || '').trim()
38
+ if (v) entry[key] = v
39
+ }
40
+ if (Array.isArray(raw.screenshots)) {
41
+ const shots = raw.screenshots.map((s) => String(s).trim()).filter(Boolean).slice(0, 4)
42
+ if (shots.length) entry.screenshots = shots
43
+ }
44
+ if (typeof raw.stars === 'number' && raw.stars >= 0) entry.stars = raw.stars
45
+ if (typeof raw.downloads === 'number' && raw.downloads >= 0) entry.downloads = raw.downloads
46
+ if (Array.isArray(raw.tags)) {
47
+ const tags = raw.tags.map((t) => String(t).trim()).filter(Boolean).slice(0, 8)
48
+ if (tags.length) entry.tags = tags
49
+ }
50
+ return entry
51
+ }
52
+
53
+ // 一个推荐源:接入插件登记的单位。
54
+ function normalizeSource(raw) {
55
+ if (!raw || typeof raw !== 'object') throw new Error('featured source must be an object')
56
+ const id = String(raw.id || '').trim()
57
+ if (!id) throw new Error('featured source needs an id (the integrating package name)')
58
+ const title = String(raw.title || id).trim()
59
+ const rawEntries = Array.isArray(raw.entries) ? raw.entries : []
60
+ const entries = []
61
+ for (const item of rawEntries) {
62
+ const entry = normalizeEntry(item, id)
63
+ if (entry) entries.push(entry)
64
+ }
65
+ return { id, title, entries }
66
+ }
67
+
68
+ /* ── HTTP helpers ───────────────────────────────────────────────────── */
69
+
70
+ function json(res, code, obj) {
71
+ const body = JSON.stringify(obj)
72
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
73
+ res.end(body)
74
+ }
75
+
76
+ // 同源校验:浏览器必带 Origin;curl 无 Origin 放行(宿主属主角色已限定)
77
+ function sameOrigin(req) {
78
+ const origin = req.headers.origin
79
+ if (!origin) return true
80
+ try { return new URL(origin).host === req.headers.host } catch { return false }
81
+ }
82
+
83
+ /* ── 嵌入入口 ───────────────────────────────────────────────────────── */
84
+
85
+ // ctx:接入插件自己的 cordis 上下文(apply 的第一参)。
86
+ // source:推荐源 { id, title?, entries: [{ package, title, ... }] }。
87
+ function integrateFeaturedPlugins(ctx, source) {
88
+ // ── 推荐源注册表(跨插件服务,先激活者提供) ──
89
+ let owner = false
90
+ let registry = null
91
+ try {
92
+ registry = ctx.get(SERVICE)
93
+ } catch { /* get 不可用时按未提供处理 */ }
94
+ if (!registry) {
95
+ const sources = new Map()
96
+ registry = {
97
+ register(rawSource) {
98
+ const normalized = normalizeSource(rawSource)
99
+ sources.set(normalized.id, normalized)
100
+ return () => {
101
+ if (sources.get(normalized.id) === normalized) sources.delete(normalized.id)
102
+ }
103
+ },
104
+ list() {
105
+ return [...sources.values()]
106
+ },
107
+ }
108
+ try {
109
+ ctx.effect(() => ctx.provide(SERVICE, registry), 'dsh-plugins-plugin: registry service')
110
+ owner = true
111
+ } catch { /* 已被并行提供 → 退化为纯登记方 */ }
112
+ }
113
+
114
+ // 登记本插件推荐源(effect 挂子上下文,插件停用即注销)
115
+ ctx.inject([], (child) => {
116
+ child.effect(() => registry.register(source), 'featured-plugins source: ' + String(source && source.id))
117
+ })
118
+
119
+ if (!owner) return // 非宿主:只贡献数据
120
+
121
+ // ── 宿主职责:远程集中目录(5 分钟内存缓存,node fetch,无浏览器缓存/CORS) ──
122
+ const REMOTE_CATALOG_URLS = [
123
+ 'https://cdn.jsdelivr.net/gh/skillpie/dsh-plugins@main/dsh-plugins-plugin/plugins.json',
124
+ 'https://raw.githubusercontent.com/skillpie/dsh-plugins/main/dsh-plugins-plugin/plugins.json',
125
+ ]
126
+ const REMOTE_TTL_MS = 5 * 60_000
127
+ let remoteCache = { at: 0, doc: null }
128
+
129
+ // 多源并发拉取,取「最新」的那份。单源「先到先用」会被 CDN 缓存坑:
130
+ // jsdelivr 的 @main 有数分钟到数小时的延迟,raw.githubusercontent 通常更快,
131
+ // 谁先返回就用谁会让旧数据长期遮住新数据。
132
+ //
133
+ // 判新三要素(优先级从高到低):
134
+ // 1. updated 日期(仓库写入时的时间戳)
135
+ // 2. 条目数 —— plugins.json 只会增不会减,多的一定更新
136
+ // 3. 版本号总和 —— 同一条目升级时条目数不变,靠这个比出来
137
+ // 只比 updated 不够:enrich 脚本按天写 updated(如 "2026-11-22"),
138
+ // 同一天内的多次提交无法区分,会退化成「谁先返回用谁」。
139
+ const catalogScore = (doc) => {
140
+ const t = Date.parse(String(doc?.updated || ''))
141
+ const entries = Array.isArray(doc?.entries) ? doc.entries : []
142
+ let versions = 0
143
+ for (const e of entries) {
144
+ const parts = String(e?.version || '0.0.0').split('.').map((n) => Number.parseInt(n, 10) || 0)
145
+ versions += (parts[0] || 0) * 1_000_000 + (parts[1] || 0) * 1_000 + (parts[2] || 0)
146
+ }
147
+ return { at: Number.isFinite(t) ? t : 0, count: entries.length, versions }
148
+ }
149
+
150
+ const newerCatalog = (a, b) => {
151
+ // a 是否比 b 新
152
+ if (a.at !== b.at) return a.at > b.at
153
+ if (a.count !== b.count) return a.count > b.count
154
+ return a.versions > b.versions
155
+ }
156
+
157
+ async function fetchRemoteCatalog() {
158
+ const now = Date.now()
159
+ if (remoteCache.doc && now - remoteCache.at < REMOTE_TTL_MS) return remoteCache.doc
160
+ const results = await Promise.all(
161
+ REMOTE_CATALOG_URLS.map(async (url) => {
162
+ try {
163
+ const res = await fetch(url, {
164
+ headers: { accept: 'application/json' },
165
+ signal: AbortSignal.timeout(8000),
166
+ cache: 'no-store',
167
+ })
168
+ if (!res.ok) return null
169
+ const doc = await res.json()
170
+ return Array.isArray(doc?.entries) ? doc : null
171
+ } catch { return null }
172
+ }),
173
+ )
174
+ const docs = results.filter(Boolean)
175
+ if (docs.length === 0) return null
176
+ // 三要素比较;完全相同时保留并发顺序靠前者(jsdelivr 在前)。
177
+ const best = docs.reduce((a, b) => (newerCatalog(catalogScore(b), catalogScore(a)) ? b : a))
178
+ remoteCache = { at: now, doc: best }
179
+ return best
180
+ }
181
+
182
+ // ── 已安装列表(host 侧轮询 pluginManager,独立 inject 作用域防回滚) ──
183
+ let installedMap = {}
184
+ try {
185
+ ctx.inject(['pluginManager'], (child) => {
186
+ child.effect(() => {
187
+ let timer = null
188
+ const refresh = async () => {
189
+ try {
190
+ const bundles = await child.pluginManager.listBundles()
191
+ const map = {}
192
+ for (const b of bundles) {
193
+ if (b && b.name && b.installed) map[b.name] = b.version || ''
194
+ }
195
+ installedMap = map
196
+ } catch { /* 保留上一次结果 */ }
197
+ }
198
+ refresh()
199
+ timer = setInterval(refresh, 30_000)
200
+ if (timer && typeof timer.unref === 'function') timer.unref() // 不阻塞宿主退出
201
+ return () => clearInterval(timer)
202
+ }, 'dsh-plugins-plugin: installed bundles watcher')
203
+ })
204
+ } catch { /* pluginManager 不可用 → 无已安装徽标,不影响板块 */ }
205
+
206
+ // ── 聚合:远程目录(主)+ 登记源(补充),按包名去重,先到者优先;富字段回填 ──
207
+ const RICH_KEYS = ['author', 'homepage', 'category', 'icon', 'screenshots', 'stars', 'downloads']
208
+ const aggregate = async () => {
209
+ const remoteRaw = Array.isArray(remoteCache.doc?.entries) ? remoteCache.doc.entries : []
210
+ const remoteIndex = new Map()
211
+ for (const raw of remoteRaw) {
212
+ const pkg = String(raw?.package || raw?.name || '').trim()
213
+ if (pkg && !remoteIndex.has(pkg)) remoteIndex.set(pkg, raw)
214
+ }
215
+ const seen = new Set()
216
+ const entries = []
217
+ const push = (normalized) => {
218
+ if (!normalized || seen.has(normalized.package)) return
219
+ seen.add(normalized.package)
220
+ const rich = remoteIndex.get(normalized.package)
221
+ if (rich && normalized.source !== 'plugins.json') {
222
+ for (const key of RICH_KEYS) {
223
+ if (normalized[key] === undefined && rich[key] !== undefined) normalized[key] = rich[key]
224
+ }
225
+ }
226
+ entries.push(normalized)
227
+ }
228
+ for (const raw of remoteRaw) push(normalizeEntry(raw, 'plugins.json'))
229
+ for (const src of registry.list()) {
230
+ for (const entry of src.entries) push(entry)
231
+ }
232
+ return {
233
+ entries,
234
+ sources: registry.list().map((s) => ({ id: s.id, title: s.title, count: s.entries.length })),
235
+ installed: installedMap,
236
+ remote: remoteCache.doc ? { fetchedAt: new Date(remoteCache.at).toISOString(), count: entries.length } : null,
237
+ }
238
+ }
239
+
240
+ // ── 聚合路由(重复注册会抛错 → try/catch 静默,已有宿主持有) ──
241
+ ctx.inject(['webServer'], (child) => {
242
+ child.effect(() => {
243
+ let dispose = null
244
+ try {
245
+ dispose = child.webServer.register({
246
+ kind: 'exact',
247
+ path: ROUTE,
248
+ handler: async (req, res) => {
249
+ try {
250
+ if (!sameOrigin(req)) { json(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
251
+ if (req.method !== 'GET' && req.method !== 'HEAD') { json(res, 405, { ok: false, error: 'method not allowed' }); return }
252
+ await fetchRemoteCatalog().catch(() => null)
253
+ json(res, 200, { ok: true, data: await aggregate() })
254
+ } catch (err) {
255
+ json(res, 200, { ok: false, error: String(err?.message || err) })
256
+ }
257
+ },
258
+ })
259
+ } catch { /* 路由已存在(另一接入方先注册)→ 本方只作数据方 */ }
260
+ return () => {
261
+ if (typeof dispose === 'function') dispose()
262
+ }
263
+ }, 'dsh-plugins-plugin: featured route')
264
+ })
265
+ }
266
+ return { integrateFeaturedPlugins }
267
+ }
268
+ const { integrateFeaturedPlugins } = dshFeaturedHostModule()
269
+ // <<< dsh-plugins-plugin featured host
3
270
 
4
271
  // 精选插件推荐源(dsh-plugins-plugin):
5
272
  const FEATURED_SOURCE = {
@@ -204,7 +471,8 @@ export default {
204
471
  Config,
205
472
  inject: [],
206
473
  async apply(ctx, config = null) {
207
- integrateFeaturedPlugins(ctx, FEATURED_SOURCE) // dsh-plugins-plugin: 推荐源登记 + 嵌入宿主
474
+ integrateFeaturedPlugins(ctx, FEATURED_SOURCE) // dsh-plugins-plugin: 推荐源登记 + 嵌入宿主
475
+
208
476
  const cfg = {
209
477
  registerUrl: config?.registerUrl ?? REGISTER_URL,
210
478
  imapHost: config?.imapHost ?? 'mail.skillpie.cn',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-skillpie-mail",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "SkillPie邮箱:管理 @skillpie.cn 邮箱(快速注册/手动添加/移除),后台 IMAP 轮询,收到新邮件全局弹窗展示并注明收件邮箱。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,7 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "dependencies": {
56
- "dsh-plugins-plugin": "^0.2.0"
57
- }
55
+ "dependencies": {}
58
56
  }