@evolustr/client 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The app database behind an interface (SPEC §2, §3.4, §6.2 rules 5–6).
3
+ * `evolu.ts` implements it with Evolu 8.x; tests use `memoryDatabases`.
4
+ */
5
+ import { type Bytes, sHash } from "@evolustr/core";
6
+
7
+ export interface Row {
8
+ readonly id: string;
9
+ readonly isDeleted: boolean;
10
+ /** `updatedAt ?? createdAt`, as Unix milliseconds. */
11
+ readonly changedAt: number;
12
+ /** The app's own columns (no system columns). */
13
+ readonly values: Readonly<Record<string, unknown>>;
14
+ }
15
+
16
+ export interface AppDatabase {
17
+ /** `sHash` of the data secret this database was opened with. */
18
+ readonly sHash: string;
19
+ /** The app's tables, which a migration copies. */
20
+ readonly tables: ReadonlyArray<string>;
21
+ readonly readRows: (table: string) => Promise<ReadonlyArray<Row>>;
22
+ readonly upsertRows: (table: string, rows: ReadonlyArray<Row>) => Promise<void>;
23
+ /** Evolustr's own small key-value table (vault copy, settings cache). */
24
+ readonly getMeta: (key: string) => Promise<string | null>;
25
+ readonly setMeta: (key: string, value: string) => Promise<void>;
26
+ /** Deletes the local database (not data on relays). */
27
+ readonly deleteLocal: () => Promise<void>;
28
+ readonly close: () => Promise<void>;
29
+ }
30
+
31
+ /** Opens (or creates) the local database for a data secret S. */
32
+ export type OpenDatabase = (s: Bytes) => Promise<AppDatabase>;
33
+
34
+ export const META_VAULT = "vault";
35
+ export const META_SHARED_SETTINGS = "sharedSettings";
36
+
37
+ export type MigrationMode =
38
+ | { readonly kind: "all" }
39
+ /** Copy rows missing in the target, or changed after `cutoffMs - marginMs`. */
40
+ | { readonly kind: "since"; readonly cutoffMs: number; readonly marginMs: number }
41
+ /** Copy only rows whose id isn't in the target; never overwrite (#51). */
42
+ | { readonly kind: "missingOnly" };
43
+
44
+ export interface MigrationResult {
45
+ /** Rows written to the target. */
46
+ readonly copied: number;
47
+ /** Rows the target already had, with different content in the source, that weren't copied. */
48
+ readonly skippedChanged: number;
49
+ }
50
+
51
+ const sameContent = (a: Row, b: Row): boolean =>
52
+ a.isDeleted === b.isDeleted && JSON.stringify(a.values) === JSON.stringify(b.values);
53
+
54
+ /** Copies rows between databases with upsert, keeping ids (SPEC §3.4). */
55
+ export const migrateRows = async (
56
+ from: AppDatabase,
57
+ to: AppDatabase,
58
+ mode: MigrationMode,
59
+ ): Promise<MigrationResult> => {
60
+ let copied = 0;
61
+ let skippedChanged = 0;
62
+ for (const table of from.tables) {
63
+ const source = await from.readRows(table);
64
+ let rows = source;
65
+ if (mode.kind !== "all") {
66
+ const existing = new Map((await to.readRows(table)).map((r) => [r.id, r]));
67
+ const after = mode.kind === "since" ? mode.cutoffMs - mode.marginMs : Number.POSITIVE_INFINITY;
68
+ rows = source.filter((r) => !existing.has(r.id) || r.changedAt > after);
69
+ const taken = new Set(rows.map((r) => r.id));
70
+ skippedChanged += source.filter((r) => {
71
+ const there = existing.get(r.id);
72
+ return there !== undefined && !taken.has(r.id) && !sameContent(r, there);
73
+ }).length;
74
+ }
75
+ if (rows.length > 0) await to.upsertRows(table, rows);
76
+ copied += rows.length;
77
+ }
78
+ return { copied, skippedChanged };
79
+ };
80
+
81
+ /** In-memory databases for tests, one per data secret. */
82
+ export const memoryDatabases = (tables: ReadonlyArray<string>, now: () => number = Date.now) => {
83
+ const dbs = new Map<string, { rows: Map<string, Map<string, Row>>; meta: Map<string, string>; deleted: boolean }>();
84
+ const open: OpenDatabase = (s) => {
85
+ const key = sHash(s);
86
+ let state = dbs.get(key);
87
+ if (state === undefined || state.deleted) {
88
+ state = { rows: new Map(tables.map((t) => [t, new Map()])), meta: new Map(), deleted: false };
89
+ dbs.set(key, state);
90
+ }
91
+ const st = state;
92
+ const db: AppDatabase = {
93
+ sHash: key,
94
+ tables,
95
+ readRows: async (table) => [...(st.rows.get(table)?.values() ?? [])],
96
+ upsertRows: async (table, rows) => {
97
+ const t = st.rows.get(table);
98
+ if (t === undefined) throw new Error(`Unknown table ${table}`);
99
+ for (const r of rows) t.set(r.id, { ...r, changedAt: now() });
100
+ },
101
+ getMeta: async (k) => st.meta.get(k) ?? null,
102
+ setMeta: async (k, v) => void st.meta.set(k, v),
103
+ deleteLocal: async () => {
104
+ st.deleted = true;
105
+ },
106
+ close: async () => {},
107
+ };
108
+ return Promise.resolve(db);
109
+ };
110
+ /** Test helper: write a row as the app would. */
111
+ const write = async (s: Bytes, table: string, id: string, values: Record<string, unknown>) =>
112
+ (await open(s)).upsertRows(table, [{ id, isDeleted: false, changedAt: now(), values }]);
113
+ return { open, write, has: (s: Bytes) => dbs.has(sHash(s)) && !dbs.get(sHash(s))!.deleted };
114
+ };
package/src/evolu.ts ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * {@link AppDatabase} over Evolu 8.x (SPEC §2).
3
+ *
4
+ * The app keeps control of Evolu's platform setup (web workers, React Native):
5
+ * it passes `createEvolu`, which Evolustr calls with the schema, the AppOwner
6
+ * made from S, and the app name.
7
+ *
8
+ * Pass `onDatabaseDeleted: () => {}` in the Evolu config: Evolustr deletes the
9
+ * old local database after a migration, and Evolu otherwise reloads the page.
10
+ */
11
+ import {
12
+ type AppOwner,
13
+ type Evolu,
14
+ type EvoluSchema,
15
+ OwnerSecret,
16
+ String as EvoluString,
17
+ createAppOwner,
18
+ createIdFromString,
19
+ createQueryBuilder,
20
+ id,
21
+ } from "@evolu/common";
22
+ import type { MutationOptions } from "@evolu/common/local-first";
23
+ import { type Bytes, sHash, sha256Hex } from "@evolustr/core";
24
+ import type { AppDatabase, OpenDatabase, Row } from "./database.ts";
25
+
26
+ /** Evolustr's own table, merged into the app's schema. */
27
+ export const evolustrSchema = {
28
+ evolustrMeta: { id: id("EvolustrMeta"), value: EvoluString },
29
+ } as const;
30
+
31
+ export type WithEvolustr<S extends EvoluSchema> = S & typeof evolustrSchema;
32
+
33
+ /** Local database name: Evolu adds the AppOwner, so accounts never mix (SPEC §2). */
34
+ export const evoluAppName = (appId: string): string => `evolustr-${sha256Hex(appId).slice(0, 16)}`;
35
+
36
+ export interface EvoluDatabaseOptions<S extends EvoluSchema> {
37
+ readonly appId: string;
38
+ readonly schema: S;
39
+ readonly createEvolu: (args: {
40
+ readonly schema: WithEvolustr<S>;
41
+ readonly appOwner: AppOwner;
42
+ readonly appName: string;
43
+ }) => Evolu<WithEvolustr<S>> | Promise<Evolu<WithEvolustr<S>>>;
44
+ }
45
+
46
+ const SYSTEM_COLUMNS = new Set(["id", "createdAt", "updatedAt", "isDeleted", "ownerId"]);
47
+
48
+ /* Evolu's API is typed per table name; Evolustr works over any table, so the
49
+ few dynamic calls below go through `Loose`. */
50
+ type Loose = any;
51
+
52
+ const toRow = (raw: Record<string, unknown>): Row => {
53
+ const values: Record<string, unknown> = {};
54
+ for (const [k, v] of Object.entries(raw)) if (!SYSTEM_COLUMNS.has(k)) values[k] = v;
55
+ const changed = (raw["updatedAt"] ?? raw["createdAt"]) as string | null | undefined;
56
+ return {
57
+ id: String(raw["id"]),
58
+ isDeleted: raw["isDeleted"] === 1,
59
+ changedAt: changed ? Date.parse(changed) : 0,
60
+ values,
61
+ };
62
+ };
63
+
64
+ /** Opens Evolu databases for data secrets; the latest instance is exposed for the app. */
65
+ export const evoluDatabases = <S extends EvoluSchema>(options: EvoluDatabaseOptions<S>) => {
66
+ const schema = { ...options.schema, ...evolustrSchema } as WithEvolustr<S>;
67
+ const createQuery = createQueryBuilder(schema) as Loose;
68
+ const appTables = Object.keys(options.schema);
69
+ const appName = evoluAppName(options.appId);
70
+ let current: Evolu<WithEvolustr<S>> | null = null;
71
+
72
+ const open: OpenDatabase = async (s: Bytes) => {
73
+ const appOwner = createAppOwner(OwnerSecret.orThrow(s));
74
+ const evolu = await options.createEvolu({ schema, appOwner, appName });
75
+ current = evolu;
76
+ const e = evolu as Loose;
77
+
78
+ /**
79
+ * Settles when Evolu stored the change (#73): `onSuccess`, or `onError` when
80
+ * it couldn't (Evolu 8.28 renamed `onComplete`, which never ran then). The
81
+ * options are typed, so a rename fails the build despite `Loose`. A
82
+ * mutation that throws, such as one over `maxMutationSize`, rejects too.
83
+ */
84
+ const upsert = (table: string, values: Record<string, unknown>) =>
85
+ new Promise<void>((resolve, reject) => {
86
+ const options: MutationOptions = {
87
+ onSuccess: () => resolve(),
88
+ onError: (error) => reject(new Error(`Evolu could not store the change: ${String(error.error)}`)),
89
+ };
90
+ e.upsert(table, values, options);
91
+ });
92
+
93
+ const db: AppDatabase = {
94
+ sHash: sHash(s),
95
+ tables: appTables,
96
+ readRows: async (table) => {
97
+ const rows = (await e.loadQuery(createQuery((q: Loose) => q.selectFrom(table).selectAll()))) as ReadonlyArray<
98
+ Record<string, unknown>
99
+ >;
100
+ return rows.map(toRow);
101
+ },
102
+ upsertRows: async (table, rows) => {
103
+ await Promise.all(
104
+ rows.map((r) => upsert(table, { ...r.values, id: r.id, isDeleted: r.isDeleted ? 1 : 0 })),
105
+ );
106
+ },
107
+ getMeta: async (key) => {
108
+ const metaId = createIdFromString(key);
109
+ const rows = (await e.loadQuery(
110
+ createQuery((q: Loose) => q.selectFrom("evolustrMeta").select(["value"]).where("id", "=", metaId)),
111
+ )) as ReadonlyArray<{ value: string | null }>;
112
+ return rows[0]?.value ?? null;
113
+ },
114
+ setMeta: (key, value) => upsert("evolustrMeta", { id: createIdFromString(key), value }),
115
+ deleteLocal: async () => {
116
+ await e.deleteDatabase();
117
+ },
118
+ close: async () => {
119
+ await e[Symbol.asyncDispose]?.();
120
+ if (current === evolu) current = null;
121
+ },
122
+ };
123
+ return db;
124
+ };
125
+
126
+ return { open, current: () => current };
127
+ };
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./database.ts";
2
+ export * from "./cache.ts";
3
+ export * from "./evolu.ts";
4
+ export * from "./client.ts";
5
+ export * from "./settings.ts";
6
+ export * from "./capable.ts";
@@ -0,0 +1,55 @@
1
+ /** Shared settings event I/O (SPEC §9.1). */
2
+ import {
3
+ type EvolustrError,
4
+ type Relays,
5
+ type Result,
6
+ type SettingsDoc,
7
+ type Signer,
8
+ SETTINGS_DTAG,
9
+ VAULT_KIND,
10
+ emptySettings,
11
+ error,
12
+ fetchReplaceable,
13
+ ok,
14
+ parseSettings,
15
+ publishReplaceable,
16
+ } from "@evolustr/core";
17
+
18
+ export interface SettingsIo {
19
+ readonly signer: Signer;
20
+ readonly relays: Relays;
21
+ readonly relayUrls: ReadonlyArray<string>;
22
+ readonly timeoutMs: number;
23
+ /** See ClientOptions.relayQuorum. */
24
+ readonly relayQuorum?: number;
25
+ }
26
+
27
+ /**
28
+ * Fetches and decrypts the shared settings; an absent event is an empty
29
+ * document. `full` waits for every relay, before a write (#62).
30
+ */
31
+ export const fetchSharedSettings = async (io: SettingsIo, pubkey: string, full = false): Promise<Result<SettingsDoc, EvolustrError>> => {
32
+ const f = await fetchReplaceable(io.relays, io.relayUrls, { author: pubkey, kind: VAULT_KIND, d: SETTINGS_DTAG }, io.timeoutMs, full ? undefined : io.relayQuorum);
33
+ if (f.kind === "none") return ok(emptySettings);
34
+ if (f.kind === "incomplete") return error("relaysUnavailable", "Not every relay answered");
35
+ try {
36
+ return parseSettings(await io.signer.nip44Decrypt(pubkey, f.event.content));
37
+ } catch (e) {
38
+ return error("signerRefused", e instanceof Error ? e.message : String(e));
39
+ }
40
+ };
41
+
42
+ export const publishSharedSettings = async (
43
+ io: SettingsIo,
44
+ pubkey: string,
45
+ doc: SettingsDoc,
46
+ at: number,
47
+ ): Promise<Result<SettingsDoc, EvolustrError>> => {
48
+ try {
49
+ const content = await io.signer.nip44Encrypt(pubkey, JSON.stringify(doc));
50
+ await publishReplaceable(io.relays, io.relayUrls, io.signer, { kind: VAULT_KIND, created_at: at, tags: [["d", SETTINGS_DTAG]], content }, io.timeoutMs);
51
+ return ok(doc);
52
+ } catch (e) {
53
+ return error("publishFailed", e instanceof Error ? e.message : String(e));
54
+ }
55
+ };