@tik-choco/mistvault 0.0.0-stage → 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.
Files changed (62) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +164 -0
  3. package/README.md +221 -2
  4. package/README.zh.md +164 -0
  5. package/dist/appState.d.ts +24 -0
  6. package/dist/appState.js +20 -0
  7. package/dist/code.d.ts +7 -0
  8. package/dist/code.js +49 -0
  9. package/dist/controller.d.ts +55 -0
  10. package/dist/controller.js +74 -0
  11. package/dist/core/client.d.ts +112 -0
  12. package/dist/core/client.js +536 -0
  13. package/dist/core/crypto.d.ts +24 -0
  14. package/dist/core/crypto.js +185 -0
  15. package/dist/core/head.d.ts +54 -0
  16. package/dist/core/head.js +123 -0
  17. package/dist/core/parse.d.ts +1 -0
  18. package/dist/core/parse.js +1 -0
  19. package/dist/core/protocol.d.ts +74 -0
  20. package/dist/core/protocol.js +93 -0
  21. package/dist/elements/PanelElement.d.ts +30 -0
  22. package/dist/elements/PanelElement.js +56 -0
  23. package/dist/elements/RoomControls.d.ts +21 -0
  24. package/dist/elements/RoomControls.js +27 -0
  25. package/dist/elements/ScopeVaultPanelElement.d.ts +10 -0
  26. package/dist/elements/ScopeVaultPanelElement.js +27 -0
  27. package/dist/elements/VaultPanelElement.d.ts +39 -0
  28. package/dist/elements/VaultPanelElement.js +191 -0
  29. package/dist/elements/dom.d.ts +14 -0
  30. package/dist/elements/dom.js +58 -0
  31. package/dist/elements/index.d.ts +15 -0
  32. package/dist/elements/index.js +12 -0
  33. package/dist/i18n.d.ts +132 -0
  34. package/dist/i18n.js +96 -0
  35. package/dist/index.d.ts +13 -0
  36. package/dist/index.js +12 -0
  37. package/dist/parts.d.ts +42 -0
  38. package/dist/parts.js +267 -0
  39. package/dist/preact/ScopeVaultPanel.d.ts +10 -0
  40. package/dist/preact/ScopeVaultPanel.js +8 -0
  41. package/dist/preact/VaultPanel.d.ts +16 -0
  42. package/dist/preact/VaultPanel.js +14 -0
  43. package/dist/preact/index.d.ts +5 -0
  44. package/dist/preact/index.js +3 -0
  45. package/dist/preact/ui.css +132 -0
  46. package/dist/preact/useVault.d.ts +6 -0
  47. package/dist/preact/useVault.js +13 -0
  48. package/dist/scopeKey.d.ts +1 -0
  49. package/dist/scopeKey.js +49 -0
  50. package/dist/scopeManager.d.ts +14 -0
  51. package/dist/scopeManager.js +110 -0
  52. package/dist/scopeVault.d.ts +39 -0
  53. package/dist/scopeVault.js +212 -0
  54. package/dist/session.d.ts +44 -0
  55. package/dist/session.js +736 -0
  56. package/dist/settings.d.ts +21 -0
  57. package/dist/settings.js +59 -0
  58. package/dist/stored.d.ts +4 -0
  59. package/dist/stored.js +27 -0
  60. package/dist/transport.d.ts +20 -0
  61. package/dist/transport.js +117 -0
  62. package/package.json +57 -4
