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

@lucidtech/las-sdk-core

Package Overview
Dependencies
Maintainers
2
Versions
113
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@lucidtech/las-sdk-core - npm Package Compare versions

Comparing version 1.2.12 to 2.0.1-alpha.0

86

lib/client.d.ts
import { Credentials } from './credentials';
/**
* A high-level http client for communicating the Lucidtech REST API
*/
export declare class Client {
apiEndpoint: string;
credentials: Credentials;
constructor(apiEndpoint: string, credentials: Credentials);
constructor(credentials: Credentials);
/**
* Get document from the REST API, calls the GET /documets/{documentId} endpoint
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @returns {Promise} - document response from REST API
*/
getDocument(documentId: string): Promise<any>;
getData(): Promise<any>;
postDocuments(content: string, contentType: string, consentId: string, batchId?: string, feedback?: Array<{
/**
* Creates a document handle, calls the POST /documents endpoint.
*
* @param {string} content - The contents to POST
* @param {string} contentType - A MIME type for the document handle
* @param {string} consentId - An identifier to mark the owner of the document handle
* @param {string} [batchId] - The batch to put the document it
* @param {Array<{ [label: string]: string }>} [feedback] A list of items
* { label: value } representing the ground truth values for the document
* @returns {Promise} - document handle id
*/
createDocument(content: string, contentType: string, consentId: string, batchId?: string, feedback?: Array<{
[key: string]: string;
}>): Promise<any>;
getDocuments(batchId: string): Promise<any>;
postDocumentId(documentId: string, feedback: Array<{
/**
* @param {string} [batchId] - the batch id that contains the documents of interest
* @param {string} [consentId] - an identifier to mark the owner of the document handle
* @returns {Promise} - documents from REST API contained in batch <batchId>
*/
listDocuments(batchId?: string, consentId?: string): Promise<any>;
/**
* Post feedback to the REST API, calls the POST /documents/{documentId} endpoint.
* Posting feedback means posting the ground truth data for the particular document.
* This enables the API to learn from past mistakes.
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @param {Array<{ [label: string]: string }>} feedback - a list of feedback items
* { label: value } representing the ground truth values for the document
* @returns {Promise} - feedback response from REST API
*/
updateDocument(documentId: string, feedback: Array<{
[key: string]: string;
}>): Promise<any>;
postPredictions(documentId: string, modelName: string): Promise<any>;
postBatches(description: string): Promise<any>;
getProcesses(search?: {
[key: string]: string | Array<string>;
}): Promise<any>;
postProcesses(stateMachineArn: string, inputData: any): Promise<any>;
postTasks(activityArn: string): Promise<any>;
deleteProcess(processId: string): Promise<any>;
/**
* Either taskResult or taskError shoud be provided, but not both.
* Run inference and create a prediction, calls the POST /predictions endpoint.
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @param {string} modelName - the name of the model to use for inference
* @param {number} [maxPages] - maximum number of pages to run predicitons on
* @param {boolean} [autoRotate] - whether or not to let the API try different rotations on
* the document when runnin predictions
* @returns {Promise} - prediction on document
*/
patchTasks(taskId: string, taskResult?: any, taskError?: any): Promise<any>;
patchUser(userId: string, consentHash: string): Promise<any>;
createPrediction(documentId: string, modelName: string, maxPages?: number, autoRotate?: boolean): Promise<any>;
/**
* Creates a batch handle, calls the POST /batches endpoint
*
* @param {string} description - a short description of the batch you intend to create
* @returns {Promise} - batch handle id and pre-signed upload url
*/
createBatch(description: string): Promise<any>;
/**
* Modifies consent hash for a user, calls the PATCH /users/{user_id} endpoint.
*
* @param {string} userId - the user id to modify consent hash for
* @param {string} consentHash - the consent hash to set
* @returns {Promise} - batch handle id and pre-signed upload url
*/
updateUser(userId: string, consentHash: string): Promise<any>;
/**
* Gets consent hash and user id for a given user id, calls the GET /users/{user_id} endpoint.
*
* @param {string} userId - the user id to get consent hash for
* @returns {Promise} - batch handle id and pre-signed upload url
*/
getUser(userId: string): Promise<any>;

@@ -29,0 +81,0 @@ makeGetRequest(path: string, query?: any): Promise<any>;

119

lib/client.js

@@ -19,14 +19,30 @@ "use strict";

var utils_1 = require("./utils");
/**
* A high-level http client for communicating the Lucidtech REST API
*/
var Client = /** @class */ (function () {
function Client(apiEndpoint, credentials) {
this.apiEndpoint = apiEndpoint;
function Client(credentials) {
this.credentials = credentials;
}
/**
* Get document from the REST API, calls the GET /documets/{documentId} endpoint
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @returns {Promise} - document response from REST API
*/
Client.prototype.getDocument = function (documentId) {
return this.makeGetRequest("/documents/" + documentId);
};
Client.prototype.getData = function () {
return this.makeGetRequest('/data');
};
Client.prototype.postDocuments = function (content, contentType, consentId, batchId, feedback) {
/**
* Creates a document handle, calls the POST /documents endpoint.
*
* @param {string} content - The contents to POST
* @param {string} contentType - A MIME type for the document handle
* @param {string} consentId - An identifier to mark the owner of the document handle
* @param {string} [batchId] - The batch to put the document it
* @param {Array<{ [label: string]: string }>} [feedback] A list of items
* { label: value } representing the ground truth values for the document
* @returns {Promise} - document handle id
*/
Client.prototype.createDocument = function (content, contentType, consentId, batchId, feedback) {
var body = {

@@ -45,9 +61,23 @@ content: Buffer.from(content).toString('base64'),

};
Client.prototype.getDocuments = function (batchId) {
var query = {
batchId: batchId,
};
/**
* @param {string} [batchId] - the batch id that contains the documents of interest
* @param {string} [consentId] - an identifier to mark the owner of the document handle
* @returns {Promise} - documents from REST API contained in batch <batchId>
*/
Client.prototype.listDocuments = function (batchId, consentId) {
var query = { batchId: batchId, consentId: consentId };
return this.makeGetRequest('/documents', query);
};
Client.prototype.postDocumentId = function (documentId, feedback) {
/**
* Post feedback to the REST API, calls the POST /documents/{documentId} endpoint.
* Posting feedback means posting the ground truth data for the particular document.
* This enables the API to learn from past mistakes.
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @param {Array<{ [label: string]: string }>} feedback - a list of feedback items
* { label: value } representing the ground truth values for the document
* @returns {Promise} - feedback response from REST API
*/
Client.prototype.updateDocument = function (documentId, feedback) {
// TODO add test for this method
var body = {

@@ -58,3 +88,13 @@ feedback: feedback,

};
Client.prototype.postPredictions = function (documentId, modelName) {
/**
* Run inference and create a prediction, calls the POST /predictions endpoint.
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @param {string} modelName - the name of the model to use for inference
* @param {number} [maxPages] - maximum number of pages to run predicitons on
* @param {boolean} [autoRotate] - whether or not to let the API try different rotations on
* the document when runnin predictions
* @returns {Promise} - prediction on document
*/
Client.prototype.createPrediction = function (documentId, modelName, maxPages, autoRotate) {
var body = {

@@ -64,5 +104,17 @@ documentId: documentId,

};
if (maxPages !== undefined) {
body = __assign(__assign({}, body), { maxPages: maxPages });
}
if (autoRotate !== undefined) {
body = __assign(__assign({}, body), { autoRotate: autoRotate });
}
return this.makePostRequest('/predictions', body);
};
Client.prototype.postBatches = function (description) {
/**
* Creates a batch handle, calls the POST /batches endpoint
*
* @param {string} description - a short description of the batch you intend to create
* @returns {Promise} - batch handle id and pre-signed upload url
*/
Client.prototype.createBatch = function (description) {
var body = {

@@ -73,33 +125,20 @@ description: description,

};
Client.prototype.getProcesses = function (search) {
return this.makeGetRequest('/processes', search);
};
Client.prototype.postProcesses = function (stateMachineArn, inputData) {
var body = {
stateMachineArn: stateMachineArn,
inputData: inputData,
};
return this.makePostRequest('/processes', body);
};
Client.prototype.postTasks = function (activityArn) {
var body = {
activityArn: activityArn,
};
return this.makePostRequest('/tasks', body);
};
Client.prototype.deleteProcess = function (processId) {
var url = "/processes/" + processId;
return this.makeDeleteRequest(url);
};
/**
* Either taskResult or taskError shoud be provided, but not both.
* Modifies consent hash for a user, calls the PATCH /users/{user_id} endpoint.
*
* @param {string} userId - the user id to modify consent hash for
* @param {string} consentHash - the consent hash to set
* @returns {Promise} - batch handle id and pre-signed upload url
*/
Client.prototype.patchTasks = function (taskId, taskResult, taskError) {
var body = taskResult ? { taskResult: taskResult } : { taskError: taskError };
return this.makePatchRequest("/tasks/" + taskId, body);
};
Client.prototype.patchUser = function (userId, consentHash) {
Client.prototype.updateUser = function (userId, consentHash) {
// TODO add test for this method
var body = { consentHash: consentHash };
return this.makePatchRequest("/users/" + userId, body);
};
/**
* Gets consent hash and user id for a given user id, calls the GET /users/{user_id} endpoint.
*
* @param {string} userId - the user id to get consent hash for
* @returns {Promise} - batch handle id and pre-signed upload url
*/
Client.prototype.getUser = function (userId) {

@@ -123,3 +162,3 @@ return this.makeGetRequest("/users/" + userId);

return new Promise(function (resolve, reject) {
var endpoint = "" + _this.apiEndpoint + path;
var endpoint = "" + _this.credentials.apiEndpoint + path;
_this.getAuthorizationHeaders().then(function (headers) {

@@ -126,0 +165,0 @@ var config = { headers: headers };

import { TokenStorage } from './storage';
/**
* Wrapper class for an AWS Cognito token
*/
export declare class Token {

@@ -6,12 +9,30 @@ readonly accessToken: string;

readonly refreshToken?: string;
/**
* Checks if current timestamp is larger than token expiration time
*/
isValid(): boolean;
/**
* @param {string} accessToken
* @param {number} expiration
* @param {string} [refreshToken]
*/
constructor(accessToken: string, expiration: number, refreshToken?: string);
}
/**
* Use to fetch and store credentials and to generate/cache an access token
*/
export declare abstract class Credentials {
readonly apiEndpoint: string;
readonly apiKey: string;
protected token?: Token;
protected storage?: TokenStorage<Token>;
protected constructor(apiKey: string, storage?: TokenStorage<Token>);
protected constructor(apiEndpoint: string, apiKey: string, storage?: TokenStorage<Token>);
/**
* Method used to get and cache an access token. Algorithm used:
* 1. Look for a valid token in memory.
* 2. Look for a valid token in the storage (if provided);
* 3. Fetch a new token from server and cache it (both in memory and in storage).
*/
getAccessToken(): Promise<string>;
protected abstract getToken(): Promise<Token>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Wrapper class for an AWS Cognito token
*/
var Token = /** @class */ (function () {
/**
* @param {string} accessToken
* @param {number} expiration
* @param {string} [refreshToken]
*/
function Token(accessToken, expiration, refreshToken) {

@@ -9,2 +17,5 @@ this.accessToken = accessToken;

}
/**
* Checks if current timestamp is larger than token expiration time
*/
Token.prototype.isValid = function () {

@@ -16,7 +27,17 @@ return Date.now() < this.expiration;

exports.Token = Token;
/**
* Use to fetch and store credentials and to generate/cache an access token
*/
var Credentials = /** @class */ (function () {
function Credentials(apiKey, storage) {
function Credentials(apiEndpoint, apiKey, storage) {
this.apiEndpoint = apiEndpoint;
this.apiKey = apiKey;
this.storage = storage;
}
/**
* Method used to get and cache an access token. Algorithm used:
* 1. Look for a valid token in memory.
* 2. Look for a valid token in the storage (if provided);
* 3. Fetch a new token from server and cache it (both in memory and in storage).
*/
Credentials.prototype.getAccessToken = function () {

@@ -23,0 +44,0 @@ var _this = this;

export declare function buildURL(url: string, params?: {
[key: string]: string | Array<string>;
[key: string]: undefined | string | Array<string>;
}): string;

@@ -8,4 +8,7 @@ "use strict";

var searchParams = new URLSearchParams();
var queryString = Object.entries(params).forEach(function (param) {
Object.entries(params).forEach(function (param) {
var key = param[0], value = param[1];
if (value === undefined) {
return;
}
if (typeof value === 'string') {

@@ -12,0 +15,0 @@ searchParams.set(key, value);

{
"name": "@lucidtech/las-sdk-core",
"version": "1.2.12",
"version": "2.0.1-alpha.0",
"author": "Lucidtech AS <hello@lucidtech.ai>",

@@ -18,3 +18,4 @@ "maintainers": [

"upgrade": "npm update",
"lint": "eslint ./src/**/*"
"lint": "eslint ./src/**/*",
"test": "jest"
},

@@ -24,3 +25,7 @@ "dependencies": {

},
"gitHead": "6e06264c0a1ee601e94527e1f329832c71c66d66"
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"gitHead": "3fb2ec9d38bf253208eb23c4b007415aa0092951"
}

@@ -5,3 +5,3 @@ import { default as uuidv4 } from 'uuid/v4';

test('Testing successful postDocuments', async () => {
test('Testing successful createDocument', async () => {
const client = getTestClient();

@@ -13,9 +13,9 @@

const testBatchId = uuidv4();
const postDocumentsPromise = client.postDocuments(testContent, testContentType, testConsentId, testBatchId);
await expect(postDocumentsPromise).resolves.toHaveProperty('consentId');
await expect(postDocumentsPromise).resolves.toHaveProperty('contentType');
await expect(postDocumentsPromise).resolves.toHaveProperty('documentId');
const createDocumentPromise = client.createDocument(testContent, testContentType, testConsentId, testBatchId);
await expect(createDocumentPromise).resolves.toHaveProperty('consentId');
await expect(createDocumentPromise).resolves.toHaveProperty('contentType');
await expect(createDocumentPromise).resolves.toHaveProperty('documentId');
});
test('Testing erroneous postDocuments', async () => {
test('Testing erroneous createDocument', async () => {
const client = getTestClient();

@@ -26,7 +26,7 @@

const testConsentId = uuidv4();
const postDocumentsPromise = client.postDocuments(testContent, testContentType, testConsentId);
await expect(postDocumentsPromise).rejects.toBeDefined();
const createDocumentPromise = client.createDocument(testContent, testContentType, testConsentId);
await expect(createDocumentPromise).rejects.toBeDefined();
});
test('Testing successful postPredictions', async () => {
test('Testing successful createPrediction', async () => {
const client = getTestClient();

@@ -36,8 +36,8 @@

const testModelName = 'invoice';
const postPredictionsPromise = client.postPredictions(testDocumentId, testModelName);
await expect(postPredictionsPromise).resolves.toHaveProperty('documentId');
await expect(postPredictionsPromise).resolves.toHaveProperty('predictions');
const createPredictionPromise = client.createPrediction(testDocumentId, testModelName);
await expect(createPredictionPromise).resolves.toHaveProperty('documentId');
await expect(createPredictionPromise).resolves.toHaveProperty('predictions');
});
test('Testing erroneous postPredictions', async () => {
test('Testing erroneous createPrediction', async () => {
const client = getTestClient();

@@ -47,61 +47,6 @@

const testModelName = 'erroneousModelName';
const postPredictionsPromise = client.postPredictions(testDocumentId, testModelName);
await expect(postPredictionsPromise).rejects.toBeDefined();
const createPredictionPromise = client.createPrediction(testDocumentId, testModelName);
await expect(createPredictionPromise).rejects.toBeDefined();
});
test('Testing successful postProcesses', async () => {
const client = getTestClient();
const testStateMachineArn = uuidv4();
const testInputData = { [uuidv4()]: uuidv4() };
const postProcessesPromise = client.postProcesses(testStateMachineArn, testInputData);
await expect(postProcessesPromise).resolves.toHaveProperty('executionArn');
});
test('Testing erroneous postProcesses', async () => {
const client = getTestClient();
const testStateMachineArn = uuidv4();
const testInputData = 'ErroneousInputData';
const postProcessesPromise = client.postProcesses(testStateMachineArn, testInputData);
await expect(postProcessesPromise).rejects.toBeDefined();
});
test('Testing successful postTasks', async () => {
const client = getTestClient();
const testActivityArn = uuidv4();
const postTasksPromise = client.postTasks(testActivityArn);
await expect(postTasksPromise).resolves.toBeDefined();
});
test('Testing successful patchTask', async () => {
const client = getTestClient();
const testTaskId = uuidv4();
const testTaskResult = { [uuidv4()]: uuidv4() };
const postTasksPromise = client.patchTasks(testTaskId, testTaskResult);
await expect(postTasksPromise).resolves.toBeDefined();
});
test('Testing erroneous patchTask', async () => {
const client = getTestClient();
const testTaskId = uuidv4();
const testTaskResult = 'ErroneousTaskResult';
const postTasksPromise = client.patchTasks(testTaskId, testTaskResult);
await expect(postTasksPromise).rejects.toBeDefined();
});
test('Testing patchTask with a non-empty taskError', async () => {
const client = getTestClient();
const testTaskId = uuidv4();
const testTaskError = {
code: 'error code',
message: 'error message',
}
const patchTaskPromise = client.patchTasks(testTaskId, {}, { testTaskError });
await expect(patchTaskPromise).resolves.toBeDefined();
})
test('Testing successful getDocument', async () => {

@@ -117,20 +62,14 @@ const client = getTestClient();

test('Testing getProcesses', async () => {
test('Testing listDocuments', async () => {
const client = getTestClient();
const getProcessesPromise = client.getProcesses({ status: 'APPROVED' });
await expect(getProcessesPromise).resolves.toHaveProperty('executionArn');
});
test('Testing getDocuments', async () => {
const client = getTestClient();
const testBatchId = uuidv4();
const getDocumentsPromise = client.getDocuments(testBatchId);
await expect(getDocumentsPromise).resolves.toBeDefined();
const listDocumentsPromise = client.listDocuments(testBatchId);
await expect(listDocumentsPromise).resolves.toBeDefined();
});
test('Testing postBatches', async () => {
test('Testing createBatch', async () => {
const client = getTestClient();
const description = "I am going to create a new batch, give me a batch ID!"
const postBatchesPromise = client.postBatches(description);
await expect(postBatchesPromise).resolves.toHaveProperty('batchId');
const createBatchPromise = client.createBatch(description);
await expect(createBatchPromise).resolves.toHaveProperty('batchId');
});

@@ -5,12 +5,19 @@ import axios, { AxiosRequestConfig } from 'axios';

/**
* A high-level http client for communicating the Lucidtech REST API
*/
export class Client {
apiEndpoint: string;
credentials: Credentials;
constructor(apiEndpoint: string, credentials: Credentials) {
this.apiEndpoint = apiEndpoint;
constructor(credentials: Credentials) {
this.credentials = credentials;
}
/**
* Get document from the REST API, calls the GET /documets/{documentId} endpoint
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @returns {Promise} - document response from REST API
*/
getDocument(documentId: string) {

@@ -20,8 +27,15 @@ return this.makeGetRequest(`/documents/${documentId}`);

getData() {
return this.makeGetRequest('/data');
}
postDocuments(content: string, contentType: string, consentId: string, batchId?: string, feedback?: Array<{[key: string]: string}>) {
let body : any = {
/**
* Creates a document handle, calls the POST /documents endpoint.
*
* @param {string} content - The contents to POST
* @param {string} contentType - A MIME type for the document handle
* @param {string} consentId - An identifier to mark the owner of the document handle
* @param {string} [batchId] - The batch to put the document it
* @param {Array<{ [label: string]: string }>} [feedback] A list of items
* { label: value } representing the ground truth values for the document
* @returns {Promise} - document handle id
*/
createDocument(content: string, contentType: string, consentId: string, batchId?: string, feedback?: Array<{[key: string]: string}>) {
let body: any = {
content: Buffer.from(content).toString('base64'),

@@ -43,10 +57,24 @@ contentType,

getDocuments(batchId: string) {
const query = {
batchId,
};
/**
* @param {string} [batchId] - the batch id that contains the documents of interest
* @param {string} [consentId] - an identifier to mark the owner of the document handle
* @returns {Promise} - documents from REST API contained in batch <batchId>
*/
listDocuments(batchId?: string, consentId?: string) {
const query = { batchId, consentId };
return this.makeGetRequest('/documents', query);
}
postDocumentId(documentId: string, feedback: Array<{[key: string]: string}>) {
/**
* Post feedback to the REST API, calls the POST /documents/{documentId} endpoint.
* Posting feedback means posting the ground truth data for the particular document.
* This enables the API to learn from past mistakes.
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @param {Array<{ [label: string]: string }>} feedback - a list of feedback items
* { label: value } representing the ground truth values for the document
* @returns {Promise} - feedback response from REST API
*/
updateDocument(documentId: string, feedback: Array<{[key: string]: string}>) {
// TODO add test for this method
const body = {

@@ -59,4 +87,14 @@ feedback,

postPredictions(documentId: string, modelName: string) {
const body = {
/**
* Run inference and create a prediction, calls the POST /predictions endpoint.
*
* @param {string} documentId - the document id to run inference and create a prediction on
* @param {string} modelName - the name of the model to use for inference
* @param {number} [maxPages] - maximum number of pages to run predicitons on
* @param {boolean} [autoRotate] - whether or not to let the API try different rotations on
* the document when runnin predictions
* @returns {Promise} - prediction on document
*/
createPrediction(documentId: string, modelName: string, maxPages?: number, autoRotate?: boolean) {
let body: any = {
documentId,

@@ -66,6 +104,20 @@ modelName,

if (maxPages !== undefined) {
body = { ...body, maxPages };
}
if (autoRotate !== undefined) {
body = { ...body, autoRotate };
}
return this.makePostRequest('/predictions', body);
}
postBatches(description: string) {
/**
* Creates a batch handle, calls the POST /batches endpoint
*
* @param {string} description - a short description of the batch you intend to create
* @returns {Promise} - batch handle id and pre-signed upload url
*/
createBatch(description: string) {
const body = {

@@ -78,37 +130,11 @@ description,

getProcesses(search?: { [key: string]: string|Array<string> }) {
return this.makeGetRequest('/processes', search);
}
postProcesses(stateMachineArn: string, inputData: any) {
const body = {
stateMachineArn,
inputData,
};
return this.makePostRequest('/processes', body);
}
postTasks(activityArn: string) {
const body = {
activityArn,
};
return this.makePostRequest('/tasks', body);
}
deleteProcess(processId: string) {
const url = `/processes/${processId}`;
return this.makeDeleteRequest(url);
}
/**
* Either taskResult or taskError shoud be provided, but not both.
* Modifies consent hash for a user, calls the PATCH /users/{user_id} endpoint.
*
* @param {string} userId - the user id to modify consent hash for
* @param {string} consentHash - the consent hash to set
* @returns {Promise} - batch handle id and pre-signed upload url
*/
patchTasks(taskId: string, taskResult?: any, taskError?: any) {
const body = taskResult ? { taskResult } : { taskError };
return this.makePatchRequest(`/tasks/${taskId}`, body);
}
patchUser(userId: string, consentHash: string) {
updateUser(userId: string, consentHash: string) {
// TODO add test for this method
const body = { consentHash };

@@ -118,2 +144,8 @@ return this.makePatchRequest(`/users/${userId}`, body);

/**
* Gets consent hash and user id for a given user id, calls the GET /users/{user_id} endpoint.
*
* @param {string} userId - the user id to get consent hash for
* @returns {Promise} - batch handle id and pre-signed upload url
*/
getUser(userId: string) {

@@ -141,3 +173,3 @@ return this.makeGetRequest(`/users/${userId}`);

return new Promise<any>((resolve, reject) => {
const endpoint = `${this.apiEndpoint}${path}`;
const endpoint = `${this.credentials.apiEndpoint}${path}`;
this.getAuthorizationHeaders().then((headers) => {

@@ -144,0 +176,0 @@ const config = { headers };

@@ -6,2 +6,3 @@ import { TestCredentials, sleep } from './helpers.spec';

test('Testing getAccessToken', async () => {
const testEndpoint = 'http://localhost:4010';
const testApiKey = 'testApiKey';

@@ -11,3 +12,3 @@ const testAccessToken = 'testAccessToken';

const testRefreshToken = 'testRefreshToken';
const credentials = new TestCredentials(testApiKey, testAccessToken, testExpiresInSeconds, testRefreshToken);
const credentials = new TestCredentials(testEndpoint, testApiKey, testAccessToken, testExpiresInSeconds, testRefreshToken);
jest.spyOn(credentials, 'getToken');

@@ -14,0 +15,0 @@

import { TokenStorage } from './storage';
/**
* Wrapper class for an AWS Cognito token
*/
export class Token {

@@ -11,6 +14,14 @@ readonly accessToken: string;

isValid() {
/**
* Checks if current timestamp is larger than token expiration time
*/
isValid(): boolean {
return Date.now() < this.expiration;
}
/**
* @param {string} accessToken
* @param {number} expiration
* @param {string} [refreshToken]
*/
constructor(accessToken: string, expiration: number, refreshToken?: string) {

@@ -23,3 +34,8 @@ this.accessToken = accessToken;

/**
* Use to fetch and store credentials and to generate/cache an access token
*/
export abstract class Credentials {
readonly apiEndpoint: string;
readonly apiKey: string;

@@ -31,3 +47,4 @@

protected constructor(apiKey: string, storage?: TokenStorage<Token>) {
protected constructor(apiEndpoint: string, apiKey: string, storage?: TokenStorage<Token>) {
this.apiEndpoint = apiEndpoint;
this.apiKey = apiKey;

@@ -37,2 +54,8 @@ this.storage = storage;

/**
* Method used to get and cache an access token. Algorithm used:
* 1. Look for a valid token in memory.
* 2. Look for a valid token in the storage (if provided);
* 3. Fetch a new token from server and cache it (both in memory and in storage).
*/
getAccessToken(): Promise<string> {

@@ -39,0 +62,0 @@ const { storage } = this;

import { Credentials, Token } from './credentials';
import { Client } from './client';
const endpoint = 'http://localhost:4010';
export class TestCredentials extends Credentials {

@@ -12,2 +14,3 @@ testAccessToken: string;

constructor(
testEndpoint: string,
testApiKey: string,

@@ -18,3 +21,3 @@ testAccessToken: string,

) {
super(testApiKey);
super(testEndpoint, testApiKey);

@@ -43,7 +46,6 @@ this.testAccessToken = testAccessToken;

const testRefreshToken = 'testRefreshToken';
const credentials = new TestCredentials(testApiKey, testAccessToken, testExpiresInSeconds, testRefreshToken);
const endpoint = 'http://localhost:8080';
return new Client(endpoint, credentials);
const credentials = new TestCredentials(endpoint, testApiKey, testAccessToken, testExpiresInSeconds, testRefreshToken);
return new Client(credentials);
}
test('Loading core helpers', () => {});

@@ -1,2 +0,2 @@

export function buildURL(url: string, params?: { [ key: string ]: string|Array<string> }) {
export function buildURL(url: string, params?: { [ key: string ]: undefined|string|Array<string> }) {
if (!params) {

@@ -7,5 +7,9 @@ return url;

const searchParams = new URLSearchParams();
const queryString = Object.entries(params).forEach((param) => {
const [ key, value ] = param;
Object.entries(params).forEach((param) => {
const [key, value] = param;
if (value === undefined) {
return;
}
if (typeof value === 'string') {

@@ -12,0 +16,0 @@ searchParams.set(key, value);

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