@sparkvault/sdk-js 12.0.2 → 12.0.4

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/dist/index.mjs CHANGED
@@ -31,7 +31,8 @@ function isTransientHttpStatus(status) {
31
31
  * publication it is bound to (a content version, and the one an ingot row
32
32
  * names), Core's revocation of an upload's token, and the refusals of Core's
33
33
  * a transfer's answer names (the header, and the lock of a vault scheduled
34
- * for deletion).
34
+ * for deletion). Every client ends an upload it gives up by one rule here
35
+ * too: the upload id its delete is conditioned on (givenUpUploadId).
35
36
  *
36
37
  * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
37
38
  * and on the final state it hands Core's activation (POST
@@ -50,6 +51,38 @@ function isTransientHttpStatus(status) {
50
51
  */
51
52
 
52
53
 
54
+ /**
55
+ * An upload's id as both services spell it: `tus_` and the 32 lowercase hex
56
+ * digits of 16 random bytes. An encrypt token that names one (`upload_id`)
57
+ * was staged by Core under it, and Forge keys the upload's session, its chunk
58
+ * prefix and its VAK wrapping by it, so Core finds and settles the upload by
59
+ * the session's id.
60
+ */
61
+ const UPLOAD_ID_PATTERN = /^tus_[0-9a-f]{32}$/;
62
+
63
+ /**
64
+ * The upload id under which a client that gives an upload up (its person
65
+ * cancelled it, or it failed for good) ends it with the file its create
66
+ * made: the `upload_id` that create answered, which Core's delete takes as
67
+ * its condition (`DELETE …/ingots/:ingot_id?upload_id=`), deleting the ingot
68
+ * only while it is still that upload's unfinished file and keeping (412) one
69
+ * the upload published, or a later upload took over. Null when the file is
70
+ * not the upload's to end: its create staged onto a row that already stood
71
+ * (`created` not true: another upload's unfinished file, or a published file
72
+ * the upload was replacing), or answered no upload id, without which the
73
+ * delete would take whatever file stands, one the upload published
74
+ * included. Every client sends a given-up upload's delete under this id
75
+ * alone, and sends none when it is null.
76
+ *
77
+ * @param {{ created?: boolean|null, uploadId?: string|null }} placement -
78
+ * What the upload's create answered: whether it made the file, and the
79
+ * upload it staged
80
+ * @returns {string|null}
81
+ */
82
+ function givenUpUploadId({ created, uploadId }) {
83
+ return created === true && typeof uploadId === 'string' && UPLOAD_ID_PATTERN.test(uploadId) ? uploadId : null;
84
+ }
85
+
53
86
  /**
54
87
  * The codes Core's activation refuses an upload with, which Forge's refusal
55
88
  * map reads (the status is Core's):
@@ -826,6 +859,20 @@ class UserCancelledError extends SparkVaultError {
826
859
  Object.setPrototypeOf(this, UserCancelledError.prototype);
827
860
  }
828
861
  }
862
+ /**
863
+ * The identity provider answered a FedCM sign-in with an error of its own
864
+ * (the browser's `IdentityCredentialError`), after the browser showed the
865
+ * person its error dialog: the request reached the provider, which refused or
866
+ * failed it, so it is no cancel. `code` is the provider's answer
867
+ * (`server_error`, `access_denied`, ...).
868
+ */
869
+ class IdentityProviderError extends SparkVaultError {
870
+ constructor(code) {
871
+ super('The identity provider could not complete the sign-in.', code || 'identity_provider_error');
872
+ this.name = 'IdentityProviderError';
873
+ Object.setPrototypeOf(this, IdentityProviderError.prototype);
874
+ }
875
+ }
829
876
  class PopupBlockedError extends SparkVaultError {
830
877
  constructor() {
831
878
  super('Popup was blocked. Please allow popups for this site.', 'popup_blocked');
@@ -10190,6 +10237,20 @@ function decodeTokenSegment(segment, message) {
10190
10237
  throw new ValidationError(message);
10191
10238
  }
10192
10239
  }
10240
+ /**
10241
+ * The provider's own answer to a FedCM id assertion, as the browser rejects
10242
+ * with it (an `IdentityCredentialError`, a DOMException read by its name, so
10243
+ * neither the class's presence nor the realm it was made in matters), or null
10244
+ * for any other rejection.
10245
+ */
10246
+ function identityProviderErrorOf(error) {
10247
+ if (typeof error !== 'object' || error === null)
10248
+ return null;
10249
+ const { name, error: code } = error;
10250
+ if (name !== 'IdentityCredentialError')
10251
+ return null;
10252
+ return new IdentityProviderError(typeof code === 'string' ? code : '');
10253
+ }
10193
10254
  class IdentityModule {
10194
10255
  constructor(config) {
10195
10256
  this.renderer = null;
@@ -10252,8 +10313,12 @@ class IdentityModule {
10252
10313
  * `IdentityModule.isFedcmAvailable()` and fall back to `signIn()` otherwise.
10253
10314
  *
10254
10315
  * @returns the verified result, or `null` when the browser has no FedCM
10255
- * support (so the caller can fall back). Throws `UserCancelledError` when the
10256
- * person dismisses the chooser.
10316
+ * support (so the caller can fall back). Throws `UserCancelledError` when
10317
+ * the browser ends the request without a credential: the person dismissed
10318
+ * the chooser, or the browser had no SparkVault account to offer (the
10319
+ * browser reports both alike). Throws `IdentityProviderError`, carrying
10320
+ * SparkVault's own error code, when SparkVault answered the sign-in with an
10321
+ * error.
10257
10322
  *
10258
10323
  * @example
10259
10324
  * const result = (await sv.products.identity.isFedcmAvailable())
@@ -10287,9 +10352,12 @@ class IdentityModule {
10287
10352
  credential = await getCredential(request);
10288
10353
  }
10289
10354
  catch (error) {
10290
- // The browser rejects with an AbortError/NotAllowedError when the person
10291
- // dismisses the chooser — normalize that to the SDK's cancel signal.
10292
- throw new UserCancelledError(error instanceof Error ? error.message : undefined);
10355
+ // The provider's own answer to the id assertion is no cancel. Every other
10356
+ // rejection ends the request without a credential: the browser answers a
10357
+ // dismissed chooser and a provider with no account to offer with the same
10358
+ // NetworkError, so that is the SDK's cancel signal.
10359
+ throw identityProviderErrorOf(error)
10360
+ ?? new UserCancelledError(error instanceof Error ? error.message : undefined);
10293
10361
  }
10294
10362
  const token = credential?.token;
10295
10363
  if (!token) {
@@ -11935,6 +12003,38 @@ function waitUntilOnline(signal) {
11935
12003
  settle(resolve);
11936
12004
  });
11937
12005
  }
12006
+ /**
12007
+ * The failures a transfer met once the server held every byte of its upload,
12008
+ * which leave the upload's end to the server ({@link isReceivedUploadFailure}).
12009
+ */
12010
+ const receivedFailures = new WeakSet();
12011
+ /** The codes that end an upload whatever the server holds of it: its session gone, Core's refusal, the caller's cancel. */
12012
+ const UPLOAD_ENDING_CODES = new Set(['session_gone', 'upload_refused', 'cancelled']);
12013
+ /**
12014
+ * A failure of the receipt, which the transfer asks for only once the server
12015
+ * holds every byte: it leaves the upload's end to the server unless it ended
12016
+ * the upload itself (UPLOAD_ENDING_CODES) or named an earlier offset, bytes
12017
+ * the server lacks.
12018
+ */
12019
+ function receiptFailure(error) {
12020
+ if (error instanceof UploadApiError &&
12021
+ !UPLOAD_ENDING_CODES.has(error.code) &&
12022
+ error.verdict !== TRANSFER_VERDICT.RESYNC) {
12023
+ receivedFailures.add(error);
12024
+ }
12025
+ return error;
12026
+ }
12027
+ /**
12028
+ * Whether a transfer failed once the server held every byte of its upload,
12029
+ * short of the upload's own end: `upload_received_publishing`, and any other
12030
+ * failure of the receipt that confirms publication (one refused, or one that
12031
+ * went unanswered), never a gone session, Core's refusal or a cancel. The
12032
+ * server publishes such an upload, or ends it, on its own, so its caller
12033
+ * neither sends it again nor gives it up (`ingots.endUpload`).
12034
+ */
12035
+ function isReceivedUploadFailure(error) {
12036
+ return error instanceof UploadApiError && receivedFailures.has(error);
12037
+ }
11938
12038
  /** A failed request of this upload's transfer; anything else is rethrown as it is. */
11939
12039
  function transferFailure(error) {
11940
12040
  if (error instanceof UploadApiError)
@@ -12332,7 +12432,9 @@ class UploadApi extends SparkVaultApi {
12332
12432
  // the server (a chunk's 204, a HEAD, a 409), publication is confirmed
12333
12433
  // before the upload resolves.
12334
12434
  if (offset === file.size) {
12335
- const receipt = await this.confirmServerFinalized(transfer);
12435
+ const receipt = await this.confirmServerFinalized(transfer).catch((error) => {
12436
+ throw receiptFailure(error);
12437
+ });
12336
12438
  if (receipt.published)
12337
12439
  return;
12338
12440
  offset = receipt.resumeAt;
@@ -14182,6 +14284,11 @@ function formatBytes(bytes, decimals = 1) {
14182
14284
  * admin how to cancel the deletion, is the console's, never this page's.
14183
14285
  */
14184
14286
  const VAULT_NOT_ACCEPTING_MESSAGE = 'This vault isn\'t accepting files right now, so your file was not saved. Please contact the person who shared this upload page with you.';
14287
+ /**
14288
+ * What an uploader reads for a file of no bytes, which Core never stores: said
14289
+ * on the form, where another file can be chosen, as the size limit is.
14290
+ */
14291
+ const EMPTY_FILE_MESSAGE = 'This file is empty, so there is nothing to upload. Choose another file.';
14185
14292
  /**
14186
14293
  * Ceremony steps for the cryptographic visualization.
14187
14294
  */
@@ -14210,6 +14317,36 @@ function transferChannelLine(requestId) {
14210
14317
  ? ''
14211
14318
  : `<p class="svu-forging-line">Secure Transfer Channel: <span class="svu-mono">${escapeHtml(requestId)}</span></p>`;
14212
14319
  }
14320
+ /**
14321
+ * Refusals that say the vault takes no upload now, whichever file is chosen:
14322
+ * it is scheduled for deletion, its owner's plan lapsed, or its upload page is
14323
+ * gone or switched off. An error view after one offers no way on.
14324
+ */
14325
+ function vaultTakesNoUpload(error) {
14326
+ return error.code === VAULT_DELETION_SCHEDULED
14327
+ || error.details?.coreCode === VAULT_DELETION_SCHEDULED
14328
+ || error.code === 'UPLOAD_SOURCE_DISABLED'
14329
+ || error.statusCode === 402
14330
+ || (error.statusCode === 404 && error.code !== 'session_gone');
14331
+ }
14332
+ /**
14333
+ * The way on an error view offers after an upload of the chosen file failed:
14334
+ * nothing while the vault takes no upload ({@link vaultTakesNoUpload}); the
14335
+ * same file again after a failure that may pass (no answer, a fault, a rate
14336
+ * limit); another file after a refusal of this one, or after one received
14337
+ * whole, which the server finishes saving on its own.
14338
+ */
14339
+ function recoveryAfterUpload(error) {
14340
+ if (!(error instanceof UploadApiError))
14341
+ return { label: 'Try Again', keepFile: true };
14342
+ if (vaultTakesNoUpload(error))
14343
+ return null;
14344
+ if (error.code === RECEIVED_STILL_SAVING)
14345
+ return { label: 'Upload Another File', keepFile: false };
14346
+ const status = error.statusCode ?? 0;
14347
+ const mayPass = status === 0 || status === 429 || status >= 500;
14348
+ return mayPass ? { label: 'Try Again', keepFile: true } : { label: 'Choose Another File', keepFile: false };
14349
+ }
14213
14350
  /**
14214
14351
  * Whether an error represents a deliberate cancellation (user close,
14215
14352
  * programmatic close, or session abort) rather than a genuine failure.
@@ -14262,11 +14399,13 @@ class UploadRenderer {
14262
14399
  // (its own button, picker, or drop target) and hand the File to the SDK.
14263
14400
  if (this.options.file) {
14264
14401
  this.selectedFile = this.options.file;
14402
+ this.callbacks.onReady?.();
14265
14403
  await this.startUpload(config);
14266
14404
  return;
14267
14405
  }
14268
14406
  // Show form
14269
14407
  this.setState({ view: 'form', config });
14408
+ this.callbacks.onReady?.();
14270
14409
  }
14271
14410
  catch (error) {
14272
14411
  this.handleApiError(error);
@@ -14773,9 +14912,26 @@ class UploadRenderer {
14773
14912
  <span class="svu-error-code-value">${escapeHtml(state.code)}</span>
14774
14913
  </div>
14775
14914
  `;
14915
+ const { action } = state;
14916
+ if (action && this.config) {
14917
+ const config = this.config;
14918
+ const recover = document.createElement('button');
14919
+ recover.className = 'svu-btn svu-btn-primary';
14920
+ recover.textContent = action.label;
14921
+ recover.addEventListener('click', () => {
14922
+ if (!action.keepFile)
14923
+ this.selectedFile = null;
14924
+ this.setState({ view: 'form', config });
14925
+ });
14926
+ div.appendChild(recover);
14927
+ }
14776
14928
  return div;
14777
14929
  }
14778
14930
  handleFileSelect(file, config) {
14931
+ if (file.size === 0) {
14932
+ this.setState({ view: 'form', config, error: EMPTY_FILE_MESSAGE });
14933
+ return;
14934
+ }
14779
14935
  // Validate file size
14780
14936
  if (file.size > config.maxSizeBytes) {
14781
14937
  this.setState({
@@ -14900,7 +15056,9 @@ class UploadRenderer {
14900
15056
  this.callbacks.onSuccess(result);
14901
15057
  }
14902
15058
  catch (error) {
14903
- this.handleApiError(error);
15059
+ // A host that chose the file itself offers its own way on; the
15060
+ // widget's form is the way on only for a file chosen on it.
15061
+ this.handleApiError(error, this.options.file ? null : recoveryAfterUpload(error));
14904
15062
  }
14905
15063
  }
14906
15064
  async runCeremony(file, ingotId, requestId) {
@@ -14932,7 +15090,11 @@ class UploadRenderer {
14932
15090
  });
14933
15091
  await new Promise(resolve => setTimeout(resolve, 500));
14934
15092
  }
14935
- handleApiError(error) {
15093
+ /**
15094
+ * Show a failure in the error view, with the way on it offers (`action`:
15095
+ * none for a page that could not load), and tell the host through onError.
15096
+ */
15097
+ handleApiError(error, action = null) {
14936
15098
  // A closed renderer must not surface errors: cancelling mid-transfer
14937
15099
  // aborts the in-flight request, whose 'cancelled' rejection races the
14938
15100
  // teardown. The host has already received onCancel — onCancel and
@@ -14948,6 +15110,7 @@ class UploadRenderer {
14948
15110
  // points at the dashboard rather than the end user.
14949
15111
  this.setState({
14950
15112
  view: 'error',
15113
+ action,
14951
15114
  title: 'Upload Widget Not Enabled',
14952
15115
  message: 'This vault has not enabled the embedded upload widget. Enable it on the vault\'s settings page in the SparkVault dashboard to start accepting uploads here.',
14953
15116
  code: 'UPLOAD_SOURCE_DISABLED',
@@ -14961,6 +15124,7 @@ class UploadRenderer {
14961
15124
  // tells it never to upload the file again.
14962
15125
  this.setState({
14963
15126
  view: 'error',
15127
+ action,
14964
15128
  title: 'Upload Received',
14965
15129
  message: error.message,
14966
15130
  code: error.code,
@@ -14974,6 +15138,7 @@ class UploadRenderer {
14974
15138
  // uploader, told only that the vault takes no files now.
14975
15139
  this.setState({
14976
15140
  view: 'error',
15141
+ action,
14977
15142
  title: 'Uploads Paused',
14978
15143
  message: VAULT_NOT_ACCEPTING_MESSAGE,
14979
15144
  code: error.code,
@@ -14986,6 +15151,7 @@ class UploadRenderer {
14986
15151
  // sentence that never asks for the file again.
14987
15152
  this.setState({
14988
15153
  view: 'error',
15154
+ action,
14989
15155
  title: 'Upload Not Saved',
14990
15156
  message: error.message,
14991
15157
  code: error.code,
@@ -14997,6 +15163,7 @@ class UploadRenderer {
14997
15163
  // can answer 404 too, and its own sentence says what became of the file.
14998
15164
  this.setState({
14999
15165
  view: 'error',
15166
+ action,
15000
15167
  title: 'Upload Page Not Found',
15001
15168
  message: 'The requested upload endpoint could not be located. This may occur if the upload link has expired or was entered incorrectly.',
15002
15169
  code: 'NOT_FOUND',
@@ -15006,6 +15173,7 @@ class UploadRenderer {
15006
15173
  else if (error.statusCode === 402) {
15007
15174
  this.setState({
15008
15175
  view: 'error',
15176
+ action,
15009
15177
  title: 'Service Unavailable',
15010
15178
  message: 'This upload endpoint has been temporarily disabled due to an account billing issue. Please contact the organization\'s administrator.',
15011
15179
  code: 'PAYMENT_REQUIRED',
@@ -15015,6 +15183,7 @@ class UploadRenderer {
15015
15183
  else {
15016
15184
  this.setState({
15017
15185
  view: 'error',
15186
+ action,
15018
15187
  title: 'Upload Failed',
15019
15188
  message: error.message,
15020
15189
  code: error.code,
@@ -15026,6 +15195,7 @@ class UploadRenderer {
15026
15195
  else if (error instanceof Error) {
15027
15196
  this.setState({
15028
15197
  view: 'error',
15198
+ action,
15029
15199
  title: 'Upload Failed',
15030
15200
  message: error.message,
15031
15201
  code: 'UNKNOWN_ERROR',
@@ -15036,6 +15206,7 @@ class UploadRenderer {
15036
15206
  const err = new Error('An unexpected error occurred');
15037
15207
  this.setState({
15038
15208
  view: 'error',
15209
+ action,
15039
15210
  title: 'Upload Failed',
15040
15211
  message: err.message,
15041
15212
  code: 'UNKNOWN_ERROR',
@@ -15122,6 +15293,7 @@ class VaultUploadModule {
15122
15293
  reject(error);
15123
15294
  },
15124
15295
  onProgress: options.onProgress,
15296
+ onReady: options.onReady,
15125
15297
  });
15126
15298
  this.renderer.start().catch((error) => {
15127
15299
  options.onError?.(error);
@@ -15654,6 +15826,74 @@ function readIngotAccess(entry) {
15654
15826
  };
15655
15827
  }
15656
15828
 
15829
+ /**
15830
+ * SparkVault Debug Logger
15831
+ *
15832
+ * Conditional logging that respects debug mode setting.
15833
+ * When debug is enabled, logs detailed information to console.
15834
+ * When disabled (default), only fatal errors are logged.
15835
+ */
15836
+ let debugEnabled = false;
15837
+ /**
15838
+ * Enable or disable debug logging
15839
+ */
15840
+ function setDebugMode(enabled) {
15841
+ debugEnabled = enabled;
15842
+ if (enabled) {
15843
+ log('info', 'Debug mode enabled');
15844
+ }
15845
+ }
15846
+ /**
15847
+ * Internal log function
15848
+ */
15849
+ function log(level, message, ...args) {
15850
+ const prefix = '[SparkVault]';
15851
+ const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
15852
+ const formattedMessage = `${prefix} ${timestamp} ${message}`;
15853
+ switch (level) {
15854
+ case 'debug':
15855
+ if (debugEnabled) {
15856
+ console.debug(formattedMessage, ...args);
15857
+ }
15858
+ break;
15859
+ case 'info':
15860
+ if (debugEnabled) {
15861
+ console.log(formattedMessage, ...args);
15862
+ }
15863
+ break;
15864
+ case 'warn':
15865
+ if (debugEnabled) {
15866
+ console.warn(formattedMessage, ...args);
15867
+ }
15868
+ break;
15869
+ case 'error':
15870
+ // Always log errors (fatal)
15871
+ console.error(formattedMessage, ...args);
15872
+ break;
15873
+ }
15874
+ }
15875
+ /**
15876
+ * Logger object for convenient access
15877
+ */
15878
+ const logger = {
15879
+ /**
15880
+ * Debug level - verbose details for troubleshooting
15881
+ */
15882
+ debug: (message, ...args) => log('debug', message, ...args),
15883
+ /**
15884
+ * Info level - general information
15885
+ */
15886
+ info: (message, ...args) => log('info', message, ...args),
15887
+ /**
15888
+ * Warn level - warnings that don't prevent operation
15889
+ */
15890
+ warn: (message, ...args) => log('warn', message, ...args),
15891
+ /**
15892
+ * Error level - always logged regardless of debug mode
15893
+ */
15894
+ error: (message, ...args) => log('error', message, ...args),
15895
+ };
15896
+
15657
15897
  /**
15658
15898
  * The one browser transfer for a signed ingot download link: fetch it into a
15659
15899
  * Blob under liveness bounds, resuming from the bytes it holds when the caller
@@ -16333,7 +16573,9 @@ class IngotsModule {
16333
16573
  * transfer yourself; otherwise prefer {@link upload}. A create another
16334
16574
  * upload of the same file superseded before its token was issued rejects
16335
16575
  * with code `upload_refused` (`details.coreCode` UPLOAD_SUPERSEDED): the
16336
- * later upload is the one kept, so a new upload is no remedy.
16576
+ * later upload is the one kept, so a new upload is no remedy. An upload
16577
+ * you give up (you cancel its transfer, or it fails for good) ends with the
16578
+ * file its create made through {@link endUpload}, given this result.
16337
16579
  *
16338
16580
  * @example
16339
16581
  * const session = await sv.ingots.createUpload({
@@ -16362,15 +16604,65 @@ class IngotsModule {
16362
16604
  onNameConflict: options.onNameConflict,
16363
16605
  });
16364
16606
  return {
16365
- id: created.ingot_id,
16607
+ ...placementOf(created),
16366
16608
  name: created.name,
16367
16609
  contentType: created.content_type,
16368
16610
  size: created.size_bytes,
16369
16611
  uploadUrl: created.forge_url,
16370
16612
  expiresAt: created.expires_at,
16371
- created: created.created,
16372
16613
  };
16373
16614
  }
16615
+ /**
16616
+ * End an upload you give up (you cancelled its transfer, or it failed for
16617
+ * good) with the file its create made ({@link createUpload}'s result): the
16618
+ * server deletes the ingot only while it is still that upload's unfinished
16619
+ * file, ending the upload first, so a publication racing the end is decided
16620
+ * before anything goes. Never give up one the server received whole
16621
+ * ({@link isReceivedUploadFailure}): the server publishes or ends it on its
16622
+ * own. Resolves `deleted` once the vault holds the file no longer, deleted
16623
+ * now or already gone. Resolves `kept` when this end deleted nothing, which
16624
+ * {@link get} shows as it is now: the upload published the file, or a later
16625
+ * upload took it over, before the end reached the server, or, with no
16626
+ * request sent, the create did not make it (`created: false`) or names no
16627
+ * upload (`uploadId: null`), since a delete without its upload would take
16628
+ * whatever file stands. Any other failure rejects, the file left as it was.
16629
+ * {@link upload} ends an upload it cannot finish this way by itself.
16630
+ *
16631
+ * @example
16632
+ * const upload = await sv.ingots.createUpload({ vault: unsealed, name: file.name,
16633
+ * contentType: file.type, sizeBytes: file.size });
16634
+ * try {
16635
+ * await sv.ingots.sendUpload(upload.uploadUrl, file, { signal: controller.signal });
16636
+ * } catch (error) {
16637
+ * if (!isReceivedUploadFailure(error) &&
16638
+ * await sv.ingots.endUpload(unsealed, upload) === 'kept') {
16639
+ * // The end deleted nothing (the upload published the file, say): show it as it is.
16640
+ * showIngot(await sv.ingots.get(unsealed, upload.id));
16641
+ * }
16642
+ * throw error;
16643
+ * }
16644
+ */
16645
+ async endUpload(vault, upload) {
16646
+ const vaultId = requireVaultId(vault);
16647
+ const id = requireResourceId(upload.id, 'ingotId');
16648
+ const uploadId = givenUpUploadId(upload);
16649
+ if (uploadId === null)
16650
+ return 'kept';
16651
+ try {
16652
+ await this.http.delete(apiPath `/v1/vaults/${vaultId}/ingots/${id}`, {
16653
+ vat: vault.vatToken,
16654
+ query: { upload_id: uploadId },
16655
+ });
16656
+ return 'deleted';
16657
+ }
16658
+ catch (error) {
16659
+ if (error instanceof SparkVaultError && error.statusCode === 404)
16660
+ return 'deleted';
16661
+ if (error instanceof SparkVaultError && error.statusCode === 412)
16662
+ return 'kept';
16663
+ throw error;
16664
+ }
16665
+ }
16374
16666
  /**
16375
16667
  * Send a file's bytes to an upload session — the `uploadUrl` a
16376
16668
  * {@link createUpload} returned — over the resumable transfer every SDK
@@ -16478,7 +16770,11 @@ class IngotsModule {
16478
16770
  * server refused — another upload of it superseded this one, at its create
16479
16771
  * or while it streamed, the storage pool cannot take it, or its vault is
16480
16772
  * scheduled for deletion (a 409 `VAULT_DELETION_SCHEDULED`) — rejects with
16481
- * code `upload_refused`, as {@link sendUpload} does.
16773
+ * code `upload_refused`, as {@link sendUpload} does. An upload that rejects
16774
+ * any way but one the server received whole ({@link isReceivedUploadFailure}:
16775
+ * the server publishes or ends that one on its own) is given up: the end of
16776
+ * it with the file its create made ({@link endUpload}) starts as it
16777
+ * rejects, without holding up its own error.
16482
16778
  *
16483
16779
  * @example
16484
16780
  * const ingot = await sv.ingots.upload(unsealed, {
@@ -16500,7 +16796,29 @@ class IngotsModule {
16500
16796
  folderId: options.folderId,
16501
16797
  onNameConflict: options.onNameConflict,
16502
16798
  });
16503
- return this.transferAndFinalize(created, created.created, options.file, options.onProgress);
16799
+ try {
16800
+ return await this.transferAndFinalize(created, created.created, options.file, options.onProgress);
16801
+ }
16802
+ catch (error) {
16803
+ // The caller holds no session to continue this upload in, so a transfer
16804
+ // that ends any way but received whole is given up, its file with it.
16805
+ if (!isReceivedUploadFailure(error))
16806
+ this.endGivenUp(vault, placementOf(created));
16807
+ throw error;
16808
+ }
16809
+ }
16810
+ /**
16811
+ * End an upload this flow gave up ({@link endUpload}) without holding up
16812
+ * the error its caller is answered with: an end that fails leaves the file
16813
+ * to the server's expiry of abandoned uploads, and is logged.
16814
+ */
16815
+ endGivenUp(vault, upload) {
16816
+ this.endUpload(vault, upload).catch((error) => {
16817
+ logger.warn('A given-up upload could not be ended with its file; the server expires it', {
16818
+ ingotId: upload.id,
16819
+ code: error instanceof SparkVaultError ? error.code : undefined,
16820
+ });
16821
+ });
16504
16822
  }
16505
16823
  /**
16506
16824
  * Replace an existing ingot's content (high-level flow). Rejects as
@@ -16738,8 +17056,11 @@ class IngotsModule {
16738
17056
  return mapSharingConfig(response.data);
16739
17057
  }
16740
17058
  /**
16741
- * Invite an identity to a shared ingot. The identity type (email or phone)
16742
- * is inferred server-side from the identity value.
17059
+ * Invite an identity to an ingot's invite-only share, or share an ingot not
17060
+ * yet shared invite-only with it. A public or authenticated share refuses
17061
+ * it (a ValidationError) and changes nothing: set its visibility to
17062
+ * `invite_only` first. The identity type (email or phone) is inferred
17063
+ * server-side from the identity value.
16743
17064
  *
16744
17065
  * @example
16745
17066
  * await sv.ingots.addInvite(unsealed, 'ing_abc', 'user@example.com');
@@ -16751,7 +17072,7 @@ class IngotsModule {
16751
17072
  const vaultId = requireVaultId(vault);
16752
17073
  const id = requireResourceId(ingotId, 'ingotId');
16753
17074
  const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots/${id}/sharing/invite`, { identity }, { vat: vault.vatToken });
16754
- return mapInvite(response.data);
17075
+ return mapInvitation(response.data);
16755
17076
  }
16756
17077
  /**
16757
17078
  * Revoke an ingot sharing invite.
@@ -16837,6 +17158,8 @@ class IngotsModule {
16837
17158
  throw stagingRefusalOf(error);
16838
17159
  });
16839
17160
  if (!response.data.forge_url) {
17161
+ // No upload can start without its URL: the file the create made goes too.
17162
+ this.endGivenUp(vault, placementOf(response.data));
16840
17163
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
16841
17164
  }
16842
17165
  return response.data;
@@ -16867,6 +17190,14 @@ class IngotsModule {
16867
17190
  }
16868
17191
  }
16869
17192
  }
17193
+ /**
17194
+ * What a create answered about the file it placed: its id, whether the create
17195
+ * made it, and the upload it staged there, which {@link IngotsModule.endUpload}
17196
+ * ends it by.
17197
+ */
17198
+ function placementOf(created) {
17199
+ return { id: created.ingot_id, created: created.created, uploadId: created.upload_id ?? null };
17200
+ }
16870
17201
  function getBlobName(file) {
16871
17202
  if (typeof File !== 'undefined' && file instanceof File && file.name) {
16872
17203
  return file.name;
@@ -16916,7 +17247,12 @@ function mapIngotPage(response) {
16916
17247
  function mapSharingConfig(wire) {
16917
17248
  return {
16918
17249
  shared: wire.shared,
16919
- visibility: wire.visibility,
17250
+ visibility: wire.visibility ?? undefined,
17251
+ publicUrl: wire.public_url,
17252
+ linkCode: wire.link_code,
17253
+ sharingEnabled: wire.sharing_enabled,
17254
+ vaultAllIngotsPublic: wire.vault_all_ingots_public,
17255
+ sessionLengthSeconds: wire.session_length_seconds,
16920
17256
  invites: wire.invites?.map(mapInvite),
16921
17257
  };
16922
17258
  }
@@ -16925,6 +17261,14 @@ function mapInvite(wire) {
16925
17261
  id: wire.invite_id,
16926
17262
  identity: wire.identity,
16927
17263
  identityType: wire.identity_type,
17264
+ invitedAt: wire.created_at,
17265
+ };
17266
+ }
17267
+ function mapInvitation(wire) {
17268
+ return {
17269
+ ...mapInvite(wire),
17270
+ shareUrl: wire.share_url,
17271
+ delivered: wire.delivered,
16928
17272
  };
16929
17273
  }
16930
17274
 
@@ -17446,74 +17790,6 @@ class NotifyModule {
17446
17790
  }
17447
17791
  }
17448
17792
 
17449
- /**
17450
- * SparkVault Debug Logger
17451
- *
17452
- * Conditional logging that respects debug mode setting.
17453
- * When debug is enabled, logs detailed information to console.
17454
- * When disabled (default), only fatal errors are logged.
17455
- */
17456
- let debugEnabled = false;
17457
- /**
17458
- * Enable or disable debug logging
17459
- */
17460
- function setDebugMode(enabled) {
17461
- debugEnabled = enabled;
17462
- if (enabled) {
17463
- log('info', 'Debug mode enabled');
17464
- }
17465
- }
17466
- /**
17467
- * Internal log function
17468
- */
17469
- function log(level, message, ...args) {
17470
- const prefix = '[SparkVault]';
17471
- const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
17472
- const formattedMessage = `${prefix} ${timestamp} ${message}`;
17473
- switch (level) {
17474
- case 'debug':
17475
- if (debugEnabled) {
17476
- console.debug(formattedMessage, ...args);
17477
- }
17478
- break;
17479
- case 'info':
17480
- if (debugEnabled) {
17481
- console.log(formattedMessage, ...args);
17482
- }
17483
- break;
17484
- case 'warn':
17485
- if (debugEnabled) {
17486
- console.warn(formattedMessage, ...args);
17487
- }
17488
- break;
17489
- case 'error':
17490
- // Always log errors (fatal)
17491
- console.error(formattedMessage, ...args);
17492
- break;
17493
- }
17494
- }
17495
- /**
17496
- * Logger object for convenient access
17497
- */
17498
- const logger = {
17499
- /**
17500
- * Debug level - verbose details for troubleshooting
17501
- */
17502
- debug: (message, ...args) => log('debug', message, ...args),
17503
- /**
17504
- * Info level - general information
17505
- */
17506
- info: (message, ...args) => log('info', message, ...args),
17507
- /**
17508
- * Warn level - warnings that don't prevent operation
17509
- */
17510
- warn: (message, ...args) => log('warn', message, ...args),
17511
- /**
17512
- * Error level - always logged regardless of debug mode
17513
- */
17514
- error: (message, ...args) => log('error', message, ...args),
17515
- };
17516
-
17517
17793
  /**
17518
17794
  * SparkVault Auto-Initialization
17519
17795
  *
@@ -17648,7 +17924,7 @@ class SparkVault {
17648
17924
  }
17649
17925
  /** Get the SDK version */
17650
17926
  static get version() {
17651
- return '12.0.2';
17927
+ return '12.0.4';
17652
17928
  }
17653
17929
  }
17654
17930
  if (typeof window !== 'undefined') {
@@ -17658,5 +17934,5 @@ if (typeof window !== 'undefined') {
17658
17934
  window.SparkVault = instance ?? SparkVault;
17659
17935
  }
17660
17936
 
17661
- export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IngotsModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, logger, setDebugMode };
17937
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IdentityProviderError, IngotsModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, isReceivedUploadFailure, logger, setDebugMode };
17662
17938
  //# sourceMappingURL=index.mjs.map