@myfield/sdk 0.9.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/src/index.ts ADDED
@@ -0,0 +1,23 @@
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";
@@ -0,0 +1,95 @@
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
+ }
@@ -0,0 +1,70 @@
1
+ export type BinaryInput = Blob | ArrayBuffer | Uint8Array;
2
+
3
+ export type BinaryOptions = {
4
+ mimeType?: string;
5
+ name?: string;
6
+ lastModified?: number;
7
+ };
8
+
9
+ export type BucketBinaryValue = {
10
+ readonly kind: "binary";
11
+ readonly size: number;
12
+ readonly mimeType?: string;
13
+ readonly name?: string;
14
+ readonly lastModified?: number;
15
+ blob(): Promise<Blob>;
16
+ arrayBuffer(): Promise<ArrayBuffer>;
17
+ };
18
+
19
+ export type CreateInstanceOptions = {
20
+ namespace?: string;
21
+ storage?: "indexeddb" | "memory";
22
+ };
23
+
24
+ export type BucketState = "disconnected" | "connecting" | "connected";
25
+
26
+ export type ListEntry = {
27
+ id: string;
28
+ updatedAt: string;
29
+ deleted?: true;
30
+ };
31
+
32
+ export type ConnectOptions = {
33
+ authBase?: string;
34
+ autoSync?: boolean;
35
+ };
36
+
37
+ export type Bucket = {
38
+ readonly id: string;
39
+ readonly state: BucketState;
40
+ binary(input: BinaryInput | BucketBinaryValue, options?: BinaryOptions): BucketBinaryValue;
41
+ ready(): Promise<void>;
42
+ put(objectId: string, object: Record<string, unknown>): Promise<void>;
43
+ get(objectId: string): Promise<Record<string, unknown> | null>;
44
+ update(objectId: string, fields: Record<string, unknown>): Promise<void>;
45
+ delete(objectId: string): Promise<void>;
46
+ list(options?: { prefix?: string; includeDeleted?: boolean }): Promise<ListEntry[]>;
47
+ resume(): Promise<BucketState>;
48
+ connect(options?: ConnectOptions): Promise<BucketState>;
49
+ disconnect(): Promise<void>;
50
+ sync(): Promise<void>;
51
+ setAutoSync(enabled: boolean): void;
52
+ on(event: "state", handler: (state: BucketState, detail?: string) => void): () => void;
53
+ on(event: "change", handler: (objectId: string) => void): () => void;
54
+ dispose(): void;
55
+ };
56
+
57
+ export type Instance = {
58
+ readonly namespace: string;
59
+ createBucket(options: { id: string }): Bucket;
60
+ };
61
+
62
+ export declare function createInstance(options?: CreateInstanceOptions): Instance;
63
+
64
+ export declare class NotConnectedError extends Error {
65
+ constructor();
66
+ }
67
+
68
+ export declare class OfflineError extends Error {
69
+ constructor();
70
+ }