@calimero-network/mero-js 33.0.0 → 33.2.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.
@@ -19,6 +19,8 @@ import type { ApiAnswer, ApiSchema } from '../routes/types.js';
19
19
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
20
20
  export type { Committed, SignUpRefusal } from '../runtime/errors.js';
21
21
  export type { CalimeroSession, NodeEvent };
22
+ /** The largest file sent as one request, and the part size a session is asked for. */
23
+ export declare const FILE_PART_BYTES: number;
22
24
  export type CallResult = ApiAnswer<'intents'>;
23
25
  export type ViewResult = ApiAnswer<'views'>;
24
26
  /** An installed package and its releases. */
@@ -32,6 +34,10 @@ export type AppInfo = ApiSchema<'AppEntry'>;
32
34
  export type UpgradeRun = ApiSchema<'UpgradeRun'>;
33
35
  /** One of an app's blobs: `blobId` base58 (what apps print), `id` hex. */
34
36
  export type BlobInfo = ApiAnswer<'blob_info'>;
37
+ /** A sealed file: `id` and `sha256` hex, `blobId` base58 (what apps print), `index` the log index that recorded it. */
38
+ export type FileInfo = ApiAnswer<'file_info'>;
39
+ /** What {@link CalimeroClient.uploadFile} takes; a `Blob` is read part by part, never whole. */
40
+ export type FileData = Blob | Uint8Array | ArrayBuffer;
35
41
  /** One device present in an app (`publishPresence`); `state` hex, `null` once retracted. */
36
42
  export type PresenceEntry = ApiAnswer<'presence_get'>['present'][number];
37
43
  /**
@@ -351,6 +357,23 @@ export declare class CalimeroClient {
351
357
  * permission. A bad or expired grant answers `NotFound`, as a missing blob.
352
358
  */
353
359
  downloadBlobGranted(app: string, id: string, grant: string): Promise<Uint8Array>;
360
+ /**
361
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
362
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
363
+ * file for each, so one that may have reached it is never repeated); a larger file
364
+ * is a session of parts, each sent again after a dropped connection or a `503`.
365
+ * A session the node lost is begun again once; any other failure aborts it.
366
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
367
+ */
368
+ uploadFile(app: string, data: FileData): Promise<FileInfo>;
369
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
370
+ private uploadSession;
371
+ /** Send every part, in order, from wherever the node says the session is. */
372
+ private sendParts;
373
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
374
+ private untilAvailable;
375
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
376
+ private isTransient;
354
377
  /** Committed events from index `from`, then live, until `signal` aborts. */
355
378
  events(app: string, from?: number, signal?: AbortSignal): AsyncGenerator<NodeEvent>;
356
379
  /**
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { DEFAULT_RETRY, NodeTransport, directoryTransport, refusal, retryDelayMs, routePath, } from '../runtime/transport.js';
13
13
  import { DEFAULT_DIRECTORY } from '../runtime/directory.js';
14
- import { CalimeroError, LoginRequired, OriginNotRegistered, WrongRecoveryCode } from '../runtime/errors.js';
14
+ import { CalimeroError, LoginRequired, OriginNotRegistered, UnavailableError, WrongRecoveryCode } from '../runtime/errors.js';
15
15
  import { b64url, fromB64url } from '../runtime/passkey.js';
16
16
  import { createRouteClient } from '../routes/route-client.js';
17
17
  import { createRoutes } from '../generated/methods.js';
@@ -19,6 +19,12 @@ import { passkeyConfirm } from '../runtime/passkey.js';
19
19
  import { signRecovery } from './recovery-key.js';
20
20
  import { confirmationCode, pageQuery, pendingApprovalsFrom, } from './approvals.js';
21
21
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
22
+ /** The largest file sent as one request, and the part size a session is asked for. */
23
+ export const FILE_PART_BYTES = 16 * 1024 * 1024;
24
+ const PART_RESENDS = 1; // times a part is sent again before the node is asked where the session is
25
+ const MAX_FAILURES = 8; // failed sends in a row, with no part accepted between them, before giving up
26
+ const MAX_JUMPS = 16; // PART_OUT_OF_ORDER answers followed in one session before giving up
27
+ const CALL_RETRIES = 8; // times beginning and completing a session are sent again while the node is unavailable
22
28
  /** A deployer's key, as `GET /deployers` lists it and `DELETE /deployers/{key}` takes it. */
