@myfield/sdk 0.9.0 → 0.9.2

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,78 @@
1
+ import { ClientError } from "../errors.ts";
2
+
3
+ export type RequestOptions = { signal?: AbortSignal };
4
+ export type RemoteRequest = (path: string, init?: RequestInit) => Promise<Response>;
5
+
6
+ export function isRecord(value: unknown): value is Record<string, unknown> {
7
+ return value !== null && typeof value === "object" && !Array.isArray(value);
8
+ }
9
+
10
+ export function requireString(value: unknown, name: string): asserts value is string {
11
+ if (typeof value !== "string" || !value.trim()) {
12
+ throw new ClientError("INVALID_INPUT", `${name} must be a non-empty string`);
13
+ }
14
+ }
15
+
16
+ export function invalidResponse(response: Response, message = "Invalid protocol response", cause?: unknown): ClientError {
17
+ return new ClientError("INVALID_RESPONSE", message, {
18
+ status: response.status, requestId: response.headers.get("x-request-id") ?? undefined, cause,
19
+ });
20
+ }
21
+
22
+ function networkError(cause: unknown, signal?: AbortSignal | null): never {
23
+ signal?.throwIfAborted();
24
+ throw new ClientError("NETWORK_ERROR", "Network request failed", { retryable: true, cause });
25
+ }
26
+
27
+ export async function readJson(response: Response, signal?: AbortSignal): Promise<Record<string, unknown>> {
28
+ let value: unknown;
29
+ try { value = await response.json(); }
30
+ catch (cause) {
31
+ signal?.throwIfAborted();
32
+ if (!(cause instanceof SyntaxError)) return networkError(cause, signal);
33
+ throw invalidResponse(response, "Invalid JSON response", cause);
34
+ }
35
+ signal?.throwIfAborted();
36
+ if (!isRecord(value)) throw invalidResponse(response);
37
+ return value;
38
+ }
39
+
40
+ export function createHttpRequest(options: { apiBase: string; fetch?: typeof globalThis.fetch }) {
41
+ requireString(options.apiBase, "apiBase");
42
+ let base: URL;
43
+ try { base = new URL(options.apiBase); }
44
+ catch (cause) { throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin", { cause }); }
45
+ if (!["http:", "https:"].includes(base.protocol) || base.pathname !== "/" || base.search || base.hash || base.username || base.password) {
46
+ throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin without a path, query, fragment or credentials");
47
+ }
48
+ const fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
49
+ if (typeof fetch !== "function") throw new ClientError("INVALID_INPUT", "fetch must be a function");
50
+ return async (path: string, init: RequestInit): Promise<Response> => {
51
+ init.signal?.throwIfAborted();
52
+ let response: Response;
53
+ try { response = await fetch(new URL(path, base).href, { ...init, credentials: "omit" }); }
54
+ catch (cause) { return networkError(cause, init.signal); }
55
+ if (response.ok) return response;
56
+ let body: Record<string, unknown> = {};
57
+ try {
58
+ const value: unknown = await response.json();
59
+ if (isRecord(value)) body = value;
60
+ } catch { init.signal?.throwIfAborted(); }
61
+ const details = isRecord(body.details) ? body.details : {};
62
+ const retry = response.headers.get("retry-after");
63
+ const seconds = retry !== null && /^\d+(?:\.\d+)?$/.test(retry.trim()) ? Number(retry) : NaN;
64
+ const date = retry === null ? NaN : Date.parse(retry);
65
+ const retryAfterMs = Number.isFinite(seconds) ? seconds * 1000
66
+ : Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
67
+ throw new ClientError(typeof body.code === "string" && body.code ? body.code : "HTTP_ERROR",
68
+ typeof body.message === "string" && body.message ? body.message
69
+ : typeof body.error === "string" && body.error ? body.error : `HTTP ${response.status}`, {
70
+ status: response.status,
71
+ requestId: typeof body.requestId === "string" ? body.requestId : response.headers.get("x-request-id") ?? undefined,
72
+ retryable: typeof details.retryable === "boolean" ? details.retryable
73
+ : response.status === 408 || response.status === 429 || response.status >= 500,
74
+ retryAfterMs,
75
+ maxBytes: typeof details.maxBytes === "number" ? details.maxBytes : undefined,
76
+ });
77
+ };
78
+ }
@@ -0,0 +1,31 @@
1
+ export type InstanceProof = {
2
+ type: "instance.es256";
3
+ instanceId: string;
4
+ alg: "ES256";
5
+ signedAt: string;
6
+ signature: string;
7
+ };
8
+
9
+ export type CloudSessionCredential =
10
+ | { carrier: "bearer"; token: string; expiresAt: string }
11
+ | { carrier: "cookie"; expiresAt: string };
12
+
13
+ type SessionIdentity = { mfid: string; resourceId: string; instanceId: string };
14
+ type Challenge = { challengeId: string; challenge: string };
15
+ type PostJson = <T>(path: string, body: unknown) => Promise<T>;
16
+
17
+ export function createSessionClient(postJson: PostJson) {
18
+ return {
19
+ createChallenge(identity: SessionIdentity): Promise<Challenge> {
20
+ return postJson("/v1/api/auth/instance-challenge", identity);
21
+ },
22
+ async createSession(input: SessionIdentity & { challengeId: string; proof: InstanceProof }): Promise<CloudSessionCredential> {
23
+ const session = await postJson<{ credential: CloudSessionCredential }>("/v1/api/auth/instance-session", {
24
+ ...input, credentialCarrier: "bearer",
25
+ });
26
+ return session.credential;
27
+ },
28
+ };
29
+ }
30
+
31
+ export type SessionClient = ReturnType<typeof createSessionClient>;
package/types/index.d.ts CHANGED
@@ -18,7 +18,9 @@ export type BucketBinaryValue = {
18
18
 
19
19
  export type CreateInstanceOptions = {
20
20
  namespace?: string;
21
+ appId?: string;
21
22
  storage?: "indexeddb" | "memory";
23
+ authUrl?: string;
22
24
  };
23
25
 
24
26
  export type BucketState = "disconnected" | "connecting" | "connected";
@@ -30,7 +32,6 @@ export type ListEntry = {
30
32
  };
31
33
 
32
34
  export type ConnectOptions = {
33
- authBase?: string;
34
35
  autoSync?: boolean;
35
36
  };
36
37
 
@@ -38,6 +39,7 @@ export type Bucket = {
38
39
  readonly id: string;
39
40
  readonly state: BucketState;
40
41
  binary(input: BinaryInput | BucketBinaryValue, options?: BinaryOptions): BucketBinaryValue;
42
+ /** @deprecated No-op kept for compatibility; operations initialize storage lazily. */
41
43
  ready(): Promise<void>;
42
44
  put(objectId: string, object: Record<string, unknown>): Promise<void>;
43
45
  get(objectId: string): Promise<Record<string, unknown> | null>;
@@ -56,9 +58,21 @@ export type Bucket = {
56
58
 
57
59
  export type Instance = {
58
60
  readonly namespace: string;
61
+ readonly remote: { getBucket(): RemoteBucket };
62
+ readonly state: BucketState;
63
+ getBucket(): Bucket;
64
+ getKey(): Promise<InstanceKey | null>;
65
+ createKey(): Promise<InstanceKey>;
66
+ importKey(key: InstanceKey): Promise<void>;
67
+ removeKey(): Promise<void>;
68
+ resume(options?: { autoSync?: boolean }): Promise<BucketState>;
69
+ connect(options?: { autoSync?: boolean }): Promise<BucketState>;
70
+ disconnect(): Promise<void>;
71
+ on(event: "state", handler: (state: BucketState, error?: ClientError) => void): () => void;
59
72
  createBucket(options: { id: string }): Bucket;
60
73
  };
61
74
 
75
+ export declare function createInstance(appId: string): Instance;
62
76
  export declare function createInstance(options?: CreateInstanceOptions): Instance;
63
77
 
64
78
  export declare class NotConnectedError extends Error {
@@ -68,3 +82,73 @@ export declare class NotConnectedError extends Error {
68
82
  export declare class OfflineError extends Error {
69
83
  constructor();
70
84
  }
85
+
86
+ export type RequestOptions = { signal?: AbortSignal };
87
+
88
+ export type VersionMeta = {
89
+ objectId: string;
90
+ versionId: string;
91
+ parentVersionIds: string[];
92
+ payloadHash?: string;
93
+ [field: string]: unknown;
94
+ };
95
+
96
+ export type CurrentVersion = {
97
+ versionId: string;
98
+ headVersionMeta: VersionMeta;
99
+ history?: string[] | null;
100
+ [field: string]: unknown;
101
+ };
102
+
103
+ export type ObjectVersion<TPayload = Response> = { meta: VersionMeta; payload: TPayload };
104
+ export type CommitInput = { meta: VersionMeta; payload: Blob | Uint8Array; expectedHeadVersionId: string | null };
105
+ export type CommitResult = { ok: true } | { ok: false; reason: "version-mismatch" | "conflict" };
106
+
107
+ export type PageOptions = RequestOptions & { cursor?: string | null; limit?: number };
108
+ export type VersionHistory = VersionMeta & { history: string[]; nextCursor: string | null };
109
+ export type FeedHint = { objectId: string; versionId: string };
110
+ export type FeedPage = { entries: FeedHint[]; cursor: string; hasMore: boolean; [field: string]: unknown };
111
+ export type BucketIndex = { bucketId: string; objects: FeedHint[]; feedCursor: string | null; hasMoreFeed: boolean; [field: string]: unknown };
112
+
113
+ export type BucketKey = { bucketId: string; keyId: string; cryptoKey: CryptoKey };
114
+
115
+ export interface RemoteBucket {
116
+ getBucketKey(options?: RequestOptions): Promise<BucketKey>;
117
+ getCurrent(objectId: string, options?: RequestOptions & { knownVersionId?: string | null }): Promise<CurrentVersion | null>;
118
+ getVersion(objectId: string, versionId: string, options?: RequestOptions): Promise<ObjectVersion>;
119
+ getVersionMeta(objectId: string, versionId: string, options?: RequestOptions): Promise<VersionMeta>;
120
+ getPayload(objectId: string, versionId: string, options?: RequestOptions): Promise<Response>;
121
+ commit(input: CommitInput, options?: RequestOptions): Promise<CommitResult>;
122
+ listVersions(objectId: string, versionId: string, options?: PageOptions): Promise<VersionHistory>;
123
+ getIndex(options?: RequestOptions): Promise<BucketIndex>;
124
+ listFeed(options?: PageOptions): Promise<FeedPage>;
125
+ watchFeed(options?: RequestOptions): Promise<AsyncGenerator<FeedHint>>;
126
+ }
127
+
128
+ export type ClientErrorOptions = {
129
+ status?: number;
130
+ requestId?: string;
131
+ retryable?: boolean;
132
+ retryAfterMs?: number;
133
+ maxBytes?: number;
134
+ cause?: unknown;
135
+ };
136
+
137
+ export declare class ClientError extends Error {
138
+ readonly code: string;
139
+ readonly status?: number;
140
+ readonly requestId?: string;
141
+ readonly retryable: boolean;
142
+ readonly retryAfterMs?: number;
143
+ readonly maxBytes?: number;
144
+ constructor(code: string, message: string, options?: ClientErrorOptions);
145
+ }
146
+
147
+ export type InstanceKey = {
148
+ instanceId: string;
149
+ signingPublicJwk: JsonWebKey;
150
+ signingPrivateKey: CryptoKey;
151
+ wrappingPublicJwk: JsonWebKey;
152
+ wrappingPrivateKey: CryptoKey;
153
+ createdAt: string;
154
+ };