@coda-console/resource-manager 0.9.3 → 0.9.5

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.
package/lib/draft.mjs CHANGED
@@ -1,57 +1,31 @@
1
- // 把文字追加到会话的输入框草稿(设计见 docs/design/phase-3.md 第 13.5 节)。
2
- // 用的是 Coda 未公开的草稿接口:依赖它的代码只在这一个文件里,上游开放正式接口后只改这里。
3
- // 流程:读草稿 → 拼文字 → 保存。保存带上现有附件的 ID,否则会删掉用户已添加的附件。
1
+ // 把文字追加到会话的输入框草稿:经 coda/thread@1 的操作 append-draft。
2
+ // 宿主在同一事务里读草稿、按 line 插入分隔符并保存,保留现有附件、按 10 万字上限校验;
3
+ // 原样传 text,避免与宿主的分隔符叠加造成连续追加多出空格或空行。
4
4
  import { DRAFT_LIMIT, ErrorCode, fail } from '../view/protocol.mjs';
5
5
 
6
- const RETRIES = 2; // 版本不符后用服务端的内容重拼,最多再试这么多次
7
-
8
- // block 为 false(路径、位置):接在现有文字后面,前后各留一个空格(已有空白或为空时前面不加)。
9
- // block 为 true(内容):另起一行,结尾换行;文字本身已以换行结尾的不再多加,免得多出空行。只能追加到末尾。
10
- export function compose(current, text, block) {
11
- if (block) return `${current}${current === '' || current.endsWith('\n') ? '' : '\n'}${text}${text.endsWith('\n') ? '' : '\n'}`;
12
- return `${current}${current === '' || /\s$/.test(current) ? '' : ' '}${text} `;
13
- }
14
-
15
- // 接口路径只在这里写:测试和 harness 的假接口也从这里取。
16
- export const draftPath = session => `threads/${encodeURIComponent(session)}/draft`;
17
- // 反过来:路径是草稿接口的返回会话,不是返回 null。
18
- export function draftSession(path) {
19
- const match = /^threads\/([^/]+)\/draft$/.exec(path);
20
- return match ? decodeURIComponent(match[1]) : null;
21
- }
22
-
23
6
  const failed = () => fail(ErrorCode.DRAFT_FAILED, '读写草稿失败');
7
+ const tooLong = () => fail(ErrorCode.DRAFT_TOO_LONG, '草稿太长,放不下');
24
8
 
