tandem-kit-core 0.0.0 → 0.1.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -1
  3. package/dist/src/browser.d.ts +19 -0
  4. package/dist/src/browser.js +19 -0
  5. package/dist/src/client-tools.d.ts +31 -0
  6. package/dist/src/client-tools.js +82 -0
  7. package/dist/src/client.d.ts +179 -0
  8. package/dist/src/client.js +213 -0
  9. package/dist/src/delta.d.ts +16 -0
  10. package/dist/src/delta.js +99 -0
  11. package/dist/src/durable.d.ts +39 -0
  12. package/dist/src/durable.js +104 -0
  13. package/dist/src/errors.d.ts +5 -0
  14. package/dist/src/errors.js +10 -0
  15. package/dist/src/eventlog-file.d.ts +12 -0
  16. package/dist/src/eventlog-file.js +39 -0
  17. package/dist/src/eventlog.d.ts +31 -0
  18. package/dist/src/eventlog.js +63 -0
  19. package/dist/src/events.d.ts +15 -0
  20. package/dist/src/events.js +79 -0
  21. package/dist/src/events.json +80 -0
  22. package/dist/src/files.d.ts +34 -0
  23. package/dist/src/files.js +122 -0
  24. package/dist/src/fsutil.d.ts +8 -0
  25. package/dist/src/fsutil.js +68 -0
  26. package/dist/src/hash.d.ts +3 -0
  27. package/dist/src/hash.js +65 -0
  28. package/dist/src/images.d.ts +24 -0
  29. package/dist/src/images.js +70 -0
  30. package/dist/src/index.d.ts +25 -0
  31. package/dist/src/index.js +25 -0
  32. package/dist/src/json.d.ts +10 -0
  33. package/dist/src/json.js +68 -0
  34. package/dist/src/merge.d.ts +34 -0
  35. package/dist/src/merge.js +111 -0
  36. package/dist/src/persist.d.ts +49 -0
  37. package/dist/src/persist.js +29 -0
  38. package/dist/src/proposals-file.d.ts +12 -0
  39. package/dist/src/proposals-file.js +36 -0
  40. package/dist/src/proposals.d.ts +149 -0
  41. package/dist/src/proposals.js +296 -0
  42. package/dist/src/reconcile.d.ts +63 -0
  43. package/dist/src/reconcile.js +61 -0
  44. package/dist/src/replica.d.ts +147 -0
  45. package/dist/src/replica.js +320 -0
  46. package/dist/src/revisions-file.d.ts +14 -0
  47. package/dist/src/revisions-file.js +28 -0
  48. package/dist/src/revisions.d.ts +78 -0
  49. package/dist/src/revisions.js +152 -0
  50. package/dist/src/revisions.json +19 -0
  51. package/dist/src/schema.d.ts +12 -0
  52. package/dist/src/schema.js +49 -0
  53. package/dist/src/session-state.d.ts +36 -0
  54. package/dist/src/session-state.js +95 -0
  55. package/dist/src/sse.d.ts +17 -0
  56. package/dist/src/sse.js +59 -0
  57. package/dist/src/workcopy.d.ts +145 -0
  58. package/dist/src/workcopy.js +556 -0
  59. package/package.json +34 -4
@@ -0,0 +1,122 @@
1
+ import { isObject } from "./json.js";
2
+ export const DEFAULT_MAX_FILES = 64;
3
+ export const DEFAULT_MAX_FILE_CHARS = 200_000;
4
+ export const DEFAULT_MAX_TOTAL_CHARS = 1_000_000;
5
+ export function emptyFiles(files = {}) {
6
+ return { files: { ...files } };
7
+ }
8
+ export function filesOf(state) {
9
+ return isObject(state) && isObject(state.files) ? state.files : {};
10
+ }
11
+ /** why a path cannot be a file in the set, or null. Paths are relative, use `/`, and never climb out of the root or start a segment with a dot */
12
+ export function pathProblem(path) {
13
+ if (typeof path !== 'string' || !path)
14
+ return 'a path is required';
15
+ if (path.length > 200)
16
+ return 'the path is too long';
17
+ if (path.includes('\\'))
18
+ return 'use / in paths, not \\';
19
+ if (path.includes('\0'))
20
+ return 'the path has a control character';
21
+ if (path.startsWith('/') || /^[A-Za-z]:/.test(path))
22
+ return 'the path must be relative to the root';
23
+ const parts = path.split('/');
24
+ if (parts.some((part) => part === ''))
25
+ return 'the path has an empty segment';
26
+ if (parts.some((part) => part === '.' || part === '..'))
27
+ return 'the path may not use . or ..';
28
+ if (parts.some((part) => part.startsWith('.')))
29
+ return 'a path segment may not start with a dot';
30
+ return null;
31
+ }
32
+ const extensionOf = (path) => {
33
+ const name = path.slice(path.lastIndexOf('/') + 1);
34
+ const dot = name.lastIndexOf('.');
35
+ return dot <= 0 ? '' : name.slice(dot);
36
+ };
37
+ export function lineCount(text) {
38
+ return text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
39
+ }
40
+ const linesOf = (text) => (text === '' ? [] : (text.endsWith('\n') ? text.slice(0, -1) : text).split('\n'));
41
+ const LCS_CELLS = 250_000;
42
+ function stat(before, after) {
43
+ const a = linesOf(before);
44
+ const b = linesOf(after);
45
+ let head = 0;
46
+ while (head < a.length && head < b.length && a[head] === b[head])
47
+ head++;
48
+ let tail = 0;
49
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail])
50
+ tail++;
51
+ const x = a.slice(head, a.length - tail);
52
+ const y = b.slice(head, b.length - tail);
53
+ let common = 0;
54
+ if (x.length * y.length <= LCS_CELLS) {
55
+ let row = new Array(y.length + 1).fill(0);
56
+ for (const line of x) {
57
+ const next = [0];
58
+ for (let j = 0; j < y.length; j++)
59
+ next.push(line === y[j] ? row[j] + 1 : Math.max(row[j + 1], next[j]));
60
+ row = next;
61
+ }
62
+ common = row[y.length];
63
+ }
64
+ return `+${y.length - common} -${x.length - common}`;
65
+ }
66
+ export function summarizeFiles(before, after) {
67
+ const was = filesOf(before);
68
+ const now = filesOf(after);
69
+ const made = Object.keys(now).filter((path) => !(path in was));
70
+ const gone = Object.keys(was).filter((path) => !(path in now));
71
+ const edited = Object.keys(now).filter((path) => path in was && was[path] !== now[path]);
72
+ const parts = [];
73
+ if (made.length)
74
+ parts.push(`created ${made.join(', ')}`);
75
+ for (const path of edited)
76
+ parts.push(`edited ${path} (${stat(was[path], now[path])})`);
77
+ if (gone.length)
78
+ parts.push(`deleted ${gone.join(', ')}`);
79
+ return parts.join('; ') || 'no change to the files';
80
+ }
81
+ /** the adapter for a files document: checks paths, kinds and sizes, then the app's own `check`. Merges per file (two writers on different files never clash) */
82
+ export function filesAdapter(policy = {}) {
83
+ const maxFiles = policy.maxFiles ?? DEFAULT_MAX_FILES;
84
+ const maxFile = policy.maxFileChars ?? DEFAULT_MAX_FILE_CHARS;
85
+ const maxTotal = policy.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;
86
+ return {
87
+ validate(state, ctx) {
88
+ if (!isObject(state) || !isObject(state.files))
89
+ return [{ level: 'block', message: 'the document must look like { files: { path: text } }' }];
90
+ const files = state.files;
91
+ const findings = [];
92
+ const paths = Object.keys(files);
93
+ if (paths.length > maxFiles)
94
+ findings.push({ level: 'block', message: `at most ${maxFiles} files are allowed, there are ${paths.length}` });
95
+ let total = 0;
96
+ for (const path of paths) {
97
+ const at = ['files', path];
98
+ const content = files[path];
99
+ const bad = pathProblem(path) ?? (policy.extensions && !policy.extensions.includes(extensionOf(path)) ? `only ${policy.extensions.join(', ')} files are allowed` : null) ?? policy.allow?.(path) ?? null;
100
+ if (bad)
101
+ findings.push({ level: 'block', path: at, message: `${path}: ${bad}` });
102
+ if (typeof content !== 'string') {
103
+ findings.push({ level: 'block', path: at, message: `${path}: the content must be text` });
104
+ continue;
105
+ }
106
+ if (content.length > maxFile)
107
+ findings.push({ level: 'block', path: at, message: `${path}: ${content.length} characters is over the ${maxFile} limit` });
108
+ total += content.length;
109
+ for (const other of paths) {
110
+ if (other.startsWith(`${path}/`))
111
+ findings.push({ level: 'block', path: at, message: `${path} is a file here and a folder for ${other}` });
112
+ }
113
+ }
114
+ if (total > maxTotal)
115
+ findings.push({ level: 'block', message: `the files total ${total} characters, over the ${maxTotal} limit` });
116
+ if (findings.some((f) => f.level === 'block'))
117
+ return findings;
118
+ return [...findings, ...(policy.check?.(files, ctx) ?? [])];
119
+ },
120
+ summarize: summarizeFiles,
121
+ };
122
+ }
@@ -0,0 +1,8 @@
1
+ export interface FileOptions {
2
+ fsync?: boolean;
3
+ }
4
+ export declare function syncDirectory(dir: string): void;
5
+ export declare function writeFileAtomic(path: string, data: string | Uint8Array, options?: FileOptions): void;
6
+ export declare function removeStaleTemps(dir: string): number;
7
+ export declare function repairLines(path: string): void;
8
+ export declare function appendLine(path: string, line: string, options?: FileOptions): void;
@@ -0,0 +1,68 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, truncateSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ export function syncDirectory(dir) {
5
+ try {
6
+ const fd = openSync(dir, 'r');
7
+ try {
8
+ fsyncSync(fd);
9
+ }
10
+ finally {
11
+ closeSync(fd);
12
+ }
13
+ }
14
+ catch {
15
+ return;
16
+ }
17
+ }
18
+ export function writeFileAtomic(path, data, options = {}) {
19
+ const dir = dirname(path);
20
+ mkdirSync(dir, { recursive: true });
21
+ const temp = join(dir, `.${basename(path)}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
22
+ const fd = openSync(temp, 'w');
23
+ try {
24
+ writeFileSync(fd, data);
25
+ if (options.fsync ?? true)
26
+ fsyncSync(fd);
27
+ }
28
+ finally {
29
+ closeSync(fd);
30
+ }
31
+ renameSync(temp, path);
32
+ if (options.fsync ?? true)
33
+ syncDirectory(dir);
34
+ }
35
+ export function removeStaleTemps(dir) {
36
+ if (!existsSync(dir))
37
+ return 0;
38
+ let removed = 0;
39
+ for (const name of readdirSync(dir)) {
40
+ if (name.startsWith('.') && name.endsWith('.tmp')) {
41
+ rmSync(join(dir, name), { force: true });
42
+ removed++;
43
+ }
44
+ }
45
+ return removed;
46
+ }
47
+ export function repairLines(path) {
48
+ if (!existsSync(path))
49
+ return;
50
+ const text = readFileSync(path);
51
+ if (text.length === 0 || text[text.length - 1] === 0x0a)
52
+ return;
53
+ truncateSync(path, text.lastIndexOf(0x0a) + 1);
54
+ }
55
+ export function appendLine(path, line, options = {}) {
56
+ if (!options.fsync) {
57
+ appendFileSync(path, `${line}\n`);
58
+ return;
59
+ }
60
+ const fd = openSync(path, 'a');
61
+ try {
62
+ writeFileSync(fd, `${line}\n`);
63
+ fsyncSync(fd);
64
+ }
65
+ finally {
66
+ closeSync(fd);
67
+ }
68
+ }
@@ -0,0 +1,3 @@
1
+ import { type Json } from './json.js';
2
+ export declare function canonicalJson(value: Json | undefined): string;
3
+ export declare function sha256Hex(text: string): string;
@@ -0,0 +1,65 @@
1
+ import { isObject } from "./json.js";
2
+ export function canonicalJson(value) {
3
+ if (value === undefined)
4
+ return 'null';
5
+ if (Array.isArray(value))
6
+ return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
7
+ if (isObject(value)) {
8
+ const keys = Object.keys(value).sort();
9
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
10
+ }
11
+ return JSON.stringify(value);
12
+ }
13
+ const K = new Uint32Array([
14
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
15
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
16
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
17
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
18
+ ]);
19
+ export function sha256Hex(text) {
20
+ const data = new TextEncoder().encode(text);
21
+ const padded = new Uint8Array((((data.length + 9 + 63) >> 6) << 6));
22
+ padded.set(data);
23
+ padded[data.length] = 0x80;
24
+ const view = new DataView(padded.buffer);
25
+ view.setUint32(padded.length - 8, Math.floor((data.length * 8) / 0x100000000));
26
+ view.setUint32(padded.length - 4, (data.length * 8) >>> 0);
27
+ const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
28
+ const w = new Uint32Array(64);
29
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
30
+ for (let offset = 0; offset < padded.length; offset += 64) {
31
+ for (let i = 0; i < 16; i++)
32
+ w[i] = view.getUint32(offset + i * 4);
33
+ for (let i = 16; i < 64; i++) {
34
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
35
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
36
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
37
+ }
38
+ let [a, b, c, d, e, f, g, hh] = h;
39
+ for (let i = 0; i < 64; i++) {
40
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
41
+ const ch = (e & f) ^ (~e & g);
42
+ const t1 = (hh + s1 + ch + K[i] + w[i]) >>> 0;
43
+ const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
44
+ const maj = (a & b) ^ (a & c) ^ (b & c);
45
+ const t2 = (s0 + maj) >>> 0;
46
+ hh = g;
47
+ g = f;
48
+ f = e;
49
+ e = (d + t1) >>> 0;
50
+ d = c;
51
+ c = b;
52
+ b = a;
53
+ a = (t1 + t2) >>> 0;
54
+ }
55
+ h[0] = (h[0] + a) >>> 0;
56
+ h[1] = (h[1] + b) >>> 0;
57
+ h[2] = (h[2] + c) >>> 0;
58
+ h[3] = (h[3] + d) >>> 0;
59
+ h[4] = (h[4] + e) >>> 0;
60
+ h[5] = (h[5] + f) >>> 0;
61
+ h[6] = (h[6] + g) >>> 0;
62
+ h[7] = (h[7] + hh) >>> 0;
63
+ }
64
+ return Array.from(h, (n) => n.toString(16).padStart(8, '0')).join('');
65
+ }
@@ -0,0 +1,24 @@
1
+ export declare const MAX_IMAGES = 8;
2
+ export type ImageSource = {
3
+ data: string;
4
+ } | {
5
+ url: string;
6
+ } | {
7
+ path: string;
8
+ };
9
+ export type ImagePart = ImageSource & {
10
+ media_type?: string;
11
+ name?: string;
12
+ };
13
+ /** the parts of a send/message `images` field, checked and reduced to the known keys; absent or null means none */
14
+ export declare function validateImages(value: unknown, max?: number): ImagePart[];
15
+ export interface ImageSummary {
16
+ media_type?: string;
17
+ name?: string;
18
+ url?: string;
19
+ path?: string;
20
+ bytes?: number;
21
+ }
22
+ /** what the event log keeps of an image: where it came from and how big, never the bytes */
23
+ export declare function summarizeImage(part: ImagePart): ImageSummary;
24
+ export declare function imageTypeOf(name: string): string | undefined;
@@ -0,0 +1,70 @@
1
+ import { TandemError } from "./errors.js";
2
+ export const MAX_IMAGES = 8;
3
+ const MEDIA_TYPE = /^image\/[A-Za-z0-9][A-Za-z0-9.+-]*$/;
4
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
5
+ const SOURCES = ['data', 'url', 'path'];
6
+ const bad = (index, message) => new TandemError(400, 'bad_request', `images[${index}]: ${message}`);
7
+ const isUrl = (value) => {
8
+ try {
9
+ const url = new URL(value);
10
+ return url.protocol === 'http:' || url.protocol === 'https:';
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ };
16
+ /** the parts of a send/message `images` field, checked and reduced to the known keys; absent or null means none */
17
+ export function validateImages(value, max = MAX_IMAGES) {
18
+ if (value === undefined || value === null)
19
+ return [];
20
+ if (!Array.isArray(value))
21
+ throw new TandemError(400, 'bad_request', 'images must be an array');
22
+ if (value.length > max)
23
+ throw new TandemError(400, 'bad_request', `at most ${max} images per message`);
24
+ return value.map((raw, index) => {
25
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
26
+ throw bad(index, 'must be an object');
27
+ const given = SOURCES.filter((key) => raw[key] !== undefined);
28
+ if (given.length !== 1)
29
+ throw bad(index, 'give exactly one of data, url or path');
30
+ const kind = given[0];
31
+ const source = raw[kind];
32
+ if (typeof source !== 'string' || !source)
33
+ throw bad(index, `${kind} must be a non-empty string`);
34
+ const { media_type: mediaType, name } = raw;
35
+ if (mediaType !== undefined && (typeof mediaType !== 'string' || !MEDIA_TYPE.test(mediaType)))
36
+ throw bad(index, 'media_type must look like image/png');
37
+ if (name !== undefined && (typeof name !== 'string' || name.length > 255))
38
+ throw bad(index, 'name must be a string of at most 255 characters');
39
+ if (kind === 'data') {
40
+ if (mediaType === undefined)
41
+ throw bad(index, 'media_type is required with data');
42
+ if (!BASE64.test(source) || source.length % 4 !== 0)
43
+ throw bad(index, 'data must be base64');
44
+ }
45
+ else if (kind === 'url' && !isUrl(source))
46
+ throw bad(index, 'url must be an absolute http or https url');
47
+ else if (kind === 'path' && source.includes('\0'))
48
+ throw bad(index, 'path is not valid');
49
+ return { ...(mediaType === undefined ? {} : { media_type: mediaType }), ...(name === undefined ? {} : { name }), [kind]: source };
50
+ });
51
+ }
52
+ /** what the event log keeps of an image: where it came from and how big, never the bytes */
53
+ export function summarizeImage(part) {
54
+ const out = {};
55
+ if (part.media_type)
56
+ out.media_type = part.media_type;
57
+ if (part.name)
58
+ out.name = part.name;
59
+ if ('url' in part)
60
+ out.url = part.url;
61
+ if ('path' in part)
62
+ out.path = part.path;
63
+ if ('data' in part)
64
+ out.bytes = Math.floor((part.data.length * 3) / 4) - (part.data.endsWith('==') ? 2 : part.data.endsWith('=') ? 1 : 0);
65
+ return out;
66
+ }
67
+ const TYPES = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp', svg: 'image/svg+xml', avif: 'image/avif', heic: 'image/heic', tif: 'image/tiff', tiff: 'image/tiff' };
68
+ export function imageTypeOf(name) {
69
+ return TYPES[name.slice(name.lastIndexOf('.') + 1).toLowerCase()];
70
+ }
@@ -0,0 +1,25 @@
1
+ export * from './client.js';
2
+ export * from './client-tools.js';
3
+ export * from './delta.js';
4
+ export * from './durable.js';
5
+ export * from './errors.js';
6
+ export * from './eventlog.js';
7
+ export * from './eventlog-file.js';
8
+ export * from './events.js';
9
+ export * from './files.js';
10
+ export * from './fsutil.js';
11
+ export * from './hash.js';
12
+ export * from './images.js';
13
+ export * from './json.js';
14
+ export * from './merge.js';
15
+ export * from './persist.js';
16
+ export * from './proposals.js';
17
+ export * from './proposals-file.js';
18
+ export * from './reconcile.js';
19
+ export * from './replica.js';
20
+ export * from './revisions.js';
21
+ export * from './revisions-file.js';
22
+ export * from './schema.js';
23
+ export * from './sse.js';
24
+ export * from './workcopy.js';
25
+ export * from './session-state.js';
@@ -0,0 +1,25 @@
1
+ export * from "./client.js";
2
+ export * from "./client-tools.js";
3
+ export * from "./delta.js";
4
+ export * from "./durable.js";
5
+ export * from "./errors.js";
6
+ export * from "./eventlog.js";
7
+ export * from "./eventlog-file.js";
8
+ export * from "./events.js";
9
+ export * from "./files.js";
10
+ export * from "./fsutil.js";
11
+ export * from "./hash.js";
12
+ export * from "./images.js";
13
+ export * from "./json.js";
14
+ export * from "./merge.js";
15
+ export * from "./persist.js";
16
+ export * from "./proposals.js";
17
+ export * from "./proposals-file.js";
18
+ export * from "./reconcile.js";
19
+ export * from "./replica.js";
20
+ export * from "./revisions.js";
21
+ export * from "./revisions-file.js";
22
+ export * from "./schema.js";
23
+ export * from "./sse.js";
24
+ export * from "./workcopy.js";
25
+ export * from "./session-state.js";
@@ -0,0 +1,10 @@
1
+ export type Json = null | boolean | number | string | Json[] | {
2
+ [key: string]: Json;
3
+ };
4
+ export type JsonObject = {
5
+ [key: string]: Json;
6
+ };
7
+ export declare function isObject(value: unknown): value is JsonObject;
8
+ export declare function equal(a: unknown, b: unknown): boolean;
9
+ export declare function clone<T>(value: T): T;
10
+ export declare function clip(text: string, max: number): string;
@@ -0,0 +1,68 @@
1
+ export function isObject(value) {
2
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ }
4
+ export function equal(a, b) {
5
+ if (a === b)
6
+ return true;
7
+ if (Array.isArray(a)) {
8
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => equal(item, b[i]));
9
+ }
10
+ if (isObject(a)) {
11
+ if (!isObject(b))
12
+ return false;
13
+ const keys = Object.keys(a);
14
+ return keys.length === Object.keys(b).length && keys.every((k) => k in b && equal(a[k], b[k]));
15
+ }
16
+ return false;
17
+ }
18
+ const viaJson = (value) => {
19
+ const text = JSON.stringify(value);
20
+ return text === undefined ? undefined : JSON.parse(text);
21
+ };
22
+ function copy(value) {
23
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
24
+ return value;
25
+ if (typeof value === 'number')
26
+ return Number.isFinite(value) ? (value === 0 ? 0 : value) : null;
27
+ if (Array.isArray(value)) {
28
+ const out = new Array(value.length);
29
+ for (let i = 0; i < value.length; i++) {
30
+ const item = copy(value[i]);
31
+ out[i] = item === undefined ? null : item;
32
+ }
33
+ return out;
34
+ }
35
+ if (typeof value === 'bigint')
36
+ return viaJson(value);
37
+ if (typeof value !== 'object')
38
+ return undefined;
39
+ const proto = Object.getPrototypeOf(value);
40
+ if (proto !== Object.prototype && proto !== null)
41
+ return viaJson(value);
42
+ const source = value;
43
+ if (typeof source.toJSON === 'function')
44
+ return viaJson(value);
45
+ const out = {};
46
+ for (const key of Object.keys(source)) {
47
+ const item = copy(source[key]);
48
+ if (item === undefined)
49
+ continue;
50
+ if (key === '__proto__')
51
+ Object.defineProperty(out, key, { value: item, enumerable: true, writable: true, configurable: true });
52
+ else
53
+ out[key] = item;
54
+ }
55
+ return out;
56
+ }
57
+ // a deep copy with the same result as a round trip through JSON (undefined members drop, undefined array items become null,
58
+ // non-finite numbers become null), without writing and parsing the text
59
+ export function clone(value) {
60
+ if (value === undefined)
61
+ return value;
62
+ if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint')
63
+ return viaJson(value);
64
+ return copy(value);
65
+ }
66
+ export function clip(text, max) {
67
+ return text.length <= max ? text : `${text.slice(0, max)}\n[${text.length - max} more characters]`;
68
+ }
@@ -0,0 +1,34 @@
1
+ import { type Delta, type Path } from './delta.js';
2
+ import { type Json } from './json.js';
3
+ export interface Clash {
4
+ path: Path;
5
+ base: Json | undefined;
6
+ mine: Json | undefined;
7
+ theirs: Json | undefined;
8
+ }
9
+ export type KeyFunction = (item: Json) => string | number | undefined;
10
+ export type KeyRule = string | {
11
+ field: string;
12
+ } | {
13
+ set: true;
14
+ } | KeyFunction;
15
+ export interface MergeOptions {
16
+ keyed?: Record<string, KeyRule>;
17
+ }
18
+ export interface MergeResult {
19
+ merged: Json;
20
+ clashes: Clash[];
21
+ }
22
+ export declare function patternFor(path: Path, keyed: Record<string, KeyRule>): KeyRule | undefined;
23
+ export declare function keyOf(rule: KeyRule, item: Json): string | undefined;
24
+ export declare function merge3(base: Json, mine: Json, theirs: Json, options?: MergeOptions): MergeResult;
25
+ export declare function concretePath(state: Json, path: Path, keyed?: Record<string, KeyRule>): Path;
26
+ export interface ClashSides {
27
+ path: Path;
28
+ dropped: Json | null;
29
+ }
30
+ export declare function clashDelta(state: Json, clash: ClashSides, keyed?: Record<string, KeyRule>): Delta;
31
+ export declare function resolveClash(state: Json, clash: ClashSides, choice: 'kept' | 'dropped', keyed?: Record<string, KeyRule>): {
32
+ delta: Delta;
33
+ state: Json;
34
+ };
@@ -0,0 +1,111 @@
1
+ import { apply } from "./delta.js";
2
+ import { TandemError } from "./errors.js";
3
+ import { canonicalJson } from "./hash.js";
4
+ import { equal, isObject } from "./json.js";
5
+ export function patternFor(path, keyed) {
6
+ const text = path.map(String);
7
+ for (const pattern of Object.keys(keyed)) {
8
+ const parts = pattern.split('.');
9
+ if (parts.length === text.length && parts.every((part, i) => part === '*' || part === text[i]))
10
+ return keyed[pattern];
11
+ }
12
+ return undefined;
13
+ }
14
+ export function keyOf(rule, item) {
15
+ if (typeof rule === 'function') {
16
+ const id = rule(item);
17
+ return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;
18
+ }
19
+ if (typeof rule === 'object' && 'set' in rule)
20
+ return typeof item === 'string' ? item : canonicalJson(item);
21
+ const field = typeof rule === 'string' ? rule : rule.field;
22
+ if (!isObject(item))
23
+ return undefined;
24
+ const id = item[field];
25
+ return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;
26
+ }
27
+ function indexByKey(items, rule) {
28
+ const map = new Map();
29
+ for (const item of items) {
30
+ const id = keyOf(rule, item);
31
+ if (id === undefined || map.has(id))
32
+ return undefined;
33
+ map.set(id, item);
34
+ }
35
+ return map;
36
+ }
37
+ export function merge3(base, mine, theirs, options = {}) {
38
+ const clashes = [];
39
+ const keyed = options.keyed ?? {};
40
+ const walk = (b, m, t, path) => {
41
+ if (equal(m, t))
42
+ return m;
43
+ if (equal(b, m))
44
+ return t;
45
+ if (equal(b, t))
46
+ return m;
47
+ if (isObject(m) && isObject(t)) {
48
+ const baseObject = isObject(b) ? b : {};
49
+ const out = {};
50
+ const keys = [...new Set([...Object.keys(m), ...Object.keys(t), ...Object.keys(baseObject)])];
51
+ for (const key of keys) {
52
+ const merged = walk(baseObject[key], m[key], t[key], [...path, key]);
53
+ if (merged !== undefined)
54
+ out[key] = merged;
55
+ }
56
+ return out;
57
+ }
58
+ const rule = Array.isArray(m) && Array.isArray(t) ? patternFor(path, keyed) : undefined;
59
+ if (rule && Array.isArray(m) && Array.isArray(t)) {
60
+ const mi = indexByKey(m, rule);
61
+ const ti = indexByKey(t, rule);
62
+ const bi = b === undefined ? new Map() : Array.isArray(b) ? indexByKey(b, rule) : undefined;
63
+ if (mi && ti && bi) {
64
+ const ids = [...new Set([...mi.keys(), ...ti.keys()])];
65
+ const items = [];
66
+ for (const id of ids) {
67
+ const merged = walk(bi.get(id), mi.get(id), ti.get(id), [...path, id]);
68
+ if (merged !== undefined)
69
+ items.push(merged);
70
+ }
71
+ return items;
72
+ }
73
+ }
74
+ clashes.push({ path, base: b, mine: m, theirs: t });
75
+ return m;
76
+ };
77
+ const merged = walk(base, mine, theirs, []);
78
+ return { merged: merged, clashes };
79
+ }
80
+ export function concretePath(state, path, keyed = {}) {
81
+ const out = [];
82
+ let node = state;
83
+ for (let i = 0; i < path.length; i++) {
84
+ const key = path[i];
85
+ if (Array.isArray(node) && typeof key === 'string') {
86
+ const rule = patternFor(path.slice(0, i), keyed);
87
+ let index = rule ? node.findIndex((item) => keyOf(rule, item) === key) : -1;
88
+ if (index === -1)
89
+ index = node.length;
90
+ out.push(index);
91
+ node = node[index];
92
+ }
93
+ else {
94
+ out.push(key);
95
+ node = Array.isArray(node) ? node[Number(key)] : isObject(node) ? node[String(key)] : undefined;
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+ export function clashDelta(state, clash, keyed = {}) {
101
+ const path = concretePath(state, clash.path, keyed);
102
+ return clash.dropped === null ? [{ op: 'delete', path }] : [{ op: 'set', path, value: clash.dropped }];
103
+ }
104
+ export function resolveClash(state, clash, choice, keyed = {}) {
105
+ if (choice !== 'kept' && choice !== 'dropped')
106
+ throw new TandemError(400, 'bad_request', 'choice must be "kept" or "dropped"');
107
+ if (choice === 'kept')
108
+ return { delta: [], state };
109
+ const delta = clashDelta(state, clash, keyed);
110
+ return { delta, state: apply(state, delta) };
111
+ }