@coda-console/friends 0.1.0 → 0.3.0

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/outbox.mjs ADDED
@@ -0,0 +1,145 @@
1
+ // 网关的纯逻辑:入参校验、保留类型、证书状态、规范哈希,以及待发队列(outbox.json)的条目与状态转换。不碰 Coda。
2
+ // 不另建目录库:签名写入与记录查询都由 coda/accord@1 完成;这里只在记录待发、暂停或失败排队时留着待发的 body,
3
+ // 同步成功就释放 body,只留去重用的轻量元数据;撤回完成就删掉条目。
4
+ import { createHash } from 'node:crypto';
5
+ import { readJson, writeJson } from './json-file.mjs';
6
+
7
+ /** 网关不替业务发布、撤回的类型:好友关系、名片等 Accord 自己的记录。 */
8
+ export const RESERVED_KINDS = new Set(['binding', 'profile', 'friends', 'coda/profile', 'coda/friends']);
9
+ export const MAX_ID_CHARS = 200, MAX_ID_BYTES = 256, MAX_BODY_BYTES = 65536, MAX_AUDIENCE = 500;
10
+ const KIND = /^[a-z][a-z0-9-]{0,63}(?:\/[a-z][a-z0-9-]{0,63})?$/;
11
+ const AUDIENCE = /^(?:public|ed25519:[0-9a-f]{64})$/;
12
+
13
+ export const invalid = message => Object.assign(new Error(message), { code: 'invalid_input', effects: 'none' });
14
+ const isPlain = value => {
15
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
16
+ const proto = Object.getPrototypeOf(value);
17
+ return proto === Object.prototype || proto === null;
18
+ };
19
+
20
+ export const validKind = kind => typeof kind === 'string' && KIND.test(kind) && !RESERVED_KINDS.has(kind);
21
+
22
+ /** kind 须符合 Accord 的格式,且不是保留类型。 */
23
+ export function checkKind(kind) {
24
+ if (typeof kind !== 'string' || !KIND.test(kind)) throw invalid('kind 须是小写字母开头的 name 或 ns/name(只含小写字母、数字、连字符,各段最长 64 位)');
25
+ if (RESERVED_KINDS.has(kind)) throw invalid(`kind「${kind}」是保留类型,网关不发布也不撤回它`);
26
+ return kind;
27
+ }
28
+
29
+ /** id 非空、合法 UTF-8、至多 256 字节;发布与撤回再限 200 个字符(`query: true` 的记录查询只管字节)。 */
30
+ export function checkId(id, { query = false } = {}) {
31
+ if (typeof id !== 'string' || !id || !id.isWellFormed()) throw invalid('id 须是非空的文本');
32
+ if (Buffer.byteLength(id) > MAX_ID_BYTES) throw invalid(`id 最多 ${MAX_ID_BYTES} 字节`);
33
+ if (!query && [...id].length > MAX_ID_CHARS) throw invalid(`id 最多 ${MAX_ID_CHARS} 个字符`);
34
+ return id;
35
+ }
36
+
37
+ /** 校验并规范发布的入参:`{ kind, id, body, audience }`,audience 缺省 `['public']`;body 复制一份纯 JSON。 */
38
+ export function checkPublish({ kind, id, body, audience = ['public'] } = {}) {
39
+ checkKind(kind);
40
+ checkId(id);
41
+ if (!isPlain(body)) throw invalid('body 须是对象');
42
+ let text;
43
+ try { text = JSON.stringify(body); } catch { throw invalid('body 须能转成 JSON'); }
44
+ if (Buffer.byteLength(text) > MAX_BODY_BYTES) throw invalid(`body 最多 ${MAX_BODY_BYTES} 字节`);
45
+ if (!Array.isArray(audience) || audience.length > MAX_AUDIENCE) throw invalid(`audience 须是至多 ${MAX_AUDIENCE} 项的数组`);
46
+ if (!audience.every(item => typeof item === 'string' && AUDIENCE.test(item))) throw invalid("audience 每项须是 'public' 或 ed25519:<64 位十六进制>");
47
+ return { kind, id, body: JSON.parse(text), audience: [...audience] };
48
+ }
49
+
50
+ /**
51
+ * 本机 Accord 记录(`coda/accord@1` 的 local)的证书状态:状态里写了 `certificate` 的按它判:null 没有身份,
52
+ * `active` 为 true 才是可发布,其余要换证书;旧宿主不写这个键,有作者就当可发布(发布遇 invalid_state 再落到需要证书)。
53
+ */
54
+ export function certStateOf(accord) {
55
+ const status = accord?.status;
56
+ if (status && typeof status === 'object' && Object.hasOwn(status, 'certificate')) {
57
+ if (status.certificate === null) return 'no_identity';
58
+ return status.certificate?.active === true ? 'active' : 'needs_cert';
59
+ }
60
+ return accord?.spec?.author ? 'active' : 'no_identity';
61
+ }
62
+
63
+ const canonical = value => {
64
+ if (Array.isArray(value)) return value.map(canonical);
65
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]));
66
+ return value;
67
+ };
68
+ /** 规范化哈希:对象键递归按字典序排,再取 JSON 的 SHA-256(十六进制);键序不同的同一内容哈希相同。 */
69
+ export const canonicalHash = value => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
70
+
71
+ // ---- 条目与状态转换 ----
72
+ // 发布条目按 `p:${kind}:${id}` 索引,待撤条目按 `r:${targetAuthor}:${kind}:${id}` 索引(kind 不含冒号,两类前缀互斥,键不会撞):
73
+ // 不同作者对同一个 (kind, id) 排下的待撤互不相干,也不挡着对方撤自己的记录。
74
+ // 每次写入发布或撤回的意图都领一个递增的整数 `seq`(落在条目里,不看系统时钟):冲洗按它的先后执行,并据它判断旧撤回是否已被更晚的发布取代。
75
+ // 待发 { seq, kind, id, desired: 'publish', state: queued|paused|no_identity|needs_cert, body, audience, hash, lastError?, + 上次同步的元数据 }
76
+ // 已同步 { seq, kind, id, desired: 'publish', state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt, lastCreatedAt? }(没有 body;
77
+ // lastCreatedAt 是 body.createdAt,同一 id 重试时沿用它,不必再查 Accord)
78
+ // 待撤 { seq, kind, id, desired: 'retract', state: queued|no_identity|needs_cert, targetAuthor, lastError?, + 上次同步的元数据 }
79
+ // targetAuthor 是排队时的作者:换了作者就不再替新作者撤,等原作者回来
80
+ // 被拒 { …, state: 'error', lastError }:Accord 明确拒绝,不再自动重试;下一次发布或撤回同一条会替换它
81
+ export const entryKey = (kind, id) => `p:${kind}:${id}`;
82
+ export const retractKey = (author, kind, id) => `r:${author}:${kind}:${id}`;
83
+ // 序号计数器挂在整张表上(不可枚举,不算条目),随表一起写进 `outbox.json` 顶层:条目删了、发布被拒了,序号也不会倒退。
84
+ const withSeq = (entries, seq) => Object.defineProperty(entries, 'seq', { value: seq, writable: true, configurable: true });
85
+ /** 分配下一个意图序号:严格大于此前分配过的所有序号,随下一次写盘落地。 */
86
+ export const nextSeq = entries => withSeq(entries, (entries.seq ?? 0) + 1).seq;
87
+ export const keyOf = entry => entry.desired === 'retract' ? retractKey(entry.targetAuthor, entry.kind, entry.id) : entryKey(entry.kind, entry.id);
88
+ /** 等着发出去的状态(被拒的 error 不算,已同步的也不算)。 */
89
+ export const isPending = entry => ['queued', 'paused', 'no_identity', 'needs_cert'].includes(entry?.state);
90
+
91
+ const synced = prev => ({ ...(prev?.lastAuthor === undefined ? {} : { lastAuthor: prev.lastAuthor }),
92
+ ...(prev?.lastSyncedHash === undefined ? {} : { lastSyncedHash: prev.lastSyncedHash }), ...(prev?.lastSyncedAt === undefined ? {} : { lastSyncedAt: prev.lastSyncedAt }) });
93
+
94
+ /** 同作者、同内容、已同步的发布不用再发。作者换了(`lastAuthor !== author`)必须重发。 */
95
+ export const canSkip = (prev, hash, author) =>
96
+ !!author && prev?.desired === 'publish' && prev.state === 'synced' && prev.lastAuthor === author && prev.lastSyncedHash === hash;
97
+
98
+ /** 一次发布的待发条目(带 body),保留上一次同步的元数据。 */
99
+ export const queuePublish = (prev, { kind, id, body, audience }, seq) =>
100
+ ({ seq, kind, id, desired: 'publish', state: 'queued', body, audience, hash: canonicalHash({ body, audience }), ...synced(prev) });
101
+
102
+ /** 一次撤回的待撤条目:记下要撤的是哪个作者的记录,保留上一次同步的元数据。 */
103
+ export const queueRetract = (prev, kind, id, targetAuthor, seq) => ({ seq, kind, id, desired: 'retract', state: 'queued', targetAuthor, ...synced(prev) });
104
+
105
+ /** 换状态;`error` 是这次失败的原因,不给就清掉旧的。 */
106
+ export function withState(entry, state, error) {
107
+ const { lastError, ...rest } = entry;
108
+ return { ...rest, state, ...(error ? { lastError: error } : {}) };
109
+ }
110
+
111
+ /** 发布成功:释放 body,只留 `{ seq, kind, id, desired, state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }`,body 有合法的 createdAt 再留 `lastCreatedAt`。 */
112
+ export const markSynced = (entry, author, now) => {
113
+ const createdAt = entry.body?.createdAt;
114
+ return { seq: entry.seq, kind: entry.kind, id: entry.id, desired: 'publish', state: 'synced', hash: entry.hash, audience: entry.audience, lastAuthor: author, lastSyncedHash: entry.hash,
115
+ lastSyncedAt: now, ...(Number.isSafeInteger(createdAt) && createdAt >= 0 ? { lastCreatedAt: createdAt } : {}) };
116
+ };
117
+
118
+ /** Accord 明确拒绝:不再留 body 和 audience,只留元数据与原因。 */
119
+ export const markRejected = (entry, message) =>
120
+ ({ kind: entry.kind, id: entry.id, desired: entry.desired, state: 'error', lastError: message, ...(entry.hash === undefined ? {} : { hash: entry.hash }), ...synced(entry) });
121
+
122
+ /** 现在拦着这个条目、不让它外发的状态:暂停(只管发布,撤回不拦)、没有身份、需要证书;没有就是 null,可以发。 */
123
+ export function holdState(entry, certState, pausedKinds) {
124
+ if (entry.desired === 'publish' && pausedKinds.includes(entry.kind)) return 'paused';
125
+ return certState === 'active' ? null : certState;
126
+ }
127
+
128
+ // ---- 持久化 ----
129
+
130
+ /**
131
+ * 读出整张表 `{ 键: 条目 }`(磁盘上是 `{ seq, entries }`,旧版是直接平铺的条目);键按条目内容重新规范(兼容旧键名),
132
+ * 缺失、损坏、条目不成样子的都丢掉。序号计数器取顶层 `seq` 与现存条目最大序号中较大的。
133
+ */
134
+ export async function readOutbox(dir) {
135
+ const parsed = await readJson(dir, 'outbox.json'), entries = withSeq({}, 0);
136
+ if (!isPlain(parsed)) return entries;
137
+ const stored = isPlain(parsed.entries) ? parsed.entries : parsed;
138
+ for (const entry of Object.values(stored)) {
139
+ if (isPlain(entry) && typeof entry.kind === 'string' && typeof entry.id === 'string' && ['publish', 'retract'].includes(entry.desired) && typeof entry.state === 'string'
140
+ && (entry.desired === 'publish' || typeof entry.targetAuthor === 'string')) entries[keyOf(entry)] = entry;
141
+ }
142
+ return withSeq(entries, Math.max(Number.isSafeInteger(parsed.seq) ? parsed.seq : 0, ...Object.values(entries).map(entry => entry.seq ?? 0)));
143
+ }
144
+
145
+ export const writeOutbox = (dir, entries) => writeJson(dir, 'outbox.json', { seq: entries.seq ?? 0, entries });
package/lib/policy.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // 网关的本机策略:哪些 kind 暂停外发。存在插件状态目录的 policy.json(卸载后保留);缺失或损坏时当 `{ pausedKinds: [] }`。
2
+ import { readJson, writeJson } from './json-file.mjs';
3
+ import { checkKind, validKind } from './outbox.mjs';
4
+
5
+ const NAME = 'policy.json';
6
+
7
+ /** 读出 `{ pausedKinds }`:只留合法且非保留的 kind,去重排序。 */
8
+ export async function readPolicy(dir) {
9
+ const parsed = await readJson(dir, NAME);
10
+ const kinds = Array.isArray(parsed?.pausedKinds) ? parsed.pausedKinds.filter(validKind) : [];
11
+ return { pausedKinds: [...new Set(kinds)].sort() };
12
+ }
13
+
14
+ /** 暂停或恢复一个 kind 的外发;kind 不合法或是保留类型就抛错。`beforeWrite` 在写第一个字节前调用(它抛错就不写)。返回现在的策略。 */
15
+ export async function setKindPaused(dir, kind, paused, beforeWrite) {
16
+ checkKind(kind);
17
+ const { pausedKinds } = await readPolicy(dir), next = new Set(pausedKinds);
18
+ if (paused) next.add(kind); else next.delete(kind);
19
+ const policy = { pausedKinds: [...next].sort() };
20
+ await writeJson(dir, NAME, policy, beforeWrite);
21
+ return policy;
22
+ }
@@ -0,0 +1,218 @@
1
+ // 私信 friends/dm 与好友动态 friends/feed 的纯逻辑:发布入参的清洗、Accord 记录的投影,以及实时流的变更集与游标。不碰 Coda,也不碰磁盘。
2
+ // 记录照旧由 coda/accord@1 签名与保存;这里只把一页页读回来的记录投影成规范项,并在内存里比对前后两份投影,算出增量帧。
3
+ import { normalizeContentPointer, readContentPointer } from './friends.mjs';
4
+
5
+ export const DM_KIND = 'friends/dm', FEED_KIND = 'friends/feed';
6
+ export const MAX_TEXT = 8000, MAX_MEDIA = 4, MAX_HISTORY = 500;
7
+ // 快照一帧的字节上限,远低于 readFrames 默认的一行 1 MiB:快照按它分片。
8
+ export const MAX_SNAPSHOT_FRAME_BYTES = 256 * 1024;
9
+ const MAX_ID = 200, MAX_ID_BYTES = 256, MAX_AUDIENCE = 500;
10
+ const AUTHOR = /^ed25519:[0-9a-f]{64}$/, AUDIENCE = /^(?:public|ed25519:[0-9a-f]{64})$/;
11
+ const CONTROL = /[\p{Cc}]/u;
12
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
13
+ const CURSOR = new RegExp(`^(${UUID}):(0|[1-9][0-9]*)$`);
14
+
15
+ const fail = message => { throw new Error(message); };
16
+ const length = text => [...text].length;
17
+ const encoder = new TextEncoder();
18
+ const bytes = text => encoder.encode(text).length;
19
+ const isPlain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ const isTime = value => Number.isSafeInteger(value) && value >= 0;
21
+ const validLabel = text => typeof text === 'string' && text.length > 0 && length(text) <= MAX_ID && !CONTROL.test(text);
22
+ export const isAuthor = value => typeof value === 'string' && AUTHOR.test(value);
23
+
24
+ // ---- 发布入参 ----
25
+
26
+ /**
27
+ * 可选的 id、replyTo:原样至多 200 个字符(与 schema 的 maxLength 同样按码点数)、UTF-8 至多 256 字节(与 Accord 一致)、
28
+ * 不含控制字符,去首尾空白后不能是空的;省略给 undefined(id 由调用方生成)。
29
+ */
30
+ function readLabel(value, name) {
31
+ if (value === undefined) return undefined;
32
+ if (typeof value !== 'string' || length(value) > MAX_ID || bytes(value) > MAX_ID_BYTES || CONTROL.test(value) || !value.trim())
33
+ fail(`${name} 须是 1–${MAX_ID} 个字符、UTF-8 至多 ${MAX_ID_BYTES} 字节的文本,不含控制字符`);
34
+ return value.trim();
35
+ }
36
+
37
+ /** text 原样至多 8000 个字(码点,与 schema 一致),再去首尾空白。 */
38
+ function readText(text) {
39
+ if (text === undefined) return '';
40
+ if (typeof text !== 'string') fail('text 须是文本');
41
+ if (length(text) > MAX_TEXT) fail(`text 最多 ${MAX_TEXT} 个字`);
42
+ return text.trim();
43
+ }
44
+
45
+ function readPointers(list, name) {
46
+ if (list === undefined) return [];
47
+ if (!Array.isArray(list) || !list.length || list.length > MAX_MEDIA) fail(`${name} 须是 1–${MAX_MEDIA} 项的数组`);
48
+ return list.map(normalizeContentPointer);
49
+ }
50
+
51
+ const createdAtOf = (existingCreatedAt, now) => {
52
+ const at = isTime(existingCreatedAt) ? existingCreatedAt : now;
53
+ if (!isTime(at)) fail('createdAt 须是非负整数');
54
+ return at;
55
+ };
56
+
57
+ /**
58
+ * 私信的入参 `{ to, id?, text?, attachments?, replyTo? }` → `{ id, to, audience: [to], body }`。只发给一个人,不能发给 public 或自己;
59
+ * text 与 attachments 不能都空。createdAt 先用同一 id 已有记录的(重试时内容不变,才能按幂等跳过),没有再取 now。
60
+ */
61
+ export function normalizeDmInput(input, { selfAuthor, existingCreatedAt, now = Date.now() } = {}) {
62
+ if (!isPlain(input)) fail('私信须是对象');
63
+ const { to } = input;
64
+ if (!isAuthor(to)) fail('to 须是一位好友的公钥 ed25519:<64 位小写十六进制>');
65
+ if (to === selfAuthor) fail('不能给自己发私信');
66
+ const id = readLabel(input.id, 'id'), text = readText(input.text), attachments = readPointers(input.attachments, 'attachments');
67
+ if (!text && !attachments.length) fail('私信的 text 与 attachments 不能都空');
68
+ const replyTo = readLabel(input.replyTo, 'replyTo'), createdAt = createdAtOf(existingCreatedAt, now);
69
+ return { id, to, audience: [to], body: { to, text, ...(attachments.length ? { attachments } : {}), ...(replyTo ? { replyTo } : {}), createdAt } };
70
+ }
71
+
72
+ /**
73
+ * 动态的入参 `{ id?, text?, media?, audience? }` → `{ id, audience, body }`。audience 省略是 `['public']`,写了须是 1–500 项、
74
+ * 每项 public 或公钥,去重;`[]` 不收(撤回走 retract)。text 与 media 不能都空;createdAt 同私信。
75
+ */
76
+ export function normalizeFeedInput(input, { existingCreatedAt, now = Date.now() } = {}) {
77
+ if (!isPlain(input)) fail('动态须是对象');
78
+ const id = readLabel(input.id, 'id'), text = readText(input.text), media = readPointers(input.media, 'media');
79
+ if (!text && !media.length) fail('动态的 text 与 media 不能都空');
80
+ const { audience = ['public'] } = input;
81
+ if (!Array.isArray(audience) || !audience.length || audience.length > MAX_AUDIENCE) fail(`audience 须是 1–${MAX_AUDIENCE} 项的数组;撤回用 retract`);
82
+ if (!audience.every(item => typeof item === 'string' && AUDIENCE.test(item))) fail("audience 每项须是 'public' 或 ed25519:<64 位小写十六进制>");
83
+ return { id, audience: [...new Set(audience)], body: { text, ...(media.length ? { media } : {}), createdAt: createdAtOf(existingCreatedAt, now) } };
84
+ }
85
+
86
+ // ---- 记录投影 ----
87
+
88
+ // 每个 (author, id) 只留 version 最大的一条:最新的是撤回(空 body)或畸形,整条就算没了,不回落到旧版本。
89
+ function latest(records) {
90
+ const top = new Map();
91
+ for (const record of records ?? []) {
92
+ if (!isPlain(record) || typeof record.author !== 'string' || typeof record.id !== 'string') continue;
93
+ const key = JSON.stringify([record.author, record.id]), version = Number.isSafeInteger(record.version) ? record.version : 0;
94
+ if (!top.has(key) || version > top.get(key).version) top.set(key, { record, version });
95
+ }
96
+ return [...top.values()];
97
+ }
98
+
99
+ // 外来正文:text 是至多 8000 字的文本(不合法当空),图片指针只留校验通过的、至多 4 个;两样都空、或 createdAt 不对就是畸形(null)。
100
+ function readBody(body, pointersKey) {
101
+ if (!isPlain(body) || !isTime(body.createdAt)) return null;
102
+ const text = typeof body.text === 'string' && length(body.text) <= MAX_TEXT ? body.text.trim() : '';
103
+ const pointers = Array.isArray(body[pointersKey]) ? body[pointersKey].map(readContentPointer).filter(Boolean).slice(0, MAX_MEDIA) : [];
104
+ return text || pointers.length ? { text, pointers, createdAt: body.createdAt } : null;
105
+ }
106
+
107
+ const compare = (a, b) => a.createdAt - b.createdAt || a.version - b.version || (a.author < b.author ? -1 : a.author > b.author ? 1 : 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
108
+
109
+ /**
110
+ * Accord 的 friends/dm 记录 → 私信规范项,按 (createdAt, version, author, id) 升序。只收真是本机与对方之间的:本机发出的须是本人签的、
111
+ * 发给别人;收到的须是别人签的、发给本人。`peer` 是对面那个人。
112
+ */
113
+ export function projectDmRecords(records, { selfAuthor } = {}) {
114
+ const items = [];
115
+ for (const { record, version } of latest(records)) {
116
+ const body = readBody(record.body, 'attachments'), to = record.body?.to;
117
+ if (!body || !isAuthor(to)) continue;
118
+ let peer;
119
+ if (record.local === true && record.author === selfAuthor && to !== selfAuthor) peer = to;
120
+ else if (record.local === false && record.author !== selfAuthor && to === selfAuthor) peer = record.author;
121
+ else continue;
122
+ const { replyTo } = record.body;
123
+ items.push({ author: record.author, id: record.id, version, local: record.local, peer, to, text: body.text, attachments: body.pointers,
124
+ ...(validLabel(replyTo) ? { replyTo } : {}), createdAt: body.createdAt });
125
+ }
126
+ return items.sort(compare);
127
+ }
128
+
129
+ /** Accord 的 friends/feed 记录 → 动态规范项,按 (createdAt, version, author, id) 降序(新的在前)。 */
130
+ export function projectFeedRecords(records) {
131
+ const items = [];
132
+ for (const { record, version } of latest(records)) {
133
+ const body = readBody(record.body, 'media');
134
+ if (body) items.push({ author: record.author, id: record.id, version, local: record.local === true, text: body.text, media: body.pointers, createdAt: body.createdAt });
135
+ }
136
+ return items.sort((a, b) => compare(b, a));
137
+ }
138
+
139
+ // ---- 变更集与游标 ----
140
+
141
+ /** 游标 `${epoch}:${seq}` → `{ epoch, seq }`;不合法给 null。 */
142
+ export function parseCursor(after) {
143
+ const match = typeof after === 'string' ? CURSOR.exec(after) : null;
144
+ if (!match) return null;
145
+ const seq = Number(match[2]);
146
+ return Number.isSafeInteger(seq) ? { epoch: match[1], seq } : null;
147
+ }
148
+
149
+ const keyOf = item => JSON.stringify([item.author, item.id]);
150
+ /** 一次变化里用来过滤的那一项:upsert 看它的 item,retract 看它自己(带 author、peer)。 */
151
+ export const subjectOf = event => event.type === 'upsert' ? event.item : event;
152
+ /** 变化 → 帧:seq 换成游标。 */
153
+ export const frameOf = (epoch, { seq, ...event }) => ({ ...event, cursor: `${epoch}:${seq}` });
154
+
155
+ /**
156
+ * 快照的帧:items 按序切成每帧 JSON 至多 `maxBytes` 字节的几片,`{ type: 'snapshot', cursor, items, more }`,还有后续分片的
157
+ * `more` 为 true,最后一片(空快照也有这一片,`items: []`)为 false;客户端收到 more 为 false 才把整份快照与游标落定。
158
+ */
159
+ export function snapshotFrames(cursor, items, maxBytes = MAX_SNAPSHOT_FRAME_BYTES) {
160
+ const empty = bytes(JSON.stringify({ type: 'snapshot', cursor, items: [], more: false })), chunks = [[]];
161
+ let size = empty;
162
+ for (const item of items) {
163
+ const one = bytes(JSON.stringify(item)) + 1;
164
+ if (chunks.at(-1).length && size + one > maxBytes) { chunks.push([]); size = empty; }
165
+ chunks.at(-1).push(item);
166
+ size += one;
167
+ }
168
+ return chunks.map((chunk, i) => ({ type: 'snapshot', cursor, items: chunk, more: i < chunks.length - 1 }));
169
+ }
170
+
171
+ /**
172
+ * 一条流的内存状态:启动时的 epoch、单调的 seq、当前投影(按 (author, id))、至多 `maxHistory` 条变化的环缓冲。
173
+ * `applySnapshot` 换上新一份投影并给出这次的变化;`resume(after, match)` 按游标给出续上的增量,续不上就给全量快照。
174
+ */
175
+ export function createStreamHub({ epoch = globalThis.crypto.randomUUID(), maxHistory = MAX_HISTORY } = {}) {
176
+ let seq = 0, current = new Map(), history = [];
177
+ const oldestSeq = () => history.length ? history[0].seq : seq + 1;
178
+ const cursor = () => `${epoch}:${seq}`;
179
+ return {
180
+ epoch,
181
+ get seq() { return seq; },
182
+ get oldestSeq() { return oldestSeq(); },
183
+ cursor,
184
+ items: () => [...current.values()],
185
+ // 先在局部算好这次的变化,最后一并换上投影、seq 与历史:中途出错,hub 还是原来那份。
186
+ applySnapshot(nextItems) {
187
+ const next = new Map(nextItems.map(item => [keyOf(item), item])), events = [];
188
+ let at = seq;
189
+ for (const [key, item] of current) {
190
+ if (!next.has(key)) events.push({ seq: ++at, type: 'retract', author: item.author, id: item.id, ...(item.peer ? { peer: item.peer } : {}) });
191
+ }
192
+ for (const [key, item] of next) {
193
+ const old = current.get(key);
194
+ if (old && old.version === item.version && JSON.stringify(old) === JSON.stringify(item)) continue;
195
+ // 同一条私信换了收件人:旧会话那边先撤掉,新会话再收到它。
196
+ if (old?.peer && old.peer !== item.peer) events.push({ seq: ++at, type: 'retract', author: old.author, id: old.id, peer: old.peer });
197
+ events.push({ seq: ++at, type: 'upsert', item });
198
+ }
199
+ // 不把 events 展开成实参(一次几十万条会超出实参上限):够多就只取最后 maxHistory 条,否则逐条追加再裁。
200
+ let kept;
201
+ if (events.length >= maxHistory) kept = events.slice(-maxHistory);
202
+ else {
203
+ kept = history.slice();
204
+ for (const event of events) kept.push(event);
205
+ if (kept.length > maxHistory) kept.splice(0, kept.length - maxHistory);
206
+ }
207
+ current = next;
208
+ seq = at;
209
+ history = kept;
210
+ return events;
211
+ },
212
+ resume(after, match = () => true) {
213
+ const at = parseCursor(after);
214
+ if (!at || at.epoch !== epoch || at.seq > seq || at.seq < oldestSeq() - 1) return { mode: 'snapshot', cursor: cursor(), items: [...current.values()].filter(match) };
215
+ return { mode: 'delta', cursor: cursor(), events: history.filter(event => event.seq > at.seq && match(subjectOf(event))) };
216
+ },
217
+ };
218
+ }
package/main.mjs CHANGED
@@ -1,12 +1,16 @@
1
- // 好友插件的模块(Coda 的 docs/plugins.md「插件宿主」)。Accord 的读写全在页面里发起(页面用自己的 coda.query / coda.call /
2
- // coda.watch);模块只管好友的本地备注:存在插件自己的持久目录 notes.json 里,不外发,页面通过视图消息读写,
3
- // 也能用 `coda self notes.list|notes.set|notes.delete` 读写。activate 里不碰 Accord。
1
+ // 好友插件的模块(Coda 的 docs/plugins.md「插件宿主」)。好友页自己的 Accord 读写在页面里发起(页面用自己的 coda.query /
2
+ // coda.call / coda.watch);模块管两件事:
3
+ // - 好友的本地备注:存在插件自己的持久目录 notes.json 里,不外发,页面通过视图消息读写,
4
+ // 也能用 `coda self notes.list|notes.set|notes.delete` 读写;
5
+ // - 业务无关的社交网关 friends/social@1(lib/gateway.mjs):别的插件经它读好友、发布与撤回记录,全部透传 coda/accord@1;
6
+ // 发布策略用 `coda self policy.get|policy.setKind` 读写。
7
+ import { createGateway } from './lib/gateway.mjs';
4
8
  import { deleteNote, readNotes, setNote } from './lib/notes.mjs';
5
9
 
6
- let dir = null;
10
+ let dir = null, gateway = null;
7
11
  const handles = [];
8
12
 
9
- export function activate(coda) {
13
+ export async function activate(coda) {
10
14
  dir = coda.plugin.state;
11
15
  const actions = {
12
16
  'notes.list': () => readNotes(dir),
@@ -28,9 +32,14 @@ export function activate(coda) {
28
32
  });
29
33
  },
30
34
  });
35
+ gateway = createGateway(coda, dir);
36
+ for (const [name, fn] of Object.entries(gateway.policy)) handles.push(coda.self.handle(name, input => fn(input ?? {})));
37
+ await gateway.start();
31
38
  }
32
39
 
33
40
  export function deactivate() {
41
+ gateway?.stop();
42
+ gateway = null;
34
43
  for (const handle of handles.splice(0)) handle?.dispose?.();
35
44
  dir = null;
36
45
  }