script-transform v0.4.0
script-transform
Installation
Install this package using NPM:
npm install script-transformWhat is it about?
script-transform is a tiny package offering two simple yet powerful
instruments to transform code of an ECMAScript without having to create
a syntax tree: match() and
replace().
script-transform takes care of the following aspects:
Tokenization: scripts are internally tokenized in such a way that
match()andreplace()will only match structures of code but neither strings nor comments. This kind of an interface has proven to be very powerful in many use cases.Normalization: the user is guaranteed a normalized form of a script. Unexpected and non-trivial special cases (two examples being Unicode variable names and whitespace outside the range of
[\x00-\xFF]) can be neglected so that variable names match/[\w\\]+/and whitespace matches/\s+/.Security: the module takes all necessesary precautions such that enforced transformations can not be circumvented even if tokenization is inaccurate.
API
new Script(code: string|Script)
Creates a new transformable ECMAScript from code code.
script.replace(pattern: RegExp|string, replacement: Function|string, all = false)
Replaces a pattern in a script in-place. Accepts the same arguments as the str.replace() method. Replaces matches of either a regular expression or a string by either a
string or the result of a callback.
By default, replace() will only match segments of code but neither string
literals nor templates nor comments. As an example, script.replace(/\bwhile\s*\(/)
is guaranteed to never match anything else but a while control structure.
If all is set to true, anything, including strings, will be matched.
If pattern is a string or a non-global regular expression, only the
first match in the script will be replaced.
Returns this.
script.match(pattern: RegExp|string, callback?: Function, all = false)
Searches a script for a pattern. If a function is given as a callback, it will be called for each match with the match parameters as arguments. Otherwise, the match parameters will be returned as an array.
Unless all is set to true, match() will only match segments of code as has been
explained for the replace() function.
If pattern is a string or a non-global regular expression, match() terminates
after the first match.
Returns a match if no callback is given or undefined otherwise.
script.toString()
Returns the transformed code as a string.
License
MIT © 2016 (see full text)