1
0
Fork 0

continue name fixes, list methods in readme

This commit is contained in:
ssube 2021-08-07 19:34:19 -05:00
parent 04de2b2bd5
commit 4ae509ce0c
Signed by: ssube
GPG Key ID: 3EED7B957D362AF1
20 changed files with 192 additions and 160 deletions

126
README.md
View File

@ -63,55 +63,79 @@ The library is bundled and has no dependencies.
## Features ## Features
- array mapper Features utilities and helpers for:
- map elements to keys by order
- skip initial, gather remaining
- async
- defer
- promise timeout
- wait for predicate
- async tracker
- track and log leaking async resources for tests
- buffer
- checklist
- include/exclude mode (whitelist/blacklist)
- child process
- wait for exit and gather output
- write and flush
- env
- check `DEBUG`
- list
- concat lists
- logger
- get test logger (null or console depending on `DEBUG`)
- map
- must get (assertion)
- get or default
- get head from list value
- get head or default
- set or push to key
- merge maps
- push-merge maps
- convert dict to map and vice versa
- normalize map values to lists
- create map from name-value pairs
- maybe
- is nil test (negative nil test)
- count array or maybe
- filter nil from list
- must find (assertion)
- does exist (positive nil test)
- must exist (assertion)
- must default (assertion)
- pid file
- write pid file
- delete pid file
- reflect
- get constructor name
- get methods from prototype chain
- signals
- wait for OS signal
- string
- left pad (please don't import just for this)
- trim with suffix
- Array
- assertions/guards:
- `hasItems`
- `isArray` for both `Array`/`ReadonlyArray`
- `isEmpty`
- `lengthOf`
- conversion
- `filterZip`
- `toArray`
- Array Mapper
- array-to-map converter, reduces an array of values to a map, using an array of keys
- Async
- timed promises
- `defer`/`deferValue`
- `deferUntil`
- `timeout`
- Buffer
- concatenation
- `concat`
- `encode`
- Checklist
- allow/deny list
- Child Process
- `childResult`
- `writeInput`
- Env Vars
- `isDebug`
- Logger
- test logging helpers
- Map
- types
- `MapLike`
- assertions/guards:
- `mustGet`
- null-safe helpers
- `getOrDefault`
- helpers for `Map<K, Array<V>>`
- `getHead`/`getHeadOrDefault`
- `setOrPush`
- concat/merge
- `mergeMap`
- `pushMergeMap`
- conversion
- `entriesOf`
- `makeDict`
- `makeMap`
- `pairsToMap`
- Math
- predicates for functional methods
- `sum`
- Maybe
- types
- `Maybe`
- `None`
- assertions/guards
- `doesExist`
- `mustExist`
- `mustDefault`
- `mustFind`
- `removeNone`
- null-safe helpers
- `isNone`
- `isSome`
- Predicate
- types for functional methods
- Reflect
- `getConstructor`
- `getMethods`
- Signal
- wait for OS signal
- `signal`
- String
- `leftPad`
- `trim` with suffix

View File

@ -0,0 +1,30 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [deferUntil](./js-utils.deferuntil.md)
## deferUntil() function
Reject after a set number of attempts if the given predicate does not return true.
<b>Signature:</b>
```typescript
export declare function deferUntil(cb: PredicateC0, step: number, tries: number): Promise<void>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| cb | PredicateC0 | |
| step | number | |
| tries | number | |
<b>Returns:</b>
Promise&lt;void&gt;
## Exceptions
TimeoutError

View File

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [ExternalModule](./js-utils.externalmodule.md) &gt; [data](./js-utils.externalmodule.data.md)
## ExternalModule.data property
<b>Signature:</b>
```typescript
data?: unknown;
```

View File

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [ExternalModule](./js-utils.externalmodule.md) &gt; [export](./js-utils.externalmodule.export.md)
## ExternalModule.export property
<b>Signature:</b>
```typescript
export: string;
```

View File

@ -1,20 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [ExternalModule](./js-utils.externalmodule.md)
## ExternalModule interface
<b>Signature:</b>
```typescript
export interface ExternalModule
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [data?](./js-utils.externalmodule.data.md) | unknown | <i>(Optional)</i> |
| [export](./js-utils.externalmodule.export.md) | string | |
| [require](./js-utils.externalmodule.require.md) | string | |

View File

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [ExternalModule](./js-utils.externalmodule.md) &gt; [require](./js-utils.externalmodule.require.md)
## ExternalModule.require property
<b>Signature:</b>
```typescript
require: string;
```

View File

@ -27,10 +27,12 @@
| Function | Description | | Function | Description |
| --- | --- | | --- | --- |
| [childResult(child)](./js-utils.childresult.md) | Wait for a child process to exit, collecting output, errors, and exit status. |
| [concat(chunks)](./js-utils.concat.md) | Concatenate a list of buffers. | | [concat(chunks)](./js-utils.concat.md) | Concatenate a list of buffers. |
| [constructorName(val)](./js-utils.constructorname.md) | Get the constructor name from an instance. | | [constructorName(val)](./js-utils.constructorname.md) | Get the constructor name from an instance. |
| [defaultWhen(condition, items)](./js-utils.defaultwhen.md) | Return the first element when <code>condition</code> is true and the second element when <code>condition</code> is false. | | [defaultWhen(condition, items)](./js-utils.defaultwhen.md) | Return the first element when <code>condition</code> is true and the second element when <code>condition</code> is false. |
| [defer(ms)](./js-utils.defer.md) | Resolve after a set amount of time. | | [defer(ms)](./js-utils.defer.md) | Resolve after a set amount of time. |
| [deferUntil(cb, step, tries)](./js-utils.deferuntil.md) | Reject after a set number of attempts if the given predicate does not return true. |
| [deferValue(ms, val)](./js-utils.defervalue.md) | | | [deferValue(ms, val)](./js-utils.defervalue.md) | |
| [doesExist(val)](./js-utils.doesexist.md) | Check if a variable is some <code>T</code>. | | [doesExist(val)](./js-utils.doesexist.md) | Check if a variable is some <code>T</code>. |
| [encode(chunks, encoding)](./js-utils.encode.md) | Concatenate then encode a list of buffers. | | [encode(chunks, encoding)](./js-utils.encode.md) | Concatenate then encode a list of buffers. |
@ -77,14 +79,15 @@
| [removeNone(list)](./js-utils.removenone.md) | Remove any null or undefined items from the list. | | [removeNone(list)](./js-utils.removenone.md) | Remove any null or undefined items from the list. |
| [setOrPush(map, key, val)](./js-utils.setorpush.md) | Set a map key to a new array or push to the existing value. | | [setOrPush(map, key, val)](./js-utils.setorpush.md) | Set a map key to a new array or push to the existing value. |
| [signal(signals)](./js-utils.signal.md) | | | [signal(signals)](./js-utils.signal.md) | |
| [spyLogger(spies)](./js-utils.spylogger.md) | Create a spy logger using the provided methods, which returns itself as a child. | | [spyLogger(spies)](./js-utils.spylogger.md) | Create a spy logger using the provided methods, which returns itself as a child. ensure all methods are present by extending null logger |
| [sum(a, b)](./js-utils.sum.md) | Add numbers. PredicateR2<!-- -->&lt;<!-- -->number, number<!-- -->&gt; | | [sum(a, b)](./js-utils.sum.md) | Add numbers. PredicateR2<!-- -->&lt;<!-- -->number, number<!-- -->&gt; |
| [timeout(ms, oper)](./js-utils.timeout.md) | Reject after a set amount of time if the original promise has not yet resolved. | | [timeout(ms, inner)](./js-utils.timeout.md) | Reject after a set amount of time if the original promise has not yet resolved. |
| [toArray(val)](./js-utils.toarray.md) | | | [toArray(val)](./js-utils.toarray.md) | |
| [toArray(val)](./js-utils.toarray_1.md) | | | [toArray(val)](./js-utils.toarray_1.md) | |
| [trim(val, max, tail)](./js-utils.trim.md) | | | [trim(val, max, tail)](./js-utils.trim.md) | |
| [waitFor(cb, step, count)](./js-utils.waitfor.md) | Reject after a set number of attempts if the given predicate does not return true. | | [waitFor(cb, step, tries)](./js-utils.waitfor.md) | |
| [waitForChild(child)](./js-utils.waitforchild.md) | Wait for a child process to exit, collecting output, errors, and exit status. | | [waitForChild(child)](./js-utils.waitforchild.md) | |
| [writeInput(stream, value)](./js-utils.writeinput.md) | |
| [writeValue(stream, value)](./js-utils.writevalue.md) | | | [writeValue(stream, value)](./js-utils.writevalue.md) | |
## Interfaces ## Interfaces
@ -96,7 +99,6 @@
| [ChildOptions](./js-utils.childoptions.md) | | | [ChildOptions](./js-utils.childoptions.md) | |
| [ChildResult](./js-utils.childresult.md) | | | [ChildResult](./js-utils.childresult.md) | |
| [Dict](./js-utils.dict.md) | | | [Dict](./js-utils.dict.md) | |
| [ExternalModule](./js-utils.externalmodule.md) | |
## Variables ## Variables
@ -114,7 +116,6 @@
| [ChildSpawner](./js-utils.childspawner.md) | | | [ChildSpawner](./js-utils.childspawner.md) | |
| [MapLike](./js-utils.maplike.md) | A <code>Map</code> or dictionary object with string keys and <code>TVal</code> values. | | [MapLike](./js-utils.maplike.md) | A <code>Map</code> or dictionary object with string keys and <code>TVal</code> values. |
| [Maybe](./js-utils.maybe.md) | Value that may be nil. | | [Maybe](./js-utils.maybe.md) | Value that may be nil. |
| [ModuleCtor](./js-utils.modulector.md) | |
| [Nil](./js-utils.nil.md) | Old name for None. | | [Nil](./js-utils.nil.md) | Old name for None. |
| [None](./js-utils.none.md) | Unset value. | | [None](./js-utils.none.md) | Unset value. |
| [Optional](./js-utils.optional.md) | Old name for Maybe. | | [Optional](./js-utils.optional.md) | Old name for Maybe. |

View File

@ -1,11 +0,0 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [ModuleCtor](./js-utils.modulector.md)
## ModuleCtor type
<b>Signature:</b>
```typescript
export declare type ModuleCtor = new (data: unknown) => Module;
```

View File

@ -6,6 +6,8 @@
Create a spy logger using the provided methods, which returns itself as a child. Create a spy logger using the provided methods, which returns itself as a child.
ensure all methods are present by extending null logger
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -9,7 +9,7 @@ Reject after a set amount of time if the original promise has not yet resolved.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript
export declare function timeout<T>(ms: number, oper: Promise<T>): Promise<T>; export declare function timeout<T>(ms: number, inner: Promise<T>): Promise<T>;
``` ```
## Parameters ## Parameters
@ -17,7 +17,7 @@ export declare function timeout<T>(ms: number, oper: Promise<T>): Promise<T>;
| Parameter | Type | Description | | Parameter | Type | Description |
| --- | --- | --- | | --- | --- | --- |
| ms | number | | | ms | number | |
| oper | Promise&lt;T&gt; | | | inner | Promise&lt;T&gt; | |
<b>Returns:</b> <b>Returns:</b>

View File

@ -4,12 +4,14 @@
## waitFor() function ## waitFor() function
Reject after a set number of attempts if the given predicate does not return true. > Warning: This API is now obsolete.
>
>
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript
export declare function waitFor(cb: PredicateC0, step: number, count: number): Promise<void>; export declare function waitFor(cb: PredicateC0, step: number, tries: number): Promise<void>;
``` ```
## Parameters ## Parameters
@ -18,13 +20,9 @@ export declare function waitFor(cb: PredicateC0, step: number, count: number): P
| --- | --- | --- | | --- | --- | --- |
| cb | PredicateC0 | | | cb | PredicateC0 | |
| step | number | | | step | number | |
| count | number | | | tries | number | |
<b>Returns:</b> <b>Returns:</b>
Promise&lt;void&gt; Promise&lt;void&gt;
## Exceptions
TimeoutError

View File

@ -4,7 +4,9 @@
## waitForChild() function ## waitForChild() function
Wait for a child process to exit, collecting output, errors, and exit status. > Warning: This API is now obsolete.
>
>
<b>Signature:</b> <b>Signature:</b>

View File

@ -0,0 +1,23 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [@apextoaster/js-utils](./js-utils.md) &gt; [writeInput](./js-utils.writeinput.md)
## writeInput() function
<b>Signature:</b>
```typescript
export declare function writeInput(stream: Writable, value: string): Promise<boolean>;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| stream | Writable | |
| value | string | |
<b>Returns:</b>
Promise&lt;boolean&gt;

View File

@ -4,6 +4,10 @@
## writeValue() function ## writeValue() function
> Warning: This API is now obsolete.
>
>
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -25,14 +25,14 @@ export function deferValue<T>(ms: number, val: T): Promise<T> {
* Reject after a set amount of time if the original promise has not yet resolved. * Reject after a set amount of time if the original promise has not yet resolved.
* @public * @public
*/ */
export function timeout<T>(ms: number, oper: Promise<T>): Promise<T> { export function timeout<T>(ms: number, inner: Promise<T>): Promise<T> {
const limit = new Promise<T>((_res, rej) => { const limit = new Promise<T>((_res, rej) => {
setTimeout(() => { setTimeout(() => {
rej(new TimeoutError()); rej(new TimeoutError());
}, ms); }, ms);
}); });
return Promise.race([limit, oper]); return Promise.race([limit, inner]);
} }
/** /**
@ -40,15 +40,23 @@ export function timeout<T>(ms: number, oper: Promise<T>): Promise<T> {
* @public * @public
* @throws TimeoutError * @throws TimeoutError
*/ */
export async function waitFor(cb: PredicateC0, step: number, count: number): Promise<void> { export async function deferUntil(cb: PredicateC0, step: number, tries: number): Promise<void> {
let accum = 0; let count = 0;
while (accum < count) { while (count < tries) {
await defer(step); await defer(step);
if (cb()) { if (cb()) {
return; return;
} }
accum += 1; count += 1;
} }
throw new TimeoutError(); throw new TimeoutError();
} }
/**
* @public
* @deprecated
*/
export async function waitFor(cb: PredicateC0, step: number, tries: number): Promise<void> {
return deferUntil(cb, step, tries);
}

View File

@ -37,7 +37,7 @@ const CHILD_OUTPUT = 'child process emitted error output';
* *
* @public * @public
*/ */
export function waitForChild(child: ChildStreams): Promise<ChildResult> { export function childResult(child: ChildStreams): Promise<ChildResult> {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const stderr: Array<Buffer> = []; const stderr: Array<Buffer> = [];
const stdout: Array<Buffer> = []; const stdout: Array<Buffer> = [];
@ -78,7 +78,15 @@ export function waitForChild(child: ChildStreams): Promise<ChildResult> {
}); });
} }
export function writeValue(stream: Writable, value: string): Promise<boolean> { /**
* @public
* @deprecated
*/
export function waitForChild(child: ChildStreams): Promise<ChildResult> {
return childResult(child);
}
export function writeInput(stream: Writable, value: string): Promise<boolean> {
return new Promise<boolean>((res, rej) => { return new Promise<boolean>((res, rej) => {
stream.write(value, (err: Maybe<Error>) => { stream.write(value, (err: Maybe<Error>) => {
if (doesExist(err)) { if (doesExist(err)) {
@ -91,3 +99,11 @@ export function writeValue(stream: Writable, value: string): Promise<boolean> {
}); });
}); });
} }
/**
* @public
* @deprecated
*/
export function writeValue(stream: Writable, value: string): Promise<boolean> {
return writeInput(stream, value);
}

View File

@ -1,14 +0,0 @@
import { Module } from 'noicejs';
export interface ExternalModule {
data?: unknown;
export: string;
require: string;
}
export type ModuleCtor = new (data: unknown) => Module;
export function isModule(it: object): it is ModuleCtor {
const p = Reflect.getPrototypeOf(it);
return p === Module || p instanceof Module;
}

View File

@ -14,11 +14,14 @@ export function getTestLogger(verbose = false): Logger {
/** /**
* Create a spy logger using the provided methods, which returns itself as a child. * Create a spy logger using the provided methods, which returns itself as a child.
*
* @todo ensure all methods are present by extending null logger
*/ */
export function spyLogger(spies: Partial<Logger>): Logger { export function spyLogger(spies: Partial<Logger>): Logger {
const logger = { const logger = {
...spies, ...spies,
child: () => logger, child: () => logger,
} as Logger; } as Logger;
return logger; return logger;
} }

View File

@ -24,6 +24,7 @@ export {
defer, defer,
deferValue, deferValue,
timeout, timeout,
deferUntil,
waitFor, waitFor,
} from './Async'; } from './Async';
export { export {
@ -40,16 +41,14 @@ export {
ChildOptions, ChildOptions,
ChildResult, ChildResult,
ChildSpawner, ChildSpawner,
childResult,
waitForChild, waitForChild,
writeInput,
writeValue, writeValue,
} from './Child'; } from './Child';
export { export {
isDebug isDebug
} from './Env'; } from './Env';
export {
ExternalModule,
ModuleCtor,
} from './ExternalModule';
export { export {
getTestLogger, getTestLogger,
spyLogger, spyLogger,

View File

@ -1,7 +1,7 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { ChildProcessError } from '../../src'; import { ChildProcessError } from '../../src';
import { ChildStreams, waitForChild } from '../../src/Child'; import { ChildStreams, childResult } from '../../src/Child';
import { Maybe, mustExist } from '../../src/Maybe'; import { Maybe, mustExist } from '../../src/Maybe';
type Closer = (status: number) => Promise<void>; type Closer = (status: number) => Promise<void>;
@ -33,7 +33,7 @@ describe('child process utils', async () => {
it('should read stdout data', async () => { it('should read stdout data', async () => {
const child = createChild(); const child = createChild();
const resultPromise = waitForChild(child); const resultPromise = childResult(child);
await mustExist(child.closer)(0); await mustExist(child.closer)(0);
const result = await resultPromise; const result = await resultPromise;
@ -46,7 +46,7 @@ describe('child process utils', async () => {
it('should reject on failure status', async () => { it('should reject on failure status', async () => {
const child = createChild(); const child = createChild();
const resultPromise = waitForChild(child); const resultPromise = childResult(child);
await mustExist(child.closer)(1); await mustExist(child.closer)(1);
return expect(resultPromise).to.eventually.be.rejectedWith(ChildProcessError); return expect(resultPromise).to.eventually.be.rejectedWith(ChildProcessError);