@bytescale/sdk
Advanced tools
Comparing version 3.0.0-alpha.9 to 3.0.0-alpha.10
import { AuthSession } from "./model/AuthSession"; | ||
import { Mutex } from "./Mutex"; | ||
/** | ||
* Maintains a global session state, even across package versions. | ||
* | ||
* This is to allow users to start auth sessions via the Bytescale JavaScript SDK, where due to versioning or other | ||
* bundling issues, the Bytescale Upload Widget has been bundled with a different Bytescale JavaScript SDK. In this | ||
* scenario, the user wouldn't be able to start an auth session with the Bytescale Upload Widget. Therefore, we use | ||
* global state (i.e. on the window) to ensure the session state can be shared between the user's instance of the | ||
* Bytescale JavaScript SDK and the Upload Widget's version of the Bytescale JavaScript SDK. | ||
* | ||
* Users also frequently have problems caused by them not keeping track of *Api and *Manager instances correctly, so | ||
* making this global prevents a lot of common mistakes. | ||
*/ | ||
export declare class AuthSessionState { | ||
private static readonly stateKey; | ||
private static readonly mutexKey; | ||
/** | ||
* Intentionally global: | ||
* | ||
* Users frequently have problems caused by them not keeping track of *Api and *Manager instances correctly, so we | ||
* make this global as in 99.9% of cases, this is what users want, and it prevents lots of common mistakes. | ||
* | ||
* We only set this in the browser. | ||
* Never in Node.js. | ||
* Called in the browser only. | ||
*/ | ||
static session: AuthSession | undefined; | ||
static getMutex(): Mutex; | ||
/** | ||
* Called in the browser only. | ||
*/ | ||
static setSession(session: AuthSession | undefined): void; | ||
/** | ||
* Called in the browser and in Node.js (so we check the env before calling env-specific code). | ||
*/ | ||
static getSession(): AuthSession | undefined; | ||
} |
{ | ||
"name": "@bytescale/sdk", | ||
"version": "3.0.0-alpha.9", | ||
"version": "3.0.0-alpha.10", | ||
"description": "Bytescale JavaScript SDK", | ||
@@ -5,0 +5,0 @@ "author": "Bytescale <hello@bytescale.com> (https://www.bytescale.com)", |
411
README.md
@@ -1,41 +0,86 @@ | ||
# Bytescale JavaScript SDK | ||
<h1 align="center"> | ||
<a href="https://www.bytescale.com/docs/sdks/javascript"> | ||
<img alt="Bytescale JavaScript SDK" width="557" height="67" src="https://raw.githubusercontent.com/bytescale/bytescale-javascript-sdk/main/.github/assets/bytescale-javascript-sdk.svg"> | ||
</a> | ||
</h1> | ||
The Bytescale JavaScript SDK allows you to quickly integrate your application with [Bytescale](https://www.bytescale.com). | ||
<p align="center"> | ||
<a href="https://www.npmjs.com/package/@bytescale/sdk"> | ||
<img src="https://img.shields.io/badge/%40bytescale%2Fsdk-npm-4ba0f6" /> | ||
</a> | ||
Effortlessly upload, optimize, transform, and host your digital media assets. | ||
<a href="https://github.com/bytescale/bytescale-javascript-sdk/actions/workflows/ci.yml"> | ||
<img src="https://img.shields.io/badge/build-passing-4ba0f6" /> | ||
</a> | ||
<a href="https://github.com/bytescale/bytescale-javascript-sdk/"> | ||
<img src="https://img.shields.io/badge/gzipped-9%20kb-4ba0f6" /> | ||
</a> | ||
<a href="https://www.npmjs.com/package/@bytescale/sdk"> | ||
<img src="https://img.shields.io/npm/dt/upload-js?color=%234ba0f6" /> | ||
</a> | ||
<br/> | ||
<a href="https://www.npmjs.com/package/@bytescale/sdk"> | ||
<img src="https://img.shields.io/badge/TypeScript-included-4ba0f6" /> | ||
</a> | ||
<a href="https://github.com/bytescale/bytescale-javascript-sdk/actions/workflows/ci.yml"> | ||
<img src="https://img.shields.io/npms-io/maintenance-score/upload-js?color=4ba0f6" /> | ||
</a> | ||
<a target="_blank" href="https://twitter.com/intent/tweet?text=This%20was%20a%20great%20find...%0A%0Ahttps%3A%2F%2Fgithub.com%2Fbytescale%2Fbytescale-javascript-sdk"> | ||
<img alt="Twitter URL" src="https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fbytescale%2Fbytescale-javascript-sdk" /> | ||
</a> | ||
</p> | ||
<hr/> | ||
<p align="center"> | ||
<b>Bytescale is the developer platform for images, video, and audio.</b> | ||
<br /> | ||
<br /> | ||
Use the Bytescale JavaScript SDK to upload, transform, and serve files at scale. | ||
<br /> | ||
<br /> | ||
<a href="https://www.bytescale.com/docs/sdks/javascript" rel="nofollow"><b>Full SDK Documentation</b></a> • <a href="https://www.bytescale.com/docs/upload-widget" rel="nofollow">Upload Widget</a> • <a href="https://www.bytescale.com/docs/media-processing-apis" rel="nofollow">Media Processing APIs</a> • <a href="https://www.bytescale.com/docs/storage/sources" rel="nofollow">Storage</a> • <a href="https://www.bytescale.com/docs/cdn" rel="nofollow">CDN</a> | ||
</p> | ||
<hr/> | ||
## Installation | ||
#### For Node.js: | ||
```bash | ||
npm install @bytescale/sdk | ||
npm install @bytescale/sdk node-fetch | ||
``` | ||
Additional step for Node.js: | ||
#### For Browsers: | ||
```bash | ||
npm install node-fetch | ||
npm install @bytescale/sdk | ||
``` | ||
## Full Documentation | ||
Or: | ||
**[Bytescale JavaScript SDK Full Documentation »](https://www.bytescale.com/docs/sdks/javascript)** | ||
```html | ||
<script src="https://js.bytescale.com/sdk/v3"></script> | ||
``` | ||
## Quick Guide | ||
## Uploading Files | ||
- [Upload a File](#upload-a-file) | ||
- [Download a File](#download-a-file) | ||
- [Process a File](#process-a-file) | ||
- [Get File Details](#get-file-details) | ||
- [List Folder](#list-folder) | ||
- **[See All Methods »](https://www.bytescale.com/docs/sdks/javascript)** | ||
This library is isomorphic, which means you can upload files from Node.js, or the browser, or both. | ||
### Upload a File | ||
#### From Node.js: | ||
```javascript | ||
import * as Bytescale from "@bytescale/sdk"; | ||
import fetch from "node-fetch"; // Node.js only. | ||
import fetch from "node-fetch"; | ||
const uploadManager = new Bytescale.UploadManager({ | ||
fetchApi: fetch, // 'fetch as any' for TypeScript | ||
apiKey: "YOUR_BYTESCALE_API_KEY" // e.g. "secret_xxxxx" | ||
fetchApi: fetch, // or 'fetch as any' (please note: you must use 'node-fetch' as errors can occur with other implementations) | ||
apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx" | ||
}); | ||
@@ -45,22 +90,164 @@ | ||
.upload({ | ||
accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk" | ||
// --------- | ||
// Required: | ||
// --------- | ||
// Your account ID (e.g. "W142hJk") | ||
accountId: "YOUR_ACCOUNT_ID", | ||
// Supported types for 'data' field: | ||
// - String | ||
// - Blob | ||
// - File (i.e. from a DOM file input element) | ||
// - Buffer | ||
// - ReadableStream (Node.js), e.g. fs.createReadStream("file.txt") | ||
data: "Example Data" | ||
data: "Hello World", | ||
// --------- | ||
// Optional: | ||
// --------- | ||
// Required if 'data' is a stream. | ||
// size: 5098, // e.g. fs.statSync("file.txt").size | ||
// Required if 'data' is a stream, buffer, or string. | ||
mime: "text/plain", | ||
// Required if 'data' is a stream, buffer, or string. | ||
originalFileName: "my_file.txt" | ||
// Controls multipart upload concurrency. Ignored if 'data' is a stream. | ||
// maxConcurrentUploadParts: 4, | ||
// Up to 2KB of arbitrary JSON. | ||
// metadata: { | ||
// productId: 60891 | ||
// }, | ||
// Up to 25 tags per file. | ||
// tags: [ | ||
// "example_tag" | ||
// ], | ||
// About file paths: | ||
// - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings. | ||
// - You can override the API key's file upload path by specifying a path below. | ||
// - You may use path variables (e.g. "{UTC_DAY}"): http://localhost:3201/docs/path-variables | ||
// path: { | ||
// folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}", | ||
// fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}" | ||
// }, | ||
// Set to 'isCancelled = true' after invoking 'upload' to cancel the upload. | ||
// cancellationToken: { | ||
// isCancelled: false | ||
// } | ||
}) | ||
.then( | ||
uploadedFile => console.log(uploadedFile), | ||
error => console.error(error) | ||
({ fileUrl, filePath }) => { | ||
// -------------------------------------------- | ||
// File successfully uploaded! | ||
// -------------------------------------------- | ||
// The 'filePath' uniquely identifies the file, | ||
// and is what you should save to your DB. | ||
// -------------------------------------------- | ||
console.log(`File uploaded to: ${fileUrl}`); | ||
}, | ||
error => console.error(`Error: ${error.message}`, error) | ||
); | ||
``` | ||
### Download a File | ||
#### From the Browser: | ||
```html | ||
<html> | ||
<head> | ||
<script src="https://js.bytescale.com/sdk/v3"></script> | ||
<script> | ||
// import * as Bytescale from "@bytescale/sdk" | ||
const uploadManager = new Bytescale.UploadManager({ | ||
apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx" | ||
}); | ||
const onFileSelected = async event => { | ||
const file = event.target.files[0]; | ||
try { | ||
const { fileUrl, filePath } = await uploadManager.upload({ | ||
// --------- | ||
// Required: | ||
// --------- | ||
// Your account ID (e.g. "W142hJk") | ||
accountId: "YOUR_ACCOUNT_ID", | ||
// Supported types for 'data' field: | ||
// - String | ||
// - Blob | ||
// - File (i.e. from a DOM file input element) | ||
data: file | ||
// --------- | ||
// Optional: | ||
// --------- | ||
// Required if 'data' is a stream. (Not required for DOM file inputs, blobs, buffers, or strings.) | ||
// size: 5098, // e.g. fs.statSync("file.txt").size | ||
// Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.) | ||
// mime: "application/octet-stream", | ||
// Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.) | ||
// originalFileName: "my_file.txt", | ||
// Controls multipart upload concurrency. Ignored if 'data' is a stream. | ||
// maxConcurrentUploadParts: 4, | ||
// Up to 2KB of arbitrary JSON. | ||
// metadata: { | ||
// productId: 60891 | ||
// }, | ||
// Up to 25 tags per file. | ||
// tags: [ | ||
// "example_tag" | ||
// ], | ||
// About file paths: | ||
// - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings. | ||
// - You can override the API key's file upload path by specifying a path below. | ||
// - You may use path variables (e.g. "{UTC_DAY}"): http://localhost:3201/docs/path-variables | ||
// path: { | ||
// folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}", | ||
// fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}" | ||
// }, | ||
// Set to 'isCancelled = true' after invoking 'upload' to cancel the upload. | ||
// cancellationToken: { | ||
// isCancelled: false | ||
// } | ||
}); | ||
// -------------------------------------------- | ||
// File successfully uploaded! | ||
// -------------------------------------------- | ||
// The 'filePath' uniquely identifies the file, | ||
// and is what you should save to your API. | ||
// -------------------------------------------- | ||
alert(`File uploaded:\n${fileUrl}`); | ||
} catch (e) { | ||
alert(`Error:\n${e.message}`); | ||
} | ||
}; | ||
</script> | ||
</head> | ||
<body> | ||
<input type="file" onchange="onFileSelected(event)" /> | ||
</body> | ||
</html> | ||
``` | ||
## Downloading Files | ||
```javascript | ||
import * as Bytescale from "@bytescale/sdk"; | ||
import fetch from "node-fetch"; // Node.js only. | ||
import fetch from "node-fetch"; // Only required for Node.js | ||
@@ -84,9 +271,9 @@ const fileApi = new Bytescale.FileApi({ | ||
**Note:** you can also download files using: `https://upcdn.io/{accountId}/raw/{filePath}` | ||
Use the [`UrlBuilder`](#urlbuilder) to get a URL to your file (if you need a URL instead of downloading the file). | ||
### Process a File | ||
## Processing Files | ||
```javascript | ||
import * as Bytescale from "@bytescale/sdk"; | ||
import fetch from "node-fetch"; // Node.js only. | ||
import fetch from "node-fetch"; // Only required for Node.js | ||
@@ -102,3 +289,9 @@ const fileApi = new Bytescale.FileApi({ | ||
filePath: "/uploads/2022/12/25/image.jpg", | ||
transformation: "thumbnail" // Create transformations here: https://www.bytescale.com/dashboard/transformations | ||
// See: https://www.bytescale.com/docs/image-processing-api | ||
transformation: "image", | ||
transformationParams: { | ||
w: 800, | ||
h: 600 | ||
} | ||
}) | ||
@@ -121,9 +314,9 @@ .then(response => response.stream()) // .text() | .json() | .blob() | .stream() | ||
**Note:** you can also process files using: `https://upcdn.io/{accountId}/{transformation}/{filePath}` | ||
Use the [`UrlBuilder`](#urlbuilder) to get a URL to your file (if you need a URL instead of downloading the file). | ||
### Get File Details | ||
## Get File Details | ||
```javascript | ||
import * as Bytescale from "@bytescale/sdk"; | ||
import fetch from "node-fetch"; // Node.js only. | ||
import fetch from "node-fetch"; // Only required for Node.js | ||
@@ -146,7 +339,7 @@ const fileApi = new Bytescale.FileApi({ | ||
### List Folder | ||
## Listing Folders | ||
```javascript | ||
import * as Bytescale from "@bytescale/sdk"; | ||
import fetch from "node-fetch"; // Node.js only. | ||
import fetch from "node-fetch"; // Only required for Node.js | ||
@@ -171,4 +364,150 @@ const folderApi = new Bytescale.FolderApi({ | ||
## Authorization | ||
The Bytescale JavaScript SDK supports two types of authorization: | ||
### API Keys | ||
The Bytescale JavaScript SDK automatically adds the `apiKey` from the constructor to the `Authorization` header for all requests made via the SDK. | ||
With API key auth, the requester has access to the resources available to the API key: | ||
- Secret API keys (`secret_***`) have access to all API endpoints. | ||
- Public API keys (`public_***`) have access to file upload, file download, and file listing API endpoints. (File listing is disabled by default. This can be changed in the API key's settings.) | ||
Each Public API Key and Secret API Key can have its read/write access limited to a subset of files/folders. | ||
### JWT Cookies | ||
JWT cookies are optional. | ||
With JWT cookies, the user can download private files directly via URL, as authorization is performed implicitly via a session cookie. This allows the browser to display private files in `<img>` and `<video>` elements. | ||
With JWT cookies, the user can also perform API requests (e.g. file uploads) granted by the [JWT's payload](https://www.bytescale.com/docs/types/BytescaleJwt). This is because the Bytescale JavaScript SDK automatically injects the user's JWT into the `authorization-token` request header for all API requests, assuming the `AuthManager.beginAuthSession` method has been called. | ||
_Note: when using JWT cookies to download files, the `?auth=true` query parameter must be added to the URL._ | ||
[Learn more about using JWT cookies »](https://www.bytescale.com/docs/authorization#jwt-cookie) | ||
## UrlBuilder | ||
Use the `UrlBuilder` to make URLs for your uploaded files: | ||
```javascript | ||
import { UrlBuilder } from "@bytescale/sdk"; | ||
``` | ||
#### Raw Files | ||
To get the URL for the uploaded image `/example.jpg` in its original form, use the following params: | ||
```javascript | ||
// Returns: "https://upcdn.io/1234abc/raw/example.jpg" | ||
new UrlBuilder().url({ | ||
accountId: "1234abc", | ||
filePath: "/example.jpg" | ||
}); | ||
``` | ||
#### Images | ||
To resize the uploaded image `/example.jpg` to 800x600, use the following params: | ||
```javascript | ||
// Returns: "https://upcdn.io/1234abc/image/example.jpg?w=800&h=600" | ||
new UrlBuilder().url({ | ||
accountId: "1234abc", | ||
filePath: "/example.jpg", | ||
options: { | ||
transformation: "image", | ||
transformationParams: { | ||
w: 800, | ||
h: 600 | ||
} | ||
} | ||
}); | ||
``` | ||
[Image Processing API Docs »](https://www.bytescale.com/docs/image-processing-api) | ||
#### Videos | ||
To transcode the uploaded video `/example.mov` to MP4/H.264 in HD, use the following params: | ||
```javascript | ||
// Returns: "https://upcdn.io/1234abc/video/example.mov?f=mp4-h264&h=1080" | ||
new UrlBuilder().url({ | ||
accountId: "1234abc", | ||
filePath: "/example.mov", | ||
options: { | ||
transformation: "video", | ||
transformationParams: { | ||
f: "mp4-h264", | ||
h: 1080 | ||
} | ||
} | ||
}); | ||
``` | ||
[Video Processing API Docs »](https://www.bytescale.com/docs/video-processing-api) | ||
#### Audio | ||
To transcode the uploaded audio `/example.wav` to AAC in 192kbps, use the following params: | ||
```javascript | ||
// Returns: "https://upcdn.io/1234abc/audio/example.wav?f=aac&br=192" | ||
new UrlBuilder().url({ | ||
accountId: "1234abc", | ||
filePath: "/example.wav", | ||
options: { | ||
transformation: "audio", | ||
transformationParams: { | ||
f: "aac", | ||
br: 192 | ||
} | ||
} | ||
}); | ||
``` | ||
[Audio Processing API Docs »](https://www.bytescale.com/docs/audio-processing-api) | ||
#### Archives | ||
To extract the file `document.docx` from the uploaded ZIP file `/example.zip`, use the following params: | ||
```javascript | ||
// Returns: "https://upcdn.io/1234abc/archive/example.zip?m=extract&artifact=/document.docx" | ||
new UrlBuilder().url({ | ||
accountId: "1234abc", | ||
filePath: "/example.zip", | ||
options: { | ||
transformation: "archive", | ||
transformationParams: { | ||
m: "extract" | ||
}, | ||
artifact: "/document.docx" | ||
} | ||
}); | ||
``` | ||
[Archive Processing API Docs »](https://www.bytescale.com/docs/archive-processing-api) | ||
## 👋 Create your Bytescale Account | ||
Bytescale is the best way to serve images, videos, and audio for web apps. | ||
**[Create a Bytescale account »](https://www.bytescale.com/get-started)** | ||
## 🙋 Can I use my own storage? | ||
Bytescale supports AWS S3, Cloudflare R2, Google Storage, DigitalOcean Spaces, and Bytescale Storage. | ||
**[Bytescale Storage Docs »](https://www.bytescale.com/docs/storage/sources)** | ||
**[Bytescale JavaScript SDK Docs »](https://www.bytescale.com/docs/sdks/javascript)** | ||
## License | ||
[MIT](LICENSE) |
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 not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
570668
12800
508