dsh-mobile-plugin 0.5.40 → 0.5.41

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.
@@ -40,10 +40,11 @@
40
40
  直接 fetch 相对路径也会自动走这条路。细节见文档第 5.5 节,我不会再解释一遍。
41
41
  7. 要 App 替你办事(例如打开一条新对话),发 { kind: 'action', id, action, params },
42
42
  动作名只能从 App 允许的那几个里挑,不能自己造。
43
- 8. 根目录要附带一份 manifest.json:{ name, version, apiVersion: "1", main: "index.html",
44
- capabilities: [...] }。要整页自绘(不要 App 那条顶栏)就再加 "chrome": "bare",那时
45
- 顶部状态栏那一截要自己用 --dsh-safe-top 让开,出口自己画(点了发 { kind: 'close' })。
46
- 要浮在对话页那张卡片里、能横滑划开侧栏,加 "placement": "panel"。
43
+ 8. 根目录要附带一份 manifest.json:{ name, version, apiVersion: "1", capabilities: [...] }。
44
+ 入口页固定叫 index.html,不用写 main。要整页自绘(不要 App 那条顶栏)就再加
45
+ "chrome": "bare",那时顶部状态栏那一截要自己用 --dsh-safe-top 让开,出口自己画
46
+ (点了发 { kind: 'close' })。要浮在对话页那张卡片里、能横滑划开侧栏,加
47
+ "placement": "panel"。
47
48
 
48
49
  产物目录我会放到:<你的插件包里 extensions/<包名>/ 这个位置>
49
50
  我要做的功能是:<一句话说清>
@@ -64,14 +65,16 @@
64
65
  ## 2. 包长什么样
65
66
 
66
67
  ```
67
- manifest.json 自述:id / name / version / apiVersion / 可选 capabilities
68
+ manifest.json 自述:name / version / apiVersion / 可选 capabilities
68
69
  index.html 入口页,固定叫这个名字
69
70
  libs/… 你自己的库、样式、字体,相对路径引用
70
71
  ```
71
72
 
72
- - **入口页固定是 `index.html`**。`manifest.json` 里没有 `main` 这一项,写了也不读 —— 手机
73
- 打开扩展时找的就是包目录下那一层 `index.html`。宿主在列包时会检查它在不在,缺了整个包
74
- 不会出现在清单里,别等装到手机上才发现打不开。
73
+ - **入口页固定是 `index.html`**。手机打开扩展时找的就是包目录下那一层 `index.html`,所以
74
+ `main` 这一格可写可不写 —— 写了也不读,样例里带它只是为了照抄时形状眼熟。宿主在列包时
75
+ 会检查 `index.html` 在不在,缺了整个包不会出现在清单里,别等装到手机上才发现打不开。
76
+ - **这个扩展叫什么不由 `manifest.json` 决定**。真正标识它的是「插件名 + 扩展目录名」拼出来的
77
+ slug(第 8 节),`manifest.json` 里的 `name` 只是界面上显示的那行字。
75
78
  - **整个目录原样落盘**。清单里的 `path` 就是落盘路径,`index.html` 里用相对路径引用
76
79
  同目录的文件;别指望「拍平到一个目录」或者「从别处按绝对路径拿」。
77
80
  - **自包含,不许外链**。注释、脚本、样式、字体都得在包里。页面加载时是不透明源,
@@ -181,9 +184,12 @@ libs/… 你自己的库、样式、字体,相对路径引用
181
184
  装进来的扩展是 `file://` 加载的,不是 `http(s)://`。这不是配置问题,是「页面从哪儿来」
182
185
  决定的:
183
186
 
184
- - **本地存储可用**。`localStorage` / `sessionStorage` 都开着,放心用它们记界面偏好。
185
- 早期版本只给声明了取数的那种扩展开,2026-11-11 起一律打开 —— 那层限制封不住想干坏事的
186
- 人(页面能拿到的东西,一张图片照样能带出去),只挡住作者正当的用法。
187
+ - **本地存储可用**。`localStorage` / `sessionStorage` 都开着。但它们挂在页面的来源上:
188
+ 你换一版、目录一挪,那份数据就可能找不着,而且跟别的扩展挤在同一个来源里。所以**只拿它
189
+ 放「丢了也无所谓、下次重画一遍」的东西**(当前滚到哪、临时展开的面板);界面偏好、草稿
190
+ 这类要留住的数据走第 5.7 节 App 那条存储通道。早期版本只给声明了取数的那种扩展开,
191
+ 2026-11-11 起一律打开 —— 那层限制封不住想干坏事的人(页面能拿到的东西,一张图片照样能
192
+ 带出去),只挡住作者正当的用法。
187
193
  - **真 Worker 起不来**。`importScripts` 会报 NetworkError。要 worker 就把它的代码当普通
188
194
  脚本引进来、在主线程上跑一个假 worker(Office 那份 pdf.js 就是这么做的)。
189
195
  - **`fetch` 本地资源受限**,`blob:` 地址同理。资源要么在包里、要么让 App 递给你。
@@ -308,7 +314,8 @@ window.__DSH_EXTENSION__.device; // { deviceId: 'office-iMac' } 或 null
308
314
 
309
315
  两条通道,形状固定:
310
316
 
311
- **页面 → App**:`window.ReactNativeWebView.postMessage(JSON.stringify({...}))`。认这五种:
317
+ **页面 → App**:`window.ReactNativeWebView.postMessage(JSON.stringify({...}))`。自己拼的话认
318
+ 这七种:
312
319
 
313
320
  ```js
314
321
  { kind: 'ready' } // 起来了
@@ -317,8 +324,12 @@ window.__DSH_EXTENSION__.device; // { deviceId: 'office-iMac' } 或 null
317
324
  { kind: 'request', id: 'r1', what: 'content' } // 要这一次的内容
318
325
  { kind: 'card', title: '已发布', detail: '刚发出去' } // 回写自己那张卡
319
326
  { kind: 'action', id: 'a1', action: 'publish', params: {} } // 让宿主办事
327
+ { kind: 'fetch', id: 'f1', service, path, method } // 让 App 代取一次数(见 5.5)
320
328
  ```
321
329
 
330
+ 挑文件、存文件、自己联网、存自己那份数据各有现成的入口(第 5.6 / 5.7 节),**用那几个
331
+ 方法,不要自己拼对应的消息** —— 它们底下多走了一道分批与回执,手拼容易只对上形状。
332
+
322
333
  - 认不出的消息、超过 64KB 的消息**一律被丢掉**,不会报错给你。大内容走 `request` 那条。
323
334
  - `action` 的动作名只允许字母数字点横线下划线,最长 64。没登记过就回
324
335
  `extension-action-unknown`(手机那张表、电脑那张表都没它);能力没授予回
