@aiti-ai/aiti-msg-share 0.1.8 → 0.1.11

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/index.ts CHANGED
@@ -8,6 +8,8 @@
8
8
  import { join, dirname } from "node:path";
9
9
  // @ts-ignore pure JS core shared with tests
10
10
  import { ShareStore, makeRedactor, publicTarget, exportSessionMarkdown, classifyFile, MAX_SHARE_FILE_BYTES } from "./lib/share-core.mjs";
11
+ // @ts-ignore pure JS icon rules shared with tests
12
+ import { resolveProviderIcon } from "./lib/provider-icons.mjs";
11
13
 
12
14
  let configDir = "";
13
15
  let stateDir = "";
@@ -66,6 +68,7 @@ async function ensureSecretEngine() {
66
68
  /** Derive a target's setup state for the UI: anonymous / ready / needs-setup. */
67
69
  function configState(entry: any, userTarget: any, reg: any): string {
68
70
  if (entry.status === "dead") return "dead";
71
+ if (entry.status === "legacy") return "legacy";
69
72
  const provider = reg.get(entry.id) || reg.get(userTarget?.provider);
70
73
  const required = (provider?.metaFields || []).filter((f: any) => f.required);
71
74
  // A user-created target with all required fields filled → ready.
@@ -98,12 +101,14 @@ function allTargets(reg) {
98
101
  return { ...t, custom: true, auth: entry?.auth ?? (t.provider === "custom" ? "key" : "none"),
99
102
  kinds: entry?.kinds ?? ["text"], category: entry?.category ?? "publish",
100
103
  fields: targetFields(t.provider, reg),
104
+ ...containerInfo(reg, t.provider),
101
105
  configState: configState(entry || { id: t.provider }, t, reg) };
102
106
  }),
103
107
  ...entries.filter((e) => !userByProvider.has(e.id)).map((e) => ({ id: e.id, name: e.name, provider: e.id,
104
108
  kinds: e.kinds, category: e.category, auth: e.auth, recommended: e.recommended, note: e.note,
105
109
  status: e.status, source: e.source, values: {},
106
110
  fields: targetFields(e.id, reg),
111
+ ...containerInfo(reg, e.id),
107
112
  configState: configState(e, null, reg) })),
108
113
  ];
109
114
  }
@@ -115,6 +120,16 @@ function findTarget(reg, id) {
115
120
  return entry ? { id: entry.id, provider: entry.id, values: {}, name: entry.name, kinds: entry.kinds, category: entry.category } : null;
116
121
  }
117
122
 
123
+ /** Provider UI metadata surfaced to the client: container picker visibility/label
124
+ * and the picker glyph. The catalog has no icon metadata, so the glyph comes from
125
+ * curated keyword rules (lib/provider-icons.mjs); null lets the client fall back
126
+ * to its category/status glyph. */
127
+ function containerInfo(reg: any, providerId: string) {
128
+ const p = reg.get(providerId);
129
+ const c = p?.containers;
130
+ return { supportsContainers: !!c, containerLabel: c?.label || null, icon: resolveProviderIcon(providerId, p) };
131
+ }
132
+
118
133
  export default {
119
134
  id: "aiti-msg-share",
120
135
  name: "消息分享",
@@ -217,6 +232,15 @@ export default {
217
232
  "share.cfg.ready": "Configured",
218
233
  "share.cfg.needs": "Needs setup",
219
234
  "share.cfg.dead": "Unavailable",
235
+ "share.cfg.legacy": "Outdated — upload path broken",
236
+ "share.container.label": "Notebook",
237
+ "share.container.default": "Service default",
238
+ "share.container.refresh": "Refresh containers",
239
+ "share.container.search": "Search notebooks…",
240
+ "share.container.empty": "No containers found",
241
+ "share.container.fail": "Could not list containers: {detail}",
242
+ "share.container.missing": "Last selection no longer exists — using default",
243
+ "share.container.matches": "{n} matches",
220
244
  },
221
245
  "zh-CN": {
222
246
  "share.err.forbidden": "该路径不在允许范围内——只能分享会话工作区内的文件。",
@@ -302,6 +326,16 @@ export default {
302
326
  "share.cfg.ready": "已配置",
303
327
  "share.cfg.needs": "需配置",
304
328
  "share.cfg.dead": "不可用",
329
+ "share.cfg.legacy": "已過時(上傳通道異常)",
330
+ "share.cfg.legacy": "已过时(上传通道异常)",
331
+ "share.container.label": "笔记本",
332
+ "share.container.default": "默认位置",
333
+ "share.container.refresh": "刷新容器列表",
334
+ "share.container.search": "搜索笔记本…",
335
+ "share.container.empty": "未找到容器",
336
+ "share.container.fail": "容器列表获取失败:{detail}",
337
+ "share.container.missing": "上次选择的容器已不存在,使用默认位置",
338
+ "share.container.matches": "{n} 条匹配",
305
339
  },
306
340
  "zh-TW": {
307
341
  "share.err.forbidden": "該路徑不在允許範圍內——只能分享工作階段工作區內的檔案。",
@@ -384,9 +418,17 @@ export default {
384
418
  "share.deleteTarget": "刪除目標",
385
419
  "share.notSet": "(未設定)",
386
420
  "share.cfg.anonymous": "匿名可用",
387
- "share.cfg.ready": "已設定",
388
- "share.cfg.needs": "需設定",
421
+ "share.cfg.ready": "已配置",
422
+ "share.cfg.needs": "需配置",
389
423
  "share.cfg.dead": "不可用",
424
+ "share.container.label": "筆記本",
425
+ "share.container.default": "預設位置",
426
+ "share.container.refresh": "重新整理容器列表",
427
+ "share.container.search": "搜尋筆記本…",
428
+ "share.container.empty": "未找到容器",
429
+ "share.container.fail": "容器列表取得失敗:{detail}",
430
+ "share.container.missing": "上次選擇的容器已不存在,使用預設位置",
431
+ "share.container.matches": "{n} 筆匹配",
390
432
  },
391
433
  },
392
434
  dialogs: [{ id: "aiti-msg-share-dialog", label: "aiti-msg-share" }],
@@ -420,13 +462,13 @@ export default {
420
462
  return json({ ok: true, targets: allTargets(reg), count: reg.catalog().length });
421
463
  }
422
464
 
423
- // GET /targets — persisted user targets
424
- if (p[0] === "targets" && req.method === "GET") {
465
+ // GET /targets — persisted user targets (!p[1]: sub-resources have own handlers)
466
+ if (p[0] === "targets" && !p[1] && req.method === "GET") {
425
467
  return json({ ok: true, targets: store.readTargets().map((t) => publicTarget(t, reg.get(t.provider))) });
426
468
  }
427
469
 
428
470
  // POST /targets — upsert a target (secrets stored raw, 0600; masked in responses)
429
- if (p[0] === "targets" && req.method === "POST") {
471
+ if (p[0] === "targets" && !p[1] && req.method === "POST") {
430
472
  const body = await req.json();
431
473
  if (!body?.id || !body?.provider) return json({ ok: false, error: "id and provider required", errorCode: "badRequest" }, 400);
432
474
  const saved = store.upsertTarget({ id: body.id, provider: body.provider, name: body.name || body.id,
@@ -450,6 +492,49 @@ export default {
450
492
  return json(await provider.probe({ provider: body.provider, values: body.values || {} }));
451
493
  }
452
494
 
495
+ // POST /containers — list selectable containers (Joplin notebooks, Obsidian dirs, …).
496
+ // Saved target: credentials come from the stored values; setup form: ad-hoc values.
497
+ // Credentials never leave the server — only {id,label,parent,path} are returned.
498
+ if (p[0] === "containers" && req.method === "POST") {
499
+ const body = await req.json().catch(() => null);
500
+ let providerId: string = body?.provider || "";
501
+ let values: Record<string, string> = body?.values || {};
502
+ if (body?.targetId) {
503
+ const t = findTarget(reg, body.targetId);
504
+ if (!t) return json({ ok: false, error: "unknown target", errorCode: "unknownTarget" }, 404);
505
+ providerId = t.provider;
506
+ values = t.values || {};
507
+ }
508
+ const provider = providerId ? reg.get(providerId) : null;
509
+ if (!provider?.containers) return json({ ok: true, supportsContainers: false, containers: [] });
510
+ try {
511
+ const containers = await provider.containers.list({ provider: providerId, values, container: "" },
512
+ typeof body?.parent === "string" ? body.parent : undefined);
513
+ return json({ ok: true, supportsContainers: true, containerLabel: provider.containers.label || null, containers });
514
+ } catch (err: any) {
515
+ return json({ ok: false, errorCode: "containerFail", error: String(err?.message || err),
516
+ detail: String(err?.message || err) }, 502);
517
+ }
518
+ }
519
+
520
+ // POST /targets/last-container — record the user's container pick on the target.
521
+ // Persisted in targets.json (0600): survives restarts and browsers; AI/headless
522
+ // shares fall back to it when the request carries no explicit container.
523
+ // recentContainers keeps a small quick-pick history (most recent distinct first).
524
+ if (p[0] === "targets" && p[1] === "last-container" && req.method === "POST") {
525
+ const body = await req.json().catch(() => null);
526
+ const t = store.readTargets().find((x) => x.id === body?.id);
527
+ if (!t) return json({ ok: false, error: "unknown target", errorCode: "unknownTarget" }, 404);
528
+ const container = String(body?.container ?? "");
529
+ const label = body?.label ? String(body.label) : (container ? t.lastContainerLabel || "" : "");
530
+ const recents: Array<{ id: string; label: string }> = (Array.isArray(t.recentContainers) ? t.recentContainers : [])
531
+ .filter((r: any) => r && r.id && r.id !== container).slice(0, 2);
532
+ const recentContainers = container ? [{ id: container, label }, ...recents] : recents;
533
+ const saved = store.upsertTarget({ ...t, lastContainer: container, lastContainerLabel: label,
534
+ lastContainerAt: new Date().toISOString(), recentContainers });
535
+ return json({ ok: true, target: publicTarget(saved, reg.get(saved.provider)) });
536
+ }
537
+
453
538
  // POST /import-sxcu — register a config at runtime + persist as a target
454
539
  if (p[0] === "import-sxcu" && req.method === "POST") {
455
540
  const body = await req.json();
@@ -540,9 +625,12 @@ export default {
540
625
  detail: `${(provider as any).label} accepts: ${kinds.join(", ")}` }, 400);
541
626
  }
542
627
  let result;
628
+ // Container selection: an explicit request wins ("" = service default);
629
+ // otherwise fall back to the target's recorded last selection (AI/headless path).
630
+ const container = typeof body.container === "string" ? body.container : String(target.lastContainer || "");
543
631
  try {
544
632
  result = await cs.share(provider, content,
545
- { provider: target.provider, values: target.values || {}, tags: meta.tags, pathPrefix: target.pathPrefix },
633
+ { provider: target.provider, values: target.values || {}, tags: meta.tags, pathPrefix: target.pathPrefix, container },
546
634
  meta, hooks);
547
635
  } catch (err: any) {
548
636
  // Turn a bare "fetch failed" into an actionable message (target + cause + hint).
@@ -566,6 +654,12 @@ export default {
566
654
  store.appendHistory({ at: new Date().toISOString(), targetId: target.id, kind,
567
655
  title: meta.title, url: result.url, extra: result.extra, hits: result.hits,
568
656
  redacted: doRedact, bytes: "text" in content ? Buffer.byteLength(content.text) : content.buffer.byteLength });
657
+ // Refresh the last-selection memory on success (bump timestamp only when the
658
+ // value changed) so headless/AI shares keep landing in the same notebook.
659
+ const stored = store.readTargets().find((t) => t.id === target.id);
660
+ if (stored && String(stored.lastContainer || "") !== container) {
661
+ store.upsertTarget({ ...stored, lastContainer: container, lastContainerAt: new Date().toISOString() });
662
+ }
569
663
  return json({ ok: true, ...result });
570
664
  }
571
665
 
@@ -0,0 +1,63 @@
1
+ /**
2
+ * provider-icons — curated per-target glyphs for the share picker (pure data, no DOM).
3
+ *
4
+ * The content-share catalog carries no icon/favicon metadata (checked against
5
+ * @aiti-ai/content-share 0.1.17: catalog entries have id/name/kinds/category/
6
+ * source/auth/note/status only, and providers have no icon field), so the old
7
+ * `icon: p?.icon` was always null. Rather than fetching third-party favicons
8
+ * (privacy + offline), resolve a stable local glyph:
9
+ *
10
+ * 1. provider.icon when a future catalog version supplies one (string or { emoji })
11
+ * 2. ordered keyword rules over the target id (ids are domain-ish: "imgur.com",
12
+ * "0x0.st (URL shortener)", "aliyun-oss", "gitee-gist", …)
13
+ * 3. null → the client keeps its category/status glyph
14
+ *
15
+ * Order matters: specific families first, generic "shortener"/"file" last.
16
+ */
17
+
18
+ /** Curated glyphs keyed by exact target id (the few curated aiti entries). */
19
+ const EXACT = {
20
+ "aliyun-oss": "☁️",
21
+ "gitee-gist": "🟠",
22
+ "local-link": "🔗",
23
+ custom: "⚙️",
24
+ };
25
+
26
+ /** Ordered keyword rules over the lower-cased target id. */
27
+ const RULES = [
28
+ [/(^|[^a-z])github|(^|[^a-z])gist|gitlab|git\.io|gitee|codeberg|sourcehut/, "💻"],
29
+ [/catbox|litterbox/, "🐱"],
30
+ [/shortener|short\.?url|\bshort\b/, "✂️"],
31
+ [/imgur|imgbb|freeimage|gyazo|chevereto|postimag|epvpimg|\bimage\b|\bimg\b|\bpic\b|photo|lsky/, "🖼️"],
32
+ [/paste|haste|dpaste|ghostbin|privatebin|ix\.io|0x0\.st/, "📋"],
33
+ [/\boss\b|s3|storage|qiniu|tencent|upyun|wasabi|minio|backblaze|\bb2\b|\br2\b|bucket/, "☁️"],
34
+ [/joplin|obsidian|notion|evernote/, "📓"],
35
+ [/telegram|discord|slack|feishu|lark|flomo|\bim\b/, "💬"],
36
+ [/\bmail|smtp|email/, "✉️"],
37
+ [/ipfs|ipns/, "🌐"],
38
+ [/local-link/, "🔗"],
39
+ [/webhook|httpreq|httpbin/, "🔗"],
40
+ [/\bfile\b|gofile|transfer|dropfile|filebin|tmpfiles|uguu|fuwa|fuck\.it|catbox/, "📦"],
41
+ ];
42
+
43
+ /**
44
+ * Resolve the glyph for one target.
45
+ * @param {string} providerId target id from the catalog
46
+ * @param {{ icon?: unknown } | null | undefined} provider registry provider (future metadata)
47
+ * @returns {string | null} glyph, or null so the client falls back
48
+ */
49
+ export function resolveProviderIcon(providerId, provider) {
50
+ const fromProvider = provider?.icon;
51
+ if (typeof fromProvider === "string" && fromProvider.trim()) return fromProvider.trim();
52
+ if (fromProvider && typeof fromProvider === "object" && typeof fromProvider.emoji === "string") {
53
+ return fromProvider.emoji.trim() || null;
54
+ }
55
+ const id = String(providerId || "").trim();
56
+ if (!id) return null;
57
+ if (EXACT[id]) return EXACT[id];
58
+ const lower = id.toLowerCase();
59
+ for (const [pattern, glyph] of RULES) {
60
+ if (pattern.test(lower)) return glyph;
61
+ }
62
+ return null;
63
+ }
package/package.json CHANGED
@@ -1,13 +1,22 @@
1
1
  {
2
2
  "name": "@aiti-ai/aiti-msg-share",
3
- "version": "0.1.8",
3
+ "version": "0.1.11",
4
4
  "type": "module",
5
5
  "description": "Share sessions, messages, selections, files and images through pluggable targets with secret redaction and QR codes",
6
+ "displayNameI18n": {
7
+ "en": "Message Share"
8
+ },
9
+ "descriptionI18n": {
10
+ "zh-CN": "把会话、单条消息、划选内容、文件与图片分享出去——工作台跑在自己机器上、外网访问不到,所以经可配置的分享目标(Gitee / 图床 / 对象存储 / 笔记库,内置 161 个)上传换回公网 URL,上传前自动脱敏,结果附二维码"
11
+ },
6
12
  "license": "MIT",
7
13
  "aitiExtProtocol": "1.0",
8
14
  "soul": "分享出去,是为了让对话继续。",
15
+ "soulI18n": {
16
+ "en": "Sharing it out is how the conversation continues."
17
+ },
9
18
  "dependencies": {
10
- "@aiti-ai/content-share": "^0.1.11",
19
+ "@aiti-ai/content-share": "^0.1.16",
11
20
  "@aiti-ai/secret-mask-core": "^0.1.0",
12
21
  "qrcode": "^1.5.4"
13
22
  },
@@ -27,5 +36,5 @@
27
36
  "bugs": {
28
37
  "url": "https://github.com/aiti-ai/aiti-ai/issues"
29
38
  },
30
- "contentHash": "603e2fa84e7f66a0"
39
+ "contentHash": "2340fd21422342db"
31
40
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * provider-icons — curated glyph rules for the share picker (pure, no DOM).
3
+ * Run: node --test extensions/aiti-msg-share/test/provider-icons.test.mjs
4
+ */
5
+ import test from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { resolveProviderIcon } from "../lib/provider-icons.mjs";
8
+
9
+ test("exact curated ids win", () => {
10
+ assert.equal(resolveProviderIcon("aliyun-oss"), "☁️");
11
+ assert.equal(resolveProviderIcon("gitee-gist"), "🟠");
12
+ assert.equal(resolveProviderIcon("local-link"), "🔗");
13
+ assert.equal(resolveProviderIcon("custom"), "⚙️");
14
+ });
15
+
16
+ test("domain-shaped catalog ids map to families", () => {
17
+ assert.equal(resolveProviderIcon("imgur.com"), "🖼️");
18
+ assert.equal(resolveProviderIcon("imgbb.com"), "🖼️");
19
+ assert.equal(resolveProviderIcon("catbox.moe"), "🐱");
20
+ assert.equal(resolveProviderIcon("paste.rs"), "📋");
21
+ assert.equal(resolveProviderIcon("ix.io"), "📋");
22
+ assert.equal(resolveProviderIcon("Discord post"), "💬");
23
+ assert.equal(resolveProviderIcon("joplin"), "📓");
24
+ assert.equal(resolveProviderIcon("ipfs.io"), "🌐");
25
+ assert.equal(resolveProviderIcon("file.io"), "📦");
26
+ assert.equal(resolveProviderIcon("github-gist"), "💻");
27
+ });
28
+
29
+ test("multi-variant ids resolve by their variant, not the base host", () => {
30
+ assert.equal(resolveProviderIcon("0x0.st (URL shortener)"), "✂️");
31
+ assert.equal(resolveProviderIcon("0x0.st (Image uploader)"), "🖼️");
32
+ });
33
+
34
+ test("unknown ids return null so the client keeps its category glyph", () => {
35
+ assert.equal(resolveProviderIcon("example"), null);
36
+ assert.equal(resolveProviderIcon(""), null);
37
+ assert.equal(resolveProviderIcon(undefined), null);
38
+ assert.equal(resolveProviderIcon(null), null);
39
+ });
40
+
41
+ test("future provider metadata wins; invalid metadata falls through", () => {
42
+ assert.equal(resolveProviderIcon("imgur.com", { icon: "🔒" }), "🔒");
43
+ assert.equal(resolveProviderIcon("imgur.com", { icon: { emoji: "🅰️" } }), "🅰️");
44
+ assert.equal(resolveProviderIcon("imgur.com", { icon: {} }), "🖼️");
45
+ assert.equal(resolveProviderIcon("imgur.com", { icon: 42 }), "🖼️");
46
+ assert.equal(resolveProviderIcon("unknown-id", { icon: " " }), null);
47
+ });
@@ -59,3 +59,17 @@ test("classifyFile: image / text / binary by extension", async () => {
59
59
  assert.deepEqual(classifyFile("archive.tar.gz"), { kind: "binary", mime: "application/octet-stream" });
60
60
  assert.deepEqual(classifyFile("noext"), { kind: "binary", mime: "application/octet-stream" });
61
61
  });
62
+
63
+ test("ShareStore persists container last-selection fields", () => {
64
+ const dir = mkdtempSync(join(tmpdir(), "share-store-"));
65
+ const store = new ShareStore(join(dir, "config"), join(dir, "state"));
66
+ store.upsertTarget({ id: "joplin", provider: "joplin", values: { token: "t" } });
67
+ const t = store.readTargets()[0];
68
+ store.upsertTarget({ ...t, lastContainer: "nb1", lastContainerLabel: "My Notebook / Work", lastContainerAt: "2026-11-20T00:00:00.000Z" });
69
+ const back = store.readTargets()[0];
70
+ assert.equal(back.lastContainer, "nb1");
71
+ assert.equal(back.lastContainerLabel, "My Notebook / Work");
72
+ // Clearing the selection keeps the label empty too.
73
+ store.upsertTarget({ ...back, lastContainer: "", lastContainerLabel: "" });
74
+ assert.equal(store.readTargets()[0].lastContainer, "");
75
+ });