23
29
  export function deployerKey(deployer) {
24
30
  return 'account' in deployer ? `account:${deployer.account}` : `org:${deployer.org}`;
@@ -75,6 +81,19 @@ export function presenceState(state) {
75
81
  return state === null ? null : toHex(state);
76
82
  }
77
83
  export { DEFAULT_RETRY, retryDelayMs };
84
+ /** Bytes `start` to `end` of `data`, as a view or a slice: a `Blob` is never read whole. */
85
+ async function readSlice(data, start, end) {
86
+ if (data instanceof Blob)
87
+ return new Uint8Array(await data.slice(start, end).arrayBuffer());
88
+ return data instanceof ArrayBuffer ? new Uint8Array(data, start, end - start) : data.subarray(start, end);
89
+ }
90
+ /** The `next` an answer names, which cannot be past the last part. */
91
+ function nextPart(answer, parts) {
92
+ const next = answer?.next;
93
+ if (typeof next === 'number' && Number.isInteger(next) && next >= 0 && next <= parts)
94
+ return next;
95
+ throw new Error(`the node answered a bad next: ${JSON.stringify(answer)}`);
96
+ }
78
97
  export class CalimeroClient {
79
98
  /**
80
99
  * A client for the Calimero Cloud cluster named `cluster`: its node list read
@@ -322,6 +341,97 @@ export class CalimeroClient {
322
341
  async downloadBlobGranted(app, id, grant) {
323
342
  return new Uint8Array(await (await this.apps.blobDownload({ app, id, grant })).arrayBuffer());
324
343
  }
344
+ /**
345
+ * Upload a sealed file for component app `app`; answers `{ id, blobId, size, sha256, index }`.
346
+ * Up to {@link FILE_PART_BYTES} it is one request, sent once (the node mints a new
347
+ * file for each, so one that may have reached it is never repeated); a larger file
348
+ * is a session of parts, each sent again after a dropped connection or a `503`.
349
+ * A session the node lost is begun again once; any other failure aborts it.
350
+ * `413 TOO_LARGE` and `429 QUOTA_EXCEEDED` are the node's refusals.
351
+ */
352
+ async uploadFile(app, data) {
353
+ const size = data instanceof Blob ? data.size : data.byteLength;
354
+ if (size <= FILE_PART_BYTES)
355
+ return this.apps.filesUpload({ app, body: await readSlice(data, 0, size) });
356
+ try {
357
+ return await this.uploadSession(app, data, size);
358
+ }
359
+ catch (error) {
360
+ if (!(error instanceof CalimeroError) || error.code !== 'UPLOAD_UNKNOWN')
361
+ throw error;
362
+ return this.uploadSession(app, data, size);
363
+ }
364
+ }
365
+ /** Begin a session, send its parts and complete it, aborting it if that fails for good. */
366
+ async uploadSession(app, data, size) {
367
+ const begin = await this.untilAvailable(() => this.apps.uploadBegin({ app, size }));
368
+ const { uploadId: upload, partBytes, parts } = begin;
369
+ if (!upload || !partBytes || partBytes <= 0 || parts !== Math.ceil(size / partBytes)) {
370
+ throw new Error(`the node began an upload it cannot take: ${JSON.stringify(begin)}`);
371
+ }
372
+ try {
373
+ await this.sendParts(app, upload, data, size, partBytes, parts);
374
+ return await this.untilAvailable(() => this.apps.uploadComplete({ app, upload }));
375
+ }
376
+ catch (error) {
377
+ if (!(error instanceof CalimeroError && error.code === 'UPLOAD_UNKNOWN'))
378
+ await this.apps.uploadAbort({ app, upload }).catch(() => undefined);
379
+ throw error;
380
+ }
381
+ }
382
+ /** Send every part, in order, from wherever the node says the session is. */
383
+ async sendParts(app, upload, data, size, partBytes, parts) {
384
+ let [next, failures, jumps] = [0, 0, 0];
385
+ while (next < parts) {
386
+ try {
387
+ const body = await readSlice(data, next * partBytes, Math.min((next + 1) * partBytes, size));
388
+ next = nextPart(await this.apps.uploadPart({ app, upload, k: String(next), body }), parts);
389
+ failures = 0;
390
+ continue;
391
+ }
392
+ catch (error) {
393
+ if (error instanceof CalimeroError && error.code === 'PART_OUT_OF_ORDER') {
394
+ jumps += 1;
395
+ if (jumps > MAX_JUMPS)
396
+ throw error;
397
+ next = nextPart(error.details, parts);
398
+ continue;
399
+ }
400
+ if (!this.isTransient(error) || ++failures > MAX_FAILURES)
401
+ throw error;
402
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(failures - 1, this.transport.retry)));
403
+ if (failures > PART_RESENDS) {
404
+ try {
405
+ const at = nextPart(await this.apps.uploadStatus({ app, upload }), parts);
406
+ if (at > next)
407
+ failures = 0;
408
+ next = at;
409
+ }
410
+ catch (asked) {
411
+ if (!this.isTransient(asked))
412
+ throw asked;
413
+ }
414
+ }
415
+ }
416
+ }
417
+ }
418
+ /** `send` again, after a backoff, while the node is unavailable or cannot be reached. */
419
+ async untilAvailable(send) {
420
+ for (let retry = 0;; retry++) {
421
+ try {
422
+ return await send();
423
+ }
424
+ catch (error) {
425
+ if (!this.isTransient(error) || retry >= CALL_RETRIES)
426
+ throw error;
427
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs(retry, this.transport.retry)));
428
+ }
429
+ }
430
+ }
431
+ /** Whether the same request may succeed if sent again: the node answered `503`, or gave no answer. */
432
+ isTransient(error) {
433
+ return error instanceof UnavailableError || this.transport.isNetworkFailure(error);
434
+ }
325
435
  // ---------------------------------------------------------------- packages
