Socket
Socket
Sign inDemoInstall

@openzeppelin/defender-autotask-client

Package Overview
Dependencies
Maintainers
7
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@openzeppelin/defender-autotask-client - npm Package Compare versions

Comparing version 1.54.1 to 1.54.2

78

lib/api.d.ts
/// <reference types="node" />
import { BaseApiClient, ApiVersion } from '@openzeppelin/defender-base-client';
import {
CreateAutotaskRequest,
UpdateAutotaskRequest,
GetSecretsResponse,
SaveSecretsRequest,
EnvironmentVariables,
} from './models/autotask';
import {
AutotaskRunBase,
AutotaskRunListResponse,
AutotaskRunResponse,
AutotaskRunStatus,
} from './models/autotask-run.res';
import { CreateAutotaskRequest, UpdateAutotaskRequest, GetSecretsResponse, SaveSecretsRequest, EnvironmentVariables } from './models/autotask';
import { AutotaskRunBase, AutotaskRunListResponse, AutotaskRunResponse, AutotaskRunStatus } from './models/autotask-run.res';
import { AutotaskDeleteResponse, AutotaskListResponse, AutotaskResponse } from './models/response';
type SourceFiles = {
'index.js': string;
[name: string]: string;
'index.js': string;
[name: string]: string;
};
export declare class AutotaskClient extends BaseApiClient {
protected getPoolId(): string;
protected getPoolClientId(): string;
protected getApiUrl(v?: ApiVersion): string;
list(): Promise<AutotaskListResponse>;
get(autotaskId: string): Promise<AutotaskResponse>;
delete(autotaskId: string): Promise<AutotaskDeleteResponse>;
create(autotask: CreateAutotaskRequest): Promise<AutotaskResponse>;
update(autotask: UpdateAutotaskRequest): Promise<AutotaskResponse>;
getEncodedZippedCodeFromBuffer(code: Buffer): string;
getEncodedZippedCodeFromSources(code: SourceFiles): Promise<string>;
getEncodedZippedCodeFromFolder(code: string): Promise<string>;
updateCodeFromZip(autotaskId: string, zippedCode: Buffer): Promise<void>;
updateCodeFromSources(autotaskId: string, sources: SourceFiles): Promise<void>;
updateCodeFromFolder(autotaskId: string, path: string): Promise<void>;
listAutotaskRuns(
autotaskId: string,
next?: string,
status?: AutotaskRunStatus | undefined,
): Promise<AutotaskRunListResponse>;
getAutotaskRun(autotaskRunId: string): Promise<AutotaskRunResponse>;
runAutotask(
autotaskId: string,
data: {
[key: string]: any;
},
): Promise<AutotaskRunBase>;
getCodeDigest(encodedZippedCode: string): string;
private updateCode;
updateEnvironmentVariables(autotaskId: string, variables: EnvironmentVariables): Promise<EnvironmentVariables>;
getEnvironmentVariables(autotaskId: string): Promise<EnvironmentVariables>;
createSecrets(data: SaveSecretsRequest): Promise<GetSecretsResponse>;
listSecrets(): Promise<GetSecretsResponse>;
protected getPoolId(): string;
protected getPoolClientId(): string;
protected getApiUrl(v?: ApiVersion): string;
list(): Promise<AutotaskListResponse>;
get(autotaskId: string): Promise<AutotaskResponse>;
delete(autotaskId: string): Promise<AutotaskDeleteResponse>;
create(autotask: CreateAutotaskRequest): Promise<AutotaskResponse>;
update(autotask: UpdateAutotaskRequest): Promise<AutotaskResponse>;
getEncodedZippedCodeFromBuffer(code: Buffer): string;
getEncodedZippedCodeFromSources(code: SourceFiles): Promise<string>;
getEncodedZippedCodeFromFolder(code: string): Promise<string>;
updateCodeFromZip(autotaskId: string, zippedCode: Buffer): Promise<void>;
updateCodeFromSources(autotaskId: string, sources: SourceFiles): Promise<void>;
updateCodeFromFolder(autotaskId: string, path: string): Promise<void>;
listAutotaskRuns(autotaskId: string, next?: string, status?: AutotaskRunStatus | undefined): Promise<AutotaskRunListResponse>;
getAutotaskRun(autotaskRunId: string): Promise<AutotaskRunResponse>;
runAutotask(autotaskId: string, data: {
[key: string]: any;
}): Promise<AutotaskRunBase>;
getCodeDigest(encodedZippedCode: string): string;
private updateCode;
updateEnvironmentVariables(autotaskId: string, variables: EnvironmentVariables): Promise<EnvironmentVariables>;
getEnvironmentVariables(autotaskId: string): Promise<EnvironmentVariables>;
createSecrets(data: SaveSecretsRequest): Promise<GetSecretsResponse>;
listSecrets(): Promise<GetSecretsResponse>;
}
export {};
//# sourceMappingURL=api.d.ts.map
//# sourceMappingURL=api.d.ts.map

