Clean up types in build/lib/optimize.ts

This commit is contained in:
Alex Dima 2016-10-20 14:16:57 +02:00
parent d904442b42
commit abce9969fe
12 changed files with 1007 additions and 99 deletions

View File

@ -22,7 +22,7 @@ var REPO_ROOT_PATH = path.join(__dirname, '../..');
function log(prefix, message) {
gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
}
exports.loaderConfig = function (emptyPaths) {
function loaderConfig(emptyPaths) {
var result = {
paths: {
'vs': 'out-build/vs',
@ -32,7 +32,8 @@ exports.loaderConfig = function (emptyPaths) {
};
result['vs/css'] = { inlineResources: true };
return result;
};
}
exports.loaderConfig = loaderConfig;
var IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
function loader(bundledFileHeader, bundleLoader) {
var sources = [
@ -104,18 +105,7 @@ function toBundleStream(bundledFileHeader, bundles) {
return toConcatStream(bundledFileHeader, bundle.sources, bundle.dest);
}));
}
/**
* opts:
* - entryPoints (for AMD files, will get bundled and get Copyright treatment)
* - otherSources (for non-AMD files that should get Copyright treatment)
* - resources (svg, etc.)
* - loaderConfig
* - bundleLoader (boolean - true by default - append css and nls to loader)
* - header (basically the Copyright treatment)
* - bundleInfo (boolean - emit bundleInfo.json file)
* - out (out folder name)
*/
exports.optimizeTask = function (opts) {
function optimizeTask(opts) {
var entryPoints = opts.entryPoints;
var otherSources = opts.otherSources;
var resources = opts.resources;
@ -176,35 +166,39 @@ exports.optimizeTask = function (opts) {
}))
.pipe(gulp.dest(out));
};
};
}
exports.optimizeTask = optimizeTask;
;
/**
* Wrap around uglify and allow the preserveComments function
* to have a file "context" to include our copyright only once per file.
*/
function uglifyWithCopyrights() {
var preserveComments = function (f) { return function (node, comment) {
var text = comment.value;
var type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
var isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
var preserveComments = function (f) {
return function (node, comment) {
var text = comment.value;
var type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
}; };
var isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
}
else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
var input = es.through();
var output = input
.pipe(flatmap(function (stream, f) {
@ -213,7 +207,7 @@ function uglifyWithCopyrights() {
}));
return es.duplex(input, output);
}
exports.minifyTask = function (src, sourceMapBaseUrl) {
function minifyTask(src, sourceMapBaseUrl) {
var sourceMappingURL = sourceMapBaseUrl && (function (f) { return (sourceMapBaseUrl + "/" + f.relative + ".map"); });
return function (cb) {
var jsFilter = filter('**/*.js', { restore: true });
@ -230,4 +224,6 @@ exports.minifyTask = function (src, sourceMapBaseUrl) {
cb(err);
});
};
};
}
exports.minifyTask = minifyTask;
;

View File

@ -5,29 +5,30 @@
'use strict';
const path = require('path');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const filter = require('gulp-filter');
const minifyCSS = require('gulp-cssnano');
const uglify = require('gulp-uglify');
const es = require('event-stream');
const concat = require('gulp-concat');
const VinylFile = require('vinyl');
const bundle = require('./bundle');
const util = require('./util');
const i18n = require('./i18n');
const gulpUtil = require('gulp-util');
const flatmap = require('gulp-flatmap');
const pump = require('pump');
import * as path from 'path';
import * as gulp from 'gulp';
import * as sourcemaps from 'gulp-sourcemaps';
import * as filter from 'gulp-filter';
import * as minifyCSS from 'gulp-cssnano';
import * as uglify from 'gulp-uglify';
import * as es from 'event-stream';
import * as concat from 'gulp-concat';
import * as VinylFile from 'vinyl';
import * as bundle from './bundle';
import * as util from './util';
import * as i18n from './i18n';
import * as gulpUtil from 'gulp-util';
import * as flatmap from 'gulp-flatmap';
import * as pump from 'pump';
import * as sm from 'source-map';
const REPO_ROOT_PATH = path.join(__dirname, '../..');
function log(prefix, message) {
function log(prefix:string, message:string): void {
gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
}
exports.loaderConfig = function (emptyPaths) {
export function loaderConfig(emptyPaths:string[]) {
const result = {
paths: {
'vs': 'out-build/vs',
@ -39,11 +40,15 @@ exports.loaderConfig = function (emptyPaths) {
result['vs/css'] = { inlineResources: true };
return result;
};
}
const IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
function loader(bundledFileHeader, bundleLoader) {
declare class FileSourceMap extends VinylFile {
public sourceMap: sm.RawSourceMap;
}
function loader(bundledFileHeader:string, bundleLoader:boolean): NodeJS.ReadWriteStream {
let sources = [
'out-build/vs/loader.js'
];
@ -73,14 +78,14 @@ function loader(bundledFileHeader, bundleLoader) {
}))
.pipe(util.loadSourcemaps())
.pipe(concat('vs/loader.js'))
.pipe(es.mapSync(function (f) {
.pipe(es.mapSync<FileSourceMap,FileSourceMap>(function (f) {
f.sourceMap.sourceRoot = util.toFileUri(path.join(REPO_ROOT_PATH, 'src'));
return f;
}))
);
}
function toConcatStream(bundledFileHeader, sources, dest) {
function toConcatStream(bundledFileHeader:string, sources:bundle.IFile[], dest:string): NodeJS.ReadWriteStream {
const useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
// If a bundle ends up including in any of the sources our copyright, then
@ -117,24 +122,44 @@ function toConcatStream(bundledFileHeader, sources, dest) {
.pipe(concat(dest));
}
function toBundleStream(bundledFileHeader, bundles) {
function toBundleStream(bundledFileHeader:string, bundles:bundle.IConcatFile[]): NodeJS.ReadWriteStream {
return es.merge(bundles.map(function(bundle) {
return toConcatStream(bundledFileHeader, bundle.sources, bundle.dest);
}));
}
/**
* opts:
* - entryPoints (for AMD files, will get bundled and get Copyright treatment)
* - otherSources (for non-AMD files that should get Copyright treatment)
* - resources (svg, etc.)
* - loaderConfig
* - bundleLoader (boolean - true by default - append css and nls to loader)
* - header (basically the Copyright treatment)
* - bundleInfo (boolean - emit bundleInfo.json file)
* - out (out folder name)
*/
exports.optimizeTask = function(opts) {
export interface IOptimizeTaskOpts {
/**
* (for AMD files, will get bundled and get Copyright treatment)
*/
entryPoints: bundle.IEntryPoint[];
/**
* (for non-AMD files that should get Copyright treatment)
*/
otherSources: string[];
/**
* (svg, etc.)
*/
resources: string[];
loaderConfig: any;
/**
* (true by default - append css and nls to loader)
*/
bundleLoader?: boolean;
/**
* (basically the Copyright treatment)
*/
header: string;
/**
* (emit bundleInfo.json file)
*/
bundleInfo: boolean;
/**
* (out folder name)
*/
out: string;
}
export function optimizeTask(opts:IOptimizeTaskOpts):()=>NodeJS.ReadWriteStream {
const entryPoints = opts.entryPoints;
const otherSources = opts.otherSources;
const resources = opts.resources;
@ -163,7 +188,7 @@ exports.optimizeTask = function(opts) {
});
gulp.src(filteredResources, { base: 'out-build' }).pipe(resourcesStream);
const bundleInfoArray = [];
const bundleInfoArray:VinylFile[] = [];
if (opts.bundleInfo) {
bundleInfoArray.push(new VinylFile({
path: 'bundleInfo.json',
@ -175,7 +200,7 @@ exports.optimizeTask = function(opts) {
});
const otherSourcesStream = es.through();
const otherSourcesStreamArr = [];
const otherSourcesStreamArr:NodeJS.ReadWriteStream[] = [];
gulp.src(otherSources, { base: 'out-build' })
.pipe(es.through(function (data) {
@ -209,49 +234,54 @@ exports.optimizeTask = function(opts) {
};
};
declare class FileWithCopyright extends VinylFile {
public __hasOurCopyright: boolean;
}
/**
* Wrap around uglify and allow the preserveComments function
* to have a file "context" to include our copyright only once per file.
*/
function uglifyWithCopyrights() {
const preserveComments = f => (node, comment) => {
const text = comment.value;
const type = comment.type;
function uglifyWithCopyrights():NodeJS.ReadWriteStream {
const preserveComments = (f:FileWithCopyright) => {
return (node, comment:{value:string;type:string;}) => {
const text = comment.value;
const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
if (/@minifier_do_not_preserve/.test(text)) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
} else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) {
if (f.__hasOurCopyright) {
return false;
}
f.__hasOurCopyright = true;
return true;
}
if ('comment2' === type) {
// check for /*!. Note that text doesn't contain leading /*
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
} else if ('comment1' === type) {
return /license|copyright/i.test(text);
}
return false;
};
};
const input = es.through();
const output = input
.pipe(flatmap((stream, f) => {
return stream
.pipe(uglify({ preserveComments: preserveComments(f) }));
.pipe(uglify({ preserveComments: preserveComments(<FileWithCopyright>f) }));
}));
return es.duplex(input, output);
}
exports.minifyTask = function (src, sourceMapBaseUrl) {
export function minifyTask(src:string, sourceMapBaseUrl:string):(cb:any)=>void {
const sourceMappingURL = sourceMapBaseUrl && (f => `${ sourceMapBaseUrl }/${ f.relative }.map`);
return cb => {
@ -274,7 +304,7 @@ exports.minifyTask = function (src, sourceMapBaseUrl) {
addComment: true
}),
gulp.dest(src + '-min')
, err => {
, (err:any) => {
if (err instanceof uglify.GulpUglifyError) {
console.error(`Uglify error in '${ err.cause && err.cause.filename }'`);
}

121
build/lib/typings/chalk.d.ts vendored Normal file
View File

@ -0,0 +1,121 @@
// Type definitions for chalk v0.4.0
// Project: https://github.com/sindresorhus/chalk
// Definitions by: Diullei Gomes <https://github.com/Diullei>, Bart van der Schoor <https://github.com/Bartvds>, Nico Jansen <https://github.com/nicojs>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Chalk {
export var enabled: boolean;
export var supportsColor: boolean;
export var styles: ChalkStyleMap;
export function stripColor(value: string): any;
export function hasColor(str: string): boolean;
export interface ChalkChain extends ChalkStyle {
(...text: string[]): string;
}
export interface ChalkStyleElement {
open: string;
close: string;
}
// General
export var reset: ChalkChain;
export var bold: ChalkChain;
export var italic: ChalkChain;
export var underline: ChalkChain;
export var inverse: ChalkChain;
export var strikethrough: ChalkChain;
// Text colors
export var black: ChalkChain;
export var red: ChalkChain;
export var green: ChalkChain;
export var yellow: ChalkChain;
export var blue: ChalkChain;
export var magenta: ChalkChain;
export var cyan: ChalkChain;
export var white: ChalkChain;
export var gray: ChalkChain;
export var grey: ChalkChain;
// Background colors
export var bgBlack: ChalkChain;
export var bgRed: ChalkChain;
export var bgGreen: ChalkChain;
export var bgYellow: ChalkChain;
export var bgBlue: ChalkChain;
export var bgMagenta: ChalkChain;
export var bgCyan: ChalkChain;
export var bgWhite: ChalkChain;
export interface ChalkStyle {
// General
reset: ChalkChain;
bold: ChalkChain;
italic: ChalkChain;
underline: ChalkChain;
inverse: ChalkChain;
strikethrough: ChalkChain;
// Text colors
black: ChalkChain;
red: ChalkChain;
green: ChalkChain;
yellow: ChalkChain;
blue: ChalkChain;
magenta: ChalkChain;
cyan: ChalkChain;
white: ChalkChain;
gray: ChalkChain;
grey: ChalkChain;
// Background colors
bgBlack: ChalkChain;
bgRed: ChalkChain;
bgGreen: ChalkChain;
bgYellow: ChalkChain;
bgBlue: ChalkChain;
bgMagenta: ChalkChain;
bgCyan: ChalkChain;
bgWhite: ChalkChain;
}
export interface ChalkStyleMap {
// General
reset: ChalkStyleElement;
bold: ChalkStyleElement;
italic: ChalkStyleElement;
underline: ChalkStyleElement;
inverse: ChalkStyleElement;
strikethrough: ChalkStyleElement;
// Text colors
black: ChalkStyleElement;
red: ChalkStyleElement;
green: ChalkStyleElement;
yellow: ChalkStyleElement;
blue: ChalkStyleElement;
magenta: ChalkStyleElement;
cyan: ChalkStyleElement;
white: ChalkStyleElement;
gray: ChalkStyleElement;
// Background colors
bgBlack: ChalkStyleElement;
bgRed: ChalkStyleElement;
bgGreen: ChalkStyleElement;
bgYellow: ChalkStyleElement;
bgBlue: ChalkStyleElement;
bgMagenta: ChalkStyleElement;
bgCyan: ChalkStyleElement;
bgWhite: ChalkStyleElement;
}
}
declare module "chalk" {
export = Chalk;
}

43
build/lib/typings/gulp-concat.d.ts vendored Normal file
View File

@ -0,0 +1,43 @@
// Type definitions for gulp-concat
// Project: http://github.com/wearefractal/gulp-concat
// Definitions by: Keita Kagurazaka <https://github.com/k-kagurazaka>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "gulp-concat" {
interface IOptions {
newLine: string;
}
interface IFsStats {
dev?: number;
ino?: number;
mode?: number;
nlink?: number;
uid?: number;
gid?: number;
rdev?: number;
size?: number;
blksize?: number;
blocks?: number;
atime?: Date;
mtime?: Date;
ctime?: Date;
}
interface IVinylOptions {
cwd?: string;
base?: string;
path?: string;
stat?: IFsStats;
contents?: NodeJS.ReadableStream | Buffer;
}
interface IConcat {
(filename: string, options?: IOptions): NodeJS.ReadWriteStream;
(options: IVinylOptions): NodeJS.ReadWriteStream;
}
var _tmp: IConcat;
export = _tmp;
}

12
build/lib/typings/gulp-cssnano.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
declare module "gulp-cssnano" {
function f(opts:{reduceIdents:boolean;}): NodeJS.ReadWriteStream;
/**
* This is required as per:
* https://github.com/Microsoft/TypeScript/issues/5073
*/
namespace f {}
export = f;
}

12
build/lib/typings/gulp-flatmap.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
declare module 'gulp-flatmap' {
import File = require('vinyl');
function f(fn:(stream:NodeJS.ReadWriteStream, file:File)=>NodeJS.ReadWriteStream): NodeJS.ReadWriteStream;
/**
* This is required as per:
* https://github.com/Microsoft/TypeScript/issues/5073
*/
namespace f {}
export = f;
}

27
build/lib/typings/gulp-sourcemaps.d.ts vendored Normal file
View File

@ -0,0 +1,27 @@
// Type definitions for gulp-sourcemaps
// Project: https://github.com/floridoo/gulp-sourcemaps
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "gulp-sourcemaps" {
interface InitOptions {
loadMaps?: boolean;
debug?: boolean;
}
interface WriteMapper {
(file: string): string;
}
interface WriteOptions {
addComment?: boolean;
includeContent?: boolean;
sourceRoot?: string | WriteMapper;
sourceMappingURLPrefix?: string | WriteMapper;
sourceMappingURL?: (f:{relative:string})=>string;
}
export function init(opts?: InitOptions): NodeJS.ReadWriteStream;
export function write(path?: string, opts?: WriteOptions): NodeJS.ReadWriteStream;
export function write(opts?: WriteOptions): NodeJS.ReadWriteStream;
}

45
build/lib/typings/gulp-uglify.d.ts vendored Normal file
View File

@ -0,0 +1,45 @@
// Type definitions for gulp-uglify
// Project: https://github.com/terinjokes/gulp-uglify
// Definitions by: Christopher Haws <https://github.com/ChristopherHaws/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "gulp-uglify" {
import * as UglifyJS from 'uglify-js';
namespace GulpUglify {
interface Options {
/**
* Pass false to skip mangling names.
*/
mangle?: boolean;
/**
* Pass if you wish to specify additional output options. The defaults are optimized for best compression.
*/
output?: UglifyJS.BeautifierOptions;
/**
* Pass an object to specify custom compressor options. Pass false to skip compression completely.
*/
compress?: UglifyJS.CompressorOptions | boolean;
/**
* A convenience option for options.output.comments. Defaults to preserving no comments.
* all - Preserve all comments in code blocks
* some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on)
* function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false.
*/
preserveComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean);
}
class GulpUglifyError {
cause: {
filename: string;
};
}
}
function GulpUglify(options?: GulpUglify.Options): NodeJS.ReadWriteStream;
export = GulpUglify;
}

133
build/lib/typings/gulp-util.d.ts vendored Normal file
View File

@ -0,0 +1,133 @@
// Type definitions for gulp-util v3.0.x
// Project: https://github.com/gulpjs/gulp-util
// Definitions by: jedmao <https://github.com/jedmao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'gulp-util' {
import vinyl = require('vinyl');
import chalk = require('chalk');
import through2 = require('through2');
export class File extends vinyl { }
/**
* Replaces a file extension in a path. Returns the new path.
*/
export function replaceExtension(npath: string, ext: string): string;
export var colors: typeof chalk;
export var date: {
(now?: Date, mask?: string, convertLocalTimeToUTC?: boolean): any;
(date?: string, mask?: string, convertLocalTimeToUTC?: boolean): any;
masks: any;
};
/**
* Logs stuff. Already prefixed with [gulp] and all that. Use the right colors
* for values. If you pass in multiple arguments it will join them by a space.
*/
export function log(message?: any, ...optionalParams: any[]): void;
/**
* This is a lodash.template function wrapper. You must pass in a valid gulp
* file object so it is available to the user or it will error. You can not
* configure any of the delimiters. Look at the lodash docs for more info.
*/
export function template(tmpl: string): (opt: { file: { path: string } }) => string;
export function template(tmpl: string, opt: { file: { path: string } }): string;
export var env: any;
export function beep(): void;
/**
* Returns a stream that does nothing but pass data straight through.
*/
export var noop: typeof through2;
export function isStream(obj: any): boolean;
export function isBuffer(obj: any): boolean;
export function isNull(obj: any): boolean;
export var linefeed: string;
export function combine(streams: NodeJS.ReadWriteStream[]): () => NodeJS.ReadWriteStream;
export function combine(...streams: NodeJS.ReadWriteStream[]): () => NodeJS.ReadWriteStream;
/**
* This is similar to es.wait but instead of buffering text into one string
* it buffers anything into an array (so very useful for file objects).
*/
export function buffer(cb?: (err: Error, data: any[]) => void): NodeJS.ReadWriteStream;
export class PluginError implements Error, PluginErrorOptions {
constructor(options?: PluginErrorOptions);
constructor(pluginName: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: Error, options?: PluginErrorOptions);
/**
* The module name of your plugin.
*/
name: string;
/**
* Can be a string or an existing error.
*/
message: any;
fileName: string;
lineNumber: number;
/**
* You need to include the message along with this stack. If you pass an
* error in as the message the stack will be pulled from that, otherwise one
* will be created.
*/
stack: string;
/**
* By default the stack will not be shown. Set this to true if you think the
* stack is important for your error.
*/
showStack: boolean;
/**
* Error properties will be included in err.toString(). Can be omitted by
* setting this to false.
*/
showProperties: boolean;
plugin: string;
error: Error;
}
}
interface PluginErrorOptions {
/**
* The module name of your plugin.
*/
name?: string;
/**
* Can be a string or an existing error.
*/
message?: any;
fileName?: string;
lineNumber?: number;
/**
* You need to include the message along with this stack. If you pass an
* error in as the message the stack will be pulled from that, otherwise one
* will be created.
*/
stack?: string;
/**
* By default the stack will not be shown. Set this to true if you think the
* stack is important for your error.
*/
showStack?: boolean;
/**
* Error properties will be included in err.toString(). Can be omitted by
* setting this to false.
*/
showProperties?: boolean;
plugin?: string;
error?: Error;
}

23
build/lib/typings/pump.d.ts vendored Normal file
View File

@ -0,0 +1,23 @@
declare module 'pump' {
function f(
str1:NodeJS.WritableStream,
str2:NodeJS.WritableStream,
str3:NodeJS.WritableStream,
str4:NodeJS.WritableStream,
str5:NodeJS.WritableStream,
str6:NodeJS.WritableStream,
str7:NodeJS.WritableStream,
str8:NodeJS.WritableStream,
str9:NodeJS.WritableStream,
str10:NodeJS.WritableStream,
cb:(err:any)=>void
): NodeJS.WritableStream;
/**
* This is required as per:
* https://github.com/Microsoft/TypeScript/issues/5073
*/
namespace f {}
export = f;
}

38
build/lib/typings/through2.d.ts vendored Normal file
View File

@ -0,0 +1,38 @@
// Type definitions for through2 v 2.0.0
// Project: https://github.com/rvagg/through2
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, jedmao <https://github.com/jedmao>, Georgios Valotasios <https://github.com/valotas>, Ben Chauvette <https://github.com/bdchauvette>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'through2' {
import stream = require('stream');
type TransformCallback = (err?: any, data?: any) => void;
type TransformFunction = (chunk: any, enc: string, callback: TransformCallback) => void;
type FlushCallback = (flushCallback: () => void) => void;
function through2(transform?: TransformFunction, flush?: FlushCallback): stream.Transform;
function through2(opts?: stream.DuplexOptions, transform?: TransformFunction, flush?: FlushCallback): stream.Transform;
namespace through2 {
export interface Through2Constructor extends stream.Transform {
new(opts?: stream.DuplexOptions): stream.Transform;
(opts?: stream.DuplexOptions): stream.Transform;
}
/**
* Convenvience method for creating object streams
*/
export function obj(transform?: TransformFunction, flush?: FlushCallback): stream.Transform;
/**
* Creates a constructor for a custom Transform. This is useful when you
* want to use the same transform logic in multiple instances.
*/
export function ctor(opts?: stream.DuplexOptions, transfrom?: TransformFunction, flush?: FlushCallback): Through2Constructor;
}
export = through2;
}

428
build/lib/typings/uglify-js.d.ts vendored Normal file
View File

@ -0,0 +1,428 @@
// Type definitions for UglifyJS 2 v2.6.1
// Project: https://github.com/mishoo/UglifyJS2
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'uglify-js' {
import * as MOZ_SourceMap from 'source-map';
namespace UglifyJS {
interface Tokenizer {
/**
* The type of this token.
* Can be "num", "string", "regexp", "operator", "punc", "atom", "name", "keyword", "comment1" or "comment2".
* "comment1" and "comment2" are for single-line, respectively multi-line comments.
*/
type: string;
/**
* The name of the file where this token originated from. Useful when compressing multiple files at once to generate the proper source map.
*/
file: string;
/**
* The "value" of the token.
* That's additional information and depends on the token type: "num", "string" and "regexp" tokens you get their literal value.
* - For "operator" you get the operator.
* - For "punc" it's the punctuation sign (parens, comma, semicolon etc).
* - For "atom", "name" and "keyword" it's the name of the identifier
* - For comments it's the body of the comment (excluding the initial "//" and "/*".
*/
value: string;
/**
* The line number of this token in the original code.
* 1-based index.
*/
line: number;
/**
* The column number of this token in the original code.
* 0-based index.
*/
col: number;
/**
* Short for "newline before", it's a boolean that tells us whether there was a newline before this node in the original source. It helps for automatic semicolon insertion.
* For multi-line comments in particular this will be set to true if there either was a newline before this comment, or * * if this comment contains a newline.
*/
nlb: boolean;
/**
* This doesn't apply for comment tokens, but for all other token types it will be an array of comment tokens that were found before.
*/
comments_before: string[];
}
interface AST_Node {
// The first token of this node
start: AST_Node;
// The last token of this node
end: AST_Node;
transform(tt: TreeTransformer): AST_Toplevel;
}
interface AST_Toplevel extends AST_Node {
// UglifyJS contains a scope analyzer which figures out variable/function definitions, references etc.
// You need to call it manually before compression or mangling.
// The figure_out_scope method is defined only on the AST_Toplevel node.
figure_out_scope(): void;
// Get names that are optimized for GZip compression (names will be generated using the most frequent characters first)
compute_char_frequency(): void;
mangle_names(): void;
print(stream: OutputStream): void;
print_to_string(options?: BeautifierOptions): string;
}
interface MinifyOptions {
spidermonkey?: boolean;
outSourceMap?: string;
sourceRoot?: string;
inSourceMap?: string;
fromString?: boolean;
warnings?: boolean;
mangle?: Object;
output?: MinifyOutput,
compress?: Object;
}
interface MinifyOutput {
code: string;
map: string;
}
function minify(files: string | Array<string>, options?: MinifyOptions): MinifyOutput;
interface ParseOptions {
// Default is false
strict?: boolean;
// Input file name, default is null
filename?: string;
// Default is null
toplevel?: AST_Toplevel;
}
/**
* The parser creates a custom abstract syntax tree given a piece of JavaScript code.
* Perhaps you should read about the AST first.
*/
function parse(code: string, options?: ParseOptions): AST_Toplevel;
interface BeautifierOptions {
/**
* Start indentation on every line (only when `beautify`)
*/
indent_start?: number;
/**
* Indentation level (only when `beautify`)
*/
indent_level?: number;
/**
* Quote all keys in object literals?
*/
quote_keys?: boolean;
/**
* Add a space after colon signs?
*/
space_colon?: boolean;
/**
* Output ASCII-safe? (encodes Unicode characters as ASCII)
*/
ascii_only?: boolean;
/**
* Escape "</script"?
*/
inline_script?: boolean;
/**
* Informative maximum line width (for beautified output)
*/
width?: number;
/**
* Maximum line length (for non-beautified output)
*/
max_line_len?: number;
/**
* Output IE-safe code?
*/
ie_proof?: boolean;
/**
* Beautify output?
*/
beautify?: boolean;
/**
* Output a source map
*/
source_map?: SourceMapOptions;
/**
* Use brackets every time?
*/
bracketize?: boolean;
/**
* Output comments?
*/
comments?: boolean;
/**
* Use semicolons to separate statements? (otherwise, newlines)
*/
semicolons?: boolean;
}
interface OutputStream {
// Return the output so far as a string
get(): string;
toString(): string;
// Insert one indentation string (usually 4 characters).
// Optionally pass true to indent half the width (I'm using that for case and default lines in switch blocks.
// If beautify is off, this function does nothing.
indent(half?: boolean): void;
// Return the current indentation width (not level; for example if we're in level 2 and indent_level is 4, this method would return 8.
indentation(): number;
// return the width of the current line text minus indentation.
current_width(): number
// Return true if current_width() is bigger than options.width (assuming options.width is non-null, non-zero).
should_break(): boolean;
// If beautification is on, this inserts a newline. Otherwise it does nothing.
newline(): void;
// Include the given string into the output, adjusting current_line, current_col and current_pos accordingly.
print(str: string): void;
// If beautification is on this always includes a space character.
// Otherwise it saves a hint somewhere that a space might be needed at current point.
// The space will go in at the next output but only when absolutely required, for example it will insert the space in return 10 but not in return"stuff".
space(): void;
// Inserts a comma, and calls space() — that is, if beautification is on you'll get a space after the comma.
comma(): void;
// Inserts a colon, and calls space() if options.space_colon is set.
colon(): void;
// Returns the last printed chunk.
last(): string;
// If beautification is on it always inserts a semicolon.
// Otherwise it saves a hint that a semicolon might be needed at current point.
// The semicolon is inserted when the next output comes in, only if required to not break the JS syntax.
semicolon(): void;
// Always inserts a semicolon and clears the hint that a semicolon might be needed.
force_semicolon(): void;
// Encodes any non-ASCII characters in string with JavaScript's conventions (using \uCODE).
to_ascii(str: string): void;
// Prints an identifier. If options.ascii_only is set, non-ASCII chars will be encoded with JavaScript conventions.
print_name(name: string): void;
// Prints a string. It adds quotes automatically.
// It prefers double-quotes, but will actually count any quotes in the string and will use single-quotes if the output proves to be shorter (depending on how many backslashes it has to insert).
// It encodes to ASCII if options.ascii_only is set.
print_string(str: string): void;
// Returns the width of the next indentation level. For example if current level is 2 and options.indent_level is 4, it'll return 12.
next_indent(): number;
// Sets the current indentation to col (column), calls the function and thereafter restores the previous indentation level.
// If beautification is off it simply calls func.
with_indent(col: number, func: Function): void;
// This is used to output blocks in curly brackets.
// It'll print an open bracket at current point, then call newline() and with the next indentation level it calls your func.
// Lastly, it'll print an indented closing bracket. As usual, if beautification is off you'll just get {x} where x is whatever func outputs.
with_block(func: Function): void;
// Adds parens around the output that your function prints.
with_parens(func: Function): void;
// Adds square brackets around the output that your function prints.
with_square(func: Function): void;
// If options.source_map is set, this will generate a source mapping between the given token (which should be an AST_Token-like object) and the current line/col.
// The name is optional; in most cases it will be inferred from the token.
add_mapping(token: AST_Node, name?: string): void;
// Returns the option with the given name.
option(name: string): any;
// Returns the current line in the output (1-based).
line(): number;
// Returns the current column in the output (zero-based).
col(): number;
// Push the given node into an internal stack. This is used to keep track of current node's parent(s).
push_node(node: AST_Node): void;
// Pops the top of the stack and returns it.
pop_node(): AST_Node;
// Returns that internal stack.
stack(): any;
// Returns the n-th parent node (where zero means the direct parent).
parent(n: number): AST_Node;
}
/**
* The code generator is a recursive process of getting back source code from an AST returned by the parser.
* Every AST node has a print method that takes an OutputStream and dumps the code from that node into it.
* The stream object supports a lot of options that control the output.
* You can specify whether you'd like to get human-readable (indented) output, the indentation level, whether you'd like to quote all properties in object literals etc.
*/
function OutputStream(options?: BeautifierOptions): OutputStream;
interface SourceMapOptions {
/**
* The compressed file name
*/
file?: string;
/**
* The root URL to the original sources
*/
root?: string;
/**
* The input source map.
* Useful when you compress code that was generated from some other source (possibly other programming language).
* If you have an input source map, pass it in this argument and UglifyJS will generate a mapping that maps back
* to the original source (as opposed to the compiled code that you are compressing).
*/
orig?: Object | JSON;
}
interface SourceMap {
add(source: string, gen_line: number, gen_col: number, orig_line: number, orig_col: number, name?: string): void;
get(): MOZ_SourceMap.SourceMapGenerator;
toString(): string;
}
/**
* The output stream keeps track of the current line/column in the output and can trivially generate a source mapping to the original code via Mozilla's source-map library.
* To use this functionality, you must load this library (it's automatically require-d by UglifyJS in the NodeJS version, but in a browser you must load it yourself)
* and make it available via the global MOZ_SourceMap variable.
*/
function SourceMap(options?: SourceMapOptions): SourceMap;
interface CompressorOptions {
// Join consecutive statemets with the “comma operator”
sequences?: boolean;
// Optimize property access: a["foo"] → a.foo
properties?: boolean;
// Discard unreachable code
dead_code?: boolean;
// Discard “debugger” statements
drop_debugger?: boolean;
// Some unsafe optimizations (see below)
unsafe?: boolean;
// Optimize if-s and conditional expressions
conditionals?: boolean;
// Optimize comparisons
comparisons?: boolean;
// Evaluate constant expressions
evaluate?: boolean;
// Optimize boolean expressions
booleans?: boolean;
// Optimize loops
loops?: boolean;
// Drop unused variables/functions
unused?: boolean;
// Hoist function declarations
hoist_funs?: boolean;
// Hoist variable declarations
hoist_vars?: boolean;
// Optimize if-s followed by return/continue
if_return?: boolean;
// Join var declarations
join_vars?: boolean;
// Try to cascade `right` into `left` in sequences
cascade?: boolean;
// Drop side-effect-free statements
side_effects?: boolean;
// Warn about potentially dangerous optimizations/code
warnings?: boolean;
// Global definitions
global_defs?: Object;
}
/**
* The compressor is a tree transformer which reduces the code size by applying various optimizations on the AST
*/
function Compressor(options?: CompressorOptions): AST_Toplevel;
// TODO
interface TreeWalker {
}
type visitor = (node: AST_Node, descend: Function) => boolean;
/**
* UglifyJS provides a TreeWalker object and every node has a walk method that given a walker will apply your visitor to each node in the tree.
* Your visitor can return a non-falsy value in order to prevent descending the current node.
*/
function TreeWalker(visitor: visitor): TreeWalker;
// TODO
interface TreeTransformer extends TreeWalker {
}
/**
* The tree transformer is a special case of a tree walker.
* In fact it even inherits from TreeWalker and you can use the same methods, but initialization and visitor protocol are a bit different.
*/
function TreeTransformer(before: visitor, after: visitor): TreeTransformer;
}
export = UglifyJS;
}