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

@xyo-network/utils

Package Overview
Dependencies
Maintainers
6
Versions
482
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@xyo-network/utils - npm Package Compare versions

Comparing version 0.26.0 to 0.29.0

src/@types/bs58.d.ts

13

dist/@types/index.d.ts

@@ -6,8 +6,12 @@ import { IXyoMetaList } from '@xyo-network/meta-list';

export declare type Callback = (...args: any[]) => void;
export interface IXyoRepository<K, V> {
add(id: K, item: V): Promise<void>;
export interface IRepoItem<V, M> {
data: V;
meta: M;
}
export interface IXyoRepository<K, V, M> {
add(id: K, item: V, meta?: M): Promise<void>;
remove(id: K): Promise<void>;
contains(id: K): Promise<boolean>;
find(id: K): Promise<V | undefined>;
list(limit: number, cursor: string | undefined): Promise<IXyoMetaList<V>>;
find(id: K): Promise<IRepoItem<V, M> | undefined>;
list(limit: number, cursor: string | undefined): Promise<IXyoMetaList<IRepoItem<V, M>>>;
}

@@ -25,2 +29,3 @@ export declare type pureFn<V> = () => V;

get(context: C): Promise<V>;
add(v: V, keep?: boolean): Promise<C>;
}

@@ -27,0 +32,0 @@ export interface IFactory<V> {

/// <reference types="node" />
export { unsubscribeFn, Callback, IXyoRepository, asyncPureFn, parameterizedFactoryFn, parameterizedProviderFn, providerFn, pureFn, IFactory, IParameterizedFactory, IParameterizedProvider, IProvider, factoryFn, IInitializable, ILifeCyclable, IRunnable, ILifeCycleEvent, IXyoProvider, IXyoProviderContainer, depScope } from './@types';
export { unsubscribeFn, Callback, IXyoRepository, asyncPureFn, parameterizedFactoryFn, parameterizedProviderFn, providerFn, pureFn, IFactory, IParameterizedFactory, IParameterizedProvider, IProvider, factoryFn, IInitializable, ILifeCyclable, IRunnable, ILifeCycleEvent, IXyoProvider, IXyoProviderContainer, depScope, IRepoItem } from './@types';
export { ProcessManager } from './process-manager';
import BigNumber = require('bn.js');
export { BigNumber as BN };
import fs from 'fs';
import { ILifeCyclable, ILifeCycleEvent, asyncPureFn, IXyoRepository, parameterizedFactoryFn } from './@types';
import { ILifeCyclable, ILifeCycleEvent, asyncPureFn } from './@types';
import { XyoBase } from '@xyo-network/base';

@@ -17,2 +19,7 @@ import { EventEmitter } from 'events';

export declare const writeFile: typeof fs.writeFile.__promisify__;
export interface IXyoRunnable {
type: 'daemon' | 'loop' | 'task';
run(): Promise<void>;
stop(): Promise<void>;
}
export declare class BaseLifeCyclable extends XyoBase implements ILifeCyclable {

@@ -49,2 +56,13 @@ private readonly partialImplementation?;

}
export declare abstract class XyoDaemon extends XyoBase {
private resolveStopLoopingPromise?;
private unscheduleTimeout;
private looping;
start(): Promise<void>;
stop(): Promise<void>;
protected abstract run(): Promise<void> | void;
protected delayRun(currentValue: number, errorOccurred: boolean): number | undefined;
protected shouldStop(): boolean;
private runner;
}
export declare class LifeCycleRunner {

@@ -61,20 +79,12 @@ readonly lifeCyclable: ILifeCyclable;

}
export declare const base58: {
encode: (b: Buffer) => string;
decode: (hex: string) => Buffer;
};
export declare function fileExists(pathToFile: string): Promise<boolean>;
export declare class XyoBaseInMemoryRepository<K, V> extends XyoBase implements IXyoRepository<K, V> {
private readonly toString;
private readonly inMemoryRepo;
constructor(toString: parameterizedFactoryFn<K, string>);
add(id: K, item: V): Promise<void>;
remove(id: K): Promise<void>;
contains(id: K): Promise<boolean>;
find(id: K): Promise<V | undefined>;
list(limit: number, cursor: string | undefined): Promise<{
items: V[];
meta: {
hasNextPage: boolean;
totalCount: number;
endCursor: string | undefined;
};
}>;
export declare class XyoPair<K, V> {
readonly k: K;
readonly v: V;
constructor(k: K, v: V);
}
//# sourceMappingURL=index.d.ts.map

@@ -16,2 +16,6 @@ "use strict";

exports.ProcessManager = process_manager_1.ProcessManager;
/// <reference path="./@types/bs58.d.ts" />
const bs58_1 = __importDefault(require("bs58"));
const BigNumber = require("bn.js");
exports.BN = BigNumber;
const util_1 = require("util");

@@ -67,3 +71,2 @@ const fs_1 = __importDefault(require("fs"));

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:pre:initialize`);
if (this.partialImplementation && this.partialImplementation.onPreInitialize) {

@@ -77,3 +80,2 @@ yield this.partialImplementation.onPreInitialize();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:initialize`);
if (this.partialImplementation && this.partialImplementation.onInitialize) {

@@ -87,3 +89,2 @@ yield this.partialImplementation.onInitialize();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:post:initialize`);
if (this.partialImplementation && this.partialImplementation.onPostInitialize) {

@@ -97,3 +98,2 @@ yield this.partialImplementation.onPostInitialize();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:pre:started`);
if (this.partialImplementation && this.partialImplementation.onPreStart) {

@@ -107,3 +107,2 @@ yield this.partialImplementation.onPreStart();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:started`);
if (this.partialImplementation && this.partialImplementation.onStart) {

@@ -117,3 +116,2 @@ yield this.partialImplementation.onStart();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:post:started`);
if (this.partialImplementation && this.partialImplementation.onPostStart) {

@@ -127,3 +125,2 @@ yield this.partialImplementation.onPostStart();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:pre:stopped`);
if (this.partialImplementation && this.partialImplementation.onPreStop) {

@@ -137,3 +134,2 @@ yield this.partialImplementation.onPreStop();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:stopped`);
if (this.partialImplementation && this.partialImplementation.onStop) {

@@ -147,3 +143,2 @@ yield this.partialImplementation.onStop();

return __awaiter(this, void 0, void 0, function* () {
this.logInfo(`${this.constructor.name}:post:stopped`);
if (this.partialImplementation && this.partialImplementation.onPostStop) {

@@ -220,2 +215,73 @@ yield this.partialImplementation.onPostStop();

// tslint:disable-next-line:max-classes-per-file
class XyoDaemon extends base_1.XyoBase {
constructor() {
super(...arguments);
this.looping = false;
}
start() {
return __awaiter(this, void 0, void 0, function* () {
return this.runner(500);
});
}
stop() {
return __awaiter(this, void 0, void 0, function* () {
if (this.unscheduleTimeout)
this.unscheduleTimeout();
this.unscheduleTimeout = undefined;
return new Promise((resolve, reject) => {
if (!this.looping) {
return resolve();
}
this.resolveStopLoopingPromise = resolve;
});
});
}
delayRun(currentValue, errorOccurred) {
return errorOccurred ? currentValue * 2 : 500; // exponential back-off
}
shouldStop() {
return this.resolveStopLoopingPromise !== undefined;
}
runner(timeout) {
return __awaiter(this, void 0, void 0, function* () {
this.looping = true;
let errorOccurred = false;
if (this.shouldStop()) {
if (this.resolveStopLoopingPromise) {
this.resolveStopLoopingPromise();
this.resolveStopLoopingPromise = undefined;
}
this.looping = false;
return;
}
try {
const runReq = this.run();
if (runReq !== undefined) {
yield runReq;
}
}
catch (err) {
this.logError(`There was an error in the block-producer loop`, err);
errorOccurred = true;
}
if (this.shouldStop()) {
if (this.resolveStopLoopingPromise) {
this.resolveStopLoopingPromise();
this.resolveStopLoopingPromise = undefined;
}
this.looping = false;
return;
}
const delay = this.delayRun(timeout, errorOccurred);
if (delay === undefined) {
this.looping = false;
return;
}
this.looping = false;
this.unscheduleTimeout = base_1.XyoBase.timeout(() => this.runner(delay), delay);
});
}
}
exports.XyoDaemon = XyoDaemon;
// tslint:disable-next-line:max-classes-per-file
class LifeCycleRunner {

@@ -229,3 +295,3 @@ constructor(lifeCyclable) {

if (!this.canInitialize()) {
throw new errors_1.XyoError(`Already initialized, can not initialize again`, errors_1.XyoErrors.CRITICAL);
throw new errors_1.XyoError(`Already initialized, can not initialize again`);
}

@@ -244,3 +310,3 @@ this.state = null;

if (!this.canStart()) {
throw new errors_1.XyoError(`Not yet initialized, can not start`, errors_1.XyoErrors.CRITICAL);
throw new errors_1.XyoError(`Not yet initialized, can not start`);
}

@@ -258,3 +324,3 @@ yield this.lifeCyclable.preStart();

if (!this.canStop()) {
throw new errors_1.XyoError(`Not yet started, can not stop`, errors_1.XyoErrors.CRITICAL);
throw new errors_1.XyoError(`Not yet started, can not stop`);
}

@@ -280,2 +346,6 @@ yield this.lifeCyclable.preStop();

exports.LifeCycleRunner = LifeCycleRunner;
exports.base58 = {
encode: (b) => bs58_1.default.encode(b),
decode: (hex) => bs58_1.default.decode(hex)
};
function fileExists(pathToFile) {

@@ -292,91 +362,9 @@ return __awaiter(this, void 0, void 0, function* () {

// tslint:disable-next-line:max-classes-per-file
class XyoBaseInMemoryRepository extends base_1.XyoBase {
constructor(toString) {
super();
this.toString = toString;
this.inMemoryRepo = {};
class XyoPair {
constructor(k, v) {
this.k = k;
this.v = v;
}
add(id, item) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.inMemoryRepo[this.toString(id)]) {
this.inMemoryRepo[this.toString(id)] = item;
}
return;
});
}
remove(id) {
return __awaiter(this, void 0, void 0, function* () {
delete this.inMemoryRepo[this.toString(id)];
});
}
contains(id) {
return __awaiter(this, void 0, void 0, function* () {
return Boolean(this.inMemoryRepo[this.toString(id)]);
});
}
find(id) {
return __awaiter(this, void 0, void 0, function* () {
return this.inMemoryRepo[this.toString(id)] || undefined;
});
}
list(limit, cursor) {
return __awaiter(this, void 0, void 0, function* () {
let startingIndex = 0;
const allKeys = Object.keys(this.inMemoryRepo);
if (cursor) {
const indexOfCursor = allKeys.indexOf(cursor);
if (indexOfCursor === -1) {
return {
meta: {
totalCount: allKeys.length,
hasNextPage: false,
endCursor: undefined
},
items: []
};
}
startingIndex = indexOfCursor + 1;
}
if (startingIndex >= allKeys.length) {
return {
meta: {
totalCount: allKeys.length,
hasNextPage: false,
endCursor: undefined
},
items: []
};
}
// tslint:disable-next-line:prefer-array-literal
const items = [];
let hasNextPage = false;
let nextCursor;
let iterations = 0;
let indexOfNext = startingIndex + iterations;
while (true) {
const key = allKeys[indexOfNext];
items.push(this.inMemoryRepo[key]);
iterations += 1;
indexOfNext = startingIndex + iterations;
hasNextPage = allKeys.length > indexOfNext;
if (iterations === limit) {
nextCursor = key;
break;
}
if (!hasNextPage) {
break;
}
}
return {
items,
meta: {
hasNextPage,
totalCount: allKeys.length,
endCursor: nextCursor,
},
};
});
}
}
exports.XyoBaseInMemoryRepository = XyoBaseInMemoryRepository;
exports.XyoPair = XyoPair;
//# sourceMappingURL=index.js.map

@@ -21,2 +21,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("@xyo-network/base");
class ProcessManager {

@@ -30,5 +31,7 @@ constructor(program) {

process.on('beforeExit', (exitCode) => {
base_1.XyoBase.unschedule();
console.log(`Will exit with exitCode ${exitCode}`);
})
.on('exit', (exitCode) => __awaiter(this, void 0, void 0, function* () {
base_1.XyoBase.unschedule();
if (this.program.canStop()) {

@@ -76,4 +79,10 @@ yield this.program.stop();

}));
yield this.program.initialize();
yield this.program.start();
try {
yield this.program.initialize();
yield this.program.start();
}
catch (e) {
console.error(`Uncaught error in process-manager`, e);
throw e;
}
});

@@ -80,0 +89,0 @@ }

{
"name": "@xyo-network/utils",
"version": "0.26.0",
"version": "0.29.0",
"description": "Provides utility functionality",

@@ -10,7 +10,10 @@ "main": "dist/index.js",

"dependencies": {
"@xyo-network/base": "^0.26.0",
"@xyo-network/errors": "^0.26.0",
"@xyo-network/meta-list": "^0.26.0"
"@xyo-network/base": "^0.29.0",
"@xyo-network/errors": "^0.29.0",
"@xyo-network/meta-list": "^0.29.0",
"bn.js": "^4.11.8",
"bs58": "^4.0.1"
},
"devDependencies": {
"@types/bn.js": "^4.11.3",
"@types/jest": "^23.3.1",

@@ -24,3 +27,3 @@ "@types/node": "^10.7.1",

},
"gitHead": "b86b8078d87e72f0a132bc5e1d6c87aa29e00b7b"
"gitHead": "6d3ef6cac153314b05cda28efed3bac7efeaa55d"
}
import { IXyoMetaList } from '@xyo-network/meta-list'
import { XyoPair } from '..'

@@ -9,8 +10,13 @@ /** A function to unsubscribe from a topic */

export interface IXyoRepository<K, V> {
add(id: K, item: V): Promise<void>
export interface IRepoItem<V, M> {
data: V,
meta: M
}
export interface IXyoRepository<K, V, M> {
add(id: K, item: V, meta?: M): Promise<void>
remove(id: K): Promise<void>
contains(id: K): Promise<boolean>
find(id: K): Promise<V | undefined>
list(limit: number, cursor: string | undefined): Promise<IXyoMetaList<V>>
find(id: K): Promise<IRepoItem<V, M> | undefined>
list(limit: number, cursor: string | undefined): Promise<IXyoMetaList<IRepoItem<V, M>>>
}

@@ -31,2 +37,3 @@

get(context: C): Promise<V>
add(v: V, keep?: boolean): Promise<C>
}

@@ -33,0 +40,0 @@ export interface IFactory<V> {

@@ -22,3 +22,4 @@

IXyoProviderContainer,
depScope
depScope,
IRepoItem
} from './@types'

@@ -28,2 +29,7 @@

/// <reference path="./@types/bs58.d.ts" />
import bs58 from 'bs58'
import BigNumber = require('bn.js')
export { BigNumber as BN }
import { promisify } from "util"

@@ -74,2 +80,8 @@ import fs from 'fs'

export interface IXyoRunnable {
type: 'daemon' | 'loop' | 'task'
run(): Promise<void>
stop(): Promise<void>
}
export class BaseLifeCyclable extends XyoBase implements ILifeCyclable {

@@ -85,3 +97,2 @@

public async preInitialize(): Promise<void> {
this.logInfo(`${this.constructor.name}:pre:initialize`)
if (this.partialImplementation && this.partialImplementation.onPreInitialize) {

@@ -95,3 +106,2 @@ await this.partialImplementation.onPreInitialize()

public async initialize(): Promise<void> {
this.logInfo(`${this.constructor.name}:initialize`)
if (this.partialImplementation && this.partialImplementation.onInitialize) {

@@ -105,4 +115,2 @@ await this.partialImplementation.onInitialize()

public async postInitialize(): Promise<void> {
this.logInfo(`${this.constructor.name}:post:initialize`)
if (this.partialImplementation && this.partialImplementation.onPostInitialize) {

@@ -116,4 +124,2 @@ await this.partialImplementation.onPostInitialize()

public async preStart(): Promise<void> {
this.logInfo(`${this.constructor.name}:pre:started`)
if (this.partialImplementation && this.partialImplementation.onPreStart) {

@@ -127,4 +133,2 @@ await this.partialImplementation.onPreStart()

public async start(): Promise<void> {
this.logInfo(`${this.constructor.name}:started`)
if (this.partialImplementation && this.partialImplementation.onStart) {

@@ -138,4 +142,2 @@ await this.partialImplementation.onStart()

public async postStart(): Promise<void> {
this.logInfo(`${this.constructor.name}:post:started`)
if (this.partialImplementation && this.partialImplementation.onPostStart) {

@@ -149,4 +151,2 @@ await this.partialImplementation.onPostStart()

public async preStop(): Promise<void> {
this.logInfo(`${this.constructor.name}:pre:stopped`)
if (this.partialImplementation && this.partialImplementation.onPreStop) {

@@ -160,4 +160,2 @@ await this.partialImplementation.onPreStop()

public async stop(): Promise<void> {
this.logInfo(`${this.constructor.name}:stopped`)
if (this.partialImplementation && this.partialImplementation.onStop) {

@@ -171,4 +169,2 @@ await this.partialImplementation.onStop()

public async postStop(): Promise<void> {
this.logInfo(`${this.constructor.name}:post:stopped`)
if (this.partialImplementation && this.partialImplementation.onPostStop) {

@@ -257,2 +253,80 @@ await this.partialImplementation.onPostStop()

// tslint:disable-next-line:max-classes-per-file
export abstract class XyoDaemon extends XyoBase {
private resolveStopLoopingPromise?: () => void
private unscheduleTimeout: (() => void) | undefined
private looping = false
public async start(): Promise<void> {
return this.runner(500)
}
public async stop(): Promise<void> {
if (this.unscheduleTimeout) this.unscheduleTimeout()
this.unscheduleTimeout = undefined
return new Promise((resolve, reject) => {
if (!this.looping) {
return resolve()
}
this.resolveStopLoopingPromise = resolve
})
}
protected abstract run(): Promise<void> | void
protected delayRun(currentValue: number, errorOccurred: boolean): number | undefined {
return errorOccurred ? currentValue * 2 : 500 // exponential back-off
}
protected shouldStop(): boolean {
return this.resolveStopLoopingPromise !== undefined
}
private async runner(timeout: number) {
this.looping = true
let errorOccurred = false
if (this.shouldStop()) {
if (this.resolveStopLoopingPromise) {
this.resolveStopLoopingPromise()
this.resolveStopLoopingPromise = undefined
}
this.looping = false
return
}
try {
const runReq = this.run()
if (runReq !== undefined) {
await runReq
}
} catch (err) {
this.logError(`There was an error in the block-producer loop`, err)
errorOccurred = true
}
if (this.shouldStop()) {
if (this.resolveStopLoopingPromise) {
this.resolveStopLoopingPromise()
this.resolveStopLoopingPromise = undefined
}
this.looping = false
return
}
const delay = this.delayRun(timeout, errorOccurred)
if (delay === undefined) {
this.looping = false
return
}
this.looping = false
this.unscheduleTimeout = XyoBase.timeout(() => this.runner(delay), delay)
}
}
// tslint:disable-next-line:max-classes-per-file
export class LifeCycleRunner {

@@ -276,3 +350,3 @@ public state:

if (!this.canInitialize()) {
throw new XyoError(`Already initialized, can not initialize again`, XyoErrors.CRITICAL)
throw new XyoError(`Already initialized, can not initialize again`)
}

@@ -293,3 +367,3 @@

if (!this.canStart()) {
throw new XyoError(`Not yet initialized, can not start`, XyoErrors.CRITICAL)
throw new XyoError(`Not yet initialized, can not start`)
}

@@ -309,3 +383,3 @@

if (!this.canStop()) {
throw new XyoError(`Not yet started, can not stop`, XyoErrors.CRITICAL)
throw new XyoError(`Not yet started, can not stop`)
}

@@ -336,2 +410,7 @@

export const base58 = {
encode: (b: Buffer) => bs58.encode(b),
decode: (hex: string) => bs58.decode(hex)
}
export async function fileExists(pathToFile: string): Promise<boolean> {

@@ -346,92 +425,4 @@ return new Promise((resolve, reject) => {

// tslint:disable-next-line:max-classes-per-file
export class XyoBaseInMemoryRepository<K, V> extends XyoBase implements IXyoRepository<K, V> {
private readonly inMemoryRepo: {[s: string]: V} = {}
constructor(private readonly toString: parameterizedFactoryFn<K, string>) {
super()
}
public async add(id: K, item: V) {
if (!this.inMemoryRepo[this.toString(id)]) {
this.inMemoryRepo[this.toString(id)] = item
}
return
}
public async remove(id: K) {
delete this.inMemoryRepo[this.toString(id)]
}
public async contains(id: K) {
return Boolean(this.inMemoryRepo[this.toString(id)])
}
public async find(id: K) {
return this.inMemoryRepo[this.toString(id)] || undefined
}
public async list(limit: number, cursor: string | undefined) {
let startingIndex = 0
const allKeys = Object.keys(this.inMemoryRepo)
if (cursor) {
const indexOfCursor = allKeys.indexOf(cursor)
if (indexOfCursor === -1) {
return {
meta: {
totalCount: allKeys.length,
hasNextPage: false,
endCursor: undefined
},
items: []
}
}
startingIndex = indexOfCursor + 1
}
if (startingIndex >= allKeys.length) {
return {
meta: {
totalCount: allKeys.length,
hasNextPage: false,
endCursor: undefined
},
items: []
}
}
// tslint:disable-next-line:prefer-array-literal
const items: V[] = []
let hasNextPage = false
let nextCursor: string | undefined
let iterations = 0
let indexOfNext = startingIndex + iterations
while (true) {
const key = allKeys[indexOfNext]
items.push(this.inMemoryRepo[key])
iterations += 1
indexOfNext = startingIndex + iterations
hasNextPage = allKeys.length > indexOfNext
if (iterations === limit) {
nextCursor = key
break
}
if (!hasNextPage) {
break
}
}
return {
items,
meta: {
hasNextPage,
totalCount: allKeys.length,
endCursor: nextCursor,
},
}
}
export class XyoPair<K, V> {
constructor(public readonly k: K, public readonly v: V) {}
}

@@ -15,2 +15,3 @@ /*

import { LifeCycleRunner } from "."
import { XyoBase } from "@xyo-network/base"

@@ -25,5 +26,7 @@ export class ProcessManager {

process.on('beforeExit', (exitCode) => {
XyoBase.unschedule()
console.log(`Will exit with exitCode ${exitCode}`)
})
.on('exit', async (exitCode) => {
XyoBase.unschedule()
if (this.program.canStop()) {

@@ -75,5 +78,10 @@ await this.program.stop()

await this.program.initialize()
await this.program.start()
try {
await this.program.initialize()
await this.program.start()
} catch (e) {
console.error(`Uncaught error in process-manager`, e)
throw e
}
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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