@@ -0,0 +1,110 @@
1
+ import { openScopeVault } from './scopeVault.js';
2
+ function roomPool(transportFor) {
3
+ const pool = new Map();
4
+ return (id, hasProvider) => {
5
+ const room = pool.get(id) ?? { source: transportFor(id), leases: 0, members: new Set() };
6
+ pool.set(id, room);
7
+ room.leases++;
8
+ let lastJoin;
9
+ let probedJoin;
10
+ const { source } = room;
11
+ function leave() {
12
+ if (room.members.delete(hasProvider) && !room.members.size && room.joined) {
13
+ room.joined = undefined;
14
+ source.leave(id);
15
+ }
16
+ }
17
+ return {
18
+ transport: {
19
+ join() {
20
+ room.members.add(hasProvider);
21
+ if (room.joined && room.joined === lastJoin) {
22
+ // Probe once if a co-tenant still sees a provider. Its view may also
23
+ // be stale, so a second unsuccessful discovery forces a fresh join.
24
+ if (probedJoin !== room.joined && [...room.members].some(connected => connected())) {
25
+ probedJoin = room.joined;
26
+ }
27
+ else {
28
+ room.joined = undefined;
29
+ source.leave(id);
30
+ }
31
+ }
32
+ room.joined ??= source.join(id);
33
+ lastJoin = room.joined;
34
+ return lastJoin;
35
+ },
36
+ leave,
37
+ send: (_, to, bytes) => source.send(id, to, bytes),
38
+ onMessage: (_, cb) => source.onMessage(id, cb),
39
+ onPeer: (_, cb) => source.onPeer(id, cb),
40
+ storageAdd: (name, bytes) => source.storageAdd(name, bytes),
41
+ storageGet: cid => source.storageGet(cid),
42
+ },
43
+ providerFound() { probedJoin = undefined; },
44
+ release() { leave(); if (--room.leases === 0)
45
+ pool.delete(id); },
46
+ };
47
+ };
48
+ }
49
+ export function createScopeVaultManager(o) {
50
+ const acquire = roomPool(room => o.transportFor(room));
51
+ const listeners = new Set();
52
+ const entries = new Map();
53
+ let disposed = false;
54
+ function emit() {
55
+ for (const cb of listeners) {
56
+ try {
57
+ cb();
58
+ }
59
+ catch { /* Isolate subscribers. */ }
60
+ }
61
+ }
62
+ function remove(id) {
63
+ const entry = entries.get(id);
64
+ entries.delete(id);
65
+ entry.off();
66
+ entry.vault.dispose();
67
+ }
68
+ return {
69
+ sync(scopes) {
70
+ if (disposed)
71
+ return;
72
+ const wanted = new Map(scopes.map(scope => [scope.roomId, scope]));
73
+ let changed = false;
74
+ for (const [id, entry] of entries) {
75
+ if (wanted.get(id)?.adapter !== entry.scope.adapter) {
76
+ remove(id);
77
+ changed = true;
78
+ }
79
+ }
80
+ for (const [id, scope] of wanted) {
81
+ const existing = entries.get(id);
82
+ if (existing) {
83
+ existing.scope = scope;
84
+ continue;
85
+ }
86
+ // The closing vault still needs its own election during its final save.
87
+ const vault = openScopeVault({ ...o, ...scope, isWriter: () => entry.scope.isWriter?.() ?? true }, acquire);
88
+ const entry = { scope, vault, room: vault.getView().room, off: vault.subscribe(view => {
89
+ if (view.room !== entry.room) {
90
+ entry.room = view.room;
91
+ emit();
92
+ }
93
+ }) };
94
+ entries.set(id, entry);
95
+ changed = true;
96
+ }
97
+ if (changed)
98
+ emit();
99
+ },
100
+ get: id => entries.get(id)?.vault,
101
+ rooms: () => [...new Set(Array.from(entries.values(), entry => entry.room).filter(Boolean))].sort(),
102
+ subscribe(cb) { listeners.add(cb); return () => { listeners.delete(cb); }; },
103
+ dispose() {
104
+ disposed = true;
105
+ for (const id of entries.keys())
106
+ remove(id);
107
+ listeners.clear();
108
+ },
109
+ };
110
+ }
@@ -0,0 +1,39 @@
1
+ import type { VaultOptions, VaultView } from './controller.js';
2
+ import type { VaultMode } from './settings.js';
3
+ import type { AcquireTransport } from './session.js';
4
+ export interface ScopeConfig {
5
+ mode: VaultMode;
6
+ room: string;
7
+ rev: number;
8
+ by: string;
9
+ }
10
+ type Setting = Pick<ScopeConfig, 'mode' | 'room'>;
11
+ export interface ScopeVaultOptions<S> extends VaultOptions<S> {
12
+ app: string;
13
+ roomId: string;
14
+ nodeId: string;
15
+ isWriter?: () => boolean;
16
+ defaultConfig?: () => Setting | Promise<Setting>;
17
+ }
18
+ export interface ScopeVaultView extends Omit<VaultView, 'hasCode' | 'appEnabled'> {
19
+ config: ScopeConfig;
20
+ providerSeen: boolean;
21
+ }
22
+ export interface ScopeVault {
23
+ getView(): ScopeVaultView;
24
+ subscribe(cb: (view: ScopeVaultView) => void): () => void;
25
+ configure(mode: VaultMode, room?: string): boolean;
26
+ materializeDefault(): Promise<boolean>;
27
+ receiveConfig(cfg: unknown, from: string): boolean;
28
+ onConfig(cb: (cfg: ScopeConfig) => void): () => void;
29
+ changed(): void;
30
+ saveNow(): Promise<void>;
31
+ restoreNow(): Promise<void>;
32
+ dispose(): void;
33
+ }
34
+ export declare function defaultScopeConfig(storage?: Storage | undefined): Promise<Setting>;
35
+ export declare function scopeInviteParam(cfg: Setting): string;
36
+ export declare function parseScopeInviteParam(v: unknown): Setting | null;
37
+ export declare function createScopeVault<S>(o: ScopeVaultOptions<S>): ScopeVault;
38
+ export declare function openScopeVault<S>(o: Omit<ScopeVaultOptions<S>, 'transport'>, acquire: AcquireTransport): ScopeVault;
39
+ export {};
@@ -0,0 +1,212 @@
1
+ import { deriveAutoRoom } from './core/crypto.js';
2
+ import { isRecord, safeInt } from './core/head.js';
3
+ import { defaultAppState, parseAppState } from './appState.js';
4
+ import { browserStorage, loadSettings, validVaultRoom } from './settings.js';
5
+ import { createVaultSession } from './session.js';
6
+ import { scopeStateKey } from './scopeKey.js';
7
+ import { read, write, notifyStored, subscribeStored } from './stored.js';
8
+ const validNode = (v) => typeof v === 'string' && v.length > 0 && v.length <= 128;
9
+ const auto = () => ({ mode: 'auto', room: '' });
10
+ // A local default has no author. Only authored configs are valid on the wire.
11
+ const localConfig = ({ mode, room }) => ({ mode, room, rev: 0, by: '' });
12
+ const validSetting = (v) => isRecord(v) && typeof v.room === 'string' &&
13
+ (v.mode === 'custom' ? validVaultRoom(v.room) : (v.mode === 'off' || v.mode === 'auto') && v.room === '');
14
+ const newer = (a, b) => a.rev > b.rev || a.rev === b.rev && a.by > b.by;
15
+ const CFG_STEP = 1000;
16
+ const peerRevisionLimit = Number.MAX_SAFE_INTEGER - CFG_STEP;
17
+ // Reopening a scope can replace its adapter while the old apply still owns the store.
18
+ const scopeWorkQueues = new Map();
19
+ function parseConfig(value, roomId) {
20
+ if (!isRecord(value))
21
+ return;
22
+ const { rev, by } = value;
23
+ if (!validNode(by) || !safeInt(rev, 0) || !validSetting(value) || value.room === roomId)
24
+ return;
25
+ return { mode: value.mode, room: value.room, rev, by };
26
+ }
27
+ function personalRoomSetting(storage) {
28
+ const personal = loadSettings(storage);
29
+ if (!personal.code || personal.mode === 'off')
30
+ return auto();
31
+ if (personal.mode === 'custom')
32
+ return { mode: 'custom', room: personal.room };
33
+ return deriveAutoRoom('tc-vault', personal.code).then(room => ({ mode: 'custom', room }));
34
+ }
35
+ export async function defaultScopeConfig(storage = browserStorage()) {
36
+ return personalRoomSetting(storage);
37
+ }
38
+ // Always explicit: unlike tc-linkai, a joiner's own default may differ (personal vault room), so 'auto' is spelled out.
39
+ // Custom rooms carry a 'c:' prefix so a room literally named 'auto' or 'off' stays unambiguous.
40
+ export function scopeInviteParam(cfg) {
41
+ return cfg.mode === 'auto' ? 'auto' : cfg.mode === 'off' ? 'off' : 'c:' + cfg.room;
42
+ }
43
+ export function parseScopeInviteParam(v) {
44
+ if (v === 'auto' || v === 'off')
45
+ return { mode: v, room: '' };
46
+ if (v === '')
47
+ return { mode: 'off', room: '' };
48
+ if (typeof v === 'string' && v.startsWith('c:'))
49
+ return validVaultRoom(v.slice(2)) ? { mode: 'custom', room: v.slice(2) } : null;
50
+ return typeof v === 'string' && validVaultRoom(v) ? { mode: 'custom', room: v } : null;
51
+ }
52
+ export function createScopeVault(o) {
53
+ return openScopeVault(o, () => ({ transport: typeof o.transport === 'function' ? o.transport() : o.transport }));
54
+ }
55
+ export function openScopeVault(o, acquire) {
56
+ const { app, roomId, nodeId } = o, storage = o.storage ?? browserStorage();
57
+ if (!app || !roomId || !validNode(nodeId))
58
+ throw new Error('Scope app, room ID and node ID are required');
59
+ const key = scopeStateKey(app, roomId);
60
+ const load = () => {
61
+ const raw = read(key, storage);
62
+ let cfg;
63
+ if (isRecord(raw)) {
64
+ if (raw.sharedConfig !== false) {
65
+ cfg = parseConfig(raw.cfg, roomId);
66
+ // Older clients persisted unchecked peer clocks. Keep the chosen room and
67
+ // author, but let a saturated legacy clock start again at the first revision.
68
+ if (cfg && raw.boundedClock !== true && cfg.rev >= peerRevisionLimit - CFG_STEP)
69
+ cfg.rev = 0;
70
+ }
71
+ else if (validSetting(raw.cfg) && raw.cfg.room !== roomId)
72
+ cfg = localConfig(raw.cfg);
73
+ }
74
+ return { state: parseAppState(raw), cfg,
75
+ providerSeen: isRecord(raw) && raw.providerSeen === true };
76
+ };
77
+ const stored = load();
78
+ let cfg = stored.cfg ?? localConfig(auto());
79
+ let providerSeen = stored.providerSeen, initialized = false, disposed = false;
80
+ const configListeners = new Set();
81
+ let ready;
82
+ const initialization = new Promise(resolve => { ready = resolve; });
83
+ const core = createVaultSession({
84
+ ...o, acquire, autoRoomApp: app, lockName: key, workQueues: scopeWorkQueues,
85
+ isWriter: o.isWriter ?? (() => true),
86
+ loadState: () => load().state,
87
+ saveState(state) {
88
+ const latest = load();
89
+ if (latest.cfg?.by && newer(latest.cfg, cfg))
90
+ return;
91
+ providerSeen ||= latest.providerSeen;
92
+ write(key, { ...state, ...(initialized && { cfg, sharedConfig: !!cfg.by, boundedClock: true }), providerSeen }, storage);
93
+ notifyStored(storage, key);
94
+ },
95
+ waitForProvider: () => cfg.mode === 'custom' || providerSeen,
96
+ providerFound() { if (!providerSeen) {
97
+ providerSeen = true;
98
+ core.persist();
99
+ } },
100
+ });
101
+ function start() {
102
+ initialized = true;
103
+ core.start({ ...cfg, code: roomId });
104
+ ready();
105
+ }
106
+ function announce() {
107
+ for (const cb of configListeners) {
108
+ try {
109
+ cb({ ...cfg });
110
+ }
111
+ catch { /* Isolate subscribers. */ }
112
+ }
113
+ }
114
+ function adopt(next, fromStorage = false) {
115
+ const switched = cfg.mode !== next.mode || cfg.room !== next.room;
116
+ cfg = next;
117
+ if (switched)
118
+ core.resetState(fromStorage ? load().state : { ...defaultAppState(), dirty: true });
119
+ if (switched || !initialized)
120
+ start();
121
+ if (!fromStorage)
122
+ core.persist();
123
+ announce();
124
+ }
125
+ function readShared() {
126
+ if (disposed || core.writing)
127
+ return;
128
+ const next = load();
129
+ providerSeen ||= next.providerSeen;
130
+ if (next.cfg?.by && newer(next.cfg, cfg))
131
+ adopt(next.cfg, true);
132
+ core.sharedStateChanged(next.state);
133
+ }
134
+ const offStorage = subscribeStored(readShared, storage, globalThis.window, k => k === key || k === null);
135
+ function initialize(setting) {
136
+ if (core.closed || initialized)
137
+ return;
138
+ const initial = validSetting(setting) && setting.room !== roomId ? setting : auto();
139
+ cfg = localConfig(initial);
140
+ start();
141
+ core.persist();
142
+ }
143
+ if (stored.cfg)
144
+ start();
145
+ else {
146
+ try {
147
+ const initial = o.defaultConfig ? o.defaultConfig() : personalRoomSetting(storage);
148
+ if (validSetting(initial))
149
+ initialize(initial);
150
+ else
151
+ void Promise.resolve(initial).then(initialize, () => initialize(auto()));
152
+ }
153
+ catch {
154
+ initialize(auto());
155
+ }
156
+ }
157
+ function getView() {
158
+ const { hasCode, appEnabled, ...view } = core.getView();
159
+ return { ...view, ...(!initialized && { mode: cfg.mode, status: 'searching' }), config: { ...cfg }, providerSeen };
160
+ }
161
+ return {
162
+ getView, subscribe: cb => core.subscribe(() => cb(getView())),
163
+ configure(mode, room = '') {
164
+ if (disposed)
165
+ return false;
166
+ readShared();
167
+ const next = { mode, room: mode === 'custom' ? room : '', rev: cfg.rev + 1, by: nodeId };
168
+ if (!parseConfig(next, roomId) || cfg.by && next.mode === cfg.mode && next.room === cfg.room)
169
+ return false;
170
+ adopt(next);
171
+ return true;
172
+ },
173
+ async materializeDefault() {
174
+ if (!disposed && !initialized)
175
+ await initialization;
176
+ if (disposed || cfg.by)
177
+ return false;
178
+ readShared();
179
+ if (disposed || cfg.by)
180
+ return false;
181
+ adopt({ ...cfg, rev: 1, by: nodeId });
182
+ return true;
183
+ },
184
+ receiveConfig(value, from) {
185
+ if (disposed || !validNode(from))
186
+ return false;
187
+ readShared();
188
+ const next = parseConfig(value, roomId);
189
+ if (!next || !newer(next, cfg))
190
+ return false;
191
+ // Bound each peer advance and reserve safe integer revisions for local edits.
192
+ if ((cfg.by && next.rev - cfg.rev > CFG_STEP) || next.rev >= peerRevisionLimit)
193
+ return false;
194
+ adopt(next);
195
+ return true;
196
+ },
197
+ onConfig(cb) { configListeners.add(cb); return () => { configListeners.delete(cb); }; },
198
+ changed: core.changed,
199
+ async saveNow() { if (!disposed && !initialized)
200
+ await initialization; await core.saveNow(); },
201
+ async restoreNow() { if (!disposed && !initialized)
202
+ await initialization; await core.restoreNow(); },
203
+ dispose() {
204
+ if (disposed)
205
+ return;
206
+ disposed = true;
207
+ offStorage();
208
+ configListeners.clear();
209
+ void core.dispose(initialization).then(ready, ready);
210
+ },
211
+ };
212
+ }
@@ -0,0 +1,44 @@
1
+ import type { EscrowTransport } from './core/client.js';
2
+ import type { VaultSettings, VaultAppState } from './settings.js';
3
+ import type { VaultAdapter, VaultView } from './controller.js';
4
+ type Destination = Pick<VaultSettings, 'mode' | 'room' | 'code'>;
5
+ export interface TransportLease {
6
+ transport: EscrowTransport;
7
+ release?(): void;
8
+ providerFound?(): void;
9
+ }
10
+ export type AcquireTransport = (room: string, hasProvider: () => boolean) => TransportLease;
11
+ interface SessionOptions<S> {
12
+ app: string;
13
+ adapter: VaultAdapter<S>;
14
+ autoRoomApp: string;
15
+ lockName: string;
16
+ acquire: AcquireTransport;
17
+ workQueues?: Map<string, Promise<void>>;
18
+ loadState(): VaultAppState;
19
+ saveState(state: VaultAppState): void;
20
+ isWriter?(): boolean;
21
+ waitForProvider?(): boolean;
22
+ providerFound?(): void;
23
+ now?: () => number;
24
+ partGcGraceMs?: number;
25
+ }
26
+ export declare function createVaultSession<S>(o: SessionOptions<S>): {
27
+ start: (destination: Destination) => void;
28
+ getView: () => VaultView;
29
+ changed: () => void;
30
+ persist: (clear?: {
31
+ version: number;
32
+ token?: string;
33
+ }) => void;
34
+ sharedStateChanged: (app: VaultAppState) => void;
35
+ readonly state: VaultAppState;
36
+ resetState(next: VaultAppState): void;
37
+ readonly writing: boolean;
38
+ readonly closed: boolean;
39
+ subscribe(cb: (view: VaultView) => void): () => void;
40
+ saveNow: () => Promise<void>;
41
+ restoreNow: () => Promise<void>;
42
+ dispose(configReady?: Promise<void>): Promise<void>;
43
+ };
44
+ export {};