@@ -353,24 +364,27 @@ window.addEventListener('dsh-extension-reply', (event) => {
353
364
 
354
365
  ```json
355
366
  "capabilities": ["content.read", "card.write", "host.data"],
356
- "hostData": { "service": "magpie", "match": ["/api/"] }
367
+ "hostData": { "service": "dsh-email", "match": ["/api/dsh-email/"] }
357
368
  ```
358
369
 
359
- `service` 必须是一个**电脑上登记过的服务名**。两类来源:
370
+ `service` 必须是一个**电脑上登记过的服务名**,来源只有一条:**插件自己在
371
+ `package.json` 里声明**。没有内置服务表,也没有「随插件走、不归你管」的那一档 —— 宿主
372
+ 只认扫到的声明:
360
373
 
361
- - 内置的几个(例如 `magpie`)随移动端插件一起走,不归你管;
362
- - **你自己的服务**:在插件自己的 `package.json` 里声明,宿主扫插件时就会登记:
374
+ ```json
375
+ { "dshMobileDataServices": [{ "service": "dsh-email", "allow": ["/api/dsh-email/"] }] }
376
+ ```
363
377
 
364
- ```json
365
- { "dshMobileDataServices": [{ "service": "dsh-email", "allow": ["/api/dsh-email/"] }] }
366
- ```
378
+ `allow` 是这个服务开放给扩展页的路径前缀,**只认本源的绝对路径**(以 `/` 开头;
379
+ 整条 URL、`//host`、相对写法都不认)。这个声明与你的插件同生共死:插件装了才有,
380
+ 卸载就没了,不用去改 App 或移动端插件的代码。
367
381
 
368
- `allow` 是这个服务开放给扩展页的路径前缀,**只认本源的绝对路径**(以 `/` 开头;
369
- 整条 URL、`//host`、相对写法都不认)。这个声明与你的插件同生共死:插件装了才有,
370
- 卸载就没了,不用去改 App 或移动端插件的代码。
382
+ **服务名全局唯一**,撞了以后扫到的优先(按包名排序),所以起名前加个前缀(`dsh-email`
383
+ 而不是 `mail`)。
371
384
 
372
- **服务名全局唯一**,撞了以后扫到的优先(按包名排序),所以起名前加个前缀(`dsh-email`
373
- 而不是 `mail`)。内置服务优先于任何第三方声明 —— 你用一个同名声明顶不掉 `magpie`。
385
+ **有些前缀写了也会被丢掉**:凡是盖到宿主自己命名空间的那几条(`/api/mobile`、`/api/relay`、
386
+ `/connect` 这一段),一律拒绝 —— 这条通道带的是宿主自己的身份,够到移动 API 就等于拿到了
387
+ 宿主接口。声明里别的服务照旧生效,被拒的那条不影响你别的路径。
374
388
 
375
389
  `match` 是路径前缀,命中的请求才交给宿主,别的照旧由页面自己发。**两个都要写**:
376
390
  `manifest` 里的 `hostData.service` 要与 `package.json` 里的 `dshMobileDataServices[].service`
@@ -381,7 +395,7 @@ window.addEventListener('dsh-extension-reply', (event) => {
381
395
  `.arrayBuffer()` / `.headers.get()` 都能用。也有显式入口:
382
396
 
383
397
  ```js
384
- await window.__dshHostFetch('magpie', '/api/state', { method: 'GET' });
398
+ await window.__dshHostFetch('dsh-email', '/api/dsh-email/state', { method: 'GET' });
385
399
  ```
386
400
 
387
401
  几条要知道的:
@@ -611,6 +625,9 @@ body {
611
625
  DSH**(插件第一次装载要重启才生效),手机那侧在扩展页下拉刷新一次,你带的扩展就出现在
612
626
  可安装清单里了。
613
627
 
628
+ 这个插件包本身怎么搭(`package.json` 每一格、入口导出、`cordis.patch.yml` 挂载行),
629
+ 见第 10 节。
630
+
614
631
  清单只来自手机当前连着的那台电脑:插件装在哪台,手机连哪台才看得见。这一步最容易踩空,
615
632
  逐条对照见第 8.5 节。
616
633
 
@@ -628,8 +645,9 @@ body {
628
645
 
629
646
  - `manifest.json` 是你写的自述(能力、版本、入口、`hostData`);逐文件的 `size` 与
630
647
  `sha256` 由宿主扫目录现算,不是你填的,别混。
631
- - 官方扩展(Office 预览、magpie)仍随 `dsh-mobile-plugin` 发布、登记在它自己的
632
- `extensions/catalog.json` 里,和第三方这条是两档;两档来源在 `extension-market.md` 里写清了。
648
+ - 官方扩展(Office 预览)仍走另一条分发路:Office 发在 APP 分发系统(`platform = extension`),
649
+ 手机上的扩展市场页读的就是那份清单。这与你自己发插件这条路互不影响 —— 你不用关心它,
650
+ 也不用和它对齐版本。
633
651
  - 作者自己写、自己在手机上边改边看的那条调试路(第 9 节)与发布是两回事:那条走电脑上的
634
652
  本地目录,不经过插件包,也不带声明。
635
653
 
@@ -658,8 +676,8 @@ body {
658
676
  从扩展页进。写了但名字撞了 App 内置入口(比如「浏览器」「目录」)也不会画那一格 —— 扩展照常
659
677
  能装、能从扩展页打开。
660
678
 
661
- > 做样板:本仓库的 `plugin/` 目录就是一个能直接装的最小插件包,带的正是那三个示例扩展。
662
- > 想看「插件带扩展」长什么样,照它抄。
679
+ > 做样板:`docs/extension-sample/` 那份就是能直接装的最小扩展,先把它跑起来,再照第 8 节
680
+ > 那三步把它搬进你自己的插件包里。
663
681
 
664
682
  ## 9. 调试
665
683
 
@@ -671,8 +689,9 @@ body {
671
689
  - 电脑上的目录是 `~/.dsh/extension-dev/<包名>/`,每个装着一个扩展的目录就是一个包,目录名
672
690
  就是它的标识。里面照第 2 节的结构放 `manifest.json` 与 `index.html` 那一套,别的文件想
673
691
  带就带。
674
- - 手机上打开扩展页,最底下那段「本地开发」点一下刷新,就能看到电脑那边有哪些包。点「导入」
675
- 就装进来;装过的会显示版本,可以「覆盖重装」或删掉。
692
+ - 手机上打开扩展页,在页面上**整页下拉刷新**一次,就能看到电脑那边有哪些包(「本地开发」那
693
+ 一段没有单独的刷新按钮,下拉即刷新)。开发包这个列表要退出这一页再重新进来才是新的。点
694
+ 「导入」就装进来;装过的会显示版本,可以「覆盖重装」或删掉。
676
695
  - 这条链路照样逐文件校验:传一半、被改过一字节,整包都不会落盘(不会留下半个能打开的包)。
677
696
  - 装进来的包标着「本地」,**不等于发布**:它只在你这台手机上看得见,随插件发版不会带走
678
697
  它,别的用户也拉不到。要让别人装上,走第 8 节那条——把它放进你自己插件的包里发一版。
@@ -683,7 +702,10 @@ body {
683
702
  问一次电脑「我这一份还是最新的吗」,发现内容变了就自己重装、自己重开。判据是文件内容
684
703
  (哈希),不是修改时间。
685
704
 
686
- 电脑这边要配一条命令,让它在你每次保存时把新产物铺到那个目录:
705
+ 电脑这边要有个循环,在你每次保存时把新产物铺到那个目录。这个 `dev-watch.mjs` **不在手机
706
+ 插件包里**,`dsh-mobile-plugin` 里也没有它 —— 它是作者自己项目里的一条构建 / 同步脚本,
707
+ 照仓库里 `dsh-magpie-plugin`、`dsh-canvas-plugin` 的 `scripts/dev-watch.mjs` 抄一份,或者
708
+ 在你自己的项目里接一条同样的命令:
687
709
 
688
710
  ```
689
711
  node scripts/dev-watch.mjs # 盯着改,边改边构建 + 同步;Ctrl-C 结束
@@ -727,23 +749,142 @@ node scripts/dev-watch.mjs --once # 只跑一次(等同于手动同步一次
727
749
  两条路可以一起用:dev server 开着时走它(热更新);不想开服务器时就 `dev-watch` 那条
728
750
  (构建 + 自动重装)。**第一次仍然要手动导入一次** —— 无论哪条路,手机得先知道有这个包。
729
751
 
730
- 想看清页面里发生了什么,用本地包顶栏右上角那个调试入口(下一条)。
752
+ 想看清页面里发生了什么,去电脑端查日志或开发者工具 —— 顶栏那个调试入口已经砍掉了,见 9.3。
753
+
754
+ ### 9.3 看日志
731
755
 
732
- 本地包比正式扩展多一个调试入口(顶栏右上角)。打开后是一条时间线:
756
+ 顶栏右上角那个调试面板已经砍掉了(2026-11-11),现在没有页面内的调试入口。要看页面里发生
757
+ 了什么,在电脑端查:
733
758
 
734
- - 你在页面里 `console.log/warn/error` 打的东西、没接住的异常;
735
- - 你发给 App 的每一条消息;
736
- - **没被认出来的消息是哪一档原因**:太大、不是 JSON、类型不认识、字段不全;
737
- - App 给你的回执,以及被哪项能力挡了;
738
- - 这一页被注入的上下文:接口版本、版本号、拿到了哪几项能力。
759
+ - **App 与电脑之间的收发**:宿主日志里有每一对消息的去向与回执,页面发出去的、宿主回过来的
760
+ 都能对上。
761
+ - **页面自己的 `console.log/warn/error` 与没接住的异常**:走网页内核的日志,别指望 App 里
762
+ 有地方看。平时开发页面挂在自己的 dev server(9.2)上、用浏览器那套开发者工具,最省事。
763
+ - **分清「没被认出来」的那几档**:消息太大、不是 JSON、类型不认识、字段不全 —— 到宿主日志
764
+ 里找对应的丢弃记录,或者按第 5 节的上限与白名单自己先判一遍。
739
765
 
740
- 同一条时间线上,消息顺序就是发生顺序,不用在页面上另写日志通道。面板上有「重载」(相当于
741
- 关掉再开一次)与「清空」。
766
+ 正式扩展更不给作者留后门:别在发布版里指望靠某个面板打日志。
742
767
 
743
- 正式扩展没有这块面板:它平时不给作者打日志,别在发布版里靠它。
768
+ ### 9.4 页面打不开,先看是哪一种
744
769
 
745
770
  - 页面打不开时,先看 App 给的提示是哪一种:**没装** / **两版都校验不过** / **页面自己
746
771
  报了 error**。这三种的出路不一样。
747
772
  - 能力没授予时的表现是「点了没反应」,但页面会收到 `capability-denied`,打一条日志就能
748
773
  分清是能力问题还是页面自己的问题。
749
774
  - 下载与校验都在 App 那侧,页面里看不到进度;装完再进页面才是新的一版。
775
+
776
+ ## 10. 怎么造一个 DSH 插件包
777
+
778
+ 第 8 节说了把扩展放进插件包就能发。这一节把这个「插件包」本身摊开:它就是一个普通 DSH
779
+ 插件,额外带了一份给手机用的扩展。下面每一格都对着仓库里真发出去的插件
780
+ (`dsh-magpie-plugin`、`dsh-canvas-plugin`)写,照它们的骨架抄就行。
781
+
782
+ ### 10.1 package.json
783
+
784
+ 一个能被装上、又能被手机认出来的插件包,`package.json` 至少长这样:
785
+
786
+ ```json
787
+ {
788
+ "name": "dsh-email-plugin",
789
+ "version": "0.1.0",
790
+ "type": "module",
791
+ "main": "./index.js",
792
+ "exports": {
793
+ ".": "./index.js",
794
+ "./package.json": "./package.json"
795
+ },
796
+ "engines": { "dsh": ">=0.2.0" },
797
+ "dsh": { "bundle": { "patch": "./cordis.patch.yml" } },
798
+ "dshMobileExtensions": "extensions",
799
+ "files": [
800
+ "index.js",
801
+ "cordis.patch.yml",
802
+ "lib/**/*.js",
803
+ "extensions/**",
804
+ "README.md",
805
+ "LICENSE"
806
+ ]
807
+ }
808
+ ```
809
+
810
+ 逐格说:
811
+
812
+ - `name`:包名,全局唯一。宿主按这个名字去 `node_modules` 里解析这个包,所以**它必须与
813
+ `cordis.patch.yml` 里那行 `name` 逐字一致**(见 10.3)。
814
+ - `version`:插件版本。扩展的更新跟着它走 —— 扩展目录里的 `manifest.json` 抬了号,插件
815
+ 也要发一版,用户升了插件,手机上的扩展才是新的。
816
+ - `type: "module"`:入口按 ESM 写。
817
+ - `main` 与 `exports`:指向入口文件,并且**把 `./package.json` 也导出**。宿主要读这份
818
+ `package.json` 才扫得到 `dshMobileExtensions` / `dshMobileDataServices`;`exports` 没把
819
+ `./package.json` 放出来,它就读不到,表现是「装了,但一个扩展都不出现」。
820
+ - `engines.dsh`:**只写下限**,例如 `">=0.2.0"`。别写上界(`">=0.2.0 <0.4.0"` 这种)——
821
+ 宿主升到 0.4,你这个包会被判成不兼容、**静默消失**:不报错、不提示,用户只觉得功能没了。
822
+ 只有真依赖了某个新特性,才抬下限。
823
+ - `dsh.bundle.patch`:指向挂载文件,说明这个包怎么插进 profile 的层栈。少了这一格,包在
824
+ `node_modules` 里躺着,但没有任何东西会去装载它。
825
+ - `dshMobileExtensions`:声明「包里哪个目录是给手机用的扩展」,值是包内的相对路径(写
826
+ `true` 等于 `extensions`)。没有这一格,手机不扫你的包,扩展一个都列不出来。
827
+ - `files`:npm 发版的白名单,**只列要发出去的东西**。`index.js`、挂载文件、`lib/`、你带的
828
+ `extensions/`、README 与 LICENSE 都写上;构建中间产物、测试、源码快照不进这个清单,
829
+ 否则包大出一截。`extensions/**` 这一行不写,扩展根本不进包。
830
+ - `repository`:可选,但**写上**。插件市场的关联、用户从哪儿看升级,都靠它;没有它,包在
831
+ 市场里是个孤儿。
832
+
833
+ **要读宿主数据的插件,还得自己声明 `dshMobileDataServices`**(第 5.5 节的规则):服务名
834
+ 和允许的路径前缀都在这儿定,`match` 用你自己的专属前缀,别用 `/api/` 去撞宿主的保留区。
835
+ 最小一份:
836
+
837
+ ```json
838
+ { "dshMobileDataServices": [{ "service": "dsh-email", "allow": ["/api/dsh-email/"] }] }
839
+ ```
840
+
841
+ 只做纯本地页面的插件不需要这一格。
842
+
843
+ ### 10.2 入口:导出 name 与 apply
844
+
845
+ 入口 `index.js` 导出两样:`name`(与包名逐字一致)和 `apply(ctx)`。
846
+
847
+ ```js
848
+ export const name = 'dsh-email-plugin'
849
+
850
+ export function apply(ctx) {
851
+ // 插件启动时要做的事放这里。
852
+ }
853
+ ```
854
+
855
+ - 只是「让包存在、把扩展列出来」,`apply` 可以什么都不做、记一行日志就够。
856
+ - 要注册自己的 HTTP 路由给扩展页取数(`host.data`)时,别在 `apply` 里直接
857
+ `ctx.get('webServer')`:插件常常比 `webServer` 先加载,那一刻拿到的还是 `undefined`,
858
+ 路由就永远挂不上。导出 `inject = ['webServer']`,在 `ctx.inject(['webServer'], (scoped) => {
859
+ ... })` 里挂,服务发布后它会跑、服务被替换时会重跑。
860
+ - **`apply` 里抛异常会拖垮整个 DSH 启动**。装载失败只记日志、别往外抛 —— 少一个插件不该让
861
+ 宿主起不来。
862
+
863
+ ### 10.3 cordis.patch.yml:把包挂进 profile
864
+
865
+ ```yaml
866
+ - insert:
867
+ - id: dsh-email
868
+ name: 'dsh-email-plugin'
869
+ config: {}
870
+ ```
871
+
872
+ - `name` **必须逐字等于 `package.json` 的 `name`**。loader 按它去 `node_modules` 里解析包,
873
+ 写歪了(大小写、少个后缀、多写 scope)**不报错**,只是这个插件永远载不进去 —— 表现就是
874
+ 「装了,但没有它」。这是最难查的一类:装完先在宿主日志里找找有没有这个名字打出来。
875
+ - `id` 是层栈里的标识,跟包名写成同一个最省心。
876
+ - 这个文件要被 `package.json` 的 `dsh.bundle.patch` 指到、也要列进 `files`,否则发出去的
877
+ 包里就没有它。
878
+
879
+ ### 10.4 装好之后:什么要重启,什么能热重载
880
+
881
+ - **插件第一次装载要重启 DSH**:宿主的插件层是进程启动时铺的,新装的插件(尤其 `apply`
882
+ 里要注册路由的那种)不重启不会跑。
883
+ - **扩展清单不靠重启**:宿主是**每次请求现扫** profile 里各插件的 `package.json`,所以包
884
+ 的文件已经落到 `node_modules` 之后,手机扩展页下拉一次就能看到你带的扩展。分开看:能不能
885
+ 「列出来」取决于包在不在盘上,能不能「跑起来」才看有没有重启。
886
+ - **`reload-dev` 只覆盖 `dsh-mobile-plugin` 自己**:它是我们这个插件自己开发时用的就地重载,
887
+ 换得掉本插件 `lib/impl.js` 那一层,换不掉别的插件,也管不到你新装的第三方插件 —— 别人的
888
+ 插件装完,老实重启。
889
+ - 扩展页(`index.html`)的改动和上面两条都无关:本地开发包走第 9 节那条自动刷新,正式扩展
890
+ 跟着插件发版更新。
@@ -18,9 +18,8 @@ index.html 入口页(固定这个名)
18
18
  2. 手机上:设置 → 扩展 → 打开「开发者模式」→ 回到扩展页 → 最底下「本地开发」→ 刷新 →
19
19
  「导入」。
20
20
 
21
- 3. 现在再改 `index.html` 里任何一个字,回到手机上重进这一页(或点调试面板的「重载」)
22
- 就是新的。要自动刷新,在你自己的插件仓库里串一条构建 + 拷到开发目录的循环,见
23
- `docs/extension-authoring.md` 第 9.1 节。
21
+ 3. 现在再改 `index.html` 里任何一个字,回到手机上重进这一页就是新的。要自动刷新,在你
22
+ 自己的插件仓库里串一条构建 + 拷到开发目录的循环,见 `docs/extension-authoring.md` 第 9.1 节。
24
23
 
25
24
  ## 它演示了三件事
26
25
 
@@ -7,6 +7,9 @@
7
7
  * 插件包自带的只读目录 —— 只有审过、登记进 `extensions/catalog.json` 的包才下发,目录里有但
8
8
  * 没登记的一律当不存在。审核闸门在清单,不在目录。
9
9
  *
10
+ * 第三方插件自己带的那一批走另一档(见 `third-party-extensions.js`):那边没有清单,能列就能装,
11
+ * 整包也由宿主把这台电脑上的目录现打成一个 zip(不会有预先产好的 `<slug>.zip`)。
12
+ *
10
13
  * 能力面只多「读这一个固定目录」:根由 `__dirname` 定位,不依赖进程 cwd,也不建目录;每个
11
14
  * 文件的 size 与 sha256 由宿主扫目录现算,不信清单里写的数字。取文件先挡绝对路径与 `..` 段,
12
15
  * 再 resolve 之后判前缀(带分隔符),不接受任意路径。仍然不暴露 shell、系统设置、任意文件读写。
@@ -71,6 +74,39 @@ function sha256Hex(raw) {
71
74
  return crypto.createHash('sha256').update(raw).digest('hex');
72
75
  }
73
76
 
77
+ /**
78
+ * 收窄清单里那一格 `devServer`:只认本机 / 局域网 / 回环上的 **http** 地址。
79
+ *
80
+ * 与开发包那条(`extension-dev.js` 的同名函数)同一套判据、同一份理由:这一格让手机把远程页面
81
+ * 装进扩展页的 WebView,写歪了重则把一个公网站点塞进 App 的沙箱里跑,所以只放行私网与回环、
82
+ * 只放行 http,其余一律当没写(页面退回加载本地那份,作者至少还能看到东西)。
83
+ */
84
+ function devServerOf(value) {
85
+ if (typeof value !== 'string') return null;
86
+ const raw = value.trim();
87
+ if (raw === '' || raw.length > 200) return null;
88
+ let url;
89
+ try { url = new URL(raw); } catch { return null; }
90
+ if (url.protocol !== 'http:') return null;
91
+ if (url.pathname !== '/' || url.search !== '' || url.hash !== '') return null;
92
+ const host = url.hostname;
93
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
94
+ if (ipv4) {
95
+ const octets = ipv4.slice(1).map((part) => Number(part));
96
+ if (octets.some((part) => part > 255)) return null;
97
+ const [a, b] = octets;
98
+ const privateOrLoop =
99
+ a === 127
100
+ || a === 10
101
+ || (a === 192 && b === 168)
102
+ || (a === 172 && b >= 16 && b <= 31);
103
+ return privateOrLoop ? `http://${host}:${url.port || '80'}/` : null;
104
+ }
105
+ if (host === 'localhost') return `http://localhost:${url.port || '80'}/`;
106
+ if (/\.local$/i.test(host)) return `http://${host}:${url.port || '80'}/`;
107
+ return null;
108
+ }
109
+
74
110
  /**
75
111
  * 读审核清单。文件不在、读坏、形状不对都当空清单 —— 空的插件包本来就没有第三方扩展。
76
112
  * 只收 slug / description / author / releaseNotes 四样,其余字段(包括任何 size / sha256)
@@ -159,6 +195,9 @@ function readPackage(directory, slug, meta = {}) {
159
195
  apiVersion: textField(manifest.apiVersion, textField(manifest.api_version, '1')),
160
196
  releaseNotes: meta.releaseNotes ?? null,
161
197
  capabilities: capabilitiesOf(manifest.capabilities),
198
+ // 作者在自己机器上开发时写进清单的开发服务器地址(可选,缺省 null):手机只在开发者模式下
199
+ // 读它拿 HMR,其余情况仍加载装到本地的那份。收窄判据同开发包那条。
200
+ devServer: devServerOf(manifest.devServer),
162
201
  // 取数声明一起下发:手机上「已装记录」里若缺这一项(早期版本装下的包),App 用当前电脑上
163
202
  // 这一份清单把老记录补上,页面才不会把 /api/… 解析成 file://… 而永远转圈。只下发声明,
164
203
  // 不在这里做任何放行判断(真正的边界在 extension-data.js 的服务登记表里)。
@@ -237,33 +276,75 @@ async function handleCatalog(_ctx, _req, res, root = catalogRoot(), pluginsRoot
237
276
  /**
238
277
  * GET /api/mobile/v1/extension/catalog/archive?slug=…(token)
239
278
  *
240
- * 整包一次下发:把一个已审核扩展的 **zip** 整个回成 base64。手机下载一个包、本地解包,
241
- * 不再按文件逐个拉几百次(那正是「269 次往返、两三百 KB/s」的病根)。zip 由产包脚本放在
242
- * `<root>/<slug>.zip`(与 slug 目录平级,不属于任何一包的文件清单)。
279
+ * 整包一次下发:把一个扩展的 **zip** 整个回成 base64。手机下载一个包、本地解包,
280
+ * 不再按文件逐个拉几百次(那正是「269 次往返、两三百 KB/s」的病根)。
243
281
  *
244
- * 审核闸门与取单文件一致:没登记进 catalog.json 的 slug 一律 404。zip 体积按包上限兜住。
282
+ * 两档来源各给各的 zip:
283
+ * - 随本插件发布的:zip 由产包脚本预先放在 `<root>/<slug>.zip`(与 slug 目录平级,不属于任何
284
+ * 一包的文件清单),这里只读;没有 zip 照旧 404,交给老插件的逐文件那条。
285
+ * - 第三方插件自带的:这台电脑上不会有人给它打包,所以与开发包那条一样**现打** —— 目录此刻的
286
+ * 样子就是手机装到的样子,不会拿到一份过期的 zip。
287
+ *
288
+ * 闸门与取单文件一致:slug 不合法 400,两档都不认识的 404,整包体积按包上限兜住(413)。
245
289
  */
246
- async function handleCatalogArchive(_ctx, req, res, root = catalogRoot()) {
290
+ async function handleCatalogArchive(_ctx, req, res, root = catalogRoot(), pluginsRoot = null) {
247
291
  const url = new URL(req.url || '/', 'http://x');
248
292
  const slug = (url.searchParams.get('slug') || '').trim();
249
293
  if (!slug || !SLUG_PATTERN.test(slug)) {
250
294
  return fail(res, 400, 'bad-request', '需要合法的 slug');
251
295
  }
252
- if (!readCatalog(root).some((entry) => entry.slug === slug)) {
253
- return fail(res, 404, 'package-missing', `审核清单里没有 ${slug} 这个包`);
254
- } const zipPath = path.join(root, `${slug}.zip`);
296
+ if (readCatalog(root).some((entry) => entry.slug === slug)) {
297
+ const zipPath = path.join(root, `${slug}.zip`);
298
+ let raw;
299
+ try {
300
+ const stat = fs.statSync(zipPath);
301
+ if (stat.size > MAX_PACKAGE_BYTES) return fail(res, 413, 'package-too-large', `${slug}.zip 超过整包上限`);
302
+ raw = fs.readFileSync(zipPath);
303
+ } catch {
304
+ // 没有 zip 不算错误:老插件 / 没打 zip 的包照旧走逐文件那条(App 侧会回退)。
305
+ return fail(res, 404, 'archive-missing', `${slug} 没有整包 zip,走逐文件下载`);
306
+ }
307
+ return sendJson(res, 200, { ok: true, slug, size: raw.length, sha256: sha256Hex(raw), content: raw.toString('base64') });
308
+ }
309
+
310
+ // 剩下只可能是第三方插件自己带的那一档:目录现扫(插件随手装 / 卸,缓存一版就要回答何时失效)。
311
+ const directory = thirdParty.directoryOf(pluginsRoot, slug);
312
+ if (!directory || !fs.existsSync(path.join(directory, 'manifest.json'))) {
313
+ return fail(res, 404, 'package-missing', `这台电脑上没有 ${slug} 这个扩展`);
314
+ }
315
+
255
316
  let raw;
256
317
  try {
257
- const stat = fs.statSync(zipPath);
258
- if (stat.size > MAX_PACKAGE_BYTES) return fail(res, 413, 'package-too-large', `${slug}.zip 超过整包上限`);
259
- raw = fs.readFileSync(zipPath);
260
- } catch {
261
- // 没有 zip 不算错误:老插件 / 没打 zip 的包照旧走逐文件那条(App 侧会回退)。
262
- return fail(res, 404, 'archive-missing', `${slug} 没有整包 zip,走逐文件下载`);
318
+ raw = zipDirectory(directory);
319
+ } catch (error) {
320
+ return fail(res, 500, 'archive-failed', `打包失败:${String(error?.message || error).slice(0, 200)}`);
321
+ }
322
+ if (raw.length > MAX_PACKAGE_BYTES) {
323
+ return fail(res, 413, 'package-too-large', `${slug} 整包 ${raw.length} 字节,超过上限 ${MAX_PACKAGE_BYTES}`);
263
324
  }
264
325
  sendJson(res, 200, { ok: true, slug, size: raw.length, sha256: sha256Hex(raw), content: raw.toString('base64') });
265
326
  }
266
327
 
328
+ /**
329
+ * 把一个目录打成 zip 字节(与 `extension-dev.js` 的整包同一条命令)。
330
+ *
331
+ * 用系统的 `zip`:宿主不引第三方压缩库,而 `zip` 三个桌面系统都有。`-X` 去掉多余的扩展属性、
332
+ * `-q` 安静、`-r` 递归;从目录里执行、打包 `.`,所以包内路径是相对路径,手机解出来的键与文件
333
+ * 清单里的 `path` 对得上。
334
+ */
335
+ function zipDirectory(directory) {
336
+ const outFile = path.join(require('node:os').tmpdir(), `dshm-catalog-${process.pid}-${Date.now()}.zip`);
337
+ try {
338
+ require('node:child_process').execFileSync('zip', ['-r', '-q', '-X', outFile, '.'], {
339
+ cwd: directory,
340
+ stdio: 'pipe',
341
+ });
342
+ return fs.readFileSync(outFile);
343
+ } finally {
344
+ try { fs.rmSync(outFile, { force: true }); } catch { /* 临时文件删不掉不影响结果 */ }
345
+ }
346
+ }
347
+
267
348
  /**
268
349
  * 一个 slug 对应的包目录:先查本插件里那批登记过的,再查第三方插件自己声明的。
269
350
  *
@@ -205,13 +205,22 @@ async function projectionBaseline(ctx, signal) {
205
205
  * 会话逐个查。
206
206
  *
207
207
  * 投影里没有运行时状态(跑没在跑、父会话在不在线),所以同口径再取一次会话列表的 summaries。
208
+ * 两发互不依赖,并发出去(见下面的注释),别改回串行。
208
209
  */
209
210
  async function subagentCatalog(ctx, payload, signal) {
210
211
  const parentSessionId = payload && payload.parentSessionId;
211
212
  if (typeof parentSessionId !== 'string' || !parentSessionId) {
212
213
  return fail({ code: 'bad-request', message: '缺少 parentSessionId' });
213
214
  }
214
- const list = await invoke(ctx, 'session', 'list', { _request: {} }, signal);
215
+ // **两发并发,不排队**:这两条互不依赖(list 给 summaries,基线给投影),串起来等于把
216
+ // 手机输入区那条最贵的请求乘二。真机记录里这条目录整发 2664ms,而同一时刻 App 自己在问
217
+ // 会话列表 —— 两次全量扫描日志的样子,就是这里先 list 再开流叠出来的。
218
+ //
219
+ // 基线自己吞异常、自带 3 秒截止,所以它跑在前面也不怕:list 失败照样走下面那条 fail。
220
+ const [list, baseline] = await Promise.all([
221
+ invoke(ctx, 'session', 'list', { _request: {} }, signal),
222
+ projectionBaseline(ctx, signal),
223
+ ]);
215
224
  if (list.error) return fail(list.error);
216
225
  const items = list.value && Array.isArray(list.value.items) ? list.value.items : [];
217
226
  const byId = new Map();
@@ -231,7 +240,6 @@ async function subagentCatalog(ctx, payload, signal) {
231
240
  ? false
232
241
  : typeof parent.agentAvailable === 'boolean' ? parent.agentAvailable : true;
233
242
 
234
- const baseline = await projectionBaseline(ctx, signal);
235
243
  // 基线优先:它是桌面端渲染目录的同一份数据。基线里没有这个会话、或者它的
236
244
  // subagentCatalog 还没算出来,就退回列表摘要内联的那份投影;两处都没有就当
237
245
  // 它没有派出过子代理。
@@ -335,6 +335,9 @@ const MAP = Object.freeze({
335
335
  '/api/mobile/v1/credentials/unset': V.CONFIG,
336
336
  '/api/mobile/v1/credentials': { GET: V.VIEW, POST: V.CONFIG },
337
337
  '/api/mobile/v1/plugin/self/auto': V.CONFIG,
338
+ // 「DSH 插件市场」的清单:只读一份社区公开 JSON、只算 installSpec,不装不卸、不写盘,
339
+ // 所以归读。装的动作仍走下面那几条 market 路由(CONFIG)。
340
+ '/api/mobile/v1/plugin/catalog': V.VIEW,
338
341
  '/api/mobile/v1/plugin/market/install': V.CONFIG,
339
342
  '/api/mobile/v1/plugin/market/remove': V.CONFIG,
340
343
  '/api/mobile/v1/plugin/market/update': V.CONFIG,
@@ -0,0 +1,501 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 手机侧「DSH 插件市场」的清单服务:读社区精选清单,收窄成 App 要的那一页。
5
+ *
6
+ * 为什么是读社区清单,而不是我们自己的分发系统:这一页装的是**电脑上 DSH 的插件**
7
+ * (npm 包 / GitHub 仓库),社区那份清单(awesome-dsh-plugin.com,另有 jsDelivr 上的镜像
8
+ * 一份)已经把「有哪些、是谁的、多少 star / 下载、图标、截图、能力声明」维护好了——那是
9
+ * 别人的一份公开索引,我们照读即可,没有自己的审核流水线要养。
10
+ *
11
+ * 为什么不在手机上装包、也不自己跑 pnpm:装插件是宿主的活。DSH 里本来就有插件管理器
12
+ * (桌面端 设置 → 插件 那个页面背后的同一个服务),版本兼容检查、依赖脚本授权、失败回滚、
13
+ * 要不要重启才生效,全由它判断。插件侧只把清单削干净、把 `installSpec` 算好,安装动作交给
14
+ * 已有的 `POST /plugin/market/install`。能力面对手机只多「读一份公开 JSON」(外网 GET),
15
+ * 仍然不碰 shell、不碰系统设置、不写任意文件。
16
+ *
17
+ * 三个取舍:
18
+ * 1. **缓存收窄后的结果,不缓存原文**:源清单 14MB / 4MB,缓存原文等于在宿主进程里常驻
19
+ * 十几 MB;收窄后通常是几百 KB 到一两 MB。10 分钟有效,过期重拉。
20
+ * 2. **过期重拉失败不回旧缓存**:清单过期是错误答案,不是降级答案(与 dshmarket 自己的
21
+ * 判据一致)。宁可让手机说「读不到清单」,也不要让它按一周前的数据装一个已经下架的包。
22
+ * 3. **并发只允许一个在飞**:手机切搜索词、翻页会连续打这条接口,每次各拉 14MB 毫无意义。
23
+ * 其余请求等同一个 Promise。
24
+ *
25
+ * 接口:`GET /api/mobile/v1/plugin/catalog`(走 token 守卫),query 见 A3-101。
26
+ * 失败回 `{ ok:false, error:{ code:'catalog-unavailable', message } }`,message 里带上每个源
27
+ * 各自的失败原因(排查时最想知道的是「哪一个源、哪一步坏了」)。
28
+ *
29
+ * 清单里认不出的条目**整条丢弃**:`name` / `owner` / `repo` 缺一、repo 不是
30
+ * `https://github.com/<owner>/<repo>`、或与 owner 不一致,都不是能安装的东西,App 侧不再兜。
31
+ */
32
+
33
+ const { sendJson } = require('../shared/http-util');
34
+
35
+ /**
36
+ * 数据源,按顺序试,前一个失败才试下一个。两份清单是社区同一批数据的两条腿:
37
+ * 主源字段全(star / 下载 / 图标 / 截图 / 收录时间),镜像源只剩名字、说明、仓库与版本。
38
+ */
39
+ const SOURCES = [
40
+ {
41
+ id: 'awesome',
42
+ url: 'https://awesome-dsh-plugin.com/plugins.json',
43
+ // { categories: { id: {en,zh} }, plugins: [...] }
44
+ format: 'plugins',
45
+ },
46
+ {
47
+ id: 'index',
48
+ url: 'https://cdn.jsdelivr.net/npm/dsh-plugin-catalog/index.json',
49
+ // { format: 1, metadata: { categories: { id: { title } } }, plugins: [...] }
50
+ format: 'index',
51
+ },
52
+ ];
53
+
54
+ /** 缓存有效期:清单一天更新不了几次,10 分钟足够新,也不至于每次翻页都拉 14MB。 */
55
+ const CACHE_TTL_MS = 10 * 60 * 1000;
56
+ /** 每个源最多试两次:14MB 的 CDN 偶发断流很常见,一次失败不代表源坏了。 */
57
+ const ATTEMPTS_PER_SOURCE = 2;
58
+ /** 单次拉取的等待上限。14MB 在慢网络上也要留够时间,但绝不能无限等。 */
59
+ const FETCH_TIMEOUT_MS = 30 * 1000;
60
+
61
+ /** 文案每门语言的字数上限(契约:600)。 */
62
+ const TEXT_MAX_CHARS = 600;
63
+ /** 图标只认 https 绝对地址;截图最多 4 张;能力最多 12 项(契约)。 */
64
+ const SCREENSHOTS_MAX = 4;
65
+ const CAPABILITIES_MAX = 12;
66
+ /** 搜索词上限 100 字,超了截断而不是报错:手机输入框不会让用户数到 100。 */
67
+ const Q_MAX_CHARS = 100;
68
+ /** 分页:缺省 20 条,最多 60 条一页(手机一屏装不下更多,再大只是白算)。 */
69
+ const LIMIT_DEFAULT = 20;
70
+ const LIMIT_MAX = 60;
71
+
72
+ const SORTS = ['downloads', 'stars', 'added', 'name'];
73
+ const DIRS = ['asc', 'desc'];
74
+ /** 条目没有分类时的落点:它仍会出现在「全部」里,只是不属于任何一颗胶囊。 */
75
+ const FALLBACK_CATEGORY = 'other';
76
+
77
+ /** 一份 `https://github.com/<owner>/<repo>`;允许尾部 `.git` 与多余斜杠,输出统一成干净形状。 */
78
+ const GITHUB_REPO = /^https:\/\/github\.com\/([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/;
79
+ /** npm 包名(含 scope)。只有合法名字才当安装目标,否则退回 github: 形态。 */
80
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
81
+ const NPM_NAME_MAX = 214;
82
+ /** 收录日期只认 `YYYY-MM-DD`。 */
83
+ const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
84
+
85
+ /** 收窄后的缓存:{ source, fetchedAt, fetchedAtWall, items, categories }。 */
86
+ let cache = null;
87
+ /** 正在飞的那一次拉取;并发请求等它。 */
88
+ let inflight = null;
89
+ /** 测试注入点:假 fetch 与假时钟。真跑时就是全局 fetch / Date.now。 */
90
+ let fetchImpl = null;
91
+ let clock = null;
92
+
93
+ function nowMs() {
94
+ return clock ? clock() : Date.now();
95
+ }
96
+
97
+ function errorText(error) {
98
+ if (!error) return '未知错误';
99
+ if (typeof error.message === 'string' && error.message) return error.message;
100
+ return String(error);
101
+ }
102
+
103
+ /** 非空字符串才收,其余 null;`max` 用来挡掉离谱长的字段。 */
104
+ function textOrNull(value, max = 300) {
105
+ if (typeof value !== 'string') return null;
106
+ const text = value.trim();
107
+ return text ? (max ? text.slice(0, max) : text) : null;
108
+ }
109
+
110
+ /** 只认 https 绝对地址:http 会混合内容、其它协议 App 也画不出来。 */
111
+ function httpsOrNull(value, max = 1000) {
112
+ const text = textOrNull(value, max);
113
+ if (!text) return null;
114
+ try {
115
+ return new URL(text).protocol === 'https:' ? text : null;
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 双语表:只留「语言 → 非空字符串」的项,每门语言截到 600 字;一项都不剩时是 `null`
123
+ * (不是空对象 —— App 侧据此判断「这条没有文案」)。
124
+ */
125
+ function localizedOf(value) {
126
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
127
+ const out = {};
128
+ for (const [language, text] of Object.entries(value)) {
129
+ const clean = textOrNull(text, TEXT_MAX_CHARS);
130
+ if (clean) out[language] = clean;
131
+ }
132
+ return Object.keys(out).length ? out : null;
133
+ }
134
+
135
+ /** 非负安全整数,否则 null(`stars` 那里再由调用方退成 0)。 */
136
+ function countOf(value) {
137
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return null;
138
+ return value;
139
+ }
140
+
141
+ /** 分类字段可能是字符串或字符串数组,取第一个可用值。 */
142
+ function firstString(value) {
143
+ if (typeof value === 'string') return textOrNull(value, 64);
144
+ if (Array.isArray(value)) {
145
+ for (const entry of value) {
146
+ const clean = textOrNull(entry, 64);
147
+ if (clean) return clean;
148
+ }
149
+ }
150
+ return null;
151
+ }
152
+
153
+ /** `https://` 截图数组,最多 4 张。 */
154
+ function screenshotsOf(value) {
155
+ if (!Array.isArray(value)) return [];
156
+ const out = [];
157
+ for (const entry of value) {
158
+ const url = httpsOrNull(entry);
159
+ if (url && out.length < SCREENSHOTS_MAX) out.push(url);
160
+ }
161
+ return out;
162
+ }
163
+
164
+ /** 能力声明:只留字符串,最多 12 项,重复的不给第二份。 */
165
+ function capabilitiesOf(value) {
166
+ if (!Array.isArray(value)) return [];
167
+ const out = [];
168
+ for (const entry of value) {
169
+ const name = textOrNull(entry, 64);
170
+ if (name && !out.includes(name) && out.length < CAPABILITIES_MAX) out.push(name);
171
+ }
172
+ return out;
173
+ }
174
+
175
+ /**
176
+ * 仓库地址解析:只认 `https://github.com/<owner>/<repo>`,统一成不带 `.git` / 尾斜杠的形状。
177
+ * 返回 null 表示这条不该进清单。
178
+ */
179
+ function parseRepo(value) {
180
+ const text = textOrNull(value, 300);
181
+ if (!text) return null;
182
+ const match = GITHUB_REPO.exec(text);
183
+ if (!match) return null;
184
+ return { owner: match[1], repo: match[2], url: `https://github.com/${match[1]}/${match[2]}` };
185
+ }
186
+
187
+ /**
188
+ * 一条原始记录 → 契约里的 Item;认不出就 null。
189
+ *
190
+ * `raw.owner` 有值时必须与 repo 里的 owner 一致(大小写不敏感):清单里这两格打架的条目,
191
+ * 装起来只会给人装错仓库。镜像源没有 owner 字段,从仓库地址里解析。
192
+ */
193
+ function normalizeItem(raw, sourceId) {
194
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
195
+ const name = textOrNull(raw.name, 200);
196
+ if (!name) return null;
197
+ const repoUrl = sourceId === 'index'
198
+ ? (raw.repository && raw.repository.url)
199
+ : (raw.url || (raw.repository && raw.repository.url));
200
+ const parsed = parseRepo(repoUrl);
201
+ if (!parsed) return null;
202
+ const declaredOwner = textOrNull(raw.owner, 100);
203
+ if (declaredOwner && declaredOwner.toLowerCase() !== parsed.owner.toLowerCase()) return null;
204
+
205
+ // 镜像源没有 npm 字段:它的 `name` 就是 npm 包名(契约这么写的)。
206
+ const npm = textOrNull(sourceId === 'index' ? raw.name : raw.npm, NPM_NAME_MAX);
207
+ // 分类:主源在顶层 `category`,镜像源在 `metadata.category`(都可能是字符串或数组)。
208
+ const rawCategory = sourceId === 'index' && raw.metadata ? raw.metadata.category : raw.category;
209
+ const npmValid = npm && NPM_NAME.test(npm) ? npm : null;
210
+
211
+ // 版本:主源给 `version`,镜像源给 `versions: [{ version }]` 取第一条。
212
+ const version = textOrNull(
213
+ raw.version || (Array.isArray(raw.versions) && raw.versions[0] && raw.versions[0].version),
214
+ 64,
215
+ );
216
+
217
+ const stars = countOf(raw.stars);
218
+ const downloads = countOf(raw.downloads);
219
+ const added = textOrNull(raw.added, 32);
220
+
221
+ return {
222
+ name,
223
+ owner: parsed.owner,
224
+ repo: parsed.url,
225
+ category: firstString(rawCategory) || FALLBACK_CATEGORY,
226
+ title: localizedOf(raw.title),
227
+ description: localizedOf(raw.description),
228
+ npm: npmValid,
229
+ version,
230
+ stars: stars === null ? 0 : stars,
231
+ downloads,
232
+ icon: httpsOrNull(raw.icon),
233
+ screenshots: screenshotsOf(raw.screenshots),
234
+ capabilities: capabilitiesOf(raw.capabilities),
235
+ // 安装目标是宿主算好的:有合法 npm 名就用它,否则让插件管理器按 GitHub 仓库去装。
236
+ installSpec: npmValid || `github:${parsed.owner}/${parsed.repo}`,
237
+ added: added && DAY_PATTERN.test(added) ? added : null,
238
+ };
239
+ }
240
+
241
+ /**
242
+ * 两份清单的形状差异只在这里抹平:返回 { categories, items }。
243
+ * `items` 已去重(按 `owner/name`,同一份清单里同名同源的两条只留第一条)。
244
+ */
245
+ function narrowCatalog(document, source) {
246
+ if (!document || typeof document !== 'object') throw new Error('返回的不是清单 JSON');
247
+ if (source.format === 'index' && document.format !== 1) {
248
+ throw new Error(`清单格式不认识(format=${String(document.format)})`);
249
+ }
250
+ const plugins = document.plugins;
251
+ if (!Array.isArray(plugins) || plugins.length === 0) throw new Error('清单里没有 plugins 数组');
252
+
253
+ // 分类:主源是 `categories: { id: {en,zh} }`,镜像源是 `metadata.categories: { id: { title } }`。
254
+ const rawCategories = source.format === 'index'
255
+ ? (document.metadata && document.metadata.categories)
256
+ : document.categories;
257
+ const categories = [];
258
+ if (rawCategories && typeof rawCategories === 'object' && !Array.isArray(rawCategories)) {
259
+ for (const [id, value] of Object.entries(rawCategories)) {
260
+ const cleanId = textOrNull(id, 64);
261
+ if (!cleanId) continue;
262
+ const title = source.format === 'index'
263
+ ? (localizedOf(value && value.title) || localizedOf(value))
264
+ : localizedOf(value);
265
+ // 分类没写文案时退回 id 当名字:胶囊总得有个字,不能画成空白。
266
+ categories.push({ id: cleanId, title: title || { en: cleanId } });
267
+ }
268
+ }
269
+
270
+ const seen = new Set();
271
+ const items = [];
272
+ for (const raw of plugins) {
273
+ const item = normalizeItem(raw, source.id);
274
+ if (!item) continue;
275
+ const key = `${item.owner}/${item.name}`.toLowerCase();
276
+ if (seen.has(key)) continue;
277
+ seen.add(key);
278
+ items.push(item);
279
+ }
280
+ if (items.length === 0) throw new Error('清单里没有一条可用的插件(缺仓库地址或名字)');
281
+ return { categories, items };
282
+ }
283
+
284
+ /** 拉一个源:读 JSON、把表单收窄。抛出的错误由 `loadCatalog` 记进失败原因。 */
285
+ async function fetchCatalogDocument(source) {
286
+ const doFetch = fetchImpl || globalThis.fetch;
287
+ if (typeof doFetch !== 'function') throw new Error('这个运行时里没有 fetch,拉不了清单');
288
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
289
+ const timer = controller ? setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS) : null;
290
+ let response;
291
+ try {
292
+ response = await doFetch(source.url, {
293
+ headers: { accept: 'application/json' },
294
+ signal: controller ? controller.signal : undefined,
295
+ });
296
+ } catch (error) {
297
+ throw new Error(`连不上:${errorText(error)}`);
298
+ } finally {
299
+ if (timer) clearTimeout(timer);
300
+ }
301
+ if (!response || response.ok !== true) {
302
+ const status = response && Number.isFinite(response.status) ? response.status : 0;
303
+ throw new Error(`HTTP ${status || '未知'}`);
304
+ }
305
+ try {
306
+ return await response.json();
307
+ } catch {
308
+ throw new Error('返回的不是 JSON');
309
+ }
310
+ }
311
+
312
+ /**
313
+ * 按顺序试源,每个源最多两次;全挂了抛错,message 是每个源各自的失败原因拼接。
314
+ * 成功时把**收窄后**的结果塞进缓存(不是原文)。
315
+ */
316
+ async function fetchCatalog() {
317
+ const failures = [];
318
+ for (const source of SOURCES) {
319
+ for (let attempt = 1; attempt <= ATTEMPTS_PER_SOURCE; attempt += 1) {
320
+ try {
321
+ const document = await fetchCatalogDocument(source);
322
+ const { categories, items } = narrowCatalog(document, source);
323
+ const fetchedAt = nowMs();
324
+ cache = {
325
+ source: source.url,
326
+ fetchedAt,
327
+ // 墙钟另存一份:`fetchedAt` 走可注入的时钟(测试用),这一格永远是真实时间。
328
+ fetchedAtWall: Date.now(),
329
+ items,
330
+ categories,
331
+ };
332
+ return cache;
333
+ } catch (error) {
334
+ failures.push(`${source.url} 第 ${attempt} 次:${errorText(error)}`);
335
+ }
336
+ }
337
+ }
338
+ throw new Error(failures.join(';'));
339
+ }
340
+
341
+ /**
342
+ * 取一份可用的收窄结果。
343
+ *
344
+ * - 缓存有效期内直接返回;
345
+ * - 过期 / 没有缓存时拉一次,**失败就抛**(绝不拿旧缓存冒充成功);
346
+ * - 并发只允许一个在飞:后来者 await 同一个 Promise。
347
+ */
348
+ async function loadCatalog() {
349
+ const at = nowMs();
350
+ if (cache && at - cache.fetchedAt >= 0 && at - cache.fetchedAt < CACHE_TTL_MS) return cache;
351
+ if (!inflight) {
352
+ inflight = fetchCatalog().finally(() => { inflight = null; });
353
+ }
354
+ return inflight;
355
+ }
356
+
357
+ /** 搜索词:名字 / 作者 / 仓库名 / 双语标题与说明 / npm 名,大小写不敏感。 */
358
+ function matchesQuery(item, needle) {
359
+ if (!needle) return true;
360
+ const haystack = [
361
+ item.name,
362
+ item.owner,
363
+ item.repo,
364
+ item.npm || '',
365
+ ...Object.values(item.title || {}),
366
+ ...Object.values(item.description || {}),
367
+ ...item.capabilities,
368
+ ].join('\n').toLowerCase();
369
+ return haystack.includes(needle);
370
+ }
371
+
372
+ /** 排序值:缺一格时 `null`(排在最后,与 App 侧「缺哪格就不画」一致)。 */
373
+ function sortValue(item, sort) {
374
+ if (sort === 'downloads') return item.downloads;
375
+ if (sort === 'stars') return item.stars;
376
+ if (sort === 'added') return item.added;
377
+ return item.name.toLowerCase();
378
+ }
379
+
380
+ /**
381
+ * 比较:null 恒排最后(不管升序降序,都不该让「没有数据」冒到顶上——镜像源本来就没有
382
+ * 下载量,排在前面等于整页被一堆空数字占住)。
383
+ */
384
+ function compareItems(a, b, sort, dir) {
385
+ const left = sortValue(a, sort);
386
+ const right = sortValue(b, sort);
387
+ if (left === null && right === null) return compareNames(a, b);
388
+ if (left === null) return 1;
389
+ if (right === null) return -1;
390
+ if (left === right) return compareNames(a, b);
391
+ const order = left < right ? -1 : 1;
392
+ return dir === 'asc' ? order : -order;
393
+ }
394
+
395
+ /** 同值的兜底顺序:名字、再作者。翻页因此是确定性的,不会两页看到同一条。 */
396
+ function compareNames(a, b) {
397
+ const an = a.name.toLowerCase();
398
+ const bn = b.name.toLowerCase();
399
+ if (an !== bn) return an < bn ? -1 : 1;
400
+ const ao = a.owner.toLowerCase();
401
+ const bo = b.owner.toLowerCase();
402
+ if (ao !== bo) return ao < bo ? -1 : 1;
403
+ return 0;
404
+ }
405
+
406
+ /** 取整数 query 参数;不是整数就退回缺省。 */
407
+ function intParam(raw, fallback) {
408
+ if (typeof raw !== 'string' || !/^\d+$/.test(raw.trim())) return fallback;
409
+ return Number.parseInt(raw.trim(), 10);
410
+ }
411
+
412
+ /**
413
+ * query 清洗。排序 / 方向 / 分页的缺省与上限全部照契约;认不出的值退回缺省而不是报错
414
+ * (手机拼错一个参数不该让整页变红,界面上的胶囊本来就只会给合法值)。
415
+ */
416
+ function parseQuery(searchParams) {
417
+ const q = textOrNull(searchParams.get('q'), Q_MAX_CHARS) || '';
418
+ const rawCategory = textOrNull(searchParams.get('category'), 64);
419
+ const category = rawCategory && rawCategory !== 'all' ? rawCategory : 'all';
420
+ const rawSort = textOrNull(searchParams.get('sort'), 16);
421
+ const sort = SORTS.includes(rawSort) ? rawSort : 'downloads';
422
+ const rawDir = textOrNull(searchParams.get('dir'), 8);
423
+ const dir = DIRS.includes(rawDir) ? rawDir : (sort === 'name' ? 'asc' : 'desc');
424
+ const offset = intParam(searchParams.get('offset'), 0);
425
+ const limit = Math.min(Math.max(intParam(searchParams.get('limit'), LIMIT_DEFAULT), 1), LIMIT_MAX);
426
+ return { q: q.toLowerCase(), category, sort, dir, offset, limit };
427
+ }
428
+
429
+ /**
430
+ * 把一份收窄结果切成契约要的那一页。
431
+ *
432
+ * `categories` 的 `count` 只受搜索词影响、**不受 `category` 影响**:否则选中一颗胶囊之后
433
+ * 其余胶囊的计数全变 0,界面只能把它们藏起来,用户就再也切不回去了。
434
+ */
435
+ function pageOf(catalog, query) {
436
+ const searched = query.q ? catalog.items.filter((item) => matchesQuery(item, query.q)) : catalog.items;
437
+
438
+ const counts = new Map();
439
+ for (const item of searched) counts.set(item.category, (counts.get(item.category) || 0) + 1);
440
+ const categories = catalog.categories.map((category) => ({
441
+ id: category.id,
442
+ title: category.title,
443
+ count: counts.get(category.id) || 0,
444
+ }));
445
+
446
+ const filtered = query.category === 'all'
447
+ ? searched
448
+ : searched.filter((item) => item.category === query.category);
449
+
450
+ const sorted = filtered.slice().sort((a, b) => compareItems(a, b, query.sort, query.dir));
451
+
452
+ const items = sorted.slice(query.offset, query.offset + query.limit);
453
+ return {
454
+ source: catalog.source,
455
+ fetchedAt: catalog.fetchedAt,
456
+ total: sorted.length,
457
+ categories,
458
+ items,
459
+ hasMore: query.offset + items.length < sorted.length,
460
+ };
461
+ }
462
+
463
+ /** GET /api/mobile/v1/plugin/catalog */
464
+ async function handlePluginCatalog(ctx, req, res) {
465
+ let catalog;
466
+ try {
467
+ catalog = await loadCatalog();
468
+ } catch (error) {
469
+ return sendJson(res, 503, {
470
+ ok: false,
471
+ error: { code: 'catalog-unavailable', message: errorText(error) },
472
+ });
473
+ }
474
+ let query;
475
+ try {
476
+ query = parseQuery(new URL((req && req.url) || '/', 'http://x').searchParams);
477
+ } catch {
478
+ query = parseQuery(new URLSearchParams());
479
+ }
480
+ const page = pageOf(catalog, query);
481
+ sendJson(res, 200, { ok: true, ...page });
482
+ }
483
+
484
+ module.exports = {
485
+ handlePluginCatalog,
486
+ // 纯逻辑(守卫 / 测试直接加载)
487
+ parseQuery,
488
+ pageOf,
489
+ narrowCatalog,
490
+ normalizeItem,
491
+ loadCatalog,
492
+ SOURCES,
493
+ CACHE_TTL_MS,
494
+ LIMIT_DEFAULT,
495
+ LIMIT_MAX,
496
+ Q_MAX_CHARS,
497
+ // 测试注入:假 fetch / 假时钟 / 清缓存(真跑时一个都不该被调用)
498
+ __setFetchForTests(next) { fetchImpl = next || null; },
499
+ __setClockForTests(next) { clock = next || null; },
500
+ __resetForTests() { cache = null; inflight = null; fetchImpl = null; clock = null; },
501
+ };
@@ -23,7 +23,6 @@ const sessions = require('../mobile/sessions.js');
23
23
  const sessionModelOptions = require('../mobile/session-model-options.js');
24
24
  const sessionFile = require('../mobile/session-file.js');
25
25
  const sessionLocalImage = require('../mobile/session-local-image.js');
26
- const { promoReceiver: promoReceiverCoords } = require('../mobile/promo-receiver.cjs');
27
26
  const sessionStep = require('../mobile/session-step.js');
28
27
  // 停止后那份「本轮交代」:从这一轮的步骤流折成展示结构(见 mobile/session-stop-summary.js)。
29
28
  // 只读步骤流、只算纯展示数据,不碰 shell / 系统设置 / 任意文件写。
@@ -75,6 +74,8 @@ const pushNotifyRoute = require('../mobile/push-notify-route.js');const plugins
75
74
  const pluginUpdate = require('../mobile/plugin-update.js');
76
75
  const pluginSelf = require('../mobile/plugin-self.js');
77
76
  const pluginMarket = require('../mobile/plugin-market.js');
77
+ // 社区精选清单(见 mobile/plugin-catalog.js):手机侧「DSH 插件市场」的数据来源,只读外网 JSON。
78
+ const pluginCatalog = require('../mobile/plugin-catalog.js');
78
79
  const { createRelayControlHandlers } = require('../mobile/relay-control.js');
79
80
  const uploads = require('../mobile/uploads.js');
80
81
  const inboxClean = require('../mobile/inbox-clean.js');
@@ -377,9 +378,6 @@ function registerMobileRoutes(deps) {
377
378
  ipv6Candidates: ipv6,
378
379
  updatedAt: lanUpdatedAt,
379
380
  lastSeen: lanUpdatedAt,
380
- // 商店素材的接收端(本机的 Mac-to-eagle 桌面程序):手机端不用手填地址与密钥,
381
- // 这里一并交给它。没有那个程序 / 还没生成密钥时是 null(App 那边什么都不做)。
382
- promoReceiver: promoReceiverCoords({ lanCandidates: candidates }),
383
381
  })
384
382
  })
385
383
 
@@ -669,6 +667,10 @@ function registerMobileRoutes(deps) {
669
667
  route('/api/mobile/v1/plugin/market/cancel', pluginMarket.handlePluginMarketCancel)
670
668
  route('/api/mobile/v1/plugin/market/enabled', pluginMarket.handlePluginMarketEnabled)
671
669
 
670
+ // 「DSH 插件市场」那一页的清单(见 mobile/plugin-catalog.js):社区精选清单收窄成手机要
671
+ // 的形状,只读、带 10 分钟缓存。装的动作仍走上面已有的 `/plugin/market/install`。
672
+ route('/api/mobile/v1/plugin/catalog', pluginCatalog.handlePluginCatalog)
673
+
672
674
  // 插件自更新:APP 的「应用更新」页给这台宿主升级插件版本(见 mobile/plugin-update.js)。
673
675
  // 与桌面控制面 `/api/relay/update/*` 同一套实现,差别只在入口:那三条 localOnly,手机
674
676
  // 永远打不到,而手机上聊天时「有对话在跑」那道闸几乎总关着 —— 自动更新等于不跑。
@@ -720,7 +722,11 @@ function registerMobileRoutes(deps) {
720
722
  extensionCatalog.handleCatalogFile(ctx, req, res, undefined, profileNodeModulesOf(ctx))
721
723
  ))
722
724
  // 整包一次下发(zip → base64),手机下载一个包再本地解包,不再逐文件拉几百次。
723
- route('/api/mobile/v1/extension/catalog/archive', extensionCatalog.handleCatalogArchive)
725
+ // 随本插件发布那一档读产包脚本预先放好的 `<slug>.zip`;第三方插件自己带的那一档由宿主现打
726
+ // (那台电脑上不会有别人替他打包),所以同样要把 profile 的 node_modules 传进去。
727
+ route('/api/mobile/v1/extension/catalog/archive', (ctx, req, res) => (
728
+ extensionCatalog.handleCatalogArchive(ctx, req, res, undefined, profileNodeModulesOf(ctx))
729
+ ))
724
730
 
725
731
  // 分享文件的落地通道(App 把手机分享进来的文件分片传上来,见 mobile/uploads.js)。
726
732
  // 手机端没有「把文件交给宿主」的路:图片能进 session.send 的 base64 内容块,其它格式
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.40",
3
+ "version": "0.5.41",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",
@@ -1,77 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 商店素材接收端(本机那个 Mac-to-eagle 桌面程序)的坐标。
5
- *
6
- * 为什么由插件来报:用户在手机 App 里不该填任何东西(2026-11-07 明确要求)。而「这台电脑的
7
- * 局域网地址 + 桌面程序的配对密钥」只有插件这一侧知道 —— 它本来就跑在这台电脑上,局域网候选
8
- * 地址(`lan-network`)和桌面程序写下的密钥文件都在本机,读一下就能把两样一起交给手机。
9
- *
10
- * 桌面程序不在跑 / 没装 / 还没生成密钥,就回 null:App 那边据此什么也不做(原图照旧留相册),
11
- * 不会因为「这台电脑上没有它」而报错。
12
- */
13
-
14
- const fs = require('node:fs');
15
- const os = require('node:os');
16
- const path = require('node:path');
17
-
18
- /** 桌面程序的默认端口(见 Mac-to-eagle `LocalAPIServer.preferredPort`)。 */
19
- const DESKTOP_PORT = 47291;
20
-
21
- /** 密钥文件:桌面程序用 owner-only 权限写在应用数据目录里。 */
22
- function accessKeyFile() {
23
- // 与 Mac-to-eagle `AppPaths.appSupport` 同一套规则:环境变量优先,其次用户应用数据目录。
24
- const override = process.env.MACTOEAGLE_DATA_DIR;
25
- const base = override && override.startsWith('/')
26
- ? override
27
- : path.join(os.homedir(), 'Library', 'Application Support', 'MacToEagle');
28
- return path.join(base, 'mobile-access-key');
29
- }
30
-
31
- /** 读配对密钥;读不到就 null(不是错误,只说明这台电脑上没有那个程序)。 */
32
- function readAccessKey() {
33
- try {
34
- const value = fs.readFileSync(accessKeyFile(), 'utf8').trim();
35
- return value || null;
36
- } catch {
37
- return null;
38
- }
39
- }
40
-
41
- /**
42
- * 这台电脑上、手机能拨到的那个局域网地址。
43
- *
44
- * 直接用 `lan-network` 那套候选(它已经滤掉了 VPN / 虚拟网卡、把私网排在前面),取第一条的
45
- * 主机部分 —— 素材回传只需要一个能连通的地址,不需要像会话通道那样挨个试。
46
- */
47
- function pickLanHost(lanCandidates) {
48
- const first = Array.isArray(lanCandidates) ? lanCandidates.find((item) => item && item.url) : null;
49
- if (!first) return null;
50
- try {
51
- return new URL(first.url).hostname;
52
- } catch {
53
- return null;
54
- }
55
- }
56
-
57
- /**
58
- * 组装给 App 的那一格。
59
- *
60
- * @param {{ lanCandidates?: Array<{url?: string}> }} options 与 `/connection-info` 同一份候选
61
- * @returns {{ url: string, key: string } | null}
62
- */
63
- function promoReceiver({ lanCandidates } = {}) {
64
- const key = readAccessKey();
65
- if (!key) return null;
66
- const host = pickLanHost(lanCandidates);
67
- if (!host) return null;
68
- return { url: `http://${host}:${DESKTOP_PORT}`, key };
69
- }
70
-
71
- module.exports = {
72
- DESKTOP_PORT,
73
- accessKeyFile,
74
- readAccessKey,
75
- pickLanHost,
76
- promoReceiver,
77
- };