angular5stringifytypescript-2.5

Use javascript-stringify library in


I want to use javascript-stringify in my angular project (or an equivalent library), but nothing I've tried thus far seems to work. I have read through a number of similar questions like mine and yet the solution evades me.

When I do:

import * as javascriptStringify from 'javascript-stringify';

I see the following error:

ERROR in src/app/prospecting/prospect-engagement/prospect-engagement.component.ts(27,13): error TS6133: 'javascriptStringify' is declared but never used.

src/app/prospecting/prospect-engagement/prospect-engagement.component.ts(27,38): error TS2497: Module '"node_modules/javascript-stringify/javascript-stringify"' resolves to a non-module entity and cannot be imported using this construct.

When I do:

import stringify from 'javascript-stringify';   

I see the following error:

ERROR in src/app/prospecting/prospect-engagement/prospect-engagement.component.ts(27,8): error TS1192: Module '"node_modules/javascript-stringify/javascript-stringify"' has no default export.

src/app/prospecting/prospect-engagement/prospect-engagement.component.ts(27,8): error TS6133: 'stringify' is declared but never used.

Here's the output of ng --version:

$ ng --version
Your global Angular CLI version (1.5.4) is greater than your local
version (1.5.0). The local Angular CLI version is used.

To disable this warning use "ng set --global warnings.versionMismatch=false".

    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/

Angular CLI: 1.5.0
Node: 8.9.1
OS: darwin x64
Angular: 5.0.3
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.5.0
@angular-devkit/build-optimizer: 0.0.34
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.38
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0
@schematics/angular: 0.1.8
typescript: 2.5.3
webpack: 3.8.1

Can someone show me a way to use this library...or point me to another library that offers the same functionality?

Update:

I found that if I change the file node_modules/javascript-stringify/javascript-stringify.d.ts from export = stringify; to export default stringify;, then import stringify from 'javascript-stringify'; works as expected.

However, the code under node_modules is subject to change and will definitely lose my changes when built inside Docker when npm install is run. Is this the best way forward? If so, what is the best way to make my changes permanent?


