Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@uploadcare/blocks

Package Overview
Dependencies
Maintainers
0
Versions
338
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@uploadcare/blocks - npm Package Compare versions

Comparing version 0.46.0 to 0.47.0

abstract/UploaderPublicApi.d.ts

7

abstract/ActivityBlock.d.ts

@@ -10,5 +10,6 @@ export class ActivityBlock extends Block {

private static _activityCallbacks;
historyTracked: boolean;
/** @protected */
protected historyTracked: boolean;
init$: {
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -66,4 +67,4 @@ '*history': never[];

}
export type ActivityType = (typeof ActivityBlock)['activities'][keyof (typeof ActivityBlock)['activities']] | null;
export type ActivityType = (typeof ActivityBlock)['activities'][keyof (typeof ActivityBlock)['activities']] | (string & {}) | null;
import { Block } from './Block.js';
//# sourceMappingURL=ActivityBlock.d.ts.map

@@ -11,3 +11,5 @@ // @ts-check

export class ActivityBlock extends Block {
/** @protected */
historyTracked = false;
init$ = activityBlockCtx(this);

@@ -41,2 +43,3 @@

/** @protected */
initCallback() {

@@ -136,2 +139,3 @@ super.initCallback();

/** @protected */
destroyCallback() {

@@ -150,2 +154,3 @@ super.destroyCallback();

this.$['*currentActivity'] = null;
this.setOrAddState('*modalActive', false);
}

@@ -206,2 +211,2 @@ }

/** @typedef {(typeof ActivityBlock)['activities'][keyof (typeof ActivityBlock)['activities']] | null} ActivityType */
/** @typedef {(typeof ActivityBlock)['activities'][keyof (typeof ActivityBlock)['activities']] | (string & {}) | null} ActivityType */

@@ -9,3 +9,4 @@ export class Block extends BaseComponent<any> {

constructor();
requireCtxName: boolean;
/** @protected */
protected requireCtxName: boolean;
/** @type {import('./ActivityBlock.js').ActivityType} */

@@ -23,2 +24,3 @@ activityType: import('./ActivityBlock.js').ActivityType;

/**
* @private
* @param {string} key

@@ -28,8 +30,9 @@ * @param {number} count

*/
pluralize(key: string, count: number): string;
private pluralize;
/**
* @param {string} key
* @param {() => void} resolver
* @protected
*/
bindL10n(key: string, resolver: () => void): void;
protected bindL10n(key: string, resolver: () => void): void;
/** @type {Map<string, Set<{ remove: () => void }>>} */

@@ -44,7 +47,7 @@ l10nProcessorSubs: Map<string, Set<{

*/
emit(type: [type: "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "change" | "group-created", payload?: unknown, ({
emit(type: [type: "change" | "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "group-created", payload?: unknown, ({
debounce?: number | boolean | undefined;
} | undefined)?][0], payload?: [type: "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "change" | "group-created", payload?: unknown, ({
} | undefined)?][0], payload?: [type: "change" | "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "group-created", payload?: unknown, ({
debounce?: number | boolean | undefined;
} | undefined)?][1], options?: [type: "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "change" | "group-created", payload?: unknown, ({
} | undefined)?][1], options?: [type: "change" | "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "group-created", payload?: unknown, ({
debounce?: number | boolean | undefined;

@@ -62,8 +65,12 @@ } | undefined)?][2]): void;

setOrAddState(prop: string, newVal: any): void;
/** @param {import('./ActivityBlock.js').ActivityType} activityType */
setActivity(activityType: import('./ActivityBlock.js').ActivityType): void;
/** @returns {LocaleManager | null} */
get localeManager(): LocaleManager | null;
/** @returns {A11y | null} */
get a11y(): A11y | null;
/**
* @private
* @returns {LocaleManager | null}
*/
private get localeManager();
/**
* @returns {A11y | null}
* @protected
*/
protected get a11y(): A11y | null;
/** @type {Set<Block>} */

@@ -78,11 +85,7 @@ get blocksRegistry(): Set<Block>;

/**
* @param {Number} bytes
* @param {Number} [decimals]
*/
fileSizeFmt(bytes: number, decimals?: number | undefined): string;
/**
* @param {String} url
* @returns {String}
* @protected
*/
proxyUrl(url: string): string;
protected proxyUrl(url: string): string;
/** @returns {import('../types').ConfigType} } */

@@ -103,4 +106,3 @@ get cfg(): import("../types").ConfigType;

import { BaseComponent } from '@symbiotejs/symbiote';
import { LocaleManager } from './LocaleManager.js';
import { A11y } from './a11y.js';
//# sourceMappingURL=Block.d.ts.map

@@ -26,4 +26,6 @@ // @ts-check

static styleAttrs = [];
/** @protected */
requireCtxName = false;
allowCustomTemplate = true;
/** @type {import('./ActivityBlock.js').ActivityType} */

@@ -56,2 +58,3 @@ activityType = null;

/**
* @private
* @param {string} key

@@ -70,2 +73,3 @@ * @param {number} count

* @param {() => void} resolver
* @protected
*/

