+
## jy-transform:jyt ℗
The command line interface.
-**Access:** private
+**Access**: private
* [jy-transform:jyt](#module_jy-transform_jyt) ℗
* [~usage](#module_jy-transform_jyt..usage) : string ℗
@@ -186,15 +214,15 @@ The command line interface.
### jy-transform:jyt~usage : string ℗
How to use the CLI.
-**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
-**Access:** private
+**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
+**Access**: private
### jy-transform:jyt~packagePath : string ℗
The path to package.json.
-**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
-**Access:** private
+**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
+**Access**: private
### jy-transform:jyt~options : Object ℗
@@ -203,19 +231,19 @@ The options description for parsing the command line input, must be an object wi
long_tag: [short_tag, description, value_type, default_value];
```
-**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
-**Access:** private
+**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
+**Access**: private
### jy-transform:jyt~error(err) ℗
-Prints the error to console and exit with 1.
+Prints the error to console and exits process with 1.
-**Kind**: inner method of [jy-transform:jyt](#module_jy-transform_jyt)
-**Access:** private
+**Kind**: inner method of [jy-transform:jyt](#module_jy-transform_jyt)
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
-| err | string | Error | The error to print. |
+| err | string \| Error | The error to print. |
@@ -224,22 +252,22 @@ The main entry callback. When calling `cli.main()` this receives the `options`
given on CLI, then does the transformation with these options and finally, it
prints the result to the CLI.
-**Kind**: inner method of [jy-transform:jyt](#module_jy-transform_jyt)
-**Access:** private
+**Kind**: inner method of [jy-transform:jyt](#module_jy-transform_jyt)
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
| args | Array | The first mandatory argument is the input file (`args[0]`), the second (optional) argument is the output file (`args[1]`). |
-| cliOptions | module:jy-transform:type-definitions~Options | The options provided via CLI. |
+| cliOptions | module:jy-transform:type-definitions~TransformerOptions | The options provided via CLI. |
-## jy-transform:constants ℗
+## jy-transform:constants
Useful constants used for the module and its usage.
-**Access:** private
+**Access**: public
-* [jy-transform:constants](#module_jy-transform_constants) ℗
+* [jy-transform:constants](#module_jy-transform_constants)
* [~DEFAULT_OPTIONS](#module_jy-transform_constants..DEFAULT_OPTIONS) : object ℗
* [~UTF8](#module_jy-transform_constants..UTF8) : string ℗
* [~TYPE_YAML](#module_jy-transform_constants..TYPE_YAML) : string
@@ -263,8 +291,8 @@ Useful constants used for the module and its usage.
### jy-transform:constants~DEFAULT_OPTIONS : object ℗
The default options.
-**Kind**: inner namespace of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner namespace of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
**See**
- [ORIGIN_DESCRIPTION](ORIGIN_DESCRIPTION)
@@ -288,106 +316,106 @@ The default options.
### jy-transform:constants~UTF8 : string ℗
The 'utf8' constant.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~TYPE_YAML : string
-The 'yaml' type constant.
+The `'yaml'` type constant.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** public
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: public
### jy-transform:constants~TYPE_JSON : string
-The 'json' type constant.
+The `'json'` type constant.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** public
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: public
### jy-transform:constants~TYPE_JS : string
-The 'js' type constant.
+The `'js'` type constant.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** public
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: public
### jy-transform:constants~TYPE_MAP : Object ℗
A map for extensions to type.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~DEFAULT_INDENT : number ℗
The default file indention (4 SPACEs).
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~MIN_INDENT : number ℗
The minimum file indention (0 SPACE).
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~MAX_INDENT : number ℗
The maximum file indention (8 SPACEs).
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~DEFAULT_ORIGIN : string ℗
The default `origin` value: 'yaml'.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~DEFAULT_TARGET : string ℗
The default `origin` value: 'js'.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~DEFAULT_FORCE_FILE_OVERWRITE : boolean ℗
Whether to overwrite existing file or object on output.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~ORIGIN_DESCRIPTION : string ℗
The `origin` description value.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~TARGET_DESCRIPTION : string ℗
The `target` description value.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~DEST_DESCRIPTION : string ℗
The `dest` description value.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
### jy-transform:constants~DEFAULT_JS_IMPORTS_IDENTIFIER : string ℗
The `src` exports identifier value to read.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
**Example**
```js
module.exports.foo = {...}; // here 'foo' is the identifier for an object to read from the source!
@@ -397,8 +425,8 @@ module.exports.foo = {...}; // here 'foo' is the identifier for an object to rea
### jy-transform:constants~DEFAULT_JS_EXPORTS_IDENTIFIER : string ℗
The `dest` exports identifier value to write.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
-**Access:** private
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
## jy-transform:debug-log ℗
@@ -406,7 +434,7 @@ The debug logger. Can be enabled via environment variables (set to `true`):
- `JYT_DEBUG`: (only DEBUG logging via `console.log`)
- `JYT_DEBUG`: (only ERROR logging via `console.error`)
-**Access:** private
+**Access**: private
* [jy-transform:debug-log](#module_jy-transform_debug-log) ℗
* [~debug](#module_jy-transform_debug-log..debug)
@@ -417,23 +445,23 @@ The debug logger. Can be enabled via environment variables (set to `true`):
### jy-transform:debug-log~debug
DEBUG function.
-**Kind**: inner constant of [jy-transform:debug-log](#module_jy-transform_debug-log)
-**Access:** protected
+**Kind**: inner constant of [jy-transform:debug-log](#module_jy-transform_debug-log)
+**Access**: protected
### jy-transform:debug-log~error
DEBUG function.
-**Kind**: inner constant of [jy-transform:debug-log](#module_jy-transform_debug-log)
-**Access:** protected
+**Kind**: inner constant of [jy-transform:debug-log](#module_jy-transform_debug-log)
+**Access**: protected
-## jy-transform:reader
+## jy-transform:reader ℗
This module provides the _read_ functionality for YAML, JS or JSON sources.
-**Access:** public
+**Access**: private
-* [jy-transform:reader](#module_jy-transform_reader)
+* [jy-transform:reader](#module_jy-transform_reader) ℗
* [~fsPromisified](#module_jy-transform_reader..fsPromisified) ℗
* [~readFromStream(readable, origin)](#module_jy-transform_reader..readFromStream) ⇒ Promise.<Object> ℗
@@ -442,16 +470,16 @@ This module provides the _read_ functionality for YAML, JS or JSON sources.
### jy-transform:reader~fsPromisified ℗
Promisified `fs` module.
-**Kind**: inner constant of [jy-transform:reader](#module_jy-transform_reader)
-**Access:** private
+**Kind**: inner constant of [jy-transform:reader](#module_jy-transform_reader)
+**Access**: private
### jy-transform:reader~readFromStream(readable, origin) ⇒ Promise.<Object> ℗
Reads from a passed stream and resolves by callback.
-**Kind**: inner method of [jy-transform:reader](#module_jy-transform_reader)
+**Kind**: inner method of [jy-transform:reader](#module_jy-transform_reader)
**Returns**: Promise.<Object> - The read content as JS object representation.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
@@ -460,141 +488,24 @@ Reads from a passed stream and resolves by callback.
-## jy-transform:transformer
+## jy-transform:transformer ℗
This module provides the _transform_ functionality for YAML, JS or JSON source to destination mapping.
-**Access:** public
-
-
-## jy-transform:type-definitions
-The type definitions for this module.
-
-**Access:** public
-
-* [jy-transform:type-definitions](#module_jy-transform_type-definitions)
- * [~ReaderOptions](#module_jy-transform_type-definitions..ReaderOptions) : object
- * [~WriterOptions](#module_jy-transform_type-definitions..WriterOptions) : object
- * [~TransformerOptions](#module_jy-transform_type-definitions..TransformerOptions) : object
- * [~joi](#external_joi) ℗
- * [.ValidationError](#external_joi.ValidationError) ℗
- * [.Schema](#external_joi.Schema) ℗
- * [.Extension](#external_joi.Extension) ℗
- * [.validate](#external_joi.validate) : function ℗
-
-
-
-### jy-transform:type-definitions~ReaderOptions : object
-The configuration properties provided to the reader function.
-
-**Kind**: inner typedef of [jy-transform:type-definitions](#module_jy-transform_type-definitions)
-**Access:** public
-**Properties**
-
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| src | string | Stream.Readable | object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
-
-
-
-### jy-transform:type-definitions~WriterOptions : object
-The writer configuration properties provided to the writer function.
-
-**Kind**: inner typedef of [jy-transform:type-definitions](#module_jy-transform_type-definitions)
-**Access:** public
-**Properties**
-
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| dest | string | Stream.Writable | object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| indent | number | 2 | The indention in files. |
-| exports | string | | The exports name for usage in JS destination files only. |
-| force | string | false | Force overwriting of existing output files on write phase. |
-
-
-
-### jy-transform:type-definitions~TransformerOptions : object
-The configuration properties provided to the transformer function.
-
-**Kind**: inner typedef of [jy-transform:type-definitions](#module_jy-transform_type-definitions)
-**Access:** public
-**Properties**
-
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| src | string | Stream.Readable | object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
-| dest | string | Stream.Writable | object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| exports | string | | The exports name for usage in JS destination files only. |
-| indent | number | 2 | The indention in files. |
-| force | string | false | Force overwriting of existing output files on write phase. |
-
-
-
-### jy-transform:type-definitions~joi ℗
-Hapi.js Joi.
-
-**Kind**: inner external of [jy-transform:type-definitions](#module_jy-transform_type-definitions)
-**Access:** private
-**See**: [Hapi Joi](https://github.com/hapijs/joi)
-
-* [~joi](#external_joi) ℗
- * [.ValidationError](#external_joi.ValidationError) ℗
- * [.Schema](#external_joi.Schema) ℗
- * [.Extension](#external_joi.Extension) ℗
- * [.validate](#external_joi.validate) : function ℗
-
-
-
-#### joi.ValidationError ℗
-Joi validation error.
-
-**Kind**: static typedef of [joi](#external_joi)
-**Access:** private
-**See**: [Joi errors](hhttps://github.com/hapijs/joi/blob/v10.2.0/API.md#errors)
-
-
-#### joi.Schema ℗
-The validation schema. Can be a [joi](#external_joi) type object or a plain object
-where every key is assigned a [joi](#external_joi) type object.
-
-**Kind**: static typedef of [joi](#external_joi)
-**Access:** private
-**See**: [Joi API](https://github.com/hapijs/joi/blob/v10.2.2/API.md#joi)
-
-
-#### joi.Extension ℗
-Hapi.js Joi schema extension.
-
-**Kind**: static typedef of [joi](#external_joi)
-**Access:** private
-**See**: [Hapi Joi Extension](https://github.com/hapijs/joi/blob/v10.2.2/API.md#extendextension)
-
-
-#### joi.validate : function ℗
-Joi `validate` method.
-
-**Kind**: static typedef of [joi](#external_joi)
-**Access:** private
-**See**: [Joi.validate](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)
+**Access**: private
## jy-transform:validation:joi-extensions-file-helper ℗
An (extended) Joi validation schema helper functions for the module options on FS validation.
-**Access:** private
+**Access**: private
### jy-transform:validation:joi-extensions-file-helper~isExistingFile(pathStr) ⇒ boolean
Checks if given `pathStr` is an existing file after resolving `pathStr` relative to CWD.
-**Kind**: inner method of [jy-transform:validation:joi-extensions-file-helper](#module_jy-transform_validation_joi-extensions-file-helper)
+**Kind**: inner method of [jy-transform:validation:joi-extensions-file-helper](#module_jy-transform_validation_joi-extensions-file-helper)
**Returns**: boolean - Value `true` if it is a file and exists, else `false`.
-**Access:** protected
+**Access**: protected
| Param | Type | Description |
| --- | --- | --- |
@@ -605,7 +516,7 @@ Checks if given `pathStr` is an existing file after resolving `pathStr` relative
## jy-transform:validation:joi-extensions-identifier-helper ℗
An (extended) Joi validation schema helper function for the module options to validate ES6 identifiers.
-**Access:** private
+**Access**: private
* [jy-transform:validation:joi-extensions-identifier-helper](#module_jy-transform_validation_joi-extensions-identifier-helper) ℗
* [~identifierRegExpECMAScript6](#module_jy-transform_validation_joi-extensions-identifier-helper..identifierRegExpECMAScript6) : RegExp ℗
@@ -617,16 +528,16 @@ An (extended) Joi validation schema helper function for the module options to va
Created at [Generating a regular expression to match valid JavaScript identifiers]
(https://mathiasbynens.be/demo/javascript-identifier-regex).
-**Kind**: inner constant of [jy-transform:validation:joi-extensions-identifier-helper](#module_jy-transform_validation_joi-extensions-identifier-helper)
-**Access:** private
+**Kind**: inner constant of [jy-transform:validation:joi-extensions-identifier-helper](#module_jy-transform_validation_joi-extensions-identifier-helper)
+**Access**: private
### jy-transform:validation:joi-extensions-identifier-helper~isValidEs6Identifier(identifier) ⇒ boolean
This method checks if a given `identifier` is a valid ECMAScript 6 identifier.
-**Kind**: inner method of [jy-transform:validation:joi-extensions-identifier-helper](#module_jy-transform_validation_joi-extensions-identifier-helper)
+**Kind**: inner method of [jy-transform:validation:joi-extensions-identifier-helper](#module_jy-transform_validation_joi-extensions-identifier-helper)
**Returns**: boolean - A `true` if valid, else `false`.
-**Access:** protected
+**Access**: protected
| Param | Type | Description |
| --- | --- | --- |
@@ -643,24 +554,24 @@ console.log('valid = ' + isValidEs6Identifier(identifier));
## jy-transform:validation:joi-extension ℗
The module exporting the [Extension](#external_joi.Extension)s for option validations.
-**Access:** private
+**Access**: private
**See**: [Joi.extend(extension) method](https://github.com/hapijs/joi/blob/v10.2.2/API.md#extendextension).
-### jy-transform:validation:joi-extension~EXTENSIONS : [Extension](#external_joi.Extension) ℗
+### jy-transform:validation:joi-extension~EXTENSIONS : [Extension](#external_joi.Extension) ℗
The common [Schema](#external_joi.Schema) validation extensions:
- `existingFile` - needs to be an absolute or relative path to an existing file.
- `validEs6Identifier` - needs to be a valid ECMAScript 6 identifier.
-**Kind**: inner constant of [jy-transform:validation:joi-extension](#module_jy-transform_validation_joi-extension)
-**Access:** private
+**Kind**: inner constant of [jy-transform:validation:joi-extension](#module_jy-transform_validation_joi-extension)
+**Access**: private
## jy-transform:validation:options-schema-helper : Object ℗
Provides some helper functions used in [module:validation:options-schema](module:validation:options-schema) to resolve default
values for origin and target depending on the `options.src` or `options.dest` value.
-**Access:** private
+**Access**: private
**See**: [module:validation:options-schema](module:validation:options-schema)
* [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper) : Object ℗
@@ -673,9 +584,9 @@ values for origin and target depending on the `options.src` or `options.dest` va
### jy-transform:validation:options-schema-helper~inferOriginDefault ⇒ string
Infers the _origin_ type value from current validation context.
-**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
**Returns**: string - The target type.
-**Access:** protected
+**Access**: protected
| Param | Type | Description |
| --- | --- | --- |
@@ -686,9 +597,9 @@ Infers the _origin_ type value from current validation context.
### jy-transform:validation:options-schema-helper~inferTargetDefault ⇒ string
Infers the _target_ type value from current validation context.
-**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
**Returns**: string - The target type.
-**Access:** protected
+**Access**: protected
| Param | Type | Description |
| --- | --- | --- |
@@ -699,9 +610,9 @@ Infers the _target_ type value from current validation context.
### jy-transform:validation:options-schema-helper~getTypeFromFilePath(pathStr, defaultValue) ⇒ string ℗
Infer from path extension to a type using default value as fallback.
-**Kind**: inner method of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Kind**: inner method of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
**Returns**: string - A type value.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
@@ -713,7 +624,7 @@ Infer from path extension to a type using default value as fallback.
## jy-transform:validation:options-schema : Object ℗
The module options schema used in [module:options-validator](module:options-validator).
-**Access:** private
+**Access**: private
**See**: [module:options-validator](module:options-validator)
* [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema) : Object ℗
@@ -725,24 +636,24 @@ The module options schema used in [module:options-validator](module:options-vali
### jy-transform:validation:options-schema~readerOptionsSchema : JoiSchema ℗
The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [Reader](Reader) options.
-**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
-**Access:** private
+**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
+**Access**: private
### jy-transform:validation:options-schema~writerOptionsSchema : JoiSchema ℗
The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [Writer](Writer) options.
-**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
-**Access:** private
+**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
+**Access**: private
-## jy-transform:writer
+## jy-transform:writer ℗
This module provides the _write_ functionality to write JS objects from memory to a JSON/JS/YAML
destination (file, object or [stream.Readable](stream.Readable)).
-**Access:** public
+**Access**: private
-* [jy-transform:writer](#module_jy-transform_writer)
+* [jy-transform:writer](#module_jy-transform_writer) ℗
* [~fsPromisified](#module_jy-transform_writer..fsPromisified) ℗
* [~writeToStream(object, dest, target)](#module_jy-transform_writer..writeToStream) ⇒ Promise.<string> ℗
@@ -751,20 +662,20 @@ destination (file, object or [stream.Readable](stream.Readable)).
### jy-transform:writer~fsPromisified ℗
Promisified `fs` module.
-**Kind**: inner constant of [jy-transform:writer](#module_jy-transform_writer)
-**Access:** private
+**Kind**: inner constant of [jy-transform:writer](#module_jy-transform_writer)
+**Access**: private
### jy-transform:writer~writeToStream(object, dest, target) ⇒ Promise.<string> ℗
Writes a string serialized data object to a stream.
-**Kind**: inner method of [jy-transform:writer](#module_jy-transform_writer)
+**Kind**: inner method of [jy-transform:writer](#module_jy-transform_writer)
**Returns**: Promise.<string> - Containing the write success message to handle by caller (e.g. for logging).
**Throws**:
- Error If serialized JS object could not be written due to any reason.
-**Access:** private
+**Access**: private
**See**
- [TYPE_YAML](TYPE_YAML)
@@ -783,7 +694,7 @@ Writes a string serialized data object to a stream.
## jy-transform:unit:helper-constants : Object ℗
The test suite constants definitions.
-**Access:** private
+**Access**: private
* [jy-transform:unit:helper-constants](#module_jy-transform_unit_helper-constants) : Object ℗
* [~TEST_SUITE_DESCRIPTION_UNIT](#module_jy-transform_unit_helper-constants..TEST_SUITE_DESCRIPTION_UNIT) : string
@@ -794,21 +705,21 @@ The test suite constants definitions.
### jy-transform:unit:helper-constants~TEST_SUITE_DESCRIPTION_UNIT : string
The unit test suite description for the plugin.
-**Kind**: inner constant of [jy-transform:unit:helper-constants](#module_jy-transform_unit_helper-constants)
-**Access:** public
+**Kind**: inner constant of [jy-transform:unit:helper-constants](#module_jy-transform_unit_helper-constants)
+**Access**: public
### jy-transform:unit:helper-constants~TEST_SUITE_DESCRIPTION_FUNCTIONAL : string
The unit test suite description for the plugin.
-**Kind**: inner constant of [jy-transform:unit:helper-constants](#module_jy-transform_unit_helper-constants)
-**Access:** public
+**Kind**: inner constant of [jy-transform:unit:helper-constants](#module_jy-transform_unit_helper-constants)
+**Access**: public
## jy-transform:unit:logger : Object ℗
The test suite logger.
-**Access:** private
+**Access**: private
* [jy-transform:unit:logger](#module_jy-transform_unit_logger) : Object ℗
* [~INDENT](#module_jy-transform_unit_logger..INDENT) : string ℗
@@ -825,28 +736,28 @@ The test suite logger.
### jy-transform:unit:logger~INDENT : string ℗
An indent of 0 SPACEs.
-**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
-**Access:** private
+**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
+**Access**: private
### jy-transform:unit:logger~TEST_TMP_DIR : string ℗
A temporary test directory.
-**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
-**Access:** private
+**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
+**Access**: private
### jy-transform:unit:logger~winstonFileOptions : Object ℗
Options for winston file logging.
-**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
-**Access:** private
+**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
+**Access**: private
#### winstonFileOptions.timestamp() ⇒ string
Formats the timestamp as [Date](Date) ISO string prefixed by an indent.
-**Kind**: static method of [winstonFileOptions](#module_jy-transform_unit_logger..winstonFileOptions)
+**Kind**: static method of [winstonFileOptions](#module_jy-transform_unit_logger..winstonFileOptions)
**Returns**: string - - The [Date](Date) ISO string.
**See**: #INDENT
@@ -854,14 +765,14 @@ Formats the timestamp as [Date](Date) ISO string prefixed by an indent.
### jy-transform:unit:logger~winstonConsoleOptions : Object ℗
Options for winston console logging.
-**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
-**Access:** private
+**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
+**Access**: private
#### winstonConsoleOptions.timestamp() ⇒ string
Overwrites the timestamp by indent.
-**Kind**: static method of [winstonConsoleOptions](#module_jy-transform_unit_logger..winstonConsoleOptions)
+**Kind**: static method of [winstonConsoleOptions](#module_jy-transform_unit_logger..winstonConsoleOptions)
**Returns**: string - - The indent only.
**See**: #INDENT
@@ -869,69 +780,75 @@ Overwrites the timestamp by indent.
### jy-transform:unit:logger~logger
The winston logger.
-**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
-**Access:** protected
+**Kind**: inner constant of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
+**Access**: protected
### jy-transform:unit:logger~formatter(options) ⇒ string ℗
This function formats the log string by given options to log.
-**Kind**: inner method of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
+**Kind**: inner method of [jy-transform:unit:logger](#module_jy-transform_unit_logger)
**Returns**: string - The log string.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
| options | Object | The formatter options. |
+
+
+## jy-transform:unit-test:test-cli ℗
+This unit test suite checks the correct transformation behaviour of the CLI interface.
+
+**Access**: private
## jy-transform:test-unit:index ℗
This unit test module tests the correct exporting from _./index.js_.
-**Access:** private
+**Access**: private
## jy-transform:unit-test:test-reader ℗
-This unit test suite checks the validity and correctness of _./src/reader.js_ module.
+This unit test suite checks the validity and correctness of the Reader module.
-**Access:** private
+**Access**: private
## jy-transform:unit-test:test-transformer ℗
-This unit test suite checks the correct transformation behaviour of [Transformer](Transformer) class.
+This unit test suite checks the correct transformation behaviour of the Transformer module.
-**Access:** private
+**Access**: private
## jy-transform:unit-test:test-writer ℗
-This unit test suite checks the validity and correctness of _./src/js_ module.
+This unit test suite checks the validity and correctness of Writer module.
-**Access:** private
+**Access**: private
## jy-transform:test-unit:test-joi-extension-file-helper ℗
This unit test module tests validation FS helper method.
-**Access:** private
+**Access**: private
## jy-transform:unit-test:test-joi-extensions-identifier-helper ℗
This unit test suite checks validity and correctness of ES6 identifiers.
-**Access:** private
+**Access**: private
## jy-transform:unit-test:test-options-schema-helper ℗
This unit test suite checks the validity and correctness of options schema helper methods.
-**Access:** private
+**Access**: private
## jy-transform:unit-test:test-options-schema ℗
This unit test suite checks the validity and correctness of options schema.
-**Access:** private
+**Access**: private
* [jy-transform:unit-test:test-options-schema](#module_jy-transform_unit-test_test-options-schema) ℗
* [~expectOptionsValidationError(invalidOptions, schema)](#module_jy-transform_unit-test_test-options-schema..expectOptionsValidationError) ℗
@@ -942,12 +859,12 @@ This unit test suite checks the validity and correctness of options schema.
### jy-transform:unit-test:test-options-schema~expectOptionsValidationError(invalidOptions, schema) ℗
Expect a `ValidationError` for a given options function.
-**Kind**: inner method of [jy-transform:unit-test:test-options-schema](#module_jy-transform_unit-test_test-options-schema)
-**Access:** private
+**Kind**: inner method of [jy-transform:unit-test:test-options-schema](#module_jy-transform_unit-test_test-options-schema)
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
-| invalidOptions | Options | The options which potentially produce the error. |
+| invalidOptions | [ReaderOptions](#ReaderOptions) \| [WriterOptions](#WriterOptions) | The options which potentially produce the error. |
| schema | Schema | The validation schema. |
@@ -955,12 +872,12 @@ Expect a `ValidationError` for a given options function.
### jy-transform:unit-test:test-options-schema~expectOptionsValidationSuccess(validOptions, schema) ℗
Expect a validation success for a given options.
-**Kind**: inner method of [jy-transform:unit-test:test-options-schema](#module_jy-transform_unit-test_test-options-schema)
-**Access:** private
+**Kind**: inner method of [jy-transform:unit-test:test-options-schema](#module_jy-transform_unit-test_test-options-schema)
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
-| validOptions | Options | The options which should be correct. |
+| validOptions | [ReaderOptions](#ReaderOptions) \| [WriterOptions](#WriterOptions) | The options which should be correct. |
| schema | Schema | The validation schema. |
@@ -970,11 +887,11 @@ Reads the data from a given JS or JSON source.
**Kind**: global variable
**Returns**: Promise.<Object> - Contains the read JS object.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#module_jy-transform_type-definitions..ReaderOptions) | Contains the JS/JSON source reference to read from. |
+| options | [ReaderOptions](#ReaderOptions) | Contains the JS/JSON source reference to read from. |
@@ -985,24 +902,27 @@ exception on those.
**Kind**: global variable
**Returns**: Promise.<Object> - Contains the read JS object.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#module_jy-transform_type-definitions..ReaderOptions) | Contains the YAML source reference to read from. |
+| options | [ReaderOptions](#ReaderOptions) | Contains the YAML source reference to read from. |
-## read ⇒ Promise.<string>
+## read ⇒ Promise
Reads a particular content type from a source provided in the passed `options`.
**Kind**: global variable
-**Returns**: Promise.<string> - Resolves with JS object result.
-**Access:** public
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string Resolves with JS object result.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error If any write error occurs.
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#module_jy-transform_type-definitions..ReaderOptions) | The read options. |
+| options | [ReaderOptions](#ReaderOptions) | The read options. |
**Example**
```js
@@ -1032,25 +952,25 @@ read(options)
```
-## transform ⇒ Promise.<String>
+## transform ⇒ Promise
The entry method for all transformation accepting a configuration object and
-an (optional) middleware function. It executes the transformation logic:
+an (optional) middleware function. It executes the transformation logic.
+
1. Input (read)
2. Transform [ + Middleware]
3. Output (write).
**Kind**: global variable
-**Returns**: Promise.<String> - Containing the transformation result as message (e.g. to be logged by caller).
-**Throws**:
-
-- TypeError Will throw this error when the passed `middleware` is not type of `Function`.
-- Error Will throw plain error when writing to _destination object_ failed due to any reason.
-
-**Access:** public
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
+**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
| Param | Type | Description |
| --- | --- | --- |
-| options | [TransformerOptions](#module_jy-transform_type-definitions..TransformerOptions) | The configuration for a transformation. |
+| options | [TransformerOptions](#TransformerOptions) | The configuration for a transformation. |
| [middleware] | function | This middleware Promise can be used to intercept the JSON object for altering the passed JSON, the function signature is: ``` async function(object) ```
**NOTE:** the Promise has to return the processed JS object. |
**Example**
@@ -1086,7 +1006,7 @@ Creates a potential named `'module.exports[.exportsTo]'` string.
**Kind**: global variable
**Returns**: Promise.<string> - Resolves with the exports string.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
@@ -1099,7 +1019,7 @@ Serialize a JS object to string.
**Kind**: global variable
**Returns**: Promise.<string> - - Promise resolve with the serialized JS content.
-**Access:** private
+**Access**: private
**Todo**
- [ ] [[#35](https://github.com/deadratfink/jy-transform/issues/35)] Add `'use strict';` in JS output file (->
@@ -1119,7 +1039,7 @@ Serialize a JS object to JSON string.
**Kind**: global variable
**Returns**: string - The serialized JSON.
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
@@ -1132,7 +1052,7 @@ Serialize a JS object to JSON string.
Ensures that all dirs exists for file type `dest` and writes the JS object to file.
**Kind**: global variable
-**Access:** private
+**Access**: private
| Param | Type | Description |
| --- | --- | --- |
@@ -1152,7 +1072,7 @@ Writes a JS object to a YAML destination.
- Error If YAML destination could not be written due to any reason.
-**Access:** private
+**Access**: private
**See**
- [MIN_INDENT](MIN_INDENT)
@@ -1163,7 +1083,7 @@ Writes a JS object to a YAML destination.
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS object to write into YAML destination. |
-| options | [WriterOptions](#module_jy-transform_type-definitions..WriterOptions) | The write destination and indention. |
+| options | [WriterOptions](#WriterOptions) | The write destination and indention. |
@@ -1172,7 +1092,7 @@ Writes a JS object to a JSON destination.
**Kind**: global variable
**Returns**: Promise.<string> - Containing the write success message to handle by caller (e.g. for logging).
-**Access:** private
+**Access**: private
**See**
- [MIN_INDENT](MIN_INDENT)
@@ -1183,7 +1103,7 @@ Writes a JS object to a JSON destination.
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS object to write into JSON destination. |
-| options | [WriterOptions](#module_jy-transform_type-definitions..WriterOptions) | The write destination and indention. |
+| options | [WriterOptions](#WriterOptions) | The write destination and indention. |
@@ -1192,7 +1112,7 @@ Writes a JS object to a JS destination. The object is prefixed by `module.export
**Kind**: global variable
**Returns**: Promise.<string> - - Containing the write success message to handle by caller (e.g. for logging).
-**Access:** private
+**Access**: private
**See**
- [MIN_INDENT](MIN_INDENT)
@@ -1203,21 +1123,24 @@ Writes a JS object to a JS destination. The object is prefixed by `module.export
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JSON to write into JS destination. |
-| options | [WriterOptions](#module_jy-transform_type-definitions..WriterOptions) | The write destination and indention. |
+| options | [WriterOptions](#WriterOptions) | The write destination and indention. |
-## write ⇒ Promise.<string>
+## write ⇒ Promise
Writes the passe JS object to a particular destination described by the passed `options`.
**Kind**: global variable
-**Returns**: Promise.<string> - Resolves with write success message.
-**Access:** public
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string With the write success message.
+**Reject**: Error If any write error occurs.
+**Reject**: ValidationError If any `options` validation occurs.
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS source object to write. |
-| options | [WriterOptions](#module_jy-transform_type-definitions..WriterOptions) | The write options. |
+| options | [WriterOptions](#WriterOptions) | The write options. |
**Example**
```js
@@ -1260,3 +1183,103 @@ write(obj, options)
.then(console.log)
.catch(console.error);
```
+
+
+## ReaderOptions : object
+The configuration properties provided to the `read` function.
+
+**Kind**: global typedef
+**Access**: public
+**Properties**
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- |
+| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
+| origin | string | "yaml" | The origin type. |
+| imports | string | | The exports name for reading from JS source files or objects only. |
+
+
+
+## WriterOptions : object
+The writer configuration properties provided to the `write` function.
+
+**Kind**: global typedef
+**Access**: public
+**Properties**
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- |
+| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
+| target | string | "js" | The target type. |
+| indent | number | 2 | The indention value for pretty-print of output. |
+| exports | string | | The exports name for usage in JS destination files only. |
+| force | string | false | Force overwriting of existing output files on write phase. |
+
+
+
+## TransformerOptions : object
+The configuration properties provided to the `transform` function.
+
+**Kind**: global typedef
+**Access**: public
+**Properties**
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- |
+| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
+| origin | string | "yaml" | The origin type. |
+| imports | string | | The exports name for reading from JS source files or objects only. |
+| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
+| target | string | "js" | The target type. |
+| indent | number | 2 | The indention value for pretty-print of output. |
+| exports | string | | The exports name for usage in JS destination files only. |
+| force | string | false | Force overwriting of existing output files on write phase. |
+
+
+
+## joi ℗
+Hapi.js Joi.
+
+**Kind**: global external
+**Access**: private
+**See**: [Hapi Joi](https://github.com/hapijs/joi)
+
+* [joi](#external_joi) ℗
+ * [.ValidationError](#external_joi.ValidationError)
+ * [.Schema](#external_joi.Schema) ℗
+ * [.Extension](#external_joi.Extension) ℗
+ * [.validate](#external_joi.validate) : function ℗
+
+
+
+### joi.ValidationError
+Joi validation error.
+
+**Kind**: static typedef of [joi](#external_joi)
+**Access**: public
+**See**: [Joi errors](hhttps://github.com/hapijs/joi/blob/v10.2.0/API.md#errors)
+
+
+### joi.Schema ℗
+The validation schema. Can be a [joi](#external_joi) type object or a plain object
+where every key is assigned a [joi](#external_joi) type object.
+
+**Kind**: static typedef of [joi](#external_joi)
+**Access**: private
+**See**: [Joi API](https://github.com/hapijs/joi/blob/v10.2.2/API.md#joi)
+
+
+### joi.Extension ℗
+Hapi.js Joi schema extension.
+
+**Kind**: static typedef of [joi](#external_joi)
+**Access**: private
+**See**: [Hapi Joi Extension](https://github.com/hapijs/joi/blob/v10.2.2/API.md#extendextension)
+
+
+### joi.validate : function ℗
+Joi `validate` method.
+
+**Kind**: static typedef of [joi](#external_joi)
+**Access**: private
+**See**: [Joi.validate](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index 3bfdcc4..65e5339 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -4,149 +4,107 @@
- [Modules](#modules)
- [Members](#members)
-- [jy-transform:reader](#jy-transformreader)
-- [jy-transform:transformer](#jy-transformtransformer)
-- [jy-transform:type-definitions](#jy-transformtype-definitions)
-- [jy-transform:writer](#jy-transformwriter)
-- [read ⇒ Promise.<string>](#read-%E2%87%92-codepromiseltstringgtcode)
-- [transform ⇒ Promise.<String>](#transform-%E2%87%92-codepromiseltstringgtcode)
-- [write ⇒ Promise.<string>](#write-%E2%87%92-codepromiseltstringgtcode)
+- [Typedefs](#typedefs)
+- [jy-transform:constants](#jy-transformconstants)
+- [read ⇒ Promise](#read-%E2%87%92-codepromisecode)
+- [transform ⇒ Promise](#transform-%E2%87%92-codepromisecode)
+- [write ⇒ Promise](#write-%E2%87%92-codepromisecode)
+- [ReaderOptions : object](#readeroptions--codeobjectcode)
+- [WriterOptions : object](#writeroptions--codeobjectcode)
+- [TransformerOptions : object](#transformeroptions--codeobjectcode)
## Modules
The configuration properties provided to the transform function.
+
+
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| src | string | Stream.Readable | object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
+
-
+## jy-transform:constants
+Useful constants used for the module and its usage.
-### jy-transform:type-definitions~WriterOptions : object
-The writer configuration properties provided to the writer function.
+**Access**: public
-**Kind**: inner typedef of [jy-transform:type-definitions](#module_jy-transform_type-definitions)
-**Access:** public
-**Properties**
+* [jy-transform:constants](#module_jy-transform_constants)
+ * [~TYPE_YAML](#module_jy-transform_constants..TYPE_YAML) : string
+ * [~TYPE_JSON](#module_jy-transform_constants..TYPE_JSON) : string
+ * [~TYPE_JS](#module_jy-transform_constants..TYPE_JS) : string
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| dest | string | Stream.Writable | object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| indent | number | 2 | The indention in files. |
-| exports | string | | The exports name for usage in JS destination files only. |
-| force | string | false | Force overwriting of existing output files on write phase. |
+
-
+### jy-transform:constants~TYPE_YAML : string
+The `'yaml'` type constant.
-### jy-transform:type-definitions~TransformerOptions : object
-The configuration properties provided to the transformer function.
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: public
+
-**Kind**: inner typedef of [jy-transform:type-definitions](#module_jy-transform_type-definitions)
-**Access:** public
-**Properties**
+### jy-transform:constants~TYPE_JSON : string
+The `'json'` type constant.
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| src | string | Stream.Readable | object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
-| dest | string | Stream.Writable | object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| exports | string | | The exports name for usage in JS destination files only. |
-| indent | number | 2 | The indention in files. |
-| force | string | false | Force overwriting of existing output files on write phase. |
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: public
+
-
+### jy-transform:constants~TYPE_JS : string
+The `'js'` type constant.
-## jy-transform:writer
-This module provides the _write_ functionality to write JS objects from memory to a JSON/JS/YAML
-destination (file, object or [stream.Readable](stream.Readable)).
-
-**Access:** public
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: public
-## read ⇒ Promise.<string>
+## read ⇒ Promise
Reads a particular content type from a source provided in the passed `options`.
**Kind**: global variable
-**Returns**: Promise.<string> - Resolves with JS object result.
-**Access:** public
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string Resolves with JS object result.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error If any write error occurs.
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#module_jy-transform_type-definitions..ReaderOptions) | The read options. |
+| options | [ReaderOptions](#ReaderOptions) | The read options. |
**Example**
```js
@@ -176,25 +134,25 @@ read(options)
```
-## transform ⇒ Promise.<String>
+## transform ⇒ Promise
The entry method for all transformation accepting a configuration object and
-an (optional) middleware function. It executes the transformation logic:
+an (optional) middleware function. It executes the transformation logic.
+
1. Input (read)
2. Transform [ + Middleware]
3. Output (write).
**Kind**: global variable
-**Returns**: Promise.<String> - Containing the transformation result as message (e.g. to be logged by caller).
-**Throws**:
-
-- TypeError Will throw this error when the passed `middleware` is not type of `Function`.
-- Error Will throw plain error when writing to _destination object_ failed due to any reason.
-
-**Access:** public
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
+**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
| Param | Type | Description |
| --- | --- | --- |
-| options | [TransformerOptions](#module_jy-transform_type-definitions..TransformerOptions) | The configuration for a transformation. |
+| options | [TransformerOptions](#TransformerOptions) | The configuration for a transformation. |
| [middleware] | function | This middleware Promise can be used to intercept the JSON object for altering the passed JSON, the function signature is: ``` async function(object) ```
**NOTE:** the Promise has to return the processed JS object. |
**Example**
@@ -225,17 +183,20 @@ try {
```
-## write ⇒ Promise.<string>
+## write ⇒ Promise
Writes the passe JS object to a particular destination described by the passed `options`.
**Kind**: global variable
-**Returns**: Promise.<string> - Resolves with write success message.
-**Access:** public
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string With the write success message.
+**Reject**: Error If any write error occurs.
+**Reject**: ValidationError If any `options` validation occurs.
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS source object to write. |
-| options | [WriterOptions](#module_jy-transform_type-definitions..WriterOptions) | The write options. |
+| options | [WriterOptions](#WriterOptions) | The write options. |
**Example**
```js
@@ -278,3 +239,55 @@ write(obj, options)
.then(console.log)
.catch(console.error);
```
+
+
+## ReaderOptions : object
+The configuration properties provided to the `read` function.
+
+**Kind**: global typedef
+**Access**: public
+**Properties**
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- |
+| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
+| origin | string | "yaml" | The origin type. |
+| imports | string | | The exports name for reading from JS source files or objects only. |
+
+
+
+## WriterOptions : object
+The writer configuration properties provided to the `write` function.
+
+**Kind**: global typedef
+**Access**: public
+**Properties**
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- |
+| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
+| target | string | "js" | The target type. |
+| indent | number | 2 | The indention value for pretty-print of output. |
+| exports | string | | The exports name for usage in JS destination files only. |
+| force | string | false | Force overwriting of existing output files on write phase. |
+
+
+
+## TransformerOptions : object
+The configuration properties provided to the `transform` function.
+
+**Kind**: global typedef
+**Access**: public
+**Properties**
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- |
+| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
+| origin | string | "yaml" | The origin type. |
+| imports | string | | The exports name for reading from JS source files or objects only. |
+| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
+| target | string | "js" | The target type. |
+| indent | number | 2 | The indention value for pretty-print of output. |
+| exports | string | | The exports name for usage in JS destination files only. |
+| force | string | false | Force overwriting of existing output files on write phase. |
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8d03d41..6397f7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,76 +3,102 @@
#### v3.0.0
- New Features:
- - The _middleware_ function must not need a Promise anymore, but is still recommended.
+ - The _middleware_ function must not need to be a Promise anymore, but it is still recommended.
+ - The `read` process returns a clone of the `options.src` when it is a JS object (so the origin
+ would never be changed).
+ - The minimum indent for YAML target types is validated for 2 now and throws a `ValidationError`
+ if < 2 (for others 0 is still valid).
+
+- Bugfix:
+ - If destination is not given on transformation process but the target is, then the destination file extension
+ is adapted to the proper type, e.g. `$ ./jyt inch.json -t yaml` results in a file _inch.yaml_ (formerly:
+ _inch.json_ with YAML content or _inch(1).json_ with YAML, the latter if `options.force` was `true`).
- **CLI & API Changes (Backwards Incompatible!):**
- - Removed support for Node.js < v4.0
- - Default `options.indent` is 2 (instead of 4) now which seems to be more common in the JS/Node.js community
+ - Removed support for Node.js < v4.0.
+ - Default `options.indent` is 2 (instead of 4) now which seems to be more common in the JS/Node.js community.
+ - An invalid indention setting (i.e. `indent` < 0 or `indent` > 8) raises a `ValidationError` now.
- **API Changes Only (Backwards Incompatible!):**
- - The exported constants `YAML`, `JS` and `JSON` (usable for `options.origin/target`) are renamed respectively to `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON`
- - Eased interface:
- - Prototype approach removed from `Transformer`, `Reader` and `Writer`, turning it to internal modules with exports of _named_ functions to provide a simplified interface
- - The formerly exported `Reader.readJs(...)/readYaml(...)` functions are not public anymore and replaced by a general `read(options)` function
- - The formerly exported `Writer.writeJs(...)/writeJson(...)/writeYaml(...)` functions are not public anymore and replaced by a general `write(object, options)` function
- - The formerly exported `middleware` is not publicly available anymore
- - Reduced and named export of constants: `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON` only
- - The `options.imports/exports` are not allowed to be empty strings anymore (semantically senseless, just leave it out)
- - The configuration property `options.dest` is required for `Transformer` and `Writer` when using the API
- - Removal of `LogWrapper` (no more logger injection possible/needed)
+ - The exported constants `YAML`, `JS` and `JSON` (usable for `options.origin/target`) are renamed respectively
+ to `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON`.
+ - Provide a simplified interface:
+ - Prototype approach removed from `Transformer`, `Reader` and `Writer`, turning it to internal modules with
+ exports of _named_ functions:
+ - The formerly exported `Reader.readJs(...)/readYaml(...)` functions are not public anymore and replaced
+ by a general `read(options)` function.
+ - The formerly exported `Writer.writeJs(...)/writeJson(...)/writeYaml(...)` functions are not public
+ anymore and replaced by a general `write(object, options)` function.
+ - The formerly exported `middleware` (identity function) is not publicly available anymore.
+ - Reduced and named export of constants: `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON` only.
+ - The `options.imports/exports` are not allowed to be empty strings anymore (semantically senseless,
+ just leave it out).
+ - The configuration property `options.dest` is required for `Writer` when using the API (but not from `Transformer`
+ if it can be inferred from `options.src` which is true for string or file stream sources).
+ - Removal of `LogWrapper` (no more logger injection possible).
- Internal Changes & Improvements:
- - Documentation restructured
- - Removal of _development_ branch
- - Usage of [babel](https://babeljs.io/) and therefore most modern language features
- - Code base could be shrinked and readabilty was improved
- - Usage of _native_ Promises instead of [bluebird](http://bluebirdjs.com/docs/getting-started.html)
- - Tests re-written in [Jest](https://facebook.github.io/jest) (could get rid of [assert](https://github.com/defunctzombie/commonjs-assert),
- [mocha](https://mochajs.org/) and [istanbul](https://github.com/gotwarlost/istanbul))
- - Add travis build for Node.js v8.x
- - Remove travis build for Node.js < v4.x
- - Removal of `OptionsHandler` and `Validator` (replaced the validation by using [joi](https://github.com/hapijs/joi/tree/v10.5.0) now)
+ - Documentation restructured.
+ - Removal of _development_ branch.
+ - Usage of [babel](https://babeljs.io/) and therefore most modern language features.
+ - Update of dependencies and amount reduced.
+ - Code base could be shrinked and readabilty was improved.
+ - Usage of _native_ Promises instead of [bluebird](http://bluebirdjs.com/docs/getting-started.html).
+ - Tests re-written in [Jest](https://facebook.github.io/jest) (could get rid of
+ [assert](https://github.com/defunctzombie/commonjs-assert),
+ [mocha](https://mochajs.org/) and [istanbul](https://github.com/gotwarlost/istanbul)).
+ - Add travis build for Node.js v8.x.
+ - Remove travis build for Node.js < v4.x.
+ - Removal of `OptionsHandler` and `Validator` (replaced the validation by using
+ [joi](https://github.com/hapijs/joi/tree/v10.5.0) now).
#### v2.0.1
-- [[#39](https://github.com/deadratfink/jy-transform/issues/39)] Maintenance release
- - Update dependencies to latest
- - Add travis build for Node.js v7.x and v6.x
- - Docs improved/corrected
- - Add target pretest in `scripts` section to `rm` _./test/tmp_ folder
+- [[#39](https://github.com/deadratfink/jy-transform/issues/39)] Maintenance release.
+ - Update dependencies to latest.
+ - Add travis build for Node.js v7.x and v6.x.
+ - Docs improved/corrected.
+ - Add target pretest in `scripts` section to `rm` _./test/tmp_ folder.
#### v2.0.0
-- [[#33](https://github.com/deadratfink/jy-transform/issues/33)] Enhance `LogWrapper` with `TRACE` level (API)
-- [[#32](https://github.com/deadratfink/jy-transform/issues/32)] Introduce input and output on CLI as ARGS instead of OPTIONS (non-backwards compatible change for CLI usage, _no_ impact on API level!)
- - e.g. on CLI type in `$ jyt.js foo.js bar.yaml` instead of `$ jyt.js -s foo.js -d bar.yaml`
-- [[#31](https://github.com/deadratfink/jy-transform/issues/31)] Bugfix: given `Object` source results in 'yaml' for origin (API)
-- [Cleanup] Update dependencies
+- [[#33](https://github.com/deadratfink/jy-transform/issues/33)] Enhance `LogWrapper` with `TRACE` level (API).
+- [[#32](https://github.com/deadratfink/jy-transform/issues/32)] Introduce input and output on CLI as
+ ARGS instead of OPTIONS
+ (non-backwards compatible change for CLI usage, _no_ impact on API level!), e.g. on CLI type in
+ `$ jyt.js foo.js bar.yaml` instead of `$ jyt.js -s foo.js -d bar.yaml`.
+- [[#31](https://github.com/deadratfink/jy-transform/issues/31)] Bugfix: given `Object` source results in
+ 'yaml' for origin (API).
+- [Cleanup] Update dependencies.
#### v1.0.2
-- [[#30](https://github.com/deadratfink/jy-transform/issues/30)] Fix README and externalize API reference to wiki
-- [[#29](https://github.com/deadratfink/jy-transform/issues/29)] Fix Promise warning on write process
+- [[#30](https://github.com/deadratfink/jy-transform/issues/30)] Fix README and externalize API reference to wiki.
+- [[#29](https://github.com/deadratfink/jy-transform/issues/29)] Fix Promise warning on write process.
#### v1.0.1
-Initial public release. This covers the basic implementation and tests. The following features and fixes and part of this release:
-
-- [[#27](https://github.com/deadratfink/jy-transform/issues/27)] Export variable for JS input
-- [[#22](https://github.com/deadratfink/jy-transform/issues/22)] Integrate Coveralls
-- [[#21](https://github.com/deadratfink/jy-transform/issues/21)] Check and fix CodeClimate issues
-- [[#20](https://github.com/deadratfink/jy-transform/issues/20)] Cleanup test dir
-- [[#19](https://github.com/deadratfink/jy-transform/issues/19)] File overwrite switch (`-f`, `-force`)
-- [[#18](https://github.com/deadratfink/jy-transform/issues/18)] Read and Write from other sources than file path
-- [[#16](https://github.com/deadratfink/jy-transform/issues/16)] ERROR: Error: Invalid target option found while creating destination file extension
-- [[#15](https://github.com/deadratfink/jy-transform/issues/15)] Measure test code coverage and add a badge
-- [[#12](https://github.com/deadratfink/jy-transform/issues/12)] Create middleware collection file to use by clients and internally
-- [[#11](https://github.com/deadratfink/jy-transform/issues/11)] Check all Promises for optimization possibilities
-- [[#10](https://github.com/deadratfink/jy-transform/issues/10)] Integrate project with Travis
-- [[#9](https://github.com/deadratfink/jy-transform/issues/9)] Resolve origin and target from file extension whenever possible
-- [[#8](https://github.com/deadratfink/jy-transform/issues/8)] Enable JS reading with `require(...)`
-- [[#7](https://github.com/deadratfink/jy-transform/issues/7)] YAML indent is not set to `Constants.MIN_YAML_INDENT` when indent is set to 0
-- [[#6](https://github.com/deadratfink/jy-transform/issues/6)] Finish full JSDoc for all methods
-- [[#5](https://github.com/deadratfink/jy-transform/issues/5)] Write unit tests
-- [[#4](https://github.com/deadratfink/jy-transform/issues/4)] Export variable for JS output
-- [[#3](https://github.com/deadratfink/jy-transform/issues/3)] Promise array as middleware solved with `Promise.all([...])`
+Initial public release. This covers the basic implementation and tests. The following features and fixes and
+part of this release:
+- [[#27](https://github.com/deadratfink/jy-transform/issues/27)] Export variable for JS input.
+- [[#22](https://github.com/deadratfink/jy-transform/issues/22)] Integrate Coveralls.
+- [[#21](https://github.com/deadratfink/jy-transform/issues/21)] Check and fix CodeClimate issues.
+- [[#20](https://github.com/deadratfink/jy-transform/issues/20)] Cleanup test dir.
+- [[#19](https://github.com/deadratfink/jy-transform/issues/19)] File overwrite switch (`-f`, `-force`).
+- [[#18](https://github.com/deadratfink/jy-transform/issues/18)] Read and Write from other sources than file path.
+- [[#16](https://github.com/deadratfink/jy-transform/issues/16)] ERROR: Error: Invalid target option found while
+ creating destination file extension.
+- [[#15](https://github.com/deadratfink/jy-transform/issues/15)] Measure test code coverage and add a badge.
+- [[#12](https://github.com/deadratfink/jy-transform/issues/12)] Create middleware collection file to use by
+ clients and internally.
+- [[#11](https://github.com/deadratfink/jy-transform/issues/11)] Check all Promises for optimization possibilities.
+- [[#10](https://github.com/deadratfink/jy-transform/issues/10)] Integrate project with Travis.
+- [[#9](https://github.com/deadratfink/jy-transform/issues/9)] Resolve origin and target from file extension
+ whenever possible.
+- [[#8](https://github.com/deadratfink/jy-transform/issues/8)] Enable JS reading with `require(...)`.
+- [[#7](https://github.com/deadratfink/jy-transform/issues/7)] YAML indent is not set to `Constants.MIN_YAML_INDENT`
+ when indent is set to 0.
+- [[#6](https://github.com/deadratfink/jy-transform/issues/6)] Finish full JSDoc for all methods.
+- [[#5](https://github.com/deadratfink/jy-transform/issues/5)] Write unit tests.
+- [[#4](https://github.com/deadratfink/jy-transform/issues/4)] Export variable for JS output.
+- [[#3](https://github.com/deadratfink/jy-transform/issues/3)] Promise array as middleware solved with `Promise.all([...])`.
diff --git a/PACKAGE.md b/PACKAGE.md
index 7c1134f..e5098b3 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -4,8 +4,6 @@ This project aims to read, write and transform YAML, JS or JSON objects into eac
## Installation
-Download node at [nodejs.org](http://nodejs.org) and install it, if you haven't already.
-
```sh
npm install jy-transform --global
```
@@ -20,9 +18,8 @@ npm test
## Dependencies
-- [bluebird](https://github.com/petkaantonov/bluebird): Full featured Promises/A+ implementation with exceptionally good performance
+- [babel-cli](https://github.com/babel/babel/tree/master/packages): Babel command line.
- [cli](https://github.com/node-js-libs/cli): A tool for rapidly building command line apps
-- [cwd](https://github.com/jonschlinkert/cwd): Easily get the CWD (current working directory) of a project based on package.json, optionally starting from a given path. (node.js/javascript util)
- [is-stream](https://github.com/sindresorhus/is-stream): Check if something is a Node.js stream
- [joi](https://github.com/hapijs/joi): Object schema validation
- [js-yaml](https://github.com/nodeca/js-yaml): YAML 1.2 parser and serializer
@@ -33,17 +30,12 @@ npm test
## Dev Dependencies
-- [babel-cli](https://github.com/babel/babel/tree/master/packages): Babel command line.
-- [babel-core](https://github.com/babel/babel/tree/master/packages): Babel compiler core.
- [babel-eslint](https://github.com/babel/babel-eslint): Custom parser for ESLint
-- [babel-plugin-transform-builtin-extend](https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend): A plugin for Babel 6 supports extending from builtin types based on static analysis.
+- [babel-plugin-transform-flow-strip-types](https://github.com/babel/babel/tree/master/packages): Strip flow type annotations from your output code.
- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
-- [babel-preset-stage-0](https://github.com/babel/babel/tree/master/packages): Babel preset for stage 0 plugins
-- [babel-watch](https://github.com/kmagiera/babel-watch): Reload your babel-node app on JS source file changes. And do it *fast*.
-- [chalk](https://github.com/chalk/chalk): Terminal string styling done right. Much color.
+- [chalk](https://github.com/chalk/chalk): Terminal string styling done right. Much color
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
- [codecov](https://github.com/codecov/codecov-node): Uploading report to Codecov: https://codecov.io
-- [combarnea-winston-console-formatter](https://github.com/combarnea/winston-console-formatter): Pretty print console formatter in yaml like style
- [coveralls](https://github.com/nickmerwin/node-coveralls): takes json-cov output into stdin and POSTs to coveralls.io
- [doctoc](https://github.com/thlorenz/doctoc): Generates TOC for markdown files of local git repo.
- [eslint](https://github.com/eslint/eslint): An AST-based pattern checker for JavaScript.
@@ -54,14 +46,10 @@ npm test
- [eslint-plugin-jest-async](https://github.com/deadratfink/jy-transform.git): ESLint plugin to detect improper Jest test assertions for asynchronous (Promise-based) actions
- [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc): JSDoc linting rules for ESLint.
- [fs-extra](https://github.com/jprichardson/node-fs-extra): fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as mkdir -p, cp -r, and rm -rf.
-- [istanbul](https://github.com/gotwarlost/istanbul): Yet another JS code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. Supports all JS coverage use cases including unit tests, server side functional tests
- [jest](https://github.com/facebook/jest): Delightful JavaScript Testing.
- [jsdoc-babel](https://github.com/ctumolosus/jsdoc-babel): A JSDoc plugin that transforms ES6 source files with Babel before they are processsed.
- [jsdoc-parse](https://github.com/jsdoc2md/jsdoc-parse): Transforms jsdoc data into something more suitable for use as template input
- [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown): Generates markdown API documentation from jsdoc annotated source code
-- [mocha](https://github.com/mochajs/mocha): simple, flexible, fun test framework
-- [mocha-lcov-reporter](https://github.com/StevenLooman/mocha-lcov-reporter): LCOV reporter for Mocha
-- [object-path](https://github.com/mariocasciaro/object-path): Access deep object properties using a path
- [package-json-to-readme](https://github.com/zeke/package-json-to-readme): Generate a README.md from package.json contents
- [winston](https://github.com/winstonjs/winston): A multi-transport async logging library for Node.js
- [winston-console-formatter](https://github.com/eugeny-dementev/winston-console-formatter): Pretty print console formatter in yaml like style
@@ -70,4 +58,3 @@ npm test
## License
SEE LICENSE IN [LICENSE.md](https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md)
-
diff --git a/README.md b/README.md
index 6d79cfd..91fcb94 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,61 @@
+[![License][gh-license-image]][gh-license-url] [![Issue Stats][gh-issues-image]][gh-issues-url] [![Releases][gh-releases-image]][gh-releases-url] [![Tags][gh-tags-image]][gh-tags-url] [![Build Status][ci-image]][ci-url] [![Waffle][waffle-image]][waffle-url] [![Code Climate][cocl-image]][cocl-url]
+[![codecov.io][cc-image-master]][cc-url-master] [![coveralls.io][ca-image-master]][ca-url-master] [![inch-ci.org][inch-image-master]][inch-url-master] [![Dependency Status][dep-image-master]][dep-url-master] [![devDependency Status][devdep-image-master]][devdep-url-master]
+
+[![NPM](https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/jy-transform/)
+
+[![NPM](https://nodei.co/npm-dl/jy-transform.png?height=3&months=9)](https://nodei.co/npm-dl/jy-transform/)
+
+[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat-square
+[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
+
+[gh-issues-image]: https://img.shields.io/github/issues/deadratfink/jy-transform.svg?style=flat-square
+[gh-issues-url]: https://github.com/deadratfink/jy-transform/issues
+
+[gh-releases-image]: https://img.shields.io/github/release/deadratfink/jy-transform.svg?style=flat-square
+[gh-releases-url]: https://github.com/deadratfink/jy-transform/releases
+
+[gh-tags-image]: https://img.shields.io/github/tag/deadratfink/jy-transform.svg?style=flat-square
+[gh-tags-url]: https://github.com/deadratfink/jy-transform/tags
+
+
+[ci-image]: https://img.shields.io/travis/deadratfink/jy-transform.svg?style=flat-square
+[ci-url]: https://travis-ci.org/deadratfink/jy-transform/branches
+
+[is-pull-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/pr?style=flat-square
+[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat-square
+[is-url]: http://issuestats.com/github/deadratfink/jy-transform
+
+[waffle-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
+[waffle-url]: https://waffle.io/deadratfink/jy-transform
+
+[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat-square
+[cocl-url]: https://codeclimate.com/github/deadratfink/jy-transform
+
+
+[cc-image-master]: https://img.shields.io/codecov/c/github/deadratfink/jy-transform/master.svg?style=flat-square
+[cc-url-master]: https://codecov.io/github/deadratfink/jy-transform?branch=master
+
+[ca-image-master]: https://img.shields.io/coveralls/deadratfink/jy-transform/master.svg?style=flat-square
+[ca-url-master]: https://coveralls.io/github/deadratfink/jy-transform?branch=master
+
+
+[inch-image-master]: https://inch-ci.org/github/deadratfink/jy-transform.svg?branch=master&style=flat-square
+[inch-url-master]: https://inch-ci.org/github/deadratfink/jy-transform?branch=master
+
+[dep-image-master]: https://img.shields.io/david/deadratfink/jy-transform/master.svg?style=flat-square
+[dep-url-master]: https://david-dm.org/deadratfink/jy-transform/master
+
+[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat-square
+[devdep-url-master]: https://david-dm.org/deadratfink/jy-transform/master#info=devDependencies
+
+
+
# jy-transform
This project aims to read, write and transform YAML, JS or JSON objects into each other using CLI or API, while the source and destination resources can be files on CLI and additionally, objects or streams on API level.
## Installation
-Download node at [nodejs.org](http://nodejs.org) and install it, if you haven't already.
-
```sh
npm install jy-transform --global
```
@@ -17,6 +67,9 @@ npm install jy-transform --global
## TOC
- [API in a Minute](#api-in-a-minute)
+ - [Read, Transform & Write from Source to Destination](#read-transform--write-from-source-to-destination)
+ - [Read into JS object from particular Source (File, Stream or JS Object) only](#read-into-js-object-from-particular-source-file-stream-or-js-object-only)
+ - [Write JS object to particular Destination only](#write-js-object-to-particular-destination-only)
- [Why This Module?](#why-this-module)
- [Usage](#usage)
- [Usage Types](#usage-types)
@@ -33,11 +86,10 @@ npm install jy-transform --global
## API in a Minute
-```javascript
-import { transform, read, write } from 'jy-transform';
-
+### Read, Transform & Write from Source to Destination
-// --- transform from source to destination ---
+```javascript
+import { transform } from 'jy-transform';
const transformOptions = {
src: 'foo/bar.yaml',
@@ -57,9 +109,12 @@ try {
} catch (err) {
console.error(err.stack);
}
+```
+### Read into JS object from particular Source (File, Stream or JS Object) only
-// --- read into JS object from particular source (file, stream or JS object) ---
+```javascript
+import { read } from 'jy-transform';
let object;
@@ -69,9 +124,12 @@ try {
} catch (err) {
console.error(err.stack);
}
+```
+### Write JS object to particular Destination only
-// --- write a JS object to particular destination ---
+```javascript
+import { write } from 'jy-transform';
try {
const msg = await write(object, { dest: 'foo/bar.yaml' });
@@ -110,13 +168,10 @@ So, what are the typical use cases for this module? In terms of _transformation_
these consists of different phases:
- Reading files (`Reader`)
-- Transforming JSON objects (`Transformer`)
-- Apply dedicated actions on the intermediate JSON objects (`Transformer` + `Middleware`)
+- Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects (`Transformer` + `Middleware`)
- Writing files (`Writer`)
-#### Reading
-
-From:
+#### Reading From
- _*.yaml_ file
- _*.js_ file
@@ -156,9 +211,7 @@ while:
As mentioned above a _middleware_ can apply particular actions on the intermediate JS object via injected functions.
This is an optional part for [transformation](#transformation) phase.
-#### Writing
-
-To:
+#### Writing To
- _*.yaml_ file
- _*.js_ file
@@ -489,7 +542,7 @@ async function transform(options, middleware)
#### Options
-The `options` object has to follow this key-values table:
+The `options` object has to follow this key-values tables:
##### Reader Options
@@ -509,8 +562,6 @@ The `options` object has to follow this key-values table:
| `imports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (to read from JS _source_ only, must be a valid JS identifier!) | _undefined_ | no |
| `exports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (for usage in JS _destination_ only, must be a valid JS identifier!) | _undefined_ | no |
-**NOTE:** an invalid indention setting (1 > indent > 8) does not raise an error but a default of 2 SPACEs is applied instead.
-
##### Transformer Options
These are a combination of the [Reader](#reader-options) and [Writer](#writer-options) Options.
@@ -658,8 +709,7 @@ wiki which describes the full API and provides more examples.
## Contributing
-Pull requests and stars are always welcome. Anybody is invited to take part
-into this project. For bugs and feature requests, please create an
+Pull requests and stars are always welcome. For bugs and feature requests, please create an
[issue](https://github.com/deadratfink/jy-transform/issues).
See the wiki [Contributing](https://github.com/deadratfink/jy-transform/wiki/Contributing)
section for more details about conventions.
diff --git a/bin/create-readme.sh b/bin/create-readme.sh
index c01422b..19e7f65 100755
--- a/bin/create-readme.sh
+++ b/bin/create-readme.sh
@@ -1,7 +1,6 @@
#!/bin/bash
api="true"
-package="true"
changelog="true"
license="true"
makefile="true"
@@ -14,10 +13,6 @@ while [[ $# -gt 1 ]]; do
api="$2"
shift # past argument
;;
- -p|--package)
- package="$2"
- shift # past argument
- ;;
-c|--changelog)
changelog="$2"
shift # past argument
@@ -42,37 +37,31 @@ done
# PACKAGE.md
###############################################################################
-if [ "$package" == "true" ]; then
- printf "Create documentation (PACKAGE.md)\n"
- touch PACKAGE.md
- node node_modules/.bin/package-json-to-readme --no-footer package.json > PACKAGE.md
- cat readme/LOGO.md >> README.md
- cat readme/BADGES.md >> README.md
- printf "\n\n" >> README.md
- head -12 PACKAGE.md > README.md
- printf "\n\n" >> README.md
-else
- # to ensure that the README.md is always empty at the beginning
- printf "" > README.md
-fi
+printf "Create documentation (PACKAGE.md)\n"
+touch PACKAGE.md
+node node_modules/.bin/package-json-to-readme --no-footer package.json > PACKAGE.md
###############################################################################
# README.md
###############################################################################
+touch README.md
+# cat readme/LOGO.md >> README.md
+cat readme/BADGES.md > README.md
+printf "\n\n" >> README.md
+head -10 PACKAGE.md >> README.md
+printf "\n\n" >> README.md
+
printf "\n\n\n" >> README.md
cat readme/DOCUMENTATION.md >> README.md
printf "\n\n" >> README.md
-if [[ "$package" == "true" ]] || [[ "$api" == "true" ]] || [[ "$env" == "true" ]] || ([[ -f "$MAKE_FILE" ]] && [[ "$makefile" == "true" ]]); then
- printf "## Further information" >> README.md
- printf "\n\n" >> README.md
-fi
+printf "## Further information" >> README.md
+printf "\n\n" >> README.md
+
+printf -- "- [Module Details](./PACKAGE.md)" >> README.md
+printf "\n\n" >> README.md
-if [ "$package" == "true" ]; then
- printf -- "- [Module Details](./PACKAGE.md)" >> README.md
- printf "\n\n" >> README.md
-fi
###############################################################################
# API-PUBLIC.md
@@ -82,8 +71,8 @@ if [ "$api" == "true" ]; then
printf "Create documentation (API-PUBLIC.md)\n"
touch API-PUBLIC.md
printf "\n\n\n" >> API-PUBLIC.md
- node node_modules/.bin/jsdoc2md --no-cache --configure .jsdoc.json . > API-PUBLIC.md
- node node_modules/.bin/doctoc API-PUBLIC.md --github --title "## TOC" --maxlevel 2
+ node node_modules/.bin/jsdoc2md package.json index.js --no-cache --configure .jsdoc-public.json . > API-PUBLIC.md
+ node node_modules/.bin/doctoc API-PUBLIC.md --github --title "## TOC" --maxlevel 2
printf -- "- [Public Api Reference](./API-PUBLIC.md)" >> README.md
printf "\n\n" >> README.md
@@ -98,7 +87,7 @@ if [ "$api" == "true" ]; then
touch API-PRIVATE.md
printf "\n\n\n" >> API-PRIVATE.md
node node_modules/.bin/jsdoc2md --no-cache --private --configure .jsdoc.json . > API-PRIVATE.md
- node node_modules/.bin/doctoc API-PRIVATE.md --github --title "## TOC" --maxlevel 2
+ node node_modules/.bin/doctoc API-PRIVATE.md --github --title "## TOC" --maxlevel 2
printf -- "- [Private Api Reference](./API-PRIVATE.md)" >> README.md
printf "\n\n" >> README.md
diff --git a/codecov.yml b/codecov.yml
index ce34c4b..19eb643 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -67,10 +67,9 @@ coverage:
# option: "X%" a static target percentage to hit
branches:
- master
- - development
- - bugfix/#*
- - feature/#*
- - hotfix/*
+ - bugfix/*
+ - feature/*
+ - refactor/*
#threshold: null # allowed to drop X% and still result in a "success" commit status
if_no_uploads: error # will post commit status of "error" if no coverage reports we uploaded
# options: success, error, failure
@@ -98,10 +97,9 @@ coverage:
enabled: yes # must be yes|true to enable this status
branches:
- master
- - development
- - bugfix/#*
- - feature/#*
- - hotfix/*
+ - bugfix/*
+ - feature/*
+ - refactor/*
if_no_uploads: error
if_not_found: success
if_ci_failed: error
@@ -117,10 +115,9 @@ comment:
layout: "header, diff, changes, sunburst, suggestions"
branches:
- master
- - development
- - bugfix/#*
- - feature/#*
- - hotfix/*
+ - bugfix/*
+ - feature/*
+ - refactor/*
behavior: default # option: "default" posts once then update, posts new if delete
# option: "once" post once then updates, if deleted do not post new
# option: "new" delete old, post new
diff --git a/jyt b/jyt
index 0fa0360..e15fef3 100755
--- a/jyt
+++ b/jyt
@@ -1,4 +1,3 @@
-#!./node_modules/.bin/babel-node
+#!/usr/bin/env node
-// eslint-disable-next-line no-unused-vars
-import jyt from './src/cli';
+require('./lib/cli');
diff --git a/package.json b/package.json
index c1f9206..ca98689 100644
--- a/package.json
+++ b/package.json
@@ -20,66 +20,57 @@
"bugs": "https://github.com/deadratfink/jy-transform/issues",
"private": false,
"scripts": {
- "build": "babel src -d lib",
+ "build": "NODE_ENV=production babel src --out-dir lib --copy-files --source-maps",
"doc": "cat docs/LOGO.md > README.md && cat docs/BADGES.md >> README.md && cat docs/TOC.md >> README.md && package-json-to-readme --no-footer ./package.json >> README.md && cat docs/USAGE.md >> README.md && echo '\n# Changelog\n' >> README.md && cat docs/CHANGELOG.md >> README.md && doctoc README.md --github --title '# TOC' --maxlevel 2",
"readme": "bin/create-readme.sh -a true -c false -m true -l false",
"wiki": "jsdoc2md ./jyt lib/*.js index.js > docs/API.md && doctoc docs/API.md --github --title '### TOC' --maxlevel 2 && cat docs/API.md > '../jy-transform.wiki/API-v2.md' && cat docs/CONTRIBUTING.md > ../jy-transform.wiki/Contributing.md && cat docs/CHANGELOG.md > ../jy-transform.wiki/Changelog.md && doctoc ../jy-transform.wiki/Changelog.md --github --title '### TOC' --maxlevel 3",
"pretest": "mkdir -pv test/tmp",
- "test": "JYT_DEBUG=true JYT_ERROR=true jest --expand --no-cache --coverage --config=./.jestrc.js",
+ "test": "JYT_DEBUG=false JYT_ERROR=false jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
"eslint": "eslint ."
},
"engines": {
"node": ">=4.0.0"
},
"dependencies": {
- "bluebird": "^3.4.6",
- "cli": "^1.0.1",
- "cwd": "~0.10.0",
- "is-stream": "^1.1.0",
- "joi": "~10.5.0",
- "js-yaml": "^3.6.1",
- "json-stringify-safe": "^5.0.1",
- "mkdirp-then": "^1.2.0",
+ "babel-cli": "~6.24.1",
+ "cli": " ~1.0.1",
+ "is-stream": " ~1.1.0",
+ "joi": "~10.6.0",
+ "js-yaml": " ~3.8.4",
+ "json-stringify-safe": " ~5.0.1",
+ "mkdirp-then": " ~1.2.0",
"promisify-es6": "~1.0.2",
- "serialize-js": "^1.1.0"
+ "serialize-js": " ~1.1.0"
},
"devDependencies": {
- "babel-cli": "~6.24.1",
- "babel-core": "~6.24.1",
- "babel-eslint": "~7.2.3",
- "babel-plugin-transform-builtin-extend": "~1.1.2",
- "babel-preset-env": "~1.4.0",
- "babel-preset-stage-0": "~6.24.1",
- "babel-watch": "~2.0.6",
- "chalk": "~1.1.3",
- "codeclimate-test-reporter": "^0.4.0",
- "codecov": "^1.0.1",
- "combarnea-winston-console-formatter": "~1.0.1",
- "coveralls": "^2.11.14",
- "doctoc": "^1.0.0",
- "eslint": "~3.19.0",
- "eslint-config-airbnb-base": "~10.0.1",
- "eslint-plugin-filenames": "~1.2.0",
- "eslint-plugin-import": "~2.2.0",
- "eslint-plugin-jest": "~20.0.3",
- "eslint-plugin-jest-async": "~1.0.3",
- "eslint-plugin-jsdoc": "~2.3.1",
- "fs-extra": "^1.0.0",
- "istanbul": "^0.4.5",
+ "babel-eslint": " ~7.2.3",
+ "babel-plugin-transform-flow-strip-types": "~6.22.0",
+ "babel-preset-env": "~1.5.2",
+ "chalk": "~2.0.1",
+ "codeclimate-test-reporter": " ~0.5.0",
+ "codecov": " ~2.2.0",
+ "coveralls": " ~2.13.1",
+ "cwd": "~0.10.0",
+ "doctoc": " ~1.3.0",
+ "eslint": "~4.1.0",
+ "eslint-config-airbnb-base": "~11.2.0",
+ "eslint-plugin-filenames": "1.2.0",
+ "eslint-plugin-import": " ~2.6.1",
+ "eslint-plugin-jest": " ~20.0.3",
+ "eslint-plugin-jest-async": " ~1.0.3",
+ "eslint-plugin-jsdoc": " ~3.1.1",
+ "fs-extra": " ~3.0.1",
"jest": "~20.0.4",
- "jsdoc-babel": "^0.3.0",
- "jsdoc-parse": "^2.0.5",
- "jsdoc-to-markdown": "^2.0.1",
- "mocha": "^3.1.2",
- "mocha-lcov-reporter": "^1.2.0",
- "object-path": "^0.11.2",
- "package-json-to-readme": "^1.5.1",
- "winston": "^2.3.0",
+ "jsdoc-babel": " ~0.3.0",
+ "jsdoc-parse": " ~3.0.0",
+ "jsdoc-to-markdown": " ~3.0.0",
+ "package-json-to-readme": " ~2.0.0",
+ "winston": " ~2.3.0",
"winston-console-formatter": "~0.3.1"
},
"preferGlobal": true,
"bin": {
- "jyt": "./jyt"
+ "jyt": "./src/cli.js"
},
"main": "./index.js",
"keywords": [
diff --git a/readme/API.md b/readme/API.md
deleted file mode 100644
index fa33aca..0000000
--- a/readme/API.md
+++ /dev/null
@@ -1,1371 +0,0 @@
-
-
-### TOC
-
-- [Classes](#classes)
-- [Typedefs](#typedefs)
-- [Constants](#constants)
-- [LogWrapper](#logwrapper)
-- [Middleware](#middleware)
-- [OptionsHandler](#optionshandler)
-- [Reader](#reader)
-- [Transformer](#transformer)
-- [Validator](#validator)
-- [Writer](#writer)
-- [Options : object](#options--codeobjectcode)
-
-
-
-## Classes
-
-
The configuration properties provided to the transform function.
@@ -205,7 +195,7 @@ The command line interface.
* [jy-transform:jyt](#module_jy-transform_jyt) ℗
* [~usage](#module_jy-transform_jyt..usage) : string ℗
* [~packagePath](#module_jy-transform_jyt..packagePath) : string ℗
- * [~options](#module_jy-transform_jyt..options) : Object ℗
+ * [~cliOptionsSchema](#module_jy-transform_jyt..cliOptionsSchema) : Object ℗
* [~error(err)](#module_jy-transform_jyt..error) ℗
* [~main(args, cliOptions)](#module_jy-transform_jyt..main) ℗
@@ -223,9 +213,9 @@ The path to package.json.
**Kind**: inner constant of [jy-transform:jyt](#module_jy-transform_jyt)
**Access**: private
-
+
-### jy-transform:jyt~options : Object ℗
+### jy-transform:jyt~cliOptionsSchema : Object ℗
The options description for parsing the command line input, must be an object with opts defined like:
```
long_tag: [short_tag, description, value_type, default_value];
@@ -258,7 +248,7 @@ prints the result to the CLI.
| Param | Type | Description |
| --- | --- | --- |
| args | Array | The first mandatory argument is the input file (`args[0]`), the second (optional) argument is the output file (`args[1]`). |
-| cliOptions | module:jy-transform:type-definitions~TransformerOptions | The options provided via CLI. |
+| cliOptions | module:jy-transform:type-definitions~TransformOptions | The options provided via CLI. |
@@ -268,14 +258,14 @@ Useful constants used for the module and its usage.
**Access**: public
* [jy-transform:constants](#module_jy-transform_constants)
- * [~DEFAULT_OPTIONS](#module_jy-transform_constants..DEFAULT_OPTIONS) : object ℗
* [~UTF8](#module_jy-transform_constants..UTF8) : string ℗
* [~TYPE_YAML](#module_jy-transform_constants..TYPE_YAML) : string
* [~TYPE_JSON](#module_jy-transform_constants..TYPE_JSON) : string
* [~TYPE_JS](#module_jy-transform_constants..TYPE_JS) : string
- * [~TYPE_MAP](#module_jy-transform_constants..TYPE_MAP) : Object ℗
+ * [~EXT_TO_TYPE_MAP](#module_jy-transform_constants..EXT_TO_TYPE_MAP) : Object ℗
* [~DEFAULT_INDENT](#module_jy-transform_constants..DEFAULT_INDENT) : number ℗
* [~MIN_INDENT](#module_jy-transform_constants..MIN_INDENT) : number ℗
+ * [~MIN_YAML_INDENT](#module_jy-transform_constants..MIN_YAML_INDENT) : number ℗
* [~MAX_INDENT](#module_jy-transform_constants..MAX_INDENT) : number ℗
* [~DEFAULT_ORIGIN](#module_jy-transform_constants..DEFAULT_ORIGIN) : string ℗
* [~DEFAULT_TARGET](#module_jy-transform_constants..DEFAULT_TARGET) : string ℗
@@ -286,31 +276,6 @@ Useful constants used for the module and its usage.
* [~DEFAULT_JS_IMPORTS_IDENTIFIER](#module_jy-transform_constants..DEFAULT_JS_IMPORTS_IDENTIFIER) : string ℗
* [~DEFAULT_JS_EXPORTS_IDENTIFIER](#module_jy-transform_constants..DEFAULT_JS_EXPORTS_IDENTIFIER) : string ℗
-
-
-### jy-transform:constants~DEFAULT_OPTIONS : object ℗
-The default options.
-
-**Kind**: inner namespace of [jy-transform:constants](#module_jy-transform_constants)
-**Access**: private
-**See**
-
-- [ORIGIN_DESCRIPTION](ORIGIN_DESCRIPTION)
-- [TARGET_DESCRIPTION](TARGET_DESCRIPTION)
-- [DEST_DESCRIPTION](DEST_DESCRIPTION)
-
-**Properties**
-
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| origin | string | "yaml" | The default origin type. |
-| target | string | "js" | The default target type. |
-| dest | string | "relative_to_input_file" | The default dest description. |
-| indent | number | 4 | The default indention for files. |
-| force | boolean | false | Whether to overwrite existing file on output. |
-| imports | string | | The exports name for reading from JS source file or objects only. |
-| exports | string | | The exports name for usage in JS file or object only. |
-
### jy-transform:constants~UTF8 : string ℗
@@ -339,9 +304,9 @@ The `'js'` type constant.
**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
**Access**: public
-
+
-### jy-transform:constants~TYPE_MAP : Object ℗
+### jy-transform:constants~EXT_TO_TYPE_MAP : Object ℗
A map for extensions to type.
**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
@@ -356,7 +321,14 @@ The default file indention (4 SPACEs).
### jy-transform:constants~MIN_INDENT : number ℗
-The minimum file indention (0 SPACE).
+The minimum file indention (0 SPACE) fo JS and JSON types.
+
+**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Access**: private
+
+
+### jy-transform:constants~MIN_YAML_INDENT : number ℗
+The minimum file indention (0 SPACE) for YAML types.
**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
**Access**: private
@@ -492,6 +464,57 @@ Reads from a passed stream and resolves by callback.
This module provides the _transform_ functionality for YAML, JS or JSON source to destination mapping.
**Access**: private
+
+
+### jy-transform:transformer~transform ⇒ Promise
+The entry method for all transformations accepting a configuration object and
+an (optional) middleware function. It executes the transformation logic.
+
+1. Input (read)
+2. Transform [ + Middleware]
+3. Output (write).
+
+**Kind**: inner property of [jy-transform:transformer](#module_jy-transform_transformer)
+**Returns**: Promise - The transformation result.
+**Access**: public
+**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
+**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
+
+| Param | Type | Description |
+| --- | --- | --- |
+| options | [TransformOptions](#TransformOptions) | The configuration for a transformation. |
+
+**Example**
+```js
+import { transform } from 'jy-transform';
+const options = {
+ src: 'foo/bar.yaml', // From YAML file...
+ transform: async (object) => { // ...with exchanging value...
+ object.foo = 'new value';
+ return object;
+ },
+ target: 'foo/bar.json', // ...to a new JSON file.
+ indent: 4,
+};
+
+// ---- Promise style:
+
+transform(options)
+ .then(console.log)
+ .catch(console.error);
+
+
+// ---- async/await style:
+
+try {
+ const msg = await transform(options);
+ console.log(msg);
+} catch (err) {
+ console.error(err.stack);
+};
+```
## jy-transform:validation:joi-extensions-file-helper ℗
@@ -577,6 +600,9 @@ values for origin and target depending on the `options.src` or `options.dest` va
* [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper) : Object ℗
* [~inferOriginDefault](#module_jy-transform_validation_options-schema-helper..inferOriginDefault) ⇒ string
* [~inferTargetDefault](#module_jy-transform_validation_options-schema-helper..inferTargetDefault) ⇒ string
+ * [~isFileStream](#module_jy-transform_validation_options-schema-helper..isFileStream) ⇒ boolean ℗
+ * [~adaptTargetPathType](#module_jy-transform_validation_options-schema-helper..adaptTargetPathType) ⇒ string ℗
+ * [~inferDestDefaultFromSrc](#module_jy-transform_validation_options-schema-helper..inferDestDefaultFromSrc) ⇒ string \| undefined
* [~getTypeFromFilePath(pathStr, defaultValue)](#module_jy-transform_validation_options-schema-helper..getTypeFromFilePath) ⇒ string ℗
@@ -605,6 +631,48 @@ Infers the _target_ type value from current validation context.
| --- | --- | --- |
| context | Object | The validation context. |
+
+
+### jy-transform:validation:options-schema-helper~isFileStream ⇒ boolean ℗
+Checks if passed `object` is a file stream instance.
+
+**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Returns**: boolean - A `true` if passed `object` is a file stream instance, else `false`.
+**Access**: private
+
+| Param | Type | Description |
+| --- | --- | --- |
+| object | \* | The object to check. |
+
+
+
+### jy-transform:validation:options-schema-helper~adaptTargetPathType ⇒ string ℗
+Returns the passes `dest` value or an adapted destination path (the latter if `target` is defined an differs from
+destinations path extension).
+
+**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Returns**: string - The `dest` value or an adapted destination path.
+**Access**: private
+
+| Param | Type | Description |
+| --- | --- | --- |
+| dest | string | The destination path. |
+| [target] | string | The target file type of destination. |
+
+
+
+### jy-transform:validation:options-schema-helper~inferDestDefaultFromSrc ⇒ string \| undefined
+This function is used to infer a _default_ value in case `options.dest` is not defined.
+Checks if `context.src` is either a string or a file stream where can get the file path from.
+If this detection process cannot be fulfilled then the function returns `undefined`.
+
+**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Returns**: string \| undefined - The adapted `dest` path if possible, or `undefined`.
+
+| Param | Type | Description |
+| --- | --- | --- |
+| context | Object | The validation context. |
+
### jy-transform:validation:options-schema-helper~getTypeFromFilePath(pathStr, defaultValue) ⇒ string ℗
@@ -628,20 +696,28 @@ The module options schema used in [module:options-validator](module:options-vali
**See**: [module:options-validator](module:options-validator)
* [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema) : Object ℗
- * [~readerOptionsSchema](#module_jy-transform_validation_options-schema..readerOptionsSchema) : JoiSchema ℗
- * [~writerOptionsSchema](#module_jy-transform_validation_options-schema..writerOptionsSchema) : JoiSchema ℗
+ * [~readOptionsSchema](#module_jy-transform_validation_options-schema..readOptionsSchema) : JoiSchema ℗
+ * [~writeOptionsSchema](#module_jy-transform_validation_options-schema..writeOptionsSchema) : JoiSchema ℗
+ * [~transformOptionsSchema](#module_jy-transform_validation_options-schema..transformOptionsSchema) : JoiSchema ℗
+
+
-
+### jy-transform:validation:options-schema~readOptionsSchema : JoiSchema ℗
+The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [ReadOptions](#ReadOptions).
+
+**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
+**Access**: private
+
-### jy-transform:validation:options-schema~readerOptionsSchema : JoiSchema ℗
-The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [Reader](Reader) options.
+### jy-transform:validation:options-schema~writeOptionsSchema : JoiSchema ℗
+The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [WriteOptions](#WriteOptions).
**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
**Access**: private
-
+
-### jy-transform:validation:options-schema~writerOptionsSchema : JoiSchema ℗
-The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [Writer](Writer) options.
+### jy-transform:validation:options-schema~transformOptionsSchema : JoiSchema ℗
+The prepared [external:joi.JoiSchema](external:joi.JoiSchema) for validating the [TransformOptions](#TransformOptions).
**Kind**: inner constant of [jy-transform:validation:options-schema](#module_jy-transform_validation_options-schema)
**Access**: private
@@ -864,7 +940,7 @@ Expect a `ValidationError` for a given options function.
| Param | Type | Description |
| --- | --- | --- |
-| invalidOptions | [ReaderOptions](#ReaderOptions) \| [WriterOptions](#WriterOptions) | The options which potentially produce the error. |
+| invalidOptions | [ReadOptions](#ReadOptions) \| [WriteOptions](#WriteOptions) | The options which potentially produce the error. |
| schema | Schema | The validation schema. |
@@ -877,7 +953,7 @@ Expect a validation success for a given options.
| Param | Type | Description |
| --- | --- | --- |
-| validOptions | [ReaderOptions](#ReaderOptions) \| [WriterOptions](#WriterOptions) | The options which should be correct. |
+| validOptions | [ReadOptions](#ReadOptions) \| [WriteOptions](#WriteOptions) | The options which should be correct. |
| schema | Schema | The validation schema. |
@@ -891,7 +967,7 @@ Reads the data from a given JS or JSON source.
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#ReaderOptions) | Contains the JS/JSON source reference to read from. |
+| options | [ReadOptions](#ReadOptions) | Contains the JS/JSON source reference to read from. |
@@ -906,7 +982,7 @@ exception on those.
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#ReaderOptions) | Contains the YAML source reference to read from. |
+| options | [ReadOptions](#ReadOptions) | Contains the YAML source reference to read from. |
@@ -922,7 +998,7 @@ Reads a particular content type from a source provided in the passed `options`.
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#ReaderOptions) | The read options. |
+| options | [ReadOptions](#ReadOptions) | The read options. |
**Example**
```js
@@ -950,55 +1026,6 @@ read(options)
.then(obj => console.log(JSON.stringify(obj)))
.catch(console.error);
```
-
-
-## transform ⇒ Promise
-The entry method for all transformation accepting a configuration object and
-an (optional) middleware function. It executes the transformation logic.
-
-1. Input (read)
-2. Transform [ + Middleware]
-3. Output (write).
-
-**Kind**: global variable
-**Returns**: Promise - The result.
-**Access**: public
-**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
-**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
-**Reject**: ValidationError If any `options` validation occurs.
-**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
-
-| Param | Type | Description |
-| --- | --- | --- |
-| options | [TransformerOptions](#TransformerOptions) | The configuration for a transformation. |
-| [middleware] | function | This middleware Promise can be used to intercept the JSON object for altering the passed JSON, the function signature is: ``` async function(object) ```
**NOTE:** the Promise has to return the processed JS object. |
-
-**Example**
-```js
-import { transform } from 'jy-transform';
-const options = {...};
-
-const middleware = async (object) {
- object.myproperty = 'new value';
- return object;
-};
-
-// ---- Promise style:
-
-transform(options, middleware)
- .then(console.log)
- .catch(console.error);
-
-
-// ---- async/await style:
-
-try {
- const msg = await transform(options, middleware);
- console.log(msg);
-} catch (err) {
- console.error(err.stack);
-};
-```
## createExportsString ⇒ Promise.<string> ℗
@@ -1083,7 +1110,7 @@ Writes a JS object to a YAML destination.
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS object to write into YAML destination. |
-| options | [WriterOptions](#WriterOptions) | The write destination and indention. |
+| options | [WriteOptions](#WriteOptions) | The write destination and indention. |
@@ -1103,7 +1130,7 @@ Writes a JS object to a JSON destination.
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS object to write into JSON destination. |
-| options | [WriterOptions](#WriterOptions) | The write destination and indention. |
+| options | [WriteOptions](#WriteOptions) | The write destination and indention. |
@@ -1123,7 +1150,7 @@ Writes a JS object to a JS destination. The object is prefixed by `module.export
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JSON to write into JS destination. |
-| options | [WriterOptions](#WriterOptions) | The write destination and indention. |
+| options | [WriteOptions](#WriteOptions) | The write destination and indention. |
@@ -1140,7 +1167,7 @@ Writes the passe JS object to a particular destination described by the passed `
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS source object to write. |
-| options | [WriterOptions](#WriterOptions) | The write options. |
+| options | [WriteOptions](#WriteOptions) | The write options. |
**Example**
```js
@@ -1183,9 +1210,9 @@ write(obj, options)
.then(console.log)
.catch(console.error);
```
-
+
-## ReaderOptions : object
+## ReadOptions : object
The configuration properties provided to the `read` function.
**Kind**: global typedef
@@ -1194,14 +1221,14 @@ The configuration properties provided to the `read` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
+| src | string \| Stream.Readable \| object | | The source (if `string` type it is treated as a file path). |
+| origin | string | "yaml" | The source origin type. |
| imports | string | | The exports name for reading from JS source files or objects only. |
-
+
-## WriterOptions : object
-The writer configuration properties provided to the `write` function.
+## WriteOptions : object
+The configuration properties provided to the `write` function.
**Kind**: global typedef
**Access**: public
@@ -1209,15 +1236,15 @@ The writer configuration properties provided to the `write` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| indent | number | 2 | The indention value for pretty-print of output. |
+| dest | string \| Stream.Writable \| object | | The destination (if `string` type it is treated as a file path). |
+| target | string | "js" | The destination target type. |
+| indent | number | 2 | The indentation value for pretty-print of output. |
| exports | string | | The exports name for usage in JS destination files only. |
| force | string | false | Force overwriting of existing output files on write phase. |
-
+
-## TransformerOptions : object
+## TransformOptions : object
The configuration properties provided to the `transform` function.
**Kind**: global typedef
@@ -1226,13 +1253,14 @@ The configuration properties provided to the `transform` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
-| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| indent | number | 2 | The indention value for pretty-print of output. |
-| exports | string | | The exports name for usage in JS destination files only. |
+| src | string \| Stream.Readable \| object | | The _read_ source (if `string` type it is treated as a file path). |
+| origin | string | "yaml" | The _read_ source origin type. |
+| imports | string | | The _read_ exports name for reading from JS source files or objects only. |
+| transform | function | | The option is a _transformation_ function with the following signature:
``` [async|Promise] function(object) ``` |
+| dest | string \| Stream.Writable \| object | | The _write_ destination (if `string` type it is treated as a file path). This property could be optional in case we infer a value from `src` which is then either a string or a file stream where can get the file path from. If this detection process cannot be fulfilled then the property is `undefined` and the transform process will fail with a `ValidationError` on write phase. |
+| target | string | "js" | The _write_ target type. |
+| indent | number | 2 | The _write_ indentation value for pretty-print of output. |
+| exports | string | | The _write_ exports name for usage in JS destination files only. |
| force | string | false | Force overwriting of existing output files on write phase. |
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index 65e5339..44da18e 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -7,11 +7,10 @@
- [Typedefs](#typedefs)
- [jy-transform:constants](#jy-transformconstants)
- [read ⇒ Promise](#read-%E2%87%92-codepromisecode)
-- [transform ⇒ Promise](#transform-%E2%87%92-codepromisecode)
- [write ⇒ Promise](#write-%E2%87%92-codepromisecode)
-- [ReaderOptions : object](#readeroptions--codeobjectcode)
-- [WriterOptions : object](#writeroptions--codeobjectcode)
-- [TransformerOptions : object](#transformeroptions--codeobjectcode)
+- [ReadOptions : object](#readoptions--codeobjectcode)
+- [WriteOptions : object](#writeoptions--codeobjectcode)
+- [TransformOptions : object](#transformoptions--codeobjectcode)
@@ -29,15 +28,6 @@
The configuration properties provided to the transform function.
@@ -104,7 +94,7 @@ Reads a particular content type from a source provided in the passed `options`.
| Param | Type | Description |
| --- | --- | --- |
-| options | [ReaderOptions](#ReaderOptions) | The read options. |
+| options | [ReadOptions](#ReadOptions) | The read options. |
**Example**
```js
@@ -132,55 +122,6 @@ read(options)
.then(obj => console.log(JSON.stringify(obj)))
.catch(console.error);
```
-
-
-## transform ⇒ Promise
-The entry method for all transformation accepting a configuration object and
-an (optional) middleware function. It executes the transformation logic.
-
-1. Input (read)
-2. Transform [ + Middleware]
-3. Output (write).
-
-**Kind**: global variable
-**Returns**: Promise - The result.
-**Access**: public
-**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
-**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
-**Reject**: ValidationError If any `options` validation occurs.
-**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
-
-| Param | Type | Description |
-| --- | --- | --- |
-| options | [TransformerOptions](#TransformerOptions) | The configuration for a transformation. |
-| [middleware] | function | This middleware Promise can be used to intercept the JSON object for altering the passed JSON, the function signature is: ``` async function(object) ```
**NOTE:** the Promise has to return the processed JS object. |
-
-**Example**
-```js
-import { transform } from 'jy-transform';
-const options = {...};
-
-const middleware = async (object) {
- object.myproperty = 'new value';
- return object;
-};
-
-// ---- Promise style:
-
-transform(options, middleware)
- .then(console.log)
- .catch(console.error);
-
-
-// ---- async/await style:
-
-try {
- const msg = await transform(options, middleware);
- console.log(msg);
-} catch (err) {
- console.error(err.stack);
-};
-```
## write ⇒ Promise
@@ -196,7 +137,7 @@ Writes the passe JS object to a particular destination described by the passed `
| Param | Type | Description |
| --- | --- | --- |
| object | Object | The JS source object to write. |
-| options | [WriterOptions](#WriterOptions) | The write options. |
+| options | [WriteOptions](#WriteOptions) | The write options. |
**Example**
```js
@@ -239,9 +180,9 @@ write(obj, options)
.then(console.log)
.catch(console.error);
```
-
+
-## ReaderOptions : object
+## ReadOptions : object
The configuration properties provided to the `read` function.
**Kind**: global typedef
@@ -250,14 +191,14 @@ The configuration properties provided to the `read` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
+| src | string \| Stream.Readable \| object | | The source (if `string` type it is treated as a file path). |
+| origin | string | "yaml" | The source origin type. |
| imports | string | | The exports name for reading from JS source files or objects only. |
-
+
-## WriterOptions : object
-The writer configuration properties provided to the `write` function.
+## WriteOptions : object
+The configuration properties provided to the `write` function.
**Kind**: global typedef
**Access**: public
@@ -265,15 +206,15 @@ The writer configuration properties provided to the `write` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| indent | number | 2 | The indention value for pretty-print of output. |
+| dest | string \| Stream.Writable \| object | | The destination (if `string` type it is treated as a file path). |
+| target | string | "js" | The destination target type. |
+| indent | number | 2 | The indentation value for pretty-print of output. |
| exports | string | | The exports name for usage in JS destination files only. |
| force | string | false | Force overwriting of existing output files on write phase. |
-
+
-## TransformerOptions : object
+## TransformOptions : object
The configuration properties provided to the `transform` function.
**Kind**: global typedef
@@ -282,12 +223,13 @@ The configuration properties provided to the `transform` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
-| src | string \| Stream.Readable \| object | | The source (if `string` type is treated as a file path). |
-| origin | string | "yaml" | The origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
-| dest | string \| Stream.Writable \| object | | The destination (if `string` type is treated as a file path). |
-| target | string | "js" | The target type. |
-| indent | number | 2 | The indention value for pretty-print of output. |
-| exports | string | | The exports name for usage in JS destination files only. |
+| src | string \| Stream.Readable \| object | | The _read_ source (if `string` type it is treated as a file path). |
+| origin | string | "yaml" | The _read_ source origin type. |
+| imports | string | | The _read_ exports name for reading from JS source files or objects only. |
+| transform | function | | The option is a _transformation_ function with the following signature:
``` [async|Promise] function(object) ``` |
+| dest | string \| Stream.Writable \| object | | The _write_ destination (if `string` type it is treated as a file path). This property could be optional in case we infer a value from `src` which is then either a string or a file stream where can get the file path from. If this detection process cannot be fulfilled then the property is `undefined` and the transform process will fail with a `ValidationError` on write phase. |
+| target | string | "js" | The _write_ target type. |
+| indent | number | 2 | The _write_ indentation value for pretty-print of output. |
+| exports | string | | The _write_ exports name for usage in JS destination files only. |
| force | string | false | Force overwriting of existing output files on write phase. |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6397f7d..f96ac71 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,58 +1,89 @@
-## Changelog
+# Changelog
-#### v3.0.0
+## v3.0.0
-- New Features:
- - The _middleware_ function must not need to be a Promise anymore, but it is still recommended.
- - The `read` process returns a clone of the `options.src` when it is a JS object (so the origin
- would never be changed).
- - The minimum indent for YAML target types is validated for 2 now and throws a `ValidationError`
- if < 2 (for others 0 is still valid).
+### Note
+This release has undergone a huge refactoring which includes some new features, cleanups in many places
+including a new public interface, bugfixes and many internal improvements. Of course, this resulted in some
+APIs and CLI backwards compatibilities (these are marked in the descriptions below). So, please read the following
+changelog entries carefully and see also the following documents for more information about how to use the
+new interface:
+- [README.md](https://github.com/deadratfink/jy-transform/blob/master/README.md)
+- [API-PUBLIC.md](https://github.com/deadratfink/jy-transform/blob/master/API-PUBLIC.md)
-- Bugfix:
- - If destination is not given on transformation process but the target is, then the destination file extension
- is adapted to the proper type, e.g. `$ ./jyt inch.json -t yaml` results in a file _inch.yaml_ (formerly:
- _inch.json_ with YAML content or _inch(1).json_ with YAML, the latter if `options.force` was `true`).
+### New Features:
+- [[#59](https://github.com/deadratfink/jy-transform/issues/59)] Support single-quotes options for JS output.
+ - **CLI & API Backwards Incompatible Change!**
+ - This is the default now.
+- [[#55](https://github.com/deadratfink/jy-transform/issues/55)] The `read` process returns a clone of the
+ `options.src` when it is a JS object (so the origin would never be changed).
+- The `options.transform` function (formerly aka _middleware_ function) must not need to be a Promise anymore, but it is still recommended.
-- **CLI & API Changes (Backwards Incompatible!):**
- - Removed support for Node.js < v4.0.
- - Default `options.indent` is 2 (instead of 4) now which seems to be more common in the JS/Node.js community.
- - An invalid indention setting (i.e. `indent` < 0 or `indent` > 8) raises a `ValidationError` now.
+### Bugfixes:
+- [[#57](https://github.com/deadratfink/jy-transform/issues/57)] The minimum indent for YAML target types is
+ validated for 2 now and throws a `ValidationError` if < 2 (for others 0 is still valid).
+- [[#56](https://github.com/deadratfink/jy-transform/issues/56)] If _destination_ is not given on transformation
+ process but the _target_ is, then the destination's file extension
+ is adapted to the proper type, e.g. `$ ./jyt inch.json -t yaml` results in a file _inch.yaml_ (formerly:
+ _inch.json_ with YAML content or respectively _inch(1).json_ with YAML, the latter if `options.force` was `true`).
-- **API Changes Only (Backwards Incompatible!):**
+### Public Interface Changes & Improvements:
+- [[#61](https://github.com/deadratfink/jy-transform/issues/61)] Invalid indention setting should raise an error:
+ - **CLI & API Backwards Incompatible Change!**
+ - An invalid indention setting (i.e. `indent` < 0 or `indent` > 8) raises a `ValidationError` now instead
+ of using default.
+- [[#60](https://github.com/deadratfink/jy-transform/issues/60)] Default `[write.]options.indent` is 2 (instead of 4):
+ - **CLI & API Backwards Incompatible Change!**
+ - This seems to be more common in the JS/Node.js community.
+- [[#57](https://github.com/deadratfink/jy-transform/issues/57)] Provide a simplified interface:
+ - **API Backwards Incompatible Changes!**
- The exported constants `YAML`, `JS` and `JSON` (usable for `options.origin/target`) are renamed respectively
to `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON`.
- - Provide a simplified interface:
- - Prototype approach removed from `Transformer`, `Reader` and `Writer`, turning it to internal modules with
- exports of _named_ functions:
- - The formerly exported `Reader.readJs(...)/readYaml(...)` functions are not public anymore and replaced
- by a general `read(options)` function.
- - The formerly exported `Writer.writeJs(...)/writeJson(...)/writeYaml(...)` functions are not public
- anymore and replaced by a general `write(object, options)` function.
- - The formerly exported `middleware` (identity function) is not publicly available anymore.
- - Reduced and named export of constants: `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON` only.
- - The `options.imports/exports` are not allowed to be empty strings anymore (semantically senseless,
- just leave it out).
- - The configuration property `options.dest` is required for `Writer` when using the API (but not from `Transformer`
- if it can be inferred from `options.src` which is true for string or file stream sources).
+ - Prototype approach removed from `Transformer`, `Reader` and `Writer`, turning it to internal modules which
+ exports _named_ functions instead:
+ - The formerly exported `Reader.readJs(...)/readYaml(...)` functions are not public anymore and replaced
+ by a general `read(options)` function.
+ - The formerly exported `Writer.writeJs(...)/writeJson(...)/writeYaml(...)` functions are not public
+ anymore and replaced by a general `write(object, options)` function.
+ - The formerly exported `Transformer.transform(options, middleware)` functions
+ does not take the `middleware` parameter anymore (it is added to options: `options.transform`).
+ - The formerly exported `middleware` (identity function) is not publicly available anymore.
+ - Reduced and named export of constants: `TYPE_YAML`, `TYPE_JS` and `TYPE_JSON` only.
- Removal of `LogWrapper` (no more logger injection possible).
-
-- Internal Changes & Improvements:
- - Documentation restructured.
- - Removal of _development_ branch.
- - Usage of [babel](https://babeljs.io/) and therefore most modern language features.
- - Update of dependencies and amount reduced.
- - Code base could be shrinked and readabilty was improved.
+ - The `options.imports/exports` are not allowed to be empty strings anymore (semantically senseless, just leave it out).
+ - Of course, the configuration property `options.dest` is required for _write_ process when using the API (but not from _transformer_
+ if it can be inferred from `options.src` but which is true for string or file stream sources only).
+
+### Internal Changes & Improvements:
+- [[#54](https://github.com/deadratfink/jy-transform/issues/54)] General dependency check and update:
+ - Latest versions.
- Usage of _native_ Promises instead of [bluebird](http://bluebirdjs.com/docs/getting-started.html).
- - Tests re-written in [Jest](https://facebook.github.io/jest) (could get rid of
- [assert](https://github.com/defunctzombie/commonjs-assert),
- [mocha](https://mochajs.org/) and [istanbul](https://github.com/gotwarlost/istanbul)).
+ - Test dependencies reduced.
+- [[#53](https://github.com/deadratfink/jy-transform/issues/53)] Update supported node versions:
+ - **CLI & API Backwards Incompatible Change!**
- Add travis build for Node.js v8.x.
- - Remove travis build for Node.js < v4.x.
- - Removal of `OptionsHandler` and `Validator` (replaced the validation by using
- [joi](https://github.com/hapijs/joi/tree/v10.5.0) now).
+ - Remove travis build for Node.js < v4.x.
+- [[#52](https://github.com/deadratfink/jy-transform/issues/52)] Leverage modern ES6 features:
+ - Integrated by [babel](https://babeljs.io/).
+ - Update of dependencies and amount reduced.
+ - Code base could be shrinked and readabilty was improved.
+- [[#51](https://github.com/deadratfink/jy-transform/issues/51)] Removal of _development_ branch.
+- [[#50](https://github.com/deadratfink/jy-transform/issues/50)] Update/upgrade ESLint
+- [[#49](https://github.com/deadratfink/jy-transform/issues/49)] Tests re-written in
+ [Jest](https://facebook.github.io/jest), could get rid of "complex" test setup
+ ([assert](https://github.com/defunctzombie/commonjs-assert), [mocha](https://mochajs.org/) and
+ [istanbul](https://github.com/gotwarlost/istanbul)).
+- [[#48](https://github.com/deadratfink/jy-transform/issues/48)] Using [Joi](https://github.com/hapijs/joi)
+ for consistent options validation:
+ - Removal of `OptionsHandler` and `Validator`
+- [[#47](https://github.com/deadratfink/jy-transform/issues/47)] Integration of
+ [bithound.io](https://www.bithound.io/github/deadratfink/jy-transform)
+- [[#46](https://github.com/deadratfink/jy-transform/issues/46)] Use Make as an abstraction to npm scripts
+- [[#45](https://github.com/deadratfink/jy-transform/issues/45)] [Node Security Plattform] integrated.
+- [[#43](https://github.com/deadratfink/jy-transform/issues/43)] Documentation restructured.
+
-#### v2.0.1
+### v2.0.1
- [[#39](https://github.com/deadratfink/jy-transform/issues/39)] Maintenance release.
- Update dependencies to latest.
@@ -60,7 +91,7 @@
- Docs improved/corrected.
- Add target pretest in `scripts` section to `rm` _./test/tmp_ folder.
-#### v2.0.0
+### v2.0.0
- [[#33](https://github.com/deadratfink/jy-transform/issues/33)] Enhance `LogWrapper` with `TRACE` level (API).
- [[#32](https://github.com/deadratfink/jy-transform/issues/32)] Introduce input and output on CLI as
@@ -71,12 +102,12 @@
'yaml' for origin (API).
- [Cleanup] Update dependencies.
-#### v1.0.2
+### v1.0.2
- [[#30](https://github.com/deadratfink/jy-transform/issues/30)] Fix README and externalize API reference to wiki.
- [[#29](https://github.com/deadratfink/jy-transform/issues/29)] Fix Promise warning on write process.
-#### v1.0.1
+### v1.0.1
Initial public release. This covers the basic implementation and tests. The following features and fixes and
part of this release:
diff --git a/CODEOWNERS b/CODEOWNERS
new file mode 100644
index 0000000..d166473
--- /dev/null
+++ b/CODEOWNERS
@@ -0,0 +1,7 @@
+# See: https://github.com/blog/2392-introducing-code-owners
+#
+# Lines starting with '#' are comments.
+# Each line is a file pattern followed by one or more owners.
+
+# These owners will be the default owners for everything in the repo.
+* @deadratfink
diff --git a/MAKE.md b/MAKE.md
index 5e11af3..c5c37a9 100644
--- a/MAKE.md
+++ b/MAKE.md
@@ -6,6 +6,7 @@ Target Call | Description | Dependencies
`$ make eslint` | Runs ESLint. |
`$ make help` | Prints the help about targets. |
`$ make install` | Installs all modules |
+`$ make nsp` | Runs an [Node Security Plattform](https://nodesecurity.io/opensource) check. |
`$ make publish` | Publishes module to NPM registry. | `test readme`
`$ make readme` | Creates all the documentation parts of the project |
-`$ make test` | Runs the test suite and ESLint. |
+`$ make test` | Runs the test suite, ESLint and a [Node Security Plattform](https://nodesecurity.io/opensource) check. |
diff --git a/Makefile b/Makefile
index 9ce77a7..b0444ee 100644
--- a/Makefile
+++ b/Makefile
@@ -16,10 +16,17 @@ clean: ## Removes generated files in folders ./node_modules, ./lib and ./coverag
rm -rf node_modules
rm -rf coverage
-test: ## Runs the test suite and ESLint.
- @printf "Running test suite and ESLint...\n"
+test: ## Runs the test suite, ESLint and a [Node Security Plattform](https://nodesecurity.io/opensource) check.
+ @printf "Running test suite, ESLint and NSP...\n"
npm test
npm run eslint
+ npm run nsp
+
+nsp: ## Runs an [Node Security Plattform](https://nodesecurity.io/opensource) check.
+ @printf "Running NSP check...\n"
+ npm run nsp
+
+bithound bithound check git@github.com:deadratfink/jy-transform.git
readme: ## Creates all the documentation parts of the project: _README.md_, _MAKE.md_, _PACKAGE.md_ and _API.md_ (the latter based on [JSDoc](http://usejsdoc.org/)).
@printf "Create documentation...\n"
diff --git a/PACKAGE.md b/PACKAGE.md
index e5098b3..d741837 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -37,6 +37,7 @@ npm test
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
- [codecov](https://github.com/codecov/codecov-node): Uploading report to Codecov: https://codecov.io
- [coveralls](https://github.com/nickmerwin/node-coveralls): takes json-cov output into stdin and POSTs to coveralls.io
+- [cwd](https://github.com/jonschlinkert/cwd): Easily get the CWD (current working directory) of a project based on package.json, optionally starting from a given path. (node.js/javascript util)
- [doctoc](https://github.com/thlorenz/doctoc): Generates TOC for markdown files of local git repo.
- [eslint](https://github.com/eslint/eslint): An AST-based pattern checker for JavaScript.
- [eslint-config-airbnb-base](https://github.com/airbnb/javascript): Airbnb's base JS ESLint config, following our styleguide
@@ -50,6 +51,7 @@ npm test
- [jsdoc-babel](https://github.com/ctumolosus/jsdoc-babel): A JSDoc plugin that transforms ES6 source files with Babel before they are processsed.
- [jsdoc-parse](https://github.com/jsdoc2md/jsdoc-parse): Transforms jsdoc data into something more suitable for use as template input
- [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown): Generates markdown API documentation from jsdoc annotated source code
+- [nsp](https://github.com/nodesecurity/nsp): The Node Security (nodesecurity.io) command line interface
- [package-json-to-readme](https://github.com/zeke/package-json-to-readme): Generate a README.md from package.json contents
- [winston](https://github.com/winstonjs/winston): A multi-transport async logging library for Node.js
- [winston-console-formatter](https://github.com/eugeny-dementev/winston-console-formatter): Pretty print console formatter in yaml like style
diff --git a/README.md b/README.md
index 91fcb94..a1dc1d6 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,27 @@
-[![License][gh-license-image]][gh-license-url] [![Issue Stats][gh-issues-image]][gh-issues-url] [![Releases][gh-releases-image]][gh-releases-url] [![Tags][gh-tags-image]][gh-tags-url] [![Build Status][ci-image]][ci-url] [![Waffle][waffle-image]][waffle-url] [![Code Climate][cocl-image]][cocl-url]
-[![codecov.io][cc-image-master]][cc-url-master] [![coveralls.io][ca-image-master]][ca-url-master] [![inch-ci.org][inch-image-master]][inch-url-master] [![Dependency Status][dep-image-master]][dep-url-master] [![devDependency Status][devdep-image-master]][devdep-url-master]
-
-[![NPM](https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/jy-transform/)
-
-[![NPM](https://nodei.co/npm-dl/jy-transform.png?height=3&months=9)](https://nodei.co/npm-dl/jy-transform/)
+[![Node version][node-version-image]][node-version-url]
+[![License][gh-license-image]][gh-license-url]
+[![Issue Stats][gh-issues-image]][gh-issues-url]
+[![Releases][gh-releases-image]][gh-releases-url]
+[![Tags][gh-tags-image]][gh-tags-url]
+[![Build Status][ci-image]][ci-url]
+[![Waffle][waffle-ready-image]][waffle-url]
+[![Waffle][waffle-waffle-in-progress-image]][waffle-url]
+[![Code Climate][cocl-image]][cocl-url]
+[![codecov.io][cc-image-master]][cc-url-master]
+[![coveralls.io][ca-image-master]][ca-url-master]
+[![inch-ci.org][inch-image-master]][inch-url-master]
+[![bitHound Code][bithound-code-image]][bithound-url]
+[![bitHound Dependencies][bitHound-dependencies-image]][bitHound-dependencies]
+[![bitHound Dev Dependencies][bitHound-dev-dependencies-image]][bitHound-dependencies]
+[![NSP Status][nsp-image-master]][nsp-url-master]
+
+
+
+
+[![NPM][npm-image]][npm-url]
+[![NPM][npm-downloads-image]][npm-url]
[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat-square
[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
@@ -25,7 +43,8 @@
[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat-square
[is-url]: http://issuestats.com/github/deadratfink/jy-transform
-[waffle-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
+[waffle-ready-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
+[waffle-waffle-in-progress-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=in%20progress&title=Waffle%20In%20Progress&style=flat-square
[waffle-url]: https://waffle.io/deadratfink/jy-transform
[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat-square
@@ -48,6 +67,22 @@
[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat-square
[devdep-url-master]: https://david-dm.org/deadratfink/jy-transform/master#info=devDependencies
+[nsp-image-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0/badge?style=flat-square
+[nsp-url-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0
+
+[node-version-image]: https://img.shields.io/node/v/jy-transform.svg?style=flat-square
+[node-version-url]: http://nodejs.org/download/
+
+[npm-image]: https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true
+[npm-url]: https://nodei.co/npm/jy-transform/
+[npm-downloads-image]: https://nodei.co/npm-dl/jy-transform.png?height=2&months=9
+
+[bithound-url]: https://www.bithound.io/github/deadratfink/jy-transform
+[bithound-code-image]: https://img.shields.io/bithound/code/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-dependencies]: https://www.bithound.io/github/deadratfink/jy-transform/master/dependencies/npm
+[bitHound-dependencies-image]: https://img.shields.io/bithound/dependencies/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-dev-dependencies-image]: https://img.shields.io/bithound/devDependencies/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-score-image]: https://img.shields.io/bithound/score/github/deadratfink/jy-transform.svg?style=flat-square
# jy-transform
@@ -91,22 +126,30 @@ npm install jy-transform --global
```javascript
import { transform } from 'jy-transform';
-const transformOptions = {
- src: 'foo/bar.yaml',
- target: 'foo/bar.json',
- indent: 4,
+const options = {
+ src: 'foo/bar.yaml', // Here: read from YAML file...
+ transform: async (object) => { // ...with exchanging value...
+ object.foo = 'new value';
+ return object;
+ },
+ dest: 'foo/bar.json', // ...to a new JSON file.
+ indent: 4, // Ensure an indentation of 4.
};
-const transformFunc = async (object) => {
- object.foo = 'new value';
- return object;
-};
+// ---- Promise style:
+
+transform(options)
+ .then(console.log)
+ .catch(console.error);
+
+
+// ---- async/await style:
+
-// of course, inside an async
try {
- const msg = await transform(transformOptions, transformFunc);
- console.log(msg);
-} catch (err) {
+ const msg = await transform(options); // Transform, of course, inside an async.
+ console.log(msg); // Success message!
+} catch (err) { // Oops!
console.error(err.stack);
}
```
@@ -116,11 +159,11 @@ try {
```javascript
import { read } from 'jy-transform';
-let object;
+const options = { src: 'foo/bar.yaml' }; // Here: read from file.
try {
- object = await read({ src: 'foo/bar.yaml' }); // here: read from file
- console.log(JSON.stringify(object));
+ const object = await read(options);
+ console.log(JSON.stringify(object)); // Print write success message.
} catch (err) {
console.error(err.stack);
}
@@ -131,9 +174,11 @@ try {
```javascript
import { write } from 'jy-transform';
+const options = { dest: 'foo/bar.yaml' }; // Here: write to file.
+
try {
- const msg = await write(object, { dest: 'foo/bar.yaml' });
- console.log(msg);
+ const msg = await write(object, options);
+ console.log(msg); // Print write success message.
} catch (err) {
console.error(err.stack);
}
@@ -142,7 +187,7 @@ try {
## Why This Module?
After struggling with some huge YAML file and accidentally
-occurring wrong indentions which results in an annoying investigation hell,
+occurring wrong indentations which results in an annoying investigation hell,
I decided to get rid of the YAML file and therefore, create a module which
should be aimed as the swiss army knife for transforming YAML, JS and JSON
types into each other format.
@@ -150,8 +195,7 @@ types into each other format.
## Usage
The module can be used on CLI or as API (the latter is fully
-[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise))
-based).
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) based).
### Usage Types
@@ -279,7 +323,7 @@ Usage:
Options:
-o, --origin [STRING] The origin type of INPUT-FILE: [ js | json | yaml ]. (Default is if not given, the type is tried to be inferred from the extension of source path, else it is 'yaml')
-t, --target [STRING] The target type of OUTPUT-FILE: [ js | json | yaml ]. (Default is if not given, the type is tried to be inferred from the extension of destination path, else it is 'js')
- -i, --indent [NUMBER] The indention for pretty-print: 1 - 8. (Default is 4)
+ -i, --indent [NUMBER] The indentation for pretty-print: 1 - 8. (Default is 4)
-f, --force Force overwriting of existing output files on write phase. When files are not overwritten (which is default),
then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in
case of foo.yaml it would be foo(1).yaml.
@@ -312,7 +356,7 @@ The OPTIONS are more formally defined in the following table:
| --- | --- | --- | --- | --- | --- |
| `-o` | `--origin` | string of: [ _js_ | _json_ | _yaml_ ] | The transformation origin type. | if not given, the type is tried to be inferred from the extension of source path, else it is _yaml_ | no |
| `-t` | `--target` | string of: [ _js_ | _json_ | _yaml_ ] | The transformation target type. | if not given, the type is tried to be inferred from the extension of destination path, else it is _js_ | no |
-| `-i` | `--indent` | integer [ 1 - 8 ] | The code indention used in destination files. | 2 | no |
+| `-i` | `--indent` | integer [ 1 - 8 ] | The code indentation used in destination files. | 2 | no |
| `-f` | `--force` | n/a | Force overwriting of existing output files on write phase. When files are not overwritten (which is default), then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in case of _foo.yaml_ it would be _foo(1).yaml_. | _false_ | no |
| `-m` | `--imports` | string | Define a 'module.exports[.identifier] = ' identifier (to read from JS _source_ file only, must be a valid JS identifier!) | _undefined_ | no |
| `-x` | `--exports` | string | Define a 'module.exports[.identifier] = ' identifier (for usage in JS _destination_ file only, must be a valid JS identifier!) | _undefined_ | no |
@@ -322,7 +366,7 @@ The OPTIONS are more formally defined in the following table:
| `-h` | `--help` | n/a | Display help and usage details. | n/a | no |
-**NOTE:** an invalid indention setting (1 > `-i`, `--indent` > 8) does not raise an error but a default of 4 SPACEs is applied instead.
+**NOTE:** an invalid indentation setting (1 > `-i`, `--indent` > 8) does not raise an error but a default of 4 SPACEs is applied instead.
#### Examples
@@ -487,7 +531,7 @@ By default this feature is not enabled to prevent you from accidentally
overwriting your input source or already generated targets.
But let's say we want to overwrite the original source now because you want
-to change the indention from 2 to 4 SPACEs, then we can do this as follows:
+to change the indentation from 2 to 4 SPACEs, then we can do this as follows:
```
$ jyt foo.js -f
```
@@ -557,7 +601,7 @@ The `options` object has to follow this key-values tables:
| Option | Type | Description | Default | Required |
| --- | --- | --- | --- | --- |
| `dest` | [ _String_ | _Stream.Writable_ | _Object_ ] | The destination information object: `String` is used as file path, `Stream.Writable` writes a stringified source and `object` is used for direct JS object assignment of the (stringified or JS object) source. If a string is set as file path then the output and if input and output file path are the same, then the file overwriting is handled depending on the `force` value! | - | yes |
-| `indent` | _Number_ | The indention in files. | 2 | no |
+| `indent` | _Number_ | The indentation in files. | 2 | no |
| `force` | _Boolean_ | Force overwriting of existing output files on write phase. When files are not overwritten, then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in case of _foo.yaml_ it would be _foo(1).yaml_. | _false_ | no |
| `imports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (to read from JS _source_ only, must be a valid JS identifier!) | _undefined_ | no |
| `exports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (for usage in JS _destination_ only, must be a valid JS identifier!) | _undefined_ | no |
diff --git a/package.json b/package.json
index ca98689..5d58f84 100644
--- a/package.json
+++ b/package.json
@@ -26,7 +26,8 @@
"wiki": "jsdoc2md ./jyt lib/*.js index.js > docs/API.md && doctoc docs/API.md --github --title '### TOC' --maxlevel 2 && cat docs/API.md > '../jy-transform.wiki/API-v2.md' && cat docs/CONTRIBUTING.md > ../jy-transform.wiki/Contributing.md && cat docs/CHANGELOG.md > ../jy-transform.wiki/Changelog.md && doctoc ../jy-transform.wiki/Changelog.md --github --title '### TOC' --maxlevel 3",
"pretest": "mkdir -pv test/tmp",
"test": "JYT_DEBUG=false JYT_ERROR=false jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
- "eslint": "eslint ."
+ "eslint": "eslint .",
+ "nsp": "nsp check"
},
"engines": {
"node": ">=4.0.0"
@@ -64,6 +65,7 @@
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": " ~3.0.0",
"jsdoc-to-markdown": " ~3.0.0",
+ "nsp": "~2.6.3",
"package-json-to-readme": " ~2.0.0",
"winston": " ~2.3.0",
"winston-console-formatter": "~0.3.1"
diff --git a/readme/BADGES.md b/readme/BADGES.md
index e03edb8..a1488bd 100644
--- a/readme/BADGES.md
+++ b/readme/BADGES.md
@@ -1,9 +1,27 @@
-[![License][gh-license-image]][gh-license-url] [![Issue Stats][gh-issues-image]][gh-issues-url] [![Releases][gh-releases-image]][gh-releases-url] [![Tags][gh-tags-image]][gh-tags-url] [![Build Status][ci-image]][ci-url] [![Waffle][waffle-image]][waffle-url] [![Code Climate][cocl-image]][cocl-url]
-[![codecov.io][cc-image-master]][cc-url-master] [![coveralls.io][ca-image-master]][ca-url-master] [![inch-ci.org][inch-image-master]][inch-url-master] [![Dependency Status][dep-image-master]][dep-url-master] [![devDependency Status][devdep-image-master]][devdep-url-master]
-
-[![NPM](https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/jy-transform/)
-
-[![NPM](https://nodei.co/npm-dl/jy-transform.png?height=3&months=9)](https://nodei.co/npm-dl/jy-transform/)
+[![Node version][node-version-image]][node-version-url]
+[![License][gh-license-image]][gh-license-url]
+[![Issue Stats][gh-issues-image]][gh-issues-url]
+[![Releases][gh-releases-image]][gh-releases-url]
+[![Tags][gh-tags-image]][gh-tags-url]
+[![Build Status][ci-image]][ci-url]
+[![Waffle][waffle-ready-image]][waffle-url]
+[![Waffle][waffle-waffle-in-progress-image]][waffle-url]
+[![Code Climate][cocl-image]][cocl-url]
+[![codecov.io][cc-image-master]][cc-url-master]
+[![coveralls.io][ca-image-master]][ca-url-master]
+[![inch-ci.org][inch-image-master]][inch-url-master]
+[![bitHound Code][bithound-code-image]][bithound-url]
+[![bitHound Dependencies][bitHound-dependencies-image]][bitHound-dependencies]
+[![bitHound Dev Dependencies][bitHound-dev-dependencies-image]][bitHound-dependencies]
+[![NSP Status][nsp-image-master]][nsp-url-master]
+
+
+
+
+[![NPM][npm-image]][npm-url]
+[![NPM][npm-downloads-image]][npm-url]
[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat-square
[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
@@ -25,7 +43,8 @@
[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat-square
[is-url]: http://issuestats.com/github/deadratfink/jy-transform
-[waffle-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
+[waffle-ready-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
+[waffle-waffle-in-progress-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=in%20progress&title=Waffle%20In%20Progress&style=flat-square
[waffle-url]: https://waffle.io/deadratfink/jy-transform
[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat-square
@@ -48,3 +67,19 @@
[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat-square
[devdep-url-master]: https://david-dm.org/deadratfink/jy-transform/master#info=devDependencies
+[nsp-image-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0/badge?style=flat-square
+[nsp-url-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0
+
+[node-version-image]: https://img.shields.io/node/v/jy-transform.svg?style=flat-square
+[node-version-url]: http://nodejs.org/download/
+
+[npm-image]: https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true
+[npm-url]: https://nodei.co/npm/jy-transform/
+[npm-downloads-image]: https://nodei.co/npm-dl/jy-transform.png?height=2&months=9
+
+[bithound-url]: https://www.bithound.io/github/deadratfink/jy-transform
+[bithound-code-image]: https://img.shields.io/bithound/code/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-dependencies]: https://www.bithound.io/github/deadratfink/jy-transform/master/dependencies/npm
+[bitHound-dependencies-image]: https://img.shields.io/bithound/dependencies/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-dev-dependencies-image]: https://img.shields.io/bithound/devDependencies/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-score-image]: https://img.shields.io/bithound/score/github/deadratfink/jy-transform.svg?style=flat-square
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index a92113e..c5b06f0 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -5,22 +5,30 @@
```javascript
import { transform } from 'jy-transform';
-const transformOptions = {
- src: 'foo/bar.yaml',
- target: 'foo/bar.json',
- indent: 4,
+const options = {
+ src: 'foo/bar.yaml', // Here: read from YAML file...
+ transform: async (object) => { // ...with exchanging value...
+ object.foo = 'new value';
+ return object;
+ },
+ dest: 'foo/bar.json', // ...to a new JSON file.
+ indent: 4, // Ensure an indentation of 4.
};
-const transformFunc = async (object) => {
- object.foo = 'new value';
- return object;
-};
+// ---- Promise style:
+
+transform(options)
+ .then(console.log)
+ .catch(console.error);
+
+
+// ---- async/await style:
+
-// of course, inside an async
try {
- const msg = await transform(transformOptions, transformFunc);
- console.log(msg);
-} catch (err) {
+ const msg = await transform(options); // Transform, of course, inside an async.
+ console.log(msg); // Success message!
+} catch (err) { // Oops!
console.error(err.stack);
}
```
@@ -30,9 +38,11 @@ try {
```javascript
import { read } from 'jy-transform';
+const options = { src: 'foo/bar.yaml' }; // Here: read from file.
+
try {
- const object = await read({ src: 'foo/bar.yaml' }); // here: read from file
- console.log(JSON.stringify(object));
+ const object = await read(options);
+ console.log(JSON.stringify(object)); // Print write success message.
} catch (err) {
console.error(err.stack);
}
@@ -43,9 +53,11 @@ try {
```javascript
import { write } from 'jy-transform';
+const options = { dest: 'foo/bar.yaml' }; // Here: write to file.
+
try {
- const msg = await write(object, { dest: 'foo/bar.yaml' });
- console.log(msg);
+ const msg = await write(object, options);
+ console.log(msg); // Print write success message.
} catch (err) {
console.error(err.stack);
}
@@ -54,7 +66,7 @@ try {
## Why This Module?
After struggling with some huge YAML file and accidentally
-occurring wrong indentions which results in an annoying investigation hell,
+occurring wrong indentations which results in an annoying investigation hell,
I decided to get rid of the YAML file and therefore, create a module which
should be aimed as the swiss army knife for transforming YAML, JS and JSON
types into each other format.
@@ -190,7 +202,7 @@ Usage:
Options:
-o, --origin [STRING] The origin type of INPUT-FILE: [ js | json | yaml ]. (Default is if not given, the type is tried to be inferred from the extension of source path, else it is 'yaml')
-t, --target [STRING] The target type of OUTPUT-FILE: [ js | json | yaml ]. (Default is if not given, the type is tried to be inferred from the extension of destination path, else it is 'js')
- -i, --indent [NUMBER] The indention for pretty-print: 1 - 8. (Default is 4)
+ -i, --indent [NUMBER] The indentation for pretty-print: 1 - 8. (Default is 4)
-f, --force Force overwriting of existing output files on write phase. When files are not overwritten (which is default),
then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in
case of foo.yaml it would be foo(1).yaml.
@@ -223,7 +235,7 @@ The OPTIONS are more formally defined in the following table:
| --- | --- | --- | --- | --- | --- |
| `-o` | `--origin` | string of: [ _js_ | _json_ | _yaml_ ] | The transformation origin type. | if not given, the type is tried to be inferred from the extension of source path, else it is _yaml_ | no |
| `-t` | `--target` | string of: [ _js_ | _json_ | _yaml_ ] | The transformation target type. | if not given, the type is tried to be inferred from the extension of destination path, else it is _js_ | no |
-| `-i` | `--indent` | integer [ 1 - 8 ] | The code indention used in destination files. | 2 | no |
+| `-i` | `--indent` | integer [ 1 - 8 ] | The code indentation used in destination files. | 2 | no |
| `-f` | `--force` | n/a | Force overwriting of existing output files on write phase. When files are not overwritten (which is default), then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in case of _foo.yaml_ it would be _foo(1).yaml_. | _false_ | no |
| `-m` | `--imports` | string | Define a 'module.exports[.identifier] = ' identifier (to read from JS _source_ file only, must be a valid JS identifier!) | _undefined_ | no |
| `-x` | `--exports` | string | Define a 'module.exports[.identifier] = ' identifier (for usage in JS _destination_ file only, must be a valid JS identifier!) | _undefined_ | no |
@@ -233,7 +245,7 @@ The OPTIONS are more formally defined in the following table:
| `-h` | `--help` | n/a | Display help and usage details. | n/a | no |
-**NOTE:** an invalid indention setting (1 > `-i`, `--indent` > 8) does not raise an error but a default of 4 SPACEs is applied instead.
+**NOTE:** an invalid indentation setting (1 > `-i`, `--indent` > 8) does not raise an error but a default of 4 SPACEs is applied instead.
#### Examples
@@ -398,7 +410,7 @@ By default this feature is not enabled to prevent you from accidentally
overwriting your input source or already generated targets.
But let's say we want to overwrite the original source now because you want
-to change the indention from 2 to 4 SPACEs, then we can do this as follows:
+to change the indentation from 2 to 4 SPACEs, then we can do this as follows:
```
$ jyt foo.js -f
```
@@ -468,7 +480,7 @@ The `options` object has to follow this key-values tables:
| Option | Type | Description | Default | Required |
| --- | --- | --- | --- | --- |
| `dest` | [ _String_ | _Stream.Writable_ | _Object_ ] | The destination information object: `String` is used as file path, `Stream.Writable` writes a stringified source and `object` is used for direct JS object assignment of the (stringified or JS object) source. If a string is set as file path then the output and if input and output file path are the same, then the file overwriting is handled depending on the `force` value! | - | yes |
-| `indent` | _Number_ | The indention in files. | 2 | no |
+| `indent` | _Number_ | The indentation in files. | 2 | no |
| `force` | _Boolean_ | Force overwriting of existing output files on write phase. When files are not overwritten, then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in case of _foo.yaml_ it would be _foo(1).yaml_. | _false_ | no |
| `imports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (to read from JS _source_ only, must be a valid JS identifier!) | _undefined_ | no |
| `exports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (for usage in JS _destination_ only, must be a valid JS identifier!) | _undefined_ | no |
diff --git a/src/cli.js b/src/cli.js
index 4459d74..48a7399 100755
--- a/src/cli.js
+++ b/src/cli.js
@@ -49,7 +49,7 @@ const packagePath = path.join(__dirname, '../package.json');
* Array}}
* @private
*/
-const options = {
+const cliOptionsSchema = {
origin: ['o', 'The origin type of INPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML
+ ' ]', 'string', ORIGIN_DESCRIPTION],
target: ['t', 'The target type of OUTPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML
@@ -87,7 +87,7 @@ function error(err) {
*
* @param {Array} args - The first mandatory argument is the input file (`args[0]`), the second (optional)
* argument is the output file (`args[1]`).
- * @param {module:jy-transform:type-definitions~TransformerOptions} cliOptions - The options provided via CLI.
+ * @param {module:jy-transform:type-definitions~TransformOptions} cliOptions - The options provided via CLI.
* @private
*/
function main(args, cliOptions) {
@@ -117,9 +117,7 @@ function main(args, cliOptions) {
cli.debug('Passed options:\n' + JSON.stringify(cliOptions, null, 4));
- // transform with options
-
- return transform(cliOptions)
+ transform(cliOptions)
.then(cli.info)
.catch(error);
}
@@ -131,5 +129,5 @@ cli.width = 120;
cli.setUsage(usage);
cli.setApp(packagePath);
cli.enable('version', 'status', 'timeout');
-cli.parse(options);
+cli.parse(cliOptionsSchema);
cli.main(main);
diff --git a/src/reader.js b/src/reader.js
index 368114a..da0998d 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -4,9 +4,9 @@ import { Buffer } from 'buffer';
import path from 'path';
import fs from 'fs';
import isStream from 'is-stream';
-import stringify from 'json-stringify-safe';
-import logger from 'cli';
-import { readerOptionsSchema } from './validation/options-schema';
+import stringify from 'json-stringify-safe'; // TODO remove
+import logger from 'cli'; // TODO remove
+import { readOptionsSchema } from './validation/options-schema';
import Joi from './validation/joi-extensions';
import {
UTF8,
@@ -61,7 +61,7 @@ function readFromStream(readable, origin) {
/**
* Reads the data from a given JS or JSON source.
*
- * @param {ReaderOptions} options - Contains the JS/JSON source reference to read from.
+ * @param {ReadOptions} options - Contains the JS/JSON source reference to read from.
* @returns {Promise.} Contains the read JS object.
* @private
*/
@@ -108,7 +108,7 @@ async function readJs(options) {
* *NOTE:* this function does not understand multi-document sources, it throws
* exception on those.
*
- * @param {ReaderOptions} options - Contains the YAML source reference to read from.
+ * @param {ReadOptions} options - Contains the YAML source reference to read from.
* @returns {Promise.} Contains the read JS object.
* @private
*/
@@ -149,7 +149,7 @@ async function readYaml(options) {
/**
* Reads a particular content type from a source provided in the passed `options`.
*
- * @param {ReaderOptions} options - The read options.
+ * @param {ReadOptions} options - The read options.
* @returns {Promise} The result.
* @resolve {string} Resolves with JS object result.
* @reject {ValidationError} If any `options` validation occurs.
@@ -181,13 +181,13 @@ async function readYaml(options) {
* .catch(console.error);
*/
export async function read(options) {
- const assertedOptions = await Joi.validate(options, readerOptionsSchema);
- switch (assertedOptions.origin) {
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
+ switch (validatedOptions.origin) {
case TYPE_JS:
case TYPE_JSON:
- return readJs(assertedOptions);
+ return readJs(validatedOptions);
default:
- return readYaml(assertedOptions);
+ return readYaml(validatedOptions);
}
}
diff --git a/src/transformer.js b/src/transformer.js
index 663a81c..2efcfac 100644
--- a/src/transformer.js
+++ b/src/transformer.js
@@ -1,10 +1,8 @@
-import logger from 'cli';
-import path from 'path';
-import fs from 'fs';
-import isStream from 'is-stream';
+import logger from 'cli'; // TODO remove
+import Joi from './validation/joi-extensions';
import { read } from './reader';
import { write } from './writer';
-import { EXT_TO_TYPE_MAP } from './constants';
+import { transformOptionsSchema } from './validation/options-schema';
/**
* @module jy-transform:transformer
@@ -13,104 +11,15 @@ import { EXT_TO_TYPE_MAP } from './constants';
*/
/**
- * Applies the `middleware` function to `object` if is passed.
- *
- * @param {Object} object - The object to alter by passed `middleware` function.
- * @param {Function} [middleware] - The function to alter `object`.
- * @returns {Object} The passed `object` which could be altered by optional `middleware` function.
- * @private
- */
-const callMiddlewareIfExists = async (object, middleware) => {
- if (middleware !== undefined && typeof middleware !== 'function') {
- throw new TypeError('The provided middleware is not a Function type');
- }
- if (!middleware) {
- return object;
- }
- return middleware(object);
-};
-
-/**
- * Turns the destination file name into a name containing a consecutive
- * number if it exists. It iterates over the files until it finds a file
- * name which does not exist.
- *
- * @param {string} dest - The destination file.
- * @returns {string} - A consecutive file name or the original one if
- * `dest` file does not exist.
- * @private
- */
-function getConsecutiveDestName(dest) {
- let tmpDest = dest;
- let i = 0;
- const destDirName = path.dirname(tmpDest);
- const ext = path.extname(tmpDest);
- const basename = path.basename(tmpDest, ext);
- while (fs.existsSync(tmpDest)) {
- tmpDest = path.join(destDirName, basename + '(' + (i += 1) + ')' + ext);
- }
- return tmpDest;
-}
-
-/**
- * Checks if passed `object` is a file stream instance.
- *
- * @param {*} object - The object to check.
- * @returns {boolean} A `true` if passed `object` is a file stream instance, else `false`.
- * @private
- */
-function isFileStream(object) {
- return isStream(object) && object.path;
-}
-
-/**
- * Returns the passes `dest` value or an adapted destination path (the latter if `target` is defined an differs from
- * destinations path extension).
- *
- * @param {string} dest - The destination path.
- * @param {string} [target] - The target file type of destination.
- * @returns {string} The `dest` value or an adapted destination path.
- * @private
- */
-function adaptTargetPathType(dest, target) {
- if (target) {
- const tmpDest = dest;
- const destDirName = path.dirname(tmpDest);
- const ext = path.extname(tmpDest);
- const basename = path.basename(tmpDest, ext);
- let destType = ext;
- if (ext.charAt(0) === '.') {
- destType = ext.substr(1);
- }
- if (EXT_TO_TYPE_MAP[destType] !== target) {
- destType = target;
- }
- return path.join(destDirName, basename + '.' + destType);
- }
- return dest;
-}
-
-// ////////////////////////////////////////////////////////////////////////////
-// PUBLIC API
-// ////////////////////////////////////////////////////////////////////////////
-
-/**
- * The entry method for all transformation accepting a configuration object and
+ * The entry method for all transformations accepting a configuration object and
* an (optional) middleware function. It executes the transformation logic.
*
* 1. Input (read)
* 2. Transform [ + Middleware]
* 3. Output (write).
*
- * @param {TransformerOptions} options - The configuration for a transformation.
- * @param {Function} [middleware] - This middleware Promise can be used to
- * intercept the JSON object for altering the passed JSON, the function signature is:
- * ```
- * async function(object)
- * ```
- *
- * **NOTE:** the Promise has to return the processed JS object.
- * @returns {Promise} The result.
+ * @param {TransformOptions} options - The configuration for a transformation.
+ * @returns {Promise} The transformation result.
* @resolve {string} With the transformation result as message (e.g. to be logged by caller).
* @reject {TypeError} Will throw this error when the passed `middleware` is not type of `Function`.
* @reject {ValidationError} If any `options` validation occurs.
@@ -118,16 +27,19 @@ function adaptTargetPathType(dest, target) {
* @public
* @example
* import { transform } from 'jy-transform';
- * const options = {...};
- *
- * const middleware = async (object) {
- * object.myproperty = 'new value';
- * return object;
+ * const options = {
+ * src: 'foo/bar.yaml', // From YAML file...
+ * transform: async (object) => { // ...with exchanging value...
+ * object.foo = 'new value';
+ * return object;
+ * },
+ * target: 'foo/bar.json', // ...to a new JSON file.
+ * indent: 4,
* };
*
* // ---- Promise style:
*
- * transform(options, middleware)
+ * transform(options)
* .then(console.log)
* .catch(console.error);
*
@@ -135,29 +47,25 @@ function adaptTargetPathType(dest, target) {
* // ---- async/await style:
*
* try {
- * const msg = await transform(options, middleware);
+ * const msg = await transform(options);
* console.log(msg);
* } catch (err) {
* console.error(err.stack);
* };
*/
-export async function transform(options, middleware) {
+export async function transform(options) {
// logger.debug('transform'); TODO remove
- let object = await read(options);
- object = await callMiddlewareIfExists(object, middleware);
+ const validatedOptions = await Joi.validate(options, transformOptionsSchema);
- // Here we have to check the options.dest, if not set we allow to use the source (string as
- // file path or File Writable with path) to be used as destination (and even allow to overwrite)!
- if (!options.dest && (typeof options.src === 'string' || isFileStream(options.src))) {
- if (options.force) {
- // Overwrite the source if target is set and does not differ!
- options.dest = adaptTargetPathType((options.src.path || options.src), options.target);
- } else {
- options.dest = getConsecutiveDestName(adaptTargetPathType((options.src.path || options.src), options.target));
- }
- }
+ console.log('Passed transform options:\n' + JSON.stringify(validatedOptions, null, 4)); // TODO remove
- return write(object, options);
+ let object = await read(validatedOptions);
+ object = await validatedOptions.transform(object);
+
+ if (options.dest) {
+ validatedOptions.dest = options.dest; // Do not loose ref to original object!
+ }
+ return write(object, validatedOptions);
}
export default {
diff --git a/src/type-definitions.js b/src/type-definitions.js
index 5f58538..755a398 100644
--- a/src/type-definitions.js
+++ b/src/type-definitions.js
@@ -48,19 +48,19 @@
/**
* The configuration properties provided to the `read` function.
- * @typedef {object} ReaderOptions
- * @property {(string|Stream.Readable|object)} src - The source (if `string` type is treated as a file path).
- * @property {string} [origin=yaml] - The origin type.
+ * @typedef {object} ReadOptions
+ * @property {(string|Stream.Readable|object)} src - The source (if `string` type it is treated as a file path).
+ * @property {string} [origin=yaml] - The source origin type.
* @property {string} [imports=undefined] - The exports name for reading from JS source files or objects only.
* @public
*/
/**
- * The writer configuration properties provided to the `write` function.
- * @typedef {object} WriterOptions
- * @property {(string|Stream.Writable|object)} dest - The destination (if `string` type is treated as a file path).
- * @property {string} [target=js] - The target type.
- * @property {number} [indent=2] - The indention value for pretty-print of output.
+ * The configuration properties provided to the `write` function.
+ * @typedef {object} WriteOptions
+ * @property {(string|Stream.Writable|object)} dest - The destination (if `string` type it is treated as a file path).
+ * @property {string} [target=js] - The destination target type.
+ * @property {number} [indent=2] - The indentation value for pretty-print of output.
* @property {string} [exports=undefined] - The exports name for usage in JS destination files only.
* @property {string} [force=false] - Force overwriting of existing output files on write phase.
* @public
@@ -68,15 +68,28 @@
/**
* The configuration properties provided to the `transform` function.
- * @typedef {object} TransformerOptions
- * @property {(string|Stream.Readable|object)} src - The source (if `string` type is treated as a file path).
- * @property {string} [origin=yaml] - The origin type.
- * @property {string} [imports=undefined] - The exports name for reading from JS source files
- * or objects only.
- * @property {(string|Stream.Writable|object)} [dest] - The destination (if `string` type is treated as a file path).
- * @property {string} [target=js] - The target type.
- * @property {number} [indent=2] - The indention value for pretty-print of output.
- * @property {string} [exports=undefined] - The exports name for usage in JS destination files only.
+ * @typedef {object} TransformOptions
+ * @property {(string|Stream.Readable|object)} src - The _read_ source (if `string` type it is treated as a file
+ * path).
+ * @property {string} [origin=yaml] - The _read_ source origin type.
+ * @property {string} [imports=undefined] - The _read_ exports name for reading from JS source files or
+ * objects only.
+ * @property {Function} [transform] - The option is a _transformation_ function with the following
+ * signature:
+ *
+ * ```
+ * [async|Promise] function(object)
+ * ```
+ * @property {(string|Stream.Writable|object)} [dest] - The _write_ destination (if `string` type it is treated as a
+ * file path). This property could be optional in case we infer a
+ * value from `src` which is then either a string or a file stream
+ * where can get the file path from. If this detection process
+ * cannot be fulfilled then the property is `undefined` and the
+ * transform process will fail with a `ValidationError` on write
+ * phase.
+ * @property {string} [target=js] - The _write_ target type.
+ * @property {number} [indent=2] - The _write_ indentation value for pretty-print of output.
+ * @property {string} [exports=undefined] - The _write_ exports name for usage in JS destination files only.
* @property {string} [force=false] - Force overwriting of existing output files on write phase.
* @public
*/
diff --git a/src/validation/options-schema-helper.js b/src/validation/options-schema-helper.js
index 04bde7f..30be3da 100644
--- a/src/validation/options-schema-helper.js
+++ b/src/validation/options-schema-helper.js
@@ -76,7 +76,63 @@ export const inferTargetDefault = (context) => {
return type;
};
+/**
+ * Checks if passed `object` is a file stream instance.
+ *
+ * @param {*} object - The object to check.
+ * @returns {boolean} A `true` if passed `object` is a file stream instance, else `false`.
+ * @private
+ */
+export const isFileStream = (object) => {
+ return isStream(object) && object.path;
+};
+
+/**
+ * Returns the passes `dest` value or an adapted destination path (the latter if `target` is defined an differs from
+ * destinations path extension).
+ *
+ * @param {string} dest - The destination path.
+ * @param {string} [target] - The target file type of destination.
+ * @returns {string} The `dest` value or an adapted destination path.
+ * @private
+ */
+export const adaptTargetPathType = (dest, target) => {
+ if (target) {
+ const tmpDest = dest;
+ const destDirName = path.dirname(tmpDest);
+ const ext = path.extname(tmpDest);
+ const basename = path.basename(tmpDest, ext);
+ let destType = ext;
+ if (ext.charAt(0) === '.') {
+ destType = ext.substr(1);
+ }
+ if (EXT_TO_TYPE_MAP[destType] !== target) {
+ destType = target;
+ }
+ return path.join(destDirName, basename + '.' + destType);
+ }
+ return dest;
+};
+
+/**
+ * This function is used to infer a _default_ value in case `options.dest` is not defined.
+ * Checks if `context.src` is either a string or a file stream where can get the file path from.
+ * If this detection process cannot be fulfilled then the function returns `undefined`.
+ *
+ * @param {Object} context - The validation context.
+ * @returns {string|undefined} The adapted `dest` path if possible, or `undefined`.
+ */
+export const inferDestDefaultFromSrc = (context) => {
+ if (typeof context.src === 'string' || isFileStream(context.src)) {
+ return adaptTargetPathType((context.src.path || context.src), context.target);
+ }
+ return undefined; // TODO how to handle this??? Throw Error?
+};
+
export default {
+ isFileStream,
+ adaptTargetPathType,
inferOriginDefault,
inferTargetDefault,
+ inferDestDefaultFromSrc,
};
diff --git a/src/validation/options-schema.js b/src/validation/options-schema.js
index 457177b..778d907 100644
--- a/src/validation/options-schema.js
+++ b/src/validation/options-schema.js
@@ -1,6 +1,7 @@
import { Stream } from 'stream';
import Joi from './joi-extensions';
import {
+ inferDestDefaultFromSrc,
inferOriginDefault,
inferTargetDefault,
} from './options-schema-helper';
@@ -24,12 +25,12 @@ import {
*/
/**
- * The prepared {@link external:joi.JoiSchema} for validating the {@link Reader} options.
+ * The prepared {@link external:joi.JoiSchema} for validating the {@link ReadOptions}.
* @type {JoiSchema}
* @constant
* @private
*/
-export const readerOptionsSchema = Joi.object().keys({
+export const readOptionsSchema = Joi.object().keys({
src: Joi
.alternatives().try(
Joi.string()
@@ -47,15 +48,14 @@ export const readerOptionsSchema = Joi.object().keys({
then: Joi
.string()
.valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
- .default(inferOriginDefault,
- 'tried origin default inferred from src type if not set (Stream.Readable)'),
+ .default(inferOriginDefault, 'try origin resolution from src type if not set (Stream.Readable)'),
otherwise: Joi
.when('src', {
is: Joi.string(),
then: Joi
.string()
.valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
- .default(inferOriginDefault, 'origin resolving from src type if latter not set (String)'),
+ .default(inferOriginDefault, 'try origin resolution from src type if latter not set (String)'),
otherwise: Joi // else could only be JS Object
.string()
.valid(TYPE_JS)
@@ -67,16 +67,17 @@ export const readerOptionsSchema = Joi.object().keys({
.string()
.validEs6Identifier()
.description('The name of property to import while reading a JS input source.'),
-}).unknown()
- .required();
+}).default()
+ .required()
+ .unknown();
/**
- * The prepared {@link external:joi.JoiSchema} for validating the {@link Writer} options.
+ * The prepared {@link external:joi.JoiSchema} for validating the {@link WriteOptions}.
* @type {JoiSchema}
* @constant
* @private
*/
-export const writerOptionsSchema = Joi.object().keys({
+export const writeOptionsSchema = Joi.object().keys({
dest: Joi
.alternatives().try(
Joi.string()
@@ -87,6 +88,78 @@ export const writerOptionsSchema = Joi.object().keys({
)
.required()
.description('The output destination (if string type is treated as a file path).'),
+ target: Joi
+ .when('dest', {
+ is: Joi.object().type(Stream.Writable),
+ then: Joi
+ .string()
+ .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
+ .default(inferTargetDefault, 'try target resolution from dest type if not set (Stream.Writable)'),
+ otherwise: Joi
+ .when('dest', {
+ is: Joi.string(),
+ then: Joi
+ .string()
+ .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
+ .default(inferTargetDefault, 'try target resolution from dest type if latter not set (String)'),
+ otherwise: Joi // check
+ .string()
+ .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
+ .default(TYPE_JS),
+ }),
+ })
+ .description('The target type of output.'),
+ exports: Joi
+ .string()
+ .validEs6Identifier()
+ .description('The name of property to export while writing a JS object to a JS output destination.'),
+ indent: Joi
+ .when('target', {
+ is: TYPE_YAML,
+ then: Joi
+ .number()
+ .integer()
+ .min(MIN_YAML_INDENT) // Must be 2 for YAML type!
+ .max(MAX_INDENT)
+ .default(DEFAULT_INDENT),
+ otherwise: Joi
+ .number()
+ .integer()
+ .min(MIN_INDENT)
+ .max(MAX_INDENT)
+ .default(DEFAULT_INDENT),
+ })
+ .description('The indention value for pretty-print of output.'),
+ force: Joi
+ .boolean()
+ .default(DEFAULT_FORCE_FILE_OVERWRITE)
+ .description('Force overwriting of existing output files on write phase.'),
+}).default()
+ .required()
+ .unknown();
+
+/**
+ * The prepared {@link external:joi.JoiSchema} for validating the {@link TransformOptions}.
+ * @type {JoiSchema}
+ * @constant
+ * @private
+ */
+export const transformOptionsSchema = readOptionsSchema.concat(Joi.object().keys({
+ transform: Joi
+ .func()
+ .arity(1)
+ .default(object => object)
+ .description('The transformation function to alter a read object.'),
+ dest: Joi
+ .alternatives().try(
+ Joi.string()
+ .min(1)
+ .label('dest - OUTPUT-FILE'),
+ Joi.object().type(Stream.Writable),
+ Joi.object().type(Object),
+ )
+ .default(inferDestDefaultFromSrc, 'try dest resolution from src if not set') // TODO message!?
+ .description('The output destination (if string type is treated as a file path).'),
target: Joi
.when('dest', {
is: Joi.object().type(Stream.Writable),
@@ -101,7 +174,7 @@ export const writerOptionsSchema = Joi.object().keys({
then: Joi
.string()
.valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
- .default(inferTargetDefault, 'try target resolving from dest type if latter not set (String)'),
+ .default(inferTargetDefault, 'try target resolution from dest type if latter not set (String)'),
otherwise: Joi // check
.string()
.valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
@@ -134,10 +207,12 @@ export const writerOptionsSchema = Joi.object().keys({
.boolean()
.default(DEFAULT_FORCE_FILE_OVERWRITE)
.description('Force overwriting of existing output files on write phase.'),
-}).unknown()
- .required();
+}).default()
+ .required()
+);
export default {
- readerOptionsSchema,
- writerOptionsSchema,
+ readOptionsSchema,
+ writeOptionsSchema,
+ transformOptionsSchema,
};
diff --git a/src/writer.js b/src/writer.js
index 51285c3..595c267 100644
--- a/src/writer.js
+++ b/src/writer.js
@@ -1,4 +1,4 @@
-import logger from 'cli';
+import logger from 'cli'; // TODO remove
import fs from 'fs';
import isStream from 'is-stream';
import jsYaml from 'js-yaml';
@@ -15,7 +15,7 @@ import {
UTF8
} from './constants';
import Joi from './validation/joi-extensions';
-import { writerOptionsSchema } from './validation/options-schema';
+import { writeOptionsSchema } from './validation/options-schema';
/**
* @module jy-transform:writer
@@ -85,8 +85,7 @@ async function serializeJsToJsonString(object, indent) {
* name which does not exist.
*
* @param {string} dest - The destination file.
- * @returns {string} - A consecutive file name or the original one if
- * `dest` file does not exist.
+ * @returns {string} - A consecutive file name or the original one if `dest` file does not exist.
* @private
*/
function getConsecutiveDestName(dest) {
@@ -184,8 +183,8 @@ function writeToStream(object, dest, target) {
/**
* Writes a JS object to a YAML destination.
*
- * @param {Object} object - The JS object to write into YAML destination.
- * @param {WriterOptions} options - The write destination and indention.
+ * @param {Object} object - The JS object to write into YAML destination.
+ * @param {WriteOptions} options - The write destination and indention.
* @see {@link MIN_INDENT}
* @see {@link DEFAULT_INDENT}
* @see {@link MAX_INDENT}
@@ -215,8 +214,8 @@ async function writeYaml(object, options) {
/**
* Writes a JS object to a JSON destination.
*
- * @param {Object} object - The JS object to write into JSON destination.
- * @param {WriterOptions} options - The write destination and indention.
+ * @param {Object} object - The JS object to write into JSON destination.
+ * @param {WriteOptions} options - The write destination and indention.
* @see {@link MIN_INDENT}
* @see {@link DEFAULT_INDENT}
* @see {@link MAX_INDENT}
@@ -238,8 +237,8 @@ async function writeJson(object, options) {
/**
* Writes a JS object to a JS destination. The object is prefixed by `module.exports[.${options.exports}] = `.
*
- * @param {Object} object - The JSON to write into JS destination.
- * @param {WriterOptions} options - The write destination and indention.
+ * @param {Object} object - The JSON to write into JS destination.
+ * @param {WriteOptions} options - The write destination and indention.
* @see {@link MIN_INDENT}
* @see {@link DEFAULT_INDENT}
* @see {@link MAX_INDENT}
@@ -268,8 +267,8 @@ async function writeJs(object, options) {
/**
* Writes the passe JS object to a particular destination described by the passed `options`.
*
- * @param {Object} object - The JS source object to write.
- * @param {WriterOptions} options - The write options.
+ * @param {Object} object - The JS source object to write.
+ * @param {WriteOptions} options - The write options.
* @returns {Promise} The result.
* @resolve {string} With the write success message.
* @reject {Error} If any write error occurs.
@@ -316,12 +315,12 @@ async function writeJs(object, options) {
* .catch(console.error);
*/
export async function write(object, options) {
- console.log('OPTIONS ON WRITE ===> ' + JSON.stringify(options, null, 4))
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ // console.log('OPTIONS ON WRITE ===> ' + JSON.stringify(options, null, 4)) // TODO remove
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
// HINT: we have to use the original options object because the caller must not loose the reference to options.dest,
// so we copy everything here except the assertedOptions.dest (joi does not return the original reference)!
- Object.assign(options, { target: validatedOptions.target }, { exports: validatedOptions.exports },
+ Object.assign(options, { target: validatedOptions.target }, { exports: validatedOptions.exports }, // TODO does this work without full copy?
{ indent: validatedOptions.indent }, { force: validatedOptions.force });
validatedOptions.dest = options.dest;
switch (validatedOptions.target) {
diff --git a/test/unit/test-transformer.js b/test/unit/test-transformer.js
index d7d5bd8..5edb68f 100644
--- a/test/unit/test-transformer.js
+++ b/test/unit/test-transformer.js
@@ -50,21 +50,20 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
/**
* Transformation middleware changing value for `foo` property.
*
- * @param {Object} json - To transform.
+ * @param {Object} object - To transform.
*/
- const middlewareFunc = async (json) => {
- json.foo = EXPECTED_VALUE;
- return json;
+ const transformFunc = async (object) => {
+ object.foo = EXPECTED_VALUE;
+ return object;
};
/**
* Helper method which asserts the successful transformation.
*
* @param {Object} options - The transformation options.
- * @param {Function} middleware - The transformation middleware.
*/
- function assertTransformSuccess(options, middleware) {
- return transform(options, middleware)
+ function assertTransformSuccess(options) {
+ return transform(options)
.then((msg) => {
logger.info(msg);
const stats = fsExtra.statSync(options.dest);
@@ -79,11 +78,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
* Helper method which asserts the successful transformation.
*
* @param {Object} options - The transformation options.
- * @param {Function} middleware - The transformation middleware.
*/
- async function assertYamlTransformSuccess(options, middleware) {
+ async function assertYamlTransformSuccess(options) {
expect.assertions(3);
- const msg = await transform(options, middleware);
+ const msg = await transform(options);
logger.info(msg);
expect(msg).toEqual(expect.any(String));
const stats = fsExtra.statSync(options.dest);
@@ -94,9 +92,20 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
}
describe('Testing transform with middleware', () => {
- it('should throw TypeError if middleware passed is not a function type', async () => {
+ it('should throw ValidationError if middleware passed is not a function type', async () => {
expect.assertions(1);
- await expect(transform({ src: {}, dest: {} }, 'not a function')).rejects.toBeInstanceOf(TypeError);
+ await expect(transform({
+ src: {},
+ transform: 'not a function',
+ dest: {},
+ })).rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
+ });
+
+ it('should throw ValidationError if options.dest is not set and cannot be resolved from options.src type', async () => {
+ expect.assertions(1);
+ await expect(transform({
+ src: {}, // we cannot infer destination from this type!
+ })).rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
});
it('should not fail if middleware passed is returning a Promise', () => {
@@ -104,8 +113,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
const returningPromise = async (object) => {
return object;
};
- return expect(transform({ src: {}, dest: {} }, returningPromise))
- .resolves.toBe('Writing JS to options.dest successful.');
+ return expect(transform({
+ src: {},
+ transform: returningPromise,
+ dest: {},
+ })).resolves.toBe('Writing JS to options.dest successful.');
});
it('should not fail if middleware passed is not returning a Promise', () => {
@@ -113,8 +125,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
const notReturningPromise = (object) => {
return object;
};
- return expect(transform({ src: {}, dest: {} }, notReturningPromise))
- .resolves.toBe('Writing JS to options.dest successful.');
+ return expect(transform({
+ src: {},
+ transform: notReturningPromise,
+ dest: {},
+ })).resolves.toBe('Writing JS to options.dest successful.');
});
});
@@ -132,8 +147,9 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const msg = await transform({
src: path.resolve(TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml'),
+ transform: transformFunc,
dest: path.resolve(TRANSFORMER_TEST_BASE_DIR + '/test-data.js'),
- }, middlewareFunc);
+ });
logger.info(msg);
const stats = fs.statSync(DEST);
expect(stats.isFile()).toBeTruthy();
@@ -151,9 +167,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options, middlewareFunc);
+ await assertTransformSuccess(options);
});
});
@@ -165,9 +182,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options, middlewareFunc);
+ await assertTransformSuccess(options);
});
});
@@ -179,9 +197,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options, middlewareFunc);
+ await assertTransformSuccess(options);
});
});
@@ -193,9 +212,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options, middlewareFunc);
+ await assertTransformSuccess(options);
});
});
@@ -208,10 +228,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- transform(options, middlewareFunc)
+ transform(options)
.then((msg) => {
logger.info(msg);
const stats = fsExtra.statSync(options.dest);
@@ -245,10 +266,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- transform(options, middlewareFunc)
+ transform(options)
.then((msg) => {
logger.info(msg);
const stats = fsExtra.statSync(options.dest);
@@ -282,9 +304,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options, middlewareFunc);
+ await assertTransformSuccess(options);
});
});
@@ -296,9 +319,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertYamlTransformSuccess(options, middlewareFunc);
+ await assertYamlTransformSuccess(options);
});
});
@@ -310,9 +334,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
expect.assertions(2);
const options = {
src: path.resolve(SRC),
+ transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options, middlewareFunc);
+ await assertTransformSuccess(options);
});
});
});
diff --git a/test/unit/validation/test-options-schema.js b/test/unit/validation/test-options-schema.js
index 9782ab7..0044b70 100644
--- a/test/unit/validation/test-options-schema.js
+++ b/test/unit/validation/test-options-schema.js
@@ -16,8 +16,8 @@ import {
MAX_INDENT,
} from '../../../src/constants';
import {
- readerOptionsSchema,
- writerOptionsSchema,
+ readOptionsSchema,
+ writeOptionsSchema,
} from '../../../src/validation/options-schema';
import Joi from '../../../src/validation/joi-extensions';
@@ -30,8 +30,8 @@ import Joi from '../../../src/validation/joi-extensions';
/**
* Expect a `ValidationError` for a given options function.
*
- * @param {ReaderOptions|WriterOptions} invalidOptions - The options which potentially produce the error.
- * @param {Schema} schema - The validation schema.
+ * @param {ReadOptions|WriteOptions} invalidOptions - The options which potentially produce the error.
+ * @param {Schema} schema - The validation schema.
* @private
*/
function expectOptionsValidationError(invalidOptions, schema) {
@@ -45,8 +45,8 @@ function expectOptionsValidationError(invalidOptions, schema) {
/**
* Expect a validation success for a given options.
*
- * @param {ReaderOptions|WriterOptions} validOptions - The options which should be correct.
- * @param {Schema} schema - The validation schema.
+ * @param {ReadOptions|WriteOptions} validOptions - The options which should be correct.
+ * @param {Schema} schema - The validation schema.
* @private
*/
function expectOptionsValidationSuccess(validOptions, schema) {
@@ -55,13 +55,13 @@ function expectOptionsValidationSuccess(validOptions, schema) {
}
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
- describe('Testing readerOptionsSchema validation', () => {
+ describe('Testing readOptionsSchema validation', () => {
it('should reject when options is missing (null)', () =>
- expectOptionsValidationError(null, readerOptionsSchema)
+ expectOptionsValidationError(null, readOptionsSchema)
);
it('should reject when options is missing (undefined)', () =>
- expectOptionsValidationError(undefined, readerOptionsSchema)
+ expectOptionsValidationError(undefined, readOptionsSchema)
);
it('should set all defaults', async () => {
@@ -70,7 +70,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.yaml',
dest: './test/tmp/test-data.js',
};
- const validatedOptions = await Joi.validate(options, readerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
expect(validatedOptions.origin).toBe(DEFAULT_ORIGIN);
expect(validatedOptions.imports).toBe(DEFAULT_JS_IMPORTS_IDENTIFIER);
});
@@ -80,7 +80,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
src: './test/data/test-data.js', // non default type
};
- const validatedOptions = await Joi.validate(options, readerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
expect(validatedOptions.origin).toBe(TYPE_JS);
});
@@ -90,7 +90,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
origin: TYPE_JS,
src: new Stream.Readable(), // no inference possible
};
- const validatedOptions = await Joi.validate(options, readerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
expect(validatedOptions.origin).toBe(TYPE_JS);
});
@@ -100,7 +100,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: {},
dest: 'some-file',
};
- const validatedOptions = await Joi.validate(options, readerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
expect(validatedOptions.origin).toBe(TYPE_JS);
});
});
@@ -110,18 +110,18 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
expectOptionsValidationError({
src: './test',
dest: 'some-file',
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
it('should reject when options.src is undefined', () =>
- expectOptionsValidationError({ dest: 'some-file' }, readerOptionsSchema)
+ expectOptionsValidationError({ dest: 'some-file' }, readOptionsSchema)
);
it('should reject when options.src is null', () =>
expectOptionsValidationError({
src: null,
dest: 'some-file',
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
it('should resolve to default origin ' + DEFAULT_ORIGIN + ' when options.src is Stream.Readable and ' +
@@ -132,7 +132,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
dest: new Stream.Writable(),
target: TYPE_YAML,
};
- const validatedOptions = await Joi.validate(options, readerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
expect(validatedOptions.origin).toBe(DEFAULT_ORIGIN);
expect(validatedOptions.target).toBe(TYPE_YAML);
});
@@ -144,7 +144,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data',
dest: 'some-file'
};
- const validatedOptions = await Joi.validate(options, readerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, readOptionsSchema);
expect(validatedOptions.origin).toBe(DEFAULT_ORIGIN);
});
@@ -153,7 +153,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data',
dest: 'some-file',
origin: TYPE_JS,
- }, readerOptionsSchema);
+ }, readOptionsSchema);
});
it('should resolve when options.origin has valid target ' + TYPE_JSON, () => {
@@ -161,7 +161,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data-json',
dest: 'some-file',
origin: TYPE_JSON,
- }, readerOptionsSchema);
+ }, readOptionsSchema);
});
it('should resolve when options.origin has valid target ' + TYPE_YAML, () => {
@@ -169,7 +169,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data-yaml',
dest: 'some-file',
origin: TYPE_YAML,
- }, readerOptionsSchema);
+ }, readOptionsSchema);
});
it('should reject when options.origin is null', () =>
@@ -177,7 +177,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data-yaml',
dest: 'some-file',
origin: null,
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
it('should reject when options.origin is not allowed value', () =>
@@ -185,7 +185,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data-yaml',
dest: 'some-file',
origin: 'not-allowed',
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
});
@@ -196,7 +196,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
imports: nonStringIdentifier,
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
const invalidIdentifier = '#3/-';
@@ -205,7 +205,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
imports: invalidIdentifier,
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
const validIdentifier = 'bar';
@@ -214,18 +214,18 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
imports: validIdentifier,
- }, readerOptionsSchema)
+ }, readOptionsSchema)
);
});
});
- describe('Testing writerOptionsSchema validation', () => {
+ describe('Testing writeOptionsSchema validation', () => {
it('should reject when options is missing (null)', () =>
- expectOptionsValidationError(null, writerOptionsSchema)
+ expectOptionsValidationError(null, writeOptionsSchema)
);
it('should reject when options is missing (undefined)', () =>
- expectOptionsValidationError(undefined, writerOptionsSchema)
+ expectOptionsValidationError(undefined, writeOptionsSchema)
);
it('should set all defaults', async () => {
@@ -233,7 +233,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
dest: './test/tmp/test-data.js',
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(DEFAULT_TARGET);
expect(validatedOptions.indent).toBe(DEFAULT_INDENT);
expect(validatedOptions.exports).toBe(DEFAULT_JS_EXPORTS_IDENTIFIER);
@@ -245,7 +245,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
dest: 'some-file.yml', // non default type
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(TYPE_YAML);
});
@@ -255,7 +255,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
target: TYPE_YAML,
dest: new Stream.Writable(), // no inference possible
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(TYPE_YAML);
});
@@ -264,20 +264,20 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
dest: {},
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(TYPE_JS);
});
describe('Testing options.dest schema validation', () => {
it('should reject when options.dest is undefined', () =>
- expectOptionsValidationError({ src: './test/data/test-data.js' }, writerOptionsSchema)
+ expectOptionsValidationError({ src: './test/data/test-data.js' }, writeOptionsSchema)
);
it('should reject when options.dest is null', () =>
expectOptionsValidationError({
src: './test/data/test-data.js',
dest: null,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should resolve output when options.dest is Stream.Writable and options.target is set', async () => {
@@ -286,7 +286,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
dest: new Stream.Writable(),
target: TYPE_YAML,
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(TYPE_YAML);
});
@@ -296,7 +296,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
dest: fs.createWriteStream('./test/tmp/test-data.yaml'),
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(TYPE_YAML);
});
@@ -306,7 +306,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
dest: new Stream.Writable(),
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(DEFAULT_TARGET);
});
});
@@ -316,7 +316,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
const options = {
dest: 'some-file'
};
- const validatedOptions = await Joi.validate(options, writerOptionsSchema);
+ const validatedOptions = await Joi.validate(options, writeOptionsSchema);
expect(validatedOptions.target).toBe(DEFAULT_TARGET);
});
@@ -325,7 +325,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
target: TYPE_JS,
- }, writerOptionsSchema);
+ }, writeOptionsSchema);
});
it('should resolve when options.target has valid target ' + TYPE_JSON, () => {
@@ -333,7 +333,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.json',
dest: 'some-file',
target: TYPE_JS,
- }, writerOptionsSchema);
+ }, writeOptionsSchema);
});
it('should resolve when options.target has valid target ' + TYPE_YAML, () => {
@@ -341,7 +341,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.yaml',
dest: 'some-file',
target: TYPE_YAML,
- }, writerOptionsSchema);
+ }, writeOptionsSchema);
});
it('should reject when options.target is null', () =>
@@ -349,7 +349,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
target: null,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should reject when options.target is not allowed value', () =>
@@ -357,7 +357,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
target: 'not-allowed',
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
});
@@ -368,7 +368,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
exports: nonStringIdentifier,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
const invalidIdentifier = '#3/-';
@@ -377,7 +377,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
exports: invalidIdentifier,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
const validIdentifier = 'bar';
@@ -386,7 +386,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
exports: validIdentifier,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
});
@@ -397,7 +397,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
force: notBoolean,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should accept valid value \'false\'', () =>
@@ -405,7 +405,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
force: false,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should accept valid value \'true\'', () =>
@@ -413,7 +413,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
force: true,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
});
@@ -424,7 +424,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
indent: notInteger,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should accept valid \'' + MIN_INDENT + '\'', () =>
@@ -432,7 +432,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
indent: MIN_INDENT,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should accept valid \'' + MAX_INDENT + '\'', () =>
@@ -440,7 +440,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
indent: MAX_INDENT,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should reject < \'' + MIN_INDENT + '\'', () =>
@@ -448,7 +448,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
indent: MIN_INDENT - 1,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
it('should reject > \'' + MAX_INDENT + '\'', () =>
@@ -456,7 +456,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
src: './test/data/test-data.js',
dest: 'some-file',
indent: MAX_INDENT + 1,
- }, writerOptionsSchema)
+ }, writeOptionsSchema)
);
});
});
From 2061abf94eeb0a049e06bb9796b9cb19dddfd8f8 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 13 Jul 2017 01:44:17 +0200
Subject: [PATCH 17/58] More fixes/features and tests 100% except clit tests
---
.eslintignore | 3 +
.jestrc.js | 5 +-
.travis.yml | 1 -
API-PRIVATE.md | 43 +++----
CHANGELOG.md | 2 +-
MAKE.md | 2 +-
Makefile | 4 +-
PACKAGE.md | 2 +-
package.json | 15 ++-
src/reader.js | 30 ++---
src/transformer.js | 5 -
src/validation/options-schema-helper.js | 110 +++++++++---------
src/writer.js | 8 +-
test/unit/test-transformer.js | 13 ++-
.../validation/test-options-schema-helper.js | 102 +++++++++++-----
15 files changed, 182 insertions(+), 163 deletions(-)
diff --git a/.eslintignore b/.eslintignore
index dc14c97..70b454f 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -8,3 +8,6 @@ lib/
index.js
test/data
test/tmp
+
+# TODO reve later when test os done
+test/unit/test-cli.js
diff --git a/.jestrc.js b/.jestrc.js
index c8c231b..639b0dc 100644
--- a/.jestrc.js
+++ b/.jestrc.js
@@ -27,8 +27,8 @@ module.exports = {
// '**/test/unit/test-index.js',
//'**/test/unit/test-reader.js',
// '**/test/unit/test-writer.js',
- //'**/test/unit/validation/test-options-schema.js',
- '**/test/unit/**/*.js',
+ // '**/test/unit/validation/test-options-schema.js',
+ '**/test/unit/**/*.js',
//'**/test/unit/validation/test-options-schema-helper.js',
// '**/test/test-log-wrapper.js',
@@ -37,7 +37,6 @@ module.exports = {
//'/*.js!**/test/functional/util/**',
//'!**/test/*.js',
],
- // testRegex: '\\/test\\/unit\\/.*|\/\\.js?$/',
testEnvironment: 'node',
testPathIgnorePatterns: [
// '/test/data/.*',
diff --git a/.travis.yml b/.travis.yml
index eb52e4b..a3e8ef4 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,6 @@ node_js:
- "7"
- "6"
- "5"
-- "4"
os:
- linux
diff --git a/API-PRIVATE.md b/API-PRIVATE.md
index 413d717..3811e22 100644
--- a/API-PRIVATE.md
+++ b/API-PRIVATE.md
@@ -598,13 +598,28 @@ values for origin and target depending on the `options.src` or `options.dest` va
**See**: [module:validation:options-schema](module:validation:options-schema)
* [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper) : Object ℗
+ * [~inferDestDefaultFromSrc](#module_jy-transform_validation_options-schema-helper..inferDestDefaultFromSrc) ⇒ string \| undefined
* [~inferOriginDefault](#module_jy-transform_validation_options-schema-helper..inferOriginDefault) ⇒ string
* [~inferTargetDefault](#module_jy-transform_validation_options-schema-helper..inferTargetDefault) ⇒ string
- * [~isFileStream](#module_jy-transform_validation_options-schema-helper..isFileStream) ⇒ boolean ℗
- * [~adaptTargetPathType](#module_jy-transform_validation_options-schema-helper..adaptTargetPathType) ⇒ string ℗
- * [~inferDestDefaultFromSrc](#module_jy-transform_validation_options-schema-helper..inferDestDefaultFromSrc) ⇒ string \| undefined
+ * [~isFileStream(object)](#module_jy-transform_validation_options-schema-helper..isFileStream) ⇒ boolean ℗
+ * [~adaptTargetPathType(dest, [target])](#module_jy-transform_validation_options-schema-helper..adaptTargetPathType) ⇒ string ℗
* [~getTypeFromFilePath(pathStr, defaultValue)](#module_jy-transform_validation_options-schema-helper..getTypeFromFilePath) ⇒ string ℗
+
+
+### jy-transform:validation:options-schema-helper~inferDestDefaultFromSrc ⇒ string \| undefined
+This function is used to infer a _default_ value in case `options.dest` is not defined.
+Checks if `context.src` is either a string or a file stream where can get the file path from.
+If this detection process cannot be fulfilled (i.e. we cannot infer from options.src `Object`
+type or a `Readable` type which is not a _file_ stream) then the function returns `undefined`.
+
+**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Returns**: string \| undefined - The adapted `dest` path if possible, or `undefined`.
+
+| Param | Type | Description |
+| --- | --- | --- |
+| context | Object | The validation context. |
+
### jy-transform:validation:options-schema-helper~inferOriginDefault ⇒ string
@@ -633,10 +648,10 @@ Infers the _target_ type value from current validation context.
-### jy-transform:validation:options-schema-helper~isFileStream ⇒ boolean ℗
+### jy-transform:validation:options-schema-helper~isFileStream(object) ⇒ boolean ℗
Checks if passed `object` is a file stream instance.
-**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Kind**: inner method of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
**Returns**: boolean - A `true` if passed `object` is a file stream instance, else `false`.
**Access**: private
@@ -646,11 +661,11 @@ Checks if passed `object` is a file stream instance.
-### jy-transform:validation:options-schema-helper~adaptTargetPathType ⇒ string ℗
+### jy-transform:validation:options-schema-helper~adaptTargetPathType(dest, [target]) ⇒ string ℗
Returns the passes `dest` value or an adapted destination path (the latter if `target` is defined an differs from
destinations path extension).
-**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
+**Kind**: inner method of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
**Returns**: string - The `dest` value or an adapted destination path.
**Access**: private
@@ -659,20 +674,6 @@ destinations path extension).
| dest | string | The destination path. |
| [target] | string | The target file type of destination. |
-
-
-### jy-transform:validation:options-schema-helper~inferDestDefaultFromSrc ⇒ string \| undefined
-This function is used to infer a _default_ value in case `options.dest` is not defined.
-Checks if `context.src` is either a string or a file stream where can get the file path from.
-If this detection process cannot be fulfilled then the function returns `undefined`.
-
-**Kind**: inner constant of [jy-transform:validation:options-schema-helper](#module_jy-transform_validation_options-schema-helper)
-**Returns**: string \| undefined - The adapted `dest` path if possible, or `undefined`.
-
-| Param | Type | Description |
-| --- | --- | --- |
-| context | Object | The validation context. |
-
### jy-transform:validation:options-schema-helper~getTypeFromFilePath(pathStr, defaultValue) ⇒ string ℗
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f96ac71..903fff7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -62,7 +62,7 @@ new interface:
- [[#53](https://github.com/deadratfink/jy-transform/issues/53)] Update supported node versions:
- **CLI & API Backwards Incompatible Change!**
- Add travis build for Node.js v8.x.
- - Remove travis build for Node.js < v4.x.
+ - Remove travis build for Node.js < v5.x.
- [[#52](https://github.com/deadratfink/jy-transform/issues/52)] Leverage modern ES6 features:
- Integrated by [babel](https://babeljs.io/).
- Update of dependencies and amount reduced.
diff --git a/MAKE.md b/MAKE.md
index c5c37a9..a01285e 100644
--- a/MAKE.md
+++ b/MAKE.md
@@ -9,4 +9,4 @@ Target Call | Description | Dependencies
`$ make nsp` | Runs an [Node Security Plattform](https://nodesecurity.io/opensource) check. |
`$ make publish` | Publishes module to NPM registry. | `test readme`
`$ make readme` | Creates all the documentation parts of the project |
-`$ make test` | Runs the test suite, ESLint and a [Node Security Plattform](https://nodesecurity.io/opensource) check. |
+`$ make test` | Runs the test suite, ESLint and a [Node Security Plattform](https://nodesecurity.io/opensource) check. | `build`
diff --git a/Makefile b/Makefile
index b0444ee..92e9717 100644
--- a/Makefile
+++ b/Makefile
@@ -16,7 +16,7 @@ clean: ## Removes generated files in folders ./node_modules, ./lib and ./coverag
rm -rf node_modules
rm -rf coverage
-test: ## Runs the test suite, ESLint and a [Node Security Plattform](https://nodesecurity.io/opensource) check.
+test: build ## Runs the test suite, ESLint and a [Node Security Plattform](https://nodesecurity.io/opensource) check.
@printf "Running test suite, ESLint and NSP...\n"
npm test
npm run eslint
@@ -26,8 +26,6 @@ nsp: ## Runs an [Node Security Plattform](https://nodesecurity.io/opensource) ch
@printf "Running NSP check...\n"
npm run nsp
-bithound bithound check git@github.com:deadratfink/jy-transform.git
-
readme: ## Creates all the documentation parts of the project: _README.md_, _MAKE.md_, _PACKAGE.md_ and _API.md_ (the latter based on [JSDoc](http://usejsdoc.org/)).
@printf "Create documentation...\n"
npm run readme
diff --git a/PACKAGE.md b/PACKAGE.md
index d741837..4c1adb0 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -59,4 +59,4 @@ npm test
## License
-SEE LICENSE IN [LICENSE.md](https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md)
+MIT
diff --git a/package.json b/package.json
index 5d58f84..c7a8ff4 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,7 @@
"url": "https://github.com/deadratfink"
},
"contributors": [],
- "license": "SEE LICENSE IN [LICENSE.md](https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md)",
+ "license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/deadratfink/jy-transform.git"
@@ -30,14 +30,14 @@
"nsp": "nsp check"
},
"engines": {
- "node": ">=4.0.0"
+ "node": ">=5.0.0"
},
"dependencies": {
"babel-cli": "~6.24.1",
"cli": " ~1.0.1",
"is-stream": " ~1.1.0",
"joi": "~10.6.0",
- "js-yaml": " ~3.8.4",
+ "js-yaml": " ~3.9.0",
"json-stringify-safe": " ~5.0.1",
"mkdirp-then": " ~1.2.0",
"promisify-es6": "~1.0.2",
@@ -46,17 +46,17 @@
"devDependencies": {
"babel-eslint": " ~7.2.3",
"babel-plugin-transform-flow-strip-types": "~6.22.0",
- "babel-preset-env": "~1.5.2",
+ "babel-preset-env": "~1.6.0",
"chalk": "~2.0.1",
"codeclimate-test-reporter": " ~0.5.0",
"codecov": " ~2.2.0",
"coveralls": " ~2.13.1",
"cwd": "~0.10.0",
"doctoc": " ~1.3.0",
- "eslint": "~4.1.0",
+ "eslint": "~4.2.0",
"eslint-config-airbnb-base": "~11.2.0",
"eslint-plugin-filenames": "1.2.0",
- "eslint-plugin-import": " ~2.6.1",
+ "eslint-plugin-import": " ~2.7.0",
"eslint-plugin-jest": " ~20.0.3",
"eslint-plugin-jest-async": " ~1.0.3",
"eslint-plugin-jsdoc": " ~3.1.1",
@@ -67,8 +67,7 @@
"jsdoc-to-markdown": " ~3.0.0",
"nsp": "~2.6.3",
"package-json-to-readme": " ~2.0.0",
- "winston": " ~2.3.0",
- "winston-console-formatter": "~0.3.1"
+ "winston": " ~2.3.0"
},
"preferGlobal": true,
"bin": {
diff --git a/src/reader.js b/src/reader.js
index da0998d..40872aa 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -4,8 +4,6 @@ import { Buffer } from 'buffer';
import path from 'path';
import fs from 'fs';
import isStream from 'is-stream';
-import stringify from 'json-stringify-safe'; // TODO remove
-import logger from 'cli'; // TODO remove
import { readOptionsSchema } from './validation/options-schema';
import Joi from './validation/joi-extensions';
import {
@@ -67,25 +65,19 @@ function readFromStream(readable, origin) {
*/
async function readJs(options) {
if (typeof options.src === 'string') { // path to JSON or JS file
- try {
- const resolvedPath = path.resolve('', options.src);
- if (options.imports) {
- // eslint-disable-next-line import/no-dynamic-require, global-require
- const object = require(resolvedPath)[options.imports];
- // logger.debug('LOADED JSON object (' + options.imports + '):: ' + stringify(object, null, 4)); TODO remove
- if (!object) { // TODO check this as part of config validation?
- throw new Error('an identifier string \'' + options.imports + '\' was specified for JS object' +
- ' but could not find this object, pls ensure that file ' + options.src + ' contains it.');
- } else {
- return object;
- }
+ const resolvedPath = path.resolve('', options.src);
+ if (options.imports) {
+ // eslint-disable-next-line import/no-dynamic-require, global-require
+ const object = require(resolvedPath)[options.imports];
+ if (!object) { // TODO check this as part of config validation?
+ throw new Error('an identifier string \'' + options.imports + '\' was specified for JS object ' +
+ 'but could not find this object, pls ensure that file ' + options.src + ' contains it.');
} else {
- // eslint-disable-next-line import/no-dynamic-require, global-require
- return require(resolvedPath); // reads both: JS and JSON!
+ return object;
}
- } catch (err) { // probably a SyntaxError
- // logger.error('Unexpected error: ' + err.stack); TODO remove
- throw err;
+ } else {
+ // eslint-disable-next-line import/no-dynamic-require, global-require
+ return require(resolvedPath); // reads both: JS and JSON!
}
} else if (isStream.readable(options.src)) {
return readFromStream(options.src, TYPE_JSON); // reads both: JS or JSON!
diff --git a/src/transformer.js b/src/transformer.js
index 2efcfac..3c41cd2 100644
--- a/src/transformer.js
+++ b/src/transformer.js
@@ -1,4 +1,3 @@
-import logger from 'cli'; // TODO remove
import Joi from './validation/joi-extensions';
import { read } from './reader';
import { write } from './writer';
@@ -54,11 +53,7 @@ import { transformOptionsSchema } from './validation/options-schema';
* };
*/
export async function transform(options) {
- // logger.debug('transform'); TODO remove
const validatedOptions = await Joi.validate(options, transformOptionsSchema);
-
- console.log('Passed transform options:\n' + JSON.stringify(validatedOptions, null, 4)); // TODO remove
-
let object = await read(validatedOptions);
object = await validatedOptions.transform(object);
diff --git a/src/validation/options-schema-helper.js b/src/validation/options-schema-helper.js
index 30be3da..85bbd5e 100644
--- a/src/validation/options-schema-helper.js
+++ b/src/validation/options-schema-helper.js
@@ -15,6 +15,61 @@ import {
* @private
*/
+
+/**
+ * Checks if passed `object` is a file stream instance.
+ *
+ * @param {*} object - The object to check.
+ * @returns {boolean} A `true` if passed `object` is a file stream instance, else `false`.
+ * @private
+ */
+const isFileStream = (object) => {
+ return isStream(object) && object.path;
+};
+
+/**
+ * Returns the passes `dest` value or an adapted destination path (the latter if `target` is defined an differs from
+ * destinations path extension).
+ *
+ * @param {string} dest - The destination path.
+ * @param {string} [target] - The target file type of destination.
+ * @returns {string} The `dest` value or an adapted destination path.
+ * @private
+ */
+const adaptTargetPathType = (dest, target) => {
+ if (target) {
+ const tmpDest = dest;
+ const destDirName = path.dirname(tmpDest);
+ const ext = path.extname(tmpDest);
+ const basename = path.basename(tmpDest, ext);
+ let destType = ext;
+ if (ext.charAt(0) === '.') {
+ destType = ext.substr(1);
+ }
+ if (EXT_TO_TYPE_MAP[destType] !== target) {
+ destType = target;
+ }
+ return path.join(destDirName, basename + '.' + destType);
+ }
+ return dest;
+};
+
+/**
+ * This function is used to infer a _default_ value in case `options.dest` is not defined.
+ * Checks if `context.src` is either a string or a file stream where can get the file path from.
+ * If this detection process cannot be fulfilled (i.e. we cannot infer from options.src `Object`
+ * type or a `Readable` type which is not a _file_ stream) then the function returns `undefined`.
+ *
+ * @param {Object} context - The validation context.
+ * @returns {string|undefined} The adapted `dest` path if possible, or `undefined`.
+ */
+export const inferDestDefaultFromSrc = (context) => {
+ if (typeof context.src === 'string' || isFileStream(context.src)) {
+ return adaptTargetPathType((context.src.path || context.src), context.target);
+ }
+ return undefined;
+};
+
/**
* Infer from path extension to a type using default value as fallback.
*
@@ -76,62 +131,7 @@ export const inferTargetDefault = (context) => {
return type;
};
-/**
- * Checks if passed `object` is a file stream instance.
- *
- * @param {*} object - The object to check.
- * @returns {boolean} A `true` if passed `object` is a file stream instance, else `false`.
- * @private
- */
-export const isFileStream = (object) => {
- return isStream(object) && object.path;
-};
-
-/**
- * Returns the passes `dest` value or an adapted destination path (the latter if `target` is defined an differs from
- * destinations path extension).
- *
- * @param {string} dest - The destination path.
- * @param {string} [target] - The target file type of destination.
- * @returns {string} The `dest` value or an adapted destination path.
- * @private
- */
-export const adaptTargetPathType = (dest, target) => {
- if (target) {
- const tmpDest = dest;
- const destDirName = path.dirname(tmpDest);
- const ext = path.extname(tmpDest);
- const basename = path.basename(tmpDest, ext);
- let destType = ext;
- if (ext.charAt(0) === '.') {
- destType = ext.substr(1);
- }
- if (EXT_TO_TYPE_MAP[destType] !== target) {
- destType = target;
- }
- return path.join(destDirName, basename + '.' + destType);
- }
- return dest;
-};
-
-/**
- * This function is used to infer a _default_ value in case `options.dest` is not defined.
- * Checks if `context.src` is either a string or a file stream where can get the file path from.
- * If this detection process cannot be fulfilled then the function returns `undefined`.
- *
- * @param {Object} context - The validation context.
- * @returns {string|undefined} The adapted `dest` path if possible, or `undefined`.
- */
-export const inferDestDefaultFromSrc = (context) => {
- if (typeof context.src === 'string' || isFileStream(context.src)) {
- return adaptTargetPathType((context.src.path || context.src), context.target);
- }
- return undefined; // TODO how to handle this??? Throw Error?
-};
-
export default {
- isFileStream,
- adaptTargetPathType,
inferOriginDefault,
inferTargetDefault,
inferDestDefaultFromSrc,
diff --git a/src/writer.js b/src/writer.js
index 595c267..dc2e2d5 100644
--- a/src/writer.js
+++ b/src/writer.js
@@ -1,4 +1,3 @@
-import logger from 'cli'; // TODO remove
import fs from 'fs';
import isStream from 'is-stream';
import jsYaml from 'js-yaml';
@@ -315,13 +314,8 @@ async function writeJs(object, options) {
* .catch(console.error);
*/
export async function write(object, options) {
- // console.log('OPTIONS ON WRITE ===> ' + JSON.stringify(options, null, 4)) // TODO remove
const validatedOptions = await Joi.validate(options, writeOptionsSchema);
-
- // HINT: we have to use the original options object because the caller must not loose the reference to options.dest,
- // so we copy everything here except the assertedOptions.dest (joi does not return the original reference)!
- Object.assign(options, { target: validatedOptions.target }, { exports: validatedOptions.exports }, // TODO does this work without full copy?
- { indent: validatedOptions.indent }, { force: validatedOptions.force });
+ // HINT: we have to use the original options object because the caller must not loose the reference to options.dest!
validatedOptions.dest = options.dest;
switch (validatedOptions.target) {
case TYPE_JSON:
diff --git a/test/unit/test-transformer.js b/test/unit/test-transformer.js
index 5edb68f..b522d6f 100644
--- a/test/unit/test-transformer.js
+++ b/test/unit/test-transformer.js
@@ -101,12 +101,13 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
})).rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
});
- it('should throw ValidationError if options.dest is not set and cannot be resolved from options.src type', async () => {
- expect.assertions(1);
- await expect(transform({
- src: {}, // we cannot infer destination from this type!
- })).rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
- });
+ it('should throw ValidationError if options.dest is not set and cannot be resolved from options.src type',
+ async () => {
+ expect.assertions(1);
+ await expect(transform({
+ src: {}, // we cannot infer destination from this type!
+ })).rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
+ });
it('should not fail if middleware passed is returning a Promise', () => {
expect.assertions(1);
diff --git a/test/unit/validation/test-options-schema-helper.js b/test/unit/validation/test-options-schema-helper.js
index fdcf53c..0e02995 100644
--- a/test/unit/validation/test-options-schema-helper.js
+++ b/test/unit/validation/test-options-schema-helper.js
@@ -3,6 +3,7 @@ import fs from 'fs';
import {
inferOriginDefault,
inferTargetDefault,
+ inferDestDefaultFromSrc,
} from '../../../src/validation/options-schema-helper';
import { TEST_SUITE_DESCRIPTION_UNIT } from '../../helper-constants';
import {
@@ -20,16 +21,16 @@ import {
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
describe('Function inferOriginDefault', () => {
- it('should infer the correct origin from relative path string with existing file having a known file type', () =>
- expect(inferOriginDefault({
- src: 'test/unit/validation/test-joi-extensions-file-helper.js'
- })).toBe(TYPE_JS)
+ it('should infer the correct origin from relative path string with existing file having a known file extension',
+ () => expect(inferOriginDefault({ src: 'test/unit/validation/test-joi-extensions-file-helper.js' })).toBe(TYPE_JS)
);
- it('should infer the default origin from relative path string with existing file having an unknown file type', () =>
- expect(inferOriginDefault({
- src: 'test/data/readable-test-dummy.txt'
- })).toBe(DEFAULT_ORIGIN)
+ it('should infer the default origin from relative path string with existing file having an unsupported file ' +
+ 'extension', () => expect(inferOriginDefault({ src: 'test/data/readable-test-dummy.txt' })).toBe(DEFAULT_ORIGIN)
+ );
+
+ it('should infer the default origin from relative path string with existing file having no file extension', () =>
+ expect(inferOriginDefault({ src: 'test/data/readable-test-dummy' })).toBe(DEFAULT_ORIGIN)
);
it('should infer the correct origin from read stream of existing file having a known file ending', () =>
@@ -39,41 +40,29 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
);
it('should infer the correct origin from read stream of existing file having an unknown file ending', () =>
- expect(inferOriginDefault({
- src: fs.createReadStream('test/data/readable-test-dummy.txt'),
- })).toBe(DEFAULT_ORIGIN)
+ expect(inferOriginDefault({ src: fs.createReadStream('test/data/readable-test-dummy.txt') })).toBe(DEFAULT_ORIGIN)
);
it('should infer the correct origin from plain read stream', () =>
- expect(inferOriginDefault({
- src: new stream.Readable(),
- })).toBe(DEFAULT_ORIGIN)
+ expect(inferOriginDefault({ src: new stream.Readable() })).toBe(DEFAULT_ORIGIN)
);
it('should infer the default origin from unsupported origin.src', () =>
- expect(inferOriginDefault({
- src: {},
- })).toBe(DEFAULT_ORIGIN)
+ expect(inferOriginDefault({ src: {} })).toBe(DEFAULT_ORIGIN)
);
});
describe('Function inferTargetDefault', () => {
it('should infer the correct target from relative path string with existing file having a known file ending', () =>
- expect(inferTargetDefault({
- dest: 'test/unit/validation/test-joi-extensions-file-helper.yaml'
- })).toBe(TYPE_YAML)
+ expect(inferTargetDefault({ dest: 'test/unit/validation/test-joi-extensions-file-helper.yaml' })).toBe(TYPE_YAML)
);
it('should infer the default target from relative path string with existing file having an unknown file type', () =>
- expect(inferTargetDefault({
- dest: 'test/data/readable-test-dummy.txt'
- })).toBe(DEFAULT_TARGET)
+ expect(inferTargetDefault({ dest: 'test/data/readable-test-dummy.txt' })).toBe(DEFAULT_TARGET)
);
it('should infer the correct target from relative path string with existing file having a known file type', () =>
- expect(inferTargetDefault({
- dest: fs.createWriteStream('test/data/writable-test-dummy.yaml'),
- })).toBe(TYPE_YAML)
+ expect(inferTargetDefault({ dest: fs.createWriteStream('test/data/writable-test-dummy.yaml') })).toBe(TYPE_YAML)
);
it('should infer the default target from relative path string with existing file having an' +
@@ -84,15 +73,64 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
);
it('should infer the correct origin from plain write stream', () =>
- expect(inferTargetDefault({
- dest: new stream.Writable(),
- })).toBe(DEFAULT_TARGET)
+ expect(inferTargetDefault({ dest: new stream.Writable() })).toBe(DEFAULT_TARGET)
);
it('should infer the default target from unsupported origin.dest', () =>
- expect(inferTargetDefault({
- dest: {},
- })).toBe(DEFAULT_TARGET)
+ expect(inferTargetDefault({ dest: {} })).toBe(DEFAULT_TARGET)
+ );
+ });
+
+ describe('Function inferDestDefaultFromSrc', () => {
+ it('should resolve missing destination from context.src string type without a target to context.src value', () => {
+ const context = { src: 'test/data/test-data.js' };
+ expect(inferDestDefaultFromSrc(context)).toBe(context.src);
+ });
+
+ it('should resolve missing destination from context.src file Readable type without a target to' +
+ 'context.src.path value', () => {
+ const context = { src: fs.createReadStream('test/data/test-data.js') };
+ expect(inferDestDefaultFromSrc(context)).toBe(context.src.path);
+ });
+
+ it('should resolve missing destination from context.src file Readable type with a target to' +
+ 'context.src.path value', () => {
+ const context = {
+ src: fs.createReadStream('test/data/test-data.js'),
+ target: TYPE_JS,
+ };
+ expect(inferDestDefaultFromSrc(context)).toBe(context.src.path);
+ });
+
+ it('should resolve missing destination from context.src string type with a target to context.src' +
+ 'value where extension is replaced with YAML file type', () => {
+ const context = {
+ src: 'test/data/test-data.js',
+ target: TYPE_YAML,
+ };
+ expect(inferDestDefaultFromSrc(context)).toBe('test/data/test-data.yaml');
+ });
+
+ it('should resolve missing destination from context.src string type (without file extension) but with a target to' +
+ 'context.src value where extension is replaced with YAML file type', () => {
+ const context = {
+ src: 'test/data/test-data',
+ target: TYPE_YAML,
+ };
+ expect(inferDestDefaultFromSrc(context)).toBe('test/data/test-data.yaml');
+ });
+
+ it('should resolve missing destination from context.src file Readable type without a target to' +
+ 'context.src.path value but with YAML file type', () => {
+ const context = {
+ src: fs.createReadStream('test/data/test-data.js'),
+ target: TYPE_YAML,
+ };
+ expect(inferDestDefaultFromSrc(context)).toBe('test/data/test-data.yaml');
+ });
+
+ it('should resolve missing destination fom context.src Object type to undefined destination value', () =>
+ expect(inferDestDefaultFromSrc({ src: {} })).toBeUndefined()
);
});
});
From 84ecbf4b8535ee805eef1e09f76b77077ba74ace Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 13 Jul 2017 02:02:41 +0200
Subject: [PATCH 18/58] Fix bithound for babel-cli dep
---
.bithoundrc | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/.bithoundrc b/.bithoundrc
index 5e0d2eb..527211f 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -1,11 +1,12 @@
{
"critics": {
- "lint": {"engine": "eslint"}
+ "lint": {
+ "engine": "eslint"
+ }
},
"dependencies": {
"unused-ignores": [
- "grunt-*",
- "bower",
+ "babel-cli",
"eslint"
]
}
From eccf94a2e8154eb421e976276c1ef25519c76d71 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 13 Jul 2017 02:05:04 +0200
Subject: [PATCH 19/58] Test less verbose
---
test/unit/test-transformer.js | 12 ++++++------
test/unit/test-writer.js | 10 +++++-----
2 files changed, 11 insertions(+), 11 deletions(-)
diff --git a/test/unit/test-transformer.js b/test/unit/test-transformer.js
index b522d6f..e221350 100644
--- a/test/unit/test-transformer.js
+++ b/test/unit/test-transformer.js
@@ -40,7 +40,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
beforeEach(() => {
try {
fsExtra.copySync(SRC_YAML, TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml');
- logger.info('copied ' + SRC_YAML + ' to ' + TRANSFORMER_TEST_BASE_DIR);
+ logger.debug('copied ' + SRC_YAML + ' to ' + TRANSFORMER_TEST_BASE_DIR);
} catch (err) {
logger.error('could not copy ' + SRC_YAML + ' to ' + TRANSFORMER_TEST_BASE_DIR + err.stack);
throw err;
@@ -65,7 +65,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
function assertTransformSuccess(options) {
return transform(options)
.then((msg) => {
- logger.info(msg);
+ logger.debug(msg);
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
// eslint-disable-next-line import/no-dynamic-require, global-require
@@ -82,7 +82,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
async function assertYamlTransformSuccess(options) {
expect.assertions(3);
const msg = await transform(options);
- logger.info(msg);
+ logger.debug(msg);
expect(msg).toEqual(expect.any(String));
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
@@ -151,7 +151,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
transform: transformFunc,
dest: path.resolve(TRANSFORMER_TEST_BASE_DIR + '/test-data.js'),
});
- logger.info(msg);
+ logger.debug(msg);
const stats = fs.statSync(DEST);
expect(stats.isFile()).toBeTruthy();
// eslint-disable-next-line import/no-unresolved, global-require, import/no-dynamic-require
@@ -235,7 +235,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
transform(options)
.then((msg) => {
- logger.info(msg);
+ logger.debug(msg);
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
@@ -273,7 +273,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
transform(options)
.then((msg) => {
- logger.info(msg);
+ logger.debug(msg);
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
diff --git a/test/unit/test-writer.js b/test/unit/test-writer.js
index 26b2b5b..5337843 100644
--- a/test/unit/test-writer.js
+++ b/test/unit/test-writer.js
@@ -79,7 +79,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
await fsPromised.stat(dest);
statErr = new Error('Error expected when checking file = ' + dest);
} catch (err) {
- logger.info('Error is EXPECTED: ' + err.stack);
+ logger.debug('Error is EXPECTED: ' + err.stack);
expect(err).toBeDefined();
expect(err.code).toBe('ENOENT');
}
@@ -178,7 +178,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
const errorThrowingStream = new stream.Writable();
// eslint-disable-next-line no-underscore-dangle, func-names
errorThrowingStream._write = function (chunk, encoding, done) {
- logger.info('stream emitting Error now');
+ logger.debug('stream emitting Error now');
this.emit('error', new Error('Dummy Error'));
done();
};
@@ -247,7 +247,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
done(new Error('Error expected, but got success message: ' + msg));
})
.catch((err) => {
- logger.info('EXPECTED ERROR: ' + (err.stack ? err.stack : err));
+ logger.debug('EXPECTED ERROR: ' + (err.stack ? err.stack : err));
expect(err).toBeDefined();
// NOTE: here wo do not get an Error type but simply an Object:
// {
@@ -437,9 +437,9 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
await asyncFunctions.reduce((p, fn, idx) => {
return p.then((msg) => {
if (msg) {
- logger.info('testing overwrite #' + (idx + 1) + '/' + asyncFunctions.length + ': ' + msg);
+ logger.debug('testing overwrite #' + (idx + 1) + '/' + asyncFunctions.length + ': ' + msg);
} else {
- logger.info('testing overwrite #' + (idx) + '/' + asyncFunctions.length + ': started!');
+ logger.debug('testing overwrite #' + (idx) + '/' + asyncFunctions.length + ': started!');
}
return fn().then(result => result).catch(err => err.message);
});
From 442d5214773134ad4c7ffdf1a4a5d6c68e4cf19f Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 13 Jul 2017 02:22:42 +0200
Subject: [PATCH 20/58] Fix bithound babel-cli
---
.bithoundrc | 1 -
package.json | 2 +-
2 files changed, 1 insertion(+), 2 deletions(-)
diff --git a/.bithoundrc b/.bithoundrc
index 527211f..be96efc 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -6,7 +6,6 @@
},
"dependencies": {
"unused-ignores": [
- "babel-cli",
"eslint"
]
}
diff --git a/package.json b/package.json
index c7a8ff4..ddcbb44 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,6 @@
"node": ">=5.0.0"
},
"dependencies": {
- "babel-cli": "~6.24.1",
"cli": " ~1.0.1",
"is-stream": " ~1.1.0",
"joi": "~10.6.0",
@@ -44,6 +43,7 @@
"serialize-js": " ~1.1.0"
},
"devDependencies": {
+ "babel-cli": "~6.24.1",
"babel-eslint": " ~7.2.3",
"babel-plugin-transform-flow-strip-types": "~6.22.0",
"babel-preset-env": "~1.6.0",
From 4f3ef038f1537d4f8f7e586403dd695bae77270f Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 13 Jul 2017 02:23:12 +0200
Subject: [PATCH 21/58] Update docs
---
PACKAGE.md | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/PACKAGE.md b/PACKAGE.md
index 4c1adb0..0cb6389 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -18,7 +18,6 @@ npm test
## Dependencies
-- [babel-cli](https://github.com/babel/babel/tree/master/packages): Babel command line.
- [cli](https://github.com/node-js-libs/cli): A tool for rapidly building command line apps
- [is-stream](https://github.com/sindresorhus/is-stream): Check if something is a Node.js stream
- [joi](https://github.com/hapijs/joi): Object schema validation
@@ -30,6 +29,7 @@ npm test
## Dev Dependencies
+- [babel-cli](https://github.com/babel/babel/tree/master/packages): Babel command line.
- [babel-eslint](https://github.com/babel/babel-eslint): Custom parser for ESLint
- [babel-plugin-transform-flow-strip-types](https://github.com/babel/babel/tree/master/packages): Strip flow type annotations from your output code.
- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
@@ -54,7 +54,6 @@ npm test
- [nsp](https://github.com/nodesecurity/nsp): The Node Security (nodesecurity.io) command line interface
- [package-json-to-readme](https://github.com/zeke/package-json-to-readme): Generate a README.md from package.json contents
- [winston](https://github.com/winstonjs/winston): A multi-transport async logging library for Node.js
-- [winston-console-formatter](https://github.com/eugeny-dementev/winston-console-formatter): Pretty print console formatter in yaml like style
## License
From 9fcdcf9da26e5a0c35668dbe909bf682f138f7b0 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 13 Jul 2017 02:52:27 +0200
Subject: [PATCH 22/58] Fix regenerator issue
---
.babelrc | 6 ++++++
API-PRIVATE.md | 12 ++++++------
PACKAGE.md | 1 +
package.json | 1 +
src/writer.js | 17 +++++++----------
5 files changed, 21 insertions(+), 16 deletions(-)
diff --git a/.babelrc b/.babelrc
index aec1179..5bb615c 100644
--- a/.babelrc
+++ b/.babelrc
@@ -5,5 +5,11 @@
"node": "current"
}
}]
+ ],
+ "plugins": [
+ ["transform-runtime", {
+ "polyfill": false,
+ "regenerator": true
+ }]
]
}
diff --git a/API-PRIVATE.md b/API-PRIVATE.md
index 3811e22..6854f98 100644
--- a/API-PRIVATE.md
+++ b/API-PRIVATE.md
@@ -1082,12 +1082,12 @@ Ensures that all dirs exists for file type `dest` and writes the JS object to fi
**Kind**: global variable
**Access**: private
-| Param | Type | Description |
-| --- | --- | --- |
-| object | string | The object to write into file. |
-| dest | string | The file destination path. |
-| target | string | The target type, one of [ 'yaml' | 'json' | 'js' ]. |
-| [forceOverwrite] | boolean | Forces overwriting the destination file if `true`. |
+| Param | Type | Default | Description |
+| --- | --- | --- | --- |
+| object | string | | The object to write into file. |
+| dest | string | | The file destination path. |
+| target | string | | The target type, one of [ 'yaml' | 'json' | 'js' ]. |
+| [forceOverwrite] | boolean | false | Forces overwriting the destination file if `true`. |
diff --git a/PACKAGE.md b/PACKAGE.md
index 0cb6389..3a7cd8a 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -32,6 +32,7 @@ npm test
- [babel-cli](https://github.com/babel/babel/tree/master/packages): Babel command line.
- [babel-eslint](https://github.com/babel/babel-eslint): Custom parser for ESLint
- [babel-plugin-transform-flow-strip-types](https://github.com/babel/babel/tree/master/packages): Strip flow type annotations from your output code.
+- [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
- [chalk](https://github.com/chalk/chalk): Terminal string styling done right. Much color
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
diff --git a/package.json b/package.json
index ddcbb44..1d0ce34 100644
--- a/package.json
+++ b/package.json
@@ -46,6 +46,7 @@
"babel-cli": "~6.24.1",
"babel-eslint": " ~7.2.3",
"babel-plugin-transform-flow-strip-types": "~6.22.0",
+ "babel-plugin-transform-runtime": "~6.23.0",
"babel-preset-env": "~1.6.0",
"chalk": "~2.0.1",
"codeclimate-test-reporter": " ~0.5.0",
diff --git a/src/writer.js b/src/writer.js
index dc2e2d5..ff8ed7d 100644
--- a/src/writer.js
+++ b/src/writer.js
@@ -84,7 +84,7 @@ async function serializeJsToJsonString(object, indent) {
* name which does not exist.
*
* @param {string} dest - The destination file.
- * @returns {string} - A consecutive file name or the original one if `dest` file does not exist.
+ * @returns {string} A consecutive file name or the original one if `dest` file does not exist.
* @private
*/
function getConsecutiveDestName(dest) {
@@ -102,21 +102,18 @@ function getConsecutiveDestName(dest) {
/**
* Ensures that all dirs exists for file type `dest` and writes the JS object to file.
*
- * @param {string} object - The object to write into file.
- * @param {string} dest - The file destination path.
- * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
- * @param {boolean} [forceOverwrite] - Forces overwriting the destination file if `true`.
+ * @param {string} object - The object to write into file.
+ * @param {string} dest - The file destination path.
+ * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
+ * @param {boolean} [forceOverwrite=false] - Forces overwriting the destination file if `true`.
* @private
*/
-async function mkdirAndWrite(object, dest, target, forceOverwrite) {
+async function mkdirAndWrite(object, dest, target, forceOverwrite = false) {
const destDir = path.dirname(dest);
- // logger.debug('Destination dir: ' + destDir); TODO remove
await mkdirp(destDir);
- // logger.debug('Destination dir ' + destDir + ' successfully written'); TODO remove
let finalDestination = dest;
- if (forceOverwrite === undefined || forceOverwrite === false) {
+ if (!forceOverwrite) {
finalDestination = getConsecutiveDestName(dest);
- // logger.debug('Setting was: do not overwrite, using destination ' + finalDestination + '.'); TODO remove
}
await fsPromisified.writeFile(finalDestination, object, UTF8);
return 'Writing \'' + target + '\' file \'' + finalDestination + '\' successful.';
From 4bcba601bd3e13cdc157efb301c89675d7ca8e45 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Mon, 17 Jul 2017 13:00:24 +0200
Subject: [PATCH 23/58] Add codacy
---
.jestrc.js | 2 +-
.travis.yml | 1 +
Makefile | 4 ++++
inch.json | 3 ++-
package.json | 5 ++++-
test/unit/test-cli.js | 39 +++++++++++++++++++++++++++++++++++++++
6 files changed, 51 insertions(+), 3 deletions(-)
diff --git a/.jestrc.js b/.jestrc.js
index 639b0dc..5272f30 100644
--- a/.jestrc.js
+++ b/.jestrc.js
@@ -20,7 +20,7 @@ module.exports = {
},
mapCoverage: true,
testMatch: [
- // '!**/test/unit/test-cli.js',
+ // '**/test/unit/test-cli.js',
// '**/test/unit/validation/test-joi-extensions-file-helper.js',
// '**/test/unit/validation/test-joi-extensions-identifier-helper.js',
//'**/test/unit/test-transformer.js',
diff --git a/.travis.yml b/.travis.yml
index a3e8ef4..acc4075 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -18,6 +18,7 @@ after_success:
- ./node_modules/codecov/bin/codecov -e TRAVIS_NODE_VERSION
- cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js --verbose
- ./node_modules/codeclimate-test-reporter/bin/codeclimate.js < ./coverage/lcov.info
+- ./node_modules/.bin/codacy-coverage < ./coverage/lcov.info
branches:
only: # whitelist
diff --git a/Makefile b/Makefile
index 92e9717..66b6a05 100644
--- a/Makefile
+++ b/Makefile
@@ -22,6 +22,10 @@ test: build ## Runs the test suite, ESLint and a [Node Security Plattform](https
npm run eslint
npm run nsp
+inch: build ## Runs [inch](https://github.com/rrrene/inchjs) for api-docs check. **NOTE: due to some bug in inch it does not work at the moment!**
+ @printf "Running inch to check api-docs status...\n"
+ npm run inch
+
nsp: ## Runs an [Node Security Plattform](https://nodesecurity.io/opensource) check.
@printf "Running NSP check...\n"
npm run nsp
diff --git a/inch.json b/inch.json
index 4268668..5618920 100644
--- a/inch.json
+++ b/inch.json
@@ -1,12 +1,13 @@
{
"files": {
"included": [
- "src/**/*.js",
+ "lib/**/*.js",
"test/test*.js",
"index.js",
"jyt"
],
"excluded": [
+ "lib/**/*"
]
}
}
diff --git a/package.json b/package.json
index 1d0ce34..7980b12 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"pretest": "mkdir -pv test/tmp",
"test": "JYT_DEBUG=false JYT_ERROR=false jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
"eslint": "eslint .",
- "nsp": "nsp check"
+ "nsp": "nsp check",
+ "inch": "inchjs suggest && inchjs list --all && inchjs stats"
},
"engines": {
"node": ">=5.0.0"
@@ -49,6 +50,7 @@
"babel-plugin-transform-runtime": "~6.23.0",
"babel-preset-env": "~1.6.0",
"chalk": "~2.0.1",
+ "codacy-coverage": "~2.0.2",
"codeclimate-test-reporter": " ~0.5.0",
"codecov": " ~2.2.0",
"coveralls": " ~2.13.1",
@@ -62,6 +64,7 @@
"eslint-plugin-jest-async": " ~1.0.3",
"eslint-plugin-jsdoc": " ~3.1.1",
"fs-extra": " ~3.0.1",
+ "inchjs": "~0.4.1",
"jest": "~20.0.4",
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": " ~3.0.0",
diff --git a/test/unit/test-cli.js b/test/unit/test-cli.js
index fe8f586..cdf9e97 100644
--- a/test/unit/test-cli.js
+++ b/test/unit/test-cli.js
@@ -30,6 +30,7 @@ const execJyt = async (args) => {
console.log(`stdout: ${JSON.stringify(result, null, 4)}`);
console.log(`stdout: ${result.stdout}`);
console.log(`stderr: ${result.stderr}`);
+ return result;
} catch (err) {
console.log(`stdout: ${err.stdout}`);
console.log(`stderr: ${err.stderr}`);
@@ -80,6 +81,43 @@ const execJyt = async (args) => {
//exec('./jyt inch.json inch.yml -i 1')
+const CLI_OPTIONS_LONGTO_SHORT_MAP = {
+ origin: '-o',
+ target: '-t',
+ indent: '-i',
+ force: '-f ',
+ imports: '-m ',
+ exports: '-x '
+};
+
+function optionsToArgs(options) {
+ const args = [];
+ args.push(options.src);
+ if (options.dest) {
+ args.push(options.dest)
+ }
+ if (options.origin) {
+ args.push(options.origin)
+ }
+}
+
+/**
+ * Helper method which asserts the successful transformation.
+ *
+ * @param {Object} options - The transformation options.
+ */
+function assertTransformSuccess(options) {
+ return transform(options)
+ .then((msg) => {
+ logger.debug(msg);
+ const stats = fsExtra.statSync(options.dest);
+ expect(stats.isFile()).toBeTruthy();
+ // eslint-disable-next-line import/no-dynamic-require, global-require
+ const json = require(path.resolve(options.dest));
+ expect(json.foo).toBe(EXPECTED_VALUE);
+ });
+}
+
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
const TEST_DATA_DIR = './test/data';
const SRC_YAML = TEST_DATA_DIR + '/test-file.yaml';
@@ -100,5 +138,6 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
it('cli', async () => {
await execJyt(['./inch.json', CLI_TEST_BASE_DIR + '/inch.yaml', '-i 2', '-t yaml']);
+
});
});
From 638ed0bc1cfb8418826ff916f5b9808b20ab07d4 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 21 Jul 2017 19:55:35 +0200
Subject: [PATCH 24/58] Intermediate work
---
.circleci/config.yml | 32 ++
.jestrc.js | 6 +-
API-PRIVATE.md | 82 ++++-
API-PUBLIC.md | 4 +-
MAKE.md | 1 +
PACKAGE.md | 2 +
README.md | 2 +
readme/BADGES.md | 2 +
src/validation/options-schema.js | 185 +++++------
src/writer.js | 2 +-
test/data/test-data-cli.js | 3 +
test/data/test-data-cli.json | 3 +
test/data/test-data-cli.yaml | 1 +
test/helper-constants.js | 16 +
test/unit/test-cli.js | 331 ++++++++++++++------
test/unit/test-transformer.js | 292 ++++++++---------
test/unit/validation/test-options-schema.js | 56 ++--
17 files changed, 613 insertions(+), 407 deletions(-)
create mode 100644 .circleci/config.yml
create mode 100644 test/data/test-data-cli.js
create mode 100644 test/data/test-data-cli.json
create mode 100644 test/data/test-data-cli.yaml
diff --git a/.circleci/config.yml b/.circleci/config.yml
new file mode 100644
index 0000000..c1cf16a
--- /dev/null
+++ b/.circleci/config.yml
@@ -0,0 +1,32 @@
+version: 2
+jobs:
+ build:
+ docker:
+ - image: circleci/node:6
+ environment:
+ - NODE_ENV: "test"
+ branches:
+ only:
+ - master
+ steps:
+ - checkout
+ - run:
+ name: Running tests
+ command: make test
+ - run:
+ name: Bithound
+ command: |
+ npm install bithound --save-dev
+ bithound check git@github.com:deadratfink/jy-transform.git
+ - run:
+ name: Codecov Coverage
+ command: ./node_modules/codecov/bin/codecov
+ - run:
+ name: Coveralls Coverage
+ command: cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js --verbose
+ - run:
+ name: Codeclimate Coverage
+ command: ./node_modules/codeclimate-test-reporter/bin/codeclimate.js < ./coverage/lcov.info
+ - run:
+ name: Codacy Coverage
+ command: ./node_modules/.bin/codacy-coverage < ./coverage/lcov.info
diff --git a/.jestrc.js b/.jestrc.js
index 5272f30..e2fc01c 100644
--- a/.jestrc.js
+++ b/.jestrc.js
@@ -23,12 +23,12 @@ module.exports = {
// '**/test/unit/test-cli.js',
// '**/test/unit/validation/test-joi-extensions-file-helper.js',
// '**/test/unit/validation/test-joi-extensions-identifier-helper.js',
- //'**/test/unit/test-transformer.js',
+ // '**/test/unit/test-transformer.js',
// '**/test/unit/test-index.js',
//'**/test/unit/test-reader.js',
// '**/test/unit/test-writer.js',
- // '**/test/unit/validation/test-options-schema.js',
- '**/test/unit/**/*.js',
+ // '**/test/unit/validation/test-options-schema.js',
+ '**/test/unit/**/*.js',
//'**/test/unit/validation/test-options-schema-helper.js',
// '**/test/test-log-wrapper.js',
diff --git a/API-PRIVATE.md b/API-PRIVATE.md
index 6854f98..81e4dd4 100644
--- a/API-PRIVATE.md
+++ b/API-PRIVATE.md
@@ -159,7 +159,7 @@ exception on those.
Writes a JS object to a JS destination. The object is prefixed by module.exports[.${options.exports}] =.
Writes the passe JS object to a particular destination described by the passed options.
+
Writes the passed JS object to a particular destination described by the passed options.
@@ -125,7 +125,7 @@ read(options)
## write ⇒ Promise
-Writes the passe JS object to a particular destination described by the passed `options`.
+Writes the passed JS object to a particular destination described by the passed `options`.
**Kind**: global variable
**Returns**: Promise - The result.
diff --git a/MAKE.md b/MAKE.md
index a01285e..cc19d42 100644
--- a/MAKE.md
+++ b/MAKE.md
@@ -5,6 +5,7 @@ Target Call | Description | Dependencies
`$ make clean` | Removes generated files in folders ./node_modules, ./lib and ./coverage" |
`$ make eslint` | Runs ESLint. |
`$ make help` | Prints the help about targets. |
+`$ make inch` | Runs [inch](https://github.com/rrrene/inchjs) for api-docs check. **NOTE | `build`
`$ make install` | Installs all modules |
`$ make nsp` | Runs an [Node Security Plattform](https://nodesecurity.io/opensource) check. |
`$ make publish` | Publishes module to NPM registry. | `test readme`
diff --git a/PACKAGE.md b/PACKAGE.md
index 3a7cd8a..9002849 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -35,6 +35,7 @@ npm test
- [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
- [chalk](https://github.com/chalk/chalk): Terminal string styling done right. Much color
+- [codacy-coverage](https://github.com/codacy/node-codacy-coverage): Code Coverage reporter for Codacy.com
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
- [codecov](https://github.com/codecov/codecov-node): Uploading report to Codecov: https://codecov.io
- [coveralls](https://github.com/nickmerwin/node-coveralls): takes json-cov output into stdin and POSTs to coveralls.io
@@ -48,6 +49,7 @@ npm test
- [eslint-plugin-jest-async](https://github.com/deadratfink/jy-transform.git): ESLint plugin to detect improper Jest test assertions for asynchronous (Promise-based) actions
- [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc): JSDoc linting rules for ESLint.
- [fs-extra](https://github.com/jprichardson/node-fs-extra): fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as mkdir -p, cp -r, and rm -rf.
+- [inchjs](https://github.com/rrrene/inchjs): JS Wrapper for Inch for JavaScript
- [jest](https://github.com/facebook/jest): Delightful JavaScript Testing.
- [jsdoc-babel](https://github.com/ctumolosus/jsdoc-babel): A JSDoc plugin that transforms ES6 source files with Babel before they are processsed.
- [jsdoc-parse](https://github.com/jsdoc2md/jsdoc-parse): Transforms jsdoc data into something more suitable for use as template input
diff --git a/README.md b/README.md
index a1dc1d6..f63d4bd 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,8 @@
[![bitHound Dependencies][bitHound-dependencies-image]][bitHound-dependencies]
[![bitHound Dev Dependencies][bitHound-dev-dependencies-image]][bitHound-dependencies]
[![NSP Status][nsp-image-master]][nsp-url-master]
+[![Codacy Badge](https://img.shields.io/codacy/grade/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat-square)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Grade)
+[![Codacy Badge](https://img.shields.io/codacy/coverage/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat-square)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Coverage)
+[![bitHound Overall Score](https://www.bithound.io/github/deadratfink/jy-transform/badges/score.svg?style=flat)](https://www.bithound.io/github/deadratfink/jy-transform) -->
@@ -25,54 +26,54 @@
[![NPM][npm-image]][npm-url]
[![NPM][npm-downloads-image]][npm-url]
-[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat-square
+[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat
[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
-[gh-issues-image]: https://img.shields.io/github/issues/deadratfink/jy-transform.svg?style=flat-square
+[gh-issues-image]: https://img.shields.io/github/issues/deadratfink/jy-transform.svg?style=flat
[gh-issues-url]: https://github.com/deadratfink/jy-transform/issues
-[gh-releases-image]: https://img.shields.io/github/release/deadratfink/jy-transform.svg?style=flat-square
+[gh-releases-image]: https://img.shields.io/github/release/deadratfink/jy-transform.svg?style=flat
[gh-releases-url]: https://github.com/deadratfink/jy-transform/releases
-[gh-tags-image]: https://img.shields.io/github/tag/deadratfink/jy-transform.svg?style=flat-square
+[gh-tags-image]: https://img.shields.io/github/tag/deadratfink/jy-transform.svg?style=flat
[gh-tags-url]: https://github.com/deadratfink/jy-transform/tags
-[ci-image]: https://img.shields.io/travis/deadratfink/jy-transform.svg?style=flat-square
+[ci-image]: https://img.shields.io/travis/deadratfink/jy-transform.svg?style=flat
[ci-url]: https://travis-ci.org/deadratfink/jy-transform/branches
-[is-pull-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/pr?style=flat-square
-[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat-square
+[is-pull-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/pr?style=flat
+[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat
[is-url]: http://issuestats.com/github/deadratfink/jy-transform
-[waffle-ready-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
-[waffle-waffle-in-progress-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=in%20progress&title=Waffle%20In%20Progress&style=flat-square
+[waffle-ready-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat
+[waffle-waffle-in-progress-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=in%20progress&title=Waffle%20In%20Progress&style=flat
[waffle-url]: https://waffle.io/deadratfink/jy-transform
-[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat-square
+[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat
[cocl-url]: https://codeclimate.com/github/deadratfink/jy-transform
-[cc-image-master]: https://img.shields.io/codecov/c/github/deadratfink/jy-transform/master.svg?style=flat-square
+[cc-image-master]: https://img.shields.io/codecov/c/github/deadratfink/jy-transform/master.svg?style=flat
[cc-url-master]: https://codecov.io/github/deadratfink/jy-transform?branch=master
-[ca-image-master]: https://img.shields.io/coveralls/deadratfink/jy-transform/master.svg?style=flat-square
+[ca-image-master]: https://img.shields.io/coveralls/deadratfink/jy-transform/master.svg?style=flat
[ca-url-master]: https://coveralls.io/github/deadratfink/jy-transform?branch=master
-[inch-image-master]: https://inch-ci.org/github/deadratfink/jy-transform.svg?branch=master&style=flat-square
+[inch-image-master]: https://inch-ci.org/github/deadratfink/jy-transform.svg?branch=master&style=flat
[inch-url-master]: https://inch-ci.org/github/deadratfink/jy-transform?branch=master
-[dep-image-master]: https://img.shields.io/david/deadratfink/jy-transform/master.svg?style=flat-square
+[dep-image-master]: https://img.shields.io/david/deadratfink/jy-transform/master.svg?style=flat
[dep-url-master]: https://david-dm.org/deadratfink/jy-transform/master
-[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat-square
+[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat
[devdep-url-master]: https://david-dm.org/deadratfink/jy-transform/master#info=devDependencies
-[nsp-image-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0/badge?style=flat-square
+[nsp-image-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0/badge?style=flat
[nsp-url-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0
-[node-version-image]: https://img.shields.io/node/v/jy-transform.svg?style=flat-square
+[node-version-image]: https://img.shields.io/node/v/jy-transform.svg?style=flat
[node-version-url]: http://nodejs.org/download/
[npm-image]: https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true
@@ -80,11 +81,11 @@
[npm-downloads-image]: https://nodei.co/npm-dl/jy-transform.png?height=2&months=9
[bithound-url]: https://www.bithound.io/github/deadratfink/jy-transform
-[bithound-code-image]: https://img.shields.io/bithound/code/github/deadratfink/jy-transform.svg?style=flat-square
+[bithound-code-image]: https://img.shields.io/bithound/code/github/deadratfink/jy-transform.svg?style=flat
[bitHound-dependencies]: https://www.bithound.io/github/deadratfink/jy-transform/master/dependencies/npm
-[bitHound-dependencies-image]: https://img.shields.io/bithound/dependencies/github/deadratfink/jy-transform.svg?style=flat-square
-[bitHound-dev-dependencies-image]: https://img.shields.io/bithound/devDependencies/github/deadratfink/jy-transform.svg?style=flat-square
-[bitHound-score-image]: https://img.shields.io/bithound/score/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-dependencies-image]: https://img.shields.io/bithound/dependencies/github/deadratfink/jy-transform.svg?style=flat
+[bitHound-dev-dependencies-image]: https://img.shields.io/bithound/devDependencies/github/deadratfink/jy-transform.svg?style=flat
+[bitHound-score-image]: https://img.shields.io/bithound/score/github/deadratfink/jy-transform.svg?style=flat
# jy-transform
@@ -113,6 +114,7 @@ npm install jy-transform --global
- [Use Cases](#use-cases)
- [Limitations](#limitations)
- [CLI Usage](#cli-usage)
+ - [Examples](#examples)
- [Origin and Target Type Inference](#origin-and-target-type-inference)
- [API Usage](#api-usage)
- [API Reference](#api-reference)
@@ -129,7 +131,7 @@ npm install jy-transform --global
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // Here: read from YAML file...
+ src: 'foo/bar.yaml', // E.g. read from YAML file...
transform: async (object) => { // ...with exchanging value...
object.foo = 'new value';
return object;
@@ -147,7 +149,6 @@ transform(options)
// ---- async/await style:
-
try {
const msg = await transform(options); // Transform, of course, inside an async.
console.log(msg); // Success message!
@@ -161,11 +162,19 @@ try {
```javascript
import { read } from 'jy-transform';
-const options = { src: 'foo/bar.yaml' }; // Here: read from file.
+const options = { src: 'foo/bar.yaml' }; // E.g. read from file.
+
+// ---- Promise style:
+
+read(options)
+ .then((object) => console.log(JSON.stringify(object))) // Print read object.
+ .catch(console.error);
+
+// ---- async/await style:
try {
const object = await read(options);
- console.log(JSON.stringify(object)); // Print write success message.
+ console.log(JSON.stringify(object)); // Print read object.
} catch (err) {
console.error(err.stack);
}
@@ -176,11 +185,19 @@ try {
```javascript
import { write } from 'jy-transform';
-const options = { dest: 'foo/bar.yaml' }; // Here: write to file.
+const options = { dest: 'foo/bar.yaml' }; // E.g. write to file.
+
+// ---- Promise style:
+
+write(object, options)
+ .then(console.log) // Print write success message.
+ .catch(console.error);
+
+// ---- async/await style:
try {
const msg = await write(object, options);
- console.log(msg); // Print write success message.
+ console.log(msg); // Print write success message.
} catch (err) {
console.error(err.stack);
}
@@ -197,7 +214,7 @@ types into each other format.
## Usage
The module can be used on CLI or as API (the latter is fully
-[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) based).
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)/`async` based).
### Usage Types
@@ -213,9 +230,9 @@ Both usage types are described in more detail in the following sections.
So, what are the typical use cases for this module? In terms of _transformation_
these consists of different phases:
-- Reading files (`Reader`)
-- Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects (`Transformer` + `Middleware`)
-- Writing files (`Writer`)
+ 1. Reading from source
+ 2. Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects
+ 3. Writing to a destination
#### Reading From
@@ -226,17 +243,18 @@ these consists of different phases:
Additionally, on API level from a:
- `stream.Readable`
- - Contain serialized JS, JSON or YAML
- - If not file stream it requires `options.origin` property set
- - Reads as UTF-8
+ - Contain serialized JS, JSON or YAML
+ - If not file stream it requires `options.origin` property set
+ - Reads as UTF-8
- JS `object`
- - Actually, this means the reading phase is "skipped", because object is in-memory already
- - Of course, this case _cannot_ not be applied to serialized JSON or YAML content
+ - Actually, this means the reading phase is "skipped", because object is in-memory already
+ - Of course, this case _cannot_ not be applied to serialized JSON or YAML content
-#### Transformation [+ Middleware]
+#### Transformation
The _transformation_ is usually a format change, but can also be refer to content changes on the
-intermediate JS object (the latter via _middleware_). All possible directions are:
+intermediate JS object, the latter with the help of a configured `transform` callback function.
+All possible directions are:
- YAML ⇒ JS
- YAML ⇒ JSON
@@ -254,8 +272,8 @@ while:
- [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript) = _*.js_ (JS object)
- [JSON](http://json.org) = _*.json_ (JS object serialized as JSON)
-As mentioned above a _middleware_ can apply particular actions on the intermediate JS object via injected functions.
-This is an optional part for [transformation](#transformation) phase.
+As mentioned above the configured `transform` callback can apply particular actions on the intermediate JS object, but
+this is an optional part for [transformation](#transformation) phase.
#### Writing To
@@ -266,12 +284,12 @@ This is an optional part for [transformation](#transformation) phase.
Additionally, on API level to a:
- `stream.Writable`
- - Serialized JS, JSON and YAML
- - Requires `options.target` property set
- - Writes UTF-8
+ - Serialized JS, JSON and YAML
+ - Requires `options.target` property set
+ - Writes UTF-8
- JS `object
- - JS as simple reference
- - YAML and JSON as serialized string
+ - JS as simple reference
+ - YAML and JSON as serialized string
### Limitations
@@ -313,7 +331,7 @@ Additionally, on API level to a:
### CLI Usage
The CLI provides the `jyt` command which requires the use of some options.
-After the global installation you can access the `Transformer`'s command options
+After the global installation you can access the command options
with the usual `--help` option which prints an overview about all
available CLI properties:
@@ -348,7 +366,8 @@ The ARGS are more formally defined in the following table:
| `INPUT-FILE` | URI | The source file path for transformation. | - | yes |
| `OUTPUT-FILE` | URI | The destination file path to transform to. | When this options is omitted then the output file is stored relative to the input file (same base name but with another extension if type differs). If input and output type are the same then the file overwriting is handled depending on the `--force` value! | no |
-**NOTE:** the input file has to be specified and should be _first_ argument (in fact, it can be anywhere but it must be before an out file argument)!
+> **NOTE:** the _input file_ has to be specified and should be _first_ argument (in fact, it can be
+> anywhere but it must be _before_ an _output file_ argument)!
#### CLI Options
@@ -367,18 +386,15 @@ The OPTIONS are more formally defined in the following table:
| `-v` | `--version` | n/a | Display the current version. | n/a | no |
| `-h` | `--help` | n/a | Display help and usage details. | n/a | no |
+### Examples
-**NOTE:** an invalid indentation setting (1 > `-i`, `--indent` > 8) does not raise an error but a default of 4 SPACEs is applied instead.
-
-#### Examples
-
-Now we know which properties can be applied on CLI, so let's assume we
+Now we know which properties can be applied on CLI it's time for some examples. Let's assume we
have a YAML content located in _foo.yaml_ holding this data:
```yaml
foo: bar
```
-##### Example: YAML ⇒ JSON
+#### Example: YAML ⇒ JSON
Then we can transform it to a JSON content as _foo.json_ file:
@@ -390,18 +406,19 @@ Then we can transform it to a JSON content as _foo.json_ file:
simply by using this command:
-```
+```text
$ jyt foo.yaml -t json -i 4
```
-In this example we have overwritten the standard target type (which is `js`)
-and applying an indent of 4 SPACEs instead of the default (2). As default the output
+In this example we have overwritten the standard _target_ type (which is `js`)
+and applying an _indent_ of 4 SPACEs instead of the default (which is 2). As default the output
file _foo.json_ is written relative to the input file (by omitting the
`dest` option here).
-**NOTE:** here you _have_ to provide the target with option `-t json` or else the
-default `js` would have been applied! If the source would have been a `js`
-type like
+> **NOTE:** here you _have_ to provide the target with option `-t json` or else the
+> default `js` would have been applied!
+
+If the source would have been a `js` type like in this example
```
$ jyt foo.js -t json -i 4
@@ -410,9 +427,11 @@ $ jyt foo.js -t json -i 4
then the `js` value for `origin` is automatically inferred from file extension.
Accordingly, this is also true for the `target` option.
-##### Example: JSON ⇒ JS
+#### Example: JSON ⇒ JS
+
The command
-```
+
+```text
$ jyt foo.json -i 4
```
results in _foo.js_:
@@ -422,34 +441,42 @@ module.exports = {
}
```
-##### Example: JS ⇒ YAML
+#### Example: JS ⇒ YAML
+
The command
-```
+
+```text
$ jyt foo.js -t yaml
```
+
results in _foo.yaml_:
+
```yaml
foo: bar
```
-##### Example: Transformation with Different Destination
+#### Example: Transformation with Different Destination
Simply specify the _output_ file with a different file name:
-```
+
+```text
$ jyt foo.json results/foobar.yaml
```
-##### Example: Transformation with Unsupported Source File Extension
+#### Example: Transformation with Unsupported Source File Extension
As said, normally we infer from file extension to the type, but assume the source
file has a file name which does not imply the type (here a JSON
type in a TEXT file), then you can simply provide the `-o` option with the
-correct `origin` type (of course, the `-t` option works analogous):
-```
+correct `origin` type:
+
+```text
$ jyt foo.txt foobar.yaml -o json
```
-##### Example: Read from File with Exports Identifier
+> **NOTE:** of course, the `-t` (`--target`) option works analogous.
+
+#### Example: Read from File with Exports Identifier
It could be that a JS source `exports` several objects and you want to read
from exactly the one you specify, then provide the `-m` (`--imports`) option.
@@ -466,81 +493,90 @@ module.exports.bar = {
};
```
but you want to convert only `bar` object, then call:
-```
+
+```text
$ jyt foo.js bar.yaml -m bar
```
+
to get the YAML result:
+
```yaml
bar: foo
```
-**NOTE:** the same applies on API level when using JS objects as `dest`:
-
-```javascript
-const fooBar = {
- foo: 'bar',
- bar: 'foo'
-};
-
-const options = {
- src: fooBar,
- dest: {},
- exports: 'bar'
-};
-
-//...transform
-```
-
-The transformation will result in this in-memory object:
-
-```javascript
-bar: {
- foo: 'bar',
- bar: 'foo'
-}
-```
-Of course, as sub-node of `options.dest`.
-
-##### Example: Write Exports Identifier for JS File
+> **NOTE:** the same applies on API level when using JS objects as `dest`:
+>
+> ```javascript
+> const fooBar = {
+> foo: 'bar',
+> bar: 'foo'
+> };
+>
+> const options = {
+> src: fooBar,
+> dest: {},
+> exports: 'bar'
+> };
+
+> //...transform
+> ```
+>
+> The transformation will result in this in-memory object:
+>
+> ```javascript
+> bar: {
+> foo: 'bar',
+> bar: 'foo'
+> }
+> ```
+>
+> Of course, as sub-node of `options.dest`.
+
+#### Example: Write Exports Identifier for JS File
Assume you want to generate a JS file with an exports string which gets an
identifier. We reuse the YAML file from above:
+
```yaml
foo: bar
```
+
using this command:
+
```
$ jyt foo.yaml foobar.js -x foobar
```
+
This generates the following output in JS file using `foobar` as identifier:
+
```javascript
module.exports.foobar = {
foo: "bar"
}
```
-**NOTE:** the identifier must be a valid JS identifier accoding to ECMAScript 6
-(see also [Valid JavaScript variable names in ECMAScript 6](https://mathiasbynens.be/notes/javascript-identifiers-es6)
-and [Generating a regular expression to match valid JavaScript identifiers](https://mathiasbynens.be/demo/javascript-identifier-regex)).
+> **NOTE:** the identifier must be a valid JS identifier accoding to ECMAScript 6
+> (see also [Valid JavaScript variable names in ECMAScript 6](https://mathiasbynens.be/notes/javascript-identifiers-es6)
+> and [Generating a regular expression to match valid JavaScript identifiers](https://mathiasbynens.be/demo/javascript-identifier-regex)).
-##### Example: Force Overwriting
+#### Example: Force Overwriting
-**IMPORTANT NOTE:** when using this feature then any subsequent
-execution which uses the same target/file name,
-will overwrite the original source or target created beforehand!
+> **IMPORTANT NOTE:** when using this feature then any subsequent execution which
+> uses the same target/file name, can _overwrite_ the original source or target created beforehand!
-By default this feature is not enabled to prevent you from accidentally
+Therefore, this feature is _not_ enabled by default to prevent you from accidentally
overwriting your input source or already generated targets.
But let's say we want to overwrite the original source now because you want
to change the indentation from 2 to 4 SPACEs, then we can do this as follows:
+
+```text
+$ jyt foo.js -i 4 -f
```
-$ jyt foo.js -f
-```
-Of course, leaving out the `-f` switch creates a new file relatively to
-the `origin`, named as _foo(1).js_ (note the consecutive number). Naturally,
-another run of the command would result in a file called _foo(2).js_
-and so forth.
+
+> **NOTE:** the other way round (i.e. leaving out the `-f` (`--force`)) switch would create a _new file_ relatively to
+> the `src` _foo.js_, named as _foo(1).js_; note the consecutive number! Naturally,
+> another run of the command would result in a file called _foo(2).js_ and so forth.
### Origin and Target Type Inference
@@ -554,8 +590,7 @@ extensions. This is supported as shown by the following table (from-to):
| _*.js_ | _js_ |
| _*.json_ | _json_ |
-**NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to
-specify the origin or target type!
+> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
### API Usage
@@ -564,12 +599,12 @@ Since the usage on CLI is a 2-step process:
1. Read from source file to JS object ⇒
2. Write out (maybe to other type)
-the direct API calls additionally provide the usage of a _middleware_ function
-where you can alter the input JS object before it is written and therefore, which turns
+the direct API calls additionally provide the optional usage of a `transform` function
+where you can alter the intermediate JS object before it is written and therefore, turns
this into a 3-step process:
1. Read from source ⇒
- 2. Alter the JS object ⇒
+ 2. Transform the JS object ⇒
3. Write out (maybe to other type)
For more details about this and all the functions provided by this module please refer to the
@@ -579,97 +614,85 @@ The `origin` and `target` type inference is also standard for the API level.
#### API Properties
-The `Transformer` exposes the following function which takes besides an (optional)
-`middleware` function the necessary `options` for the transformation:
+The public `transform` function (that does not mean the optional `transform `callback here!) takes
+the necessary `options` for the transformation:
```javascript
-async function transform(options, middleware)
+async function transform(options)
```
-#### Options
-
-The `options` object has to follow this key-values tables:
+> **HINT:** of course, if you like you can use the `read`and `write` functionality solely besides any transformation needs.
-##### Reader Options
-
-| Option | Type | Description | Default | Required |
-| --- | --- | --- | --- | --- |
-| `origin` | _String_ | The origin type. | If not given, the type is tried to be inferred from the extension of source path, else it is _yaml_. | no |
-| `target` | _String_ | The target type. | If not given, the type is tried to be inferred from the extension of destination path, else it is _js_. | no |
-| `src` | [ _String_ | _Stream.Readable_ | _Object_ ] | The source information object: `String` is used as file path, `Stream.Readable` provides a stringified source and `object` is used as direct JS source. | - | yes |
-
-##### Writer Options
-
-| Option | Type | Description | Default | Required |
-| --- | --- | --- | --- | --- |
-| `dest` | [ _String_ | _Stream.Writable_ | _Object_ ] | The destination information object: `String` is used as file path, `Stream.Writable` writes a stringified source and `object` is used for direct JS object assignment of the (stringified or JS object) source. If a string is set as file path then the output and if input and output file path are the same, then the file overwriting is handled depending on the `force` value! | - | yes |
-| `indent` | _Number_ | The indentation in files. | 2 | no |
-| `force` | _Boolean_ | Force overwriting of existing output files on write phase. When files are not overwritten, then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in case of _foo.yaml_ it would be _foo(1).yaml_. | _false_ | no |
-| `imports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (to read from JS _source_ only, must be a valid JS identifier!) | _undefined_ | no |
-| `exports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (for usage in JS _destination_ only, must be a valid JS identifier!) | _undefined_ | no |
+#### Options
-##### Transformer Options
+For a detailed description see:
-These are a combination of the [Reader](#reader-options) and [Writer](#writer-options) Options.
+- [Read Options](API-PUBLIC.md#readoptions--codeobjectcode)
+- [Write Options](API-PUBLIC.md#writeoptions--codeobjectcode)
+- [Transform Options](API-PUBLIC.md#transformoptions--codeobjectcode)
##### Example
```javascript
const options = {
- origin: 'json',
- target: 'yaml',
src: 'foo.json',
+ origin: 'json', // actually, not needed here, inferred from src's extension automatically!
dest: './foo/bar.yaml',
+ target: 'yaml', // actually, not needed here, inferred from dest's extension automatically!
indent: 4
}
```
-#### Using Middleware
+#### Using Transform Callback
+
+The `transform` property is optional but if provided it must be of type `Function` and could but must not be
+a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)/`async`.
+
+- When being a Promise it has to resolve with the `data` object or reject with an `Error` based object.
+- In case of normal or `async` function return `data` or throw an `Error`.
-The `middleware` is optional but if provided it must be of type `Function` and
-a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
One of the easiest ones is the identity function
_f(data) → data_
-which could be expressed as [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
-function as follows:
+which could be expressed as follows:
```javascript
-const identity = async (data) => {
- return data;
-}
+const identity = data => data;
```
Of course, this would have no effect on the provided JS data. Actually, this one is
-used internally when no middleware is provided to ensure the proper promised
+used internally as default when no `transform` function is configured to ensure the proper
control flow.
-OK, lets go back to a more practical example, e.g. we want to alter the value of
+OK, lets go back to a more practical example, e.g. we want to alter the value of a
JS property before it is written to a file. Assuming we have this piece of YAML
-object as input:
+as input from a file called _src.yaml_:
```yaml
foo: old bar
```
-Applying this [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
-as middleware
+Applying this `transform` callback option to the `src` content
```javascript
import { transform } from 'jy-transform';
-const middleware = async (data) => {
- data.foo = 'new bar';
- return data;
+const options = {
+ src: 'src.yaml',
+ dest: 'result.json',
+ transform: async (data) => {
+ data.foo = 'new bar';
+ return data;
+ }
};
-transform(options, middleware)
+transform(options)
.then(console.log)
.catch(console.error);
```
-will result in such JSON file:
+will result in such JSON file content:
```json
{
@@ -687,43 +710,44 @@ Let's assume we have some Promise functions to apply. For simplicity reasons we
simulate these for the moment by some functions, each adding a key-value to the
given (initially empty) JS object.
-**NOTE:** each of them has to resolve with the `data` object!
+> **NOTE:** each of them has to resolve with the `object` object!
```javascript
-const key1 = async (data) => {
- odata.key1 = 'value1';
- return data;
+const key1 = async (object) => {
+ object.key1 = 'value1';
+ return object;
};
-const key2 = async (data) => {
- data.key2 = 'value2';
- return data;
+const key2 = async (object) => {
+ object.key2 = 'value2';
+ return object;
};
-const key3 = async (data) => {
- data.key3 = 'value3';
- return data;
+const key3 = async (object) => {
+ object.key3 = 'value3';
+ return object;
};
```
These can be collected by different aggregation or composition functions of the underlying
Promise framework, e.g. using the [`Promise.all([...])`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
-function. This one can collect all three functions above and ensure their proper subsequent execution:
+function. This one can collect all three functions above and ensure their proper execution:
```javascript
import { transform } from 'jy-transform';
-const middleware = (data) => {
- return Promise.all([key1(data), key2(data), key3(data)])
- .then(result => result[result.length - 1]);
+const options = {
+ src: {},
+ transform: async (object) => Promise.all([key1(object), key2(object), key3(object)])
+ .then(result => result[result.length - 1])
};
-return transform({ src: {} }, middleware)
+transform(options)
.then(console.log)
.catch(console.error);
```
-Then the result in the `middleware` function can be retrieved from the returned
+The result in the `transform` function can be retrieved from the returned
array, i.e. in case of [`Promise.all([...])`](http://bluebirdjs.com/docs/api/promise.all.html)
you have to pick the _last_ element which contains the "final product".
@@ -737,26 +761,24 @@ From our example above it would be result in this object
}
```
-which then is passed back to the transformation chain. Following this pattern
+which is passed back to the transformation chain. Following this pattern
you can do almost everything with the JS object, like
-- deleting properties
-- changing properties to other types
-- validating and throwing error if not valid
+- Deleting properties
+- Changing properties to other types
+- Validating and throwing/resolving with error if not valid
- ...
-Whatever you do during transformation, just keep it valid ;-)
-
## API Reference
For more details on how to use the API, please refer to the
-[API Reference](https://github.com/deadratfink/jy-transform/wiki/API-v3)
+[API Reference](https://github.com/deadratfink/jy-transform/wiki/API-public-v3)
wiki which describes the full API and provides more examples.
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an
-[issue](https://github.com/deadratfink/jy-transform/issues).
+[issue](https://github.com/deadratfink/jy-transform/issues) or create a PR.
See the wiki [Contributing](https://github.com/deadratfink/jy-transform/wiki/Contributing)
section for more details about conventions.
diff --git a/jyt b/jyt
index e15fef3..c86e3b2 100755
--- a/jyt
+++ b/jyt
@@ -1,3 +1,4 @@
#!/usr/bin/env node
+// eslint-disable-next-line import/no-commonjs
require('./lib/cli');
diff --git a/package.json b/package.json
index 7980b12..fac4177 100644
--- a/package.json
+++ b/package.json
@@ -21,11 +21,10 @@
"private": false,
"scripts": {
"build": "NODE_ENV=production babel src --out-dir lib --copy-files --source-maps",
- "doc": "cat docs/LOGO.md > README.md && cat docs/BADGES.md >> README.md && cat docs/TOC.md >> README.md && package-json-to-readme --no-footer ./package.json >> README.md && cat docs/USAGE.md >> README.md && echo '\n# Changelog\n' >> README.md && cat docs/CHANGELOG.md >> README.md && doctoc README.md --github --title '# TOC' --maxlevel 2",
"readme": "bin/create-readme.sh -a true -c false -m true -l false",
"wiki": "jsdoc2md ./jyt lib/*.js index.js > docs/API.md && doctoc docs/API.md --github --title '### TOC' --maxlevel 2 && cat docs/API.md > '../jy-transform.wiki/API-v2.md' && cat docs/CONTRIBUTING.md > ../jy-transform.wiki/Contributing.md && cat docs/CHANGELOG.md > ../jy-transform.wiki/Changelog.md && doctoc ../jy-transform.wiki/Changelog.md --github --title '### TOC' --maxlevel 3",
"pretest": "mkdir -pv test/tmp",
- "test": "JYT_DEBUG=false JYT_ERROR=false jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
+ "test": "jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
"eslint": "eslint .",
"nsp": "nsp check",
"inch": "inchjs suggest && inchjs list --all && inchjs stats"
@@ -41,7 +40,7 @@
"json-stringify-safe": " ~5.0.1",
"mkdirp-then": " ~1.2.0",
"promisify-es6": "~1.0.2",
- "serialize-js": " ~1.1.0"
+ "serialize-js": "deadratfink/serialize-js#feature/single_quote_only"
},
"devDependencies": {
"babel-cli": "~6.24.1",
diff --git a/readme/BADGES.md b/readme/BADGES.md
index e90bae4..1dcc8f8 100644
--- a/readme/BADGES.md
+++ b/readme/BADGES.md
@@ -13,11 +13,12 @@
[![bitHound Code][bithound-code-image]][bithound-url]
[![bitHound Dependencies][bitHound-dependencies-image]][bitHound-dependencies]
[![bitHound Dev Dependencies][bitHound-dev-dependencies-image]][bitHound-dependencies]
+[![Codacy Badge](https://img.shields.io/codacy/grade/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Grade)
+[![Codacy Badge](https://img.shields.io/codacy/coverage/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Coverage)
+[![Greenkeeper badge](https://badges.greenkeeper.io/deadratfink/jy-transform.svg?style=flat)](https://greenkeeper.io/)
[![NSP Status][nsp-image-master]][nsp-url-master]
-[![Codacy Badge](https://img.shields.io/codacy/grade/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat-square)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Grade)
-[![Codacy Badge](https://img.shields.io/codacy/coverage/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat-square)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Coverage)
+[![bitHound Overall Score](https://www.bithound.io/github/deadratfink/jy-transform/badges/score.svg?style=flat)](https://www.bithound.io/github/deadratfink/jy-transform) -->
@@ -25,54 +26,54 @@
[![NPM][npm-image]][npm-url]
[![NPM][npm-downloads-image]][npm-url]
-[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat-square
+[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat
[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
-[gh-issues-image]: https://img.shields.io/github/issues/deadratfink/jy-transform.svg?style=flat-square
+[gh-issues-image]: https://img.shields.io/github/issues/deadratfink/jy-transform.svg?style=flat
[gh-issues-url]: https://github.com/deadratfink/jy-transform/issues
-[gh-releases-image]: https://img.shields.io/github/release/deadratfink/jy-transform.svg?style=flat-square
+[gh-releases-image]: https://img.shields.io/github/release/deadratfink/jy-transform.svg?style=flat
[gh-releases-url]: https://github.com/deadratfink/jy-transform/releases
-[gh-tags-image]: https://img.shields.io/github/tag/deadratfink/jy-transform.svg?style=flat-square
+[gh-tags-image]: https://img.shields.io/github/tag/deadratfink/jy-transform.svg?style=flat
[gh-tags-url]: https://github.com/deadratfink/jy-transform/tags
-[ci-image]: https://img.shields.io/travis/deadratfink/jy-transform.svg?style=flat-square
+[ci-image]: https://img.shields.io/travis/deadratfink/jy-transform.svg?style=flat
[ci-url]: https://travis-ci.org/deadratfink/jy-transform/branches
-[is-pull-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/pr?style=flat-square
-[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat-square
+[is-pull-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/pr?style=flat
+[is-issue-image]: http://issuestats.com/github/deadratfink/jy-transform/badge/issue?style=flat
[is-url]: http://issuestats.com/github/deadratfink/jy-transform
-[waffle-ready-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat-square
-[waffle-waffle-in-progress-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=in%20progress&title=Waffle%20In%20Progress&style=flat-square
+[waffle-ready-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=ready&title=Waffle%20Ready&style=flat
+[waffle-waffle-in-progress-image]: https://img.shields.io/waffle/label/deadratfink/jy-transform.svg?label=in%20progress&title=Waffle%20In%20Progress&style=flat
[waffle-url]: https://waffle.io/deadratfink/jy-transform
-[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat-square
+[cocl-image]: https://img.shields.io/codeclimate/github/deadratfink/jy-transform.svg?style=flat
[cocl-url]: https://codeclimate.com/github/deadratfink/jy-transform
-[cc-image-master]: https://img.shields.io/codecov/c/github/deadratfink/jy-transform/master.svg?style=flat-square
+[cc-image-master]: https://img.shields.io/codecov/c/github/deadratfink/jy-transform/master.svg?style=flat
[cc-url-master]: https://codecov.io/github/deadratfink/jy-transform?branch=master
-[ca-image-master]: https://img.shields.io/coveralls/deadratfink/jy-transform/master.svg?style=flat-square
+[ca-image-master]: https://img.shields.io/coveralls/deadratfink/jy-transform/master.svg?style=flat
[ca-url-master]: https://coveralls.io/github/deadratfink/jy-transform?branch=master
-[inch-image-master]: https://inch-ci.org/github/deadratfink/jy-transform.svg?branch=master&style=flat-square
+[inch-image-master]: https://inch-ci.org/github/deadratfink/jy-transform.svg?branch=master&style=flat
[inch-url-master]: https://inch-ci.org/github/deadratfink/jy-transform?branch=master
-[dep-image-master]: https://img.shields.io/david/deadratfink/jy-transform/master.svg?style=flat-square
+[dep-image-master]: https://img.shields.io/david/deadratfink/jy-transform/master.svg?style=flat
[dep-url-master]: https://david-dm.org/deadratfink/jy-transform/master
-[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat-square
+[devdep-image-master]: https://img.shields.io/david/dev/deadratfink/jy-transform/master.svg?style=flat
[devdep-url-master]: https://david-dm.org/deadratfink/jy-transform/master#info=devDependencies
-[nsp-image-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0/badge?style=flat-square
+[nsp-image-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0/badge?style=flat
[nsp-url-master]: https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0
-[node-version-image]: https://img.shields.io/node/v/jy-transform.svg?style=flat-square
+[node-version-image]: https://img.shields.io/node/v/jy-transform.svg?style=flat
[node-version-url]: http://nodejs.org/download/
[npm-image]: https://nodei.co/npm/jy-transform.png?downloads=true&downloadRank=true&stars=true
@@ -80,8 +81,8 @@
[npm-downloads-image]: https://nodei.co/npm-dl/jy-transform.png?height=2&months=9
[bithound-url]: https://www.bithound.io/github/deadratfink/jy-transform
-[bithound-code-image]: https://img.shields.io/bithound/code/github/deadratfink/jy-transform.svg?style=flat-square
+[bithound-code-image]: https://img.shields.io/bithound/code/github/deadratfink/jy-transform.svg?style=flat
[bitHound-dependencies]: https://www.bithound.io/github/deadratfink/jy-transform/master/dependencies/npm
-[bitHound-dependencies-image]: https://img.shields.io/bithound/dependencies/github/deadratfink/jy-transform.svg?style=flat-square
-[bitHound-dev-dependencies-image]: https://img.shields.io/bithound/devDependencies/github/deadratfink/jy-transform.svg?style=flat-square
-[bitHound-score-image]: https://img.shields.io/bithound/score/github/deadratfink/jy-transform.svg?style=flat-square
+[bitHound-dependencies-image]: https://img.shields.io/bithound/dependencies/github/deadratfink/jy-transform.svg?style=flat
+[bitHound-dev-dependencies-image]: https://img.shields.io/bithound/devDependencies/github/deadratfink/jy-transform.svg?style=flat
+[bitHound-score-image]: https://img.shields.io/bithound/score/github/deadratfink/jy-transform.svg?style=flat
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index c5b06f0..5833f57 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -6,7 +6,7 @@
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // Here: read from YAML file...
+ src: 'foo/bar.yaml', // E.g. read from YAML file...
transform: async (object) => { // ...with exchanging value...
object.foo = 'new value';
return object;
@@ -24,7 +24,6 @@ transform(options)
// ---- async/await style:
-
try {
const msg = await transform(options); // Transform, of course, inside an async.
console.log(msg); // Success message!
@@ -38,11 +37,19 @@ try {
```javascript
import { read } from 'jy-transform';
-const options = { src: 'foo/bar.yaml' }; // Here: read from file.
+const options = { src: 'foo/bar.yaml' }; // E.g. read from file.
+
+// ---- Promise style:
+
+read(options)
+ .then((object) => console.log(JSON.stringify(object))) // Print read object.
+ .catch(console.error);
+
+// ---- async/await style:
try {
const object = await read(options);
- console.log(JSON.stringify(object)); // Print write success message.
+ console.log(JSON.stringify(object)); // Print read object.
} catch (err) {
console.error(err.stack);
}
@@ -53,11 +60,19 @@ try {
```javascript
import { write } from 'jy-transform';
-const options = { dest: 'foo/bar.yaml' }; // Here: write to file.
+const options = { dest: 'foo/bar.yaml' }; // E.g. write to file.
+
+// ---- Promise style:
+
+write(object, options)
+ .then(console.log) // Print write success message.
+ .catch(console.error);
+
+// ---- async/await style:
try {
const msg = await write(object, options);
- console.log(msg); // Print write success message.
+ console.log(msg); // Print write success message.
} catch (err) {
console.error(err.stack);
}
@@ -74,7 +89,7 @@ types into each other format.
## Usage
The module can be used on CLI or as API (the latter is fully
-[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) based).
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)/`async` based).
### Usage Types
@@ -90,9 +105,9 @@ Both usage types are described in more detail in the following sections.
So, what are the typical use cases for this module? In terms of _transformation_
these consists of different phases:
-- Reading files (`Reader`)
-- Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects (`Transformer` + `Middleware`)
-- Writing files (`Writer`)
+ 1. Reading from source
+ 2. Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects
+ 3. Writing to a destination
#### Reading From
@@ -103,17 +118,18 @@ these consists of different phases:
Additionally, on API level from a:
- `stream.Readable`
- - Contain serialized JS, JSON or YAML
- - If not file stream it requires `options.origin` property set
- - Reads as UTF-8
+ - Contain serialized JS, JSON or YAML
+ - If not file stream it requires `options.origin` property set
+ - Reads as UTF-8
- JS `object`
- - Actually, this means the reading phase is "skipped", because object is in-memory already
- - Of course, this case _cannot_ not be applied to serialized JSON or YAML content
+ - Actually, this means the reading phase is "skipped", because object is in-memory already
+ - Of course, this case _cannot_ not be applied to serialized JSON or YAML content
-#### Transformation [+ Middleware]
+#### Transformation
The _transformation_ is usually a format change, but can also be refer to content changes on the
-intermediate JS object (the latter via _middleware_). All possible directions are:
+intermediate JS object, the latter with the help of a configured `transform` callback function.
+All possible directions are:
- YAML ⇒ JS
- YAML ⇒ JSON
@@ -131,8 +147,8 @@ while:
- [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript) = _*.js_ (JS object)
- [JSON](http://json.org) = _*.json_ (JS object serialized as JSON)
-As mentioned above a _middleware_ can apply particular actions on the intermediate JS object via injected functions.
-This is an optional part for [transformation](#transformation) phase.
+As mentioned above the configured `transform` callback can apply particular actions on the intermediate JS object, but
+this is an optional part for [transformation](#transformation) phase.
#### Writing To
@@ -143,12 +159,12 @@ This is an optional part for [transformation](#transformation) phase.
Additionally, on API level to a:
- `stream.Writable`
- - Serialized JS, JSON and YAML
- - Requires `options.target` property set
- - Writes UTF-8
+ - Serialized JS, JSON and YAML
+ - Requires `options.target` property set
+ - Writes UTF-8
- JS `object
- - JS as simple reference
- - YAML and JSON as serialized string
+ - JS as simple reference
+ - YAML and JSON as serialized string
### Limitations
@@ -190,7 +206,7 @@ Additionally, on API level to a:
### CLI Usage
The CLI provides the `jyt` command which requires the use of some options.
-After the global installation you can access the `Transformer`'s command options
+After the global installation you can access the command options
with the usual `--help` option which prints an overview about all
available CLI properties:
@@ -225,7 +241,8 @@ The ARGS are more formally defined in the following table:
| `INPUT-FILE` | URI | The source file path for transformation. | - | yes |
| `OUTPUT-FILE` | URI | The destination file path to transform to. | When this options is omitted then the output file is stored relative to the input file (same base name but with another extension if type differs). If input and output type are the same then the file overwriting is handled depending on the `--force` value! | no |
-**NOTE:** the input file has to be specified and should be _first_ argument (in fact, it can be anywhere but it must be before an out file argument)!
+> **NOTE:** the _input file_ has to be specified and should be _first_ argument (in fact, it can be
+> anywhere but it must be _before_ an _output file_ argument)!
#### CLI Options
@@ -244,18 +261,15 @@ The OPTIONS are more formally defined in the following table:
| `-v` | `--version` | n/a | Display the current version. | n/a | no |
| `-h` | `--help` | n/a | Display help and usage details. | n/a | no |
+### Examples
-**NOTE:** an invalid indentation setting (1 > `-i`, `--indent` > 8) does not raise an error but a default of 4 SPACEs is applied instead.
-
-#### Examples
-
-Now we know which properties can be applied on CLI, so let's assume we
+Now we know which properties can be applied on CLI it's time for some examples. Let's assume we
have a YAML content located in _foo.yaml_ holding this data:
```yaml
foo: bar
```
-##### Example: YAML ⇒ JSON
+#### Example: YAML ⇒ JSON
Then we can transform it to a JSON content as _foo.json_ file:
@@ -267,18 +281,19 @@ Then we can transform it to a JSON content as _foo.json_ file:
simply by using this command:
-```
+```text
$ jyt foo.yaml -t json -i 4
```
-In this example we have overwritten the standard target type (which is `js`)
-and applying an indent of 4 SPACEs instead of the default (2). As default the output
+In this example we have overwritten the standard _target_ type (which is `js`)
+and applying an _indent_ of 4 SPACEs instead of the default (which is 2). As default the output
file _foo.json_ is written relative to the input file (by omitting the
`dest` option here).
-**NOTE:** here you _have_ to provide the target with option `-t json` or else the
-default `js` would have been applied! If the source would have been a `js`
-type like
+> **NOTE:** here you _have_ to provide the target with option `-t json` or else the
+> default `js` would have been applied!
+
+If the source would have been a `js` type like in this example
```
$ jyt foo.js -t json -i 4
@@ -287,9 +302,11 @@ $ jyt foo.js -t json -i 4
then the `js` value for `origin` is automatically inferred from file extension.
Accordingly, this is also true for the `target` option.
-##### Example: JSON ⇒ JS
+#### Example: JSON ⇒ JS
+
The command
-```
+
+```text
$ jyt foo.json -i 4
```
results in _foo.js_:
@@ -299,34 +316,42 @@ module.exports = {
}
```
-##### Example: JS ⇒ YAML
+#### Example: JS ⇒ YAML
+
The command
-```
+
+```text
$ jyt foo.js -t yaml
```
+
results in _foo.yaml_:
+
```yaml
foo: bar
```
-##### Example: Transformation with Different Destination
+#### Example: Transformation with Different Destination
Simply specify the _output_ file with a different file name:
-```
+
+```text
$ jyt foo.json results/foobar.yaml
```
-##### Example: Transformation with Unsupported Source File Extension
+#### Example: Transformation with Unsupported Source File Extension
As said, normally we infer from file extension to the type, but assume the source
file has a file name which does not imply the type (here a JSON
type in a TEXT file), then you can simply provide the `-o` option with the
-correct `origin` type (of course, the `-t` option works analogous):
-```
+correct `origin` type:
+
+```text
$ jyt foo.txt foobar.yaml -o json
```
-##### Example: Read from File with Exports Identifier
+> **NOTE:** of course, the `-t` (`--target`) option works analogous.
+
+#### Example: Read from File with Exports Identifier
It could be that a JS source `exports` several objects and you want to read
from exactly the one you specify, then provide the `-m` (`--imports`) option.
@@ -343,81 +368,90 @@ module.exports.bar = {
};
```
but you want to convert only `bar` object, then call:
-```
+
+```text
$ jyt foo.js bar.yaml -m bar
```
+
to get the YAML result:
+
```yaml
bar: foo
```
-**NOTE:** the same applies on API level when using JS objects as `dest`:
-
-```javascript
-const fooBar = {
- foo: 'bar',
- bar: 'foo'
-};
-
-const options = {
- src: fooBar,
- dest: {},
- exports: 'bar'
-};
-
-//...transform
-```
-
-The transformation will result in this in-memory object:
-
-```javascript
-bar: {
- foo: 'bar',
- bar: 'foo'
-}
-```
-Of course, as sub-node of `options.dest`.
-
-##### Example: Write Exports Identifier for JS File
+> **NOTE:** the same applies on API level when using JS objects as `dest`:
+>
+> ```javascript
+> const fooBar = {
+> foo: 'bar',
+> bar: 'foo'
+> };
+>
+> const options = {
+> src: fooBar,
+> dest: {},
+> exports: 'bar'
+> };
+
+> //...transform
+> ```
+>
+> The transformation will result in this in-memory object:
+>
+> ```javascript
+> bar: {
+> foo: 'bar',
+> bar: 'foo'
+> }
+> ```
+>
+> Of course, as sub-node of `options.dest`.
+
+#### Example: Write Exports Identifier for JS File
Assume you want to generate a JS file with an exports string which gets an
identifier. We reuse the YAML file from above:
+
```yaml
foo: bar
```
+
using this command:
+
```
$ jyt foo.yaml foobar.js -x foobar
```
+
This generates the following output in JS file using `foobar` as identifier:
+
```javascript
module.exports.foobar = {
foo: "bar"
}
```
-**NOTE:** the identifier must be a valid JS identifier accoding to ECMAScript 6
-(see also [Valid JavaScript variable names in ECMAScript 6](https://mathiasbynens.be/notes/javascript-identifiers-es6)
-and [Generating a regular expression to match valid JavaScript identifiers](https://mathiasbynens.be/demo/javascript-identifier-regex)).
+> **NOTE:** the identifier must be a valid JS identifier accoding to ECMAScript 6
+> (see also [Valid JavaScript variable names in ECMAScript 6](https://mathiasbynens.be/notes/javascript-identifiers-es6)
+> and [Generating a regular expression to match valid JavaScript identifiers](https://mathiasbynens.be/demo/javascript-identifier-regex)).
-##### Example: Force Overwriting
+#### Example: Force Overwriting
-**IMPORTANT NOTE:** when using this feature then any subsequent
-execution which uses the same target/file name,
-will overwrite the original source or target created beforehand!
+> **IMPORTANT NOTE:** when using this feature then any subsequent execution which
+> uses the same target/file name, can _overwrite_ the original source or target created beforehand!
-By default this feature is not enabled to prevent you from accidentally
+Therefore, this feature is _not_ enabled by default to prevent you from accidentally
overwriting your input source or already generated targets.
But let's say we want to overwrite the original source now because you want
to change the indentation from 2 to 4 SPACEs, then we can do this as follows:
+
+```text
+$ jyt foo.js -i 4 -f
```
-$ jyt foo.js -f
-```
-Of course, leaving out the `-f` switch creates a new file relatively to
-the `origin`, named as _foo(1).js_ (note the consecutive number). Naturally,
-another run of the command would result in a file called _foo(2).js_
-and so forth.
+
+> **NOTE:** the other way round (i.e. leaving out the `-f` (`--force`)) switch would create a _new file_ relatively to
+> the `src` _foo.js_, named as _foo(1).js_; note the consecutive number! Naturally,
+> another run of the command would result in a file called _foo(2).js_ and so forth.
### Origin and Target Type Inference
@@ -431,8 +465,7 @@ extensions. This is supported as shown by the following table (from-to):
| _*.js_ | _js_ |
| _*.json_ | _json_ |
-**NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to
-specify the origin or target type!
+> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
### API Usage
@@ -441,12 +474,12 @@ Since the usage on CLI is a 2-step process:
1. Read from source file to JS object ⇒
2. Write out (maybe to other type)
-the direct API calls additionally provide the usage of a _middleware_ function
-where you can alter the input JS object before it is written and therefore, which turns
+the direct API calls additionally provide the optional usage of a `transform` function
+where you can alter the intermediate JS object before it is written and therefore, turns
this into a 3-step process:
1. Read from source ⇒
- 2. Alter the JS object ⇒
+ 2. Transform the JS object ⇒
3. Write out (maybe to other type)
For more details about this and all the functions provided by this module please refer to the
@@ -456,97 +489,85 @@ The `origin` and `target` type inference is also standard for the API level.
#### API Properties
-The `Transformer` exposes the following function which takes besides an (optional)
-`middleware` function the necessary `options` for the transformation:
+The public `transform` function (that does not mean the optional `transform `callback here!) takes
+the necessary `options` for the transformation:
```javascript
-async function transform(options, middleware)
+async function transform(options)
```
-#### Options
-
-The `options` object has to follow this key-values tables:
+> **HINT:** of course, if you like you can use the `read`and `write` functionality solely besides any transformation needs.
-##### Reader Options
-
-| Option | Type | Description | Default | Required |
-| --- | --- | --- | --- | --- |
-| `origin` | _String_ | The origin type. | If not given, the type is tried to be inferred from the extension of source path, else it is _yaml_. | no |
-| `target` | _String_ | The target type. | If not given, the type is tried to be inferred from the extension of destination path, else it is _js_. | no |
-| `src` | [ _String_ | _Stream.Readable_ | _Object_ ] | The source information object: `String` is used as file path, `Stream.Readable` provides a stringified source and `object` is used as direct JS source. | - | yes |
-
-##### Writer Options
-
-| Option | Type | Description | Default | Required |
-| --- | --- | --- | --- | --- |
-| `dest` | [ _String_ | _Stream.Writable_ | _Object_ ] | The destination information object: `String` is used as file path, `Stream.Writable` writes a stringified source and `object` is used for direct JS object assignment of the (stringified or JS object) source. If a string is set as file path then the output and if input and output file path are the same, then the file overwriting is handled depending on the `force` value! | - | yes |
-| `indent` | _Number_ | The indentation in files. | 2 | no |
-| `force` | _Boolean_ | Force overwriting of existing output files on write phase. When files are not overwritten, then the next transformation with same output file name gets a consecutive number on the base file name, e.g. in case of _foo.yaml_ it would be _foo(1).yaml_. | _false_ | no |
-| `imports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (to read from JS _source_ only, must be a valid JS identifier!) | _undefined_ | no |
-| `exports` | _String_ | Define a `module.exports[.identifier] = ...` identifier (for usage in JS _destination_ only, must be a valid JS identifier!) | _undefined_ | no |
+#### Options
-##### Transformer Options
+For a detailed description see:
-These are a combination of the [Reader](#reader-options) and [Writer](#writer-options) Options.
+- [Read Options](API-PUBLIC.md#readoptions--codeobjectcode)
+- [Write Options](API-PUBLIC.md#writeoptions--codeobjectcode)
+- [Transform Options](API-PUBLIC.md#transformoptions--codeobjectcode)
##### Example
```javascript
const options = {
- origin: 'json',
- target: 'yaml',
src: 'foo.json',
+ origin: 'json', // actually, not needed here, inferred from src's extension automatically!
dest: './foo/bar.yaml',
+ target: 'yaml', // actually, not needed here, inferred from dest's extension automatically!
indent: 4
}
```
-#### Using Middleware
+#### Using Transform Callback
+
+The `transform` property is optional but if provided it must be of type `Function` and could but must not be
+a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)/`async`.
+
+- When being a Promise it has to resolve with the `data` object or reject with an `Error` based object.
+- In case of normal or `async` function return `data` or throw an `Error`.
-The `middleware` is optional but if provided it must be of type `Function` and
-a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
One of the easiest ones is the identity function
_f(data) → data_
-which could be expressed as [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
-function as follows:
+which could be expressed as follows:
```javascript
-const identity = async (data) => {
- return data;
-}
+const identity = data => data;
```
Of course, this would have no effect on the provided JS data. Actually, this one is
-used internally when no middleware is provided to ensure the proper promised
+used internally as default when no `transform` function is configured to ensure the proper
control flow.
-OK, lets go back to a more practical example, e.g. we want to alter the value of
+OK, lets go back to a more practical example, e.g. we want to alter the value of a
JS property before it is written to a file. Assuming we have this piece of YAML
-object as input:
+as input from a file called _src.yaml_:
```yaml
foo: old bar
```
-Applying this [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
-as middleware
+Applying this `transform` callback option to the `src` content
```javascript
import { transform } from 'jy-transform';
-const middleware = async (data) => {
- data.foo = 'new bar';
- return data;
+const options = {
+ src: 'src.yaml',
+ dest: 'result.json',
+ transform: async (data) => {
+ data.foo = 'new bar';
+ return data;
+ }
};
-transform(options, middleware)
+transform(options)
.then(console.log)
.catch(console.error);
```
-will result in such JSON file:
+will result in such JSON file content:
```json
{
@@ -564,43 +585,44 @@ Let's assume we have some Promise functions to apply. For simplicity reasons we
simulate these for the moment by some functions, each adding a key-value to the
given (initially empty) JS object.
-**NOTE:** each of them has to resolve with the `data` object!
+> **NOTE:** each of them has to resolve with the `object` object!
```javascript
-const key1 = async (data) => {
- odata.key1 = 'value1';
- return data;
+const key1 = async (object) => {
+ object.key1 = 'value1';
+ return object;
};
-const key2 = async (data) => {
- data.key2 = 'value2';
- return data;
+const key2 = async (object) => {
+ object.key2 = 'value2';
+ return object;
};
-const key3 = async (data) => {
- data.key3 = 'value3';
- return data;
+const key3 = async (object) => {
+ object.key3 = 'value3';
+ return object;
};
```
These can be collected by different aggregation or composition functions of the underlying
Promise framework, e.g. using the [`Promise.all([...])`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
-function. This one can collect all three functions above and ensure their proper subsequent execution:
+function. This one can collect all three functions above and ensure their proper execution:
```javascript
import { transform } from 'jy-transform';
-const middleware = (data) => {
- return Promise.all([key1(data), key2(data), key3(data)])
- .then(result => result[result.length - 1]);
+const options = {
+ src: {},
+ transform: async (object) => Promise.all([key1(object), key2(object), key3(object)])
+ .then(result => result[result.length - 1])
};
-return transform({ src: {} }, middleware)
+transform(options)
.then(console.log)
.catch(console.error);
```
-Then the result in the `middleware` function can be retrieved from the returned
+The result in the `transform` function can be retrieved from the returned
array, i.e. in case of [`Promise.all([...])`](http://bluebirdjs.com/docs/api/promise.all.html)
you have to pick the _last_ element which contains the "final product".
@@ -614,26 +636,24 @@ From our example above it would be result in this object
}
```
-which then is passed back to the transformation chain. Following this pattern
+which is passed back to the transformation chain. Following this pattern
you can do almost everything with the JS object, like
-- deleting properties
-- changing properties to other types
-- validating and throwing error if not valid
+- Deleting properties
+- Changing properties to other types
+- Validating and throwing/resolving with error if not valid
- ...
-Whatever you do during transformation, just keep it valid ;-)
-
## API Reference
For more details on how to use the API, please refer to the
-[API Reference](https://github.com/deadratfink/jy-transform/wiki/API-v3)
+[API Reference](https://github.com/deadratfink/jy-transform/wiki/API-public-v3)
wiki which describes the full API and provides more examples.
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an
-[issue](https://github.com/deadratfink/jy-transform/issues).
+[issue](https://github.com/deadratfink/jy-transform/issues) or create a PR.
See the wiki [Contributing](https://github.com/deadratfink/jy-transform/wiki/Contributing)
section for more details about conventions.
diff --git a/src/cli.js b/src/cli.js
index 48a7399..5906e5b 100755
--- a/src/cli.js
+++ b/src/cli.js
@@ -10,7 +10,10 @@ import {
TARGET_DESCRIPTION,
TYPE_JS,
TYPE_JSON,
- TYPE_YAML
+ TYPE_YAML,
+ DEFAULT_STRICT,
+ DEFAULT_NO_ES6,
+ DEFAULT_NO_SINGLE_QUOTES,
} from './constants';
import { transform } from './transformer';
@@ -50,18 +53,24 @@ const packagePath = path.join(__dirname, '../package.json');
* @private
*/
const cliOptionsSchema = {
- origin: ['o', 'The origin type of INPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML
- + ' ]', 'string', ORIGIN_DESCRIPTION],
- target: ['t', 'The target type of OUTPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML
- + ' ]', 'string', TARGET_DESCRIPTION],
+ origin: ['o', 'The origin type of INPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML + ' ]',
+ 'string', ORIGIN_DESCRIPTION],
+ target: ['t', 'The target type of OUTPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML + ' ]',
+ 'string', TARGET_DESCRIPTION],
indent: ['i', 'The indention for pretty-print: 1 - 8', 'int', DEFAULT_INDENT],
force: ['f', 'Force overwriting of existing output files on write phase: when files are not overwritten (which' +
' is default), then the next transformation with same output file name gets a consecutive number on the base' +
' file name, e.g. in case of foo.yaml it would be foo(1).yaml', 'boolean', DEFAULT_FORCE_FILE_OVERWRITE],
- imports: ['m', 'Define a \'module.exports[.identifier] = \' identifier for object (to read from JS source file ' +
- 'only, must be a valid JS identifier!)', 'string', DEFAULT_JS_IMPORTS_IDENTIFIER],
- exports: ['x', 'Define a \'module.exports[.identifier] = \' identifier for object (to write in JS destination file ' +
- 'only, must be a valid JS identifier!)', 'string', DEFAULT_JS_EXPORTS_IDENTIFIER]
+ imports: ['m', 'Define an identifier for object (to read as "export const identifier / module.exports[.identifier]"' +
+ ' from JS source file only, must be a valid JS identifier!)', 'string', DEFAULT_JS_IMPORTS_IDENTIFIER],
+ exports: ['x', 'Define an identifier for object (write to "export const identifier / module.exports[.identifier]"' +
+ ' in JS destination file only, must be a valid JS identifier!)', 'string', DEFAULT_JS_EXPORTS_IDENTIFIER],
+ strict: ['s', 'Whether to write a "use strict;" in JS type output',
+ 'boolean', DEFAULT_STRICT],
+ 'no-es6': [false, 'Whether not to use ECMAScript6 syntax for JS type output like "module.exports" instead of ' +
+ '"export default", applicable only for JS output', 'boolean', DEFAULT_NO_ES6],
+ 'no-single': [false, 'Whether not to use single-quotes style for values in JS type output (i.e. double-quotes)',
+ 'boolean', DEFAULT_NO_SINGLE_QUOTES],
};
/**
diff --git a/src/constants.js b/src/constants.js
index 5ed1626..8c1aebc 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -105,6 +105,31 @@ export const DEFAULT_TARGET = TYPE_JS;
*/
export const DEFAULT_FORCE_FILE_OVERWRITE = false;
+/**
+ * Whether to write a "use strict;" in JS type output.
+ * @type {boolean}
+ * @constant
+ * @private
+ */
+export const DEFAULT_STRICT = false;
+
+
+/**
+ * Whether _not_ to use ECMAScript6 syntax for JS type output.
+ * @type {boolean}
+ * @constant
+ * @private
+ */
+export const DEFAULT_NO_ES6 = false;
+
+/**
+ * Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes).
+ * @type {boolean}
+ * @constant
+ * @private
+ */
+export const DEFAULT_NO_SINGLE_QUOTES = false;
+
/**
* The `origin` description value.
* @type {string}
diff --git a/src/io-utils.js b/src/io-utils.js
new file mode 100644
index 0000000..d5ff4c3
--- /dev/null
+++ b/src/io-utils.js
@@ -0,0 +1,219 @@
+import mkdirp from 'mkdirp-then';
+import path from 'path';
+import fs from 'fs';
+import { Buffer } from 'buffer';
+import jsYaml from 'js-yaml';
+import promisify from 'promisify-es6';
+import {
+ UTF8,
+ TYPE_JS,
+ TYPE_JSON,
+} from './constants';
+
+/**
+ * Promisified `fs` module.
+ * @private
+ */
+const fsPromisified = promisify(fs);
+
+/**
+ * @module jy-transform:io-utils
+ * @description This module provides an I/O interface for files, streams or `Object`.
+ * @private
+ */
+
+/**
+ * Reads JS or JSON from file.
+ *
+ * @param {string} file - The file path.
+ * @param {string} [imports] - An object which is exported in the file.
+ * @returns {Object} The read object.
+ * @throws {Error} When an `imports` is given but the declared object key is not exported by the file.
+ * @private
+ */
+export function readJsOrJsonFromFile(file, imports) {
+ const resolvedPath = path.resolve('', file);
+ if (imports) {
+ // eslint-disable-next-line import/no-dynamic-require, global-require
+ const object = require(resolvedPath)[imports];
+ if (!object) {
+ throw new Error('an identifier string \'' + imports + '\' was specified for JS object ' +
+ 'but could not find this object, pls ensure that file ' + file + ' exports it.');
+ }
+ return object;
+ }
+ // eslint-disable-next-line import/no-dynamic-require, global-require
+ return require(resolvedPath); // reads both: JS and JSON!
+}
+
+/**
+ * Reads JS from JS object.
+ *
+ * @param {string} object - The JS object source.
+ * @param {string} [imports] - An object which is is a sub-object in `object`.
+ * @returns {Object} The given `object` object or any sub-object specified by `imports`.
+ * @throws {Error} When an `imports` is given but the declared object key is not contained in the source object.
+ * @private
+ */
+export function readJsFromObject(object, imports) {
+ if (imports) {
+ const subObject = object[imports];
+ if (!subObject) {
+ throw new Error('an identifier string \'' + imports + '\' was specified for JS sub-object ' +
+ 'but could not find this sub-object, pls ensure that object source contains it.');
+ }
+ return Object.assign({}, subObject); // clone, do not alter original object!
+ }
+ return Object.assign({}, object); // clone, do not alter original object!
+}
+
+/**
+ * Reads YAML from file.
+ *
+ * @param {string} file - The YAML file source.
+ * @returns {Object} The read JS object from YAML file.
+ * @throws {Error} When any I/O error occurs while the source file.
+ * @private
+ */
+export async function readYamlFromfile(file) {
+ // load source from YAML file
+ const yaml = await fsPromisified.readFile(file, UTF8);
+ try {
+ return jsYaml.safeLoad(yaml); // TODO promisify???
+ } catch (err) { // probably a YAMLException
+ throw err;
+ }
+}
+
+/**
+ * Reads from a passed stream and resolves by callback.
+ *
+ * @param {Stream.Readable} readable - The source to read from.
+ * @param {string} origin - Origin type, must be 'yaml' or 'json'/'js'.
+ * @returns {Promise.} The read content as JS object representation.
+ * @see {@link TYPE_YAML}
+ * @see {@link TYPE_JSON}
+ * @see {@link TYPE_JS}
+ * @private
+ */
+export function readFromStream(readable, origin) {
+ return new Promise((resolve, reject) => {
+ const buffers = [];
+ readable
+ .on('data', data => buffers.push(data))
+ .on('error', reject)
+ .on('end', () => {
+ const buffer = Buffer.concat(buffers);
+ try {
+ if (origin === TYPE_JS || origin === TYPE_JSON) {
+ resolve(JSON.parse(buffer.toString(UTF8)));
+ } else { // Validation allows only YAML here!
+ resolve(jsYaml.safeLoad(buffer.toString(UTF8)));
+ }
+ } catch (err) { // probably a SyntaxError for JSON or a YAMLException
+ readable.emit('error', err); // send to .on('error',...
+ }
+ });
+ });
+}
+
+/**
+ * Turns the destination file name into a name containing a consecutive
+ * number if it exists. It iterates over the files until it finds a file
+ * name which does not exist.
+ *
+ * @param {string} dest - The destination file.
+ * @returns {string} A consecutive file name or the original one if `dest` file does not exist.
+ * @private
+ */
+function getConsecutiveDestName(dest) {
+ let tmpDest = dest;
+ let i = 0;
+ const destDirName = path.dirname(tmpDest);
+ const ext = path.extname(tmpDest);
+ const basename = path.basename(tmpDest, ext);
+ while (fs.existsSync(tmpDest)) {
+ tmpDest = path.join(destDirName, basename + '(' + (i += 1) + ')' + ext);
+ }
+ return tmpDest;
+}
+
+/**
+ * Ensures that all dirs exists for file type `dest` and writes the JS object to file.
+ *
+ * @param {string} object - The object to write into file.
+ * @param {string} dest - The file destination path.
+ * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
+ * @param {boolean} [forceOverwrite=false] - Forces overwriting the destination file if `true`.
+ * @see {@link TYPE_YAML}
+ * @see {@link TYPE_JSON}
+ * @see {@link TYPE_JS}
+ * @private
+ */
+async function mkdirAndWrite(object, dest, target, forceOverwrite = false) {
+ const destDir = path.dirname(dest);
+ await mkdirp(destDir);
+ let finalDestination = dest;
+ if (!forceOverwrite) {
+ finalDestination = getConsecutiveDestName(dest);
+ }
+ await fsPromisified.writeFile(finalDestination, object, UTF8);
+ return 'Writing \'' + target + '\' file \'' + finalDestination + '\' successful.';
+}
+
+/**
+ * Writes a serialized object to file.
+ *
+ * @param {string} object - The object to write into file.
+ * @param {string} dest - The file destination path.
+ * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
+ * @param {boolean} [forceOverwrite] - Forces overwriting the destination file if `true`.
+ * @see {@link TYPE_YAML}
+ * @see {@link TYPE_JSON}
+ * @see {@link TYPE_JS}
+ * @returns {Promise.} Containing the write success message to handle by caller (e.g. for logging).
+ * @throws {Error} If serialized JSON file could not be written due to any reason.
+ * @private
+ */
+export function writeToFile(object, dest, target, forceOverwrite) {
+ return new Promise((resolve, reject) => {
+ fsPromisified.stat(dest)
+ .then((stats) => {
+ if (stats.isDirectory()) {
+ reject(new Error('Destination file is a directory, pls specify a valid file resource!'));
+ return;
+ }
+ // file exists
+ resolve(mkdirAndWrite(object, dest, target, forceOverwrite));
+ })
+ .catch(() => {
+ // ignore error (because file could possibly not exist at this point of time)
+ resolve(mkdirAndWrite(object, dest, target, forceOverwrite));
+ });
+ });
+}
+
+/**
+ * Writes a string serialized data object to a stream.
+ *
+ * @param {string} object - The data to write into stream.
+ * @param {string} dest - The stream destination.
+ * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
+ * @see {@link TYPE_YAML}
+ * @see {@link TYPE_JSON}
+ * @see {@link TYPE_JS}
+ * @returns {Promise.} Containing the write success message to handle by caller (e.g. for logging).
+ * @throws {Error} If serialized JS object could not be written due to any reason.
+ * @private
+ */
+export function writeToStream(object, dest, target) {
+ return new Promise((resolve, reject) => {
+ dest
+ .on('error', reject)
+ .on('finish', () => resolve('Writing ' + target + ' to stream successful.'));
+
+ // write stringified data
+ dest.write(object);
+ dest.end();
+ });
+}
diff --git a/src/reader.js b/src/reader.js
index 40872aa..6ed060d 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -1,13 +1,13 @@
-import jsYaml from 'js-yaml';
-import promisify from 'promisify-es6';
-import { Buffer } from 'buffer';
-import path from 'path';
-import fs from 'fs';
import isStream from 'is-stream';
import { readOptionsSchema } from './validation/options-schema';
import Joi from './validation/joi-extensions';
import {
- UTF8,
+ readJsFromObject,
+ readJsOrJsonFromFile,
+ readYamlFromfile,
+ readFromStream,
+} from './io-utils';
+import {
TYPE_YAML,
TYPE_JS,
TYPE_JSON,
@@ -15,46 +15,10 @@ import {
/**
* @module jy-transform:reader
- * @description This module provides the _read_ functionality for YAML, JS or JSON sources.
- * @private
- */
-
-/**
- * Promisified `fs` module.
+ * @description This module provides the _public_ interface for the _read_ functionality of YAML, JS or JSON sources
+ * (file, `Object` or {@link stream.Readable}).
* @private
*/
-const fsPromisified = promisify(fs);
-
-/**
- * Reads from a passed stream and resolves by callback.
- *
- * @param {Stream.Readable} readable - The source to read from.
- * @param {string} origin - Origin type, must be 'yaml' or 'json'/'js'.
- * @returns {Promise.} The read content as JS object representation.
- * @private
- */
-function readFromStream(readable, origin) {
- return new Promise((resolve, reject) => {
- const buffers = [];
- readable
- .on('data', data => buffers.push(data))
- .on('error', reject)
- .on('end', () => {
- const buffer = Buffer.concat(buffers);
- try {
- // logger.debug(origin + ' reading from Readable'); TODO remove
- if (origin === TYPE_JSON || origin === TYPE_JS) {
- resolve(JSON.parse(buffer.toString(UTF8)));
- } else { // HINT: commented (see below): if (origin === YAML) {
- resolve(jsYaml.safeLoad(buffer.toString(UTF8)));
- }
- } catch (err) { // probably a SyntaxError for JSON or a YAMLException
- // logger.error('Unexpected error: ' + err.stack); TODO remove
- readable.emit('error', err); // send to .on('error',...
- }
- });
- });
-}
/**
* Reads the data from a given JS or JSON source.
@@ -63,36 +27,14 @@ function readFromStream(readable, origin) {
* @returns {Promise.} Contains the read JS object.
* @private
*/
-async function readJs(options) {
+async function readJsOrJson(options) {
if (typeof options.src === 'string') { // path to JSON or JS file
- const resolvedPath = path.resolve('', options.src);
- if (options.imports) {
- // eslint-disable-next-line import/no-dynamic-require, global-require
- const object = require(resolvedPath)[options.imports];
- if (!object) { // TODO check this as part of config validation?
- throw new Error('an identifier string \'' + options.imports + '\' was specified for JS object ' +
- 'but could not find this object, pls ensure that file ' + options.src + ' contains it.');
- } else {
- return object;
- }
- } else {
- // eslint-disable-next-line import/no-dynamic-require, global-require
- return require(resolvedPath); // reads both: JS and JSON!
- }
+ return readJsOrJsonFromFile(options.src, options.imports);
} else if (isStream.readable(options.src)) {
return readFromStream(options.src, TYPE_JSON); // reads both: JS or JSON!
- } else if (options.imports) { // options.src is JS object here!
- const subObject = options.src[options.imports];
- // logger.debug('LOADED JSON object (' + options.imports + '):: ' + stringify(subObject, null, 4)); TODO remove
- if (!subObject) {
- throw new Error('an identifier string \'' + options.imports + '\' was specified for JS object ' +
- 'but could not find this object, pls ensure that object source contains it.');
- } else {
- return Object.assign({}, subObject); // clone, do not alter original object!
- }
- } else { // options.src is JS object here!
- return Object.assign({}, options.src); // clone, do not alter original object!
}
+ // options.src is JS object here!
+ return readJsFromObject(options.src, options.imports);
}
/**
@@ -106,15 +48,7 @@ async function readJs(options) {
*/
async function readYaml(options) {
if (typeof options.src === 'string') {
- // load source from YAML file
- const yaml = await fsPromisified.readFile(options.src, UTF8);
- // logger.debug('YAML loaded from file ' + options.src); TODO remove
- try {
- return jsYaml.safeLoad(yaml);
- } catch (err) { // probably a YAMLException
- // logger.error('Unexpected error: ' + err.stack); TODO remove
- throw err;
- }
+ return readYamlFromfile(options.src);
}
// as validation has passed already, this can only be stream here
return readFromStream(options.src, TYPE_YAML);
@@ -177,7 +111,7 @@ export async function read(options) {
switch (validatedOptions.origin) {
case TYPE_JS:
case TYPE_JSON:
- return readJs(validatedOptions);
+ return readJsOrJson(validatedOptions);
default:
return readYaml(validatedOptions);
}
diff --git a/src/serialize-utils.js b/src/serialize-utils.js
new file mode 100644
index 0000000..a32026e
--- /dev/null
+++ b/src/serialize-utils.js
@@ -0,0 +1,62 @@
+import os from 'os';
+import jsonStringifySafe from 'json-stringify-safe';
+import serializeJs from 'serialize-js';
+
+/**
+ * @module jy-transform:serialize-utils
+ * @description This module provides an interface for serializing JS either to string or the JSON format.
+ * @private
+ */
+
+/**
+ * Creates a potential named `'module.exports[.exportsTo]'` string.
+ *
+ * @param {boolean} es6 - Whether to use ECMAScript6 export syntax.
+ * @param {string} [exportsTo] - The export name.
+ * @returns {Promise.} Resolves with the exports string.
+ * @private
+ */
+async function createExportString(es6, exportsTo) {
+ console.log('################## ####### es6 = ' + es6)
+ let exports = es6 ? 'export' : 'module.exports';
+ if (exportsTo) {
+ exports += es6 ? ` const ${exportsTo} = ` : '.' + exportsTo + ' = ';
+ } else {
+ exports += es6 ? ' default ' : ' = ';
+ }
+ return exports;
+}
+
+/**
+ * Serialize a JS object to string.
+ *
+ * @param {Object} object - The JS Object to serialize.
+ * @param {WriteOptions} options - The write options.
+ * @returns {Promise.} - Promise resolve with the serialized JS content.
+ * @private
+ */
+export async function serializeJsToString(object, options) {
+ let useStrict = '';
+ if (options.strict) {
+ const quote = options['no-single'] ? '"' : '\'';
+ useStrict = `${quote}use strict;${quote}${os.EOL}${os.EOL}`;
+ }
+ const exportsStr = await createExportString(!options['no-es6'], options.exports);
+ return `${useStrict}${exportsStr}${serializeJs.serialize(object, {
+ indent: options.indent,
+ forceSingleQuotes: !options['no-single'],
+ })};${os.EOL}`;
+}
+
+/**
+ * Serialize a JS object to JSON string.
+ *
+ * @param {Object} object - The object to serialize.
+ * @param {number} indent - The code indention.
+ * @returns {string} The serialized JSON.
+ * @private
+ */
+export async function serializeJsToJsonString(object, indent) {
+ return jsonStringifySafe(object, null, indent) + os.EOL;
+}
+
diff --git a/src/type-definitions.js b/src/type-definitions.js
index 755a398..d15fbb1 100644
--- a/src/type-definitions.js
+++ b/src/type-definitions.js
@@ -63,6 +63,11 @@
* @property {number} [indent=2] - The indentation value for pretty-print of output.
* @property {string} [exports=undefined] - The exports name for usage in JS destination files only.
* @property {string} [force=false] - Force overwriting of existing output files on write phase.
+ * @property {boolean} [no-es6=false] - Whether not to use ECMAScript6 syntax for JS type output like
+ * `module.exports` instead of `export default`, applicable only
+ * for JS output.
+ * @property {boolean} [no-single=false] - Whether _not_ to use single-quotes style for values in JS type
+ * output (i.e. double-quotes).
* @public
*/
@@ -91,5 +96,10 @@
* @property {number} [indent=2] - The _write_ indentation value for pretty-print of output.
* @property {string} [exports=undefined] - The _write_ exports name for usage in JS destination files only.
* @property {string} [force=false] - Force overwriting of existing output files on write phase.
+ * @property {boolean} [no-es6=false] - Whether not to use ECMAScript6 syntax for JS type output like
+ * `module.exports` instead of `export default`, applicable only
+ * for JS output.
+ * @property {boolean} [no-single=false] - Whether _not_ to use single-quotes style for values in JS type
+ * output (i.e. double-quotes).
* @public
*/
diff --git a/src/validation/joi-extensions-file-helper.js b/src/validation/joi-extensions-file-utils.js
similarity index 91%
rename from src/validation/joi-extensions-file-helper.js
rename to src/validation/joi-extensions-file-utils.js
index e43b663..4b00f24 100644
--- a/src/validation/joi-extensions-file-helper.js
+++ b/src/validation/joi-extensions-file-utils.js
@@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
/**
- * @module jy-transform:validation:joi-extensions-file-helper
+ * @module jy-transform:validation:joi-extensions-file-utils
* @description An (extended) Joi validation schema helper functions for the module options on FS validation.
* @private
*/
diff --git a/src/validation/joi-extensions-identifier-helper.js b/src/validation/joi-extensions-identifier-utils.js
similarity index 99%
rename from src/validation/joi-extensions-identifier-helper.js
rename to src/validation/joi-extensions-identifier-utils.js
index 397770c..7fd3d80 100644
--- a/src/validation/joi-extensions-identifier-helper.js
+++ b/src/validation/joi-extensions-identifier-utils.js
@@ -1,5 +1,5 @@
/**
- * @module jy-transform:validation:joi-extensions-identifier-helper
+ * @module jy-transform:validation:joi-extensions-identifier-utils
* @description An (extended) Joi validation schema helper function for the module options to validate ES6 identifiers.
* @private
*/
@@ -20,7 +20,7 @@ const identifierRegExpECMAScript6 = /^(?!(?:do|if|in|for|let|new|try|var|case|el
* @returns {boolean} A `true` if valid, else `false`.
* @protected
* @example
- * import { isValidEs6Identifier } from './validation/joi-extensions-identifier-helper.js';
+ * import { isValidEs6Identifier } from './validation/joi-extensions-identifier-utils.js';
* const identifier = 'foo';
* console.log('valid = ' + isValidEs6Identifier(identifier));
*/
diff --git a/src/validation/joi-extensions.js b/src/validation/joi-extensions.js
index 3e8d3da..005eea2 100644
--- a/src/validation/joi-extensions.js
+++ b/src/validation/joi-extensions.js
@@ -1,7 +1,7 @@
import JoiBase from 'joi';
import promisify from 'promisify-es6';
-import { isExistingFile } from './joi-extensions-file-helper';
-import { isValidEs6Identifier } from './joi-extensions-identifier-helper';
+import { isExistingFile } from './joi-extensions-file-utils';
+import { isValidEs6Identifier } from './joi-extensions-identifier-utils';
/**
* @module jy-transform:validation:joi-extension
diff --git a/src/validation/options-schema-helper.js b/src/validation/options-schema-utils.js
similarity index 98%
rename from src/validation/options-schema-helper.js
rename to src/validation/options-schema-utils.js
index 85bbd5e..d0f7de2 100644
--- a/src/validation/options-schema-helper.js
+++ b/src/validation/options-schema-utils.js
@@ -7,7 +7,7 @@ import {
} from '../constants';
/**
- * @module jy-transform:validation:options-schema-helper
+ * @module jy-transform:validation:options-schema-utils
* @description Provides some helper functions used in {@link module:validation:options-schema} to resolve default
* values for origin and target depending on the `options.src` or `options.dest` value.
* @type {Object}
diff --git a/src/validation/options-schema.js b/src/validation/options-schema.js
index b1c486d..7a62e97 100644
--- a/src/validation/options-schema.js
+++ b/src/validation/options-schema.js
@@ -4,7 +4,7 @@ import {
inferDestDefaultFromSrc,
inferOriginDefault,
inferTargetDefault,
-} from './options-schema-helper';
+} from './options-schema-utils';
import {
TYPE_YAML,
TYPE_JS,
@@ -14,6 +14,9 @@ import {
MIN_INDENT,
MIN_YAML_INDENT,
MAX_INDENT,
+ DEFAULT_STRICT,
+ DEFAULT_NO_ES6,
+ DEFAULT_NO_SINGLE_QUOTES,
} from '../constants';
/**
@@ -25,7 +28,7 @@ import {
*/
/**
- * The `force` options schema.
+ * The `force` option schema.
* @type {external:joi.Schema}
* @private
*/
@@ -35,30 +38,59 @@ const forceSchema = Joi
.description('Force overwriting of existing output files on write phase.');
/**
- * The `indent` options schema.
+ * The `force` option schema.
* @type {external:joi.Schema}
* @private
*/
-const indentSchema = Joi
- .when('target', {
- is: TYPE_YAML,
- then: Joi
- .number()
- .integer()
- .min(MIN_YAML_INDENT) // Must be 2 for YAML type!
- .max(MAX_INDENT)
- .default(DEFAULT_INDENT),
- otherwise: Joi
- .number()
- .integer()
- .min(MIN_INDENT)
- .max(MAX_INDENT)
- .default(DEFAULT_INDENT),
- })
- .description('The indention value for pretty-print of output.');
+const strictSchema = Joi
+ .boolean()
+ .default(DEFAULT_STRICT)
+ .description('Whether to write a "use strict;" in JS type output.');
+
+/**
+ * The `no-es6` option schema.
+ * @type {external:joi.Schema}
+ * @private
+ */
+const noES6Schema = Joi
+ .boolean()
+ .default(DEFAULT_NO_ES6)
+ .description('Whether not to use ECMAScript6 syntax for JS type output like "module.exports" instead of ' +
+ '"export default", applicable only for JS output.');
+
+/**
+ * The `no-single` option schema.
+ * @type {external:joi.Schema}
+ * @private
+ */
+const noSingleSchema = Joi
+ .boolean()
+ .default(DEFAULT_NO_SINGLE_QUOTES)
+ .description('Whether not to use single-quotes style for values in JS type output (i.e. double-quotes).');
+
+/**
+ * The `indent` option schema.
+ * @type {external:joi.Schema}
+ * @private
+ */
+const indentSchema = Joi.when('target', {
+ is: TYPE_YAML,
+ then: Joi
+ .number()
+ .integer()
+ .min(MIN_YAML_INDENT) // Must be 2 for YAML type!
+ .max(MAX_INDENT)
+ .default(DEFAULT_INDENT),
+ otherwise: Joi
+ .number()
+ .integer()
+ .min(MIN_INDENT)
+ .max(MAX_INDENT)
+ .default(DEFAULT_INDENT),
+}).description('The indention value for pretty-print of output.');
/**
- * The `exports` options schema.
+ * The `exports` option schema.
* @type {external:joi.Schema}
* @private
*/
@@ -68,31 +100,29 @@ const exportsSchema = Joi
.description('The name of property to export while writing a JS object to a JS output destination.');
/**
- * The `target` options schema.
+ * The `target` option schema.
* @type {external:joi.Schema}
* @private
*/
-const targetSchema = Joi
- .when('dest', {
- is: Joi.object().type(Stream.Writable),
- then: Joi
- .string()
- .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
- .default(inferTargetDefault, 'try target default resolution from dest type if not set (Stream.Writable)'),
- otherwise: Joi
- .when('dest', {
- is: Joi.string(),
- then: Joi
- .string()
- .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
- .default(inferTargetDefault, 'try target resolution from dest type if latter not set (String)'),
- otherwise: Joi // check
- .string()
- .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
- .default(TYPE_JS),
- }),
- })
- .description('The target type of output.');
+const targetSchema = Joi.when('dest', {
+ is: Joi.object().type(Stream.Writable),
+ then: Joi
+ .string()
+ .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
+ .default(inferTargetDefault, 'try target default resolution from dest type if not set (Stream.Writable)'),
+ otherwise: Joi
+ .when('dest', {
+ is: Joi.string(),
+ then: Joi
+ .string()
+ .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
+ .default(inferTargetDefault, 'try target resolution from dest type if latter not set (String)'),
+ otherwise: Joi // check
+ .string()
+ .valid(TYPE_YAML, TYPE_JSON, TYPE_JS)
+ .default(TYPE_JS),
+ }),
+}).description('The target type of output.');
/**
* The prepared {@link external:joi.Schema} for validating the {@link ReadOptions}.
@@ -162,6 +192,9 @@ export const writeOptionsSchema = Joi.object().keys({
exports: exportsSchema,
indent: indentSchema,
force: forceSchema,
+ strict: strictSchema,
+ 'no-es6': noES6Schema,
+ 'no-single': noSingleSchema,
}).default()
.required()
.unknown();
@@ -192,6 +225,9 @@ export const transformOptionsSchema = readOptionsSchema.concat(Joi.object().keys
exports: exportsSchema,
indent: indentSchema,
force: forceSchema,
+ strict: strictSchema,
+ 'no-es6': noES6Schema,
+ 'no-single': noSingleSchema,
}).default()
.required()
);
diff --git a/src/writer.js b/src/writer.js
index a2574ba..0f96e49 100644
--- a/src/writer.js
+++ b/src/writer.js
@@ -1,181 +1,32 @@
-import fs from 'fs';
import isStream from 'is-stream';
import jsYaml from 'js-yaml';
-import jsonStringifySafe from 'json-stringify-safe';
-import mkdirp from 'mkdirp-then';
-import os from 'os';
-import path from 'path';
-import promisify from 'promisify-es6';
-import serializeJs from 'serialize-js';
import {
TYPE_JS,
TYPE_JSON,
TYPE_YAML,
- UTF8
} from './constants';
import Joi from './validation/joi-extensions';
import { writeOptionsSchema } from './validation/options-schema';
+import {
+ serializeJsToJsonString,
+ serializeJsToString
+} from './serialize-utils';
+import {
+ writeToFile,
+ writeToStream,
+} from './io-utils';
/**
* @module jy-transform:writer
- * @description This module provides the _write_ functionality to write JS objects from memory to a JSON/JS/YAML
- * destination (file, object or {@link stream.Readable}).
- * @private
- */
-
-/**
- * Promisified `fs` module.
+ * @description This module provides the _public_ interface for the _write_ functionality to write JS objects from
+ * memory to a JSON/JS/YAML destination (file, `Object` or {@link stream.Writable}).
* @private
*/
-const fsPromisified = promisify(fs);
// ////////////////////////////////////////////////////////////////////////////
// METHODS (PRIVATE)
// ////////////////////////////////////////////////////////////////////////////
-/**
- * Creates a potential named `'module.exports[.exportsTo]'` string.
- *
- * @param {string} [exportsTo] - The export name.
- * @returns {Promise.} Resolves with the exports string.
- * @private
- */
-async function createExportsString(exportsTo) {
- let exports = 'module.exports';
- if (exportsTo) {
- exports += '.' + exportsTo + ' = ';
- } else {
- exports += ' = ';
- }
- return exports;
-}
-
-/**
- * Serialize a JS object to string.
- *
- * @param {Object} object - The JS Object to serialize.
- * @param {number} indent - The indention.
- * @param {string} [exportsTo] - Name for export (*IMPORTANT:* must be a valid ES6 identifier).
- * @returns {Promise.} - Promise resolve with the serialized JS content.
- * @private
- * @todo [[#35](https://github.com/deadratfink/jy-transform/issues/35)] Add `'use strict';` in JS output file (->
- * `'\'use strict\';' + os.EOL + os.EOL + ...`)?
- */
-async function serializeJsToString(object, indent, exportsTo) {
- const exportsStr = await createExportsString(exportsTo);
- return exportsStr + serializeJs.serialize(object, { indent }) + ';' + os.EOL;
-}
-
-/**
- * Serialize a JS object to JSON string.
- *
- * @param {Object} object - The object to serialize.
- * @param {number} indent - The code indention.
- * @returns {string} The serialized JSON.
- * @private
- */
-async function serializeJsToJsonString(object, indent) {
- return jsonStringifySafe(object, null, indent) + os.EOL;
-}
-
-/**
- * Turns the destination file name into a name containing a consecutive
- * number if it exists. It iterates over the files until it finds a file
- * name which does not exist.
- *
- * @param {string} dest - The destination file.
- * @returns {string} A consecutive file name or the original one if `dest` file does not exist.
- * @private
- */
-function getConsecutiveDestName(dest) {
- let tmpDest = dest;
- let i = 0;
- const destDirName = path.dirname(tmpDest);
- const ext = path.extname(tmpDest);
- const basename = path.basename(tmpDest, ext);
- while (fs.existsSync(tmpDest)) {
- tmpDest = path.join(destDirName, basename + '(' + (i += 1) + ')' + ext);
- }
- return tmpDest;
-}
-
-/**
- * Ensures that all dirs exists for file type `dest` and writes the JS object to file.
- *
- * @param {string} object - The object to write into file.
- * @param {string} dest - The file destination path.
- * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
- * @param {boolean} [forceOverwrite=false] - Forces overwriting the destination file if `true`.
- * @private
- */
-async function mkdirAndWrite(object, dest, target, forceOverwrite = false) {
- const destDir = path.dirname(dest);
- await mkdirp(destDir);
- let finalDestination = dest;
- if (!forceOverwrite) {
- finalDestination = getConsecutiveDestName(dest);
- }
- await fsPromisified.writeFile(finalDestination, object, UTF8);
- return 'Writing \'' + target + '\' file \'' + finalDestination + '\' successful.';
-}
-
-/**
- * Writes a serialized object to file.
- *
- * @param {string} object - The object to write into file.
- * @param {string} dest - The file destination path.
- * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
- * @param {boolean} [forceOverwrite] - Forces overwriting the destination file if `true`.
- * @see {@link TYPE_YAML}
- * @see {@link TYPE_JSON}
- * @see {@link TYPE_JS}
- * @returns {Promise.} Containing the write success message to handle by caller (e.g. for logging).
- * @throws {Error} If serialized JSON file could not be written due to any reason.
- * @private
- */
-function writeToFile(object, dest, target, forceOverwrite) {
- return new Promise((resolve, reject) => {
- fsPromisified.stat(dest)
- .then((stats) => {
- if (stats.isDirectory()) {
- reject(new Error('Destination file is a directory, pls specify a valid file resource!'));
- return;
- }
- // file exists
- resolve(mkdirAndWrite(object, dest, target, forceOverwrite));
- })
- .catch(() => {
- // ignore error (because file could possibly not exist at this point of time)
- resolve(mkdirAndWrite(object, dest, target, forceOverwrite));
- });
- });
-}
-
-/**
- * Writes a string serialized data object to a stream.
- *
- * @param {string} object - The data to write into stream.
- * @param {string} dest - The stream destination.
- * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
- * @see {@link TYPE_YAML}
- * @see {@link TYPE_JSON}
- * @see {@link TYPE_JS}
- * @returns {Promise.} Containing the write success message to handle by caller (e.g. for logging).
- * @throws {Error} If serialized JS object could not be written due to any reason.
- * @private
- */
-function writeToStream(object, dest, target) {
- return new Promise((resolve, reject) => {
- dest
- .on('error', reject)
- .on('finish', () => resolve('Writing ' + target + ' to stream successful.'));
-
- // write stringified data
- dest.write(object);
- dest.end();
- });
-}
-
/**
* Writes a JS object to a YAML destination.
*
@@ -231,18 +82,18 @@ async function writeJson(object, options) {
}
/**
- * Writes a JS object to a JS destination. The object is prefixed by `module.exports[.${options.exports}] = `.
+ * Writes a JS object to a JS destination.
*
* @param {Object} object - The JSON to write into JS destination.
- * @param {WriteOptions} options - The write destination and indention.
+ * @param {WriteOptions} options - The write options.
* @see {@link MIN_INDENT}
* @see {@link DEFAULT_INDENT}
* @see {@link MAX_INDENT}
- * @returns {Promise.} - Containing the write success message to handle by caller (e.g. for logging).
+ * @returns {Promise.} Containing the write success message to handle by caller (e.g. for logging).
* @private
*/
async function writeJs(object, options) {
- const data = await serializeJsToString(object, options.indent, options.exports);
+ const data = await serializeJsToString(object, options);
if (typeof options.dest === 'string') { // file
return writeToFile(data, options.dest, TYPE_JS, options.force);
} else if (isStream.writable(options.dest)) { // stream
diff --git a/test/unit/test-cli.js b/test/functional/test-jyt-cli.js
similarity index 67%
rename from test/unit/test-cli.js
rename to test/functional/test-jyt-cli.js
index 06bed89..2078645 100644
--- a/test/unit/test-cli.js
+++ b/test/functional/test-jyt-cli.js
@@ -16,7 +16,6 @@ import {
EXPECTED_VALUE,
} from '../helper-constants';
-
const fsPromised = promisify(fs);
/**
@@ -31,7 +30,7 @@ const fsPromised = promisify(fs);
* @constant
* @private
*/
-const CLI_TEST_BASE_DIR = './test/tmp/cli';
+const CLI_TEST_BASE_DIR = './test/functional/tmp/cli';
/**
* A YAML source file path.
@@ -59,18 +58,22 @@ const SRC_JS = TEST_DATA_DIR + '/test-data-cli.js';
/**
* Object mapping from JS option to to short CLI option.
- * @type {{src: string, dest: string, origin: string, target: string, indent: string, force: string, imports: string, exports: string}}
+ * @type {{src: string, dest: string, origin: string, target: string, indent: string, force: string, imports: string,
+ * exports: string}}
* @private
*/
const CLI_OPTIONS_LONG_TO_SHORT_MAP = {
src: '',
dest: '',
- origin: '-o ',
- target: '-t ',
- indent: '-i ',
- force: '-f ',
- imports: '-m ',
- exports: '-x '
+ origin: '-o',
+ target: '-t',
+ indent: '-i',
+ force: '-f',
+ imports: '-m',
+ exports: '-x',
+ strict: '-s',
+ 'no-es6': '--no-es6',
+ 'no-single': '--no-single',
};
/**
@@ -92,7 +95,7 @@ function createOptions(src, dest) {
* Executes `./jyt` script with given args (which includes source, destination and all options).
*
* @param {string[]} args - The source, destination CLI arguments and all CLI options.
- * @return {Promise}
+ * @returns {Promise} A result, see details.
* @resolve {string} The transformation success message.
* @rejects {Error} Any error occurred.
* @private
@@ -102,7 +105,7 @@ function execJyt(args) {
console.log('CWD: ' + cwd());
const command = './jyt ' + args.join(' ');
logger.info('executing command: ' + command);
- const childProcess = exec(command, { cwd: cwd() /*, encoding: 'utf8' */ }, (err, stdout, stderr) => {
+ const childProcess = exec(command, { cwd: cwd() /* , encoding: 'utf8' */ }, (err, stdout, stderr) => {
if (err) {
logger.error(`err: ${err}`);
reject(err);
@@ -113,7 +116,8 @@ function execJyt(args) {
resolve(stdout || stderr);
});
childProcess.on('error', logger.error);
- childProcess.on('exit', (code, signal) => logger.debug(`child process exited with code ${code} and signal ${signal}`));
+ childProcess.on('exit', (code, signal) =>
+ logger.debug(`child process exited with code ${code} and signal ${signal}`));
});
}
@@ -121,12 +125,12 @@ function execJyt(args) {
* Creates the CLI args/options from given `options` object.
*
* @param {TransformOptions} options - The transformation options.
- * @return {string[]} The CLI args and options.
+ * @returns {string[]} The CLI args and options.
* @private
*/
function optionsToArgs(options) {
const keys = Object.keys(options);
- return keys.map(key => CLI_OPTIONS_LONG_TO_SHORT_MAP[key] + options[key]);
+ return keys.map(key => `${CLI_OPTIONS_LONG_TO_SHORT_MAP[key]} ${options[key]}`);
}
/**
@@ -135,14 +139,14 @@ function optionsToArgs(options) {
* @param {TransformOptions} options - The transformation options.
* @private
*/
-async function assertTransformSuccess(options) {
+async function assertTransformSuccess(options, es6 = true) {
expect.assertions(2);
const msg = await execJyt(optionsToArgs(options));
logger.debug(msg);
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
// eslint-disable-next-line import/no-dynamic-require, global-require
- const json = require(path.resolve(options.dest));
+ const json = es6 ? require(path.resolve(options.dest)).default : require(path.resolve(options.dest));
expect(json.foo).toBe(EXPECTED_VALUE);
}
@@ -171,17 +175,22 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - ./jyt -> ./src/cli.js - ', () => {
describe('Testing CLI transforming from YAML to JS to relative path', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data.js';
+ const DEST_NO_ES6 = CLI_TEST_BASE_DIR + '/test-data-no-es6.js';
- it('should store ' + DEST + ' file relative to ' + CLI_TEST_BASE_DIR + '/test-data.yaml', async () => {
- expect.assertions(2);
+ beforeAll(async () => {
// Prepare test data.
try {
fsExtra.copySync(SRC_YAML, CLI_TEST_BASE_DIR + '/test-data.yaml');
logger.debug('copied ' + SRC_YAML + ' to ' + CLI_TEST_BASE_DIR + '/test-data.yaml');
} catch (err) {
- logger.error('could not copy ' + SRC_YAML + ' to ' + CLI_TEST_BASE_DIR + '/test-data.yaml: ' + err.stack);
+ logger.error('could not copy ' + SRC_YAML + ' to ' + CLI_TEST_BASE_DIR + '/test-data.yaml: ' +
+ err.stack);
throw err;
}
+ });
+
+ it('should store ' + DEST + ' file relative to ' + CLI_TEST_BASE_DIR + '/test-data.yaml', async () => {
+ expect.assertions(2);
const msg = await execJyt(optionsToArgs({
src: path.resolve(CLI_TEST_BASE_DIR + '/test-data.yaml'),
target: TYPE_JS,
@@ -191,80 +200,97 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - ./jyt -> ./src/cli.js - ', () => {
logger.debug('STATS: ' + JSON.stringify(stats, null, 4));
expect(stats.isFile()).toBe(true);
// eslint-disable-next-line import/no-unresolved, global-require, import/no-dynamic-require
- const json = require('../tmp/cli/test-data.js');
- expect(json.foo).toBe(EXPECTED_VALUE);
+ const result = require('./tmp/cli/test-data.js').default;
+ expect(result.foo).toBe(EXPECTED_VALUE);
+ });
+
+ it('should store ' + CLI_TEST_BASE_DIR + '/test-data-no-es6.js file relative to ' +
+ CLI_TEST_BASE_DIR + '/test-data.yaml (non-ES6 syntax)', async () => {
+ expect.assertions(2);
+ const msg = await execJyt(optionsToArgs({
+ src: path.resolve(CLI_TEST_BASE_DIR + '/test-data.yaml'),
+ dest: path.resolve(DEST_NO_ES6),
+ target: TYPE_JS,
+ 'no-es6': true,
+ }));
+ logger.debug(msg);
+ const stats = fs.statSync(DEST_NO_ES6);
+ expect(stats.isFile()).toBe(true);
+ // eslint-disable-next-line import/no-unresolved, global-require, import/no-dynamic-require
+ const result = require('./tmp/cli/test-data-no-es6.js');
+ expect(result.foo).toBe(EXPECTED_VALUE);
});
});
describe('Testing CLI transforming from YAML to JS', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-yaml-js.js';
- it('should store ' + SRC_YAML + ' file to ' + DEST, async () =>
- await assertTransformSuccess(createOptions(SRC_YAML, DEST))
+ it('should store ' + SRC_YAML + ' file to ' + DEST, () =>
+ assertTransformSuccess(createOptions(SRC_YAML, DEST))
);
});
describe('Testing CLI transforming from YAML to JSON', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-yaml-json.json';
- it('should store ' + SRC_YAML + ' file to ' + DEST, async () =>
- await assertTransformSuccess(createOptions(SRC_YAML, DEST))
+ it('should store ' + SRC_YAML + ' file to ' + DEST, () =>
+ assertTransformSuccess(createOptions(SRC_YAML, DEST), false)
);
});
describe('Testing CLI transforming from JSON to JS', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-json-js.js';
- it('should store ' + SRC_JSON + ' file to ' + DEST, async () =>
- await assertTransformSuccess(createOptions(SRC_JSON, DEST))
+ it('should store ' + SRC_JSON + ' file to ' + DEST, () =>
+ assertTransformSuccess(createOptions(SRC_JSON, DEST))
);
});
describe('Testing CLI transforming from JS to JSON', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-js-json.json';
- it('should store ' + SRC_JS + ' file to ' + DEST, async () =>
- await assertTransformSuccess(createOptions(SRC_JS, DEST))
+ it('should store ' + SRC_JS + ' file to ' + DEST, () =>
+ assertTransformSuccess(createOptions(SRC_JS, DEST), false)
);
});
describe('Testing CLI transforming from JS to YAML', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-js-yaml.yaml';
- it('should store ' + SRC_JS + ' file to ' + DEST, async () =>
- await assertYamlTransformSuccess(createOptions(SRC_JS, DEST))
+ it('should store ' + SRC_JS + ' file to ' + DEST, () =>
+ assertYamlTransformSuccess(createOptions(SRC_JS, DEST))
);
});
describe('Testing CLI transforming from YAML to YAML', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-yaml-yaml.yaml';
- it('should store ' + SRC_YAML + ' file to ' + DEST, async () =>
- await assertYamlTransformSuccess(createOptions(SRC_YAML, DEST))
+ it('should store ' + SRC_YAML + ' file to ' + DEST, () =>
+ assertYamlTransformSuccess(createOptions(SRC_YAML, DEST))
);
});
describe('Testing CLI transforming from JSON to JSON', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-json-json.json';
- it('should store ' + SRC_JS + ' file to ' + DEST, async () =>
- await assertTransformSuccess(createOptions(SRC_JS, DEST))
+ it('should store ' + SRC_JS + ' file to ' + DEST, () =>
+ assertTransformSuccess(createOptions(SRC_JS, DEST), false)
);
});
describe('Testing CLI transforming from JSON to YAML', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-json-yaml.yaml';
- it('should store ' + SRC_JSON + ' file to ' + DEST, async () =>
- await assertYamlTransformSuccess(createOptions(SRC_JSON, DEST))
+ it('should store ' + SRC_JSON + ' file to ' + DEST, () =>
+ assertYamlTransformSuccess(createOptions(SRC_JSON, DEST))
);
});
describe('Testing CLI transforming from JS to JS', () => {
const DEST = CLI_TEST_BASE_DIR + '/test-data-transform-js-js.js';
- it('should store ' + SRC_JS + ' file to ' + DEST, async () =>
- await assertTransformSuccess(createOptions(SRC_JS, DEST))
+ it('should store ' + SRC_JS + ' file to ' + DEST, () =>
+ assertTransformSuccess(createOptions(SRC_JS, DEST))
);
});
});
diff --git a/test/unit/test-reader.js b/test/functional/test-reader.js
similarity index 100%
rename from test/unit/test-reader.js
rename to test/functional/test-reader.js
diff --git a/test/unit/test-transformer.js b/test/functional/test-transformer.js
similarity index 79%
rename from test/unit/test-transformer.js
rename to test/functional/test-transformer.js
index d92067e..f77647d 100644
--- a/test/unit/test-transformer.js
+++ b/test/functional/test-transformer.js
@@ -15,7 +15,11 @@ import {
EXPECTED_VALUE,
} from '../helper-constants';
-const fsPromised = promisify(fs);
+/**
+ * Promisified `fs` module.
+ * @private
+ */
+const fsPromisified = promisify(fs);
/**
* @module jy-transform:unit-test:test-transformer
@@ -53,8 +57,7 @@ const SRC_JS = TEST_DATA_DIR + '/test-file.js';
* @constant
* @private
*/
-const TRANSFORMER_TEST_BASE_DIR = './test/tmp/transformer';
-
+const TRANSFORMER_TEST_BASE_DIR = './test/functional/tmp/transformer';
/**
* Transformation middleware changing value for `foo` property.
@@ -71,14 +74,14 @@ async function transformFunc(object) {
*
* @param {Object} options - The transformation options.
*/
-async function assertTransformSuccess(options) {
+async function assertTransformSuccess(options, es6 = true) {
expect.assertions(2);
const msg = await transform(options);
logger.debug(msg);
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
// eslint-disable-next-line import/no-dynamic-require, global-require
- const json = require(path.resolve(options.dest));
+ const json = es6 ? require(path.resolve(options.dest)).default : require(path.resolve(options.dest));
expect(json.foo).toBe(EXPECTED_VALUE);
}
@@ -94,7 +97,7 @@ async function assertYamlTransformSuccess(options) {
expect(msg).toEqual(expect.any(String));
const stats = fsExtra.statSync(options.dest);
expect(stats.isFile()).toBeTruthy();
- const yaml = await fsPromised.readFile(options.dest, UTF8);
+ const yaml = await fsPromisified.readFile(options.dest, UTF8);
const object = jsYaml.safeLoad(yaml);
expect(object.foo).toBe(EXPECTED_VALUE);
}
@@ -125,7 +128,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
describe('Testing transform with middleware', () => {
it('should throw ValidationError if middleware passed is not a function type', async () => {
expect.assertions(1);
- await expect(transform(createOptions({}, 'not a function', {})))
+ await expect(transform(createOptions({}, {}, 'not a function')))
.rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
});
@@ -160,9 +163,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
describe('Testing Transformer transforming from YAML to JS to relative path', () => {
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data.js';
+ const DEST_NO_ES6 = TRANSFORMER_TEST_BASE_DIR + '/test-data-no-es6.js';
+ const DEST_DQ_AND_STRICT = TRANSFORMER_TEST_BASE_DIR + '/test-data-double-quotes-and-strict.js';
- it('should store ' + DEST + ' file relative to ' + TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml', async () => {
- expect.assertions(2);
+ beforeAll(async () => {
// Prepare test data.
try {
fsExtra.copySync(SRC_YAML, TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml');
@@ -172,6 +176,10 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
err.stack);
throw err;
}
+ });
+
+ it('should store ' + DEST + ' file relative to ' + TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml', async () => {
+ expect.assertions(2);
const msg = await transform({
src: path.resolve(TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml'),
transform: transformFunc,
@@ -181,7 +189,43 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
const stats = fs.statSync(DEST);
expect(stats.isFile()).toBe(true);
// eslint-disable-next-line import/no-unresolved, global-require, import/no-dynamic-require
- const json = require('../tmp/transformer/test-data.js');
+ const json = require('./tmp/transformer/test-data.js').default;
+ expect(json.foo).toBe(EXPECTED_VALUE);
+ });
+
+ it('should store ' + DEST + ' file with double-quotes and strict', async () => {
+ expect.assertions(2);
+ const msg = await transform({
+ src: path.resolve(TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml'),
+ dest: path.resolve(DEST_DQ_AND_STRICT),
+ transform: transformFunc,
+ target: TYPE_JS,
+ strict: true,
+ 'no-single': true,
+ });
+ logger.debug(msg);
+ const stats = fs.statSync(DEST_DQ_AND_STRICT);
+ expect(stats.isFile()).toBe(true);
+ // eslint-disable-next-line import/no-unresolved, global-require, import/no-dynamic-require
+ const jsContentString = await fsPromisified.readFile(DEST_DQ_AND_STRICT, UTF8);
+ expect(jsContentString.startsWith('"use strict;"')).toBe(true);
+ });
+
+ it('should store ' + TRANSFORMER_TEST_BASE_DIR + '/test-data-no-es6.js file relative to ' +
+ TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml (non-ES6 syntax)', async () => {
+ expect.assertions(2);
+ const msg = await transform({
+ src: path.resolve(TRANSFORMER_TEST_BASE_DIR + '/test-data.yaml'),
+ dest: path.resolve(DEST_NO_ES6),
+ transform: transformFunc,
+ target: TYPE_JS,
+ 'no-es6': true,
+ });
+ logger.debug(msg);
+ const stats = fs.statSync(DEST_NO_ES6);
+ expect(stats.isFile()).toBe(true);
+ // eslint-disable-next-line import/no-unresolved, global-require, import/no-dynamic-require
+ const json = require('./tmp/transformer/test-data-no-es6.js');
expect(json.foo).toBe(EXPECTED_VALUE);
});
});
@@ -210,7 +254,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options);
+ await assertTransformSuccess(options, false);
});
});
@@ -238,7 +282,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options);
+ await assertTransformSuccess(options, false);
});
});
@@ -281,7 +325,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
transform: transformFunc,
dest: path.resolve(DEST),
};
- await assertTransformSuccess(options);
+ await assertTransformSuccess(options, false);
});
});
diff --git a/test/unit/test-writer.js b/test/functional/test-writer.js
similarity index 98%
rename from test/unit/test-writer.js
rename to test/functional/test-writer.js
index 5337843..12942a8 100644
--- a/test/unit/test-writer.js
+++ b/test/functional/test-writer.js
@@ -36,7 +36,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
* @constant
* @private
*/
- const WRITER_TEST_BASE_DIR = './test/tmp/writer';
+ const WRITER_TEST_BASE_DIR = './test/functional/tmp/writer';
beforeAll(() => {
fsExtra.ensureDirSync(WRITER_TEST_BASE_DIR);
@@ -143,7 +143,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
expect(msg).toBeDefined();
await expectDestFileExists(file);
// eslint-disable-next-line import/no-unresolved, global-require
- const object = require('../tmp/writer/test-data-by-js-stream-with-exports-identifier.js').test;
+ const object = require('./tmp/writer/test-data-by-js-stream-with-exports-identifier.js').test;
expect(object.test).toBeDefined();
expect(object.test).toBe('value');
});
diff --git a/test/unit/test-serialize-js-utils.js b/test/unit/test-serialize-js-utils.js
new file mode 100644
index 0000000..b33cae3
--- /dev/null
+++ b/test/unit/test-serialize-js-utils.js
@@ -0,0 +1,3 @@
+/**
+ * Created by jens.krefeldt on 24.08.17.
+ */
diff --git a/test/unit/validation/test-joi-extensions-file-helper.js b/test/unit/validation/test-joi-extensions-file-utils.js
similarity index 86%
rename from test/unit/validation/test-joi-extensions-file-helper.js
rename to test/unit/validation/test-joi-extensions-file-utils.js
index 11b8e63..ac4a1dc 100644
--- a/test/unit/validation/test-joi-extensions-file-helper.js
+++ b/test/unit/validation/test-joi-extensions-file-utils.js
@@ -1,8 +1,8 @@
import { TEST_SUITE_DESCRIPTION_UNIT } from '../../helper-constants';
-import { isExistingFile } from '../../../src/validation/joi-extensions-file-helper';
+import { isExistingFile } from '../../../src/validation/joi-extensions-file-utils';
/**
- * @module jy-transform:test-unit:test-joi-extension-file-helper
+ * @module jy-transform:test-unit:test-joi-extension-file-utils
* @description This unit test module tests validation FS helper method.
* @private
*/
@@ -10,11 +10,11 @@ import { isExistingFile } from '../../../src/validation/joi-extensions-file-help
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - joi-extensions-file-helper - ', () => {
describe('Method isExistingFile(pathStr) ', () => {
it('should return true on relative path string with existing file', () =>
- expect(isExistingFile('test/unit/validation/test-joi-extensions-file-helper.js')).toBe(true)
+ expect(isExistingFile('test/unit/validation/test-joi-extensions-file-utils.js')).toBe(true)
);
it('should return true on relative path string with existing file starting with \'./\'', () =>
- expect(isExistingFile('./test/unit/validation/test-joi-extensions-file-helper.js')).toBe(true)
+ expect(isExistingFile('./test/unit/validation/test-joi-extensions-file-utils.js')).toBe(true)
);
it('should return false on incorrect path string with non-existing file', () =>
diff --git a/test/unit/validation/test-joi-extensions-identifier-helper.js b/test/unit/validation/test-joi-extensions-identifier-utils.js
similarity index 96%
rename from test/unit/validation/test-joi-extensions-identifier-helper.js
rename to test/unit/validation/test-joi-extensions-identifier-utils.js
index c9b76d2..6d1d483 100644
--- a/test/unit/validation/test-joi-extensions-identifier-helper.js
+++ b/test/unit/validation/test-joi-extensions-identifier-utils.js
@@ -1,8 +1,8 @@
-import { isValidEs6Identifier } from '../../../src/validation/joi-extensions-identifier-helper';
+import { isValidEs6Identifier } from '../../../src/validation/joi-extensions-identifier-utils';
import { TEST_SUITE_DESCRIPTION_UNIT } from '../../helper-constants';
/**
- * @module jy-transform:unit-test:test-joi-extensions-identifier-helper
+ * @module jy-transform:unit-test:test-joi-extensions-identifier-utils
* @description This unit test suite checks validity and correctness of ES6 identifiers.
* @private
*/
diff --git a/test/unit/validation/test-options-schema-helper.js b/test/unit/validation/test-options-schema-utils.js
similarity index 96%
rename from test/unit/validation/test-options-schema-helper.js
rename to test/unit/validation/test-options-schema-utils.js
index 0e02995..13dd0c2 100644
--- a/test/unit/validation/test-options-schema-helper.js
+++ b/test/unit/validation/test-options-schema-utils.js
@@ -4,7 +4,7 @@ import {
inferOriginDefault,
inferTargetDefault,
inferDestDefaultFromSrc,
-} from '../../../src/validation/options-schema-helper';
+} from '../../../src/validation/options-schema-utils';
import { TEST_SUITE_DESCRIPTION_UNIT } from '../../helper-constants';
import {
TYPE_YAML,
@@ -14,7 +14,7 @@ import {
} from '../../../src/constants';
/**
- * @module jy-transform:unit-test:test-options-schema-helper
+ * @module jy-transform:unit-test:test-options-schema-utils
* @description This unit test suite checks the validity and correctness of options schema helper methods.
* @private
*/
@@ -22,7 +22,7 @@ import {
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
describe('Function inferOriginDefault', () => {
it('should infer the correct origin from relative path string with existing file having a known file extension',
- () => expect(inferOriginDefault({ src: 'test/unit/validation/test-joi-extensions-file-helper.js' })).toBe(TYPE_JS)
+ () => expect(inferOriginDefault({ src: 'test/unit/validation/test-joi-extensions-file-utils.js' })).toBe(TYPE_JS)
);
it('should infer the default origin from relative path string with existing file having an unsupported file ' +
@@ -35,7 +35,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
it('should infer the correct origin from read stream of existing file having a known file ending', () =>
expect(inferOriginDefault({
- src: fs.createReadStream('test/unit/validation/test-joi-extensions-file-helper.js'),
+ src: fs.createReadStream('test/unit/validation/test-joi-extensions-file-utils.js'),
})).toBe(TYPE_JS)
);
diff --git a/test/unit/validation/test-options-schema.js b/test/unit/validation/test-options-schema.js
index 64cef28..8462458 100644
--- a/test/unit/validation/test-options-schema.js
+++ b/test/unit/validation/test-options-schema.js
@@ -14,6 +14,9 @@ import {
DEFAULT_INDENT,
MIN_INDENT,
MAX_INDENT,
+ DEFAULT_STRICT,
+ DEFAULT_NO_ES6,
+ DEFAULT_NO_SINGLE_QUOTES,
} from '../../../src/constants';
import {
readOptionsSchema,
@@ -229,7 +232,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
);
it('should set all defaults', async () => {
- expect.assertions(4);
+ expect.assertions(7);
const options = {
dest: './test/tmp/test-data.js',
};
@@ -238,6 +241,9 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
expect(validatedOptions.indent).toBe(DEFAULT_INDENT);
expect(validatedOptions.exports).toBe(DEFAULT_JS_EXPORTS_IDENTIFIER);
expect(validatedOptions.force).toBe(DEFAULT_FORCE_FILE_OVERWRITE);
+ expect(validatedOptions.strict).toBe(DEFAULT_STRICT);
+ expect(validatedOptions['no-es6']).toBe(DEFAULT_NO_ES6);
+ expect(validatedOptions['no-single']).toBe(DEFAULT_NO_SINGLE_QUOTES);
});
it('should infer options.target from file type', async () => {
From 5e00e59c65dd252e8d2ffb70cd5a330b58215e68 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 24 Aug 2017 13:52:29 +0200
Subject: [PATCH 26/58] Deps updated
---
package.json | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/package.json b/package.json
index be45906..24d67b0 100644
--- a/package.json
+++ b/package.json
@@ -36,27 +36,27 @@
"cli": "~1.0.1",
"is-stream": "~1.1.0",
"joi": "~10.6.0",
- "js-yaml": "~3.6.1",
+ "js-yaml": " ~3.9.1",
"json-stringify-safe": "~5.0.1",
"mkdirp-then": "~1.2.0",
"promisify-es6": "~1.0.2",
"serialize-js": "deadratfink/serialize-js#feature/single_quote_only"
},
"devDependencies": {
- "babel-cli": "~6.24.1",
+ "babel-cli": "~6.26.0",
"babel-eslint": " ~7.2.3",
"babel-plugin-transform-flow-strip-types": "~6.22.0",
"babel-plugin-transform-runtime": "~6.23.0",
"babel-preset-env": "~1.6.0",
- "chalk": "~2.0.1",
+ "chalk": "~2.1.0",
"codacy-coverage": "~2.0.2",
"codeclimate-test-reporter": "~0.5.0",
"codecov": " ~2.3.0",
"coveralls": " ~2.13.1",
"cwd": "~0.10.0",
"doctoc": " ~1.3.0",
- "eslint": "~4.2.0",
- "eslint-config-airbnb-base": "~11.2.0",
+ "eslint": "~4.5.0",
+ "eslint-config-airbnb-base": "~11.3.2",
"eslint-plugin-filenames": "1.2.0",
"eslint-plugin-import": " ~2.7.0",
"eslint-plugin-jest": " ~20.0.3",
@@ -68,7 +68,7 @@
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": "~3.0.0",
"jsdoc-to-markdown": "~3.0.0",
- "nsp": "~2.6.3",
+ "nsp": "~2.7.0",
"package-json-to-readme": "~2.0.0",
"winston": "~2.3.0"
},
From e781fb5d683e1706770f8eea74a088f290163740 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 24 Aug 2017 13:52:55 +0200
Subject: [PATCH 27/58] Deps updated
---
PACKAGE.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/PACKAGE.md b/PACKAGE.md
index 9002849..d95726f 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -34,7 +34,7 @@ npm test
- [babel-plugin-transform-flow-strip-types](https://github.com/babel/babel/tree/master/packages): Strip flow type annotations from your output code.
- [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
-- [chalk](https://github.com/chalk/chalk): Terminal string styling done right. Much color
+- [chalk](https://github.com/chalk/chalk): Terminal string styling done right
- [codacy-coverage](https://github.com/codacy/node-codacy-coverage): Code Coverage reporter for Codacy.com
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
- [codecov](https://github.com/codecov/codecov-node): Uploading report to Codecov: https://codecov.io
From e9692b63e9d6cbcbbb78665cd104a63eea3b0369 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 1 Sep 2017 09:15:29 +0200
Subject: [PATCH 28/58] More tests and improvements
---
.eslintignore | 1 +
.jestrc.js | 3 +-
.jsdoc-public.json | 3 +-
API-PRIVATE.md | 32 ++-
API-PUBLIC.md | 197 ++++++++++++++++--
CHANGELOG.md | 2 +-
README.md | 75 ++++---
bin/create-readme.sh | 20 +-
index.js | 15 +-
readme/DOCUMENTATION.md | 67 +++---
src/jy-transform.js | 171 +++++++++++++++
src/reader.js | 26 +--
src/serialize-utils.js | 3 +-
src/transformer.js | 29 +--
src/writer.js | 39 ----
test/functional/test-jyt-cli.js | 14 +-
test/functional/test-reader.js | 4 +-
test/functional/test-transformer.js | 42 ++--
test/functional/test-writer.js | 4 +-
test/unit/test-index.js | 14 +-
test/unit/test-jy-transform.js | 48 +++++
test/unit/test-serialize-js-utils.js | 3 -
test/unit/test-serialize-utils.js | 101 +++++++++
.../test-joi-extensions-file-utils.js | 2 +-
.../test-joi-extensions-identifier-utils.js | 2 +-
.../validation/test-options-schema-utils.js | 4 +-
26 files changed, 651 insertions(+), 270 deletions(-)
create mode 100755 src/jy-transform.js
create mode 100644 test/unit/test-jy-transform.js
delete mode 100644 test/unit/test-serialize-js-utils.js
create mode 100644 test/unit/test-serialize-utils.js
diff --git a/.eslintignore b/.eslintignore
index 70b454f..7d53bb8 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -8,6 +8,7 @@ lib/
index.js
test/data
test/tmp
+test/functional/tmp
# TODO reve later when test os done
test/unit/test-cli.js
diff --git a/.jestrc.js b/.jestrc.js
index 310dfeb..8bdb047 100644
--- a/.jestrc.js
+++ b/.jestrc.js
@@ -33,7 +33,8 @@ module.exports = {
'**/test/functional/**/*.js',
//'**/test/unit/validation/test-options-schema-helper.js',
- // '**/test/test-log-wrapper.js',
+
+ //'**/test/unit/test-serialize-utils.js',
// '**/test/unit/test-middleware.js',
// '**/test/test-index.js',
//'/*.js!**/test/functional/util/**',
diff --git a/.jsdoc-public.json b/.jsdoc-public.json
index 86923ee..1e14c9e 100644
--- a/.jsdoc-public.json
+++ b/.jsdoc-public.json
@@ -1,7 +1,8 @@
{
"source": {
"include": [
- "./"
+ "./src/jy-transform.js",
+ "./src/type-definitions.js"
],
"exclude": [
"test",
diff --git a/API-PRIVATE.md b/API-PRIVATE.md
index 871cc9c..1345812 100644
--- a/API-PRIVATE.md
+++ b/API-PRIVATE.md
@@ -27,6 +27,7 @@
- [jy-transform:unit:helper-constants : Object ℗](#jy-transformunithelper-constants--codeobjectcode-%E2%84%97)
- [jy-transform:unit:logger : Object ℗](#jy-transformunitlogger--codeobjectcode-%E2%84%97)
- [jy-transform:test-unit:index ℗](#jy-transformtest-unitindex-%E2%84%97)
+- [jy-transform:test-unit:serialize-utils ℗](#jy-transformtest-unitserialize-utils-%E2%84%97)
- [jy-transform:test-unit:test-joi-extension-file-utils ℗](#jy-transformtest-unittest-joi-extension-file-utils-%E2%84%97)
- [jy-transform:unit-test:test-joi-extensions-identifier-utils ℗](#jy-transformunit-testtest-joi-extensions-identifier-utils-%E2%84%97)
- [jy-transform:unit-test:test-options-schema-utils ℗](#jy-transformunit-testtest-options-schema-utils-%E2%84%97)
@@ -119,6 +120,9 @@ memory to a JSON/JS/YAML destination (file, Object or jy-transform:test-unit:index ℗
This unit test module tests the correct exporting from ./index.js.
This module provides the public interface for the read, write and transform functionality.
@@ -33,38 +33,193 @@
-
+
-## jy-transform:constants
-Useful constants used for the module and its usage.
+## jy-transform
+This module provides the _public_ interface for the _read_, _write_ and _transform_ functionality.
**Access**: public
+**Author**: Jens Krefeldt
-* [jy-transform:constants](#module_jy-transform_constants)
- * [~TYPE_YAML](#module_jy-transform_constants..TYPE_YAML) : string
- * [~TYPE_JSON](#module_jy-transform_constants..TYPE_JSON) : string
- * [~TYPE_JS](#module_jy-transform_constants..TYPE_JS) : string
+* [jy-transform](#module_jy-transform)
+ * [~transform](#module_jy-transform..transform) ⇒ Promise
+ * [~read](#module_jy-transform..read) ⇒ Promise
+ * [~write](#module_jy-transform..write) ⇒ Promise
+ * [~TYPE_YAML](#module_jy-transform..TYPE_YAML) : string
+ * [~TYPE_JS](#module_jy-transform..TYPE_JS) : string
+ * [~TYPE_JSON](#module_jy-transform..TYPE_JSON) : string
-
+
-### jy-transform:constants~TYPE_YAML : string
-The `'yaml'` type constant.
+### jy-transform~transform ⇒ Promise
+The entry method for all transformations accepting a configuration object and
+an (optional) middleware function. It executes the transformation logic.
+
+1. Input (read)
+2. Transform [ + Middleware]
+3. Output (write).
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Returns**: Promise - The transformation result.
**Access**: public
-
+**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
+**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
-### jy-transform:constants~TYPE_JSON : string
-The `'json'` type constant.
+| Param | Type | Description |
+| --- | --- | --- |
+| options | [TransformOptions](#TransformOptions) | The configuration for a transformation. |
+
+**Example**
+```js
+import { transform } from 'jy-transform';
+const options = {
+ src: 'foo/bar.yaml', // From YAML file...
+ transform: async (object) => { // ...with exchanging value...
+ object.foo = 'new value';
+ return object;
+ },
+ target: 'foo/bar.json', // ...to a new JSON file.
+ indent: 4,
+};
+
+// ---- Promise style:
+
+transform(options)
+ .then(console.log)
+ .catch(console.error);
+
+
+// ---- async/await style:
+
+try {
+ const msg = await transform(options);
+ console.log(msg);
+} catch (err) {
+ console.error(err.stack);
+};
+```
+
+
+### jy-transform~read ⇒ Promise
+Reads a particular content type from a source provided in the passed `options`.
+
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Returns**: Promise - The result.
+**Access**: public
+**Resolve**: string Resolves with JS object result.
+**Reject**: ValidationError If any `options` validation occurs.
+**Reject**: Error If any write error occurs.
+
+| Param | Type | Description |
+| --- | --- | --- |
+| options | [ReadOptions](#ReadOptions) | The read options. |
+
+**Example**
+```js
+import { read } from 'jy-transform';
+
+
+// --- from file path
+
+options = {
+ src: 'foo.yml'
+};
+
+read(options)
+ .then(obj => console.log(JSON.stringify(obj)))
+ .catch(console.error);
+
+
+// --- from Readable
+
+options = {
+ src: fs.createReadStream('foo.yml')
+};
+
+read(options)
+ .then(obj => console.log(JSON.stringify(obj)))
+ .catch(console.error);
+```
+
+
+### jy-transform~write ⇒ Promise
+Writes the passed JS object to a particular destination described by the passed `options`.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Returns**: Promise - The result.
**Access**: public
-
+**Resolve**: string With the write success message.
+**Reject**: Error If any write error occurs.
+**Reject**: ValidationError If any `options` validation occurs.
-### jy-transform:constants~TYPE_JS : string
+| Param | Type | Description |
+| --- | --- | --- |
+| object | Object | The JS source object to write. |
+| options | [WriteOptions](#WriteOptions) | The write options. |
+
+**Example**
+```js
+import { write } from 'jy-transform';
+
+
+// ---- write obj to file ---
+
+const obj = {...};
+const options = {
+ dest: 'result.js',
+ indent: 4
+}
+
+write(obj, options)
+ .then(console.log)
+ .catch(console.error);
+
+
+// ---- write obj to Writable ---
+
+options = {
+ dest: fs.createWriteStream('result.json'),
+ indent: 4
+}
+
+write(obj, options)
+ .then(console.log)
+ .catch(console.error);
+
+
+// ---- write obj to object ---
+
+options = {
+ dest: {},
+ indent: 4
+}
+
+write(obj, options)
+ .then(console.log)
+ .catch(console.error);
+```
+
+
+### jy-transform~TYPE_YAML : string
+The `'yaml'` type constant.
+
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Access**: public
+
+
+### jy-transform~TYPE_JS : string
The `'js'` type constant.
-**Kind**: inner constant of [jy-transform:constants](#module_jy-transform_constants)
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Access**: public
+
+
+### jy-transform~TYPE_JSON : string
+The `'json'` type constant.
+
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
**Access**: public
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95538f4..cd47d25 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ new interface:
- This is the default now:
- Usage of `export default` instead of `module.exports`.
- Usage of `export const foo` instead of `module.exports.foo`.
- - Can be suppressed by `options[no-es6]` (default `false`).
+ - Can be suppressed by `options[no-es6] = true` (default `false`).
- [[#62](https://github.com/deadratfink/jy-transform/issues/62)] The `options.transform` function (formerly aka
_middleware_ function) is no longer necessary to be a Promise/`async` one.
- [[#59](https://github.com/deadratfink/jy-transform/issues/59)] Support single-quotes options for JS output.
diff --git a/README.md b/README.md
index 3ce54e7..707d5d0 100644
--- a/README.md
+++ b/README.md
@@ -105,9 +105,9 @@ npm install jy-transform --global
## TOC
- [API in a Minute](#api-in-a-minute)
- - [Read, Transform & Write from Source to Destination](#read-transform--write-from-source-to-destination)
- - [Read into JS object from particular Source (File, Stream or JS Object) only](#read-into-js-object-from-particular-source-file-stream-or-js-object-only)
- - [Write JS object to particular Destination only](#write-js-object-to-particular-destination-only)
+ - [Transform from Source to Destination](#transform-from-source-to-destination)
+ - [Read into JS object from particular Source (File, Stream or JS Object)](#read-into-js-object-from-particular-source-file-stream-or-js-object)
+ - [Write JS object to particular Destination](#write-js-object-to-particular-destination)
- [Why This Module?](#why-this-module)
- [Usage](#usage)
- [Usage Types](#usage-types)
@@ -125,7 +125,7 @@ npm install jy-transform --global
## API in a Minute
-### Read, Transform & Write from Source to Destination
+### Transform from Source to Destination
```javascript
import { transform } from 'jy-transform';
@@ -153,11 +153,11 @@ try {
const msg = await transform(options); // Transform, of course, inside an async.
console.log(msg); // Success message!
} catch (err) { // Oops!
- console.error(err.stack);
+ console.error(err);
}
```
-### Read into JS object from particular Source (File, Stream or JS Object) only
+### Read into JS object from particular Source (File, Stream or JS Object)
```javascript
import { read } from 'jy-transform';
@@ -176,11 +176,11 @@ try {
const object = await read(options);
console.log(JSON.stringify(object)); // Print read object.
} catch (err) {
- console.error(err.stack);
+ console.error(err);
}
```
-### Write JS object to particular Destination only
+### Write JS object to particular Destination
```javascript
import { write } from 'jy-transform';
@@ -199,7 +199,7 @@ try {
const msg = await write(object, options);
console.log(msg); // Print write success message.
} catch (err) {
- console.error(err.stack);
+ console.error(err);
}
```
@@ -231,26 +231,28 @@ So, what are the typical use cases for this module? In terms of _transformation_
these consists of different phases:
1. Reading from source
- 2. Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects
+ 2. Transforming JSON objects or apply dedicated actions on the intermediate JSON objects
3. Writing to a destination
-#### Reading From
+#### Read Case
-- _*.yaml_ file
-- _*.js_ file
-- _*.json_ file
+Reading from a file:
-Additionally, on API level from a:
+- _*.yaml_
+- _*.js_
+- _*.json_
-- `stream.Readable`
- - Contain serialized JS, JSON or YAML
- - If not file stream it requires `options.origin` property set
+Additionally, on API level from:
+
+- `stream.Readable`:
+ - Contains serialized JS, JSON or YAML
+ - If not a file stream then setting requires `options.origin` property is mandatory
- Reads as UTF-8
-- JS `object`
+- JS `object`:
- Actually, this means the reading phase is "skipped", because object is in-memory already
- Of course, this case _cannot_ not be applied to serialized JSON or YAML content
-#### Transformation
+#### Transformation Case
The _transformation_ is usually a format change, but can also be refer to content changes on the
intermediate JS object, the latter with the help of a configured `transform` callback function.
@@ -275,21 +277,23 @@ while:
As mentioned above the configured `transform` callback can apply particular actions on the intermediate JS object, but
this is an optional part for [transformation](#transformation) phase.
-#### Writing To
+#### Write Case
+
+Writing to a file:
-- _*.yaml_ file
-- _*.js_ file
-- _*.json_ file
+- _*.yaml_
+- _*.js_
+- _*.json_
-Additionally, on API level to a:
+Additionally, on API level to:
-- `stream.Writable`
+- `stream.Writable`:
- Serialized JS, JSON and YAML
- Requires `options.target` property set
- Writes UTF-8
-- JS `object
- - JS as simple reference
- - YAML and JSON as serialized string
+- JS `object`:
+ - JS as a simple reference
+ - YAML and JSON as a serialized string
### Limitations
@@ -324,9 +328,6 @@ Additionally, on API level to a:
and JS only, but at the moment we require that each document to transform is a
_single_ one per source (or in case of JS could be identified)! This feature is
planned and reflected in [#14](https://github.com/deadratfink/jy-transform/issues/14).
-- Schema validation for input and output is another topic which is planned by
- [#1](https://github.com/deadratfink/jy-transform/issues/1) and
- [#2](https://github.com/deadratfink/jy-transform/issues/2).
### CLI Usage
@@ -400,7 +401,7 @@ Then we can transform it to a JSON content as _foo.json_ file:
```json
{
- "foo": "bar"
+ "foo": "bar"
}
```
@@ -432,13 +433,11 @@ Accordingly, this is also true for the `target` option.
The command
```text
-$ jyt foo.json -i 4
+$ jyt foo.json
```
results in _foo.js_:
```javascript
-module.exports = {
- foo: "bar"
-}
+export default {foo: 'bar'}
```
#### Example: JS ⇒ YAML
@@ -790,7 +789,5 @@ section for more details about conventions.
- [Public Api Reference](./API-PUBLIC.md)
-- [Private Api Reference](./API-PRIVATE.md)
-
- [Makefile Reference](./MAKE.md)
diff --git a/bin/create-readme.sh b/bin/create-readme.sh
index 19e7f65..d5aac43 100755
--- a/bin/create-readme.sh
+++ b/bin/create-readme.sh
@@ -82,16 +82,16 @@ fi
# API-PRIVATE.md
###############################################################################
-if [ "$api" == "true" ]; then
- printf "Create documentation (API-PRIVATE.md)\n"
- touch API-PRIVATE.md
- printf "\n\n\n" >> API-PRIVATE.md
- node node_modules/.bin/jsdoc2md --no-cache --private --configure .jsdoc.json . > API-PRIVATE.md
- node node_modules/.bin/doctoc API-PRIVATE.md --github --title "## TOC" --maxlevel 2
-
- printf -- "- [Private Api Reference](./API-PRIVATE.md)" >> README.md
- printf "\n\n" >> README.md
-fi
+#if [ "$api" == "true" ]; then
+# printf "Create documentation (API-PRIVATE.md)\n"
+# touch API-PRIVATE.md
+# printf "\n\n\n" >> API-PRIVATE.md
+# node node_modules/.bin/jsdoc2md --no-cache --private --configure .jsdoc.json . > API-PRIVATE.md
+# node node_modules/.bin/doctoc API-PRIVATE.md --github --title "## TOC" --maxlevel 2
+#
+# printf -- "- [Private Api Reference](./API-PRIVATE.md)" >> README.md
+# printf "\n\n" >> README.md
+#fi
###############################################################################
# MAKE.md
diff --git a/index.js b/index.js
index aad8f64..3a2685e 100755
--- a/index.js
+++ b/index.js
@@ -1,14 +1 @@
-const Transformer = require('./src/transformer.js').default;
-const Reader = require('./src/reader.js').default;
-const Writer = require('./src/writer.js').default;
-const Constants = require('./src/constants.js');
-
-module.exports = {
- transform: Transformer.transform,
- read: Reader.read,
- write: Writer.write,
- TYPE_YAML: Constants.TYPE_YAML,
- TYPE_JS: Constants.TYPE_JS,
- TYPE_JSON: Constants.TYPE_JSON,
-};
-
+module.exports = require('./src/jy-transform');
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index 5833f57..70fcdcb 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -1,6 +1,6 @@
## API in a Minute
-### Read, Transform & Write from Source to Destination
+### Transform from Source to Destination
```javascript
import { transform } from 'jy-transform';
@@ -28,11 +28,11 @@ try {
const msg = await transform(options); // Transform, of course, inside an async.
console.log(msg); // Success message!
} catch (err) { // Oops!
- console.error(err.stack);
+ console.error(err);
}
```
-### Read into JS object from particular Source (File, Stream or JS Object) only
+### Read into JS object from particular Source (File, Stream or JS Object)
```javascript
import { read } from 'jy-transform';
@@ -51,11 +51,11 @@ try {
const object = await read(options);
console.log(JSON.stringify(object)); // Print read object.
} catch (err) {
- console.error(err.stack);
+ console.error(err);
}
```
-### Write JS object to particular Destination only
+### Write JS object to particular Destination
```javascript
import { write } from 'jy-transform';
@@ -74,7 +74,7 @@ try {
const msg = await write(object, options);
console.log(msg); // Print write success message.
} catch (err) {
- console.error(err.stack);
+ console.error(err);
}
```
@@ -106,26 +106,28 @@ So, what are the typical use cases for this module? In terms of _transformation_
these consists of different phases:
1. Reading from source
- 2. Transforming JSON objects (`Transformer`) or apply dedicated actions on the intermediate JSON objects
+ 2. Transforming JSON objects or apply dedicated actions on the intermediate JSON objects
3. Writing to a destination
-#### Reading From
+#### Read Case
-- _*.yaml_ file
-- _*.js_ file
-- _*.json_ file
+Reading from a file:
-Additionally, on API level from a:
+- _*.yaml_
+- _*.js_
+- _*.json_
-- `stream.Readable`
- - Contain serialized JS, JSON or YAML
- - If not file stream it requires `options.origin` property set
+Additionally, on API level from:
+
+- `stream.Readable`:
+ - Contains serialized JS, JSON or YAML
+ - If not a file stream then setting requires `options.origin` property is mandatory
- Reads as UTF-8
-- JS `object`
+- JS `object`:
- Actually, this means the reading phase is "skipped", because object is in-memory already
- Of course, this case _cannot_ not be applied to serialized JSON or YAML content
-#### Transformation
+#### Transformation Case
The _transformation_ is usually a format change, but can also be refer to content changes on the
intermediate JS object, the latter with the help of a configured `transform` callback function.
@@ -150,21 +152,23 @@ while:
As mentioned above the configured `transform` callback can apply particular actions on the intermediate JS object, but
this is an optional part for [transformation](#transformation) phase.
-#### Writing To
+#### Write Case
+
+Writing to a file:
-- _*.yaml_ file
-- _*.js_ file
-- _*.json_ file
+- _*.yaml_
+- _*.js_
+- _*.json_
-Additionally, on API level to a:
+Additionally, on API level to:
-- `stream.Writable`
+- `stream.Writable`:
- Serialized JS, JSON and YAML
- Requires `options.target` property set
- Writes UTF-8
-- JS `object
- - JS as simple reference
- - YAML and JSON as serialized string
+- JS `object`:
+ - JS as a simple reference
+ - YAML and JSON as a serialized string
### Limitations
@@ -199,9 +203,6 @@ Additionally, on API level to a:
and JS only, but at the moment we require that each document to transform is a
_single_ one per source (or in case of JS could be identified)! This feature is
planned and reflected in [#14](https://github.com/deadratfink/jy-transform/issues/14).
-- Schema validation for input and output is another topic which is planned by
- [#1](https://github.com/deadratfink/jy-transform/issues/1) and
- [#2](https://github.com/deadratfink/jy-transform/issues/2).
### CLI Usage
@@ -275,7 +276,7 @@ Then we can transform it to a JSON content as _foo.json_ file:
```json
{
- "foo": "bar"
+ "foo": "bar"
}
```
@@ -307,13 +308,11 @@ Accordingly, this is also true for the `target` option.
The command
```text
-$ jyt foo.json -i 4
+$ jyt foo.json
```
results in _foo.js_:
```javascript
-module.exports = {
- foo: "bar"
-}
+export default {foo: 'bar'}
```
#### Example: JS ⇒ YAML
diff --git a/src/jy-transform.js b/src/jy-transform.js
new file mode 100755
index 0000000..e7ac8ed
--- /dev/null
+++ b/src/jy-transform.js
@@ -0,0 +1,171 @@
+import { transform as _transform } from './transformer';
+import { read as _read } from './reader';
+import { write as _write } from './writer';
+import {
+ TYPE_YAML as _TYPE_YAML,
+ TYPE_JS as _TYPE_JS,
+ TYPE_JSON as _TYPE_JSON,
+} from './constants';
+
+/**
+ * @module jy-transform
+ * @description This module provides the _public_ interface for the _read_, _write_ and _transform_ functionality.
+ * @public
+ * @author Jens Krefeldt
+ */
+
+/**
+ * The entry method for all transformations accepting a configuration object and
+ * an (optional) middleware function. It executes the transformation logic.
+ *
+ * 1. Input (read)
+ * 2. Transform [ + Middleware]
+ * 3. Output (write).
+ *
+ * @param {TransformOptions} options - The configuration for a transformation.
+ * @returns {Promise} The transformation result.
+ * @resolve {string} With the transformation result as message (e.g. to be logged by caller).
+ * @reject {TypeError} Will throw this error when the passed `middleware` is not type of `Function`.
+ * @reject {ValidationError} If any `options` validation occurs.
+ * @reject {Error} Will throw any error if read, transform or write operation failed due to any reason.
+ * @public
+ * @example
+ * import { transform } from 'jy-transform';
+ * const options = {
+ * src: 'foo/bar.yaml', // From YAML file...
+ * transform: async (object) => { // ...with exchanging value...
+ * object.foo = 'new value';
+ * return object;
+ * },
+ * target: 'foo/bar.json', // ...to a new JSON file.
+ * indent: 4,
+ * };
+ *
+ * // ---- Promise style:
+ *
+ * transform(options)
+ * .then(console.log)
+ * .catch(console.error);
+ *
+ *
+ * // ---- async/await style:
+ *
+ * try {
+ * const msg = await transform(options);
+ * console.log(msg);
+ * } catch (err) {
+ * console.error(err.stack);
+ * };
+ */
+export const transform = _transform;
+/**
+ * Reads a particular content type from a source provided in the passed `options`.
+ *
+ * @param {ReadOptions} options - The read options.
+ * @returns {Promise} The result.
+ * @resolve {string} Resolves with JS object result.
+ * @reject {ValidationError} If any `options` validation occurs.
+ * @reject {Error} If any write error occurs.
+ * @public
+ * @example
+ * import { read } from 'jy-transform';
+ *
+ *
+ * // --- from file path
+ *
+ * options = {
+ * src: 'foo.yml'
+ * };
+ *
+ * read(options)
+ * .then(obj => console.log(JSON.stringify(obj)))
+ * .catch(console.error);
+ *
+ *
+ * // --- from Readable
+ *
+ * options = {
+ * src: fs.createReadStream('foo.yml')
+ * };
+ *
+ * read(options)
+ * .then(obj => console.log(JSON.stringify(obj)))
+ * .catch(console.error);
+ */
+export const read = _read;
+
+/**
+ * Writes the passed JS object to a particular destination described by the passed `options`.
+ *
+ * @param {Object} object - The JS source object to write.
+ * @param {WriteOptions} options - The write options.
+ * @returns {Promise} The result.
+ * @resolve {string} With the write success message.
+ * @reject {Error} If any write error occurs.
+ * @reject {ValidationError} If any `options` validation occurs.
+ * @public
+ * @example
+ * import { write } from 'jy-transform';
+ *
+ *
+ * // ---- write obj to file ---
+ *
+ * const obj = {...};
+ * const options = {
+ * dest: 'result.js',
+ * indent: 4
+ * }
+ *
+ * write(obj, options)
+ * .then(console.log)
+ * .catch(console.error);
+ *
+ *
+ * // ---- write obj to Writable ---
+ *
+ * options = {
+ * dest: fs.createWriteStream('result.json'),
+ * indent: 4
+ * }
+ *
+ * write(obj, options)
+ * .then(console.log)
+ * .catch(console.error);
+ *
+ *
+ * // ---- write obj to object ---
+ *
+ * options = {
+ * dest: {},
+ * indent: 4
+ * }
+ *
+ * write(obj, options)
+ * .then(console.log)
+ * .catch(console.error);
+ */
+export const write = _write;
+
+/**
+ * The `'yaml'` type constant.
+ * @type {string}
+ * @constant
+ * @public
+ */
+export const TYPE_YAML = _TYPE_YAML;
+
+/**
+ * The `'js'` type constant.
+ * @type {string}
+ * @constant
+ * @public
+ */
+export const TYPE_JS = _TYPE_JS;
+
+/**
+ * The `'json'` type constant.
+ * @type {string}
+ * @constant
+ * @public
+ */
+export const TYPE_JSON = _TYPE_JSON;
diff --git a/src/reader.js b/src/reader.js
index 6ed060d..f021bca 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -80,31 +80,7 @@ async function readYaml(options) {
* @resolve {string} Resolves with JS object result.
* @reject {ValidationError} If any `options` validation occurs.
* @reject {Error} If any write error occurs.
- * @public
- * @example
- * import { read } from 'jy-transform';
- *
- *
- * // --- from file path
- *
- * options = {
- * src: 'foo.yml'
- * };
- *
- * read(options)
- * .then(obj => console.log(JSON.stringify(obj)))
- * .catch(console.error);
- *
- *
- * // --- from Readable
- *
- * options = {
- * src: fs.createReadStream('foo.yml')
- * };
- *
- * read(options)
- * .then(obj => console.log(JSON.stringify(obj)))
- * .catch(console.error);
+ * @private
*/
export async function read(options) {
const validatedOptions = await Joi.validate(options, readOptionsSchema);
diff --git a/src/serialize-utils.js b/src/serialize-utils.js
index a32026e..b837689 100644
--- a/src/serialize-utils.js
+++ b/src/serialize-utils.js
@@ -16,8 +16,7 @@ import serializeJs from 'serialize-js';
* @returns {Promise.} Resolves with the exports string.
* @private
*/
-async function createExportString(es6, exportsTo) {
- console.log('################## ####### es6 = ' + es6)
+export async function createExportString(es6, exportsTo) {
let exports = es6 ? 'export' : 'module.exports';
if (exportsTo) {
exports += es6 ? ` const ${exportsTo} = ` : '.' + exportsTo + ' = ';
diff --git a/src/transformer.js b/src/transformer.js
index 3c41cd2..1155fc9 100644
--- a/src/transformer.js
+++ b/src/transformer.js
@@ -23,34 +23,7 @@ import { transformOptionsSchema } from './validation/options-schema';
* @reject {TypeError} Will throw this error when the passed `middleware` is not type of `Function`.
* @reject {ValidationError} If any `options` validation occurs.
* @reject {Error} Will throw any error if read, transform or write operation failed due to any reason.
- * @public
- * @example
- * import { transform } from 'jy-transform';
- * const options = {
- * src: 'foo/bar.yaml', // From YAML file...
- * transform: async (object) => { // ...with exchanging value...
- * object.foo = 'new value';
- * return object;
- * },
- * target: 'foo/bar.json', // ...to a new JSON file.
- * indent: 4,
- * };
- *
- * // ---- Promise style:
- *
- * transform(options)
- * .then(console.log)
- * .catch(console.error);
- *
- *
- * // ---- async/await style:
- *
- * try {
- * const msg = await transform(options);
- * console.log(msg);
- * } catch (err) {
- * console.error(err.stack);
- * };
+ * @private
*/
export async function transform(options) {
const validatedOptions = await Joi.validate(options, transformOptionsSchema);
diff --git a/src/writer.js b/src/writer.js
index 0f96e49..45a0df7 100644
--- a/src/writer.js
+++ b/src/writer.js
@@ -121,45 +121,6 @@ async function writeJs(object, options) {
* @reject {Error} If any write error occurs.
* @reject {ValidationError} If any `options` validation occurs.
* @public
- * @example
- * import { write } from 'jy-transform';
- *
- *
- * // ---- write obj to file ---
- *
- * const obj = {...};
- * const options = {
- * dest: 'result.js',
- * indent: 4
- * }
- *
- * write(obj, options)
- * .then(console.log)
- * .catch(console.error);
- *
- *
- * // ---- write obj to Writable ---
- *
- * options = {
- * dest: fs.createWriteStream('result.json'),
- * indent: 4
- * }
- *
- * write(obj, options)
- * .then(console.log)
- * .catch(console.error);
- *
- *
- * // ---- write obj to object ---
- *
- * options = {
- * dest: {},
- * indent: 4
- * }
- *
- * write(obj, options)
- * .then(console.log)
- * .catch(console.error);
*/
export async function write(object, options) {
const validatedOptions = await Joi.validate(options, writeOptionsSchema);
diff --git a/test/functional/test-jyt-cli.js b/test/functional/test-jyt-cli.js
index 2078645..0c17b2d 100644
--- a/test/functional/test-jyt-cli.js
+++ b/test/functional/test-jyt-cli.js
@@ -1,6 +1,6 @@
import jsYaml from 'js-yaml';
import promisify from 'promisify-es6';
-import { exec, execFile, spawn } from 'child_process';
+import { exec } from 'child_process';
import fsExtra from 'fs-extra';
import fs from 'fs';
import cwd from 'cwd';
@@ -11,7 +11,7 @@ import {
TYPE_JS,
} from '../../src/constants';
import {
- TEST_SUITE_DESCRIPTION_UNIT,
+ TEST_SUITE_DESCRIPTION_FUNCTIONAL,
TEST_DATA_DIR,
EXPECTED_VALUE,
} from '../helper-constants';
@@ -72,8 +72,8 @@ const CLI_OPTIONS_LONG_TO_SHORT_MAP = {
imports: '-m',
exports: '-x',
strict: '-s',
- 'no-es6': '--no-es6',
- 'no-single': '--no-single',
+ 'no-es6': '--no-es6', // no short available
+ 'no-single': '--no-single', // no short available
};
/**
@@ -97,12 +97,11 @@ function createOptions(src, dest) {
* @param {string[]} args - The source, destination CLI arguments and all CLI options.
* @returns {Promise} A result, see details.
* @resolve {string} The transformation success message.
- * @rejects {Error} Any error occurred.
+ * @reject {Error} Any error occurred.
* @private
*/
function execJyt(args) {
return new Promise((resolve, reject) => {
- console.log('CWD: ' + cwd());
const command = './jyt ' + args.join(' ');
logger.info('executing command: ' + command);
const childProcess = exec(command, { cwd: cwd() /* , encoding: 'utf8' */ }, (err, stdout, stderr) => {
@@ -137,6 +136,7 @@ function optionsToArgs(options) {
* Helper method which asserts the successful transformation.
*
* @param {TransformOptions} options - The transformation options.
+ * @param {boolean} [es6=true] - Whether to use ES6 syntax.
* @private
*/
async function assertTransformSuccess(options, es6 = true) {
@@ -167,7 +167,7 @@ async function assertYamlTransformSuccess(options) {
expect(object.foo).toBe(EXPECTED_VALUE);
}
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - ./jyt -> ./src/cli.js - ', () => {
+describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - ./jyt -> ./src/cli.js - ', () => {
beforeAll(() => {
fsExtra.ensureDirSync(CLI_TEST_BASE_DIR);
fsExtra.emptyDirSync(CLI_TEST_BASE_DIR);
diff --git a/test/functional/test-reader.js b/test/functional/test-reader.js
index e232f20..9dade25 100644
--- a/test/functional/test-reader.js
+++ b/test/functional/test-reader.js
@@ -1,7 +1,7 @@
import YAMLException from 'js-yaml/lib/js-yaml/exception';
import fs from 'fs';
import { read } from '../../src/reader';
-import { TEST_SUITE_DESCRIPTION_UNIT } from '../helper-constants';
+import { TEST_SUITE_DESCRIPTION_FUNCTIONAL } from '../helper-constants';
import {
TYPE_JS,
TYPE_YAML,
@@ -14,7 +14,7 @@ import {
* @private
*/
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - reader - ', () => {
+describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
/**
* Assert a `Error` properties for a given reader function.
*
diff --git a/test/functional/test-transformer.js b/test/functional/test-transformer.js
index f77647d..5c89e6c 100644
--- a/test/functional/test-transformer.js
+++ b/test/functional/test-transformer.js
@@ -10,7 +10,7 @@ import {
TYPE_JS,
} from '../../src/constants';
import {
- TEST_SUITE_DESCRIPTION_UNIT,
+ TEST_SUITE_DESCRIPTION_FUNCTIONAL,
TEST_DATA_DIR,
EXPECTED_VALUE,
} from '../helper-constants';
@@ -72,7 +72,8 @@ async function transformFunc(object) {
/**
* Helper method which asserts the successful transformation.
*
- * @param {Object} options - The transformation options.
+ * @param {Object} options - The transformation options.
+ * @param {boolean} [es6=true] - Whether to use ES6 syntax.
*/
async function assertTransformSuccess(options, es6 = true) {
expect.assertions(2);
@@ -119,7 +120,7 @@ function createOptions(src, dest, func = transformFunc) {
};
}
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
+describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - transformer - ', () => {
beforeAll(() => {
fsExtra.ensureDirSync(TRANSFORMER_TEST_BASE_DIR);
fsExtra.emptyDirSync(TRANSFORMER_TEST_BASE_DIR);
@@ -231,13 +232,12 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
});
describe('Testing Transformer transforming from YAML to JS', () => {
- const SRC = './test/data/test-file.yaml';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-yaml-js.js';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_YAML + ' file to ' + DEST, async () => {
expect.assertions(2);
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_YAML),
transform: transformFunc,
dest: path.resolve(DEST),
};
@@ -272,13 +272,12 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
});
describe('Testing Transformer transforming from JS to JSON', () => {
- const SRC = './test/data/test-file.js';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-js-json.json';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_JS + ' file to ' + DEST, async () => {
expect.assertions(2);
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_JS),
transform: transformFunc,
dest: path.resolve(DEST),
};
@@ -288,12 +287,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
describe('Testing Transformer transforming from JS to YAML', () => {
expect.assertions(2);
- const SRC = './test/data/test-file.js';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-js-yaml.yaml';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_JS + ' file to ' + DEST, async () => {
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_JS),
transform: transformFunc,
dest: path.resolve(DEST),
};
@@ -302,12 +300,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
});
describe('Testing Transformer transforming from YAML to YAML', () => {
- const SRC = './test/data/test-file.yaml';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-yaml-yaml.yaml';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_YAML + ' file to ' + DEST, async () => {
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_YAML),
transform: transformFunc,
dest: path.resolve(DEST),
};
@@ -316,12 +313,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
});
describe('Testing Transformer transforming from JSON to JSON', () => {
- const SRC = './test/data/test-file.json';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-json-json.json';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_JSON + ' file to ' + DEST, async () => {
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_JSON),
transform: transformFunc,
dest: path.resolve(DEST),
};
@@ -330,12 +326,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
});
describe('Testing Transformer transforming from JSON to YAML', () => {
- const SRC = './test/data/test-file.json';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-json-yaml.yaml';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_JSON + ' file to ' + DEST, async () => {
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_JSON),
transform: transformFunc,
dest: path.resolve(DEST),
};
@@ -344,13 +339,12 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - transformer - ', () => {
});
describe('Testing Transformer transforming from JS to JS', () => {
- const SRC = './test/data/test-file.js';
const DEST = TRANSFORMER_TEST_BASE_DIR + '/test-data-transform-js-js.js';
- it('should store ' + SRC + ' file to ' + DEST, async () => {
+ it('should store ' + SRC_JS + ' file to ' + DEST, async () => {
expect.assertions(2);
const options = {
- src: path.resolve(SRC),
+ src: path.resolve(SRC_JS),
transform: transformFunc,
dest: path.resolve(DEST),
};
diff --git a/test/functional/test-writer.js b/test/functional/test-writer.js
index 12942a8..a56574d 100644
--- a/test/functional/test-writer.js
+++ b/test/functional/test-writer.js
@@ -5,7 +5,7 @@ import os from 'os';
import stream from 'stream';
import { write } from '../../src/writer';
import { logger } from '../logger';
-import { TEST_SUITE_DESCRIPTION_UNIT } from '../helper-constants';
+import { TEST_SUITE_DESCRIPTION_FUNCTIONAL } from '../helper-constants';
import {
TYPE_YAML,
TYPE_JS,
@@ -20,7 +20,7 @@ const fsPromised = promisify(fs);
* @private
*/
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - writer - ', () => {
+describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
/**
* Sample JS content used in tests.
*
diff --git a/test/unit/test-index.js b/test/unit/test-index.js
index 32e132c..ead9f60 100644
--- a/test/unit/test-index.js
+++ b/test/unit/test-index.js
@@ -1,6 +1,9 @@
-import index, { transform, read, write, TYPE_YAML, TYPE_JS, TYPE_JSON } from '../../index';
+import { transform, read, write, TYPE_YAML, TYPE_JS, TYPE_JSON } from '../../index';
import { TEST_SUITE_DESCRIPTION_UNIT } from '../helper-constants';
+// eslint-disable-next-line import/no-commonjs
+const index = require('../../index');
+
/**
* @module jy-transform:test-unit:index
* @description This unit test module tests the correct exporting from _./index.js_.
@@ -11,10 +14,15 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - index - ', () => {
describe('Exports Check Unit Tests', () => {
describe('Exports', () =>
it('should be an existing Object', () => {
- expect.assertions(3);
+ expect.assertions(8);
expect(index).toBeDefined();
- expect(index).toBeInstanceOf(Object);
expect(Object.keys(index)).toHaveLength(6);
+ expect(index.transform).toBeDefined();
+ expect(index.transform).toBeInstanceOf(Function);
+ expect(index.read).toBeDefined();
+ expect(index.read).toBeInstanceOf(Function);
+ expect(index.write).toBeDefined();
+ expect(index.write).toBeInstanceOf(Function);
})
);
diff --git a/test/unit/test-jy-transform.js b/test/unit/test-jy-transform.js
new file mode 100644
index 0000000..7e16be8
--- /dev/null
+++ b/test/unit/test-jy-transform.js
@@ -0,0 +1,48 @@
+import { transform, read, write, TYPE_YAML, TYPE_JS, TYPE_JSON } from '../../src/jy-transform';
+import { TEST_SUITE_DESCRIPTION_UNIT } from '../helper-constants';
+
+/**
+ * @module jy-transform:test-unit:jy-transform
+ * @description This unit test module tests the correct exporting from _./src/jy-transform.js_.
+ * @private
+ */
+
+describe(TEST_SUITE_DESCRIPTION_UNIT + ' - jy-transform - ', () => {
+ describe('Exports Check Unit Tests', () => {
+ describe('Exported transform', () =>
+ it('should be an existing function', () => {
+ expect.assertions(2);
+ expect(transform).toBeDefined();
+ expect(transform).toBeInstanceOf(Function);
+ })
+ );
+
+ describe('Exported read', () =>
+ it('should be an existing function', () => {
+ expect.assertions(2);
+ expect(read).toBeDefined();
+ expect(read).toBeInstanceOf(Function);
+ })
+ );
+
+ describe('Exported write', () =>
+ it('should be an existing function', () => {
+ expect.assertions(2);
+ expect(write).toBeDefined();
+ expect(write).toBeInstanceOf(Function);
+ })
+ );
+
+ describe('Exported constants', () =>
+ it('should be existing string values', () => {
+ expect.assertions(6);
+ expect(TYPE_YAML).toBeDefined();
+ expect(TYPE_YAML).toBe('yaml');
+ expect(TYPE_JS).toBeDefined();
+ expect(TYPE_JS).toBe('js');
+ expect(TYPE_JSON).toBeDefined();
+ expect(TYPE_JSON).toBe('json');
+ })
+ );
+ });
+});
diff --git a/test/unit/test-serialize-js-utils.js b/test/unit/test-serialize-js-utils.js
deleted file mode 100644
index b33cae3..0000000
--- a/test/unit/test-serialize-js-utils.js
+++ /dev/null
@@ -1,3 +0,0 @@
-/**
- * Created by jens.krefeldt on 24.08.17.
- */
diff --git a/test/unit/test-serialize-utils.js b/test/unit/test-serialize-utils.js
new file mode 100644
index 0000000..61c19ef
--- /dev/null
+++ b/test/unit/test-serialize-utils.js
@@ -0,0 +1,101 @@
+import os from 'os';
+import {
+ createExportString,
+ serializeJsToString,
+ serializeJsToJsonString,
+} from '../../src/serialize-utils';
+import { TEST_SUITE_DESCRIPTION_UNIT } from '../helper-constants';
+
+/**
+ * @module jy-transform:test-unit:serialize-utils
+ * @description This unit test suite checks the validity and correctness of JS serialization utility methods.
+ * @private
+ */
+
+describe(TEST_SUITE_DESCRIPTION_UNIT + ' - serialize-utils - ', () => {
+ const namedExport = 'foo';
+ const indent = ' ';
+ const nl = os.EOL;
+ const toSerializeToJs = {
+ foo: 'bar',
+ bar: {
+ bar: 'bar'
+ },
+ };
+
+ describe('Function createExportString', () => {
+ it('should create ES6 default export', async () => {
+ expect.assertions(1);
+ const result = await createExportString(true);
+ expect(result).toBe('export default ');
+ });
+
+ it('should create "module.exports"', async () => {
+ expect.assertions(1);
+ const result = await createExportString(false);
+ expect(result).toBe('module.exports = ');
+ });
+
+ it('should create ES6 default export with named export', async () => {
+ expect.assertions(1);
+ const result = await createExportString(true, 'foo');
+ expect(result).toBe(`export const ${namedExport} = `);
+ });
+
+ it('should create "module.exports" with named export', async () => {
+ expect.assertions(1);
+ const result = await createExportString(false, 'foo');
+ expect(result).toBe(`module.exports.${namedExport} = `);
+ });
+ });
+
+ describe('Function serializeJsToString', () => {
+ it('should create "use strict;" if configured', async () => {
+ expect.assertions(1);
+ const result = await serializeJsToString(toSerializeToJs, {
+ strict: true,
+ indent: indent.length,
+ 'no-es6': false,
+ });
+ expect(result).toBe(
+ `'use strict;'${nl}${nl}export default {${nl}${indent}foo: 'bar',${nl}${indent}bar: {bar: 'bar'}${nl}};${nl}`
+ );
+ });
+
+ it('should not create "use strict;" if not configured', async () => {
+ expect.assertions(1);
+ const result = await serializeJsToString(toSerializeToJs, {
+ strict: false,
+ indent: indent.length,
+ 'no-es6': false,
+ });
+ expect(result).toBe(`export default {${nl}${indent}foo: 'bar',${nl}${indent}bar: {bar: 'bar'}${nl}};${nl}`);
+ });
+
+ it('should serialize all with double quotes if configured', async () => {
+ expect.assertions(1);
+ const result = await serializeJsToString(toSerializeToJs, {
+ strict: true,
+ indent: indent.length,
+ 'no-es6': false,
+ 'no-single': true,
+ });
+ expect(result).toBe(
+ `"use strict;"${nl}${nl}export default {${nl}${indent}foo: "bar",${nl}${indent}bar: {bar: "bar"}${nl}};${nl}`
+ );
+ });
+ });
+
+ describe('Function serializeJsToJsonString', () => {
+ it('should serialize correctly', async () => {
+ expect.assertions(1);
+ const toSerializeToJson = {
+ foo: {
+ bar: 'bar'
+ },
+ };
+ const result = await serializeJsToJsonString(toSerializeToJson, indent.length);
+ expect(result).toBe(`{${nl}${indent}"foo": {${nl}${indent}${indent}"bar": "bar"${nl}${indent}}${nl}}${nl}`);
+ });
+ });
+});
diff --git a/test/unit/validation/test-joi-extensions-file-utils.js b/test/unit/validation/test-joi-extensions-file-utils.js
index ac4a1dc..44d8cd9 100644
--- a/test/unit/validation/test-joi-extensions-file-utils.js
+++ b/test/unit/validation/test-joi-extensions-file-utils.js
@@ -7,7 +7,7 @@ import { isExistingFile } from '../../../src/validation/joi-extensions-file-util
* @private
*/
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - joi-extensions-file-helper - ', () => {
+describe(TEST_SUITE_DESCRIPTION_UNIT + ' - joi-extensions-file-utils - ', () => {
describe('Method isExistingFile(pathStr) ', () => {
it('should return true on relative path string with existing file', () =>
expect(isExistingFile('test/unit/validation/test-joi-extensions-file-utils.js')).toBe(true)
diff --git a/test/unit/validation/test-joi-extensions-identifier-utils.js b/test/unit/validation/test-joi-extensions-identifier-utils.js
index 6d1d483..5ebe5d1 100644
--- a/test/unit/validation/test-joi-extensions-identifier-utils.js
+++ b/test/unit/validation/test-joi-extensions-identifier-utils.js
@@ -7,7 +7,7 @@ import { TEST_SUITE_DESCRIPTION_UNIT } from '../../helper-constants';
* @private
*/
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - joi-extensions-identifier-helper - ', () => {
+describe(TEST_SUITE_DESCRIPTION_UNIT + ' - joi-extensions-identifier-utils - ', () => {
const nonStringIdentifier = {};
it('should validate non-string identifier \'' + JSON.toString(nonStringIdentifier) + '\' to false', () =>
expect(isValidEs6Identifier(nonStringIdentifier)).toBe(false)
diff --git a/test/unit/validation/test-options-schema-utils.js b/test/unit/validation/test-options-schema-utils.js
index 13dd0c2..130b28a 100644
--- a/test/unit/validation/test-options-schema-utils.js
+++ b/test/unit/validation/test-options-schema-utils.js
@@ -19,7 +19,7 @@ import {
* @private
*/
-describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
+describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-utils - ', () => {
describe('Function inferOriginDefault', () => {
it('should infer the correct origin from relative path string with existing file having a known file extension',
() => expect(inferOriginDefault({ src: 'test/unit/validation/test-joi-extensions-file-utils.js' })).toBe(TYPE_JS)
@@ -54,7 +54,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema-helper - ', () => {
describe('Function inferTargetDefault', () => {
it('should infer the correct target from relative path string with existing file having a known file ending', () =>
- expect(inferTargetDefault({ dest: 'test/unit/validation/test-joi-extensions-file-helper.yaml' })).toBe(TYPE_YAML)
+ expect(inferTargetDefault({ dest: 'test/unit/validation/test-joi-extensions-file-utils.yaml' })).toBe(TYPE_YAML)
);
it('should infer the default target from relative path string with existing file having an unknown file type', () =>
From 923aa0f184aab09e2cbb67127181106fe2574cbb Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 1 Sep 2017 09:28:33 +0200
Subject: [PATCH 29/58] Add CLI example at the beginning
---
README.md | 12 ++++++++++++
readme/DOCUMENTATION.md | 10 ++++++++++
2 files changed, 22 insertions(+)
diff --git a/README.md b/README.md
index 707d5d0..69d8fb0 100644
--- a/README.md
+++ b/README.md
@@ -108,6 +108,8 @@ npm install jy-transform --global
- [Transform from Source to Destination](#transform-from-source-to-destination)
- [Read into JS object from particular Source (File, Stream or JS Object)](#read-into-js-object-from-particular-source-file-stream-or-js-object)
- [Write JS object to particular Destination](#write-js-object-to-particular-destination)
+- [CLI in 3 Seconds](#cli-in-3-seconds)
+ - [File Transformation](#file-transformation)
- [Why This Module?](#why-this-module)
- [Usage](#usage)
- [Usage Types](#usage-types)
@@ -203,6 +205,16 @@ try {
}
```
+## CLI in 3 Seconds
+
+### File Transformation
+
+E.g. transform YAML content file to a JSON file with an indention of 4:
+
+```text
+$ jyt foo/bar.yaml -t json -i 4
+```
+
## Why This Module?
After struggling with some huge YAML file and accidentally
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index 70fcdcb..f9f4f3f 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -78,6 +78,16 @@ try {
}
```
+## CLI in 3 Seconds
+
+### File Transformation
+
+E.g. transform YAML content file to a JSON file with an indention of 4:
+
+```text
+$ jyt foo/bar.yaml -t json -i 4
+```
+
## Why This Module?
After struggling with some huge YAML file and accidentally
From bcd6402bffb217d55b986e22d7016bf5ec655c69 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 1 Sep 2017 09:32:41 +0200
Subject: [PATCH 30/58] Remove unneeded api reference section
---
README.md | 7 -------
readme/DOCUMENTATION.md | 6 ------
2 files changed, 13 deletions(-)
diff --git a/README.md b/README.md
index 69d8fb0..0848f7e 100644
--- a/README.md
+++ b/README.md
@@ -119,7 +119,6 @@ npm install jy-transform --global
- [Examples](#examples)
- [Origin and Target Type Inference](#origin-and-target-type-inference)
- [API Usage](#api-usage)
-- [API Reference](#api-reference)
- [Contributing](#contributing)
- [Further information](#further-information)
@@ -780,12 +779,6 @@ you can do almost everything with the JS object, like
- Validating and throwing/resolving with error if not valid
- ...
-## API Reference
-
-For more details on how to use the API, please refer to the
-[API Reference](https://github.com/deadratfink/jy-transform/wiki/API-public-v3)
-wiki which describes the full API and provides more examples.
-
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index f9f4f3f..efcebab 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -653,12 +653,6 @@ you can do almost everything with the JS object, like
- Validating and throwing/resolving with error if not valid
- ...
-## API Reference
-
-For more details on how to use the API, please refer to the
-[API Reference](https://github.com/deadratfink/jy-transform/wiki/API-public-v3)
-wiki which describes the full API and provides more examples.
-
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an
From ea468f9a15a29d278e20f82d25a35e04c624d72d Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 8 Sep 2017 08:25:31 +0200
Subject: [PATCH 31/58] Add bithound overall
---
.eslintignore | 3 +--
.jestrc.js | 1 -
bin/test.sh | 3 ++-
readme/BADGES.md | 1 +
src/debug-log.js | 29 -----------------------------
src/io-utils.js | 2 +-
6 files changed, 5 insertions(+), 34 deletions(-)
delete mode 100644 src/debug-log.js
diff --git a/.eslintignore b/.eslintignore
index 7d53bb8..3881da2 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1,7 +1,6 @@
coverage/**
node_modules/**
api-docs
-coverage/
readme/
.idea
lib/
@@ -10,5 +9,5 @@ test/data
test/tmp
test/functional/tmp
-# TODO reve later when test os done
+# TODO revert later when test is done
test/unit/test-cli.js
diff --git a/.jestrc.js b/.jestrc.js
index 8bdb047..329904d 100644
--- a/.jestrc.js
+++ b/.jestrc.js
@@ -5,7 +5,6 @@ module.exports = {
'!lib/**/*.js',
'src/**/*.js',
'!src/cli.js', // TODO: maybe later!
- '!src/debug-log.js', // TODO: maybe later!
'index.js',
'jyt',
],
diff --git a/bin/test.sh b/bin/test.sh
index 1a11dad..23f25c3 100644
--- a/bin/test.sh
+++ b/bin/test.sh
@@ -20,7 +20,8 @@ fi
#git checkout --track origin/master
#git checkout --track origin/development
#export GIT_MERGE_AUTOEDIT=no
-#git config gitflow.branch.develop development
+#git config gi
+# tflow.branch.develop development
#git config gitflow.prefix.versiontag v
#git flow init -fd
#git flow release start $VERSION
diff --git a/readme/BADGES.md b/readme/BADGES.md
index 1dcc8f8..ea6fdf9 100644
--- a/readme/BADGES.md
+++ b/readme/BADGES.md
@@ -10,6 +10,7 @@
[![codecov.io][cc-image-master]][cc-url-master]
[![coveralls.io][ca-image-master]][ca-url-master]
[![inch-ci.org][inch-image-master]][inch-url-master]
+[![bitHound Overall Score](https://www.bithound.io/github/deadratfink/jy-transform/badges/score.svg)](https://www.bithound.io/github/deadratfink/jy-transform)
[![bitHound Code][bithound-code-image]][bithound-url]
[![bitHound Dependencies][bitHound-dependencies-image]][bitHound-dependencies]
[![bitHound Dev Dependencies][bitHound-dev-dependencies-image]][bitHound-dependencies]
diff --git a/src/debug-log.js b/src/debug-log.js
deleted file mode 100644
index 0bc339f..0000000
--- a/src/debug-log.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* eslint-disable no-console */
-
-/**
- * @module jy-transform:debug-log
- * @description The debug logger. Can be enabled via environment variables (set to `true`):
- * - `JYT_DEBUG`: (only DEBUG logging via `console.log`)
- * - `JYT_DEBUG`: (only ERROR logging via `console.error`)
- * @private
- */
-
-/**
- * DEBUG function.
- *
- * @protected
- */
-export const debug = process.env.JYT_DEBUG === 'true' ?
- console.log.bind(null, '[DEBUG][jyt.js]:') :
- (() => null);
-
-/**
- * DEBUG function.
- *
- * @protected
- */
-export const error = process.env.JYT_ERROR === 'true' ?
- console.error.bind(null, '[ERROR][jyt.js]:') :
- (() => null);
-
-/* eslint-enable no-console */
diff --git a/src/io-utils.js b/src/io-utils.js
index d5ff4c3..9e97a80 100644
--- a/src/io-utils.js
+++ b/src/io-utils.js
@@ -79,7 +79,7 @@ export async function readYamlFromfile(file) {
// load source from YAML file
const yaml = await fsPromisified.readFile(file, UTF8);
try {
- return jsYaml.safeLoad(yaml); // TODO promisify???
+ return jsYaml.safeLoad(yaml);
} catch (err) { // probably a YAMLException
throw err;
}
From cd681df6bec063b1932ffba4f941689c1c60f87d Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 8 Sep 2017 10:31:49 +0200
Subject: [PATCH 32/58] update bithound config
---
.bithoundrc | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
diff --git a/.bithoundrc b/.bithoundrc
index be96efc..1493b3b 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -1,12 +1,19 @@
{
"critics": {
- "lint": {
- "engine": "eslint"
- }
+ "lint": {
+ "engine": "eslint",
+ "configLocation": ".eslintrc.js",
+ "ignoreLocation": ".eslintignore"
+ }
},
"dependencies": {
"unused-ignores": [
"eslint"
+ ],
+ "mute": [
+ "package-json-to-readme",
+ "jsdoc-to-markdown",
+ "inchjs"
]
}
"ignore": [
@@ -17,6 +24,7 @@
"**/readme/**"
],
"test": [
- "**/test/unit/**"
+ "**/test/unit/**",
+ "**/test/functional/**"
]
}
From 0e7b4b6e97a9e334442cf70df8413e0f11b08f20 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 8 Sep 2017 10:33:51 +0200
Subject: [PATCH 33/58] update bithound config
---
.bithoundrc | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/.bithoundrc b/.bithoundrc
index 1493b3b..8a211c0 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -21,7 +21,9 @@
"**/coverage/**",
"**/lib/**",
"**/node_modules/**",
- "**/readme/**"
+ "**/readme/**",
+ "**/test/tmp/**"
+ "**/test/functional/tmp/**"
],
"test": [
"**/test/unit/**",
From 1686f632daf93f1f0afedf7a914fffcb4ad6b42f Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 8 Sep 2017 10:39:10 +0200
Subject: [PATCH 34/58] update bithound config
---
.bithoundrc | 3 +++
1 file changed, 3 insertions(+)
diff --git a/.bithoundrc b/.bithoundrc
index 8a211c0..e361a40 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -4,6 +4,9 @@
"engine": "eslint",
"configLocation": ".eslintrc.js",
"ignoreLocation": ".eslintignore"
+ },
+ "wc": {
+ "limit": 500
}
},
"dependencies": {
From 84bc313c098a89f3562ba766aabbc001eb69745b Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 8 Sep 2017 13:36:08 +0200
Subject: [PATCH 35/58] Add bithound, clean a test
---
package.json | 4 +++-
test/functional/test-reader.js | 4 ----
2 files changed, 3 insertions(+), 5 deletions(-)
diff --git a/package.json b/package.json
index 24d67b0..e7345a9 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"test": "jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
"eslint": "eslint .",
"nsp": "nsp check",
- "inch": "inchjs suggest && inchjs list --all && inchjs stats"
+ "inch": "inchjs suggest && inchjs list --all && inchjs stats",
+ "bithound": "bithound check git@github.com:deadratfink/jy-transform.git"
},
"engines": {
"node": ">=5.0.0"
@@ -48,6 +49,7 @@
"babel-plugin-transform-flow-strip-types": "~6.22.0",
"babel-plugin-transform-runtime": "~6.23.0",
"babel-preset-env": "~1.6.0",
+ "bithound": "~1.7.0",
"chalk": "~2.1.0",
"codacy-coverage": "~2.0.2",
"codeclimate-test-reporter": "~0.5.0",
diff --git a/test/functional/test-reader.js b/test/functional/test-reader.js
index 9dade25..8ff4b32 100644
--- a/test/functional/test-reader.js
+++ b/test/functional/test-reader.js
@@ -244,10 +244,6 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
expectReaderSuccess({ src: './test/data/test-data.yaml' }, 'myproperty', 'old value')
);
- it('should read JS from object successfully', () => // TODO
- expectReaderSuccess({ src: { test: 'value' } }, 'test', 'value')
- );
-
it('should read YAML from stream successfully', () =>
expectReaderSuccess({
origin: TYPE_YAML,
From 05d7bc8c98323e273fc34d49ba5d8c1bf1e02827 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 29 Sep 2017 17:35:07 +0200
Subject: [PATCH 36/58] Dependency update and tests/eslint fixed for it
---
.bithoundrc | 5 +--
.eslintrc.js | 1 +
package.json | 18 +++++------
src/cli.js | 4 +--
test/functional/test-reader.js | 35 +++++++++++----------
test/functional/test-transformer.js | 23 +++++++++-----
test/functional/test-writer.js | 30 ++++++++++--------
test/unit/validation/test-options-schema.js | 17 +++++-----
8 files changed, 73 insertions(+), 60 deletions(-)
diff --git a/.bithoundrc b/.bithoundrc
index e361a40..e550371 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -14,9 +14,10 @@
"eslint"
],
"mute": [
- "package-json-to-readme",
+ "bithound",
+ "inchjs",
"jsdoc-to-markdown",
- "inchjs"
+ "package-json-to-readme"
]
}
"ignore": [
diff --git a/.eslintrc.js b/.eslintrc.js
index 8a79d29..cdb5e5e 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -26,6 +26,7 @@ module.exports = {
}],
'consistent-return': 'error',
'filenames/match-regex': ['error', '^[a-z0-9-]+$'],
+ 'function-paren-newline': 'off', //['error', 'multiline'],
'import/no-amd': 'error',
'import/no-commonjs': 'error',
'import/prefer-default-export': 'off',
diff --git a/package.json b/package.json
index e7345a9..e609aca 100644
--- a/package.json
+++ b/package.json
@@ -37,10 +37,10 @@
"cli": "~1.0.1",
"is-stream": "~1.1.0",
"joi": "~10.6.0",
- "js-yaml": " ~3.9.1",
+ "js-yaml": " ~3.10.0",
"json-stringify-safe": "~5.0.1",
"mkdirp-then": "~1.2.0",
- "promisify-es6": "~1.0.2",
+ "promisify-es6": "~1.0.3",
"serialize-js": "deadratfink/serialize-js#feature/single_quote_only"
},
"devDependencies": {
@@ -57,22 +57,22 @@
"coveralls": " ~2.13.1",
"cwd": "~0.10.0",
"doctoc": " ~1.3.0",
- "eslint": "~4.5.0",
- "eslint-config-airbnb-base": "~11.3.2",
+ "eslint": "~4.6.1",
+ "eslint-config-airbnb-base": "~12.0.0",
"eslint-plugin-filenames": "1.2.0",
"eslint-plugin-import": " ~2.7.0",
- "eslint-plugin-jest": " ~20.0.3",
+ "eslint-plugin-jest": " ~21.0.2",
"eslint-plugin-jest-async": " ~1.0.3",
- "eslint-plugin-jsdoc": " ~3.1.1",
+ "eslint-plugin-jsdoc": " ~3.1.2",
"fs-extra": "~4.0.1",
"inchjs": "~0.4.1",
- "jest": "~20.0.4",
+ "jest": "~21.0.2",
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": "~3.0.0",
"jsdoc-to-markdown": "~3.0.0",
- "nsp": "~2.7.0",
+ "nsp": "~2.8.0",
"package-json-to-readme": "~2.0.0",
- "winston": "~2.3.0"
+ "winston": "~2.3.1"
},
"preferGlobal": true,
"bin": {
diff --git a/src/cli.js b/src/cli.js
index 5906e5b..feb7ffd 100755
--- a/src/cli.js
+++ b/src/cli.js
@@ -104,13 +104,13 @@ function main(args, cliOptions) {
if (args.length > 0) {
cli.debug('input file: ' + args[0]);
- cliOptions.src = args[0];
+ cliOptions.src = args[0]; // eslint-disable-line prefer-destructuring
} else {
error('please specify an input file as first argument!');
}
if (args.length > 1) {
cli.debug('output file: ' + args[1]);
- cliOptions.dest = args[1];
+ cliOptions.dest = args[1]; // eslint-disable-line prefer-destructuring
} else {
cli.debug('output file not specified, using default');
}
diff --git a/test/functional/test-reader.js b/test/functional/test-reader.js
index 8ff4b32..2b77186 100644
--- a/test/functional/test-reader.js
+++ b/test/functional/test-reader.js
@@ -18,13 +18,17 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
/**
* Assert a `Error` properties for a given reader function.
*
- * @param {Object} options - The options which potentially produce the error.
- * @param {Object} [match={name:'Error'}] - The propertie(s) error should contain.
+ * @param {Object} options - The options which potentially produce the error.
+ * @param {string} [match=Error] - The error name to match.
* @private
*/
- const expectReaderError = (options, match = { name: 'Error' }) => {
+ const expectReaderError = async (options, match = 'Error') => {
expect.assertions(1);
- return expect(read(options)).rejects.toMatchObject(match);
+ try {
+ await read(options);
+ } catch (err) {
+ expect(err.name).toMatch(match);
+ }
};
/**
@@ -64,7 +68,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
src: './test/data/test-data.js',
imports: '',
};
- return expectReaderError(options, { name: 'ValidationError', isJoi: true });
+ return expectReaderError(options, 'ValidationError');
});
it('should read JS successfully', () =>
@@ -122,7 +126,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
src: './test/data/test-imports.js',
imports: invalidIdentifier,
};
- return expectReaderError(options, { name: 'ValidationError', isJoi: true });
+ return expectReaderError(options, 'ValidationError');
});
it('should reject reading JS from file with Error on non-existent identifier for options.imports: '
@@ -178,7 +182,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
},
imports: invalidIdentifier,
};
- return expectReaderError(options, { name: 'ValidationError', isJoi: true });
+ return expectReaderError(options, 'ValidationError');
});
it('should reject reading JS (deeply) from file with Error on non-existent identifier for options.imports: '
@@ -231,11 +235,11 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
);
it('should fail JS(ON) read by missing options', () =>
- expectReaderError(null, { name: 'ValidationError', isJoi: true })
+ expectReaderError(null, 'ValidationError')
);
it('should fail JS(ON) read by missing options.src', () =>
- expectReaderError({}, { name: 'ValidationError', isJoi: true })
+ expectReaderError({}, 'ValidationError')
);
});
@@ -263,26 +267,23 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - reader - ', () => {
);
it('should fail reading YAML by providing empty JS object as options.src', () =>
- expectReaderError({ src: {}, origin: TYPE_YAML }, { name: 'ValidationError', isJoi: true })
+ expectReaderError({ src: {}, origin: TYPE_YAML }, 'ValidationError')
);
it('should fail YAML reading by missing input options', () =>
- expectReaderError(null, { name: 'ValidationError', isJoi: true })
+ expectReaderError(null, 'ValidationError')
);
it('should fail reading YAML by missing options.src', () =>
- expectReaderError({}, { name: 'ValidationError', isJoi: true })
+ expectReaderError({}, 'ValidationError')
);
it('should fail reading YAML from configured directory source', () =>
- expectReaderError({ src: './test/data' }, { name: 'ValidationError', isJoi: true })
+ expectReaderError({ src: './test/data' }, 'ValidationError')
);
it('should fail reading YAML from non-existing file', () =>
- expectReaderError({ src: './test/data/non-existing.yml' }, {
- name: 'ValidationError',
- isJoi: true
- })
+ expectReaderError({ src: './test/data/non-existing.yml' }, 'ValidationError')
);
});
});
diff --git a/test/functional/test-transformer.js b/test/functional/test-transformer.js
index 5c89e6c..8c29617 100644
--- a/test/functional/test-transformer.js
+++ b/test/functional/test-transformer.js
@@ -129,25 +129,32 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - transformer - ', () => {
describe('Testing transform with middleware', () => {
it('should throw ValidationError if middleware passed is not a function type', async () => {
expect.assertions(1);
- await expect(transform(createOptions({}, {}, 'not a function')))
- .rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
+ try {
+ await transform(createOptions({}, {}, 'not a function'));
+ } catch (err) {
+ expect(err.name).toMatch('ValidationError');
+ }
});
it('should throw ValidationError if options.dest is not set and cannot be resolved from options.src type',
async () => {
expect.assertions(1);
- await expect(transform(createOptions({} /* We cannot infer destination from this src type! */)))
- .rejects.toMatchObject({ name: 'ValidationError', isJoi: true });
- });
+ try {
+ await transform(createOptions({} /* We cannot infer destination from undefined src type! */));
+ } catch (err) {
+ expect(err.name).toMatch('ValidationError');
+ }
+ }
+ );
- it('should not fail if middleware passed is returning a Promise', () => {
+ it('should not fail if transform callback passed is returning a Promise', () => {
expect.assertions(1);
const returningPromise = async object => object;
return expect(transform(createOptions({}, {}, returningPromise)))
.resolves.toBe('Writing JS to options.dest successful.');
});
- it('should not fail if middleware passed is not returning a Promise', () => {
+ it('should not fail if transform callback passed is not returning a Promise', () => {
expect.assertions(1);
const notReturningPromise = object => object;
return expect(transform(createOptions({}, {}, notReturningPromise)))
@@ -155,7 +162,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - transformer - ', () => {
});
});
- describe('Testing transform without middleware', () => {
+ describe('Testing transform without transform callback', () => {
it('should not fail', () => {
expect.assertions(1);
return expect(transform({ src: {}, dest: {} })).resolves.toBe('Writing JS to options.dest successful.');
diff --git a/test/functional/test-writer.js b/test/functional/test-writer.js
index a56574d..c3f8fa8 100644
--- a/test/functional/test-writer.js
+++ b/test/functional/test-writer.js
@@ -91,14 +91,18 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
/**
* Assert an `Error` for a given writer function.
*
- * @param {Object} object - The JS object to write.
- * @param {Object} options - The options which potentially produce the error.
- * @param {Object} [match={name:'Error'}] - The propertie(s) an error should contain.
+ * @param {Object} object - The JS object to write.
+ * @param {Object} options - The options which potentially produce the error.
+ * @param {string} [match=Error] - The error name to match.
* @private
*/
- const expectWriteError = (object, options, match = { name: 'Error' }) => {
+ const expectWriteError = async (object, options, match = 'Error') => {
expect.assertions(1);
- return expect(write(object, options)).rejects.toMatchObject(match);
+ try {
+ await write(object, options);
+ } catch (err) {
+ expect(err.name).toMatch(match);
+ }
};
/**
@@ -153,7 +157,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
dest: WRITER_TEST_BASE_DIR + '/test-data-by-js-stream-with-invalid-exports-identifier.js',
exports: '#3/-',
};
- return expectWriteError(JS_CONTENT, options, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, options, 'ValidationError');
});
it('should write JS to stream and fail by invalid exports identifier (\'#3/-\')', () => {
@@ -162,7 +166,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
dest: fs.createWriteStream(file),
exports: '#3/-',
};
- return expectWriteError(JS_CONTENT, options, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, options, 'ValidationError');
});
it('should write JS to stream and fail by invalid exports identifier (\'if\')', () => {
@@ -171,7 +175,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
dest: fs.createWriteStream(file),
exports: 'if',
};
- return expectWriteError(JS_CONTENT, options, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, options, 'ValidationError');
});
it('should write JS to stream and fail by provoked error', () => {
@@ -203,7 +207,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
dest: {},
exports: '',
};
- return expectWriteError(JS_CONTENT, options, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, options, 'ValidationError');
});
const exports = 'foo';
@@ -227,11 +231,11 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
dest: {},
exports: invalidIdentifier,
};
- return expectWriteError(JS_CONTENT, options, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, options, 'ValidationError');
});
it('should reject write JS with Error on missing destination', () => {
- return expectWriteError(JS_CONTENT, {}, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, {}, 'ValidationError');
});
it('should reject write JS to file by invalid file path', (done) => {
@@ -353,11 +357,11 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - writer - ', () => {
};
return expectWriteError(invalidYamlJson, {
dest: WRITER_TEST_BASE_DIR + '/test-data-by-js-to-file-invalid.yaml'
- }, { name: 'YAMLException' });
+ }, 'YAMLException');
});
it('should reject with Error on missing destination', () => {
- return expectWriteError(JS_CONTENT, {}, { name: 'ValidationError', isJoi: true });
+ return expectWriteError(JS_CONTENT, {}, 'ValidationError');
});
});
diff --git a/test/unit/validation/test-options-schema.js b/test/unit/validation/test-options-schema.js
index 8462458..332efd2 100644
--- a/test/unit/validation/test-options-schema.js
+++ b/test/unit/validation/test-options-schema.js
@@ -37,12 +37,13 @@ import Joi from '../../../src/validation/joi-extensions';
* @param {Schema} schema - The validation schema.
* @private
*/
-function expectOptionsValidationError(invalidOptions, schema) {
+async function expectOptionsValidationError(invalidOptions, schema) {
expect.assertions(1);
- return expect(Joi.validate(invalidOptions, schema)).rejects.toMatchObject({
- name: 'ValidationError',
- isJoi: true,
- });
+ try {
+ await Joi.validate(invalidOptions, schema);
+ } catch (err) {
+ expect(err.name).toMatch('ValidationError');
+ }
}
/**
@@ -60,12 +61,10 @@ function expectOptionsValidationSuccess(validOptions, schema) {
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
describe('Testing readOptionsSchema validation', () => {
it('should reject when options is missing (null)', () =>
- expectOptionsValidationError(null, readOptionsSchema)
- );
+ expectOptionsValidationError(null, readOptionsSchema));
it('should reject when options is missing (undefined)', () =>
- expectOptionsValidationError(undefined, readOptionsSchema)
- );
+ expectOptionsValidationError(undefined, readOptionsSchema));
it('should set all defaults', async () => {
expect.assertions(2);
From e7d69941a9767e7be18ec52a26c2e3e3a753f83b Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 29 Sep 2017 17:44:33 +0200
Subject: [PATCH 37/58] Fix readme
---
PACKAGE.md | 1 +
README.md | 54 ++++++++++++++++++++---------------------
readme/DOCUMENTATION.md | 51 +++++++++++++++++++-------------------
3 files changed, 53 insertions(+), 53 deletions(-)
diff --git a/PACKAGE.md b/PACKAGE.md
index d95726f..55fe591 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -34,6 +34,7 @@ npm test
- [babel-plugin-transform-flow-strip-types](https://github.com/babel/babel/tree/master/packages): Strip flow type annotations from your output code.
- [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
+- [bithound](https://github.com/bithound/cli.bithound.io): Commands for interacting with bitHound: https://bithound.io
- [chalk](https://github.com/chalk/chalk): Terminal string styling done right
- [codacy-coverage](https://github.com/codacy/node-codacy-coverage): Code Coverage reporter for Codacy.com
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
diff --git a/README.md b/README.md
index 0848f7e..b2d2e9d 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,7 @@
[![codecov.io][cc-image-master]][cc-url-master]
[![coveralls.io][ca-image-master]][ca-url-master]
[![inch-ci.org][inch-image-master]][inch-url-master]
+[![bitHound Overall Score](https://www.bithound.io/github/deadratfink/jy-transform/badges/score.svg)](https://www.bithound.io/github/deadratfink/jy-transform)
[![bitHound Code][bithound-code-image]][bithound-url]
[![bitHound Dependencies][bitHound-dependencies-image]][bitHound-dependencies]
[![bitHound Dev Dependencies][bitHound-dev-dependencies-image]][bitHound-dependencies]
@@ -114,10 +115,10 @@ npm install jy-transform --global
- [Usage](#usage)
- [Usage Types](#usage-types)
- [Use Cases](#use-cases)
+ - [Origin and Target Type Inference](#origin-and-target-type-inference)
- [Limitations](#limitations)
- [CLI Usage](#cli-usage)
- [Examples](#examples)
- - [Origin and Target Type Inference](#origin-and-target-type-inference)
- [API Usage](#api-usage)
- [Contributing](#contributing)
- [Further information](#further-information)
@@ -306,6 +307,19 @@ Additionally, on API level to:
- JS as a simple reference
- YAML and JSON as a serialized string
+### Origin and Target Type Inference
+
+This module supports automatic type inference from file extensions as shown by the following table (from-to):
+
+| File Extension | Type |
+| --- | --- |
+| _*.yaml_ | _yaml_ |
+| _*.yml_ | _yaml_ |
+| _*.js_ | _js_ |
+| _*.json_ | _json_ |
+
+> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
+
### Limitations
- Since this module is build to transform from and to different type formats, any
@@ -527,7 +541,7 @@ bar: foo
> dest: {},
> exports: 'bar'
> };
-
+>
> //...transform
> ```
>
@@ -588,20 +602,6 @@ $ jyt foo.js -i 4 -f
> the `src` _foo.js_, named as _foo(1).js_; note the consecutive number! Naturally,
> another run of the command would result in a file called _foo(2).js_ and so forth.
-### Origin and Target Type Inference
-
-The examples above have shown that we have an automatic type inference from file
-extensions. This is supported as shown by the following table (from-to):
-
-| File Extension | Type |
-| --- | --- |
-| _*.yaml_ | _yaml_ |
-| _*.yml_ | _yaml_ |
-| _*.js_ | _js_ |
-| _*.json_ | _json_ |
-
-> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
-
### API Usage
Since the usage on CLI is a 2-step process:
@@ -720,22 +720,22 @@ Let's assume we have some Promise functions to apply. For simplicity reasons we
simulate these for the moment by some functions, each adding a key-value to the
given (initially empty) JS object.
-> **NOTE:** each of them has to resolve with the `object` object!
+> **NOTE:** each of them has to resolve with the `data` object!
```javascript
-const key1 = async (object) => {
- object.key1 = 'value1';
- return object;
+const key1 = async (data) => {
+ data.key1 = 'value1';
+ return data;
};
-const key2 = async (object) => {
- object.key2 = 'value2';
- return object;
+const key2 = async (data) => {
+ data.key2 = 'value2';
+ return data;
};
-const key3 = async (object) => {
- object.key3 = 'value3';
- return object;
+const key3 = async (data) => {
+ data.key3 = 'value3';
+ return data;
};
```
@@ -748,7 +748,7 @@ import { transform } from 'jy-transform';
const options = {
src: {},
- transform: async (object) => Promise.all([key1(object), key2(object), key3(object)])
+ transform: (data) => Promise.all([key1(data), key2(data), key3(data)])
.then(result => result[result.length - 1])
};
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index efcebab..0be0c4a 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -180,6 +180,19 @@ Additionally, on API level to:
- JS as a simple reference
- YAML and JSON as a serialized string
+### Origin and Target Type Inference
+
+This module supports automatic type inference from file extensions as shown by the following table (from-to):
+
+| File Extension | Type |
+| --- | --- |
+| _*.yaml_ | _yaml_ |
+| _*.yml_ | _yaml_ |
+| _*.js_ | _js_ |
+| _*.json_ | _json_ |
+
+> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
+
### Limitations
- Since this module is build to transform from and to different type formats, any
@@ -401,7 +414,7 @@ bar: foo
> dest: {},
> exports: 'bar'
> };
-
+>
> //...transform
> ```
>
@@ -462,20 +475,6 @@ $ jyt foo.js -i 4 -f
> the `src` _foo.js_, named as _foo(1).js_; note the consecutive number! Naturally,
> another run of the command would result in a file called _foo(2).js_ and so forth.
-### Origin and Target Type Inference
-
-The examples above have shown that we have an automatic type inference from file
-extensions. This is supported as shown by the following table (from-to):
-
-| File Extension | Type |
-| --- | --- |
-| _*.yaml_ | _yaml_ |
-| _*.yml_ | _yaml_ |
-| _*.js_ | _js_ |
-| _*.json_ | _json_ |
-
-> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
-
### API Usage
Since the usage on CLI is a 2-step process:
@@ -594,22 +593,22 @@ Let's assume we have some Promise functions to apply. For simplicity reasons we
simulate these for the moment by some functions, each adding a key-value to the
given (initially empty) JS object.
-> **NOTE:** each of them has to resolve with the `object` object!
+> **NOTE:** each of them has to resolve with the `data` object!
```javascript
-const key1 = async (object) => {
- object.key1 = 'value1';
- return object;
+const key1 = async (data) => {
+ data.key1 = 'value1';
+ return data;
};
-const key2 = async (object) => {
- object.key2 = 'value2';
- return object;
+const key2 = async (data) => {
+ data.key2 = 'value2';
+ return data;
};
-const key3 = async (object) => {
- object.key3 = 'value3';
- return object;
+const key3 = async (data) => {
+ data.key3 = 'value3';
+ return data;
};
```
@@ -622,7 +621,7 @@ import { transform } from 'jy-transform';
const options = {
src: {},
- transform: async (object) => Promise.all([key1(object), key2(object), key3(object)])
+ transform: (data) => Promise.all([key1(data), key2(data), key3(data)])
.then(result => result[result.length - 1])
};
From 981dded08a07265e160d101341d1463a6223e223 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 29 Sep 2017 17:53:16 +0200
Subject: [PATCH 38/58] Update deps
---
package.json | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/package.json b/package.json
index e609aca..dcef972 100644
--- a/package.json
+++ b/package.json
@@ -36,7 +36,7 @@
"dependencies": {
"cli": "~1.0.1",
"is-stream": "~1.1.0",
- "joi": "~10.6.0",
+ "joi": "~11.1.1",
"js-yaml": " ~3.10.0",
"json-stringify-safe": "~5.0.1",
"mkdirp-then": "~1.2.0",
@@ -45,7 +45,7 @@
},
"devDependencies": {
"babel-cli": "~6.26.0",
- "babel-eslint": " ~7.2.3",
+ "babel-eslint": " ~8.0.1",
"babel-plugin-transform-flow-strip-types": "~6.22.0",
"babel-plugin-transform-runtime": "~6.23.0",
"babel-preset-env": "~1.6.0",
@@ -54,19 +54,19 @@
"codacy-coverage": "~2.0.2",
"codeclimate-test-reporter": "~0.5.0",
"codecov": " ~2.3.0",
- "coveralls": " ~2.13.1",
+ "coveralls": " ~3.0.0",
"cwd": "~0.10.0",
"doctoc": " ~1.3.0",
- "eslint": "~4.6.1",
+ "eslint": "~4.7.2",
"eslint-config-airbnb-base": "~12.0.0",
"eslint-plugin-filenames": "1.2.0",
"eslint-plugin-import": " ~2.7.0",
- "eslint-plugin-jest": " ~21.0.2",
+ "eslint-plugin-jest": " ~21.2.0",
"eslint-plugin-jest-async": " ~1.0.3",
"eslint-plugin-jsdoc": " ~3.1.2",
"fs-extra": "~4.0.1",
"inchjs": "~0.4.1",
- "jest": "~21.0.2",
+ "jest": "~21.2.1",
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": "~3.0.0",
"jsdoc-to-markdown": "~3.0.0",
From b11ce1affd85341817730c6a5b330d03215b8eb4 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Mon, 2 Oct 2017 10:19:39 +0200
Subject: [PATCH 39/58] Some readme fixes
---
README.md | 28 ++++++++++++++--------------
readme/DOCUMENTATION.md | 28 ++++++++++++++--------------
2 files changed, 28 insertions(+), 28 deletions(-)
diff --git a/README.md b/README.md
index b2d2e9d..e8ce644 100644
--- a/README.md
+++ b/README.md
@@ -133,13 +133,13 @@ npm install jy-transform --global
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // E.g. read from YAML file...
- transform: async (object) => { // ...with exchanging value...
+ src: 'foo/bar.yaml', // E.g. read from YAML file...
+ transform: async (object) => { // ...with exchanging value...
object.foo = 'new value';
return object;
},
- dest: 'foo/bar.json', // ...to a new JSON file.
- indent: 4, // Ensure an indentation of 4.
+ dest: 'foo/bar-transformed.json', // ...to a new JSON file.
+ indent: 4, // Ensure an indentation of 4.
};
// ---- Promise style:
@@ -318,7 +318,7 @@ This module supports automatic type inference from file extensions as shown by t
| _*.js_ | _js_ |
| _*.json_ | _json_ |
-> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
+> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the `origin` or `target` type!
### Limitations
@@ -326,7 +326,7 @@ This module supports automatic type inference from file extensions as shown by t
`Function`s residing in JS type objects are _not_ supported, e.g. transforming
```javascript
- module.exports = {
+ export const foobar = {
fooKey: 'foo',
fooFunction: function foo() {
//...
@@ -508,11 +508,11 @@ from exactly the one you specify, then provide the `-m` (`--imports`) option.
In this this example we have a _foo.js_ file exporting _two_ objects:
```javascript
-module.exports.foo = {
+export const foo = {
foo: 'bar'
};
-module.exports.bar = {
+export const bar = {
bar: 'foo'
};
```
@@ -574,8 +574,8 @@ $ jyt foo.yaml foobar.js -x foobar
This generates the following output in JS file using `foobar` as identifier:
```javascript
-module.exports.foobar = {
- foo: "bar"
+export const foobar = {
+ foo: 'bar'
}
```
@@ -622,17 +622,17 @@ For more details about this and all the functions provided by this module please
The `origin` and `target` type inference is also standard for the API level.
+> **HINT:** of course, if you like you can use the `read`and `write` functionality solely besides any transformation needs.
+
#### API Properties
-The public `transform` function (that does not mean the optional `transform `callback here!) takes
+The public `transform` function (that does not mean the optional `transform` callback here!) takes
the necessary `options` for the transformation:
```javascript
-async function transform(options)
+[async] function transform(options)
```
-> **HINT:** of course, if you like you can use the `read`and `write` functionality solely besides any transformation needs.
-
#### Options
For a detailed description see:
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index 0be0c4a..a7a132a 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -6,13 +6,13 @@
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // E.g. read from YAML file...
- transform: async (object) => { // ...with exchanging value...
+ src: 'foo/bar.yaml', // E.g. read from YAML file...
+ transform: async (object) => { // ...with exchanging value...
object.foo = 'new value';
return object;
},
- dest: 'foo/bar.json', // ...to a new JSON file.
- indent: 4, // Ensure an indentation of 4.
+ dest: 'foo/bar-transformed.json', // ...to a new JSON file.
+ indent: 4, // Ensure an indentation of 4.
};
// ---- Promise style:
@@ -191,7 +191,7 @@ This module supports automatic type inference from file extensions as shown by t
| _*.js_ | _js_ |
| _*.json_ | _json_ |
-> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the origin or target type!
+> **NOTE:** if you have files without an extension or e.g. _*.txt_ you _have_ to specify the `origin` or `target` type!
### Limitations
@@ -199,7 +199,7 @@ This module supports automatic type inference from file extensions as shown by t
`Function`s residing in JS type objects are _not_ supported, e.g. transforming
```javascript
- module.exports = {
+ export const foobar = {
fooKey: 'foo',
fooFunction: function foo() {
//...
@@ -381,11 +381,11 @@ from exactly the one you specify, then provide the `-m` (`--imports`) option.
In this this example we have a _foo.js_ file exporting _two_ objects:
```javascript
-module.exports.foo = {
+export const foo = {
foo: 'bar'
};
-module.exports.bar = {
+export const bar = {
bar: 'foo'
};
```
@@ -447,8 +447,8 @@ $ jyt foo.yaml foobar.js -x foobar
This generates the following output in JS file using `foobar` as identifier:
```javascript
-module.exports.foobar = {
- foo: "bar"
+export const foobar = {
+ foo: 'bar'
}
```
@@ -495,17 +495,17 @@ For more details about this and all the functions provided by this module please
The `origin` and `target` type inference is also standard for the API level.
+> **HINT:** of course, if you like you can use the `read`and `write` functionality solely besides any transformation needs.
+
#### API Properties
-The public `transform` function (that does not mean the optional `transform `callback here!) takes
+The public `transform` function (that does not mean the optional `transform` callback here!) takes
the necessary `options` for the transformation:
```javascript
-async function transform(options)
+[async] function transform(options)
```
-> **HINT:** of course, if you like you can use the `read`and `write` functionality solely besides any transformation needs.
-
#### Options
For a detailed description see:
From aeedf4b61407933d34ba2f7dbcc6ac1413b4607a Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 5 Oct 2017 23:19:24 +0200
Subject: [PATCH 40/58] transpile to node 5
---
.babelrc | 22 ++++++++++++++--------
1 file changed, 14 insertions(+), 8 deletions(-)
diff --git a/.babelrc b/.babelrc
index 5bb615c..4862d50 100644
--- a/.babelrc
+++ b/.babelrc
@@ -1,15 +1,21 @@
{
"presets": [
- ["env", {
- "targets": {
- "node": "current"
+ [
+ "env",
+ {
+ "targets": {
+ "node": "5"
+ }
}
- }]
+ ]
],
"plugins": [
- ["transform-runtime", {
- "polyfill": false,
- "regenerator": true
- }]
+ [
+ "transform-runtime",
+ {
+ "polyfill": false,
+ "regenerator": true
+ }
+ ]
]
}
From 195d1fa25da55bc9d97c1240f742d6546cae72a9 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 5 Oct 2017 23:45:22 +0200
Subject: [PATCH 41/58] Update some deps
---
package.json | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/package.json b/package.json
index dcef972..925a088 100644
--- a/package.json
+++ b/package.json
@@ -57,7 +57,7 @@
"coveralls": " ~3.0.0",
"cwd": "~0.10.0",
"doctoc": " ~1.3.0",
- "eslint": "~4.7.2",
+ "eslint": "~4.8.0",
"eslint-config-airbnb-base": "~12.0.0",
"eslint-plugin-filenames": "1.2.0",
"eslint-plugin-import": " ~2.7.0",
@@ -72,7 +72,7 @@
"jsdoc-to-markdown": "~3.0.0",
"nsp": "~2.8.0",
"package-json-to-readme": "~2.0.0",
- "winston": "~2.3.1"
+ "winston": "~2.4.0"
},
"preferGlobal": true,
"bin": {
From a3d5c5704ff83eaf283902de09023150181324ce Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Fri, 6 Oct 2017 00:46:43 +0200
Subject: [PATCH 42/58] Rename options to es5 and double
---
.jestrc.js | 9 +--
package.json | 2 +-
src/cli.js | 36 ++++++-----
src/constants.js | 4 +-
src/serialize-utils.js | 16 ++---
src/validation/options-schema.js | 70 +++++++++++----------
test/functional/test-jyt-cli.js | 6 +-
test/functional/test-transformer.js | 4 +-
test/unit/test-serialize-utils.js | 18 +++---
test/unit/validation/test-options-schema.js | 68 ++++++++++++++++++--
10 files changed, 150 insertions(+), 83 deletions(-)
diff --git a/.jestrc.js b/.jestrc.js
index 329904d..4485542 100644
--- a/.jestrc.js
+++ b/.jestrc.js
@@ -20,16 +20,17 @@ module.exports = {
},
mapCoverage: true,
testMatch: [
- // '**/test/functional/test-jyt-cli.js',
+ // '**/test/unit/test-serialize-utils.js',
+ // '**/test/functional/test-jyt-cli.js',
// '**/test/unit/validation/test-joi-extensions-file-helper.js',
// '**/test/unit/validation/test-joi-extensions-identifier-helper.js',
//'**/test/functional/test-transformer.js',
// '**/test/unit/test-index.js',
//'**/test/unit/test-reader.js',
// '**/test/unit/test-writer.js',
- // '**/test/unit/validation/test-options-schema.js',
- '**/test/unit/**/*.js',
- '**/test/functional/**/*.js',
+ //'**/test/unit/validation/test-options-schema.js',
+ '**/test/unit/**/*.js',
+ '**/test/functional/**/*.js',
//'**/test/unit/validation/test-options-schema-helper.js',
diff --git a/package.json b/package.json
index 925a088..1576dbb 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,7 @@
"jsdoc-to-markdown": "~3.0.0",
"nsp": "~2.8.0",
"package-json-to-readme": "~2.0.0",
- "winston": "~2.4.0"
+ "winston": "^2.4.0"
},
"preferGlobal": true,
"bin": {
diff --git a/src/cli.js b/src/cli.js
index feb7ffd..5aee982 100755
--- a/src/cli.js
+++ b/src/cli.js
@@ -12,8 +12,8 @@ import {
TYPE_JSON,
TYPE_YAML,
DEFAULT_STRICT,
- DEFAULT_NO_ES6,
- DEFAULT_NO_SINGLE_QUOTES,
+ DEFAULT_ES5,
+ DEFAULT_DOUBLE_QUOTES,
} from './constants';
import { transform } from './transformer';
@@ -53,24 +53,32 @@ const packagePath = path.join(__dirname, '../package.json');
* @private
*/
const cliOptionsSchema = {
- origin: ['o', 'The origin type of INPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML + ' ]',
+ origin: [
+ 'o', 'The origin type of INPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML + ' ]',
'string', ORIGIN_DESCRIPTION],
- target: ['t', 'The target type of OUTPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML + ' ]',
+ target: [
+ 't', 'The target type of OUTPUT-FILE: [ ' + TYPE_JS + ' | ' + TYPE_JSON + ' | ' + TYPE_YAML + ' ]',
'string', TARGET_DESCRIPTION],
indent: ['i', 'The indention for pretty-print: 1 - 8', 'int', DEFAULT_INDENT],
- force: ['f', 'Force overwriting of existing output files on write phase: when files are not overwritten (which' +
+ force: [
+ 'f', 'Force overwriting of existing output files on write phase: when files are not overwritten (which' +
' is default), then the next transformation with same output file name gets a consecutive number on the base' +
' file name, e.g. in case of foo.yaml it would be foo(1).yaml', 'boolean', DEFAULT_FORCE_FILE_OVERWRITE],
- imports: ['m', 'Define an identifier for object (to read as "export const identifier / module.exports[.identifier]"' +
- ' from JS source file only, must be a valid JS identifier!)', 'string', DEFAULT_JS_IMPORTS_IDENTIFIER],
- exports: ['x', 'Define an identifier for object (write to "export const identifier / module.exports[.identifier]"' +
- ' in JS destination file only, must be a valid JS identifier!)', 'string', DEFAULT_JS_EXPORTS_IDENTIFIER],
- strict: ['s', 'Whether to write a "use strict;" in JS type output',
+ imports: [
+ 'm', 'Define an identifier for object (to read as "export const identifier / module.exports[.identifier]"' +
+ ' from JS source file only, must be a valid JS identifier!)', 'string', DEFAULT_JS_IMPORTS_IDENTIFIER],
+ exports: [
+ 'x', 'Define an identifier for object (write to "export const identifier / module.exports[.identifier]"' +
+ ' in JS destination file only, must be a valid JS identifier!)', 'string', DEFAULT_JS_EXPORTS_IDENTIFIER],
+ strict: [
+ 's', 'Whether to write a "use strict;" in JS type output',
'boolean', DEFAULT_STRICT],
- 'no-es6': [false, 'Whether not to use ECMAScript6 syntax for JS type output like "module.exports" instead of ' +
- '"export default", applicable only for JS output', 'boolean', DEFAULT_NO_ES6],
- 'no-single': [false, 'Whether not to use single-quotes style for values in JS type output (i.e. double-quotes)',
- 'boolean', DEFAULT_NO_SINGLE_QUOTES],
+ es5: [
+ false, 'Whether not to use ECMAScript6 syntax for JS type output like "module.exports" instead of ' +
+ '"export default", applicable only for JS output', 'boolean', DEFAULT_ES5],
+ double: [
+ false, 'Whether not to use single-quotes style for values in JS type output (i.e. double-quotes)',
+ 'boolean', DEFAULT_DOUBLE_QUOTES],
};
/**
diff --git a/src/constants.js b/src/constants.js
index 8c1aebc..35e198f 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -120,7 +120,7 @@ export const DEFAULT_STRICT = false;
* @constant
* @private
*/
-export const DEFAULT_NO_ES6 = false;
+export const DEFAULT_ES5 = false;
/**
* Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes).
@@ -128,7 +128,7 @@ export const DEFAULT_NO_ES6 = false;
* @constant
* @private
*/
-export const DEFAULT_NO_SINGLE_QUOTES = false;
+export const DEFAULT_DOUBLE_QUOTES = false;
/**
* The `origin` description value.
diff --git a/src/serialize-utils.js b/src/serialize-utils.js
index b837689..2838af1 100644
--- a/src/serialize-utils.js
+++ b/src/serialize-utils.js
@@ -11,17 +11,17 @@ import serializeJs from 'serialize-js';
/**
* Creates a potential named `'module.exports[.exportsTo]'` string.
*
- * @param {boolean} es6 - Whether to use ECMAScript6 export syntax.
+ * @param {boolean} es5 - Whether to use ECMAScript5 export syntax.
* @param {string} [exportsTo] - The export name.
* @returns {Promise.} Resolves with the exports string.
* @private
*/
-export async function createExportString(es6, exportsTo) {
- let exports = es6 ? 'export' : 'module.exports';
+export async function createExportString(es5, exportsTo) {
+ let exports = es5 ? 'module.exports' : 'export';
if (exportsTo) {
- exports += es6 ? ` const ${exportsTo} = ` : '.' + exportsTo + ' = ';
+ exports += es5 ? '.' + exportsTo + ' = ' : ` const ${exportsTo} = `;
} else {
- exports += es6 ? ' default ' : ' = ';
+ exports += es5 ? ' = ' : ' default ';
}
return exports;
}
@@ -37,13 +37,13 @@ export async function createExportString(es6, exportsTo) {
export async function serializeJsToString(object, options) {
let useStrict = '';
if (options.strict) {
- const quote = options['no-single'] ? '"' : '\'';
+ const quote = options.double ? '"' : '\'';
useStrict = `${quote}use strict;${quote}${os.EOL}${os.EOL}`;
}
- const exportsStr = await createExportString(!options['no-es6'], options.exports);
+ const exportsStr = await createExportString(options.es5, options.exports);
return `${useStrict}${exportsStr}${serializeJs.serialize(object, {
indent: options.indent,
- forceSingleQuotes: !options['no-single'],
+ forceSingleQuotes: !options.double,
})};${os.EOL}`;
}
diff --git a/src/validation/options-schema.js b/src/validation/options-schema.js
index 7a62e97..27e5113 100644
--- a/src/validation/options-schema.js
+++ b/src/validation/options-schema.js
@@ -15,8 +15,8 @@ import {
MIN_YAML_INDENT,
MAX_INDENT,
DEFAULT_STRICT,
- DEFAULT_NO_ES6,
- DEFAULT_NO_SINGLE_QUOTES,
+ DEFAULT_ES5,
+ DEFAULT_DOUBLE_QUOTES,
} from '../constants';
/**
@@ -48,24 +48,24 @@ const strictSchema = Joi
.description('Whether to write a "use strict;" in JS type output.');
/**
- * The `no-es6` option schema.
+ * The `es5` option schema.
* @type {external:joi.Schema}
* @private
*/
-const noES6Schema = Joi
+const es5Schema = Joi
.boolean()
- .default(DEFAULT_NO_ES6)
+ .default(DEFAULT_ES5)
.description('Whether not to use ECMAScript6 syntax for JS type output like "module.exports" instead of ' +
'"export default", applicable only for JS output.');
/**
- * The `no-single` option schema.
+ * The `double` option schema.
* @type {external:joi.Schema}
* @private
*/
-const noSingleSchema = Joi
+const doubleSchema = Joi
.boolean()
- .default(DEFAULT_NO_SINGLE_QUOTES)
+ .default(DEFAULT_DOUBLE_QUOTES)
.description('Whether not to use single-quotes style for values in JS type output (i.e. double-quotes).');
/**
@@ -193,8 +193,8 @@ export const writeOptionsSchema = Joi.object().keys({
indent: indentSchema,
force: forceSchema,
strict: strictSchema,
- 'no-es6': noES6Schema,
- 'no-single': noSingleSchema,
+ es5: es5Schema,
+ double: doubleSchema,
}).default()
.required()
.unknown();
@@ -205,30 +205,32 @@ export const writeOptionsSchema = Joi.object().keys({
* @constant
* @private
*/
-export const transformOptionsSchema = readOptionsSchema.concat(Joi.object().keys({
- transform: Joi
- .func()
- .arity(1)
- .default(object => object)
- .description('The transformation function to alter a read object.'),
- dest: Joi
- .alternatives().try(
- Joi.string()
- .min(1)
- .label('dest - OUTPUT-FILE'),
- Joi.object().type(Stream.Writable),
- Joi.object().type(Object),
- )
- .default(inferDestDefaultFromSrc, 'try dest resolution from src if not set')
- .description('The output destination (if string type is treated as a file path).'),
- target: targetSchema,
- exports: exportsSchema,
- indent: indentSchema,
- force: forceSchema,
- strict: strictSchema,
- 'no-es6': noES6Schema,
- 'no-single': noSingleSchema,
-}).default()
+export const transformOptionsSchema = readOptionsSchema.concat(Joi
+ .object()
+ .keys({
+ transform: Joi
+ .func()
+ .arity(1)
+ .default(object => object)
+ .description('The transformation function to alter a read object.'),
+ dest: Joi
+ .alternatives().try(
+ Joi.string()
+ .min(1)
+ .label('dest - OUTPUT-FILE'),
+ Joi.object().type(Stream.Writable),
+ Joi.object().type(Object),
+ )
+ .default(inferDestDefaultFromSrc, 'try dest resolution from src if not set')
+ .description('The output destination (if string type is treated as a file path).'),
+ target: targetSchema,
+ exports: exportsSchema,
+ indent: indentSchema,
+ force: forceSchema,
+ strict: strictSchema,
+ es5: es5Schema,
+ double: doubleSchema,
+ }).default()
.required()
);
diff --git a/test/functional/test-jyt-cli.js b/test/functional/test-jyt-cli.js
index 0c17b2d..b92bae5 100644
--- a/test/functional/test-jyt-cli.js
+++ b/test/functional/test-jyt-cli.js
@@ -72,8 +72,8 @@ const CLI_OPTIONS_LONG_TO_SHORT_MAP = {
imports: '-m',
exports: '-x',
strict: '-s',
- 'no-es6': '--no-es6', // no short available
- 'no-single': '--no-single', // no short available
+ es5: '--es5', // no short available
+ double: '--double', // no short available
};
/**
@@ -211,7 +211,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - ./jyt -> ./src/cli.js - ', () =
src: path.resolve(CLI_TEST_BASE_DIR + '/test-data.yaml'),
dest: path.resolve(DEST_NO_ES6),
target: TYPE_JS,
- 'no-es6': true,
+ es5: true,
}));
logger.debug(msg);
const stats = fs.statSync(DEST_NO_ES6);
diff --git a/test/functional/test-transformer.js b/test/functional/test-transformer.js
index 8c29617..83fe9d9 100644
--- a/test/functional/test-transformer.js
+++ b/test/functional/test-transformer.js
@@ -209,7 +209,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - transformer - ', () => {
transform: transformFunc,
target: TYPE_JS,
strict: true,
- 'no-single': true,
+ double: true,
});
logger.debug(msg);
const stats = fs.statSync(DEST_DQ_AND_STRICT);
@@ -227,7 +227,7 @@ describe(TEST_SUITE_DESCRIPTION_FUNCTIONAL + ' - transformer - ', () => {
dest: path.resolve(DEST_NO_ES6),
transform: transformFunc,
target: TYPE_JS,
- 'no-es6': true,
+ es5: true,
});
logger.debug(msg);
const stats = fs.statSync(DEST_NO_ES6);
diff --git a/test/unit/test-serialize-utils.js b/test/unit/test-serialize-utils.js
index 61c19ef..fe333cc 100644
--- a/test/unit/test-serialize-utils.js
+++ b/test/unit/test-serialize-utils.js
@@ -26,25 +26,25 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - serialize-utils - ', () => {
describe('Function createExportString', () => {
it('should create ES6 default export', async () => {
expect.assertions(1);
- const result = await createExportString(true);
+ const result = await createExportString(false);
expect(result).toBe('export default ');
});
it('should create "module.exports"', async () => {
expect.assertions(1);
- const result = await createExportString(false);
+ const result = await createExportString(true);
expect(result).toBe('module.exports = ');
});
it('should create ES6 default export with named export', async () => {
expect.assertions(1);
- const result = await createExportString(true, 'foo');
+ const result = await createExportString(false, 'foo');
expect(result).toBe(`export const ${namedExport} = `);
});
it('should create "module.exports" with named export', async () => {
expect.assertions(1);
- const result = await createExportString(false, 'foo');
+ const result = await createExportString(true, 'foo');
expect(result).toBe(`module.exports.${namedExport} = `);
});
});
@@ -55,7 +55,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - serialize-utils - ', () => {
const result = await serializeJsToString(toSerializeToJs, {
strict: true,
indent: indent.length,
- 'no-es6': false,
+ es5: false,
});
expect(result).toBe(
`'use strict;'${nl}${nl}export default {${nl}${indent}foo: 'bar',${nl}${indent}bar: {bar: 'bar'}${nl}};${nl}`
@@ -67,7 +67,7 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - serialize-utils - ', () => {
const result = await serializeJsToString(toSerializeToJs, {
strict: false,
indent: indent.length,
- 'no-es6': false,
+ // es5: false,
});
expect(result).toBe(`export default {${nl}${indent}foo: 'bar',${nl}${indent}bar: {bar: 'bar'}${nl}};${nl}`);
});
@@ -77,11 +77,11 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - serialize-utils - ', () => {
const result = await serializeJsToString(toSerializeToJs, {
strict: true,
indent: indent.length,
- 'no-es6': false,
- 'no-single': true,
+ es5: true,
+ double: true,
});
expect(result).toBe(
- `"use strict;"${nl}${nl}export default {${nl}${indent}foo: "bar",${nl}${indent}bar: {bar: "bar"}${nl}};${nl}`
+ `"use strict;"${nl}${nl}module.exports = {${nl}${indent}foo: "bar",${nl}${indent}bar: {bar: "bar"}${nl}};${nl}`
);
});
});
diff --git a/test/unit/validation/test-options-schema.js b/test/unit/validation/test-options-schema.js
index 332efd2..3e7b79b 100644
--- a/test/unit/validation/test-options-schema.js
+++ b/test/unit/validation/test-options-schema.js
@@ -15,8 +15,8 @@ import {
MIN_INDENT,
MAX_INDENT,
DEFAULT_STRICT,
- DEFAULT_NO_ES6,
- DEFAULT_NO_SINGLE_QUOTES,
+ DEFAULT_ES5,
+ DEFAULT_DOUBLE_QUOTES,
} from '../../../src/constants';
import {
readOptionsSchema,
@@ -61,10 +61,12 @@ function expectOptionsValidationSuccess(validOptions, schema) {
describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
describe('Testing readOptionsSchema validation', () => {
it('should reject when options is missing (null)', () =>
- expectOptionsValidationError(null, readOptionsSchema));
+ expectOptionsValidationError(null, readOptionsSchema)
+ );
it('should reject when options is missing (undefined)', () =>
- expectOptionsValidationError(undefined, readOptionsSchema));
+ expectOptionsValidationError(undefined, readOptionsSchema)
+ );
it('should set all defaults', async () => {
expect.assertions(2);
@@ -241,8 +243,8 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
expect(validatedOptions.exports).toBe(DEFAULT_JS_EXPORTS_IDENTIFIER);
expect(validatedOptions.force).toBe(DEFAULT_FORCE_FILE_OVERWRITE);
expect(validatedOptions.strict).toBe(DEFAULT_STRICT);
- expect(validatedOptions['no-es6']).toBe(DEFAULT_NO_ES6);
- expect(validatedOptions['no-single']).toBe(DEFAULT_NO_SINGLE_QUOTES);
+ expect(validatedOptions.es5).toBe(DEFAULT_ES5);
+ expect(validatedOptions.double).toBe(DEFAULT_DOUBLE_QUOTES);
});
it('should infer options.target from file type', async () => {
@@ -464,5 +466,59 @@ describe(TEST_SUITE_DESCRIPTION_UNIT + ' - options-schema - ', () => {
}, writeOptionsSchema)
);
});
+
+ describe('Testing options.es5 schema validation', () => {
+ const notBoolean = {};
+ it('should reject non-boolean value \'' + stringify(notBoolean) + '\'', () =>
+ expectOptionsValidationError({
+ src: './test/data/test-data.js',
+ dest: 'some-file',
+ es5: notBoolean,
+ }, writeOptionsSchema)
+ );
+
+ it('should accept valid value \'false\'', () =>
+ expectOptionsValidationSuccess({
+ src: './test/data/test-data.js',
+ dest: 'some-file',
+ es5: false,
+ }, writeOptionsSchema)
+ );
+
+ it('should accept valid value \'true\'', () =>
+ expectOptionsValidationSuccess({
+ src: './test/data/test-data.js',
+ dest: 'some-file',
+ es5: true,
+ }, writeOptionsSchema)
+ );
+ });
+
+ describe('Testing options.double schema validation', () => {
+ const notBoolean = {};
+ it('should reject non-boolean value \'' + stringify(notBoolean) + '\'', () =>
+ expectOptionsValidationError({
+ src: './test/data/test-data.js',
+ dest: 'some-file',
+ double: notBoolean,
+ }, writeOptionsSchema)
+ );
+
+ it('should accept valid value \'false\'', () =>
+ expectOptionsValidationSuccess({
+ src: './test/data/test-data.js',
+ dest: 'some-file',
+ double: false,
+ }, writeOptionsSchema)
+ );
+
+ it('should accept valid value \'true\'', () =>
+ expectOptionsValidationSuccess({
+ src: './test/data/test-data.js',
+ dest: 'some-file',
+ double: true,
+ }, writeOptionsSchema)
+ );
+ });
});
});
From 38423d17d20176985114a88f2d77d1c52983d8d0 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 23 Nov 2017 19:09:36 +0100
Subject: [PATCH 43/58] some improvements
---
.gitignore | 1 +
API-PUBLIC.md | 9 ++-
README.md | 8 +--
index.js | 2 +-
package.json | 2 +-
readme/DOCUMENTATION.md | 8 +--
src/io-utils.js | 99 ++++++++++++++++++--------------
src/jy-transform.js | 9 ++-
src/transformer.js | 5 +-
src/validation/joi-extensions.js | 6 +-
src/writer.js | 12 ++--
11 files changed, 85 insertions(+), 76 deletions(-)
diff --git a/.gitignore b/.gitignore
index 8918b9c..f7bcff8 100755
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,4 @@ coverage
nohup.out
/jy-transform.wiki/
/lib
+/package-lock.json
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index 721eb98..fb821c0 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -53,17 +53,16 @@ This module provides the _public_ interface for the _read_, _write_ and _transfo
### jy-transform~transform ⇒ Promise
The entry method for all transformations accepting a configuration object and
-an (optional) middleware function. It executes the transformation logic.
+an (optional) callback function. It executes the transformation logic.
1. Input (read)
-2. Transform [ + Middleware]
+2. Transform [ + callback]
3. Output (write).
**Kind**: inner constant of [jy-transform](#module_jy-transform)
**Returns**: Promise - The transformation result.
**Access**: public
**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
-**Reject**: TypeError Will throw this error when the passed `middleware` is not type of `Function`.
**Reject**: ValidationError If any `options` validation occurs.
**Reject**: Error Will throw any error if read, transform or write operation failed due to any reason.
@@ -76,11 +75,11 @@ an (optional) middleware function. It executes the transformation logic.
import { transform } from 'jy-transform';
const options = {
src: 'foo/bar.yaml', // From YAML file...
- transform: async (object) => { // ...with exchanging value...
+ transform: async (object) => { // ...callback with exchanging value...
object.foo = 'new value';
return object;
},
- target: 'foo/bar.json', // ...to a new JSON file.
+ target: 'foo/bar-transformed.json', // ...to a new JSON file.
indent: 4,
};
diff --git a/README.md b/README.md
index e8ce644..b1c1af5 100644
--- a/README.md
+++ b/README.md
@@ -256,11 +256,11 @@ Reading from a file:
Additionally, on API level from:
-- `stream.Readable`:
+- `stream.Readable` (stream2):
- Contains serialized JS, JSON or YAML
- If not a file stream then setting requires `options.origin` property is mandatory
- Reads as UTF-8
-- JS `object`:
+- JS `Object`:
- Actually, this means the reading phase is "skipped", because object is in-memory already
- Of course, this case _cannot_ not be applied to serialized JSON or YAML content
@@ -299,11 +299,11 @@ Writing to a file:
Additionally, on API level to:
-- `stream.Writable`:
+- `stream.Writable` (stream2) implementations:
- Serialized JS, JSON and YAML
- Requires `options.target` property set
- Writes UTF-8
-- JS `object`:
+- JS `Object`:
- JS as a simple reference
- YAML and JSON as a serialized string
diff --git a/index.js b/index.js
index 3a2685e..20f9117 100755
--- a/index.js
+++ b/index.js
@@ -1 +1 @@
-module.exports = require('./src/jy-transform');
+module.exports = require('./lib/jy-transform');
diff --git a/package.json b/package.json
index dcef972..9d4d4d4 100644
--- a/package.json
+++ b/package.json
@@ -36,7 +36,7 @@
"dependencies": {
"cli": "~1.0.1",
"is-stream": "~1.1.0",
- "joi": "~11.1.1",
+ "joi": "~13.0.2",
"js-yaml": " ~3.10.0",
"json-stringify-safe": "~5.0.1",
"mkdirp-then": "~1.2.0",
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index a7a132a..7956e7d 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -129,11 +129,11 @@ Reading from a file:
Additionally, on API level from:
-- `stream.Readable`:
+- `stream.Readable` (stream2):
- Contains serialized JS, JSON or YAML
- If not a file stream then setting requires `options.origin` property is mandatory
- Reads as UTF-8
-- JS `object`:
+- JS `Object`:
- Actually, this means the reading phase is "skipped", because object is in-memory already
- Of course, this case _cannot_ not be applied to serialized JSON or YAML content
@@ -172,11 +172,11 @@ Writing to a file:
Additionally, on API level to:
-- `stream.Writable`:
+- `stream.Writable` (stream2) implementations:
- Serialized JS, JSON and YAML
- Requires `options.target` property set
- Writes UTF-8
-- JS `object`:
+- JS `Object`:
- JS as a simple reference
- YAML and JSON as a serialized string
diff --git a/src/io-utils.js b/src/io-utils.js
index 9e97a80..da9be57 100644
--- a/src/io-utils.js
+++ b/src/io-utils.js
@@ -18,16 +18,16 @@ const fsPromisified = promisify(fs);
/**
* @module jy-transform:io-utils
- * @description This module provides an I/O interface for files, streams or `Object`.
+ * @description This module provides a helper I/O interface for files, streams or `Object`.
* @private
*/
/**
- * Reads JS or JSON from file.
+ * Reads JS or JSON from file, optionally choosing a property given by `imports`.
*
* @param {string} file - The file path.
* @param {string} [imports] - An object which is exported in the file.
- * @returns {Object} The read object.
+ * @returns {Object} The read object from `file`.
* @throws {Error} When an `imports` is given but the declared object key is not exported by the file.
* @private
*/
@@ -37,7 +37,7 @@ export function readJsOrJsonFromFile(file, imports) {
// eslint-disable-next-line import/no-dynamic-require, global-require
const object = require(resolvedPath)[imports];
if (!object) {
- throw new Error('an identifier string \'' + imports + '\' was specified for JS object ' +
+ throw new Error(`An identifier string '${imports}' was specified for JS object ` +
'but could not find this object, pls ensure that file ' + file + ' exports it.');
}
return object;
@@ -47,11 +47,11 @@ export function readJsOrJsonFromFile(file, imports) {
}
/**
- * Reads JS from JS object.
+ * Reads JS from JS object, optionally choosing a property given by `imports`.
*
* @param {string} object - The JS object source.
- * @param {string} [imports] - An object which is is a sub-object in `object`.
- * @returns {Object} The given `object` object or any sub-object specified by `imports`.
+ * @param {string} [imports] - An object which is is a property/sub-object in `object`.
+ * @returns {Object} The given but cloned `object` or any property/sub-object specified by `imports`.
* @throws {Error} When an `imports` is given but the declared object key is not contained in the source object.
* @private
*/
@@ -59,8 +59,8 @@ export function readJsFromObject(object, imports) {
if (imports) {
const subObject = object[imports];
if (!subObject) {
- throw new Error('an identifier string \'' + imports + '\' was specified for JS sub-object ' +
- 'but could not find this sub-object, pls ensure that object source contains it.');
+ throw new Error(`An identifier string '${imports}' was specified for property/JS sub-object ` +
+ 'but could not be found, pls ensure that object source contains it.');
}
return Object.assign({}, subObject); // clone, do not alter original object!
}
@@ -70,19 +70,14 @@ export function readJsFromObject(object, imports) {
/**
* Reads YAML from file.
*
- * @param {string} file - The YAML file source.
+ * @param {string} file - The YAML file source.
* @returns {Object} The read JS object from YAML file.
* @throws {Error} When any I/O error occurs while the source file.
* @private
*/
export async function readYamlFromfile(file) {
- // load source from YAML file
const yaml = await fsPromisified.readFile(file, UTF8);
- try {
- return jsYaml.safeLoad(yaml);
- } catch (err) { // probably a YAMLException
- throw err;
- }
+ return jsYaml.safeLoad(yaml);
}
/**
@@ -141,7 +136,7 @@ function getConsecutiveDestName(dest) {
/**
* Ensures that all dirs exists for file type `dest` and writes the JS object to file.
*
- * @param {string} object - The object to write into file.
+ * @param {string} data - The object to write into file.
* @param {string} dest - The file destination path.
* @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
* @param {boolean} [forceOverwrite=false] - Forces overwriting the destination file if `true`.
@@ -150,21 +145,21 @@ function getConsecutiveDestName(dest) {
* @see {@link TYPE_JS}
* @private
*/
-async function mkdirAndWrite(object, dest, target, forceOverwrite = false) {
+async function mkdirAndWrite(data, dest, target, forceOverwrite = false) {
const destDir = path.dirname(dest);
await mkdirp(destDir);
let finalDestination = dest;
if (!forceOverwrite) {
finalDestination = getConsecutiveDestName(dest);
}
- await fsPromisified.writeFile(finalDestination, object, UTF8);
+ await fsPromisified.writeFile(finalDestination, data, UTF8);
return 'Writing \'' + target + '\' file \'' + finalDestination + '\' successful.';
}
/**
* Writes a serialized object to file.
*
- * @param {string} object - The object to write into file.
+ * @param {string} data - The object data to write into file.
* @param {string} dest - The file destination path.
* @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
* @param {boolean} [forceOverwrite] - Forces overwriting the destination file if `true`.
@@ -175,30 +170,50 @@ async function mkdirAndWrite(object, dest, target, forceOverwrite = false) {
* @throws {Error} If serialized JSON file could not be written due to any reason.
* @private
*/
-export function writeToFile(object, dest, target, forceOverwrite) {
+export async function writeToFile(data, dest, target, forceOverwrite) {
+ let stats;
+ try {
+ stats = await fsPromisified.stat(dest);
+ } catch (_) {
+ // ignore error (because file could possibly not exist at this point of time)
+ }
+ if (stats && stats.isDirectory()) {
+ throw new Error(`Destination file '${dest}' is a directory, pls specify a valid file resource!`);
+ }
+ return mkdirAndWrite(data, dest, target, forceOverwrite);
+}
+
+/**
+ * Writes a string serialized data object to a `stream.Transform`.
+ *
+ * @param {string} data - The data to write into stream.
+ * @param {stream.Transform} writable - The stream destination.
+ * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
+ * @see {@link TYPE_YAML}
+ * @see {@link TYPE_JSON}
+ * @see {@link TYPE_JS}
+ * @returns {Promise.} Containing the write success message to handle by caller (e.g. for logging).
+ * @throws {Error} If serialized JS object could not be written due to any reason.
+ * @private
+ */
+export function writeToStreamTransform(data, writable, target) {
return new Promise((resolve, reject) => {
- fsPromisified.stat(dest)
- .then((stats) => {
- if (stats.isDirectory()) {
- reject(new Error('Destination file is a directory, pls specify a valid file resource!'));
- return;
- }
- // file exists
- resolve(mkdirAndWrite(object, dest, target, forceOverwrite));
- })
- .catch(() => {
- // ignore error (because file could possibly not exist at this point of time)
- resolve(mkdirAndWrite(object, dest, target, forceOverwrite));
- });
+ writable
+ .on('error', reject)
+ .on('finish', () => resolve('Writing ' + target + ' to stream successful.'));
+
+ // write stringified data
+ writable.write(data);
+ writable.end();
});
}
/**
- * Writes a string serialized data object to a stream.
+ * Writes a string serialized data object to a `stream.Writable`.
*
- * @param {string} object - The data to write into stream.
- * @param {string} dest - The stream destination.
- * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
+ * @param {string} data - The data to write into stream.
+ * @param {stream.Writable|stream.Duplex} writable - The stream destination.
+ * @param {string} target - The target type, one of [ 'yaml' | 'json' | 'js' ].
* @see {@link TYPE_YAML}
* @see {@link TYPE_JSON}
* @see {@link TYPE_JS}
@@ -206,14 +221,14 @@ export function writeToFile(object, dest, target, forceOverwrite) {
* @throws {Error} If serialized JS object could not be written due to any reason.
* @private
*/
-export function writeToStream(object, dest, target) {
+export function writeToStreamWritable(data, writable, target) {
return new Promise((resolve, reject) => {
- dest
+ writable
.on('error', reject)
.on('finish', () => resolve('Writing ' + target + ' to stream successful.'));
// write stringified data
- dest.write(object);
- dest.end();
+ writable.write(data);
+ writable.end();
});
}
diff --git a/src/jy-transform.js b/src/jy-transform.js
index e7ac8ed..6d2b11a 100755
--- a/src/jy-transform.js
+++ b/src/jy-transform.js
@@ -16,16 +16,15 @@ import {
/**
* The entry method for all transformations accepting a configuration object and
- * an (optional) middleware function. It executes the transformation logic.
+ * an (optional) callback function. It executes the transformation logic.
*
* 1. Input (read)
- * 2. Transform [ + Middleware]
+ * 2. Transform [ + callback]
* 3. Output (write).
*
* @param {TransformOptions} options - The configuration for a transformation.
* @returns {Promise} The transformation result.
* @resolve {string} With the transformation result as message (e.g. to be logged by caller).
- * @reject {TypeError} Will throw this error when the passed `middleware` is not type of `Function`.
* @reject {ValidationError} If any `options` validation occurs.
* @reject {Error} Will throw any error if read, transform or write operation failed due to any reason.
* @public
@@ -33,11 +32,11 @@ import {
* import { transform } from 'jy-transform';
* const options = {
* src: 'foo/bar.yaml', // From YAML file...
- * transform: async (object) => { // ...with exchanging value...
+ * transform: async (object) => { // ...callback with exchanging value...
* object.foo = 'new value';
* return object;
* },
- * target: 'foo/bar.json', // ...to a new JSON file.
+ * target: 'foo/bar-transformed.json', // ...to a new JSON file.
* indent: 4,
* };
*
diff --git a/src/transformer.js b/src/transformer.js
index 1155fc9..44d0204 100644
--- a/src/transformer.js
+++ b/src/transformer.js
@@ -11,16 +11,15 @@ import { transformOptionsSchema } from './validation/options-schema';
/**
* The entry method for all transformations accepting a configuration object and
- * an (optional) middleware function. It executes the transformation logic.
+ * an (optional) callback function. It executes the transformation logic.
*
* 1. Input (read)
- * 2. Transform [ + Middleware]
+ * 2. Transform [ + callback]
* 3. Output (write).
*
* @param {TransformOptions} options - The configuration for a transformation.
* @returns {Promise} The transformation result.
* @resolve {string} With the transformation result as message (e.g. to be logged by caller).
- * @reject {TypeError} Will throw this error when the passed `middleware` is not type of `Function`.
* @reject {ValidationError} If any `options` validation occurs.
* @reject {Error} Will throw any error if read, transform or write operation failed due to any reason.
* @private
diff --git a/src/validation/joi-extensions.js b/src/validation/joi-extensions.js
index 005eea2..2134f00 100644
--- a/src/validation/joi-extensions.js
+++ b/src/validation/joi-extensions.js
@@ -1,5 +1,4 @@
import JoiBase from 'joi';
-import promisify from 'promisify-es6';
import { isExistingFile } from './joi-extensions-file-utils';
import { isValidEs6Identifier } from './joi-extensions-identifier-utils';
@@ -48,7 +47,4 @@ export const EXTENSIONS = {
]
};
-const JoiExtended = JoiBase.extend(EXTENSIONS);
-JoiExtended.validate = promisify(JoiExtended.validate);
-
-export default JoiExtended;
+export default JoiBase.extend(EXTENSIONS);
diff --git a/src/writer.js b/src/writer.js
index 45a0df7..d99de2b 100644
--- a/src/writer.js
+++ b/src/writer.js
@@ -13,7 +13,7 @@ import {
} from './serialize-utils';
import {
writeToFile,
- writeToStream,
+ writeToStreamWritable,
} from './io-utils';
/**
@@ -50,8 +50,8 @@ async function writeYaml(object, options) {
if (typeof options.dest === 'string') { // file
return writeToFile(yaml, options.dest, TYPE_YAML, options.force);
- } else if (isStream.writable(options.dest)) { // stream
- return writeToStream(yaml, options.dest, TYPE_YAML);
+ } else if (isStream.writable(options.dest)) { // stream.Writable | stream.Duplex
+ return writeToStreamWritable(yaml, options.dest, TYPE_YAML);
}
// object
options.dest = yaml;
@@ -74,7 +74,7 @@ async function writeJson(object, options) {
if (typeof options.dest === 'string') { // file
return writeToFile(jsonString, options.dest, TYPE_JSON, options.force);
} else if (isStream.writable(options.dest)) { // stream
- return writeToStream(jsonString, options.dest, TYPE_JSON);
+ return writeToStreamWritable(jsonString, options.dest, TYPE_JSON);
}
// object
options.dest = jsonString;
@@ -97,7 +97,7 @@ async function writeJs(object, options) {
if (typeof options.dest === 'string') { // file
return writeToFile(data, options.dest, TYPE_JS, options.force);
} else if (isStream.writable(options.dest)) { // stream
- return writeToStream(data, options.dest, TYPE_JS);
+ return writeToStreamWritable(data, options.dest, TYPE_JS);
}
// object
let msg;
@@ -116,7 +116,7 @@ async function writeJs(object, options) {
*
* @param {Object} object - The JS source object to write.
* @param {WriteOptions} options - The write options.
- * @returns {Promise} The result.
+ * @returns {Promise.} The result message.
* @resolve {string} With the write success message.
* @reject {Error} If any write error occurs.
* @reject {ValidationError} If any `options` validation occurs.
From 3cdadf7410d8f6a31bdc6e3f526a7edb68f99afa Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 23 Nov 2017 19:22:31 +0100
Subject: [PATCH 44/58] Update deps
---
API-PUBLIC.md | 6 +++---
PACKAGE.md | 2 +-
package.json | 22 +++++++++++-----------
3 files changed, 15 insertions(+), 15 deletions(-)
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index fb821c0..ddfedac 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -59,7 +59,7 @@ an (optional) callback function. It executes the transformation logic.
2. Transform [ + callback]
3. Output (write).
-**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Kind**: inner property of [jy-transform](#module_jy-transform)
**Returns**: Promise - The transformation result.
**Access**: public
**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
@@ -104,7 +104,7 @@ try {
### jy-transform~read ⇒ Promise
Reads a particular content type from a source provided in the passed `options`.
-**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Kind**: inner property of [jy-transform](#module_jy-transform)
**Returns**: Promise - The result.
**Access**: public
**Resolve**: string Resolves with JS object result.
@@ -146,7 +146,7 @@ read(options)
### jy-transform~write ⇒ Promise
Writes the passed JS object to a particular destination described by the passed `options`.
-**Kind**: inner constant of [jy-transform](#module_jy-transform)
+**Kind**: inner property of [jy-transform](#module_jy-transform)
**Returns**: Promise - The result.
**Access**: public
**Resolve**: string With the write success message.
diff --git a/PACKAGE.md b/PACKAGE.md
index 55fe591..0e78081 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -46,7 +46,7 @@ npm test
- [eslint-config-airbnb-base](https://github.com/airbnb/javascript): Airbnb's base JS ESLint config, following our styleguide
- [eslint-plugin-filenames](https://github.com/selaux/eslint-plugin-filenames): Eslint rule for consistent filenames.
- [eslint-plugin-import](https://github.com/benmosher/eslint-plugin-import): Import with sanity.
-- [eslint-plugin-jest](https://github.com/facebook/jest): Eslint rules for Jest
+- [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest): Eslint rules for Jest
- [eslint-plugin-jest-async](https://github.com/deadratfink/jy-transform.git): ESLint plugin to detect improper Jest test assertions for asynchronous (Promise-based) actions
- [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc): JSDoc linting rules for ESLint.
- [fs-extra](https://github.com/jprichardson/node-fs-extra): fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as mkdir -p, cp -r, and rm -rf.
diff --git a/package.json b/package.json
index 7298196..974de51 100644
--- a/package.json
+++ b/package.json
@@ -45,32 +45,32 @@
},
"devDependencies": {
"babel-cli": "~6.26.0",
- "babel-eslint": " ~8.0.1",
+ "babel-eslint": " ~8.0.2",
"babel-plugin-transform-flow-strip-types": "~6.22.0",
"babel-plugin-transform-runtime": "~6.23.0",
- "babel-preset-env": "~1.6.0",
+ "babel-preset-env": "~1.6.1",
"bithound": "~1.7.0",
- "chalk": "~2.1.0",
+ "chalk": "~2.3.0",
"codacy-coverage": "~2.0.2",
"codeclimate-test-reporter": "~0.5.0",
- "codecov": " ~2.3.0",
+ "codecov": " ~3.0.0",
"coveralls": " ~3.0.0",
"cwd": "~0.10.0",
"doctoc": " ~1.3.0",
- "eslint": "~4.8.0",
- "eslint-config-airbnb-base": "~12.0.0",
+ "eslint": "~4.11.0",
+ "eslint-config-airbnb-base": "~12.1.0",
"eslint-plugin-filenames": "1.2.0",
- "eslint-plugin-import": " ~2.7.0",
- "eslint-plugin-jest": " ~21.2.0",
+ "eslint-plugin-import": " ~2.8.0",
+ "eslint-plugin-jest": " ~21.3.2",
"eslint-plugin-jest-async": " ~1.0.3",
- "eslint-plugin-jsdoc": " ~3.1.2",
+ "eslint-plugin-jsdoc": " ~3.2.0",
"fs-extra": "~4.0.1",
"inchjs": "~0.4.1",
"jest": "~21.2.1",
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": "~3.0.0",
- "jsdoc-to-markdown": "~3.0.0",
- "nsp": "~2.8.0",
+ "jsdoc-to-markdown": "~3.0.2",
+ "nsp": "~3.1.0",
"package-json-to-readme": "~2.0.0",
"winston": "^2.4.0"
},
From d7d44225516a63bae134578bb09af3cec4eef5e2 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Sun, 18 Feb 2018 11:05:25 +0100
Subject: [PATCH 45/58] Add eslint json plugin
---
.eslintrc.js | 3 ++-
package.json | 3 ++-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/.eslintrc.js b/.eslintrc.js
index cdb5e5e..3984b54 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -7,6 +7,7 @@ module.exports = {
plugins: [
'import',
'jsdoc',
+ 'json',
'filenames',
'jest',
'jest-async'
@@ -71,6 +72,6 @@ module.exports = {
additionalTagNames: {
customTags: ['resolve', 'reject']
},
- }
+ }
}
};
diff --git a/package.json b/package.json
index 974de51..e87c50d 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,7 @@
"wiki": "jsdoc2md ./jyt lib/*.js index.js > docs/API.md && doctoc docs/API.md --github --title '### TOC' --maxlevel 2 && cat docs/API.md > '../jy-transform.wiki/API-v2.md' && cat docs/CONTRIBUTING.md > ../jy-transform.wiki/Contributing.md && cat docs/CHANGELOG.md > ../jy-transform.wiki/Changelog.md && doctoc ../jy-transform.wiki/Changelog.md --github --title '### TOC' --maxlevel 3",
"pretest": "mkdir -pv test/tmp",
"test": "jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
- "eslint": "eslint .",
+ "eslint": "eslint . --ext .json --ext .js",
"nsp": "nsp check",
"inch": "inchjs suggest && inchjs list --all && inchjs stats",
"bithound": "bithound check git@github.com:deadratfink/jy-transform.git"
@@ -64,6 +64,7 @@
"eslint-plugin-jest": " ~21.3.2",
"eslint-plugin-jest-async": " ~1.0.3",
"eslint-plugin-jsdoc": " ~3.2.0",
+ "eslint-plugin-json": "^1.2.0",
"fs-extra": "~4.0.1",
"inchjs": "~0.4.1",
"jest": "~21.2.1",
From 819de55d5dcaf9200401ea15ee165a361b8ac2ab Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Sun, 18 Feb 2018 11:10:45 +0100
Subject: [PATCH 46/58] correct some docs
---
API-PUBLIC.md | 42 +++++++++++++++++++++---------------------
PACKAGE.md | 31 ++++++++++++++++---------------
src/jy-transform.js | 6 +++---
3 files changed, 40 insertions(+), 39 deletions(-)
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index ddfedac..3f7613d 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -74,12 +74,12 @@ an (optional) callback function. It executes the transformation logic.
```js
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // From YAML file...
- transform: async (object) => { // ...callback with exchanging value...
+ src: 'foo/bar.yaml', // From YAML file...
+ transform: async (object) => { // ...callback with exchanging value...
object.foo = 'new value';
return object;
},
- target: 'foo/bar-transformed.json', // ...to a new JSON file.
+ target: 'foo/bar-transformed.json', // ...to a new JSON file.
indent: 4,
};
@@ -232,8 +232,8 @@ The configuration properties provided to the `read` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| src | string \| Stream.Readable \| object | | The source (if `string` type it is treated as a file path). |
-| origin | string | "yaml" | The source origin type. |
-| imports | string | | The exports name for reading from JS source files or objects only. |
+| [origin] | string | "yaml" | The source origin type. |
+| [imports] | string | | The exports name for reading from JS source files or objects only. |
@@ -247,12 +247,12 @@ The configuration properties provided to the `write` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| dest | string \| Stream.Writable \| object | | The destination (if `string` type it is treated as a file path). |
-| target | string | "js" | The destination target type. |
-| indent | number | 2 | The indentation value for pretty-print of output. |
-| exports | string | | The exports name for usage in JS destination files only. |
-| force | string | false | Force overwriting of existing output files on write phase. |
-| no-es6 | boolean | false | Whether not to use ECMAScript6 syntax for JS type output like `module.exports` instead of `export default`, applicable only for JS output. |
-| no-single | boolean | false | Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes). |
+| [target] | string | "js" | The destination target type. |
+| [indent] | number | 2 | The indentation value for pretty-print of output. |
+| [exports] | string | | The exports name for usage in JS destination files only. |
+| [force] | string | false | Force overwriting of existing output files on write phase. |
+| [no-es6] | boolean | false | Whether not to use ECMAScript6 syntax for JS type output like `module.exports` instead of `export default`, applicable only for JS output. |
+| [no-single] | boolean | false | Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes). |
@@ -266,14 +266,14 @@ The configuration properties provided to the `transform` function.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| src | string \| Stream.Readable \| object | | The _read_ source (if `string` type it is treated as a file path). |
-| origin | string | "yaml" | The _read_ source origin type. |
-| imports | string | | The _read_ exports name for reading from JS source files or objects only. |
-| transform | function | | The option is a _transformation_ function with the following signature:
``` [async|Promise] function(object) ``` |
-| dest | string \| Stream.Writable \| object | | The _write_ destination (if `string` type it is treated as a file path). This property could be optional in case we infer a value from `src` which is then either a string or a file stream where can get the file path from. If this detection process cannot be fulfilled then the property is `undefined` and the transform process will fail with a `ValidationError` on write phase. |
-| target | string | "js" | The _write_ target type. |
-| indent | number | 2 | The _write_ indentation value for pretty-print of output. |
-| exports | string | | The _write_ exports name for usage in JS destination files only. |
-| force | string | false | Force overwriting of existing output files on write phase. |
-| no-es6 | boolean | false | Whether not to use ECMAScript6 syntax for JS type output like `module.exports` instead of `export default`, applicable only for JS output. |
-| no-single | boolean | false | Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes). |
+| [origin] | string | "yaml" | The _read_ source origin type. |
+| [imports] | string | | The _read_ exports name for reading from JS source files or objects only. |
+| [transform] | function | | The option is a _transformation_ function with the following signature:
``` [async|Promise] function(object) ``` |
+| [dest] | string \| Stream.Writable \| object | | The _write_ destination (if `string` type it is treated as a file path). This property could be optional in case we infer a value from `src` which is then either a string or a file stream where can get the file path from. If this detection process cannot be fulfilled then the property is `undefined` and the transform process will fail with a `ValidationError` on write phase. |
+| [target] | string | "js" | The _write_ target type. |
+| [indent] | number | 2 | The _write_ indentation value for pretty-print of output. |
+| [exports] | string | | The _write_ exports name for usage in JS destination files only. |
+| [force] | string | false | Force overwriting of existing output files on write phase. |
+| [no-es6] | boolean | false | Whether not to use ECMAScript6 syntax for JS type output like `module.exports` instead of `export default`, applicable only for JS output. |
+| [no-single] | boolean | false | Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes). |
diff --git a/PACKAGE.md b/PACKAGE.md
index 0e78081..d908d96 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -19,44 +19,45 @@ npm test
## Dependencies
- [cli](https://github.com/node-js-libs/cli): A tool for rapidly building command line apps
-- [is-stream](https://github.com/sindresorhus/is-stream): Check if something is a Node.js stream
-- [joi](https://github.com/hapijs/joi): Object schema validation
-- [js-yaml](https://github.com/nodeca/js-yaml): YAML 1.2 parser and serializer
+- [is-stream](): Check if something is a Node.js stream
+- [joi](): Object schema validation
+- [js-yaml](): YAML 1.2 parser and serializer
- [json-stringify-safe](https://github.com/isaacs/json-stringify-safe): Like JSON.stringify, but doesn't blow up on circular refs.
-- [mkdirp-then](https://github.com/fs-utils/mkdirp-then): mkdirp as promised
+- [mkdirp-then](): mkdirp as promised
- [promisify-es6](https://github.com/manuel-di-iorio/promisify-es6): Promisify callback-style functions to ES6 promises
- [serialize-js](https://github.com/RReverser/serialize-js): User-readable object serialization for JavaScript.
## Dev Dependencies
-- [babel-cli](https://github.com/babel/babel/tree/master/packages): Babel command line.
+- [babel-cli](): Babel command line.
- [babel-eslint](https://github.com/babel/babel-eslint): Custom parser for ESLint
-- [babel-plugin-transform-flow-strip-types](https://github.com/babel/babel/tree/master/packages): Strip flow type annotations from your output code.
-- [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
-- [babel-preset-env](https://github.com/babel/babel-preset-env): A Babel preset for each environment.
+- [babel-plugin-transform-flow-strip-types](): Strip flow type annotations from your output code.
+- [babel-plugin-transform-runtime](): Externalise references to helpers and builtins, automatically polyfilling your code without polluting globals
+- [babel-preset-env](): A Babel preset for each environment.
- [bithound](https://github.com/bithound/cli.bithound.io): Commands for interacting with bitHound: https://bithound.io
-- [chalk](https://github.com/chalk/chalk): Terminal string styling done right
+- [chalk](): Terminal string styling done right
- [codacy-coverage](https://github.com/codacy/node-codacy-coverage): Code Coverage reporter for Codacy.com
- [codeclimate-test-reporter](https://github.com/codeclimate/javascript-test-reporter): Code Climate test reporter client for javascript projects
- [codecov](https://github.com/codecov/codecov-node): Uploading report to Codecov: https://codecov.io
- [coveralls](https://github.com/nickmerwin/node-coveralls): takes json-cov output into stdin and POSTs to coveralls.io
-- [cwd](https://github.com/jonschlinkert/cwd): Easily get the CWD (current working directory) of a project based on package.json, optionally starting from a given path. (node.js/javascript util)
+- [cwd](): Easily get the CWD (current working directory) of a project based on package.json, optionally starting from a given path. (node.js/javascript util)
- [doctoc](https://github.com/thlorenz/doctoc): Generates TOC for markdown files of local git repo.
-- [eslint](https://github.com/eslint/eslint): An AST-based pattern checker for JavaScript.
+- [eslint](): An AST-based pattern checker for JavaScript.
- [eslint-config-airbnb-base](https://github.com/airbnb/javascript): Airbnb's base JS ESLint config, following our styleguide
- [eslint-plugin-filenames](https://github.com/selaux/eslint-plugin-filenames): Eslint rule for consistent filenames.
- [eslint-plugin-import](https://github.com/benmosher/eslint-plugin-import): Import with sanity.
-- [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest): Eslint rules for Jest
+- [eslint-plugin-jest](): Eslint rules for Jest
- [eslint-plugin-jest-async](https://github.com/deadratfink/jy-transform.git): ESLint plugin to detect improper Jest test assertions for asynchronous (Promise-based) actions
- [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc): JSDoc linting rules for ESLint.
+- [eslint-plugin-json](https://github.com/azeemba/eslint-plugin-json): Lint JSON files
- [fs-extra](https://github.com/jprichardson/node-fs-extra): fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as mkdir -p, cp -r, and rm -rf.
- [inchjs](https://github.com/rrrene/inchjs): JS Wrapper for Inch for JavaScript
- [jest](https://github.com/facebook/jest): Delightful JavaScript Testing.
- [jsdoc-babel](https://github.com/ctumolosus/jsdoc-babel): A JSDoc plugin that transforms ES6 source files with Babel before they are processsed.
-- [jsdoc-parse](https://github.com/jsdoc2md/jsdoc-parse): Transforms jsdoc data into something more suitable for use as template input
-- [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown): Generates markdown API documentation from jsdoc annotated source code
+- [jsdoc-parse](): Transforms jsdoc data into something more suitable for use as template input
+- [jsdoc-to-markdown](): Generates markdown API documentation from jsdoc annotated source code
- [nsp](https://github.com/nodesecurity/nsp): The Node Security (nodesecurity.io) command line interface
-- [package-json-to-readme](https://github.com/zeke/package-json-to-readme): Generate a README.md from package.json contents
+- [package-json-to-readme](): Generate a README.md from package.json contents
- [winston](https://github.com/winstonjs/winston): A multi-transport async logging library for Node.js
diff --git a/src/jy-transform.js b/src/jy-transform.js
index 6d2b11a..8209a78 100755
--- a/src/jy-transform.js
+++ b/src/jy-transform.js
@@ -31,12 +31,12 @@ import {
* @example
* import { transform } from 'jy-transform';
* const options = {
- * src: 'foo/bar.yaml', // From YAML file...
- * transform: async (object) => { // ...callback with exchanging value...
+ * src: 'foo/bar.yaml', // From YAML file...
+ * transform: async (object) => { // ...callback with exchanging value...
* object.foo = 'new value';
* return object;
* },
- * target: 'foo/bar-transformed.json', // ...to a new JSON file.
+ * target: 'foo/bar-transformed.json', // ...to a new JSON file.
* indent: 4,
* };
*
From 37129cc97a0693283b1b5e4ad2b17ed3a51a68a9 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 07:45:17 +0100
Subject: [PATCH 47/58] Fix deps and some doc error
---
.babelrc | 2 ++
API-PUBLIC.md | 4 ++--
package.json | 3 ++-
src/type-definitions.js | 10 +++++-----
4 files changed, 11 insertions(+), 8 deletions(-)
diff --git a/.babelrc b/.babelrc
index 4862d50..ad586b8 100644
--- a/.babelrc
+++ b/.babelrc
@@ -10,9 +10,11 @@
]
],
"plugins": [
+ "transform-es2015-spread",
[
"transform-runtime",
{
+ "helpers": true,
"polyfill": false,
"regenerator": true
}
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index 3f7613d..07f7923 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -250,7 +250,7 @@ The configuration properties provided to the `write` function.
| [target] | string | "js" | The destination target type. |
| [indent] | number | 2 | The indentation value for pretty-print of output. |
| [exports] | string | | The exports name for usage in JS destination files only. |
-| [force] | string | false | Force overwriting of existing output files on write phase. |
+| [force] | boolean | false | Force overwriting of existing output files on write phase. |
| [no-es6] | boolean | false | Whether not to use ECMAScript6 syntax for JS type output like `module.exports` instead of `export default`, applicable only for JS output. |
| [no-single] | boolean | false | Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes). |
@@ -273,7 +273,7 @@ The configuration properties provided to the `transform` function.
| [target] | string | "js" | The _write_ target type. |
| [indent] | number | 2 | The _write_ indentation value for pretty-print of output. |
| [exports] | string | | The _write_ exports name for usage in JS destination files only. |
-| [force] | string | false | Force overwriting of existing output files on write phase. |
+| [force] | boolean | false | Force overwriting of existing output files on write phase. |
| [no-es6] | boolean | false | Whether not to use ECMAScript6 syntax for JS type output like `module.exports` instead of `export default`, applicable only for JS output. |
| [no-single] | boolean | false | Whether _not_ to use single-quotes style for values in JS type output (i.e. double-quotes). |
diff --git a/package.json b/package.json
index e87c50d..39ae55c 100644
--- a/package.json
+++ b/package.json
@@ -34,9 +34,10 @@
"node": ">=5.0.0"
},
"dependencies": {
+ "babel-runtime": "^6.26.0",
"cli": "~1.0.1",
"is-stream": "~1.1.0",
- "joi": "~13.0.2",
+ "joi": "~12.0.0",
"js-yaml": " ~3.10.0",
"json-stringify-safe": "~5.0.1",
"mkdirp-then": "~1.2.0",
diff --git a/src/type-definitions.js b/src/type-definitions.js
index d15fbb1..85c091e 100644
--- a/src/type-definitions.js
+++ b/src/type-definitions.js
@@ -49,9 +49,9 @@
/**
* The configuration properties provided to the `read` function.
* @typedef {object} ReadOptions
- * @property {(string|Stream.Readable|object)} src - The source (if `string` type it is treated as a file path).
- * @property {string} [origin=yaml] - The source origin type.
- * @property {string} [imports=undefined] - The exports name for reading from JS source files or objects only.
+ * @property {(string|Stream.Readable|object)} src - The source (if `string` type it is treated as a file path).
+ * @property {string} [origin=yaml] - The source origin type.
+ * @property {string} [imports=undefined] - The exports name for reading from JS source files or objects only.
* @public
*/
@@ -62,7 +62,7 @@
* @property {string} [target=js] - The destination target type.
* @property {number} [indent=2] - The indentation value for pretty-print of output.
* @property {string} [exports=undefined] - The exports name for usage in JS destination files only.
- * @property {string} [force=false] - Force overwriting of existing output files on write phase.
+ * @property {boolean} [force=false] - Force overwriting of existing output files on write phase.
* @property {boolean} [no-es6=false] - Whether not to use ECMAScript6 syntax for JS type output like
* `module.exports` instead of `export default`, applicable only
* for JS output.
@@ -95,7 +95,7 @@
* @property {string} [target=js] - The _write_ target type.
* @property {number} [indent=2] - The _write_ indentation value for pretty-print of output.
* @property {string} [exports=undefined] - The _write_ exports name for usage in JS destination files only.
- * @property {string} [force=false] - Force overwriting of existing output files on write phase.
+ * @property {boolean} [force=false] - Force overwriting of existing output files on write phase.
* @property {boolean} [no-es6=false] - Whether not to use ECMAScript6 syntax for JS type output like
* `module.exports` instead of `export default`, applicable only
* for JS output.
From a5084d43c999365fd35f70f456c1c61e4608d5cd Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 07:46:04 +0100
Subject: [PATCH 48/58] Update doc
---
PACKAGE.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/PACKAGE.md b/PACKAGE.md
index d908d96..82ef1ce 100644
--- a/PACKAGE.md
+++ b/PACKAGE.md
@@ -18,6 +18,7 @@ npm test
## Dependencies
+- [babel-runtime](): babel selfContained runtime
- [cli](https://github.com/node-js-libs/cli): A tool for rapidly building command line apps
- [is-stream](): Check if something is a Node.js stream
- [joi](): Object schema validation
From 271c0005ffbc51cc050db98e29be0a24fac77acd Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 07:56:41 +0100
Subject: [PATCH 49/58] Fix bithound for joi
---
.bithoundrc | 1 +
1 file changed, 1 insertion(+)
diff --git a/.bithoundrc b/.bithoundrc
index e550371..1778260 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -16,6 +16,7 @@
"mute": [
"bithound",
"inchjs",
+ "joi",
"jsdoc-to-markdown",
"package-json-to-readme"
]
From f07a8e226f820710e313ef3fbb78cb98e744563e Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 08:01:38 +0100
Subject: [PATCH 50/58] Fix bithound for joi
---
.bithoundrc | 1 +
1 file changed, 1 insertion(+)
diff --git a/.bithoundrc b/.bithoundrc
index 1778260..f9bab83 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -15,6 +15,7 @@
],
"mute": [
"bithound",
+ "eslint-plugin-json",
"inchjs",
"joi",
"jsdoc-to-markdown",
From 6cce066863e1f7c971c2bbb429abef8c9377ad43 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 08:03:13 +0100
Subject: [PATCH 51/58] Fix bithound for babel-runtime
---
.bithoundrc | 1 +
1 file changed, 1 insertion(+)
diff --git a/.bithoundrc b/.bithoundrc
index f9bab83..5fff4a2 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -11,6 +11,7 @@
},
"dependencies": {
"unused-ignores": [
+ "babel-runtime",
"eslint"
],
"mute": [
From b7dbd55d2a65f99a789911a1411ef8121592cab2 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 12:49:40 +0100
Subject: [PATCH 52/58] Fix bithound config
---
.bithoundrc | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.bithoundrc b/.bithoundrc
index 5fff4a2..65b152c 100644
--- a/.bithoundrc
+++ b/.bithoundrc
@@ -22,14 +22,14 @@
"jsdoc-to-markdown",
"package-json-to-readme"
]
- }
+ },
"ignore": [
"**/bin/**",
"**/coverage/**",
"**/lib/**",
"**/node_modules/**",
"**/readme/**",
- "**/test/tmp/**"
+ "**/test/tmp/**",
"**/test/functional/tmp/**"
],
"test": [
From 46f291ad50bb6d0278ed73dd9f3a831053645a2f Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 20 Feb 2018 14:52:21 +0100
Subject: [PATCH 53/58] Fix stuff
---
.babelrc | 3 +--
.travis.yml | 2 +-
CHANGELOG.md | 12 +++++++-----
package.json | 2 +-
4 files changed, 10 insertions(+), 9 deletions(-)
diff --git a/.babelrc b/.babelrc
index ad586b8..c6961e7 100644
--- a/.babelrc
+++ b/.babelrc
@@ -4,13 +4,12 @@
"env",
{
"targets": {
- "node": "5"
+ "node": "6"
}
}
]
],
"plugins": [
- "transform-es2015-spread",
[
"transform-runtime",
{
diff --git a/.travis.yml b/.travis.yml
index acc4075..52d0368 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,9 +1,9 @@
language: node_js
node_js:
+- "9"
- "8"
- "7"
- "6"
-- "5"
os:
- linux
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd47d25..ebfcff8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,12 +11,14 @@ new interface:
- [README.md](https://github.com/deadratfink/jy-transform/blob/master/README.md)
- [API-PUBLIC.md](https://github.com/deadratfink/jy-transform/blob/master/API-PUBLIC.md)
+> **IMPORTANT NOTE: Backwards Incompatible - Node.js version >= v6.0.0 required!**
+
### New Features:
- [[#64](https://github.com/deadratfink/jy-transform/issues/64)] Support ES6 for JS output.
- **CLI & API Backwards Incompatible Change!**
- This is the default now:
- - Usage of `export default` instead of `module.exports`.
- - Usage of `export const foo` instead of `module.exports.foo`.
+ - Generation of `export default` instead of `module.exports`.
+ - Generation of `export const foo` instead of `module.exports.foo`.
- Can be suppressed by `options[no-es6] = true` (default `false`).
- [[#62](https://github.com/deadratfink/jy-transform/issues/62)] The `options.transform` function (formerly aka
_middleware_ function) is no longer necessary to be a Promise/`async` one.
@@ -33,7 +35,7 @@ new interface:
validated for 2 now and throws a `ValidationError` if < 2 (for others 0 is still valid).
- [[#56](https://github.com/deadratfink/jy-transform/issues/56)] If _destination_ is not given on transformation
process but the _target_ is, then the destination's file extension
- is adapted to the proper type, e.g. `$ ./jyt inch.json -t yaml` results in a file _inch.yaml_ (formerly:
+ is adapted to the proper type, e.g. `$ jyt inch.json -t yaml` results in a file _inch.yaml_ (formerly:
_inch.json_ with YAML content or respectively _inch(1).json_ with YAML, the latter if `options.force` was `true`).
### Public Interface Changes & Improvements:
@@ -70,9 +72,9 @@ new interface:
- Usage of _native_ Promises instead of [bluebird](http://bluebirdjs.com/docs/getting-started.html).
- Test dependencies reduced.
- [[#53](https://github.com/deadratfink/jy-transform/issues/53)] Update supported node versions:
+ - Add travis build for Node.js v8.x and v9.x.
- **CLI & API Backwards Incompatible Change!**
- - Add travis build for Node.js v8.x.
- - Remove travis build for Node.js < v5.x.
+ - Remove travis build for Node.js < v6.x.
- [[#52](https://github.com/deadratfink/jy-transform/issues/52)] Leverage modern ES6 features:
- Integrated by [babel](https://babeljs.io/).
- Update of dependencies and amount reduced.
diff --git a/package.json b/package.json
index 39ae55c..82e87a1 100644
--- a/package.json
+++ b/package.json
@@ -31,7 +31,7 @@
"bithound": "bithound check git@github.com:deadratfink/jy-transform.git"
},
"engines": {
- "node": ">=5.0.0"
+ "node": ">=6.0.0"
},
"dependencies": {
"babel-runtime": "^6.26.0",
From eef8e5941eb83e6960b80ff042bea41a9bd88095 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 22 Feb 2018 07:23:25 +0100
Subject: [PATCH 54/58] Deactivate unreliable bithound check
---
.travis.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 52d0368..427d7fa 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -11,8 +11,8 @@ os:
script:
- make test
-- npm install bithound --save-dev
-- bithound check git@github.com:deadratfink/jy-transform.git
+# - npm install bithound --save-dev
+# - bithound check git@github.com:deadratfink/jy-transform.git
after_success:
- ./node_modules/codecov/bin/codecov -e TRAVIS_NODE_VERSION
From 468eb3df53ab7b306ac8fe7eedd263d00f0ffbb0 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 22 Feb 2018 07:25:50 +0100
Subject: [PATCH 55/58] Add bithound check to Makefile
---
API-PUBLIC.md | 6 +++---
MAKE.md | 1 +
Makefile | 4 ++++
3 files changed, 8 insertions(+), 3 deletions(-)
diff --git a/API-PUBLIC.md b/API-PUBLIC.md
index 07f7923..074ecba 100644
--- a/API-PUBLIC.md
+++ b/API-PUBLIC.md
@@ -59,7 +59,7 @@ an (optional) callback function. It executes the transformation logic.
2. Transform [ + callback]
3. Output (write).
-**Kind**: inner property of [jy-transform](#module_jy-transform)
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
**Returns**: Promise - The transformation result.
**Access**: public
**Resolve**: string With the transformation result as message (e.g. to be logged by caller).
@@ -104,7 +104,7 @@ try {
### jy-transform~read ⇒ Promise
Reads a particular content type from a source provided in the passed `options`.
-**Kind**: inner property of [jy-transform](#module_jy-transform)
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
**Returns**: Promise - The result.
**Access**: public
**Resolve**: string Resolves with JS object result.
@@ -146,7 +146,7 @@ read(options)
### jy-transform~write ⇒ Promise
Writes the passed JS object to a particular destination described by the passed `options`.
-**Kind**: inner property of [jy-transform](#module_jy-transform)
+**Kind**: inner constant of [jy-transform](#module_jy-transform)
**Returns**: Promise - The result.
**Access**: public
**Resolve**: string With the write success message.
diff --git a/MAKE.md b/MAKE.md
index cc19d42..7ed89d0 100644
--- a/MAKE.md
+++ b/MAKE.md
@@ -1,6 +1,7 @@
Target Call | Description | Dependencies
---|---|---
`$ make` | This calls the default target `help`. |
+`$ make bithound` | Runs bithound check. |
`$ make build` | Babel transpiles files from _./src_ to _./lib_. |
`$ make clean` | Removes generated files in folders ./node_modules, ./lib and ./coverage" |
`$ make eslint` | Runs ESLint. |
diff --git a/Makefile b/Makefile
index 66b6a05..a9081cb 100644
--- a/Makefile
+++ b/Makefile
@@ -42,6 +42,10 @@ eslint: ## Runs ESLint.
@printf "Running ESLint...\n"
npm run eslint
+bithound: ## Runs bithound check.
+ @printf "Running bithound check...\n"
+ npm run bithound
+
help: ## Prints the help about targets.
@printf "Usage: make [\033[34mtarget\033[0m]\n"
@printf "Default: \033[34m%s\033[0m\n" $(.DEFAULT_GOAL)
From 96a7cd739776a0e8ddf3f860fa99af33394479c0 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Thu, 22 Feb 2018 08:23:48 +0100
Subject: [PATCH 56/58] Improve docs
---
README.md | 71 +++++++++++++++++++++--------------------
readme/BADGES.md | 3 +-
readme/DOCUMENTATION.md | 60 +++++++++++++++++-----------------
src/transformer.js | 4 +--
4 files changed, 70 insertions(+), 68 deletions(-)
diff --git a/README.md b/README.md
index b1c1af5..59afd97 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,7 @@
[![Codacy Badge](https://img.shields.io/codacy/coverage/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Coverage)
[![Greenkeeper badge](https://badges.greenkeeper.io/deadratfink/jy-transform.svg?style=flat)](https://greenkeeper.io/)
[![NSP Status][nsp-image-master]][nsp-url-master]
+[![HitCount](http://hits.dwyl.io/deadratfink/jy-transform.svg?style=flat)](http://hits.dwyl.io/deadratfink/jy-transform)
[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat
[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
@@ -105,13 +106,13 @@ npm install jy-transform --global
## TOC
+- [Why This Module?](#why-this-module)
+- [CLI in 3 Seconds](#cli-in-3-seconds)
+ - [File Transformation](#file-transformation)
- [API in a Minute](#api-in-a-minute)
- - [Transform from Source to Destination](#transform-from-source-to-destination)
+ - [Transformation from Source to Destination](#transformation-from-source-to-destination)
- [Read into JS object from particular Source (File, Stream or JS Object)](#read-into-js-object-from-particular-source-file-stream-or-js-object)
- [Write JS object to particular Destination](#write-js-object-to-particular-destination)
-- [CLI in 3 Seconds](#cli-in-3-seconds)
- - [File Transformation](#file-transformation)
-- [Why This Module?](#why-this-module)
- [Usage](#usage)
- [Usage Types](#usage-types)
- [Use Cases](#use-cases)
@@ -125,28 +126,46 @@ npm install jy-transform --global
+## Why This Module?
+
+After struggling with some huge YAML file and accidentally
+occurring wrong indentations which results in an annoying investigation hell,
+I decided to get rid of the YAML file and therefore, create a module which
+should be aimed as the swiss army knife for transforming YAML, JS and JSON
+types into each other format.
+
+## CLI in 3 Seconds
+
+### File Transformation
+
+E.g. transform YAML content file to a JSON file with an indention of 4:
+
+```text
+$ jyt foo/bar.yaml -t json -i 4
+```
+
## API in a Minute
-### Transform from Source to Destination
+### Transformation from Source to Destination
```javascript
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // E.g. read from YAML file...
- transform: async (object) => { // ...with exchanging value...
+ src: 'foo/bar.yaml', // E.g. read from YAML file...
+ transform: async (object) => { // ...with exchanging value...
object.foo = 'new value';
return object;
},
- dest: 'foo/bar-transformed.json', // ...to a new JSON file.
- indent: 4, // Ensure an indentation of 4.
+ dest: 'foo/bar-transformed.json', // ...to a new JSON file.
+ indent: 4, // Ensure an indentation of 4.
};
// ---- Promise style:
-transform(options)
- .then(console.log)
- .catch(console.error);
+transform(options) // Transform, of course, inside an async.
+ .then(console.log) // Success message!
+ .catch(console.error); // Oops!
// ---- async/await style:
@@ -164,7 +183,7 @@ try {
```javascript
import { read } from 'jy-transform';
-const options = { src: 'foo/bar.yaml' }; // E.g. read from file.
+const options = { src: 'foo/bar.yaml' }; // E.g. read from file.
// ---- Promise style:
@@ -176,7 +195,7 @@ read(options)
try {
const object = await read(options);
- console.log(JSON.stringify(object)); // Print read object.
+ console.log(JSON.stringify(object)); // Print read object.
} catch (err) {
console.error(err);
}
@@ -205,24 +224,6 @@ try {
}
```
-## CLI in 3 Seconds
-
-### File Transformation
-
-E.g. transform YAML content file to a JSON file with an indention of 4:
-
-```text
-$ jyt foo/bar.yaml -t json -i 4
-```
-
-## Why This Module?
-
-After struggling with some huge YAML file and accidentally
-occurring wrong indentations which results in an annoying investigation hell,
-I decided to get rid of the YAML file and therefore, create a module which
-should be aimed as the swiss army knife for transforming YAML, JS and JSON
-types into each other format.
-
## Usage
The module can be used on CLI or as API (the latter is fully
@@ -267,7 +268,7 @@ Additionally, on API level from:
#### Transformation Case
The _transformation_ is usually a format change, but can also be refer to content changes on the
-intermediate JS object, the latter with the help of a configured `transform` callback function.
+intermediate JS object, the latter with the help of a configurable `transform` callback function.
All possible directions are:
- YAML ⇒ JS
@@ -286,7 +287,7 @@ while:
- [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript) = _*.js_ (JS object)
- [JSON](http://json.org) = _*.json_ (JS object serialized as JSON)
-As mentioned above the configured `transform` callback can apply particular actions on the intermediate JS object, but
+As mentioned above a configurable `transform` callback can apply particular actions on the intermediate JS object, but
this is an optional part for [transformation](#transformation) phase.
#### Write Case
diff --git a/readme/BADGES.md b/readme/BADGES.md
index ea6fdf9..5610584 100644
--- a/readme/BADGES.md
+++ b/readme/BADGES.md
@@ -18,6 +18,7 @@
[![Codacy Badge](https://img.shields.io/codacy/coverage/c2ebaac0f9874062ba468ff6bd7edc4e.svg?style=flat)](https://www.codacy.com/app/deadratfink/jy-transform?utm_source=github.com&utm_medium=referral&utm_content=deadratfink/jy-transform&utm_campaign=Badge_Coverage)
[![Greenkeeper badge](https://badges.greenkeeper.io/deadratfink/jy-transform.svg?style=flat)](https://greenkeeper.io/)
[![NSP Status][nsp-image-master]][nsp-url-master]
+[![HitCount](http://hits.dwyl.io/deadratfink/jy-transform.svg?style=flat)](http://hits.dwyl.io/deadratfink/jy-transform)
[gh-license-image]: https://img.shields.io/github/license/deadratfink/jy-transform.svg?style=flat
[gh-license-url]: https://github.com/deadratfink/jy-transform/blob/master/LICENSE.md
diff --git a/readme/DOCUMENTATION.md b/readme/DOCUMENTATION.md
index 7956e7d..c397522 100644
--- a/readme/DOCUMENTATION.md
+++ b/readme/DOCUMENTATION.md
@@ -1,25 +1,43 @@
+## Why This Module?
+
+After struggling with some huge YAML file and accidentally
+occurring wrong indentations which results in an annoying investigation hell,
+I decided to get rid of the YAML file and therefore, create a module which
+should be aimed as the swiss army knife for transforming YAML, JS and JSON
+types into each other format.
+
+## CLI in 3 Seconds
+
+### File Transformation
+
+E.g. transform YAML content file to a JSON file with an indention of 4:
+
+```text
+$ jyt foo/bar.yaml -t json -i 4
+```
+
## API in a Minute
-### Transform from Source to Destination
+### Transformation from Source to Destination
```javascript
import { transform } from 'jy-transform';
const options = {
- src: 'foo/bar.yaml', // E.g. read from YAML file...
- transform: async (object) => { // ...with exchanging value...
+ src: 'foo/bar.yaml', // E.g. read from YAML file...
+ transform: async (object) => { // ...with exchanging value...
object.foo = 'new value';
return object;
},
- dest: 'foo/bar-transformed.json', // ...to a new JSON file.
- indent: 4, // Ensure an indentation of 4.
+ dest: 'foo/bar-transformed.json', // ...to a new JSON file.
+ indent: 4, // Ensure an indentation of 4.
};
// ---- Promise style:
-transform(options)
- .then(console.log)
- .catch(console.error);
+transform(options) // Transform, of course, inside an async.
+ .then(console.log) // Success message!
+ .catch(console.error); // Oops!
// ---- async/await style:
@@ -37,7 +55,7 @@ try {
```javascript
import { read } from 'jy-transform';
-const options = { src: 'foo/bar.yaml' }; // E.g. read from file.
+const options = { src: 'foo/bar.yaml' }; // E.g. read from file.
// ---- Promise style:
@@ -49,7 +67,7 @@ read(options)
try {
const object = await read(options);
- console.log(JSON.stringify(object)); // Print read object.
+ console.log(JSON.stringify(object)); // Print read object.
} catch (err) {
console.error(err);
}
@@ -78,24 +96,6 @@ try {
}
```
-## CLI in 3 Seconds
-
-### File Transformation
-
-E.g. transform YAML content file to a JSON file with an indention of 4:
-
-```text
-$ jyt foo/bar.yaml -t json -i 4
-```
-
-## Why This Module?
-
-After struggling with some huge YAML file and accidentally
-occurring wrong indentations which results in an annoying investigation hell,
-I decided to get rid of the YAML file and therefore, create a module which
-should be aimed as the swiss army knife for transforming YAML, JS and JSON
-types into each other format.
-
## Usage
The module can be used on CLI or as API (the latter is fully
@@ -140,7 +140,7 @@ Additionally, on API level from:
#### Transformation Case
The _transformation_ is usually a format change, but can also be refer to content changes on the
-intermediate JS object, the latter with the help of a configured `transform` callback function.
+intermediate JS object, the latter with the help of a configurable `transform` callback function.
All possible directions are:
- YAML ⇒ JS
@@ -159,7 +159,7 @@ while:
- [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript) = _*.js_ (JS object)
- [JSON](http://json.org) = _*.json_ (JS object serialized as JSON)
-As mentioned above the configured `transform` callback can apply particular actions on the intermediate JS object, but
+As mentioned above a configurable `transform` callback can apply particular actions on the intermediate JS object, but
this is an optional part for [transformation](#transformation) phase.
#### Write Case
diff --git a/src/transformer.js b/src/transformer.js
index 44d0204..465934c 100644
--- a/src/transformer.js
+++ b/src/transformer.js
@@ -11,7 +11,7 @@ import { transformOptionsSchema } from './validation/options-schema';
/**
* The entry method for all transformations accepting a configuration object and
- * an (optional) callback function. It executes the transformation logic.
+ * a (configurable) transformation callback function.
*
* 1. Input (read)
* 2. Transform [ + callback]
@@ -21,7 +21,7 @@ import { transformOptionsSchema } from './validation/options-schema';
* @returns {Promise} The transformation result.
* @resolve {string} With the transformation result as message (e.g. to be logged by caller).
* @reject {ValidationError} If any `options` validation occurs.
- * @reject {Error} Will throw any error if read, transform or write operation failed due to any reason.
+ * @reject {Error} Will throw any error if read, transform or write operation has failed due to any reason.
* @private
*/
export async function transform(options) {
From 081c41d235c6be2e8c7e2218405fd61202070de1 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 23 Oct 2018 22:18:50 +0200
Subject: [PATCH 57/58] Delete bithound
---
.bithoundrc | 39 ---------------------------------------
.circleci/config.yml | 5 -----
.travis.yml | 2 --
CHANGELOG.md | 2 --
package.json | 4 +---
5 files changed, 1 insertion(+), 51 deletions(-)
delete mode 100644 .bithoundrc
diff --git a/.bithoundrc b/.bithoundrc
deleted file mode 100644
index 65b152c..0000000
--- a/.bithoundrc
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "critics": {
- "lint": {
- "engine": "eslint",
- "configLocation": ".eslintrc.js",
- "ignoreLocation": ".eslintignore"
- },
- "wc": {
- "limit": 500
- }
- },
- "dependencies": {
- "unused-ignores": [
- "babel-runtime",
- "eslint"
- ],
- "mute": [
- "bithound",
- "eslint-plugin-json",
- "inchjs",
- "joi",
- "jsdoc-to-markdown",
- "package-json-to-readme"
- ]
- },
- "ignore": [
- "**/bin/**",
- "**/coverage/**",
- "**/lib/**",
- "**/node_modules/**",
- "**/readme/**",
- "**/test/tmp/**",
- "**/test/functional/tmp/**"
- ],
- "test": [
- "**/test/unit/**",
- "**/test/functional/**"
- ]
-}
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 8654dee..cb77ff6 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -16,11 +16,6 @@ jobs:
- run:
name: Running tests
command: make test
- - run:
- name: Bithound
- command: |
- npm install bithound --save-dev
- bithound check git@github.com:deadratfink/jy-transform.git
- run:
name: Codecov Coverage
command: ./node_modules/codecov/bin/codecov
diff --git a/.travis.yml b/.travis.yml
index 427d7fa..83d0cb3 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -11,8 +11,6 @@ os:
script:
- make test
-# - npm install bithound --save-dev
-# - bithound check git@github.com:deadratfink/jy-transform.git
after_success:
- ./node_modules/codecov/bin/codecov -e TRAVIS_NODE_VERSION
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebfcff8..3ff572b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -88,8 +88,6 @@ new interface:
- [[#48](https://github.com/deadratfink/jy-transform/issues/48)] Using [Joi](https://github.com/hapijs/joi)
for consistent options validation:
- Removal of `OptionsHandler` and `Validator`.
-- [[#47](https://github.com/deadratfink/jy-transform/issues/47)] Integration of
- [bithound.io](https://www.bithound.io/github/deadratfink/jy-transform)
- [[#46](https://github.com/deadratfink/jy-transform/issues/46)] Use Make as an abstraction to npm scripts.
- [[#45](https://github.com/deadratfink/jy-transform/issues/45)] [Node Security Plattform](https://nodesecurity.io/orgs/deadratfink/projects/7ac99a62-a8c4-4321-8d57-8a5e542f04f0) integrated.
- [[#43](https://github.com/deadratfink/jy-transform/issues/43)] Documentation restructured.
diff --git a/package.json b/package.json
index 82e87a1..e6b4d41 100644
--- a/package.json
+++ b/package.json
@@ -27,8 +27,7 @@
"test": "jest --forceExit --expand --no-cache --coverage --config=./.jestrc.js",
"eslint": "eslint . --ext .json --ext .js",
"nsp": "nsp check",
- "inch": "inchjs suggest && inchjs list --all && inchjs stats",
- "bithound": "bithound check git@github.com:deadratfink/jy-transform.git"
+ "inch": "inchjs suggest && inchjs list --all && inchjs stats"
},
"engines": {
"node": ">=6.0.0"
@@ -50,7 +49,6 @@
"babel-plugin-transform-flow-strip-types": "~6.22.0",
"babel-plugin-transform-runtime": "~6.23.0",
"babel-preset-env": "~1.6.1",
- "bithound": "~1.7.0",
"chalk": "~2.3.0",
"codacy-coverage": "~2.0.2",
"codeclimate-test-reporter": "~0.5.0",
From 0d3729198ef74a7c128f7ec68543663ed806d3b2 Mon Sep 17 00:00:00 2001
From: Jens Krefeldt
Date: Tue, 23 Oct 2018 22:28:31 +0200
Subject: [PATCH 58/58] Update nsp
---
package.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/package.json b/package.json
index e6b4d41..721f6c6 100644
--- a/package.json
+++ b/package.json
@@ -70,7 +70,7 @@
"jsdoc-babel": " ~0.3.0",
"jsdoc-parse": "~3.0.0",
"jsdoc-to-markdown": "~3.0.2",
- "nsp": "~3.1.0",
+ "nsp": "^3.2.1",
"package-json-to-readme": "~2.0.0",
"winston": "^2.4.0"
},