@@ -1,115 +0,115 @@

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutotaskClient = void 0;
const crypto_1 = require('crypto');
const defender_base_client_1 = require('@openzeppelin/defender-base-client');
const zip_1 = require('./zip');
const crypto_1 = require("crypto");
const defender_base_client_1 = require("@openzeppelin/defender-base-client");
const zip_1 = require("./zip");
class AutotaskClient extends defender_base_client_1.BaseApiClient {
getPoolId() {
return process.env.DEFENDER_AUTOTASK_POOL_ID || 'us-west-2_94f3puJWv';
}
getPoolClientId() {
return process.env.DEFENDER_AUTOTASK_POOL_CLIENT_ID || '40e58hbc7pktmnp9i26hh5nsav';
}
getApiUrl(v = 'v1') {
if (v === 'v2') {
return process.env.DEFENDER_API_V2_URL || 'https://defender-api.openzeppelin.com/v2/';
getPoolId() {
return process.env.DEFENDER_AUTOTASK_POOL_ID || 'us-west-2_94f3puJWv';
}
return process.env.DEFENDER_AUTOTASK_API_URL || 'https://defender-api.openzeppelin.com/autotask/';
}
async list() {
return this.apiCall(async (api) => {
return await api.get(`/autotasks`);
});
}
async get(autotaskId) {
return this.apiCall(async (api) => {
return await api.get(`/autotasks/${autotaskId}`);
});
}
async delete(autotaskId) {
return this.apiCall(async (api) => {
return await api.delete(`/autotasks/${autotaskId}`);
});
}
async create(autotask) {
return this.apiCall(async (api) => {
return await api.post(`/autotasks`, autotask);
});
}
async update(autotask) {
return this.apiCall(async (api) => {
return await api.put(`/autotasks/`, autotask);
});
}
getEncodedZippedCodeFromBuffer(code) {
return code.toString('base64');
}
async getEncodedZippedCodeFromSources(code) {
return await (0, zip_1.zipSources)(code);
}
async getEncodedZippedCodeFromFolder(code) {
return await (0, zip_1.zipFolder)(code);
}
async updateCodeFromZip(autotaskId, zippedCode) {
const encodedZippedCode = this.getEncodedZippedCodeFromBuffer(zippedCode);
return this.updateCode(autotaskId, encodedZippedCode);
}
async updateCodeFromSources(autotaskId, sources) {
const encodedZippedCode = await this.getEncodedZippedCodeFromSources(sources);
return this.updateCode(autotaskId, encodedZippedCode);
}
async updateCodeFromFolder(autotaskId, path) {
const encodedZippedCode = await this.getEncodedZippedCodeFromFolder(path);
return this.updateCode(autotaskId, encodedZippedCode);
}
async listAutotaskRuns(autotaskId, next, status) {
if (next && !status && (next === 'success' || next === 'error' || next === 'pending' || next === 'throttle')) {
status = next;
next = undefined;
getPoolClientId() {
return process.env.DEFENDER_AUTOTASK_POOL_CLIENT_ID || '40e58hbc7pktmnp9i26hh5nsav';
}
return this.apiCall(async (api) => {
return api.get(`/autotasks/${autotaskId}/runs`, { params: { next, status } });
});
}
async getAutotaskRun(autotaskRunId) {
return this.apiCall(async (api) => {
return await api.get(`/autotasks/runs/${autotaskRunId}`);
});
}
async runAutotask(autotaskId, data) {
return this.apiCall(async (api) => {
return await api.post(`/autotasks/${autotaskId}/runs/manual`, data);
});
}
getCodeDigest(encodedZippedCode) {
const binary = Buffer.from(encodedZippedCode, 'base64');
return (0, crypto_1.createHash)('SHA256').update(binary).end().digest('base64');
}
async updateCode(autotaskId, encodedZippedCode) {
return this.apiCall(async (api) => {
return await api.put(`/autotasks/${autotaskId}/code`, { encodedZippedCode });
});
}
async updateEnvironmentVariables(autotaskId, variables) {
return this.apiCall(async (api) => {
return await api.put(`/autotasks/${autotaskId}/environment`, { variables });
});
}
async getEnvironmentVariables(autotaskId) {
return this.apiCall(async (api) => {
return await api.get(`/autotasks/${autotaskId}/environment`);
});
}
async createSecrets(data) {
return this.apiCall(async (api) => {
return await api.post(`/secrets`, data);
});
}
async listSecrets() {
return this.apiCall(async (api) => {
return await api.get(`/secrets`);
});
}
getApiUrl(v = 'v1') {
if (v === 'v2') {
return process.env.DEFENDER_API_V2_URL || 'https://defender-api.openzeppelin.com/v2/';
}
return process.env.DEFENDER_AUTOTASK_API_URL || 'https://defender-api.openzeppelin.com/autotask/';
}
async list() {
return this.apiCall(async (api) => {
return await api.get(`/autotasks`);
});
}
async get(autotaskId) {
return this.apiCall(async (api) => {
return await api.get(`/autotasks/${autotaskId}`);
});
}
async delete(autotaskId) {
return this.apiCall(async (api) => {
return await api.delete(`/autotasks/${autotaskId}`);
});
}
async create(autotask) {
return this.apiCall(async (api) => {
return await api.post(`/autotasks`, autotask);
});
}
async update(autotask) {
return this.apiCall(async (api) => {
return await api.put(`/autotasks/`, autotask);
});
}
getEncodedZippedCodeFromBuffer(code) {
return code.toString('base64');
}
async getEncodedZippedCodeFromSources(code) {
return await (0, zip_1.zipSources)(code);
}
async getEncodedZippedCodeFromFolder(code) {
return await (0, zip_1.zipFolder)(code);
}
async updateCodeFromZip(autotaskId, zippedCode) {
const encodedZippedCode = this.getEncodedZippedCodeFromBuffer(zippedCode);
return this.updateCode(autotaskId, encodedZippedCode);
}
async updateCodeFromSources(autotaskId, sources) {
const encodedZippedCode = await this.getEncodedZippedCodeFromSources(sources);
return this.updateCode(autotaskId, encodedZippedCode);
}
async updateCodeFromFolder(autotaskId, path) {
const encodedZippedCode = await this.getEncodedZippedCodeFromFolder(path);
return this.updateCode(autotaskId, encodedZippedCode);
}
async listAutotaskRuns(autotaskId, next, status) {
if (next && !status && (next === 'success' || next === 'error' || next === 'pending' || next === 'throttle')) {
status = next;
next = undefined;
}
return this.apiCall(async (api) => {
return api.get(`/autotasks/${autotaskId}/runs`, { params: { next, status } });
});
}
async getAutotaskRun(autotaskRunId) {
return this.apiCall(async (api) => {
return await api.get(`/autotasks/runs/${autotaskRunId}`);
});
}
async runAutotask(autotaskId, data) {
return this.apiCall(async (api) => {
return await api.post(`/autotasks/${autotaskId}/runs/manual`, data);
});
}
getCodeDigest(encodedZippedCode) {
const binary = Buffer.from(encodedZippedCode, 'base64');
return (0, crypto_1.createHash)('SHA256').update(binary).end().digest('base64');
}
async updateCode(autotaskId, encodedZippedCode) {
return this.apiCall(async (api) => {
return await api.put(`/autotasks/${autotaskId}/code`, { encodedZippedCode });
});
}
async updateEnvironmentVariables(autotaskId, variables) {
return this.apiCall(async (api) => {
return await api.put(`/autotasks/${autotaskId}/environment`, { variables });
});
}
async getEnvironmentVariables(autotaskId) {
return this.apiCall(async (api) => {
return await api.get(`/autotasks/${autotaskId}/environment`);
});
}
async createSecrets(data) {
return this.apiCall(async (api) => {
return await api.post(`/secrets`, data);
});
}
async listSecrets() {
return this.apiCall(async (api) => {
return await api.get(`/secrets`);
});
}
}
exports.AutotaskClient = AutotaskClient;
#!/usr/bin/env node
import 'dotenv/config';
//# sourceMappingURL=bin.d.ts.map
//# sourceMappingURL=bin.d.ts.map
#!/usr/bin/env node
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('dotenv/config');
const process_1 = require('process');
const _1 = require('.');
const utils_1 = require('./utils');
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("dotenv/config");
const process_1 = require("process");
const _1 = require(".");
const utils_1 = require("./utils");
function printUsage(dueToError = true) {
if (dueToError) {
console.error(`\ndefender-autotask-client: Command not found or wrong parameters provided!\n`);
}
console.error(`Defender Autotask Client (version ${_1.VERSION})\n`);
console.error('Usage: defender-autotask update-code $AUTOTASK_ID $PATH');
console.error('\nExample:\n defender-autotask update-code 19ef0257-bba4-4723-a18f-67d96726213e ./lib/autotask\n');
console.error('Usage: defender-autotask tail-runs $AUTOTASK_ID');
console.error('\nExample:\n defender-autotask tail-runs 19ef0257-bba4-4723-a18f-67d96726213e\n');
console.error('Usage: defender-autotask execute-run $AUTOTASK_ID');
console.error('\nExample:\n defender-autotask execute-run 19ef0257-bba4-4723-a18f-67d96726213e\n');
if (dueToError) {
console.error(`\ndefender-autotask-client: Command not found or wrong parameters provided!\n`);
}
console.error(`Defender Autotask Client (version ${_1.VERSION})\n`);
console.error('Usage: defender-autotask update-code $AUTOTASK_ID $PATH');
console.error('\nExample:\n defender-autotask update-code 19ef0257-bba4-4723-a18f-67d96726213e ./lib/autotask\n');
console.error('Usage: defender-autotask tail-runs $AUTOTASK_ID');
console.error('\nExample:\n defender-autotask tail-runs 19ef0257-bba4-4723-a18f-67d96726213e\n');
console.error('Usage: defender-autotask execute-run $AUTOTASK_ID');
console.error('\nExample:\n defender-autotask execute-run 19ef0257-bba4-4723-a18f-67d96726213e\n');
}

@@ -25,21 +25,21 @@ /**

function mandatoryParamGuard(command) {
switch (command) {
case 'update-code':
if (!process_1.argv[3] || !process_1.argv[4]) {
printUsage();
process.exit(1);
}
break;
// Same requirements for now
case 'tail-runs':
case 'execute-run':
if (!process_1.argv[3]) {
printUsage();
process.exit(1);
}
break;
default:
printUsage();
process.exit(1);
}
switch (command) {
case 'update-code':
if (!process_1.argv[3] || !process_1.argv[4]) {
printUsage();
process.exit(1);
}
break;
// Same requirements for now
case 'tail-runs':
case 'execute-run':
if (!process_1.argv[3]) {
printUsage();
process.exit(1);
}
break;
default:
printUsage();
process.exit(1);
}
}

@@ -51,15 +51,16 @@ /* -------------------------------- Commands -------------------------------- */

async function updateCode() {
const autotaskId = process_1.argv[3];
const path = process_1.argv[4];
try {
(0, utils_1.validateId)(autotaskId);
(0, utils_1.validatePath)(path);
const client = (0, utils_1.initClient)();
console.error(`Uploading code for autotask ${autotaskId} from ${path}...`);
await client.updateCodeFromFolder(autotaskId, path);
} catch (error) {
const err = error;
console.error(`Error updating Autotask code: ${err.message}`);
process.exit(1);
}
const autotaskId = process_1.argv[3];
const path = process_1.argv[4];
try {
(0, utils_1.validateId)(autotaskId);
(0, utils_1.validatePath)(path);
const client = (0, utils_1.initClient)();
console.error(`Uploading code for autotask ${autotaskId} from ${path}...`);
await client.updateCodeFromFolder(autotaskId, path);
}
catch (error) {
const err = error;
console.error(`Error updating Autotask code: ${err.message}`);
process.exit(1);
}
}

@@ -70,10 +71,11 @@ /**

async function tailRuns() {
const autotaskId = process_1.argv[3];
try {
await (0, utils_1.tailLogsFor)((0, utils_1.initClient)(), autotaskId);
} catch (e) {
const err = e;
console.error(`Error on listening to Autotask runs: ${err.message}`);
process.exit(1);
}
const autotaskId = process_1.argv[3];
try {
await (0, utils_1.tailLogsFor)((0, utils_1.initClient)(), autotaskId);
}
catch (e) {
const err = e;
console.error(`Error on listening to Autotask runs: ${err.message}`);
process.exit(1);
}
}

@@ -84,35 +86,34 @@ /**

async function executeRun() {
const autotaskId = process_1.argv[3];
try {
(0, utils_1.validateId)(autotaskId);
const client = (0, utils_1.initClient)();
console.warn(`Executing autotask run for autotask '${autotaskId}'...`);
const resp = await client.runAutotask(autotaskId, {});
console.warn(`Successfully executed autotask run for autotask '${autotaskId}'`);
console.warn(`Run ID: ${resp.autotaskRunId}, \nStatus: ${resp.status}`);
console.warn(`Tip: Call 'defender-autotask tail-runs ${autotaskId}' to follow the runs.`);
} catch (error) {
const err = error;
console.error(`Error executing autotask run: ${err.message}`);
process.exit(1);
}
const autotaskId = process_1.argv[3];
try {
(0, utils_1.validateId)(autotaskId);
const client = (0, utils_1.initClient)();
console.warn(`Executing autotask run for autotask '${autotaskId}'...`);
const resp = await client.runAutotask(autotaskId, {});
console.warn(`Successfully executed autotask run for autotask '${autotaskId}'`);
console.warn(`Run ID: ${resp.autotaskRunId}, \nStatus: ${resp.status}`);
console.warn(`Tip: Call 'defender-autotask tail-runs ${autotaskId}' to follow the runs.`);
}
catch (error) {
const err = error;
console.error(`Error executing autotask run: ${err.message}`);
process.exit(1);
}
}
async function main() {
mandatoryParamGuard(process_1.argv[2]);
switch (process_1.argv[2]) {
case 'update-code':
await updateCode();
break;
case 'tail-runs':
await tailRuns();
break;
case 'execute-run':
await executeRun();
break;
default:
throw new Error(
`unhandled command '${process_1.argv[2]}'. Make sure your 'mandatoryParamGuard' handles this command.`,
);
}
mandatoryParamGuard(process_1.argv[2]);
switch (process_1.argv[2]) {
case 'update-code':
await updateCode();
break;
case 'tail-runs':
await tailRuns();
break;
case 'execute-run':
await executeRun();
break;
default:
throw new Error(`unhandled command '${process_1.argv[2]}'. Make sure your 'mandatoryParamGuard' handles this command.`);
}
}
main();
export { AutotaskClient } from './api';
export {
CreateAutotaskRequest,
UpdateAutotaskRequest,
GetSecretsResponse,
SaveSecretsRequest,
EnvironmentVariables,
} from './models/autotask';
export { CreateAutotaskRequest, UpdateAutotaskRequest, GetSecretsResponse, SaveSecretsRequest, EnvironmentVariables, } from './models/autotask';
export { AutotaskRunBase, AutotaskRunListResponse, AutotaskRunResponse } from './models/autotask-run.res';
export { AutotaskDeleteResponse, AutotaskListResponse, AutotaskResponse } from './models/response';
export declare const VERSION: any;
//# sourceMappingURL=index.d.ts.map
//# sourceMappingURL=index.d.ts.map

@@ -1,12 +0,7 @@

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VERSION = exports.AutotaskClient = void 0;
var api_1 = require('./api');
Object.defineProperty(exports, 'AutotaskClient', {
enumerable: true,
get: function () {
return api_1.AutotaskClient;
},
});
var api_1 = require("./api");
Object.defineProperty(exports, "AutotaskClient", { enumerable: true, get: function () { return api_1.AutotaskClient; } });
// eslint-disable-next-line @typescript-eslint/no-var-requires
exports.VERSION = require('../package.json').version;

@@ -6,36 +6,35 @@ import { Autotask } from './autotask';

export interface AutotaskRunBase {
autotaskRunId: string;
autotaskId: string;
trigger: AutotaskRunTrigger;
status: string;
createdAt: string;
errorType?: AutotaskErrorType;
autotaskRunId: string;
autotaskId: string;
trigger: AutotaskRunTrigger;
status: string;
createdAt: string;
errorType?: AutotaskErrorType;
}
export interface AutotaskRunPendingData {
status: 'pending';
status: 'pending';
}
export interface AutotaskRunThrottledData {
status: 'throttled';
status: 'throttled';
}
export interface AutotaskRunErrorData {
status: 'error';
message: string;
decodedLogs?: string;
requestId?: string;
errorType?: AutotaskErrorType;
status: 'error';
message: string;
decodedLogs?: string;
requestId?: string;
errorType?: AutotaskErrorType;
}
export interface AutotaskRunSuccessData {
status: 'success';
decodedLogs?: string;
result: string;
requestId: string;
status: 'success';
decodedLogs?: string;
result: string;
requestId: string;
}
export type AutotaskRunListResponse = {
items: AutotaskRunBase[];
next: string;
items: AutotaskRunBase[];
next: string;
};
export type AutotaskRunListItemResponse = AutotaskRunBase;
export type AutotaskRunResponse = AutotaskRunBase &
(AutotaskRunPendingData | AutotaskRunErrorData | AutotaskRunSuccessData | AutotaskRunThrottledData);
export type AutotaskRunResponse = AutotaskRunBase & (AutotaskRunPendingData | AutotaskRunErrorData | AutotaskRunSuccessData | AutotaskRunThrottledData);
export type AutotaskRunFinishedResponse = AutotaskRunBase & (AutotaskRunErrorData | AutotaskRunSuccessData);
//# sourceMappingURL=autotask-run.res.d.ts.map
//# sourceMappingURL=autotask-run.res.d.ts.map

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

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export interface CreateAutotaskRequest {
name: string;
encodedZippedCode: string;
relayerId?: string;
trigger: {
type: 'schedule' | 'webhook' | 'sentinel' | 'monitor-filter' | 'scenario';
frequencyMinutes?: number;
cron?: string;
};
paused: boolean;
stackResourceId?: string;
dependenciesVersion?: string;
environmentVariables?: EnvironmentVariables;
name: string;
encodedZippedCode: string;
relayerId?: string;
trigger: {
type: 'schedule' | 'webhook' | 'sentinel' | 'monitor-filter' | 'scenario';
frequencyMinutes?: number;
cron?: string;
};
paused: boolean;
stackResourceId?: string;
dependenciesVersion?: string;
environmentVariables?: EnvironmentVariables;
}
export interface UpdateAutotaskRequest extends Omit<CreateAutotaskRequest, 'encodedZippedCode'> {
autotaskId: string;
encodedZippedCode?: string;
autotaskId: string;
encodedZippedCode?: string;
}
export interface ScheduleTrigger {
type: 'schedule';
frequencyMinutes?: number;
cron?: string;
type: 'schedule';
frequencyMinutes?: number;
cron?: string;
}
export interface WebhookTrigger {
type: 'webhook';
token: string;
type: 'webhook';
token: string;
}
export interface SentinelTrigger {
type: 'sentinel';
type: 'sentinel';
}
export interface MonitorFilterTrigger {
type: 'monitor-filter';
type: 'monitor-filter';
}
export type ScenarioTrigger = {
type: 'scenario';
type: 'scenario';
};
export interface Autotask
extends Pick<
CreateAutotaskRequest,
'name' | 'relayerId' | 'paused' | 'stackResourceId' | 'dependenciesVersion' | 'environmentVariables'
> {
autotaskId: string;
encodedZippedCode?: string;
trigger: ScheduleTrigger | WebhookTrigger | SentinelTrigger | MonitorFilterTrigger | ScenarioTrigger;
createdAt?: string;
codeDigest?: string;
export interface Autotask extends Pick<CreateAutotaskRequest, 'name' | 'relayerId' | 'paused' | 'stackResourceId' | 'dependenciesVersion' | 'environmentVariables'> {
autotaskId: string;
encodedZippedCode?: string;
trigger: ScheduleTrigger | WebhookTrigger | SentinelTrigger | MonitorFilterTrigger | ScenarioTrigger;
createdAt?: string;
codeDigest?: string;
}
export interface SaveSecretsRequest {
deletes: string[];
secrets: SecretsMap;
deletes: string[];
secrets: SecretsMap;
}
export interface SecretsMap {
[k: string]: string;
[k: string]: string;
}
export interface GetSecretsResponse {
secretNames?: string[];
secretNames?: string[];
}
export type EnvironmentVariables = {
[key: string]: string;
[key: string]: string;
};
//# sourceMappingURL=autotask.d.ts.map
//# sourceMappingURL=autotask.d.ts.map

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

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
import { Autotask } from './autotask';
export type AutotaskListResponse = {
items: Autotask[];
keyValueStoreItemsCount: number;
runsQuotaUsage: number;
items: Autotask[];
keyValueStoreItemsCount: number;
runsQuotaUsage: number;
};
export type AutotaskResponse = Autotask;
export type AutotaskDeleteResponse = {
message: string;
message: string;
};
//# sourceMappingURL=response.d.ts.map
//# sourceMappingURL=response.d.ts.map

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

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

@@ -16,2 +16,2 @@ import { AutotaskClient } from './api';

export declare function tailLogsFor(client: AutotaskClient, autotaskId: string): Promise<void>;
//# sourceMappingURL=utils.d.ts.map
//# sourceMappingURL=utils.d.ts.map

@@ -1,6 +0,6 @@

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tailLogsFor = exports.validatePath = exports.validateId = exports.initClient = void 0;
const fs_1 = require('fs');
const api_1 = require('./api');
const fs_1 = require("fs");
const api_1 = require("./api");
/**

@@ -11,6 +11,7 @@ * Verifies that the environment variables are present and initializes the client.

function initClient() {
const { API_KEY: apiKey, API_SECRET: apiSecret } = process.env;
if (!apiKey || !apiSecret) throw new Error(`API_KEY or API_SECRET env vars are missing`);
const client = new api_1.AutotaskClient({ apiKey, apiSecret });
return client;
const { API_KEY: apiKey, API_SECRET: apiSecret } = process.env;
if (!apiKey || !apiSecret)
throw new Error(`API_KEY or API_SECRET env vars are missing`);
const client = new api_1.AutotaskClient({ apiKey, apiSecret });
return client;
}

@@ -22,8 +23,9 @@ exports.initClient = initClient;

function validateId(id) {
const regex = /^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/i;
if (regex.test(id)) {
return;
} else {
throw new Error(`invalid id '${id}'`);
}
const regex = /^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/i;
if (regex.test(id)) {
return;
}
else {
throw new Error(`invalid id '${id}'`);
}
}

@@ -35,43 +37,47 @@ exports.validateId = validateId;

function validatePath(path) {
if ((0, fs_1.existsSync)(path)) {
return;
} else {
throw new Error(`path ${path} does not exist`);
}
if ((0, fs_1.existsSync)(path)) {
return;
}
else {
throw new Error(`path ${path} does not exist`);
}
}
exports.validatePath = validatePath;
async function tailLogsFor(client, autotaskId) {
try {
validateId(autotaskId);
console.warn(`\nPolling latest runs of autotask '${autotaskId}'...\n`);
// Poll autotask runs every 2 seconds and if there are new runs, get run details and print them out.
let lastRun;
while (true) {
const newRuns = await client.listAutotaskRuns(autotaskId);
// If cached last run id has changed
if (newRuns.items[0]?.autotaskRunId !== lastRun?.autotaskRunId) {
lastRun = newRuns.items[0]; // cache new last run to avoid duplicates.
if (!lastRun) throw new Error('last run not found');
const status = lastRun.status;
if (status === 'pending') {
lastRun = undefined; // clean up so we can check it again on the next poll.
} else if (status === 'error') {
const runDetails = await client.getAutotaskRun(lastRun.autotaskRunId);
console.log(`\nError: ${runDetails.message}`);
runDetails.decodedLogs ? console.log(`\n${runDetails.decodedLogs}`) : console.log(`No logs available.`);
} else if (status === 'success') {
const runDetails = await client.getAutotaskRun(lastRun.autotaskRunId);
console.log(`\n${runDetails.decodedLogs}`);
} else if (status === 'throttled') {
console.warn(
`\nThis autotask run was canceled since the hourly run capacity for your account has been exceeded. Contact us at defender-support@openzeppelin.com for additional capacity.`,
);
try {
validateId(autotaskId);
console.warn(`\nPolling latest runs of autotask '${autotaskId}'...\n`);
// Poll autotask runs every 2 seconds and if there are new runs, get run details and print them out.
let lastRun;
while (true) {
const newRuns = await client.listAutotaskRuns(autotaskId);
// If cached last run id has changed
if (newRuns.items[0]?.autotaskRunId !== lastRun?.autotaskRunId) {
lastRun = newRuns.items[0]; // cache new last run to avoid duplicates.
if (!lastRun)
throw new Error('last run not found');
const status = lastRun.status;
if (status === 'pending') {
lastRun = undefined; // clean up so we can check it again on the next poll.
}
else if (status === 'error') {
const runDetails = (await client.getAutotaskRun(lastRun.autotaskRunId));
console.log(`\nError: ${runDetails.message}`);
runDetails.decodedLogs ? console.log(`\n${runDetails.decodedLogs}`) : console.log(`No logs available.`);
}
else if (status === 'success') {
const runDetails = (await client.getAutotaskRun(lastRun.autotaskRunId));
console.log(`\n${runDetails.decodedLogs}`);
}
else if (status === 'throttled') {
console.warn(`\nThis autotask run was canceled since the hourly run capacity for your account has been exceeded. Contact us at defender-support@openzeppelin.com for additional capacity.`);
}
}
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
await new Promise((resolve) => setTimeout(resolve, 2000));
}
} catch (e) {
throw e;
}
catch (e) {
throw e;
}
}
exports.tailLogsFor = tailLogsFor;

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

export declare function zipSources(sources: { [name: string]: string }): Promise<string>;
export declare function zipSources(sources: {
[name: string]: string;
}): Promise<string>;
export declare function zipFolder(folderPath: string): Promise<string>;
//# sourceMappingURL=zip.d.ts.map
//# sourceMappingURL=zip.d.ts.map

@@ -1,39 +0,38 @@

'use strict';
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, '__esModule', { value: true });
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.zipFolder = exports.zipSources = void 0;
const jszip_1 = __importDefault(require('jszip'));
const glob_1 = __importDefault(require('glob'));
const util_1 = require('util');
const fs_1 = require('fs');
const fs_2 = require('fs');
const path_1 = require('path');
const jszip_1 = __importDefault(require("jszip"));
const glob_1 = __importDefault(require("glob"));
const util_1 = require("util");
const fs_1 = require("fs");
const fs_2 = require("fs");
const path_1 = require("path");
async function zipSources(sources) {
if (!sources['index.js']) throw new Error(`Expected index.js entrypoint in sources`);
const zip = new jszip_1.default();
for (const source in sources) {
zip.file(source, sources[source], { binary: false });
}
const zippedCode = await zip.generateAsync({ type: 'nodebuffer' });
return zippedCode.toString('base64');
if (!sources['index.js'])
throw new Error(`Expected index.js entrypoint in sources`);
const zip = new jszip_1.default();
for (const source in sources) {
zip.file(source, sources[source], { binary: false });
}
const zippedCode = await zip.generateAsync({ type: 'nodebuffer' });
return zippedCode.toString('base64');
}
exports.zipSources = zipSources;
async function zipFolder(folderPath) {
if (!(0, fs_2.existsSync)((0, path_1.join)(folderPath, 'index.js')))
throw new Error(`Expected index.js entrypoint in folder`);
const files = await (0, util_1.promisify)(glob_1.default)('**', { cwd: folderPath, nodir: true });
const zip = new jszip_1.default();
for (const path of files) {
const content = await (0, util_1.promisify)(fs_1.readFile)((0, path_1.join)(folderPath, path));
// We hardcode the date so we generate the same zip every time given the same contents
// This allows us to use the codedigest to decide whether or not to reupload code
zip.file(path, content, { date: new Date(2020, 1, 1, 0, 0, 0, 0) });
}
const zippedCode = await zip.generateAsync({ type: 'nodebuffer' });
return zippedCode.toString('base64');
if (!(0, fs_2.existsSync)((0, path_1.join)(folderPath, 'index.js')))
throw new Error(`Expected index.js entrypoint in folder`);
const files = await (0, util_1.promisify)(glob_1.default)('**', { cwd: folderPath, nodir: true });
const zip = new jszip_1.default();
for (const path of files) {
const content = await (0, util_1.promisify)(fs_1.readFile)((0, path_1.join)(folderPath, path));
// We hardcode the date so we generate the same zip every time given the same contents
// This allows us to use the codedigest to decide whether or not to reupload code
zip.file(path, content, { date: new Date(2020, 1, 1, 0, 0, 0, 0) });
}
const zippedCode = await zip.generateAsync({ type: 'nodebuffer' });
return zippedCode.toString('base64');
}
exports.zipFolder = zipFolder;
export {};
//# sourceMappingURL=zip.test.d.ts.map
//# sourceMappingURL=zip.test.d.ts.map

@@ -1,47 +0,41 @@

'use strict';
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, '__esModule', { value: true });
const jszip_1 = __importDefault(require('jszip'));
const zip_1 = require('./zip');
const path_1 = require('path');
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jszip_1 = __importDefault(require("jszip"));
const zip_1 = require("./zip");
const path_1 = require("path");
describe('zip', () => {
describe('zipSources', () => {
it('zips sources', async function () {
const zip = await (0, zip_1.zipSources)({
'index.js': 'exports.handler = () => {};',
'data.json': '{ "value": 42 }',
'subfolder/nested.json': '{ "nested": true }',
});
await expectZip(zip);
describe('zipSources', () => {
it('zips sources', async function () {
const zip = await (0, zip_1.zipSources)({
'index.js': 'exports.handler = () => {};',
'data.json': '{ "value": 42 }',
'subfolder/nested.json': '{ "nested": true }',
});
await expectZip(zip);
});
it('validates index.js', async function () {
expect(() => (0, zip_1.zipSources)({ 'other.js': 'exports.handler = () => {};' })).rejects.toThrowError(/entrypoint/);
});
});
it('validates index.js', async function () {
expect(() => (0, zip_1.zipSources)({ 'other.js': 'exports.handler = () => {};' })).rejects.toThrowError(
/entrypoint/,
);
describe('zipFolder', () => {
it('zips folder', async function () {
const zip = await (0, zip_1.zipFolder)((0, path_1.resolve)(__dirname, '../fixtures/valid'));
await expectZip(zip);
});
it('validates index.js', async function () {
expect(() => (0, zip_1.zipFolder)((0, path_1.resolve)(__dirname, '../fixtures/invalid'))).rejects.toThrowError(/entrypoint/);
});
});
});
describe('zipFolder', () => {
it('zips folder', async function () {
const zip = await (0, zip_1.zipFolder)((0, path_1.resolve)(__dirname, '../fixtures/valid'));
await expectZip(zip);
});
it('validates index.js', async function () {
expect(() => (0, zip_1.zipFolder)((0, path_1.resolve)(__dirname, '../fixtures/invalid'))).rejects.toThrowError(
/entrypoint/,
);
});
});
});
async function expectZip(zipContent) {
const zip = new jszip_1.default();
await zip.loadAsync(Buffer.from(zipContent, 'base64'));
expect(Object.keys(zip.files).sort()).toEqual(['data.json', 'index.js', 'subfolder/', 'subfolder/nested.json']);
console.log(await zip.file('index.js')?.async('text'));
expect(await zip.file('index.js')?.async('text')).toEqual('exports.handler = () => {};');
expect(await zip.file('data.json')?.async('text')).toEqual('{ "value": 42 }');
expect(await zip.file('subfolder/nested.json')?.async('text')).toEqual('{ "nested": true }');
const zip = new jszip_1.default();
await zip.loadAsync(Buffer.from(zipContent, 'base64'));
expect(Object.keys(zip.files).sort()).toEqual(['data.json', 'index.js', 'subfolder/', 'subfolder/nested.json']);
console.log(await zip.file('index.js')?.async('text'));
expect(await zip.file('index.js')?.async('text')).toEqual('exports.handler = () => {};');
expect(await zip.file('data.json')?.async('text')).toEqual('{ "value": 42 }');
expect(await zip.file('subfolder/nested.json')?.async('text')).toEqual('{ "nested": true }');
}
{
"name": "@openzeppelin/defender-autotask-client",
"version": "1.54.1",
"version": "1.54.2",
"description": "Client library for managing Defender Autotasks",

@@ -30,3 +30,3 @@ "bin": {

"dependencies": {
"@openzeppelin/defender-base-client": "1.54.1",
"@openzeppelin/defender-base-client": "1.54.2",
"axios": "^1.4.0",

@@ -43,3 +43,3 @@ "dotenv": "^10.0.0",

},
"gitHead": "ff20768e5718ebff4bccc199508834bb7219f7c1"
"gitHead": "a4f42ccd3773997da730ed215a2600dc94aefd43"
}

Sorry, the diff of this file is not supported yet

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