Commit 49575265 by 蒋勇

d

parent a0aa16e2
......@@ -58,6 +58,7 @@ class CompanyCtl extends CtlBase {
var rtntmp={
id:cmp.id,
name:cmp.name,
companykey:cmp.companykey,
description:cmp.description,
logoUrl:cmp.logoUrl,
isCurrent:cmp.usercompany.isCurrent,
......
......@@ -77,7 +77,7 @@ class AppDao extends Dao {
async findAndCountAll(qobj, t) {
if(qobj.codepath.indexOf("comapps")>=0){
var rtn={};
var comp=await this.db.models.company.findById(qobj.search.company_id);
var comp=await this.db.models.company.findOne({where:{companykey:qobj.search.companykey}});
var apps=await comp.getApps();
rtn.results={rows:apps,count:apps.length};
rtn.aggresult={};
......
......@@ -137,6 +137,24 @@ module.exports = {
"isleft":true,
},
{
"code": "comorgs",
"label": "组织结构",
"bizCode": "comorgs",
"isMenu": false,
"bizConfig": null,
"path": "",
"isleft":true,
},
{
"code": "comusers",
"label": "公司员工",
"bizCode": "comusers",
"isMenu": false,
"bizConfig": null,
"path": "",
"isleft":true,
},
{
"code": "pmgmyapps",
"label": "我的应用",
"isMenu": true,
......@@ -217,6 +235,8 @@ module.exports = {
"allapps": {"title": "所有APP", "config": null, "path": "/allapps", "comname": "apps"},
"pmgmyapps": {"title": "我的APP", "config": null, "path": "/pmgmyapps", "comname": "apps"},
"comapps": {"title": "公司租用", "config": null, "path": "/comapps", "comname": "apps"},
"comorgs": {"title": "公司组织结构", "config": null, "path": "/comorgs", "comname": "comorgs"},
"comusers": {"title": "公司用户", "config": null, "path": "/comusers", "comname": "users"},
"myappinfo": {"title": "应用信息", "config": null, "path": "/myappinfo", "comname": "myappinfo"},
"cachsearches": { "title": "缓存档案", "config": null, "path": "/cachsearches", "comname": "cachsearches" },
"companyinfo": {"title": "应用信息", "config": null, "path": "/companyinfo", "comname": "companyinfo"},
......
module.exports={
"list":{
columnMetaData:[
]
},
"form":[
{
"title":"基本信息",
"colnum":1,
ctls:[
{"type":"input","label":"编码","prop":"code","placeHolder":"输入组织编码","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"名称","prop":"name","placeHolder":"输入组织名称","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"switch","label":"是否岗位","targetprop":"Roles,isMain","prop":"isPosition","acText":"是","inactText":"否","placeHolder":"","style":""},
{"type":"select","refModel":"auth.role","defaultHide":true,"isMulti":true,"label":"角色","prop":"Roles","labelField":"name","valueField":"id","style":""},
{"type":"switch","label":"是否负责人岗","defaultHide":true,"prop":"isMain","acText":"是","inactText":"否","placeHolder":"","style":""},
{"type":"btn","label":"保存","prop":"btnLogin","placeHolder":"保存","style":{"width":"150px","margin-left":"100px","margin-top":"20px"},"face":"warning"},
]
}
],
"search":[
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-edit","title":"数据授权","type":"default","key":"datapriv","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
{"icon":"el-icon-edit","title":"停用","type":"default","key":"stopUser","isInRow":true,"boolProp":"isEnabled","falseText":"启用"},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
......@@ -35,7 +35,7 @@ module.exports={
],
"edit":[
{"icon":"el-icon-edit","title":"设置为当前","type":"default","key":"setcurrent","isInRow":true},
{"icon":"el-icon-edit","title":"组织结构","type":"default","key":"orgmanage","isInRow":true},
{"icon":"el-icon-edit","title":"组织结构","type":"default","key":"comorgs","isInRow":true},
{"icon":"el-icon-edit","title":"租用列表","type":"default","key":"comapps","isInRow":true},
],
"delete":[
......
module.exports={
"list":{
columnMetaData:[
{"width":"100","label":"昵称","prop":"nickName","isShowTip":true,"isTmpl":false},
{"width":"100","label":"登录账号","prop":"userName","isShowTip":true,"isTmpl":false},
{"width":"100","label":"角色","prop":"Roles","isShowTip":true,"isTmpl":false},
{"width":"80","label":"状态","prop":"isEnabled","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":true},
]
},
"form":[
{
"title":"控制信息",
ctls:[
{"type":"switch","prop":"isAdmin","acText":"是管理员","inactText":"否","placeHolder":"请输入单次使用消耗的宝币数","style":""},
// {"type":"select","refModel":"pmproduct","isMulti":false,"label":"所属产品","prop":"pmproduct_id","labelField":"name","valueField":"id","style":""},
]
},
{
"title":"基本信息",
ctls:[
{"type":"input","label":"账号","prop":"userName","placeHolder":"登录账号","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"昵称","prop":"nickName","placeHolder":"昵称","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"电话","prop":"mobile","placeHolder":"请输入电话","style":"",rules:[ { "validator":"validatex","trigger": 'blur' },{ "required": true, "message": ' ', "trigger": 'blur' },]},
// {"type":"select","refModel":"auth.role","isMulti":true,"label":"角色","prop":"roles","labelField":"name","valueField":"id","style":""},
]
}
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"昵称","prop":"nickName","placeHolder":"请输入昵称","style":""},
]
},
],
"auth":{
"add":[
// {"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
// {"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
// {"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
],
"delete":[
// {"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
// {"icon":"el-icon-edit","title":"停用","type":"default","key":"stopUser","isInRow":true,"boolProp":"isEnabled","falseText":"启用"},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
......@@ -49,7 +49,7 @@
mounted:function(){
var cmpid=this.$router.history.current.query.compid;
this.selCompanyid=cmpid;
this.$refs.cgrid.linkInInitQuery("company_id",cmpid);
this.$refs.cgrid.linkInInitQuery("companykey",cmpid);
},
created:function(){
if(this.codePath.indexOf("myapps")>=0){
......
<gsb-pagecard class="organization">
<div slot="content">
<gsb-tree
ref="orgtree"
@initheight="initheight"
@initdata="initdata"
node_title="组织信息"
bizCode="comorgs"
@loadforminfo="loadforminfo"
:fetchNodeData="fetchtreedata"
children_name="orgs"
label_name="name"
leaf_name="isLeaf"
@remove="remove"
@onsel="onsel"
>
<el-tag>当前选择:{{currentPath?currentPath:"/"}}</el-tag>
<gsb-grid2
ref="userGrid"
bizCode="comusers"
spaceHeight="100"
groupName="auth"
modelName="user"
listMethod="findAndCountAll"
deleteMethod="delete"
initMethod="initNewInstance"
isDataAuto="true"
:headStyle="headStyle"
:colFormatter="onColFormater"
:isSingleSelect="isSingleSelect"
@rowclick="onRowClick"
:validateformmethod="validateformmethod"
:beforesave="beforesave">
</gsb-grid2>
<gsb-form ref="orgform" @btnclick="saveclick" style="width:500px" @onswitchchange="switchchange" slot="treeform" :metaData="formMetaData"></gsb-form>
</gsb-tree>
<el-dialog
title="岗位变更"
:visible.sync="positonChange"
width="350px"
center>
<gsb-select cssStyle="width:300px" refModel="auth.org" modelName="org" v-model="orgidchageto" labelField="orgpath" :refwhere2="refwhereorg" valueField="id"></gsb-select>
<span slot="footer" class="dialog-footer">
<el-button @click="positonChange = false">取 消</el-button>
<el-button type="primary" @click="changeok">确 定</el-button>
</span>
</el-dialog>
</div>
</gsb-pagecard>
\ No newline at end of file
......@@ -41,8 +41,12 @@
}
}
if(key="comapps"){
this.$router.push({path:"/comapps",query:{"compid":row.id}});
if(key=="comapps"){
this.$router.push({path:"/comapps",query:{"compid":row.companykey}});
}
if(key=="comorgs"){
this.$router.push({path:"/comorgs",query:{"compid":row.id}});
}
},
onColFormater(row,column,cellvalue,index){
......
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
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
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (http://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Mon, 18 Nov 2019 20:48:11 GMT
* Dependencies: none
* Global values: `Buffer`, `NodeJS`, `Symbol`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout`
# Credits
These definitions were written by Microsoft TypeScript (https://github.com/Microsoft), DefinitelyTyped (https://github.com/DefinitelyTyped), Alberto Schiabel (https://github.com/jkomyno), Alexander T. (https://github.com/a-tarasyuk), Alvis HT Tang (https://github.com/alvis), Andrew Makarov (https://github.com/r3nya), Benjamin Toueg (https://github.com/btoueg), Bruno Scheufler (https://github.com/brunoscheufler), Chigozirim C. (https://github.com/smac89), Christian Vaagland Tellnes (https://github.com/tellnes), David Junger (https://github.com/touffy), Deividas Bakanas (https://github.com/DeividasBakanas), Eugene Y. Q. Shen (https://github.com/eyqs), Flarna (https://github.com/Flarna), Hannes Magnusson (https://github.com/Hannes-Magnusson-CK), Hoàng Văn Khải (https://github.com/KSXGitHub), Huw (https://github.com/hoo29), Kelvin Jin (https://github.com/kjin), Klaus Meinhardt (https://github.com/ajafff), Lishude (https://github.com/islishude), Mariusz Wiktorczyk (https://github.com/mwiktorczyk), Mohsen Azimi (https://github.com/mohsen1), Nicolas Even (https://github.com/n-e), Nicolas Voigt (https://github.com/octo-sniffle), Nikita Galkin (https://github.com/galkin), Parambir Singh (https://github.com/parambirs), Sebastian Silbermann (https://github.com/eps1lon), Simon Schick (https://github.com/SimonSchick), Thomas den Hollander (https://github.com/ThomasdenH), Wilco Bakker (https://github.com/WilcoBakker), wwwy3y3 (https://github.com/wwwy3y3), Zane Hannan AU (https://github.com/ZaneHannanAU), Samuel Ainsworth (https://github.com/samuela), Kyle Uehlein (https://github.com/kuehlein), Jordi Oliveras Rovira (https://github.com/j-oliveras), Thanik Bhongbhibhat (https://github.com/bhongy), Marcin Kopacz (https://github.com/chyzwar), Trivikram Kamat (https://github.com/trivikr), and Minh Son Nguyen (https://github.com/nguymin4).
declare module "assert" {
function internal(value: any, message?: string | Error): void;
namespace internal {
class AssertionError implements Error {
name: string;
message: string;
actual: any;
expected: any;
operator: string;
generatedMessage: boolean;
code: 'ERR_ASSERTION';
constructor(options?: {
message?: string; actual?: any; expected?: any;
operator?: string; stackStartFn?: Function
});
}
function fail(message?: string | Error): never;
/** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */
function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never;
function ok(value: any, message?: string | Error): void;
function equal(actual: any, expected: any, message?: string | Error): void;
function notEqual(actual: any, expected: any, message?: string | Error): void;
function deepEqual(actual: any, expected: any, message?: string | Error): void;
function notDeepEqual(actual: any, expected: any, message?: string | Error): void;
function strictEqual(actual: any, expected: any, message?: string | Error): void;
function notStrictEqual(actual: any, expected: any, message?: string | Error): void;
function deepStrictEqual(actual: any, expected: any, message?: string | Error): void;
function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void;
function throws(block: () => any, message?: string | Error): void;
function throws(block: () => any, error: RegExp | Function | Object | Error, message?: string | Error): void;
function doesNotThrow(block: () => any, message?: string | Error): void;
function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void;
function ifError(value: any): void;
function rejects(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
function rejects(block: (() => Promise<any>) | Promise<any>, error: RegExp | Function | Object | Error, message?: string | Error): Promise<void>;
function doesNotReject(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
function doesNotReject(block: (() => Promise<any>) | Promise<any>, error: RegExp | Function, message?: string | Error): Promise<void>;
const strict: typeof internal;
}
export = internal;
}
/**
* Async Hooks module: https://nodejs.org/api/async_hooks.html
*/
declare module "async_hooks" {
/**
* Returns the asyncId of the current execution context.
*/
function executionAsyncId(): number;
/**
* Returns the ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called when a promise has resolve() called. This may not be in the same execution id
* as the promise itself.
* @param asyncId the unique id for the promise that was resolve()d.
*/
promiseResolve?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
interface AsyncHook {
/**
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
*/
enable(): this;
/**
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
*/
disable(): this;
}
/**
* Registers functions to be called for different lifetime events of each async operation.
* @param options the callbacks to register
* @return an AsyncHooks instance used for disabling and enabling hooks
*/
function createHook(options: HookCallbacks): AsyncHook;
interface AsyncResourceOptions {
/**
* The ID of the execution context that created this async event.
* Default: `executionAsyncId()`
*/
triggerAsyncId?: number;
/**
* Disables automatic `emitDestroy` when the object is garbage collected.
* This usually does not need to be set (even if `emitDestroy` is called
* manually), unless the resource's `asyncId` is retrieved and the
* sensitive API's `emitDestroy` is called with it.
* Default: `false`
*/
requireManualDestroy?: boolean;
}
/**
* The class AsyncResource was designed to be extended by the embedder's async resources.
* Using this users can easily trigger the lifetime events of their own resources.
*/
class AsyncResource {
/**
* AsyncResource() is meant to be extended. Instantiating a
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* async_hook.executionAsyncId() is used.
* @param type The type of async event.
* @param triggerAsyncId The ID of the execution context that created
* this async event (default: `executionAsyncId()`), or an
* AsyncResourceOptions object (since 9.3)
*/
constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions);
/**
* Call the provided function with the provided arguments in the
* execution context of the async resource. This will establish the
* context, trigger the AsyncHooks before callbacks, call the function,
* trigger the AsyncHooks after callbacks, and then restore the original
* execution context.
* @param fn The function to call in the execution context of this
* async resource.
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result;
/**
* Call AsyncHooks destroy callbacks.
*/
emitDestroy(): void;
/**
* @return the unique ID assigned to this AsyncResource instance.
*/
asyncId(): number;
/**
* @return the trigger ID for this AsyncResource instance.
*/
triggerAsyncId(): number;
}
}
// base definnitions for all NodeJS modules that are not specific to any version of TypeScript
/// <reference path="globals.d.ts" />
/// <reference path="assert.d.ts" />
/// <reference path="async_hooks.d.ts" />
/// <reference path="buffer.d.ts" />
/// <reference path="child_process.d.ts" />
/// <reference path="cluster.d.ts" />
/// <reference path="console.d.ts" />
/// <reference path="constants.d.ts" />
/// <reference path="crypto.d.ts" />
/// <reference path="dgram.d.ts" />
/// <reference path="dns.d.ts" />
/// <reference path="domain.d.ts" />
/// <reference path="events.d.ts" />
/// <reference path="fs.d.ts" />
/// <reference path="http.d.ts" />
/// <reference path="http2.d.ts" />
/// <reference path="https.d.ts" />
/// <reference path="inspector.d.ts" />
/// <reference path="module.d.ts" />
/// <reference path="net.d.ts" />
/// <reference path="os.d.ts" />
/// <reference path="path.d.ts" />
/// <reference path="perf_hooks.d.ts" />
/// <reference path="process.d.ts" />
/// <reference path="punycode.d.ts" />
/// <reference path="querystring.d.ts" />
/// <reference path="readline.d.ts" />
/// <reference path="repl.d.ts" />
/// <reference path="stream.d.ts" />
/// <reference path="string_decoder.d.ts" />
/// <reference path="timers.d.ts" />
/// <reference path="tls.d.ts" />
/// <reference path="trace_events.d.ts" />
/// <reference path="tty.d.ts" />
/// <reference path="url.d.ts" />
/// <reference path="util.d.ts" />
/// <reference path="v8.d.ts" />
/// <reference path="vm.d.ts" />
/// <reference path="worker_threads.d.ts" />
/// <reference path="zlib.d.ts" />
declare module "buffer" {
export const INSPECT_MAX_BYTES: number;
export const kMaxLength: number;
export const kStringMaxLength: number;
export const constants: {
MAX_LENGTH: number;
MAX_STRING_LENGTH: number;
};
const BuffType: typeof Buffer;
export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary";
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer;
export const SlowBuffer: {
/** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */
new(size: number): Buffer;
prototype: Buffer;
};
export { BuffType as Buffer };
}
declare module "dgram" {
import { AddressInfo } from "net";
import * as dns from "dns";
import * as events from "events";
interface RemoteInfo {
address: string;
family: 'IPv4' | 'IPv6';
port: number;
size: number;
}
interface BindOptions {
port: number;
address?: string;
exclusive?: boolean;
}
type SocketType = "udp4" | "udp6";
interface SocketOptions {
type: SocketType;
reuseAddr?: boolean;
/**
* @default false
*/
ipv6Only?: boolean;
recvBufferSize?: number;
sendBufferSize?: number;
lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void;
}
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
class Socket extends events.EventEmitter {
send(msg: string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
bind(port?: number, address?: string, callback?: () => void): void;
bind(port?: number, callback?: () => void): void;
bind(callback?: () => void): void;
bind(options: BindOptions, callback?: () => void): void;
close(callback?: () => void): void;
address(): AddressInfo | string;
setBroadcast(flag: boolean): void;
setTTL(ttl: number): void;
setMulticastTTL(ttl: number): void;
setMulticastInterface(multicastInterface: string): void;
setMulticastLoopback(flag: boolean): void;
addMembership(multicastAddress: string, multicastInterface?: string): void;
dropMembership(multicastAddress: string, multicastInterface?: string): void;
ref(): this;
unref(): this;
setRecvBufferSize(size: number): void;
setSendBufferSize(size: number): void;
getRecvBufferSize(): number;
getSendBufferSize(): number;
/**
* events.EventEmitter
* 1. close
* 2. error
* 3. listening
* 4. message
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this;
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean;
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this;
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this;
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this;
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
}
}
declare module "domain" {
import * as events from "events";
class Domain extends events.EventEmitter implements NodeJS.Domain {
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
add(emitter: events.EventEmitter | NodeJS.Timer): void;
remove(emitter: events.EventEmitter | NodeJS.Timer): void;
bind<T extends Function>(cb: T): T;
intercept<T extends Function>(cb: T): T;
members: Array<events.EventEmitter | NodeJS.Timer>;
enter(): void;
exit(): void;
}
function create(): Domain;
}
declare module "events" {
class internal extends NodeJS.EventEmitter { }
interface NodeEventTarget {
once(event: string | symbol, listener: (...args: any[]) => void): this;
}
interface DOMEventTarget {
addEventListener(event: string, listener: (...args: any[]) => void, opts?: { once: boolean }): any;
}
namespace internal {
function once(emitter: NodeEventTarget, event: string | symbol): Promise<any[]>;
function once(emitter: DOMEventTarget, event: string): Promise<any[]>;
class EventEmitter extends internal {
/** @deprecated since v4.0.0 */
static listenerCount(emitter: EventEmitter, event: string | symbol): number;
static defaultMaxListeners: number;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
removeAllListeners(event?: string | symbol): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: string | symbol): Function[];
rawListeners(event: string | symbol): Function[];
emit(event: string | symbol, ...args: any[]): boolean;
eventNames(): Array<string | symbol>;
listenerCount(type: string | symbol): number;
}
}
export = internal;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
declare module "https" {
import * as tls from "tls";
import * as events from "events";
import * as http from "http";
import { URL } from "url";
type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions;
type RequestOptions = http.RequestOptions & tls.SecureContextOptions & {
rejectUnauthorized?: boolean; // Defaults to true
servername?: string; // SNI TLS Extension
};
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
rejectUnauthorized?: boolean;
maxCachedSessions?: number;
}
class Agent extends http.Agent {
constructor(options?: AgentOptions);
options: AgentOptions;
}
class Server extends tls.Server {
constructor(requestListener?: http.RequestListener);
constructor(options: ServerOptions, requestListener?: http.RequestListener);
setTimeout(callback: () => void): this;
setTimeout(msecs?: number, callback?: () => void): this;
/**
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
* @default 2000
* {@link https://nodejs.org/api/http.html#http_server_maxheaderscount}
*/
maxHeadersCount: number | null;
timeout: number;
/**
* Limit the amount of time the parser will wait to receive the complete HTTP headers.
* @default 40000
* {@link https://nodejs.org/api/http.html#http_server_headerstimeout}
*/
headersTimeout: number;
keepAliveTimeout: number;
}
function createServer(requestListener?: http.RequestListener): Server;
function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server;
function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
let globalAgent: Agent;
}
// Type definitions for non-npm package Node.js 12.12
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
// DefinitelyTyped <https://github.com/DefinitelyTyped>
// Alberto Schiabel <https://github.com/jkomyno>
// Alexander T. <https://github.com/a-tarasyuk>
// Alvis HT Tang <https://github.com/alvis>
// Andrew Makarov <https://github.com/r3nya>
// Benjamin Toueg <https://github.com/btoueg>
// Bruno Scheufler <https://github.com/brunoscheufler>
// Chigozirim C. <https://github.com/smac89>
// Christian Vaagland Tellnes <https://github.com/tellnes>
// David Junger <https://github.com/touffy>
// Deividas Bakanas <https://github.com/DeividasBakanas>
// Eugene Y. Q. Shen <https://github.com/eyqs>
// Flarna <https://github.com/Flarna>
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
// Hoàng Văn Khải <https://github.com/KSXGitHub>
// Huw <https://github.com/hoo29>
// Kelvin Jin <https://github.com/kjin>
// Klaus Meinhardt <https://github.com/ajafff>
// Lishude <https://github.com/islishude>
// Mariusz Wiktorczyk <https://github.com/mwiktorczyk>
// Mohsen Azimi <https://github.com/mohsen1>
// Nicolas Even <https://github.com/n-e>
// Nicolas Voigt <https://github.com/octo-sniffle>
// Nikita Galkin <https://github.com/galkin>
// Parambir Singh <https://github.com/parambirs>
// Sebastian Silbermann <https://github.com/eps1lon>
// Simon Schick <https://github.com/SimonSchick>
// Thomas den Hollander <https://github.com/ThomasdenH>
// Wilco Bakker <https://github.com/WilcoBakker>
// wwwy3y3 <https://github.com/wwwy3y3>
// Zane Hannan AU <https://github.com/ZaneHannanAU>
// Samuel Ainsworth <https://github.com/samuela>
// Kyle Uehlein <https://github.com/kuehlein>
// Jordi Oliveras Rovira <https://github.com/j-oliveras>
// Thanik Bhongbhibhat <https://github.com/bhongy>
// Marcin Kopacz <https://github.com/chyzwar>
// Trivikram Kamat <https://github.com/trivikr>
// Minh Son Nguyen <https://github.com/nguymin4>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// NOTE: These definitions support NodeJS and TypeScript 3.2.
// NOTE: TypeScript version-specific augmentations can be found in the following paths:
// - ~/base.d.ts - Shared definitions common to all TypeScript versions
// - ~/index.d.ts - Definitions specific to TypeScript 2.1
// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2
// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides
// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions
// prior to TypeScript 3.2, so the older definitions will be found here.
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
/// <reference path="base.d.ts" />
// TypeScript 2.1-specific augmentations:
// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`)
// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files
// just to ensure the names are known and node typings can be sued without importing these libs.
// if someone really needs these types the libs need to be added via --lib or in tsconfig.json
interface MapConstructor { }
interface WeakMapConstructor { }
interface SetConstructor { }
interface WeakSetConstructor { }
interface Set<T> {}
interface Map<K, V> {}
interface ReadonlySet<T> {}
interface Iterable<T> { }
interface IteratorResult<T> { }
interface AsyncIterable<T> { }
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
}
interface IterableIterator<T> { }
interface AsyncIterableIterator<T> {}
interface SymbolConstructor {
readonly iterator: symbol;
readonly asyncIterator: symbol;
}
declare var Symbol: SymbolConstructor;
// even this is just a forward declaration some properties are added otherwise
// it would be allowed to pass anything to e.g. Buffer.from()
interface SharedArrayBuffer {
readonly byteLength: number;
slice(begin?: number, end?: number): SharedArrayBuffer;
}
declare module "util" {
namespace inspect {
const custom: symbol;
}
namespace promisify {
const custom: symbol;
}
namespace types {
function isBigInt64Array(value: any): boolean;
function isBigUint64Array(value: any): boolean;
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
declare module "module" {
export = NodeJS.Module;
}
declare module "os" {
interface CpuInfo {
model: string;
speed: number;
times: {
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
};
}
interface NetworkInterfaceBase {
address: string;
netmask: string;
mac: string;
internal: boolean;
cidr: string | null;
}
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase {
family: "IPv4";
}
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase {
family: "IPv6";
scopeid: number;
}
interface UserInfo<T> {
username: T;
uid: number;
gid: number;
shell: T;
homedir: T;
}
type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6;
function hostname(): string;
function loadavg(): number[];
function uptime(): number;
function freemem(): number;
function totalmem(): number;
function cpus(): CpuInfo[];
function type(): string;
function release(): string;
function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] };
function homedir(): string;
function userInfo(options: { encoding: 'buffer' }): UserInfo<Buffer>;
function userInfo(options?: { encoding: string }): UserInfo<string>;
const constants: {
UV_UDP_REUSEADDR: number;
// signals: { [key in NodeJS.Signals]: number; }; @todo: change after migration to typescript 2.1
signals: {
SIGHUP: number;
SIGINT: number;
SIGQUIT: number;
SIGILL: number;
SIGTRAP: number;
SIGABRT: number;
SIGIOT: number;
SIGBUS: number;
SIGFPE: number;
SIGKILL: number;
SIGUSR1: number;
SIGSEGV: number;
SIGUSR2: number;
SIGPIPE: number;
SIGALRM: number;
SIGTERM: number;
SIGCHLD: number;
SIGSTKFLT: number;
SIGCONT: number;
SIGSTOP: number;
SIGTSTP: number;
SIGBREAK: number;
SIGTTIN: number;
SIGTTOU: number;
SIGURG: number;
SIGXCPU: number;
SIGXFSZ: number;
SIGVTALRM: number;
SIGPROF: number;
SIGWINCH: number;
SIGIO: number;
SIGPOLL: number;
SIGLOST: number;
SIGPWR: number;
SIGINFO: number;
SIGSYS: number;
SIGUNUSED: number;
};
errno: {
E2BIG: number;
EACCES: number;
EADDRINUSE: number;
EADDRNOTAVAIL: number;
EAFNOSUPPORT: number;
EAGAIN: number;
EALREADY: number;
EBADF: number;
EBADMSG: number;
EBUSY: number;
ECANCELED: number;
ECHILD: number;
ECONNABORTED: number;
ECONNREFUSED: number;
ECONNRESET: number;
EDEADLK: number;
EDESTADDRREQ: number;
EDOM: number;
EDQUOT: number;
EEXIST: number;
EFAULT: number;
EFBIG: number;
EHOSTUNREACH: number;
EIDRM: number;
EILSEQ: number;
EINPROGRESS: number;
EINTR: number;
EINVAL: number;
EIO: number;
EISCONN: number;
EISDIR: number;
ELOOP: number;
EMFILE: number;
EMLINK: number;
EMSGSIZE: number;
EMULTIHOP: number;
ENAMETOOLONG: number;
ENETDOWN: number;
ENETRESET: number;
ENETUNREACH: number;
ENFILE: number;
ENOBUFS: number;
ENODATA: number;
ENODEV: number;
ENOENT: number;
ENOEXEC: number;
ENOLCK: number;
ENOLINK: number;
ENOMEM: number;
ENOMSG: number;
ENOPROTOOPT: number;
ENOSPC: number;
ENOSR: number;
ENOSTR: number;
ENOSYS: number;
ENOTCONN: number;
ENOTDIR: number;
ENOTEMPTY: number;
ENOTSOCK: number;
ENOTSUP: number;
ENOTTY: number;
ENXIO: number;
EOPNOTSUPP: number;
EOVERFLOW: number;
EPERM: number;
EPIPE: number;
EPROTO: number;
EPROTONOSUPPORT: number;
EPROTOTYPE: number;
ERANGE: number;
EROFS: number;
ESPIPE: number;
ESRCH: number;
ESTALE: number;
ETIME: number;
ETIMEDOUT: number;
ETXTBSY: number;
EWOULDBLOCK: number;
EXDEV: number;
WSAEINTR: number;
WSAEBADF: number;
WSAEACCES: number;
WSAEFAULT: number;
WSAEINVAL: number;
WSAEMFILE: number;
WSAEWOULDBLOCK: number;
WSAEINPROGRESS: number;
WSAEALREADY: number;
WSAENOTSOCK: number;
WSAEDESTADDRREQ: number;
WSAEMSGSIZE: number;
WSAEPROTOTYPE: number;
WSAENOPROTOOPT: number;
WSAEPROTONOSUPPORT: number;
WSAESOCKTNOSUPPORT: number;
WSAEOPNOTSUPP: number;
WSAEPFNOSUPPORT: number;
WSAEAFNOSUPPORT: number;
WSAEADDRINUSE: number;
WSAEADDRNOTAVAIL: number;
WSAENETDOWN: number;
WSAENETUNREACH: number;
WSAENETRESET: number;
WSAECONNABORTED: number;
WSAECONNRESET: number;
WSAENOBUFS: number;
WSAEISCONN: number;
WSAENOTCONN: number;
WSAESHUTDOWN: number;
WSAETOOMANYREFS: number;
WSAETIMEDOUT: number;
WSAECONNREFUSED: number;
WSAELOOP: number;
WSAENAMETOOLONG: number;
WSAEHOSTDOWN: number;
WSAEHOSTUNREACH: number;
WSAENOTEMPTY: number;
WSAEPROCLIM: number;
WSAEUSERS: number;
WSAEDQUOT: number;
WSAESTALE: number;
WSAEREMOTE: number;
WSASYSNOTREADY: number;
WSAVERNOTSUPPORTED: number;
WSANOTINITIALISED: number;
WSAEDISCON: number;
WSAENOMORE: number;
WSAECANCELLED: number;
WSAEINVALIDPROCTABLE: number;
WSAEINVALIDPROVIDER: number;
WSAEPROVIDERFAILEDINIT: number;
WSASYSCALLFAILURE: number;
WSASERVICE_NOT_FOUND: number;
WSATYPE_NOT_FOUND: number;
WSA_E_NO_MORE: number;
WSA_E_CANCELLED: number;
WSAEREFUSED: number;
};
priority: {
PRIORITY_LOW: number;
PRIORITY_BELOW_NORMAL: number;
PRIORITY_NORMAL: number;
PRIORITY_ABOVE_NORMAL: number;
PRIORITY_HIGH: number;
PRIORITY_HIGHEST: number;
}
};
function arch(): string;
function platform(): NodeJS.Platform;
function tmpdir(): string;
const EOL: string;
function endianness(): "BE" | "LE";
/**
* Gets the priority of a process.
* Defaults to current process.
*/
function getPriority(pid?: number): number;
/**
* Sets the priority of the current process.
* @param priority Must be in range of -20 to 19
*/
function setPriority(priority: number): void;
/**
* Sets the priority of the process specified process.
* @param priority Must be in range of -20 to 19
*/
function setPriority(pid: number, priority: number): void;
}
{
"name": "@types/node",
"version": "12.12.9",
"description": "TypeScript definitions for Node.js",
"license": "MIT",
"contributors": [
{
"name": "Microsoft TypeScript",
"url": "https://github.com/Microsoft",
"githubUsername": "Microsoft"
},
{
"name": "DefinitelyTyped",
"url": "https://github.com/DefinitelyTyped",
"githubUsername": "DefinitelyTyped"
},
{
"name": "Alberto Schiabel",
"url": "https://github.com/jkomyno",
"githubUsername": "jkomyno"
},
{
"name": "Alexander T.",
"url": "https://github.com/a-tarasyuk",
"githubUsername": "a-tarasyuk"
},
{
"name": "Alvis HT Tang",
"url": "https://github.com/alvis",
"githubUsername": "alvis"
},
{
"name": "Andrew Makarov",
"url": "https://github.com/r3nya",
"githubUsername": "r3nya"
},
{
"name": "Benjamin Toueg",
"url": "https://github.com/btoueg",
"githubUsername": "btoueg"
},
{
"name": "Bruno Scheufler",
"url": "https://github.com/brunoscheufler",
"githubUsername": "brunoscheufler"
},
{
"name": "Chigozirim C.",
"url": "https://github.com/smac89",
"githubUsername": "smac89"
},
{
"name": "Christian Vaagland Tellnes",
"url": "https://github.com/tellnes",
"githubUsername": "tellnes"
},
{
"name": "David Junger",
"url": "https://github.com/touffy",
"githubUsername": "touffy"
},
{
"name": "Deividas Bakanas",
"url": "https://github.com/DeividasBakanas",
"githubUsername": "DeividasBakanas"
},
{
"name": "Eugene Y. Q. Shen",
"url": "https://github.com/eyqs",
"githubUsername": "eyqs"
},
{
"name": "Flarna",
"url": "https://github.com/Flarna",
"githubUsername": "Flarna"
},
{
"name": "Hannes Magnusson",
"url": "https://github.com/Hannes-Magnusson-CK",
"githubUsername": "Hannes-Magnusson-CK"
},
{
"name": "Hoàng Văn Khải",
"url": "https://github.com/KSXGitHub",
"githubUsername": "KSXGitHub"
},
{
"name": "Huw",
"url": "https://github.com/hoo29",
"githubUsername": "hoo29"
},
{
"name": "Kelvin Jin",
"url": "https://github.com/kjin",
"githubUsername": "kjin"
},
{
"name": "Klaus Meinhardt",
"url": "https://github.com/ajafff",
"githubUsername": "ajafff"
},
{
"name": "Lishude",
"url": "https://github.com/islishude",
"githubUsername": "islishude"
},
{
"name": "Mariusz Wiktorczyk",
"url": "https://github.com/mwiktorczyk",
"githubUsername": "mwiktorczyk"
},
{
"name": "Mohsen Azimi",
"url": "https://github.com/mohsen1",
"githubUsername": "mohsen1"
},
{
"name": "Nicolas Even",
"url": "https://github.com/n-e",
"githubUsername": "n-e"
},
{
"name": "Nicolas Voigt",
"url": "https://github.com/octo-sniffle",
"githubUsername": "octo-sniffle"
},
{
"name": "Nikita Galkin",
"url": "https://github.com/galkin",
"githubUsername": "galkin"
},
{
"name": "Parambir Singh",
"url": "https://github.com/parambirs",
"githubUsername": "parambirs"
},
{
"name": "Sebastian Silbermann",
"url": "https://github.com/eps1lon",
"githubUsername": "eps1lon"
},
{
"name": "Simon Schick",
"url": "https://github.com/SimonSchick",
"githubUsername": "SimonSchick"
},
{
"name": "Thomas den Hollander",
"url": "https://github.com/ThomasdenH",
"githubUsername": "ThomasdenH"
},
{
"name": "Wilco Bakker",
"url": "https://github.com/WilcoBakker",
"githubUsername": "WilcoBakker"
},
{
"name": "wwwy3y3",
"url": "https://github.com/wwwy3y3",
"githubUsername": "wwwy3y3"
},
{
"name": "Zane Hannan AU",
"url": "https://github.com/ZaneHannanAU",
"githubUsername": "ZaneHannanAU"
},
{
"name": "Samuel Ainsworth",
"url": "https://github.com/samuela",
"githubUsername": "samuela"
},
{
"name": "Kyle Uehlein",
"url": "https://github.com/kuehlein",
"githubUsername": "kuehlein"
},
{
"name": "Jordi Oliveras Rovira",
"url": "https://github.com/j-oliveras",
"githubUsername": "j-oliveras"
},
{
"name": "Thanik Bhongbhibhat",
"url": "https://github.com/bhongy",
"githubUsername": "bhongy"
},
{
"name": "Marcin Kopacz",
"url": "https://github.com/chyzwar",
"githubUsername": "chyzwar"
},
{
"name": "Trivikram Kamat",
"url": "https://github.com/trivikr",
"githubUsername": "trivikr"
},
{
"name": "Minh Son Nguyen",
"url": "https://github.com/nguymin4",
"githubUsername": "nguymin4"
}
],
"main": "",
"types": "index.d.ts",
"typesVersions": {
">=3.2.0-0": {
"*": [
"ts3.2/*"
]
}
},
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/node"
},
"scripts": {},
"dependencies": {},
"typesPublisherContentHash": "9c94a4ee4d32b9ff9fae5de2eb33fa954fbb96c5c84e749d38ed8560fdaeb9a0",
"typeScriptVersion": "2.8",
"__npminstall_done": "Tue Nov 19 2019 19:23:44 GMT+0800 (CST)",
"_from": "@types/node@12.12.9",
"_resolved": "https://registry.npm.taobao.org/@types/node/download/@types/node-12.12.9.tgz"
}
\ No newline at end of file
declare module "path" {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
*/
root: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base: string;
/**
* The file extension (if any) such as '.html'
*/
ext: string;
/**
* The file name without extension (if any) such as 'index'
*/
name: string;
}
interface FormatInputPathObject {
/**
* The root of the path such as '/' or 'c:\'
*/
root?: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir?: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base?: string;
/**
* The file extension (if any) such as '.html'
*/
ext?: string;
/**
* The file name without extension (if any) such as 'index'
*/
name?: string;
}
/**
* Normalize a string path, reducing '..' and '.' parts.
* When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
*
* @param p string path to normalize.
*/
function normalize(p: string): string;
/**
* Join all arguments together and normalize the resulting path.
* Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
*
* @param paths paths to join.
*/
function join(...paths: string[]): string;
/**
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
*
* Starting from leftmost {from} parameter, resolves {to} to an absolute path.
*
* If {to} isn't already absolute, {from} arguments are prepended in right to left order,
* until an absolute path is found. If after using all {from} paths still no absolute path is found,
* the current working directory is used as well. The resulting path is normalized,
* and trailing slashes are removed unless the path gets resolved to the root directory.
*
* @param pathSegments string paths to join. Non-string arguments are ignored.
*/
function resolve(...pathSegments: string[]): string;
/**
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
*
* @param path path to test.
*/
function isAbsolute(path: string): boolean;
/**
* Solve the relative path from {from} to {to}.
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
*/
function relative(from: string, to: string): string;
/**
* Return the directory name of a path. Similar to the Unix dirname command.
*
* @param p the path to evaluate.
*/
function dirname(p: string): string;
/**
* Return the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
*
* @param p the path to evaluate.
* @param ext optionally, an extension to remove from the result.
*/
function basename(p: string, ext?: string): string;
/**
* Return the extension of the path, from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
*
* @param p the path to evaluate.
*/
function extname(p: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
const sep: '\\' | '/';
/**
* The platform-specific file delimiter. ';' or ':'.
*/
const delimiter: ';' | ':';
/**
* Returns an object from a path string - the opposite of format().
*
* @param pathString path to evaluate.
*/
function parse(pathString: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathString path to evaluate.
*/
function format(pathObject: FormatInputPathObject): string;
namespace posix {
function normalize(p: string): string;
function join(...paths: string[]): string;
function resolve(...pathSegments: string[]): string;
function isAbsolute(p: string): boolean;
function relative(from: string, to: string): string;
function dirname(p: string): string;
function basename(p: string, ext?: string): string;
function extname(p: string): string;
const sep: string;
const delimiter: string;
function parse(p: string): ParsedPath;
function format(pP: FormatInputPathObject): string;
}
namespace win32 {
function normalize(p: string): string;
function join(...paths: string[]): string;
function resolve(...pathSegments: string[]): string;
function isAbsolute(p: string): boolean;
function relative(from: string, to: string): string;
function dirname(p: string): string;
function basename(p: string, ext?: string): string;
function extname(p: string): string;
const sep: string;
const delimiter: string;
function parse(p: string): ParsedPath;
function format(pP: FormatInputPathObject): string;
}
}
declare module "process" {
import * as tty from "tty";
global {
namespace NodeJS {
// this namespace merge is here because these are specifically used
// as the type for process.stdin, process.stdout, and process.stderr.
// they can't live in tty.d.ts because we need to disambiguate the imported name.
interface ReadStream extends tty.ReadStream {}
interface WriteStream extends tty.WriteStream {}
}
}
export = process;
}
declare module "punycode" {
function decode(string: string): string;
function encode(string: string): string;
function toUnicode(domain: string): string;
function toASCII(domain: string): string;
const ucs2: ucs2;
interface ucs2 {
decode(string: string): number[];
encode(codePoints: number[]): string;
}
const version: string;
}
declare module "querystring" {
interface StringifyOptions {
encodeURIComponent?: (str: string) => string;
}
interface ParseOptions {
maxKeys?: number;
decodeURIComponent?: (str: string) => string;
}
interface ParsedUrlQuery { [key: string]: string | string[]; }
interface ParsedUrlQueryInput {
[key: string]: NodeJS.PoorMansUnknown;
}
function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string;
function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery;
/**
* The querystring.encode() function is an alias for querystring.stringify().
*/
const encode: typeof stringify;
/**
* The querystring.decode() function is an alias for querystring.parse().
*/
const decode: typeof parse;
function escape(str: string): string;
function unescape(str: string): string;
}
declare module "readline" {
import * as events from "events";
import * as stream from "stream";
interface Key {
sequence?: string;
name?: string;
ctrl?: boolean;
meta?: boolean;
shift?: boolean;
}
class Interface extends events.EventEmitter {
readonly terminal: boolean;
/**
* NOTE: According to the documentation:
*
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface
*/
protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean);
/**
* NOTE: According to the documentation:
*
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface
*/
protected constructor(options: ReadLineOptions);
setPrompt(prompt: string): void;
prompt(preserveCursor?: boolean): void;
question(query: string, callback: (answer: string) => void): void;
pause(): this;
resume(): this;
close(): void;
write(data: string | Buffer, key?: Key): void;
/**
* events.EventEmitter
* 1. close
* 2. line
* 3. pause
* 4. resume
* 5. SIGCONT
* 6. SIGINT
* 7. SIGTSTP
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "line", listener: (input: string) => void): this;
addListener(event: "pause", listener: () => void): this;
addListener(event: "resume", listener: () => void): this;
addListener(event: "SIGCONT", listener: () => void): this;
addListener(event: "SIGINT", listener: () => void): this;
addListener(event: "SIGTSTP", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "line", input: string): boolean;
emit(event: "pause"): boolean;
emit(event: "resume"): boolean;
emit(event: "SIGCONT"): boolean;
emit(event: "SIGINT"): boolean;
emit(event: "SIGTSTP"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "line", listener: (input: string) => void): this;
on(event: "pause", listener: () => void): this;
on(event: "resume", listener: () => void): this;
on(event: "SIGCONT", listener: () => void): this;
on(event: "SIGINT", listener: () => void): this;
on(event: "SIGTSTP", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "line", listener: (input: string) => void): this;
once(event: "pause", listener: () => void): this;
once(event: "resume", listener: () => void): this;
once(event: "SIGCONT", listener: () => void): this;
once(event: "SIGINT", listener: () => void): this;
once(event: "SIGTSTP", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "line", listener: (input: string) => void): this;
prependListener(event: "pause", listener: () => void): this;
prependListener(event: "resume", listener: () => void): this;
prependListener(event: "SIGCONT", listener: () => void): this;
prependListener(event: "SIGINT", listener: () => void): this;
prependListener(event: "SIGTSTP", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "line", listener: (input: string) => void): this;
prependOnceListener(event: "pause", listener: () => void): this;
prependOnceListener(event: "resume", listener: () => void): this;
prependOnceListener(event: "SIGCONT", listener: () => void): this;
prependOnceListener(event: "SIGINT", listener: () => void): this;
prependOnceListener(event: "SIGTSTP", listener: () => void): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string>;
}
type ReadLine = Interface; // type forwarded for backwards compatiblity
type Completer = (line: string) => CompleterResult;
type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => any;
type CompleterResult = [string[], string];
interface ReadLineOptions {
input: NodeJS.ReadableStream;
output?: NodeJS.WritableStream;
completer?: Completer | AsyncCompleter;
terminal?: boolean;
historySize?: number;
prompt?: string;
crlfDelay?: number;
removeHistoryDuplicates?: boolean;
}
function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface;
function createInterface(options: ReadLineOptions): Interface;
function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void;
type Direction = -1 | 0 | 1;
/**
* Clears the current line of this WriteStream in a direction identified by `dir`.
*/
function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean;
/**
* Clears this `WriteStream` from the current cursor down.
*/
function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean;
/**
* Moves this WriteStream's cursor to the specified position.
*/
function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean;
/**
* Moves this WriteStream's cursor relative to its current position.
*/
function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean;
}
declare module "string_decoder" {
class StringDecoder {
constructor(encoding?: string);
write(buffer: Buffer): string;
end(buffer?: Buffer): string;
}
}
declare module "timers" {
function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout;
namespace setTimeout {
function __promisify__(ms: number): Promise<void>;
function __promisify__<T>(ms: number, value: T): Promise<T>;
}
function clearTimeout(timeoutId: NodeJS.Timeout): void;
function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout;
function clearInterval(intervalId: NodeJS.Timeout): void;
function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate;
namespace setImmediate {
function __promisify__(): Promise<void>;
function __promisify__<T>(value: T): Promise<T>;
}
function clearImmediate(immediateId: NodeJS.Immediate): void;
}
declare module "trace_events" {
/**
* The `Tracing` object is used to enable or disable tracing for sets of
* categories. Instances are created using the
* `trace_events.createTracing()` method.
*
* When created, the `Tracing` object is disabled. Calling the
* `tracing.enable()` method adds the categories to the set of enabled trace
* event categories. Calling `tracing.disable()` will remove the categories
* from the set of enabled trace event categories.
*/
interface Tracing {
/**
* A comma-separated list of the trace event categories covered by this
* `Tracing` object.
*/
readonly categories: string;
/**
* Disables this `Tracing` object.
*
* Only trace event categories _not_ covered by other enabled `Tracing`
* objects and _not_ specified by the `--trace-event-categories` flag
* will be disabled.
*/
disable(): void;
/**
* Enables this `Tracing` object for the set of categories covered by
* the `Tracing` object.
*/
enable(): void;
/**
* `true` only if the `Tracing` object has been enabled.
*/
readonly enabled: boolean;
}
interface CreateTracingOptions {
/**
* An array of trace category names. Values included in the array are
* coerced to a string when possible. An error will be thrown if the
* value cannot be coerced.
*/
categories: string[];
}
/**
* Creates and returns a Tracing object for the given set of categories.
*/
function createTracing(options: CreateTracingOptions): Tracing;
/**
* Returns a comma-separated list of all currently-enabled trace event
* categories. The current set of enabled trace event categories is
* determined by the union of all currently-enabled `Tracing` objects and
* any categories enabled using the `--trace-event-categories` flag.
*/
function getEnabledCategories(): string | undefined;
}
// tslint:disable-next-line:no-bad-reference
/// <reference path="../fs.d.ts" />
declare module 'fs' {
interface BigIntStats extends StatsBase<BigInt> {
}
class BigIntStats {
atimeNs: BigInt;
mtimeNs: BigInt;
ctimeNs: BigInt;
birthtimeNs: BigInt;
}
interface BigIntOptions {
bigint: true;
}
interface StatOptions {
bigint: boolean;
}
function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void;
function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void;
namespace stat {
function __promisify__(path: PathLike, options: BigIntOptions): Promise<BigIntStats>;
function __promisify__(path: PathLike, options: StatOptions): Promise<Stats | BigIntStats>;
}
function statSync(path: PathLike, options: BigIntOptions): BigIntStats;
function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats;
}
// tslint:disable-next-line:no-bad-reference
/// <reference path="../globals.d.ts" />
declare namespace NodeJS {
interface HRTime {
bigint(): bigint;
}
}
interface Buffer extends Uint8Array {
readBigUInt64BE(offset?: number): bigint;
readBigUInt64LE(offset?: number): bigint;
readBigInt64BE(offset?: number): bigint;
readBigInt64LE(offset?: number): bigint;
writeBigInt64BE(value: bigint, offset?: number): number;
writeBigInt64LE(value: bigint, offset?: number): number;
writeBigUInt64BE(value: bigint, offset?: number): number;
writeBigUInt64LE(value: bigint, offset?: number): number;
}
// NOTE: These definitions support NodeJS and TypeScript 3.2.
// NOTE: TypeScript version-specific augmentations can be found in the following paths:
// - ~/base.d.ts - Shared definitions common to all TypeScript versions
// - ~/index.d.ts - Definitions specific to TypeScript 2.1
// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2
// Reference required types from the default lib:
/// <reference lib="es2018" />
/// <reference lib="esnext.asynciterable" />
/// <reference lib="esnext.intl" />
/// <reference lib="esnext.bigint" />
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
// tslint:disable-next-line:no-bad-reference
/// <reference path="../base.d.ts" />
// TypeScript 3.2-specific augmentations:
/// <reference path="fs.d.ts" />
/// <reference path="util.d.ts" />
/// <reference path="globals.d.ts" />
// tslint:disable-next-line:no-bad-reference
/// <reference path="../util.d.ts" />
declare module "util" {
namespace inspect {
const custom: unique symbol;
}
namespace promisify {
const custom: unique symbol;
}
namespace types {
function isBigInt64Array(value: any): value is BigInt64Array;
function isBigUint64Array(value: any): value is BigUint64Array;
}
}
declare module "tty" {
import * as net from "net";
function isatty(fd: number): boolean;
class ReadStream extends net.Socket {
constructor(fd: number, options?: net.SocketConstructorOpts);
isRaw: boolean;
setRawMode(mode: boolean): void;
isTTY: boolean;
}
/**
* -1 - to the left from cursor
* 0 - the entire line
* 1 - to the right from cursor
*/
type Direction = -1 | 0 | 1;
class WriteStream extends net.Socket {
constructor(fd: number);
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "resize", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "resize"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "resize", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "resize", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "resize", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "resize", listener: () => void): this;
/**
* Clears the current line of this WriteStream in a direction identified by `dir`.
*/
clearLine(dir: Direction, callback?: () => void): boolean;
/**
* Clears this `WriteStream` from the current cursor down.
*/
clearScreenDown(callback?: () => void): boolean;
/**
* Moves this WriteStream's cursor to the specified position.
*/
cursorTo(x: number, y?: number, callback?: () => void): boolean;
cursorTo(x: number, callback: () => void): boolean;
/**
* Moves this WriteStream's cursor relative to its current position.
*/
moveCursor(dx: number, dy: number, callback?: () => void): boolean;
/**
* @default `process.env`
*/
getColorDepth(env?: {}): number;
hasColors(depth?: number): boolean;
hasColors(env?: {}): boolean;
hasColors(depth: number, env?: {}): boolean;
getWindowSize(): [number, number];
columns: number;
rows: number;
isTTY: boolean;
}
}
declare module "url" {
import { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring';
// Input to `url.format`
interface UrlObject {
auth?: string | null;
hash?: string | null;
host?: string | null;
hostname?: string | null;
href?: string | null;
path?: string | null;
pathname?: string | null;
protocol?: string | null;
search?: string | null;
slashes?: boolean | null;
port?: string | number | null;
query?: string | null | ParsedUrlQueryInput;
}
// Output of `url.parse`
interface Url {
auth: string | null;
hash: string | null;
host: string | null;
hostname: string | null;
href: string;
path: string | null;
pathname: string | null;
protocol: string | null;
search: string | null;
slashes: boolean | null;
port: string | null;
query: string | null | ParsedUrlQuery;
}
interface UrlWithParsedQuery extends Url {
query: ParsedUrlQuery;
}
interface UrlWithStringQuery extends Url {
query: string | null;
}
function parse(urlStr: string): UrlWithStringQuery;
function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery;
function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery;
function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url;
function format(URL: URL, options?: URLFormatOptions): string;
function format(urlObject: UrlObject | string): string;
function resolve(from: string, to: string): string;
function domainToASCII(domain: string): string;
function domainToUnicode(domain: string): string;
/**
* This function ensures the correct decodings of percent-encoded characters as
* well as ensuring a cross-platform valid absolute path string.
* @param url The file URL string or URL object to convert to a path.
*/
function fileURLToPath(url: string | URL): string;
/**
* This function ensures that path is resolved absolutely, and that the URL
* control characters are correctly encoded when converting into a File URL.
* @param url The path to convert to a File URL.
*/
function pathToFileURL(url: string): URL;
interface URLFormatOptions {
auth?: boolean;
fragment?: boolean;
search?: boolean;
unicode?: boolean;
}
class URL {
constructor(input: string, base?: string | URL);
hash: string;
host: string;
hostname: string;
href: string;
readonly origin: string;
password: string;
pathname: string;
port: string;
protocol: string;
search: string;
readonly searchParams: URLSearchParams;
username: string;
toString(): string;
toJSON(): string;
}
class URLSearchParams implements Iterable<[string, string]> {
constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>);
append(name: string, value: string): void;
delete(name: string): void;
entries(): IterableIterator<[string, string]>;
forEach(callback: (value: string, name: string, searchParams: this) => void): void;
get(name: string): string | null;
getAll(name: string): string[];
has(name: string): boolean;
keys(): IterableIterator<string>;
set(name: string, value: string): void;
sort(): void;
toString(): string;
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[string, string]>;
}
}
declare module "v8" {
import { Readable } from "stream";
interface HeapSpaceInfo {
space_name: string;
space_size: number;
space_used_size: number;
space_available_size: number;
physical_space_size: number;
}
// ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */
type DoesZapCodeSpaceFlag = 0 | 1;
interface HeapInfo {
total_heap_size: number;
total_heap_size_executable: number;
total_physical_size: number;
total_available_size: number;
used_heap_size: number;
heap_size_limit: number;
malloced_memory: number;
peak_malloced_memory: number;
does_zap_garbage: DoesZapCodeSpaceFlag;
number_of_native_contexts: number;
number_of_detached_contexts: number;
}
interface HeapCodeStatistics {
code_and_metadata_size: number;
bytecode_and_metadata_size: number;
external_script_source_size: number;
}
/**
* Returns an integer representing a "version tag" derived from the V8 version, command line flags and detected CPU features.
* This is useful for determining whether a vm.Script cachedData buffer is compatible with this instance of V8.
*/
function cachedDataVersionTag(): number;
function getHeapStatistics(): HeapInfo;
function getHeapSpaceStatistics(): HeapSpaceInfo[];
function setFlagsFromString(flags: string): void;
/**
* Generates a snapshot of the current V8 heap and returns a Readable
* Stream that may be used to read the JSON serialized representation.
* This conversation was marked as resolved by joyeecheung
* This JSON stream format is intended to be used with tools such as
* Chrome DevTools. The JSON schema is undocumented and specific to the
* V8 engine, and may change from one version of V8 to the next.
*/
function getHeapSnapshot(): Readable;
/**
*
* @param fileName The file path where the V8 heap snapshot is to be
* saved. If not specified, a file name with the pattern
* `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be
* generated, where `{pid}` will be the PID of the Node.js process,
* `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from
* the main Node.js thread or the id of a worker thread.
*/
function writeHeapSnapshot(fileName?: string): string;
function getHeapCodeStatistics(): HeapCodeStatistics;
/**
* @experimental
*/
class Serializer {
/**
* Writes out a header, which includes the serialization format version.
*/
writeHeader(): void;
/**
* Serializes a JavaScript value and adds the serialized representation to the internal buffer.
* This throws an error if value cannot be serialized.
*/
writeValue(val: any): boolean;
/**
* Returns the stored internal buffer.
* This serializer should not be used once the buffer is released.
* Calling this method results in undefined behavior if a previous write has failed.
*/
releaseBuffer(): Buffer;
/**
* Marks an ArrayBuffer as having its contents transferred out of band.\
* Pass the corresponding ArrayBuffer in the deserializing context to deserializer.transferArrayBuffer().
*/
transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
/**
* Write a raw 32-bit unsigned integer.
*/
writeUint32(value: number): void;
/**
* Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
*/
writeUint64(hi: number, lo: number): void;
/**
* Write a JS number value.
*/
writeDouble(value: number): void;
/**
* Write raw bytes into the serializer’s internal buffer.
* The deserializer will require a way to compute the length of the buffer.
*/
writeRawBytes(buffer: NodeJS.TypedArray): void;
}
/**
* A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects,
* and only stores the part of their underlying `ArrayBuffers` that they are referring to.
* @experimental
*/
class DefaultSerializer extends Serializer {
}
/**
* @experimental
*/
class Deserializer {
constructor(data: NodeJS.TypedArray);
/**
* Reads and validates a header (including the format version).
* May, for example, reject an invalid or unsupported wire format.
* In that case, an Error is thrown.
*/
readHeader(): boolean;
/**
* Deserializes a JavaScript value from the buffer and returns it.
*/
readValue(): any;
/**
* Marks an ArrayBuffer as having its contents transferred out of band.
* Pass the corresponding `ArrayBuffer` in the serializing context to serializer.transferArrayBuffer()
* (or return the id from serializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).
*/
transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
/**
* Reads the underlying wire format version.
* Likely mostly to be useful to legacy code reading old wire format versions.
* May not be called before .readHeader().
*/
getWireFormatVersion(): number;
/**
* Read a raw 32-bit unsigned integer and return it.
*/
readUint32(): number;
/**
* Read a raw 64-bit unsigned integer and return it as an array [hi, lo] with two 32-bit unsigned integer entries.
*/
readUint64(): [number, number];
/**
* Read a JS number value.
*/
readDouble(): number;
/**
* Read raw bytes from the deserializer’s internal buffer.
* The length parameter must correspond to the length of the buffer that was passed to serializer.writeRawBytes().
*/
readRawBytes(length: number): Buffer;
}
/**
* A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects,
* and only stores the part of their underlying `ArrayBuffers` that they are referring to.
* @experimental
*/
class DefaultDeserializer extends Deserializer {
}
/**
* Uses a `DefaultSerializer` to serialize value into a buffer.
* @experimental
*/
function serialize(value: any): Buffer;
/**
* Uses a `DefaultDeserializer` with default options to read a JS value from a buffer.
* @experimental
*/
function deserialize(data: NodeJS.TypedArray): any;
}
declare module "vm" {
interface Context {
[key: string]: any;
}
interface BaseOptions {
/**
* Specifies the filename used in stack traces produced by this script.
* Default: `''`.
*/
filename?: string;
/**
* Specifies the line number offset that is displayed in stack traces produced by this script.
* Default: `0`.
*/
lineOffset?: number;
/**
* Specifies the column number offset that is displayed in stack traces produced by this script.
* Default: `0`
*/
columnOffset?: number;
}
interface ScriptOptions extends BaseOptions {
displayErrors?: boolean;
timeout?: number;
cachedData?: Buffer;
produceCachedData?: boolean;
}
interface RunningScriptOptions extends BaseOptions {
/**
* When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace.
* Default: `true`.
*/
displayErrors?: boolean;
/**
* Specifies the number of milliseconds to execute code before terminating execution.
* If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer.
*/
timeout?: number;
/**
* If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received.
* Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that.
* If execution is terminated, an `Error` will be thrown.
* Default: `false`.
*/
breakOnSigint?: boolean;
}
interface CompileFunctionOptions extends BaseOptions {
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: Buffer;
/**
* Specifies whether to produce new cache data.
* Default: `false`,
*/
produceCachedData?: boolean;
/**
* The sandbox/context in which the said function should be compiled in.
*/
parsingContext?: Context;
/**
* An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling
*/
contextExtensions?: Object[];
}
interface CreateContextOptions {
/**
* Human-readable name of the newly created context.
* @default 'VM Context i' Where i is an ascending numerical index of the created context.
*/
name?: string;
/**
* Corresponds to the newly created context for display purposes.
* The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary),
* like the value of the `url.origin` property of a URL object.
* Most notably, this string should omit the trailing slash, as that denotes a path.
* @default ''
*/
origin?: string;
codeGeneration?: {
/**
* If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc)
* will throw an EvalError.
* @default true
*/
strings?: boolean;
/**
* If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError.
* @default true
*/
wasm?: boolean;
};
}
class Script {
constructor(code: string, options?: ScriptOptions);
runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any;
runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any;
runInThisContext(options?: RunningScriptOptions): any;
createCachedData(): Buffer;
}
function createContext(sandbox?: Context, options?: CreateContextOptions): Context;
function isContext(sandbox: Context): boolean;
function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any;
function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any;
function runInThisContext(code: string, options?: RunningScriptOptions | string): any;
function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function;
}
declare module "worker_threads" {
import { Context } from "vm";
import { EventEmitter } from "events";
import { Readable, Writable } from "stream";
const isMainThread: boolean;
const parentPort: null | MessagePort;
const threadId: number;
const workerData: any;
class MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
}
class MessagePort extends EventEmitter {
close(): void;
postMessage(value: any, transferList?: Array<ArrayBuffer | MessagePort>): void;
ref(): void;
unref(): void;
start(): void;
addListener(event: "close", listener: () => void): this;
addListener(event: "message", listener: (value: any) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "close"): boolean;
emit(event: "message", value: any): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "close", listener: () => void): this;
on(event: "message", listener: (value: any) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "message", listener: (value: any) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "message", listener: (value: any) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "message", listener: (value: any) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "close", listener: () => void): this;
removeListener(event: "message", listener: (value: any) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: "close", listener: () => void): this;
off(event: "message", listener: (value: any) => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
}
interface WorkerOptions {
eval?: boolean;
workerData?: any;
stdin?: boolean;
stdout?: boolean;
stderr?: boolean;
execArgv?: string[];
}
class Worker extends EventEmitter {
readonly stdin: Writable | null;
readonly stdout: Readable;
readonly stderr: Readable;
readonly threadId: number;
constructor(filename: string, options?: WorkerOptions);
postMessage(value: any, transferList?: Array<ArrayBuffer | MessagePort>): void;
ref(): void;
unref(): void;
/**
* Stop all JavaScript execution in the worker thread as soon as possible.
* Returns a Promise for the exit code that is fulfilled when the `exit` event is emitted.
*/
terminate(): Promise<number>;
/**
* Transfer a `MessagePort` to a different `vm` Context. The original `port`
* object will be rendered unusable, and the returned `MessagePort` instance will
* take its place.
*
* The returned `MessagePort` will be an object in the target context, and will
* inherit from its global `Object` class. Objects passed to the
* `port.onmessage()` listener will also be created in the target context
* and inherit from its global `Object` class.
*
* However, the created `MessagePort` will no longer inherit from
* `EventEmitter`, and only `port.onmessage()` can be used to receive
* events using it.
*/
moveMessagePortToContext(port: MessagePort, context: Context): MessagePort;
/**
* Receive a single message from a given `MessagePort`. If no message is available,
* `undefined` is returned, otherwise an object with a single `message` property
* that contains the message payload, corresponding to the oldest message in the
* `MessagePort`’s queue.
*/
receiveMessageOnPort(port: MessagePort): {} | undefined;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "exit", listener: (exitCode: number) => void): this;
addListener(event: "message", listener: (value: any) => void): this;
addListener(event: "online", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "error", err: Error): boolean;
emit(event: "exit", exitCode: number): boolean;
emit(event: "message", value: any): boolean;
emit(event: "online"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "error", listener: (err: Error) => void): this;
on(event: "exit", listener: (exitCode: number) => void): this;
on(event: "message", listener: (value: any) => void): this;
on(event: "online", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "exit", listener: (exitCode: number) => void): this;
once(event: "message", listener: (value: any) => void): this;
once(event: "online", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "exit", listener: (exitCode: number) => void): this;
prependListener(event: "message", listener: (value: any) => void): this;
prependListener(event: "online", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "exit", listener: (exitCode: number) => void): this;
prependOnceListener(event: "message", listener: (value: any) => void): this;
prependOnceListener(event: "online", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: "exit", listener: (exitCode: number) => void): this;
removeListener(event: "message", listener: (value: any) => void): this;
removeListener(event: "online", listener: () => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: "error", listener: (err: Error) => void): this;
off(event: "exit", listener: (exitCode: number) => void): this;
off(event: "message", listener: (value: any) => void): this;
off(event: "online", listener: () => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
}
}
# EJS
Embedded JavaScript templates
[![Build Status](https://img.shields.io/travis/mde/ejs/master.svg?style=flat)](https://travis-ci.org/mde/ejs)
[![Developing Dependencies](https://img.shields.io/david/dev/mde/ejs.svg?style=flat)](https://david-dm.org/mde/ejs?type=dev)
[![Known Vulnerabilities](https://snyk.io/test/npm/ejs/badge.svg?style=flat)](https://snyk.io/test/npm/ejs)
## Installation
```bash
$ npm install ejs
```
## Features
* Control flow with `<% %>`
* Escaped output with `<%= %>` (escape function configurable)
* Unescaped raw output with `<%- %>`
* Newline-trim mode ('newline slurping') with `-%>` ending tag
* Whitespace-trim mode (slurp all whitespace) for control flow with `<%_ _%>`
* Custom delimiters (e.g., use `<? ?>` instead of `<% %>`)
* Includes
* Client-side support
* Static caching of intermediate JavaScript
* Static caching of templates
* Complies with the [Express](http://expressjs.com) view system
## Example
```ejs
<% if (user) { %>
<h2><%= user.name %></h2>
<% } %>
```
Try EJS online at: https://ionicabizau.github.io/ejs-playground/.
## Usage
```javascript
let template = ejs.compile(str, options);
template(data);
// => Rendered HTML string
ejs.render(str, data, options);
// => Rendered HTML string
ejs.renderFile(filename, data, options, function(err, str){
// str => Rendered HTML string
});
```
It is also possible to use `ejs.render(dataAndOptions);` where you pass
everything in a single object. In that case, you'll end up with local variables
for all the passed options. However, be aware that your code could break if we
add an option with the same name as one of your data object's properties.
Therefore, we do not recommend using this shortcut.
## Options
- `cache` Compiled functions are cached, requires `filename`
- `filename` The name of the file being rendered. Not required if you
are using `renderFile()`. Used by `cache` to key caches, and for includes.
- `root` Set project root for includes with an absolute path (/file.ejs).
- `context` Function execution context
- `compileDebug` When `false` no debug instrumentation is compiled
- `client` When `true`, compiles a function that can be rendered
in the browser without needing to load the EJS Runtime
([ejs.min.js](https://github.com/mde/ejs/releases/latest)).
- `delimiter` Character to use with angle brackets for open/close
- `debug` Output generated function body
- `strict` When set to `true`, generated function is in strict mode
- `_with` Whether or not to use `with() {}` constructs. If `false`
then the locals will be stored in the `locals` object. Set to `false` in strict mode.
- `destructuredLocals` An array of local variables that are always destructured from
the locals object, available even in strict mode.
- `localsName` Name to use for the object storing local variables when not using
`with` Defaults to `locals`
- `rmWhitespace` Remove all safe-to-remove whitespace, including leading
and trailing whitespace. It also enables a safer version of `-%>` line
slurping for all scriptlet tags (it does not strip new lines of tags in
the middle of a line).
- `escape` The escaping function used with `<%=` construct. It is
used in rendering and is `.toString()`ed in the generation of client functions.
(By default escapes XML).
- `outputFunctionName` Set to a string (e.g., 'echo' or 'print') for a function to print
output inside scriptlet tags.
- `async` When `true`, EJS will use an async function for rendering. (Depends
on async/await support in the JS runtime.
This project uses [JSDoc](http://usejsdoc.org/). For the full public API
documentation, clone the repository and run `npm run doc`. This will run JSDoc
with the proper options and output the documentation to `out/`. If you want
the both the public & private API docs, run `npm run devdoc` instead.
## Tags
- `<%` 'Scriptlet' tag, for control-flow, no output
- `<%_` 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it
- `<%=` Outputs the value into the template (escaped)
- `<%-` Outputs the unescaped value into the template
- `<%#` Comment tag, no execution, no output
- `<%%` Outputs a literal '<%'
- `%%>` Outputs a literal '%>'
- `%>` Plain ending tag
- `-%>` Trim-mode ('newline slurp') tag, trims following newline
- `_%>` 'Whitespace Slurping' ending tag, removes all whitespace after it
For the full syntax documentation, please see [docs/syntax.md](https://github.com/mde/ejs/blob/master/docs/syntax.md).
## Includes
Includes either have to be an absolute path, or, if not, are assumed as
relative to the template with the `include` call. For example if you are
including `./views/user/show.ejs` from `./views/users.ejs` you would
use `<%- include('user/show') %>`.
You must specify the `filename` option for the template with the `include`
call unless you are using `renderFile()`.
You'll likely want to use the raw output tag (`<%-`) with your include to avoid
double-escaping the HTML output.
```ejs
<ul>
<% users.forEach(function(user){ %>
<%- include('user/show', {user: user}) %>
<% }); %>
</ul>
```
Includes are inserted at runtime, so you can use variables for the path in the
`include` call (for example `<%- include(somePath) %>`). Variables in your
top-level data object are available to all your includes, but local variables
need to be passed down.
NOTE: Include preprocessor directives (`<% include user/show %>`) are
still supported.
## Custom delimiters
Custom delimiters can be applied on a per-template basis, or globally:
```javascript
let ejs = require('ejs'),
users = ['geddy', 'neil', 'alex'];
// Just one template
ejs.render('<?= users.join(" | "); ?>', {users: users}, {delimiter: '?'});
// => 'geddy | neil | alex'
// Or globally
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
// => 'geddy | neil | alex'
```
## Caching
EJS ships with a basic in-process cache for caching the intermediate JavaScript
functions used to render templates. It's easy to plug in LRU caching using
Node's `lru-cache` library:
```javascript
let ejs = require('ejs'),
LRU = require('lru-cache');
ejs.cache = LRU(100); // LRU cache with 100-item limit
```
If you want to clear the EJS cache, call `ejs.clearCache`. If you're using the
LRU cache and need a different limit, simple reset `ejs.cache` to a new instance
of the LRU.
## Custom file loader
The default file loader is `fs.readFileSync`, if you want to customize it, you can set ejs.fileLoader.
```javascript
let ejs = require('ejs');
let myFileLoad = function (filePath) {
return 'myFileLoad: ' + fs.readFileSync(filePath);
};
ejs.fileLoader = myFileLoad;
```
With this feature, you can preprocess the template before reading it.
## Layouts
EJS does not specifically support blocks, but layouts can be implemented by
including headers and footers, like so:
```ejs
<%- include('header') -%>
<h1>
Title
</h1>
<p>
My page
</p>
<%- include('footer') -%>
```
## Client-side support
Go to the [Latest Release](https://github.com/mde/ejs/releases/latest), download
`./ejs.js` or `./ejs.min.js`. Alternately, you can compile it yourself by cloning
the repository and running `jake build` (or `$(npm bin)/jake build` if jake is
not installed globally).
Include one of these files on your page, and `ejs` should be available globally.
### Example
```html
<div id="output"></div>
<script src="ejs.min.js"></script>
<script>
let people = ['geddy', 'neil', 'alex'],
html = ejs.render('<%= people.join(", "); %>', {people: people});
// With jQuery:
$('#output').html(html);
// Vanilla JS:
document.getElementById('output').innerHTML = html;
</script>
```
### Caveats
Most of EJS will work as expected; however, there are a few things to note:
1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work.
2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example:
```javascript
let str = "Hello <%= include('file', {person: 'John'}); %>",
fn = ejs.compile(str, {client: true});
fn(data, null, function(path, d){ // include callback
// path -> 'file'
// d -> {person: 'John'}
// Put your code here
// Return the contents of file as a string
}); // returns rendered string
```
See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details.
### IDE Integration with Syntax Highlighting
VSCode:Javascript EJS by *DigitalBrainstem*
## Related projects
There are a number of implementations of EJS:
* TJ's implementation, the v1 of this library: https://github.com/tj/ejs
* Jupiter Consulting's EJS: http://www.embeddedjs.com/
* EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/
* Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs
* Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript
* DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar
## License
Licensed under the Apache License, Version 2.0
(<http://www.apache.org/licenses/LICENSE-2.0>)
- - -
EJS Embedded JavaScript templates copyright 2112
mde@fleegix.org.
var fs = require('fs');
var execSync = require('child_process').execSync;
var exec = function (cmd) {
execSync(cmd, {stdio: 'inherit'});
};
/* global jake, task, desc, publishTask */
task('build', ['lint', 'clean', 'browserify', 'minify'], function () {
console.log('Build completed.');
});
desc('Cleans browerified/minified files and package files');
task('clean', ['clobber'], function () {
jake.rmRf('./ejs.js');
jake.rmRf('./ejs.min.js');
console.log('Cleaned up compiled files.');
});
desc('Lints the source code');
task('lint', ['clean'], function () {
exec('./node_modules/.bin/eslint "**/*.js"');
console.log('Linting completed.');
});
task('browserify', function () {
exec('./node_modules/browserify/bin/cmd.js --standalone ejs lib/ejs.js > ejs.js');
console.log('Browserification completed.');
});
task('minify', function () {
exec('./node_modules/uglify-js/bin/uglifyjs ejs.js > ejs.min.js');
console.log('Minification completed.');
});
desc('Generates the EJS API docs');
task('doc', function (dev) {
jake.rmRf('out');
var p = dev ? '-p' : '';
exec('./node_modules/.bin/jsdoc ' + p + ' -c jsdoc.json lib/* docs/jsdoc/*');
console.log('Documentation generated.');
});
desc('Publishes the EJS API docs');
task('docPublish', ['doc'], function () {
fs.writeFileSync('out/CNAME', 'api.ejs.co');
console.log('Pushing docs to gh-pages...');
exec('./node_modules/.bin/git-directory-deploy --directory out/');
console.log('Docs published to gh-pages.');
});
desc('Runs the EJS test suite');
task('test', ['lint'], function () {
exec('./node_modules/.bin/mocha');
});
publishTask('ejs', ['build'], function () {
this.packageFiles.include([
'jakefile.js',
'README.md',
'LICENSE',
'package.json',
'postinstall.js',
'ejs.js',
'ejs.min.js',
'lib/**'
]);
});
jake.Task.publish.on('complete', function () {
console.log('Updating hosted docs...');
console.log('If this fails, run jake docPublish to re-try.');
jake.Task.docPublish.invoke();
});
/*
* EJS Embedded JavaScript templates
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Private utility functions
* @module utils
* @private
*/
'use strict';
var regExpChars = /[|\\{}()[\]^$+*?.]/g;
/**
* Escape characters reserved in regular expressions.
*
* If `string` is `undefined` or `null`, the empty string is returned.
*
* @param {String} string Input string
* @return {String} Escaped string
* @static
* @private
*/
exports.escapeRegExpChars = function (string) {
// istanbul ignore if
if (!string) {
return '';
}
return String(string).replace(regExpChars, '\\$&');
};
var _ENCODE_HTML_RULES = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;'
};
var _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
}
/**
* Stringified version of constants used by {@link module:utils.escapeXML}.
*
* It is used in the process of generating {@link ClientFunction}s.
*
* @readonly
* @type {String}
*/
var escapeFuncStr =
'var _ENCODE_HTML_RULES = {\n'
+ ' "&": "&amp;"\n'
+ ' , "<": "&lt;"\n'
+ ' , ">": "&gt;"\n'
+ ' , \'"\': "&#34;"\n'
+ ' , "\'": "&#39;"\n'
+ ' }\n'
+ ' , _MATCH_HTML = /[&<>\'"]/g;\n'
+ 'function encode_char(c) {\n'
+ ' return _ENCODE_HTML_RULES[c] || c;\n'
+ '};\n';
/**
* Escape characters reserved in XML.
*
* If `markup` is `undefined` or `null`, the empty string is returned.
*
* @implements {EscapeCallback}
* @param {String} markup Input string
* @return {String} Escaped string
* @static
* @private
*/
exports.escapeXML = function (markup) {
return markup == undefined
? ''
: String(markup)
.replace(_MATCH_HTML, encode_char);
};
exports.escapeXML.toString = function () {
return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
};
/**
* Naive copy of properties from one object to another.
* Does not recurse into non-scalar properties
* Does not check to see if the property has a value before copying
*
* @param {Object} to Destination object
* @param {Object} from Source object
* @return {Object} Destination object
* @static
* @private
*/
exports.shallowCopy = function (to, from) {
from = from || {};
for (var p in from) {
to[p] = from[p];
}
return to;
};
/**
* Naive copy of a list of key names, from one object to another.
* Only copies property if it is actually defined
* Does not recurse into non-scalar properties
*
* @param {Object} to Destination object
* @param {Object} from Source object
* @param {Array} list List of properties to copy
* @return {Object} Destination object
* @static
* @private
*/
exports.shallowCopyFromList = function (to, from, list) {
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (typeof from[p] != 'undefined') {
to[p] = from[p];
}
}
return to;
};
/**
* Simple in-process cache implementation. Does not implement limits of any
* sort.
*
* @implements Cache
* @static
* @private
*/
exports.cache = {
_data: {},
set: function (key, val) {
this._data[key] = val;
},
get: function (key) {
return this._data[key];
},
remove: function (key) {
delete this._data[key];
},
reset: function () {
this._data = {};
}
};
{
"name": "ejs",
"description": "Embedded JavaScript templates",
"keywords": [
"template",
"engine",
"ejs"
],
"version": "2.7.3",
"author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
"license": "Apache-2.0",
"main": "./lib/ejs.js",
"repository": {
"type": "git",
"url": "git://github.com/mde/ejs.git"
},
"bugs": "https://github.com/mde/ejs/issues",
"homepage": "https://github.com/mde/ejs",
"dependencies": {},
"devDependencies": {
"browserify": "^13.1.1",
"eslint": "^4.14.0",
"git-directory-deploy": "^1.5.1",
"istanbul": "~0.4.3",
"jake": "^10.3.1",
"jsdoc": "^3.4.0",
"lru-cache": "^4.0.1",
"mocha": "^5.0.5",
"uglify-js": "^3.3.16"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"postinstall": "node ./postinstall.js"
},
"__npminstall_done": "Tue Nov 19 2019 19:23:41 GMT+0800 (CST)",
"_from": "ejs@2.7.3",
"_resolved": "https://registry.npm.taobao.org/ejs/download/ejs-2.7.3.tgz"
}
\ No newline at end of file
#!/usr/bin/env node
function isTrue(value) {
return !!value && value !== '0' && value !== 'false';
}
let envDisable = isTrue(process.env.DISABLE_OPENCOLLECTIVE) || isTrue(process.env.CI);
let logLevel = process.env.npm_config_loglevel;
let logLevelDisplay = ['silent', 'error', 'warn'].indexOf(logLevel) > -1;
if (!envDisable && !logLevelDisplay) {
console.log('Thank you for installing \u001b[35mEJS\u001b[0m: built with the \u001b[32mJake\u001b[0m JavaScript build tool (\u001b[32mhttps://jakejs.com/\u001b[0m)\n');
}
1.16.2 / 2019-11-19
==================
**fixes**
* [[`bb8f5d4`](http://github.com/node-modules/utility/commit/bb8f5d4becb61df6e8ce1788a172f8ae4e9937b4)] - fix: getParamNames throw when input is not function (#51) (Daniels.Sun <<better.sunjian@gmail.com>>)
**others**
* [[`7016803`](http://github.com/node-modules/utility/commit/7016803364f22c70c42da59870eee64dd1d99020)] - build: add node 12 in ci (dead-horse <<dead_horse@qq.com>>)
1.16.1 / 2019-03-25
==================
**fixes**
* [[`a8b0c0d`](http://github.com/node-modules/utility/commit/a8b0c0d38e7d2f6c85169975cfc7f2f1a033c310)] - fix: detect number first before check NaN (#48) (fengmk2 <<fengmk2@gmail.com>>)
1.16.0 / 2019-03-25
==================
**features**
* [[`16104be`](http://github.com/node-modules/utility/commit/16104befbfde9c2a0bf95b88029436c4a182b1bb)] - feat: add getOwnEnumerables(obj, ignoreNull) (#47) (fengmk2 <<fengmk2@gmail.com>>)
1.15.1 / 2019-03-13
==================
**features**
* [[`b092817`](http://github.com/node-modules/utility/commit/b092817be0c4de459bde180e754ba4872e715027)] - feat: support for ts (#45) (yyge <<33921398+ddzy@users.noreply.github.com>>)
**others**
* [[`09bd9d0`](http://github.com/node-modules/utility/commit/09bd9d061b57a2ef6b24a39b41063f51cf251fc1)] - chore: package.json files add [index.d.ts] (#46) (ccccQ <<chenqiuws@gmail.com>>)
* [[`7c102f4`](http://github.com/node-modules/utility/commit/7c102f4aff81e44b96629d692ce74f22cc02919f)] - test: travis support windows (#40) (fengmk2 <<fengmk2@gmail.com>>)
* [[`fdd2d27`](http://github.com/node-modules/utility/commit/fdd2d27ce99c25458795ad1e7555370498c051bd)] - chore: fix typo function name of sha256 (#39) (fengmk2 <<fengmk2@gmail.com>>)
1.15.0 / 2018-09-12
==================
**features**
* [[`e3ae527`](http://github.com/node-modules/utility/commit/e3ae5277161e8870e097897f0dd41cd783170182)] - feat: add utility.unescape (#38) (Yiyu He <<dead_horse@qq.com>>)
**others**
* [[`50fb750`](http://github.com/node-modules/utility/commit/50fb750d0f24b7b47f0ef6e2ba5c42e5b2c7166a)] - chore: use ^ as deps version (#37) (fengmk2 <<fengmk2@gmail.com>>)
1.14.0 / 2018-06-29
==================
**features**
* [[`d401917`](http://github.com/node-modules/utility/commit/d401917f20f89c52be237279d575c695f1bf6ae0)] - feat: add replacer and space to writeJSON* (#34) (Khaidi Chu <<i@2333.moe>>)
1.13.1 / 2017-10-17
==================
**fixes**
* [[`fbbf905`](http://github.com/node-modules/utility/commit/fbbf905880185dce1e9cf980112a0f0b890e5969)] - fix: don't use arrow function (#31) (Yiyu He <<dead_horse@qq.com>>)
1.13.0 / 2017-10-17
==================
**features**
* [[`8a84707`](https://github.com/node-modules/utility.git/commit/8a847077b4d543193e4ca2f9ff69068a48d84909)] - feat: add readJSON and writeJSON (#29) (Haoliang Gao <<sakura9515@gmail.com>>)
1.12.0 / 2017-04-19
==================
* feat: add includesInvalidHttpHeaderChar() to detect invalid char
* test: add url test for replaceInvalidHttpHeaderChar
* chore: remove unused comments
* feat: replacement support function format
1.11.0 / 2017-02-21
==================
* feat: add utility.assign (#27)
1.10.0 / 2017-02-14
==================
* feat: add replace invalid http header character (#26)
1.9.0 / 2016-11-14
==================
* feat: add utils.random function (#25)
* bench: add Array.from(arguments) bench test
1.8.0 / 2016-05-09
==================
* feat(array): impl faster splice one element on array (#24)
1.7.1 / 2016-05-03
==================
* refactor: use faster empty object instead of Object.create(null) (#23)
1.7.0 / 2016-04-07
==================
* benchmark: update arguments to array
* chore: add doc
* feat: add utility.argumentsToArray
* chore: add david-dm status badge
* deps: remove unuse mm module
* test: use ava and nyc instead of mocha and istanbul
* bench: add string and tpl string benchmark
1.6.0 / 2015-12-04
==================
* refactor: use escape-html
1.5.0 / 2015-11-25
==================
* feat: utility.dig
* test(date): fix timezone on test assert
* feat(date): make YYYYMMDDHHmmss() support param not Date
* test: use codecov.io
1.4.0 / 2015-05-22
==================
* feat(JSON): add strict JSON parse
1.3.2 / 2015-05-08
==================
* feat(crypto): add sha256 hash
1.3.1 / 2015-04-09
==================
* fix(crypto): base64decode support return buffer
1.3.0 / 2015-01-31
==================
* feat(string): add string replace
1.2.1 / 2014-11-14
==================
* setImmediate support argmuents
1.2.0 / 2014-09-14
==================
* add utility.try
1.1.0 / 2014-08-23
==================
* add split(str, sep=,)
1.0.0 / 2014-08-01
==================
* remove address methods, please use `address` module
0.1.16 / 2014-07-07
==================
* fix deps
0.1.15 / 2014-07-07
==================
* YYYYMMDDHHmmss() support custom dateSep
0.1.14 / 2014-06-25
==================
* support `YYYYMMDD(d, sep)`
* add YYYYMMDDHHmmss benchmark
* add sha1 to readme
* add random string benchmark
0.1.13 / 2014-04-24
==================
* utils.YYYYMMDDHHmmssSSS(','); // '2013-04-17 14:43:02,674'
0.1.12 / 2014-04-03
==================
* support var map = util.map({a: 1})
0.1.11 / 2014-03-15
==================
* add sha1()
* remove config from scripts
0.1.10 / 2014-01-08
==================
* add randomString() and has() (@dead-horse)
* install from cnpm
0.1.9 / 2013-12-09
==================
* add YYYYMMDD()
0.1.8 / 2013-11-25
==================
* support sub object md5
0.1.7 / 2013-11-23
==================
* support timestamp string
0.1.6 / 2013-11-23
==================
* parse timestamp
0.1.5 / 2013-11-23
==================
* hash object
* add npm image
0.1.4 / 2013-11-16
==================
* utils.setImmediate()
* fix test case
0.1.3 / 2013-10-23
==================
* add number utils: toSafeNumber()
0.1.2 / 2013-10-07
==================
* add utils.YYYYMMDDHHmmss()
0.1.1 / 2013-09-23
==================
* add base64 format md5
0.1.0 / 2013-09-03
==================
* add timestamp()
0.0.13 / 2013-07-31
==================
* move getIP() to address, fixed #2
0.0.12 / 2013-06-27
==================
* utils.getParamNames(): get a function parameters names
0.0.11 / 2013-06-25
==================
* fixed interface name wrong on liunx
0.0.10 / 2013-06-25
==================
* add getIP()
* add more test cases
0.0.9 / 2013-05-08
==================
* Safe encodeURIComponent and decodeURIComponent
0.0.8 / 2013-05-06
==================
* add randomSlice() fixed #1
0.0.7 / 2013-04-17
==================
* fixed timezone +0000 and test cases
0.0.6 / 2013-04-17
==================
* utils.logDate(); // '2013-04-17 14:43:02.674'
0.0.5 / 2013-04-16
==================
* faster accesslogDate() impl
* add benchmark
0.0.4 / 2013-04-16
==================
* add accessLogDate()
0.0.3 / 2013-03-06
==================
* add hmac()
* update copyright year
* update md5 readme
0.0.2 / 2013-01-31
==================
* add base64 encode and urlsafe base64 encode
* add html escape()
* update makefile
0.0.1 / 2012-11-13
==================
* first commit
This software is licensed under the MIT License.
Copyright(c) 2012 - present node-modules and other contributors.
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.
'use strict';
/**
* Array random slice with items count.
* @param {Array} arr
* @param {Number} num, number of sub items.
* @return {Array}
*/
exports.randomSlice = function randomSlice(arr, num) {
if (!num || num >= arr.length) {
return arr.slice();
}
var index = Math.floor(Math.random() * arr.length);
var a = [];
for (var i = 0, j = index; i < num; i++) {
a.push(arr[j++]);
if (j === arr.length) {
j = 0;
}
}
return a;
};
/**
* Remove one exists element from an array
* @param {Array} arr
* @param {Number} index - remove element index
* @return {Array} the array instance
*/
exports.spliceOne = function spliceOne(arr, index) {
if (index < 0) {
index = arr.length + index;
// still negative, not found element
if (index < 0) {
return arr;
}
}
// don't touch
if (index >= arr.length) {
return arr;
}
for (var i = index, k = i + 1, n = arr.length; k < n; i += 1, k += 1) {
arr[i] = arr[k];
}
arr.pop();
return arr;
};
'use strict';
var crypto = require('crypto');
/**
* hash
*
* @param {String} method hash method, e.g.: 'md5', 'sha1'
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
* @return {String} md5 hash string
* @public
*/
exports.hash = function hash(method, s, format) {
var sum = crypto.createHash(method);
var isBuffer = Buffer.isBuffer(s);
if (!isBuffer && typeof s === 'object') {
s = JSON.stringify(sortObject(s));
}
sum.update(s, isBuffer ? 'binary' : 'utf8');
return sum.digest(format || 'hex');
};
/**
* md5 hash
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
* @return {String} md5 hash string
* @public
*/
exports.md5 = function md5(s, format) {
return exports.hash('md5', s, format);
};
/**
* sha1 hash
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
* @return {String} sha1 hash string
* @public
*/
exports.sha1 = function sha1(s, format) {
return exports.hash('sha1', s, format);
};
/**
* sha256 hash
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
* @return {String} sha256 hash string
* @public
*/
exports.sha256 = function sha256(s, format) {
return exports.hash('sha256', s, format);
};
/**
* HMAC algorithm.
*
* Equal bash:
*
* ```bash
* $ echo -n "$data" | openssl dgst -binary -$algorithm -hmac "$key" | openssl $encoding
* ```
*
* @param {String} algorithm, dependent on the available algorithms supported by the version of OpenSSL on the platform.
* Examples are 'sha1', 'md5', 'sha256', 'sha512', etc.
* On recent releases, `openssl list-message-digest-algorithms` will display the available digest algorithms.
* @param {String} key, the hmac key to be used.
* @param {String|Buffer} data, content string.
* @param {String} [encoding='base64']
* @return {String} digest string.
*/
exports.hmac = function hmac(algorithm, key, data, encoding) {
encoding = encoding || 'base64';
var hmac = crypto.createHmac(algorithm, key);
hmac.update(data, Buffer.isBuffer(data) ? 'binary' : 'utf8');
return hmac.digest(encoding);
};
/**
* Base64 encode string.
*
* @param {String|Buffer} s
* @param {Boolean} [urlsafe=false] Encode string s using a URL-safe alphabet,
* which substitutes - instead of + and _ instead of / in the standard Base64 alphabet.
* @return {String} base64 encode format string.
*/
exports.base64encode = function base64encode(s, urlsafe) {
if (!Buffer.isBuffer(s)) {
s = typeof Buffer.from === 'function' ? Buffer.from(s) : new Buffer(s);
}
var encode = s.toString('base64');
if (urlsafe) {
encode = encode.replace(/\+/g, '-').replace(/\//g, '_');
}
return encode;
};
/**
* Base64 string decode.
*
* @param {String} encode, base64 encoding string.
* @param {Boolean} [urlsafe=false] Decode string s using a URL-safe alphabet,
* which substitutes - instead of + and _ instead of / in the standard Base64 alphabet.
* @param {encoding} [encoding=utf8] if encoding = buffer, will return Buffer instance
* @return {String|Buffer} plain text.
*/
exports.base64decode = function base64decode(encodeStr, urlsafe, encoding) {
if (urlsafe) {
encodeStr = encodeStr.replace(/\-/g, '+').replace(/_/g, '/');
}
var buf = typeof Buffer.from === 'function' ? Buffer.from(encodeStr, 'base64') : new Buffer(encodeStr, 'base64');
if (encoding === 'buffer') {
return buf;
}
return buf.toString(encoding || 'utf8');
};
function sortObject(o) {
if (!o || Array.isArray(o) || typeof o !== 'object') {
return o;
}
var keys = Object.keys(o);
keys.sort();
var values = [];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
values.push([k, sortObject(o[k])]);
}
return values;
}
'use strict';
var MONTHS = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];
// only set once.
var TIMEZONE = ' ';
var _hourOffset = parseInt(-(new Date().getTimezoneOffset()) / 60, 10);
if (_hourOffset >= 0) {
TIMEZONE += '+';
} else {
TIMEZONE += '-';
}
_hourOffset = Math.abs(_hourOffset);
if (_hourOffset < 10) {
_hourOffset = '0' + _hourOffset;
}
TIMEZONE += _hourOffset + '00';
/**
* Access log format date. format: `moment().format('DD/MMM/YYYY:HH:mm:ss ZZ')`
*
* @return {String}
*/
exports.accessLogDate = function (d) {
// 16/Apr/2013:16:40:09 +0800
d = d || new Date();
var date = d.getDate();
if (date < 10) {
date = '0' + date;
}
var hours = d.getHours();
if (hours < 10) {
hours = '0' + hours;
}
var mintues = d.getMinutes();
if (mintues < 10) {
mintues = '0' + mintues;
}
var seconds = d.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
return date + '/' + MONTHS[d.getMonth()] + '/' + d.getFullYear() +
':' + hours + ':' + mintues + ':' + seconds + TIMEZONE;
};
/**
* Normal log format date. format: `moment().format('YYYY-MM-DD HH:mm:ss.SSS')`
*
* @return {String}
*/
exports.logDate = exports.YYYYMMDDHHmmssSSS = function (d, msSep) {
if (typeof d === 'string') {
// logDate(msSep)
msSep = d;
d = new Date();
} else {
// logDate(d, msSep)
d = d || new Date();
}
var date = d.getDate();
if (date < 10) {
date = '0' + date;
}
var month = d.getMonth() + 1;
if (month < 10) {
month = '0' + month;
}
var hours = d.getHours();
if (hours < 10) {
hours = '0' + hours;
}
var mintues = d.getMinutes();
if (mintues < 10) {
mintues = '0' + mintues;
}
var seconds = d.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
var milliseconds = d.getMilliseconds();
if (milliseconds < 10) {
milliseconds = '00' + milliseconds;
} else if (milliseconds < 100) {
milliseconds = '0' + milliseconds;
}
return d.getFullYear() + '-' + month + '-' + date + ' ' +
hours + ':' + mintues + ':' + seconds + (msSep || '.') + milliseconds;
};
/**
* `moment().format('YYYY-MM-DD HH:mm:ss')` format date string.
*
* @return {String}
*/
exports.YYYYMMDDHHmmss = function (d, options) {
d = d || new Date();
if (!(d instanceof Date)) {
d = new Date(d);
}
var dateSep = '-';
var timeSep = ':';
if (options) {
if (options.dateSep) {
dateSep = options.dateSep;
}
if (options.timeSep) {
timeSep = options.timeSep;
}
}
var date = d.getDate();
if (date < 10) {
date = '0' + date;
}
var month = d.getMonth() + 1;
if (month < 10) {
month = '0' + month;
}
var hours = d.getHours();
if (hours < 10) {
hours = '0' + hours;
}
var mintues = d.getMinutes();
if (mintues < 10) {
mintues = '0' + mintues;
}
var seconds = d.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
return d.getFullYear() + dateSep + month + dateSep + date + ' ' +
hours + timeSep + mintues + timeSep + seconds;
};
/**
* `moment().format('YYYY-MM-DD')` format date string.
*
* @return {String}
*/
exports.YYYYMMDD = function YYYYMMDD(d, sep) {
if (typeof d === 'string') {
// YYYYMMDD(sep)
sep = d;
d = new Date();
} else {
// YYYYMMDD(d, sep)
d = d || new Date();
if (typeof sep !== 'string') {
sep = '-';
}
}
var date = d.getDate();
if (date < 10) {
date = '0' + date;
}
var month = d.getMonth() + 1;
if (month < 10) {
month = '0' + month;
}
return d.getFullYear() + sep + month + sep + date;
};
/**
* return datetime struct.
*
* @return {Object} date
* - {Number} YYYYMMDD, 20130401
* - {Number} H, 0, 1, 9, 12, 23
*/
exports.datestruct = function (now) {
now = now || new Date();
return {
YYYYMMDD: now.getFullYear() * 10000 + (now.getMonth() + 1) * 100 + now.getDate(),
H: now.getHours()
};
};
/**
* Get Unix's timestamp in seconds.
* @return {Number}
*/
exports.timestamp = function timestamp(t) {
if (t) {
var v = t;
if (typeof v === 'string') {
v = Number(v);
}
if (String(t).length === 10) {
v *= 1000;
}
return new Date(v);
}
return Math.round(Date.now() / 1000);
};
'use strict';
var assert = require('assert');
/**
* A empty function.
*
* @return {Function}
* @public
*/
exports.noop = function noop() {};
/**
* Get a function parameter's names.
*
* @param {Function} func
* @param {Boolean} [useCache], default is true
* @return {Array} names
*/
exports.getParamNames = function getParamNames(func, cache) {
var type = typeof func;
assert(type === 'function', `The "func" must be a function. Received type "${type}"`);
cache = cache !== false;
if (cache && func.__cache_names) {
return func.__cache_names;
}
var str = func.toString();
var names = str.slice(str.indexOf('(') + 1, str.indexOf(')')).match(/([^\s,]+)/g) || [];
func.__cache_names = names;
return names;
};
'use strict';
var fs = require('mz/fs');
var path = require('path');
var mkdirp = require('mkdirp');
exports.strictJSONParse = function (str) {
var obj = JSON.parse(str);
if (!obj || typeof obj !== 'object') {
throw new Error('JSON string is not object');
}
return obj;
};
exports.readJSONSync = function(filepath) {
if (!fs.existsSync(filepath)) {
throw new Error(filepath + ' is not found');
}
return JSON.parse(fs.readFileSync(filepath));
};
exports.writeJSONSync = function(filepath, str, options) {
options = options || {};
if (!('space' in options)) {
options.space = 2;
}
mkdirp.sync(path.dirname(filepath));
if (typeof str === 'object') {
str = JSON.stringify(str, options.replacer, options.space) + '\n';
}
fs.writeFileSync(filepath, str);
};
exports.readJSON = function(filepath) {
return fs.exists(filepath)
.then(function(exists) {
if (!exists) {
throw new Error(filepath + ' is not found');
}
return fs.readFile(filepath);
})
.then(function(buf) {
return JSON.parse(buf);
});
};
exports.writeJSON = function(filepath, str, options) {
options = options || {};
if (!('space' in options)) {
options.space = 2;
}
if (typeof str === 'object') {
str = JSON.stringify(str, options.replacer, options.space) + '\n';
}
return mkdir(path.dirname(filepath))
.then(function() {
return fs.writeFile(filepath, str);
});
};
function mkdir(dir) {
return new Promise(function(resolve, reject) {
mkdirp(dir, function(err) {
if (err) {
return reject(err);
}
resolve();
});
});
}
'use strict';
// http://www.2ality.com/2013/10/safe-integers.html
// http://es6.ruanyifeng.com/#docs/number
exports.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
exports.MIN_SAFE_INTEGER = -exports.MAX_SAFE_INTEGER;
var MAX_SAFE_INTEGER_STR = exports.MAX_SAFE_INTEGER_STR = String(exports.MAX_SAFE_INTEGER);
var MAX_SAFE_INTEGER_STR_LENGTH = MAX_SAFE_INTEGER_STR.length;
/**
* Detect a number string can safe convert to Javascript Number.
*
* @param {String} s number format string, like `"123"`, `"-1000123123123123123123"`
* @return {Boolean}
*/
exports.isSafeNumberString = function isSafeNumberString(s) {
if (s[0] === '-') {
s = s.substring(1);
}
if (s.length < MAX_SAFE_INTEGER_STR_LENGTH ||
(s.length === MAX_SAFE_INTEGER_STR_LENGTH && s <= MAX_SAFE_INTEGER_STR)) {
return true;
}
return false;
};
/**
* Convert string to Number if string in safe Number scope.
*
* @param {String} s number format string.
* @return {Number|String} success will return Number, otherise return the original string.
*/
exports.toSafeNumber = function toSafeNumber(s) {
if (typeof s === 'number') {
return s;
}
return exports.isSafeNumberString(s) ? Number(s) : s;
};
/**
* Produces a random integer between the inclusive `lower` and `upper` bounds.
*
* @param {Number} lower The lower bound.
* @param {Number} upper The upper bound.
* @return {Number} Returns the random number.
*/
exports.random = function random(lower, upper) {
if (lower === undefined && upper === undefined) {
return 0;
}
if (upper === undefined) {
upper = lower;
lower = 0;
}
var temp;
if (lower > upper) {
temp = lower;
lower = upper;
upper = temp;
}
return Math.floor(lower + Math.random() * (upper - lower));
};
'use strict';
/**
* High performance assign before node6
* @param {Object} target - target object
* @param {Object | Array} objects - object assign from
* @return {Object} - return target object
*/
exports.assign = function(target, objects) {
if (!Array.isArray(objects)) {
objects = [ objects ];
}
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
if (obj) {
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
target[key] = obj[key];
}
}
}
return target;
};
exports.has = function has(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
/**
* Get all enumerable and ownership of property names
* @param {Object} obj - detect object
* @param {Boolean} [ignoreNull] - ignore null, undefined or NaN property
* @return {Array<String>} property names
*/
exports.getOwnEnumerables = function getOwnEnumerables(obj, ignoreNull) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
return [];
}
return Object.keys(obj).filter(function(key) {
if (ignoreNull) {
var value = obj[key];
if (value === null || value === undefined || Number.isNaN(value)) {
return false;
}
}
return exports.has(obj, key);
});
};
/**
* generate a real map object(clean object), no constructor, no __proto__
* @param {Object} [obj] - init object, optional
* @return {Object}
*/
exports.map = function map(obj) {
var map = new EmptyObject();
if (!obj) {
return map;
}
for (var key in obj) {
map[key] = obj[key];
}
return map;
};
// faster way like `Object.create(null)` to get a 'clean' empty object
// https://github.com/nodejs/node/blob/master/lib/events.js#L5
// https://cnodejs.org/topic/571e0c445a26c4a841ecbcf1
function EmptyObject() {}
EmptyObject.prototype = Object.create(null);
'use strict';
/**
* optimize try catch
* @param {Function} fn
* @return {Object}
* - {Error} error
* - {Mix} value
*/
exports.try = function (fn) {
var res = {
error: undefined,
value: undefined
};
try {
res.value = fn();
} catch (err) {
res.error = err instanceof Error
? err
: new Error(err);
}
return res;
};
/**
* @description Deal with typescript
*/
exports.UNSTABLE_METHOD = {
try: exports.try,
};
/**
* avoid if (a && a.b && a.b.c)
* @param {Object} obj
* @param {...String} keys
* @return {Object}
*/
exports.dig = function (obj) {
if (!obj) {
return;
}
if (arguments.length <= 1) {
return obj;
}
var value = obj[arguments[1]];
for (var i = 2; i < arguments.length; i++) {
if (!value) {
break;
}
value = value[arguments[i]];
}
return value;
};
/**
* optimize arguments to array
* @param {Arguments} args
* @return {Array}
*/
exports.argumentsToArray = function (args) {
var res = new Array(args.length);
for (var i = 0; i < args.length; i++) {
res[i] = args[i];
}
return res;
};
'use strict';
exports.setImmediate = typeof setImmediate === 'function'
? setImmediate
: function(fn){
process.nextTick(fn.bind.apply(fn, arguments));
};
'use strict';
exports.randomString = function randomString(length, charSet) {
var result = [];
length = length || 16;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (length--) {
result.push(charSet[Math.floor(Math.random() * charSet.length)]);
}
return result.join('');
};
/**
* split string to array
* @param {String} str
* @param {String} [sep] default is ','
* @return {Array}
*/
exports.split = function split(str, sep) {
str = str || '';
sep = sep || ',';
var items = str.split(sep);
var needs = [];
for (var i = 0; i < items.length; i++) {
var s = items[i].trim();
if (s.length > 0) {
needs.push(s);
}
}
return needs;
};
// always optimized
exports.splitAlwaysOptimized = function splitAlwaysOptimized() {
var str = '';
var sep = ',';
if (arguments.length === 1) {
str = arguments[0] || '';
} else if (arguments.length === 2) {
str = arguments[0] || '';
sep = arguments[1] || ',';
}
var items = str.split(sep);
var needs = [];
for (var i = 0; i < items.length; i++) {
var s = items[i].trim();
if (s.length > 0) {
needs.push(s);
}
}
return needs;
};
/**
* Replace string
*
* @param {String} str
* @param {String|RegExp} substr
* @param {String|Function} newSubstr
* @return {String}
*/
exports.replace = function replace(str, substr, newSubstr) {
var replaceFunction = newSubstr;
if (typeof replaceFunction !== 'function') {
replaceFunction = function () {
return newSubstr;
};
}
return str.replace(substr, replaceFunction);
};
// original source https://github.com/nodejs/node/blob/v7.5.0/lib/_http_common.js#L300
/**
* True if val contains an invalid field-vchar
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
*
* checkInvalidHeaderChar() is currently designed to be inlinable by v8,
* so take care when making changes to the implementation so that the source
* code size does not exceed v8's default max_inlined_source_size setting.
**/
var validHdrChars = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, // 0 - 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 32 - 47
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 63
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 95
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 112 - 127
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 128 ...
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // ... 255
];
/**
* Replace invalid http header characters with replacement
*
* @param {String} val
* @param {String|Function} replacement - can be `function(char)`
* @return {Object}
*/
exports.replaceInvalidHttpHeaderChar = function replaceInvalidHttpHeaderChar(val, replacement) {
replacement = replacement || ' ';
var invalid = false;
if (!val || typeof val !== 'string') {
return {
val: val,
invalid: invalid,
};
}
var replacementType = typeof replacement;
var chars;
for (var i = 0; i < val.length; ++i) {
if (!validHdrChars[val.charCodeAt(i)]) {
// delay create chars
chars = chars || val.split('');
if (replacementType === 'function') {
chars[i] = replacement(chars[i]);
} else {
chars[i] = replacement;
}
}
}
if (chars) {
val = chars.join('');
invalid = true;
}
return {
val: val,
invalid: invalid,
};
};
/**
* Detect invalid http header characters in a string
*
* @param {String} val
* @return {Boolean}
*/
exports.includesInvalidHttpHeaderChar = function includesInvalidHttpHeaderChar(val) {
if (!val || typeof val !== 'string') {
return false;
}
for (var i = 0; i < val.length; ++i) {
if (!validHdrChars[val.charCodeAt(i)]) {
return true;
}
}
return false;
};
'use strict';
var copy = require('copy-to');
copy(require('./function'))
.and(require('./polyfill'))
.and(require('./optimize'))
.and(require('./crypto'))
.and(require('./number'))
.and(require('./string'))
.and(require('./array'))
.and(require('./json'))
.and(require('./date'))
.and(require('./object'))
.and(require('./web'))
.to(module.exports);
'use strict';
/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @public
*/
exports.escape = require('escape-html');
/**
* Unescape the given string from html
* @param {String} html
* @param {String} type
* @return {String}
* @public
*/
exports.unescape = require('unescape');
/**
* Safe encodeURIComponent, won't throw any error.
* If `encodeURIComponent` error happen, just return the original value.
*
* @param {String} text
* @return {String} URL encode string.
*/
exports.encodeURIComponent = function encodeURIComponent_(text) {
try {
return encodeURIComponent(text);
} catch (e) {
return text;
}
};
/**
* Safe decodeURIComponent, won't throw any error.
* If `decodeURIComponent` error happen, just return the original value.
*
* @param {String} encodeText
* @return {String} URL decode original string.
*/
exports.decodeURIComponent = function decodeURIComponent_(encodeText) {
try {
return decodeURIComponent(encodeText);
} catch (e) {
return encodeText;
}
};
../../../_mkdirp@0.5.1@mkdirp/bin/cmd.js
\ No newline at end of file
../../_copy-to@2.0.1@copy-to
\ No newline at end of file
../../_escape-html@1.0.3@escape-html
\ No newline at end of file
../../_mkdirp@0.5.1@mkdirp
\ No newline at end of file
../../_mz@2.7.0@mz
\ No newline at end of file
../../_unescape@1.0.1@unescape
\ No newline at end of file
{
"name": "utility",
"version": "1.16.2",
"description": "A collection of useful utilities.",
"main": "lib/utility.js",
"files": [
"lib",
"index.d.ts"
],
"scripts": {
"test": "npm run lint && npm run test-local",
"test-ts": "npm run test-local-ts",
"test-local": "ava test/**/*.test.js",
"test-local-ts": "ava-ts test_ts/**/*.test.ts",
"test-cov": "nyc ava test/**/*.test.js && nyc report --reporter=lcov",
"lint": "jshint .",
"ci": "npm run lint && npm run test-cov && npm run test-ts",
"autod": "autod -w --prefix '^' -e benchmark",
"test-optimized": "node --allow-natives-syntax --trace_opt --trace_deopt test/optimized.js",
"contributor": "git-contributor"
},
"dependencies": {
"copy-to": "^2.0.1",
"escape-html": "^1.0.3",
"mkdirp": "^0.5.1",
"mz": "^2.7.0",
"unescape": "^1.0.1"
},
"devDependencies": {
"@types/escape-html": "0.0.20",
"@types/node": "^10.12.12",
"autod": "*",
"ava": "^0.25.0",
"ava-ts": "^0.25.2",
"beautify-benchmark": "*",
"benchmark": "^2.1.0",
"contributors": "*",
"git-contributor": "^1.0.10",
"jshint": "*",
"moment": "^2.22.2",
"nyc": "6",
"object-assign": "^4.1.1",
"optimized": "^1.2.0",
"rimraf": "^2.6.2",
"ts-node": "^7.0.1",
"typescript": "^3.2.2"
},
"homepage": "https://github.com/node-modules/utility",
"repository": {
"type": "git",
"url": "git://github.com/node-modules/utility.git",
"web": "https://github.com/node-modules/utility"
},
"keywords": [
"utility",
"util",
"utils",
"sha256",
"sha1",
"hash",
"hex"
],
"engines": {
"node": ">= 0.12.0"
},
"author": "fengmk2 <fengmk2@gmail.com> (https://fengmk2.com)",
"license": "MIT",
"__npminstall_done": "Tue Nov 19 2019 19:23:42 GMT+0800 (CST)",
"_from": "utility@1.16.2",
"_resolved": "https://registry.npm.taobao.org/utility/download/utility-1.16.2.tgz"
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment