kraken 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,34 +1,37 @@
1
1
  # Node.js module for Kraken.io API
2
2
 
3
- [![Build Status](https://app.travis-ci.com/kraken-io/kraken-node.svg?branch=master)](https://app.travis-ci.com/kraken-io/kraken-node)
3
+ [![Node.js CI](https://github.com/kraken-io/kraken-node/actions/workflows/node.js.yml/badge.svg?branch=master)](https://github.com/kraken-io/kraken-node/actions/workflows/node.js.yml)
4
4
 
5
5
  With this Node module you can plug into the power and speed of [Kraken.io](http://kraken.io/) Image Optimizer.
6
6
 
7
- - [Node.js module for Kraken.io API](#nodejs-module-for-krakenio-api)
8
- - [Installation](#installation)
9
- - [Requirements](#requirements)
10
- - [Dependencies](#dependencies)
11
- - [Getting Started](#getting-started)
12
- - [Downloading Images](#downloading-images)
13
- - [How to use](#how-to-use)
14
- - [Wait and Callback URL](#wait-and-callback-url)
15
- - [Wait option](#wait-option)
16
- - [Callback URL](#callback-url)
17
- - [Promises](#promises)
18
- - [Async/Await](#asyncawait)
19
- - [Authentication](#authentication)
20
- - [Usage - Image URL](#usage---image-url)
21
- - [Usage - Image Upload](#usage---image-upload)
22
- - [Usage - User status](#usage---user-status)
23
- - [Lossy Optimization](#lossy-optimization)
24
- - [PNG Images](#png-images)
25
- - [JPEG Images](#jpeg-images)
26
- - [Image Resizing](#image-resizing)
27
- - [WebP Compression](#webp-compression)
28
- - [Amazon S3 and Rackspace Cloud Files](#amazon-s3-and-rackspace-cloud-files)
29
- - [Amazon S3](#amazon-s3)
30
- - [Rackspace Cloud Files](#rackspace-cloud-files)
31
- - [LICENSE - MIT](#license---mit)
7
+ - [Node.js module for Kraken.io API](#nodejs-module-for-krakenio-api)
8
+ - [Installation](#installation)
9
+ - [Requirements](#requirements)
10
+ - [Dependencies](#dependencies)
11
+ - [Getting Started](#getting-started)
12
+ - [Downloading Images](#downloading-images)
13
+ - [How to use](#how-to-use)
14
+ - [Wait and Callback URL](#wait-and-callback-url)
15
+ - [Wait option](#wait-option)
16
+ - [Callback URL](#callback-url)
17
+ - [Promises](#promises)
18
+ - [Async/Await](#asyncawait)
19
+ - [Error Handling](#error-handling)
20
+ - [Authentication](#authentication)
21
+ - [Usage - Image URL](#usage---image-url)
22
+ - [Usage - Image Upload](#usage---image-upload)
23
+ - [Usage - User status](#usage---user-status)
24
+ - [Lossy Optimization](#lossy-optimization)
25
+ - [PNG Images](#png-images)
26
+ - [JPEG Images](#jpeg-images)
27
+ - [Image Resizing](#image-resizing)
28
+ - [WebP Compression](#webp-compression)
29
+ - [PDF Compression](#pdf-compression)
30
+ - [Amazon S3, Rackspace Cloud Files, and Google Cloud Storage](#amazon-s3-rackspace-cloud-files-and-google-cloud-storage)
31
+ - [Amazon S3](#amazon-s3)
32
+ - [Rackspace Cloud Files](#rackspace-cloud-files)
33
+ - [Google Cloud Storage](#google-cloud-storage)
34
+ - [LICENSE - MIT](#license---mit)
32
35
 
33
36
  ## Installation
34
37
 
@@ -36,7 +39,8 @@ With this Node module you can plug into the power and speed of [Kraken.io](http:
36
39
 
37
40
  ## Requirements
38
41
 
39
- - Minimum NodeJS version: `12.20.0`
42
+ - Node.js `12.20.0` or later
43
+ - Tested on Node.js 12, 14, 16, 18, 20, 22, 24 and 26
40
44
 
41
45
  ## Dependencies
42
46
 
@@ -172,6 +176,24 @@ async function exampleAsynFunction() {
172
176
  exampleAsynFunction()
173
177
  ```
174
178
 
179
+ ## Error Handling
180
+
181
+ Errors returned by the Kraken API (for example a wrong API key) and network errors do not reject the promise. The promise resolves with a response where `success` is `false`, so always check `success`:
182
+
183
+ ```javascript
184
+ kraken.userStatus().then((status) => {
185
+ if (status.success) {
186
+ console.log('Kraken user status:', status)
187
+ } else {
188
+ console.error('Kraken error:', status.message || status.error)
189
+ }
190
+ })
191
+ ```
192
+
193
+ With a callback, the response comes as the second argument in the same way. The first argument (`err`) is only set when the request could not be made, for example when an upload file does not exist.
194
+
195
+ The promise is rejected only when the request could not be made and no callback was given.
196
+
175
197
  ## Authentication
176
198
 
177
199
  The first step is to authenticate to Kraken API by providing your unique API Key and API Secret while creating a new Kraken instance:
@@ -212,11 +234,12 @@ kraken.url(opts, function (err, data) {
212
234
  })
213
235
 
214
236
  // with promises
215
- kraken.url(opts)
216
- .then(data => {
237
+ kraken
238
+ .url(opts)
239
+ .then((data) => {
217
240
  console.log('Success. Optimized image URL: %s', data.kraked_url)
218
241
  })
219
- .catch(err => {
242
+ .catch((err) => {
220
243
  console.log('Failed. Error message: %s', err)
221
244
  })
222
245
  ```
@@ -250,7 +273,7 @@ If you want to upload your images directly to Kraken API use the `kraken.upload(
250
273
  `file` parameter have next options:
251
274
 
252
275
  - `String` - if file parameter is a string type, then it will be interpreted as a path to file and will be loaded using `fs.createReadStream()` function
253
- - `Stream` | `Buffer` | `String` - file content, will be generated random filename
276
+ - `Stream` | `Buffer` - file content, will be generated random filename
254
277
  - `Object` with next properties:
255
278
  - _mandatory_ `path` or `value` - if `path` is present, `value` is ignored
256
279
  - `path` - path to file, will be loaded using `fs.createReadStream()` function
@@ -283,11 +306,12 @@ kraken.upload(opts, function (err, data) {
283
306
  })
284
307
 
285
308
  // with promise
286
- kraken.upload(opts)
287
- .then(data => {
309
+ kraken
310
+ .upload(opts)
311
+ .then((data) => {
288
312
  console.log('Success. Optimized image URL: %s', data.kraked_url)
289
313
  })
290
- .catch(err => {
314
+ .catch((err) => {
291
315
  console.log('Failed. Error message: %s', err)
292
316
  })
293
317
  ```
@@ -310,11 +334,12 @@ kraken.upload(opts, function (err, data) {
310
334
  })
311
335
 
312
336
  // with promise
313
- kraken.upload(opts)
314
- .then(data => {
337
+ kraken
338
+ .upload(opts)
339
+ .then((data) => {
315
340
  console.log('Success. Optimized image URL: %s', data.kraked_url)
316
341
  })
317
- .catch(err => {
342
+ .catch((err) => {
318
343
  console.log('Failed. Error message: %s', err)
319
344
  })
320
345
  ```
@@ -337,11 +362,12 @@ kraken.upload(opts, function (err, data) {
337
362
  })
338
363
 
339
364
  // with promise
340
- kraken.upload(opts)
341
- .then(data => {
365
+ kraken
366
+ .upload(opts)
367
+ .then((data) => {
342
368
  console.log('Success. Optimized image URL: %s', data.kraked_url)
343
369
  })
344
- .catch(err => {
370
+ .catch((err) => {
345
371
  console.log('Failed. Error message: %s', err)
346
372
  })
347
373
  ```
@@ -367,11 +393,12 @@ kraken.upload(opts, function (err, data) {
367
393
  })
368
394
 
369
395
  // with promise
370
- kraken.upload(opts)
371
- .then(data => {
396
+ kraken
397
+ .upload(opts)
398
+ .then((data) => {
372
399
  console.log('Success. Optimized image URL: %s', data.kraked_url)
373
400
  })
374
- .catch(err => {
401
+ .catch((err) => {
375
402
  console.log('Failed. Error message: %s', err)
376
403
  })
377
404
  ```
@@ -382,8 +409,8 @@ Object as file options with buffer as value:
382
409
  var opts = {
383
410
  file: {
384
411
  value: fs.readFileSync('file.jpg'),
385
- fileName: 'new_file_name.jpg'
386
- }
412
+ filename: 'new_file_name.jpg'
413
+ },
387
414
  wait: true
388
415
  }
389
416
 
@@ -444,8 +471,9 @@ kraken.userStatus(function (err, data) {
444
471
  }) //formatBytes(data,2)
445
472
 
446
473
  // with promise
447
- kraken.userStatus()
448
- .then(data => {
474
+ kraken
475
+ .userStatus()
476
+ .then((data) => {
449
477
  console.log('Success', {
450
478
  success: data.success,
451
479
  active: data.active,
@@ -454,9 +482,9 @@ kraken.userStatus()
454
482
  quota_remaining: formatBytes(data.quota_remaining, 2)
455
483
  })
456
484
  })
457
- .catch(err => {
485
+ .catch((err) => {
458
486
  console.log('Failed. Error message: %s', err)
459
- })//formatBytes(data,2)
487
+ }) //formatBytes(data,2)
460
488
 
461
489
  // Optional function which will format the bytes value
462
490
  function formatBytes(value, decimal) {
@@ -523,11 +551,12 @@ kraken.upload(opts, function (err, data) {
523
551
  })
524
552
 
525
553
  // with promise
526
- kraken.upload(opts)
527
- .then(data => {
554
+ kraken
555
+ .upload(opts)
556
+ .then((data) => {
528
557
  console.log('Success. Optimized image URL: %s', data.kraked_url)
529
558
  })
530
- .catch(err => {
559
+ .catch((err) => {
531
560
  console.log('Failed. Error message: %s', err)
532
561
  })
533
562
  ```
@@ -535,8 +564,8 @@ kraken.upload(opts)
535
564
  The `strategy` property can have one of the following values:
536
565
 
537
566
  - `exact` - Resize by exact width/height. No aspect ratio will be maintained.
538
- - `portrait` - Exact width will be set, height will be adjusted according to aspect ratio.
539
- - `landscape` - Exact height will be set, width will be adjusted according to aspect ratio.
567
+ - `portrait` - Exact height will be set, width will be adjusted according to aspect ratio.
568
+ - `landscape` - Exact width will be set, height will be adjusted according to aspect ratio.
540
569
  - `auto` - The best strategy (portrait or landscape) will be selected for a given image according to aspect ratio.
541
570
  - `crop` - This option will crop your image to the exact size you specify with no distortion.
542
571
 
@@ -544,20 +573,67 @@ The `strategy` property can have one of the following values:
544
573
 
545
574
  WebP is a new image format introduced by Google in 2010 which supports both lossy and lossless compression. According to [Google](https://developers.google.com/speed/webp/), WebP lossless images are **26% smaller** in size compared to PNGs and WebP lossy images are **25-34% smaller** in size compared to JPEG images.
546
575
 
547
- To recompress your PNG or JPEG files into WebP format simply set `"webp": true` flag in your request JSON. You can also optionally set `"lossy": true` flag to leverage WebP's lossy compression:
576
+ WebP's lossy compression:WebP compression no longer requires setting `"webp": true` . Instead, you should make a standard optimization request, and Kraken.io will handle WebP conversion based on your configured settings.
577
+
578
+ ### Convert to WebP format
548
579
 
549
580
  ```javascript
550
581
  var opts = {
551
582
  file: '/path/to/image/file.jpg',
552
583
  wait: true,
553
- webp: true,
584
+ lossy: true,
585
+ convert: {
586
+ format: 'webp'
587
+ }
588
+ }
589
+ ```
590
+
591
+ ### Optimize WebP Image
592
+
593
+ ```javascript
594
+ var opts = {
595
+ file: '/path/to/image/file.webp',
596
+ wait: true,
554
597
  lossy: true
555
598
  }
556
599
  ```
557
600
 
558
- ## Amazon S3 and Rackspace Cloud Files
601
+ ## PDF Compression
559
602
 
560
- Kraken API allows you to store optimized images directly in your S3 bucket or Cloud Files container. With just a few additional parameters your optimized images will be pushed to your external storage in no time.
603
+ Kraken.io now supports PDF compression, allowing you to optimize PDF files with minimal loss of quality.
604
+
605
+ Kraken API automatically determines the optimal compression settings based on the content type of the PDF (e.g., image-heavy, text-heavy, or mixed content). Additionally, users can optionally provide custom parameters to further control the compression process.
606
+
607
+ ```javascript
608
+ var opts = {
609
+ file: '/path/to/image/document.pdf',
610
+ wait: true
611
+ }
612
+ ```
613
+
614
+ **Optional Parameters:**
615
+
616
+ [API Docs for PDF Compression](https://kraken.io/docs/pdf-compression)
617
+
618
+ - `level` - Optimization level for the PDF. Available options are `screen`, `ebook`, `printer` and `prepress`. **Overrides DPI values**.
619
+ - `quality` - JPEG quality for embedded images. Acceptable values: **1-100**. Higher values preserve more detail but increase file size. Default is **65**.
620
+ - `dpi` - Resolution for images within the PDF. Default value is calculated based on the PDF type. Adjust this value based on your desired output quality.
621
+ - `downsampleType` - Method used to downsample images. Available options are `bicubic`, `average` and `subsample`
622
+
623
+ ```javascript
624
+ var opts = {
625
+ file: '/path/to/image/file.webp',
626
+ wait: true,
627
+ level: 'ebook',
628
+ quality: 60,
629
+ dpi: 150,
630
+ downsampleType: 'bicubic'
631
+ }
632
+ ```
633
+
634
+ ## Amazon S3, Rackspace Cloud Files and Google Cloud Storage
635
+
636
+ Kraken API allows you to store optimized images directly in your S3 bucket, Google Cloud Storage or Cloud Files container. With just a few additional parameters your optimized images will be pushed to your external storage in no time.
561
637
 
562
638
  ### Amazon S3
563
639
 
@@ -604,11 +680,12 @@ kraken.upload(opts, function (err, data) {
604
680
  })
605
681
 
606
682
  // with promise
607
- kraken.upload(opts)
608
- .then(data => {
683
+ kraken
684
+ .upload(opts)
685
+ .then((data) => {
609
686
  console.log('Success. Optimized image URL: %s', data.kraked_url)
610
687
  })
611
- .catch(err => {
688
+ .catch((err) => {
612
689
  console.log('Failed. Error message: %s', err)
613
690
  })
614
691
  ```
@@ -653,7 +730,6 @@ var opts = {
653
730
  }
654
731
  }
655
732
 
656
-
657
733
  // with callback
658
734
  kraken.upload(opts, function (err, data) {
659
735
  if (err) {
@@ -664,11 +740,12 @@ kraken.upload(opts, function (err, data) {
664
740
  })
665
741
 
666
742
  // with promise
667
- kraken.upload(opts)
668
- .then(data => {
743
+ kraken
744
+ .upload(opts)
745
+ .then((data) => {
669
746
  console.log('Success. Optimized image URL: %s', data.kraked_url)
670
747
  })
671
- .catch(err => {
748
+ .catch((err) => {
672
749
  console.log('Failed. Error message: %s', err)
673
750
  })
674
751
  ```
@@ -685,6 +762,90 @@ If your container is not CDN-enabled `kraked_url` will point to the optimized im
685
762
  kraked_url: 'http://dl.kraken.io/ecdfa5c55d5668b1b5fe9e420554c4ee/file.jpg'
686
763
  ```
687
764
 
765
+ ### Google Cloud Storage
766
+
767
+ Kraken.io API allows you to store optimized images directly in your Google Cloud Storage (GCS) bucket. Follow the steps below to configure your GCS integration and securely store your optimized images.
768
+
769
+ #### Prerequisites:
770
+
771
+ Ensure you have access to Google Cloud Platform (GCP) and an active project where you will store your images.
772
+
773
+ #### Mandatory Parameters:
774
+
775
+ - `gcs_store.bucket` - Name of the destination bucket on your Google Cloud Storage account.
776
+ - `gcs_store.credentials` - Your service account credentials (JSON format) to authenticate with GCS.
777
+
778
+ #### Optional Parameters:
779
+
780
+ - `gcs_store.path` - Destination path in your GCS bucket (e.g., "images/layout/header.jpg"). Defaults to root `/`.
781
+ - `gcs_store.acl` - Permissions of the destination object. This can be "publicRead" or "private". Defaults to "private".
782
+ - `gcs_store.metadata` - Metadata you would like to assign to your GCS object (optimized image).
783
+
784
+ #### Important:
785
+
786
+ Make sure your Google Cloud Storage bucket has the appropriate permissions set to allow Kraken.io API to store images.
787
+
788
+ #### Step 1: Creating a Google Cloud Storage Bucket
789
+
790
+ 1. Log in to your Google Cloud Console.
791
+ 2. Navigate to the "Storage" section and select "Browser."
792
+ 3. Click "Create bucket" and follow the prompts.
793
+ 4. Note the bucket name for later use.
794
+
795
+ #### Step 2: Obtaining GCS Credentials
796
+
797
+ To interact with GCS through the API, you need appropriate credentials as a service account key:
798
+
799
+ 1. Go to "IAM & Admin" in Google Cloud Console.
800
+ 2. Select "Service Accounts" and click "Create Service Account."
801
+ 3. Enter a name and description for the service account.
802
+ 4. Assign necessary roles like "Storage Object Admin" or "Storage Object Creator."
803
+ 5. Click "Create Key" and choose JSON type. This will download a JSON file with your credentials.
804
+ 6. Securely store this JSON file. It contains sensitive information that allows access to your GCS resources.
805
+
806
+ #### Step 3: Configuring Your Kraken.io API Request
807
+
808
+ Include the necessary details in your Kraken.io API request to store the optimized image directly in your GCS bucket. Insert the JSON file's contents into the `credentials` property inside `gcs_store`.
809
+
810
+ ```javascript
811
+ const fs = require('fs').promises;
812
+ const Kraken = require("kraken");
813
+
814
+ (async () => {
815
+ try {
816
+ const kraken = new Kraken({
817
+ api_key: "your_api_key",
818
+ api_secret: "your_api_secret"
819
+ });
820
+
821
+ const credentials = JSON.parse(await fs.readFile('path/to/your/credentials.json', 'utf8'));
822
+
823
+ const params = {
824
+ url: "https://example.com/image.png",
825
+ wait: true,
826
+ lossy: true,
827
+ gcs_store: {
828
+ acl: "private",
829
+ bucket: "your-bucket-name",
830
+ path: "path/to/your/image.png",
831
+ credentials
832
+ }
833
+ };
834
+
835
+ kraken.url(params, function (status) {
836
+ if (status.success) {
837
+ console.log("Success. Optimized image URL: %s", status.kraked_url);
838
+ } else {
839
+ console.log("Fail. Error message: %s", status.message);
840
+ }
841
+ });
842
+ } catch (error) {
843
+ console.error("Error:", error);
844
+ }
845
+ })();
846
+ }
847
+ ```
848
+
688
849
  # LICENSE - MIT
689
850
 
690
851
  Copyright (c) 2013-2021 Nekkra UG
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kraken",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "author": {
5
5
  "name": "Kraken.io",
6
6
  "email": "support@kraken.io"
@@ -8,6 +8,9 @@
8
8
  "description": "Plug into the power and speed of Kraken.io Image Optimizer",
9
9
  "homepage": "https://github.com/kraken-io/kraken-node",
10
10
  "main": "./src/kraken",
11
+ "files": [
12
+ "src"
13
+ ],
11
14
  "repository": {
12
15
  "type": "git",
13
16
  "url": "https://github.com/kraken-io/kraken-node.git"
@@ -19,12 +22,12 @@
19
22
  "image optimiser"
20
23
  ],
21
24
  "license": "MIT",
22
- "engine": {
25
+ "engines": {
23
26
  "node": ">=12.20.0"
24
27
  },
25
28
  "dependencies": {
26
- "axios": "^0.24.0",
27
- "form-data": "^4.0.0"
29
+ "axios": "^1.21.1",
30
+ "form-data": "^4.0.1"
28
31
  },
29
32
  "devDependencies": {
30
33
  "dotenv": "^16.3.1",
@@ -38,6 +41,9 @@
38
41
  },
39
42
  "jest": {
40
43
  "collectCoverage": true,
44
+ "collectCoverageFrom": [
45
+ "src/**/*.js"
46
+ ],
41
47
  "coverageDirectory": "coverage",
42
48
  "coverageProvider": "v8",
43
49
  "coverageReporters": [
@@ -45,7 +51,15 @@
45
51
  "text",
46
52
  "lcov",
47
53
  "clover"
48
- ]
54
+ ],
55
+ "coverageThreshold": {
56
+ "global": {
57
+ "branches": 100,
58
+ "functions": 100,
59
+ "lines": 100,
60
+ "statements": 100
61
+ }
62
+ }
49
63
  },
50
64
  "eslintConfig": {
51
65
  "parserOptions": {
package/src/kraken.js CHANGED
@@ -31,12 +31,12 @@ function convertError(err) {
31
31
 
32
32
  // In some cases err.response can be empty (network errors and etc.)
33
33
  if (res) {
34
- // Got data from server response
35
- if (res.data) {
34
+ // Got JSON data from server response
35
+ if (res.data && typeof res.data === 'object') {
36
36
  return new KrakenResponse(res.data) // Standard Kraken error
37
37
  }
38
38
 
39
- // Server response without data or it can't be processed by axios
39
+ // Server response without JSON data (empty body, HTML error page and etc.)
40
40
  return new KrakenResponse({
41
41
  success: false,
42
42
  error: err.toString(),
@@ -65,14 +65,12 @@ function axiosPost(url, data, axiosOpts, cb) {
65
65
  .catch(convertError) // Errors processing
66
66
 
67
67
  if (cb) {
68
- // Callback processing
69
- result
70
- .then(function (status) {
71
- cb(null, status)
72
- }) // Result to callback
73
- .catch(function (err) {
74
- cb(err, null)
75
- }) // Error to callback
68
+ // Callback processing. `result` never rejects: errors are converted
69
+ // to a KrakenResponse above. Calling `cb` once also means an error
70
+ // thrown inside `cb` is not passed back to `cb` a second time.
71
+ result.then(function (status) {
72
+ cb(null, status)
73
+ }) // Result to callback
76
74
  }
77
75
  return result
78
76
  }
@@ -91,7 +89,7 @@ class Kraken {
91
89
  * @memberof Kraken
92
90
  */
93
91
  constructor(keyOrAuth, secret = null) {
94
- if(!keyOrAuth) throw new Error('Please provide an API key');
92
+ if (!keyOrAuth) throw new Error('Please provide an API key')
95
93
 
96
94
  if (keyOrAuth instanceof KrakenAuth) {
97
95
  this.auth = keyOrAuth
@@ -102,9 +100,8 @@ class Kraken {
102
100
  typeof secret === 'string'
103
101
  ) {
104
102
  this.auth = new KrakenAuth(keyOrAuth, secret)
105
- }
106
- else {
107
- throw new Error('Please provide an API key and secret');
103
+ } else {
104
+ throw new Error('Please provide an API key and secret')
108
105
  }
109
106
  this.api = new KrakenApiList()
110
107
  }
@@ -120,13 +117,18 @@ class Kraken {
120
117
  try {
121
118
  var data = new KrakenUploadData(this, options) // Processing options
122
119
  } catch (err) {
123
- return Promise.reject(
124
- new KrakenResponse({
125
- success: false,
126
- error: err.toString(),
127
- originalError: err
128
- })
129
- )
120
+ const res = new KrakenResponse({
121
+ success: false,
122
+ error: err.toString(),
123
+ originalError: err
124
+ })
125
+ if (cb) {
126
+ // Report to the callback instead of leaving a rejected
127
+ // promise that nobody handles
128
+ cb(res, null)
129
+ return res
130
+ }
131
+ return Promise.reject(res)
130
132
  }
131
133
  const axiosOpts = new AxiosOptions(Kraken.default.axios, {
132
134
  // Processing axios options
@@ -1,7 +1,6 @@
1
1
  // NodeJS libs
2
2
  const fs = require('fs')
3
3
  const path = require('path')
4
- const { Stream } = require('stream')
5
4
  const crypto = require('crypto')
6
5
 
7
6
  // External libs
@@ -14,6 +13,22 @@ const KrakenApiData = require('./KrakenApiData')
14
13
  const nameLen = 20
15
14
  const readOptions = { flags: 'r' }
16
15
 
16
+ // Check that a value looks like a readable stream
17
+ function isStream(value) {
18
+ return (
19
+ value !== null &&
20
+ typeof value === 'object' &&
21
+ typeof value.pipe === 'function'
22
+ )
23
+ }
24
+
25
+ // Open a file for reading. createReadStream is async, so the access
26
+ // check has to be sync to report a wrong path right away.
27
+ function openFile(filePath) {
28
+ fs.accessSync(filePath, fs.constants.R_OK)
29
+ return fs.createReadStream(filePath, readOptions)
30
+ }
31
+
17
32
  /**
18
33
  * KrakenUploadData processing a data for uploading.
19
34
  * @class KrakenUploadData
@@ -57,21 +72,24 @@ class KrakenUploadData extends FormData {
57
72
 
58
73
  // Prepare variables
59
74
  const file = options.file
60
- let fileData = file // Set default data as file prop (Buffer, Stream or whatever)
75
+ const isPath = typeof file === 'string' || file instanceof String
76
+ let fileData
61
77
  let opt = {}
62
78
 
63
- // Processing various types of data
64
- if (typeof file === 'string' || file instanceof String) {
65
- // createReadStream is async - file access check is required to be sync
66
- fs.accessSync(file, fs.constants.R_OK)
67
- fileData = fs.createReadStream(file, readOptions)
68
- opt.filename = path.basename(file) // Set the filename for form data
69
- } else if (file instanceof Object) {
79
+ // Processing various types of data.
80
+ // Buffer and stream checks must not rely on `instanceof Object`:
81
+ // a Buffer is an Object too, and `instanceof` fails across realms.
82
+ if (isPath) {
83
+ fileData = openFile(String(file))
84
+ opt.filename = path.basename(String(file)) // Set the filename for form data
85
+ } else if (Buffer.isBuffer(file) || isStream(file)) {
86
+ fileData = file
87
+ } else if (file && typeof file === 'object') {
70
88
  // TODO: In case of breaking changes - update
71
89
  // this block and method's options format to flat version
72
- if (typeof file.path === 'string' || file instanceof String) {
73
- fs.accessSync(file.path, fs.constants.R_OK)
74
- fileData = fs.createReadStream(file.path, readOptions)
90
+ if (typeof file.path === 'string') {
91
+ fileData = openFile(file.path)
92
+ opt.filename = path.basename(file.path)
75
93
  } else if (file.value) {
76
94
  fileData = file.value
77
95
  } else {
@@ -79,18 +97,23 @@ class KrakenUploadData extends FormData {
79
97
  'Not found required option `file.path` or `file.value`'
80
98
  )
81
99
  }
82
- opt = file.options || {}
100
+ opt = Object.assign(opt, file.options) // Do not mutate user options
101
+ } else {
102
+ throw new Error('Not found required option `file`')
83
103
  }
84
104
 
85
- // Set length parameter for formData options
86
- // in case if length property is present
87
- if (typeof file.length === 'number') {
105
+ // Set length parameter for formData options in case if length
106
+ // property is present. For a path, `length` is the length of the
107
+ // path string, not the file size, so it must not be used.
108
+ if (!isPath && typeof file.length === 'number') {
88
109
  opt.knownLength = file.length
89
110
  }
90
111
 
91
112
  // Generate random filename in case if it missing
92
113
  opt.filename =
93
- file.filename || crypto.randomBytes(nameLen).toString('hex')
114
+ file.filename ||
115
+ opt.filename ||
116
+ crypto.randomBytes(nameLen).toString('hex')
94
117
 
95
118
  // Add file data and file options to form
96
119
  this.append('file', fileData, opt)
@@ -1,37 +0,0 @@
1
- # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2
- # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3
-
4
- name: Node.js CI
5
-
6
- on:
7
- push:
8
- branches:
9
- - master
10
- - develop
11
- pull_request:
12
- branches:
13
- - '*'
14
-
15
- jobs:
16
- build:
17
- runs-on: ubuntu-latest
18
-
19
- strategy:
20
- matrix:
21
- node-version: [12.x, 14.x, 16.x, 17.x, 18.x, 20.x]
22
- # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
23
-
24
- env:
25
- KRAKEN_API_KEY: ${{ secrets.KRAKEN_API_KEY }}
26
- KRAKEN_API_SECRET: ${{ secrets.KRAKEN_API_SECRET }}
27
-
28
- steps:
29
- - uses: actions/checkout@v2
30
- - name: Use Node.js ${{ matrix.node-version }}
31
- uses: actions/setup-node@v2
32
- with:
33
- node-version: ${{ matrix.node-version }}
34
- cache: 'npm'
35
- - run: npm ci
36
- - run: npm run build --if-present
37
- - run: npm test
@@ -1,46 +0,0 @@
1
- # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
- # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
3
-
4
- name: Node.js Package
5
-
6
- on:
7
- release:
8
- types: [published]
9
-
10
- jobs:
11
- build:
12
- runs-on: ubuntu-latest
13
- strategy:
14
- matrix:
15
- node-version: [14.x, 15.x, 16.x, 17.x, 18.x, 20.x]
16
-
17
- env:
18
- KRAKEN_API_KEY: ${{ secrets.KRAKEN_API_KEY }}
19
- KRAKEN_API_SECRET: ${{ secrets.KRAKEN_API_SECRET }}
20
-
21
- steps:
22
- - uses: actions/checkout@v2
23
- - name: Use Node.js ${{ matrix.node-version }}
24
- uses: actions/setup-node@v2
25
- with:
26
- node-version: ${{ matrix.node-version }}
27
- cache: 'npm'
28
- - run: npm ci
29
- - run: npm run build --if-present
30
- - run: npm test
31
-
32
- publish-npm:
33
- needs: build
34
- runs-on: ubuntu-latest
35
- steps:
36
- - uses: actions/checkout@v2
37
- - uses: actions/setup-node@v2
38
- with:
39
- node-version: 18
40
- registry-url: https://registry.npmjs.org/
41
- - run: npm ci
42
- - run: npm publish
43
- env:
44
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
45
- KRAKEN_API_KEY: ${{ secrets.KRAKEN_API_KEY }}
46
- KRAKEN_API_SECRET: ${{ secrets.KRAKEN_API_SECRET }}
package/.jshintrc DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "maxerr": 50, // {int} Maximum error before stopping
3
- "camelcase": false, // true: Identifiers must be in camelCase
4
- "curly": true, // true: Require {} for every new block or scope
5
- "eqeqeq": true, // true: Require triple equals (===) for comparison
6
- "forin": true, // true: Require filtering for..in loops with obj.hasOwnProperty()
7
- "freeze": true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
8
- "indent": 4, // {int} Number of spaces to use for indentation
9
- "noempty": true, // true: Prohibit use of empty blocks
10
- "nonbsp": true, // true: Prohibit "non-breaking whitespace" characters.
11
- "nonew": false, // true: Prohibit use of constructors for side-effects (without assignment)
12
- "quotmark": "single",
13
- "undef": true, // true: Require all non-global variables to be declared (prevents global leaks)
14
- "unused": true, // true: Require all defined variables be used
15
- "strict": false, // true: Requires all functions run in ES5 Strict Mode
16
- "devel": false, // Development/debugging (alert, confirm, etc)
17
- "node": true, // Node.js
18
- "globals": {}, // additional predefined global variables
19
- "esversion": 10,
20
- "asi": true // Missing semicolon warning off
21
- }
@@ -1,176 +0,0 @@
1
- <!-- Generated by documentation.js. Update this documentation by updating the source code. -->
2
-
3
- ### Table of Contents
4
-
5
- * [Kraken][1]
6
- * [Parameters][2]
7
- * [upload][3]
8
- * [Parameters][4]
9
- * [url][5]
10
- * [Parameters][6]
11
- * [userStatus][7]
12
- * [Parameters][8]
13
- * [AxiosOptions][9]
14
- * [KrakenApiData][10]
15
- * [toJson][11]
16
- * [KrakenApiList][12]
17
- * [KrakenAuth][13]
18
- * [KrakenResponse][14]
19
- * [KrakenUploadData][15]
20
-
21
- ## Kraken
22
-
23
- [src/kraken.js:85-156][16]
24
-
25
- This class describes a Kraken-io API
26
-
27
- ### Parameters
28
-
29
- * `keyOrAuth` **[string][17]** Kraken API key
30
- * `secret` **[string][17]** Kraken API secret (optional, default `null`)
31
-
32
- ### upload
33
-
34
- [src/kraken.js:113-131][18]
35
-
36
- Upload image to Kraken.io and optimize it
37
-
38
- #### Parameters
39
-
40
- * `options` **[object][19]** Kraken options for uploaded image
41
- * `cb` **[Function][20]** \=null (optional, default `null`)
42
-
43
- Returns **[Promise][21]<[KrakenResponse][22]>**
44
-
45
- ### url
46
-
47
- [src/kraken.js:139-143][23]
48
-
49
- Optimize image from URL
50
-
51
- #### Parameters
52
-
53
- * `options` **[object][19]** Kraken options for url
54
- * `cb` **[Function][20]** \=null Callback (optional, default `null`)
55
-
56
- Returns **[Promise][21]**
57
-
58
- ### userStatus
59
-
60
- [src/kraken.js:151-155][24]
61
-
62
- Get user status
63
-
64
- #### Parameters
65
-
66
- * `cb` **[Function][20]** Callback (optional, default `null`)
67
-
68
- Returns **[Promise][21]**
69
-
70
- ## AxiosOptions
71
-
72
- [src/lib/AxiosOptions.js:6-22][25]
73
-
74
- Provides options processing for axios
75
-
76
- ## KrakenApiData
77
-
78
- [src/lib/KrakenApiData.js:6-23][26]
79
-
80
- Provides kraken API data processing
81
-
82
- ### toJson
83
-
84
- [src/lib/KrakenApiData.js:20-22][27]
85
-
86
- Convert API Data to JSON string
87
-
88
- Returns **[string][17]**
89
-
90
- ## KrakenApiList
91
-
92
- [src/lib/KrakenApiList.js:9-25][28]
93
-
94
- Provides Kraken API methods list
95
-
96
- ## KrakenAuth
97
-
98
- [src/lib/KrakenAuth.js:6-16][29]
99
-
100
- Provides Kraken.io credentials for API
101
-
102
- ## KrakenResponse
103
-
104
- [src/lib/KrakenResponse.js:6-14][30]
105
-
106
- Just a container for Kraken API response data
107
-
108
- ## KrakenUploadData
109
-
110
- [src/lib/KrakenUploadData.js:22-98][31]
111
-
112
- **Extends FormData**
113
-
114
- KrakenUploadData processing a data for uploading.
115
-
116
- [1]: #kraken
117
-
118
- [2]: #parameters
119
-
120
- [3]: #upload
121
-
122
- [4]: #parameters-1
123
-
124
- [5]: #url
125
-
126
- [6]: #parameters-2
127
-
128
- [7]: #userstatus
129
-
130
- [8]: #parameters-3
131
-
132
- [9]: #axiosoptions
133
-
134
- [10]: #krakenapidata
135
-
136
- [11]: #tojson
137
-
138
- [12]: #krakenapilist
139
-
140
- [13]: #krakenauth
141
-
142
- [14]: #krakenresponse
143
-
144
- [15]: #krakenuploaddata
145
-
146
- [16]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/kraken.js#L85-L156 "Source code on GitHub"
147
-
148
- [17]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
149
-
150
- [18]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/kraken.js#L113-L131 "Source code on GitHub"
151
-
152
- [19]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
153
-
154
- [20]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
155
-
156
- [21]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
157
-
158
- [22]: #krakenresponse
159
-
160
- [23]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/kraken.js#L139-L143 "Source code on GitHub"
161
-
162
- [24]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/kraken.js#L151-L155 "Source code on GitHub"
163
-
164
- [25]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/AxiosOptions.js#L6-L22 "Source code on GitHub"
165
-
166
- [26]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/KrakenApiData.js#L6-L23 "Source code on GitHub"
167
-
168
- [27]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/KrakenApiData.js#L20-L22 "Source code on GitHub"
169
-
170
- [28]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/KrakenApiList.js#L9-L25 "Source code on GitHub"
171
-
172
- [29]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/KrakenAuth.js#L6-L16 "Source code on GitHub"
173
-
174
- [30]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/KrakenResponse.js#L6-L14 "Source code on GitHub"
175
-
176
- [31]: https://github.com/kraken-io/kraken-node/blob/0b4bbcefcd070e8431660f20a2b6a95db38caa13/src/lib/KrakenUploadData.js#L22-L98 "Source code on GitHub"
package/test/.jshintrc DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "maxerr": 50, // {int} Maximum error before stopping
3
- "camelcase": false, // true: Identifiers must be in camelCase
4
- "curly": true, // true: Require {} for every new block or scope
5
- "eqeqeq": true, // true: Require triple equals (===) for comparison
6
- "forin": true, // true: Require filtering for..in loops with obj.hasOwnProperty()
7
- "freeze": true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
8
- "indent": 4, // {int} Number of spaces to use for indentation
9
- "noempty": true, // true: Prohibit use of empty blocks
10
- "nonbsp": true, // true: Prohibit "non-breaking whitespace" characters.
11
- "nonew": false, // true: Prohibit use of constructors for side-effects (without assignment)
12
- "quotmark": "single",
13
- "undef": true, // true: Require all non-global variables to be declared (prevents global leaks)
14
- "unused": true, // true: Require all defined variables be used
15
- "strict": false, // true: Requires all functions run in ES5 Strict Mode
16
- "devel": false, // Development/debugging (alert, confirm, etc)
17
- "node": true, // Node.js
18
- "globals": {
19
- // additional predefined global variables
20
- "describe": true,
21
- "test": true,
22
- "it": true,
23
- "expect": true
24
- },
25
- "esversion": 10,
26
- "asi": true // Missing semicolon warning off
27
- }
@@ -1,177 +0,0 @@
1
- const Kraken = require('../')
2
- const fs = require('fs')
3
- require('dotenv').config();
4
-
5
- // Environment variables names with API key and secret
6
- const envKey = 'KRAKEN_API_KEY'
7
- const envSecret = 'KRAKEN_API_SECRET'
8
-
9
- const krakenKey = process.env[envKey]
10
- const krakenSecret = process.env[envSecret]
11
-
12
- const MAX_TIMEOUT = 20000;
13
-
14
- // Check key and secret variables
15
- CheckEnvVars([envKey, envSecret])
16
-
17
- // Tests extensions
18
- expect.extend({
19
- toBeKrakenSuccess(status) {
20
- const result = {
21
- message: () => 'Unknown error',
22
- pass: false
23
- }
24
-
25
- if (status == null) {
26
- result.message = () => 'Empty status'
27
- } else if (status.success === true) {
28
- result.message = () => 'Not passed'
29
- result.pass = true
30
- } else if (status.error) {
31
- result.message = () =>
32
- `Kraken API returned an error: ${status.error}`
33
- }
34
-
35
- return result
36
- }
37
- })
38
-
39
- class DevData {
40
- constructor(data) {
41
- this.wait = true
42
- this.dev = true
43
- Object.assign(this, data)
44
- }
45
- }
46
-
47
- // Main tests
48
- describe('Kraken.io API', () => {
49
- // Test variables
50
- let krakenAuth = null
51
- let kraken = null
52
-
53
- // Test prepare
54
- beforeAll(() => {
55
- krakenAuth = {
56
- api_key: krakenKey,
57
- api_secret: krakenSecret
58
- }
59
- kraken = new Kraken(krakenAuth)
60
- })
61
-
62
- // auth 1
63
- it('new Kraken({api_key, api_secret})', () => {
64
- const kraken = new Kraken(krakenAuth)
65
- expect(kraken.auth).toEqual(krakenAuth)
66
- })
67
-
68
- // auth 2
69
- it('new Kraken(api_key, api_secret)', () => {
70
- const kraken = new Kraken(krakenAuth.api_key, krakenAuth.api_secret)
71
- expect(kraken.auth).toEqual(krakenAuth)
72
- })
73
-
74
- // userStatus
75
- it('kraken.userStatus()', () => {
76
- return expect(kraken.userStatus()).resolves.toBeKrakenSuccess()
77
- })
78
-
79
- // url
80
- it('kraken.url()', () => {
81
- const data = {
82
- url: 'https://kraken-nekkraug.netdna-ssl.com/assets/images/kraken-logotype@2x.png',
83
- wait: true,
84
- dev: true
85
- }
86
-
87
- return expect(kraken.url(data)).resolves.toBeKrakenSuccess()
88
- },MAX_TIMEOUT)
89
-
90
- // url various formats
91
- describe('kraken.upload({ file })', () => {
92
- it('file<String> -> catch wrong file path', () => {
93
- const data = new DevData({
94
- file: 'test/support/images/wrong-file-path.gif'
95
- })
96
-
97
- return expect(kraken.upload(data)).rejects.toHaveProperty(
98
- 'originalError.code',
99
- 'ENOENT'
100
- )
101
- })
102
-
103
- it('file<String> -> path', () => {
104
- const data = new DevData({
105
- file: 'test/support/images/image.gif'
106
- })
107
-
108
- return expect(kraken.upload(data)).resolves.toBeKrakenSuccess()
109
- })
110
-
111
- it('file<Buffer>', () => {
112
- const fileData = fs.readFileSync('test/support/images/image.gif')
113
- const data = new DevData({
114
- file: fileData
115
- })
116
-
117
- return expect(kraken.upload(data)).resolves.toBeKrakenSuccess()
118
- })
119
-
120
- it('file<Stream>', () => {
121
- const fileData = fs.createReadStream(
122
- 'test/support/images/image.gif'
123
- )
124
- const data = new DevData({
125
- file: fileData
126
- })
127
-
128
- return expect(kraken.upload(data)).resolves.toBeKrakenSuccess()
129
- })
130
-
131
- it('file<Object>: path and options', () => {
132
- const data = new DevData({
133
- file: {
134
- path: 'test/support/images/image.gif',
135
- options: {}
136
- }
137
- })
138
-
139
- return expect(kraken.upload(data)).resolves.toBeKrakenSuccess()
140
- })
141
-
142
- it('file<Object>: <Buffer> and options', () => {
143
- const fileData = fs.readFileSync('test/support/images/image.gif')
144
- const data = new DevData({
145
- file: {
146
- value: fileData,
147
- options: {}
148
- }
149
- })
150
-
151
- return expect(kraken.upload(data)).resolves.toBeKrakenSuccess()
152
- })
153
-
154
- it('file<Object>: <Stream> and options', () => {
155
- const fileData = fs.createReadStream(
156
- 'test/support/images/image.gif'
157
- )
158
- const data = new DevData({
159
- file: {
160
- value: fileData,
161
- options: {}
162
- }
163
- })
164
-
165
- return expect(kraken.upload(data)).resolves.toBeKrakenSuccess()
166
- })
167
- })
168
- })
169
-
170
- // Check if environment variable is defined
171
- function CheckEnvVars(names) {
172
- for (let name of names) {
173
- if (!process.env[name]) {
174
- throw new Error(`Not found environment variable: ${name}`)
175
- }
176
- }
177
- }
Binary file