25
- // 接口回答里的草稿 → { text, revision, ids };形状不对算失败。
26
- function parseDraft(draft) {
27
- if (typeof draft?.text !== 'string' || !Array.isArray(draft.attachments)) throw failed();
28
- const ids = draft.attachments.map(attachment => attachment?.id);
29
- if (!ids.every(id => typeof id === 'string')) throw failed();
30
- return { text: draft.text, revision: draft.revision, ids };
9
+ function isTooLong(error) {
10
+ const code = typeof error?.code === 'string' ? error.code.toLowerCase() : '';
11
+ if (code === ErrorCode.DRAFT_TOO_LONG || code === ErrorCode.TOO_LARGE || code === 'too_long' || code === 'payload_too_large') return true;
12
+ const message = typeof error?.message === 'string' ? error.message : '';
13
+ return /too[_ ]?long|limit|上限|太长|过长|超出|超过/i.test(message);
31
14
  }
32
15
 
33
- // 追加成功返回 true;valid() 变假(会话换了、视图关了)静默结束,返回 false:不写、不报。
34
- // 每次保存之前、每个 await 回来之后都核对,重试也始终写传进来的这个会话。
35
- // 失败抛 draft_failed(保存的回答不带合法的 draft 也算失败),拼完超过上限抛 draft_too_long,不截断。
36
- export async function addText(coda, session, { text, block }, { valid = () => true } = {}) {
16
+ // 追加成功返回 true;valid() 变假或 signal 已中止(会话换了、视图关了)静默结束,返回 false:不写、不报。
17
+ // block 为 true(内容)时传 line: true,false(路径、位置)时传 line: false。
18
+ // 失败抛 draft_failed,拼完超过上限抛 draft_too_long,不截断。
19
+ export async function addText(coda, session, { text, block }, { valid = () => true, signal } = {}) {
37
20
  if (typeof text !== 'string' || text.includes('\0') || typeof block !== 'boolean') throw failed();
38
- const path = draftPath(session);
39
- const call = async body => {
40
- try { return await (body ? coda.api(path, body) : coda.api(path)); } catch { throw failed(); }
41
- };
42
-
43
- const first = await call();
44
- if (!valid()) return false;
45
- let draft = parseDraft(first);
46
- for (let attempt = 0; ; attempt++) {
47
- const next = compose(draft.text, text, block);
48
- if (next.length > DRAFT_LIMIT) throw fail(ErrorCode.DRAFT_TOO_LONG, '草稿太长,放不下');
49
- const saved = await call({ text: next, attachments: draft.ids, revision: draft.revision });
50
- if (!valid()) return false;
51
- const reply = parseDraft(saved?.draft); // 成功和版本不符的回答都带 draft;没有或形状不对,不能当成已写入
52
- if (!saved.conflict) return true;
53
- if (attempt >= RETRIES) throw failed();
54
- draft = reply;
55
- if (!valid()) return false;
21
+ if (text.length > DRAFT_LIMIT) throw tooLong();
22
+ if (!valid() || signal?.aborted) return false;
23
+ try {
24
+ await coda.call({ kind: 'coda/thread@1', id: session }, 'append-draft', { text, line: block }, signal ? { signal } : undefined);
25
+ } catch (error) {
26
+ if (!valid() || signal?.aborted) return false;
27
+ if (isTooLong(error)) throw tooLong();
28
+ throw failed();
56
29
  }
30
+ return valid() && !signal?.aborted;
57
31
  }
package/lib/media.mjs CHANGED
@@ -8,6 +8,7 @@ import { ErrorCode, servedType } from '../view/protocol.mjs';
8
8
  import { fromFsError, resolveInRoot } from './paths.mjs';
9
9
 
10
10
  const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
11
+ const NONBLOCK = constants.O_NONBLOCK ?? 0;
11
12
 
12
13
  const CORS = { 'access-control-allow-origin': '*', 'access-control-expose-headers': 'content-length, content-range, etag' };
13
14
 
@@ -50,7 +51,8 @@ export function createMedia() {
50
51
  if (!type) return end(415);
51
52
  let handle;
52
53
  try {
53
- handle = await open(await resolveInRoot(root, path), constants.O_RDONLY | NOFOLLOW);
54
+ // 加 O_NONBLOCK:避免指向命名管道(FIFO)时在 open 阶段永久阻塞,随后由 info.isFile() 及时拒绝。
55
+ handle = await open(await resolveInRoot(root, path), constants.O_RDONLY | NOFOLLOW | NONBLOCK);
54
56
  const info = await handle.stat();
55
57
  if (!info.isFile()) return end(404);
56
58
  const { size } = info;
package/lib/root.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // 从会话取根目录。这是唯一读取 `threads/<id>` 返回结构(checkout)和 `agents` 返回结构(projects)的地方,它们都不是文档写明的契约。
1
+ // 从会话取根目录:经 coda/thread@1 的只读查询 workspace 取 { path, project: { id, name }, state }。
2
2
  import { realpath, stat } from 'node:fs/promises';
3
3
  import { RootState } from '../view/protocol.mjs';
4
4
 
@@ -7,15 +7,10 @@ export const NO_ROOT = Object.freeze({ state: RootState.NONE, path: null, projec
7
7
  // project 不是根目录的身份(保存、恢复、换根都只看路径),但变了页面要重画标题,所以算进来。
8
8
  export const sameRoot = (a, b) => a?.state === b?.state && a?.path === b?.path && (a?.project ?? null) === (b?.project ?? null);
9
9
 
10
- // worktree 的项目名:Coda 里这个会话所属项目的名字。Coda 的 worktree 目录以 UUID 命名,只看目录名认不出项目。
11
- // 项目 id 是会话详情里 checkout 的 projectId(缺了看 detail.thread.projectId),名字查 `agents` 回答里的 projects([{ id, name }])。
12
- // 会话详情 `threads/<id>` 的回答结构是 { thread: { …, projectId }, draft, checkout, … }:thread 是详情里的一个字段,checkout 和它并列,不是 thread 的子字段。
13
- // 项目名默认是原仓库的文件夹名;在 Coda 里改过名字时显示改后的。不读任何文件:项目名不来自工作目录之外的东西(设计第 19.7 节)。
14
- // 取不到(没有 id、接口失败、列表里没有这个 id、名字为空)都是 null,页面退回显示文件夹名;这里从不抛:
15
- // queryRoot 抛出的意思是「保留上一次的根目录」,项目名取不到不该触发它。
16
- // 项目列表按机器缓存(WeakMap:一个 coda 一份),很少变:超过 MAX_AGE 或查不到这个 id 时重取,两次请求之间至少隔 MISS_AGE(接口失败也算一次),不会反复请求;同时发起的查询共用一次请求。
17
- const MAX_AGE = 60_000, MISS_AGE = 5_000, NAME_LIMIT = 256;
18
- const caches = new WeakMap(); // coda → { names: Map(id → name) | null, at: 上次请求的时间, pending: 在途的请求 | null }
10
+ // Coda 的 worktree 目录以 UUID 命名,只看目录名认不出项目,所以给页面带上项目名;普通目录的目录名本身就能认出,project 留 null。
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const NAME_LIMIT = 256;
13
+ const baseName = path => path.split('/').filter(Boolean).pop() ?? '';
19
14
 
20
15
  // 名字:去掉首尾空白,空的、含控制字符的不用,太长的按码点截断。
21
16
  function cleanName(name) {
@@ -25,47 +20,24 @@ function cleanName(name) {
25
20
  return Array.from(text).slice(0, NAME_LIMIT).join('');
26
21
  }
27
22
 
28
- async function fetchNames(coda, cache, now) {
29
- cache.at = now();
30
- try {
31
- const reply = await coda.api('agents');
32
- const names = new Map();
33
- for (const project of Array.isArray(reply?.projects) ? reply.projects : []) {
34
- if (typeof project?.id === 'string' && project.id) names.set(project.id, cleanName(project.name));
35
- }
36
- cache.names = names;
37
- } catch { /* 取不到:保留上一次的列表,名字退回文件夹名 */ }
38
- }
39
-
40
- async function projectNameOf(coda, projectId, now) {
41
- if (typeof projectId !== 'string' || !projectId) return null;
42
- try {
43
- let cache = caches.get(coda);
44
- if (!cache) caches.set(coda, cache = { names: null, at: -Infinity, pending: null });
45
- const age = now() - cache.at, stale = !cache.names || age >= MAX_AGE || (!cache.names.has(projectId) && age >= MISS_AGE);
46
- if (stale) await (cache.pending ??= fetchNames(coda, cache, now).finally(() => { cache.pending = null; }));
47
- else if (cache.pending) await cache.pending;
48
- return cache.names?.get(projectId) ?? null;
49
- } catch {
50
- return null;
51
- }
52
- }
53
-
54
- // checkout.state 是 preparing、ready、failed。failed 没有可看的目录,按 none;
55
- // ready 但目录已不在(归档后工作树被回收)是 gone。
23
+ // workspace.state 取 preparing、ready、failed、gone 之一,path 只在 ready 时有值。
24
+ // failed 没有可看的目录,按 none;ready 但目录已不在(归档后工作树被回收)按 gone。
56
25
  // 查询失败(接口出错、读目录权限)直接抛出,由调用方保留上一次的结果。
57
- export async function queryRoot(coda, session, { now = Date.now } = {}) {
26
+ export async function queryRoot(coda, session) {
58
27
  if (!session) return NO_ROOT;
59
- const detail = await coda.api(`threads/${encodeURIComponent(session)}`);
60
- const checkout = detail?.checkout;
61
- if (!checkout || typeof checkout !== 'object') return NO_ROOT;
62
- if (checkout.state === 'preparing') return { state: RootState.PREPARING, path: null, project: null };
63
- if (checkout.state !== 'ready' || typeof checkout.path !== 'string' || !checkout.path) return NO_ROOT;
28
+ const detail = await coda.query({ kind: 'coda/thread@1', id: session }, 'workspace', {});
29
+ if (!detail || typeof detail !== 'object') return NO_ROOT;
30
+ if (detail.state === 'preparing') return { state: RootState.PREPARING, path: null, project: null };
31
+ if (detail.state === 'gone') return { state: RootState.GONE, path: typeof detail.path === 'string' && detail.path ? detail.path : null, project: null };
32
+ if (detail.state !== 'ready' || typeof detail.path !== 'string' || !detail.path) return NO_ROOT;
64
33
  try {
65
- const real = await realpath(checkout.path);
66
- if ((await stat(real)).isDirectory()) return { state: RootState.READY, path: real, project: checkout.kind === 'worktree' ? await projectNameOf(coda, checkout.projectId ?? detail.thread?.projectId, now) : null };
34
+ const real = await realpath(detail.path);
35
+ if ((await stat(real)).isDirectory()) {
36
+ const project = UUID.test(baseName(real)) ? cleanName(detail.project?.name) : null;
37
+ return { state: RootState.READY, path: real, project };
38
+ }
67
39
  } catch (error) {
68
40
  if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error;
69
41
  }
70
- return { state: RootState.GONE, path: checkout.path, project: null };
42
+ return { state: RootState.GONE, path: detail.path, project: null };
71
43
  }
package/main.mjs CHANGED
@@ -39,6 +39,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
39
39
  const s = {
40
40
  session: sessionOf(view.context), generation: 1, root: NO_ROOT, sent: null,
41
41
  hello: false, closed: false, rootSeq: 0, poll: null,
42
+ abort: new AbortController(), // 绑定当前会话代次与视图生命周期,换会话或关闭时中止在途的草稿写入
42
43
  listing: makeListing(), // 这个视图共用的并发上限和快照;视图关闭、换会话、根目录变化时丢弃
43
44
  };
44
45
  const turns = new Map();
@@ -102,6 +103,8 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
102
103
 
103
104
  function switchSession(session) {
104
105
  stopPoll();
106
+ s.abort.abort();
107
+ s.abort = new AbortController();
105
108
  s.session = session ?? null;
106
109
  s.generation++;
107
110
  resetReads();
@@ -134,7 +137,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
134
137
  },
135
138
  async [Type.ADD_TEXT](message, { generation }) {
136
139
  if (!s.session) throw fail(ErrorCode.NO_ROOT, '没有会话');
137
- return await addText(coda, s.session, message, { valid: () => !stale(generation) }) ? {} : null;
140
+ return await addText(coda, s.session, message, { valid: () => !stale(generation), signal: s.abort.signal }) ? {} : null;
138
141
  },
139
142
  };
140
143
  // 回答依赖根目录的:读完回来根目录换了,不能带旧根目录的内容。
@@ -206,6 +209,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
206
209
 
207
210
  view.onClose(async () => {
208
211
  s.closed = true;
212
+ s.abort.abort();
209
213
  resetReads();
210
214
  stopPoll();
211
215
  try { await (await watching)?.dispose(); } catch { /* 已经取消 */ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "@coda-console/resource-manager",
4
4
  "displayName": "资源管理器",
5
5
  "description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本、图片、音频、视频和 3D 模型,把路径交给对话。",
6
- "version": "0.9.3",
6
+ "version": "0.9.5",
7
7
  "categories": ["工作流程"],
8
8
  "license": "MIT",
9
9
  "repository": {
@@ -15,14 +15,15 @@
15
15
  "scripts": {
16
16
  "test": "node --test test/*.test.mjs",
17
17
  "test:webgl": "node test/harness/inspect3d.mjs",
18
- "check:coda": "npx --yes @coda-console/plugin-check@0.5.31 . --manifest"
18
+ "check:coda": "npx --yes @coda-console/plugin-check@0.8.31 . --manifest"
19
19
  },
20
+ "engines": { "coda": 3 },
20
21
  "main": "main.mjs",
21
- "uses": { "coda/thread@1": ["read"] },
22
+ "uses": { "coda/thread@1": ["read", "workspace", "append-draft"] },
22
23
  "contributes": {
23
24
  "views": [
24
- { "id": "files", "title": "资源管理器", "entry": "view/index.html", "in": ["side"], "icon": "folder" },
25
- { "id": "file", "title": "文件", "entry": "view/file.html" }
25
+ { "id": "files", "title": "资源管理器", "entry": "view/index.html", "in": ["side"], "icon": "folder", "frame": "canvas" },
26
+ { "id": "file", "title": "文件", "entry": "view/file.html", "frame": "canvas" }
26
27
  ]
27
28
  }
28
29
  }
package/view/app.mjs CHANGED
@@ -14,7 +14,7 @@ import { Model, STATE_LIMIT, View, noticeText, parseState, putSession, trimState
14
14
  import { showNotice } from './notice.mjs';
15
15
  import { mountPreview } from './preview.mjs';
16
16
  import { mountPress, onMotionChange, reducedMotion } from './press.mjs';
17
- import { EntryKind, RootState, SortKey, Type } from './protocol.mjs';
17
+ import { EntryKind, RootState, SortKey, Type, externalPreviewOf } from './protocol.mjs';
18
18
  import { createRestore, createTrail } from './restore.mjs';
19
19
  import { createSearch } from './search.mjs';
20
20
  import { mountSearchbar } from './searchbar.mjs';
@@ -169,12 +169,60 @@ function openInView(path) {
169
169
  }
170
170
  // 两端都在页内打开:model.openFile 设 selected 和 opened,经 onChange 切到预览。iPhone 触屏没有键盘焦点,不交焦点;
171
171
  // 快速两次轻点:第一次已切到预览,目录树 .off 不接指针事件,第二次落不到条目上。
172
- // 打开文件的统一入口(目录树、图标视图和搜索结果):焦点交接和过渡意图在这里记,不随调用方复制。select 为假(搜索结果)时只设预览,不改 model.selected。
173
- function openFile(path, { select = true } = {}) {
172
+ // 独立自增序号(不复用 epoch)与单在途串行队列:
173
+ // 同一页面同时只允许一个 coda.open 在途,在途期间的新打开意图合并到最新一次;
174
+ // 换会话、根目录变化、切目录、打开属性页或改开页内文件时递增序号并清空待执行队列,防止旧操作晚完成或晚失败覆盖新状态。
175
+ let openSeq = 0;
176
+ let openingExternal = false;
177
+ let queuedExternal = null;
178
+ const cancelExternal = () => { openSeq++; queuedExternal = null; };
179
+ const encodePath = path => path.split('/').map(encodeURIComponent).join('/');
180
+ function openInline(path, { select = true } = {}) {
174
181
  openPressed = !isIOS; // 用户在 Mac 上打开的:render 把焦点交给预览面板
175
182
  note({ kind: 'push', from: mode(), to: 'preview' });
176
183
  model.openFile(path, { select });
177
184
  }
185
+ async function drainExternal(first) {
186
+ openingExternal = true;
187
+ let current = first;
188
+ try {
189
+ while (current) {
190
+ const { path, select, seq } = current;
191
+ current = null;
192
+ if (seq === openSeq) {
193
+ try {
194
+ const granted = await conn.link.call(Type.MEDIA, { path });
195
+ if (seq === openSeq) {
196
+ if (!granted?.token) throw new Error('no media service');
197
+ await coda.open(`coda-view://service/media/${granted.token}/${encodePath(path)}`);
198
+ }
199
+ } catch {
200
+ if (seq === openSeq && model.ready) openInline(path, { select });
201
+ }
202
+ }
203
+ if (queuedExternal) {
204
+ current = queuedExternal;
205
+ queuedExternal = null;
206
+ }
207
+ }
208
+ } finally {
209
+ openingExternal = false;
210
+ }
211
+ }
212
+ // 打开文件的统一入口(目录树、图标视图和搜索结果):PDF/Office/iWork 与 Markdown 优先经本机流式服务走 coda.open,失败静默退回页内预览;其余保持页内预览。
213
+ // 走 coda.open 成功时不设 model.opened(因此不记入 setState 的 opened)。select 为假(搜索结果)时回退页内预览只设预览,不改 model.selected。
214
+ function openFile(path, { select = true } = {}) {
215
+ cancelExternal();
216
+ const seq = openSeq;
217
+ const via = typeof coda.open === 'function' && model.ready && model.root?.path ? externalPreviewOf(path) : null;
218
+ if (via) {
219
+ const task = { path, select, seq };
220
+ if (openingExternal) queuedExternal = task;
221
+ else drainExternal(task);
222
+ return;
223
+ }
224
+ openInline(path, { select });
225
+ }
178
226
 
179
227
  // ---- 渲染:同一批变化合并成一次 ----
180
228
  let queued = false;
@@ -614,6 +662,7 @@ $('preview').addEventListener('keydown', event => {
614
662
  let shownCwd = '';
615
663
  const enterDir = taken(path => enterInto(path));
616
664
  function enterInto(path) {
665
+ cancelExternal();
617
666
  trail.remember(model.cwd, grid.scroll());
618
667
  selectEntry(null); // 进入新的一层:选中清空
619
668
  model.enter(path);
@@ -627,6 +676,7 @@ function enterInto(path) {
627
676
  function leaveDir(levels = 1, record = true) {
628
677
  takeover++; // 用户经按钮、键盘、返回退出图标视图的一层
629
678
  if (model.cwd === '') return false;
679
+ cancelExternal();
630
680
  const from = model.cwd.split('/');
631
681
  model.leave(levels);
632
682
  if (record) note({ kind: 'fade', to: model.cwd });
@@ -690,6 +740,7 @@ if (nativeBack) quiet(() => coda.on('back', event => {
690
740
 
691
741
  // ---- 属性页:所有关闭的路径(原生返回、横屏的返回、换会话、根目录变化)都重新声明回上层 ----
692
742
  function openInfo(row) {
743
+ cancelExternal();
693
744
  note({ kind: 'push', from: mode(), to: 'info' });
694
745
  infoOpen = true;
695
746
  infoStopped = false;
@@ -723,6 +774,7 @@ function onSession(data) {
723
774
  locator.cancel();
724
775
  clearSearch(); // 换会话:搜索词、结果、结果的选中、定位都清掉
725
776
  epoch++;
777
+ cancelExternal();
726
778
  hint.hide();
727
779
  const saved = persisted.sessions[data.session] ?? null;
728
780
  pending = saved?.opened ? { preview: { top: saved.scroll.top, left: saved.scroll.left }, path: saved.opened } : { preview: null, path: null };
@@ -739,7 +791,7 @@ function onSession(data) {
739
791
  function onRoot(data) {
740
792
  const before = model.root;
741
793
  if (data.state !== before?.state || data.path !== before?.path) { menu.hide(); intent = null; endRunning(); } // 开着的菜单里的路径是旧根目录下的;换根目录不播过渡
742
- if (data.state !== RootState.READY || before?.path !== data.path) closeInfo(false, true); // 属性页看的是旧根目录下的路径
794
+ if (data.state !== RootState.READY || before?.path !== data.path) { cancelExternal(); closeInfo(false, true); } // 属性页看的是旧根目录下的路径
743
795
  const scope = model.scope;
744
796
  if (data.state !== RootState.READY) { search.suspend(); locator.cancel(); } // 根目录暂不可用:取消在途搜索,丢掉结果,搜索词留着;定位作废(再就绪也不接着做)
745
797
  const done = model.receive(data);
package/view/protocol.mjs CHANGED
@@ -78,25 +78,84 @@ const MEDIA_TYPES = {
78
78
  };
79
79
  // 模型的伴随文件:服务要供应(gltf 的 .bin、obj 的 .mtl),但页面不把它们当媒体预览(.mtl 仍是文本,.bin 仍是二进制)。
80
80
  const COMPANION_TYPES = { bin: 'application/octet-stream', mtl: 'text/plain; charset=utf-8' };
81
+ // 经 Coda 的 coda.open 预览的文档类型:统一经插件本机流式服务供应,复用 resolveInRoot 与 O_NOFOLLOW 校验,防止越出工作目录。
82
+ const DOCUMENT_TYPES = {
83
+ md: 'text/markdown; charset=utf-8',
84
+ markdown: 'text/markdown; charset=utf-8',
85
+ pdf: 'application/pdf',
86
+ doc: 'application/msword',
87
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
88
+ xls: 'application/vnd.ms-excel',
89
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
90
+ ppt: 'application/vnd.ms-powerpoint',
91
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
92
+ rtf: 'application/rtf',
93
+ pages: 'application/vnd.apple.pages',
94
+ numbers: 'application/vnd.apple.numbers',
95
+ key: 'application/vnd.apple.keynote',
96
+ };
97
+ // Markdown 相对链接可能指向的常见目录内文本/代码文件:只供流式服务响应相对链接,直接点击时仍走页内预览。
98
+ const LINK_TARGET_TYPES = {
99
+ txt: 'text/plain; charset=utf-8',
100
+ csv: 'text/csv; charset=utf-8',
101
+ tsv: 'text/tab-separated-values; charset=utf-8',
102
+ json: 'application/json; charset=utf-8',
103
+ yaml: 'text/yaml; charset=utf-8',
104
+ yml: 'text/yaml; charset=utf-8',
105
+ xml: 'application/xml; charset=utf-8',
106
+ html: 'text/html; charset=utf-8',
107
+ htm: 'text/html; charset=utf-8',
108
+ css: 'text/css; charset=utf-8',
109
+ js: 'text/javascript; charset=utf-8',
110
+ mjs: 'text/javascript; charset=utf-8',
111
+ ts: 'text/plain; charset=utf-8',
112
+ tsx: 'text/plain; charset=utf-8',
113
+ jsx: 'text/plain; charset=utf-8',
114
+ py: 'text/plain; charset=utf-8',
115
+ go: 'text/plain; charset=utf-8',
116
+ rs: 'text/plain; charset=utf-8',
117
+ sh: 'text/plain; charset=utf-8',
118
+ sql: 'text/plain; charset=utf-8',
119
+ toml: 'text/plain; charset=utf-8',
120
+ ini: 'text/plain; charset=utf-8',
121
+ log: 'text/plain; charset=utf-8',
122
+ };
81
123
  // 查证过 Coda 播放器不支持的视频:按扩展名直接不预览,不读字节(mkv 容器不支持,avi 的 canPlayType 说 maybe 但实际报错)。
82
124
  const NO_PREVIEW = new Set(['mkv', 'avi']);
83
125
 
126
+ function extensionOf(name) {
127
+ const str = String(name);
128
+ const base = str.slice(str.lastIndexOf('/') + 1);
129
+ const dot = base.lastIndexOf('.');
130
+ return dot <= 0 ? null : base.slice(dot + 1).toLowerCase();
131
+ }
132
+
84
133
  // 按扩展名给出 { kind: 'audio' | 'video' | 'image' | 'model', type, preview };不是媒体文件返回 null。preview 为 false 的没有 type,不经服务。
85
134
  export function mediaOf(name) {
86
- const dot = String(name).lastIndexOf('.');
87
- if (dot < 0) return null;
88
- const ext = name.slice(dot + 1).toLowerCase();
135
+ const ext = extensionOf(name);
136
+ if (!ext) return null;
89
137
  if (NO_PREVIEW.has(ext)) return { kind: 'video', type: null, preview: false };
90
- const entry = MEDIA_TYPES[ext];
138
+ const entry = Object.hasOwn(MEDIA_TYPES, ext) ? MEDIA_TYPES[ext] : null;
91
139
  return entry ? { kind: entry[0], type: entry[1], preview: true } : null;
92
140
  }
93
141
 
94
- // 流式服务肯供应的文件的 MIME 类型:能预览的媒体加上模型的伴随文件;其余返回 null(服务回 415)。
142
+ // 按扩展名判断是否优先经本机流式服务走 coda.open(PDF / Office / iWork / Markdown 返回 'media',其余返回 null 保持页内预览)。
143
+ export function externalPreviewOf(name) {
144
+ const ext = extensionOf(name);
145
+ if (!ext) return null;
146
+ return Object.hasOwn(DOCUMENT_TYPES, ext) ? 'media' : null;
147
+ }
148
+
149
+ // 流式服务肯供应的文件的 MIME 类型:能预览的媒体、模型的伴随文件、经 coda.open 预览的文档和 Markdown 相对链接目标;其余返回 null(服务回 415)。
95
150
  export function servedType(name) {
96
151
  const media = mediaOf(name);
97
152
  if (media) return media.preview ? media.type : null;
98
- const dot = String(name).lastIndexOf('.');
99
- return dot < 0 ? null : COMPANION_TYPES[name.slice(dot + 1).toLowerCase()] ?? null;
153
+ const ext = extensionOf(name);
154
+ if (!ext) return null;
155
+ if (Object.hasOwn(COMPANION_TYPES, ext)) return COMPANION_TYPES[ext];
156
+ if (Object.hasOwn(DOCUMENT_TYPES, ext)) return DOCUMENT_TYPES[ext];
157
+ if (Object.hasOwn(LINK_TARGET_TYPES, ext)) return LINK_TARGET_TYPES[ext];
158
+ return null;
100
159
  }
101
160
 
102
161
  // 相对路径的规则只在这一处:模块(lib/paths.mjs)校验请求,页面恢复保存的 cwd 时用同一个函数。