Solution

  • I never got the npm module javascript-stringify to work, but I was able to port it to be an Angular 5 / Typescript service, where it works fine. The original module is MIT license and so is my ported code below:

    /**
      The MIT License (MIT)
    
      Copyright (c) 2018 Joshua Kaldon (jkaldon@gmail.com)
    
      Based heavily on code from Blake Embrey's javascript-stringify library 
      which can be found at https://github.com/blakeembrey/javascript-stringify
    
      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files (the "Software"), to deal
      in the Software without restriction, including without limitation the rights
      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      copies of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:
    
      The above copyright notice and this permission notice shall be included in
      all copies or substantial portions of the Software.
    
      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      THE SOFTWARE.
    */
    
    import { Injectable } from '@angular/core';
    
    declare const Buffer;
    
    @Injectable()
    export class StringifyJavascriptService {
    
      constructor() {
    
        /**
         * Map reserved words to the object.
         */
        (
          'break else new var case finally return void catch for switch while ' +
          'continue function this with default if throw delete in try ' +
          'do instanceof typeof abstract enum int short boolean export ' +
          'interface static byte extends long super char final native synchronized ' +
          'class float package throws const goto private transient debugger ' +
          'implements protected volatile double import public let yield'
        ).split(' ').map(function (key) {
          StringifyJavascriptService.RESERVED_WORDS[key] = true;
        });
      }
    
    
      /**
       * Match all characters that need to be escaped in a string. Modified from
       * source to match single quotes instead of double.
       *
       * Source: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
       */
      private static ESCAPABLE = /[\\\'\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    
      /**
       * Map of characters to escape characters.
       */
      private static META_CHARS = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        "'":  "\\'",
        '"':  '\\"',
        '\\': '\\\\'
      };
    
      /**
       * Escape any character into its literal JavaScript string.
       *
       * @param  {string} char
       * @return {string}
       */
      private static escapeChar (char) {
        var meta = StringifyJavascriptService.META_CHARS[char];
    
        return meta || '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4);
      };
    
      /**
       * JavaScript reserved word list.
       */
      private static RESERVED_WORDS = {};
    
      /**
       * Test for valid JavaScript identifier.
       */
      private static IS_VALID_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
    
      /**
       * Check if a variable name is valid.
       *
       * @param  {string}  name
       * @return {boolean}
       */
      private static isValidVariableName (name: string) {
        return !StringifyJavascriptService.RESERVED_WORDS[name] && StringifyJavascriptService.IS_VALID_IDENTIFIER.test(name);
      }
    
      /**
       * Return the global variable name.
       *
       * @return {string}
       */
      private static toGlobalVariable (value: any): string {
        true == value;
        return 'Function(' + StringifyJavascriptService.stringify('return this;') + ')()';
      }
    
      /**
       * Serialize the path to a string.
       *
       * @param  {Array}  path
       * @return {string}
       */
      private static toPath (path: Array<any>) {
        var result = '';
    
        for (var i = 0; i < path.length; i++) {
          if (StringifyJavascriptService.isValidVariableName(path[i])) {
            result += '.' + path[i];
          } else {
            result += '[' + StringifyJavascriptService.stringify(path[i]) + ']';
          }
        }
    
        return result;
      }
    
      /**
       * Stringify an array of values.
       *
       * @param  {Array}    array
       * @param  {string}   indent
       * @param  {Function} next
       * @return {string}
       */
      private static stringifyArray (array: Array<any>, indent?: string, next?: Function): string {
        // Map array values to their stringified values with correct indentation.
        var values = array.map(function (value, index) {
          var str = next(value, index);
    
          if (str === undefined) {
            return String(str);
          }
    
          return indent + str.split('\n').join('\n' + indent);
        }).join(indent ? ',\n' : ',');
    
        // Wrap the array in newlines if we have indentation set.
        if (indent && values) {
          return '[\n' + values + '\n]';
        }
    
        return '[' + values + ']';
      }
    
      /**
       * Stringify a map of values.
       *
       * @param  {Object}   object
       * @param  {string}   indent
       * @param  {Function} next
       * @return {string}
       */
      private static stringifyObject (object: any, indent?: string, next?: Function): string {
        // Iterate over object keys and concat string together.
        var values = Object.keys(object).reduce(function (values, key) {
          var value = next(object[key], key);
    
          // Omit `undefined` object values.
          if (value === undefined) {
            return values;
          }
    
          // String format the key and value data.
          key   = StringifyJavascriptService.isValidVariableName(key) ? key : StringifyJavascriptService.stringify(key);
          value = String(value).split('\n').join('\n' + indent);
    
          // Push the current object key and value into the values array.
          values.push(indent + key + ':' + (indent ? ' ' : '') + value);
    
          return values;
        }, []).join(indent ? ',\n' : ',');
    
        // Wrap the object in newlines if we have indentation set.
        if (indent && values) {
          return '{\n' + values + '\n}';
        }
    
        return '{' + values + '}';
      }
    
      /**
       * Convert JavaScript objects into strings.
       */
      private static OBJECT_TYPES = {
        '[object Array]': StringifyJavascriptService.stringifyArray,
        '[object Object]': StringifyJavascriptService.stringifyObject,
        '[object Error]': function (error) {
          return 'new Error(' + StringifyJavascriptService.stringify(error.message) + ')';
        },
        '[object Date]': function (date) {
          return 'new Date(' + date.getTime() + ')';
        },
        '[object String]': function (string) {
          return 'new String(' + StringifyJavascriptService.stringify(string.toString()) + ')';
        },
        '[object Number]': function (number) {
          return 'new Number(' + number + ')';
        },
        '[object Boolean]': function (boolean) {
          return 'new Boolean(' + boolean + ')';
        },
        '[object Uint8Array]': function (array, indent) {
          return 'new Uint8Array(' + StringifyJavascriptService.stringifyArray(array, indent) + ')';
        },
        '[object Set]': function (array, indent, next) {
          if (typeof Array.from === 'function') {
            return 'new Set(' + StringifyJavascriptService.stringify(Array.from(array), indent, next) + ')';
          } else return undefined;
        },
        '[object Map]': function (array, indent, next) {
          if (typeof Array.from === 'function') {
            return 'new Map(' + StringifyJavascriptService.stringify(Array.from(array), indent, next) + ')';
          } else return undefined;
        },
        '[object RegExp]': String,
        '[object Function]': String,
        '[object global]': StringifyJavascriptService.toGlobalVariable,
        '[object Window]': StringifyJavascriptService.toGlobalVariable
      };
    
      /**
       * Convert JavaScript primitives into strings.
       */
      private static PRIMITIVE_TYPES = {
        'string': function (string) {
          return "'" + string.replace(StringifyJavascriptService.ESCAPABLE, StringifyJavascriptService.escapeChar) + "'";
        },
        'number': String,
        'object': String,
        'boolean': String,
        'symbol': String,
        'undefined': String
      };
    
      /**
       * Convert any value to a string.
       *
       * @param  {*}        value
       * @param  {string}   indent
       * @param  {Function} next
       * @return {string}
       */
      private static stringify (value: any, indent?: string, next?: Function): string {
        // Convert primitives into strings.
        if (Object(value) !== value) {
          return StringifyJavascriptService.PRIMITIVE_TYPES[typeof value](value, indent, next);
        }
    
        // Handle buffer objects before recursing (node < 6 was an object, node >= 6 is a `Uint8Array`).
        if (typeof Buffer === 'function' && Buffer.isBuffer(value)) {
          return 'new Buffer(' + next(value.toString()) + ')';
        }
    
        // Use the internal object string to select stringification method.
        var toString = StringifyJavascriptService.OBJECT_TYPES[Object.prototype.toString.call(value)];
    
        // Convert objects into strings.
        return toString ? toString(value, indent, next) : undefined;
      }
    
      /**
       * Stringify an object into the literal string.
       *
       * @param  {*}               value
       * @param  {Function}        [replacer]
       * @param  {(number|string)} [space]
       * @param  {Object}          [options]
       * @return {string}
       */
      public toString(value: any, replacer?: Function, space?: number|string, options?: any): string {
        options = options || {}
    
        // Convert the spaces into a string.
        if (typeof space !== 'string') {
          space = new Array(Math.max(0, space|0) + 1).join(' ');
        }
    
        var maxDepth = Number(options.maxDepth) || 100;
        var references = !!options.references;
        var skipUndefinedProperties = !!options.skipUndefinedProperties;
        var valueCount = Number(options.maxValues) || 100000;
    
        var path = [];
        var stack = [];
        var encountered = [];
        var paths = [];
        var restore = [];
    
        /**
         * Stringify the next value in the stack.
         *
         * @param  {*}      value
         * @param  {string} key
         * @return {string}
         */
        function next (value: any, key: string): string {
          if (skipUndefinedProperties && value === undefined) {
            return undefined;
          }
    
          path.push(key);
          var result = recurse(value, StringifyJavascriptService.stringify);
          path.pop();
          return result;
        }
    
        /**
         * Handle recursion by checking if we've visited this node every iteration.
         *
         * @param  {*}        value
         * @param  {Function} stringify
         * @return {string}
         */
        var recurse = references ?
          function (value, stringify) {
            if (value && (typeof value === 'object' || typeof value === 'function')) {
              const seen = encountered.indexOf(value);
    
              // Track nodes to restore later.
              if (seen > -1) {
                restore.push(path.slice(), paths[seen]);
                return;
              }
    
              // Track encountered nodes.
              encountered.push(value);
              paths.push(path.slice());
            }
    
            // Stop when we hit the max depth.
            if (path.length > maxDepth || valueCount-- <= 0) {
              return;
            }
    
            // Stringify the value and fallback to
            return stringify(value, space, next);
          } :
          function (value, stringify) {
            const seen = stack.indexOf(value);
    
            if (seen > -1 || path.length > maxDepth || valueCount-- <= 0) {
              return;
            }
    
            stack.push(value);
            var value = stringify(value, space, next);
            stack.pop();
            return value;
          };
    
        // If the user defined a replacer function, make the recursion function
        // a double step process - `recurse -> replacer -> stringify`.
        if (typeof replacer === 'function') {
          const before = recurse
    
          // Intertwine the replacer function with the regular recursion.
          recurse = function (value, stringify) {
            return before(value, function (value, space, next) {
              return replacer(value, space, function (value) {
                return stringify(value, space, next);
              });
            });
          };
        }
    
        var result = recurse(value, StringifyJavascriptService.stringify);
    
        // Attempt to restore circular references.
        if (restore.length) {
          var sep = space ? '\n' : '';
          var assignment = space ? ' = ' : '=';
          var eol = ';' + sep;
          var before = space ? '(function () {' : '(function(){'
          var after = '}())'
          var results = ['var x' + assignment + result];
    
          for (var i = 0; i < restore.length; i += 2) {
            results.push('x' + StringifyJavascriptService.toPath(restore[i]) + assignment + 'x' + StringifyJavascriptService.toPath(restore[i + 1]));
          }
    
          results.push('return x');
    
          return before + sep + results.join(eol) + eol + after
        }
    
        return result;
      }
    }