326
436
  // ---------------------------------------------------------------- app instances
327
437
  /** Committed events from index `from`, then live, until `signal` aborts. */
@@ -1,9 +1,9 @@
1
- export { CalimeroClient, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
1
+ export { CalimeroClient, FILE_PART_BYTES, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
2
2
  export { DEFAULT_DIRECTORY, DirectoryError } from '../runtime/directory.js';
3
3
  export type { DirectoryFailure } from '../runtime/directory.js';
4
4
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ClusterNotUpgraded, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, NotServing, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
5
5
  export type { Committed, SignUpRefusal } from '../runtime/errors.js';
6
- export type { AppInfo, AppTeam, AppTeams, BlobInfo, DeadLetter, Deployer, FrontendManifest, PackageOrigin, SignInOptions, AccountRecovery, SignUpOptions, SignUpPolicy, CallResult, CalimeroClientOptions, CalimeroConnectOptions, NodeEvent, CalimeroSession, PackageInfo, RetryOptions, OrgInfo, OrgInvite, OrgMode, RecoveryTimes, PresenceEntry, ScopeAppsResult, ScopedAppTeam, TeamInfo, UpgradeRun, ViewResult, } from './calimero-client.js';
6
+ export type { AppInfo, AppTeam, AppTeams, BlobInfo, FileData, FileInfo, DeadLetter, Deployer, FrontendManifest, PackageOrigin, SignInOptions, AccountRecovery, SignUpOptions, SignUpPolicy, CallResult, CalimeroClientOptions, CalimeroConnectOptions, NodeEvent, CalimeroSession, PackageInfo, RetryOptions, OrgInfo, OrgInvite, OrgMode, RecoveryTimes, PresenceEntry, ScopeAppsResult, ScopedAppTeam, TeamInfo, UpgradeRun, ViewResult, } from './calimero-client.js';
7
7
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from '../runtime/attestation.js';
8
8
  export type { AttestationDoc, NodePolicy, NodeReleasePolicy } from '../runtime/attestation.js';
9
9
  export { browserPasskey, b64url, fromB64url, passkeyConfirm } from '../runtime/passkey.js';
@@ -7,7 +7,7 @@
7
7
  // (`recovery-key.ts`) and capability bits (`capabilities.ts`). It re-exports
8
8
  // the runtime's errors, passkeys and directory, which callers of the client
9
9
  // use. src/routes/index.ts describes the layering.
10
- export { CalimeroClient, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
10
+ export { CalimeroClient, FILE_PART_BYTES, deployerKey, frontendManifest, pageDeployment, presenceState } from './calimero-client.js';
11
11
  export { DEFAULT_DIRECTORY, DirectoryError } from '../runtime/directory.js';
12
12
  export { AppError, ArgsTooLarge, BadOrigin, CalimeroError, ClusterNotUpgraded, ConfirmCancelled, ConfirmPromptBlocked, ConfirmRequired, IdempotencyMismatch, LoginRequired, ConsentStale, FeatureNotActive, NotFound, NotServing, OriginNotRegistered, OriginTaken, PasskeyUnknownHere, QuotaExceeded, RecoveryNotReady, ReleaseDeadlineError, RuntimeTooOld, SignUpRefused, TrapError, UnavailableError, WrongNode, WrongRecoveryCode, errorFrom, } from '../runtime/errors.js';
13
13
  export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from '../runtime/attestation.js';