@sprucelabs/spruce-file-utils 15.0.2 → 15.1.1

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.
@@ -1,2 +1,4 @@
1
1
  export { default as FileUploaderImpl } from './uploading/FileUploader';
2
2
  export * from './uploading/FileUploader';
3
+ export { default as ChunkingUploaderImpl } from './uploading/ChunkingUploader';
4
+ export * from './uploading/ChunkingUploader';
@@ -1,2 +1,4 @@
1
1
  export { default as FileUploaderImpl } from './uploading/FileUploader.js';
2
2
  export * from './uploading/FileUploader.js';
3
+ export { default as ChunkingUploaderImpl } from './uploading/ChunkingUploader.js';
4
+ export * from './uploading/ChunkingUploader.js';
@@ -0,0 +1,55 @@
1
+ import { MercuryConnectFactory } from '@sprucelabs/mercury-client';
2
+ import { AbstractEventEmitter } from '@sprucelabs/mercury-event-emitter';
3
+ import { MercuryEventEmitter } from '@sprucelabs/mercury-types';
4
+ import { UploadedFile } from '../files.types';
5
+ export default class ChunkingUploaderImpl extends AbstractEventEmitter<ChunkingUploaderEventContract> implements ChunkingUploader {
6
+ private connectToApi;
7
+ static fetch: typeof fetch;
8
+ static chunkSizeKb: number;
9
+ static Class?: new (connectToApi: MercuryConnectFactory) => ChunkingUploader;
10
+ private restEndpointUrl?;
11
+ private person;
12
+ private proxyToken;
13
+ protected constructor(connectToApi: MercuryConnectFactory);
14
+ static Uploader(connectToApi: MercuryConnectFactory): ChunkingUploaderImpl | ChunkingUploader;
15
+ upload(options: UploadOptions): Promise<{
16
+ file: UploadedFile;
17
+ }>;
18
+ private uploadChunking;
19
+ private splitIntoChunks;
20
+ private get chunkSizeKb();
21
+ private doesSupportChunking;
22
+ private emitUpload;
23
+ private loadRestEndpoint;
24
+ private login;
25
+ private post;
26
+ private get fetch();
27
+ }
28
+ export interface ChunkingUploader extends MercuryEventEmitter<ChunkingUploaderEventContract> {
29
+ upload(options: UploadOptions): Promise<{
30
+ file: UploadedFile;
31
+ }>;
32
+ }
33
+ declare const chunkingUploaderEventContract: {
34
+ eventSignatures: {
35
+ 'did-upload-chunk': {
36
+ emitPayloadSchema: {
37
+ id: string;
38
+ fields: {
39
+ percentComplete: {
40
+ type: "number";
41
+ isRequired: true;
42
+ };
43
+ };
44
+ };
45
+ };
46
+ };
47
+ };
48
+ type ChunkingUploaderEventContract = typeof chunkingUploaderEventContract;
49
+ export interface UploadOptions {
50
+ fileName: string;
51
+ base64: string;
52
+ locationId?: string;
53
+ organizationId?: string;
54
+ }
55
+ export {};
@@ -0,0 +1,162 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { AbstractEventEmitter } from '@sprucelabs/mercury-event-emitter';
11
+ import { buildEventContract, } from '@sprucelabs/mercury-types';
12
+ import { assertOptions, buildSchema } from '@sprucelabs/schema';
13
+ import SpruceError from '../errors/SpruceError.js';
14
+ class ChunkingUploaderImpl extends AbstractEventEmitter {
15
+ constructor(connectToApi) {
16
+ super(chunkingUploaderEventContract);
17
+ this.connectToApi = connectToApi;
18
+ }
19
+ static Uploader(connectToApi) {
20
+ var _a;
21
+ assertOptions({ connectToApi }, ['connectToApi']);
22
+ return new ((_a = this.Class) !== null && _a !== void 0 ? _a : this)(connectToApi);
23
+ }
24
+ upload(options) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const { fileName, locationId, organizationId, base64 } = assertOptions(options, ['fileName', 'base64']);
27
+ yield this.login();
28
+ yield this.loadRestEndpoint();
29
+ const method = this.doesSupportChunking() ? 'uploadChunking' : 'emitUpload';
30
+ const file = yield this[method]({
31
+ fileName,
32
+ locationId,
33
+ organizationId,
34
+ base64,
35
+ });
36
+ return { file };
37
+ });
38
+ }
39
+ uploadChunking(options) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ const { fileName, locationId, organizationId, base64 } = options;
42
+ const totalChunks = Math.ceil(base64.length / (this.chunkSizeKb * 1024));
43
+ const initialize = yield this.post('/initialize', {
44
+ proxyToken: this.proxyToken,
45
+ fileName,
46
+ personId: this.person.id,
47
+ totalChunks,
48
+ locationId,
49
+ organizationId,
50
+ });
51
+ const chunks = this.splitIntoChunks(base64);
52
+ let upload = {};
53
+ for (let i = 0; i < chunks.length; i++) {
54
+ const chunk = chunks[i];
55
+ upload = yield this.post('/upload', {
56
+ chunkIdx: i,
57
+ base64: chunk,
58
+ }, {
59
+ 'x-upload-token': initialize.uploadToken,
60
+ });
61
+ const percentComplete = (i + 1) / totalChunks;
62
+ yield this.emit('did-upload-chunk', {
63
+ percentComplete,
64
+ });
65
+ }
66
+ const file = upload.file;
67
+ return file;
68
+ });
69
+ }
70
+ splitIntoChunks(base64) {
71
+ const chunks = [];
72
+ for (let i = 0; i < base64.length; i += this.chunkSizeKb * 1024) {
73
+ chunks.push(base64.slice(i, i + this.chunkSizeKb * 1024));
74
+ }
75
+ return chunks;
76
+ }
77
+ get chunkSizeKb() {
78
+ return ChunkingUploaderImpl.chunkSizeKb;
79
+ }
80
+ doesSupportChunking() {
81
+ return !!this.restEndpointUrl;
82
+ }
83
+ emitUpload(options) {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ const { organizationId, locationId, base64, fileName } = options;
86
+ const client = yield this.connectToApi();
87
+ const [{ file }] = yield client.emitAndFlattenResponses('files.upload::v2022_05_13', {
88
+ target: {
89
+ organizationId,
90
+ locationId,
91
+ },
92
+ payload: {
93
+ base64Body: base64,
94
+ name: fileName,
95
+ },
96
+ });
97
+ return file;
98
+ });
99
+ }
100
+ loadRestEndpoint() {
101
+ return __awaiter(this, void 0, void 0, function* () {
102
+ const client = yield this.connectToApi();
103
+ const [{ restEndpointUrl }] = yield client.emitAndFlattenResponses('files.get-upload-endpoint::v2022_05_13');
104
+ this.restEndpointUrl = restEndpointUrl;
105
+ });
106
+ }
107
+ login() {
108
+ return __awaiter(this, void 0, void 0, function* () {
109
+ const client = yield this.connectToApi();
110
+ const [{ type, auth }] = yield client.emitAndFlattenResponses('whoami::v2020_12_25');
111
+ if (type === 'anonymous') {
112
+ throw new SpruceError({
113
+ code: 'UNAUTHORIZED',
114
+ friendlyMessage: `You have to be logged in before you can upload any files.`,
115
+ endpoint: 'whoami::v2020_12_25',
116
+ });
117
+ }
118
+ this.person = auth.person;
119
+ this.proxyToken = client.getProxyToken();
120
+ return client;
121
+ });
122
+ }
123
+ post(path, postBody, headers) {
124
+ return __awaiter(this, void 0, void 0, function* () {
125
+ const response = yield this.fetch(this.restEndpointUrl + path, {
126
+ headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
127
+ method: 'POST',
128
+ body: JSON.stringify(postBody),
129
+ });
130
+ const body = yield response.json();
131
+ if (response.status !== 200) {
132
+ throw new SpruceError({
133
+ code: response.status === 400 ? 'BAD_REQUEST' : 'UNAUTHORIZED',
134
+ friendlyMessage: body.errorMessage,
135
+ endpoint: this.restEndpointUrl + path,
136
+ });
137
+ }
138
+ return body;
139
+ });
140
+ }
141
+ get fetch() {
142
+ return ChunkingUploaderImpl.fetch;
143
+ }
144
+ }
145
+ ChunkingUploaderImpl.fetch = fetch;
146
+ ChunkingUploaderImpl.chunkSizeKb = 1024;
147
+ export default ChunkingUploaderImpl;
148
+ const chunkingUploaderEventContract = buildEventContract({
149
+ eventSignatures: {
150
+ 'did-upload-chunk': {
151
+ emitPayloadSchema: buildSchema({
152
+ id: 'didUploadChunkPayload',
153
+ fields: {
154
+ percentComplete: {
155
+ type: 'number',
156
+ isRequired: true,
157
+ },
158
+ },
159
+ }),
160
+ },
161
+ },
162
+ });
@@ -1,2 +1,4 @@
1
1
  export { default as FileUploaderImpl } from './uploading/FileUploader';
2
2
  export * from './uploading/FileUploader';
3
+ export { default as ChunkingUploaderImpl } from './uploading/ChunkingUploader';
4
+ export * from './uploading/ChunkingUploader';
@@ -17,7 +17,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.FileUploaderImpl = void 0;
20
+ exports.ChunkingUploaderImpl = exports.FileUploaderImpl = void 0;
21
21
  var FileUploader_1 = require("./uploading/FileUploader");
22
22
  Object.defineProperty(exports, "FileUploaderImpl", { enumerable: true, get: function () { return __importDefault(FileUploader_1).default; } });
23
23
  __exportStar(require("./uploading/FileUploader"), exports);
24
+ var ChunkingUploader_1 = require("./uploading/ChunkingUploader");
25
+ Object.defineProperty(exports, "ChunkingUploaderImpl", { enumerable: true, get: function () { return __importDefault(ChunkingUploader_1).default; } });
26
+ __exportStar(require("./uploading/ChunkingUploader"), exports);
@@ -0,0 +1,55 @@
1
+ import { MercuryConnectFactory } from '@sprucelabs/mercury-client';
2
+ import { AbstractEventEmitter } from '@sprucelabs/mercury-event-emitter';
3
+ import { MercuryEventEmitter } from '@sprucelabs/mercury-types';
4
+ import { UploadedFile } from '../files.types';
5
+ export default class ChunkingUploaderImpl extends AbstractEventEmitter<ChunkingUploaderEventContract> implements ChunkingUploader {
6
+ private connectToApi;
7
+ static fetch: typeof fetch;
8
+ static chunkSizeKb: number;
9
+ static Class?: new (connectToApi: MercuryConnectFactory) => ChunkingUploader;
10
+ private restEndpointUrl?;
11
+ private person;
12
+ private proxyToken;
13
+ protected constructor(connectToApi: MercuryConnectFactory);
14
+ static Uploader(connectToApi: MercuryConnectFactory): ChunkingUploaderImpl | ChunkingUploader;
15
+ upload(options: UploadOptions): Promise<{
16
+ file: UploadedFile;
17
+ }>;
18
+ private uploadChunking;
19
+ private splitIntoChunks;
20
+ private get chunkSizeKb();
21
+ private doesSupportChunking;
22
+ private emitUpload;
23
+ private loadRestEndpoint;
24
+ private login;
25
+ private post;
26
+ private get fetch();
27
+ }
28
+ export interface ChunkingUploader extends MercuryEventEmitter<ChunkingUploaderEventContract> {
29
+ upload(options: UploadOptions): Promise<{
30
+ file: UploadedFile;
31
+ }>;
32
+ }
33
+ declare const chunkingUploaderEventContract: {
34
+ eventSignatures: {
35
+ 'did-upload-chunk': {
36
+ emitPayloadSchema: {
37
+ id: string;
38
+ fields: {
39
+ percentComplete: {
40
+ type: "number";
41
+ isRequired: true;
42
+ };
43
+ };
44
+ };
45
+ };
46
+ };
47
+ };
48
+ type ChunkingUploaderEventContract = typeof chunkingUploaderEventContract;
49
+ export interface UploadOptions {
50
+ fileName: string;
51
+ base64: string;
52
+ locationId?: string;
53
+ organizationId?: string;
54
+ }
55
+ export {};
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const mercury_event_emitter_1 = require("@sprucelabs/mercury-event-emitter");
7
+ const mercury_types_1 = require("@sprucelabs/mercury-types");
8
+ const schema_1 = require("@sprucelabs/schema");
9
+ const SpruceError_1 = __importDefault(require("../errors/SpruceError"));
10
+ class ChunkingUploaderImpl extends mercury_event_emitter_1.AbstractEventEmitter {
11
+ constructor(connectToApi) {
12
+ super(chunkingUploaderEventContract);
13
+ this.connectToApi = connectToApi;
14
+ }
15
+ static Uploader(connectToApi) {
16
+ (0, schema_1.assertOptions)({ connectToApi }, ['connectToApi']);
17
+ return new (this.Class ?? this)(connectToApi);
18
+ }
19
+ async upload(options) {
20
+ const { fileName, locationId, organizationId, base64 } = (0, schema_1.assertOptions)(options, ['fileName', 'base64']);
21
+ await this.login();
22
+ await this.loadRestEndpoint();
23
+ const method = this.doesSupportChunking() ? 'uploadChunking' : 'emitUpload';
24
+ const file = await this[method]({
25
+ fileName,
26
+ locationId,
27
+ organizationId,
28
+ base64,
29
+ });
30
+ return { file };
31
+ }
32
+ async uploadChunking(options) {
33
+ const { fileName, locationId, organizationId, base64 } = options;
34
+ const totalChunks = Math.ceil(base64.length / (this.chunkSizeKb * 1024));
35
+ const initialize = await this.post('/initialize', {
36
+ proxyToken: this.proxyToken,
37
+ fileName,
38
+ personId: this.person.id,
39
+ totalChunks,
40
+ locationId,
41
+ organizationId,
42
+ });
43
+ const chunks = this.splitIntoChunks(base64);
44
+ let upload = {};
45
+ for (let i = 0; i < chunks.length; i++) {
46
+ const chunk = chunks[i];
47
+ upload = await this.post('/upload', {
48
+ chunkIdx: i,
49
+ base64: chunk,
50
+ }, {
51
+ 'x-upload-token': initialize.uploadToken,
52
+ });
53
+ const percentComplete = (i + 1) / totalChunks;
54
+ await this.emit('did-upload-chunk', {
55
+ percentComplete,
56
+ });
57
+ }
58
+ const file = upload.file;
59
+ return file;
60
+ }
61
+ splitIntoChunks(base64) {
62
+ const chunks = [];
63
+ for (let i = 0; i < base64.length; i += this.chunkSizeKb * 1024) {
64
+ chunks.push(base64.slice(i, i + this.chunkSizeKb * 1024));
65
+ }
66
+ return chunks;
67
+ }
68
+ get chunkSizeKb() {
69
+ return ChunkingUploaderImpl.chunkSizeKb;
70
+ }
71
+ doesSupportChunking() {
72
+ return !!this.restEndpointUrl;
73
+ }
74
+ async emitUpload(options) {
75
+ const { organizationId, locationId, base64, fileName } = options;
76
+ const client = await this.connectToApi();
77
+ const [{ file }] = await client.emitAndFlattenResponses('files.upload::v2022_05_13', {
78
+ target: {
79
+ organizationId,
80
+ locationId,
81
+ },
82
+ payload: {
83
+ base64Body: base64,
84
+ name: fileName,
85
+ },
86
+ });
87
+ return file;
88
+ }
89
+ async loadRestEndpoint() {
90
+ const client = await this.connectToApi();
91
+ const [{ restEndpointUrl }] = await client.emitAndFlattenResponses('files.get-upload-endpoint::v2022_05_13');
92
+ this.restEndpointUrl = restEndpointUrl;
93
+ }
94
+ async login() {
95
+ const client = await this.connectToApi();
96
+ const [{ type, auth }] = await client.emitAndFlattenResponses('whoami::v2020_12_25');
97
+ if (type === 'anonymous') {
98
+ throw new SpruceError_1.default({
99
+ code: 'UNAUTHORIZED',
100
+ friendlyMessage: `You have to be logged in before you can upload any files.`,
101
+ endpoint: 'whoami::v2020_12_25',
102
+ });
103
+ }
104
+ this.person = auth.person;
105
+ this.proxyToken = client.getProxyToken();
106
+ return client;
107
+ }
108
+ async post(path, postBody, headers) {
109
+ const response = await this.fetch(this.restEndpointUrl + path, {
110
+ headers: {
111
+ 'Content-Type': 'application/json',
112
+ ...headers,
113
+ },
114
+ method: 'POST',
115
+ body: JSON.stringify(postBody),
116
+ });
117
+ const body = await response.json();
118
+ if (response.status !== 200) {
119
+ throw new SpruceError_1.default({
120
+ code: response.status === 400 ? 'BAD_REQUEST' : 'UNAUTHORIZED',
121
+ friendlyMessage: body.errorMessage,
122
+ endpoint: this.restEndpointUrl + path,
123
+ });
124
+ }
125
+ return body;
126
+ }
127
+ get fetch() {
128
+ return ChunkingUploaderImpl.fetch;
129
+ }
130
+ }
131
+ ChunkingUploaderImpl.fetch = fetch;
132
+ ChunkingUploaderImpl.chunkSizeKb = 1024;
133
+ exports.default = ChunkingUploaderImpl;
134
+ const chunkingUploaderEventContract = (0, mercury_types_1.buildEventContract)({
135
+ eventSignatures: {
136
+ 'did-upload-chunk': {
137
+ emitPayloadSchema: (0, schema_1.buildSchema)({
138
+ id: 'didUploadChunkPayload',
139
+ fields: {
140
+ percentComplete: {
141
+ type: 'number',
142
+ isRequired: true,
143
+ },
144
+ },
145
+ }),
146
+ },
147
+ },
148
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sprucelabs/spruce-file-utils",
3
3
  "description": "Utils for working with files and Sprucebot.",
4
- "version": "15.0.2",
4
+ "version": "15.1.1",
5
5
  "skill": {
6
6
  "namespace": "files"
7
7
  },
@@ -25,6 +25,11 @@
25
25
  "build/uploading/FileUploader.d.ts",
26
26
  "build/uploading/FileUploader.js",
27
27
 
28
+ "build/esm/uploading/ChunkingUploader.d.ts",
29
+ "build/esm/uploading/ChunkingUploader.js",
30
+ "build/uploading/ChunkingUploader.d.ts",
31
+ "build/uploading/ChunkingUploader.js",
32
+
28
33
  "build/esm/uploading/LocalUploadStrategy.d.ts",
29
34
  "build/esm/uploading/LocalUploadStrategy.js",
30
35
  "build/uploading/LocalUploadStrategy.d.ts",
@@ -42,10 +47,11 @@
42
47
  },
43
48
  "dependencies": {
44
49
  "@sprucelabs/schema": "latest",
50
+ "@sprucelabs/mercury-event-emitter": "latest",
45
51
  "aws-sdk": "^2.1558.0",
46
52
  "file-type": "16.5.3",
47
- "mime-types": "^2.1.35",
48
- "uuid": "^9.0.1"
53
+ "@types/mime-types": "^3.0.1",
54
+ "uuid": "^11.1.0"
49
55
  },
50
56
  "engines": {
51
57
  "yarn": "1.x"