@@ -124,11 +128,3 @@ bindL10n(key, resolver) {

/** @param {import('./ActivityBlock.js').ActivityType} activityType */
setActivity(activityType) {
if (this.hasBlockInCtx((b) => b.activityType === activityType)) {
this.$['*currentActivity'] = activityType;
return;
}
console.warn(`Activity type "${activityType}" not found in the context`);
}
/** @protected */
connectedCallback() {

@@ -165,2 +161,3 @@ const styleAttrs = /** @type {typeof Block} */ (this.constructor).styleAttrs;

/** @protected */
disconnectedCallback() {

@@ -171,2 +168,3 @@ super.disconnectedCallback();

/** @protected */
initCallback() {

@@ -197,3 +195,6 @@ if (!this.has('*blocksRegistry')) {

/** @returns {LocaleManager | null} */
/**
* @private
* @returns {LocaleManager | null}
*/
get localeManager() {

@@ -203,3 +204,6 @@ return this.has('*localeManager') ? this.$['*localeManager'] : null;

/** @returns {A11y | null} */
/**
* @returns {A11y | null}
* @protected
*/
get a11y() {

@@ -214,2 +218,3 @@ return this.has('*a11y') ? this.$['*a11y'] : null;

/** @protected */
destroyCallback() {

@@ -247,23 +252,5 @@ let blocksRegistry = this.blocksRegistry;

/**
* @param {Number} bytes
* @param {Number} [decimals]
*/
fileSizeFmt(bytes, decimals = 2) {
let units = ['B', 'KB', 'MB', 'GB', 'TB'];
/**
* @param {String} str
* @returns {String}
*/
if (bytes === 0) {
return `0 ${units[0]}`;
}
let k = 1024;
let dm = decimals < 0 ? 0 : decimals;
let i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / k ** i).toFixed(dm)) + ' ' + units[i];
}
/**
* @param {String} url
* @returns {String}
* @protected
*/

@@ -270,0 +257,0 @@ proxyUrl(url) {

export function blockCtx(): {};
export function activityBlockCtx(fnCtx: import('./Block').Block): {
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -14,3 +14,2 @@ '*history': never[];

'*uploadQueue': Queue;
'*uploadCollection': null;
/** @type {ReturnType<import('../types').OutputErrorCollection>[]} */

@@ -26,3 +25,3 @@ '*collectionErrors': ReturnType<import('../types').OutputErrorCollection>[];

'*secureUploadsManager': import('./SecureUploadsManager.js').SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -29,0 +28,0 @@ '*history': never[];

@@ -9,3 +9,3 @@ // @ts-check

...blockCtx(),
'*currentActivity': '',
'*currentActivity': null,
'*currentActivityParams': {},

@@ -16,4 +16,4 @@ '*history': [],

fnCtx.set$({
'*currentActivity': null,
'*modalActive': false,
'*currentActivity': '',
});

@@ -30,3 +30,2 @@ },

'*uploadQueue': new Queue(1),
'*uploadCollection': null,
/** @type {ReturnType<import('../types').OutputErrorCollection>[]} */

@@ -33,0 +32,0 @@ '*collectionErrors': [],

@@ -9,3 +9,2 @@ export class SolutionBlock extends Block {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -16,3 +15,3 @@ '*collectionState': import("../index.js").OutputCollectionState<import("../index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("./SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -19,0 +18,0 @@ '*history': never[];

export class UploaderBlock extends ActivityBlock {
couldBeCtxOwner: boolean;
isCtxOwner: boolean;
/** @protected */
protected couldBeCtxOwner: boolean;
/** @private */
private isCtxOwner;
init$: {

@@ -9,3 +11,2 @@ '*commonProgress': number;

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -16,3 +17,3 @@ '*collectionState': import("../types").OutputCollectionState<import("../types").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -23,67 +24,20 @@ '*history': never[];

};
get hasCtxOwner(): boolean;
/** @returns {ValidationManager | null} */
get validationManager(): ValidationManager | null;
initCtxOwner(): void;
/** @private */
private _unobserveCollection;
/** @private */
private _unobserveCollectionProperties;
private get hasCtxOwner();
/**
* @param {string} url
* @param {{ silent?: boolean; fileName?: string; source?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
* @returns {ValidationManager}
* @protected
*/
addFileFromUrl(url: string, { silent, fileName, source }?: {
silent?: boolean | undefined;
fileName?: string | undefined;
source?: string | undefined;
} | undefined): import('../types').OutputFileEntry<'idle'>;
/**
* @param {string} uuid
* @param {{ silent?: boolean; fileName?: string; source?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromUuid(uuid: string, { silent, fileName, source }?: {
silent?: boolean | undefined;
fileName?: string | undefined;
source?: string | undefined;
} | undefined): import('../types').OutputFileEntry<'idle'>;
/**
* @param {string} cdnUrl
* @param {{ silent?: boolean; fileName?: string; source?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromCdnUrl(cdnUrl: string, { silent, fileName, source }?: {
silent?: boolean | undefined;
fileName?: string | undefined;
source?: string | undefined;
} | undefined): import('../types').OutputFileEntry<'idle'>;
/**
* @param {File} file
* @param {{ silent?: boolean; fileName?: string; source?: string; fullPath?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromObject(file: File, { silent, fileName, source, fullPath }?: {
silent?: boolean | undefined;
fileName?: string | undefined;
source?: string | undefined;
fullPath?: string | undefined;
} | undefined): import('../types').OutputFileEntry<'idle'>;
/** @param {string} internalId */
removeFileByInternalId(internalId: string): void;
removeAllFiles(): void;
uploadAll: () => void;
/** @param {{ captureCamera?: boolean }} options */
openSystemDialog(options?: {
captureCamera?: boolean;
}): void;
fileInput: HTMLInputElement | null | undefined;
/** @type {string[]} */
get sourceList(): string[];
/** @param {Boolean} [force] */
initFlow(force?: boolean | undefined): void;
doneFlow(): void;
protected get validationManager(): ValidationManager;
/** @returns {UploaderPublicApi} */
get api(): UploaderPublicApi;
get getAPI(): UploaderPublicApi;
/** @returns {TypedCollection} */
get uploadCollection(): TypedCollection;
/** @private */
private initCtxOwner;
/** @private */
private _unobserveCollection;
/** @private */
private _unobserveCollectionProperties;
/**

@@ -116,17 +70,9 @@ * @private

protected getMetadataFor(entryId: string): Promise<import("@uploadcare/upload-client").Metadata | undefined>;
/** @returns {Promise<import('@uploadcare/upload-client').FileFromOptions>} */
getUploadClientOptions(): Promise<import('@uploadcare/upload-client').FileFromOptions>;
/**
* @template {import('../types').OutputFileStatus} TStatus
* @param {string} entryId
* @returns {import('../types/exported.js').OutputFileEntry<TStatus>}
* @returns {Promise<import('@uploadcare/upload-client').FileFromOptions>}
* @protected
*/
getOutputItem<TStatus extends import("../types").OutputFileStatus>(entryId: string): import("../types").OutputFileEntry<TStatus>;
/**
* @param {(item: import('./TypedData.js').TypedData) => Boolean} [checkFn]
* @returns {import('../types/exported.js').OutputFileEntry[]}
*/
getOutputData(checkFn?: ((item: import('./TypedData.js').TypedData) => boolean) | undefined): import('../types/exported.js').OutputFileEntry[];
/** @template {import('../types').OutputCollectionStatus} TStatus */
getOutputCollectionState<TStatus_1 extends import("../types").OutputCollectionStatus>(): import("../types").OutputCollectionState<TStatus_1, "maybe-has-group">;
protected getUploadClientOptions(): Promise<import('@uploadcare/upload-client').FileFromOptions>;
/** @returns {import('../types/exported.js').OutputFileEntry[]} */
getOutputData(): import('../types/exported.js').OutputFileEntry[];
}

@@ -170,3 +116,4 @@ export namespace UploaderBlock {

import { ValidationManager } from './ValidationManager.js';
import { UploaderPublicApi } from './UploaderPublicApi.js';
import { TypedCollection } from './TypedCollection.js';
//# sourceMappingURL=UploaderBlock.d.ts.map

@@ -9,19 +9,17 @@ // @ts-check

import { EventType } from '../blocks/UploadCtxProvider/EventEmitter.js';
import { UploadSource } from '../blocks/utils/UploadSource.js';
import { serializeCsv } from '../blocks/utils/comma-separated.js';
import { debounce } from '../blocks/utils/debounce.js';
import { customUserAgent } from '../blocks/utils/userAgent.js';
import { createCdnUrl, createCdnUrlModifiers } from '../utils/cdn-utils.js';
import { IMAGE_ACCEPT_LIST, fileIsImage, mergeFileTypes } from '../utils/fileTypes.js';
import { stringToArray } from '../utils/stringToArray.js';
import { uploaderBlockCtx } from './CTX.js';
import { SecureUploadsManager } from './SecureUploadsManager.js';
import { TypedCollection } from './TypedCollection.js';
import { buildOutputCollectionState } from './buildOutputCollectionState.js';
import { UploaderPublicApi } from './UploaderPublicApi.js';
import { ValidationManager } from './ValidationManager.js';
import { uploadEntrySchema } from './uploadEntrySchema.js';
import { parseCdnUrl } from '../utils/parseCdnUrl.js';
import { SecureUploadsManager } from './SecureUploadsManager.js';
import { ValidationManager } from './ValidationManager.js';
export class UploaderBlock extends ActivityBlock {
/** @protected */
couldBeCtxOwner = false;
/** @private */
isCtxOwner = false;

@@ -31,2 +29,3 @@

/** @private */
get hasCtxOwner() {

@@ -41,6 +40,7 @@ return this.hasBlockInCtx((block) => {

/** @protected */
initCallback() {
super.initCallback();
if (!this.$['*uploadCollection']) {
if (!this.has('*uploadCollection')) {
let uploadCollection = new TypedCollection({

@@ -50,5 +50,9 @@ typedSchema: uploadEntrySchema,

});
this.$['*uploadCollection'] = uploadCollection;
this.add('*uploadCollection', uploadCollection);
}
//
if (!this.has('*publicApi')) {
this.add('*publicApi', new UploaderPublicApi(this));
}
if (!this.has('*validationManager')) {

@@ -63,7 +67,34 @@ this.add('*validationManager', new ValidationManager(this));

/** @returns {ValidationManager | null} */
/**
* @returns {ValidationManager}
* @protected
*/
get validationManager() {
return this.has('*validationManager') ? this.$['*validationManager'] : null;
if (!this.has('*validationManager')) {
throw new Error('Unexpected error: ValidationManager is not initialized');
}
return this.$['*validationManager'];
}
/** @returns {UploaderPublicApi} */
get api() {
if (!this.has('*publicApi')) {
throw new Error('Unexpected error: UploaderPublicApi is not initialized');
}
return this.$['*publicApi'];
}
get getAPI() {
return this.api;
}
/** @returns {TypedCollection} */
get uploadCollection() {
if (!this.has('*uploadCollection')) {
throw new Error('Unexpected error: TypedCollection is not initialized');
}
return this.$['*uploadCollection'];
}
/** @protected */
destroyCtxCallback() {

@@ -78,2 +109,3 @@ this._unobserveCollectionProperties?.();

/** @private */
initCtxOwner() {

@@ -97,206 +129,12 @@ this.isCtxOwner = true;

}
}
// TODO: Probably we should not allow user to override `source` property
/**
* @param {string} url
* @param {{ silent?: boolean; fileName?: string; source?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromUrl(url, { silent, fileName, source } = {}) {
const internalId = this.uploadCollection.add({
externalUrl: url,
fileName: fileName ?? null,
silent: silent ?? false,
source: source ?? UploadSource.API,
});
return this.getOutputItem(internalId);
}
/**
* @param {string} uuid
* @param {{ silent?: boolean; fileName?: string; source?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromUuid(uuid, { silent, fileName, source } = {}) {
const internalId = this.uploadCollection.add({
uuid,
fileName: fileName ?? null,
silent: silent ?? false,
source: source ?? UploadSource.API,
});
return this.getOutputItem(internalId);
}
/**
* @param {string} cdnUrl
* @param {{ silent?: boolean; fileName?: string; source?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromCdnUrl(cdnUrl, { silent, fileName, source } = {}) {
const parsedCdnUrl = parseCdnUrl({ url: cdnUrl, cdnBase: this.cfg.cdnCname });
if (!parsedCdnUrl) {
throw new Error('Invalid CDN URL');
}
const internalId = this.uploadCollection.add({
uuid: parsedCdnUrl.uuid,
cdnUrl,
cdnUrlModifiers: parsedCdnUrl.cdnUrlModifiers,
fileName: fileName ?? parsedCdnUrl.filename ?? null,
silent: silent ?? false,
source: source ?? UploadSource.API,
});
return this.getOutputItem(internalId);
}
/**
* @param {File} file
* @param {{ silent?: boolean; fileName?: string; source?: string; fullPath?: string }} [options]
* @returns {import('../types').OutputFileEntry<'idle'>}
*/
addFileFromObject(file, { silent, fileName, source, fullPath } = {}) {
const internalId = this.uploadCollection.add({
file,
isImage: fileIsImage(file),
mimeType: file.type,
fileName: fileName ?? file.name,
fileSize: file.size,
silent: silent ?? false,
source: source ?? UploadSource.API,
fullPath: fullPath ?? null,
});
return this.getOutputItem(internalId);
}
/** @param {string} internalId */
removeFileByInternalId(internalId) {
if (!this.uploadCollection.read(internalId)) {
throw new Error(`File with internalId ${internalId} not found`);
}
this.uploadCollection.remove(internalId);
}
removeAllFiles() {
this.uploadCollection.clearAll();
}
uploadAll = () => {
const itemsToUpload = this.uploadCollection.items().filter((id) => {
const entry = this.uploadCollection.read(id);
return !entry.getValue('isRemoved') && !entry.getValue('isUploading') && !entry.getValue('fileInfo');
});
if (itemsToUpload.length === 0) {
return;
}
this.$['*uploadTrigger'] = new Set(itemsToUpload);
this.emit(
EventType.COMMON_UPLOAD_START,
/** @type {import('../types').OutputCollectionState<'uploading'>} */ (this.getOutputCollectionState()),
);
};
/** @param {{ captureCamera?: boolean }} options */
openSystemDialog(options = {}) {
let accept = serializeCsv(mergeFileTypes([this.cfg.accept ?? '', ...(this.cfg.imgOnly ? IMAGE_ACCEPT_LIST : [])]));
if (this.cfg.accept && !!this.cfg.imgOnly) {
console.warn(
'There could be a mistake.\n' +
'Both `accept` and `imgOnly` parameters are set.\n' +
'The value of `accept` will be concatenated with the internal image mime types list.',
);
}
this.fileInput = document.createElement('input');
this.fileInput.type = 'file';
this.fileInput.multiple = this.cfg.multiple;
if (options.captureCamera) {
this.fileInput.capture = this.cfg.cameraCapture;
this.fileInput.accept = 'image/*';
} else {
this.fileInput.accept = accept;
}
this.fileInput.dispatchEvent(new MouseEvent('click'));
this.fileInput.onchange = () => {
// @ts-ignore TODO: fix this
[...this.fileInput['files']].forEach((file) =>
this.addFileFromObject(file, { source: options.captureCamera ? UploadSource.CAMERA : UploadSource.LOCAL }),
);
// To call uploadTrigger UploadList should draw file items first:
this.$['*currentActivity'] = ActivityBlock.activities.UPLOAD_LIST;
this.setOrAddState('*modalActive', true);
// @ts-ignore TODO: fix this
this.fileInput['value'] = '';
this.fileInput = null;
};
}
/** @type {string[]} */
get sourceList() {
/** @type {string[]} */
let list = [];
if (this.cfg.sourceList) {
list = stringToArray(this.cfg.sourceList);
}
// @ts-ignore TODO: fix this
return list;
}
/** @param {Boolean} [force] */
initFlow(force = false) {
if (this.uploadCollection.size > 0 && !force) {
this.set$({
'*currentActivity': ActivityBlock.activities.UPLOAD_LIST,
if (this.has('*modalActive')) {
this.sub('*modalActive', (modalActive) => {
if (modalActive && !this.$['*currentActivity']) {
this.$['*modalActive'] = false;
}
});
this.setOrAddState('*modalActive', true);
} else {
if (this.sourceList?.length === 1) {
const srcKey = this.sourceList[0];
// TODO: We should refactor those handlers
if (srcKey === 'local') {
this.$['*currentActivity'] = ActivityBlock.activities.UPLOAD_LIST;
this?.['openSystemDialog']();
return;
}
const blocksRegistry = this.blocksRegistry;
/**
* @param {import('./Block').Block} block
* @returns {block is import('../blocks/SourceBtn/SourceBtn.js').SourceBtn}
*/
const isSourceBtn = (block) => 'type' in block && block.type === srcKey;
const sourceBtnBlock = [...blocksRegistry].find(isSourceBtn);
// TODO: This is weird that we have this logic inside UI component, we should consider to move it somewhere else
sourceBtnBlock?.activate();
if (this.$['*currentActivity']) {
this.setOrAddState('*modalActive', true);
}
} else {
// Multiple sources case:
this.set$({
'*currentActivity': ActivityBlock.activities.START_FROM,
});
this.setOrAddState('*modalActive', true);
}
}
}
doneFlow() {
this.set$({
'*currentActivity': this.doneActivity,
'*history': this.doneActivity ? [this.doneActivity] : [],
});
if (!this.$['*currentActivity']) {
this.setOrAddState('*modalActive', false);
}
}
/** @returns {TypedCollection} */
get uploadCollection() {
return this.$['*uploadCollection'];
}
/**

@@ -319,6 +157,6 @@ * @private

const collectionStateWithGroup = /** @type {import('../types').OutputCollectionState<'success', 'has-group'>} */ (
this.getOutputCollectionState()
this.api.getOutputCollectionState()
);
this.emit(EventType.GROUP_CREATED, collectionStateWithGroup);
this.emit(EventType.CHANGE, () => this.getOutputCollectionState(), { debounce: true });
this.emit(EventType.CHANGE, () => this.api.getOutputCollectionState(), { debounce: true });
this.$['*collectionState'] = collectionStateWithGroup;

@@ -333,5 +171,5 @@ }

}
const collectionState = this.getOutputCollectionState();
const collectionState = this.api.getOutputCollectionState();
this.$['*collectionState'] = collectionState;
this.emit(EventType.CHANGE, () => this.getOutputCollectionState(), { debounce: true });
this.emit(EventType.CHANGE, () => this.api.getOutputCollectionState(), { debounce: true });

@@ -352,10 +190,8 @@ if (this.cfg.groupOutput && collectionState.totalCount > 0 && collectionState.status === 'success') {

}
if (this.validationManager) {
this.validationManager.runFileValidators();
this.validationManager.runCollectionValidators();
}
this.validationManager.runFileValidators();
this.validationManager.runCollectionValidators();
for (const entry of added) {
if (!entry.getValue('silent')) {
this.emit(EventType.FILE_ADDED, this.getOutputItem(entry.uid));
this.emit(EventType.FILE_ADDED, this.api.getOutputItem(entry.uid));
}

@@ -375,3 +211,3 @@ }

URL.revokeObjectURL(entry?.getValue('thumbUrl'));
this.emit(EventType.FILE_REMOVED, this.getOutputItem(entry.uid));
this.emit(EventType.FILE_REMOVED, this.api.getOutputItem(entry.uid));
}

@@ -407,3 +243,3 @@

// We can't modify entry properties in the same tick, so we need to wait a bit
if (this.validationManager) this.validationManager.runFileValidators(entriesToRunValidation);
this.validationManager.runFileValidators(entriesToRunValidation);
});

@@ -415,3 +251,3 @@

if (isUploading && !silent) {
this.emit(EventType.FILE_UPLOAD_PROGRESS, this.getOutputItem(entryId));
this.emit(EventType.FILE_UPLOAD_PROGRESS, this.api.getOutputItem(entryId));
}

@@ -426,3 +262,3 @@ }

if (isUploading && !silent) {
this.emit(EventType.FILE_UPLOAD_START, this.getOutputItem(entryId));
this.emit(EventType.FILE_UPLOAD_START, this.api.getOutputItem(entryId));
}

@@ -435,3 +271,3 @@ }

if (fileInfo && !silent) {
this.emit(EventType.FILE_UPLOAD_SUCCESS, this.getOutputItem(entryId));
this.emit(EventType.FILE_UPLOAD_SUCCESS, this.api.getOutputItem(entryId));
}

@@ -451,3 +287,3 @@ }

EventType.COMMON_UPLOAD_SUCCESS,
/** @type {import('../types').OutputCollectionState<'success'>} */ (this.getOutputCollectionState()),
/** @type {import('../types').OutputCollectionState<'success'>} */ (this.api.getOutputCollectionState()),
);

@@ -460,6 +296,7 @@ }

if (errors.length > 0) {
this.emit(EventType.FILE_UPLOAD_FAILED, this.getOutputItem(entryId));
this.emit(EventType.FILE_UPLOAD_FAILED, this.api.getOutputItem(entryId));
this.emit(
EventType.COMMON_UPLOAD_FAILED,
() => /** @type {import('../types').OutputCollectionState<'failed'>} */ (this.getOutputCollectionState()),
() =>
/** @type {import('../types').OutputCollectionState<'failed'>} */ (this.api.getOutputCollectionState()),
{ debounce: true },

@@ -475,3 +312,3 @@ );

uids.forEach((uid) => {
this.emit(EventType.FILE_URL_CHANGED, this.getOutputItem(uid));
this.emit(EventType.FILE_URL_CHANGED, this.api.getOutputItem(uid));
});

@@ -502,3 +339,3 @@

EventType.COMMON_UPLOAD_PROGRESS,
/** @type {import('../types').OutputCollectionState<'uploading'>} */ (this.getOutputCollectionState()),
/** @type {import('../types').OutputCollectionState<'uploading'>} */ (this.api.getOutputCollectionState()),
);

@@ -554,3 +391,3 @@ };

if (typeof configValue === 'function') {
const outputFileEntry = this.getOutputItem(entryId);
const outputFileEntry = this.api.getOutputItem(entryId);
const metadata = await configValue(outputFileEntry);

@@ -562,3 +399,6 @@ return metadata;

/** @returns {Promise<import('@uploadcare/upload-client').FileFromOptions>} */
/**
* @returns {Promise<import('@uploadcare/upload-client').FileFromOptions>}
* @protected
*/
async getUploadClientOptions() {

@@ -590,65 +430,8 @@ /** @type {SecureUploadsManager} */

/**
* @template {import('../types').OutputFileStatus} TStatus
* @param {string} entryId
* @returns {import('../types/exported.js').OutputFileEntry<TStatus>}
*/
getOutputItem(entryId) {
const uploadEntryData = /** @type {import('./uploadEntrySchema.js').UploadEntry} */ (Data.getCtx(entryId).store);
/** @type {import('@uploadcare/upload-client').UploadcareFile?} */
const fileInfo = uploadEntryData.fileInfo;
/** @type {import('../types').OutputFileEntry['status']} */
let status = uploadEntryData.isRemoved
? 'removed'
: uploadEntryData.errors.length > 0
? 'failed'
: !!uploadEntryData.fileInfo
? 'success'
: uploadEntryData.isUploading
? 'uploading'
: 'idle';
/** @type {unknown} */
const outputItem = {
uuid: fileInfo?.uuid ?? uploadEntryData.uuid ?? null,
internalId: entryId,
name: fileInfo?.originalFilename ?? uploadEntryData.fileName,
size: fileInfo?.size ?? uploadEntryData.fileSize,
isImage: fileInfo?.isImage ?? uploadEntryData.isImage,
mimeType: fileInfo?.mimeType ?? uploadEntryData.mimeType,
file: uploadEntryData.file,
externalUrl: uploadEntryData.externalUrl,
cdnUrlModifiers: uploadEntryData.cdnUrlModifiers,
cdnUrl: uploadEntryData.cdnUrl ?? fileInfo?.cdnUrl ?? null,
fullPath: uploadEntryData.fullPath,
uploadProgress: uploadEntryData.uploadProgress,
fileInfo: fileInfo ?? null,
metadata: uploadEntryData.metadata ?? fileInfo?.metadata ?? null,
isSuccess: status === 'success',
isUploading: status === 'uploading',
isFailed: status === 'failed',
isRemoved: status === 'removed',
errors: /** @type {import('../types/exported.js').OutputFileEntry['errors']} */ (uploadEntryData.errors),
status,
};
return /** @type {import('../types/exported.js').OutputFileEntry<TStatus>} */ (outputItem);
}
/**
* @param {(item: import('./TypedData.js').TypedData) => Boolean} [checkFn]
* @returns {import('../types/exported.js').OutputFileEntry[]}
*/
getOutputData(checkFn) {
const entriesIds = checkFn ? this.uploadCollection.findItems(checkFn) : this.uploadCollection.items();
const data = entriesIds.map((itemId) => this.getOutputItem(itemId));
/** @returns {import('../types/exported.js').OutputFileEntry[]} */
getOutputData() {
const entriesIds = this.uploadCollection.items();
const data = entriesIds.map((itemId) => this.api.getOutputItem(itemId));
return data;
}
/** @template {import('../types').OutputCollectionStatus} TStatus */
getOutputCollectionState() {
return /** @type {ReturnType<typeof buildOutputCollectionState<TStatus>>} */ (buildOutputCollectionState(this));
}
}

@@ -655,0 +438,0 @@

@@ -29,4 +29,4 @@ export class ValidationManager {

}
export type FuncFileValidator = (outputEntry: import('../types').OutputFileEntry, ctx: import('./UploaderBlock.js').UploaderBlock) => undefined | import('../types').OutputErrorFile;
export type FuncCollectionValidator = (collection: ReturnType<typeof import('./buildOutputCollectionState.js').buildOutputCollectionState<import('../types').OutputCollectionStatus>>, ctx: import('./UploaderBlock.js').UploaderBlock) => undefined | import('../types').OutputErrorCollection;
export type FuncFileValidator = (outputEntry: import('../types').OutputFileEntry, api: import('./UploaderPublicApi.js').UploaderPublicApi) => undefined | import('../types').OutputErrorFile;
export type FuncCollectionValidator = (collection: ReturnType<typeof import('./buildOutputCollectionState.js').buildOutputCollectionState<import('../types').OutputCollectionStatus>>, api: import('./UploaderPublicApi.js').UploaderPublicApi) => undefined | import('../types').OutputErrorCollection;
//# sourceMappingURL=ValidationManager.d.ts.map

@@ -14,3 +14,3 @@ // @ts-check

* outputEntry: import('../types').OutputFileEntry,
* ctx: import('./UploaderBlock.js').UploaderBlock,
* api: import('./UploaderPublicApi.js').UploaderPublicApi,
* ) => undefined | import('../types').OutputErrorFile} FuncFileValidator

@@ -26,3 +26,3 @@ */

* >,
* ctx: import('./UploaderBlock.js').UploaderBlock,
* api: import('./UploaderPublicApi.js').UploaderPublicApi,
* ) => undefined | import('../types').OutputErrorCollection} FuncCollectionValidator

@@ -81,3 +81,3 @@ */

runCollectionValidators() {
const collection = this._blockInstance.getOutputCollectionState();
const collection = this._blockInstance.api.getOutputCollectionState();
const errors = [];

@@ -90,3 +90,3 @@

try {
const errorOrErrors = validator(collection, this._blockInstance);
const errorOrErrors = validator(collection, this._blockInstance.api);
if (!errorOrErrors) {

@@ -114,3 +114,3 @@ continue;

/** @type {import('../types').OutputCollectionState<'failed'>} */ (
this._blockInstance.getOutputCollectionState()
this._blockInstance.api.getOutputCollectionState()
),

@@ -127,3 +127,3 @@ { debounce: true },

_runFileValidatorsForEntry(entry) {
const outputEntry = this._blockInstance.getOutputItem(entry.uid);
const outputEntry = this._blockInstance.api.getOutputItem(entry.uid);
const errors = [];

@@ -136,3 +136,3 @@

try {
const error = validator(outputEntry, this._blockInstance);
const error = validator(outputEntry, this._blockInstance.api);
if (!error) {

@@ -139,0 +139,0 @@ continue;

@@ -174,3 +174,3 @@ import { UploaderBlock } from '../../abstract/UploaderBlock.js';

});
this.addFileFromObject(file, { source: UploadSource.CAMERA });
this.api.addFileFromObject(file, { source: UploadSource.CAMERA });
this.set$({

@@ -177,0 +177,0 @@ '*currentActivity': ActivityBlock.activities.UPLOAD_LIST,

@@ -9,3 +9,2 @@ export class CloudImageEditorActivity extends UploaderBlock {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -16,3 +15,3 @@ '*collectionState': import("../../index.js").OutputCollectionState<import("../../index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -19,0 +18,0 @@ '*history': never[];

@@ -65,4 +65,4 @@ /**

/** Mapping of attribute names to state */
declare const attrStateMapping: Record<"pubkey" | "multiple" | "accept" | "store" | "debug" | "secure-expire" | "crop-preset" | "max-local-file-size-bytes" | "multiple-min" | "multiple-max" | "confirm-upload" | "img-only" | "external-sources-preferred-types" | "camera-mirror" | "camera-capture" | "source-list" | "thumb-size" | "show-empty-list" | "use-local-image-editor" | "use-cloud-image-editor" | "cloud-image-editor-tabs" | "remove-copyright" | "image-shrink" | "modal-scroll-lock" | "modal-backdrop-strokes" | "source-list-wrap" | "remote-tab-session-key" | "cdn-cname" | "base-url" | "social-base-url" | "secure-signature" | "secure-delivery-proxy" | "retry-throttled-request-max-times" | "multipart-min-file-size" | "multipart-chunk-size" | "max-concurrent-requests" | "multipart-max-concurrent-requests" | "multipart-max-attempts" | "check-for-url-duplicates" | "save-url-for-recurrent-uploads" | "group-output" | "user-agent-integration" | "locale-name" | "secure-uploads-expire-threshold" | "secureexpire" | "croppreset" | "maxlocalfilesizebytes" | "multiplemin" | "multiplemax" | "confirmupload" | "imgonly" | "externalsourcespreferredtypes" | "cameramirror" | "cameracapture" | "sourcelist" | "thumbsize" | "showemptylist" | "uselocalimageeditor" | "usecloudimageeditor" | "cloudimageeditortabs" | "removecopyright" | "imageshrink" | "modalscrolllock" | "modalbackdropstrokes" | "sourcelistwrap" | "remotetabsessionkey" | "cdncname" | "baseurl" | "socialbaseurl" | "securesignature" | "securedeliveryproxy" | "retrythrottledrequestmaxtimes" | "multipartminfilesize" | "multipartchunksize" | "maxconcurrentrequests" | "multipartmaxconcurrentrequests" | "multipartmaxattempts" | "checkforurlduplicates" | "saveurlforrecurrentuploads" | "groupoutput" | "useragentintegration" | "localename" | "secureuploadsexpirethreshold", string>;
declare const attrStateMapping: Record<"multiple" | "pubkey" | "accept" | "store" | "debug" | "secure-expire" | "crop-preset" | "multiple-min" | "multiple-max" | "confirm-upload" | "img-only" | "external-sources-preferred-types" | "camera-mirror" | "camera-capture" | "source-list" | "max-local-file-size-bytes" | "thumb-size" | "show-empty-list" | "use-local-image-editor" | "use-cloud-image-editor" | "cloud-image-editor-tabs" | "remove-copyright" | "image-shrink" | "modal-scroll-lock" | "modal-backdrop-strokes" | "source-list-wrap" | "remote-tab-session-key" | "cdn-cname" | "base-url" | "social-base-url" | "secure-signature" | "secure-delivery-proxy" | "retry-throttled-request-max-times" | "multipart-min-file-size" | "multipart-chunk-size" | "max-concurrent-requests" | "multipart-max-concurrent-requests" | "multipart-max-attempts" | "check-for-url-duplicates" | "save-url-for-recurrent-uploads" | "group-output" | "user-agent-integration" | "locale-name" | "secure-uploads-expire-threshold" | "secureexpire" | "croppreset" | "multiplemin" | "multiplemax" | "confirmupload" | "imgonly" | "externalsourcespreferredtypes" | "cameramirror" | "cameracapture" | "sourcelist" | "maxlocalfilesizebytes" | "thumbsize" | "showemptylist" | "uselocalimageeditor" | "usecloudimageeditor" | "cloudimageeditortabs" | "removecopyright" | "imageshrink" | "modalscrolllock" | "modalbackdropstrokes" | "sourcelistwrap" | "remotetabsessionkey" | "cdncname" | "baseurl" | "socialbaseurl" | "securesignature" | "securedeliveryproxy" | "retrythrottledrequestmaxtimes" | "multipartminfilesize" | "multipartchunksize" | "maxconcurrentrequests" | "multipartmaxconcurrentrequests" | "multipartmaxattempts" | "checkforurlduplicates" | "saveurlforrecurrentuploads" | "groupoutput" | "useragentintegration" | "localename" | "secureuploadsexpirethreshold", string>;
export {};
//# sourceMappingURL=Config.d.ts.map

@@ -15,3 +15,2 @@ export class DropArea extends UploaderBlock {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -22,3 +21,3 @@ '*collectionState': import("../../index.js").OutputCollectionState<import("../../index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -25,0 +24,0 @@ '*history': never[];

@@ -112,5 +112,5 @@ // @ts-check

if (item.type === 'url') {
this.addFileFromUrl(item.url, { source: UploadSource.DROP_AREA });
this.api.addFileFromUrl(item.url, { source: UploadSource.DROP_AREA });
} else if (item.type === 'file') {
this.addFileFromObject(item.file, { source: UploadSource.DROP_AREA, fullPath: item.fullPath });
this.api.addFileFromObject(item.file, { source: UploadSource.DROP_AREA, fullPath: item.fullPath });
}

@@ -177,6 +177,6 @@ });

if (event.code === 'Space' || event.code === 'Enter') {
this.openSystemDialog();
this.api.openSystemDialog();
}
} else if (event.type === 'click') {
this.openSystemDialog();
this.api.openSystemDialog();
}

@@ -183,0 +183,0 @@ };

@@ -32,3 +32,2 @@ /** @typedef {{ externalSourceType: string }} ActivityParams */

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -39,3 +38,3 @@ '*collectionState': import("../../index.js").OutputCollectionState<import("../../index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -42,0 +41,0 @@ '*history': never[];

@@ -52,3 +52,3 @@ // @ts-check

const { externalSourceType } = this.activityParams;
this.addFileFromUrl(url, { fileName: filename, source: externalSourceType });
this.api.addFileFromUrl(url, { fileName: filename, source: externalSourceType });
}

@@ -76,2 +76,9 @@

if (!externalSourceType) {
this.$['*currentActivity'] = null;
this.setOrAddState('*modalActive', false);
console.error(`Param "externalSourceType" is required for activity "${this.activityType}"`);
return;
}
this.set$({

@@ -85,2 +92,9 @@ activityCaption: `${externalSourceType?.[0].toUpperCase()}${externalSourceType?.slice(1)}`,

});
this.sub('*currentActivityParams', (val) => {
if (!this.isActivityActive) {
return;
}
this.unmountIframe();
this.mountIframe();
});
this.sub('*currentActivity', (val) => {

@@ -87,0 +101,0 @@ if (val !== this.activityType) {

@@ -38,9 +38,8 @@ export class FileItem extends UploaderBlock {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];
'*collectionState': import("../../index.js").OutputCollectionState<import("../../index.js").OutputCollectionStatus, "maybe-has-group"> | null;
'*groupInfo': import("@uploadcare/upload-client").UploadcareGroup | null;
'*uploadTrigger': Set<string>;
'*uploadTrigger': Set<string>; /** @private */
'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -47,0 +46,0 @@ '*history': never[];

@@ -10,3 +10,2 @@ export class SimpleBtn extends UploaderBlock {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -17,3 +16,3 @@ '*collectionState': import("../../index.js").OutputCollectionState<import("../../index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -20,0 +19,0 @@ '*history': never[];

@@ -15,3 +15,3 @@ // @ts-check

onClick: () => {
this.initFlow();
this.api.initFlow();
},

@@ -18,0 +18,0 @@ 'button-text': '',

@@ -26,3 +26,2 @@ /**

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -33,3 +32,3 @@ '*collectionState': import("../../index.js").OutputCollectionState<import("../../index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -36,0 +35,0 @@ '*history': never[];

@@ -42,3 +42,3 @@ // @ts-check

activate: () => {
this.openSystemDialog();
this.api.openSystemDialog();
return false;

@@ -58,3 +58,3 @@ },

if (supportsCapture) {
this.openSystemDialog({ captureCamera: true });
this.api.openSystemDialog({ captureCamera: true });
}

@@ -61,0 +61,0 @@ return !supportsCapture;

@@ -81,3 +81,3 @@ export const EventType: Readonly<{

*/
emit<T extends "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "change" | "group-created", TDebounce extends number | boolean | undefined>(type: T, payload?: (TDebounce extends false | undefined ? unknown : () => unknown) | undefined, { debounce }?: {
emit<T extends "change" | "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "group-created", TDebounce extends number | boolean | undefined>(type: T, payload?: (TDebounce extends false | undefined ? unknown : () => unknown) | undefined, { debounce }?: {
debounce?: TDebounce | undefined;

@@ -84,0 +84,0 @@ } | undefined): void;

export type UploadCtxProvider = (new () => {
addEventListener<T extends "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "change" | "group-created">(type: T, listener: (e: CustomEvent<import("./EventEmitter.js").EventPayload[T]>) => void, options?: boolean | AddEventListenerOptions): void;
removeEventListener<T_1 extends "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "change" | "group-created">(type: T_1, listener: (e: CustomEvent<import("./EventEmitter.js").EventPayload[T_1]>) => void, options?: boolean | EventListenerOptions): void;
addEventListener<T extends "change" | "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "group-created">(type: T, listener: (e: CustomEvent<import("./EventEmitter.js").EventPayload[T]>) => void, options?: boolean | AddEventListenerOptions): void;
removeEventListener<T_1 extends "change" | "file-added" | "file-removed" | "file-upload-start" | "file-upload-progress" | "file-upload-success" | "file-upload-failed" | "file-url-changed" | "modal-open" | "modal-close" | "done-click" | "upload-click" | "activity-change" | "common-upload-start" | "common-upload-progress" | "common-upload-success" | "common-upload-failed" | "group-created">(type: T_1, listener: (e: CustomEvent<import("./EventEmitter.js").EventPayload[T_1]>) => void, options?: boolean | EventListenerOptions): void;
} & UploadCtxProviderClass) & Omit<typeof UploadCtxProviderClass, "new">;

@@ -5,0 +5,0 @@ /**

@@ -28,3 +28,2 @@ /**

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -35,3 +34,3 @@ '*collectionState': import("../../types").OutputCollectionState<import("../../types").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -38,0 +37,0 @@ '*history': never[];

@@ -38,12 +38,12 @@ // @ts-check

onAdd: () => {
this.initFlow(true);
this.api.initFlow(true);
},
onUpload: () => {
this.emit(EventType.UPLOAD_CLICK);
this.uploadAll();
this.api.uploadAll();
this._throttledHandleCollectionUpdate();
},
onDone: () => {
this.emit(EventType.DONE_CLICK, this.getOutputCollectionState());
this.doneFlow();
this.emit(EventType.DONE_CLICK, this.api.getOutputCollectionState());
this.api.doneFlow();
},

@@ -70,3 +70,3 @@ onCancel: () => {

_updateUploadsState() {
const collectionState = this.getOutputCollectionState();
const collectionState = this.api.getOutputCollectionState();
/** @type {Summary} */

@@ -168,3 +168,3 @@ const summary = {

if (!this.cfg.confirmUpload) {
this.uploadAll();
this.api.uploadAll();
}

@@ -171,0 +171,0 @@ },

@@ -16,3 +16,3 @@ import { UploaderBlock } from '../../abstract/UploaderBlock.js';

let url = this.ref.input['value'];
this.addFileFromUrl(url, { source: UploadSource.URL_TAB });
this.api.addFileFromUrl(url, { source: UploadSource.URL_TAB });
this.$['*currentActivity'] = ActivityBlock.activities.UPLOAD_LIST;

@@ -19,0 +19,0 @@ },

{
"name": "@uploadcare/blocks",
"version": "0.46.0",
"version": "0.47.0",
"description": "Building blocks for Uploadcare products integration",

@@ -5,0 +5,0 @@ "keywords": [

@@ -9,3 +9,2 @@ export class FileUploaderInline extends SolutionBlock {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -16,3 +15,3 @@ '*collectionState': import("./index.js").OutputCollectionState<import("./index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -19,0 +18,0 @@ '*history': never[];

@@ -8,3 +8,2 @@ export class FileUploaderRegular extends SolutionBlock {

'*uploadQueue': import("@uploadcare/upload-client").Queue;
'*uploadCollection': null;
'*collectionErrors': any[];

@@ -15,3 +14,3 @@ '*collectionState': import("./index.js").OutputCollectionState<import("./index.js").OutputCollectionStatus, "maybe-has-group"> | null;

'*secureUploadsManager': import("../../../abstract/SecureUploadsManager.js").SecureUploadsManager | null;
'*currentActivity': string;
'*currentActivity': null;
'*currentActivityParams': {};

@@ -18,0 +17,0 @@ '*history': never[];

@@ -6,2 +6,3 @@ import type { LocaleDefinition } from '../abstract/localeRegistry';

export type { FuncFileValidator, FuncCollectionValidator } from '../abstract/ValidationManager';
export type { UploaderPublicApi } from '../abstract/UploaderPublicApi';

@@ -8,0 +9,0 @@ export type UploadError = import('@uploadcare/upload-client').UploadError;

// @ts-check
/** @type {import('../../../abstract/ValidationManager.js').FuncCollectionValidator} */
export const validateCollectionUploadError = (collection, block) => {
export const validateCollectionUploadError = (collection, api) => {
if (collection.failedCount > 0) {
return {
type: 'SOME_FILES_HAS_ERRORS',
message: block.l10n('some-files-were-not-uploaded'),
message: api.l10n('some-files-were-not-uploaded'),
};
}
};
//@ts-check
/** @type {import('../../../abstract/ValidationManager.js').FuncCollectionValidator} */
export const validateMultiple = (collection, block) => {
export const validateMultiple = (collection, api) => {
const total = collection.totalCount;
const multipleMin = block.cfg.multiple ? block.cfg.multipleMin : 0;
const multipleMax = block.cfg.multiple ? block.cfg.multipleMax : 1;
const multipleMin = api.cfg.multiple ? api.cfg.multipleMin : 0;
const multipleMax = api.cfg.multiple ? api.cfg.multipleMax : 1;
if (multipleMin && total < multipleMin) {
const message = block.l10n('files-count-limit-error-too-few', {
const message = api.l10n('files-count-limit-error-too-few', {
min: multipleMin,

@@ -28,3 +28,3 @@ max: multipleMax,

if (multipleMax && total > multipleMax) {
const message = block.l10n('files-count-limit-error-too-many', {
const message = api.l10n('files-count-limit-error-too-many', {
min: multipleMin,

@@ -31,0 +31,0 @@ max: multipleMax,

@@ -5,5 +5,5 @@ // @ts-check

/** @type {import('../../../abstract/ValidationManager.js').FuncFileValidator} */
export const validateFileType = (outputEntry, block) => {
const imagesOnly = block.cfg.imgOnly;
const accept = block.cfg.accept;
export const validateFileType = (outputEntry, api) => {
const imagesOnly = api.cfg.imgOnly;
const accept = api.cfg.accept;
const allowedFileTypes = mergeFileTypes([...(imagesOnly ? IMAGE_ACCEPT_LIST : []), accept]);

@@ -27,3 +27,3 @@ if (!allowedFileTypes.length) return;

type: 'FORBIDDEN_FILE_TYPE',
message: block.l10n('file-type-not-allowed'),
message: api.l10n('file-type-not-allowed'),
payload: { entry: outputEntry },

@@ -30,0 +30,0 @@ };

@@ -1,3 +0,3 @@

/** @type import('../../../abstract/ValidationManager.js').FuncFileValidator */
/** @type {import('../../../abstract/ValidationManager.js').FuncFileValidator} */
export const validateIsImage: import('../../../abstract/ValidationManager.js').FuncFileValidator;
//# sourceMappingURL=validateIsImage.d.ts.map
// @ts-check
/** @type import('../../../abstract/ValidationManager.js').FuncFileValidator */
export const validateIsImage = (outputEntry, block) => {
const imagesOnly = block.cfg.imgOnly;
/** @type {import('../../../abstract/ValidationManager.js').FuncFileValidator} */
export const validateIsImage = (outputEntry, api) => {
const imagesOnly = api.cfg.imgOnly;
const isImage = outputEntry.isImage;

@@ -22,5 +22,5 @@

type: 'NOT_AN_IMAGE',
message: block.l10n('images-only-accepted'),
message: api.l10n('images-only-accepted'),
payload: { entry: outputEntry },
};
};

@@ -5,4 +5,4 @@ // @ts-check

/** @type {import('../../../abstract/ValidationManager.js').FuncFileValidator} */
export const validateMaxSizeLimit = (outputEntry, block) => {
const maxFileSize = block.cfg.maxLocalFileSizeBytes;
export const validateMaxSizeLimit = (outputEntry, api) => {
const maxFileSize = api.cfg.maxLocalFileSizeBytes;
const fileSize = outputEntry.size;

@@ -12,3 +12,3 @@ if (maxFileSize && fileSize && fileSize > maxFileSize) {

type: 'FILE_SIZE_EXCEEDED',
message: block.l10n('files-max-size-limit-error', { maxFileSize: prettyBytes(maxFileSize) }),
message: api.l10n('files-max-size-limit-error', { maxFileSize: prettyBytes(maxFileSize) }),
payload: { entry: outputEntry },

@@ -15,0 +15,0 @@ };

@@ -5,7 +5,10 @@ // @ts-check

/** @type {import('../../../abstract/ValidationManager.js').FuncFileValidator} */
export const validateUploadError = (outputEntry, block) => {
export const validateUploadError = (outputEntry, api) => {
const { internalId } = outputEntry;
// @ts-expect-error Use private API that is not exposed in the types
const internalEntry = api._uploadCollection.read(internalId);
/** @type {unknown} */
const cause = block.uploadCollection.read(internalId)?.getValue('uploadError');
const cause = internalEntry?.getValue('uploadError');
if (!cause) {

@@ -12,0 +15,0 @@ return;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc