@myfield/sdk 0.9.2 → 0.9.3

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/src/index.ts DELETED
@@ -1,29 +0,0 @@
1
- // @myfield/sdk — Myfield open SDK.
2
- //
3
- // The mental model for apps: a bucket is a local-first end-to-end-encrypted
4
- // object KV with CAS-backed sync. Local CRUD needs no account and no
5
- // network; connect() is the single network/identity boundary. The cloud is
6
- // a sync relay, not a backup — objects may be missing in cloud (old data
7
- // rotates out), uploads may transiently fail (rate limits), and local
8
- // storage is the source of truth. See docs/API.md.
9
-
10
- export {
11
- createInstance,
12
- type Bucket,
13
- type BinaryInput,
14
- type BinaryOptions,
15
- type BucketBinaryValue,
16
- type BucketState,
17
- type ConnectOptions,
18
- type CreateInstanceOptions,
19
- type Instance,
20
- type ListEntry,
21
- } from "./facade.ts";
22
- export { NotConnectedError } from "./errors.ts";
23
- export { OfflineError } from "./bucket/transport.ts";
24
- export type { RemoteBucket, BucketKey, VersionMeta, CurrentVersion, ObjectVersion, CommitInput, CommitResult,
25
- PageOptions, VersionHistory, FeedHint, FeedPage, BucketIndex } from "./remote/bucket.ts";
26
- export type { RequestOptions } from "./remote/http.ts";
27
- export { ClientError } from "./errors.ts";
28
- export type { ClientErrorOptions } from "./errors.ts";
29
- export type { InstanceKey } from "./auth/keys.ts";
@@ -1,95 +0,0 @@
1
- const B64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2
- const B64URL_DECODE = new Map([...B64URL_ALPHABET].map((char, index) => [char, index]));
3
-
4
- export function bytesToB64url(bytes: Uint8Array): string {
5
- let out = "";
6
- for (let i = 0; i < bytes.length; i += 3) {
7
- const a = bytes[i] ?? 0;
8
- const b = bytes[i + 1] ?? 0;
9
- const c = bytes[i + 2] ?? 0;
10
- const triple = (a << 16) | (b << 8) | c;
11
- out += B64URL_ALPHABET[(triple >> 18) & 63];
12
- out += B64URL_ALPHABET[(triple >> 12) & 63];
13
- if (i + 1 < bytes.length) out += B64URL_ALPHABET[(triple >> 6) & 63];
14
- if (i + 2 < bytes.length) out += B64URL_ALPHABET[triple & 63];
15
- }
16
- return out;
17
- }
18
-
19
- export function b64urlToBytes(value: string): Uint8Array {
20
- const safe = String(value || "").trim().replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
21
- if (safe.length % 4 === 1) throw new Error("invalid base64url length");
22
- const out: number[] = [];
23
- for (let i = 0; i < safe.length; i += 4) {
24
- const chunk = safe.slice(i, i + 4);
25
- const values = [...chunk].map((char) => {
26
- const decoded = B64URL_DECODE.get(char);
27
- if (decoded === undefined) throw new Error("invalid base64url character");
28
- return decoded;
29
- });
30
- const a = values[0] ?? 0;
31
- const b = values[1] ?? 0;
32
- const c = values[2] ?? 0;
33
- const d = values[3] ?? 0;
34
- const triple = (a << 18) | (b << 12) | (c << 6) | d;
35
- out.push((triple >> 16) & 255);
36
- if (values.length > 2) out.push((triple >> 8) & 255);
37
- if (values.length > 3) out.push(triple & 255);
38
- }
39
- return new Uint8Array(out);
40
- }
41
-
42
- export function bytesToHex(bytes: Uint8Array): string {
43
- return Array.from(bytes)
44
- .map((b) => b.toString(16).padStart(2, "0"))
45
- .join("");
46
- }
47
-
48
- export function utf8Encode(value: string): Uint8Array {
49
- return new TextEncoder().encode(value);
50
- }
51
-
52
- export function utf8Decode(bytes: Uint8Array): string {
53
- return new TextDecoder().decode(bytes);
54
- }
55
-
56
- export function randomId(prefix: string, byteLength = 16): string {
57
- return `${prefix}_${bytesToHex(crypto.getRandomValues(new Uint8Array(byteLength)))}`;
58
- }
59
-
60
- export async function sha256Hex(input: string | Uint8Array): Promise<string> {
61
- const bytes = typeof input === "string" ? utf8Encode(input) : input;
62
- const digest = await crypto.subtle.digest("SHA-256", bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer);
63
- return bytesToHex(new Uint8Array(digest));
64
- }
65
-
66
- export function fnv1a32Bytes(bytes: Uint8Array): string {
67
- let hash = 2166136261;
68
- for (let i = 0; i < bytes.length; i += 1) {
69
- hash ^= bytes[i] as number;
70
- hash = Math.imul(hash, 16777619) >>> 0;
71
- }
72
- return hash.toString(16).padStart(8, "0");
73
- }
74
-
75
- export function stableStringify(value: unknown): string {
76
- return JSON.stringify(sortJson(value));
77
- }
78
-
79
- function sortJson(value: unknown): unknown {
80
- if (Array.isArray(value)) return value.map(sortJson);
81
- if (!value || typeof value !== "object") return value;
82
- return Object.fromEntries(
83
- Object.entries(value as Record<string, unknown>)
84
- .sort(([a], [b]) => a.localeCompare(b))
85
- .map(([key, item]) => [key, sortJson(item)])
86
- );
87
- }
88
-
89
- export function normalizeIsoDateTime(value: unknown): string | null {
90
- if (typeof value !== "string") return null;
91
- const safe = value.trim();
92
- if (!safe) return null;
93
- const date = new Date(/Z|[+-]\d{2}:\d{2}$/.test(safe) ? safe : `${safe}Z`);
94
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
95
- }
@@ -1,180 +0,0 @@
1
- import { ClientError } from "../errors.ts";
2
- import { bytesToB64url, utf8Encode } from "../internal/encoding.ts";
3
- import { invalidResponse, readJson, isRecord, requireString, type RemoteRequest, type RequestOptions } from "./http.ts";
4
- import { openFeedStream, isFeedHint, type FeedHint } from "./feed.ts";
5
- export type { FeedHint } from "./feed.ts";
6
-
7
- export type VersionMeta = {
8
- objectId: string;
9
- versionId: string;
10
- parentVersionIds: string[];
11
- payloadHash?: string;
12
- [field: string]: unknown;
13
- };
14
-
15
- export type CurrentVersion = {
16
- versionId: string;
17
- headVersionMeta: VersionMeta;
18
- history?: string[] | null;
19
- [field: string]: unknown;
20
- };
21
-
22
- export type ObjectVersion<TPayload = Response> = { meta: VersionMeta; payload: TPayload };
23
- export type CommitInput = { meta: VersionMeta; payload: Blob | Uint8Array; expectedHeadVersionId: string | null };
24
- export type CommitResult = { ok: true } | { ok: false; reason: "version-mismatch" | "conflict" };
25
- export type PageOptions = RequestOptions & { cursor?: string | null; limit?: number };
26
- export type VersionHistory = VersionMeta & { history: string[]; nextCursor: string | null };
27
- export type FeedPage = { entries: FeedHint[]; cursor: string; hasMore: boolean; [field: string]: unknown };
28
- export type BucketIndex = { bucketId: string; objects: FeedHint[]; feedCursor: string | null; hasMoreFeed: boolean; [field: string]: unknown };
29
-
30
- export type BucketKey = { bucketId: string; keyId: string; cryptoKey: CryptoKey };
31
-
32
- export interface RemoteBucket {
33
- getBucketKey(options?: RequestOptions): Promise<BucketKey>;
34
- getCurrent(objectId: string, options?: RequestOptions & { knownVersionId?: string | null }): Promise<CurrentVersion | null>;
35
- getVersion(objectId: string, versionId: string, options?: RequestOptions): Promise<ObjectVersion>;
36
- getVersionMeta(objectId: string, versionId: string, options?: RequestOptions): Promise<VersionMeta>;
37
- getPayload(objectId: string, versionId: string, options?: RequestOptions): Promise<Response>;
38
- commit(input: CommitInput, options?: RequestOptions): Promise<CommitResult>;
39
- listVersions(objectId: string, versionId: string, options?: PageOptions): Promise<VersionHistory>;
40
- getIndex(options?: RequestOptions): Promise<BucketIndex>;
41
- listFeed(options?: PageOptions): Promise<FeedPage>;
42
- watchFeed(options?: RequestOptions): Promise<AsyncGenerator<FeedHint>>;
43
- }
44
-
45
- export type RemoteBucketClient = Omit<RemoteBucket, "getBucketKey">;
46
-
47
- function isHistory(value: unknown): value is string[] {
48
- return Array.isArray(value) && value.every(id => typeof id === "string" && id.length > 0)
49
- && new Set(value).size === value.length;
50
- }
51
-
52
- function pageQuery(options: PageOptions): URLSearchParams {
53
- const query = new URLSearchParams();
54
- if (options.cursor != null) {
55
- if (typeof options.cursor !== "string") throw new ClientError("INVALID_INPUT", "cursor must be a string or null");
56
- if (options.cursor) query.set("cursor", options.cursor);
57
- }
58
- if (options.limit !== undefined) {
59
- if (!Number.isInteger(options.limit) || options.limit < 1) throw new ClientError("INVALID_INPUT", "limit must be a positive integer");
60
- query.set("limit", String(options.limit));
61
- }
62
- return query;
63
- }
64
-
65
- function isVersionMeta(value: unknown, objectId: string, versionId?: string): value is VersionMeta {
66
- return isRecord(value) && value.objectId === objectId
67
- && typeof value.versionId === "string" && value.versionId.length > 0
68
- && (versionId === undefined || value.versionId === versionId)
69
- && Array.isArray(value.parentVersionIds)
70
- && value.parentVersionIds.every(id => typeof id === "string" && id.length > 0);
71
- }
72
-
73
- function segment(id: string): string {
74
- requireString(id, "ID");
75
- if (id === "." || id === "..") throw new ClientError("INVALID_INPUT", "Dot segments cannot be requested");
76
- return encodeURIComponent(id);
77
- }
78
-
79
- function writableId(id: string): void {
80
- requireString(id, "ID");
81
- if (id === "." || id.includes("..")) throw new ClientError("INVALID_INPUT", "Dot-segment IDs cannot be committed");
82
- }
83
-
84
- export function createBucketClient(request: RemoteRequest, bucketId: string): RemoteBucketClient {
85
- const root = `/v1/api/sync/buckets/${segment(bucketId)}`;
86
- const objectPath = (id: string) => `${root}/objects/${segment(id)}`;
87
- const versionPath = (id: string, versionId: string) => `${objectPath(id)}/versions/${segment(versionId)}`;
88
- async function json(path: string, options: RequestOptions) {
89
- const response = await request(path, { signal: options.signal });
90
- return { response, body: await readJson(response, options.signal) };
91
- }
92
- async function getVersionMeta(objectId: string, versionId: string, options: RequestOptions = {}): Promise<VersionMeta> {
93
- const { response, body } = await json(`${versionPath(objectId, versionId)}/meta`, options);
94
- if (!isVersionMeta(body, objectId, versionId)) throw invalidResponse(response);
95
- return body;
96
- }
97
- return {
98
- async getCurrent(objectId, options = {}) {
99
- const query = new URLSearchParams({ miss: "null" });
100
- if (options.knownVersionId != null) { requireString(options.knownVersionId, "knownVersionId"); query.set("have", options.knownVersionId); }
101
- const { response, body } = await json(`${objectPath(objectId)}/current?${query}`, options);
102
- if (body.versionId === null && body.headVersionMeta === null) return null;
103
- if (typeof body.versionId !== "string" || !isVersionMeta(body.headVersionMeta, objectId, body.versionId)) throw invalidResponse(response);
104
- if (options.knownVersionId != null && !Object.hasOwn(body, "history")) throw invalidResponse(response, "Missing history evidence");
105
- if (Object.hasOwn(body, "history") && body.history !== null) {
106
- if (!isHistory(body.history)) throw invalidResponse(response);
107
- if (body.history.length && (body.history[0] !== body.versionId
108
- || (options.knownVersionId != null && body.history.at(-1) !== options.knownVersionId))) throw invalidResponse(response);
109
- }
110
- return body as CurrentVersion;
111
- },
112
- getVersionMeta,
113
- async listVersions(objectId, versionId, options = {}) {
114
- const query = pageQuery(options);
115
- query.set("history", "full");
116
- const { response, body } = await json(`${versionPath(objectId, versionId)}/meta?${query}`, options);
117
- if (!isVersionMeta(body, objectId, versionId) || !isHistory(body.history)
118
- || (!query.has("cursor") && body.history[0] !== versionId)
119
- || !(body.nextCursor === null || (typeof body.nextCursor === "string" && body.nextCursor.length > 0))) throw invalidResponse(response);
120
- return body as VersionHistory;
121
- },
122
- async getIndex(options = {}) {
123
- const { response, body } = await json(`${root}/objects:index`, options);
124
- if (body.bucketId !== bucketId || !Array.isArray(body.objects) || !body.objects.every(isFeedHint)
125
- || !(body.feedCursor === null || typeof body.feedCursor === "string")
126
- || typeof body.hasMoreFeed !== "boolean") throw invalidResponse(response);
127
- return body as BucketIndex;
128
- },
129
- async listFeed(options = {}) {
130
- const query = pageQuery(options);
131
- const { response, body } = await json(`${root}/feed${query.size ? `?${query}` : ""}`, options);
132
- if (!Array.isArray(body.entries) || !body.entries.every(isFeedHint)
133
- || typeof body.cursor !== "string" || typeof body.hasMore !== "boolean") throw invalidResponse(response);
134
- return body as FeedPage;
135
- },
136
- async watchFeed(options = {}) {
137
- const response = await request(`${root}/feed/stream`, { headers: { accept: "text/event-stream" }, signal: options.signal });
138
- return openFeedStream(response, options.signal);
139
- },
140
- async getPayload(objectId, versionId, options = {}) {
141
- return request(`${versionPath(objectId, versionId)}/payload`, { signal: options.signal });
142
- },
143
- async getVersion(objectId, versionId, options = {}) {
144
- const path = versionPath(objectId, versionId);
145
- let payload: Response | undefined;
146
- let failed = false;
147
- const download = request(`${path}/payload`, { signal: options.signal }).then(response => {
148
- if (failed) void response.body?.cancel().catch(() => {});
149
- else payload = response;
150
- return response;
151
- });
152
- try {
153
- const [meta, response] = await Promise.all([getVersionMeta(objectId, versionId, options), download]);
154
- return { meta, payload: response };
155
- } catch (error) {
156
- failed = true;
157
- void payload?.body?.cancel().catch(() => {});
158
- throw error;
159
- }
160
- },
161
- async commit(input, options = {}) {
162
- if (!isRecord(input) || !isRecord(input.meta)) throw new ClientError("INVALID_INPUT", "Commit metadata is required");
163
- if (input.expectedHeadVersionId !== null) requireString(input.expectedHeadVersionId, "expectedHeadVersionId");
164
- writableId(input.meta.objectId);
165
- writableId(input.meta.versionId);
166
- if (!(input.payload instanceof Blob) && !(input.payload instanceof Uint8Array)) throw new ClientError("INVALID_INPUT", "Payload must be a Blob or Uint8Array");
167
- let headers: Headers;
168
- try {
169
- headers = new Headers({ "content-type": "application/octet-stream",
170
- "x-myfield-version-meta": bytesToB64url(utf8Encode(JSON.stringify(input.meta))) });
171
- if (input.expectedHeadVersionId !== null) headers.set("x-myfield-expected-head-version-id", input.expectedHeadVersionId);
172
- } catch (cause) { throw new ClientError("INVALID_INPUT", "Invalid commit metadata or CAS header", { cause }); }
173
- const response = await request(objectPath(input.meta.objectId), { method: "POST", headers, body: input.payload as BodyInit, signal: options.signal });
174
- const body = await readJson(response, options.signal);
175
- if (body.ok === true) return body as CommitResult;
176
- if (body.ok === false && (body.reason === "version-mismatch" || body.reason === "conflict")) return body as CommitResult;
177
- throw invalidResponse(response, "Invalid commit result");
178
- },
179
- };
180
- }
@@ -1,38 +0,0 @@
1
- import { ClientError } from "../errors.ts";
2
- import { createBucketClient, type RemoteBucketClient } from "./bucket.ts";
3
- import { createHttpRequest, isRecord, requireString, type RemoteRequest } from "./http.ts";
4
-
5
- export type RemoteClientOptions = {
6
- apiBase: string;
7
- mfid: string;
8
- bucketId: string;
9
- getCredential(): { token: string } | Promise<{ token: string }>;
10
- fetch?: typeof globalThis.fetch;
11
- };
12
-
13
- export type RemoteClient = { getBucket(): RemoteBucketClient };
14
-
15
- export function createRemoteClient(options: RemoteClientOptions): RemoteClient {
16
- if (!isRecord(options)) throw new ClientError("INVALID_INPUT", "Client options are required");
17
- const httpRequest = createHttpRequest(options);
18
- const { mfid, bucketId, getCredential } = options;
19
- requireString(mfid, "mfid");
20
- if (typeof getCredential !== "function") throw new ClientError("INVALID_INPUT", "getCredential must be a function");
21
-
22
- const request: RemoteRequest = async (path, init = {}) => {
23
- init.signal?.throwIfAborted();
24
- const credential = await getCredential();
25
- requireString(credential?.token, "token");
26
- init.signal?.throwIfAborted();
27
- let headers: Headers;
28
- try {
29
- headers = new Headers(init.headers);
30
- headers.set("x-myfield-mfid", mfid);
31
- headers.set("authorization", `Bearer ${credential.token}`);
32
- } catch (cause) { throw new ClientError("INVALID_INPUT", "Invalid request headers", { cause }); }
33
- return httpRequest(path, { ...init, headers });
34
- };
35
-
36
- const bucket = createBucketClient(request, bucketId);
37
- return { getBucket: () => bucket };
38
- }